Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork): stop reporting a cancelled run as a failed tool call
Akarshan Biswas100d612e7853
diff --git a/web-app/src/containers/CoworkRunNotice.tsx b/web-app/src/containers/CoworkRunNotice.tsxnew file mode 100644index 000000000..c4e062b94--- /dev/null+++ b/web-app/src/containers/CoworkRunNotice.tsx@@ -0,0 +1,54 @@+import { CircleSlash, TriangleAlert } from 'lucide-react'+import { Button } from '@/components/ui/button'+import { useTranslation } from '@/i18n/react-i18next-compat'++type Props =+ | { kind: 'stopped' }+ | { kind: 'error'; message?: string; onRetry: () => void }++/**+ * How a run ended when it ended without an answer.+ *+ * Split from the budget notice by weight, not by wording: a stop is something+ * the user just did and needs no colour, while a failure is the one state on+ * this surface that should look like one. Neither is a tool call, which is what+ * they used to be rendered as — a fake `error` tool whose card claimed the agent+ * had run something.+ */+export function CoworkRunNotice(props: Props) {+ const { t } = useTranslation()++ if (props.kind === 'stopped') {+ return (+ <div+ role="status"+ data-testid="cowork-run-notice"+ className="mt-2 flex items-center gap-2 text-xs text-muted-foreground"+ >+ <CircleSlash size={14} aria-hidden className="shrink-0" />+ <span>{t('common:run.stopped')}</span>+ </div>+ )+ }++ return (+ <div+ role="alert"+ data-testid="cowork-run-notice"+ className="mt-2 flex flex-wrap items-center gap-2 text-xs text-destructive"+ >+ <TriangleAlert size={14} aria-hidden className="shrink-0" />+ <span className="min-w-0 break-words">+ {props.message?.trim() || t('common:run.failed')}+ </span>+ <Button+ variant="outline"+ size="sm"+ className="h-7"+ onClick={props.onRetry}+ >+ {t('common:run.tryAgain')}+ </Button>+ </div>+ )+}diff --git a/web-app/src/containers/__tests__/CoworkRunNotice.test.tsx b/web-app/src/containers/__tests__/CoworkRunNotice.test.tsxnew file mode 100644index 000000000..422b3a983--- /dev/null+++ b/web-app/src/containers/__tests__/CoworkRunNotice.test.tsx@@ -0,0 +1,44 @@+import { describe, it, expect, vi } from 'vitest'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({ t: (k: string) => k }),+}))++import { CoworkRunNotice } from '../CoworkRunNotice'++describe('CoworkRunNotice', () => {+ // A stop is something the user just did: no colour, no alert role, and+ // nothing to act on.+ it('states a stop quietly, with no action', () => {+ render(<CoworkRunNotice kind="stopped" />)+ expect(screen.getByRole('status')).toHaveTextContent('common:run.stopped')+ expect(screen.queryByRole('button')).toBeNull()+ })++ it('shows the provider’s own message rather than a generic one', () => {+ render(+ <CoworkRunNotice+ kind="error"+ message="error sending request for url"+ onRetry={vi.fn()}+ />+ )+ expect(screen.getByRole('alert')).toHaveTextContent(+ 'error sending request for url'+ )+ })++ it('falls back to its own wording when the failure has none', () => {+ render(<CoworkRunNotice kind="error" message=" " onRetry={vi.fn()} />)+ expect(screen.getByRole('alert')).toHaveTextContent('common:run.failed')+ })++ it('offers a retry', async () => {+ const onRetry = vi.fn()+ render(<CoworkRunNotice kind="error" onRetry={onRetry} />)+ await userEvent.click(screen.getByRole('button'))+ expect(onRetry).toHaveBeenCalledOnce()+ })+})diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.test.tsindex 8806decdf..f1a2d905b 100644--- a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts+++ b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts@@ -11,7 +11,8 @@ vi.mock('@/lib/backendStorage', () => ({import { useCoworkSessions } from '../useCoworkSessions'import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'-const reset = () => useCoworkSessions.setState({ sessions: [], currentId: null })+const reset = () =>+ useCoworkSessions.setState({ sessions: [], currentId: null })const sub = (runId: string, name: string): SubagentRun => ({runId,@@ -31,6 +32,39 @@ describe('useCoworkSessions', () => {expect(s.folder).toBeNull()})+ it('rewinds a run back to the question that started it', () => {+ const id = useCoworkSessions.getState().createSession()+ const turns: CoworkTurn[] = [+ { role: 'user', content: 'first' },+ { role: 'assistant', content: 'done' },+ { role: 'user', content: 'second' },+ { role: 'tool', content: '', name: 'read', status: 'done' },+ { role: 'assistant', content: 'answer' },+ ]+ const msgs = [+ { id: 'm1', role: 'user', parts: [] },+ { id: 'm2', role: 'assistant', parts: [] },+ { id: 'm3', role: 'user', parts: [] },+ { id: 'm4', role: 'assistant', parts: [] },+ ] as never+ useCoworkSessions.getState().commitTurns(id, turns, msgs, [])+ useCoworkSessions.getState().rewindToLastUser(id)++ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!+ // The question survives; the chain of tool calls it produced does not.+ expect(s.turns.map((t) => t.content)).toEqual(['first', 'done', 'second'])+ expect(s.messages.map((m) => m.id)).toEqual(['m1', 'm2', 'm3'])+ })++ // Rewinding a session that has never had a turn would otherwise empty it.+ it('leaves a session with no user turn alone', () => {+ const id = useCoworkSessions.getState().createSession()+ useCoworkSessions.getState().rewindToLastUser(id)+ const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!+ expect(s.turns).toEqual([])+ expect(s.messages).toEqual([])+ })+it('appends turns and replaces the message list on commit', () => {const id = useCoworkSessions.getState().createSession()const turn: CoworkTurn = { role: 'user', content: 'hi' }@@ -59,7 +93,9 @@ describe('useCoworkSessions', () => {it('keeps the last usage when a run reports none', () => {const id = useCoworkSessions.getState().createSession()- useCoworkSessions.getState().commitTurns(id, [], [], [], { total_tokens: 42 })+ useCoworkSessions+ .getState()+ .commitTurns(id, [], [], [], { total_tokens: 42 })useCoworkSessions.getState().commitTurns(id, [], [], [])const s = useCoworkSessions.getState().sessions.find((x) => x.id === id)!expect(s.lastUsage?.total_tokens).toBe(42)@@ -130,9 +166,9 @@ describe('useCoworkSessions persist migration', () => {(m: { parts?: unknown[] }) => m.parts ?? [])expect(out.sessions[0].messages.length).toBeGreaterThan(0)- expect(- parts.some((p: { type?: string }) => p.type === 'tool-write')- ).toBe(true)+ expect(parts.some((p: { type?: string }) => p.type === 'tool-write')).toBe(+ true+ )})it('leaves an already-migrated session alone', () => {diff --git a/web-app/src/hooks/useCoworkSessions.ts b/web-app/src/hooks/useCoworkSessions.tsindex 339ca90bc..15d21f9e3 100644--- a/web-app/src/hooks/useCoworkSessions.ts+++ b/web-app/src/hooks/useCoworkSessions.ts@@ -89,6 +89,10 @@ type CoworkSessionsState = {subagents: SubagentRun[],usage?: Usage) => void+ /** Drop everything the agent produced since the last question, so the run can+ * be taken again. Both lists are rewound together or the transcript and the+ * history the model sees would disagree. */+ rewindToLastUser: (id: string) => voidclearSession: (id: string) => void}@@ -193,6 +197,28 @@ export const useCoworkSessions = create<CoworkSessionsState>()(}),})),+ rewindToLastUser: (id) =>+ set((s) => ({+ sessions: s.sessions.map((x) => {+ if (x.id !== id) return x+ const lastIndexOfUser = (roles: { role: string }[]) => {+ for (let i = roles.length - 1; i >= 0; i--) {+ if (roles[i].role === 'user') return i+ }+ return -1+ }+ const lastTurn = lastIndexOfUser(x.turns)+ const lastMessage = lastIndexOfUser(x.messages)+ if (lastTurn < 0 || lastMessage < 0) return x+ return {+ ...x,+ turns: x.turns.slice(0, lastTurn + 1),+ messages: x.messages.slice(0, lastMessage + 1),+ updated: now(),+ }+ }),+ })),+clearSession: (id) =>set((s) => ({sessions: s.sessions.map((x) =>@@ -232,7 +258,10 @@ export const useCoworkSessions = create<CoworkSessionsState>()(? session: {...session,- messages: coworkTurnsToUIMessages(session.turns ?? [], session.id),+ messages: coworkTurnsToUIMessages(+ session.turns ?? [],+ session.id+ ),}),}diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.tsindex 7a124ea97..1d32f3f2c 100644--- a/web-app/src/lib/__tests__/coworkRunner.test.ts+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts@@ -7,6 +7,7 @@ import {turnsFor,abortRun,answerAsk,+ isAbortLike,isRunning,__testing,type PendingToolCall,@@ -36,7 +37,11 @@ const textStep = (text: string, usageTotal?: number): UIMessageChunk[] => []const toolStep = (name: string, id = 'c1'): UIMessageChunk[] => [- { type: 'tool-input-start', toolCallId: id, toolName: name } as UIMessageChunk,+ {+ type: 'tool-input-start',+ toolCallId: id,+ toolName: name,+ } as UIMessageChunk,{type: 'tool-input-available',toolCallId: id,@@ -58,7 +63,9 @@ const deps = () => {let i = 0return {- sendStep: vi.fn(async () => streamOf(steps[Math.min(i++, steps.length - 1)])),+ sendStep: vi.fn(async () =>+ streamOf(steps[Math.min(i++, steps.length - 1)])+ ),dispatch,sink: noopSink(),onStep: vi.fn(),@@ -288,3 +295,72 @@ describe('run handles', () => {expect(() => abortRun('nope')).not.toThrow()})})++describe('isAbortLike', () => {+ it('recognises the stop the tauri http plugin actually reports', () => {+ expect(isAbortLike(new Error('Request cancelled'))).toBe(true)+ const err = new Error('nope')+ err.name = 'AbortError'+ expect(isAbortLike(err)).toBe(true)+ })++ // A dropped socket says "connection aborted"; reporting that as a user stop+ // would hide a real failure behind a notice that says nothing went wrong.+ it('does not mistake a network failure for a stop', () => {+ expect(isAbortLike(new Error('connection aborted by peer'))).toBe(false)+ })++ it('trusts the signal over the message', () => {+ const c = new AbortController()+ c.abort()+ expect(isAbortLike(new Error('error sending request'), c.signal)).toBe(true)+ })+})++describe('runTurn failure paths', () => {+ const throwingDeps = (error: unknown) => ({+ ...deps([[]]),+ sendStep: vi.fn(async () => {+ throw error+ }),+ })++ it('reports a stop as an outcome instead of throwing', async () => {+ const c = new AbortController()+ const d = throwingDeps(new Error('Request cancelled'))+ c.abort()+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: c.signal,+ })+ expect(out.stoppedBy).toBe('aborted')+ expect(out.errorText).toBeUndefined()+ })++ it('reports a transport failure as an outcome, message intact', async () => {+ const d = throwingDeps(new Error('error sending request for url (…)'))+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('error')+ expect(out.errorText).toContain('error sending request')+ // Nothing to replay: the model never answered, so no assistant turn exists.+ expect(out.messages).toHaveLength(1)+ })++ // An assistant message with no parts is a turn the model never took, and the+ // next request would replay it as one.+ it('appends no assistant message for a step that produced nothing', async () => {+ const d = deps([[{ type: 'error', errorText: 'boom' } as UIMessageChunk]])+ const out = await runTurn({+ messages: [user('hi')],+ deps: d,+ signal: new AbortController().signal,+ })+ expect(out.stoppedBy).toBe('error')+ expect(out.messages).toHaveLength(1)+ })+})diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.tsindex 2116fb3ec..7be0bc3dd 100644--- a/web-app/src/lib/coworkRunner.ts+++ b/web-app/src/lib/coworkRunner.ts@@ -98,6 +98,24 @@ export function abortRun(sid: string, reason = 'cancelled'): void {handles.delete(sid)}+/**+ * Whether a rejection means "the user stopped this", not "this failed".+ *+ * Needed because the abort does not arrive as an `AbortError`: Jan streams+ * through `@tauri-apps/plugin-http`, whose `fetch` rejects with a plain+ * `Error('Request cancelled')` when the signal fires. Matched exactly rather+ * than by substring — "connection aborted" is a network failure and must keep+ * being reported as one.+ */+export function isAbortLike(e: unknown, signal?: AbortSignal): boolean {+ if (signal?.aborted) return true+ if (e instanceof Error && e.name === 'AbortError') return true+ const message = (e instanceof Error ? e.message : String(e)).trim()+ return /^(request cancelled|the operation was aborted\.?|the user aborted a request\.?)$/i.test(+ message+ )+}+/** Settle a pending `ask`. Returns false when the request is already gone. */export function answerAsk(sid: string,@@ -253,10 +271,7 @@ export type RunDeps = {signal: AbortSignal) => Promise<ReadableStream<UIMessageChunk>>/** Run one tool call. Must resolve, never reject. */- dispatch: (- call: PendingToolCall,- signal: AbortSignal- ) => Promise<ToolOutcome>+ dispatch: (call: PendingToolCall, signal: AbortSignal) => Promise<ToolOutcome>sink: StreamSink/** Called once per completed step with everything that step produced. */onStep: (info: {@@ -329,8 +344,27 @@ export async function runTurn(opts: {// A snapshot, not the live array: the loop pushes to `messages` after the// stream is handed over, and the transport rewrites what it is given// (trimming, compaction) without expecting it to move underneath.- const stream = await deps.sendStep([...messages], signal)- const result = await consumeStep(stream, deps.sink)+ let result: StepResult+ try {+ const stream = await deps.sendStep([...messages], signal)+ result = await consumeStep(stream, deps.sink)+ } catch (e) {+ // A transport failure is an outcome, not an exception: throwing here left+ // the caller with no steps, no usage and nothing to render but the raw+ // message, and a user-initiated stop arrived down this same path.+ return {+ messages,+ steps: step,+ usage,+ sessionTokens: spend.spent,+ stoppedBy: isAbortLike(e, signal) ? 'aborted' : 'error',+ errorText: isAbortLike(e, signal)+ ? undefined+ : e instanceof Error+ ? e.message+ : String(e),+ }+ }step += 1if (result.usage) {usage = result.usage@@ -338,7 +372,13 @@ export async function runTurn(opts: {}if (result.errorText) {- messages.push(assistantMessageFor(deps.nextMessageId(), result, new Map()))+ // Only when the step produced something: an assistant message with no+ // parts is a turn the model never took, and it would be replayed as one.+ if (result.text || result.toolCalls.length > 0) {+ messages.push(+ assistantMessageFor(deps.nextMessageId(), result, new Map())+ )+ }deps.onStep({step,result,@@ -369,7 +409,9 @@ export async function runTurn(opts: {outcomes.set(call.toolCallId, await deps.dispatch(call, signal))}- messages.push(assistantMessageFor(deps.nextMessageId(), result, outcomes))+ if (result.text || result.toolCalls.length > 0) {+ messages.push(assistantMessageFor(deps.nextMessageId(), result, outcomes))+ }deps.onStep({ step, result, turns: turnsFor(result, outcomes), outcomes })if (result.aborted || signal.aborted) {diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex eba8c7a36..842e0af48 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -685,6 +685,11 @@"compact": "Compact","newSession": "New session"},+ "run": {+ "stopped": "Stopped.",+ "failed": "The run stopped early.",+ "tryAgain": "Try again"+ },"modelNoTools": "{{model}} can’t call tools, so it can’t act as an agent. Pick a tool-calling model.","askContinue": "Continue","askNext": "Next question",diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex c03a956ee..08eb7ac27 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -50,6 +50,7 @@ import { CoworkChangesChip } from '@/containers/CoworkChangesChip'import { collectCodeFileDiffs } from '@/lib/coworkDiffs'import { CoworkSandboxChip } from '@/containers/CoworkSandboxChip'import { CoworkBudgetNotice } from '@/containers/CoworkBudgetNotice'+import { CoworkRunNotice } from '@/containers/CoworkRunNotice'import { CoworkAskCard } from '@/containers/CoworkAskCard'import { CoworkChatTransport } from '@/lib/coworkTransport'import { dispatchCoworkTool } from '@/lib/coworkDispatch'@@ -60,6 +61,7 @@ import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { MAX_AGENT_STEPS } from '@/lib/coworkBudget'import {abortRun,+ isAbortLike,answerAsk,runTurn,type RunOutcome,@@ -102,6 +104,7 @@ function CoworkPage() {const [stoppedBy, setStoppedBy] = useState<RunOutcome['stoppedBy'] | null>(null)+ const [runError, setRunError] = useState<string | undefined>(undefined)const [gitBranch, setGitBranch] = useState<string | null>(null)const [subagentDefs, setSubagentDefs] = useState<SubagentDefinition[]>([])const [workspacePath, setWorkspacePath] = useState<string | null>(null)@@ -182,8 +185,14 @@ function CoworkPage() {if (session?.id) useCoworkSessions.getState().setFolder(session.id, null)}, [session?.id])+ // `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 displayedTurns = useMemo(- () => (running ? liveTurns : (session?.turns ?? [])),+ () =>+ running+ ? [...(session?.turns ?? []), ...liveTurns]+ : (session?.turns ?? []),[running, liveTurns, session?.turns])const uiMessages = useMemo(@@ -229,11 +238,17 @@ function CoworkPage() {setLiveTurns(liveTurnsRef.current)}, [])- const handleSubmit = async (text: string) => {+ /**+ * Drive one request. `text` is null for a resume — a retry after a failure+ * re-runs the committed history rather than re-sending the question, which+ * would leave the model reading it twice.+ */+ const runRequest = async (text: string | null) => {if (running) returnconst sid = ensureCurrentSession()const store = useCoworkSessions.getState()const current = store.sessions.find((s) => s.id === sid)+ if (!text && !(current?.messages?.length ?? 0)) returnif (!selectedModel?.id) {toast.error(t('common:selectModel'))return@@ -245,11 +260,13 @@ function CoworkPage() {toast.error(t('common:modelNoTools', { model: selectedModel.id }))return}- if (current?.title === 'New session') store.setTitle(sid, text.slice(0, 40))+ if (text && current?.title === 'New session')+ store.setTitle(sid, text.slice(0, 40))setStoppedBy(null)+ setRunError(undefined)setLiveUsage(null)- liveTurnsRef.current = [{ role: 'user', content: text }]+ liveTurnsRef.current = text ? [{ role: 'user', content: text }] : []setLiveTurns(liveTurnsRef.current)useCoworkRun.getState().resetSubagents(sid)setRunning(true)@@ -316,16 +333,19 @@ function CoworkPage() {}const baseMessages = current?.messages ?? []- const messages = [- ...baseMessages,- {- id: `${sid}-user-${baseMessages.length}`,- role: 'user',- parts: [{ type: 'text', text }],- } as any,- ]+ const messages = text+ ? [+ ...baseMessages,+ {+ id: `${sid}-user-${baseMessages.length}`,+ role: 'user',+ parts: [{ type: 'text', text }],+ } as any,+ ]+ : [...baseMessages]let outcome: RunOutcome | null = null+ let thrown: Pick<RunOutcome, 'stoppedBy' | 'errorText'> | null = nulltry {outcome = await runTurn({messages,@@ -481,16 +501,15 @@ function CoworkPage() {},})} catch (e) {- pushLive([- {- role: 'tool',- content: '',- name: 'error',- result: e instanceof Error ? e.message : String(e),- isError: true,- status: 'done',- },- ])+ // The runner turns a failed step into an outcome, so this is the last+ // resort — a fault in the loop itself. Either way it is not a tool call,+ // and rendering it as one claimed the agent had run something.+ thrown = isAbortLike(e, controller.signal)+ ? { stoppedBy: 'aborted' }+ : {+ stoppedBy: 'error',+ errorText: e instanceof Error ? e.message : String(e),+ }} finally {useAppState.getState().updateLoadingModel(false)useCoworkSessions@@ -508,10 +527,29 @@ function CoworkPage() {abortRef.current = nullaskResolvers.current.clear()setAsk(null)- setStoppedBy(outcome?.stoppedBy ?? null)+ setStoppedBy(thrown?.stoppedBy ?? outcome?.stoppedBy ?? null)+ setRunError(thrown?.errorText ?? outcome?.errorText)}}+ // Read through a ref so the memoized message rows keep a stable callback+ // while still calling the current render's closure.+ const runRequestRef = useRef(runRequest)+ runRequestRef.current = runRequest++ const handleSubmit = (text: string) => void runRequest(text)++ /**+ * Take the last turn again. Rewinding to the question and resuming is the+ * whole operation — an agent turn is a chain of tool calls, so regenerating+ * means discarding that chain, not re-sending the question after it.+ */+ const handleRegenerate = useCallback(() => {+ if (running || !session?.id) return+ useCoworkSessions.getState().rewindToLastUser(session.id)+ void runRequestRef.current(null)+ }, [running, session?.id])+const abortRef = useRef<AbortController | null>(null)const askResolvers = useRef(new Map<string, (answers: AskAnswer[] | null) => void>()@@ -579,6 +617,7 @@ function CoworkPage() {isFirstMessage={i === 0}isLastMessage={i === uiMessages.length - 1}status={running ? 'streaming' : 'ready'}+ onRegenerate={handleRegenerate}reasoningContainerRef={reasoningContainerRef}isReasoningAtBottom={isReasoningAtBottom}onReasoningScroll={handleReasoningScroll}@@ -615,6 +654,16 @@ function CoworkPage() {onContinue={() => void handleSubmit('Continue.')}/>)}+ {stoppedBy === 'aborted' && (+ <CoworkRunNotice kind="stopped" />+ )}+ {stoppedBy === 'error' && (+ <CoworkRunNotice+ kind="error"+ message={runError}+ onRetry={() => void runRequest(null)}+ />+ )}{stoppedBy === 'tokens' && (<CoworkBudgetNoticekind="tokens"