From af3c01187f377fa5603abaccee75aaa32b089e34 Mon Sep 17 00:00:00 2001 From: Fectivnfy112357 <213389510+Fectivnfy112357@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:08:07 +0800 Subject: [PATCH 1/3] Require an affirmative WebUI shutdown receipt --- packages/webui/docs/runtime/boot.md | 2 +- .../src/client/bindings/use-webui-shutdown.ts | 56 +++++------ .../client/features/account/ui/UserMenu.tsx | 10 +- .../src/client/platform/webui-shutdown.ts | 96 +++++++------------ .../test/browser/user-menu-shutdown.spec.mjs | 81 ++++++++++++---- 5 files changed, 128 insertions(+), 117 deletions(-) diff --git a/packages/webui/docs/runtime/boot.md b/packages/webui/docs/runtime/boot.md index 7bb3e795..ae5863ef 100644 --- a/packages/webui/docs/runtime/boot.md +++ b/packages/webui/docs/runtime/boot.md @@ -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). | diff --git a/packages/webui/src/client/bindings/use-webui-shutdown.ts b/packages/webui/src/client/bindings/use-webui-shutdown.ts index f64e18d8..b1d4f6e6 100644 --- a/packages/webui/src/client/bindings/use-webui-shutdown.ts +++ b/packages/webui/src/client/bindings/use-webui-shutdown.ts @@ -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 { return useCallback(async (): Promise => { 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; } }, []); } diff --git a/packages/webui/src/client/features/account/ui/UserMenu.tsx b/packages/webui/src/client/features/account/ui/UserMenu.tsx index 6b2f0de5..b5a1957e 100644 --- a/packages/webui/src/client/features/account/ui/UserMenu.tsx +++ b/packages/webui/src/client/features/account/ui/UserMenu.tsx @@ -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); } diff --git a/packages/webui/src/client/platform/webui-shutdown.ts b/packages/webui/src/client/platform/webui-shutdown.ts index 8ec0ec32..60232163 100644 --- a/packages/webui/src/client/platform/webui-shutdown.ts +++ b/packages/webui/src/client/platform/webui-shutdown.ts @@ -18,29 +18,19 @@ 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 { +): Promise { // 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. @@ -48,54 +38,40 @@ export async function requestWebuiShutdown( 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 { - 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" }; } diff --git a/packages/webui/test/browser/user-menu-shutdown.spec.mjs b/packages/webui/test/browser/user-menu-shutdown.spec.mjs index f608920d..b5937f42 100644 --- a/packages/webui/test/browser/user-menu-shutdown.spec.mjs +++ b/packages/webui/test/browser/user-menu-shutdown.spec.mjs @@ -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(); + } }); From ab7f6311825709c01d7beedb9ec8077ad43c5e90 Mon Sep 17 00:00:00 2001 From: Fectivnfy112357 <213389510+Fectivnfy112357@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:08:07 +0800 Subject: [PATCH 2/3] Observe detached Mini App leases without retrying failed starts --- ...20-webui-miniapp-view-and-runtime-seams.md | 6 +- .../miniapp/application/miniapp-workflows.ts | 9 ++- .../miniapp/ui/MiniAppView.public.tsx | 4 +- .../integration/miniapp-real-flow.test.ts | 65 ++++++++++++++++--- .../test/unit/miniapp-client-state.test.ts | 52 +++++++++++++++ 5 files changed, 122 insertions(+), 14 deletions(-) diff --git a/packages/webui/docs/adr/0020-webui-miniapp-view-and-runtime-seams.md b/packages/webui/docs/adr/0020-webui-miniapp-view-and-runtime-seams.md index b8b10897..f9dbdea6 100644 --- a/packages/webui/docs/adr/0020-webui-miniapp-view-and-runtime-seams.md +++ b/packages/webui/docs/adr/0020-webui-miniapp-view-and-runtime-seams.md @@ -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 diff --git a/packages/webui/src/client/features/miniapp/application/miniapp-workflows.ts b/packages/webui/src/client/features/miniapp/application/miniapp-workflows.ts index 128731aa..fab0e00c 100644 --- a/packages/webui/src/client/features/miniapp/application/miniapp-workflows.ts +++ b/packages/webui/src/client/features/miniapp/application/miniapp-workflows.ts @@ -1251,9 +1251,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"); diff --git a/packages/webui/src/client/features/miniapp/ui/MiniAppView.public.tsx b/packages/webui/src/client/features/miniapp/ui/MiniAppView.public.tsx index 6a8e7b3c..904ff2fe 100644 --- a/packages/webui/src/client/features/miniapp/ui/MiniAppView.public.tsx +++ b/packages/webui/src/client/features/miniapp/ui/MiniAppView.public.tsx @@ -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" }, diff --git a/packages/webui/test/integration/miniapp-real-flow.test.ts b/packages/webui/test/integration/miniapp-real-flow.test.ts index 35d666a0..33f906e4 100644 --- a/packages/webui/test/integration/miniapp-real-flow.test.ts +++ b/packages/webui/test/integration/miniapp-real-flow.test.ts @@ -32,10 +32,11 @@ // is `miniapp-ui-flow.test.ts`. The data directory is a temporary one, so a // run can never reach the operator's own `~/.minimax`. +import { spawn } from "node:child_process"; +import { once } from "node:events"; import { mkdir } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; -import { acquireMiniAppOwner } from "../../../local-runtime-v2/src/service/miniapp/process/node-runtime/owner-lease.js"; import { LOCAL_SOURCE, @@ -138,7 +139,7 @@ describe("the Mini App business flow against the real host", () => { expect(rowsOf(await client.call("listMiniApps"))).toEqual([]); }, 60_000); - it("reports another client's ownership and opens after that client releases the lease", async () => { + it("reports ownership held by a separate desktop-labelled process and opens after its release", async () => { const host = await bootRealHost(); const client = await connect(host.url); const name = "ownership-flow.miniapp"; @@ -149,21 +150,69 @@ describe("the Mini App business flow against the real host", () => { })); const pluginDataDir = join(host.dataDir, "v2", "plugin-data", "liveboards", name); await mkdir(pluginDataDir, { recursive: true }); - const owner = await acquireMiniAppOwner({ - pluginDataDir, - pluginId: name, - identity: { client: "desktop" }, + // A separate process exercises the production OS lease endpoint, not an + // in-memory owner. It only stands in for Desktop's ownership capability, + // so this is not an acceptance run against the Desktop application. + const leaseModule = new URL( + "../../../local-runtime-v2/src/service/miniapp/process/node-runtime/owner-lease.ts", + import.meta.url, + ).href; + const contender = spawn(process.execPath, [ + "--import", "tsx", "--input-type=module", "-e", ` + const [leaseModule, pluginDataDir, pluginId] = process.argv.slice(1); + const { acquireMiniAppOwner } = await import(leaseModule); + const owner = await acquireMiniAppOwner({ + pluginDataDir, + pluginId, + identity: { client: "desktop" }, + }); + if (owner.kind !== "acquired") throw new Error("Expected to acquire the fixture lease"); + process.once("message", async (message) => { + if (message !== "release") throw new Error("Unexpected fixture command"); + await owner.release(); + process.disconnect(); + }); + process.send({ ownerPid: process.pid }); + `, leaseModule, pluginDataDir, name, + ], { stdio: ["ignore", "ignore", "pipe", "ipc"] }); + let stderr = ""; + contender.stderr?.setEncoding("utf8"); + contender.stderr?.on("data", (chunk: string) => { stderr = (stderr + chunk).slice(-4_096); }); + const closed = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => { + contender.once("close", (code, signal) => resolve({ code, signal })); }); - if (owner.kind !== "acquired") throw new Error("The fixture could not acquire the ownership lease"); try { + const [ready] = await Promise.race([ + once(contender, "message", { signal: AbortSignal.timeout(10_000) }), + closed.then((outcome) => { + throw new Error(`Lease contender exited before acquiring: ${JSON.stringify(outcome)} — ${stderr}`); + }), + ]); + expect(ready).toEqual({ ownerPid: contender.pid }); + expect(contender.pid).not.toBe(process.pid); const refused = await client.call("openMiniApp", { pluginId: name }); expect(refused).toMatchObject({ kind: "error", code: "MINIAPP_PREPARATION_FAILED", reasonCode: "OWNED_ELSEWHERE", }); + await new Promise((resolve, reject) => { + contender.send("release", (error) => error ? reject(error) : resolve()); + }); + let exitDeadline: ReturnType | undefined; + try { + await expect(Promise.race([ + closed, + new Promise((_, reject) => { + exitDeadline = setTimeout(() => reject(new Error(`Lease contender did not exit after release — ${stderr}`)), 10_000); + }), + ])).resolves.toEqual({ code: 0, signal: null }); + } finally { + clearTimeout(exitDeadline); + } } finally { - await owner.release(); + if (contender.exitCode === null && contender.signalCode === null) contender.kill("SIGKILL"); + await closed; } const opened = await client.call("openMiniApp", { pluginId: name }); expectAnswered(opened); diff --git a/packages/webui/test/unit/miniapp-client-state.test.ts b/packages/webui/test/unit/miniapp-client-state.test.ts index e9b83ce2..be7bd4c0 100644 --- a/packages/webui/test/unit/miniapp-client-state.test.ts +++ b/packages/webui/test/unit/miniapp-client-state.test.ts @@ -393,6 +393,58 @@ describe("the Mini App business", () => { }, ); + it("observes a detached lease after a failed inline start without opening again", async () => { + vi.useFakeTimers(); + let detached = false; + let refuse = true; + const pluginId = "shared-app"; + const attempts = vi.fn(async () => { + if (refuse) { + // Another browser document took the lease while the inline start was pending. + detached = true; + throw Object.assign(new Error("Mini App publication preparation failed"), { + code: "MINIAPP_PREPARATION_FAILED", + }); + } + return { pluginId, viewUrl: "http://127.0.0.1:49152" }; + }); + const list = vi.fn(async () => ({ + miniApps: [miniApp(pluginId, "running", { detached, presentationRevision: 1 })], + })); + const workflows = createWebuiMiniAppWorkflows({ + port: { + openMiniApp: attempts, + listMiniApps: list, + stopMiniApp: async () => ({ success: true }), + }, + }); + const release = workflows.acquirePresentation(pluginId, false); + try { + await vi.advanceTimersByTimeAsync(0); + expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("failed"); + expect(workflows.getSnapshot().listing.rows[0]?.detached).toBe(true); + expect(attempts).toHaveBeenCalledTimes(1); + + detached = false; + await vi.advanceTimersByTimeAsync(2_000); + expect(workflows.getSnapshot().listing.rows[0]?.detached).toBe(false); + expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("failed"); + expect(attempts).toHaveBeenCalledTimes(1); + const readsAfterRelease = list.mock.calls.length; + await vi.advanceTimersByTimeAsync(4_000); + expect(list).toHaveBeenCalledTimes(readsAfterRelease); + + refuse = false; + expect(await workflows.open(pluginId)).toBe(true); + expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("open"); + expect(attempts).toHaveBeenCalledTimes(2); + } finally { + release(); + workflows.dispose(); + vi.useRealTimers(); + } + }); + it("offers to stop a Mini App another client is running", () => { const rows = webuiMiniAppRows([ miniApp("shared", "stopped", { From cd907020e0f3a49aeb98855174abaf8c9cb86673 Mon Sep 17 00:00:00 2001 From: Fectivnfy112357 <213389510+Fectivnfy112357@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:08:07 +0800 Subject: [PATCH 3/3] Continue lease observation after a failed explicit Mini App retry --- .../miniapp/application/miniapp-workflows.ts | 3 + .../test/unit/miniapp-client-state.test.ts | 114 ++++++++++-------- 2 files changed, 67 insertions(+), 50 deletions(-) diff --git a/packages/webui/src/client/features/miniapp/application/miniapp-workflows.ts b/packages/webui/src/client/features/miniapp/application/miniapp-workflows.ts index fab0e00c..9319aef5 100644 --- a/packages/webui/src/client/features/miniapp/application/miniapp-workflows.ts +++ b/packages/webui/src/client/features/miniapp/application/miniapp-workflows.ts @@ -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") diff --git a/packages/webui/test/unit/miniapp-client-state.test.ts b/packages/webui/test/unit/miniapp-client-state.test.ts index be7bd4c0..cc58de4d 100644 --- a/packages/webui/test/unit/miniapp-client-state.test.ts +++ b/packages/webui/test/unit/miniapp-client-state.test.ts @@ -393,57 +393,71 @@ describe("the Mini App business", () => { }, ); - it("observes a detached lease after a failed inline start without opening again", async () => { - vi.useFakeTimers(); - let detached = false; - let refuse = true; - const pluginId = "shared-app"; - const attempts = vi.fn(async () => { - if (refuse) { - // Another browser document took the lease while the inline start was pending. - detached = true; - throw Object.assign(new Error("Mini App publication preparation failed"), { - code: "MINIAPP_PREPARATION_FAILED", - }); + it.each(["observer", "explicit"] as const)( + "observes a detached lease after a failed inline start via %s without opening again", + async (entry) => { + vi.useFakeTimers(); + let detached = false; + let refuse = true; + let takeLease = entry === "observer"; + const pluginId = "shared-app"; + const attempts = vi.fn(async () => { + if (refuse) { + // Another browser document took the lease while the inline start was pending. + detached = takeLease; + throw Object.assign(new Error("Mini App publication preparation failed"), { + code: "MINIAPP_PREPARATION_FAILED", + }); + } + return { pluginId, viewUrl: "http://127.0.0.1:49152" }; + }); + const list = vi.fn(async () => ({ + miniApps: [miniApp(pluginId, "running", { detached, presentationRevision: 1 })], + })); + const workflows = createWebuiMiniAppWorkflows({ + port: { + openMiniApp: attempts, + listMiniApps: list, + stopMiniApp: async () => ({ success: true }), + }, + }); + let release: (() => void) | undefined; + try { + if (entry === "explicit") { + // A retained previous failure does not start or poll again on mount. + expect(await workflows.open(pluginId)).toBe(false); + release = workflows.acquirePresentation(pluginId, false); + takeLease = true; + expect(await workflows.open(pluginId)).toBe(false); + } else { + release = workflows.acquirePresentation(pluginId, false); + await vi.advanceTimersByTimeAsync(0); + } + const attemptsBeforeRelease = entry === "explicit" ? 2 : 1; + expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("failed"); + expect(workflows.getSnapshot().listing.rows[0]?.detached).toBe(true); + expect(attempts).toHaveBeenCalledTimes(attemptsBeforeRelease); + + detached = false; + await vi.advanceTimersByTimeAsync(2_000); + expect(workflows.getSnapshot().listing.rows[0]?.detached).toBe(false); + expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("failed"); + expect(attempts).toHaveBeenCalledTimes(attemptsBeforeRelease); + const readsAfterRelease = list.mock.calls.length; + await vi.advanceTimersByTimeAsync(4_000); + expect(list).toHaveBeenCalledTimes(readsAfterRelease); + + refuse = false; + expect(await workflows.open(pluginId)).toBe(true); + expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("open"); + expect(attempts).toHaveBeenCalledTimes(attemptsBeforeRelease + 1); + } finally { + release?.(); + workflows.dispose(); + vi.useRealTimers(); } - return { pluginId, viewUrl: "http://127.0.0.1:49152" }; - }); - const list = vi.fn(async () => ({ - miniApps: [miniApp(pluginId, "running", { detached, presentationRevision: 1 })], - })); - const workflows = createWebuiMiniAppWorkflows({ - port: { - openMiniApp: attempts, - listMiniApps: list, - stopMiniApp: async () => ({ success: true }), - }, - }); - const release = workflows.acquirePresentation(pluginId, false); - try { - await vi.advanceTimersByTimeAsync(0); - expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("failed"); - expect(workflows.getSnapshot().listing.rows[0]?.detached).toBe(true); - expect(attempts).toHaveBeenCalledTimes(1); - - detached = false; - await vi.advanceTimersByTimeAsync(2_000); - expect(workflows.getSnapshot().listing.rows[0]?.detached).toBe(false); - expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("failed"); - expect(attempts).toHaveBeenCalledTimes(1); - const readsAfterRelease = list.mock.calls.length; - await vi.advanceTimersByTimeAsync(4_000); - expect(list).toHaveBeenCalledTimes(readsAfterRelease); - - refuse = false; - expect(await workflows.open(pluginId)).toBe(true); - expect(workflows.getSnapshot().presentations[pluginId]?.kind).toBe("open"); - expect(attempts).toHaveBeenCalledTimes(2); - } finally { - release(); - workflows.dispose(); - vi.useRealTimers(); - } - }); + }, + ); it("offers to stop a Mini App another client is running", () => { const rows = webuiMiniAppRows([