From 03d4a03c844737d65504730c029d07d2d84d8472 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Fri, 20 Nov 2026 01:04:24 +0900 Subject: [PATCH] Show live background job status in Claude tool rows --- docs/CLI.md | 1 + src/renderer/components/chat/claude-tab.tsx | 10 ++- src/renderer/components/chat/message-list.tsx | 61 ++++++++++++++----- .../components/chat/running-section.tsx | 11 +--- src/renderer/components/chat/tool-row.tsx | 40 ++++++++++-- src/renderer/services/chat/item-view.ts | 9 +++ src/renderer/services/chat/panel.ts | 5 +- src/renderer/services/chat/running.ts | 40 +++++++++++- src/renderer/services/chat/tool-runs.ts | 11 +++- .../renderer/services/chat/item-view.test.ts | 37 ++++++++++- 10 files changed, 186 insertions(+), 39 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 899a0491d..181df8873 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -146,6 +146,7 @@ nexus chat resume 5f2a # 지난 대화 이어 - `chat answer` 는 터미널에서 도는 Claude Code 의 요청에도 답합니다(앱의 요청 카드와 같음). `--stop` 은 거절하면서 턴도 멈춥니다. - `chat interrupt` 는 탭의 멈춤 버튼과 같습니다. 대기열의 메시지는 그대로 남습니다. - `chat panel` 은 탭 옆 패널의 내용입니다: 목표, 할 일, 작업(백그라운드 실행, `chat stop-task` 가 받는 id), 서브에이전트, 바뀐 파일, 컨텍스트 · 비용 · 플랜 사용량, MCP 서버, 원격 제어, 보류 메시지. 로그인한 계정은 보이지 않습니다. +- 작업 패널의 백그라운드 명령은 현재 실행에서 수집하며, 앱을 재시작하면 대화 기록에서 복원되지 않습니다. - `chat unsend <탭> ` 는 보류 메시지를 id 로 회수하고 그 내용을 출력합니다. 번호를 주면 턴 중에 보내 아직 읽지 않은 메시지(`chat read` 에 `(unread)` 로 표시)를 회수합니다(Claude 탭만). 이미 읽었으면 종료 코드 1 입니다. - `chat rewind <탭> <번호>` 는 되감기 버튼과 같습니다. 그 메시지 전으로 대화를, `--files` 면 그 뒤 Claude 가 바꾼 파일도 되돌립니다. `--preview` 는 되돌릴 파일만 보여줍니다. 턴 중에는 안 되고, 사용자에게 매번 묻습니다(Claude 탭만). - `chat fork <탭> [번호]` 는 대화를 새 탭(뒤쪽)으로 복사합니다. 번호가 없으면 전부, 답변 번호면 그 답변까지, 메시지 번호면 그 메시지 전까지입니다. 메시지에서 갈라내면 그 메시지는 보내지 않고 출력합니다(Claude 탭만). diff --git a/src/renderer/components/chat/claude-tab.tsx b/src/renderer/components/chat/claude-tab.tsx index e21217488..a537038c9 100644 --- a/src/renderer/components/chat/claude-tab.tsx +++ b/src/renderer/components/chat/claude-tab.tsx @@ -58,6 +58,7 @@ import { } from "../../services/chat/print-runs"; import { withRelayed } from "../../services/chat/relayed"; import { revertChangedFile } from "../../services/chat/revert-file"; +import { jobToolStatuses } from "../../services/chat/running"; import { type ChatTabState, type ComposerDraft, @@ -397,10 +398,14 @@ export function ClaudeTabView({ workspaceId, tabId, props, isVisible }: ClaudeTa }, [isVisible]); // The previews may read what the tab links outside the workspace, while it is open. const [looked, setLooked] = useState([]); - // Taken from the parts it reads, so a line that changes none of them (a - // usage report, a turn's end) does not walk the whole session again. const history = state.history; const { items: liveItems, tools: liveTools, tasks } = state.model; + const toolStatuses = useMemo( + () => jobToolStatuses({ tasks, tools: liveTools, running }), + [tasks, liveTools, running], + ); + // Taken from the parts it reads, so a line that changes none of them (a + // usage report, a turn's end) does not walk the whole session again. const outside = useMemo(() => { const items = history ? [...history.items, ...liveItems] : liveItems; const tools = history ? { ...history.tools, ...liveTools } : liveTools; @@ -681,6 +686,7 @@ export function ClaudeTabView({ workspaceId, tabId, props, isVisible }: ClaudeTa rootPath={rootPath} history={pastModel} model={state.model} + toolStatuses={toolStatuses} actions={shown ? undefined : actions} items={shownTranscript} reveal={shown ? null : callAsk} diff --git a/src/renderer/components/chat/message-list.tsx b/src/renderer/components/chat/message-list.tsx index d46e948cf..ae8b71baf 100644 --- a/src/renderer/components/chat/message-list.tsx +++ b/src/renderer/components/chat/message-list.tsx @@ -72,6 +72,7 @@ import { } from "../../services/chat/panel"; import { followsMessage } from "../../services/chat/profile-moves"; import { RELAY_KINDS, withRelayed } from "../../services/chat/relayed"; +import type { ToolRowStatuses } from "../../services/chat/running"; import { isOwnScroll, nearBottom, scrolledDown } from "../../services/chat/stick-to-bottom"; import { foldToolRuns, tallyRun } from "../../services/chat/tool-runs"; import { showPeerSession } from "../../services/remote/show-peer"; @@ -98,6 +99,8 @@ import { AnsweredQuestions, PlanOutcome, showsAsPrompt } from "./prompt-rows"; import { SentFiles } from "./sent-files"; import { ToolRow } from "./tool-row"; +const NO_TOOL_STATUSES: ToolRowStatuses = {}; + interface MessageListProps { workspaceId: string; /** The tab the conversation is, if it is one. */ @@ -106,6 +109,7 @@ interface MessageListProps { rootPath: string; history: ChatModel | null; model: ChatModel; + toolStatuses?: ToolRowStatuses; /** Shown when there is no message yet. */ empty?: React.ReactNode; actions?: MessageActions; @@ -219,6 +223,7 @@ export function MessageList({ rootPath, history, model, + toolStatuses = NO_TOOL_STATUSES, empty, actions, items, @@ -495,14 +500,22 @@ export function MessageList({ ); const under = useMemo(() => callsUnder(tools), [tools]); const views = useMemo(() => { - const sources = { tools, callsUnder: under, shown, extras, earlier, asked: shownCall }; + const sources = { + tools, + toolStatuses, + callsUnder: under, + shown, + extras, + earlier, + asked: shownCall, + }; const out = new Map(); for (const item of windowItems) { const view = itemView(item, sources); if (view) out.set(item, view); } return out; - }, [windowItems, tools, under, shown, extras, earlier, shownCall]); + }, [windowItems, tools, toolStatuses, under, shown, extras, earlier, shownCall]); const list = (
@@ -558,6 +571,7 @@ export function MessageList({ streaming={streaming} ctx={ctx} tools={tools} + toolStatuses={toolStatuses} shownEarlier={earlier.inLastTurn} /> )} @@ -614,7 +628,14 @@ const Item = memo(function Item({ item, ctx, view }: ItemProps) { ); case "notice": @@ -1064,6 +1085,7 @@ function AssistantMessage({ toolUseId={block.toolUseId} ctx={ctx} tools={view.tools} + toolStatuses={view.toolStatuses} shownEarlier={view.earlier.get(block.toolUseId)} /> ), @@ -1100,10 +1122,6 @@ function runKey(blocks: AssistantBlock[]): string { return first?.type === "tool" ? first.toolUseId : ""; } -function isLive(tool: ToolCall | undefined): boolean { - return !tool || tool.status === "running" || tool.status === "streaming"; -} - /** The kinds of call a run's line counts, in its order. */ const RUN_KINDS = ["commands", "reads", "edits", "searches", "others"] as const; @@ -1123,7 +1141,7 @@ function ToolRun({ }) { const { t } = useTranslation(); const [open, setOpen] = useState(false); - const { tools } = view; + const { tools, toolStatuses } = view; // Opens when the side panel asks to see a call of the run's. const asked = view.asked; // biome-ignore lint/correctness/useExhaustiveDependencies: each ask once; a call joining the run later does not open it again @@ -1133,14 +1151,17 @@ function ToolRun({ } }, [asked]); const calls = blocks.flatMap((block) => (block.type === "tool" ? [tools[block.toolUseId]] : [])); - const running = calls.some(isLive); - const tally = tallyRun(calls); + const live = blocks.filter((block) => { + if (block.type !== "tool") return false; + const status = toolStatuses[block.toolUseId] ?? tools[block.toolUseId]?.status; + return !status || status === "running" || status === "streaming" || status === "background"; + }); + const running = live.length > 0; + const tally = tallyRun(calls, toolStatuses); const label = RUN_KINDS.filter((kind) => tally[kind] > 0) .map((kind) => t(`chat.tool.run.${kind}`, { count: tally[kind] })) .join(" · "); - const rows = open - ? blocks - : blocks.filter((block) => block.type === "tool" && isLive(tools[block.toolUseId])); + const rows = open ? blocks : live; return (
@@ -1191,6 +1212,7 @@ function ToolRun({ toolUseId={block.toolUseId} tool={tools[block.toolUseId]} tools={tools} + toolStatuses={toolStatuses} cwd={ctx.cwd} onBackground={backgroundOf(ctx.actions, block.toolUseId)} /> @@ -1210,12 +1232,14 @@ function CallRow({ toolUseId, ctx, tools, + toolStatuses, shownEarlier, }: { toolUseId: string; ctx: ItemContext; /** Its call and the calls it runs, by id; more is fine. */ tools: Readonly>; + toolStatuses: ToolRowStatuses; /** The image files it sends that its turn showed before. */ shownEarlier?: ReadonlySet; }) { @@ -1254,6 +1278,7 @@ function CallRow({ toolUseId={toolUseId} tool={tool} tools={tools} + toolStatuses={toolStatuses} cwd={ctx.cwd} onBackground={backgroundOf(ctx.actions, toolUseId)} /> @@ -1302,11 +1327,13 @@ function Streaming({ streaming, ctx, tools, + toolStatuses, shownEarlier, }: { streaming: StreamingMessage; ctx: ItemContext; tools: Record; + toolStatuses: ToolRowStatuses; /** What the last turn shows in full so far, which it shows as chips. */ shownEarlier: ReadonlySet; }) { @@ -1329,7 +1356,13 @@ function Streaming({ ) : block.type === "thinking" ? ( ) : block.toolUseId ? ( - + ) : null, )}
diff --git a/src/renderer/components/chat/running-section.tsx b/src/renderer/components/chat/running-section.tsx index c61e4a68d..83d2f8e57 100644 --- a/src/renderer/components/chat/running-section.tsx +++ b/src/renderer/components/chat/running-section.tsx @@ -42,7 +42,7 @@ import { IconButton } from "../ui/icon-button"; import { SearchInput } from "../ui/search-input"; import { relativeTime } from "./message-list"; import { FirstFew, Row, Section, useFold, useRevealedRow } from "./panel-section"; -import { BackgroundIcon } from "./tool-row"; +import { BackgroundBadge, BackgroundIcon } from "./tool-row"; /** How many ended rows show before the rest is asked for. */ export const ENDED_FIRST = 5; @@ -405,14 +405,7 @@ const RunningRow = memo(function RunningRow({ {row.description} - {row.background && ( - - {t("chat.panel.running.background")} - - )} + {row.background && } {foreground && onBackground && ( ; + toolStatuses: ToolRowStatuses; cwd: string; /** Sends a running command or subagent to the background, as Ctrl+B does in the terminal. */ onBackground?: (toolUseId: string) => void; @@ -51,21 +56,35 @@ export function toolTint(name: string): string { */ export const BackgroundIcon = Layers2; +/** The label for a job running beside the turn, in the conversation and the panel. */ +export function BackgroundBadge({ testId }: { testId?: string }) { + const { t } = useTranslation(); + return ( + + {t("chat.panel.running.background")} + + ); +} + /** Longest output an open row shows; the rest is cut. */ const MAX_OUTPUT_CHARS = 20_000; -export function ToolRow({ tool, toolUseId, tools, cwd, onBackground }: ToolRowProps) { +export function ToolRow({ tool, toolUseId, tools, toolStatuses, cwd, onBackground }: ToolRowProps) { const { t } = useTranslation(); const [open, setOpen] = useState(false); const name = tool?.displayName || tool?.name || "tool"; const summary = tool ? toolSummary(tool, cwd) : ""; - const status = tool?.status ?? "running"; + const jobStatus = toolStatuses[toolUseId]; + const status = jobStatus ?? tool?.status ?? "running"; const unsandboxed = tool ? isUnsandboxed(tool.input) : false; const children = tool && AGENT_TOOLS.has(tool.name) ? Object.values(tools).filter((t) => t.parentToolUseId === toolUseId) : []; - const backgroundable = onBackground && tool && canBackground(tool); + const backgroundable = onBackground && tool && jobStatus === undefined && canBackground(tool); return (
@@ -88,6 +107,7 @@ export function ToolRow({ tool, toolUseId, tools, cwd, onBackground }: ToolRowPr {t("chat.tool.unsandboxed")} )} + {status === "background" && } {status === "denied" && ( {t("chat.tool.denied")} )} @@ -122,7 +142,14 @@ export function ToolRow({ tool, toolUseId, tools, cwd, onBackground }: ToolRowPr {open && children.length > 0 && (
{children.map((child) => ( - + ))}
)} @@ -143,11 +170,12 @@ export function isUnsandboxed(input: unknown): boolean { ); } -function StatusIcon({ status }: { status: ToolCall["status"] }) { +function StatusIcon({ status }: { status: ToolRowStatus }) { const cls = "size-3.5 shrink-0"; switch (status) { case "streaming": case "running": + case "background": return ( ); diff --git a/src/renderer/services/chat/item-view.ts b/src/renderer/services/chat/item-view.ts index 75c6ff6d1..b5c957cd8 100644 --- a/src/renderer/services/chat/item-view.ts +++ b/src/renderer/services/chat/item-view.ts @@ -13,6 +13,7 @@ */ import type { AssistantBlock, AssistantItem, ChatItem, ToolCall } from "./model"; import type { AnswerExtras, ImagesShownEarlier } from "./panel"; +import type { ToolRowStatus, ToolRowStatuses } from "./running"; import type { ShownBlock } from "./tool-runs"; /** A message's part of its list's sources. */ @@ -21,6 +22,8 @@ export interface ItemView { blocks: readonly ShownBlock[]; /** Its calls and the calls they run (a subagent's), by id. */ tools: Readonly>; + /** Statuses supplied by background jobs for these calls. */ + toolStatuses: ToolRowStatuses; /** What its answer ends with. */ extras?: AnswerExtras; /** By part, the image files it shows that its turn showed before. */ @@ -32,6 +35,7 @@ export interface ItemView { /** What a list renders its messages from. */ export interface ListSources { tools: Record; + toolStatuses: ToolRowStatuses; /** By a call's id, the calls it runs (callsUnder). */ callsUnder: ReadonlyMap; shown: ReadonlyMap; @@ -60,12 +64,15 @@ export function itemView(item: ChatItem, sources: ListSources): ItemView | undef if (item.kind !== "assistant") return undefined; const blocks = sources.shown.get(item) ?? item.blocks; const tools: Record = {}; + const toolStatuses: Partial> = {}; const taken = new Set(); const take = (id: string) => { if (taken.has(id)) return; taken.add(id); const tool = sources.tools[id]; if (tool) tools[id] = tool; + const status = sources.toolStatuses[id]; + if (status) toolStatuses[id] = status; for (const call of sources.callsUnder.get(id) ?? []) take(call.id); }; const earlier = new Map>(); @@ -91,6 +98,7 @@ export function itemView(item: ChatItem, sources: ListSources): ItemView | undef return { blocks, tools, + toolStatuses, earlier: earlier.size > 0 ? earlier : NO_EARLIER, ...(extras ? { extras } : {}), ...(asked ? { asked } : {}), @@ -105,6 +113,7 @@ export function sameView(a: ItemView | undefined, b: ItemView | undefined): bool a.asked === b.asked && sameBlocks(a.blocks, b.blocks) && sameRecord(a.tools, b.tools) && + sameRecord(a.toolStatuses, b.toolStatuses) && sameExtras(a.extras, b.extras) && sameEarlier(a.earlier, b.earlier) ); diff --git a/src/renderer/services/chat/panel.ts b/src/renderer/services/chat/panel.ts index d59a048bd..5ddb0693d 100644 --- a/src/renderer/services/chat/panel.ts +++ b/src/renderer/services/chat/panel.ts @@ -250,7 +250,10 @@ export function agentTranscript(model: Pick, agent: Age return [...prompt, ...(model.agentItems[agent.toolUseId] ?? [])]; } -/** Background Bash runs, workflows and the like: the tasks that are not agents. */ +/** + * Background Bash runs, workflows and the like: the tasks that are not agents. + * Background commands come from the current run's live model and are not restored from history. + */ export function jobsOf(model: Pick): TaskInfo[] { return Object.values(model.tasks).filter((task) => !AGENT_TASK_TYPES.has(task.type)); } diff --git a/src/renderer/services/chat/running.ts b/src/renderer/services/chat/running.ts index 4db7b5785..7602ab40d 100644 --- a/src/renderer/services/chat/running.ts +++ b/src/renderer/services/chat/running.ts @@ -3,8 +3,8 @@ // subagents and the `claude -p` runs it started), and below, folded, what // ended, newest first. -import type { ChatItem, ToolCall } from "./model"; -import { AGENT_TOOLS, type AgentRow, type AgentStatus } from "./panel"; +import type { ChatItem, ChatModel, ToolCall } from "./model"; +import { AGENT_TOOLS, type AgentRow, type AgentStatus, jobsOf } from "./panel"; /** A background job as the panel takes it: a task of the tab's, or as another computer tells one. */ export interface JobLike { @@ -15,6 +15,7 @@ export interface JobLike { /** running, then completed, failed, killed or stopped. */ status: string; toolUseId?: string; + backgrounded?: boolean; startedAt?: number; endedAt?: number; summary?: string; @@ -72,6 +73,38 @@ export function jobStatus(status: string): AgentStatus { } } +/** The CLI can confirm the handoff before the foreground call returns. */ +function waitsForJob(job: JobLike, waitsForCall: boolean): boolean { + return waitsForCall && job.backgrounded !== true; +} + +export type ToolRowStatus = ToolCall["status"] | "background"; +export type ToolRowStatuses = Readonly>>; + +const JOB_TOOL_STATUS = { + running: "background", + completed: "done", + failed: "error", + stopped: "stopped", +} as const; + +/** A handed-off call's row follows the job once the CLI starts tracking it. */ +export function jobToolStatuses({ + tasks, + tools, + running, +}: Pick): ToolRowStatuses { + const statuses: Partial> = {}; + for (const job of jobsOf({ tasks })) { + const id = job.toolUseId; + const tool = id ? tools[id] : undefined; + if (!id || !tool || tool.status === "denied") continue; + if (waitsForJob(job, running && canBackground(tool))) continue; + statuses[id] = JOB_TOOL_STATUS[jobStatus(job.status)]; + } + return statuses; +} + function str(value: unknown): string | undefined { return typeof value === "string" ? value : undefined; } @@ -158,7 +191,8 @@ export function activityOf({ const status = jobStatus(job.status); const running = status === "running"; // A command just sent to the background is the job its call started. - const isWaited = running && job.toolUseId !== undefined && waited.has(job.toolUseId); + const isWaited = + running && waitsForJob(job, job.toolUseId !== undefined && waited.has(job.toolUseId)); rows.push({ key: `job:${job.taskId}`, kind: "command", diff --git a/src/renderer/services/chat/tool-runs.ts b/src/renderer/services/chat/tool-runs.ts index b5e5e27f7..3b061d86f 100644 --- a/src/renderer/services/chat/tool-runs.ts +++ b/src/renderer/services/chat/tool-runs.ts @@ -4,6 +4,7 @@ import { ARTIFACT_TOOL } from "./artifact"; import type { AssistantBlock, AssistantItem, ChatItem, ToolCall } from "./model"; import { AGENT_TOOLS, SEND_FILES_TOOL } from "./panel"; +import type { ToolRowStatuses } from "./running"; /** * Calls that keep a line of their own: a subagent's, those that ask the @@ -95,7 +96,10 @@ export interface RunTally { denied: number; } -export function tallyRun(calls: readonly (ToolCall | undefined)[]): RunTally { +export function tallyRun( + calls: readonly (ToolCall | undefined)[], + toolStatuses: ToolRowStatuses, +): RunTally { const tally: RunTally = { commands: 0, reads: 0, @@ -108,8 +112,9 @@ export function tallyRun(calls: readonly (ToolCall | undefined)[]): RunTally { const read = new Set(); const edited = new Set(); for (const call of calls) { - if (call?.status === "error") tally.failed++; - if (call?.status === "denied") tally.denied++; + const status = call && (toolStatuses[call.id] ?? call.status); + if (status === "error") tally.failed++; + if (status === "denied") tally.denied++; const name = call?.name ?? ""; const input = (call?.input ?? {}) as Record; const path = [input.file_path, input.notebook_path].find( diff --git a/tests/unit/renderer/services/chat/item-view.test.ts b/tests/unit/renderer/services/chat/item-view.test.ts index c550ae62b..2549f8ead 100644 --- a/tests/unit/renderer/services/chat/item-view.test.ts +++ b/tests/unit/renderer/services/chat/item-view.test.ts @@ -17,6 +17,7 @@ import type { ToolCall, } from "../../../../../src/renderer/services/chat/model"; import type { AnswerExtras } from "../../../../../src/renderer/services/chat/panel"; +import { jobToolStatuses } from "../../../../../src/renderer/services/chat/running"; import { foldToolRuns } from "../../../../../src/renderer/services/chat/tool-runs"; const call = (id: string, extra: Partial = {}): ToolCall => @@ -48,6 +49,7 @@ function sources( ): ListSources { return { tools, + toolStatuses: {}, callsUnder: callsUnder(tools), shown: foldToolRuns(items, tools), extras: new Map(), @@ -73,6 +75,34 @@ describe("itemView", () => { expect(rendersAgain(b, sources(items, tools), sources(items, next))).toBe(true); }); + test.each([ + ["running", "background"], + ["completed", "done"], + ["failed", "error"], + ])("a background job that is %s gives its tool row %s", (status, expected) => { + const calls = { ...tools, c2: call("c2", { status: "done" }) }; + const job = { + taskId: "bash-job", + type: "local_bash", + description: "Build", + toolUseId: "c2", + backgrounded: true, + }; + const withJob = (jobStatus: string) => + sources(items, calls, { + toolStatuses: jobToolStatuses({ + tasks: { [job.taskId]: { ...job, status: jobStatus } }, + tools: calls, + running: false, + }), + }); + const before = status === "running" ? sources(items, calls) : withJob("running"); + const after = withJob(status); + expect(itemView(b, after)?.toolStatuses).toEqual({ c2: expected }); + expect(rendersAgain(b, before, after)).toBe(true); + expect(rendersAgain(a, before, after)).toBe(false); + }); + test("a call under its subagent's call changing renders it again", () => { const agent = { ...tools, c1: call("c1", { name: "Agent" }) }; const sub = { ...agent, s1: call("s1", { parentToolUseId: "c1" }) }; @@ -163,7 +193,12 @@ describe("itemView", () => { describe("sameView", () => { test("its own blocks changing renders it again", () => { - const view: ItemView = { blocks: [{ type: "text", text: "a" }], tools: {}, earlier: new Map() }; + const view: ItemView = { + blocks: [{ type: "text", text: "a" }], + tools: {}, + toolStatuses: {}, + earlier: new Map(), + }; expect(sameView(view, { ...view })).toBe(true); expect(sameView(view, { ...view, blocks: [{ type: "text", text: "a" }] })).toBe(false); });