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 = ["threads", "thread", "terminal", "review", "environments"] as const;
15export type ShowcaseScene = (typeof SHOWCASE_SCENES)[number];
16
17const PROJECTOR_NAMES = [
18 "projection.projects",
19 "projection.threads",
20 "projection.thread-messages",
21 "projection.thread-proposed-plans",
22 "projection.thread-activities",
23 "projection.thread-sessions",
24 "projection.thread-turns",
25 "projection.checkpoints",
26 "projection.pending-approvals",
27] as const;
28
29const MODEL_SELECTION = JSON.stringify({ instanceId: "codex", model: "gpt-5.4" });
30const PROJECT_SCRIPTS = JSON.stringify([
31 {
32 id: "dev",
33 name: "Dev",
34 command: "pnpm dev",
35 icon: "play",
36 runOnWorktreeCreate: false,
37 },
38 {
39 id: "test",
40 name: "Tests",
41 command: "pnpm test",
42 icon: "test",
43 runOnWorktreeCreate: false,
44 },
45]);
46
47export const SHOWCASE_TERMINAL_BUFFER = [
48 "\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m",
49 "$ vp test run --changed",
50 "",
51 " \u001b[38;5;117mt3code-mobile\u001b[0m 184 passed",
52 " \u001b[38;5;213mclient-runtime\u001b[0m 263 passed",
53 " \u001b[38;5;221mserver\u001b[0m 165 passed",
54 "",
55 "\u001b[32m✨ 612 tests passed\u001b[0m · 3 environments online",
56 "",
57 "\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m $ ",
58].join("\r\n");
59
60const BASE_ENVIRONMENT_PRESENCE = `export function environmentLabel(count: number): string {
61 return \`${"${count}"} environments\`;
62}
63`;
64
65const UPDATED_ENVIRONMENT_PRESENCE = `const PULSE = ["✦", "✧", "·", "✧"] as const;
66
67export function environmentLabel(connected: number, total: number, frame: number): string {
68 const pulse = PULSE[frame % PULSE.length];
69 return \`${"${pulse} ${connected}/${total}"} ready\`;
70}
71`;
72
73const REMOTE_HANDOFF_CARD = `import { View, Text } from "react-native";
74
75export function RemoteHandoffCard(props: { machine: string; latencyMs: number }) {
76 return (
77 <View className="rounded-2xl bg-surface-2 p-4">
78 <Text className="font-semibold">Ready on {props.machine}</Text>
79 <Text className="text-success">Handoff in {props.latencyMs}ms</Text>
80 </View>
81 );
82}
83`;
84
85const PROJECT_FAVICONS = {
86 t3code: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
87 <rect width="128" height="128" rx="10" fill="#000"/>
88 <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"/>
89</svg>`,
90 react: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
91 <rect width="64" height="64" rx="15" fill="#20232a"/>
92 <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>
93 <circle cx="32" cy="32" r="4.8" fill="#61dafb"/>
94</svg>`,
95 linux: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
96 <rect width="64" height="64" rx="15" fill="#f7c948"/>
97 <ellipse cx="32" cy="35" rx="17" ry="22" fill="#202124"/>
98 <ellipse cx="32" cy="40" rx="12" ry="14" fill="#f5f5f2"/>
99 <circle cx="27" cy="24" r="5" fill="white"/><circle cx="37" cy="24" r="5" fill="white"/>
100 <circle cx="28" cy="25" r="2"/><circle cx="36" cy="25" r="2"/>
101 <path d="M27 31l5-4 5 4-5 4z" fill="#f28c28"/><path d="M16 55h14l-7-5zM34 55h14l-7-5z" fill="#f28c28"/>
102</svg>`,
103} as const;
104
105export const SHOWCASE_PROJECTS = [
106 {
107 id: "t3code",
108 title: "T3 Code",
109 directory: "t3code",
110 repositoryUrl: "https://github.com/pingdotgg/t3code.git",
111 favicon: PROJECT_FAVICONS.t3code,
112 },
113 {
114 id: "react",
115 title: "React",
116 directory: "react",
117 repositoryUrl: "https://github.com/facebook/react.git",
118 favicon: PROJECT_FAVICONS.react,
119 },
120 {
121 id: "linux",
122 title: "Linux",
123 directory: "linux",
124 repositoryUrl: "https://github.com/torvalds/linux.git",
125 favicon: PROJECT_FAVICONS.linux,
126 },
127] as const;
128
129export const SHOWCASE_ENVIRONMENTS = [
130 {
131 id: "moonbase-terminal",
132 label: "Moonbase Terminal",
133 projectIds: ["t3code"],
134 },
135 {
136 id: "suspense-station",
137 label: "Suspense Station",
138 projectIds: ["react"],
139 },
140 {
141 id: "kernel-cabin",
142 label: "Kernel Cabin",
143 projectIds: ["linux"],
144 },
145] as const;
146
147export const SHOWCASE_THREADS = [
148 {
149 id: SHOWCASE_THREAD_ID,
150 projectId: "t3code",
151 title: "Make remote coding feel local ✦",
152 branch: "feat/remote-command-center",
153 minutesAgo: 3,
154 request:
155 "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.",
156 response:
157 "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**.",
158 },
159 {
160 id: "pocket-command-center",
161 projectId: "t3code",
162 title: "Put the command center in your pocket",
163 branch: "feat/pocket-command-center",
164 minutesAgo: 21,
165 state: "approval" as const,
166 request: "Make switching between desktop, phone, and tablet feel like one continuous session.",
167 response:
168 "The handoff flow preserves the selected thread, terminal buffer, and working diff. The final motion treatment is ready for approval.",
169 },
170 {
171 id: "buttery-suspense",
172 projectId: "react",
173 title: "Make Suspense transitions buttery",
174 branch: "perf/buttery-suspense",
175 minutesAgo: 12,
176 state: "working" as const,
177 request:
178 "Trace the last few dropped frames in nested Suspense transitions and make them disappear.",
179 response: null,
180 },
181 {
182 id: "hydration-haikus",
183 projectId: "react",
184 title: "Turn hydration warnings into haikus",
185 branch: "dev/hydration-haikus",
186 minutesAgo: 44,
187 request:
188 "Keep hydration errors precise, but make the development copy unexpectedly delightful.",
189 response:
190 "The diagnostics still lead with the exact mismatch and component stack. A tiny optional haiku now closes the expanded explanation.",
191 },
192 {
193 id: "beautiful-boot",
194 projectId: "linux",
195 title: "Make boot logs oddly beautiful",
196 branch: "feat/beautiful-boot",
197 minutesAgo: 34,
198 state: "plan" as const,
199 request:
200 "Design a clearer boot timeline that remains useful over serial and never hides kernel detail.",
201 response:
202 "The plan groups milestones without changing the underlying log stream, preserves plain-text output, and adds zero work to the hot path.",
203 },
204 // Finished work, settled by hand: the list keeps it as a receded tail so
205 // the active block above reads as everything still in flight. The active
206 // block stays small enough that the settled tail begins above the fold —
207 // a store screenshot has to show that history exists, not just imply it.
208 {
209 id: "handoff-haptics",
210 projectId: "t3code",
211 title: "Tune the handoff haptics",
212 branch: "feat/handoff-haptics",
213 minutesAgo: 5 * 60,
214 settled: true,
215 request: "Give the desktop-to-phone handoff a haptic that lands with the animation.",
216 response:
217 "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.",
218 },
219 {
220 id: "streaming-shell",
221 projectId: "react",
222 title: "Stream the shell before the data",
223 branch: "feat/streaming-shell",
224 minutesAgo: 28 * 60,
225 settled: true,
226 request: "Get the app shell painted before any data request resolves.",
227 response:
228 "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.",
229 },
230 {
231 id: "quieter-oom",
232 projectId: "linux",
233 title: "Make the OOM killer explain itself",
234 branch: "feat/quieter-oom",
235 minutesAgo: 2 * 24 * 60,
236 settled: true,
237 request: "Make out-of-memory kills legible without adding a single allocation to the hot path.",
238 response:
239 "Kills now report the winning heuristic and the runner-up alongside the usual dump, assembled entirely from data the path already had.",
240 },
241] as const;
242
243function minutesBefore(now: number, minutes: number): string {
244 return new Date(now - minutes * 60_000).toISOString();
245}
246
247async function runGit(workspaceRoot: string, args: ReadonlyArray<string>): Promise<void> {
248 await execFile("git", [...args], {
249 cwd: workspaceRoot,
250 env: {
251 ...process.env,
252 GIT_AUTHOR_NAME: "Alex Rivera",
253 GIT_AUTHOR_EMAIL: "alex@lumen.test",
254 GIT_COMMITTER_NAME: "Alex Rivera",
255 GIT_COMMITTER_EMAIL: "alex@lumen.test",
256 },
257 });
258}
259
260async function initializeRepository(input: {
261 readonly workspaceRoot: string;
262 readonly repositoryUrl: string;
263 readonly commitMessage: string;
264}): Promise<void> {
265 await runGit(input.workspaceRoot, ["init", "-b", "main"]);
266 await runGit(input.workspaceRoot, ["remote", "add", "origin", input.repositoryUrl]);
267 await runGit(input.workspaceRoot, ["add", "."]);
268 await runGit(input.workspaceRoot, ["commit", "-m", input.commitMessage]);
269}
270
271async function seedT3CodeWorkspace(workspaceRoot: string): Promise<void> {
272 await NodeFSP.mkdir(NodePath.join(workspaceRoot, "apps/mobile/src/features/home"), {
273 recursive: true,
274 });
275 await NodeFSP.writeFile(
276 NodePath.join(workspaceRoot, "package.json"),
277 `${JSON.stringify({ name: "t3code", private: true, scripts: { test: "vp test" } }, null, 2)}\n`,
278 );
279 await NodeFSP.writeFile(NodePath.join(workspaceRoot, "favicon.svg"), PROJECT_FAVICONS.t3code);
280 await NodeFSP.writeFile(
281 NodePath.join(workspaceRoot, "apps/mobile/src/features/home/environmentPresence.ts"),
282 BASE_ENVIRONMENT_PRESENCE,
283 );
284 await initializeRepository({
285 workspaceRoot,
286 repositoryUrl: "https://github.com/pingdotgg/t3code.git",
287 commitMessage: "Show connected environments",
288 });
289 await runGit(workspaceRoot, ["checkout", "-b", "feat/remote-command-center"]);
290 await NodeFSP.writeFile(
291 NodePath.join(workspaceRoot, "apps/mobile/src/features/home/environmentPresence.ts"),
292 UPDATED_ENVIRONMENT_PRESENCE,
293 );
294 await NodeFSP.writeFile(
295 NodePath.join(workspaceRoot, "apps/mobile/src/features/home/RemoteHandoffCard.tsx"),
296 REMOTE_HANDOFF_CARD,
297 );
298}
299
300async function seedCompanionWorkspace(input: {
301 readonly workspaceRoot: string;
302 readonly title: string;
303 readonly repositoryUrl: string;
304 readonly favicon: string;
305}): Promise<void> {
306 await NodeFSP.mkdir(input.workspaceRoot, { recursive: true });
307 await NodeFSP.writeFile(NodePath.join(input.workspaceRoot, "favicon.svg"), input.favicon);
308 await NodeFSP.writeFile(
309 NodePath.join(input.workspaceRoot, "README.md"),
310 `# ${input.title}\n\nSeeded by the T3 Code mobile screenshot harness.\n`,
311 );
312 await initializeRepository({
313 workspaceRoot: input.workspaceRoot,
314 repositoryUrl: input.repositoryUrl,
315 commitMessage: `Seed ${input.title} workspace`,
316 });
317}
318
319function insertThread(
320 database: NodeSqlite.DatabaseSync,
321 now: number,
322 input: {
323 readonly id: string;
324 readonly projectId: string;
325 readonly title: string;
326 readonly branch: string;
327 readonly minutesAgo: number;
328 readonly state?: "working" | "approval" | "plan";
329 readonly settled?: boolean;
330 readonly workspaceRoot: string;
331 },
332): void {
333 const turnId = `${input.id}-turn`;
334 const updatedAt = minutesBefore(now, input.minutesAgo);
335 const isWorking = input.state === "working";
336 database
337 .prepare(
338 `INSERT INTO projection_threads (
339 thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
340 branch, worktree_path, latest_turn_id, latest_user_message_at, pending_approval_count,
341 pending_user_input_count, has_actionable_proposed_plan, created_at, updated_at,
342 archived_at, deleted_at, settled_override, settled_at
343 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, NULL, NULL, ?, ?)`,
344 )
345 .run(
346 input.id,
347 input.projectId,
348 input.title,
349 MODEL_SELECTION,
350 "full-access",
351 input.state === "plan" ? "plan" : "default",
352 input.branch,
353 input.workspaceRoot,
354 turnId,
355 minutesBefore(now, input.minutesAgo + 1),
356 input.state === "approval" ? 1 : 0,
357 input.state === "plan" ? 1 : 0,
358 minutesBefore(now, input.minutesAgo + 120),
359 updatedAt,
360 input.settled ? "settled" : null,
361 input.settled ? updatedAt : null,
362 );
363 database
364 .prepare(
365 `INSERT INTO projection_turns (
366 thread_id, turn_id, pending_message_id, assistant_message_id, state, requested_at,
367 started_at, completed_at, checkpoint_turn_count, checkpoint_ref, checkpoint_status,
368 checkpoint_files_json, source_proposed_plan_thread_id, source_proposed_plan_id
369 ) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, NULL, NULL, NULL, '[]', NULL, NULL)`,
370 )
371 .run(
372 input.id,
373 turnId,
374 isWorking ? null : `${input.id}-answer`,
375 isWorking ? "running" : "completed",
376 minutesBefore(now, input.minutesAgo + 2),
377 minutesBefore(now, input.minutesAgo + 2),
378 isWorking ? null : updatedAt,
379 );
380 database
381 .prepare(
382 `INSERT INTO projection_thread_sessions (
383 thread_id, status, provider_name, provider_instance_id, provider_session_id,
384 provider_thread_id, runtime_mode, active_turn_id, last_error, updated_at
385 ) VALUES (?, ?, 'Codex', 'codex', NULL, NULL, 'full-access', ?, NULL, ?)`,
386 )
387 .run(input.id, isWorking ? "running" : "ready", isWorking ? turnId : null, updatedAt);
388}
389
390const SEEDED_PROJECTION_TABLES = [
391 "projection_pending_approvals",
392 "projection_thread_proposed_plans",
393 "projection_thread_activities",
394 "projection_thread_messages",
395 "projection_thread_sessions",
396 "projection_turns",
397 "projection_threads",
398 "projection_projects",
399 "projection_state",
400] as const;
401
402function hasSeedableSchema(dbPath: string): boolean {
403 let database: NodeSqlite.DatabaseSync;
404 try {
405 database = new NodeSqlite.DatabaseSync(dbPath, { readOnly: true });
406 } catch {
407 return false;
408 }
409 try {
410 const row = database
411 .prepare(
412 `SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name IN (${SEEDED_PROJECTION_TABLES.map(() => "?").join(", ")})`,
413 )
414 .get(...SEEDED_PROJECTION_TABLES) as { count: number };
415 return row.count === SEEDED_PROJECTION_TABLES.length;
416 } catch {
417 return false;
418 } finally {
419 database.close();
420 }
421}
422
423async function waitForSeedableSchema(dbPath: string, timeoutMs = 60_000): Promise<void> {
424 const deadline = Date.now() + timeoutMs;
425 while (Date.now() < deadline) {
426 if (hasSeedableSchema(dbPath)) return;
427 await new Promise((resolve) => setTimeout(resolve, 250));
428 }
429 throw new Error(`The environment server did not migrate ${dbPath} within ${timeoutMs}ms.`);
430}
431
432function seedDatabase(
433 dbPath: string,
434 workspaceRoots: ReadonlyMap<string, string>,
435 projects: ReadonlyArray<(typeof SHOWCASE_PROJECTS)[number]>,
436 threads: ReadonlyArray<(typeof SHOWCASE_THREADS)[number]>,
437 now: number,
438): void {
439 // The environment server is already running against this file and keeps
440 // writing (migrations, projections) while we seed, so the write lock is
441 // genuinely contended — without a busy timeout `BEGIN IMMEDIATE` fails
442 // instantly with SQLITE_BUSY on a loaded machine.
443 const database = new NodeSqlite.DatabaseSync(dbPath, { timeout: 30_000 });
444 try {
445 database.exec("BEGIN IMMEDIATE");
446 for (const table of SEEDED_PROJECTION_TABLES) {
447 database.exec(`DELETE FROM ${table}`);
448 }
449 const insertProject = database.prepare(
450 `INSERT INTO projection_projects (
451 project_id, title, workspace_root, default_model_selection_json, scripts_json,
452 created_at, updated_at, deleted_at
453 ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`,
454 );
455 for (const [index, project] of projects.entries()) {
456 const workspaceRoot = workspaceRoots.get(project.id);
457 if (!workspaceRoot) throw new Error(`Missing workspace root for ${project.id}.`);
458 const latestThreadMinutes = Math.min(
459 ...threads
460 .filter((thread) => thread.projectId === project.id)
461 .map((thread) => thread.minutesAgo),
462 );
463 insertProject.run(
464 project.id,
465 project.title,
466 workspaceRoot,
467 MODEL_SELECTION,
468 PROJECT_SCRIPTS,
469 minutesBefore(now, 60 * 24 * (90 - index * 12)),
470 minutesBefore(now, latestThreadMinutes),
471 );
472 }
473
474 for (const thread of threads) {
475 const workspaceRoot = workspaceRoots.get(thread.projectId);
476 if (!workspaceRoot) throw new Error(`Missing workspace root for ${thread.projectId}.`);
477 insertThread(database, now, {
478 ...thread,
479 ...("state" in thread ? { state: thread.state } : {}),
480 workspaceRoot,
481 });
482 }
483
484 const insertMessage = database.prepare(
485 `INSERT INTO projection_thread_messages (
486 message_id, thread_id, turn_id, role, text, is_streaming, attachments_json,
487 created_at, updated_at
488 ) VALUES (?, ?, ?, ?, ?, 0, NULL, ?, ?)`,
489 );
490 for (const thread of threads) {
491 const turnId = `${thread.id}-turn`;
492 const requestTime = minutesBefore(now, thread.minutesAgo + 5);
493 insertMessage.run(
494 `${thread.id}-request`,
495 thread.id,
496 turnId,
497 "user",
498 thread.request,
499 requestTime,
500 requestTime,
501 );
502 if (thread.response !== null) {
503 const responseTime = minutesBefore(now, thread.minutesAgo);
504 insertMessage.run(
505 `${thread.id}-answer`,
506 thread.id,
507 turnId,
508 "assistant",
509 thread.response,
510 responseTime,
511 responseTime,
512 );
513 }
514 }
515
516 const turnId = `${SHOWCASE_THREAD_ID}-turn`;
517 const insertActivity = database.prepare(
518 `INSERT INTO projection_thread_activities (
519 activity_id, thread_id, turn_id, tone, kind, summary, payload_json, sequence, created_at
520 ) VALUES (?, ?, ?, 'tool', 'tool.completed', ?, ?, ?, ?)`,
521 );
522 insertActivity.run(
523 "trace-remote-handoff",
524 SHOWCASE_THREAD_ID,
525 turnId,
526 "Traced the remote handoff path",
527 JSON.stringify({
528 itemType: "command_execution",
529 title: "Traced the remote handoff path",
530 detail: "Three environments, one continuous workspace",
531 status: "completed",
532 }),
533 1,
534 minutesBefore(now, 8),
535 );
536 insertActivity.run(
537 "sync-command-center",
538 SHOWCASE_THREAD_ID,
539 turnId,
540 "Synced the command center",
541 JSON.stringify({
542 itemType: "file_change",
543 title: "Synced the command center",
544 detail: "2 files changed · instant handoffs · calm reconnects",
545 status: "completed",
546 }),
547 2,
548 minutesBefore(now, 6),
549 );
550 insertActivity.run(
551 "run-changed-suite",
552 SHOWCASE_THREAD_ID,
553 turnId,
554 "Ran the changed workspace",
555 JSON.stringify({
556 itemType: "command_execution",
557 title: "Ran the changed workspace",
558 detail: "612 tests passed · 3 environments online",
559 status: "completed",
560 }),
561 3,
562 minutesBefore(now, 4),
563 );
564
565 for (const [index, projector] of PROJECTOR_NAMES.entries()) {
566 database
567 .prepare(
568 "INSERT INTO projection_state (projector, last_applied_sequence, updated_at) VALUES (?, ?, ?)",
569 )
570 .run(projector, index + 1, minutesBefore(now, 1));
571 }
572 database.exec("COMMIT");
573 } catch (error) {
574 // A failed BEGIN (or an error SQLite already auto-rolled back) leaves no
575 // transaction, and the rollback's own "cannot rollback" error would then
576 // replace the one that actually explains the failure.
577 try {
578 database.exec("ROLLBACK");
579 } catch {
580 // Nothing to roll back.
581 }
582 throw error;
583 } finally {
584 database.close();
585 }
586}
587
588export async function seedShowcaseEnvironment(input: {
589 readonly baseDir: string;
590 readonly projectIds?: ReadonlyArray<string>;
591 readonly now?: number;
592}): Promise<{ readonly dbPath: string; readonly workspaceRoot: string }> {
593 const now = input.now ?? Date.now();
594 const selectedProjectIds = new Set(
595 input.projectIds ?? SHOWCASE_PROJECTS.map((project) => project.id),
596 );
597 const projects = SHOWCASE_PROJECTS.filter((project) => selectedProjectIds.has(project.id));
598 if (projects.length === 0) throw new Error("At least one showcase project must be selected.");
599 const threads = SHOWCASE_THREADS.filter((thread) => selectedProjectIds.has(thread.projectId));
600 const workspaceBase = NodePath.join(input.baseDir, "workspace");
601 const workspaceRoots = new Map(
602 projects.map(
603 (project) => [project.id, NodePath.join(workspaceBase, project.directory)] as const,
604 ),
605 );
606 const primaryProject =
607 projects.find((project) => project.id === SHOWCASE_PROJECT_ID) ?? projects[0];
608 if (!primaryProject) throw new Error("The primary showcase workspace is not configured.");
609 const workspaceRoot = workspaceRoots.get(primaryProject.id);
610 if (!workspaceRoot) throw new Error("The primary showcase workspace is not configured.");
611 const dbPath = NodePath.join(input.baseDir, "userdata", "state.sqlite");
612 if (primaryProject.id === SHOWCASE_PROJECT_ID) {
613 await seedT3CodeWorkspace(workspaceRoot);
614 }
615 await Promise.all(
616 projects
617 .filter((project) => project.id !== SHOWCASE_PROJECT_ID)
618 .map(async (project) => {
619 const projectWorkspaceRoot = workspaceRoots.get(project.id);
620 if (!projectWorkspaceRoot) throw new Error(`Missing workspace root for ${project.id}.`);
621 await seedCompanionWorkspace({
622 workspaceRoot: projectWorkspaceRoot,
623 title: project.title,
624 repositoryUrl: project.repositoryUrl,
625 favicon: project.favicon,
626 });
627 }),
628 );
629 // The environment server begins listening before it finishes migrating the
630 // database, so wait for the schema before deleting from and reseeding it.
631 await waitForSeedableSchema(dbPath);
632 seedDatabase(dbPath, workspaceRoots, projects, threads, now);
633
634 const terminalDirectory = NodePath.join(input.baseDir, "userdata", "logs", "terminals");
635 if (selectedProjectIds.has(SHOWCASE_PROJECT_ID)) {
636 const safeThreadId = Buffer.from(SHOWCASE_THREAD_ID).toString("base64url");
637 await NodeFSP.mkdir(terminalDirectory, { recursive: true });
638 await NodeFSP.writeFile(
639 NodePath.join(terminalDirectory, `terminal_${safeThreadId}.log`),
640 SHOWCASE_TERMINAL_BUFFER,
641 );
642 }
643 return { dbPath, workspaceRoot };
644}