From 7d71565f133f3a1a513d6958896bd7496c39e6c4 Mon Sep 17 00:00:00 2001 From: stevenjj33 <75509501+stevenjj33@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:08:04 +0800 Subject: [PATCH 1/2] feat(webui): the user menu can stop the local server The user menu gets a item that asks first and then asks the service to stop. The service owns its listener, not the process, so the route is a request: it answers and then asks the host to stop. A host with no such answer refuses the route instead of pretending, and the credential is required even on loopback because ending the process is not a privilege the ordinary routes hand out. --- .../src/client/bindings/use-webui-shutdown.ts | 17 +++++ .../client/features/account/ui/UserMenu.tsx | 76 +++++++++++++++++++ .../src/client/platform/webui-shutdown.ts | 53 +++++++++++++ packages/webui/src/server/http/router.ts | 24 ++++++ packages/webui/src/server/http/shutdown.ts | 57 ++++++++++++++ packages/webui/src/server/service.ts | 11 +++ .../test/browser/user-menu-shutdown.spec.mjs | 31 ++++++++ release/webui-npm/bin/mcode-webui.mjs | 3 + 8 files changed, 272 insertions(+) create mode 100644 packages/webui/src/client/bindings/use-webui-shutdown.ts create mode 100644 packages/webui/src/client/platform/webui-shutdown.ts create mode 100644 packages/webui/src/server/http/shutdown.ts create mode 100644 packages/webui/test/browser/user-menu-shutdown.spec.mjs diff --git a/packages/webui/src/client/bindings/use-webui-shutdown.ts b/packages/webui/src/client/bindings/use-webui-shutdown.ts new file mode 100644 index 000000000..ed8fef5a8 --- /dev/null +++ b/packages/webui/src/client/bindings/use-webui-shutdown.ts @@ -0,0 +1,17 @@ +// The React edge to the shutdown request. +// +// The request itself -- posting it to the service that served this page -- is +// browser IO and lives in `client/platform/webui-shutdown.ts`. A feature's +// presentation does not call an IO port, so this binding is the door between +// the two: the menu asks it to stop, and it asks the platform. +// +// Nothing here decides whether the person meant it. The confirmation that +// precedes the request lives with the menu that offers it. + +import { useCallback } from "react"; + +import { requestWebuiShutdown } from "../platform/webui-shutdown.js"; + +export function useWebuiShutdown(): () => Promise { + return useCallback(() => requestWebuiShutdown(), []); +} diff --git a/packages/webui/src/client/features/account/ui/UserMenu.tsx b/packages/webui/src/client/features/account/ui/UserMenu.tsx index 3c55614a1..4a5a0a873 100644 --- a/packages/webui/src/client/features/account/ui/UserMenu.tsx +++ b/packages/webui/src/client/features/account/ui/UserMenu.tsx @@ -26,6 +26,7 @@ import { createPortal } from "react-dom"; import { IconCalendarEvent, IconChevronRight, + IconPower, IconSettings, IconUserCircle, } from "@tabler/icons-react"; @@ -38,6 +39,8 @@ import type { WebuiVersionInfo } from "../../../../shared/contracts/version.js"; import { WebuiDropdown } from "../../../ui/Dropdown.js"; import { WebuiMenuItem, WebuiMenuSeparator } from "../../../ui/menu-item.js"; import { WebuiButton, WebuiIconButton } from "../../../ui/button.js"; +import { WebuiDialog } from "../../../ui/dialog.js"; +import { useWebuiShutdown } from "../../../bindings/use-webui-shutdown.js"; import { FeedbackSkeleton } from "../../../ui/feedback.js"; import { WebuiMotionSlot, WebuiPage } from "../../../ui/page.js"; import { useWebuiBrowserCapabilities } from "../../../bindings/browser-capabilities.js"; @@ -160,6 +163,7 @@ export function UserMenu({ onCreateMemorySession, }: UserMenuProps): ReactElement { const { dom } = useWebuiBrowserCapabilities(); + const shutdown = useWebuiShutdown(); // The account, usage, check-in and login answers all come from the one // application owner. This component submits commands and reads the snapshot; // it holds no transport method for them. @@ -181,6 +185,27 @@ export function UserMenu({ const [loginOpen, setLoginOpen] = useState(false); const [usageOpen, setUsageOpen] = useState(false); const [signinOpen, setSigninOpen] = useState(false); + // The shutdown request belongs to the menu that offers it: the item opens + // the confirmation, and the confirmation is what asks the server to stop. + const [shutdownOpen, setShutdownOpen] = useState(false); + const [shutdownBusy, setShutdownBusy] = useState(false); + const [shutdownError, setShutdownError] = useState( + undefined, + ); + const confirmShutdown = useCallback(async () => { + setShutdownBusy(true); + setShutdownError(undefined); + try { + await shutdown(); + // The service answers before it stops, so the page is still alive here; + // the connection drop is what tells the person the server is gone. + setShutdownOpen(false); + } catch (error: unknown) { + setShutdownError(error instanceof Error ? error.message : String(error)); + } finally { + setShutdownBusy(false); + } + }, [shutdown]); const panelCloseTimer = useRef | undefined>( undefined, ); @@ -517,9 +542,60 @@ export function UserMenu({ }} /> + + + { + if (!shutdownBusy) setShutdownOpen(false); + }} + footer={ + <> + setShutdownOpen(false)} + > + 取消 + + { + void confirmShutdown(); + }} + > + 关闭服务 + + + } + > + {shutdownError ? ( +

{shutdownError}

+ ) : null} +
{ + // Presence is checked, not truthiness: an injected empty token is a valid + // dev target, and falling back to the global for it would silently ignore + // the caller's origin. + const target = + options.origin !== undefined && options.token !== undefined + ? { origin: options.origin, token: options.token } + : readWebuiSessionTransferTarget(); + if (!target) { + throw new WebuiShutdownRefused("当前 WebUI 未连接运行时,无法关闭服务。"); + } + + const query = new URLSearchParams({ token: target.token }); + const doFetch = options.fetchImpl ?? globalThis.fetch; + const response = await doFetch( + `${target.origin}/webui-shutdown?${query.toString()}`, + { method: "POST" }, + ); + if (!response.ok) { + throw new WebuiShutdownRefused( + response.status === 404 + ? "当前 WebUI 不支持关闭服务。" + : `关闭服务失败(HTTP ${response.status})。`, + ); + } +} diff --git a/packages/webui/src/server/http/router.ts b/packages/webui/src/server/http/router.ts index 5a6c19489..08a2f694b 100644 --- a/packages/webui/src/server/http/router.ts +++ b/packages/webui/src/server/http/router.ts @@ -18,6 +18,7 @@ import { rejectHttp, parseHttpUrl } from "./responses.js"; import { serveClientAsset } from "./client-assets.js"; import { serveBrowserExtensionPackage } from "./browser-extension.js"; import { handleSessionTransfer, handleSessionImport } from "./session-transfer.js"; +import { handleWebuiShutdown } from "./shutdown.js"; import { serveWorkspaceFile } from "./workspace-file.js"; import type { WebuiHarnessPort } from "../../runtime/port.js"; import type { WebuiBrowserExtensionPackage } from "../browser-bridge/extension-package.js"; @@ -40,6 +41,15 @@ export interface WebuiHttpRouterContext { */ readonly browserExtensionPackage?: WebuiBrowserExtensionPackage; readonly port: WebuiHarnessPort; + /** + * The host's answer to a request to stop the server. + * + * The service owns its listener, not the process: the host that assembled + * it does. Absent when the host has no such answer -- the service embedded + * in an application that outlives it -- and the shutdown route then refuses + * rather than stopping something nobody offered to stop. + */ + readonly requestShutdown?: () => void; } export async function serveHttpRequest( @@ -87,6 +97,20 @@ export async function serveHttpRequest( await handleSessionImport(request, url, response, context.port); return; } + // The page's own request to stop the server. It sits after the loopback, + // origin and credential checks so it inherits them, and it asks the credential + // again: stopping the process is not a privilege the ordinary routes hand + // out on loopback. + if (request.method === "POST" && url.pathname === "/webui-shutdown") { + handleWebuiShutdown(request, response, url, { + credential: context.credential, + fullAccess: context.fullAccess === true, + ...(context.requestShutdown + ? { requestShutdown: context.requestShutdown } + : {}), + }); + return; + } // Ahead of the GET-only gate below because this route also answers HEAD: // `serveWorkspaceFile` reports the byte range and content length with no // body. It sits after the loopback, origin and credential checks, so it diff --git a/packages/webui/src/server/http/shutdown.ts b/packages/webui/src/server/http/shutdown.ts new file mode 100644 index 000000000..9de9d6e6f --- /dev/null +++ b/packages/webui/src/server/http/shutdown.ts @@ -0,0 +1,57 @@ +// The shutdown route: the page's own request to stop the local server. +// +// The service owns the HTTP listener but not the process: the host that +// assembled it does. This route is therefore a *request*, not an action. It +// answers, and then asks the host to stop. A host that has no such answer -- +// the service embedded in the desktop app, whose process is not the server's +// to end -- refuses the route instead of pretending. +// +// The credential is required even where the loopback interface would not +// normally ask for one. This route ends the process, and "any local process +// can stop the server" is not a privilege the ordinary routes hand out. + +import type { IncomingMessage, ServerResponse } from "node:http"; + +import { credentialPresented, type WebuiCredential } from "../credentials.js"; +import { rejectHttp } from "./responses.js"; + +export interface WebuiShutdownRouteOptions { + readonly credential: WebuiCredential; + /** Full access is the explicit "no credential" mode; it applies here too. */ + readonly fullAccess: boolean; + /** + * The host's answer to "stop now". + * + * Absent when the host has none, and the route then says it has none rather + * than stopping something the host did not offer to stop. + */ + readonly requestShutdown?: () => void; +} + +export function handleWebuiShutdown( + request: IncomingMessage, + response: ServerResponse, + url: URL, + options: WebuiShutdownRouteOptions, +): void { + if (!options.requestShutdown) { + rejectHttp(response, 404, "Not Found"); + return; + } + if ( + !options.fullAccess && + !credentialPresented( + options.credential, + url.searchParams.get("token"), + request.headers.cookie, + ) + ) { + rejectHttp(response, 401, "Unauthorized"); + return; + } + // The answer goes out before the host stops: a request refused by a closed + // listener looks like a crash to the page that asked. + response.end(JSON.stringify({ ok: true, closing: true }), () => { + setTimeout(() => options.requestShutdown?.(), 100); + }); +} diff --git a/packages/webui/src/server/service.ts b/packages/webui/src/server/service.ts index f8335f772..72f7c5af3 100644 --- a/packages/webui/src/server/service.ts +++ b/packages/webui/src/server/service.ts @@ -144,6 +144,14 @@ export interface WebuiServiceOptions { readonly credential?: WebuiCredential; /** Explicitly allow all WebUI HTTP and WebSocket requests without a token. */ readonly fullAccess?: boolean; + /** + * The host's answer to a request to stop the service. + * + * The service owns its listener, not the process: the host that assembled + * it does, so the host hands this answer down and the shutdown route asks + * it. Absent when the host has none. + */ + readonly requestShutdown?: () => void; /** Optional server factory; tests inject an HTTP server without listening. */ readonly httpServerFactory?: () => Server; /** @@ -281,6 +289,9 @@ export class WebuiService { ...(this.browserExtensionPackage ? { browserExtensionPackage: this.browserExtensionPackage } : {}), + ...(options.requestShutdown + ? { requestShutdown: options.requestShutdown } + : {}), port: this.port, }; this.httpServer.on("upgrade", this.wsServer.handleUpgrade); diff --git a/packages/webui/test/browser/user-menu-shutdown.spec.mjs b/packages/webui/test/browser/user-menu-shutdown.spec.mjs new file mode 100644 index 000000000..4b736e0a0 --- /dev/null +++ b/packages/webui/test/browser/user-menu-shutdown.spec.mjs @@ -0,0 +1,31 @@ +// The user menu's shutdown request, end to end against the built client. +// +// Stopping the server is the one action the page cannot take back, so the +// item asks first: the confirmation is what the person answers, and the +// request is what the answer asks for. +// +// The spec stops at the confirmation. The request itself ends the server the +// suite runs against, so a spec that confirmed it would take the suite down +// with it. + +import { expect } from "@playwright/test"; + +import { openApp, test } from "./harness.mjs"; + +test("the user menu asks before it stops the server", async ({ page }) => { + await openApp(page); + + // The rail has two triggers for the same menu: the expanded row and the + // collapsed icon. Which one is rendered is the viewport's business, so the + // spec takes whichever is there. + await page + .locator( + '[data-testid="sidebar-user-menu-trigger"], [data-testid="sidebar-user-menu-trigger-rail"]', + ) + .first() + .click(); + await page.locator('[data-testid="user-menu-shutdown"]').click(); + + await expect(page.getByRole("alertdialog")).toBeVisible(); + await expect(page.getByText("关闭本地 WebUI 服务")).toBeVisible(); +}); diff --git a/release/webui-npm/bin/mcode-webui.mjs b/release/webui-npm/bin/mcode-webui.mjs index c47c1543f..66a43b6af 100644 --- a/release/webui-npm/bin/mcode-webui.mjs +++ b/release/webui-npm/bin/mcode-webui.mjs @@ -281,6 +281,9 @@ const service = new WebuiService({ }), // Closed on shutdown: a leaked Mini App listener holds a plugin's derived port. miniappProxies, + // The page's own request to stop. The launcher owns the process, so the + // service asks it and the launcher ends the run the way Ctrl+C does. + requestShutdown: () => void close().finally(() => process.exit(0)), }); let closing; From 183203bbe70e87e71042a03fe68d6c55d85ae1bb Mon Sep 17 00:00:00 2001 From: stevenjj33 <75509501+stevenjj33@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:13:34 +0800 Subject: [PATCH 2/2] test(webui): record the shutdown paths in the frozen inventories The shutdown feature adds three source paths and changes the account menu's rendered vocabulary, so the frozen path metadata, the presentation coverage review and the public source inventory all have to say so before the gates accept the change. --- .../gates/fixtures/path-metadata-f00.json | 23 ++++++++++++++++++- release/public-source.json | 4 ++++ scripts/lib/webui-presentation-inventory.json | 2 +- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/webui/test/gates/fixtures/path-metadata-f00.json b/packages/webui/test/gates/fixtures/path-metadata-f00.json index ed872a53c..ccdd42bc2 100644 --- a/packages/webui/test/gates/fixtures/path-metadata-f00.json +++ b/packages/webui/test/gates/fixtures/path-metadata-f00.json @@ -1,7 +1,7 @@ { "baseline": "f00b1268c28ad15054a8882620c3fb08beb86d58", "sourceSha256": "46b86b658adc1611f3531d8dc9844612f7e9ee3de0eec4a532aeec44b5de0a12", - "declaredDelta": "Public marker preserves the original layer and adds only the published- role prefix; publication legality has separate positive/negative fixtures. Post-baseline additions: conversation/pagination remains a mechanism, platform/transport-origin remains infrastructure, and runtime/ssh/authentication remains outside the client.", + "declaredDelta": "Public marker preserves the original layer and adds only the published- role prefix; publication legality has separate positive/negative fixtures. Post-baseline additions: conversation/pagination remains a mechanism, platform/transport-origin remains infrastructure, runtime/ssh/authentication remains outside the client, bindings/use-webui-shutdown remains a binding, platform/webui-shutdown remains infrastructure, and server/http/shutdown remains outside the client.", "cases": [ { "path": "runtime/native-pty.ts", @@ -6375,6 +6375,27 @@ "role": "outside", "business": null, "home": "outside" + }, + { + "path": "client/bindings/use-webui-shutdown.ts", + "layers": ["bindings"], + "role": "bindings", + "business": null, + "home": "current" + }, + { + "path": "client/platform/webui-shutdown.ts", + "layers": ["infrastructure"], + "role": "platform", + "business": null, + "home": "target" + }, + { + "path": "server/http/shutdown.ts", + "layers": ["server"], + "role": "outside", + "business": null, + "home": "outside" } ], "directions": [ diff --git a/release/public-source.json b/release/public-source.json index 7e9473fff..7ee2f527d 100644 --- a/release/public-source.json +++ b/release/public-source.json @@ -3986,6 +3986,7 @@ "packages/webui/src/client/bindings/use-connection-health.ts", "packages/webui/src/client/bindings/use-query-state.tsx", "packages/webui/src/client/bindings/use-session-state.ts", + "packages/webui/src/client/bindings/use-webui-shutdown.ts", "packages/webui/src/client/client.js", "packages/webui/src/client/contracts/browser-drawing.ts", "packages/webui/src/client/contracts/transport.ts", @@ -4362,6 +4363,7 @@ "packages/webui/src/client/platform/team-mode.ts", "packages/webui/src/client/platform/transport-origin.ts", "packages/webui/src/client/platform/transport.ts", + "packages/webui/src/client/platform/webui-shutdown.ts", "packages/webui/src/client/platform/wire.ts", "packages/webui/src/client/projection/common/context-menu.ts", "packages/webui/src/client/projection/common/diff-workspace-boundary.ts", @@ -4552,6 +4554,7 @@ "packages/webui/src/server/http/responses.ts", "packages/webui/src/server/http/router.ts", "packages/webui/src/server/http/session-transfer.ts", + "packages/webui/src/server/http/shutdown.ts", "packages/webui/src/server/http/workspace-file.ts", "packages/webui/src/server/index.ts", "packages/webui/src/server/miniapp/agent-connections.ts", @@ -4774,6 +4777,7 @@ "packages/webui/test/browser/transcript-scroll.spec.mjs", "packages/webui/test/browser/transcript.spec.mjs", "packages/webui/test/browser/turn-lifecycle.spec.mjs", + "packages/webui/test/browser/user-menu-shutdown.spec.mjs", "packages/webui/test/browser/visual-baselines.spec.mjs", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-linux.png", diff --git a/scripts/lib/webui-presentation-inventory.json b/scripts/lib/webui-presentation-inventory.json index d78690b27..cc996de00 100644 --- a/scripts/lib/webui-presentation-inventory.json +++ b/scripts/lib/webui-presentation-inventory.json @@ -158,7 +158,7 @@ "reviewed": { "features/account/ui/AccountLoginPage.tsx": "37ae4e50a0f4dedb", "features/account/ui/ConversationUsageBanner.tsx": "c0403acfd2a1f12b", - "features/account/ui/UserMenu.tsx": "91d80e3c5a9609cc", + "features/account/ui/UserMenu.tsx": "31a3050c8cb1ca4f", "features/account/ui/UserMenuSignin.tsx": "640554aea4a84be7", "features/account/ui/UserMenuUsage.tsx": "6afecd2411c833bb", "features/browser/ui/BrowserAuthorizationSwitches.public.tsx": "8999c432c97c210c",