fix: command output streams live while it runs #15094
Mergedscratchyone(GitHub profile, opens in a new tab)merged 30 commits into
main fromrefs/pull/15094/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -1990,3 +1991,8 @@19901991 "orchestration_v2.thread_id": input.threadId,19911992 },19921993 ),1994+ [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: (input) =>1995+ observeRpcStream(1996+ ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput,1997+ Stream.unwrap(1998+ CommandOutputHub.CommandOutputHub.use((hub) => Effect.succeed(hub.subscribe(input))),packages/shared/src/terminalOutput.ts lines 327 to 327OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +307,21 @@307+ }308+309+ write(text: string): void {310+ this.lines[this.row] = writeLine(this.lines[this.row]!, this.col, text, this.pen);311+ this.col += text.length;312+ }313+314+ newline(): void {315+ this.row += 1;316+ this.col = 0;317+ if (this.row === this.lines.length) this.lines.push([]);318+ while (this.lines.length > LIVE_LINES) {319+ this.settled += `${serializeLine(this.lines.shift()!)}\n`;320+ this.row -= 1;321+ if (this.saved !== null) this.saved = { ...this.saved, row: Math.max(0, this.saved.row - 1) };322+ }323+ }324+325+ moveTo(row: number, col: number): void {326+ this.row = Math.max(0, Math.min(this.lines.length - 1, row));327+ this.col = Math.max(0, col);apps/server/src/orchestration-v2/CommandOutputHub.ts line 245Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +197,21 @@197+ snapshotOutput = item.output;198+ } else {199+ return Effect.void;200+ }201+ subscriber.needsReplace = true;202+ return Queue.offer(wake, undefined);203+ });204+ const fromSequence = yield* eventSink.latestSequence({ threadId: target.threadId });205+ yield* eventSink206+ .stream({207+ threadId: target.threadId,208+ afterSequence: fromSequence,209+ eventType: "turn-item.updated",210+ })211+ .pipe(212+ Stream.runForEach((stored) =>213+ stored.event.type === "turn-item.updated" && stored.event.payload.id === target.itemId214+ ? observe(stored.event.payload)215+ : Effect.void,216+ ),217+ Effect.catchCause((cause) =>apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 3828OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3777,10 +3817,12 @@37773817 const webSearchResults = webSearchResultsFromClaudeOutput(input.output);37783818 const outputValue = claudeNativeToolOutputValue(input.output);37793819 const outputText = claudeNativeToolOutputText(input.output);3820+ const commandOutputText =3821+ itemType === "command_execution" ? claudeCommandOutputText(input.output) : "";37803822 const turnItem: OrchestrationV2TurnItem =37813823 itemType === "command_execution"37823824 ? {37833825 ...itemBase,37843826 type: "command_execution",37853827 input: commandInputFromClaudeTool(input.toolName, input.toolInput),3786- ...(outputText.length === 0 ? {} : { output: outputText }),3828+ ...(commandOutputText.length === 0 ? {} : { output: commandOutputText }),packages/shared/src/terminalOutput.ts line 644Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +504,21 @@504+ return {505+ text: tail.text,506+ truncated: truncated || settled.truncated || tail.truncated,507+ pending,508+ screen: {509+ settled: settled.text,510+ lines: terminal.lines,511+ row: terminal.row,512+ col: terminal.col,513+ pen: terminal.pen,514+ saved: terminal.saved,515+ },516+ };517+}518+519+/**520+ * Text that rebuilds `state` when fed to an empty state: the output, then the521+ * cursor, style and any unfinished escape. A viewer that starts from it (or522+ * resyncs to it) applies later raw chunks exactly as the server does.523+ */524+export function terminalOutputResumeText(state: TerminalOutputState): string {apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts lines 113 to 113OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+ Effect.orElseSucceed(() => offset),94+ );95+ if (size < offset) offset = 0;96+ if (size > offset) {97+ const start = size - offset > MAX_READ_BYTES ? size - MAX_READ_BYTES : offset;98+ const bytes = yield* Effect.scoped(99+ Effect.gen(function* () {100+ const handle = yield* fileSystem.open(filePath, { flag: "r" });101+ yield* handle.seek(BigInt(start), "start");102+ return yield* handle.readAlloc(size - start);103+ }),104+ ).pipe(Effect.orElseSucceed(() => Option.none<Uint8Array>()));105+ if (Option.isSome(bytes)) {106+ // Skipped output must not splice two unrelated lines together.107+ const skipped = start > offset;108+ offset = start + bytes.value.byteLength;109+ const text = (skipped ? "\n" : "") + decoder.decode(bytes.value, { stream: true });110+ if (text.length > 0) yield* input.onChunk(text);111+ }112+ }113+ if (last) return;
- apps/mobile/src/features/threads/thread-command-output.tsx lines 21 to 30OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+11+import { AppText as Text } from "../../components/AppText";12+import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";13+import { useServerConfigs } from "../../state/entities";14+import { orchestrationEnvironment } from "../../state/orchestration";15+import { useEnvironmentQuery } from "../../state/query";16+17+// Within this many points of the end still counts as following the output.18+const FOLLOW_SLACK = 8;19+20+function spanStyle(style: TerminalSpanStyle): TextStyle {21+ const decorations = [style.underline ? "underline" : "", style.strike ? "line-through" : ""]22+ .filter(Boolean)23+ .join(" ") as TextStyle["textDecorationLine"];24+ return {25+ ...(style.color === undefined ? {} : { color: style.color }),26+ ...(style.backgroundColor === undefined ? {} : { backgroundColor: style.backgroundColor }),27+ ...(style.bold ? { fontWeight: "600" as const } : {}),28+ ...(style.dim ? { opacity: 0.65 } : {}),29+ ...(style.italic ? { fontStyle: "italic" as const } : {}),30+ ...(decorations === "" ? {} : { textDecorationLine: decorations }),apps/server/src/orchestration-v2/CommandOutputHub.ts line 42OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +22,21 @@22+import * as Stream from "effect/Stream";23+24+import * as EventSink from "./EventSink.ts";25+import * as ProjectionStore from "./ProjectionStore.ts";26+27+/**28+ * Live command output.29+ *30+ * Output never becomes an orchestration event. Adapters push raw chunks here31+ * (through the session manager), the hub keeps a bounded, normalized tail per32+ * running command, and `subscribe` serves one expanded row: the current tail,33+ * then coalesced appends, then the persisted final output. Memory is bounded34+ * per command and in count, and a client that is not showing the row receives nothing.35+ */36+37+/** Fastest a subscriber receives frames while output flows. */38+export const COMMAND_OUTPUT_FRAME_INTERVAL_MS = 100;39+/** After a subscriber falls behind and is sent the whole tail, it waits this long. */40+export const COMMAND_OUTPUT_REPLACE_INTERVAL_MS = 500;41+/** Raw text a subscriber may accumulate before it is sent the tail instead. */42+export const COMMAND_OUTPUT_MAX_APPEND_CHARS = 16 * 1024;packages/shared/src/terminalOutput.ts line 70OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +50,21 @@50+const EMPTY_SCREEN: TerminalScreen = {51+ settled: "",52+ lines: [[]],53+ row: 0,54+ col: 0,55+ pen: "",56+ saved: null,57+};58+59+export const EMPTY_TERMINAL_OUTPUT: TerminalOutputState = {60+ text: "",61+ truncated: false,62+ pending: "",63+ screen: EMPTY_SCREEN,64+};65+66+/** The default tail kept for one running command, in UTF-16 code units. */67+export const TERMINAL_OUTPUT_TAIL_CHARS = 64 * 1024;68+69+/** Lines that cursor movement can still reach; older output is fixed. */70+export const LIVE_LINES = 64;
- apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts line 87OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +67,21 @@67+ readonly sessionId: string;68+ readonly taskId: string;69+ readonly stop: Deferred.Deferred<void>;70+ readonly onChunk: (chunk: string) => Effect.Effect<void>;71+}) {72+ const fileSystem = yield* FileSystem.FileSystem;73+ // True once stopped: the next read is the last.74+ const pause = Effect.raceFirst(75+ Effect.sleep(CLAUDE_TASK_OUTPUT_POLL_MS).pipe(Effect.as(false)),76+ Deferred.await(input.stop).pipe(Effect.as(true)),77+ );78+ let file = Option.none<string>();79+ for (let attempt = 0; Option.isNone(file); attempt += 1) {80+ file = yield* locate(input);81+ if (Option.isSome(file)) break;82+ if (attempt + 1 >= MAX_LOCATE_ATTEMPTS || (yield* pause)) return;83+ }84+ const filePath = file.value;85+ // `stream: true` keeps a multi-byte character split across reads intact;86+ // invalid bytes become U+FFFD.87+ const decoder = new TextDecoder("utf-8", { fatal: false });packages/shared/src/terminalOutput.ts lines 495 to 501OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +481,21 @@481+}482+483+/** Appends one decoded chunk and returns the new bounded state. */484+export function appendTerminalOutput(485+ state: TerminalOutputState,486+ chunk: string,487+ maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,488+): TerminalOutputState {489+ const input = state.pending + chunk;490+ if (input.length === 0) return state;491+ const terminal = new Terminal(state.screen);492+ const pending = terminal.feed(input);493+ let truncated = state.truncated;494+ // A line longer than the whole tail only ever shows its end.495+ terminal.lines = terminal.lines.map((line, row) => {496+ const length = lineLength(line);497+ if (length <= maxChars) return line;498+ truncated = true;499+ if (row === terminal.row) terminal.col = Math.max(0, terminal.col - (length - maxChars));500+ return sliceLine(line, length - maxChars, length);501+ });
- apps/server/src/orchestration-v2/CommandOutputHub.ts line 101OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +81,21 @@81+) {}82+83+const isCommandOutputError = Schema.is(OrchestrationV2CommandOutputError);84+85+function commandKey(target: CommandOutputTarget): string {86+ return `${target.threadId}\u0000${target.itemId}`;87+}88+89+function isSettled(item: OrchestrationV2TurnItem): boolean {90+ return item.status !== "pending" && item.status !== "running" && item.status !== "waiting";91+}92+93+/** The output a row shows from a persisted item, bounded before normalization. */94+function persistedCommandOutput(output: string | undefined): {95+ readonly text: string;96+ readonly truncated: boolean;97+} {98+ if (output === undefined) return { text: "", truncated: false };99+ const source =100+ output.length > MAX_FINAL_SOURCE_CHARS101+ ? output.slice(output.length - MAX_FINAL_SOURCE_CHARS)@@ -0,0 +357,21 @@357+ case "D":358+ return this.moveTo(this.row, this.col - count);359+ case "E":360+ return this.moveTo(this.row + count, 0);361+ case "F":362+ return this.moveTo(this.row - count, 0);363+ case "G":364+ return this.moveTo(this.row, count - 1);365+ case "H":366+ case "f":367+ // Rows count from the top of the window: there is no fixed screen height.368+ return this.moveTo(count - 1, Math.max(1, numbers[1] || 1) - 1);369+ case "K":370+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, numbers[0] ?? 0);371+ return;372+ case "J": {373+ const mode = numbers[0] ?? 0;374+ if (mode === 0) {375+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 0);376+ this.lines.length = this.row + 1;377+ } else if (mode === 1) {packages/shared/src/terminalOutput.ts lines 464 to 481Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +365,21 @@365+ case "H":366+ case "f":367+ // Rows count from the top of the window: there is no fixed screen height.368+ return this.moveTo(count - 1, Math.max(1, numbers[1] || 1) - 1);369+ case "K":370+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, numbers[0] ?? 0);371+ return;372+ case "J": {373+ const mode = numbers[0] ?? 0;374+ if (mode === 0) {375+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 0);376+ this.lines.length = this.row + 1;377+ } else if (mode === 1) {378+ for (let row = 0; row < this.row; row += 1) this.lines[row] = [];379+ this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 1);380+ } else {381+ // A cleared screen starts the window over; what scrolled out stays.382+ this.lines = [[]];383+ this.row = 0;384+ this.col = 0;385+ }packages/shared/src/terminalOutput.ts line 495OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +475,21 @@475+ const style = styleAt(text, start);476+ start = style.start;477+ // Never start on a lone low surrogate.478+ const first = text.charCodeAt(start);479+ if (first >= 0xdc00 && first <= 0xdfff) start += 1;480+ return { text: style.prefix + text.slice(start), truncated: true };481+}482+483+/** Appends one decoded chunk and returns the new bounded state. */484+export function appendTerminalOutput(485+ state: TerminalOutputState,486+ chunk: string,487+ maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,488+): TerminalOutputState {489+ const input = state.pending + chunk;490+ if (input.length === 0) return state;491+ const terminal = new Terminal(state.screen);492+ const pending = terminal.feed(input);493+ let truncated = state.truncated;494+ // A line longer than the whole tail only ever shows its end.495+ terminal.lines = terminal.lines.map((line, row) => {packages/shared/src/terminalOutput.ts lines 334 to 334OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +314,21 @@314+ newline(): void {315+ this.row += 1;316+ this.col = 0;317+ if (this.row === this.lines.length) this.lines.push([]);318+ while (this.lines.length > LIVE_LINES) {319+ this.settled += `${serializeLine(this.lines.shift()!)}\n`;320+ this.row -= 1;321+ if (this.saved !== null) this.saved = { ...this.saved, row: Math.max(0, this.saved.row - 1) };322+ }323+ }324+325+ moveTo(row: number, col: number): void {326+ this.row = Math.max(0, Math.min(this.lines.length - 1, row));327+ // A huge column (ESC[999999999C) would otherwise pad a line past any string limit.328+ this.col = Math.max(0, Math.min(TERMINAL_OUTPUT_TAIL_CHARS, col));329+ }330+331+ csi(params: string, final: string): void {332+ const private_ = params.startsWith("?") || params.startsWith(">") || params.startsWith("=");333+ if (private_) return; // Mode switches (cursor visibility, bracketed paste).334+ const numbers = params === "" ? [] : params.replaceAll(":", ";").split(";").map(Number);
- packages/shared/src/terminalOutput.ts line 328OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +308,21 @@308+class Terminal {309+ settled: string;310+ lines: Array<Line>;311+ row: number;312+ col: number;313+ pen: string;314+ saved: { row: number; col: number } | null;315+ /** Output was discarded on purpose (scrollback cleared or window over budget). */316+ dropped = false;317+318+ constructor(screen: TerminalScreen) {319+ this.settled = screen.settled;320+ this.lines = screen.lines.slice();321+ this.row = screen.row;322+ this.col = screen.col;323+ this.pen = screen.pen;324+ this.saved = screen.saved;325+ }326+327+ write(text: string): void {328+ this.lines[this.row] = writeLine(this.lines[this.row]!, this.col, text, this.pen);
- packages/shared/src/terminalOutput.ts line 337OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +317,21 @@317+318+ constructor(screen: TerminalScreen) {319+ this.settled = screen.settled;320+ this.lines = screen.lines.slice();321+ this.row = screen.row;322+ this.col = screen.col;323+ this.pen = screen.pen;324+ this.saved = screen.saved;325+ }326+327+ write(text: string): void {328+ this.lines[this.row] = writeLine(this.lines[this.row]!, this.col, text, this.pen);329+ this.col += text.length;330+ }331+332+ newline(): void {333+ this.row += 1;334+ this.col = 0;335+ if (this.row === this.lines.length) this.lines.push([]);336+ while (this.lines.length > LIVE_LINES) {337+ this.settled += `${serializeLine(this.lines.shift()!)}\n`;packages/shared/src/terminalOutput.ts line 517OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +497,21 @@497+ const style = styleAt(text, start);498+ start = style.start;499+ // Never start on a lone low surrogate.500+ const first = text.charCodeAt(start);501+ if (first >= 0xdc00 && first <= 0xdfff) start += 1;502+ return { text: style.prefix + text.slice(start), truncated: true };503+}504+505+/** Appends one decoded chunk and returns the new bounded state. */506+export function appendTerminalOutput(507+ state: TerminalOutputState,508+ chunk: string,509+ maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,510+): TerminalOutputState {511+ const input = state.pending + chunk;512+ if (input.length === 0) return state;513+ const terminal = new Terminal(state.screen);514+ const pending = terminal.feed(input);515+ let truncated = state.truncated;516+ // A line longer than the whole tail only ever shows its end.517+ terminal.lines = terminal.lines.map((line, row) => {
- apps/web/src/components/chat/V2ItemInspector.tsx line 123Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -99,6 +100,7 @@99100 function useFetchedTurnItem(100101 projectedItem: OrchestrationV2ProjectedTurnItem,101102 environmentId: EnvironmentId,103+ skip = false,102104 ) {103105 const wireItem = projectedItem.item;104- const fetches = turnItemNeedsDetailFetch(wireItem);106+ const fetches = !skip && turnItemNeedsDetailFetch(wireItem);apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts lines 5920 to 5920OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5888,3 +5910,11 @@5888591058895911 if (message.type === "system" && message.subtype === "task_started") {58905912 if (isClaudeNonSubagentTask(message)) {5913+ const tailedCall =5914+ message.tool_use_id === undefined5915+ ? undefined5916+ : context.toolCalls.get(message.tool_use_id);5917+ if (5918+ taskOutputRoot !== undefined &&5919+ message.task_type === "local_bash" &&5920+ message.is_backgrounded === false &&
- packages/contracts/src/orchestrationV2.ts lines 3296 to 3305Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -2982,5 +2982,20 @@29822982 subscribeArchivedShell: "orchestration.subscribeArchivedShell",29832983 subscribeShell: "orchestration.subscribeShell",29842984 subscribeThread: "orchestration.subscribeThread",2985+ subscribeCommandOutput: "orchestration.subscribeCommandOutput",29852986 } as const;298629872988+export const OrchestrationV2SubscribeCommandOutputInput = Schema.Struct({2989+ threadId: ThreadId,2990+ itemId: TurnItemId,2991+});2992+export type OrchestrationV2SubscribeCommandOutputInput =2993+ typeof OrchestrationV2SubscribeCommandOutputInput.Type;2994+2995+/**2996+ * Output of one command row, separate from the thread stream so it is never2997+ * persisted as events and only reaches clients that show the row expanded.2998+ * `replace` carries the whole bounded tail (first frame, or after the client2999+ * fell behind); `append` extends it. Text is already stripped of terminal3000+ * escapes. The stream ends after a frame with `running: false`.3001+ */packages/shared/src/terminalOutput.ts lines 298 to 308OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +288,21 @@288+ const next = input[index + 1];289+ if (next === undefined) return -1;290+ if (next === "[") {291+ // CSI: parameters/intermediates, then a final byte in @-~.292+ for (let cursor = index + 2; cursor < input.length; cursor += 1) {293+ const code = input.charCodeAt(cursor);294+ if (code >= 0x40 && code <= 0x7e) return cursor - index + 1;295+ }296+ return -1;297+ }298+ if (next === "]" || next === "P" || next === "_" || next === "^") {299+ // OSC/DCS/APC/PM end at BEL or ST (ESC \).300+ for (let cursor = index + 2; cursor < input.length; cursor += 1) {301+ if (input[cursor] === "\u0007") return cursor - index + 1;302+ if (input[cursor] === ESC) {303+ if (cursor + 1 >= input.length) return -1;304+ if (input[cursor + 1] === "\\") return cursor - index + 2;305+ }306+ }307+ return -1;308+ }
- packages/shared/src/terminalOutput.ts line 532OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +512,21 @@512+ let printable = 0;513+ const flush = (end: number) => {514+ if (end > printable) this.write(input.slice(printable, end));515+ };516+ for (let index = 0; index < input.length; index += 1) {517+ const code = input.charCodeAt(index);518+ // Printable text, including tabs, is batched into one write.519+ if (code === 0x09 || (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f))) {520+ continue;521+ }522+ flush(index);523+ printable = index + 1;524+ if (code === 0x0a) this.newline();525+ else if (code === 0x0d) this.col = 0;526+ else if (code === 0x08) this.col = Math.max(0, this.col - 1);527+ else if (code === 0x1b) {528+ const length = escapeLength(input, index);529+ if (length === -1) {530+ const fragment = input.slice(index);531+ // A runaway unterminated sequence is noise; drop it instead of waiting forever.532+ return fragment.length <= MAX_PENDING_ESCAPE ? fragment : "";apps/server/src/orchestration-v2/CommandOutputHub.ts lines 162 to 166OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +146,21 @@146+ subscriber.pendingAppend = "";147+ }148+ }149+ return Queue.offer(subscriber.wake, undefined);150+ },151+ { discard: true },152+ );153+154+ const append: CommandOutputHubShape["append"] = ({ chunk, ...target }) =>155+ Effect.suspend(() => {156+ if (chunk.length === 0) return Effect.void;157+ const key = commandKey(target);158+ const previous = tails.get(key);159+ tails.delete(key);160+ tails.set(key, appendTerminalOutput(previous ?? EMPTY_TERMINAL_OUTPUT, chunk));161+ if (previous === undefined) {162+ while (tails.size > MAX_LIVE_COMMANDS) {163+ const oldest = tails.keys().next().value;164+ if (oldest === undefined) break;165+ tails.delete(oldest);166+ }
- apps/server/src/orchestration-v2/CommandOutputHub.ts line 95Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +81,21 @@81+ "t3/orchestration-v2/CommandOutputHub",82+) {}83+84+const isCommandOutputError = Schema.is(OrchestrationV2CommandOutputError);85+86+function commandKey(target: CommandOutputTarget): string {87+ return `${target.threadId}\u0000${target.itemId}`;88+}89+90+function isSettled(item: OrchestrationV2TurnItem): boolean {91+ return item.status !== "pending" && item.status !== "running" && item.status !== "waiting";92+}93+94+/** The output a row shows from a persisted item, bounded before normalization. */95+/** Claude Bash rows stored before #15505 hold the raw `{ stdout, stderr, interrupted, ... }` result. */96+const decodeLegacyClaudeBashResult = Schema.decodeUnknownOption(97+ Schema.fromJsonString(Schema.Struct({ stdout: Schema.String, stderr: Schema.String })),98+);99+100+function legacyClaudeBashOutput(output: string): string {101+ if (!output.trimStart().startsWith('{"stdout"')) return output;
- @@ -3873,3 +3873,12 @@38733873 }),38743874 );387538753876+ yield* client.handleServerNotification("item/commandExecution/outputDelta", (payload) =>3877+ Effect.gen(function* () {3878+ // A delta always follows its item/started, so the turn is already3879+ // known; background commands keep printing after it settles.3880+ const context =3881+ (yield* Ref.get(activeTurns)).get(payload.turnId) ??3882+ (yield* Ref.get(settledTurns)).get(payload.turnId);3883+ if (context === undefined) return;3884+ yield* emitProviderEvent({
- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 6221OutdatedResolvedby scratchyone(GitHub profile, opens in a new tab)@@ -6193,3 +6215,7 @@6193621561946216 if (message.type === "system" && message.subtype === "task_started") {61956217 if (isClaudeNonSubagentTask(message)) {6218+ const tailedCall =6219+ message.tool_use_id === undefined6220+ ? undefined6221+ : context.toolCalls.get(message.tool_use_id);apps/server/src/orchestration-v2/CommandOutputHub.ts lines 120 to 120OutdatedResolvedby scratchyone(GitHub profile, opens in a new tab)@@ -0,0 +100,21 @@100+function legacyClaudeBashOutput(output: string): string {101+ if (!output.trimStart().startsWith('{"stdout"')) return output;102+ const parsed = decodeLegacyClaudeBashResult(output);103+ if (Option.isNone(parsed)) return output;104+ const out = parsed.value.stdout.trim().length > 0 ? parsed.value.stdout : "";105+ const err = parsed.value.stderr.trim().length > 0 ? parsed.value.stderr : "";106+ return out.length > 0 && err.length > 0 && !out.endsWith("\n") ? `${out}\n${err}` : out + err;107+}108+109+function persistedCommandOutput(rawOutput: string | undefined): {110+ readonly text: string;111+ readonly truncated: boolean;112+} {113+ if (rawOutput === undefined) return { text: "", truncated: false };114+ const output = legacyClaudeBashOutput(rawOutput);115+ let source = output;116+ if (output.length > MAX_FINAL_SOURCE_CHARS) {117+ // Start on a fresh line, so the cut can't land inside an escape sequence.118+ source = output.slice(output.length - MAX_FINAL_SOURCE_CHARS);119+ const newline = source.indexOf("\n");120+ if (newline !== -1) source = source.slice(newline + 1);
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed