Skip to content

Commit d335563

Browse files
committed
refactor(projects): derive preview ports from URL placeholders
Use the placeholder as the reservation request, removing the separate flag and editor control. Reuse existing port validation and workspace helpers, reduce repeated error mapping, and retain the launch ownership safeguards. Preserve thread-specific failure feedback and distinguish shell prompts from real output ending with a closing parenthesis.
1 parent 76ef0b6 commit d335563

25 files changed

Lines changed: 212 additions & 404 deletions

‎apps/mobile/src/features/threads/ThreadRouteScreen.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -709,7 +709,7 @@ function ThreadRouteContent(
709709
if (result.value.status === "no-script") {
710710
Dialog.alert(
711711
"Couldn't run script",
712-
`"${script.name}" is no longer saved with a reserved port. Check the action and try again.`,
712+
`"${script.name}" is no longer available. Check the action and try again.`,
713713
);
714714
return;
715715
}

‎apps/server/src/auth/RpcAuthorization.test.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,17 +60,12 @@ describe("RPC authorization scopes", () => {
6060
WS_METHODS.terminalRestart,
6161
WS_METHODS.terminalClose,
6262
WS_METHODS.projectsRunScript,
63+
WS_METHODS.projectsGetScriptPorts,
6364
]) {
6465
expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
6566
}
6667
});
6768

68-
it("reserves action ports only for clients that can run actions", () => {
69-
expect(requiredScopeForRpcMethod(WS_METHODS.projectsGetScriptPorts)).toBe(
70-
AuthTerminalOperateScope,
71-
);
72-
});
73-
7469
it("rejects unknown RPC method names", () => {
7570
for (const method of ["server.notRegistered", "toString", "constructor"]) {
7671
expect(() => requiredScopeForRpcMethod(method)).toThrow(

‎apps/server/src/mcp/WorktreeMcpService.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -698,12 +698,11 @@ describe("t3_worktree_status", () => {
698698
command: "vp dev",
699699
icon: "play",
700700
runOnWorktreeCreate: false,
701-
reservePort: true,
702701
previewUrl: "http://localhost:${T3CODE_PREVIEW_PORT}/preview",
703702
};
704703
const effectiveScripts = [
705704
previewScript,
706-
{ ...previewScript, id: "fixed", reservePort: false },
705+
{ ...previewScript, id: "fixed", previewUrl: "http://localhost:5173" },
707706
{ ...previewScript, id: "no-preview", previewUrl: undefined },
708707
];
709708
for (const worktreePath of [null, "/worktrees/project/existing"]) {

‎apps/server/src/mcp/WorktreeMcpService.ts‎

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
type WorktreeMcpStatusResult,
1111
} from "@t3tools/contracts";
1212
import {
13+
projectScriptCwd,
1314
projectScriptPreviewUrl,
1415
projectScriptReservesPort,
1516
resolveProjectScripts,
@@ -447,35 +448,29 @@ const make = Effect.gen(function* () {
447448
const scriptPreviews = yield* Effect.forEach(
448449
resolveProjectScripts(settings, project).filter(projectScriptReservesPort),
449450
(script) =>
450-
Effect.gen(function* () {
451-
const port = yield* scriptPorts
452-
.reserve({
453-
cwd: projection.thread.worktreePath ?? project.workspaceRoot,
451+
scriptPorts
452+
.reserve({
453+
cwd: projectScriptCwd({
454+
project: { cwd: project.workspaceRoot },
455+
worktreePath: projection.thread.worktreePath,
456+
}),
457+
scriptId: script.id,
458+
})
459+
.pipe(
460+
Effect.map((port) => ({
454461
scriptId: script.id,
455-
})
456-
.pipe(
457-
Effect.tapError((error) =>
458-
Effect.logWarning("Unable to reserve a preview port", {
459-
scriptId: script.id,
460-
startPort: error.startPort,
461-
attempts: error.attempts,
462-
}),
463-
),
464-
Effect.option,
465-
);
466-
if (Option.isNone(port)) return [];
467-
const url = projectScriptPreviewUrl(script, port.value);
468-
return url
469-
? [
470-
{
471-
scriptId: script.id,
472-
name: script.name,
473-
port: port.value,
474-
url,
475-
},
476-
]
477-
: [];
478-
}),
462+
name: script.name,
463+
port,
464+
url: projectScriptPreviewUrl(script.previewUrl, port),
465+
})),
466+
Effect.catch((error) =>
467+
Effect.logWarning("Unable to reserve a preview port", {
468+
scriptId: script.id,
469+
startPort: error.startPort,
470+
attempts: error.attempts,
471+
}).pipe(Effect.as(undefined)),
472+
),
473+
),
479474
);
480475

481476
const result: WorktreeMcpStatusResult = {
@@ -484,7 +479,7 @@ const make = Effect.gen(function* () {
484479
branch: projection.thread.branch,
485480
projectWorkspaceRoot: project.workspaceRoot,
486481
defaultStartFromOrigin: settings.newWorktreesStartFromOrigin,
487-
scriptPreviews: scriptPreviews.flat(),
482+
scriptPreviews: scriptPreviews.filter((preview) => preview !== undefined),
488483
};
489484
return result;
490485
},

‎apps/server/src/project/ProjectScriptPorts.ts‎

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -41,23 +41,20 @@ const make = Effect.gen(function* () {
4141
const reserve: ProjectScriptPorts["Service"]["reserve"] = Effect.fn("ProjectScriptPorts.reserve")(
4242
function* (input) {
4343
const key = `${path.resolve(input.cwd)}\0${input.scriptId}`;
44-
return yield* lock.withPermit(
45-
Effect.gen(function* () {
46-
const existing = assignments.get(key);
47-
if (existing !== undefined) return existing;
48-
const startPort = FIRST_PORT + (Math.abs(Hash.string(key)) % PORT_COUNT);
49-
for (let offset = 0; offset < PORT_COUNT; offset++) {
50-
const port = FIRST_PORT + ((startPort - FIRST_PORT + offset) % PORT_COUNT);
51-
if (assignedPorts.has(port) || !(yield* net.isPortAvailableOnLoopback(port))) continue;
52-
assignments.set(key, port);
53-
assignedPorts.add(port);
54-
yield* Effect.annotateCurrentSpan({ startPort, port, attempts: offset + 1 });
55-
return port;
56-
}
57-
return yield* new ProjectScriptPortUnavailableError({ startPort, attempts: PORT_COUNT });
58-
}),
59-
);
44+
const existing = assignments.get(key);
45+
if (existing !== undefined) return existing;
46+
const startPort = FIRST_PORT + (Math.abs(Hash.string(key)) % PORT_COUNT);
47+
for (let offset = 0; offset < PORT_COUNT; offset++) {
48+
const port = FIRST_PORT + ((startPort - FIRST_PORT + offset) % PORT_COUNT);
49+
if (assignedPorts.has(port) || !(yield* net.isPortAvailableOnLoopback(port))) continue;
50+
assignments.set(key, port);
51+
assignedPorts.add(port);
52+
yield* Effect.annotateCurrentSpan({ startPort, port, attempts: offset + 1 });
53+
return port;
54+
}
55+
return yield* new ProjectScriptPortUnavailableError({ startPort, attempts: PORT_COUNT });
6056
},
57+
lock.withPermit,
6158
);
6259

6360
return ProjectScriptPorts.of({

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

Lines changed: 47 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22
import { assert, it } from "@effect/vitest";
3-
import { ProjectId, ThreadId } from "@t3tools/contracts";
3+
import { ProjectId, ThreadId, type TerminalEvent } from "@t3tools/contracts";
44
import * as Effect from "effect/Effect";
55
import * as Deferred from "effect/Deferred";
66
import * as Fiber from "effect/Fiber";
@@ -22,6 +22,8 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
2222
const listeners = new Set<
2323
Parameters<TerminalManager.TerminalManager["Service"]["subscribe"]>[0]
2424
>();
25+
const publish = (event: TerminalEvent) =>
26+
Effect.forEach([...listeners], (listener) => listener(event), { discard: true });
2527
let openCount = 0;
2628
const openRequests: Array<Parameters<TerminalManager.TerminalManager["Service"]["open"]>[0]> =
2729
[];
@@ -37,7 +39,6 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
3739
icon: "play" as const,
3840
runOnWorktreeCreate: true,
3941
runOnSettle: true,
40-
reservePort: true,
4142
previewUrl: "http://localhost:${T3CODE_PREVIEW_PORT}",
4243
async: false,
4344
};
@@ -78,15 +79,13 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
7879
}
7980
terminalExited = exitBeforeSubscribe;
8081
if (terminalExited) {
81-
yield* Effect.forEach([...listeners], (listener) =>
82-
listener({
83-
type: "exited",
84-
threadId: request.threadId,
85-
terminalId: request.terminalId,
86-
exitCode: 1,
87-
exitSignal: null,
88-
}),
89-
);
82+
yield* publish({
83+
type: "exited",
84+
threadId: request.threadId,
85+
terminalId: request.terminalId,
86+
exitCode: 1,
87+
exitSignal: null,
88+
});
9089
}
9190
return {
9291
...request,
@@ -181,14 +180,12 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
181180
);
182181

183182
const token = /__T3_SETUP_DONE___(\w+):/.exec(writes[0]!)![1];
184-
yield* Effect.forEach([...listeners], (listener) =>
185-
listener({
186-
type: "output",
187-
threadId: input.threadId,
188-
terminalId: "script-43123",
189-
data: `\r\n__T3_SETUP_DONE___${token}:0\r\n$ `,
190-
}),
191-
);
183+
yield* publish({
184+
type: "output",
185+
threadId: input.threadId,
186+
terminalId: "script-43123",
187+
data: `\r\n__T3_SETUP_DONE___${token}:0\r\n$ `,
188+
});
192189
assert.equal((yield* lifecycle.completion!).exitCode, 0);
193190
assert.equal(listeners.size, 0);
194191
failWrite = true;
@@ -207,26 +204,24 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
207204
projectId,
208205
worktreePath: input.worktreePath,
209206
});
210-
yield* Effect.forEach([...listeners], (listener) =>
211-
listener({
212-
type: "restarted",
207+
yield* publish({
208+
type: "restarted",
209+
threadId: input.threadId,
210+
terminalId: "script-43123",
211+
snapshot: {
213212
threadId: input.threadId,
214213
terminalId: "script-43123",
215-
snapshot: {
216-
threadId: input.threadId,
217-
terminalId: "script-43123",
218-
cwd: input.worktreePath,
219-
worktreePath: input.worktreePath,
220-
status: "running",
221-
pid: 456,
222-
history: "",
223-
exitCode: null,
224-
exitSignal: null,
225-
label: "Shell",
226-
updatedAt: project.createdAt,
227-
},
228-
}),
229-
);
214+
cwd: input.worktreePath,
215+
worktreePath: input.worktreePath,
216+
status: "running",
217+
pid: 456,
218+
history: "",
219+
exitCode: null,
220+
exitSignal: null,
221+
label: "Shell",
222+
updatedAt: project.createdAt,
223+
},
224+
});
230225
assert.equal(restarted.status, "started");
231226
if (restarted.status === "started") {
232227
assert.equal((yield* restarted.completion!).exitCode, null);
@@ -248,15 +243,13 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
248243
projectId,
249244
worktreePath: input.worktreePath,
250245
});
251-
yield* Effect.forEach([...listeners], (listener) =>
252-
listener({
253-
type: "exited",
254-
threadId: input.threadId,
255-
terminalId: "script-43123",
256-
exitCode: 0,
257-
exitSignal: null,
258-
}),
259-
);
246+
yield* publish({
247+
type: "exited",
248+
threadId: input.threadId,
249+
terminalId: "script-43123",
250+
exitCode: 0,
251+
exitSignal: null,
252+
});
260253
if (interruptedRun.status === "started") yield* interruptedRun.completion!;
261254

262255
exitBeforeSubscribe = true;
@@ -280,7 +273,7 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
280273
},
281274
});
282275

283-
script.reservePort = false;
276+
script.previewUrl = "http://localhost:5173";
284277
const outputLines: string[] = [];
285278
const observed = yield* runner.runForThread({
286279
threadId: input.threadId,
@@ -298,16 +291,14 @@ it.effect("ReservedScript-overlappingStarts-reusesOwnerAndRetriesAfterCompletion
298291
if (observed.status !== "started") return;
299292
const wrapper = writes.at(-1)!;
300293
const outputToken = /__T3_SETUP_DONE___(\w+):/.exec(wrapper)![1];
301-
yield* Effect.forEach([...listeners], (listener) =>
302-
listener({
303-
type: "output",
304-
threadId: input.threadId,
305-
terminalId: "setup-output",
306-
data: `${wrapper}\r\nReady (vite)\r\nbackend\r\n__T3_SETUP_DONE___${outputToken}:0\r\n$ `,
307-
}),
308-
);
294+
yield* publish({
295+
type: "output",
296+
threadId: input.threadId,
297+
terminalId: "setup-output",
298+
data: `${wrapper}\r\n% (\r\nsubsh> )\r\nReady (vite)\r\nBuild complete ( 42 files )\r\nbackend\r\n__T3_SETUP_DONE___${outputToken}:0\r\n$ `,
299+
});
309300
assert.equal((yield* observed.completion!).exitCode, 0);
310-
assert.deepEqual(outputLines, ["Ready (vite)", "backend"]);
301+
assert.deepEqual(outputLines, ["Ready (vite)", "Build complete ( 42 files )", "backend"]);
311302
}).pipe(Effect.provide(layer));
312303
assert.equal(listeners.size, 0);
313304
}),

0 commit comments

Comments
 (0)