Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): preserve native context menus in authenticated shells
Generb91f6e6ac1bb
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex 60943452d..f0a87a427 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -64,6 +64,7 @@ export const SPEC_SECONDS = {"51-share-image-assets.spec.ts": 20,"52-chat-composer-ordered-list.spec.ts": 90,"53-mobile-inbox-surface.spec.ts": 45,+ "54-authenticated-context-menu-policy.spec.ts": 55,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex f63d31ae7..96985fc03 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -70,7 +70,7 @@ describe("planE2eShards", () => {expect(first).toHaveLength(E2E_SHARD_COUNT)expect([...assigned].sort()).toEqual(specs)expect(new Set(assigned).size).toBe(specs.length)- expect(totals.sort((left, right) => left - right)).toEqual([491, 492, 493, 494, 495])+ expect(totals.sort((left, right) => left - right)).toEqual([502, 502, 505, 505, 506])expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)})diff --git a/src/web/src/app/(app)/layout.tsx b/src/web/src/app/(app)/layout.tsxindex 668024b8b..2042dae5a 100644--- a/src/web/src/app/(app)/layout.tsx+++ b/src/web/src/app/(app)/layout.tsx@@ -4,6 +4,7 @@ import { getSession } from "@/lib/session";import { SignupTracker } from "@/components/signup-tracker";import { SigninTracker } from "@/components/signin-tracker";import { DaemonUpdateNotice } from "@/components/daemon-update-notice";+import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary";export const metadata: Metadata = {robots: { index: false, follow: false },@@ -18,11 +19,11 @@ export default async function AppLayout({if (!session) redirect("/sign-in");return (- <>+ <AuthenticatedContextMenuBoundary><SignupTracker /><SigninTracker /><DaemonUpdateNotice userId={session.user.id} />{children}- </>+ </AuthenticatedContextMenuBoundary>);}diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsxindex ed035b397..680f804ff 100644--- a/src/web/src/app/c/layout.tsx+++ b/src/web/src/app/c/layout.tsx@@ -8,6 +8,7 @@ import { avatarInitial } from "@/lib/community/avatar"import { SignupTracker } from "@/components/signup-tracker"import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"import { resolveCommunityModulePlan } from "@/lib/community/community-route"+import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary"// The invite landing page is preview-first: a logged-out visitor must be able// to see it (and only hit the login wall on Join). It's a standalone@@ -50,9 +51,9 @@ export default function CommunityLayout({}return (- <>+ <AuthenticatedContextMenuBoundary><SignupTracker redirectTo="/c/me/machines" /><CommunityShell currentUser={currentUser}>{children}</CommunityShell>- </>+ </AuthenticatedContextMenuBoundary>)}diff --git a/src/web/src/components/authenticated-context-menu-boundary.test.ts b/src/web/src/components/authenticated-context-menu-boundary.test.tsnew file mode 100644index 000000000..f1552c523--- /dev/null+++ b/src/web/src/components/authenticated-context-menu-boundary.test.ts@@ -0,0 +1,112 @@+import { createElement } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import {+ AuthenticatedContextMenuBoundary,+ createAuthenticatedContextMenuHandler,+ useAuthenticatedContextMenuPolicy,+} from "./authenticated-context-menu-boundary"++let pathname = "/c/me"++vi.mock("next/navigation", () => ({+ usePathname: () => pathname,+}))++describe("AuthenticatedContextMenuBoundary", () => {+ const addEventListener = vi.fn()+ const removeEventListener = vi.fn()++ beforeEach(() => {+ pathname = "/c/me"+ addEventListener.mockReset()+ removeEventListener.mockReset()+ vi.stubGlobal("document", { addEventListener, removeEventListener })+ vi.stubGlobal("window", { getSelection: () => null })+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ it("prevents only product disposition without stopping propagation", () => {+ const preventDefault = vi.fn()+ const stopPropagation = vi.fn()+ const stopImmediatePropagation = vi.fn()+ const event = { preventDefault, stopPropagation, stopImmediatePropagation } as unknown as MouseEvent++ createAuthenticatedContextMenuHandler(() => "product")(event)+ expect(preventDefault).toHaveBeenCalledOnce()+ expect(stopPropagation).not.toHaveBeenCalled()+ expect(stopImmediatePropagation).not.toHaveBeenCalled()++ preventDefault.mockClear()+ createAuthenticatedContextMenuHandler(() => "native")(event)+ expect(preventDefault).not.toHaveBeenCalled()+ expect(stopPropagation).not.toHaveBeenCalled()+ expect(stopImmediatePropagation).not.toHaveBeenCalled()+ })++ it("owns exactly one capture listener and removes it on unmount", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(+ AuthenticatedContextMenuBoundary,+ null,+ createElement("span", null, "child"),+ ))+ })+ expect(addEventListener).toHaveBeenCalledOnce()+ expect(addEventListener).toHaveBeenCalledWith("contextmenu", expect.any(Function), { capture: true })++ await act(async () => renderer.unmount())+ expect(removeEventListener).toHaveBeenCalledOnce()+ expect(removeEventListener).toHaveBeenCalledWith(+ "contextmenu",+ addEventListener.mock.calls[0]?.[1],+ { capture: true },+ )+ })++ it("removes ownership on workspace invite navigation and restores it once", async () => {+ function Status() {+ return createElement("span", null, useAuthenticatedContextMenuPolicy() ? "owned" : "native")+ }+ const tree = () => createElement(+ AuthenticatedContextMenuBoundary,+ null,+ createElement(Status),+ )+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(tree())+ })+ expect(renderer.root.findByType("span").children).toEqual(["owned"])++ pathname = "/invite/token"+ await act(async () => renderer.update(tree()))+ expect(renderer.root.findByType("span").children).toEqual(["native"])+ expect(removeEventListener).toHaveBeenCalledOnce()++ pathname = "/w/demo/home"+ await act(async () => renderer.update(tree()))+ expect(renderer.root.findByType("span").children).toEqual(["owned"])+ expect(addEventListener).toHaveBeenCalledTimes(2)+ await act(async () => renderer.unmount())+ })++ it("never owns an initially excluded invite route", async () => {+ pathname = "/invite/token"+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(+ AuthenticatedContextMenuBoundary,+ null,+ createElement("span", null, "invite"),+ ))+ })+ expect(addEventListener).not.toHaveBeenCalled()+ await act(async () => renderer.unmount())+ expect(removeEventListener).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/components/authenticated-context-menu-boundary.tsx b/src/web/src/components/authenticated-context-menu-boundary.tsxnew file mode 100644index 000000000..f77872fe8--- /dev/null+++ b/src/web/src/components/authenticated-context-menu-boundary.tsx@@ -0,0 +1,54 @@+"use client"++import { createContext, useCallback, useContext, useEffect, useMemo } from "react"+import { usePathname } from "next/navigation"+import {+ contextMenuDisposition,+ isNativeContextMenuPolicyExcludedPath,+ type ContextMenuDisposition,+} from "@/lib/authenticated-context-menu-policy"++export type AuthenticatedContextMenuPolicy = {+ disposition(event: MouseEvent): ContextMenuDisposition+}++const AuthenticatedContextMenuPolicyContext = createContext<AuthenticatedContextMenuPolicy | null>(null)++export function createAuthenticatedContextMenuHandler(+ disposition: AuthenticatedContextMenuPolicy["disposition"],+) {+ return (event: MouseEvent) => {+ if (disposition(event) === "product") event.preventDefault()+ }+}++export function useAuthenticatedContextMenuPolicy() {+ return useContext(AuthenticatedContextMenuPolicyContext)+}++export function AuthenticatedContextMenuBoundary({ children }: { children: React.ReactNode }) {+ const pathname = usePathname()+ const enabled = !isNativeContextMenuPolicyExcludedPath(pathname)+ const disposition = useCallback((event: MouseEvent) => contextMenuDisposition({+ event,+ selection: window.getSelection(),+ ownerDocument: document,+ }), [])+ const policy = useMemo<AuthenticatedContextMenuPolicy | null>(+ () => enabled ? { disposition } : null,+ [disposition, enabled],+ )++ useEffect(() => {+ if (!policy || typeof document === "undefined") return+ const handler = createAuthenticatedContextMenuHandler(policy.disposition)+ document.addEventListener("contextmenu", handler, { capture: true })+ return () => document.removeEventListener("contextmenu", handler, { capture: true })+ }, [policy])++ return (+ <AuthenticatedContextMenuPolicyContext.Provider value={policy}>+ {children}+ </AuthenticatedContextMenuPolicyContext.Provider>+ )+}diff --git a/src/web/src/components/community/messages/message.render.test.ts b/src/web/src/components/community/messages/message.render.test.tsindex ee247db71..ec07502cc 100644--- a/src/web/src/components/community/messages/message.render.test.ts+++ b/src/web/src/components/community/messages/message.render.test.ts@@ -768,14 +768,7 @@ describe("Message desktop text selection", () => {expect(selectionBelongsToRow(null, rowElement)).toBe(false)})- it("preserves the native context menu for a selection inside the row", () => {- vi.stubGlobal("window", {- getSelection: () => ({- isCollapsed: false,- anchorNode: insideAnchor,- focusNode: insideFocus,- }),- })+ it("delegates desktop selection contextmenu policy to the authenticated boundary", () => {let renderer: TestRenderer.ReactTestRendereract(() => {renderer = TestRenderer.create(makeTree({@@ -790,45 +783,7 @@ describe("Message desktop text selection", () => {&& node.props.className.includes("group relative -mx-2"),)- const stopPropagation = vi.fn()- const preventDefault = vi.fn()- act(() => row.props.onContextMenuCapture({- currentTarget: rowElement,- stopPropagation,- preventDefault,- }))-- expect(stopPropagation).toHaveBeenCalledOnce()- expect(preventDefault).not.toHaveBeenCalled()- act(() => renderer!.unmount())- })-- it("keeps Alook's context menu for a row with no active selection", () => {- vi.stubGlobal("window", { getSelection: () => null })- let renderer: TestRenderer.ReactTestRenderer- act(() => {- renderer = TestRenderer.create(makeTree({- m: baseMsg(),- onOpenThread: vi.fn(),- onCopy: vi.fn(),- }), { createNodeMock: () => genericMock })- })-- const row = renderer!.root.find(- (node) => typeof node.props.className === "string"- && node.props.className.includes("group relative -mx-2"),- )-- const stopPropagation = vi.fn()- const preventDefault = vi.fn()- act(() => row.props.onContextMenuCapture({- currentTarget: rowElement,- stopPropagation,- preventDefault,- }))-- expect(stopPropagation).not.toHaveBeenCalled()- expect(preventDefault).not.toHaveBeenCalled()+ expect(row.props.onContextMenuCapture).toBeUndefined()act(() => renderer!.unmount())})})diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsxindex b57554ee3..8ff3bd775 100644--- a/src/web/src/components/community/messages/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -338,16 +338,6 @@ function MessageImpl({: undefined}onFocusCapture={activate}onKeyDownCapture={activate}- onContextMenuCapture={interactive && hoverCapable- ? (event) => {- if (!selectionBelongsToRow(window.getSelection(), event.currentTarget)) return-- // Stop before Base UI's trigger and document listeners see the- // event. Deliberately do not preventDefault: the browser must stay- // in charge of the native menu for copying the selected fragment.- event.stopPropagation()- }- : undefined}onTouchStart={interactive && !hoverCapable? () => {touchStartedAt.current = performance.now()diff --git a/src/web/src/components/ui/context-menu.test.ts b/src/web/src/components/ui/context-menu.test.tsnew file mode 100644index 000000000..7f22225f5--- /dev/null+++ b/src/web/src/components/ui/context-menu.test.ts@@ -0,0 +1,409 @@+import { createElement, type ReactElement, type ReactNode } from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"++const policy = vi.hoisted(() => ({ disposition: vi.fn() }))++vi.mock("@/components/authenticated-context-menu-boundary", () => ({+ useAuthenticatedContextMenuPolicy: () => policy,+}))++vi.mock("@base-ui/react/context-menu", async () => {+ const ReactModule = await import("react")+ return {+ ContextMenu: {+ Root: ({ children, ...props }: { children?: ReactNode }) =>+ ReactModule.createElement("mock-context-root", props, children),+ Trigger: ({ render, children, ...props }: { render?: ReactElement; children?: ReactNode }) =>+ ReactModule.cloneElement(render ?? ReactModule.createElement("div"), props, children),+ Portal: ({ children }: { children?: ReactNode }) =>+ ReactModule.createElement("mock-portal", null, children),+ Positioner: ({ children }: { children?: ReactNode }) =>+ ReactModule.createElement("mock-positioner", null, children),+ Popup: ({ children }: { children?: ReactNode }) =>+ ReactModule.createElement("mock-popup", null, children),+ },+ }+})++import {+ ContextMenu,+ ContextMenuTrigger,+ isKeyboardContextMenu,+ isSecondaryContextPointer,+ nativeContextGestureMatches,+} from "./context-menu"++type Listener = EventListenerOrEventListenerObject++function pointerEvent({+ pointerId = 1,+ button = 2,+ ctrlKey = false,+ clientX = 20,+ clientY = 30,+}: {+ pointerId?: number+ button?: number+ ctrlKey?: boolean+ clientX?: number+ clientY?: number+} = {}) {+ return {+ pointerId,+ pointerType: "mouse",+ button,+ ctrlKey,+ clientX,+ clientY,+ timeStamp: 100,+ } as PointerEvent+}++function triggerTree(disabled = false, id = "trigger") {+ return createElement(+ ContextMenu,+ { disabled },+ createElement(ContextMenuTrigger, {+ render: createElement("button", { id }),+ }),+ )+}++function handlers(renderer: TestRenderer.ReactTestRenderer) {+ const root = renderer.root.findByType("mock-context-root")+ const trigger = renderer.root.findByType("button")+ return { root, trigger }+}++function syntheticPointer(nativeEvent: PointerEvent, currentTarget: EventTarget) {+ return { nativeEvent, currentTarget }+}++function syntheticContext(nativeEvent: PointerEvent, currentTarget: EventTarget) {+ return {+ nativeEvent,+ currentTarget,+ preventBaseUIHandler: vi.fn(),+ }+}++describe("ContextMenu native gesture bypass", () => {+ const listeners = new Map<string, Set<Listener>>()+ const addEventListener = vi.fn((type: string, listener: Listener) => {+ const current = listeners.get(type) ?? new Set()+ current.add(listener)+ listeners.set(type, current)+ })+ const removeEventListener = vi.fn((type: string, listener: Listener) => {+ listeners.get(type)?.delete(listener)+ })++ beforeEach(() => {+ policy.disposition.mockReset()+ listeners.clear()+ addEventListener.mockClear()+ removeEventListener.mockClear()+ vi.stubGlobal("window", { addEventListener, removeEventListener })+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ it("recognizes right-click and control-click only", () => {+ expect(isSecondaryContextPointer({ button: 2, ctrlKey: false } as MouseEvent)).toBe(true)+ expect(isSecondaryContextPointer({ button: 0, ctrlKey: true } as MouseEvent)).toBe(true)+ expect(isSecondaryContextPointer({ button: 0, ctrlKey: false } as MouseEvent)).toBe(false)+ expect(isSecondaryContextPointer({ button: 1, ctrlKey: false } as MouseEvent)).toBe(false)+ })++ it("recognizes the keyboard menu key and Shift+F10 only", () => {+ expect(isKeyboardContextMenu({ key: "ContextMenu", shiftKey: false } as KeyboardEvent)).toBe(true)+ expect(isKeyboardContextMenu({ key: "F10", shiftKey: true } as KeyboardEvent)).toBe(true)+ expect(isKeyboardContextMenu({ key: "F10", shiftKey: false } as KeyboardEvent)).toBe(false)+ expect(isKeyboardContextMenu({ key: "Enter", shiftKey: true } as KeyboardEvent)).toBe(false)+ })++ it("routes keyboard activation through contextmenu without overriding caller cancellation", async () => {+ policy.disposition.mockReturnValue("product")+ const dispatched: Event[] = []+ const source = {+ dispatchEvent: vi.fn((event: Event) => {+ dispatched.push(event)+ return true+ }),+ getBoundingClientRect: () => ({ left: 10, top: 20, width: 40, height: 20 }),+ }+ class ContextEvent {+ type: string+ bubbles: boolean+ cancelable: boolean+ button: number+ clientX: number+ clientY: number++ constructor(type: string, init: MouseEventInit) {+ this.type = type+ this.bubbles = init.bubbles ?? false+ this.cancelable = init.cancelable ?? false+ this.button = init.button ?? 0+ this.clientX = init.clientX ?? 0+ this.clientY = init.clientY ?? 0+ }+ }+ vi.stubGlobal("MouseEvent", ContextEvent)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(triggerTree())+ })+ const preventDefault = vi.fn()+ handlers(renderer).trigger.props.onKeyDown({+ currentTarget: source,+ defaultPrevented: false,+ nativeEvent: { key: "F10", shiftKey: true },+ preventDefault,+ })+ expect(preventDefault).toHaveBeenCalledOnce()+ expect(source.dispatchEvent).toHaveBeenCalledOnce()+ expect(dispatched[0]).toMatchObject({+ type: "contextmenu",+ bubbles: true,+ cancelable: true,+ button: 2,+ clientX: 30,+ clientY: 30,+ })++ const callerCancelled = vi.fn((event: { preventDefault(): void }) => event.preventDefault())+ await act(async () => {+ renderer.update(createElement(+ ContextMenu,+ null,+ createElement(ContextMenuTrigger, {+ onKeyDown: callerCancelled,+ render: createElement("button", { id: "trigger" }),+ }),+ ))+ })+ const cancelledEvent = {+ currentTarget: source,+ defaultPrevented: false,+ nativeEvent: { key: "ContextMenu", shiftKey: false },+ preventDefault() {+ this.defaultPrevented = true+ },+ }+ handlers(renderer).trigger.props.onKeyDown(cancelledEvent)+ expect(callerCancelled).toHaveBeenCalledOnce()+ expect(source.dispatchEvent).toHaveBeenCalledOnce()+ await act(async () => renderer.unmount())+ })++ it("matches source and pointer identity with a MouseEvent fallback", () => {+ const source = {}+ const gesture = {+ token: 1,+ source,+ pointerId: 7,+ pointerType: "mouse",+ button: 2,+ ctrlKey: false,+ startedAt: 1,+ clientX: 2,+ clientY: 3,+ }+ expect(nativeContextGestureMatches(gesture, pointerEvent({ pointerId: 7 }), source)).toBe(true)+ expect(nativeContextGestureMatches(gesture, pointerEvent({ pointerId: 8 }), source)).toBe(false)+ expect(nativeContextGestureMatches(gesture, pointerEvent({ pointerId: 7 }), {})).toBe(false)+ expect(nativeContextGestureMatches(+ { ...gesture, pointerId: null },+ { button: 2, ctrlKey: false } as MouseEvent,+ source,+ )).toBe(true)+ })++ it("disables for one matching native gesture and restores the next custom gesture", async () => {+ policy.disposition.mockReturnValue("native")+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(triggerTree())+ })+ const source = {}+ const nativeEvent = pointerEvent()+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(syntheticPointer(nativeEvent, source))+ })+ expect(handlers(renderer).root.props.disabled).toBe(true)++ const contextEvent = syntheticContext(nativeEvent, source)+ await act(async () => {+ handlers(renderer).trigger.props.onContextMenu(contextEvent)+ })+ expect(contextEvent.preventBaseUIHandler).toHaveBeenCalledOnce()+ expect(handlers(renderer).root.props.disabled).toBe(false)++ policy.disposition.mockReturnValue("product")+ const nextContext = syntheticContext(pointerEvent(), source)+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(syntheticPointer(pointerEvent(), source))+ handlers(renderer).trigger.props.onContextMenu(nextContext)+ })+ expect(nextContext.preventBaseUIHandler).not.toHaveBeenCalled()+ expect(handlers(renderer).root.props.disabled).toBe(false)+ await act(async () => renderer.unmount())+ })++ it("clears a stale arm on mismatched contextmenu without consuming it", async () => {+ policy.disposition.mockReturnValue("native")+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(triggerTree())+ })+ const source = {}+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(+ syntheticPointer(pointerEvent({ pointerId: 1 }), source),+ )+ })+ const mismatch = syntheticContext(pointerEvent({ pointerId: 2 }), source)+ await act(async () => handlers(renderer).trigger.props.onContextMenu(mismatch))+ expect(mismatch.preventBaseUIHandler).not.toHaveBeenCalled()+ expect(handlers(renderer).root.props.disabled).toBe(false)+ await act(async () => renderer.unmount())+ })++ it("keeps a different trigger root enabled while another root is armed", async () => {+ policy.disposition.mockReturnValue("native")+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(+ "section",+ null,+ triggerTree(false, "first"),+ triggerTree(false, "second"),+ ))+ })+ const roots = renderer.root.findAllByType("mock-context-root")+ const triggers = renderer.root.findAllByType("button")+ const firstSource = {}+ await act(async () => {+ triggers[0]!.props.onPointerDownCapture(syntheticPointer(pointerEvent(), firstSource))+ })+ expect(roots[0]!.props.disabled).toBe(true)+ expect(roots[1]!.props.disabled).toBe(false)++ policy.disposition.mockReturnValue("product")+ const secondContext = syntheticContext(pointerEvent(), {})+ await act(async () => triggers[1]!.props.onContextMenu(secondContext))+ expect(secondContext.preventBaseUIHandler).not.toHaveBeenCalled()+ expect(roots[1]!.props.disabled).toBe(false)++ await act(async () => triggers[0]!.props.onPointerLeave({ currentTarget: firstSource }))+ expect(roots[0]!.props.disabled).toBe(false)+ await act(async () => renderer.unmount())+ })++ it.each(["pointerup", "pointercancel"])("clears on matching global %s", async (type) => {+ policy.disposition.mockReturnValue("native")+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(triggerTree())+ })+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(+ syntheticPointer(pointerEvent({ pointerId: 4 }), {}),+ )+ })+ expect(handlers(renderer).root.props.disabled).toBe(true)+ const listener = [...(listeners.get(type) ?? [])][0] as EventListener+ await act(async () => listener(pointerEvent({ pointerId: 4 })))+ expect(handlers(renderer).root.props.disabled).toBe(false)+ await act(async () => renderer.unmount())+ })++ it("clears on pointer leave and blur", async () => {+ policy.disposition.mockReturnValue("native")+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(triggerTree())+ })+ const source = {}+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(syntheticPointer(pointerEvent(), source))+ handlers(renderer).trigger.props.onPointerLeave({ currentTarget: source })+ })+ expect(handlers(renderer).root.props.disabled).toBe(false)++ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(syntheticPointer(pointerEvent(), source))+ })+ const blur = [...(listeners.get("blur") ?? [])][0] as EventListener+ await act(async () => blur({} as Event))+ expect(handlers(renderer).root.props.disabled).toBe(false)+ await act(async () => renderer.unmount())+ })++ it("fences a late cleanup from an older replaced gesture", async () => {+ policy.disposition.mockReturnValue("native")+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(triggerTree())+ })+ const source = {}+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(+ syntheticPointer(pointerEvent({ pointerId: 1 }), source),+ )+ })+ const stalePointerUp = [...(listeners.get("pointerup") ?? [])][0] as EventListener+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(+ syntheticPointer(pointerEvent({ pointerId: 2 }), source),+ )+ })+ await act(async () => stalePointerUp(pointerEvent({ pointerId: 1 })))+ expect(handlers(renderer).root.props.disabled).toBe(true)++ const currentPointerUp = [...(listeners.get("pointerup") ?? [])][0] as EventListener+ await act(async () => currentPointerUp(pointerEvent({ pointerId: 2 })))+ expect(handlers(renderer).root.props.disabled).toBe(false)+ await act(async () => renderer.unmount())+ })++ it("never overrides caller disabled ownership", async () => {+ policy.disposition.mockReturnValue("native")+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(triggerTree(true))+ })+ const source = {}+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(syntheticPointer(pointerEvent(), source))+ })+ expect(handlers(renderer).root.props.disabled).toBe(true)+ expect(policy.disposition).not.toHaveBeenCalled()++ await act(async () => renderer.update(triggerTree(false)))+ expect(handlers(renderer).root.props.disabled).toBe(false)+ await act(async () => renderer.unmount())+ })++ it("removes armed global cleanup listeners on unmount", async () => {+ policy.disposition.mockReturnValue("native")+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(triggerTree())+ })+ await act(async () => {+ handlers(renderer).trigger.props.onPointerDownCapture(syntheticPointer(pointerEvent(), {}))+ })+ expect(listeners.get("pointerup")?.size).toBe(1)+ expect(listeners.get("pointercancel")?.size).toBe(1)+ expect(listeners.get("blur")?.size).toBe(1)+ await act(async () => renderer.unmount())+ expect(listeners.get("pointerup")?.size).toBe(0)+ expect(listeners.get("pointercancel")?.size).toBe(0)+ expect(listeners.get("blur")?.size).toBe(0)+ })+})diff --git a/src/web/src/components/ui/context-menu.tsx b/src/web/src/components/ui/context-menu.tsxindex 11d9addc1..a60c99425 100644--- a/src/web/src/components/ui/context-menu.tsx+++ b/src/web/src/components/ui/context-menu.tsx@@ -5,9 +5,119 @@ import { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menuimport { cn } from "@/lib/utils"import { ChevronRightIcon, CheckIcon } from "lucide-react"+import { useAuthenticatedContextMenuPolicy } from "@/components/authenticated-context-menu-boundary"-function ContextMenu({ ...props }: ContextMenuPrimitive.Root.Props) {- return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />+type NativeContextGesture = {+ token: number+ source: EventTarget+ pointerId: number | null+ pointerType: string+ button: number+ ctrlKey: boolean+ startedAt: number+ clientX: number+ clientY: number+}++type NativeContextGestureController = {+ current(): NativeContextGesture | null+ arm(event: React.PointerEvent<HTMLElement>): void+ clear(token: number): void+}++const NativeContextGestureContext = React.createContext<NativeContextGestureController | null>(null)++function contextPointerId(event: MouseEvent): number | null {+ return "pointerId" in event && typeof event.pointerId === "number"+ ? event.pointerId+ : null+}++export function isSecondaryContextPointer({ button, ctrlKey }: Pick<MouseEvent, "button" | "ctrlKey">) {+ return button === 2 || (button === 0 && ctrlKey)+}++export function isKeyboardContextMenu({ key, shiftKey }: Pick<KeyboardEvent, "key" | "shiftKey">) {+ return key === "ContextMenu" || (key === "F10" && shiftKey)+}++export function nativeContextGestureMatches(+ gesture: NativeContextGesture,+ event: MouseEvent,+ source: EventTarget,+): boolean {+ if (gesture.source !== source || !isSecondaryContextPointer(event)) return false+ const pointerId = contextPointerId(event)+ return gesture.pointerId === null || pointerId === null || gesture.pointerId === pointerId+}++function ContextMenu({ disabled, ...props }: ContextMenuPrimitive.Root.Props) {+ const policy = useAuthenticatedContextMenuPolicy()+ const nextTokenRef = React.useRef(0)+ const gestureRef = React.useRef<NativeContextGesture | null>(null)+ const [gesture, setGesture] = React.useState<NativeContextGesture | null>(null)++ const clear = React.useCallback((token: number) => {+ if (gestureRef.current?.token !== token) return+ gestureRef.current = null+ setGesture((current) => current?.token === token ? null : current)+ }, [])++ const arm = React.useCallback((event: React.PointerEvent<HTMLElement>) => {+ if (disabled || !policy || !isSecondaryContextPointer(event.nativeEvent)) return+ if (policy.disposition(event.nativeEvent) !== "native") return+ const nativeEvent = event.nativeEvent+ const next: NativeContextGesture = {+ token: ++nextTokenRef.current,+ source: event.currentTarget,+ pointerId: contextPointerId(nativeEvent),+ pointerType: nativeEvent.pointerType,+ button: nativeEvent.button,+ ctrlKey: nativeEvent.ctrlKey,+ startedAt: nativeEvent.timeStamp,+ clientX: nativeEvent.clientX,+ clientY: nativeEvent.clientY,+ }+ gestureRef.current = next+ setGesture(next)+ }, [disabled, policy])++ React.useEffect(() => {+ if (!gesture) return+ const { token, pointerId } = gesture+ const clearMatchingPointer = (event: PointerEvent) => {+ if (pointerId === null || pointerId === event.pointerId) clear(token)+ }+ const clearOnBlur = () => clear(token)+ window.addEventListener("pointerup", clearMatchingPointer, true)+ window.addEventListener("pointercancel", clearMatchingPointer, true)+ window.addEventListener("blur", clearOnBlur)+ return () => {+ window.removeEventListener("pointerup", clearMatchingPointer, true)+ window.removeEventListener("pointercancel", clearMatchingPointer, true)+ window.removeEventListener("blur", clearOnBlur)+ }+ }, [clear, gesture])++ React.useEffect(() => () => {+ gestureRef.current = null+ }, [])++ const controller = React.useMemo<NativeContextGestureController>(() => ({+ current: () => gestureRef.current,+ arm,+ clear,+ }), [arm, clear])++ return (+ <NativeContextGestureContext.Provider value={controller}>+ <ContextMenuPrimitive.Root+ data-slot="context-menu"+ disabled={disabled || gesture !== null}+ {...props}+ />+ </NativeContextGestureContext.Provider>+ )}function ContextMenuPortal({ ...props }: ContextMenuPrimitive.Portal.Props) {@@ -18,12 +128,54 @@ function ContextMenuPortal({ ...props }: ContextMenuPrimitive.Portal.Props) {function ContextMenuTrigger({className,+ onPointerDownCapture,+ onPointerLeave,+ onContextMenu,+ onKeyDown,...props}: ContextMenuPrimitive.Trigger.Props) {+ const policy = useAuthenticatedContextMenuPolicy()+ const gestureController = React.useContext(NativeContextGestureContext)return (<ContextMenuPrimitive.Triggerdata-slot="context-menu-trigger"className={cn("select-none", className)}+ onPointerDownCapture={(event) => {+ onPointerDownCapture?.(event)+ gestureController?.arm(event)+ }}+ onPointerLeave={(event) => {+ onPointerLeave?.(event)+ const gesture = gestureController?.current()+ if (gesture && gesture.source === event.currentTarget) {+ gestureController?.clear(gesture.token)+ }+ }}+ onContextMenu={(event) => {+ onContextMenu?.(event)+ const gesture = gestureController?.current()+ if (!gesture) return+ const matches = nativeContextGestureMatches(+ gesture,+ event.nativeEvent,+ event.currentTarget,+ ) && policy?.disposition(event.nativeEvent) === "native"+ if (matches) event.preventBaseUIHandler()+ gestureController?.clear(gesture.token)+ }}+ onKeyDown={(event) => {+ onKeyDown?.(event)+ if (event.defaultPrevented || !isKeyboardContextMenu(event.nativeEvent)) return+ event.preventDefault()+ const rect = event.currentTarget.getBoundingClientRect()+ event.currentTarget.dispatchEvent(new MouseEvent("contextmenu", {+ bubbles: true,+ cancelable: true,+ button: 2,+ clientX: rect.left + rect.width / 2,+ clientY: rect.top + rect.height / 2,+ }))+ }}{...props}/>)diff --git a/src/web/src/lib/authenticated-context-menu-policy.test.ts b/src/web/src/lib/authenticated-context-menu-policy.test.tsnew file mode 100644index 000000000..bd42b66d3--- /dev/null+++ b/src/web/src/lib/authenticated-context-menu-policy.test.ts@@ -0,0 +1,276 @@+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"+import {+ contextMenuDisposition,+ contextMenuElementPath,+ hasNativeContextMenuEscape,+ isEditableContextPath,+ isNativeContextMenuPolicyExcludedPath,+ selectionContainsClientPoint,+} from "./authenticated-context-menu-policy"++class FakeElement {+ tagName: string+ type = ""+ disabled = false+ readOnly = false+ isContentEditable = false+ parentElement: FakeElement | null = null+ private attributes = new Map<string, string>()++ constructor(tagName = "div") {+ this.tagName = tagName.toUpperCase()+ if (this.tagName === "INPUT") this.type = "text"+ }++ append(...children: FakeElement[]) {+ for (const child of children) child.parentElement = this+ }++ setAttribute(name: string, value: string) {+ this.attributes.set(name, value)+ }++ closest(selector: string): FakeElement | null {+ if (+ selector === "input, textarea"+ && (this.tagName === "INPUT" || this.tagName === "TEXTAREA")+ ) {+ return this+ }+ if (+ selector === '[data-native-context-menu="true"]'+ && this.attributes.get("data-native-context-menu") === "true"+ ) {+ return this+ }+ return this.parentElement?.closest(selector) ?? null+ }+}++function element(tagName = "div") {+ return new FakeElement(tagName) as unknown as Element+}++function eventAt(target: Element, clientX = 15, clientY = 15, path: EventTarget[] = [target]) {+ return {+ target,+ clientX,+ clientY,+ composedPath: () => path,+ }+}++function rect(overrides: Partial<DOMRect> = {}): DOMRect {+ return {+ x: 10,+ y: 10,+ left: 10,+ top: 10,+ right: 20,+ bottom: 20,+ width: 10,+ height: 10,+ toJSON: () => ({}),+ ...overrides,+ }+}++function selectionWith({+ collapsed = false,+ text = "selected",+ rects = [rect()],+ pointInRange = true,+}: {+ collapsed?: boolean+ text?: string+ rects?: DOMRect[]+ pointInRange?: boolean+} = {}): Selection {+ const range = {+ getClientRects: () => rects,+ isPointInRange: () => pointInRange,+ }+ return {+ isCollapsed: collapsed,+ rangeCount: 1,+ toString: () => text,+ getRangeAt: () => range,+ } as unknown as Selection+}++function ownerDocumentWith(caret: { node: Node; offset: number } | null): Document {+ return {+ caretPositionFromPoint: () => caret && ({+ offsetNode: caret.node,+ offset: caret.offset,+ }),+ } as unknown as Document+}++describe("authenticated context-menu policy", () => {+ beforeAll(() => {+ vi.stubGlobal("Element", FakeElement)+ })++ afterAll(() => {+ vi.unstubAllGlobals()+ })++ it("excludes only the standalone workspace invite route", () => {+ expect(isNativeContextMenuPolicyExcludedPath("/invite/token")).toBe(true)+ expect(isNativeContextMenuPolicyExcludedPath("/invite/token/")).toBe(true)+ expect(isNativeContextMenuPolicyExcludedPath("/invite")).toBe(false)+ expect(isNativeContextMenuPolicyExcludedPath("/invite/token/extra")).toBe(false)+ expect(isNativeContextMenuPolicyExcludedPath("/c/invite/token")).toBe(false)+ expect(isNativeContextMenuPolicyExcludedPath("/w/demo/home")).toBe(false)+ })++ it("uses the composed element path before a retargeted event target", () => {+ const retargeted = element()+ const deepest = element("span")+ const nonElement = {} as EventTarget+ expect(contextMenuElementPath(eventAt(retargeted, 0, 0, [deepest, retargeted, nonElement])))+ .toEqual([deepest, retargeted])+ expect(contextMenuElementPath({+ target: retargeted,+ composedPath: () => [nonElement],+ })).toEqual([retargeted])+ })++ it.each(["text", "search", "email", "url", "tel", "password", "number"])(+ "keeps an enabled %s input native",+ (type) => {+ const input = element("input") as unknown as FakeElement+ input.type = type+ expect(isEditableContextPath([input as unknown as Element])).toBe(true)+ input.readOnly = true+ expect(isEditableContextPath([input as unknown as Element])).toBe(false)+ input.readOnly = false+ input.disabled = true+ expect(isEditableContextPath([input as unknown as Element])).toBe(false)+ },+ )++ it("recognizes default text input, textarea descendants, and effective contenteditable", () => {+ const input = element("input") as unknown as FakeElement+ const textarea = element("textarea") as unknown as FakeElement+ const inputChild = element("span") as unknown as FakeElement+ const editableChild = element("span") as unknown as FakeElement+ input.append(inputChild)+ editableChild.isContentEditable = true++ expect(isEditableContextPath([input as unknown as Element])).toBe(true)+ expect(isEditableContextPath([textarea as unknown as Element])).toBe(true)+ expect(isEditableContextPath([inputChild as unknown as Element])).toBe(true)+ expect(isEditableContextPath([editableChild as unknown as Element])).toBe(true)+ textarea.readOnly = true+ expect(isEditableContextPath([textarea as unknown as Element])).toBe(false)+ })++ it.each(["checkbox", "radio", "range", "file", "button", "color", "date"])(+ "keeps a %s input product-owned",+ (type) => {+ const input = element("input") as unknown as FakeElement+ input.type = type+ expect(isEditableContextPath([input as unknown as Element])).toBe(false)+ },+ )++ it("does not infer editability from select or ARIA", () => {+ expect(isEditableContextPath([element("select")])).toBe(false)+ expect(isEditableContextPath([element("div")])).toBe(false)+ })++ it("requires the exact native escape value on the target path or an ancestor", () => {+ const wrapper = element() as unknown as FakeElement+ const child = element("span") as unknown as FakeElement+ const sibling = element("span") as unknown as FakeElement+ wrapper.append(child, sibling)+ wrapper.setAttribute("data-native-context-menu", "true")+ expect(hasNativeContextMenuEscape([child as unknown as Element])).toBe(true)+ wrapper.setAttribute("data-native-context-menu", "false")+ expect(hasNativeContextMenuEscape([child as unknown as Element])).toBe(false)+ wrapper.setAttribute("data-native-context-menu", "")+ expect(hasNativeContextMenuEscape([child as unknown as Element])).toBe(false)+ sibling.setAttribute("data-native-context-menu", "true")+ expect(hasNativeContextMenuEscape([child as unknown as Element])).toBe(false)+ })++ it("requires both selected geometry and caret containment", () => {+ const text = {} as Node+ const ownerDocument = ownerDocumentWith({ node: text, offset: 3 })+ expect(selectionContainsClientPoint(selectionWith(), ownerDocument, { clientX: 15, clientY: 15 })).toBe(true)+ expect(selectionContainsClientPoint(selectionWith(), ownerDocument, { clientX: 25, clientY: 15 })).toBe(false)+ expect(selectionContainsClientPoint(selectionWith({ pointInRange: false }), ownerDocument, {+ clientX: 15,+ clientY: 15,+ })).toBe(false)+ expect(selectionContainsClientPoint(selectionWith({ collapsed: true }), ownerDocument, {+ clientX: 15,+ clientY: 15,+ })).toBe(false)+ expect(selectionContainsClientPoint(selectionWith({ text: "" }), ownerDocument, {+ clientX: 15,+ clientY: 15,+ })).toBe(false)+ expect(selectionContainsClientPoint(selectionWith({ rects: [rect({ width: 0, right: 10 })] }), ownerDocument, {+ clientX: 10,+ clientY: 15,+ })).toBe(false)+ })++ it("falls back to caretRangeFromPoint and accepts selection boundaries", () => {+ const text = {} as Node+ const ownerDocument = {+ caretPositionFromPoint: undefined,+ caretRangeFromPoint: () => ({ startContainer: text, startOffset: 0 }),+ } as unknown as Document+ expect(selectionContainsClientPoint(selectionWith(), ownerDocument, { clientX: 10, clientY: 10 })).toBe(true)+ expect(selectionContainsClientPoint(selectionWith(), ownerDocument, { clientX: 20, clientY: 20 })).toBe(true)+ })++ it("checks every selection range", () => {+ const ownerDocument = ownerDocumentWith({ node: {} as Node, offset: 1 })+ const ranges = [+ { getClientRects: () => [rect({ left: 30, right: 40, x: 30 })], isPointInRange: () => false },+ { getClientRects: () => [rect()], isPointInRange: () => true },+ ]+ const selection = {+ isCollapsed: false,+ rangeCount: 2,+ toString: () => "selected",+ getRangeAt: (index: number) => ranges[index],+ } as unknown as Selection+ expect(selectionContainsClientPoint(selection, ownerDocument, { clientX: 15, clientY: 15 })).toBe(true)+ })++ it("reduces editable, escape, and selected-point facts to native disposition", () => {+ const ownerDocument = ownerDocumentWith({ node: {} as Node, offset: 1 })+ const input = element("input")+ expect(contextMenuDisposition({+ event: eventAt(input),+ selection: null,+ ownerDocument,+ })).toBe("native")++ const escape = element() as unknown as FakeElement+ escape.setAttribute("data-native-context-menu", "true")+ expect(contextMenuDisposition({+ event: eventAt(escape as unknown as Element),+ selection: null,+ ownerDocument,+ })).toBe("native")++ const plain = element()+ expect(contextMenuDisposition({+ event: eventAt(plain),+ selection: selectionWith(),+ ownerDocument,+ })).toBe("native")+ expect(contextMenuDisposition({+ event: eventAt(plain, 30, 30),+ selection: selectionWith(),+ ownerDocument,+ })).toBe("product")+ })+})diff --git a/src/web/src/lib/authenticated-context-menu-policy.ts b/src/web/src/lib/authenticated-context-menu-policy.tsnew file mode 100644index 000000000..bcdd01736--- /dev/null+++ b/src/web/src/lib/authenticated-context-menu-policy.ts@@ -0,0 +1,149 @@+export type ContextMenuDisposition = "native" | "product"++export type ContextMenuPoint = {+ clientX: number+ clientY: number+}++type ContextMenuEventLike = ContextMenuPoint & {+ target: EventTarget | null+ composedPath(): EventTarget[]+}++type CaretPositionDocument = Document & {+ caretPositionFromPoint?: (x: number, y: number) => {+ offsetNode: Node+ offset: number+ } | null+ caretRangeFromPoint?: (x: number, y: number) => Range | null+}++type PointInRange = Pick<Range, "getClientRects" | "isPointInRange">++const TEXT_INPUT_TYPES = new Set([+ "email",+ "number",+ "password",+ "search",+ "tel",+ "text",+ "url",+])++const WORKSPACE_INVITE_PATH = /^\/invite\/[^/]+\/?$/++export function isNativeContextMenuPolicyExcludedPath(pathname: string): boolean {+ return WORKSPACE_INVITE_PATH.test(pathname)+}++export function contextMenuElementPath(+ event: Pick<ContextMenuEventLike, "target" | "composedPath">,+): Element[] {+ const path = event.composedPath()+ const elements = path.filter((target): target is Element => target instanceof Element)+ if (elements.length > 0) return elements+ return event.target instanceof Element ? [event.target] : []+}++function closestTextControl(element: Element): Element | null {+ return element.closest("input, textarea")+}++function isEditableTextControl(element: Element): boolean {+ const tagName = element.tagName.toLowerCase()+ if (tagName === "textarea") {+ const textarea = element as HTMLTextAreaElement+ return !textarea.disabled && !textarea.readOnly+ }+ if (tagName !== "input") return false++ const input = element as HTMLInputElement+ return !input.disabled && !input.readOnly && TEXT_INPUT_TYPES.has(input.type)+}++export function isEditableContextPath(path: readonly Element[]): boolean {+ for (const element of path) {+ if ((element as HTMLElement).isContentEditable) return true+ const control = closestTextControl(element)+ if (control) return isEditableTextControl(control)+ }+ return false+}++export function hasNativeContextMenuEscape(path: readonly Element[]): boolean {+ return path.some((element) => (+ element.closest('[data-native-context-menu="true"]') !== null+ ))+}++function pointInsideRect(rect: DOMRect, point: ContextMenuPoint): boolean {+ if (+ !Number.isFinite(rect.left)+ || !Number.isFinite(rect.right)+ || !Number.isFinite(rect.top)+ || !Number.isFinite(rect.bottom)+ || rect.width <= 0+ || rect.height <= 0+ ) {+ return false+ }+ return point.clientX >= rect.left+ && point.clientX <= rect.right+ && point.clientY >= rect.top+ && point.clientY <= rect.bottom+}++function caretPointFromClientPoint(+ ownerDocument: Document,+ point: ContextMenuPoint,+): { node: Node; offset: number } | null {+ const caretDocument = ownerDocument as CaretPositionDocument+ const position = caretDocument.caretPositionFromPoint?.(point.clientX, point.clientY)+ if (position) return { node: position.offsetNode, offset: position.offset }++ const range = caretDocument.caretRangeFromPoint?.(point.clientX, point.clientY)+ if (!range) return null+ return { node: range.startContainer, offset: range.startOffset }+}++export function selectionContainsClientPoint(+ selection: Selection | null,+ ownerDocument: Document,+ point: ContextMenuPoint,+): boolean {+ if (+ !selection+ || selection.isCollapsed+ || selection.rangeCount === 0+ || selection.toString().length === 0+ ) {+ return false+ }++ const caret = caretPointFromClientPoint(ownerDocument, point)+ if (!caret) return false++ for (let index = 0; index < selection.rangeCount; index += 1) {+ const range = selection.getRangeAt(index) as PointInRange+ const rectContainsPoint = Array.from(range.getClientRects())+ .some((rect) => pointInsideRect(rect, point))+ if (rectContainsPoint && range.isPointInRange(caret.node, caret.offset)) return true+ }+ return false+}++export function contextMenuDisposition({+ event,+ selection,+ ownerDocument,+}: {+ event: ContextMenuEventLike+ selection: Selection | null+ ownerDocument: Document+}): ContextMenuDisposition {+ const path = contextMenuElementPath(event)+ if (isEditableContextPath(path) || hasNativeContextMenuEscape(path)) return "native"+ return selectionContainsClientPoint(selection, ownerDocument, event)+ ? "native"+ : "product"+}diff --git a/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts b/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.tsindex 6d86e8d9c..bc678a2ae 100644--- a/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts+++ b/src/web/src/test/e2e-ui/23-message-selection-context-menu.spec.ts@@ -3,6 +3,33 @@ import { gotoAfterUserWsAuth } from "./_fixtures/actions"import { seedChannel, seedMessage, seedServer } from "./_fixtures/seed"import { tid } from "./_fixtures/testids"+async function observeNextContextMenu(page: import("@playwright/test").Page) {+ await page.evaluate(() => {+ const state = window as typeof window & {+ __contextMenuProbe?: { defaultPrevented: boolean | null; bubbled: boolean }+ }+ state.__contextMenuProbe = { defaultPrevented: null, bubbled: false }+ document.addEventListener("contextmenu", (event) => {+ setTimeout(() => {+ if (state.__contextMenuProbe) {+ state.__contextMenuProbe.defaultPrevented = event.defaultPrevented+ }+ })+ }, { capture: true, once: true })+ document.addEventListener("contextmenu", () => {+ if (state.__contextMenuProbe) state.__contextMenuProbe.bubbled = true+ }, { once: true })+ })+}++async function contextMenuProbe(page: import("@playwright/test").Page) {+ return page.evaluate(() => (+ window as typeof window & {+ __contextMenuProbe?: { defaultPrevented: boolean | null; bubbled: boolean }+ }+ ).__contextMenuProbe)+}+test("selected message text keeps the native context menu", async ({ asUser }) => {const serverId = await seedServer("alice", `Selection Menu ${Date.now()}`)const channelId = await seedChannel("alice", serverId, "selection-menu")@@ -18,9 +45,10 @@ test("selected message text keeps the native context menu", async ({ asUser }) =// Message action overlays (including Base UI's context-menu trigger) mount// lazily after hover. Reproduce the real pointer path before selecting text.await row.hover()- await expect(row.locator('[data-slot="context-menu-trigger"]')).toHaveCount(1)+ const trigger = row.locator('[data-slot="context-menu-trigger"]')+ await expect(trigger).toHaveCount(1)- const selectionPoint = await messageBody.evaluate((element) => {+ const points = await messageBody.evaluate((element) => {const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT)const textNode = walker.nextNode()if (!textNode) throw new Error("message body has no text node")@@ -31,27 +59,42 @@ test("selected message text keeps the native context menu", async ({ asUser }) =selection?.removeAllRanges()selection?.addRange(range)const rect = range.getBoundingClientRect()- return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }+ const bodyRect = element.getBoundingClientRect()+ return {+ selection: { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 },+ outsideSelection: {+ x: Math.min(bodyRect.right - 2, rect.right + Math.max(4, (bodyRect.right - rect.right) / 2)),+ y: rect.top + rect.height / 2,+ },+ }})await expect.poll(() => page.evaluate(() => window.getSelection()?.toString())).toBe("copy only this phrase")- await page.evaluate(() => {- const state = window as typeof window & { __contextMenuDefaultPrevented?: boolean }- delete state.__contextMenuDefaultPrevented- document.addEventListener("contextmenu", (event) => {- setTimeout(() => {- state.__contextMenuDefaultPrevented = event.defaultPrevented- })- }, { capture: true, once: true })- })- await page.mouse.click(selectionPoint.x, selectionPoint.y, { button: "right" })+ await observeNextContextMenu(page)+ await page.mouse.click(points.selection.x, points.selection.y, { button: "right" })- await expect.poll(() => page.evaluate(() => (- window as typeof window & { __contextMenuDefaultPrevented?: boolean }- ).__contextMenuDefaultPrevented)).toBe(false)+ await expect.poll(() => contextMenuProbe(page)).toEqual({+ defaultPrevented: false,+ bubbled: true,+ })await expect(page.locator('[data-slot="context-menu-content"]')).toHaveCount(0)+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString()))+ .toBe("copy only this phrase")++ await observeNextContextMenu(page)+ await page.mouse.click(points.outsideSelection.x, points.outsideSelection.y, { button: "right" })+ const openContextMenu = page.locator('[data-slot="context-menu-content"][data-open]')+ await expect(openContextMenu).toBeVisible()+ await expect.poll(() => contextMenuProbe(page).then((probe) => probe?.defaultPrevented)).toBe(true)+ await page.keyboard.press("Escape")+ await expect(openContextMenu).toHaveCount(0)+ await page.waitForTimeout(150)await page.evaluate(() => window.getSelection()?.removeAllRanges())- await messageBody.click({ button: "right" })- await expect(page.locator('[data-slot="context-menu-content"]')).toBeVisible()+ await trigger.evaluate((element) => {+ element.setAttribute("tabindex", "0")+ element.focus()+ })+ await page.keyboard.press("Shift+F10")+ await expect(openContextMenu).toBeVisible()})diff --git a/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts b/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.tsnew file mode 100644index 000000000..fcb2af1e7--- /dev/null+++ b/src/web/src/test/e2e-ui/54-authenticated-context-menu-policy.spec.ts@@ -0,0 +1,251 @@+import type { Locator, Page } from "@playwright/test"+import { test, expect } from "./_fixtures/community-fixture"+import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"+import { seedChannel, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"++type ContextMenuProbe = {+ defaultPrevented: boolean | null+ bubbled: boolean+}++async function observeNextContextMenu(page: Page) {+ await page.evaluate(() => {+ const state = window as typeof window & { __authenticatedContextMenuProbe?: ContextMenuProbe }+ state.__authenticatedContextMenuProbe = { defaultPrevented: null, bubbled: false }+ document.addEventListener("contextmenu", (event) => {+ setTimeout(() => {+ if (state.__authenticatedContextMenuProbe) {+ state.__authenticatedContextMenuProbe.defaultPrevented = event.defaultPrevented+ }+ })+ }, { capture: true, once: true })+ document.addEventListener("contextmenu", () => {+ if (state.__authenticatedContextMenuProbe) {+ state.__authenticatedContextMenuProbe.bubbled = true+ }+ }, { once: true })+ })+}++async function contextMenuProbe(page: Page) {+ return page.evaluate(() => (+ window as typeof window & { __authenticatedContextMenuProbe?: ContextMenuProbe }+ ).__authenticatedContextMenuProbe)+}++async function rightClickDisposition(+ page: Page,+ target: Locator,+ expectedDefaultPrevented: boolean,+) {+ await observeNextContextMenu(page)+ await target.click({ button: "right" })+ await expect.poll(() => contextMenuProbe(page)).toEqual({+ defaultPrevented: expectedDefaultPrevented,+ bubbled: true,+ })+}++async function installOrdinaryProbe(page: Page) {+ await page.locator("body").evaluate(() => {+ document.querySelector("[data-authenticated-context-menu-probe]")?.remove()+ const probe = document.createElement("div")+ probe.setAttribute("data-authenticated-context-menu-probe", "")+ Object.assign(probe.style, {+ position: "fixed",+ top: "8px",+ right: "8px",+ width: "32px",+ height: "32px",+ zIndex: "2147483646",+ pointerEvents: "auto",+ })+ document.body.appendChild(probe)+ })+ return page.locator("[data-authenticated-context-menu-probe]")+}++async function dispatchSecondaryPointer(+ target: Locator,+ type: "pointerdown" | "pointerup" | "pointercancel",+ pointerId: number,+) {+ await target.dispatchEvent(type, {+ bubbles: true,+ button: 2,+ buttons: type === "pointerdown" ? 2 : 0,+ clientX: 20,+ clientY: 20,+ pointerId,+ pointerType: "mouse",+ })+}++function visibleContextMenu(page: Page) {+ return page.locator('[data-slot="context-menu-content"][data-open]')+}++async function dismissContextMenu(page: Page) {+ await page.keyboard.press("Escape")+ await expect(visibleContextMenu(page)).toHaveCount(0)+ await page.waitForTimeout(150)+}++test("Community owns ordinary context menus and preserves native exceptions", async ({ asUser }) => {+ const serverId = await seedServer("alice", `Context policy ${Date.now()}`)+ const channelId = await seedChannel("alice", serverId, "context-policy")+ const messageId = await seedMessage("alice", channelId, `Context policy row ${Date.now()}`)+ const { page } = await asUser("alice")+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)+ const row = page.getByTestId(tid.message(messageId))+ await row.hover()+ const trigger = row.locator('[data-slot="context-menu-trigger"]')+ await expect(trigger).toHaveCount(1)+ await expect(composerEditable(page)).toBeVisible()+ await page.waitForTimeout(250)+ const writes: string[] = []+ page.on("request", (request) => {+ if (!["GET", "HEAD", "OPTIONS"].includes(request.method())) {+ writes.push(`${request.method()} ${new URL(request.url()).pathname}`)+ }+ })++ for (const sample of [+ { width: 1280, height: 720, colorScheme: "light" as const },+ { width: 639, height: 720, colorScheme: "dark" as const },+ { width: 640, height: 720, colorScheme: "light" as const },+ { width: 390, height: 720, colorScheme: "dark" as const },+ { width: 320, height: 640, colorScheme: "light" as const },+ ]) {+ await page.setViewportSize({ width: sample.width, height: sample.height })+ await page.emulateMedia({ colorScheme: sample.colorScheme })+ await rightClickDisposition(page, await installOrdinaryProbe(page), true)+ }++ await rightClickDisposition(page, composerEditable(page), false)+ await page.setViewportSize({ width: 1280, height: 720 })+ await page.emulateMedia({ colorScheme: "light" })+ await row.hover()+ await expect(trigger).toHaveCount(1)++ await trigger.evaluate((element) => element.setAttribute("data-native-context-menu", "true"))+ await rightClickDisposition(page, trigger, false)+ await expect(visibleContextMenu(page)).toHaveCount(0)++ await trigger.evaluate((element) => element.setAttribute("data-native-context-menu", "true"))+ await dispatchSecondaryPointer(trigger, "pointerdown", 31)+ await page.waitForTimeout(50)+ await dispatchSecondaryPointer(trigger, "pointerup", 31)+ await page.waitForTimeout(50)+ await trigger.evaluate((element) => element.removeAttribute("data-native-context-menu"))+ await page.evaluate(() => window.getSelection()?.removeAllRanges())+ await rightClickDisposition(page, trigger, true)+ await expect(visibleContextMenu(page)).toBeVisible()+ await dismissContextMenu(page)++ await trigger.evaluate((element) => {+ element.setAttribute("tabindex", "0")+ const htmlElement = element as HTMLElement+ htmlElement.focus()+ })+ await page.keyboard.press("Shift+F10")+ await expect(visibleContextMenu(page)).toBeVisible()+ await dismissContextMenu(page)+ expect(writes).toEqual([])+})++test("workspace menus keep custom behavior while editors and escapes stay native", async ({ asUser }) => {+ const { context, page } = await asUser("alice", { viewport: { width: 1280, height: 720 } })+ const suffix = Date.now().toString(36)+ const slug = `context-policy-${suffix}`+ const workspaceResponse = await context.request.post("/api/workspaces", {+ data: { name: `Context Policy ${suffix}`, slug },+ })+ expect(workspaceResponse.status()).toBe(201)+ const workspace = await workspaceResponse.json() as { id: string; slug: string }+ const onboardedResponse = await context.request.post(`/api/workspaces/${workspace.id}/onboarded`)+ expect(onboardedResponse.status()).toBe(200)++ const titles = [`Context alpha ${suffix}`, `Context beta ${suffix}`]+ for (const title of titles) {+ const issueResponse = await context.request.post(`/api/issues?workspace_id=${workspace.id}`, {+ data: { title, description: "" },+ })+ expect(issueResponse.status()).toBe(201)+ }++ const writes: string[] = []+ page.on("request", (request) => {+ if (!["GET", "HEAD", "OPTIONS"].includes(request.method())) {+ writes.push(`${request.method()} ${new URL(request.url()).pathname}`)+ }+ })+ await page.goto(`/w/${workspace.slug}/issues`, { waitUntil: "commit" })+ await expect(page.getByRole("heading", { name: "Issues" })).toBeVisible({ timeout: 20_000 })+ const first = page.locator('[data-slot="context-menu-trigger"]').filter({ hasText: titles[0] }).first()+ const second = page.locator('[data-slot="context-menu-trigger"]').filter({ hasText: titles[1] }).first()+ await expect(first).toBeVisible()+ await expect(second).toBeVisible()++ await rightClickDisposition(page, first, true)+ await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()+ await dismissContextMenu(page)++ await first.evaluate((element) => element.setAttribute("data-native-context-menu", "true"))+ await rightClickDisposition(page, first, false)+ await expect(visibleContextMenu(page)).toHaveCount(0)++ await first.evaluate((element) => element.setAttribute("data-native-context-menu", "true"))+ await dispatchSecondaryPointer(first, "pointerdown", 41)+ await page.waitForTimeout(50)+ await page.evaluate(() => window.dispatchEvent(new Event("blur")))+ await page.waitForTimeout(50)+ await first.evaluate((element) => element.removeAttribute("data-native-context-menu"))+ await rightClickDisposition(page, first, true)+ await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()+ await dismissContextMenu(page)++ await first.evaluate((element) => element.setAttribute("data-native-context-menu", "true"))+ await dispatchSecondaryPointer(first, "pointerdown", 51)+ await page.waitForTimeout(50)+ await first.evaluate((element) => element.removeAttribute("data-native-context-menu"))+ await rightClickDisposition(page, second, true)+ await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()+ await dismissContextMenu(page)+ await page.evaluate(() => window.dispatchEvent(new Event("blur")))+ await page.waitForTimeout(50)++ await rightClickDisposition(page, first, true)+ await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()+ await dismissContextMenu(page)++ await first.focus()+ await page.keyboard.press("Shift+F10")+ await expect(visibleContextMenu(page).getByRole("menuitem", { name: "Delete" })).toBeVisible()+ await dismissContextMenu(page)++ await page.getByRole("button", { name: "New issue" }).click()+ const titleEditor = page.getByPlaceholder("New issue")+ await expect(titleEditor).toBeVisible()+ await rightClickDisposition(page, titleEditor, false)+ await page.keyboard.press("Escape")+ expect(writes).toEqual([])+})++test("public, auth, and invite routes remain browser owned", async ({ page, asUser }) => {+ for (const route of ["/", "/sign-in", "/c/invite/not-a-real-token"]) {+ await page.goto(route, { waitUntil: "commit" })+ await expect(page.locator("body")).toBeVisible()+ await rightClickDisposition(page, await installOrdinaryProbe(page), false)+ }++ const authenticated = await asUser("alice")+ await authenticated.page.goto("/invite/not-a-real-token", { waitUntil: "commit" })+ await expect(authenticated.page.locator("body")).toBeVisible()+ await rightClickDisposition(+ authenticated.page,+ await installOrdinaryProbe(authenticated.page),+ false,+ )+})