Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mobile-showcase-environment.ts

597 lines22.5 KB

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