diff --git a/apps/portal/src/ConnectApp.test.tsx b/apps/portal/src/ConnectApp.test.tsx
index e5231e4a4..1eb605565 100644
--- a/apps/portal/src/ConnectApp.test.tsx
+++ b/apps/portal/src/ConnectApp.test.tsx
@@ -1264,13 +1264,14 @@ describe("ConnectApp", () => {
expect(calls("/v1/ui-configuration")).toBe(1);
});
- it("uses one overview read when a visibility refresh settles before the paired focus event", async () => {
+ it.each(["visibilitychange", "focus"] as const)("uses one overview read after %s and its paired event", async first => {
render();
await settle();
- fireEvent(document, new Event("visibilitychange"));
- await settle();
- fireEvent(window, new Event("focus"));
- await settle();
+ const events = first === "focus" ? ["focus", "visibilitychange"] : ["visibilitychange", "focus"];
+ for (const event of events) {
+ fireEvent(event === "focus" ? window : document, new Event(event));
+ await settle();
+ }
expect(overviewReads()).toEqual(["", omitted]);
});
@@ -1419,7 +1420,7 @@ describe("ConnectApp", () => {
const older = structuredClone(overview);
let resolveOlder: ((response: Response) => void) | undefined;
let overviewCall = 0;
- vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
+ const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
vi.mocked(fetch).mockImplementation(async (input) => {
const path = new URL(String(input)).pathname;
if (path === "/v1/account/sessions") return Response.json({ sessions: [] });
@@ -1442,6 +1443,9 @@ describe("ConnectApp", () => {
await act(async () => resolveOlder?.(Response.json(older)));
expect(await screen.findByRole("heading", { name: "Garden notes" })).toBeInTheDocument();
+ visibility.mockReturnValue("hidden");
+ fireEvent(document, new Event("visibilitychange"));
+ visibility.mockReturnValue("visible");
fireEvent(document, new Event("visibilitychange"));
expect(await screen.findByRole("heading", { name: "Newest collection" })).toBeInTheDocument();
expect(overviewCall).toBe(2);
diff --git a/apps/portal/src/ConnectApp.tsx b/apps/portal/src/ConnectApp.tsx
index 5d36e94f5..5a9962a26 100644
--- a/apps/portal/src/ConnectApp.tsx
+++ b/apps/portal/src/ConnectApp.tsx
@@ -67,7 +67,7 @@ import "@mdbase-dev/ui/feedback.css";
import { Select } from "@mdbase-dev/ui/select";
import { literal } from "./literal";
import { usePortalCommands } from "./portal-commands";
-import { NativeStorageReads, useOverviewRefresh } from "./overview-refresh";
+import { announceCollectionDeletion, NativeStorageReads, useOverviewRefresh } from "./overview-refresh";
type MemberRole = "viewer" | "editor";
@@ -118,7 +118,7 @@ function ConnectWorkspace({ onFeedbackContext }: { onFeedbackContext(view: Conne
const [busy, setBusy] = useState>(() => new Set());
const busyRef = useRef(new Set());
const refreshGenerationRef = useRef(0);
- const refreshInFlightRef = useRef<{ promise: Promise; signal: AbortSignal; nativeStorage: boolean } | null>(null);
+ const refreshInFlightRef = useRef<{ promise: Promise; signal: AbortSignal; nativeStorage: boolean; mutationRevision: number } | null>(null);
const nativeStorageRef = useRef(new NativeStorageReads());
const mutationRevisionRef = useRef(0);
const optimisticRef = useRef(new Map());
@@ -148,14 +148,14 @@ function ConnectWorkspace({ onFeedbackContext }: { onFeedbackContext(view: Conne
const refresh = useCallback((signal = lifecycleRef.current?.signal, animate = false, storageAgeMs?: number): Promise => {
if (accountDeleted || !signal || signal.aborted) return Promise.resolve();
const nativeStorage = nativeStorageRef.current.due(storageAgeMs);
+ const mutationRevision = mutationRevisionRef.current;
const pending = refreshInFlightRef.current;
if (pending && !pending.signal.aborted) {
- if (pending.nativeStorage || !nativeStorage) return pending.promise;
+ if (pending.mutationRevision === mutationRevision && (pending.nativeStorage || !nativeStorage)) return pending.promise;
return pending.promise.then(() => refresh(signal, animate, storageAgeMs));
}
setRefreshing(true);
const generation = ++refreshGenerationRef.current;
- const mutationRevision = mutationRevisionRef.current;
const isCurrent = () => !signal.aborted && !lifecycleRef.current?.signal.aborted
&& generation === refreshGenerationRef.current && mutationRevision === mutationRevisionRef.current;
const failed = (reason: unknown) => {
@@ -201,7 +201,7 @@ function ConnectWorkspace({ onFeedbackContext }: { onFeedbackContext(view: Conne
});
}
})().catch(failed);
- refreshInFlightRef.current = { promise: request, signal, nativeStorage };
+ refreshInFlightRef.current = { promise: request, signal, nativeStorage, mutationRevision };
const settled = () => {
if (refreshInFlightRef.current?.promise === request) {
refreshInFlightRef.current = null;
@@ -212,13 +212,12 @@ function ConnectWorkspace({ onFeedbackContext }: { onFeedbackContext(view: Conne
return request;
}, [accountDeleted]);
- useOverviewRefresh(refresh, view);
-
- function refreshAfterMutation(animate = false): Promise {
+ const refreshAfterMutation = useCallback((animate = false): Promise => {
mutationRevisionRef.current++;
- const lifecycle = lifecycleRef.current?.signal;
- return (refreshInFlightRef.current?.promise ?? Promise.resolve()).then(() => refresh(lifecycle, animate));
- }
+ return refresh(undefined, animate);
+ }, [refresh]);
+
+ useOverviewRefresh(refresh, refreshAfterMutation, view);
useEffect(() => {
const update = () => setView(viewFromPath());
@@ -978,6 +977,7 @@ function DeleteCollectionDialog({ open, error, collection, busy, returnFocusRef,
async options => {
if (native) await management.deleteNativeCollection(collection.id, target.name, options);
else await management.deleteHostedCollection(collection.id, options);
+ announceCollectionDeletion();
},
false,
undefined,
diff --git a/apps/portal/src/authorization.css b/apps/portal/src/authorization.css
index 89858bc37..f4f395354 100644
--- a/apps/portal/src/authorization.css
+++ b/apps/portal/src/authorization.css
@@ -188,7 +188,6 @@
/* The list grows with the page. A nested box sized to the gap above the sticky
footer left room for one row on short windows; search narrows long lists. */
.collection-picker-list { border-block: 1px solid var(--line); }
-.collection-picker input::placeholder { color: var(--color-text-muted); }
.collection-picker-option > span[aria-hidden] { min-width: 0; }
.installation-additional-collection { padding-right: var(--space-3); }
.installation-additional-collection label { display: flex; align-items: center; gap: var(--space-3); min-width: 0; }
diff --git a/apps/portal/src/overview-refresh.ts b/apps/portal/src/overview-refresh.ts
index e97c0b8b1..ba1064abb 100644
--- a/apps/portal/src/overview-refresh.ts
+++ b/apps/portal/src/overview-refresh.ts
@@ -4,6 +4,14 @@ import type { ConnectView } from "./ConnectPrimitives";
/** `storageAgeMs`: include storage when the last successful storage read is at least this old. */
type Refresh = (signal?: AbortSignal, animate?: boolean, storageAgeMs?: number) => Promise;
+const collectionDeletionChannel = "mdbase-connect:collection-deleted";
+
+export function announceCollectionDeletion(): void {
+ if (typeof BroadcastChannel === "undefined") return;
+ const channel = new BroadcastChannel(collectionDeletionChannel);
+ channel.postMessage(null);
+ channel.close();
+}
/**
* Each native storage read wakes every held collection's log, so reads are
@@ -30,7 +38,7 @@ export class NativeStorageReads {
}
/** Refreshes on load, while visible, and when Account or Apps opens. */
-export function useOverviewRefresh(refresh: Refresh, view: ConnectView): void {
+export function useOverviewRefresh(refresh: Refresh, invalidate: () => Promise, view: ConnectView): void {
useEffect(() => {
const controller = new AbortController();
void refresh(controller.signal, false, 0);
@@ -39,24 +47,25 @@ export function useOverviewRefresh(refresh: Refresh, view: ConnectView): void {
};
const refreshWhenVisible = whenVisible();
const refreshStorageWhenVisible = whenVisible(30_000);
- let visibleAt = -Infinity;
- const onVisibility = () => {
- if (document.visibilityState !== "visible") return;
- visibleAt = performance.now();
+ let resumedAt = -Infinity;
+ // Browsers can dispatch focus and visibility in either order on return.
+ const onResume = () => {
+ if (document.visibilityState !== "visible" || performance.now() - resumedAt < 250) return;
+ resumedAt = performance.now();
refreshStorageWhenVisible();
};
- // Browsers often dispatch both events when returning to a tab.
- const onFocus = () => {
- if (performance.now() - visibleAt >= 250) refreshStorageWhenVisible();
+ const onVisibility = () => {
+ if (document.visibilityState === "hidden") resumedAt = -Infinity;
+ else onResume();
};
const timer = window.setInterval(refreshWhenVisible, 15_000);
document.addEventListener("visibilitychange", onVisibility);
- window.addEventListener("focus", onFocus);
+ window.addEventListener("focus", onResume);
window.addEventListener("online", refreshWhenVisible);
return () => {
controller.abort();
document.removeEventListener("visibilitychange", onVisibility);
- window.removeEventListener("focus", onFocus);
+ window.removeEventListener("focus", onResume);
window.removeEventListener("online", refreshWhenVisible);
window.clearInterval(timer);
};
@@ -66,4 +75,11 @@ export function useOverviewRefresh(refresh: Refresh, view: ConnectView): void {
if (view === "account") void refresh(undefined, false, 0);
if (view === "applications") void refresh();
}, [view, refresh]);
+
+ useEffect(() => {
+ if (view !== "applications" || typeof BroadcastChannel === "undefined") return;
+ const channel = new BroadcastChannel(collectionDeletionChannel);
+ channel.onmessage = () => { void invalidate(); };
+ return () => channel.close();
+ }, [view, invalidate]);
}
diff --git a/apps/portal/src/styles.css b/apps/portal/src/styles.css
index 90bb10258..051a97d08 100644
--- a/apps/portal/src/styles.css
+++ b/apps/portal/src/styles.css
@@ -5,6 +5,15 @@ body,
min-height: 100%;
}
+:root {
+ --color-placeholder: var(--color-text-muted);
+ --portal-control-border: color-mix(in oklch, var(--color-text-muted) 80%, var(--color-surface));
+}
+
+:where(.mdbase-field, .mdbase-select, .mdbase-checkbox, .mdbase-switch) {
+ --color-border-strong: var(--portal-control-border);
+}
+
.page-brand {
display: flex;
align-items: center;
diff --git a/apps/portal/tests/review/scenarios.mjs b/apps/portal/tests/review/scenarios.mjs
index 7b4a727af..d9c9d003f 100644
--- a/apps/portal/tests/review/scenarios.mjs
+++ b/apps/portal/tests/review/scenarios.mjs
@@ -127,6 +127,8 @@ const definitions = [
["signup-agreements", "/signup#verification=review-email", "Create an account", 0, state => { state.signedIn = false; }],
["forgot-password", "/forgot-password", "Reset your password", 0, state => { state.signedIn = false; }],
["reset-password", "/reset-password#reset=review-reset", "Choose a new password", 0, state => { state.signedIn = false; }],
+ ["unsubscribe", "/unsubscribe#unsubscribe=review-email", "Unsubscribe from mdbase email", 0, state => { state.signedIn = false; }],
+ ["device-approval", "/device", "Approval code", 0],
["onboarding-pending", "/getting-started", "Creating your first collection", 0, state => { state.onboarding = "pending"; }],
["onboarding-failed", "/getting-started", "We couldn't create your collection", 0, state => { state.onboarding = "failed"; }],
["empty-account", "/collections", "No collections", 0],
@@ -154,9 +156,26 @@ const definitions = [
["collection-overview", "/?collection=hosted-0", "Shared research library", 5],
["collection-storage", "/storage?collection=hosted-0", "Storage", 5],
["collection-access", "/access?collection=hosted-0", "Sam Okafor", 5],
+ ["collection-invitation", "/access?collection=hosted-0", "researcher@example.com", 5, state => {
+ state.invitations["hosted-0"] = [{ id: "invite-researcher", collection_id: "hosted-0", target_mode: "email",
+ submitted_email: "researcher@example.com", role: "viewer", state: "pending", created_at: clock, expires_at: expires }];
+ }],
["applications", "/applications", "Apps", 5],
+ ["app-installations", "/applications", "TaskNotes", 5, state => {
+ state.overview.installation_access = [{ application_id: "app-0", application_family_id: "app-0", application_name: "TaskNotes",
+ icon: null, application_origin: "https://tasknotes.mdbase.dev", device_kind: "app-runtime", created_at: clock,
+ connector_id: "connector-tasknotes", installation_id: "installation-tasknotes", create_collections: false,
+ collection_id: "collection-0", collection_name: "Field research", sync: "cloud_copy", available: true,
+ role: "owner", approved_optional_file_actions: [] }];
+ }],
["computers", "/computers", "Computers", 5],
["account-sessions", "/account", "Travel Safari", 5],
+ ["account-deleted", "/account-deleted", "Your account has been deleted", 0, state => { state.signedIn = false; }],
+ ["account-billing", "/account", "Manage billing", 5, state => {
+ state.account.backend = "next";
+ state.overview.billing = { available: true, plus: { status: "canceled", current_period_end: expires,
+ cancels_at: null, access_ends_at: expires } };
+ }],
["feedback", "/feedback", "Send feedback", 5],
["computer-offline", "/storage?collection=collection-2", "Storage", 5],
["revoking", "/storage?collection=hosted-0", "Disconnecting…", 5, state => { state.overview.hosted_collections[0].replicas[0].revocation_status = "revoking"; state.overview.grants[0].revocation_status = "revoking"; }],
diff --git a/apps/portal/tests/review/server.mjs b/apps/portal/tests/review/server.mjs
index 574ac49be..fe852bee5 100644
--- a/apps/portal/tests/review/server.mjs
+++ b/apps/portal/tests/review/server.mjs
@@ -119,7 +119,7 @@ export function reviewServer({ editorUrl = process.env.REVIEW_EDITOR_URL ?? "htt
if (path === "/v1/account/sessions" && method === "GET") return send({ sessions: state.sessions });
if (path === "/v1/account/sessions/revoke-others" && method === "POST") { state.sessions = state.sessions.filter(session => session.current); return send({ ok: true }); }
if (path.startsWith("/v1/account/sessions/") && method === "DELETE") { state.sessions = state.sessions.filter(session => session.id !== path.split("/").at(-1)); return send({ ok: true }); }
- if (path === "/v1/account" && method === "GET") return send({ ...account(data), authentication: state.account.authentication, email_preferences: state.account.email_preferences });
+ if (path === "/v1/account" && method === "GET") return send({ ...account(data), backend: state.account.backend, authentication: state.account.authentication, email_preferences: state.account.email_preferences });
if (path === "/v1/account/email-preferences" && method === "PATCH") { Object.assign(state.account.email_preferences, body); return send({ email_preferences: state.account.email_preferences }); }
if (path === "/v1/account/password" && method === "PATCH") {
state.account.authentication.password.configured = true;
diff --git a/apps/portal/tests/workspace-audit.spec.ts b/apps/portal/tests/workspace-audit.spec.ts
index 10e75d199..890cbc6d9 100644
--- a/apps/portal/tests/workspace-audit.spec.ts
+++ b/apps/portal/tests/workspace-audit.spec.ts
@@ -1,27 +1,202 @@
import { createRequire } from "node:module";
+import type { Page } from "@playwright/test";
import { expect, openScenario, test } from "./review/fixture";
import { clock, scenarios } from "./review/scenarios.mjs";
// Use the workspace's existing axe installation for browser checks.
const { AxeBuilder } = createRequire(new URL("../../editor/package.json", import.meta.url))("@axe-core/playwright");
+test.describe.configure({ mode: "parallel" });
+
+async function auditPage(page: Page, state: string, width: number) {
+ await page.evaluate(() => new Promise(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ }));
+ const audit = await new AxeBuilder({ page }).analyze();
+ expect.soft(audit.violations.map(rule => ({ id: rule.id, nodes: rule.nodes.map(node => ({ target: node.target, summary: node.failureSummary })) })), state).toEqual([]);
+ // Axe's text checks do not cover placeholder pseudo-elements or control borders.
+ const controlContrast = await page.evaluate(() => {
+ const ctx = document.createElement("canvas").getContext("2d", { willReadFrequently: true })!;
+ const paint = (color: string) => { ctx.fillStyle = color; ctx.fillRect(0, 0, 1, 1); };
+ const luminance = () => {
+ const channels = ctx.getImageData(0, 0, 1, 1).data.slice(0, 3);
+ const linear = Array.from(channels, channel => {
+ const value = channel / 255;
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
+ };
+ const contrast = (foreground: number, background: number) =>
+ (Math.max(foreground, background) + 0.05) / (Math.min(foreground, background) + 0.05);
+ const results: { control: string; feature: string; ratio: number }[] = [];
+ const modal = document.querySelector("dialog:modal");
+ // Language selectors use a visible value and chevron in the borderless footer.
+ const bordered = ".mdbase-field, .mdbase-select:not(.theme-select), .mdbase-checkbox, .mdbase-switch";
+ const selector = `${bordered}, input:placeholder-shown, textarea:placeholder-shown`;
+ for (const control of (modal ?? document).querySelectorAll(selector)) {
+ if (!control.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) || control.matches(":disabled, [aria-disabled=true]")) continue;
+ const layers: string[] = [];
+ for (let node = control.parentElement; node; node = node.parentElement) layers.unshift(getComputedStyle(node).backgroundColor);
+ const paintBackdrop = () => {
+ paint(getComputedStyle(document.documentElement).colorScheme === "dark" ? "#000" : "#fff");
+ layers.forEach(paint);
+ };
+ const style = getComputedStyle(control);
+ const record = (feature: string, ratio: number, minimum: number) => {
+ if (ratio < minimum) results.push({ control: control.getAttribute("aria-label") ?? control.className, feature, ratio });
+ };
+ if (control.matches(bordered)) {
+ paintBackdrop();
+ const adjacent = luminance();
+ paint(style.backgroundColor);
+ paint(style.borderTopColor);
+ record("border", contrast(luminance(), adjacent), 3);
+ }
+ if (control.matches(":placeholder-shown")) {
+ paintBackdrop();
+ paint(style.backgroundColor);
+ const background = luminance();
+ const placeholder = getComputedStyle(control, "::placeholder");
+ ctx.globalAlpha = Number(placeholder.opacity);
+ paint(placeholder.color);
+ ctx.globalAlpha = 1;
+ record("placeholder", contrast(luminance(), background), 4.5);
+ }
+ }
+ return results;
+ });
+ expect.soft(controlContrast, `${state} control contrast`).toEqual([]);
+ expect.soft(await page.evaluate(() => document.documentElement.scrollWidth), state).toBeLessThanOrEqual(width);
+}
+
+const managementStates = ["heavy-account", "applications", "computers", "account-sessions", "collection-access", "authorization-review"];
+
+async function auditDialogs(page: Page, width: number) {
+ const dialog = page.getByRole("dialog");
+ const button = (name: string) => page.getByRole("button", { name, exact: true });
+ const auditDialog = async (name: string) => {
+ await expect(page.getByRole("dialog", { name, exact: true })).toBeVisible();
+ await auditPage(page, name, width);
+ await page.keyboard.press("Escape");
+ await expect(dialog).toHaveCount(0);
+ };
+ const menuAction = async (trigger: string, action: string, name: string) => {
+ await button(trigger).click();
+ await auditPage(page, trigger, width);
+ await page.getByRole("menuitem", { name: action, exact: true }).click();
+ await auditDialog(name);
+ };
+
+ await openScenario(page, "typical-account");
+ if (width === 360) {
+ await button("Open menu").click();
+ await auditDialog("Navigation");
+ }
+ await page.keyboard.press("Control+k");
+ await auditDialog("Commands");
+ await page.keyboard.press("?");
+ await auditDialog("Keyboard shortcuts");
+ await page.keyboard.press("c");
+ await auditDialog("Add collection");
+ await page.keyboard.press("c");
+ await dialog.getByRole("button", { name: /^New collection/ }).click();
+ await dialog.getByRole("textbox").focus();
+ await page.keyboard.press("Tab");
+ await expect(dialog.getByRole("alert")).toBeVisible();
+ await auditDialog("Add collection");
+ await page.keyboard.press("c");
+ await dialog.getByRole("button", { name: /^A folder on this computer/ }).click();
+ await auditDialog("Add collection");
+
+ await openScenario(page, "collection-storage");
+ await menuAction("Actions for Shared research library", "Rename", "Rename Shared research library");
+ await button("Actions for Shared research library").click();
+ await page.getByRole("menuitem", { name: "Delete", exact: true }).click();
+ await dialog.getByRole("textbox").fill("Shared research library");
+ await auditDialog("Delete Shared research library?");
+ await button("Disconnect").click();
+ await auditDialog("Disconnect Studio Markdown folder?");
+
+ await openScenario(page, "new-cloud-copy");
+ await page.route("**/v1/next/collections/native-cloud/mode", route => route.fulfill({ json: {
+ collection_id: "native-cloud", current_mode: "cloud_copy", execution_available: true,
+ change: { request_id: "mode-change", source_mode: "cloud_copy", target_mode: "private", phase: "finishing" }
+ } }));
+ await page.goto("/storage?collection=native-cloud");
+ await button("Stop this switch").click();
+ await auditDialog("Stop this switch to Private?");
+
+ await openScenario(page, "collection-invitation");
+ await button("Remove").first().click();
+ await auditDialog("Remove Sam Okafor from Shared research library?");
+ await button("Cancel").click();
+ await auditDialog("Cancel this collection invitation?");
+ await button("Invite person").click();
+ await expect(page.getByRole("textbox", { name: "Email address" })).toBeVisible();
+ await auditPage(page, "collection invitation form", width);
+
+ await openScenario(page, "app-installations");
+ const app = page.locator('[data-command="app:app-0"]');
+ await app.locator(":scope > summary").press("Enter");
+ await expect(button("Remove installation")).toBeVisible();
+ await auditPage(page, "expanded installation details", width);
+ await button("Remove installation").click();
+ await auditDialog("Remove installation asknotes of TaskNotes?");
+ await button("Revoke collection access").click();
+ await auditDialog("Revoke TaskNotes access to Field research?");
+ await app.locator(".connect-grant > summary").first().press("Enter");
+ await app.getByRole("button", { name: "Revoke", exact: true }).first().click();
+ await auditDialog("Revoke access to Coastal restoration?");
+ await button("Revoke app").click();
+ await auditDialog("Revoke TaskNotes?");
+
+ await openScenario(page, "computers");
+ await menuAction("Actions for Studio MacBook", "Rename", "Rename Studio MacBook");
+ await button("Actions for Studio MacBook").click();
+ await page.getByRole("menuitem", { name: "Revoke", exact: true }).click();
+ await auditDialog("Revoke Studio MacBook?");
+
+ await openScenario(page, "account-sessions");
+ for (const [action, name] of [
+ [button("Sign out other sessions"), "Sign out other sessions?"],
+ [page.locator("[data-list-item]").filter({ hasText: "Travel Safari" }).getByRole("button", { name: "Sign out", exact: true }), "Sign out Travel Safari?"],
+ [button("Sign out of this browser"), "Sign out of this browser?"],
+ [button("Delete account…"), "Delete account"],
+ ] as const) {
+ await expect(action).toBeVisible();
+ await action.click();
+ await auditDialog(name);
+ }
+}
for (const width of [360, 768, 1280]) {
for (const colorScheme of ["light", "dark"] as const) {
- test(`management and consent pass axe at ${width}px in ${colorScheme}`, async ({ page }) => {
- test.setTimeout(90_000);
+ test(`Portal routes pass axe at ${width}px in ${colorScheme}`, async ({ page }) => {
+ test.setTimeout(180_000);
await page.setViewportSize({ width, height: 812 });
await page.emulateMedia({ colorScheme });
- for (const scenario of ["heavy-account", "applications", "computers", "account-sessions", "collection-access", "authorization-review"]) {
+ for (const scenario of width === 768 ? managementStates : scenarios.map(({ name }) => name)) {
await openScenario(page, scenario);
+ await expect(page.locator("html")).toHaveCSS("color-scheme", colorScheme);
+ await auditPage(page, scenario, width);
if (scenario === "applications") {
await page.locator(".connect-application > summary").first().press("Enter");
await expect(page.getByRole("button", { name: "Revoke app" })).toBeVisible();
+ await auditPage(page, "expanded app access", width);
+ }
+ if (scenario === "feedback") {
+ const dialog = page.getByRole("dialog");
+ await dialog.getByText("What gets sent", { exact: true }).click();
+ await dialog.getByRole("textbox").first().fill("Collection picker feedback");
+ await auditPage(page, "expanded feedback details", width);
}
- const audit = await new AxeBuilder({ page }).analyze();
- expect(audit.violations.map(rule => ({ id: rule.id, nodes: rule.nodes.map(node => ({ target: node.target, summary: node.failureSummary })) })), scenario).toEqual([]);
- expect(await page.evaluate(() => document.documentElement.scrollWidth), scenario).toBeLessThanOrEqual(width);
}
});
+ if (width !== 768) test(`Portal dialogs pass axe at ${width}px in ${colorScheme}`, async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width, height: 812 });
+ await page.emulateMedia({ colorScheme });
+ await auditDialogs(page, width);
+ });
}
}
@@ -53,6 +228,45 @@ test("clearing a filter from its empty state returns keyboard focus to search",
await expect(page.locator(".connect-collections-list [data-list-item]")).toHaveCount(66);
});
+test("an open Apps view updates after another tab deletes a collection during a refresh", async ({ page, context }) => {
+ await openScenario(page, "applications");
+ const deletingTab = await context.newPage();
+ await deletingTab.goto("/storage?collection=hosted-0");
+ const reader = page.locator('[data-command="app:app-1"]');
+ const summary = reader.locator(":scope > summary");
+ await expect(summary).toContainText("2 collections");
+ await summary.press("Enter");
+ await expect(reader.getByRole("button", { name: "Revoke app" })).toBeVisible();
+
+ const { promise: hold, resolve: release } = Promise.withResolvers();
+ const { promise: captured, resolve: capture } = Promise.withResolvers();
+ let reads = 0;
+ await page.route(url => url.pathname === "/v1/me", async route => {
+ if (++reads !== 1) return route.continue();
+ const oldOverview = await route.fetch();
+ capture();
+ await hold;
+ await route.fulfill({ response: oldOverview });
+ });
+ try {
+ await page.evaluate(() => window.dispatchEvent(new Event("online")));
+ await captured;
+ await expect(page.locator("main")).toHaveAttribute("aria-busy", "true");
+ await deletingTab.getByRole("button", { name: "Actions for Shared research library" }).click();
+ await deletingTab.getByRole("menuitem", { name: "Delete", exact: true }).click();
+ const dialog = deletingTab.getByRole("dialog", { name: "Delete Shared research library?" });
+ await dialog.getByRole("textbox").fill("Shared research library");
+ await dialog.getByRole("button", { name: "Delete permanently" }).click();
+ await expect(dialog).toHaveCount(0);
+ expect(reads).toBe(1);
+ } finally {
+ release();
+ }
+ await expect(summary.getByText("1 collection", { exact: true })).toBeVisible({ timeout: 3_000 });
+ await expect(reader.getByRole("button", { name: "Revoke app" })).toBeVisible();
+ expect(reads).toBe(2);
+});
+
test("mounts permission and installation controls only after their app is expanded", async ({ page }) => {
const heavy = structuredClone(scenarios.find(scenario => scenario.name === "heavy-account")!.state.overview);
heavy.installation_access = Array.from({ length: 80 }, (_, index) => ({
diff --git a/changelog.d/portal-live-apps-accessibility.md b/changelog.d/portal-live-apps-accessibility.md
new file mode 100644
index 000000000..f6cc6d65c
--- /dev/null
+++ b/changelog.d/portal-live-apps-accessibility.md
@@ -0,0 +1,5 @@
+## Fixed
+
+- Portal Apps updates collection counts after a collection is deleted in another Portal tab and checks for changes when the view regains focus.
+- Portal fields, checkboxes and switches have clearer outlines, and placeholder text has stronger contrast in both themes.
+- Late replies from cancelled Native app approvals no longer interrupt a newer approval in the browser worker.
diff --git a/runtime/packages/sdk/src/application/worker-host.ts b/runtime/packages/sdk/src/application/worker-host.ts
index 3ce24badf..ab7fb740e 100644
--- a/runtime/packages/sdk/src/application/worker-host.ts
+++ b/runtime/packages/sdk/src/application/worker-host.ts
@@ -429,7 +429,11 @@ export class ApplicationWorkerHost {
const frame=event.data;
if(Array.isArray(frame)&&frame.length===5&&frame[0]===APPLICATION_WORKER_PROTOCOL&&frame[1]===client.binding&&frame[2]==="nativeAuthorizationReply"){
const reply=nativeAuthorizationReply(frame[4]),slot=this.nativeWait;
+ if(!Number.isInteger(frame[3])||frame[3]<1||frame[3]>client.lastId||reply.rpc<1)throw new ApplicationWorkerError("application_worker_binding");
if(!slot){if(reply.rpc>this.nativeRpc)throw new ApplicationWorkerError("application_worker_binding");return;}
+ // A cancelled approval can reply after the next tab or request has
+ // started waiting. RPCs are never reused, so it cannot settle this wait.
+ if(reply.rpc((resolve,reject)=>{const timer=setTimeout(()=>reject(new Error(`missing ${kind}:${requestId}`)),1000);waiters.push(()=>{clearTimeout(timer);resolve();});});
}
}
- return{host,events,event,send:(requestId:number,action:ApplicationWorkerAction,payload:string|boolean|null=null)=>channel.port2.postMessage([schema,binding,requestId,action,payload])};
+ return{host,events,event,send:(requestId:number,action:ApplicationWorkerAction,payload:string|boolean|null=null)=>channel.port2.postMessage([schema,binding,requestId,action,payload]),
+ nativeReply:(requestId:number,rpc:number)=>channel.port2.postMessage([schema,binding,"nativeAuthorizationReply",requestId,{rpc,ok:true,value:{applicationId:id,authorizationId:id,manifestDigest:"ab".repeat(32)}}])};
}
function deferred(){let resolve!:(value:T)=>void;const promise=new Promise(r=>{resolve=r;});return{promise,resolve};}
afterEach(async()=>{for(const host of active.splice(0))await host.stop().catch(()=>{});for(const port of ports.splice(0))port.close();vi.restoreAllMocks();});
@@ -98,6 +99,36 @@ describe("private SDK Worker bounded lifecycle",()=>{
const f=fixture(),start=vi.spyOn(f.host.session,"start").mockResolvedValue(f.host.session.getSnapshot());f.send(1,"start");await f.event("reply",1);f.send(1,"start");
expect((await f.event("fatal",0))[4]).toEqual({code:"application_worker_binding"});await vi.waitFor(()=>expect(f.host.session.getSnapshot().status).toBe("closed"));expect(start).toHaveBeenCalledTimes(1);
});
+ it.each(["cancelled reply","wrong request ID"] as const)("handles a Native authorization %s while a newer approval waits",async scenario=>{
+ let callbacks:ApplicationWorkerSessionHost|undefined;
+ const compose=WorkerSession.applicationWorkerSession;
+ vi.spyOn(WorkerSession,"applicationWorkerSession").mockImplementation((declaration,packaged,host)=>{callbacks=host;return compose(declaration,packaged,host);});
+ const f=fixture(),first=new AbortController(),second=new AbortController();
+ const prepare=async(signal:AbortSignal)=>{
+ const portal=callbacks!.openPortal(),native=portal.nativeAuthorization!;
+ try{await native.prepare({requestId:id,accountId:id,appId:id,challenge:"ab".repeat(32)},signal);}
+ finally{native.cancel();portal.close();}
+ return f.host.session.getSnapshot();
+ };
+ vi.spyOn(f.host.session,"authorize").mockImplementationOnce(()=>prepare(first.signal)).mockImplementationOnce(()=>prepare(second.signal));
+ f.send(1,"authorize");
+ const oldCall=await f.event("nativeAuthorization",1);
+ if(oldCall[2]!=="nativeAuthorization")throw new Error("missing cancelled approval call");
+ first.abort();
+ expect((await f.event("reply",1))[4]).toMatchObject({ok:false,problem:{code:"application_worker_fenced"}});
+ f.send(2,"authorize");
+ const currentCall=await f.event("nativeAuthorization",2);
+ if(currentCall[2]!=="nativeAuthorization")throw new Error("missing current approval call");
+ if(scenario==="wrong request ID"){
+ f.nativeReply(1,currentCall[4].rpc);
+ expect((await f.event("fatal",0))[4]).toEqual({code:"application_worker_binding"});
+ return;
+ }
+ f.nativeReply(1,oldCall[4].rpc);
+ f.nativeReply(2,currentCall[4].rpc);
+ expect((await f.event("reply",2))[4]).toMatchObject({ok:true});
+ expect(f.events.some(value=>value[2]==="fatal")).toBe(false);
+ });
it("scopes original portal ownership and transfers all present original data/control/timer ports",async()=>{
let callbacks:ApplicationWorkerSessionHost|undefined;
const compose=WorkerSession.applicationWorkerSession;