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

AntigravityAdapter.test.ts

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