Files
nexu-io__open-design/e2e/ui/cms-modal.test.ts
Caprika 8fb94d28eb feat(cms): 统一客户端活动点位接入与验收修复 (#7986)
* feat(cms): add verified desktop touchpoint hosts and Test acceptance

* fix(cms): keep Test modal scrim above app chrome

* fix(cms): load host styles and support hover packages

* fix(cms): report mounted host compatibility for restoration

* fix(cms): parse Vela actions in shared manifests without executing them

* fix(cms): preserve authorized actions and correct modal and hover behavior (#8003)

* fix(cms): harden touchpoint host interactions

* fix(cms): preserve modal actions and verify effective close controls

* test(cms): cover hover exit and above-anchor placement

* fix(cms): hide client test controls by default

* fix(cms): persist automatic campaign impressions per account and device

* fix(web): remove host campaign close button

* fix(cms): suppress campaign modals during onboarding

* fix(cms): unify test and production campaign lifecycle (#8118)

* fix(cms): enable safe campaign navigation in test and production

* fix(cms): enforce server-authorized touchpoint lifetimes

* fix(cms): refresh production touchpoints when client language changes

* fix(cms): stabilize hover refresh and synchronize Test locale

* fix(cms): preserve campaigns on focus and remember Test dismissal

* fix(cms): discover Test deployments without reloading

* fix(cms): keep granted touchpoint display authority through transport failures

A refresh that times out or fails in transport is not a withdrawal, but the
shared lifecycle treated every failure the same way: `status = "error"` then
`revoke()`, which tore down a lease the server had already granted and was
still inside its own deadline. One slow poll therefore blanked a running
campaign until the next 30s tick, and a second failure could not restore it
because the value had been dropped.

`abandonAttempt` now names the invariant: cancel the attempt, keep the lease,
and let `armExpiry` retire it at the deadline the server actually granted. The
lease length is the bound, so no retry budget is needed — Test's sixty-second
contract survives exactly one missed poll, and Production survives as many as
its authorization covers.

Three cases still clear, and one of them is new:

  - the failure carries the server's own withdrawal. A 410 is authoritative
    even when its receipt body is unreadable, so `ProductionTouchpointLoadError`
    now marks that one case and the lifecycle honours it. Without this, a
    malformed 410 would have been ridden out as if it were transport noise.
  - nothing is mounted, or the lease was already fenced by `wake`. Page
    recovery has no evidence the activity is still live, so it stays withdrawn.
  - the lease has run out on its own.

This does not fix OPEND-3237, which is a new activity failing its FIRST load:
there is no prior lease to keep and the display stays empty. It fixes the
adjacent class where a mounted activity is erased by a transient refresh.

* fix(cms): keep a failed refresh recoverable inside its own poll cycle

Three changes to how one refresh cycle behaves when it does not go cleanly.
None of them fixes OPEND-3237, whose first-load failure is still unexplained;
they remove the ways a working campaign is lost to an ordinary hiccup.

Bounded retries. A failed attempt used to get its next chance from the fixed
30s tick. For the sixty-second lease the Test runtime is granted, that chance
lands exactly when the lease expires, so a single failure put display on the
edge of going blank with nothing able to recover it. Retries at 1s and 3s give
a fast failure — transport error, 5xx, DNS — several chances while the lease is
still comfortably alive.

A retry must finish inside the cycle that spawned it. `refresh` declines to
start while a request is in flight, so a chain that ran past the next tick
would not merely be late: it would swallow that tick entirely. Worst case was
15+1+15+3+15 = 49s against a 30s interval. Scheduling now requires room for the
retry AND its full budget, which is also what makes "retries cover fast
failures" true in the code rather than only in a comment — an attempt that
burned the whole budget leaves no room by construction and is never retried.
The retry budget resets per cycle, not per success: otherwise the first cycle
to exhaust its retries would leave every later cycle with none.

Request budget 10s -> 15s. One refresh fetches a context and every enabled
placement, so the budget covers a round, not a request. A real round of 11.5s
whose placements all succeeded was being abandoned by the ten-second budget. It
stays well under the 30s interval on purpose.

Forward `accept-encoding` through the touchpoint runtime proxy. Decisions carry
base64 content and run to megabytes, and the proxy built its upstream headers
from scratch, dropping the caller's preference — every refresh pulled the
payload uncompressed, measured at 383KB against 214KB for the same decision.
Because the body is piped through verbatim, upstream's `content-encoding` has
to be handed back with it, or the caller decodes gzip as JSON; both halves land
together. Verified end to end through daemon and web: 2,149,685 -> 1,606,678
bytes on the wire, byte-identical after decode.

An authoritative withdrawal is never retried: a 410 that took a campaign off
the screen must not put it back.

* fix(cms): present each Test campaign modal once per account and device

Test modal presentations now share the production touchpoint-displayed:v1
impression: recorded once visible, read before any new automatic opening,
and persisted across reload, remount, and client restart.

* fix(cms): give the Test control readout an explicit ladder weight
2026-09-17 05:58:48 +00:00

368 lines
11 KiB
TypeScript

import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { expect, test } from "@/playwright/suite";
import {
mockAmrPersonalWorkspace,
mockAmrWalletSnapshot,
} from "@/playwright/amr";
import { applyStandardMocks } from "@/playwright/mock-factory";
import { T } from "@/timeouts";
import type { Page, Route } from "@playwright/test";
const { cmsHostReleaseFingerprint } = (await import(
`${process.cwd()}/../apps/web/next.config.ts`
)) as {
cmsHostReleaseFingerprint: (
readFile: (file: string) => string | Buffer,
) => string;
};
const workspaceRoot = resolve(process.cwd(), "..");
const digest = (value: string | Buffer) =>
`sha256:${createHash("sha256").update(value).digest("hex")}`;
const hostFingerprint = cmsHostReleaseFingerprint((file) =>
readFileSync(resolve(workspaceRoot, file)),
);
const PLACEMENT = "opend.home.campaign-modal";
const ACTION_ID = "use";
type CloseMode = "sdk" | "failed" | "hidden" | "disabled" | "none";
const moduleFor = (mode: CloseMode, tall = false) => `
export function mount(root, context, sdk) {
${mode === "failed" ? "throw new Error('fixture_mount_failed');" : ""}
${tall ? "const filler = document.createElement('div'); filler.style.cssText = 'height: 900px; width: 420px;'; root.append(filler);" : ""}
const title = document.createElement('h1');
title.textContent = 'CMS campaign fixture';
root.append(title);
${mode === "sdk" ? "const close = document.createElement('button'); close.type = 'button'; close.setAttribute('aria-label', 'Close campaign'); close.textContent = 'Close'; close.addEventListener('click', () => sdk.requestClose()); root.append(close);" : ""}
${mode === "hidden" ? "const close = document.createElement('button'); close.type = 'button'; close.setAttribute('aria-label', 'Close campaign'); close.hidden = true; close.textContent = 'Close'; root.append(close);" : ""}
${mode === "disabled" ? "const close = document.createElement('button'); close.type = 'button'; close.setAttribute('aria-label', 'Close campaign'); close.disabled = true; close.textContent = 'Close'; root.append(close);" : ""}
const action = document.createElement('button');
action.type = 'button';
action.textContent = 'Use campaign';
action.addEventListener('click', () => void sdk.dispatchAction('${ACTION_ID}'));
root.append(action);
return root;
}
`;
function contentFor(mode: CloseMode, tall = false) {
const entryModule = moduleFor(mode, tall);
const manifest = {
formatVersion: 2 as const,
runtimeKind: "web-component" as const,
runtimeApiVersion: 1 as const,
platformWrapperVersion: "vela-touchpoint-wrapper-v1" as const,
sdkVersion: "vela-touchpoint-sdk-v1" as const,
contentLine: "cms-modal-browser-fixture",
placements: [
{
key: PLACEMENT,
entry: "campaign-modal.js",
resources: [],
locales: ["en-US"],
requiredCapabilities: ["close", "static-action"],
staticActions: [
{
id: ACTION_ID,
target: {
kind: "https" as const,
url: "https://example.com/campaign",
},
},
],
},
],
resources: ["campaign-modal.js"],
images: [],
};
return {
id: `cms-modal-${mode}-${tall ? "tall" : "normal"}`,
placementKey: PLACEMENT,
locale: "en-US",
manifest,
manifestHash: digest(JSON.stringify(manifest)),
entryPath: "campaign-modal.js",
entryDigest: digest(entryModule),
entryModule,
resources: [
{
path: "campaign-modal.js",
digest: digest(entryModule),
bytes: Buffer.from(entryModule).toString("base64"),
},
],
runtime: {
kind: "web-component" as const,
apiVersion: 1 as const,
wrapperVersion: "vela-touchpoint-wrapper-v1" as const,
sdkVersion: "vela-touchpoint-sdk-v1" as const,
},
buildIdentity: { fingerprint: hostFingerprint },
};
}
function decisionFor(mode: CloseMode, tall = false) {
const now = Date.now();
return {
activityId: `cms-modal-${mode}-activity`,
touchpointDecisionId: `cms-modal-${mode}-decision`,
deploymentId: "cms-modal-browser-deployment",
authorizationExpiresAt: new Date(now + 60_000).toISOString(),
endsAt: new Date(now + 300_000).toISOString(),
serverTime: new Date(now).toISOString(),
placementKey: PLACEMENT,
requiredCapabilities: ["close", "static-action"],
staticActions: [
{
id: ACTION_ID,
target: {
kind: "https" as const,
url: "https://example.com/campaign",
},
},
],
content: contentFor(mode, tall),
};
}
async function installDesktopHost(page: Page) {
await page.addInitScript(() => {
const scope = window as Window & {
__od__?: unknown;
__cmsExternalOpens?: string[];
};
scope.__cmsExternalOpens = [];
scope.__od__ = {
version: 2,
client: { type: "desktop", platform: "test", osLocale: "en-US" },
shell: {
openExternal: async (url: string) => {
scope.__cmsExternalOpens?.push(url);
return { ok: true };
},
openPath: async () => ({ ok: true }),
},
browser: { clearData: async () => ({ ok: true }) },
capture: {
page: async () => ({
ok: true,
dataUrl: "data:image/png;base64,",
h: 1,
w: 1,
}),
},
project: {
pickAndImport: async () => ({
ok: true,
projectId: "fixture",
conversationId: "fixture",
entryFile: "index.html",
}),
pickAndReplaceWorkingDir: async () => ({
ok: true,
baseDir: "/tmp/fixture",
entryFile: null,
}),
},
pdf: { print: async () => ({ ok: true }) },
pet: { setVisible: () => undefined },
updater: {
status: async () => ({
arch: "arm64",
capabilities: {},
channel: "beta",
currentVersion: "fixture",
enabled: true,
mode: "test",
platform: "test",
state: "idle",
supported: true,
}),
check: async () => ({ ok: true }),
"clear-cache": async () => ({ ok: true }),
download: async () => ({ ok: true }),
install: async () => ({ ok: true }),
quit: async () => ({ ok: true }),
setMenuLabels: async () => ({ ok: true }),
subscribe: () => () => undefined,
subscribeOpenDialog: () => () => undefined,
},
};
});
}
async function installProductionFixture(
page: Page,
options: {
mode?: CloseMode;
tall?: boolean;
eventStatus?: number;
eventNetworkFailure?: boolean;
} = {},
) {
const mode = options.mode ?? "none";
const events: Array<Record<string, unknown>> = [];
await page.route("**/api/integrations/vela/status", async (route) => {
await route.fulfill({
json: {
loggedIn: true,
profile: "local",
user: {
id: "cms-modal-user",
email: "cms-modal@example.com",
plan: "free",
},
},
});
});
await mockAmrPersonalWorkspace(page, undefined, { accountPlan: "free" });
await mockAmrWalletSnapshot(page, {
email: "cms-modal@example.com",
plan: "free",
});
await page.route(
"**/api/touchpoints/production-runtime**",
async (route: Route) => {
const request = route.request();
if (request.method() === "POST") {
if (options.eventNetworkFailure) {
await route.abort();
return;
}
events.push(request.postDataJSON() as Record<string, unknown>);
await route.fulfill({
status: options.eventStatus ?? 200,
json: {
ok: options.eventStatus == null || options.eventStatus < 400,
},
});
return;
}
await route.fulfill({ json: decisionFor(mode, options.tall) });
},
);
return { events };
}
async function gotoModal(page: Page) {
await page.goto("/", { waitUntil: "domcontentloaded" });
await expect(page.getByText("Loading OpenDesign…")).toHaveCount(0, {
timeout: T.long,
});
await expect(page.getByRole("dialog", { name: "Campaign" })).toBeVisible({
timeout: T.long,
});
}
test.describe.configure({ timeout: T.xlong });
test.beforeEach(async ({ page }) => {
await applyStandardMocks(page);
await installDesktopHost(page);
});
test("[P1] production modal closes through its mounted SDK control without a host fallback", async ({
page,
}) => {
await installProductionFixture(page, { mode: "sdk" });
await gotoModal(page);
const modal = page.getByRole("dialog", { name: "Campaign" });
await expect(
modal.getByRole("button", { name: "Close campaign" }),
).toBeVisible({
timeout: T.medium,
});
await expect(
modal.getByRole("button", { name: "Close", exact: true }),
).toHaveCount(0);
await modal.getByRole("button", { name: "Close campaign" }).click();
await expect(modal).toBeHidden();
});
for (const mode of ["failed", "hidden", "disabled"] as const) {
test(`[P1] production modal adds no host Close button and Escape dismisses when the mounted control is ${mode}`, async ({
page,
}) => {
await installProductionFixture(page, { mode });
await gotoModal(page);
const modal = page.getByRole("dialog", { name: "Campaign" });
const fallback = modal.getByRole("button", { name: "Close", exact: true });
await expect(modal).toBeVisible({ timeout: T.medium });
await expect(fallback).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(modal).toBeHidden();
});
}
test("[P1] production modal stays within short and narrow viewports and closes on Escape", async ({
page,
}) => {
await page.setViewportSize({ width: 500, height: 240 });
await installProductionFixture(page, { mode: "sdk", tall: true });
await gotoModal(page);
const modal = page.getByRole("dialog", { name: "Campaign" });
const surface = modal;
await expect(surface).toBeVisible();
const box = await surface.boundingBox();
expect(box).not.toBeNull();
expect(box!.width).toBeLessThanOrEqual(500);
expect(box!.height).toBeLessThanOrEqual(240);
await page.setViewportSize({ width: 320, height: 180 });
const narrowBox = await modal.boundingBox();
expect(narrowBox).not.toBeNull();
expect(narrowBox!.width).toBeLessThanOrEqual(320);
expect(narrowBox!.height).toBeLessThanOrEqual(180);
await page.keyboard.press("Escape");
await expect(modal).toBeHidden();
await expect(page.locator("body")).toHaveCSS("overflow", "visible");
});
for (const outcome of [
{ label: "401", eventStatus: 401, navigates: false },
{ label: "403", eventStatus: 403, navigates: false },
{ label: "409", eventStatus: 409, navigates: false },
{ label: "500", eventStatus: 500, navigates: true },
{ label: "network failure", eventNetworkFailure: true, navigates: true },
] as const) {
test(`[P1] production action telemetry ${outcome.label} ${outcome.navigates ? "still navigates" : "denies navigation"}`, async ({
page,
}) => {
const fixture = await installProductionFixture(page, outcome);
await gotoModal(page);
const modal = page.getByRole("dialog", { name: "Campaign" });
await modal.getByRole("button", { name: "Use campaign" }).click();
await expect
.poll(() => fixture.events.length)
.toBeGreaterThanOrEqual(outcome.eventNetworkFailure ? 0 : 1);
await expect
.poll(async () =>
page.evaluate(
() =>
(window as Window & { __cmsExternalOpens?: string[] })
.__cmsExternalOpens?.length ?? 0,
),
)
.toBe(outcome.navigates ? 1 : 0);
if (outcome.navigates) {
expect(
await page.evaluate(
() =>
(window as Window & { __cmsExternalOpens?: string[] })
.__cmsExternalOpens,
),
).toEqual(["https://example.com/campaign"]);
} else {
expect(
await page.evaluate(
() =>
(window as Window & { __cmsExternalOpens?: string[] })
.__cmsExternalOpens,
),
).toEqual([]);
}
});
}