From 0a5a92ded0c950b3e27793368660b5779c470050 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 22 Feb 2026 04:41:46 +0000 Subject: [PATCH] Fix streaming token persistence, double project deletion, session threadId overwrite, and bootstrap duplication Bug 1: Add dispatchVolatile to OrchestrationEngine that updates the in-memory read model and broadcasts to clients without persisting to the SQLite event store. Streaming text deltas now use volatile dispatch and accumulate in a buffer; only the final complete message is persisted on turn/completed. Bug 2: In Electron mode, api.projects.remove already triggers a server-side project.delete dispatch. Wrap the client-side orchestration dispatch in an else branch to avoid the duplicate event. Bug 3: The reducer's thread.session-set case was hardcoding the orchestration aggregate threadId instead of reading from sessionPayload.threadId. The server event handler was also passing thread.id instead of the provider's runtime thread ID. Both now correctly propagate the Codex runtime thread ID. Bug 4: AutoProjectBootstrap now waits for state.threadsHydrated before subscribing to onServerWelcome, ensuring the duplicate-project check runs against the server's actual state instead of the empty initial state. --- apps/server/src/orchestration/engine.ts | 37 +++++++++++++++++++----- apps/server/src/orchestration/reducer.ts | 2 +- apps/server/src/wsServer.ts | 14 ++++++--- apps/web/src/components/Sidebar.tsx | 14 ++++----- apps/web/src/routes/__root.tsx | 4 +-- 5 files changed, 50 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration/engine.ts b/apps/server/src/orchestration/engine.ts index 4069645dd9..98807205c9 100644 --- a/apps/server/src/orchestration/engine.ts +++ b/apps/server/src/orchestration/engine.ts @@ -25,6 +25,7 @@ import { UI_ENTITY_CONTRACTS } from "./uiContractInventory"; type CommandEnvelope = { command: OrchestrationCommand; result: Deferred.Deferred<{ sequence: number }, Error>; + volatile?: boolean; }; function asError(error: unknown, fallbackMessage: string): Error { @@ -225,21 +226,32 @@ export class OrchestrationEngine { private processEnvelope(envelope: CommandEnvelope): Effect.Effect { return Effect.gen(this, function* () { const eventBase = mapCommandToEvent(envelope.command); - const savedEvent = yield* this.eventStore.append(eventBase); + + let savedEvent: OrchestrationEvent; + if (envelope.volatile) { + savedEvent = { ...eventBase, sequence: this.readModel.sequence }; + } else { + savedEvent = yield* this.eventStore.append(eventBase); + } yield* Effect.sync(() => { this.readModel = reduceEvent(this.readModel, savedEvent); }); const snapshot = this.readModel; - yield* Effect.all([ - PubSub.publish(this.eventPubSub, savedEvent), - PubSub.publish(this.readModelPubSub, snapshot), - ]); + + if (!envelope.volatile) { + yield* Effect.all([ + PubSub.publish(this.eventPubSub, savedEvent), + PubSub.publish(this.readModelPubSub, snapshot), + ]); + } yield* Effect.sync(() => { - for (const listener of this.domainEventListeners) { - listener(savedEvent); + if (!envelope.volatile) { + for (const listener of this.domainEventListeners) { + listener(savedEvent); + } } for (const listener of this.readModelListeners) { listener(snapshot); @@ -332,6 +344,17 @@ export class OrchestrationEngine { }); } + async dispatchVolatile(command: OrchestrationCommand): Promise<{ sequence: number }> { + const program = Effect.gen(this, function* () { + const result = yield* Deferred.make<{ sequence: number }, Error>(); + yield* Queue.offer(this.commandQueue, { command, result, volatile: true }); + return yield* Deferred.await(result); + }); + return Runtime.runPromise(this.runtime)(program).catch((error) => { + throw asError(error, "Queue offer failed"); + }); + } + subscribeToReadModel(callback: (snapshot: OrchestrationReadModel) => void): () => void { this.readModelListeners.add(callback); return () => { diff --git a/apps/server/src/orchestration/reducer.ts b/apps/server/src/orchestration/reducer.ts index 14e2c237fb..96365c754c 100644 --- a/apps/server/src/orchestration/reducer.ts +++ b/apps/server/src/orchestration/reducer.ts @@ -181,7 +181,7 @@ export function reduceEvent( (asString(sessionPayload.status) as OrchestrationSession["status"] | null) ?? "connecting", provider: (asString(sessionPayload.provider) as OrchestrationSession["provider"] | null) ?? "codex", - threadId, + threadId: asString(sessionPayload.threadId) ?? threadId, activeTurnId: asString(sessionPayload.activeTurnId), createdAt: asString(sessionPayload.createdAt) ?? event.occurredAt, updatedAt: asString(sessionPayload.updatedAt) ?? event.occurredAt, diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index dd8f3fd6eb..db7cabc589 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -176,6 +176,8 @@ export function createServer(options: ServerOptions) { }); } + const streamingTextBuffers = new Map(); + // Forward provider events to all connected WebSocket clients providerManager.on("event", (event) => { void (async () => { @@ -197,7 +199,7 @@ export function createServer(options: ServerOptions) { sessionId: event.sessionId, provider: event.provider, status: event.method === "turn/started" ? "running" : "ready", - threadId: thread.id, + threadId: event.threadId ?? thread.session?.threadId ?? thread.id, activeTurnId: event.method === "turn/started" ? (event.turnId ?? null) : null, createdAt: thread.session?.createdAt ?? now, updatedAt: now, @@ -208,7 +210,9 @@ export function createServer(options: ServerOptions) { } if (event.textDelta && event.textDelta.length > 0) { const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`; - await orchestrationEngine.dispatch({ + const current = streamingTextBuffers.get(assistantMessageId) ?? ""; + streamingTextBuffers.set(assistantMessageId, current + event.textDelta); + await orchestrationEngine.dispatchVolatile({ type: "message.send", commandId: crypto.randomUUID(), threadId: thread.id, @@ -221,13 +225,15 @@ export function createServer(options: ServerOptions) { } if (event.method === "turn/completed") { const assistantMessageId = `assistant:${event.turnId ?? event.itemId ?? event.sessionId}`; + const accumulatedText = streamingTextBuffers.get(assistantMessageId) ?? ""; + streamingTextBuffers.delete(assistantMessageId); await orchestrationEngine.dispatch({ type: "message.send", commandId: crypto.randomUUID(), threadId: thread.id, messageId: assistantMessageId, role: "assistant", - text: "", + text: accumulatedText, streaming: false, createdAt: now, }); @@ -261,7 +267,7 @@ export function createServer(options: ServerOptions) { sessionId: event.sessionId, provider: event.provider, status: "error", - threadId: thread.id, + threadId: event.threadId ?? thread.session?.threadId ?? thread.id, activeTurnId: event.turnId ?? null, createdAt: thread.session?.createdAt ?? now, updatedAt: now, diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 0d2ad398f2..0b83b9a1e6 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -395,14 +395,14 @@ export default function Sidebar() { }); return; } + } else { + await api.orchestration.dispatchCommand({ + type: "project.delete", + commandId: crypto.randomUUID(), + projectId, + createdAt: new Date().toISOString(), + }); } - - await api.orchestration.dispatchCommand({ - type: "project.delete", - commandId: crypto.randomUUID(), - projectId, - createdAt: new Date().toISOString(), - }); }, [api, dispatch, state.projects, state.threads], ); diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 1ef0eabe4b..82241fd9ef 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -153,6 +153,7 @@ function AutoProjectBootstrap() { // Browser mode bootstraps from server welcome. // Electron bootstraps from persisted projects via DesktopProjectBootstrap. if (isElectron) return; + if (!state.threadsHydrated) return; return onServerWelcome((payload) => { if (bootstrappedRef.current) return; @@ -161,7 +162,6 @@ function AutoProjectBootstrap() { const existing = state.projects.find((project) => project.cwd === payload.cwd); if (existing) { bootstrappedRef.current = true; - dispatch({ type: "SET_THREADS_HYDRATED", hydrated: true }); return; } @@ -194,7 +194,7 @@ function AutoProjectBootstrap() { ) .catch(() => undefined); }); - }, [api, state.projects, dispatch]); + }, [api, state.projects, state.threadsHydrated, dispatch]); return null; }