From c35a0784c443267468c32dddce166cf65f847298 Mon Sep 17 00:00:00 2001 From: syedmustafan Date: Tue, 24 Nov 2026 10:07:31 +0500 Subject: [PATCH 1/4] fix(desktop): show pending approval in tool rows Refs #459 --- changes/459.fixed.md | 1 + desktop/src/features/chat/ToolCallCard.tsx | 30 +++-- .../src/features/chat/cards/BrowserCard.tsx | 20 +-- .../src/features/chat/cards/CodeRunCard.tsx | 6 +- .../src/features/chat/cards/SubagentCard.tsx | 2 +- .../src/features/chat/cards/TerminalCard.tsx | 2 +- desktop/src/features/chat/cards/bits.tsx | 2 +- desktop/src/features/chat/toolMeta.ts | 8 ++ desktop/src/lib/chatFold.ts | 17 +-- desktop/tests/approvalToolRows.test.ts | 115 ++++++++++++++++++ 10 files changed, 168 insertions(+), 35 deletions(-) create mode 100644 changes/459.fixed.md create mode 100644 desktop/tests/approvalToolRows.test.ts diff --git a/changes/459.fixed.md b/changes/459.fixed.md new file mode 100644 index 000000000..1692a80d2 --- /dev/null +++ b/changes/459.fixed.md @@ -0,0 +1 @@ +**Chat shows which actions are waiting for your approval.** The file or browser step shows what Sentient would do and updates when it finishes. Declined, failed and interrupted steps show their own status. diff --git a/desktop/src/features/chat/ToolCallCard.tsx b/desktop/src/features/chat/ToolCallCard.tsx index 2d5cfbe1b..a87ea4571 100644 --- a/desktop/src/features/chat/ToolCallCard.tsx +++ b/desktop/src/features/chat/ToolCallCard.tsx @@ -1,7 +1,7 @@ -import { IconAlertTriangle, IconCheck, IconChevronRight, IconClockHour4, IconHandFinger, IconShieldQuestion, IconX } from '@tabler/icons-react' +import { IconAlertTriangle, IconChevronRight, IconClockHour4, IconHandFinger } from '@tabler/icons-react' import { AnimatePresence, motion } from 'motion/react' import { useState } from 'react' -import { JsonView, Spinner } from '@/components/ui' +import { JsonView } from '@/components/ui' import type { ApprovalView, ToolCallView } from '@/lib/chatFold' import type { ApprovalDecision } from '@/lib/types' import { cn, formatDuration } from '@/lib/utils' @@ -14,7 +14,7 @@ import { TerminalCard } from './cards/TerminalCard' import { asHandOff, HandOffCard } from './HandOffCard' import { UndoCard } from './UndoCard' import { IMAGE_FILE_RE, openOutputFile, outputPath } from './files' -import { argsPreview, toolMeta } from './toolMeta' +import { argsPreview, toolMeta, toolStatusLabel } from './toolMeta' function GenericToolCard({ tool, @@ -33,9 +33,15 @@ function GenericToolCard({ const running = tool.status === 'running' const failed = tool.status === 'error' const denied = tool.status === 'denied' - const preview = argsPreview(tool.arguments) + const fileName = tool.status === 'awaiting_approval' && tool.name === 'file_write' && typeof tool.arguments?.name === 'string' + ? tool.arguments.name.trim() + : '' + const preview = fileName || argsPreview(tool.arguments) const hasResult = tool.result !== undefined && tool.result !== null && tool.result !== '' const handOff = asHandOff(tool.result) + const label = fileName + ? 'Would write' + : toolStatusLabel(tool.name, tool.status) ?? (running ? meta.running : handOff ? 'Prepared for you' : meta.done) return (
@@ -60,7 +66,7 @@ function GenericToolCard({ ) : ( <> - {running ? meta.running : handOff ? 'Prepared for you' : meta.done} + {label} {preview && {preview}} {!preview && } @@ -72,22 +78,14 @@ function GenericToolCard({ {running && tool.undo?.status === 'waiting' ? ( - ) : running ? ( - - ) : tool.status === 'awaiting_approval' ? ( - - ) : failed ? ( - - ) : denied ? ( - - ) : handOff ? ( + ) : tool.status === 'done' && handOff ? ( - ) : problem ? ( + ) : tool.status === 'done' && problem ? ( ) : ( - + )} diff --git a/desktop/src/features/chat/cards/BrowserCard.tsx b/desktop/src/features/chat/cards/BrowserCard.tsx index 90302f1e1..cea6d9ee4 100644 --- a/desktop/src/features/chat/cards/BrowserCard.tsx +++ b/desktop/src/features/chat/cards/BrowserCard.tsx @@ -5,8 +5,8 @@ import { api } from '@/lib/api' import type { ApprovalView, ToolCallView } from '@/lib/chatFold' import { cn, truncate } from '@/lib/utils' import { outputPath } from '../files' -import { toolMeta } from '../toolMeta' -import { asRecord, DeclinedText, hostOf, prettyUrl, refLabel, Shimmer, StatusGlyph } from './bits' +import { toolMeta, toolStatusLabel } from '../toolMeta' +import { actionTarget, asRecord, DeclinedText, hostOf, prettyUrl, refLabel, Shimmer, StatusGlyph } from './bits' export const isBrowserTool = (name: string) => name.startsWith('browser_') @@ -18,7 +18,12 @@ interface BrowserResult { element?: string } -function stepLabel(t: ToolCallView): string { +function stepLabel(t: ToolCallView, approval?: ApprovalView): string { + const label = toolStatusLabel(t.name, t.status) + if (label) { + const target = t.status === 'awaiting_approval' && t.name === 'browser_click' ? actionTarget(t, approval) : null + return target ? `${label} “${truncate(target, 48)}”` : label + } const a = t.arguments as Record const r = asRecord(t.result) const running = t.status === 'running' @@ -50,7 +55,7 @@ function stepLabel(t: ToolCallView): string { export function BrowserCard({ tools, approvals = [] }: { tools: ToolCallView[]; approvals?: ApprovalView[] }) { const liveFrame = useBrowserView((s) => s.frame) const running = tools.some((t) => t.status === 'running' || t.status === 'awaiting_approval') - const allDeclined = tools.length > 0 && tools.every((t) => t.status === 'denied') + const used = tools.some((t) => t.status === 'done') const results = tools.map((t) => asRecord(t.result)) const progressFrame = [...tools].reverse().find((t) => t.progress?.frame)?.progress?.frame const shot = [...results].reverse().find((r) => r?.file)?.file @@ -96,7 +101,7 @@ export function BrowserCard({ tools, approvals = [] }: { tools: ToolCallView[];
- {running ? Using the browser : allDeclined ? 'Browser step not done' : 'Used the browser'} + {running ? Using the browser : used ? 'Used the browser' : 'Browser'} {tools.length} {tools.length === 1 ? 'step' : 'steps'} @@ -112,13 +117,14 @@ export function BrowserCard({ tools, approvals = [] }: { tools: ToolCallView[]; {hidden > 0 &&
  • {hidden} earlier steps
  • } {steps.map((t) => { const meta = toolMeta(t.name) + const approval = approvals.find((a) => a.callId === t.callId) return (
  • {t.status === 'denied' ? ( - a.callId === t.callId)} className="min-w-0 flex-1" /> + ) : ( - {stepLabel(t)} + {stepLabel(t, approval)} )}
  • diff --git a/desktop/src/features/chat/cards/CodeRunCard.tsx b/desktop/src/features/chat/cards/CodeRunCard.tsx index 9b99da218..6827dc61c 100644 --- a/desktop/src/features/chat/cards/CodeRunCard.tsx +++ b/desktop/src/features/chat/cards/CodeRunCard.tsx @@ -31,7 +31,7 @@ export function CodeRunCard({ tool }: { tool: ToolCallView }) { if (running && output.current) output.current.scrollTop = output.current.scrollHeight }, [running, stdout, stderr]) - const title = args.purpose?.trim() || 'Ran some code' + const title = args.purpose?.trim() || (tool.status === 'done' ? 'Ran some code' : 'Code') const subline = waiting ? 'Waiting for your OK before running' : running @@ -40,7 +40,9 @@ export function CodeRunCard({ tool }: { tool: ToolCallView }) { ? 'Not run, so nothing changed' : failed ? `Stopped with a problem${duration ? ` after ${formatDuration(duration)}` : ''}` - : `Finished${duration ? ` in ${formatDuration(duration)}` : ''}` + : tool.status === 'cancelled' + ? 'Step interrupted' + : `Finished${duration ? ` in ${formatDuration(duration)}` : ''}` const backend = res?.backend const hasResult = res && res.result !== null && res.result !== undefined && res.result !== '' const showOutput = !!(stdout || stderr) diff --git a/desktop/src/features/chat/cards/SubagentCard.tsx b/desktop/src/features/chat/cards/SubagentCard.tsx index 82c2ba0e1..d3671f531 100644 --- a/desktop/src/features/chat/cards/SubagentCard.tsx +++ b/desktop/src/features/chat/cards/SubagentCard.tsx @@ -15,7 +15,7 @@ export const isSubagentTool = (name: string) => name === 'delegate_task' || name function statusFromTool(tool: ToolCallView): SubagentStatus { if (tool.status === 'running' || tool.status === 'awaiting_approval') return 'running' if (tool.status === 'error') return 'error' - if (tool.status === 'denied') return 'cancelled' + if (tool.status === 'denied' || tool.status === 'cancelled') return 'cancelled' return 'completed' } diff --git a/desktop/src/features/chat/cards/TerminalCard.tsx b/desktop/src/features/chat/cards/TerminalCard.tsx index 956cfd17b..60b1151c6 100644 --- a/desktop/src/features/chat/cards/TerminalCard.tsx +++ b/desktop/src/features/chat/cards/TerminalCard.tsx @@ -50,7 +50,7 @@ export function TerminalCard({ tool }: { tool: ToolCallView }) { ? 'Stopped because it took too long' : res && res.exit_code !== null ? `${res.exit_code === 0 ? 'Finished' : `Finished with exit code ${res.exit_code}`}${duration ? ` in ${formatDuration(duration)}` : ''}` - : null + : tool.status === 'cancelled' ? 'Step interrupted' : null return (
    diff --git a/desktop/src/features/chat/cards/bits.tsx b/desktop/src/features/chat/cards/bits.tsx index 41c8070cf..30b77a1be 100644 --- a/desktop/src/features/chat/cards/bits.tsx +++ b/desktop/src/features/chat/cards/bits.tsx @@ -80,7 +80,7 @@ export function Shimmer({ children, className }: { children: ReactNode; classNam ) } -export function StatusGlyph({ status, size = 14 }: { status: ToolStatus | 'cancelled'; size?: number }) { +export function StatusGlyph({ status, size = 14 }: { status: ToolStatus; size?: number }) { if (status === 'running') return if (status === 'awaiting_approval') return if (status === 'error') return diff --git a/desktop/src/features/chat/toolMeta.ts b/desktop/src/features/chat/toolMeta.ts index c53ef6bf4..c4f58989b 100644 --- a/desktop/src/features/chat/toolMeta.ts +++ b/desktop/src/features/chat/toolMeta.ts @@ -37,6 +37,7 @@ import { IconWorld, type Icon } from '@tabler/icons-react' +import type { ToolStatus } from '@/lib/chatFold' import { humanize, truncate } from '@/lib/utils' interface ToolMeta { @@ -145,6 +146,13 @@ export function askingLabel(name: string): string | null { return KNOWN[name] && !KNOWN[name].would ? null : wouldLabel(name) } +/** Wording for steps waiting for an answer or ending without success. */ +export function toolStatusLabel(name: string, status: ToolStatus): string | undefined { + if (status === 'awaiting_approval') return askingLabel(name) ?? 'Waiting for your answer' + if (status === 'error') return 'Step failed' + if (status === 'cancelled') return 'Step interrupted' +} + export function toolMeta(name: string): ToolMeta { const known = KNOWN[name] if (known) return known diff --git a/desktop/src/lib/chatFold.ts b/desktop/src/lib/chatFold.ts index 04a00b832..74b67a20d 100644 --- a/desktop/src/lib/chatFold.ts +++ b/desktop/src/lib/chatFold.ts @@ -8,7 +8,7 @@ import type { ActionPreview, AgentEvent, AnswerSource, ApprovalDecision, ContextMeter, MemorySource, OutcomeCheck, Risk, TranscriptMessage, UsageEvent } from './types' import { safeJsonParse } from './utils' -export type ToolStatus = 'running' | 'awaiting_approval' | 'done' | 'error' | 'denied' +export type ToolStatus = 'running' | 'awaiting_approval' | 'done' | 'error' | 'denied' | 'cancelled' /** Live `tool_progress` accumulated per call (§10). Not persisted: history shows the final result only. */ export interface ToolProgressView { @@ -246,7 +246,8 @@ export function foldTranscript(rows: TranscriptMessage[]): TimelineItem[] { callId: tc.id, name: tc.function?.name ?? 'tool', arguments: safeJsonParse>(tc.function?.arguments, {}), - status: 'done' + // A turn can stop after recording the call and before recording its result. + status: 'cancelled' } } if (!row.tool_calls?.length) turn.messageId = row.id @@ -403,16 +404,18 @@ export function applyAgentEvent(turn: AssistantTurnView, ev: AgentEvent): Assist const memorySources = ev.memory_sources?.length ? ev.memory_sources : turn.memorySources const sources = ev.sources?.length ? ev.sources : turn.sources const checks = ev.checks?.length ? ev.checks : turn.checks + const tools = Object.fromEntries( + Object.entries(turn.tools).map(([k, t]) => [k, t.status === 'running' || t.status === 'awaiting_approval' ? { ...t, status: 'cancelled' as const } : t]) + ) + const approvals = turn.approvals.map((a) => a.status === 'pending' ? { ...a, status: 'expired' as const } : a) + const settled = { ...turn, tools, approvals, messageId: ev.message_id, memorySources, sources, checks } if (ev.cancelled) { const error = turn.error?.message === 'Stopped.' ? undefined : turn.error - return { ...turn, status: 'cancelled', error, messageId: ev.message_id, memorySources, sources, checks } + return { ...settled, status: 'cancelled', error } } const hasText = turn.segments.some((s) => s.kind === 'text' && s.text.trim()) const segments = !hasText && ev.content?.trim() ? [...turn.segments, { kind: 'text' as const, text: ev.content }] : turn.segments - const tools = Object.fromEntries( - Object.entries(turn.tools).map(([k, t]) => [k, t.status === 'running' || t.status === 'awaiting_approval' ? { ...t, status: 'done' as const } : t]) - ) - return { ...turn, segments, tools, status: turn.error && !hasText && !ev.content ? 'error' : 'done', messageId: ev.message_id, memorySources, sources, checks } + return { ...settled, segments, status: turn.error && !hasText && !ev.content ? 'error' : 'done' } } default: return turn diff --git a/desktop/tests/approvalToolRows.test.ts b/desktop/tests/approvalToolRows.test.ts new file mode 100644 index 000000000..3f86ce38f --- /dev/null +++ b/desktop/tests/approvalToolRows.test.ts @@ -0,0 +1,115 @@ +import assert from 'node:assert/strict' +import { after, test } from 'node:test' +import { fileURLToPath } from 'node:url' +import { createElement } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { createServer } from 'vite' +import type { AssistantTurnView } from '../src/lib/chatFold.ts' + +// Load the real chat cards with the renderer's JSX and path alias, without starting Electron. +const vite = await createServer({ + root: fileURLToPath(new URL('../', import.meta.url)), + configFile: false, + resolve: { alias: { '@': fileURLToPath(new URL('../src', import.meta.url)) } }, + esbuild: { jsx: 'automatic' }, + server: { middlewareMode: true, ws: false, watch: null }, + appType: 'custom', + logLevel: 'error' +}) +after(() => vite.close()) + +const { applyAgentEvent, emptyTurn, foldTranscript } = await vite.ssrLoadModule('/src/lib/chatFold.ts') +const { ToolCallCard } = await vite.ssrLoadModule('/src/features/chat/ToolCallCard.tsx') +const { BrowserCard } = await vite.ssrLoadModule('/src/features/chat/cards/BrowserCard.tsx') + +const call = { call_id: 'step', session_id: 'chat', turn_id: 'turn' } +const fileArgs = { name: 'balcony-plants.txt', content: 'Water on Thursday' } +const clickArgs = { ref: 'e4' } + +function waitingTurn(name: string, args: Record, target?: string): AssistantTurnView { + const started = applyAgentEvent(emptyTurn(call.turn_id), { ...call, type: 'tool_call', name, arguments: args }) + return applyAgentEvent(started, { + ...call, + type: 'approval_request', + approval_id: 'approval', + name, + arguments: args, + risk: 'write', + reason: '', + target + }) +} + +function finishStep(turn: AssistantTurnView, result: unknown, isError = false): AssistantTurnView { + return applyAgentEvent(turn, { + ...call, + type: 'tool_result', + name: turn.tools.step.name, + result, + is_error: isError, + duration_ms: 2 + }) +} + +function fileRow(turn: AssistantTurnView): string { + return renderToStaticMarkup(createElement(ToolCallCard, { tool: turn.tools.step, approval: turn.approvals[0] })) +} + +function browserRow(turn: AssistantTurnView): string { + return renderToStaticMarkup(createElement(BrowserCard, { tools: [turn.tools.step], approvals: turn.approvals })) +} + +test('a waiting file write names the file and reports success on its result', () => { + const turn = waitingTurn('file_write', fileArgs) + const waiting = fileRow(turn) + assert.match(waiting, />Would writebalcony-plants\.txt { + const turn = waitingTurn('browser_click', clickArgs, 'Save preferences') + const waiting = browserRow(turn) + assert.match(waiting, /Would click “Save preferences”/) + assert.doesNotMatch(waiting, /Clicked/) + assert.match(browserRow(finishStep(turn, { clicked: 'Save preferences' })), /Clicked “Save preferences”/) +}) + +test('declined and failed actions have their own wording', () => { + const file = waitingTurn('file_write', fileArgs) + const click = waitingTurn('browser_click', clickArgs, 'Save preferences') + const declined = { error: 'The user declined this action.', declined: true } + const failed = { error: 'The action failed.' } + for (const [turn, render, done] of [[file, fileRow, /Wrote file/], [click, browserRow, /Clicked/]] as const) { + const declinedRow = render(finishStep(turn, declined, true)) + assert.match(declinedRow, /You declined:/) + assert.doesNotMatch(declinedRow, done) + const failedRow = render(finishStep(turn, failed, true)) + assert.match(failedRow, /Step failed/) + assert.doesNotMatch(failedRow, done) + } +}) + +test('a chat ending without a tool result leaves the step interrupted in the live chat and history', () => { + const turn = waitingTurn('file_write', fileArgs) + const click = waitingTurn('browser_click', clickArgs, 'Save preferences') + for (const cancelled of [true, false]) { + const event = { ...call, type: 'done', cancelled, content: '', message_id: null } as const + const ended = applyAgentEvent(turn, event) + assert.match(fileRow(ended), /Step interrupted/) + assert.equal(ended.approvals[0].status, 'expired') + const browser = browserRow(applyAgentEvent(click, event)) + assert.match(browser, /Step interrupted/) + assert.doesNotMatch(browser, /Clicked|Used the browser/) + } + + const [reloaded] = foldTranscript([{ + id: 'assistant', + role: 'assistant', + content: null, + created_at: '2026-11-24T00:00:00Z', + tool_calls: [{ id: call.call_id, function: { name: 'file_write', arguments: JSON.stringify(fileArgs) } }] + }]) + assert.match(fileRow(reloaded), /Step interrupted/) +}) From d22f76630f095f154499c84ea970464c77f5255a Mon Sep 17 00:00:00 2001 From: syedmustafan Date: Tue, 24 Nov 2026 11:00:24 +0500 Subject: [PATCH 2/4] fix(desktop): keep unfinished history steps pending --- desktop/src/features/chat/ToolCallCard.tsx | 2 +- .../src/features/chat/cards/CodeRunCard.tsx | 5 ++- .../src/features/chat/cards/SubagentCard.tsx | 16 +++++++--- .../src/features/chat/cards/TerminalCard.tsx | 3 +- desktop/src/features/chat/cards/bits.tsx | 3 +- desktop/src/features/chat/toolMeta.ts | 1 + desktop/src/lib/chatFold.ts | 17 +++++++--- desktop/tests/approvalToolRows.test.ts | 32 +++++++++++++++---- 8 files changed, 58 insertions(+), 21 deletions(-) diff --git a/desktop/src/features/chat/ToolCallCard.tsx b/desktop/src/features/chat/ToolCallCard.tsx index a87ea4571..032e3b0ea 100644 --- a/desktop/src/features/chat/ToolCallCard.tsx +++ b/desktop/src/features/chat/ToolCallCard.tsx @@ -114,7 +114,7 @@ function GenericToolCard({
    {failed ? 'Error' : 'Result'}
    - {running ? ( + {running || tool.status === 'awaiting_result' ? (
    Waiting for result…
    ) : !hasResult ? (
    No result
    diff --git a/desktop/src/features/chat/cards/CodeRunCard.tsx b/desktop/src/features/chat/cards/CodeRunCard.tsx index 6827dc61c..38ffb8450 100644 --- a/desktop/src/features/chat/cards/CodeRunCard.tsx +++ b/desktop/src/features/chat/cards/CodeRunCard.tsx @@ -7,6 +7,7 @@ import { wasDenied, type ToolCallView } from '@/lib/chatFold' import type { SandboxResult } from '@/lib/types' import { cn, formatDuration } from '@/lib/utils' import { fileBase, IMAGE_FILE_RE, openOutputFile, outputPath } from '../files' +import { toolStatusLabel } from '../toolMeta' import { asRecord, DeclinedText, Shimmer, StatTiles, StatusGlyph } from './bits' /** `execute_code` (§11): purpose, live output, result, created files, and the code folded away. */ @@ -40,9 +41,7 @@ export function CodeRunCard({ tool }: { tool: ToolCallView }) { ? 'Not run, so nothing changed' : failed ? `Stopped with a problem${duration ? ` after ${formatDuration(duration)}` : ''}` - : tool.status === 'cancelled' - ? 'Step interrupted' - : `Finished${duration ? ` in ${formatDuration(duration)}` : ''}` + : toolStatusLabel(tool.name, tool.status) ?? `Finished${duration ? ` in ${formatDuration(duration)}` : ''}` const backend = res?.backend const hasResult = res && res.result !== null && res.result !== undefined && res.result !== '' const showOutput = !!(stdout || stderr) diff --git a/desktop/src/features/chat/cards/SubagentCard.tsx b/desktop/src/features/chat/cards/SubagentCard.tsx index d3671f531..98eb7e51a 100644 --- a/desktop/src/features/chat/cards/SubagentCard.tsx +++ b/desktop/src/features/chat/cards/SubagentCard.tsx @@ -12,8 +12,11 @@ import { asRecord, DeclinedText, Shimmer, StatusGlyph } from './bits' export const isSubagentTool = (name: string) => name === 'delegate_task' || name === 'delegate_tasks' -function statusFromTool(tool: ToolCallView): SubagentStatus { +type HelperStatus = SubagentStatus | 'awaiting_result' + +function statusFromTool(tool: ToolCallView): HelperStatus { if (tool.status === 'running' || tool.status === 'awaiting_approval') return 'running' + if (tool.status === 'awaiting_result') return 'awaiting_result' if (tool.status === 'error') return 'error' if (tool.status === 'denied' || tool.status === 'cancelled') return 'cancelled' return 'completed' @@ -66,7 +69,7 @@ function HelperRow({ goal: string background: boolean subagentId?: string - status: SubagentStatus + status: HelperStatus summary: string | null error: string | null messages: string[] @@ -90,7 +93,9 @@ function HelperRow({ ? `Done${steps ? ` after ${steps} ${steps === 1 ? 'step' : 'steps'}` : ''}` : status === 'cancelled' ? 'Stopped' - : (sub.data?.error ?? error ?? 'Ran into a problem') + : status === 'awaiting_result' + ? 'Waiting for result' + : (sub.data?.error ?? error ?? 'Ran into a problem') return (
    @@ -168,6 +173,7 @@ function SubagentGroup({ tool }: { tool: ToolCallView }) { ? ((raw as { results: DelegateResult[] }).results) : [] const fallback = statusFromTool(tool) + const finished = fallback === 'completed' const done = list.filter((r) => r?.status === 'completed').length return (
    @@ -177,9 +183,9 @@ function SubagentGroup({ tool }: { tool: ToolCallView }) {
    - {fallback === 'running' ? {`${tasks.length} helpers working in parallel`} : `${tasks.length} helpers worked in parallel`} + {fallback === 'running' ? {`${tasks.length} helpers working in parallel`} : `${tasks.length} helpers${finished ? ' worked in parallel' : ''}`}
    - {fallback !== 'running' &&
    {done || tasks.length} finished
    } + {finished &&
    {done || tasks.length} finished
    }
    diff --git a/desktop/src/features/chat/cards/TerminalCard.tsx b/desktop/src/features/chat/cards/TerminalCard.tsx index 60b1151c6..c2daff848 100644 --- a/desktop/src/features/chat/cards/TerminalCard.tsx +++ b/desktop/src/features/chat/cards/TerminalCard.tsx @@ -7,6 +7,7 @@ import { wasDenied, type ToolCallView } from '@/lib/chatFold' import type { TerminalResult } from '@/lib/types' import { cn, formatDuration } from '@/lib/utils' import { openOutputFile } from '../files' +import { toolStatusLabel } from '../toolMeta' import { asRecord, DeclinedText, Shimmer, StatusGlyph } from './bits' /** `terminal_run` (§18): the command, its folder, live output, exit code and a Stop button while it runs. */ @@ -50,7 +51,7 @@ export function TerminalCard({ tool }: { tool: ToolCallView }) { ? 'Stopped because it took too long' : res && res.exit_code !== null ? `${res.exit_code === 0 ? 'Finished' : `Finished with exit code ${res.exit_code}`}${duration ? ` in ${formatDuration(duration)}` : ''}` - : tool.status === 'cancelled' ? 'Step interrupted' : null + : toolStatusLabel(tool.name, tool.status) return (
    diff --git a/desktop/src/features/chat/cards/bits.tsx b/desktop/src/features/chat/cards/bits.tsx index 30b77a1be..5f82c9fe3 100644 --- a/desktop/src/features/chat/cards/bits.tsx +++ b/desktop/src/features/chat/cards/bits.tsx @@ -1,4 +1,4 @@ -import { IconCheck, IconHandStop, IconShieldQuestion, IconX } from '@tabler/icons-react' +import { IconCheck, IconClockHour4, IconHandStop, IconShieldQuestion, IconX } from '@tabler/icons-react' import type { ReactNode } from 'react' import { Spinner } from '@/components/ui' import { wasUndone, type ToolCallView, type ToolStatus } from '@/lib/chatFold' @@ -83,6 +83,7 @@ export function Shimmer({ children, className }: { children: ReactNode; classNam export function StatusGlyph({ status, size = 14 }: { status: ToolStatus; size?: number }) { if (status === 'running') return if (status === 'awaiting_approval') return + if (status === 'awaiting_result') return if (status === 'error') return if (status === 'denied') return if (status === 'cancelled') return diff --git a/desktop/src/features/chat/toolMeta.ts b/desktop/src/features/chat/toolMeta.ts index c4f58989b..edbb42975 100644 --- a/desktop/src/features/chat/toolMeta.ts +++ b/desktop/src/features/chat/toolMeta.ts @@ -149,6 +149,7 @@ export function askingLabel(name: string): string | null { /** Wording for steps waiting for an answer or ending without success. */ export function toolStatusLabel(name: string, status: ToolStatus): string | undefined { if (status === 'awaiting_approval') return askingLabel(name) ?? 'Waiting for your answer' + if (status === 'awaiting_result') return 'Waiting for result' if (status === 'error') return 'Step failed' if (status === 'cancelled') return 'Step interrupted' } diff --git a/desktop/src/lib/chatFold.ts b/desktop/src/lib/chatFold.ts index 74b67a20d..cf15f7595 100644 --- a/desktop/src/lib/chatFold.ts +++ b/desktop/src/lib/chatFold.ts @@ -8,7 +8,7 @@ import type { ActionPreview, AgentEvent, AnswerSource, ApprovalDecision, ContextMeter, MemorySource, OutcomeCheck, Risk, TranscriptMessage, UsageEvent } from './types' import { safeJsonParse } from './utils' -export type ToolStatus = 'running' | 'awaiting_approval' | 'done' | 'error' | 'denied' | 'cancelled' +export type ToolStatus = 'running' | 'awaiting_approval' | 'awaiting_result' | 'done' | 'error' | 'denied' | 'cancelled' /** Live `tool_progress` accumulated per call (§10). Not persisted: history shows the final result only. */ export interface ToolProgressView { @@ -246,11 +246,20 @@ export function foldTranscript(rows: TranscriptMessage[]): TimelineItem[] { callId: tc.id, name: tc.function?.name ?? 'tool', arguments: safeJsonParse>(tc.function?.arguments, {}), - // A turn can stop after recording the call and before recording its result. - status: 'cancelled' + // The call is saved before it runs, including while its approval is still open. + status: 'awaiting_result' + } + } + if (!row.tool_calls?.length) { + turn.messageId = row.id + // The engine saves this final paragraph when a turn stops. Other assistant rows can arrive + // while a call is open, including notes from background helpers. + if (/(^|\n\n)_\(stopped\)_$/.test(row.content?.trimEnd() ?? '')) { + for (const tool of Object.values(turn.tools)) { + if (tool.status === 'awaiting_result') tool.status = 'cancelled' + } } } - if (!row.tool_calls?.length) turn.messageId = row.id if (row.memory_sources?.length) turn.memorySources = row.memory_sources if (row.sources?.length) turn.sources = row.sources if (row.checks?.length) turn.checks = row.checks diff --git a/desktop/tests/approvalToolRows.test.ts b/desktop/tests/approvalToolRows.test.ts index 3f86ce38f..6da10c763 100644 --- a/desktop/tests/approvalToolRows.test.ts +++ b/desktop/tests/approvalToolRows.test.ts @@ -5,6 +5,7 @@ import { createElement } from 'react' import { renderToStaticMarkup } from 'react-dom/server' import { createServer } from 'vite' import type { AssistantTurnView } from '../src/lib/chatFold.ts' +import type { TranscriptMessage } from '../src/lib/types.ts' // Load the real chat cards with the renderer's JSX and path alias, without starting Electron. const vite = await createServer({ @@ -25,6 +26,13 @@ const { BrowserCard } = await vite.ssrLoadModule('/src/features/chat/cards/Brows const call = { call_id: 'step', session_id: 'chat', turn_id: 'turn' } const fileArgs = { name: 'balcony-plants.txt', content: 'Water on Thursday' } const clickArgs = { ref: 'e4' } +const savedFileCall: TranscriptMessage = { + id: 'assistant', + role: 'assistant', + content: null, + created_at: '2026-11-24T00:00:00Z', + tool_calls: [{ id: call.call_id, type: 'function', function: { name: 'file_write', arguments: JSON.stringify(fileArgs) } }] +} function waitingTurn(name: string, args: Record, target?: string): AssistantTurnView { const started = applyAgentEvent(emptyTurn(call.turn_id), { ...call, type: 'tool_call', name, arguments: args }) @@ -104,12 +112,24 @@ test('a chat ending without a tool result leaves the step interrupted in the liv assert.doesNotMatch(browser, /Clicked|Used the browser/) } - const [reloaded] = foldTranscript([{ - id: 'assistant', - role: 'assistant', - content: null, - created_at: '2026-11-24T00:00:00Z', - tool_calls: [{ id: call.call_id, function: { name: 'file_write', arguments: JSON.stringify(fileArgs) } }] + const [reloaded] = foldTranscript([savedFileCall, { + id: 'stopped', role: 'assistant', content: 'Saving your note.\n\n_(stopped)_', created_at: savedFileCall.created_at }]) assert.match(fileRow(reloaded), /Step interrupted/) }) + +test('a saved file write stays pending in history until its result arrives', () => { + const helperNote: TranscriptMessage = { + id: 'helper', role: 'assistant', content: 'Your helper finished checking the forecast.', created_at: savedFileCall.created_at + } + const [pending] = foldTranscript([savedFileCall, helperNote]) + const waiting = fileRow(pending) + assert.match(waiting, /Waiting for result/) + assert.doesNotMatch(waiting, /Wrote file|Step interrupted/) + + const [done] = foldTranscript([savedFileCall, helperNote, { + id: 'result', role: 'tool', tool_call_id: call.call_id, + content: JSON.stringify({ saved: fileArgs.name }), created_at: savedFileCall.created_at + }]) + assert.match(fileRow(done), /Wrote file/) +}) From a1397f895a1538c20409b3c1faa01fbdfe6b81f3 Mon Sep 17 00:00:00 2001 From: syedmustafan Date: Tue, 24 Nov 2026 11:16:17 +0500 Subject: [PATCH 3/4] fix(chat): keep interrupted tool status in history --- desktop/src/lib/chatFold.ts | 16 +++++++++++++--- desktop/src/lib/types.ts | 4 ++-- desktop/tests/approvalToolRows.test.ts | 11 +++++++++++ docs/API.md | 8 +++++--- sentient/agent/loop.py | 24 +++++++++++++++++++++--- tests/test_turn_end.py | 26 +++++++++++++++++++++++++- 6 files changed, 77 insertions(+), 12 deletions(-) diff --git a/desktop/src/lib/chatFold.ts b/desktop/src/lib/chatFold.ts index cf15f7595..331ae4c54 100644 --- a/desktop/src/lib/chatFold.ts +++ b/desktop/src/lib/chatFold.ts @@ -200,6 +200,10 @@ export function wasDenied(result: unknown): boolean { return DECLINED_RE.test(s) || (/^(error|not done|tool error)\b/i.test(s) && /\bdeclined\b/i.test(s)) } +function interruptWaitingTool(tool: ToolCallView | undefined): void { + if (tool?.status === 'awaiting_result') tool.status = 'cancelled' +} + export function foldTranscript(rows: TranscriptMessage[]): TimelineItem[] { const items: TimelineItem[] = [] let turn: AssistantTurnView | null = null @@ -222,6 +226,14 @@ export function foldTranscript(rows: TranscriptMessage[]): TimelineItem[] { } if (row.role === 'event') { if (row.name === 'trusted') items.push({ kind: 'note', id: row.id, text: trustedNote(row.content), createdAt: row.created_at }) + if (row.name === 'turn_interrupted' && turn) { + const callIds = safeJsonParse(row.content, []) + if (Array.isArray(callIds)) { + for (const id of callIds) { + if (typeof id === 'string') interruptWaitingTool(turn.tools[id]) + } + } + } continue } if (row.role === 'user') { @@ -255,9 +267,7 @@ export function foldTranscript(rows: TranscriptMessage[]): TimelineItem[] { // The engine saves this final paragraph when a turn stops. Other assistant rows can arrive // while a call is open, including notes from background helpers. if (/(^|\n\n)_\(stopped\)_$/.test(row.content?.trimEnd() ?? '')) { - for (const tool of Object.values(turn.tools)) { - if (tool.status === 'awaiting_result') tool.status = 'cancelled' - } + Object.values(turn.tools).forEach(interruptWaitingTool) } } if (row.memory_sources?.length) turn.memorySources = row.memory_sources diff --git a/desktop/src/lib/types.ts b/desktop/src/lib/types.ts index f59618ba3..92407b8b8 100644 --- a/desktop/src/lib/types.ts +++ b/desktop/src/lib/types.ts @@ -554,8 +554,8 @@ export interface ToolCallRef { function: { name: string; arguments: string } } -/** `other`: a message someone else wrote in a paired group chat (`name` = who); `event`: something the user did to - * the chat, e.g. trusting it again (`name: "trusted"`, content JSON `{event, was, via}`), ADR 0029. */ +/** `other` is a paired group member's message. `event` carries transcript metadata such as trust changes or + * interrupted tool calls. */ export type MessageRole = 'user' | 'assistant' | 'tool' | 'system' | 'other' | 'event' /** Raw transcript row (`GET /api/sessions/{id}/messages`). */ diff --git a/desktop/tests/approvalToolRows.test.ts b/desktop/tests/approvalToolRows.test.ts index 6da10c763..dee7af095 100644 --- a/desktop/tests/approvalToolRows.test.ts +++ b/desktop/tests/approvalToolRows.test.ts @@ -133,3 +133,14 @@ test('a saved file write stays pending in history until its result arrives', () }]) assert.match(fileRow(done), /Wrote file/) }) + +test('a saved interruption marks its named tool as interrupted in history', () => { + const failure: TranscriptMessage = { + id: 'failed', role: 'event', name: 'turn_interrupted', + content: JSON.stringify([call.call_id]), created_at: savedFileCall.created_at + } + const [failed] = foldTranscript([savedFileCall, failure]) + const row = fileRow(failed) + assert.match(row, /Step interrupted/) + assert.doesNotMatch(row, /Waiting for result|Wrote file/) +}) diff --git a/docs/API.md b/docs/API.md index 05217f617..511b80b88 100644 --- a/docs/API.md +++ b/docs/API.md @@ -358,9 +358,11 @@ accept or loosen a rule. ``` The UI folds each `assistant` message with `tool_calls` plus its following `tool` messages into one assistant turn. `other` (ADR 0029): a message someone other than the owner wrote in a paired group chat, `name` = their display - name; the model reads it as outside content, the window shows it as theirs. `event`: something the user did to the - chat, never sent to the model; `name: "trusted"` with `content` JSON `{event: "trusted", was, via: "desktop"|}` is "trusted this chat again". + name; the model reads it as outside content, the window shows it as theirs. + `event` describes the chat for the window and stays outside the model history. `name: "trusted"` with `content` + JSON `{event: "trusted", was, via: "desktop"|}` is "trusted this chat again". + `name: "turn_interrupted"` carries a JSON array of unfinished call IDs when a turn ends early. The window shows + these steps as interrupted after a reload. `approval` (tool messages, #147) is how the user answered that call's approval request, `null` when it did not ask: `{decision: "allow"|"allow_session"|"allow_timed"|"allow_always"|"deny", asked_at, answered_at, target, risk_label, untrusted, rule, warning}` (a request nobody answered in time is `deny`; `rule` is the lasting rule then, e.g. diff --git a/sentient/agent/loop.py b/sentient/agent/loop.py index 8dfc39011..1728f5321 100644 --- a/sentient/agent/loop.py +++ b/sentient/agent/loop.py @@ -2042,6 +2042,15 @@ def release() -> list[str]: result = LoopResult() partial = "" + unfinished_calls: set[str] = set() + + async def save_interrupted_calls() -> None: + if unfinished_calls: + with contextlib.suppress(Exception): + await self.store.add_message( + session_id, "event", json.dumps(sorted(unfinished_calls)), name="turn_interrupted" + ) + sources = MemorySources() # what this reply had in mind (shown under it, never asked of the model) used = AnswerSources() # pages, emails, files and apps it used (#174) notes: list[dict] = [] # pieces of the user's notes put into the prompt (#354) @@ -2145,7 +2154,11 @@ def release() -> list[str]: tool_names = None async def persist(role_: str, content: str | None, **fields: Any) -> None: + if role_ == "assistant": + unfinished_calls.update(call["id"] for call in fields.get("tool_calls") or ()) mid = await self.store.add_message(session_id, role_, content, **fields) + if role_ == "tool": + unfinished_calls.discard(fields["tool_call_id"]) if role_ == "user" and content: # a steer message can be a standing instruction too (#130) check = None if channel == "mcp" else self._start_rule_check(session_id, mid, content) if check is not None: @@ -2180,6 +2193,7 @@ async def persist(role_: str, content: str | None, **fields: Any) -> None: (json.dumps(sorted(ctx.visited)), session_id), ) yield event + await save_interrupted_calls() except (asyncio.CancelledError, GeneratorExit): release() # the user pressed Stop (or the window went away): keep what was shown @@ -2194,9 +2208,13 @@ async def persist(role_: str, content: str | None, **fields: Any) -> None: on_stopped(save.result()) self._turn_done(session_id) raise - except BaseException: - release() - self._turn_done(session_id) + except BaseException as exc: + try: + if isinstance(exc, Exception): + await save_interrupted_calls() + finally: + release() + self._turn_done(session_id) raise leftover = release() diff --git a/tests/test_turn_end.py b/tests/test_turn_end.py index 2a9aec843..cd455931f 100644 --- a/tests/test_turn_end.py +++ b/tests/test_turn_end.py @@ -11,7 +11,7 @@ from sentient.gateway.app import create_app from sentient.llm.events import Done, Error from sentient.llm.provider import ProviderError, StreamChunk -from tests.conftest import FakeProvider +from tests.conftest import FakeProvider, tool_call FAILURE = "Can't reach the model at localhost:9. Check that it is running, or pick another model." @@ -129,6 +129,30 @@ async def broken(*args, **kwargs): assert terminal(lines) == ["error", "done"] and lines[-1]["error"] == "the store went away" +def test_a_failed_approval_records_which_tool_was_interrupted(config, make_client, monkeypatch): + config.tools.approvals.rules["file_write"] = "ask" + client = make_client(FakeProvider([[ + tool_call("current_datetime"), + tool_call("file_write", name="garden-note.txt", content="Water on Thursday"), + ]])) + + async def failed_notification(*args, **kwargs): + raise RuntimeError("could not post the approval") + + monkeypatch.setattr(client.core, "notify", failed_notification) + response = client.post("/api/chat", json={"text": "Check the time and write garden-note.txt", "channel": "api"}) + events = [json.loads(line) for line in response.text.splitlines()] + assert terminal(events) == ["error", "done"] + assert events[-1]["error"] == "could not post the approval" + assert [e["name"] for e in events if e["type"] == "tool_result"] == ["current_datetime"] + + session_id = events[0]["session_id"] + history = client.get(f"/api/sessions/{session_id}/messages").json() + assert history[-1]["role"] == "event" + assert history[-1]["name"] == "turn_interrupted" + assert json.loads(history[-1]["content"]) == ["call_file_write"] + + def test_a_break_after_done_sends_no_second_done(make_client, monkeypatch): client = make_client(FakeProvider()) From 8103014cefc5c8833ef35c59bc4c592db0a4fe2b Mon Sep 17 00:00:00 2001 From: syedmustafan Date: Tue, 24 Nov 2026 11:34:09 +0500 Subject: [PATCH 4/4] fix(chat): match interrupted tools across group messages --- desktop/src/lib/chatFold.ts | 9 ++++++-- desktop/tests/approvalToolRows.test.ts | 31 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/desktop/src/lib/chatFold.ts b/desktop/src/lib/chatFold.ts index 331ae4c54..03c07b263 100644 --- a/desktop/src/lib/chatFold.ts +++ b/desktop/src/lib/chatFold.ts @@ -226,11 +226,16 @@ export function foldTranscript(rows: TranscriptMessage[]): TimelineItem[] { } if (row.role === 'event') { if (row.name === 'trusted') items.push({ kind: 'note', id: row.id, text: trustedNote(row.content), createdAt: row.created_at }) - if (row.name === 'turn_interrupted' && turn) { + if (row.name === 'turn_interrupted') { const callIds = safeJsonParse(row.content, []) if (Array.isArray(callIds)) { for (const id of callIds) { - if (typeof id === 'string') interruptWaitingTool(turn.tools[id]) + if (typeof id !== 'string') continue + // A group message can split the timeline while an earlier tool is still open. + const owner = items.findLast( + (item): item is AssistantTurnView => item.kind === 'assistant' && Object.hasOwn(item.tools, id) + ) + interruptWaitingTool(owner?.tools[id]) } } } diff --git a/desktop/tests/approvalToolRows.test.ts b/desktop/tests/approvalToolRows.test.ts index dee7af095..7fa1e526b 100644 --- a/desktop/tests/approvalToolRows.test.ts +++ b/desktop/tests/approvalToolRows.test.ts @@ -144,3 +144,34 @@ test('a saved interruption marks its named tool as interrupted in history', () = assert.match(row, /Step interrupted/) assert.doesNotMatch(row, /Waiting for result|Wrote file/) }) + +test('a group message does not hide which earlier tool was interrupted', () => { + const createdAt = savedFileCall.created_at + const history: TranscriptMessage[] = [{ + ...savedFileCall, + tool_calls: [ + { id: 'lookup', type: 'function', function: { name: 'current_datetime', arguments: '{}' } }, + ...(savedFileCall.tool_calls ?? []) + ] + }, { + id: 'time', role: 'tool', tool_call_id: 'lookup', content: '"9:00 AM"', created_at: createdAt + }, { + id: 'group-message', role: 'other', name: 'Priya', content: 'I watered the plants.', created_at: createdAt + }] + const newerCall: TranscriptMessage = { + ...savedFileCall, id: 'new-activity', + tool_calls: [{ id: 'next', type: 'function', function: { name: 'file_read', arguments: '{"name":"weather.txt"}' } }] + } + const interruption: TranscriptMessage = { + id: 'interrupted', role: 'event', name: 'turn_interrupted', + content: JSON.stringify([call.call_id]), created_at: createdAt + } + + for (const newerRows of [[], [newerCall]]) { + const [earlier, groupMessage, newer] = foldTranscript([...history, ...newerRows, interruption]) + assert.match(fileRow(earlier), /Step interrupted/) + assert.equal(earlier.tools.lookup.status, 'done') + assert.equal(groupMessage.kind, 'other') + if (newer) assert.equal(newer.tools.next.status, 'awaiting_result') + } +})