The best way to control Claude Code, Codex and more from any computer or phone

main
ts 603 lines 21.1 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, it } from "@effect/vitest";
4 import { AuthSessionId, ProjectId, RunId, ThreadId } from "@t3tools/contracts";
5 import * as HostProcess from "@t3tools/shared/HostProcess";
6 import * as NetService from "@t3tools/shared/Net";
7 import * as ConfigProvider from "effect/ConfigProvider";
8 import * as DateTime from "effect/DateTime";
9 import * as Effect from "effect/Effect";
10 import * as Fiber from "effect/Fiber";
11 import * as FileSystem from "effect/FileSystem";
12 import * as Layer from "effect/Layer";
13 import * as Option from "effect/Option";
14 import * as Path from "effect/Path";
15 import { ChildProcess, ChildProcessSpawner } from "effect/process";
16 import * as TestClock from "effect/testing/TestClock";
17 import * as TestConsole from "effect/testing/TestConsole";
18 import { Command } from "effect/cli";
19 import { vi } from "vite-plus/test";
20
21 import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts";
22 import {
23 makePersistedServerRuntimeState,
24 persistServerRuntimeState,
25 } from "../serverRuntimeState.ts";
26 import {
27 latestRunError,
28 launchModelSelection,
29 readLatestMessages,
30 resolveProject,
31 threadCommand,
32 type ThreadTools,
33 titleFromMessage,
34 waitForRun,
35 } from "./thread.ts";
36
37 vi.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
53 const threadId = ThreadId.make("thread-1");
54 const runId = RunId.make("run-1");
55
56 it.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
144 it.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. */
184 const 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
194 it.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. */
219 const 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
232 it.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 },
245 ],
246 // The wake run starts from a notification, which the messages view leaves out.
247 t3_thread_read: laterRunReads(wakeRun, []),
248 });
249
250 const outcome = yield* waitForRun(tools, threadId, runId, true);
251
252 assert.deepStrictEqual(
253 calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
254 [
255 { threadId, runId, timeoutMs: 15_000 },
256 { threadId, runId, timeoutMs: 15_000, untilDelegatedWorkSettled: true },
257 ],
258 );
259 assert.deepStrictEqual(outcome, { type: "ended", runId: wakeRun, status: "completed" });
260 }),
261 );
262
263 it.effect(
264 "--wait waits out the moment between background work ending and its wake run starting",
265 () =>
266 Effect.gen(function* () {
267 const wakeRun = RunId.make("run-2");
268 const ownOnly = { recentRuns: [{ runId, ordinal: 1, status: "completed" }] };
269 const withWake = (status: string) => [
270 {
271 recentRuns: [
272 { runId, ordinal: 1, status: "completed" },
273 { runId: wakeRun, ordinal: 2, status },
274 ],
275 },
276 { thread: {}, items: [], nextPosition: null, hasMore: false },
277 ];
278 const { tools } = scriptedTools({
279 t3_thread_wait: [
280 { threadId, runId, status: "completed", timedOut: false },
281 { threadId, runId, status: "completed", timedOut: true },
282 // The work ended, and the run it wakes is not recorded yet.
283 {
284 threadId,
285 runId,
286 status: "completed",
287 timedOut: false,
288 resultRun: { runId, status: "completed" },
289 },
290 {
291 threadId,
292 runId,
293 status: "completed",
294 timedOut: false,
295 resultRun: { runId: wakeRun, status: "completed" },
296 },
297 ],
298 t3_thread_read: [
299 ownOnly,
300 { thread: { pendingRequestCount: 0 } },
301 ownOnly,
302 ...withWake("running"),
303 ...withWake("completed"),
304 ],
305 });
306
307 const fiber = yield* Effect.forkChild(waitForRun(tools, threadId, runId, true));
308 yield* TestClock.adjust("500 millis");
309
310 assert.deepStrictEqual(yield* Fiber.join(fiber), {
311 type: "ended",
312 runId: wakeRun,
313 status: "completed",
314 });
315 }),
316 );
317
318 it.effect(
319 "--wait keeps its own run's result when another client's later run settles the thread",
320 () =>
321 Effect.gen(function* () {
322 const sentRun = RunId.make("run-2");
323 const { tools } = scriptedTools({
324 t3_thread_wait: [
325 { threadId, runId, status: "completed", timedOut: false },
326 {
327 threadId,
328 runId,
329 status: "completed",
330 timedOut: false,
331 resultRun: { runId: sentRun, status: "failed" },
332 },
333 ],
334 t3_thread_read: laterRunReads(sentRun, [{ runId: sentRun, type: "user_message" }]),
335 });
336
337 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId, true), {
338 type: "ended",
339 runId,
340 status: "completed",
341 });
342 }),
343 );
344
345 it.effect("--wait stops when the thread waits for an answer instead of polling forever", () =>
346 Effect.gen(function* () {
347 const { tools } = scriptedTools({
348 t3_thread_wait: [
349 { threadId, runId, status: "queued", timedOut: true },
350 { threadId, runId, status: "queued", timedOut: true },
351 ],
352 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
353 });
354
355 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), { type: "needs_input" });
356 }),
357 );
358
359 it.effect("--wait reports its run's result when a later run is the one waiting", () =>
360 Effect.gen(function* () {
361 const { tools } = scriptedTools({
362 t3_thread_wait: [
363 { threadId, runId, status: "running", timedOut: true },
364 { threadId, runId, status: "completed", timedOut: false },
365 ],
366 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
367 });
368
369 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), {
370 type: "ended",
371 runId,
372 status: "completed",
373 });
374 }),
375 );
376
377 it.effect("start sends each --option as a typed model option", () =>
378 Effect.gen(function* () {
379 const selection = yield* launchModelSelection({
380 provider: Option.some("codex"),
381 model: Option.some("gpt-6.1-sol"),
382 option: ["reasoningEffort=high", " fastMode = false ", "note=a=b"],
383 });
384
385 assert.deepStrictEqual(selection, {
386 instanceId: "codex",
387 model: "gpt-6.1-sol",
388 options: [
389 { id: "reasoningEffort", value: "high" },
390 { id: "fastMode", value: false },
391 { id: "note", value: "a=b" },
392 ],
393 });
394 }),
395 );
396
397 it.effect("start rejects a repeated --option before reaching the server", () =>
398 Effect.gen(function* () {
399 const error = yield* Command.runWith(threadCommand, { version: "0.0.0" })([
400 "start",
401 ".",
402 "hi",
403 "--provider",
404 "codex",
405 "--model",
406 "gpt-6.1-sol",
407 "--option",
408 "reasoningEffort=high",
409 "--option",
410 "reasoningEffort=low",
411 ]).pipe(Effect.flip);
412
413 assert.strictEqual(error.message, "--option reasoningEffort is given more than once.");
414 }).pipe(
415 Effect.provide(
416 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer),
417 ),
418 ),
419 );
420
421 /** Serves t3_thread_read pages the way the server does: positions count every item. */
422 const timelineTools = (types: ReadonlyArray<string>) => {
423 const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type }));
424 const served: Array<number> = [];
425 const call = ((_tool: string, input: unknown) => {
426 const args = input as { readonly afterPosition?: number; readonly limit: number };
427 // Scanning one match past the page keeps reads of huge fixtures linear.
428 const matching: typeof items = [];
429 for (let position = (args.afterPosition ?? -1) + 1; position < items.length; position++) {
430 const item = items[position]!;
431 if (["user_message", "assistant_message", "proposed_plan"].includes(item.type)) {
432 matching.push(item);
433 if (matching.length > args.limit) break;
434 }
435 }
436 const page = matching.slice(0, args.limit);
437 served.push(page.length);
438 return Effect.succeed({
439 thread: { itemCount: items.length },
440 items: page,
441 nextPosition: page.at(-1)?.position ?? null,
442 hasMore: matching.length > page.length,
443 });
444 }) as ThreadTools["call"];
445 const latest = (count: number) =>
446 items
447 .filter((item) => item.type === "user_message" || item.type === "assistant_message")
448 .slice(-count)
449 .map((item) => item.itemId);
450 return { tools: { call } satisfies ThreadTools, served, latest };
451 };
452
453 const tail = (tools: number) => [...Array<string>(tools).fill("tool_call"), "assistant_message"];
454
455 it.effect("show reads the end of a long thread, not its whole history", () =>
456 Effect.gen(function* () {
457 const { tools, served, latest } = timelineTools([
458 ...Array.from({ length: 1000 }, (_, index) =>
459 index % 2 === 0 ? "user_message" : "assistant_message",
460 ),
461 ...Array.from({ length: 10 }, () => tail(30)).flat(),
462 "proposed_plan",
463 ]);
464
465 const { messages } = yield* readLatestMessages(tools, threadId, 10);
466
467 assert.deepStrictEqual(
468 messages.map((item) => item.itemId),
469 latest(10),
470 );
471 assert.isBelow(
472 served.reduce((sum, count) => sum + count, 0),
473 100,
474 );
475 }),
476 );
477
478 it.effect("show widens back to the first item when the thread has fewer messages", () =>
479 Effect.gen(function* () {
480 const { tools, latest } = timelineTools([
481 "user_message",
482 ...Array.from({ length: 4 }, () => tail(150)).flat(),
483 ]);
484
485 const { messages } = yield* readLatestMessages(tools, threadId, 10);
486
487 assert.deepStrictEqual(
488 messages.map((item) => item.itemId),
489 latest(10),
490 );
491 assert.lengthOf(messages, 5);
492 }),
493 );
494
495 it.effect("show returns a --messages count larger than one call can spread", () =>
496 Effect.gen(function* () {
497 const { tools, latest } = timelineTools(Array<string>(200_000).fill("assistant_message"));
498
499 const { messages } = yield* readLatestMessages(tools, threadId, 200_000);
500
501 assert.deepStrictEqual(
502 messages.map((item) => item.itemId),
503 latest(200_000),
504 );
505 }),
506 );
507
508 it.effect("show gives the latest run's last error only when that run did not complete", () =>
509 Effect.gen(function* () {
510 const page = {
511 thread: {},
512 items: [
513 { itemId: "item-0", runId: RunId.make("run-0"), type: "error", text: "earlier run" },
514 { itemId: "item-1", runId, type: "error", text: "first try" },
515 { itemId: "item-2", runId, type: "error", text: "Usage limit reached" },
516 ],
517 nextPosition: null,
518 hasMore: false,
519 };
520 const { tools, calls } = scriptedTools({ t3_thread_read: [page] });
521
522 assert.strictEqual(
523 yield* latestRunError(tools, { threadId, status: "failed", latestRunId: runId }),
524 "Usage limit reached",
525 );
526 assert.deepInclude(calls[0]?.args, { view: "activity" });
527 for (const status of ["completed", "running", "queued", "idle"] as const) {
528 assert.isNull(yield* latestRunError(tools, { threadId, status, latestRunId: runId }), status);
529 }
530 assert.lengthOf(calls, 1);
531 }),
532 );
533
534 it("titles from a long first line without splitting an emoji", () => {
535 const title = titleFromMessage(`${"a".repeat(78)}😀 and the rest of a long first line`);
536 assert.strictEqual(title, `${"a".repeat(78)}…`);
537 });
538
539 const git = Effect.fn("test.git")(function* (cwd: string, args: ReadonlyArray<string>) {
540 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
541 const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }));
542 assert.strictEqual(Number(exitCode), 0, `git ${args.join(" ")}`);
543 });
544
545 const commitAll = (cwd: string) =>
546 Effect.andThen(
547 git(cwd, ["add", "."]),
548 git(cwd, [
549 "-c",
550 "user.name=Test",
551 "-c",
552 "user.email=test@example.test",
553 "commit",
554 "--quiet",
555 "-m",
556 "initial",
557 ]),
558 );
559
560 it.live("resolves a path inside a git worktree of the project's repository to that project", () =>
561 Effect.gen(function* () {
562 const fileSystem = yield* FileSystem.FileSystem;
563 const path = yield* Path.Path;
564 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-thread-worktree-" });
565 const repo = path.join(root, "sample");
566 const worktree = path.join(root, "worktrees", "sample", "t3-8ff64c24");
567 const feature = path.join(root, "wt", "feature");
568 const featureWorktree = path.join(root, "worktrees", "feature", "t3-1a2b3c4d");
569 yield* fileSystem.makeDirectory(path.join(repo, "pkg"), { recursive: true });
570 yield* fileSystem.writeFileString(path.join(repo, "pkg", "index.ts"), "export {};\n");
571 yield* git(repo, ["init", "--quiet", "-b", "main"]);
572 yield* commitAll(repo);
573 yield* git(repo, ["worktree", "add", "--quiet", "-b", "t3/8ff64c24", worktree]);
574 yield* git(repo, ["worktree", "add", "--quiet", "-b", "feature", feature]);
575 yield* git(feature, ["worktree", "add", "--quiet", "-b", "t3/1a2b3c4d", featureWorktree]);
576
577 const project = (id: string, workspaceRoot: string) => ({
578 id: ProjectId.make(id),
579 title: path.basename(workspaceRoot),
580 workspaceRoot,
581 });
582 const sample = project("project-sample", repo);
583 const featureProject = project("project-feature", feature);
584 const resolveFrom = (
585 projects: ReadonlyArray<ReturnType<typeof project>>,
586 workingDirectory: string,
587 identifier = ".",
588 ) =>
589 resolveProject(
590 scriptedTools({ t3_project_list: [{ projects, nextCursor: null }] }).tools,
591 identifier,
592 ).pipe(Effect.provideService(HostProcess.WorkingDirectory, workingDirectory));
593
594 assert.deepStrictEqual(yield* resolveFrom([sample], worktree), sample);
595 assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample);
596 assert.deepStrictEqual(yield* resolveFrom([sample], worktree, "pkg/index.ts"), sample);
597 assert.deepStrictEqual(yield* resolveFrom([featureProject], featureWorktree), featureProject);
598 const ambiguous = yield* Effect.flip(resolveFrom([sample, featureProject], featureWorktree));
599 assert.strictEqual(ambiguous._tag, "ThreadUsageError");
600 assert.include(ambiguous.message, "sample (project-sample)");
601 assert.include(ambiguous.message, "feature (project-feature)");
602 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
603 );