Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: union authoritative tool-use capability into the agent model picker hint (#4125)

[._.]/ Adam Eivy2076a8a95563
diff --git a/.changelog/next/fixed-issue-4125.md b/.changelog/next/fixed-issue-4125.md
new file mode 100644
index 0000000000..3a6a7a37cf
--- /dev/null
+++ b/.changelog/next/fixed-issue-4125.md
@@ -0,0 +1 @@
+- Agent model pickers now union each local backend's authoritative tool-use capability (Ollama /api/show) into the model-id heuristic, so a genuinely tool-capable model the id regex predates is no longer labelled "no known tool use"
diff --git a/client/src/components/ProviderModelSelector.jsx b/client/src/components/ProviderModelSelector.jsx
index be5a769b95..4d46d822b6 100644
--- a/client/src/components/ProviderModelSelector.jsx
+++ b/client/src/components/ProviderModelSelector.jsx
@@ -46,11 +46,14 @@
* marks each LOCAL (Ollama / LM Studio) model option with a tool-use indicator
* and warns below the select when the chosen local model can't call tools (it
* would narrate instead of acting). Off by default so non-agent pickers
- * (embeddings, vision, prose generation) stay unannotated. No-op for cloud/API
- * providers, whose ids don't encode their family.
+ * (embeddings, vision, prose generation) stay unannotated — it also gates the
+ * authoritative capability fetch (`useToolUseModelIds`), so an unannotated
+ * picker costs nothing. No-op for cloud/API providers, whose ids don't encode
+ * their family.
*/
import { useId } from 'react';
import { effectiveModelFor, effortLevelsForProvider, effortSurvivingModel, localToolUseHint, withToolUseOptionLabel } from '../utils/providers.js';
+import useToolUseModelIds from '../hooks/useToolUseModelIds.js';
import EffortSelect from './cos/EffortSelect.jsx';
const SELECT_CLASS =
@@ -101,7 +104,19 @@ export default function ProviderModelSelector({
// model (explicit selection, else the provider default) for the warning — and
// for the effort ladder, which is per-model on Antigravity.
const effectiveModel = effectiveModelFor(selectedProvider, selectedModel);
- const toolHint = highlightToolUse ? localToolUseHint(effectiveModel, selectedProvider) : null;
+ // Authoritative tool-use capability from the backends themselves, unioned into
+ // the id regex so a tool-capable family the regex predates isn't mislabelled.
+ // Gated on `highlightToolUse`, so the many non-agent pickers never pay for the
+ // capability scan; the fetch is module-shared, so a list page rendering one
+ // selector per row still issues a single request.
+ const { idsByProvider: toolUseIdsByProvider, loaded: toolUseLoaded } = useToolUseModelIds(highlightToolUse);
+ // Nothing is asserted until the scan settles (success OR failure). Annotating
+ // mid-fetch would show the exact false "⚠ no known tool use" this union exists
+ // to remove, only for it to vanish a beat later; a failed fetch settles too, so
+ // an unreachable backend degrades to the regex-only labels rather than muting
+ // the annotation forever.
+ const annotateToolUse = highlightToolUse && toolUseLoaded;
+ const toolHint = annotateToolUse ? localToolUseHint(effectiveModel, selectedProvider, toolUseIdsByProvider) : null;
const toolIncapable = toolHint?.toolCapable === false;
// Only offer enabled providers (treat a missing `enabled` as enabled). The
// currently-selected provider stays visible even if disabled, so a record
@@ -165,8 +180,8 @@ export default function ProviderModelSelector({
{availableModels.map(m => {
const opt = modelOption(m);
if (!opt) return null;
- const label = highlightToolUse
- ? withToolUseOptionLabel(opt.value, opt.label, selectedProvider)
+ const label = annotateToolUse
+ ? withToolUseOptionLabel(opt.value, opt.label, selectedProvider, toolUseIdsByProvider)
: opt.label;
return <option key={opt.value} value={opt.value}>{label}</option>;
})}
diff --git a/client/src/components/ProviderModelSelector.test.jsx b/client/src/components/ProviderModelSelector.test.jsx
index 3e31ccc8ff..0f7d1a6f8e 100644
--- a/client/src/components/ProviderModelSelector.test.jsx
+++ b/client/src/components/ProviderModelSelector.test.jsx
@@ -1,6 +1,13 @@
-import { describe, it, expect, vi } from 'vitest';
-import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+// The tool-use annotation unions the server's authoritative capability list into
+// the client id regex, so the picker fetches it whenever `highlightToolUse` is on.
+const getToolUseModels = vi.fn();
+vi.mock('../services/apiLocalLlm', () => ({ getToolUseModels: (...a) => getToolUseModels(...a) }));
+
import ProviderModelSelector from './ProviderModelSelector';
+import { __resetToolUseModelIdsCache } from '../hooks/useToolUseModelIds.js';
const PROVIDERS = [
{ id: 'p1', name: 'Provider One' },
@@ -119,8 +126,18 @@ describe('ProviderModelSelector', () => {
describe('highlightToolUse (agent pickers)', () => {
const OLLAMA = [{ id: 'ollama', name: 'Ollama' }];
+ const modelLabels = () =>
+ [...screen.getAllByRole('combobox')[1].querySelectorAll('option')].map((o) => o.textContent);
- it('marks local model options with a tool-use indicator', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ __resetToolUseModelIdsCache();
+ // Default: the capability scan finds nothing extra, so every assertion
+ // below is about the id regex unless the case says otherwise.
+ getToolUseModels.mockResolvedValue({ models: [] });
+ });
+
+ it('marks local model options with a tool-use indicator', async () => {
renderSelector({
providers: OLLAMA,
selectedProviderId: 'ollama',
@@ -128,11 +145,11 @@ describe('ProviderModelSelector', () => {
availableModels: ['qwen3.6:35b', 'gemma3:4b'],
highlightToolUse: true,
});
- const labels = [...screen.getAllByRole('combobox')[1].querySelectorAll('option')].map((o) => o.textContent);
- expect(labels).toEqual(['qwen3.6:35b · 🔧 tool use', 'gemma3:4b · ⚠ no known tool use']);
+ await waitFor(() =>
+ expect(modelLabels()).toEqual(['qwen3.6:35b · 🔧 tool use', 'gemma3:4b · ⚠ no known tool use']));
});
- it('warns when the selected LOCAL model cannot call tools', () => {
+ it('warns when the selected LOCAL model cannot call tools', async () => {
renderSelector({
providers: OLLAMA,
selectedProviderId: 'ollama',
@@ -140,10 +157,10 @@ describe('ProviderModelSelector', () => {
availableModels: ['qwen3.6:35b', 'gemma3:4b'],
highlightToolUse: true,
});
- expect(screen.getByText(/recognized tool-calling model/i)).toBeInTheDocument();
+ expect(await screen.findByText(/recognized tool-calling model/i)).toBeInTheDocument();
});
- it('warns on the provider default when the model selection is blank', () => {
+ it('warns on the provider default when the model selection is blank', async () => {
// "Default model" (blank) isn't a no-op — the resolver runs the provider's
// defaultModel, which here is a non-tool local model.
renderSelector({
@@ -155,10 +172,10 @@ describe('ProviderModelSelector', () => {
emptyModelOption: 'Default model',
highlightToolUse: true,
});
- expect(screen.getByText(/recognized tool-calling model/i)).toBeInTheDocument();
+ expect(await screen.findByText(/recognized tool-calling model/i)).toBeInTheDocument();
});
- it('does not warn when the selected local model is tool-capable', () => {
+ it('does not warn when the selected local model is tool-capable', async () => {
renderSelector({
providers: OLLAMA,
selectedProviderId: 'ollama',
@@ -166,10 +183,11 @@ describe('ProviderModelSelector', () => {
availableModels: ['qwen3.6:35b', 'gemma3:4b'],
highlightToolUse: true,
});
+ await waitFor(() => expect(getToolUseModels).toHaveBeenCalled());
expect(screen.queryByText(/recognized tool-calling model/i)).not.toBeInTheDocument();
});
- it('is a no-op for cloud providers (ids do not encode family)', () => {
+ it('is a no-op for cloud providers (ids do not encode family)', async () => {
renderSelector({
providers: [{ id: 'openai', name: 'OpenAI', endpoint: 'https://api.openai.com/v1' }],
selectedProviderId: 'openai',
@@ -177,8 +195,8 @@ describe('ProviderModelSelector', () => {
availableModels: ['gpt-4o', 'o1'],
highlightToolUse: true,
});
- const labels = [...screen.getAllByRole('combobox')[1].querySelectorAll('option')].map((o) => o.textContent);
- expect(labels).toEqual(['gpt-4o', 'o1']);
+ await waitFor(() => expect(getToolUseModels).toHaveBeenCalled());
+ expect(modelLabels()).toEqual(['gpt-4o', 'o1']);
expect(screen.queryByText(/recognized tool-calling model/i)).not.toBeInTheDocument();
});
@@ -189,9 +207,63 @@ describe('ProviderModelSelector', () => {
selectedModel: 'gemma3:4b',
availableModels: ['qwen3.6:35b', 'gemma3:4b'],
});
- const labels = [...screen.getAllByRole('combobox')[1].querySelectorAll('option')].map((o) => o.textContent);
- expect(labels).toEqual(['qwen3.6:35b', 'gemma3:4b']);
+ expect(modelLabels()).toEqual(['qwen3.6:35b', 'gemma3:4b']);
+ expect(screen.queryByText(/recognized tool-calling model/i)).not.toBeInTheDocument();
+ // An unannotated picker must not pay for the capability scan either.
+ expect(getToolUseModels).not.toHaveBeenCalled();
+ });
+
+ it('trusts the server over the id regex for a family the regex predates', async () => {
+ // `phi4-mini` reports Ollama's `tools` capability but matches no
+ // TOOL_USE_RE alternative — the mislabel this union exists to fix.
+ getToolUseModels.mockResolvedValue({
+ models: [{ providerId: 'ollama', id: 'phi4-mini:latest', toolUse: true }],
+ });
+ renderSelector({
+ providers: OLLAMA,
+ selectedProviderId: 'ollama',
+ selectedModel: 'phi4-mini:latest',
+ availableModels: ['phi4-mini:latest', 'gemma3:4b'],
+ highlightToolUse: true,
+ });
+ await waitFor(() =>
+ expect(modelLabels()).toEqual(['phi4-mini:latest · 🔧 tool use', 'gemma3:4b · ⚠ no known tool use']));
+ expect(screen.queryByText(/recognized tool-calling model/i)).not.toBeInTheDocument();
+ });
+
+ it('asserts nothing until the capability scan settles', async () => {
+ let resolveScan;
+ getToolUseModels.mockReturnValue(new Promise((r) => { resolveScan = r; }));
+ renderSelector({
+ providers: OLLAMA,
+ selectedProviderId: 'ollama',
+ selectedModel: 'phi4-mini:latest',
+ availableModels: ['phi4-mini:latest'],
+ highlightToolUse: true,
+ });
+ // Mid-scan the regex would say "⚠ no known tool use" — showing it here
+ // just to retract it a beat later is the bug, so hold the annotation.
+ expect(modelLabels()).toEqual(['phi4-mini:latest']);
expect(screen.queryByText(/recognized tool-calling model/i)).not.toBeInTheDocument();
+
+ resolveScan({ models: [{ providerId: 'ollama', id: 'phi4-mini:latest', toolUse: true }] });
+ await waitFor(() => expect(modelLabels()).toEqual(['phi4-mini:latest · 🔧 tool use']));
+ });
+
+ it('falls back to the id regex when the capability scan fails', async () => {
+ getToolUseModels.mockRejectedValue(new Error('ollama down'));
+ renderSelector({
+ providers: OLLAMA,
+ selectedProviderId: 'ollama',
+ selectedModel: 'gemma3:4b',
+ availableModels: ['qwen3.6:35b', 'gemma3:4b'],
+ highlightToolUse: true,
+ });
+ // A failed scan still settles, so the annotation appears — regex-only is
+ // the best answer available, not a reason to go silent forever.
+ await waitFor(() =>
+ expect(modelLabels()).toEqual(['qwen3.6:35b · 🔧 tool use', 'gemma3:4b · ⚠ no known tool use']));
+ expect(screen.getByText(/recognized tool-calling model/i)).toBeInTheDocument();
});
});
diff --git a/client/src/components/apps/SlashDoRunDrawer.test.jsx b/client/src/components/apps/SlashDoRunDrawer.test.jsx
index c157d3ecb1..2dfbc27bf8 100644
--- a/client/src/components/apps/SlashDoRunDrawer.test.jsx
+++ b/client/src/components/apps/SlashDoRunDrawer.test.jsx
@@ -14,6 +14,14 @@ const api = vi.hoisted(() => ({
vi.mock('../../services/api', () => api);
+// The drawer's `highlightToolUse` picker fetches the backends' authoritative
+// tool-use capabilities from apiLocalLlm directly (not through services/api),
+// so stub it here or the suite makes a real network call. Parked unresolved —
+// the annotation itself is covered in ProviderModelSelector.test.jsx.
+vi.mock('../../services/apiLocalLlm', () => ({
+ getToolUseModels: vi.fn(() => new Promise(() => {})),
+}));
+
const renderDrawer = (props = {}) => render(
<SlashDoRunDrawer
open
diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
index 60959bd19b..92cb03cc59 100644
--- a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
@@ -1,5 +1,16 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
+
+// The card's pins render a `highlightToolUse` ProviderModelSelector, which
+// fetches the backends' authoritative tool-use capabilities. Park that scan
+// unresolved: this suite is about the provider/model/effort pins, not the
+// tool-use annotation (covered in ProviderModelSelector.test.jsx), and a scan
+// that settles mid-test would land a state update outside act() in the
+// synchronous cases below.
+vi.mock('../../../../services/apiLocalLlm', () => ({
+ getToolUseModels: vi.fn(() => new Promise(() => {})),
+}));
+
import AppTaskCard from './AppTaskCard';
// `claude-code-*` ids carry the claude effort ladder (see effortLevelsForProvider).
diff --git a/client/src/components/creative-director/CreativeDirectorModelsDrawer.jsx b/client/src/components/creative-director/CreativeDirectorModelsDrawer.jsx
index 808f387608..f596d58fc5 100644
--- a/client/src/components/creative-director/CreativeDirectorModelsDrawer.jsx
+++ b/client/src/components/creative-director/CreativeDirectorModelsDrawer.jsx
@@ -6,6 +6,7 @@ import toast from '../ui/Toast';
import { getAiAssignments, updateAiAssignment } from '../../services/api';
import { updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';
import useVisionModelIds from '../../hooks/useVisionModelIds.js';
+import useToolUseModelIds from '../../hooks/useToolUseModelIds.js';
import {
providerDisplayName,
assignmentProviderOptions,
@@ -82,6 +83,13 @@ export default function CreativeDirectorModelsDrawer({ open, onClose, project, o
// normal first render, and asserting "none found" there would flash the exact
// empty-picker bug this drawer was fixed for.
const { idsByProvider: visionIdsByProvider, loaded: visionLoaded } = useVisionModelIds(open);
+ // Same shape for the AGENT stages (treatment/plan): the authoritative
+ // tool-use capability each backend reports, unioned into the client's id regex
+ // so a tool-capable family the regex predates isn't warned about. `null` until
+ // fetched, which the union degrades to regex-only for; `toolUseLoaded` gates
+ // the annotation so the ⚠ warning isn't asserted during the scan and then
+ // retracted. Gated on `open` — this drawer stays mounted on a closed page.
+ const { idsByProvider: toolUseIdsByProvider, loaded: toolUseLoaded } = useToolUseModelIds(open);
const seed = useCallback((next) => { setDrafts(next); setBaseline(next); }, []);
@@ -240,7 +248,10 @@ export default function CreativeDirectorModelsDrawer({ open, onClose, project, o
// provider whose default is a non-tool local model wedges the stage
// just the same.
const effectiveModel = draft.model || selectedProvider?.defaultModel || '';
- const toolHint = stage.needsTools ? localToolUseHint(effectiveModel, selectedProvider) : null;
+ const annotateToolUse = stage.needsTools && toolUseLoaded;
+ const toolHint = annotateToolUse
+ ? localToolUseHint(effectiveModel, selectedProvider, toolUseIdsByProvider)
+ : null;
const toolIncapable = pinned && toolHint?.toolCapable === false;
// Both hints below are about the LOCAL capability scan, so they only
// apply when the pinned provider is an Ollama / LM Studio backend. A
@@ -321,7 +332,9 @@ export default function CreativeDirectorModelsDrawer({ open, onClose, project, o
<option value="">Provider default / auto</option>
{modelOptions.map((m) => (
<option key={m} value={m}>
- {stage.needsTools ? withToolUseOptionLabel(m, m, selectedProvider) : m}
+ {annotateToolUse
+ ? withToolUseOptionLabel(m, m, selectedProvider, toolUseIdsByProvider)
+ : m}
</option>
))}
</select>
diff --git a/client/src/components/creative-director/CreativeDirectorModelsDrawer.test.jsx b/client/src/components/creative-director/CreativeDirectorModelsDrawer.test.jsx
index 8d518893e1..5a3e4b99d5 100644
--- a/client/src/components/creative-director/CreativeDirectorModelsDrawer.test.jsx
+++ b/client/src/components/creative-director/CreativeDirectorModelsDrawer.test.jsx
@@ -4,13 +4,14 @@ import { MemoryRouter } from 'react-router';
vi.mock('../../services/api', () => ({ getAiAssignments: vi.fn(), updateAiAssignment: vi.fn() }));
vi.mock('../../services/apiCreativeDirector.js', () => ({ updateCreativeDirectorProject: vi.fn() }));
-vi.mock('../../services/apiLocalLlm', () => ({ getVisionModels: vi.fn() }));
+vi.mock('../../services/apiLocalLlm', () => ({ getVisionModels: vi.fn(), getToolUseModels: vi.fn() }));
vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));
import CreativeDirectorModelsDrawer from './CreativeDirectorModelsDrawer.jsx';
import { getAiAssignments, updateAiAssignment } from '../../services/api';
import { updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';
-import { getVisionModels } from '../../services/apiLocalLlm';
+import { getVisionModels, getToolUseModels } from '../../services/apiLocalLlm';
+import { __resetToolUseModelIdsCache } from '../../hooks/useToolUseModelIds.js';
const ASSIGNMENTS = {
providers: [
@@ -50,6 +51,10 @@ beforeEach(() => {
// Default: the local backends report no vision models, so the id regex alone
// decides — the pre-`useVisionModelIds` behavior.
getVisionModels.mockResolvedValue({ models: [] });
+ // Same default for the tool-use capability scan: nothing authoritative, so the
+ // id regex alone decides the agent stages' annotation.
+ __resetToolUseModelIdsCache();
+ getToolUseModels.mockResolvedValue({ models: [] });
});
describe('CreativeDirectorModelsDrawer', () => {
@@ -81,6 +86,27 @@ describe('CreativeDirectorModelsDrawer', () => {
expect(screen.getByText(/recognized tool-calling model/i)).toBeInTheDocument();
});
+ it('clears the plan-stage warning for a model the server reports as tool-capable', async () => {
+ // `gemma2:9b` matches no TOOL_USE_RE alternative, but if Ollama's /api/show
+ // says it has `tools`, the authoritative answer wins over the stale regex —
+ // otherwise this drawer contradicts the Local LLMs tab's "Agents" badge.
+ getToolUseModels.mockResolvedValue({
+ models: [{ providerId: 'ollama', id: 'gemma2:9b', toolUse: true }],
+ });
+ renderDrawer({ id: 'cd-1', name: 'Demo', modelOverrides: { plan: { providerId: 'ollama', model: 'gemma2:9b' } } });
+ await waitFor(() => expect(getToolUseModels).toHaveBeenCalled());
+ await waitFor(() => expect(screen.getByLabelText('Production plan model')).toBeTruthy());
+ expect(screen.queryByText(/recognized tool-calling model/i)).not.toBeInTheDocument();
+ });
+
+ it('still warns on the plan stage when the capability scan fails', async () => {
+ // A failed scan must degrade to the id regex, not go silent — going silent
+ // would hide the wedge this warning exists to prevent.
+ getToolUseModels.mockRejectedValue(new Error('ollama down'));
+ renderDrawer({ id: 'cd-1', name: 'Demo', modelOverrides: { plan: { providerId: 'ollama', model: 'gemma2:9b' } } });
+ await waitFor(() => expect(screen.getByText(/recognized tool-calling model/i)).toBeInTheDocument());
+ });
+
it('never shows a tool-use warning on the vision (evaluation) stage', async () => {
// The evaluation stage is a direct vision call, not an agent — a non-tool
// local model there is expected and must NOT be flagged as tool-incapable.
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 742c9d9a16..f51131730d 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -167,6 +167,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useReviewerModelOptions` | Selectable model ids per model-taking reviewer for `ReviewerPicker`'s Model column — local-LLM ids from `/api/local-llm/status`, codex/claude/antigravity tiers from `/api/providers` (claude's list also spans installed Ollama ids for an Ollama-backed CLI; agy's collapses to base ids since the row has its own Effort cell). Returns `{ optionsByReviewer, freeText, unavailable, loaded, reviewers }`. | Every surface that renders `ReviewerPicker` (Code Review Defaults, TaskAddForm, ScheduleTab, SlashDoRunDrawer) — the picker never fetches; pass this as its `modelOptions`. |
| `useLocalModels` | Live installed Ollama/LM Studio model ids per backend + the server's editorial recommendation. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`). Fold in via `mergeModelLists` + `localBackendForProvider`. |
| `useVisionModelIds` | `{ idsByProvider, loaded }` — vision-capable model ids the server reports (Ollama `/api/show` + LM Studio `type:'vlm'`), keyed by the provider id that serves them (`{ ollama: Set, lmstudio: Set }`), `null` until fetched; `loaded` flips once the fetch settles. Drops `backend:'cli'` rows (a blanket per-provider claim, not a per-model fact) and never vouches for a provider the server didn't enumerate. | Any VISION model picker — pass `idsByProvider` to `visionLocalModelFilter` / `assignmentModelOptions` so a new multimodal family (`gemma4`) isn't hidden by the stale client id regex, and so an installed VLM shows even when the provider's stored `models` snapshot is stale; gate any "none installed" messaging on `loaded` and on the provider being a local backend. |
+| `useToolUseModelIds` | `{ idsByProvider, loaded }` — TOOL-USE (function-calling) capable model ids the server reports (Ollama `/api/show` `tools` capability + LM Studio catalog capabilities) via `/api/local-llm/tool-use-models`, keyed by the provider id that serves them (`{ ollama: Set, lmstudio: Set }`), `null` until fetched; `loaded` flips once the fetch settles. One module-shared fetch across every mounted caller, retried on a later mount if it failed. | Any AGENT model picker — pass `idsByProvider` to `localToolUseHint` / `withToolUseOptionLabel` so a tool-capable family the client id regex predates (`phi4-mini`) isn't mislabelled "⚠ no known tool use", and gate the annotation on `loaded` so the warning isn't asserted mid-fetch. |
| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
| `useThreejsModelFamilies` | Three.js subject-family checklist options served by `/api/threejs-models/families`; `[]` when the fetch fails, plus the exported `GENERAL_FAMILY_ID` default. | Any surface picking a subject family — the taxonomy is served, never mirrored client-side, so the picker and the generation prompt cannot drift. Hide the picker on an empty list rather than rendering an empty select. |
| `useSingToScore` | Capture a sung melody from the mic and transcribe it into lead-sheet notation. `start()` opens the mic, counts in on the shared metronome, then accumulates a pitch track relative to beat 1; `stop()` runs the `transcribePitchTrack` pipeline (segment → quantize at the song tempo → spell for the key) and returns the lead-sheet body. Exposes `{ phase, beat, result, error, start, stop, reset }`; tears down mic/analyser/tracker/metronome on stop and unmount. | The Song editor's Sing-to-score panel. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 095ccec7c2..51e21981c2 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -61,6 +61,8 @@ export { default as useAgyModels } from './useAgyModels.js';
export * from './useAgyModels.js';
export { default as useLocalModels } from './useLocalModels.js';
export { default as useVisionModelIds } from './useVisionModelIds.js';
+export { default as useToolUseModelIds } from './useToolUseModelIds.js';
+export * from './useToolUseModelIds.js';
export { default as usePreviewRoute } from './usePreviewRoute.js';
export { default as useProviderModels } from './useProviderModels.js';
export { default as useReviewerModelOptions } from './useReviewerModelOptions.js';
diff --git a/client/src/hooks/useToolUseModelIds.js b/client/src/hooks/useToolUseModelIds.js
new file mode 100644
index 0000000000..56e231b10d
--- /dev/null
+++ b/client/src/hooks/useToolUseModelIds.js
@@ -0,0 +1,120 @@
+import { useEffect, useState } from 'react';
+import { getToolUseModels } from '../services/apiLocalLlm';
+
+/**
+ * The provider ids the server tags its local rows with (`PROVIDER_ID[backend]`
+ * in server/services/localLlm.js). Seeded into the map so a backend that reports
+ * no tool-capable model is a definite "none installed" rather than an absent key.
+ * A CUSTOM provider pointed at a different Ollama/LM Studio host is deliberately
+ * NOT here: the server never enumerated that host, so it stays regex-only.
+ */
+const LOCAL_PROVIDER_IDS = ['ollama', 'lmstudio'];
+
+/**
+ * Module-level fetch cache. `null` = never fetched (or the last attempt failed
+ * and was cleared for retry); a Promise once a fetch is in flight or has
+ * resolved. Agent pickers are rendered one-per-row on list pages (a schedule
+ * card each), and the endpoint asks Ollama for every installed model's
+ * capabilities — so N mounted selectors must share ONE capability scan rather
+ * than firing N of them.
+ *
+ * Deliberately a promise-of-result, not a result: the second mount during the
+ * first mount's in-flight window has to join that request, not start another.
+ */
+let inFlight = null;
+
+/**
+ * Resolve to `idsByProvider` (a map, possibly with empty Sets) or `null` when
+ * the fetch failed. A failure clears the cache so a later mount can retry — a
+ * transient backend hiccup must not pin every agent picker to regex-only for
+ * the rest of the session.
+ */
+function fetchToolUseIds() {
+ inFlight ||= getToolUseModels({ silent: true })
+ .then((res) => {
+ // Key by the providerId the server itself reports for each row, so the map
+ // only ever vouches for the provider the server actually enumerated. Seed
+ // a key per enumerated local provider even when it reports nothing, so a
+ // present-but-empty backend reads as "none installed" rather than
+ // "unknown" — the null-vs-empty sentinel rule.
+ const idsByProvider = {};
+ for (const m of res?.models || []) {
+ if (!m?.providerId) continue;
+ (idsByProvider[m.providerId] ||= new Set());
+ if (m.id) idsByProvider[m.providerId].add(m.id);
+ }
+ for (const providerId of LOCAL_PROVIDER_IDS) idsByProvider[providerId] ||= new Set();
+ return idsByProvider;
+ })
+ .catch(() => { inFlight = null; return null; });
+ return inFlight;
+}
+
+/** Test seam — drop the shared cache so each case starts from "never fetched". */
+export function __resetToolUseModelIdsCache() {
+ inFlight = null;
+}
+
+/**
+ * The model ids the SERVER reports as TOOL-USE (function-calling) capable, keyed
+ * BY THE PROVIDER ID that serves them (`{ ollama: Set, lmstudio: Set }`),
+ * fetched once per page load and shared across every caller.
+ *
+ * The client's `isToolUseModel` regex is a positive allowlist of families with
+ * dependable function calling, so it goes stale the moment a new one ships: a
+ * genuinely tool-capable local model the regex doesn't know (`phi4-mini`, a
+ * newer function-calling Gemma build) rendered as "⚠ no known tool use", while
+ * the Local LLMs tab's "Agents" badge — reading the very same authoritative
+ * capabilities — disagreed. The server has the real answer (Ollama's `/api/show`
+ * `tools` capability; LM Studio's catalog capabilities), so agent pickers union
+ * this map in via `localToolUseHint` / `withToolUseOptionLabel`.
+ *
+ * Returns `{ idsByProvider, loaded }`. Callers UNION `idsByProvider` with the
+ * regex, so it only ever ADDS models the regex didn't recognize — a `null`/empty
+ * map degrades to regex-only rather than blanking the annotation. Widening is
+ * the safe direction here in both senses: the map can't speak for a provider the
+ * server never enumerated, and the regex can't speak for a family it predates,
+ * so neither vetoes the other.
+ *
+ * Keyed by the ENUMERATED PROVIDER, never flattened and never keyed by backend
+ * alone — a bare id is not a capability. A CUSTOM provider (or an Ollama-BACKED
+ * CLI wrapper) pointed at a *different* host resolves to the same backend but was
+ * never enumerated, so a local model's id must not vouch for a remote model that
+ * merely shares its name. Those providers stay on the regex-only path, which is
+ * the conservative answer: a false "🔧 tool use" sends an agent to a model that
+ * narrates instead of acting — the incident this annotation exists to prevent.
+ *
+ * `loaded` flips true once the fetch SETTLES (success or failure) and exists so a
+ * caller can tell "still fetching" from "fetched, none capable". The endpoint
+ * asks Ollama for each installed model's capabilities, so the pending window is
+ * real, and asserting "⚠ no known tool use" inside it is the very bug this hook
+ * fixes — only to have it vanish a beat later. `idsByProvider` alone can't carry
+ * that distinction: it stays `null` on failure too.
+ *
+ * @param {boolean} [enabled] gate the fetch — pass a picker's `highlightToolUse`
+ * or a drawer's `open` so a page that merely *contains* a non-agent picker
+ * doesn't pay for the capability scan. Fetches once and keeps the result if
+ * `enabled` later goes false.
+ * @returns {{idsByProvider: Record<string, Set<string>>|null, loaded: boolean}}
+ */
+export default function useToolUseModelIds(enabled = true) {
+ const [state, setState] = useState({ idsByProvider: null, loaded: false });
+
+ useEffect(() => {
+ if (!enabled || state.loaded) return undefined;
+ let canceled = false;
+ // Secondary control — a failed fetch falls back to the regex rather than
+ // toasting over the host page. It still marks `loaded`, so an unreachable
+ // backend can't suppress the annotation forever; regex-only is then the best
+ // answer available.
+ fetchToolUseIds().then((idsByProvider) => {
+ if (!canceled) setState({ idsByProvider, loaded: true });
+ });
+ // A cancel (drawer closed mid-flight) leaves `loaded` false, so reopening
+ // re-reads rather than rendering against a result that never arrived. The
+ // shared cache means that re-read is free when the first fetch succeeded.
+ return () => { canceled = true; };
+ }, [enabled, state.loaded]);
+
+ return state;
+}
diff --git a/client/src/hooks/useToolUseModelIds.test.jsx b/client/src/hooks/useToolUseModelIds.test.jsx
new file mode 100644
index 0000000000..aa122dab08
--- /dev/null
+++ b/client/src/hooks/useToolUseModelIds.test.jsx
@@ -0,0 +1,110 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, waitFor } from '@testing-library/react';
+
+const getToolUseModels = vi.fn();
+vi.mock('../services/apiLocalLlm', () => ({ getToolUseModels: (...a) => getToolUseModels(...a) }));
+
+import useToolUseModelIds, { __resetToolUseModelIdsCache } from './useToolUseModelIds.js';
+
+describe('useToolUseModelIds', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ __resetToolUseModelIdsCache();
+ });
+
+ it('keys the server-reported ids by the provider that serves them', async () => {
+ getToolUseModels.mockResolvedValue({
+ models: [
+ { providerId: 'ollama', backend: 'ollama', id: 'phi4-mini:latest', name: 'phi4-mini:latest', toolUse: true },
+ { providerId: 'ollama', backend: 'ollama', id: 'qwen3.6:35b', name: 'qwen3.6:35b', toolUse: true },
+ { providerId: 'lmstudio', backend: 'lmstudio', id: 'mistral-7b', name: 'mistral-7b', toolUse: true },
+ ],
+ });
+ const { result } = renderHook(() => useToolUseModelIds());
+ // Not fetched yet — `null`, and `loaded` false so a caller knows the
+ // difference between "still scanning" and "scanned, none capable".
+ expect(result.current).toEqual({ idsByProvider: null, loaded: false });
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ expect(result.current.idsByProvider.ollama).toEqual(new Set(['phi4-mini:latest', 'qwen3.6:35b']));
+ expect(result.current.idsByProvider.lmstudio).toEqual(new Set(['mistral-7b']));
+ });
+
+ it('distinguishes fetched-and-empty from never-fetched', async () => {
+ // A backend with zero tool-capable models must come back as a present-but-
+ // EMPTY set (a real answer the caller can union against), not an absent key
+ // and not `null` — the sentinel rule that keeps "none installed" from
+ // reading the same as "we never asked".
+ getToolUseModels.mockResolvedValue({ models: [] });
+ const { result } = renderHook(() => useToolUseModelIds());
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ expect(result.current.idsByProvider).toEqual({ ollama: new Set(), lmstudio: new Set() });
+ });
+
+ it('reports a failed fetch as null-but-loaded so callers degrade to the id regex', async () => {
+ getToolUseModels.mockRejectedValue(new Error('ollama down'));
+ const { result } = renderHook(() => useToolUseModelIds());
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ // `null`, NOT an empty map: a failed scan must never read as "nothing here
+ // is tool-capable" — that would assert the warning this hook exists to lift.
+ expect(result.current.idsByProvider).toBeNull();
+ });
+
+ it('does not fetch while disabled, and fetches once enabled', async () => {
+ getToolUseModels.mockResolvedValue({ models: [] });
+ const { result, rerender } = renderHook(({ enabled }) => useToolUseModelIds(enabled), {
+ initialProps: { enabled: false },
+ });
+ expect(getToolUseModels).not.toHaveBeenCalled();
+ expect(result.current.loaded).toBe(false);
+ rerender({ enabled: true });
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ expect(getToolUseModels).toHaveBeenCalledTimes(1);
+ });
+
+ it('shares ONE request across concurrently mounted callers', async () => {
+ // Agent pickers render one per schedule card, and the endpoint asks Ollama
+ // for every installed model's capabilities — N selectors must not mean N
+ // capability scans.
+ getToolUseModels.mockResolvedValue({
+ models: [{ providerId: 'ollama', id: 'phi4-mini:latest', toolUse: true }],
+ });
+ const a = renderHook(() => useToolUseModelIds());
+ const b = renderHook(() => useToolUseModelIds());
+ await waitFor(() => expect(a.result.current.loaded).toBe(true));
+ await waitFor(() => expect(b.result.current.loaded).toBe(true));
+ expect(getToolUseModels).toHaveBeenCalledTimes(1);
+ expect(b.result.current.idsByProvider.ollama).toEqual(new Set(['phi4-mini:latest']));
+ });
+
+ it('retries on a later mount after a failure instead of poisoning the session', async () => {
+ getToolUseModels.mockRejectedValueOnce(new Error('ollama down'));
+ const first = renderHook(() => useToolUseModelIds());
+ await waitFor(() => expect(first.result.current.loaded).toBe(true));
+ expect(first.result.current.idsByProvider).toBeNull();
+
+ getToolUseModels.mockResolvedValue({
+ models: [{ providerId: 'ollama', id: 'phi4-mini:latest', toolUse: true }],
+ });
+ const second = renderHook(() => useToolUseModelIds());
+ await waitFor(() => expect(second.result.current.idsByProvider).not.toBeNull());
+ expect(second.result.current.idsByProvider.ollama).toEqual(new Set(['phi4-mini:latest']));
+ expect(getToolUseModels).toHaveBeenCalledTimes(2);
+ });
+
+ it('ignores rows the server did not attribute to a provider', async () => {
+ // A bare id is not a capability — an unattributed row can't be allowed to
+ // vouch for whichever provider happens to list that id.
+ getToolUseModels.mockResolvedValue({
+ models: [
+ { id: 'orphan-model', toolUse: true },
+ { providerId: 'ollama', id: 'phi4-mini:latest', toolUse: true },
+ ],
+ });
+ const { result } = renderHook(() => useToolUseModelIds());
+ await waitFor(() => expect(result.current.loaded).toBe(true));
+ expect(result.current.idsByProvider).toEqual({
+ ollama: new Set(['phi4-mini:latest']),
+ lmstudio: new Set(),
+ });
+ });
+});
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index dd156f77a1..0d3360866f 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -8,6 +8,12 @@ export const getLocalLlmStatus = (options) => request('/local-llm/status', optio
// provider id that serves it. Powers the LoRA caption-model picker.
export const getVisionModels = (options) => request('/local-llm/vision-models', options);
+// Tool-use (function-calling) capable installed models across both backends,
+// each tagged with the provider id that serves it. Authoritative where the
+// backend reports capabilities (Ollama `/api/show`); agent pickers union it with
+// the client-side id regex via `useToolUseModelIds`.
+export const getToolUseModels = (options) => request('/local-llm/tool-use-models', options);
+
// `variants: true` opts into per-quant RAM-aware enrichment (probes Hugging Face
// per HF-backed entry) — the recommended-models picker wants it. Callers that only
// need catalog metadata (e.g. the playground decorating installed models) omit it
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 7bc3dee6ae..4627b14db4 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -494,21 +494,41 @@ export const isToolUseModel = (id) =>
*
* Returns `null` for cloud / API providers: their model ids don't encode their
* family, so the name heuristic would mislabel them. LOCAL backends return
- * `{ toolCapable }` keyed on {@link isToolUseModel} — where "local" is BOTH a
- * direct Ollama / LM Studio backend ({@link localBackendForProvider}) AND an
- * Ollama-BACKED CLI/TUI wrapper ({@link isOllamaBackedProvider}): a renamed
- * `claude-ollama-tui` / OpenCode wrapper keeps `ollamaBacked: true` but may lose
- * the "ollama" name/endpoint/id that `localBackendForProvider` matches on, and
- * that wrapper is exactly the incident's provider class — so it must still be
- * flagged, not silently skipped.
+ * `{ toolCapable }` — where "local" is BOTH a direct Ollama / LM Studio backend
+ * ({@link localBackendForProvider}) AND an Ollama-BACKED CLI/TUI wrapper
+ * ({@link isOllamaBackedProvider}): a renamed `claude-ollama-tui` / OpenCode
+ * wrapper keeps `ollamaBacked: true` but may lose the "ollama"
+ * name/endpoint/id that `localBackendForProvider` matches on, and that wrapper
+ * is exactly the incident's provider class — so it must still be flagged, not
+ * silently skipped.
+ *
+ * `toolUseIdsByProvider` is the AUTHORITATIVE map the server reports from each
+ * backend's own capability metadata (Ollama `/api/show` `tools`) keyed by the
+ * PROVIDER ID the server says serves each model — see `useToolUseModelIds`. It
+ * is UNIONED with, never substituted for, {@link isToolUseModel}: the regex is a
+ * positive allowlist that goes stale every time a new function-calling family
+ * ships (`phi4-mini`, newer Gemma builds got "⚠ no known tool use" while the
+ * Local LLMs tab's "Agents" badge, reading these same capabilities, said
+ * otherwise), while the map can't speak for a provider the server never
+ * enumerated. Pass `null` (the default) when it hasn't loaded — that degrades to
+ * regex-only, the behavior this picker has always had.
+ *
+ * Keyed by the ENUMERATED PROVIDER, not flattened and not keyed by backend,
+ * because a bare id is not a capability: a CUSTOM provider (or an Ollama-backed
+ * CLI wrapper) pointed at a *different* Ollama/LM Studio host resolves to the
+ * same backend, but the server never enumerated that host — so a local model's
+ * id must not vouch for a remote model that merely shares its name. Such a
+ * provider stays regex-only, which is the conservative direction: a false
+ * "tool-capable" sends an agent to a model that narrates instead of acting.
* @param {string} id
* @param {object} [provider]
+ * @param {Record<string, Set<string>>|null} [toolUseIdsByProvider]
* @returns {{toolCapable:boolean}|null}
*/
-export const localToolUseHint = (id, provider) =>
+export const localToolUseHint = (id, provider, toolUseIdsByProvider = null) =>
(localBackendForProvider(provider) || isOllamaBackedProvider(provider))
&& typeof id === 'string' && id.length > 0
- ? { toolCapable: isToolUseModel(id) }
+ ? { toolCapable: toolUseIdsByProvider?.[provider?.id]?.has(id) === true || isToolUseModel(id) }
: null;
/**
@@ -523,14 +543,18 @@ export const localToolUseHint = (id, provider) =>
* "tool-capable", but a NON-match only means "not a recognized tool-caller" —
* NOT a proven negative (a newer tool-capable family whose id isn't in the regex
* yet would fall here). So the negative marker is worded as unverified, not a
- * false-certain "no tool use".
+ * false-certain "no tool use". Passing `toolUseIdsByProvider` (from
+ * `useToolUseModelIds`) shrinks that unverified band to the models the server
+ * couldn't speak for; see {@link localToolUseHint} for the union rule.
* @param {string} id - model id (drives the heuristic)
* @param {string} label - display label to annotate (often === id)
* @param {object} [provider] - the selected provider object
+ * @param {Record<string, Set<string>>|null} [toolUseIdsByProvider] - authoritative
+ * server-reported tool-capable ids, keyed by provider id; `null` = regex-only
* @returns {string}
*/
-export const withToolUseOptionLabel = (id, label, provider) => {
- const hint = localToolUseHint(id, provider);
+export const withToolUseOptionLabel = (id, label, provider, toolUseIdsByProvider = null) => {
+ const hint = localToolUseHint(id, provider, toolUseIdsByProvider);
if (!hint) return label;
return `${label}${hint.toolCapable ? ' · 🔧 tool use' : ' · ⚠ no known tool use'}`;
};
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index c53d8f8d6b..9b06ccdd2e 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -660,6 +660,57 @@ describe('localToolUseHint', () => {
it('returns null for a blank id', () => {
expect(localToolUseHint('', ollama)).toBeNull();
});
+
+ describe('authoritative capability union (useToolUseModelIds)', () => {
+ // The map is keyed by the PROVIDER ID the server enumerated, so the fixture
+ // provider needs one.
+ const ollamaProvider = { id: 'ollama', name: 'Ollama', endpoint: 'http://localhost:11434/v1' };
+
+ it('flags a tool-capable model the id regex does not recognize', () => {
+ // The bug: `phi4-mini` reports the `tools` capability from Ollama's
+ // /api/show, but no TOOL_USE_RE alternative matches it — so the picker
+ // said "⚠ no known tool use" while the Local LLMs tab's Agents badge,
+ // reading the same capabilities, disagreed.
+ expect(localToolUseHint('phi4-mini:latest', ollamaProvider)).toEqual({ toolCapable: false });
+ const ids = { ollama: new Set(['phi4-mini:latest']) };
+ expect(localToolUseHint('phi4-mini:latest', ollamaProvider, ids)).toEqual({ toolCapable: true });
+ expect(withToolUseOptionLabel('phi4-mini:latest', 'phi4-mini:latest', ollamaProvider, ids))
+ .toBe('phi4-mini:latest · 🔧 tool use');
+ });
+
+ it('keeps the regex verdict for a model the server did not list (union, not substitution)', () => {
+ // A fetched-and-legitimately-EMPTY set is not a veto: the server can only
+ // ADD to the regex, never subtract from it, so a regex hit still wins.
+ const ids = { ollama: new Set(), lmstudio: new Set() };
+ expect(localToolUseHint('qwen3.6:35b', ollamaProvider, ids)).toEqual({ toolCapable: true });
+ expect(localToolUseHint('gemma3:4b', ollamaProvider, ids)).toEqual({ toolCapable: false });
+ });
+
+ it('falls back to regex-only when the fetch never landed or failed (null map)', () => {
+ // `null` = not fetched / failed — distinct from a fetched empty map above.
+ // Both degrade to the regex, but only the empty map is a real answer.
+ expect(localToolUseHint('qwen3.6:35b', ollamaProvider, null)).toEqual({ toolCapable: true });
+ expect(localToolUseHint('phi4-mini:latest', ollamaProvider, null)).toEqual({ toolCapable: false });
+ expect(localToolUseHint('phi4-mini:latest', ollamaProvider, undefined)).toEqual({ toolCapable: false });
+ });
+
+ it('never lets one provider vouch for another (keyed by enumerated provider)', () => {
+ // A CUSTOM provider pointed at a DIFFERENT Ollama host resolves to the same
+ // backend but was never enumerated — a matching id there is a coincidence,
+ // and a false "tool-capable" wedges the agent. It stays regex-only.
+ const ids = { ollama: new Set(['phi4-mini:latest']) };
+ const remote = { id: 'ollama-remote', name: 'Remote Ollama', endpoint: 'http://192.0.2.10:11434/v1' };
+ expect(localToolUseHint('phi4-mini:latest', remote, ids)).toEqual({ toolCapable: false });
+ // Same for a renamed Ollama-backed wrapper with its own provider id.
+ const wrapper = { id: 'my-local-agent', name: 'My Local Agent', ollamaBacked: true };
+ expect(localToolUseHint('phi4-mini:latest', wrapper, ids)).toEqual({ toolCapable: false });
+ });
+
+ it('still returns null for cloud providers even with a map present', () => {
+ const cloud = { id: 'openai', name: 'OpenAI', endpoint: 'https://api.openai.com/v1' };
+ expect(localToolUseHint('gpt-4o', cloud, { openai: new Set(['gpt-4o']) })).toBeNull();
+ });
+ });
});
describe('withToolUseOptionLabel', () => {
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index e5a412996c..0a1545fdc3 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -28,7 +28,7 @@ import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import { isAppleSilicon } from '../lib/platform.js'
import { searchHuggingFaceModels, enrichCatalogWithVariants } from '../services/huggingFaceCatalog.js'
import {
- getStatus, listModels, listVisionModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer,
+ getStatus, listModels, listVisionModels, listToolUseModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer,
describeInstallProgress
} from '../services/localLlm.js'
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'
@@ -57,6 +57,19 @@ router.get('/vision-models', asyncHandler(async (_req, res) => {
res.json({ models: await listVisionModels() })
}))
+// GET /api/local-llm/tool-use-models — tool-use (function-calling) capable
+// installed models across both backends, tagged with the provider id that serves
+// them. Powers the agent model pickers' tool-use annotation.
+//
+// Kept separate from /vision-models rather than folded into it: that endpoint's
+// contract is "every row returned is vision-capable" (the LoRA caption picker
+// lists its rows verbatim), so returning tool-only rows there would need a
+// discriminator plus a filter in every existing consumer, and its CLI-provider
+// expansion has no tool-use analogue.
+router.get('/tool-use-models', asyncHandler(async (_req, res) => {
+ res.json({ models: await listToolUseModels() })
+}))
+
// GET /api/local-llm/catalog?backend=ollama&q=llama — curated install picker.
// HF-repo-backed entries are enriched with the same per-quant variant picker +
// RAM-aware default as the live Hugging Face search, so the recommended quant
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 79d56544ef..36e5b18cc2 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -3,7 +3,7 @@ import express from 'express';
import { request } from '../lib/testHelper.js';
import localLlmRoutes from './localLlm.js';
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js';
-import { listModels } from '../services/localLlm.js';
+import { listModels, listVisionModels, listToolUseModels } from '../services/localLlm.js';
import { enrichCatalogWithVariants } from '../services/huggingFaceCatalog.js';
import { getLoadedModels, unloadModel } from '../services/ollamaManager.js';
import { localLlmCompareSchema, localLlmTestSchema } from '../lib/validation.js';
@@ -17,6 +17,8 @@ errorEvents.on('error', () => {});
vi.mock('../services/localLlm.js', () => ({
getStatus: vi.fn(),
listModels: vi.fn(async () => []),
+ listVisionModels: vi.fn(async () => []),
+ listToolUseModels: vi.fn(async () => []),
installModel: vi.fn(),
deleteModel: vi.fn(),
switchBackend: vi.fn(),
@@ -309,3 +311,42 @@ describe('local LLM memory-management routes', () => {
expect(unloadModel).not.toHaveBeenCalled();
});
});
+
+describe('local LLM capability routes', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('GET /tool-use-models returns the service list under `models`', async () => {
+ listToolUseModels.mockResolvedValueOnce([
+ { providerId: 'ollama', backend: 'ollama', id: 'phi4-mini:latest', name: 'phi4-mini:latest', toolUse: true },
+ ]);
+
+ const res = await request(makeApp()).get('/api/local-llm/tool-use-models');
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({
+ models: [
+ { providerId: 'ollama', backend: 'ollama', id: 'phi4-mini:latest', name: 'phi4-mini:latest', toolUse: true },
+ ],
+ });
+ expect(listToolUseModels).toHaveBeenCalledTimes(1);
+ });
+
+ it('GET /tool-use-models is a distinct list from /vision-models', async () => {
+ // The two endpoints answer different questions; folding tool-use rows into
+ // /vision-models would break its "every row is vision-capable" contract,
+ // which the LoRA caption picker lists verbatim.
+ listVisionModels.mockResolvedValueOnce([
+ { providerId: 'ollama', backend: 'ollama', id: 'qwen2.5-vl:7b', name: 'qwen2.5-vl:7b', vision: true },
+ ]);
+ listToolUseModels.mockResolvedValueOnce([
+ { providerId: 'ollama', backend: 'ollama', id: 'phi4-mini:latest', name: 'phi4-mini:latest', toolUse: true },
+ ]);
+ const app = makeApp();
+
+ const vision = await request(app).get('/api/local-llm/vision-models');
+ const tools = await request(app).get('/api/local-llm/tool-use-models');
+
+ expect(vision.body.models.map((m) => m.id)).toEqual(['qwen2.5-vl:7b']);
+ expect(tools.body.models.map((m) => m.id)).toEqual(['phi4-mini:latest']);
+ });
+});
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index 22b3606a20..db20394734 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -782,6 +782,62 @@ export async function listVisionModels() {
]
}
+/**
+ * Tool-use (function-calling) capable installed models across both local
+ * backends, tagged with the aiToolkit provider id (`ollama` / `lmstudio`) that
+ * serves them. Each entry: `{ providerId, backend, id, name, toolUse: true }`.
+ *
+ * Powers the AGENT model pickers' tool-use annotation, whose client-side
+ * `isToolUseModel` id regex is a positive allowlist that goes stale every time a
+ * new function-calling family ships — so a genuinely tool-capable model whose id
+ * the regex doesn't know (`phi4-mini`, a newer function-calling Gemma build) got
+ * flagged "⚠ no known tool use" while the Local LLMs tab's "Agents" badge, which
+ * reads these same authoritative capabilities, said otherwise.
+ *
+ * Deliberately NOT a mirror of `listVisionModels`' CLI expansion: a CLI provider
+ * has no enumerable per-model capability, and its tool-calling comes from the CLI
+ * harness rather than the model, so there is nothing authoritative to report.
+ * Callers union this with the id regex, so an unlisted model still falls back to
+ * the regex rather than being asserted incapable.
+ */
+export async function listToolUseModels() {
+ // Cache-first for both backends — same rationale as listVisionModels: the
+ // model-list caches are busted on install/delete, so they stay accurate.
+ const [ollama, lmstudio] = await Promise.all([
+ listModels('ollama').catch(() => []),
+ listModels('lmstudio').catch(() => [])
+ ])
+ // Ollama's /api/tags carries no capability flags at all, so `normalizeModels`
+ // could only regex-guess. /api/show reports an authoritative `tools`
+ // capability (cached per model), which is what makes this endpoint worth more
+ // than the client's own regex — consult it for every model. Unlike the vision
+ // path there is no id short-circuit: an id-regex hit is exactly the case the
+ // client can already decide for itself, so skipping the round-trip would leave
+ // this list adding nothing beyond what the caller already knows.
+ const ollamaToolUse = await Promise.all(ollama.map(async (m) => {
+ const capabilities = await ollamaManager.getModelCapabilities(m.id).catch(() => [])
+ // `isToolUseModel` treats a NON-EMPTY capabilities array as authoritative in
+ // both directions; an empty one (daemon didn't report, or /api/show failed)
+ // falls back to the id regex.
+ return { ...m, toolUse: isToolUseModel({ id: m.id, capabilities }) }
+ }))
+ // LM Studio reports no tool-calling flag, so `lmStudioBadgeCapabilities`
+ // already resolved `tools` from the shared id heuristic — read that rather
+ // than re-deriving it, so this endpoint and the Local LLMs tab's badges can
+ // never disagree about the same model.
+ const lmStudioToolUse = lmstudio.map((m) => ({
+ ...m,
+ toolUse: (m.capabilities || []).includes('tools')
+ }))
+ const tag = (backend, models) => models
+ .filter((m) => m.toolUse)
+ .map((m) => ({ providerId: PROVIDER_ID[backend], backend, id: m.id, name: m.name || m.id, toolUse: true }))
+ return [
+ ...tag('ollama', ollamaToolUse),
+ ...tag('lmstudio', lmStudioToolUse),
+ ]
+}
+
/**
* Vision-capable CLI providers (codex / claude-code), expanded to one entry per
* configured model so the caption picker can offer e.g. "codex / gpt-5" or
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index 39ef0532aa..68634209c6 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -525,6 +525,85 @@ describe('localLlm', () => {
});
});
+ describe('listToolUseModels', () => {
+ it('reports a tool-capable Ollama model whose id the TOOL_USE_RE does not match', async () => {
+ mocks.ollama.getInstalledModels.mockResolvedValueOnce([
+ // The bug: /api/show says `tools`, but no id-regex alternative matches
+ // `phi4-mini` — so the agent picker warned "no known tool use".
+ { id: 'phi4-mini:latest', name: 'phi4-mini:latest', family: 'phi3' },
+ { id: 'gemma3:4b', name: 'gemma3:4b', family: 'gemma3' },
+ ]);
+ mocks.ollama.getModelCapabilities.mockImplementation(async (id) =>
+ id === 'phi4-mini:latest' ? ['completion', 'tools'] : ['completion', 'vision']);
+
+ const models = await svc.listToolUseModels();
+ expect(models).toEqual([
+ { providerId: 'ollama', backend: 'ollama', id: 'phi4-mini:latest', name: 'phi4-mini:latest', toolUse: true },
+ ]);
+ });
+
+ it('consults /api/show even for an id the regex already matches', async () => {
+ // Unlike the vision path there is no id short-circuit: an id-regex hit is
+ // exactly what the client can already decide for itself, so skipping the
+ // round-trip would leave this endpoint adding nothing.
+ mocks.ollama.getInstalledModels.mockResolvedValueOnce([
+ { id: 'qwen3.6:35b', name: 'qwen3.6:35b', family: 'qwen35moe' },
+ ]);
+ mocks.ollama.getModelCapabilities.mockResolvedValue(['completion', 'tools']);
+
+ const models = await svc.listToolUseModels();
+ expect(models.map((m) => m.id)).toEqual(['qwen3.6:35b']);
+ expect(mocks.ollama.getModelCapabilities).toHaveBeenCalledWith('qwen3.6:35b');
+ });
+
+ it('falls back to the id regex when /api/show reports no capabilities', async () => {
+ // Empty array = the daemon didn't answer / doesn't report — NOT an
+ // explicit "no tools". Regex-only is then the best answer available.
+ mocks.ollama.getInstalledModels.mockResolvedValueOnce([
+ { id: 'qwen3.6:35b', name: 'qwen3.6:35b', family: 'qwen35moe' },
+ { id: 'phi4-mini:latest', name: 'phi4-mini:latest', family: 'phi3' },
+ ]);
+ mocks.ollama.getModelCapabilities.mockResolvedValue([]);
+
+ const models = await svc.listToolUseModels();
+ expect(models.map((m) => m.id)).toEqual(['qwen3.6:35b']);
+ });
+
+ it('reads LM Studio tool capability off the normalized catalog badges', async () => {
+ // LM Studio reports no tool flag, so `lmStudioBadgeCapabilities` already
+ // resolved `tools` from the shared id heuristic — reading that keeps this
+ // endpoint and the Local LLMs tab's badges from ever disagreeing.
+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([
+ { id: 'mistral-7b-instruct', type: 'llm' },
+ { id: 'nomic-embed-text', type: 'embeddings' },
+ { id: 'some-unknown-model', type: 'llm' },
+ ]);
+
+ const models = await svc.listToolUseModels();
+ expect(models).toEqual([
+ { providerId: 'lmstudio', backend: 'lmstudio', id: 'mistral-7b-instruct', name: 'mistral-7b-instruct', toolUse: true },
+ ]);
+ });
+
+ it('never emits CLI-provider rows (no per-model capability to report)', async () => {
+ mocks.providers.getAllProviders.mockResolvedValueOnce({
+ providers: [
+ { id: 'claude-code', type: 'cli', command: 'claude', enabled: true, models: ['claude-opus-4-8'] },
+ ],
+ });
+ const models = await svc.listToolUseModels();
+ expect(models.some((m) => m.backend === 'cli')).toBe(false);
+ });
+
+ it('survives a backend being down — the other still reports', async () => {
+ mocks.ollama.getInstalledModels.mockRejectedValueOnce(new Error('ollama down'));
+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([{ id: 'mistral-7b-instruct', type: 'llm' }]);
+
+ const models = await svc.listToolUseModels();
+ expect(models.map((m) => m.id)).toEqual(['mistral-7b-instruct']);
+ });
+ });
+
describe('getLatestOllamaVersion', () => {
afterEach(() => vi.unstubAllGlobals());