diff --git a/src/renderer/services/chat/codex/controller.ts b/src/renderer/services/chat/codex/controller.ts index 4c7d68896..9ac4c9d40 100644 --- a/src/renderer/services/chat/codex/controller.ts +++ b/src/renderer/services/chat/codex/controller.ts @@ -2099,14 +2099,18 @@ export class CodexController { | { threadId?: string; item?: { type?: string; agentThreadId?: unknown; receiverThreadIds?: unknown }; + status?: { type?: unknown }; } | undefined; const from = params?.threadId; if (from && from === this.model.threadId && method === "turn/completed") { invalidateCodexHistory(this.target.workspaceId); } + const childBecameIdle = + method === "thread/statusChanged" && + (params?.status?.type === "idle" || params?.status?.type === "systemError"); if ( - (method === "item/completed" || method === "turn/completed") && + (method === "item/completed" || method === "turn/completed" || childBecameIdle) && from && this.model.tasks[from]?.type === "codex_subagent" ) { diff --git a/src/renderer/services/chat/codex/model.ts b/src/renderer/services/chat/codex/model.ts index 94fb9e4a0..6c78ed1ed 100644 --- a/src/renderer/services/chat/codex/model.ts +++ b/src/renderer/services/chat/codex/model.ts @@ -38,6 +38,7 @@ import { type ToolCall, type UserItem, } from "../model"; +import { commandLabel, WAITED_CALL_DELAY_MS } from "../running"; import { type CodexCollaborationMode, type CodexCollaborationSettings, @@ -88,6 +89,13 @@ export interface CodexServerRequest { params: Rec; } +/** A live command and whether its process can outlast the turn that started it. */ +interface LiveCommand { + turnId: string; + startedAt?: number; + canContinue: boolean; +} + export interface CodexModel extends ChatModel { /** Keeps sequence-based item keys unique across the tab's agent logs. */ logSeqOffset?: number; @@ -103,6 +111,8 @@ export interface CodexModel extends ChatModel { turnId?: string; /** Log sequence of the current turn's last tool completion. */ toolCompletedSeq?: number; + /** Commands observed starting in the live log, until their lifecycle settles. */ + liveCommands?: Record; /** What the program is signed in with (its kind only); null when it is not. */ account?: { type: string } | null; /** The program needs a sign-in before a turn can run. */ @@ -167,6 +177,7 @@ export function loseCodexLog(prev: CodexModel): CodexModel { mcpServers: undefined, mcpLogin: undefined, }); + settleCommands(draft, undefined); stopRunningTools(draft); stopRunningTasks(draft, undefined); return draft.next; @@ -255,6 +266,7 @@ export function applyCodexLine( draft.next.originals = { ...draft.next.originals, [path]: before }; } } else if (line.dir === "sys") { + if (message.event === "exit" || message.event === "start") settleCommands(draft, at); applySys(draft, message, keySeq, at); if (message.event === "start") draft.next.canonicalCwd = str(message.canonicalCwd); if (message.event === "start" || message.event === "exit") { @@ -440,7 +452,7 @@ function applyResponse( const child = rec(raw); const id = str(child?.id); if (child && id && id !== m.threadId && parentThreadOf(child) === m.threadId) { - applyNativeAgent(m, id, child); + applyNativeAgent(m, id, child, undefined, undefined, at); } } } @@ -455,7 +467,7 @@ function applyResponse( sent.request.includeTurns === true && m.tasks[id]?.type === "codex_subagent" ) { - applyNativeAgent(m, id, thread); + applyNativeAgent(m, id, thread, undefined, undefined, at); applyAgentTranscript(draft, id, thread, seq); } else if ( sent.request.includeTurns === false && @@ -603,17 +615,70 @@ function parentThreadOf(thread: Rec): string | undefined { return str(thread.parentThreadId) ?? str(spawn?.parent_thread_id); } +/** Translates a child turn's outcome without treating a still-active turn as ended. */ +function nativeTurnEnd(status: unknown): string | undefined { + switch (status) { + case "completed": + case "failed": + return status; + case "interrupted": + return "stopped"; + } +} + +/** Updates a known child from its own thread and turn events. */ +function applyNativeAgentNotification( + m: CodexModel, + id: string, + method: string, + params: Rec, + at: number | undefined, +): void { + const task = m.tasks[id]; + if (task?.type !== "codex_subagent") return; + let status: string | undefined; + switch (method) { + case "thread/statusChanged": + if (!["active", "idle", "systemError"].includes(String(rec(params.status)?.type))) return; + applyNativeAgent(m, id, { status: params.status }, undefined, undefined, at); + return; + case "thread/closed": + if (task.status === "running") status = "stopped"; + break; + case "turn/started": + status = "running"; + break; + case "turn/completed": + status = nativeTurnEnd(rec(params.turn)?.status); + break; + } + if (status) applyNativeAgent(m, id, {}, status, undefined, at); +} + +/** Merges discovery metadata or an explicit child lifecycle update into its row. */ function applyNativeAgent( m: CodexModel, id: string, metadata: Rec = {}, status?: string, prompt?: string, + at?: number, ): void { const before = m.tasks[id]; const kind = str(rec(metadata.status)?.type); const lastTurn = Array.isArray(metadata.turns) ? rec(metadata.turns.at(-1)) : undefined; - const terminal = str(lastTurn?.status); + const previous = before?.status; + // An idle status says the turn ended. Its specific outcome can arrive + // separately and takes precedence over an idle snapshot. + const nextStatus = + status ?? + (kind === "active" + ? "running" + : kind === "systemError" + ? "failed" + : (nativeTurnEnd(lastTurn?.status) ?? + (kind === "idle" && (!previous || previous === "running") ? "completed" : previous) ?? + "stopped")); const next: TaskInfo = { ...before, taskId: id, @@ -622,20 +687,13 @@ function applyNativeAgent( description: str(metadata.agentNickname) || str(metadata.name) || before?.description || prompt || id, subagentType: str(metadata.agentRole) ?? before?.subagentType, - status: - status ?? - (kind === "active" - ? "running" - : terminal === "failed" || kind === "systemError" - ? "failed" - : terminal === "interrupted" - ? "stopped" - : terminal === "completed" || kind === "idle" - ? "completed" - : (before?.status ?? "stopped")), + status: nextStatus, prompt: before?.prompt ?? (prompt || str(metadata.preview) || undefined), startedAt: - num(metadata.createdAt) === undefined ? before?.startedAt : Number(metadata.createdAt) * 1000, + num(metadata.createdAt) === undefined + ? (before?.startedAt ?? (nextStatus === "running" ? at : undefined)) + : Number(metadata.createdAt) * 1000, + endedAt: nextStatus === "running" ? undefined : (before?.endedAt ?? at), }; m.tasks = { ...m.tasks, [id]: next }; } @@ -863,7 +921,10 @@ function applyNotification( // its context's size and compactions. const threadId = str(params.threadId); const another = threadId && m.threadId && threadId !== m.threadId; - if (another && (!method.startsWith("thread/") || OWN_THREAD_ONLY.has(method))) return; + if (another) { + applyNativeAgentNotification(m, threadId, method, params, at); + if (!method.startsWith("thread/") || OWN_THREAD_ONLY.has(method)) return; + } if ( threadId && !m.threadId && @@ -889,16 +950,12 @@ function applyNotification( const item = rec(params.item); const turnId = str(params.turnId) ?? m.turnId ?? ""; if (item) { - const when = num(item.startedAtMs) ?? at; const completed = method === "item/completed"; - const toolRan = applyItem( - draft, - turnId, - item, - completed ? "completed" : "started", - tag, - when, - ); + const phase = completed ? "completed" : "started"; + const toolRan = + item.type === "commandExecution" + ? applyCommandEvent(draft, turnId, item, phase, tag, at) + : applyItem(draft, turnId, item, phase, tag, num(item.startedAtMs) ?? at); if (m.running && turnId === m.turnId) { noteTurnActivity(m, at); if (completed && toolRan && m.permissions.length === 0) { @@ -1083,7 +1140,25 @@ function applyNotification( function applyTurnCompleted(draft: CodexDraft, turn: Rec, seq: number, at: number | undefined) { const m = draft.next; const status = str(turn.status) ?? "completed"; + if (status === "inProgress") return; const turnId = str(turn.id); + if (turnId) { + // Some versions include the command's final item here even when its + // individual completion notification did not reach the tab. + for (const raw of Array.isArray(turn.items) ? turn.items : []) { + const item = rec(raw); + const id = str(item?.id); + if ( + item?.type === "commandExecution" && + id && + m.liveCommands?.[id]?.turnId === turnId && + (item.status === "completed" || item.status === "failed" || item.status === "declined") + ) { + applyCommandEvent(draft, turnId, item, "completed", String(seq), at); + } + } + settleCommands(draft, at, turnId); + } const sawTurnStart = turnId && turnId === m.turnId; m.running = false; m.turn = null; @@ -1107,15 +1182,131 @@ function applyTurnCompleted(draft: CodexDraft, turn: Rec, seq: number, at: numbe }; const failure = status === "failed" ? (str(rec(turn.error)?.message) ?? "failed") : undefined; finishSubmittedTurn(draft, turnId, failure); + if (status === "interrupted" || status === "failed") { + stopRunningTools(draft, (tool) => !tool.parentToolUseId && !m.liveCommands?.[tool.id]); + } if (status === "interrupted") { - stopRunningTools(draft); draft.push({ kind: "notice", key: `n${seq}`, code: "interrupted", at }); } else if (status === "failed") { - stopRunningTools(draft); pushError(draft, failure ?? "failed", `n${seq}`, at); } } +/** Projects a live command into the same job list the local and remote panels consume. */ +function setCommandJob( + m: CodexModel, + id: string, + status: string, + startedAt: number | undefined, + endedAt?: number, + durationMs?: number, +): void { + const tool = m.tools[id]; + if (!tool) return; + const taskId = `codex-command:${id}`; + const elapsed = + startedAt !== undefined && endedAt !== undefined ? endedAt - startedAt : durationMs; + // A brief foreground command never reached the running panel. + if ( + !m.tasks[taskId] && + status !== "running" && + elapsed !== undefined && + elapsed < WAITED_CALL_DELAY_MS + ) + return; + m.tasks = { + ...m.tasks, + [taskId]: { + taskId, + type: "local_bash", + toolUseId: id, + description: commandLabel(tool), + status, + startedAt, + endedAt, + }, + }; +} + +/** Drops the live tracking entry after its terminal row has been recorded. */ +function forgetCommand(m: CodexModel, id: string): void { + const { [id]: _command, ...rest } = m.liveCommands ?? {}; + m.liveCommands = Object.keys(rest).length > 0 ? rest : undefined; +} + +/** Applies a live command item without closing a still-running terminal on a partial update. */ +function applyCommandEvent( + draft: CodexDraft, + turnId: string, + item: Rec, + phase: "started" | "completed", + tag: string, + at: number | undefined, +): boolean | undefined { + const m = draft.next; + const id = str(item.id); + if (!id) return; + const live = m.liveCommands?.[id]; + const job = m.tasks[`codex-command:${id}`]; + if (live && phase === "completed" && live.turnId !== turnId) return; + const when = num(item.startedAtMs) ?? at; + const canContinue = + live?.canContinue === true || + str(item.processId) !== undefined || + item.source === "unifiedExecStartup" || + item.source === "unifiedExecInteraction"; + const stillRunning = + canContinue && item.status === "inProgress" && num(item.exitCode) === undefined; + const toolRan = applyItem(draft, turnId, item, stillRunning ? "started" : phase, tag, when); + const tool = m.tools[id]; + if (!tool) return toolRan; + if (tool.status === "running") { + const command = { turnId, startedAt: live?.startedAt ?? when, canContinue }; + m.liveCommands = { ...m.liveCommands, [id]: command }; + if (job?.status === "running") markCommandBackground(draft, tool); + return false; + } + if (live || job) { + const status = + tool.status === "done" ? "completed" : tool.status === "error" ? "failed" : "stopped"; + setCommandJob( + m, + id, + status, + live?.startedAt ?? job?.startedAt, + num(item.completedAtMs) ?? at, + num(item.durationMs), + ); + if (live) forgetCommand(m, id); + } + return toolRan; +} + +/** A terminal kept past its original turn does not block a later turn. */ +function markCommandBackground(draft: CodexDraft, tool: ToolCall): void { + draft.setTool(tool.id, () => ({ + ...tool, + input: { ...rec(tool.input), run_in_background: true }, + })); +} + +/** Settles one turn's foreground commands, or all commands on program exit. */ +function settleCommands(draft: CodexDraft, at: number | undefined, turnId?: string): void { + const m = draft.next; + for (const [id, command] of Object.entries(m.liveCommands ?? {})) { + if (turnId !== undefined && command.turnId !== turnId) continue; + const tool = m.tools[id]; + if (turnId !== undefined && command.canContinue && tool?.status === "running") { + markCommandBackground(draft, tool); + setCommandJob(m, id, "running", command.startedAt); + continue; + } + if (tool?.status === "running") draft.setTool(id, () => ({ ...tool, status: "stopped" })); + setCommandJob(m, id, "stopped", command.startedAt, at); + forgetCommand(m, id); + } +} + /** An error, once: the turn's failure repeats the error it was told. */ function pushError(draft: CodexDraft, detail: string, key: string, at: number | undefined) { const last = draft.next.items.at(-1); @@ -1208,7 +1399,7 @@ function applyItem( } return; } - if (discoverAgents) applyNativeAgentItem(m, item); + if (discoverAgents) applyNativeAgentItem(m, item, at); const tools = toolsOf(item, id, phase); if (!tools) return; const ran = @@ -1221,12 +1412,12 @@ function applyItem( return ran; } -function applyNativeAgentItem(m: CodexModel, item: Rec): void { +function applyNativeAgentItem(m: CodexModel, item: Rec, at: number | undefined): void { if (item.type === "subAgentActivity") { const id = str(item.agentThreadId); const status = item.kind === "completed" ? "completed" : item.kind === "interrupted" ? "stopped" : "running"; - if (id && id !== m.threadId) applyNativeAgent(m, id, {}, status); + if (id && id !== m.threadId) applyNativeAgent(m, id, {}, status, undefined, at); } if (item.type !== "collabAgentToolCall" || !Array.isArray(item.receiverThreadIds)) return; if (item.senderThreadId && item.senderThreadId !== m.threadId) return; @@ -1243,7 +1434,14 @@ function applyNativeAgentItem(m: CodexModel, item: Rec): void { : state === "pendingInit" || state === "running" || item.tool === "spawnAgent" ? "running" : undefined; - applyNativeAgent(m, id, {}, status, item.tool === "spawnAgent" ? str(item.prompt) : undefined); + applyNativeAgent( + m, + id, + {}, + status, + item.tool === "spawnAgent" ? str(item.prompt) : undefined, + at, + ); } } diff --git a/src/renderer/services/chat/running.ts b/src/renderer/services/chat/running.ts index 3bd2c7160..4db7b5785 100644 --- a/src/renderer/services/chat/running.ts +++ b/src/renderer/services/chat/running.ts @@ -77,7 +77,7 @@ function str(value: unknown): string | undefined { } /** A command's line as a row says it: what the model said it does, else its first line. */ -function commandLabel(tool: ToolCall): string { +export function commandLabel(tool: ToolCall): string { const input = (tool.input ?? {}) as Record; const said = str(input.description)?.trim(); if (said) return said; diff --git a/tests/unit/renderer/services/chat/codex/model.test.ts b/tests/unit/renderer/services/chat/codex/model.test.ts index f7738476a..7f535c92b 100644 --- a/tests/unit/renderer/services/chat/codex/model.test.ts +++ b/tests/unit/renderer/services/chat/codex/model.test.ts @@ -17,6 +17,10 @@ import type { ChatLine, UserItem, } from "../../../../../../src/renderer/services/chat/model"; +import { agentsOf, jobsOf } from "../../../../../../src/renderer/services/chat/panel"; +import { activityOf } from "../../../../../../src/renderer/services/chat/running"; +import { emptyTabState } from "../../../../../../src/renderer/services/chat/store"; +import { chatPanelOf } from "../../../../../../src/renderer/services/remote/chat-panel"; // Lines as `codex app-server` 0.166.0 writes them (newline-delimited // JSON-RPC without the "jsonrpc" field), after the generated schema. @@ -33,6 +37,16 @@ function run(lines: ChatLine[], from: CodexModel = emptyCodexModel()): CodexMode const T = "thr_1"; +/** The activity inputs shared by the local and remote panels. */ +const activity = (model: CodexModel) => + activityOf({ + agents: agentsOf(model), + jobs: jobsOf(model), + tools: model.tools, + items: model.items, + turnRunning: model.running, + }); + function started(): ChatLine[] { return [ sys({ event: "start", pid: 1 }), @@ -53,6 +67,168 @@ function started(): ChatLine[] { ]; } +test("a known child leaves running on its own terminal signal after the parent turn ends", () => { + const child = "child"; + const sibling = "sibling"; + const status = (threadId: string, type: string) => + note("thread/statusChanged", { + threadId, + status: { type, ...(type === "active" ? { activeFlags: ["waitingOnApproval"] } : {}) }, + }); + const launch = run([ + ...started(), + note("turn/started", { threadId: T, turn: { id: "parent" } }), + note("item/completed", { + threadId: T, + turnId: "parent", + item: { + type: "collabAgentToolCall", + id: "spawn", + tool: "spawnAgent", + status: "completed", + senderThreadId: T, + receiverThreadIds: [child, sibling], + agentsStates: { child: { status: "running" }, sibling: { status: "running" } }, + }, + }), + note("turn/completed", { threadId: T, turn: { id: "parent", status: "completed", items: [] } }), + status("unrelated", "idle"), + status(child, "active"), + ]); + expect(activity(launch).running.map((row) => row.key)).toEqual([child, sibling]); + const cases = [ + { end: [status(child, "idle")], expected: "completed" }, + { end: [status(child, "systemError")], expected: "failed" }, + { + end: [ + note("turn/completed", { + threadId: child, + turn: { id: "child-turn", status: "interrupted", items: [] }, + }), + status(child, "idle"), + ], + expected: "stopped", + }, + ]; + for (const { end, expected } of cases) { + const model = run(end, launch); + const rows = activity(model); + expect(rows.running.map((row) => row.key)).toEqual([sibling]); + expect(rows.ended).toMatchObject([{ key: child, status: expected, endedAt: 1000 }]); + expect(model.lastResult?.subtype).toBe("completed"); + } +}); + +test("Codex commands move from running to ended on the panel with their own lifecycle", () => { + const turnId = "turn_1"; + const command = (id: string, detail: Record = {}) => ({ + id, + type: "commandExecution", + command: id, + status: "inProgress", + ...detail, + }); + const item = ( + event: "started" | "completed", + commandItem: ReturnType, + at: number, + ) => ({ ...note(`item/${event}`, { threadId: T, turnId, item: commandItem }), at }); + const turnEnd = (status: string, items: unknown[] = []) => ({ + ...note("turn/completed", { threadId: T, turn: { id: turnId, status, items } }), + at: 6_000, + }); + + const startCommands = (observedTurnId = turnId) => + run([ + ...started(), + ...sendTurn("run both", "c1", observedTurnId), + item("started", command("foreground"), 1_000), + item( + "started", + command("background", { source: "unifiedExecStartup", processId: "42" }), + 1_000, + ), + item("started", command("quick"), 1_000), + item("completed", command("quick", { status: "completed" }), 1_100), + ]); + const base = startCommands(); + expect(activity(base).running.map((row) => row.description)).toEqual([ + "foreground", + "background", + ]); + expect(activity(base).ended).toEqual([]); + + const cases = [ + { + end: [ + item("completed", command("foreground", { status: "completed" }), 5_000), + turnEnd("completed"), + ], + status: "completed", + background: "running", + }, + { end: [turnEnd("completed")], status: "stopped", background: "running" }, + { + // The actual turn's items reached the log, but its turn/started did not. + from: startCommands("previous-turn"), + end: [turnEnd("completed")], + status: "stopped", + background: "running", + }, + { end: [turnEnd("interrupted")], status: "stopped", background: "running" }, + { + end: [turnEnd("failed", [command("foreground", { status: "failed", exitCode: 1 })])], + status: "failed", + background: "running", + }, + { + end: [{ ...sys({ event: "exit", code: 1 }), at: 6_000 }], + status: "stopped", + background: "stopped", + }, + ]; + for (const { end, status, background, from = base } of cases) { + const model = run(end, from); + expect(model.running).toBe(false); + const rows = activity(model); + expect(rows.ended).toContainEqual( + expect.objectContaining({ description: "foreground", status }), + ); + expect([...rows.running, ...rows.ended]).toContainEqual( + expect.objectContaining({ description: "background", status: background, waited: false }), + ); + const panel = chatPanelOf({ agent: "codex", title: "", chat: { ...emptyTabState(), model } }); + expect(panel.tasks.map(({ description, status }) => ({ description, status }))).toEqual( + expect.arrayContaining([ + { description: "foreground", status }, + { description: "background", status: background }, + ]), + ); + } + const stillRunning = run( + [ + turnEnd("completed"), + note("turn/started", { threadId: T, turn: { id: "next" } }), + item("completed", command("background", { status: "inProgress", processId: "42" }), 7_000), + ], + base, + ); + expect(activity(stillRunning).running).toMatchObject([ + { description: "background", waited: false }, + ]); + const ended = run( + [item("completed", command("background", { status: "completed", exitCode: 0 }), 8_000)], + stillRunning, + ); + expect(activity(ended).running).toEqual([]); + expect(activity(ended).ended[0]).toMatchObject({ + description: "background", + status: "completed", + endedAt: 8_000, + }); + expect(ended.running).toBe(true); +}); + test("keeps the latest own-thread plan and ignores a child thread's plan", () => { const plan = (threadId: string, steps: unknown[]) => note("turn/plan/updated", { threadId, turnId: "turn_1", plan: steps });