Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - This host-side fixture creates an isolated local T3 environment.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFSP from "node:fs/promises";
4import * as NodePath from "node:path";
5import * as NodeSqlite from "node:sqlite";
6import * as NodeUtil from "node:util";
7
8const execFile = NodeUtil.promisify(NodeChildProcess.execFile);
9
10export const SHOWCASE_PROJECT_ID = "t3code";
11export const SHOWCASE_THREAD_ID = "remote-command-center";
12export const SHOWCASE_TERMINAL_ID = "term-1";
13
14export const SHOWCASE_SCENES = [
15 "threads",
16 "thread",
17 "terminal",
18 "review",
19 "environments",
20 "agent-activity",
21] as const;
22export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
23
24const PROJECTOR_NAMES = [
25 "projection.projects",
26 "projection.threads",
27 "projection.thread-messages",
28 "projection.thread-proposed-plans",
29 "projection.thread-activities",
30 "projection.thread-sessions",
31 "projection.thread-turns",
32 "projection.checkpoints",
33 "projection.pending-approvals",
34] as const;
35
36const MODEL_SELECTION = JSON.stringify({ instanceId: "codex", model: "gpt-5.4" });
37const PROJECT_SCRIPTS = JSON.stringify([
38 {
39 id: "dev",
40 name: "Dev",
41 command: "pnpm dev",
42 icon: "play",
43 runOnWorktreeCreate: false,
44 },
45 {
46 id: "test",
47 name: "Tests",
48 command: "pnpm test",
49 icon: "test",
50 runOnWorktreeCreate: false,
51 },
52]);
53
54const SHOWCASE_TERMINAL_PROMPT =
55 "\u001b[1;32m→\u001b[0m \u001b[1;36mt3code\u001b[0m \u001b[1;34mgit:(\u001b[1;31mfeat/remote-command-center\u001b[1;34m)\u001b[0m \u001b[1;33m✗\u001b[0m ";
56
57export const SHOWCASE_TERMINAL_BUFFER = [
58 `${SHOWCASE_TERMINAL_PROMPT}vpr dev`,
59 "",
60 " \u001b[1;32mVITE\u001b[0m \u001b[32mv7.1.1\u001b[0m \u001b[2mready in\u001b[0m \u001b[1m1.24s\u001b[0m",
61 "",
62 " \u001b[32m→\u001b[0m \u001b[2mLocal:\u001b[0m \u001b[4;36mhttp://127.0.0.1:5173/\u001b[0m",
63 " \u001b[32m→\u001b[0m \u001b[2mNetwork:\u001b[0m \u001b[4;36mhttp://192.168.1.24:5173/\u001b[0m",
64 " \u001b[32m→\u001b[0m \u001b[2mProject:\u001b[0m \u001b[1mt3code\u001b[0m \u001b[2m— ~/Code/t3code\u001b[0m",
65 "",
66 " \u001b[32m✓ 612 passed\u001b[0m \u001b[33m△ 2 warnings\u001b[0m \u001b[31m✗ 0 failed\u001b[0m",
67 "",
68 " \u001b[42;30m READY \u001b[0m \u001b[2mwatching for changes — press\u001b[0m \u001b[1mq\u001b[0m \u001b[2mto quit\u001b[0m",
69 "",
70 SHOWCASE_TERMINAL_PROMPT,
71].join("\r\n");
72
73const BASE_ENVIRONMENT_PRESENCE = `export function environmentLabel(count: number): string {
74 return \`${"${count}"} environments\`;
75}
76`;
77
78const UPDATED_ENVIRONMENT_PRESENCE = `const PULSE = ["✦", "✧", "·", "✧"] as const;
79
80export function environmentLabel(connected: number, total: number, frame: number): string {
81 const pulse = PULSE[frame % PULSE.length];
82 return \`${"${pulse} ${connected}/${total}"} ready\`;
83}
84`;
85
86const REMOTE_HANDOFF_CARD = `import { View, Text } from "react-native";
87
88export function RemoteHandoffCard(props: { machine: string; latencyMs: number }) {
89 return (
90 <View className="rounded-2xl bg-surface-2 p-4">
91 <Text className="font-semibold">Ready on {props.machine}</Text>
92 <Text className="text-success">Handoff in {props.latencyMs}ms</Text>
93 </View>
94 );
95}
96`;
97
98const PROJECT_FAVICONS = {
99 t3code: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
100 <rect width="128" height="128" rx="10" fill="#000"/>
101 <path d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z" fill="#fff"/>
102</svg>`,
103 react: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
104 <rect width="64" height="64" rx="15" fill="#20232a"/>
105 <g fill="none" stroke="#61dafb" stroke-width="2.8"><ellipse cx="32" cy="32" rx="25" ry="9"/><ellipse cx="32" cy="32" rx="25" ry="9" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="25" ry="9" transform="rotate(120 32 32)"/></g>
106 <circle cx="32" cy="32" r="4.8" fill="#61dafb"/>
107</svg>`,
108 linux: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
109 <rect width="64" height="64" rx="15" fill="#f7c948"/>
110 <ellipse cx="32" cy="35" rx="17" ry="22" fill="#202124"/>
111 <ellipse cx="32" cy="40" rx="12" ry="14" fill="#f5f5f2"/>
112 <circle cx="27" cy="24" r="5" fill="white"/><circle cx="37" cy="24" r="5" fill="white"/>
113 <circle cx="28" cy="25" r="2"/><circle cx="36" cy="25" r="2"/>
114 <path d="M27 31l5-4 5 4-5 4z" fill="#f28c28"/><path d="M16 55h14l-7-5zM34 55h14l-7-5z" fill="#f28c28"/>
115</svg>`,
116} as const;
117
118export const SHOWCASE_PROJECTS = [
119 {
120 id: "t3code",
121 title: "T3 Code",
122 directory: "t3code",
123 repositoryUrl: "https://github.com/pingdotgg/t3code.git",
124 favicon: PROJECT_FAVICONS.t3code,
125 },
126 {
127 id: "react",
128 title: "React",
129 directory: "react",
130 repositoryUrl: "https://github.com/facebook/react.git",
131 favicon: PROJECT_FAVICONS.react,
132 },
133 {
134 id: "linux",
135 title: "Linux",
136 directory: "linux",
137 repositoryUrl: "https://github.com/torvalds/linux.git",
138 favicon: PROJECT_FAVICONS.linux,
139 },
140] as const;
141
142export const SHOWCASE_ENVIRONMENTS = [
143 {
144 id: "moonbase-terminal",
145 label: "Moonbase Terminal",
146 projectIds: ["t3code"],
147 },
148 {
149 id: "suspense-station",
150 label: "Suspense Station",
151 projectIds: ["react"],
152 },
153 {
154 id: "kernel-cabin",
155 label: "Kernel Cabin",
156 projectIds: ["linux"],
157 },
158] as const;
159
160export const SHOWCASE_THREADS = [
161 {
162 id: SHOWCASE_THREAD_ID,
163 projectId: "t3code",
164 title: "Make remote coding feel local ✦",
165 branch: "feat/remote-command-center",
166 minutesAgo: 3,
167 request:
168 "Give T3 Code a remote-first command center. Make three machines feel one tap away, keep agent work in sync, and make every handoff feel instant.",
169 response:
170 "T3 Code now treats every machine like it is right here in the room. ✦\n\n- Moonbase, Suspense Station, and Kernel Cabin stay live together\n- Terminal state follows you without losing a single line\n- Agent work remains perfectly in sync across devices\n- Handoffs land before your train of thought can wander\n\nI also ran the changed workspace: **612 tests passed**.",
171 },
172 {
173 id: "pocket-command-center",
174 projectId: "t3code",
175 title: "Put the command center in your pocket",
176 branch: "feat/pocket-command-center",
177 minutesAgo: 21,
178 state: "approval" as const,
179 request: "Make switching between desktop, phone, and tablet feel like one continuous session.",
180 response:
181 "The handoff flow preserves the selected thread, terminal buffer, and working diff. The final motion treatment is ready for approval.",
182 },
183 {
184 id: "buttery-suspense",
185 projectId: "react",
186 title: "Make Suspense transitions buttery",
187 branch: "perf/buttery-suspense",
188 minutesAgo: 12,
189 state: "working" as const,
190 request:
191 "Trace the last few dropped frames in nested Suspense transitions and make them disappear.",
192 response: null,
193 },
194 {
195 id: "hydration-haikus",
196 projectId: "react",
197 title: "Turn hydration warnings into haikus",
198 branch: "dev/hydration-haikus",
199 minutesAgo: 44,
200 request:
201 "Keep hydration errors precise, but make the development copy unexpectedly delightful.",
202 response:
203 "The diagnostics still lead with the exact mismatch and component stack. A tiny optional haiku now closes the expanded explanation.",
204 snoozeMinutes: 90,
205 },
206 {
207 id: "beautiful-boot",
208 projectId: "linux",
209 title: "Make boot logs oddly beautiful",
210 branch: "feat/beautiful-boot",
211 minutesAgo: 34,
212 state: "plan" as const,
213 request:
214 "Design a clearer boot timeline that remains useful over serial and never hides kernel detail.",
215 response:
216 "The plan groups milestones without changing the underlying log stream, preserves plain-text output, and adds zero work to the hot path.",
217 },
218 {
219 id: "patient-penguins",
220 projectId: "linux",
221 title: "Teach penguins to wait patiently",
222 branch: "feat/patient-penguins",
223 minutesAgo: 52,
224 request: "Make delayed work easier to follow without adding noise to the scheduler trace.",
225 response:
226 "Delayed work now carries a concise reason through the trace, so the wait is legible without changing scheduling behavior.",
227 snoozeMinutes: 8 * 60,
228 },
229 {
230 id: "handoff-haptics",
231 projectId: "t3code",
232 title: "Tune the handoff haptics",
233 branch: "feat/handoff-haptics",
234 minutesAgo: 5 * 60,
235 settled: true,
236 request: "Give the desktop-to-phone handoff a haptic that lands with the animation.",
237 response:
238 "The handoff now taps once as the thread lands and stays silent on failure, so the phone never celebrates a handoff that did not happen.",
239 },
240 {
241 id: "streaming-shell",
242 projectId: "react",
243 title: "Stream the shell before the data",
244 branch: "feat/streaming-shell",
245 minutesAgo: 28 * 60,
246 settled: true,
247 request: "Get the app shell painted before any data request resolves.",
248 response:
249 "The shell now flushes on first byte and the data boundaries hydrate underneath it, so the first paint no longer waits on the slowest query.",
250 },
251 {
252 id: "quieter-oom",
253 projectId: "linux",
254 title: "Make the OOM killer explain itself",
255 branch: "feat/quieter-oom",
256 minutesAgo: 2 * 24 * 60,
257 settled: true,
258 request: "Make out-of-memory kills legible without adding a single allocation to the hot path.",
259 response:
260 "Kills now report the winning heuristic and the runner-up alongside the usual dump, assembled entirely from data the path already had.",
261 },
262] as const;
263
264function minutesBefore(now: number, minutes: number): string {
265 return new Date(now - minutes * 60_000).toISOString();
266}
267
268async function runGit(workspaceRoot: string, args: ReadonlyArray<string>): Promise<void> {
269 await execFile("git", [...args], {
270 cwd: workspaceRoot,
271 env: {
272 ...process.env,
273 GIT_AUTHOR_NAME: "Alex Rivera",
274 GIT_AUTHOR_EMAIL: "alex@lumen.test",
275 GIT_COMMITTER_NAME: "Alex Rivera",
276 GIT_COMMITTER_EMAIL: "alex@lumen.test",
277 },
278 });
279}
280
281async function initializeRepository(input: {
282 readonly workspaceRoot: string;
283 readonly repositoryUrl: string;
284 readonly commitMessage: string;
285}): Promise<void> {
286 await runGit(input.workspaceRoot, ["init", "-b", "main"]);
287 await runGit(input.workspaceRoot, ["remote", "add", "origin", input.repositoryUrl]);
288 await runGit(input.workspaceRoot, ["add", "."]);
289 await runGit(input.workspaceRoot, ["commit", "-m", input.commitMessage]);
290}
291
292async function seedT3CodeWorkspace(workspaceRoot: string): Promise<void> {
293 await NodeFSP.mkdir(NodePath.join(workspaceRoot, "apps/mobile/src/features/home"), {
294 recursive: true,
295 });
296 await NodeFSP.writeFile(
297 NodePath.join(workspaceRoot, "package.json"),
298 `${JSON.stringify({ name: "t3code", private: true, scripts: { test: "vp test" } }, null, 2)}\n`,
299 );
300 await NodeFSP.writeFile(NodePath.join(workspaceRoot, "favicon.svg"), PROJECT_FAVICONS.t3code);
301 await NodeFSP.writeFile(
302 NodePath.join(workspaceRoot, "apps/mobile/src/features/home/environmentPresence.ts"),
303 BASE_ENVIRONMENT_PRESENCE,
304 );
305 await initializeRepository({
306 workspaceRoot,
307 repositoryUrl: "https://github.com/pingdotgg/t3code.git",
308 commitMessage: "Show connected environments",
309 });
310 await runGit(workspaceRoot, ["checkout", "-b", "feat/remote-command-center"]);
311 await NodeFSP.writeFile(
312 NodePath.join(workspaceRoot, "apps/mobile/src/features/home/environmentPresence.ts"),
313 UPDATED_ENVIRONMENT_PRESENCE,
314 );
315 await NodeFSP.writeFile(
316 NodePath.join(workspaceRoot, "apps/mobile/src/features/home/RemoteHandoffCard.tsx"),
317 REMOTE_HANDOFF_CARD,
318 );
319}
320
321async function seedCompanionWorkspace(input: {
322 readonly workspaceRoot: string;
323 readonly title: string;
324 readonly repositoryUrl: string;
325 readonly favicon: string;
326}): Promise<void> {
327 await NodeFSP.mkdir(input.workspaceRoot, { recursive: true });
328 await NodeFSP.writeFile(NodePath.join(input.workspaceRoot, "favicon.svg"), input.favicon);
329 await NodeFSP.writeFile(
330 NodePath.join(input.workspaceRoot, "README.md"),
331 `# ${input.title}\n\nSeeded by the T3 Code mobile screenshot harness.\n`,
332 );
333 await initializeRepository({
334 workspaceRoot: input.workspaceRoot,
335 repositoryUrl: input.repositoryUrl,
336 commitMessage: `Seed ${input.title} workspace`,
337 });
338}
339
340function insertThread(
341 database: NodeSqlite.DatabaseSync,
342 now: number,
343 input: {
344 readonly id: string;
345 readonly projectId: string;
346 readonly title: string;
347 readonly branch: string;
348 readonly minutesAgo: number;
349 readonly state?: "working" | "approval" | "plan";
350 readonly settled?: boolean;
351 readonly snoozeMinutes?: number;
352 readonly workspaceRoot: string;
353 },
354): void {
355 const turnId = `${input.id}-turn`;
356 const updatedAt = minutesBefore(now, input.minutesAgo);
357 const isWorking = input.state === "working";
358 const snoozedUntil =
359 input.snoozeMinutes === undefined
360 ? null
361 : new Date(now + input.snoozeMinutes * 60_000).toISOString();
362 const snoozedAt =
363 input.snoozeMinutes === undefined
364 ? null
365 : minutesBefore(now, Math.max(1, Math.floor(input.minutesAgo / 2)));
366 database
367 .prepare(
368 `INSERT INTO projection_threads (
369 thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
370 branch, worktree_path, latest_turn_id, latest_user_message_at, pending_approval_count,
371 pending_user_input_count, has_actionable_proposed_plan, created_at, updated_at,
372 archived_at, deleted_at, settled_override, settled_at, snoozed_until, snoozed_at
373 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, NULL, NULL, ?, ?, ?, ?)`,
374 )
375 .run(
376 input.id,
377 input.projectId,
378 input.title,
379 MODEL_SELECTION,
380 "full-access",
381 input.state === "plan" ? "plan" : "default",
382 input.branch,
383 input.workspaceRoot,
384 turnId,
385 minutesBefore(now, input.minutesAgo + 1),
386 input.state === "approval" ? 1 : 0,
387 input.state === "plan" ? 1 : 0,
388 minutesBefore(now, input.minutesAgo + 120),
389 updatedAt,
390 input.settled ? "settled" : null,
391 input.settled ? updatedAt : null,
392 snoozedUntil,
393 snoozedAt,
394 );
395 database
396 .prepare(
397 `INSERT INTO projection_turns (
398 thread_id, turn_id, pending_message_id, assistant_message_id, state, requested_at,
399 started_at, completed_at, checkpoint_turn_count, checkpoint_ref, checkpoint_status,
400 checkpoint_files_json, source_proposed_plan_thread_id, source_proposed_plan_id
401 ) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, NULL, NULL, NULL, '[]', NULL, NULL)`,
402 )
403 .run(
404 input.id,
405 turnId,
406 isWorking ? null : `${input.id}-answer`,
407 isWorking ? "running" : "completed",
408 minutesBefore(now, input.minutesAgo + 2),
409 minutesBefore(now, input.minutesAgo + 2),
410 isWorking ? null : updatedAt,
411 );
412 database
413 .prepare(
414 `INSERT INTO projection_thread_sessions (
415 thread_id, status, provider_name, provider_instance_id, provider_session_id,
416 provider_thread_id, runtime_mode, active_turn_id, last_error, updated_at
417 ) VALUES (?, ?, 'Codex', 'codex', NULL, NULL, 'full-access', ?, NULL, ?)`,
418 )
419 .run(input.id, isWorking ? "running" : "ready", isWorking ? turnId : null, updatedAt);
420}
421
422// V1 tables this seed owns. `projection_projects` is not listed: V2 still
423// stores projects there, so the seed upserts its own rows instead. V2 clients
424// do not read the V1 thread rows; moving the seed to V2 is tracked in
425// https://github.com/pingdotgg/t3code/issues/15013.
426const SEEDED_V1_TABLES = [
427 "projection_pending_approvals",
428 "projection_thread_proposed_plans",
429 "projection_thread_activities",
430 "projection_thread_messages",
431 "projection_thread_sessions",
432 "projection_turns",
433 "projection_threads",
434 "projection_state",
435] as const;
436
437const SEEDED_PROJECTION_TABLES = [...SEEDED_V1_TABLES, "projection_projects"] as const;
438
439const SEEDED_THREAD_COLUMNS = ["snoozed_until", "snoozed_at"] as const;
440
441function hasSeedableSchema(dbPath: string): boolean {
442 let database: NodeSqlite.DatabaseSync;
443 try {
444 database = new NodeSqlite.DatabaseSync(dbPath, { readOnly: true });
445 } catch {
446 return false;
447 }
448 try {
449 const tableCount = database
450 .prepare(
451 `SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name IN (${SEEDED_PROJECTION_TABLES.map(() => "?").join(", ")})`,
452 )
453 .get(...SEEDED_PROJECTION_TABLES) as { count: number };
454 if (tableCount.count !== SEEDED_PROJECTION_TABLES.length) return false;
455
456 const threadColumns = database.prepare("PRAGMA table_info(projection_threads)").all() as Array<{
457 name: string;
458 }>;
459 const threadColumnNames = new Set(threadColumns.map((column) => column.name));
460 return SEEDED_THREAD_COLUMNS.every((column) => threadColumnNames.has(column));
461 } catch {
462 return false;
463 } finally {
464 database.close();
465 }
466}
467
468async function waitForSeedableSchema(dbPath: string, timeoutMs = 60_000): Promise<void> {
469 const deadline = Date.now() + timeoutMs;
470 while (Date.now() < deadline) {
471 if (hasSeedableSchema(dbPath)) return;
472 await new Promise((resolve) => setTimeout(resolve, 250));
473 }
474 throw new Error(`The environment server did not migrate ${dbPath} within ${timeoutMs}ms.`);
475}
476
477function seedDatabase(
478 dbPath: string,
479 workspaceRoots: ReadonlyMap<string, string>,
480 projects: ReadonlyArray<(typeof SHOWCASE_PROJECTS)[number]>,
481 threads: ReadonlyArray<(typeof SHOWCASE_THREADS)[number]>,
482 now: number,
483): void {
484 // The environment server is already running against this file and keeps
485 // writing (migrations, projections) while we seed, so the write lock is
486 // genuinely contended — without a busy timeout `BEGIN IMMEDIATE` fails
487 // instantly with SQLITE_BUSY on a loaded machine.
488 const database = new NodeSqlite.DatabaseSync(dbPath, { timeout: 30_000 });
489 try {
490 database.exec("BEGIN IMMEDIATE");
491 for (const table of SEEDED_V1_TABLES) {
492 database.exec(`DELETE FROM ${table}`);
493 }
494 const insertProject = database.prepare(
495 `INSERT OR REPLACE INTO projection_projects (
496 project_id, title, workspace_root, default_model_selection_json, scripts_json,
497 created_at, updated_at, deleted_at
498 ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`,
499 );
500 for (const [index, project] of projects.entries()) {
501 const workspaceRoot = workspaceRoots.get(project.id);
502 if (!workspaceRoot) throw new Error(`Missing workspace root for ${project.id}.`);
503 const latestThreadMinutes = Math.min(
504 ...threads
505 .filter((thread) => thread.projectId === project.id)
506 .map((thread) => thread.minutesAgo),
507 );
508 insertProject.run(
509 project.id,
510 project.title,
511 workspaceRoot,
512 MODEL_SELECTION,
513 PROJECT_SCRIPTS,
514 minutesBefore(now, 60 * 24 * (90 - index * 12)),
515 minutesBefore(now, latestThreadMinutes),
516 );
517 }
518
519 for (const thread of threads) {
520 const workspaceRoot = workspaceRoots.get(thread.projectId);
521 if (!workspaceRoot) throw new Error(`Missing workspace root for ${thread.projectId}.`);
522 insertThread(database, now, {
523 ...thread,
524 ...("state" in thread ? { state: thread.state } : {}),
525 workspaceRoot,
526 });
527 }
528
529 const insertMessage = database.prepare(
530 `INSERT INTO projection_thread_messages (
531 message_id, thread_id, turn_id, role, text, is_streaming, attachments_json,
532 created_at, updated_at
533 ) VALUES (?, ?, ?, ?, ?, 0, NULL, ?, ?)`,
534 );
535 for (const thread of threads) {
536 const turnId = `${thread.id}-turn`;
537 const requestTime = minutesBefore(now, thread.minutesAgo + 5);
538 insertMessage.run(
539 `${thread.id}-request`,
540 thread.id,
541 turnId,
542 "user",
543 thread.request,
544 requestTime,
545 requestTime,
546 );
547 if (thread.response !== null) {
548 const responseTime = minutesBefore(now, thread.minutesAgo);
549 insertMessage.run(
550 `${thread.id}-answer`,
551 thread.id,
552 turnId,
553 "assistant",
554 thread.response,
555 responseTime,
556 responseTime,
557 );
558 }
559 }
560
561 const turnId = `${SHOWCASE_THREAD_ID}-turn`;
562 const insertActivity = database.prepare(
563 `INSERT INTO projection_thread_activities (
564 activity_id, thread_id, turn_id, tone, kind, summary, payload_json, sequence, created_at
565 ) VALUES (?, ?, ?, 'tool', 'tool.completed', ?, ?, ?, ?)`,
566 );
567 insertActivity.run(
568 "trace-remote-handoff",
569 SHOWCASE_THREAD_ID,
570 turnId,
571 "Traced the remote handoff path",
572 JSON.stringify({
573 itemType: "command_execution",
574 title: "Traced the remote handoff path",
575 detail: "Three environments, one continuous workspace",
576 status: "completed",
577 }),
578 1,
579 minutesBefore(now, 8),
580 );
581 insertActivity.run(
582 "sync-command-center",
583 SHOWCASE_THREAD_ID,
584 turnId,
585 "Synced the command center",
586 JSON.stringify({
587 itemType: "file_change",
588 title: "Synced the command center",
589 detail: "2 files changed · instant handoffs · calm reconnects",
590 status: "completed",
591 }),
592 2,
593 minutesBefore(now, 6),
594 );
595 insertActivity.run(
596 "run-changed-suite",
597 SHOWCASE_THREAD_ID,
598 turnId,
599 "Ran the changed workspace",
600 JSON.stringify({
601 itemType: "command_execution",
602 title: "Ran the changed workspace",
603 detail: "612 tests passed · 3 environments online",
604 status: "completed",
605 }),
606 3,
607 minutesBefore(now, 4),
608 );
609
610 for (const [index, projector] of PROJECTOR_NAMES.entries()) {
611 database
612 .prepare(
613 "INSERT INTO projection_state (projector, last_applied_sequence, updated_at) VALUES (?, ?, ?)",
614 )
615 .run(projector, index + 1, minutesBefore(now, 1));
616 }
617 database.exec("COMMIT");
618 } catch (error) {
619 // A failed BEGIN (or an error SQLite already auto-rolled back) leaves no
620 // transaction, and the rollback's own "cannot rollback" error would then
621 // replace the one that actually explains the failure.
622 try {
623 database.exec("ROLLBACK");
624 } catch {}
625 throw error;
626 } finally {
627 database.close();
628 }
629}
630
631export async function seedShowcaseEnvironment(input: {
632 readonly baseDir: string;
633 readonly projectIds?: ReadonlyArray<string>;
634 readonly now?: number;
635}): Promise<{ readonly dbPath: string; readonly workspaceRoot: string }> {
636 const now = input.now ?? Date.now();
637 const selectedProjectIds = new Set(
638 input.projectIds ?? SHOWCASE_PROJECTS.map((project) => project.id),
639 );
640 const projects = SHOWCASE_PROJECTS.filter((project) => selectedProjectIds.has(project.id));
641 if (projects.length === 0) throw new Error("At least one showcase project must be selected.");
642 const threads = SHOWCASE_THREADS.filter((thread) => selectedProjectIds.has(thread.projectId));
643 const workspaceBase = NodePath.join(input.baseDir, "workspace");
644 const workspaceRoots = new Map(
645 projects.map(
646 (project) => [project.id, NodePath.join(workspaceBase, project.directory)] as const,
647 ),
648 );
649 const primaryProject =
650 projects.find((project) => project.id === SHOWCASE_PROJECT_ID) ?? projects[0];
651 if (!primaryProject) throw new Error("The primary showcase workspace is not configured.");
652 const workspaceRoot = workspaceRoots.get(primaryProject.id);
653 if (!workspaceRoot) throw new Error("The primary showcase workspace is not configured.");
654 const dbPath = NodePath.join(input.baseDir, "userdata", "statev2.sqlite");
655 if (primaryProject.id === SHOWCASE_PROJECT_ID) {
656 await seedT3CodeWorkspace(workspaceRoot);
657 }
658 await Promise.all(
659 projects
660 .filter((project) => project.id !== SHOWCASE_PROJECT_ID)
661 .map(async (project) => {
662 const projectWorkspaceRoot = workspaceRoots.get(project.id);
663 if (!projectWorkspaceRoot) throw new Error(`Missing workspace root for ${project.id}.`);
664 await seedCompanionWorkspace({
665 workspaceRoot: projectWorkspaceRoot,
666 title: project.title,
667 repositoryUrl: project.repositoryUrl,
668 favicon: project.favicon,
669 });
670 }),
671 );
672 // The environment server begins listening before it finishes migrating the
673 // database, so wait for the schema before deleting from and reseeding it.
674 await waitForSeedableSchema(dbPath);
675 seedDatabase(dbPath, workspaceRoots, projects, threads, now);
676
677 const terminalDirectory = NodePath.join(input.baseDir, "userdata", "logs", "terminals");
678 if (selectedProjectIds.has(SHOWCASE_PROJECT_ID)) {
679 const safeThreadId = Buffer.from(SHOWCASE_THREAD_ID).toString("base64url");
680 await NodeFSP.mkdir(terminalDirectory, { recursive: true });
681 await NodeFSP.writeFile(
682 NodePath.join(terminalDirectory, `terminal_${safeThreadId}.log`),
683 SHOWCASE_TERMINAL_BUFFER,
684 );
685 }
686 return { dbPath, workspaceRoot };
687}