The best way to control Claude Code, Codex and more from any computer or phone
feat(dev): test turns in the UI for free with a replay provider (#26207)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 27, 2026 at 18:58 UTC
e2a8ef0174447c16aeed6e1154ae969040e10c74
11 files changed
+884
-4
.agents/skills/test-t3-app/SKILL.md
+13
@@ -21,6 +21,19 @@ Test with meaningful project and thread data. Read
21
[references/sqlite-fixtures.md](references/sqlite-fixtures.md) only when
22
inspecting or seeding SQLite. Stop the test server before direct fixture writes.
23
24
+## Drive agent turns for free
25
+
26
+Do not spend a paid model to see a turn render. `vp run dev` registers the
27
+`Replay (dev)` provider, which replays recorded turns with simulated streaming
28
+through the real adapter and orchestration. Its models are scenarios:
29
+`showcase` covers thinking, a plan, tool calls, an approval, and markdown.
30
+Press `Ctrl+Alt+Shift+R` for a picker (GNOME takes that key for screen
31
+recording), call `window.t3dev.replay("showcase")`
32
+with `preview_evaluate`, or run
33
+`node apps/server/src/bin.ts thread start --base-dir .t3 --provider devReplay --model showcase <project> "go"`.
34
+When the test needs real provider behavior, use that provider's cheapest
35
+model, such as Haiku for Claude or Luna for Codex.
36
+
37
## Use the Browser panel
38
39
Call `preview_status`, then `preview_open` if the Browser panel is
AGENTS.md
+2
@@ -137,6 +137,8 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
137
138
- Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web, `test-t3-mobile` for mobile. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers.
139
140
+- Real agent turns cost money. To watch a turn stream through the pipeline and UI, use the free `Replay (dev)` provider that `vp run dev` registers; [test-t3-app](.agents/skills/test-t3-app/SKILL.md) shows how to start one. Use a real provider only when the change depends on that provider's behavior, and then pick its cheapest model, such as Haiku for Claude or Luna for Codex.
141
+
142
For authorized mobile verification, a missing or outdated native client is an install step, not a blocker. Run `vp run mobile:install <ios|android> [device-id]` on the device host before starting Metro; it targets the only booted simulator or connected Android device when the id is omitted. It installs the dev client for this checkout's native fingerprint from the shared cache in seconds and builds only when no machine has built it yet, so prefer it over `expo run:*`, `xcodebuild`, or `gradlew`, which rebuild from scratch. Its stdout is one JSON line; build output goes to the log it names. See `test-t3-mobile` for the full workflow.
143
144
## Evals
apps/server/scripts/dev-replay-agent.test.ts
new
+186
@@ -0,0 +1,186 @@
1
+// @effect-diagnostics nodeBuiltinImport:off
2
+import * as NodeChildProcess from "node:child_process";
3
+import * as NodeFS from "node:fs";
4
+import * as NodeReadline from "node:readline";
5
+import * as NodeURL from "node:url";
6
+
7
+import { describe, expect, it } from "@effect/vitest";
8
+
9
+import { parseReplayTurns, SCENARIOS, streamChunks } from "./dev-replay-agent.ts";
10
+
11
+interface AgentMessage {
12
+ readonly id?: number;
13
+ readonly method?: string;
14
+ readonly params?: {
15
+ readonly update?: {
16
+ readonly sessionUpdate?: string;
17
+ readonly toolCallId?: string;
18
+ readonly status?: string;
19
+ };
20
+ };
21
+ readonly result?: { readonly sessionId?: string; readonly stopReason?: string };
22
+ readonly error?: { readonly code?: number };
23
+}
24
+
25
+/**
26
+ * Runs the agent over stdio and returns every message it sent until each request is answered.
27
+ * Permission requests get `permissionResult`.
28
+ */
29
+async function talkToAgent(
30
+ requests: ReadonlyArray<(sessionId: string) => object>,
31
+ permissionResult: object = { outcome: { outcome: "selected", optionId: "allow-once" } },
32
+) {
33
+ const agent = NodeChildProcess.spawn(
34
+ process.execPath,
35
+ [NodeURL.fileURLToPath(new URL("./dev-replay-agent.ts", import.meta.url))],
36
+ { stdio: ["pipe", "pipe", "inherit"] },
37
+ );
38
+ const lines = NodeReadline.createInterface({ input: agent.stdout })[Symbol.asyncIterator]();
39
+ const received: Array<AgentMessage> = [];
40
+ let sessionId = "";
41
+ try {
42
+ for (const [index, request] of requests.entries()) {
43
+ agent.stdin.write(
44
+ `${JSON.stringify({ jsonrpc: "2.0", id: index + 1, ...request(sessionId) })}\n`,
45
+ );
46
+ for (;;) {
47
+ const message = JSON.parse((await lines.next()).value as string) as AgentMessage;
48
+ received.push(message);
49
+ if (message.method === "session/request_permission") {
50
+ const answer = { jsonrpc: "2.0", id: message.id, result: permissionResult };
51
+ agent.stdin.write(`${JSON.stringify(answer)}\n`);
52
+ }
53
+ if (message.id !== index + 1 || message.method !== undefined) continue;
54
+ sessionId = message.result?.sessionId ?? sessionId;
55
+ break;
56
+ }
57
+ }
58
+ } finally {
59
+ agent.kill();
60
+ }
61
+ return { sessionId, received };
62
+}
63
+
64
+describe("dev replay agent", () => {
65
+ it("keeps sessions and tool ids unique across processes and reloads", async () => {
66
+ const prompt = (sessionId: string) => ({ method: "session/prompt", params: { sessionId } });
67
+ const selectTodoList = (sessionId: string) => ({
68
+ method: "session/set_model",
69
+ params: { sessionId, modelId: "todo-list" },
70
+ });
71
+ const run = () =>
72
+ talkToAgent([
73
+ () => ({ method: "session/new", params: { cwd: "/tmp" } }),
74
+ selectTodoList,
75
+ prompt,
76
+ prompt,
77
+ ]);
78
+ const [first, second] = await Promise.all([run(), run()]);
79
+ expect(first.sessionId).not.toBe(second.sessionId);
80
+ // A server restart loads the same session in a new agent process.
81
+ const reloaded = await talkToAgent([
82
+ () => ({ method: "session/load", params: { sessionId: first.sessionId, cwd: "/tmp" } }),
83
+ () => selectTodoList(first.sessionId),
84
+ () => prompt(first.sessionId),
85
+ ]);
86
+ const toolCallIds = [...first.received, ...reloaded.received].flatMap((message) =>
87
+ message.params?.update?.toolCallId === undefined ? [] : [message.params.update.toolCallId],
88
+ );
89
+ expect(new Set(toolCallIds).size).toBe(6);
90
+ });
91
+
92
+ it.each(SCENARIOS)("$id plays a turn without session setup frames", ({ file }) => {
93
+ const turns = parseReplayTurns(NodeFS.readFileSync(new URL(file, import.meta.url), "utf8"));
94
+ expect(turns.length).toBeGreaterThan(0);
95
+ const updates = turns.flatMap((turn) =>
96
+ turn.frames.flatMap(({ frame }) =>
97
+ frame.method === "session/update"
98
+ ? [(frame.params as { update: { sessionUpdate: string } }).update.sessionUpdate]
99
+ : [],
100
+ ),
101
+ );
102
+ expect(updates).toContain("agent_message_chunk");
103
+ expect(updates).not.toContain("available_commands_update");
104
+ });
105
+
106
+ it("keeps permission requests and the recorded stop reason in order", () => {
107
+ const turns = parseReplayTurns(
108
+ NodeFS.readFileSync(new URL(SCENARIOS[0].file, import.meta.url), "utf8"),
109
+ );
110
+ const methods = turns[0]!.frames.map(({ frame }) => frame.method);
111
+ expect(methods).toContain("session/request_permission");
112
+ expect(turns[0]!.stopReason).toBe("end_turn");
113
+ });
114
+
115
+ it("rejects an unknown scenario instead of playing another one", async () => {
116
+ const { received } = await talkToAgent([
117
+ () => ({ method: "session/new", params: { cwd: "/tmp" } }),
118
+ (sessionId) => ({ method: "session/set_model", params: { sessionId, modelId: "typo" } }),
119
+ ]);
120
+ expect(received.at(-1)?.error?.code).toBe(-32602);
121
+ });
122
+
123
+ it("ends the turn with a failed tool call when the user rejects an approval", async () => {
124
+ const { received } = await talkToAgent(
125
+ [
126
+ () => ({ method: "session/new", params: { cwd: "/tmp" } }),
127
+ (sessionId) => ({ method: "session/prompt", params: { sessionId } }),
128
+ ],
129
+ { outcome: { outcome: "selected", optionId: "reject-once" } },
130
+ );
131
+ const updates = received.flatMap((message) =>
132
+ message.params?.update === undefined ? [] : [message.params.update],
133
+ );
134
+ expect(updates.at(-1)).toMatchObject({ sessionUpdate: "tool_call_update", status: "failed" });
135
+ expect(updates.some((update) => update.toolCallId?.endsWith("showcase-test"))).toBe(false);
136
+ expect(received.at(-1)?.result?.stopReason).toBe("end_turn");
137
+ });
138
+
139
+ it("ends the turn as cancelled when the client cancels an open approval", async () => {
140
+ const { received } = await talkToAgent(
141
+ [
142
+ () => ({ method: "session/new", params: { cwd: "/tmp" } }),
143
+ (sessionId) => ({ method: "session/prompt", params: { sessionId } }),
144
+ ],
145
+ { outcome: { outcome: "cancelled" } },
146
+ );
147
+ const requestIndex = received.findIndex(
148
+ (message) => message.method === "session/request_permission",
149
+ );
150
+ expect(received.slice(requestIndex + 1).some((message) => message.method !== undefined)).toBe(
151
+ false,
152
+ );
153
+ expect(received.at(-1)?.result?.stopReason).toBe("cancelled");
154
+ });
155
+
156
+ it("leaves frames after a prompt's response out of that turn", () => {
157
+ const update = (text: string) => ({
158
+ type: "emit_inbound",
159
+ frame: {
160
+ kind: "notification",
161
+ method: "session/update",
162
+ params: {
163
+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
164
+ },
165
+ },
166
+ });
167
+ const transcript = [
168
+ { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
169
+ update("root"),
170
+ { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: {} } },
171
+ update("background"),
172
+ ]
173
+ .map((entry) => JSON.stringify(entry))
174
+ .join("\n");
175
+ const turns = parseReplayTurns(transcript);
176
+ expect(turns).toHaveLength(1);
177
+ expect(turns[0]!.frames).toHaveLength(1);
178
+ });
179
+
180
+ it("streams text in chunks that rebuild the original", () => {
181
+ const text = "One two three four five\n\n```ts\nx\n```";
182
+ const chunks = streamChunks(text);
183
+ expect(chunks.length).toBeGreaterThan(1);
184
+ expect(chunks.join("")).toBe(text);
185
+ });
186
+});
apps/server/scripts/dev-replay-agent.ts
new
+384
@@ -0,0 +1,384 @@
1
+#!/usr/bin/env node
2
+// @effect-diagnostics nodeBuiltinImport:off globalTimers:off
3
+/**
4
+ * A free ACP agent for dev servers. It plays recorded ACP transcripts with simulated
5
+ * streaming, so the real adapter, orchestration, and UI run without a paid model.
6
+ * Each scenario is a "model"; each prompt plays the next recorded turn.
7
+ * Unlike acp-replay-agent.ts, it does not assert the client's frames.
8
+ */
9
+import * as NodeCrypto from "node:crypto";
10
+import * as NodeFS from "node:fs";
11
+import * as NodeReadline from "node:readline";
12
+
13
+interface LogicalFrame {
14
+ readonly kind: "notification" | "request" | "response";
15
+ readonly method: string;
16
+ readonly params?: unknown;
17
+ readonly result?: unknown;
18
+}
19
+
20
+interface ReplayEntry {
21
+ readonly type: "emit_inbound" | "expect_outbound" | "runtime_exit" | "transcript_start";
22
+ readonly frame?: LogicalFrame;
23
+ readonly afterMs?: number;
24
+}
25
+
26
+interface JsonRpcMessage {
27
+ readonly jsonrpc?: string;
28
+ readonly id?: string | number | null;
29
+ readonly method?: string;
30
+ readonly params?: Record<string, unknown>;
31
+ readonly result?: unknown;
32
+ readonly error?: unknown;
33
+}
34
+
35
+export interface ReplayTurn {
36
+ /** Frames the agent sends: session updates and agent-to-client requests. */
37
+ readonly frames: ReadonlyArray<{ readonly frame: LogicalFrame; readonly afterMs?: number }>;
38
+ readonly stopReason: string;
39
+}
40
+
41
+const FIXTURES = "../src/orchestration-v2/testkit/fixtures";
42
+
43
+// Recorded fixtures the replay tests already pin, plus a hand-written UI showcase.
44
+// Use acpRegistry transcripts: vendor transcripts carry state in frames this agent drops.
45
+export const SCENARIOS = [
46
+ { id: "showcase", name: "Showcase", file: "./dev-replay/showcase_transcript.ndjson" },
47
+ {
48
+ id: "todo-list",
49
+ name: "Plan and reads",
50
+ file: `${FIXTURES}/todo_list/registry_transcript.ndjson`,
51
+ },
52
+ {
53
+ id: "approval",
54
+ name: "Write approval",
55
+ file: `${FIXTURES}/tool_call_read_only_on_request/registry_transcript.ndjson`,
56
+ },
57
+ {
58
+ id: "question",
59
+ name: "Question",
60
+ file: `${FIXTURES}/acp_elicitation/registry_transcript.ndjson`,
61
+ },
62
+ {
63
+ id: "multi-turn",
64
+ name: "Multi turn",
65
+ file: `${FIXTURES}/multi_turn/registry_transcript.ndjson`,
66
+ },
67
+] as const;
68
+
69
+// Session setup and vendor state stay out: they would replace the replay agent's own models.
70
+const REPLAYED_UPDATES = new Set([
71
+ "agent_message_chunk",
72
+ "agent_thought_chunk",
73
+ "tool_call",
74
+ "tool_call_update",
75
+ "plan",
76
+ "plan_update",
77
+ "plan_removed",
78
+ "session_info_update",
79
+ "usage_update",
80
+]);
81
+
82
+// Only requests that ask the user. A replayed terminal/create would run a real command.
83
+const REPLAYED_REQUESTS = new Set(["session/request_permission", "elicitation/create"]);
84
+
85
+const CHUNK_DELAY_MS = 30;
86
+const FRAME_DELAY_MS = 250;
87
+const MAX_RECORDED_DELAY_MS = 2_000;
88
+const WORDS_PER_CHUNK = 3;
89
+
90
+function isReplayedFrame(frame: LogicalFrame): boolean {
91
+ if (frame.kind === "request") return REPLAYED_REQUESTS.has(frame.method);
92
+ if (frame.kind !== "notification" || frame.method !== "session/update") return false;
93
+ const update = (frame.params as { update?: { sessionUpdate?: unknown } } | undefined)?.update;
94
+ return typeof update?.sessionUpdate === "string" && REPLAYED_UPDATES.has(update.sessionUpdate);
95
+}
96
+
97
+/** Splits a recorded transcript into the turns that follow each `session/prompt`. */
98
+export function parseReplayTurns(ndjson: string): ReadonlyArray<ReplayTurn> {
99
+ const turns: Array<{ frames: Array<ReplayTurn["frames"][number]>; stopReason: string }> = [];
100
+ // Frames after a prompt's response belong to background work, not to that turn.
101
+ let turn: (typeof turns)[number] | undefined;
102
+ for (const line of ndjson.split("\n")) {
103
+ if (line.trim().length === 0) continue;
104
+ const entry = JSON.parse(line) as ReplayEntry;
105
+ const frame = entry.frame;
106
+ if (frame === undefined) continue;
107
+ if (
108
+ entry.type === "expect_outbound" &&
109
+ frame.kind === "request" &&
110
+ frame.method === "session/prompt"
111
+ ) {
112
+ turn = { frames: [], stopReason: "end_turn" };
113
+ turns.push(turn);
114
+ continue;
115
+ }
116
+ if (entry.type !== "emit_inbound" || turn === undefined) continue;
117
+ if (frame.kind === "response" && frame.method === "session/prompt") {
118
+ const stopReason = (frame.result as { stopReason?: unknown } | undefined)?.stopReason;
119
+ if (typeof stopReason === "string") turn.stopReason = stopReason;
120
+ turn = undefined;
121
+ continue;
122
+ }
123
+ if (isReplayedFrame(frame)) {
124
+ turn.frames.push(entry.afterMs === undefined ? { frame } : { frame, afterMs: entry.afterMs });
125
+ }
126
+ }
127
+ return turns;
128
+}
129
+
130
+/** Splits streamed text into small chunks so the client sees real deltas. */
131
+export function streamChunks(text: string): ReadonlyArray<string> {
132
+ const words = text.match(/\S+\s*|\s+/g) ?? [];
133
+ const chunks: Array<string> = [];
134
+ for (let index = 0; index < words.length; index += WORDS_PER_CHUNK) {
135
+ chunks.push(words.slice(index, index + WORDS_PER_CHUNK).join(""));
136
+ }
137
+ return chunks.length === 0 ? [text] : chunks;
138
+}
139
+
140
+/** Fills the live session, workspace, and per-prompt tool ids, so repeated turns add rows. */
141
+function materialize(
142
+ value: unknown,
143
+ live: { readonly sessionId: string; readonly workspace: string; readonly turnKey: string },
144
+): unknown {
145
+ if (typeof value === "string") return value.replaceAll("<workspace>", live.workspace);
146
+ if (Array.isArray(value)) return value.map((entry) => materialize(entry, live));
147
+ if (typeof value !== "object" || value === null) return value;
148
+ return Object.fromEntries(
149
+ Object.entries(value).map(([key, entry]) => [
150
+ key,
151
+ key === "sessionId"
152
+ ? live.sessionId
153
+ : key === "toolCallId"
154
+ ? `${live.turnKey}-${String(entry)}`
155
+ : materialize(entry, live),
156
+ ]),
157
+ );
158
+}
159
+
160
+/** The tool call a permission answer rejected, if the user declined or cancelled. */
161
+function permissionRejectedToolCallId(request: LogicalFrame, answer: unknown): string | undefined {
162
+ if (request.method !== "session/request_permission") return undefined;
163
+ const params = request.params as {
164
+ toolCall?: { toolCallId?: string };
165
+ options?: ReadonlyArray<{ optionId: string; kind: string }>;
166
+ };
167
+ const outcome = (answer as { outcome?: { outcome?: string; optionId?: string } } | undefined)
168
+ ?.outcome;
169
+ const chosen = params.options?.find((option) => option.optionId === outcome?.optionId);
170
+ const rejected = outcome?.outcome !== "selected" || chosen?.kind.startsWith("reject") === true;
171
+ return rejected ? params.toolCall?.toolCallId : undefined;
172
+}
173
+
174
+function runAgent(): void {
175
+ const turnsByScenario = new Map<string, ReadonlyArray<ReplayTurn>>();
176
+ const loadTurns = (scenarioId: string) => {
177
+ const cached = turnsByScenario.get(scenarioId);
178
+ if (cached !== undefined) return cached;
179
+ const scenario = SCENARIOS.find((candidate) => candidate.id === scenarioId) ?? SCENARIOS[0];
180
+ const turns = parseReplayTurns(
181
+ NodeFS.readFileSync(new URL(scenario.file, import.meta.url), "utf8"),
182
+ );
183
+ turnsByScenario.set(scenarioId, turns);
184
+ return turns;
185
+ };
186
+
187
+ const sessions = new Map<
188
+ string,
189
+ { cwd: string; model: string; promptCount: number; cancel: (() => void) | undefined }
190
+ >();
191
+ const pendingAgentRequests = new Map<string, (result: unknown) => void>();
192
+ let nextAgentRequestId = 1;
193
+
194
+ const send = (message: JsonRpcMessage) =>
195
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
196
+ // Resolves when `promise` settles or the turn is cancelled, whichever comes first.
197
+ const untilAbort = (promise: Promise<unknown>, signal: AbortSignal) =>
198
+ new Promise<void>((resolve) => {
199
+ if (signal.aborted) return resolve();
200
+ const onAbort = () => resolve();
201
+ signal.addEventListener("abort", onAbort, { once: true });
202
+ void promise.then(() => {
203
+ signal.removeEventListener("abort", onAbort);
204
+ resolve();
205
+ });
206
+ });
207
+ const sleep = (ms: number, signal: AbortSignal) =>
208
+ untilAbort(
209
+ new Promise((resolve) => setTimeout(resolve, Math.min(ms, MAX_RECORDED_DELAY_MS))),
210
+ signal,
211
+ );
212
+
213
+ const playTurn = async (
214
+ sessionId: string,
215
+ turn: ReplayTurn,
216
+ signal: AbortSignal,
217
+ ): Promise<"cancelled" | undefined> => {
218
+ const session = sessions.get(sessionId)!;
219
+ // Random, so a session loaded after a restart cannot reuse earlier tool rows.
220
+ const live = { sessionId, workspace: session.cwd, turnKey: NodeCrypto.randomUUID() };
221
+ for (const recorded of turn.frames) {
222
+ const frame = materialize(recorded.frame, live) as LogicalFrame;
223
+ if (frame.kind === "request") {
224
+ await sleep(recorded.afterMs ?? FRAME_DELAY_MS, signal);
225
+ if (signal.aborted) return;
226
+ const id = nextAgentRequestId++;
227
+ let answer: unknown;
228
+ const response = new Promise((resolve) =>
229
+ pendingAgentRequests.set(String(id), (result) => resolve((answer = result))),
230
+ );
231
+ send({ id, method: frame.method, params: frame.params as Record<string, unknown> });
232
+ await untilAbort(response, signal);
233
+ pendingAgentRequests.delete(String(id));
234
+ // The client answers "cancelled" when the user stops the turn mid-request.
235
+ const outcome = (answer as { outcome?: { outcome?: string } } | undefined)?.outcome;
236
+ if (signal.aborted || outcome?.outcome === "cancelled") return "cancelled";
237
+ const toolCallId = permissionRejectedToolCallId(frame, answer);
238
+ if (toolCallId === undefined) continue;
239
+ // The recording only has the approved path, so a rejection ends the turn here.
240
+ send({
241
+ method: "session/update",
242
+ params: {
243
+ sessionId,
244
+ update: { sessionUpdate: "tool_call_update", toolCallId, status: "failed" },
245
+ },
246
+ });
247
+ return;
248
+ }
249
+ const params = frame.params as { update: { sessionUpdate: string; content?: unknown } };
250
+ const content = params.update.content as { type?: string; text?: string } | undefined;
251
+ const text =
252
+ (params.update.sessionUpdate === "agent_message_chunk" ||
253
+ params.update.sessionUpdate === "agent_thought_chunk") &&
254
+ content?.type === "text"
255
+ ? content.text
256
+ : undefined;
257
+ // Live recordings hold one frame per token, so text defaults to the chunk pace.
258
+ const firstDelay = recorded.afterMs ?? (text === undefined ? FRAME_DELAY_MS : CHUNK_DELAY_MS);
259
+ const chunks = text === undefined ? [undefined] : streamChunks(text);
260
+ for (const [index, chunk] of chunks.entries()) {
261
+ await sleep(index === 0 ? firstDelay : CHUNK_DELAY_MS, signal);
262
+ if (signal.aborted) return;
263
+ send({
264
+ method: frame.method,
265
+ params:
266
+ chunk === undefined
267
+ ? params
268
+ : { ...params, update: { ...params.update, content: { ...content, text: chunk } } },
269
+ });
270
+ }
271
+ }
272
+ };
273
+
274
+ const handleRequest = async (message: JsonRpcMessage): Promise<unknown> => {
275
+ const params = message.params ?? {};
276
+ switch (message.method) {
277
+ case "initialize":
278
+ return {
279
+ protocolVersion: 1,
280
+ agentCapabilities: {
281
+ loadSession: true,
282
+ promptCapabilities: { image: false, audio: false, embeddedContext: true },
283
+ },
284
+ authMethods: [],
285
+ agentInfo: { name: "t3-dev-replay", version: "1" },
286
+ };
287
+ case "session/new":
288
+ case "session/load": {
289
+ // T3 starts one agent process per thread, so ids must be unique across processes.
290
+ // Loading after a restart keeps the thread usable; T3 already holds its history.
291
+ const sessionId =
292
+ message.method === "session/load" ? String(params.sessionId) : NodeCrypto.randomUUID();
293
+ const cwd = typeof params.cwd === "string" ? params.cwd : process.cwd();
294
+ sessions.set(sessionId, { cwd, model: SCENARIOS[0].id, promptCount: 0, cancel: undefined });
295
+ return {
296
+ ...(message.method === "session/new" ? { sessionId } : {}),
297
+ models: {
298
+ currentModelId: SCENARIOS[0].id,
299
+ availableModels: SCENARIOS.map((scenario) => ({
300
+ modelId: scenario.id,
301
+ name: scenario.name,
302
+ })),
303
+ },
304
+ };
305
+ }
306
+ case "session/set_model": {
307
+ const session = sessions.get(String(params.sessionId));
308
+ if (!SCENARIOS.some((scenario) => scenario.id === params.modelId)) {
309
+ throw Object.assign(new Error(`Unknown replay scenario ${String(params.modelId)}`), {
310
+ code: -32602,
311
+ });
312
+ }
313
+ if (session !== undefined && session.model !== params.modelId) {
314
+ session.model = String(params.modelId);
315
+ session.promptCount = 0;
316
+ }
317
+ return {};
318
+ }
319
+ case "session/prompt": {
320
+ const sessionId = String(params.sessionId);
321
+ const session = sessions.get(sessionId);
322
+ if (session === undefined) throw new Error(`Unknown session ${sessionId}`);
323
+ const turns = loadTurns(session.model);
324
+ const turn = turns[session.promptCount % Math.max(turns.length, 1)];
325
+ session.promptCount += 1;
326
+ const controller = new AbortController();
327
+ session.cancel = () => controller.abort();
328
+ let ended: "cancelled" | undefined;
329
+ try {
330
+ if (turn !== undefined) ended = await playTurn(sessionId, turn, controller.signal);
331
+ } finally {
332
+ session.cancel = undefined;
333
+ }
334
+ return {
335
+ stopReason:
336
+ controller.signal.aborted || ended === "cancelled"
337
+ ? "cancelled"
338
+ : (turn?.stopReason ?? "end_turn"),
339
+ };
340
+ }
341
+ case "session/close":
342
+ sessions.get(String(params.sessionId))?.cancel?.();
343
+ sessions.delete(String(params.sessionId));
344
+ return {};
345
+ case "authenticate":
346
+ case "session/set_mode":
347
+ return {};
348
+ default:
349
+ throw Object.assign(new Error(`Method not found: ${message.method}`), { code: -32601 });
350
+ }
351
+ };
352
+
353
+ const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
354
+ input.on("line", (line) => {
355
+ if (line.trim().length === 0) return;
356
+ let message: JsonRpcMessage;
357
+ try {
358
+ message = JSON.parse(line) as JsonRpcMessage;
359
+ } catch {
360
+ process.stderr.write(`dev replay agent ignored a line that is not JSON\n`);
361
+ return;
362
+ }
363
+ if (message.method === undefined) {
364
+ const resolve = pendingAgentRequests.get(String(message.id));
365
+ pendingAgentRequests.delete(String(message.id));
366
+ resolve?.(message.result);
367
+ return;
368
+ }
369
+ if (message.id === undefined || message.id === null) {
370
+ if (message.method === "session/cancel") {
371
+ sessions.get(String(message.params?.sessionId))?.cancel?.();
372
+ }
373
+ return;
374
+ }
375
+ const id = message.id;
376
+ handleRequest(message).then(
377
+ (result) => send({ id, result }),
378
+ (error: Error & { code?: number }) =>
379
+ send({ id, error: { code: error.code ?? -32603, message: error.message } }),
380
+ );
381
+ });
382
+}
383
+
384
+if (import.meta.main) runAgent();
apps/server/scripts/dev-replay/showcase_transcript.ndjson
new
+18
@@ -0,0 +1,18 @@
1
+{"type":"transcript_start","provider":"acpRegistry","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"dev_replay_showcase","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":"agent_thought_chunk","content":{"type":"text","text":"The user wants a short tour. I will read the manifest, add a small helper, run the tests, and then summarize with some markdown."}}}}}
4
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"plan","entries":[{"content":"Read the package manifest","priority":"high","status":"in_progress"},{"content":"Add a clamp helper","priority":"high","status":"pending"},{"content":"Run the tests","priority":"medium","status":"pending"}]}}}}
5
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call","toolCallId":"showcase-read","kind":"read","title":"Read package.json","status":"pending","rawInput":{"path":"<workspace>/package.json"}}}}}
6
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call_update","toolCallId":"showcase-read","status":"completed","content":[{"type":"content","content":{"type":"text","text":"{\n \"name\": \"demo\",\n \"scripts\": { \"test\": \"vp test run\" }\n}"}}]}}}}
7
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"plan","entries":[{"content":"Read the package manifest","priority":"high","status":"completed"},{"content":"Add a clamp helper","priority":"high","status":"in_progress"},{"content":"Run the tests","priority":"medium","status":"pending"}]}}}}
8
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The project has a single math module. I will add a `clamp` helper beside `sum`.\n\n"}}}}}
9
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call","toolCallId":"showcase-edit","kind":"edit","title":"Edit src/math.ts","rawInput":{"path":"<workspace>/src/math.ts"},"status":"pending","content":[{"type":"diff","path":"<workspace>/src/math.ts","oldText":"export function sum(a: number, b: number) {\n return a + b;\n}\n","newText":"export function sum(a: number, b: number) {\n return a + b;\n}\n\nexport function clamp(value: number, min: number, max: number) {\n return Math.min(Math.max(value, min), max);\n}\n"}]}}}}
10
+{"type":"emit_inbound","frame":{"kind":"request","method":"session/request_permission","params":{"sessionId":"dev-replay-session","toolCall":{"toolCallId":"showcase-edit","kind":"edit","title":"Edit src/math.ts","rawInput":{"path":"<workspace>/src/math.ts"}},"options":[{"optionId":"allow-once","name":"Yes","kind":"allow_once"},{"optionId":"reject-once","name":"No","kind":"reject_once"}]}}}
11
+{"type":"expect_outbound","frame":{"kind":"response","method":"session/request_permission","result":"<any>"}}
12
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call_update","toolCallId":"showcase-edit","status":"completed","content":[{"type":"diff","path":"<workspace>/src/math.ts","oldText":"export function sum(a: number, b: number) {\n return a + b;\n}\n","newText":"export function sum(a: number, b: number) {\n return a + b;\n}\n\nexport function clamp(value: number, min: number, max: number) {\n return Math.min(Math.max(value, min), max);\n}\n"}]}}}}
13
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"plan","entries":[{"content":"Read the package manifest","priority":"high","status":"completed"},{"content":"Add a clamp helper","priority":"high","status":"completed"},{"content":"Run the tests","priority":"medium","status":"in_progress"}]}}}}
14
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call","toolCallId":"showcase-test","kind":"execute","title":"vp test run","status":"in_progress","rawInput":{"command":"vp test run"}}}}}
15
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"tool_call_update","toolCallId":"showcase-test","status":"completed","content":[{"type":"content","content":{"type":"text","text":" ✓ src/math.test.ts (12 tests) 14ms\n\n Test Files 1 passed (1)\n Tests 12 passed (12)"}}]}}},"afterMs":1200}
16
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"plan","entries":[{"content":"Read the package manifest","priority":"high","status":"completed"},{"content":"Add a clamp helper","priority":"high","status":"completed"},{"content":"Run the tests","priority":"medium","status":"completed"}]}}}}
17
+{"type":"emit_inbound","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"dev-replay-session","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"## Done\n\nI added `clamp` next to `sum` and the tests pass.\n\n- Reads the manifest first\n- Asks before it writes\n- Streams a terminal result\n\n```ts\nclamp(12, 0, 10); // 10\nclamp(-3, 0, 10); // 0\n```\n\n| Step | Tool | Result |\n| --- | --- | --- |\n| Read | `read` | 1 file |\n| Edit | `edit` | +4 lines |\n| Test | `execute` | 12 passed |\n\nThis turn is a replay. It costs nothing, so send it again as often as you need."}}}}}
18
+{"type":"emit_inbound","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts
+60
-1
@@ -5,9 +5,19 @@ import {
5
ProviderInstanceId,
6
type ServerSettings,
7
} from "@t3tools/contracts";
8
+import * as NodeServices from "@effect/platform-node/NodeServices";
9
+import { it as effectIt } from "@effect/vitest";
10
+import * as Effect from "effect/Effect";
11
+import * as Layer from "effect/Layer";
12
import { describe, expect, it } from "vite-plus/test";
13
10
-import { deriveProviderInstanceConfigMap } from "./ProviderInstanceRegistryHydration.ts";
14
+import * as ServerConfig from "../config.ts";
15
+import { ServerSettingsService } from "../serverSettings.ts";
16
+import {
17
+ DEV_REPLAY_INSTANCE_ID,
18
+ deriveProviderInstanceConfigMap,
19
+ seedDevReplayInstance,
20
+} from "./ProviderInstanceRegistryHydration.ts";
21
22
const projectId = ProjectId.make("project-a");
23
const instanceId = ProviderInstanceId.make("codex_work");
@@ -82,3 +92,52 @@ describe("deriveProviderInstanceConfigMap", () => {
92
expect(merged[instanceId]).toBe(settings.providerInstances[instanceId]);
93
});
94
});
95
+
96
+describe("seedDevReplayInstance", () => {
97
+ const seed = (devUrl: URL | undefined) =>
98
+ Effect.gen(function* () {
99
+ const config = yield* ServerConfig.ServerConfig;
100
+ yield* seedDevReplayInstance().pipe(
101
+ Effect.provideService(ServerConfig.ServerConfig, { ...config, devUrl }),
102
+ );
103
+ const settings = yield* ServerSettingsService;
104
+ return (yield* settings.getSettings).providerInstances[DEV_REPLAY_INSTANCE_ID];
105
+ }).pipe(
106
+ Effect.provide(
107
+ Layer.mergeAll(
108
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-dev-replay-seed-" }),
109
+ ServerSettingsService.layerTest({
110
+ providerInstances: {
111
+ [DEV_REPLAY_INSTANCE_ID]: {
112
+ driver: ProviderDriverKind.make("acpRegistry"),
113
+ displayName: "My replay",
114
+ enabled: false,
115
+ config: { source: "local", commandPath: "/old/node" },
116
+ },
117
+ },
118
+ }),
119
+ ).pipe(Layer.provideMerge(NodeServices.layer)),
120
+ ),
121
+ );
122
+
123
+ effectIt.effect("leaves settings alone outside dev", () =>
124
+ seed(undefined).pipe(
125
+ Effect.map((instance) =>
126
+ expect(instance?.config).toEqual({ source: "local", commandPath: "/old/node" }),
127
+ ),
128
+ ),
129
+ );
130
+
131
+ effectIt.effect("points a dev server at the replay agent and keeps user edits", () =>
132
+ seed(new URL("http://localhost:5733")).pipe(
133
+ Effect.map((instance) => {
134
+ expect(instance?.displayName).toBe("My replay");
135
+ expect(instance?.enabled).toBe(false);
136
+ expect(instance?.config).toMatchObject({
137
+ source: "local",
138
+ commandArgs: [expect.stringMatching(/scripts[/\\]dev-replay-agent\.ts$/)],
139
+ });
140
+ }),
141
+ ),
142
+ );
143
+});
apps/server/src/provider/ProviderInstanceRegistryHydration.ts
+52
-2
@@ -1,14 +1,18 @@
1
import {
2
defaultInstanceIdForDriver,
3
+ ProviderDriverKind,
4
+ ProviderInstanceId,
5
providerInstanceConfigEnabledFlag,
6
resolveProviderInstanceEnabled,
7
type ProviderInstanceConfig,
8
type ProviderInstanceConfigMap,
7
- type ProviderInstanceId,
9
ServerSettings,
10
} from "@t3tools/contracts";
11
+import * as HostProcess from "@t3tools/shared/HostProcess";
12
import * as Effect from "effect/Effect";
13
+import * as FileSystem from "effect/FileSystem";
14
import * as Layer from "effect/Layer";
15
+import * as Path from "effect/Path";
16
import * as Stream from "effect/Stream";
17
18
import * as Settings from "../serverSettings.ts";
@@ -20,7 +24,7 @@ import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRe
24
import * as ProviderHostLive from "./ProviderHostLive.ts";
25
import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
26
import type * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
23
-import type * as ServerConfig from "../config.ts";
27
+import * as ServerConfig from "../config.ts";
28
import type * as PortScanner from "../preview/PortScanner.ts";
29
30
type ProviderInstanceRegistryHydrationEnv =
@@ -33,6 +37,8 @@ type ProviderInstanceRegistryHydrationEnv =
37
| Settings.ServerSettingsService
38
| BackgroundPolicy.BackgroundPolicy
39
| ServerConfig.ServerConfig
40
+ | Path.Path
41
+ | FileSystem.FileSystem
42
// The Claude runner counts its CLIs as running agents for port discovery.
43
| PortScanner.PortDiscovery;
44
@@ -70,6 +76,47 @@ export const deriveProviderInstanceConfigMap = (
76
return merged as ProviderInstanceConfigMap;
77
};
78
79
+export const DEV_REPLAY_INSTANCE_ID = ProviderInstanceId.make("devReplay");
80
+
81
+/**
82
+ * Dev servers run from source keep a free ACP agent that replays recorded turns, so UI checks
83
+ * need no paid model. Bundled servers, such as desktop dev, have no agent script and skip it.
84
+ */
85
+export const seedDevReplayInstance = Effect.fn(
86
+ "ProviderInstanceRegistryHydration.seedDevReplayInstance",
87
+)(function* () {
88
+ const config = yield* ServerConfig.ServerConfig;
89
+ if (config.devUrl === undefined) return;
90
+ const path = yield* Path.Path;
91
+ const agentPath = yield* path.fromFileUrl(
92
+ new URL("../../scripts/dev-replay-agent.ts", import.meta.url),
93
+ );
94
+ if (!(yield* (yield* FileSystem.FileSystem).exists(agentPath))) return;
95
+ const commandPath = yield* HostProcess.ExecutablePath;
96
+ const serverSettings = yield* Settings.ServerSettingsService;
97
+ const existing = (yield* serverSettings.getSettings).providerInstances[DEV_REPLAY_INSTANCE_ID];
98
+ const existingConfig = existing?.config as Record<string, unknown> | undefined;
99
+ // Rewritten only when stale: the node and checkout paths can move.
100
+ if (
101
+ existingConfig?.commandPath === commandPath &&
102
+ (existingConfig.commandArgs as ReadonlyArray<unknown> | undefined)?.[0] === agentPath
103
+ ) {
104
+ return;
105
+ }
106
+ // Keeps user edits, such as turning the provider off.
107
+ const instance: ProviderInstanceConfig = {
108
+ displayName: "Replay (dev)",
109
+ ...existing,
110
+ driver: ProviderDriverKind.make("acpRegistry"),
111
+ config: { ...existingConfig, source: "local", commandPath, commandArgs: [agentPath] },
112
+ };
113
+ yield* serverSettings.updateProviderInstance({
114
+ operation: "upsert",
115
+ instanceId: DEV_REPLAY_INSTANCE_ID,
116
+ instance,
117
+ });
118
+});
119
+
120
const layerSettingsWatcher = (settingsChanges: Stream.Stream<ServerSettings>) =>
121
Layer.effectDiscard(
122
Effect.gen(function* () {
@@ -100,6 +147,9 @@ export const layer: Layer.Layer<
147
> = Layer.unwrap(
148
Effect.gen(function* () {
149
const serverSettings = yield* Settings.ServerSettingsService;
150
+ yield* seedDevReplayInstance().pipe(
151
+ Effect.catchCause((cause) => Effect.logWarning("Dev replay agent unavailable", cause)),
152
+ );
153
// Subscribe before the seed read so saves during registry construction are queued.
154
const settingsChanges = yield* serverSettings.subscribeChanges;
155
const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
apps/web/src/components/DevReplayHost.tsx
new
+148
@@ -0,0 +1,148 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3
+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4
+import { ProviderInstanceId, type ThreadId } from "@t3tools/contracts";
5
+import { useNavigate, useParams } from "@tanstack/react-router";
6
+import { useEffect, useEffectEvent, useState } from "react";
7
+
8
+import { newMessageId, newThreadId } from "~/lib/utils";
9
+import { useProjects, useThreadShell } from "../state/entities";
10
+import { usePrimaryEnvironmentId } from "../state/environments";
11
+import { primaryServerProvidersAtom } from "../state/server";
12
+import { threadEnvironment } from "../state/threads";
13
+import { useOrchestrationCommand } from "../state/use-orchestration-command";
14
+import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
15
+import { Button } from "./ui/button";
16
+import { Dialog, DialogHeader, DialogPanel, DialogPopup, DialogTitle } from "./ui/dialog";
17
+import { toastManager } from "./ui/toast";
18
+
19
+// Dev servers register this free ACP agent; see ProviderInstanceRegistryHydration.ts.
20
+const DEV_REPLAY_INSTANCE_ID = ProviderInstanceId.make("devReplay");
21
+
22
+/**
23
+ * Starts free replay threads on the primary environment in dev builds. Ctrl+Alt+Shift+R
24
+ * opens a picker, and `window.t3dev.replay(scenario)` does the same from the console.
25
+ */
26
+export function DevReplayHost() {
27
+ const [open, setOpen] = useState(false);
28
+ const navigate = useNavigate();
29
+ const environmentId = usePrimaryEnvironmentId();
30
+ const providers = useAtomValue(primaryServerProvidersAtom);
31
+ const projects = useProjects();
32
+ const target = resolveThreadRouteTarget(useParams({ strict: false }));
33
+ const routeThread = useThreadShell(target?.kind === "server" ? target.threadRef : null);
34
+ const startTurn = useOrchestrationCommand(threadEnvironment.startTurn, { reportFailure: false });
35
+
36
+ const replayProvider = providers.find(
37
+ (provider) => provider.instanceId === DEV_REPLAY_INSTANCE_ID && provider.enabled,
38
+ );
39
+ const scenarios = replayProvider?.models ?? [];
40
+ const environmentProjects = projects.filter((project) => project.environmentId === environmentId);
41
+ const project =
42
+ environmentProjects.find((candidate) => candidate.id === routeThread?.projectId) ??
43
+ environmentProjects[0];
44
+
45
+ const replay = async (scenario?: string): Promise<ThreadId> => {
46
+ const model = scenario ?? scenarios[0]?.slug;
47
+ if (environmentId === null || project === undefined || model === undefined) {
48
+ throw new Error("Replay needs a dev server with a project and the Replay (dev) provider.");
49
+ }
50
+ if (!scenarios.some((candidate) => candidate.slug === model)) {
51
+ throw new Error(`Unknown replay scenario "${model}".`);
52
+ }
53
+ const threadId = newThreadId();
54
+ const modelSelection = { instanceId: DEV_REPLAY_INSTANCE_ID, model };
55
+ const title = `Replay: ${model}`;
56
+ const createdAt = new Date().toISOString();
57
+ const result = await startTurn({
58
+ environmentId,
59
+ input: {
60
+ threadId,
61
+ message: { messageId: newMessageId(), role: "user", text: title, attachments: [] },
62
+ modelSelection,
63
+ runtimeMode: "approval-required",
64
+ interactionMode: "default",
65
+ bootstrap: {
66
+ createThread: {
67
+ projectId: project.id,
68
+ title,
69
+ modelSelection,
70
+ runtimeMode: "approval-required",
71
+ interactionMode: "default",
72
+ branch: null,
73
+ worktreePath: null,
74
+ createdAt,
75
+ },
76
+ },
77
+ createdAt,
78
+ },
79
+ });
80
+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);
81
+ await navigate({
82
+ to: "/$environmentId/$threadId",
83
+ params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
84
+ });
85
+ return threadId;
86
+ };
87
+
88
+ const replayFromConsole = useEffectEvent(replay);
89
+ const listScenarios = useEffectEvent(() => scenarios.map((scenario) => scenario.slug));
90
+
91
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- exposes the console API on window and listens for the hidden window hotkey
92
+ useEffect(() => {
93
+ window.t3dev = {
94
+ replayScenarios: () => listScenarios(),
95
+ replay: (scenario) => replayFromConsole(scenario),
96
+ };
97
+ const onKeyDown = (event: KeyboardEvent) => {
98
+ if (event.repeat) return;
99
+ if (event.ctrlKey && event.altKey && event.shiftKey && event.code === "KeyR") {
100
+ event.preventDefault();
101
+ setOpen((current) => !current);
102
+ }
103
+ };
104
+ window.addEventListener("keydown", onKeyDown);
105
+ return () => {
106
+ delete window.t3dev;
107
+ window.removeEventListener("keydown", onKeyDown);
108
+ };
109
+ }, []);
110
+
111
+ const start = (scenario: string) => {
112
+ setOpen(false);
113
+ replay(scenario).catch((error: unknown) =>
114
+ toastManager.add({
115
+ type: "error",
116
+ title: "Replay failed",
117
+ description: error instanceof Error ? error.message : String(error),
118
+ }),
119
+ );
120
+ };
121
+
122
+ return (
123
+ <Dialog open={open} onOpenChange={setOpen}>
124
+ <DialogPopup className="sm:max-w-sm">
125
+ <DialogHeader>
126
+ <DialogTitle>
127
+ {project === undefined ? "Replay a recorded turn" : `Replay in ${project.title}`}
128
+ </DialogTitle>
129
+ </DialogHeader>
130
+ <DialogPanel>
131
+ {scenarios.length === 0 || project === undefined ? (
132
+ <p className="text-sm text-muted-foreground">
133
+ Needs a project and the Replay (dev) provider, which dev servers start.
134
+ </p>
135
+ ) : (
136
+ <div className="flex flex-col items-start gap-1">
137
+ {scenarios.map((scenario) => (
138
+ <Button key={scenario.slug} variant="ghost" onClick={() => start(scenario.slug)}>
139
+ {scenario.name}
140
+ </Button>
141
+ ))}
142
+ </div>
143
+ )}
144
+ </DialogPanel>
145
+ </DialogPopup>
146
+ </Dialog>
147
+ );
148
+}
apps/web/src/routes/__root.tsx
+2
@@ -20,6 +20,7 @@ import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
20
import { GuestShareDialogHost } from "../components/chat/GuestShareControls";
21
import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
22
import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
23
+import { DevReplayHost } from "../components/DevReplayHost";
24
import { FirstRunGate } from "../components/onboarding/FirstRunGate";
25
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
26
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
@@ -211,6 +212,7 @@ function RootRouteBranch() {
212
<GuestShareDialogHost />
213
<ProjectCloneToastCoordinator />
214
<AddProjectToMachineDialogHost />
215
+ {import.meta.env.DEV && primaryEnvironmentAuthenticated ? <DevReplayHost /> : null}
216
{primaryEnvironmentAuthenticated ? (
217
<EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
218
) : null}
apps/web/src/vite-env.d.ts
+6
-1
@@ -1,6 +1,6 @@
1
/// <reference types="vite-plus/client" />
2
3
-import type { DesktopBridge } from "@t3tools/contracts";
3
+import type { DesktopBridge, ThreadId } from "@t3tools/contracts";
4
5
interface ImportMetaEnv {
6
readonly VITE_HTTP_URL: string;
@@ -25,5 +25,10 @@ interface ImportMeta {
25
declare global {
26
interface Window {
27
desktopBridge?: DesktopBridge;
28
+ /** Dev builds only, from DevReplayHost. Agents call these from the browser console. */
29
+ t3dev?: {
30
+ readonly replayScenarios: () => ReadonlyArray<string>;
31
+ readonly replay: (scenario?: string) => Promise<ThreadId>;
32
+ };
33
}
34
}
docs/operations/development.md
+13
@@ -73,6 +73,19 @@ Read ports from the `[dev-runner]` output. Worktrees derive stable preferences f
73
but occupied ports can shift them. `T3CODE_PORT_OFFSET` or `T3CODE_DEV_INSTANCE` can select a
74
different preference when needed.
75
76
+### Replay provider
77
+
78
+`vp run dev` registers `Replay (dev)`, a local ACP agent at
79
+[dev-replay-agent.ts](../../apps/server/scripts/dev-replay-agent.ts). It plays recorded
80
+ACP transcripts with simulated streaming, so the real adapter, orchestration, and UI run
81
+without a paid model. Each scenario is a model, and each prompt plays the next recorded turn.
82
+Bundled servers, including desktop dev, skip it because they have no agent script.
83
+Dev servers add it back on start, so turn it off in Settings instead of removing it.
84
+To add a scenario, point a `SCENARIOS` entry at a generic ACP replay fixture
85
+(`registry_transcript.ndjson`) or a file in [dev-replay](../../apps/server/scripts/dev-replay).
86
+The agent replays session updates, permission requests, and questions. It drops session setup
87
+and vendor frames, so Grok and fx recordings lose their vendor-only behavior.
88
+
89
### Sharing and remote debugging
90
91
`vp run dev --share` publishes the web port over the machine's tailnet and prints a pairing URL