Open History to see the last commit
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>;
54}
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) };
70}
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 // The adapter resolves the cwd it was given through the host Path.
425 expect(second.cwd).toBe((yield* Path.Path).resolve("/tmp"));
426 expect(h.launches[1]?.resumeSessionId).toBe(nativeSessionId);
427 expect(h.calls).toEqual([
428 "start",
429 `model:${nativeAlternative}`,
430 "mode:auto_edit",
431 "start",
432 `model:${nativeAlternative}`,
433 "mode:auto_edit",
434 ]);
435 expect(h.commandUpdates.at(-1)?.map((command) => command.name)).toEqual(["plan", "logout"]);
436 expect(h.adapter.capabilities.supportsConversationRollback).toBe(false);
437 const rollback = yield* h.adapter.rollbackThread(threadId, 1).pipe(Effect.exit);
438 expect(Exit.isFailure(rollback)).toBe(true);
439 }),
440 );
441
442 it.effect("keeps thoughts, native command results, and replies on the active turn", () =>
443 Effect.gen(function* () {
444 const h = yield* makeHarness();
445 yield* h.adapter.startSession({
446 threadId,
447 cwd: process.cwd(),
448 runtimeMode: "approval-required",
449 });
450 const sending = yield* h.adapter
451 .sendTurn({ threadId, input: "Read the file" })
452 .pipe(Effect.forkChild);
453 const prompt = yield* h.nextPrompt;
454 yield* h.emitNative({ _tag: "ThoughtDelta", text: "I will read it.", rawPayload: {} });
455 yield* h.emitNative({
456 _tag: "ToolCallUpdated",
457 toolCall: {
458 toolCallId: "command-1",
459 kind: "execute",
460 status: "completed",
461 data: {
462 rawInput: { CommandLine: "cat probe.txt", Cwd: "/tmp" },
463 rawOutput: { combinedOutput: "after\n", exitCode: 0 },
464 },
465 },
466 rawPayload: {},
467 });
468 yield* h.emitNative({ _tag: "ContentDelta", text: "The file says after.", rawPayload: {} });
469 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
470 const result = yield* Fiber.join(sending);
471 yield* h.waitForEvent((event) => event.type === "turn.completed");
472 const deltas = h.seen.filter((event) => event.type === "content.delta");
473 expect(deltas.map((event) => event.payload.streamKind)).toEqual([
474 "reasoning_text",
475 "assistant_text",
476 ]);
477 expect(deltas.every((event) => event.turnId === result.turnId)).toBe(true);
478 const tool = h.seen.find(
479 (event) =>
480 event.type === "item.completed" && event.payload.itemType === "command_execution",
481 );
482 expect(tool?.type === "item.completed" ? tool.payload.data : undefined).toMatchObject({
483 command: "cat probe.txt",
484 cwd: "/tmp",
485 item: { aggregatedOutput: "after\n", exitCode: 0 },
486 });
487 }),
488 );
489
490 it.effect("does not auto-approve a remaining native request in full access", () =>
491 Effect.gen(function* () {
492 const h = yield* makeHarness();
493 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
494 const permission = yield* h
495 .invokePermission({
496 sessionId: nativeSessionId,
497 toolCall: { toolCallId: "write-1", kind: "edit", title: "Write probe.txt" },
498 options: [
499 { optionId: "native:allow", name: "Allow", kind: "allow_once" },
500 { optionId: "native:deny", name: "Deny", kind: "reject_once" },
501 ],
502 })
503 .pipe(Effect.forkChild);
504 const opened = yield* h.waitForEvent((event) => event.type === "request.opened");
505 expect(h.calls).toContain("mode:yolo");
506 expect(opened.payload.options).toEqual([
507 { decision: "accept", label: "Allow once" },
508 { decision: "decline", label: "Deny" },
509 { decision: "cancel", label: "Cancel" },
510 ]);
511 expect(permission.pollUnsafe()).toBeUndefined();
512 const always = yield* h.adapter
513 .respondToRequest(threadId, ApprovalRequestId.make(opened.requestId!), "acceptAlways")
514 .pipe(Effect.exit);
515 expect(Exit.isFailure(always)).toBe(true);
516 yield* h.adapter.respondToRequest(
517 threadId,
518 ApprovalRequestId.make(opened.requestId!),
519 "decline",
520 );
521 expect(yield* Fiber.join(permission)).toEqual({
522 outcome: { outcome: "selected", optionId: "native:deny" },
523 });
524 }),
525 );
526
527 it.effect("returns opaque native question choices and rejects ambiguous labels", () =>
528 Effect.gen(function* () {
529 const h = yield* makeHarness();
530 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
531 const question = yield* h
532 .invokePermission({
533 sessionId: nativeSessionId,
534 toolCall: { toolCallId: "interaction_opaque", title: "Which target?" },
535 options: [
536 { optionId: "choice:a", name: "Same label", kind: "allow_once" },
537 { optionId: "choice:b", name: "Same label", kind: "allow_once" },
538 ],
539 })
540 .pipe(Effect.forkChild);
541 const opened = yield* h.waitForEvent((event) => event.type === "user-input.requested");
542 expect(opened.payload.questions[0]?.allowCustomAnswer).toBe(false);
543 expect(opened.payload.questions[0]?.options.map((option) => option.value)).toEqual([
544 "choice:a",
545 "choice:b",
546 ]);
547 const invalid = yield* h.adapter
548 .respondToUserInput(threadId, ApprovalRequestId.make(opened.requestId!), {
549 interaction_opaque: "Same label",
550 })
551 .pipe(Effect.exit);
552 expect(Exit.isFailure(invalid)).toBe(true);
553 expect(question.pollUnsafe()).toBeUndefined();
554 yield* h.adapter.respondToUserInput(threadId, ApprovalRequestId.make(opened.requestId!), {
555 interaction_opaque: "choice:b",
556 });
557 expect(yield* Fiber.join(question)).toEqual({
558 outcome: { outcome: "selected", optionId: "choice:b" },
559 });
560 }),
561 );
562
563 it.effect("cancels native questions before waiting for the prompt to end", () =>
564 Effect.gen(function* () {
565 const h = yield* makeHarness();
566 yield* h.adapter.startSession({
567 threadId,
568 cwd: process.cwd(),
569 runtimeMode: "approval-required",
570 });
571 const sending = yield* h.adapter
572 .sendTurn({ threadId, input: "Ask a question" })
573 .pipe(Effect.forkChild);
574 yield* h.nextPrompt;
575 const question = yield* h
576 .invokePermission({
577 sessionId: nativeSessionId,
578 toolCall: { toolCallId: "interaction_cancel", title: "Continue?" },
579 options: [{ optionId: "yes", name: "Yes", kind: "allow_once" }],
580 })
581 .pipe(Effect.forkChild);
582 yield* h.waitForEvent((event) => event.type === "user-input.requested");
583 yield* h.adapter.interruptTurn(threadId);
584 expect(yield* Fiber.join(question)).toEqual({ outcome: { outcome: "cancelled" } });
585 yield* Fiber.join(sending);
586 const ended = yield* h.waitForEvent((event) => event.type === "turn.completed");
587 expect(ended.payload.state).toBe("cancelled");
588 expect(h.seen.some((event) => event.type === "user-input.resolved")).toBe(true);
589 }),
590 );
591
592 it.effect("waits for native cancellation before a steer changes the model", () =>
593 Effect.gen(function* () {
594 const h = yield* makeHarness({ holdCancel: true });
595 yield* h.adapter.startSession({
596 threadId,
597 cwd: process.cwd(),
598 runtimeMode: "approval-required",
599 });
600 const first = yield* h.adapter
601 .sendTurn({ threadId, input: "First prompt" })
602 .pipe(Effect.forkChild);
603 const initialPrompt = yield* h.nextPrompt;
604 expect(initialPrompt.content).toEqual([
605 { type: "text", text: "First prompt" },
606 { type: "text", text: expect.stringContaining(`Antigravity harness, as ${nativeDefault}`) },
607 ]);
608 const marker = h.calls.length;
609 const second = yield* h.adapter
610 .sendTurn({
611 threadId,
612 input: "Steer the turn",
613 modelSelection: { instanceId, model: nativeAlternative },
614 })
615 .pipe(Effect.forkChild);
616 expect(yield* h.nextCancellation).toBe(1);
617 expect(h.calls.slice(marker)).toEqual(["cancel:1"]);
618 yield* h.emitNative({
619 _tag: "ContentDelta",
620 text: "The first prompt stopped.",
621 rawPayload: {},
622 });
623 yield* Deferred.succeed(h.cancelRelease, undefined);
624 const replacement = yield* h.nextPrompt;
625 expect(replacement.content).toEqual([
626 { type: "text", text: "Steer the turn" },
627 {
628 type: "text",
629 text: expect.stringContaining(`Antigravity harness, as ${nativeAlternative}`),
630 },
631 ]);
632 expect(h.calls.slice(marker)).toEqual([
633 "cancel:1",
634 "drained:1",
635 `model:${nativeAlternative}`,
636 "mode:default",
637 "prompt:2",
638 ]);
639 yield* Deferred.succeed(replacement.result, { stopReason: "end_turn" });
640 const [oldResult, newResult] = yield* Effect.all([Fiber.join(first), Fiber.join(second)]);
641 expect(oldResult.turnId).toBe(newResult.turnId);
642 yield* h.waitForEvent((event) => event.type === "turn.completed");
643 expect(h.seen.filter((event) => event.type === "turn.completed")).toHaveLength(1);
644 expect((yield* h.adapter.listSessions())[0]).toMatchObject({
645 status: "ready",
646 activeTurnId: undefined,
647 model: nativeAlternative,
648 });
649 }),
650 );
651
652 it.effect("rejects an unavailable steer model without cancelling current work", () =>
653 Effect.gen(function* () {
654 const h = yield* makeHarness();
655 yield* h.adapter.startSession({
656 threadId,
657 cwd: process.cwd(),
658 runtimeMode: "approval-required",
659 });
660 const first = yield* h.adapter
661 .sendTurn({ threadId, input: "Keep working" })
662 .pipe(Effect.forkChild);
663 const prompt = yield* h.nextPrompt;
664 const invalid = yield* h.adapter
665 .sendTurn({
666 threadId,
667 input: "Change model",
668 modelSelection: { instanceId, model: "not-in-this-account" },
669 })
670 .pipe(Effect.exit);
671 expect(Exit.isFailure(invalid)).toBe(true);
672 expect(h.calls.some((call) => call.startsWith("cancel:"))).toBe(false);
673 expect(h.hasActivePrompt()).toBe(true);
674 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
675 yield* Fiber.join(first);
676 }),
677 );
678
679 it.effect("settles a failed steer configuration and allows a later turn", () =>
680 Effect.gen(function* () {
681 const h = yield* makeHarness();
682 yield* h.adapter.startSession({
683 threadId,
684 cwd: process.cwd(),
685 runtimeMode: "approval-required",
686 });
687 const first = yield* h.adapter.sendTurn({ threadId, input: "First" }).pipe(Effect.forkChild);
688 yield* h.nextPrompt;
689 h.controls.failModel = true;
690 const failed = yield* h.adapter
691 .sendTurn({
692 threadId,
693 input: "Replacement",
694 modelSelection: { instanceId, model: nativeAlternative },
695 })
696 .pipe(Effect.exit);
697 expect(Exit.isFailure(failed)).toBe(true);
698 yield* Fiber.join(first);
699 const ended = yield* h.waitForEvent((event) => event.type === "turn.completed");
700 expect(ended.payload.state).toBe("failed");
701 expect((yield* h.adapter.listSessions())[0]).toMatchObject({
702 status: "error",
703 activeTurnId: undefined,
704 });
705 const later = yield* h.adapter
706 .sendTurn({ threadId, input: "Try again" })
707 .pipe(Effect.forkChild);
708 const prompt = yield* h.nextPrompt;
709 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
710 const recovered = yield* Fiber.join(later);
711 expect(recovered.turnId).not.toBe(ended.turnId);
712 expect((yield* h.adapter.listSessions())[0]?.status).toBe("ready");
713 }),
714 );
715
716 it.effect("cancels the native prompt if its send caller is interrupted", () =>
717 Effect.gen(function* () {
718 const h = yield* makeHarness();
719 yield* h.adapter.startSession({
720 threadId,
721 cwd: process.cwd(),
722 runtimeMode: "approval-required",
723 });
724 const sending = yield* h.adapter
725 .sendTurn({ threadId, input: "Keep working" })
726 .pipe(Effect.forkChild);
727 yield* h.nextPrompt;
728 yield* Fiber.interrupt(sending);
729 const ended = yield* h.waitForEvent((event) => event.type === "turn.completed");
730 expect(ended.payload.state).toBe("cancelled");
731 expect(h.hasActivePrompt()).toBe(false);
732 expect((yield* h.adapter.listSessions())[0]).toMatchObject({
733 status: "ready",
734 activeTurnId: undefined,
735 });
736 }),
737 );
738
739 it.effect("tracks native commands that survive a turn and clears terminal tasks", () =>
740 Effect.gen(function* () {
741 const h = yield* makeHarness();
742 yield* h.adapter.startSession({
743 threadId,
744 cwd: process.cwd(),
745 runtimeMode: "approval-required",
746 });
747 const sending = yield* h.adapter
748 .sendTurn({ threadId, input: "Start a watcher" })
749 .pipe(Effect.forkChild);
750 const prompt = yield* h.nextPrompt;
751 yield* h.emitNative({
752 _tag: "ToolCallUpdated",
753 toolCall: {
754 toolCallId: "watcher-1",
755 kind: "execute",
756 status: "inProgress",
757 command: "watch files",
758 data: {},
759 },
760 rawPayload: {},
761 });
762 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
763 const turn = yield* Fiber.join(sending);
764 const started = yield* h.waitForEvent((event) => event.type === "task.started");
765 expect(started.payload.taskType).toBe("local_bash");
766 expect(started.turnId).toBe(turn.turnId);
767 yield* h.emitNative({
768 _tag: "ToolCallUpdated",
769 toolCall: { toolCallId: "watcher-1", kind: "execute", status: "completed", data: {} },
770 rawPayload: {},
771 });
772 const ended = yield* h.waitForEvent((event) => event.type === "task.completed");
773 expect(ended.payload.taskId).toBe(started.payload.taskId);
774 expect(ended.payload.status).toBe("completed");
775 }),
776 );
777
778 it.effect("keeps a launched batch active while child tools continue", () =>
779 Effect.gen(function* () {
780 const h = yield* makeHarness();
781 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
782 const sending = yield* h.adapter
783 .sendTurn({ threadId, input: "Run two readers in one batch" })
784 .pipe(Effect.forkChild);
785 const prompt = yield* h.nextPrompt;
786 // ACP 1.1.1 capture: one launch call covers both children and returns
787 // only its description before either child finishes.
788 const started = nativeToolUpdate({
789 sessionUpdate: "tool_call",
790 toolCallId: `${nativeSessionId}:2`,
791 title: "Running start_subagent",
792 kind: "other",
793 status: "in_progress",
794 rawInput: {},
795 });
796 yield* h.emitNative(started);
797 yield* h.waitForEvent((event) => event.type === "task.progress");
798 yield* h.emitNative(
799 nativeToolUpdate(
800 {
801 sessionUpdate: "tool_call_update",
802 toolCallId: started.toolCall.toolCallId,
803 status: "completed",
804 rawOutput: "Launch subagents",
805 },
806 started.toolCall,
807 ),
808 );
809 const launched = yield* h.waitForEvent((event) => event.type === "task.progress");
810 expect(launched.payload).toMatchObject({
811 taskId: started.toolCall.toolCallId,
812 title: "Antigravity subagent batch",
813 taskType: "subagent_batch",
814 description: "Launch subagents",
815 status: "running",
816 });
817 for (const child of ["alpha", "beta"]) {
818 yield* h.emitNative(
819 nativeToolUpdate({
820 sessionUpdate: "tool_call",
821 toolCallId: `${child}:1`,
822 title: "Read file",
823 kind: "read",
824 status: "completed",
825 rawOutput: "File contents",
826 }),
827 );
828 }
829 yield* h.drainEvents;
830 expect(h.seen.filter((event) => event.type === "task.completed")).toHaveLength(0);
831 expect(h.seen.filter((event) => event.type === "task.updated")).toHaveLength(0);
832 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
833 yield* Fiber.join(sending);
834 yield* h.waitForEvent((event) => event.type === "turn.completed");
835 expect(h.seen.filter((event) => event.type === "task.completed")).toHaveLength(0);
836 expect(h.seen.find((event) => event.type === "task.updated")?.payload).toMatchObject({
837 taskId: started.toolCall.toolCallId,
838 status: "idle",
839 description: "Turn ended. Individual agent status is unavailable.",
840 timelineBypass: true,
841 });
842 }),
843 );
844
845 it.effect("waits for a replayed subagent's final status and result", () =>
846 Effect.gen(function* () {
847 const h = yield* makeHarness();
848 yield* h.adapter.startSession({
849 threadId,
850 cwd: process.cwd(),
851 runtimeMode: "approval-required",
852 });
853 // ACP history announces a completed tool first, even when its result failed.
854 yield* h.emitNative(
855 nativeToolUpdate({
856 sessionUpdate: "tool_call",
857 toolCallId: "replayed:4",
858 title: "Running start_subagent",
859 kind: "other",
860 status: "completed",
861 rawInput: "{}",
862 }),
863 );
864 yield* h.emitNative(
865 nativeToolUpdate({
866 sessionUpdate: "tool_call_update",
867 toolCallId: "replayed:4",
868 status: "failed",
869 rawOutput: "Review failed.",
870 }),
871 );
872 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
873 expect(completed.payload).toEqual({
874 taskId: "replayed:4",
875 taskType: "subagent_batch",
876 toolUseId: "replayed:4",
877 title: "Antigravity subagent batch",
878 status: "failed",
879 summary: "Review failed.",
880 });
881 expect(h.seen.filter((event) => event.type.startsWith("task."))).toHaveLength(1);
882 }),
883 );
884
885 it.effect("keeps one-message launches active and ignores late updates after settlement", () =>
886 Effect.gen(function* () {
887 const h = yield* makeHarness();
888 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
889 const first = yield* h.adapter
890 .sendTurn({ threadId, input: "Start readers" })
891 .pipe(Effect.forkChild);
892 const firstPrompt = yield* h.nextPrompt;
893 const launches = ["Launch readers", undefined].map((rawOutput, index) =>
894 nativeToolUpdate({
895 sessionUpdate: "tool_call",
896 toolCallId: `old:${index}`,
897 title: "Running start_subagent",
898 kind: "other",
899 status: "completed",
900 rawInput: {},
901 ...(rawOutput ? { rawOutput } : {}),
902 }),
903 );
904 for (const launch of launches) yield* h.emitNative(launch);
905 yield* h.drainEvents;
906 expect(h.seen.filter((event) => event.type === "task.progress")).toHaveLength(2);
907 expect(h.seen.filter((event) => event.type === "task.completed")).toHaveLength(0);
908 yield* Deferred.succeed(firstPrompt.result, { stopReason: "end_turn" });
909 yield* Fiber.join(first);
910 yield* h.waitForEvent((event) => event.type === "turn.completed");
911 const second = yield* h.adapter
912 .sendTurn({ threadId, input: "Next task" })
913 .pipe(Effect.forkChild);
914 const secondPrompt = yield* h.nextPrompt;
915 for (const launch of launches) {
916 for (const status of ["in_progress", "completed", "failed"] as const) {
917 yield* h.emitNative(
918 nativeToolUpdate(
919 {
920 sessionUpdate: "tool_call_update",
921 toolCallId: launch.toolCall.toolCallId,
922 status,
923 rawOutput: "Late update",
924 },
925 launch.toolCall,
926 ),
927 );
928 }
929 }
930 yield* h.drainEvents;
931 expect(h.seen.filter((event) => event.type === "task.progress")).toHaveLength(2);
932 expect(h.seen.filter((event) => event.type === "task.updated")).toHaveLength(2);
933 expect(h.seen.filter((event) => event.type === "task.completed")).toHaveLength(0);
934 yield* Deferred.succeed(secondPrompt.result, { stopReason: "end_turn" });
935 yield* Fiber.join(second);
936 }),
937 );
938
939 it.effect("does not report a historical launch as running or completed work", () =>
940 Effect.gen(function* () {
941 const h = yield* makeHarness();
942 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
943 const launch = nativeToolUpdate({
944 sessionUpdate: "tool_call",
945 toolCallId: "history:2",
946 title: "Running start_subagent",
947 kind: "other",
948 status: "completed",
949 rawInput: {},
950 });
951 yield* h.emitNative(launch);
952 yield* h.emitNative(
953 nativeToolUpdate(
954 {
955 sessionUpdate: "tool_call_update",
956 toolCallId: launch.toolCall.toolCallId,
957 status: "completed",
958 rawOutput: "Launch readers",
959 },
960 launch.toolCall,
961 ),
962 );
963 yield* h.drainEvents;
964 expect(h.seen.filter((event) => event.type.startsWith("task."))).toMatchObject([
965 {
966 type: "task.updated",
967 payload: { status: "idle", timelineBypass: true },
968 },
969 ]);
970 }),
971 );
972
973 it.effect("keeps MCP identity when later updates omit metadata", () =>
974 Effect.gen(function* () {
975 const h = yield* makeHarness();
976 yield* h.adapter.startSession({
977 threadId,
978 cwd: process.cwd(),
979 runtimeMode: "approval-required",
980 });
981 const sending = yield* h.adapter
982 .sendTurn({ threadId, input: "Run an MCP tool" })
983 .pipe(Effect.forkChild);
984 const prompt = yield* h.nextPrompt;
985 const started = nativeToolUpdate({
986 sessionUpdate: "tool_call",
987 toolCallId: "mcp-4",
988 title: "Running start_subagent",
989 kind: "other",
990 status: "in_progress",
991 rawInput: { arguments: {} },
992 _meta: { is_mcp_tool_call: true },
993 });
994 yield* h.emitNative(started);
995 for (const status of ["in_progress", "completed"] as const) {
996 yield* h.emitNative(
997 nativeToolUpdate(
998 {
999 sessionUpdate: "tool_call_update",
1000 toolCallId: "mcp-4",
1001 status,
1002 rawOutput: "MCP output.",
1003 },
1004 started.toolCall,
1005 ),
1006 );
1007 }
1008 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1009 yield* Fiber.join(sending);
1010 yield* h.waitForEvent((event) => event.type === "turn.completed");
1011 expect(h.seen.filter((event) => event.type.startsWith("task."))).toHaveLength(0);
1012 expect(h.seen.filter((event) => event.type === "item.updated")).toHaveLength(2);
1013 expect(h.seen.filter((event) => event.type === "item.completed")).toHaveLength(1);
1014 }),
1015 );
1016
1017 it.effect("shows pending subagents and closes a denied invocation", () =>
1018 Effect.gen(function* () {
1019 const h = yield* makeHarness();
1020 yield* h.adapter.startSession({
1021 threadId,
1022 cwd: process.cwd(),
1023 runtimeMode: "approval-required",
1024 });
1025 yield* h.emitNative(
1026 nativeToolUpdate({
1027 sessionUpdate: "tool_call",
1028 toolCallId: "permission-1",
1029 title: "Run start_subagent?",
1030 kind: "other",
1031 status: "pending",
1032 rawInput: {},
1033 }),
1034 );
1035 const pending = yield* h.waitForEvent((event) => event.type === "task.progress");
1036 expect(pending.payload.status).toBe("pending");
1037 yield* h.emitNative(
1038 nativeToolUpdate({
1039 sessionUpdate: "tool_call_update",
1040 toolCallId: "permission-1",
1041 status: "failed",
1042 }),
1043 );
1044 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
1045 expect(completed.payload.status).toBe("failed");
1046 }),
1047 );
1048
1049 for (const stop of ["cancel", "steer", "disconnect", "end_turn"] as const) {
1050 it.effect(`settles open subagent calls on ${stop}`, () =>
1051 Effect.gen(function* () {
1052 const h = yield* makeHarness();
1053 yield* h.adapter.startSession({
1054 threadId,
1055 cwd: process.cwd(),
1056 runtimeMode: "approval-required",
1057 });
1058 const sending = yield* h.adapter
1059 .sendTurn({ threadId, input: "Start a subagent" })
1060 .pipe(Effect.forkChild);
1061 const prompt = yield* h.nextPrompt;
1062 yield* h.emitNative(
1063 nativeToolUpdate({
1064 sessionUpdate: "tool_call",
1065 toolCallId: "trajectory:4",
1066 title: "Running start_subagent",
1067 kind: "other",
1068 status: "in_progress",
1069 rawInput: {},
1070 }),
1071 );
1072 yield* h.waitForEvent((event) => event.type === "task.progress");
1073 yield* h.emitNative(
1074 nativeToolUpdate({
1075 sessionUpdate: "tool_call_update",
1076 toolCallId: "trajectory:4",
1077 status: "completed",
1078 rawOutput: "Launch subagents",
1079 }),
1080 );
1081 yield* h.waitForEvent((event) => event.type === "task.progress");
1082 if (stop === "disconnect") {
1083 yield* h.emitNative({
1084 _tag: "ConnectionTerminated",
1085 error: new AcpErrors.AcpTransportError({ detail: "Process exited.", cause: undefined }),
1086 });
1087 } else if (stop === "cancel") {
1088 yield* h.adapter.interruptTurn(threadId);
1089 } else if (stop === "steer") {
1090 const steering = yield* h.adapter
1091 .sendTurn({ threadId, input: "Change direction" })
1092 .pipe(Effect.forkChild);
1093 const replacement = yield* h.nextPrompt;
1094 yield* Deferred.succeed(replacement.result, { stopReason: "end_turn" });
1095 yield* Fiber.join(steering);
1096 } else {
1097 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1098 }
1099 const settled = yield* h.waitForEvent((event) => event.type === "task.updated");
1100 expect(settled.payload).toMatchObject({
1101 taskId: "trajectory:4",
1102 title: "Antigravity subagent batch",
1103 taskType: "subagent_batch",
1104 status:
1105 stop === "disconnect"
1106 ? "failed"
1107 : stop === "cancel" || stop === "steer"
1108 ? "cancelled"
1109 : "idle",
1110 });
1111 if (stop === "disconnect")
1112 yield* h.waitForEvent((event) => event.type === "session.exited");
1113 else yield* Fiber.join(sending);
1114 }),
1115 );
1116 }
1117
1118 it.effect("retires a prompt cancelled before native dispatch", () =>
1119 Effect.gen(function* () {
1120 const h = yield* makeHarness({ holdDispatch: true });
1121 yield* h.adapter.startSession({
1122 threadId,
1123 cwd: process.cwd(),
1124 runtimeMode: "approval-required",
1125 });
1126 const sending = yield* h.adapter
1127 .sendTurn({ threadId, input: "Do not dispatch this prompt" })
1128 .pipe(Effect.forkChild);
1129 yield* Deferred.await(h.dispatchStarted);
1130 yield* Fiber.interrupt(sending);
1131 yield* Deferred.succeed(h.dispatchRelease, undefined);
1132 const cancelled = yield* h.waitForEvent((event) => event.type === "turn.completed");
1133 expect(cancelled.payload.state).toBe("cancelled");
1134 expect(h.calls.some((call) => call.startsWith("prompt:"))).toBe(false);
1135 expect(h.hasActivePrompt()).toBe(false);
1136 const later = yield* h.adapter
1137 .sendTurn({ threadId, input: "This prompt can run" })
1138 .pipe(Effect.forkChild);
1139 const prompt = yield* h.nextPrompt;
1140 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1141 const result = yield* Fiber.join(later);
1142 expect(result.turnId).not.toBe(cancelled.turnId);
1143 expect(h.calls.filter((call) => call.startsWith("prompt:"))).toEqual(["prompt:1"]);
1144 }),
1145 );
1146
1147 it.effect("awaits full process cleanup for concurrent stop requests", () =>
1148 Effect.gen(function* () {
1149 const h = yield* makeHarness({ holdClose: true });
1150 yield* h.adapter.startSession({
1151 threadId,
1152 cwd: process.cwd(),
1153 runtimeMode: "approval-required",
1154 });
1155 const stopping = yield* h.adapter.stopSession(threadId).pipe(Effect.forkChild);
1156 yield* Deferred.await(h.closeStarted);
1157 const registeredStop = h.stops[0];
1158 if (!registeredStop) return yield* Effect.die("Missing process cleanup registration");
1159 const signOutStop = yield* registeredStop.pipe(Effect.forkChild({ startImmediately: true }));
1160 expect(signOutStop.pollUnsafe()).toBeUndefined();
1161 yield* Deferred.succeed(h.closeRelease, undefined);
1162 yield* Effect.all([Fiber.join(stopping), Fiber.join(signOutStop)]);
1163 yield* h.waitForEvent((event) => event.type === "session.exited");
1164 expect(h.controls.closed).toBe(1);
1165 expect(h.seen.filter((event) => event.type === "session.exited")).toHaveLength(1);
1166 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1167 }),
1168 );
1169
1170 it.effect("stops a session while its prompt is waiting to dispatch", () =>
1171 Effect.gen(function* () {
1172 const h = yield* makeHarness({ holdDispatch: true });
1173 yield* h.adapter.startSession({
1174 threadId,
1175 cwd: process.cwd(),
1176 runtimeMode: "approval-required",
1177 });
1178 const sending = yield* h.adapter
1179 .sendTurn({ threadId, input: "Do not dispatch after stop" })
1180 .pipe(Effect.forkChild);
1181 yield* Deferred.await(h.dispatchStarted);
1182 yield* h.adapter.stopSession(threadId);
1183 yield* Fiber.await(sending);
1184 yield* Deferred.succeed(h.dispatchRelease, undefined);
1185 expect(h.calls.some((call) => call.startsWith("prompt:"))).toBe(false);
1186 expect(h.controls.closed).toBe(1);
1187 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1188 }),
1189 );
1190
1191 it.effect("propagates idle process exits and rejects stale session use", () =>
1192 Effect.gen(function* () {
1193 const h = yield* makeHarness();
1194 yield* h.adapter.startSession({
1195 threadId,
1196 cwd: process.cwd(),
1197 runtimeMode: "approval-required",
1198 });
1199 yield* h.emitNative({
1200 _tag: "ConnectionTerminated",
1201 error: new AcpErrors.AcpTransportError({ detail: "Process exited.", cause: undefined }),
1202 });
1203 const exited = yield* h.waitForEvent((event) => event.type === "session.exited");
1204 expect(exited.payload.exitKind).toBe("error");
1205 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1206 expect(
1207 Exit.isFailure(yield* h.adapter.sendTurn({ threadId, input: "Hello" }).pipe(Effect.exit)),
1208 ).toBe(true);
1209 }),
1210 );
1211
1212 it.effect("reports hidden login requests as sign-in required and clears account metadata", () =>
1213 Effect.gen(function* () {
1214 const h = yield* makeHarness();
1215 h.controls.failAuth = true;
1216 const started = yield* h.adapter
1217 .startSession({ threadId, cwd: process.cwd(), runtimeMode: "approval-required" })
1218 .pipe(Effect.exit);
1219 expect(Exit.isFailure(started)).toBe(true);
1220 expect(h.controls.authInvalidations).toBe(1);
1221 expect(h.controls.closed).toBe(1);
1222 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1223 }),
1224 );
1225
1226 it.effect("serves client file reads and writes only inside the session roots", () =>
1227 Effect.gen(function* () {
1228 const fs = yield* FileSystem.FileSystem;
1229 const path = yield* Path.Path;
1230 const h = yield* makeHarness();
1231 const { attachmentsDir } = yield* ServerConfig;
1232 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-fs-" });
1233 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-outside-" });
1234 yield* fs.writeFileString(path.join(cwd, "notes.txt"), "one\ntwo\nthree\n");
1235 yield* h.adapter.startSession({ threadId, cwd, runtimeMode: "approval-required" });
1236 expect(h.launches[0]?.clientFileSystem).toBe(true);
1237 expect(h.launches[0]?.additionalDirectories).toEqual([attachmentsDir]);
1238 const read = h.fileHandlers.read;
1239 const write = h.fileHandlers.write;
1240 if (!read || !write) return yield* Effect.die("File handlers were not registered.");
1241
1242 const full = yield* read({ sessionId: nativeSessionId, path: path.join(cwd, "notes.txt") });
1243 expect(full.content).toBe("one\ntwo\nthree\n");
1244 const window = yield* read({
1245 sessionId: nativeSessionId,
1246 path: path.join(cwd, "notes.txt"),
1247 line: 2,
1248 limit: 1,
1249 });
1250 expect(window.content).toBe("two");
1251
1252 yield* write({
1253 sessionId: nativeSessionId,
1254 path: path.join(cwd, "nested", "new.txt"),
1255 content: "created",
1256 });
1257 expect(yield* fs.readFileString(path.join(cwd, "nested", "new.txt"))).toBe("created");
1258
1259 const escape = yield* write({
1260 sessionId: nativeSessionId,
1261 path: path.join(outside, "escape.txt"),
1262 content: "nope",
1263 }).pipe(Effect.flip);
1264 expect(escape._tag).toBe("AcpRequestError");
1265 expect(yield* fs.exists(path.join(outside, "escape.txt"))).toBe(false);
1266 const missing = yield* read({
1267 sessionId: nativeSessionId,
1268 path: path.join(cwd, "missing.txt"),
1269 }).pipe(Effect.flip);
1270 expect(missing._tag).toBe("AcpRequestError");
1271 }).pipe(Effect.scoped),
1272 );
1273
1274 it.effect("does not launch a process for a disabled instance or invalid resume cursor", () =>
1275 Effect.gen(function* () {
1276 const disabled = yield* makeHarness({ enabled: false });
1277 const rejected = yield* disabled.adapter
1278 .startSession({ threadId, cwd: process.cwd(), runtimeMode: "approval-required" })
1279 .pipe(Effect.exit);
1280 expect(Exit.isFailure(rejected)).toBe(true);
1281 expect(disabled.launches).toHaveLength(0);
1282 const active = yield* makeHarness();
1283 const stale = yield* active.adapter
1284 .startSession({
1285 threadId,
1286 cwd: process.cwd(),
1287 runtimeMode: "approval-required",
1288 resumeCursor: { sessionId: nativeSessionId },
1289 })
1290 .pipe(Effect.exit);
1291 expect(Exit.isFailure(stale)).toBe(true);
1292 expect(active.launches).toHaveLength(0);
1293 }),
1294 );
1295});