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 FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as TestConsole from "effect/testing/TestConsole";
14import { Command } from "effect/cli";
15import { vi } from "vite-plus/test";
16
17import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts";
18import {
19 makePersistedServerRuntimeState,
20 persistServerRuntimeState,
21} from "../serverRuntimeState.ts";
22import {
23 readLatestMessages,
24 threadCommand,
25 type ThreadTools,
26 titleFromMessage,
27 waitForRun,
28} from "./thread.ts";
29
30vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => {
31 const actual = await importOriginal<typeof import("../auth/EnvironmentAuth.ts")>();
32 return {
33 ...actual,
34 layerRuntime: Layer.mock(actual.EnvironmentAuth)({
35 issueMcpClientSession: () =>
36 Effect.map(DateTime.now, (expiresAt) => ({
37 sessionId: AuthSessionId.make("test-session"),
38 token: "synthetic-token",
39 expiresAt,
40 })),
41 revokeSession: () => Effect.succeed(true),
42 }),
43 };
44});
45
46const threadId = ThreadId.make("thread-1");
47const runId = RunId.make("run-1");
48
49it.effect(
50 "start resolves home-relative project paths while preserving ids and relative paths",
51 () =>
52 Effect.gen(function* () {
53 const fs = yield* FileSystem.FileSystem;
54 const path = yield* Path.Path;
55 const root = yield* fs
56 .makeTempDirectoryScoped({ prefix: "t3-thread-project-path-" })
57 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
58 const home = path.join(root, "home");
59 const cwd = path.join(root, "current");
60 const workspaceRoot = path.join(home, "My Project");
61 const nestedRoot = path.join(workspaceRoot, "nested");
62 const baseDir = path.join(root, "state");
63 yield* fs.makeDirectory(nestedRoot, { recursive: true });
64 yield* fs.makeDirectory(cwd);
65 const projects = [
66 { id: ProjectId.make("current-project"), title: "Current", workspaceRoot: cwd },
67 { id: ProjectId.make("home-project"), title: "Home", workspaceRoot: home },
68 { id: ProjectId.make("intended-project"), title: "Intended", workspaceRoot },
69 { id: ProjectId.make("nested-project"), title: "Nested", workspaceRoot: nestedRoot },
70 { id: ProjectId.make("~/literal-id"), title: "Exact id", workspaceRoot: cwd },
71 ];
72 yield* persistServerRuntimeState({
73 path: path.join(baseDir, "userdata", "server-runtime.json"),
74 state: yield* makePersistedServerRuntimeState({
75 config: { host: "127.0.0.1", devUrl: undefined },
76 port: 3_773,
77 }),
78 });
79 using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue(
80 Effect.succeed({
81 call: (tool, args) => {
82 switch (tool) {
83 case "t3_project_list":
84 return Effect.succeed({ structuredContent: { projects, nextCursor: null } });
85 case "t3_thread_launch":
86 return Effect.succeed({
87 structuredContent: { threadId, projectId: args.projectId, runId: null },
88 });
89 default:
90 return Effect.die(`unexpected ${tool} call`);
91 }
92 },
93 }),
94 );
95
96 for (const [identifier, expectedProjectId] of [
97 ["intended-project", "intended-project"],
98 ["~/literal-id", "~/literal-id"],
99 [workspaceRoot, "intended-project"],
100 [path.relative(cwd, workspaceRoot), "intended-project"],
101 [".", "current-project"],
102 ["~/My Project", "intended-project"],
103 ["~", "home-project"],
104 ["~/My Project/nested", "nested-project"],
105 ["~/My Project/missing", "intended-project"],
106 ] as const) {
107 yield* Command.runWith(threadCommand, { version: "0.0.0" })([
108 "start",
109 identifier,
110 "Inspect this project",
111 "--json",
112 "--base-dir",
113 baseDir,
114 ]).pipe(
115 Effect.provideService(HostProcess.HomeDirectory, home),
116 Effect.provideService(HostProcess.WorkingDirectory, cwd),
117 );
118 assert.strictEqual(
119 (yield* TestConsole.logLines).at(-1),
120 JSON.stringify({ threadId, projectId: expectedProjectId, runId: null }),
121 identifier,
122 );
123 }
124 }).pipe(
125 Effect.scoped,
126 Effect.provide(
127 Layer.mergeAll(
128 NodeServices.layer,
129 NodeCrypto.layer,
130 NetService.layer,
131 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })),
132 ),
133 ),
134 ),
135);
136
137/** Answers each tool call with the next scripted response for that tool. */
138const scriptedTools = (script: Record<string, Array<unknown>>) => {
139 const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];
140 const call = ((tool: string, args: unknown) => {
141 calls.push({ tool, args });
142 const next = script[tool]?.shift();
143 return next === undefined ? Effect.die(`unscripted ${tool} call`) : Effect.succeed(next);
144 }) as ThreadTools["call"];
145 return { tools: { call } satisfies ThreadTools, calls };
146};
147
148it.effect("--wait follows the sent run to its continuation's terminal status", () =>
149 Effect.gen(function* () {
150 const continuation = RunId.make("run-2");
151 const { tools, calls } = scriptedTools({
152 t3_thread_wait: [
153 { threadId, runId, status: "running", timedOut: true },
154 { threadId, runId: continuation, status: "failed", timedOut: false },
155 ],
156 t3_thread_read: [{ thread: { pendingRequestCount: 0 } }],
157 });
158
159 const outcome = yield* waitForRun(tools, threadId, runId);
160
161 assert.deepStrictEqual(outcome, { type: "ended", runId: continuation, status: "failed" });
162 assert.deepStrictEqual(
163 calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
164 [
165 { threadId, runId, timeoutMs: 15_000 },
166 { threadId, runId, timeoutMs: 15_000 },
167 ],
168 );
169 }),
170);
171
172it.effect("--wait stops when the thread waits for an answer instead of polling forever", () =>
173 Effect.gen(function* () {
174 const { tools } = scriptedTools({
175 t3_thread_wait: [
176 { threadId, runId, status: "queued", timedOut: true },
177 { threadId, runId, status: "queued", timedOut: true },
178 ],
179 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
180 });
181
182 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), { type: "needs_input" });
183 }),
184);
185
186it.effect("--wait reports its run's result when a later run is the one waiting", () =>
187 Effect.gen(function* () {
188 const { tools } = scriptedTools({
189 t3_thread_wait: [
190 { threadId, runId, status: "running", timedOut: true },
191 { threadId, runId, status: "completed", timedOut: false },
192 ],
193 t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
194 });
195
196 assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId), {
197 type: "ended",
198 runId,
199 status: "completed",
200 });
201 }),
202);
203
204/** Serves t3_thread_read pages the way the server does: positions count every item. */
205const timelineTools = (types: ReadonlyArray<string>) => {
206 const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type }));
207 const served: Array<number> = [];
208 const call = ((_tool: string, input: unknown) => {
209 const args = input as { readonly afterPosition?: number; readonly limit: number };
210 // Scanning one match past the page keeps reads of huge fixtures linear.
211 const matching: typeof items = [];
212 for (let position = (args.afterPosition ?? -1) + 1; position < items.length; position++) {
213 const item = items[position]!;
214 if (["user_message", "assistant_message", "proposed_plan"].includes(item.type)) {
215 matching.push(item);
216 if (matching.length > args.limit) break;
217 }
218 }
219 const page = matching.slice(0, args.limit);
220 served.push(page.length);
221 return Effect.succeed({
222 thread: { itemCount: items.length },
223 items: page,
224 nextPosition: page.at(-1)?.position ?? null,
225 hasMore: matching.length > page.length,
226 });
227 }) as ThreadTools["call"];
228 const latest = (count: number) =>
229 items
230 .filter((item) => item.type === "user_message" || item.type === "assistant_message")
231 .slice(-count)
232 .map((item) => item.itemId);
233 return { tools: { call } satisfies ThreadTools, served, latest };
234};
235
236const tail = (tools: number) => [...Array<string>(tools).fill("tool_call"), "assistant_message"];
237
238it.effect("show reads the end of a long thread, not its whole history", () =>
239 Effect.gen(function* () {
240 const { tools, served, latest } = timelineTools([
241 ...Array.from({ length: 1000 }, (_, index) =>
242 index % 2 === 0 ? "user_message" : "assistant_message",
243 ),
244 ...Array.from({ length: 10 }, () => tail(30)).flat(),
245 "proposed_plan",
246 ]);
247
248 const { messages } = yield* readLatestMessages(tools, threadId, 10);
249
250 assert.deepStrictEqual(
251 messages.map((item) => item.itemId),
252 latest(10),
253 );
254 assert.isBelow(
255 served.reduce((sum, count) => sum + count, 0),
256 100,
257 );
258 }),
259);
260
261it.effect("show widens back to the first item when the thread has fewer messages", () =>
262 Effect.gen(function* () {
263 const { tools, latest } = timelineTools([
264 "user_message",
265 ...Array.from({ length: 4 }, () => tail(150)).flat(),
266 ]);
267
268 const { messages } = yield* readLatestMessages(tools, threadId, 10);
269
270 assert.deepStrictEqual(
271 messages.map((item) => item.itemId),
272 latest(10),
273 );
274 assert.lengthOf(messages, 5);
275 }),
276);
277
278it.effect("show returns a --messages count larger than one call can spread", () =>
279 Effect.gen(function* () {
280 const { tools, latest } = timelineTools(Array<string>(200_000).fill("assistant_message"));
281
282 const { messages } = yield* readLatestMessages(tools, threadId, 200_000);
283
284 assert.deepStrictEqual(
285 messages.map((item) => item.itemId),
286 latest(200_000),
287 );
288 }),
289);
290
291it("titles from a long first line without splitting an emoji", () => {
292 const title = titleFromMessage(`${"a".repeat(78)}😀 and the rest of a long first line`);
293 assert.strictEqual(title, `${"a".repeat(78)}…`);
294});