A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): 左下角账户菜单加用户反馈入口,提交进本机的需求箱
lmliheng4e79c473f846
diff --git a/changelog/unreleased/2026-10-07-feedback-entry.md b/changelog/unreleased/2026-10-07-feedback-entry.mdnew file mode 100644index 00000000..cf31ce8e--- /dev/null+++ b/changelog/unreleased/2026-10-07-feedback-entry.md@@ -0,0 +1,36 @@+# Web: a feedback entry in the account menu, filed straight into the install's queue++- **Date:** 2026-10-07+- **Type:** feature+- **Scope:** `web`, `server`, `ui-gallery`++[中文版](2026-10-07-feedback-entry.zh.md)++The bottom-left account menu gained a **反馈 / Feedback** row that opens a two-field dialog — a+one-line title and an optional detail — and files what the user typed into the install's feedback+queue. The answer comes back as a toast naming the item the queue created.++## Where the words go++- The install names its queue with `ADELIE_FEEDBACK_URL`; the credential it wants, if any, is+ `ADELIE_FEEDBACK_KEY`. Both are read at startup like the rest of the deployment environment, and+ the address must be an absolute `http(s)` URL with no credentials in it (the key has its own+ variable, so it does not end up in a logged request line).+- The browser never learns either one. `GET /api/feedback` answers `{ok, configured}` alone, and+ the row is drawn only where that is true — an install with nothing to send to offers no button+ that can only fail. The submission itself goes to `POST /api/feedback` and the server forwards+ it to the configured endpoint as the box's own `POST /api/requirements` body, `{title, detail}`,+ with the key as its `x-adelie-key` header. The item then sits in the same queue that queue's+ page lists and the patrol rounds read their work from.+- The title is required and capped at 200 characters, the detail at 20000 — the endpoint's own+ limits, applied before the hop so an over-long submission is answered in place.+- Failures are named for what the user can do about them: a submission with no endpoint+ configured (the operator turned it off under an open dialog) says so, everything else is one+ retryable sentence. A rejection or an unreachable endpoint is reported as this server's own+ failure with the status code — the far end's error text is written for the operator, and is not+ relayed to whoever is typing.++## The demo gallery++`packages/ui-gallery` answers both routes as an install that has a queue behind it, so the row and+its dialog can be reviewed on the component gallery without a server.diff --git a/changelog/unreleased/2026-10-07-feedback-entry.zh.md b/changelog/unreleased/2026-10-07-feedback-entry.zh.mdnew file mode 100644index 00000000..d053b078--- /dev/null+++ b/changelog/unreleased/2026-10-07-feedback-entry.zh.md@@ -0,0 +1,30 @@+# Web:左下角账户菜单新增用户反馈入口,提交直接进本机的反馈队列++- **Date:** 2026-10-07+- **Type:** feature+- **Scope:** `web`, `server`, `ui-gallery`++[English](2026-10-07-feedback-entry.md)++左下角的账户菜单新增**反馈**一行,点开是一个两栏对话框——一句话标题加可不填的详细说明——把用户写下的+内容直接投进本机的反馈队列。收下之后会有一条提示,把队列给这条起的编号报出来。++## 内容去哪里++- 队列地址由 `ADELIE_FEEDBACK_URL` 指定,需要的凭据(如果有)是 `ADELIE_FEEDBACK_KEY`。两者与其余部署+ 环境变量一样在启动时读取;地址必须是绝对的 `http(s)` URL 且不得内嵌凭据(凭据有自己的变量,否则会+ 跟着请求行进日志)。+- 浏览器两个都拿不到。`GET /api/feedback` 只回 `{ok, configured}`,也只有它为真时那一行才画出来——+ 没地方可投的安装不给出一个只会失败的按钮。提交本身走 `POST /api/feedback`,由服务端按那个队列自己的+ `POST /api/requirements` 形状转发过去(`{title, detail}`),凭据放在 `x-adelie-key` 头里。这条内容随后+ 就躺在队列页列出的同一份清单里,巡台轮次也从那里领活。+- 标题必填、上限 200 字符,详细说明上限 20000——用的是队列自己的上限,在转发之前先判,超长的提交当场+ 就有回复。+- 失败按用户能做什么来说:没配反馈后端时(也就是对话框开着的时候运维把这个开关关了)就照实说,其余一律+ 同一句「稍后再试」。对方拒收或连不上都记成本服务自己的失败并带上状态码——对面那段错误文字是写给运维的,+ 不转给正在打字的人。++## 演示画廊++`packages/ui-gallery` 把这两条路由都答成「后端有队列」的安装,所以不用起服务也能在组件画廊上过一遍+这一行与它背后的对话框。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 547a575e..c85b0226 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -5812,3 +5812,31 @@ export interface DesktopBrowserEventMessage {type: "desktop-browser-event";event: DesktopBrowserEvent;}++// ---------------------------------------------------------------------------+// Feedback (GET|POST /api/feedback)+// ---------------------------------------------------------------------------++/**+ * Whether this install has somewhere to send feedback (ADELIE_FEEDBACK_URL). The sidebar+ * renders the entry only where the answer is true; the endpoint's address itself is the+ * server's business and never crosses this boundary.+ */+export interface FeedbackConfigResponse {+ ok: true;+ configured: boolean;+}++/** One submission from the feedback entry: a title, and what the user typed under it. */+export interface FeedbackRequest {+ /** One line naming the feedback (the box's `title`, at most 200 characters). */+ title: string;+ /** The body, at most 20000 characters; may be empty. */+ detail?: string;+}++/** The acceptance: `id` names the item the endpoint filed, when it reported one. */+export interface FeedbackResponse {+ ok: true;+ id?: string;+}diff --git a/packages/server/src/config.ts b/packages/server/src/config.tsindex 7871a47a..ef1aa31a 100644--- a/packages/server/src/config.ts+++ b/packages/server/src/config.ts@@ -129,6 +129,19 @@ export interface ServerConfig {* no CLI to offer and no shim written.*/cliEntry?: string | null;+ /**+ * Feedback endpoint (ADELIE_FEEDBACK_URL): the absolute http(s) URL the Web UI's feedback+ * entry posts to, with ADELIE_FEEDBACK_KEY sent as its `x-adelie-key` header when set. Null+ * — the default — turns the entry off: an install with no feedback backend has nothing to+ * send its users' words to, and a button that can only fail is worse than no button.+ *+ * The contract is the Adelie requirements box's (`POST /api/requirements`, `{title, detail}`+ * in, `{ok, item}` out) — the same box the patrol rounds read their work from, so feedback+ * filed from the UI lands in the queue an Agent already works through.+ */+ feedbackUrl: string | null;+ /** The feedback endpoint's credential (ADELIE_FEEDBACK_KEY), sent as `x-adelie-key`; null when the endpoint takes none. */+ feedbackKey: string | null;}const DAY_MS = 24 * 60 * 60 * 1000;@@ -234,7 +247,33 @@ export function normalizeModelScopeBridgeUrl(raw: string | undefined): string {return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;}-/** Parses server config from environment variables (PORT / HOST / ADELIE_HOME / ADELIE_WEB_DIST / ADELIE_WEB_DB / ADELIE_PREVIEW_ORIGIN / PENGUIN_GO_ORIGIN / MODELSCOPE_BRIDGE_URL / ADELIE_SEED_ADMIN_PASSWORD / ADELIE_DESKTOP_TOKEN / ADELIE_PORT_FILE / ADELIE_TRUST_PROXY / ADELIE_CLI_ENTRY; each of the deployment names is also read in its pre-rename `PENGUIN_*` spelling, see state/boundary-env.ts). */+/**+ * Validates ADELIE_FEEDBACK_URL into an absolute http(s) URL, or null when unset. A blank+ * value counts as unset (the common `.env` case of `ADELIE_FEEDBACK_URL=`), and a malformed+ * one throws here rather than at the first submission: the alternative is a feedback entry+ * that looks live and answers with a network error the operator cannot connect to a typo.+ * Credentials in the URL stay rejected — the key has its own variable, and putting it in the+ * URL would leak it into the journal through the logged request line.+ */+export function normalizeFeedbackUrl(raw: string | undefined): string | null {+ const value = raw?.trim();+ if (!value) return null;+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ throw new Error(`Invalid ADELIE_FEEDBACK_URL=${value} (expected an absolute HTTP(S) URL)`);+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") {+ throw new Error(`Invalid ADELIE_FEEDBACK_URL=${value} (only http/https are supported)`);+ }+ if (url.username !== "" || url.password !== "") {+ throw new Error(`Invalid ADELIE_FEEDBACK_URL=${value} (put the key in ADELIE_FEEDBACK_KEY)`);+ }+ return url.toString();+}++/** Parses server config from environment variables (PORT / HOST / ADELIE_HOME / ADELIE_WEB_DIST / ADELIE_WEB_DB / ADELIE_PREVIEW_ORIGIN / PENGUIN_GO_ORIGIN / MODELSCOPE_BRIDGE_URL / ADELIE_SEED_ADMIN_PASSWORD / ADELIE_DESKTOP_TOKEN / ADELIE_PORT_FILE / ADELIE_TRUST_PROXY / ADELIE_CLI_ENTRY / ADELIE_FEEDBACK_URL / ADELIE_FEEDBACK_KEY; each of the deployment names is also read in its pre-rename `PENGUIN_*` spelling, see state/boundary-env.ts). */export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): ServerConfig {// The root is read off the passed environment rather than `process.env` (this function takes// one so tests can hand it a fabricated environment), so the two names are spelled here as@@ -271,5 +310,9 @@ export function resolveServerConfig(env: NodeJS.ProcessEnv = process.env): ServetrustProxy: env.ADELIE_TRUST_PROXY === "1",supervised: env.ADELIE_SUPERVISED === "1",cliEntry: boundaryEnv(env, "cliEntry")?.trim() || defaultCliEntry(),+ feedbackUrl: normalizeFeedbackUrl(env.ADELIE_FEEDBACK_URL),+ // An empty value counts as unset: an endpoint that wants no credential gets no header,+ // rather than an empty one it would have to treat as a wrong key.+ feedbackKey: env.ADELIE_FEEDBACK_KEY?.trim() || null,};}diff --git a/packages/server/src/http/routes/feedback.ts b/packages/server/src/http/routes/feedback.tsnew file mode 100644index 00000000..53947a09--- /dev/null+++ b/packages/server/src/http/routes/feedback.ts@@ -0,0 +1,134 @@+/**+ * Feedback routes: the sidebar's feedback entry, and whether this install has anywhere to+ * send it.+ *+ * GET /api/feedback -> { ok, configured } whether a feedback endpoint is configured+ * POST /api/feedback -> { ok, id? } forwards the entry's words to that endpoint+ *+ * The endpoint is the Adelie requirements box (ADELIE_FEEDBACK_URL, the key in+ * ADELIE_FEEDBACK_KEY, see config.ts): the UI posts its title and detail here, this route+ * forwards them as the box's `POST /api/requirements`, and the round the patrol runs picks+ * the item up like any other. The hop exists because the box's key is the operator's — it is+ * held by this process and never reaches the browser, and the box itself needs neither CORS+ * nor to be reachable from wherever the user happens to sit.+ *+ * The browser is told only whether there is somewhere to send to (GET), never where: a+ * 404/500 at the other end is this route's problem to report, not the client's to explain.+ */+import { Hono } from "hono";+import type { AppEnv } from "../../auth/middleware.js";+import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";+import type { FeedbackConfigResponse, FeedbackResponse } from "../../api/types.js";+import type { ServerConfig } from "../../config.js";+import type { Config } from "../../hmr/capabilities.js";+import { HttpError } from "../errors.js";+import { badRequest, readJson } from "../validate.js";+import type { HttpFetch } from "../../services/update-check-service.js";++export interface FeedbackRouteDeps {+ config: ServerConfig;+ /** Outbound HTTP, injectable so tests need not stub the global fetch. */+ http: HttpFetch;+}++/** The box trims and caps these itself; the same caps here give the user an answer before the hop. */+const MAX_TITLE = 200;+const MAX_DETAIL = 20000;++/** A feedback submission must not hold a request thread open behind a wedged backend. */+const FEEDBACK_TIMEOUT_MS = 10_000;++export function feedbackRoutes(deps: FeedbackRouteDeps): Hono<AppEnv> {+ const routes = new Hono<AppEnv>();++ routes.get("/", (c) => {+ const body: FeedbackConfigResponse = { ok: true, configured: deps.config.feedbackUrl !== null };+ return c.json(body);+ });++ routes.post("/", async (c) => {+ const { feedbackUrl, feedbackKey } = deps.config;+ // Checked here rather than in a middleware: the entry is hidden without an endpoint, so+ // this only answers a hand-made request — and it answers with a code the UI can name.+ if (feedbackUrl === null) {+ throw new HttpError(+ 503,+ "feedback_not_configured",+ "This install has no feedback endpoint (ADELIE_FEEDBACK_URL).",+ );+ }++ const body = await readJson(c);+ const title = typeof body.title === "string" ? body.title.trim() : "";+ const detail = typeof body.detail === "string" ? body.detail.trim() : "";+ if (title === "") throw badRequest("title must not be empty.");+ if (title.length > MAX_TITLE)+ throw badRequest(`title must be at most ${MAX_TITLE} characters.`);+ if (detail.length > MAX_DETAIL)+ throw badRequest(`detail must be at most ${MAX_DETAIL} characters.`);++ let response: Response;+ try {+ response = await deps.http.fetch(feedbackUrl, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ ...(feedbackKey !== null ? { "x-adelie-key": feedbackKey } : {}),+ },+ body: JSON.stringify({ title, detail }),+ signal: AbortSignal.timeout(FEEDBACK_TIMEOUT_MS),+ });+ } catch {+ // The backend's own error text is not relayed: it is written for the box's operator,+ // and a user typing into a text box can do nothing with it.+ throw new HttpError(502, "feedback_unreachable", "Could not reach the feedback endpoint.");+ }+ if (!response.ok) {+ throw new HttpError(+ 502,+ "feedback_rejected",+ `The feedback endpoint refused the submission (status ${response.status}).`,+ );+ }++ // The created item's id is handed back so the report can name what was filed; a backend+ // that answers with something else is still a success, just a nameless one.+ let id: string | undefined;+ try {+ const data = (await response.json()) as { item?: { id?: unknown } };+ if (typeof data?.item?.id === "string") id = data.item.id;+ } catch {+ // A reply that is not JSON (an empty 204, a proxy's HTML) is not a failure.+ }+ const answer: FeedbackResponse = { ok: true, ...(id !== undefined ? { id } : {}) };+ return c.json(answer);+ });++ return routes;+}++/**+ * The route group's declaration. `auth: "user"` — anyone signed in may report something;+ * the audience is the operator either way, and gating it by role would only hide the+ * channel from the people who use the UI most.+ */+@Component({+ contributes: {+ "HttpModule.routes": [+ {+ id: "FeedbackModule.routes",+ prefix: "/api/feedback",+ auth: "user",+ order: 75,+ },+ ],+ },+})+export class FeedbackRoutes {+ @Use() private readonly config!: Config;+ @Use() private readonly http!: HttpFetch;+ @Bind("FeedbackModule.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = feedbackRoutes({ config: this.config, http: this.http });+ }+}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex afb89744..56aff570 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -70,6 +70,7 @@ import {} from "./services/update-check-service.js";import { UpdateJobService } from "./services/update-job.js";import { HarnessHistoryStore } from "./services/harness-history.js";+import { FeedbackRoutes } from "./http/routes/feedback.js";import { UsersRepo } from "./db/repos/users.js";import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";import { ServerSettingsRepo } from "./db/repos/server-settings.js";@@ -449,6 +450,7 @@ export class CompanyModule {}WebModule,InstallRoutes,VersionRoutes,+ FeedbackRoutes,HmrRoutes,DesktopRoutes,DesktopUpdateRoutes,diff --git a/packages/server/test/feedback.test.ts b/packages/server/test/feedback.test.tsnew file mode 100644index 00000000..53d46980--- /dev/null+++ b/packages/server/test/feedback.test.ts@@ -0,0 +1,176 @@+/**+ * The feedback routes: whether this install has a backend, and the hop that files what the+ * user typed into it.+ *+ * - GET /api/feedback needs a session and reports only whether a backend is configured —+ * never its address or its key.+ * - Without ADELIE_FEEDBACK_URL the entry stays off and a hand-made POST is answered+ * `feedback_not_configured`, not with a network attempt.+ * - With one, POST forwards `{title, detail}` and the configured key as `x-adelie-key`,+ * and hands back the item id the backend reported.+ * - A backend that refuses, or that cannot be reached, is a 502 — and its own error text+ * is not relayed to the browser.+ * - A blank title is a 400 before anything is sent; over-long title/detail are refused here+ * with the same caps the box applies.+ *+ * Nothing here reaches the network: the hop is the suite's fetch fake.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { FeedbackConfigResponse, FeedbackResponse } from "../src/api/types.js";+import { jsonResponse, stubFetch } from "./fixtures/fetch.js";+import { apiClient, createTestApp, loginAdmin } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const BOX_URL = "http://127.0.0.1:3003/api/requirements";+const BOX_KEY = "box-key-0123456789";++/** A failure body's `error`, the one shape every route here refuses with. */+const errorOf = (body: unknown): { code: string; message: string } =>+ (body as { error: { code: string; message: string } }).error;++describe("feedback routes", () => {+ let app: TestApp;++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ describe("without a backend", () => {+ beforeEach(async () => {+ app = await createTestApp();+ });++ it("reports the entry as off and never dials out", async () => {+ const fake = stubFetch(() => jsonResponse({ ok: true, item: { id: "req-1" } }));+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ const res = await api.get("/api/feedback");+ expect(res.status).toBe(200);+ const body = (await res.json()) as FeedbackConfigResponse;+ expect(body).toEqual({ ok: true, configured: false });+ // The address is the server's business: it must not travel, configured or not.+ expect(JSON.stringify(body)).not.toContain("3003");+ expect(fake.calls).toHaveLength(0);+ });++ it("refuses a submission with a code the UI can name", async () => {+ const fake = stubFetch(() => jsonResponse({ ok: true }));+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ const res = await api.post("/api/feedback", { title: "加个深色主题", detail: "…" });+ expect(res.status).toBe(503);+ expect(errorOf(await res.json()).code).toBe("feedback_not_configured");+ expect(fake.calls).toHaveLength(0);+ });+ });++ describe("with a backend", () => {+ beforeEach(async () => {+ app = await createTestApp({ config: { feedbackUrl: BOX_URL, feedbackKey: BOX_KEY } });+ });++ it("reports the entry as on without naming the endpoint", async () => {+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ const res = await api.get("/api/feedback");+ expect(res.status).toBe(200);+ const body = (await res.json()) as FeedbackConfigResponse;+ expect(body).toEqual({ ok: true, configured: true });+ expect(JSON.stringify(body)).not.toContain("3003");+ expect(JSON.stringify(body)).not.toContain(BOX_KEY);+ });++ it("forwards the words and the key, and hands back the item id", async () => {+ const fake = stubFetch((call) =>+ jsonResponse({ ok: true, item: { id: "req-7", title: "字体太小" } }, 201),+ );+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ const res = await api.post("/api/feedback", {+ title: "字体太小",+ detail: "侧栏的字看不清楚",+ });+ expect(res.status).toBe(200);+ expect((await res.json()) as FeedbackResponse).toEqual({ ok: true, id: "req-7" });++ expect(fake.calls).toHaveLength(1);+ const call = fake.calls[0]!;+ expect(call.url).toBe(BOX_URL);+ expect(call.method).toBe("POST");+ expect(call.headers.get("x-adelie-key")).toBe(BOX_KEY);+ expect(call.headers.get("content-type")).toContain("application/json");+ expect(JSON.parse(call.body)).toEqual({ title: "字体太小", detail: "侧栏的字看不清楚" });+ });++ it("sends no key header when none is configured", async () => {+ const other = await createTestApp({ config: { feedbackUrl: BOX_URL, feedbackKey: null } });+ const fake = stubFetch(() => jsonResponse({ ok: true, item: { id: "req-8" } }, 201));+ const api = apiClient(other.app, (await loginAdmin(other.app)).cookie);+ const res = await api.post("/api/feedback", { title: "只有标题" });+ expect(res.status).toBe(200);+ expect(fake.calls[0]!.headers.get("x-adelie-key")).toBeNull();+ expect(JSON.parse(fake.calls[0]!.body)).toEqual({ title: "只有标题", detail: "" });+ });++ it("treats a reply without an id as a success, not a failure", async () => {+ stubFetch(() => new Response(null, { status: 204 }));+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ const res = await api.post("/api/feedback", { title: "空回执" });+ expect(res.status).toBe(200);+ expect((await res.json()) as FeedbackResponse).toEqual({ ok: true });+ });++ it("answers 502 when the backend refuses, without relaying its text", async () => {+ stubFetch(() =>+ jsonResponse({ ok: false, error: "口令不对(x-adelie-key 头或 ?key=)" }, 401),+ );+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ const res = await api.post("/api/feedback", { title: "会被拒" });+ expect(res.status).toBe(502);+ const error = errorOf(await res.json());+ expect(error.code).toBe("feedback_rejected");+ expect(error.message).toContain("401");+ expect(error.message).not.toContain("口令");+ });++ it("answers 502 when the backend cannot be reached", async () => {+ stubFetch(() => {+ throw new TypeError("fetch failed", {+ cause: Object.assign(new Error("ECONNREFUSED"), { code: "ECONNREFUSED" }),+ });+ });+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ const res = await api.post("/api/feedback", { title: "没人接" });+ expect(res.status).toBe(502);+ expect(errorOf(await res.json()).code).toBe("feedback_unreachable");+ });++ it("refuses a blank title before anything is sent", async () => {+ const fake = stubFetch(() => jsonResponse({ ok: true }));+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ for (const title of ["", " ", undefined]) {+ const res = await api.post("/api/feedback", { title, detail: "有正文" });+ expect(res.status).toBe(400);+ }+ expect(fake.calls).toHaveLength(0);+ });++ it("caps the title and the detail at the box's own limits", async () => {+ const fake = stubFetch(() => jsonResponse({ ok: true, item: { id: "req-9" } }, 201));+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ expect((await api.post("/api/feedback", { title: "x".repeat(201) })).status).toBe(400);+ expect(+ (await api.post("/api/feedback", { title: "长正文", detail: "y".repeat(20001) })).status,+ ).toBe(400);+ expect(fake.calls).toHaveLength(0);+ // The limits themselves are inclusive: exactly at the cap is accepted.+ expect(+ (await api.post("/api/feedback", { title: "x".repeat(200), detail: "y".repeat(20000) }))+ .status,+ ).toBe(200);+ expect(fake.calls).toHaveLength(1);+ });+ });++ it("needs a session", async () => {+ app = await createTestApp({ config: { feedbackUrl: BOX_URL, feedbackKey: BOX_KEY } });+ const res = await app.app.request("/api/feedback");+ expect(res.status).toBe(401);+ });+});diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.tsindex afc74827..9f937cfb 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -154,6 +154,10 @@ export function testConfig(root: string): ServerConfig {// No CLI to offer: nothing is written into the temp root, and no directory is put on// the PATH of whatever a test's Agent runs.cliEntry: null,+ // No feedback endpoint: the entry stays hidden, which is what an install without a box+ // shows. feedback.test.ts builds its own config for the configured cases.+ feedbackUrl: null,+ feedbackKey: null,};}diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex d9b31954..48ecf969 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -41,6 +41,8 @@ import type {DirDeleteResponse,DirListResponse,EndpointModelListResponse,+ FeedbackConfigResponse,+ FeedbackResponse,FilesStatResponse,GoalResponse,InstallResponse,@@ -2074,7 +2076,7 @@ router);// ----------------------------------------------------------------------------------------------// Version, self-update, desktop+// Version and self-update// ---------------------------------------------------------------------------------------------const idleJob: UpdateJobStatus = { state: "idle", targetVersion: null, output: "" };@@ -2095,7 +2097,31 @@ router.post("/api/version/restart", (): RestartResponse => ({restarting: false,reason: "no_supervisor",- }))+ }));++// ---------------------------------------------------------------------------------------------+// Feedback: the demo answers as an install that has a queue behind it, so the entry renders+// ---------------------------------------------------------------------------------------------++/** How many submissions the demo has accepted, so each one is answered with its own item id. */+let filedFeedback = 0;++router+ .get("/api/feedback", (): FeedbackConfigResponse => ({ ok: true, configured: true }))+ .post("/api/feedback", ({ body }): FeedbackResponse => {+ const title = str(record(body).title).trim();+ // The title is the one field the server's own route insists on; the demo refuses it here+ // rather than filing something the queue could not name.+ if (title === "") fail(400, "bad_request", "A title is required.");+ filedFeedback += 1;+ return { ok: true, id: `req-demo-${filedFeedback}` };+ });++// ---------------------------------------------------------------------------------------------+// Desktop client update (the shell's own; a browser-only gallery has none)+// ---------------------------------------------------------------------------------------------++router.get("/api/desktop/update", (): DesktopUpdateStatusResponse => ({ status: null })).post("/api/desktop/update/check", () => notFound("Desktop updater")).post("/api/desktop/update/download", () => notFound("Desktop updater"))diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 809997ad..3b269377 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -46,6 +46,9 @@ import type {DirListResponse,EndpointModelListRequest,EndpointModelListResponse,+ FeedbackConfigResponse,+ FeedbackRequest,+ FeedbackResponse,FeishuBindingPutRequest,FeishuBindingResponse,FeishuTestRequest,@@ -1947,6 +1950,15 @@ export const startUpdateJob = () =>export const restartServer = () =>apiFetch<RestartResponse>("/api/version/restart", { method: "POST", body: {} });+// Feedback (the sidebar's entry) --------------------------------------------------------++/** Whether this install has a feedback backend. The entry renders only where it does. */+export const getFeedbackConfig = () => apiFetch<FeedbackConfigResponse>("/api/feedback");++/** Files one submission; `id` names the item the backend created, when it reported one. */+export const sendFeedback = (body: FeedbackRequest) =>+ apiFetch<FeedbackResponse>("/api/feedback", { method: "POST", body });+// Desktop client update (desktop-shell sessions only) ----------------------------------export const getDesktopUpdate = () => apiFetch<DesktopUpdateStatusResponse>("/api/desktop/update");diff --git a/packages/web/src/components/account/feedback-dialog.tsx b/packages/web/src/components/account/feedback-dialog.tsxnew file mode 100644index 00000000..5d952850--- /dev/null+++ b/packages/web/src/components/account/feedback-dialog.tsx@@ -0,0 +1,159 @@+/**+ * The feedback entry in the account menu, and the dialog behind it.+ *+ * Two fields, and only one of them is required: a one-line title and an optional detail. That+ * pair is the shape the endpoint files (the requirements box's own `{title, detail}`), so+ * nothing is derived here — what the user types as the title is what the queue shows as the+ * item's name.+ *+ * Where the words go is the server's business (ADELIE_FEEDBACK_URL, see the server's feedback+ * route): the browser never learns the endpoint or its key, and the only state it needs is+ * whether there is one at all — {@link useFeedbackChannel} asks that once per menu mount. The+ * row is the caller's to place; the dialog belongs OUTSIDE the menu panel, which unmounts its+ * children the moment the menu closes (user-menu.tsx).+ *+ * `feedback_not_configured` can still come back if the operator turns the endpoint off while+ * the dialog is open, and its own sentence says so rather than blaming the network.+ */+import { useEffect, useState } from "react";+import { Button, Input, Modal, Textarea, toastSuccess } from "@lmliheng/penguin-ui";+import * as api from "../../api/endpoints";+import { ApiError } from "../../api/client";+import { S } from "../../lib/strings";++/**+ * Whether this install has a feedback channel, and the dialog's open state. Fails closed — an+ * unreadable answer leaves the row out rather than offering a submission that would land in a+ * 503 — and never re-asks: the endpoint is the operator's launch environment, which does not+ * change under a running server.+ */+export function useFeedbackChannel(): {+ configured: boolean;+ open: boolean;+ setOpen: (v: boolean) => void;+} {+ const [configured, setConfigured] = useState(false);+ const [open, setOpen] = useState(false);++ useEffect(() => {+ let alive = true;+ api+ .getFeedbackConfig()+ .then((res) => {+ if (alive) setConfigured(res.configured);+ })+ .catch(() => {+ if (alive) setConfigured(false);+ });+ return () => {+ alive = false;+ };+ }, []);++ return { configured, open, setOpen };+}++/**+ * What a failed submission says. One server code means the operator's switch, and it says so in+ * its own words rather than blaming the network; everything else is the same sentence, because+ * from here the user can act on none of them differently. A pure function because vitest runs+ * node-only (no click reaches a handler) and this is the whole of the dialog's error handling.+ */+export function feedbackErrorMessage(error: unknown): string {+ return error instanceof ApiError && error.code === "feedback_not_configured"+ ? S.feedback.notConfigured+ : S.feedback.sendFailed;+}++export function FeedbackDialog({ open, onClose }: { open: boolean; onClose: () => void }) {+ const [title, setTitle] = useState("");+ const [detail, setDetail] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ /** Closing clears the draft, so a re-open never shows the previous submission's text. */+ const close = () => {+ if (busy) return;+ setTitle("");+ setDetail("");+ setError(null);+ onClose();+ };++ const submit = async () => {+ const trimmed = title.trim();+ if (trimmed === "") {+ setError(S.feedback.titleRequired);+ return;+ }+ setBusy(true);+ try {+ const result = await api.sendFeedback({ title: trimmed, detail: detail.trim() });+ toastSuccess(result.id ? S.feedback.submittedWithId(result.id) : S.feedback.submitted);+ setTitle("");+ setDetail("");+ setError(null);+ onClose();+ } catch (e) {+ setError(feedbackErrorMessage(e));+ } finally {+ setBusy(false);+ }+ };++ return (+ <Modal+ open={open}+ title={S.feedback.title}+ onClose={close}+ footer={+ <>+ <Button size="sm" onClick={close} disabled={busy}>+ {S.common.cancel}+ </Button>+ <Button+ size="sm"+ variant="primary"+ disabled={busy || title.trim() === ""}+ onClick={() => void submit()}+ >+ {S.feedback.submit}+ </Button>+ </>+ }+ >+ <div className="space-y-3">+ <p className="text-sm text-gray-600 dark:text-gray-300">{S.feedback.intro}</p>+ <Input+ size="sm"+ label={S.feedback.titleLabel}+ placeholder={S.feedback.titlePlaceholder}+ value={title}+ // The one field this dialog insists on — the red "*" says so, not the label's words+ // (the detail beside it carries no mark, which is what makes it optional).+ required+ // The endpoint's own cap; refusing an over-long title here saves a round trip.+ maxLength={200}+ autoFocus+ error={error ?? undefined}+ onChange={(e) => {+ setTitle(e.target.value);+ if (error) setError(null);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" && title.trim() !== "" && !busy) void submit();+ }}+ />+ <Textarea+ size="sm"+ rows={5}+ label={S.feedback.detailLabel}+ placeholder={S.feedback.detailPlaceholder}+ value={detail}+ maxLength={20000}+ onChange={(e) => setDetail(e.target.value)}+ />+ </div>+ </Modal>+ );+}diff --git a/packages/web/src/components/layout/user-menu.tsx b/packages/web/src/components/layout/user-menu.tsxindex 49838fa5..ce8e27f7 100644--- a/packages/web/src/components/layout/user-menu.tsx+++ b/packages/web/src/components/layout/user-menu.tsx@@ -24,6 +24,7 @@ import { S } from "../../lib/strings";import { useAuth } from "../../state/auth";import { UpdateRow } from "../account/update-row";import { UserVaultDialog } from "../account/user-vault-dialog";+import { FeedbackDialog, useFeedbackChannel } from "../account/feedback-dialog";import { openUpdateModal } from "../../lib/use-update-flow";import { SettingsDialog } from "../../features/settings/settings-dialog";import { onSettingsRequest } from "../../features/settings/settings-request";@@ -59,6 +60,9 @@ export function UserMenu({/** The page a request asked for; the menu's own row asks for none (the viewer's first). */const [settingsSection, setSettingsSection] = useState<SettingsSectionKey | undefined>(undefined);const [confirmingLogout, setConfirmingLogout] = useState(false);+ /** The feedback row and its dialog; both live here because the row sits inside the panel and+ * the dialog must outlive it. */+ const feedback = useFeedbackChannel();// Settings can be asked for from outside this menu (see settings-request.ts): the request// opens the same dialog, on the page it names.@@ -139,6 +143,18 @@ export function UserMenu({navigate("/schedules");}}/>+ {/* Feedback, below the navigation rows: the one row here that files something for+ the operator rather than opening a page of this account's own. Left out entirely+ where the install has no endpoint — see the hook. */}+ {feedback.configured && (+ <MenuItem+ label={S.feedback.title}+ onSelect={() => {+ setOpen(false);+ feedback.setOpen(true);+ }}+ />+ )}{/* Update entry, under the two navigation rows rather than on a page inside thesettings dialog: one row for both backends (the server release here, theshell's own updater in the desktop window), naming where the update flow@@ -175,6 +191,8 @@ export function UserMenu({{/* The account's own secrets, mounted here like the settings dialog so it outlives themenu that opened it. */}<UserVaultDialog open={vaultOpen} onClose={() => setVaultOpen(false)} />+ {/* Feedback, likewise outside the panel: its row closes the menu as it opens this. */}+ <FeedbackDialog open={feedback.open} onClose={() => feedback.setOpen(false)} />{/* Signing out is confirmed first: the row sits in a menu of harmless entries, and aslip would end the session and land on the login page. Mounted beside the settingsdialog, outside the dropdown, so it outlives the menu that opened it. */}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 09625656..9184a673 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -946,6 +946,29 @@ export const en: Strings = {},},+ /**+ * The sidebar's feedback entry and the dialog behind it. The words are the user's own — the+ * dialog promises only where they go, which is the operator's queue, so a note left here is+ * read and acted on rather than merely archived.+ */+ feedback: {+ title: "Feedback",+ intro:+ "Say what you want changed, what went wrong, or anything else. It lands straight in this machine's feedback queue.",+ titleLabel: "One-line title",+ titlePlaceholder: "e.g. the sidebar text is too small",+ detailLabel: "Details",+ detailPlaceholder: "Where you were and what you expected helps — a paragraph is plenty.",+ submit: "Send",+ submitted: "Sent — thank you",+ submittedWithId: (id: string): string => `Sent (${id}) — thank you`,+ titleRequired: "A title is required",+ sendFailed: "Sending failed — try again in a moment",+ /** Shown when the server has nowhere to send to — names the switch, so the operator can act on it. */+ notConfigured:+ "This machine has no feedback endpoint configured (ADELIE_FEEDBACK_URL), so nothing can be sent from here yet.",+ },+admin: {users: "Users",roleAdmin: "Admin",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex f8d80d1d..cb89bc6b 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -996,6 +996,27 @@ export const zh = {},},+ /**+ * The sidebar's feedback entry and the dialog behind it. The words are the user's own — the+ * dialog promises only where they go, which is the operator's queue, so a note left here is+ * read and acted on rather than merely archived.+ */+ feedback: {+ title: "用户反馈",+ intro: "写下你想要的改动、遇到的问题,或者任何一句话。它会被直接收进这台机器的反馈队列。",+ titleLabel: "一句话标题",+ titlePlaceholder: "例如:侧栏的字太小",+ detailLabel: "详细说明",+ detailPlaceholder: "方便的话说清在哪一步、期望是什么——一段话就够。",+ submit: "提交",+ submitted: "已提交,谢谢",+ submittedWithId: (id: string): string => `已提交(${id}),谢谢`,+ titleRequired: "标题不能为空",+ sendFailed: "提交失败,请稍后再试",+ /** Shown when the server has nowhere to send to — names the switch, so the operator can act on it. */+ notConfigured: "这台机器还没配反馈后端(ADELIE_FEEDBACK_URL),所以这里暂时收不了。",+ },+admin: {users: "用户管理",roleAdmin: "管理员",diff --git a/packages/web/test/feedback-dialog.test.ts b/packages/web/test/feedback-dialog.test.tsnew file mode 100644index 00000000..3e22ba68--- /dev/null+++ b/packages/web/test/feedback-dialog.test.ts@@ -0,0 +1,121 @@+/**+ * The feedback entry's dialog (components/account/feedback-dialog.tsx), rendered to static+ * markup: vitest runs node-only here, so no click ever reaches a handler. What is checkable is+ * what the dialog offers — two fields, the title the only one it insists on, and the caps the+ * endpoint applies so an over-long title is refused here rather than at the far end — and the+ * one decision its failure path makes.+ *+ * The dialog hangs off the account menu (user-menu.tsx), which mounts it outside the panel: the+ * panel's children unmount the moment the menu closes, and the row closes the menu as it opens+ * this. A closed dialog therefore has to render nothing at all, which is the first case here.+ *+ * The Modal is a body portal, which the server renderer refuses and which node has no document+ * for: `createPortal` is mocked to render in place (the ui package's own tests do the same), and+ * `document`/`HTMLElement` stand in for the `document.activeElement` the dialog reads as it+ * renders. Effects never run here, so this is exactly the markup.+ */+import { createElement } from "react";+import type { ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ApiError } from "../src/api/client";+import { FeedbackDialog, feedbackErrorMessage } from "../src/components/account/feedback-dialog";+import { S, setActiveStrings, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++vi.mock("react-dom", async (importOriginal) => ({+ ...(await importOriginal<typeof import("react-dom")>()),+ createPortal: (node: ReactNode) => node,+}));++const noop = () => {};++const render = (open: boolean) =>+ renderToStaticMarkup(createElement(FeedbackDialog, { open, onClose: noop }));++beforeEach(() => {+ vi.stubGlobal("document", { body: {}, activeElement: null });+ vi.stubGlobal("HTMLElement", class {});+});++afterEach(() => {+ setActiveStrings(zh);+});++describe("FeedbackDialog", () => {+ it("draws nothing while it is closed, so the menu can mount it unconditionally", () => {+ expect(render(false)).toBe("");+ });++ it("asks for a title and an optional detail, in the interface's own words", () => {+ const html = render(true);+ expect(html).toContain(S.feedback.intro);+ expect(html).toContain(S.feedback.titleLabel);+ expect(html).toContain(S.feedback.titlePlaceholder);+ expect(html).toContain(S.feedback.detailLabel);+ expect(html).toContain(S.feedback.detailPlaceholder);+ expect(html).toContain(S.feedback.submit);+ expect(html).toContain(S.common.cancel);+ });++ it("marks the title field, and only it, as required", () => {+ const html = render(true);+ // The red "*" is the only thing that says a field is required (test/required-mark.test.ts) —+ // which is exactly why the detail's row carries no counterpart mark.+ expect(html.match(/text-tone-danger-fg/g)).toHaveLength(1);+ expect(html).toMatch(+ new RegExp(+ `${S.feedback.titleLabel}<span class="ml-0.5 text-tone-danger-fg"[^>]*>\\*</span>`,+ ),+ );+ });++ it("caps both fields at the endpoint's own limits, sparing the round trip", () => {+ const html = render(true);+ expect(html).toContain('maxLength="200"');+ expect(html).toContain('maxLength="20000"');+ });++ it("opens with Send unavailable: an empty title is the one thing the endpoint refuses", () => {+ const html = render(true);+ // The disabled attribute itself, not the `disabled:` variant every Button's classes spell out+ // whether it is disabled or not.+ const button = (label: string) =>+ [...html.matchAll(/<button\b[^>]*>[^<]*<\/button>/g)]+ .map((m) => m[0])+ .find((b) => b.endsWith(`>${label}</button>`)) ?? "";+ expect(button(S.feedback.submit)).toContain('disabled=""');+ // Cancel stays available — a dialog that traps a user with nothing to send is worse.+ expect(button(S.common.cancel)).not.toContain('disabled=""');+ });++ it("speaks English when the interface does", () => {+ setActiveStrings(en);+ const html = render(true);+ expect(html).toContain(en.feedback.titleLabel);+ expect(html).toContain(en.feedback.submit);+ expect(html).not.toContain(zh.feedback.titleLabel);+ expect(html).not.toContain(zh.feedback.submit);+ });+});++describe("feedbackErrorMessage", () => {+ it("names the operator's switch when that is what the server answered", () => {+ // The one code the dialog treats differently: the endpoint was turned off under an open+ // dialog, which is the operator's doing and not a network the user could retry.+ expect(feedbackErrorMessage(new ApiError(503, "feedback_not_configured", "nope"))).toBe(+ S.feedback.notConfigured,+ );+ });++ it("gives every other failure the same retryable sentence", () => {+ expect(feedbackErrorMessage(new ApiError(502, "feedback_rejected", "nope"))).toBe(+ S.feedback.sendFailed,+ );+ expect(feedbackErrorMessage(new ApiError(400, "bad_request", "nope"))).toBe(+ S.feedback.sendFailed,+ );+ // Not even an ApiError — a thrown string must not reach the user as one.+ expect(feedbackErrorMessage("boom")).toBe(S.feedback.sendFailed);+ });+});