The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 09:45 UTC
fix(scripts): dev --share no longer replaces another server's Serve route (#37888)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Jackson Miller committed
Nov 16, 2026 at 22:49 UTC
d7373c44feaa85f561c0f1e829ea1c31918acbeb
2 files changed
+134
-15
scripts/lib/dev-share.test.ts
+89
-8
@@ -1,4 +1,5 @@
1
import { assert, describe, it } from "@effect/vitest";
2
+import * as NetService from "@t3tools/shared/Net";
3
import * as Effect from "effect/Effect";
4
import * as Layer from "effect/Layer";
5
import * as Sink from "effect/Sink";
@@ -8,6 +9,7 @@ import { ChildProcessSpawner } from "effect/process";
9
import {
10
type DevShareError,
11
DevServeFailedError,
12
+ DevServePortTakenError,
13
shareDevServer,
14
unshareDevServer,
15
} from "./dev-share.ts";
@@ -22,21 +24,40 @@ interface CallResult {
24
25
const encode = (value: string) => Stream.make(new TextEncoder().encode(value));
26
27
+const serveStatusWithRoot = (webPort: number, proxy: string) =>
28
+ JSON.stringify({
29
+ Web: { [`host.example.ts.net:${String(webPort)}`]: { Handlers: { "/": { Proxy: proxy } } } },
30
+ });
31
+
32
const spawnerLayer = (input: {
33
readonly off?: CallResult;
34
readonly serve?: CallResult;
35
+ readonly serveStatus?: CallResult & { readonly stdout?: string };
36
+ readonly liveLoopbackPorts?: ReadonlyArray<number>;
37
readonly calls?: Array<ReadonlyArray<string>>;
29
-}) =>
30
- Layer.succeed(
38
+}) => {
39
+ const live = new Set(input.liveLoopbackPorts ?? []);
40
+ const unused = Effect.die("unused in dev-share tests");
41
+ const net = Layer.succeed(NetService.NetService, {
42
+ hasListenerOnHost: (port: number) => Effect.succeed(live.has(port)),
43
+ canListenOnHost: () => unused,
44
+ isPortAvailableOnLoopback: () => unused,
45
+ reserveLoopbackPort: () => unused,
46
+ findAvailablePort: () => unused,
47
+ });
48
+ const spawner = Layer.succeed(
49
ChildProcessSpawner.ChildProcessSpawner,
50
ChildProcessSpawner.make((command) => {
51
const args = "args" in command ? (command.args as ReadonlyArray<string>) : [];
52
input.calls?.push(args);
35
- const result: CallResult = args.includes("status")
36
- ? { exitCode: 0 }
37
- : args.includes("off")
38
- ? (input.off ?? { exitCode: 0 })
39
- : (input.serve ?? { exitCode: 0 });
53
+ const isServeStatus = args[0] === "serve" && args.includes("status");
54
+ const result: CallResult & { readonly stdout?: string } = isServeStatus
55
+ ? (input.serveStatus ?? { exitCode: 0, stdout: "{}" })
56
+ : args.includes("status")
57
+ ? { exitCode: 0, stdout: TAILNET_STATUS }
58
+ : args.includes("off")
59
+ ? (input.off ?? { exitCode: 0 })
60
+ : (input.serve ?? { exitCode: 0 });
61
62
return Effect.succeed(
63
ChildProcessSpawner.makeHandle({
@@ -46,7 +67,7 @@ const spawnerLayer = (input: {
67
kill: () => Effect.void,
68
unref: Effect.succeed(Effect.void),
69
stdin: Sink.drain,
49
- stdout: args.includes("status") ? encode(TAILNET_STATUS) : Stream.empty,
70
+ stdout: result.stdout !== undefined ? encode(result.stdout) : Stream.empty,
71
stderr: result.stderr ? encode(result.stderr) : Stream.empty,
72
all: Stream.empty,
73
getInputFd: () => Sink.drain,
@@ -55,6 +76,8 @@ const spawnerLayer = (input: {
76
);
77
}),
78
);
79
+ return Layer.merge(spawner, net);
80
+};
81
82
describe("unshareDevServer", () => {
83
// `tailscale serve … off` exits 1 when the port had no mapping, which is the
@@ -131,4 +154,62 @@ describe("shareDevServer", () => {
154
assert.include(error.message, "permission denied");
155
}),
156
);
157
+
158
+ it.effect("leaves a mapping that another running server holds alone", () =>
159
+ Effect.gen(function* () {
160
+ const calls: Array<ReadonlyArray<string>> = [];
161
+ const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
162
+ Effect.provide(
163
+ spawnerLayer({
164
+ serveStatus: {
165
+ exitCode: 0,
166
+ stdout: serveStatusWithRoot(5788, "http://127.0.0.1:9555"),
167
+ },
168
+ liveLoopbackPorts: [9555],
169
+ calls,
170
+ }),
171
+ ),
172
+ Effect.flip,
173
+ );
174
+
175
+ assert.instanceOf(error, DevServePortTakenError);
176
+ assert.isUndefined(calls.find((args) => args.includes("off") || args.includes("--bg")));
177
+ }),
178
+ );
179
+
180
+ it.effect("replaces a mapping that dials a port nothing listens on", () =>
181
+ Effect.gen(function* () {
182
+ const calls: Array<ReadonlyArray<string>> = [];
183
+ yield* shareDevServer({ webPort: 5788 }).pipe(
184
+ Effect.provide(
185
+ spawnerLayer({
186
+ serveStatus: {
187
+ exitCode: 0,
188
+ stdout: serveStatusWithRoot(5788, "http://127.0.0.1:9555"),
189
+ },
190
+ calls,
191
+ }),
192
+ ),
193
+ );
194
+
195
+ assert.isDefined(calls.find((args) => args.includes("off")));
196
+ assert.isDefined(calls.find((args) => args.includes("--bg")));
197
+ }),
198
+ );
199
+
200
+ it.effect("leaves the port alone when its mapping cannot be read", () =>
201
+ Effect.gen(function* () {
202
+ const calls: Array<ReadonlyArray<string>> = [];
203
+ const error: DevShareError = yield* shareDevServer({ webPort: 5788 }).pipe(
204
+ Effect.provide(
205
+ spawnerLayer({ serveStatus: { exitCode: 1, stderr: "permission denied" }, calls }),
206
+ ),
207
+ Effect.flip,
208
+ );
209
+
210
+ assert.instanceOf(error, DevServeFailedError);
211
+ assert.equal(error.stage, "read-existing");
212
+ assert.isUndefined(calls.find((args) => args.includes("off") || args.includes("--bg")));
213
+ }),
214
+ );
215
});
scripts/lib/dev-share.ts
+45
-7
@@ -4,6 +4,7 @@ import {
4
buildTailscaleHttpsBaseUrl,
5
disableTailscaleServe,
6
ensureTailscaleServe,
7
+ readTailscaleServeRootHolder,
8
readTailscaleStatus,
9
type TailscaleCommandError,
10
type TailscaleServeHttpsDisabledError,
@@ -61,7 +62,7 @@ export class TailnetNameMissingError extends Schema.TaggedError<TailnetNameMissi
62
export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>()(
63
"DevServeFailedError",
64
{
64
- stage: Schema.Literals(["clear-existing", "serve"]),
65
+ stage: Schema.Literals(["read-existing", "clear-existing", "serve"]),
66
webPort: Schema.Number,
67
explanation: Schema.optional(Schema.String),
68
cause: Schema.optional(Schema.Defect()),
@@ -70,9 +71,11 @@ export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>
71
override get message(): string {
72
const port = String(this.webPort);
73
const base =
73
- this.stage === "clear-existing"
74
- ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} --set-path=/ off\` and retry`
75
- : `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
74
+ this.stage === "read-existing"
75
+ ? `could not read the existing mapping for port ${port}, so it was left alone`
76
+ : this.stage === "clear-existing"
77
+ ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} --set-path=/ off\` and retry`
78
+ : `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
79
return this.explanation ? `${base}: ${this.explanation}` : base;
80
}
81
@@ -81,10 +84,24 @@ export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>
84
}
85
}
86
87
+export class DevServePortTakenError extends Schema.TaggedError<DevServePortTakenError>()(
88
+ "DevServePortTakenError",
89
+ { webPort: Schema.Number },
90
+) {
91
+ override get message(): string {
92
+ return `tailnet port ${String(this.webPort)} already serves another running server, so it was left alone`;
93
+ }
94
+
95
+ get hint(): string {
96
+ return `Pick another port with T3CODE_PORT_OFFSET, or remove that mapping with \`tailscale serve --https=${String(this.webPort)} --set-path=/ off\` if nothing needs it.`;
97
+ }
98
+}
99
+
100
export type DevShareError =
101
| TailscaleUnavailableError
102
| TailnetNameMissingError
87
- | DevServeFailedError;
103
+ | DevServeFailedError
104
+ | DevServePortTakenError;
105
106
/** Finalizer cleanup must be uninterruptible or cancellation can leave stale mappings. */
107
export const unshareDevServer = (
@@ -138,6 +155,27 @@ export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (in
155
return yield* new TailnetNameMissingError();
156
}
157
158
+ const target = input.localTarget ?? { port: input.webPort, host: "localhost" };
159
+ // A mapping left by an earlier run, or one dialing a dead loopback port, is safe to replace.
160
+ const holder = yield* readTailscaleServeRootHolder(input.webPort, {
161
+ port: target.port,
162
+ host: target.host.replace(/^\[|\]$/gu, ""),
163
+ }).pipe(
164
+ Effect.mapError((error) => {
165
+ const explanation =
166
+ error._tag === "TailscaleStatusParseError" ? undefined : explainCommandFailure(error);
167
+ return new DevServeFailedError({
168
+ stage: "read-existing",
169
+ webPort: input.webPort,
170
+ ...(explanation !== undefined ? { explanation } : {}),
171
+ cause: error,
172
+ });
173
+ }),
174
+ );
175
+ if (holder === "other") {
176
+ return yield* new DevServePortTakenError({ webPort: input.webPort });
177
+ }
178
+
179
const cleared = yield* unshareDevServer(input.webPort);
180
if (!cleared.cleared) {
181
// Refuse stale routes: the page could load while /ws and /api still point at a dead backend.
@@ -151,9 +189,9 @@ export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (in
189
190
// Vite's localhost can bind only ::1; a 127.0.0.1 proxy target would return 502.
191
yield* ensureTailscaleServe({
154
- localPort: input.localTarget?.port ?? input.webPort,
192
+ localPort: target.port,
193
servePort: input.webPort,
156
- localHost: input.localTarget?.host ?? "localhost",
194
+ localHost: target.host,
195
}).pipe(
196
Effect.mapError((error) => {
197
const explanation = explainCommandFailure(error);