Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): an env-backed model counts as having a key (#395)

Yaowei Zhenga53e0915dc07
diff --git a/changelog/unreleased/2026-08-21-model-key-env-detection.md b/changelog/unreleased/2026-08-21-model-key-env-detection.md
new file mode 100644
index 00000000..cb718bd4
--- /dev/null
+++ b/changelog/unreleased/2026-08-21-model-key-env-detection.md
@@ -0,0 +1,16 @@
+# A model backed by an environment variable counts as having a key
+
+- **Date:** 2026-08-21
+- **Type:** fix
+- **Scope:** `web`
+- **PR:** [#395](https://github.com/Prism-Shadow/penguin-harness/pull/395)
+
+[中文版](2026-08-21-model-key-env-detection.zh.md)
+
+The chat model picker judged "has an API key" by the stored masked key alone, while the model library already showed a model backed by an exported environment variable as configured. A model whose key came from `ANTHROPIC_API_KEY` was therefore pushed behind the picker's "show models without key" expander and marked with the struck-through key icon, on the same screen where the library card printed that variable's masked value. Both surfaces were put on one rule: a stored key **or** an env fallback the server proved is set.
+
+## Details
+
+- `hasConfiguredKey` (`model-grouping.ts`) became the single predicate behind every surface — the picker's default list, its struck-through key icon and the "show models without key" count all read it — and `ModelCredentialRowLike` gained `envKeyMasked`. `envKey` still counts for nothing: it is only the NAME of a fallback variable and says nothing about whether that variable holds a value, while the server emits `envKeyMasked` only for one that currently does.
+- The model page's own `hasKey` was rebuilt on top of that predicate and now adds only what the DTO shape cannot carry: a key typed into the dialog counts before it is saved, and `clearApiKey` drops the **stored** key only — an environment variable cannot be cleared from there, so an env-backed row keeps its key through a clear. The card's key status line moved into `keyStatusText`, guarded by the same `hasKey`, so the card and the picker can no longer disagree about which rows are "not configured".
+- The chat credential guide — the one-time "no model credential configured" dialog — now asks `hasConfiguredKey` about the Project's default model instead of reading its masked key directly, so a Project whose default model runs on an environment variable is not nagged on first entry.
diff --git a/changelog/unreleased/2026-08-21-model-key-env-detection.zh.md b/changelog/unreleased/2026-08-21-model-key-env-detection.zh.md
new file mode 100644
index 00000000..2e45c4ca
--- /dev/null
+++ b/changelog/unreleased/2026-08-21-model-key-env-detection.zh.md
@@ -0,0 +1,16 @@
+# 由环境变量提供 key 的模型同样算作已配置
+
+- **Date:** 2026-08-21
+- **Type:** fix
+- **Scope:** `web`
+- **PR:** [#395](https://github.com/Prism-Shadow/penguin-harness/pull/395)
+
+[English](2026-08-21-model-key-env-detection.md)
+
+对话的模型选择器此前只按存储的掩码 key 判定「是否配置了 API key」,而模型库早已把由环境变量提供 key 的模型显示为已配置。于是 key 来自 `ANTHROPIC_API_KEY` 的模型会被折到选择器的「显示未配置 key 的模型」展开行之后、并带上划掉的 key 图标——而同一屏里模型库卡片正打印着该变量的掩码值。两处判定改为同一条规则:存储的 key **或**服务端已确认存在取值的环境变量兜底。
+
+## 细节
+
+- `hasConfiguredKey`(`model-grouping.ts`)成为所有界面共用的唯一判定——选择器的默认列表、划掉的 key 图标、以及「显示未配置 key 的模型」的计数都读它——`ModelCredentialRowLike` 随之新增 `envKeyMasked`。`envKey` 依旧不作数:它只是兜底变量的名字,并不能说明该变量是否有取值;而服务端只为当前确有取值的变量输出 `envKeyMasked`。
+- 模型页自己的 `hasKey` 改为构建在该判定之上,只额外承担 DTO 形状无法携带的两件事:对话框里刚输入、尚未保存的 key 立即算数;`clearApiKey` 只清除**存储的** key——环境变量无法从这里清除,因此由环境变量支撑的条目在清除后仍然有 key。卡片的 key 状态行抽为 `keyStatusText`,并由同一个 `hasKey` 把关,卡片与选择器不会再对「哪些条目未配置」给出不同答案。
+- 对话的 credential 引导——只弹一次的「尚未配置模型 credential」对话框——改为对 Project 的默认模型调用 `hasConfiguredKey`,不再直接读它的掩码 key;默认模型靠环境变量运行的 Project 首次进入时不会再被提示。
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index eb601d48..c6dc9620 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -106,7 +106,7 @@ import { buildInputHistory } from "./input-history";
import { buildOutline } from "./outline-model";
import { GoalStatusBanner } from "./goal-banner";
import { handoffMessage, modelSwitchMessage } from "./agent-handoff";
-import { sameModelRef } from "../models/model-grouping";
+import { hasConfiguredKey, sameModelRef } from "../models/model-grouping";
import { providerInfo } from "@prismshadow/penguin-core/model-catalog";
import { FilesPanel } from "./files-panel";
import { useFilesPanel } from "./use-files-panel";
@@ -998,6 +998,8 @@ export function ChatPage() {
// gated by the server prefs' credentialGuideSeen — previously it checked "default model has no
// key" and popped up a dialog on every visit to the chat page, which was repeated nagging for
// users who simply don't intend to configure a key / use environment variables instead.
+ // "Has a key" is hasConfiguredKey, the same rule the model library and the model picker use: a
+ // model backed by an exported environment variable is configured and must not be nagged.
useEffect(() => {
if (!projectId) return;
let cancelled = false;
@@ -1010,7 +1012,7 @@ export function ChatPage() {
const { prefs } = await api.getPrefs();
if (cancelled || prefs.credentialGuideSeen) return;
const def = res.models.find((m) => sameModelRef(m, res.defaultModel));
- const missing = !res.defaultModel || !def?.credential?.apiKeyMasked;
+ const missing = !res.defaultModel || !def || !hasConfiguredKey(def);
if (missing) setCredentialGuide(true);
// Mark as "seen" regardless of whether the dialog actually popped up: only ever once.
void api.putPrefs({ credentialGuideSeen: true }).catch(() => undefined);
diff --git a/packages/web/src/features/chat/model-select.tsx b/packages/web/src/features/chat/model-select.tsx
index fa586b96..259ba509 100644
--- a/packages/web/src/features/chat/model-select.tsx
+++ b/packages/web/src/features/chat/model-select.tsx
@@ -156,14 +156,14 @@ export function PickerList<T>({
* viewport no matter how many models there are.
* Dropdown order mirrors the model library page (visibleChatModels): a top quick-search box
* (the model page's rule — filters by id / display name / provider name); by default only
- * models with a configured API key are listed (stored masked key — the same standard as the
- * model page's key status; `envKey` is merely the NAME of a fallback env var and doesn't
- * count), with the selected and the default model always visible even without a key; a muted
- * bottom row reveals the remaining key-less models (marked by a struck-through key icon, with
- * the "no key" text in its title) without closing the menu or changing the selection — when
- * no model has a key at all, everything is listed directly. Rows carry the provider logo, the
- * light-yellow "Free" badge for zero-cost models (same as the model library card), the
- * project-default marker, and the selected checkmark.
+ * models with an API key are listed (hasConfiguredKey — a stored masked key or a masked env
+ * fallback, the same standard as the model page's key status; `envKey` is merely the NAME of a
+ * fallback env var and doesn't count on its own), with the selected and the default model
+ * always visible even without a key; a muted bottom row reveals the remaining key-less models
+ * (marked by a struck-through key icon, with the "no key" text in its title) without closing
+ * the menu or changing the selection — when no model has a key at all, everything is listed
+ * directly. Rows carry the provider logo, the light-yellow "Free" badge for zero-cost models
+ * (same as the model library card), the project-default marker, and the selected checkmark.
*/
export function ModelMenuList({
models,
diff --git a/packages/web/src/features/models/model-grouping.ts b/packages/web/src/features/models/model-grouping.ts
index b576a598..e391d1c7 100644
--- a/packages/web/src/features/models/model-grouping.ts
+++ b/packages/web/src/features/models/model-grouping.ts
@@ -99,19 +99,29 @@ export function orderModelsLikeLibrary<T extends ModelRowLike>(rows: T[]): T[] {
return groupModelRows(rows, "").flatMap((g) => g.rows);
}
-/** Row shape for the configured-key filter: adds the read-only credential display (the DTO's ModelInfo is a superset). */
+/**
+ * Row shape for the configured-key filter: adds the read-only credential display and the masked
+ * env-fallback preview (the DTO's ModelInfo is a superset).
+ */
export interface ModelCredentialRowLike extends ModelRowLike {
credential?: { apiKeyMasked?: string };
+ /**
+ * Masked preview of the env-fallback value: the server emits it only for a variable that
+ * currently holds a non-empty value, so its presence is proof the environment can authenticate
+ * this entry.
+ */
+ envKeyMasked?: string;
}
/**
- * Whether the model has an API key configured: judged solely by the stored (masked) key — the
- * same standard as the chat credential guide and the model page's key status. `envKey` is only
- * the NAME of a fallback environment variable; its presence says nothing about whether that
- * variable is actually set, so it never counts as configured.
+ * Whether the model has an API key behind it — the single rule shared by the model library, the
+ * chat model picker and the chat credential guide: a stored (masked) key **or** a masked env
+ * fallback, since a user who exported the variable has configured the key just as deliberately as
+ * one who typed it into the dialog. `envKey` is only the NAME of that variable and says nothing
+ * about whether it is set, so it never counts on its own.
*/
export function hasConfiguredKey(m: ModelCredentialRowLike): boolean {
- return !!m.credential?.apiKeyMasked;
+ return !!m.credential?.apiKeyMasked || !!m.envKeyMasked;
}
/**
@@ -143,10 +153,10 @@ export interface VisibleChatModelsOptions {
}
/**
- * Candidate list for the chat model dropdown: library order → keep only key-configured models
- * (plus the selected and the default model, unless showAll) → the query then filters whatever
- * is visible. When NO model has a configured key, the key filter degrades to showAll
- * (everything listed), so the dropdown is never uselessly empty.
+ * Candidate list for the chat model dropdown: library order → keep only models with a key
+ * (hasConfiguredKey: stored or env-backed; plus the selected and the default model, unless
+ * showAll) → the query then filters whatever is visible. When NO model has a key, the filter
+ * degrades to showAll (everything listed), so the dropdown is never uselessly empty.
*/
export function visibleChatModels<T extends ModelCredentialRowLike>(
models: T[],
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index ac3ec01f..0a7126ff 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -75,7 +75,13 @@ import {
resolveModelEnv,
} from "@prismshadow/penguin-core/model-catalog";
import type { FastModeProtocol, ModelProviderInfo } from "@prismshadow/penguin-core/model-catalog";
-import { groupModelRows, isFreeModel, sameModelRef, userProviderInfo } from "./model-grouping";
+import {
+ groupModelRows,
+ hasConfiguredKey,
+ isFreeModel,
+ sameModelRef,
+ userProviderInfo,
+} from "./model-grouping";
import { protocolPathForModel } from "./protocol-path";
import { ProtocolSuffixMenu } from "./protocol-suffix";
import {
@@ -321,11 +327,31 @@ function isPreset(row: RowState): boolean {
);
}
-/** Whether this row already has (or will have, after this edit) an API key configured. */
-function hasKey(row: RowState): boolean {
- return (
- !row.clearApiKey && (Boolean(row.apiKeyInput.trim()) || Boolean(row.credential?.apiKeyMasked))
- );
+/**
+ * Whether this row already has (or will have, after this edit) an API key: the shared
+ * hasConfiguredKey rule — a stored key or an env fallback the server proved is set — plus the two
+ * edit-only notions the DTO shape cannot carry. A key typed into the dialog counts before it is
+ * saved, and `clearApiKey` drops the **stored** key only: an environment variable cannot be
+ * cleared from here, so an env-backed row keeps its key through a clear.
+ */
+export function hasKey(row: RowState): boolean {
+ if (row.clearApiKey) return hasConfiguredKey({ ...row, credential: undefined });
+ return row.apiKeyInput.trim() !== "" || hasConfiguredKey(row);
+}
+
+/**
+ * The model card's key status line, most specific first: a stored key (not being cleared) shows
+ * its mask; a key typed but not yet saved has no mask of its own and just reads as configured;
+ * otherwise a detected first-party env fallback shows that variable's value under the same mask
+ * (the server reports envKeyMasked for official vendor entries only), so an env-backed row reads
+ * like a configured one. hasKey guards the whole ladder, so the card and the chat model picker can
+ * never disagree about which rows count as "not configured".
+ */
+export function keyStatusText(row: RowState): string {
+ if (!hasKey(row)) return S.models.noKey;
+ if (row.credential?.apiKeyMasked && !row.clearApiKey) return row.credential.apiKeyMasked;
+ if (row.apiKeyInput.trim() !== "") return S.models.keyConfigured;
+ return row.envKeyMasked ?? S.models.keyConfigured;
}
/** DTO -> row edit state (exported for unit tests): provider and modelId are both entry fields, never decomposed. */
@@ -1413,15 +1439,9 @@ function ModelCard({
priced
? `${displayPrice(row.cacheRead, currency)} / ${displayPrice(row.cacheWrite, currency)} / ${displayPrice(row.output, currency)}`
: null,
- // Key status: the mask when configured; with no stored key, a detected first-party env
- // fallback shows that variable's value under the same mask (the server only reports
- // envKeyMasked for official vendor entries), so the row reads like a configured one;
- // otherwise "not configured".
- row.credential?.apiKeyMasked && !row.clearApiKey
- ? row.credential.apiKeyMasked
- : hasKey(row)
- ? S.models.keyConfigured
- : (row.envKeyMasked ?? S.models.noKey),
+ // Key status (see keyStatusText): the stored mask, a detected env fallback's mask, a plain
+ // "configured" for a key typed but not yet saved, or "not configured".
+ keyStatusText(row),
].filter((v): v is string => v !== null);
const speedBadges =
diff --git a/packages/web/test/model-grouping.test.ts b/packages/web/test/model-grouping.test.ts
index f574b006..fdce980e 100644
--- a/packages/web/test/model-grouping.test.ts
+++ b/packages/web/test/model-grouping.test.ts
@@ -7,8 +7,9 @@
* group, sorted by name and appended after custom; empty groups are hidden, except the
* custom group, which is always shown when there's no search query, hosting the generic
* "add model" entry point. Also covers the chat dropdown's visibility rule (visibleChatModels):
- * key-configured models only by default (a stored masked key, judged by hasConfiguredKey),
- * selected/default always visible, everything listed when nothing is configured or on showAll.
+ * models with a key only by default (a stored masked key or a masked env fallback, judged by
+ * hasConfiguredKey), selected/default always visible, everything listed when nothing is
+ * configured or on showAll.
*/
import { describe, expect, it } from "vitest";
import { MODEL_PROVIDERS } from "@prismshadow/penguin-core/model-catalog";
@@ -145,7 +146,7 @@ describe("groupModelRows", () => {
});
describe("hasConfiguredKey", () => {
- it("only a stored (masked) key counts as configured", () => {
+ it("a stored (masked) key counts as configured", () => {
expect(
hasConfiguredKey({
provider: "anthropic",
@@ -155,7 +156,24 @@ describe("hasConfiguredKey", () => {
).toBe(true);
expect(hasConfiguredKey({ provider: "anthropic", modelId: "m" })).toBe(false);
expect(hasConfiguredKey({ provider: "anthropic", modelId: "m", credential: {} })).toBe(false);
- // envKey is merely the NAME of a fallback env var (nothing says the var is actually set): never counts.
+ });
+
+ it("a masked env fallback counts too: the server reports it only for a variable that holds a value", () => {
+ expect(
+ hasConfiguredKey({ provider: "anthropic", modelId: "m", envKeyMasked: "sk-a\u20263456" }),
+ ).toBe(true);
+ // Stored key absent but the environment behind it: still configured, same as the model card shows.
+ expect(
+ hasConfiguredKey({
+ provider: "anthropic",
+ modelId: "m",
+ credential: {},
+ envKeyMasked: "sk-a\u20263456",
+ }),
+ ).toBe(true);
+ });
+
+ it("envKey alone is merely the NAME of a fallback var (nothing says it is set): never counts", () => {
const envOnly = { provider: "anthropic", modelId: "m", envKey: "ANTHROPIC_API_KEY" };
expect(hasConfiguredKey(envOnly)).toBe(false);
});
@@ -186,6 +204,37 @@ describe("visibleChatModels", () => {
]);
});
+ it("an env-backed model is listed like a stored-key one, not hidden behind show-all", () => {
+ const envBacked: ModelCredentialRowLike = {
+ provider: "anthropic",
+ modelId: "claude-opus-4-8",
+ envKeyMasked: "sk-a\u20263456",
+ };
+ const withEnv = [...pool.filter((m) => m.modelId !== "claude-opus-4-8"), envBacked];
+ expect(visibleChatModels(withEnv, { showAll: false, query: "" }).map((m) => m.modelId)).toEqual(
+ [
+ "claude-sonnet-4-6",
+ "claude-opus-4-8", // env fallback only — still counts as having a key
+ "kimi-k2.6",
+ ],
+ );
+ // The "show models without key" expander counts only the two genuinely key-less rows.
+ expect(
+ visibleChatModels(withEnv, { showAll: true, query: "" }).length -
+ visibleChatModels(withEnv, { showAll: false, query: "" }).length,
+ ).toBe(2);
+ // Knowing the variable's NAME is not knowing it is set: such a row stays hidden.
+ const nameOnly = {
+ provider: "anthropic",
+ modelId: "claude-opus-4-8",
+ envKey: "ANTHROPIC_API_KEY",
+ };
+ const withNameOnly = [...pool.filter((m) => m.modelId !== "claude-opus-4-8"), nameOnly];
+ expect(
+ visibleChatModels(withNameOnly, { showAll: false, query: "" }).map((m) => m.modelId),
+ ).toEqual(["claude-sonnet-4-6", "kimi-k2.6"]);
+ });
+
it("showAll lists everything, still in library order", () => {
expect(visibleChatModels(pool, { showAll: true, query: "" }).map((m) => m.modelId)).toEqual([
"deepseek-v4",
diff --git a/packages/web/test/models-input.test.ts b/packages/web/test/models-input.test.ts
index 2c03dd78..74f7869f 100644
--- a/packages/web/test/models-input.test.ts
+++ b/packages/web/test/models-input.test.ts
@@ -11,6 +11,9 @@
* model_id changes) moves the pointer along.
* - Which env fallback variables a key hint may promise (detectedEnvKeys):
* only those the server reported a value for.
+ * - Whether a row has a key (hasKey) and what the card prints for it
+ * (keyStatusText): the shared hasConfiguredKey rule (stored key or a masked
+ * env fallback) plus the dialog's unsaved-edit notions.
*/
import { describe, expect, it } from "vitest";
import {
@@ -20,10 +23,13 @@ import {
detectedEnvKeys,
digitsOnly,
fastModeState,
+ hasKey,
+ keyStatusText,
nextPointers,
rowRef,
toRow,
} from "../src/features/models/models-page";
+import { S } from "../src/lib/strings";
describe("digitsOnly (context window)", () => {
it("keeps digits only", () => {
@@ -72,6 +78,66 @@ describe("detectedEnvKeys (variables a key hint may promise)", () => {
});
});
+describe("hasKey / keyStatusText (the model card's key judgement)", () => {
+ const stored = toRow({
+ provider: "moonshot",
+ modelId: "kimi-k2.6",
+ credential: { apiKeyMasked: "sk-o\u20261111" },
+ isDefault: false,
+ });
+ const envBacked = toRow({
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ envKey: "ANTHROPIC_API_KEY",
+ envKeyMasked: "sk-a\u20263456",
+ isDefault: false,
+ });
+ const bare = toRow({ provider: "custom", modelId: "my-model", isDefault: false });
+
+ it("a stored key or a masked env fallback both count; a bare row does not", () => {
+ expect(hasKey(stored)).toBe(true);
+ expect(hasKey(envBacked)).toBe(true);
+ expect(hasKey(bare)).toBe(false);
+ // Variable name only: nothing proves it is set, so it is still key-less.
+ const nameOnly = toRow({
+ provider: "deepseek",
+ modelId: "deepseek-v4-pro",
+ envKey: "DEEPSEEK_API_KEY",
+ isDefault: false,
+ });
+ expect(hasKey(nameOnly)).toBe(false);
+ });
+
+ it("a key typed in the dialog counts before it is saved", () => {
+ expect(hasKey({ ...bare, apiKeyInput: " sk-new " })).toBe(true);
+ expect(hasKey({ ...bare, apiKeyInput: " " })).toBe(false);
+ });
+
+ it("clearApiKey drops the stored key only: an env-backed row keeps its key", () => {
+ expect(hasKey({ ...stored, clearApiKey: true })).toBe(false);
+ // The environment cannot be cleared from the dialog, so clearing leaves it behind.
+ expect(
+ hasKey({ ...envBacked, credential: { apiKeyMasked: "sk-a\u20269999" }, clearApiKey: true }),
+ ).toBe(true);
+ });
+
+ it("the status line shows the most specific source it has", () => {
+ expect(keyStatusText(stored)).toBe("sk-o\u20261111");
+ expect(keyStatusText(envBacked)).toBe("sk-a\u20263456");
+ expect(keyStatusText(bare)).toBe(S.models.noKey);
+ // A key typed but not yet saved has no mask of its own.
+ expect(keyStatusText({ ...bare, apiKeyInput: "sk-new" })).toBe(S.models.keyConfigured);
+ // Clearing a stored key falls back to the environment's mask rather than "no key".
+ expect(
+ keyStatusText({
+ ...envBacked,
+ credential: { apiKeyMasked: "sk-a\u20269999" },
+ clearApiKey: true,
+ }),
+ ).toBe("sk-a\u20263456");
+ });
+});
+
describe("clientTypeAfterProviderChange", () => {
it("uses openai-chat when moving to Custom and otherwise preserves the current client", () => {
expect(clientTypeAfterProviderChange("custom", "")).toBe("openai-chat");