@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,259 lines 47.3 KB
Raw
1 import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts";
2 import { expect, it } from "@effect/vitest";
3 import {
4 EnvironmentId,
5 GitCommandError,
6 ProjectId,
7 ProviderInstanceId,
8 ProviderDriverKind,
9 type ServerProvider,
10 type Project as ProjectRecord,
11 type ModelSelection,
12 type ProjectScript,
13 type RuntimeMode,
14 type OrchestrationV2ThreadShell,
15 ThreadId,
16 } from "@t3tools/contracts";
17 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
18 import * as NodeServices from "@effect/platform-node/NodeServices";
19 import * as Cause from "effect/Cause";
20 import * as Deferred from "effect/Deferred";
21 import * as Effect from "effect/Effect";
22 import * as Exit from "effect/Exit";
23 import * as Fiber from "effect/Fiber";
24 import * as FileSystem from "effect/FileSystem";
25 import * as Path from "effect/Path";
26 import * as Layer from "effect/Layer";
27 import * as Option from "effect/Option";
28 import * as Stream from "effect/Stream";
29 import { ChildProcessSpawner } from "effect/process";
30 import * as TestClock from "effect/testing/TestClock";
31
32 import * as DocumentText from "../../../provider/DocumentText.ts";
33 import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
34 import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
35 import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
36 import * as ServerConfig from "../../../config.ts";
37 import * as ServerSettings from "../../../serverSettings.ts";
38 import * as Project from "../../../project/ProjectService.ts";
39 import * as ProjectCloneTracker from "../../../project/ProjectCloneTracker.ts";
40 import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
41 import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
42 import * as SourceControlProviderRegistry from "../../../sourceControl/SourceControlProviderRegistry.ts";
43 import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts";
44 import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
45 import * as VcsProcess from "../../../vcs/VcsProcess.ts";
46 import * as McpInvocationContext from "../../McpInvocationContext.ts";
47 import * as McpToolAccess from "../../McpToolAccess.ts";
48 import * as ProjectHandlers from "./handlers.ts";
49 import { ProjectToolkit } from "./tools.ts";
50
51 const clientLaunchHarness = (input: {
52 readonly runtimeModeCeiling: RuntimeMode;
53 readonly defaultRuntimeMode?: RuntimeMode;
54 readonly newWorktreesStartFromOrigin?: boolean;
55 readonly defaultThreadEnvMode?: "local" | "worktree";
56 readonly fallbackModel?: ModelSelection;
57 readonly providers?: readonly ServerProvider[];
58 /** Where Settings saves a project's model; the legacy project field stays null. */
59 readonly overrideModel?: ModelSelection;
60 readonly overrideScripts?: readonly ProjectScript[];
61 readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
62 readonly workspaceRoot?: string;
63 readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
64 readonly hostedAppUrl?: string;
65 /** The orchestrator refuses the new thread's mode, as under a managed ceiling. */
66 readonly refusedByCeiling?: true;
67 }) => {
68 const projectId = ProjectId.make("project:client-target");
69 const modelSelection = {
70 instanceId: ProviderInstanceId.make("claudeAgent"),
71 model: "claude-opus",
72 };
73 // The project's own default model, which a test can clear between launches.
74 const projectDefaults: { model: ModelSelection | null } = {
75 model: input.overrideModel === undefined ? modelSelection : null,
76 };
77 const layerDependencies = Layer.mergeAll(
78 Layer.mock(ProviderRegistry.ProviderRegistry)({
79 getProviders: Effect.succeed(input.providers ?? []),
80 refreshWorkspaceSnapshot: () => Effect.succeed(input.providers ?? []),
81 }),
82 ServerSettings.layerTest({
83 fallbackModelSelection: input.fallbackModel ?? null,
84 ...(input.defaultRuntimeMode === undefined
85 ? {}
86 : { defaultRuntimeMode: input.defaultRuntimeMode }),
87 ...(input.newWorktreesStartFromOrigin === undefined
88 ? {}
89 : { newWorktreesStartFromOrigin: input.newWorktreesStartFromOrigin }),
90 ...(input.defaultThreadEnvMode === undefined
91 ? {}
92 : { defaultThreadEnvMode: input.defaultThreadEnvMode }),
93 ...(input.overrideModel === undefined
94 ? {}
95 : {
96 projectSettingsFolded: true,
97 projectSettingsOverrides: {
98 [projectId]: {
99 defaultModelSelection: input.overrideModel,
100 ...(input.overrideScripts === undefined
101 ? {}
102 : { defaultProjectScripts: input.overrideScripts }),
103 },
104 },
105 }),
106 }),
107 Layer.succeed(McpInvocationContext.McpInvocationContext, {
108 environmentId: EnvironmentId.make("environment"),
109 requestNamespace: "client:session-1",
110 thread: undefined,
111 client: {
112 sessionId: "session-1",
113 label: "Claude Code",
114 access: input.runtimeModeCeiling,
115 hostedAppUrl: input.hostedAppUrl,
116 },
117 issuedAt: 0,
118 capabilities: new Set(["orchestration" as const]),
119 }),
120 Layer.mock(ThreadManagement.ThreadManagementService)({
121 // A thread exists once a launch started it.
122 getThreadShell: (threadId) => {
123 const launch = input.launched.find((candidate) => candidate.threadId === threadId);
124 return Effect.succeed(
125 launch === undefined
126 ? null
127 : ({
128 id: launch.threadId,
129 projectId: launch.projectId,
130 modelSelection: launch.modelSelection,
131 deletedAt: null,
132 } as unknown as OrchestrationV2ThreadShell),
133 );
134 },
135 }),
136 Layer.mock(ThreadLaunch.ThreadLaunchService)({
137 checkWorktreeBase: input.checkWorktreeBase ?? (() => Effect.void),
138 launch: (launch) => {
139 input.launched.push(launch);
140 if (input.refusedByCeiling) {
141 return Effect.fail(
142 new ThreadLaunch.ThreadLaunchError({
143 operation: "create-thread",
144 commandId: launch.commandId,
145 projectId: launch.projectId,
146 cause: new OrchestratorRuntimeModeAboveCeilingError({
147 commandId: launch.commandId,
148 threadId: launch.threadId ?? ThreadId.make("thread:refused"),
149 refused: "mode",
150 runtimeMode: launch.runtimeMode,
151 maxRuntimeMode: "approval-required",
152 organization: "Example Corp",
153 }),
154 }),
155 );
156 }
157 return Effect.succeed({
158 threadId: launch.threadId,
159 projection: {
160 thread: {
161 id: launch.threadId,
162 projectId: launch.projectId,
163 title: launch.title,
164 modelSelection: launch.modelSelection,
165 },
166 runs: [],
167 },
168 resumed: false,
169 } as unknown as ThreadLaunch.ThreadLaunchResult);
170 },
171 }),
172 Layer.mock(Project.ProjectService)({
173 getById: (id) =>
174 Effect.succeed(
175 id === projectId
176 ? Option.some({
177 id,
178 workspaceRoot: input.workspaceRoot ?? "/projects/client-target",
179 defaultModelSelection: projectDefaults.model,
180 } as unknown as ProjectRecord)
181 : Option.none(),
182 ),
183 workspaceScanDirectory: Effect.succeed,
184 }),
185 Layer.mock(PeerForwarding.PeerForwarding)({}),
186 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
187 namedProjectsRoot: "/projects",
188 isScratchProject: () => Effect.succeed(false),
189 }),
190 DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer)),
191 ).pipe(
192 Layer.provideMerge(GitVcsDriver.layer),
193 Layer.provideMerge(VcsProcess.layer),
194 Layer.provideMerge(
195 ServerConfig.layerTest(process.cwd(), { prefix: "t3-client-launch-" }).pipe(
196 Layer.provide(NodeServices.layer),
197 ),
198 ),
199 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
200 );
201 return { projectId, modelSelection, projectDefaults, dependencies: layerDependencies };
202 };
203
204 it.effect(
205 "a client launches with the project's default model and mode, capped at its ceiling",
206 () =>
207 Effect.gen(function* () {
208 const launchWith = Effect.fn("test.launchWith")(function* (
209 runtimeModeCeiling: RuntimeMode,
210 defaultRuntimeMode: RuntimeMode,
211 params: {
212 readonly title: string;
213 readonly message?: string;
214 readonly runtimeMode?: RuntimeMode;
215 readonly targeted?: false;
216 readonly overrideModel?: ModelSelection;
217 readonly hostedAppUrl?: string;
218 readonly refusedByCeiling?: true;
219 },
220 ) {
221 const { targeted, overrideModel, hostedAppUrl, refusedByCeiling, ...input } = params;
222 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
223 const { projectId, modelSelection, dependencies } = clientLaunchHarness({
224 runtimeModeCeiling,
225 defaultRuntimeMode,
226 launched,
227 ...(overrideModel === undefined ? {} : { overrideModel }),
228 ...(hostedAppUrl === undefined ? {} : { hostedAppUrl }),
229 ...(refusedByCeiling === undefined ? {} : { refusedByCeiling }),
230 });
231 const toolkit = yield* ProjectToolkit.pipe(
232 Effect.provide(
233 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
234 Layer.provide(dependencies),
235 ),
236 ),
237 );
238 const result = yield* toolkit
239 .handle("t3_thread_launch", targeted === false ? input : { ...input, projectId })
240 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
241 return { result: result.at(-1)?.result, launched, projectId, modelSelection };
242 });
243
244 const belowCeiling = yield* launchWith("full-access", "approval-required", {
245 title: "Fix",
246 message: "Fix the bug",
247 });
248 expect(belowCeiling.result).toMatchObject({
249 projectId: belowCeiling.projectId,
250 modelSelection: belowCeiling.modelSelection,
251 link: `[Fix](t3-thread://v2/environment/${belowCeiling.launched[0]?.threadId})`,
252 });
253 expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required");
254 expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined();
255
256 const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", {
257 title: "Fix",
258 hostedAppUrl: "https://t3.example.com",
259 });
260 expect(aboveCeiling.launched[0]?.runtimeMode).toBe("auto-accept-edits");
261 expect(aboveCeiling.result).toMatchObject({
262 link: `https://t3.example.com/threads/environment/${encodeURIComponent(aboveCeiling.launched[0]?.threadId ?? "")}`,
263 });
264
265 const requested = yield* launchWith("full-access", "approval-required", {
266 title: "Fix",
267 runtimeMode: "auto",
268 });
269 expect(requested.launched[0]?.runtimeMode).toBe("auto");
270
271 const escalated = yield* launchWith("auto-accept-edits", "auto-accept-edits", {
272 title: "Fix",
273 runtimeMode: "full-access",
274 });
275 expect(escalated.result).toMatchObject({ code: "runtime_mode_escalation_denied" });
276 expect(escalated.launched).toHaveLength(0);
277
278 const untargeted = yield* launchWith("full-access", "full-access", {
279 title: "Fix",
280 targeted: false,
281 });
282 expect(untargeted.result).toMatchObject({ code: "target_required" });
283
284 const overrideModel = {
285 instanceId: ProviderInstanceId.make("codex"),
286 model: "gpt-settings",
287 };
288 const fromSettings = yield* launchWith("full-access", "full-access", {
289 title: "Fix",
290 overrideModel,
291 });
292 expect(fromSettings.launched[0]?.modelSelection).toEqual(overrideModel);
293
294 // An administrator's ceiling the orchestrator enforces is named, not reported as unavailable.
295 const managed = yield* launchWith("full-access", "full-access", {
296 title: "Fix",
297 refusedByCeiling: true,
298 });
299 expect(managed.result).toMatchObject({
300 code: "invalid_request",
301 message: "Example Corp limits threads to Supervised.",
302 });
303 }),
304 );
305
306 it.effect("a launch steps an inherited mode down to the provider's, and refuses one it lacks", () =>
307 Effect.gen(function* () {
308 // Pi offers no Auto; a mode a provider lacks would run as Supervised.
309 const pi = ProviderInstanceId.make("pi");
310 const launchPi = Effect.fn("test.launchPi")(function* (runtimeMode?: RuntimeMode) {
311 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
312 const { projectId, dependencies } = clientLaunchHarness({
313 runtimeModeCeiling: "auto",
314 launched,
315 providers: [
316 {
317 instanceId: pi,
318 driver: ProviderDriverKind.make("pi"),
319 enabled: true,
320 installed: true,
321 status: "ready",
322 version: null,
323 auth: { status: "authenticated" },
324 checkedAt: "2026-01-01T00:00:00Z",
325 models: [],
326 slashCommands: [],
327 skills: [],
328 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"],
329 },
330 ],
331 });
332 const toolkit = yield* ProjectToolkit.pipe(
333 Effect.provide(
334 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
335 Layer.provide(dependencies),
336 ),
337 ),
338 );
339 const result = yield* toolkit
340 .handle("t3_thread_launch", {
341 projectId,
342 title: "Fix",
343 modelSelection: { instanceId: pi, model: "pi-model" },
344 ...(runtimeMode === undefined ? {} : { runtimeMode }),
345 })
346 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
347 return { result: result.at(-1)?.result, launched };
348 });
349
350 const inherited = yield* launchPi();
351 expect(inherited.launched[0]?.runtimeMode).toBe("auto-accept-edits");
352
353 const requested = yield* launchPi("auto");
354 expect(requested.result).toMatchObject({ code: "invalid_request" });
355 expect(requested.launched).toHaveLength(0);
356
357 const offered = yield* launchPi("approval-required");
358 expect(offered.launched[0]?.runtimeMode).toBe("approval-required");
359 }),
360 );
361
362 it.effect("a launch with a model its provider does not advertise creates no thread", () =>
363 Effect.gen(function* () {
364 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
365 const providers: ServerProvider[] = ["claudeAgent", "codex"].map((driver) => ({
366 instanceId: ProviderInstanceId.make(driver),
367 driver: ProviderDriverKind.make(driver),
368 enabled: true,
369 installed: true,
370 status: "ready",
371 version: null,
372 auth: { status: "authenticated" },
373 checkedAt: "2026-01-01T00:00:00Z",
374 models: [
375 driver === "claudeAgent"
376 ? {
377 slug: "claude-opus",
378 name: "Opus",
379 aliases: ["opus"],
380 isCustom: false,
381 capabilities: null,
382 }
383 : { slug: "gpt-5.4", name: "GPT", isCustom: false, capabilities: null },
384 ],
385 slashCommands: [],
386 skills: [],
387 // The project folder's own provider config adds a model the machine catalog lacks.
388 workspaceSnapshots:
389 driver === "codex"
390 ? [
391 {
392 cwd: "/projects/client-target",
393 checkedAt: "2026-01-01T00:00:00Z",
394 slashCommands: [],
395 skills: [],
396 models: [
397 { slug: "gpt-5.4", name: "GPT", isCustom: false, capabilities: null },
398 { slug: "folder-local", name: "Local", isCustom: false, capabilities: null },
399 ],
400 },
401 ]
402 : [],
403 }));
404 const { projectId, dependencies } = clientLaunchHarness({
405 runtimeModeCeiling: "auto",
406 launched,
407 providers,
408 });
409 const toolkit = yield* ProjectToolkit.pipe(
410 Effect.provide(
411 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
412 ),
413 );
414 const launchWith = (instanceId: string, model: string) =>
415 toolkit
416 .handle("t3_thread_launch", {
417 title: "Fix",
418 projectId,
419 modelSelection: { instanceId: ProviderInstanceId.make(instanceId), model },
420 })
421 .pipe(
422 Stream.unwrap,
423 Stream.runCollect,
424 Effect.map((result) => result.at(-1)?.result),
425 Effect.provide(dependencies),
426 );
427
428 for (const [instanceId, model] of [
429 ["claudeAgent", "claude-unadvertised"],
430 ["codex", "opus"],
431 ] as const) {
432 expect(yield* launchWith(instanceId, model)).toMatchObject({
433 code: "model_unavailable",
434 message: expect.stringContaining(
435 `Model ${model} is not advertised by provider ${instanceId}. Advertised models: `,
436 ),
437 });
438 }
439 expect(launched).toHaveLength(0);
440
441 expect(yield* launchWith("claudeAgent", "Opus")).toMatchObject({
442 modelSelection: { instanceId: "claudeAgent", model: "Opus" },
443 });
444 expect(yield* launchWith("codex", "folder-local")).toMatchObject({
445 modelSelection: { instanceId: "codex", model: "folder-local" },
446 });
447 expect(launched).toHaveLength(2);
448 }),
449 );
450
451 it.effect("a launch retried with the same clientRequestId replays the first one", () =>
452 Effect.gen(function* () {
453 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
454 const { projectId, dependencies } = clientLaunchHarness({
455 runtimeModeCeiling: "auto",
456 launched,
457 });
458 const toolkit = yield* ProjectToolkit.pipe(
459 Effect.provide(
460 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
461 ),
462 );
463 const launch = (clientRequestId: string | undefined) =>
464 toolkit
465 .handle("t3_thread_launch", {
466 title: "Fix",
467 projectId,
468 message: "Fix the bug",
469 ...(clientRequestId === undefined ? {} : { clientRequestId }),
470 })
471 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
472
473 yield* launch("fix-1");
474 yield* launch("fix-1");
475 yield* launch("fix-2");
476 yield* launch(undefined);
477 yield* launch(undefined);
478 const ids = launched.map((input) => [input.commandId, input.threadId]);
479 // The same key sends the same command and thread ids, which the launch
480 // service replays instead of starting a second thread.
481 expect(ids[0]).toEqual(ids[1]);
482 expect(ids[0]?.[0]).toMatch(/^mcp:launch:[0-9a-f]{64}$/);
483 expect(ids[2]).not.toEqual(ids[0]);
484 // Without a key every launch is new.
485 expect(ids[3]).not.toEqual(ids[4]);
486 }),
487 );
488
489 it.effect("a launch key of any length or content gives a short id and never a defect", () =>
490 Effect.gen(function* () {
491 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
492 const { projectId, dependencies } = clientLaunchHarness({
493 runtimeModeCeiling: "auto",
494 launched,
495 });
496 const toolkit = yield* ProjectToolkit.pipe(
497 Effect.provide(
498 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
499 ),
500 );
501 const launch = (clientRequestId: string) =>
502 toolkit
503 .handle("t3_thread_launch", { title: "Fix", projectId, clientRequestId })
504 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
505
506 // Percent-encoding would grow this six times; scratch folders are named from the id.
507 yield* launch("\u00e9".repeat(256));
508 expect(launched.map((input) => input.commandId)).toEqual([
509 expect.stringMatching(/^mcp:launch:[0-9a-f]{64}$/),
510 ]);
511
512 const loneSurrogate = yield* launch("key-\ud800").pipe(Effect.exit);
513 expect(Exit.isFailure(loneSurrogate) && Cause.hasDies(loneSurrogate.cause)).toBe(false);
514 expect(launched).toHaveLength(1);
515 }),
516 );
517
518 it.effect("a retried launch replays after the project loses its default model", () =>
519 Effect.gen(function* () {
520 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
521 const { projectId, modelSelection, projectDefaults, dependencies } = clientLaunchHarness({
522 runtimeModeCeiling: "auto",
523 launched,
524 });
525 const toolkit = yield* ProjectToolkit.pipe(
526 Effect.provide(
527 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
528 ),
529 );
530 const launch = toolkit
531 .handle("t3_thread_launch", { title: "Fix", projectId, clientRequestId: "fix-1" })
532 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
533
534 yield* launch;
535 projectDefaults.model = null;
536 const retried = (yield* launch).at(-1)?.result;
537 expect(retried).toMatchObject({ projectId, modelSelection });
538 expect(launched.map((input) => input.threadId)).toEqual([
539 launched[0]?.threadId,
540 launched[0]?.threadId,
541 ]);
542 }),
543 );
544
545 it.effect("a launch binds only an existing checkout that is one of the project's worktrees", () =>
546 Effect.gen(function* () {
547 const fileSystem = yield* FileSystem.FileSystem;
548 const path = yield* Path.Path;
549 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" });
550 const repo = path.join(root, "repo");
551 const worktree = path.join(root, "feature");
552 const outside = path.join(root, "outside");
553 yield* fileSystem.makeDirectory(repo);
554 yield* fileSystem.makeDirectory(outside);
555
556 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
557 const { projectId, dependencies } = clientLaunchHarness({
558 runtimeModeCeiling: "auto",
559 launched,
560 workspaceRoot: repo,
561 });
562 const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(dependencies));
563 for (const args of [
564 ["init", "-b", "main"],
565 ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "--allow-empty", "-m", "init"],
566 ["worktree", "add", "-b", "feature", worktree],
567 ]) {
568 yield* git.execute({ operation: "test.setupRepo", cwd: repo, args });
569 }
570 const toolkit = yield* ProjectToolkit.pipe(
571 Effect.provide(
572 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
573 ),
574 );
575 const launchInto = (worktreePath: string, clientRequestId?: string) =>
576 toolkit
577 .handle("t3_thread_launch", {
578 title: "Fix",
579 projectId,
580 ...(clientRequestId === undefined ? {} : { clientRequestId }),
581 workspaceStrategy: { type: "existing_worktree", worktreePath },
582 })
583 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
584
585 expect((yield* launchInto(worktree, "existing-checkout")).at(-1)?.result).toMatchObject({
586 projectId,
587 });
588 expect((yield* launchInto(outside, "existing-checkout")).at(-1)?.result).toMatchObject({
589 code: "invalid_request",
590 });
591 expect((yield* launchInto(repo)).at(-1)?.result).toMatchObject({ projectId });
592 for (const elsewhere of [outside, path.join(worktree, "..", "outside"), "/"]) {
593 expect((yield* launchInto(elsewhere)).at(-1)?.result).toMatchObject({
594 code: "invalid_request",
595 });
596 }
597 expect(launched.map((launch) => launch.workspaceStrategy)).toEqual([
598 { type: "existing_worktree", worktreePath: worktree },
599 { type: "existing_worktree", worktreePath: repo },
600 ]);
601
602 yield* fileSystem.remove(worktree, { recursive: true });
603 yield* fileSystem.makeDirectory(worktree);
604 expect((yield* launchInto(worktree)).at(-1)?.result).toMatchObject({
605 code: "invalid_request",
606 });
607 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
608 );
609
610 it.effect("a launch into a new worktree creates nothing when its base ref has no commit", () =>
611 Effect.gen(function* () {
612 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
613 const { projectId, dependencies } = clientLaunchHarness({
614 runtimeModeCeiling: "auto",
615 launched,
616 checkWorktreeBase: ({ projectId, workspaceStrategy }) =>
617 workspaceStrategy.type !== "worktree"
618 ? Effect.void
619 : workspaceStrategy.baseRef === "t3/renamed"
620 ? Effect.fail(
621 new ThreadLaunch.ThreadLaunchBaseRefError({
622 projectId,
623 projectTitle: "Client target",
624 workspaceRoot: "/projects/client-target",
625 baseRef: workspaceStrategy.baseRef,
626 }),
627 )
628 : workspaceStrategy.branch === "feature/taken"
629 ? Effect.fail(
630 new ThreadLaunch.ThreadLaunchBranchExistsError({
631 projectId,
632 projectTitle: "Client target",
633 branch: workspaceStrategy.branch,
634 }),
635 )
636 : Effect.void,
637 });
638 const toolkit = yield* ProjectToolkit.pipe(
639 Effect.provide(
640 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
641 ),
642 );
643 const launchFrom = (baseRef: string, branch?: string) =>
644 toolkit
645 .handle("t3_thread_launch", {
646 title: "Fix",
647 projectId,
648 workspaceStrategy: {
649 type: "worktree",
650 baseRef,
651 ...(branch === undefined ? {} : { branch }),
652 startFromOrigin: false,
653 },
654 })
655 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
656
657 const refused = (yield* launchFrom("t3/renamed")).at(-1)?.result;
658 expect(refused).toMatchObject({ code: "invalid_request" });
659 expect((refused as { message: string }).message).toContain(
660 'Base ref "t3/renamed" does not resolve to a commit in project "Client target" (/projects/client-target). No thread was created. Pass a branch, tag, or commit that exists there',
661 );
662 expect((yield* launchFrom("main", "feature/taken")).at(-1)?.result).toMatchObject({
663 code: "invalid_request",
664 message:
665 'Branch "feature/taken" already exists in project "Client target". No thread was created. Pass a branch name that does not exist yet, or omit branch to get a generated name.',
666 });
667 expect(launched).toHaveLength(0);
668
669 expect((yield* launchFrom("main")).at(-1)?.result).toMatchObject({ projectId });
670 expect(launched).toHaveLength(1);
671 }),
672 );
673
674 it.effect("a worktree launch that omits startFromOrigin follows the new-worktree setting", () =>
675 Effect.gen(function* () {
676 const cases = [
677 { setting: true, given: undefined, expected: true },
678 { setting: false, given: undefined, expected: false },
679 { setting: true, given: false, expected: false },
680 ];
681 for (const { setting, given, expected } of cases) {
682 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
683 const checked: Array<ThreadLaunch.ThreadLaunchInput["workspaceStrategy"]> = [];
684 const { projectId, dependencies } = clientLaunchHarness({
685 runtimeModeCeiling: "auto",
686 launched,
687 newWorktreesStartFromOrigin: setting,
688 checkWorktreeBase: ({ workspaceStrategy }) =>
689 Effect.sync(() => {
690 checked.push(workspaceStrategy);
691 }),
692 });
693 const toolkit = yield* ProjectToolkit.pipe(
694 Effect.provide(
695 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
696 Layer.provide(dependencies),
697 ),
698 ),
699 );
700 yield* toolkit
701 .handle("t3_thread_launch", {
702 title: "Fix",
703 projectId,
704 workspaceStrategy: {
705 type: "worktree",
706 baseRef: "main",
707 ...(given === undefined ? {} : { startFromOrigin: given }),
708 },
709 })
710 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
711
712 const strategy = { type: "worktree", baseRef: "main", startFromOrigin: expected };
713 expect(checked).toEqual([strategy]);
714 expect(launched.map((launch) => launch.workspaceStrategy)).toEqual([strategy]);
715 }
716 }),
717 );
718
719 it.effect("a launch that omits its workspace follows the new-threads-in-a-worktree default", () =>
720 Effect.gen(function* () {
721 const fileSystem = yield* FileSystem.FileSystem;
722 for (const source of ["setting", "t3.json"] as const) {
723 const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-env-mode-" });
724 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
725 const { projectId, dependencies } = clientLaunchHarness({
726 runtimeModeCeiling: "auto",
727 launched,
728 workspaceRoot: repo,
729 ...(source === "setting" ? { defaultThreadEnvMode: "worktree" as const } : {}),
730 });
731 const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(dependencies));
732 for (const args of [
733 ["init", "-b", "main"],
734 ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "--allow-empty", "-m", "init"],
735 ]) {
736 yield* git.execute({ operation: "test.setupRepo", cwd: repo, args });
737 }
738 if (source === "t3.json")
739 yield* fileSystem.writeFileString(
740 `${repo}/t3.json`,
741 JSON.stringify({ defaultThreadEnvMode: "worktree" }),
742 );
743 const toolkit = yield* ProjectToolkit.pipe(
744 Effect.provide(
745 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
746 Layer.provide(dependencies),
747 ),
748 ),
749 );
750 for (const workspaceStrategy of [undefined, { type: "root" as const }]) {
751 yield* toolkit
752 .handle("t3_thread_launch", {
753 title: "Fix",
754 projectId,
755 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
756 })
757 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
758 }
759
760 expect(
761 launched.map((launch) => launch.workspaceStrategy.type),
762 source,
763 ).toEqual(["worktree", "root"]);
764 }
765 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
766 );
767
768 it.effect("a defaulted worktree launch stays shared only when Git says HEAD has no commit", () =>
769 Effect.gen(function* () {
770 const fileSystem = yield* FileSystem.FileSystem;
771 const commitArgs = ["-c", "user.email=t@t", "-c", "user.name=t", "commit", "--allow-empty"];
772 for (const [checkout, expected] of [
773 ["not a repository", "root"],
774 ["no commit yet", "root"],
775 ["branch tip object missing", "worktree"],
776 ["git refuses the repository", "refused"],
777 ] as const) {
778 const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-head-" });
779 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
780 const { projectId, dependencies } = clientLaunchHarness({
781 runtimeModeCeiling: "auto",
782 launched,
783 workspaceRoot: repo,
784 defaultThreadEnvMode: "worktree",
785 });
786 const git = yield* GitVcsDriver.GitVcsDriver.pipe(Effect.provide(dependencies));
787 if (checkout !== "not a repository")
788 yield* git.execute({
789 operation: "test.setupRepo",
790 cwd: repo,
791 args: ["init", "-b", "main"],
792 });
793 if (checkout === "branch tip object missing")
794 yield* fileSystem.writeFileString(`${repo}/.git/refs/heads/main`, `${"1".repeat(40)}\n`);
795 if (checkout === "git refuses the repository") {
796 yield* git.execute({
797 operation: "test.setupRepo",
798 cwd: repo,
799 args: [...commitArgs, "-m", "init"],
800 });
801 // Git quotes the broken file's path in its refusal; that path must not read as "not a repository".
802 yield* fileSystem.writeFileString(`${repo}/not a git repository`, "[core\n");
803 yield* fileSystem.writeFileString(
804 `${repo}/.git/config`,
805 `[include]\n\tpath = ${repo}/not a git repository\n`,
806 );
807 }
808 const toolkit = yield* ProjectToolkit.pipe(
809 Effect.provide(
810 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(
811 Layer.provide(dependencies),
812 ),
813 ),
814 );
815 const result = (yield* toolkit
816 .handle("t3_thread_launch", { title: "Fix", projectId })
817 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies))).at(-1)?.result;
818
819 if (expected === "refused") {
820 expect(result, checkout).toMatchObject({ code: "orchestration_error" });
821 expect(launched, checkout).toHaveLength(0);
822 } else {
823 expect(
824 launched.map((launch) => launch.workspaceStrategy.type),
825 checkout,
826 ).toEqual([expected]);
827 }
828 }
829 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
830 );
831
832 it.effect("a launch into a new worktree creates nothing when its branch collides", () =>
833 Effect.gen(function* () {
834 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
835 const { projectId, dependencies } = clientLaunchHarness({
836 runtimeModeCeiling: "auto",
837 launched,
838 checkWorktreeBase: ({ projectId, workspaceStrategy }) =>
839 Effect.fail(
840 new ThreadLaunch.ThreadLaunchBranchConflictError({
841 projectId,
842 projectTitle: "Client target",
843 branch: workspaceStrategy.branch ?? "",
844 conflictingBranch: "werkstatt",
845 }),
846 ),
847 });
848 const toolkit = yield* ProjectToolkit.pipe(
849 Effect.provide(
850 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
851 ),
852 );
853 const refused = (yield* toolkit
854 .handle("t3_thread_launch", {
855 title: "Fix",
856 projectId,
857 workspaceStrategy: { type: "worktree", baseRef: "main", branch: "werkstatt/baseline" },
858 })
859 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies))).at(-1)?.result;
860
861 expect(refused).toMatchObject({
862 code: "invalid_request",
863 message:
864 'Branch "werkstatt/baseline" cannot be created in project "Client target": branch "werkstatt" exists. No thread was created. Use a name that does not nest under or contain an existing branch, such as "werkstatt-baseline".',
865 });
866 expect(launched).toHaveLength(0);
867 }),
868 );
869
870 it.effect("a launch into an unknown project says the project was not found", () =>
871 Effect.gen(function* () {
872 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
873 const { modelSelection, dependencies } = clientLaunchHarness({
874 runtimeModeCeiling: "auto",
875 launched,
876 });
877 const toolkit = yield* ProjectToolkit.pipe(
878 Effect.provide(
879 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
880 ),
881 );
882 for (const workspaceStrategy of [
883 undefined,
884 { type: "worktree", baseRef: "main", startFromOrigin: false } as const,
885 ]) {
886 const result = yield* toolkit
887 .handle("t3_thread_launch", {
888 title: "Fix",
889 message: "Fix the bug",
890 projectId: ProjectId.make("current"),
891 modelSelection,
892 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
893 })
894 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
895 expect(result.at(-1)?.result).toMatchObject({
896 code: "invalid_request",
897 message: "The project was not found.",
898 });
899 }
900 expect(launched).toHaveLength(0);
901 }),
902 );
903
904 it.effect("a retried worktree launch replays after its base ref is gone", () =>
905 Effect.gen(function* () {
906 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
907 const base = { exists: true };
908 const { projectId, dependencies } = clientLaunchHarness({
909 runtimeModeCeiling: "auto",
910 launched,
911 checkWorktreeBase: ({ projectId, workspaceStrategy }) =>
912 base.exists || workspaceStrategy.type !== "worktree"
913 ? Effect.void
914 : Effect.fail(
915 new ThreadLaunch.ThreadLaunchBaseRefError({
916 projectId,
917 projectTitle: "Client target",
918 workspaceRoot: "/projects/client-target",
919 baseRef: workspaceStrategy.baseRef,
920 }),
921 ),
922 });
923 const toolkit = yield* ProjectToolkit.pipe(
924 Effect.provide(
925 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
926 ),
927 );
928 const launch = toolkit
929 .handle("t3_thread_launch", {
930 title: "Fix",
931 projectId,
932 clientRequestId: "fix-worktree",
933 workspaceStrategy: { type: "worktree", baseRef: "feature", startFromOrigin: false },
934 })
935 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
936
937 yield* launch;
938 base.exists = false;
939 expect((yield* launch).at(-1)?.result).toMatchObject({ projectId });
940 expect(launched.map((input) => input.threadId)).toEqual([
941 launched[0]?.threadId,
942 launched[0]?.threadId,
943 ]);
944 }),
945 );
946
947 it.effect("a client launches with the fallback for an exhausted default", () =>
948 Effect.gen(function* () {
949 const launched: ThreadLaunch.ThreadLaunchInput[] = [];
950 const fallbackModel = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" };
951 const providers: ServerProvider[] = ["claudeAgent", "codex"].map((driver) => ({
952 instanceId: ProviderInstanceId.make(driver),
953 driver: ProviderDriverKind.make(driver),
954 enabled: true,
955 installed: true,
956 status: "ready",
957 version: null,
958 auth: { status: "authenticated" },
959 checkedAt: "2026-01-01T00:00:00Z",
960 models: [],
961 slashCommands: [],
962 skills: [],
963 ...(driver === "claudeAgent"
964 ? {
965 usageLimits: {
966 checkedAt: "2026-01-01T00:00:00Z",
967 windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 100 }],
968 },
969 }
970 : {}),
971 }));
972 const { projectId, dependencies } = clientLaunchHarness({
973 runtimeModeCeiling: "full-access",
974 launched,
975 fallbackModel,
976 providers,
977 });
978 const toolkit = yield* ProjectToolkit.pipe(
979 Effect.provide(
980 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
981 ),
982 );
983 const result = yield* toolkit
984 .handle("t3_thread_launch", {
985 projectId,
986 title: "Fallback",
987 })
988 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
989 expect(result.at(-1)?.result).toMatchObject({
990 modelSelection: fallbackModel,
991 });
992 expect(launched[0]?.modelSelection).toEqual(fallbackModel);
993 }),
994 );
995
996 it.effect("creating a project through MCP refuses a model default instead of dropping it", () =>
997 Effect.gen(function* () {
998 const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] });
999 const dependencies = Layer.merge(
1000 harness.dependencies,
1001 Layer.mock(Project.ProjectService)({
1002 create: () => Effect.die("the project was created without its model default"),
1003 }),
1004 );
1005 const toolkit = yield* ProjectToolkit.pipe(
1006 Effect.provide(
1007 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
1008 ),
1009 );
1010
1011 const refused = yield* toolkit
1012 .handle("t3_project_create", {
1013 title: "client-target",
1014 workspaceRoot: "/projects/client-target",
1015 defaultModelSelection: harness.modelSelection,
1016 })
1017 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
1018
1019 expect(refused.at(-1)?.result).toMatchObject({
1020 code: "invalid_request",
1021 message: expect.stringContaining("t3_project_update"),
1022 });
1023 }),
1024 );
1025
1026 it.effect("an agent's clone is not cut off while git is still transferring", () =>
1027 Effect.gen(function* () {
1028 const fs = yield* FileSystem.FileSystem;
1029 const path = yield* Path.Path;
1030 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-clone-" });
1031 const destinationPath = path.join(parent, "repo");
1032 const started = yield* Deferred.make<void>();
1033 const transferred = yield* Deferred.make<void>();
1034 const { dependencies } = clientLaunchHarness({
1035 runtimeModeCeiling: "full-access",
1036 launched: [],
1037 });
1038 const repositories = Repositories.layer.pipe(
1039 Layer.provide(
1040 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
1041 resolveLink: () => undefined,
1042 }),
1043 ),
1044 Layer.provide(
1045 Layer.mock(GitVcsDriver.GitVcsDriver)({
1046 invalidateRefs: () => Effect.void,
1047 // Like the real driver, the clone fails once it outlives the deadline it was given.
1048 execute: (input) =>
1049 Deferred.succeed(started, undefined).pipe(
1050 Effect.andThen(Deferred.await(transferred)),
1051 Effect.as({
1052 exitCode: ChildProcessSpawner.ExitCode(0),
1053 stdout: "",
1054 stderr: "",
1055 stdoutTruncated: false,
1056 stderrTruncated: false,
1057 }),
1058 Effect.timeoutOrElse({
1059 duration: input.timeoutMs ?? Infinity,
1060 orElse: () =>
1061 Effect.fail(
1062 new GitCommandError({
1063 operation: input.operation,
1064 command: "git",
1065 cwd: input.cwd,
1066 detail: "Git command timed out.",
1067 }),
1068 ),
1069 }),
1070 ),
1071 }),
1072 ),
1073 Layer.provideMerge(dependencies),
1074 );
1075 const toolkit = yield* ProjectToolkit.pipe(
1076 Effect.provide(
1077 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(repositories)),
1078 ),
1079 );
1080
1081 const clone = yield* toolkit
1082 .handle("t3_project_clone", { remoteUrl: "https://example.test/repo.git", destinationPath })
1083 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(repositories), Effect.forkChild);
1084 yield* Deferred.await(started);
1085 // A large repository over a slow link; agents' MCP calls get a far longer budget.
1086 yield* TestClock.adjust("10 minutes");
1087 yield* Deferred.succeed(transferred, undefined);
1088
1089 expect((yield* Fiber.join(clone)).at(-1)?.result).toMatchObject({ cwd: destinationPath });
1090 }).pipe(Effect.provide(NodeServices.layer)),
1091 );
1092
1093 const deletedProject = (id: ProjectId) => ({
1094 id,
1095 title: "client-target",
1096 workspaceRoot: "/projects/client-target",
1097 repositoryIdentity: null,
1098 faviconPath: null,
1099 defaultModelSelection: null,
1100 defaultThreadEnvMode: null,
1101 autoPull: false,
1102 projectIcon: null,
1103 scripts: [],
1104 createdAt: "2026-01-01T00:00:00.000Z",
1105 updatedAt: "2026-01-01T00:00:00.000Z",
1106 deletedAt: "2026-01-01T00:00:00.000Z",
1107 });
1108
1109 it.effect("deleting a project through MCP also discards its clone record", () =>
1110 Effect.gen(function* () {
1111 const discarded: Array<ProjectId> = [];
1112 const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] });
1113 const dependencies = Layer.merge(
1114 harness.dependencies,
1115 Layer.mergeAll(
1116 Layer.mock(Project.ProjectService)({
1117 delete: (input) => Effect.succeed(deletedProject(input.projectId)),
1118 }),
1119 Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({
1120 discard: (projectId) => Effect.sync(() => void discarded.push(projectId)),
1121 }),
1122 ),
1123 );
1124 const toolkit = yield* ProjectToolkit.pipe(
1125 Effect.provide(
1126 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
1127 ),
1128 );
1129
1130 yield* toolkit
1131 .handle("t3_project_delete", { projectId: harness.projectId })
1132 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
1133
1134 expect(discarded).toEqual([harness.projectId]);
1135 }),
1136 );
1137
1138 it.effect("an agent cannot delete the built-in scratch project, even with force", () =>
1139 Effect.gen(function* () {
1140 const deleted: Array<ProjectId> = [];
1141 const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] });
1142 const dependencies = Layer.merge(
1143 harness.dependencies,
1144 Layer.mergeAll(
1145 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
1146 namedProjectsRoot: "/projects",
1147 isScratchProject: (projectId) => Effect.succeed(projectId === harness.projectId),
1148 }),
1149 Layer.mock(Project.ProjectService)({
1150 delete: (input) =>
1151 Effect.sync(() => {
1152 deleted.push(input.projectId);
1153 return deletedProject(input.projectId);
1154 }),
1155 }),
1156 Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({ discard: () => Effect.void }),
1157 ),
1158 );
1159 const toolkit = yield* ProjectToolkit.pipe(
1160 Effect.provide(
1161 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
1162 ),
1163 );
1164
1165 const refused = yield* toolkit
1166 .handle("t3_project_delete", { projectId: harness.projectId, force: true })
1167 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
1168
1169 expect(deleted).toEqual([]);
1170 expect(refused.at(-1)?.result).toMatchObject({
1171 code: "invalid_request",
1172 message: expect.stringMatching(/scratch|no project/i),
1173 });
1174 }),
1175 );
1176
1177 it.effect("reading a project shows the default model and actions saved in Settings", () =>
1178 Effect.gen(function* () {
1179 const overrideModel = {
1180 instanceId: ProviderInstanceId.make("claudeAgent"),
1181 model: "claude-sonnet",
1182 };
1183 const overrideScripts = [
1184 { id: "test", name: "Test", command: "pnpm test", icon: "test", runOnWorktreeCreate: false },
1185 ] satisfies ProjectScript[];
1186 const harness = clientLaunchHarness({
1187 runtimeModeCeiling: "full-access",
1188 overrideModel,
1189 overrideScripts,
1190 launched: [],
1191 });
1192 const dependencies = Layer.merge(
1193 harness.dependencies,
1194 Layer.mock(Project.ProjectService)({
1195 getById: (projectId) =>
1196 Effect.succeedSome({
1197 id: projectId,
1198 title: "Client target",
1199 workspaceRoot: "/projects/client-target",
1200 defaultModelSelection: null,
1201 scripts: [
1202 {
1203 id: "stale",
1204 name: "Stale",
1205 command: "true",
1206 icon: "play",
1207 runOnWorktreeCreate: false,
1208 },
1209 ],
1210 createdAt: "2026-01-01T00:00:00.000Z",
1211 updatedAt: "2026-01-01T00:00:00.000Z",
1212 deletedAt: null,
1213 }),
1214 }),
1215 );
1216 const toolkit = yield* ProjectToolkit.pipe(
1217 Effect.provide(
1218 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
1219 ),
1220 );
1221
1222 const read = yield* toolkit
1223 .handle("t3_project_read", { projectId: harness.projectId })
1224 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
1225
1226 expect(read.at(-1)?.result).toMatchObject({
1227 defaultModelSelection: overrideModel,
1228 scripts: overrideScripts,
1229 });
1230 }),
1231 );
1232
1233 it.effect("an update the project refuses tells the agent why", () =>
1234 Effect.gen(function* () {
1235 const harness = clientLaunchHarness({ runtimeModeCeiling: "full-access", launched: [] });
1236 const detail = "Project monograms must contain at most two characters.";
1237 const dependencies = Layer.merge(
1238 harness.dependencies,
1239 Layer.mock(Project.ProjectService)({
1240 update: (input) =>
1241 Effect.fail(new Project.ProjectInvalidError({ projectId: input.projectId, detail })),
1242 }),
1243 );
1244 const toolkit = yield* ProjectToolkit.pipe(
1245 Effect.provide(
1246 McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
1247 ),
1248 );
1249
1250 const refused = yield* toolkit
1251 .handle("t3_project_update", {
1252 projectId: harness.projectId,
1253 projectIcon: { kind: "monogram", text: "ABC", color: "blue" },
1254 })
1255 .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
1256
1257 expect(refused.at(-1)?.result).toMatchObject({ code: "invalid_request", message: detail });
1258 }),
1259 );