Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
test(jev): cover opt-in classifier integration
vastsa8881c97f908b
diff --git a/apps/desktop/test/jev-session-launch.test.mjs b/apps/desktop/test/jev-session-launch.test.mjsnew file mode 100644index 000000000..d9f9ff089--- /dev/null+++ b/apps/desktop/test/jev-session-launch.test.mjs@@ -0,0 +1,138 @@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { mkdtemp, rm } from "node:fs/promises";+import { join } from "node:path";+import test from "node:test";+import { pathToFileURL } from "node:url";+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");++test("session launch resolves Jev credentials only for opted-in Agent mode", async () => {+ const temp = await mkdtemp(join(root, "apps/desktop/.jev-launch-test-"));+ const priorHome = process.env.HOME;+ process.env.HOME = temp;+ try {+ const bundle = join(temp, "session-launch.mjs");+ await build({+ entryPoints: [join(root, "apps/desktop/electron/main/runtime/session-launch.ts")],+ outfile: bundle,+ bundle: true,+ platform: "node",+ format: "esm",+ packages: "external",+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ const { createSessionLaunchRuntime } = await import(pathToFileURL(bundle).href);+ const provider = {+ id: "fixture-provider",+ name: "Fixture provider",+ authKind: "none",+ apiStyle: "openai-completions",+ baseUrl: "http://127.0.0.1:11434/v1",+ enabled: true,+ defaultModelId: "fixture-model",+ models: [],+ };+ const keyReads = [];+ const logs = [];+ let failJevSecretRead = false;+ const host = {+ isAvailable: () => true,+ async call(method, input) {+ if (method === "commandShells.list") {+ const shell = {+ id: "bash",+ label: "Bash",+ dialect: "posix",+ available: true,+ isDefault: true,+ };+ return { configuredId: "bash", effective: shell, fallback: false, choices: [shell] };+ }+ if (method === "providers.list") return { providers: [provider] };+ if (method === "providers.getSecret") return { value: "" };+ if (method === "skills.active") return { skills: [] };+ if (method === "mcp.active") return { servers: [] };+ if (method === "agents.active") return { subagents: [] };+ if (method === "agents.disabledBuiltins") return { disabled: [] };+ if (method === "secrets.getForRuntime") {+ keyReads.push(input);+ if (failJevSecretRead) throw new Error("private fixture detail");+ return { value: "jev-launch-fixture-key" };+ }+ throw new Error("Unexpected fixture Host method: " + method);+ },+ };+ const dependencies = {+ runtimeState: {+ host,+ sidecar: { setVendorAuthBindings() {} },+ agentHostBridge: null,+ },+ logger: { app(...args) { logs.push(args); } },+ userMcp: { setRecords() {}, async toolsForProject() { return []; } },+ plugins: {+ getTools: () => [],+ getSkills: () => [],+ listLoaded: () => [],+ getAgentExtensions: () => [],+ },+ sessionProjects: new Map(),+ dataDir: temp,+ vendorOAuth: { async bindingFor() { return undefined; } },+ modelsDevCatalog: {+ async ensureLoaded() {},+ configureAccount() {},+ findModel() { return undefined; },+ },+ getWorkspacePath: () => null,+ pluginActiveInProject: () => true,+ bindingForModel: () => undefined,+ effectiveSubagentModelConfig: () => ({ modelConfig: undefined, capabilities: {} }),+ normalizeThinkingLevel: () => "off",+ };+ const launchRuntime = createSessionLaunchRuntime(dependencies);+ const launch = async (mode, jevEnabled) =>+ launchRuntime.resolveAgentRuntimeLaunch(+ "session-fixture",+ { providerId: provider.id, modelId: provider.defaultModelId },+ {+ defaultProviderId: provider.id,+ defaultModelId: provider.defaultModelId,+ defaultMode: mode,+ jevEnabled,+ },+ );++ const enabledAgent = await launch("agent", true);+ assert.equal(enabledAgent.sidecarParams.jevApiKey, "jev-launch-fixture-key");+ assert.equal(enabledAgent.sidecarParams.provider.apiKey, "");+ assert.deepEqual(keyReads, [{ secretRef: "secret:app:typesafe-jev" }]);++ keyReads.length = 0;+ const disabledAgent = await launch("agent", false);+ assert.equal("jevApiKey" in disabledAgent.sidecarParams, false);+ assert.deepEqual(keyReads, []);++ const plan = await launch("plan", true);+ assert.equal("jevApiKey" in plan.sidecarParams, false);+ assert.deepEqual(keyReads, []);++ failJevSecretRead = true;+ const unavailable = await launch("agent", true);+ assert.equal("jevApiKey" in unavailable.sidecarParams, false);+ assert.equal(JSON.stringify(logs).includes("private fixture detail"), false);+ assert.deepEqual(logs, [[+ "session",+ "warn",+ "Jev API key could not be loaded",+ { sessionId: "session-fixture" },+ ]]);+ } finally {+ if (priorHome === undefined) delete process.env.HOME;+ else process.env.HOME = priorHome;+ 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.mjsnew file mode 100644index 000000000..2b76c0160--- /dev/null+++ b/apps/desktop/test/jev-settings-user-path.test.mjs@@ -0,0 +1,228 @@+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 { useAppStore } from "../../apps/desktop/src/stores/app-store";++const apiCalls = [];+let savedKey;+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/secrets/has":+ 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;+ 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 });+function JevSettingsHarness() {+ const settings = useAppStore((state) => state.settings);+ return React.createElement(JevSettingsCard, { settings: settings ?? undefined });+}+const rootNode = createRoot(document.getElementById("root"));+flushSync(() => rootNode.render(React.createElement(JevSettingsHarness)));++const frame = () => new Promise(requestAnimationFrame);+async function settle() { await frame(); await frame(); }+async function waitFor(predicate, message) {+ for (let attempt = 0; attempt < 90; 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);+}++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 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 }));+ 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 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");++ flushSync(() => button("Remove key").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));+ return {+ initialToggleDisabled,+ keySavedInHost,+ keyDraftCleared: input.value === "",+ enabledSettingPersisted: writes.some((call) => call.input.jevEnabled === true),+ disabledAfterRemoval: finalToggle.getAttribute("aria-checked") === "false",+ 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")),+ };+};+`;++test("Jev settings stores a secret, enables Jev, then disables and removes it", {+ 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-settings-ui-"));+ try {+ await build({+ stdin: {+ contents: fixtureSource,+ resolveDir: join(root, "scripts", "e2e"),+ sourcefile: join(root, "scripts", "e2e", "jev-settings.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: 900, height: 700,+ 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.jevSettingsProbe()");+ console.log("JEV_SETTINGS_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_SETTINGS_PROBE "));+ assert(line, output.slice(-6000));+ const result = JSON.parse(line.slice("JEV_SETTINGS_PROBE ".length));+ assert.deepEqual(result, {+ initialToggleDisabled: true,+ keySavedInHost: true,+ keyDraftCleared: true,+ enabledSettingPersisted: true,+ disabledAfterRemoval: true,+ keyRemovedFromHost: true,+ allSecretRefsFixed: true,+ noKeyInSettings: true,+ });+ } finally {+ await rm(temp, { recursive: true, force: true });+ }+});diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex bebb12dbf..92b889d14 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -16922,32 +16922,30 @@ host-created files. The full app's file-preview viewer is covered separately.rejected submission does not. Deferred configuration alone does not countas usage.-## E2E-AGENT-jev-classifier-opt-in--- **Preconditions:** Isolated desktop profile, a deterministic local chat- provider fixture, a fake Host secret store, and a sidecar `fetch` fixture- that intercepts `https://api.typesafe.ai/v1/systemone`. Do not use a real- TypeSafe key or provider endpoint.-- **Steps:** 1) Open Settings → Models, save a sentinel TypeSafe key, and enable- Jev. 2) Start an Agent turn whose deterministic chat fixture requests- `ToolSearch` for Jev, then calls `JevClassify` with one choice, one score and- one boolean question over a small JSON state. 3) Inspect the fixture request- and the rendered tool result. 4) Start turns in Plan and Goal. 5) Disable Jev- and start another Agent turn, then re-enable it and remove the key.-- **Expected:** The key is stored under the fixed Host secret reference and is- never returned to renderer state or transcript. `JevClassify` appears in the- Agent's deferred catalog only while enabled with a saved 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. A- disabled/missing key omits the tool on the next turn, and removing the key- turns the setting off.+- **Preconditions:** Isolated Electron profile, fake Host IPC/secret storage,+ 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+ 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.- **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 fixture verifies request- body, auth redaction, cancellation, timeout, malformed input rejection, and- that disabling/removing Jev affects the next Agent launch.+- **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.- 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.jsonindex 0b81bcc7d..b234a0ba1 100644--- a/package.json+++ b/package.json@@ -21,6 +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: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/agent-runtime/src/jev-classifier-tool.test.ts b/packages/agent-runtime/src/jev-classifier-tool.test.tsnew file mode 100644index 000000000..0a817b3af--- /dev/null+++ b/packages/agent-runtime/src/jev-classifier-tool.test.ts@@ -0,0 +1,196 @@+import { describe, expect, it, vi } from "vitest";+import { createJevClassifierTool } from "./jev-classifier-tool.js";++const API_KEY = "jev-fixture-secret-do-not-leak";++const params = {+ state: { message: "The change works." },+ questions: {+ category: {+ type: "choice",+ instructions: "Classify the message.",+ criteria: { approval: "Approves", correction: "Requests a correction" },+ },+ satisfaction: {+ type: "score",+ instructions: "Score satisfaction.",+ criteria: ["low", "medium", "high"],+ },+ approved: {+ type: "bool",+ instructions: "Does the user approve?",+ criteria: { true: "Approval", false: "No approval" },+ },+ },+};++function successResponse(): Response {+ return new Response(+ JSON.stringify({+ answers: {+ category: {+ type: "choice",+ choice: "approval",+ probabilities: { approval: 0.9, correction: 0.1 },+ confidence: 0.9,+ },+ satisfaction: { type: "score", score: 2, confidence: 0.8 },+ approved: { type: "noul", noul: 0.95 },+ },+ usage: { input_tokens: 12, output_tokens: 4 },+ }),+ { status: 200, headers: { "content-type": "application/json" } },+ );+}++describe("JevClassify", () => {+ it("sends the typed state to TypeSafe and returns structured answers", async () => {+ const fetchMock = vi.fn<typeof fetch>(async () => successResponse());+ vi.stubGlobal("fetch", fetchMock);+ try {+ const result = await createJevClassifierTool(API_KEY).execute(+ "call-1",+ params,+ );++ expect(result.isError).not.toBe(true);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0];+ expect(String(url)).toBe("https://api.typesafe.ai/v1/systemone");+ expect(new Headers(init?.headers).get("authorization")).toBe(+ `Bearer ${API_KEY}`,+ );+ expect(JSON.parse(String(init?.body))).toEqual({+ model: "jev-latest",+ state: params.state,+ questions: {+ ...params.questions,+ approved: {+ ...params.questions.approved,+ type: "noul",+ },+ },+ });+ expect(result.details).toMatchObject({+ answers: {+ category: { type: "choice", choice: "approval" },+ satisfaction: { type: "score", score: 2 },+ approved: { type: "bool", probability: 0.95 },+ },+ usage: { input: 12, output: 4, totalTokens: 16 },+ });+ expect(JSON.stringify(result)).not.toContain(API_KEY);+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("rejects malformed and oversized inputs before making a request", async () => {+ const fetchMock = vi.fn<typeof fetch>(async () => successResponse());+ vi.stubGlobal("fetch", fetchMock);+ try {+ const tool = createJevClassifierTool(API_KEY);+ const malformed = await tool.execute("call-bad", {+ ...params,+ state: { score: Number.NaN },+ });+ const oversized = await tool.execute("call-large", {+ ...params,+ state: { message: "x".repeat(24 * 1024) },+ });++ expect(malformed.isError).toBe(true);+ expect(oversized.isError).toBe(true);+ expect(fetchMock).not.toHaveBeenCalled();+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("observes cancellation and redacts credentials from provider errors", async () => {+ const controller = new AbortController();+ let markStarted: () => void = () => undefined;+ const requestStarted = new Promise<void>((resolve) => {+ markStarted = resolve;+ });+ const fetchMock = vi.fn<typeof fetch>(+ (_input, init) =>+ new Promise<Response>((_resolve, reject) => {+ markStarted();+ init?.signal?.addEventListener(+ "abort",+ () => reject(new DOMException("Aborted", "AbortError")),+ { once: true },+ );+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ try {+ const pending = createJevClassifierTool(API_KEY).execute(+ "call-abort",+ params,+ controller.signal,+ );+ await requestStarted;+ controller.abort();+ const cancelled = await pending;+ expect(cancelled.isError).toBe(true);+ expect(cancelled.details).toMatchObject({ errorCode: "JEV_ABORTED" });++ vi.stubGlobal(+ "fetch",+ vi.fn<typeof fetch>(async () =>+ new Response(API_KEY, { status: 401 }),+ ),+ );+ const failed = await createJevClassifierTool(API_KEY).execute(+ "call-error",+ params,+ );+ expect(failed.isError).toBe(true);+ expect(JSON.stringify(failed)).not.toContain(API_KEY);+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("enforces the bounded provider timeout", async () => {+ const timeout = new AbortController();+ const timeoutSpy = vi+ .spyOn(AbortSignal, "timeout")+ .mockReturnValue(timeout.signal);+ let markStarted: () => void = () => undefined;+ const requestStarted = new Promise<void>((resolve) => {+ markStarted = resolve;+ });+ vi.stubGlobal(+ "fetch",+ vi.fn<typeof fetch>(+ (_input, init) =>+ new Promise<Response>((_resolve, reject) => {+ markStarted();+ init?.signal?.addEventListener(+ "abort",+ () => reject(new DOMException("Aborted", "AbortError")),+ { once: true },+ );+ }),+ ),+ );+ try {+ const pending = createJevClassifierTool(API_KEY).execute(+ "call-timeout",+ params,+ );+ await requestStarted;+ expect(timeoutSpy).toHaveBeenCalledWith(45_000);+ timeout.abort();+ const result = await pending;+ expect(result.isError).toBe(true);+ expect(result.details).toMatchObject({ errorCode: "JEV_ABORTED" });+ } finally {+ timeoutSpy.mockRestore();+ vi.unstubAllGlobals();+ }+ });+});diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 7e366f6c0..7593d0ec9 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -177,6 +177,7 @@ function createRuntime(subagentModelKeys: string[];pluginSkills: import("./plugin-skills-prompt.js").PluginSkillDef[];commandShell: CommandShellOption;+ jevApiKey: string;turnId: string;host: { call: ReturnType<typeof vi.fn>; onNotification?: ReturnType<typeof vi.fn> };onEvent: (envelope: unknown) => void;@@ -186,6 +187,7 @@ function createRuntime(host: (overrides.host ?? { call: vi.fn(), onNotification: vi.fn(() => () => {}) }) as never,sessionId: "session-1",mode: overrides.mode === "chat" ? "plan" : overrides.mode ?? "agent",+ jevApiKey: overrides.jevApiKey,turnId: overrides.turnId,provider: overrides.provider ?? provider,commandShell: overrides.commandShell ?? commandShell,@@ -1988,6 +1990,83 @@ describe("DesktopAgentRuntime live activity", () => {});describe("DesktopAgentRuntime deferred tool catalog", () => {+ it("offers Jev only in Agent mode when an API key is supplied", async () => {+ type ToolResult = {+ content: Array<{ type: "text"; text: string }>;+ details: { activated: string[]; addedToolNames: string[] };+ isError?: boolean;+ };+ type RuntimeTestTool = {+ name: string;+ execute?: (id: string, input: { query: string }) => Promise<ToolResult>;+ };+ type RuntimeTestView = {+ agent: { state: { tools: RuntimeTestTool[]; systemPrompt: string } };+ prepareNextTurn: (input: never) => Promise<{+ context: { tools: RuntimeTestTool[] };+ }>;+ };++ const enabled = createRuntime({ jevApiKey: "fixture-key" });+ try {+ const view = enabled as unknown as RuntimeTestView;+ const tools = view.agent.state.tools;+ const search = tools.find((tool) => tool.name === "ToolSearch");+ expect(search).toBeDefined();+ expect(view.agent.state.systemPrompt).toContain("JevClassify");++ const result = await search?.execute?.("search-jev", {+ query: "JevClassify",+ });+ expect(result?.details.activated).toEqual(["JevClassify"]);+ const next = await view.prepareNextTurn({+ context: { systemPrompt: "", messages: [], tools },+ messages: [],+ newMessages: [],+ toolResults: [+ {+ role: "toolResult",+ toolCallId: "search-jev",+ toolName: "ToolSearch",+ content: result?.content ?? [],+ details: result?.details,+ isError: result?.isError ?? false,+ timestamp: Date.now(),+ },+ ],+ } as never);+ expect(next.context.tools.map((tool) => tool.name)).toContain(+ "JevClassify",+ );+ } finally {+ await enabled.dispose();+ }++ for (const mode of ["plan", "goal"] as const) {+ const restricted = createRuntime({ mode, jevApiKey: "fixture-key" });+ try {+ const view = restricted as unknown as RuntimeTestView;+ expect(view.agent.state.systemPrompt).not.toContain("JevClassify");+ expect(view.agent.state.tools.map((tool) => tool.name)).not.toContain(+ "JevClassify",+ );+ } finally {+ await restricted.dispose();+ }+ }++ const missingKey = createRuntime();+ try {+ const view = missingKey as unknown as RuntimeTestView;+ expect(view.agent.state.systemPrompt).not.toContain("JevClassify");+ expect(view.agent.state.tools.map((tool) => tool.name)).not.toContain(+ "JevClassify",+ );+ } finally {+ await missingKey.dispose();+ }+ });+it("starts Agent with core tools plus workspace search and discovery", async () => {const runtime = createRuntime({pluginTools: [