Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(e2e): repair broken Playwright specs and uncovered OAuth/scroll/WS bugs (MUL-9867) (#11216)

Jiayuan Zhang0600855d6d5f
diff --git a/apps/web/app/auth/callback/page.tsx b/apps/web/app/auth/callback/page.tsx
index 118051b1fe..2035301b9d 100644
--- a/apps/web/app/auth/callback/page.tsx
+++ b/apps/web/app/auth/callback/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Suspense, useEffect, useState } from "react";
+import { Suspense, useEffect, useRef, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { sanitizeNextUrl, useAuthStore } from "@multica/core/auth";
@@ -32,6 +32,9 @@ function CallbackContent() {
const loginWithGoogle = useAuthStore((s) => s.loginWithGoogle);
const [error, setError] = useState<CallbackError | null>(null);
const [desktopToken, setDesktopToken] = useState<string | null>(null);
+ // Single-use OAuth codes must only be exchanged once even if React StrictMode
+ // re-invokes mount effects in development.
+ const exchangedCodeRef = useRef<string | null>(null);
useEffect(() => {
const code = searchParams.get("code");
@@ -51,6 +54,11 @@ function CallbackContent() {
return;
}
+ if (exchangedCodeRef.current === code) {
+ return;
+ }
+ exchangedCodeRef.current = code;
+
const state = searchParams.get("state") || "";
const stateParts = state.split(",");
const isDesktop = stateParts.includes("platform:desktop");
diff --git a/e2e/agent-mcp.spec.ts b/e2e/agent-mcp.spec.ts
index 75171f3a72..4eec5bb696 100644
--- a/e2e/agent-mcp.spec.ts
+++ b/e2e/agent-mcp.spec.ts
@@ -2,15 +2,13 @@ import { test, expect, type Page } from "@playwright/test";
import { TestApiClient } from "./fixtures";
import { waitForPageText } from "./helpers";
-// Stage 3.2 (MUL-3870): the creator-only MCP tab on the agent detail page.
+// Agent Apps section and Advanced Settings Apps management (MUL-8990):
//
// Auth + workspace bootstrap go through the real backend (same as every other
-// spec), but the agent list and the Composio connection/catalog endpoints are
-// mocked at the network boundary so the test runs without a configured
-// COMPOSIO_API_KEY or a live runtime to bind an agent to. The PUT /api/agents
-// write is intercepted so we can assert the exact allowlist body the toggle
-// produces — the heart of the data contract — instead of depending on the
-// backend persisting it.
+// spec), while the agent list and connected-apps endpoints are mocked at the
+// network boundary so the test runs without a configured COMPOSIO_API_KEY or a
+// live runtime. The PUT /api/agents/<id>/apps write is intercepted so we can
+// assert the exact payload the toggle produces.
const E2E_WORKER =
process.env.TEST_PARALLEL_INDEX ?? process.env.TEST_WORKER_INDEX ?? "0";
@@ -75,119 +73,172 @@ function mockAgent(ownerId: string, workspaceId: string) {
};
}
-/** Mock the Composio catalog + the current user's active connections (Notion +
- * Slack), the agent list (owned by `ownerId`), and capture any PUT
- * /api/agents/<id> body. Returns a getter for the last captured allowlist. */
-async function mockApis(page: Page, ownerId: string) {
- const captured: { allowlist?: unknown } = {};
-
- await page.route("**/api/integrations/composio/toolkits", (route) =>
- route.fulfill({
- status: 200,
- contentType: "application/json",
- body: JSON.stringify([
- { slug: "notion", name: "Notion", connectable: true },
- { slug: "slack", name: "Slack", connectable: true },
- ]),
- }),
+/** Mock the connected apps overview/catalog + agent list + agent apps write.
+ * When `viewerRole` is `"member"`, the logged-in user is mocked as a plain
+ * member so `canEdit` is false for an agent owned by someone else. */
+async function mockApis(
+ page: Page,
+ ownerId: string,
+ viewerUserId: string,
+ viewerRole: "owner" | "member" = "owner",
+) {
+ let agentApps: Array<{ agent_id: string; toolkit_slug: string; account_scope: string; level: string }> = [];
+ const captured: { apps?: unknown } = {};
+
+ await page.route(
+ (url) => url.pathname === "/api/config",
+ async (route) => {
+ const response = await route.fetch();
+ const body = await response.json();
+ await route.fulfill({
+ response,
+ json: { ...body, feature_flags: { ...body.feature_flags, composio_mcp_apps: true } },
+ });
+ },
);
- await page.route("**/api/integrations/composio/connections", (route) =>
- route.fulfill({
- status: 200,
- contentType: "application/json",
- body: JSON.stringify([
- {
- id: "conn-notion",
- toolkit_slug: "notion",
- status: "active",
- connected_at: "2026-06-30T00:00:00Z",
- last_used_at: null,
+ if (viewerRole === "member") {
+ await page.route(
+ (url) => /^\/api\/workspaces\/[^/]+\/members$/.test(url.pathname),
+ async (route) => {
+ const response = await route.fetch();
+ const members = (await response.json()) as Array<{ user_id: string; role: string }>;
+ await route.fulfill({
+ response,
+ json: members.map((m) => (m.user_id === viewerUserId ? { ...m, role: "member" } : m)),
+ });
+ },
+ );
+ }
+
+ await page.route(
+ (url) => url.pathname === "/api/apps",
+ (route) =>
+ route.fulfill({
+ json: {
+ catalog_mode: "all",
+ can_manage: viewerRole === "owner",
+ team: [],
+ personal: [
+ {
+ id: "conn-notion",
+ toolkit_slug: "notion",
+ status: "active",
+ connected_at: "2026-06-30T00:00:00Z",
+ last_used_at: null,
+ },
+ {
+ id: "conn-slack",
+ toolkit_slug: "slack",
+ status: "active",
+ connected_at: "2026-06-30T00:00:00Z",
+ last_used_at: null,
+ },
+ ],
+ agent_apps: agentApps,
},
- {
- id: "conn-slack",
- toolkit_slug: "slack",
- status: "active",
- connected_at: "2026-06-30T00:00:00Z",
- last_used_at: null,
+ }),
+ );
+
+ await page.route(
+ (url) => url.pathname === "/api/apps/catalog",
+ (route) =>
+ route.fulfill({
+ json: {
+ catalog_mode: "all",
+ apps: [
+ { slug: "notion", name: "Notion", curated: true, recommended_scope: "personal" },
+ { slug: "slack", name: "Slack", curated: true, recommended_scope: "personal" },
+ ],
},
- ]),
- }),
+ }),
+ );
+
+ await page.route(
+ (url) => url.pathname === `/api/agents/${AGENT_ID}/apps`,
+ (route) => {
+ const req = route.request();
+ if (req.method() === "PUT") {
+ const body = (req.postDataJSON?.() ?? {}) as {
+ apps?: Array<{ toolkit_slug: string; account_scope: string; level: string }>;
+ };
+ captured.apps = body.apps;
+ agentApps = (body.apps ?? []).map((app) => ({ ...app, agent_id: AGENT_ID }));
+ return route.fulfill({ json: { apps: agentApps } });
+ }
+ return route.fulfill({ json: { apps: agentApps } });
+ },
);
- // One handler for both the list (GET, query string) and the write
- // (PUT /api/agents/<id>). Other agent sub-routes fall through.
await page.route("**/api/agents**", (route) => {
const req = route.request();
const url = new URL(req.url());
const workspaceId = url.searchParams.get("workspace_id") ?? "ws-mock";
- if (req.method() === "PUT" && url.pathname.endsWith(`/api/agents/${AGENT_ID}`)) {
- const body = req.postDataJSON?.() ?? {};
- captured.allowlist = body.composio_toolkit_allowlist;
+ if (req.method() === "GET" && url.pathname.endsWith("/api/agents")) {
return route.fulfill({
- status: 200,
- contentType: "application/json",
- body: JSON.stringify({
- ...mockAgent(ownerId, workspaceId),
- composio_toolkit_allowlist: body.composio_toolkit_allowlist ?? [],
- }),
+ json: [mockAgent(ownerId, workspaceId)],
});
}
- if (req.method() === "GET" && url.pathname.endsWith("/api/agents")) {
+ if (req.method() === "GET" && url.pathname.endsWith(`/api/agents/${AGENT_ID}`)) {
return route.fulfill({
- status: 200,
- contentType: "application/json",
- body: JSON.stringify([mockAgent(ownerId, workspaceId)]),
+ json: mockAgent(ownerId, workspaceId),
});
}
return route.fallback();
});
- return () => captured.allowlist;
+ return () => captured.apps;
}
-test.describe("Agent MCP tab (creator-only)", () => {
- test("creator sees the MCP Apps tab and toggling a toolkit writes the allowlist", async ({
+test.describe("Agent Apps management (editor-only)", () => {
+ test("creator can manage agent apps and toggling an app writes the config", async ({
page,
}) => {
const { slug, userId } = await loginCapturingUser(page);
- const getAllowlist = await mockApis(page, userId);
+ const getApps = await mockApis(page, userId, userId, "owner");
await page.goto(`/${slug}/agents/${AGENT_ID}`, {
waitUntil: "domcontentloaded",
});
await waitForPageText(page, "MCP Test Agent");
- // The creator-only tab entry is present and opens the connection list.
- const tab = page.getByRole("button", { name: "MCP Apps" });
- await expect(tab).toBeVisible({ timeout: 15000 });
- await tab.click();
+ const appsSection = page.locator(`#agent-apps-${AGENT_ID}`);
+ await expect(appsSection).toBeVisible({ timeout: 15000 });
+ await appsSection.getByRole("button", { name: "Manage" }).click();
- await expect(page.getByText("Notion")).toBeVisible();
- await expect(page.getByText("Slack")).toBeVisible();
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByText("Notion")).toBeVisible();
+ await expect(dialog.getByText("Slack")).toBeVisible();
- // Allow Notion → the PUT body carries exactly ["notion"].
- await page.getByLabel(/Allow Notion for this agent/i).click();
- await expect.poll(() => getAllowlist()).toEqual(["notion"]);
+ // Enable Notion → PUT /api/agents/<id>/apps carries the new app entry.
+ await dialog.getByRole("switch", { name: "Enable Notion" }).click();
+ await expect.poll(() => getApps()).toEqual([
+ { toolkit_slug: "notion", account_scope: "personal", level: "write" },
+ ]);
});
- test("a non-creator viewer does not see the MCP Apps tab", async ({ page }) => {
- const { slug } = await loginCapturingUser(page);
- // Agent owned by someone else → the creator gate hides the tab entry.
- await mockApis(page, OTHER_USER_ID);
+ test("a non-editor viewer sees Apps read-only and cannot open Apps settings", async ({ page }) => {
+ const { slug, userId } = await loginCapturingUser(page);
+ // Agent owned by someone else and viewer is a plain member → read-only Apps section.
+ await mockApis(page, OTHER_USER_ID, userId, "member");
await page.goto(`/${slug}/agents/${AGENT_ID}`, {
waitUntil: "domcontentloaded",
});
await waitForPageText(page, "MCP Test Agent");
- // Other tabs render, but the creator-only MCP Apps entry must not.
- await expect(page.getByRole("button", { name: "Activity" })).toBeVisible({
- timeout: 15000,
- });
- await expect(page.getByRole("button", { name: "MCP Apps" })).toHaveCount(0);
+ const appsSection = page.locator(`#agent-apps-${AGENT_ID}`);
+ await expect(appsSection).toBeVisible({ timeout: 15000 });
+ await expect(appsSection.getByRole("button", { name: "Manage" })).toHaveCount(0);
+ await expect(appsSection.getByRole("button", { name: "Add" })).toHaveCount(0);
+
+ await page.getByRole("button", { name: "Settings" }).first().click();
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByRole("button", { name: "Apps", exact: true })).toHaveCount(0);
});
});
diff --git a/e2e/auth-callback-locale.spec.ts b/e2e/auth-callback-locale.spec.ts
index bf1bab4bd1..ec3ae54ceb 100644
--- a/e2e/auth-callback-locale.spec.ts
+++ b/e2e/auth-callback-locale.spec.ts
@@ -13,7 +13,7 @@ for (const scenario of [
name: "same account language",
language: "zh-Hans",
htmlLang: "zh-CN",
- continueLabel: "在 web 端继续",
+ continueLabel: "在网页端继续",
},
]) {
test(`Google callback keeps its single-use code while synchronizing ${scenario.name}`, async ({
@@ -25,6 +25,10 @@ for (const scenario of [
throw new Error("The callback regression requires a configured baseURL");
}
const origin = new URL(baseURL).origin;
+ const apiBase =
+ process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;
+ const apiOrigin = new URL(apiBase).origin;
+ const allowedOrigins = new Set([origin, apiOrigin]);
const code = "locale-regression-code";
const user = {
id: "66666666-6666-4666-8666-666666666666",
@@ -77,7 +81,7 @@ for (const scenario of [
await context.route("**/*", async (route) => {
const request = route.request();
const url = new URL(request.url());
- if (url.origin !== origin) {
+ if (!allowedOrigins.has(url.origin)) {
if (
/(^|\.)(google\.com|googleapis\.com|googleusercontent\.com)$/.test(url.hostname)
) {
diff --git a/e2e/auth.spec.ts b/e2e/auth.spec.ts
index 5e78d8550a..67e39536f7 100644
--- a/e2e/auth.spec.ts
+++ b/e2e/auth.spec.ts
@@ -37,7 +37,7 @@ test.describe("Authentication", () => {
// Open the workspace dropdown menu
await openAccountMenu(page);
- await page.getByRole("menuitem", { name: "Log out" }).click();
+ await page.getByRole("menuitem", { name: "Sign out" }).click();
await page.waitForURL("**/login", { timeout: 10000, waitUntil: "domcontentloaded" });
await waitForPageText(page, "Sign in to Multica");
diff --git a/e2e/chat-attachments.spec.ts b/e2e/chat-attachments.spec.ts
index cf9bd8a536..5b06af0775 100644
--- a/e2e/chat-attachments.spec.ts
+++ b/e2e/chat-attachments.spec.ts
@@ -114,8 +114,8 @@ test.describe("Chat attachments", () => {
createdAgentId = agentIns.rows[0].id as string;
const sessionIns = await pgc.query(
- `INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
- VALUES ($1, $2, $3, 'E2E Chat Attachment Session', 'active')
+ `INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status, explicitly_created_at)
+ VALUES ($1, $2, $3, 'E2E Chat Attachment Session', 'active', now())
RETURNING id`,
[ws.id, createdAgentId, userId],
);
diff --git a/e2e/comment-agent-routing.spec.ts b/e2e/comment-agent-routing.spec.ts
index cc72841fc6..e42238bca6 100644
--- a/e2e/comment-agent-routing.spec.ts
+++ b/e2e/comment-agent-routing.spec.ts
@@ -72,7 +72,7 @@ test("reply stays with the thread agent and hides unused historical fallbacks",
localStorage.setItem("multica:chat:isOpen", "false");
}, api.getToken());
await page.setViewportSize({ width: 1440, height: 1050 });
- await page.goto(`/${workspace.slug}/issues/${issue.id}`, { waitUntil: "domcontentloaded" });
+ await page.goto(`/${workspace.slug}/issues/${issue.identifier}`, { waitUntil: "domcontentloaded" });
await expect(page.getByText("Agent B is following this thread. Please reply here.", { exact: true })).toBeVisible({ timeout: 45_000 });
await expect(page.locator(`[data-run-id="${controlId}"]`)).toBeVisible();
for (const id of hiddenIds) await expect(page.locator(`[data-run-id="${id}"]`)).toHaveCount(0);
diff --git a/e2e/comment-steering.spec.ts b/e2e/comment-steering.spec.ts
index 89c1353c6d..96661568d4 100644
--- a/e2e/comment-steering.spec.ts
+++ b/e2e/comment-steering.spec.ts
@@ -54,7 +54,7 @@ for (const provider of ["codex", "pi"]) {
localStorage.setItem("multica:chat:isOpen", "false");
}, api.getToken());
await page.setViewportSize({ width: 1440, height: 1000 });
- await page.goto(`/${workspace.slug}/issues/${issue.id}`, { waitUntil: "domcontentloaded" });
+ await page.goto(`/${workspace.slug}/issues/${issue.identifier}`, { waitUntil: "domcontentloaded" });
await expect(page.locator(`[data-run-id="${turnId}"]`)).toBeVisible({ timeout: 45_000 });
const shell = page.getByTestId("reply-composer-shell").first();
diff --git a/e2e/docs.spec.ts b/e2e/docs.spec.ts
index 7c6f96871e..b498fb1334 100644
--- a/e2e/docs.spec.ts
+++ b/e2e/docs.spec.ts
@@ -23,7 +23,17 @@ async function docMode(page: Page): Promise<DocMode> {
let api: TestApiClient;
let slug: string;
+const API_BASE = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;
+let docsEnabledPromise: Promise<boolean> | null = null;
+function isDocsEnabled() {
+ return (docsEnabledPromise ??= fetch(`${API_BASE}/api/config`)
+ .then((res) => (res.ok ? res.json() : null))
+ .then((body: { feature_flags?: { docs_v1?: boolean } } | null) => body?.feature_flags?.docs_v1 === true)
+ .catch(() => false));
+}
+
test.beforeEach(async ({ page }) => {
+ test.skip(!(await isDocsEnabled()), "Docs is off; start the API with FF_DOCS_V1=true.");
page.on("pageerror", (error) => {
throw error;
});
@@ -40,8 +50,8 @@ test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
});
test.afterEach(async () => {
- await api.cleanup();
- await api.deleteWorkspace();
+ await api?.cleanup();
+ await api?.deleteWorkspace();
});
test("Markdown autosave, folder move, immutable history and restore", async ({
diff --git a/e2e/helpers.ts b/e2e/helpers.ts
index 72dfaa0873..59bd4ce38a 100644
--- a/e2e/helpers.ts
+++ b/e2e/helpers.ts
@@ -24,7 +24,7 @@ export async function waitForPageText(page: Page, text: string, timeout = 30000)
export async function reloadAppPage(page: Page) {
await page.reload({ waitUntil: "domcontentloaded" });
- await waitForPageText(page, "Issues");
+ await waitForIssuesPage(page);
}
/**
@@ -85,14 +85,15 @@ export function appRail(page: Page) {
return page.getByRole("navigation", { name: "App navigation" });
}
-/** The current workspace's tile in the rail; its accessible name is the workspace name. */
+/** The workspace switcher button at the top of the rail. */
export function currentWorkspaceTile(page: Page) {
- return appRail(page)
- .getByRole("link", { name: /E2E Workspace|Renamed WS/ })
- .and(page.locator('[aria-current="page"]'));
+ return appRail(page).getByRole("button", { name: "Switch workspace" });
}
export async function openAccountMenu(page: Page) {
+ // In `next dev`, the Next.js dev indicator sits in the bottom-left corner
+ // directly over the rail's Account button and intercepts pointer clicks.
+ await page.addStyleTag({ content: "nextjs-portal { display: none !important; }" });
const accountButton = appRail(page).getByRole("button", { name: "Account" });
await expect(accountButton).toBeVisible({ timeout: 15000 });
await accountButton.click();
diff --git a/e2e/html-preview-fragment-nav.spec.ts b/e2e/html-preview-fragment-nav.spec.ts
index 9b6f60b7a4..e8781a2a86 100644
--- a/e2e/html-preview-fragment-nav.spec.ts
+++ b/e2e/html-preview-fragment-nav.spec.ts
@@ -173,7 +173,7 @@ for (const [kind, html, links] of [
contentType: "application/json",
});
await expect(page).toHaveURL(previousUrl);
- await expect(page.getByRole("button", { name: "New Issue", exact: true }).first()).toBeVisible();
+ await expect(page.getByRole("button", { name: "New issue", exact: true }).first()).toBeVisible();
await expect(page.getByText("HTML fragment navigation regression", { exact: true })).toBeVisible();
const screenshot = testInfo.outputPath("after-one-back.png");
await page.screenshot({ path: screenshot });
diff --git a/e2e/html-preview-fullscreen.spec.ts b/e2e/html-preview-fullscreen.spec.ts
index 0bb8421677..b79f93d901 100644
--- a/e2e/html-preview-fullscreen.spec.ts
+++ b/e2e/html-preview-fullscreen.spec.ts
@@ -72,7 +72,7 @@ test.describe("HTML preview fullscreen", () => {
});
const block = page.locator(
location === "description"
- ? ".code-block-wrapper"
+ ? '[data-dynamic-code-block] [data-dynamic-block="html"]'
: `[data-comment-content="${comment!.id}"] [data-dynamic-block="html"]`,
);
await block.scrollIntoViewIfNeeded();
@@ -154,7 +154,7 @@ test.describe("HTML preview fullscreen", () => {
});
if (location === "description") {
- await block.getByRole("button", { name: "Show source" }).click();
+ await block.getByRole("tab", { name: "Source" }).click();
await opener.scrollIntoViewIfNeeded();
const sourceHeight = (await block.boundingBox())!.height;
const sourceScroll = await scroller.evaluate(readScroll);
diff --git a/e2e/inbox-delete.spec.ts b/e2e/inbox-delete.spec.ts
index 5e902a08c0..762aa585b3 100644
--- a/e2e/inbox-delete.spec.ts
+++ b/e2e/inbox-delete.spec.ts
@@ -26,16 +26,18 @@ test("delete a failed inbox entry with confirmation, retry, and cross-session re
localStorage.setItem("multica_token", token!);
localStorage.setItem("multica:chat:isOpen", "false");
}, api.getToken());
- await page.setViewportSize({ width: 1280, height: 850 });
+ // Compact viewport renders InboxPage's own InboxList (with right-click
+ // Delete); at desktop widths the live list lives in the Work panel.
+ await page.setViewportSize({ width: 640, height: 850 });
await page.goto(`/${workspace.slug}/inbox`, { waitUntil: "domcontentloaded" });
const row = page.locator('[data-mc="inbox-item"]').filter({ hasText: "Failed test run" });
await expect(row).toBeVisible({ timeout: 60000 });
const other = await context.newPage();
+ await other.setViewportSize({ width: 640, height: 850 });
await other.goto(`/${workspace.slug}/inbox`);
const otherRow = other.locator('[data-mc="inbox-item"]').filter({ hasText: "Failed test run" });
await expect(otherRow).toBeVisible();
- await row.click();
await row.click({ button: "right" });
await expect(page.getByRole("menuitem", { name: "Delete", exact: true })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("inbox-delete-menu.png") });
@@ -104,14 +106,14 @@ test("deleting active issue notifications restores archived history with explici
localStorage.setItem("multica_token", token!);
localStorage.setItem("multica:chat:isOpen", "false");
}, api.getToken());
- await page.setViewportSize({ width: 1280, height: 850 });
+ await page.setViewportSize({ width: 640, height: 850 });
await page.goto(`/${workspace.slug}/inbox`, { waitUntil: "domcontentloaded" });
const row = page.locator('[data-mc="inbox-item"]').filter({ hasText: "Issue with archived history" });
await expect(row).toBeVisible({ timeout: 60000 });
await row.click({ button: "right" });
await page.getByRole("menuitem", { name: "Delete", exact: true }).click();
const dialog = page.getByRole("alertdialog", { name: "Delete notification?" });
- await expect(dialog).toContainText("Previously archived notifications remain and will be visible again in Archived.");
+ await expect(dialog).toContainText("Previously archived notifications, the issue, and its runs are kept.");
await expect(dialog).toHaveCSS("opacity", "1");
await expect(page.getByRole("menuitem", { name: "Delete", exact: true })).not.toBeVisible();
await page.screenshot({ path: testInfo.outputPath("inbox-delete-history-warning.png") });
diff --git a/e2e/issue-add-property-overflow.spec.ts b/e2e/issue-add-property-overflow.spec.ts
index 845cd78e3d..31648c7094 100644
--- a/e2e/issue-add-property-overflow.spec.ts
+++ b/e2e/issue-add-property-overflow.spec.ts
@@ -34,7 +34,7 @@ test.describe("Issue sidebar add property", () => {
const title = `E2E add property overflow ${suffix}`;
const issue = await api.createIssue(title);
const slug = await loginAsDefault(page);
- await page.goto(`/${slug}/issues/${issue.id}`, { waitUntil: "domcontentloaded" });
+ await page.goto(`/${slug}/issues/${issue.identifier}`, { waitUntil: "domcontentloaded" });
await waitForPageText(page, title);
await page.locator("[data-right-sidebar-panel]").getByRole("button", { name: "Add property" }).click();
diff --git a/e2e/issue-duplicate.spec.ts b/e2e/issue-duplicate.spec.ts
index 5304105ba9..d17d722498 100644
--- a/e2e/issue-duplicate.spec.ts
+++ b/e2e/issue-duplicate.spec.ts
@@ -24,7 +24,7 @@ test.describe("Mark as duplicate", () => {
const duplicateTitle = `Status picker hard to tap ${run}`;
const duplicate = await api.createIssue(duplicateTitle, { status: "todo" });
- await page.goto(`/${slug}/issues/${duplicate.id}`);
+ await page.goto(`/${slug}/issues/${duplicate.identifier}`);
// The detail page can close a just-opened picker while it finishes
// loading, so retry opening until the action takes the click.
await expect(async () => {
@@ -46,14 +46,14 @@ test.describe("Mark as duplicate", () => {
await expect(page.getByRole("link", { name: original.identifier, exact: true })).toBeVisible();
await originalLink.click();
- await expect(page).toHaveURL(new RegExp(`/issues/${original.id}$`));
+ await expect(page).toHaveURL(new RegExp(`/issues/${original.identifier}$`));
await expect(page.getByRole("button", { name: "Duplicates" })).toBeVisible();
// The sidebar row names the duplicate with its title; the activity feed
// links it by identifier alone.
await expect(page.getByRole("link", { name: `${duplicate.identifier} ${duplicateTitle}` })).toBeVisible();
await expect(page.getByText(`marked ${duplicate.identifier} as a duplicate of this issue`)).toBeVisible();
- await page.goto(`/${slug}/issues/${duplicate.id}`);
+ await page.goto(`/${slug}/issues/${duplicate.identifier}`);
await page.getByRole("button", { name: "Not a duplicate" }).click();
await expect(page.getByRole("button", { name: "Not a duplicate" })).toHaveCount(0);
await expect(page.getByRole("button", { name: "Todo", exact: true }).first()).toBeVisible();
diff --git a/e2e/issue-filter-advanced.spec.ts b/e2e/issue-filter-advanced.spec.ts
index d53a6f99a7..4a1dd603da 100644
--- a/e2e/issue-filter-advanced.spec.ts
+++ b/e2e/issue-filter-advanced.spec.ts
@@ -64,7 +64,7 @@ test.describe("Issue filter: search, due date, advanced", () => {
await expect.poll(() => visibleIssueTitles(page, all)).toEqual([...all].sort());
await page.getByRole("button", { name: "Filter", exact: true }).click();
- await page.getByRole("textbox", { name: "Filter by field or value…" }).fill("urg");
+ await page.getByRole("textbox", { name: "Filter by field or value..." }).fill("urg");
const urgentRow = page.getByRole("menuitemcheckbox", { name: /Priority\s*is\s*Urgent/ });
await expect(urgentRow).toBeVisible();
await shot(page, "01-search");
@@ -133,7 +133,7 @@ test.describe("Issue filter: search, due date, advanced", () => {
// Delete the group: one overdue rule is a simple filter again.
await page.getByRole("button", { name: "Advanced filter" }).click();
await expect(panel).toBeVisible();
- await group.getByRole("button", { name: "Condition actions" }).last().click();
+ await group.getByRole("button", { name: "Condition actions" }).first().click();
await page.getByRole("menuitem", { name: "Delete group" }).click();
await expect.poll(() => visibleIssueTitles(page, all)).toEqual([lowLate, mediumLate, urgentLate].sort());
await panel.getByRole("button", { name: "Switch to simple filter" }).click();
@@ -160,12 +160,11 @@ test.describe("Issue filter: search, due date, advanced", () => {
await expect(page.getByRole("menuitem", { name: property.name })).toBeVisible();
await shot(page, "05-advanced-field-picker");
await page.getByRole("menuitem", { name: property.name }).click();
- await panel.getByRole("button", { name: "Values" }).nth(1).click();
- await page.getByRole("menuitemcheckbox", { name: "No value" }).click();
- await page.keyboard.press("Escape");
-
const rows = panel.getByTestId("advanced-filter-row");
await expect(rows).toHaveCount(2);
+ await rows.nth(1).getByRole("combobox", { name: "Match" }).click();
+ await page.getByRole("option", { name: "is empty" }).click();
+
await expect(rows.nth(1)).toContainText(property.name);
await expect(panel.getByRole("button", { name: "Add property filter" })).toHaveCount(0);
await expect.poll(() => visibleIssueTitles(page, all)).toEqual([urgentLate, urgentUndated].sort());
diff --git a/e2e/issue-project-status-filter.spec.ts b/e2e/issue-project-status-filter.spec.ts
index b2760560b7..5e1bdc1680 100644
--- a/e2e/issue-project-status-filter.spec.ts
+++ b/e2e/issue-project-status-filter.spec.ts
@@ -13,9 +13,12 @@ async function openProjectStatusMenu(page: Page) {
}
async function visibleIssueTitles(page: Page, titles: string[]) {
+ // Match only issue cards/rows so project names in the Work sidebar
+ // (which sits inside <main>) do not match when they share the issue title.
+ const issues = page.locator('[data-mc="board-card"], [data-mc="issue-row"]');
const present: string[] = [];
for (const title of titles) {
- if (await page.getByText(title, { exact: true }).first().isVisible()) {
+ if (await issues.getByText(title, { exact: true }).first().isVisible()) {
present.push(title);
}
}
@@ -71,10 +74,13 @@ test.describe("Issue filter: project status", () => {
// issue is out too: with no project there is no status to match.
await expect.poll(() => visibleIssueTitles(page, all)).toEqual([activeIssue]);
- // The chip reports the dimension, and removing it restores the list.
- const chipsBar = page.getByRole("main");
- await expect(chipsBar.getByText("Project status")).toBeVisible();
- await chipsBar.getByRole("button", { name: /Remove .*filter/ }).first().click();
+ // The filter trigger reports the active filter and its summary tooltip names
+ // the dimension; Reset clears it and restores the list.
+ const filterTrigger = page.getByRole("button", { name: "1 filter" });
+ await expect(filterTrigger).toBeVisible();
+ await filterTrigger.hover();
+ await expect(page.getByText("Project status")).toBeVisible();
+ await page.getByRole("button", { name: "Reset", exact: true }).click();
await expect
.poll(() => visibleIssueTitles(page, all))
.toEqual([...all].sort());
diff --git a/e2e/issue-sidebar-containment.spec.ts b/e2e/issue-sidebar-containment.spec.ts
index 32c5a0b51a..d2b06efff6 100644
--- a/e2e/issue-sidebar-containment.spec.ts
+++ b/e2e/issue-sidebar-containment.spec.ts
@@ -25,7 +25,7 @@ test.describe("Issue detail sidebar containment", () => {
const title = "E2E sidebar containment " + Date.now();
const issue = await api.createIssue(title);
const slug = await loginAsDefault(page);
- await page.goto(`/${slug}/issues/${issue.id}`, { waitUntil: "domcontentloaded" });
+ await page.goto(`/${slug}/issues/${issue.identifier}`, { waitUntil: "domcontentloaded" });
await waitForPageText(page, title);
await expect(page.locator("text=Properties")).toBeVisible();
diff --git a/e2e/issue-table.spec.ts b/e2e/issue-table.spec.ts
index cb80bbeb42..0b895c8f3c 100644
--- a/e2e/issue-table.spec.ts
+++ b/e2e/issue-table.spec.ts
@@ -42,31 +42,27 @@ function tableBody(request: Request): TableRequestBody {
}
async function switchToTable(page: Page) {
- const currentView = page.getByRole("button", { name: "Board", exact: true });
- await expect(currentView).toBeVisible();
- await currentView.click();
- const tableOption = page.getByRole("menuitemradio", {
- name: "Table",
- exact: true,
- });
- await tableOption.click();
- await expect(
- page.getByRole("button", { name: "Table", exact: true }),
- ).toBeVisible();
- await expect(tableOption).toBeHidden();
+ await page.getByRole("button", { name: "Display", exact: true }).click();
+ const popover = page.locator("[data-slot=popover-content]");
+ const tableToggle = popover.getByRole("button", { name: "Table", exact: true });
+ await expect(tableToggle).toBeVisible();
+ await tableToggle.click();
+ await expect(tableToggle).toHaveAttribute("aria-pressed", "true");
+ await page.keyboard.press("Escape");
+ await expect(popover).toBeHidden();
}
async function groupByStatus(page: Page) {
- await page.getByRole("button", { name: "Group", exact: true }).click();
- const statusOption = page.getByRole("menuitemradio", {
- name: "Status",
- exact: true,
- });
+ await page.getByRole("button", { name: "Display", exact: true }).click();
+ const popover = page.locator("[data-slot=popover-content]");
+ const grouping = popover.locator('[aria-label="Grouping"]');
+ await expect(grouping).toBeVisible();
+ await grouping.click();
+ const statusOption = page.getByRole("option", { name: "Status", exact: true });
await statusOption.click();
- await expect(
- page.getByRole("button", { name: "Group: Status", exact: true }),
- ).toBeVisible();
- await expect(statusOption).toBeHidden();
+ await expect(grouping).toContainText("Status");
+ await page.keyboard.press("Escape");
+ await expect(popover).toBeHidden();
}
test.describe("Issue Table server grouping", () => {
@@ -148,7 +144,9 @@ test.describe("Issue Table server grouping", () => {
.filter({ hasText: "Backlog" })
.first();
await expect(backlogGroup).toContainText("501");
- await expect(page.getByText(/Loaded \d+ of 1001/)).toBeVisible();
+ await expect(
+ page.getByRole("button", { name: new RegExp(`E2E Table Large ${run}`) }).first(),
+ ).toBeVisible();
await expect(
page.getByText(/Grouping and hierarchy are paused/),
).toHaveCount(0);
@@ -200,6 +198,11 @@ test.describe("Issue Table server grouping", () => {
await reloadAppPage(page);
await switchToTable(page);
+ const groupsPromise = page.waitForResponse(
+ (response) =>
+ apiPath(response.request()) === "/api/issues/table/groups" &&
+ response.status() === 200,
+ );
const todoRootPromise = page.waitForResponse((response) => {
if (apiPath(response.request()) !== "/api/issues/table/rows") return false;
const body = tableBody(response.request());
@@ -225,18 +228,28 @@ test.describe("Issue Table server grouping", () => {
});
await groupByStatus(page);
- const [todoRootResponse, todoChildrenResponse, doneRootResponse] =
+ const [groupsResponse, todoRootResponse, todoChildrenResponse, doneRootResponse] =
await Promise.all([
+ groupsPromise,
todoRootPromise,
todoChildrenPromise,
doneRootPromise,
]);
+ const groups = (await groupsResponse.json()) as TableGroupsResponse;
const todoRoot = (await todoRootResponse.json()) as TableRowsResponse;
const todoChildren =
(await todoChildrenResponse.json()) as TableRowsResponse;
const doneRoot = (await doneRootResponse.json()) as TableRowsResponse;
- expect(todoRoot.total).toBe(3);
+ expect(groups.total).toBe(3);
+ expect(
+ Object.fromEntries(groups.groups.map((group) => [group.key, group.count])),
+ ).toEqual({
+ "status:todo": 2,
+ "status:done": 1,
+ });
+ // Grouped root requests skip the query-wide COUNT; totals come from /groups.
+ expect(todoRoot.total).toBe(0);
expect(todoRoot.rows).toEqual([
expect.objectContaining({
issue: expect.objectContaining({ id: parent.id, title: parentTitle }),
@@ -270,15 +283,13 @@ test.describe("Issue Table server grouping", () => {
page,
}) => {
const run = Date.now();
- const seeds = await api.seedTableIssues(
+ await api.seedTableIssues(
Array.from({ length: 60 }, (_, index) => ({
title: `E2E Table Cursor ${run} ${index.toString().padStart(2, "0")}`,
status: "todo" as const,
position: index + 1,
})),
);
- const moved = seeds.at(-1);
- if (!moved) throw new Error("Cursor fixture was not created");
await reloadAppPage(page);
const firstHeadPromise = page.waitForResponse((response) => {
@@ -304,8 +315,10 @@ test.describe("Issue Table server grouping", () => {
await tableScroller.evaluate((element) => {
element.scrollTop = element.scrollHeight;
});
- await firstTailPromise;
- await expect(page.getByText("Loaded 60 of 60", { exact: true })).toBeVisible();
+ const firstTail = (await (await firstTailPromise).json()) as TableRowsResponse;
+ const moved = firstTail.rows.at(-1)?.issue;
+ if (!moved) throw new Error("Tail cursor fixture row was not returned");
+ await expect(page.getByText("No more", { exact: true })).toBeVisible();
const postUpdateResponses: Array<{
body: TableRequestBody;
@@ -324,7 +337,9 @@ test.describe("Issue Table server grouping", () => {
});
};
page.on("response", collectResponse);
- await api.updateIssue(moved.id, { position: 0 });
+ // Moving a tail-page issue to the top of the default updated_at DESC order
+ // shifts the head/tail sort boundary and invalidates staleCursor.
+ await api.updateIssue(moved.id, { title: `${moved.title} moved` });
await expect
.poll(
@@ -365,7 +380,7 @@ test.describe("Issue Table server grouping", () => {
].map((row) => row.issue.id);
expect(new Set(refreshedIds).size).toBe(60);
expect(refreshedIds).toContain(moved.id);
- await expect(page.getByText("Loaded 60 of 60", { exact: true })).toBeVisible();
+ await expect(page.getByText("No more", { exact: true })).toBeVisible();
page.off("response", collectResponse);
});
diff --git a/e2e/issue-task-history.spec.ts b/e2e/issue-task-history.spec.ts
index 145f9f1469..93d0755aaf 100644
--- a/e2e/issue-task-history.spec.ts
+++ b/e2e/issue-task-history.spec.ts
@@ -49,7 +49,7 @@ test("issue loads compact runs until Runs requests full own or subtree history",
const url = new URL(response.url());
return isIssueTasks(url) && url.searchParams.get("view") === "timeline";
});
- await page.goto(`/${workspace.slug}/issues/${issue.id}`);
+ await page.goto(`/${workspace.slug}/issues/${issue.identifier}`);
const compact = await (await compactResponse).json();
expect(compact).toHaveLength(1);
expect(compact[0].result).toEqual({ comment: "Inline run summary" });
diff --git a/e2e/issue-timeline-scroll.spec.ts b/e2e/issue-timeline-scroll.spec.ts
index fb12422a0d..17016574d5 100644
--- a/e2e/issue-timeline-scroll.spec.ts
+++ b/e2e/issue-timeline-scroll.spec.ts
@@ -48,13 +48,32 @@ test("Inbox restores the current reply after leaving a virtualized long thread",
await notification.click();
const target = page.locator(`#comment-${targetId}`);
await expect(target).toBeVisible();
- await expect.poll(() => readingPosition(page, targetId).then((p) => p?.mounted)).toBe(true);
- await expect.poll(() => readingPosition(page, targetId).then((p) => p?.visible)).toBe(true);
- const before = (await readingPosition(page, targetId))!;
+ const waitForSettledPosition = async (commentId?: string) => {
+ let last: { id: string; offset: number } | null = null;
+ let stable = 0;
+ await expect.poll(async () => {
+ const current = await readingPosition(page, commentId);
+ if (!current?.mounted || !current.visible) {
+ last = null;
+ stable = 0;
+ return 0;
+ }
+ if (last && last.id === current.id && Math.abs(current.offset - last.offset) < 2) {
+ stable += 1;
+ } else {
+ stable = 1;
+ }
+ last = { id: current.id, offset: current.offset };
+ return stable;
+ }, { timeout: 10_000, intervals: [100] }).toBeGreaterThanOrEqual(3);
+ return last!;
+ };
+ const before = await waitForSettledPosition(targetId);
const leaveAndReturn = async () => {
await page.locator(`a[href="/${slug}/issues"]`).first().click();
await expect(page).toHaveURL((url) => url.pathname === `/${slug}/issues`);
+ await expect(page.getByRole("heading", { name: "All issues" })).toBeVisible();
await page.goBack();
};
const expectRestored = async (position: { id: string; offset: number }) => {
@@ -76,12 +95,13 @@ test("Inbox restores the current reply after leaving a virtualized long thread",
await container.hover();
await page.mouse.wheel(0, -1800);
await expect.poll(async () => (await readingPosition(page))?.id).not.toBe(targetId);
- const reading = (await readingPosition(page))!;
+ const reading = await waitForSettledPosition();
expect(reading).not.toBeNull();
await leaveAndReturn();
await expectRestored(reading);
await page.locator(`a[href="/${slug}/issues"]`).first().click();
await expect(page).toHaveURL((url) => url.pathname === `/${slug}/issues`);
+ await expect(page.getByRole("heading", { name: "All issues" })).toBeVisible();
await page.setViewportSize({ width: 1200, height: 900 });
await page.goBack();
await expectRestored(reading);
@@ -157,14 +177,14 @@ test("scrolling up a virtualized long thread keeps the reading position steady",
await page.goto(`/${slug}/inbox`);
await page.getByText(title, { exact: true }).first().click();
await expect(page.locator(`#comment-${targetId}`)).toBeVisible();
- await expect.poll(() => readingPosition(page, targetId).then((p) => p?.mounted && p.visible)).toBe(true);
+ await expect.poll(() => readingPosition(page, targetId).then((p) => p?.mounted && p.visible), { timeout: 10_000 }).toBe(true);
await page.waitForTimeout(1000);
const fromInbox = await scrollUpShifts(page, 40);
expect(fromInbox.length).toBeGreaterThan(30);
expect.soft(fromInbox.filter((s) => Math.abs(s) > 2), `Inbox landing shifts: ${fromInbox}`).toEqual([]);
// 2. Open the issue normally, go to the end of the discussion, read upward.
- await page.goto(`/${slug}/issues/${mixed.issue.id}`);
+ await page.goto(`/${slug}/issues/${mixed.issue.identifier}`);
await expect(page.getByText("Long discussion root")).toBeVisible();
const toEnd = () => page.evaluate(() => {
const c = document.querySelector<HTMLElement>('[data-tab-scroll-root^="main:"]')!;
diff --git a/e2e/issue-wakeups.spec.ts b/e2e/issue-wakeups.spec.ts
index 49b9f4bec3..eb48d841b8 100644
--- a/e2e/issue-wakeups.spec.ts
+++ b/e2e/issue-wakeups.spec.ts
@@ -42,7 +42,7 @@ test("members see the child-done system rule and create a wakeup", async ({ page
localStorage.setItem("multica:chat:isOpen", "false");
}, api.getToken());
await page.setViewportSize({ width: 1440, height: 1000 });
- await page.goto(`/${workspace.slug}/issues/${parent.id}`, { waitUntil: "domcontentloaded" });
+ await page.goto(`/${workspace.slug}/issues/${parent.identifier}`, { waitUntil: "domcontentloaded" });
const systemRule = page.getByRole("button", { name: /When stage 1's sub-issues all finish/ });
await expect(systemRule).toBeVisible({ timeout: 45_000 });
@@ -117,7 +117,7 @@ test("a member waits for a condition the platform checks", async ({ page }) => {
localStorage.setItem("multica:chat:isOpen", "false");
}, api.getToken());
await page.setViewportSize({ width: 1440, height: 1000 });
- await page.goto(`/${workspace.slug}/issues/${issue.id}`, { waitUntil: "domcontentloaded" });
+ await page.goto(`/${workspace.slug}/issues/${issue.identifier}`, { waitUntil: "domcontentloaded" });
await page.getByRole("button", { name: "New wakeup" }).click({ timeout: 45_000 });
const form = page.getByRole("form", { name: "New wakeup" });
@@ -131,7 +131,7 @@ test("a member waits for a condition the platform checks", async ({ page }) => {
const rule = page.getByRole("button", { name: /When this issue moves to In Review/ });
await expect(rule).toBeVisible();
- await expect(page.getByRole("button", { name: /Condition Grok: Waiting for In Review/ })).toBeVisible();
+ await expect(rule).toContainText("Wake Condition Grok · Trigger once");
const stored = await db.query<{ id: string; condition: unknown; event_types: string[] }>(
`SELECT id, condition, event_types FROM issue_wakeup WHERE issue_id = $1`,
[issue.id],
@@ -153,7 +153,8 @@ test("a member waits for a condition the platform checks", async ({ page }) => {
await expect(page.getByText("When this issue moves to In Review · woke Condition Grok")).toBeVisible({ timeout: 20_000 });
await page.goto(`/${workspace.slug}/autopilots?tab=wakeups`, { waitUntil: "domcontentloaded" });
- await page.getByRole("button", { name: /^All/ }).click();
+ await page.getByRole("button", { name: "Waiting or running" }).click();
+ await page.getByRole("menuitemradio", { name: /^All wakeups/ }).click();
const row = page.getByRole("row", { name: /Review the upload design/ });
await expect(row).toContainText("When this issue moves to In Review");
await expect(row).toContainText("1");
diff --git a/e2e/issues.spec.ts b/e2e/issues.spec.ts
index f0f78a0a6d..ed4e0bb541 100644
--- a/e2e/issues.spec.ts
+++ b/e2e/issues.spec.ts
@@ -86,7 +86,7 @@ test.describe("Issues", () => {
await expect(page.getByText(oldTitle)).toBeVisible();
await expect(page.getByText(updatedTodayTitle)).toBeVisible();
- await page.getByRole("button", { name: /filter/i }).click();
+ await page.getByRole("button", { name: "Filter", exact: true }).click();
await page.getByRole("menuitem", { name: /^Date\b/ }).hover();
await page.getByRole("menuitem", { name: "Today" }).click();
@@ -121,7 +121,7 @@ test.describe("Issues", () => {
await expect(page.getByText(todayTitle)).toBeVisible();
await expect(page.getByText(oldTitle)).toBeVisible();
- await page.getByRole("button", { name: /filter/i }).click();
+ await page.getByRole("button", { name: "Filter", exact: true }).click();
await page.getByRole("menuitem", { name: /^Date\b/ }).hover();
const customDateButton = page.getByRole("button", { name: "Custom date or range" });
await expect(customDateButton).toBeVisible();
@@ -163,10 +163,8 @@ test.describe("Issues", () => {
// Reload to see the new issue
await reloadAppPage(page);
- // Navigate to the issue detail. Use a suffix match so the selector works
- // whether the href is legacy `/issues/{id}` or URL-refactored
- // `/{slug}/issues/{id}`.
- const issueLink = page.locator(`a[href$="/issues/${issue.id}"]`);
+ // Navigate to the issue detail using its canonical identifier link.
+ const issueLink = page.locator(`a[href$="/issues/${issue.identifier}"]`);
await expect(issueLink).toBeVisible({ timeout: 5000 });
await issueLink.click();
diff --git a/e2e/lazy-calendar-smoke.spec.ts b/e2e/lazy-calendar-smoke.spec.ts
index e0c8d80efe..e0e7973154 100644
--- a/e2e/lazy-calendar-smoke.spec.ts
+++ b/e2e/lazy-calendar-smoke.spec.ts
@@ -9,7 +9,7 @@ test("calendar lazy loading in issue details, custom properties and date-range f
await api.createProperty("Review date", "date");
const issue = await api.createIssue("Calendar loading verification", { due_date: "2026-11-05" });
const slug = await loginAsDefault(page);
- await page.goto(`/${slug}/issues/${issue.id}`);
+ await page.goto(`/${slug}/issues/${issue.identifier}`);
const sidebar = page.locator("[data-right-sidebar-panel]");
const date = sidebar.getByRole("button", { name: "Nov 5", exact: true });
await date.click();
diff --git a/e2e/local-search.spec.ts b/e2e/local-search.spec.ts
index 9ce418f98c..9ce977273c 100644
--- a/e2e/local-search.spec.ts
+++ b/e2e/local-search.spec.ts
@@ -6,7 +6,7 @@ import { createTestApi, loginAsDefault, openAccountMenu } from "./helpers";
// (MUL-7754): results match server search, follow writes made elsewhere, and
// no server search request is sent while typing.
-const SEARCH_PLACEHOLDER = "Type a command or search...";
+const SEARCH_PLACEHOLDER = "Search, or type what needs doing...";
function isSearchIndexChanges(res: Response): boolean {
return res.url().includes("/api/search-index/changes") && res.ok();
@@ -103,7 +103,7 @@ test.describe("Local search index", () => {
await expect.poll(() => searchIndexDatabases(page)).toHaveLength(1);
await openAccountMenu(page);
- await page.getByRole("menuitem", { name: "Log out" }).click();
+ await page.getByRole("menuitem", { name: "Sign out" }).click();
await page.waitForURL("**/login", { timeout: 10_000, waitUntil: "domcontentloaded" });
await expect.poll(() => searchIndexDatabases(page)).toEqual([]);
@@ -120,12 +120,22 @@ test.describe("Local search index", () => {
const memberId = await owner.addMemberByEmail(api.getEmail());
await loginAsDefault(page);
+ const wsConnected = page.waitForEvent("websocket", (ws) => {
+ const url = new URL(ws.url());
+ return url.pathname === "/ws" && url.searchParams.get("workspace_slug") === shared.slug;
+ });
const synced = page.waitForResponse(isSearchIndexChanges, { timeout: 45_000 });
await page.goto(`/${shared.slug}/issues`, { waitUntil: "domcontentloaded" });
- await synced;
+ await Promise.all([wsConnected, synced]);
+ await expect(page.getByText(`shared ${run} issue`)).toBeVisible({ timeout: 15_000 });
const sharedCopy = (names: string[]) => names.some((name) => name.endsWith(`:${shared.id}`));
await expect.poll(async () => sharedCopy(await searchIndexDatabases(page))).toBe(true);
+ // Confirm the active socket (after any dev StrictMode reconnect) is
+ // registered on the server and delivering realtime events before removal.
+ await owner.createIssue(`shared ${run} ws-ready`);
+ await expect(page.getByText(`shared ${run} ws-ready`)).toBeVisible({ timeout: 15_000 });
+
await owner.removeMember(memberId);
// The client relocates to a workspace the user still has; the removed
diff --git a/e2e/navigation.spec.ts b/e2e/navigation.spec.ts
index 8029398f11..d287187aad 100644
--- a/e2e/navigation.spec.ts
+++ b/e2e/navigation.spec.ts
@@ -6,27 +6,25 @@ const ROUTE_CHANGE_TIMEOUT = 30000;
test.describe("Navigation", () => {
test.beforeEach(async ({ page }) => {
await loginAsDefault(page);
- await page.waitForLoadState("networkidle");
});
test("rail navigation works", async ({ page }) => {
const rail = appRail(page);
- await rail.getByRole("link", { name: "Inbox" }).click();
- await expect(page).toHaveURL(/\/inbox/, { timeout: ROUTE_CHANGE_TIMEOUT });
- await waitForPageText(page, "Inbox");
- // Each destination renames the browser tab after itself (MUL-6222).
- await expect(page).toHaveTitle("Inbox | Multica");
-
// Team lands on its first page, Agents.
await rail.getByRole("link", { name: "Team" }).click();
await expect(page).toHaveURL(/\/agents/, { timeout: ROUTE_CHANGE_TIMEOUT });
await waitForPageText(page, "Agents");
+ // Each destination renames the browser tab after itself (MUL-6222).
await expect(page).toHaveTitle("Agents | Multica");
+ await rail.getByRole("link", { name: "Chat" }).click();
+ await expect(page).toHaveURL(/\/chat/, { timeout: ROUTE_CHANGE_TIMEOUT });
+ await expect(page).toHaveTitle("Chat | Multica");
+
// Work lands on its first page, Issues.
await rail.getByRole("link", { name: "Work", exact: true }).click();
await expect(page).toHaveURL(/\/issues/, { timeout: ROUTE_CHANGE_TIMEOUT });
- await waitForPageText(page, "Issues");
+ await waitForPageText(page, "All issues");
await expect(page).toHaveTitle("Issues | Multica");
});
@@ -35,8 +33,8 @@ test.describe("Navigation", () => {
await expect(page).toHaveURL(/\/settings/, { timeout: ROUTE_CHANGE_TIMEOUT });
await waitForPageText(page, "Settings");
- await expect(page.getByRole("tab", { name: "General" })).toBeVisible();
- await expect(page.getByRole("tab", { name: "Members" })).toBeVisible();
+ await expect(page.getByRole("link", { name: "General" })).toBeVisible();
+ await expect(page.getByRole("link", { name: "Members" })).toBeVisible();
});
test("agents page shows agent list", async ({ page }) => {
diff --git a/e2e/onboarding-smoke.spec.ts b/e2e/onboarding-smoke.spec.ts
index f8b5d1c817..db2599a556 100644
--- a/e2e/onboarding-smoke.spec.ts
+++ b/e2e/onboarding-smoke.spec.ts
@@ -10,11 +10,10 @@ import { waitForPageText } from "./helpers";
// landing on /onboarding.
const EMAIL = `onboarding-v3-${Date.now()}@localhost`;
-const SHOTS_DIR = "../shots-rail";
test.use({ viewport: { width: 1440, height: 900 } });
-test("onboarding — welcome → about you (answer path)", async ({ page }) => {
+test("onboarding — welcome → about you (answer path)", async ({ page }, testInfo) => {
const api = new TestApiClient();
await api.login(EMAIL, "OBv3 Tester");
const token = api.getToken();
@@ -27,7 +26,7 @@ test("onboarding — welcome → about you (answer path)", async ({ page }) => {
// 1. Welcome screen
await expect(page.getByRole("button", { name: "Continue on web" })).toBeVisible({ timeout: 15000 });
- await page.screenshot({ path: `${SHOTS_DIR}/01-welcome.png`, fullPage: false });
+ await page.screenshot({ path: testInfo.outputPath("01-welcome.png"), fullPage: false });
// Click Continue on web to advance to About you
await page.getByRole("button", { name: "Continue on web" }).click();
@@ -49,7 +48,7 @@ test("onboarding — welcome → about you (answer path)", async ({ page }) => {
).toBeVisible();
await expect(page.getByText("How did you hear about Multica?")).toHaveCount(0);
await page.waitForTimeout(500);
- await page.screenshot({ path: `${SHOTS_DIR}/02-about-you.png` });
+ await page.screenshot({ path: testInfo.outputPath("02-about-you.png") });
// Answer both groups, then Continue → workspace step.
await page.getByRole("radio", { name: /Engineer \/ developer/i }).click();
@@ -62,7 +61,7 @@ test("onboarding — welcome → about you (answer path)", async ({ page }) => {
page.locator('[aria-current="step"]').filter({ hasText: "Workspace" }),
).toBeVisible();
await page.waitForTimeout(600);
- await page.screenshot({ path: `${SHOTS_DIR}/03-workspace.png` });
+ await page.screenshot({ path: testInfo.outputPath("03-workspace.png") });
// 4. Runtime step — the rail should now show two completed steps and mark
// "Meet Mika" current.
@@ -72,10 +71,10 @@ test("onboarding — welcome → about you (answer path)", async ({ page }) => {
page.locator('[aria-current="step"]').filter({ hasText: "Meet Mika" }),
).toBeVisible({ timeout: 20000 });
await page.waitForTimeout(800);
- await page.screenshot({ path: `${SHOTS_DIR}/06-runtime.png` });
+ await page.screenshot({ path: testInfo.outputPath("06-runtime.png") });
});
-test("onboarding — one skip clears the whole questionnaire step", async ({ page }) => {
+test("onboarding — one skip clears the whole questionnaire step", async ({ page }, testInfo) => {
const api = new TestApiClient();
await api.login(`skip-${Date.now()}@localhost`, "Skipper");
const token = api.getToken();
@@ -91,10 +90,10 @@ test("onboarding — one skip clears the whole questionnaire step", async ({ pag
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByRole("heading", { name: /Name your workspace/i })).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(600);
- await page.screenshot({ path: `${SHOTS_DIR}/04-after-skip.png` });
+ await page.screenshot({ path: testInfo.outputPath("04-after-skip.png") });
});
-test("onboarding — zh-Hans renders Chinese labels", async ({ page, context, baseURL }) => {
+test("onboarding — zh-Hans renders Chinese labels", async ({ page, context, baseURL }, testInfo) => {
await context.addCookies([
{
name: "multica-locale",
@@ -108,17 +107,17 @@ test("onboarding — zh-Hans renders Chinese labels", async ({ page, context, ba
await page.addInitScript((t) => localStorage.setItem("multica_token", t), token);
await page.goto("/onboarding", { waitUntil: "domcontentloaded" });
- await waitForPageText(page, "在 web 端继续");
+ await waitForPageText(page, "在网页端继续");
// Click the CTA by name. `getByRole("button").first()` used to stand in for
// it, but the welcome screen renders the pinned Log out button first in DOM
// order — so this step was signing the user out and the assertions below
// were waiting on a page that had already redirected to login.
- await page.getByRole("button", { name: "在 web 端继续" }).click();
+ await page.getByRole("button", { name: "在网页端继续" }).click();
// About-you screen — Chinese headline + both sub-questions.
await expect(page.getByText("简单介绍一下你自己。")).toBeVisible({ timeout: 10000 });
await expect(page.getByText("哪一项最符合你?")).toBeVisible();
await page.waitForTimeout(500);
- await page.screenshot({ path: `${SHOTS_DIR}/05-about-you-zh.png` });
+ await page.screenshot({ path: testInfo.outputPath("05-about-you-zh.png") });
});
diff --git a/e2e/plugin-surface-document.spec.ts b/e2e/plugin-surface-document.spec.ts
deleted file mode 100644
index d9d230ef40..0000000000
--- a/e2e/plugin-surface-document.spec.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { expect, test } from "@playwright/test";
-import { buildSurfaceDocument } from "../packages/views/plugins/surface-document";
-
-/**
- * Real Chromium coverage for behavior jsdom does not implement: executing a
- * sandboxed srcdoc document, reporting errors from a dynamically inserted
- * script, and firing page lifecycle events when the host rewrites srcdoc.
- */
-
-test.describe("plugin surface document (real Chromium, sandboxed srcdoc)", () => {
- test("a host-authored srcdoc reload is not reported as hostile navigation", async ({ page }) => {
- const first = buildSurfaceDocument({
- code: "parent.postMessage({ type: 'plugin-test-ran' }, '*');",
- grantedScopes: [],
- theme: {},
- });
- const themed = buildSurfaceDocument({
- code: "parent.postMessage({ type: 'plugin-test-ran' }, '*');",
- grantedScopes: [],
- theme: { "--background": "white" },
- });
-
- await page.setContent("<!doctype html><body></body>");
- await page.evaluate((srcdoc) => {
- const state = { ran: 0, navigated: 0 };
- (window as unknown as { __surfaceState: typeof state }).__surfaceState = state;
- window.addEventListener("message", (event) => {
- const type = (event.data as { type?: string } | null)?.type;
- if (type === "plugin-test-ran") state.ran++;
- if (type === "multica:plugin-surface-navigated") state.navigated++;
- });
- const frame = document.createElement("iframe");
- frame.id = "surface";
- frame.sandbox.add("allow-scripts");
- frame.srcdoc = srcdoc;
- document.body.appendChild(frame);
- }, first);
-
- await expect.poll(() => page.evaluate(() =>
- (window as unknown as { __surfaceState: { ran: number } }).__surfaceState.ran,
- )).toBe(1);
-
- await page.evaluate((srcdoc) => {
- document.querySelector<HTMLIFrameElement>("#surface")!.srcdoc = srcdoc;
- }, themed);
- await expect.poll(() => page.evaluate(() =>
- (window as unknown as { __surfaceState: { ran: number } }).__surfaceState.ran,
- )).toBe(2);
-
- expect(await page.evaluate(() =>
- (window as unknown as { __surfaceState: { navigated: number } }).__surfaceState.navigated,
- )).toBe(0);
- });
-
- test("reports a synchronous plugin error even when the host listener mounts late", async ({ page }) => {
- const documentWithError = buildSurfaceDocument({
- code: "throw new Error('plugin failed during bootstrap');",
- grantedScopes: [],
- theme: {},
- });
-
- await page.setContent("<!doctype html><body></body>");
- await page.evaluate((srcdoc) => {
- const frame = document.createElement("iframe");
- frame.id = "surface";
- frame.sandbox.add("allow-scripts");
- frame.srcdoc = srcdoc;
- document.body.appendChild(frame);
- }, documentWithError);
-
- // The guest has already executed and failed before the host starts
- // listening. A one-shot postMessage is lost in this ordering.
- await page.waitForTimeout(300);
- await page.evaluate(() => {
- (window as unknown as { __surfaceErrors: number }).__surfaceErrors = 0;
- window.addEventListener("message", (event) => {
- if ((event.data as { type?: string } | null)?.type !== "multica:plugin-surface-error") return;
- const frame = document.querySelector<HTMLIFrameElement>("#surface")!;
- if (event.source !== frame.contentWindow) return;
- (window as unknown as { __surfaceErrors: number }).__surfaceErrors++;
- frame.contentWindow!.postMessage({ type: "multica:plugin-surface-error-ack" }, "*");
- });
- });
-
- await expect.poll(() => page.evaluate(() =>
- (window as unknown as { __surfaceErrors: number }).__surfaceErrors,
- )).toBe(1);
- });
-});
diff --git a/e2e/project-resource-ref.spec.ts b/e2e/project-resource-ref.spec.ts
index 3da01ee7bd..2c1b35d221 100644
--- a/e2e/project-resource-ref.spec.ts
+++ b/e2e/project-resource-ref.spec.ts
@@ -16,11 +16,17 @@ test("pins, edits and clears a repository's checkout ref", async ({ page }) => {
await page.goto(`/${slug}/projects`, { waitUntil: "domcontentloaded" });
await waitForPageText(page, "Projects");
- await page.getByRole("button", { name: /new project/i }).first().click();
+ await page
+ .getByRole("heading", { name: "All projects" })
+ .locator("../..")
+ .getByRole("button", { name: /new project/i })
+ .first()
+ .click();
// TitleEditor is a contenteditable, not an <input> with a placeholder attr.
await page.getByRole("textbox", { name: /project title/i }).fill("Release line");
- await page.getByRole("button", { name: /repos/i }).first().click();
+ await page.getByRole("button", { name: /more options/i }).click();
+ await page.getByRole("menuitem", { name: /repos/i }).click();
await page.getByPlaceholder(/github\.com\/owner\/repo/i).fill(REPO);
await page.getByLabel(/starting branch/i).fill("release/2026-09");
await page.getByRole("button", { name: /^add$/i }).click();
diff --git a/e2e/rail-order.spec.ts b/e2e/rail-order.spec.ts
index 0d30886361..c329567afb 100644
--- a/e2e/rail-order.spec.ts
+++ b/e2e/rail-order.spec.ts
@@ -24,7 +24,7 @@ test("rail spaces reorder by drag and keep their order", async ({ page }) => {
await page.evaluate(() => localStorage.removeItem("multica_rail_order"));
await reloadAppPage(page);
- expect(await railOrder(page)).toEqual(["inbox", "work", "team", "chat", "autopilots"]);
+ expect(await railOrder(page)).toEqual(["work", "team", "chat", "autopilots"]);
// A drag that starts but moves nothing must not open Chat on release.
const chat = await page.locator("[data-slot='app-rail'] [data-rail-item='chat']").boundingBox();
@@ -34,19 +34,19 @@ test("rail spaces reorder by drag and keep their order", async ({ page }) => {
await page.mouse.move(chat.x + chat.width / 2, chat.y + chat.height / 2 + 10, { steps: 5 });
await page.mouse.up();
await page.waitForTimeout(300);
- expect(await railOrder(page)).toEqual(["inbox", "work", "team", "chat", "autopilots"]);
+ expect(await railOrder(page)).toEqual(["work", "team", "chat", "autopilots"]);
await expect(page).toHaveURL(new RegExp(`/${slug}/issues`));
- // Dropping Chat on Inbox must not also open Chat.
- await dragOnto(page, "chat", "inbox");
- expect(await railOrder(page)).toEqual(["chat", "inbox", "work", "team", "autopilots"]);
+ // Dropping Chat on Work must not also open Chat.
+ await dragOnto(page, "chat", "work");
+ expect(await railOrder(page)).toEqual(["chat", "work", "team", "autopilots"]);
await expect(page).toHaveURL(new RegExp(`/${slug}/issues`));
- await dragOnto(page, "inbox", "autopilots");
- expect(await railOrder(page)).toEqual(["chat", "work", "team", "autopilots", "inbox"]);
+ await dragOnto(page, "work", "autopilots");
+ expect(await railOrder(page)).toEqual(["chat", "team", "autopilots", "work"]);
await reloadAppPage(page);
- expect(await railOrder(page)).toEqual(["chat", "work", "team", "autopilots", "inbox"]);
+ expect(await railOrder(page)).toEqual(["chat", "team", "autopilots", "work"]);
// A plain click after a drag still works.
await page.locator("[data-rail-item='chat'] a").click();
diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts
index 11d8067b93..bc0232a424 100644
--- a/e2e/settings.spec.ts
+++ b/e2e/settings.spec.ts
@@ -1,5 +1,5 @@
import { test, expect, type Page } from "@playwright/test";
-import { appRail, currentWorkspaceTile, loginAsDefault, waitForPageText } from "./helpers";
+import { currentWorkspaceTile, loginAsDefault, waitForPageText } from "./helpers";
test.describe("Settings", () => {
test("updating workspace name reflects in the rail immediately", async ({
@@ -7,36 +7,45 @@ test.describe("Settings", () => {
}) => {
const workspaceSlug = await loginAsDefault(page);
- // Read the current workspace name from its rail tile
const tile = currentWorkspaceTile(page);
await expect(tile).toBeVisible({ timeout: 15000 });
- const originalName = (await tile.getAttribute("aria-label")) ?? "E2E Workspace";
+
+ // Read the current workspace name from the rail's workspace switcher menu
+ await tile.click();
+ const currentItem = page.getByRole("menu").locator('[role="menuitem"][aria-current="page"]');
+ await expect(currentItem).toBeVisible();
+ const originalName = (await currentItem.locator("span.truncate").innerText()).trim() || "E2E Workspace";
+ await page.keyboard.press("Escape");
+ await expect(page.getByRole("menu")).toBeHidden();
await page.goto(`/${workspaceSlug}/settings?tab=workspace`, { waitUntil: "domcontentloaded" });
- await waitForPageText(page, "General");
+ await waitForPageText(page, "Workspace details");
- // Change workspace name
- const nameInput = page
- .locator('input[type="text"]')
- .first();
- await nameInput.clear();
+ // Change workspace name (General settings auto-save)
+ const nameInput = page.getByRole("textbox", { name: "Name" });
+ await expect(nameInput).toBeVisible();
const newName = "Renamed WS " + Date.now();
await nameInput.fill(newName);
+ await nameInput.blur();
- // Save
- await page.locator("button", { hasText: "Save" }).click();
-
- await expect(page.getByText("Workspace settings saved").first()).toBeVisible({ timeout: 5000 });
-
- // The rail should reflect the new name WITHOUT page refresh
- await expect(appRail(page).getByRole("link", { name: newName })).toBeVisible();
+ // The rail should reflect the new name WITHOUT page refresh (avatar initial + switcher menu)
+ await expect(tile).toHaveText("R", { timeout: 10000 });
+ await tile.click();
+ await expect(
+ page.getByRole("menu").locator('[role="menuitem"][aria-current="page"]'),
+ ).toContainText(newName);
+ await page.keyboard.press("Escape");
+ await expect(page.getByRole("menu")).toBeHidden();
// Restore original name so other tests aren't affected
- await nameInput.clear();
- await nameInput.fill(originalName.trim());
- await page.locator("button", { hasText: "Save" }).click();
- await expect(page.getByText("Workspace settings saved").first()).toBeVisible({ timeout: 5000 });
- await expect(appRail(page).getByRole("link", { name: originalName })).toBeVisible();
+ await nameInput.fill(originalName);
+ await nameInput.blur();
+ await expect(tile).toHaveText(originalName.charAt(0).toUpperCase(), { timeout: 10000 });
+ await tile.click();
+ await expect(
+ page.getByRole("menu").locator('[role="menuitem"][aria-current="page"]'),
+ ).toContainText(originalName);
+ await page.keyboard.press("Escape");
});
// Connected apps are mocked at the network boundary so the flow runs without
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index d002d2b229..b88f35e184 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -1556,7 +1556,6 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
// must neither restore the full page's offset nor leave one behind for it.
const scrollContainerKey = `${isPeek ? "peek" : "main"}:${id}`;
const restoredScrollTop = useRestoredScrollOffset(scrollContainerKey);
- const restoreScrollRef = useRestoredScrollRef(scrollContainerKey);
// Whether this issue's comment-highlight deep link already landed here
// (survives the tab's unmount, unlike didHighlightRef below): a remount
// that restores the view must not re-run the jump.
@@ -1658,16 +1657,6 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
onHighlightLandedRef.current = onHighlightLanded;
const writeViewState = useViewStateWriter();
const rightSidebarShortcutTargetRef = useRef<HTMLDivElement | null>(null);
- const attachScrollContainer = useCallback(
- (el: HTMLDivElement | null) => {
- // The peek has no sidebar, so it must not claim the toggle shortcut.
- rightSidebarShortcutTargetRef.current = isPeek ? null : el;
- setScrollContainerEl(el);
- setScrollContainerWidth(el?.clientWidth ?? 0);
- restoreScrollRef(el);
- },
- [isPeek, restoreScrollRef],
- );
const [pendingPostedCommentId, setPendingPostedCommentId] = useState<string | null>(null);
const scrollToTimelineBottom = useCallback((commentId: string) => {
setPendingPostedCommentId(commentId);
@@ -2239,6 +2228,23 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
ready: timelineReady,
skipRestore: isPeek || pendingHighlight,
});
+ // When a deep-link landing or semantic reading anchor owns scroll, disable
+ // pixel scroll restoration so its settle-window hold cannot yank the scroll
+ // container back to a stale pixel offset while virtualized rows measure.
+ const ownsTimelineScroll = isPeek || landingAtMount || pendingHighlight || !!readingAnchor;
+ const restoreScrollRef = useRestoredScrollRef(scrollContainerKey, {
+ disabled: ownsTimelineScroll,
+ });
+ const attachScrollContainer = useCallback(
+ (el: HTMLDivElement | null) => {
+ // The peek has no sidebar, so it must not claim the toggle shortcut.
+ rightSidebarShortcutTargetRef.current = isPeek ? null : el;
+ setScrollContainerEl(el);
+ setScrollContainerWidth(el?.clientWidth ?? 0);
+ restoreScrollRef(el);
+ },
+ [isPeek, restoreScrollRef],
+ );
useEffect(() => {
const container = scrollContainerEl;
if (!readingAnchor || !container || issueLoading || timelineLoading || commentTasksLoading) return;
@@ -4573,7 +4579,7 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
ref={virtuosoRef}
customScrollParent={scrollContainerEl}
data={items}
- initialScrollTop={readingAnchor ? undefined : restoredScrollTop}
+ initialScrollTop={ownsTimelineScroll ? undefined : restoredScrollTop}
heightEstimates={timelineHeightEstimates}
increaseViewportBy={timelineOverscan}
totalListHeightChanged={handleTimelineHeightChange}
diff --git a/packages/views/issues/utils/scroll-to-timeline-comment.ts b/packages/views/issues/utils/scroll-to-timeline-comment.ts
index 2977745fd9..7090b04c06 100644
--- a/packages/views/issues/utils/scroll-to-timeline-comment.ts
+++ b/packages/views/issues/utils/scroll-to-timeline-comment.ts
@@ -92,6 +92,7 @@ export function scrollToTimelineComment({
let rafId = 0;
let mountFrames = 0;
let frames = 0;
+ let settledFrames = 0;
let last = -1;
let cancelled = false;
let mounted = false;
@@ -160,10 +161,14 @@ export function scrollToTimelineComment({
return;
}
const target = alignTarget(current);
- if (Math.abs(target - last) > 1 && ++frames < 30) {
- last = target;
- rafId = requestAnimationFrame(align);
- } else finish();
+ if (Math.abs(target - last) <= 1) {
+ if (++settledFrames >= 3 || ++frames >= 30) { finish(); return; }
+ } else {
+ settledFrames = 0;
+ if (++frames >= 30) { finish(); return; }
+ }
+ last = target;
+ rafId = requestAnimationFrame(align);
};
rafId = requestAnimationFrame(align);
};
diff --git a/packages/views/platform/scroll-restoration.test.tsx b/packages/views/platform/scroll-restoration.test.tsx
index aa0daee46c..7cb6bd160c 100644
--- a/packages/views/platform/scroll-restoration.test.tsx
+++ b/packages/views/platform/scroll-restoration.test.tsx
@@ -181,4 +181,54 @@ describe("useRestoredScrollRef while the content settles", () => {
nextFrame();
expect(view.el.scrollTop).toBe(0);
});
+
+ it("skips pixel restore when disabled while still registering capture", () => {
+ const view = scroller(3000);
+ const registerScrollRoot = vi.fn(() => vi.fn());
+ const get = vi.fn(() => ({ top: 1500, height: 3000 }));
+ const adapter: ScrollRestorationAdapter = { get, registerScrollRoot };
+ const { result } = renderHook(
+ () => useRestoredScrollRef("main", { disabled: true }),
+ {
+ wrapper: ({ children }) => (
+ <ScrollRestorationProvider adapter={adapter}>{children}</ScrollRestorationProvider>
+ ),
+ },
+ );
+
+ result.current(view.el);
+ expect(get).not.toHaveBeenCalled();
+ expect(registerScrollRoot).toHaveBeenCalledWith("main", view.el);
+ expect(view.el.scrollTop).toBe(0);
+
+ view.resize(3400);
+ nextFrame();
+ expect(view.el.scrollTop).toBe(0);
+ });
+
+ it("cancels an active settle hold if disabled flips true after attach", () => {
+ const view = scroller(3000);
+ const adapter = makeAdapter(() => ({ top: 1500, height: 3000 }));
+ const { result, rerender } = renderHook(
+ ({ disabled }: { disabled: boolean }) =>
+ useRestoredScrollRef("main", { disabled }),
+ {
+ initialProps: { disabled: false },
+ wrapper: ({ children }) => (
+ <ScrollRestorationProvider adapter={adapter}>{children}</ScrollRestorationProvider>
+ ),
+ },
+ );
+ const refBefore = result.current;
+ result.current(view.el);
+ expect(view.el.scrollTop).toBe(1500);
+
+ rerender({ disabled: true });
+ expect(result.current).toBe(refBefore);
+
+ view.el.scrollTop = 400;
+ view.resize(3400);
+ nextFrame();
+ expect(view.el.scrollTop).toBe(400);
+ });
});
diff --git a/packages/views/platform/scroll-restoration.tsx b/packages/views/platform/scroll-restoration.tsx
index 44634f98b8..2899bb6e76 100644
--- a/packages/views/platform/scroll-restoration.tsx
+++ b/packages/views/platform/scroll-restoration.tsx
@@ -4,7 +4,9 @@ import {
createContext,
useCallback,
useContext,
+ useEffect,
useMemo,
+ useRef,
type ReactNode,
} from "react";
@@ -222,19 +224,37 @@ function restoreOffsets(
*/
export function useRestoredScrollRef(
containerKey: string,
+ options?: {
+ /** Skip applying the saved pixel offset while keeping unmount capture active
+ * (e.g. when semantic anchor restoration or a deep-link landing owns scroll). */
+ disabled?: boolean;
+ },
): (el: HTMLElement | null) => void {
const adapter = useContext(ScrollRestorationContext);
+ const disabled = options?.disabled ?? false;
+ const disabledRef = useRef(disabled);
+ disabledRef.current = disabled;
+ const cancelRestoreRef = useRef<(() => void) | undefined>(undefined);
+
+ useEffect(() => {
+ if (disabled) {
+ cancelRestoreRef.current?.();
+ cancelRestoreRef.current = undefined;
+ }
+ }, [disabled]);
+
return useMemo(() => {
let capture: (() => void) | undefined;
- let cancelRestore: (() => void) | undefined;
return (el: HTMLElement | null) => {
- cancelRestore?.();
- cancelRestore = undefined;
+ cancelRestoreRef.current?.();
+ cancelRestoreRef.current = undefined;
capture?.();
capture = undefined;
if (!el) return;
- const saved = adapter?.get(containerKey);
- if (saved) cancelRestore = restoreOffsets(el, saved);
+ if (!disabledRef.current) {
+ const saved = adapter?.get(containerKey);
+ if (saved) cancelRestoreRef.current = restoreOffsets(el, saved);
+ }
capture = adapter?.registerScrollRoot?.(containerKey, el);
};
}, [adapter, containerKey]);
diff --git a/server/internal/realtime/membership.go b/server/internal/realtime/membership.go
index 270518f9cb..1c58dc13ce 100644
--- a/server/internal/realtime/membership.go
+++ b/server/internal/realtime/membership.go
@@ -131,22 +131,28 @@ func memberRemovalCandidate(raw []byte) bool {
}
func (h *Hub) stopClient(client *Client, notice []byte, deadline time.Time) {
- client.stopped.Store(true)
+ firstStop := !client.stopped.Swap(true)
+ // Write the removal notice before removeClient closes client.send: closing
+ // send wakes writePump, which acquires writeMu and calls defer conn.Close()
+ // on return, racing with both TryLock() and WriteMessage() here.
+ if client.conn != nil {
+ if firstStop && len(notice) != 0 && time.Now().Before(deadline) && client.writeMu.TryLock() {
+ client.conn.SetWriteDeadline(deadline)
+ _ = client.conn.WriteMessage(websocket.TextMessage, notice)
+ _ = client.conn.WriteMessage(
+ websocket.CloseMessage,
+ websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
+ )
+ client.writeMu.Unlock()
+ }
+ client.conn.Close()
+ }
h.removeClient(client)
client.closeSend() // a writer may stop before registration completes
for range client.send {
// Discard queued content, including frames whose writer is doing a
// membership lookup concurrently. The writer also checks stopped.
}
- if client.conn == nil {
- return
- }
- if len(notice) != 0 && time.Now().Before(deadline) && client.writeMu.TryLock() {
- client.conn.SetWriteDeadline(deadline)
- _ = client.conn.WriteMessage(websocket.TextMessage, notice)
- client.writeMu.Unlock()
- }
- client.conn.Close()
}
// Capture the bounded batch BEFORE querying membership. A successful lookup
diff --git a/server/internal/realtime/membership_test.go b/server/internal/realtime/membership_test.go
index 2acd77f217..d91c16d93e 100644
--- a/server/internal/realtime/membership_test.go
+++ b/server/internal/realtime/membership_test.go
@@ -644,3 +644,23 @@ func TestMembershipBatchCoalescesAndDeduplicatesIdentities(t *testing.T) {
t.Fatal("one queued wave was checked with multiple queries")
}
}
+
+func TestDisconnectMemberDeliversRemovalNoticeBeforeWritePumpClosesConn(t *testing.T) {
+ for range 30 {
+ hub := NewHub()
+ var revoked atomic.Bool
+ mc := membershipFunc(func(context.Context, string, string) (bool, error) {
+ return !revoked.Load(), nil
+ })
+ server := membershipServer(t, hub, mc)
+ conn := connectWS(t, server)
+ waitFor(t, "client registration", func() bool { return totalClients(hub) == 1 })
+
+ revoked.Store(true)
+ hub.DisconnectMember(testWorkspaceID, testUserID, "member-id")
+ wantMembershipFrame(t, conn, "member:removed")
+ wantMembershipClosed(t, conn)
+ conn.Close()
+ server.Close()
+ }
+}