Skip to content

fix(provider): record the picked model so model-less sessions inherit it - #1347

Merged
Astro-Han merged 14 commits into
devfrom
claude/model-recent-writer
Jun 17, 2026
Merged

fix(provider): record the picked model so model-less sessions inherit it#1347
Astro-Han merged 14 commits into
devfrom
claude/model-recent-writer

Conversation

@Astro-Han

@Astro-Han Astro-Han commented Jun 17, 2026

Copy link
Copy Markdown
Owner

Summary

Restore the writer for state/model.json's recent list, so a session that sends no explicit model inherits the user's actually-picked model instead of falling back to the first configured provider. The list is written at the one place that truly knows the user chose a model — the desktop model picker — via a new server endpoint.

  • New provider/model-state.ts: applyRecent (pure: front-promote, dedupe, cap, preserve sibling fields) and recordRecent (locked, best-effort read-modify-write). Reuses the shared util/record isRecord.
  • New POST /provider/recent (provider.recordRecent) persists {providerID, modelID} into recent.
  • Renderer: on an explicit pick (model.set(item, { recent: true }), the model picker's onSelect), local.tsx calls provider.recordRecent best-effort, alongside its own models.recent.push.
  • SDK: the generated recordRecent client method + types for the new endpoint.

Why record on pick, not on the prompt path. The prompt path cannot tell an explicit pick from an agent-pin fallback: the renderer always sends input.model (current() falls back to agent.current().model), so a prompt-path heuristic mislabels one or the other (an earlier shouldRecordRecent provenance filter, then a modelFromAgent equality guess, each traded false positives for false negatives). The model picker is the only place with unambiguous intent, so recording there is structurally correct — an agent's pinned model, a slash command, automation, or a subagent can never leak into the global default, with no provenance guessing. prompt.ts is fully reverted.

Why

Provider.defaultModel() picks the default from recent, but nothing in this fork wrote that list — upstream wrote it from the TUI (packages/tui/src/context/local.tsx), and replacing the TUI with the desktop UI kept only the reader (provider.ts). With recent permanently empty, every model-less entry point gets the wrong default:

  • Telegram /new (remote-bridge createSession/sendPrompt send no model)
  • a bare HTTP caller

The desktop chat hides this because the renderer sends its per-workspace selection as an explicit input.model.

Related Issue

No issue. Surfaced while debugging the mobile-companion work (#1339) — a Telegram /new used the wrong model. This is an independent opencode-core gap, so it ships as its own PR.

Human Review Status

Pending

Review Focus

  • Where recording happens: only the model picker's explicit pick (recent: true) calls the endpoint — mirroring the renderer's own recent semantics. model.cycle (no recent) and every prompt path do not. Is the picker the right and complete single source of truth?
  • Concurrency / safety: recordRecent uses Flock.withLock + read-modify-write because writeJson is not atomic; it preserves favorite/variant and treats only a missing file (ENOENT) as empty — a parse/permission failure skips the write rather than clobber sibling state.
  • SDK generated files (see Risk Notes).

Risk Notes

  • Blast radius: changes the default-model behavior for every model-less entry point (CLI, Telegram, HTTP) to "inherit the model you last explicitly picked" — what defaultModel()'s recent branch was designed for. Intentional; matches upstream semantics.
  • Generated SDK files: sdk.gen.ts/types.gen.ts gain only the new recordRecent method + its types (+77 lines, additive). Running the full generator also surfaces ~640 lines of pre-existing drift between dev's committed SDK and its server (e.g. roots?: boolean"true" | "false"); that drift is unrelated and would change other endpoints' caller-facing types, so it is deliberately excluded — the additions here match what the generator emits for this endpoint.
  • Local file writes: writes state/model.json (locked, best-effort, sibling fields preserved).
  • Renderer call: best-effort fire-and-forget (.catch(() => {})); a failure never disrupts the pick.
  • Skipped conditional checklist items: UI/screenshots — no visible UI or copy changed (the picker behaves identically; the added call is invisible). Platform/packaging — no packaging/updater/signing/path/shell/permission surface touched; reuses the existing Global.Path.state.

How To Verify

opencode typecheck (tsgo --noEmit): clean
app typecheck (tsgo -b): clean
sdk typecheck (tsgo --noEmit): clean   # confirms the hand-isolated generated method + types compile
src/provider/model-state.test.ts: 8 pass
  - applyRecent: front-promote, dedupe, cap, preserve favorite/variant, tolerate garbage
  - recordRecent: preserves sibling state on a normal file; creates from empty on ENOENT;
    does NOT overwrite a file it cannot parse (sibling state survives)
test/provider/provider.test.ts: Provider.defaultModel reads a recordRecent-seeded model back
  via the model.json round-trip (fails if defaultModel stops reading recent, or recordRecent stops writing)
app test:unit: 1931 pass (local.tsx change introduces no renderer regression)

Screenshots or Recordings

N/A — no visible UI change.

Checklist

How to use this checklist:

  • Tick a box by replacing [ ] with [x]. Do not edit, add, or remove items.
  • The bot-applied label items can only be honestly ticked AFTER the PR is opened and the labeler / priority-triage bots have run — return to the PR description and tick them then.
  • Most items are required. The few that are conditional are explicitly marked (conditional); for those, leave unticked if they truly do not apply and explain why in Risk Notes. All other items must be ticked before requesting human review.
  • Type label — this PR carries exactly one of bug, enhancement, task, documentation. Type labels are author-added; the labeler bot does NOT assign them. Add the label in the GitHub UI, then tick this.
  • Routing labels — this PR carries at least one of app, ui, platform, harness, ci. The labeler bot assigns these on PR open based on changed paths. Confirm the bot's choice (or override if wrong), then tick this.
  • Priority label — this PR carries exactly one of P0, P1, P2, P3. The priority-triage bot suggests one on PR open. Confirm or override, then tick this.
  • Human Review Status above is set to Pending, Approved by @<reviewer>, or Not required: <reason> (default is Pending; "not required" is restricted to bot-authored low-risk PRs).
  • I linked the related issue, or stated in Summary why there is no issue.
  • I described the review focus and any meaningful risks.
  • I replaced the example block in How To Verify with the real verification steps and the key result for each.
  • I did not introduce unrelated refactors, dependencies, generated files, or file changes beyond the stated scope.
  • (conditional) I manually checked visible UI or copy changes when needed, with screenshots or recordings. Leave unticked only if no visible UI or copy changed.
  • (conditional) I considered macOS and Windows impact for platform, packaging, updater, signing, paths, shell, or permissions changes. Leave unticked only if no platform/packaging surface was touched.
  • (conditional) I called out docs, release notes, dependencies, permissions, credentials, deletion behavior, generated content, or local file changes when relevant. Leave unticked only if none of those surfaces was touched.
  • I reviewed the final diff for unrelated changes and suspicious dependency changes.
  • I am targeting dev, and my PR title and commit messages use Conventional Commits in English.

Summary by CodeRabbit

  • New Features
    • Added automatic saving of your model selections to a “recent models” history, promoting newly picked models to the top, deduplicating them, and capping history length.
    • Added a server endpoint to record recent model picks, and made the app mirror explicit recent selections to the server.
    • Updated model selection behavior so seeded “recent” models are preferred when starting up.
  • Tests
    • Added coverage for recent history update logic and the new server route, including persistence, file creation, and handling corrupt state.

defaultModel() picks the default from state/model.json's `recent` list, but
nothing in this fork writes that list — upstream wrote it from the TUI, and
replacing the TUI with the desktop UI kept only the reader. With `recent`
permanently empty, any session that sends no explicit model (a Telegram /new,
a bare HTTP caller) falls through to the first configured provider instead of
the user's actual last choice.

Restore the writer on the server side: after a user's top-level prompt settles
on a model, record it into `recent` via a locked read-modify-write that
preserves the file's other fields (favorite/variant). Only the user's own
top-level prompt seeds the default — automation runs and subagent/agent-tool
child sessions are filtered out, so an inner agent model can never leak into
the default a fresh session inherits.

Verified against upstream/dev (tui writes recent; this fork dropped it). Tests
cover the pollution filter and recent dedupe/cap/field preservation.
@coderabbitai

coderabbitai Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Astro-Han, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 28 minutes and 17 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d44dc944-6cb5-4a6d-ad0b-4fa021aa261a

📥 Commits

Reviewing files that changed from the base of the PR and between 8d87301 and 8c62eb2.

📒 Files selected for processing (4)
  • packages/app/src/context/local.tsx
  • packages/opencode/src/provider/model-state.test.ts
  • packages/opencode/src/provider/model-state.ts
  • packages/opencode/test/server/provider-recent-route.test.ts
📝 Walkthrough

Walkthrough

Adds a ModelState namespace that persists the user's recently selected model into state/model.json via a locked read-modify-write. A new POST /recent server route exposes this to clients, and the app's local context mirrors model selections to the server as a best-effort fire-and-forget call. Unit tests validate the pure logic and filesystem behavior; integration tests verify defaultModel selection honors the seeded recent model and the server route persists posted selections.

Changes

Recent Model History

Layer / File(s) Summary
ModelState namespace: applyRecent and recordRecent
packages/opencode/src/provider/model-state.ts
New ModelState namespace with ModelRef, MAX_RECENT, applyRecent (dedup, prepend, cap), isEnoent helper, and recordRecent (Flock-based read-modify-write to state/model.json with full error suppression).
POST /recent route and client wiring
packages/opencode/src/server/instance/provider.ts, packages/app/src/context/local.tsx
ProviderRoutes gains a POST /recent endpoint that validates providerID/modelID and delegates to ModelState.recordRecent. local.tsx adds a fire-and-forget call to sdk.client.provider.recordRecent in the options?.recent path.
ModelState unit tests
packages/opencode/src/provider/model-state.test.ts
Tests cover applyRecent (promotion, dedup, sibling fields, max-length, invalid input) and recordRecent (valid file update, ENOENT creation, corrupt JSON skip).
defaultModel integration test
packages/opencode/test/provider/provider.test.ts
Adds a regression test that seeds a model via recordRecent, asserts defaultModel() picks the seeded model over the provider default, and cleans up model.json to prevent test leakage.
POST /recent route integration tests
packages/opencode/test/server/provider-recent-route.test.ts
Tests the POST /provider/recent endpoint, asserting valid requests persist the posted model as recent[0] in model.json and requests missing modelID are rejected with HTTP 400.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

platform

🐇 A hop, a skip, a model in mind,
I jot it down so it's easy to find!
model.json holds the history tight,
deduped and capped — everything right.
The server recalls what the bunny picked last,
✨ Recent selections remembered so fast!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: restoring the mechanism to record picked models so model-less sessions can inherit the last-used model instead of defaulting to the first provider.
Description check ✅ Passed The description covers all required template sections: Summary, Why, Related Issue, Human Review Status, Review Focus, Risk Notes, How To Verify, and a complete Checklist with most items checked.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/model-recent-writer

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added harness Model harness, prompts, tool descriptions, and session mechanics P2 Medium priority labels Jun 17, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggested priority: P2 (includes non-doc, non-test paths outside the low-risk bucket).

P1/P0 are reserved for maintainer confirmation. Please relabel manually if this is a release blocker, security issue, data-loss risk, or updater/runtime failure.

@Astro-Han Astro-Han added the bug Something isn't working label Jun 17, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces the ModelState namespace to persist and manage the user's last-used model in state/model.json. It includes pure functions to compute the updated recent models list, filters to prevent automation or subagent sessions from polluting the global default, and a locked write-modify-write mechanism to safely persist the state. Additionally, corresponding unit tests are added, and the state-recording logic is integrated into the session prompt workflow. The feedback highlights an incorrect relative import path for Flock that should be updated to its proper package entrypoint.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread packages/opencode/src/provider/model-state.ts
A slash command resolves its own (often pinned) model and reuses the prompt
path, so the recent-model writer recorded that command-scoped model into
state/model.json. A later model-less session (e.g. a Telegram /new) then
inherited the command's utility model instead of the user's chat model.

Treat command invocations as a pollution source alongside automation and
subagent child sessions: thread an internal fromCommand flag through
PromptRuntimeOptions and fold it into shouldRecordRecent so a command never
seeds the global default.

Reported by Codex review (P2).
@Astro-Han

Copy link
Copy Markdown
Owner Author

Review round 1

Codex (xhigh) — 1× P2, fixed in 3db6a46:
A slash command resolves its own (often pinned) model and reuses the prompt path, so the recent-model writer was recording that command-scoped model. A later model-less session (Telegram /new) could then inherit the command's utility model instead of the user's chat model. Fixed by treating command invocations as a pollution source alongside automation/subagent: an internal fromCommand flag threads through PromptRuntimeOptions into shouldRecordRecent. Added a unit test; bun test 9 pass, typecheck clean.

Gemini — 1× high (../util/flock import), false positive, resolved:
../util/flock is package-local — packages/opencode/src/util/flock.ts has its own independent namespace Flock. Sibling provider/models.ts:10 uses the identical import in working code, and typecheck passes.

CodeRabbit — rate-limited, no review delivered.

The recent-model writer recorded the resolved message.info.model, which is
input.model ?? agent.model ?? lastModel — so a session whose agent pins its own
model (ag.model, used when no input.model is passed) leaked that model into the
global default a model-less session (Telegram /new, HTTP) inherits.

Gate on input.model instead: only the user's own explicit pick from the chat
model picker seeds recent. A model merely derived from the agent, a command,
automation, or a subagent does not. The desktop always sends input.model (the
picker refuses to send without one), so this is zero-change for desktop chat and
only drops the headless ag.model pollution.

Adds the integration coverage the pure-function tests lacked: a prompt with an
explicit model writes model.json.recent; an agent-only or automation prompt does
not; and Provider.defaultModel reads a recordRecent-seeded model back.

Semantic: only explicit user selections become the default. Reported by code review (P2).
model-state.ts defined its own isRecord; util/record already exports an
identical guard. Drop the local copy.

Reported by code review (P3).
@Astro-Han

Copy link
Copy Markdown
Owner Author

Review round 2

P2 — recorded the resolved model, not the user's explicit choice (fixed 6505f42):
The writer recorded message.info.model = input.model ?? agent.model ?? lastModel, so an agent-pinned ag.model (used when no input.model is passed) could leak into the global default. Now gated on input.model — only the user's explicit pick from the chat model picker seeds recent.

Chosen semantic (per the review's product-decision callout): only explicit user model selections become the new-session default. A model merely derived from the agent, a slash command, automation, or a subagent does not seed it. This matches upstream (the TUI wrote recent on model selection) and is zero-change for desktop chat — submit.ts always sends input.model (the picker refuses to send without one); it only drops the headless ag.model pollution.

P2 — only pure functions were tested (fixed 6505f42):
Added integration coverage of the real chain:

  • prompt.test.ts: an explicit-model prompt writes model.json.recent; an agent-only prompt and an automation prompt do not.
  • provider.test.ts: Provider.defaultModel reads a recordRecent-seeded model back (model.json round-trip).
    These fail if the prompt hook is removed, recordRecent no-ops, or defaultModel stops reading recent.

P3 — reused shared isRecord (fixed 1731f4b): dropped model-state.ts's local copy in favour of util/record.

model-state 9 · provider 109 · prompt 24 pass · typecheck clean.

…ate tests

The desktop UI always sends a resolved model with every prompt, and that model
can be the selected agent's own configured pin rather than a model-picker
choice (the renderer's model falls back to the agent's model). Gating the
recent-model writer on input.model alone therefore still let an agent's utility
model become the default a model-less session (Telegram /new) inherits — the
pollution the guard is meant to prevent.

createUserMessage now surfaces the agent's configured model so prompt() can tell
an explicit pick apart from a fall-through to the agent pin; shouldRecordRecent
gains a modelFromAgent guard alongside the existing automation/subagent/command
exclusions.

Tests: the new prompt→model.json→defaultModel tests share the process-wide
state/model.json, so clear it around each so assertions on recent[0] stay
independent of run order.
@Astro-Han

Copy link
Copy Markdown
Owner Author

Round 3 — review fixes (019a2be)

[P2] Agent-pinned models could still pollute the recent default (Codex fresh-eye)
The desktop renderer always sends a resolved input.model, and local.model.current() falls back to the selected agent's configured model (local.tsx current()agent.current()?.model; agent.set() even writes the agent pin into scope().model). So gating on input.model presence alone still recorded an agent's utility model — e.g. a plan agent pinned to a cheap model — which a later /new would inherit. Verified against the renderer code.

Fix is server-side (no renderer/SDK change): createUserMessage already computes the agent's configured model, so it now surfaces it and prompt() passes a modelFromAgent flag to shouldRecordRecent, which excludes a model that merely equals the agent's pin — same shape as the existing automation/subagent/command guards. Net effect matches the chosen "only explicit selection" semantic; the one residual is that explicitly re-picking the exact model the agent already pins won't re-seed (harmless).

Regression test: a prompt carrying input.model equal to the agent's configured model does not seed recent.

[P3] Shared state/model.json across tests
The new prompt → model.json → defaultModel tests read/write the process-wide state/model.json (one XDG_STATE_HOME per test process) without cleanup, so order/leftovers could affect assertions. Added beforeEach/afterEach clears in the prompt describe block and before/after clears around the provider round-trip test.

Verification: model-state 10 pass, prompt 25 pass, provider 109 pass; the three files run together in one process (shared model.json) — 144 pass; tsgo --noEmit clean.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/opencode/test/session/prompt.test.ts (1)

1399-1595: ⚡ Quick win

Use the Effect test harness (testEffect + it.live) for this new suite.

This block exercises Effect services and real filesystem/time behavior, so it should use the test harness pattern required for packages/opencode/test/**/*.test.{ts,tsx} instead of raw test(...).

As per coding guidelines: “Use testEffect(...) from test/lib/effect.ts for tests that exercise Effect services… Use it.live(...) when the test depends on real time [and] filesystem…”.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/opencode/test/session/prompt.test.ts` around lines 1399 - 1595, The
test suite in the describe block "session.prompt seeds the recent default model"
is currently using raw `test(...)` functions but should use the Effect test
harness since the tests exercise Effect services (SessionPrompt.Service,
Session.Service) and depend on real filesystem operations (fs.readFile, fs.rm)
and real time behavior (setTimeout polling). Import `it.live` from
`test/lib/effect.ts` at the top of the file and replace each `test(...)` call
with `it.live(...)` for the four test cases: "an explicit-model user prompt
seeds recent[0]", "a prompt that only inherits the agent's model does NOT seed
recent", "an automation prompt does NOT seed recent", and "a prompt whose model
equals the agent's configured model does NOT seed recent".

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/opencode/src/provider/model-state.ts`:
- Around line 81-83: The issue is in the withLock block where
Filesystem.readJson catches all read errors indiscriminately and treats them as
undefined, causing applyRecent to create a fresh object that overwrites the file
and loses existing favorite/variant data. Instead, differentiate between ENOENT
(file not found) errors and other read errors (permission denied, malformed
JSON, transient failures) by checking the error code. Only call applyRecent and
write via Filesystem.writeJson when the file doesn't exist; skip the write
operation if the file exists but is temporarily unreadable or malformed to
preserve existing data.

In `@packages/opencode/test/session/prompt.test.ts`:
- Around line 1487-1490: The test at lines 1487, 1533, and 1582 uses a fixed
setTimeout(150) before asserting that recent data is not polluted by a detached
recordRecent operation, which is unreliable on slow CI environments. Replace
each single setTimeout(150) with a bounded polling mechanism that repeatedly
checks the condition (that recent data does not contain the unwanted model with
providerID "openai" and modelID "gpt-5.2") within a reasonable timeout window,
ensuring the test waits for the actual state rather than relying on a fixed time
delay. This pattern should be applied consistently to all three test blocks
mentioned in the comment.

---

Nitpick comments:
In `@packages/opencode/test/session/prompt.test.ts`:
- Around line 1399-1595: The test suite in the describe block "session.prompt
seeds the recent default model" is currently using raw `test(...)` functions but
should use the Effect test harness since the tests exercise Effect services
(SessionPrompt.Service, Session.Service) and depend on real filesystem
operations (fs.readFile, fs.rm) and real time behavior (setTimeout polling).
Import `it.live` from `test/lib/effect.ts` at the top of the file and replace
each `test(...)` call with `it.live(...)` for the four test cases: "an
explicit-model user prompt seeds recent[0]", "a prompt that only inherits the
agent's model does NOT seed recent", "an automation prompt does NOT seed
recent", and "a prompt whose model equals the agent's configured model does NOT
seed recent".
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d56bba84-27dd-4d98-9302-3b49e0793f6a

📥 Commits

Reviewing files that changed from the base of the PR and between e1f1ef9 and 019a2be.

📒 Files selected for processing (5)
  • packages/opencode/src/provider/model-state.test.ts
  • packages/opencode/src/provider/model-state.ts
  • packages/opencode/src/session/prompt.ts
  • packages/opencode/test/provider/provider.test.ts
  • packages/opencode/test/session/prompt.test.ts

Comment thread packages/opencode/src/provider/model-state.ts Outdated
Comment thread packages/opencode/test/session/prompt.test.ts Outdated
…mpt path

The prompt path cannot distinguish an explicit model pick from an agent-pin
fallback: the renderer always sends input.model (current() falls back to
agent.current().model), so any prompt-path heuristic mislabels one or the
other. The earlier attempts (shouldRecordRecent provenance flags, then a
modelFromAgent equality guess) only traded false positives for false negatives.

Record at the one place that truly knows the user chose a model: the desktop
model picker. On an explicit pick the renderer calls a new POST /provider/recent,
which persists the choice into state/model.json's `recent` list — the source
Provider.defaultModel() reads when a session carries no model (e.g. a Telegram /new).

- model-state: drop the prompt-path provenance helpers; recordRecent does a
  locked read-modify-write that preserves sibling fields and treats only a
  missing file (ENOENT) as empty — a parse/permission failure skips the write
  rather than clobber sibling state.
- prompt.ts: fully reverted, no provenance plumbing.
- server: POST /provider/recent (provider.recordRecent).
- sdk: generated recordRecent client method + types.
- renderer: mirror an explicit pick to the server, best-effort.
@github-actions github-actions Bot added app Application behavior and product flows ui Design system and user interface labels Jun 17, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/opencode/src/provider/model-state.test.ts (1)

51-51: 💤 Low value

Await the cleanup promise for consistency.

The beforeEach hook properly awaits its async operations, but afterEach returns the promise without awaiting. While Bun handles returned promises, adding async/await here aligns with beforeEach and makes the async behavior explicit.

-  afterEach(() => fs.rm(modelFile(), { force: true }))
+  afterEach(async () => await fs.rm(modelFile(), { force: true }))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/opencode/src/provider/model-state.test.ts` at line 51, The afterEach
hook returns the promise from fs.rm without awaiting it, while the beforeEach
hook properly awaits its async operations. To fix this for consistency, make the
afterEach callback function async and add the await keyword before the fs.rm
call to ensure the promise is properly awaited, matching the explicit async
pattern used in beforeEach.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/opencode/src/provider/model-state.test.ts`:
- Line 51: The afterEach hook returns the promise from fs.rm without awaiting
it, while the beforeEach hook properly awaits its async operations. To fix this
for consistency, make the afterEach callback function async and add the await
keyword before the fs.rm call to ensure the promise is properly awaited,
matching the explicit async pattern used in beforeEach.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a1c0f59a-c2f3-4a44-88e5-97544cd0f537

📥 Commits

Reviewing files that changed from the base of the PR and between 019a2be and d15a11d.

⛔ Files ignored due to path filters (2)
  • packages/sdk/js/src/v2/gen/sdk.gen.ts is excluded by !**/gen/**
  • packages/sdk/js/src/v2/gen/types.gen.ts is excluded by !**/gen/**
📒 Files selected for processing (4)
  • packages/app/src/context/local.tsx
  • packages/opencode/src/provider/model-state.test.ts
  • packages/opencode/src/provider/model-state.ts
  • packages/opencode/src/server/instance/provider.ts

@Astro-Han Astro-Han changed the title fix(provider): persist last-used model so model-less sessions inherit it fix(provider): record the picked model so model-less sessions inherit it Jun 17, 2026
The unit tests exercised ModelState.recordRecent and the recordRecent ->
defaultModel round-trip directly; nothing hit the actual /provider/recent
route. Add a route-level test (Server.Default().app) that POSTs a model and
asserts it lands at model.json recent[0], plus a 400 case for a body missing
modelID — so the route path, request body schema, and handler -> model.json
wiring all fail loudly if broken.
Match the async/await form of the file's beforeEach and the sibling route
test's hook. No behavior change (Bun already awaits a returned promise).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/opencode/test/server/provider-recent-route.test.ts (1)

46-57: ⚡ Quick win

Assert no state write on 400 responses.

This test verifies status code, but not the no-side-effect guarantee. Add an assertion that model.json is still absent/unchanged when schema validation fails.

Proposed test hardening
   test("rejects a body missing modelID (request schema is enforced)", async () => {
     await using tmp = await tmpdir({ git: true })
     const app = Server.Default().app

     const response = await app.request("/provider/recent", {
       method: "POST",
       headers: { "x-opencode-directory": tmp.path, "content-type": "application/json" },
       body: JSON.stringify({ providerID: "deepseek" }),
     })

     expect(response.status).toBe(400)
+    await expect(fs.access(modelFile())).rejects.toThrow()
   })
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/opencode/test/server/provider-recent-route.test.ts` around lines 46
- 57, The test "rejects a body missing modelID (request schema is enforced)"
currently only verifies the HTTP status code is 400, but does not assert that no
state was written to the filesystem. Add an assertion after the status code
check that verifies model.json is still absent or unchanged in the tmp directory
to ensure the no-side-effect guarantee when schema validation fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/opencode/test/server/provider-recent-route.test.ts`:
- Around line 46-57: The test "rejects a body missing modelID (request schema is
enforced)" currently only verifies the HTTP status code is 400, but does not
assert that no state was written to the filesystem. Add an assertion after the
status code check that verifies model.json is still absent or unchanged in the
tmp directory to ensure the no-side-effect guarantee when schema validation
fails.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6996b8e5-8f45-4fce-80ba-7efd9b55d12a

📥 Commits

Reviewing files that changed from the base of the PR and between d15a11d and 8d87301.

📒 Files selected for processing (2)
  • packages/opencode/src/provider/model-state.test.ts
  • packages/opencode/test/server/provider-recent-route.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/opencode/src/provider/model-state.test.ts

…see a partial file

recordRecent held a lock, but Provider.defaultModel() reads model.json unlocked
and treats a parse failure as empty recent (falling back to the first provider's
model), and writeFile is not atomic — so a read landing inside the write window
could see a half-written file and pick the wrong default.

Write to a temp file and rename (atomic on the same filesystem): a concurrent
reader now sees either the old or the new complete file, never a partial one.
Scoped to recordRecent (no change to shared Filesystem behavior). Add a
concurrency test asserting a valid file and no temp residue.
applyRecent only deduped; a structurally-invalid old entry (non-object, or
missing string providerID/modelID) survived, occupied a cap slot, and could push
a still-valid older model out of `recent` — which defaultModel() would otherwise
fall through to. Filter the previous list to well-formed refs first; sibling
fields (favorite/variant) are untouched.
…elper

The pick-to-server call lived inline in local.tsx's model.set, untestable
without standing up the whole Local context. Extract recordPickedModel(client,
item, options) — which owns the "only an explicit pick (recent flag) records"
gate — and unit-test it: an explicit pick records exactly once with the picked
ref; a non-explicit set (model.cycle / plain set) and a cleared selection record
nothing; a rejected recordRecent is swallowed so the pick is never disrupted.
Harden the schema-rejection case to prove the no-side-effect guarantee: a body
missing modelID is rejected before the handler runs, so model.json stays absent.
The extracted recordPickedModel helper was a production module created only for
testability, and its unit test exercised the helper in isolation — not that
local.tsx actually calls it — so it added indirection without proving the real
wiring. Inline the one best-effort call back into the picker's recent branch.
The real HTTP boundary stays covered by the /provider/recent route test; the
gate is the existing `if (!options?.recent) return` shared with models.recent.
The test only read the file after all writes settled, so a non-atomic plain
write would have passed it too — false confidence. A deterministic atomicity
test would need a slow-writer injection (production DI just for the test) or
timing-based partial reads (flaky); neither is worth it. The temp+rename write
is atomic by construction, and its read-modify-write path is already exercised
end-to-end by the sibling-preservation / ENOENT / corrupt-file tests.
@Astro-Han
Astro-Han merged commit 15ad201 into dev Jun 17, 2026
36 checks passed
@Astro-Han
Astro-Han deleted the claude/model-recent-writer branch June 17, 2026 12:28
Astro-Han added a commit that referenced this pull request Jun 18, 2026
… (#1354)

Follow-up to the #1347 review (recent-model default): guard the picker's recordRecent wiring with a unit test, plus a model-state comment trim.

Root cause of the gap: `model.set(item, { recent: true })` is the only path that calls `provider.recordRecent`. The existing `ModelState`, route, and `defaultModel` tests all exercise the server side, so a refactor that drops `{ recent: true }` at the picker call site — or deletes the client call — would leave every test green while silently breaking the model-less-session default (a Telegram /new inherits the recent model).

Change boundary:
- Extract the picker's single write path into a dependency-free `selectModel()` (`model-picker-select.ts`); `model-picker.tsx`'s `ModelList.onSelect` now calls it.
- `model-picker-select.test.ts` asserts the load-bearing invariant: an explicit pick AND clearing the selection both pass `{ recent: true }`.
- `model-state.ts`: trim the upstream-TUI backstory header and PR-style doc to the load-bearing constraints (recent list in `state/model.json`; ENOENT starts empty; other read failures skip to protect sibling state; atomic rename for the unlocked reader).

Why extract instead of testing the component: importing `model-picker.tsx` pulls `@kobalte/core`, which throws `Client-only API called on the server side` under the bun server-condition test runtime, so the real picker interaction is reachable only via Playwright e2e. The pure-function seam mirrors the existing `sidebar-item-navigation.ts` precedent.

Review follow-ups:
- An earlier attempt extracted `set`/`cycle` into a `createModelActions` factory; that added production surface for test-only reasons (YAGNI) and was reverted — `local.tsx`/`local.test.ts` are back at the merge base.
- The negative cases (plain programmatic `set` / `cycle` must not record) are intentionally not asserted: there is no light real-path seam for them, and exercising them would require mounting the full `LocalProvider` — the heavy e2e the #1347 review vetoed.

Verification:
- `bun test model-picker-select.test.ts local.test.ts` — 8 pass (2 new + 6 unchanged local)
- red/green gate confirmed: removing `{ recent: true }` from `selectModel` turns the test red
- `bun run typecheck` app + opencode clean, eslint clean, full CI green

Residual risk: the real picker click interaction (DOM → onSelect) is covered by e2e, not this unit test; this guards the wiring invariant only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app Application behavior and product flows bug Something isn't working harness Model harness, prompts, tool descriptions, and session mechanics P2 Medium priority ui Design system and user interface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant