Skip to content

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

fix(desktop): import the login shell environment on GUI launches (#370)

Yaowei Zheng3339cb9a38b4
diff --git a/changelog/unreleased/2026-08-20-desktop-login-shell-env.md b/changelog/unreleased/2026-08-20-desktop-login-shell-env.md
new file mode 100644
index 00000000..6a14be92
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-desktop-login-shell-env.md
@@ -0,0 +1,21 @@
+# Desktop imports the login shell's environment on GUI launches
+
+- **Date:** 2026-08-20
+- **Type:** fix
+- **Scope:** `desktop`, `server`, `web`, `docs`
+- **PR:** [#370](https://github.com/Prism-Shadow/penguin-harness/pull/370)
+- **Issue:** [#351](https://github.com/Prism-Shadow/penguin-harness/issues/351)
+
+[中文版](2026-08-20-desktop-login-shell-env.zh.md)
+
+Made the desktop app read the user's login-shell environment on macOS and Linux GUI launches, so API keys exported in `.zshrc` / `.profile` reach core's model env fallback and the agent shell gets the user's real `PATH` — neither had been visible to an app started from the Dock or a desktop session, forcing keys to be re-entered and agent commands onto the bare system `PATH`.
+
+## Details
+
+- Before anything reads `process.env`, the shell runs the user's `$SHELL` once as an interactive login shell around a sentinel-framed `env -0` dump (NUL separation keeps values containing newlines intact; the frame cuts away rc-file noise), then merges the result **fill-missing-only** — a variable set on the launch itself always wins. The embedded server, and with it the agent shell, inherits the merged environment at fork time.
+- `PATH` is the one merged key: the login shell's entries first, launch-time-only entries appended, deduplicated.
+- Shell bookkeeping (`_`, `SHLVL`, `PWD`, `OLDPWD`, `TERM`) and `ELECTRON_RUN_AS_NODE` are never imported, nor are `PENGUIN_WEB_DIST` and `PENGUIN_CLI_ENTRY` — they pick which code the embedded server serves and self-updates through, so a profile line written for a repo checkout must not retarget an installed app.
+- The probe is best-effort with a 5s hard timeout; any failure leaves the environment untouched. Launches from a terminal (`TERM` set) and Windows skip it entirely. `PENGUIN_NO_LOGIN_SHELL_ENV` opts out.
+- Made the env fallback visible, for first-party official entries only (vendor group, catalog shape unmodified — gateway, custom and user-defined groups are excluded, so the official `OPENAI_API_KEY` is never steered toward a reseller endpoint): with no stored key and the variable detected, the card's key slot and the model dialog both show the variable's value masked by the same rule as stored keys — the dialog putting "Read from environment variable" in the created-at position, and offering no clear control; storing a key still overrides the variable. The models API reports `envKeyMasked` alongside `envKey` — masked preview only, the plaintext is never serialized.
+- Narrowed the "leave the key empty and the environment covers it" hint — the model dialog's API key placeholder, the note under it, and the group-wide key dialog's placeholder — to variables the server reported a value for. Knowing which variable a provider reads says nothing about whether it is set, so the hint used to promise an empty field would work on machines where it would have left the model with no key at all.
+- Documented in the desktop quickstart and the configuration reference.
diff --git a/changelog/unreleased/2026-08-20-desktop-login-shell-env.zh.md b/changelog/unreleased/2026-08-20-desktop-login-shell-env.zh.md
new file mode 100644
index 00000000..88afa1d7
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-desktop-login-shell-env.zh.md
@@ -0,0 +1,21 @@
+# 桌面版图形界面启动时导入登录 shell 环境变量
+
+- **Date:** 2026-08-20
+- **Type:** fix
+- **Scope:** `desktop`, `server`, `web`, `docs`
+- **PR:** [#370](https://github.com/Prism-Shadow/penguin-harness/pull/370)
+- **Issue:** [#351](https://github.com/Prism-Shadow/penguin-harness/issues/351)
+
+[English](2026-08-20-desktop-login-shell-env.md)
+
+让桌面版在 macOS 与 Linux 的图形界面启动时读取用户登录 shell 的环境变量:`.zshrc` / `.profile` 里 export 的 API key 能进入 core 的模型环境变量回退,agent shell 也拿到用户真实的 `PATH`——此前从 Dock / 桌面会话启动的应用看不到这些变量,用户被迫重复填写 key,agent 命令只能在系统裸 `PATH` 上运行。
+
+## 细节
+
+- 在任何代码读取 `process.env` 之前,外壳把用户的 `$SHELL` 以交互式登录 shell 跑一次,用哨兵标记框住 `env -0` 输出(NUL 分隔保住含换行的值,框定裁掉 rc 文件的杂音),然后**只补缺不覆盖**地合并——启动环境里已有的变量永远优先。内嵌 server 在 fork 时继承合并后的环境,agent shell 随之受益。
+- `PATH` 是唯一做合并的键:登录 shell 的条目在前,启动环境独有的条目追加在后,并去重。
+- shell 的簿记变量(`_`、`SHLVL`、`PWD`、`OLDPWD`、`TERM`)与 `ELECTRON_RUN_AS_NODE` 永不导入;`PENGUIN_WEB_DIST`、`PENGUIN_CLI_ENTRY` 同样排除——它们决定内嵌 server 提供哪份前端代码、从哪个入口自更新,为仓库检出写下的 profile 行不该改写已安装应用的指向。
+- 探测尽力而为,5 秒硬超时,任何失败都保持环境原样。从终端启动(`TERM` 已设置)与 Windows 完全跳过。设置 `PENGUIN_NO_LOGIN_SHELL_ENV` 可关闭导入。
+- 让环境变量回退可见,且仅限官方 first-party 条目(官方 vendor 分组、catalog 形态未被改动——网关、custom 与自定义分组一律排除,避免把官方 `OPENAI_API_KEY` 引向转售端点):未配置存储 key 且检测到变量时,卡片的 key 槽位与模型详情都以存储 key 相同的规则显示该变量取值的掩码,详情里「创建时间」的位置改写为「读取自环境变量」,且不提供清除项;存入 key 仍按既有优先级覆盖变量。models API 在 `envKey` 旁新增 `envKeyMasked`——只下发掩码预览,明文绝不序列化。
+- 收窄「留空则由环境变量兜底」这类提示——模型详情里 API key 的 placeholder、其下方的默认端点说明,以及整组配置 key 对话框的 placeholder——只在服务端确实读到了值的变量上出现。知道某个 provider 读哪个变量,并不等于那个变量被设置过;此前的提示会在变量为空的机器上劝用户留空,结果模型一个 key 都没有。
+- 已写入桌面版速上手与配置参考文档。
diff --git a/packages/desktop/src/login-shell-env.ts b/packages/desktop/src/login-shell-env.ts
new file mode 100644
index 00000000..6f75a5ee
--- /dev/null
+++ b/packages/desktop/src/login-shell-env.ts
@@ -0,0 +1,242 @@
+/**
+ * Login-shell environment import for GUI launches (#351).
+ *
+ * A shell launched from the macOS Dock or a Linux desktop session inherits the session
+ * manager's environment, not the user's login shell — exports from `.zshrc` / `.profile`
+ * (model API keys picked up by core's env fallback, the PATH the agent shell needs for
+ * user-installed tooling) never reach it. Without this import, the desktop app makes the
+ * user re-enter keys that already work in their terminal, and agent commands run on the
+ * bare system PATH.
+ *
+ * On macOS and Linux, when no terminal launched us (no TERM), the user's shell is run
+ * once as an interactive login shell (`-i -l -c`, so both profile and rc files are read)
+ * around a sentinel-framed `env -0` dump. NUL separation keeps values containing
+ * newlines intact, and the sentinel frame cuts away whatever the rc files print around
+ * it. The result is merged fill-missing-only into `process.env` before anything reads it:
+ * an explicitly provided variable always wins, so a launch from a terminal — where the
+ * import is skipped anyway — and a launch with variables set on the command line behave
+ * exactly as before. The embedded server (and with it the agent shell) inherits
+ * `process.env` at fork time, so the import reaches both without further plumbing.
+ *
+ * Everything but the probe spawn is pure and unit-tests without Electron; the probe is
+ * best-effort with a hard timeout — any failure leaves the environment untouched.
+ * `PENGUIN_NO_LOGIN_SHELL_ENV` (any non-empty value) skips the probe, the escape hatch
+ * for a login shell that cannot run non-interactively within the timeout.
+ */
+import { spawn } from "node:child_process";
+
+/** Frame marker around the probe's `env -0` output; rc-file noise falls outside the frame. */
+const SENTINEL = "__PENGUIN_LOGIN_SHELL_ENV__";
+
+/** The probe: static string, no interpolation, so no quoting hazards in any POSIX-ish shell. */
+const PROBE_COMMAND = `printf '%s' '${SENTINEL}'; env -0; printf '%s' '${SENTINEL}'`;
+
+/** Hard cap on the probe's lifetime; a hung interactive rc file must not stall app startup. */
+export const PROBE_TIMEOUT_MS = 5_000;
+
+/** Cap on collected probe output; an env dump is kilobytes, anything larger is runaway noise. */
+const PROBE_OUTPUT_CAP = 4 * 1024 * 1024;
+
+/**
+ * Keys never imported: shell-position bookkeeping the probe shell wrote for itself
+ * (`_`, `SHLVL`, `PWD`, `OLDPWD`), the probe's own terminal identity (`TERM`), and
+ * `ELECTRON_RUN_AS_NODE` — importing that one would make every later relaunch of the
+ * app run as plain Node instead of Electron.
+ *
+ * `PENGUIN_WEB_DIST` and `PENGUIN_CLI_ENTRY` join them because they select *code*: the
+ * embedded server reads the first for the Web App it serves and the second for the entry it
+ * self-updates through, and the fork does not override either. A profile line written for a
+ * repo checkout would silently retarget an installed app that the user only double-clicked.
+ * Data and settings variables are not excluded — `PENGUIN_HOME` chooses which data root the
+ * app opens, which is a configuration choice a user can mean to make once for both the CLI
+ * and the app.
+ */
+const EXCLUDED_KEYS = new Set([
+ "_",
+ "SHLVL",
+ "PWD",
+ "OLDPWD",
+ "TERM",
+ "ELECTRON_RUN_AS_NODE",
+ "PENGUIN_WEB_DIST",
+ "PENGUIN_CLI_ENTRY",
+]);
+
+/** Environment variable names as the POSIX shells define them; also drops `BASH_FUNC_f%%` exported functions. */
+const KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+/**
+ * Whether this launch should import the login shell environment: never on Windows (GUI
+ * processes inherit the user environment there), never when a terminal launched us
+ * (TERM set — the environment is already the shell's), and never when the escape hatch
+ * `PENGUIN_NO_LOGIN_SHELL_ENV` is set.
+ */
+export function shouldImportLoginShellEnv(opts: {
+ platform: NodeJS.Platform;
+ env: NodeJS.ProcessEnv;
+}): boolean {
+ if (opts.platform === "win32") return false;
+ if (opts.env.TERM !== undefined) return false;
+ if (opts.env.PENGUIN_NO_LOGIN_SHELL_ENV) return false;
+ return true;
+}
+
+/** The shell to probe: the user's `$SHELL` when absolute, else the platform default. */
+export function probeShell(shell: string | undefined, platform: NodeJS.Platform): string {
+ if (shell !== undefined && shell.startsWith("/")) return shell;
+ return platform === "darwin" ? "/bin/zsh" : "/bin/bash";
+}
+
+/**
+ * Extracts the environment record from the probe's stdout: the NUL-separated
+ * `KEY=VALUE` entries between the first sentinel and the next one after it (a zsh
+ * `zlogout` may print after the closing frame, so the close is the *next* occurrence,
+ * not the last). Returns null when the frame is missing or holds no valid entry —
+ * including when `env` does not support `-0` and printed nothing between the frames.
+ */
+export function parseLoginShellEnvDump(stdout: string): Record<string, string> | null {
+ const open = stdout.indexOf(SENTINEL);
+ if (open === -1) return null;
+ const close = stdout.indexOf(SENTINEL, open + SENTINEL.length);
+ if (close === -1) return null;
+ const dump = stdout.slice(open + SENTINEL.length, close);
+ const out: Record<string, string> = {};
+ for (const entry of dump.split("\0")) {
+ if (entry.length === 0) continue;
+ const eq = entry.indexOf("=");
+ if (eq <= 0) continue;
+ const key = entry.slice(0, eq);
+ if (!KEY_PATTERN.test(key)) continue;
+ out[key] = entry.slice(eq + 1);
+ }
+ return Object.keys(out).length > 0 ? out : null;
+}
+
+/**
+ * The patch to apply to `current`: every imported variable `current` leaves unset,
+ * minus `EXCLUDED_KEYS`. PATH is the one merged key — a GUI launch *has* a PATH (the
+ * bare system one), so fill-missing alone would never improve it: the login shell's
+ * entries come first (its ordering wins), current-only entries are appended, duplicates
+ * and empties dropped.
+ */
+export function mergeLoginShellEnv(
+ current: NodeJS.ProcessEnv,
+ imported: Record<string, string>,
+): Record<string, string> {
+ const patch: Record<string, string> = {};
+ for (const [key, value] of Object.entries(imported)) {
+ if (key === "PATH" || EXCLUDED_KEYS.has(key)) continue;
+ if (current[key] !== undefined) continue;
+ patch[key] = value;
+ }
+ const importedPath = imported["PATH"];
+ if (importedPath !== undefined) {
+ const currentPath = current["PATH"];
+ const merged =
+ currentPath === undefined ? importedPath : mergePathValue(importedPath, currentPath);
+ if (merged !== currentPath) patch["PATH"] = merged;
+ }
+ return patch;
+}
+
+/** Login-shell PATH entries first, then current-only ones; deduplicated, empties dropped. */
+function mergePathValue(importedPath: string, currentPath: string): string {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const entry of [...importedPath.split(":"), ...currentPath.split(":")]) {
+ if (entry.length === 0 || seen.has(entry)) continue;
+ seen.add(entry);
+ out.push(entry);
+ }
+ return out.join(":");
+}
+
+/**
+ * Runs the probe and returns the parsed environment, or null on any failure (spawn
+ * error, timeout, output cap, unparseable output). The exit code is deliberately
+ * ignored: login rc files exit non-zero for reasons of their own, and the
+ * sentinel-framed dump is the actual signal.
+ */
+export function resolveLoginShellEnv(opts: {
+ shell: string;
+ env: NodeJS.ProcessEnv;
+ timeoutMs?: number;
+}): Promise<Record<string, string> | null> {
+ return new Promise((resolve) => {
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(opts.shell, ["-i", "-l", "-c", PROBE_COMMAND], {
+ env: opts.env,
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ } catch {
+ resolve(null);
+ return;
+ }
+ let stdout = "";
+ let settled = false;
+ // Settle exactly once, and stop reading. On timeout or cap overrun the promise resolves
+ // immediately after the kill instead of waiting for "close": a hung rc file's own
+ // children inherit the stdout pipe and would hold "close" open for as long as they live
+ // — and would keep feeding the buffer below, so the pipe is dropped here rather than
+ // left collecting output nobody will read.
+ const settle = (value: Record<string, string> | null): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ child.stdout?.destroy();
+ resolve(value);
+ };
+ const timer = setTimeout(() => {
+ child.kill("SIGKILL");
+ settle(null);
+ }, opts.timeoutMs ?? PROBE_TIMEOUT_MS);
+ // Decode across chunk boundaries: the dump arrives in pipe-sized reads that cut wherever
+ // they land, and a per-chunk Buffer -> string would turn every UTF-8 sequence straddling
+ // a boundary into replacement characters (a value with any non-ASCII in it, in an
+ // environment large enough to need a second read).
+ child.stdout?.setEncoding("utf8");
+ child.stdout?.on("data", (chunk: string) => {
+ stdout += chunk;
+ if (stdout.length > PROBE_OUTPUT_CAP) {
+ child.kill("SIGKILL");
+ settle(null);
+ }
+ });
+ child.on("error", () => settle(null));
+ child.on("close", () => settle(parseLoginShellEnvDump(stdout)));
+ });
+}
+
+/**
+ * Entry point for the shell's boot path: probes when `shouldImportLoginShellEnv` says
+ * to, merges fill-missing into `opts.env` (normally `process.env`), and returns the
+ * number of variables applied. Best-effort: every failure path logs one line and
+ * returns 0 with the environment untouched.
+ */
+export async function applyLoginShellEnv(opts: {
+ platform: NodeJS.Platform;
+ env: NodeJS.ProcessEnv;
+ shell: string | undefined;
+ timeoutMs?: number;
+ log: (line: string) => void;
+}): Promise<number> {
+ if (!shouldImportLoginShellEnv(opts)) return 0;
+ const shell = probeShell(opts.shell, opts.platform);
+ const resolved = await resolveLoginShellEnv({
+ shell,
+ env: opts.env,
+ ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),
+ });
+ if (resolved === null) {
+ opts.log(`login shell environment unavailable (${shell}); continuing without it`);
+ return 0;
+ }
+ const patch = mergeLoginShellEnv(opts.env, resolved);
+ Object.assign(opts.env, patch);
+ const count = Object.keys(patch).length;
+ if (count > 0) {
+ opts.log(`imported ${count} environment variable(s) from the login shell (${shell})`);
+ }
+ return count;
+}
diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts
index 4b05749a..7a6830cc 100644
--- a/packages/desktop/src/main.ts
+++ b/packages/desktop/src/main.ts
@@ -35,6 +35,7 @@ import { liveServerLock } from "@prismshadow/penguin-server/lock";
import { appIdentity, desktopDataRoot } from "./app-identity.js";
import { resolveWindowIcon } from "./app-icon.js";
import { installCliCommand, maybeOfferCliInstall, currentCliInstallKind } from "./cli-install.js";
+import { applyLoginShellEnv } from "./login-shell-env.js";
import { installAppMenu } from "./menu.js";
import { startEmbeddedServer, stopEmbeddedServer } from "./server-process.js";
import type { EmbeddedServer } from "./server-process.js";
@@ -249,6 +250,16 @@ if (!app.requestSingleInstanceLock()) {
void app.whenReady().then(() =>
(async () => {
+ // GUI launches on macOS/Linux miss the login shell's exports (model API keys for
+ // core's env fallback, the PATH the agent shell needs). Import them fill-missing
+ // before anything reads process.env — boot() resolves PENGUIN_HOME from it, and
+ // the forked server inherits it (#351).
+ await applyLoginShellEnv({
+ platform: process.platform,
+ env: process.env,
+ shell: process.env.SHELL,
+ log: (line) => process.stdout.write(`[shell] ${line}\n`),
+ });
// Standard menu plus native desktop-only actions; the window gets no IPC channel.
installAppMenu({
includeCliInstall: currentCliInstallKind() !== null,
diff --git a/packages/desktop/test/login-shell-env.test.ts b/packages/desktop/test/login-shell-env.test.ts
new file mode 100644
index 00000000..938bdd1a
--- /dev/null
+++ b/packages/desktop/test/login-shell-env.test.ts
@@ -0,0 +1,237 @@
+/**
+ * Login-shell environment import (#351): the pure parts (launch gate, dump parsing,
+ * fill-missing merge) everywhere, and the probe orchestration against fake shell
+ * scripts where a POSIX /bin/sh exists (skipped on Windows, where the import never
+ * runs anyway).
+ */
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import {
+ applyLoginShellEnv,
+ mergeLoginShellEnv,
+ parseLoginShellEnvDump,
+ probeShell,
+ resolveLoginShellEnv,
+ shouldImportLoginShellEnv,
+} from "../src/login-shell-env.js";
+
+const SENTINEL = "__PENGUIN_LOGIN_SHELL_ENV__";
+
+describe("shouldImportLoginShellEnv", () => {
+ it("imports only on a GUI launch of a POSIX platform", () => {
+ expect(shouldImportLoginShellEnv({ platform: "darwin", env: {} })).toBe(true);
+ expect(shouldImportLoginShellEnv({ platform: "linux", env: {} })).toBe(true);
+ expect(shouldImportLoginShellEnv({ platform: "win32", env: {} })).toBe(false);
+ });
+
+ it("skips a terminal launch (TERM set) — that environment is already the shell's", () => {
+ expect(shouldImportLoginShellEnv({ platform: "darwin", env: { TERM: "xterm-256color" } })).toBe(
+ false,
+ );
+ });
+
+ it("honors the PENGUIN_NO_LOGIN_SHELL_ENV escape hatch", () => {
+ expect(
+ shouldImportLoginShellEnv({ platform: "linux", env: { PENGUIN_NO_LOGIN_SHELL_ENV: "1" } }),
+ ).toBe(false);
+ });
+});
+
+describe("probeShell", () => {
+ it("uses an absolute $SHELL and falls back per platform otherwise", () => {
+ expect(probeShell("/usr/local/bin/fish", "linux")).toBe("/usr/local/bin/fish");
+ expect(probeShell(undefined, "darwin")).toBe("/bin/zsh");
+ expect(probeShell(undefined, "linux")).toBe("/bin/bash");
+ expect(probeShell("zsh", "linux")).toBe("/bin/bash");
+ });
+});
+
+describe("parseLoginShellEnvDump", () => {
+ const frame = (dump: string): string => `${SENTINEL}${dump}${SENTINEL}`;
+
+ it("parses NUL-separated entries, keeping values that contain newlines", () => {
+ const parsed = parseLoginShellEnvDump(frame("A=1\0MULTI=line1\nline2\0PATH=/usr/bin:/bin\0"));
+ expect(parsed).toEqual({ A: "1", MULTI: "line1\nline2", PATH: "/usr/bin:/bin" });
+ });
+
+ it("ignores rc-file noise outside the frame, including output after the close", () => {
+ const parsed = parseLoginShellEnvDump(`motd banner\n${frame("KEY=value\0")}\nzlogout says bye`);
+ expect(parsed).toEqual({ KEY: "value" });
+ });
+
+ it("closes the frame at the next sentinel, not the last one", () => {
+ // A zlogout that echoes the sentinel again must not extend the frame.
+ const parsed = parseLoginShellEnvDump(`${frame("K=v\0")}noise ${SENTINEL}`);
+ expect(parsed).toEqual({ K: "v" });
+ });
+
+ it("drops malformed entries and non-POSIX names (exported bash functions)", () => {
+ const parsed = parseLoginShellEnvDump(
+ frame("=nokey\0noequals\0BASH_FUNC_f%%=() { :; }\0OK=1\0"),
+ );
+ expect(parsed).toEqual({ OK: "1" });
+ });
+
+ it("returns null without a frame or without a single valid entry", () => {
+ expect(parseLoginShellEnvDump("no sentinels at all")).toBeNull();
+ expect(parseLoginShellEnvDump(`${SENTINEL}unclosed`)).toBeNull();
+ // `env` without -0 support prints nothing between the frames.
+ expect(parseLoginShellEnvDump(frame(""))).toBeNull();
+ });
+});
+
+describe("mergeLoginShellEnv", () => {
+ it("fills only variables the current environment leaves unset", () => {
+ const patch = mergeLoginShellEnv(
+ { PRESENT: "keep" },
+ { PRESENT: "ignored", ANTHROPIC_API_KEY: "sk-from-zshrc" },
+ );
+ expect(patch).toEqual({ ANTHROPIC_API_KEY: "sk-from-zshrc" });
+ });
+
+ it("never imports the excluded bookkeeping keys", () => {
+ const patch = mergeLoginShellEnv(
+ {},
+ {
+ _: "/usr/bin/env",
+ SHLVL: "2",
+ PWD: "/home/user",
+ OLDPWD: "/",
+ TERM: "dumb",
+ ELECTRON_RUN_AS_NODE: "1",
+ KEEP: "yes",
+ },
+ );
+ expect(patch).toEqual({ KEEP: "yes" });
+ });
+
+ it("never imports the variables that pick which code the embedded server runs", () => {
+ const patch = mergeLoginShellEnv(
+ {},
+ {
+ PENGUIN_WEB_DIST: "/home/user/src/penguin-harness/packages/web/dist",
+ PENGUIN_CLI_ENTRY: "/home/user/src/penguin-harness/packages/cli/dist/penguin.js",
+ // Data root, by contrast, is a configuration choice and does travel.
+ PENGUIN_HOME: "/home/user/.penguin",
+ },
+ );
+ expect(patch).toEqual({ PENGUIN_HOME: "/home/user/.penguin" });
+ });
+
+ it("merges PATH with the login shell's ordering first and current-only entries appended", () => {
+ const patch = mergeLoginShellEnv(
+ { PATH: "/usr/bin:/bin:/only/current" },
+ { PATH: "/home/user/.local/bin:/usr/bin:/bin" },
+ );
+ expect(patch["PATH"]).toBe("/home/user/.local/bin:/usr/bin:/bin:/only/current");
+ });
+
+ it("adopts the imported PATH outright when none is set, and leaves an equal PATH alone", () => {
+ expect(mergeLoginShellEnv({}, { PATH: "/a:/b" })).toEqual({ PATH: "/a:/b" });
+ expect(mergeLoginShellEnv({ PATH: "/a:/b" }, { PATH: "/a:/b" })).toEqual({});
+ });
+});
+
+describe.skipIf(process.platform === "win32")("resolveLoginShellEnv (fake shells)", () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "penguin-login-shell-"));
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+ function fakeShell(name: string, script: string): string {
+ const file = path.join(dir, name);
+ writeFileSync(file, `#!/bin/sh\n${script}\n`);
+ chmodSync(file, 0o755);
+ return file;
+ }
+
+ it("returns the parsed environment from a well-behaved shell", async () => {
+ const shell = fakeShell(
+ "good.sh",
+ `printf '%s' '${SENTINEL}'; printf 'FROM_LOGIN=1\\0MULTI=a\\nb\\0'; printf '%s' '${SENTINEL}'`,
+ );
+ const resolved = await resolveLoginShellEnv({ shell, env: {} });
+ expect(resolved).toEqual({ FROM_LOGIN: "1", MULTI: "a\nb" });
+ });
+
+ it("keeps a value whose UTF-8 bytes straddle a read boundary", async () => {
+ // One write larger than the pipe buffer, so the reader takes it in several chunks that
+ // cut wherever they land: decoding chunk by chunk would corrupt the characters spanning
+ // a cut. Built in the shell — an argument this size does not survive exec.
+ const shell = fakeShell(
+ "wide.sh",
+ [
+ `big=$(i=0; while [ $i -lt 5000 ]; do printf '中中中中中中中中中中'; i=$((i+1)); done)`,
+ `printf '%s' '${SENTINEL}'`,
+ `printf 'WIDE=%s\\0' "$big"`,
+ `printf '%s' '${SENTINEL}'`,
+ ].join("\n"),
+ );
+ const resolved = await resolveLoginShellEnv({ shell, env: {} });
+ expect(resolved?.["WIDE"]).toBe("中".repeat(50_000));
+ });
+
+ it("accepts a dump despite a non-zero exit code", async () => {
+ const shell = fakeShell(
+ "grumpy.sh",
+ `printf '%s' '${SENTINEL}'; printf 'OK=1\\0'; printf '%s' '${SENTINEL}'; exit 3`,
+ );
+ const resolved = await resolveLoginShellEnv({ shell, env: {} });
+ expect(resolved).toEqual({ OK: "1" });
+ });
+
+ it("returns null for output without a frame", async () => {
+ const shell = fakeShell("garbage.sh", `echo 'not an env dump'`);
+ await expect(resolveLoginShellEnv({ shell, env: {} })).resolves.toBeNull();
+ });
+
+ it("returns null when the shell hangs past the timeout", async () => {
+ const shell = fakeShell("hang.sh", "sleep 30");
+ const started = Date.now();
+ const resolved = await resolveLoginShellEnv({ shell, env: process.env, timeoutMs: 300 });
+ expect(resolved).toBeNull();
+ expect(Date.now() - started).toBeLessThan(5_000);
+ });
+
+ it("returns null when the shell cannot be spawned at all", async () => {
+ const resolved = await resolveLoginShellEnv({
+ shell: path.join(dir, "does-not-exist"),
+ env: {},
+ });
+ expect(resolved).toBeNull();
+ });
+
+ it("applyLoginShellEnv merges into the given env and reports the count", async () => {
+ const shell = fakeShell(
+ "apply.sh",
+ `printf '%s' '${SENTINEL}'; printf 'NEW_KEY=v\\0PRESENT=other\\0'; printf '%s' '${SENTINEL}'`,
+ );
+ const env: NodeJS.ProcessEnv = { SHELL: shell, PRESENT: "keep" };
+ const lines: string[] = [];
+ const count = await applyLoginShellEnv({
+ platform: "linux",
+ env,
+ shell,
+ log: (line) => lines.push(line),
+ });
+ expect(count).toBe(1);
+ expect(env.NEW_KEY).toBe("v");
+ expect(env.PRESENT).toBe("keep");
+ expect(lines.some((l) => l.includes("imported 1 environment variable"))).toBe(true);
+ });
+
+ it("applyLoginShellEnv is a no-op with a log line when the probe fails", async () => {
+ const shell = fakeShell("fail.sh", "exit 1");
+ const env: NodeJS.ProcessEnv = {};
+ const lines: string[] = [];
+ const count = await applyLoginShellEnv({
+ platform: "linux",
+ env,
+ shell,
+ log: (line) => lines.push(line),
+ });
+ expect(count).toBe(0);
+ expect(env).toEqual({});
+ expect(lines.some((l) => l.includes("unavailable"))).toBe(true);
+ });
+});
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index 34bc1b61..d8a183ef 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -20,6 +20,7 @@ The CLI and the server automatically load a `.env` file from the working directo
| `PENGUIN_SEED_ADMIN_PASSWORD` | Fixed initial password for the seeded built-in admin (automated tests / e2e) | unset — a random `penguin-<4 digits>` password is generated and printed once at seed time |
| `PENGUIN_LANG` | CLI language (`en` / `zh`), set via `penguin config lang` | `en` |
| `PENGUIN_UPDATE_CHECK` | `off` disables the web app's new-release check (the server's only outbound internet call) | enabled |
+| `PENGUIN_NO_LOGIN_SHELL_ENV` | Any non-empty value stops the desktop app from importing the login shell's environment on macOS/Linux GUI launches (see [Desktop quickstart](/quickstart-desktop)) | unset — the import runs, filling only variables the launch left unset |
These configure PenguinHarness itself, so `PORT`, `HOST`, `PENGUIN_WEB_DIST` and the internal `PENGUIN_CLI_ENTRY` are **removed from the environment of commands the Agent runs** — otherwise a dev server started by `exec_command` would read `PORT` and try to bind the port meant for PenguinHarness instead of choosing its own. The rest of the host environment passes through, with one further exception: `GIT_EDITOR`, `GIT_TERMINAL_PROMPT`, `TERM`, `NO_COLOR`, `PAGER` and `GIT_PAGER` are always forced to fixed values, so that a command cannot hang waiting on an editor, a credential prompt or a pager. The Agent's [vault](#vault) is applied on top of the host environment — setting `PORT` there does reach commands — but not on top of those six.
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index 5450fb8a..e724ac34 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -20,6 +20,7 @@ CLI 与服务端启动时会自动加载工作目录下的 `.env` 文件。
| `PENGUIN_SEED_ADMIN_PASSWORD` | 固定内置管理员的种子初始密码(自动化测试 / e2e 使用) | 未设置,种子时随机生成 `penguin-<四位数字>` 并打印一次 |
| `PENGUIN_LANG` | CLI 语言(`en` / `zh`),用 `penguin config lang` 设置 | `en` |
| `PENGUIN_UPDATE_CHECK` | 设为 `off` 关闭 Web 应用的新版本检查(服务端唯一的对外网络请求) | 开启 |
+| `PENGUIN_NO_LOGIN_SHELL_ENV` | 任意非空值可禁止桌面版在 macOS/Linux 图形界面启动时导入登录 shell 环境变量(见[桌面版速上手](/quickstart-desktop)) | 未设置,导入开启,且只补启动环境中缺失的变量 |
这些变量配置的是 PenguinHarness 自身,因此 `PORT`、`HOST`、`PENGUIN_WEB_DIST` 以及内部使用的 `PENGUIN_CLI_ENTRY` **不会出现在 Agent 所执行命令的环境变量中**——否则 `exec_command` 启动的开发服务器会读到 `PORT`,去占用留给 PenguinHarness 的端口,而不是自己另选一个。宿主环境中的其余变量原样透传,但还有一处例外:`GIT_EDITOR`、`GIT_TERMINAL_PROMPT`、`TERM`、`NO_COLOR`、`PAGER`、`GIT_PAGER` 一律被固定值覆盖,以免命令因等待编辑器、凭证输入或分页器而挂起。Agent 的 [vault](#vault) 覆盖在宿主环境之上——在 vault 里设置 `PORT` 仍然可以送达命令——但覆盖不了这六个变量。
diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.md
index fa43bb5c..fd343107 100644
--- a/packages/docs/content/quickstart-desktop.en.md
+++ b/packages/docs/content/quickstart-desktop.en.md
@@ -37,6 +37,8 @@ Get the installer for your platform from the [download page](https://penguin.ooo
Open the app, go to the **Models** page in the sidebar, click "Add model" and fill in the Provider, model id and API key, then set it as the default.
+API keys already exported in your shell profile (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, …) work without re-entering them: on macOS and Linux the app imports the login shell's environment when launched from the Dock or desktop, filling only variables the launch itself did not set (the agent shell's `PATH` benefits the same way; set `PENGUIN_NO_LOGIN_SHELL_ENV` to opt out). For an official-provider model without a stored key, the Models page shows the detected variable's value masked, exactly as a stored key is shown: on the card, and in the model's dialog, which marks it as read from an environment variable (gateway and custom groups are not matched against these variables).
+
A model is always referenced as a `(provider, model_id)` pair — the Provider is never inferred from the model id. See [Models & Providers](/models) for the built-in groups.
## Run your first Task
diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.md
index f96c758a..1ebe738b 100644
--- a/packages/docs/content/quickstart-desktop.zh.md
+++ b/packages/docs/content/quickstart-desktop.zh.md
@@ -37,6 +37,8 @@ description: 双击安装,打开即已登录——对终端要求最少的那
打开应用,在左侧进入**模型**页,点「添加模型」填入 Provider、模型 id 与 API key,保存后设为默认模型。
+已在 shell 配置里 export 过的 API key(`ANTHROPIC_API_KEY`、`OPENAI_API_KEY` 等)无需重复填写:macOS 与 Linux 上从 Dock / 桌面启动时,应用会导入登录 shell 的环境变量,且只补启动环境中缺失的项(agent shell 的 `PATH` 同样受益;设置 `PENGUIN_NO_LOGIN_SHELL_ENV` 可关闭导入)。未配置存储 key 的官方供应商模型,**模型**页会像显示存储 key 一样,以掩码显示检测到的变量取值:卡片上如此,模型详情里也一样,并注明该 key 读取自环境变量(网关与自定义分组不匹配这些变量)。
+
模型引用始终是 `(provider, model_id)` 二元组,Provider 绝不由模型 id 推断;内置分组见[模型与 Provider](/models)。
## 跑通第一个 Task
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 829a4690..b4b27c66 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -376,6 +376,14 @@ export interface ModelInfo {
pricing?: ModelPricingDto;
/** Environment variable name to fall back to when api_key is empty (e.g. ANTHROPIC_API_KEY); unset if no known fallback. */
envKey?: string;
+ /**
+ * Masked preview (same rule as `credential.apiKeyMasked`) of the value the server process
+ * currently holds for `envKey` — the plaintext is never serialized. Reported only for
+ * first-party official entries (vendor group, catalog shape unmodified); gateway, custom
+ * and user-defined groups never carry it. Absent = the variable is unset or empty, or the
+ * entry is not first-party.
+ */
+ envKeyMasked?: string;
credential?: CredentialInfo;
isDefault: boolean;
}
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index 991e6962..7c4263b1 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -41,6 +41,7 @@ import {
resolveModelEnv,
userText,
} from "@prismshadow/penguin-core";
+import { providerInfo } from "@prismshadow/penguin-core/model-catalog";
import type { LLMOutcome, ModelRef, OmniMessage, ProjectConfig } from "@prismshadow/penguin-core";
import type {
ChatDefaultsDto,
@@ -84,6 +85,42 @@ export function maskApiKey(key: string): string {
return `${key.slice(0, 4)}…${key.slice(-4)}`;
}
+/**
+ * Whether a model's env fallback is *first-party*: the entry points at the provider's own
+ * official endpoint, so consulting the vendor variable (ANTHROPIC_API_KEY, …) is the intended
+ * configuration and its value may be previewed masked. Excluded — no detection, no preview:
+ *
+ * - gateway groups (they resell through generic OpenAI-protocol clients whose fallback is
+ * OPENAI_API_KEY, the *official OpenAI* variable; steering it to a reseller endpoint is
+ * exactly the misconfiguration the preview must not encourage) and the custom group;
+ * - user-defined groups (not in MODEL_PROVIDERS at all);
+ * - any entry re-pointed away from the official shape: a catalog preset whose client_type or
+ * base_url differs from the catalog's own values, or an off-catalog vendor-group entry that
+ * pins either (a bare auto-routed id targets the vendor's first-party client and stays in).
+ *
+ * `envKey` itself is still reported for every routable entry — this gate governs only the
+ * presence preview.
+ */
+export function envFallbackFirstParty(entry: {
+ provider: string;
+ modelId: string;
+ clientType: string | undefined;
+ baseUrl: string | undefined;
+}): boolean {
+ const group = providerInfo(entry.provider);
+ if (group === undefined || group.id === "custom" || group.gatewayBaseUrl !== undefined) {
+ return false;
+ }
+ const cat = catalogEntryFor(entry.provider, entry.modelId);
+ if (cat !== undefined) {
+ return (
+ canonicalClientType(entry.clientType) === canonicalClientType(cat.clientType) &&
+ entry.baseUrl === cat.baseUrl
+ );
+ }
+ return entry.clientType === undefined && entry.baseUrl === undefined;
+}
+
function asTable(v: unknown): RawTable {
return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as RawTable) : {};
}
@@ -694,6 +731,17 @@ export class ProjectConfigService {
const apiKey = optStr(m.api_key);
const credBaseUrl = optStr(m.base_url);
const createdAt = optStr(m.created_at);
+ // Masked env-fallback preview, first-party entries only (see envFallbackFirstParty):
+ // presence is implied by the field, the plaintext never leaves the server, and an
+ // empty variable counts as absent — it would not authenticate either. Read from this
+ // process's env, which on the desktop already includes the imported login-shell
+ // variables.
+ const envValue =
+ envKey !== undefined &&
+ envFallbackFirstParty({ provider, modelId, clientType, baseUrl: credBaseUrl })
+ ? (process.env[envKey] ?? "")
+ : "";
+ const envKeyMasked = envValue !== "" ? maskApiKey(envValue) : undefined;
const info: ModelInfo = {
provider,
modelId,
@@ -710,6 +758,7 @@ export class ProjectConfigService {
...(maxTokens !== undefined ? { maxTokens } : {}),
...(fastMode !== undefined ? { fastMode } : {}),
...(envKey ? { envKey } : {}),
+ ...(envKeyMasked !== undefined ? { envKeyMasked } : {}),
...(pricingDto ? { pricing: pricingDto } : {}),
...(apiKey !== undefined || credBaseUrl !== undefined
? {
diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.ts
index 49c1c615..47fb5d99 100644
--- a/packages/server/test/models.test.ts
+++ b/packages/server/test/models.test.ts
@@ -125,6 +125,69 @@ describe("models preset & catalog enrichment", () => {
expect(mimo.credential?.apiKeyMasked).toBeUndefined();
});
+ it("masks the env fallback for first-party official entries only, and never leaks the value", async () => {
+ const saved = {
+ anthropic: process.env.ANTHROPIC_API_KEY,
+ deepseek: process.env.DEEPSEEK_API_KEY,
+ openai: process.env.OPENAI_API_KEY,
+ };
+ const anthropicValue = "sk-ant-test-secret-value-123456";
+ const openaiValue = "sk-openai-test-secret-value-789";
+ process.env.ANTHROPIC_API_KEY = anthropicValue;
+ process.env.OPENAI_API_KEY = openaiValue;
+ // Empty counts as absent — it would not authenticate either.
+ process.env.DEEPSEEK_API_KEY = "";
+ try {
+ const put = await api.put(url(), {
+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },
+ models: [
+ // First-party catalog preset, variable set: masked preview.
+ { provider: "anthropic", modelId: "claude-sonnet-4-6" },
+ // First-party catalog preset, variable empty: no preview.
+ { provider: "deepseek", modelId: "deepseek-v4-pro" },
+ // Off-catalog id in a vendor group, pure auto-route: still first-party.
+ { provider: "anthropic", modelId: "claude-sonnet-4-6-preview" },
+ // Vendor group re-pointed at a generic protocol: not first-party.
+ { provider: "anthropic", modelId: "claude-via-gateway", clientType: "openai" },
+ // Gateway and custom groups never carry a preview, even with OPENAI_API_KEY set.
+ {
+ provider: "openrouter",
+ modelId: "xiaomi/mimo-v2.5",
+ clientType: "openai-chat",
+ baseUrl: "https://openrouter.ai/api/v1",
+ },
+ { provider: "custom", modelId: "my-model", clientType: "openai" },
+ ],
+ });
+ expect(put.status).toBe(200);
+ // The masked preview follows maskApiKey; the plaintext must never be serialized.
+ const text = await put.text();
+ expect(text).not.toContain(anthropicValue);
+ expect(text).not.toContain(openaiValue);
+ const body = JSON.parse(text) as ModelsResponse;
+ const masked = `${anthropicValue.slice(0, 4)}…${anthropicValue.slice(-4)}`;
+ expect(pick(body, "anthropic", "claude-sonnet-4-6").envKeyMasked).toBe(masked);
+ expect(pick(body, "anthropic", "claude-sonnet-4-6-preview").envKeyMasked).toBe(masked);
+ expect(pick(body, "deepseek", "deepseek-v4-pro").envKeyMasked).toBeUndefined();
+ const rePointed = pick(body, "anthropic", "claude-via-gateway");
+ expect(rePointed.envKey).toBe("OPENAI_API_KEY");
+ expect(rePointed.envKeyMasked).toBeUndefined();
+ const gateway = pick(body, "openrouter", "xiaomi/mimo-v2.5");
+ expect(gateway.envKey).toBe("OPENAI_API_KEY");
+ expect(gateway.envKeyMasked).toBeUndefined();
+ expect(pick(body, "custom", "my-model").envKeyMasked).toBeUndefined();
+ } finally {
+ for (const [key, value] of [
+ ["ANTHROPIC_API_KEY", saved.anthropic],
+ ["DEEPSEEK_API_KEY", saved.deepseek],
+ ["OPENAI_API_KEY", saved.openai],
+ ] as const) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ }
+ });
+
it("PUT a custom model: the vision flag persists; the openai protocol falls back to OPENAI_API_KEY; provider is required", async () => {
const put = await api.put(url(), {
defaultModel: { provider: "custom", modelId: "my-model" },
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index 043f5f12..668e7ae4 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -229,6 +229,8 @@ export interface RowState {
vision: boolean;
/** Environment variable name used as fallback when api_key is empty (given by the server based on catalog/protocol). */
envKey?: string;
+ /** Masked preview of the env-fallback value (first-party official entries only; the plaintext never leaves the server). */
+ envKeyMasked?: string;
contextWindow: string;
/** Per-model max output tokens ("" = inherit the Agent setting): caps output per request; user-only, never preset by the catalog. */
maxTokens: string;
@@ -347,10 +349,27 @@ export function toRow(m: ModelsResponse["models"][number]): RowState {
};
if (m.displayName !== undefined) row.displayName = m.displayName;
if (m.envKey !== undefined) row.envKey = m.envKey;
+ if (m.envKeyMasked !== undefined) row.envKeyMasked = m.envKeyMasked;
if (m.credential) row.credential = m.credential;
return row;
}
+/**
+ * The env-fallback variables the server proved are set (exported for unit tests): it reports
+ * `envKeyMasked` only for a variable that currently holds a value, and an environment is
+ * process-wide, so one row carrying it settles the question for every entry reading the same
+ * variable. A hint may promise "leave this empty and the environment covers it" only for a
+ * variable in here — elsewhere the page cannot tell a set variable from an absent one, and an
+ * empty field would leave the model with no key at all.
+ */
+export function detectedEnvKeys(rows: readonly RowState[]): Set<string> {
+ const keys = new Set<string>();
+ for (const row of rows) {
+ if (row.envKeyMasked !== undefined && row.envKey !== undefined) keys.add(row.envKey);
+ }
+ return keys;
+}
+
/**
* Whether the model dialog offers the fast-mode switch for a draft row, and on which protocol
* the parameter would travel.
@@ -564,6 +583,8 @@ export function ModelsPage() {
};
const groups = useMemo(() => (rows ? groupModelRows(rows, query) : []), [rows, query]);
+ /** Env-fallback variables the server reported a value for: the only ones a key hint may promise. */
+ const envKeysDetected = useMemo(() => detectedEnvKeys(rows ?? []), [rows]);
/** Non-empty search query: groups are filtered to matches and force-opened while it lasts. */
const searching = query.trim() !== "";
@@ -920,6 +941,7 @@ export function ModelsPage() {
MODEL_PROVIDERS.find((p) => p.id === groupKeyFor) ?? userProviderInfo(groupKeyFor)
}
count={rows.filter((r) => r.provider === groupKeyFor).length}
+ detectedEnvKeys={envKeysDetected}
onClose={() => setGroupKeyFor(null)}
onSubmit={(key) => {
const target = groupKeyFor;
@@ -1012,6 +1034,7 @@ export function ModelsPage() {
row={addingTo !== null ? null : (editingRow ?? null)}
addProvider={addingTo ?? "custom"}
existingRefs={rows.map(rowRef)}
+ detectedEnvKeys={envKeysDetected}
currency={currency}
canEdit={isOwner}
isDefault={editingRow !== undefined && sameModelRef(rowRef(editingRow), defaultModel)}
@@ -1393,12 +1416,15 @@ function ModelCard({
priced
? `${displayPrice(row.cacheRead, currency)} / ${displayPrice(row.cacheWrite, currency)} / ${displayPrice(row.output, currency)}`
: null,
- // Key status: shows the mask when configured, otherwise "not configured" (doesn't mention environment variables).
+ // 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
- : S.models.noKey,
+ : (row.envKeyMasked ?? S.models.noKey),
].filter((v): v is string => v !== null);
const speedBadges =
@@ -1500,6 +1526,7 @@ function ModelDialog({
row,
addProvider,
existingRefs,
+ detectedEnvKeys,
currency,
canEdit,
isDefault,
@@ -1512,6 +1539,8 @@ function ModelDialog({
/** Target group for add mode (row is null): the group of the header entry point / falls back to custom when empty. */
addProvider: string;
existingRefs: ModelRefDto[];
+ /** Env-fallback variables the server reported a value for (see detectedEnvKeys): the only ones the key hint may promise. */
+ detectedEnvKeys: ReadonlySet<string>;
currency: Currency;
canEdit: boolean;
isDefault: boolean;
@@ -2079,21 +2108,30 @@ function ModelDialog({
</>
);
- // Hint for a blank API key: an existing key means keep the original value;
- // no existing key but an env var fallback exists means use the env var
- // (the fallback name resolves live, so it updates as the id / protocol is edited).
+ // The variable a blank API key would actually be covered by: no stored key, the entry
+ // routes to a variable (resolved live, so it follows the id / protocol as they are
+ // edited), and that variable is one the server reported a value for. Knowing a variable's
+ // *name* is not knowing it is set — promising an unset one would tell the user to leave
+ // the field empty and leave the model with no key at all.
+ const envHintKey =
+ !form.credential?.apiKeyMasked && liveEnvKey !== undefined && detectedEnvKeys.has(liveEnvKey)
+ ? liveEnvKey
+ : undefined;
+ // Hint for a blank API key: an existing key means keep the original value; a covered
+ // variable means the environment answers for it; neither means there is nothing truthful
+ // to say, so the field carries no placeholder.
const apiKeyHint = form.credential?.apiKeyMasked
? S.models.apiKeyKeepHint
- : liveEnvKey
- ? S.models.apiKeyEnvHint(liveEnvKey)
- : S.models.apiKeyKeepHint;
+ : envHintKey !== undefined
+ ? S.models.apiKeyEnvHint(envHintKey)
+ : undefined;
// Default endpoint note (zhipu / moonshot each have domestic / international
- // endpoints): shown only when the env fallback hint appears (no existing key)
- // and this entry actually goes through the provider's own client (the
+ // endpoints): shown only when the env fallback hint appears (hence keyed off the same
+ // envHintKey) and this entry actually goes through the provider's own client (the
// resolved envKey matches the provider) — entries going through the OpenAI
// client (OPENAI_API_KEY) have no provider default endpoint to speak of.
const envNote =
- !form.credential?.apiKeyMasked && liveEnvKey && liveEnvKey === dialogProvider?.envKey
+ envHintKey !== undefined && envHintKey === dialogProvider?.envKey
? S.models.providerEnvNotes[form.provider]
: undefined;
@@ -2299,6 +2337,17 @@ function ModelDialog({
)}
</div>
)}
+ {/* Detected first-party env fallback, shown like a stored key (same slot, same mask
+ rule): the created-at position says where the key comes from instead, and there is
+ no clear control — an environment variable cannot be cleared from here. Typing a new
+ key hides this like the stored block; once saved, the stored key takes priority and
+ the display switches to the stored form. */}
+ {!form.credential?.apiKeyMasked && form.envKeyMasked !== undefined && !form.apiKeyInput && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
+ <span className="font-mono">{form.envKeyMasked}</span>
+ <span className="text-gray-400">{S.models.readFromEnv}</span>
+ </div>
+ )}
{/* 2) base URL (required for custom / user-defined groups and explicit openai protocol — see
baseUrlRequired). The in-field suffix at the right edge shows the protocol path the
@@ -2694,11 +2743,14 @@ function ModelDialog({
function GroupKeyDialog({
provider,
count,
+ detectedEnvKeys,
onClose,
onSubmit,
}: {
provider: ModelProviderInfo;
count: number;
+ /** Env-fallback variables the server reported a value for (see detectedEnvKeys). */
+ detectedEnvKeys: ReadonlySet<string>;
onClose: () => void;
onSubmit: (apiKey: string) => void;
}) {
@@ -2728,7 +2780,13 @@ function GroupKeyDialog({
className="font-mono"
autoComplete="off"
autoFocus
- placeholder={S.models.apiKeyEnvHint(provider.envKey)}
+ // Only promise the variable when the server reported a value for it: the group's
+ // variable name is always known, which says nothing about whether it is set.
+ placeholder={
+ detectedEnvKeys.has(provider.envKey)
+ ? S.models.apiKeyEnvHint(provider.envKey)
+ : undefined
+ }
/>
<p className="text-xs text-gray-500 dark:text-gray-400">
{S.models.groupApiKeyHint(count)}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 10c21a69..058c0581 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -707,6 +707,7 @@ export const en: Strings = {
readOnlyHint: "Members have read-only access; only owners can change models and credentials",
empty: "No models configured yet",
noKey: "No key",
+ readFromEnv: "Read from environment variable",
showModelsWithoutKey: (n: number): string =>
`Show model${n === 1 ? "" : "s"} without a key (${n})`,
modelIdExists: "This model id already exists",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 6f80ec0f..b71f48ad 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -685,6 +685,12 @@ export const zh = {
readOnlyHint: "member 只读;模型与 credential 修改仅 owner 可执行",
empty: "尚未配置任何模型",
noKey: "未配置 key",
+ /**
+ * Model dialog credential slot: sits where a stored key shows its created-at line. It
+ * names no variable — the slot next to it already shows that variable's value masked,
+ * which is what identifies the key to the reader.
+ */
+ readFromEnv: "读取自环境变量",
/** Chat model dropdown's bottom expander row: reveals the models hidden by the configured-key filter. */
showModelsWithoutKey: (n: number): string => `显示未配置 key 的模型(${n} 个)`,
modelIdExists: "该模型 id 已存在",
diff --git a/packages/web/test/models-input.test.ts b/packages/web/test/models-input.test.ts
index 938839eb..2c03dd78 100644
--- a/packages/web/test/models-input.test.ts
+++ b/packages/web/test/models-input.test.ts
@@ -9,12 +9,15 @@
* - Ownership of the default/vision-agent model pointers after save
* (nextPointers): always compared as pairs; renaming (either provider or
* 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.
*/
import { describe, expect, it } from "vitest";
import {
capabilityRow,
clientTypeAfterProviderChange,
decimalOnly,
+ detectedEnvKeys,
digitsOnly,
fastModeState,
nextPointers,
@@ -44,6 +47,31 @@ describe("decimalOnly (price)", () => {
});
});
+describe("detectedEnvKeys (variables a key hint may promise)", () => {
+ it("collects the variables the server reported a value for, and only those", () => {
+ const rows = [
+ toRow({
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ envKey: "ANTHROPIC_API_KEY",
+ envKeyMasked: "sk-a…3456",
+ isDefault: false,
+ }),
+ // Variable name known, no value reported: nothing here proves it is set, so a hint
+ // must not tell the user that leaving the key empty is covered.
+ toRow({
+ provider: "deepseek",
+ modelId: "deepseek-v4-pro",
+ envKey: "DEEPSEEK_API_KEY",
+ isDefault: false,
+ }),
+ toRow({ provider: "custom", modelId: "my-model", isDefault: false }),
+ ];
+ expect(detectedEnvKeys(rows)).toEqual(new Set(["ANTHROPIC_API_KEY"]));
+ expect(detectedEnvKeys([])).toEqual(new Set());
+ });
+});
+
describe("clientTypeAfterProviderChange", () => {
it("uses openai-chat when moving to Custom and otherwise preserves the current client", () => {
expect(clientTypeAfterProviderChange("custom", "")).toBe("openai-chat");
@@ -66,6 +94,21 @@ describe("toRow (DTO → row edit state)", () => {
expect(rowRef(row)).toEqual({ provider: "anthropic", modelId: "claude-sonnet-4-6" });
});
+ it("carries the env-fallback name and its masked preview through to the row", () => {
+ const row = toRow({
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ envKey: "ANTHROPIC_API_KEY",
+ envKeyMasked: "sk-a…3456",
+ isDefault: false,
+ });
+ expect(row.envKey).toBe("ANTHROPIC_API_KEY");
+ expect(row.envKeyMasked).toBe("sk-a…3456");
+ expect(toRow({ provider: "custom", modelId: "m", isDefault: false }).envKeyMasked).toBe(
+ undefined,
+ );
+ });
+
it("providers outside the catalog list are kept as-is (only the display layer buckets them under custom)", () => {
const row = toRow({ provider: "myproxy", modelId: "claude-sonnet-4-6", isDefault: false });
expect(row.provider).toBe("myproxy");