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

thread.test.ts

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