Python
fix(settings): no Remove key for a provider key set by an environment variable (#742)
Devika Vermaf574c4145408
diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex b4298ea0..4eaedb80 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -4052,10 +4052,17 @@ class SessionManager:for f in d.fieldsif not f.secret and profile.get(f.key)}+ env_var = d.env_key if (d.env_key and os.environ.get(d.env_key)) else Nonerow = {**d.to_dict(),"configured": configured,"values": values,+ # Where the key comes from: a key saved in Settings ("store"), the+ # provider's environment variable ("env"), or nowhere. A stored key wins+ # over the variable, as resolve_api_key does. The Settings card uses this+ # to hide "Remove key" for a key it cannot remove (#742).+ "key_source": "store" if profile.get("api_key") else ("env" if env_var else None),+ "env_key": env_var,"suggested_models": self._suggested_models(d.name),# Key hygiene for the Settings pane: when the key was saved (date, stamped# by set_provider) and when the provider last served a completion (epoch,@@ -4236,9 +4243,29 @@ class SessionManager:d = get_descriptor(name)if d is None:return {"ok": False, "error": f"unknown provider: {name}"}+ env_var = d.env_key if (d.env_key and os.environ.get(d.env_key)) else None+ stored = bool((self.secrets.get(f"provider:{name}") or {}).get("api_key"))+ if env_var and not stored:+ # Nothing of ours to remove: the key is the environment variable, which only+ # the user can unset. Say so instead of reporting a removal that changes+ # nothing (#742).+ return {+ "ok": False,+ "provider": name,+ "env_key": env_var,+ "error": (+ f"The {d.title} key comes from {env_var} in the server's environment. "+ "Unset it and restart the server to remove it."+ ),+ }self.secrets.delete(f"provider:{name}")self._refresh_provider(name)- return {"ok": True, "provider": name}+ out: dict[str, Any] = {"ok": True, "provider": name}+ if env_var:+ # The stored key is gone but the variable still configures the provider.+ out["env_key"] = env_var+ out["configured"] = True+ return out# -- ChatGPT-subscription provider (OAuth, no key) ---------------------------def begin_codex_signin(self) -> None:diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex dbf37aba..c27591ed 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -2418,6 +2418,11 @@ export interface ProviderInfo {recommended_model: string | null; // pre-filled default for this provider (e.g. qwen3-coder:30b)blurb?: string; // one-line note under the title ("Uses X's OpenAI-compatible API…")key_set_at?: string | null; // ISO date the key was last (re)saved — absent for env-only config+ // Where the key comes from: saved in Settings, the provider's environment variable, or+ // nowhere. "env" keys cannot be removed from the app, so the card hides "Remove key" and+ // names the variable instead (#742). Absent on an older backend → treated as "store".+ key_source?: "store" | "env" | null;+ env_key?: string | null; // the variable's name, when it is setlast_used_at?: number | null; // epoch secs the provider last served a completion// OAuth providers (auth === "oauth"): browser sign-in instead of a key form.auth?: string | null;diff --git a/surfaces/gui/src/components/ManageTabs.keyfooter.test.tsx b/surfaces/gui/src/components/ManageTabs.keyfooter.test.tsxnew file mode 100644index 00000000..008ffe8b--- /dev/null+++ b/surfaces/gui/src/components/ManageTabs.keyfooter.test.tsx@@ -0,0 +1,50 @@+// #742: "Remove key…" only for a key the app stores. A key that comes from the provider's+// environment variable cannot be removed here, so the footer is empty for it.+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { ProviderKeyFooter } from "./ManageTabs";+import type { ProviderInfo } from "../api";++afterEach(cleanup);++const base: ProviderInfo = {+ name: "openrouter",+ title: "OpenRouter",+ needs_key: true,+ configured: true,+ values: {},+ suggested_models: [],+ recommended_model: null,+ fields: [{ key: "api_key", label: "API key", secret: true, required: true, help: "", placeholder: "" }],+};++describe("ProviderKeyFooter", () => {+ it("offers Remove key for a stored key and removes on confirm", () => {+ const onRemove = vi.fn();+ vi.spyOn(window, "confirm").mockReturnValue(true);+ render(<ProviderKeyFooter info={{ ...base, key_source: "store" }} credentialed onRemove={onRemove} />);+ fireEvent.click(screen.getByTestId("set-remove-key"));+ expect(onRemove).toHaveBeenCalledTimes(1);+ });++ it("hides Remove key when the key comes from an environment variable", () => {+ render(+ <ProviderKeyFooter+ info={{ ...base, key_source: "env", env_key: "OPENROUTER_API_KEY" }}+ credentialed+ onRemove={vi.fn()}+ />,+ );+ expect(screen.queryByTestId("set-remove-key")).toBeNull();+ });++ it("still offers Remove key on an older backend that sends no key_source", () => {+ render(<ProviderKeyFooter info={base} credentialed onRemove={vi.fn()} />);+ expect(screen.getByTestId("set-remove-key")).toBeTruthy();+ });++ it("shows nothing for a provider without a key", () => {+ render(<ProviderKeyFooter info={{ ...base, configured: false }} credentialed={false} onRemove={vi.fn()} />);+ expect(screen.queryByTestId("set-remove-key")).toBeNull();+ });+});diff --git a/surfaces/gui/src/components/ManageTabs.tsx b/surfaces/gui/src/components/ManageTabs.tsxindex de87d6ba..a047b40d 100644--- a/surfaces/gui/src/components/ManageTabs.tsx+++ b/surfaces/gui/src/components/ManageTabs.tsx@@ -57,6 +57,33 @@ function initials(name: string): string {return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();}+// "Remove key…" under a provider's form. Only for a key the app itself stores: a key+// that comes from the provider's environment variable (key_source "env") cannot be+// removed here, so the button is left out and the env note below the form says why (#742).+export function ProviderKeyFooter({+ info,+ credentialed,+ onRemove,+}: {+ info: ProviderInfo | null | undefined;+ credentialed: boolean;+ onRemove: () => void;+}) {+ const { t } = useTranslation();+ if (!credentialed || info?.key_source === "env") return null;+ return (+ <button+ className="text-ui text-danger/80 hover:text-danger hover:underline underline-offset-2"+ data-testid="set-remove-key"+ onClick={() => {+ if (window.confirm(t("manage.remove_key_confirm", { title: info?.title || "" }))) onRemove();+ }}+ >+ {t("manage.remove_key")}+ </button>+ );+}+// -- Configure Models tab (UX-021: the shared provider gallery + key form) ----// Settings ▸ Models reuses onboarding §39's ProviderCards/ProviderForm so the two// surfaces can't drift. Settings-only extras: per-card "used Nh ago", a "Remove@@ -113,24 +140,12 @@ export function ModelsTab() {<ProviderFormps={ps}tp="set"- footer={- ps.credentialed ? (- <button- className="text-ui text-danger/80 hover:text-danger hover:underline underline-offset-2"- data-testid="set-remove-key"- onClick={() => {- if (window.confirm(t("manage.remove_key_confirm", { title: info?.title || "" }))) ps.removeKey();- }}- >- {t("manage.remove_key")}- </button>- ) : null- }+ footer={<ProviderKeyFooter info={info} credentialed={ps.credentialed} onRemove={ps.removeKey} />}/>- {ps.sel === "openai" && settings.source === "env" && (- <p className="text-meta text-muted mt-3 leading-relaxed">- {t("manage.openai_env_help")}+ {info?.env_key && (+ <p className="text-meta text-muted mt-3 leading-relaxed" data-testid="set-env-key-note">+ {t(info.key_source === "env" ? "manage.env_key_help" : "manage.env_key_fallback_help", { var: info.env_key })}</p>)}diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex c420c3a6..0439a5bc 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -1282,6 +1282,8 @@"could_not_connect": "could not connect","could_not_start_connect": "could not start the connect","could_not_start_managed": "could not start the connect",+ "env_key_fallback_help": "A key is also set by {{var}} in the server's environment. Removing the key saved here falls back to it.",+ "env_key_help": "This key is set by {{var}} in the server's environment, so it can't be removed here. Add a different key above to override it for this computer, or unset the variable and restart the server.","id_title": "ID: {{id}}","included_models": "Included models","included_models_help_signin": "Curated, agent-capable models this provider serves — sign in above to enable them.",@@ -1312,7 +1314,6 @@"models": "Models","models_help": "Ticked models show in the composer's picker; the black badge marks the default for new sessions.","one_click_coming": "One-click sign-in is coming soon — connect manually below for now:",- "openai_env_help": "A key is set via OPENAI_API_KEY in this server's environment. Add a different key here to override it for this computer.","optional": "(optional)","or_connect_manually": "or connect manually:","parked_allow_deliver": "Allow & deliver",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 9ded9cb7..ceedb227 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -1265,6 +1265,8 @@"could_not_connect": "无法连接","could_not_start_connect": "无法启动连接","could_not_start_managed": "无法启动连接",+ "env_key_fallback_help": "服务器环境中的 {{var}} 也设置了密钥。移除此处保存的密钥后将回退到该环境变量。",+ "env_key_help": "此密钥由服务器环境中的 {{var}} 设置,无法在此移除。在上方添加其他密钥可覆盖本机设置,或取消该环境变量并重启服务器。","id_title": "ID:{{id}}","included_models": "内置模型","included_models_help_signin": "此提供方精选的 agent 模型 —— 在上方登录即可启用。",@@ -1295,7 +1297,6 @@"models": "模型","models_help": "已勾选的模型会显示在输入框的选择器中;黑色徽标表示新会话的默认模型。","one_click_coming": "一键登录即将推出 —— 目前请在下方手动连接:",- "openai_env_help": "此服务器的环境中已通过 OPENAI_API_KEY 设置密钥。在此添加其他密钥可覆盖本机设置。","optional": "(可选)","or_connect_manually": "或手动连接:","parked_allow_deliver": "允许并送达",diff --git a/tests/test_settings.py b/tests/test_settings.pyindex 0ce9bcbc..3b5f5cdd 100644--- a/tests/test_settings.py+++ b/tests/test_settings.py@@ -245,3 +245,46 @@ def test_ollama_adoption_never_steals_a_working_default(tmp_path, monkeypatch):before = manager.get_settings()["model"]assert manager.adopt_provider_default("ollama") is Noneassert manager.get_settings()["model"] == before+++def test_env_key_provider_reports_its_source_and_refuses_removal(tmp_path, monkeypatch):+ """#742: a key that comes from the provider's environment variable is not ours to+ remove. The provider row says where the key comes from, and remove_provider answers+ truthfully instead of reporting a removal that changes nothing."""+ from coworker.server.manager import SessionManager++ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-from-env")+ mgr = SessionManager(data_dir=tmp_path)++ row = {p["name"]: p for p in mgr.get_providers()}["anthropic"]+ assert row["configured"] is True+ assert row["key_source"] == "env" and row["env_key"] == "ANTHROPIC_API_KEY"++ res = mgr.remove_provider("anthropic")+ assert res["ok"] is False and res["env_key"] == "ANTHROPIC_API_KEY"+ assert "ANTHROPIC_API_KEY" in res["error"]+ assert {p["name"]: p for p in mgr.get_providers()}["anthropic"]["configured"] is True++ # A key saved in Settings wins over the variable and can be removed; the provider+ # then stays configured by the variable, and the answer says so.+ mgr.set_provider("anthropic", {"api_key": "sk-ant-stored"})+ row = {p["name"]: p for p in mgr.get_providers()}["anthropic"]+ assert row["key_source"] == "store" and row["env_key"] == "ANTHROPIC_API_KEY"+ res = mgr.remove_provider("anthropic")+ assert res == {"ok": True, "provider": "anthropic", "env_key": "ANTHROPIC_API_KEY", "configured": True}+ row = {p["name"]: p for p in mgr.get_providers()}["anthropic"]+ assert row["key_source"] == "env" and row["configured"] is True+++def test_stored_key_provider_removes_cleanly(tmp_path, monkeypatch):+ from coworker.server.manager import SessionManager++ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)+ mgr = SessionManager(data_dir=tmp_path)+ assert {p["name"]: p for p in mgr.get_providers()}["anthropic"]["key_source"] is None+ mgr.set_provider("anthropic", {"api_key": "sk-ant-stored"})+ row = {p["name"]: p for p in mgr.get_providers()}["anthropic"]+ assert row["key_source"] == "store" and row["env_key"] is None+ assert mgr.remove_provider("anthropic") == {"ok": True, "provider": "anthropic"}+ row = {p["name"]: p for p in mgr.get_providers()}["anthropic"]+ assert row["configured"] is False and row["key_source"] is None