diff --git a/apps/server/src/orchestration/reducer.ts b/apps/server/src/orchestration/reducer.ts index 1b05441b1f..59e2812df0 100644 --- a/apps/server/src/orchestration/reducer.ts +++ b/apps/server/src/orchestration/reducer.ts @@ -214,10 +214,21 @@ export function reduceEvent( return nextBase; } - const session: OrchestrationSession = yield* decodeSession({ - ...payload.session, - threadId: payload.threadId, - }); + const session: OrchestrationSession = yield* decodeSession(payload.session); + + const turnTimingPatch: ThreadPatch = + session.status === "running" && session.activeTurnId + ? { latestTurnStartedAt: event.occurredAt, latestTurnDurationMs: null } + : session.status === "ready" && thread.latestTurnStartedAt + ? (() => { + const startMs = Date.parse(thread.latestTurnStartedAt); + const endMs = Date.parse(event.occurredAt); + if (!Number.isNaN(startMs) && !Number.isNaN(endMs) && endMs >= startMs) { + return { latestTurnDurationMs: endMs - startMs } as ThreadPatch; + } + return {}; + })() + : {}; return { ...nextBase, @@ -225,6 +236,7 @@ export function reduceEvent( session, updatedAt: event.occurredAt, error: session.lastError, + ...turnTimingPatch, }), }; }); diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index 42fb00d352..48d28ba45a 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -237,7 +237,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, @@ -311,7 +311,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/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 8a6ee0752b..f44ccc0815 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -147,6 +147,8 @@ function AutoProjectBootstrap() { const api = useNativeApi(); const { state, dispatch } = useStore(); const bootstrappedRef = useRef(false); + const threadsRef = useRef(state.threads); + threadsRef.current = state.threads; useEffect(() => { if (!api) return; @@ -173,7 +175,9 @@ function AutoProjectBootstrap() { const projects = await api.projects.list(); dispatch({ type: "SYNC_PROJECTS", projects }); - const hasThread = state.threads.some((thread) => thread.projectId === result.project.id); + const hasThread = threadsRef.current.some( + (thread) => thread.projectId === result.project.id, + ); if (hasThread) { return; }