Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
2import * as NodeHttp from "node:http";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { AuthStandardClientScopes, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
9import * as NetService from "@t3tools/shared/Net";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { assert, describe, expect, it } from "@effect/vitest";
12import * as Cause from "effect/Cause";
13import * as ConfigProvider from "effect/ConfigProvider";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Layer from "effect/Layer";
17import * as Sink from "effect/Sink";
18import * as Stream from "effect/Stream";
19import { FetchHttpClient } from "effect/http";
20import { ChildProcess, ChildProcessSpawner } from "effect/process";
21import * as TestClock from "effect/testing/TestClock";
22import * as TestConsole from "effect/testing/TestConsole";
23import { Command, CliError } from "effect/cli";
24
25import { cli } from "../binCli.ts";
26import {
27 SERVICE_LAUNCHER_CONTEXT_ENV,
28 SERVICE_LAUNCHER_PROTOCOL,
29} from "../cloud/serviceProtocol.ts";
30import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
31import {
32 makePersistedServerRuntimeState,
33 persistServerRuntimeState,
34 type PersistedServerRuntimeState,
35} from "../serverRuntimeState.ts";
36import { DevServerNotProxiableError, resolveTailscaleLocalTarget } from "./pair.ts";
37
38import packageJson from "../../package.json" with { type: "json" };
39import { buildPairingAppLink } from "@t3tools/shared/remote";
40
41const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
42
43const baseState = {
44 version: 1,
45 pid: 123,
46 port: 3_773,
47 origin: "http://127.0.0.1:3773",
48 startedAt: "2026-06-20T00:00:00.000Z",
49} as const satisfies PersistedServerRuntimeState;
50
51describe("pair tailscale local target", () => {
52 it("proxies the dev web port for dev servers", () => {
53 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
54 { localPort: 5_733 },
55 );
56 // tailscale serve defaults to loopback, so non-loopback dev servers need an explicit target.
57 expect(
58 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
59 ).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
60 expect(
61 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
62 ).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
63 });
64
65 it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
66 expect(
67 resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
68 ).toBeInstanceOf(DevServerNotProxiableError);
69 });
70});
71
72const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
73
74const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
75 Effect.provide(effect, Layer.mergeAll(layerCliRuntime, TestConsole.layer));
76
77const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
78 provideCliTestLayers(
79 Effect.gen(function* () {
80 yield* effect;
81 return (
82 (yield* TestConsole.logLines).findLast(
83 (line): line is string => typeof line === "string",
84 ) ?? ""
85 );
86 }),
87 );
88
89const testDescriptor = {
90 environmentId: "pair-test-environment",
91 label: "pair-test",
92 platform: { os: "linux", arch: "x64" },
93 serverVersion: "0.0.1",
94 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
95 capabilities: { repositoryIdentity: true },
96};
97
98const withDescriptorServer = <A, E, R>(
99 run: (origin: string) => Effect.Effect<A, E, R>,
100 host = "127.0.0.1",
101 descriptor: object = testDescriptor,
102) =>
103 Effect.acquireUseRelease(
104 Effect.callback<NodeHttp.Server>((resume) => {
105 const server = NodeHttp.createServer((request, response) => {
106 if (request.url === "/.well-known/t3/environment") {
107 response.writeHead(200, { "content-type": "application/json" });
108 response.end(JSON.stringify(descriptor));
109 return;
110 }
111 response.writeHead(404);
112 response.end();
113 });
114 server.listen(0, host, () => resume(Effect.succeed(server)));
115 }),
116 (server) => {
117 const address = server.address();
118 if (address === null || typeof address === "string") {
119 return Effect.die(new Error("Expected a TCP address"));
120 }
121 return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);
122 },
123 (server) => Effect.sync(() => server.close()),
124 );
125
126describe("t3 pair", () => {
127 it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>
128 withDescriptorServer(
129 (origin) =>
130 Effect.gen(function* () {
131 const fetch = yield* FetchHttpClient.Fetch;
132 let serving = false;
133 const spawner = ChildProcessSpawner.make((command) =>
134 Effect.gen(function* () {
135 if (!ChildProcess.isStandardCommand(command))
136 return yield* Effect.die("Unexpected pipeline");
137 if (command.args[0] === "serve") {
138 const target = command.args.at(-1)!;
139 const descriptor = yield* Effect.promise(async () =>
140 (await fetch(new URL("/.well-known/t3/environment", target))).json(),
141 );
142 expect(descriptor).toEqual(testDescriptor);
143 serving = true;
144 }
145 return ChildProcessSpawner.makeHandle({
146 pid: ChildProcessSpawner.ProcessId(1),
147 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
148 isRunning: Effect.succeed(false),
149 kill: () => Effect.void,
150 unref: Effect.succeed(Effect.void),
151 stdin: Sink.drain,
152 stdout: Stream.make(
153 new TextEncoder().encode('{"Self":{"DNSName":"pair-test.tail.ts.net."}}'),
154 ),
155 stderr: Stream.empty,
156 all: Stream.empty,
157 getInputFd: () => Sink.drain,
158 getOutputFd: () => Stream.empty,
159 });
160 }),
161 );
162
163 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ipv6-test-"));
164 yield* persistServerRuntimeState({
165 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
166 state: yield* makePersistedServerRuntimeState({
167 config: { host: "::1", devUrl: undefined },
168 port: Number(new URL(origin).port),
169 }),
170 });
171 const output = yield* captureStdout(
172 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
173 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
174 Effect.provideService(HostProcess.Platform, "linux"),
175 Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
176 if (String(input).startsWith(origin)) return fetch(input, init);
177 assert.equal(
178 String(input),
179 "https://pair-test.tail.ts.net/.well-known/t3/environment",
180 );
181 return serving
182 ? Response.json(testDescriptor)
183 : new Response(null, { status: 503 });
184 }),
185 ),
186 );
187
188 expect(serving).toBe(true);
189 assert.include(output, "Pairing URL: https://pair-test.tail.ts.net/pair#token=");
190 }),
191 "::1",
192 ).pipe(Effect.provide(NodeServices.layer)),
193 );
194
195 it.effect("mints a token and prints a QR pairing URL for a live server", () =>
196 withDescriptorServer((origin) =>
197 Effect.gen(function* () {
198 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
199 const port = Number(new URL(origin).port);
200 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
201 yield* persistServerRuntimeState({
202 path: statePath,
203 state: yield* makePersistedServerRuntimeState({
204 config: { host: "127.0.0.1", devUrl: undefined },
205 port,
206 }),
207 });
208
209 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
210
211 assert.include(output, `Pairing with pair-test (${origin})`);
212 assert.include(output, `Pairing URL: ${origin}/pair#token=`);
213 assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
214 assert.include(output, "only reachable from this machine");
215
216 const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
217 assert.isString(token);
218 assert.include(output, `App link: ${buildPairingAppLink(`${origin}/pair#token=${token}`)}`);
219
220 const listed = yield* captureStdout(
221 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
222 );
223 const credentials = JSON.parse(listed) as ReadonlyArray<{
224 readonly label?: string;
225 readonly scopes: ReadonlyArray<string>;
226 }>;
227 assert.equal(credentials.length, 1);
228 assert.equal(credentials[0]?.label, "t3 pair");
229 assert.deepEqual(credentials[0]?.scopes, AuthStandardClientScopes);
230 }),
231 ).pipe(
232 Effect.provide(NodeServices.layer),
233 Effect.provideService(HostProcess.Environment, {
234 ...process.env,
235 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
236 protocol: SERVICE_LAUNCHER_PROTOCOL,
237 childVersion: packageJson.version,
238 }),
239 }),
240 Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, {
241 connected: false,
242 send: () => false,
243 on: () => undefined,
244 off: () => undefined,
245 }),
246 ),
247 );
248
249 it.effect("pairs through the recorded dev web URL for dev servers", () =>
250 withDescriptorServer((origin) =>
251 Effect.gen(function* () {
252 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
253 const port = Number(new URL(origin).port);
254 const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
255 yield* persistServerRuntimeState({
256 path: statePath,
257 state: yield* makePersistedServerRuntimeState({
258 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
259 port,
260 }),
261 });
262
263 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
264
265 assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
266 }),
267 ).pipe(Effect.provide(NodeServices.layer)),
268 );
269
270 it.effect("refuses --tailscale before turning on Serve when the policy keeps clients local", () =>
271 withDescriptorServer((origin) =>
272 Effect.gen(function* () {
273 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-policy-test-"));
274 const policyPath = NodePath.join(baseDir, "policy.json");
275 NodeFS.writeFileSync(
276 policyPath,
277 JSON.stringify({
278 schemaVersion: 1,
279 organization: "Example Corp",
280 limits: { clients: ["desktop", "local-browser"] },
281 }),
282 );
283 yield* persistServerRuntimeState({
284 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
285 state: yield* makePersistedServerRuntimeState({
286 config: { host: "127.0.0.1", devUrl: undefined },
287 port: Number(new URL(origin).port),
288 }),
289 });
290
291 const error = yield* provideCliTestLayers(
292 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
293 Effect.provideService(
294 ChildProcessSpawner.ChildProcessSpawner,
295 ChildProcessSpawner.make(() => Effect.die("tailscale must not run")),
296 ),
297 Effect.provide(
298 ConfigProvider.layer(
299 ConfigProvider.fromEnv({ env: { T3CODE_DEV_MANAGED_POLICY_PATH: policyPath } }),
300 ),
301 ),
302 Effect.flip,
303 ),
304 );
305
306 assert.include(
307 String(error),
308 "Example Corp's policy does not allow remote clients, so Tailscale Serve cannot be turned on.",
309 );
310 }),
311 ).pipe(Effect.provide(NodeServices.layer)),
312 );
313
314 it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
315 withDescriptorServer((origin) =>
316 Effect.gen(function* () {
317 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-pid-test-"));
318 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
319 const state = yield* makePersistedServerRuntimeState({
320 config: { host: "127.0.0.1", devUrl: undefined },
321 port: Number(new URL(origin).port),
322 });
323 yield* persistServerRuntimeState({
324 path: statePath,
325 state: { ...state, pid: 4_194_305 },
326 });
327
328 const error = yield* provideCliTestLayers(
329 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
330 );
331
332 const rendered = String(
333 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
334 );
335 assert.include(rendered, "No running T3 Code server found.");
336 }),
337 ).pipe(Effect.provide(NodeServices.layer)),
338 );
339
340 // regression: #10516 minting opens the target database with this checkout's
341 // migrations, so a worktree must never fall back to the live install.
342 it.effect("does not fall back to the shared home from a linked worktree", () =>
343 withDescriptorServer((origin) =>
344 Effect.gen(function* () {
345 const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-worktree-test-"));
346 const worktree = NodePath.join(root, "worktree");
347 NodeFS.mkdirSync(worktree);
348 NodeFS.writeFileSync(
349 NodePath.join(worktree, ".git"),
350 `gitdir: ${NodePath.join(root, "repo", ".git", "worktrees", "worktree")}\n`,
351 );
352 const sharedHome = NodePath.join(root, "shared");
353 yield* persistServerRuntimeState({
354 path: NodePath.join(sharedHome, "userdata", "server-runtime.json"),
355 state: yield* makePersistedServerRuntimeState({
356 config: { host: "127.0.0.1", devUrl: undefined },
357 port: Number(new URL(origin).port),
358 }),
359 });
360
361 const error = yield* provideCliTestLayers(
362 runCli(["pair"]).pipe(
363 Effect.provideService(HostProcess.WorkingDirectory, worktree),
364 Effect.provide(
365 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_HOME: sharedHome } })),
366 ),
367 Effect.flip,
368 ),
369 );
370
371 assert.include(String(error), "No running T3 Code server found.");
372 assert.notInclude(String(error), sharedHome);
373 assert.deepEqual(NodeFS.readdirSync(NodePath.join(sharedHome, "userdata")), [
374 "server-runtime.json",
375 ]);
376 }),
377 ).pipe(Effect.provide(NodeServices.layer)),
378 );
379
380 // regression: #15492 an older CLI minted into a V1 database the protocol 2
381 // server never reads, so pairing must refuse before opening the database.
382 it.effect("rejects a server on another protocol before opening its database", () =>
383 withDescriptorServer(
384 (origin) =>
385 Effect.gen(function* () {
386 const baseDir = NodeFS.mkdtempSync(
387 NodePath.join(NodeOS.tmpdir(), "t3-pair-protocol-test-"),
388 );
389 yield* persistServerRuntimeState({
390 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
391 state: yield* makePersistedServerRuntimeState({
392 config: { host: "127.0.0.1", devUrl: undefined },
393 port: Number(new URL(origin).port),
394 }),
395 });
396
397 const exit = yield* provideCliTestLayers(
398 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.exit),
399 );
400
401 assert.deepEqual(NodeFS.readdirSync(NodePath.join(baseDir, "userdata")), [
402 "server-runtime.json",
403 ]);
404 assert.isTrue(Exit.isFailure(exit));
405 if (Exit.isFailure(exit)) {
406 assert.include(String(Cause.squash(exit.cause)), "t3@0.0.45 pair");
407 }
408 }),
409 "127.0.0.1",
410 { ...testDescriptor, serverVersion: "0.0.45", orchestrationProtocolVersion: 1 },
411 ).pipe(Effect.provide(NodeServices.layer)),
412 );
413
414 // Without the capability `tailscale serve` blocks on an enablement URL, so
415 // pairing must stop at status instead of spawning it.
416 it.effect("explains a tailnet without HTTPS serve instead of running tailscale serve", () =>
417 withDescriptorServer((origin) =>
418 Effect.gen(function* () {
419 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-test-"));
420 yield* persistServerRuntimeState({
421 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
422 state: yield* makePersistedServerRuntimeState({
423 config: { host: "127.0.0.1", devUrl: undefined },
424 port: Number(new URL(origin).port),
425 }),
426 });
427 const tailscaleCalls: Array<ReadonlyArray<string>> = [];
428 const spawner = ChildProcessSpawner.make((command) => {
429 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
430 tailscaleCalls.push(args);
431 const stdout =
432 args[0] === "status"
433 ? `{"Self":{"DNSName":"pair-test.invalid.","CapMap":{"funnel":null}}}`
434 : "";
435 return Effect.succeed(
436 ChildProcessSpawner.makeHandle({
437 pid: ChildProcessSpawner.ProcessId(1),
438 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(args[0] === "status" ? 0 : 1)),
439 isRunning: Effect.succeed(false),
440 kill: () => Effect.void,
441 unref: Effect.succeed(Effect.void),
442 stdin: Sink.drain,
443 stdout: Stream.make(new TextEncoder().encode(stdout)),
444 stderr: Stream.empty,
445 all: Stream.empty,
446 getInputFd: () => Sink.drain,
447 getOutputFd: () => Stream.empty,
448 }),
449 );
450 });
451
452 const error = yield* provideCliTestLayers(
453 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
454 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
455 Effect.flip,
456 ),
457 );
458
459 assert.include(String(error), "Tailscale Serve is not enabled on your tailnet.");
460 assert.include(String(error), "https://login.tailscale.com/admin/dns");
461 assert.deepEqual(tailscaleCalls, [["status", "--json"]]);
462 }),
463 ).pipe(Effect.provide(NodeServices.layer)),
464 );
465});
466
467describe("auth scope options", () => {
468 it.effect.each([
469 { group: "pairing", action: "create" },
470 { group: "session", action: "issue" },
471 ] as const)(
472 "issues and persists only the selected scopes for auth $group $action",
473 ({ group, action }) =>
474 Effect.gen(function* () {
475 const baseDir = NodeFS.mkdtempSync(
476 NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-scopes-test-"),
477 );
478 const output = yield* captureStdout(
479 runCli([
480 "auth",
481 group,
482 action,
483 "--base-dir",
484 baseDir,
485 "--json",
486 "--scope",
487 "orchestration:read",
488 "--scope",
489 "access:read",
490 "--scope",
491 "orchestration:read",
492 ]),
493 );
494 const issued = JSON.parse(output) as { readonly scopes: ReadonlyArray<string> };
495 const listOutput = yield* captureStdout(
496 runCli(["auth", group, "list", "--base-dir", baseDir, "--json"]),
497 );
498 const listed = JSON.parse(listOutput) as ReadonlyArray<{
499 readonly scopes: ReadonlyArray<string>;
500 }>;
501
502 assert.deepEqual(issued.scopes, ["orchestration:read", "access:read"]);
503 assert.lengthOf(listed, 1);
504 assert.deepEqual(listed[0]?.scopes, issued.scopes);
505 }),
506 );
507
508 it.effect.each(
509 [["pair"], ["auth", "pairing", "create"], ["auth", "session", "issue"]].map((command) => ({
510 command,
511 label: command.join(" "),
512 })),
513 )("rejects invalid scopes before running $label", ({ command }) =>
514 Effect.gen(function* () {
515 const error = yield* runCli([
516 ...command,
517 "--scope",
518 "orchestration:read",
519 "--scope",
520 "admin",
521 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
522
523 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
524 assert.fail(`Expected ShowHelp, got ${String(error)}`);
525 }
526 assert.deepEqual(error.commandPath, ["t3", ...command]);
527 const scopeError = error.errors[0];
528 if (scopeError?._tag !== "InvalidValue") {
529 assert.fail(`Expected InvalidValue, got ${String(scopeError?._tag)}`);
530 }
531 assert.equal(scopeError.option, "scope");
532 assert.equal(scopeError.value, "admin");
533 }),
534 );
535});
536
537describe("auth pairing create --base-url", () => {
538 it.effect.each(["192.168.1.5:3773", "localhost:3773", "ftp://localhost:3773"])(
539 "rejects %s before issuing a token",
540 (baseUrl) =>
541 Effect.gen(function* () {
542 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-base-url-test-"));
543 const error = yield* runCli([
544 "auth",
545 "pairing",
546 "create",
547 "--base-dir",
548 baseDir,
549 "--base-url",
550 baseUrl,
551 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
552
553 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
554 assert.fail(`Expected ShowHelp, got ${String(error)}`);
555 }
556 const flagError = error.errors[0];
557 if (flagError?._tag !== "InvalidValue") {
558 assert.fail(`Expected InvalidValue, got ${String(flagError?._tag)}`);
559 }
560 assert.equal(flagError.option, "base-url");
561 assert.equal(flagError.value, baseUrl);
562
563 const listOutput = yield* captureStdout(
564 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
565 );
566 assert.deepEqual(JSON.parse(listOutput), []);
567 }),
568 );
569
570 it.effect.each(["http://192.168.1.5:3773", "https://example.com", "http:localhost:3773"])(
571 "prints a pair URL for %s",
572 (baseUrl) =>
573 Effect.gen(function* () {
574 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-base-url-test-"));
575 const output = yield* captureStdout(
576 runCli([
577 "auth",
578 "pairing",
579 "create",
580 "--base-dir",
581 baseDir,
582 "--base-url",
583 baseUrl,
584 "--json",
585 ]),
586 );
587 const issued = JSON.parse(output) as {
588 readonly credential: string;
589 readonly pairUrl: string;
590 };
591
592 assert.equal(issued.pairUrl, `${new URL(baseUrl).origin}/pair#token=${issued.credential}`);
593 }),
594 );
595});
596
597describe("scripted auth output", () => {
598 it.effect.each(
599 [
600 ["auth", "session", "issue", "--token-only"],
601 ["auth", "session", "list", "--json"],
602 ["auth", "pairing", "list", "--json"],
603 ].map((command) => ({ command, label: command.join(" ") })),
604 )("prints only the result for $label after removing an abandoned upload", ({ command }) =>
605 Effect.gen(function* () {
606 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-quiet-test-"));
607 const attachmentsDir = NodePath.join(baseDir, "userdata", "attachments");
608 NodeFS.mkdirSync(attachmentsDir, { recursive: true });
609 // An abandoned upload makes config resolution log that it removed it.
610 const abandoned = NodePath.join(attachmentsDir, "abandoned.part");
611 NodeFS.writeFileSync(abandoned, "");
612 const jan2020Seconds = 1_577_836_800;
613 NodeFS.utimesSync(abandoned, jan2020Seconds, jan2020Seconds);
614 // The sweep reads Clock, so a week past the upload's mtime makes it expired.
615 yield* TestClock.setTime((jan2020Seconds + 7 * 24 * 60 * 60) * 1000);
616
617 const lines = yield* provideCliTestLayers(
618 Effect.gen(function* () {
619 yield* runCli([...command, "--base-dir", baseDir]);
620 return yield* TestConsole.logLines;
621 }),
622 );
623
624 assert.isFalse(NodeFS.existsSync(abandoned));
625 assert.lengthOf(lines, 1);
626 const output = String(lines[0]);
627 if (command.includes("--json")) {
628 assert.deepEqual(JSON.parse(output), []);
629 } else {
630 assert.match(output.trim(), /^[\w-]+\.[\w-]+/);
631 }
632 }),
633 );
634});