The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 14:45 UTC
fix(server,client): preserve literal JSON command output (#36793)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 14, 2026 at 16:40 UTC
5583b26460da46841c62f0e7c86abbdd6715279b
10 files changed
+156
-47
apps/server/scripts/dev-replay-agent.ts
+5
@@ -64,6 +64,11 @@ export const SCENARIOS = [
64
name: "Multi turn",
65
file: `${FIXTURES}/multi_turn/registry_transcript.ndjson`,
66
},
67
+ {
68
+ id: "command-output",
69
+ name: "Command output",
70
+ file: "./dev-replay/command_output_transcript.ndjson",
71
+ },
72
] as const;
73
74
// Session setup and vendor state stay out: they would replace the replay agent's own models.
apps/server/scripts/dev-replay/command_output_transcript.ndjson
new
+6
@@ -0,0 +1,6 @@
1
+{"type":"transcript_start","provider":"acpRegistry","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"dev_replay_command_output","metadata":{"generatedBy":"hand-written for the dev replay agent"}}
2
+{"type":"expect_outbound","frame":{"kind":"request","method":"session/prompt","params":"<any>"}}
3
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call","toolCallId":"command-output-json","kind":"execute","title":"node -e 'process.stdout.write(JSON.stringify({stdout:\"line 1\\n行 2 🚀\",stderr:\"é warning\",interrupted:false,requestId:\"keep-me\"})+\"\\n\")'","status":"in_progress","rawInput":{"command":"node -e 'process.stdout.write(JSON.stringify({stdout:\"line 1\\n行 2 🚀\",stderr:\"é warning\",interrupted:false,requestId:\"keep-me\"})+\"\\n\")'"}}}}}
4
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call_update","toolCallId":"command-output-json","status":"completed","rawOutput":"{\"stdout\":\"line 1\\n行 2 🚀\",\"stderr\":\"é warning\",\"interrupted\":false,\"requestId\":\"keep-me\"}\n"}}},"afterMs":300}
5
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The command printed one JSON line."}}}}}
6
+{"type":"emit_inbound","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
apps/server/src/orchestration-v2/CommandOutputHub.test.ts
+16
-10
@@ -48,6 +48,7 @@ const modelSelection = {
48
model: "gpt-5.4",
49
} satisfies ModelSelection;
50
const CODEX_DRIVER = ProviderDriverKind.make("codex");
51
+const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent");
52
const ITEM_ID = TurnItemId.make("turn-item:command");
53
54
function applyFrame(
@@ -109,12 +110,15 @@ const writeCommandItem = (
110
fields: Pick<
111
Extract<OrchestrationV2TurnItem, { type: "command_execution" }>,
112
"status" | "output" | "exitCode"
112
- >,
113
+ > & {
114
+ readonly driver?: ProviderDriverKind;
115
+ readonly startedAt?: DateTime.Utc;
116
+ },
117
) =>
118
Effect.gen(function* () {
119
const idAllocator = yield* IdAllocator.IdAllocatorV2;
120
const eventSink = yield* EventSink.EventSinkV2;
117
- const now = yield* DateTime.now;
121
+ const { driver = CODEX_DRIVER, startedAt = yield* DateTime.now, ...itemFields } = fields;
122
const settled = fields.status !== "running";
123
const item: OrchestrationV2TurnItem = {
124
id: ITEM_ID,
@@ -123,16 +127,16 @@ const writeCommandItem = (
127
nodeId: null,
128
providerThreadId: null,
129
providerTurnId: null,
126
- nativeItemRef: null,
130
+ nativeItemRef: { driver, nativeId: "tool-1", strength: "strong" },
131
parentItemId: null,
132
ordinal: 1,
133
title: null,
130
- startedAt: now,
131
- completedAt: settled ? now : null,
132
- updatedAt: now,
134
+ startedAt,
135
+ completedAt: settled ? startedAt : null,
136
+ updatedAt: startedAt,
137
type: "command_execution",
138
input: "yes | head -n 1000000",
135
- ...fields,
139
+ ...itemFields,
140
};
141
yield* eventSink.write({
142
events: [
@@ -140,9 +144,9 @@ const writeCommandItem = (
144
id: yield* idAllocator.allocate.event({ threadId }),
145
type: "turn-item.updated",
146
threadId,
143
- driver: CODEX_DRIVER,
147
+ driver,
148
providerInstanceId: modelSelection.instanceId,
145
- occurredAt: now,
149
+ occurredAt: startedAt,
150
payload: item,
151
},
152
],
@@ -294,13 +298,15 @@ layer("CommandOutputHub", (it) => {
298
}),
299
);
300
297
- it.effect("an old Claude row's raw Bash result shows as its stdout and stderr", () =>
301
+ it.effect("an early Claude row's raw Bash result shows as its stdout and stderr", () =>
302
Effect.gen(function* () {
303
const threadId = yield* seedThread;
304
yield* writeCommandItem(threadId, {
305
status: "completed",
306
exitCode: 0,
307
output: '{"stdout":"built","stderr":"1 warning","interrupted":false}',
308
+ driver: CLAUDE_DRIVER,
309
+ startedAt: DateTime.makeUnsafe("2026-10-03T12:00:00Z"),
310
});
311
const frames = yield* subscribeFrames(threadId);
312
const final = yield* takeFrame(frames);
apps/server/src/orchestration-v2/CommandOutputHub.ts
+6
-18
@@ -13,12 +13,12 @@ import {
13
TERMINAL_OUTPUT_TAIL_CHARS,
14
terminalOutputResumeText,
15
} from "@t3tools/shared/terminalOutput";
16
+import { commandItemOutput } from "@t3tools/shared/commandOutput";
17
import * as Cause from "effect/Cause";
18
import * as Clock from "effect/Clock";
19
import * as Context from "effect/Context";
20
import * as Effect from "effect/Effect";
21
import * as Layer from "effect/Layer";
21
-import * as Option from "effect/Option";
22
import * as Queue from "effect/Queue";
23
import * as Schema from "effect/Schema";
24
import * as Stream from "effect/Stream";
@@ -69,21 +69,6 @@ function commandKey(target: CommandOutputTarget): string {
69
return `${target.threadId}\u0000${target.itemId}`;
70
}
71
72
-const decodeLegacyClaudeBashResult = Schema.decodeUnknownOption(
73
- Schema.fromJsonString(
74
- Schema.Struct({ stdout: Schema.String, stderr: Schema.String, interrupted: Schema.Boolean }),
75
- ),
76
-);
77
-
78
-function legacyClaudeBashOutput(output: string): string {
79
- if (!output.trimStart().startsWith('{"stdout"')) return output;
80
- const parsed = decodeLegacyClaudeBashResult(output);
81
- if (Option.isNone(parsed)) return output;
82
- const out = parsed.value.stdout.trim().length > 0 ? parsed.value.stdout : "";
83
- const err = parsed.value.stderr.trim().length > 0 ? parsed.value.stderr : "";
84
- return out.length > 0 && err.length > 0 && !out.endsWith("\n") ? `${out}\n${err}` : out + err;
85
-}
86
-
72
function persistedCommandOutput(output: string | undefined): {
73
readonly text: string;
74
readonly truncated: boolean;
@@ -269,8 +254,11 @@ export const make = Effect.gen(function* () {
254
running: false,
255
};
256
}
272
- const output = settled.output && legacyClaudeBashOutput(settled.output);
273
- return { kind: "replace", ...persistedCommandOutput(output), running: false };
257
+ return {
258
+ kind: "replace",
259
+ ...persistedCommandOutput(commandItemOutput(settled)),
260
+ running: false,
261
+ };
262
}
263
if (subscriber.needsReplace || tail === undefined) {
264
if (subscriber.overflowed) throttle = COMMAND_OUTPUT_REPLACE_INTERVAL_MS;
packages/client-runtime/src/work-log/itemDetail.ts
+5
-18
@@ -1,4 +1,5 @@
1
import type { AssetResource, OrchestrationV2TurnItem } from "@t3tools/contracts";
2
+import { commandItemOutput } from "@t3tools/shared/commandOutput";
3
import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp";
4
import {
5
mcpToolResultOutput,
@@ -170,22 +171,6 @@ export function turnItemNeedsDetailFetch(item: OrchestrationV2TurnItem): boolean
171
}
172
}
173
173
-function commandOutputText(output: string): string {
174
- if (!output.trimStart().startsWith('{"stdout"')) return output;
175
- const parsed = parseJson(output.trim());
176
- if (
177
- !isRecord(parsed) ||
178
- typeof parsed.stdout !== "string" ||
179
- typeof parsed.stderr !== "string" ||
180
- typeof parsed.interrupted !== "boolean"
181
- ) {
182
- return output;
183
- }
184
- return [parsed.stdout, parsed.stderr]
185
- .filter((part): part is string => typeof part === "string" && part.trim().length > 0)
186
- .join("\n");
187
-}
188
-
174
// App calls store the provider result beside the app reference; its images get no preview.
175
function dynamicToolOutputText(
176
item: Extract<OrchestrationV2TurnItem, { readonly type: "dynamic_tool" }>,
@@ -200,8 +185,10 @@ function dynamicToolOutputText(
185
186
export function turnItemOutputText(item: OrchestrationV2TurnItem): string | null {
187
switch (item.type) {
203
- case "command_execution":
204
- return item.output?.trim() ? commandOutputText(item.output) || null : null;
188
+ case "command_execution": {
189
+ const output = commandItemOutput(item);
190
+ return output?.trim() ? output : null;
191
+ }
192
case "dynamic_tool":
193
return item.outputOmitted === true ? null : dynamicToolOutputText(item);
194
case "file_search":
packages/shared/package.json
+4
@@ -419,6 +419,10 @@
419
"types": "./src/thirdPartyLicenses.ts",
420
"import": "./src/thirdPartyLicenses.ts"
421
},
422
+ "./commandOutput": {
423
+ "types": "./src/commandOutput.ts",
424
+ "import": "./src/commandOutput.ts"
425
+ },
426
"./claudeCompaction": {
427
"types": "./src/claudeCompaction.ts",
428
"import": "./src/claudeCompaction.ts"
packages/shared/src/commandOutput.test.ts
new
+53
@@ -0,0 +1,53 @@
1
+import {
2
+ ProviderDriverKind,
3
+ ThreadId,
4
+ TurnItemId,
5
+ type OrchestrationV2TurnItem,
6
+} from "@t3tools/contracts";
7
+import * as DateTime from "effect/DateTime";
8
+import { describe, expect, it } from "vite-plus/test";
9
+
10
+import { commandItemOutput } from "./commandOutput.ts";
11
+
12
+const envelope =
13
+ '{"stdout":"line 1\\n行 2 🚀","stderr":"é warning","interrupted":false,"requestId":"keep-me"}\n';
14
+
15
+const commandItem = (driver: string, startedAt: string) =>
16
+ ({
17
+ id: TurnItemId.make("command"),
18
+ threadId: ThreadId.make("thread"),
19
+ runId: null,
20
+ nodeId: null,
21
+ providerThreadId: null,
22
+ providerTurnId: null,
23
+ nativeItemRef: {
24
+ driver: ProviderDriverKind.make(driver),
25
+ nativeId: "tool-1",
26
+ strength: "strong",
27
+ },
28
+ parentItemId: null,
29
+ ordinal: 1,
30
+ status: "completed",
31
+ title: null,
32
+ startedAt: DateTime.makeUnsafe(startedAt),
33
+ completedAt: null,
34
+ updatedAt: DateTime.makeUnsafe(startedAt),
35
+ type: "command_execution",
36
+ input: "node print-json.js",
37
+ output: envelope,
38
+ }) satisfies OrchestrationV2TurnItem;
39
+
40
+describe("commandItemOutput", () => {
41
+ it("unwraps an early Claude row's raw Bash result into stdout and stderr", () => {
42
+ expect(commandItemOutput(commandItem("claudeAgent", "2026-10-03T12:00:00Z"))).toBe(
43
+ "line 1\n行 2 🚀\né warning",
44
+ );
45
+ });
46
+
47
+ it.each([
48
+ ["codex", "2026-10-03T12:00:00Z"],
49
+ ["claudeAgent", "2026-11-01T12:00:00Z"],
50
+ ])("keeps literal JSON a %s command printed at %s", (driver, startedAt) => {
51
+ expect(commandItemOutput(commandItem(driver, startedAt))).toBe(envelope);
52
+ });
53
+});
packages/shared/src/commandOutput.ts
new
+35
@@ -0,0 +1,35 @@
1
+import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
2
+import * as DateTime from "effect/DateTime";
3
+import * as Option from "effect/Option";
4
+import * as Schema from "effect/Schema";
5
+
6
+type CommandExecutionItem = Extract<OrchestrationV2TurnItem, { type: "command_execution" }>;
7
+
8
+// Only nightlies 20261003.2610 to 20261004.2644 stored raw Claude Bash envelopes; rows carry no
9
+// build stamp, so start time is the only discriminator. The cutoff leaves nightly laggards four days.
10
+const CLAUDE_RAW_BASH_RESULT_CUTOFF = DateTime.makeUnsafe("2026-10-08T00:00:00Z");
11
+
12
+const decodeClaudeBashResult = Schema.decodeUnknownOption(
13
+ Schema.fromJsonString(
14
+ Schema.Struct({ stdout: Schema.String, stderr: Schema.String, interrupted: Schema.Boolean }),
15
+ ),
16
+);
17
+
18
+function storesRawClaudeBashResult(item: CommandExecutionItem): boolean {
19
+ return (
20
+ item.nativeItemRef?.driver === "claudeAgent" &&
21
+ DateTime.isLessThan(item.startedAt ?? item.updatedAt, CLAUDE_RAW_BASH_RESULT_CUTOFF)
22
+ );
23
+}
24
+
25
+/** The output a command row shows: the stored bytes, except early Claude rows' raw Bash envelopes. */
26
+export function commandItemOutput(item: CommandExecutionItem): string | undefined {
27
+ const output = item.output;
28
+ if (output === undefined || !storesRawClaudeBashResult(item)) return output;
29
+ if (!output.trimStart().startsWith('{"stdout"')) return output;
30
+ const parsed = decodeClaudeBashResult(output);
31
+ if (Option.isNone(parsed)) return output;
32
+ const out = parsed.value.stdout.trim().length > 0 ? parsed.value.stdout : "";
33
+ const err = parsed.value.stderr.trim().length > 0 ? parsed.value.stderr : "";
34
+ return out.length > 0 && err.length > 0 && !out.endsWith("\n") ? `${out}\n${err}` : out + err;
35
+}
scripts/scenarios/command-output-keeps-literal-json.e2e.ts
new
+24
@@ -0,0 +1,24 @@
1
+import { expect } from "e2e";
2
+
3
+import { test, WEB } from "./t3.ts";
4
+
5
+test(
6
+ "An expanded command shows the JSON line it printed, keys and all",
7
+ WEB,
8
+ async ({ t3, app, screen }) => {
9
+ const project = await t3.project("demo");
10
+ const thread = await t3.thread({
11
+ project,
12
+ title: "JSON output",
13
+ messages: ["Print the JSON"],
14
+ model: "command-output",
15
+ });
16
+ await t3.open(thread);
17
+
18
+ await expect(screen.getByText("The command printed one JSON line.")).toBeVisible();
19
+ await screen.getByRole("button", "Worked for", { exact: false }).tap();
20
+ await screen.getByRole("button", "node -e", { exact: false }).first().tap();
21
+ await app.screenshot("expanded");
22
+ await expect(screen.getByText('"requestId":"keep-me"', { exact: false })).toBeVisible();
23
+ },
24
+);
scripts/scenarios/t3.ts
+2
-1
@@ -21,7 +21,8 @@ export interface T3State {
21
) => Promise<string>;
22
/**
23
* Starts a thread in a project and plays one replayed turn per message before returning.
24
- * `model` is a dev replay recording: showcase, todo-list, approval, question, multi-turn.
24
+ * `model` is a dev replay recording: showcase, todo-list, approval, question, multi-turn,
25
+ * command-output.
26
*/
27
readonly thread: (input: {
28
readonly project: string;