Skip to content

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

test(plugins): cover OAuth provider user flow

vastsa974882bd29b7
diff --git a/apps/desktop/src/components/settings/ServiceChooser.tsx b/apps/desktop/src/components/settings/ServiceChooser.tsx
index c1492b4f5..e136592e2 100644
--- a/apps/desktop/src/components/settings/ServiceChooser.tsx
+++ b/apps/desktop/src/components/settings/ServiceChooser.tsx
@@ -198,6 +198,7 @@ export function ServiceChooser({
key={vendor.vendorId}
type="button"
data-service-tile
+ data-subscription-vendor-id={vendor.vendorId}
className={cx(
"service-chooser-tile",
enterTarget === `subscription:${vendor.vendorId}` && "is-active",
diff --git a/apps/desktop/test/e2e/trusted-extensions/README.md b/apps/desktop/test/e2e/trusted-extensions/README.md
index 23f140996..bb1cb70b3 100644
--- a/apps/desktop/test/e2e/trusted-extensions/README.md
+++ b/apps/desktop/test/e2e/trusted-extensions/README.md
@@ -34,12 +34,18 @@ What the automated run proves:
`sendUserMessage` through the Host-owned queue (E2E-243);
- a throwing module and unsupported terminal-UI imports degrading to
diagnostics while the remaining extensions continue to run (E2E-244).
+- plugin-declared OAuth permission projection, the real Settings sign-in picker
+ and Host-rendered device-code/secret prompt, provider-scoped refresh, model
+ request auth, cancellation, and sign-out against a local fixture (E2E-PLUGIN
+ declared-provider scenario).
The native picker/import journey and explicit enable/disable UI flow in
E2E-241 are not faked by this headless driver. The 30-second stalled-handler
fixture in E2E-244 and the packaged sidecar/jiti journey in E2E-245 remain
outside this command; E2E-245 has contract coverage in
`packages/agent-runtime/src/extensions/bundle.test.ts`.
+The OAuth journey uses synthetic credentials and a loopback provider; it does
+not contact a real identity provider or verify a live account.
For manual inspection, the lower-level steps remain available:
diff --git a/apps/desktop/test/e2e/trusted-extensions/drive.mjs b/apps/desktop/test/e2e/trusted-extensions/drive.mjs
index 6af2242a9..01c7abc64 100644
--- a/apps/desktop/test/e2e/trusted-extensions/drive.mjs
+++ b/apps/desktop/test/e2e/trusted-extensions/drive.mjs
@@ -1,6 +1,7 @@
// MCP-control driver for the trusted extensions E2E run.
import { readFileSync, existsSync, writeFileSync } from "node:fs";
import { connectRenderer } from "./renderer.mjs";
+import { connectRenderer as connectUiRenderer } from "../plugin-ui-slots/clients.mjs";
import { join } from "node:path";
const root = process.env.E2E_ROOT || "/tmp/pi-ext-e2e";
@@ -148,15 +149,132 @@ const providerList = await invoke("providers/list");
const declaredRow = (providerList.providers ?? []).find((p) => p.id === "plugin:e2e.agent:declared");
check("contributed provider is a row owned by its plugin", declaredRow?.ownerPluginId === "e2e.agent", JSON.stringify([declaredRow?.id, declaredRow?.ownerPluginId, declaredRow?.name]));
check("the declared row carries the plugin's endpoint and models", declaredRow?.baseUrl?.endsWith("/v1") === true && (declaredRow?.models ?? []).some((m) => m.id === "stub-1"), JSON.stringify([declaredRow?.baseUrl, declaredRow?.models?.map((m) => m.id)]));
+check("agent plugin receives the provider OAuth permission", (byName.agent?.permissions ?? []).includes("provider.oauth"));
+const pluginOAuthId = "plugin:e2e.agent:declared-oauth";
+const oauthRow = (providerList.providers ?? []).find((p) => p.id === pluginOAuthId);
+check("OAuth provider materializes as a plugin-owned row", oauthRow?.ownerPluginId === "e2e.agent" && oauthRow?.authKind === "oauth", JSON.stringify([oauthRow?.id, oauthRow?.ownerPluginId, oauthRow?.authKind]));
check("other plugins keep no owned provider rows", (providerList.providers ?? []).every((p) => !p.ownerPluginId || p.ownerPluginId === "e2e.agent"));
-// 4) commands in palette/composer (E2E-243)
+// 4) plugin OAuth through the real Settings page, Host-rendered dialog, and
+// provider runtime. The plugin returns only synthetic fixture credentials.
+const ui = await connectUiRenderer(Number(process.env.E2E_CDP_PORT));
+await ui.click('button[data-nav="settings"]');
+await ui.until(() => Boolean(document.querySelector(".settings-shell-full")), null, "Settings page");
+const openedModels = await ui.run((label) => {
+ const button = [...document.querySelectorAll(".settings-nav-item")].find((entry) => entry.textContent?.includes(label));
+ button?.click();
+ return Boolean(button);
+}, "Models");
+check("Model configuration is reachable from Settings navigation", openedModels);
+await ui.until(() => Boolean(document.querySelector("button.model-provider-add")), null, "Add provider action");
+await ui.click("button.model-provider-add");
+await ui.until(
+ (id) => [...document.querySelectorAll("[data-subscription-vendor-id]")].some((entry) => entry.getAttribute("data-subscription-vendor-id") === id),
+ pluginOAuthId,
+ "plugin OAuth provider in the sign-in picker",
+);
+const oauthTile = `[data-subscription-vendor-id="${pluginOAuthId}"]`;
+await ui.click(oauthTile);
+const loginSurface = await ui.until(
+ () => {
+ const dialog = document.querySelector(".oauth-dialog");
+ return Boolean(dialog?.textContent?.includes("E2E-OAUTH-42") && dialog.querySelector('input[type="password"]'));
+ },
+ null,
+ "plugin OAuth device-code and secret prompt",
+);
+check("Host renders the plugin's device code and secure prompt", loginSurface);
+const loginCopy = await ui.run(() => document.querySelector(".oauth-dialog")?.textContent ?? "");
+check("Host dialog shows fixture code and prompt label", loginCopy.includes("E2E-OAUTH-42") && loginCopy.includes("Approve E2E OAuth fixture"));
+await ui.type("e2e-approved");
+await ui.click('.oauth-answer button[type="submit"]');
+await ui.until(
+ (id) => {
+ const row = document.querySelector(`[data-provider-id="${id}"]`);
+ return Boolean(row?.textContent?.includes("[email protected]"));
+ },
+ pluginOAuthId,
+ "signed-in OAuth account row",
+);
+const oauthRowText = await ui.run((id) => document.querySelector(`[data-provider-id="${id}"]`)?.textContent ?? "", pluginOAuthId);
+check("signed-in provider row shows the non-secret account label", oauthRowText.includes("[email protected]"));
+const rendererLeaksCredential = await ui.run(() =>
+ document.body.innerText.includes("expired-plugin-access") || document.body.innerText.includes("plugin-refresh"),
+);
+check("renderer does not display access or refresh tokens", rendererLeaksCredential === false);
+
+// Cancel a second login while its Host prompt is open; the plugin signal must
+// abort without disturbing the credential from the completed login.
+await ui.click("button.model-provider-add");
+await ui.click(oauthTile);
+await ui.until(
+ () => Boolean(document.querySelector('.oauth-dialog input[type="password"]')),
+ null,
+ "second plugin OAuth prompt",
+);
+await ui.click(".provider-dialog-actions button");
+await ui.until(() => !document.querySelector(".oauth-dialog"), null, "cancelled OAuth dialog to close");
+const hookPath = join(root, "hooks.log");
+const cancelDeadline = Date.now() + 10_000;
+while (Date.now() < cancelDeadline && !readFileSync(hookPath, "utf8").includes("provider_oauth_aborted")) {
+ await sleep(50);
+}
+const cancelledOAuth = readFileSync(hookPath, "utf8").includes("provider_oauth_aborted");
+check("cancelling the Host prompt aborts the plugin callback", cancelledOAuth);
+const retainedAccount = await ui.run((id) =>
+ document.querySelector(`[data-provider-id="${id}"]`)?.textContent?.includes("[email protected]") === true,
+ pluginOAuthId,
+);
+check("cancelling another login keeps the existing account", retainedAccount);
+
+await tool("pi_session_configure", {
+ id: sessionId,
+ mode: "agent",
+ providerId: pluginOAuthId,
+ modelId: "oauth-stub-1",
+ confirm: true,
+});
+const oauthTurn = await tool("pi_agent_prompt", { sessionId, content: "use the signed-in plugin OAuth provider" });
+await waitForTurn(sessionId, oauthTurn?.turnId);
+requests = readRequests();
+const oauthRequest = [...requests].reverse().find((request) =>
+ request.payload?.model === "oauth-stub-1" && request.headers?.authorization === "Bearer refreshed-plugin-access",
+);
+check("a model turn refreshes the plugin credential and uses its access token", Boolean(oauthRequest), JSON.stringify(oauthRequest?.headers?.authorization ?? "missing"));
+check("the refresh callback ran in the plugin process", readFileSync(hookPath, "utf8").includes("provider_oauth_refresh"));
+check("refresh credentials never enter model requests", !JSON.stringify(oauthRequest ?? {}).includes("plugin-refresh"));
+
+await ui.click(`[data-provider-id="${pluginOAuthId}"] button[aria-haspopup="menu"]`);
+const armedSignOut = await ui.run(() => {
+ const item = [...document.querySelectorAll('[role="menuitem"]')].find((entry) => entry.textContent?.includes("Sign out"));
+ item?.click();
+ return Boolean(item);
+});
+check("OAuth account row offers a sign-out action", armedSignOut);
+const confirmedSignOut = await ui.run(() => {
+ const item = [...document.querySelectorAll('[role="menuitem"]')].find((entry) => entry.textContent?.includes("Click again to delete"));
+ item?.click();
+ return Boolean(item);
+});
+check("the sign-out action requires its confirmation click", confirmedSignOut);
+const disconnected = await ui.until(
+ async (id) => {
+ const result = await window.piDesktop.invoke(window.piDesktop.channels.invoke.providersOauthVendors);
+ return result.vendors.some((vendor) => vendor.vendorId === id && vendor.accounts.some((account) => !account.connected));
+ },
+ pluginOAuthId,
+ "plugin OAuth sign-out",
+);
+check("sign-out clears the plugin OAuth credential", disconnected);
+ui.close();
+
+// 5) commands in palette/composer (E2E-243)
const palette = await invoke("commandPalette/search", "greet");
check("greet in global search", (palette.commands ?? []).some((c) => c.id === "extension:greet" && c.source === "extension"));
const composer = await invoke("composer/commands");
check("greet in composer slash menu", (composer.commands ?? []).some((c) => c.name === "greet" && c.kind === "extension"));
-// 5) command run + prompt round trip (E2E-243), answered through the broker
+// 6) command run + prompt round trip (E2E-243), answered through the broker
const runPromise = invoke("extensions/commands/run", { sessionId, name: "greet", args: "now" });
// Prompts go to the renderer dialog; main also audits each prompt id in
// plugin.log, so this driver answers them the way the dialog would.
@@ -186,7 +304,7 @@ check("greet handler saw answers, args, and exec", hooks.includes("greet Ann blu
const renamed = await tool("pi_session_get", { id: sessionId });
check("setSessionName renamed the session", (renamed?.session?.title ?? "").startsWith("Hello Ann blue now"), renamed?.session?.title);
-// 6) abort while a prompt is open dismisses it with the abort value (spec §9)
+// 7) abort while a prompt is open dismisses it with the abort value (spec §9)
const before6 = (existsSync(logPath) ? readFileSync(logPath, "utf8") : "").split("\n").filter((l) => l.includes("extension prompt")).length;
const abortRun = invoke("extensions/commands/run", { sessionId, name: "greet", args: "aborted" });
for (let i = 0; i < 40; i++) {
@@ -195,14 +313,14 @@ for (let i = 0; i < 40; i++) {
if (now > before6) break;
}
// Abort retires the command itself, including later UI and exec calls.
-const renderer = await connectRenderer(process.env.E2E_CDP_PORT);
-await renderer.waitForDialog(true);
-writeFileSync(join(root, "prompt-active.png"), Buffer.from(await renderer.screenshot(), "base64"));
+const extensionRenderer = await connectRenderer(process.env.E2E_CDP_PORT);
+await extensionRenderer.waitForDialog(true);
+writeFileSync(join(root, "prompt-active.png"), Buffer.from(await extensionRenderer.screenshot(), "base64"));
const seen6 = new Set(readFileSync(logPath, "utf8").split("\n").map((l) => /"promptId":"([^"]+)"/.exec(l)?.[1]).filter(Boolean));
await tool("pi_agent_abort", { sessionId });
-await renderer.waitForDialog(false);
-writeFileSync(join(root, "prompt-retired.png"), Buffer.from(await renderer.screenshot(), "base64"));
-renderer.close();
+await extensionRenderer.waitForDialog(false);
+writeFileSync(join(root, "prompt-retired.png"), Buffer.from(await extensionRenderer.screenshot(), "base64"));
+extensionRenderer.close();
check("Stop removes the extension dialog from the real renderer", true);
let abortResult;
try { abortResult = await Promise.race([abortRun, sleep(20000).then(() => "timeout")]); } catch (e) { abortResult = String(e); }
@@ -211,7 +329,7 @@ check("abort retires the command before later prompts and exec", abortResult?.ok
const after6 = readFileSync(logPath, "utf8").split("\n").map((l) => /"promptId":"([^"]+)"/.exec(l)?.[1]).filter(Boolean);
check("aborted command publishes no additional prompts", after6.every((id) => seen6.has(id)));
-// 7) sendUserMessage goes through the Host-owned queue (D386) and runs a turn
+// 8) sendUserMessage goes through the Host-owned queue (D386) and runs a turn
const queued = await invoke("extensions/commands/run", { sessionId, name: "queue", args: "" });
check("queue command ran", queued?.ok === true, JSON.stringify(queued));
let queuedSeen = false;
@@ -224,7 +342,7 @@ for (let i = 0; i < 60 && !queuedSeen; i++) {
}
check("queued user message ran as a turn with the extension tool", queuedSeen);
-// 8) plugin-owned model transport: registerAgent + registerProvider + setModel
+// 9) plugin-owned model transport: registerAgent + registerProvider + setModel
// (spec 07-plugins/16 §5, E2E-TRUSTED-EXTENSION-custom-agent-stream-and-binding)
const agentHooks = () => readFileSync(join(root, "hooks.log"), "utf8").split("\n");
const lastLine = (prefix) => [...agentHooks()].reverse().find((l) => l.startsWith(prefix)) ?? "";
diff --git a/apps/desktop/test/e2e/trusted-extensions/seed.mjs b/apps/desktop/test/e2e/trusted-extensions/seed.mjs
index e6e42e827..307c63dcd 100644
--- a/apps/desktop/test/e2e/trusted-extensions/seed.mjs
+++ b/apps/desktop/test/e2e/trusted-extensions/seed.mjs
@@ -141,21 +141,76 @@ function pluginFor(name) {
const dir = join(pluginsDir, name);
mkdirSync(join(dir, "src"), { recursive: true });
writeFileSync(join(dir, "src", `${name}.ts`), readFileSync(join(extDir, `${name}.ts`)));
- writeFileSync(join(dir, "main.js"), "module.exports = {};\n");
+ const mainSource = name === "agent"
+ ? `const { appendFileSync } = require("node:fs");
+const log = (line) => appendFileSync(${JSON.stringify(hookLog)}, line + "\\n");
+module.exports = {
+ async onProviderOAuth(request, { signal }) {
+ if (request.operation === "login") {
+ signal.addEventListener("abort", () => log("provider_oauth_aborted"), { once: true });
+ await globalThis.pi.providers.oauth.notify(request.loginId, {
+ kind: "deviceCode",
+ userCode: "E2E-OAUTH-42",
+ verificationUri: "http://127.0.0.1:${stubPort}/oauth/verify",
+ });
+ const approval = await globalThis.pi.providers.oauth.prompt(request.loginId, {
+ type: "secret",
+ message: "Approve E2E OAuth fixture",
+ placeholder: "Fixture approval",
+ });
+ if (signal.aborted) throw new Error("OAuth login cancelled");
+ if (approval !== "e2e-approved") throw new Error("Unexpected fixture approval");
+ return {
+ accessToken: "expired-plugin-access",
+ refreshToken: "plugin-refresh",
+ expiresAt: Date.now() - 1,
+ accountLabel: "[email protected]",
+ };
+ }
+ if (request.operation === "refresh") {
+ if (request.credential?.refreshToken !== "plugin-refresh") {
+ throw new Error("OAuth refresh credential was not provider-scoped");
+ }
+ log("provider_oauth_refresh");
+ return {
+ accessToken: "refreshed-plugin-access",
+ refreshToken: "plugin-refresh",
+ expiresAt: Date.now() + 60_000,
+ accountLabel: "[email protected]",
+ };
+ }
+ throw new Error("Unsupported fixture OAuth operation");
+ },
+};
+`
+ : "module.exports = {};\n";
+ writeFileSync(join(dir, "main.js"), mainSource);
const permissions = ["agent.extension"];
const contributes = { agentExtensions: [`src/${name}.ts`] };
// The agent fixture also declares a provider row (ADR 0259): the declaration
// materializes in the native provider list, owned by this plugin.
if (name === "agent") {
permissions.push("provider.register");
- contributes.providers = [{
- id: "declared",
- name: "E2E declared",
- baseUrl: `http://127.0.0.1:${stubPort}/v1`,
- apiStyle: "chat_completions",
- authKind: "api_key",
- models: [{ id: "stub-1", name: "Stub 1", contextWindow: 128000, maxTokens: 4096 }],
- }];
+ permissions.push("provider.oauth");
+ contributes.providers = [
+ {
+ id: "declared",
+ name: "E2E declared",
+ baseUrl: `http://127.0.0.1:${stubPort}/v1`,
+ apiStyle: "chat_completions",
+ authKind: "api_key",
+ models: [{ id: "stub-1", name: "Stub 1", contextWindow: 128000, maxTokens: 4096 }],
+ },
+ {
+ id: "declared-oauth",
+ name: "E2E OAuth",
+ baseUrl: `http://127.0.0.1:${stubPort}/v1`,
+ apiStyle: "chat_completions",
+ authKind: "oauth",
+ oauth: { loginLabel: "E2E fixture login", isSubscription: true },
+ models: [{ id: "oauth-stub-1", name: "OAuth Stub 1", contextWindow: 128000, maxTokens: 4096 }],
+ },
+ ];
}
writeFileSync(join(dir, "manifest.json"), JSON.stringify({
schemaVersion: 1,
@@ -201,7 +256,7 @@ const created = await call("providers.create", {
defaultModelId: "stub-1",
});
const providerId = created.provider?.id ?? created.id;
-await call("settings.set", { defaultProviderId: providerId, defaultModelId: "stub-1", defaultMode: "agent" });
+await call("settings.set", { language: "en", defaultProviderId: providerId, defaultModelId: "stub-1", defaultMode: "agent" });
// Register the fixture plugins as development plugins; dev loads enable them
// with their declared permissions. `proj` is limited to the fixture project.
for (const [name, dir] of Object.entries(pluginDirs)) {
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index dca79aee1..88e7d20f8 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -15842,12 +15842,14 @@ plugin-form fixtures in an isolated temporary directory at runtime.
- **Acceptance**: B (model config), E (tools & permissions), F (persistence),
G (plugins), Security, Quality
- **Milestone**: Post-MVP (R7 v1)
-- **Status**: Partially automated (`pnpm test:e2e:trusted-extensions`): the
- API-key declared row materializing with its endpoint, models, and thinking
- binding passes. Ownership refusal, disable/enable, cleanup, and manifest
- validation are covered by host-core checks. OAuth callback, prompt, token
- refresh, cancellation, sign-out, permission presentation, and the renderer's
- provider/account interaction require task-candidate E2E coverage.
+- **Status**: Automated scenario (`pnpm test:e2e:trusted-extensions`) with local
+ synthetic OAuth credentials: the API-key and OAuth declared rows, permission
+ projection, Settings sign-in picker, Host-rendered device-code and secret
+ prompt, encrypted-credential handoff, refresh, model request auth,
+ cancellation, and sign-out are exercised through the real Electron renderer
+ and plugin process. Ownership refusal, disable/enable, cleanup, and malformed
+ manifest cases remain covered by host-core checks. No live identity provider
+ is used.
#### E2E-CHAT-disclosure-toggle-keeps-reading-position