@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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