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

thread.test.ts

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