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