Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(network): trust system certificates and stop certificate retries
hui4559ea66b9c7d43
diff --git a/apps/desktop/electron/main/agent-sidecar.ts b/apps/desktop/electron/main/agent-sidecar.tsindex 3b0daadae..0f97f3cc1 100644--- a/apps/desktop/electron/main/agent-sidecar.ts+++ b/apps/desktop/electron/main/agent-sidecar.ts@@ -52,7 +52,9 @@ export class AgentSidecar extends RuntimeAgentSidecar {super({launch: {command: process.execPath,- args: [resolveSidecarEntry()],+ // Electron 43's Node supports the OS trust store. Keep bundled roots+ // and inherited NODE_EXTRA_CA_CERTS; never bypass TLS verification.+ args: ["--use-system-ca", resolveSidecarEntry()],env: {...process.env,ELECTRON_RUN_AS_NODE: "1",diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsxindex debdf1aa5..8a6ce8937 100644--- a/apps/desktop/src/features/chat/transcript/shared.tsx+++ b/apps/desktop/src/features/chat/transcript/shared.tsx@@ -14,6 +14,7 @@ import type {} from "@pi-desktop/shared";import {formatCompactTokenCount,+ isCertificateVerificationError,THINKING_LEVELS,type ThinkingLevel,} from "@pi-desktop/shared";@@ -136,7 +137,16 @@ export function AssistantErrorMessage({ message }: { message: UiMessage }) {const detailsId = useId();const error = message.error;if (!error) return null;- const localizedKey = `errors.${error.code}`;+ const networkDetails = error.details;+ const certificateFailure =+ error.code === "NETWORK_ERROR" &&+ networkDetails !== null && typeof networkDetails === "object" &&+ isCertificateVerificationError(+ (networkDetails as { networkCode?: unknown }).networkCode,+ );+ const localizedKey = certificateFailure+ ? "errors.providerCertificate"+ : `errors.${error.code}`;const localized = t(localizedKey);const summary = localized === localizedKey ? t("chat.responseFailed") : localized;const configurationError = [diff --git a/docs/adr/0271-provider-transport-rebuild.md b/docs/adr/0271-provider-transport-rebuild.mdindex c12c8c1d7..052f1aeb5 100644--- a/docs/adr/0271-provider-transport-rebuild.md+++ b/docs/adr/0271-provider-transport-rebuild.md@@ -86,3 +86,9 @@ string by pi-ai before classification, so the log could only sayfree-form provider text (URLs, header values, query strings) into logs and thetranscript for a small diagnostic gain over the errno, the category, and theroute.++## Amendment: certificate verification (issue #714)++Recognized certificate verification errors also skip rebuilding. Unlike the+broader TLS/protocol category, these cannot be repaired by replacing a socket+pool. See [system certificate trust](provider-system-certificates.md).diff --git a/docs/adr/README.md b/docs/adr/README.mdindex e995670e8..33bb16ed9 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -329,3 +329,4 @@ Each ADR includes:| 0298 | [The app ships no fonts](0298-remove-bundled-fonts.md) | Accepted (D598; amends ADR 0083 / D232) || turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted || provider-display-order | [Provider display order](provider-display-order.md) | Accepted |+| provider-system-certificates | [Desktop sidecar uses OS-trusted certificates](provider-system-certificates.md) | Accepted |diff --git a/docs/adr/provider-system-certificates.md b/docs/adr/provider-system-certificates.mdnew file mode 100644index 000000000..5fcbd5852--- /dev/null+++ b/docs/adr/provider-system-certificates.md@@ -0,0 +1,60 @@+# ADR: Desktop sidecar uses the operating system's trusted certificates++- Status: Accepted+- Date: 2026-09-20+- Related: Issue #714, ADR 0177, ADR 0271++## Context++HTTPS inspection can present a chain anchored in a locally installed trusted+root. Chromium and the agent sidecar use different TLS implementations; the+sidecar's bundled roots alone can reject a chain trusted by the operating+system. Rebuilding an undici pool does not change that trust decision.++The current Electron 43 runtime supports Node's `--use-system-ca`. A Windows+probe of Electron 43.6.0 / Node 24.20.0 confirmed that this flag includes the+system roots in the default CA set. The older Node 22.16.0 behavior reported in+#714 is not evidence that the current packaged runtime lacks this capability.++## Decision++The desktop launcher passes `--use-system-ca` before the sidecar entry point.+Node combines its bundled roots with system roots and inherited+`NODE_EXTRA_CA_CERTS`. Certificate chain, expiration and hostname validation+remain enabled. The app neither installs roots nor exports a certificate bundle.+The operating system's existing trust policy is the authority for local roots.++This applies to the desktop sidecar's default Node TLS clients, including the+direct, HTTP proxy and SOCKS provider transports. It is a process-level default,+not a per-provider exception. Headless pi-host launch policy is unchanged.+Restart the desktop after changing roots or its extra-CA startup environment.++Explicit certificate verification codes make `NETWORK_ERROR` non-retriable+and exclude it from transport rebuilding. The same classification is used+before setup replay and after the adapter flattens the error, for both the+session and built-in delegates. Other TLS/protocol failures retain their+existing recovery behavior. The transcript explains certificate validation+failure without asserting that security software must be its cause.++## Alternatives++- Exporting the Windows stores to PEM adds platform-specific subprocesses,+ filesystem lifecycle, and duplicate trust-policy maintenance. The current+ runtime's native support avoids those costs.+- A new custom-CA setting introduces persistence and restart semantics. The+ inherited `NODE_EXTRA_CA_CERTS` option already remains available.+- Disabling certificate or hostname verification is unacceptable.+- Suppressing every `tls` category is too broad: that category also includes+ protocol errors, not just certificate validation failures.++## Consequences and validation++Organizations that install trusted inspection roots now extend that trust to+the desktop sidecar. Untrusted chains and hostname mismatches remain rejected.+No IPC fields, database format, credentials, or proxy settings change.++`scripts/e2e-provider-certificates.mjs` exercises the real desktop launcher,+bundled sidecar, pi-ai and a loopback HTTPS provider. It checks inclusion of+system roots without modifying OS stores, then rejection of an untrusted root,+success with an inherited extra CA, and rejection of a mismatched hostname.+Native macOS/Linux and the reporter's security product require separate checks.diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex c39871745..b885e5257 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1368,3 +1368,18 @@ no Desktop provider fallback. Missing cwd, required project trust, unsupportedformat, repair-needing newline, unavailable provider/auth, active lease, orexternal byte change makes continuation fail closed while detail remainsbrowseable.++### Provider certificate trust (issue #714)++The desktop sidecar starts with Node's `--use-system-ca`, retaining bundled+roots and inherited `NODE_EXTRA_CA_CERTS`. It uses the OS trust store without+turning off chain or hostname validation. Restart after updating local trust+or the extra-CA startup environment. Headless pi-host launch behavior and+System/Direct/Custom proxy routing are unchanged.++Explicit certificate verification errors are terminal for both setup and+stream recovery in main sessions and built-in delegates. Their structured+cause survives adapter message flattening, remains on the final error row,+and never triggers a provider transport rebuild. Protocol errors such as+`EPROTO` keep their existing retry behavior. See+[certificate trust ADR](../../adr/provider-system-certificates.md).diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.mdindex d7b7ccca1..a668211c6 100644--- a/docs/spec/03-runtime/08-error-codes.md+++ b/docs/spec/03-runtime/08-error-codes.md@@ -436,3 +436,20 @@ Examples:expiry, scheduled-rejection, and restart-interruption paths map to stablecodes; only the documented pre-turn catalog fallback is allowed and no workis replayed++### Certificate verification failures (issue #714)++`NETWORK_ERROR` is non-retriable when `details.networkCode` is a recognized+certificate verification failure, including an untrusted/self-signed chain,+an expired/not-yet-valid certificate, or `ERR_TLS_CERT_ALTNAME_INVALID`.+A concrete certificate cause takes precedence over generic socket/proxy+wrapper codes. Captured fetch causes apply this policy after adapter error+flattening as well as during direct classification. Unknown and non-certificate+TLS/protocol errors retain existing recovery behavior.++The transcript keeps the stable error code, transport errno and raw details,+but uses localized certificate guidance instead of the generic connectivity+summary. It asks the user to check the certificate, clock, and trusted roots+used by security software/proxies, then restart after changing trust. It does+not claim that interception is the only possible cause or offer a TLS bypass.+Manual Continue remains available after the cause is corrected.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 29d07c29e..bb5ad75e3 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13854,3 +13854,31 @@ the latest destination. These assertions measure work counts, not device FPS.- **Automation:** `pnpm test:e2e:dialog-overflow`; source/contract dialog suitessupplement, but do not replace, real Chromium geometry and pointer checks.- **Status:** Implemented. Native Windows evidence; macOS/Linux not qualified.++### E2E-PROVIDER-certificate-trust-and-terminal-errors++- **Preconditions:** Built request candidate incorporating current `origin/main`,+ Electron installed, isolated test process/profile and loopback HTTPS fixture.+ No real provider, credentials, user profile, or OS certificate-store writes.+- **Steps:** Run `node scripts/e2e-provider-certificates.mjs`. Launch the actual+ desktop sidecar and submit a chat prompt against an untrusted localhost+ certificate. Relaunch with its CA in `NODE_EXTRA_CA_CERTS`, then request the+ same certificate through a hostname absent from its SAN.+- **Expected:** The child's default CA set includes system roots and extra CAs.+ The first request fails once with a non-retriable certificate error and no+ retry status; the trusted request returns text; the hostname mismatch still+ fails once. TLS and hostname verification remain enabled.+- **UI:** Run `node scripts/e2e-provider-certificate-ui.mjs` for the real error+ component in isolated Chromium. Certificate errors get localized guidance;+ DNS and protocol errors retain the generic summary. Errno/raw details remain+ visible, and details can be closed and reopened. Optional+ `PI_CERTIFICATE_EVIDENCE_DIR` records a screenshot; `--baseline` uses the+ upstream error component with the same fixture and stylesheet.+- **Lower-level coverage:** `provider-certificate-flow.test.ts` enters main+ session `prompt()` and delegate `run()` through real Agent/pi-ai wiring,+ with only the external fetch mocked. Both stop after one request and retain+ the certificate cause. Error classification and recovery suites cover direct,+ nested, flattened, non-certificate and wrapped certificate failures.+- **Limits:** OS-root inclusion is checked without installing a root. The TLS+ success fixture uses a child-only extra CA; it does not reproduce a specific+ antivirus installation or claim native macOS/Linux verification.diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex c5ff9a9c2..12b23502f 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -1031,3 +1031,18 @@ sidecar 序列化针对相同标准化路径的 IPC/`sequential` 调用跟踪差距(MVP 后积压):更丰富的系统提示组成 (§7) 和provider/model 目录发现超出当前有线路径。++### Provider certificate trust (issue #714)++The desktop sidecar starts with Node's `--use-system-ca`, retaining bundled+roots and inherited `NODE_EXTRA_CA_CERTS`. It uses the OS trust store without+turning off chain or hostname validation. Restart after updating local trust+or the extra-CA startup environment. Headless pi-host launch behavior and+System/Direct/Custom proxy routing are unchanged.++Explicit certificate verification errors are terminal for both setup and+stream recovery in main sessions and built-in delegates. Their structured+cause survives adapter message flattening, remains on the final error row,+and never triggers a provider transport rebuild. Protocol errors such as+`EPROTO` keep their existing retry behavior. See+[certificate trust ADR](../../../adr/provider-system-certificates.md).diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.mdindex 2925f0940..19020f18c 100644--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md@@ -412,3 +412,20 @@ errors.<code>.action到期、计划拒绝和重新启动中断路径映射到稳定代码;仅允许记录的预转目录后备,并且不进行任何工作正在重播++### Certificate verification failures (issue #714)++`NETWORK_ERROR` is non-retriable when `details.networkCode` is a recognized+certificate verification failure, including an untrusted/self-signed chain,+an expired/not-yet-valid certificate, or `ERR_TLS_CERT_ALTNAME_INVALID`.+A concrete certificate cause takes precedence over generic socket/proxy+wrapper codes. Captured fetch causes apply this policy after adapter error+flattening as well as during direct classification. Unknown and non-certificate+TLS/protocol errors retain existing recovery behavior.++The transcript keeps the stable error code, transport errno and raw details,+but uses localized certificate guidance instead of the generic connectivity+summary. It asks the user to check the certificate, clock, and trusted roots+used by security software/proxies, then restart after changing trust. It does+not claim that interception is the only possible cause or offer a TLS bypass.+Manual Continue remains available after the cause is corrected.diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex c600c7b1f..f2260c45e 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -8158,3 +8158,31 @@ the latest destination. These assertions measure work counts, not device FPS.- **阶段:** 发布后维护。- **自动化:** `pnpm test:e2e:dialog-overflow`;源代码检查不能替代实际布局验证。- **状态:** 已实现,原生 Windows 已验证,macOS/Linux 尚未实机验证。++### E2E-PROVIDER-certificate-trust-and-terminal-errors++- **Preconditions:** Built request candidate incorporating current `origin/main`,+ Electron installed, isolated test process/profile and loopback HTTPS fixture.+ No real provider, credentials, user profile, or OS certificate-store writes.+- **Steps:** Run `node scripts/e2e-provider-certificates.mjs`. Launch the actual+ desktop sidecar and submit a chat prompt against an untrusted localhost+ certificate. Relaunch with its CA in `NODE_EXTRA_CA_CERTS`, then request the+ same certificate through a hostname absent from its SAN.+- **Expected:** The child's default CA set includes system roots and extra CAs.+ The first request fails once with a non-retriable certificate error and no+ retry status; the trusted request returns text; the hostname mismatch still+ fails once. TLS and hostname verification remain enabled.+- **UI:** Run `node scripts/e2e-provider-certificate-ui.mjs` for the real error+ component in isolated Chromium. Certificate errors get localized guidance;+ DNS and protocol errors retain the generic summary. Errno/raw details remain+ visible, and details can be closed and reopened. Optional+ `PI_CERTIFICATE_EVIDENCE_DIR` records a screenshot; `--baseline` uses the+ upstream error component with the same fixture and stylesheet.+- **Lower-level coverage:** `provider-certificate-flow.test.ts` enters main+ session `prompt()` and delegate `run()` through real Agent/pi-ai wiring,+ with only the external fetch mocked. Both stop after one request and retain+ the certificate cause. Error classification and recovery suites cover direct,+ nested, flattened, non-certificate and wrapped certificate failures.+- **Limits:** OS-root inclusion is checked without installing a root. The TLS+ success fixture uses a child-only extra CA; it does not reproduce a specific+ antivirus installation or claim native macOS/Linux verification.diff --git a/packages/agent-runtime/src/agent-errors.test.ts b/packages/agent-runtime/src/agent-errors.test.tsindex 539d77115..9118f0e72 100644--- a/packages/agent-runtime/src/agent-errors.test.ts+++ b/packages/agent-runtime/src/agent-errors.test.ts@@ -5,6 +5,44 @@ import {} from "./agent-errors.js";describe("classifyAgentError", () => {+ it.each([+ "SELF_SIGNED_CERT_IN_CHAIN",+ "DEPTH_ZERO_SELF_SIGNED_CERT",+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",+ "CERT_HAS_EXPIRED",+ "CERT_NOT_YET_VALID",+ "ERR_TLS_CERT_ALTNAME_INVALID",+ ])("makes certificate verification failure %s terminal", (code) => {+ const cause = Object.assign(new Error("certificate verification failed"), { code });+ for (const error of [cause, new Error("Connection error.", { cause }), code]) {+ expect(classifyAgentError(error)).toMatchObject({+ code: "NETWORK_ERROR",+ retriable: false,+ details: { networkCategory: "tls", networkCode: code },+ });+ }+ });++ it.each(["EPROTO", "ERR_SSL_PROTOCOL_ERROR", "ECONNRESET"])(+ "keeps non-certificate transport failure %s retryable", (code) => {+ expect(classifyAgentError(new Error("fetch failed", {+ cause: Object.assign(new Error(code), { code }),+ })).retriable).toBe(true);+ },+ );++ it.each(["UND_ERR_SOCKET", "ERR_PROXY_CONNECTION_FAILED"])(+ "keeps the certificate cause terminal beneath %s", (code) => {+ const error = Object.assign(new Error("fetch failed"), {+ code, cause: Object.assign(new Error("certificate failed"), { code: "CERT_HAS_EXPIRED" }),+ });+ expect(classifyAgentError(error)).toMatchObject({+ retriable: false, details: { networkCode: "CERT_HAS_EXPIRED", networkCategory: "tls" },+ });+ },+ );+it("classifies auth failures from status fields", () => {const err = Object.assign(new Error("Incorrect API key provided"), {status: 401,diff --git a/packages/agent-runtime/src/agent-errors.ts b/packages/agent-runtime/src/agent-errors.tsindex 3ac3360a4..d833a5450 100644--- a/packages/agent-runtime/src/agent-errors.ts+++ b/packages/agent-runtime/src/agent-errors.ts@@ -8,6 +8,8 @@* "error") and the rejected-promise paths.*/+import { isCertificateVerificationError } from "@pi-desktop/shared";+export type ClassifiedAgentError = {code: string;message: string;@@ -170,6 +172,7 @@ const NETWORK_CATEGORY_PATTERNS: ReadonlyArray<function networkCategoryForCode(code: string,): NetworkFailureCategory | undefined {+ if (isCertificateVerificationError(code)) return "tls";for (const [pattern, category] of NETWORK_CATEGORY_PATTERNS) {if (pattern.test(code)) return category;}@@ -177,14 +180,15 @@ function networkCategoryForCode(}/**- * Pick the errno worth reporting and its category. A code naming the proxy wins- * wherever it sits in the chain, because that is the layer that actually failed- * — undici reports the proxy's own socket errno as a deeper cause.+ * A concrete certificate rejection wins over a generic socket/proxy wrapper:+ * retrying cannot repair trust. Otherwise prefer the proxy layer's own code.*/function pickNetworkCode(codes: readonly string[]): {code?: string;category?: NetworkFailureCategory;} {+ const certificate = codes.find(isCertificateVerificationError);+ if (certificate) return { code: certificate, category: "tls" };for (const candidate of codes) {if (networkCategoryForCode(candidate) === "proxy") {return { code: candidate, category: "proxy" };@@ -292,10 +296,12 @@ export function describeNetworkFailure(// errno (bounded, errno-shaped) before it can be reported; the object chain// above is probed first and its codes are kept.for (const match of message.matchAll(- /\b(?:E[A-Z]{3,}|UND_ERR_[A-Z_]+|ERR_[A-Z0-9_]+|HPE_[A-Z_]+)\b/g,+ /\b[A-Z][A-Z0-9_]{2,63}\b/g,)) {if (codes.length >= 16) break;- if (SAFE_NETWORK_CODE_PATTERN.test(match[0])) codes.push(match[0]);+ if (networkCategoryForCode(match[0]) !== undefined || NETWORK_PATTERN.test(match[0])) {+ codes.push(match[0]);+ }}if (hostname === undefined) {const dnsHost = message.match(@@ -393,11 +399,13 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {// "fetch failed" causes don't fall through to the generic bucket. The cause// chain is summarized as a coarse category plus the transport errno, so the// failing layer is identifiable without a user-visible code per layer.- if (hasNetworkCause(err, rawMessage)) {+ const network = describeNetworkFailure(err, rawMessage);+ const certificateFailure = isCertificateVerificationError(network.code);+ if (hasNetworkCause(err, rawMessage) || (status === undefined && certificateFailure)) {return result("NETWORK_ERROR",- true,- networkDetailFields(describeNetworkFailure(err, rawMessage)),+ !certificateFailure,+ networkDetailFields(network),);}diff --git a/packages/agent-runtime/src/provider-certificate-flow.test.ts b/packages/agent-runtime/src/provider-certificate-flow.test.tsnew file mode 100644index 000000000..b533cb1d1--- /dev/null+++ b/packages/agent-runtime/src/provider-certificate-flow.test.ts@@ -0,0 +1,52 @@+import { afterEach, expect, it, vi } from "vitest";+import type { AgentEventEnvelope } from "@pi-desktop/shared";+import { DesktopAgentRuntime } from "./runtime.js";+import type { RuntimeProviderConfig } from "./provider-binding.js";+import { SubagentRun } from "./subagent.js";++const provider: RuntimeProviderConfig = {+ id: "certificate-fixture", name: "Certificate fixture",+ baseUrl: "https://provider.invalid/v1", modelId: "fixture-model",+ apiKey: "fixture-key", authKind: "api_key", apiStyle: "chat_completions",+ supportsReasoning: false, supportedThinkingLevels: ["off"],+};++afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); });++it.each(["session", "delegate"])(+ "%s stops certificate failures before setup or stream replay and preserves the cause",+ async (kind) => {+ const events: AgentEventEnvelope[] = [];+ const fetch = vi.fn(async () => {+ throw new TypeError("fetch failed", {+ cause: Object.assign(new Error("self signed certificate in certificate chain"), {+ code: "SELF_SIGNED_CERT_IN_CHAIN",+ }),+ });+ });+ vi.stubGlobal("fetch", fetch);+ const onEvent = (event: AgentEventEnvelope) => events.push(event);+ const runtime = kind === "session" ? new DesktopAgentRuntime({+ sessionId: "certificate-session", mode: "agent", provider,+ thinkingLevel: "off", onEvent,+ host: { call: async () => { throw new Error("Unexpected host request"); } },+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ }) : undefined;+ try {+ const done = runtime ? runtime.prompt("Hello", "user-1", "turn-1") : new SubagentRun({+ sessionId: "certificate-session", turnId: "turn-1", parentToolCallId: "task-1",+ definition: { name: "explorer", description: "Fixture", prompt: "Reply", tools: [], source: "builtin" },+ task: "Hello", systemPrompt: "Reply", tools: [], provider, thinkingLevel: "off", onEvent,+ }).run();+ await done;+ expect(fetch).toHaveBeenCalledTimes(1);+ const errors = events.flatMap(({ event }) =>+ event.type === "message_end" && event.message.error ? [event.message.error] : [],+ );+ expect(errors).toContainEqual(expect.objectContaining({+ code: "NETWORK_ERROR", retriable: false,+ details: expect.objectContaining({ networkCode: "SELF_SIGNED_CERT_IN_CHAIN" }),+ }));+ } finally { await runtime?.dispose(); }+ },+);diff --git a/packages/agent-runtime/src/provider-transport-recovery.test.ts b/packages/agent-runtime/src/provider-transport-recovery.test.tsindex 39c1aa025..950168b31 100644--- a/packages/agent-runtime/src/provider-transport-recovery.test.ts+++ b/packages/agent-runtime/src/provider-transport-recovery.test.ts@@ -12,6 +12,29 @@ import {/** The reporter's endpoint (issue #234): a provider fetch that never answered. */const CODEX_URL = "https://chatgpt.com/backend-api/codex/responses";+it("neither rebuilds nor retries a captured certificate rejection after flattening", () => {+ const failure = describeProviderFetchFailure(+ fetchFailed(coded("SELF_SIGNED_CERT_IN_CHAIN")), CODEX_URL,+ );+ expect(failure).toBeDefined();+ if (!failure) throw new Error("missing failure");+ const health = createProviderTransportHealth();+ expect(health.observeFailure(buildFailure(failure.origin, "reset"))).toBe(false);+ for (let attempt = 0; attempt < 4; attempt++) {+ expect(health.observeFailure(failure)).toBe(false);+ }+ expect(withProviderFetchFailure({+ code: "NETWORK_ERROR", message: "Connection error.", retriable: true,+ }, failure)).toMatchObject({+ retriable: false,+ details: { networkCode: "SELF_SIGNED_CERT_IN_CHAIN" },+ });+ const protocol = describeProviderFetchFailure(fetchFailed(coded("EPROTO")), CODEX_URL);+ if (!protocol) throw new Error("missing protocol failure");+ expect(health.observeFailure(protocol)).toBe(false);+ expect(health.observeFailure(protocol)).toBe(true);+});+function fetchFailed(cause?: unknown): TypeError {return Object.assign(new TypeError("fetch failed"), {...(cause === undefined ? {} : { cause }),diff --git a/packages/agent-runtime/src/provider-transport-recovery.ts b/packages/agent-runtime/src/provider-transport-recovery.tsindex a3ff6637e..c584181a6 100644--- a/packages/agent-runtime/src/provider-transport-recovery.ts+++ b/packages/agent-runtime/src/provider-transport-recovery.ts@@ -34,6 +34,7 @@ import type {} from "./agent-errors.js";import { networkFailureDiagnostics } from "./agent-errors.js";import { activeNodeTransportRoute } from "./node-proxy.js";+import { isCertificateVerificationError } from "@pi-desktop/shared";/** Consecutive unanswered failures for one origin that justify a rebuild. */export const PROVIDER_TRANSPORT_REBUILD_THRESHOLD = 2;@@ -68,9 +69,9 @@ export function explainsProviderFetchFailure(code: string): boolean {}/**- * Categories a fresh pool cannot fix. DNS is the whole list: the lookup happens- * before a connection exists, so rebuilding the pool would close other- * sessions' idle sockets and still resolve the name the same way.+ * DNS happens before a connection exists. Certificate verification errors are+ * excluded separately by their exact code; the broader TLS category includes+ * protocol failures for which a fresh connection can still help.*/const UNREBUILDABLE_CATEGORIES: ReadonlySet<NetworkFailureCategory> = new Set(["dns",@@ -162,7 +163,10 @@ export function createProviderTransportHealth(): ProviderTransportHealth {return {observeFailure(failure) {- if (UNREBUILDABLE_CATEGORIES.has(failure.category)) {+ if (+ UNREBUILDABLE_CATEGORIES.has(failure.category) ||+ isCertificateVerificationError(failure.fields.networkCode)+ ) {clear();return false;}@@ -201,6 +205,7 @@ export function withProviderFetchFailure(}return {...error,+ retriable: error.retriable && !isCertificateVerificationError(failure.fields.networkCode),details: { ...(error.details ?? {}), ...failure.fields },};}diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 359324422..37e74730a 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -207,6 +207,7 @@ import { rebuildNodeNetworkTransport } from "./node-proxy.js";import {createProviderTransportHealth,explainsProviderFetchFailure,+ withProviderFetchFailure,type ProviderFetchFailure,type ProviderTransportHealth,} from "./provider-transport-recovery.js";@@ -5316,7 +5317,8 @@ Delegation rules:providerWaitMs?: number,streamMs?: number,): ReturnType<typeof classifyAgentError> {- const existingDetails = isRecord(error.details) ? error.details : {};+ const explained = withProviderFetchFailure(error, this.providerFetchFailure);+ const existingDetails = explained.details ?? {};// A capture exists only for an attempt that rejected before any response, so// it is also the honest phase: whatever the message lifecycle that surfaced// the failure looks like, this request never reached the provider, and@@ -5328,12 +5330,9 @@ Delegation rules:? this.providerFetchFailure: undefined;return {- ...error,+ ...explained,details: {...existingDetails,- // First-hand cause, so it replaces the `unknown` the text classifier- // falls back to for a bare `fetch failed`.- ...(captured ? captured.fields : {}),phase: captured ? "request" : phase,// Correlation for a failure that produced no response to inspect: how// much context and how many bytes the attempt carried, and whichdiff --git a/packages/agent-runtime/src/subagent-model-binding.ts b/packages/agent-runtime/src/subagent-model-binding.tsindex 65fbbfe6f..a48ff23d3 100644--- a/packages/agent-runtime/src/subagent-model-binding.ts+++ b/packages/agent-runtime/src/subagent-model-binding.ts@@ -15,10 +15,12 @@ import { captureProviderResponse, carriesRetryDelayHeaders, createProviderRetrySimport type { AgentOptions } from "@earendil-works/pi-agent-core";import type { SubagentThinkingLevel } from "@pi-desktop/shared";import type { ClassifiedAgentError } from "./agent-errors.js";+import type { ProviderFetchFailure } from "./provider-transport-recovery.js";export type SubagentProviderRetryState = {headers?: Record<string, string>;status?: number;+ failure?: ProviderFetchFailure;claim: (error: ClassifiedAgentError, phase: "request" | "stream") => number | undefined;};@@ -54,13 +56,15 @@ export function subagentModelBinding(opts: {streamFn: (m, context, options) => {retry.headers = undefined;retry.status = undefined;+ retry.failure = undefined;const requestOptions = withProviderHeaders(withOpenCodeSessionHeaders({...options,maxRetries: 0,sessionId: opts.sessionId,- fetch: captureProviderResponse(options?.fetch, (response) => {+ fetch: captureProviderResponse(options?.fetch, (response, _bytes, failure) => {+ retry.failure = failure;retry.status = response?.status;retry.headers = carriesRetryDelayHeaders(response?.status,@@ -91,6 +95,7 @@ export function subagentModelBinding(opts: {claim: (error, phase) => retry.claim(error, phase),headers: () => retry.headers,status: () => retry.status,+ failure: () => retry.failure,},);},diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.tsindex 58247e346..09db5f093 100644--- a/packages/agent-runtime/src/subagent.ts+++ b/packages/agent-runtime/src/subagent.ts@@ -33,6 +33,7 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";import {addUsage,cumulativeDelta,+ isCertificateVerificationError,subagentCanMutate,subagentToolsLabel,type AgentEventEnvelope,@@ -43,6 +44,7 @@ import {type UiMessage,} from "@pi-desktop/shared";import { classifyAgentError } from "./agent-errors.js";+import { withProviderFetchFailure } from "./provider-transport-recovery.js";import {assistantContent,nowIso,@@ -573,7 +575,10 @@ export class SubagentRun {typeof (message as { errorMessage?: unknown }).errorMessage === "string"? ((message as { errorMessage?: string }).errorMessage as string): "provider stream failed";- classifiedError = classifyProviderError(raw, this.retryState.status);+ classifiedError = withProviderFetchFailure(+ classifyProviderError(raw, this.retryState.status),+ this.retryState.failure,+ );retryAttempt = this.claimProviderRetry(classifiedError, "stream");if (retryAttempt !== undefined) {this.pendingProviderRetry = classifiedError;@@ -617,6 +622,8 @@ export class SubagentRun {status: failed ? "error" : stopReason === "aborted" ? "aborted" : "complete",...(messageUsage ? { usage: messageUsage } : {}),...(failed ? { isError: true } : {}),+ ...(isCertificateVerificationError(classifiedError?.details?.networkCode)+ ? { error: classifiedError } : {}),};this.currentAssistant = undefined;this.emit({ type: "message_end", message: row });diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 3d50ad723..485ebd199 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2110,6 +2110,7 @@ sklm: {"PROVIDER_RATE_LIMITED": "Der KI-Anbieter begrenzt Anfragen. Warten Sie einen Moment und versuchen Sie es erneut.","PROVIDER_ERROR": "Der KI-Anbieter hat einen Fehler zurückgegeben.","NETWORK_ERROR": "Der KI-Anbieter kann nicht erreicht werden. Überprüfen Sie Ihr Netzwerk oder Ihre Basis-URL.",+ providerCertificate: "Das Zertifikat des KI-Dienstes konnte nicht überprüft werden. Prüfen Sie das Zertifikat, die Systemzeit und die vertrauenswürdigen Stammzertifikate Ihrer Sicherheitssoftware oder Ihres Proxys. Starten Sie die App nach Änderungen an den Vertrauenseinstellungen neu.",NETWORK_POLICY_BLOCKED: "Die Adressprüfung der App hat diese Anfrage blockiert. Bei Proxy oder VPN: Einstellungen → Allgemein → Netzwerk prüfen.","TIMEOUT": "Bei der Anfrage an den KI-Anbieter ist eine Zeitüberschreitung aufgetreten.","STREAM_FAILED": "Die Antwort wurde unterbrochen.",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 0337c6bf2..f3590bb7a 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2149,6 +2149,7 @@ importConfirm: "Imported extensions run inside the agent process with the same aPROVIDER_RATE_LIMITED: "The AI provider is rate-limiting requests. Wait a moment and try again.",PROVIDER_ERROR: "The AI provider returned an error.",NETWORK_ERROR: "Can't reach the AI provider. Check your network or base URL.",+ providerCertificate: "The AI service certificate could not be verified. Check the certificate, system clock, and trusted roots used by your security software or proxy. Restart the app after updating trust settings.",NETWORK_POLICY_BLOCKED: "The app's address check blocked this request. Behind a proxy or VPN, check Settings → General → Network.",TIMEOUT: "The request to the AI provider timed out.",STREAM_FAILED: "The reply was interrupted.",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 6db3644b7..088ef61cb 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2110,6 +2110,7 @@ sklm: {"PROVIDER_RATE_LIMITED": "El proveedor de IA limita la velocidad de las solicitudes. Espere un momento y vuelva a intentarlo.","PROVIDER_ERROR": "El proveedor de IA devolvió un error.","NETWORK_ERROR": "No se puede comunicar con el proveedor de IA. Verifique su red o URL base.",+ providerCertificate: "No se pudo verificar el certificado del servicio de IA. Compruebe el certificado, la hora del sistema y los certificados raíz de confianza del software de seguridad o proxy. Reinicie la aplicación tras actualizar la configuración de confianza.",NETWORK_POLICY_BLOCKED: "La comprobación de direcciones de la aplicación bloqueó esta solicitud. Si usas proxy o VPN, revisa Configuración → General → Red.","TIMEOUT": "Se agotó el tiempo de espera de la solicitud al proveedor de IA.","STREAM_FAILED": "La respuesta fue interrumpida.",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex dd1863387..1150c579e 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2110,6 +2110,7 @@ sklm: {"PROVIDER_RATE_LIMITED": "Le fournisseur d'IA limite le débit des requêtes. Attendez un moment et réessayez.","PROVIDER_ERROR": "Le fournisseur d'IA a renvoyé une erreur.","NETWORK_ERROR": "Impossible de joindre le fournisseur d'IA. Vérifiez votre réseau ou votre URL de base.",+ providerCertificate: "Le certificat du service IA n’a pas pu être vérifié. Vérifiez le certificat, l’horloge système et les certificats racines approuvés utilisés par votre logiciel de sécurité ou proxy. Redémarrez l’application après avoir modifié les paramètres de confiance.",NETWORK_POLICY_BLOCKED: "Le contrôle d'adresse de l'application a bloqué cette requête. Si vous utilisez un proxy ou un VPN, vérifiez Paramètres → Général → Réseau.","TIMEOUT": "La demande adressée au fournisseur d'IA a expiré.","STREAM_FAILED": "La réponse a été interrompue.",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 4ae4abf01..25c6873db 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2147,6 +2147,7 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이PROVIDER_RATE_LIMITED: "AI 프로바이더가 요청을 제한하고 있습니다. 잠시 후 다시 시도하세요.",PROVIDER_ERROR: "AI 프로바이더에서 오류를 반환했습니다.",NETWORK_ERROR: "AI 프로바이더에 연결할 수 없습니다. 네트워크 또는 기본 URL을 확인하세요.",+ providerCertificate: "AI 서비스 인증서를 확인할 수 없습니다. 인증서, 시스템 시간, 보안 소프트웨어나 프록시가 사용하는 신뢰할 수 있는 루트 인증서를 확인하세요. 신뢰 설정을 변경한 후 앱을 다시 시작하세요.",NETWORK_POLICY_BLOCKED: "앱의 주소 검사가 이 요청을 차단했습니다. 프록시나 VPN을 사용한다면 설정 → 일반 → 네트워크를 확인하세요.",TIMEOUT: "AI 프로바이더 요청 시간이 초과되었습니다.",STREAM_FAILED: "답변이 중단되었습니다.",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex e673e52b2..eeb41d0e8 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2147,6 +2147,7 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçPROVIDER_RATE_LIMITED: "AI servisi istekleri hız sınırlıyor. Biraz bekleyip yeniden deneyin.",PROVIDER_ERROR: "AI servisi bir hata döndürdü.",NETWORK_ERROR: "AI servisine ulaşılamıyor. Ağınızı veya temel URL’yi kontrol edin.",+ providerCertificate: "AI hizmetinin sertifikası doğrulanamadı. Sertifikayı, sistem saatini ve güvenlik yazılımınızın veya proxy’nizin kullandığı güvenilir kök sertifikaları kontrol edin. Güven ayarlarını güncelledikten sonra uygulamayı yeniden başlatın.",NETWORK_POLICY_BLOCKED: "Uygulamanın adres denetimi bu isteği engelledi. Proxy veya VPN kullanıyorsanız Ayarlar → Genel → Ağ bölümüne bakın.",TIMEOUT: "AI servisine istek zaman aşımına uğradı.",STREAM_FAILED: "Yanıt kesildi.",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 7e18317e2..d1d1cfe8d 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2112,6 +2112,7 @@ sklm: {PROVIDER_RATE_LIMITED: "AI 服务触发了限流,请稍后再试。",PROVIDER_ERROR: "AI 服务返回了错误。",NETWORK_ERROR: "无法连接 AI 服务,请检查网络或接口地址。",+ providerCertificate: "无法验证 AI 服务的证书。请检查证书、系统时间,以及安全软件或代理使用的受信任根证书。更新信任设置后请重启应用。",NETWORK_POLICY_BLOCKED: "应用的地址校验阻止了该请求。若使用代理或 VPN,请检查 设置 → 常规 → 网络。",TIMEOUT: "请求 AI 服务超时。",STREAM_FAILED: "回复中断了。",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 3081e17c7..17e227859 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2110,6 +2110,7 @@ sklm: {PROVIDER_RATE_LIMITED: "AI 服務觸發了限流,請稍後再試。",PROVIDER_ERROR: "AI 服務返回了錯誤。",NETWORK_ERROR: "無法連線 AI 服務,請檢查網路或介面地址。",+ providerCertificate: "無法驗證 AI 服務的憑證。請檢查憑證、系統時間,以及安全軟體或代理使用的受信任根憑證。更新信任設定後請重新啟動應用程式。",NETWORK_POLICY_BLOCKED: "應用程式的地址校驗阻止了該請求。若使用代理或 VPN,請檢查 設定 → 常規 → 網路。",TIMEOUT: "請求 AI 服務超時。",STREAM_FAILED: "回覆中斷了。",diff --git a/packages/shared/src/certificate-errors.test.ts b/packages/shared/src/certificate-errors.test.tsnew file mode 100644index 000000000..7481d5c01--- /dev/null+++ b/packages/shared/src/certificate-errors.test.ts@@ -0,0 +1,17 @@+import { expect, it } from "vitest";+import { isCertificateVerificationError } from "./certificate-errors.js";++it("recognizes explicit certificate failures without treating all TLS errors as terminal", () => {+ for (const code of ["SELF_SIGNED_CERT_IN_CHAIN", "CERT_HAS_EXPIRED", "ERR_TLS_CERT_ALTNAME_INVALID"]) {+ expect(isCertificateVerificationError(code)).toBe(true);+ }+ for (const code of ["EPROTO", "ERR_SSL_PROTOCOL_ERROR", "UND_ERR_SOCKET", "ENOTFOUND"]) {+ expect(isCertificateVerificationError(code)).toBe(false);+ }+});++it("rejects malformed or free-text persisted diagnostics", () => {+ for (const value of [null, undefined, 1, {}, ["CERT_HAS_EXPIRED"], "certificate failed", "cert_has_expired"]) {+ expect(isCertificateVerificationError(value)).toBe(false);+ }+});diff --git a/packages/shared/src/certificate-errors.ts b/packages/shared/src/certificate-errors.tsnew file mode 100644index 000000000..fdf6d53f9--- /dev/null+++ b/packages/shared/src/certificate-errors.ts@@ -0,0 +1,23 @@+/** Certificate validation failures, not every TLS handshake/protocol failure. */+const CERTIFICATE_VERIFICATION_CODES: ReadonlySet<string> = new Set([+ "SELF_SIGNED_CERT_IN_CHAIN",+ "DEPTH_ZERO_SELF_SIGNED_CERT",+ "UNABLE_TO_GET_ISSUER_CERT",+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",+ "CERT_HAS_EXPIRED",+ "CERT_NOT_YET_VALID",+ "CERT_REVOKED",+ "CERT_UNTRUSTED",+ "CERT_REJECTED",+ "CERT_SIGNATURE_FAILURE",+ "INVALID_CA",+ "INVALID_PURPOSE",+ "PATH_LENGTH_EXCEEDED",+ "ERR_TLS_CERT_ALTNAME_INVALID",+]);++/** Shared by transport recovery and localized error presentation. */+export function isCertificateVerificationError(code: unknown): boolean {+ return typeof code === "string" && CERTIFICATE_VERIFICATION_CODES.has(code);+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 8ea44c4c4..c310ecbac 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -1,6 +1,7 @@export * from "./activation.js";export * from "./protocol.js";export * from "./errors.js";+export * from "./certificate-errors.js";export * from "./types.js";export * from "./transcript-truncation.js";export * from "./keyboard-shortcuts.js";diff --git a/scripts/README.md b/scripts/README.mdindex e54305203..1074b94a4 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -85,3 +85,13 @@ the publish job assembles the GitHub Release. Tag builds Developer ID-sign,notarize, and staple macOS artifacts; `workflow_dispatch` may set`sign_macos: false` only for unsigned debug artifacts. See the [releaserunbook](../docs/spec/06-delivery/06-release-runbook.md).++### Provider certificate regression++- `node scripts/e2e-provider-certificates.mjs`: real desktop launcher and+ bundled sidecar against a loopback TLS model; tests trust, terminal failure,+ inherited extra CA, and hostname validation. Requires installed Electron.+- `node scripts/e2e-provider-certificate-ui.mjs`: production transcript error+ component, localized guidance and detail disclosure. Requires built desktop+ styles. Optional `PI_CERTIFICATE_EVIDENCE_DIR` saves a review screenshot;+ `--baseline` renders the `origin/main` error component for comparison.diff --git a/scripts/e2e-provider-certificate-ui.mjs b/scripts/e2e-provider-certificate-ui.mjsnew file mode 100644index 000000000..68a7400cc--- /dev/null+++ b/scripts/e2e-provider-certificate-ui.mjs@@ -0,0 +1,65 @@+#!/usr/bin/env node+/** Production error component in isolated Chromium; optional review captures. */+import assert from "node:assert/strict";+import { execFileSync, spawn } from "node:child_process";+import { createRequire } from "node:module";+import { cp, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";+const root = join(dirname(fileURLToPath(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-certificate-ui-"));+const baseline = process.argv.includes("--baseline");+const evidence = process.env.PI_CERTIFICATE_EVIDENCE_DIR;+try {+ await build({+ entryPoints: [join(root, "scripts/e2e/provider-certificate-ui.tsx")], outfile: join(temp, "renderer.js"),+ bundle: true, platform: "browser", format: "iife", jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"' }, loader: { ".css": "empty" },+ alias: { "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),+ react: join(root, "apps/desktop/node_modules/react"), "react-dom": join(root, "apps/desktop/node_modules/react-dom") },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ plugins: baseline ? [{ name: "upstream-error-component", setup(build) {+ build.onLoad({ filter: /[/\\]transcript[/\\]shared\.tsx$/ }, () => ({+ contents: execFileSync("git", ["show", "origin/main:apps/desktop/src/features/chat/transcript/shared.tsx"], { cwd: root, encoding: "utf8" }), loader: "tsx",+ }));+ } }] : [],+ });+ const renderer = join(root, "apps/desktop/out/renderer");+ const html = await readFile(join(renderer, "index.html"), "utf8");+ const css = [...html.matchAll(/href="([^" ]+\.css)"/g)].map((m) => m[1]);+ assert.ok(css.length, "build desktop first");+ await cp(join(renderer, "assets"), join(temp, "assets"), { recursive: true });+ await writeFile(join(temp, "index.html"), `<!doctype html><html data-theme="light"><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:">${css.map(p => `<link rel="stylesheet" href="${p}">`).join("")}<body><script src="renderer.js"></script></body></html>`);+ let screenshot;+ if (evidence) { await mkdir(resolve(evidence), { recursive: true }); screenshot = join(resolve(evidence), baseline ? "before.png" : "after.png"); }+ await writeFile(join(temp, "main.cjs"), `+const { app, BrowserWindow } = require('electron');+const path = require('node:path'); const fs = require('node:fs/promises');+app.setPath('userData', path.join(__dirname, 'profile'));+app.whenReady().then(async () => {+ const window = new BrowserWindow({show:false,width:1100,height:520,webPreferences:{sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});+ try {+ await window.loadFile(path.join(__dirname, 'index.html'));+ const result = await window.webContents.executeJavaScript('globalThis.certificateUiProbe(${baseline})');+ await window.webContents.executeJavaScript('document.fonts.ready.then(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))');+ const screenshot = ${JSON.stringify(screenshot ?? null)};+ if (screenshot) await fs.writeFile(screenshot, (await window.webContents.capturePage()).toPNG());+ console.log('CERTIFICATE_UI ' + JSON.stringify(result)); app.quit();+ } catch(error) { console.error(error); app.exit(1); }+});`);+ const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });+ let output = "";+ for (const stream of [child.stdout, child.stderr]) stream.on("data", data => { output += data; });+ const timeout = setTimeout(() => child.kill(), 30_000);+ let code;+ try { code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); }); }+ finally { clearTimeout(timeout); }+ assert.equal(code, 0, output);+ assert.ok(output.includes('"ok":true'), output);+ console.log(output.trim());+} finally { await rm(temp, { recursive: true, force: true }); }diff --git a/scripts/e2e-provider-certificates.mjs b/scripts/e2e-provider-certificates.mjsnew file mode 100644index 000000000..dc9753203--- /dev/null+++ b/scripts/e2e-provider-certificates.mjs@@ -0,0 +1,72 @@+#!/usr/bin/env node+/** Real desktop launcher -> bundled sidecar -> pi-ai -> local HTTPS fixture. */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createServer } from "node:https";+import { createRequire } from "node:module";+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = join(dirname(fileURLToPath(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-certificates-"));+const fixture = join(root, "scripts/e2e/fixtures/certificates");+const cert = await readFile(join(fixture, "localhost-cert.pem"));+const key = await readFile(join(fixture, "localhost-key.pem"));+let handshakes = 0;+const server = createServer({ key, cert }, (_request, response) => {+ response.writeHead(200, { "content-type": "text/event-stream" });+ const chunk = { id: "tls-fixture", object: "chat.completion.chunk", created: 1, model: "fixture",+ choices: [{ index: 0, delta: { role: "assistant", content: "Hello from TLS" }, finish_reason: null }] };+ response.write(`data: ${JSON.stringify(chunk)}\n\n`);+ response.write(`data: ${JSON.stringify({ ...chunk, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\n`);+ response.end("data: [DONE]\n\n");+});+server.on("connection", () => { handshakes++; });+async function run(host, expected, extra) {+ const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1" };+ for (const name of ["NODE_EXTRA_CA_CERTS", "NODE_OPTIONS", "NODE_USE_ENV_PROXY", "NODE_TLS_REJECT_UNAUTHORIZED", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "PI_DESKTOP_PROXY_JSON"])+ delete env[name];+ if (extra) env.NODE_EXTRA_CA_CERTS = join(fixture, "localhost-cert.pem");+ const before = handshakes;+ const child = spawn(electronBinary, [join(temp, "parent.mjs"), temp,+ `https://${host}:${server.address().port}/v1`, expected], { env, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });+ let output = "";+ for (const stream of [child.stdout, child.stderr]) stream.on("data", (data) => { output += data; });+ const timeout = setTimeout(() => child.kill(), 30_000);+ let code;+ try { code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); }); }+ finally { clearTimeout(timeout); }+ assert.equal(code, 0, output);+ assert.equal(handshakes - before, 1, "a certificate failure must not retry TLS");+ console.log(output.trim());+}+try {+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ await mkdir(join(temp, "agent-runtime"));+ await writeFile(join(temp, "agent-runtime/package.json"), '{"type":"module"}');+ await build({ entryPoints: [join(root, "packages/agent-runtime/src/sidecar.ts")],+ outfile: join(temp, "agent-runtime/sidecar.js"), bundle: true, platform: "node", format: "esm",+ define: { PI_BUNDLED_NODE: "true" },+ banner: { js: `import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);+import __certificateProbeTls from 'node:tls';+{ const tls = __certificateProbeTls; const defaults = new Set(tls.getCACertificates('default'));+process.stdout.write(JSON.stringify({jsonrpc:'2.0',method:'test.trust',params:{systemCount:tls.getCACertificates('system').length,systemIncluded:tls.getCACertificates('system').every(c=>defaults.has(c)),extraIncluded:tls.getCACertificates('extra').every(c=>defaults.has(c))}})+'\\n'); }` },+ });+ await build({ entryPoints: [join(root, "scripts/e2e/provider-certificate-sidecar.ts")],+ outfile: join(temp, "parent.mjs"), bundle: true, platform: "node", format: "esm",+ alias: { "@pi-desktop/host-runtime": join(root, "packages/host-runtime/src/agent-sidecar.ts") },+ banner: { js: "import { createRequire } from 'node:module'; import { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; const require = createRequire(import.meta.url); const __dirname = dirname(fileURLToPath(import.meta.url));" },+ });+ await run("localhost", "DEPTH_ZERO_SELF_SIGNED_CERT", false);+ await run("localhost", "success", true);+ await run("127.0.0.1", "ERR_TLS_CERT_ALTNAME_INVALID", true);+} finally {+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ await rm(temp, { recursive: true, force: true });+}diff --git a/scripts/e2e/fixtures/certificates/README.md b/scripts/e2e/fixtures/certificates/README.mdnew file mode 100644index 000000000..b114347ab--- /dev/null+++ b/scripts/e2e/fixtures/certificates/README.md@@ -0,0 +1,17 @@+# Local TLS fixture++The certificate and unencrypted private key are public test data for localhost,+not production credentials. The key must never be used outside tests. The+self-signed certificate has a DNS SAN for `localhost` only; requests to+`127.0.0.1` must fail hostname validation even when its CA is trusted.++Generated with OpenSSL (valid for ten years from September 20, 2026):++```sh+openssl req -x509 -newkey rsa:2048 -nodes -keyout localhost-key.pem \+ -out localhost-cert.pem -sha256 -days 3650 -subj '/CN=localhost' \+ -addext 'subjectAltName=DNS:localhost'+```++The E2E test supplies the certificate only through a child process's+`NODE_EXTRA_CA_CERTS`. It never modifies the machine's certificate stores.diff --git a/scripts/e2e/fixtures/certificates/localhost-cert.pem b/scripts/e2e/fixtures/certificates/localhost-cert.pemnew file mode 100644index 000000000..29dee50ef--- /dev/null+++ b/scripts/e2e/fixtures/certificates/localhost-cert.pem@@ -0,0 +1,19 @@+-----BEGIN CERTIFICATE-----+MIIDHzCCAgegAwIBAgIUbGwFivLiISVzkW738SjNvQtjpqAwDQYJKoZIhvcNAQEL+BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDkyMDEzNTYyNFoXDTM2MDkx+NzEzNTYyNFowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF+AAOCAQ8AMIIBCgKCAQEAqWyecEL5KT8o2TwF3Y1V1EcUd6aNkcdEbj3lH6BW3Apr+QK8+WkBHz+/kdeDKLqoi2aXht/HfG/k6f2e+XBEXfYcproSA19NfETnADV7alH4R+NEjFQAuOkkxSQ/UuKzbNf6KXLxGxjg0xr4o9Z+FmpSMQEG//S++lXk/3PkVAOA2j+kmJrKts138mBNg0ouWS+FabM+5AX/ApbyWi590vz9SpCzGiWrLhSztU70506OpjH+iLZMSiULmoRF1Cm4voc6AVXyc3TuLv38gnqBAa85ww7KohRwfoZJG8Onkk1vlvk9+p/lehQJ9VeXH2ioPw9qaA11iQX1ezlnQDyY3iSPInQIDAQABo2kwZzAdBgNVHQ4E+FgQUPafcuk9/dsmcivIsmLgEQ3ookMIwHwYDVR0jBBgwFoAUPafcuk9/dsmcivIs+mLgEQ3ookMIwDwYDVR0TAQH/BAUwAwEB/zAUBgNVHREEDTALgglsb2NhbGhvc3Qw+DQYJKoZIhvcNAQELBQADggEBAJb292UmaWqnzW9EyoqfV44AQuKcykHp+H1PkJgu+w/kfqxB9KQgPSGDP5XFTiFSjyptdqY8EHwASdHH6auLhbWnCtv2V0v6ULUG9134y+teY5L/YGFDM3jdoz9t867ce0Q5yAxsS2SZsTZce514+Od1Gxe6hZCPdWS3eIHS26+ISuM6moW1gX1kTmydfbSPVvIroTRPACeQn6Tajl6vcYRV7H3xzAUsjG3kyGO7aXU+4Hg7fJAALS3I6vhID1tmOVOsOQix8pAwV4PHKAocktVUgceS9S7qq1SytP+NcsdC+l0CgfFtiIuMUXENYlOeeP3m6BOsyGicKfXdS68Ih4R1GaG4=+-----END CERTIFICATE-----diff --git a/scripts/e2e/fixtures/certificates/localhost-key.pem b/scripts/e2e/fixtures/certificates/localhost-key.pemnew file mode 100644index 000000000..ec2549392--- /dev/null+++ b/scripts/e2e/fixtures/certificates/localhost-key.pem@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCpbJ5wQvkpPyjZ+PAXdjVXURxR3po2Rx0RuPeUfoFbcCmtArz5aQEfP7+R14MouqiLZpeG38d8b+Tp/+Z75cERd9hymuhIDX018ROcANXtqUfhE0SMVAC46STFJD9S4rNs1/opcvEbGODTGv+ij1n4WalIxAQb/9L76VeT/c+RUA4DaOSYmsq2zXfyYE2DSi5ZL4Vpsz7kBf8ClvJ+aLn3S/P1KkLMaJasuFLO1TvTnTo6mMeItkxKJQuahEXUKbi+hzoBVfJzdO4u/fyC+eoEBrznDDsqiFHB+hkkbw6eSTW+W+T2n+V6FAn1V5cfaKg/D2poDXWJBfV7OWdAP+JjeJI8idAgMBAAECggEAOsu6mjvrywAjtWvKn032rMH0HOfcdmxAV7+8HYMf0aH++AYcvbNOk+EkIsE3P7GzXxk92a0cRhdwyjFdc7QdzbvkyomFSc1PjyI8RkrJJycGM+R+g/J9A67JN28yWJna6Zl0M+EzQhOapjhUdEsyG6ZPGrmAC+CMTET1wR8fbHaAvm+bCXcaj5XZl4rmpNKFBqNeguT3yN+46x6bzkimuBivnGDeK4fR/qLxjITWIzKJhZg+wMxTRqCSI1O5Y1/026cWl0aftYLQv0fTd1qSCjTzTf6IWuNOgI09sPuINEfuYBK8+SHUnrkRYwFtPcPOpdfN6iNZXjQLCejULB9JKHLfvowKBgQDlpUIaaSrLPsdor61h+3lDwIy2yz4N9DIrStb2luQV9+iaKc28i3C4UcEjhff3DZo38DXRkcsexYkg786wJ+1COkYGkYdcZ37GW3sBcP+NdLHO6lY6YrOoen/qedwcRJx1UFJ9sIeVoKuq0U+44F+P7RP03/4XINCTlZMw935jza7jwKBgQC83h/dUHOFKCnS9GQgH1UA9UUBRAxm/MPL+yHSEicqmSCMyyDjAMNkVSylbMEHYmVYdrRkUVLw8uX0BbZ62FZtcVOfXwU9S2nnv+1lgxQVCUQi+KKm1U+ZK3N8ic15MnCbcjUfhBcT+WQG4gni3itU4XTnRRZzMJ2txB+SPW5sjPTEwKBgFwtg2UahaTjZCNvMMcx94cMd9FoXj0ZhbeiX6dfpwa0HDhCsX9q+pcxqbbalXfDK/38G34taTzGyY5A89PdVAaF/WXAKBkoox4N92SP+HFz4Fgqo/xAn+BEC4hQtbtbBvpH7XSqISI8Revg7IEm+k7HmGSb2lVMKOszFJBZagl7WdAoGBALEs+UooDmYrVZX6+wlqb6drvOx933YaTIX2+eweGV3NrgpF14D7y1AI0swQXHf35wh4u+rrMy1i7E9q5rThKT7F1OTPtKHYak6vSBh9QU6GlcOUqMiGnJgcecbfYsCJ/7bjCV+CaUifrsNkAHLQVJGMI6Oi3F9tRROmoYn0lO0Bwe/AoGAaj9eDy4aIi7wagei8oA2+VutHKftF8xnIFHcU8jU4HdGY2QfHvd6v+y1RSxVSU9WnHx+DL/glZ5evwPKVmlSY+d4pYbIcbQa/2mqoV3mEIm0ATYsop95SRZO568N7mBFMCjF33X4gw1hqtpCfxRJp3+XniPSibd2xbL7pfYKE5VhEo=+-----END PRIVATE KEY-----diff --git a/scripts/e2e/provider-certificate-sidecar.ts b/scripts/e2e/provider-certificate-sidecar.tsnew file mode 100644index 000000000..a736dcdd3--- /dev/null+++ b/scripts/e2e/provider-certificate-sidecar.ts@@ -0,0 +1,53 @@+import assert from "node:assert/strict";+import { AgentSidecar } from "../../apps/desktop/electron/main/agent-sidecar";+import type { AgentEventEnvelope } from "@pi-desktop/shared";++Object.defineProperty(process, "resourcesPath", { value: process.argv[2] });+const sidecar = new AgentSidecar((text) => process.stderr.write(text));+sidecar.setHost({+ async call<T>() { return { session: { messages: [] } } as T; },+ onNotification: () => () => {}, onExit: () => () => {},+});+let trust: { systemCount: number; systemIncluded: boolean; extraIncluded: boolean } | undefined;+const events: AgentEventEnvelope[] = [];+const ended = Promise.withResolvers<void>();+sidecar.onNotification((method, params) => {+ if (method === "test.trust") trust = params as typeof trust;+ if (method !== "agent.event") return;+ const envelope = params as AgentEventEnvelope;+ events.push(envelope);+ if (envelope.event.type === "agent_end") ended.resolve();+});+const timeout = setTimeout(() => ended.reject(new Error(`certificate turn timed out: ${JSON.stringify(events)}`)), 15_000);+try {+ await sidecar.call("sidecar.health");+ await sidecar.call("agent.prompt", {+ sessionId: "certificate-e2e", turnId: "turn-e2e", userMessageId: "user-e2e",+ content: "Say hello", mode: "agent", thinkingLevel: "off",+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ provider: {+ id: "local-fixture", name: "Local TLS fixture", baseUrl: process.argv[3],+ modelId: "fixture", apiKey: "fixture-key", authKind: "api_key", apiStyle: "chat_completions",+ supportsReasoning: false, supportedThinkingLevels: ["off"],+ },+ });+ await ended.promise;+ assert.ok(trust?.systemIncluded, "sidecar must include OS-trusted roots");+ assert.ok(trust?.extraIncluded, "inherited extra CA must remain trusted");+ const messages = events.flatMap(({ event }) => event.type === "message_end" ? [event.message] : []);+ const expected = process.argv[4];+ if (expected === "success") {+ assert.ok(messages.some((m) => m.content === "Hello from TLS" && !m.error));+ } else {+ const error = messages.find((m) => m.error)?.error;+ assert.ok(error, "certificate failure must produce an error row");+ assert.equal(error?.code, "NETWORK_ERROR");+ assert.equal(error?.retriable, false);+ assert.equal((error.details as { networkCode: string }).networkCode, expected);+ assert.equal(events.some(({ event }) => event.type === "status" && event.status.activity?.phase === "retrying"), false);+ }+ console.log(JSON.stringify({ ok: true, expected, trust }));+} finally {+ clearTimeout(timeout);+ await sidecar.dispose();+}diff --git a/scripts/e2e/provider-certificate-ui.tsx b/scripts/e2e/provider-certificate-ui.tsxnew file mode 100644index 000000000..4d3f1cf40--- /dev/null+++ b/scripts/e2e/provider-certificate-ui.tsx@@ -0,0 +1,42 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import type { UiMessage } from "@pi-desktop/shared";+import { AssistantErrorMessage } from "../../apps/desktop/src/features/chat/transcript/shared";++declare global { var certificateUiProbe: (baseline: boolean) => Promise<unknown>; }+const assert = (value: unknown, message: string) => { if (!value) throw new Error(message); };+globalThis.certificateUiProbe = async (baseline) => {+ const i18n = createInstance();+ await i18n.init({ lng: "zh-CN", resources: { "zh-CN": { translation: catalogs["zh-CN"] } }, interpolation: { escapeValue: false } });+ const container = document.createElement("main");+ container.style.cssText = "max-width:900px;margin:60px auto;padding:24px";+ document.body.append(container);+ const root = createRoot(container);+ const render = (code: string) => {+ const message: UiMessage = {+ id: "certificate-error", role: "assistant", content: "", createdAt: "2026-09-20T00:00:00Z",+ providerId: "fixture-provider", modelId: "fixture-model", status: "error", isError: true,+ error: { code: "NETWORK_ERROR", message: "Connection error.", retriable: false,+ details: { networkCode: code } },+ };+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><AssistantErrorMessage message={message} /></I18nextProvider>));+ };+ for (const code of ["SELF_SIGNED_CERT_IN_CHAIN", "CERT_HAS_EXPIRED", "ERR_TLS_CERT_ALTNAME_INVALID", "EPROTO", "ENOTFOUND"]) {+ render(code);+ const certificate = !baseline && !["EPROTO", "ENOTFOUND"].includes(code);+ assert(container.querySelector("strong")?.textContent === i18n.t(certificate ? "errors.providerCertificate" : "errors.NETWORK_ERROR"), `${code}: wrong summary`);+ assert(container.querySelector("code")?.textContent?.includes(code), "errno disappeared");+ }+ render("SELF_SIGNED_CERT_IN_CHAIN");+ const disclosure = container.querySelector<HTMLButtonElement>("button[aria-expanded]");+ assert(disclosure, "missing details control");+ flushSync(() => disclosure?.click());+ assert(disclosure?.getAttribute("aria-expanded") === "false", "details did not close");+ flushSync(() => disclosure?.click());+ assert(disclosure?.getAttribute("aria-expanded") === "true", "details did not reopen");+ assert(container.textContent?.includes("Connection error."), "raw details lost");+ return { ok: true, baseline, cases: 5, detailsToggle: true };+};