Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork): isolate concurrent session runs
thinhlpg045da55ba06b
diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.test.tsindex c1888c07f..f1ff02863 100644--- a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts+++ b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts@@ -46,6 +46,17 @@ describe('startNewSession', () => {expect(useCoworkSessions.getState().sessions).toHaveLength(1)})+ it('opens a different session while the current first response is still streaming', () => {+ const running = useCoworkSessions.getState().createSession()+ const fresh = startNewSession([running])+ expect(fresh).not.toBe(running)+ expect(useCoworkSessions.getState().currentId).toBe(fresh)+ expect(useCoworkSessions.getState().sessions.map((s) => s.id)).toEqual([+ fresh,+ running,+ ])+ })+it('sweeps abandoned empties but keeps one whose first run is streaming', () => {const store = useCoworkSessions.getState()const used = store.createSession()diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.tsindex 7be2d1641..bb0207dc3 100644--- a/web-app/src/hooks/useCoworkRun.ts+++ b/web-app/src/hooks/useCoworkRun.ts@@ -11,6 +11,7 @@ import type {import type { MonitorUpdate } from '@/lib/agentTools'import { userTurn } from '@/lib/coworkTurns'import type { ModelLoadProgress } from '@/hooks/useAppState'+import type { RunOutcome } from '@/lib/coworkRunner'// The ask shapes live in the store-free types module; re-exported here because// this store is where the pending-ask queue lives.@@ -30,7 +31,13 @@ export type StreamEvent =| { type: 'tool_call_started'; id: string; name: string }| { type: 'tool_call_args_delta'; id: string; delta: string }| { type: 'tool_call'; id: string; name: string; args: unknown }- | { type: 'tool_result'; id: string; content: string; is_error: boolean; diff?: string }+ | {+ type: 'tool_result'+ id: string+ content: string+ is_error: boolean+ diff?: string+ }| { type: 'done'; stop_reason: string; usage: Usage | null }| { type: 'error'; code: string; message: string }| { type: 'todo_update'; list: TodoList }@@ -76,14 +83,23 @@ function mergeToolResult(callId: string,patch: Partial<CoworkTurn>): CoworkTurn[] {- const idx = turns.findIndex((tn) => tn.role === 'tool' && tn.callId === callId)+ const idx = turns.findIndex(+ (tn) => tn.role === 'tool' && tn.callId === callId+ )if (idx === -1) return turns- return [...turns.slice(0, idx), { ...turns[idx], ...patch }, ...turns.slice(idx + 1)]+ return [+ ...turns.slice(0, idx),+ { ...turns[idx], ...patch },+ ...turns.slice(idx + 1),+ ]}// Apply one wrapped inner subagent event to that subagent's own turn lane// (token append / tool_call push / tool_result merge). Pure.-function applyInnerToTurns(turns: CoworkTurn[], inner: StreamEvent): CoworkTurn[] {+function applyInnerToTurns(+ turns: CoworkTurn[],+ inner: StreamEvent+): CoworkTurn[] {switch (inner.type) {case 'token':return appendAssistantToken(turns, inner.text)@@ -97,20 +113,38 @@ function applyInnerToTurns(turns: CoworkTurn[], inner: StreamEvent): CoworkTurn[...turns.slice(0, -1),{ ...last, reasoning: (last.reasoning ?? '') + inner.text },]- return [...turns, { role: 'assistant', content: '', reasoning: inner.text }]+ return [+ ...turns,+ { role: 'assistant', content: '', reasoning: inner.text },+ ]}case 'tool_call_started': {- if (turns.some((tn) => tn.role === 'tool' && tn.callId === inner.id)) return turns+ if (turns.some((tn) => tn.role === 'tool' && tn.callId === inner.id))+ return turnsreturn [...turns,- { role: 'tool', content: '', callId: inner.id, name: inner.name, args: null, argsLive: '', status: 'running' },+ {+ role: 'tool',+ content: '',+ callId: inner.id,+ name: inner.name,+ args: null,+ argsLive: '',+ status: 'running',+ },]}case 'tool_call_args_delta': {- const idx = turns.findIndex((tn) => tn.role === 'tool' && tn.callId === inner.id)+ const idx = turns.findIndex(+ (tn) => tn.role === 'tool' && tn.callId === inner.id+ )if (idx === -1) return turnsconst prev = turns[idx].argsLive ?? ''- return [...turns.slice(0, idx), { ...turns[idx], argsLive: prev + inner.delta }, ...turns.slice(idx + 1)]+ return [+ ...turns.slice(0, idx),+ { ...turns[idx], argsLive: prev + inner.delta },+ ...turns.slice(idx + 1),+ ]}case 'tool_call':return [...turns, makeToolCallTurn(inner)]@@ -143,6 +177,12 @@ function omitKey<T>(map: Record<string, T>, key: string): Record<string, T> {// would need to be kept in sync with it.type CoworkRunState = {liveTurns: Record<string, CoworkTurn[]>+ outcomes: Record<string, Pick<RunOutcome, 'stoppedBy' | 'errorText'>>+ setOutcome: (+ sid: string,+ outcome: Pick<RunOutcome, 'stoppedBy' | 'errorText'>+ ) => void+ setLiveTurns: (sid: string, turns: CoworkTurn[]) => voidsubagents: Record<string, SubagentRun[]>// The session's file monitors. Unlike the subagent lanes they survive the// run: a watcher keeps going after the model has answered, and a later@@ -154,7 +194,10 @@ type CoworkRunState = {runId: Record<string, string>// In-flight `ask` tool questions per session. A subagent's wrapped ask is// attributed to the parent session the same way.- pendingAsks: Record<string, { requestId: string; request: AskRequestPayload }[]>+ pendingAsks: Record<+ string,+ { requestId: string; request: AskRequestPayload }[]+ >// Usage from the latest `done` event, per session. Set once per run (the// terminal event); untouched by a `null` usage so a provider that doesn't// report it on a given turn doesn't blank out the last known value.@@ -184,16 +227,30 @@ type CoworkRunState = {loadingModels: Record<string, boolean>modelLoadProgress: Record<string, ModelLoadProgress>- beginRun: (sid: string, runId: string, userText: string, media?: CoworkMediaPart[]) => void+ beginRun: (+ sid: string,+ runId: string,+ userText: string,+ media?: CoworkMediaPart[]+ ) => voidappendToken: (sid: string, text: string) => voidpushToolTurn: (sid: string, turn: CoworkTurn) => void- updateToolTurn: (sid: string, callId: string, patch: Partial<CoworkTurn>) => void+ updateToolTurn: (+ sid: string,+ callId: string,+ patch: Partial<CoworkTurn>+ ) => void/** Empty a session's subagent lanes at the start of a run, so the panel shows* this run's children rather than every child the session ever had. */resetSubagents: (sid: string) => voidstartSubagent: (sid: string, runId: string, name: string) => void// `subagent_queued`: mark a child as waiting for a concurrency slot.- queueSubagent: (sid: string, runId: string, name: string, waiting: number) => void+ queueSubagent: (+ sid: string,+ runId: string,+ name: string,+ waiting: number+ ) => voidendSubagent: (sid: string, runId: string, usage?: Usage | null) => voidrouteIntoSubagent: (sid: string, runId: string, inner: StreamEvent) => voidattachSubagentOutput: (sid: string, runId: string, content: string) => void@@ -222,19 +279,31 @@ type CoworkRunState = {sid: string,progress: ModelLoadProgress | undefined) => void- addPendingAsk: (sid: string, requestId: string, request: AskRequestPayload) => void+ addPendingAsk: (+ sid: string,+ requestId: string,+ request: AskRequestPayload+ ) => voidremovePendingAsk: (sid: string, requestId: string) => void// Mark running tool turns + subagents done (interrupted). Leaves// liveTurns/subagents in place and returns the final values so the caller// can commit them before clearCodeRun without a second round of store// reads. Run-level failure is surfaced separately via `useMessageErrors`,// not through this function.- finalizeRun: (sid: string) => { turns: CoworkTurn[]; subagents: SubagentRun[] }+ finalizeRun: (sid: string) => {+ turns: CoworkTurn[]+ subagents: SubagentRun[]+ }clearCodeRun: (sid: string) => void}export const useCoworkRun = create<CoworkRunState>()((set, get) => ({liveTurns: {},+ outcomes: {},+ setOutcome: (sid, outcome) =>+ set((s) => ({ outcomes: { ...s.outcomes, [sid]: outcome } })),+ setLiveTurns: (sid, turns) =>+ set((s) => ({ liveTurns: { ...s.liveTurns, [sid]: turns } })),subagents: {},monitors: {},parked: {},@@ -250,6 +319,8 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({beginRun: (sid, runId, userText, media) =>set((s) => ({runId: { ...s.runId, [sid]: runId },+ outcomes: omitKey(s.outcomes, sid),+ usage: omitKey(s.usage, sid),liveTurns: {...s.liveTurns,[sid]: [userTurn(userText, media)],@@ -276,7 +347,9 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({set((s) => {const turns = s.liveTurns[sid] ?? []const next = mergeToolResult(turns, callId, patch)- return next === turns ? {} : { liveTurns: { ...s.liveTurns, [sid]: next } }+ return next === turns+ ? {}+ : { liveTurns: { ...s.liveTurns, [sid]: next } }}),resetSubagents: (sid) =>@@ -295,7 +368,12 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({...s.subagents,[sid]: [...runs.slice(0, idx),- { ...existing, status: 'running' as const, waiting: undefined, startedAt: Date.now() },+ {+ ...existing,+ status: 'running' as const,+ waiting: undefined,+ startedAt: Date.now(),+ },...runs.slice(idx + 1),],},@@ -308,7 +386,13 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({...s.subagents,[sid]: [...runs,- { runId, name, status: 'running', startedAt: Date.now(), turns: [] },+ {+ runId,+ name,+ status: 'running',+ startedAt: Date.now(),+ turns: [],+ },],},}@@ -323,13 +407,19 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({...s.subagents,[sid]: [...runs,- { runId, name, status: 'queued', waiting, startedAt: Date.now(), turns: [] },+ {+ runId,+ name,+ status: 'queued',+ waiting,+ startedAt: Date.now(),+ turns: [],+ },],},}}),-endSubagent: (sid, runId, usage) =>set((s) => ({subagents: {@@ -352,7 +442,9 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({subagents: {...s.subagents,[sid]: (s.subagents[sid] ?? []).map((r) =>- r.runId === runId ? { ...r, turns: applyInnerToTurns(r.turns, inner) } : r+ r.runId === runId+ ? { ...r, turns: applyInnerToTurns(r.turns, inner) }+ : r),},})),@@ -362,7 +454,9 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({subagents: {...s.subagents,[sid]: (s.subagents[sid] ?? []).map((r) =>- r.runId === runId && r.finalOutput == null ? { ...r, finalOutput: content } : r+ r.runId === runId && r.finalOutput == null+ ? { ...r, finalOutput: content }+ : r),},})),@@ -381,7 +475,9 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({? {...m,status: 'done' as const,- outcome: update.matched ? ('matched' as const) : ('timeout' as const),+ outcome: update.matched+ ? ('matched' as const)+ : ('timeout' as const),endedAt: Date.now(),}: m@@ -435,7 +531,8 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({setUsage: (sid, usage) =>set((s) => (usage ? { usage: { ...s.usage, [sid]: usage } } : {})),- requestPreview: (sessionId, path) => set({ pendingPreview: { sessionId, path } }),+ requestPreview: (sessionId, path) =>+ set({ pendingPreview: { sessionId, path } }),clearPendingPreview: () => set({ pendingPreview: null }),setLlamacppRun: (sid, modelId) =>@@ -449,7 +546,9 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({takePendingLlamacppError: (sid) => {const message = get().pendingLlamacppError[sid]if (message !== undefined) {- set((s) => ({ pendingLlamacppError: omitKey(s.pendingLlamacppError, sid) }))+ set((s) => ({+ pendingLlamacppError: omitKey(s.pendingLlamacppError, sid),+ }))}return message},@@ -480,7 +579,9 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({set((s) => ({pendingAsks: {...s.pendingAsks,- [sid]: (s.pendingAsks[sid] ?? []).filter((a) => a.requestId !== requestId),+ [sid]: (s.pendingAsks[sid] ?? []).filter(+ (a) => a.requestId !== requestId+ ),},})),@@ -490,11 +591,18 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({// misleading error-styled tool card even though no tool call failed.const turns: CoworkTurn[] = (get().liveTurns[sid] ?? []).map((tn) =>tn.role === 'tool' && tn.status === 'running'- ? { ...tn, status: 'done' as const, isError: true, result: tn.result || '(interrupted)' }+ ? {+ ...tn,+ status: 'done' as const,+ isError: true,+ result: tn.result || '(interrupted)',+ }: tn)const subs = (get().subagents[sid] ?? []).map((r) =>- r.status !== 'done' ? { ...r, status: 'done' as const, endedAt: Date.now() } : r+ r.status !== 'done'+ ? { ...r, status: 'done' as const, endedAt: Date.now() }+ : r)set((s) => ({liveTurns: { ...s.liveTurns, [sid]: turns },@@ -507,6 +615,7 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({clearCodeRun: (sid) =>set((s) => ({liveTurns: omitKey(s.liveTurns, sid),+ outcomes: omitKey(s.outcomes, sid),subagents: omitKey(s.subagents, sid),parked: omitKey(s.parked, sid),runId: omitKey(s.runId, sid),@@ -524,4 +633,3 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({// changes, not on every other session's.export const useIsSessionActive = (sid: string | undefined) =>useCoworkRun((s) => (sid ? s.runId[sid] != null : false))-diff --git a/web-app/src/hooks/useCoworkSessions.ts b/web-app/src/hooks/useCoworkSessions.tsindex cb31bad0d..5b161702c 100644--- a/web-app/src/hooks/useCoworkSessions.ts+++ b/web-app/src/hooks/useCoworkSessions.ts@@ -351,6 +351,11 @@ export const useCoworkSessions = create<CoworkSessionsState>()(*/export function startNewSession(runningIds: string[]): string {const store = useCoworkSessions.getState()+ // A first response has no committed turns yet, but its session is not+ // untouched. Do not let createSession reuse the in-flight conversation.+ if (store.currentId && runningIds.includes(store.currentId)) {+ useCoworkSessions.setState({ currentId: null })+ }const id = store.createSession()store.pruneEmptySessions(runningIds)return iddiff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.tsindex 418ec52db..88276a487 100644--- a/web-app/src/lib/coworkRunner.ts+++ b/web-app/src/lib/coworkRunner.ts@@ -77,7 +77,7 @@ export function isRunning(sid: string): boolean {return handles.has(sid)}-function createHandle(sid: string, runId: string): RunHandle {+export function createHandle(sid: string, runId: string): RunHandle {const handle: RunHandle = {runId,outer: new AbortController(),@@ -89,6 +89,10 @@ function createHandle(sid: string, runId: string): RunHandle {return handle}+export function releaseHandle(sid: string, handle: RunHandle): void {+ if (handles.get(sid) === handle) handles.delete(sid)+}+/*** Stop a session's run: the model stream, the tool dispatch loop, every nested* subagent, and any question the user was being asked.diff --git a/web-app/src/routes/__tests__/coworkSkills.test.tsx b/web-app/src/routes/__tests__/coworkSkills.test.tsxindex c70221fb9..c71677cbe 100644--- a/web-app/src/routes/__tests__/coworkSkills.test.tsx+++ b/web-app/src/routes/__tests__/coworkSkills.test.tsx@@ -9,6 +9,13 @@ const backend = vi.hoisted(() => ({skills: new Map<string, string>(),projectSkills: new Map<string, string>(),received: [] as UIMessage[][],+ hold: false,+ preparationError: false,+ runs: [] as {+ signal: AbortSignal+ sink: CoworkRunner.StreamSink+ finish: () => void+ }[],}))vi.mock('@tanstack/react-router', () => ({createFileRoute: () => (options: unknown) => options,@@ -55,15 +62,27 @@ vi.mock('@/hooks/useModelProvider', () => ({}))vi.mock('@/lib/coworkTransport', () => ({CoworkChatTransport: class {- async refreshTools() {}+ async refreshTools() {+ if (backend.preparationError) throw new Error('Tool preparation failed')+ }},}))vi.mock('@/lib/coworkEnv', () => ({ getCoworkEnvironment: async () => ({}) }))vi.mock('@/lib/coworkRunner', async (original) => ({...(await original<typeof CoworkRunner>()),- runTurn: async ({ messages }: { messages: UIMessage[] }) => {+ runTurn: async ({+ messages,+ signal,+ deps,+ }: Parameters<typeof CoworkRunner.runTurn>[0]) => {backend.received.push(messages)- return { messages, stoppedBy: 'done' }+ if (backend.hold) {+ await new Promise<void>((resolve) => {+ backend.runs.push({ signal, sink: deps.sink, finish: resolve })+ signal.addEventListener('abort', () => resolve(), { once: true })+ })+ }+ return { messages, stoppedBy: signal.aborted ? 'aborted' : 'done' }},}))vi.mock('@/lib/agentTools', () => ({@@ -81,8 +100,37 @@ vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({sessionWorkspacePath: async () => '/sandbox',}))vi.mock('@/containers/ChatInput', () => ({- default: ({ onSubmit }: { onSubmit: (text: string) => void }) => (- <button onClick={() => onSubmit(usePrompt.getState().prompt)}>Send</button>+ default: ({+ onSubmit,+ onStop,+ chatStatus,+ scopeKey,+ }: {+ onSubmit: (text: string) => void+ onStop: () => void+ chatStatus: string+ scopeKey: string+ }) => (+ <>+ <output aria-label="Composer status">{chatStatus}</output>+ <button+ onClick={() => {+ const text = usePrompt.getState().prompt+ if (chatStatus === 'streaming')+ useMessageQueue+ .getState()+ .enqueue(scopeKey, {+ id: crypto.randomUUID(),+ text,+ createdAt: Date.now(),+ })+ else onSubmit(text)+ }}+ >+ Send+ </button>+ <button onClick={onStop}>Stop</button>+ </>),}))vi.mock('@/containers/MessageItem', () => ({@@ -161,7 +209,10 @@ vi.mock('@/containers/CoworkSandboxChip', () => ({vi.mock('@/containers/CoworkBudgetNotice', () => ({CoworkBudgetNotice: () => null,}))-vi.mock('@/containers/CoworkRunNotice', () => ({ CoworkRunNotice: () => null }))+vi.mock('@/containers/CoworkRunNotice', () => ({+ CoworkRunNotice: ({ onRetry }: { onRetry?: () => void }) =>+ onRetry ? <button onClick={onRetry}>Retry failed run</button> : null,+}))vi.mock('@/containers/CoworkAskCard', () => ({ CoworkAskCard: () => null }))vi.mock('@/containers/CoworkParkedNotice', () => ({CoworkParkedNotice: () => null,@@ -170,7 +221,9 @@ vi.mock('@/containers/CoworkParkedNotice', () => ({import { Route } from '../cowork'import { useSkills } from '@/hooks/useSkills'import { usePrompt } from '@/hooks/usePrompt'-import { useCoworkSessions } from '@/hooks/useCoworkSessions'+import { startNewSession, useCoworkSessions } from '@/hooks/useCoworkSessions'+import { useCoworkRun } from '@/hooks/useCoworkRun'+import { useMessageQueue } from '@/stores/message-queue-store'// The router mock returns the supplied component options directly.const routeOptions = Route as unknown as { component: () => ReactNode }const CoworkPage = routeOptions.component@@ -189,6 +242,11 @@ beforeEach(() => {backend.skills.clear()backend.projectSkills.clear()backend.received = []+ backend.hold = false+ backend.preparationError = false+ backend.runs = []+ useCoworkRun.setState(useCoworkRun.getInitialState())+ useMessageQueue.setState(useMessageQueue.getInitialState())useCoworkSessions.setState({ sessions: [], currentId: null })usePrompt.setState({ prompt: '' })Element.prototype.scrollIntoView = vi.fn()@@ -265,3 +323,100 @@ it('invokes the project skill when it shadows a global skill', async () => {'Project instructions')})++it('isolates concurrent session streams and stops only the viewed session', async () => {+ backend.hold = true+ const a = useCoworkSessions.getState().createSession()+ const view = render(<CoworkPage />)+ act(() => usePrompt.getState().setPrompt('Question A'))+ fireEvent.click(screen.getByText('Send'))+ await waitFor(() => expect(backend.runs).toHaveLength(1))+ let b = ''+ act(() => {+ b = startNewSession(Object.keys(useCoworkRun.getState().runId))+ })+ expect(screen.getByLabelText('Composer status')).toHaveTextContent('ready')+ act(() => usePrompt.getState().setPrompt('Question B'))+ fireEvent.click(screen.getByText('Send'))+ await waitFor(() => expect(backend.runs).toHaveLength(2))+ act(() => {+ backend.runs[0].sink.onText('Answer A')+ backend.runs[1].sink.onText('Answer B')+ })+ expect(screen.getByText('Answer B')).toBeInTheDocument()+ expect(screen.queryByText('Answer A')).not.toBeInTheDocument()+ view.unmount()+ render(<CoworkPage />)+ expect(screen.getByText('Answer B')).toBeInTheDocument()+ fireEvent.click(screen.getByText('Stop'))+ await waitFor(() =>+ expect(screen.getByLabelText('Composer status')).toHaveTextContent('ready')+ )+ expect(backend.runs[0].signal.aborted).toBe(false)+ expect(backend.runs[1].signal.aborted).toBe(true)+ act(() => useCoworkSessions.getState().selectSession(a))+ expect(screen.getByLabelText('Composer status')).toHaveTextContent(+ 'streaming'+ )+ expect(screen.getByText('Answer A')).toBeInTheDocument()+ await act(async () => backend.runs[0].finish())+ const sessions = useCoworkSessions.getState().sessions+ expect(sessions.find((s) => s.id === a)?.turns.map((t) => t.content)).toEqual(+ ['Question A', 'Answer A']+ )+ expect(sessions.find((s) => s.id === b)?.turns.map((t) => t.content)).toEqual(+ ['Question B', 'Answer B']+ )+})++it('continues a background session queue without redirecting it into the viewed run', async () => {+ backend.hold = true+ const b = useCoworkSessions.getState().createSession()+ useCoworkSessions.setState({ currentId: null })+ const a = useCoworkSessions.getState().createSession()+ render(<CoworkPage />)+ act(() => usePrompt.getState().setPrompt('First A'))+ fireEvent.click(screen.getByText('Send'))+ await waitFor(() => expect(backend.runs).toHaveLength(1))+ act(() => usePrompt.getState().setPrompt('Follow-up A'))+ fireEvent.click(screen.getByText('Send'))+ act(() => useCoworkSessions.getState().selectSession(b))+ act(() => usePrompt.getState().setPrompt('First B'))+ fireEvent.click(screen.getByText('Send'))+ await waitFor(() => expect(backend.runs).toHaveLength(2))+ await act(async () => backend.runs[0].finish())+ await waitFor(() => expect(backend.runs).toHaveLength(3))+ expect(backend.received[2].map((m) => m.parts)).toEqual([+ [{ type: 'text', text: 'First A' }],+ [{ type: 'text', text: 'Follow-up A' }],+ ])+ expect(useMessageQueue.getState().getQueue(a)).toEqual([])+ expect(screen.getByLabelText('Composer status')).toHaveTextContent(+ 'streaming'+ )+ expect(screen.queryByText('Follow-up A')).not.toBeInTheDocument()+ await act(async () => {+ backend.runs[1].finish()+ backend.runs[2].finish()+ })+ expect(+ useCoworkSessions+ .getState()+ .sessions.find((s) => s.id === b)+ ?.turns.map((t) => t.content)+ ).toEqual(['First B'])+})++it('retries the original question after request preparation fails', async () => {+ backend.preparationError = true+ render(<CoworkPage />)+ act(() => usePrompt.getState().setPrompt('Keep this question'))+ fireEvent.click(screen.getByText('Send'))+ const retry = await screen.findByText('Retry failed run')+ backend.preparationError = false+ fireEvent.click(retry)+ await waitFor(() => expect(backend.received).toHaveLength(1))+ expect(backend.received[0].at(-1)?.parts).toEqual([+ { type: 'text', text: 'Keep this question' },+ ])+})diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 4a3c580c2..4d8f81eca 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -38,7 +38,6 @@ import type {CoworkAttachedFile,CoworkMediaPart,CoworkTurn,- Usage,} from '@/types/coworkSession'import type { Attachment } from '@/types/attachment'import DropdownModelProvider from '@/containers/DropdownModelProvider'@@ -108,6 +107,8 @@ import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { MAX_AGENT_STEPS } from '@/lib/coworkBudget'import {abortRun,+ createHandle,+ releaseHandle,isAbortLike,answerAsk,runTurn,@@ -167,6 +168,7 @@ const MANUAL_COMPACT_CONFIG: ContextManagerConfig = {// Stable empty set, so a session with no monitors does not re-render on every// store write the way a fresh `[]` from the selector would.const NO_MONITORS: MonitorView[] = []+const NO_TURNS: CoworkTurn[] = []/** The session's monitor lane, mirrored into the run store for the rail. */function sessionMonitorLane(sid: string): MonitorLane {@@ -194,49 +196,21 @@ function CoworkPage() {const { skills: skillCommands, invoke: invokeSkillCommand } = useSkills(folder)const planMode = session?.planMode ?? false- const [running, setRunning] = useState(false)+ const running = useCoworkRun((s) => !!(currentId && s.runId[currentId]))const contextRecovery = useRef({ mounted: true, pending: false })useEffect(() => {const recovery = contextRecovery.currentrecovery.mounted = truereturn () => { recovery.mounted = false }}, [])- // The session the in-flight run belongs to. The live rows are appended to- // that session's transcript only — without this, switching sessions mid-run- // rendered the running session's live turns under the viewed one.- const [runSid, setRunSid] = useState<string | null>(null)- const [liveTurns, setLiveTurns] = useState<CoworkTurn[]>([])- const liveTurnsRef = useRef<CoworkTurn[]>([])- const liveFrameRef = useRef<number | null>(null)- // Every stream delta mutates `liveTurnsRef` in place; the state behind the- // transcript is refreshed from it at most once per frame. A large `write`- // arrives as thousands of deltas, and re-rendering the transcript for each- // one is what made the card lag behind the model.- const syncLive = useCallback(() => {- if (liveFrameRef.current != null) {- cancelAnimationFrame(liveFrameRef.current)- liveFrameRef.current = null- }- setLiveTurns([...liveTurnsRef.current])- }, [])- const scheduleLiveSync = useCallback(() => {- if (liveFrameRef.current != null) return- liveFrameRef.current = requestAnimationFrame(() => {- liveFrameRef.current = null- setLiveTurns([...liveTurnsRef.current])- })- }, [])- useEffect(- () => () => {- if (liveFrameRef.current != null)- cancelAnimationFrame(liveFrameRef.current)- },- []+ const liveTurns = useCoworkRun(+ (s) => (currentId ? s.liveTurns[currentId] : undefined) ?? NO_TURNS)- const [stoppedBy, setStoppedBy] = useState<RunOutcome['stoppedBy'] | null>(- null+ const runOutcome = useCoworkRun((s) =>+ currentId ? s.outcomes[currentId] : undefined)- const [runError, setRunError] = useState<string | undefined>(undefined)+ const stoppedBy = runOutcome?.stoppedBy ?? null+ const runError = runOutcome?.errorTextconst overflowProvider =stoppedBy === 'error' && runError && isContextOverflowMessage(runError)? providers.find((provider) => provider.provider === selectedProvider)@@ -254,7 +228,9 @@ function CoworkPage() {const [workspacePath, setWorkspacePath] = useState<string | null>(null)// The step just finished, so the counter tracks a run instead of jumping once// at the end. Falls back to the committed usage between runs.- const [liveUsage, setLiveUsage] = useState<Usage | null>(null)+ const liveUsage = useCoworkRun((s) =>+ currentId ? s.usage[currentId] : undefined+ )// The rail holds one panel at a time: they all want the width, so showing// two together starves the transcript (C7).const [rail, setRail] = useState<@@ -270,10 +246,9 @@ function CoworkPage() {(path: string) => setRail({ kind: 'preview', path }),[])- const [ask, setAsk] = useState<{- requestId: string- request: ReturnType<typeof parseAskRequest>- } | null>(null)+ const ask = useCoworkRun((s) =>+ currentId ? s.pendingAsks[currentId]?.[0] : undefined+ )const {containerRef: reasoningContainerRef,@@ -338,7 +313,7 @@ function CoworkPage() {// `liveTurns` holds only the rows this run has produced — `commitTurns`// appends them — so the committed transcript has to be shown alongside it or// the conversation disappears the moment a follow-up run starts.- const viewingRun = running && runSid === session?.id+ const viewingRun = runningconst displayedTurns = useMemo(() =>viewingRun@@ -439,13 +414,6 @@ function CoworkPage() {[running, displayedTurns])- const pushLive = useCallback(- (turns: CoworkTurn[]) => {- liveTurnsRef.current = [...liveTurnsRef.current, ...turns]- syncLive()- },- [syncLive]- )/*** Drive one request. `text` is null for a resume — a retry after a failure@@ -459,12 +427,12 @@ function CoworkPage() {const runRequest = async (text: string | null,- attachments?: CoworkAttachments+ attachments?: CoworkAttachments,+ sid = ensureCurrentSession()) => {- if (running) return- const sid = ensureCurrentSession()const store = useCoworkSessions.getState()const current = store.sessions.find((s) => s.id === sid)+ if (!current || useCoworkRun.getState().runId[sid]) returnif (!text && !(current?.messages?.length ?? 0)) returnif (!selectedModel?.id) {toast.error(t('common:selectModel'))@@ -477,179 +445,203 @@ function CoworkPage() {toast.error(t('common:modelNoTools', { model: selectedModel.id }))return}- // Display the invocation, but expand it only in the model's history. Keep- // this in the shared request path so edits, retries and queued turns also- // invoke skills instead of sending the slash text as an ordinary prompt.- let modelText = text- const parsedSkill = text ? parseSkillCommand(text) : null- const builtIn = parsedSkill- ? SLASH_COMMANDS.some((command) => command.name === `/${parsedSkill.name}`)- : false- const skill =- parsedSkill && (parsedSkill.explicit || !builtIn)- ? resolveSkillCommand(skillCommands, parsedSkill)- : null- if (parsedSkill?.explicit && !skill) {- toast.error(t('common:coworkSlash.skillUnavailable', { name: parsedSkill.name }))- return- }- if (skill && parsedSkill) {- try {- modelText = await invokeSkillCommand(skill.name, parsedSkill.args)- } catch (error) {- toast.error(String(error))- return- }- }- if (text && current?.title === 'New session')- // Collapse newlines/runs of whitespace so a pasted multi-line prompt- // doesn't become an unreadable sidebar title.- store.setTitle(sid, text.trim().replace(/\s+/g, ' ').slice(0, 40))-- setStoppedBy(null)- setRunError(undefined)- setLiveUsage(null)- liveTurnsRef.current = text- ? [userTurn(text, attachments?.media, attachments?.files)]- : []- syncLive()- // Marks the session running in the store (and resets its subagent lanes),- // so surfaces outside this component — the sidebar's per-session spinner- // and its empty-session filter — can see a run this component owns.+ // Claim this session before asynchronous preparation. Another session may+ // submit immediately, but a second request in this one must wait.+ const handle = createHandle(sid, crypto.randomUUID())+ const controller = handle.outeruseCoworkRun.getState()- .beginRun(sid, crypto.randomUUID(), text ?? '', attachments?.media)- setRunSid(sid)- setRunning(true)-- // Local models load before the first token, but only on a cold start. Probe- // the engine so the load card shows on a real load, not on every warm run.- if (selectedProvider === 'llamacpp') {- try {- const loaded = await getLoadedModels()- if (!loaded.includes(selectedModel.id)) {- useCoworkRun.getState().setSessionModelLoadProgress(sid, undefined)- useCoworkRun.getState().setSessionLoadingModel(sid, true)- }- } catch {- // Probe failed; skip the card rather than flash it every run.+ .beginRun(sid, handle.runId, text ?? '', attachments?.media)+ let runTurns: CoworkTurn[] = []+ let liveFrame: number | null = null+ const syncLive = () => {+ if (liveFrame != null) {+ cancelAnimationFrame(liveFrame)+ liveFrame = null}+ useCoworkRun.getState().setLiveTurns(sid, [...runTurns])}-- // Documents go into the workspace before the question is sent, so the- // paths the question names exist by the time the agent reads them. The- // row was shown first: parsing a large PDF takes a moment.- let files = attachments?.files- if (text && files?.length) {- files = await importAttachedFiles(files, {- parse: async (path, fileType) =>- (await serviceHub.rag().parseDocument?.(path, fileType)) ?? '',- importFile: (path, parsed) => importAttachment(sid, path, parsed),+ const scheduleLiveSync = () => {+ if (liveFrame != null) return+ liveFrame = requestAnimationFrame(() => {+ liveFrame = null+ useCoworkRun.getState().setLiveTurns(sid, [...runTurns])})- liveTurnsRef.current = [userTurn(text, attachments?.media, files)]+ }+ const pushLive = (turns: CoworkTurn[]) => {+ runTurns.push(...turns)syncLive()}+ let messages = current.messages ?? []+ let outcome: RunOutcome | null = null+ let thrown: Pick<RunOutcome, 'stoppedBy' | 'errorText'> | null = null+ try {+ // Display the invocation, but expand it only in the model's history. Keep+ // this in the shared request path so edits, retries and queued turns also+ // invoke skills instead of sending the slash text as an ordinary prompt.+ let modelText = text+ const parsedSkill = text ? parseSkillCommand(text) : null+ const builtIn = parsedSkill+ ? SLASH_COMMANDS.some(+ (command) => command.name === `/${parsedSkill.name}`+ )+ : false+ const skill =+ parsedSkill && (parsedSkill.explicit || !builtIn)+ ? resolveSkillCommand(skillCommands, parsedSkill)+ : null+ if (parsedSkill?.explicit && !skill) {+ toast.error(+ t('common:coworkSlash.skillUnavailable', { name: parsedSkill.name })+ )+ return+ }+ if (skill && parsedSkill) {+ try {+ modelText = await invokeSkillCommand(skill.name, parsedSkill.args)+ } catch (error) {+ toast.error(String(error))+ return+ }+ }+ if (text && current?.title === 'New session')+ // Collapse newlines/runs of whitespace so a pasted multi-line prompt+ // doesn't become an unreadable sidebar title.+ store.setTitle(sid, text.trim().replace(/\s+/g, ' ').slice(0, 40))- // Warm the sandbox probe: the transport's prompt and tool set read it- // synchronously via sandboxEnforces().- await getSandboxStatus()- // Read once per run, not subscribed: the advertised set is frozen for the- // run anyway, so a mid-run flip in Settings would only desync the prompt.- const webSearch = useWebSearchConfig.getState().webSearchEnabled- // One snapshot per run, shared with every child this run dispatches.- const environment = await getCoworkEnvironment()- const transport = new CoworkChatTransport(sid, {- planMode: current?.planMode ?? false,- subagentNames: subagentDefs.map((d) => d.name),- // Always on at depth 0, even with nothing saved: a one-off subagent with- // an inline `system_prompt` is first-class, as it is in Rust.- allowSubagents: true,- webSearch,- workspacePath,- readOnlyFolder: current?.folder ?? null,- })- await transport.refreshTools()+ runTurns = text+ ? [userTurn(text, attachments?.media, attachments?.files)]+ : []+ syncLive()- const controller = new AbortController()- abortRef.current = controller- // Owned by this request: children cannot outlive the run whose signal- // aborts them, so a fresh inbox per run can never hold a stale ping.- const inbox = new SubagentInbox()- // The session's, not the run's: a watcher keeps going after this run has- // answered, and its pings are drained by whichever run is up next.- const monitorLane = sessionMonitorLane(sid)+ let files = attachments?.files+ const baseMessages = current?.messages ?? []+ messages = text+ ? [+ ...baseMessages,+ {+ id: `${sid}-user-${baseMessages.length}`,+ role: 'user',+ parts: [+ {+ type: 'text',+ text: withAttachedFiles(modelText ?? text, files),+ },+ ...(attachments?.media ?? []),+ ],+ } as any,+ ]+ : [...baseMessages]+ // Local models load before the first token, but only on a cold start. Probe+ // the engine so the load card shows on a real load, not on every warm run.+ if (selectedProvider === 'llamacpp') {+ try {+ const loaded = await getLoadedModels()+ if (!loaded.includes(selectedModel.id)) {+ useCoworkRun.getState().setSessionModelLoadProgress(sid, undefined)+ useCoworkRun.getState().setSessionLoadingModel(sid, true)+ }+ } catch {+ // Probe failed; skip the card rather than flash it every run.+ }+ }- const sink: StreamSink = {- onText: (delta) => {- const last = liveTurnsRef.current[liveTurnsRef.current.length - 1]- if (last && last.role === 'assistant') {- last.content += delta- scheduleLiveSync()- } else {- pushLive([{ role: 'assistant', content: delta }])+ // Documents go into the workspace before the question is sent, so the+ // paths the question names exist by the time the agent reads them. The+ // row was shown first: parsing a large PDF takes a moment.+ if (text && files?.length) {+ files = await importAttachedFiles(files, {+ parse: async (path, fileType) =>+ (await serviceHub.rag().parseDocument?.(path, fileType)) ?? '',+ importFile: (path, parsed) => importAttachment(sid, path, parsed),+ })+ runTurns = [userTurn(text, attachments?.media, files)]+ messages[messages.length - 1].parts[0] = {+ type: 'text',+ text: withAttachedFiles(modelText ?? text, files),}- },- // Native reasoning streams beside the content, so the collapsible- // thinking block fills in live instead of the transcript sitting silent- // for the whole chain of thought.- onReasoning: (delta) => {- const last = liveTurnsRef.current[liveTurnsRef.current.length - 1]- if (last && last.role === 'assistant') {- last.reasoning = (last.reasoning ?? '') + delta+ syncLive()+ }++ // Warm the sandbox probe: the transport's prompt and tool set read it+ // synchronously via sandboxEnforces().+ await getSandboxStatus()+ // Read once per run, not subscribed: the advertised set is frozen for the+ // run anyway, so a mid-run flip in Settings would only desync the prompt.+ const webSearch = useWebSearchConfig.getState().webSearchEnabled+ // One snapshot per run, shared with every child this run dispatches.+ const environment = await getCoworkEnvironment()+ const transport = new CoworkChatTransport(sid, {+ planMode: current?.planMode ?? false,+ subagentNames: subagentDefs.map((d) => d.name),+ // Always on at depth 0, even with nothing saved: a one-off subagent with+ // an inline `system_prompt` is first-class, as it is in Rust.+ allowSubagents: true,+ webSearch,+ workspacePath,+ readOnlyFolder: current?.folder ?? null,+ })+ await transport.refreshTools()++ // Owned by this request: children cannot outlive the run whose signal+ // aborts them, so a fresh inbox per run can never hold a stale ping.+ const inbox = new SubagentInbox()+ // The session's, not the run's: a watcher keeps going after this run has+ // answered, and its pings are drained by whichever run is up next.+ const monitorLane = sessionMonitorLane(sid)++ const sink: StreamSink = {+ onText: (delta) => {+ const last = runTurns[runTurns.length - 1]+ if (last && last.role === 'assistant') {+ last.content += delta+ scheduleLiveSync()+ } else {+ pushLive([{ role: 'assistant', content: delta }])+ }+ },+ // Native reasoning streams beside the content, so the collapsible+ // thinking block fills in live instead of the transcript sitting silent+ // for the whole chain of thought.+ onReasoning: (delta) => {+ const last = runTurns[runTurns.length - 1]+ if (last && last.role === 'assistant') {+ last.reasoning = (last.reasoning ?? '') + delta+ scheduleLiveSync()+ } else {+ pushLive([{ role: 'assistant', content: '', reasoning: delta }])+ }+ },+ onToolStart: (callId, name) =>+ pushLive([+ {+ role: 'tool',+ content: '',+ callId,+ name,+ status: 'running',+ argsLive: '',+ },+ ]),+ // Raw JSON, appended as it arrives. The transcript reads a `write`'s+ // destination and body straight out of this fragment, so the card fills+ // in as the model types rather than waiting for the closing brace.+ onToolArgsDelta: (callId, delta) => {+ const row = runTurns.find((turn) => turn.callId === callId)+ if (!row) return+ row.argsLive = (row.argsLive ?? '') + deltascheduleLiveSync()- } else {- pushLive([{ role: 'assistant', content: '', reasoning: delta }])- }- },- onToolStart: (callId, name) =>- pushLive([- {- role: 'tool',- content: '',- callId,- name,- status: 'running',- argsLive: '',- },- ]),- // Raw JSON, appended as it arrives. The transcript reads a `write`'s- // destination and body straight out of this fragment, so the card fills- // in as the model types rather than waiting for the closing brace.- onToolArgsDelta: (callId, delta) => {- const row = liveTurnsRef.current.find((turn) => turn.callId === callId)- if (!row) return- row.argsLive = (row.argsLive ?? '') + delta- scheduleLiveSync()- },- onToolCall: (call) => {- const row = liveTurnsRef.current.find(- (turn) => turn.callId === call.toolCallId- )- if (row) {- row.args = call.input- syncLive()- }- },- }+ },+ onToolCall: (call) => {+ const row = runTurns.find((turn) => turn.callId === call.toolCallId)+ if (row) {+ row.args = call.input+ syncLive()+ }+ },+ }- const baseMessages = current?.messages ?? []- const messages = text- ? [- ...baseMessages,- {- id: `${sid}-user-${baseMessages.length}`,- role: 'user',- parts: [- { type: 'text', text: withAttachedFiles(modelText ?? text, files) },- ...(attachments?.media ?? []),- ],- } as any,- ]- : [...baseMessages]- let outcome: RunOutcome | null = null- let thrown: Pick<RunOutcome, 'stoppedBy' | 'errorText'> | null = null- try {outcome = await runTurn({messages,signal: controller.signal,@@ -698,9 +690,9 @@ function CoworkPage() {resolve({ output: `ERROR: ${parsed}`, isError: true })return}- setAsk({ requestId: callId, request: parsed })- askResolvers.current.set(callId, (answers) => {- setAsk(null)+ useCoworkRun.getState().addPendingAsk(sid, callId, parsed)+ handle.pendingAsks.set(callId, (answers) => {+ useCoworkRun.getState().removePendingAsk(sid, callId)resolve(renderAskResult(answers))})}),@@ -843,10 +835,11 @@ function CoworkPage() {),sink,onStep: ({ result, turns, outcomes }) => {- if (result.usage) setLiveUsage(result.usage)+ if (result.usage)+ useCoworkRun.getState().setUsage(sid, result.usage)// Replace the optimistic running rows with the settled ones so the// transcript shows results, not spinners.- liveTurnsRef.current = liveTurnsRef.current.filter(+ runTurns = runTurns.filter((turn) =>!(turn.role === 'tool' && outcomes.has(turn.callId ?? '')) &&!(turn.role === 'assistant' && turn.content === result.text)@@ -911,22 +904,22 @@ function CoworkPage() {.getState().commitTurns(sid,- liveTurnsRef.current,+ runTurns,outcome?.messages ?? messages,useCoworkRun.getState().subagents[sid] ?? [],outcome?.usage ?? undefined)+ if (liveFrame != null) cancelAnimationFrame(liveFrame)+ for (const resolve of handle.pendingAsks.values()) resolve(null)+ handle.pendingAsks.clear()+ releaseHandle(sid, handle)useCoworkRun.getState().clearCodeRun(sid)- liveTurnsRef.current = []- syncLive()- setRunning(false)- setRunSid(null)- abortRef.current = null- askResolvers.current.clear()- setAsk(null)const stop = thrown?.stoppedBy ?? outcome?.stoppedBy ?? null- setStoppedBy(stop)- setRunError(thrown?.errorText ?? outcome?.errorText)+ if (stop)+ useCoworkRun.getState().setOutcome(sid, {+ stoppedBy: stop,+ errorText: thrown?.errorText ?? outcome?.errorText,+ })// Message queue (ChatInput enqueues while chatStatus is 'streaming',// scoped to this session): a clean finish sends the next queued message;@@ -936,13 +929,14 @@ function CoworkPage() {if (stop === 'error') {useMessageQueue.getState().clearQueue(sid)} else if (stop === 'done') {- // Deferred past the re-render so the next runRequest closure sees- // running=false; skipped if the user has since switched sessions, since- // runRequest always targets the current one.+ // Continue the originating session with its captured model and skill+ // context, even when a different session is now being viewed.setTimeout(() => {- if (useCoworkSessions.getState().currentId !== sid) return+ if (!useCoworkSessions.getState().sessions.some((s) => s.id === sid))+ return+ if (useCoworkRun.getState().runId[sid]) returnconst next = useMessageQueue.getState().dequeue(sid)- if (next) void runRequestRef.current(next.text)+ if (next) void runRequest(next.text, undefined, sid)}, 0)}}@@ -1271,29 +1265,19 @@ function CoworkPage() {[running, session?.id, questionTurnIndex])- const abortRef = useRef<AbortController | null>(null)- const askResolvers = useRef(- new Map<string, (answers: AskAnswer[] | null) => void>()- )const handleStop = useCallback(() => {- abortRef.current?.abort('cancelled')// Aborting the JS run only discards the pending tool result; a running or// backgrounded bash keeps executing until this kills the session's shells.if (session?.id) {abortRun(session.id)void cancelAgentThreadBash(session.id)}- for (const resolve of askResolvers.current.values()) resolve(null)- askResolvers.current.clear()}, [session?.id])const respondAsk = useCallback((requestId: string, answers: AskAnswer[] | null) => {- const resolve = askResolvers.current.get(requestId)- askResolvers.current.delete(requestId)- if (resolve) resolve(answers)- else if (session?.id) answerAsk(session.id, requestId, answers)+ if (session?.id) answerAsk(session.id, requestId, answers)},[session?.id])