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

AntigravityAdapter.test.ts

1,317 lines49.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import {
4 AntigravitySettings,
5 ApprovalRequestId,
6 ProviderInstanceId,
7 ThreadId,
8 type ProviderRuntimeEvent,
9} from "@t3tools/contracts";
10import * as Deferred from "effect/Deferred";
11import * as Crypto from "effect/Crypto";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Fiber from "effect/Fiber";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Path from "effect/Path";
18import * as Queue from "effect/Queue";
19import * as Schema from "effect/Schema";
20import * as Stream from "effect/Stream";
21import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
22import * as AcpErrors from "effect-acp/errors";
23import type * as AcpSchema from "effect-acp/schema";
24​
25import { ServerConfig } from "../../config.ts";
26import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../antigravityAuthSupport.ts";
27import type { AcpSessionRuntimeEvent } from "../acp/AcpSessionRuntime.ts";
28import { makeAntigravityAcpRuntime } from "../acp/AntigravityAcpSupport.ts";
29import {
30 mergeToolCallState,
31 parseSessionUpdateEvent,
32 type AcpToolCallState,
33} from "../acp/AcpRuntimeModel.ts";
34import { makeAntigravityAdapter, type AntigravityAdapterOptions } from "./AntigravityAdapter.ts";
35​
36const instanceId = ProviderInstanceId.make("antigravity-test");
37const threadId = ThreadId.make("antigravity-thread");
38const nativeSessionId = "b75db7e9-cd99-40e5-aa63-ac2b4674a6a9";
39const nativeDefault = "gemini-test-low";
40const nativeAlternative = "gemini-test-high";
41const decodeSettings = Schema.decodeSync(AntigravitySettings);
42const decodeRequestLog = Schema.decodeEffect(
43 Schema.Array(
44 Schema.fromJsonString(
45 Schema.Struct({ method: Schema.String, params: Schema.optional(Schema.Unknown) }),
46 ),
47 ),
48);
49​
50interface NativePrompt {
51 readonly index: number;
52 readonly result: Deferred.Deferred<AcpSchema.PromptResponse, AcpErrors.AcpError>;
54​
55type Runtime = Effect.Success<ReturnType<AntigravityAdapterOptions["makeRuntime"]>>;
56​
57function nativeToolUpdate(
58 update: Extract<
59 AcpSchema.SessionNotification["update"],
60 { sessionUpdate: "tool_call" | "tool_call_update" }
61 >,
62 previous?: AcpToolCallState,
63) {
64 const event = parseSessionUpdateEvent({ sessionId: nativeSessionId, update }).events.find(
65 (event) => event._tag === "ToolCallUpdated",
66 );
67 if (!event) throw new Error("Expected a native tool update");
68 return { ...event, toolCall: mergeToolCallState(previous, event.toolCall) };
70​
71const makeHarness = Effect.fn("makeAntigravityAdapterHarness")(function* (options?: {
72 readonly enabled?: boolean;
73 readonly holdCancel?: boolean;
74 readonly holdClose?: boolean;
75 readonly holdDispatch?: boolean;
76}) {
77 const runtimeEvents = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
78 const canonicalEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
79 const prompts = yield* Queue.unbounded<NativePrompt>();
80 const cancellations = yield* Queue.unbounded<number>();
81 const cancelRelease = yield* Deferred.make<void>();
82 const closeStarted = yield* Deferred.make<void>();
83 const closeRelease = yield* Deferred.make<void>();
84 const dispatchStarted = yield* Deferred.make<void>();
85 const dispatchRelease = yield* Deferred.make<void>();
86 const seen: ProviderRuntimeEvent[] = [];
87 const calls: string[] = [];
88 const launches: Array<Parameters<AntigravityAdapterOptions["makeRuntime"]>[0]> = [];
89 const stops: Array<Effect.Effect<void>> = [];
90 const controls = { failModel: false, failAuth: false, authInvalidations: 0, closed: 0 };
91 let currentModel = nativeDefault;
92 let promptIndex = 0;
93 let active: NativePrompt | undefined;
94 const fileHandlers: {
95 read?: Parameters<Runtime["handleReadTextFile"]>[0];
96 write?: Parameters<Runtime["handleWriteTextFile"]>[0];
97 } = {};
98 let permissionHandler:
99 | ((
100 request: AcpSchema.RequestPermissionRequest,
101 ) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpErrors.AcpError>)
102 | undefined;
103​
104 const configOptions = (): ReadonlyArray<AcpSchema.SessionConfigOption> => [
105 {
106 id: "model",
107 name: "Model",
108 type: "select",
109 category: "model",
110 currentValue: currentModel,
111 options: [
112 { value: nativeDefault, name: "Gemini test low" },
113 { value: nativeAlternative, name: "Gemini test high" },
114 ],
115 },
116 ];
117 const drainEvents = Effect.gen(function* () {
118 const acknowledge = yield* Deferred.make<void>();
119 yield* Queue.offer(runtimeEvents, { _tag: "EventStreamBarrier", acknowledge });
120 yield* Deferred.await(acknowledge);
121 });
122 const emitNative = (event: AcpSessionRuntimeEvent) =>
123 Queue.offer(runtimeEvents, event).pipe(Effect.asVoid);
124 const runtime: Effect.Success<ReturnType<AntigravityAdapterOptions["makeRuntime"]>> = {
125 handleRequestPermission: (handler) =>
126 Effect.sync(() => {
127 permissionHandler = handler;
128 }),
129 handleReadTextFile: (handler) =>
130 Effect.sync(() => {
131 fileHandlers.read = handler;
132 }),
133 handleWriteTextFile: (handler) =>
134 Effect.sync(() => {
135 fileHandlers.write = handler;
136 }),
137 start: () =>
138 Effect.gen(function* () {
139 if (controls.failAuth) {
140 return yield* new AcpErrors.AcpTransportError({
141 detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
142 cause: undefined,
143 });
144 }
145 currentModel = nativeDefault;
146 calls.push("start");
147 yield* emitNative({
148 _tag: "AvailableCommandsUpdated",
149 availableCommands: [
150 { name: "plan", description: "Create a plan" },
151 { name: "logout", description: "Sign out" },
152 ],
153 rawPayload: {},
154 });
155 return {
156 sessionId: nativeSessionId,
157 initializeResult: {
158 protocolVersion: 1,
159 agentCapabilities: { sessionCapabilities: { resume: {} } },
160 },
161 sessionSetupResult: { sessionId: nativeSessionId, configOptions: configOptions() },
162 modelConfigId: "model",
163 };
164 }),
165 getConfigOptions: Effect.sync(configOptions),
166 setModel: (model) =>
167 Effect.gen(function* () {
168 calls.push(`model:${model}`);
169 if (controls.failModel) {
170 controls.failModel = false;
171 return yield* AcpErrors.AcpRequestError.invalidParams("Native model selection failed.");
172 }
173 currentModel = model;
174 }),
175 setMode: (mode) =>
176 Effect.sync(() => {
177 calls.push(`mode:${mode}`);
178 return {};
179 }),
180 getEvents: () => Stream.fromQueue(runtimeEvents),
181 drainEvents,
182 prompt: (_payload, promptOptions) =>
183 Effect.gen(function* () {
184 yield* Deferred.succeed(dispatchStarted, undefined);
185 if (options?.holdDispatch) yield* Deferred.await(dispatchRelease);
186 const prompt: NativePrompt = {
187 index: ++promptIndex,
188 result: yield* Deferred.make<AcpSchema.PromptResponse, AcpErrors.AcpError>(),
189 };
190 active = prompt;
191 calls.push(`prompt:${prompt.index}`);
192 if (promptOptions?.dispatched) yield* Deferred.succeed(promptOptions.dispatched, undefined);
193 yield* Queue.offer(prompts, prompt);
194 return yield* Deferred.await(prompt.result).pipe(
195 Effect.ensuring(
196 Effect.sync(() => {
197 if (active === prompt) active = undefined;
198 }),
199 ),
200 );
201 }),
202 cancel: Effect.gen(function* () {
203 const prompt = active;
204 if (!prompt) return;
205 calls.push(`cancel:${prompt.index}`);
206 yield* Queue.offer(cancellations, prompt.index);
207 if (options?.holdCancel) yield* Deferred.await(cancelRelease);
208 yield* Deferred.succeed(prompt.result, { stopReason: "cancelled" });
209 yield* Deferred.await(prompt.result);
210 yield* drainEvents;
211 calls.push(`drained:${prompt.index}`);
212 }),
213 };
214 const commandUpdates: Array<ReadonlyArray<AcpSchema.AvailableCommand>> = [];
215 const adapter = yield* makeAntigravityAdapter(
216 decodeSettings({ enabled: options?.enabled ?? true }),
217 {
218 instanceId,
219 makeRuntime: (input) =>
220 Effect.gen(function* () {
221 launches.push(input);
222 yield* Effect.addFinalizer(() =>
223 Effect.gen(function* () {
224 yield* Deferred.succeed(closeStarted, undefined);
225 if (options?.holdClose) yield* Deferred.await(closeRelease);
226 controls.closed += 1;
227 }),
228 );
229 return runtime;
230 }),
231 withProcess: (stop, task) =>
232 Effect.suspend(() => {
233 stops.push(stop);
234 return task;
235 }),
236 onAvailableCommands: (commands) =>
237 Effect.sync(() => {
238 commandUpdates.push(commands);
239 }),
240 onAuthRequired: Effect.sync(() => {
241 controls.authInvalidations += 1;
242 }),
243 },
244 );
245 yield* adapter.streamEvents.pipe(
246 Stream.runForEach((event) =>
247 Effect.sync(() => {
248 seen.push(event);
249 }).pipe(Effect.andThen(Queue.offer(canonicalEvents, event))),
250 ),
251 Effect.forkScoped({ startImmediately: true }),
252 );
253 yield* Effect.addFinalizer(() =>
254 Effect.all([
255 Deferred.succeed(cancelRelease, undefined),
256 Deferred.succeed(closeRelease, undefined),
257 Deferred.succeed(dispatchRelease, undefined),
258 ]).pipe(Effect.asVoid),
259 );
260 const waitForEvent = Effect.fn("AntigravityAdapterTest.waitForEvent")(function* <
261 T extends ProviderRuntimeEvent,
262 >(predicate: (event: ProviderRuntimeEvent) => event is T) {
263 while (true) {
264 const event = yield* Queue.take(canonicalEvents);
265 if (predicate(event)) return event;
266 }
267 });
268 const invokePermission = (request: AcpSchema.RequestPermissionRequest) =>
269 Effect.suspend(() =>
270 permissionHandler
271 ? permissionHandler(request)
272 : Effect.die("Missing native permission handler"),
273 );
274 return {
275 fileHandlers,
276 adapter,
277 calls,
278 launches,
279 commandUpdates,
280 controls,
281 seen,
282 stops,
283 waitForEvent,
284 emitNative,
285 invokePermission,
286 closeStarted,
287 closeRelease,
288 cancelRelease,
289 dispatchStarted,
290 dispatchRelease,
291 nextPrompt: Queue.take(prompts),
292 nextCancellation: Queue.take(cancellations),
293 drainEvents,
294 hasActivePrompt: () => active !== undefined,
295 };
296});
297​
298const layer = ServerConfig.layerTest(process.cwd(), {
299 prefix: "t3-antigravity-adapter-test-",
300}).pipe(Layer.provideMerge(NodeServices.layer));
301​
302it.layer(layer)("AntigravityAdapter", (it) => {
303 it.effect(
304 "runs native auth, resume, models, commands, and streaming through the ACP transport",
305 () =>
306 Effect.gen(function* () {
307 const fileSystem = yield* FileSystem.FileSystem;
308 const path = yield* Path.Path;
309 const crypto = yield* Crypto.Crypto;
310 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
311 const cwd = yield* fileSystem.makeTempDirectoryScoped({
312 prefix: "t3-antigravity-transport-",
313 });
314 const mockAgentPath = yield* path.fromFileUrl(
315 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
316 );
317 const requestLog = path.join(cwd, "requests.ndjson");
318 const commands: string[] = [];
319 const modelSelections: string[] = [];
320 const observed: ProviderRuntimeEvent[] = [];
321 const completed = yield* Deferred.make<void>();
322 const adapter = yield* makeAntigravityAdapter(decodeSettings({ enabled: true }), {
323 instanceId,
324 withProcess: (_stop, task) => task,
325 makeRuntime: (input) =>
326 makeAntigravityAcpRuntime({
327 ...input,
328 childProcessSpawner,
329 spawn: {
330 command: process.execPath,
331 args: [mockAgentPath],
332 cwd: input.cwd,
333 env: {
334 ...process.env,
335 T3_ACP_ANTIGRAVITY: "1",
336 T3_ACP_REQUEST_LOG_PATH: requestLog,
337 },
338 extendEnv: false,
339 },
340 }).pipe(Effect.provideService(Crypto.Crypto, crypto)),
341 onAvailableCommands: (available) =>
342 Effect.sync(() => {
343 commands.push(...available.map((command) => command.name));
344 }),
345 onConfigOptionsUpdated: (configOptions) =>
346 Effect.sync(() => {
347 const model = configOptions.find((option) => option.category === "model");
348 if (model?.type === "select") modelSelections.push(model.currentValue);
349 }),
350 });
351 yield* adapter.streamEvents.pipe(
352 Stream.runForEach((event) =>
353 Effect.gen(function* () {
354 observed.push(event);
355 if (event.type === "turn.completed") yield* Deferred.succeed(completed, undefined);
356 }),
357 ),
358 Effect.forkScoped({ startImmediately: true }),
359 );
360 const original = yield* adapter.startSession({
361 threadId,
362 cwd,
363 runtimeMode: "auto-accept-edits",
364 modelSelection: { instanceId, model: nativeAlternative },
365 });
366 yield* adapter.stopSession(threadId);
367 const resumed = yield* adapter.startSession({
368 threadId,
369 cwd,
370 runtimeMode: "auto-accept-edits",
371 modelSelection: { instanceId, model: nativeAlternative },
372 resumeCursor: original.resumeCursor,
373 });
374 expect(resumed.model).toBe(nativeAlternative);
375 yield* adapter.sendTurn({ threadId, input: "Reply with one short line." });
376 yield* Deferred.await(completed);
377 expect(commands).toEqual(["plan", "logout", "plan", "logout"]);
378 expect(modelSelections.length).toBeGreaterThan(0);
379 expect(modelSelections.every((model) => model === nativeAlternative)).toBe(true);
380 expect(
381 observed
382 .filter((event) => event.type === "content.delta")
383 .map((event) => event.payload.delta)
384 .join(""),
385 ).toBe("hello from mock");
386 const lines = (yield* fileSystem.readFileString(requestLog)).trim().split("\n");
387 const requests = yield* decodeRequestLog(lines);
388 expect(
389 requests
390 .filter((request) => request.method === "authenticate")
391 .map((request) => request.params),
392 ).toEqual([{ methodId: "oauth-personal" }, { methodId: "oauth-personal" }]);
393 expect(requests.some((request) => request.method === "session/resume")).toBe(true);
394 expect(requests.some((request) => request.method === "session/load")).toBe(false);
395 expect(
396 requests
397 .filter((request) => request.method === "session/set_config_option")
398 .map((request) => request.params),
399 ).toContainEqual({ sessionId: "mock-session-1", configId: "mode", value: "auto_edit" });
400 }),
401 );
402​
403 it.effect("reapplies the exact saved model and mode after a native resume", () =>
404 Effect.gen(function* () {
405 const h = yield* makeHarness();
406 const first = yield* h.adapter.startSession({
407 threadId,
408 cwd: process.cwd(),
409 runtimeMode: "auto-accept-edits",
410 modelSelection: { instanceId, model: nativeAlternative },
411 });
412 expect(first.model).toBe(nativeAlternative);
413 yield* h.adapter.stopSession(threadId);
414 const second = yield* h.adapter.startSession({
415 threadId,
416 cwd: "/tmp",
417 runtimeMode: "auto-accept-edits",
418 resumeCursor: first.resumeCursor,
419 modelSelection: { instanceId, model: nativeAlternative },
420 });
421 expect(second.model).toBe(nativeAlternative);
422 expect(second.cwd).toBe("/tmp");
423 expect(h.launches[1]?.resumeSessionId).toBe(nativeSessionId);
424 expect(h.calls).toEqual([
425 "start",
426 `model:${nativeAlternative}`,
427 "mode:auto_edit",
428 "start",
429 `model:${nativeAlternative}`,
430 "mode:auto_edit",
431 ]);
432 expect(h.commandUpdates.at(-1)?.map((command) => command.name)).toEqual(["plan", "logout"]);
433 expect(h.adapter.capabilities.supportsConversationRollback).toBe(false);
434 const rollback = yield* h.adapter.rollbackThread(threadId, 1).pipe(Effect.exit);
435 expect(Exit.isFailure(rollback)).toBe(true);
436 }),
437 );
438​
439 it.effect("keeps thoughts, native command results, and replies on the active turn", () =>
440 Effect.gen(function* () {
441 const h = yield* makeHarness();
442 yield* h.adapter.startSession({
443 threadId,
444 cwd: process.cwd(),
445 runtimeMode: "approval-required",
446 });
447 const sending = yield* h.adapter
448 .sendTurn({ threadId, input: "Read the file" })
449 .pipe(Effect.forkChild);
450 const prompt = yield* h.nextPrompt;
451 yield* h.emitNative({ _tag: "ThoughtDelta", text: "I will read it.", rawPayload: {} });
452 yield* h.emitNative({
453 _tag: "ToolCallUpdated",
454 toolCall: {
455 toolCallId: "command-1",
456 kind: "execute",
457 status: "completed",
458 data: {
459 rawInput: { CommandLine: "cat probe.txt", Cwd: "/tmp" },
460 rawOutput: { combinedOutput: "after\n", exitCode: 0 },
461 },
462 },
463 rawPayload: {},
464 });
465 yield* h.emitNative({ _tag: "ContentDelta", text: "The file says after.", rawPayload: {} });
466 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
467 const result = yield* Fiber.join(sending);
468 yield* h.waitForEvent((event) => event.type === "turn.completed");
469 const deltas = h.seen.filter((event) => event.type === "content.delta");
470 expect(deltas.map((event) => event.payload.streamKind)).toEqual([
471 "reasoning_text",
472 "assistant_text",
473 ]);
474 expect(deltas.every((event) => event.turnId === result.turnId)).toBe(true);
475 const tool = h.seen.find(
476 (event) =>
477 event.type === "item.completed" && event.payload.itemType === "command_execution",
478 );
479 expect(tool?.type === "item.completed" ? tool.payload.data : undefined).toMatchObject({
480 command: "cat probe.txt",
481 cwd: "/tmp",
482 item: { aggregatedOutput: "after\n", exitCode: 0 },
483 });
484 }),
485 );
486​
487 it.effect("does not auto-approve a remaining native request in full access", () =>
488 Effect.gen(function* () {
489 const h = yield* makeHarness();
490 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
491 const permission = yield* h
492 .invokePermission({
493 sessionId: nativeSessionId,
494 toolCall: { toolCallId: "write-1", kind: "edit", title: "Write probe.txt" },
495 options: [
496 { optionId: "native:allow", name: "Allow", kind: "allow_once" },
497 { optionId: "native:deny", name: "Deny", kind: "reject_once" },
498 ],
499 })
500 .pipe(Effect.forkChild);
501 const opened = yield* h.waitForEvent((event) => event.type === "request.opened");
502 expect(h.calls).toContain("mode:yolo");
503 expect(opened.payload.options).toEqual([
504 { decision: "accept", label: "Allow once" },
505 { decision: "decline", label: "Deny" },
506 { decision: "cancel", label: "Cancel" },
507 ]);
508 expect(permission.pollUnsafe()).toBeUndefined();
509 const always = yield* h.adapter
510 .respondToRequest(threadId, ApprovalRequestId.make(opened.requestId!), "acceptAlways")
511 .pipe(Effect.exit);
512 expect(Exit.isFailure(always)).toBe(true);
513 yield* h.adapter.respondToRequest(
514 threadId,
515 ApprovalRequestId.make(opened.requestId!),
516 "decline",
517 );
518 expect(yield* Fiber.join(permission)).toEqual({
519 outcome: { outcome: "selected", optionId: "native:deny" },
520 });
521 }),
522 );
523​
524 it.effect("returns opaque native question choices and rejects ambiguous labels", () =>
525 Effect.gen(function* () {
526 const h = yield* makeHarness();
527 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
528 const question = yield* h
529 .invokePermission({
530 sessionId: nativeSessionId,
531 toolCall: { toolCallId: "interaction_opaque", title: "Which target?" },
532 options: [
533 { optionId: "choice:a", name: "Same label", kind: "allow_once" },
534 { optionId: "choice:b", name: "Same label", kind: "allow_once" },
535 ],
536 })
537 .pipe(Effect.forkChild);
538 const opened = yield* h.waitForEvent((event) => event.type === "user-input.requested");
539 expect(opened.payload.questions[0]?.allowCustomAnswer).toBe(false);
540 expect(opened.payload.questions[0]?.options.map((option) => option.value)).toEqual([
541 "choice:a",
542 "choice:b",
543 ]);
544 const invalid = yield* h.adapter
545 .respondToUserInput(threadId, ApprovalRequestId.make(opened.requestId!), {
546 interaction_opaque: "Same label",
547 })
548 .pipe(Effect.exit);
549 expect(Exit.isFailure(invalid)).toBe(true);
550 expect(question.pollUnsafe()).toBeUndefined();
551 yield* h.adapter.respondToUserInput(threadId, ApprovalRequestId.make(opened.requestId!), {
552 interaction_opaque: "choice:b",
553 });
554 expect(yield* Fiber.join(question)).toEqual({
555 outcome: { outcome: "selected", optionId: "choice:b" },
556 });
557 }),
558 );
559​
560 it.effect("cancels native questions before waiting for the prompt to end", () =>
561 Effect.gen(function* () {
562 const h = yield* makeHarness();
563 yield* h.adapter.startSession({
564 threadId,
565 cwd: process.cwd(),
566 runtimeMode: "approval-required",
567 });
568 const sending = yield* h.adapter
569 .sendTurn({ threadId, input: "Ask a question" })
570 .pipe(Effect.forkChild);
571 yield* h.nextPrompt;
572 const question = yield* h
573 .invokePermission({
574 sessionId: nativeSessionId,
575 toolCall: { toolCallId: "interaction_cancel", title: "Continue?" },
576 options: [{ optionId: "yes", name: "Yes", kind: "allow_once" }],
577 })
578 .pipe(Effect.forkChild);
579 yield* h.waitForEvent((event) => event.type === "user-input.requested");
580 yield* h.adapter.interruptTurn(threadId);
581 expect(yield* Fiber.join(question)).toEqual({ outcome: { outcome: "cancelled" } });
582 yield* Fiber.join(sending);
583 const ended = yield* h.waitForEvent((event) => event.type === "turn.completed");
584 expect(ended.payload.state).toBe("cancelled");
585 expect(h.seen.some((event) => event.type === "user-input.resolved")).toBe(true);
586 }),
587 );
588​
589 it.effect("waits for native cancellation before a steer changes the model", () =>
590 Effect.gen(function* () {
591 const h = yield* makeHarness({ holdCancel: true });
592 yield* h.adapter.startSession({
593 threadId,
594 cwd: process.cwd(),
595 runtimeMode: "approval-required",
596 });
597 const first = yield* h.adapter
598 .sendTurn({ threadId, input: "First prompt" })
599 .pipe(Effect.forkChild);
600 yield* h.nextPrompt;
601 const marker = h.calls.length;
602 const second = yield* h.adapter
603 .sendTurn({
604 threadId,
605 input: "Steer the turn",
606 modelSelection: { instanceId, model: nativeAlternative },
607 })
608 .pipe(Effect.forkChild);
609 expect(yield* h.nextCancellation).toBe(1);
610 expect(h.calls.slice(marker)).toEqual(["cancel:1"]);
611 yield* h.emitNative({
612 _tag: "ContentDelta",
613 text: "The first prompt stopped.",
614 rawPayload: {},
615 });
616 yield* Deferred.succeed(h.cancelRelease, undefined);
617 const replacement = yield* h.nextPrompt;
618 expect(h.calls.slice(marker)).toEqual([
619 "cancel:1",
620 "drained:1",
621 `model:${nativeAlternative}`,
622 "mode:default",
623 "prompt:2",
624 ]);
625 yield* Deferred.succeed(replacement.result, { stopReason: "end_turn" });
626 const [oldResult, newResult] = yield* Effect.all([Fiber.join(first), Fiber.join(second)]);
627 expect(oldResult.turnId).toBe(newResult.turnId);
628 yield* h.waitForEvent((event) => event.type === "turn.completed");
629 expect(h.seen.filter((event) => event.type === "turn.completed")).toHaveLength(1);
630 expect((yield* h.adapter.listSessions())[0]).toMatchObject({
631 status: "ready",
632 activeTurnId: undefined,
633 model: nativeAlternative,
634 });
635 }),
636 );
637​
638 it.effect("rejects an unavailable steer model without cancelling current work", () =>
639 Effect.gen(function* () {
640 const h = yield* makeHarness();
641 yield* h.adapter.startSession({
642 threadId,
643 cwd: process.cwd(),
644 runtimeMode: "approval-required",
645 });
646 const first = yield* h.adapter
647 .sendTurn({ threadId, input: "Keep working" })
648 .pipe(Effect.forkChild);
649 const prompt = yield* h.nextPrompt;
650 const invalid = yield* h.adapter
651 .sendTurn({
652 threadId,
653 input: "Change model",
654 modelSelection: { instanceId, model: "not-in-this-account" },
655 })
656 .pipe(Effect.exit);
657 expect(Exit.isFailure(invalid)).toBe(true);
658 expect(h.calls.some((call) => call.startsWith("cancel:"))).toBe(false);
659 expect(h.hasActivePrompt()).toBe(true);
660 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
661 yield* Fiber.join(first);
662 }),
663 );
664​
665 it.effect("settles a failed steer configuration and allows a later turn", () =>
666 Effect.gen(function* () {
667 const h = yield* makeHarness();
668 yield* h.adapter.startSession({
669 threadId,
670 cwd: process.cwd(),
671 runtimeMode: "approval-required",
672 });
673 const first = yield* h.adapter.sendTurn({ threadId, input: "First" }).pipe(Effect.forkChild);
674 yield* h.nextPrompt;
675 h.controls.failModel = true;
676 const failed = yield* h.adapter
677 .sendTurn({
678 threadId,
679 input: "Replacement",
680 modelSelection: { instanceId, model: nativeAlternative },
681 })
682 .pipe(Effect.exit);
683 expect(Exit.isFailure(failed)).toBe(true);
684 yield* Fiber.join(first);
685 const ended = yield* h.waitForEvent((event) => event.type === "turn.completed");
686 expect(ended.payload.state).toBe("failed");
687 expect((yield* h.adapter.listSessions())[0]).toMatchObject({
688 status: "error",
689 activeTurnId: undefined,
690 });
691 const later = yield* h.adapter
692 .sendTurn({ threadId, input: "Try again" })
693 .pipe(Effect.forkChild);
694 const prompt = yield* h.nextPrompt;
695 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
696 const recovered = yield* Fiber.join(later);
697 expect(recovered.turnId).not.toBe(ended.turnId);
698 expect((yield* h.adapter.listSessions())[0]?.status).toBe("ready");
699 }),
700 );
701​
702 it.effect("cancels the native prompt if its send caller is interrupted", () =>
703 Effect.gen(function* () {
704 const h = yield* makeHarness();
705 yield* h.adapter.startSession({
706 threadId,
707 cwd: process.cwd(),
708 runtimeMode: "approval-required",
709 });
710 const sending = yield* h.adapter
711 .sendTurn({ threadId, input: "Keep working" })
712 .pipe(Effect.forkChild);
713 yield* h.nextPrompt;
714 yield* Fiber.interrupt(sending);
715 const ended = yield* h.waitForEvent((event) => event.type === "turn.completed");
716 expect(ended.payload.state).toBe("cancelled");
717 expect(h.hasActivePrompt()).toBe(false);
718 expect((yield* h.adapter.listSessions())[0]).toMatchObject({
719 status: "ready",
720 activeTurnId: undefined,
721 });
722 }),
723 );
724​
725 it.effect("tracks native commands that survive a turn and clears terminal tasks", () =>
726 Effect.gen(function* () {
727 const h = yield* makeHarness();
728 yield* h.adapter.startSession({
729 threadId,
730 cwd: process.cwd(),
731 runtimeMode: "approval-required",
732 });
733 const sending = yield* h.adapter
734 .sendTurn({ threadId, input: "Start a watcher" })
735 .pipe(Effect.forkChild);
736 const prompt = yield* h.nextPrompt;
737 yield* h.emitNative({
738 _tag: "ToolCallUpdated",
739 toolCall: {
740 toolCallId: "watcher-1",
741 kind: "execute",
742 status: "inProgress",
743 command: "watch files",
744 data: {},
745 },
746 rawPayload: {},
747 });
748 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
749 const turn = yield* Fiber.join(sending);
750 const started = yield* h.waitForEvent((event) => event.type === "task.started");
751 expect(started.payload.taskType).toBe("local_bash");
752 expect(started.turnId).toBe(turn.turnId);
753 yield* h.emitNative({
754 _tag: "ToolCallUpdated",
755 toolCall: { toolCallId: "watcher-1", kind: "execute", status: "completed", data: {} },
756 rawPayload: {},
757 });
758 const ended = yield* h.waitForEvent((event) => event.type === "task.completed");
759 expect(ended.payload.taskId).toBe(started.payload.taskId);
760 expect(ended.payload.status).toBe("completed");
761 }),
762 );
763​
764 it.effect(
765 "shows concurrent native subagent calls and their results without inventing metadata",
766 () =>
767 Effect.gen(function* () {
768 const h = yield* makeHarness();
769 yield* h.adapter.startSession({
770 threadId,
771 cwd: process.cwd(),
772 runtimeMode: "approval-required",
773 });
774 const sending = yield* h.adapter
775 .sendTurn({ threadId, input: "Review with subagents" })
776 .pipe(Effect.forkChild);
777 const prompt = yield* h.nextPrompt;
778 for (const id of ["trajectory:4", "trajectory:5"]) {
779 yield* h.emitNative(
780 nativeToolUpdate({
781 sessionUpdate: "tool_call",
782 toolCallId: id,
783 title: "Running start_subagent",
784 kind: "other",
785 status: "in_progress",
786 rawInput: {},
787 }),
788 );
789 const running = yield* h.waitForEvent((event) => event.type === "task.progress");
790 expect(running.payload).toEqual({
791 taskId: id,
792 taskType: "subagent",
793 toolUseId: id,
794 title: "Antigravity subagent",
795 description: "Antigravity subagent",
796 status: "running",
797 });
798 yield* h.emitNative(
799 nativeToolUpdate({
800 sessionUpdate: "tool_call_update",
801 toolCallId: id,
802 status: "in_progress",
803 }),
804 );
805 }
806 for (const [id, status, result] of [
807 ["trajectory:4", "completed", "No defects found."],
808 ["trajectory:5", "failed", "Subagent exceeded its limit."],
809 ] as const) {
810 yield* h.emitNative(
811 nativeToolUpdate({
812 sessionUpdate: "tool_call_update",
813 toolCallId: id,
814 status,
815 rawOutput: result,
816 }),
817 );
818 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
819 expect(completed.payload).toEqual({
820 taskId: id,
821 taskType: "subagent",
822 toolUseId: id,
823 title: "Antigravity subagent",
824 status,
825 summary: result,
826 });
827 }
828 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
829 const turn = yield* Fiber.join(sending);
830 yield* h.waitForEvent((event) => event.type === "turn.completed");
831 expect(
832 h.seen
833 .filter((event) => event.type.startsWith("task."))
834 .every((event) => event.turnId === turn.turnId),
835 ).toBe(true);
836 expect(h.seen.filter((event) => event.type.startsWith("item."))).toHaveLength(0);
837 expect(h.seen.filter((event) => event.type === "task.progress")).toHaveLength(2);
838 }),
839 );
840​
841 it.effect("waits for a replayed subagent's final status and result", () =>
842 Effect.gen(function* () {
843 const h = yield* makeHarness();
844 yield* h.adapter.startSession({
845 threadId,
846 cwd: process.cwd(),
847 runtimeMode: "approval-required",
848 });
849 // ACP history announces a completed tool first, even when its result failed.
850 yield* h.emitNative(
851 nativeToolUpdate({
852 sessionUpdate: "tool_call",
853 toolCallId: "replayed:4",
854 title: "Running start_subagent",
855 kind: "other",
856 status: "completed",
857 rawInput: "{}",
858 }),
859 );
860 yield* h.emitNative(
861 nativeToolUpdate({
862 sessionUpdate: "tool_call_update",
863 toolCallId: "replayed:4",
864 status: "failed",
865 rawOutput: "Review failed.",
866 }),
867 );
868 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
869 expect(completed.payload).toEqual({
870 taskId: "replayed:4",
871 taskType: "subagent",
872 toolUseId: "replayed:4",
873 title: "Antigravity subagent",
874 status: "failed",
875 summary: "Review failed.",
876 });
877 expect(h.seen.filter((event) => event.type.startsWith("task."))).toHaveLength(1);
878 }),
879 );
880​
881 it.effect("completes a live subagent delivered in one tool call", () =>
882 Effect.gen(function* () {
883 const h = yield* makeHarness();
884 yield* h.adapter.startSession({
885 threadId,
886 cwd: process.cwd(),
887 runtimeMode: "approval-required",
888 });
889 const sending = yield* h.adapter
890 .sendTurn({ threadId, input: "Review with subagents" })
891 .pipe(Effect.forkChild);
892 const prompt = yield* h.nextPrompt;
893 for (const [id, rawOutput] of [
894 ["live:4", "Review complete."],
895 ["live:5", undefined],
896 ] as const) {
897 yield* h.emitNative(
898 nativeToolUpdate({
899 sessionUpdate: "tool_call",
900 toolCallId: id,
901 title: "Running start_subagent",
902 kind: "other",
903 status: "completed",
904 rawInput: {},
905 ...(rawOutput ? { rawOutput } : {}),
906 }),
907 );
908 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
909 expect(completed.payload).toMatchObject({ taskId: id, status: "completed" });
910 expect(completed.payload.summary).toBe(rawOutput);
911 }
912 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
913 yield* Fiber.join(sending);
914 yield* h.waitForEvent((event) => event.type === "turn.completed");
915 expect(h.seen.filter((event) => event.type === "task.updated")).toHaveLength(0);
916 }),
917 );
918​
919 for (const settlement of ["cancelled", "interrupted", "completed"] as const) {
920 it.effect(`does not reopen a ${settlement} subagent on late merged updates`, () =>
921 Effect.gen(function* () {
922 const h = yield* makeHarness();
923 yield* h.adapter.startSession({
924 threadId,
925 cwd: process.cwd(),
926 runtimeMode: "approval-required",
927 });
928 const first = yield* h.adapter
929 .sendTurn({ threadId, input: "Start review" })
930 .pipe(Effect.forkChild);
931 const firstPrompt = yield* h.nextPrompt;
932 const started = nativeToolUpdate({
933 sessionUpdate: "tool_call",
934 toolCallId: "old:4",
935 title: "Running start_subagent",
936 kind: "other",
937 status: "in_progress",
938 rawInput: {},
939 });
940 yield* h.emitNative(started);
941 yield* h.waitForEvent((event) => event.type === "task.progress");
942 if (settlement === "cancelled") {
943 yield* h.adapter.interruptTurn(threadId);
944 } else {
945 if (settlement === "completed") {
946 yield* h.emitNative(
947 nativeToolUpdate(
948 {
949 sessionUpdate: "tool_call_update",
950 toolCallId: "old:4",
951 status: "completed",
952 rawOutput: "Original result.",
953 },
954 started.toolCall,
955 ),
956 );
957 }
958 yield* Deferred.succeed(firstPrompt.result, { stopReason: "end_turn" });
959 }
960 yield* Fiber.join(first);
961 yield* h.waitForEvent((event) => event.type === "turn.completed");
962 const second = yield* h.adapter
963 .sendTurn({ threadId, input: "Next review" })
964 .pipe(Effect.forkChild);
965 const secondPrompt = yield* h.nextPrompt;
966 for (const status of ["in_progress", "completed"] as const) {
967 yield* h.emitNative(
968 nativeToolUpdate(
969 {
970 sessionUpdate: "tool_call_update",
971 toolCallId: "old:4",
972 status,
973 rawOutput: "Late result.",
974 },
975 started.toolCall,
976 ),
977 );
978 }
979 yield* h.emitNative(
980 nativeToolUpdate({
981 sessionUpdate: "tool_call",
982 toolCallId: "new:4",
983 title: "Running start_subagent",
984 kind: "other",
985 status: "completed",
986 rawOutput: "New result.",
987 }),
988 );
989 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
990 expect(completed.payload.taskId).toBe("new:4");
991 yield* Deferred.succeed(secondPrompt.result, { stopReason: "end_turn" });
992 yield* Fiber.join(second);
993 yield* h.waitForEvent((event) => event.type === "turn.completed");
994 expect(h.seen.filter((event) => event.type === "task.progress")).toHaveLength(1);
995 expect(
996 h.seen.filter(
997 (event) => event.type === "task.completed" && event.payload.taskId === "old:4",
998 ),
999 ).toHaveLength(settlement === "completed" ? 1 : 0);
1000 }),
1001 );
1003​
1004 it.effect("keeps MCP identity when later updates omit metadata", () =>
1005 Effect.gen(function* () {
1006 const h = yield* makeHarness();
1007 yield* h.adapter.startSession({
1008 threadId,
1009 cwd: process.cwd(),
1010 runtimeMode: "approval-required",
1011 });
1012 const sending = yield* h.adapter
1013 .sendTurn({ threadId, input: "Run an MCP tool" })
1014 .pipe(Effect.forkChild);
1015 const prompt = yield* h.nextPrompt;
1016 const started = nativeToolUpdate({
1017 sessionUpdate: "tool_call",
1018 toolCallId: "mcp-4",
1019 title: "Running start_subagent",
1020 kind: "other",
1021 status: "in_progress",
1022 rawInput: { arguments: {} },
1023 _meta: { is_mcp_tool_call: true },
1024 });
1025 yield* h.emitNative(started);
1026 for (const status of ["in_progress", "completed"] as const) {
1027 yield* h.emitNative(
1028 nativeToolUpdate(
1030 sessionUpdate: "tool_call_update",
1031 toolCallId: "mcp-4",
1032 status,
1033 rawOutput: "MCP output.",
1034 },
1035 started.toolCall,
1036 ),
1037 );
1039 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1040 yield* Fiber.join(sending);
1041 yield* h.waitForEvent((event) => event.type === "turn.completed");
1042 expect(h.seen.filter((event) => event.type.startsWith("task."))).toHaveLength(0);
1043 expect(h.seen.filter((event) => event.type === "item.updated")).toHaveLength(2);
1044 expect(h.seen.filter((event) => event.type === "item.completed")).toHaveLength(1);
1045 }),
1046 );
1047​
1048 it.effect("shows pending subagents and closes a denied invocation", () =>
1049 Effect.gen(function* () {
1050 const h = yield* makeHarness();
1051 yield* h.adapter.startSession({
1052 threadId,
1053 cwd: process.cwd(),
1054 runtimeMode: "approval-required",
1055 });
1056 yield* h.emitNative(
1057 nativeToolUpdate({
1058 sessionUpdate: "tool_call",
1059 toolCallId: "permission-1",
1060 title: "Run start_subagent?",
1061 kind: "other",
1062 status: "pending",
1063 rawInput: {},
1064 }),
1065 );
1066 const pending = yield* h.waitForEvent((event) => event.type === "task.progress");
1067 expect(pending.payload.status).toBe("pending");
1068 yield* h.emitNative(
1069 nativeToolUpdate({
1070 sessionUpdate: "tool_call_update",
1071 toolCallId: "permission-1",
1072 status: "failed",
1073 }),
1074 );
1075 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
1076 expect(completed.payload.status).toBe("failed");
1077 }),
1078 );
1079​
1080 for (const stop of ["cancel", "steer", "disconnect", "end_turn"] as const) {
1081 it.effect(`settles open subagent calls on ${stop}`, () =>
1082 Effect.gen(function* () {
1083 const h = yield* makeHarness();
1084 yield* h.adapter.startSession({
1085 threadId,
1086 cwd: process.cwd(),
1087 runtimeMode: "approval-required",
1088 });
1089 const sending = yield* h.adapter
1090 .sendTurn({ threadId, input: "Start a subagent" })
1091 .pipe(Effect.forkChild);
1092 const prompt = yield* h.nextPrompt;
1093 yield* h.emitNative(
1094 nativeToolUpdate({
1095 sessionUpdate: "tool_call",
1096 toolCallId: "trajectory:4",
1097 title: "Running start_subagent",
1098 kind: "other",
1099 status: "in_progress",
1100 rawInput: {},
1101 }),
1102 );
1103 yield* h.waitForEvent((event) => event.type === "task.progress");
1104 if (stop === "disconnect") {
1105 yield* h.emitNative({
1106 _tag: "ConnectionTerminated",
1107 error: new AcpErrors.AcpTransportError({ detail: "Process exited.", cause: undefined }),
1108 });
1109 } else if (stop === "cancel") {
1110 yield* h.adapter.interruptTurn(threadId);
1111 } else if (stop === "steer") {
1112 const steering = yield* h.adapter
1113 .sendTurn({ threadId, input: "Change direction" })
1114 .pipe(Effect.forkChild);
1115 const replacement = yield* h.nextPrompt;
1116 yield* Deferred.succeed(replacement.result, { stopReason: "end_turn" });
1117 yield* Fiber.join(steering);
1118 } else {
1119 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1121 const settled = yield* h.waitForEvent((event) => event.type === "task.updated");
1122 expect(settled.payload).toMatchObject({
1123 taskId: "trajectory:4",
1124 title: "Antigravity subagent",
1125 taskType: "subagent",
1126 status:
1127 stop === "disconnect"
1128 ? "failed"
1129 : stop === "cancel" || stop === "steer"
1130 ? "cancelled"
1131 : "interrupted",
1132 });
1133 if (stop === "disconnect")
1134 yield* h.waitForEvent((event) => event.type === "session.exited");
1135 else yield* Fiber.join(sending);
1136 }),
1137 );
1139​
1140 it.effect("retires a prompt cancelled before native dispatch", () =>
1141 Effect.gen(function* () {
1142 const h = yield* makeHarness({ holdDispatch: true });
1143 yield* h.adapter.startSession({
1144 threadId,
1145 cwd: process.cwd(),
1146 runtimeMode: "approval-required",
1147 });
1148 const sending = yield* h.adapter
1149 .sendTurn({ threadId, input: "Do not dispatch this prompt" })
1150 .pipe(Effect.forkChild);
1151 yield* Deferred.await(h.dispatchStarted);
1152 yield* Fiber.interrupt(sending);
1153 yield* Deferred.succeed(h.dispatchRelease, undefined);
1154 const cancelled = yield* h.waitForEvent((event) => event.type === "turn.completed");
1155 expect(cancelled.payload.state).toBe("cancelled");
1156 expect(h.calls.some((call) => call.startsWith("prompt:"))).toBe(false);
1157 expect(h.hasActivePrompt()).toBe(false);
1158 const later = yield* h.adapter
1159 .sendTurn({ threadId, input: "This prompt can run" })
1160 .pipe(Effect.forkChild);
1161 const prompt = yield* h.nextPrompt;
1162 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1163 const result = yield* Fiber.join(later);
1164 expect(result.turnId).not.toBe(cancelled.turnId);
1165 expect(h.calls.filter((call) => call.startsWith("prompt:"))).toEqual(["prompt:1"]);
1166 }),
1167 );
1168​
1169 it.effect("awaits full process cleanup for concurrent stop requests", () =>
1170 Effect.gen(function* () {
1171 const h = yield* makeHarness({ holdClose: true });
1172 yield* h.adapter.startSession({
1173 threadId,
1174 cwd: process.cwd(),
1175 runtimeMode: "approval-required",
1176 });
1177 const stopping = yield* h.adapter.stopSession(threadId).pipe(Effect.forkChild);
1178 yield* Deferred.await(h.closeStarted);
1179 const registeredStop = h.stops[0];
1180 if (!registeredStop) return yield* Effect.die("Missing process cleanup registration");
1181 const signOutStop = yield* registeredStop.pipe(Effect.forkChild({ startImmediately: true }));
1182 expect(signOutStop.pollUnsafe()).toBeUndefined();
1183 yield* Deferred.succeed(h.closeRelease, undefined);
1184 yield* Effect.all([Fiber.join(stopping), Fiber.join(signOutStop)]);
1185 yield* h.waitForEvent((event) => event.type === "session.exited");
1186 expect(h.controls.closed).toBe(1);
1187 expect(h.seen.filter((event) => event.type === "session.exited")).toHaveLength(1);
1188 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1189 }),
1190 );
1191​
1192 it.effect("stops a session while its prompt is waiting to dispatch", () =>
1193 Effect.gen(function* () {
1194 const h = yield* makeHarness({ holdDispatch: true });
1195 yield* h.adapter.startSession({
1196 threadId,
1197 cwd: process.cwd(),
1198 runtimeMode: "approval-required",
1199 });
1200 const sending = yield* h.adapter
1201 .sendTurn({ threadId, input: "Do not dispatch after stop" })
1202 .pipe(Effect.forkChild);
1203 yield* Deferred.await(h.dispatchStarted);
1204 yield* h.adapter.stopSession(threadId);
1205 yield* Fiber.await(sending);
1206 yield* Deferred.succeed(h.dispatchRelease, undefined);
1207 expect(h.calls.some((call) => call.startsWith("prompt:"))).toBe(false);
1208 expect(h.controls.closed).toBe(1);
1209 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1210 }),
1211 );
1212​
1213 it.effect("propagates idle process exits and rejects stale session use", () =>
1214 Effect.gen(function* () {
1215 const h = yield* makeHarness();
1216 yield* h.adapter.startSession({
1217 threadId,
1218 cwd: process.cwd(),
1219 runtimeMode: "approval-required",
1220 });
1221 yield* h.emitNative({
1222 _tag: "ConnectionTerminated",
1223 error: new AcpErrors.AcpTransportError({ detail: "Process exited.", cause: undefined }),
1224 });
1225 const exited = yield* h.waitForEvent((event) => event.type === "session.exited");
1226 expect(exited.payload.exitKind).toBe("error");
1227 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1228 expect(
1229 Exit.isFailure(yield* h.adapter.sendTurn({ threadId, input: "Hello" }).pipe(Effect.exit)),
1230 ).toBe(true);
1231 }),
1232 );
1233​
1234 it.effect("reports hidden login requests as sign-in required and clears account metadata", () =>
1235 Effect.gen(function* () {
1236 const h = yield* makeHarness();
1237 h.controls.failAuth = true;
1238 const started = yield* h.adapter
1239 .startSession({ threadId, cwd: process.cwd(), runtimeMode: "approval-required" })
1240 .pipe(Effect.exit);
1241 expect(Exit.isFailure(started)).toBe(true);
1242 expect(h.controls.authInvalidations).toBe(1);
1243 expect(h.controls.closed).toBe(1);
1244 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1245 }),
1246 );
1247​
1248 it.effect("serves client file reads and writes only inside the session roots", () =>
1249 Effect.gen(function* () {
1250 const fs = yield* FileSystem.FileSystem;
1251 const path = yield* Path.Path;
1252 const h = yield* makeHarness();
1253 const { attachmentsDir } = yield* ServerConfig;
1254 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-fs-" });
1255 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-outside-" });
1256 yield* fs.writeFileString(path.join(cwd, "notes.txt"), "one\ntwo\nthree\n");
1257 yield* h.adapter.startSession({ threadId, cwd, runtimeMode: "approval-required" });
1258 expect(h.launches[0]?.clientFileSystem).toBe(true);
1259 expect(h.launches[0]?.additionalDirectories).toEqual([attachmentsDir]);
1260 const read = h.fileHandlers.read;
1261 const write = h.fileHandlers.write;
1262 if (!read || !write) return yield* Effect.die("File handlers were not registered.");
1263​
1264 const full = yield* read({ sessionId: nativeSessionId, path: path.join(cwd, "notes.txt") });
1265 expect(full.content).toBe("one\ntwo\nthree\n");
1266 const window = yield* read({
1267 sessionId: nativeSessionId,
1268 path: path.join(cwd, "notes.txt"),
1269 line: 2,
1270 limit: 1,
1271 });
1272 expect(window.content).toBe("two");
1273​
1274 yield* write({
1275 sessionId: nativeSessionId,
1276 path: path.join(cwd, "nested", "new.txt"),
1277 content: "created",
1278 });
1279 expect(yield* fs.readFileString(path.join(cwd, "nested", "new.txt"))).toBe("created");
1280​
1281 const escape = yield* write({
1282 sessionId: nativeSessionId,
1283 path: path.join(outside, "escape.txt"),
1284 content: "nope",
1285 }).pipe(Effect.flip);
1286 expect(escape._tag).toBe("AcpRequestError");
1287 expect(yield* fs.exists(path.join(outside, "escape.txt"))).toBe(false);
1288 const missing = yield* read({
1289 sessionId: nativeSessionId,
1290 path: path.join(cwd, "missing.txt"),
1291 }).pipe(Effect.flip);
1292 expect(missing._tag).toBe("AcpRequestError");
1293 }).pipe(Effect.scoped),
1294 );
1295​
1296 it.effect("does not launch a process for a disabled instance or invalid resume cursor", () =>
1297 Effect.gen(function* () {
1298 const disabled = yield* makeHarness({ enabled: false });
1299 const rejected = yield* disabled.adapter
1300 .startSession({ threadId, cwd: process.cwd(), runtimeMode: "approval-required" })
1301 .pipe(Effect.exit);
1302 expect(Exit.isFailure(rejected)).toBe(true);
1303 expect(disabled.launches).toHaveLength(0);
1304 const active = yield* makeHarness();
1305 const stale = yield* active.adapter
1306 .startSession({
1307 threadId,
1308 cwd: process.cwd(),
1309 runtimeMode: "approval-required",
1310 resumeCursor: { sessionId: nativeSessionId },
1311 })
1312 .pipe(Effect.exit);
1313 expect(Exit.isFailure(stale)).toBe(true);
1314 expect(active.launches).toHaveLength(0);
1315 }),
1316 );
1317});