Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): pick Antigravity's reasoning effort in the chat, not the model list

Elian Doran259151d142ad
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index ea085108ad..03f46ece11 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2586,6 +2586,16 @@
"sources": "Sources",
"sources_summary": "{{count}} sources from {{sites}} sites",
"extended_thinking": "Extended thinking",
+ "reasoning_effort_title": "Reasoning effort: {{level}}",
+ "reasoning_effort_levels": {
+ "none": "None",
+ "minimal": "Minimal",
+ "low": "Low",
+ "medium": "Medium",
+ "high": "High",
+ "xhigh": "Extra high",
+ "max": "Maximum"
+ },
"model_cost_included": "Subscription",
"no_models_selected": "No models selected — click the pencil to choose",
"no_model_selected": "Select a model",
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
index 144c0d6ec8..37efb222b5 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.css
@@ -242,6 +242,10 @@
min-width: 0;
}
+.llm-chat-reasoning-effort-icon {
+ margin-inline-end: 0.35em;
+}
+
.llm-chat-model-select-name {
overflow: hidden;
text-overflow: ellipsis;
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index ec09ed2402..5790ffea7d 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -1,7 +1,7 @@
import "./ChatInputBar.css";
import type { AttributeEditor as CKEditorAttributeEditor, CKTextEditor, MentionFeed } from "@triliumnext/ckeditor5";
-import type { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
+import type { DISPLAYABLE_LOCALE_IDS, LlmReasoningEffort } from "@triliumnext/commons";
import { Fragment } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
@@ -22,6 +22,7 @@ import { computeContextUsage } from "./chat_context_usage.js";
import { insertNewBlock as insertNewBlockCommand, isSelectionInCodeBlock, outdentListItemAtStart } from "./chat_input_editing.js";
import { editorHtmlToMarkdown } from "./chat_input_markdown.js";
import { shortModelName } from "./model_name.js";
+import ReasoningEffortDropdown from "./ReasoningEffortDropdown.js";
import { SafeImage } from "./retry_image.js";
import { useChatAttachments } from "./useChatAttachments.js";
import { type ModelOption, resolveSelectedModel } from "../../../services/llm_providers.js";
@@ -75,7 +76,7 @@ interface ChatInputBarProps {
onWebSearchChange?: () => void;
/** Callback when note tools toggle changes */
onNoteToolsChange?: () => void;
- /** Callback when extended thinking toggle changes */
+ /** Callback when the extended thinking switch or the reasoning effort changes */
onExtendedThinkingChange?: () => void;
/** Callback when model changes */
onModelChange?: (model: string) => void;
@@ -184,6 +185,11 @@ export default function ChatInputBar({
onExtendedThinkingChange?.();
};
+ const handleReasoningEffortChange = (effort: LlmReasoningEffort) => {
+ chat.setReasoningEffort(effort);
+ onExtendedThinkingChange?.();
+ };
+
const handleModelSelect = (model: ModelOption) => {
chat.setSelectedModel(model.id, model.provider, model.providerId);
onModelChange?.(model.id);
@@ -473,6 +479,15 @@ export default function ChatInputBar({
</Fragment>
))}
</Dropdown>
+ {currentModel?.reasoningEfforts?.length ? (
+ <ReasoningEffortDropdown
+ model={currentModel}
+ value={chat.reasoningEffort}
+ onChange={handleReasoningEffortChange}
+ disabled={chat.isStreaming}
+ inSidebar={inSidebar}
+ />
+ ) : null}
</div>
{/* What the model can reach this turn. Lifted out of the model dropdown so
their state reads at a glance and flipping one is a single click — the
@@ -494,13 +509,15 @@ export default function ChatInputBar({
onToggle={handleNoteToolsToggle}
disabled={chat.isStreaming}
/>
- <CapabilityToggle
- icon="bx bx-brain"
- label={t("llm_chat.extended_thinking")}
- active={chat.enableExtendedThinking}
- onToggle={handleExtendedThinkingToggle}
- disabled={chat.isStreaming}
- />
+ {!currentModel?.reasoningEfforts?.length && (
+ <CapabilityToggle
+ icon="bx bx-brain"
+ label={t("llm_chat.extended_thinking")}
+ active={chat.enableExtendedThinking}
+ onToggle={handleExtendedThinkingToggle}
+ disabled={chat.isStreaming}
+ />
+ )}
</div>
{/* The actions, boxed so they keep a fixed gap from the capabilities. The
row's `auto` spacer collapses to nothing once the row is full — which is
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
new file mode 100644
index 0000000000..d93973b882
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ReasoningEffortDropdown.spec.tsx
@@ -0,0 +1,76 @@
+import type { LlmModelInfo } from "@triliumnext/commons";
+import { type ComponentChildren, 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?: { level?: string }) => (options?.level ? `${key}(${options.level})` : key)
+}));
+
+// Renders the toggle's face, its tooltip and class, and the menu, without Bootstrap.
+vi.mock("../../react/Dropdown.js", () => ({
+ default: ({ text, title, buttonClassName, children }: { text: ComponentChildren; title?: string; buttonClassName?: string; children: ComponentChildren }) => (
+ <div className="dropdown-stub">
+ <button className={buttonClassName} title={title}>{text}</button>
+ <div className="menu">{children}</div>
+ </div>
+ )
+}));
+
+import ReasoningEffortDropdown, { effectiveReasoningEffort } from "./ReasoningEffortDropdown.js";
+
+const FLASH: LlmModelInfo = { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", reasoningEfforts: [ "low", "medium", "high" ], defaultReasoningEffort: "high" };
+const PRO: LlmModelInfo = { id: "gemini-3.1-pro", name: "Gemini 3.1 Pro", reasoningEfforts: [ "low", "high" ], defaultReasoningEffort: "high" };
+
+let host: HTMLElement | undefined;
+
+afterEach(() => {
+ if (host) {
+ render(null, host);
+ host.remove();
+ host = undefined;
+ }
+});
+
+function renderDropdown(model: LlmModelInfo, value: Parameters<typeof ReasoningEffortDropdown>[0]["value"], onChange = vi.fn()) {
+ host = document.body.appendChild(document.createElement("div"));
+ const target = host;
+ act(() => render(<ReasoningEffortDropdown model={model} value={value} onChange={onChange} />, target));
+ return { host: target, onChange };
+}
+
+describe("effectiveReasoningEffort", () => {
+ it("uses the chat's level where the model has it, the model's default otherwise", () => {
+ expect(effectiveReasoningEffort(FLASH, "medium")).toBe("medium");
+ expect(effectiveReasoningEffort(PRO, "medium")).toBe("high");
+ expect(effectiveReasoningEffort(PRO, undefined)).toBe("high");
+ expect(effectiveReasoningEffort({ ...PRO, defaultReasoningEffort: undefined }, undefined)).toBe("high");
+ });
+});
+
+describe("ReasoningEffortDropdown", () => {
+ it("lists the model's levels, ticks the one in effect and picks another", () => {
+ const { host, onChange } = renderDropdown(PRO, "medium");
+
+ // Only the levels: the toggle's tooltip already names the menu.
+ expect(host.querySelector(".menu")?.children.length).toBe(2);
+ const items = [ ...host.querySelectorAll<HTMLElement>(".menu .dropdown-item") ];
+ expect(items.map(item => item.textContent?.trim())).toEqual([
+ "llm_chat.reasoning_effort_levels.low",
+ "llm_chat.reasoning_effort_levels.high"
+ ]);
+ // Pro has no Medium, so High is in effect and ticked.
+ expect(items.map(item => item.classList.contains("checked") || !!item.querySelector(".bx-check"))).toEqual([ false, true ]);
+ expect(host.querySelector("button")?.title).toBe("llm_chat.reasoning_effort_title(llm_chat.reasoning_effort_levels.high)");
+
+ act(() => items[0].click());
+ expect(onChange).toHaveBeenCalledWith("low");
+ });
+
+ it("reads like the model picker: a combobox naming the level in effect", () => {
+ const button = renderDropdown(FLASH, "low").host.querySelector("button");
+ expect(button?.classList.contains("llm-chat-model-select")).toBe(true);
+ expect(button?.textContent).toBe("llm_chat.reasoning_effort_levels.low");
+ expect(button?.querySelector(".bx-brain")).not.toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ReasoningEffortDropdown.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ReasoningEffortDropdown.tsx
new file mode 100644
index 0000000000..3b3f3ac0a9
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ReasoningEffortDropdown.tsx
@@ -0,0 +1,57 @@
+import type { LlmModelInfo, LlmReasoningEffort } from "@triliumnext/commons";
+
+import { t } from "../../../services/i18n.js";
+import Dropdown from "../../react/Dropdown.js";
+import { FormListItem } from "../../react/FormList.js";
+import Icon from "../../react/Icon.js";
+
+/**
+ * The reasoning effort picker of the chat input bar, for a model that lists
+ * `reasoningEfforts`; such a model has no extended thinking switch. It stands
+ * beside the model picker and shares its combobox styling.
+ */
+export default function ReasoningEffortDropdown({ model, value, onChange, disabled, inSidebar }: {
+ model: LlmModelInfo;
+ /** The chat's chosen level; undefined means the model's default. */
+ value: LlmReasoningEffort | undefined;
+ onChange: (effort: LlmReasoningEffort) => void;
+ disabled?: boolean;
+ inSidebar?: boolean;
+}) {
+ const effective = effectiveReasoningEffort(model, value);
+ const label = t(`llm_chat.reasoning_effort_levels.${effective}`);
+
+ return (
+ <Dropdown
+ text={<>
+ <Icon icon="bx bx-brain" className="llm-chat-reasoning-effort-icon" />
+ <span className="llm-chat-model-select-name">{label}</span>
+ </>}
+ title={t("llm_chat.reasoning_effort_title", { level: label })}
+ titlePosition="top"
+ buttonClassName="llm-chat-model-select"
+ className="llm-chat-reasoning-effort"
+ disabled={disabled}
+ // A few items, so the menu never scrolls and keeps the working backdrop blur.
+ noDropdownListStyle
+ // Same reason as the model selector: the sidebar clips an unportaled menu.
+ portalToBody={inSidebar}
+ dropdownOptions={inSidebar ? { popperConfig: { strategy: "fixed" } } : undefined}
+ >
+ {(model.reasoningEfforts ?? []).map(level => (
+ <FormListItem key={level} checked={level === effective} onClick={() => onChange(level)}>
+ {t(`llm_chat.reasoning_effort_levels.${level}`)}
+ </FormListItem>
+ ))}
+ </Dropdown>
+ );
+}
+
+/** The level a turn runs at: the chat's choice where the model has it, else the model's default, else its strongest. */
+export function effectiveReasoningEffort(model: LlmModelInfo, value: LlmReasoningEffort | undefined): LlmReasoningEffort {
+ const levels = model.reasoningEfforts ?? [];
+ if (value && levels.includes(value)) {
+ return value;
+ }
+ return model.defaultReasoningEffort ?? levels[levels.length - 1] ?? "high";
+}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
index 57e4ff4303..703e6b5a4e 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts
@@ -1,4 +1,4 @@
-import type { LlmCitation, LlmErrorDetails, LlmUsage } from "@triliumnext/commons";
+import type { LlmCitation, LlmErrorDetails, LlmReasoningEffort, LlmUsage } from "@triliumnext/commons";
export type MessageType = "message" | "error" | "thinking";
@@ -174,4 +174,6 @@ export interface LlmChatContent {
enableWebSearch?: boolean;
enableNoteTools?: boolean;
enableExtendedThinking?: boolean;
+ /** The effort chosen for a model with levels; absent means the model's default. */
+ reasoningEffort?: LlmReasoningEffort;
}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
index 1bc19c5d6a..8343009662 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx
@@ -218,6 +218,50 @@ describe("useLlmChat", () => {
expect(api().lastCompletionTokens).toBe(0);
});
+ it("keeps, saves and sends the reasoning effort, only for a model that has levels", async () => {
+ optionsGetJsonMock.mockReturnValue([
+ ...PROVIDERS,
+ { id: "ag_1", name: "Google Antigravity", provider: "antigravity-agent", selectedModels: [
+ { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", reasoningEfforts: [ "low", "medium", "high" ], defaultReasoningEffort: "high" }
+ ] }
+ ]);
+ await mountChat();
+ const sentOptions = async () => {
+ streamChatCompletionMock.mockClear();
+ await act(async () => {
+ api().setInput("hi");
+ });
+ await act(async () => {
+ await api().handleSubmit(new Event("submit"));
+ });
+ return streamChatCompletionMock.mock.calls[0][1];
+ };
+
+ await act(async () => {
+ api().setSelectedModel("gemini-3.8-flash", "antigravity-agent", "ag_1");
+ });
+ expect(api().reasoningEffort).toBeUndefined();
+ expect((await sentOptions()).reasoningEffort).toBeUndefined();
+
+ await act(async () => {
+ api().setReasoningEffort("low");
+ });
+ expect(api().getContent()).toMatchObject({ reasoningEffort: "low" });
+ expect((await sentOptions()).reasoningEffort).toBe("low");
+
+ // A model without levels is sent none.
+ await act(async () => {
+ api().setSelectedModel("opus", "anthropic", "a_1");
+ });
+ expect((await sentOptions()).reasoningEffort).toBeUndefined();
+
+ // A saved chat brings its level back.
+ await act(async () => {
+ api().loadFromContent({ version: 1, messages: [], selectedModel: "gemini-3.8-flash", selectedProvider: "antigravity-agent", selectedProviderId: "ag_1", reasoningEffort: "medium" });
+ });
+ expect(api().reasoningEffort).toBe("medium");
+ });
+
it("round-trips the selected provider through getContent", async () => {
await mountChat();
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
index 4fffb9e03f..39d8c41f05 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts
@@ -1,4 +1,4 @@
-import type { LlmCitation, LlmMessage, LlmMessagePart, LlmModelInfo, LlmUsage } from "@triliumnext/commons";
+import { LLM_REASONING_EFFORTS, type LlmCitation, type LlmMessage, type LlmMessagePart, type LlmModelInfo, type LlmReasoningEffort, type LlmUsage } from "@triliumnext/commons";
import { RefObject } from "preact";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
@@ -109,6 +109,8 @@ export interface UseLlmChatReturn {
enableWebSearch: boolean;
enableNoteTools: boolean;
enableExtendedThinking: boolean;
+ /** The effort chosen for a model with levels; undefined means the model's default. */
+ reasoningEffort: LlmReasoningEffort | undefined;
contextNoteId: string | undefined;
/** The chat note's ID — used as the upload target for attachments. */
chatNoteId: string | undefined;
@@ -145,6 +147,7 @@ export interface UseLlmChatReturn {
setEnableWebSearch: (value: boolean) => void;
setEnableNoteTools: (value: boolean) => void;
setEnableExtendedThinking: (value: boolean) => void;
+ setReasoningEffort: (value: LlmReasoningEffort | undefined) => void;
setContextNoteId: (noteId: string | undefined) => void;
setChatNoteId: (noteId: string | undefined) => void;
/** Append a freshly uploaded image or file to the pending-attachments list. */
@@ -208,6 +211,7 @@ export function useLlmChat(
const [enableWebSearch, setEnableWebSearch] = useState(true);
const [enableNoteTools, setEnableNoteTools] = useState(defaultEnableNoteTools);
const [enableExtendedThinking, setEnableExtendedThinking] = useState(false);
+ const [reasoningEffort, setReasoningEffort] = useState<LlmReasoningEffort | undefined>(undefined);
const [contextNoteId, setContextNoteId] = useState<string | undefined>(initialContextNoteId);
const [chatNoteId, setChatNoteIdState] = useState<string | undefined>(initialChatNoteId);
const [lastPromptTokens, setLastPromptTokens] = useState<number>(0);
@@ -249,6 +253,8 @@ export function useLlmChat(
enableNoteToolsRef.current = enableNoteTools;
const enableExtendedThinkingRef = useRef(enableExtendedThinking);
enableExtendedThinkingRef.current = enableExtendedThinking;
+ const reasoningEffortRef = useRef(reasoningEffort);
+ reasoningEffortRef.current = reasoningEffort;
const chatNoteIdRef = useRef(chatNoteId);
chatNoteIdRef.current = chatNoteId;
const setChatNoteId = useCallback((noteId: string | undefined) => {
@@ -506,6 +512,7 @@ export function useLlmChat(
if (supportsExtendedThinking && typeof content.enableExtendedThinking === "boolean") {
setEnableExtendedThinking(content.enableExtendedThinking);
}
+ setReasoningEffort(LLM_REASONING_EFFORTS.find(level => level === content.reasoningEffort));
// Restore last prompt tokens from the most recent message with usage
const lastUsage = [...(content.messages || [])].reverse().find(m => m.usage)?.usage;
setLastPromptTokens(lastUsage?.promptTokens ?? 0);
@@ -526,6 +533,9 @@ export function useLlmChat(
if (supportsExtendedThinking) {
content.enableExtendedThinking = enableExtendedThinkingRef.current;
}
+ if (reasoningEffortRef.current) {
+ content.reasoningEffort = reasoningEffortRef.current;
+ }
return content;
}, [supportsExtendedThinking]);
@@ -590,6 +600,9 @@ export function useLlmChat(
if (supportsExtendedThinking) {
streamOptions.enableExtendedThinking = enableExtendedThinking;
}
+ if (reasoningEffort && matchedModel?.reasoningEfforts?.length) {
+ streamOptions.reasoningEffort = reasoningEffort;
+ }
const abortController = new AbortController();
abortControllerRef.current = abortController;
@@ -806,7 +819,7 @@ export function useLlmChat(
setIsStreaming(false);
abortControllerRef.current = null;
});
- }, [selectedModel, selectedProvider, selectedProviderId, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, contextNoteId, supportsExtendedThinking, setMessages, smoothAppend, smoothDrain, smoothReset]);
+ }, [selectedModel, selectedProvider, selectedProviderId, availableModels, enableWebSearch, enableNoteTools, enableExtendedThinking, reasoningEffort, contextNoteId, supportsExtendedThinking, setMessages, smoothAppend, smoothDrain, smoothReset]);
const handleSubmit = useCallback(async (e: Event) => {
e.preventDefault();
@@ -918,6 +931,7 @@ export function useLlmChat(
enableWebSearch,
enableNoteTools,
enableExtendedThinking,
+ reasoningEffort,
contextNoteId,
chatNoteId,
lastPromptTokens,
@@ -942,6 +956,7 @@ export function useLlmChat(
setEnableWebSearch,
setEnableNoteTools,
setEnableExtendedThinking,
+ setReasoningEffort,
setContextNoteId,
setChatNoteId,
addPendingAttachment,
diff --git a/apps/server/src/services/llm/providers/acp_agent.ts b/apps/server/src/services/llm/providers/acp_agent.ts
index a51490ec75..bbe229c474 100644
--- a/apps/server/src/services/llm/providers/acp_agent.ts
+++ b/apps/server/src/services/llm/providers/acp_agent.ts
@@ -168,6 +168,15 @@ export abstract class AcpAgentProvider implements LlmProvider {
abstract recommendedModelIds(models: ModelInfo[]): Set<string>;
+ /**
+ * The id to hand `session/set_model` for the chat's model and settings. A
+ * provider whose agent names an effort level inside the model id maps
+ * {@link LlmProviderConfig.reasoningEffort} here.
+ */
+ protected sessionModelId(model: string, _config: LlmProviderConfig): string {
+ return model;
+ }
+
/** The cheap model for the title turn, if the agent offers one. */
protected titleModelId(): string | undefined {
return undefined;
@@ -345,7 +354,7 @@ export abstract class AcpAgentProvider implements LlmProvider {
// Model selection is an optional ACP capability — degrade to the
// agent's default rather than failing the turn.
try {
- await client.request("session/set_model", { sessionId, modelId: model }, INIT_TIMEOUT_MS);
+ await client.request("session/set_model", { sessionId, modelId: this.sessionModelId(model, config) }, INIT_TIMEOUT_MS);
} catch (err) {
getLog().error(`${this.logLabel}: failed to select model "${model}" (${describeError(err)}); continuing with the agent's default.`);
}
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 b3a6a3ada9..d4b26dcd80 100644
--- a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
@@ -91,11 +91,14 @@ async function collect(iterable: AsyncIterable<LlmStreamChunk>): Promise<LlmStre
return chunks;
}
+/** The catalog agy_acp_server 1.1.1 reports on session/new, newest first. */
const REMOTE_MODELS = [
- { modelId: "gemini-3.8-flash-high", name: "Gemini 3.8 Flash (High)" },
- { modelId: "gemini-3.8-flash-low", name: "Gemini 3.8 Flash (Low)" },
- { modelId: "gemini-3.7-flash-low", name: "Gemini 3.7 Flash (Low)" },
- { modelId: "gemini-pro-agent", name: "Gemini 3.1 Pro (High)" }
+ ...["3.8", "3.7", "3.6"].flatMap(version => ["High", "Medium", "Low"].map(effort => ({
+ modelId: `gemini-${version}-flash-${effort.toLowerCase()}`,
+ name: `Gemini ${version} Flash (${effort})`
+ }))),
+ { modelId: "gemini-pro-agent", name: "Gemini 3.1 Pro (High)" },
+ { modelId: "gemini-3.1-pro-low", name: "Gemini 3.1 Pro (Low)" }
];
const PERMISSION_OPTIONS = [
@@ -181,7 +184,7 @@ describe("AntigravityAgentProvider", () => {
const models = await new AntigravityAgentProvider().listModels();
expect(FakeAcpClient.current?.methods()).toEqual(["initialize", "session/new", "authenticate", "session/new"]);
expect(FakeAcpClient.current?.requests[2].params).toEqual({ methodId: "oauth-personal" });
- expect(models.map(m => m.id)).toEqual(["default", "gemini-3.8-flash-high", "gemini-3.8-flash-low", "gemini-3.7-flash-low", "gemini-pro-agent"]);
+ expect(models.map(m => m.id)).toEqual(["default", "gemini-3.8-flash", "gemini-3.7-flash", "gemini-3.6-flash", "gemini-3.1-pro"]);
});
it("leaves the default model to the server, selects any other, and titles on the newest Flash Low", async () => {
@@ -197,28 +200,33 @@ describe("AntigravityAgentProvider", () => {
expect(FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params).toEqual({ sessionId: "sess-1", modelId: "gemini-3.8-flash-low" });
});
- it("pre-selects the newest version of each family, every effort level included", () => {
- // The catalog agy_acp_server 1.1.1 reports on session/new, newest first.
+ it("pre-selects the newest version of each family", () => {
const models = buildAntigravityModelList({ availableModels: [
- ...["3.8", "3.7", "3.6"].flatMap(version => ["High", "Medium", "Low"].map(effort => ({
- modelId: `gemini-${version}-flash-${effort.toLowerCase()}`,
- name: `Gemini ${version} Flash (${effort})`
- }))),
- { modelId: "gemini-pro-agent", name: "Gemini 3.1 Pro (High)" },
- { modelId: "gemini-3.1-pro-low", name: "Gemini 3.1 Pro (Low)" },
+ ...REMOTE_MODELS,
// A model named some other way is kept rather than hidden.
{ modelId: "gemini-nano-agent", name: "Gemini Nano Agent" }
] });
- expect([...new AntigravityAgentProvider().recommendedModelIds(models)].sort()).toEqual([
- "default",
- "gemini-3.1-pro-low",
- "gemini-3.8-flash-high",
- "gemini-3.8-flash-low",
- "gemini-3.8-flash-medium",
- "gemini-nano-agent",
- "gemini-pro-agent"
- ]);
+ expect([...new AntigravityAgentProvider().recommendedModelIds(models)].sort())
+ .toEqual([ "default", "gemini-3.1-pro", "gemini-3.8-flash", "gemini-nano-agent" ]);
+ });
+
+ it("runs a model at the effort the chat chose, the model's default otherwise", async () => {
+ const provider = new AntigravityAgentProvider();
+ const modelSetFor = async (config: Record<string, unknown>) => {
+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], config));
+ return (FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params as { modelId?: string } | undefined)?.modelId;
+ };
+
+ expect(await modelSetFor({ model: "gemini-3.8-flash", reasoningEffort: "medium" })).toBe("gemini-3.8-flash-medium");
+ expect(await modelSetFor({ model: "gemini-3.1-pro", reasoningEffort: "low" })).toBe("gemini-3.1-pro-low");
+ // No choice: the model's default, High.
+ expect(await modelSetFor({ model: "gemini-3.1-pro" })).toBe("gemini-pro-agent");
+ // A level the model lacks: the nearest one, the higher on a tie.
+ expect(await modelSetFor({ model: "gemini-3.1-pro", reasoningEffort: "medium" })).toBe("gemini-pro-agent");
+ expect(await modelSetFor({ model: "gemini-3.8-flash", reasoningEffort: "minimal" })).toBe("gemini-3.8-flash-low");
+ // A variant id saved before the variants were grouped still works.
+ expect(await modelSetFor({ model: "gemini-3.7-flash-low", reasoningEffort: "high" })).toBe("gemini-3.7-flash-low");
});
});
@@ -275,6 +283,17 @@ describe("AntigravityAgentProvider tool calls", () => {
});
describe("buildAntigravityModelList", () => {
+ it("lists each model once, with the efforts it comes in", () => {
+ const efforts = { pricing: { input: 0, output: 0 }, isSubscription: true, defaultReasoningEffort: "high" };
+ expect(buildAntigravityModelList({ availableModels: REMOTE_MODELS })).toEqual([
+ { id: "default", name: "Default", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true },
+ { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", reasoningEfforts: [ "low", "medium", "high" ], ...efforts },
+ { id: "gemini-3.7-flash", name: "Gemini 3.7 Flash", reasoningEfforts: [ "low", "medium", "high" ], ...efforts },
+ { id: "gemini-3.6-flash", name: "Gemini 3.6 Flash", reasoningEfforts: [ "low", "medium", "high" ], ...efforts },
+ { id: "gemini-3.1-pro", name: "Gemini 3.1 Pro", reasoningEfforts: [ "low", "high" ], ...efforts }
+ ]);
+ });
+
it("leads with the server's own default and keeps the server's order and names", () => {
expect(buildAntigravityModelList({ availableModels: [{ modelId: "gemini-x" }, { modelId: "default" }, { modelId: "" }] })).toEqual([
{ id: "default", name: "Default", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true },
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.ts b/apps/server/src/services/llm/providers/antigravity_agent.ts
index 06d291a1a4..59c182831a 100644
--- a/apps/server/src/services/llm/providers/antigravity_agent.ts
+++ b/apps/server/src/services/llm/providers/antigravity_agent.ts
@@ -16,7 +16,8 @@
* Trilium's note tools.
*/
-import type { ModelInfo } from "@triliumnext/core/src/services/llm/types.js";
+import { LLM_REASONING_EFFORTS, type LlmReasoningEffort } from "@triliumnext/commons";
+import type { LlmProviderConfig, ModelInfo } from "@triliumnext/core/src/services/llm/types.js";
import { existsSync } from "fs";
import path from "path";
@@ -58,8 +59,13 @@ const LINUX_CA_BUNDLES = [
"/etc/ssl/cert.pem"
];
-/** The cheap model for the title turn, recorded from the last probe. */
-let titleModel: string | undefined;
+/**
+ * What the last catalog the server reported says about its variants: for each
+ * listed model, the real id of each effort level, and the cheap model for the
+ * title turn. Every `session/new` refreshes it, so a chat turn resolves
+ * against the catalog of the session it runs in.
+ */
+let catalog: { variants: Map<string, Map<LlmReasoningEffort, string>>; titleModel?: string } = { variants: new Map() };
export class AntigravityAgentProvider extends AcpAgentProvider {
name = "antigravity-agent";
@@ -93,7 +99,11 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
}
protected titleModelId(): string | undefined {
- return titleModel;
+ return catalog.titleModel;
+ }
+
+ protected sessionModelId(model: string, config: LlmProviderConfig): string {
+ return resolveAntigravityModel(model, config.reasoningEffort, catalog.variants);
}
protected async launchSpec(): Promise<AcpLaunchSpec> {
@@ -107,9 +117,8 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
}
protected buildModelList(remote: AcpSessionModelState): ModelInfo[] {
- const models = buildAntigravityModelList(remote);
- titleModel = pickTitleModel(models);
- return models;
+ recordCatalog(remote);
+ return buildAntigravityModelList(remote);
}
protected decidePermission(request: AcpPermissionRequest): AcpPermissionOutcome {
@@ -134,15 +143,20 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
* sign-in under `GEMINI_HOME`, so later sessions need none.
*/
protected async createSession(client: AcpClient, params: AcpNewSessionParams, interactive: boolean, timeoutMs: number) {
+ let created: Awaited<ReturnType<AcpAgentProvider["createSession"]>>;
try {
- return await super.createSession(client, params, interactive, timeoutMs);
+ created = await super.createSession(client, params, interactive, timeoutMs);
} catch (err) {
if (!interactive || !isSignInRequired(err)) {
throw err;
}
+ await client.request("authenticate", { methodId: SIGN_IN_METHOD }, SIGN_IN_TIMEOUT_MS);
+ created = await super.createSession(client, params, interactive, timeoutMs);
+ }
+ if (created.models) {
+ recordCatalog(created.models);
}
- await client.request("authenticate", { methodId: SIGN_IN_METHOD }, SIGN_IN_TIMEOUT_MS);
- return await super.createSession(client, params, interactive, timeoutMs);
+ return created;
}
protected describeFailure(error: unknown): string {
@@ -182,20 +196,47 @@ export function decideAntigravityPermission(request: AcpPermissionRequest, logLa
}
/**
- * The server's catalog, led by the entry that defers to its own default. The
- * server's order is kept: it is the picker Antigravity itself shows, newest
- * first.
+ * The server's catalog, led by the entry that defers to its own default, with
+ * each model listed once. The server names an effort level inside the model
+ * (`Gemini 3.8 Flash (High)`, `gemini-3.8-flash-high`), so its variants
+ * become one entry, `gemini-3.8-flash`, that lists the levels as
+ * `reasoningEfforts`; {@link resolveAntigravityModel} picks the variant for a
+ * turn. The server's order is kept: it is the picker Antigravity itself
+ * shows, newest first.
*/
export function buildAntigravityModelList(remote: AcpSessionModelState): ModelInfo[] {
- const models = (remote.availableModels ?? [])
- .filter(m => m.modelId && m.modelId !== DEFAULT_MODEL_ID)
- .map<ModelInfo>(m => ({
- id: m.modelId,
- name: m.name ?? m.modelId,
- pricing: { input: 0, output: 0 },
- isSubscription: true
- }));
- return [...AVAILABLE_MODELS, ...models];
+ const models = groupAntigravityCatalog(remote).map<ModelInfo>(entry => {
+ const common = { pricing: { input: 0, output: 0 }, isSubscription: true };
+ if (entry.variants.size === 1) {
+ const [ [ , modelId ] ] = entry.variants;
+ return { id: modelId, name: entry.variantNames.get(modelId) ?? modelId, ...common };
+ }
+ const reasoningEfforts = sortEfforts([ ...entry.variants.keys() ]);
+ return { id: entry.id, name: entry.name, ...common, reasoningEfforts, defaultReasoningEffort: defaultEffort(reasoningEfforts) };
+ });
+ return [ ...AVAILABLE_MODELS, ...models ];
+}
+
+/**
+ * The real model id for a listed model at an effort level: the variant for
+ * that level, the nearest one when the model lacks it (the higher on a tie),
+ * or the model's default level without a choice. An id that names no grouped
+ * model, such as a variant saved before grouping, is returned as it is.
+ */
+export function resolveAntigravityModel(model: string, effort: LlmReasoningEffort | undefined, variants: Map<string, Map<LlmReasoningEffort, string>>): string {
+ const byEffort = variants.get(model);
+ if (!byEffort) {
+ return model;
+ }
+ const levels = sortEfforts([ ...byEffort.keys() ]);
+ const wanted = LLM_REASONING_EFFORTS.indexOf(effort ?? defaultEffort(levels));
+ let chosen = levels[0];
+ for (const level of levels) {
+ if (Math.abs(LLM_REASONING_EFFORTS.indexOf(level) - wanted) <= Math.abs(LLM_REASONING_EFFORTS.indexOf(chosen) - wanted)) {
+ chosen = level;
+ }
+ }
+ return byEffort.get(chosen) ?? model;
}
/**
@@ -240,10 +281,70 @@ export function buildAntigravityEnv(
return result;
}
-/** `Gemini 3.8 Flash (High)` → family `Flash`, version `[3, 8]`; undefined for any other shape. */
-function parseGeminiModelName(name: string): { family: string; version: number[] } | undefined {
- const match = /^Gemini (\d+(?:\.\d+)*) (.+?) \([^)]+\)$/.exec(name);
- return match ? { family: match[2], version: match[1].split(".").map(Number) } : undefined;
+/**
+ * `Gemini 3.8 Flash (High)` → family `Flash`, version `[3, 8]`, model
+ * `Gemini 3.8 Flash`, effort `high`; the effort is absent from a name without
+ * one. Undefined for any other shape, or an effort label that is not a level.
+ */
+function parseGeminiModelName(name: string): { family: string; version: number[]; model: string; effort?: LlmReasoningEffort } | undefined {
+ const match = /^Gemini (\d+(?:\.\d+)*) (.+?)(?: \(([^)]+)\))?$/.exec(name);
+ if (!match) {
+ return undefined;
+ }
+ const effort = match[3] === undefined ? undefined : EFFORT_LABELS[match[3].toLowerCase()];
+ if (match[3] !== undefined && !effort) {
+ return undefined;
+ }
+ return { family: match[2], version: match[1].split(".").map(Number), model: `Gemini ${match[1]} ${match[2]}`, effort };
+}
+
+/** The effort levels Antigravity names in its models, by their label. */
+const EFFORT_LABELS: Record<string, LlmReasoningEffort | undefined> = { low: "low", medium: "medium", high: "high" };
+
+/**
+ * The catalog's models, variants of one model gathered into one entry. A model
+ * whose name carries no level is an entry with a single variant.
+ */
+function groupAntigravityCatalog(remote: AcpSessionModelState) {
+ const entries = new Map<string, { id: string; name: string; variants: Map<LlmReasoningEffort, string>; variantNames: Map<string, string> }>();
+ for (const model of remote.availableModels ?? []) {
+ if (!model.modelId || model.modelId === DEFAULT_MODEL_ID) {
+ continue;
+ }
+ const name = model.name ?? model.modelId;
+ const parsed = parseGeminiModelName(name);
+ const id = parsed?.effort ? parsed.model.toLowerCase().replace(/\s+/g, "-") : model.modelId;
+ let entry = entries.get(id);
+ if (!entry) {
+ entry = { id, name: parsed?.effort ? parsed.model : name, variants: new Map(), variantNames: new Map() };
+ entries.set(id, entry);
+ }
+ // A model without a level still needs a key; "high" is never read back for it.
+ entry.variants.set(parsed?.effort ?? "high", model.modelId);
+ entry.variantNames.set(model.modelId, name);
+ }
+ return [ ...entries.values() ];
+}
+
+/** Remember the variants and the title model of a catalog the server reported. */
+function recordCatalog(remote: AcpSessionModelState) {
+ const variants = new Map<string, Map<LlmReasoningEffort, string>>();
+ for (const entry of groupAntigravityCatalog(remote)) {
+ if (entry.variants.size > 1) {
+ variants.set(entry.id, entry.variants);
+ }
+ }
+ const titleModel = (remote.availableModels ?? []).find(m => /flash-low$/.test(m.modelId))?.modelId;
+ catalog = { variants, titleModel };
+}
+
+function sortEfforts(efforts: LlmReasoningEffort[]): LlmReasoningEffort[] {
+ return [ ...efforts ].sort((a, b) => LLM_REASONING_EFFORTS.indexOf(a) - LLM_REASONING_EFFORTS.indexOf(b));
+}
+
+/** High where the model has it, as the server itself defaults to a High variant; the strongest otherwise. */
+function defaultEffort(sortedEfforts: LlmReasoningEffort[]): LlmReasoningEffort {
+ return sortedEfforts.includes("high") ? "high" : sortedEfforts[sortedEfforts.length - 1];
}
function compareVersions(a: number[], b: number[]): number {
@@ -256,11 +357,6 @@ function compareVersions(a: number[], b: number[]): number {
return 0;
}
-/** The newest low-effort Flash model, which the catalog lists first among its peers. */
-function pickTitleModel(models: ModelInfo[]): string | undefined {
- return models.find(m => /flash-low$/.test(m.id))?.id;
-}
-
/** The server's home, `GEMINI_HOME`: its sign-in, sessions and tool descriptions. */
function agentHome(): string {
return path.resolve(dataDirs.TRILIUM_DATA_DIR, "antigravity-agent", "home");
diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.ts
index f0c6405fd0..325b0ec1ed 100644
--- a/packages/commons/src/lib/llm_api.ts
+++ b/packages/commons/src/lib/llm_api.ts
@@ -73,6 +73,14 @@ export interface LlmCitation {
citedText?: string;
}
+/**
+ * How much a model reasons before it answers, weakest first. The names are the
+ * AI SDK's `reasoning` call option, plus Anthropic's `max`.
+ */
+export const LLM_REASONING_EFFORTS = [ "none", "minimal", "low", "medium", "high", "xhigh", "max" ] as const;
+
+export type LlmReasoningEffort = (typeof LLM_REASONING_EFFORTS)[number];
+
/**
* Configuration for LLM chat requests.
*/
@@ -95,6 +103,12 @@ export interface LlmChatConfig {
enableExtendedThinking?: boolean;
/** Token budget for extended thinking (default: 10000) */
thinkingBudget?: number;
+ /**
+ * Reasoning effort for a model that lists {@link LlmModelInfo.reasoningEfforts}. Takes the
+ * place of {@link enableExtendedThinking} for such a model; absent means the model's
+ * {@link LlmModelInfo.defaultReasoningEffort}.
+ */
+ reasoningEffort?: LlmReasoningEffort;
/** Current note context (note ID the user is viewing) */
contextNoteId?: string;
/** The note ID of the chat note (used for auto-renaming on first message) */
@@ -137,6 +151,13 @@ export interface LlmModelInfo {
contextWindow?: number;
/** Whether usage is covered by a subscription plan rather than metered per token */
isSubscription?: boolean;
+ /**
+ * The reasoning efforts the model can be run at, weakest first. Absent for a model with no
+ * graded setting, which keeps the on/off extended thinking switch instead.
+ */
+ reasoningEfforts?: LlmReasoningEffort[];
+ /** The effort used when a chat has not chosen one. One of {@link reasoningEfforts}. */
+ defaultReasoningEffort?: LlmReasoningEffort;
}
/**
diff --git a/packages/trilium-core/src/services/llm/types.ts b/packages/trilium-core/src/services/llm/types.ts
index 308560e947..0514bec083 100644
--- a/packages/trilium-core/src/services/llm/types.ts
+++ b/packages/trilium-core/src/services/llm/types.ts
@@ -4,7 +4,7 @@
* should be imported from @triliumnext/commons.
*/
-import type { LlmChatConfig, LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
+import type { LlmChatConfig, LlmMessage, LlmReasoningEffort, LlmStreamChunk } from "@triliumnext/commons";
import type { streamText } from "ai";
/**
@@ -56,6 +56,10 @@ export interface ModelInfo {
recommended?: boolean;
/** Whether usage is covered by a subscription plan rather than metered per token */
isSubscription?: boolean;
+ /** The reasoning efforts the model can be run at, weakest first; see `LlmModelInfo`. */
+ reasoningEfforts?: LlmReasoningEffort[];
+ /** The effort used when a chat has not chosen one. */
+ defaultReasoningEffort?: LlmReasoningEffort;
}
export interface LlmProvider {