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
Original file line number Diff line number Diff line change
Expand Up @@ -330,8 +330,10 @@ A failed start leaves an actionable “not opened” state in the mounted view,
attempt's error toast. Dismissing the toast does not remove the state or its explicit retry
control. Only an `OWNED_ELSEWHERE` refusal tells the user to close the other client's app;
a generic preparation failure does not establish ownership. Retry uses the normal open
operation, never a takeover, and polling does not restart a failed presentation. Stop or
lease failures do not create this failed-start state.
operation, never a takeover, and polling does not restart a failed presentation. If
another tab holds the presentation lease, the failed inline view only reads until the
lease releases, then reveals the retry control. Stop or lease failures do not create
this failed-start state.


### The standalone presentation is a lease
Expand Down
2 changes: 1 addition & 1 deletion packages/webui/docs/runtime/boot.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ session transfer · the terminal process manager (one per service) · the six sl

| Entry | Path | Notes |
| --- | --- | --- |
| Development server | `scripts/run-webui-server.mjs` via `pnpm --filter @mavis/webui dev:server` | Spawns itself under `tsx` with the repository's `tsconfig.standalone.json`; assembles the host, constructs `new WebuiService(...)` with the registry and the terminal manager, calls `service.start()`, and closes the service on SIGINT/SIGTERM or an authenticated `POST /webui-shutdown`. The HTTP route acknowledges the request before the same bounded process cleanup starts. Serves the built client from `dist-webui/client/`. `WEBUI_SERVER_PORT` overrides 2233. `WEBUI_HOST` overrides the bind address (`127.0.0.1` by default); a wider bind prints the LAN URLs and the per-start credential, and a request that did not arrive over loopback presents that credential (ADR 0031). |
| Development server | `scripts/run-webui-server.mjs` via `pnpm --filter @mavis/webui dev:server` | Spawns itself under `tsx` with the repository's `tsconfig.standalone.json`; assembles the host, constructs `new WebuiService(...)` with the registry and the terminal manager, calls `service.start()`, and closes the service on SIGINT/SIGTERM or an authenticated `POST /webui-shutdown`. The HTTP route acknowledges the request before the same bounded process cleanup starts. The menu treats only the route's affirmative receipt as acceptance; a missing or invalid reply leaves the outcome unconfirmed and offers a manual retry. The browser's receipt timeout does not cancel server cleanup. Serves the built client from `dist-webui/client/`. `WEBUI_SERVER_PORT` overrides 2233. `WEBUI_HOST` overrides the bind address (`127.0.0.1` by default); a wider bind prints the LAN URLs and the per-start credential, and a request that did not arrive over loopback presents that credential (ADR 0031). |
| Packaged service | `runtime/index.ts` + `server/index.ts` | The runtime's public entry and the server build entry. `scripts/build-webui.mjs` bundles both. |
| npm preview package | `release/webui-npm/` | See [`../releasing.md`](../releasing.md). |

Expand Down
56 changes: 26 additions & 30 deletions packages/webui/src/client/bindings/use-webui-shutdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,42 +10,38 @@

import { useCallback } from "react";

import {
requestWebuiShutdown,
WebuiShutdownRefused,
} from "../platform/webui-shutdown.js";
import { requestWebuiShutdown } from "../platform/webui-shutdown.js";

/**
* What the shutdown request found, in the terms the confirmation can show.
*
* `stopped` is the state the request was after: the service is not running,
* whether it said so or simply stopped answering. `failed` carries a
* message the person can act on -- never the browser's own wording, which
* describes the network rather than what happened here.
*/
export type WebuiShutdownOutcome =
| { readonly kind: "stopped" }
| { readonly kind: "failed"; readonly message: string };
type WebuiShutdownOutcome =
| { readonly kind: "accepted" }
| { readonly kind: "unconfirmed" | "refused"; readonly message: string };

const unconfirmed: WebuiShutdownOutcome = {
kind: "unconfirmed",
message: "未收到关闭确认,无法确定服务是否已停止。你可以关闭此提示,或手动重试。",
};

export function useWebuiShutdown(): () => Promise<WebuiShutdownOutcome> {
return useCallback(async (): Promise<WebuiShutdownOutcome> => {
try {
const state = await requestWebuiShutdown();
if (state === "still-running") {
return {
kind: "failed",
message: "关闭服务失败:本地服务仍在运行,请重试。",
};
}
return { kind: "stopped" };
} catch (error: unknown) {
if (error instanceof WebuiShutdownRefused) {
return { kind: "failed", message: error.message };
const receipt = await requestWebuiShutdown();
switch (receipt.kind) {
case "accepted":
return { kind: "accepted" };
case "not-connected":
return { kind: "refused", message: "当前 WebUI 未连接运行时,无法关闭服务。" };
case "refused":
return {
kind: "refused",
message: receipt.status === 404
? "当前 WebUI 不支持关闭服务。"
: `关闭服务失败(HTTP ${receipt.status})。`,
};
case "unknown":
return unconfirmed;
}
// An error the platform did not name is a defect rather than an
// answer, and its wording is not something to put in front of a
// person: they are told the request did not go through.
return { kind: "failed", message: "关闭服务失败,请重试。" };
} catch {
return unconfirmed;
}
}, []);
}
10 changes: 4 additions & 6 deletions packages/webui/src/client/features/account/ui/UserMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,12 @@ export function UserMenu({
setShutdownError(undefined);
try {
const outcome = await shutdown();
if (outcome.kind === "stopped") {
// The service is not running. It says so before it stops, and it
// says nothing at all when it was already down -- both leave the
// page here without a backend, which is what was asked for.
if (outcome.kind === "accepted") {
// The host accepted the request, not necessarily stopped already.
setShutdownOpen(false);
return;
} else {
setShutdownError(outcome.message);
}
setShutdownError(outcome.message);
} finally {
setShutdownBusy(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,9 @@ export function createWebuiMiniAppWorkflows(deps: {
await loadListing(true);
if (!isCurrent()) return false;
setRefusal(pluginId, refusal);
// An explicit retry does not run inside the observer. Restart the
// read-only clock if this fresh catalogue reported a detached lease.
scheduleObservation();
return false;
} finally {
if (currentOperation(pluginId, revision) && !isInterested() && state.presentations[pluginId]?.kind === "opening")
Expand Down Expand Up @@ -1251,9 +1254,14 @@ export function createWebuiMiniAppWorkflows(deps: {
});

// One clock for interested readers. A slow read never overlaps the next tick.
const needsClock = (): boolean => [...presentationInterests.keys()].some((pluginId) => {
const needsClock = (): boolean => [...presentationInterests].some(([pluginId, interest]) => {
const presentation = state.presentations[pluginId];
return presentation?.kind === "open" ||
// A failed inline start can race with another document taking the lease.
// Keep reading while that document owns the view so its departure can
// reveal the manual retry. The observer never opens a failed presentation.
const waitingForDetachedLease = presentation?.kind === "failed" && !interest.standalone &&
state.listing.rows.some((row) => row.pluginId === pluginId && row.detached);
return presentation?.kind === "open" || waitingForDetachedLease ||
(presentation === undefined && state.refusals[pluginId] === undefined);
}) ||
[...listingInterests.values()].some((kind) => kind === "launcher");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ export function MiniAppView({
* so reporting itself as "open elsewhere" would be the one wrong answer.
*/
const detached = !standalone && row?.detached === true;
/* The app that stopped and the start that was refused are events, not
* states: each is said once, and the view keeps the surface it has. */
/* The toasts report individual operations. A failed start separately
* keeps an explicit recovery action in the view. */
useWebuiToastError(
presentation?.kind === "stopped" && !detached ? presentation.reason : undefined,
{ testId: "miniapp-view-stopped" },
Expand Down
96 changes: 36 additions & 60 deletions packages/webui/src/client/platform/webui-shutdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,84 +18,60 @@ export interface WebuiShutdownOptions {
readonly token?: string;
}

/**
* What the request found.
*
* - `stopping` -- the service took the request and is on its way down.
* - `gone` -- nothing is listening any more: the service is not running.
* - `still-running` -- the request got no answer, but the service is still
* there and still answering.
*
* The last two are the same question asked twice. Asking a service that is
* already down to stop is not a failure, and a request that never reached a
* service that is still up is not a success either; which of the two happened
* is what the person needs to be told.
*/
export type WebuiShutdownState = "stopping" | "gone" | "still-running";
export type WebuiShutdownReceipt =
| { readonly kind: "accepted" }
| { readonly kind: "refused"; readonly status: number }
| { readonly kind: "not-connected" }
| { readonly kind: "unknown" };

/** The server answered, and it refused. */
export class WebuiShutdownRefused extends Error {
override readonly name = "WebuiShutdownRefused";
}
// This bounds how long the confirmation stays busy, not how long the
// server may take to stop. Aborting cannot revoke an already sent request.
const SHUTDOWN_RECEIPT_TIMEOUT_MS = 5_000;

export async function requestWebuiShutdown(
options: WebuiShutdownOptions = {},
): Promise<WebuiShutdownState> {
): Promise<WebuiShutdownReceipt> {
// 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 未连接运行时,无法关闭服务。");
}
if (!target) return { kind: "not-connected" };

const query = new URLSearchParams({ token: target.token });
const doFetch = options.fetchImpl ?? globalThis.fetch;
let response: Response;
try {
response = await doFetch(
const response = await doFetch(
`${target.origin}/webui-shutdown?${query.toString()}`,
{ method: "POST" },
);
} catch {
// The request got no answer. That is what a service that is already
// down looks like, and it is also what a service that went down before
// its answer arrived looks like: the answer and the teardown race, and
// a browser that reads the answer late loses that race. A second
// question settles which of the two it was -- the listener that is
// still there answers, the one that is gone does not.
return (await isListening(target.origin, doFetch))
? "still-running"
: "gone";
}
if (!response.ok) {
throw new WebuiShutdownRefused(
response.status === 404
? "当前 WebUI 不支持关闭服务。"
: `关闭服务失败(HTTP ${response.status})。`,
{
method: "POST",
redirect: "error",
signal: AbortSignal.timeout(SHUTDOWN_RECEIPT_TIMEOUT_MS),
},
);
}
return "stopping";
}
if (!response.ok) {
// A gateway failure or timeout can happen after the origin received
// the POST. Only an explicit client rejection is definitive.
return response.status >= 400 && response.status < 500 && response.status !== 408
? { kind: "refused", status: response.status }
: { kind: "unknown" };
}

/**
* Whether the service still answers on that address.
*
* Any HTTP answer counts, including a refusal: the question is whether the
* listener is there, and a listener that refuses is still a listener. A HEAD
* keeps the answer empty.
*/
async function isListening(
origin: string,
doFetch: typeof fetch,
): Promise<boolean> {
try {
await doFetch(`${origin}/`, { method: "HEAD", cache: "no-store" });
return true;
// A proxy or stale page can answer 200 without accepting the request.
// The host's receipt also does not claim the process has stopped yet.
const body: unknown = await response.json();
if (
typeof body === "object" && body !== null &&
"ok" in body && body.ok === true &&
"closing" in body && body.closing === true
) {
return { kind: "accepted" };
}
} catch {
return false;
// A network failure, timeout or unreadable reply proves neither that
// the request was rejected nor that the service stopped. No auto-retry.
}
return { kind: "unknown" };
}
81 changes: 61 additions & 20 deletions packages/webui/test/browser/user-menu-shutdown.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -72,31 +72,72 @@ test("a refused shutdown can be dismissed by clicking outside after the error",
await expect(dialog).toHaveCount(0);
});

test("a shutdown request that gets no answer closes the dialog when the service is gone", async ({ page }) => {
test("a failed shutdown transport is unconfirmed even when the backend is still up; retry is manual", async ({ page }) => {
let posts = 0;
let browserProbes = 0;
await page.route("**/webui-shutdown?*", (route) => {
expect(route.request().method()).toBe("POST");
posts += 1;
return posts === 1
? route.abort("connectionrefused")
: route.fulfill({ json: { ok: true, closing: true } });
});
await openApp(page);
// The service is not running any more: the page is still open, but
// nothing answers on the address it came from. That is the state the
// request was asking for, so it is not a failure to report -- and the
// browser's own wording for a request that got no answer says nothing
// about it either way.
await page.route("**/webui-shutdown?*", (route) => route.abort("connectionrefused"));
await page.route("**/", (route) => route.abort("connectionrefused"));
await page.route("**/", (route) => {
browserProbes += 1;
return route.abort("connectionrefused");
});
await page.locator('[data-testid="sidebar-user-menu-trigger"], [data-testid="sidebar-user-menu-trigger-rail"]').first().click();
await page.getByTestId("user-menu-shutdown").click();
const dialog = page.getByRole("alertdialog");
await dialog.getByRole("button", { name: "关闭服务", exact: true }).click();
const confirm = dialog.getByRole("button", { name: "关闭服务", exact: true });
await confirm.click();

await expect(dialog).toContainText("未收到关闭确认,无法确定服务是否已停止。");
await expect(confirm).toBeEnabled();
const health = await page.request.get("/health");
expect(health.ok()).toBe(true);
expect((await health.json()).status).toBe("ok");
expect(posts).toBe(1);
expect(browserProbes).toBe(0);

await confirm.click();
await expect(dialog).toHaveCount(0);
expect(posts).toBe(2);
});

test("a shutdown request that gets no answer while the service still answers reports the failure in the page's own words", async ({ page }) => {
await openApp(page);
// The request did not get through, but the service is there and still
// answering: the person is told to retry, in the page's language rather
// than the browser's.
await page.route("**/webui-shutdown?*", (route) => route.abort("connectionrefused"));
await page.locator('[data-testid="sidebar-user-menu-trigger"], [data-testid="sidebar-user-menu-trigger-rail"]').first().click();
await page.getByTestId("user-menu-shutdown").click();
const dialog = page.getByRole("alertdialog");
await dialog.getByRole("button", { name: "关闭服务", exact: true }).click();
await expect(dialog).toContainText("关闭服务失败:本地服务仍在运行,请重试。");
for (const [label, status] of [["2xx without the receipt", 200], ["gateway timeout", 504]]) {
test(`${label} cannot dismiss the confirmation`, async ({ page }) => {
await page.route("**/webui-shutdown?*", (route) => route.fulfill({
status, json: { ok: true, closing: false },
}));
await openApp(page);
await page.locator('[data-testid="sidebar-user-menu-trigger"], [data-testid="sidebar-user-menu-trigger-rail"]').first().click();
await page.getByTestId("user-menu-shutdown").click();
const dialog = page.getByRole("alertdialog");
await dialog.getByRole("button", { name: "关闭服务", exact: true }).click();
await expect(dialog).toContainText("未收到关闭确认,无法确定服务是否已停止。");
});
}

test("no shutdown response releases the dialog at the receipt deadline", async ({ page }) => {
let release;
const pending = new Promise((resolve) => { release = resolve; });
await page.route("**/webui-shutdown?*", async (route) => {
await pending;
await route.abort().catch(() => {});
});
try {
await openApp(page);
await page.locator('[data-testid="sidebar-user-menu-trigger"], [data-testid="sidebar-user-menu-trigger-rail"]').first().click();
await page.getByTestId("user-menu-shutdown").click();
const dialog = page.getByRole("alertdialog");
const confirm = dialog.getByRole("button", { name: "关闭服务", exact: true });
await confirm.click();
await expect(confirm).toBeDisabled();
await expect(dialog).toContainText("未收到关闭确认,无法确定服务是否已停止。", { timeout: 10_000 });
await expect(confirm).toBeEnabled();
} finally {
release();
}
});
Loading
Loading