Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/main/ipc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,16 +187,15 @@ export function registerIpc(
changed();
});

ipcMain.handle('analysisStart', async (event, input: AnalysisStartInput) => {
const { sender } = event;
ipcMain.handle('analysisStart', async ({ sender }, input: AnalysisStartInput, subscriptionId: string) => {
input = await analysisStartSchema.parseAsync(input);
await services.dataset.prepareOAuth(input.datasetId);
const titleUpdate = services.analysis.start(
input,
services.model.getDefaultModelConfig(),
services.settings.getPreferences(),
(chunk) => {
if (!sender.isDestroyed()) sender.send('analysis:chunk', input.message.id, chunk);
if (!sender.isDestroyed()) sender.send('analysis:chunk', subscriptionId, input.message.id, chunk);
},
);
changed();
Expand All @@ -205,6 +204,12 @@ export function registerIpc(
});
});

ipcMain.handle('analysisReconnect', ({ sender }, conversationId: string, subscriptionId: string) => {
return services.analysis.reconnect(conversationId, (messageId, chunk) => {
if (!sender.isDestroyed()) sender.send('analysis:chunk', subscriptionId, messageId, chunk);
});
});

ipcMain.handle('analysisCancel', (_event, conversationId: string) =>
services.analysis.cancel(conversationId),
);
Expand Down
46 changes: 40 additions & 6 deletions src/main/services/analysis/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { isTextUIPart } from 'ai';
import type { UIMessageChunk } from 'ai';
import { isAnalysisToolResult } from '@shared/analysis-trace';
import type { AnalysisStartInput, ChatMessage, DuckDBEngineConfig, Preferences } from '@shared/api';
import type {
AnalysisStartInput,
AnalysisStreamChunk,
ChatMessage,
DuckDBEngineConfig,
Preferences,
} from '@shared/api';
import type { AnalysisOptions } from '@shared/schema';
import { createAnalysisAgent } from '../../ai';
import type { AnalysisAgent } from '../../ai';
Expand All @@ -13,7 +19,15 @@ import type { ModelConfig } from '../model';
import type { DatasetRow } from '../../db/schema/datasets';
import { checkLocalFile, localFilePath } from '../../util/localFile';

type Emit = (chunk: UIMessageChunk | null) => void;
type Emit = (chunk: AnalysisStreamChunk) => void;

type AnalysisTask = {
datasetId: string;
controller: AbortController;
messageId: string;
chunks: UIMessageChunk[];
emit: Emit;
};

export class AnalysisService {
// Add a Map to store agents associated with conversation IDs, along with their dataset IDs and engine keys.
Expand All @@ -28,7 +42,7 @@ export class AnalysisService {
}
>();

private tasks = new Map<string, { datasetId: string; controller: AbortController }>();
private tasks = new Map<string, AnalysisTask>();

private updatingDatasets = new Set<string>();

Expand Down Expand Up @@ -116,14 +130,24 @@ export class AnalysisService {
});
const agent = this.getAgent(conversation.id, model, dataset, preferences.engine);
const controller = new AbortController();
this.tasks.set(conversation.id, { datasetId: dataset.id, controller });
const task: AnalysisTask = {
datasetId: dataset.id,
controller,
messageId: input.message.id,
chunks: [],
emit,
};
this.tasks.set(conversation.id, task);
void this.run(
conversation.id,
agent,
analysisOptions,
preferences.agent,
controller,
emit,
(chunk) => {
if (chunk) task.chunks.push(chunk);
task.emit(chunk);
},
localFilePath(dataset.sourceConfig),
);

Expand All @@ -148,6 +172,16 @@ export class AnalysisService {
this.tasks.get(conversationId)?.controller.abort();
}

reconnect(conversationId: string, emit: (messageId: string, chunk: AnalysisStreamChunk) => void) {
const task = this.tasks.get(conversationId);
if (!task) return false;
task.emit('replaced');
task.emit = (chunk) => emit(task.messageId, chunk);
// Send the replay before yielding to the producer of live chunks.
for (const chunk of task.chunks) task.emit(chunk);
return true;
}

private getAgent(
conversationId: string,
model: ModelConfig,
Expand Down Expand Up @@ -180,7 +214,7 @@ export class AnalysisService {
analysisOptions: Required<AnalysisOptions>,
agentConfig: Preferences['agent'],
controller: AbortController,
emit: Emit,
emit: (chunk: UIMessageChunk | null) => void,
file?: string,
) {
let terminal: Extract<UIMessageChunk, { type: 'error' | 'abort' }> | undefined;
Expand Down
8 changes: 4 additions & 4 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import '@sentry/electron/preload';
import { contextBridge, ipcRenderer } from 'electron';
import type { IpcRendererEvent } from 'electron';
import type { UIMessageChunk } from 'ai';
import type { ModelTestProgress, WorkbenchApi } from './api';

const api = {
Expand Down Expand Up @@ -58,12 +57,13 @@ const api = {
},
modelActivate: (id, model) => ipcRenderer.invoke('modelActivate', id, model),
modelDelete: (id) => ipcRenderer.invoke('modelDelete', id),
analysisStart: (input) => ipcRenderer.invoke('analysisStart', input),
analysisStart: (input, subscriptionId) => ipcRenderer.invoke('analysisStart', input, subscriptionId),
analysisReconnect: (conversationId, subscriptionId) =>
ipcRenderer.invoke('analysisReconnect', conversationId, subscriptionId),
analysisCancel: (conversationId) => ipcRenderer.invoke('analysisCancel', conversationId),
analysisGetMessages: (conversationId) => ipcRenderer.invoke('analysisGetMessages', conversationId),
analysisOnChunk: (callback) => {
const listener = (_event: IpcRendererEvent, messageId: string, chunk: UIMessageChunk | null) =>
callback(messageId, chunk);
const listener = (_event: IpcRendererEvent, ...args: Parameters<typeof callback>) => callback(...args);
ipcRenderer.on('analysis:chunk', listener);
return () => ipcRenderer.removeListener('analysis:chunk', listener);
},
Expand Down
31 changes: 21 additions & 10 deletions src/renderer/components/chat/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,12 @@ export function Chat({
messages,
setMessages,
sendMessage,
resumeStream,
status,
error: chatError,
} = useChat<ChatMessage>({ id: chatId, transport });
const [historyLoading, setHistoryLoading] = useState(Boolean(conversationId));
const reconnectAttempted = useRef(false);
const [loadedChatId, setLoadedChatId] = useState<string | null>(null);
const [suggestions, setSuggestions] = useState<SuggestResult[]>([]);
const [suggestionsLoading, setSuggestionsLoading] = useState(true);
Expand All @@ -84,29 +86,38 @@ export function Chat({
useEffect(() => {
let live = true;
if (!conversationId) {
reconnectAttempted.current = true;
setLoadedChatId(chatId);
setHistoryLoading(false);
} else if (!busy) {
setLoadedChatId(null);
window.workbench
.analysisGetMessages(conversationId)
.then((history) => {
const shouldReconnect = !reconnectAttempted.current;
reconnectAttempted.current = true;

const restore = async () => {
try {
const history = await window.workbench.analysisGetMessages(conversationId);
if (live) {
setMessages(history);
setLoadedChatId(chatId);
}
})
.catch((cause) => {
if (live) setError(errorMessage(cause));
})
.finally(() => {
} finally {
if (live) setHistoryLoading(false);
});
}
if (!live || !shouldReconnect) return;
await resumeStream();
if (!live) return;
const history = await window.workbench.analysisGetMessages(conversationId);
if (live) setMessages(history);
};
restore().catch((cause) => {
if (live) setError(errorMessage(cause));
});
}
return () => {
live = false;
};
}, [chatId, conversationId, busy, setMessages]);
}, [chatId, conversationId, busy, setMessages, resumeStream]);

useEffect(() => {
let live = true;
Expand Down
Loading
Loading