Skip to content

Commit 7aa57ec

Browse files
author
James Cane
committed
fix(projects): preserve shell readiness for reserved preview actions
1 parent b0b1565 commit 7aa57ec

2 files changed

Lines changed: 265 additions & 91 deletions

File tree

‎apps/server/src/project/ProjectSetupScriptRunner.test.ts‎

Lines changed: 139 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22
import { assert, describe, expect, it } from "@effect/vitest";
3-
import { ProjectId, ThreadId, type TerminalEvent, type TerminalSessionSnapshot } from "@t3tools/contracts";
3+
import {
4+
ProjectId,
5+
ThreadId,
6+
type TerminalEvent,
7+
type TerminalSessionSnapshot,
8+
} from "@t3tools/contracts";
49
import * as Effect from "effect/Effect";
510
import * as HostProcess from "@t3tools/shared/HostProcess";
611
import * as Queue from "effect/Queue";
@@ -34,6 +39,7 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
3439
let exitBeforeSubscribe = false;
3540
let terminalExited = false;
3641
const writes: string[] = [];
42+
let outputWritten: Deferred.Deferred<void> | undefined;
3743
const projectId = ProjectId.make("project:reserved-runner");
3844
const script = {
3945
id: "preview",
@@ -90,6 +96,12 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
9096
exitSignal: null,
9197
});
9298
}
99+
yield* publish({
100+
type: "output",
101+
threadId: request.threadId,
102+
terminalId: request.terminalId,
103+
data: "% \x1b[?2004h",
104+
});
93105
return {
94106
...request,
95107
worktreePath: request.worktreePath ?? null,
@@ -104,7 +116,10 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
104116
}),
105117
write: (request) =>
106118
Effect.gen(function* () {
107-
assert.equal(request.expectedPid, 123);
119+
assert.equal(
120+
request.expectedPid,
121+
request.terminalId.startsWith("script-") ? 123 : undefined,
122+
);
108123
assert.match(request.data, /^ \S/);
109124
if (terminalExited) {
110125
return yield* new TerminalManager.TerminalNotRunningError({
@@ -121,6 +136,7 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
121136
});
122137
}
123138
writes.push(request.data);
139+
if (outputWritten) yield* Deferred.succeed(outputWritten, undefined);
124140
const pendingWrite = writeGate;
125141
if (pendingWrite) {
126142
yield* Deferred.succeed(writing, undefined);
@@ -278,6 +294,7 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
278294

279295
script.previewUrl = "http://localhost:5173";
280296
const outputLines: string[] = [];
297+
outputWritten = yield* Deferred.make<void>();
281298
const observed = yield* runner.runForThread({
282299
threadId: input.threadId,
283300
projectId,
@@ -292,6 +309,7 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
292309
});
293310
assert.equal(observed.status, "started");
294311
if (observed.status !== "started") return;
312+
yield* Deferred.await(outputWritten);
295313
const wrapper = writes.at(-1)!;
296314
const outputToken = /__T3_SETUP_DONE___(\w+):/.exec(wrapper)![1];
297315
yield* publish({
@@ -328,29 +346,65 @@ const openSnapshot = (history: string): TerminalSessionSnapshot => ({
328346
const makeHarness = Effect.fn(function* (options: {
329347
readonly history?: string;
330348
readonly opening?: Deferred.Deferred<void>;
349+
readonly reserved?: boolean;
331350
}) {
351+
let currentPid = 123;
352+
let openCount = 0;
353+
const scriptTerminalId = options.reserved ? "script-43123" : terminalId;
332354
const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
333355
const writes = yield* Queue.unbounded<string>();
334356
const outputLines = yield* Queue.unbounded<string>();
335357
const terminals = Layer.mock(TerminalManager.TerminalManager)({
336-
open: () =>
337-
(options.opening
338-
? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
339-
: Effect.void
340-
).pipe(Effect.as(openSnapshot(options.history ?? ""))),
358+
open: () => {
359+
openCount += 1;
360+
return (
361+
options.opening
362+
? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
363+
: Effect.void
364+
).pipe(Effect.as({ ...openSnapshot(options.history ?? ""), terminalId: scriptTerminalId }));
365+
},
341366
subscribe: (listener) =>
342367
Effect.sync(() => {
343368
listeners.add(listener);
344369
return () => listeners.delete(listener);
345370
}),
346-
write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid),
371+
write: (input) =>
372+
input.expectedPid !== undefined && input.expectedPid !== currentPid
373+
? Effect.fail(
374+
new TerminalManager.TerminalNotRunningError({ threadId, terminalId: scriptTerminalId }),
375+
)
376+
: Queue.offer(writes, input.data).pipe(Effect.asVoid),
347377
closeIdle: () => Effect.void,
348378
});
379+
const project = {
380+
id: ProjectId.make("project-1"),
381+
workspaceRoot: "/repo",
382+
title: "Project",
383+
repositoryIdentity: null,
384+
faviconPath: null,
385+
defaultModelSelection: null,
386+
createdAt: "2026-06-20T00:00:00.000Z",
387+
updatedAt: "2026-06-20T00:00:00.000Z",
388+
deletedAt: null,
389+
scripts: [
390+
{
391+
id: "setup",
392+
name: "Setup",
393+
command: "vp i",
394+
icon: "configure" as const,
395+
runOnWorktreeCreate: true,
396+
...(options.reserved ? { previewUrl: "http://localhost:${T3CODE_PREVIEW_PORT}" } : {}),
397+
},
398+
],
399+
};
349400
const runner = yield* ProjectSetupScriptRunner.make.pipe(
350401
Effect.provide(
351402
Layer.mergeAll(
352403
terminals,
353-
Layer.mock(ProjectService.ProjectService)({}),
404+
Layer.mock(ProjectScriptPorts.ProjectScriptPorts)({ reserve: () => Effect.succeed(43123) }),
405+
Layer.mock(ProjectService.ProjectService)({
406+
getById: () => Effect.succeed(Option.some(project)),
407+
}),
354408
ServerSettings.layerTest(),
355409
NodeCrypto.layer,
356410
),
@@ -362,23 +416,27 @@ const makeHarness = Effect.fn(function* (options: {
362416
threadId,
363417
worktreePath: "/repo/.t3/worktrees/feature",
364418
observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) },
365-
project: {
366-
id: ProjectId.make("project-1"),
367-
workspaceRoot: "/repo",
368-
scripts: [
369-
{
370-
id: "setup",
371-
name: "Setup",
372-
command: "vp i",
373-
icon: "configure",
374-
runOnWorktreeCreate: true,
375-
},
376-
],
377-
},
419+
project,
378420
});
379-
const emit = (terminalEvent: TerminalEvent) =>
380-
Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true });
381-
return { start, listeners, writes, outputLines, emit };
421+
const emit = (terminalEvent: TerminalEvent) => {
422+
if (terminalEvent.type === "restarted") currentPid = terminalEvent.snapshot.pid!;
423+
return Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true });
424+
};
425+
return {
426+
start,
427+
listeners,
428+
writes,
429+
outputLines,
430+
emit,
431+
openCount: () => openCount,
432+
runManual: runner.runScript({
433+
threadId: ThreadId.make(threadId),
434+
projectId: ProjectId.make("project-1"),
435+
worktreePath: "/repo/.t3/worktrees/feature",
436+
scriptId: "setup",
437+
}),
438+
event: { ...event, terminalId: scriptTerminalId },
439+
};
382440
});
383441

384442
const setup = Effect.fn(function* (options: { readonly history?: string } = {}) {
@@ -390,6 +448,59 @@ const setup = Effect.fn(function* (options: { readonly history?: string } = {})
390448
});
391449

392450
describe("ProjectSetupScriptRunner", () => {
451+
it.effect(
452+
"shares a reserved launch while startup waits and reports delivery to manual callers",
453+
() =>
454+
Effect.gen(function* () {
455+
const harness = yield* makeHarness({ reserved: true });
456+
const result = yield* harness.start;
457+
expect(result.status).toBe("started");
458+
yield* harness.emit({ ...harness.event, type: "output", data: "Install Node? [y/N]: " });
459+
yield* harness.emit({
460+
...harness.event,
461+
type: "activity",
462+
hasRunningSubprocess: true,
463+
label: "fnm",
464+
});
465+
const manual = yield* harness.runManual.pipe(Effect.forkChild);
466+
yield* TestClock.adjust("1 minute");
467+
expect(harness.openCount()).toBe(1);
468+
expect(yield* Queue.size(harness.writes)).toBe(0);
469+
expect(manual.pollUnsafe()).toBeUndefined();
470+
expect(yield* Queue.takeAll(harness.outputLines)).toEqual(["Install Node? [y/N]:"]);
471+
yield* harness.emit({ ...harness.event, type: "output", data: "\r\n% \x1b[?2004h" });
472+
const command = yield* Queue.take(harness.writes);
473+
expect(yield* Fiber.join(manual)).toMatchObject({ status: "started", port: 43123 });
474+
const token = /__T3_SETUP_DONE___(\w+):/.exec(command)![1];
475+
yield* harness.emit({
476+
...harness.event,
477+
type: "output",
478+
data: `\r\n__T3_SETUP_DONE___${token}:0\r\n$ `,
479+
});
480+
if (result.status === "started") expect((yield* result.completion!).exitCode).toBe(0);
481+
expect(harness.listeners.size).toBe(0);
482+
}),
483+
);
484+
485+
it.effect("rejects a reserved command if its terminal is replaced during startup", () =>
486+
Effect.gen(function* () {
487+
const harness = yield* makeHarness({ reserved: true });
488+
const result = yield* harness.start;
489+
yield* harness.emit({
490+
...harness.event,
491+
type: "restarted",
492+
snapshot: { ...openSnapshot(""), pid: 456 },
493+
});
494+
yield* harness.emit({ ...harness.event, type: "output", data: "% \x1b[?2004h" });
495+
if (result.status !== "started") return;
496+
const failure = yield* result.commandDelivery!.pipe(Effect.flip);
497+
expect(failure.operation).toBe("writeCommand");
498+
expect((yield* result.completion!).exitCode).toBeNull();
499+
expect(yield* Queue.size(harness.writes)).toBe(0);
500+
expect(harness.listeners.size).toBe(0);
501+
}),
502+
);
503+
393504
it.effect("shows a startup prompt and types only once the line editor starts", () =>
394505
Effect.gen(function* () {
395506
const { result, writes, outputLines, emit } = yield* setup();
@@ -403,15 +514,15 @@ describe("ProjectSetupScriptRunner", () => {
403514

404515
yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
405516
yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
406-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
517+
expect(yield* Queue.take(writes)).toMatch(/^ \(\rtrap 'exit 130' INT\r/);
407518
}),
408519
);
409520

410521
it.effect("types into a quiet shell that has no line editor", () =>
411522
Effect.gen(function* () {
412523
const { writes } = yield* setup();
413524
yield* TestClock.adjust("3 seconds");
414-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
525+
expect(yield* Queue.take(writes)).toMatch(/^ \(\rtrap 'exit 130' INT\r/);
415526
}),
416527
);
417528

@@ -433,7 +544,7 @@ describe("ProjectSetupScriptRunner", () => {
433544
yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
434545
// The restart lands inside a quiet window, so the next full window decides.
435546
yield* TestClock.adjust("6 seconds");
436-
expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
547+
expect(yield* Queue.take(writes)).toMatch(/^ \(\rtrap 'exit 130' INT\r/);
437548
}),
438549
);
439550

0 commit comments

Comments
 (0)