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 @@ -223,9 +223,13 @@ function refusalOf(error: unknown): WebuiMiniAppRefusal {
error && typeof error === "object" && typeof (error as { code?: unknown }).code === "string"
? ((error as { code: string }).code)
: "harness_error";
const message = error instanceof Error ? error.message : String(error);
const reasonCode = code === "MINIAPP_PREPARATION_FAILED" && error instanceof Error
? (error as { reasonCode?: unknown }).reasonCode
: undefined;
return {
code,
message: error instanceof Error ? error.message : String(error),
code: reasonCode === "OWNED_ELSEWHERE" ? reasonCode : code,
message: typeof reasonCode === "string" ? `${message} (${reasonCode})` : message,
};
}

Expand Down
1 change: 1 addition & 0 deletions packages/webui/src/client/platform/event-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export type WireFrame =
readonly requestId: string;
readonly code: WebuiWireErrorCode;
readonly message: string;
readonly reasonCode?: string;
};

export interface WebuiSocket {
Expand Down
2 changes: 1 addition & 1 deletion packages/webui/src/client/platform/wire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ export function createWebuiWire({
// stable code intact instead of turning every refusal into one shape.
fail(
session,
new WebuiWireError(frame.code, frame.message, frame.requestId),
new WebuiWireError(frame.code, frame.message, frame.requestId, frame.reasonCode),
);
return;
}
Expand Down
17 changes: 16 additions & 1 deletion packages/webui/src/server/operation/operation-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
type WebuiWireErrorCode,
} from "../../shared/envelope.js";
import type { WebuiOperationRegistryEntry } from "./operations.js";
import { OPEN_MINI_APP_OPERATION_NAME } from "../../shared/operation-names.js";

/**
* The stable code a thrown failure carries, if it names one.
Expand Down Expand Up @@ -150,11 +151,23 @@ export async function dispatchWebuiFrame(
sendFrame(ws, responseFrame(parsed.requestId, result.body));
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const code = stableCodeOf(error);
const miniAppPreparationFailed = parsed.operation === OPEN_MINI_APP_OPERATION_NAME &&
code === "MINIAPP_PREPARATION_FAILED";
let reasonCode: string | undefined;
if (miniAppPreparationFailed) {
const reason = (error as { reasonCode?: unknown }).reasonCode ??
(error instanceof Error ? stableCodeOf(error.cause) : undefined);
if (typeof reason === "string" && /^[A-Z][A-Z0-9_]{0,63}$/u.test(reason)) {
reasonCode = reason;
}
console.warn("[webui] Mini App publication preparation failed", { code, reasonCode });
}
// The capability's own stable code is preserved; only a failure that names
// no code at all becomes `harness_error`.
sendFrame(
ws,
errorFrame(parsed.requestId, stableCodeOf(error), message),
errorFrame(parsed.requestId, code, message, reasonCode),
);
}
}
Expand Down Expand Up @@ -201,12 +214,14 @@ export function errorFrame(
requestId: string,
code: string,
message: string,
reasonCode?: string,
): WebuiErrorFrame {
return {
protocolVersion: WEBUI_PROTOCOL_VERSION,
kind: "error",
requestId,
code,
message,
...(reasonCode !== undefined ? { reasonCode } : {}),
};
}
5 changes: 5 additions & 0 deletions packages/webui/src/shared/envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export interface WebuiErrorFrame {
readonly requestId: string;
readonly code: string;
readonly message: string;
readonly reasonCode?: string;
}

export interface WebuiEventFrame {
Expand Down Expand Up @@ -218,6 +219,7 @@ export function decodeWebuiServerFrame(text: string): WebuiFrameDecode {
requestId: candidate.requestId,
code: candidate.code,
message: candidate.message,
...(typeof candidate.reasonCode === "string" ? { reasonCode: candidate.reasonCode } : {}),
},
};
}
Expand Down Expand Up @@ -245,16 +247,19 @@ export class WebuiWireError extends Error {
readonly code: WebuiWireErrorCode;
/** The request this refusal answers, or {@link WEBUI_ANONYMOUS_REQUEST_ID} for one that could not be attributed. */
readonly requestId: string;
readonly reasonCode: string | undefined;

constructor(
code: WebuiWireErrorCode,
message: string,
requestId: string = WEBUI_ANONYMOUS_REQUEST_ID,
reasonCode?: string,
) {
super(message);
this.name = "WebuiWireError";
this.code = code;
this.requestId = requestId;
this.reasonCode = reasonCode;
}
}

Expand Down
38 changes: 38 additions & 0 deletions packages/webui/test/integration/miniapp-real-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@
// 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 { 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,
Expand Down Expand Up @@ -135,6 +138,40 @@ 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 () => {
const host = await bootRealHost();
const client = await connect(host.url);
const name = "ownership-flow.miniapp";
await publishLocalPackage(host.dataDir, name);
expectAnswered(await client.call("pluginManagement", {
action: "enablePlugin",
input: { pluginName: name, source: LOCAL_SOURCE },
}));
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" },
});
if (owner.kind !== "acquired") throw new Error("The fixture could not acquire the ownership lease");
try {
const refused = await client.call("openMiniApp", { pluginId: name });
expect(refused).toMatchObject({
kind: "error",
code: "MINIAPP_PREPARATION_FAILED",
reasonCode: "OWNED_ELSEWHERE",
});
} finally {
await owner.release();
}
const opened = await client.call("openMiniApp", { pluginId: name });
expectAnswered(opened);
const page = await fetch(String(bodyOf(opened).viewUrl));
expect(page.status).toBe(200);
expect(await page.text()).toContain(PAGE_MARKER);
}, 120_000);

it("keeps a Mini App that failed to start out of the running set", async () => {
const host = await bootRealHost();
const client = await connect(host.url);
Expand All @@ -161,6 +198,7 @@ describe("the Mini App business flow against the real host", () => {
// person has to act on: the entry refused to start.
const cause = await openCause(host, name);
expect(cause.join(" <- ")).toContain("RUNNER_START_FAILED");
expect(opened.reasonCode, cause.join(" <- ")).toBe("RUNNER_START_FAILED");

// And the Mini App is not left claiming to be running: the row says the
// start failed, and names the reason, instead of reading as a Mini App
Expand Down
59 changes: 32 additions & 27 deletions packages/webui/test/unit/miniapp-client-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,33 +360,38 @@ describe("the Mini App business", () => {
expect(workflows.getSnapshot().presentations.fourth?.kind).toBe("open");
});

it("reports an app another client owns, naming that client, in both surfaces' state", async () => {
const port = scriptedPort({
miniApps: [miniApp("shared-app", "stopped")],
open: async () => {
throw Object.assign(
new Error("Mini App shared-app is already running in electron (pid 4242)"),
{ code: "OWNED_ELSEWHERE" },
);
},
});
const workflows = createWebuiMiniAppWorkflows({ port });
await workflows.loadListing();
expect(await workflows.open("shared-app")).toBe(false);

const snapshot = workflows.getSnapshot();
const refusal = snapshot.refusals["shared-app"];
expect(refusal?.code).toBe("OWNED_ELSEWHERE");
const text = webuiMiniAppRefusalText({
code: refusal!.code,
message: refusal!.message,
rows: snapshot.listing.rows,
});
// Keep diagnostics while presenting a neutral client name.
expect(text).not.toContain("electron");
expect(text).toContain("4242");
expect(snapshot.presentations["shared-app"]).toEqual({ kind: "failed", refusal });
});
it.each(["OWNED_ELSEWHERE", "MINIAPP_PREPARATION_FAILED"])(
"reports an app another client owns when the runtime returns %s",
async (code) => {
const wrapped = code === "MINIAPP_PREPARATION_FAILED";
const port = scriptedPort({
miniApps: [miniApp("shared-app", "stopped")],
open: async () => {
throw Object.assign(
new Error(wrapped
? "Mini App publication preparation failed"
: "Mini App shared-app is already running in electron (pid 4242)"),
{ code, ...(wrapped ? { reasonCode: "OWNED_ELSEWHERE" } : {}) },
);
},
});
const workflows = createWebuiMiniAppWorkflows({ port });
await workflows.loadListing();
expect(await workflows.open("shared-app")).toBe(false);

const snapshot = workflows.getSnapshot();
const refusal = snapshot.refusals["shared-app"];
expect(refusal?.code).toBe("OWNED_ELSEWHERE");
const text = webuiMiniAppRefusalText({
code: refusal!.code,
message: refusal!.message,
rows: snapshot.listing.rows,
});
expect(text).not.toContain("electron");
expect(text).toContain(wrapped ? "OWNED_ELSEWHERE" : "4242");
expect(snapshot.presentations["shared-app"]).toEqual({ kind: "failed", refusal });
},
);

it("offers to stop a Mini App another client is running", () => {
const rows = webuiMiniAppRows([
Expand Down
20 changes: 20 additions & 0 deletions packages/webui/test/unit/webui-transport-wire.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,26 @@ describe("an inbound frame is judged before it is believed", () => {
);
});

it("carries the Mini App preparation reason to the request caller", async () => {
const transport = transportWith(ControllableSocket);
const pending = transport.openMiniApp!({ pluginId: "fixture" });
const refused = expect(pending).rejects.toMatchObject({
code: "MINIAPP_PREPARATION_FAILED",
reasonCode: "OWNED_ELSEWHERE",
});
await tick();
const socket = ControllableSocket.latest!;
socket.deliver({
protocolVersion: 1,
kind: "error",
requestId: socket.request.requestId,
code: "MINIAPP_PREPARATION_FAILED",
message: "Mini App publication preparation failed",
reasonCode: "OWNED_ELSEWHERE",
});
await refused;
});

it("refuses a frame from a different protocol version instead of reading it as an answer", async () => {
// The client used to `JSON.parse(...) as WireFrame` and check nothing else,
// so a frame from a service speaking another version was accepted as though
Expand Down
20 changes: 20 additions & 0 deletions packages/webui/test/unit/webui-wire-envelope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,26 @@ function socket(): { readyState: number; OPEN: number; sent: string[]; send(payl
}

describe("the service judges an inbound frame", () => {
it("preserves the reason of a Mini App publication refusal", async () => {
const ws = socket();
const entry = {
operation: { validate: () => ({ ok: true, body: {} }) },
handle: async () => {
throw Object.assign(new Error("Mini App publication preparation failed"), {
code: "MINIAPP_PREPARATION_FAILED",
reasonCode: "OWNED_ELSEWHERE",
});
},
} as unknown as WebuiOperationRegistryEntry;
await dispatchWebuiFrame(ws as unknown as WebSocket,
{ protocolVersion: 1, kind: "request", requestId: "open", operation: "openMiniApp", body: {} },
new Map([["openMiniApp", entry]]), true, () => undefined);
expect(JSON.parse(ws.sent[0]!)).toMatchObject({
code: "MINIAPP_PREPARATION_FAILED",
reasonCode: "OWNED_ELSEWHERE",
});
});

it("observes a rejecting finalizer once when abort interrupts a parked pull", async () => {
const ws = socket();
const controller = new AbortController();
Expand Down
Loading