Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(session): pin the first selected model instead of following the default

vastsa7d92d961d092
diff --git a/apps/desktop/src/lib/session-model.ts b/apps/desktop/src/lib/session-model.ts
new file mode 100644
index 000000000..41b71431c
--- /dev/null
+++ b/apps/desktop/src/lib/session-model.ts
@@ -0,0 +1,92 @@
+/** Resolve the provider/model a session should keep after first selection. */
+
+export type SessionModelRef = {
+ providerId?: string;
+ modelId?: string;
+};
+
+export type SessionModelProvider = {
+ id: string;
+ defaultModelId?: string;
+ models?: Array<{ id: string }>;
+};
+
+export type SessionModelSettings = {
+ defaultProviderId?: string;
+ defaultModelId?: string;
+};
+
+/**
+ * App default (or an explicit draft override) at the moment a session is
+ * created. Later Settings default-model changes must not rewrite this pair.
+ */
+export function inheritedSessionModelBinding({
+ draft,
+ settings,
+ providers,
+}: {
+ draft?: SessionModelRef | null;
+ settings?: SessionModelSettings | null;
+ providers: readonly SessionModelProvider[];
+}): SessionModelRef {
+ const providerId = draft?.providerId ?? settings?.defaultProviderId;
+ const provider = providers.find((item) => item.id === providerId);
+ const modelId =
+ draft?.modelId ??
+ settings?.defaultModelId ??
+ provider?.defaultModelId ??
+ provider?.models?.[0]?.id;
+ return {
+ ...(providerId ? { providerId } : {}),
+ ...(modelId ? { modelId } : {}),
+ };
+}
+
+/** Newest transcript turn that already recorded a provider/model. */
+export function lastUsedSessionModel(
+ messages: readonly SessionModelRef[],
+): SessionModelRef {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (message.modelId || message.providerId) {
+ return {
+ ...(message.providerId ? { providerId: message.providerId } : {}),
+ ...(message.modelId ? { modelId: message.modelId } : {}),
+ };
+ }
+ }
+ return {};
+}
+
+export function sessionNeedsModelPin(
+ session: SessionModelRef & { source?: string },
+): boolean {
+ if (session.source === "pi-native" || session.source === "remote") return false;
+ return !session.providerId || !session.modelId;
+}
+
+/**
+ * Durable snapshot for an unpinned session: last used turn, else the current
+ * app default. Callers persist this so the session stops following Settings.
+ */
+export function pinnedSessionModelBinding({
+ session,
+ messages,
+ settings,
+ providers,
+}: {
+ session: SessionModelRef;
+ messages?: readonly SessionModelRef[];
+ settings?: SessionModelSettings | null;
+ providers: readonly SessionModelProvider[];
+}): SessionModelRef {
+ const used = lastUsedSessionModel(messages ?? []);
+ return inheritedSessionModelBinding({
+ draft: {
+ providerId: session.providerId ?? used.providerId,
+ modelId: session.modelId ?? used.modelId,
+ },
+ settings,
+ providers,
+ });
+}
diff --git a/apps/desktop/src/stores/runtime/session-coordination.ts b/apps/desktop/src/stores/runtime/session-coordination.ts
index 7af1d3144..d99734139 100644
--- a/apps/desktop/src/stores/runtime/session-coordination.ts
+++ b/apps/desktop/src/stores/runtime/session-coordination.ts
@@ -18,6 +18,7 @@ import {
FORKED_SESSION_WINDOW,
} from "../../lib/session-fork";
import { EMPTY_SESSION_WINDOW } from "../../lib/session-create";
+import { inheritedSessionModelBinding } from "../../lib/session-model";
import {
clearSessionPanes,
retainSessionPane,
@@ -279,16 +280,16 @@ export function createSessionCoordination({
options && "draftConfiguration" in options
? options.draftConfiguration
: state.draftConfiguration;
+ const inherited = inheritedSessionModelBinding({
+ draft: draftConfig,
+ settings,
+ providers: state.providers,
+ });
const defaultProvider = state.providers.find(
- (provider) =>
- provider.id === (draftConfig?.providerId ?? settings?.defaultProviderId),
+ (provider) => provider.id === inherited.providerId,
);
- const inheritedModelId =
- draftConfig?.modelId ??
- settings?.defaultModelId ??
- defaultProvider?.defaultModelId;
const inheritedBinding = defaultProvider?.models.find((candidate) =>
- modelIdsMatch(candidate.id, inheritedModelId ?? ""),
+ modelIdsMatch(candidate.id, inherited.modelId ?? ""),
);
const defaultThinkingLevel = initialThinkingLevelForBinding(
inheritedBinding,
@@ -303,8 +304,8 @@ export function createSessionCoordination({
mode: draftConfig?.mode ?? normalizeMode(settings?.defaultMode),
thinkingLevel: draftConfig?.thinkingLevel ?? defaultThinkingLevel,
permissionMode: draftConfig?.permissionMode,
- providerId: draftConfig?.providerId,
- modelId: draftConfig?.modelId,
+ providerId: inherited.providerId,
+ modelId: inherited.modelId,
projectPath: projectPath ?? undefined,
});
} catch (error) {
diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.ts
index 7af59e84c..56ead6928 100644
--- a/apps/desktop/src/stores/slices/session-slice.ts
+++ b/apps/desktop/src/stores/slices/session-slice.ts
@@ -18,6 +18,10 @@ import {
EMPTY_SESSION_WINDOW,
sessionIsReusableEmpty,
} from "../../lib/session-create";
+import {
+ pinnedSessionModelBinding,
+ sessionNeedsModelPin,
+} from "../../lib/session-model";
import {
retainSessionPane,
} from "../../lib/session-panes";
@@ -387,6 +391,41 @@ export function createSessionSlice({
rememberSessionCompactions(id, detail.session);
void get().restorePendingPlan(id);
void get().acknowledgeSessionOutcome(id);
+ const selected = get().sessions.find((session) => session.id === id);
+ if (
+ selected &&
+ sessionNeedsModelPin(selected) &&
+ get().pendingPlans[id]?.status !== "pending"
+ ) {
+ const pin = pinnedSessionModelBinding({
+ session: selected,
+ messages: selectedMessages,
+ settings: get().settings,
+ providers: get().providers,
+ });
+ if (pin.providerId && pin.modelId) {
+ set((state) => ({
+ sessions: state.sessions.map((session) =>
+ session.id === id
+ ? applyOptimisticSessionConfiguration(session, pin)
+ : session,
+ ),
+ }));
+ if (get().activeSessionId === id) {
+ void get().configureActiveSession({
+ mode: selected.mode,
+ providerId: pin.providerId,
+ modelId: pin.modelId,
+ });
+ } else {
+ void api.configureSession(id, {
+ mode: selected.mode,
+ providerId: pin.providerId,
+ modelId: pin.modelId,
+ });
+ }
+ }
+ }
} finally {
if (runtime.isCurrentSessionSelection(selection)) {
runtime.clearSessionSelection(selection);
diff --git a/apps/desktop/test/session-create.test.mjs b/apps/desktop/test/session-create.test.mjs
index f41b0dabf..a3a737c02 100644
--- a/apps/desktop/test/session-create.test.mjs
+++ b/apps/desktop/test/session-create.test.mjs
@@ -62,6 +62,11 @@ test("creating a session reveals the empty destination before host IO", () => {
assert.match(persist, /commitCreatedEmptySession/);
assert.match(sessionCoordination, /function commitCreatedEmptySession/);
assert.match(sessionCoordination, /scheduleHomeDraftAdopt/);
+ assert.match(persist, /inheritedSessionModelBinding/);
+ assert.match(persist, /providerId: inherited\.providerId/);
+ assert.match(persist, /modelId: inherited\.modelId/);
+ assert.doesNotMatch(persist, /providerId: draftConfig\?\.providerId/);
+ assert.doesNotMatch(persist, /modelId: draftConfig\?\.modelId/);
});
test("send and paste wait for an in-flight New Task instead of creating a second session", () => {
@@ -72,3 +77,14 @@ test("send and paste wait for an in-flight New Task instead of creating a second
assert.match(materialize, /pendingNewSessionRequests/);
assert.match(materialize, /await pending/);
});
+
+test("opening an unpinned session snapshots its first selected model", () => {
+ const select =
+ sessionSlice.match(/selectSession: async[\s\S]*?\n newSession: async/)?.[0] ?? "";
+ assert.ok(select.length > 0, "selectSession implementation not found");
+ assert.match(select, /sessionNeedsModelPin/);
+ assert.match(select, /pinnedSessionModelBinding/);
+ assert.match(select, /configureActiveSession/);
+ assert.match(select, /api\.configureSession\(id,/);
+});
+
diff --git a/apps/desktop/test/session-model.test.mjs b/apps/desktop/test/session-model.test.mjs
new file mode 100644
index 000000000..1705853d5
--- /dev/null
+++ b/apps/desktop/test/session-model.test.mjs
@@ -0,0 +1,105 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ inheritedSessionModelBinding,
+ lastUsedSessionModel,
+ pinnedSessionModelBinding,
+ sessionNeedsModelPin,
+} from "../src/lib/session-model.ts";
+
+const providers = [
+ {
+ id: "openai",
+ defaultModelId: "gpt-4.1",
+ models: [{ id: "gpt-4.1" }, { id: "gpt-4.1-mini" }],
+ },
+ {
+ id: "anthropic",
+ defaultModelId: "claude-sonnet",
+ models: [{ id: "claude-sonnet" }],
+ },
+];
+
+test("new sessions snapshot the app default provider and model", () => {
+ assert.deepEqual(
+ inheritedSessionModelBinding({
+ draft: null,
+ settings: { defaultProviderId: "openai", defaultModelId: "gpt-4.1-mini" },
+ providers,
+ }),
+ { providerId: "openai", modelId: "gpt-4.1-mini" },
+ );
+});
+
+test("an explicit composer draft wins over the app default", () => {
+ assert.deepEqual(
+ inheritedSessionModelBinding({
+ draft: { providerId: "anthropic", modelId: "claude-sonnet" },
+ settings: { defaultProviderId: "openai", defaultModelId: "gpt-4.1-mini" },
+ providers,
+ }),
+ { providerId: "anthropic", modelId: "claude-sonnet" },
+ );
+});
+
+test("changing the app default later does not rewrite a pinned session", () => {
+ const created = inheritedSessionModelBinding({
+ draft: null,
+ settings: { defaultProviderId: "openai", defaultModelId: "gpt-4.1" },
+ providers,
+ });
+ const laterDefault = inheritedSessionModelBinding({
+ draft: null,
+ settings: { defaultProviderId: "anthropic", defaultModelId: "claude-sonnet" },
+ providers,
+ });
+ assert.deepEqual(created, { providerId: "openai", modelId: "gpt-4.1" });
+ assert.deepEqual(laterDefault, { providerId: "anthropic", modelId: "claude-sonnet" });
+ assert.notDeepEqual(created, laterDefault);
+});
+
+test("unpinned desktop sessions need a durable model pin", () => {
+ assert.equal(sessionNeedsModelPin({}), true);
+ assert.equal(sessionNeedsModelPin({ providerId: "openai" }), true);
+ assert.equal(sessionNeedsModelPin({ modelId: "gpt-4.1" }), true);
+ assert.equal(
+ sessionNeedsModelPin({ providerId: "openai", modelId: "gpt-4.1" }),
+ false,
+ );
+ assert.equal(
+ sessionNeedsModelPin({ source: "pi-native", providerId: "openai" }),
+ false,
+ );
+ assert.equal(
+ sessionNeedsModelPin({ source: "remote", modelId: "gpt-4.1" }),
+ false,
+ );
+});
+
+test("legacy unpinned sessions pin the last used turn before the live default", () => {
+ assert.deepEqual(
+ lastUsedSessionModel([
+ { providerId: "openai", modelId: "gpt-4.1" },
+ { providerId: "anthropic", modelId: "claude-sonnet" },
+ ]),
+ { providerId: "anthropic", modelId: "claude-sonnet" },
+ );
+ assert.deepEqual(
+ pinnedSessionModelBinding({
+ session: {},
+ messages: [{ providerId: "anthropic", modelId: "claude-sonnet" }],
+ settings: { defaultProviderId: "openai", defaultModelId: "gpt-4.1-mini" },
+ providers,
+ }),
+ { providerId: "anthropic", modelId: "claude-sonnet" },
+ );
+ assert.deepEqual(
+ pinnedSessionModelBinding({
+ session: {},
+ messages: [],
+ settings: { defaultProviderId: "openai", defaultModelId: "gpt-4.1-mini" },
+ providers,
+ }),
+ { providerId: "openai", modelId: "gpt-4.1-mini" },
+ );
+});
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 1e0cc9f11..29762db6d 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -932,8 +932,10 @@ Electron main enriches session list/get/create/fork/configure results with
effective reasoning capability from the local models.dev record for that
session's exact provider/API URL and model. Sessions without a pinned
`providerId`/`modelId` inherit the app default provider/model for this
-enrichment only; the durable ids remain unset so later default-model changes
-still apply. An ID absent from the snapshot, or a session with no resolvable
+enrichment only. Desktop session create writes the then-current default (or an
+explicit Composer draft override) into the durable ids; later default-model
+changes do not rewrite an already created session. A home draft with no session
+still follows the live default. An ID absent from the snapshot, or a session with no resolvable
default, gets `supportsReasoning: false` and `off`; cached/provider claims do
not replace catalog semantics. The Rust host remains authoritative only for the
durable `thinkingLevel`.
diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.md
index a149ea9cb..fea41af2d 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -203,10 +203,14 @@ never rewrites an existing session's stored choice.
Unpinned sessions still advertise that inherited default model's reasoning
capability on session list/get/create/fork/configure. Enrichment does not pin
-`providerId`/`modelId`. The Composer never treats a `supportsReasoning: false`
-or empty thinking-level snapshot as authoritative when the selected
-catalog/binding model exposes levels, so a mid-turn thinking or model pick
-cannot collapse the menu to Off-only.
+`providerId`/`modelId`; desktop session create does, by writing the then-current
+app default (or Composer draft override) into the durable ids. Later Settings
+default-model changes do not rewrite an already created session. Opening a
+legacy row whose ids are still empty snapshots the last used turn, else the
+current default, so it stops following Settings. The Composer never treats a
+`supportsReasoning: false` or empty thinking-level snapshot as authoritative
+when the selected catalog/binding model exposes levels, so a mid-turn thinking
+or model pick cannot collapse the menu to Off-only.
## 5. Capability warnings
@@ -370,7 +374,9 @@ App-level default:
- if none configured, onboarding checklist requires provider setup before first agent run
Session-level:
-- inherits app default at creation
+- inherits app default at creation and stores that `providerId`/`modelId` pair
+- later Settings default-model changes apply only to new sessions and the
+ unpersisted home draft, not to already created sessions
- initializes thinking to the highest level enabled by the inherited model's
binding; published levels seed a new binding, while an empty or `off`-only
binding starts at `off`
@@ -499,6 +505,7 @@ same model to the check mark, the toggle and the duplicate guard.
refresh keeps the cached picker populated
- [ ] capability badges visible
- [ ] session model change applies to next turn only
+- [ ] a newly created session stores the then-current default provider/model, and later default-model changes do not rewrite that session
- [ ] a new session defaults a reasoning-capable inherited model to that
binding's stored default thinking level (clamped onto the enabled set;
strongest-enabled only when unset) and otherwise defaults to `off`
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 1880c7567..2afc57d17 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -438,8 +438,12 @@ identify the platform validation still needed.
provider name and exact model ID beneath the Default model label; its quiet
Change action does not repeat the current value. The picker groups
model-level entries by provider, marks the exact current model, and a newly
- created session inherits that exact model and its owning provider.
- Searching by provider or model filters locally, the result list scrolls without moving the settings card, and an unmatched query shows an empty state.
+ created session inherits that exact model and its owning provider. Changing
+ the default later does not rewrite an already created session's stored
+ provider/model; only a new session or the unpersisted home draft follows the
+ live default. Searching by provider or model filters locally, the result list
+ scrolls without moving the settings card, and an unmatched query shows an empty
+ state.
- **Specs linked**: `03-runtime/13-model-catalog-and-selection.md`
- **Acceptance**: B (model selection)
- **Milestone**: M6
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index 181af0e78..247d47a50 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -793,9 +793,10 @@ type SessionDetail = SessionSummary & {
Electron 主进程用该会话精确 provider/API URL 与 model 的本地 models.dev
记录,丰富 session list/get/create/fork/configure 结果中的有效推理能力。
-未固定 `providerId`/`modelId` 的会话仅在此丰富步骤继承应用默认供应商/模型;
-持久化 id 保持为空,以便之后的默认模型变更仍然生效。快照中没有该 ID、或
-会话无法解析出默认目标时,得到 `supportsReasoning: false` 和 `off`;缓存/
+未固定 `providerId`/`modelId` 的会话仅在此丰富步骤继承应用默认供应商/模型。
+桌面创建会话时会把当时的默认(或 Composer 草稿覆盖)写入持久化 id;之后改
+默认模型不会改写已创建会话。没有会话的首页草稿仍跟随当前默认。快照中没有该
+ID、或会话无法解析出默认目标时,得到 `supportsReasoning: false` 和 `off`;缓存/
供应商声明不能取代目录语义。Rust 主机仅对持久化的 `thinkingLevel` 权威。
全局插件启动器使用仅 Electron 允许的通道:
diff --git a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
index d2afd1e75..a735c627a 100644
--- a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
@@ -118,9 +118,12 @@ type RecentModelRef = {
重写现有会话的存储选择。
未固定的会话仍在 list/get/create/fork/configure 上展示该继承默认模型的
-推理能力;丰富步骤不会写入 `providerId`/`modelId`。当所选目录/绑定模型
-暴露了思考等级时,Composer 不得把 `supportsReasoning: false` 或空等级列表
-当作权威快照,因此回合中改档不会把菜单塌缩成只剩关闭思考。
+推理能力;丰富步骤不会写入 `providerId`/`modelId`。桌面创建会话时会把当时的
+应用默认(或 Composer 草稿覆盖)写入持久化 id。之后改默认模型不会改写已创建
+会话。打开仍为空 id 的旧行时,会快照最近一次使用的模型,否则快照当前默认,
+从而不再跟随设置。当所选目录/绑定模型暴露了思考等级时,Composer 不得把
+`supportsReasoning: false` 或空等级列表当作权威快照,因此回合中改档不会把
+菜单塌缩成只剩关闭思考。
## 5. 能力警告
@@ -233,7 +236,8 @@ type ModelCatalogItem = {
- 如果未配置,则新手引导清单需要在第一个代理运行之前设置提供商
会话级别:
-- 继承应用程序创建时的默认设置
+- 创建时继承应用默认,并写入该 `providerId`/`modelId`
+- 之后改设置里的默认模型只作用于新会话和未持久化的首页草稿,不改已创建会话
- 将思维初始化到所选模型绑定的默认思考等级(钳位到已启用档;
未设置时才回落最高已启用档),当它支持推理时,否则 `off`
- 可以独立覆盖
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 176d3e516..1085fa6ba 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -221,7 +221,7 @@ unit/integration 测试;代码 pull request 使用有选择且高价值的 E2E
- **前置条件**:存在两个可运行的提供商,其中一个至少配置两个模型绑定。
- **步骤**:打开“设置 → 模型配置 → 更改默认模型”,选择该提供商下的第二个模型。
-- **预期**:选择器显示模型级条目而非仅显示提供商;所选模型被标记为当前模型,新建会话继承准确的模型及其所属提供商。
+- **预期**:选择器显示模型级条目而非仅显示提供商;所选模型被标记为当前模型,新建会话继承准确的模型及其所属提供商。之后改默认模型不会改写已创建会话的存储模型;只有新会话和未持久化的首页草稿跟随当前默认。
按提供商或模型搜索会在本地过滤;结果列表在不移动设置卡片的情况下滚动,无匹配查询显示空状态。
- **关联规格**:`03-runtime/13-model-catalog-and-selection.md`
- **验收标准**:B(模型选择)