Skip to content

Remove the Ollama-native inference path: drive Ollama through its OpenAI-compatible endpoint - #1806

Merged
malibio merged 5 commits into
mainfrom
worktree-issue-1793-ollama-openai-compat
Jul 29, 2026
Merged

malibio merged 5 commits into
mainfrom
worktree-issue-1793-ollama-openai-compat

Conversation

@malibio

@malibio malibio commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator

Closes #1793

malibio and others added 4 commits July 29, 2026 08:29
Drives Ollama through its OpenAI-compatible /v1 endpoint instead of its
bespoke native wire format, so one protocol implementation serves every
remotely-served model.

Verified against a live Ollama 0.32.1 before deleting anything:
- /v1/models returns the same catalog as the native /api/tags
- /v1/chat/completions tool calling works both streaming and non-streaming

New: openai_compat_discovery
The OpenAI-compat path had no listing surface at all, so a straight delete
would have cost Ollama users auto-discovery and left them hand-writing one
daemon.toml config per model. discover_models() queries GET {base_url}/models,
which every OpenAI-compatible server implements. A discovered model is
addressed as "openai-compat:<config_id>:<model>" — one endpoint config now
exposes N models rather than pinning exactly one.

/v1/models reports only id/created/owned_by, so discovered rows carry no
size, quantization or context window; those fields are left at their unknown
sentinels rather than guessed at.

Deleted: ollama_inference.rs, ollama_model_manager.rs, composite_model_manager.rs
(it existed only to route GGUF vs Ollama, so it collapses entirely rather than
being reworked), and tests/ollama_integration.rs.

Kept, renamed: ollama_ndjson.rs -> ndjson.rs. The surviving OpenAI-compat
engine depends on it for SSE line buffering, so deleting it as scoped would
have broken the engine we are keeping. It is a generic newline-delimited
buffer; only its name and docs were Ollama-specific.

ModelBackend::Ollama -> OpenAiCompat, with an explicit as_wire_str(). The
daemon stringified this enum via format!("{:?}").to_lowercase(), which would
have rendered the new variant as "openaicompat" and silently disagreed with
the hyphenated value the frontend matches on.

Also fixes the original defect this issue reported, in the engine that
survives: OpenAiCompatInferenceEngine built a bare reqwest::Client with no
timeout, so an endpoint that accepts the connection then stalls would hang
the turn forever. Adds connect and request timeouts.

Refs #1793

Co-Authored-By: Claude <[email protected]>
… RPC

list_models now merges GGUF catalog rows with every model discovered at a
configured OpenAI-compatible endpoint. Endpoints are queried concurrently via
a JoinSet — they are independent network calls and the selector awaits the
whole listing — and a dead endpoint contributes nothing rather than failing
the catalog, so one bad provider cannot blank out the others.

CompositeModelManager is gone, so the daemon holds a GgufModelManager
directly and the Ollama load branch collapses into the OpenAI-compat branch
above it. Adds parse_openai_compat_id() for the "<uuid>:<model>" form, which
splits on the FIRST colon after the prefix: a UUID never contains one, while
a model identifier routinely does ("mistral:7b"). A discovered model wins over
the config's pinned `model` field.

Removes the OllamaAvailable RPC end to end — proto, daemon handler, Tauri
command, and its invoke_handler registration. Whether a remote endpoint is
reachable is now answered by discovery returning rows for it.

Also fixes a live bug that predates this work: behaviors/mod.rs accepted only
native|ollama|openai|pty for an ai-chat node's provider, while the frontend
has been emitting "openai-compat" and persisting it verbatim — so those nodes
failed validation. The accepted set is now native|openai|openai-compat|pty.

Refs #1793

Co-Authored-By: Claude <[email protected]>
…ckend

The chat selector's OpenAI-compat options were rendered disabled with a
"(coming soon)" label, so the Ollama optgroup was the only working way to
pick a remotely-served model. Deleting the native path without finishing this
would have left no selectable remote model at all — so the selector now
renders discovered models as real, selectable options under "Remote
endpoints", replacing both the Ollama section and the stubbed config list.

Settings' dedicated Ollama panel (running/not-running state, install link,
its own refresh) becomes "Available remote models", listing what discovery
actually returned. It no longer duplicates the "Custom endpoints" section
directly below it, which is where endpoints are configured.

buildDefaultOptions() now emits one row per discovered model and falls back
to a bare config row only when that config contributed nothing — otherwise a
configured endpoint appeared twice in the default-model picker.

Frontend types follow the daemon: ModelFamily drops 'ollama' for
'openai-compat', AiChatProvider drops 'ollama', and the catalog row's backend
discriminator becomes 'gguf' | 'openai-compat'. ollamaAvailable() and the
dev-proxy's /api/agent/ollama-available route are removed.

Fixes a latent mismatch in ai-chat-node-viewer: its openai-compat branch
prefixed the stored model, assuming a bare config UUID. Selections are now
fully-qualified daemon ids, so the value passes through unchanged.

Frontend suite: 170 files / 4106 tests, matching baseline exactly.

Refs #1793

Co-Authored-By: Claude <[email protected]>
The smoke test drives the real production path — discover_models() then a
streamed tool-calling turn through OpenAiCompatInferenceEngine — against a
locally running server. It guards the claim this whole change rests on: that
Ollama's /v1 serves both discovery and tool calls, so the native client was
redundant rather than merely similar. #[ignore]d, since it needs a real
server; run with --ignored.

Verified against Ollama 0.32.1: discovered 3 models, mistral:7b requested
get_weather (71 prompt / 55 completion tokens).

Remaining "Ollama" mentions are deliberate prose explaining that it is now
reached through the OpenAI-compatible endpoint. The ones removed here had
gone stale — "Ollama-managed models", "the Ollama engine", and three
references to a "local Ollama agent" that described the local agent generally
and were inaccurate even before this change.

Refs #1793

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review — PR #1806

Review Type: Initial Review
Scope reviewed: 075ae606..8c426601 only (4 commits). #1801 / #1803 changes that ride along in origin/main...HEAD (collection_service.rs, node_service/embedding.rs, dev-proxy reconnect backoff) were excluded. dev-proxy.ts was reviewed for the /api/agent/ollama-available route removal only.


Summary

A genuinely excellent deletion: -3477 / +705. Three native modules, a 1843-line integration test, and an entire CompositeModelManager indirection layer collapse into one protocol path. The architectural claim — "OpenAI-compat is a superset of what we used Ollama's native API for" — is not merely asserted; live_openai_compat_smoke.rs mechanically proves the load-bearing part (discovery + tool-calling), which is exactly the right way to justify deleting a redundant client. Comments consistently explain why rather than what, and several encode a real trap for the next reader (the first-colon split, as_wire_str vs Debug, the "newline resets overflow count" invariant).

I verified the acceptance criteria independently rather than trusting the summary. grep -rniI ollama packages/ returns 28 hits, all intentional prose — module docs describing which servers speak the protocol, and test fixtures naming the server that produced a verbatim response body. Zero orphan identifiers: ollamaAvailable / OllamaAvailable / ollama_available / ollama-available return nothing across Rust, TS, proto, and dev-proxy. ModelFamily::Ollama and ModelBackend::Ollama are gone from both Rust and the TS union with no orphan match arms.

Findings are one 🟡 correctness bug (a real round-trip break in the default-model selector), plus one 🟡 latent scaling concern and a few 🟢s. Nothing blocking.


Requirements Check

# Criterion Status
1 /v1 verified live incl. tool-calling turn ✅ packages/agent/tests/live_openai_compat_smoke.rs — #[ignore]d, asserts get_weather called exactly once
2 Ollama discovery via OpenAI-compat path ✅ Better than the criterion's fallback — auto-discovery, not a documented manual step
3 Three native modules + integration test deleted ✅ ollama_inference.rs, ollama_model_manager.rs, composite_model_manager.rs, ollama_integration.rs — plus the [[test]] stanza in Cargo.toml
4 ModelFamily::Ollama removed, Rust + TS, no orphans ✅ Verified both unions; recommended_model_id_for arm correctly collapsed
5 composite_model_manager.rs restructured, no vestigial field ✅ Deleted outright; LocalAgentServiceInner.model_manager is now Arc<GgufModelManager> directly
6 No --no-verify; gate passes ✅ Per author; consistent with test-file updates in the diff
7 grep -ri ollama → only intentional ✅ Independently confirmed — 28 hits, all prose/fixtures
8 No-timeout defect fixed in OpenAiCompatInferenceEngine ✅ See 🟢 note below

📝 Scope deviations — all four were the right call:

  1. ollama_ndjson.rs renamed, not deleted. The issue said delete; the surviving engine imports NdjsonLineBuffer. Renaming to ndjson.rs with provider-neutral docs is correct — the buffer was never Ollama-specific, it handles any newline-delimited body, and the new doc comment says so explicitly ("Both NDJSON and SSE"). Rename verified complete: mod.rs updated, the sole importer updated, no stale ollama_ndjson path anywhere. The 1 MiB MAX_LINE_BYTES DoS bound and its 7 tests survive intact — deleting the file would have silently dropped that protection.

  2. Discovery added. Deleting Ollama without it would have been a net functional regression: CompositeModelManager::list() auto-merged Ollama models, while OpenAI-compat models came only from hand-written [[openai_compat.configs]]. Adding openai_compat_discovery.rs is what makes this a pure refactor instead of a feature removal. Correct scope call.

  3. Selector rework. Options were rendered disabled with "(coming soon)". Shipping the deletion without this leaves zero selectable remote models — a broken product. Correct scope call.

  4. behaviors/mod.rs provider validation. This one deserves calling out: the validator accepted native|ollama|openai|pty and rejected "openai-compat" — which the frontend already emitted and persisted. That is a pre-existing write-path bug the Ollama removal happened to expose. Fixing it here is right.


Findings

🟡 Important

1. encodeSelection round-trip breaks for configs with no discovered models — the saved default silently renders as "None"

📁 packages/desktop-app/src/lib/components/settings/model-manager.svelte:68-86, 116-143

buildDefaultOptions() emits fallback rows for configs that contributed no discovered models, constructing modelId as the fully-qualified id:

opts.push({
  label: c.name,
  value: encodeSelection({
    provider: 'openai-compat',
    modelId: `openai-compat:${c.id}`,   // fully qualified
    configId: c.id,
  }),
});

But handleDefaultChange stores whatever decodeSelection produced, and the <select> binds value={defaultModel ? encodeSelection(defaultModel) : ''}. encodeSelection now returns s.modelId verbatim for openai-compat. So the round-trip only holds if modelId is always fully qualified.

It isn't. ai-chat-model-selector.svelte is the other producer of ModelSelection, and both feed the same ModelSelection type in settings.svelte.ts. Worse, any defaultModelSelection already in localStorage from before this PR stores modelId as the bare config UUID (the old code did modelId: configId). On next load, encodeSelection returns the bare UUID, no <option> has that value, and the select falls back to "" — the user's saved default silently reads as "None".

Per CLAUDE.md this is greenfield with zero users, so losing the persisted value is acceptable by policy. The problem is the failure mode, not the data loss: it fails silently to a valid-looking state rather than loudly. A user who set a default sees it quietly forgotten with no error, no log line, nothing to grep for.

Two options, either fine:

  • Make encodeSelection normalize rather than pass through — if s.modelId doesn't already start with openai-compat:, build it from configId. That makes the function total over both shapes and kills the whole class of bug.
  • Or, on load, drop a log.warn when defaultModel is non-null but matches no option, so the silent-reset is at least observable.

I'd take the first — it's three lines and removes the invariant entirely rather than reporting its violation.

Principle: Encode/decode pairs must be mutual inverses over the full domain of their input type. encodeSelection is now partial — correct only for the subset of ModelSelection values whose modelId is pre-qualified — but its signature promises totality. The type system can't catch it because both shapes are string.


2. list_models latency is now max(endpoint RTT), and no endpoint count is bounded

📁 packages/daemon/src/services/local_agent_service.rs:1020-1063

The JoinSet fan-out is the right structure — endpoints are independent network calls and running them concurrently means total latency is the slowest endpoint, not the sum. discover_models_or_empty correctly degrades per-endpoint so one dead provider can't blank the catalog. Good.

But note what this does to list_models, which was previously a fast local read:

  • Every ListModels RPC now pays up to DISCOVERY_TIMEOUT (5s) before returning. It's called from three frontend call sites on mount (model-store, agent-store, ai-chat-model-selector) — so one misconfigured endpoint makes the model selector spin for 5s on every chat open, every time. There's no caching.
  • configs is unbounded, so N endpoints spawn N concurrent tasks. Small N in practice, but nothing enforces it.

The 5s timeout is well-chosen and the doc comment justifies it precisely ("must degrade to no models quickly rather than stall the whole list"). I'm not asking for a change in this PR — the behavior is strictly better than the old Ollama path, which had no timeout at all. But a short-TTL cache on the discovery result (even 30s) would turn a repeated 5s stall into a one-time one, and is worth a follow-up issue.

Principle: A synchronous read path that acquires a network dependency inherits that dependency's worst-case latency. Fanning out concurrently bounds it to one timeout instead of N; caching removes it from the steady state.


🟢 Suggestions

3. agent-store.refreshAgents() now surfaces remote models as "local agents"

📁 packages/desktop-app/src/lib/stores/agent-store.svelte.ts:144-151

const localAgents = models.map(modelToAgent);   // no backend filter

model-store.refreshModels() correctly filters e.backend === 'gguf' with a good comment explaining why. agent-store does not — it maps every catalog row through modelToAgent, which stamps binary: 'local' and available: true.

I checked: this was already unfiltered before this PR (git show 075ae606^ confirms), so it's pre-existing, not a regression you introduced. But this PR meaningfully widens the blast radius — previously the extra rows only appeared when an Ollama daemon happened to be running; now every discovered remote model shows up in the agent picker labelled as local. Worth a one-line filter to match model-store's established pattern, or a follow-up issue.

Principle: DRY applies to filtering invariants, not just code. Two stores consuming the same catalog disagree about which rows belong to them; the one with the comment explaining the rule is the one that should be copied.


4. The no-timeout fix is sound, and the fallback is correctly reasoned

📁 packages/agent/src/local_agent/openai_compat_inference.rs:72-108

CONNECT_TIMEOUT 10s / REQUEST_TIMEOUT 600s is right for the workload: a local generation legitimately runs for minutes, so a conventional 30s request timeout would break normal use, while 600s still bounds the pathological connected-but-silent server. The comment nails why the bare default couldn't: "reqwest surfaces an error only on transport failure, and a connected-but-stalled server is not one."

build_http_client's .unwrap_or_else(|_| reqwest::Client::new()) is defensible and documented (TLS-init failure only; losing timeouts beats refusing to construct). Note this is one of the few places in the diff where a failure is swallowed without even a tracing::debug! — the discovery path logs its degradation, this one doesn't. Nit: a tracing::warn! in that arm would make an un-timeout'd client observable rather than invisible. Genuinely minor; the branch is near-unreachable.


5. parse_openai_compat_id — the tricky part is right, and tested as such

📁 packages/agent/src/local_agent/openai_compat_inference.rs:41-56

Splitting on the first colon is the correct choice and the reasoning is airtight: UUIDs never contain a colon, model names routinely do (mistral:7b). The Some((config_id, model)) if !model.is_empty() guard correctly treats a trailing openai-compat:uuid: as the no-model form rather than yielding Some("").

I traced all four parse sites and they agree:

  • parse_openai_compat_id (Rust, daemon load path) — first colon ✅
  • decodeSelection in model-manager.svelte:82 — .split(':')[0] ✅
  • handleChange in ai-chat-model-selector.svelte:230 — .split(':')[0] ✅
  • discoveredConfigIds in model-manager.svelte:130 — .split(':')[0] ✅

discovered_id_round_trips_through_the_prefix_helpers pins the invariant in Rust with a comment naming the trap ("not the last, and not the whole remainder"), and the TS test asserts openai-compat:abc-123:mistral:7b → configId: 'abc-123'. This is well-covered.

6. ModelBackend::as_wire_str() — correct instinct, and complete

📁 packages/agent/src/agent_types.rs:257-275, local_agent_service.rs:863

Catching that format!("{:?}", m.backend).to_lowercase() would render OpenAiCompat as "openaicompat" while the frontend matches "openai-compat" is a good catch — a silent, type-invisible wire mismatch that would have manifested as "no remote models ever appear" with nothing to grep. I checked for other Debug-derived wire strings in the changed daemon paths and found none remaining. The #[serde(rename_all = "kebab-case")] change on the same enum keeps the serde path consistent with the manual one.

Nit: as_wire_str(&self) could take self by value — ModelBackend is Copy. Trivial.

7. Test quality is notably good

The /models parse test uses a verbatim Ollama 0.32.1 body rather than a hand-written fixture, with a comment noting what the real payload does not carry. discovered_row_leaves_unreported_fields_at_unknown_sentinels asserts the sentinels explicitly — locking in "we don't invent metadata we can't observe" as a tested contract rather than a convention. parse_rejects_non_models_body covers the 200-with-unrelated-JSON case that a naive serde_json::from_str into a permissive struct would silently pass.


Recommendation

COMMENT — approve-with-nits in substance.

This is comfortably net-positive: a large, well-justified deletion that removes an entire redundant protocol client and its indirection layer, backed by a live test that proves the redundancy claim rather than asserting it. All eight acceptance criteria are met, and the three scope expansions were each necessary to avoid shipping a regression.

Finding #1 is a real bug and worth fixing before merge — it's a few lines and the silent-failure mode is the objectionable part, not the data loss. Findings #2 and #3 are legitimate follow-up issues, not merge blockers.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initial review posted as a PR comment. Recommendation: COMMENT (approve-with-nits). One 🟡 correctness finding worth fixing before merge (encodeSelection round-trip in model-manager.svelte), plus two follow-up-issue items. All 8 acceptance criteria verified independently.

…ilently reset

Review finding #1 (🟡). encodeSelection() returned modelId verbatim for
openai-compat, so the encode/decode round-trip held only when modelId was
already fully qualified. It is not always: buildDefaultOptions' fallback rows
and any default persisted before this branch carry a bare config UUID. The
<select> binds to encodeSelection(defaultModel), so a bare UUID matched no
<option> and the picker fell back to "" — the user's saved default silently
read as "None", with no error and nothing to grep for.

Losing the persisted value is fine per CLAUDE.md (greenfield, zero users);
failing silently to a valid-looking state is not. encodeSelection now
normalizes instead of passing through, making it total over ModelSelection
rather than correct only on a subset its signature does not distinguish.

Verified the old code encoded a pre-existing default to "abc-123" (matching no
option) where the new code yields "openai-compat:abc-123" (matching). Adds
model-manager-selection.test.ts pinning the round-trip, including the
colon-bearing model name, the bare-UUID case, and idempotency so a future
pass-through cannot silently reintroduce this.

Also from review:
- #4 nit: log when the HTTP client falls back to an untimed one — that branch
  discards the very timeouts the constants exist to enforce, so silence there
  hid the failure it was meant to prevent.
- #6 nit: as_wire_str takes self by value; ModelBackend is Copy.

Not addressed, deliberately:
- #2 (list_models inherits endpoint latency): reviewer flagged as non-blocking
  and strictly better than the old no-timeout path. A TTL cache needs an
  invalidation design — when should a newly pulled model appear? — which is a
  design decision, not review feedback. Follow-up issue.
- #3 (agent-store missing the backend === 'gguf' filter): reviewer verified it
  predates this branch. Fixing unrelated pre-existing bugs mid-PR is the scope
  creep the project guide warns against. Follow-up issue.

Frontend: 171 files / 4112 tests (was 170 / 4106; +1 file, +6 tests).

Refs #1793

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — commit 287f93f

✅ Addressed (3)

🟡 #1 — encodeSelection round-trip / silent default reset
📁 packages/desktop-app/src/lib/components/settings/model-manager.svelte:68-86

Confirmed as a real bug before fixing. Reproduced the exact failure the review described:

old: encodes to "abc-123"               -> matches an option? false
new: encodes to "openai-compat:abc-123" -> matches an option? true

encodeSelection now normalizes instead of passing through, so it is total over ModelSelection rather than correct only on the pre-qualified subset its signature doesn't distinguish. Took the first of the two suggested options, for the reason given in the review — it removes the invariant rather than reporting its violation.

Added src/tests/components/model-manager-selection.test.ts (6 tests) pinning the round-trip: colon-bearing model names, the bare-UUID case, the no-configId fallback, and idempotency — so a future pass-through refactor can't silently reintroduce this.

🟢 #4 nit — swallowed HTTP-client fallback
📁 packages/agent/src/local_agent/openai_compat_inference.rs:102-114

Added a tracing::warn!. As noted, that branch discards the very timeouts the constants exist to enforce, so silence there hid the failure it was meant to prevent.

🟢 #6 nit — as_wire_str(self) by value
📁 packages/agent/src/agent_types.rs. ModelBackend is Copy.

⏭️ Deferred to follow-up issues (2)

🟡 #2 — list_models inherits endpoint latency → #1807
Flagged non-blocking and strictly better than the old no-timeout path. A TTL cache needs an invalidation design — should a freshly ollama pulled model appear without restart, and via TTL, explicit refresh, or config-write invalidation? That's a design decision rather than review feedback, so it gets its own issue with the options written up.

🟢 #3 — agent-store missing the backend === 'gguf' filter → #1808
Verified pre-existing, as the review found. Fixing unrelated pre-existing bugs mid-PR is the scope creep CLAUDE.md warns against. The issue records that this PR widens the blast radius, which is the part worth acting on.

Verification

  • Frontend: 171 files / 4112 tests passing (baseline 170 / 4106; +1 file, +6 tests)
  • cargo check --workspace --all-targets clean; clippy -D warnings clean
  • svelte-check + tsc: 0 errors, 0 warnings
  • Pre-push gate passed again, no --no-verify

Re-Review Decision

NO RE-REVIEW NEEDED.

The one behavioral change is three lines in a pure function, its correctness is pinned by six new tests including an idempotency case, and the before/after was verified against the concrete failure the review reported. The other two changes are a log line and a &self → self. Nothing architectural, no new functionality.

@malibio
malibio merged commit 511e32a into main Jul 29, 2026
2 checks passed
@malibio
malibio deleted the worktree-issue-1793-ollama-openai-compat branch July 29, 2026 15:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove the Ollama-native inference path: drive Ollama through its OpenAI-compatible endpoint

1 participant