Skip to content

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

feat(settings): add Jev from the service chooser with a checked key

vastsad135b7ac5c32
diff --git a/apps/desktop/electron/main/ipc/jev-ipc.ts b/apps/desktop/electron/main/ipc/jev-ipc.ts
new file mode 100644
index 000000000..0fce1e24f
--- /dev/null
+++ b/apps/desktop/electron/main/ipc/jev-ipc.ts
@@ -0,0 +1,27 @@
+/**
+ * The Jev key check channel.
+ *
+ * One job, separate from the provider channels: Jev owns no provider row, and
+ * its credential lives under a fixed Host secret reference rather than a
+ * provider id. The handler only asks TypeSafe; it stores nothing, so a key
+ * that fails the check never reaches the secret store.
+ */
+import { IPC } from "@pi-desktop/shared";
+import { probeJevApiKey } from "../jev-probe";
+import type { Logger } from "../logger";
+import type { IpcRegistrar } from "./types";
+
+export type JevIpcDependencies = {
+ registrar: IpcRegistrar;
+ logger: Pick<Logger, "app">;
+};
+
+export function registerJevIpc({ registrar, logger }: JevIpcDependencies): void {
+ registrar.handle(IPC.invoke.jevTest, async (apiKey: unknown) => {
+ const result = await probeJevApiKey(typeof apiKey === "string" ? apiKey : "");
+ logger.app("provider", result.ok ? "info" : "warn", "TypeSafe Jev key check", {
+ data: { ok: result.ok, status: result.status },
+ });
+ return result;
+ });
+}
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 009d0e31e..63fd043a7 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -17,6 +17,7 @@ import { searchMcpMarket } from "../mcp-registry-catalog";
import { registerNotificationIpc } from "./notification-ipc";
import { registerPluginIpc } from "./plugin-ipc";
import { registerPluginUiIpc } from "./plugin-ui-ipc";
+import { registerJevIpc } from "./jev-ipc";
import { registerProviderIpc } from "./provider-ipc";
import { registerScheduledIpc } from "./scheduled-ipc";
import { registerSessionIpc } from "./session-ipc";
@@ -298,6 +299,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
bindingForModel,
onProviderInvalidated: (providerId) => liveCallService?.invalidateProvider(providerId),
});
+ registerJevIpc({ registrar, logger });
const loadComposerTemplatesCached = createComposerTemplateLoader(logger);
const composerCommandService = registerComposerIpc({
registrar,
diff --git a/apps/desktop/electron/main/jev-probe.ts b/apps/desktop/electron/main/jev-probe.ts
new file mode 100644
index 000000000..ba9830589
--- /dev/null
+++ b/apps/desktop/electron/main/jev-probe.ts
@@ -0,0 +1,101 @@
+/**
+ * TypeSafe reachability check for the Jev classifier key.
+ *
+ * Jev is configured from settings, where a wrong or expired key would
+ * otherwise be discovered by the Agent mid-task. The check is the smallest
+ * real System One round trip — one boolean question over a one-field state —
+ * against the same address and classifier id the Agent's `JevClassify` tool
+ * uses, so "the key works" means TypeSafe answered this key, not that the
+ * string looks plausible.
+ *
+ * Nothing is written here: the caller stores the key only when this answered.
+ * The key never reaches a log line or an error message; failure text is
+ * redacted before it is returned.
+ */
+import {
+ TYPESAFE_JEV_MODEL_ID,
+ TYPESAFE_SYSTEM_ONE_URL,
+ type JevKeyCheckResult,
+} from "@pi-desktop/shared";
+
+export const JEV_PROBE_TIMEOUT_MS = 20_000;
+
+/** Longest provider message echoed back to the settings dialog. */
+const MAX_DETAIL_LENGTH = 300;
+
+export type JevProbeOptions = {
+ /** The caller's own cancellation, combined with the timeout. */
+ signal?: AbortSignal;
+ /** Test seam; defaults to the global fetch. */
+ fetchImpl?: typeof fetch;
+ timeoutMs?: number;
+};
+
+/**
+ * The smallest valid System One request: `bool` is PI-Desktop's public name for
+ * the wire-level `noul` question (see pi-ai's System One transport).
+ */
+function probeRequestBody() {
+ return {
+ model: TYPESAFE_JEV_MODEL_ID,
+ state: { probe: true },
+ questions: {
+ reachable: {
+ type: "noul",
+ instructions: "Did this request reach the classifier?",
+ criteria: {
+ true: "The request reached the classifier.",
+ false: "The request did not reach the classifier.",
+ },
+ },
+ },
+ };
+}
+
+/** A message that never carries the credential it describes. */
+function redact(value: string, apiKey: string): string {
+ if (!apiKey) return value;
+ return value.split(apiKey).join("[redacted]");
+}
+
+export async function probeJevApiKey(
+ apiKey: string,
+ options: JevProbeOptions = {},
+): Promise<JevKeyCheckResult> {
+ const key = apiKey.trim();
+ if (!key) return { ok: false, message: "No TypeSafe API key was provided." };
+ const timeoutMs = options.timeoutMs ?? JEV_PROBE_TIMEOUT_MS;
+ const timeout = AbortSignal.timeout(timeoutMs);
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
+ const doFetch = options.fetchImpl ?? globalThis.fetch;
+ try {
+ const response = await doFetch(TYPESAFE_SYSTEM_ONE_URL, {
+ method: "POST",
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
+ body: JSON.stringify(probeRequestBody()),
+ signal,
+ });
+ if (response.ok) return { ok: true, status: response.status };
+ const body = await response.text().catch(() => "");
+ const detail = redact(body.slice(0, MAX_DETAIL_LENGTH).trim(), key);
+ return {
+ ok: false,
+ status: response.status,
+ message: detail
+ ? `TypeSafe returned ${response.status}: ${detail}`
+ : `TypeSafe returned ${response.status}`,
+ };
+ } catch (error) {
+ if (options.signal?.aborted) {
+ return { ok: false, message: "The TypeSafe key check was cancelled." };
+ }
+ const name = (error as { name?: unknown }).name;
+ if (name === "TimeoutError" || name === "AbortError") {
+ return {
+ ok: false,
+ message: `TypeSafe did not answer within ${Math.round(timeoutMs / 1000)}s.`,
+ };
+ }
+ return { ok: false, message: redact(error instanceof Error ? error.message : String(error), key) };
+ }
+}
diff --git a/apps/desktop/electron/main/mcp-control.ts b/apps/desktop/electron/main/mcp-control.ts
index 4c69e3c7d..1befeba83 100644
--- a/apps/desktop/electron/main/mcp-control.ts
+++ b/apps/desktop/electron/main/mcp-control.ts
@@ -471,6 +471,8 @@ export const MCP_CONTROL_BLOCKED_CHANNEL_KEYS = [
"providersUpdate",
"providersDelete",
"providersTest",
+ // A key check spends a credential the control surface must not hold.
+ "jevTest",
"providersOauthStart",
"providersOauthRespond",
"providersOauthCancel",
diff --git a/apps/desktop/src/components/settings/JevServiceForm.tsx b/apps/desktop/src/components/settings/JevServiceForm.tsx
new file mode 100644
index 000000000..030aca7cd
--- /dev/null
+++ b/apps/desktop/src/components/settings/JevServiceForm.tsx
@@ -0,0 +1,124 @@
+/**
+ * Adding Jev from the service list (D625).
+ *
+ * The service chooser answers "which service"; this is the whole second half
+ * for Jev, whose only decision is a TypeSafe key. One button runs both steps —
+ * check the key against TypeSafe, then store it and turn Jev on — so a key
+ * that never answered is never kept, and adding Jev is the same click as
+ * enabling it. Closing this dialog while the check is still running cancels
+ * the whole action: nothing is stored and nothing is enabled.
+ */
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useAppStore } from "../../stores/app-store";
+import { Button, Field, PasswordInput } from "../ui";
+import { addJevService } from "./jev-config";
+import { appJevConfigDeps, useJevKeyStatus } from "./jev-app-config";
+
+export type JevServiceFormProps = {
+ onClose: () => void;
+ /** The key was stored and Jev turned on; the caller closes this dialog. */
+ onConfigured: () => void;
+};
+
+export function JevServiceForm({ onClose, onConfigured }: JevServiceFormProps) {
+ const { t } = useTranslation();
+ const showToast = useAppStore((state) => state.showToast);
+ const [keyDraft, setKeyDraft] = useState("");
+ const [checking, setChecking] = useState(false);
+ const [keyStatus] = useJevKeyStatus();
+ const aborted = useRef<AbortController | null>(null);
+ const configured = keyStatus === "configured";
+
+ // Unmounting is a cancel: the check may still be in flight, and a dialog the
+ // user closed must not come back later with a stored credential.
+ useEffect(() => () => aborted.current?.abort(), []);
+
+ const statusText = configured
+ ? t("settings.jevKeyConfigured")
+ : keyStatus === "unavailable"
+ ? t("settings.jevKeyStatusUnavailable")
+ : keyStatus === "loading"
+ ? t("settings.jevKeyStatusChecking")
+ : t("settings.jevKeyMissing");
+
+ const save = async () => {
+ if (checking || !keyDraft.trim()) return;
+ const controller = new AbortController();
+ aborted.current = controller;
+ setChecking(true);
+ try {
+ const outcome = await addJevService(appJevConfigDeps(), keyDraft, controller.signal);
+ if (!outcome.ok) {
+ // Closed while the check ran: the user cancelled, so say nothing at all.
+ if (outcome.reason === "cancelled") return;
+ showToast(
+ outcome.reason === "missing-key"
+ ? t("settings.jevKeyRequired")
+ : outcome.message || t("settings.jevKeyCheckFailed"),
+ { variant: "error" },
+ );
+ return;
+ }
+ setKeyDraft("");
+ showToast(t("settings.jevServiceAdded"), { variant: "success" });
+ onConfigured();
+ } catch (error) {
+ if (controller.signal.aborted) return;
+ showToast(error instanceof Error ? error.message : String(error), {
+ variant: "error",
+ });
+ } finally {
+ if (!controller.signal.aborted) setChecking(false);
+ }
+ };
+
+ return (
+ <>
+ <div className="provider-setup-head">
+ <h3 id="provider-setup-title" className="provider-setup-title">
+ {t("settings.jevTitle")}
+ </h3>
+ <div className="provider-setup-head-actions">
+ <Button variant="ghost" size="sm" disabled={checking} onClick={onClose}>
+ {t("settings.cancel")}
+ </Button>
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={checking || !keyDraft.trim()}
+ onClick={() => void save()}
+ >
+ {checking ? t("settings.jevCheckingKey") : t("settings.jevTestAndSave")}
+ </Button>
+ </div>
+ </div>
+
+ <div className="provider-setup-body">
+ <div className="provider-setup-credentials">
+ <div className="jev-setup">
+ <p className="jev-setup-description">{t("settings.jevDescription")}</p>
+ <p className="jev-setup-privacy">{t("settings.jevPrivacyNotice")}</p>
+ <Field label={t("settings.jevApiKey")}>
+ <PasswordInput
+ value={keyDraft}
+ autoFocus
+ placeholder={t("settings.jevApiKeyPlaceholder")}
+ aria-label={t("settings.jevApiKey")}
+ autoComplete="new-password"
+ showLabel={t("settings.configSync.showPassword")}
+ hideLabel={t("settings.configSync.hidePassword")}
+ disabled={checking}
+ onChange={(event) => setKeyDraft(event.target.value)}
+ />
+ </Field>
+ <p className="jev-setup-status" role="status">
+ {statusText}
+ </p>
+ <p className="jev-setup-note">{t("settings.jevAddEnableNote")}</p>
+ </div>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/apps/desktop/src/components/settings/JevSettingsCard.tsx b/apps/desktop/src/components/settings/JevSettingsCard.tsx
index da80ff5b8..0ba5a909e 100644
--- a/apps/desktop/src/components/settings/JevSettingsCard.tsx
+++ b/apps/desktop/src/components/settings/JevSettingsCard.tsx
@@ -1,58 +1,58 @@
-import { useEffect, useState } from "react";
+/**
+ * Jev on the model configuration page (D625, settings IA).
+ *
+ * The card is the state of the integration and the way in: whether a TypeSafe
+ * key is stored, whether the classifier is on for Agent mode, and the actions
+ * that change either. The key itself is entered in the service dialog, which
+ * is also where Jev is added from — one place stores a key, and that place
+ * checks it against TypeSafe first. A field here would be a second way to keep
+ * a key nothing verified.
+ */
+import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { AppSettings } from "@pi-desktop/shared";
import { api } from "../../lib/api";
import { useAppStore } from "../../stores/app-store";
-import { Button, Field, PasswordInput, SettingsToggle } from "../ui";
+import { Button, SettingsToggle } from "../ui";
import { SettingsCard, SettingsRow } from "../../features/settings/primitives";
+import { removeJevService } from "./jev-config";
+import { persistJevEnabled, useJevKeyStatus } from "./jev-app-config";
-type KeyStatus = "loading" | "configured" | "missing" | "unavailable";
-type BusyAction = "save" | "remove" | "toggle" | null;
+type BusyAction = "toggle" | "remove" | null;
-async function persistSettings(patch: Partial<AppSettings>): Promise<void> {
- const current = useAppStore.getState().settings;
- if (!current) throw new Error("Settings are not ready");
- const next = { ...current, ...patch };
- await api.setSettings(next);
- useAppStore.setState({ settings: next });
-}
+export type JevSettingsCardProps = {
+ settings?: AppSettings;
+ /** Opens the Jev service dialog, the one place a key is entered. */
+ onConfigure: () => void;
+ /** Bumped when that dialog stored a key, so this card re-reads the state. */
+ statusRevision?: number;
+};
-export function JevSettingsCard({ settings }: { settings?: AppSettings }) {
+export function JevSettingsCard({
+ settings,
+ onConfigure,
+ statusRevision = 0,
+}: JevSettingsCardProps) {
const { t } = useTranslation();
const showToast = useAppStore((state) => state.showToast);
- const [keyDraft, setKeyDraft] = useState("");
- const [keyStatus, setKeyStatus] = useState<KeyStatus>("loading");
+ const [keyStatus, setKeyStatus] = useJevKeyStatus(statusRevision);
const [busy, setBusy] = useState<BusyAction>(null);
const enabled = settings?.jevEnabled === true;
const configured = keyStatus === "configured";
- useEffect(() => {
- let current = true;
- void api.hasJevApiKey().then(
- (hasKey) => {
- if (current) setKeyStatus(hasKey ? "configured" : "missing");
- },
- () => {
- if (current) setKeyStatus("unavailable");
- },
- );
- return () => {
- current = false;
- };
- }, []);
+ const fail = (error: unknown) => {
+ showToast(error instanceof Error ? error.message : String(error), {
+ variant: "error",
+ });
+ };
- const saveKey = async () => {
- if (!keyDraft.trim()) return;
- setBusy("save");
+ const toggleEnabled = async () => {
+ if (!settings || (!enabled && !configured)) return;
+ setBusy("toggle");
try {
- await api.setJevApiKey(keyDraft);
- setKeyDraft("");
- setKeyStatus("configured");
- showToast(t("settings.jevKeySaved"), { variant: "success" });
+ await persistJevEnabled(!enabled);
} catch (error) {
- showToast(error instanceof Error ? error.message : String(error), {
- variant: "error",
- });
+ fail(error);
} finally {
setBusy(null);
}
@@ -61,47 +61,27 @@ export function JevSettingsCard({ settings }: { settings?: AppSettings }) {
const removeKey = async () => {
setBusy("remove");
try {
- if (enabled) await persistSettings({ jevEnabled: false });
- await api.deleteJevApiKey();
+ await removeJevService({
+ setEnabled: persistJevEnabled,
+ deleteKey: () => api.deleteJevApiKey(),
+ });
setKeyStatus("missing");
- setKeyDraft("");
showToast(t("settings.jevKeyRemoved"), { variant: "success" });
} catch (error) {
- try {
- setKeyStatus((await api.hasJevApiKey()) ? "configured" : "missing");
- } catch {
- setKeyStatus("unavailable");
- }
- showToast(error instanceof Error ? error.message : String(error), {
- variant: "error",
- });
+ setKeyStatus((await api.hasJevApiKey().catch(() => configured)) ? "configured" : "missing");
+ fail(error);
} finally {
setBusy(null);
}
};
- const toggleEnabled = async () => {
- if (!settings || (!enabled && !configured)) return;
- setBusy("toggle");
- try {
- await persistSettings({ jevEnabled: !enabled });
- } catch (error) {
- showToast(error instanceof Error ? error.message : String(error), {
- variant: "error",
- });
- } finally {
- setBusy(null);
- }
- };
-
- const keyStatusText =
- keyStatus === "configured"
- ? t("settings.jevKeyConfigured")
- : keyStatus === "unavailable"
- ? t("settings.jevKeyStatusUnavailable")
- : keyStatus === "loading"
- ? t("settings.jevKeyStatusChecking")
- : t("settings.jevKeyMissing");
+ const keyStatusText = configured
+ ? t("settings.jevKeyConfigured")
+ : keyStatus === "unavailable"
+ ? t("settings.jevKeyStatusUnavailable")
+ : keyStatus === "loading"
+ ? t("settings.jevKeyStatusChecking")
+ : t("settings.jevKeyMissing");
return (
<SettingsCard
@@ -113,49 +93,35 @@ export function JevSettingsCard({ settings }: { settings?: AppSettings }) {
description={t("settings.jevEnableDescription")}
detail={keyStatusText}
>
- <SettingsToggle
- checked={enabled}
- label={t("settings.jevEnable")}
- disabled={busy !== null || !settings || (!configured && !enabled)}
- busy={busy === "toggle"}
- onChange={() => void toggleEnabled()}
- />
- </SettingsRow>
- <p className="jev-settings-privacy-note">{t("settings.jevPrivacyNotice")}</p>
- <div className="jev-settings-key-form">
- <Field label={t("settings.jevApiKey")}>
- <PasswordInput
- value={keyDraft}
- onChange={(event) => setKeyDraft(event.target.value)}
- placeholder={t("settings.jevApiKeyPlaceholder")}
- aria-label={t("settings.jevApiKey")}
- autoComplete="new-password"
- showLabel={t("settings.configSync.showPassword")}
- hideLabel={t("settings.configSync.hidePassword")}
- disabled={busy !== null}
- />
- </Field>
- <div className="jev-settings-key-actions">
- <Button
- variant="primary"
- size="sm"
- disabled={busy !== null || !keyDraft.trim()}
- onClick={() => void saveKey()}
- >
- {t("settings.jevSaveKey")}
- </Button>
+ <div className="jev-settings-controls">
<Button
variant="ghost"
size="sm"
- disabled={
- busy !== null || keyStatus === "missing" || keyStatus === "loading"
- }
- onClick={() => void removeKey()}
+ disabled={busy !== null}
+ onClick={onConfigure}
>
- {t("settings.jevRemoveKey")}
+ {configured ? t("settings.jevReplaceKey") : t("settings.jevConfigureKey")}
</Button>
+ {configured ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={busy !== null}
+ onClick={() => void removeKey()}
+ >
+ {t("settings.jevRemoveKey")}
+ </Button>
+ ) : null}
+ <SettingsToggle
+ checked={enabled}
+ label={t("settings.jevEnable")}
+ disabled={busy !== null || !settings || (!configured && !enabled)}
+ busy={busy === "toggle"}
+ onChange={() => void toggleEnabled()}
+ />
</div>
- </div>
+ </SettingsRow>
+ <p className="jev-settings-privacy-note">{t("settings.jevPrivacyNotice")}</p>
</SettingsCard>
);
}
diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsx
index 0b6cc025e..0d95754e0 100644
--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx
+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx
@@ -40,6 +40,7 @@ import { VendorAccountDialog, type VendorAccountForm } from "./VendorAccountDial
import { ModelConfigImportPanel } from "../../features/settings/imports/ModelConfigImportPanel";
import { ImportToggleButton } from "../../features/settings/import-workbench";
import { JevSettingsCard } from "./JevSettingsCard";
+import { JEV_SERVICE } from "./service-catalog";
type CatalogStatus = {
loaded: boolean;
@@ -92,6 +93,11 @@ export function ModelConfigPage() {
// null = closed, "" = add flow, provider id = edit flow.
const [copyDraft, setCopyDraft] = useState<ProviderCopyDraft | null>(null);
const [setupFor, setSetupFor] = useState<string | null>(null);
+
+ // The Jev card opens the same dialog, straight on the Jev service.
+ const [jevSetup, setJevSetup] = useState(false);
+ // Bumped when that dialog stored a key, so the card re-reads what exists.
+ const [jevStatusRevision, setJevStatusRevision] = useState(0);
const [busyId, setBusyId] = useState<string | null>(null);
const [testingId, setTestingId] = useState<string | null>(null);
const [changingImageModel, setChangingImageModel] = useState(false);
@@ -383,7 +389,14 @@ export function ModelConfigPage() {
</section>
) : null}
- <JevSettingsCard settings={settings} />
+ <JevSettingsCard
+ settings={settings}
+ onConfigure={() => {
+ setJevSetup(true);
+ setSetupFor("");
+ }}
+ statusRevision={jevStatusRevision}
+ />
<section className="settings-card-block">
<div className="model-config-section-head">
@@ -513,13 +526,25 @@ export function ModelConfigPage() {
<ProviderSetupDialog
provider={editingProvider}
initialDraft={copyDraft}
- onClose={() => { setSetupFor(null); setCopyDraft(null); }}
+ initialService={jevSetup ? JEV_SERVICE : undefined}
+ onClose={() => {
+ setSetupFor(null);
+ setCopyDraft(null);
+ setJevSetup(false);
+ }}
imageModelIds={editingProvider
? imageGenerationCandidates
.filter((binding) => binding.providerId === editingProvider.id)
.map((binding) => binding.modelId)
: undefined}
onSaved={afterSaved}
+ onJevConfigured={() => {
+ setSetupFor(null);
+ setCopyDraft(null);
+ setJevSetup(false);
+ // The card is already mounted: tell it the key it read has changed.
+ setJevStatusRevision((revision) => revision + 1);
+ }}
vendors={vendors}
onPickSubscription={(vendor) => {
setSetupFor(null);
diff --git a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
index 5c873a69f..c28d5b40b 100644
--- a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
+++ b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
@@ -29,7 +29,8 @@ import { ModelSelectionPanes, useModelSelection } from "./ModelSelectionPanes";
import { ProviderConnectionFields } from "./ProviderConnectionFields";
import { useProbeFeedback } from "./useProbeFeedback";
import { ServiceChooser } from "./ServiceChooser";
-import { CUSTOM_SERVICE } from "./service-catalog";
+import { CUSTOM_SERVICE, JEV_SERVICE } from "./service-catalog";
+import { JevServiceForm } from "./JevServiceForm";
import { useRecommendedModelSelection } from "./useRecommendedModelSelection";
import type { ProviderCopyDraft } from "./provider-copy";
import {
@@ -60,6 +61,23 @@ function initialBaseUrl(provider?: ProviderPublic | null): string {
return providerSetupPreset(provider)?.baseUrl ?? provider?.baseUrl ?? "";
}
+/**
+ * Which service the dialog opens on: the caller's own choice first (Jev has no
+ * preset and no row), then a copied draft's format, then the edited row's.
+ */
+function initialServiceId(
+ initialService: string | null | undefined,
+ initialDraft: ProviderCopyDraft | null | undefined,
+ provider: ProviderPublic | null | undefined,
+): string {
+ if (initialService) return initialService;
+ if (!initialDraft) return serviceIdFor(provider);
+ return initialDraft.apiStyle === OPENCODE_GO_API_STYLE
+ ? NAMED_ENDPOINT_PRESETS.find((preset) => preset.apiStyle === OPENCODE_GO_API_STYLE)?.id ??
+ CUSTOM_SERVICE
+ : CUSTOM_SERVICE;
+}
+
export type ProviderSetupDialogProps = {
provider?: ProviderPublic | null;
initialDraft?: ProviderCopyDraft | null;
@@ -70,6 +88,10 @@ export type ProviderSetupDialogProps = {
vendors?: OAuthVendor[] | null;
/** Leaves this dialog for the vendor's browser sign-in. */
onPickSubscription?: (vendor: OAuthVendor) => void;
+ /** Opens straight on this service; Jev has no preset tile to land on. */
+ initialService?: string | null;
+ /** Jev was configured from inside this dialog. */
+ onJevConfigured?: () => void;
};
export function ProviderSetupDialog({
@@ -80,16 +102,16 @@ export function ProviderSetupDialog({
imageModelIds,
vendors,
onPickSubscription,
+ initialService,
+ onJevConfigured,
}: ProviderSetupDialogProps) {
const { t } = useTranslation();
const [imageModelDraft, setImageModelDraft] = useState<string[] | undefined>();
const editing = !!provider;
const apiKeyRef = useRef<HTMLInputElement>(null);
- const [service, setService] = useState(() => initialDraft
- ? initialDraft.apiStyle === OPENCODE_GO_API_STYLE
- ? NAMED_ENDPOINT_PRESETS.find((preset) => preset.apiStyle === OPENCODE_GO_API_STYLE)?.id ?? CUSTOM_SERVICE
- : CUSTOM_SERVICE
- : serviceIdFor(provider));
+ const [service, setService] = useState(() =>
+ initialServiceId(initialService, initialDraft, provider),
+ );
const [name, setName] = useState(() => initialDraft?.name ?? initialName(provider));
const [baseUrl, setBaseUrl] = useState(() => initialDraft?.baseUrl ?? initialBaseUrl(provider));
const [apiKey, setApiKey] = useState("");
@@ -111,6 +133,8 @@ export function ProviderSetupDialog({
const namedPreset = NAMED_ENDPOINT_PRESETS.find((preset) => preset.id === service);
const named = Boolean(namedPreset);
const custom = service === CUSTOM_SERVICE;
+ /** Jev never becomes a provider row, so it is a view of its own. */
+ const jevService = service === JEV_SERVICE;
const resolvedName = namedPreset ? name.trim() || namedPreset.name : name;
const resolvedBaseUrl = namedPreset?.baseUrl ?? baseUrl;
/*
@@ -504,10 +528,20 @@ export function ProviderSetupDialog({
current={service}
onPickService={pickService}
onPickSubscription={editing ? undefined : onPickSubscription}
+ showClassifiers={!editing}
/>
</>
);
+ /*
+ Jev is the one entry here that is not a provider row: a key and no models,
+ so it renders its own half of the dialog instead of the connection form and
+ the model panes.
+ */
+ const jevView = (
+ <JevServiceForm onClose={onClose} onConfigured={() => onJevConfigured?.()} />
+ );
+
return portalOverlay(
<div
className="overlay provider-setup-overlay"
@@ -524,7 +558,7 @@ export function ProviderSetupDialog({
aria-labelledby="provider-setup-title"
onClick={(event) => event.stopPropagation()}
>
- {chooserOpen ? chooserView : formView}
+ {chooserOpen ? chooserView : jevService ? jevView : formView}
</div>
{advancedOpen && (named || custom) ? (
diff --git a/apps/desktop/src/components/settings/ServiceChooser.tsx b/apps/desktop/src/components/settings/ServiceChooser.tsx
index e136592e2..14856be04 100644
--- a/apps/desktop/src/components/settings/ServiceChooser.tsx
+++ b/apps/desktop/src/components/settings/ServiceChooser.tsx
@@ -19,6 +19,7 @@ import {
CUSTOM_SERVICE,
customServiceOption,
filterServiceOptions,
+ jevServiceOption,
namedServiceOptions,
} from "./service-catalog";
@@ -30,6 +31,8 @@ export type ServiceChooserProps = {
disabled?: boolean;
onPickService: (id: string) => void;
onPickSubscription?: (vendor: OAuthVendor) => void;
+ /** Offers the classifier group; a new service, never an existing row. */
+ showClassifiers?: boolean;
};
type SubscriptionOption = { vendor: OAuthVendor; haystack: string };
@@ -42,6 +45,7 @@ export function ServiceChooser({
disabled = false,
onPickService,
onPickSubscription,
+ showClassifiers = false,
}: ServiceChooserProps) {
const { t } = useTranslation();
const [query, setQuery] = useState("");
@@ -64,6 +68,13 @@ export function ServiceChooser({
[onPickSubscription, vendors],
);
+ // Jev is offered where a service is added: an existing row cannot be turned
+ // into a classifier, so this group stays out of that flow.
+ const classifierOptions = useMemo(
+ () => (showClassifiers ? [jevServiceOption(t)] : []),
+ [showClassifiers, t],
+ );
+
const visibleServices = useMemo(
() => filterServiceOptions(serviceOptions, query),
[query, serviceOptions],
@@ -72,16 +83,25 @@ export function ServiceChooser({
() => filterServiceOptions(subscriptionOptions, query),
[query, subscriptionOptions],
);
- const nothingMatches = visibleServices.length === 0 && visibleSubscriptions.length === 0;
+ const visibleClassifiers = useMemo(
+ () => filterServiceOptions(classifierOptions, query),
+ [classifierOptions, query],
+ );
+ const nothingMatches =
+ visibleServices.length === 0 &&
+ visibleSubscriptions.length === 0 &&
+ visibleClassifiers.length === 0;
- // Enter prefers an API service over a subscription: a pick there only moves
- // to the key field, while a subscription opens the browser.
+ // Enter prefers a service the pick only moves to the key field for: the
+ // classifier keeps the same dialog, while a subscription leaves it.
const enterTarget = query.trim()
? visibleServices[0]
? `service:${visibleServices[0].id}`
- : visibleSubscriptions[0]
- ? `subscription:${visibleSubscriptions[0].vendor.vendorId}`
- : ""
+ : visibleClassifiers[0]
+ ? `service:${visibleClassifiers[0].id}`
+ : visibleSubscriptions[0]
+ ? `subscription:${visibleSubscriptions[0].vendor.vendorId}`
+ : ""
: "";
const pickService = (id: string) => {
@@ -93,6 +113,7 @@ export function ServiceChooser({
const pickEnterTarget = () => {
if (visibleServices[0]) pickService(visibleServices[0].id);
+ else if (visibleClassifiers[0]) pickService(visibleClassifiers[0].id);
else if (visibleSubscriptions[0]) pickSubscription(visibleSubscriptions[0].vendor);
else pickService(CUSTOM_SERVICE);
};
@@ -265,6 +286,40 @@ export function ServiceChooser({
</div>
</section>
) : null}
+
+ {visibleClassifiers.length > 0 ? (
+ <section className="service-chooser-group" aria-labelledby="service-chooser-classifiers">
+ <h4 id="service-chooser-classifiers" className="service-chooser-group-title">
+ {t("settings.chooserClassifiers")}
+ </h4>
+ <div className="service-chooser-grid">
+ {/* A classifier answers structured questions rather than holding a
+ conversation: it carries a key and no model list. */}
+ {visibleClassifiers.map((option) => (
+ <button
+ key={option.id}
+ type="button"
+ data-service-tile
+ data-service-id={option.id}
+ className={cx(
+ "service-chooser-tile",
+ enterTarget === `service:${option.id}` && "is-active",
+ )}
+ aria-current={option.id === current ? "true" : undefined}
+ disabled={disabled}
+ onKeyDown={onTileKeyDown}
+ onClick={() => pickService(option.id)}
+ >
+ <ServiceMonogram name={option.label} />
+ <span className="service-chooser-tile-copy">
+ <span className="service-chooser-tile-name">{option.label}</span>
+ <span className="service-chooser-tile-detail">{option.endpoint}</span>
+ </span>
+ </button>
+ ))}
+ </div>
+ </section>
+ ) : null}
</div>
</div>
);
diff --git a/apps/desktop/src/components/settings/jev-app-config.ts b/apps/desktop/src/components/settings/jev-app-config.ts
new file mode 100644
index 000000000..db21a2a3b
--- /dev/null
+++ b/apps/desktop/src/components/settings/jev-app-config.ts
@@ -0,0 +1,59 @@
+/**
+ * The app-wired half of Jev configuration: the real API calls, the settings
+ * write, and the key-status read both Jev surfaces show.
+ *
+ * Split from `jev-config.ts` so the ordering rules there stay testable without
+ * a renderer, an IPC bridge or a store.
+ */
+import { useEffect, useState } from "react";
+import type { AppSettings } from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import { useAppStore } from "../../stores/app-store";
+import type { JevConfigDeps } from "./jev-config";
+
+export type JevKeyStatus = "loading" | "configured" | "missing" | "unavailable";
+
+/** Jev is one field of the same AppSettings document, so it takes a full write. */
+export async function persistJevEnabled(enabled: boolean): Promise<void> {
+ const current = useAppStore.getState().settings;
+ if (!current) throw new Error("Settings are not ready");
+ const next: AppSettings = { ...current, jevEnabled: enabled };
+ await api.setSettings(next);
+ useAppStore.setState({ settings: next });
+}
+
+export function appJevConfigDeps(): JevConfigDeps {
+ return {
+ probe: (key) => api.testJevApiKey(key),
+ storeKey: (key) => api.setJevApiKey(key),
+ deleteKey: () => api.deleteJevApiKey(),
+ setEnabled: persistJevEnabled,
+ };
+}
+
+/**
+ * Whether a TypeSafe key is stored. The renderer only ever learns whether one
+ * exists, and a Host that cannot answer reads as `unavailable` — never as
+ * "no key", which would describe a configured install as unconfigured.
+ */
+export function useJevKeyStatus(
+ /** Bump to re-read: the service dialog reports a key it just stored this way. */
+ revision = 0,
+): readonly [JevKeyStatus, (next: JevKeyStatus) => void] {
+ const [status, setStatus] = useState<JevKeyStatus>("loading");
+ useEffect(() => {
+ let current = true;
+ void api.hasJevApiKey().then(
+ (hasKey) => {
+ if (current) setStatus(hasKey ? "configured" : "missing");
+ },
+ () => {
+ if (current) setStatus("unavailable");
+ },
+ );
+ return () => {
+ current = false;
+ };
+ }, [revision]);
+ return [status, setStatus] as const;
+}
diff --git a/apps/desktop/src/components/settings/jev-config.ts b/apps/desktop/src/components/settings/jev-config.ts
new file mode 100644
index 000000000..927c77cbb
--- /dev/null
+++ b/apps/desktop/src/components/settings/jev-config.ts
@@ -0,0 +1,64 @@
+/**
+ * The order Jev's credential and its switch move in.
+ *
+ * Adding Jev means "a key that works is stored, and the classifier is on", in
+ * that order: the key is checked against TypeSafe first, nothing is written
+ * when the check fails, and only a key that answered becomes `jevEnabled`. So
+ * an enabled Jev always has a key the Agent can actually spend.
+ *
+ * Removing Jev takes the switch down before the key is deleted, so no state in
+ * between can leave an enabled classifier without a key. Closing the dialog
+ * abandons an in-flight check the same way: cancel means nothing was kept.
+ *
+ * This lives outside the components because the settings card and the service
+ * dialog both drive it, and because the order is the part worth testing. It
+ * imports nothing at runtime: the caller supplies the effects.
+ */
+import type { JevKeyCheckResult } from "@pi-desktop/shared";
+
+export type JevConfigDeps = {
+ /** Ask TypeSafe whether the key works; never stores anything. */
+ probe: (key: string) => Promise<JevKeyCheckResult>;
+ storeKey: (key: string) => Promise<void>;
+ deleteKey: () => Promise<void>;
+ setEnabled: (enabled: boolean) => Promise<void>;
+};
+
+export type JevAddOutcome =
+ | { ok: true }
+ | { ok: false; reason: "missing-key" }
+ | { ok: false; reason: "cancelled" }
+ | { ok: false; reason: "check-failed"; status?: number; message?: string };
+
+/**
+ * Store `apiKey` and turn Jev on, or leave everything untouched.
+ *
+ * `signal` abandons the whole action: a dialog the user closed while the check
+ * was still in flight must not come back later with a stored credential and an
+ * enabled classifier. The check is the long part, so it is the only step that
+ * needs the guard — everything after it has already been decided.
+ */
+export async function addJevService(
+ deps: JevConfigDeps,
+ apiKey: string,
+ signal?: AbortSignal,
+): Promise<JevAddOutcome> {
+ const key = apiKey.trim();
+ if (!key) return { ok: false, reason: "missing-key" };
+ const check = await deps.probe(key);
+ if (signal?.aborted) return { ok: false, reason: "cancelled" };
+ if (!check.ok) {
+ return { ok: false, reason: "check-failed", status: check.status, message: check.message };
+ }
+ await deps.storeKey(key);
+ await deps.setEnabled(true);
+ return { ok: true };
+}
+
+/** Turn Jev off and drop the key; disabled first, so neither step is orphaned. */
+export async function removeJevService(
+ deps: Pick<JevConfigDeps, "deleteKey" | "setEnabled">,
+): Promise<void> {
+ await deps.setEnabled(false);
+ await deps.deleteKey();
+}
diff --git a/apps/desktop/src/components/settings/service-catalog.ts b/apps/desktop/src/components/settings/service-catalog.ts
index 975b6b593..b0eeb8a51 100644
--- a/apps/desktop/src/components/settings/service-catalog.ts
+++ b/apps/desktop/src/components/settings/service-catalog.ts
@@ -5,7 +5,18 @@
* the preset's canonical name, id, vendor key, aliases, base URL and host, so
* "kimi", "moonshot" and "api.moonshot.cn" all land on the same entry.
*/
-import { NAMED_ENDPOINT_PRESETS, type NamedEndpointPreset } from "@pi-desktop/shared";
+import {
+ NAMED_ENDPOINT_PRESETS,
+ TYPESAFE_SYSTEM_ONE_URL,
+ type NamedEndpointPreset,
+} from "@pi-desktop/shared";
+
+/**
+ * Jev is offered where a service is added, not where a provider is edited: it
+ * owns no provider row and no model list, so it is never a target of "change
+ * the service on this row".
+ */
+export const JEV_SERVICE = "jev";
export const CUSTOM_SERVICE = "custom";
@@ -66,3 +77,19 @@ export function filterServiceOptions<T extends { haystack: string }>(
if (!needle) return [...options];
return options.filter((option) => option.haystack.includes(needle));
}
+
+/**
+ * TypeSafe Jev, the classifier on the add path. Its detail line names the
+ * address the key is spent on, because there is no model list to describe.
+ */
+export function jevServiceOption(translate: Translate): ServiceOption {
+ const label = translate("settings.jevTitle");
+ const endpoint = endpointLabel(TYPESAFE_SYSTEM_ONE_URL);
+ return {
+ id: JEV_SERVICE,
+ label,
+ endpoint,
+ haystack:
+ `${label} jev typesafe classifier ${endpoint} ${TYPESAFE_SYSTEM_ONE_URL}`.toLowerCase(),
+ };
+}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index b56cfac32..128356947 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -29,6 +29,7 @@ import type {
PendingInteractiveRequests,
AgentInstructionFile,
AppSettings,
+ JevKeyCheckResult,
CommandShellCatalog,
AppVersionInfo,
BrowserAction,
@@ -667,11 +668,16 @@ export const api = {
invoke(IPC.invoke.settingsSet, validateSettingsWrite(settings)),
/** Store the Jev key in Host secure storage; it is never returned to renderer state. */
setJevApiKey: (value: string) =>
- invoke(IPC.invoke.secretsSet, { secretRef: JEV_API_KEY_SECRET_REF, value }),
- deleteJevApiKey: () =>
- invoke(IPC.invoke.secretsDelete, JEV_API_KEY_SECRET_REF),
+ invoke<void>(IPC.invoke.secretsSet, { secretRef: JEV_API_KEY_SECRET_REF, value }),
+ deleteJevApiKey: () => invoke<void>(IPC.invoke.secretsDelete, JEV_API_KEY_SECRET_REF),
hasJevApiKey: () =>
invoke<{ has: boolean }>(IPC.invoke.secretsHas, JEV_API_KEY_SECRET_REF).then((result) => result.has),
+ /**
+ * Ask TypeSafe whether this key works, without storing anything. Jev keeps
+ * a key only after this answered it; the check text is TypeSafe's own.
+ */
+ testJevApiKey: (value: string) =>
+ invoke<JevKeyCheckResult>(IPC.invoke.jevTest, value),
configSyncGetState: () => invoke<ConfigSyncState>(IPC.invoke.configSyncGetState),
configSyncConfigure: (input: ConfigSyncConfigureInput) =>
invoke<ConfigSyncState>(IPC.invoke.configSyncConfigure, input),
diff --git a/apps/desktop/src/styles/model-config.css b/apps/desktop/src/styles/model-config.css
index c9d2c95bd..f51d5be23 100644
--- a/apps/desktop/src/styles/model-config.css
+++ b/apps/desktop/src/styles/model-config.css
@@ -103,6 +103,30 @@
flex: none;
}
+/*
+ The Jev service form: an explanation, the one key field and what saving does.
+ It is the whole form, so it stacks without the provider form's labelled rows.
+*/
+.jev-setup {
+ display: grid;
+ gap: 10px;
+}
+
+.jev-setup-description,
+.jev-setup-privacy,
+.jev-setup-status,
+.jev-setup-note {
+ margin: 0;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+ line-height: var(--leading-body);
+}
+
+/* The key's current state, beside the field that would replace it. */
+.jev-setup-status {
+ color: var(--ds-text-primary);
+}
+
/*
Named services are Service + key. Custom is Service, then Name beside URL,
then the key beside API format. An unchosen service is one searchable picker
diff --git a/apps/desktop/src/styles/settings.css b/apps/desktop/src/styles/settings.css
index 542cf0369..7d95e7719 100644
--- a/apps/desktop/src/styles/settings.css
+++ b/apps/desktop/src/styles/settings.css
@@ -1072,17 +1072,15 @@
line-height: var(--leading-body);
}
-.jev-settings-key-form {
- display: grid;
- gap: 10px;
- padding: 0 16px 16px;
-}
-
-.jev-settings-key-actions {
+/*
+ The Jev row's control column: two actions and the switch. The row metric
+ above only matches a bare toggle, so the group keeps its own height.
+*/
+.jev-settings-controls {
display: flex;
- flex-wrap: wrap;
+ align-items: center;
gap: 8px;
- justify-content: flex-end;
+ min-height: var(--ds-field-height);
}
/*
diff --git a/apps/desktop/test/jev-api-key-check.test.mjs b/apps/desktop/test/jev-api-key-check.test.mjs
new file mode 100644
index 000000000..ba462047b
--- /dev/null
+++ b/apps/desktop/test/jev-api-key-check.test.mjs
@@ -0,0 +1,118 @@
+/**
+ * Contract test for the TypeSafe key check behind Jev (settings IA, D625).
+ *
+ * Jev keeps a key only when TypeSafe answered it, so this probe is the gate:
+ * it must ask the same address and classifier the Agent's `JevClassify` tool
+ * uses, report a refusal with its status, never leak the key into its own
+ * message, and answer a hung or unreachable service with a sentence instead
+ * of a rejection.
+ */
+import assert from "node:assert/strict";
+import test from "node:test";
+import { JEV_PROBE_TIMEOUT_MS, probeJevApiKey } from "../electron/main/jev-probe.ts";
+import {
+ TYPESAFE_JEV_MODEL_ID,
+ TYPESAFE_SYSTEM_ONE_URL,
+} from "../../../packages/shared/src/secret-refs.ts";
+
+const KEY = "typesafe-fixture-key";
+
+/** A fetch stand-in that records the one request it received. */
+function recordingFetch(response) {
+ const calls = [];
+ return {
+ calls,
+ fetch: async (url, init) => {
+ calls.push({ url, init });
+ return typeof response === "function" ? response(url, init) : response;
+ },
+ };
+}
+
+function jsonResponse({ ok, status, body = "" }) {
+ return {
+ ok,
+ status,
+ text: async () => body,
+ };
+}
+
+test("the check asks the System One endpoint the classifier tool uses", async () => {
+ const { calls, fetch } = recordingFetch(jsonResponse({ ok: true, status: 200 }));
+ const result = await probeJevApiKey(KEY, { fetchImpl: fetch });
+
+ assert.deepEqual(result, { ok: true, status: 200 });
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].url, TYPESAFE_SYSTEM_ONE_URL);
+ assert.equal(calls[0].init.method, "POST");
+ assert.equal(calls[0].init.headers.authorization, `Bearer ${KEY}`);
+ assert.equal(calls[0].init.headers["content-type"], "application/json");
+ assert.ok(calls[0].init.signal, "the request carries an abort signal");
+ const body = JSON.parse(calls[0].init.body);
+ assert.equal(body.model, TYPESAFE_JEV_MODEL_ID);
+ assert.equal(Object.keys(body.questions).length, 1);
+ const [question] = Object.values(body.questions);
+ assert.equal(question.type, "noul");
+ assert.deepEqual(Object.keys(question.criteria), ["true", "false"]);
+});
+
+test("a trimmed key is what travels, and a blank key sends nothing", async () => {
+ const { calls, fetch } = recordingFetch(jsonResponse({ ok: true, status: 200 }));
+ await probeJevApiKey(` ${KEY} `, { fetchImpl: fetch });
+ assert.equal(calls[0].init.headers.authorization, `Bearer ${KEY}`);
+
+ const blank = recordingFetch(jsonResponse({ ok: true, status: 200 }));
+ const result = await probeJevApiKey(" ", { fetchImpl: blank.fetch });
+ assert.equal(result.ok, false);
+ assert.deepEqual(blank.calls, [], "a blank key must not reach the network");
+});
+
+test("a refused key reports TypeSafe's status without repeating the key", async () => {
+ const { fetch } = recordingFetch(
+ jsonResponse({ ok: false, status: 401, body: `invalid api key ${KEY}` }),
+ );
+ const result = await probeJevApiKey(KEY, { fetchImpl: fetch });
+
+ assert.equal(result.ok, false);
+ assert.equal(result.status, 401);
+ assert.match(result.message, /401/);
+ assert.ok(!result.message.includes(KEY), "the key must not be echoed back");
+ assert.match(result.message, /\[redacted\]/);
+});
+
+test("a refusal without a body still names the status", async () => {
+ const { fetch } = recordingFetch(jsonResponse({ ok: false, status: 403 }));
+ const result = await probeJevApiKey(KEY, { fetchImpl: fetch });
+ assert.deepEqual(result, { ok: false, status: 403, message: "TypeSafe returned 403" });
+});
+
+test("an unreachable service answers with a message, not a rejection", async () => {
+ const { fetch } = recordingFetch(() => {
+ throw new Error(`connect ECONNREFUSED ${KEY}`);
+ });
+ const result = await probeJevApiKey(KEY, { fetchImpl: fetch });
+ assert.equal(result.ok, false);
+ assert.equal(result.status, undefined);
+ assert.ok(!result.message.includes(KEY), "a transport error must not leak the key");
+});
+
+test("a silent service is reported as a timeout", async () => {
+ const { fetch } = recordingFetch(
+ (_url, init) =>
+ new Promise((_resolve, reject) => {
+ init.signal.addEventListener("abort", () => {
+ const error = new Error("aborted");
+ error.name = "TimeoutError";
+ reject(error);
+ });
+ }),
+ );
+ const result = await probeJevApiKey(KEY, { fetchImpl: fetch, timeoutMs: 20 });
+ assert.equal(result.ok, false);
+ assert.match(result.message, /did not answer/);
+ assert.ok(!result.message.includes(KEY));
+});
+
+test("the default timeout is bounded", () => {
+ assert.ok(JEV_PROBE_TIMEOUT_MS > 0 && JEV_PROBE_TIMEOUT_MS <= 60_000);
+});
diff --git a/apps/desktop/test/jev-config.test.mjs b/apps/desktop/test/jev-config.test.mjs
new file mode 100644
index 000000000..8b991ab1b
--- /dev/null
+++ b/apps/desktop/test/jev-config.test.mjs
@@ -0,0 +1,103 @@
+/**
+ * The order Jev's credential and switch move in.
+ *
+ * Adding Jev stores a key only after TypeSafe answered it and then enables the
+ * classifier; removing Jev disables it before the key is deleted. Both orders
+ * are the contract this test pins, because either one reversed leaves a state
+ * the Agent cannot run in: an enabled classifier without a key, or a key with
+ * nothing to spend it on.
+ */
+import assert from "node:assert/strict";
+import test from "node:test";
+import { addJevService, removeJevService } from "../src/components/settings/jev-config.ts";
+
+const KEY = "typesafe-fixture-key";
+
+/** Records what the caller asked for, in the order it happened. */
+function deps({ check = { ok: true, status: 200 }, failStore = false } = {}) {
+ const log = [];
+ return {
+ log,
+ config: {
+ probe: async (key) => {
+ log.push(["probe", key]);
+ return check;
+ },
+ storeKey: async (key) => {
+ log.push(["store", key]);
+ if (failStore) throw new Error("secret store unavailable");
+ },
+ deleteKey: async () => {
+ log.push(["delete"]);
+ },
+ setEnabled: async (enabled) => {
+ log.push(["enabled", enabled]);
+ },
+ },
+ };
+}
+
+test("a key that answered is stored, then Jev is enabled", async () => {
+ const { log, config } = deps();
+ const outcome = await addJevService(config, ` ${KEY} `);
+
+ assert.deepEqual(outcome, { ok: true });
+ assert.deepEqual(log, [
+ ["probe", KEY],
+ ["store", KEY],
+ ["enabled", true],
+ ]);
+});
+
+test("a blank key is never probed and never stored", async () => {
+ const { log, config } = deps();
+ assert.deepEqual(await addJevService(config, " "), { ok: false, reason: "missing-key" });
+ assert.deepEqual(log, []);
+});
+
+test("a check the user closed the dialog on is cancelled, not stored", async () => {
+ const { log, config } = deps();
+ const controller = new AbortController();
+ // The dialog closes while TypeSafe is still thinking, then answers ok.
+ config.probe = async (key) => {
+ log.push(["probe", key]);
+ controller.abort();
+ return { ok: true, status: 200 };
+ };
+ const outcome = await addJevService(config, KEY, controller.signal);
+
+ assert.deepEqual(outcome, { ok: false, reason: "cancelled" });
+ assert.deepEqual(log, [["probe", KEY]]);
+});
+
+test("a key TypeSafe refused is reported and nothing is written", async () => {
+ const { log, config } = deps({
+ check: { ok: false, status: 401, message: "TypeSafe returned 401: invalid key" },
+ });
+ const outcome = await addJevService(config, KEY);
+
+ assert.deepEqual(outcome, {
+ ok: false,
+ reason: "check-failed",
+ status: 401,
+ message: "TypeSafe returned 401: invalid key",
+ });
+ // Only the check happened: a refused key must not reach the secret store,
+ // and must not switch the classifier on.
+ assert.deepEqual(log, [["probe", KEY]]);
+});
+
+test("a store failure surfaces and leaves Jev disabled", async () => {
+ const { log, config } = deps({ failStore: true });
+ await assert.rejects(() => addJevService(config, KEY), /secret store unavailable/);
+ assert.deepEqual(log, [
+ ["probe", KEY],
+ ["store", KEY],
+ ]);
+});
+
+test("removing Jev disables it before the key is deleted", async () => {
+ const { log, config } = deps();
+ await removeJevService(config);
+ assert.deepEqual(log, [["enabled", false], ["delete"]]);
+});
diff --git a/apps/desktop/test/jev-service-setup-user-path.test.mjs b/apps/desktop/test/jev-service-setup-user-path.test.mjs
new file mode 100644
index 000000000..ffd97a818
--- /dev/null
+++ b/apps/desktop/test/jev-service-setup-user-path.test.mjs
@@ -0,0 +1,397 @@
+/**
+ * Isolated Electron user path for adding Jev as a service (D625).
+ *
+ * Jev is offered where a service is added, not where an existing row is
+ * edited, and adding it is one action with two steps: check the TypeSafe key,
+ * then store it and turn the classifier on. The check comes first and nothing
+ * is written when it fails — otherwise a saved key would be a key the Agent
+ * cannot spend, and "enabled" would mean nothing.
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import test from "node:test";
+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+const fixtureSource = String.raw`
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { JEV_API_KEY_SECRET_REF } from "@pi-desktop/shared";
+import { JevSettingsCard } from "../../apps/desktop/src/components/settings/JevSettingsCard";
+import { ProviderSetupDialog } from "../../apps/desktop/src/components/settings/ProviderSetupDialog";
+import { ServiceChooser } from "../../apps/desktop/src/components/settings/ServiceChooser";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+const apiCalls = [];
+let savedKey;
+let jevCheck = { ok: true, status: 200 };
+/** Set to hold the next check open, so a test can close the dialog mid-flight. */
+let pendingCheck = null;
+let pickedService = null;
+let configured = false;
+let savedSettings = {
+ defaultMode: "agent",
+ theme: "light",
+ language: "en",
+ developerMode: false,
+ jevEnabled: false,
+};
+window.piDesktop = {
+ platform: "darwin",
+ on() { return () => {}; },
+ async invoke(channel, ...args) {
+ const input = args[0];
+ apiCalls.push({ channel, input });
+ switch (channel) {
+ case "pi-desktop/jev/test":
+ if (pendingCheck) {
+ return new Promise((resolve) => {
+ pendingCheck.resolve = () => resolve({ ok: true, data: pendingCheck.result });
+ });
+ }
+ return { ok: true, data: jevCheck };
+ case "pi-desktop/secrets/has":
+ if (input !== JEV_API_KEY_SECRET_REF) throw new Error("unexpected secret ref");
+ return { ok: true, data: { has: typeof savedKey === "string" } };
+ case "pi-desktop/secrets/set":
+ if (input.secretRef !== JEV_API_KEY_SECRET_REF) throw new Error("unexpected secret ref");
+ savedKey = input.value;
+ return { ok: true, data: undefined };
+ case "pi-desktop/settings/set":
+ savedSettings = input;
+ useAppStore.setState({ settings: savedSettings });
+ return { ok: true, data: undefined };
+ default:
+ throw new Error("Unexpected fixture IPC: " + channel);
+ }
+ },
+};
+
+await i18n.use(initReactI18next).init({
+ lng: "en",
+ fallbackLng: "en",
+ keySeparator: false,
+ resources: { en: { translation: flattenCatalog(catalogs.en) } },
+ interpolation: { escapeValue: false },
+});
+useAppStore.setState({ settings: savedSettings });
+
+const frame = () => new Promise(requestAnimationFrame);
+async function settle() { await frame(); await frame(); }
+async function waitFor(predicate, message) {
+ for (let attempt = 0; attempt < 120; attempt += 1) {
+ await settle();
+ const value = predicate();
+ if (value) return value;
+ }
+ throw new Error(message);
+}
+function button(label) {
+ return [...document.querySelectorAll("button")]
+ .find((candidate) => candidate.textContent.trim() === label);
+}
+function setValue(input, value) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;
+ valueSetter.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+}
+function jevTile() {
+ return [...document.querySelectorAll('[data-service-id="jev"]')][0];
+}
+
+const rootNode = createRoot(document.getElementById("root"));
+function mount(element) {
+ flushSync(() => rootNode.render(element));
+}
+function jevDialog(key) {
+ return React.createElement(ProviderSetupDialog, {
+ key,
+ provider: null,
+ initialService: "jev",
+ onClose: () => { mount(null); },
+ onSaved: () => {},
+ onJevConfigured: () => { configured = true; },
+ });
+}
+
+/**
+ * The settings page's own wiring: the card opens the dialog, and the dialog's
+ * report of a stored key is what makes the card read the state again.
+ */
+function JevSurface() {
+ const settings = useAppStore((state) => state.settings);
+ const [open, setOpen] = React.useState(false);
+ const [revision, setRevision] = React.useState(0);
+ return React.createElement(
+ React.Fragment,
+ null,
+ React.createElement(JevSettingsCard, {
+ settings: settings ?? undefined,
+ onConfigure: () => setOpen(true),
+ statusRevision: revision,
+ }),
+ open
+ ? React.createElement(ProviderSetupDialog, {
+ provider: null,
+ initialService: "jev",
+ onClose: () => setOpen(false),
+ onSaved: () => {},
+ onJevConfigured: () => {
+ setOpen(false);
+ setRevision((value) => value + 1);
+ configured = true;
+ },
+ })
+ : null,
+ );
+}
+
+window.jevServiceSetupProbe = async () => {
+ // 1) The add path offers Jev beside the API services.
+ mount(React.createElement(ServiceChooser, {
+ showClassifiers: true,
+ onPickService: (id) => { pickedService = id; },
+ }));
+ await settle();
+ const offersClassifiers = document.body.innerText.includes("Classifiers");
+ const tile = jevTile();
+ if (!tile) throw new Error("the add path must offer Jev");
+ flushSync(() => tile.click());
+ await settle();
+ const pickedJev = pickedService === "jev";
+
+ // 2) Editing an existing row cannot turn it into a classifier.
+ mount(React.createElement(ServiceChooser, {
+ showClassifiers: false,
+ onPickService: () => {},
+ }));
+ await settle();
+ const hiddenWhenEditing = !jevTile();
+ const hiddenGroup = !document.body.innerText.includes("Classifiers");
+
+ // 3) The card and the dialog, wired the way the settings page wires them:
+ // adding Jev checks the key, stores it, turns Jev on, and the card reads it.
+ apiCalls.length = 0;
+ savedKey = undefined;
+ configured = false;
+ jevCheck = { ok: true, status: 200 };
+ mount(React.createElement(JevSurface));
+ await waitFor(() => document.body.innerText.includes("API key not configured"), "the card did not read the empty state");
+ flushSync(() => button("Add key").click());
+ await waitFor(() => !!document.querySelector('input[aria-label="TypeSafe API key"]'), "the Jev form did not open");
+ // The dialog is portaled onto documentElement, so the whole page is read.
+ const privacyNoticeShown = await waitFor(
+ () => document.documentElement.innerText.includes("sent directly to TypeSafe"),
+ "the Jev form must carry the privacy notice",
+ );
+ const noModelPanes = !document.documentElement.innerText.includes("Models from this service");
+ setValue(document.querySelector('input[aria-label="TypeSafe API key"]'), "jev-ui-fixture-key");
+ await settle();
+ flushSync(() => button("Check and save").click());
+ await waitFor(
+ () => document.body.innerText.includes("API key saved securely"),
+ "the card did not pick up the key the dialog stored",
+ );
+ const switchOn = document.querySelector('[role="switch"][aria-label="Enable Jev for Agent"]').getAttribute("aria-checked") === "true";
+ const dialogClosed = !document.querySelector('input[aria-label="TypeSafe API key"]');
+ // The check, the store and the switch, in that order.
+ const flow = apiCalls.filter((call) => call.channel !== "pi-desktop/secrets/has");
+ const checkedFirst = flow[0]?.channel === "pi-desktop/jev/test";
+ const checkedTheTypedKey = checkedFirst && flow[0].input === "jev-ui-fixture-key";
+ const storedAfterChecking = flow[1]?.channel === "pi-desktop/secrets/set"
+ && flow[1].input.secretRef === JEV_API_KEY_SECRET_REF
+ && flow[1].input.value === "jev-ui-fixture-key";
+ const enabledAfterStoring = flow[2]?.channel === "pi-desktop/settings/set"
+ && flow[2].input.jevEnabled === true;
+
+ // 4) A key TypeSafe refuses is never stored and never enabled.
+ apiCalls.length = 0;
+ savedKey = undefined;
+ configured = false;
+ useAppStore.setState({ toasts: [] });
+ jevCheck = { ok: false, status: 401, message: "TypeSafe returned 401: invalid api key" };
+ mount(jevDialog("refused"));
+ await waitFor(() => !!document.querySelector('input[aria-label="TypeSafe API key"]'), "the Jev form did not reopen");
+ setValue(document.querySelector('input[aria-label="TypeSafe API key"]'), "jev-rejected-key");
+ await settle();
+ flushSync(() => button("Check and save").click());
+ await waitFor(() => apiCalls.some((call) => call.channel === "pi-desktop/jev/test"), "the key was never checked");
+ await settle();
+ await settle();
+ const refused = {
+ nothingStored: savedKey === undefined
+ && !apiCalls.some((call) => call.channel === "pi-desktop/secrets/set"),
+ nothingEnabled: !apiCalls.some((call) => call.channel === "pi-desktop/settings/set"),
+ stillOpen: !!document.querySelector('input[aria-label="TypeSafe API key"]'),
+ notConfigured: configured === false,
+ reported: useAppStore.getState().toasts.some(
+ (item) => item.variant === "error" && item.message.includes("401"),
+ ),
+ };
+
+ // 5) Closing the dialog while the check is in flight cancels the action: an
+ // abandoned dialog must not leave a stored credential behind.
+ apiCalls.length = 0;
+ savedKey = undefined;
+ configured = false;
+ useAppStore.setState({ toasts: [] });
+ pendingCheck = { resolve: null, result: { ok: true, status: 200 } };
+ mount(jevDialog("abandoned"));
+ await waitFor(() => !!document.querySelector('input[aria-label="TypeSafe API key"]'), "the Jev form did not open");
+ setValue(document.querySelector('input[aria-label="TypeSafe API key"]'), "jev-abandoned-key");
+ await settle();
+ flushSync(() => button("Check and save").click());
+ await waitFor(() => apiCalls.some((call) => call.channel === "pi-desktop/jev/test"), "the check never started");
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ await waitFor(() => !document.querySelector('input[aria-label="TypeSafe API key"]'), "Escape did not close the Jev form");
+ flushSync(() => pendingCheck.resolve());
+ await settle();
+ await settle();
+ const abandoned = {
+ nothingStored: savedKey === undefined
+ && !apiCalls.some((call) => call.channel === "pi-desktop/secrets/set"),
+ nothingEnabled: !apiCalls.some((call) => call.channel === "pi-desktop/settings/set"),
+ noSuccessToast: !useAppStore.getState().toasts.some((item) => item.variant === "success"),
+ };
+ pendingCheck = null;
+
+ return {
+ offersClassifiers,
+ pickedJev,
+ hiddenWhenEditing,
+ hiddenGroup,
+ privacyNoticeShown,
+ noModelPanes,
+ switchOn,
+ dialogClosed,
+ checkedFirst,
+ checkedTheTypedKey,
+ storedAfterChecking,
+ enabledAfterStoring,
+ refusedNothingStored: refused.nothingStored,
+ refusedNothingEnabled: refused.nothingEnabled,
+ refusedStaysOpen: refused.stillOpen,
+ refusedNotConfigured: refused.notConfigured,
+ refusedReported: refused.reported,
+ abandonedNothingStored: abandoned.nothingStored,
+ abandonedNothingEnabled: abandoned.nothingEnabled,
+ abandonedSilent: abandoned.noSuccessToast,
+ };
+};
+`;
+
+test("adding Jev checks the key before storing it, enables it on success, and cancels on close", {
+ timeout: 60_000,
+ skip:
+ process.platform === "linux" && !process.env.DISPLAY
+ ? "Isolated Electron UI test requires a display"
+ : false,
+}, async () => {
+ const temp = await mkdtemp(join(root, "apps/desktop/.jev-service-ui-"));
+ try {
+ await build({
+ stdin: {
+ contents: fixtureSource,
+ resolveDir: join(root, "scripts", "e2e"),
+ sourcefile: join(root, "scripts", "e2e", "jev-service-setup.jsx"),
+ loader: "tsx",
+ },
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "esm",
+ jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(
+ join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><body><div id="root"></div><script type="module" src="renderer.js"></script>',
+ );
+ await writeFile(
+ join(temp, "main.cjs"),
+ `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({ show: false, width: 1000, height: 760,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ win.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ const result = await win.webContents.executeJavaScript("window.jevServiceSetupProbe()");
+ console.log("JEV_SERVICE_PROBE " + JSON.stringify(result));
+ app.exit(0);
+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }
+});
+`,
+ );
+
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => { output += chunk; });
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+ assert.equal(code, 0, output.slice(-6000));
+ const line = output.split(/\r?\n/).find((item) => item.startsWith("JEV_SERVICE_PROBE "));
+ assert(line, output.slice(-6000));
+ const result = JSON.parse(line.slice("JEV_SERVICE_PROBE ".length));
+ assert.deepEqual(result, {
+ offersClassifiers: true,
+ pickedJev: true,
+ hiddenWhenEditing: true,
+ hiddenGroup: true,
+ privacyNoticeShown: true,
+ noModelPanes: true,
+ switchOn: true,
+ dialogClosed: true,
+ checkedFirst: true,
+ checkedTheTypedKey: true,
+ storedAfterChecking: true,
+ enabledAfterStoring: true,
+ refusedNothingStored: true,
+ refusedNothingEnabled: true,
+ refusedStaysOpen: true,
+ refusedNotConfigured: true,
+ refusedReported: true,
+ abandonedNothingStored: true,
+ abandonedNothingEnabled: true,
+ abandonedSilent: true,
+ });
+ } finally {
+ await rm(temp, { recursive: true, force: true });
+ }
+});
diff --git a/apps/desktop/test/jev-settings-user-path.test.mjs b/apps/desktop/test/jev-settings-user-path.test.mjs
index 2b76c0160..f67e4242c 100644
--- a/apps/desktop/test/jev-settings-user-path.test.mjs
+++ b/apps/desktop/test/jev-settings-user-path.test.mjs
@@ -1,3 +1,15 @@
+/**
+ * Isolated Electron user path for Jev settings (D625, settings IA).
+ *
+ * What the card is now: the state of the integration and the way in. It reads
+ * whether a TypeSafe key is stored, lets the switch move only when one is, and
+ * sends the user to the service dialog to add or replace the key — it never
+ * stores a key itself. Removing the key takes the switch down first.
+ *
+ * The key is written by the service dialog (see the Jev service setup test);
+ * this fixture stands in for that by storing one in the fake Host and
+ * remounting the card.
+ */
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { createRequire } from "node:module";
@@ -22,6 +34,7 @@ import { useAppStore } from "../../apps/desktop/src/stores/app-store";
const apiCalls = [];
let savedKey;
+let configureClicks = 0;
let savedSettings = {
defaultMode: "agent",
theme: "light",
@@ -37,11 +50,8 @@ window.piDesktop = {
apiCalls.push({ channel, input });
switch (channel) {
case "pi-desktop/secrets/has":
+ if (input !== JEV_API_KEY_SECRET_REF) throw new Error("unexpected secret ref");
return { ok: true, data: { has: typeof savedKey === "string" } };
- case "pi-desktop/secrets/set":
- if (input.secretRef !== JEV_API_KEY_SECRET_REF) throw new Error("unexpected secret ref");
- savedKey = input.value;
- return { ok: true, data: undefined };
case "pi-desktop/secrets/delete":
if (input !== JEV_API_KEY_SECRET_REF) throw new Error("unexpected secret ref");
savedKey = undefined;
@@ -64,9 +74,16 @@ await i18n.use(initReactI18next).init({
interpolation: { escapeValue: false },
});
useAppStore.setState({ settings: savedSettings });
+
function JevSettingsHarness() {
const settings = useAppStore((state) => state.settings);
- return React.createElement(JevSettingsCard, { settings: settings ?? undefined });
+ const [round, setRound] = React.useState(0);
+ window.__remount = () => setRound((value) => value + 1);
+ return React.createElement(JevSettingsCard, {
+ key: round,
+ settings: settings ?? undefined,
+ onConfigure: () => { configureClicks += 1; },
+ });
}
const rootNode = createRoot(document.getElementById("root"));
flushSync(() => rootNode.render(React.createElement(JevSettingsHarness)));
@@ -88,51 +105,64 @@ function button(label) {
window.jevSettingsProbe = async () => {
await waitFor(() => document.body.innerText.includes("API key not configured"), "initial key state missing");
- const toggle = document.querySelector('[role="switch"][aria-label="Enable Jev for Agent"]');
- if (!toggle?.disabled) throw new Error("Jev must stay disabled until a key is saved");
- const initialToggleDisabled = toggle.disabled;
+ const toggle = () => document.querySelector('[role="switch"][aria-label="Enable Jev for Agent"]');
+ if (!toggle()) throw new Error("the Jev switch is missing");
+ const initialToggleDisabled = toggle().disabled;
- const input = document.querySelector('input[aria-label="TypeSafe API key"]');
- if (!input) throw new Error("TypeSafe API key field is missing");
- const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;
- valueSetter.call(input, "jev-ui-fixture-key");
- input.dispatchEvent(new Event("input", { bubbles: true }));
+ const addKey = button("Add key");
+ if (!addKey) throw new Error("the card must offer adding a key");
+ flushSync(() => addKey.click());
await settle();
- const save = button("Save key");
- if (!save || save.disabled) throw new Error("Save action did not enable for a key");
- flushSync(() => save.click());
- await waitFor(() => document.body.innerText.includes("API key saved securely"), "saved key state was not shown");
- const keySavedInHost = typeof savedKey === "string";
- if (input.value !== "") throw new Error("Saved key draft should be cleared");
+ const configureOpened = configureClicks === 1;
- const enable = document.querySelector('[role="switch"][aria-label="Enable Jev for Agent"]');
- flushSync(() => enable.click());
- await waitFor(() => enable.getAttribute("aria-checked") === "true", "Jev setting did not turn on");
+ // Without a key the switch stays refused, whatever the card offers.
+ flushSync(() => toggle().click());
+ await settle();
+ // Pressing a switch that has no key behind it must not write a setting.
+ const refusedWithoutKey = toggle().getAttribute("aria-checked") === "false"
+ && !apiCalls.some((call) => call.channel === "pi-desktop/settings/set");
- flushSync(() => button("Remove key").click());
+ // A key the service dialog stored is what the next mount reads.
+ savedKey = "jev-ui-fixture-key";
+ flushSync(() => window.__remount());
+ await waitFor(() => document.body.innerText.includes("API key saved securely"), "configured state missing");
+ const replaceOffered = Boolean(button("Replace key"));
+ const removeOffered = Boolean(button("Remove key"));
+
+ flushSync(() => toggle().click());
+ await waitFor(() => toggle().getAttribute("aria-checked") === "true", "Jev setting did not turn on");
+
+ const remove = button("Remove key");
+ if (!remove) throw new Error("removing the key must stay possible");
+ flushSync(() => remove.click());
await waitFor(() => document.body.innerText.includes("API key not configured"), "removed key state was not shown");
- const finalToggle = document.querySelector('[role="switch"][aria-label="Enable Jev for Agent"]');
- const writes = apiCalls.filter((call) => call.channel === "pi-desktop/settings/set");
- const secretWrites = apiCalls.filter((call) => [
- "pi-desktop/secrets/set", "pi-desktop/secrets/delete",
- ].includes(call.channel));
+
+ const finalToggle = toggle();
+ const settingsWrites = apiCalls.filter((call) => call.channel === "pi-desktop/settings/set");
+ const lastDisable = apiCalls.findLastIndex(
+ (call) => call.channel === "pi-desktop/settings/set" && call.input.jevEnabled === false,
+ );
+ const firstDelete = apiCalls.findIndex((call) => call.channel === "pi-desktop/secrets/delete");
return {
initialToggleDisabled,
- keySavedInHost,
- keyDraftCleared: input.value === "",
- enabledSettingPersisted: writes.some((call) => call.input.jevEnabled === true),
+ configureOpened,
+ refusedWithoutKey,
+ replaceOffered,
+ removeOffered,
+ enabledSettingPersisted: settingsWrites.some((call) => call.input.jevEnabled === true),
disabledAfterRemoval: finalToggle.getAttribute("aria-checked") === "false",
+ toggleDisabledAfterRemoval: finalToggle.disabled === true,
keyRemovedFromHost: savedKey === undefined,
- allSecretRefsFixed: secretWrites.every((call) =>
- call.channel === "pi-desktop/secrets/set"
- ? call.input.secretRef === JEV_API_KEY_SECRET_REF
- : call.input === JEV_API_KEY_SECRET_REF),
- noKeyInSettings: writes.every((call) => !Object.values(call.input).includes("jev-ui-fixture-key")),
+ removalDisabledFirst: firstDelete !== -1 && lastDisable !== -1 && firstDelete > lastDisable,
+ keyNeverStoredFromTheCard: !apiCalls.some((call) => call.channel === "pi-desktop/secrets/set"),
+ storedKeyNeverInSettings: settingsWrites.every(
+ (call) => !Object.values(call.input).includes("jev-ui-fixture-key"),
+ ),
};
};
`;
-test("Jev settings stores a secret, enables Jev, then disables and removes it", {
+test("the Jev card reads the key, gates the switch, and disables before removing", {
timeout: 60_000,
skip:
process.platform === "linux" && !process.env.DISPLAY
@@ -214,13 +244,17 @@ app.whenReady().then(async () => {
const result = JSON.parse(line.slice("JEV_SETTINGS_PROBE ".length));
assert.deepEqual(result, {
initialToggleDisabled: true,
- keySavedInHost: true,
- keyDraftCleared: true,
+ configureOpened: true,
+ refusedWithoutKey: true,
+ replaceOffered: true,
+ removeOffered: true,
enabledSettingPersisted: true,
disabledAfterRemoval: true,
+ toggleDisabledAfterRemoval: true,
keyRemovedFromHost: true,
- allSecretRefsFixed: true,
- noKeyInSettings: true,
+ removalDisabledFirst: true,
+ keyNeverStoredFromTheCard: true,
+ storedKeyNeverInSettings: true,
});
} finally {
await rm(temp, { recursive: true, force: true });
diff --git a/apps/desktop/test/service-chooser.test.mjs b/apps/desktop/test/service-chooser.test.mjs
index 6f1d2e0d4..7794d1180 100644
--- a/apps/desktop/test/service-chooser.test.mjs
+++ b/apps/desktop/test/service-chooser.test.mjs
@@ -27,7 +27,7 @@ const rule = (selector) => {
test("a new service starts on a searchable chooser, not a closed menu (D625)", () => {
assert.match(setupSource, /<ServiceChooser/);
assert.match(setupSource, /const chooserOpen = choosing \|\| !service/);
- assert.match(setupSource, /\{chooserOpen \? chooserView : formView\}/);
+ assert.match(setupSource, /\{chooserOpen \? chooserView : jevService \? jevView : formView\}/);
assert.doesNotMatch(setupSource, /<ServicePicker/);
assert.doesNotMatch(setupSource, /<optgroup/);
assert.match(chooserSource, /settings\.searchService/);
@@ -60,6 +60,12 @@ test("subscriptions and API services share the chooser, custom endpoint first",
assert.doesNotMatch(chooserSource, /presetGroupInternational|presetGroupChina/);
assert.doesNotMatch(chooserSource, /NAMED_PRESET_GROUPS/);
assert.doesNotMatch(catalogSource, /NAMED_PRESET_GROUPS/);
+ // Jev is a classifier, not a row anyone edits: it is offered on the add path
+ // only, and it renders its own view instead of the connection form.
+ assert.match(chooserSource, /settings\.chooserClassifiers/);
+ assert.match(chooserSource, /showClassifiers \? \[jevServiceOption\(t\)\] : \[\]/);
+ assert.match(setupSource, /showClassifiers=\{!editing\}/);
+ assert.match(setupSource, /const jevService = service === JEV_SERVICE/);
});
test("the chooser answers the keyboard and never dead-ends", () => {
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index 48c05c542..28db42871 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -219,8 +219,11 @@ PI-Desktop must not permanently restrict users to a short fixed model list.
transport and typed non-chat operations that models.dev does not describe.
PI-Desktop's optional Jev integration uses pi-ai's built-in
`typesafe/jev-latest` classifier directly; it is never listed or selectable
- as a chat provider/model. A saved TypeSafe key and explicit Jev setting are
- required before Agent mode receives the on-demand `JevClassify` tool.
+ as a chat provider/model, and it owns no provider row even though it is
+ added from the same service chooser. The key is checked against TypeSafe
+ over that same System One address before settings keeps it, so a saved key
+ and an explicit Jev setting together mean Agent mode receives the on-demand
+ `JevClassify` tool.
6. Free-form IDs remain configurable. Conservative generic metadata applies
when no published model matches; explicit user overrides remain supported.
Unknown relay metadata uses exact final-segment matching and an unambiguous
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 9553af0e3..e8f3aef82 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -543,15 +543,26 @@ contract modes are intent boundaries, not strict read-only security profiles.
### Jev classifier
-- Keep Jev separate from the chat provider/model list: it is a TypeSafe
- structured classifier, not a conversation model.
-- Let the user store or remove a TypeSafe API key and explicitly enable Jev
- for Agent mode. The key stays in Host secure storage; the renderer only reads
- whether one exists.
+- Keep Jev out of the chat provider/model list: it is a TypeSafe structured
+ classifier, not a conversation model, and it owns no provider row.
+- Offer it from **Add service**, in its own Classifiers group, on the add path
+ only: changing an existing row's service never turns it into a classifier.
+ The tile carries the TypeSafe address the key is spent on.
+- Adding Jev is one action with two steps: check the key against TypeSafe, then
+ store it and turn the classifier on. Nothing is written when the check fails,
+ and closing the dialog while the check is still running cancels the whole
+ action, so an enabled Jev always has a key the Agent can spend and an
+ abandoned dialog never leaves a credential behind. The credential is a
+ TypeSafe API key; this integration has no OAuth path.
+- The model configuration page keeps one Jev card: the stored-key state, the
+ Agent-mode switch, and the actions that add, replace or remove the key. The
+ key itself is entered only in the service dialog, which is also where it is
+ checked. It stays in Host secure storage; the renderer only learns whether
+ one exists.
- Explain that `JevClassify` sends only the state and questions the Agent passes
to TypeSafe, and warn users not to include secrets or personal information.
- The tool is on demand and unavailable in Plan and Goal modes. Removing the
- key disables Jev.
+ key turns Jev off first, then deletes it.
### Agent capability destinations (Skills / MCP / Subagents)
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 89c75b8a4..f96c5d459 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -16926,26 +16926,36 @@ host-created files. The full app's file-preview viewer is covered separately.
and a `globalThis.fetch` fixture for `https://api.typesafe.ai/v1/systemone`.
Build workspace JS packages with `pnpm build:js`, then run
`pnpm test:e2e:jev`. Do not use a real TypeSafe key or endpoint.
-- **Steps:** 1) In the rendered Jev settings card, save a sentinel key and
- enable Jev. 2) Resolve a session launch with Jev enabled, then disabled and
- in Plan mode. 3) Through the runtime's deferred catalog, request Jev in Agent
- mode and inspect Plan/Goal catalogs. 4) Call `JevClassify` with one choice,
- one score and one boolean question over a small JSON state. 5) Disable Jev
- and remove the key in settings.
-- **Expected:** The UI stores the key under the fixed Host secret reference,
- never returns it to settings state, and disables Jev after removal. Only an
+- **Steps:** 1) On the service chooser's add path, confirm Jev is offered in
+ its own Classifiers group and absent when an existing row changes service.
+ 2) Open the Jev form, paste a sentinel key and Check and save: the fixture
+ answers the check, the key reaches Host secure storage, Jev is on. 3) Resolve
+ a session launch with Jev enabled, then disabled and in Plan mode. 4) Through
+ the runtime's deferred catalog, request Jev in Agent mode and inspect
+ Plan/Goal catalogs. 5) Call `JevClassify` with one choice, one score and one
+ boolean question over a small JSON state. 6) Answer a check with 401 for a
+ second key: nothing is written and Jev stays off. 7) Start a check and close
+ the dialog while it is still in flight: the key is not stored and Jev stays
+ off. 8) In the Jev card, switch Jev off and remove the key.
+- **Expected:** The check runs before any write, in the order check, store, then
+ enable, so a refused key leaves no secret and no enabled setting behind, and
+ the refusal is reported with TypeSafe's status. The UI never returns the key
+ to settings state, and removal disables Jev before deleting it. Only an
enabled Agent launch reads the key and passes it ephemerally to the sidecar.
`JevClassify` appears in the Agent's deferred catalog only with a key and
- never in Plan or Goal. The fixture receives the TypeSafe System One payload
- and bearer header; the tool returns bounded structured answers and usage.
+ never in Plan or Goal. Closing the dialog cancels an in-flight check the same
+ way a refused key does: nothing stored, nothing enabled. The fixture receives
+ the TypeSafe System One payload and bearer header; the tool returns bounded
+ structured answers and usage.
- **Specs:** [Tools and permissions](../03-runtime/03-tools-and-permissions.md),
[provider/model system](../03-runtime/11-provider-model-system.md),
[secrets storage](../03-runtime/14-secrets-storage.md),
[settings IA](../04-ux/06-settings-ia.md).
- **Acceptance:** No paid or real-provider call. The suite verifies the UI user
- path, fixed secret reference, opt-in Agent launch boundary, deferred mode
- catalog, request body, bearer auth, usage, error redaction, cancellation,
- timeout, malformed and oversized input rejection, and key removal.
+ path, the ordered check-then-store gate, the refused-key path, the fixed
+ secret reference, opt-in Agent launch boundary, deferred mode catalog,
+ request body, bearer auth, usage, error redaction, cancellation, timeout,
+ malformed and oversized input rejection, and key removal.
- Disable/remove a provider or model and mark a model for image generation:
unavailable history entries are skipped for inheritance and recent menu rows.
- Settings contains no fixed chat-default picker or Make default service action;
diff --git a/package.json b/package.json
index b234a0ba1..a1c4005ac 100644
--- a/package.json
+++ b/package.json
@@ -21,7 +21,7 @@
"test": "pnpm build:js && pnpm -r --if-present test && cargo test -p host-core",
"test:host": "cargo test -p host-core",
"test:e2e": "node scripts/e2e-smoke.mjs",
- "test:e2e:jev": "node --test apps/desktop/test/jev-settings-user-path.test.mjs apps/desktop/test/jev-session-launch.test.mjs && node packages/agent-runtime/node_modules/vitest/vitest.mjs run packages/agent-runtime/src/jev-classifier-tool.test.ts packages/agent-runtime/src/runtime.test.ts -t Jev --config packages/agent-runtime/vitest.config.ts",
+ "test:e2e:jev": "node --test apps/desktop/test/jev-api-key-check.test.mjs apps/desktop/test/jev-config.test.mjs apps/desktop/test/jev-settings-user-path.test.mjs apps/desktop/test/jev-service-setup-user-path.test.mjs apps/desktop/test/jev-session-launch.test.mjs && node packages/agent-runtime/node_modules/vitest/vitest.mjs run packages/agent-runtime/src/jev-classifier-tool.test.ts packages/agent-runtime/src/runtime.test.ts -t Jev --config packages/agent-runtime/vitest.config.ts",
"test:e2e:storage": "node scripts/e2e-storage-settings.mjs && node scripts/e2e-storage-migration.mjs && node scripts/e2e-storage-bootstrap.mjs",
"test:e2e:asktool-card": "node scripts/e2e-asktool-card.mjs",
"test:e2e:scheduled": "node scripts/e2e-scheduled.mjs",
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 614b21345..9b8aa2a76 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -1379,6 +1379,7 @@ sklm: {
"useCustomEndpoint": "Eigenen Endpunkt verwenden",
"chooserSubscriptions": "Mit einem Abo anmelden",
"chooserApiKeys": "Mit einem API-Schlüssel verbinden",
+ "chooserClassifiers": "Klassifikatoren",
"customEndpointDesc": "Jede OpenAI- oder Anthropic-kompatible URL",
"connectionReady_one": "Verbunden · {{count}} Modell gefunden",
"connectionReady_other": "Verbunden · {{count}} Modelle gefunden",
@@ -1497,13 +1498,19 @@ sklm: {
"jevPrivacyNotice": "Bei JevClassify werden der übergebene Zustand und die Fragen direkt an TypeSafe gesendet. Keine Geheimnisse oder persönlichen Daten übermitteln.",
"jevApiKey": "TypeSafe-API-Schlüssel",
"jevApiKeyPlaceholder": "TypeSafe-API-Schlüssel einfügen",
- "jevSaveKey": "Schlüssel speichern",
- "jevRemoveKey": "Schlüssel entfernen",
"jevKeyConfigured": "API-Schlüssel sicher gespeichert",
"jevKeyMissing": "Kein API-Schlüssel konfiguriert",
"jevKeyStatusChecking": "API-Schlüssel wird geprüft…",
"jevKeyStatusUnavailable": "API-Schlüsselstatus konnte nicht geprüft werden",
- "jevKeySaved": "Jev-API-Schlüssel gespeichert",
+ "jevConfigureKey": "Schlüssel hinzufügen",
+ "jevReplaceKey": "Schlüssel ersetzen",
+ "jevRemoveKey": "Schlüssel entfernen",
+ "jevTestAndSave": "Prüfen und speichern",
+ "jevCheckingKey": "Schlüssel wird geprüft…",
+ "jevKeyRequired": "Bitte zuerst einen TypeSafe-API-Schlüssel eingeben.",
+ "jevKeyCheckFailed": "TypeSafe hat diesen Schlüssel nicht akzeptiert.",
+ "jevServiceAdded": "TypeSafe-Schlüssel gespeichert, Jev ist aktiv",
+ "jevAddEnableNote": "„Prüfen und speichern“ fragt TypeSafe, ob der Schlüssel funktioniert, und aktiviert danach Jev für den Agent-Modus.",
"jevKeyRemoved": "Jev-API-Schlüssel entfernt",
"catalogNeverFetched": "nie",
"serviceModels": "Modelle aus diesem Dienst",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 1ccfa0e77..dfcdf9314 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -1399,6 +1399,7 @@ sklm: {
useCustomEndpoint: "Use a custom endpoint",
chooserSubscriptions: "Sign in with a subscription",
chooserApiKeys: "Connect with an API key",
+ chooserClassifiers: "Classifiers",
customEndpointDesc: "Any OpenAI- or Anthropic-compatible URL",
connectionReady_one: "Connected · {{count}} model found",
connectionReady_other: "Connected · {{count}} models found",
@@ -1520,13 +1521,19 @@ sklm: {
jevPrivacyNotice: "When the Agent calls JevClassify, the state and questions passed to it are sent directly to TypeSafe. Do not include secrets or personal information.",
jevApiKey: "TypeSafe API key",
jevApiKeyPlaceholder: "Paste TypeSafe API key",
- jevSaveKey: "Save key",
- jevRemoveKey: "Remove key",
jevKeyConfigured: "API key saved securely",
jevKeyMissing: "API key not configured",
jevKeyStatusChecking: "Checking API key…",
jevKeyStatusUnavailable: "Could not check API key status",
- jevKeySaved: "Jev API key saved",
+ jevConfigureKey: "Add key",
+ jevReplaceKey: "Replace key",
+ jevRemoveKey: "Remove key",
+ jevTestAndSave: "Check and save",
+ jevCheckingKey: "Checking key…",
+ jevKeyRequired: "Enter a TypeSafe API key first.",
+ jevKeyCheckFailed: "TypeSafe did not accept this key.",
+ jevServiceAdded: "TypeSafe key saved; Jev is on",
+ jevAddEnableNote: "Check and save asks TypeSafe whether the key works, then turns Jev on for Agent mode.",
jevKeyRemoved: "Jev API key removed",
catalogNeverFetched: "never",
serviceModels: "Models from this service",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index e2c6c7681..6114667db 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -1379,6 +1379,7 @@ sklm: {
"useCustomEndpoint": "Usar un endpoint personalizado",
"chooserSubscriptions": "Iniciar sesión con una suscripción",
"chooserApiKeys": "Conectar con una clave de API",
+ "chooserClassifiers": "Clasificadores",
"customEndpointDesc": "Cualquier URL compatible con OpenAI o Anthropic",
"connectionReady_one": "Conectado · {{count}} modelo encontrado",
"connectionReady_other": "Conectado · {{count}} modelos encontrados",
@@ -1497,13 +1498,19 @@ sklm: {
"jevPrivacyNotice": "Al llamar a JevClassify, el estado y las preguntas que se le pasen se envían directamente a TypeSafe. No incluyas secretos ni datos personales.",
"jevApiKey": "Clave API de TypeSafe",
"jevApiKeyPlaceholder": "Pega la clave API de TypeSafe",
- "jevSaveKey": "Guardar clave",
- "jevRemoveKey": "Eliminar clave",
"jevKeyConfigured": "Clave API guardada de forma segura",
"jevKeyMissing": "No hay una clave API configurada",
- "jevKeyStatusChecking": "Comprobando clave API…",
+ "jevKeyStatusChecking": "Comprobando la clave API…",
"jevKeyStatusUnavailable": "No se pudo comprobar el estado de la clave API",
- "jevKeySaved": "Clave API de Jev guardada",
+ "jevConfigureKey": "Añadir clave",
+ "jevReplaceKey": "Reemplazar clave",
+ "jevRemoveKey": "Eliminar clave",
+ "jevTestAndSave": "Comprobar y guardar",
+ "jevCheckingKey": "Comprobando la clave…",
+ "jevKeyRequired": "Introduce primero una clave API de TypeSafe.",
+ "jevKeyCheckFailed": "TypeSafe no aceptó esta clave.",
+ "jevServiceAdded": "Clave de TypeSafe guardada; Jev está activado",
+ "jevAddEnableNote": "Comprobar y guardar pregunta a TypeSafe si la clave funciona y después activa Jev para el modo Agent.",
"jevKeyRemoved": "Clave API de Jev eliminada",
"catalogNeverFetched": "nunca",
"serviceModels": "Modelos de este servicio",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 42d5b3eb9..7644ccfd3 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -1379,6 +1379,7 @@ sklm: {
"useCustomEndpoint": "Utiliser un endpoint personnalisé",
"chooserSubscriptions": "Se connecter avec un abonnement",
"chooserApiKeys": "Se connecter avec une clé API",
+ "chooserClassifiers": "Classificateurs",
"customEndpointDesc": "Toute URL compatible OpenAI ou Anthropic",
"connectionReady_one": "Connecté · {{count}} modèle trouvé",
"connectionReady_other": "Connecté · {{count}} modèles trouvés",
@@ -1497,13 +1498,19 @@ sklm: {
"jevPrivacyNotice": "Lors d’un appel à JevClassify, l’état et les questions fournis sont envoyés directement à TypeSafe. N’incluez ni secrets ni données personnelles.",
"jevApiKey": "Clé API TypeSafe",
"jevApiKeyPlaceholder": "Collez la clé API TypeSafe",
- "jevSaveKey": "Enregistrer la clé",
- "jevRemoveKey": "Supprimer la clé",
"jevKeyConfigured": "Clé API enregistrée de façon sécurisée",
"jevKeyMissing": "Aucune clé API configurée",
"jevKeyStatusChecking": "Vérification de la clé API…",
"jevKeyStatusUnavailable": "Impossible de vérifier l’état de la clé API",
- "jevKeySaved": "Clé API Jev enregistrée",
+ "jevConfigureKey": "Ajouter une clé",
+ "jevReplaceKey": "Remplacer la clé",
+ "jevRemoveKey": "Supprimer la clé",
+ "jevTestAndSave": "Vérifier et enregistrer",
+ "jevCheckingKey": "Vérification de la clé…",
+ "jevKeyRequired": "Saisissez d’abord une clé API TypeSafe.",
+ "jevKeyCheckFailed": "TypeSafe n’a pas accepté cette clé.",
+ "jevServiceAdded": "Clé TypeSafe enregistrée ; Jev est activé",
+ "jevAddEnableNote": "Vérifier et enregistrer demande à TypeSafe si la clé fonctionne, puis active Jev en mode Agent.",
"jevKeyRemoved": "Clé API Jev supprimée",
"catalogNeverFetched": "jamais",
"serviceModels": "Modèles de ce service",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index d5aa00b73..378a0ed44 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -1392,6 +1392,7 @@ sklm: {
useCustomEndpoint: "사용자 지정 엔드포인트 사용",
chooserSubscriptions: "구독으로 로그인",
chooserApiKeys: "API 키로 연결",
+ chooserClassifiers: "분류기",
customEndpointDesc: "OpenAI 또는 Anthropic 호환 URL",
connectionReady_one: "연결됨 · 모델 {{count}}개 발견",
connectionReady_other: "연결됨 · 모델 {{count}}개 발견",
@@ -1513,13 +1514,19 @@ sklm: {
jevPrivacyNotice: "Agent가 JevClassify를 호출하면 전달된 상태와 질문이 TypeSafe로 직접 전송됩니다. 비밀이나 개인 정보를 포함하지 마세요.",
jevApiKey: "TypeSafe API 키",
jevApiKeyPlaceholder: "TypeSafe API 키 붙여넣기",
- jevSaveKey: "키 저장",
- jevRemoveKey: "키 삭제",
jevKeyConfigured: "API 키가 안전하게 저장됨",
jevKeyMissing: "API 키가 설정되지 않음",
jevKeyStatusChecking: "API 키 확인 중…",
jevKeyStatusUnavailable: "API 키 상태를 확인할 수 없음",
- jevKeySaved: "Jev API 키 저장됨",
+ jevConfigureKey: "키 추가",
+ jevReplaceKey: "키 교체",
+ jevRemoveKey: "키 삭제",
+ jevTestAndSave: "확인 후 저장",
+ jevCheckingKey: "키 확인 중…",
+ jevKeyRequired: "먼저 TypeSafe API 키를 입력하세요.",
+ jevKeyCheckFailed: "TypeSafe가 이 키를 거부했습니다.",
+ jevServiceAdded: "TypeSafe 키를 저장했고 Jev를 켰습니다",
+ jevAddEnableNote: "확인 후 저장은 TypeSafe에 키가 작동하는지 물은 뒤 Agent 모드에서 Jev를 켭니다.",
jevKeyRemoved: "Jev API 키 삭제됨",
catalogNeverFetched: "없음",
serviceModels: "이 서비스의 모델",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 8525bdd1d..111d9ce7a 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -1341,6 +1341,7 @@ export const ptBR = {
useCustomEndpoint: "Usar um endpoint personalizado",
chooserSubscriptions: "Entrar com uma assinatura",
chooserApiKeys: "Conectar com uma chave de API",
+ chooserClassifiers: "Classificadores",
customEndpointDesc: "Qualquer URL compatível com OpenAI ou Anthropic",
connectionReady_one: "Conectado · {{count}} modelo encontrado",
connectionReady_other: "Conectado · {{count}} modelos encontrados",
@@ -1461,13 +1462,19 @@ export const ptBR = {
jevPrivacyNotice: "Ao chamar JevClassify, o estado e as perguntas fornecidos são enviados diretamente ao TypeSafe. Não inclua segredos nem dados pessoais.",
jevApiKey: "Chave de API do TypeSafe",
jevApiKeyPlaceholder: "Cole a chave de API do TypeSafe",
- jevSaveKey: "Salvar chave",
- jevRemoveKey: "Remover chave",
jevKeyConfigured: "Chave de API salva com segurança",
jevKeyMissing: "Nenhuma chave de API configurada",
jevKeyStatusChecking: "Verificando a chave de API…",
jevKeyStatusUnavailable: "Não foi possível verificar o status da chave de API",
- jevKeySaved: "Chave de API do Jev salva",
+ jevConfigureKey: "Adicionar chave",
+ jevReplaceKey: "Substituir chave",
+ jevRemoveKey: "Remover chave",
+ jevTestAndSave: "Testar e salvar",
+ jevCheckingKey: "Testando a chave…",
+ jevKeyRequired: "Informe primeiro uma chave de API do TypeSafe.",
+ jevKeyCheckFailed: "O TypeSafe não aceitou esta chave.",
+ jevServiceAdded: "Chave do TypeSafe salva; o Jev está ativado",
+ jevAddEnableNote: "Testar e salvar pergunta ao TypeSafe se a chave funciona e depois ativa o Jev no modo Agent.",
jevKeyRemoved: "Chave de API do Jev removida",
catalogNeverFetched: "nunca",
serviceModels: "Modelos deste serviço",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 0498eb717..50345e407 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -1382,6 +1382,7 @@ sklm: {
useCustomEndpoint: "Özel uç nokta kullan",
chooserSubscriptions: "Abonelikle oturum aç",
chooserApiKeys: "API anahtarıyla bağlan",
+ chooserClassifiers: "Sınıflandırıcılar",
customEndpointDesc: "OpenAI veya Anthropic uyumlu herhangi bir URL",
connectionReady_one: "Bağlandı · {{count}} model bulundu",
connectionReady_other: "Bağlandı · {{count}} model bulundu",
@@ -1503,13 +1504,19 @@ sklm: {
jevPrivacyNotice: "Agent JevClassify'ı çağırdığında sağlanan durum ve sorular doğrudan TypeSafe'e gönderilir. Gizli veya kişisel bilgi eklemeyin.",
jevApiKey: "TypeSafe API anahtarı",
jevApiKeyPlaceholder: "TypeSafe API anahtarını yapıştırın",
- jevSaveKey: "Anahtarı kaydet",
- jevRemoveKey: "Anahtarı kaldır",
jevKeyConfigured: "API anahtarı güvenli biçimde kaydedildi",
jevKeyMissing: "API anahtarı yapılandırılmadı",
jevKeyStatusChecking: "API anahtarı denetleniyor…",
jevKeyStatusUnavailable: "API anahtarı durumu denetlenemedi",
- jevKeySaved: "Jev API anahtarı kaydedildi",
+ jevConfigureKey: "Anahtar ekle",
+ jevReplaceKey: "Anahtarı değiştir",
+ jevRemoveKey: "Anahtarı kaldır",
+ jevTestAndSave: "Denetle ve kaydet",
+ jevCheckingKey: "Anahtar denetleniyor…",
+ jevKeyRequired: "Önce bir TypeSafe API anahtarı girin.",
+ jevKeyCheckFailed: "TypeSafe bu anahtarı kabul etmedi.",
+ jevServiceAdded: "TypeSafe anahtarı kaydedildi; Jev açık",
+ jevAddEnableNote: "Denetle ve kaydet, anahtarın çalışıp çalışmadığını TypeSafe'e sorar ve ardından Agent modunda Jev'i açar.",
jevKeyRemoved: "Jev API anahtarı kaldırıldı",
catalogNeverFetched: "hiç",
serviceModels: "Bu servisin modelleri",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 799a3b130..6687edca9 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -1366,6 +1366,7 @@ sklm: {
useCustomEndpoint: "使用自定义端点",
chooserSubscriptions: "用订阅登录",
chooserApiKeys: "用 API Key 连接",
+ chooserClassifiers: "分类器",
customEndpointDesc: "任意 OpenAI 或 Anthropic 兼容地址",
connectionReady_one: "已连接 · 发现 {{count}} 个模型",
connectionReady_other: "已连接 · 发现 {{count}} 个模型",
@@ -1484,13 +1485,19 @@ sklm: {
jevPrivacyNotice: "Agent 调用 JevClassify 时,传入的状态和问题会直接发送给 TypeSafe。请勿包含密钥或个人信息。",
jevApiKey: "TypeSafe API 密钥",
jevApiKeyPlaceholder: "粘贴 TypeSafe API 密钥",
- jevSaveKey: "保存密钥",
- jevRemoveKey: "移除密钥",
jevKeyConfigured: "API 密钥已安全保存",
jevKeyMissing: "尚未配置 API 密钥",
jevKeyStatusChecking: "正在检查 API 密钥…",
jevKeyStatusUnavailable: "无法检查 API 密钥状态",
- jevKeySaved: "Jev API 密钥已保存",
+ jevConfigureKey: "配置密钥",
+ jevReplaceKey: "更换密钥",
+ jevRemoveKey: "移除密钥",
+ jevTestAndSave: "测试并保存",
+ jevCheckingKey: "正在测试密钥…",
+ jevKeyRequired: "请先填写 TypeSafe API 密钥。",
+ jevKeyCheckFailed: "TypeSafe 未接受该密钥。",
+ jevServiceAdded: "TypeSafe 密钥已保存,Jev 已启用",
+ jevAddEnableNote: "保存时会先向 TypeSafe 测试此密钥,通过后为 Agent 模式启用 Jev。",
jevKeyRemoved: "Jev API 密钥已移除",
catalogNeverFetched: "从未获取",
serviceModels: "该服务的模型",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index d3fa3660d..cab7ab144 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -1366,6 +1366,7 @@ sklm: {
useCustomEndpoint: "使用自訂端點",
chooserSubscriptions: "用訂閱登入",
chooserApiKeys: "用 API Key 連線",
+ chooserClassifiers: "分類器",
customEndpointDesc: "任意 OpenAI 或 Anthropic 相容位址",
connectionReady_one: "已連線 · 發現 {{count}} 個模型",
connectionReady_other: "已連線 · 發現 {{count}} 個模型",
@@ -1484,13 +1485,19 @@ sklm: {
jevPrivacyNotice: "Agent 呼叫 JevClassify 時,傳入的狀態和問題會直接傳送給 TypeSafe。請勿包含密鑰或個人資訊。",
jevApiKey: "TypeSafe API 金鑰",
jevApiKeyPlaceholder: "貼上 TypeSafe API 金鑰",
- jevSaveKey: "儲存金鑰",
- jevRemoveKey: "移除金鑰",
jevKeyConfigured: "API 金鑰已安全儲存",
jevKeyMissing: "尚未設定 API 金鑰",
jevKeyStatusChecking: "正在檢查 API 金鑰…",
jevKeyStatusUnavailable: "無法檢查 API 金鑰狀態",
- jevKeySaved: "Jev API 金鑰已儲存",
+ jevConfigureKey: "設定金鑰",
+ jevReplaceKey: "更換金鑰",
+ jevRemoveKey: "移除金鑰",
+ jevTestAndSave: "測試並儲存",
+ jevCheckingKey: "正在測試金鑰…",
+ jevKeyRequired: "請先填寫 TypeSafe API 金鑰。",
+ jevKeyCheckFailed: "TypeSafe 未接受此金鑰。",
+ jevServiceAdded: "TypeSafe 金鑰已儲存,Jev 已啟用",
+ jevAddEnableNote: "儲存時會先向 TypeSafe 測試此金鑰,通過後為 Agent 模式啟用 Jev。",
jevKeyRemoved: "Jev API 金鑰已移除",
catalogNeverFetched: "從未獲取",
serviceModels: "該服務的模型",
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index bd4ce9e48..255bd7761 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -234,6 +234,14 @@ export const IPC = {
*/
providersSetSecret: "pi-desktop/providers/setSecret",
providersTest: "pi-desktop/providers/testConnection",
+ /**
+ * Check a TypeSafe key before the Jev settings row keeps it.
+ *
+ * Jev is not a provider row, so `providersTest` cannot answer this: the
+ * key is checked by the same System One round trip the Agent's
+ * `JevClassify` tool makes, and only a key that answered is stored.
+ */
+ jevTest: "pi-desktop/jev/test",
providersListModels: "pi-desktop/providers/listModels",
/**
* Look one model id up in the local models.dev snapshot.
diff --git a/packages/shared/src/secret-refs.ts b/packages/shared/src/secret-refs.ts
index 9711a6488..9f5bd0e2e 100644
--- a/packages/shared/src/secret-refs.ts
+++ b/packages/shared/src/secret-refs.ts
@@ -1,2 +1,17 @@
-/** Fixed Host secret references owned by first-party desktop features. */
+/**
+ * Fixed constants owned by first-party desktop integrations: the Host secret
+ * references their credentials are stored under, and the addresses those
+ * credentials are spent on.
+ */
export const JEV_API_KEY_SECRET_REF = "secret:app:typesafe-jev";
+
+/**
+ * The TypeSafe System One endpoint behind Jev, and the classifier it asks.
+ *
+ * The settings key check calls this address. The Agent's `JevClassify` tool
+ * reaches the same one through pi-ai's `typesafe` provider, whose published
+ * base URL resolves to it; if that address ever moves in pi-ai, this constant
+ * is what the check has to follow.
+ */
+export const TYPESAFE_SYSTEM_ONE_URL = "https://api.typesafe.ai/v1/systemone";
+export const TYPESAFE_JEV_MODEL_ID = "jev-latest";
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index 9ba26c663..03eae315b 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -14,6 +14,19 @@ import type { LiveVoiceSettings } from "./live-voice.js";
export type ThemePreference = "system" | "light" | "dark" | `plugin:${string}`;
+/**
+ * What a TypeSafe key check answered.
+ *
+ * `ok` means the classifier answered this key at its own address. A refusal
+ * carries the HTTP `status` and `message` when TypeSafe sent one; `message` is
+ * provider text with the key already redacted.
+ */
+export type JevKeyCheckResult = {
+ ok: boolean;
+ status?: number;
+ message?: string;
+};
+
/**
* What closing the main window does on Windows/Linux. macOS keeps the native
* Dock lifecycle and never consults this preference.