diff --git a/desktop/src/features/chat/cards/TerminalCard.tsx b/desktop/src/features/chat/cards/TerminalCard.tsx
index 956cfd17b..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)}` : ''}`
- : 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 41c8070cf..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'
@@ -80,9 +80,10 @@ 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 === '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 c53ef6bf4..edbb42975 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,14 @@ 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 === 'awaiting_result') return 'Waiting for result'
+ 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..03c07b263 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' | 'awaiting_result' | 'done' | 'error' | 'denied' | 'cancelled'
/** Live `tool_progress` accumulated per call (§10). Not persisted: history shows the final result only. */
export interface ToolProgressView {
@@ -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,19 @@ 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') {
+ const callIds = safeJsonParse(row.content, [])
+ if (Array.isArray(callIds)) {
+ for (const id of callIds) {
+ 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])
+ }
+ }
+ }
continue
}
if (row.role === 'user') {
@@ -246,10 +263,18 @@ export function foldTranscript(rows: TranscriptMessage[]): TimelineItem[] {
callId: tc.id,
name: tc.function?.name ?? 'tool',
arguments: safeJsonParse>(tc.function?.arguments, {}),
- status: 'done'
+ // 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() ?? '')) {
+ Object.values(turn.tools).forEach(interruptWaitingTool)
}
}
- 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
@@ -403,16 +428,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/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
new file mode 100644
index 000000000..7fa1e526b
--- /dev/null
+++ b/desktop/tests/approvalToolRows.test.ts
@@ -0,0 +1,177 @@
+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'
+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({
+ 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' }
+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 })
+ 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 write)
+ assert.match(waiting, />balcony-plants\.txt)
+ assert.doesNotMatch(waiting, /Wrote file/)
+ assert.match(fileRow(finishStep(turn, { saved: fileArgs.name })), /Wrote file/)
+})
+
+test('a waiting browser click names the target and reports success on its result', () => {
+ 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([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/)
+})
+
+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/)
+})
+
+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')
+ }
+})
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())