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

AntigravityTextGeneration.test.ts

633 lines25.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import {
4 ANTIGRAVITY_DEFAULT_MODEL,
5 ProviderInstanceId,
6 ProviderSetupError,
7} from "@t3tools/contracts";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import * as Queue from "effect/Queue";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19import { type AcpError, AcpRequestError } from "effect-acp/errors";
20import type * as AcpSchema from "effect-acp/schema";
21import { expect } from "vite-plus/test";
22​
23import type { AcpSessionRuntimeEvent } from "../provider/acp/AcpSessionRuntime.ts";
24import { removeAntigravitySessionFiles } from "../provider/acp/AntigravitySessionFiles.ts";
25​
26import {
27 type AntigravityTextGenerationOptions,
28 isAntigravityTextGenerationAvailable,
29 makeAntigravityTextGeneration,
30} from "./AntigravityTextGeneration.ts";
31​
32type TextRuntime = Effect.Success<ReturnType<AntigravityTextGenerationOptions["makeRuntime"]>>;
33​
34const SESSION_ID = "047c62f6-607b-44db-bfbe-f83b67e9e8b1";
35const modelSelection = {
36 instanceId: ProviderInstanceId.make("antigravity-test"),
37 model: "gemini-test",
38};
39const encodeMetadata = Schema.encodeEffect(
40 Schema.fromJsonString(Schema.Struct({ cwd: Schema.String })),
41);
42​
43interface PromptContext {
44 readonly emit: (
45 update: AcpSchema.SessionNotification["update"],
46 sessionId?: string,
47 ) => Effect.Effect<void, AcpError>;
48 permission: Parameters<TextRuntime["handleRequestPermission"]>[0];
49 question: Parameters<TextRuntime["handleElicitation"]>[0];
50 readFile: Parameters<TextRuntime["handleReadTextFile"]>[0];
51 createTerminal: Parameters<TextRuntime["handleCreateTerminal"]>[0];
52 extension: Parameters<TextRuntime["handleUnknownExtRequest"]>[0];
53 readonly cwd: string;
55​
56const makeFixture = Effect.fn("makeAntigravityTextGenerationFixture")(function* (
57 options: {
58 readonly outputs?: ReadonlyArray<string>;
59 readonly prompt?: (context: PromptContext) => Effect.Effect<AcpSchema.PromptResponse, AcpError>;
60 readonly startError?: AcpError;
61 readonly rejectAdmission?: boolean;
62 readonly sessionId?: string;
63 } = {},
64) {
65 const fs = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-text-test-" });
68 const profileDirectory = path.join(root, "profile");
69 const projectDirectory = path.join(root, "project");
70 const conversations = path.join(profileDirectory, "antigravity-acp", "conversations");
71 const nativeSessionId = options.sessionId ?? SESSION_ID;
72 const sessionBase = path.join(conversations, SESSION_ID);
73 const brainDirectory = path.join(profileDirectory, "antigravity-acp", "brain", SESSION_ID);
74 yield* fs.makeDirectory(projectDirectory, { recursive: true });
75 yield* fs.makeDirectory(conversations, { recursive: true });
76 yield* fs.writeFileString(path.join(projectDirectory, "keep.txt"), "untouched");
77 yield* fs.writeFileString(path.join(conversations, "user-session.db"), "keep native history");
78 const enteredPrompt = yield* Deferred.make<void>();
79 const state = {
80 workspaces: [] as Array<string>,
81 closed: [] as Array<string>,
82 prompts: [] as Array<Parameters<TextRuntime["prompt"]>[0]>,
83 selectedModels: [] as Array<string>,
84 selectedModes: [] as Array<string>,
85 nativeFilesAtClose: [] as Array<boolean>,
86 cancellations: 0,
87 stop: undefined as Effect.Effect<void> | undefined,
88 };
89 const outputs = [...(options.outputs ?? ['{"title":"Repair login"}'])];
90 const incoming: Omit<PromptContext, "cwd" | "emit"> = {
91 permission: () => Effect.die("No permission handler."),
92 question: () => Effect.die("No question handler."),
93 readFile: () => Effect.die("No file handler."),
94 createTerminal: () => Effect.die("No terminal handler."),
95 extension: () => Effect.die("No extension handler."),
96 };
97​
98 const withProcess: AntigravityTextGenerationOptions["withProcess"] = (stop, task) =>
99 Effect.gen(function* () {
100 if (options.rejectAdmission) {
101 return yield* new ProviderSetupError({
102 instanceId: modelSelection.instanceId,
103 operation: "launch",
104 detail: "Sign in before starting Antigravity.",
105 });
106 }
107 const scope = yield* Scope.Scope;
108 const child = yield* Effect.forkIn(task, scope);
109 state.stop = Fiber.interrupt(child).pipe(Effect.andThen(stop));
110 yield* Effect.addFinalizer(() =>
111 Effect.sync(() => {
112 state.stop = undefined;
113 }),
114 );
115 return yield* Fiber.await(child).pipe(
116 Effect.flatMap((exit) => exit),
117 Effect.ensuring(Fiber.interrupt(child)),
118 );
119 });
120​
121 const makeRuntime: AntigravityTextGenerationOptions["makeRuntime"] = (cwd) =>
122 Effect.gen(function* () {
123 const events = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
124 state.workspaces.push(cwd);
125 expect(yield* fs.readDirectory(cwd).pipe(Effect.orDie)).toEqual([]);
126 yield* Effect.addFinalizer(() =>
127 Effect.gen(function* () {
128 state.nativeFilesAtClose.push(yield* fs.exists(`${sessionBase}.db`).pipe(Effect.orDie));
129 state.closed.push(cwd);
130 }),
131 );
132 let sessionUpdate: Parameters<TextRuntime["handleSessionUpdate"]>[0] = () => Effect.void;
133​
134 return {
135 start: () =>
136 Effect.gen(function* () {
137 if (options.startError) return yield* options.startError;
138 yield* fs.makeDirectory(brainDirectory, { recursive: true }).pipe(Effect.orDie);
139 yield* fs.writeFileString(`${sessionBase}.db`, "helper session").pipe(Effect.orDie);
140 yield* fs.writeFileString(`${sessionBase}.db-wal`, "helper journal").pipe(Effect.orDie);
141 const metadata = yield* encodeMetadata({ cwd }).pipe(Effect.orDie);
142 yield* fs.writeFileString(`${sessionBase}.meta`, metadata).pipe(Effect.orDie);
143 yield* fs
144 .writeFileString(path.join(brainDirectory, "output.txt"), "helper artifact")
145 .pipe(Effect.orDie);
146 return {
147 sessionId: nativeSessionId,
148 initializeResult: { protocolVersion: 1 },
149 sessionSetupResult: { sessionId: nativeSessionId },
150 modelConfigId: "model",
151 };
152 }),
153 setMode: (mode) =>
154 Effect.sync(() => {
155 state.selectedModes.push(mode);
156 return {};
157 }),
158 getConfigOptions: Effect.succeed([
159 {
160 id: "model",
161 name: "Model",
162 category: "model",
163 type: "select",
164 currentValue: modelSelection.model,
165 options: [{ value: modelSelection.model, name: "Gemini test" }],
166 },
167 ]),
168 getEvents: () => Stream.fromQueue(events),
169 setModel: (model) =>
170 Effect.sync(() => {
171 state.selectedModels.push(model);
172 }),
173 prompt: (request) =>
174 Effect.gen(function* () {
175 state.prompts.push(request);
176 yield* Deferred.succeed(enteredPrompt, undefined);
177 const emit: PromptContext["emit"] = (update, sessionId = nativeSessionId) =>
178 sessionUpdate({ sessionId, update });
179 if (options.prompt) {
180 return yield* options.prompt({
181 emit,
182 ...incoming,
183 cwd,
184 });
185 }
186 const output = outputs.shift() ?? '{"title":"Repair login"}';
187 yield* emit({
188 sessionUpdate: "agent_thought_chunk",
189 content: { type: "text", text: "Choose concise text." },
190 });
191 yield* emit(
192 {
193 sessionUpdate: "agent_message_chunk",
194 content: { type: "text", text: "unrelated session" },
195 },
196 "another-session",
197 );
198 for (const text of [output.slice(0, 9), output.slice(9)]) {
199 yield* emit({
200 sessionUpdate: "agent_message_chunk",
201 content: { type: "text", text },
202 });
203 }
204 return { stopReason: "end_turn" };
205 }),
206 cancel: Effect.gen(function* () {
207 state.cancellations += 1;
208 const acknowledge = yield* Deferred.make<void>();
209 yield* Queue.offer(events, { _tag: "EventStreamBarrier", acknowledge });
210 yield* Deferred.await(acknowledge);
211 }),
212 handleSessionUpdate: (handler) =>
213 Effect.sync(() => {
214 sessionUpdate = handler;
215 }),
216 handleRequestPermission: (handler) =>
217 Effect.sync(() => {
218 incoming.permission = handler;
219 }),
220 handleElicitation: (handler) =>
221 Effect.sync(() => {
222 incoming.question = handler;
223 }),
224 handleReadTextFile: (handler) =>
225 Effect.sync(() => {
226 incoming.readFile = handler;
227 }),
228 handleWriteTextFile: () => Effect.void,
229 handleCreateTerminal: (handler) =>
230 Effect.sync(() => {
231 incoming.createTerminal = handler;
232 }),
233 handleTerminalOutput: () => Effect.void,
234 handleTerminalWaitForExit: () => Effect.void,
235 handleTerminalKill: () => Effect.void,
236 handleTerminalRelease: () => Effect.void,
237 handleUnknownExtRequest: (handler) =>
238 Effect.sync(() => {
239 incoming.extension = handler;
240 }),
241 } satisfies TextRuntime;
242 });
243​
244 const textGeneration = yield* makeAntigravityTextGeneration({
245 profileDirectory,
246 makeRuntime,
247 withProcess,
248 });
249 const titleInput = { cwd: projectDirectory, message: "Repair Google login", modelSelection };
250 const assertCleaned = Effect.gen(function* () {
251 expect(state.closed).toEqual(state.workspaces);
252 for (const workspace of state.workspaces) {
253 expect(yield* fs.exists(workspace)).toBe(false);
254 }
255 expect(yield* fs.exists(`${sessionBase}.db`)).toBe(false);
256 expect(yield* fs.exists(`${sessionBase}.db-wal`)).toBe(false);
257 expect(yield* fs.exists(`${sessionBase}.meta`)).toBe(false);
258 expect(yield* fs.exists(brainDirectory)).toBe(false);
259 expect(yield* fs.readFileString(path.join(projectDirectory, "keep.txt"))).toBe("untouched");
260 expect(yield* fs.readFileString(path.join(conversations, "user-session.db"))).toBe(
261 "keep native history",
262 );
263 });
264 return {
265 fs,
266 path,
267 profileDirectory,
268 projectDirectory,
269 sessionBase,
270 brainDirectory,
271 state,
272 incoming,
273 enteredPrompt,
274 textGeneration,
275 titleInput,
276 assertCleaned,
277 };
278});
279​
280it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
281 it.effect(
282 "generates all helper types in empty workspaces and removes only owned session files",
283 () =>
284 Effect.gen(function* () {
285 const fixture = yield* makeFixture({
286 outputs: [
287 '{"subject":" Repair Google login.\\nExtra line","body":" Keep the remote callback. ","branch":"Repair Login"}',
288 '```json\n{"title":" Repair Google login\\nExtra line","body":" ## Summary\\nSupport remote callbacks. "}\n```',
289 '{"branch":" Repair Google Login "}',
290 '{"title":" \\"Repair Google login\\" "}',
291 ],
292 });
293 const common = { cwd: fixture.projectDirectory, modelSelection };
294 expect(
295 yield* fixture.textGeneration.generateCommitMessage({
296 ...common,
297 branch: "feature/login",
298 stagedSummary: "M login.ts",
299 stagedPatch: "+handleRemoteCallback()",
300 includeBranch: true,
301 }),
302 ).toEqual({
303 subject: "Repair Google login",
304 body: "Keep the remote callback.",
305 branch: "feature/repair-login",
306 });
307 expect(
308 yield* fixture.textGeneration.generatePrContent({
309 ...common,
310 baseBranch: "main",
311 headBranch: "feature/login",
312 commitSummary: "Repair login",
313 diffSummary: "M login.ts",
314 diffPatch: "+handleRemoteCallback()",
315 }),
316 ).toEqual({ title: "Repair Google login", body: "## Summary\nSupport remote callbacks." });
317 expect(
318 yield* fixture.textGeneration.generateBranchName({
319 ...common,
320 message: "Repair Google login",
321 }),
322 ).toEqual({ branch: "repair-google-login" });
323 expect(yield* fixture.textGeneration.generateThreadTitle(fixture.titleInput)).toEqual({
324 title: "Repair Google login",
325 });
326 expect(new Set(fixture.state.workspaces).size).toBe(4);
327 expect(fixture.state.workspaces).not.toContain(fixture.projectDirectory);
328 expect(fixture.state.nativeFilesAtClose).toEqual([true, true, true, true]);
329 expect(fixture.state.selectedModes).toEqual(["default", "default", "default", "default"]);
330 expect(fixture.state.selectedModels).toEqual(Array(4).fill(modelSelection.model));
331 expect(fixture.state.prompts[0]?.prompt).toEqual([
332 { type: "text", text: expect.stringContaining("+handleRemoteCallback()") },
333 ]);
334 yield* fixture.assertCleaned;
335 }).pipe(Effect.scoped),
336 );
337​
338 it.effect.each(["tool_call", "tool_call_update"] as const)(
339 "aborts on %s even without a permission request",
340 (sessionUpdate) =>
341 Effect.gen(function* () {
342 const fixture = yield* makeFixture({
343 prompt: ({ emit }) =>
344 emit({ sessionUpdate, toolCallId: "tool-1", title: "Read files" }).pipe(
345 Effect.andThen(Effect.never),
346 ),
347 });
348 const error = yield* fixture.textGeneration
349 .generateThreadTitle(fixture.titleInput)
350 .pipe(Effect.flip);
351 expect(error.detail).toContain("tool work");
352 expect(fixture.state.cancellations).toBe(1);
353 yield* fixture.assertCleaned;
354 }).pipe(Effect.scoped),
355 );
356​
357 it.effect("rejects native permission and choice requests instead of answering them", () =>
358 Effect.gen(function* () {
359 const fixture = yield* makeFixture({ prompt: () => Effect.never });
360 const child = yield* fixture.textGeneration
361 .generateThreadTitle(fixture.titleInput)
362 .pipe(Effect.forkChild);
363 yield* Deferred.await(fixture.enteredPrompt);
364 const reply = yield* fixture.incoming.permission({
365 sessionId: SESSION_ID,
366 toolCall: { toolCallId: "question-1", title: "Choose a title", kind: "other" },
367 options: [
368 { optionId: "first-native-choice", name: "Use this title", kind: "allow_once" },
369 { optionId: "second-native-choice", name: "Use this title", kind: "allow_once" },
370 ],
371 });
372 const error = yield* Fiber.join(child).pipe(Effect.flip);
373 expect(reply).toEqual({ outcome: { outcome: "cancelled" } });
374 expect(error.detail).toContain("permission or user input");
375 yield* fixture.assertCleaned;
376 }).pipe(Effect.scoped),
377 );
378​
379 it.effect("declines elicitation and stops the helper", () =>
380 Effect.gen(function* () {
381 const fixture = yield* makeFixture({ prompt: () => Effect.never });
382 const child = yield* fixture.textGeneration
383 .generateThreadTitle(fixture.titleInput)
384 .pipe(Effect.forkChild);
385 yield* Deferred.await(fixture.enteredPrompt);
386 const reply = yield* fixture.incoming.question({
387 sessionId: SESSION_ID,
388 mode: "form",
389 message: "Name this branch",
390 requestedSchema: { type: "object", properties: {} },
391 });
392 const error = yield* Fiber.join(child).pipe(Effect.flip);
393 expect(reply).toEqual({ action: { action: "decline" } });
394 expect(error.detail).toContain("user input");
395 yield* fixture.assertCleaned;
396 }).pipe(Effect.scoped),
397 );
398​
399 it.effect.each(["file", "terminal", "extension"] as const)(
400 "denies unexpected %s requests",
401 (kind) =>
402 Effect.gen(function* () {
403 const fixture = yield* makeFixture({ prompt: () => Effect.never });
404 const child = yield* fixture.textGeneration
405 .generateThreadTitle(fixture.titleInput)
406 .pipe(Effect.forkChild);
407 yield* Deferred.await(fixture.enteredPrompt);
408 const request =
409 kind === "file"
410 ? fixture.incoming.readFile({ sessionId: SESSION_ID, path: "/not-allowed" })
411 : kind === "terminal"
412 ? fixture.incoming.createTerminal({ sessionId: SESSION_ID, command: "not-allowed" })
413 : fixture.incoming.extension("_ask_user", {});
414 const denied = yield* request.pipe(Effect.exit);
415 expect(Exit.isFailure(denied)).toBe(true);
416 const error = yield* Fiber.join(child).pipe(Effect.flip);
417 expect(error.detail).toContain("tool or user input");
418 yield* fixture.assertCleaned;
419 }).pipe(Effect.scoped),
420 );
421​
422 it.effect.each([
423 { output: " ", detail: "empty" },
424 { output: "No JSON here", detail: "invalid structured output" },
425 { output: '{"title":42}', detail: "invalid structured output" },
426 { output: "x".repeat(128_001), detail: "output limit" },
427 ])("rejects $detail output and closes the runtime", ({ output, detail }) =>
428 Effect.gen(function* () {
429 const fixture = yield* makeFixture({ outputs: [output] });
430 const error = yield* fixture.textGeneration
431 .generateThreadTitle(fixture.titleInput)
432 .pipe(Effect.flip);
433 expect(error.detail).toContain(detail);
434 yield* fixture.assertCleaned;
435 }).pipe(Effect.scoped),
436 );
437​
438 it.effect("does not return partial JSON after native cancellation", () =>
439 Effect.gen(function* () {
440 const fixture = yield* makeFixture({
441 prompt: ({ emit }) =>
442 emit({
443 sessionUpdate: "agent_message_chunk",
444 content: { type: "text", text: '{"title":"Partial title"}' },
445 }).pipe(Effect.as({ stopReason: "cancelled" })),
446 });
447 const error = yield* fixture.textGeneration
448 .generateThreadTitle(fixture.titleInput)
449 .pipe(Effect.flip);
450 expect(error.detail).toContain("cancelled");
451 yield* fixture.assertCleaned;
452 }).pipe(Effect.scoped),
453 );
454​
455 it.effect("rejects a helper that writes files in its temporary workspace", () =>
456 Effect.gen(function* () {
457 const fs = yield* FileSystem.FileSystem;
458 const path = yield* Path.Path;
459 const fixture = yield* makeFixture({
460 prompt: ({ cwd, emit }) =>
461 Effect.gen(function* () {
462 yield* fs
463 .writeFileString(path.join(cwd, "unexpected.txt"), "unexpected")
464 .pipe(Effect.orDie);
465 yield* emit({
466 sessionUpdate: "agent_message_chunk",
467 content: { type: "text", text: '{"title":"Ignored output"}' },
468 });
469 return { stopReason: "end_turn" };
470 }),
471 });
472 const error = yield* fixture.textGeneration
473 .generateThreadTitle(fixture.titleInput)
474 .pipe(Effect.flip);
475 expect(error.detail).toContain("wrote files");
476 yield* fixture.assertCleaned;
477 }).pipe(Effect.scoped),
478 );
479​
480 it.effect("fails an unavailable model before prompting", () =>
481 Effect.gen(function* () {
482 const fixture = yield* makeFixture();
483 const error = yield* fixture.textGeneration
484 .generateThreadTitle({
485 ...fixture.titleInput,
486 modelSelection: { ...modelSelection, model: "not-in-the-account" },
487 })
488 .pipe(Effect.flip);
489 expect(error.detail).toContain("select the Antigravity model");
490 expect(fixture.state.prompts).toEqual([]);
491 yield* fixture.assertCleaned;
492 }).pipe(Effect.scoped),
493 );
494​
495 it.effect("uses the native default without sending T3's default selection as a model ID", () =>
496 Effect.gen(function* () {
497 const fixture = yield* makeFixture();
498 const result = yield* fixture.textGeneration.generateThreadTitle({
499 ...fixture.titleInput,
500 modelSelection: { ...modelSelection, model: ANTIGRAVITY_DEFAULT_MODEL },
501 });
502 expect(result).toEqual({ title: "Repair login" });
503 expect(fixture.state.selectedModels).toEqual([]);
504 yield* fixture.assertCleaned;
505 }).pipe(Effect.scoped),
506 );
507​
508 it.effect.each([
509 {
510 name: "hooks.json",
511 value: '{"default":{"PreInvocation":[{"command":"do-not-run"}]}}',
512 available: false,
513 },
514 {
515 name: "mcp_config.json",
516 value: '{"mcpServers":{"server":{"command":"do-not-run"}}}',
517 available: false,
518 },
519 { name: "hooks.json", value: "invalid JSON", available: false },
520 { name: "mcp_config.json", value: "x".repeat(64_001), available: false },
521 { name: "hooks.json", value: "{}", available: true },
522 { name: "hooks.json", value: '{"hooks":{}}', available: true },
523 { name: "mcp_config.json", value: '{"mcpServers":{}}', available: true },
524 ])("checks $name before starting a helper, available=$available", ({ name, value, available }) =>
525 Effect.gen(function* () {
526 const fixture = yield* makeFixture();
527 const configDirectory = fixture.path.join(fixture.profileDirectory, "config");
528 yield* fixture.fs.makeDirectory(configDirectory, { recursive: true });
529 yield* fixture.fs.writeFileString(fixture.path.join(configDirectory, name), value);
530 expect(yield* isAntigravityTextGenerationAvailable(fixture.profileDirectory)).toBe(available);
531 const result = yield* fixture.textGeneration
532 .generateThreadTitle(fixture.titleInput)
533 .pipe(Effect.exit);
534 expect(Exit.isSuccess(result)).toBe(available);
535 expect(fixture.state.workspaces.length).toBe(available ? 1 : 0);
536 yield* fixture.assertCleaned;
537 }).pipe(Effect.scoped),
538 );
539​
540 it.effect("does not start another runtime or prompt after authentication fails", () =>
541 Effect.gen(function* () {
542 const fixture = yield* makeFixture({
543 startError: new AcpRequestError({ code: -32000, errorMessage: "Authentication required" }),
544 });
545 const error = yield* fixture.textGeneration
546 .generateThreadTitle(fixture.titleInput)
547 .pipe(Effect.flip);
548 expect(error._tag).toBe("TextGenerationError");
549 expect(fixture.state.workspaces).toHaveLength(1);
550 expect(fixture.state.prompts).toEqual([]);
551 yield* fixture.assertCleaned;
552 }).pipe(Effect.scoped),
553 );
554​
555 it.effect("does not launch during sign-out or before sign-in", () =>
556 Effect.gen(function* () {
557 const fixture = yield* makeFixture({ rejectAdmission: true });
558 const error = yield* fixture.textGeneration
559 .generateThreadTitle(fixture.titleInput)
560 .pipe(Effect.flip);
561 expect(error._tag).toBe("TextGenerationError");
562 expect(fixture.state.workspaces).toEqual([]);
563 yield* fixture.assertCleaned;
564 }).pipe(Effect.scoped),
565 );
566​
567 it.effect("times out a stalled helper and waits for cleanup", () =>
568 Effect.gen(function* () {
569 const fixture = yield* makeFixture({ prompt: () => Effect.never });
570 const child = yield* fixture.textGeneration
571 .generateThreadTitle(fixture.titleInput)
572 .pipe(Effect.forkChild);
573 yield* Deferred.await(fixture.enteredPrompt);
574 yield* TestClock.adjust(180_000);
575 const error = yield* Fiber.join(child).pipe(Effect.flip);
576 expect(error.detail).toContain("timed out");
577 expect(fixture.state.cancellations).toBe(1);
578 yield* fixture.assertCleaned;
579 }).pipe(Effect.scoped),
580 );
581​
582 it.effect.each(["caller", "sign-out"] as const)(
583 "closes all helper resources when stopped by %s",
584 (source) =>
585 Effect.gen(function* () {
586 const fixture = yield* makeFixture({ prompt: () => Effect.never });
587 const child = yield* fixture.textGeneration
588 .generateThreadTitle(fixture.titleInput)
589 .pipe(Effect.forkChild);
590 yield* Deferred.await(fixture.enteredPrompt);
591 if (source === "caller") {
592 yield* Fiber.interrupt(child);
593 } else {
594 if (!fixture.state.stop) return yield* Effect.die("No tracked helper to stop.");
595 yield* fixture.state.stop;
596 yield* Fiber.await(child);
597 }
598 expect(fixture.state.cancellations).toBe(1);
599 yield* fixture.assertCleaned;
600 }).pipe(Effect.scoped),
601 );
602​
603 it.effect("refuses unsafe native session IDs without deleting other files", () =>
604 Effect.gen(function* () {
605 const fixture = yield* makeFixture({ sessionId: "../../user-session" });
606 const error = yield* fixture.textGeneration
607 .generateThreadTitle(fixture.titleInput)
608 .pipe(Effect.flip);
609 expect(error.detail).toContain("invalid text helper session ID");
610 expect(fixture.state.prompts).toEqual([]);
611 expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.db`)).toBe("helper session");
612 expect(fixture.state.closed).toEqual(fixture.state.workspaces);
613 }).pipe(Effect.scoped),
614 );
615​
616 it.effect("keeps native sessions whose metadata belongs to a different workspace", () =>
617 Effect.gen(function* () {
618 const fixture = yield* makeFixture();
619 yield* fixture.fs.writeFileString(`${fixture.sessionBase}.db`, "keep this session");
620 const metadata = yield* encodeMetadata({ cwd: fixture.projectDirectory });
621 yield* fixture.fs.writeFileString(`${fixture.sessionBase}.meta`, metadata);
622 yield* removeAntigravitySessionFiles({
623 profileDirectory: fixture.profileDirectory,
624 sessionId: SESSION_ID,
625 cwd: "different-temporary-workspace",
626 });
627 expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.db`)).toBe(
628 "keep this session",
629 );
630 expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.meta`)).toBe(metadata);
631 }).pipe(Effect.scoped),
632 );
633});