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("stops commands left running after a turn when the idle turn is stopped", () =>
779 Effect.gen(function* () {
780 const h = yield* makeHarness();
781 yield* h.adapter.startSession({
782 threadId,
783 cwd: process.cwd(),
784 runtimeMode: "approval-required",
785 });
786 const sending = yield* h.adapter
787 .sendTurn({ threadId, input: "Start a watcher" })
788 .pipe(Effect.forkChild);
789 const prompt = yield* h.nextPrompt;
790 yield* h.emitNative({
791 _tag: "ToolCallUpdated",
792 toolCall: {
793 toolCallId: "watcher-1",
794 kind: "execute",
795 status: "inProgress",
796 command: "tail -f log",
797 data: {},
798 },
799 rawPayload: {},
800 });
801 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
802 yield* Fiber.join(sending);
803 const started = yield* h.waitForEvent((event) => event.type === "task.started");
804
805 // Monitoring's Stop reaches the adapter as a turn interrupt. With no
806 // prompt to cancel, it has to end the session to stop the command.
807 yield* h.adapter.interruptTurn(threadId);
808 const stopped = yield* h.waitForEvent((event) => event.type === "task.completed");
809 expect(stopped.payload).toMatchObject({ taskId: started.payload.taskId, status: "stopped" });
810 yield* h.waitForEvent((event) => event.type === "session.exited");
811 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
812 expect(h.controls.closed).toBe(1);
813 }),
814 );
815
816 it.effect("keeps a launched batch active while child tools continue", () =>
817 Effect.gen(function* () {
818 const h = yield* makeHarness();
819 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
820 const sending = yield* h.adapter
821 .sendTurn({ threadId, input: "Run two readers in one batch" })
822 .pipe(Effect.forkChild);
823 const prompt = yield* h.nextPrompt;
824 // ACP 1.1.1 capture: one launch call covers both children and returns
825 // only its description before either child finishes.
826 const started = nativeToolUpdate({
827 sessionUpdate: "tool_call",
828 toolCallId: `${nativeSessionId}:2`,
829 title: "Running start_subagent",
830 kind: "other",
831 status: "in_progress",
832 rawInput: {},
833 });
834 yield* h.emitNative(started);
835 yield* h.waitForEvent((event) => event.type === "task.progress");
836 yield* h.emitNative(
837 nativeToolUpdate(
838 {
839 sessionUpdate: "tool_call_update",
840 toolCallId: started.toolCall.toolCallId,
841 status: "completed",
842 rawOutput: "Launch subagents",
843 },
844 started.toolCall,
845 ),
846 );
847 const launched = yield* h.waitForEvent((event) => event.type === "task.progress");
848 expect(launched.payload).toMatchObject({
849 taskId: started.toolCall.toolCallId,
850 title: "Antigravity subagent batch",
851 taskType: "subagent_batch",
852 description: "Launch subagents",
853 status: "running",
854 });
855 for (const child of ["alpha", "beta"]) {
856 yield* h.emitNative(
857 nativeToolUpdate({
858 sessionUpdate: "tool_call",
859 toolCallId: `${child}:1`,
860 title: "Read file",
861 kind: "read",
862 status: "completed",
863 rawOutput: "File contents",
864 }),
865 );
866 }
867 yield* h.drainEvents;
868 expect(h.seen.filter((event) => event.type === "task.completed")).toHaveLength(0);
869 expect(h.seen.filter((event) => event.type === "task.updated")).toHaveLength(0);
870 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
871 yield* Fiber.join(sending);
872 yield* h.waitForEvent((event) => event.type === "turn.completed");
873 expect(h.seen.filter((event) => event.type === "task.completed")).toHaveLength(0);
874 expect(h.seen.find((event) => event.type === "task.updated")?.payload).toMatchObject({
875 taskId: started.toolCall.toolCallId,
876 status: "idle",
877 description: "Turn ended. Individual agent status is unavailable.",
878 timelineBypass: true,
879 });
880 }),
881 );
882
883 it.effect("waits for a replayed subagent's final status and result", () =>
884 Effect.gen(function* () {
885 const h = yield* makeHarness();
886 yield* h.adapter.startSession({
887 threadId,
888 cwd: process.cwd(),
889 runtimeMode: "approval-required",
890 });
891 // ACP history announces a completed tool first, even when its result failed.
892 yield* h.emitNative(
893 nativeToolUpdate({
894 sessionUpdate: "tool_call",
895 toolCallId: "replayed:4",
896 title: "Running start_subagent",
897 kind: "other",
898 status: "completed",
899 rawInput: "{}",
900 }),
901 );
902 yield* h.emitNative(
903 nativeToolUpdate({
904 sessionUpdate: "tool_call_update",
905 toolCallId: "replayed:4",
906 status: "failed",
907 rawOutput: "Review failed.",
908 }),
909 );
910 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
911 expect(completed.payload).toEqual({
912 taskId: "replayed:4",
913 taskType: "subagent_batch",
914 toolUseId: "replayed:4",
915 title: "Antigravity subagent batch",
916 status: "failed",
917 summary: "Review failed.",
918 });
919 expect(h.seen.filter((event) => event.type.startsWith("task."))).toHaveLength(1);
920 }),
921 );
922
923 it.effect("keeps one-message launches active and ignores late updates after settlement", () =>
924 Effect.gen(function* () {
925 const h = yield* makeHarness();
926 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
927 const first = yield* h.adapter
928 .sendTurn({ threadId, input: "Start readers" })
929 .pipe(Effect.forkChild);
930 const firstPrompt = yield* h.nextPrompt;
931 const launches = ["Launch readers", undefined].map((rawOutput, index) =>
932 nativeToolUpdate({
933 sessionUpdate: "tool_call",
934 toolCallId: `old:${index}`,
935 title: "Running start_subagent",
936 kind: "other",
937 status: "completed",
938 rawInput: {},
939 ...(rawOutput ? { rawOutput } : {}),
940 }),
941 );
942 for (const launch of launches) yield* h.emitNative(launch);
943 yield* h.drainEvents;
944 expect(h.seen.filter((event) => event.type === "task.progress")).toHaveLength(2);
945 expect(h.seen.filter((event) => event.type === "task.completed")).toHaveLength(0);
946 yield* Deferred.succeed(firstPrompt.result, { stopReason: "end_turn" });
947 yield* Fiber.join(first);
948 yield* h.waitForEvent((event) => event.type === "turn.completed");
949 const second = yield* h.adapter
950 .sendTurn({ threadId, input: "Next task" })
951 .pipe(Effect.forkChild);
952 const secondPrompt = yield* h.nextPrompt;
953 for (const launch of launches) {
954 for (const status of ["in_progress", "completed", "failed"] as const) {
955 yield* h.emitNative(
956 nativeToolUpdate(
957 {
958 sessionUpdate: "tool_call_update",
959 toolCallId: launch.toolCall.toolCallId,
960 status,
961 rawOutput: "Late update",
962 },
963 launch.toolCall,
964 ),
965 );
966 }
967 }
968 yield* h.drainEvents;
969 expect(h.seen.filter((event) => event.type === "task.progress")).toHaveLength(2);
970 expect(h.seen.filter((event) => event.type === "task.updated")).toHaveLength(2);
971 expect(h.seen.filter((event) => event.type === "task.completed")).toHaveLength(0);
972 yield* Deferred.succeed(secondPrompt.result, { stopReason: "end_turn" });
973 yield* Fiber.join(second);
974 }),
975 );
976
977 it.effect("does not report a historical launch as running or completed work", () =>
978 Effect.gen(function* () {
979 const h = yield* makeHarness();
980 yield* h.adapter.startSession({ threadId, cwd: process.cwd(), runtimeMode: "full-access" });
981 const launch = nativeToolUpdate({
982 sessionUpdate: "tool_call",
983 toolCallId: "history:2",
984 title: "Running start_subagent",
985 kind: "other",
986 status: "completed",
987 rawInput: {},
988 });
989 yield* h.emitNative(launch);
990 yield* h.emitNative(
991 nativeToolUpdate(
992 {
993 sessionUpdate: "tool_call_update",
994 toolCallId: launch.toolCall.toolCallId,
995 status: "completed",
996 rawOutput: "Launch readers",
997 },
998 launch.toolCall,
999 ),
1000 );
1001 yield* h.drainEvents;
1002 expect(h.seen.filter((event) => event.type.startsWith("task."))).toMatchObject([
1003 {
1004 type: "task.updated",
1005 payload: { status: "idle", timelineBypass: true },
1006 },
1007 ]);
1008 }),
1009 );
1010
1011 it.effect("keeps MCP identity when later updates omit metadata", () =>
1012 Effect.gen(function* () {
1013 const h = yield* makeHarness();
1014 yield* h.adapter.startSession({
1015 threadId,
1016 cwd: process.cwd(),
1017 runtimeMode: "approval-required",
1018 });
1019 const sending = yield* h.adapter
1020 .sendTurn({ threadId, input: "Run an MCP tool" })
1021 .pipe(Effect.forkChild);
1022 const prompt = yield* h.nextPrompt;
1023 const started = nativeToolUpdate({
1024 sessionUpdate: "tool_call",
1025 toolCallId: "mcp-4",
1026 title: "Running start_subagent",
1027 kind: "other",
1028 status: "in_progress",
1029 rawInput: { arguments: {} },
1030 _meta: { is_mcp_tool_call: true },
1031 });
1032 yield* h.emitNative(started);
1033 for (const status of ["in_progress", "completed"] as const) {
1034 yield* h.emitNative(
1035 nativeToolUpdate(
1036 {
1037 sessionUpdate: "tool_call_update",
1038 toolCallId: "mcp-4",
1039 status,
1040 rawOutput: "MCP output.",
1041 },
1042 started.toolCall,
1043 ),
1044 );
1045 }
1046 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1047 yield* Fiber.join(sending);
1048 yield* h.waitForEvent((event) => event.type === "turn.completed");
1049 expect(h.seen.filter((event) => event.type.startsWith("task."))).toHaveLength(0);
1050 expect(h.seen.filter((event) => event.type === "item.updated")).toHaveLength(2);
1051 expect(h.seen.filter((event) => event.type === "item.completed")).toHaveLength(1);
1052 }),
1053 );
1054
1055 it.effect("shows pending subagents and closes a denied invocation", () =>
1056 Effect.gen(function* () {
1057 const h = yield* makeHarness();
1058 yield* h.adapter.startSession({
1059 threadId,
1060 cwd: process.cwd(),
1061 runtimeMode: "approval-required",
1062 });
1063 yield* h.emitNative(
1064 nativeToolUpdate({
1065 sessionUpdate: "tool_call",
1066 toolCallId: "permission-1",
1067 title: "Run start_subagent?",
1068 kind: "other",
1069 status: "pending",
1070 rawInput: {},
1071 }),
1072 );
1073 const pending = yield* h.waitForEvent((event) => event.type === "task.progress");
1074 expect(pending.payload.status).toBe("pending");
1075 yield* h.emitNative(
1076 nativeToolUpdate({
1077 sessionUpdate: "tool_call_update",
1078 toolCallId: "permission-1",
1079 status: "failed",
1080 }),
1081 );
1082 const completed = yield* h.waitForEvent((event) => event.type === "task.completed");
1083 expect(completed.payload.status).toBe("failed");
1084 }),
1085 );
1086
1087 for (const stop of ["cancel", "steer", "disconnect", "end_turn"] as const) {
1088 it.effect(`settles open subagent calls on ${stop}`, () =>
1089 Effect.gen(function* () {
1090 const h = yield* makeHarness();
1091 yield* h.adapter.startSession({
1092 threadId,
1093 cwd: process.cwd(),
1094 runtimeMode: "approval-required",
1095 });
1096 const sending = yield* h.adapter
1097 .sendTurn({ threadId, input: "Start a subagent" })
1098 .pipe(Effect.forkChild);
1099 const prompt = yield* h.nextPrompt;
1100 yield* h.emitNative(
1101 nativeToolUpdate({
1102 sessionUpdate: "tool_call",
1103 toolCallId: "trajectory:4",
1104 title: "Running start_subagent",
1105 kind: "other",
1106 status: "in_progress",
1107 rawInput: {},
1108 }),
1109 );
1110 yield* h.waitForEvent((event) => event.type === "task.progress");
1111 yield* h.emitNative(
1112 nativeToolUpdate({
1113 sessionUpdate: "tool_call_update",
1114 toolCallId: "trajectory:4",
1115 status: "completed",
1116 rawOutput: "Launch subagents",
1117 }),
1118 );
1119 yield* h.waitForEvent((event) => event.type === "task.progress");
1120 if (stop === "disconnect") {
1121 yield* h.emitNative({
1122 _tag: "ConnectionTerminated",
1123 error: new AcpErrors.AcpTransportError({ detail: "Process exited.", cause: undefined }),
1124 });
1125 } else if (stop === "cancel") {
1126 yield* h.adapter.interruptTurn(threadId);
1127 } else if (stop === "steer") {
1128 const steering = yield* h.adapter
1129 .sendTurn({ threadId, input: "Change direction" })
1130 .pipe(Effect.forkChild);
1131 const replacement = yield* h.nextPrompt;
1132 yield* Deferred.succeed(replacement.result, { stopReason: "end_turn" });
1133 yield* Fiber.join(steering);
1134 } else {
1135 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1136 }
1137 const settled = yield* h.waitForEvent((event) => event.type === "task.updated");
1138 expect(settled.payload).toMatchObject({
1139 taskId: "trajectory:4",
1140 title: "Antigravity subagent batch",
1141 taskType: "subagent_batch",
1142 status:
1143 stop === "disconnect"
1144 ? "failed"
1145 : stop === "cancel" || stop === "steer"
1146 ? "cancelled"
1147 : "idle",
1148 });
1149 if (stop === "disconnect")
1150 yield* h.waitForEvent((event) => event.type === "session.exited");
1151 else yield* Fiber.join(sending);
1152 }),
1153 );
1154 }
1155
1156 it.effect("retires a prompt cancelled before native dispatch", () =>
1157 Effect.gen(function* () {
1158 const h = yield* makeHarness({ holdDispatch: true });
1159 yield* h.adapter.startSession({
1160 threadId,
1161 cwd: process.cwd(),
1162 runtimeMode: "approval-required",
1163 });
1164 const sending = yield* h.adapter
1165 .sendTurn({ threadId, input: "Do not dispatch this prompt" })
1166 .pipe(Effect.forkChild);
1167 yield* Deferred.await(h.dispatchStarted);
1168 yield* Fiber.interrupt(sending);
1169 yield* Deferred.succeed(h.dispatchRelease, undefined);
1170 const cancelled = yield* h.waitForEvent((event) => event.type === "turn.completed");
1171 expect(cancelled.payload.state).toBe("cancelled");
1172 expect(h.calls.some((call) => call.startsWith("prompt:"))).toBe(false);
1173 expect(h.hasActivePrompt()).toBe(false);
1174 const later = yield* h.adapter
1175 .sendTurn({ threadId, input: "This prompt can run" })
1176 .pipe(Effect.forkChild);
1177 const prompt = yield* h.nextPrompt;
1178 yield* Deferred.succeed(prompt.result, { stopReason: "end_turn" });
1179 const result = yield* Fiber.join(later);
1180 expect(result.turnId).not.toBe(cancelled.turnId);
1181 expect(h.calls.filter((call) => call.startsWith("prompt:"))).toEqual(["prompt:1"]);
1182 }),
1183 );
1184
1185 it.effect("awaits full process cleanup for concurrent stop requests", () =>
1186 Effect.gen(function* () {
1187 const h = yield* makeHarness({ holdClose: true });
1188 yield* h.adapter.startSession({
1189 threadId,
1190 cwd: process.cwd(),
1191 runtimeMode: "approval-required",
1192 });
1193 const stopping = yield* h.adapter.stopSession(threadId).pipe(Effect.forkChild);
1194 yield* Deferred.await(h.closeStarted);
1195 const registeredStop = h.stops[0];
1196 if (!registeredStop) return yield* Effect.die("Missing process cleanup registration");
1197 const signOutStop = yield* registeredStop.pipe(Effect.forkChild({ startImmediately: true }));
1198 expect(signOutStop.pollUnsafe()).toBeUndefined();
1199 yield* Deferred.succeed(h.closeRelease, undefined);
1200 yield* Effect.all([Fiber.join(stopping), Fiber.join(signOutStop)]);
1201 yield* h.waitForEvent((event) => event.type === "session.exited");
1202 expect(h.controls.closed).toBe(1);
1203 expect(h.seen.filter((event) => event.type === "session.exited")).toHaveLength(1);
1204 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1205 }),
1206 );
1207
1208 it.effect("stops a session while its prompt is waiting to dispatch", () =>
1209 Effect.gen(function* () {
1210 const h = yield* makeHarness({ holdDispatch: true });
1211 yield* h.adapter.startSession({
1212 threadId,
1213 cwd: process.cwd(),
1214 runtimeMode: "approval-required",
1215 });
1216 const sending = yield* h.adapter
1217 .sendTurn({ threadId, input: "Do not dispatch after stop" })
1218 .pipe(Effect.forkChild);
1219 yield* Deferred.await(h.dispatchStarted);
1220 yield* h.adapter.stopSession(threadId);
1221 yield* Fiber.await(sending);
1222 yield* Deferred.succeed(h.dispatchRelease, undefined);
1223 expect(h.calls.some((call) => call.startsWith("prompt:"))).toBe(false);
1224 expect(h.controls.closed).toBe(1);
1225 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1226 }),
1227 );
1228
1229 it.effect("propagates idle process exits and rejects stale session use", () =>
1230 Effect.gen(function* () {
1231 const h = yield* makeHarness();
1232 yield* h.adapter.startSession({
1233 threadId,
1234 cwd: process.cwd(),
1235 runtimeMode: "approval-required",
1236 });
1237 yield* h.emitNative({
1238 _tag: "ConnectionTerminated",
1239 error: new AcpErrors.AcpTransportError({ detail: "Process exited.", cause: undefined }),
1240 });
1241 const exited = yield* h.waitForEvent((event) => event.type === "session.exited");
1242 expect(exited.payload.exitKind).toBe("error");
1243 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1244 expect(
1245 Exit.isFailure(yield* h.adapter.sendTurn({ threadId, input: "Hello" }).pipe(Effect.exit)),
1246 ).toBe(true);
1247 }),
1248 );
1249
1250 it.effect("reports hidden login requests as sign-in required and clears account metadata", () =>
1251 Effect.gen(function* () {
1252 const h = yield* makeHarness();
1253 h.controls.failAuth = true;
1254 const started = yield* h.adapter
1255 .startSession({ threadId, cwd: process.cwd(), runtimeMode: "approval-required" })
1256 .pipe(Effect.exit);
1257 expect(Exit.isFailure(started)).toBe(true);
1258 expect(h.controls.authInvalidations).toBe(1);
1259 expect(h.controls.closed).toBe(1);
1260 expect(yield* h.adapter.hasSession(threadId)).toBe(false);
1261 }),
1262 );
1263
1264 it.effect("serves client file reads and writes only inside the session roots", () =>
1265 Effect.gen(function* () {
1266 const fs = yield* FileSystem.FileSystem;
1267 const path = yield* Path.Path;
1268 const h = yield* makeHarness();
1269 const { attachmentsDir } = yield* ServerConfig;
1270 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-fs-" });
1271 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-outside-" });
1272 yield* fs.writeFileString(path.join(cwd, "notes.txt"), "one\ntwo\nthree\n");
1273 yield* h.adapter.startSession({ threadId, cwd, runtimeMode: "approval-required" });
1274 expect(h.launches[0]?.clientFileSystem).toBe(true);
1275 expect(h.launches[0]?.additionalDirectories).toEqual([attachmentsDir]);
1276 const read = h.fileHandlers.read;
1277 const write = h.fileHandlers.write;
1278 if (!read || !write) return yield* Effect.die("File handlers were not registered.");
1279
1280 const full = yield* read({ sessionId: nativeSessionId, path: path.join(cwd, "notes.txt") });
1281 expect(full.content).toBe("one\ntwo\nthree\n");
1282 const window = yield* read({
1283 sessionId: nativeSessionId,
1284 path: path.join(cwd, "notes.txt"),
1285 line: 2,
1286 limit: 1,
1287 });
1288 expect(window.content).toBe("two");
1289
1290 yield* write({
1291 sessionId: nativeSessionId,
1292 path: path.join(cwd, "nested", "new.txt"),
1293 content: "created",
1294 });
1295 expect(yield* fs.readFileString(path.join(cwd, "nested", "new.txt"))).toBe("created");
1296
1297 const escape = yield* write({
1298 sessionId: nativeSessionId,
1299 path: path.join(outside, "escape.txt"),
1300 content: "nope",
1301 }).pipe(Effect.flip);
1302 expect(escape._tag).toBe("AcpRequestError");
1303 expect(yield* fs.exists(path.join(outside, "escape.txt"))).toBe(false);
1304 const missing = yield* read({
1305 sessionId: nativeSessionId,
1306 path: path.join(cwd, "missing.txt"),
1307 }).pipe(Effect.flip);
1308 expect(missing._tag).toBe("AcpRequestError");
1309 }).pipe(Effect.scoped),
1310 );
1311
1312 it.effect("does not launch a process for a disabled instance or invalid resume cursor", () =>
1313 Effect.gen(function* () {
1314 const disabled = yield* makeHarness({ enabled: false });
1315 const rejected = yield* disabled.adapter
1316 .startSession({ threadId, cwd: process.cwd(), runtimeMode: "approval-required" })
1317 .pipe(Effect.exit);
1318 expect(Exit.isFailure(rejected)).toBe(true);
1319 expect(disabled.launches).toHaveLength(0);
1320 const active = yield* makeHarness();
1321 const stale = yield* active.adapter
1322 .startSession({
1323 threadId,
1324 cwd: process.cwd(),
1325 runtimeMode: "approval-required",
1326 resumeCursor: { sessionId: nativeSessionId },
1327 })
1328 .pipe(Effect.exit);
1329 expect(Exit.isFailure(stale)).toBe(true);
1330 expect(active.launches).toHaveLength(0);
1331 }),
1332 );
1333});