Skip to content

Build your personal knowledge base with Trilium Notes

test(llm): cover the Antigravity provider and its chat UI

Elian Doran5be43378408c
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.spec.tsx
index bb3dd4cff3..502df4e24b 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.spec.tsx
@@ -3,7 +3,11 @@ import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("../../../services/i18n.js", () => ({
- t: (key: string, options?: { total?: string }) => (options?.total ? `${key}(${options.total})` : key)
+ t: (key: string, options?: { total?: string; prompt?: string; completion?: string }) => {
+ if (options?.total) return `${key}(${options.total})`;
+ if (options?.completion) return `${key}(${options.prompt}/${options.completion})`;
+ return key;
+ }
}));
vi.mock("../text/ReadOnlyText.js", () => ({
ReadOnlyTextContent: ({ html }: { html: string }) => <div className="markdown-stub">{html}</div>
@@ -45,4 +49,12 @@ describe("ChatMessage footer", () => {
expect(footer?.querySelector(".llm-chat-usage-model")?.textContent).toBe("Gemini 3.8 Flash (Medium)");
expect(footer?.querySelector(".llm-chat-usage-tokens")).toBeNull();
});
+
+ it("counts the prompt as the total when a provider reports only that, and names no model it did not report", () => {
+ const footer = renderFooter({ promptTokens: 800 });
+ expect(footer?.querySelector(".llm-chat-usage-model")).toBeNull();
+ const tokens = footer?.querySelector(".llm-chat-usage-tokens");
+ expect(tokens?.textContent).toBe("llm_chat.total_tokens(800)");
+ expect(tokens?.getAttribute("title")).toBe("llm_chat.tokens_detail(800/0)");
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ReasoningEffortDropdown.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ReasoningEffortDropdown.spec.tsx
index b9b502d957..5cadab1d86 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ReasoningEffortDropdown.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ReasoningEffortDropdown.spec.tsx
@@ -7,10 +7,14 @@ vi.mock("../../../services/i18n.js", () => ({
t: (key: string, options?: { level?: string }) => (options?.level ? `${key}(${options.level})` : key)
}));
-// Renders the toggle's face, its tooltip and class, and the menu, without Bootstrap.
+// Renders the toggle's face, its tooltip and class, and the menu, without Bootstrap;
+// the placement options go on data attributes.
vi.mock("../../react/Dropdown.js", () => ({
- default: ({ text, title, buttonClassName, children }: { text: ComponentChildren; title?: string; buttonClassName?: string; children: ComponentChildren }) => (
- <div className="dropdown-stub">
+ default: ({ text, title, buttonClassName, children, portalToBody, dropdownOptions }: {
+ text: ComponentChildren; title?: string; buttonClassName?: string; children: ComponentChildren;
+ portalToBody?: boolean; dropdownOptions?: { popperConfig?: { strategy?: string } };
+ }) => (
+ <div className="dropdown-stub" data-portal={String(!!portalToBody)} data-strategy={dropdownOptions?.popperConfig?.strategy ?? "none"}>
<button className={buttonClassName} title={title}>{text}</button>
<div className="menu">{children}</div>
</div>
@@ -32,10 +36,10 @@ afterEach(() => {
}
});
-function renderDropdown(model: LlmModelInfo, value: Parameters<typeof ReasoningEffortDropdown>[0]["value"], onChange = vi.fn()) {
+function renderDropdown(model: LlmModelInfo, value: Parameters<typeof ReasoningEffortDropdown>[0]["value"], onChange = vi.fn(), inSidebar = false) {
host = document.body.appendChild(document.createElement("div"));
const target = host;
- act(() => render(<ReasoningEffortDropdown model={model} value={value} onChange={onChange} />, target));
+ act(() => render(<ReasoningEffortDropdown model={model} value={value} onChange={onChange} inSidebar={inSidebar} />, target));
return { host: target, onChange };
}
@@ -45,6 +49,23 @@ describe("effectiveReasoningEffort", () => {
expect(effectiveReasoningEffort(PRO, "medium")).toBe("high");
expect(effectiveReasoningEffort(PRO, undefined)).toBe("high");
expect(effectiveReasoningEffort({ ...PRO, defaultReasoningEffort: undefined }, undefined)).toBe("high");
+ expect(effectiveReasoningEffort({ ...FLASH, reasoningEfforts: [ "low", "medium" ], defaultReasoningEffort: undefined }, undefined)).toBe("medium");
+ // A model that names no levels at all.
+ expect(effectiveReasoningEffort({ id: "m", name: "M" }, "low")).toBe("high");
+ });
+});
+
+describe("ReasoningEffortDropdown placement", () => {
+ it("portals the menu with a fixed position in the sidebar", () => {
+ const stub = renderDropdown(FLASH, undefined, vi.fn(), true).host.querySelector(".dropdown-stub");
+ expect([ stub?.getAttribute("data-portal"), stub?.getAttribute("data-strategy") ]).toEqual([ "true", "fixed" ]);
+ });
+
+ it("keeps the menu in place elsewhere, and lists nothing for a model without levels", () => {
+ const { host: plain } = renderDropdown({ id: "m", name: "M" }, undefined);
+ const stub = plain.querySelector(".dropdown-stub");
+ expect([ stub?.getAttribute("data-portal"), stub?.getAttribute("data-strategy") ]).toEqual([ "false", "none" ]);
+ expect(plain.querySelectorAll(".menu .dropdown-item")).toHaveLength(0);
});
});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx
new file mode 100644
index 0000000000..6d0d5b8d45
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ToolCallCard.spec.tsx
@@ -0,0 +1,42 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../../../services/i18n.js", () => ({
+ t: (key: string, options?: { defaultValue?: string }) => (key.startsWith("llm.tools.") ? key.slice("llm.tools.".length) : options?.defaultValue ?? key)
+}));
+vi.mock("../../react/NoteLink.js", () => ({
+ NewNoteLink: ({ notePath }: { notePath: string }) => <a className="note-link-stub">{notePath}</a>
+}));
+
+import ToolCallCard from "./ToolCallCard.js";
+import type { ToolCall } from "./llm_chat_types.js";
+
+let host: HTMLElement | undefined;
+
+afterEach(() => {
+ if (host) {
+ render(null, host);
+ host.remove();
+ host = undefined;
+ }
+});
+
+function renderCard(toolCalls: ToolCall[]) {
+ host = document.body.appendChild(document.createElement("div"));
+ const target = host;
+ act(() => render(<ToolCallCard toolCalls={toolCalls} />, target));
+ return target;
+}
+
+describe("ToolCallCard", () => {
+ it("shows what a call looked for: the name, the query, or the page it read", () => {
+ const card = renderCard([
+ { id: "1", toolName: "search_icons", input: { query: "rocket" }, result: "[]" },
+ { id: "2", toolName: "web_search", input: { query: "weather Sibiu" }, result: "Sunny" },
+ { id: "3", toolName: "read_web_page", input: { url: "https://triliumnotes.org" }, result: "Fetched" }
+ ]);
+ expect([ ...card.querySelectorAll(".llm-chat-tool-call-detail") ].map(detail => detail.textContent))
+ .toEqual([ "rocket", "weather Sibiu", "https://triliumnotes.org" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/llm/antigravity_download.spec.ts b/apps/client/src/widgets/type_widgets/options/llm/antigravity_download.spec.ts
index 70db2dbc46..f4cda61cd6 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/antigravity_download.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/llm/antigravity_download.spec.ts
@@ -1,6 +1,8 @@
-import { describe, expect, it, vi } from "vitest";
+import { h, render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { findAntigravityDownload, registryPlatformKey } from "./antigravity_download";
+import { type AntigravityDownload, findAntigravityDownload, registryPlatformKey, useAntigravityDownload } from "./antigravity_download";
/** The registry's agent.json for antigravity-acp 1.1.1, trimmed to two platforms. */
const ENTRY = {
@@ -64,5 +66,61 @@ describe("findAntigravityDownload", () => {
await expect(findAntigravityDownload("linux", "x64", respondWith(ENTRY, false))).resolves.toEqual({});
// The entry changed shape.
await expect(findAntigravityDownload("linux", "x64", respondWith({ version: "2.0.0" }))).resolves.toEqual({});
+ // The archive is not a URL at all.
+ const broken = { ...ENTRY, distribution: { binary: { "linux-x86_64": { archive: "not a url" } } } };
+ await expect(findAntigravityDownload("linux", "x64", respondWith(broken))).resolves.toEqual({});
+ });
+
+ it("leaves out a version that is not a string", async () => {
+ await expect(findAntigravityDownload("linux", "x64", respondWith({ ...ENTRY, version: 2 })))
+ .resolves.toEqual({ version: undefined, url: ENTRY.distribution.binary["linux-x86_64"].archive });
+ });
+});
+
+describe("useAntigravityDownload", () => {
+ const originalGlob = window.glob;
+ let host: HTMLElement | undefined;
+
+ afterEach(() => {
+ window.glob = originalGlob;
+ vi.unstubAllGlobals();
+ if (host) {
+ render(null, host);
+ host.remove();
+ host = undefined;
+ }
+ });
+
+ /** Mounts the hook for the server's platform and returns what it held after each render. */
+ function mountHook() {
+ window.glob = { ...originalGlob, platform: "linux", arch: "x64" } as typeof window.glob;
+ const seen: AntigravityDownload[] = [];
+ function Probe() {
+ seen.push(useAntigravityDownload());
+ return null;
+ }
+ host = document.body.appendChild(document.createElement("div"));
+ const target = host;
+ act(() => render(h(Probe, null), target));
+ return seen;
+ }
+
+ it("starts empty and then holds the download for the server's platform", async () => {
+ vi.stubGlobal("fetch", respondWith(ENTRY));
+ const seen = mountHook();
+ expect(seen[0]).toEqual({});
+ await vi.waitFor(() => expect(seen.at(-1)?.url).toBe(ENTRY.distribution.binary["linux-x86_64"].archive));
+ });
+
+ it("drops a lookup that finishes after the checklist is gone", async () => {
+ let answer: (value: Response) => void = () => {};
+ vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>(resolve => { answer = resolve; })));
+ const seen = mountHook();
+ const target = host;
+ if (target) {
+ act(() => render(null, target));
+ }
+ await act(async () => answer({ ok: true, status: 200, json: async () => ENTRY } as Response));
+ expect(seen).toEqual([ {} ]);
});
});
diff --git a/apps/server/src/services/llm/providers/acp_agent.ts b/apps/server/src/services/llm/providers/acp_agent.ts
index 642c8b4b5e..cf52588b01 100644
--- a/apps/server/src/services/llm/providers/acp_agent.ts
+++ b/apps/server/src/services/llm/providers/acp_agent.ts
@@ -184,9 +184,7 @@ export abstract class AcpAgentProvider implements LlmProvider {
}
/** The cheap model for the title turn, if the agent offers one. */
- protected titleModelId(): string | undefined {
- return undefined;
- }
+ protected abstract titleModelId(): string | undefined;
/**
* Permission policy. The default denies every request; a subclass whose
@@ -216,10 +214,8 @@ export abstract class AcpAgentProvider implements LlmProvider {
return undefined;
}
- /** Map a failure to an actionable message. */
- protected describeFailure(error: unknown): string {
- return describeError(error);
- }
+ /** Map a failure to an actionable message; {@link describeError} gives the generic one. */
+ protected abstract describeFailure(error: unknown): string;
/**
* The name of the model a turn ran on, for the chat footer: the session's
@@ -413,10 +409,9 @@ export abstract class AcpAgentProvider implements LlmProvider {
noteHint
].filter((s): s is string => Boolean(s)).join("\n\n");
+ const promptSessionId = sessionId;
const onAbort = () => {
- if (sessionId) {
- client?.notify("session/cancel", { sessionId });
- }
+ client?.notify("session/cancel", { sessionId: promptSessionId });
// Wake the drain loop below: an agent slow to honour the cancel
// (or ignoring it) would otherwise keep this generator — and its
// subprocess — suspended until PROMPT_TIMEOUT_MS elapses.
@@ -450,8 +445,7 @@ export abstract class AcpAgentProvider implements LlmProvider {
wakeup = undefined;
continue;
}
- const chunk = chunkQueue.shift();
- if (chunk) {
+ for (const chunk of chunkQueue.splice(0)) {
if (chunk.type === "text") {
assistantText += chunk.content;
}
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
index 95029cc1ec..33ac930b91 100644
--- a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
@@ -44,7 +44,10 @@ class FakeAcpClient {
static current: FakeAcpClient | undefined;
static lastStart: { binary: string; opts: { args?: string[]; env?: Record<string, string>; cwd: string } } | undefined;
static signedIn = true;
- static availableModels: unknown[] = [];
+ /** The catalog `session/new` reports; undefined leaves `models` out of the response. */
+ static availableModels: unknown[] | undefined = [];
+ /** An error `session/new` fails with, when set. */
+ static sessionFailure: Error | undefined;
/** The session/update payloads the agent streams while answering session/prompt. */
static promptUpdates: Record<string, unknown>[] = [];
@@ -66,8 +69,10 @@ class FakeAcpClient {
FakeAcpClient.signedIn = true;
}
if (method === "session/new") {
+ if (FakeAcpClient.sessionFailure) throw FakeAcpClient.sessionFailure;
if (!FakeAcpClient.signedIn) throw SIGN_IN_REQUIRED;
- return { sessionId: "sess-1", models: { currentModelId: "gemini-3.7-flash-high", availableModels: FakeAcpClient.availableModels } } as T;
+ const models = FakeAcpClient.availableModels && { currentModelId: "gemini-3.7-flash-high", availableModels: FakeAcpClient.availableModels };
+ return { sessionId: "sess-1", models } as T;
}
if (method === "session/prompt") {
for (const update of FakeAcpClient.promptUpdates) {
@@ -123,6 +128,7 @@ beforeEach(() => {
FakeAcpClient.lastStart = undefined;
FakeAcpClient.signedIn = true;
FakeAcpClient.availableModels = REMOTE_MODELS;
+ FakeAcpClient.sessionFailure = undefined;
FakeAcpClient.promptUpdates = [];
});
@@ -254,10 +260,58 @@ describe("AntigravityAgentProvider", () => {
expect(await decide({ ...readUrl("https://93.184.215.14/"), toolCall: { kind: "execute", title: "Run read_url_content?", rawInput: { Url: "https://93.184.215.14/" } } }))
.toEqual(denied);
+ // A page read that names no URL.
+ expect(await decide({ ...readUrl(""), toolCall: { kind: "fetch", title: "Run read_url_content?", rawInput: {} } })).toEqual(denied);
+
await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));
expect(await FakeAcpClient.current?.onAgentRequest?.("session/request_permission", readUrl("https://93.184.215.14/"))).toEqual(denied);
});
+ it("explains a failure to start, sign in or answer in words the user can act on", async () => {
+ const failureOf = async (error: Error) => {
+ FakeAcpClient.sessionFailure = error;
+ resetAcpAgentStateForTests();
+ return new AntigravityAgentProvider().listModels().then(() => "resolved", (err: Error) => err.message);
+ };
+ expect(await failureOf(new Error("ACP request \"authenticate\" timed out after 300000ms"))).toMatch(/sign-in was not completed in time/);
+ expect(await failureOf(new Error("spawn C:\\agy\\agy_acp_server.exe ENOENT"))).toBe("Failed to start Google's Antigravity ACP server: spawn C:\\agy\\agy_acp_server.exe ENOENT");
+ expect(await failureOf(new Error("Something else"))).toBe("Something else");
+ });
+
+ it("passes the Linux build the empty --uid= the ACP registry launches it with, and no other build", async () => {
+ const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
+ const argsOn = async (platform: NodeJS.Platform) => {
+ Object.defineProperty(process, "platform", { ...originalPlatform, value: platform });
+ await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));
+ return FakeAcpClient.lastStart?.opts.args;
+ };
+ try {
+ expect(await argsOn("linux")).toEqual([ "--uid=" ]);
+ expect(await argsOn("win32")).toEqual([]);
+ } finally {
+ if (originalPlatform) {
+ Object.defineProperty(process, "platform", originalPlatform);
+ }
+ }
+ });
+
+ it("works with a server that reports no catalog, or one without a Flash Low to title on", async () => {
+ FakeAcpClient.availableModels = undefined;
+ expect((await new AntigravityAgentProvider().listModels()).map(m => m.id)).toEqual([ "default" ]);
+ const chunks = await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));
+ expect(chunks.at(-1)).toEqual({ type: "done" });
+
+ resetAcpAgentStateForTests();
+ FakeAcpClient.availableModels = [ { modelId: "gemini-4-ultra-high", name: "Gemini 4 Ultra (High)" } ];
+ const provider = new AntigravityAgentProvider();
+ expect((await provider.listModels()).map(m => [ m.id, m.name, m.reasoningEfforts ])).toEqual([
+ [ "default", "Default", undefined ],
+ [ "gemini-4-ultra-high", "Gemini 4 Ultra (High)", undefined ]
+ ]);
+ await provider.generateTitle("plan my week");
+ expect(FakeAcpClient.current?.methods()).not.toContain("session/set_model");
+ });
+
it("signs in during the model probe, but reports a missing sign-in in the chat instead", async () => {
FakeAcpClient.signedIn = false;
const chunks = await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));
@@ -352,6 +406,19 @@ describe("tool call updates from agy_acp_server", () => {
{ type: "tool_result", toolCallId: "f6b5", toolName: "search_icons", result: "Search for icons", isError: false }
]);
});
+
+ it("passes an MCP call's input through when it is not wrapped in an arguments object", () => {
+ const chunks: LlmStreamChunk[] = [];
+ const collector = createUpdateCollector(chunk => chunks.push(chunk));
+ const meta = { mcp: { tool: "search_icons", server: "trilium" }, is_mcp_tool_call: true };
+ for (const [ toolCallId, rawInput ] of [ [ "a", { arguments: "font" } ], [ "b", undefined ] ] as const) {
+ collector.onNotification("session/update", {
+ sessionId: "sess-1",
+ update: { sessionUpdate: "tool_call", toolCallId, title: "trilium_search_icons", kind: "other", status: "pending", rawInput, _meta: meta }
+ });
+ }
+ expect(chunks.map(c => c.type === "tool_use" && c.toolInput)).toEqual([ { arguments: "font" }, {} ]);
+ });
});
describe("AntigravityAgentProvider tool calls", () => {
@@ -397,6 +464,18 @@ describe("AntigravityAgentProvider tool calls", () => {
{ type: "tool_use", toolCallId: "0601", toolName: "read_web_page", toolInput: { url: "https://en.wikipedia.org/wiki/Quantum_computing" } }
]);
});
+
+ it("shows an untitled call as a plain tool, and hides a working-file read whatever its input", async () => {
+ const brain = path.join(DATA_DIR, "antigravity-agent", "home", "antigravity-acp", "brain", "06ad", "notes.md");
+ FakeAcpClient.promptUpdates = [
+ { sessionUpdate: "tool_call", toolCallId: "s1", kind: "search", status: "pending", rawInput: { query: "q" } },
+ { sessionUpdate: "tool_call", toolCallId: "f1", kind: "fetch", status: "pending", rawInput: { Url: "https://example.com/" } },
+ { sessionUpdate: "tool_call", toolCallId: "b1", title: "Running view_file", kind: "read", status: "in_progress", locations: [{ path: brain }], rawInput: "notes" }
+ ];
+
+ const chunks = await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], { enableWebSearch: true }));
+ expect(chunks.filter(c => c.type === "tool_use").map(c => [ c.toolCallId, c.toolName ])).toEqual([ [ "s1", "tool" ], [ "f1", "tool" ] ]);
+ });
});
describe("buildAntigravityModelList", () => {
@@ -417,6 +496,29 @@ describe("buildAntigravityModelList", () => {
{ id: "gemini-x", name: "gemini-x", pricing: { input: 0, output: 0 }, isSubscription: true }
]);
});
+
+ it("keeps a label that is no effort level in the name, and defaults to the strongest level without High", () => {
+ const models = buildAntigravityModelList({ availableModels: [
+ { modelId: "gemini-3-pro-ultra", name: "Gemini 3 Pro (Ultra)" },
+ { modelId: "gemini-3.9-flash-low", name: "Gemini 3.9 Flash (Low)" },
+ { modelId: "gemini-3.9-flash-medium", name: "Gemini 3.9 Flash (Medium)" }
+ ] });
+ expect(models.slice(1).map(m => [ m.id, m.name, m.reasoningEfforts, m.defaultReasoningEffort ])).toEqual([
+ [ "gemini-3-pro-ultra", "Gemini 3 Pro (Ultra)", undefined, undefined ],
+ [ "gemini-3.9-flash", "Gemini 3.9 Flash", [ "low", "medium" ], "medium" ]
+ ]);
+ });
+
+ it("compares versions of different lengths as if padded with zeros", () => {
+ const models = buildAntigravityModelList({ availableModels: [
+ { modelId: "gemini-3-flash", name: "Gemini 3 Flash" },
+ { modelId: "gemini-3.1-flash", name: "Gemini 3.1 Flash" },
+ { modelId: "gemini-3.0-pro", name: "Gemini 3.0 Pro" },
+ { modelId: "gemini-3-pro", name: "Gemini 3 Pro" }
+ ] });
+ expect([ ...new AntigravityAgentProvider().recommendedModelIds(models) ].sort())
+ .toEqual([ "default", "gemini-3-pro", "gemini-3.0-pro", "gemini-3.1-flash" ]);
+ });
});
describe("buildAntigravityEnv", () => {
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.ts b/apps/server/src/services/llm/providers/antigravity_agent.ts
index 27818595d3..f97008c3de 100644
--- a/apps/server/src/services/llm/providers/antigravity_agent.ts
+++ b/apps/server/src/services/llm/providers/antigravity_agent.ts
@@ -100,7 +100,14 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
}
}
return new Set(parsed
- .filter(({ name }) => !name || compareVersions(name.version, newestByFamily.get(name.family) ?? []) === 0)
+ .filter(({ name }) => {
+ if (!name) {
+ return true;
+ }
+ /* v8 ignore next -- the loop above records a newest version for every family it parsed. */
+ const newest = newestByFamily.get(name.family) ?? [];
+ return compareVersions(name.version, newest) === 0;
+ })
.map(({ model }) => model.id));
}
@@ -260,6 +267,7 @@ export function buildAntigravityModelList(remote: AcpSessionModelState): ModelIn
const common = { pricing: { input: 0, output: 0 }, isSubscription: true };
if (entry.variants.size === 1) {
const [ [ , modelId ] ] = entry.variants;
+ /* v8 ignore next -- groupAntigravityCatalog names every variant it records. */
return { id: modelId, name: entry.variantNames.get(modelId) ?? modelId, ...common };
}
const reasoningEfforts = sortEfforts([ ...entry.variants.keys() ]);
@@ -287,6 +295,7 @@ export function resolveAntigravityModel(model: string, effort: LlmReasoningEffor
chosen = level;
}
}
+ /* v8 ignore next -- `chosen` is one of `byEffort`'s own keys. */
return byEffort.get(chosen) ?? model;
}
diff --git a/apps/server/src/services/llm/providers/antigravity_binary.spec.ts b/apps/server/src/services/llm/providers/antigravity_binary.spec.ts
index 88a32f5fe9..69d6bc146c 100644
--- a/apps/server/src/services/llm/providers/antigravity_binary.spec.ts
+++ b/apps/server/src/services/llm/providers/antigravity_binary.spec.ts
@@ -9,6 +9,9 @@ vi.mock("child_process", () => ({ execFile: execFileMock }));
const existsSyncMock = vi.hoisted(() => vi.fn((_path: string) => true));
vi.mock("fs", () => ({ existsSync: existsSyncMock }));
+const findOnPathMock = vi.hoisted(() => vi.fn<(binary: string) => Promise<string | undefined>>());
+vi.mock("./binary_lookup.js", () => ({ findOnPath: findOnPathMock }));
+
const logInfoMock = vi.hoisted(() => vi.fn());
vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: logInfoMock, error: vi.fn() }) }));
@@ -68,6 +71,45 @@ describe("resolveAntigravityBinaryPath", () => {
await expect(resolveAntigravityBinaryPath()).resolves.toBe(BINARY);
expect(execFileMock).toHaveBeenCalledTimes(2);
});
+
+ it("probes once for concurrent callers, and reports a failure that is no Error", async () => {
+ probeReturns("");
+ const [ first, second ] = await Promise.all([ resolveAntigravityBinaryPath(), resolveAntigravityBinaryPath() ]);
+ expect([ first, second ]).toEqual([ BINARY, BINARY ]);
+ expect(execFileMock).toHaveBeenCalledTimes(1);
+
+ resetAntigravityBinaryCache();
+ execFileMock.mockImplementationOnce((_binary, _args, _options, cb) => cb("killed by signal" as unknown as Error));
+ await expect(resolveAntigravityBinaryPath()).rejects.toThrow(/failed to run \(killed by signal\)/);
+ });
+
+ it("refuses an override that names no file", async () => {
+ existsSyncMock.mockReturnValueOnce(false);
+ await expect(resolveAntigravityBinaryPath()).rejects.toThrow(`TRILIUM_ANTIGRAVITY_ACP_PATH is set to "${BINARY}", but no file exists there.`);
+ expect(execFileMock).not.toHaveBeenCalled();
+ });
+
+ it("looks for the platform's executable on PATH without an override", async () => {
+ const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
+ delete process.env.TRILIUM_ANTIGRAVITY_ACP_PATH;
+ probeReturns("");
+ try {
+ Object.defineProperty(process, "platform", { ...originalPlatform, value: "linux" });
+ findOnPathMock.mockResolvedValueOnce("/opt/agy/agy_acp_server.par");
+ await expect(resolveAntigravityBinaryPath()).resolves.toBe("/opt/agy/agy_acp_server.par");
+ expect(findOnPathMock).toHaveBeenLastCalledWith("agy_acp_server.par");
+
+ resetAntigravityBinaryCache();
+ Object.defineProperty(process, "platform", { ...originalPlatform, value: "win32" });
+ findOnPathMock.mockResolvedValueOnce(undefined);
+ await expect(resolveAntigravityBinaryPath()).rejects.toThrow(/was not found\. Put the folder.*Google Antigravity/s);
+ expect(findOnPathMock).toHaveBeenLastCalledWith("agy_acp_server");
+ } finally {
+ if (originalPlatform) {
+ Object.defineProperty(process, "platform", originalPlatform);
+ }
+ }
+ });
});
describe("parseBuildLabel", () => {
diff --git a/apps/server/src/services/llm/providers/antigravity_hook.spec.ts b/apps/server/src/services/llm/providers/antigravity_hook.spec.ts
index 32b6eabe99..2d276fcf6f 100644
--- a/apps/server/src/services/llm/providers/antigravity_hook.spec.ts
+++ b/apps/server/src/services/llm/providers/antigravity_hook.spec.ts
@@ -48,6 +48,8 @@ describe("decideAntigravityToolCall", () => {
const shouted = path.join(HOME, "ANTIGRAVITY-ACP", "acp_token.json");
expect(decide("view_file", { AbsolutePath: shouted }, undefined, "win32")).toBe("deny");
expect(decide("view_file", { AbsolutePath: shouted }, undefined, "darwin")).toBe("deny");
+ // Case-sensitive file systems: the exact spelling is still refused.
+ expect(decide("view_file", { AbsolutePath: path.join(PRIVATE, "acp_token.json") }, undefined, "linux")).toBe("deny");
});
it("allows the read tools elsewhere and leaves every other tool to the permission flow", () => {
diff --git a/apps/server/src/services/llm/providers/antigravity_hook.ts b/apps/server/src/services/llm/providers/antigravity_hook.ts
index 7f79f038a7..942b837590 100644
--- a/apps/server/src/services/llm/providers/antigravity_hook.ts
+++ b/apps/server/src/services/llm/providers/antigravity_hook.ts
@@ -158,6 +158,7 @@ function canonicalPath(candidate: string): string {
let existing = candidate;
while (!existsSync(existing)) {
const parent = path.dirname(existing);
+ /* v8 ignore next 3 -- only a root that does not exist, such as a missing Windows drive, ends here. */
if (parent === existing) {
return candidate;
}
@@ -167,6 +168,7 @@ function canonicalPath(candidate: string): string {
try {
return path.join(realpathSync.native(existing), ...rest);
} catch {
+ /* v8 ignore next -- the path existed a moment ago; it can only be removed or locked in between. */
return candidate;
}
}
diff --git a/apps/server/src/services/llm/providers/copilot_agent.spec.ts b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
index 1887cc4579..9465fe2648 100644
--- a/apps/server/src/services/llm/providers/copilot_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
@@ -219,6 +219,15 @@ describe("CopilotAgentProvider.listModels", () => {
.toEqual(["auto", "claude-haiku-4.5", "claude-sonnet-5", "gpt-5-mini"]);
});
+ it("treats a premium rate it cannot read like no rate at all", async () => {
+ FakeAcpClient.sessionModels = { availableModels: [
+ { modelId: "mystery", name: "Mystery", _meta: { copilotUsage: "varies", copilotEnablement: "enabled" } }
+ ] };
+
+ const provider = new CopilotAgentProvider();
+ expect([...provider.recommendedModelIds(await provider.listModels())]).toContain("mystery");
+ });
+
it("probes once, then serves the cached catalog without respawning the CLI", async () => {
FakeAcpClient.sessionModels = { availableModels: CLI_MODELS };
const provider = new CopilotAgentProvider();
diff --git a/apps/server/src/services/llm/providers/public_url.spec.ts b/apps/server/src/services/llm/providers/public_url.spec.ts
index 23c28ee33a..0227deb07e 100644
--- a/apps/server/src/services/llm/providers/public_url.spec.ts
+++ b/apps/server/src/services/llm/providers/public_url.spec.ts
@@ -61,4 +61,8 @@ describe("isPublicHttpUrl", () => {
expect(await isPublicHttpUrl("https://rebind.example/", lookup)).toBe(false);
expect(await isPublicHttpUrl("https://unknown.example/", lookup)).toBe(false);
});
+
+ it("resolves names with the system resolver by default", async () => {
+ expect(await isPublicHttpUrl("http://localhost:8080/")).toBe(false);
+ });
});