A local-first multi-agent app development platform, built on PenguinHarness
feat(web): measure the server's reach to the model providers from Proxy options (#686)
Yaowei Zhengb16ce66a9540
diff --git a/changelog/unreleased/2026-09-11-proxy-reachability-probe.md b/changelog/unreleased/2026-09-11-proxy-reachability-probe.mdnew file mode 100644index 00000000..c124dd62--- /dev/null+++ b/changelog/unreleased/2026-09-11-proxy-reachability-probe.md@@ -0,0 +1,41 @@+# Proxy options can measure the server's reach to the model providers++- **Date:** 2026-09-11+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#686](https://github.com/Prism-Shadow/penguin-harness/pull/686)++[中文版](2026-09-11-proxy-reachability-probe.zh.md)++The Proxy options settings page gained a reachability test, below the save row: it lists six+provider targets — OpenAI, Anthropic, Gemini, DeepSeek, and GLM's two hosts, Z.AI and BigModel —+with the exact URL each one probes, and one button measures them all, reporting a latency for every+host that answered. Each row fills the moment its own answer arrives rather than waiting for the+slowest. The probes run on the server, behind the new admin-only+`GET /api/admin/settings/proxy-probe` and `POST /api/admin/settings/proxy-probe/:provider` — the+path under test is the server's own outbound one, which is what the proxy settings configure and+what the browser has no view of.++## Details++- No credential is sent. Each probe is an unauthenticated `GET` of the provider's model-listing+ endpoint, and unlike protocol detection it does not fall back to `OPENAI_API_KEY` or its+ siblings in the process environment. `GET` on the base route serves the target list without+ probing anything, so the URLs the page shows are the URLs the server fetches.+- GLM is two targets, not one: `api.z.ai` is the global endpoint the catalog defaults to and+ `open.bigmodel.cn` the mainland one a bigmodel.cn key needs. They resolve and route+ differently, so a proxy can carry one and not the other.+- Any HTTP answer counts as reachable, 401 and 403 included: a rejected credential still proves+ the name resolved, TCP connected, TLS completed and the host replied. Unreachable means the+ transport failed, reported as one of `timeout`, `dns`, `refused`, `tls` or `network`.+- A reachable target shows its round trip in milliseconds and nothing more; the worded state is+ kept for targets that have no number — unreachable ones and the not-yet-measured state — and+ travels with the figure for assistive technology.+- The targets are hard-coded and the probe route accepts no request body — only a provider id,+ matched against that same list, with anything else a 404 that reaches no network. No caller+ chooses an address for the server to fetch. Each target is given 5 seconds, and the page asks+ for all of them at once, so one dead host holds up only its own row.+- The measurement describes the saved settings, since only a save rebuilds the outbound+ dispatcher. That is why the test sits below Save, and why the reason sits behind the page's+ existing "?". Saving clears results that describe a superseded configuration.+- `packages/docs/content/server-api.{zh,en}.md` gained both routes.diff --git a/changelog/unreleased/2026-09-11-proxy-reachability-probe.zh.md b/changelog/unreleased/2026-09-11-proxy-reachability-probe.zh.mdnew file mode 100644index 00000000..80723096--- /dev/null+++ b/changelog/unreleased/2026-09-11-proxy-reachability-probe.zh.md@@ -0,0 +1,32 @@+# 代理选项可以测量服务器到各模型服务商的连通情况++- **Date:** 2026-09-11+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#686](https://github.com/Prism-Shadow/penguin-harness/pull/686)++[English](2026-09-11-proxy-reachability-probe.md)++代理选项设置页在保存行下方新增连通性测速:它先列出 OpenAI、Anthropic、Gemini、DeepSeek 以及 GLM 的+两个主机 Z.AI 与 BigModel 共六个目标及各自将被请求的具体地址,一个按钮把它们一并测一遍,对回应的主机+报出延迟;每一行各自到达即显示,不必等最慢的那个。探测在服务器上执行,接口是新增的+`GET /api/admin/settings/proxy-probe` 与 `POST /api/admin/settings/proxy-probe/:provider`+(仅管理员)——被测的正是服务器自身的出站链路,它由代理设置决定,浏览器看不到。++## 细节++- 不发送任何凭据。每次探测都是对服务商模型列表接口的一次匿名 `GET`;与协议探测不同,它不会退回到进程+ 环境里的 `OPENAI_API_KEY` 之类。基础路由的 `GET` 只返回目标列表、不发起探测,页面上展示的地址因此+ 就是服务端真正请求的地址。+- GLM 算两个目标而非一个:`api.z.ai` 是模型目录默认使用的国际版端点,`open.bigmodel.cn` 则是+ bigmodel.cn 的 key 所需的国内端点。两者解析与路由都不同,代理可能只通其中之一。+- 只要回了 HTTP 响应就算连通,401、403 同样算:凭据被拒也说明域名已解析、TCP 已连接、TLS 已握手、+ 对方已应答。连不通指传输本身失败,归为 `timeout`、`dns`、`refused`、`tls`、`network` 之一。+- 连通的目标只显示往返毫秒数;文字状态留给没有数字的目标——连不通的和尚未测的——并随数字一同提供给+ 辅助技术。+- 目标地址写死在服务端,探测路由不接受任何请求体——只接受一个 provider id,并在同一份列表里比对,+ 其余一律 404 且不会发起任何网络请求,因此调用方无法指定服务器去抓取的地址。每个目标限时 5 秒,+ 页面一次性把它们全部发出,某个不通的主机只会拖住它自己那一行。+- 测量描述的是已保存的设置,因为只有保存才会重建出站 dispatcher;测速因此排在「保存」下方,理由则+ 放在该页原有的问号里。保存后会清掉描述旧配置的结果。+- `packages/docs/content/server-api.{zh,en}.md` 补上了这两条路由。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex ca3b866d..4510f9cd 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -92,6 +92,8 @@ In desktop mode (the server spawned by the desktop app) the whole surface answer| --- | --- | --- || GET | /api/admin/settings | Server-global settings: `{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb}}` || PUT | /api/admin/settings | Update settings (fields optional; omitted fields keep their current value), returns the full updated settings |+| GET | /api/admin/settings/proxy-probe | The reachability probe's targets: `{targets: [{provider, url}]}` (no request is made) |+| POST | /api/admin/settings/proxy-probe/:provider | Probe one of those targets over the server's outbound path, no credential sent: `{probe: {provider, url, outcome, ms, status?}}`; `outcome` is `reachable` for any HTTP answer, else `timeout` / `dns` / `refused` / `tls` / `network`; 404 `probe_target_not_found` for an id outside the list |The proxy settings are two independent switches sharing one optional explicit address; changes take effect for newly initiated connections/spawns immediately — no restart:diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 27d78bb7..184d677c 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -92,6 +92,8 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \| --- | --- | --- || GET | /api/admin/settings | 服务端全局设置:`{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb}}` || PUT | /api/admin/settings | 更新设置(字段可省略,省略即保持现值),返回更新后的完整设置 |+| GET | /api/admin/settings/proxy-probe | 连通性测速的目标列表:`{targets: [{provider, url}]}`(不发起任何请求) |+| POST | /api/admin/settings/proxy-probe/:provider | 沿服务端出站链路探测其中一个目标,不携带任何凭据:`{probe: {provider, url, outcome, ms, status?}}`;`outcome` 在收到任意 HTTP 响应时为 `reachable`,否则为 `timeout` / `dns` / `refused` / `tls` / `network`;列表之外的 id 返回 404 `probe_target_not_found` |代理设置为两个独立开关共享一个可选的显式地址;修改即时生效(对新发起的连接与新派生的子进程),无需重启:diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 57b8e843..b7c30a9d 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -249,6 +249,60 @@ export interface ServerSettingsUpdateRequest {attachmentTotalMb?: number;}+/**+ * The endpoints the proxy reachability probe covers. A fixed list: the route takes a provider+ * id from this set and never a URL, so nothing a caller sends decides what the server fetches.+ *+ * GLM is two entries rather than one because it is two hosts: Z.AI serves the global endpoint+ * and BigModel the mainland one, they are reached over different routes, and a proxy can carry+ * one and not the other.+ */+export type ProxyProbeProvider =+ "openai" | "anthropic" | "gemini" | "deepseek" | "zai" | "bigmodel";++/**+ * One probe's verdict. `reachable` means an HTTP answer arrived, whatever its status — a+ * rejected credential still proves the whole path works. The rest are transport failures,+ * named so a proxy that swallows connections can be told apart from one whose address does+ * not resolve: `timeout` (no answer within the probe's window), `dns` (the name never+ * became an address), `refused` (the connection was refused at the TCP level), `tls` (the+ * handshake or the certificate failed) and `network` (anything else).+ */+export type ProxyProbeOutcome = "reachable" | "timeout" | "dns" | "refused" | "tls" | "network";++/**+ * One probe target. Served before any probe runs so the page can list what it is about to+ * request — the URLs are the concrete answer to "what does no API key mean here".+ */+export interface ProxyProbeTargetDto {+ provider: ProxyProbeProvider;+ /** The exact URL a probe requests, unauthenticated. */+ url: string;+}++/** What the probe endpoint would request, without requesting it. */+export interface ProxyProbeTargetsResponse {+ targets: ProxyProbeTargetDto[];+}++/** One provider's probe result. */+export interface ProxyProbeDto extends ProxyProbeTargetDto {+ outcome: ProxyProbeOutcome;+ /** Wall time in milliseconds until the answer's headers arrived, or until the attempt failed. */+ ms: number;+ /** The HTTP status, present only when `outcome` is `reachable`. */+ status?: number;+}++/**+ * One probe's answer. The route measures a single target per call: the page asks for all of+ * them at once and fills each row the moment its own answer lands, so one black-holed host+ * cannot hold every other result behind its timeout.+ */+export interface ProxyProbeResponse {+ probe: ProxyProbeDto;+}+/*** One draft-screen shortcut: a prompt the user wrote, filed under a name they chose. Clicking it* fills the composer exactly like a built-in example does, and sends nothing. Deliberately holdsdiff --git a/packages/server/src/http/routes/admin-settings.ts b/packages/server/src/http/routes/admin-settings.tsindex a6f94e2c..8bfc512d 100644--- a/packages/server/src/http/routes/admin-settings.ts+++ b/packages/server/src/http/routes/admin-settings.ts@@ -10,15 +10,28 @@* switch needs no push — the command-subprocess policy getter re-reads the repo at* every spawn). The upload limits need no push either, for the same reason: the* attachment validators and the request body cap both read the repo per request.+ *+ * GET /api/admin/settings/proxy-probe names the model provider hosts the reachability probe+ * would request; POST .../proxy-probe/:provider measures one of them — unauthenticated, see+ * services/proxy-probe.ts.*/import { Hono } from "hono";-import type { ServerSettingsResponse } from "../../api/types.js";+import type {+ ProxyProbeResponse,+ ProxyProbeTargetsResponse,+ ServerSettingsResponse,+} from "../../api/types.js";import { HttpError } from "../errors.js";import type { AppEnv } from "../../auth/middleware.js";import { optionalBoolean, readJson } from "../validate.js";import type { AppDeps } from "../../app.js";import { applyProxySettings, normalizeProxyUrl } from "../../net/proxy.js";import { MAX_ATTACHMENT_MB, MIN_ATTACHMENT_MB } from "../../services/attachment-limits.js";+import {+ PROXY_PROBE_TARGETS,+ probeProxyReachabilityOf,+ proxyProbeTarget,+} from "../../services/proxy-probe.js";/*** proxyUrl update value -> stored value: null and empty/whitespace-only clear the@@ -126,5 +139,36 @@ export function adminSettingsRoutes(deps: AppDeps): Hono<AppEnv> {return c.json(settings());});+ // What the probe would request, without requesting it: the page lists the targets — name+ // and exact URL — before anyone presses the button, so the list is served rather than+ // copied into the frontend, where a second copy could drift from what is really fetched.+ app.get("/proxy-probe", (c) =>+ c.json({ targets: [...PROXY_PROBE_TARGETS] } satisfies ProxyProbeTargetsResponse),+ );++ // Reachability and latency of the server's outbound path to ONE provider host, named by a+ // path segment matched against the fixed target list. Admin-only through the router's guard+ // above, like every other route here.+ //+ // Takes no request body and no URL: the only thing a caller supplies is a provider id, and+ // an id that is not in the list is a 404 rather than a fetch. Nothing is written, but it+ // does reach the network, so it is a POST rather than a GET.+ //+ // One target per call because the page renders each answer as it arrives; the concurrency+ // is the browser's, and a host that black-holes connections holds up only its own row.+ // The path measured is whatever the process dispatcher currently is, which follows the+ // STORED settings — a PUT is what moves it, which is why the page puts this below Save.+ app.post("/proxy-probe/:provider", async (c) => {+ const target = proxyProbeTarget(c.req.param("provider"));+ if (target === null) {+ throw new HttpError(404, "probe_target_not_found", "No probe target with that provider id.");+ }+ // Plain global fetch on purpose — that is the undici fetch the startup entry installed,+ // and it resolves the proxy dispatcher per call. No credential is attached anywhere+ // below, including from the process environment (see services/proxy-probe.ts).+ const probe = await probeProxyReachabilityOf(target);+ return c.json({ probe } satisfies ProxyProbeResponse);+ });+return app;}diff --git a/packages/server/src/services/proxy-probe.ts b/packages/server/src/services/proxy-probe.tsnew file mode 100644index 00000000..a098981a--- /dev/null+++ b/packages/server/src/services/proxy-probe.ts@@ -0,0 +1,198 @@+/**+ * Reachability and latency probe for the well-known model provider hosts, behind the proxy+ * settings page's test button.+ *+ * The question is "can THIS SERVER reach the provider, and how long does one round trip+ * take" — the outbound path the admin proxy settings configure. That path is the server's+ * own: the browser reaches the internet by a different route entirely and could not be+ * asked (a cross-origin request to a provider host is refused before it is sent), so the+ * probe belongs here. It travels the configured path for free: the startup entry replaces+ * globalThis.fetch with undici's, which resolves the process-global dispatcher per call,+ * and that dispatcher is what the proxy settings drive (see net/proxy.ts).+ *+ * Reachable is judged by the fact that an answer arrived AT ALL, and any HTTP status counts+ * — 401 and 403 included. A refused credential still proves the name resolved, TCP+ * connected, TLS completed and the host replied, which is the entire question here;+ * unlike protocol detection next door, nothing about the response body is being read.+ * Unreachable means the transport failed, and the failure keeps a short kind (timeout,+ * dns, refused, tls, network) so an admin can tell a black-holed proxy from a name with no+ * route behind it.+ *+ * No credential is ever sent. Not the caller's, and — unlike protocol detection, which+ * falls back to OPENAI_API_KEY and friends because an authenticated probe identifies a+ * protocol far more reliably — not the process environment's either: nothing about+ * reachability improves with a key, and a probe the admin did not authenticate must not+ * quietly spend one.+ *+ * The target list is hard-coded and the endpoint takes no URL from anyone — only a provider+ * id, matched against that list. An admin-triggered fetch of a caller-supplied address would+ * be an SSRF surface, and this feature has no use for one.+ *+ * One target per call. The page asks for all of them at once and renders each answer as it+ * arrives; probing them together behind a single response would hold every row blank until+ * the slowest one landed, which for a black-holed host is the whole timeout.+ */+import type { ProxyProbeDto, ProxyProbeOutcome, ProxyProbeTargetDto } from "../api/types.js";++/**+ * The targets, with the cheapest request that still proves the path: each host's+ * model-listing endpoint, which answers an unauthenticated GET with a small+ * credential-rejection body (OpenAI 401, Anthropic 401, Gemini 403, DeepSeek 401, and both+ * GLM hosts 401 as of this writing — the exact status is immaterial, an answer is an+ * answer). GET rather than HEAD because two of them do not answer HEAD honestly:+ * api.anthropic.com replies 405 and generativelanguage.googleapis.com 404, which would still+ * prove reachability but would measure a path the real traffic never takes.+ *+ * GLM is listed twice because it is two hosts: api.z.ai is the global endpoint the catalog+ * defaults to, open.bigmodel.cn the mainland one a bigmodel.cn key needs. They resolve and+ * route differently, so one can be reachable while the other is not, and an admin choosing+ * between the two keys is exactly the reader this page has.+ */+export const PROXY_PROBE_TARGETS: readonly ProxyProbeTargetDto[] = [+ { provider: "openai", url: "https://api.openai.com/v1/models" },+ { provider: "anthropic", url: "https://api.anthropic.com/v1/models" },+ { provider: "gemini", url: "https://generativelanguage.googleapis.com/v1beta/models" },+ { provider: "deepseek", url: "https://api.deepseek.com/models" },+ { provider: "zai", url: "https://api.z.ai/api/paas/v4/models" },+ { provider: "bigmodel", url: "https://open.bigmodel.cn/api/paas/v4/models" },+];++/**+ * Per-target timeout, matching the protocol probes next door. A live host answers these in+ * tens of milliseconds even through a proxy, so five seconds is far past "slow" and well+ * short of the wait a black-holed connection would otherwise impose — and since a call+ * measures one target, it is the wait a single row can impose, not the whole run's.+ */+export const PROXY_PROBE_TIMEOUT_MS = 5_000;++/** DNS never produced an address (a proxy host that does not resolve lands here too). */+const DNS_CODES = new Set(["ENOTFOUND", "EAI_AGAIN"]);++/** Something on the path refused the connection at the TCP level — classically a dead proxy port. */+const REFUSED_CODES = new Set(["ECONNREFUSED"]);++/**+ * TLS handshake or certificate failures, which an intercepting proxy with an untrusted CA+ * produces. Node spells these either as an `ERR_TLS_*` / `ERR_SSL_*` code or as one of+ * OpenSSL's verification names; a code outside both forms is reported as a plain network+ * failure rather than guessed at.+ */+const TLS_CODES = new Set([+ "CERT_HAS_EXPIRED",+ "CERT_NOT_YET_VALID",+ "DEPTH_ZERO_SELF_SIGNED_CERT",+ "SELF_SIGNED_CERT_IN_CHAIN",+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",+]);++/**+ * The `code` of every error in a `cause` chain, outermost first. undici wraps the real+ * fault — `TypeError: fetch failed` on the outside, the socket or resolver error+ * underneath — so the diagnosis is never on the error that was thrown. The depth cap+ * guards against a chain that loops back on itself.+ */+function errorCodeChain(err: unknown): string[] {+ const codes: string[] = [];+ let current: unknown = err;+ for (let depth = 0; current instanceof Error && depth < 8; depth += 1) {+ const { code } = current as { code?: unknown };+ if (typeof code === "string") codes.push(code);+ current = current.cause;+ }+ return codes;+}++/** One probe attempt: the status an answer came back with, or the error thrown when none did. */+export type ProxyProbeAttempt = { status: number } | { error: unknown };++/**+ * Classifies one attempt (pure; the rule this feature has, and what the unit tests pin).+ *+ * An HTTP status — any HTTP status — is reachable. Everything else is a transport failure+ * named by the deepest thing that identifies it.+ */+export function classifyProxyProbe(attempt: ProxyProbeAttempt): ProxyProbeOutcome {+ if ("status" in attempt) return "reachable";+ const { error } = attempt;+ // The timeout is our own abort, and it surfaces as a TimeoutError on the OUTERMOST error.+ // Deliberately not looked for down the chain: undici reports a proxy that refuses the+ // CONNECT tunnel as an AbortError nested under "fetch failed", and that is a refusal to+ // carry the request, not a host that took too long.+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {+ return "timeout";+ }+ for (const code of errorCodeChain(error)) {+ if (DNS_CODES.has(code)) return "dns";+ if (REFUSED_CODES.has(code)) return "refused";+ if (TLS_CODES.has(code) || code.startsWith("ERR_TLS_") || code.startsWith("ERR_SSL_")) {+ return "tls";+ }+ }+ return "network";+}++async function probeTarget(+ target: ProxyProbeTargetDto,+ fetchImpl: typeof fetch,+ timeoutMs: number,+): Promise<ProxyProbeDto> {+ const startedAt = performance.now();+ const elapsedMs = () => Math.round(performance.now() - startedAt);+ try {+ const res = await fetchImpl(target.url, {+ method: "GET",+ // No Authorization, no x-api-key, no environment fallback: this probe is+ // unauthenticated by design and must stay that way even though the process has+ // OPENAI_API_KEY and its siblings to hand (see the module header).+ headers: { accept: "application/json" },+ signal: AbortSignal.timeout(timeoutMs),+ });+ // fetch settles when the response HEAD arrives, so this is the wall time of everything+ // the user waits for on a real request — DNS, connect, TLS, request, first answer —+ // and nothing more. The body is never read: no part of it is classified.+ const ms = elapsedMs();+ // Releases the connection instead of leaving it draining in the background.+ await res.body?.cancel().catch(() => {});+ return {+ provider: target.provider,+ url: target.url,+ // Through the same rule the failure branch uses, so "any HTTP answer is reachable"+ // is stated once and the exported classifier is the one production runs.+ outcome: classifyProxyProbe({ status: res.status }),+ ms,+ status: res.status,+ };+ } catch (err) {+ return {+ provider: target.provider,+ url: target.url,+ outcome: classifyProxyProbe({ error: err }),+ ms: elapsedMs(),+ };+ }+}++/** The target a provider id names, or null when the id is not one of the fixed set. */+export function proxyProbeTarget(provider: string): ProxyProbeTargetDto | null {+ return PROXY_PROBE_TARGETS.find((t) => t.provider === provider) ?? null;+}++/**+ * Probes one target. Never throws: every failure mode is an outcome, including the timeout,+ * so a caller waiting on several of these always gets an answer from each.+ */+export async function probeProxyReachabilityOf(+ target: ProxyProbeTargetDto,+ options: {+ /** Injection point for tests; defaults to global fetch, which is the proxied path (see the module header). */+ fetchImpl?: typeof fetch;+ timeoutMs?: number;+ } = {},+): Promise<ProxyProbeDto> {+ return probeTarget(+ target,+ options.fetchImpl ?? fetch,+ options.timeoutMs ?? PROXY_PROBE_TIMEOUT_MS,+ );+}diff --git a/packages/server/test/admin-settings.test.ts b/packages/server/test/admin-settings.test.tsindex f1978d81..9821bd7a 100644--- a/packages/server/test/admin-settings.test.ts+++ b/packages/server/test/admin-settings.test.ts@@ -10,9 +10,19 @@* between the two — the total may not sit below the per-file cap, checked against the EFFECTIVE* post-write pair so a one-field PUT cannot create an unsendable configuration — and the same* atomicity guarantee the proxy fields have.+ *+ * The reachability probe rides the same route too: the rule that decides reachable from+ * unreachable, and the endpoint around it. Its fetch is always stubbed — a test that reached a+ * real provider would fail on an offline machine and turn CI into a network monitor.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";-import type { ServerSettingsResponse } from "../src/api/types.js";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type {+ ProxyProbeDto,+ ProxyProbeResponse,+ ProxyProbeTargetsResponse,+ ServerSettingsResponse,+} from "../src/api/types.js";+import { classifyProxyProbe } from "../src/services/proxy-probe.js";import {DEFAULT_ATTACHMENT_MAX_MB,DEFAULT_ATTACHMENT_TOTAL_MB,@@ -31,6 +41,8 @@ describe("admin server settings", () => {admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);});afterEach(async () => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();await t.cleanup();});@@ -45,6 +57,10 @@ describe("admin server settings", () => {const api = apiClient(t.app, cookie);expect((await api.get("/api/admin/settings")).status).toBe(403);expect((await api.put("/api/admin/settings", { proxyForApp: false })).status).toBe(403);+ // The probe reaches the network on the server's behalf, so it sits behind the same gate,+ // and so does the list of what it would reach.+ expect((await api.get("/api/admin/settings/proxy-probe")).status).toBe(403);+ expect((await api.post("/api/admin/settings/proxy-probe/openai")).status).toBe(403);// The failed PUT changed nothing.expect((await getSettings()).settings.proxyForApp).toBe(true);});@@ -278,4 +294,133 @@ describe("admin server settings", () => {expect(settings.proxyForApp).toBe(true);expect(settings.attachmentMaxMb).toBe(DEFAULT_ATTACHMENT_MAX_MB);});+ // —— reachability probe ——++ /** undici's shape for a transport failure: `TypeError: fetch failed` over the real error. */+ const fetchFailed = (code: string) =>+ new TypeError("fetch failed", { cause: Object.assign(new Error(code), { code }) });++ it("probe classification: any HTTP answer is reachable", () => {+ // The probe carries no credential, so a rejection is the expected answer — and an answer+ // is the whole proof: the name resolved, TCP connected, TLS completed, the host replied.+ expect(classifyProxyProbe({ status: 401 })).toBe("reachable");+ expect(classifyProxyProbe({ status: 403 })).toBe("reachable");+ expect(classifyProxyProbe({ status: 404 })).toBe("reachable");+ expect(classifyProxyProbe({ status: 200 })).toBe("reachable");+ expect(classifyProxyProbe({ status: 503 })).toBe("reachable");+ });++ it("probe classification: a transport failure is named by the cause underneath it", () => {+ const timedOut = Object.assign(new Error("aborted due to timeout"), { name: "TimeoutError" });+ expect(classifyProxyProbe({ error: timedOut })).toBe("timeout");+ expect(classifyProxyProbe({ error: fetchFailed("ENOTFOUND") })).toBe("dns");+ expect(classifyProxyProbe({ error: fetchFailed("ECONNREFUSED") })).toBe("refused");+ expect(classifyProxyProbe({ error: fetchFailed("DEPTH_ZERO_SELF_SIGNED_CERT") })).toBe("tls");+ expect(classifyProxyProbe({ error: fetchFailed("ERR_TLS_CERT_ALTNAME_INVALID") })).toBe("tls");+ expect(classifyProxyProbe({ error: fetchFailed("ENETUNREACH") })).toBe("network");+ // A proxy that refuses the CONNECT tunnel arrives as an AbortError NESTED under "fetch+ // failed". That is a refusal to carry the request, not a host that took too long, so only+ // an abort on the outermost error may read as a timeout.+ const tunnelRefused = new TypeError("fetch failed", {+ cause: Object.assign(new Error("Proxy response (403) !== 200 when HTTP Tunneling"), {+ name: "AbortError",+ code: "UND_ERR_ABORTED",+ }),+ });+ expect(classifyProxyProbe({ error: tunnelRefused })).not.toBe("timeout");+ });++ it("one request per target: each is reported on its own, with no credential and the listed URL", async () => {+ // The page lists these before anyone presses the button, so they must be the very URLs+ // the probes then request — asserted together at the end of this test.+ const listed = (await (+ await admin.get("/api/admin/settings/proxy-probe")+ ).json()) as ProxyProbeTargetsResponse;+ expect(listed.targets.map((t) => t.provider)).toEqual([+ "openai",+ "anthropic",+ "gemini",+ "deepseek",+ // GLM is two hosts, not one: a proxy can carry the global endpoint and not the mainland+ // one, which is the difference an admin choosing between the two keys needs to see.+ "zai",+ "bigmodel",+ ]);++ // Every provider key the process could reach for is present, so "no credential is sent"+ // is a claim about the code rather than about an empty environment: a probe that fell+ // back to these the way protocol detection does would now be caught.+ for (const key of [+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "GEMINI_API_KEY",+ "DEEPSEEK_API_KEY",+ "ZAI_API_KEY",+ ]) {+ vi.stubEnv(key, `secret-${key}`);+ }++ const requests: Array<{ url: string; init: RequestInit }> = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string, init: RequestInit) => {+ requests.push({ url, init });+ // One dead target proves the others are reported independently rather than as a batch+ // that fails whole.+ if (url.includes("deepseek")) throw fetchFailed("ECONNREFUSED");+ // A 5xx is still an answer, so it is still reachable — the rule protocol detection+ // next door deliberately does NOT share, since it reads the response and this does not.+ if (url.includes("googleapis")) return new Response("nope", { status: 503 });+ return new Response("{}", { status: 401 });+ }),+ );++ // One call per provider, the way the page fires them — it renders each answer as it+ // lands rather than waiting for a response carrying all of them.+ const probes: ProxyProbeDto[] = [];+ for (const target of listed.targets) {+ const res = await admin.post(`/api/admin/settings/proxy-probe/${target.provider}`);+ expect(res.status).toBe(200);+ probes.push(((await res.json()) as ProxyProbeResponse).probe);+ }++ // Each answer names its own target, so a row cannot be filled from another's result.+ expect(probes.map((p) => p.provider)).toEqual(listed.targets.map((t) => t.provider));+ expect(probes.map((p) => p.url)).toEqual(listed.targets.map((t) => t.url));+ expect(probes.filter((p) => p.outcome === "reachable").map((p) => p.status)).toEqual([+ 401, 401, 503, 401, 401,+ ]);+ expect(probes.find((p) => p.provider === "deepseek")).toMatchObject({ outcome: "refused" });+ // Every result is timed, the failed one included.+ for (const probe of probes) expect(probe.ms).toBeGreaterThanOrEqual(0);+ // What was listed is exactly what was fetched: a page that advertises one URL and probes+ // another would be lying about what "no API key" applies to.+ expect(requests.map((r) => r.url)).toEqual(listed.targets.map((t) => t.url));+ // Hard-coded https targets, and not one credential on any of them — the process+ // environment's provider keys must not leak into an unauthenticated probe.+ expect(requests).toHaveLength(listed.targets.length);+ for (const { url, init } of requests) {+ expect(url.startsWith("https://")).toBe(true);+ const headers = new Headers(init.headers);+ expect(headers.get("authorization")).toBeNull();+ expect(headers.get("x-api-key")).toBeNull();+ // Not under any other header name either, and not smuggled into the query string.+ const sent = `${url} ${[...headers].map(([k, v]) => `${k}: ${v}`).join(" ")}`;+ expect(sent).not.toContain("secret-");+ }+ });++ it("a provider id outside the fixed list is a 404 that reaches no network at all", async () => {+ const fetchSpy = vi.fn(async () => new Response("{}", { status: 200 }));+ vi.stubGlobal("fetch", fetchSpy);+ // The route takes an id and never a URL, so an id nobody put in the list must not become+ // a fetch of anything — that is the whole reason this endpoint has no request body.+ for (const provider of ["evil", "openai/../evil", "https://evil.example", "OPENAI", ""]) {+ const res = await admin.post(+ `/api/admin/settings/proxy-probe/${encodeURIComponent(provider)}`,+ );+ expect(res.status).toBe(404);+ }+ expect(fetchSpy).not.toHaveBeenCalled();+ });});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex f3d3606a..b69e94fa 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -85,6 +85,9 @@ import type {ScheduleItem,SchedulesResponse,ScheduleUpsertRequest,+ ProxyProbeProvider,+ ProxyProbeResponse,+ ProxyProbeTargetsResponse,ServerSettingsResponse,ServerSettingsUpdateRequest,SessionCategory,@@ -194,6 +197,22 @@ export const adminGetSettings = () => apiFetch<ServerSettingsResponse>("/api/admexport const adminPutSettings = (body: ServerSettingsUpdateRequest) =>apiFetch<ServerSettingsResponse>("/api/admin/settings", { method: "PUT", body });+/**+ * What the reachability probe would request — name and exact URL per provider — without+ * requesting it. Served rather than held as a frontend constant so the listed URLs cannot+ * drift from the ones actually fetched.+ */+export const adminGetProxyProbeTargets = () =>+ apiFetch<ProxyProbeTargetsResponse>("/api/admin/settings/proxy-probe");++/**+ * Measures the server's own outbound path to ONE of those targets, unauthenticated. One+ * request per provider so each row can be filled the moment its own answer arrives; the+ * provider id is the only thing sent, and the server matches it against the same fixed list.+ */+export const adminProbeProxy = (provider: ProxyProbeProvider) =>+ apiFetch<ProxyProbeResponse>(`/api/admin/settings/proxy-probe/${provider}`, { method: "POST" });+// Project & members --------------------------------------------------------------export const listProjects = () => apiFetch<ProjectsResponse>("/api/projects");diff --git a/packages/web/src/features/settings/proxy-section.tsx b/packages/web/src/features/settings/proxy-section.tsxindex 5854a2c3..b63075ef 100644--- a/packages/web/src/features/settings/proxy-section.tsx+++ b/packages/web/src/features/settings/proxy-section.tsx@@ -12,19 +12,55 @@* controls and Save stay disabled until they arrive. The saved response is adopted as the new* baseline, including the address in the exact form the server stored, so the page reflects* what is on the server rather than what was typed at it.+ *+ * The reachability test sits BELOW the save row, in its own block, because it measures the+ * SAVED configuration: only a PUT moves the server's outbound dispatcher, so a typed-but-unsaved+ * address is not in the path the probes travel. Reading top to bottom — edit, save, then+ * measure — is what makes that honest without a warning banner. A save clears results that now+ * describe a superseded configuration.+ *+ * One request per target, fired together and rendered as each lands. A single response carrying+ * all of them would hold every row blank until the slowest answered, which for a host that+ * black-holes connections is the full five-second timeout with five working results behind it.+ *+ * It carries its own busy flag rather than borrowing Save's: a measurement is not an unsaved+ * edit, so it neither blocks Save nor is blocked by it.+ *+ * The targets — name and exact URL — come from the server and are listed before anyone presses+ * the button, so the page shows concretely what will be requested and a reader can see that+ * these are plain unauthenticated GETs. A frontend copy of that list could drift from the URLs+ * the server really fetches, so it is fetched, not hard-coded.*/-import { useEffect, useState } from "react";-import type { ServerSettings } from "@prismshadow/penguin-server/api";+import { useEffect, useRef, useState } from "react";+import type {+ ProxyProbeDto,+ ProxyProbeProvider,+ ProxyProbeTargetDto,+ ServerSettings,+} from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";+import { toneInk } from "../../lib/tone";import { Button } from "../../components/ui/button";import { Input } from "../../components/ui/input";import { Switch } from "../../components/ui/switch";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { SectionShell } from "./section-shell";+/** Brand names: identical in every locale, so they are keyed off the server's provider id rather than doubled into both dictionaries. */+const PROVIDER_LABEL: Record<ProxyProbeProvider, string> = {+ openai: "OpenAI",+ anthropic: "Anthropic",+ gemini: "Gemini",+ deepseek: "DeepSeek",+ // GLM's two hosts, named by the one each key comes from: the global endpoint the catalog+ // defaults to, and the mainland one a bigmodel.cn key needs.+ zai: "Z.AI",+ bigmodel: "BigModel",+};+export function ProxySection() {/** Stored settings as hydrated on mount (null until then) — the no-change baseline. */const [settings, setSettings] = useState<ServerSettings | null>(null);@@ -35,6 +71,17 @@ export function ProxySection() {/** Inline error under the address input (the server's invalid_proxy_url rejection). */const [addressError, setAddressError] = useState<string | null>(null);const [busy, setBusy] = useState(false);+ /** What the probe would request, listed before it is run (null until it arrives). */+ const [targets, setTargets] = useState<ProxyProbeTargetDto[] | null>(null);+ /** Results by provider (null until a run starts, then filled one at a time), and the probe's own busy flag. */+ const [results, setResults] = useState<Map<ProxyProbeProvider, ProxyProbeDto> | null>(null);+ const [probing, setProbing] = useState(false);+ /**+ * Which run each in-flight answer belongs to. A result can land after its run stopped being+ * the current one — a save adopts new settings mid-flight — and a row filled from a+ * superseded run would report a path nothing travelled.+ */+ const runSeq = useRef(0);/** Adopt server-side truth: the baseline and the drafts move together. */const adopt = (next: ServerSettings) => {@@ -42,6 +89,11 @@ export function ProxySection() {setProxyForApp(next.proxyForApp);setProxyForAgent(next.proxyForAgent);setProxyUrl(next.proxyUrl ?? "");+ // Results describe the path they travelled; a save may have replaced it. Bumping the run+ // counter also discards whatever is still in flight against the old one.+ runSeq.current += 1;+ setResults(null);+ setProbing(false);};useEffect(() => {@@ -55,6 +107,14 @@ export function ProxySection() {// Controls stay disabled; leaving and returning to the section retries the fetch.if (!cancelled) toastError(apiErrorText(e));});+ // The target list is static server-side, so its failure is not worth a second toast on+ // top of the settings one — the block simply stays empty until a retry succeeds.+ void api+ .adminGetProxyProbeTargets()+ .then((res) => {+ if (!cancelled) setTargets(res.targets);+ })+ .catch(() => {});return () => {cancelled = true;};@@ -89,35 +149,130 @@ export function ProxySection() {}};+ const runProbe = () => {+ if (settings === null || targets === null || probing) return;+ const run = (runSeq.current += 1);+ setProbing(true);+ // The previous run's numbers go now rather than lingering under a running test: a stale+ // figure beside a live one cannot be told apart. An empty map, not null — null is "never+ // run", and the rows read it to tell "not tested" from "still measuring".+ setResults(new Map());+ // One toast per run, not one per target: a lost session fails every request identically,+ // and six copies of the same sentence is not six pieces of information.+ let reported = false;+ void Promise.allSettled(+ targets.map((t) =>+ api+ .adminProbeProxy(t.provider)+ .then((res) => {+ if (runSeq.current !== run) return;+ setResults((prev) => new Map(prev ?? []).set(res.probe.provider, res.probe));+ })+ .catch((e: unknown) => {+ // Every outcome the probe itself can have, reachable or not, comes back inside a+ // 200; only the request failing (a lost session, a dead server) lands here.+ if (runSeq.current !== run || reported) return;+ reported = true;+ toastError(apiErrorText(e));+ }),+ ),+ ).finally(() => {+ if (runSeq.current === run) setProbing(false);+ });+ };+const hydrated = settings !== null;+return (- <SectionShell- actions={- <Button variant="primary" disabled={!hydrated || busy} onClick={() => void save()}>- {S.common.save}- </Button>- }- >- <div className="flex items-center justify-between gap-3">- <span className="text-sm font-medium">{S.settings.proxyForApp}</span>- <Switch checked={proxyForApp} onChange={setProxyForApp} disabled={!hydrated} />- </div>- <div className="flex items-center justify-between gap-3">- <span className="text-sm font-medium">{S.settings.proxyForAgent}</span>- <Switch checked={proxyForAgent} onChange={setProxyForAgent} disabled={!hydrated} />- </div>- <Input- label={S.settings.proxyAddress}- size="sm"- value={proxyUrl}- placeholder={S.settings.proxyAddressPlaceholder}- disabled={!hydrated}- {...(addressError !== null ? { error: addressError } : {})}- onChange={(e) => {- setProxyUrl(e.target.value);- if (addressError !== null) setAddressError(null);- }}- />- </SectionShell>+ <>+ <SectionShell+ actions={+ <Button variant="primary" disabled={!hydrated || busy} onClick={() => void save()}>+ {S.common.save}+ </Button>+ }+ >+ <div className="flex items-center justify-between gap-3">+ <span className="text-sm font-medium">{S.settings.proxyForApp}</span>+ <Switch checked={proxyForApp} onChange={setProxyForApp} disabled={!hydrated} />+ </div>+ <div className="flex items-center justify-between gap-3">+ <span className="text-sm font-medium">{S.settings.proxyForAgent}</span>+ <Switch checked={proxyForAgent} onChange={setProxyForAgent} disabled={!hydrated} />+ </div>+ <Input+ label={S.settings.proxyAddress}+ size="sm"+ value={proxyUrl}+ placeholder={S.settings.proxyAddressPlaceholder}+ disabled={!hydrated}+ {...(addressError !== null ? { error: addressError } : {})}+ onChange={(e) => {+ setProxyUrl(e.target.value);+ if (addressError !== null) setAddressError(null);+ }}+ />+ </SectionShell>+ <section className="mt-6">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0 text-sm font-medium">{S.settings.proxyProbe}</div>+ <Button+ size="sm"+ disabled={!hydrated || targets === null || probing}+ aria-busy={probing}+ onClick={runProbe}+ >+ {probing ? S.settings.proxyProbeRunning : S.settings.proxyProbeRun}+ </Button>+ </div>+ <ul className="mt-3 space-y-3">+ {(targets ?? []).map((t) => {+ // This row's own answer, shown the moment it exists — the rows still waiting keep+ // saying so beside it. Checked on `probe.outcome` itself rather than through a+ // boolean, so the failure branch narrows to the kinds the dictionary has a word for.+ const probe = results?.get(t.provider);+ const outcomeText =+ probe !== undefined+ ? probe.outcome === "reachable"+ ? S.settings.proxyProbeLatency(probe.ms)+ : S.settings.proxyProbeFailure[probe.outcome]+ : probing+ ? S.settings.proxyProbeRunning+ : S.settings.proxyProbeIdle;+ const reachable = probe !== undefined && probe.outcome === "reachable";+ return (+ <li key={t.provider}>+ <div className="flex items-baseline justify-between gap-3">+ <span className="text-xs font-medium text-gray-700 dark:text-gray-300">+ {PROVIDER_LABEL[t.provider]}+ </span>+ <span+ className={`shrink-0 text-xs tabular-nums ${+ probe === undefined+ ? // No verdict yet: secondary text, not a status tone — an absence+ // is not a judgement about the target.+ "text-gray-500 dark:text-gray-400"+ : reachable+ ? toneInk.success+ : toneInk.danger+ }`}+ >+ {outcomeText}+ {/* A bare number does not say "reachable"; the word travels with it for+ anyone who cannot see the colour. */}+ {reachable && (+ <span className="sr-only"> · {S.settings.proxyProbeReachableState}</span>+ )}+ </span>+ </div>+ <div className="truncate font-mono text-[11px] text-gray-400 dark:text-gray-500">+ {t.url}+ </div>+ </li>+ );+ })}+ </ul>+ </section>+ </>);}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 58e68446..10ebd355 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -141,13 +141,38 @@ export const en: Strings = {/** Admin-only sub-page (server-global); its explanation is disclosed at the pane heading. */proxyTitle: "Proxy options",proxyInfo:- "Server-global, and in force the moment it is saved — nothing to restart. Loopback addresses always go direct.",+ "Server-global, and in force the moment it is saved — nothing to restart. Loopback " ++ "addresses always go direct. The reachability test sends one credential-free GET to each " ++ "address listed below and measures this server's own outbound hop: any HTTP answer counts " ++ "as reachable, 401 and 403 included — a refused credential still proves DNS, TCP and TLS " ++ "all completed — while unreachable means the transport itself failed. It measures the " ++ "saved settings, since only a save rebuilds the outbound dispatcher; that is why the test " ++ "sits below Save, and why an edited address has to be saved before testing. Results " ++ "appear one by one, each as soon as its own answer arrives.",/** The two switches: the server's own outbound traffic / agent command subprocess environments. */proxyForApp: "Application uses the proxy",proxyForAgent: "Agent environment uses the proxy",/** The shared explicit proxy address (empty = follow the proxy environment variables). */proxyAddress: "Proxy address",proxyAddressPlaceholder: "Empty = follow system proxy",+ /** Reachability test: the block's heading, and its button at rest and while probing. */+ proxyProbe: "Reachability test",+ proxyProbeRun: "Test",+ proxyProbeRunning: "Testing…",+ /** A provider answered: the latency IS the result, so this is the only visible text. */+ proxyProbeLatency: (ms: number): string => `${ms} ms`,+ /** The same verdict in words, read out beside the number — a bare figure does not say "reachable". */+ proxyProbeReachableState: "Reachable",+ /** Listed but not yet measured: an absence, not a verdict. */+ proxyProbeIdle: "Not tested",+ /** A provider did not answer: the transport fault, each naming the state in words. */+ proxyProbeFailure: {+ timeout: "Timed out",+ dns: "DNS lookup failed",+ refused: "Connection refused",+ tls: "TLS handshake failed",+ network: "Unreachable",+ },/** Admin-only sub-page (server-global). */uploadLimitsTitle: "Upload limits",/** Its two number fields, both in whole MB. */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 7df20774..bb6d47f0 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -158,13 +158,36 @@ export const zh = {importTraceTooLarge: "文件超过 14MB 上限。",/** Admin-only sub-page (server-global); its explanation is disclosed at the pane heading. */proxyTitle: "代理选项",- proxyInfo: "服务器全局设置,保存后立即生效,无需重启。回环地址始终直连。",+ proxyInfo:+ "服务器全局设置,保存后立即生效,无需重启。回环地址始终直连。" ++ "「连通性测速」向下方列出的地址各发一次不带凭据的 GET,量的是本服务器出站这一跳:" ++ "对方回了 HTTP 响应即算连通,401、403 同样算——它们说明域名解析、TCP 连接与 TLS 握手都已走通;" ++ "连不通指的是传输本身失败。测的是已保存的设置——只有保存才会重建出站 dispatcher," ++ "所以测速排在「保存」下方,改过地址要先保存再测。结果先到先出,各自到达即显示。",/** The two switches: the server's own outbound traffic / agent command subprocess environments. */proxyForApp: "应用程序使用代理",proxyForAgent: "Agent 环境使用代理",/** The shared explicit proxy address (empty = follow the proxy environment variables). */proxyAddress: "代理地址",proxyAddressPlaceholder: "留空 = 跟随系统代理",+ /** Reachability test: the block's heading, and its button at rest and while probing. */+ proxyProbe: "连通性测速",+ proxyProbeRun: "测速",+ proxyProbeRunning: "测速中…",+ /** A provider answered: the latency IS the result, so this is the only visible text. */+ proxyProbeLatency: (ms: number): string => `${ms} ms`,+ /** The same verdict in words, read out beside the number — a bare figure does not say "reachable". */+ proxyProbeReachableState: "已连通",+ /** Listed but not yet measured: an absence, not a verdict. */+ proxyProbeIdle: "未测试",+ /** A provider did not answer: the transport fault, each naming the state in words. */+ proxyProbeFailure: {+ timeout: "连接超时",+ dns: "域名解析失败",+ refused: "连接被拒绝",+ tls: "TLS 握手失败",+ network: "无法连接",+ },/** Admin-only sub-page (server-global). */uploadLimitsTitle: "上传限制",/** Its two number fields, both in whole MB. */