Open History to see the last commit
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(
57 "start resolves home-relative project paths while preserving ids and relative paths",
58 () =>
59 Effect.gen(function* () {
60 const fs = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const root = yield* fs
63 .makeTempDirectoryScoped({ prefix: "t3-thread-project-path-" })
64 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
65 const home = path.join(root, "home");
66 const cwd = path.join(root, "current");
67 const workspaceRoot = path.join(home, "My Project");
68 const nestedRoot = path.join(workspaceRoot, "nested");
69 const baseDir = path.join(root, "state");
70 yield* fs.makeDirectory(nestedRoot, { recursive: true });
71 yield* fs.makeDirectory(cwd);
72 const projects = [
73 { id: ProjectId.make("current-project"), title: "Current", workspaceRoot: cwd },
74 { id: ProjectId.make("home-project"), title: "Home", workspaceRoot: home },
75 { id: ProjectId.make("intended-project"), title: "Intended", workspaceRoot },
76 { id: ProjectId.make("nested-project"), title: "Nested", workspaceRoot: nestedRoot },
77 { id: ProjectId.make("~/literal-id"), title: "Exact id", workspaceRoot: cwd },
78 ];
79 yield* persistServerRuntimeState({
80 path: path.join(baseDir, "userdata", "server-runtime.json"),
81 state: yield* makePersistedServerRuntimeState({
82 config: { host: "127.0.0.1", devUrl: undefined },
83 port: 3_773,
84 }),
85 });
86 using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue(
87 Effect.succeed({
88 call: (tool, args) => {
89 switch (tool) {
90 case "t3_project_list":
91 return Effect.succeed({ structuredContent: { projects, nextCursor: null } });
92 case "t3_thread_launch":
93 return Effect.succeed({
94 structuredContent: { threadId, projectId: args.projectId, runId: null },
95 });
96 default:
97 return Effect.die(`unexpected ${tool} call`);
98 }
99 },
100 }),
101 );
102β
103 for (const [identifier, expectedProjectId] of [
104 ["intended-project", "intended-project"],
105 ["~/literal-id", "~/literal-id"],
106 [workspaceRoot, "intended-project"],
107 [path.relative(cwd, workspaceRoot), "intended-project"],
108 [".", "current-project"],
109 ["~/My Project", "intended-project"],
110 ["~", "home-project"],
111 ["~/My Project/nested", "nested-project"],
112 ["~/My Project/missing", "intended-project"],
113 ] as const) {
114 yield* Command.runWith(threadCommand, { version: "0.0.0" })([
115 "start",
116 identifier,
117 "Inspect this project",
118 "--json",
119 "--base-dir",
120 baseDir,
121 ]).pipe(
122 Effect.provideService(HostProcess.HomeDirectory, home),
123 Effect.provideService(HostProcess.WorkingDirectory, cwd),
124 );
125 assert.strictEqual(
126 (yield* TestConsole.logLines).at(-1),
127 JSON.stringify({ threadId, projectId: expectedProjectId, runId: null }),
128 identifier,
129 );
130 }
131 }).pipe(
132 Effect.scoped,
133 Effect.provide(
134 Layer.mergeAll(
135 NodeServices.layer,
136 NodeCrypto.layer,
137 NetService.layer,
138 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
139 ),
140 ),
141 ),
142);
143β
144it.effect("does not sign in to whatever took over a dead server's port", () =>
145 Effect.gen(function* () {
146 const fs = yield* FileSystem.FileSystem;
147 const path = yield* Path.Path;
148 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-dead-server-" });
149 const state = yield* makePersistedServerRuntimeState({
150 config: { host: "127.0.0.1", devUrl: undefined },
151 port: 3_773,
152 });
153 yield* persistServerRuntimeState({
154 path: path.join(baseDir, "userdata", "server-runtime.json"),
155 // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
156 state: { ...state, pid: 4_194_305 },
157 });
158 using session = vi
159 .spyOn(McpBridge, "mcpToolSession")
160 .mockReturnValue(Effect.die("no session should open"));
161β
162 const error = yield* Command.runWith(threadCommand, { version: "0.0.0" })([
163 "list",
164 "--base-dir",
165 baseDir,
166 ]).pipe(Effect.flip);
167β
168 assert.strictEqual(error._tag, "ThreadServerNotRunningError");
169 assert.strictEqual(session.mock.calls.length, 0);
170 }).pipe(
171 Effect.scoped,
172 Effect.provide(
173 Layer.mergeAll(
174 NodeServices.layer,
175 NodeCrypto.layer,
176 NetService.layer,
177 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
178 ),
179 ),
180 ),
181);
182β
183/** Answers each tool call with the next scripted response for that tool. */
184const scriptedTools = (script: Record<string, Array<unknown>>) => {
185 const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];
186 const call = ((tool: string, args: unknown) => {
187 calls.push({ tool, args });
188 const next = script[tool]?.shift();
189 return next === undefined ? Effect.die(`unscripted ${tool} call`) : Effect.succeed(next);
190 }) as ThreadTools["call"];
191 return { tools: { call } satisfies ThreadTools, calls };
192};
193β
194it.effect("--wait follows the sent run to its continuation's terminal status", () =>
195 Effect.gen(function* () {
196 const continuation = RunId.make("run-2");
197 const { tools, calls } = scriptedTools({
198 t3_thread_wait: [
199 { threadId, runId, status: "running", timedOut: true },
200 { threadId, runId: continuation, status: "failed", timedOut: false },
201 ],
202 t3_thread_read: [{ thread: { pendingRequestCount: 0 } }],
203 });
204β
205 const outcome = yield* waitForRun(tools, threadId, runId);
206β
207 assert.deepStrictEqual(outcome, { type: "ended", runId: continuation, status: "failed" });
208 assert.deepStrictEqual(
209 calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
210 [
211 { threadId, runId, timeoutMs: 15_000 },
212 { threadId, runId, timeoutMs: 15_000 },
213 ],
214 );
215 }),
216);
217β
218/** The reads that ask whether a run after `runId` holds a message someone sent. */
219const laterRunReads = (
220 laterRun: RunId,
221 items: ReadonlyArray<{ readonly runId: RunId; readonly type: string }>,
222) => [
223 {
224 recentRuns: [
225 { runId, ordinal: 1 },
226 { runId: laterRun, ordinal: 2 },
227 ],
228 },
229 { thread: {}, items, nextPosition: null, hasMore: false },
230];
231β
232it.effect("--wait lasts until background work the agent waits on wakes it and that run ends", () =>
233 Effect.gen(function* () {
234 const wakeRun = RunId.make("run-2");
235 const { tools, calls } = scriptedTools({
236 t3_thread_wait: [
237 { threadId, runId, status: "completed", timedOut: false },
238 {
239 threadId,
240 runId,
241 status: "completed",
242 timedOut: false,
243 resultRun: { runId: wakeRun, status: "completed" },
244 // The wake run submits the result the first run owes, which the server stores there.
245 output: { head: "abc" },
246 },
247 ],
248 // The wake run starts from a notification, which the messages view leaves out.
249 t3_thread_read: laterRunReads(wakeRun, []),
250 });
251β
252 const outcome = yield* waitForRun(tools, threadId, runId, true);
253β
254 assert.deepStrictEqual(
255 calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
256 [
257 { threadId, runId, timeoutMs: 15_000 },
258 { threadId, runId, timeoutMs: 15_000, untilDelegatedWorkSettled: true },
259 ],
260 );
261 assert.deepStrictEqual(outcome, {
262 type: "ended",
263 runId: wakeRun,
264 status: "completed",
265 output: { head: "abc" },
266 });
267 }),
268);
269β
270it.effect(
271 "--wait waits out the moment between background work ending and its wake run starting",
272 () =>
273 Effect.gen(function* () {
274 const wakeRun = RunId.make("run-2");
275 const ownOnly = { recentRuns: [{ runId, ordinal: 1, status: "completed" }] };
276 const withWake = (status: string) => [
277 {
278 recentRuns: [
279 { runId, ordinal: 1, status: "completed" },
280 { runId: wakeRun, ordinal: 2, status },
281 ],
282 },
283 { thread: {}, items: [], nextPosition: null, hasMore: false },
284 ];
285 const { tools } = scriptedTools({
286 t3_thread_wait: [
287 { threadId, runId, status: "completed", timedOut: false },
288 { threadId, runId, status: "completed", timedOut: true },
289 // The work ended, and the run it wakes is not recorded yet.
290 {
291 threadId,
292 runId,
293 status: "completed",
294 timedOut: false,
295 resultRun: { runId, status: "completed" },
296 },
297 {
298 threadId,
299 runId,
300 status: "completed",
301 timedOut: false,
302 resultRun: { runId: wakeRun, status: "completed" },
303 },
304 ],
305 t3_thread_read: [
306 ownOnly,
307 { thread: { pendingRequestCount: 0 } },
308 ownOnly,
309 ...withWake("running"),
310 ...withWake("completed"),
311 ],
312 });
313β
314 const fiber = yield* Effect.forkChild(waitForRun(tools, threadId, runId, true));
315 yield* TestClock.adjust("500 millis");
316β
317 assert.deepStrictEqual(yield* Fiber.join(fiber), {
318 type: "ended",
319 runId: wakeRun,
320 status: "completed",
321 });
322 }),
323);
324β
325it.effect(
326 "--wait keeps its own run's result when another client's later run settles the thread",
327 () =>
328 Effect.gen(function* () {
329 const sentRun = RunId.make("run-2");
330 const { tools } = scriptedTools({
331 t3_thread_wait: [
332 { threadId, runId, status: "completed", timedOut: false },
333 {
334 threadId,
335 runId,
336 status: "completed",
337 timedOut: false,
338 resultRun: { runId: sentRun, status: "failed" },
339 output: { head: "abc" },
340 },
341 ],
342 t3_thread_read: laterRunReads(sentRun, [{ runId: sentRun, type: "user_message" }]),
343 });
344β
345 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId, true), {
346 type: "ended",
347 runId,
348 status: "completed",
349 output: { head: "abc" },
350 });
351 }),
352);
353β
354it.effect("--wait stops when the thread waits for an answer instead of polling forever", () =>
355 Effect.gen(function* () {
356 const { tools } = scriptedTools({
357 t3_thread_wait: [
358 { threadId, runId, status: "queued", timedOut: true },
359 { threadId, runId, status: "queued", timedOut: true },
360 ],
361 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
362 });
363β
364 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), { type: "needs_input" });
365 }),
366);
367β
368it.effect("--wait reports its run's result when a later run is the one waiting", () =>
369 Effect.gen(function* () {
370 const { tools } = scriptedTools({
371 t3_thread_wait: [
372 { threadId, runId, status: "running", timedOut: true },
373 { threadId, runId, status: "completed", timedOut: false },
374 ],
375 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
376 });
377β
378 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), {
379 type: "ended",
380 runId,
381 status: "completed",
382 });
383 }),
384);
385β
386it.effect("start sends each --option as a typed model option", () =>
387 Effect.gen(function* () {
388 const selection = yield* launchModelSelection({
389 provider: Option.some("codex"),
390 model: Option.some("gpt-6.1-sol"),
391 option: ["reasoningEffort=high", " fastMode = false ", "note=a=b"],
392 });
393β
394 assert.deepStrictEqual(selection, {
395 instanceId: "codex",
396 model: "gpt-6.1-sol",
397 options: [
398 { id: "reasoningEffort", value: "high" },
399 { id: "fastMode", value: false },
400 { id: "note", value: "a=b" },
401 ],
402 });
403 }),
404);
405β
406it.effect("start rejects a repeated --option before reaching the server", () =>
407 Effect.gen(function* () {
408 const error = yield* Command.runWith(threadCommand, { version: "0.0.0" })([
409 "start",
410 ".",
411 "hi",
412 "--provider",
413 "codex",
414 "--model",
415 "gpt-6.1-sol",
416 "--option",
417 "reasoningEffort=high",
418 "--option",
419 "reasoningEffort=low",
420 ]).pipe(Effect.flip);
421β
422 assert.strictEqual(error.message, "--option reasoningEffort is given more than once.");
423 }).pipe(
424 Effect.provide(
425 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
426 ),
427 ),
428);
429β
430/** Serves t3_thread_read pages the way the server does: positions count every item. */
431const timelineTools = (types: ReadonlyArray<string>) => {
432 const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type }));
433 const served: Array<number> = [];
434 const call = ((_tool: string, input: unknown) => {
435 const args = input as { readonly afterPosition?: number; readonly limit: number };
436 // Scanning one match past the page keeps reads of huge fixtures linear.
437 const matching: typeof items = [];
438 for (let position = (args.afterPosition ?? -1) + 1; position < items.length; position++) {
439 const item = items[position]!;
440 if (["user_message", "assistant_message", "proposed_plan"].includes(item.type)) {
441 matching.push(item);
442 if (matching.length > args.limit) break;
443 }
444 }
445 const page = matching.slice(0, args.limit);
446 served.push(page.length);
447 return Effect.succeed({
448 thread: { itemCount: items.length },
449 items: page,
450 nextPosition: page.at(-1)?.position ?? null,
451 hasMore: matching.length > page.length,
452 });
453 }) as ThreadTools["call"];
454 const latest = (count: number) =>
455 items
456 .filter((item) => item.type === "user_message" || item.type === "assistant_message")
457 .slice(-count)
458 .map((item) => item.itemId);
459 return { tools: { call } satisfies ThreadTools, served, latest };
460};
461β
462const tail = (tools: number) => [...Array<string>(tools).fill("tool_call"), "assistant_message"];
463β
464it.effect("show reads the end of a long thread, not its whole history", () =>
465 Effect.gen(function* () {
466 const { tools, served, latest } = timelineTools([
467 ...Array.from({ length: 1000 }, (_, index) =>
468 index % 2 === 0 ? "user_message" : "assistant_message",
469 ),
470 ...Array.from({ length: 10 }, () => tail(30)).flat(),
471 "proposed_plan",
472 ]);
473β
474 const { messages } = yield* readLatestMessages(tools, threadId, 10);
475β
476 assert.deepStrictEqual(
477 messages.map((item) => item.itemId),
478 latest(10),
479 );
480 assert.isBelow(
481 served.reduce((sum, count) => sum + count, 0),
482 100,
483 );
484 }),
485);
486β
487it.effect("show widens back to the first item when the thread has fewer messages", () =>
488 Effect.gen(function* () {
489 const { tools, latest } = timelineTools([
490 "user_message",
491 ...Array.from({ length: 4 }, () => tail(150)).flat(),
492 ]);
493β
494 const { messages } = yield* readLatestMessages(tools, threadId, 10);
495β
496 assert.deepStrictEqual(
497 messages.map((item) => item.itemId),
498 latest(10),
499 );
500 assert.lengthOf(messages, 5);
501 }),
502);
503β
504it.effect("show returns a --messages count larger than one call can spread", () =>
505 Effect.gen(function* () {
506 const { tools, latest } = timelineTools(Array<string>(200_000).fill("assistant_message"));
507β
508 const { messages } = yield* readLatestMessages(tools, threadId, 200_000);
509β
510 assert.deepStrictEqual(
511 messages.map((item) => item.itemId),
512 latest(200_000),
513 );
514 }),
515);
516β
517it.effect("show gives the latest run's last error only when that run did not complete", () =>
518 Effect.gen(function* () {
519 const page = {
520 thread: {},
521 items: [
522 { itemId: "item-0", runId: RunId.make("run-0"), type: "error", text: "earlier run" },
523 { itemId: "item-1", runId, type: "error", text: "first try" },
524 { itemId: "item-2", runId, type: "error", text: "Usage limit reached" },
525 ],
526 nextPosition: null,
527 hasMore: false,
528 };
529 const { tools, calls } = scriptedTools({ t3_thread_read: [page] });
530β
531 assert.strictEqual(
532 yield* latestRunError(tools, { threadId, status: "failed", latestRunId: runId }),
533 "Usage limit reached",
534 );
535 assert.deepInclude(calls[0]?.args, { view: "activity" });
536 for (const status of ["completed", "running", "queued", "idle"] as const) {
537 assert.isNull(yield* latestRunError(tools, { threadId, status, latestRunId: runId }), status);
538 }
539 assert.lengthOf(calls, 1);
540 }),
541);
542β
543it("titles from a long first line without splitting an emoji", () => {
544 const title = titleFromMessage(`${"a".repeat(78)}π and the rest of a long first line`);
545 assert.strictEqual(title, `${"a".repeat(78)}β¦`);
546});
547β
548const git = Effect.fn("test.git")(function* (cwd: string, args: ReadonlyArray<string>) {
549 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
550 const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }));
551 assert.strictEqual(Number(exitCode), 0, `git ${args.join(" ")}`);
552});
553β
554const commitAll = (cwd: string) =>
555 Effect.andThen(
556 git(cwd, ["add", "."]),
557 git(cwd, [
558 "-c",
559 "user.name=Test",
560 "-c",
561 "user.email=test@example.test",
562 "commit",
563 "--quiet",
564 "-m",
565 "initial",
566 ]),
567 );
568β
569it.live("resolves a path inside a git worktree of the project's repository to that project", () =>
570 Effect.gen(function* () {
571 const fileSystem = yield* FileSystem.FileSystem;
572 const path = yield* Path.Path;
573 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-thread-worktree-" });
574 const repo = path.join(root, "sample");
575 const worktree = path.join(root, "worktrees", "sample", "t3-8ff64c24");
576 const feature = path.join(root, "wt", "feature");
577 const featureWorktree = path.join(root, "worktrees", "feature", "t3-1a2b3c4d");
578 yield* fileSystem.makeDirectory(path.join(repo, "pkg"), { recursive: true });
579 yield* fileSystem.writeFileString(path.join(repo, "pkg", "index.ts"), "export {};\n");
580 yield* git(repo, ["init", "--quiet", "-b", "main"]);
581 yield* commitAll(repo);
582 yield* git(repo, ["worktree", "add", "--quiet", "-b", "t3/8ff64c24", worktree]);
583 yield* git(repo, ["worktree", "add", "--quiet", "-b", "feature", feature]);
584 yield* git(feature, ["worktree", "add", "--quiet", "-b", "t3/1a2b3c4d", featureWorktree]);
585β
586 const project = (id: string, workspaceRoot: string) => ({
587 id: ProjectId.make(id),
588 title: path.basename(workspaceRoot),
589 workspaceRoot,
590 });
591 const sample = project("project-sample", repo);
592 const featureProject = project("project-feature", feature);
593 const resolveFrom = (
594 projects: ReadonlyArray<ReturnType<typeof project>>,
595 workingDirectory: string,
596 identifier = ".",
597 ) =>
598 resolveProject(
599 scriptedTools({ t3_project_list: [{ projects, nextCursor: null }] }).tools,
600 identifier,
601 ).pipe(Effect.provideService(HostProcess.WorkingDirectory, workingDirectory));
602β
603 assert.deepStrictEqual(yield* resolveFrom([sample], worktree), sample);
604 assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample);
605 assert.deepStrictEqual(yield* resolveFrom([sample], worktree, "pkg/index.ts"), sample);
606 assert.deepStrictEqual(yield* resolveFrom([featureProject], featureWorktree), featureProject);
607 const ambiguous = yield* Effect.flip(resolveFrom([sample, featureProject], featureWorktree));
608 assert.strictEqual(ambiguous._tag, "ThreadUsageError");
609 assert.include(ambiguous.message, "sample (project-sample)");
610 assert.include(ambiguous.message, "feature (project-feature)");
611 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
612);