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

thread.test.ts

743 lines25.7 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import { AuthSessionId, ProjectId, RunId, ThreadId } from "@t3tools/contracts";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as NetService from "@t3tools/shared/Net";
7import * as ConfigProvider from "effect/ConfigProvider";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16import * as TestClock from "effect/testing/TestClock";
17import * as TestConsole from "effect/testing/TestConsole";
18import { Command } from "effect/cli";
19import { vi } from "vite-plus/test";
20​
21import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts";
22import {
23 makePersistedServerRuntimeState,
24 persistServerRuntimeState,
25} from "../serverRuntimeState.ts";
26import {
27 latestRunError,
28 launchModelSelection,
29 readLatestMessages,
30 resolveProject,
31 threadCommand,
32 type ThreadTools,
33 titleFromMessage,
34 waitForRun,
35} from "./thread.ts";
36​
37vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => {
38 const actual = await importOriginal<typeof import("../auth/EnvironmentAuth.ts")>();
39 return {
40 ...actual,
41 layerRuntime: Layer.mock(actual.EnvironmentAuth)({
42 issueMcpClientSession: () =>
43 Effect.map(DateTime.now, (expiresAt) => ({
44 sessionId: AuthSessionId.make("test-session"),
45 token: "synthetic-token",
46 expiresAt,
47 })),
48 revokeSession: () => Effect.succeed(true),
49 }),
50 };
51});
52​
53const threadId = ThreadId.make("thread-1");
54const runId = RunId.make("run-1");
55​
56it.effect("list includes delegated threads across pages and still leaves out subagents", () =>
57 Effect.gen(function* () {
58 const fs = yield* FileSystem.FileSystem;
59 const path = yield* Path.Path;
60 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-list-" });
61 yield* persistServerRuntimeState({
62 path: path.join(baseDir, "userdata", "server-runtime.json"),
63 state: yield* makePersistedServerRuntimeState({
64 config: { host: "127.0.0.1", devUrl: undefined },
65 port: 3_773,
66 }),
67 });
68 const projectId = ProjectId.make("project-1");
69 const item = (id: string) => ({
70 threadId: id,
71 projectId,
72 title: id,
73 createdBy: "user",
74 creationSource: "web",
75 status: "idle",
76 latestRunId: null,
77 providerInstanceId: "codex",
78 model: "test",
79 runtimeMode: "full-access",
80 interactionMode: "default",
81 linkedPullRequest: null,
82 settled: false,
83 settledAt: null,
84 snoozed: false,
85 snoozedUntil: null,
86 parentThreadId: null,
87 relationshipToParent: null,
88 itemCount: 0,
89 createdAt: "2026-01-01T00:00:00.000Z",
90 updatedAt: "2026-01-01T00:00:00.000Z",
91 });
92 const root = item("root");
93 const delegated = {
94 ...item("delegated"),
95 delegatedFrom: { environmentId: "env-1", threadId: "remote", title: "Remote" },
96 };
97 const subagent = { ...item("child"), parentThreadId: "root", relationshipToParent: "subagent" };
98 using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue(
99 Effect.succeed({
100 call: (tool, args) => {
101 if (tool === "t3_project_list")
102 return Effect.succeed({
103 structuredContent: {
104 projects: [{ id: projectId, title: "Project", workspaceRoot: baseDir }],
105 nextCursor: null,
106 },
107 });
108 if (tool === "t3_thread_list") {
109 const all = args.includeSubagents ? [root, subagent, delegated] : [root];
110 const cursor = Number(args.cursor);
111 return Effect.succeed({
112 structuredContent: {
113 projectId,
114 currentThreadId: null,
115 threads: all.slice(cursor, cursor + 2),
116 nextCursor: cursor + 2 < all.length ? cursor + 2 : null,
117 total: all.length,
118 },
119 });
120 }
121 return Effect.die(`unexpected ${tool} call`);
122 },
123 }),
124 );
125 yield* Command.runWith(threadCommand, { version: "0.0.0" })([
126 "list",
127 "--project",
128 projectId,
129 "--json",
130 "--base-dir",
131 baseDir,
132 ]);
133 const listed = JSON.parse(String((yield* TestConsole.logLines).at(-1))) as Array<{
134 threadId: string;
135 }>;
136 assert.deepStrictEqual(
137 listed.map((entry) => entry.threadId),
138 ["root", "delegated"],
139 );
140 }).pipe(
141 Effect.scoped,
142 Effect.provide(
143 Layer.mergeAll(
144 NodeServices.layer,
145 NodeCrypto.layer,
146 NetService.layer,
147 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
148 ),
149 ),
150 ),
151);
152​
153it.effect(
154 "start resolves home-relative project paths while preserving ids and relative paths",
155 () =>
156 Effect.gen(function* () {
157 const fs = yield* FileSystem.FileSystem;
158 const path = yield* Path.Path;
159 const root = yield* fs
160 .makeTempDirectoryScoped({ prefix: "t3-thread-project-path-" })
161 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
162 const home = path.join(root, "home");
163 const cwd = path.join(root, "current");
164 const workspaceRoot = path.join(home, "My Project");
165 const nestedRoot = path.join(workspaceRoot, "nested");
166 const baseDir = path.join(root, "state");
167 yield* fs.makeDirectory(nestedRoot, { recursive: true });
168 yield* fs.makeDirectory(cwd);
169 const projects = [
170 { id: ProjectId.make("current-project"), title: "Current", workspaceRoot: cwd },
171 { id: ProjectId.make("home-project"), title: "Home", workspaceRoot: home },
172 { id: ProjectId.make("intended-project"), title: "Intended", workspaceRoot },
173 { id: ProjectId.make("nested-project"), title: "Nested", workspaceRoot: nestedRoot },
174 { id: ProjectId.make("~/literal-id"), title: "Exact id", workspaceRoot: cwd },
175 ];
176 yield* persistServerRuntimeState({
177 path: path.join(baseDir, "userdata", "server-runtime.json"),
178 state: yield* makePersistedServerRuntimeState({
179 config: { host: "127.0.0.1", devUrl: undefined },
180 port: 3_773,
181 }),
182 });
183 using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue(
184 Effect.succeed({
185 call: (tool, args) => {
186 switch (tool) {
187 case "t3_project_list":
188 return Effect.succeed({ structuredContent: { projects, nextCursor: null } });
189 case "t3_thread_launch":
190 return Effect.succeed({
191 structuredContent: { threadId, projectId: args.projectId, runId: null },
192 });
193 default:
194 return Effect.die(`unexpected ${tool} call`);
195 }
196 },
197 }),
198 );
199​
200 for (const [identifier, expectedProjectId] of [
201 ["intended-project", "intended-project"],
202 ["~/literal-id", "~/literal-id"],
203 [workspaceRoot, "intended-project"],
204 [path.relative(cwd, workspaceRoot), "intended-project"],
205 [".", "current-project"],
206 ["~/My Project", "intended-project"],
207 ["~", "home-project"],
208 ["~/My Project/nested", "nested-project"],
209 ["~/My Project/missing", "intended-project"],
210 ] as const) {
211 yield* Command.runWith(threadCommand, { version: "0.0.0" })([
212 "start",
213 identifier,
214 "Inspect this project",
215 "--json",
216 "--base-dir",
217 baseDir,
218 ]).pipe(
219 Effect.provideService(HostProcess.HomeDirectory, home),
220 Effect.provideService(HostProcess.WorkingDirectory, cwd),
221 );
222 assert.strictEqual(
223 (yield* TestConsole.logLines).at(-1),
224 JSON.stringify({ threadId, projectId: expectedProjectId, runId: null }),
225 identifier,
226 );
227 }
228 }).pipe(
229 Effect.scoped,
230 Effect.provide(
231 Layer.mergeAll(
232 NodeServices.layer,
233 NodeCrypto.layer,
234 NetService.layer,
235 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
236 ),
237 ),
238 ),
239);
240​
241it.effect("does not sign in to whatever took over a dead server's port", () =>
242 Effect.gen(function* () {
243 const fs = yield* FileSystem.FileSystem;
244 const path = yield* Path.Path;
245 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-dead-server-" });
246 const state = yield* makePersistedServerRuntimeState({
247 config: { host: "127.0.0.1", devUrl: undefined },
248 port: 3_773,
249 });
250 yield* persistServerRuntimeState({
251 path: path.join(baseDir, "userdata", "server-runtime.json"),
252 // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
253 state: { ...state, pid: 4_194_305 },
254 });
255 using session = vi
256 .spyOn(McpBridge, "mcpToolSession")
257 .mockReturnValue(Effect.die("no session should open"));
258​
259 const error = yield* Command.runWith(threadCommand, { version: "0.0.0" })([
260 "list",
261 "--base-dir",
262 baseDir,
263 ]).pipe(Effect.flip);
264​
265 assert.strictEqual(error._tag, "ThreadServerNotRunningError");
266 assert.strictEqual(session.mock.calls.length, 0);
267 }).pipe(
268 Effect.scoped,
269 Effect.provide(
270 Layer.mergeAll(
271 NodeServices.layer,
272 NodeCrypto.layer,
273 NetService.layer,
274 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
275 ),
276 ),
277 ),
278);
279​
280/** Answers each tool call with the next scripted response for that tool. */
281const scriptedTools = (script: Record<string, Array<unknown>>) => {
282 const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];
283 const call = ((tool: string, args: unknown) => {
284 calls.push({ tool, args });
285 const next = script[tool]?.shift();
286 return next === undefined ? Effect.die(`unscripted ${tool} call`) : Effect.succeed(next);
287 }) as ThreadTools["call"];
288 return { tools: { call } satisfies ThreadTools, calls };
289};
290​
291it.effect("--wait follows the sent run to its continuation's terminal status", () =>
292 Effect.gen(function* () {
293 const continuation = RunId.make("run-2");
294 const { tools, calls } = scriptedTools({
295 t3_thread_wait: [
296 { threadId, runId, status: "running", timedOut: true },
297 { threadId, runId: continuation, status: "failed", timedOut: false },
298 ],
299 t3_thread_read: [{ thread: { pendingRequestCount: 0 } }],
300 });
301​
302 const outcome = yield* waitForRun(tools, threadId, runId);
303​
304 assert.deepStrictEqual(outcome, { type: "ended", runId: continuation, status: "failed" });
305 assert.deepStrictEqual(
306 calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
307 [
308 { threadId, runId, timeoutMs: 15_000 },
309 { threadId, runId, timeoutMs: 15_000 },
310 ],
311 );
312 }),
313);
314​
315/** The reads that ask whether a run after `runId` holds a message someone sent. */
316const laterRunReads = (
317 laterRun: RunId,
318 items: ReadonlyArray<{ readonly runId: RunId; readonly type: string }>,
319) => [
320 {
321 recentRuns: [
322 { runId, ordinal: 1 },
323 { runId: laterRun, ordinal: 2 },
324 ],
325 },
326 { thread: {}, items, nextPosition: null, hasMore: false },
327];
328​
329it.effect("--wait lasts until background work the agent waits on wakes it and that run ends", () =>
330 Effect.gen(function* () {
331 const wakeRun = RunId.make("run-2");
332 const { tools, calls } = scriptedTools({
333 t3_thread_wait: [
334 { threadId, runId, status: "completed", timedOut: false },
335 {
336 threadId,
337 runId,
338 status: "completed",
339 timedOut: false,
340 resultRun: { runId: wakeRun, status: "completed" },
341 // The wake run submits the result the first run owes, which the server stores there.
342 output: { head: "abc" },
343 },
344 ],
345 // The wake run starts from a notification, which the messages view leaves out.
346 t3_thread_read: laterRunReads(wakeRun, []),
347 });
348​
349 const outcome = yield* waitForRun(tools, threadId, runId, true);
350​
351 assert.deepStrictEqual(
352 calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
353 [
354 { threadId, runId, timeoutMs: 15_000 },
355 { threadId, runId, timeoutMs: 15_000, untilDelegatedWorkSettled: true },
356 ],
357 );
358 assert.deepStrictEqual(outcome, {
359 type: "ended",
360 runId: wakeRun,
361 status: "completed",
362 output: { head: "abc" },
363 });
364 }),
365);
366​
367it.effect(
368 "--wait waits out the moment between background work ending and its wake run starting",
369 () =>
370 Effect.gen(function* () {
371 const wakeRun = RunId.make("run-2");
372 const ownOnly = { recentRuns: [{ runId, ordinal: 1, status: "completed" }] };
373 const withWake = (status: string) => [
374 {
375 recentRuns: [
376 { runId, ordinal: 1, status: "completed" },
377 { runId: wakeRun, ordinal: 2, status },
378 ],
379 },
380 { thread: {}, items: [], nextPosition: null, hasMore: false },
381 ];
382 const { tools } = scriptedTools({
383 t3_thread_wait: [
384 { threadId, runId, status: "completed", timedOut: false },
385 { threadId, runId, status: "completed", timedOut: true },
386 // The work ended, and the run it wakes is not recorded yet.
387 {
388 threadId,
389 runId,
390 status: "completed",
391 timedOut: false,
392 resultRun: { runId, status: "completed" },
393 },
394 {
395 threadId,
396 runId,
397 status: "completed",
398 timedOut: false,
399 resultRun: { runId: wakeRun, status: "completed" },
400 },
401 ],
402 t3_thread_read: [
403 ownOnly,
404 { thread: { pendingRequestCount: 0 } },
405 ownOnly,
406 ...withWake("running"),
407 ...withWake("completed"),
408 ],
409 });
410​
411 const fiber = yield* Effect.forkChild(waitForRun(tools, threadId, runId, true));
412 yield* TestClock.adjust("500 millis");
413​
414 assert.deepStrictEqual(yield* Fiber.join(fiber), {
415 type: "ended",
416 runId: wakeRun,
417 status: "completed",
418 });
419 }),
420);
421​
422it.effect(
423 "--wait keeps its own run's result when another client's later run settles the thread",
424 () =>
425 Effect.gen(function* () {
426 const sentRun = RunId.make("run-2");
427 const { tools } = scriptedTools({
428 t3_thread_wait: [
429 { threadId, runId, status: "completed", timedOut: false },
430 {
431 threadId,
432 runId,
433 status: "completed",
434 timedOut: false,
435 resultRun: { runId: sentRun, status: "failed" },
436 output: { head: "abc" },
437 },
438 ],
439 t3_thread_read: laterRunReads(sentRun, [{ runId: sentRun, type: "user_message" }]),
440 });
441​
442 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId, true), {
443 type: "ended",
444 runId,
445 status: "completed",
446 output: { head: "abc" },
447 });
448 }),
449);
450​
451it.effect("--wait stops when the thread waits for an answer instead of polling forever", () =>
452 Effect.gen(function* () {
453 const { tools } = scriptedTools({
454 t3_thread_wait: [
455 { threadId, runId, status: "queued", timedOut: true },
456 { threadId, runId, status: "queued", timedOut: true },
457 ],
458 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
459 });
460​
461 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), { type: "needs_input" });
462 }),
463);
464​
465it.effect("--wait reports its run's result when a later run is the one waiting", () =>
466 Effect.gen(function* () {
467 const { tools } = scriptedTools({
468 t3_thread_wait: [
469 { threadId, runId, status: "running", timedOut: true },
470 { threadId, runId, status: "completed", timedOut: false },
471 ],
472 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
473 });
474​
475 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), {
476 type: "ended",
477 runId,
478 status: "completed",
479 });
480 }),
481);
482​
483it.effect("start sends each --option as a typed model option", () =>
484 Effect.gen(function* () {
485 const selection = yield* launchModelSelection({
486 provider: Option.some("codex"),
487 model: Option.some("gpt-6.1-sol"),
488 option: ["reasoningEffort=high", " fastMode = false ", "note=a=b"],
489 });
490​
491 assert.deepStrictEqual(selection, {
492 instanceId: "codex",
493 model: "gpt-6.1-sol",
494 options: [
495 { id: "reasoningEffort", value: "high" },
496 { id: "fastMode", value: false },
497 { id: "note", value: "a=b" },
498 ],
499 });
500 }),
501);
502​
503it.effect("start rejects a repeated --option before reaching the server", () =>
504 Effect.gen(function* () {
505 const error = yield* Command.runWith(threadCommand, { version: "0.0.0" })([
506 "start",
507 ".",
508 "hi",
509 "--provider",
510 "codex",
511 "--model",
512 "gpt-6.1-sol",
513 "--option",
514 "reasoningEffort=high",
515 "--option",
516 "reasoningEffort=low",
517 ]).pipe(Effect.flip);
518​
519 assert.strictEqual(error.message, "--option reasoningEffort is given more than once.");
520 }).pipe(
521 Effect.provide(
522 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
523 ),
524 ),
525);
526​
527/** Serves t3_thread_read pages the way the server does: positions count every item. */
528const timelineTools = (types: ReadonlyArray<string>) => {
529 const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type }));
530 const served: Array<number> = [];
531 const call = ((_tool: string, input: unknown) => {
532 const args = input as { readonly afterPosition?: number; readonly limit: number };
533 // Scanning one match past the page keeps reads of huge fixtures linear.
534 const matching: typeof items = [];
535 for (let position = (args.afterPosition ?? -1) + 1; position < items.length; position++) {
536 const item = items[position]!;
537 if (["user_message", "assistant_message", "proposed_plan"].includes(item.type)) {
538 matching.push(item);
539 if (matching.length > args.limit) break;
540 }
541 }
542 const page = matching.slice(0, args.limit);
543 served.push(page.length);
544 return Effect.succeed({
545 thread: { itemCount: items.length },
546 items: page,
547 nextPosition: page.at(-1)?.position ?? null,
548 hasMore: matching.length > page.length,
549 });
550 }) as ThreadTools["call"];
551 const latest = (count: number) =>
552 items
553 .filter((item) => item.type === "user_message" || item.type === "assistant_message")
554 .slice(-count)
555 .map((item) => item.itemId);
556 return { tools: { call } satisfies ThreadTools, served, latest };
557};
558​
559const tail = (tools: number) => [...Array<string>(tools).fill("tool_call"), "assistant_message"];
560​
561it.effect("show retains pull request metadata when reading a later message window", () =>
562 Effect.gen(function* () {
563 const link = {
564 host: "github.com",
565 repository: "owner/repo",
566 number: 1,
567 url: "https://github.com/owner/repo/pull/1",
568 source: "manual",
569 state: "open",
570 watching: false,
571 watchStartedAt: null,
572 } as const;
573 const call = ((_tool: string, input: unknown) => {
574 const args = input as { afterPosition?: number; limit: number };
575 const first = args.afterPosition === undefined && args.limit === 1;
576 return Effect.succeed({
577 thread: {
578 itemCount: 200,
579 status: first ? "running" : "completed",
580 pullRequestCount: 1,
581 ...(first ? { pullRequests: [link], openPullRequestCount: 1 } : {}),
582 },
583 items: first ? [] : [{ position: 199, itemId: "message", type: "assistant_message" }],
584 nextPosition: 199,
585 hasMore: false,
586 });
587 }) as ThreadTools["call"];
588 const { thread } = yield* readLatestMessages({ call }, threadId, 1);
589 assert.strictEqual(thread.status, "completed");
590 assert.deepStrictEqual(thread.pullRequests, [link]);
591 assert.strictEqual(thread.openPullRequestCount, 1);
592 }),
593);
594​
595it.effect("show reads the end of a long thread, not its whole history", () =>
596 Effect.gen(function* () {
597 const { tools, served, latest } = timelineTools([
598 ...Array.from({ length: 1000 }, (_, index) =>
599 index % 2 === 0 ? "user_message" : "assistant_message",
600 ),
601 ...Array.from({ length: 10 }, () => tail(30)).flat(),
602 "proposed_plan",
603 ]);
604​
605 const { messages } = yield* readLatestMessages(tools, threadId, 10);
606​
607 assert.deepStrictEqual(
608 messages.map((item) => item.itemId),
609 latest(10),
610 );
611 assert.isBelow(
612 served.reduce((sum, count) => sum + count, 0),
613 100,
614 );
615 }),
616);
617​
618it.effect("show widens back to the first item when the thread has fewer messages", () =>
619 Effect.gen(function* () {
620 const { tools, latest } = timelineTools([
621 "user_message",
622 ...Array.from({ length: 4 }, () => tail(150)).flat(),
623 ]);
624​
625 const { messages } = yield* readLatestMessages(tools, threadId, 10);
626​
627 assert.deepStrictEqual(
628 messages.map((item) => item.itemId),
629 latest(10),
630 );
631 assert.lengthOf(messages, 5);
632 }),
633);
634​
635it.effect("show returns a --messages count larger than one call can spread", () =>
636 Effect.gen(function* () {
637 const { tools, latest } = timelineTools(Array<string>(200_000).fill("assistant_message"));
638​
639 const { messages } = yield* readLatestMessages(tools, threadId, 200_000);
640​
641 assert.deepStrictEqual(
642 messages.map((item) => item.itemId),
643 latest(200_000),
644 );
645 }),
646);
647​
648it.effect("show gives the latest run's last error only when that run did not complete", () =>
649 Effect.gen(function* () {
650 const page = {
651 thread: {},
652 items: [
653 { itemId: "item-0", runId: RunId.make("run-0"), type: "error", text: "earlier run" },
654 { itemId: "item-1", runId, type: "error", text: "first try" },
655 { itemId: "item-2", runId, type: "error", text: "Usage limit reached" },
656 ],
657 nextPosition: null,
658 hasMore: false,
659 };
660 const { tools, calls } = scriptedTools({ t3_thread_read: [page] });
661​
662 assert.strictEqual(
663 yield* latestRunError(tools, { threadId, status: "failed", latestRunId: runId }),
664 "Usage limit reached",
665 );
666 assert.deepInclude(calls[0]?.args, { view: "activity" });
667 for (const status of ["completed", "running", "queued", "idle"] as const) {
668 assert.isNull(yield* latestRunError(tools, { threadId, status, latestRunId: runId }), status);
669 }
670 assert.lengthOf(calls, 1);
671 }),
672);
673​
674it("titles from a long first line without splitting an emoji", () => {
675 const title = titleFromMessage(`${"a".repeat(78)}πŸ˜€ and the rest of a long first line`);
676 assert.strictEqual(title, `${"a".repeat(78)}…`);
677});
678​
679const git = Effect.fn("test.git")(function* (cwd: string, args: ReadonlyArray<string>) {
680 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
681 const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }));
682 assert.strictEqual(Number(exitCode), 0, `git ${args.join(" ")}`);
683});
684​
685const commitAll = (cwd: string) =>
686 Effect.andThen(
687 git(cwd, ["add", "."]),
688 git(cwd, [
689 "-c",
690 "user.name=Test",
691 "-c",
692 "user.email=test@example.test",
693 "commit",
694 "--quiet",
695 "-m",
696 "initial",
697 ]),
698 );
699​
700it.live("resolves a path inside a git worktree of the project's repository to that project", () =>
701 Effect.gen(function* () {
702 const fileSystem = yield* FileSystem.FileSystem;
703 const path = yield* Path.Path;
704 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-thread-worktree-" });
705 const repo = path.join(root, "sample");
706 const worktree = path.join(root, "worktrees", "sample", "t3-8ff64c24");
707 const feature = path.join(root, "wt", "feature");
708 const featureWorktree = path.join(root, "worktrees", "feature", "t3-1a2b3c4d");
709 yield* fileSystem.makeDirectory(path.join(repo, "pkg"), { recursive: true });
710 yield* fileSystem.writeFileString(path.join(repo, "pkg", "index.ts"), "export {};\n");
711 yield* git(repo, ["init", "--quiet", "-b", "main"]);
712 yield* commitAll(repo);
713 yield* git(repo, ["worktree", "add", "--quiet", "-b", "t3/8ff64c24", worktree]);
714 yield* git(repo, ["worktree", "add", "--quiet", "-b", "feature", feature]);
715 yield* git(feature, ["worktree", "add", "--quiet", "-b", "t3/1a2b3c4d", featureWorktree]);
716​
717 const project = (id: string, workspaceRoot: string) => ({
718 id: ProjectId.make(id),
719 title: path.basename(workspaceRoot),
720 workspaceRoot,
721 });
722 const sample = project("project-sample", repo);
723 const featureProject = project("project-feature", feature);
724 const resolveFrom = (
725 projects: ReadonlyArray<ReturnType<typeof project>>,
726 workingDirectory: string,
727 identifier = ".",
728 ) =>
729 resolveProject(
730 scriptedTools({ t3_project_list: [{ projects, nextCursor: null }] }).tools,
731 identifier,
732 ).pipe(Effect.provideService(HostProcess.WorkingDirectory, workingDirectory));
733​
734 assert.deepStrictEqual(yield* resolveFrom([sample], worktree), sample);
735 assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample);
736 assert.deepStrictEqual(yield* resolveFrom([sample], worktree, "pkg/index.ts"), sample);
737 assert.deepStrictEqual(yield* resolveFrom([featureProject], featureWorktree), featureProject);
738 const ambiguous = yield* Effect.flip(resolveFrom([sample, featureProject], featureWorktree));
739 assert.strictEqual(ambiguous._tag, "ThreadUsageError");
740 assert.include(ambiguous.message, "sample (project-sample)");
741 assert.include(ambiguous.message, "feature (project-feature)");
742 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
743);