Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/webui/src/client/bindings/use-webui-shutdown.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
return useCallback(() => requestWebuiShutdown(), []);
}
76 changes: 76 additions & 0 deletions packages/webui/src/client/features/account/ui/UserMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { createPortal } from "react-dom";
import {
IconCalendarEvent,
IconChevronRight,
IconPower,
IconSettings,
IconUserCircle,
} from "@tabler/icons-react";
Expand All @@ -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";
Expand Down Expand Up @@ -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.
Expand All @@ -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<string | undefined>(
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<ReturnType<typeof setTimeout> | undefined>(
undefined,
);
Expand Down Expand Up @@ -517,9 +542,60 @@ export function UserMenu({
}}
/>
</div>
<WebuiMenuSeparator />
<WebuiMenuItem
className="webui-user-menu-item"
icon={<IconPower aria-hidden="true" size={18} stroke={1.7} />}
data-testid="user-menu-shutdown"
onClick={() => {
setOpen(false);
setShutdownOpen(true);
}}
>
关闭本地服务
</WebuiMenuItem>
</div>
</WebuiDropdown>
</div>
<WebuiDialog
id="webui-shutdown-dialog"
open={shutdownOpen}
role="alertdialog"
title="关闭本地 WebUI 服务"
description="关闭后这个页面会断开连接,需要重新启动服务才能继续使用。"
dismissOnEscape
width="compact"
portalTarget={portalTarget}
onClose={() => {
if (!shutdownBusy) setShutdownOpen(false);
}}
footer={
<>
<WebuiButton
variant="secondary"
size="dialog"
disabled={shutdownBusy}
onClick={() => setShutdownOpen(false)}
>
取消
</WebuiButton>
<WebuiButton
variant="primary"
size="dialog"
disabled={shutdownBusy}
onClick={() => {
void confirmShutdown();
}}
>
关闭服务
</WebuiButton>
</>
}
>
{shutdownError ? (
<p className="text-sm text-text_default_tertiary">{shutdownError}</p>
) : null}
</WebuiDialog>
<AccountLoginPage
open={loginOpen}
mode="sign-in"
Expand Down
53 changes: 53 additions & 0 deletions packages/webui/src/client/platform/webui-shutdown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Asking the local WebUI server to stop.
//
// Responsibility: this is **browser infrastructure IO**. It posts the request
// the shutdown route answers and reports what the server said; it decides
// nothing about the user's intent -- the confirmation that precedes it lives
// with the menu that offers it.
//
// The origin and the token are the ones the transfer routes use: both are
// served by the same listener the socket was opened against, so the answer is
// read from the injected runtime config rather than restated here.

import { readWebuiSessionTransferTarget } from "./session-transfer-target.js";

export interface WebuiShutdownOptions {
/** Injected in tests; defaults to the global fetch. */
readonly fetchImpl?: typeof fetch;
readonly origin?: string;
readonly token?: string;
}

/** The server refused the request, or the server could not be reached. */
export class WebuiShutdownRefused extends Error {
override readonly name = "WebuiShutdownRefused";
}

export async function requestWebuiShutdown(
options: WebuiShutdownOptions = {},
): Promise<void> {
// 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})。`,
);
}
}
24 changes: 24 additions & 0 deletions packages/webui/src/server/http/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand Down
57 changes: 57 additions & 0 deletions packages/webui/src/server/http/shutdown.ts
Original file line number Diff line number Diff line change
@@ -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);
});
}
11 changes: 11 additions & 0 deletions packages/webui/src/server/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
/**
Expand Down Expand Up @@ -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);
Expand Down
31 changes: 31 additions & 0 deletions packages/webui/test/browser/user-menu-shutdown.spec.mjs
Original file line number Diff line number Diff line change
@@ -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();
});
23 changes: 22 additions & 1 deletion packages/webui/test/gates/fixtures/path-metadata-f00.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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": [
Expand Down
Loading
Loading