diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 3a4f54c59c41b..cefe60f9e74db 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -2345,3 +2345,50 @@ it("caps live thought previews while preserving reasoning detail", () => { expect(JSON.parse(activity.getFullDetail()!).item).toMatchObject({ text }); expect(activity.getCopyText()).toContain(text); }); + +it("surfaces a running background command with its summary below an interim assistant message", () => { + const startedAt = "2026-06-20T00:00:01.000Z"; + const runningCmd: OrchestrationV2TurnItem = { + ...command(), + id: TurnItemId.make("item-bg-cmd"), + status: "running", + completedAt: null, + title: "Check outer moons sky level and capture 60 frames if clean", + input: "mkdir -p /tmp/out && python3 capture.py", + }; + const interimReply: OrchestrationV2TurnItem = { + ...assistantMessage(), + text: "Checking 1 frame right now.", + streaming: false, + }; + const feed = buildThreadFeed([ + projected(userMessage(), 0), + projected(runningCmd, 1), + projected(interimReply, 2), + ]); + const rows = deriveThreadFeedPresentation( + feed, + { runId, status: "running", startedAt, completedAt: null }, + new Set(), + new Set(), + startedAt, + ); + const replyIdx = rows.findIndex( + (row) => row.type === "message" && row.message.role === "assistant", + ); + const liveIdx = rows.findIndex((row) => row.id === "live-activity-row"); + expect(replyIdx).toBeGreaterThan(-1); + expect(liveIdx).toBeGreaterThan(replyIdx); + expect(rows.some((row) => row.type === "thinking")).toBe(false); + const liveRow = rows[liveIdx]; + expect(liveRow?.type).toBe("activity-group"); + if (liveRow?.type === "activity-group") { + expect(liveRow.activities[0]?.live).toBe(true); + expect(liveRow.activities[0]?.groupStandIn?.label).toBe( + "Check outer moons sky level and capture 60 frames if clean", + ); + expect(workEntryRowLabel(liveRow.activities[0]!.workEntry)).toBe( + "Check outer moons sky level and capture 60 frames if clean", + ); + } +}); diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index b63a7e0f56442..09c16f5dbd5b5 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -22,6 +22,7 @@ import { commandProgramName, } from "@t3tools/client-runtime/work-log/command-label"; import { + commandCustomTitle, commandlessCommandLabel, contextCompactionLabel, liveThoughtLine, @@ -301,6 +302,8 @@ export function workEntryRowLabel( : resolve(msg("Thought")); const presentation = resolveWorkEntryToolPresentation(entry, undefined, resolve); if (presentation) return presentation.displayName; + const customCommandTitle = commandCustomTitle(entry); + if (customCommandTitle) return compactWorkEntryText(customCommandTitle); if (entry.command?.trim()) return compactWorkEntryText(commandDisplayText(entry.command)); const commandless = commandlessCommandLabel( entry, @@ -957,6 +960,8 @@ function singleToolCallLabel( : compactWorkEntryText(activity.workEntry.detail ?? "") || resolve(msg("Thought")); const presentation = resolveWorkEntryToolPresentation(activity.workEntry, "completed", resolve); if (presentation) return presentation.displayName; + const customCommandTitle = commandCustomTitle(activity.workEntry); + if (customCommandTitle) return compactWorkEntryText(customCommandTitle); const command = activity.workEntry.command?.trim(); return command ? truncate(command, WORK_LOG_LABEL_MAX_LENGTH) : activity.summary; } @@ -1822,6 +1827,31 @@ export function deriveThreadFeedPresentation( for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId); } } + const tailIsActiveActivityGroup = + activeTailGroup?.type === "activity-group" && activeTailGroup.runId === activeRunId; + const trailingRunningCommands: ThreadFeedActivity[] = []; + const trailingRunningCommandIds = new Set(); + if ( + !zen && + isWorking && + latestRun?.turnEnded !== true && + !tailIsActiveActivityGroup && + (activeRunId !== null || runlessWorkActive) + ) { + for (const entry of sourceFeed) { + if (entry.type !== "activity-group" || collapsedEntryIds.has(entry.id)) continue; + for (const activity of entry.activities) { + if ( + activity.projectedItem.item.type === "command_execution" && + activity.lifecycleStatus === "inProgress" && + activity.runId === activeRunId + ) { + trailingRunningCommands.push(activity); + trailingRunningCommandIds.add(activity.id); + } + } + } + } // The working run's fold row shows its live timer where "Worked for" lands once it settles. // Zen never folds, so it keeps only the Thinking row. // Runless work folds under its prompt's key once it settles, so the live row takes that key. @@ -1930,9 +1960,24 @@ export function deriveThreadFeedPresentation( result.push(...rows); continue; } + const presentationEntry = + trailingRunningCommandIds.size > 0 && entry.type === "activity-group" + ? { + ...entry, + activities: entry.activities.filter( + (activity) => !trailingRunningCommandIds.has(activity.id), + ), + } + : entry; + if ( + presentationEntry.type === "activity-group" && + presentationEntry.activities.length === 0 + ) { + continue; + } appendPresentedFeedEntry( result, - entry, + presentationEntry, expandedWorkGroupIds, activeRunId, isWorking, @@ -1943,6 +1988,25 @@ export function deriveThreadFeedPresentation( } } if (liveFold !== null && !liveFoldPlaced) result.push(liveFold); + if (trailingRunningCommands.length > 0) { + const anchor = trailingRunningCommands[0]!; + appendPresentedFeedEntry( + result, + { + type: "activity-group", + id: anchor.id, + createdAt: anchor.createdAt, + runId: activeRunId, + activities: trailingRunningCommands, + }, + expandedWorkGroupIds, + activeRunId, + isWorking, + true, + resolve, + locale, + ); + } if ( isWorking && activeWorkStartedAt !== null && @@ -2412,6 +2476,8 @@ function liveToolActivitySummary( resolve, ); if (presentation) return presentation.displayName; + const customCommandTitle = commandCustomTitle(activity.workEntry); + if (customCommandTitle) return compactWorkEntryText(customCommandTitle); const command = activity.workEntry.command?.trim(); if (command) { const program = commandProgramName(command); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..22256ccf8d4ed 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -38,6 +38,7 @@ import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { makeAcpAdapterV2 } from "@t3tools/provider-acp/server/adapter"; import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts"; +import { commandStep } from "../../provider/acp/AntigravityChildWork.testkit.ts"; import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts"; import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -1672,6 +1673,84 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + it.live( + "tails background task-.log into command_output.delta and hydrates toolSummary from SQLite", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const NodeSqlite = yield* Effect.promise(() => import("node:sqlite")); + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-ag-cmd-tail-" }); + const acpDir = path.join(profile, "antigravity-acp"); + const conversationsDir = path.join(acpDir, "conversations"); + const tasksDir = path.join(acpDir, "brain", "mock-session-1", ".system_generated", "tasks"); + yield* fileSystem.makeDirectory(conversationsDir, { recursive: true }); + yield* fileSystem.makeDirectory(tasksDir, { recursive: true }); + const db = new NodeSqlite.DatabaseSync(path.join(conversationsDir, "mock-session-1.db")); + db.exec( + "CREATE TABLE steps (idx integer PRIMARY KEY, step_type integer NOT NULL DEFAULT 0, step_format integer NOT NULL DEFAULT 0, step_payload blob)", + ); + db.prepare("INSERT INTO steps (idx, step_type, step_payload) VALUES (?, ?, ?)").run( + 17, + 132, + commandStep({ + callId: "call_bg_capture", + commandLine: "python3 capture.py", + toolSummary: "Capture 60 frames if sky is clean", + }), + ); + db.close(); + const logFile = path.join(tasksDir, "task-17.log"); + yield* fileSystem.writeFileString(logFile, "sky median 412 ADU\n"); + + const cmd = { + toolCallId: "call_bg_capture", + kind: "execute", + title: "Run command", + rawInput: { CommandLine: "python3 capture.py", WaitMsBeforeAsync: 5000 }, + } as const; + const { send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + profileDirectory: profile, + initialToolCalls: [{ sessionUpdate: "tool_call", ...cmd, status: "in_progress" }], + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + + const sawTitle = yield* until( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.title === "Capture 60 frames if sky is clean", + ); + assert.isTrue(sawTitle.length > 0); + const sawChunk = yield* until( + (event) => + event.type === "command_output.delta" && event.chunk.includes("sky median 412 ADU"), + ); + assert.isTrue(sawChunk.length > 0); + + yield* fileSystem.writeFileString(logFile, "sky median 412 ADU\n60 frames captured\n"); + yield* send({ + sessionUpdate: "tool_call_update", + ...cmd, + status: "completed", + rawOutput: { combinedOutput: "sky median 412 ADU\n60 frames captured\n", exitCode: 0 }, + }); + const settled = yield* until( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.status === "completed", + ); + const completedEvent = settled.at(-1); + assert.equal( + completedEvent?.type === "turn_item.updated" ? completedEvent.turnItem.title : null, + "Capture 60 frames if sky is clean", + ); + }).pipe(Effect.provide(layerSession)), + ); + // agy 1.5.11 reads a prompt sent mid-turn as a steer: it answers the running prompt end_turn // and goes on under the new one. session/cancel would end its running commands and subagents. it.effect("steers a running prompt with the next one and leaves its work running", () => diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..d37a628c0bf2b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -37,6 +37,7 @@ import { readAntigravityPendingReply, } from "../../provider/acp/AntigravityChildWork.ts"; import { readAntigravityClientTextFile } from "../../provider/acp/AntigravityClientFiles.ts"; +import { tailAntigravityCommandOutput } from "../../provider/acp/AntigravityTaskOutputTail.ts"; import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTurnOutcome.ts"; import { antigravityApprovalOptions, @@ -310,6 +311,15 @@ export function makeAntigravityAcpAdapterFlavor( profileDirectory, sessionId, }), + tailCommandOutput: ({ sessionId, toolCallId, stop, onChunk, onTitle }) => + tailAntigravityCommandOutput({ + profileDirectory, + sessionId, + toolCallId, + stop, + onChunk, + onTitle, + }), }), }; } diff --git a/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts b/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts index 82a2befbf6698..3461573d8b83f 100644 --- a/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts +++ b/apps/server/src/provider/acp/AntigravityChildWork.testkit.ts @@ -49,6 +49,33 @@ export const invokeStep = (input: { ); export const plannerStep = (callIds: ReadonlyArray) => proto(field(20, proto(...callIds.map((id) => field(7, toolCall(id)))))); +export const commandStep = (input: { + readonly callId: string; + readonly commandLine: string; + readonly toolSummary?: string; +}) => + proto( + [...varint(1 * 8), ...varint(132)], + field( + 5, + proto( + field( + 4, + proto( + field(1, input.callId), + field(2, "run_command"), + field( + 3, + JSON.stringify({ + CommandLine: input.commandLine, + ...(input.toolSummary === undefined ? {} : { toolSummary: input.toolSummary }), + }), + ), + ), + ), + ), + ), + ); export const transcriptLines = [ // Trimmed from 1.4.5: the launch envelope around the prompt the parent record already holds. diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index cfe47280fc4f1..c39deeb4bcacc 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -709,3 +709,35 @@ describe("Antigravity served reads", () => { }); }); }); + +describe("Antigravity command toolSummary normalization", () => { + it("uses rawInput toolSummary when the command carries a generic title", () => { + const normalized = normalizeAntigravityToolCall({ + toolCallId: "call_cmd_1", + title: "Run command", + kind: "execute", + status: "inProgress", + data: { + rawInput: { + CommandLine: "mkdir -p /tmp/out && python3 capture.py", + toolSummary: "Check outer moons sky level and capture 60 frames if clean", + }, + }, + }); + expect(normalized.title).toBe("Check outer moons sky level and capture 60 frames if clean"); + + const preserved = normalizeAntigravityToolCall({ + toolCallId: "call_cmd_2", + title: "Already named task", + kind: "execute", + status: "inProgress", + data: { + rawInput: { + CommandLine: "echo hi", + tool_summary: "Fallback summary", + }, + }, + }); + expect(preserved.title).toBe("Already named task"); + }); +}); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 2ba17c8a86db5..b066b809df998 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -38,8 +38,25 @@ const NativeToolFields = Schema.Struct({ exitCode: Schema.optional(Schema.Int), exit_code: Schema.optional(Schema.Int), imagePath: Schema.optional(Schema.String), + toolSummary: Schema.optional(Schema.String), + tool_summary: Schema.optional(Schema.String), }); const decodeNativeToolFields = Schema.decodeUnknownOption(NativeToolFields); +const GENERIC_ANTIGRAVITY_COMMAND_TITLES = new Set([ + "run command", + "running command", + "ran command", + "command", + "run_command", + "run run_command", + "running run_command", + "run run_command?", +]); + +function isGenericAntigravityCommandTitle(title: string | undefined): boolean { + const trimmed = title?.trim(); + return !trimmed || GENERIC_ANTIGRAVITY_COMMAND_TITLES.has(trimmed.toLowerCase()); +} const decodeSingleAnswer = Schema.decodeUnknownOption( Schema.Union([Schema.String, Schema.Tuple([Schema.String])]), ); @@ -482,9 +499,19 @@ export function normalizeAntigravityToolCall( const aggregatedOutput = nativeOutput === undefined ? undefined : boundCommandText(nativeOutput); const exitCode = output?.exitCode ?? output?.exit_code; const imagePath = localImagePath(output?.imagePath); + const nativeSummary = input?.toolSummary ?? input?.tool_summary; + const toolSummary = nativeSummary?.trim() ? boundText(nativeSummary.trim()) : undefined; const sanitizedData = sanitizeAntigravityToolPayload(toolCall.data); const data: Record = Predicate.isObject(sanitizedData) ? sanitizedData : {}; const kind = toolCall.kind ?? (command !== undefined ? "execute" : undefined); + const title = + kind === "execute" && + toolSummary !== undefined && + isGenericAntigravityCommandTitle(toolCall.title) + ? toolSummary + : toolCall.title !== undefined + ? boundText(toolCall.title) + : undefined; if (kind !== undefined) data.kind = kind; if (command !== undefined) data.command = command; if (cwd !== undefined) data.cwd = cwd; @@ -513,7 +540,7 @@ export function normalizeAntigravityToolCall( ...toolCall, ...(kind !== undefined ? { kind } : {}), ...(command !== undefined ? { command } : {}), - ...(toolCall.title !== undefined ? { title: boundText(toolCall.title) } : {}), + ...(title !== undefined ? { title } : {}), ...(command !== undefined ? { detail: command } : toolCall.detail !== undefined diff --git a/apps/server/src/provider/acp/AntigravityTaskOutputTail.test.ts b/apps/server/src/provider/acp/AntigravityTaskOutputTail.test.ts new file mode 100644 index 0000000000000..fad833d07d026 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravityTaskOutputTail.test.ts @@ -0,0 +1,123 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; + +import { commandStep, makeProfile, ROOT } from "./AntigravityChildWork.testkit.ts"; +import { tailAntigravityCommandOutput } from "./AntigravityTaskOutputTail.ts"; + +describe("tailAntigravityCommandOutput", () => { + it.live("discovers toolSummary and streams task-.log across split UTF-8 bytes", () => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const callId = "call_capture_moons"; + const { profile } = yield* makeProfile({ + steps: () => [ + [ + 42, + 132, + commandStep({ + callId, + commandLine: "python3 capture.py", + toolSummary: "Check outer moons sky level and capture 60 frames if clean", + }), + ], + ], + }); + const tasksDir = path.join( + profile, + "antigravity-acp", + "brain", + ROOT, + ".system_generated", + "tasks", + ); + const logFile = path.join(tasksDir, "task-42.log"); + const titles = yield* Queue.unbounded(); + const chunks = yield* Queue.unbounded(); + const stop = yield* Deferred.make(); + + const fiber = yield* tailAntigravityCommandOutput({ + profileDirectory: profile, + sessionId: ROOT, + toolCallId: callId, + stop, + onTitle: (title) => Queue.offer(titles, title), + onChunk: (chunk) => Queue.offer(chunks, chunk), + }).pipe(Effect.forkScoped); + + assert.equal( + yield* Queue.take(titles), + "Check outer moons sky level and capture 60 frames if clean", + ); + + yield* fileSystem.makeDirectory(tasksDir, { recursive: true }); + const encoded = new TextEncoder().encode("café frame 1\n"); + yield* fileSystem.writeFile(logFile, encoded.subarray(0, 4)); + assert.equal(yield* Queue.take(chunks), "caf"); + + yield* fileSystem.writeFile(logFile, encoded); + yield* Deferred.succeed(stop, undefined); + assert.equal(yield* Queue.take(chunks), "é frame 1\n"); + yield* Fiber.await(fiber); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("refuses a symlinked task log outside the profile", () => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const callId = "call_symlink"; + const { profile } = yield* makeProfile({ + steps: () => [ + [ + 7, + 132, + commandStep({ + callId, + commandLine: "echo secret", + toolSummary: "Symlink probe", + }), + ], + ], + }); + const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-agy-outside-" }); + const secret = path.join(outside, "secret.log"); + yield* fileSystem.writeFileString(secret, "do not read\n"); + const tasksDir = path.join( + profile, + "antigravity-acp", + "brain", + ROOT, + ".system_generated", + "tasks", + ); + yield* fileSystem.makeDirectory(tasksDir, { recursive: true }); + yield* fileSystem.symlink(secret, path.join(tasksDir, "task-7.log")); + + const chunks: string[] = []; + const stop = yield* Deferred.make(); + yield* Deferred.succeed(stop, undefined); + yield* tailAntigravityCommandOutput({ + profileDirectory: profile, + sessionId: ROOT, + toolCallId: callId, + stop, + onChunk: (chunk) => + Effect.sync(() => { + chunks.push(chunk); + }), + }); + assert.deepEqual(chunks, []); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/provider/acp/AntigravityTaskOutputTail.ts b/apps/server/src/provider/acp/AntigravityTaskOutputTail.ts new file mode 100644 index 0000000000000..0980f86fe22e8 --- /dev/null +++ b/apps/server/src/provider/acp/AntigravityTaskOutputTail.ts @@ -0,0 +1,287 @@ +// @effect-diagnostics nodeBuiltinImport:off -- node:sqlite and O_NOFOLLOW read Antigravity's native session records safely. +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; +import * as NodeSqlite from "node:sqlite"; + +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { protoFields } from "./AntigravityChildWork.ts"; +import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts"; +import { boundAntigravityToolText } from "./AntigravityProtocol.ts"; + +// Field numbers from the runtime's trajectory protos (exa.cortex_pb). +const STEP_METADATA = 5; +const METADATA_TOOL_CALL = 4; +const RUN_COMMAND_STEP_TYPE = 132; + +const ANTIGRAVITY_TASK_OUTPUT_POLL_MS = 250; +// Covers WaitMsBeforeAsync (up to 10s) plus startup jitter before task-.log appears. +const MAX_LOCATE_ATTEMPTS = 120; +const MAX_READ_BYTES = 256 * 1024; +const MAX_STEP_BYTES = 1024 * 1024; +const MAX_COMMAND_ROWS = 400; +const MAX_SCAN_BYTES = 8 * 1024 * 1024; + +const NATIVE_ID = /^[A-Za-z0-9-]{1,64}$/; +const textDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + +const CommandToolArguments = Schema.Struct({ + toolSummary: Schema.optional(Schema.String), + tool_summary: Schema.optional(Schema.String), +}); +const decodeCommandToolArguments = Schema.decodeUnknownOption( + Schema.fromJsonString(CommandToolArguments), +); + +interface AntigravityCommandStep { + readonly stepIdx: number; + readonly toolSummary: string | undefined; +} + +const fieldBytes = (bytes: Uint8Array | undefined, field: number): Uint8Array | undefined => { + if (bytes === undefined) return undefined; + for (const [number, value] of protoFields(bytes)) { + if (number === field) return value; + } + return undefined; +}; + +const fieldText = (bytes: Uint8Array | undefined, field: number): string | undefined => { + const value = fieldBytes(bytes, field); + return value === undefined ? undefined : textDecoder.decode(value); +}; + +function decodeCommandToolCall( + payload: Uint8Array, +): { readonly toolCallId: string; readonly toolSummary: string | undefined } | undefined { + try { + const toolCall = fieldBytes(fieldBytes(payload, STEP_METADATA), METADATA_TOOL_CALL); + const toolCallId = fieldText(toolCall, 1); + if (!toolCallId) return undefined; + const argsJson = fieldText(toolCall, 3); + const args = + argsJson === undefined + ? undefined + : Option.getOrUndefined(decodeCommandToolArguments(argsJson)); + const rawSummary = (args?.toolSummary ?? args?.tool_summary)?.trim(); + const toolSummary = rawSummary ? boundAntigravityToolText(rawSummary) : undefined; + return { toolCallId, toolSummary }; + } catch { + return undefined; + } +} + +async function findCommandStep( + profileRoot: string, + sessionId: string, + toolCallId: string, +): Promise { + const databasePath = ( + await antigravityManagedPath( + profileRoot, + ["antigravity-acp", "conversations", `${sessionId}.db`], + "file", + ) + )?.path; + if (databasePath === undefined) return undefined; + let database: NodeSqlite.DatabaseSync; + try { + database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true }); + } catch { + return undefined; + } + try { + let rows = 0; + let bytes = 0; + for (const row of database + .prepare( + "SELECT idx, length(step_payload) AS size, CASE WHEN length(step_payload) <= ? THEN step_payload END AS step_payload FROM steps WHERE step_type = ? AND step_format = 0 ORDER BY idx DESC", + ) + .iterate(MAX_STEP_BYTES, RUN_COMMAND_STEP_TYPE)) { + if (row === null || typeof row !== "object") continue; + const size = "size" in row ? Number(row.size) : 0; + rows += 1; + bytes += size; + if (rows > MAX_COMMAND_ROWS || size > MAX_STEP_BYTES || bytes > MAX_SCAN_BYTES) { + return undefined; + } + const payload = + "step_payload" in row && row.step_payload instanceof Uint8Array + ? row.step_payload + : undefined; + if (payload === undefined) continue; + const decoded = decodeCommandToolCall(payload); + if (decoded === undefined || decoded.toolCallId !== toolCallId) continue; + const stepIdx = "idx" in row ? Number(row.idx) : Number.NaN; + if (!Number.isInteger(stepIdx) || stepIdx < 0) return undefined; + return { stepIdx, toolSummary: decoded.toolSummary }; + } + return undefined; + } catch { + return undefined; + } finally { + database.close(); + } +} + +async function readTaskLogSlice( + logPath: string, + offset: number, +): Promise< + | { readonly kind: "unchanged" } + | { + readonly kind: "chunk"; + readonly bytes: Uint8Array; + readonly nextOffset: number; + readonly reset: boolean; + readonly skipped: boolean; + } +> { + const handle = await NodeFSP.open( + logPath, + NodeFS.constants.O_RDONLY | (NodeFS.constants.O_NOFOLLOW ?? 0), + ); + try { + const stat = await handle.stat(); + if (!stat.isFile()) return { kind: "unchanged" }; + const size = stat.size; + const reset = size < offset; + const effectiveOffset = reset ? 0 : offset; + if (size <= effectiveOffset) { + return reset + ? { kind: "chunk", bytes: new Uint8Array(0), nextOffset: 0, reset: true, skipped: false } + : { kind: "unchanged" }; + } + const start = size - effectiveOffset > MAX_READ_BYTES ? size - MAX_READ_BYTES : effectiveOffset; + const length = size - start; + const buffer = Buffer.alloc(length); + const { bytesRead } = await handle.read(buffer, 0, length, start); + return { + kind: "chunk", + bytes: buffer.subarray(0, bytesRead), + nextOffset: start + bytesRead, + reset, + skipped: start > effectiveOffset, + }; + } finally { + await handle.close(); + } +} + +class AntigravityTaskOutputReadError extends Schema.TaggedError()( + "AntigravityTaskOutputReadError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read Antigravity task output."; + } +} + +const tryRead = (read: () => Promise, fallback: A) => + Effect.tryPromise({ + try: read, + catch: (cause) => new AntigravityTaskOutputReadError({ cause }), + }).pipe(Effect.orElseSucceed(() => fallback)); + +/** + * Antigravity streams background `run_command` output to `brain//.system_generated/tasks/task-.log` + * without sending ACP terminal chunks, and may strip `toolSummary` from the wire payload. + * Complete `stop` on command completion or turn end, then await the fiber for a final read. + */ +export const tailAntigravityCommandOutput = Effect.fn("AntigravityTaskOutputTail.tail")( + function* (input: { + readonly profileDirectory: string; + readonly sessionId: string; + readonly toolCallId: string; + readonly stop: Deferred.Deferred; + readonly onChunk: (chunk: string) => Effect.Effect; + readonly onTitle?: (title: string) => Effect.Effect; + }) { + if (!NATIVE_ID.test(input.sessionId) || input.toolCallId.trim().length === 0) return; + const pause = Deferred.await(input.stop).pipe( + Effect.as(true), + Effect.timeoutOrElse({ + duration: ANTIGRAVITY_TASK_OUTPUT_POLL_MS, + orElse: () => Effect.succeed(false), + }), + ); + const profileRoot = yield* tryRead( + () => antigravityProfileRoot(input.profileDirectory), + undefined, + ); + if (profileRoot === undefined) return; + + let step: AntigravityCommandStep | undefined; + let titleReported = false; + let logPath: string | undefined; + + for (let attempt = 0; logPath === undefined; attempt += 1) { + if (step === undefined) { + step = yield* tryRead( + () => findCommandStep(profileRoot, input.sessionId, input.toolCallId), + undefined, + ); + if (step?.toolSummary !== undefined && !titleReported && input.onTitle !== undefined) { + titleReported = true; + yield* input.onTitle(step.toolSummary); + } + } + if (step !== undefined) { + const stepIdx = step.stepIdx; + logPath = yield* tryRead( + async () => + ( + await antigravityManagedPath( + profileRoot, + [ + "antigravity-acp", + "brain", + input.sessionId, + ".system_generated", + "tasks", + `task-${stepIdx}.log`, + ], + "file", + ) + )?.path, + undefined, + ); + if (logPath !== undefined) break; + } + if (attempt + 1 >= MAX_LOCATE_ATTEMPTS || (yield* pause)) return; + } + + let decoder = new TextDecoder("utf-8", { fatal: false }); + let offset = 0; + let last = yield* Deferred.isDone(input.stop); + while (true) { + const slice = yield* tryRead(() => readTaskLogSlice(logPath, offset), { + kind: "unchanged" as const, + }); + if (slice.kind === "chunk") { + if (slice.reset) { + decoder = new TextDecoder("utf-8", { fatal: false }); + } + let first = 0; + if (slice.skipped) { + decoder = new TextDecoder("utf-8", { fatal: false }); + while (((slice.bytes[first] ?? 0) & 0xc0) === 0x80) first += 1; + } + offset = slice.nextOffset; + const text = + (slice.skipped ? "\n" : "") + + decoder.decode(slice.bytes.subarray(first), { stream: true }); + if (text.length > 0) yield* input.onChunk(text); + } + if (last) { + const rest = decoder.decode(); + if (rest.length > 0) yield* input.onChunk(rest); + return; + } + last = yield* pause; + } + }, +); diff --git a/apps/web/src/components/chat/MessagesTimeline.active-tools.test.ts b/apps/web/src/components/chat/MessagesTimeline.active-tools.test.ts index d05bbdcf32557..663c90bbfbbe3 100644 --- a/apps/web/src/components/chat/MessagesTimeline.active-tools.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.active-tools.test.ts @@ -1,4 +1,4 @@ -import { RunId } from "@t3tools/contracts"; +import { MessageId, RunId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { deriveMessagesTimelineRows, @@ -98,3 +98,125 @@ describe("liveWorkEntryLabel for a command execution without a command", () => { }, ); }); + +describe("running background command visibility", () => { + it("prefers a non-generic command title over the raw command and ignores generic titles", () => { + const titled = { + id: "work-titled-command", + createdAt: "2026-10-12T00:00:00Z", + label: "Check outer moons sky level and capture 60 frames if clean", + toolTitle: "Check outer moons sky level and capture 60 frames if clean", + tone: "tool" as const, + itemType: "command_execution" as const, + command: "mkdir -p /tmp/out && python3 capture.py", + toolLifecycleStatus: "inProgress" as const, + }; + expect(liveWorkEntryLabel(titled, undefined, true)).toBe( + "Check outer moons sky level and capture 60 frames if clean", + ); + expect(workEntryDisplayLabel(titled, undefined)).toBe( + "Check outer moons sky level and capture 60 frames if clean", + ); + + const generic = { + ...titled, + label: "Run command", + toolTitle: "bash", + }; + expect(liveWorkEntryLabel(generic, undefined, true)).toBe("Running mkdir"); + expect(workEntryDisplayLabel(generic, undefined)).toBe( + "mkdir -p /tmp/out && python3 capture.py", + ); + }); + + it("surfaces a running command below an interim assistant message and settles it back when done", () => { + const runId = RunId.make("bg-cmd-run"); + const createdAt = "2026-10-12T00:00:00Z"; + const makeEntries = (status: "inProgress" | "completed") => [ + { + id: "user-1", + kind: "message" as const, + createdAt, + message: { + id: MessageId.make("user-1"), + role: "user" as const, + text: "Capture 60 frames", + createdAt, + updatedAt: createdAt, + streaming: false, + runId, + }, + }, + { + id: "cmd-1", + kind: "work" as const, + createdAt, + entry: { + id: "cmd-1", + createdAt, + runId, + label: "Check outer moons sky level and capture 60 frames if clean", + toolTitle: "Check outer moons sky level and capture 60 frames if clean", + tone: "tool" as const, + itemType: "command_execution" as const, + command: "python3 capture.py", + toolLifecycleStatus: status, + }, + }, + { + id: "assistant-1", + kind: "message" as const, + createdAt, + message: { + id: MessageId.make("assistant-1"), + role: "assistant" as const, + text: "Checking 1 frame right now.", + createdAt, + updatedAt: createdAt, + streaming: false, + runId, + }, + }, + ]; + + const runningRows = deriveMessagesTimelineRows({ + timelineEntries: makeEntries("inProgress"), + isWorking: true, + runningRunId: runId, + activeTurnStartedAt: createdAt, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + const assistantIdx = runningRows.findIndex( + (row) => row.kind === "message" && row.id === "assistant-1", + ); + const liveIdx = runningRows.findIndex((row) => row.kind === "work-live"); + expect(assistantIdx).toBeGreaterThan(-1); + expect(liveIdx).toBeGreaterThan(assistantIdx); + const liveRow = runningRows[liveIdx]; + expect(liveRow?.kind).toBe("work-live"); + expect(liveRow?.id).toBe("live-activity-row"); + expect( + liveRow?.kind === "work-live" && liveWorkEntryLabel(liveRow.entry, undefined, liveRow.active), + ).toBe("Check outer moons sky level and capture 60 frames if clean"); + // Not duplicated above the interim message, and no generic Thinking row underneath. + expect(runningRows.filter((row) => row.kind === "work-live")).toHaveLength(1); + expect(runningRows.some((row) => row.kind === "thinking")).toBe(false); + + const completedRows = deriveMessagesTimelineRows({ + timelineEntries: makeEntries("completed"), + isWorking: false, + runningRunId: null, + activeTurnStartedAt: null, + turnDiffSummaries: [], + supportsConversationRollback: false, + expandedRunIds: new Set([runId]), + }); + const settledCmdIdx = completedRows.findIndex((row) => row.id === "cmd-1"); + const settledAssistantIdx = completedRows.findIndex( + (row) => row.kind === "message" && row.id === "assistant-1", + ); + expect(settledCmdIdx).toBeGreaterThan(-1); + expect(settledCmdIdx).toBeLessThan(settledAssistantIdx); + }); +}); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 124062303e0cf..924f9f6314829 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -20,6 +20,7 @@ import { commandProgramName, } from "@t3tools/client-runtime/work-log/command-label"; import { + commandCustomTitle, commandlessCommandLabel, genericCommandStatusLabel, liveActivityToolStatus, @@ -158,6 +159,8 @@ export function workEntryDisplayLabel( } const toolPresentation = resolveWorkEntryToolPresentation(entry, undefined, resolve); if (toolPresentation) return toolPresentation.displayName; + const customCommandTitle = commandCustomTitle(entry); + if (customCommandTitle) return customCommandTitle; if (entry.command?.trim()) return commandDisplayText(entry.command); const commandless = commandlessCommandLabel( entry, @@ -275,6 +278,8 @@ export function liveWorkEntryLabel( resolve, ); if (toolPresentation) return toolPresentation.displayName; + const customCommandTitle = commandCustomTitle(entry); + if (customCommandTitle) return customCommandTitle; const command = entry.command?.trim(); if (command) { const program = commandProgramName(command); @@ -1808,9 +1813,28 @@ export function deriveMessagesTimelineRows( }; })() : null; - const activeWorkEntryIds = new Set( - activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [], - ); + const trailingRunningCommandEntries = + input.isWorking && + activeWorkRow === null && + input.latestRun?.turnEnded !== true && + (unsettledRunId !== null || runlessWorkActive) + ? timelineEntries.filter( + (entry): entry is Extract => + entry.kind === "work" && + entry.entry.itemType === "command_execution" && + workEntryIsInActiveRun(entry.entry) && + !collapsedEntryIds.has(entry.id) && + !collapsedSupersededEntryIds.has(entry.id) && + !foldsByAnchorEntryId.has(entry.id) && + !supersededFoldsByAnchorEntryId.has(entry.id), + ) + : []; + const activeWorkEntryIds = new Set([ + ...(activeWorkRow !== null || latestToolFailed + ? activeToolEntries.map((entry) => entry.id) + : []), + ...trailingRunningCommandEntries.map((entry) => entry.id), + ]); // A bare `/compact` turn is the compaction itself: one compaction row stands in for its prompt // and working indicator, from the moment the turn starts. Likewise an answered "compact before // continuing?" question folds into the compaction it asked for. @@ -2380,6 +2404,27 @@ export function deriveMessagesTimelineRows( if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === timelineEntries.length) { appendWorkingRow(); } + if (trailingRunningCommandEntries.length > 0) { + const anchor = trailingRunningCommandEntries[0]!; + const latest = trailingRunningCommandEntries.at(-1)!; + const groupId = workGroupId(anchor.id); + const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false; + const groupedEntries = trailingRunningCommandEntries.map((entry) => entry.entry); + nextRows.push({ + kind: "work-live", + id: LIVE_ACTIVITY_ROW_ID, + createdAt: anchor.createdAt, + entry: latest.entry, + groupedEntries, + groupId, + expanded, + active: true, + }); + hasActivityRow = true; + if (expanded) { + nextRows.push(expandedWorkGroupRow(groupId, anchor.createdAt, groupedEntries)); + } + } if ( input.isWorking && input.latestRun?.turnEnded !== true && diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index 676f147a3d7ef..9f073bef70ac0 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -272,7 +272,37 @@ export function genericCommandStatusLabel( ); } -const GENERIC_COMMAND_TITLES = new Set(["Ran command", "Run command", "Command"]); +const GENERIC_COMMAND_TITLES = new Set([ + "ran command", + "run command", + "running command", + "command", + "bash", + "run bash", + "running bash", + "ran bash", + "shell", + "run shell", + "running shell", + "ran shell", + "run_command", + "run run_command", + "running run_command", +]); + +/** Non-generic human summary a provider attached to a command (e.g. Antigravity `toolSummary`). */ +export function commandCustomTitle( + entry: Pick, +): string | null { + if (entry.itemType !== "command_execution") return null; + // The provider's own title, before a client substitutes its translated fallback. + const title = ( + entry.structuredPayload ? entry.structuredPayload.title : entry.toolTitle || entry.label + )?.trim(); + if (!title) return null; + const normalized = normalizeCompactToolLabel(title).toLowerCase(); + return GENERIC_COMMAND_TITLES.has(normalized) ? null : title; +} export function commandlessCommandLabel( entry: Pick< @@ -283,13 +313,7 @@ export function commandlessCommandLabel( resolve: MFunctionType = mFallback, ): string | null { if (entry.itemType !== "command_execution" || entry.command?.trim()) return null; - // The provider's own title, before a client substitutes its translated fallback. - const title = ( - entry.structuredPayload ? entry.structuredPayload.title : entry.toolTitle || entry.label - )?.trim(); - return !title || GENERIC_COMMAND_TITLES.has(normalizeCompactToolLabel(title)) - ? genericCommandStatusLabel(status, resolve) - : null; + return commandCustomTitle(entry) === null ? genericCommandStatusLabel(status, resolve) : null; } export function resolveWorkEntryToolPresentation( diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index e214a51586f4c..cef5a9b08733e 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -652,6 +652,18 @@ export interface AcpAdapterV2Flavor { * Checked before finalizing a settled prompt or its deferred debounce, so the turn waits * through `ACP_OPEN_REPLY_QUIET_LIMIT` instead of closing early. */ + /** + * Tails a running command's live output (and optional human summary) from provider-owned + * storage when the ACP agent does not stream terminal output chunks itself. Complete `stop` + * on command completion or turn end; the adapter awaits the final flush. + */ + readonly tailCommandOutput?: (input: { + readonly sessionId: string; + readonly toolCallId: string; + readonly stop: Deferred.Deferred; + readonly onChunk: (chunk: string) => Effect.Effect; + readonly onTitle: (title: string) => Effect.Effect; + }) => Effect.Effect; readonly hasPendingReply?: (sessionId: string) => Effect.Effect; readonly assertComplete?: Effect.Effect; /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */ @@ -1674,6 +1686,7 @@ interface ActiveAcpTurn { readonly stoppedToolCallIds: Set; readonly toolUpdatesSkipped: Map; readonly toolStartedAt: Map; + readonly commandOutputTitles: Map; readonly subagents: Map; readonly subagentsBySessionId: Map; readonly pendingSubagentNotifications: Map>; @@ -2168,6 +2181,36 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (clientTerminals !== undefined) { yield* Scope.addFinalizer(sessionScope, clientTerminals.disposeAll); } + const commandOutputTails = new Map< + string, + { + readonly context: ActiveAcpTurn; + readonly fiber: Fiber.Fiber; + readonly stop: Deferred.Deferred; + } + >(); + // Waits for the tail's last read so its output lands before the call settles. + const stopCommandOutputTail = (nativeItemId: string) => + Effect.suspend(() => { + const tail = commandOutputTails.get(nativeItemId); + if (tail === undefined) return Effect.void; + commandOutputTails.delete(nativeItemId); + return Deferred.succeed(tail.stop, undefined).pipe( + Effect.andThen(Fiber.await(tail.fiber)), + Effect.asVoid, + ); + }); + const stopTurnCommandOutputTails = (context: ActiveAcpTurn) => + Effect.suspend(() => { + const keys = [...commandOutputTails.entries()].flatMap(([key, tail]) => + tail.context === context ? [key] : [], + ); + return Effect.forEach(keys, stopCommandOutputTail, { discard: true }); + }); + yield* Scope.addFinalizer( + sessionScope, + Effect.forEach([...commandOutputTails.keys()], stopCommandOutputTail, { discard: true }), + ); const sessionScopedId = (sessionId: string, nativeId: string): string => JSON.stringify([sessionId, nativeId]); const embeddedTerminalsByToolCallId = new Map< @@ -4409,7 +4452,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* closeTextStream(context, "user"); const previous = context.tools.get(incoming.toolCallId); const merged = mergeToolCallState(previous, incoming); - const normalized = flavor.normalizeToolCall?.(merged) ?? merged; + const rawNormalized = flavor.normalizeToolCall?.(merged) ?? merged; + const discoveredTitle = context.commandOutputTitles.get(rawNormalized.toolCallId); + const normalized = + discoveredTitle !== undefined && rawNormalized.title !== discoveredTitle + ? { ...rawNormalized, title: discoveredTitle } + : rawNormalized; const backgroundTaskId = flavor.extractBackgroundTaskId?.(normalized); const backgroundCommandTaskId = flavor.isBackgroundCommandTool?.(normalized) === true @@ -4928,6 +4976,52 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } } + if (turnItem.type === "command_execution") { + if (status !== "pending" && status !== "running") { + yield* stopCommandOutputTail(nativeItemId); + } else if ( + status === "running" && + flavor.tailCommandOutput !== undefined && + !commandOutputTails.has(nativeItemId) + ) { + const stop = yield* Deferred.make(); + const tailCommandOutput = flavor.tailCommandOutput; + const tailedToolCallId = toolCall.toolCallId; + const fiber = yield* tailCommandOutput({ + sessionId: context.nativeThreadId, + toolCallId: tailedToolCallId, + stop, + onChunk: (chunk) => + emitProviderEvent({ + type: "command_output.delta", + driver, + threadId: context.input.threadId, + itemId: turnItem.id, + chunk, + }), + onTitle: Effect.fnUntraced(function* (nextTitle: string) { + const trimmed = nextTitle.trim(); + if (trimmed.length === 0 || context.finalized) return; + context.commandOutputTitles.set(tailedToolCallId, trimmed); + const current = context.tools.get(tailedToolCallId); + if (current === undefined || current.title === trimmed) return; + const currentStatus = toolStatus(current.status); + if (currentStatus !== "pending" && currentStatus !== "running") return; + yield* emitTool(context, { ...current, title: trimmed }); + }), + }).pipe( + Effect.ensuring( + Effect.sync(() => { + if (commandOutputTails.get(nativeItemId)?.stop === stop) { + commandOutputTails.delete(nativeItemId); + } + }), + ), + Effect.forkIn(sessionScope), + ); + commandOutputTails.set(nativeItemId, { context, fiber, stop }); + } + } yield* emitProviderEvent({ type: "turn_item.updated", driver, turnItem }); yield* rearmDeferredFinalize(context); }); @@ -8586,6 +8680,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( terminalizeSubagents: directStopQuarantine, }); } + yield* stopTurnCommandOutputTails(context); yield* closeTextStreams(context); // Ingestion may stop at turn.terminal, before a delayed flush would run. yield* textEmissionPermit.withPermit( @@ -9444,6 +9539,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( stoppedToolCallIds: new Set(), toolUpdatesSkipped: new Map(), toolStartedAt: new Map(), + commandOutputTitles: new Map(), subagents: new Map(), subagentsBySessionId: new Map(), pendingSubagentNotifications: new Map(),