"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(desktop): protect packaged credentials with safeStorage
QCYTSN2b1b499b4231
diff --git a/agent/src/api/settings_routes.py b/agent/src/api/settings_routes.pyindex 8472e7993..53e4d2a75 100644--- a/agent/src/api/settings_routes.py+++ b/agent/src/api/settings_routes.py@@ -152,6 +152,19 @@ LLM_API_KEY_PLACEHOLDERS = {"", "sk-or-v1-your-key-here", "sk-xxx", "xxx", "gsk_TUSHARE_TOKEN_PLACEHOLDERS = {"", "your-tushare-token"}+def _desktop_secure_credential_names() -> set[str]:+ """Return secrets owned by the desktop host when secure storage is active."""+ names = {"TUSHARE_TOKEN", "QVERIS_API_KEY"}+ names.update(+ provider.api_key_env for provider in LLM_PROVIDERS if provider.api_key_env+ )+ return names+++def _desktop_secure_credentials_enabled() -> bool:+ return os.environ.get("VIBE_TRADING_DESKTOP_SECURE_CREDENTIALS") == "1"++# ---------------------------------------------------------------------------# Host access helpers (late-binding for test monkeypatch compat)# ---------------------------------------------------------------------------@@ -206,6 +219,13 @@ def _read_settings_env_values() -> Dict[str, str]:else:values = {}+ if _desktop_secure_credentials_enabled():+ for name in _desktop_secure_credential_names():+ runtime_value = os.environ.get(name, "")+ if runtime_value:+ values[name] = runtime_value+ else:+ values.pop(name, None)return values@@ -306,8 +326,6 @@ async def _list_provider_models(models=models or fallback,source="provider" if discovered else "default",)--# ---------------------------------------------------------------------------# Response builders# ---------------------------------------------------------------------------@@ -429,6 +447,10 @@ def _persist_settings_updates(updates: Dict[str, str]) -> Dict[str, str]:merged = dict(updates)if not target.exists() and legacy != target and legacy.exists():merged = {**host._read_env_values(legacy), **updates}+ if _desktop_secure_credentials_enabled():+ # Empty known secret keys in dotenv while preserving the decrypted+ # environment values injected by Electron for this process.+ merged.update({name: "" for name in _desktop_secure_credential_names()})try:host._write_env_values(target, merged)except OSError as exc:@@ -439,7 +461,7 @@ def _persist_settings_updates(updates: Dict[str, str]) -> Dict[str, str]:"~/.vibe-trading/.env"),) from exc- return host._read_env_values(target)+ return _read_settings_env_values()# ---------------------------------------------------------------------------diff --git a/agent/tests/test_settings_api.py b/agent/tests/test_settings_api.pyindex 055f521cd..c9d4ee8ff 100644--- a/agent/tests/test_settings_api.py+++ b/agent/tests/test_settings_api.py@@ -256,6 +256,29 @@ def test_update_deepseek_settings_uses_exact_reported_payload(assert "DEEPSEEK_API_KEY=sk-deepseek-test" in env_textassert "DEEPSEEK_BASE_URL=https://api.deepseek.com/v1" in env_text+def test_desktop_secure_mode_never_persists_injected_llm_key(+ client: TestClient,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("VIBE_TRADING_DESKTOP_SECURE_CREDENTIALS", "1")+ monkeypatch.setenv("DEEPSEEK_API_KEY", "dpapi-decrypted-key")++ response = client.put(+ "/settings/llm",+ json={+ "provider": "deepseek",+ "model_name": "deepseek-chat",+ "base_url": "https://api.deepseek.com/v1",+ },+ )++ assert response.status_code == 200+ assert response.json()["api_key_configured"] is True+ env_text = (tmp_path / ".env").read_text(encoding="utf-8")+ assert "dpapi-decrypted-key" not in env_text+ assert "DEEPSEEK_API_KEY=" in env_text+@pytest.mark.parametrize(("provider", "api_key_env", "base_url_env", "base_url"),[@@ -506,6 +529,23 @@ def test_update_data_source_settings_persists_tushare_token(assert "TUSHARE_TOKEN=ts-secret-token" in env_text+def test_desktop_secure_mode_never_persists_injected_tushare_token(+ client: TestClient,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("VIBE_TRADING_DESKTOP_SECURE_CREDENTIALS", "1")+ monkeypatch.setenv("TUSHARE_TOKEN", "dpapi-tushare-token")++ response = client.put("/settings/data-sources", json={})++ assert response.status_code == 200+ assert response.json()["tushare_token_configured"] is True+ env_text = (tmp_path / ".env").read_text(encoding="utf-8")+ assert "dpapi-tushare-token" not in env_text+ assert "TUSHARE_TOKEN=" in env_text++def test_settings_writes_reject_remote_dev_mode_clients(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/desktop/electron/src/backend-manager.ts b/desktop/electron/src/backend-manager.tsindex 7cd85766c..1884cdb91 100644--- a/desktop/electron/src/backend-manager.ts+++ b/desktop/electron/src/backend-manager.ts@@ -20,6 +20,7 @@ type BackendManagerOptions = {logDirectory: string;apiAuthKey: string;messages: DesktopMessages;+ credentialEnvironment?: NodeJS.ProcessEnv;onStatus: (message: string) => void;onUnexpectedExit: (message: string) => void;};@@ -91,7 +92,9 @@ export class BackendManager {const gtkBin = path.join(path.dirname(executable), "gtk", "bin");const childEnvironment: NodeJS.ProcessEnv = {...process.env,+ ...this.options.credentialEnvironment,API_AUTH_KEY: this.options.apiAuthKey,+ VIBE_TRADING_DESKTOP_SECURE_CREDENTIALS: "1",PYTHONUTF8: "1",PYTHONUNBUFFERED: "1",ELECTRON_RUN_AS_NODE: "1",diff --git a/desktop/electron/src/main.ts b/desktop/electron/src/main.tsindex c446b6ca6..630a94abd 100644--- a/desktop/electron/src/main.ts+++ b/desktop/electron/src/main.ts@@ -17,6 +17,7 @@ import {getRendererLocale,resolveDesktopLocale,} from "./locales";+import { SecureCredentialStore } from "./secure-credentials";let mainWindow: BrowserWindow | undefined;let backend: BackendManager | undefined;@@ -27,6 +28,7 @@ let desktopMessages = getDesktopMessages(desktopLocale);const apiAuthKey = randomBytes(32).toString("base64url");const productName = "Vibe-Trading Desktop (Unofficial Community Build)";const testUserData = process.env.VIBE_TRADING_DESKTOP_TEST_USER_DATA;+const credentialStore = new SecureCredentialStore();if (testUserData) app.setPath("userData", path.resolve(testUserData));app.setName(productName);@@ -51,6 +53,7 @@ async function ready(): Promise<void> {desktopMessages = getDesktopMessages(desktopLocale);nativeTheme.themeSource = "dark";app.setAppLogsPath();+ await credentialStore.initialize();createWindow();registerIpc();createMenu();@@ -126,6 +129,18 @@ function registerIpc(): void {await boot();return true;});+ ipcMain.handle("desktop:get-credential-status", (event) => {+ assertMainWindowSender(event.sender);+ return credentialStore.status();+ });+ ipcMain.handle("desktop:set-credential", async (event, name: unknown, value: unknown) => {+ assertMainWindowSender(event.sender);+ if (typeof name !== "string" || (typeof value !== "string" && value !== null)) {+ throw new Error("Invalid credential request");+ }+ await credentialStore.set(name, value);+ return credentialStore.status();+ });}async function showLoadingPage(): Promise<void> {@@ -157,6 +172,7 @@ async function bootInternal(): Promise<void> {logDirectory: app.getPath("logs"),apiAuthKey,messages: desktopMessages,+ credentialEnvironment: credentialStore.environment(),onStatus: (message) => mainWindow?.webContents.send("desktop:status", message),onUnexpectedExit: (message) => {if (!quitting) void reportBootError(message);diff --git a/desktop/electron/src/preload.ts b/desktop/electron/src/preload.tsindex f96b95faa..6043d4236 100644--- a/desktop/electron/src/preload.ts+++ b/desktop/electron/src/preload.ts@@ -11,4 +11,7 @@ contextBridge.exposeInMainWorld("vibeDesktop", {retry: () => ipcRenderer.send("desktop:retry"),openLogs: () => ipcRenderer.send("desktop:open-logs"),restartBackend: () => ipcRenderer.invoke("desktop:restart-backend") as Promise<boolean>,+ getCredentialStatus: () => ipcRenderer.invoke("desktop:get-credential-status"),+ setCredential: (name: string, value: string | null) =>+ ipcRenderer.invoke("desktop:set-credential", name, value),});diff --git a/desktop/electron/src/secure-credentials.ts b/desktop/electron/src/secure-credentials.tsnew file mode 100644index 000000000..5d6cfd3fb--- /dev/null+++ b/desktop/electron/src/secure-credentials.ts@@ -0,0 +1,209 @@+import { app, safeStorage } from "electron";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";++type CredentialFile = {+ version: 1;+ values: Record<string, string>;+};++const ENV_CREDENTIALS = new Set([+ "OPENROUTER_API_KEY",+ "REQUESTY_API_KEY",+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "DEEPSEEK_API_KEY",+ "SILICONFLOW_API_KEY",+ "SILICONFLOW_GLOBAL_API_KEY",+ "NVIDIA_API_KEY",+ "GEMINI_API_KEY",+ "GROQ_API_KEY",+ "DASHSCOPE_API_KEY",+ "ZHIPU_API_KEY",+ "MOONSHOT_API_KEY",+ "KIMI_CODING_API_KEY",+ "MINIMAX_API_KEY",+ "MIMO_API_KEY",+ "SPARK_API_KEY",+ "ZAI_API_KEY",+ "TUSHARE_TOKEN",+ "QVERIS_API_KEY",+]);++const PLACEHOLDER_VALUES = new Set([+ "",+ "sk-or-v1-your-key-here",+ "sk-or-...here",+ "sk-xxx",+ "xxx",+ "gsk_xxx",+ "your-tushare-token",+]);++export type CredentialStatus = {+ available: boolean;+ configured: string[];+ migrated: string[];+};++export class SecureCredentialStore {+ private readonly filePath = path.join(app.getPath("userData"), "credentials.v1.json");+ private values: Record<string, string> = {};+ private migrated: string[] = [];++ async initialize(): Promise<void> {+ if (!safeStorage.isEncryptionAvailable()) {+ throw new Error("Windows credential encryption is unavailable for this user session.");+ }+ await this.load();+ await this.migrateDotenv(path.join(os.homedir(), ".vibe-trading", ".env"));+ await this.migrateJsonField(+ path.join(os.homedir(), ".vibe-trading", "qveris.json"),+ "api_key",+ "QVERIS_API_KEY",+ );+ }++ status(): CredentialStatus {+ return {+ available: safeStorage.isEncryptionAvailable(),+ configured: Object.keys(this.values).sort(),+ migrated: [...this.migrated],+ };+ }++ async set(name: string, value: string | null): Promise<void> {+ this.assertAllowed(name);+ const normalized = value?.trim() ?? "";+ if (!normalized) {+ delete this.values[name];+ } else {+ this.values[name] = safeStorage.encryptString(normalized).toString("base64");+ }+ await this.persist();+ }++ environment(): NodeJS.ProcessEnv {+ const output: NodeJS.ProcessEnv = {};+ for (const name of Object.keys(this.values)) {+ const value = this.decrypt(name);+ if (value) output[name] = value;+ }+ return output;+ }++ private decrypt(name: string): string {+ try {+ return safeStorage.decryptString(Buffer.from(this.values[name], "base64"));+ } catch {+ return "";+ }+ }++ private assertAllowed(name: string): void {+ if (!ENV_CREDENTIALS.has(name)) {+ throw new Error("Unsupported credential key");+ }+ }++ private async load(): Promise<void> {+ try {+ const parsed = JSON.parse(await fs.readFile(this.filePath, "utf8")) as CredentialFile;+ if (parsed.version !== 1 || !parsed.values || typeof parsed.values !== "object") {+ throw new Error("Unsupported desktop credential file");+ }+ this.values = Object.fromEntries(+ Object.entries(parsed.values).filter(+ ([name, value]) => ENV_CREDENTIALS.has(name) && typeof value === "string",+ ),+ );+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ }+ }++ private async persist(): Promise<void> {+ await fs.mkdir(path.dirname(this.filePath), { recursive: true });+ const temporary = `${this.filePath}.${process.pid}.tmp`;+ await fs.writeFile(+ temporary,+ `${JSON.stringify({ version: 1, values: this.values }, null, 2)}\n`,+ { encoding: "utf8", mode: 0o600 },+ );+ await fs.rename(temporary, this.filePath);+ }++ private async migrateDotenv(filePath: string): Promise<void> {+ let text: string;+ try {+ text = await fs.readFile(filePath, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;+ throw error;+ }++ let changed = false;+ const nextLines: string[] = [];+ for (const line of text.split(/\r?\n/u)) {+ const match = line.match(/^\s*([A-Z][A-Z0-9_]*)\s*=\s*(.*)\s*$/u);+ const name = match?.[1] ?? "";+ const value = unquote(match?.[2] ?? "");+ if (ENV_CREDENTIALS.has(name) && !PLACEHOLDER_VALUES.has(value.toLowerCase())) {+ if (!this.values[name]) {+ this.values[name] = safeStorage.encryptString(value).toString("base64");+ this.migrated.push(name);+ }+ nextLines.push(`# ${name} is stored by Vibe-Trading Desktop secure storage.`);+ changed = true;+ } else {+ nextLines.push(line);+ }+ }+ if (changed) {+ await this.persist();+ await atomicTextWrite(filePath, nextLines.join("\n"));+ }+ }++ private async migrateJsonField(+ filePath: string,+ field: string,+ credential: string,+ ): Promise<void> {+ try {+ const parsed = JSON.parse(await fs.readFile(filePath, "utf8")) as Record<string, unknown>;+ const value = typeof parsed[field] === "string" ? parsed[field].trim() : "";+ if (!value) return;+ if (!this.values[credential]) {+ this.values[credential] = safeStorage.encryptString(value).toString("base64");+ this.migrated.push(credential);+ await this.persist();+ }+ delete parsed[field];+ await atomicTextWrite(filePath, `${JSON.stringify(parsed, null, 2)}\n`);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !(error instanceof SyntaxError)) {+ throw error;+ }+ }+ }+}++function unquote(value: string): string {+ const trimmed = value.trim();+ if (+ trimmed.length >= 2 &&+ ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||+ (trimmed.startsWith("'") && trimmed.endsWith("'")))+ ) {+ return trimmed.slice(1, -1).trim();+ }+ return trimmed;+}++async function atomicTextWrite(filePath: string, content: string): Promise<void> {+ const temporary = `${filePath}.${process.pid}.tmp`;+ await fs.writeFile(temporary, content, { encoding: "utf8", mode: 0o600 });+ await fs.rename(temporary, filePath);+}diff --git a/frontend/src/components/settings/QVerisSettings.tsx b/frontend/src/components/settings/QVerisSettings.tsxindex 9cdecc1dd..ed79d8a66 100644--- a/frontend/src/components/settings/QVerisSettings.tsx+++ b/frontend/src/components/settings/QVerisSettings.tsx@@ -157,15 +157,23 @@ export function QVerisSettings() {budget_credits_per_session: Number(form.budget_credits_per_session) || 0,};const trimmedApiKey = form.api_key.trim();- if (trimmedApiKey) payload.api_key = trimmedApiKey;+ if (trimmedApiKey && !window.vibeDesktop) payload.api_key = trimmedApiKey;const nextConfig = await requestJson<QVerisConfig>("/qveris/config", {method: "PUT",body: JSON.stringify(payload),});+ if (trimmedApiKey && window.vibeDesktop) {+ await window.vibeDesktop.setCredential("QVERIS_API_KEY", trimmedApiKey);+ }setConfig(nextConfig);setForm(formFromConfig(nextConfig));toast.success(t("qveris.saved"));+ if (trimmedApiKey && window.vibeDesktop) {+ toast.info("Credential encrypted. Restarting the local service...");+ await window.vibeDesktop.restartBackend();+ return;+ }await load();} catch (saveError) {const message = saveError instanceof Error ? saveError.message : t("qveris.testFailed");diff --git a/frontend/src/desktop.d.ts b/frontend/src/desktop.d.tsnew file mode 100644index 000000000..af9042cf7--- /dev/null+++ b/frontend/src/desktop.d.ts@@ -0,0 +1,21 @@+export {};++export interface DesktopCredentialStatus {+ available: boolean;+ configured: string[];+ migrated: string[];+}++declare global {+ interface Window {+ vibeDesktop?: {+ isDesktop: boolean;+ restartBackend: () => Promise<boolean>;+ getCredentialStatus: () => Promise<DesktopCredentialStatus>;+ setCredential: (+ name: string,+ value: string | null,+ ) => Promise<DesktopCredentialStatus>;+ };+ }+}diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex eeecef54d..fdb93c9ec 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -390,6 +390,7 @@"llmSettingsSaved": "تم حفظ إعدادات LLM","saveLlmSettingsFailed": "فشل حفظ إعدادات LLM: {{message}}","dataSourceSettingsSaved": "تم حفظ إعدادات مصادر البيانات",+ "desktopCredentialRestarting": "تم تشفير بيانات الاعتماد. جارٍ إعادة تشغيل الخدمة المحلية…","saveDataSourceSettingsFailed": "فشل حفظ إعدادات مصادر البيانات: {{message}}","configured": "تم التكوين","keepCurrentKey": "اتركه فارغًا للاحتفاظ بالمفتاح الحالي",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex b0342cbed..001be1f7f 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -395,6 +395,7 @@"llmSettingsSaved": "LLM settings saved","saveLlmSettingsFailed": "Failed to save LLM settings: {{message}}","dataSourceSettingsSaved": "Data source settings saved",+ "desktopCredentialRestarting": "Credential encrypted. Restarting the local service…","saveDataSourceSettingsFailed": "Failed to save data source settings: {{message}}","configured": "Configured","keepCurrentKey": "Leave blank to keep the current key",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex de0932c57..734a1aec7 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -390,6 +390,7 @@"llmSettingsSaved": "LLM 設定を保存しました","saveLlmSettingsFailed": "LLM 設定の保存に失敗: {{message}}","dataSourceSettingsSaved": "データソース設定を保存しました",+ "desktopCredentialRestarting": "認証情報を暗号化しました。ローカルサービスを再起動しています…","saveDataSourceSettingsFailed": "データソース設定の保存に失敗: {{message}}","configured": "設定済み","keepCurrentKey": "空欄で現在のキーを保持",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 8e5afeff2..72331da0e 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -390,6 +390,7 @@"llmSettingsSaved": "LLM 설정이 저장되었습니다","saveLlmSettingsFailed": "LLM 설정 저장 실패: {{message}}","dataSourceSettingsSaved": "데이터 소스 설정이 저장되었습니다",+ "desktopCredentialRestarting": "자격 증명이 암호화되었습니다. 로컬 서비스를 다시 시작하는 중입니다…","saveDataSourceSettingsFailed": "데이터 소스 설정 저장 실패: {{message}}","configured": "구성됨","keepCurrentKey": "비우면 현재 키 유지",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 485a6fb1c..5f377dcf0 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -390,6 +390,7 @@"llmSettingsSaved": "LLM 设置已保存","saveLlmSettingsFailed": "保存 LLM 设置失败: {{message}}","dataSourceSettingsSaved": "数据源设置已保存",+ "desktopCredentialRestarting": "凭据已加密,正在重启本地服务…","saveDataSourceSettingsFailed": "保存数据源设置失败: {{message}}","configured": "已配置","keepCurrentKey": "留空以保留当前密钥",diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsxindex 640c95fef..7775e2bc0 100644--- a/frontend/src/pages/Settings.tsx+++ b/frontend/src/pages/Settings.tsx@@ -36,6 +36,7 @@ function toForm(settings: LLMSettings): LLMFormState {export function Settings() {const { t } = useTranslation();+ const isDesktop = window.vibeDesktop?.isDesktop === true;const [settings, setSettings] = useState<LLMSettings | null>(null);const [dataSettings, setDataSettings] = useState<DataSourceSettings | null>(null);const [channelStatus, setChannelStatus] = useState<ChannelRuntimeStatus | null>(null);@@ -218,16 +219,27 @@ export function Settings() {if (!form) return;setSaving(true);try {+ const desktop = window.vibeDesktop;const updated = await api.updateLLMSettings({...form,- api_key: apiKey.trim() || undefined,- clear_api_key: clearApiKey,+ api_key: isDesktop ? undefined : apiKey.trim() || undefined,+ clear_api_key: isDesktop ? false : clearApiKey,});+ if (desktop && selectedProvider?.api_key_env && (apiKey.trim() || clearApiKey)) {+ await desktop.setCredential(+ selectedProvider.api_key_env,+ clearApiKey ? null : apiKey.trim(),+ );+ }setSettings(updated);setForm(toForm(updated));setApiKey("");setClearApiKey(false);toast.success(t("settings.llmSettingsSaved"));+ if (desktop && selectedProvider?.api_key_env && (apiKey.trim() || clearApiKey)) {+ toast.info(t("settings.desktopCredentialRestarting"));+ await desktop.restartBackend();+ }} catch (error) {toast.error(t("settings.saveLlmSettingsFailed", {message: error instanceof Error@@ -243,14 +255,25 @@ export function Settings() {event.preventDefault();setDataSaving(true);try {+ const desktop = window.vibeDesktop;const updated = await api.updateDataSourceSettings({- tushare_token: tushareToken.trim() || undefined,- clear_tushare_token: clearTushareToken,+ tushare_token: isDesktop ? undefined : tushareToken.trim() || undefined,+ clear_tushare_token: isDesktop ? false : clearTushareToken,});+ if (desktop && (tushareToken.trim() || clearTushareToken)) {+ await desktop.setCredential(+ "TUSHARE_TOKEN",+ clearTushareToken ? null : tushareToken.trim(),+ );+ }setDataSettings(updated);setTushareToken("");setClearTushareToken(false);toast.success(t("settings.dataSourceSettingsSaved"));+ if (desktop && (tushareToken.trim() || clearTushareToken)) {+ toast.info(t("settings.desktopCredentialRestarting"));+ await desktop.restartBackend();+ }} catch (error) {toast.error(t("settings.saveDataSourceSettingsFailed", {message: error instanceof Error@@ -302,7 +325,7 @@ export function Settings() {<h1 className="text-2xl font-semibold tracking-tight">{t("settings.title")}</h1><p className="max-w-3xl text-sm text-muted-foreground">{t("settings.subtitle")}</p></div>- {localApiAccessSection}+ {!isDesktop && localApiAccessSection}{/* QVERIS-INTEGRATION */}<QVerisSettings /><div className="flex min-h-32 items-center justify-center rounded-lg border bg-card p-5 text-sm text-muted-foreground">@@ -455,7 +478,7 @@ export function Settings() {<p className="max-w-3xl text-sm text-muted-foreground">{t("settings.subtitle")}</p></div>- {localApiAccessSection}+ {!isDesktop && localApiAccessSection}{/* QVERIS-INTEGRATION */}<QVerisSettings />diff --git a/frontend/src/pages/__tests__/SettingsQVeris.test.tsx b/frontend/src/pages/__tests__/SettingsQVeris.test.tsxindex 5b9349364..2b32186ef 100644--- a/frontend/src/pages/__tests__/SettingsQVeris.test.tsx+++ b/frontend/src/pages/__tests__/SettingsQVeris.test.tsx@@ -31,6 +31,7 @@ vi.mock("@/lib/apiAuth", () => ({vi.mock("sonner", () => ({toast: {success: vi.fn(),+ info: vi.fn(),error: vi.fn(),},}));@@ -153,6 +154,7 @@ describe("Settings QVeris card", () => {afterEach(() => {cleanup();+ delete window.vibeDesktop;vi.unstubAllGlobals();});@@ -207,6 +209,40 @@ describe("Settings QVeris card", () => {expect(JSON.parse(String(putCall?.[1]?.body))).not.toHaveProperty("api_key");});+ it("stores a desktop API key through safe storage and restarts the backend", async () => {+ const setCredential = vi.fn().mockResolvedValue({+ available: true,+ configured: ["QVERIS_API_KEY"],+ migrated: [],+ });+ const restartBackend = vi.fn().mockResolvedValue(true);+ window.vibeDesktop = {+ isDesktop: true,+ getCredentialStatus: vi.fn(),+ setCredential,+ restartBackend,+ };+ const fetchMock = mockQVerisFetch();+ render(<QVerisSettings />);++ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Save QVeris settings" })).toBeEnabled(),+ );+ fireEvent.change(screen.getByPlaceholderText("sk-...8TI"), {+ target: { value: "sk-desktop-key" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Save QVeris settings" }));++ await waitFor(() =>+ expect(setCredential).toHaveBeenCalledWith("QVERIS_API_KEY", "sk-desktop-key"),+ );+ const putCall = fetchMock.mock.calls.find(+ ([path, init]) => String(path) === "/qveris/config" && init?.method === "PUT",+ );+ expect(JSON.parse(String(putCall?.[1]?.body))).not.toHaveProperty("api_key");+ expect(restartBackend).toHaveBeenCalledTimes(1);+ });+it("uses the signup href from the config response and renders the empty usage state", async () => {mockQVerisFetch(qverisConfig({ signup_url: "https://qveris.ai/?ref=config-response" }), qverisStatus({ recent: [] }));render(<QVerisSettings />);