Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import {
3 EnvironmentId,
4 ProjectId,
5 ProviderInstanceId,
6 ThreadId,
7 type OrchestrationV2ThreadShell,
8 type Project as ProjectRecord,
9} from "@t3tools/contracts";
10import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
11import * as NodeServices from "@effect/platform-node/NodeServices";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Path from "effect/Path";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Stream from "effect/Stream";
18
19import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
20import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
21import * as ServerConfig from "../../../config.ts";
22import * as Project from "../../../project/ProjectService.ts";
23import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
24import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
25import * as VcsProcess from "../../../vcs/VcsProcess.ts";
26import * as McpInvocationContext from "../../McpInvocationContext.ts";
27import * as McpToolAccess from "../../McpToolAccess.ts";
28import * as ProjectHandlers from "./handlers.ts";
29import { ProjectToolkit } from "./tools.ts";
30
31it.effect("attributes a launched thread's first message to the calling thread", () =>
32 Effect.gen(function* () {
33 const sourceThreadId = ThreadId.make("source-thread");
34 const projectId = ProjectId.make("project");
35 const providerInstanceId = ProviderInstanceId.make("codex");
36 const modelSelection = { instanceId: providerInstanceId, model: "gpt-5" };
37 const caller = {
38 id: sourceThreadId,
39 projectId,
40 providerInstanceId,
41 modelSelection,
42 runtimeMode: "full-access",
43 interactionMode: "default",
44 activeRunId: "active-run",
45 archivedAt: null,
46 deletedAt: null,
47 } as OrchestrationV2ThreadShell;
48 let launchedSender: ThreadId | undefined;
49 const layerDependencies = Layer.mergeAll(
50 NodeCrypto.layer,
51 Layer.succeed(McpInvocationContext.McpInvocationContext, {
52 environmentId: EnvironmentId.make("environment"),
53 requestNamespace: "session",
54 thread: {
55 threadId: sourceThreadId,
56 providerSessionId: "session",
57 providerInstanceId,
58 },
59 client: undefined,
60 issuedAt: 0,
61 capabilities: new Set(["orchestration" as const]),
62 }),
63 Layer.mock(ThreadManagement.ThreadManagementService)({
64 getThreadShell: () => Effect.succeed(caller),
65 }),
66 Layer.mock(ThreadLaunch.ThreadLaunchService)({
67 launch: (input) => {
68 launchedSender = input.initialMessage?.senderThreadId;
69 return Effect.succeed({
70 threadId: input.threadId,
71 projection: {
72 thread: { id: input.threadId, projectId, modelSelection },
73 runs: [],
74 },
75 resumed: false,
76 } as unknown as ThreadLaunch.ThreadLaunchResult);
77 },
78 }),
79 Layer.mock(Project.ProjectService)({}),
80 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
81 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
82 NodeServices.layer,
83 ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-link-" }).pipe(
84 Layer.provide(NodeServices.layer),
85 ),
86 );
87 const toolkit = yield* ProjectToolkit.pipe(
88 Effect.provide(
89 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
90 Layer.provide(layerDependencies),
91 ),
92 ),
93 );
94 const result = yield* toolkit
95 .handle("t3_thread_launch", { title: "Audit", message: "Review the change" })
96 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies));
97 expect(result.at(-1)?.result).toMatchObject({ projectId, modelSelection });
98 expect(launchedSender).toBe(sourceThreadId);
99 }),
100);
101
102it.effect("launches a scratch thread into the Scratch project", () =>
103 Effect.gen(function* () {
104 const sourceThreadId = ThreadId.make("source-thread");
105 const scratchProjectId = ProjectId.make("project:scratch");
106 const providerInstanceId = ProviderInstanceId.make("codex");
107 const modelSelection = { instanceId: providerInstanceId, model: "gpt-5" };
108 const caller = {
109 id: sourceThreadId,
110 projectId: ProjectId.make("project:caller"),
111 providerInstanceId,
112 modelSelection,
113 runtimeMode: "full-access",
114 interactionMode: "default",
115 activeRunId: "active-run",
116 archivedAt: null,
117 deletedAt: null,
118 } as OrchestrationV2ThreadShell;
119 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
120 const layerDependencies = Layer.mergeAll(
121 NodeCrypto.layer,
122 Layer.succeed(McpInvocationContext.McpInvocationContext, {
123 environmentId: EnvironmentId.make("environment"),
124 requestNamespace: "session",
125 thread: {
126 threadId: sourceThreadId,
127 providerSessionId: "session",
128 providerInstanceId,
129 },
130 client: undefined,
131 issuedAt: 0,
132 capabilities: new Set(["orchestration" as const]),
133 }),
134 Layer.mock(ThreadManagement.ThreadManagementService)({
135 getThreadShell: () => Effect.succeed(caller),
136 }),
137 Layer.mock(ThreadLaunch.ThreadLaunchService)({
138 launch: (input) => {
139 launched.push(input);
140 return Effect.succeed({
141 threadId: input.threadId,
142 projection: {
143 thread: { id: input.threadId, projectId: input.projectId, modelSelection },
144 runs: [],
145 },
146 resumed: false,
147 } as unknown as ThreadLaunch.ThreadLaunchResult);
148 },
149 }),
150 Layer.mock(Project.ProjectService)({}),
151 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
152 namedProjectsRoot: "/projects",
153 ensureScratchProject: Effect.succeed({ projectId: scratchProjectId }),
154 }),
155 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
156 NodeServices.layer,
157 ServerConfig.layerTest(process.cwd(), { prefix: "t3-scratch-launch-" }).pipe(
158 Layer.provide(NodeServices.layer),
159 ),
160 );
161 const toolkit = yield* ProjectToolkit.pipe(
162 Effect.provide(
163 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
164 Layer.provide(layerDependencies),
165 ),
166 ),
167 );
168 const handle = (params: Parameters<typeof toolkit.handle<"t3_thread_launch">>[1]) =>
169 toolkit
170 .handle("t3_thread_launch", params)
171 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies));
172
173 const result = yield* handle({ title: "Notes", scratch: true, message: "Draft a list" });
174 expect(result.at(-1)?.result).toMatchObject({ projectId: scratchProjectId });
175 expect(launched.map((input) => [input.projectId, input.workspaceStrategy])).toEqual([
176 [scratchProjectId, { type: "root" }],
177 ]);
178
179 const rejected = yield* handle({
180 title: "Notes",
181 scratch: true,
182 projectId: caller.projectId,
183 });
184 expect(rejected.at(-1)?.result).toMatchObject({ code: "invalid_request" });
185 expect(launched).toHaveLength(1);
186 }),
187);
188
189it.effect("starts a project from just a title when workspaceRoot is omitted", () =>
190 Effect.gen(function* () {
191 const sourceThreadId = ThreadId.make("source-thread");
192 const createdProjectId = ProjectId.make("project:named");
193 const providerInstanceId = ProviderInstanceId.make("codex");
194 const caller = {
195 id: sourceThreadId,
196 projectId: ProjectId.make("project:caller"),
197 providerInstanceId,
198 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
199 runtimeMode: "full-access",
200 interactionMode: "default",
201 activeRunId: "active-run",
202 archivedAt: null,
203 deletedAt: null,
204 } as OrchestrationV2ThreadShell;
205 const named: Array<string> = [];
206 const registered: Array<string> = [];
207 const createdProject = {
208 id: createdProjectId,
209 title: "Pinball Stats",
210 workspaceRoot: "/projects/pinball-stats",
211 defaultModelSelection: null,
212 scripts: [],
213 createdAt: "2026-10-01T00:00:00.000Z",
214 updatedAt: "2026-10-01T00:00:00.000Z",
215 deletedAt: null,
216 };
217 const layerDependencies = Layer.mergeAll(
218 NodeCrypto.layer,
219 Layer.succeed(McpInvocationContext.McpInvocationContext, {
220 environmentId: EnvironmentId.make("environment"),
221 requestNamespace: "session",
222 thread: {
223 threadId: sourceThreadId,
224 providerSessionId: "session",
225 providerInstanceId,
226 },
227 client: undefined,
228 issuedAt: 0,
229 capabilities: new Set(["orchestration" as const]),
230 }),
231 Layer.mock(ThreadManagement.ThreadManagementService)({
232 getThreadShell: () => Effect.succeed(caller),
233 }),
234 Layer.mock(ThreadLaunch.ThreadLaunchService)({}),
235 Layer.mock(Project.ProjectService)({
236 create: (input) =>
237 Effect.sync(() => {
238 registered.push(input.workspaceRoot);
239 return { ...createdProject, id: input.projectId, workspaceRoot: input.workspaceRoot };
240 }),
241 getById: (projectId) =>
242 Effect.succeed(
243 projectId === createdProjectId ? Option.some(createdProject) : Option.none(),
244 ),
245 }),
246 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
247 namedProjectsRoot: "/projects",
248 createNamedProject: (input) =>
249 Effect.sync(() => {
250 named.push(input.name);
251 return {
252 projectId: createdProjectId,
253 workspaceRoot: createdProject.workspaceRoot,
254 commitError: "Git has no name or email on this machine.",
255 };
256 }),
257 }),
258 Layer.mock(GitVcsDriver.GitVcsDriver)({}),
259 NodeServices.layer,
260 ServerConfig.layerTest(process.cwd(), { prefix: "t3-named-project-" }).pipe(
261 Layer.provide(NodeServices.layer),
262 ),
263 );
264 const toolkit = yield* ProjectToolkit.pipe(
265 Effect.provide(
266 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
267 Layer.provide(layerDependencies),
268 ),
269 ),
270 );
271 const handle = (params: Parameters<typeof toolkit.handle<"t3_project_create">>[1]) =>
272 toolkit
273 .handle("t3_project_create", params)
274 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies));
275
276 const result = yield* handle({ title: "Pinball Stats" });
277 expect(result.at(-1)?.result).toMatchObject({
278 id: createdProjectId,
279 workspaceRoot: "/projects/pinball-stats",
280 commitError: "Git has no name or email on this machine.",
281 });
282 expect(named).toEqual(["Pinball Stats"]);
283
284 // A path still registers that folder, and never makes a named project.
285 yield* handle({ title: "Existing", workspaceRoot: "/work/existing" });
286 expect(registered).toEqual(["/work/existing"]);
287
288 // Fields this mode cannot apply are rejected, not dropped.
289 for (const extra of [
290 { scripts: [] },
291 { defaultModelSelection: { instanceId: providerInstanceId, model: "gpt-5" } },
292 ]) {
293 const rejected = yield* handle({ title: "Configured", ...extra });
294 expect(rejected.at(-1)?.result).toMatchObject({ code: "invalid_request" });
295 }
296 expect(named).toEqual(["Pinball Stats"]);
297 }),
298);
299
300const clientLaunchHarness = (input: {
301 readonly runtimeModeCeiling: "approval-required" | "auto-accept-edits" | "auto" | "full-access";
302 readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
303 readonly workspaceRoot?: string;
304}) => {
305 const projectId = ProjectId.make("project:client-target");
306 const modelSelection = { instanceId: ProviderInstanceId.make("claude"), model: "claude-opus" };
307 const layerDependencies = Layer.mergeAll(
308 NodeCrypto.layer,
309 Layer.succeed(McpInvocationContext.McpInvocationContext, {
310 environmentId: EnvironmentId.make("environment"),
311 requestNamespace: "client:session-1",
312 thread: undefined,
313 client: {
314 sessionId: "session-1",
315 label: "Claude Code",
316 access: input.runtimeModeCeiling,
317 },
318 issuedAt: 0,
319 capabilities: new Set(["orchestration" as const]),
320 }),
321 Layer.mock(ThreadManagement.ThreadManagementService)({}),
322 Layer.mock(ThreadLaunch.ThreadLaunchService)({
323 launch: (launch) => {
324 input.launched.push(launch);
325 return Effect.succeed({
326 threadId: launch.threadId,
327 projection: {
328 thread: {
329 id: launch.threadId,
330 projectId: launch.projectId,
331 modelSelection: launch.modelSelection,
332 },
333 runs: [],
334 },
335 resumed: false,
336 } as unknown as ThreadLaunch.ThreadLaunchResult);
337 },
338 }),
339 Layer.mock(Project.ProjectService)({
340 getById: (id) =>
341 Effect.succeed(
342 id === projectId
343 ? Option.some({
344 id,
345 workspaceRoot: input.workspaceRoot ?? "/projects/client-target",
346 defaultModelSelection: modelSelection,
347 } as unknown as ProjectRecord)
348 : Option.none(),
349 ),
350 }),
351 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
352 NodeServices.layer,
353 ).pipe(
354 Layer.provideMerge(GitVcsDriver.layer),
355 Layer.provideMerge(VcsProcess.layer),
356 Layer.provideMerge(
357 ServerConfig.layerTest(process.cwd(), { prefix: "t3-client-launch-" }).pipe(
358 Layer.provide(NodeServices.layer),
359 ),
360 ),
361 Layer.provideMerge(NodeServices.layer),
362 );
363 return { projectId, modelSelection, dependencies: layerDependencies };
364};
365
366it.effect("a client launches at its ceiling with the project's default model", () =>
367 Effect.gen(function* () {
368 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
369 const { projectId, modelSelection, dependencies } = clientLaunchHarness({
370 runtimeModeCeiling: "auto-accept-edits",
371 launched,
372 });
373 const toolkit = yield* ProjectToolkit.pipe(
374 Effect.provide(
375 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
376 ),
377 );
378 const handle = (params: Parameters<typeof toolkit.handle<"t3_thread_launch">>[1]) =>
379 toolkit
380 .handle("t3_thread_launch", params)
381 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
382
383 const result = yield* handle({ title: "Fix", projectId, message: "Fix the bug" });
384 expect(result.at(-1)?.result).toMatchObject({ projectId, modelSelection });
385 expect(launched[0]?.runtimeMode).toBe("auto-accept-edits");
386 expect(launched[0]?.initialMessage?.senderThreadId).toBeUndefined();
387
388 const escalated = yield* handle({ title: "Fix", projectId, runtimeMode: "full-access" });
389 expect(escalated.at(-1)?.result).toMatchObject({ code: "runtime_mode_escalation_denied" });
390
391 const untargeted = yield* handle({ title: "Fix" });
392 expect(untargeted.at(-1)?.result).toMatchObject({ code: "target_required" });
393 expect(launched).toHaveLength(1);
394 }),
395);
396
397it.effect("a launch binds only an existing checkout that is one of the project's worktrees", () =>
398 Effect.gen(function* () {
399 const fileSystem = yield* FileSystem.FileSystem;
400 const path = yield* Path.Path;
401 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" });
402 const repo = path.join(root, "repo");
403 const worktree = path.join(root, "feature");
404 const outside = path.join(root, "outside");
405 yield* fileSystem.makeDirectory(repo);
406 yield* fileSystem.makeDirectory(outside);
407
408 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
409 const { projectId, dependencies } = clientLaunchHarness({
410 runtimeModeCeiling: "auto",
411 launched,
412 workspaceRoot: repo,
413 });
414 const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(dependencies));
415 for (const args of [
416 ["init", "-b", "main"],
417 ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "--allow-empty", "-m", "init"],
418 ["worktree", "add", "-b", "feature", worktree],
419 ]) {
420 yield* git.execute({ operation: "test.setupRepo", cwd: repo, args });
421 }
422 const toolkit = yield* ProjectToolkit.pipe(
423 Effect.provide(
424 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
425 ),
426 );
427 const launchInto = (worktreePath: string) =>
428 toolkit
429 .handle("t3_thread_launch", {
430 title: "Fix",
431 projectId,
432 workspaceStrategy: { type: "existing_worktree", worktreePath },
433 })
434 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
435
436 expect((yield* launchInto(worktree)).at(-1)?.result).toMatchObject({ projectId });
437 expect((yield* launchInto(repo)).at(-1)?.result).toMatchObject({ projectId });
438 for (const elsewhere of [outside, path.join(worktree, "..", "outside"), "/"]) {
439 expect((yield* launchInto(elsewhere)).at(-1)?.result).toMatchObject({
440 code: "invalid_request",
441 });
442 }
443 expect(launched.map((launch) => launch.workspaceStrategy)).toEqual([
444 { type: "existing_worktree", worktreePath: worktree },
445 { type: "existing_worktree", worktreePath: repo },
446 ]);
447
448 // A removed worktree stays listed as prunable until `git worktree prune`;
449 // whatever directory is later made at its path is not one of the project's.
450 yield* fileSystem.remove(worktree, { recursive: true });
451 yield* fileSystem.makeDirectory(worktree);
452 expect((yield* launchInto(worktree)).at(-1)?.result).toMatchObject({
453 code: "invalid_request",
454 });
455 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
456);