TypeScript
fix: command output streams live while it runs (#15094)
scratchyonea5d97921f6a2
diff --git a/apps/mobile/src/features/threads/thread-command-output.tsx b/apps/mobile/src/features/threads/thread-command-output.tsxnew file mode 100644index 00000000000..6aa31e98f5c--- /dev/null+++ b/apps/mobile/src/features/threads/thread-command-output.tsx@@ -0,0 +1,99 @@+import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";+import { TERMINAL_PALETTES, terminalOutputSpans } from "@t3tools/shared/terminalOutput";+import type React from "react";+import { useMemo, useRef } from "react";+import { ScrollView, View } from "react-native";++import { AppText as Text } from "../../components/AppText";+import { useServerConfigs } from "../../state/entities";+import { orchestrationEnvironment } from "../../state/orchestration";+import { useEnvironmentQuery } from "../../state/query";++// Within this many points of the end still counts as following the output.+const FOLLOW_SLACK = 8;++/** True when the environment streams command output; older servers only return final output. */+export function useCommandOutputStreaming(environmentId: EnvironmentId): boolean {+ return (+ useServerConfigs().get(environmentId)?.environment.capabilities.commandOutputStreaming === true+ );+}++/**+ * Output of one expanded command row: streams while the command runs, then+ * shows its final output. Mount it only when `useCommandOutputStreaming` holds.+ * It subscribes only while mounted, so collapsed rows and other threads receive nothing.+ */+export function ThreadCommandOutput(props: {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+ readonly itemId: TurnItemId;+ readonly themeAppearance: "light" | "dark";+}) {+ const { data, error } = useEnvironmentQuery(+ orchestrationEnvironment.v2.commandOutput({+ environmentId: props.environmentId,+ input: { threadId: props.threadId, itemId: props.itemId },+ }),+ );+ const scrollRef = useRef<React.ComponentRef<typeof ScrollView>>(null);+ // Follow new output until the reader scrolls up; scrolling back down resumes.+ const followRef = useRef(true);+ const text = data?.output.text ?? "";+ const spans = useMemo(+ () => terminalOutputSpans(text, TERMINAL_PALETTES[props.themeAppearance]),+ [text, props.themeAppearance],+ );+ if (text.length === 0) {+ const message = error+ ? `Couldn't load output: ${error}`+ : data === null+ ? "Loading output…"+ : data.running+ ? null+ : "No output.";+ return message === null ? null : (+ <Text className="pt-1.5 font-mono text-2xs leading-normal text-foreground-muted">+ {message}+ </Text>+ );+ }+ return (+ <View className="pt-1.5">+ {data?.output.truncated ? (+ <Text className="pb-0.5 text-3xs text-foreground-subtle">Earlier output not shown</Text>+ ) : null}+ <ScrollView+ ref={scrollRef}+ nestedScrollEnabled+ directionalLockEnabled+ showsVerticalScrollIndicator+ className="max-h-60"+ contentContainerStyle={{ paddingRight: 8 }}+ scrollEventThrottle={100}+ onScroll={(event) => {+ const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;+ followRef.current =+ contentSize.height - contentOffset.y - layoutMeasurement.height <= FOLLOW_SLACK;+ }}+ onContentSizeChange={() => {+ if (followRef.current) scrollRef.current?.scrollToEnd({ animated: false });+ }}+ >+ <Text selectable className="font-mono text-2xs leading-normal text-foreground-muted">+ {spans.map((span, index) =>+ span.style === null ? (+ span.text+ ) : (+ // Spans are rebuilt from scratch on every update and never reorder.+ // oxlint-disable-next-line react/no-array-index-key+ <Text key={index} style={span.style}>+ {span.text}+ </Text>+ ),+ )}+ </Text>+ </ScrollView>+ </View>+ );+}diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsxindex a7b076ed686..fb80358b787 100644--- a/apps/mobile/src/features/threads/thread-work-log.tsx+++ b/apps/mobile/src/features/threads/thread-work-log.tsx@@ -8,6 +8,7 @@ import {WorkLogPressable,} from "./work-log-layout";import { QuestionAnswerHistory } from "./QuestionAnswerHistory";+import { ThreadCommandOutput, useCommandOutputStreaming } from "./thread-command-output";import {getQuestionAnswerPreview,hasQuestionAnswer,@@ -901,8 +902,12 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow() {const { row, expanded } = props;const navigation = useNavigation();+ // Command rows stream their output, including the final output, from the server.+ const streamsOutput =+ useCommandOutputStreaming(props.environmentId) &&+ row.projectedItem.item.type === "command_execution";const fetchedDetail = useTurnItemDetail(- expanded && row.fetchesDetail+ expanded && row.fetchesDetail && !streamsOutput? { environmentId: props.environmentId, row: row.projectedItem }: null,);@@ -1014,20 +1019,27 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(: null;const outputImages = expanded && fetchedItem ? turnItemOutputImages(fetchedItem) : [];const viewedImagePath = workEntryViewedImagePath(row.workEntry);- const fetchedOutput = !expanded- ? null- : shownItem.type === "file_search" || shownItem.type === "web_search"- ? turnItemOutputText(shownItem)- : fetchedItem- ? (turnItemOutputText(fetchedItem) ??- (outputImages.length > 0 || viewedImagePath ? null : "No output."))- : fetchedDetail.error- ? `Couldn't load output: ${fetchedDetail.error}`- : row.fetchesDetail- ? fetchedDetail.data- ? "Output is no longer available."- : "Loading output…"- : null;+ const fetchedOutput =+ !expanded || streamsOutput+ ? null+ : shownItem.type === "file_search" || shownItem.type === "web_search"+ ? turnItemOutputText(shownItem)+ : fetchedItem+ ? (turnItemOutputText(fetchedItem) ??+ (outputImages.length > 0 || viewedImagePath ? null : "No output."))+ : fetchedDetail.error+ ? `Couldn't load output: ${fetchedDetail.error}`+ : row.fetchesDetail+ ? fetchedDetail.data+ ? "Output is no longer available."+ : "Loading output…"+ : null;+ const exitLine =+ failedExitCode === null ? null : (+ <Text className="mt-1.5 font-mono text-2xs leading-normal text-danger-foreground">+ exit {failedExitCode}+ </Text>+ );const toolPresentation = resolveWorkEntryToolPresentation(row.workEntry);const previewText = workEntryRowLabel(row.workEntry);const answerPreview = row.workEntry.questionAnswer@@ -1274,12 +1286,19 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow({fetchedOutput}</Text>) : null}- {failedExitCode !== null ? (- <Text className="mt-1.5 font-mono text-2xs leading-normal text-danger-foreground">- exit {failedExitCode}- </Text>- ) : null}+ {streamsOutput ? null : exitLine}</ScrollView>+ {streamsOutput ? (+ <>+ <ThreadCommandOutput+ environmentId={props.environmentId}+ threadId={row.projectedItem.sourceThreadId}+ itemId={row.projectedItem.sourceItemId}+ themeAppearance={props.themeAppearance}+ />+ {exitLine}+ </>+ ) : null}</Animated.View>) : null}</Animated.View>diff --git a/apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts b/apps/server/scripts/record-claude-agent-sdk-replay-fixture.tsindex a509ed8c88d..4cccf8b109b 100644--- a/apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts+++ b/apps/server/scripts/record-claude-agent-sdk-replay-fixture.ts@@ -52,6 +52,7 @@ import {TOOL_CALL_READ_ONLY_WORKSPACE_ROOT,TOOL_CALL_WRITE_PROMPT,TURN_INTERRUPT_MID_TOOL_PROMPT,+ COMMAND_OUTPUT_STREAMING_PROMPT,TURN_INTERRUPT_PROMPT,TURN_INTERRUPT_RECOVERY_PROMPT,WORKSPACE_NEVER_POLICY,@@ -115,6 +116,12 @@ const CLAUDE_RECORDINGS = {queryMode: "active_steering",enableTools: true,},+ command_output_streaming: {+ prompts: [COMMAND_OUTPUT_STREAMING_PROMPT],+ defaultTranscriptFile: "fixtures/command_output_streaming/claude_transcript.ndjson",+ queryMode: "streaming",+ enableTools: true,+ },turn_interrupt_mid_tool: {prompts: [TURN_INTERRUPT_MID_TOOL_PROMPT],defaultTranscriptFile: "fixtures/turn_interrupt_mid_tool/claude_transcript.ndjson",diff --git a/apps/server/scripts/record-codex-app-server-replay-fixture.ts b/apps/server/scripts/record-codex-app-server-replay-fixture.tsindex 0d18e917e03..e8ecb9ce2d9 100644--- a/apps/server/scripts/record-codex-app-server-replay-fixture.ts+++ b/apps/server/scripts/record-codex-app-server-replay-fixture.ts@@ -58,6 +58,7 @@ import {TODO_LIST_PROMPT,TOOL_CALL_WRITE_PROMPT,TURN_INTERRUPT_MID_TOOL_PROMPT,+ COMMAND_OUTPUT_STREAMING_PROMPT,TURN_INTERRUPT_PROMPT,WEB_SEARCH_PROMPT,} from "../src/orchestration-v2/testkit/fixtures/shared.ts";@@ -98,6 +99,7 @@ const SCENARIO_NAMES = ["message_steering","turn_interrupt","turn_interrupt_mid_tool",+ "command_output_streaming","thread_rollback","thread_rollback_after_restart","thread_rollback_to_stopped_turn",@@ -768,6 +770,29 @@ function scenarios(): ReadonlyArray<ReplayScenario> {},],},+ {+ name: "command_output_streaming",+ fileName: "command_output_streaming.ndjson",+ description: "One command prints over several seconds, so Codex streams its output deltas.",+ runs: [+ {+ name: "command-output-streaming",+ description: "Run a foreground command that prints a line a second.",+ prompt: COMMAND_OUTPUT_STREAMING_PROMPT,+ turnDefaults: {+ approvalPolicy: "never",+ sandboxPolicy: workspaceWriteSandbox(),+ },+ steps: [+ {+ type: "turn",+ label: "command-output-streaming",+ prompt: COMMAND_OUTPUT_STREAMING_PROMPT,+ },+ ],+ },+ ],+ },{name: "thread_rollback",fileName: "thread_rollback.ndjson",diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 986a8c05f43..b9b7f1e5999 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -59,6 +59,7 @@ export const RPC_REQUIRED_SCOPES = {[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,+ [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: AuthOrchestrationReadScope,[WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope,[WS_METHODS.serverProbe]: AuthOrchestrationReadScope,[WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex 71464911d6f..4667be737bb 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -248,6 +248,7 @@ export const make = Effect.gen(function* () {threadActiveReorder: true,threadAutoSettleOptOut: true,threadTitleRegeneration: true,+ commandOutputStreaming: true,threadVisitedTracking: true,threadPullRequests: true,threadPullRequestWatch: true,diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 00009c59eca..6b05224313e 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -30,6 +30,7 @@ const RPC_AGGREGATES = {[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: "orchestrationV2",[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: "orchestrationV2",+ [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: "orchestrationV2",[WS_METHODS.projectsMutate]: "orchestration",[WS_METHODS.serverProbe]: "server",[WS_METHODS.serverGetConfig]: "server",diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.tsindex 9f75ffb90ee..ef03f2700ad 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts@@ -21,7 +21,9 @@ import * as Crypto from "effect/Crypto";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";+import * as Path from "effect/Path";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";@@ -31,6 +33,7 @@ import {resolveClaudeSdkExecutablePath,} from "../../provider/Drivers/ClaudeExecutable.ts";import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts";+import { claudeTaskOutputRoot } from "./ClaudeTaskOutputTail.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import { ProviderAdapterDriverCreateError } from "@t3tools/provider-core/server/adapterDriver";import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";@@ -998,6 +1001,52 @@ function layerClaudeAgentSdkReplay();}+/**+ * While a foreground Bash call runs, Claude Code writes its output to a task+ * file the adapter tails. A replay has no Claude Code process, so it writes the+ * file each recorded `task_started` names, holding that call's recorded output,+ * under a scenario-owned `CLAUDE_CODE_TMPDIR`.+ */+const writeReplayTaskOutputFiles = Effect.fn("ClaudeReplay.writeTaskOutputFiles")(function* (+ transcript: ClaudeAgentSdkReplayTranscript,+) {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const tmpRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-replay-tasks-" });+ const frames = transcript.entries.flatMap((entry) =>+ entry.type === "emit_inbound" && typeof entry.frame === "object" && entry.frame !== null+ ? [entry.frame as Record<string, unknown>]+ : [],+ );+ const outputByToolUseId = new Map<string, string>();+ for (const frame of frames) {+ const result = frame.tool_use_result as Record<string, unknown> | undefined;+ const content = (frame.message as { readonly content?: unknown } | undefined)?.content;+ if (typeof result?.stdout !== "string" || !Array.isArray(content)) continue;+ const toolResult = content.find(+ (block): block is { readonly tool_use_id: string } =>+ block?.type === "tool_result" && typeof block.tool_use_id === "string",+ );+ if (toolResult === undefined) continue;+ const stderr = typeof result.stderr === "string" ? result.stderr : "";+ outputByToolUseId.set(toolResult.tool_use_id, `${result.stdout}${stderr}`);+ }+ const root = claudeTaskOutputRoot({ CLAUDE_CODE_TMPDIR: tmpRoot }, path);+ for (const frame of frames) {+ if (frame.type !== "system" || frame.subtype !== "task_started") continue;+ if (frame.task_type !== "local_bash" || frame.is_backgrounded !== false) continue;+ const output =+ typeof frame.tool_use_id === "string" ? outputByToolUseId.get(frame.tool_use_id) : undefined;+ if (root === undefined || output === undefined || typeof frame.session_id !== "string") {+ continue;+ }+ const tasks = path.join(root, "replay-project", frame.session_id, "tasks");+ yield* fileSystem.makeDirectory(tasks, { recursive: true });+ yield* fileSystem.writeFileString(path.join(tasks, `${String(frame.task_id)}.output`), output);+ }+ return tmpRoot;+});+function layerClaudeProviderAdapterRegistryReplay(transcript: ClaudeAgentSdkReplayTranscript,options: {@@ -1009,14 +1058,23 @@ function layerClaudeProviderAdapterRegistryReplay(ServerConfig.ServerConfig,makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),).pipe(Layer.provide(NodeServices.layer));- return ProviderAdapterRegistry.layerFromDrivers({- drivers: [ClaudeAdapterV2.ClaudeAdapterV2Driver],- configMap: {- [ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID]: {- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,- },- },- }).pipe(+ return Layer.unwrap(+ writeReplayTaskOutputFiles(transcript).pipe(+ Effect.orDie,+ Effect.map((tmpRoot) =>+ ProviderAdapterRegistry.layerFromDrivers({+ drivers: [ClaudeAdapterV2.ClaudeAdapterV2Driver],+ configMap: {+ [ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID]: {+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,+ environment: [{ name: "CLAUDE_CODE_TMPDIR", value: tmpRoot, sensitive: false }],+ },+ },+ }),+ ),+ Effect.provide(NodeServices.layer),+ ),+ ).pipe(Layer.provide(Layer.mergeAll(layerClaudeAgentSdkReplay(transcript, options),diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 92c3b44ec58..d5a4d16510b 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -1,4 +1,5 @@import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";+import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";import {dynamicToolTitle,formatReadToolLabel,@@ -2233,9 +2234,11 @@ function claudeCommandOutputText(output: ClaudeNativeToolOutput): string {const stdout = Reflect.get(value, "stdout");const stderr = Reflect.get(value, "stderr");if (typeof stdout === "string" || typeof stderr === "string") {- const text = [stdout, stderr]- .filter((part): part is string => typeof part === "string" && part.trim().length > 0)- .join("\n");+ const out = typeof stdout === "string" && stdout.trim().length > 0 ? stdout : "";+ const err = typeof stderr === "string" && stderr.trim().length > 0 ? stderr : "";+ // Claude trims each stream's trailing newline, so stderr may need one to start its line.+ const text =+ out.length > 0 && err.length > 0 && !out.endsWith("\n") ? `${out}\n${err}` : out + err;if (text.length > 0) return text;return output.type === "structured_tool_use_result" && output.fallbackValue !== undefined? claudeSubagentResultText({ type: "content_block", value: output.fallbackValue })@@ -3540,6 +3543,23 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (});const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();const activeTurn = yield* Ref.make<ActiveClaudeTurnContext | null>(null);+ // Foreground Bash calls whose output file is being tailed, by tool_use_id.+ const taskOutputTails = new Map<+ string,+ { readonly fiber: Fiber.Fiber<void>; readonly stop: Deferred.Deferred<void> }+ >();+ const taskOutputRoot = claudeTaskOutputRoot(adapterOptions.environment, path);+ // Waits for the tail's last read so its output lands before the call settles.+ const stopTaskOutputTail = (toolUseId: string) =>+ Effect.suspend(() => {+ const tail = taskOutputTails.get(toolUseId);+ if (tail === undefined) return Effect.void;+ taskOutputTails.delete(toolUseId);+ return Deferred.succeed(tail.stop, undefined).pipe(+ Effect.andThen(Fiber.await(tail.fiber)),+ Effect.asVoid,+ );+ });const sdkMessageLock = yield* Semaphore.make(1);// Survives turn settle: members mostly finish after the launching// turn has ended, and each transition must be emitted exactly once.@@ -5856,6 +5876,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (readonly completedAt: DateTime.Utc;}) {for (const toolCall of input.toolCalls) {+ yield* stopTaskOutputTail(toolCall.nativeItemId);yield* emitToolCallArtifacts(buildToolCallArtifacts({context: input.context,@@ -7321,6 +7342,43 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (if (message.type === "system" && message.subtype === "task_started") {if (isClaudeNonSubagentTask(message)) {+ const tailedCall =+ message.tool_use_id === undefined+ ? undefined+ : findToolCall(context, message.tool_use_id);+ if (+ taskOutputRoot !== undefined &&+ message.task_type === "local_bash" &&+ // Older Claude Code builds omit the flag on foreground calls.+ message.is_backgrounded !== true &&+ tailedCall?.classification.itemType === "command_execution" &&+ !taskOutputTails.has(tailedCall.nativeItemId)+ ) {+ const itemId = idAllocator.derive.turnItemFromProviderItem({+ driver: CLAUDE_PROVIDER,+ nativeItemId: tailedCall.nativeItemId,+ });+ const stop = yield* Deferred.make<void>();+ const fiber = yield* tailClaudeTaskOutput({+ root: taskOutputRoot,+ sessionId: message.session_id,+ taskId: message.task_id,+ stop,+ onChunk: (chunk) =>+ emitProviderEvent({+ type: "command_output.delta",+ driver: CLAUDE_PROVIDER,+ threadId: tailedCall.threadId,+ itemId,+ chunk,+ }),+ }).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.forkIn(sessionScope),+ );+ taskOutputTails.set(tailedCall.nativeItemId, { fiber, stop });+ }context.ignoredTaskIds.add(message.task_id);yield* applyBackgroundTaskRosterMessage({nativeThreadId: liveQuery.nativeThreadId,@@ -7654,6 +7712,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (updatedAt: completedAt,presentation: toolCall.presentation,});+ yield* stopTaskOutputTail(toolCall.nativeItemId);yield* emitToolCallArtifacts(artifacts);toolCallsFor(context, toolCall).delete(toolCall.nativeItemId);// A subagent's task tools must not replace the parent's list.diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.tsnew file mode 100644index 00000000000..bca0e457054--- /dev/null+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts@@ -0,0 +1,126 @@+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 { tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts";++const SESSION_ID = "0c91bb28-9e89-4889-bd22-3de9880233d3";+const TASK_ID = "bk6xreeye";++// Claude Code's layout: <root>/<project>/<session_id>/tasks/<task_id>.output.+const makeTaskFile = Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-task-output-" });+ const tasks = path.join(root, "-private-tmp-project", SESSION_ID, "tasks");+ return { root, tasks, file: path.join(tasks, `${TASK_ID}.output`) };+});++// Live clock and a real file: this proves the tail follows the writer, which+// TestClock cannot interleave with filesystem IO.+describe("tailClaudeTaskOutput", () => {+ it.live("follows a file that appears after the task starts, across split characters", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const { root, tasks, file } = yield* makeTaskFile;+ const chunks = yield* Queue.unbounded<string>();+ yield* tailClaudeTaskOutput({+ root,+ sessionId: SESSION_ID,+ taskId: TASK_ID,+ stop: yield* Deferred.make<void>(),+ onChunk: (chunk) => Queue.offer(chunks, chunk),+ }).pipe(Effect.forkScoped);++ yield* fileSystem.makeDirectory(tasks, { recursive: true });+ // "é" is two bytes; the first write ends between them.+ const encoded = new TextEncoder().encode("café 1\n");+ yield* fileSystem.writeFile(file, encoded.subarray(0, 4));+ assert.equal(yield* Queue.take(chunks), "caf");++ yield* fileSystem.writeFile(file, encoded);+ assert.equal(yield* Queue.take(chunks), "é 1\n");+ }),+ ).pipe(Effect.provide(NodeServices.layer)),+ );++ it.live("skips ahead when the command writes faster than it is read", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const { root, tasks, file } = yield* makeTaskFile;+ yield* fileSystem.makeDirectory(tasks, { recursive: true });+ yield* fileSystem.writeFileString(file, "start\n");+ const chunks = yield* Queue.unbounded<string>();+ yield* tailClaudeTaskOutput({+ root,+ sessionId: SESSION_ID,+ taskId: TASK_ID,+ stop: yield* Deferred.make<void>(),+ onChunk: (chunk) => Queue.offer(chunks, chunk),+ }).pipe(Effect.forkScoped);+ assert.equal(yield* Queue.take(chunks), "start\n");++ yield* fileSystem.writeFileString(file, `start\n${"y\n".repeat(1_000_000)}end\n`);+ const flooded = yield* Queue.take(chunks);+ assert.isAtMost(flooded.length, 256 * 1024 + 1);+ assert.isTrue(flooded.startsWith("\n"));+ assert.isTrue(flooded.endsWith("y\nend\n"));+ }),+ ).pipe(Effect.provide(NodeServices.layer)),+ );++ it.live("reads what was written last when the tool result stops it", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const { root, tasks, file } = yield* makeTaskFile;+ yield* fileSystem.makeDirectory(tasks, { recursive: true });+ yield* fileSystem.writeFileString(file, "one\n");+ const chunks: Array<string> = [];+ const stop = yield* Deferred.make<void>();+ const first = yield* Deferred.make<void>();+ const fiber = yield* tailClaudeTaskOutput({+ root,+ sessionId: SESSION_ID,+ taskId: TASK_ID,+ stop,+ onChunk: (chunk) =>+ Effect.sync(() => chunks.push(chunk)).pipe(+ Effect.andThen(Deferred.succeed(first, undefined)),+ ),+ }).pipe(Effect.forkScoped);+ yield* Deferred.await(first);+ // Written right before the command exits, then the result arrives.+ yield* fileSystem.writeFileString(file, "one\ntwo\n");+ yield* Deferred.succeed(stop, undefined);+ yield* Fiber.join(fiber);+ assert.deepEqual(chunks, ["one\n", "two\n"]);+ }).pipe(Effect.provide(NodeServices.layer)),+ ),+ );++ it.live("ends when stopped even if Claude Code never wrote the file", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const { root } = yield* makeTaskFile;+ const stop = yield* Deferred.make<void>();+ const fiber = yield* tailClaudeTaskOutput({+ root,+ sessionId: SESSION_ID,+ taskId: TASK_ID,+ stop,+ onChunk: () => Effect.die("no file, no output"),+ }).pipe(Effect.forkScoped);+ yield* Deferred.succeed(stop, undefined);+ yield* Fiber.join(fiber);+ }).pipe(Effect.provide(NodeServices.layer)),+ ),+ );+});diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.tsnew file mode 100644index 00000000000..fbe759e973a--- /dev/null+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts@@ -0,0 +1,123 @@+import * as Deferred from "effect/Deferred";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Path from "effect/Path";++/**+ * Live output for a foreground Claude Bash call.+ *+ * The Agent SDK sends no stdout until the tool result. Claude Code does write+ * each running command's combined output to+ * `<tmp>/claude-<uid>/<project>/<session_id>/tasks/<task_id>.output`, naming+ * the task in its `task_started` frame (`task_type: "local_bash"`). This path is+ * Claude Code's private layout, not SDK API, so every step degrades to "no live+ * output": the row still gets its full output from the tool result.+ */++/** How often the file is checked while its command runs. */+const CLAUDE_TASK_OUTPUT_POLL_MS = 250;+/** Give up looking for a file Claude Code never wrote (a newer layout, or Windows). */+const MAX_LOCATE_ATTEMPTS = 40;+/** Bytes read per poll. A faster writer skips ahead: only the tail is shown anyway. */+const MAX_READ_BYTES = 256 * 1024;++/** Claude Code's per-user temp root, or none where it has no uid (Windows). */+export function claudeTaskOutputRoot(+ environment: Readonly<Record<string, string | undefined>> | undefined,+ path: Path.Path,+): string | undefined {+ const uid = process.getuid?.();+ if (uid === undefined) return undefined;+ const base = environment?.CLAUDE_CODE_TMPDIR?.trim() || "/tmp";+ return path.join(base, `claude-${uid}`);+}++const locate = Effect.fn("ClaudeTaskOutputTail.locate")(function* (input: {+ readonly root: string;+ readonly sessionId: string;+ readonly taskId: string;+}) {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const projects = yield* fileSystem.readDirectory(input.root).pipe(Effect.orElseSucceed(() => []));+ for (const project of projects) {+ const candidate = path.join(+ input.root,+ project,+ input.sessionId,+ "tasks",+ `${input.taskId}.output`,+ );+ if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {+ return Option.some(candidate);+ }+ }+ return Option.none<string>();+});++/**+ * Reads appended output until `stop` completes, then reads once more so the+ * last bytes written before the command exited still reach live viewers. The+ * caller completes `stop` when the tool result arrives or the turn ends, and+ * awaits the returned effect.+ */+export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(function* (input: {+ readonly root: string;+ readonly sessionId: string;+ readonly taskId: string;+ readonly stop: Deferred.Deferred<void>;+ readonly onChunk: (chunk: string) => Effect.Effect<void>;+}) {+ const fileSystem = yield* FileSystem.FileSystem;+ // True once stopped: the next read is the last.+ const pause = Effect.raceFirst(+ Effect.sleep(CLAUDE_TASK_OUTPUT_POLL_MS).pipe(Effect.as(false)),+ Deferred.await(input.stop).pipe(Effect.as(true)),+ );+ let file = Option.none<string>();+ for (let attempt = 0; Option.isNone(file); attempt += 1) {+ file = yield* locate(input);+ if (Option.isSome(file)) break;+ if (attempt + 1 >= MAX_LOCATE_ATTEMPTS || (yield* pause)) return;+ }+ const filePath = file.value;+ // `stream: true` keeps a multi-byte character split across reads intact;+ // invalid bytes become U+FFFD.+ let decoder = new TextDecoder("utf-8", { fatal: false });+ let offset = 0;+ let last = yield* Deferred.isDone(input.stop);+ while (true) {+ const size = yield* fileSystem.stat(filePath).pipe(+ Effect.map((info) => Number(info.size)),+ Effect.orElseSucceed(() => offset),+ );+ if (size < offset) offset = 0;+ if (size > offset) {+ const start = size - offset > MAX_READ_BYTES ? size - MAX_READ_BYTES : offset;+ const bytes = yield* Effect.scoped(+ Effect.gen(function* () {+ const handle = yield* fileSystem.open(filePath, { flag: "r" });+ yield* handle.seek(BigInt(start), "start");+ return yield* handle.readAlloc(size - start);+ }),+ ).pipe(Effect.orElseSucceed(() => Option.none<Uint8Array>()));+ if (Option.isSome(bytes)) {+ // Skipped output must not splice two unrelated lines together.+ const skipped = start > offset;+ // Bytes held from before the gap belong to a character we never finished reading.+ if (skipped) decoder = new TextDecoder("utf-8", { fatal: false });+ offset = start + bytes.value.byteLength;+ const text = (skipped ? "\n" : "") + decoder.decode(bytes.value, { stream: true });+ if (text.length > 0) yield* input.onChunk(text);+ }+ }+ if (last) {+ // A command that ended mid-character still shows a replacement character.+ const rest = decoder.decode();+ if (rest.length > 0) yield* input.onChunk(rest);+ return;+ }+ last = yield* pause;+ }+});diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex 7f55417ea2a..72d8f93cecf 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -4324,6 +4324,27 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}),);+ yield* client.handleServerNotification("item/commandExecution/outputDelta", (payload) =>+ Effect.gen(function* () {+ // A delta always follows its item/started, so the turn is already+ // known; background commands keep printing after it settles.+ const context =+ (yield* Ref.get(activeTurns)).get(payload.turnId) ??+ (yield* Ref.get(settledTurns)).get(payload.turnId);+ if (context === undefined) return;+ yield* emitProviderEvent({+ type: "command_output.delta",+ driver: CODEX_PROVIDER,+ threadId: context.projectionThreadId,+ itemId: idAllocator.derive.turnItemFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: payload.itemId,+ }),+ chunk: payload.delta,+ });+ }),+ );+yield* client.handleServerNotification("item/reasoning/summaryTextDelta", (payload) =>appendReasoning(payload, "summary", payload.summaryIndex),);diff --git a/apps/server/src/orchestration-v2/CommandOutputHub.test.ts b/apps/server/src/orchestration-v2/CommandOutputHub.test.tsnew file mode 100644index 00000000000..9ec21bacd79--- /dev/null+++ b/apps/server/src/orchestration-v2/CommandOutputHub.test.ts@@ -0,0 +1,461 @@+import { assert, it } from "@effect/vitest";+import {+ type ModelSelection,+ type OrchestrationV2AppThread,+ type OrchestrationV2CommandOutputFrame,+ type OrchestrationV2TurnItem,+ ProviderDriverKind,+ ProviderInstanceId,+ type ThreadId,+ TurnItemId,+} from "@t3tools/contracts";+import {+ appendTerminalOutput,+ EMPTY_TERMINAL_OUTPUT,+ normalizeTerminalOutput,+ TERMINAL_OUTPUT_TAIL_CHARS,+ type TerminalOutputState,+} from "@t3tools/shared/terminalOutput";+import * as Clock from "effect/Clock";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Queue from "effect/Queue";+import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";++import * as SqlitePersistence from "../persistence/Sqlite.ts";+import * as CommandOutputHub from "./CommandOutputHub.ts";+import * as EventSink from "./EventSink.ts";+import * as EventStore from "./EventStore.ts";+import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";+import * as ProjectionStore from "./ProjectionStore.ts";++const layerTestDatabase = SqlitePersistence.layerMemory;+const layerTestStores = Layer.merge(EventStore.layer, ProjectionStore.layer).pipe(+ Layer.provide(layerTestDatabase),+);+const layerTestEventSink = EventSink.layer.pipe(+ Layer.provide(Layer.mergeAll(layerTestStores, layerTestDatabase)),+);+const layerTest = Layer.mergeAll(+ layerTestEventSink,+ IdAllocator.layer,+ CommandOutputHub.layer.pipe(Layer.provide(Layer.merge(layerTestEventSink, layerTestStores))),+);++const modelSelection = {+ instanceId: ProviderInstanceId.make("codex"),+ model: "gpt-5.4",+} satisfies ModelSelection;+const CODEX_DRIVER = ProviderDriverKind.make("codex");+const ITEM_ID = TurnItemId.make("turn-item:command");++/** What a client holds after applying frames, using the same shared normalizer. */+function applyFrame(+ state: TerminalOutputState,+ frame: OrchestrationV2CommandOutputFrame,+): TerminalOutputState {+ return frame.kind === "replace"+ ? appendTerminalOutput({ ...EMPTY_TERMINAL_OUTPUT, truncated: frame.truncated }, frame.text)+ : appendTerminalOutput(state, frame.text);+}++const seedThread = Effect.gen(function* () {+ const idAllocator = yield* IdAllocator.IdAllocatorV2;+ const eventSink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const projectId = yield* idAllocator.allocate.project({ fixtureName: "command-output" });+ const threadId = yield* idAllocator.allocate.thread({ fixtureName: "command-output", projectId });+ const thread: OrchestrationV2AppThread = {+ createdBy: "user",+ creationSource: "web",+ id: threadId,+ projectId,+ title: "Command output",+ providerInstanceId: modelSelection.instanceId,+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ branchPullRequest: null,+ activeOrderKey: null,+ activeProviderThreadId: null,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ };+ yield* eventSink.write({+ events: [+ {+ id: yield* idAllocator.allocate.event({ threadId }),+ type: "thread.created",+ threadId,+ occurredAt: now,+ payload: thread,+ },+ ],+ });+ return threadId;+});++const writeCommandItem = (+ threadId: ThreadId,+ fields: Pick<+ Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,+ "status" | "output" | "exitCode"+ >,+) =>+ Effect.gen(function* () {+ const idAllocator = yield* IdAllocator.IdAllocatorV2;+ const eventSink = yield* EventSink.EventSinkV2;+ const now = yield* DateTime.now;+ const settled = fields.status !== "running";+ const item: OrchestrationV2TurnItem = {+ id: ITEM_ID,+ threadId,+ runId: null,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ title: null,+ startedAt: now,+ completedAt: settled ? now : null,+ updatedAt: now,+ type: "command_execution",+ input: "yes | head -n 1000000",+ ...fields,+ };+ yield* eventSink.write({+ events: [+ {+ id: yield* idAllocator.allocate.event({ threadId }),+ type: "turn-item.updated",+ threadId,+ driver: CODEX_DRIVER,+ providerInstanceId: modelSelection.instanceId,+ occurredAt: now,+ payload: item,+ },+ ],+ });+ });++/** Collect frames into a queue so the test takes them one receipt at a time. */+const subscribeFrames = (threadId: ThreadId) =>+ Effect.gen(function* () {+ const hub = yield* CommandOutputHub.CommandOutputHub;+ const frames = yield* Queue.unbounded<OrchestrationV2CommandOutputFrame | "ended">();+ yield* hub.subscribe({ threadId, itemId: ITEM_ID }).pipe(+ Stream.runForEach((frame) => Queue.offer(frames, frame)),+ Effect.andThen(Queue.offer(frames, "ended")),+ Effect.forkScoped,+ );+ return frames;+ });++const takeFrame = (frames: Queue.Queue<OrchestrationV2CommandOutputFrame | "ended">) =>+ Queue.take(frames).pipe(+ Effect.flatMap((frame) =>+ frame === "ended" ? Effect.die("command output stream ended early") : Effect.succeed(frame),+ ),+ );++const layer = it.layer(layerTest);++layer("CommandOutputHub", (it) => {+ it.effect(+ "a late subscriber gets the running tail, then live appends, then the final output",+ () =>+ Effect.scoped(+ Effect.gen(function* () {+ const hub = yield* CommandOutputHub.CommandOutputHub;+ const threadId = yield* seedThread;+ yield* writeCommandItem(threadId, { status: "running" });+ // Output that arrived before anyone looked, ending mid-escape and mid-redraw.+ yield* hub.append({+ threadId,+ itemId: ITEM_ID,+ chunk: "\u001b[32mbuilding\u001b[0m\n10%",+ });+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r55%\u001b[3" });++ const frames = yield* subscribeFrames(threadId);+ const first = yield* takeFrame(frames);+ assert.equal(first.kind, "replace");+ assert.isTrue(first.running);+ let client = applyFrame(EMPTY_TERMINAL_OUTPUT, first);+ assert.equal(client.text, "\u001b[0;32mbuilding\u001b[0m\n55%");++ // Chunks that land between frames arrive together in one append.+ yield* TestClock.adjust("1 second");+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "1m" });+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r100%\u001b[0m\ndone\n" });+ const append = yield* takeFrame(frames);+ assert.equal(append.kind, "append");+ client = applyFrame(client, append);+ assert.equal(+ client.text,+ normalizeTerminalOutput(+ "\u001b[32mbuilding\u001b[0m\n10%\r55%\u001b[31m\r100%\u001b[0m\ndone\n",+ ).text,+ );++ // The persisted item settles the row; its output is what the client keeps.+ yield* TestClock.adjust("1 second");+ yield* writeCommandItem(threadId, {+ status: "completed",+ exitCode: 0,+ output: "building\n100%\ndone\n",+ });+ const final = yield* takeFrame(frames);+ assert.deepEqual(final, {+ kind: "replace",+ text: "building\n100%\ndone\n",+ truncated: false,+ running: false,+ });+ assert.equal(yield* Queue.take(frames), "ended");+ }),+ ),+ );++ it.effect("a row that is not a known command fails instead of waiting forever", () =>+ Effect.gen(function* () {+ const hub = yield* CommandOutputHub.CommandOutputHub;+ const threadId = yield* seedThread;+ const error = yield* hub+ .subscribe({ threadId, itemId: ITEM_ID })+ .pipe(Stream.runDrain, Effect.flip);+ assert.equal(error._tag, "OrchestrationV2CommandOutputError");+ assert.equal(error.message, "No such command.");+ }),+ );++ it.effect("a viewer whose command was evicted for newer ones is resynced, not appended to", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const hub = yield* CommandOutputHub.CommandOutputHub;+ const threadId = yield* seedThread;+ yield* writeCommandItem(threadId, { status: "running" });+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "abc" });+ const frames = yield* subscribeFrames(threadId);+ let client = applyFrame(EMPTY_TERMINAL_OUTPUT, yield* takeFrame(frames));+ assert.equal(client.text, "abc");+ // 64 newer commands push this one's tail out of the hub.+ for (let index = 0; index < 64; index += 1) {+ yield* hub.append({+ threadId,+ itemId: TurnItemId.make(`turn-item:other-${index}`),+ chunk: "x",+ });+ }+ yield* TestClock.adjust("1 second");+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\rX" });+ const next = yield* takeFrame(frames);+ assert.equal(next.kind, "replace");+ client = applyFrame(client, next);+ assert.equal(client.text, "X");+ }),+ ),+ );++ it.effect("every viewer of one command reconstructs the same text", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const hub = yield* CommandOutputHub.CommandOutputHub;+ const threadId = yield* seedThread;+ yield* writeCommandItem(threadId, { status: "running" });+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "first\n" });+ const viewers = [yield* subscribeFrames(threadId), yield* subscribeFrames(threadId)];+ const states = [EMPTY_TERMINAL_OUTPUT, EMPTY_TERMINAL_OUTPUT];+ for (const [index, frames] of viewers.entries()) {+ states[index] = applyFrame(states[index]!, yield* takeFrame(frames));+ }+ yield* TestClock.adjust("1 second");+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "second\r\nthird" });+ for (const [index, frames] of viewers.entries()) {+ states[index] = applyFrame(states[index]!, yield* takeFrame(frames));+ }+ assert.equal(states[0]!.text, "first\nsecond\nthird");+ assert.equal(states[1]!.text, states[0]!.text);+ }),+ ),+ );++ it.effect("a flood is sent as bounded tails at a slower rate, not as every chunk", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const hub = yield* CommandOutputHub.CommandOutputHub;+ const threadId = yield* seedThread;+ yield* writeCommandItem(threadId, { status: "running" });+ const stamped = yield* Queue.unbounded<{+ readonly frame: OrchestrationV2CommandOutputFrame;+ readonly at: number;+ }>();+ yield* hub.subscribe({ threadId, itemId: ITEM_ID }).pipe(+ Stream.runForEach((frame) =>+ Clock.currentTimeMillis.pipe(+ Effect.flatMap((at) => Queue.offer(stamped, { frame, at })),+ ),+ ),+ Effect.forkScoped,+ );+ let client = applyFrame(EMPTY_TERMINAL_OUTPUT, (yield* Queue.take(stamped)).frame);+ yield* TestClock.adjust("1 second");++ // `yes | head -n 1000000`: 2 MB in 4 KB chunks, 64 KB every 100 ms.+ const chunk = "y\n".repeat(2_048);+ const sent: Array<{+ readonly frame: OrchestrationV2CommandOutputFrame;+ readonly at: number;+ }> = [];+ const drain = Effect.gen(function* () {+ for (const entry of yield* Queue.clear(stamped)) {+ sent.push(entry);+ client = applyFrame(client, entry.frame);+ }+ });+ for (let tick = 0; tick < 32; tick += 1) {+ for (let index = 0; index < 16; index += 1) {+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk });+ }+ yield* TestClock.adjust(CommandOutputHub.COMMAND_OUTPUT_FRAME_INTERVAL_MS);+ yield* drain;+ }+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "tail\n" });+ yield* TestClock.adjust("1 second");+ yield* drain;++ const bytes = sent.reduce((total, { frame }) => total + frame.text.length, 0);+ // 3.2 s of flooding: a frame per chunk would be 512 frames and 2 MB.+ assert.isAtMost(sent.length, 10);+ assert.isAtMost(bytes, 10 * TERMINAL_OUTPUT_TAIL_CHARS);+ for (const { frame } of sent) {+ assert.isAtMost(frame.text.length, TERMINAL_OUTPUT_TAIL_CHARS);+ }+ for (let index = 1; index < sent.length; index += 1) {+ if (sent[index - 1]!.frame.kind === "replace") {+ assert.isAtLeast(+ sent[index]!.at - sent[index - 1]!.at,+ CommandOutputHub.COMMAND_OUTPUT_REPLACE_INTERVAL_MS,+ );+ }+ }+ assert.isTrue(client.truncated);+ assert.isTrue(client.text.endsWith("y\ny\ntail\n"));+ assert.isAtMost(client.text.length, TERMINAL_OUTPUT_TAIL_CHARS);+ }),+ ),+ );++ it.effect("a finished command sends only its bounded final output", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const threadId = yield* seedThread;+ const huge = Array.from({ length: 400_000 }, (_, index) => `line ${index}`).join("\n");+ yield* writeCommandItem(threadId, { status: "failed", exitCode: 1, output: huge });+ const frames = yield* subscribeFrames(threadId);+ const final = yield* takeFrame(frames);+ assert.equal(final.kind, "replace");+ assert.isFalse(final.running);+ assert.isTrue(final.truncated);+ assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);+ assert.isTrue(final.text.endsWith("line 399999"));+ assert.equal(yield* Queue.take(frames), "ended");+ }),+ ),+ );++ it.effect("a finished command whose output is one huge line still shows its tail", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const threadId = yield* seedThread;+ const line = "x".repeat(TERMINAL_OUTPUT_TAIL_CHARS * 8);+ yield* writeCommandItem(threadId, {+ status: "completed",+ exitCode: 0,+ output: `${line}\n`,+ });+ const frames = yield* subscribeFrames(threadId);+ const final = yield* takeFrame(frames);+ assert.equal(final.kind, "replace");+ assert.isTrue(final.truncated);+ assert.isTrue(final.text.includes("xxxx"));+ assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);+ }),+ ),+ );++ it.effect("an old Claude row's raw Bash result shows as its stdout and stderr", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const threadId = yield* seedThread;+ yield* writeCommandItem(threadId, {+ status: "completed",+ exitCode: 0,+ output: '{"stdout":"built","stderr":"1 warning","interrupted":false}',+ });+ const frames = yield* subscribeFrames(threadId);+ const final = yield* takeFrame(frames);+ assert.equal(final.text, "built\n1 warning");+ }),+ ),+ );++ it.effect("providers that only report output in item snapshots still stream", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const threadId = yield* seedThread;+ yield* writeCommandItem(threadId, { status: "running", output: "step 1\n" });+ const frames = yield* subscribeFrames(threadId);+ assert.equal((yield* takeFrame(frames)).text, "step 1\n");+ yield* TestClock.adjust("1 second");+ yield* writeCommandItem(threadId, { status: "running", output: "step 1\nstep 2\n" });+ const update = yield* takeFrame(frames);+ assert.deepEqual(update, {+ kind: "replace",+ text: "step 1\nstep 2\n",+ truncated: false,+ running: true,+ });+ }),+ ),+ );++ it.effect("an interrupted command ends the stream with the output it printed", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const hub = yield* CommandOutputHub.CommandOutputHub;+ const threadId = yield* seedThread;+ yield* writeCommandItem(threadId, { status: "running" });+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "waiting for server\n" });+ const frames = yield* subscribeFrames(threadId);+ yield* takeFrame(frames);+ yield* TestClock.adjust("1 second");+ // Some providers stop a command without reporting its output. The session+ // manager releases the live tail before the settled item is persisted.+ yield* hub.finish({ threadId, itemId: ITEM_ID });+ yield* writeCommandItem(threadId, { status: "interrupted" });+ const final = yield* takeFrame(frames);+ assert.deepEqual(final, {+ kind: "replace",+ text: "waiting for server\n",+ truncated: false,+ running: false,+ });+ assert.equal(yield* Queue.take(frames), "ended");+ }),+ ),+ );+});diff --git a/apps/server/src/orchestration-v2/CommandOutputHub.ts b/apps/server/src/orchestration-v2/CommandOutputHub.tsnew file mode 100644index 00000000000..532a44df601--- /dev/null+++ b/apps/server/src/orchestration-v2/CommandOutputHub.ts@@ -0,0 +1,342 @@+import {+ isOrchestrationV2WorkActive,+ OrchestrationV2CommandOutputError,+ type OrchestrationV2CommandOutputFrame,+ type OrchestrationV2SubscribeCommandOutputInput,+ type OrchestrationV2TurnItem,+} from "@t3tools/contracts";+import {+ appendTerminalOutput,+ EMPTY_TERMINAL_OUTPUT,+ normalizeTerminalOutput,+ type TerminalOutputState,+ TERMINAL_OUTPUT_TAIL_CHARS,+ terminalOutputResumeText,+} from "@t3tools/shared/terminalOutput";+import * as Cause from "effect/Cause";+import * as Clock from "effect/Clock";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Queue from "effect/Queue";+import * as Schema from "effect/Schema";+import * as Stream from "effect/Stream";++import * as EventSink from "./EventSink.ts";+import * as ProjectionStore from "./ProjectionStore.ts";++/**+ * Live command output.+ *+ * Output never becomes an orchestration event. Adapters push raw chunks here+ * (through the session manager), the hub keeps a bounded, normalized tail per+ * running command, and `subscribe` serves one expanded row: the current tail,+ * then coalesced appends, then the persisted final output. Memory is bounded+ * per command and in count, and a client that is not showing the row receives nothing.+ */++/** Fastest a subscriber receives frames while output flows. */+export const COMMAND_OUTPUT_FRAME_INTERVAL_MS = 100;+/** After a subscriber falls behind and is sent the whole tail, it waits this long. */+export const COMMAND_OUTPUT_REPLACE_INTERVAL_MS = 500;+/** Raw text a subscriber may accumulate before it is sent the tail instead. */+const COMMAND_OUTPUT_MAX_APPEND_CHARS = 16 * 1024;+/** Running commands tracked at once; the least recently written is dropped beyond this. */+const MAX_LIVE_COMMANDS = 64;+/** Finished tails kept for a settle that reports no output of its own (an interrupt). */+const MAX_FINISHED_COMMANDS = 16;+/** Final output read from persistence is normalized from at most this many trailing chars. */+const MAX_FINAL_SOURCE_CHARS = TERMINAL_OUTPUT_TAIL_CHARS * 4;++interface Subscriber {+ pendingAppend: string;+ /** The next frame must carry the whole tail. */+ needsReplace: boolean;+ /** `needsReplace` was caused by the subscriber falling behind. */+ overflowed: boolean;+ readonly wake: Queue.Queue<void>;+}++export type CommandOutputTarget = OrchestrationV2SubscribeCommandOutputInput;++export interface CommandOutputHubShape {+ /** Add raw output for a running command. Called for every provider chunk. */+ readonly append: (input: CommandOutputTarget & { readonly chunk: string }) => Effect.Effect<void>;+ /**+ * The command settled. Its tail is kept briefly for a settle that carries no+ * output (an interrupt); otherwise the persisted output is what rows show.+ */+ readonly finish: (input: CommandOutputTarget) => Effect.Effect<void>;+ /** Frames for one row until its command settles; see `OrchestrationV2CommandOutputFrame`. */+ readonly subscribe: (+ input: CommandOutputTarget,+ ) => Stream.Stream<OrchestrationV2CommandOutputFrame, OrchestrationV2CommandOutputError>;+}++export class CommandOutputHub extends Context.Service<CommandOutputHub, CommandOutputHubShape>()(+ "t3/orchestration-v2/CommandOutputHub",+) {}++const isCommandOutputError = Schema.is(OrchestrationV2CommandOutputError);++function commandKey(target: CommandOutputTarget): string {+ return `${target.threadId}\u0000${target.itemId}`;+}++/** Claude Bash rows stored before #15505 hold the raw `{ stdout, stderr, interrupted, ... }` result. */+const decodeLegacyClaudeBashResult = Schema.decodeUnknownOption(+ Schema.fromJsonString(+ Schema.Struct({ stdout: Schema.String, stderr: Schema.String, interrupted: Schema.Boolean }),+ ),+);++function legacyClaudeBashOutput(output: string): string {+ if (!output.trimStart().startsWith('{"stdout"')) return output;+ const parsed = decodeLegacyClaudeBashResult(output);+ if (Option.isNone(parsed)) return output;+ const out = parsed.value.stdout.trim().length > 0 ? parsed.value.stdout : "";+ const err = parsed.value.stderr.trim().length > 0 ? parsed.value.stderr : "";+ return out.length > 0 && err.length > 0 && !out.endsWith("\n") ? `${out}\n${err}` : out + err;+}++/** The output a row shows from a persisted item, bounded before normalization. */+function persistedCommandOutput(output: string | undefined): {+ readonly text: string;+ readonly truncated: boolean;+} {+ if (output === undefined) return { text: "", truncated: false };+ let source = output;+ if (output.length > MAX_FINAL_SOURCE_CHARS) {+ // Start on a fresh line, so the cut can't land inside an escape sequence.+ source = output.slice(output.length - MAX_FINAL_SOURCE_CHARS);+ const newline = source.indexOf("\n");+ if (newline !== -1 && newline + 1 < source.length) source = source.slice(newline + 1);+ }+ const normalized = normalizeTerminalOutput(source);+ return {+ text: normalized.text,+ truncated: normalized.truncated || source.length !== output.length,+ };+}++/** Sets `key` as the newest entry of `map`, dropping the oldest beyond `max`. */+function setBounded<V>(+ map: Map<string, V>,+ key: string,+ value: V,+ max: number,+ onEvict?: (key: string) => void,+): void {+ map.delete(key);+ map.set(key, value);+ if (map.size <= max) return;+ const oldest = map.keys().next().value!;+ map.delete(oldest);+ onEvict?.(oldest);+}++export const make = Effect.gen(function* () {+ const eventSink = yield* EventSink.EventSinkV2;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ // Insertion order doubles as recency: every write re-inserts its entry.+ const tails = new Map<string, TerminalOutputState>();+ const finished = new Map<string, TerminalOutputState>();+ const subscribers = new Map<string, Set<Subscriber>>();++ const wakeAll = (key: string, chunk: string) =>+ Effect.forEach(+ subscribers.get(key) ?? [],+ (subscriber) => {+ if (!subscriber.needsReplace) {+ subscriber.pendingAppend += chunk;+ if (subscriber.pendingAppend.length > COMMAND_OUTPUT_MAX_APPEND_CHARS) {+ subscriber.needsReplace = true;+ subscriber.overflowed = true;+ subscriber.pendingAppend = "";+ }+ }+ return Queue.offer(subscriber.wake, undefined);+ },+ { discard: true },+ );++ const append: CommandOutputHubShape["append"] = ({ chunk, ...target }) =>+ Effect.suspend(() => {+ if (chunk.length === 0) return Effect.void;+ const key = commandKey(target);+ const tail = appendTerminalOutput(tails.get(key) ?? EMPTY_TERMINAL_OUTPUT, chunk);+ setBounded(tails, key, tail, MAX_LIVE_COMMANDS, (oldest) => {+ // Its viewers no longer share the hub's state; resync them on the next frame.+ for (const subscriber of subscribers.get(oldest) ?? []) {+ subscriber.needsReplace = true;+ subscriber.pendingAppend = "";+ }+ });+ return wakeAll(key, chunk);+ });++ const finish: CommandOutputHubShape["finish"] = (target) =>+ Effect.sync(() => {+ const key = commandKey(target);+ const tail = tails.get(key);+ if (tail === undefined) return;+ tails.delete(key);+ setBounded(finished, key, tail, MAX_FINISHED_COMMANDS);+ });++ const subscribe: CommandOutputHubShape["subscribe"] = (target) =>+ Stream.unwrap(+ Effect.gen(function* () {+ const key = commandKey(target);+ const wake = yield* Queue.sliding<void>(1);+ const subscriber: Subscriber = {+ pendingAppend: "",+ needsReplace: true,+ overflowed: false,+ wake,+ };+ // Attach before reading anything, so no chunk falls between a read and the attach.+ const keySubscribers = subscribers.get(key) ?? new Set<Subscriber>();+ keySubscribers.add(subscriber);+ subscribers.set(key, keySubscribers);+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ keySubscribers.delete(subscriber);+ if (keySubscribers.size === 0 && subscribers.get(key) === keySubscribers) {+ subscribers.delete(key);+ }+ }),+ );++ // The persisted item says when the command is done and what it finally printed.+ // Providers that report output only in item snapshots (ACP, Pi) stream through here too.+ let snapshotOutput: string | undefined;+ let lost: Cause.Cause<unknown> | undefined;+ let settled: Extract<OrchestrationV2TurnItem, { type: "command_execution" }> | undefined;+ const observe = (item: OrchestrationV2TurnItem | undefined) =>+ Effect.suspend(() => {+ if (item === undefined || item.type !== "command_execution") return Effect.void;+ if (!isOrchestrationV2WorkActive(item.status)) {+ settled = item;+ } else if (item.output !== undefined && item.output !== snapshotOutput) {+ snapshotOutput = item.output;+ } else {+ return Effect.void;+ }+ subscriber.needsReplace = true;+ return Queue.offer(wake, undefined);+ });+ const fromSequence = yield* eventSink.latestSequence({ threadId: target.threadId });+ yield* eventSink+ .stream({+ threadId: target.threadId,+ afterSequence: fromSequence,+ eventType: "turn-item.updated",+ })+ .pipe(+ Stream.runForEach((stored) =>+ stored.event.type === "turn-item.updated" && stored.event.payload.id === target.itemId+ ? observe(stored.event.payload)+ : Effect.void,+ ),+ // Without its event stream the row can never settle: end with an error+ // instead of waiting forever.+ Effect.catchCause((cause) =>+ Effect.sync(() => {+ lost = cause;+ }).pipe(Effect.andThen(Queue.offer(wake, undefined))),+ ),+ Effect.forkScoped,+ );+ const item = yield* projections.getTurnItem(target);+ // Only command rows have output; anything else would hold a subscription open forever.+ if (item === null || item.type !== "command_execution") {+ return yield* new OrchestrationV2CommandOutputError({+ threadId: target.threadId,+ message: "No such command.",+ });+ }+ yield* observe(item);+ yield* Queue.offer(wake, undefined);++ let lastFrameAt: number | undefined;+ let throttle = COMMAND_OUTPUT_FRAME_INTERVAL_MS;+ const nextFrame = Effect.gen(function* (): Effect.fn.Return<+ OrchestrationV2CommandOutputFrame,+ OrchestrationV2CommandOutputError+ > {+ yield* Queue.take(wake);+ if (lost !== undefined) {+ return yield* new OrchestrationV2CommandOutputError({+ threadId: target.threadId,+ message: "Lost the thread's event stream.",+ cause: Cause.squash(lost),+ });+ }+ const now = yield* Clock.currentTimeMillis;+ if (lastFrameAt !== undefined && now - lastFrameAt < throttle) {+ yield* Effect.sleep(throttle - (now - lastFrameAt));+ }+ lastFrameAt = yield* Clock.currentTimeMillis;+ throttle = COMMAND_OUTPUT_FRAME_INTERVAL_MS;+ // A finished tail still shows until the settled item arrives.+ const tail = tails.get(key) ?? finished.get(key);+ if (settled !== undefined) {+ if (settled.output === undefined && tail !== undefined) {+ return {+ kind: "replace",+ text: tail.text,+ truncated: tail.truncated,+ running: false,+ };+ }+ const output = settled.output && legacyClaudeBashOutput(settled.output);+ return { kind: "replace", ...persistedCommandOutput(output), running: false };+ }+ if (subscriber.needsReplace || tail === undefined) {+ if (subscriber.overflowed) throttle = COMMAND_OUTPUT_REPLACE_INTERVAL_MS;+ subscriber.needsReplace = false;+ subscriber.overflowed = false;+ subscriber.pendingAppend = "";+ if (tail === undefined) {+ return { kind: "replace", ...persistedCommandOutput(snapshotOutput), running: true };+ }+ // The cursor, style and any unfinished escape ride along so the client+ // applies later appends exactly as the hub does.+ return {+ kind: "replace",+ text: terminalOutputResumeText(tail),+ truncated: tail.truncated,+ running: true,+ };+ }+ const text = subscriber.pendingAppend;+ subscriber.pendingAppend = "";+ return { kind: "append", text, truncated: tail.truncated, running: true };+ });+ return Stream.fromEffectRepeat(nextFrame).pipe(+ Stream.filter((frame) => frame.kind !== "append" || frame.text.length > 0),+ Stream.takeUntil((frame) => !frame.running),+ );+ }).pipe(+ Effect.mapError((cause) =>+ isCommandOutputError(cause)+ ? cause+ : new OrchestrationV2CommandOutputError({+ threadId: target.threadId,+ message: "Failed to read command output.",+ cause,+ }),+ ),+ ),+ );++ return CommandOutputHub.of({ append, finish, subscribe });+});++export const layer: Layer.Layer<+ CommandOutputHub,+ never,+ EventSink.EventSinkV2 | ProjectionStore.ProjectionStoreV2+> = Layer.effect(CommandOutputHub, make);diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.tsindex ddf2efbcff8..d749669164d 100644--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts@@ -690,6 +690,9 @@ export const layer: Layer.Layer<}),];}+ case "command_output.delta":+ // Live output is routed to the command output hub before ingestion.+ return [];case "turn.terminal":const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId);if (input.event.status !== "failed") {diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.tsindex 55029b4bd32..e191cc38f40 100644--- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts@@ -50,6 +50,7 @@ import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";import * as ProviderSessionManager from "./ProviderSessionManager.ts";+import * as CommandOutputHub from "./CommandOutputHub.ts";import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";const layerTestDatabase = SqlitePersistence.layerMemory;@@ -560,6 +561,9 @@ function layerTest(input: {Layer.provide(Layer.mergeAll(layerRegistry.pipe(Layer.provideMerge(McpProviderSessions.layer)),+ CommandOutputHub.layer.pipe(+ Layer.provide(Layer.merge(layerConfiguredEventSink, layerTestStores)),+ ),layerConfiguredEventSink,IdAllocator.layer,layerProviderEventIngestorTest,diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.tsindex 92eeb91ad23..32428d81e80 100644--- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts@@ -2,6 +2,7 @@ import { AgentScope } from "@t3tools/shared/AgentScope";import * as KeyedLock from "@t3tools/shared/KeyedLock";import { resolveProjectSettings } from "@t3tools/shared/projectSettings";import {+ isOrchestrationV2WorkActive,ModelSelection,OrchestrationV2DomainEvent,OrchestrationV2ProviderSession,@@ -45,6 +46,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSimport * as ServerSettings from "../serverSettings.ts";import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";import * as EventSink from "./EventSink.ts";+import * as CommandOutputHub from "./CommandOutputHub.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";@@ -331,6 +333,7 @@ export const layerWithOptions = (): Layer.Layer<ProviderSessionManagerV2,never,+ | CommandOutputHub.CommandOutputHub| EventSink.EventSinkV2| FileSystem.FileSystem| IdAllocator.IdAllocatorV2@@ -358,6 +361,7 @@ export const layerWithOptions = (const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);const projectService = yield* Effect.serviceOption(ProjectService.ProjectService);const eventSink = yield* EventSink.EventSinkV2;+ const commandOutput = yield* CommandOutputHub.CommandOutputHub;const idAllocator = yield* IdAllocator.IdAllocatorV2;const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;const projectionStore = yield* ProjectionStore.ProjectionStoreV2;@@ -2021,6 +2025,21 @@ export const layerWithOptions = (return entry.runtime.events.pipe(Stream.runForEach((event) => {if (shutdownSignal.received) return Effect.void;+ // Live output skips run subscribers and ingestion entirely: it is+ // never persisted, and a flood of it must not queue ahead of real events.+ if (event.type === "command_output.delta") {+ return commandOutput.append(event);+ }+ // A settled item carries its final output, so its live tail can go.+ const releaseLiveOutput =+ event.type === "turn_item.updated" &&+ event.turnItem.type === "command_execution" &&+ !isOrchestrationV2WorkActive(event.turnItem.status)+ ? commandOutput.finish({+ threadId: event.turnItem.threadId,+ itemId: event.turnItem.id,+ })+ : Effect.void;if (event.type === "provider_session.updated" &&event.providerSession.status === "stopped"@@ -2076,6 +2095,7 @@ export const layerWithOptions = (return;}yield* publishToSubscribers(entry.eventSubscribers, { type: "event", event });+ yield* releaseLiveOutput;}),),);diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex 8d9fd792d9b..9ca399357aa 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -475,6 +475,9 @@ export function routeProviderEvent(state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),state,];+ case "command_output.delta":+ // The session manager hands live output to the command output hub; runs never see it.+ return [false, state];case "turn.terminal":return event.providerTurnId === state.rootProviderTurnId? [true, { ...state, rootTurnEnded: true }]diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.tsindex 18ad606d976..d4ba1508484 100644--- a/apps/server/src/orchestration-v2/runtimeLayer.ts+++ b/apps/server/src/orchestration-v2/runtimeLayer.ts@@ -36,6 +36,7 @@ import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationServicimport * as ProviderEventIngestor from "./ProviderEventIngestor.ts";import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";import * as ProviderSessionManager from "./ProviderSessionManager.ts";+import * as CommandOutputHub from "./CommandOutputHub.ts";import * as ProviderRuntimeRecoveryService from "./ProviderRuntimeRecoveryService.ts";import * as ProviderSwitchService from "./ProviderSwitchService.ts";import * as ProviderTurnControlService from "./ProviderTurnControlService.ts";@@ -124,9 +125,14 @@ const layerProviderSwitchServiceProvided = ProviderSwitchService.layer.pipe(Layer.provide(layerProviderAdapterRegistryProvided),);+const layerCommandOutputHubProvided = CommandOutputHub.layer.pipe(+ Layer.provide(Layer.merge(layerEventSinkProvided, ProjectionStore.layer)),+);+const layerProviderSessionManagerProvided = ProviderSessionManager.layer.pipe(Layer.provide(Layer.mergeAll(+ layerCommandOutputHubProvided,layerProviderAdapterRegistryProvided,layerEventSinkProvided,IdAllocator.layer,@@ -337,6 +343,7 @@ const layerMcpAppRequestsProvided = McpAppRequests.layer.pipe();export const layer = Layer.mergeAll(+ layerCommandOutputHubProvided,layerOrchestratorProvided,layerMcpAppRequestsProvided,layerThreadManagementProvided,diff --git a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.tsindex eb2482cb654..6e105d0deac 100644--- a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts+++ b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts@@ -246,6 +246,19 @@ const scenarioExpectations = {turnCompletedCount: 1,approvalRequestCount: 0,},+ command_output_streaming: {+ outgoing: ["initialize", "initialized", "thread/start", "turn/start"],+ incoming: [+ "turn/started",+ "item/started",+ "item/commandExecution/outputDelta",+ "item/completed",+ "turn/completed",+ ],+ turnStartCount: 1,+ turnCompletedCount: 1,+ approvalRequestCount: 0,+ },turn_interrupt_mid_tool: {outgoing: ["initialize",diff --git a/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts b/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.tsnew file mode 100644index 00000000000..7cdb030297b--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts@@ -0,0 +1,55 @@+import type { TurnItemId } from "@t3tools/contracts";+import {+ appendTerminalOutput,+ EMPTY_TERMINAL_OUTPUT,+ type TerminalOutputState,+} from "@t3tools/shared/terminalOutput";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import * as CommandOutputHub from "../CommandOutputHub.ts";+import type * as EventSink from "../EventSink.ts";+import type * as ProjectionStore from "../ProjectionStore.ts";++/** What one command streamed through the hub during a replay. */+export interface RecordedCommandOutput {+ readonly chunks: number;+ /** The live tail as a viewer would have seen it. */+ readonly output: TerminalOutputState;+}++export class CommandOutputRecorder extends Context.Service<+ CommandOutputRecorder,+ { readonly snapshot: Effect.Effect<ReadonlyMap<TurnItemId, RecordedCommandOutput>> }+>()("t3/orchestration-v2/testkit/CommandOutputRecorder") {}++/** The real hub, plus a record of every chunk it was given, keyed by turn item. */+export const layer: Layer.Layer<+ CommandOutputHub.CommandOutputHub | CommandOutputRecorder,+ never,+ EventSink.EventSinkV2 | ProjectionStore.ProjectionStoreV2+> = Layer.effectContext(+ Effect.gen(function* () {+ const hub = yield* CommandOutputHub.make;+ const recorded = new Map<TurnItemId, RecordedCommandOutput>();+ return Context.make(+ CommandOutputHub.CommandOutputHub,+ CommandOutputHub.CommandOutputHub.of({+ ...hub,+ append: (input) =>+ Effect.sync(() => {+ const previous = recorded.get(input.itemId);+ recorded.set(input.itemId, {+ chunks: (previous?.chunks ?? 0) + 1,+ output: appendTerminalOutput(previous?.output ?? EMPTY_TERMINAL_OUTPUT, input.chunk),+ });+ }).pipe(Effect.andThen(hub.append(input))),+ }),+ ).pipe(+ Context.add(CommandOutputRecorder, {+ snapshot: Effect.sync(() => new Map(recorded)),+ }),+ );+ }),+);diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.tsindex 4ad182401d7..bbb414f26f5 100644--- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts@@ -329,6 +329,66 @@ describe("orchestrator replay fixtures", () => {const rest = entries.filter((_, index) => index !== toolIndex);return [...rest.slice(0, resultIndex), toolEntry, ...rest.slice(resultIndex)];};+ // A subagent's foreground Bash run during the root's turn is tailed like a+ // root call's, so the child's command row streams live.+ const SUBAGENT_BASH_ID = "toolu_01JMN3SSQCHzUTNua9AWdkiH";+ it.effect("streams a subagent's foreground Bash output live during the root turn", () =>+ runFixtureProviderWithRegisteredHarness({+ fixtureName: afterRootFixture.name,+ buildInput: afterRootFixture.buildInput,+ driver: {+ ...afterRootProvider,+ assertOutput: (result) => {+ const childThreadId = projectionFor(result, afterRootFixture.name).subagents[0]+ ?.childThreadId;+ assert.exists(childThreadId);+ const command = result.projections+ .get(childThreadId)+ ?.turnItems.find(+ (item) =>+ item.type === "command_execution" &&+ JSON.stringify(item.input).includes("SUB_DONE_1"),+ );+ assert.exists(command);+ const streamed = result.commandOutput?.get(command.id);+ assert.exists(streamed, "the subagent's command must stream its output");+ assert.include(streamed.output.text, "SUB_DONE_1");+ },+ },+ transformTranscript: (transcript) => {+ const isBashFrame = (entry: ProviderReplayEntry) => {+ if (entry.type !== "emit_inbound") return false;+ const frame = entry.frame as Record<string, any>;+ return (+ frame.message?.content?.[0]?.id === SUBAGENT_BASH_ID ||+ frame.message?.content?.[0]?.tool_use_id === SUBAGENT_BASH_ID ||+ (frame.type === "system" && frame.tool_use_id === SUBAGENT_BASH_ID)+ );+ };+ // Recorded without the structured result the replay writes output files from.+ const bashFrames = transcript.entries.filter(isBashFrame).map((entry) => {+ const frame = (entry as { readonly frame: Record<string, any> }).frame;+ return frame.type === "user"+ ? {+ ...entry,+ frame: { ...frame, tool_use_result: { stdout: "SUB_DONE_1\n", stderr: "" } },+ }+ : entry;+ });+ const rest = transcript.entries.filter((entry) => !isBashFrame(entry));+ const resultIndex = rest.findIndex(+ (entry) => entry.type === "emit_inbound" && entry.label === "result",+ );+ assert.lengthOf(bashFrames, 4, "transcript shape changed");+ assert.isAtLeast(resultIndex, 0, "transcript shape changed");+ return {+ ...transcript,+ entries: [...rest.slice(0, resultIndex), ...bashFrames, ...rest.slice(resultIndex)],+ };+ },+ }),+ );+it.effect.each((["WebFetch", "Write"] as const).flatMap((tool) =>(["before root settles", "while root is idle"] as const).flatMap((opens) =>diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.tsindex c43c17e0129..3fcb15fea57 100644--- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts@@ -11,6 +11,7 @@ import type {ProviderUserInputAnswers,CommandId,ThreadId,+ TurnItemId,} from "@t3tools/contracts";import * as Clock from "effect/Clock";import * as Duration from "effect/Duration";@@ -23,6 +24,7 @@ import * as Stream from "effect/Stream";import { TestClock } from "effect/testing";import * as Orchestrator from "../Orchestrator.ts";+import type { RecordedCommandOutput } from "./CommandOutputRecorder.ts";import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate";export type OrchestratorV2ScenarioStep =@@ -117,6 +119,8 @@ export interface OrchestratorV2ScenarioResult {readonly projections: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;readonly shellSnapshot: OrchestrationV2ThreadShellSnapshot;readonly capturedShellSnapshots: ReadonlyMap<string, OrchestrationV2ThreadShellSnapshot>;+ /** Live output each command streamed (never persisted). Provider replays fill it in. */+ readonly commandOutput?: ReadonlyMap<TurnItemId, RecordedCommandOutput>;}export class OrchestratorV2ScenarioStepError extends Schema.TaggedError<OrchestratorV2ScenarioStepError>()(diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.tsindex 1ee5fb99648..2d01f430380 100644--- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts+++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts@@ -41,6 +41,7 @@ import * as ProviderContinuationService from "../ProviderContinuationService.ts"import * as ProviderEventIngestor from "../ProviderEventIngestor.ts";import * as ProviderRuntimeRecoveryService from "../ProviderRuntimeRecoveryService.ts";import * as ProviderSessionManager from "../ProviderSessionManager.ts";+import * as CommandOutputRecorder from "./CommandOutputRecorder.ts";import * as ProviderSwitchService from "../ProviderSwitchService.ts";import * as ProviderTurnControlService from "../ProviderTurnControlService.ts";import * as ProviderTurnStartService from "../ProviderTurnStartService.ts";@@ -220,7 +221,11 @@ export function runOrchestratorV2ProviderReplayScenario<replayGate,});- return runOrchestratorV2Scenario(scenario, { replayGate }).pipe(Effect.provide(layer));+ return Effect.gen(function* () {+ const result = yield* runOrchestratorV2Scenario(scenario, { replayGate });+ const recorder = yield* CommandOutputRecorder.CommandOutputRecorder;+ return { ...result, commandOutput: yield* recorder.snapshot };+ }).pipe(Effect.provide(layer));}export function layerProviderReplay<Transcript extends ProviderReplayTranscript, Error>(@@ -245,6 +250,7 @@ export function layerProviderReplay<Transcript extends ProviderReplayTranscript,| Orchestrator.OrchestratorV2| EffectWorker.OrchestrationEffectWorkerV2| EventSink.EventSinkV2+ | CommandOutputRecorder.CommandOutputRecorder| ProviderSessionManager.ProviderSessionManagerV2,Error | MigrationError | PlatformError.PlatformError | SqlError> {@@ -280,7 +286,8 @@ export function layerWithRegistry<Error>(| Orchestrator.OrchestratorV2| EffectWorker.OrchestrationEffectWorkerV2| EventSink.EventSinkV2- | ProviderSessionManager.ProviderSessionManagerV2,+ | ProviderSessionManager.ProviderSessionManagerV2+ | CommandOutputRecorder.CommandOutputRecorder,Error | MigrationError | PlatformError.PlatformError | SqlError> {const layerServerConfig = Layer.effect(@@ -353,11 +360,16 @@ export function layerWithRegistry<Error>(IdAllocator.layer,layerProviderEventIngestorProvided,);+ // The real hub, recording what each command streamed so fixtures can assert it.+ const layerCommandOutputHubProvided = CommandOutputRecorder.layer.pipe(+ Layer.provide(Layer.merge(layerEventSinkProvided, layerStores)),+ );const layerProviderSessionManagerProvided = ProviderSessionManager.layerWithOptions({configureMcp: false,}).pipe(Layer.provide(Layer.mergeAll(+ layerCommandOutputHubProvided,layerProvidedRegistry,layerEventSinkProvided,IdAllocator.layer,@@ -503,6 +515,7 @@ export function layerWithRegistry<Error>(layerEffectWorkerProvided,layerEventSinkProvided,layerContinuationWorkerProvided,+ layerCommandOutputHubProvided,).pipe(Layer.provide(ProviderTurnStartServiceTestkit.layer), Layer.provide(NodeServices.layer));// Build the daemon from the exact worker instance exposed alongside thediff --git a/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/claude_transcript.ndjsonnew file mode 100644index 00000000000..3eb36167f4e--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/claude_transcript.ndjson@@ -0,0 +1,77 @@+{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"command_output_streaming","metadata":{"prompts":["Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete"],"model":"claude-sonnet-4-6","nativeSessionId":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","queryMode":"streaming","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript"}}+{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","settings":{"showThinkingSummaries":true},"allowDangerouslySkipPermissions":true,"sessionId":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}}+{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete"},"parent_tool_use_id":null,"uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}}+{"type":"emit_inbound","label":"command_lifecycle","frame":{"type":"command_lifecycle","command_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","state":"queued","uuid":"6fe0d477-fdc3-47dc-8ff1-3ccc54d469b4","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}+{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"08a52454-78a5-452f-9bb8-e88ed4059728","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"commands_changed","commands":[],"uuid":"c8217962-8361-44e9-bb14-3af863bc1120","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}+{"type":"emit_inbound","label":"command_lifecycle","frame":{"type":"command_lifecycle","command_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","state":"started","uuid":"97a54d83-3bcd-4777-a5cf-2bdc595582a9","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.282","cwd":"/tmp/claude-replay-command_output_streaming","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"6248439e-cbe2-4414-9c47-a9961bd454c9","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"status","status":"requesting","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"1323609c-6e72-4fbf-b08e-8c17d9f048c4"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_start","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefxsSL5BaoUrPAkdYT6","type":"message","role":"assistant","content":[],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"14c64722-b32e-4b2c-84f1-023bfbf450dd","ttft_ms":2404,"user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","user_message_uuids":["99a8b580-5528-4f14-b057-e5bf7b2769d5"]}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"0762a100-bc7a-4557-a875-e37071475656"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":2,"estimated_tokens_delta":2,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"20278113-d72a-4a92-a4d3-f48347bcb130","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"The user","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"02859d8a-a956-4b0e-95c5-9537c5bd781e"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":13,"estimated_tokens_delta":11,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"0cc23935-3171-427f-a238-46528dcfecdc","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" wants me to run a specific shell command","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"bd7870f4-f4aa-4edf-bc7f-dfe221b3d537"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":22,"estimated_tokens_delta":9,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"76c1c5d1-147a-4b51-bd88-8431586bea3a","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" in the foreground and wait for it","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"1d725fd5-c0d4-4004-b077-4beb6117cc68"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":25,"estimated_tokens_delta":3,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"1158a602-d8ae-48d0-aba0-3404106a2dfc","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" to finish,","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"b951aa7f-7bcd-44e3-967c-fa0b8aa75e5f"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":30,"estimated_tokens_delta":5,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"c220c092-c175-428f-b03d-387d39a4bf1e","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" then respond with a","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"6b796b6f-ded8-4600-9581-f777d9d724e2"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":33,"estimated_tokens_delta":3,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"b6a5e466-cf90-4b90-a26c-476f6512e9af","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" specific","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"30b7dcc3-2343-4a82-b963-b9fa4d24986b"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":35,"estimated_tokens_delta":2,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"d0cda494-8525-4cd5-89d5-163ae364929b","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":" message","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"97d5635f-12f7-4e57-b7b4-f42326f83c36"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":36,"estimated_tokens_delta":1,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"62158fd5-a0ac-433f-8beb-ae2ae37ff9f1","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":".","estimated_tokens":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"7e08edaa-a314-4d6d-9344-1877c66066ad"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"thinking_tokens","estimated_tokens":108,"estimated_tokens_delta":72,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"a645e3ae-7e68-41b6-a062-cc6a160a3876","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"EqkDCsABCBIYAipA2mzY654tInaSF6DeGkvp3gfkITqOPZhhqF8GT6ZkzgeQ15s7+XBSfSQ5waInilWZR6l+T/1k8YSW/kl1gNLy2TIRY2xhdWRlLXNvbm5ldC00LTY4AEIIdGhpbmtpbmdaJGFmOTIzNWNiLWRjNTItNDViMC05MTI2LTNmZTBkZmJmNzNkY3IQOUPUj6Q5Zqq7Ny6ZW11Rk4gBAZoBEwoRY2xhdWRlLXNvbm5ldC00LTaoAeiIgtYGsAECEgyJBKaNGwE4Bq7bVUAaDK7KTwkdSFhS109YaCIwwQY7/tQ9YthmKPKGQi6d7IN4+9F66tIrCAVIFJCm+PPT55S9uF86eX7hsdezKmtRKpUB81ib01do6Pc5sBsDW11G42sz8a3Vj3bwgXSnmOzsGy2MThUkQMwjiK0goinTRyDI4CM+M8891vUuMH6rNz7tUEla394ITlWCKynXRPRB4M0K/ap4SQKgq7TXOXtbWZd32nSkA7tKL+z4dERb4jwuWmFr6MGUS3IIanrtkdCwUR5dfsLjr8cG2YQjK0H1gUxQSfSwT04YAQ=="}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"bcffb6f7-03d6-42aa-a5d5-fb1dfe835408"}}+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefxsSL5BaoUrPAkdYT6","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run a specific shell command in the foreground and wait for it to finish, then respond with a specific message.","signature":"EqkDCsABCBIYAipA2mzY654tInaSF6DeGkvp3gfkITqOPZhhqF8GT6ZkzgeQ15s7+XBSfSQ5waInilWZR6l+T/1k8YSW/kl1gNLy2TIRY2xhdWRlLXNvbm5ldC00LTY4AEIIdGhpbmtpbmdaJGFmOTIzNWNiLWRjNTItNDViMC05MTI2LTNmZTBkZmJmNzNkY3IQOUPUj6Q5Zqq7Ny6ZW11Rk4gBAZoBEwoRY2xhdWRlLXNvbm5ldC00LTaoAeiIgtYGsAECEgyJBKaNGwE4Bq7bVUAaDK7KTwkdSFhS109YaCIwwQY7/tQ9YthmKPKGQi6d7IN4+9F66tIrCAVIFJCm+PPT55S9uF86eX7hsdezKmtRKpUB81ib01do6Pc5sBsDW11G42sz8a3Vj3bwgXSnmOzsGy2MThUkQMwjiK0goinTRyDI4CM+M8891vUuMH6rNz7tUEla394ITlWCKynXRPRB4M0K/ap4SQKgq7TXOXtbWZd32nSkA7tKL+z4dERb4jwuWmFr6MGUS3IIanrtkdCwUR5dfsLjr8cG2YQjK0H1gUxQSfSwT04YAQ=="}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"9bdb9448-9eec-4d7f-9596-7c2bb88a520e","timestamp":"2026-10-03T04:28:24.096Z","user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","user_message_uuids":["99a8b580-5528-4f14-b057-e5bf7b2769d5"]}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_stop","index":0},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5b1c3d6b-54da-4169-ba99-0d44d6b0676b"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"09c1e8b7-dd45-4109-aa49-854bc20fd260"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"Running"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"289bbc2e-7af9-4776-b417-8425e8da5e1f"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":" the specified"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"19b641ae-50c2-43e2-ad0e-50e18956404b"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":" command now."}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"a63755c5-4ac7-4b69-b76b-29a27198c05e"}}+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefxsSL5BaoUrPAkdYT6","type":"message","role":"assistant","content":[{"type":"text","text":"Running the specified command now."}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"21c52985-f6d0-4bce-a041-9a14335cbe4c","timestamp":"2026-10-03T04:28:24.667Z"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_stop","index":1},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"155f9033-d2f5-4bb2-8bbe-99eb910a7eab"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","name":"Bash","input":{},"caller":{"type":"direct"}}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5f52cf4d-782c-4365-b9e8-39de7da83b04"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":""}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"2a952797-fdcd-4d07-89b0-d08a7da2e4c4"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"comma"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"7c365772-6e18-4e21-ac82-1b610115eebd"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"nd\": \"f"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"a57acdd1-dc29-4b9e-b324-7825012d7238"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"or i in"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"526ce67e-3518-43c6-a6fa-757466973f6e"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":" 1 2 3 "}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"68228de6-f113-4cfa-b850-fa283e2df465"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"4; do p"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5dd7b26c-4058-40c0-bb8f-ec6529608e3c"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"rintf '"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"3da221cd-debd-4b28-9995-d9e29817a8b6"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\\\\033[3"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"0cd8e2d7-defd-4d81-9707-3d2a7b925788"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"2mstrea"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"751d286c-526b-404b-9e58-03d63ded03b6"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"m line "}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4634f627-4af6-4479-9bc0-3c20dcf85bef"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"%s\\\\033"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4975e7ac-dd15-48b5-96df-4b5f870bed94"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"[0m\\\\n'"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4e42af58-4532-4228-9bbc-2a34571f1dcf"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":" $i; sl"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4dbaff2d-53b1-40fd-af40-1565e3bd6412"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"eep 1; "}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"7869dd97-9bc2-4a96-982e-ff95245344d8"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"done; p"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"ba427143-74fa-4926-bec9-588519a38563"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"rintf '"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"f2b8b20a-dcec-4254-a5b7-c42ddf90965e"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"progres"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5ab8b845-c735-4951-ad72-2b91598d3c54"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"s 50%%\\"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"c2ae622a-a328-4547-91a0-fcea5a1b8f1c"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\\rprogr"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"a55100e6-a2c4-4240-bf1f-cc3528e0dd6e"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"ess 100"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"9dbf6788-2d4c-4bb8-853a-48d75d96b1da"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"%%\\\\n'\"}"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"01f00aea-874b-48b1-af4b-a6f21171ca8a"}}+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefxsSL5BaoUrPAkdYT6","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","name":"Bash","input":{"command":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'"},"caller":{"type":"direct"}}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"459b10f0-5940-4da5-b476-58a8e2d1a1f5","timestamp":"2026-10-03T04:28:25.208Z","wire_tool_inputs":{"toolu_01CJnQSvsvh3iZtmvSWQVVvg":{"command":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'"}}}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_stop","index":2},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"717ffcb1-64d9-406a-ae9b-bf5ea86b067e"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"container":null},"usage":{"input_tokens":3,"cache_creation_input_tokens":13590,"cache_read_input_tokens":121265,"output_tokens":168,"output_tokens_details":{"thinking_tokens":40},"iterations":[{"input_tokens":3,"output_tokens":168,"cache_read_input_tokens":121265,"cache_creation_input_tokens":13590,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":13590},"type":"message"}]},"context_management":{"applied_edits":[]}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"4e7b88bb-8780-4fa2-9180-9d0100709db2"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_stop"},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5c4f50f3-448a-4769-9e18-19fef01623e0"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_started","task_id":"bmjeipgqr","tool_use_id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","description":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'","is_backgrounded":false,"task_type":"local_bash","uuid":"6d2c30a6-ae01-4f1e-b461-a788611fbb27","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_notification","task_id":"bmjeipgqr","tool_use_id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","status":"completed","output_file":"","summary":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'","uuid":"bc93586f-9042-46d7-bb2d-bef6306dae41","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d"}}+{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01CJnQSvsvh3iZtmvSWQVVvg","type":"tool_result","content":"\u001b[32mstream line 1\u001b[0m\n\u001b[32mstream line 2\u001b[0m\n\u001b[32mstream line 3\u001b[0m\n\u001b[32mstream line 4\u001b[0m\nprogress 50%\rprogress 100%","is_error":false}]},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"1e330b27-e5ec-4efd-a1e8-f3210856a354","timestamp":"2026-10-03T04:28:29.316Z","tool_use_result":{"stdout":"\u001b[32mstream line 1\u001b[0m\n\u001b[32mstream line 2\u001b[0m\n\u001b[32mstream line 3\u001b[0m\n\u001b[32mstream line 4\u001b[0m\nprogress 50%\rprogress 100%","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false}}}+{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"status","status":"requesting","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"4b915a96-3ef5-45bb-bedd-316a6225ff28"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_start","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefyTbebJFTYTaoceKGP","type":"message","role":"assistant","content":[],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":233,"cache_read_input_tokens":134855,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":233},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"025b50aa-f18e-44e0-a3ad-824463157e25","ttft_ms":1793}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"f89c4bd0-d960-4f8f-ba37-8bcf20bba907"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"command"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"544181d2-af8e-4b44-bdfb-1a4b62448555"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" output fixture complete"}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"39ce0edf-4f40-4486-a31d-0e64ed05f4e3"}}+{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CfefyTbebJFTYTaoceKGP","type":"message","role":"assistant","content":[{"type":"text","text":"command output fixture complete"}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":233,"cache_read_input_tokens":134855,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":233},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","uuid":"a2e4190b-50b6-4d97-9402-64912e5cd213","timestamp":"2026-10-03T04:28:31.124Z"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"content_block_stop","index":0},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"f028526e-63ab-422d-9891-afaf0e23240b"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"container":null},"usage":{"input_tokens":1,"cache_creation_input_tokens":233,"cache_read_input_tokens":134855,"output_tokens":7,"output_tokens_details":{"thinking_tokens":0},"iterations":[{"input_tokens":1,"output_tokens":7,"cache_read_input_tokens":134855,"cache_creation_input_tokens":233,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":233},"type":"message"}]},"context_management":{"applied_edits":[]}},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"5090dc1b-46e7-4b61-8f8b-f9d2fb385124"}}+{"type":"emit_inbound","label":"stream_event","frame":{"type":"stream_event","event":{"type":"message_stop"},"session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","parent_tool_use_id":null,"uuid":"c2ec1520-26b6-4735-8318-64cac0040303"}}+{"type":"emit_inbound","label":"result","frame":{"duration_api_ms":6707,"stop_reason":"end_turn","session_id":"95b68ca2-f0b8-4902-839b-3586d4ba3f3d","total_cost_usd":0.16666124999999998,"usage":{"input_tokens":4,"cache_creation_input_tokens":13823,"cache_read_input_tokens":256120,"output_tokens":175,"output_tokens_details":{"thinking_tokens":40},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":13823,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":1,"output_tokens":7,"cache_read_input_tokens":134855,"cache_creation_input_tokens":233,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":233},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":7,"outputTokens":186,"cacheReadInputTokens":256120,"cacheCreationInputTokens":14910,"webSearchRequests":0,"costUSD":0.16666124999999998,"contextWindow":200000,"maxOutputTokens":32000,"thinkingTokens":40,"canonicalModel":"claude-sonnet-4-6","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"is_error":false,"num_turns":2,"subtype":"success","api_error_status":null,"result":"command output fixture complete","ttft_ms":2938,"type":"result","duration_ms":9977,"uuid":"3e15a737-b7dc-4213-9895-92757055d07e","ttft_stream_ms":2442,"time_to_request_ms":39,"first_content_frame_ms":2512,"user_message_uuid":"99a8b580-5528-4f14-b057-e5bf7b2769d5","user_message_uuids":["99a8b580-5528-4f14-b057-e5bf7b2769d5"],"request_sent_wall_ms":1791001701197,"queued_turn_count":0,"result_index":0}}+{"type":"runtime_exit","status":"success"}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjsonnew file mode 100644index 00000000000..abe0b1b1f65--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/codex_transcript.ndjson@@ -0,0 +1,65 @@+{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.157.0","scenario":"command_output_streaming","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"command_output_streaming.ndjson","description":"One command prints over several seconds, so Codex streams its output deltas.","model":"gpt-6-luna"}}+{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.45"}}}}+{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"T3 Code/0.157.0 (Mac OS 27.0.0; arm64) unknown (T3 Code; 0.0.45)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"macos"}}}+{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}+{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000},"cwd":"<workspace>","model":"gpt-6-luna"}}}+{"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1791001627148}}+{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"readOnly","networkAccess":false},"activePermissionProfile":{"id":":read-only","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}}+{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"<workspace>","input":[{"text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"networkAccess":false,"type":"workspaceWrite","writableRoots":[]},"summary":"detailed","threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6"}}}+{"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a10004-0a27-7421-852d-0f7f99ace2d6","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/apps/server","runtimeWorkspaceRoots":["/home/replay-user/t3code/apps/server"]}],"extra":null,"sessionId":"01a10004-0a27-7421-852d-0f7f99ace2d6","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"cpa","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1791001627,"updatedAt":1791001627,"recencyAt":1791001627,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/10/03/rollout-2026-10-03T00-27-07-01a10004-0a27-7421-852d-0f7f99ace2d6.jsonl","cwd":"/home/replay-user/t3code/apps/server","cliVersion":"0.157.0","originator":"T3 Code","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1791001627410}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"cua_repl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"firecrawl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"paper","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"node_repl","status":"starting","error":null,"failureReason":null},"emittedAtMs":1791001627411}}+{"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/apps/server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"cpa","serviceTier":"default","effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1791001627437}}+{"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}+{"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1791001627550}}+{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1791001627553}}+{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1791001627,"completedAt":null,"durationMs":null}},"emittedAtMs":1791001627553}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"paper","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001627558}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"node_repl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001627758}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"cua_repl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001628542}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"firecrawl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629447}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"paper","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629994}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629994}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"node_repl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629994}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","name":"cua_repl","status":"ready","error":null,"failureReason":null},"emittedAtMs":1791001629994}}+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a10004-1683-7d83-9525-bcae2f675340","clientId":null,"content":[{"type":"text","text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","text_elements":[]}]},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","startedAtMs":1791001630341},"emittedAtMs":1791001630342}}+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a10004-1683-7d83-9525-bcae2f675340","clientId":null,"content":[{"type":"text","text":"Run this exact shell command in the foreground and wait for it to finish: `for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'`. Then respond exactly: command output fixture complete","text_elements":[]}]},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","completedAtMs":1791001630342},"emittedAtMs":1791001630347}}+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","text":"","phase":"commentary","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","startedAtMs":1791001632408},"emittedAtMs":1791001632408}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":"I"},"emittedAtMs":1791001632408}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":"’ll"},"emittedAtMs":1791001632408}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" run"},"emittedAtMs":1791001632408}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" the"},"emittedAtMs":1791001632584}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" command"},"emittedAtMs":1791001632584}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" in"},"emittedAtMs":1791001632584}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" the"},"emittedAtMs":1791001632584}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" foreground"},"emittedAtMs":1791001632584}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" and"},"emittedAtMs":1791001632584}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" wait"},"emittedAtMs":1791001632585}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" for"},"emittedAtMs":1791001632585}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" it"},"emittedAtMs":1791001632585}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" to"},"emittedAtMs":1791001632666}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":" finish"},"emittedAtMs":1791001632666}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","delta":"."},"emittedAtMs":1791001632667}}+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac08420563087d2af7fb28a3cee1956","text":"I’ll run the command in the foreground and wait for it to finish.","phase":"commentary","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","completedAtMs":1791001633018},"emittedAtMs":1791001633021}}+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","pluginId":null,"scriptPath":null,"command":"/bin/zsh -lc \"for i in 1 2 3 4; do printf '\\\\033[32mstream line %s\\\\033[0m\\\\n' \"'$i; sleep 1; done; printf '\"'progress 50%%\\\\rprogress 100%%\\\\n'\"","cwd":"/home/replay-user/t3code/apps/server","processId":"44027","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"unknown","command":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'"}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","startedAtMs":1791001635941},"emittedAtMs":1791001635947}}+{"type":"emit_inbound","label":"item/commandExecution/outputDelta","frame":{"method":"item/commandExecution/outputDelta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","delta":"\u001b[32mstream line 2\u001b[0m\n"},"emittedAtMs":1791001636825}}+{"type":"emit_inbound","label":"item/commandExecution/outputDelta","frame":{"method":"item/commandExecution/outputDelta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","delta":"\u001b[32mstream line 3\u001b[0m\n"},"emittedAtMs":1791001637829}}+{"type":"emit_inbound","label":"item/commandExecution/outputDelta","frame":{"method":"item/commandExecution/outputDelta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","delta":"\u001b[32mstream line 4\u001b[0m\n"},"emittedAtMs":1791001638840}}+{"type":"emit_inbound","label":"item/commandExecution/outputDelta","frame":{"method":"item/commandExecution/outputDelta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","delta":"progress 50%\rprogress 100%\n"},"emittedAtMs":1791001639845}}+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"exec-1a2dcd5e-1591-48a8-bb8e-47cb40883d2c","pluginId":null,"scriptPath":null,"command":"/bin/zsh -lc \"for i in 1 2 3 4; do printf '\\\\033[32mstream line %s\\\\033[0m\\\\n' \"'$i; sleep 1; done; printf '\"'progress 50%%\\\\rprogress 100%%\\\\n'\"","cwd":"/home/replay-user/t3code/apps/server","processId":"44027","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"unknown","command":"for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'"}],"aggregatedOutput":"\u001b[32mstream line 2\u001b[0m\n\u001b[32mstream line 3\u001b[0m\n\u001b[32mstream line 4\u001b[0m\nprogress 50%\rprogress 100%\n","exitCode":0,"durationMs":3903},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","completedAtMs":1791001639846},"emittedAtMs":1791001639848}}+{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","tokenUsage":{"total":{"totalTokens":17795,"inputTokens":17653,"cachedInputTokens":3840,"cacheWriteInputTokens":0,"outputTokens":142,"reasoningOutputTokens":0},"last":{"totalTokens":17795,"inputTokens":17653,"cachedInputTokens":3840,"cacheWriteInputTokens":0,"outputTokens":142,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1791001639853}}+{"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":null,"secondary":null,"credits":null,"individualLimit":null,"spendControlReached":null,"planType":null,"rateLimitReachedType":null}},"emittedAtMs":1791001639853}}+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","startedAtMs":1791001642659},"emittedAtMs":1791001642660}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","delta":"command"},"emittedAtMs":1791001642660}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","delta":" output"},"emittedAtMs":1791001642660}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","delta":" fixture"},"emittedAtMs":1791001642660}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","itemId":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","delta":" complete"},"emittedAtMs":1791001642870}}+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","text":"command output fixture complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","completedAtMs":1791001642938},"emittedAtMs":1791001642940}}+{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turnId":"01a10004-0b1b-78f0-a41c-b253bded078e","tokenUsage":{"total":{"totalTokens":35682,"inputTokens":35532,"cachedInputTokens":20992,"cacheWriteInputTokens":0,"outputTokens":150,"reasoningOutputTokens":0},"last":{"totalTokens":17887,"inputTokens":17879,"cachedInputTokens":17152,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1791001642955}}+{"type":"emit_inbound","label":"account/rateLimits/updated","frame":{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"normalModelSlug":null,"primary":null,"secondary":null,"credits":null,"individualLimit":null,"spendControlReached":null,"planType":null,"rateLimitReachedType":null}},"emittedAtMs":1791001642955}}+{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","status":{"type":"idle"}},"emittedAtMs":1791001642982}}+{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a10004-0a27-7421-852d-0f7f99ace2d6","turn":{"id":"01a10004-0b1b-78f0-a41c-b253bded078e","items":[{"type":"agentMessage","id":"msg_0038d12d01b50ff0016ac0842a975c87d2bf566b8ae1f7e5f3","text":"command output fixture complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1791001627,"completedAt":1791001642,"durationMs":15546}},"emittedAtMs":1791001642982}}+{"type":"runtime_exit","status":"success"}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/input.ts b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/input.tsnew file mode 100644index 00000000000..48d4f652751--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/input.ts@@ -0,0 +1,7 @@+import { COMMAND_OUTPUT_STREAMING_PROMPT, type OrchestratorFixtureInput } from "../shared.ts";++export function commandOutputStreamingInput(): OrchestratorFixtureInput {+ return {+ steps: [{ type: "message", text: COMMAND_OUTPUT_STREAMING_PROMPT }],+ };+}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/output.tsnew file mode 100644index 00000000000..7e353e00332--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/fixtures/command_output_streaming/output.ts@@ -0,0 +1,69 @@+import { assert } from "@effect/vitest";+import type { ProviderReplayTranscript } from "@t3tools/contracts";+import { normalizeTerminalOutput, terminalOutputPlainText } from "@t3tools/shared/terminalOutput";++import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";+import {+ assertBaseProjection,+ assertSemanticProjectionIntegrity,+ assertUserMessagesInclude,+ assertVisibleTurnItemsMirrorLocalTurnItems,+ COMMAND_OUTPUT_STREAMING_PROMPT,+ projectionFor,+} from "../shared.ts";++/**+ * A command that prints for a few seconds streams its output live, and that+ * output never becomes an orchestration event: the command item is persisted+ * while running with no output, then once with its final output.+ */+export function assertCommandOutputStreamingOutput(+ result: OrchestratorV2ScenarioResult,+ transcript: ProviderReplayTranscript,+) {+ assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] });+ const projection = projectionFor(result, transcript.scenario);+ assertSemanticProjectionIntegrity(projection);+ assertVisibleTurnItemsMirrorLocalTurnItems(projection);+ assertUserMessagesInclude(projection, [COMMAND_OUTPUT_STREAMING_PROMPT]);++ const command = projection.turnItems.find((item) => item.type === "command_execution");+ assert.isDefined(command);+ assert.equal(command?.type, "command_execution");+ if (command?.type !== "command_execution") return;+ assert.equal(command.status, "completed");+ assert.include(command.output ?? "", "progress 100%");++ // Live output reached the hub, cleaned of escapes and the progress redraw.+ const streamed = result.commandOutput?.get(command.id);+ assert.isDefined(streamed, "the running command must stream its output");+ assert.isAbove(streamed?.chunks ?? 0, 0);+ const liveText = streamed?.output.text ?? "";+ const live = terminalOutputPlainText(liveText);+ // Codex never streams what a command prints before its first yield (the recorded+ // session has no delta, and no aggregatedOutput, for line 1), so it is not asserted.+ for (const line of ["stream line 2", "stream line 3", "stream line 4", "progress 100%"]) {+ assert.include(live, line);+ }+ // The command's green survives as a canonical colour code; nothing else does.+ assert.include(liveText, "\u001b[0;32mstream line 2\u001b[0m");+ assert.notInclude(live, "\u001b");+ assert.notInclude(live, "progress 50%");+ // What viewers watched is the end of what the row keeps once it settles.+ const final = terminalOutputPlainText(normalizeTerminalOutput(command.output ?? "").text);+ assert.isTrue(+ final.trimEnd().endsWith(live.trimEnd()),+ `the live tail must agree with the persisted final output: ${JSON.stringify({ final, live })}`,+ );+ // The row shows what the command printed, not a serialized tool result.+ assert.notInclude(final, '"stdout"');++ // Never persisted while running: no event carries partial command output.+ const commandEvents = result.domainEvents.flatMap((event) =>+ event.type === "turn-item.updated" && event.payload.id === command.id ? [event.payload] : [],+ );+ for (const item of commandEvents) {+ if (item.type !== "command_execution" || item.status === "completed") continue;+ assert.isUndefined(item.output, "a running command item must not persist live output");+ }+}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts b/apps/server/src/orchestration-v2/testkit/fixtures/index.tsindex da11d9046b8..96a93589736 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts@@ -186,6 +186,8 @@ import { assertToolCallWorkspaceNeverClaudeOutput } from "./tool_call_workspace_import { assertToolCallWorkspaceNeverOutput } from "./tool_call_workspace_never/codex_output.ts";import { toolCallWorkspaceNeverInput } from "./tool_call_workspace_never/input.ts";import { assertTurnInterruptClaudeOutput } from "./turn_interrupt/claude_output.ts";+import { assertCommandOutputStreamingOutput } from "./command_output_streaming/output.ts";+import { commandOutputStreamingInput } from "./command_output_streaming/input.ts";import { assertTurnInterruptOutput } from "./turn_interrupt/codex_output.ts";import { turnInterruptInput } from "./turn_interrupt/input.ts";import { assertTurnInterruptMidToolClaudeOutput } from "./turn_interrupt_mid_tool/claude_output.ts";@@ -1567,6 +1569,31 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu},],},+ {+ name: "command_output_streaming",+ buildInput: commandOutputStreamingInput,+ providers: [+ {+ driver: ProviderDriverKind.make("codex"),+ transcriptFile: new URL(+ "./command_output_streaming/codex_transcript.ndjson",+ import.meta.url,+ ),+ modelSelection: CODEX_MODEL_SELECTION,+ runtimePolicyOverride: WORKSPACE_NEVER_POLICY,+ assertOutput: assertCommandOutputStreamingOutput,+ },+ {+ driver: ProviderDriverKind.make("claudeAgent"),+ transcriptFile: new URL(+ "./command_output_streaming/claude_transcript.ndjson",+ import.meta.url,+ ),+ modelSelection: CLAUDE_MODEL_SELECTION,+ assertOutput: assertCommandOutputStreamingOutput,+ },+ ],+ },{name: "turn_interrupt_mid_tool",buildInput: turnInterruptMidToolInput,diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.tsindex 1fda1cbf649..54c24f5e295 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts@@ -102,6 +102,10 @@ export const TURN_INTERRUPT_PROMPT ="Do not answer immediately. First run the local shell command `sleep 30`, then respond with exactly: interrupt fixture should not finish naturally.";export const TURN_INTERRUPT_MID_TOOL_PROMPT ="Run this exact local command: `node -e \"console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)\"`. Do not answer until it completes, then respond exactly: interrupt fixture should not finish naturally.";+/** A command that prints over a few seconds, with colour and a carriage-return redraw. */+const COMMAND_OUTPUT_STREAMING_COMMAND =+ "for i in 1 2 3 4; do printf '\\033[32mstream line %s\\033[0m\\n' $i; sleep 1; done; printf 'progress 50%%\\rprogress 100%%\\n'";+export const COMMAND_OUTPUT_STREAMING_PROMPT = `Run this exact shell command in the foreground and wait for it to finish: \`${COMMAND_OUTPUT_STREAMING_COMMAND}\`. Then respond exactly: command output fixture complete`;export const TURN_INTERRUPT_RECOVERY_PROMPT ="Respond with exactly: interrupt recovery fixture complete";export const MESSAGE_STEERING_STEER_PROMPT =diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex d3878ef8beb..21f74d94ba9 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -117,6 +117,7 @@ import * as EnvironmentTheme from "./environmentTheme.ts";import * as Keybindings from "./keybindings.ts";import * as ExternalLauncher from "./process/externalLauncher.ts";import * as ThreadManagementService from "./orchestration-v2/ThreadManagementService.ts";+import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts";import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";@@ -1239,6 +1240,7 @@ const layerWsRpc = (}};const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;+ const commandOutputHub = yield* CommandOutputHub.CommandOutputHub;const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2;const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService;const secretRequests = yield* SecretRequests.SecretRequests;@@ -2068,6 +2070,12 @@ const layerWsRpc = (Effect.andThen(subscribeOrchestrationV2Thread(input)),),),+ [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: (input) =>+ Stream.unwrap(+ Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(+ Effect.as(commandOutputHub.subscribe(input)),+ ),+ ),[WS_METHODS.scheduledTasksList]: (_input) =>scheduledTasks.list().pipe(Effect.map(withVisibleWebhookUrls)),[WS_METHODS.scheduledTasksSubscribe]: (_input) =>diff --git a/apps/web/src/components/chat/CommandOutputPanel.tsx b/apps/web/src/components/chat/CommandOutputPanel.tsxnew file mode 100644index 00000000000..bfa98583a84--- /dev/null+++ b/apps/web/src/components/chat/CommandOutputPanel.tsx@@ -0,0 +1,85 @@+import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";+import { TERMINAL_PALETTES, terminalOutputSpans } from "@t3tools/shared/terminalOutput";+import { useLayoutEffect, useMemo, useRef } from "react";++import { useTheme } from "../../hooks/useTheme";+import { useServerConfigs } from "../../state/entities";+import { orchestrationEnvironment } from "../../state/orchestration";+import { useEnvironmentQuery } from "../../state/query";++// Within this many pixels of the end still counts as following the output.+const FOLLOW_SLACK_PX = 8;++/** True when the environment streams command output; older servers only return final output. */+export function useCommandOutputStreaming(environmentId: EnvironmentId): boolean {+ return (+ useServerConfigs().get(environmentId)?.environment.capabilities.commandOutputStreaming === true+ );+}++/**+ * Output of one expanded command row: streams while the command runs, then+ * shows its final output. Mount it only when `useCommandOutputStreaming` holds.+ * It subscribes only while mounted, so collapsed rows and other threads receive nothing.+ */+export function CommandOutputPanel(props: {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+ readonly itemId: TurnItemId;+}) {+ const { data, error } = useEnvironmentQuery(+ orchestrationEnvironment.v2.commandOutput({+ environmentId: props.environmentId,+ input: { threadId: props.threadId, itemId: props.itemId },+ }),+ );+ const scrollRef = useRef<HTMLDivElement>(null);+ // Follow new output until the reader scrolls up; scrolling back down resumes.+ const followRef = useRef(true);+ const text = data?.output.text ?? "";+ const { resolvedTheme } = useTheme();+ const spans = useMemo(+ () => terminalOutputSpans(text, TERMINAL_PALETTES[resolvedTheme]),+ [text, resolvedTheme],+ );++ // This panel only re-renders when its output changes, so keep the end in view after each.+ useLayoutEffect(() => {+ const element = scrollRef.current;+ if (element && followRef.current) element.scrollTop = element.scrollHeight;+ });++ if (text.length === 0) {+ if (error) return <div className="text-destructive">Couldn't load output: {error}</div>;+ if (data === null) return <div className="text-muted-foreground italic">Loading output…</div>;+ return data.running ? null : <div className="text-muted-foreground italic">No output.</div>;+ }+ return (+ <div>+ {data?.output.truncated ? (+ <div className="text-muted-foreground italic">Earlier output not shown</div>+ ) : null}+ <div+ ref={scrollRef}+ onScroll={(event) => {+ const element = event.currentTarget;+ followRef.current =+ element.scrollHeight - element.scrollTop - element.clientHeight <= FOLLOW_SLACK_PX;+ }}+ className="max-h-80 overflow-auto text-muted-foreground"+ >+ {spans.map((span, index) =>+ span.style === null ? (+ span.text+ ) : (+ // Spans are rebuilt from scratch on every update and never reorder.+ // oxlint-disable-next-line react/no-array-index-key+ <span key={index} style={span.style}>+ {span.text}+ </span>+ ),+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsxindex 2bc30383254..7060536f03d 100644--- a/apps/web/src/components/chat/V2ItemInspector.tsx+++ b/apps/web/src/components/chat/V2ItemInspector.tsx@@ -14,7 +14,7 @@ import {import { formatDiffCount } from "@t3tools/client-runtime/diff-count";import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity";import { ExternalLinkIcon, GitBranchIcon, RotateCcwIcon } from "lucide-react";-import { memo, Suspense, use, useMemo } from "react";+import { memo, type ReactNode, Suspense, use, useMemo } from "react";import { useTheme } from "../../hooks/useTheme";import { cn } from "../../lib/utils";@@ -26,6 +26,7 @@ import { formatWorkspaceRelativePath } from "../../filePathDisplay";import { Button } from "../ui/button";import ChatMarkdown, { ChatMarkdownAssetImage } from "../ChatMarkdown";import { RenderErrorBoundary } from "../RenderErrorBoundary";+import { CommandOutputPanel, useCommandOutputStreaming } from "./CommandOutputPanel";import { resolveExternalWebLinkHref } from "./externalLinkContextMenu";import type { ExpandedImagePreview } from "./ExpandedImagePreview";import { ShellCommandBlock } from "./ShellCommandBlock";@@ -116,9 +117,10 @@ function StructuredValue({function useFetchedTurnItem(projectedItem: OrchestrationV2ProjectedTurnItem,environmentId: EnvironmentId,+ skip = false,) {const wireItem = projectedItem.item;- const fetches = turnItemNeedsDetailFetch(wireItem);+ const fetches = !skip && turnItemNeedsDetailFetch(wireItem);const detail = useTurnItemDetail(fetches? {@@ -208,6 +210,8 @@ function ToolCallBody(readonly args?: unknown;readonly toolName?: string | null;readonly exitCode?: number | undefined;+ /** Replaces the fetched output, e.g. with a command's live output. */+ readonly outputSlot?: ReactNode;},) {const call = toolCallLines({ command: props.command, args: props.args });@@ -229,7 +233,7 @@ function ToolCallBody(</div>) : null}{call.argsText ? <StructuredValue value={call.argsText} highlightJson /> : null}- <ToolOutput {...props} />+ {props.outputSlot ?? <ToolOutput {...props} />}{props.exitCode !== undefined && props.exitCode !== 0 ? (<div className="text-destructive">exit {props.exitCode}</div>) : null}@@ -238,7 +242,11 @@ function ToolCallBody(}export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspectorProps) {- const fetched = useFetchedTurnItem(props.projectedItem, props.environmentId);+ // Command rows stream their output, including the final output, from the server.+ const streamsOutput =+ useCommandOutputStreaming(props.environmentId) &&+ props.projectedItem.item.type === "command_execution";+ const fetched = useFetchedTurnItem(props.projectedItem, props.environmentId, streamsOutput);const item = fetched.item;const outputState = fetched.output;const support = useV2ItemSupport({@@ -268,6 +276,15 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspecexitCode={item.exitCode}{...outputState}onImageExpand={props.onImageExpand}+ outputSlot={+ streamsOutput ? (+ <CommandOutputPanel+ environmentId={props.environmentId}+ threadId={props.projectedItem.sourceThreadId}+ itemId={props.projectedItem.sourceItemId}+ />+ ) : undefined+ }/>) : null}diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.mdindex 83fb5e20e29..ac3d4a29d48 100644--- a/docs/internals/performance-regressions.md+++ b/docs/internals/performance-regressions.md@@ -34,6 +34,13 @@ The v2 checks pin these invariants:Explicit cross-environment transcript exports preserve full tool bodies so the destinationagent can read the context. The export rejects timeline JSON above the file attachment limitbefore sending it; the client still applies its attachment limit to the complete file.+- Live command output reaches a client only through `orchestration.subscribeCommandOutput`, which+ an expanded command row opens and closes with itself. Raw output deltas are never orchestration+ events: adapters send them to the+ [command output hub](../../apps/server/src/orchestration-v2/CommandOutputHub.ts) ahead of+ ingestion, which keeps one bounded tail per running command and throttles each subscriber. Do not+ route output deltas through `turn_item.updated`: a busy command would flood the event store and+ block ingestion for every other thread.- The initial shell contains active navigation rows only. Archived rows use the dedicated archivequery, and transcript message bodies stay in thread detail regardless of message size.- Shell resume sends deltas plus compact repository-enrichment metadata, not another full projectdiff --git a/docs/user/activity-log.md b/docs/user/activity-log.mdindex 24b28b61ea9..0aad505e0fa 100644--- a/docs/user/activity-log.md+++ b/docs/user/activity-log.md@@ -1,8 +1,9 @@# Activity logOn web and desktop, consecutive tool calls appear as an expandable summary. Open it to inspect-commands, tool inputs, status, and exit codes. Raw command output and tool-result bodies are not-shown. Use **Open diff** on a file change to review its contents.+commands, tool inputs, status, and exit codes. Expand a tool call to see its output. A running+command's output updates live, and long output shows only its most recent part. Use **Open diff** on+a file change to review its contents.T3 Orchestrator summaries describe the actions taken, such as **Ran 2 commands and sent messagesto 3 threads**. Repeated messages to the same destinations show both counts: **Sent 5 messages todiff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 703d418ac93..80462970d59 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -163,6 +163,10 @@"types": "./src/state/git.ts","default": "./src/state/git.ts"},+ "./state/command-output": {+ "types": "./src/state/commandOutput.ts",+ "default": "./src/state/commandOutput.ts"+ },"./state/item-support": {"types": "./src/state/itemSupport.ts","default": "./src/state/itemSupport.ts"diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.tsindex c3cd2967feb..f5ab86545d5 100644--- a/packages/client-runtime/src/rpc/client.ts+++ b/packages/client-runtime/src/rpc/client.ts@@ -53,6 +53,7 @@ export type EnvironmentSubscriptionRpcTag =| typeof WS_METHODS.providerInstallSubscribe| typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell| typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread+ | typeof ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput| typeof ORCHESTRATION_V2_WS_METHODS.searchThreadStream| typeof WS_METHODS.subscribeAuthAccess| typeof WS_METHODS.subscribeServerConfigdiff --git a/packages/client-runtime/src/state/commandOutput.test.ts b/packages/client-runtime/src/state/commandOutput.test.tsnew file mode 100644index 00000000000..13179efab08--- /dev/null+++ b/packages/client-runtime/src/state/commandOutput.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vite-plus/test";++import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT } from "./commandOutput.ts";++describe("applyCommandOutputFrame", () => {+ it("continues an escape and a redraw split across appends", () => {+ let view = applyCommandOutputFrame(EMPTY_COMMAND_OUTPUT, {+ kind: "replace",+ text: "install\n12%\u001b[3",+ truncated: false,+ running: true,+ });+ expect(view.output.text).toBe("install\n12%");+ view = applyCommandOutputFrame(view, {+ kind: "append",+ text: "2m\r100%\u001b[0m\n",+ truncated: false,+ running: true,+ });+ // The colour opened before the redraw survives it.+ expect(view.output.text).toBe("install\n\u001b[0;32m100%\u001b[0m\n");+ expect(view.running).toBe(true);+ });++ it("starts over from the tail a reconnect sends, keeping only that", () => {+ const stale = applyCommandOutputFrame(EMPTY_COMMAND_OUTPUT, {+ kind: "replace",+ text: "line 1\n",+ truncated: false,+ running: true,+ });+ const resumed = applyCommandOutputFrame(stale, {+ kind: "replace",+ text: "line 7\nline 8\n",+ truncated: true,+ running: true,+ });+ expect(resumed.output.text).toBe("line 7\nline 8\n");+ expect(resumed.output.truncated).toBe(true);+ });++ it("marks the output final when the command settles", () => {+ const view = applyCommandOutputFrame(EMPTY_COMMAND_OUTPUT, {+ kind: "replace",+ text: "done\n",+ truncated: false,+ running: false,+ });+ expect(view.output.text).toBe("done\n");+ expect(view.output.truncated).toBe(false);+ expect(view.running).toBe(false);+ });+});diff --git a/packages/client-runtime/src/state/commandOutput.ts b/packages/client-runtime/src/state/commandOutput.tsnew file mode 100644index 00000000000..4317862fa03--- /dev/null+++ b/packages/client-runtime/src/state/commandOutput.ts@@ -0,0 +1,37 @@+import type { OrchestrationV2CommandOutputFrame } from "@t3tools/contracts";+import {+ appendTerminalOutput,+ EMPTY_TERMINAL_OUTPUT,+ type TerminalOutputState,+} from "@t3tools/shared/terminalOutput";++/** One command row's output as a client holds it. */+export interface CommandOutputView {+ readonly output: TerminalOutputState;+ /** False once the command settled and `output` is final. */+ readonly running: boolean;+}++export const EMPTY_COMMAND_OUTPUT: CommandOutputView = {+ output: EMPTY_TERMINAL_OUTPUT,+ running: true,+};++/**+ * Applies one server frame. A `replace` carries the whole bounded tail (the+ * first frame, a viewer that fell behind, or the final output); an `append`+ * is raw terminal text normalized with the same rules the server uses.+ */+export function applyCommandOutputFrame(+ view: CommandOutputView,+ frame: OrchestrationV2CommandOutputFrame,+): CommandOutputView {+ const base = frame.kind === "replace" ? EMPTY_TERMINAL_OUTPUT : view.output;+ return {+ output: appendTerminalOutput(+ { ...base, truncated: base.truncated || frame.truncated },+ frame.text,+ ),+ running: frame.running,+ };+}diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.tsindex 68495a181c9..aab0edd2fad 100644--- a/packages/client-runtime/src/state/orchestration.ts+++ b/packages/client-runtime/src/state/orchestration.ts@@ -1,10 +1,13 @@import { ORCHESTRATION_V2_WS_METHODS, type ThreadId } from "@t3tools/contracts";import * as Effect from "effect/Effect";import * as Option from "effect/Option";+import * as Stream from "effect/Stream";import * as SubscriptionRef from "effect/SubscriptionRef";import type { HttpClient } from "effect/http";import { Atom } from "effect/reactivity";+import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT } from "./commandOutput.ts";+import {createEnvironmentRpcCommand,createEnvironmentRpcQueryAtomFamily,@@ -64,6 +67,19 @@ export function createOrchestrationEnvironmentAtoms<R, E>(tag: ORCHESTRATION_V2_WS_METHODS.subscribeThread,idleTtlMs: 0,}),+ // One expanded command row's output. Mounted only while the row is open,+ // and released as soon as it closes, so hidden rows receive nothing.+ commandOutput: createEnvironmentRpcSubscriptionAtomFamily(runtime, {+ label: "environment-data:orchestration-v2:command-output",+ tag: ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput,+ idleTtlMs: 0,+ // `scan` emits its seed first; skipping it keeps the row "loading" until the first frame.+ transform: (frames) =>+ frames.pipe(+ Stream.scan(() => EMPTY_COMMAND_OUTPUT, applyCommandOutputFrame),+ Stream.filter((view) => view !== EMPTY_COMMAND_OUTPUT),+ ),+ }),},turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:orchestration:turn-diff",diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 8086603afca..cc2e31fadae 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -221,6 +221,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({desktop servers whose app predates the remote trigger, where clientsmust keep telling the user to update the app on that machine. */desktopAppUpdate: Schema.optionalKey(Schema.Boolean),+ /** Server answers orchestration.subscribeCommandOutput. Absent on older servers,+ which never send command output, so clients must not subscribe. */+ commandOutputStreaming: Schema.optionalKey(Schema.Boolean),/** Server hosts preview tabs in its own headless Chromium (`runtime:"server"`) and streams them over `/api/preview-stream`. Clientswithout a local browser runtime open server tabs here. */diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex e4179a201be..d505631439e 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -3283,8 +3283,44 @@ export const ORCHESTRATION_V2_WS_METHODS = {subscribeArchivedShell: "orchestration.subscribeArchivedShell",subscribeShell: "orchestration.subscribeShell",subscribeThread: "orchestration.subscribeThread",+ subscribeCommandOutput: "orchestration.subscribeCommandOutput",} as const;+export const OrchestrationV2SubscribeCommandOutputInput = Schema.Struct({+ threadId: ThreadId,+ itemId: TurnItemId,+});+export type OrchestrationV2SubscribeCommandOutputInput =+ typeof OrchestrationV2SubscribeCommandOutputInput.Type;++/**+ * Output of one command row, separate from the thread stream so it is never+ * persisted as events and only reaches clients that show the row expanded.+ * `replace` carries the whole bounded tail (first frame, or after the client+ * fell behind); `append` extends it. Text is terminal output, not display+ * text: `replace` carries the cleaned tail plus the cursor and style escapes+ * needed to resume, and `append` carries raw chunks. Clients must feed both+ * through `appendTerminalOutput` from `@t3tools/shared/terminalOutput`.+ * The stream ends after a frame with `running: false`.+ */+export const OrchestrationV2CommandOutputFrame = Schema.Struct({+ kind: Schema.Literals(["replace", "append"]),+ text: Schema.String,+ /** Earlier output was dropped to keep the tail bounded. */+ truncated: Schema.Boolean,+ running: Schema.Boolean,+});+export type OrchestrationV2CommandOutputFrame = typeof OrchestrationV2CommandOutputFrame.Type;++export class OrchestrationV2CommandOutputError extends Schema.TaggedError<OrchestrationV2CommandOutputError>()(+ "OrchestrationV2CommandOutputError",+ {+ threadId: ThreadId,+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ },+) {}+export const OrchestrationV2ArchivedShellSnapshot = Schema.Struct({schemaVersion: PositiveInt,snapshotSequence: NonNegativeInt,@@ -3817,6 +3853,10 @@ export const OrchestrationV2RpcSchemas = {input: OrchestrationV2SubscribeThreadInput,output: OrchestrationV2ThreadStreamItem,},+ subscribeCommandOutput: {+ input: OrchestrationV2SubscribeCommandOutputInput,+ output: OrchestrationV2CommandOutputFrame,+ },} as const;export const ProviderReplayEntry = Schema.Union([diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 08d08609e57..fc99d123895 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -212,6 +212,7 @@ import {OrchestrationV2StopWorkflowError,OrchestrationV2DispatchCommandError,OrchestrationV2GetShellSnapshotError,+ OrchestrationV2CommandOutputError,OrchestrationV2GetThreadProjectionError,OrchestrationV2RpcSchemas,OrchestrationV2ThreadLaunchError,@@ -1738,6 +1739,16 @@ const WsOrchestrationV2SubscribeThreadRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODSstream: true,});+const WsOrchestrationV2SubscribeCommandOutputRpc = Rpc.make(+ ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput,+ {+ payload: OrchestrationV2RpcSchemas.subscribeCommandOutput.input,+ success: OrchestrationV2RpcSchemas.subscribeCommandOutput.output,+ error: Schema.Union([OrchestrationV2CommandOutputError, EnvironmentAuthorizationError]),+ stream: true,+ },+);+const WsSubscribeTerminalEventsRpc = Rpc.make(WS_METHODS.subscribeTerminalEvents, {payload: Schema.Struct({}),success: TerminalEvent,@@ -2079,4 +2090,5 @@ export const WsRpcGroup = RpcGroup.make(WsOrchestrationV2SubscribeArchivedShellRpc,WsOrchestrationV2SubscribeShellRpc,WsOrchestrationV2SubscribeThreadRpc,+ WsOrchestrationV2SubscribeCommandOutputRpc,).middleware(RpcScopeAuthorization);diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.tsindex 48d569137e7..4d7cc3136c6 100644--- a/packages/provider-core/src/server/ProviderAdapter.ts+++ b/packages/provider-core/src/server/ProviderAdapter.ts@@ -32,6 +32,7 @@ import {RunAttemptId,RunId,ThreadId,+ TurnItemId,} from "@t3tools/contracts";import * as Context from "effect/Context";import * as Schema from "effect/Schema";@@ -124,6 +125,18 @@ export const ProviderAdapterV2Event = Schema.Union([driver: ProviderDriverKind,turnItem: OrchestrationV2TurnItem,}),+ /**+ * Raw output from a running command. Never persisted: the session manager+ * hands it to the command output hub, which only clients showing the row see.+ * The item's final output still arrives in its `turn_item.updated`.+ */+ Schema.Struct({+ type: Schema.Literal("command_output.delta"),+ driver: ProviderDriverKind,+ threadId: ThreadId,+ itemId: TurnItemId,+ chunk: Schema.String,+ }),Schema.Struct({type: Schema.Literal("runtime_request.updated"),driver: ProviderDriverKind,diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.tsindex a43ed2901a5..0d3815c0cfc 100644--- a/packages/provider-cursor/src/server/adapter.ts+++ b/packages/provider-cursor/src/server/adapter.ts@@ -788,6 +788,10 @@ interface CursorProjectionTarget {readonly providerTurnId: OrchestrationV2ProviderTurn["id"] | null;}+// Fallback final output when Cursor's result carries none. The persisted row only+// ever shows a bounded tail, so keep a little more than that.+const MAX_CURSOR_STREAMED_OUTPUT_CHARS = 256 * 1024;+interface ActiveCursorToolCall {readonly callId: string;toolCall: ToolCall;@@ -1922,8 +1926,24 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (if (shell === undefined) {return;}- shell.streamedOutput += shellOutputText(update.event);- yield* emitToolArtifacts({ active: shell, completed: false });+ const chunk = shellOutputText(update.event);+ if (chunk.length === 0) return;+ // The completed call persists the final output once. Re-emitting the+ // whole accumulated output on every delta grew the event store+ // quadratically; live output goes to the command output hub instead.+ shell.streamedOutput = (shell.streamedOutput + chunk).slice(+ -MAX_CURSOR_STREAMED_OUTPUT_CHARS,+ );+ yield* emitProviderEvent({+ type: "command_output.delta",+ driver: CursorAgentSdk.CURSOR_PROVIDER,+ threadId: shell.target.threadId,+ itemId: idAllocator.derive.turnItemFromProviderItem({+ driver: CursorAgentSdk.CURSOR_PROVIDER,+ nativeItemId: shell.callId,+ }),+ chunk,+ });return;}default:diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 029aabda6c0..4b78dfb9543 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -119,6 +119,10 @@"types": "./src/toolActivity.ts","import": "./src/toolActivity.ts"},+ "./terminalOutput": {+ "types": "./src/terminalOutput.ts",+ "import": "./src/terminalOutput.ts"+ },"./toolOutput": {"types": "./src/toolOutput.ts","import": "./src/toolOutput.ts"diff --git a/packages/shared/src/terminalOutput.test.ts b/packages/shared/src/terminalOutput.test.tsnew file mode 100644index 00000000000..7f3a603b13b--- /dev/null+++ b/packages/shared/src/terminalOutput.test.ts@@ -0,0 +1,279 @@+import { describe, expect, it } from "vite-plus/test";++import {+ appendTerminalOutput,+ EMPTY_TERMINAL_OUTPUT,+ normalizeTerminalOutput,+ TERMINAL_PALETTES,+ terminalOutputPlainText,+ terminalOutputResumeText,+ terminalOutputSpans,+ terminalOutputTail,+ type TerminalOutputState,+} from "./terminalOutput.ts";++function feed(chunks: ReadonlyArray<string>, maxChars?: number): TerminalOutputState {+ return chunks.reduce(+ (state, chunk) => appendTerminalOutput(state, chunk, maxChars),+ EMPTY_TERMINAL_OUTPUT,+ );+}++const plain = (input: string) => terminalOutputPlainText(normalizeTerminalOutput(input).text);++describe("appendTerminalOutput", () => {+ it("keeps colours as canonical codes that reset at each line end", () => {+ expect(normalizeTerminalOutput("\u001b[1;32mPASS\u001b[0m ok\u001b]0;title\u0007\n").text).toBe(+ "\u001b[0;1;32mPASS\u001b[0m ok\n",+ );+ // A colour left on across a newline is restated on the next line.+ expect(normalizeTerminalOutput("\u001b[31mone\ntwo").text).toBe(+ "\u001b[0;31mone\u001b[0m\n\u001b[0;31mtwo\u001b[0m",+ );+ });++ it("keeps only the latest frame of a carriage-return progress bar", () => {+ expect(feed(["[1/3]", "\r[2/3]", "\r[3/3] done\nnext"]).text).toBe("[3/3] done\nnext");+ });++ it("redraws several lines in place when the cursor moves up", () => {+ // docker pull / pnpm style: print two bars, move up two lines, redraw both.+ const frames = [+ "layer a: 10%\nlayer b: 10%\n",+ "\u001b[2A\u001b[2Klayer a: 60%\n\u001b[2Klayer b: 40%\n",+ "\u001b[2A\u001b[2Klayer a: done\n\u001b[2Klayer b: done\n",+ ];+ expect(feed(frames).text).toBe("layer a: done\nlayer b: done\n");+ });++ it("erases from the cursor to the end of the screen", () => {+ // log-update style: move up, clear everything below, print the new frame.+ expect(plain("status 1\ndetail 1\n\u001b[2A\u001b[Jstatus 2\n")).toBe("status 2\n");+ });++ it("overwrites in place like a terminal: carriage return, backspace, columns", () => {+ expect(plain("progress 100%\rdone\u001b[K")).toBe("done");+ expect(plain("abc\b\bX")).toBe("aXc");+ expect(plain("12345\u001b[3GX")).toBe("12X45");+ });++ it("treats CRLF as one newline even when the pair is split across chunks", () => {+ const state = feed(["one\r", "\ntwo\r\n"]);+ expect(state.text).toBe("one\ntwo\n");+ expect(state.pending).toBe("");+ });++ it("holds an escape sequence split across chunks until it finishes", () => {+ const first = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, "red: \u001b[3");+ expect(first.text).toBe("red: ");+ expect(feed(["red: \u001b[3", "1mR\u001b[0m"]).text).toBe("red: \u001b[0;31mR\u001b[0m");+ });++ it("drops binary control bytes but keeps tabs and replacement characters", () => {+ expect(normalizeTerminalOutput("a\u0000b\u0007\tc�\u0090d").text).toBe("ab\tc�d");+ });++ it("keeps a bounded tail that starts on a fresh line", () => {+ const lines = Array.from({ length: 2_000 }, (_, index) => `line ${index}`).join("\n");+ const state = feed([lines], 1_000);+ expect(state.truncated).toBe(true);+ expect(state.text.length).toBeLessThanOrEqual(1_000);+ expect(state.text.startsWith("line ")).toBe(true);+ expect(state.text.endsWith("line 1999")).toBe(true);+ });++ it("stays bounded across many appends of huge output, including one endless line", () => {+ let state = EMPTY_TERMINAL_OUTPUT;+ for (let index = 0; index < 5_000; index += 1) {+ state = appendTerminalOutput(state, "y\n".repeat(200), 4_096);+ }+ expect(state.text.length).toBeLessThanOrEqual(4_096);+ expect(state.truncated).toBe(true);+ for (let index = 0; index < 1_000; index += 1) {+ state = appendTerminalOutput(state, ".".repeat(100), 4_096);+ }+ expect(state.text.length).toBeLessThanOrEqual(4_096);+ expect(state.text.endsWith(".")).toBe(true);+ });++ it("hides a long string sequence's payload however it is split into chunks", () => {+ const input = `a\u001b]0;${"t".repeat(100)}\u0007b`;+ expect(feed([input]).text).toBe("ab");+ expect(feed(["a\u001b]0;", "t".repeat(100), "\u0007b"]).text).toBe("ab");+ expect(feed([`a\u001b]0;${"t".repeat(80)}`, "\u001b", "\\b"]).text).toBe("ab");+ });++ it("hides an SOS string sequence and its payload", () => {+ expect(normalizeTerminalOutput("a\u001bXhidden \u001b\\b").text).toBe("ab");+ });++ it("drops an escape sequence that never terminates and resumes after it", () => {+ expect(feed(["ok\u001b]", "x".repeat(200), "\nafter"]).text).toBe("ok\nafter");+ });+});++describe("appendTerminalOutput edge cases from review", () => {+ it("reads colon-form true colour with or without a colour-space id", () => {+ const red = normalizeTerminalOutput("\u001b[38:2::255:0:0mR").text;+ expect(red).toBe("\u001b[0;38;2;255;0;0mR\u001b[0m");+ expect(normalizeTerminalOutput("\u001b[38:2:0:255:0:0mR").text).toBe(red);+ });++ it("clears only scrollback on ESC[3J", () => {+ const lines = Array.from({ length: 70 }, (_, index) => `line ${index}`).join("\n");+ const state = feed([lines, "\u001b[3J"]);+ expect(state.text.startsWith("line 6\n")).toBe(true);+ expect(state.text.endsWith("line 69")).toBe(true);+ expect(state.truncated).toBe(true);+ });++ it("keeps the whole window within the tail when every line is long", () => {+ const long = `${"x".repeat(900)}\n`;+ const state = feed([long.repeat(64)], 4_096);+ const windowChars = state.screen.lines.reduce(+ (total, line) => total + line.reduce((sum, run) => sum + run.text.length, 0),+ 0,+ );+ expect(windowChars).toBeLessThanOrEqual(4_096);+ expect(state.text.length).toBeLessThanOrEqual(4_096);+ });++ it("bounds long lines below a cursor that moved up", () => {+ const long = `${"x".repeat(900)}\n`;+ const state = feed([long.repeat(63), "\u001b[63A"], 4_096);+ const windowChars = state.screen.lines.reduce(+ (total, line) => total + line.reduce((sum, run) => sum + run.text.length, 0),+ 0,+ );+ expect(windowChars).toBeLessThanOrEqual(2 * 4_096);+ });+});++describe("appendTerminalOutput under adversarial output", () => {+ it("gives the same result however the output is split into chunks", () => {+ const input = "abcdef\rX\u001b[31mred\u001b[0m\nnext line\r\u001b[2Kdone\n";+ const whole = feed([input], 3).text;+ for (let cut = 1; cut < input.length; cut += 1) {+ expect(feed([input.slice(0, cut), input.slice(cut)], 3).text).toBe(whole);+ }+ expect(feed(["abcdef", "\rX"], 3).text).toBe(feed(["abcdef\rX"], 3).text);+ });++ it("handles a colour change on every character in linear time", () => {+ const chunk = Array.from({ length: 200_000 }, (_, index) =>+ index % 2 === 0 ? "\u001b[31mx" : "\u001b[32my",+ ).join("");+ const started = performance.now();+ const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, chunk);+ expect(performance.now() - started).toBeLessThan(2_000);+ expect(terminalOutputPlainText(state.text).length).toBeLessThanOrEqual(64 * 1024);+ });++ it("keeps scrollback bounded while a single huge chunk scrolls", () => {+ const state = appendTerminalOutput(+ EMPTY_TERMINAL_OUTPUT,+ "line of log output\n".repeat(200_000),+ 4_096,+ );+ expect(state.screen.settled.length).toBeLessThanOrEqual(2 * 4_096);+ expect(state.truncated).toBe(true);+ });+});++describe("terminalOutputResumeText", () => {+ it("lets a viewer that starts from it apply later chunks exactly as the source does", () => {+ // Mid-redraw: cursor two lines up, a colour on, and half an escape pending.+ const chunks = [+ "a: 1%\nb: 1%\n",+ "\u001b[2A\u001b[2K\u001b[33ma: 5",+ "0%\u001b[0",+ "m\n\u001b[2Kb: 50%\n",+ ];+ const source = feed(chunks.slice(0, 3));+ const viewer = appendTerminalOutput(+ appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source)),+ chunks[3]!,+ );+ expect(viewer.text).toBe(feed(chunks).text);+ expect(terminalOutputPlainText(viewer.text)).toBe("a: 50%\nb: 50%\n");+ });+});++describe("terminalOutputResumeText with a saved cursor or trimmed output", () => {+ it("restores a cursor saved before the resync", () => {+ const source = feed(["abc\u001b7def"]);+ const viewer = appendTerminalOutput(+ appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source)),+ "\u001b8X",+ );+ expect(viewer.text).toBe("abcXef");+ });++ it("stays on the right line when early output was trimmed away", () => {+ const lines = Array.from({ length: 40 }, (_, index) => `line ${index}`).join("\n");+ const source = feed([lines, "\u001b[1A\rLINE"], 120);+ const viewer = appendTerminalOutput(+ appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, terminalOutputResumeText(source), 120),+ " edited",+ 120,+ );+ expect(viewer.text).toBe(appendTerminalOutput(source, " edited", 120).text);+ });++ it("survives a huge cursor move without throwing", () => {+ expect(() => normalizeTerminalOutput("a\u001b[999999999999Cb")).not.toThrow();+ });+});++describe("terminalOutputTail", () => {+ it("never begins on a lone low surrogate", () => {+ const text = `${"a".repeat(10)}😀${"b".repeat(4)}`;+ const tail = terminalOutputTail(text, 5);+ expect(tail.text).toBe("bbbb");+ });++ it("never splits a colour code and keeps the colour in force when cutting a line", () => {+ const text = `\u001b[0;32m${"g".repeat(100)}\u001b[0m`;+ const cut = terminalOutputTail(text, 10).text;+ expect(cut.startsWith("\u001b[0;32m")).toBe(true);+ expect(terminalOutputPlainText(cut)).toMatch(/^g+$/u);+ });+});++describe("terminalOutputSpans", () => {+ it("resolves standard, 256-colour and true-colour codes against the palette", () => {+ const text = normalizeTerminalOutput(+ "\u001b[31mred\u001b[0m \u001b[1;38;5;196mhot\u001b[0m \u001b[38;2;1;2;3mrgb\u001b[0m",+ ).text;+ expect(terminalOutputSpans(text, TERMINAL_PALETTES.dark)).toEqual([+ { text: "red", style: { color: TERMINAL_PALETTES.dark[1] } },+ { text: " ", style: null },+ { text: "hot", style: { color: "rgb(255,0,0)", fontWeight: "600" } },+ { text: " ", style: null },+ { text: "rgb", style: { color: "rgb(1,2,3)" } },+ ]);+ });++ it("keeps text on a coloured background readable on either palette", () => {+ // "PASS" badge: black on green; "FAIL" badge: grey-white on red.+ const text = normalizeTerminalOutput(+ "\u001b[30;42m PASS \u001b[0m\u001b[1;37;41m FAIL \u001b[0m",+ ).text;+ for (const palette of [TERMINAL_PALETTES.light, TERMINAL_PALETTES.dark]) {+ for (const span of terminalOutputSpans(text, palette)) {+ expect(span.style?.color === undefined).toBe(false);+ }+ }+ const [pass, fail] = terminalOutputSpans(text, TERMINAL_PALETTES.light);+ expect(pass?.style?.color).toBe("#ffffff");+ expect(fail?.style?.color).toBe("#ffffff");+ });++ it("collapses the rest into plain text past the span limit", () => {+ const text = normalizeTerminalOutput("\u001b[31mx\u001b[32my".repeat(50)).text;+ const spans = terminalOutputSpans(text, TERMINAL_PALETTES.light, 10);+ expect(spans.length).toBe(11);+ expect(spans.at(-1)?.style).toBeNull();+ expect(spans.map((span) => span.text).join("")).toBe("xy".repeat(50));+ });+});diff --git a/packages/shared/src/terminalOutput.ts b/packages/shared/src/terminalOutput.tsnew file mode 100644index 00000000000..f4da028a390--- /dev/null+++ b/packages/shared/src/terminalOutput.ts@@ -0,0 +1,872 @@+/**+ * Turns raw terminal bytes (already decoded to text) into a bounded tail that+ * a timeline can show. Runs on the server before output crosses the wire, and+ * again on clients when they splice appends onto what they hold, so both sides+ * must reach the same state from the same input.+ *+ * It models a small terminal: the last `LIVE_LINES` lines form a window that+ * cursor movement can rewrite, so `\r` progress bars and multi-line redraws+ * (docker pull, pnpm, test reporters) keep only their latest frame. Older lines+ * are fixed text. The model has no width, so lines never wrap.+ *+ * - Colours and text attributes (SGR) survive as canonical `ESC[0;…m` codes.+ * Every line starts from the default style and resets at its end, so any line+ * boundary is a safe place to cut. `terminalOutputSpans` reads them back.+ * - Cursor moves, line and screen erases, and save/restore are applied. Other+ * escape sequences (titles, modes) and control characters are dropped.+ * - Only the last `maxChars` survive, cut at a line boundary when possible.+ *+ * Chunks can split an escape sequence, so the unfinished fragment is carried in+ * `pending` until the next chunk arrives.+ */+export interface TerminalOutputState {+ /** What to show: fixed lines, then the window. Contains only SGR escapes. */+ readonly text: string;+ /** True once anything was dropped from the front. */+ readonly truncated: boolean;+ /** An unfinished escape sequence awaiting the next chunk. */+ readonly pending: string;+ readonly screen: TerminalScreen;+}++/** A styled stretch of one line. `pen` is canonical SGR parameters, "" for default. */+interface Run {+ readonly pen: string;+ readonly text: string;+}+type Line = ReadonlyArray<Run>;++interface TerminalScreen {+ /** Serialized lines, each ending in `\n`, that scrolled out of the window. */+ readonly settled: string;+ /** The live window; never empty. */+ readonly lines: ReadonlyArray<Line>;+ readonly row: number;+ readonly col: number;+ readonly pen: string;+ readonly saved: { readonly row: number; readonly col: number } | null;+}++export const EMPTY_TERMINAL_OUTPUT: TerminalOutputState = {+ text: "",+ truncated: false,+ pending: "",+ screen: { settled: "", lines: [[]], row: 0, col: 0, pen: "", saved: null },+};++/** The default tail kept for one running command, in UTF-16 code units. */+export const TERMINAL_OUTPUT_TAIL_CHARS = 64 * 1024;++/** Lines that cursor movement can still reach; older output is fixed. */+const LIVE_LINES = 64;++// Longest fragment we will hold waiting for an escape sequence to finish.+const MAX_PENDING_ESCAPE = 64;++const ESC = "\u001b";++function sgr(pen: string): string {+ return pen === "" ? `${ESC}[0m` : `${ESC}[0;${pen}m`;+}++// Lengths of lines already measured. Lines are never mutated once a feed ends.+const lineLengths = new WeakMap<Line, number>();++function lineLength(line: Line): number {+ const cached = lineLengths.get(line);+ if (cached !== undefined) return cached;+ let length = 0;+ for (const run of line) length += run.text.length;+ lineLengths.set(line, length);+ return length;+}++// Past this many style changes, a line's oldest runs lose their style. Rendering+// already caps spans, and it keeps per-write work bounded on colour-per-character output.+const MAX_LINE_RUNS = 2_048;++/** Runs covering columns [start, end) of `line`. */+function sliceLine(line: Line, start: number, end: number): Array<Run> {+ const out: Array<Run> = [];+ let offset = 0;+ for (const run of line) {+ const runEnd = offset + run.text.length;+ if (runEnd > start && offset < end) {+ out.push({+ pen: run.pen,+ text: run.text.slice(Math.max(0, start - offset), Math.min(run.text.length, end - offset)),+ });+ }+ offset = runEnd;+ if (offset >= end) break;+ }+ return out;+}++function pushRun(runs: Array<Run>, run: Run): void {+ if (run.text.length === 0) return;+ const last = runs.at(-1);+ if (last !== undefined && last.pen === run.pen) {+ runs[runs.length - 1] = { pen: last.pen, text: last.text + run.text };+ } else {+ runs.push(run);+ }+}++/** Drops the first `count` columns of a line this feed owns, in place. */+function trimLineStart(runs: Array<Run>, count: number): void {+ let dropped = 0;+ let remaining = count;+ while (remaining > 0 && dropped < runs.length) {+ const run = runs[dropped]!;+ if (run.text.length <= remaining) {+ remaining -= run.text.length;+ dropped += 1;+ } else {+ runs[dropped] = { pen: run.pen, text: run.text.slice(remaining) };+ remaining = 0;+ }+ }+ if (dropped > 0) runs.splice(0, dropped);+}++/** `line` with `text` written over it from `col`, as a terminal overwrites. */+function writeLine(line: Line, col: number, text: string, pen: string): Line {+ const length = lineLength(line);+ if (col === length) {+ // The common case: printing at the end of the line.+ const runs = line.slice();+ pushRun(runs, { pen, text });+ return runs;+ }+ const runs: Array<Run> = [];+ for (const run of sliceLine(line, 0, Math.min(col, length))) pushRun(runs, run);+ if (col > length) pushRun(runs, { pen: "", text: " ".repeat(col - length) });+ pushRun(runs, { pen, text });+ for (const run of sliceLine(line, col + text.length, length)) pushRun(runs, run);+ return runs;+}++/** Erase in line: 0 cursor to end, 1 start to cursor, 2 whole line. */+function eraseLine(line: Line, col: number, mode: number): Line {+ const length = lineLength(line);+ if (mode === 0) return sliceLine(line, 0, col);+ if (mode === 1) {+ const runs: Array<Run> = [];+ pushRun(runs, { pen: "", text: " ".repeat(Math.min(col + 1, length)) });+ for (const run of sliceLine(line, col + 1, length)) pushRun(runs, run);+ return runs;+ }+ return [];+}++function serializeLine(line: Line): string {+ let out = "";+ let current = "";+ for (const run of line) {+ if (run.pen !== current) {+ out += sgr(run.pen);+ current = run.pen;+ }+ out += run.text;+ }+ return current === "" ? out : out + sgr("");+}++interface Attributes {+ bold: boolean;+ dim: boolean;+ italic: boolean;+ underline: boolean;+ strike: boolean;+ inverse: boolean;+ fg: string;+ bg: string;+}++function parsePen(pen: string): Attributes {+ const attributes: Attributes = {+ bold: false,+ dim: false,+ italic: false,+ underline: false,+ strike: false,+ inverse: false,+ fg: "",+ bg: "",+ };+ if (pen !== "") applySgr(attributes, pen.split(";").map(Number));+ return attributes;+}++function formatPen(attributes: Attributes): string {+ const parts: Array<string> = [];+ if (attributes.bold) parts.push("1");+ if (attributes.dim) parts.push("2");+ if (attributes.italic) parts.push("3");+ if (attributes.underline) parts.push("4");+ if (attributes.inverse) parts.push("7");+ if (attributes.strike) parts.push("9");+ if (attributes.fg !== "") parts.push(attributes.fg);+ if (attributes.bg !== "") parts.push(attributes.bg);+ return parts.join(";");+}++/** Reads an extended colour (`5;n` or `2;r;g;b`) starting at `index`; returns the code and next index. */+function extendedColor(+ code: number,+ params: ReadonlyArray<number>,+ index: number,+): [string | undefined, number] {+ const mode = params[index + 1];+ if (mode === 5) {+ const value = params[index + 2];+ return value === undefined || value > 255+ ? [undefined, index + 3]+ : [`${code};5;${value}`, index + 3];+ }+ if (mode === 2) {+ const [r, g, b] = [params[index + 2], params[index + 3], params[index + 4]];+ if (r === undefined || g === undefined || b === undefined) return [undefined, index + 5];+ return [`${code};2;${r & 255};${g & 255};${b & 255}`, index + 5];+ }+ return [undefined, index + 2];+}++function applySgr(attributes: Attributes, params: ReadonlyArray<number>): void {+ if (params.length === 0) params = [0];+ for (let index = 0; index < params.length;) {+ const code = params[index]!;+ if (code === 0 || Number.isNaN(code)) {+ Object.assign(attributes, parsePen(""));+ } else if (code === 1) attributes.bold = true;+ else if (code === 2) attributes.dim = true;+ else if (code === 3) attributes.italic = true;+ else if (code === 4) attributes.underline = true;+ else if (code === 7) attributes.inverse = true;+ else if (code === 9) attributes.strike = true;+ else if (code === 22) attributes.bold = attributes.dim = false;+ else if (code === 23) attributes.italic = false;+ else if (code === 24) attributes.underline = false;+ else if (code === 27) attributes.inverse = false;+ else if (code === 29) attributes.strike = false;+ else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) attributes.fg = String(code);+ else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))+ attributes.bg = String(code);+ else if (code === 39) attributes.fg = "";+ else if (code === 49) attributes.bg = "";+ else if (code === 38 || code === 48) {+ const [color, next] = extendedColor(code, params, index);+ if (color !== undefined) attributes[code === 38 ? "fg" : "bg"] = color;+ index = next;+ continue;+ }+ index += 1;+ }+}++const STRING_SEQUENCE_INTRODUCERS = new Set(["]", "P", "X", "_", "^"]);++/** Length of a complete escape sequence starting at `index` (an ESC), or -1 if unfinished. */+function escapeLength(input: string, index: number): number {+ const next = input[index + 1];+ if (next === undefined) return -1;+ if (next === "[") {+ // CSI: parameters/intermediates, then a final byte in @-~.+ for (let cursor = index + 2; cursor < input.length; cursor += 1) {+ const code = input.charCodeAt(cursor);+ if (code >= 0x40 && code <= 0x7e) return cursor - index + 1;+ }+ return -1;+ }+ if (STRING_SEQUENCE_INTRODUCERS.has(next)) {+ // OSC/DCS/SOS/APC/PM end at BEL or ST (ESC \). A newline also ends one (and is+ // kept), so a stray introducer in binary output can't hide everything after it.+ for (let cursor = index + 2; cursor < input.length; cursor += 1) {+ if (input[cursor] === "\u0007") return cursor - index + 1;+ if (input[cursor] === "\n") return cursor - index;+ if (input[cursor] === ESC) {+ if (cursor + 1 >= input.length) return -1;+ if (input[cursor + 1] === "\\") return cursor - index + 2;+ }+ }+ return -1;+ }+ // Charset designation (ESC ( B) takes three; other two-byte sequences (ESC 7) two.+ if (next === "(" || next === ")" || next === "*" || next === "+") {+ return index + 2 < input.length ? 3 : -1;+ }+ return 2;+}++const penTransitions = new Map<string, string>();++/** CSI parameters as numbers. Colon sub-parameters (`38:2::r:g:b`) carry an optional+ colour-space id that the semicolon form (`38;2;r;g;b`) has no slot for. */+function csiParams(params: string): Array<number> {+ const numbers: Array<number> = [];+ for (const part of params.split(";")) {+ if (!part.includes(":")) {+ numbers.push(Number(part));+ continue;+ }+ const sub = part.split(":").map(Number);+ if ((sub[0] === 38 || sub[0] === 48) && sub[1] === 2 && sub.length >= 6) sub.splice(2, 1);+ numbers.push(...sub);+ }+ return numbers;+}++/** A mutable copy of the screen, for applying one chunk. */+class Terminal {+ settled: string;+ lines: Array<Line>;+ row: number;+ col: number;+ pen: string;+ saved: { row: number; col: number } | null;+ /** Output was discarded on purpose (scrollback cleared or window over budget). */+ dropped = false;+ readonly maxChars: number;+ /** Lines created during this feed, which it may extend in place. */+ private readonly owned = new WeakSet<Line>();++ constructor(screen: TerminalScreen, maxChars: number) {+ this.maxChars = maxChars;+ this.settled = screen.settled;+ this.lines = screen.lines.slice();+ this.row = screen.row;+ this.col = screen.col;+ this.pen = screen.pen;+ this.saved = screen.saved;+ }++ write(text: string): void {+ let line = this.lines[this.row]!;+ const length = lineLength(line);+ if (this.col === length && this.owned.has(line)) {+ // Printing at the end of a line this feed already copied: extend it in place.+ pushRun(line as Array<Run>, { pen: this.pen, text });+ lineLengths.set(line, length + text.length);+ } else {+ line = writeLine(line, this.col, text, this.pen);+ this.owned.add(line);+ }+ this.col += text.length;+ if (line.length > MAX_LINE_RUNS) {+ // Fold all but the newest runs into one plain run, so trimming below eats it cheaply.+ const keep = line.length - MAX_LINE_RUNS / 8;+ const plain = line+ .slice(0, keep)+ .map((run) => run.text)+ .join("");+ line = [{ pen: "", text: plain }, ...line.slice(keep)];+ this.owned.add(line);+ }+ // A line keeps only its last `maxChars` columns, trimmed on every write so the+ // result never depends on how the output was split into chunks.+ let current = lineLength(line);+ if (current > this.maxChars) {+ let removed = current - this.maxChars;+ if (!this.owned.has(line)) {+ line = line.slice();+ this.owned.add(line);+ }+ trimLineStart(line as Array<Run>, removed);+ // Never start on a lone low surrogate.+ const first = line[0]?.text.charCodeAt(0) ?? 0;+ if (first >= 0xdc00 && first <= 0xdfff) {+ trimLineStart(line as Array<Run>, 1);+ removed += 1;+ }+ current -= removed;+ this.dropped = true;+ this.col = Math.max(0, this.col - removed);+ if (this.saved !== null && this.saved.row === this.row) {+ this.saved = { ...this.saved, col: Math.max(0, this.saved.col - removed) };+ }+ }+ lineLengths.set(line, current);+ this.lines[this.row] = line;+ }++ newline(): void {+ this.row += 1;+ this.col = 0;+ if (this.row === this.lines.length) this.lines.push([]);+ while (this.lines.length > LIVE_LINES) this.scrollOut();+ }++ /** Moves the top line out of the window into scrollback; returns its length. */+ scrollOut(): number {+ const line = this.lines.shift()!;+ this.settle(line);+ this.row -= 1;+ if (this.saved !== null) this.saved = { ...this.saved, row: Math.max(0, this.saved.row - 1) };+ return lineLength(line);+ }++ /** Fixes a line that left the window, keeping scrollback near the tail size as it grows. */+ settle(line: Line): void {+ this.settled += `${serializeLine(line)}\n`;+ if (this.settled.length > 2 * this.maxChars) {+ this.settled = terminalOutputTail(this.settled, this.maxChars).text;+ this.dropped = true;+ }+ }++ moveTo(row: number, col: number): void {+ this.row = Math.max(0, Math.min(this.lines.length - 1, row));+ // A huge column (ESC[999999999C) would otherwise pad a line past any string limit.+ this.col = Math.max(0, Math.min(TERMINAL_OUTPUT_TAIL_CHARS, col));+ }++ csi(params: string, final: string): void {+ if (/^[?>=]/u.test(params)) return; // Mode switches (cursor visibility, bracketed paste).+ const numbers = params === "" ? [] : csiParams(params);+ const count = Math.max(1, numbers[0] || 1);+ switch (final) {+ case "m": {+ // Colourful output repeats a handful of transitions, so they are cached.+ const key = `${this.pen}|${params}`;+ let pen = penTransitions.get(key);+ if (pen === undefined) {+ const attributes = parsePen(this.pen);+ applySgr(attributes, numbers);+ pen = formatPen(attributes);+ if (penTransitions.size >= 512) penTransitions.clear();+ penTransitions.set(key, pen);+ }+ this.pen = pen;+ return;+ }+ case "A":+ return this.moveTo(this.row - count, this.col);+ case "B":+ return this.moveTo(this.row + count, this.col);+ case "C":+ return this.moveTo(this.row, this.col + count);+ case "D":+ return this.moveTo(this.row, this.col - count);+ case "E":+ return this.moveTo(this.row + count, 0);+ case "F":+ return this.moveTo(this.row - count, 0);+ case "G":+ return this.moveTo(this.row, count - 1);+ case "H":+ case "f":+ // Rows count from the top of the window: there is no fixed screen height.+ return this.moveTo(count - 1, Math.max(1, numbers[1] || 1) - 1);+ case "K":+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, numbers[0] ?? 0);+ return;+ case "J": {+ const mode = numbers[0] ?? 0;+ if (mode === 0) {+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 0);+ this.lines.length = this.row + 1;+ } else if (mode === 1) {+ for (let row = 0; row < this.row; row += 1) this.lines[row] = [];+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 1);+ } else if (mode === 3) {+ // Clear scrollback: what already scrolled out goes, the window stays.+ if (this.settled !== "") this.dropped = true;+ this.settled = "";+ } else {+ // A cleared screen starts the window over; what scrolled out stays.+ this.lines = [[]];+ this.row = 0;+ this.col = 0;+ }+ return;+ }+ case "s":+ this.saved = { row: this.row, col: this.col };+ return;+ case "u":+ if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);+ return;+ default:+ }+ }++ escape(sequence: string): void {+ if (sequence[1] === "[") {+ this.csi(sequence.slice(2, -1), sequence.at(-1)!);+ } else if (sequence === `${ESC}7`) {+ this.saved = { row: this.row, col: this.col };+ } else if (sequence === `${ESC}8`) {+ if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);+ } else if (sequence === `${ESC}M`) {+ this.moveTo(this.row - 1, this.col); // Reverse line feed.+ }+ }++ /** Applies `input`; returns the unfinished escape left at its end. */+ feed(input: string): string {+ let printable = 0;+ const flush = (end: number) => {+ if (end > printable) this.write(input.slice(printable, end));+ };+ for (let index = 0; index < input.length; index += 1) {+ const code = input.charCodeAt(index);+ // Printable text, including tabs, is batched into one write.+ if (code === 0x09 || (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f))) {+ continue;+ }+ flush(index);+ printable = index + 1;+ if (code === 0x0a) this.newline();+ else if (code === 0x0d) this.col = 0;+ else if (code === 0x08) this.col = Math.max(0, this.col - 1);+ else if (code === 0x1b) {+ const length = escapeLength(input, index);+ if (length === -1) {+ const fragment = input.slice(index);+ if (fragment.length <= MAX_PENDING_ESCAPE) return fragment;+ // A long string sequence keeps only its introducer (and a trailing ESC that+ // may start its ST), so the payload stays hidden until it ends.+ if (STRING_SEQUENCE_INTRODUCERS.has(fragment[1]!)) {+ return fragment.slice(0, 2) + (fragment.endsWith(ESC) ? ESC : "");+ }+ // Any other runaway sequence is noise; drop it instead of waiting forever.+ return "";+ }+ this.escape(input.slice(index, index + length));+ index += length - 1;+ printable = index + 1;+ }+ // Other C0, DEL and C1 controls carry no visible text.+ }+ flush(input.length);+ return "";+ }+}++/** The active style at `index` of `text` and where a cut there may safely start. */+function styleAt(text: string, index: number): { readonly start: number; readonly prefix: string } {+ const lineStart = text.lastIndexOf("\n", index - 1) + 1;+ let prefix = "";+ let cursor = lineStart;+ while (cursor < index) {+ const found = text.indexOf(`${ESC}[`, cursor);+ if (found === -1 || found >= index) break;+ const end = text.indexOf("m", found);+ if (end === -1) break;+ if (end >= index) return { start: end + 1, prefix: text.slice(found, end + 1) };+ prefix = text.slice(found, end + 1);+ cursor = end + 1;+ }+ return { start: index, prefix: prefix === sgr("") ? "" : prefix };+}++/** Keeps the last `maxChars`, preferring to start on a fresh line. */+export function terminalOutputTail(+ text: string,+ maxChars: number,+): { readonly text: string; readonly truncated: boolean } {+ if (text.length <= maxChars) return { text, truncated: false };+ let start = text.length - maxChars;+ const newline = text.indexOf("\n", start);+ // Drop the partial first line unless that would discard most of the tail.+ if (newline !== -1 && newline - start < maxChars / 4) {+ return { text: text.slice(newline + 1), truncated: true };+ }+ // Cutting inside a line: never split an escape, and keep the colour in force.+ const style = styleAt(text, start);+ start = style.start;+ // Never start on a lone low surrogate.+ const first = text.charCodeAt(start);+ if (first >= 0xdc00 && first <= 0xdfff) start += 1;+ return { text: style.prefix + text.slice(start), truncated: true };+}++/** Appends one decoded chunk and returns the new bounded state. */+export function appendTerminalOutput(+ state: TerminalOutputState,+ chunk: string,+ maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,+): TerminalOutputState {+ const input = state.pending + chunk;+ if (input.length === 0) return state;+ const terminal = new Terminal(state.screen, maxChars);+ const pending = terminal.feed(input);+ let truncated = state.truncated;+ // The window as a whole stays within the tail too: oldest lines scroll out early.+ let windowChars = terminal.lines.reduce((total, line) => total + lineLength(line), 0);+ while (windowChars > maxChars && terminal.row > 0) windowChars -= terminal.scrollOut();+ // Lines below a cursor that moved up can't scroll out; they keep only their ends.+ if (windowChars > maxChars) {+ let budget = maxChars;+ for (let row = 0; row <= terminal.row; row += 1) budget -= lineLength(terminal.lines[row]!);+ for (let row = terminal.row + 1; row < terminal.lines.length; row += 1) {+ const line = terminal.lines[row]!;+ const length = lineLength(line);+ const keep = Math.max(0, Math.min(length, budget));+ if (keep < length) {+ truncated = true;+ terminal.lines[row] = sliceLine(line, length - keep, length);+ if (terminal.saved !== null && terminal.saved.row === row) {+ terminal.saved = {+ ...terminal.saved,+ col: Math.max(0, terminal.saved.col - (length - keep)),+ };+ }+ }+ budget -= keep;+ }+ }+ if (terminal.dropped) truncated = true;+ const settled = terminalOutputTail(terminal.settled, maxChars);+ const window = terminal.lines.map(serializeLine).join("\n");+ const tail = terminalOutputTail(settled.text + window, maxChars);+ return {+ text: tail.text,+ truncated: truncated || settled.truncated || tail.truncated,+ pending,+ screen: {+ settled: settled.text,+ lines: terminal.lines,+ row: terminal.row,+ col: terminal.col,+ pen: terminal.pen,+ saved: terminal.saved,+ },+ };+}++/**+ * Text that rebuilds `state` when fed to an empty state: the output, then the+ * cursor, style and any unfinished escape. A viewer that starts from it (or+ * resyncs to it) applies later raw chunks exactly as the server does.+ */+export function terminalOutputResumeText(state: TerminalOutputState): string {+ const { screen } = state;+ const lastRow = screen.lines.length - 1;+ // Moves are relative to the last line, and a viewer only holds the lines in `text`.+ const shownLines = state.text.split("\n").length;+ const reachable = Math.min(LIVE_LINES, shownLines) - 1;+ const up = (row: number) => Math.min(lastRow - row, reachable);+ const goTo = (row: number, col: number) =>+ (up(row) > 0 ? `${ESC}[${up(row)}A` : "") + `${ESC}[${col + 1}G`;+ let suffix = "";+ if (screen.saved !== null) {+ suffix += `${goTo(screen.saved.row, screen.saved.col)}${ESC}7`;+ if (up(screen.saved.row) > 0) suffix += `${ESC}[${up(screen.saved.row)}B`;+ }+ if (+ screen.saved !== null ||+ screen.row < lastRow ||+ screen.col !== lineLength(screen.lines[screen.row]!)+ ) {+ suffix += goTo(screen.row, screen.col);+ }+ if (screen.pen !== "") suffix += sgr(screen.pen);+ return state.text + suffix + state.pending;+}++/** Normalizes a complete output string in one pass. */+export function normalizeTerminalOutput(+ text: string,+ maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,+): { readonly text: string; readonly truncated: boolean } {+ const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, text, maxChars);+ return { text: state.text, truncated: state.truncated };+}++/** A stretch of shown output with one style. */+export interface TerminalSpan {+ readonly text: string;+ readonly style: TerminalSpanStyle | null;+}++/** A span's style, usable as-is by a web or React Native `style` prop. */+export interface TerminalSpanStyle {+ /** CSS colours, already resolved against the palette. */+ readonly color?: string;+ readonly backgroundColor?: string;+ readonly fontWeight?: "600";+ readonly opacity?: number;+ readonly fontStyle?: "italic";+ readonly textDecorationLine?: "underline" | "line-through" | "underline line-through";+}++/** The 16 standard terminal colours, chosen to stay readable on each app theme. */+export const TERMINAL_PALETTES = {+ dark: [+ "#3b4048",+ "#f47067",+ "#57ab5a",+ "#c69026",+ "#539bf5",+ "#b083f0",+ "#39c5cf",+ "#adbac7",+ "#768390",+ "#ff938a",+ "#6bc46d",+ "#daaa3f",+ "#6cb6ff",+ "#dcbdfb",+ "#56d4dd",+ "#cdd9e5",+ ],+ light: [+ "#24292f",+ "#cf222e",+ "#116329",+ "#7d4e00",+ "#0550ae",+ "#8250df",+ "#1b7c83",+ "#6e7781",+ "#57606a",+ "#a40e26",+ "#1a7f37",+ "#633c01",+ "#0969da",+ "#6639ba",+ "#3192aa",+ "#8c959f",+ ],+} as const;++function xtermColor(index: number, palette: ReadonlyArray<string>): string {+ if (index < 16) return palette[index]!;+ if (index >= 232) {+ const level = 8 + (index - 232) * 10;+ return `rgb(${level},${level},${level})`;+ }+ const cube = index - 16;+ const channel = (value: number) => (value === 0 ? 0 : 55 + value * 40);+ return `rgb(${channel(Math.floor(cube / 36))},${channel(Math.floor(cube / 6) % 6)},${channel(cube % 6)})`;+}++function resolveColor(+ code: string,+ base: number,+ palette: ReadonlyArray<string>,+): string | undefined {+ const parts = code.split(";").map(Number);+ const head = parts[0]!;+ if (head === base + 8) {+ if (parts[1] === 5) return xtermColor(parts[2]!, palette);+ return `rgb(${parts[2]},${parts[3]},${parts[4]})`;+ }+ if (head >= base && head <= base + 7) return palette[head - base];+ if (head >= base + 60 && head <= base + 67) return palette[head - base - 52];+ return undefined;+}++type Rgb = readonly [number, number, number];++/** Reads the `#rrggbb` and `rgb(r,g,b)` colours this module produces. */+function parseCssColor(color: string): Rgb | undefined {+ if (color.startsWith("#") && color.length === 7) {+ return [1, 3, 5].map((offset) =>+ Number.parseInt(color.slice(offset, offset + 2), 16),+ ) as unknown as Rgb;+ }+ const match = /^rgb\((\d+),(\d+),(\d+)\)$/u.exec(color);+ return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];+}++function luminance([r, g, b]: Rgb): number {+ const channel = (value: number) => {+ const scaled = value / 255;+ return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+}++function contrastRatio(a: Rgb, b: Rgb): number {+ const [first, second] = [luminance(a), luminance(b)];+ return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);+}++function spanStyle(pen: string, palette: ReadonlyArray<string>): TerminalSpanStyle | null {+ if (pen === "") return null;+ const attributes = parsePen(pen);+ let color = attributes.fg === "" ? undefined : resolveColor(attributes.fg, 30, palette);+ let backgroundColor = attributes.bg === "" ? undefined : resolveColor(attributes.bg, 40, palette);+ if (attributes.inverse) {+ [color, backgroundColor] = [backgroundColor, color ?? palette[7]];+ }+ // Badges like "PASS" on green assume a terminal's own palette; keep their text readable.+ if (backgroundColor !== undefined) {+ const background = parseCssColor(backgroundColor);+ const foreground = color === undefined ? undefined : parseCssColor(color);+ if (+ background !== undefined &&+ (foreground === undefined || contrastRatio(foreground, background) < 3)+ ) {+ color = luminance(background) > 0.35 ? "#1f2328" : "#ffffff";+ }+ }+ const textDecorationLine = attributes.underline+ ? attributes.strike+ ? "underline line-through"+ : "underline"+ : attributes.strike+ ? "line-through"+ : undefined;+ return {+ ...(color === undefined ? {} : { color }),+ ...(backgroundColor === undefined ? {} : { backgroundColor }),+ ...(attributes.bold ? { fontWeight: "600" } : {}),+ ...(attributes.dim ? { opacity: 0.65 } : {}),+ ...(attributes.italic ? { fontStyle: "italic" } : {}),+ ...(textDecorationLine === undefined ? {} : { textDecorationLine }),+ };+}++/**+ * Splits shown output into styled spans for rendering. Past `maxSpans` the rest+ * is one plain span, so a pathological stream of colour changes cannot turn+ * into tens of thousands of DOM or native nodes.+ */+export function terminalOutputSpans(+ text: string,+ palette: ReadonlyArray<string>,+ maxSpans = 2_000,+): ReadonlyArray<TerminalSpan> {+ const spans: Array<TerminalSpan> = [];+ const styles = new Map<string, TerminalSpanStyle | null>();+ let pen = "";+ let cursor = 0;+ const push = (end: number) => {+ if (end <= cursor) return;+ let style = styles.get(pen);+ if (style === undefined) {+ style = spanStyle(pen, palette);+ styles.set(pen, style);+ }+ spans.push({ text: text.slice(cursor, end), style });+ };+ while (cursor < text.length) {+ const escape = text.indexOf(`${ESC}[`, cursor);+ if (escape === -1 || spans.length >= maxSpans) break;+ push(escape);+ const end = text.indexOf("m", escape);+ if (end === -1) break;+ const params = text.slice(escape + 2, end);+ pen = params === "0" ? "" : params.replace(/^0;/u, "");+ cursor = end + 1;+ }+ if (cursor < text.length) {+ if (spans.length >= maxSpans) {+ spans.push({ text: terminalOutputPlainText(text.slice(cursor)), style: null });+ } else {+ push(text.length);+ }+ }+ return spans;+}++const SGR_PATTERN = new RegExp(`${ESC}\\[[0-9;]*m`, "gu");++/** Shown output without its colour codes. */+export function terminalOutputPlainText(text: string): string {+ return text.replace(SGR_PATTERN, "");+}