Skip to content

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

fix(providers): handle optional client certificate requests

yixin9a69e1d8863b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 23fd405d2..57b85e956 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -159,6 +159,9 @@ jobs:
- name: Build Desktop bundle
run: pnpm --filter @pi-desktop/desktop build
+ - name: Run provider optional client certificate E2E
+ run: pnpm test:e2e:provider-client-certificate
+
- name: Run browser capture/resize E2E
run: xvfb-run --auto-servernum sh -c 'openbox >/dev/null 2>&1 & exec node scripts/e2e-browser-capture-resize.mjs'
diff --git a/apps/desktop/electron/main/model-discovery.ts b/apps/desktop/electron/main/model-discovery.ts
index 1ba9f5c9b..9c1e1a3b9 100644
--- a/apps/desktop/electron/main/model-discovery.ts
+++ b/apps/desktop/electron/main/model-discovery.ts
@@ -15,6 +15,8 @@
* "Test connection" cannot drift into two different URL or auth rules.
*/
+import { fetchProviderMetadata } from "./provider-metadata-fetch.ts";
+
import {
discoveryProbeUrl,
discoveryStyleForApiStyle,
@@ -280,7 +282,7 @@ async function probeAnthropicMessagesEndpoint(opts: {
if (allowOrigin && originOf(requestUrl) !== allowOrigin) {
throw new Error("message endpoint request refused: it left the configured origin");
}
- const response = await fetch(requestUrl, {
+ const response = await fetchProviderMetadata(requestUrl, {
method: "OPTIONS",
signal: opts.signal,
redirect: "manual",
@@ -361,7 +363,7 @@ export async function probeModelList(opts: {
let url = request.url;
for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
- const res = await fetch(url, {
+ const res = await fetchProviderMetadata(url, {
headers: request.headers,
signal: responseSignal,
// Never let fetch carry the credential to another origin on its own.
diff --git a/apps/desktop/electron/main/provider-certificate-retry.ts b/apps/desktop/electron/main/provider-certificate-retry.ts
new file mode 100644
index 000000000..fb9b429d1
--- /dev/null
+++ b/apps/desktop/electron/main/provider-certificate-retry.ts
@@ -0,0 +1,15 @@
+import { parseProxyUrl } from "@pi-desktop/shared";
+import { socks5Connect } from "@pi-desktop/agent-runtime/proxy-tunnel";
+import { ensureSystemProxyRelay } from "./network-proxy";
+import { fetchHttpsMetadata } from "./provider-https-metadata";
+import type { ProviderMetadataFetch } from "./provider-metadata-fetch";
+
+/** The existing authenticated relay resolves the active Chromium route per URL,
+ * including Direct, System/PAC, custom proxies and bypass rules. */
+export const fetchProviderWithoutClientCertificate: ProviderMetadataFetch = async (url, init) => {
+ init.signal.throwIfAborted();
+ const relay = parseProxyUrl(await ensureSystemProxyRelay());
+ init.signal.throwIfAborted();
+ if (!relay.ok) throw new Error("invalid provider proxy relay");
+ return fetchHttpsMetadata(url, init, (host, port) => socks5Connect(relay.value, host, port));
+};
diff --git a/apps/desktop/electron/main/provider-https-metadata.ts b/apps/desktop/electron/main/provider-https-metadata.ts
new file mode 100644
index 000000000..ea3f0f683
--- /dev/null
+++ b/apps/desktop/electron/main/provider-https-metadata.ts
@@ -0,0 +1,108 @@
+import { once } from "node:events";
+import { Agent, request } from "node:https";
+import { isIP, type Socket } from "node:net";
+import { buffer } from "node:stream/consumers";
+import { connect as tlsConnect, getCACertificates } from "node:tls";
+import { createBrotliDecompress, createUnzip } from "node:zlib";
+import type { ProviderMetadataRequest } from "./provider-metadata-fetch";
+
+type Connect = (host: string, port: number) => Promise<Socket>;
+
+/** Own a late tunnel even when cancellation wins the race to connect. */
+async function connectWithSignal(connect: () => Promise<Socket>, signal: AbortSignal): Promise<Socket> {
+ signal.throwIfAborted();
+ return new Promise((resolve, reject) => {
+ const abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ void connect().then((socket) => {
+ signal.removeEventListener("abort", abort);
+ if (signal.aborted) {
+ socket.destroy();
+ reject(signal.reason);
+ } else resolve(socket);
+ }, (error: unknown) => {
+ signal.removeEventListener("abort", abort);
+ reject(error);
+ });
+ });
+}
+
+/** One HTTPS metadata request, with no redirects, cookies or client identity.
+ * The caller supplies the route; TLS still verifies the original hostname.
+ * Buffering the small metadata response gives each attempt a bounded socket
+ * lifetime, including cancellation during body consumption. */
+export async function fetchHttpsMetadata(
+ url: string,
+ init: ProviderMetadataRequest,
+ connect: Connect,
+): Promise<Response> {
+ const target = new URL(url);
+ if (target.protocol !== "https:" || target.username || target.password) {
+ throw new Error("provider metadata retry requires an HTTPS URL without userinfo");
+ }
+ const host = target.hostname.replace(/^\[|\]$/g, "");
+ const raw = await connectWithSignal(() => connect(host, Number(target.port) || 443), init.signal);
+ // Keep the bundled/extra roots and OS roots, as the sidecar does (#1187).
+ // This is per-request: never change the process-wide TLS defaults.
+ let socket;
+ try {
+ socket = tlsConnect({
+ socket: raw,
+ host,
+ ...(isIP(host) ? {} : { servername: host }),
+ ca: [...new Set([...getCACertificates("default"), ...getCACertificates("system")])],
+ rejectUnauthorized: true,
+ ALPNProtocols: ["http/1.1"],
+ });
+ } catch (error) {
+ raw.destroy();
+ throw error;
+ }
+ const agent = new Agent({ keepAlive: false, maxCachedSessions: 0 });
+ agent.createConnection = () => socket;
+ const abort = () => socket.destroy(new DOMException("The operation was aborted", "AbortError"));
+ init.signal.addEventListener("abort", abort, { once: true });
+ try {
+ const connected = once(socket, "secureConnect", { signal: init.signal });
+ await connected;
+ init.signal.throwIfAborted();
+ return await new Promise<Response>((resolve, reject) => {
+ const req = request(target, {
+ agent,
+ method: init.method ?? "GET",
+ headers: { ...init.headers, "accept-encoding": "identity" },
+ signal: init.signal,
+ }, (incoming) => {
+ void (async () => {
+ const headers = new Headers();
+ for (const [name, value] of Object.entries(incoming.headers)) {
+ if (Array.isArray(value)) for (const item of value) headers.append(name, item);
+ else if (value !== undefined) headers.set(name, value);
+ }
+ const encoding = incoming.headers["content-encoding"];
+ const decoder = encoding === "br" ? createBrotliDecompress()
+ : encoding === "gzip" || encoding === "deflate" ? createUnzip() : null;
+ // Even a server ignoring Accept-Encoding must produce fetch's decoded body.
+ if (decoder) incoming.on("error", (error) => decoder.destroy(error));
+ try {
+ const body = await buffer(decoder ? incoming.pipe(decoder) : incoming);
+ const status = incoming.statusCode ?? 0;
+ resolve(new Response([204, 205, 304].includes(status) ? null : body, { status, headers }));
+ } finally {
+ decoder?.destroy();
+ incoming.destroy();
+ }
+ })().catch(reject);
+ });
+ req.once("error", reject);
+ req.end();
+ });
+ } catch (error) {
+ init.signal.throwIfAborted();
+ throw error;
+ } finally {
+ init.signal.removeEventListener("abort", abort);
+ socket.destroy();
+ agent.destroy();
+ }
+}
diff --git a/apps/desktop/electron/main/provider-metadata-fetch.ts b/apps/desktop/electron/main/provider-metadata-fetch.ts
new file mode 100644
index 000000000..c172ecc3d
--- /dev/null
+++ b/apps/desktop/electron/main/provider-metadata-fetch.ts
@@ -0,0 +1,43 @@
+/** Metadata probes are replayable; agent turns and plugin requests are not. */
+export type ProviderMetadataRequest = {
+ method?: "GET" | "OPTIONS";
+ headers?: Record<string, string>;
+ signal: AbortSignal;
+ redirect: "manual";
+};
+
+export type ProviderMetadataFetch = (
+ url: string,
+ init: ProviderMetadataRequest,
+) => Promise<Response>;
+
+export function createProviderMetadataFetch(
+ primary: ProviderMetadataFetch,
+ withoutClientCertificate: ProviderMetadataFetch,
+): ProviderMetadataFetch {
+ return async (url, init) => {
+ try {
+ return await primary(url, init);
+ } catch (error) {
+ // Electron 43 drops the certificate responder before sending HTTP.
+ // Never retry unrelated TLS failures, HTTP errors or cancelled work.
+ if (
+ !(error instanceof Error) ||
+ error.message !== "net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED" ||
+ new URL(url).protocol !== "https:" ||
+ (init.method !== undefined && init.method !== "GET" && init.method !== "OPTIONS")
+ ) throw error;
+ init.signal.throwIfAborted();
+ return withoutClientCertificate(url, init);
+ }
+ };
+}
+
+export const fetchProviderMetadata = createProviderMetadataFetch(
+ (url, init) => fetch(url, init),
+ async (url, init) => {
+ const { fetchProviderWithoutClientCertificate } = await import("./provider-certificate-retry");
+ init.signal.throwIfAborted();
+ return fetchProviderWithoutClientCertificate(url, init);
+ },
+);
diff --git a/apps/desktop/test/provider-https-metadata.test.mjs b/apps/desktop/test/provider-https-metadata.test.mjs
new file mode 100644
index 000000000..ed0093785
--- /dev/null
+++ b/apps/desktop/test/provider-https-metadata.test.mjs
@@ -0,0 +1,152 @@
+import assert from "node:assert/strict";
+import { once } from "node:events";
+import { readFile } from "node:fs/promises";
+import { createServer } from "node:https";
+import { register } from "node:module";
+import { connect as tcpConnect } from "node:net";
+import { getCACertificates, setDefaultCACertificates } from "node:tls";
+import { gzipSync } from "node:zlib";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { fetchHttpsMetadata } = await import("../electron/main/provider-https-metadata.ts");
+const fixtures = new URL("../../../scripts/e2e/fixtures/certificates/", import.meta.url);
+const cert = await readFile(new URL("localhost-cert.pem", fixtures), "utf8");
+const key = await readFile(new URL("localhost-key.pem", fixtures), "utf8");
+
+async function fixture(t, { required = false, handler } = {}) {
+ const sockets = new Set();
+ const received = [];
+ const server = createServer({ cert, key, ca: cert, requestCert: true, rejectUnauthorized: required }, (req, res) => {
+ received.push({ url: req.url, method: req.method, auth: req.headers.authorization, certificate: req.socket.getPeerCertificate() });
+ if (handler) return handler(req, res);
+ res.writeHead(req.headers.authorization === "Bearer fixture" ? 200 : 401, { "content-type": "application/json" });
+ res.end(JSON.stringify({ data: [{ id: "fixture-model" }] }));
+ });
+ server.on("connection", (socket) => {
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ t.after(async () => {
+ for (const socket of sockets) socket.destroy();
+ await new Promise((resolve) => server.close(resolve));
+ });
+ return { server, received, url: `https://localhost:${server.address().port}/v1/models` };
+}
+
+const init = (signal = new AbortController().signal) => ({ headers: { Authorization: "Bearer fixture" }, redirect: "manual", signal });
+async function connect(_host, port) {
+ const socket = tcpConnect({ host: "127.0.0.1", port });
+ await once(socket, "connect");
+ return socket;
+}
+function trustFixture(t) {
+ const defaults = getCACertificates("default");
+ setDefaultCACertificates([...defaults, cert]);
+ t.after(() => setDefaultCACertificates(defaults));
+}
+
+test("optional client certificates permit authenticated metadata and ordinary 401 responses", async (t) => {
+ trustFixture(t);
+ const { url, received } = await fixture(t);
+ const response = await fetchHttpsMetadata(url, init(), connect);
+ assert.equal(response.status, 200);
+ assert.deepEqual(await response.json(), { data: [{ id: "fixture-model" }] });
+ assert.deepEqual(received[0], { url: "/v1/models", method: "GET", auth: "Bearer fixture", certificate: {} });
+ assert.equal((await fetchHttpsMetadata(url, { ...init(), headers: {} }, connect)).status, 401);
+});
+
+test("required client authentication still fails", async (t) => {
+ trustFixture(t);
+ const { url, received } = await fixture(t, { required: true });
+ await assert.rejects(fetchHttpsMetadata(url, init(), connect));
+ assert.equal(received.length, 0);
+});
+
+test("untrusted server certificates are rejected", async (t) => {
+ const { url, received } = await fixture(t);
+ await assert.rejects(fetchHttpsMetadata(url, init(), connect), { code: "DEPTH_ZERO_SELF_SIGNED_CERT" });
+ assert.equal(received.length, 0);
+});
+
+test("hostname validation is retained even through a supplied tunnel", async (t) => {
+ trustFixture(t);
+ const { url, received } = await fixture(t);
+ await assert.rejects(fetchHttpsMetadata(url.replace("localhost", "127.0.0.1"), init(), connect), { code: "ERR_TLS_CERT_ALTNAME_INVALID" });
+ assert.equal(received.length, 0);
+});
+
+test("redirects are returned to the existing origin guard without sending credentials onward", async (t) => {
+ trustFixture(t);
+ const { url, received } = await fixture(t, { handler: (_req, res) => {
+ res.writeHead(302, { location: "https://other.example/v1/models" });
+ res.end();
+ } });
+ const response = await fetchHttpsMetadata(url, init(), connect);
+ assert.equal(response.status, 302);
+ assert.equal(response.headers.get("location"), "https://other.example/v1/models");
+ assert.equal(received.length, 1);
+});
+
+test("compressed metadata is decoded", async (t) => {
+ trustFixture(t);
+ const { url } = await fixture(t, { handler: (_req, res) => {
+ res.writeHead(200, { "content-encoding": "gzip" });
+ res.end(gzipSync('{"data":[]}'));
+ } });
+ assert.deepEqual(await (await fetchHttpsMetadata(url, init(), connect)).json(), { data: [] });
+});
+
+test("aborting while the response body is pending closes the request", async (t) => {
+ trustFixture(t);
+ const controller = new AbortController();
+ const { url } = await fixture(t, { handler: (_req, res) => {
+ res.writeHead(200);
+ res.write('{"data":[');
+ controller.abort();
+ } });
+ await assert.rejects(fetchHttpsMetadata(url, init(controller.signal), connect), { name: "AbortError" });
+});
+
+test("cancellation rejects before a late tunnel arrives and closes that tunnel", async () => {
+ const controller = new AbortController();
+ let deliver;
+ const connected = new Promise((resolve) => { deliver = resolve; });
+ const request = fetchHttpsMetadata("https://localhost/v1/models", init(controller.signal), () => connected);
+ controller.abort();
+ await assert.rejects(request, { name: "AbortError" });
+ const { Socket } = await import("node:net");
+ const socket = new Socket();
+ deliver(socket);
+ await once(socket, "close");
+ assert.equal(socket.destroyed, true);
+});
+
+
+test("the original timeout reason survives cancellation during TLS handshake", async (t) => {
+ const controller = new AbortController();
+ const timeout = new DOMException("metadata budget exhausted", "TimeoutError");
+ const { createServer: createTcpServer } = await import("node:net");
+ const server = createTcpServer((socket) => {
+ t.after(() => socket.destroy());
+ controller.abort(timeout);
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ t.after(() => new Promise((resolve) => server.close(resolve)));
+ const port = server.address().port;
+ await assert.rejects(fetchHttpsMetadata(`https://localhost:${port}/models`, init(controller.signal), connect), (error) => error === timeout);
+});
+
+test("OPTIONS probes keep their method and pre-aborted probes never connect", async (t) => {
+ trustFixture(t);
+ const { url, received } = await fixture(t);
+ const response = await fetchHttpsMetadata(url, { ...init(), method: "OPTIONS" }, connect);
+ assert.equal(response.status, 200);
+ assert.equal(received[0].method, "OPTIONS");
+ await assert.rejects(fetchHttpsMetadata(url, init(AbortSignal.abort()), () => {
+ assert.fail("pre-aborted probe connected");
+ }), { name: "AbortError" });
+});
diff --git a/apps/desktop/test/provider-metadata-fetch.test.mjs b/apps/desktop/test/provider-metadata-fetch.test.mjs
new file mode 100644
index 000000000..84b188797
--- /dev/null
+++ b/apps/desktop/test/provider-metadata-fetch.test.mjs
@@ -0,0 +1,59 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { createProviderMetadataFetch } = await import("../electron/main/provider-metadata-fetch.ts");
+
+const url = "https://provider.example/v1/models";
+const options = () => ({ headers: { Authorization: "Bearer fixture" }, redirect: "manual", signal: new AbortController().signal });
+const certificateError = () => new Error("net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED");
+
+test("optional client certificate failure retries the same metadata request once", async () => {
+ const init = options();
+ const transport = createProviderMetadataFetch(async (target, request) => {
+ assert.equal(target, url);
+ assert.equal(request, init);
+ throw certificateError();
+ }, async (target, request) => {
+ assert.equal(target, url);
+ assert.equal(request, init);
+ return new Response('{"data":[{"id":"fixture-model"}]}');
+ });
+ assert.deepEqual(await (await transport(url, init)).json(), { data: [{ id: "fixture-model" }] });
+});
+
+test("HTTP responses and unrelated TLS/network errors never use the fallback", async () => {
+ const forbidden = () => { assert.fail("unexpected fallback"); };
+ for (const status of [200, 401, 403, 429, 500]) {
+ const response = new Response("", { status });
+ assert.equal(await createProviderMetadataFetch(async () => response, forbidden)(url, options()), response);
+ }
+ for (const message of ["net::ERR_CERT_AUTHORITY_INVALID", "net::ERR_CERT_COMMON_NAME_INVALID", "net::ERR_CONNECTION_RESET", "net::ERR_TIMED_OUT", "net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED_SUFFIX"]) {
+ const error = new Error(message);
+ await assert.rejects(createProviderMetadataFetch(async () => { throw error; }, forbidden)(url, options()), (actual) => actual === error);
+ }
+});
+
+test("fallback failures propagate without another retry", async () => {
+ const failure = new Error("client certificate required by server");
+ await assert.rejects(createProviderMetadataFetch(async () => { throw certificateError(); }, async () => { throw failure; })(url, options()), (error) => error === failure);
+});
+
+test("an aborted request cannot start a second transport", async () => {
+ const controller = new AbortController();
+ const transport = createProviderMetadataFetch(async () => {
+ controller.abort();
+ throw certificateError();
+ }, () => { assert.fail("aborted retry"); });
+ await assert.rejects(transport(url, { ...options(), signal: controller.signal }), { name: "AbortError" });
+});
+
+test("non-metadata methods and non-HTTPS URLs cannot be replayed", async () => {
+ const error = certificateError();
+ const transport = createProviderMetadataFetch(async () => { throw error; }, () => { assert.fail("unsafe replay"); });
+ for (const method of ["POST", "PUT", "DELETE"]) {
+ await assert.rejects(transport(url, { ...options(), method }), (actual) => actual === error);
+ }
+ await assert.rejects(transport("http://provider.example/models", options()), (actual) => actual === error);
+});
diff --git a/docs/adr/README.md b/docs/adr/README.md
index c65981843..b35889ea2 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -20,6 +20,7 @@ Each ADR includes:
| ID | Title | Status |
|---|---|---|
+| provider-metadata-client-certificate-retry | [Provider metadata recovery from optional client certificates](provider-metadata-client-certificate-retry.md) | Implemented candidate |
| device-local-project-lists-in-config-sync | [Device-local project lists in configuration sync](device-local-project-lists-in-config-sync.md) | Accepted |
| s3-only-configuration-backup-sync | [S3-only encrypted configuration backup and synchronization](s3-only-configuration-backup-sync.md) | Accepted; supersedes WebDAV decisions in 0300 / 0301 |
| remote-provider-import | [Explicit provider import into a running remote Host](remote-provider-import.md) | Accepted for the experimental SSH MVP |
diff --git a/docs/adr/provider-metadata-client-certificate-retry.md b/docs/adr/provider-metadata-client-certificate-retry.md
new file mode 100644
index 000000000..f5742f92f
--- /dev/null
+++ b/docs/adr/provider-metadata-client-certificate-retry.md
@@ -0,0 +1,58 @@
+# Provider metadata recovery from optional client certificate requests
+
+- Status: Implemented candidate
+- Date: 2026-10-16
+- Related: issue #1676, ADR 0177, `03-runtime/07-process-model.md`
+
+## Context
+
+Electron 43's net module leaves its client certificate responder unimplemented.
+A server requesting an optional client certificate therefore aborts model
+metadata discovery with `net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED` before HTTP is
+sent, even when it accepts an empty client identity. An app-level
+`select-client-certificate` listener cannot reach that path. Electron #52162
+fixes it in 44, but that release also removes macOS 12 support and changes the
+clipboard API. This repair retains the existing platform compatibility.
+
+## Decision
+
+Keep Chromium as the primary transport. Extract the metadata transport from
+model discovery and connection probes. On exactly the client-auth-certificate
+error, retry that HTTPS GET or OPTIONS once through Node TLS, without a client
+identity. Do not install a global fetch fallback or retry agent turns, plugin
+requests, ordinary HTTP responses, unrelated TLS failures or cancelled work.
+
+The retry uses the existing authenticated loopback SOCKS relay. Its resolver
+consults the default Chromium session, including the active System/PAC, Direct,
+custom proxy and bypass configuration. There is no direct fallback when proxy
+routing fails. The request retains its original AbortSignal and manual redirect
+mode; the existing model discovery origin guard remains the only redirect owner.
+
+Use bundled/default and OS CA roots per request, without changing process-wide
+TLS settings or disabling chain, expiration or hostname verification. The
+metadata attempt owns its tunnel, TLS socket and HTTP agent through response
+consumption and closes them on success, failure or cancellation. A tunnel that
+completes after cancellation is destroyed on arrival; the underlying existing
+SOCKS handshake remains bounded by its own timeout.
+
+## Consequences
+
+Optional client authentication reaches ordinary HTTP responses; mandatory client
+authentication still fails. There are no persistence, IPC or plugin contract
+changes. The Node retry inherits the existing relay limitation for interactive
+or OS-integrated proxy authentication and fails closed in those environments.
+
+A focused Electron E2E reproduces the original failure and exercises actual
+model discovery and connection tests through direct and authenticated proxy
+routes. Lower-level TLS tests cover trust, hostname validation, mandatory client
+authentication, redirects, compressed metadata and cancellation.
+
+## Alternatives
+
+- Electron 44: the upstream solution, but requires a separate platform/API
+ migration decision. Remove the compatibility retry when a validated runtime
+ provides native recovery and an explicit client-identity policy.
+- Only add an app event handler: Electron 43 never emits it for net requests.
+- Replace global fetch with Node: changes unrelated networking, cookies, proxy
+ authentication and plugin behavior.
+- Disable server certificate checks: unrelated to the root cause and unsafe.
diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.md
index db39b7499..823540b3f 100644
--- a/docs/spec/03-runtime/07-process-model.md
+++ b/docs/spec/03-runtime/07-process-model.md
@@ -86,6 +86,17 @@ cannot carry userinfo (issue #490). host-core marketplace `curl` gets explicit
proxy arguments and does **not** inherit proxy env, so workspace Bash cannot
see proxy credentials. Direct mode bypasses the System relay. TLS certificate
verification remains enabled on every route.
+
+Provider model-list and connection probes recover from Electron 43's exact
+`net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED` failure with one Node HTTPS metadata
+attempt through the same authenticated relay and active Chromium proxy route.
+The retry supplies no client certificate, retains the original cancellation
+budget and manual redirect/origin checks, and validates the server certificate
+and hostname with default plus OS CA roots. Mandatory client authentication
+continues to fail. Other TLS errors, HTTP responses and cancelled requests do
+not trigger this retry; agent turns and plugin requests are unaffected. See
+[the metadata transport decision](../../adr/provider-metadata-client-certificate-retry.md).
+
Marketplace curl diagnostics prefer UTF-8 and fall back to the active Windows
ANSI code page before crossing the UTF-8 RPC boundary, so localized Schannel
errors remain readable instead of becoming replacement characters.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 380d370ae..bd10a626e 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -10072,6 +10072,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| Acceptance | Scenarios |
|---|---|
+| B / Security / Quality — Optional provider client certificate requests | E2E-PROVIDER-optional-client-certificate |
| C / E / F / Quality / Security — Session Todo checklist | E2E-CHAT-session-todo-checklist |
| C / E / Security / Quality — Live Voice four-stage interaction | E2E-LIVE-VOICE-four-stage-ui |
| C / F — Hourly task updates | E2E-SCHEDULED-manual-to-hourly |
@@ -18137,3 +18138,28 @@ host-created files. The full app's file-preview viewer is covered separately.
the theme-token and reduced-motion guarantees; the interactive sidebar
scenario remains a manual validation scenario run in a capable
environment.
+
+### E2E-PROVIDER-optional-client-certificate
+
+- **Preconditions:** The locked Electron 43 runtime, built workspace packages,
+ and an isolated profile. Only a local HTTPS fixture and local proxy are used;
+ trust is confined to the test process/session and fixture certificate.
+- **Steps:** Run `node scripts/e2e-provider-client-certificate.mjs`. Confirm the
+ original `net.fetch` aborts before HTTP. Probe the model list and connection
+ through the real metadata service; repeat with an invalid fixture key and an
+ authenticated custom HTTP proxy. Return a cross-origin redirect, then cancel
+ a pending response.
+- **Expected:** Valid credentials return the fixture model; invalid credentials
+ reach HTTP 401. The retry follows the proxy route, sends no client identity,
+ refuses cross-origin redirects and aborts with the original signal.
+- **Security coverage:** `provider-https-metadata.test.mjs` additionally checks
+ mandatory client authentication, untrusted server certificates, hostname
+ mismatch, compressed responses, and late-tunnel cleanup. The metadata policy
+ tests reject fallback on other TLS/network errors or HTTP failures.
+- **Specs linked:** `03-runtime/07-process-model.md`,
+ ADR `provider-metadata-client-certificate-retry`, issue #1676.
+- **Acceptance:** Recovery without an Electron major upgrade, TLS verification
+ bypass, direct proxy bypass, or change to persisted provider bindings.
+- **Milestone:** Maintenance.
+- **Status:** Automated fixture; record the tested head/base and execution
+ result in the delivery report.
diff --git a/package.json b/package.json
index b0897e67d..09f2cd427 100644
--- a/package.json
+++ b/package.json
@@ -46,6 +46,7 @@
"test:e2e:copy-tex": "node scripts/e2e-copy-tex.mjs",
"test:e2e:transcript-disclosure": "node scripts/e2e-transcript-disclosure-anchor.mjs",
"test:e2e:images": "node scripts/e2e-image-generation.mjs && node scripts/e2e-image-generation-ui.mjs && node scripts/e2e-image-chat.mjs",
+ "test:e2e:provider-client-certificate": "node scripts/e2e-provider-client-certificate.mjs",
"test:e2e:provider-order": "node scripts/e2e-provider-order.mjs",
"test:e2e:project-edit": "node scripts/e2e-project-edit.mjs",
"test:e2e:provider-api-style": "node scripts/e2e-provider-api-style.mjs",
diff --git a/scripts/README.md b/scripts/README.md
index 1bcdb7159..e2dba3b88 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -58,6 +58,7 @@ The scenarios are specified in
| `e2e-transcript-cache.mjs` | `pnpm test:e2e:transcript-cache` | Isolated Host RPC regression for large transcript cache creation, append plus middle Task rewrite, legacy cache recovery, paging, message navigation, invalid UTF-8 recovery, and process restart |
| `e2e-plan-ui.mjs` | `pnpm test:e2e:plan-ui` | Plan approval through the rendered UI |
| `e2e-electron-boot.mjs` | `pnpm test:e2e:boot` | Electron boot probe |
+| `e2e-provider-client-certificate.mjs` | `pnpm test:e2e:provider-client-certificate` | Isolated Electron 43 model discovery with optional client certificates, authenticated proxy routing, redirects and cancellation |
| `e2e-provider-recovery.mjs` | `node scripts/e2e-provider-recovery.mjs` | Isolated desktop with a localhost fault-injection provider: socket failures, interrupted streams, Responses recovery, exhausted retries, Continue, and recovery across eleven real Read calls. Requires a built desktop/runtime and host binary (`PI_DESKTOP_HOST_BIN` when outside the checkout); retains screenshots and JSON under `.artifacts/issue-699/` |
| `e2e-settings-scroll.mjs` | `pnpm test:e2e:settings-scroll` | Production Settings component navigation, search anchoring, focus-on-mount, and scroll behavior |
| `e2e-transcript-render.mjs` | `pnpm test:e2e:transcript` | Production transcript render boundaries, runtime status geometry, and deterministic smooth-text cadence |
diff --git a/scripts/e2e-provider-client-certificate.mjs b/scripts/e2e-provider-client-certificate.mjs
new file mode 100644
index 000000000..2876c7479
--- /dev/null
+++ b/scripts/e2e-provider-client-certificate.mjs
@@ -0,0 +1,41 @@
+#!/usr/bin/env node
+/** Real Electron net.fetch + model discovery against an isolated TLS fixture. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtemp, rm } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = fileURLToPath(new URL("..", import.meta.url));
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const { electronBinary } = resolveElectronBinary(root);
+const temp = await mkdtemp(join(tmpdir(), "pi-client-certificate-"));
+try {
+ await build({
+ entryPoints: [join(root, "scripts/e2e/provider-client-certificate.ts")],
+ outfile: join(temp, "main.mjs"), bundle: true, platform: "node", format: "esm",
+ banner: { js: "import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);" },
+ external: ["electron"],
+ });
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.mjs"), temp,
+ join(root, "scripts/e2e/fixtures/certificates")], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", (chunk) => {
+ output += chunk;
+ process.stdout.write(chunk);
+ });
+ const timer = setTimeout(() => child.kill(), 60_000);
+ try {
+ const code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ assert.equal(code, 0, output);
+ assert.match(output, /provider client certificate E2E passed/);
+ } finally { clearTimeout(timer); }
+} finally { await rm(temp, { recursive: true, force: true }); }
diff --git a/scripts/e2e/provider-client-certificate.ts b/scripts/e2e/provider-client-certificate.ts
new file mode 100644
index 000000000..c9b70710e
--- /dev/null
+++ b/scripts/e2e/provider-client-certificate.ts
@@ -0,0 +1,112 @@
+import assert from "node:assert/strict";
+import { X509Certificate } from "node:crypto";
+import { once } from "node:events";
+import { readFileSync } from "node:fs";
+import { createServer as createHttpsServer } from "node:https";
+import { createServer as createHttpServer } from "node:http";
+import { connect, type Socket } from "node:net";
+import { join } from "node:path";
+import { getCACertificates, setDefaultCACertificates, type TLSSocket } from "node:tls";
+import { app, net, session } from "electron";
+import { applyNetworkProxy, disposeSystemProxyRelay } from "../../apps/desktop/electron/main/network-proxy";
+import { probeModelList, probeProviderEndpoint } from "../../apps/desktop/electron/main/model-discovery";
+
+app.setPath("userData", process.argv[2]);
+app.commandLine.appendSwitch("ozone-platform", "headless");
+app.disableHardwareAcceleration();
+const fixture = process.argv[3];
+const cert = readFileSync(join(fixture, "localhost-cert.pem"), "utf8");
+const key = readFileSync(join(fixture, "localhost-key.pem"), "utf8");
+const fingerprint = new X509Certificate(cert).fingerprint256;
+const sockets = new Set<Socket>();
+let requests = 0;
+let mode: "models" | "redirect" | "stall" = "models";
+let requestStarted: (() => void) | undefined;
+const server = createHttpsServer({ key, cert, ca: cert, requestCert: true, rejectUnauthorized: false }, (req, res) => {
+ requests++;
+ assert.deepEqual((req.socket as TLSSocket).getPeerCertificate(), {});
+ if (mode === "redirect") {
+ res.writeHead(302, { location: "https://other.example/v1/models" });
+ res.end();
+ return;
+ }
+ if (mode === "stall") { requestStarted?.(); return; }
+ res.writeHead(req.headers.authorization === "Bearer fixture" ? 200 : 401, { "content-type": "application/json" });
+ res.end(JSON.stringify({ data: [{ id: "fixture-model" }] }));
+});
+const proxy = createHttpServer();
+let tunnels = 0;
+proxy.on("connect", (req, client, head) => {
+ assert.equal(req.headers["proxy-authorization"], `Basic ${Buffer.from("fixture:password").toString("base64")}`);
+ const target = new URL(`http://${req.url}`);
+ assert.equal(target.hostname, "localhost");
+ tunnels++;
+ const upstream = connect({ host: "127.0.0.1", port: Number(target.port) });
+ sockets.add(upstream);
+ upstream.on("close", () => sockets.delete(upstream));
+ upstream.on("error", () => client.destroy());
+ client.on("error", () => upstream.destroy());
+ client.on("close", () => upstream.destroy());
+ upstream.on("connect", () => {
+ client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
+ if (head.length) upstream.write(head);
+ client.pipe(upstream).pipe(client);
+ });
+});
+for (const listener of [server, proxy]) listener.on("connection", (socket) => {
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+});
+
+void app.whenReady().then(async () => {
+ try {
+ // Trust only this local fixture, only in this isolated Electron session.
+ session.defaultSession.setCertificateVerifyProc((request, callback) => {
+ const matches = request.hostname === "localhost" &&
+ new X509Certificate(request.certificate.data).fingerprint256 === fingerprint;
+ callback(matches ? 0 : -3);
+ });
+ setDefaultCACertificates([...getCACertificates("default"), cert]);
+ server.listen(0, "127.0.0.1");
+ proxy.listen(0, "127.0.0.1");
+ await Promise.all([once(server, "listening"), once(proxy, "listening")]);
+ const address = server.address();
+ const proxyAddress = proxy.address();
+ assert.ok(address && typeof address !== "string" && proxyAddress && typeof proxyAddress !== "string");
+ const baseUrl = `https://localhost:${address.port}/v1`;
+ await applyNetworkProxy({ mode: "direct" });
+ await assert.rejects(net.fetch(`${baseUrl}/models`), /ERR_SSL_CLIENT_AUTH_CERT_NEEDED/);
+ assert.equal(requests, 0, "the original Electron 43 failure precedes HTTP");
+ console.log("baseline: Electron 43 net.fetch fails before HTTP");
+ const options = { baseUrl, apiKey: "fixture", signal: AbortSignal.timeout(8_000) };
+ assert.deepEqual((await probeModelList(options)).models, [{ modelId: "fixture-model", displayName: "fixture-model" }]);
+ assert.equal((await probeProviderEndpoint(options)).status, 200);
+ await assert.rejects(probeModelList({ ...options, apiKey: "wrong" }), { status: 401 });
+ await applyNetworkProxy({ mode: "custom", url: `http://fixture:[email protected]:${proxyAddress.port}`, bypass: "<-loopback>" });
+ const before = tunnels;
+ assert.equal((await probeProviderEndpoint(options)).status, 200);
+ assert.ok(tunnels > before, "the retry must use the configured authenticated proxy");
+ await applyNetworkProxy({ mode: "custom", url: `http://fixture:[email protected]:${proxyAddress.port}` });
+ const beforeBypass = tunnels;
+ assert.equal((await probeProviderEndpoint(options)).status, 200);
+ assert.equal(tunnels, beforeBypass, "localhost bypass must apply to both transports");
+ await applyNetworkProxy({ mode: "direct" });
+ mode = "redirect";
+ await assert.rejects(probeModelList(options), /left the configured origin/);
+ mode = "stall";
+ const controller = new AbortController();
+ const started = new Promise<void>((resolve) => { requestStarted = resolve; });
+ const pending = probeModelList({ ...options, signal: controller.signal });
+ await started;
+ controller.abort();
+ await assert.rejects(pending, { name: "AbortError" });
+ console.log("provider client certificate E2E passed");
+ await disposeSystemProxyRelay();
+ for (const socket of sockets) socket.destroy();
+ await Promise.all([new Promise<void>((resolve) => server.close(() => resolve())), new Promise<void>((resolve) => proxy.close(() => resolve()))]);
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ app.exit(1);
+ }
+});