Skip to content

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

Go

perf(desktop,issues): single-router tab sessions (MUL-4741 Phase 2) + trace-driven surface mount/render overhaul (MUL-4474/4750 reland) (#5403)

Naiyuan Qingea03912baf95
diff --git a/.gitignore b/.gitignore
index 1371578f75..864575245d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -68,3 +68,4 @@ server/server
data/
.kilo
.idea
+.gstack/
diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjs
index 3690c9dfda..51f4e97ce9 100644
--- a/apps/desktop/eslint.config.mjs
+++ b/apps/desktop/eslint.config.mjs
@@ -41,4 +41,39 @@ export default [
"no-restricted-syntax": "off",
},
},
+ // Navigation boundary (MUL-4741): the tab Coordinator must be the only
+ // navigation initiator — a Router location change without a Coordinator
+ // token is a protocol error. Application code must not navigate directly;
+ // it goes through the navigation adapter / Coordinator in src/platform.
+ // Remaining legacy sites carry an inline eslint-disable tagged MUL-4741;
+ // the Phase 2 migration removes them one by one, and this rule holding
+ // with zero disables is the machine check that the migration is complete.
+ {
+ files: ["src/renderer/src/**/*.{ts,tsx}"],
+ ignores: ["src/renderer/src/platform/**", "src/renderer/src/**/*.test.*"],
+ rules: {
+ "no-restricted-imports": [
+ "error",
+ {
+ paths: [
+ {
+ name: "react-router-dom",
+ importNames: ["useNavigate", "Navigate"],
+ message:
+ "Direct navigation from application code breaks the Coordinator protocol (MUL-4741). Use the navigation adapter from src/platform instead.",
+ },
+ ],
+ },
+ ],
+ "no-restricted-syntax": [
+ "error",
+ {
+ selector:
+ "CallExpression[callee.object.name='router'][callee.property.name='navigate']",
+ message:
+ "Direct router.navigate from application code breaks the Coordinator protocol (MUL-4741). Route it through the navigation adapter in src/platform.",
+ },
+ ],
+ },
+ },
];
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 8d39f99f21..d00732fc78 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -236,13 +236,13 @@ export function DesktopShell() {
{slug && <WindowToolbar />}
{slug && <AppSidebar topSlot={<SidebarTopSpacer />} searchSlot={<SearchTrigger />} />}
{/* Right side: header + content container */}
- <motion.div layout transition={toolbarMotion} className="flex flex-1 min-w-0 flex-col">
+ <div className="flex flex-1 min-w-0 flex-col">
<MainTopBar />
<MainCanvas>
<TabContent />
{slug && <FloatingChat />}
</MainCanvas>
- </motion.div>
+ </div>
</SidebarProvider>
</div>
{slug && <ModalRegistry />}
diff --git a/apps/desktop/src/renderer/src/components/route-error-page.tsx b/apps/desktop/src/renderer/src/components/route-error-page.tsx
index ab37076afc..ccf9abac50 100644
--- a/apps/desktop/src/renderer/src/components/route-error-page.tsx
+++ b/apps/desktop/src/renderer/src/components/route-error-page.tsx
@@ -1,5 +1,5 @@
import { useMemo } from "react";
-import { useLocation, useNavigate, useRouteError } from "react-router-dom";
+import { useLocation, useRouteError } from "react-router-dom";
import { AlertTriangle, RotateCw, Send, X } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { useModalStore } from "@multica/core/modals";
@@ -45,7 +45,6 @@ export function formatRouteErrorReport({
export function DesktopRouteErrorPage() {
const error = useRouteError();
const location = useLocation();
- const navigate = useNavigate();
const workspaceSlug = location.pathname.split("/").filter(Boolean)[0];
const safeRoute = workspaceSlug ? `/${workspaceSlug}/issues` : null;
const report = useMemo(
@@ -89,7 +88,17 @@ export function DesktopRouteErrorPage() {
Reload tab
</Button>
{safeRoute ? (
- <Button type="button" variant="outline" onClick={() => navigate(safeRoute, { replace: true })}>
+ <Button
+ type="button"
+ variant="outline"
+ // Session mutation, not a router call: the Coordinator projects
+ // the new session URL into the router (MUL-4741 invariant 1).
+ onClick={() =>
+ useTabStore
+ .getState()
+ .navigateActiveSession(safeRoute, { replace: true })
+ }
+ >
Go to issues
</Button>
) : null}
diff --git a/apps/desktop/src/renderer/src/components/tab-content.tsx b/apps/desktop/src/renderer/src/components/tab-content.tsx
index 6113382f06..5f2fb93863 100644
--- a/apps/desktop/src/renderer/src/components/tab-content.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-content.tsx
@@ -1,55 +1,50 @@
-import { Activity, useEffect } from "react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { RouterProvider } from "react-router-dom";
-import { useActiveGroup } from "@/stores/tab-store";
-import { TabNavigationProvider } from "@/platform/navigation";
-import { useTabRouterSync } from "@/hooks/use-tab-router-sync";
-import { useTabScrollRestore } from "@/hooks/use-tab-scroll-restore";
-import type { Tab } from "@/stores/tab-store";
+import { useQueryClient } from "@tanstack/react-query";
+import { ScrollRestorationProvider } from "@multica/views/platform";
+import { useActiveGroup, useTabStore } from "@/stores/tab-store";
+import {
+ createScrollRestorationAdapter,
+ getAppRouter,
+ initTabCoordinator,
+ registerActiveHostElement,
+ registerCoordinatorQueryClient,
+} from "@/platform/tab-coordinator";
/**
- * Inner wrapper rendered inside each tab's RouterProvider. The router
- * reference is stable for a tab's lifetime, so passing it in directly
- * (instead of re-deriving from the store) avoids needless re-renders.
- */
-function TabRouterInner({ tab }: { tab: Tab }) {
- useTabRouterSync(tab.id, tab.router);
- return null;
-}
-
-/**
- * Wraps a tab's subtree so its scroll position survives the round trip
- * through `<Activity mode="hidden">`. Lives inside Activity so the hook's
- * effects cycle with the tab's visibility — see `useTabScrollRestore` for
- * the mechanism. `display: contents` keeps the wrapper transparent to
- * the surrounding flex layout.
- */
-function TabScrollRestoreWrapper({
- tabPath,
- children,
-}: {
- tabPath: string;
- children: React.ReactNode;
-}) {
- const ref = useTabScrollRestore(tabPath);
- return (
- <div ref={ref} style={{ display: "contents" }}>
- {children}
- </div>
- );
-}
-
-/**
- * Renders the active workspace's tabs using Activity for state preservation.
- * Only the active tab is visible; hidden tabs keep their DOM and React state.
+ * Renders the active tab session through THE single app router
+ * (MUL-4741 single-router session architecture).
+ *
+ * Exactly one tab is mounted at a time. Switching tabs remounts this host
+ * (the key includes the tab id), and reload() remounts it without switching
+ * (the key includes mountGeneration). Inactive tabs are pure state — their
+ * restorable view state lives in the session memento, captured by the
+ * Coordinator on deactivation and restored here on mount:
*
- * When switching workspaces, the previous workspace's tabs unmount entirely
- * and the new workspace's tabs mount fresh — cross-workspace state
- * preservation is an explicit non-goal (keeping all workspaces' tabs warm
- * simultaneously would bloat memory and make workspace switching feel
- * anything but "switching").
+ * - restore is PULL-based: views ask for their saved offset while they
+ * mount (ScrollRestorationProvider) — virtualized lists feed it into
+ * their initial render, plain containers assign it at ref-attach. The
+ * first painted frame is already at the restored position; cold
+ * restores show the correct shell + skeletons and settle when data
+ * lands, never a flash of another workspace's data.
*/
export function TabContent() {
const group = useActiveGroup();
+ const generation = useTabStore((s) => s.mountGeneration);
+ const qc = useQueryClient();
+
+ // Wire the Coordinator before the first host mount so the router already
+ // projects the active session's URL when RouterProvider first renders.
+ // useState's initializer is the earliest once-per-tree hook slot; the call
+ // is idempotent.
+ useState(() => {
+ initTabCoordinator();
+ return true;
+ });
+
+ useEffect(() => {
+ registerCoordinatorQueryClient(qc);
+ }, [qc]);
// Sync document.title when switching tabs within the active workspace.
useEffect(() => {
@@ -61,20 +56,35 @@ export function TabContent() {
if (!group) return null;
return (
- <>
- {group.tabs.map((tab) => (
- <Activity
- key={tab.id}
- mode={tab.id === group.activeTabId ? "visible" : "hidden"}
- >
- <TabScrollRestoreWrapper tabPath={tab.path}>
- <TabNavigationProvider router={tab.router}>
- <RouterProvider router={tab.router} />
- <TabRouterInner tab={tab} />
- </TabNavigationProvider>
- </TabScrollRestoreWrapper>
- </Activity>
- ))}
- </>
+ <ActiveTabHost
+ key={`${group.activeTabId}:${generation}`}
+ tabId={group.activeTabId}
+ />
+ );
+}
+
+function ActiveTabHost({ tabId }: { tabId: string }) {
+ const hostRef = useRef<HTMLDivElement>(null);
+ const router = getAppRouter();
+ const scrollAdapter = useMemo(
+ () => createScrollRestorationAdapter(tabId),
+ [tabId],
+ );
+
+ // The Coordinator captures the outgoing memento from this element while
+ // the store notification is still synchronous (pre-unmount).
+ useLayoutEffect(() => {
+ registerActiveHostElement(hostRef.current);
+ return () => registerActiveHostElement(null);
+ }, []);
+
+ // `display: contents` keeps the wrapper transparent to the surrounding
+ // flex layout.
+ return (
+ <div ref={hostRef} style={{ display: "contents" }}>
+ <ScrollRestorationProvider adapter={scrollAdapter}>
+ <RouterProvider router={router} />
+ </ScrollRestorationProvider>
+ </div>
);
}
diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
index 959f8b6b7f..b346b094f1 100644
--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
@@ -1,7 +1,7 @@
import { useEffect } from "react";
-import { Outlet, useNavigate, useParams } from "react-router-dom";
+import { Outlet, useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
-import { WorkspaceSlugProvider, paths } from "@multica/core/paths";
+import { WorkspaceSlugProvider } from "@multica/core/paths";
import {
workspaceBySlugOptions,
workspaceListOptions,
@@ -34,7 +34,6 @@ import { useWindowOverlayStore } from "@/stores/window-overlay-store";
*/
export function WorkspaceRouteLayout() {
const { workspaceSlug } = useParams<{ workspaceSlug: string }>();
- const navigate = useNavigate();
const user = useAuthStore((s) => s.user);
const isAuthLoading = useAuthStore((s) => s.isLoading);
// While a WindowOverlay is open (onboarding, accept-invite, new-workspace),
@@ -47,10 +46,11 @@ export function WorkspaceRouteLayout() {
// signal is still set.
const overlayActive = useWindowOverlayStore((s) => s.overlay !== null);
- // Workspace routes require auth. If user is unauthenticated, bounce to /login.
- useEffect(() => {
- if (!isAuthLoading && !user) navigate(paths.login(), { replace: true });
- }, [isAuthLoading, user, navigate]);
+ // Workspace routes require auth. App.tsx renders <DesktopLoginPage>
+ // instead of the shell whenever `user` is null, so this tree never mounts
+ // unauthenticated — the old in-router bounce to /login was dead defensive
+ // code and violated MUL-4741 invariant 1 (only the Coordinator navigates).
+ // The `!user` early return below keeps the defense without navigating.
const { data: workspace, isFetched: listFetched } = useQuery({
...workspaceBySlugOptions(workspaceSlug ?? ""),
@@ -89,6 +89,7 @@ export function WorkspaceRouteLayout() {
}, [user, listFetched, workspace, hasBeenSeen, wsList]);
if (isAuthLoading) return null;
+ if (!user) return null;
if (!workspaceSlug) return null;
if (!listFetched) return null;
if (!workspace) return null; // auto-heal effect above handles the cleanup
diff --git a/apps/desktop/src/renderer/src/hooks/use-tab-history.ts b/apps/desktop/src/renderer/src/hooks/use-tab-history.ts
index 1c47fbd36e..90f6565d5b 100644
--- a/apps/desktop/src/renderer/src/hooks/use-tab-history.ts
+++ b/apps/desktop/src/renderer/src/hooks/use-tab-history.ts
@@ -1,40 +1,28 @@
import { useCallback } from "react";
-import type { DataRouter } from "react-router-dom";
-import { useActiveTabRouter, useActiveTabHistory } from "@/stores/tab-store";
+import { useTabStore, useActiveTabHistory } from "@/stores/tab-store";
/**
- * Shared hint map so useTabRouterSync can distinguish back vs forward POP.
- * Set before calling router.navigate(-1 | 1), read in the synchronous subscription.
- */
-export const popDirectionHints = new Map<DataRouter, "back" | "forward">();
-
-/**
- * Per-tab back/forward navigation derived from the active workspace's
- * active tab.
+ * Shell back/forward for the active tab (MUL-4741 session architecture).
*
- * Subscribed via primitive selectors so this hook only re-renders when
- * the numeric history state actually changes — path ticks on the active
- * tab (which don't shift historyIndex) don't churn the back/forward
- * buttons.
+ * Per-tab history is a virtual stack on the tab session — the single app
+ * router has no usable history of its own (the Coordinator always navigates
+ * with replace). goBack/goForward move the session's history index; the
+ * Coordinator then reconciles the router to the newly projected URL. No
+ * direction hints, no router.navigate(±1).
*/
export function useTabHistory() {
- const router = useActiveTabRouter();
const { historyIndex, historyLength } = useActiveTabHistory();
const canGoBack = historyIndex > 0;
const canGoForward = historyIndex < historyLength - 1;
const goBack = useCallback(() => {
- if (!router || historyIndex <= 0) return;
- popDirectionHints.set(router, "back");
- router.navigate(-1);
- }, [router, historyIndex]);
+ useTabStore.getState().goBack();
+ }, []);
const goForward = useCallback(() => {
- if (!router || historyIndex >= historyLength - 1) return;
- popDirectionHints.set(router, "forward");
- router.navigate(1);
- }, [router, historyIndex, historyLength]);
+ useTabStore.getState().goForward();
+ }, []);
return { canGoBack, canGoForward, goBack, goForward };
}
diff --git a/apps/desktop/src/renderer/src/hooks/use-tab-router-sync.ts b/apps/desktop/src/renderer/src/hooks/use-tab-router-sync.ts
deleted file mode 100644
index 0f4bfbd0d3..0000000000
--- a/apps/desktop/src/renderer/src/hooks/use-tab-router-sync.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useEffect, useRef } from "react";
-import type { DataRouter } from "react-router-dom";
-import { useTabStore, resolveRouteIcon } from "@/stores/tab-store";
-import { popDirectionHints } from "./use-tab-history";
-
-/**
- * Subscribe to a tab's memory router and sync path + history tracking
- * back into the tab store.
- *
- * Called once per tab inside its RouterProvider subtree.
- */
-export function useTabRouterSync(tabId: string, router: DataRouter) {
- const indexRef = useRef(0);
- const lengthRef = useRef(1);
-
- useEffect(() => {
- // Sync initial state
- const initialPath = router.state.location.pathname;
- const store = useTabStore.getState();
- store.updateTab(tabId, { path: initialPath, icon: resolveRouteIcon(initialPath) });
-
- const unsubscribe = router.subscribe((state) => {
- const { pathname } = state.location;
- const action = state.historyAction;
-
- if (action === "PUSH") {
- indexRef.current += 1;
- lengthRef.current = indexRef.current + 1;
- } else if (action === "POP") {
- // Determine direction from the hint set by goBack/goForward
- const hint = popDirectionHints.get(router);
- popDirectionHints.delete(router);
- if (hint === "forward") {
- indexRef.current = Math.min(indexRef.current + 1, lengthRef.current - 1);
- } else {
- // Default to back
- indexRef.current = Math.max(0, indexRef.current - 1);
- }
- }
- // REPLACE: index and length stay the same
-
- const store = useTabStore.getState();
- store.updateTab(tabId, { path: pathname, icon: resolveRouteIcon(pathname) });
- store.updateTabHistory(tabId, indexRef.current, lengthRef.current);
- });
-
- return unsubscribe;
- }, [tabId, router]);
-}
diff --git a/apps/desktop/src/renderer/src/hooks/use-tab-scroll-restore.test.tsx b/apps/desktop/src/renderer/src/hooks/use-tab-scroll-restore.test.tsx
deleted file mode 100644
index 3f0f25bf76..0000000000
--- a/apps/desktop/src/renderer/src/hooks/use-tab-scroll-restore.test.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { Activity } from "react";
-import { describe, expect, it } from "vitest";
-import { fireEvent, render } from "@testing-library/react";
-import { useTabScrollRestore } from "./use-tab-scroll-restore";
-
-function Harness({ path }: { path: string }) {
- const ref = useTabScrollRestore(path);
- return (
- <div ref={ref} style={{ display: "contents" }}>
- <div
- data-tab-scroll-root
- data-testid="scroller"
- style={{ height: 100, overflow: "auto" }}
- >
- <div style={{ height: 1000 }} />
- </div>
- <div
- data-tab-scroll-root="aside"
- data-testid="aside"
- style={{ height: 100, overflow: "auto" }}
- >
- <div style={{ height: 1000 }} />
- </div>
- <div
- data-testid="unmarked"
- style={{ height: 100, overflow: "auto" }}
- >
- <div style={{ height: 1000 }} />
- </div>
- </div>
- );
-}
-
-function App({ visible, path }: { visible: boolean; path: string }) {
- return (
- <Activity mode={visible ? "visible" : "hidden"}>
- <Harness path={path} />
- </Activity>
- );
-}
-
-function setScroll(el: HTMLElement, top: number) {
- el.scrollTop = top;
- fireEvent.scroll(el);
-}
-
-describe("useTabScrollRestore", () => {
- it("restores scroll position when a tab cycles through hidden -> visible", () => {
- const { rerender, getByTestId } = render(
- <App visible={true} path="/acme/issues/1" />,
- );
- const scroller = getByTestId("scroller") as HTMLElement;
-
- setScroll(scroller, 500);
- expect(scroller.scrollTop).toBe(500);
-
- // Simulate Activity hiding the subtree: layout would drop the offset.
- rerender(<App visible={false} path="/acme/issues/1" />);
- scroller.scrollTop = 0;
-
- rerender(<App visible={true} path="/acme/issues/1" />);
- expect(scroller.scrollTop).toBe(500);
- });
-
- it("restores multiple named scroll roots independently", () => {
- const { rerender, getByTestId } = render(
- <App visible={true} path="/acme/issues/1" />,
- );
- const main = getByTestId("scroller") as HTMLElement;
- const aside = getByTestId("aside") as HTMLElement;
-
- setScroll(main, 300);
- setScroll(aside, 150);
-
- rerender(<App visible={false} path="/acme/issues/1" />);
- main.scrollTop = 0;
- aside.scrollTop = 0;
-
- rerender(<App visible={true} path="/acme/issues/1" />);
- expect(main.scrollTop).toBe(300);
- expect(aside.scrollTop).toBe(150);
- });
-
- it("ignores scroll on elements without the data-tab-scroll-root marker", () => {
- const { rerender, getByTestId } = render(
- <App visible={true} path="/acme/issues/1" />,
- );
- const unmarked = getByTestId("unmarked") as HTMLElement;
-
- setScroll(unmarked, 250);
-
- rerender(<App visible={false} path="/acme/issues/1" />);
- unmarked.scrollTop = 0;
-
- rerender(<App visible={true} path="/acme/issues/1" />);
- expect(unmarked.scrollTop).toBe(0);
- });
-
- it("drops saved offsets when the tab path changes (intra-tab navigation)", () => {
- const { rerender, getByTestId } = render(
- <App visible={true} path="/acme/issues/1" />,
- );
- const scroller = getByTestId("scroller") as HTMLElement;
-
- setScroll(scroller, 500);
-
- // Navigating within the tab swaps the active route — same marker key,
- // different page. We should NOT restore the prior page's offset.
- rerender(<App visible={true} path="/acme/issues/2" />);
- scroller.scrollTop = 0;
-
- rerender(<App visible={false} path="/acme/issues/2" />);
- rerender(<App visible={true} path="/acme/issues/2" />);
- expect(scroller.scrollTop).toBe(0);
- });
-});
diff --git a/apps/desktop/src/renderer/src/hooks/use-tab-scroll-restore.ts b/apps/desktop/src/renderer/src/hooks/use-tab-scroll-restore.ts
deleted file mode 100644
index 3b13273347..0000000000
--- a/apps/desktop/src/renderer/src/hooks/use-tab-scroll-restore.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { useEffect, useLayoutEffect, useRef } from "react";
-
-/**
- * Persist a tab's scroll positions across <Activity> visibility transitions.
- *
- * Tabs render under `<Activity mode="visible|hidden">`, which keeps React
- * state but loses DOM scrollTop — the subtree is taken out of layout while
- * hidden and rejoins with scrollTop=0. This hook records every marked
- * container's `scrollTop` while the tab is visible (continuously, via a
- * capture-phase scroll listener) and restores them in a `useLayoutEffect`
- * the next time the tab becomes visible, before the browser paints.
- *
- * Mark scroll containers in views with `data-tab-scroll-root`. The
- * attribute value is the cache key — defaults to `"main"` for unnamed
- * roots. Most pages have a single scroll container, so a bare attribute
- * is enough; named keys are only needed when a page has multiple
- * independently scrollable regions whose positions must all be restored.
- *
- * When the tab's path changes (intra-tab navigation), the saved offsets
- * are dropped — the new route's container shares the same marker key but
- * is a different page, and restoring the old offset would land the user
- * somewhere arbitrary on the new page.
- *
- * For virtualized children (Virtuoso, react-virtual, etc.) the single
- * synchronous `scrollTop = saved` inside useLayoutEffect isn't enough:
- * the child registers its observers in a passive useEffect that fires
- * later, so at restore time the container's scrollHeight has collapsed
- * to clientHeight and the browser clamps our assignment to 0. The
- * restore loops across rAF frames until the assignment sticks, which
- * lets virtualization rehydrate before we give up.
- */
-export function useTabScrollRestore(tabPath: string) {
- const containerRef = useRef<HTMLDivElement>(null);
- const savedRef = useRef<Map<string, number>>(new Map());
- const prevPathRef = useRef(tabPath);
-
- if (prevPathRef.current !== tabPath) {
- savedRef.current.clear();
- prevPathRef.current = tabPath;
- }
-
- // <Activity> cleans up effects on hidden and re-mounts them on visible,
- // so an empty-deps useLayoutEffect runs exactly on every hidden → visible
- // transition. Restoring here (before the browser paints) handles the
- // common case without a flash.
- //
- // The synchronous set isn't enough for virtualized lists though
- // (issue-detail uses Virtuoso with customScrollParent). Virtuoso wires
- // its scroll/resize observers in a passive useEffect, which fires AFTER
- // useLayoutEffect — so at the moment we try to restore, the spacer that
- // gives the container its tall scrollHeight hasn't been re-established
- // yet. The browser silently clamps `scrollTop = saved` down to 0 because
- // `scrollHeight === clientHeight` in that window. Retry across rAF
- // frames until the set sticks (or we time out around the time any sane
- // child should have laid out, ~500ms).
- useLayoutEffect(() => {
- const root = containerRef.current;
- if (!root) return;
- const els = root.querySelectorAll<HTMLElement>("[data-tab-scroll-root]");
- const cancellers: Array<() => void> = [];
- els.forEach((el) => {
- const key = scrollKey(el);
- const saved = savedRef.current.get(key);
- if (saved === undefined) return;
- el.scrollTop = saved;
- if (el.scrollTop === saved) return;
-
- let cancelled = false;
- let attempts = 0;
- const maxAttempts = 30; // ~500ms at 60fps
- const tick = () => {
- if (cancelled) return;
- el.scrollTop = saved;
- attempts++;
- if (el.scrollTop === saved) return;
- if (attempts >= maxAttempts) return;
- requestAnimationFrame(tick);
- };
- requestAnimationFrame(tick);
- cancellers.push(() => {
- cancelled = true;
- });
- });
- return () => cancellers.forEach((c) => c());
- }, []);
-
- useEffect(() => {
- const root = containerRef.current;
- if (!root) return;
- const onScroll = (e: Event) => {
- const target = e.target;
- if (!(target instanceof HTMLElement)) return;
- if (!target.hasAttribute("data-tab-scroll-root")) return;
- savedRef.current.set(scrollKey(target), target.scrollTop);
- };
- // Scroll events don't bubble, but capture catches them anyway.
- root.addEventListener("scroll", onScroll, { capture: true, passive: true });
- return () => root.removeEventListener("scroll", onScroll, true);
- }, []);
-
- return containerRef;
-}
-
-function scrollKey(el: HTMLElement): string {
- return el.getAttribute("data-tab-scroll-root") || "main";
-}
diff --git a/apps/desktop/src/renderer/src/platform/navigation.test.tsx b/apps/desktop/src/renderer/src/platform/navigation.test.tsx
index a2644c6e41..857ff9e44c 100644
--- a/apps/desktop/src/renderer/src/platform/navigation.test.tsx
+++ b/apps/desktop/src/renderer/src/platform/navigation.test.tsx
@@ -2,128 +2,42 @@ import { describe, expect, it, vi, beforeEach } from "vitest";
import { render } from "@testing-library/react";
import { useEffect } from "react";
-// Shared in-memory state that the mocked tab store reads / mutates. The test
-// records every method call so we can assert openInNewTab does NOT activate
-// the new tab (i.e. setActiveTab is never invoked on the same-workspace path).
-type MockRouter = {
- state: { location: { pathname: string; search: string; hash: string } };
- navigate: ReturnType<typeof vi.fn>;
-};
-
-type MockTab = {
- id: string;
- path: string;
- pinned: boolean;
- router: MockRouter;
-};
-
-function makeMockRouter(pathname: string, search = "", hash = ""): MockRouter {
- return {
- state: { location: { pathname, search, hash } },
- navigate: vi.fn(),
- };
-}
-
-const state = vi.hoisted(() => ({
- activeWorkspaceSlug: "acme" as string | null,
- byWorkspace: {
- acme: {
- activeTabId: "tA",
- tabs: [
- {
- id: "tA",
- path: "/acme/issues",
- pinned: false,
- router: makeMockRouter("/acme/issues"),
- },
- ] as MockTab[],
- },
- } as Record<string, { activeTabId: string; tabs: MockTab[] }>,
- openTab: vi.fn<(path: string, title?: string, icon?: string) => string>(),
- setActiveTab: vi.fn<(tabId: string) => void>(),
- switchWorkspace: vi.fn<(slug: string, openPath?: string) => void>(),
+// MUL-4741: the adapter mutates tab sessions in the REAL store (no router,
+// no mocks needed for it anymore) — the Coordinator, not tested here, is
+// what projects sessions into the single router. Overlay and auth stay
+// mocked so we can spy on their entry points.
+
+const overlay = vi.hoisted(() => ({
+ overlay: null as null | { type: string },
+ open: vi.fn(),
+ close: vi.fn(),
}));
-vi.mock("@/stores/tab-store", () => {
- const store = {
- get activeWorkspaceSlug() {
- return state.activeWorkspaceSlug;
- },
- get byWorkspace() {
- return state.byWorkspace;
- },
- openTab: state.openTab,
- setActiveTab: state.setActiveTab,
- switchWorkspace: state.switchWorkspace,
- };
- const useTabStore = Object.assign(
- (selector?: (s: typeof store) => unknown) =>
- selector ? selector(store) : store,
- { getState: () => store },
- );
- const getActiveTab = () => {
- const slug = state.activeWorkspaceSlug;
- if (!slug) return null;
- const group = state.byWorkspace[slug];
- if (!group) return null;
- return group.tabs.find((t) => t.id === group.activeTabId) ?? null;
- };
- const useActiveTabIdentity = () => ({
- slug: state.activeWorkspaceSlug,
- tabId: state.activeWorkspaceSlug
- ? (state.byWorkspace[state.activeWorkspaceSlug]?.activeTabId ?? null)
- : null,
- });
- const useActiveTabRouter = () => null;
- const resolveRouteIcon = () => "File";
- return {
- useTabStore,
- getActiveTab,
- useActiveTabIdentity,
- useActiveTabRouter,
- resolveRouteIcon,
- };
-});
-
vi.mock("@/stores/window-overlay-store", () => ({
- useWindowOverlayStore: Object.assign(
- () => null,
- { getState: () => ({ overlay: null, open: vi.fn(), close: vi.fn() }) },
- ),
+ useWindowOverlayStore: Object.assign(() => null, {
+ getState: () => overlay,
+ }),
}));
+const auth = vi.hoisted(() => ({ logout: vi.fn() }));
+
vi.mock("@multica/core/auth", () => ({
- useAuthStore: Object.assign(
- () => null,
- { getState: () => ({ logout: vi.fn() }) },
- ),
+ useAuthStore: Object.assign(() => null, {
+ getState: () => auth,
+ }),
}));
-vi.mock("@multica/core/paths", () => ({
- isReservedSlug: (s: string) =>
- ["login", "workspaces", "invite", "onboarding", "invitations"].includes(s),
-}));
+import { DesktopNavigationProvider } from "./navigation";
+import { useNavigation } from "@multica/views/navigation";
+import { useTabStore, getActiveTab } from "@/stores/tab-store";
-// DesktopNavigationProvider reads window.desktopAPI.runtimeConfig synchronously.
beforeEach(() => {
- state.openTab.mockReset();
- state.setActiveTab.mockReset();
- state.switchWorkspace.mockReset();
- state.openTab.mockImplementation(() => "tNew");
- state.activeWorkspaceSlug = "acme";
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [
- {
- id: "tA",
- path: "/acme/issues",
- pinned: false,
- router: makeMockRouter("/acme/issues"),
- },
- ],
- },
- };
+ overlay.open.mockReset();
+ overlay.close.mockReset();
+ overlay.overlay = null;
+ auth.logout.mockReset();
+ useTabStore.getState().reset();
+ useTabStore.getState().switchWorkspace("acme"); // default tab /acme/issues
Object.defineProperty(window, "desktopAPI", {
configurable: true,
value: {
@@ -132,12 +46,6 @@ beforeEach(() => {
});
});
-import {
- DesktopNavigationProvider,
- TabNavigationProvider,
-} from "./navigation";
-import { useNavigation } from "@multica/views/navigation";
-
function captureAdapter(onAdapter: (adapter: ReturnType<typeof useNavigation>) => void) {
function Probe() {
const nav = useNavigation();
@@ -149,273 +57,164 @@ function captureAdapter(onAdapter: (adapter: ReturnType<typeof useNavigation>) =
return Probe;
}
-describe("DesktopNavigationProvider.openInNewTab", () => {
- it("opens a background tab (no setActiveTab) for a same-workspace path", () => {
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- render(
- <DesktopNavigationProvider>
- <Probe />
- </DesktopNavigationProvider>,
- );
- expect(adapter).not.toBeNull();
- adapter!.openInNewTab!("/acme/agents", "Agents");
- expect(state.openTab).toHaveBeenCalledWith("/acme/agents", "Agents", "File");
- expect(state.setActiveTab).not.toHaveBeenCalled();
- expect(state.switchWorkspace).not.toHaveBeenCalled();
+function renderProvider() {
+ let adapter: ReturnType<typeof useNavigation> | null = null;
+ const Probe = captureAdapter((a) => {
+ adapter = a;
+ });
+ render(
+ <DesktopNavigationProvider>
+ <Probe />
+ </DesktopNavigationProvider>,
+ );
+ return () => adapter!;
+}
+
+function acmeGroup() {
+ return useTabStore.getState().byWorkspace.acme;
+}
+
+describe("openInNewTab", () => {
+ it("opens a background tab (active tab unchanged) for a same-workspace path", () => {
+ const getAdapter = renderProvider();
+ const activeBefore = acmeGroup().activeTabId;
+
+ getAdapter().openInNewTab!("/acme/agents", "Agents");
+
+ const group = acmeGroup();
+ expect(group.tabs.map((t) => t.url)).toEqual(["/acme/issues", "/acme/agents"]);
+ expect(group.activeTabId).toBe(activeBefore);
});
it("activates the new tab when opts.activate is true (foreground)", () => {
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- render(
- <DesktopNavigationProvider>
- <Probe />
- </DesktopNavigationProvider>,
- );
- adapter!.openInNewTab!("/acme/agents", "Agents", { activate: true });
- expect(state.openTab).toHaveBeenCalledWith("/acme/agents", "Agents", "File");
- expect(state.setActiveTab).toHaveBeenCalledWith("tNew");
- expect(state.switchWorkspace).not.toHaveBeenCalled();
+ const getAdapter = renderProvider();
+
+ getAdapter().openInNewTab!("/acme/agents", "Agents", { activate: true });
+
+ const group = acmeGroup();
+ const agents = group.tabs.find((t) => t.url === "/acme/agents")!;
+ expect(group.activeTabId).toBe(agents.id);
});
it("delegates to switchWorkspace for a cross-workspace path", () => {
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- render(
- <DesktopNavigationProvider>
- <Probe />
- </DesktopNavigationProvider>,
- );
- adapter!.openInNewTab!("/butter/inbox");
- expect(state.switchWorkspace).toHaveBeenCalledWith("butter", "/butter/inbox");
- expect(state.openTab).not.toHaveBeenCalled();
- expect(state.setActiveTab).not.toHaveBeenCalled();
+ const getAdapter = renderProvider();
+
+ getAdapter().openInNewTab!("/butter/inbox");
+
+ const s = useTabStore.getState();
+ expect(s.activeWorkspaceSlug).toBe("butter");
+ expect(getActiveTab(s)?.url).toBe("/butter/inbox");
+ // acme's group is untouched.
+ expect(s.byWorkspace.acme.tabs).toHaveLength(1);
});
});
-describe("DesktopNavigationProvider.push with pinned active tab", () => {
- function pinActive(pathname: string) {
- state.byWorkspace.acme.tabs[0] = {
- id: "tA",
- path: pathname,
- pinned: true,
- router: makeMockRouter(pathname),
- };
- }
+describe("push", () => {
+ it("navigates the active session in-tab (url + virtual history)", () => {
+ const getAdapter = renderProvider();
- it("redirects push to a new foreground tab when pathname differs", () => {
- pinActive("/acme/issues");
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- render(
- <DesktopNavigationProvider>
- <Probe />
- </DesktopNavigationProvider>,
- );
- adapter!.push("/acme/projects");
- expect(state.openTab).toHaveBeenCalledWith("/acme/projects", "/acme/projects", "File");
- expect(state.setActiveTab).toHaveBeenCalledWith("tNew");
- });
+ getAdapter().push("/acme/projects?sort=name");
- it("allows in-tab navigation when only search/hash changes", () => {
- pinActive("/acme/issues");
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
+ const active = getActiveTab(useTabStore.getState())!;
+ expect(active.url).toBe("/acme/projects?sort=name");
+ expect(active.history).toEqual({
+ stack: ["/acme/issues", "/acme/projects?sort=name"],
+ index: 1,
});
- render(
- <DesktopNavigationProvider>
- <Probe />
- </DesktopNavigationProvider>,
- );
- adapter!.push("/acme/issues?filter=open");
- // Pathname unchanged → pinned interception declines and falls through to
- // the router's own navigate — openTab / setActiveTab must not fire.
- expect(state.openTab).not.toHaveBeenCalled();
- expect(state.setActiveTab).not.toHaveBeenCalled();
});
- it("leaves cross-workspace push to the workspace switcher (not pin)", () => {
- pinActive("/acme/issues");
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- render(
- <DesktopNavigationProvider>
- <Probe />
- </DesktopNavigationProvider>,
- );
- adapter!.push("/butter/inbox");
- // Cross-workspace push runs through tryRouteToOtherWorkspace before
- // tryRouteToPinnedNewTab, so switchWorkspace wins.
- expect(state.switchWorkspace).toHaveBeenCalledWith("butter", "/butter/inbox");
- expect(state.openTab).not.toHaveBeenCalled();
+ it("is a no-op when the target exactly matches the active session url", () => {
+ const getAdapter = renderProvider();
+ const before = acmeGroup();
+
+ getAdapter().push("/acme/issues");
+
+ expect(acmeGroup()).toBe(before);
});
-});
-describe("DesktopNavigationProvider.push duplicate path guard", () => {
- it("does not navigate when the target exactly matches the active tab location", () => {
- const activeRouter = makeMockRouter("/acme/issues/child");
- state.byWorkspace.acme.tabs[0] = {
- id: "tA",
- path: "/acme/issues/child",
- pinned: false,
- router: activeRouter,
- };
-
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- render(
- <DesktopNavigationProvider>
- <Probe />
- </DesktopNavigationProvider>,
- );
+ it("switches workspace for a cross-workspace path", () => {
+ const getAdapter = renderProvider();
- adapter!.push("/acme/issues/child");
+ getAdapter().push("/butter/inbox");
- expect(activeRouter.navigate).not.toHaveBeenCalled();
+ const s = useTabStore.getState();
+ expect(s.activeWorkspaceSlug).toBe("butter");
+ expect(getActiveTab(s)?.url).toBe("/butter/inbox");
});
-});
-describe("TabNavigationProvider.openInNewTab", () => {
- function renderTabProvider() {
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- const fakeRouter = {
- state: { location: { pathname: "/acme/issues", search: "" } },
- subscribe: () => () => {},
- navigate: vi.fn(),
- } as unknown as Parameters<typeof TabNavigationProvider>[0]["router"];
- render(
- <TabNavigationProvider router={fakeRouter}>
- <Probe />
- </TabNavigationProvider>,
- );
- return () => adapter!;
- }
+ it("logs out instead of navigating for /login", () => {
+ const getAdapter = renderProvider();
- it("opens a background tab (no setActiveTab) for a same-workspace path", () => {
- const getAdapter = renderTabProvider();
- getAdapter().openInNewTab!("/acme/agents", "Agents");
- expect(state.openTab).toHaveBeenCalledWith("/acme/agents", "Agents", "File");
- expect(state.setActiveTab).not.toHaveBeenCalled();
- expect(state.switchWorkspace).not.toHaveBeenCalled();
+ getAdapter().push("/login");
+
+ expect(auth.logout).toHaveBeenCalledOnce();
+ expect(getActiveTab(useTabStore.getState())?.url).toBe("/acme/issues");
});
- it("activates the new tab when opts.activate is true (foreground)", () => {
- const getAdapter = renderTabProvider();
- getAdapter().openInNewTab!("/acme/agents", "Agents", { activate: true });
- expect(state.openTab).toHaveBeenCalledWith("/acme/agents", "Agents", "File");
- expect(state.setActiveTab).toHaveBeenCalledWith("tNew");
- expect(state.switchWorkspace).not.toHaveBeenCalled();
+ it("routes transition paths to the window overlay without touching sessions", () => {
+ const getAdapter = renderProvider();
+ const before = acmeGroup();
+
+ getAdapter().push("/workspaces/new");
+
+ expect(overlay.open).toHaveBeenCalledWith({ type: "new-workspace" });
+ expect(acmeGroup()).toBe(before);
});
});
-describe("TabNavigationProvider.push duplicate path guard", () => {
- function renderTabProviderAt(
- pathname: string,
- search = "",
- hash = "",
- ) {
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- const fakeRouter = {
- state: { location: { pathname, search, hash } },
- subscribe: () => () => {},
- navigate: vi.fn(),
- } as unknown as Parameters<typeof TabNavigationProvider>[0]["router"];
- render(
- <TabNavigationProvider router={fakeRouter}>
- <Probe />
- </TabNavigationProvider>,
- );
- return { getAdapter: () => adapter!, fakeRouter };
+describe("push with pinned active tab", () => {
+ function pinActive() {
+ const store = useTabStore.getState();
+ store.togglePin(acmeGroup().activeTabId);
}
- it("does not navigate when the target exactly matches the current full location", () => {
- const { getAdapter, fakeRouter } = renderTabProviderAt("/acme/issues/child");
+ it("redirects push to a new foreground tab when pathname differs", () => {
+ pinActive();
+ const getAdapter = renderProvider();
+ const pinnedId = acmeGroup().activeTabId;
- getAdapter().push("/acme/issues/child");
+ getAdapter().push("/acme/projects");
- expect(fakeRouter.navigate).not.toHaveBeenCalled();
+ const group = acmeGroup();
+ const pinned = group.tabs.find((t) => t.id === pinnedId)!;
+ const projects = group.tabs.find((t) => t.url === "/acme/projects")!;
+ // The pinned tab stays parked on its url; focus follows the new tab.
+ expect(pinned.url).toBe("/acme/issues");
+ expect(group.activeTabId).toBe(projects.id);
});
- it("still navigates when only search or hash differs", () => {
- const { getAdapter, fakeRouter } = renderTabProviderAt("/acme/issues");
+ it("allows in-tab navigation when only search/hash changes (RFC §3 D2b)", () => {
+ pinActive();
+ const getAdapter = renderProvider();
- getAdapter().push("/acme/issues?filter=open#top");
+ getAdapter().push("/acme/issues?filter=open");
- expect(fakeRouter.navigate).toHaveBeenCalledWith("/acme/issues?filter=open#top");
+ const group = acmeGroup();
+ expect(group.tabs).toHaveLength(1); // no new tab
+ expect(group.tabs[0].url).toBe("/acme/issues?filter=open");
});
-});
-describe("TabNavigationProvider.push with pinned active tab", () => {
- type ProviderRouter = Parameters<typeof TabNavigationProvider>[0]["router"];
-
- function renderPinnedTabProvider(pathname: string) {
- // The active tab and the per-tab router must share the same pathname:
- // tryRouteToPinnedNewTab reads the *active tab's* router for the current
- // pathname (so query-only pushes routed via React Router still compare
- // correctly), while the TabNavigationProvider falls back to *its own*
- // router.navigate when no interception fires. In real desktop usage they
- // are the same router instance; this helper mirrors that invariant.
- const fakeRouter = {
- state: { location: { pathname, search: "", hash: "" } },
- subscribe: () => () => {},
- navigate: vi.fn(),
- } as unknown as ProviderRouter;
- state.byWorkspace.acme.tabs[0] = {
- id: "tA",
- path: pathname,
- pinned: true,
- router: fakeRouter as unknown as MockRouter,
- };
-
- let adapter: ReturnType<typeof useNavigation> | null = null;
- const Probe = captureAdapter((a) => {
- adapter = a;
- });
- render(
- <TabNavigationProvider router={fakeRouter}>
- <Probe />
- </TabNavigationProvider>,
- );
- return { getAdapter: () => adapter!, fakeRouter };
- }
+ it("leaves cross-workspace push to the workspace switcher (not pin)", () => {
+ pinActive();
+ const getAdapter = renderProvider();
- it("redirects push to a new foreground tab when pathname differs", () => {
- const { getAdapter, fakeRouter } = renderPinnedTabProvider("/acme/issues");
- getAdapter().push("/acme/projects");
- expect(state.openTab).toHaveBeenCalledWith("/acme/projects", "/acme/projects", "File");
- expect(state.setActiveTab).toHaveBeenCalledWith("tNew");
- // Pinned interception short-circuits — the per-tab router must NOT
- // navigate, otherwise the pinned tab itself would move off its path.
- expect(fakeRouter.navigate).not.toHaveBeenCalled();
+ getAdapter().push("/butter/inbox");
+
+ expect(useTabStore.getState().activeWorkspaceSlug).toBe("butter");
+ // No extra tab was opened in acme by the pin interception.
+ expect(useTabStore.getState().byWorkspace.acme.tabs).toHaveLength(1);
});
+});
- it("allows in-tab navigation when only search/hash changes", () => {
- const { getAdapter, fakeRouter } = renderPinnedTabProvider("/acme/issues");
- getAdapter().push("/acme/issues?filter=open");
- // Same pathname → pinned interception declines, push falls through to
- // the tab's own router.navigate, and no new tab is opened.
- expect(state.openTab).not.toHaveBeenCalled();
- expect(state.setActiveTab).not.toHaveBeenCalled();
- expect(fakeRouter.navigate).toHaveBeenCalledWith("/acme/issues?filter=open");
+describe("back", () => {
+ it("moves the session's virtual history backwards", () => {
+ const getAdapter = renderProvider();
+ getAdapter().push("/acme/projects");
+
+ getAdapter().back!();
+
+ const active = getActiveTab(useTabStore.getState())!;
+ expect(active.url).toBe("/acme/issues");
+ expect(active.history.index).toBe(0);
});
});
diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsx
index f8a01d9af2..c7649c1e1c 100644
--- a/apps/desktop/src/renderer/src/platform/navigation.tsx
+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx
@@ -1,5 +1,4 @@
-import { useEffect, useMemo, useState } from "react";
-import type { DataRouter } from "react-router-dom";
+import { useMemo } from "react";
import {
NavigationProvider,
type NavigationAdapter,
@@ -9,9 +8,9 @@ import { isReservedSlug } from "@multica/core/paths";
import {
useTabStore,
resolveRouteIcon,
- useActiveTabIdentity,
- useActiveTabRouter,
getActiveTab,
+ splitTabUrl,
+ useActiveTabUrl,
} from "@/stores/tab-store";
import { useWindowOverlayStore } from "@/stores/window-overlay-store";
@@ -41,35 +40,24 @@ function extractWorkspaceSlug(path: string): string | null {
* desktop are rendered as a window-level overlay instead of a tab route.
* Returns `true` if the navigation was handled (caller should NOT proceed).
*
- * Side effect: when opening the new-workspace overlay, the tab router is
- * ALSO reset to "/". Rationale — the only way a push lands on
- * /workspaces/new is that the workspace context is gone (fresh install,
- * delete-last, leave-last). Leaving the tab parked on a workspace-scoped
- * path would keep those components mounted under the overlay; the next
- * render after the list cache updates would then throw (useWorkspaceId
- * etc) because the slug no longer resolves.
+ * MUL-4741 note: the old adapter also parked the tab's router at "/" when
+ * opening these overlays. Under the session architecture the Coordinator
+ * parks the single router automatically whenever `activeWorkspaceSlug` goes
+ * null (the zero-workspace flows), and an overlay opened over a still-valid
+ * workspace simply covers the mounted tab — no navigation happens at all.
*/
-function tryRouteToOverlay(path: string, router?: DataRouter): boolean {
+function tryRouteToOverlay(path: string): boolean {
const overlay = useWindowOverlayStore.getState();
if (path === "/workspaces/new") {
overlay.open({ type: "new-workspace" });
- if (router && router.state.location.pathname !== "/") {
- router.navigate("/", { replace: true });
- }
return true;
}
if (path === "/onboarding") {
overlay.open({ type: "onboarding" });
- if (router && router.state.location.pathname !== "/") {
- router.navigate("/", { replace: true });
- }
return true;
}
if (path === "/invitations") {
overlay.open({ type: "invitations" });
- if (router && router.state.location.pathname !== "/") {
- router.navigate("/", { replace: true });
- }
return true;
}
if (path.startsWith("/invite/")) {
@@ -89,11 +77,6 @@ function tryRouteToOverlay(path: string, router?: DataRouter): boolean {
return false;
}
-function routerLocationPath(router: DataRouter): string {
- const { pathname, search, hash } = router.state.location;
- return `${pathname}${search ?? ""}${hash ?? ""}`;
-}
-
/**
* Intercept pushes that change workspace. Returns `true` if the navigation
* was delegated to the tab store (caller should NOT proceed).
@@ -121,35 +104,34 @@ function tryRouteToOtherWorkspace(path: string): boolean {
* still work — see RFC §3 D2a (FINAL: any pathname change → new tab) and
* D2b (FINAL: same pathname → allowed in pinned tab).
*
- * Dedupe is preserved (D4a): `openTab` activates an existing same-path tab
- * if one exists, otherwise creates a new one. The newly-focused tab is
- * activated foreground — a pinned-tab push is an explicit user action, not
- * a background cmd+click, so the focus follows.
+ * Dedupe is preserved (D4a): `openTab` activates an existing tab with the
+ * same resourceKey if one exists, otherwise creates a new one. The
+ * newly-focused tab is activated foreground — a pinned-tab push is an
+ * explicit user action, not a background cmd+click, so the focus follows.
*/
function tryRouteToPinnedNewTab(path: string): boolean {
const store = useTabStore.getState();
const active = getActiveTab(store);
if (!active?.pinned) return false;
- // Use the live router pathname rather than `active.path` so query-only
- // navigations performed via React Router (which only sync pathname back
- // to the store) still compare correctly.
- const currentPathname = active.router.state.location.pathname;
- const newPathname = path.split("?")[0].split("#")[0];
+ const currentPathname = splitTabUrl(active.url).pathname;
+ const newPathname = splitTabUrl(path).pathname;
if (currentPathname === newPathname) return false;
const icon = resolveRouteIcon(path);
- const newId = store.openTab(path, path, icon);
- if (newId) store.setActiveTab(newId);
+ store.openTab(path, path, icon, { activate: true });
return true;
}
/**
- * Root-level navigation provider for components outside the per-tab
- * RouterProviders (sidebar, search dialog, modals, WindowOverlay contents).
+ * Navigation provider for the whole desktop shell — sidebar, search dialog,
+ * modals, WindowOverlay contents, AND the page tree inside the single
+ * RouterProvider (there is no per-tab provider anymore; the active session's
+ * URL is the location for everyone).
*
- * Reads from the active tab's memory router via router.subscribe().
- * Does NOT use any react-router hooks — it's above all RouterProviders.
+ * MUL-4741 invariant 1: none of these operations touch the router. They
+ * mutate tab sessions in the store; the Coordinator reconciles the single
+ * router to the active session URL with a navigation token.
*/
export function DesktopNavigationProvider({
children,
@@ -157,39 +139,16 @@ export function DesktopNavigationProvider({
children: React.ReactNode;
}) {
const appUrl = requireRuntimeAppUrl("DesktopNavigationProvider");
- // Primitive-only subscriptions so this component doesn't re-render on
- // unrelated store updates (e.g. an inactive tab's router tick). We
- // resolve the active router here only to subscribe once per tab switch.
- const { tabId: activeTabId } = useActiveTabIdentity();
- const router = useActiveTabRouter();
- // Mirror the active tab router's full location (pathname + search) so
- // shell-level consumers of useNavigation() — ChatWindow in particular —
- // can read URL search params. Must stay in sync with TabNavigationProvider
- // below; a partial shape here (just pathname) silently broke focus-mode
- // anchor resolution on `/inbox?issue=…`.
- const [location, setLocation] = useState<{ pathname: string; search: string }>(
- () => ({
- pathname: router?.state.location.pathname ?? "/",
- search: router?.state.location.search ?? "",
- }),
- );
-
- useEffect(() => {
- if (!router) {
- setLocation({ pathname: "/", search: "" });
- return;
- }
- setLocation({
- pathname: router.state.location.pathname,
- search: router.state.location.search,
- });
- return router.subscribe((state) => {
- setLocation({
- pathname: state.location.pathname,
- search: state.location.search,
- });
- });
- }, [activeTabId, router]);
+ // The active session's url IS the location. Primitive subscription: this
+ // only re-renders when the active url actually changes.
+ const activeUrl = useActiveTabUrl();
+ const location = useMemo(() => {
+ const url = activeUrl ?? "/";
+ const { pathname, suffix } = splitTabUrl(url);
+ const hashIdx = suffix.indexOf("#");
+ const search = hashIdx === -1 ? suffix : suffix.slice(0, hashIdx);
+ return { pathname, search };
+ }, [activeUrl]);
const adapter: NavigationAdapter = useMemo(
() => ({
@@ -198,21 +157,21 @@ export function DesktopNavigationProvider({
useAuthStore.getState().logout();
return;
}
- const active = currentActiveTab();
- if (tryRouteToOverlay(path, active?.router)) return;
- if (active && routerLocationPath(active.router) === path) return;
+ if (tryRouteToOverlay(path)) return;
+ const store = useTabStore.getState();
+ const active = getActiveTab(store);
+ if (active && active.url === path) return;
if (tryRouteToOtherWorkspace(path)) return;
if (tryRouteToPinnedNewTab(path)) return;
- active?.router.navigate(path);
+ store.navigateActiveSession(path);
},
replace: (path: string) => {
- const active = currentActiveTab();
- if (tryRouteToOverlay(path, active?.router)) return;
+ if (tryRouteToOverlay(path)) return;
if (tryRouteToOtherWorkspace(path)) return;
- active?.router.navigate(path, { replace: true });
+ useTabStore.getState().navigateActiveSession(path, { replace: true });
},
back: () => {
- currentActiveTab()?.router.navigate(-1);
+ useTabStore.getState().goBack();
},
pathname: location.pathname,
searchParams: new URLSearchParams(location.search),
@@ -233,10 +192,7 @@ export function DesktopNavigationProvider({
return;
}
const icon = resolveRouteIcon(path);
- const newId = store.openTab(path, title ?? path, icon);
- if (opts?.activate && newId) {
- store.setActiveTab(newId);
- }
+ store.openTab(path, title ?? path, icon, { activate: opts?.activate });
},
getShareableUrl: (path: string) => `${appUrl}${path}`,
}),
@@ -245,72 +201,3 @@ export function DesktopNavigationProvider({
return <NavigationProvider value={adapter}>{children}</NavigationProvider>;
}
-
-function currentActiveTab() {
- return getActiveTab(useTabStore.getState());
-}
-
-/**
- * Per-tab navigation provider rendered inside each tab's Activity wrapper.
- * Subscribes to the tab's own router for up-to-date pathname.
- *
- * This is what @multica/views page components read via useNavigation().
- */
-export function TabNavigationProvider({
- router,
- children,
-}: {
- router: DataRouter;
- children: React.ReactNode;
-}) {
- const appUrl = requireRuntimeAppUrl("TabNavigationProvider");
- const [location, setLocation] = useState(router.state.location);
-
- useEffect(() => {
- setLocation(router.state.location);
- return router.subscribe((state) => {
- setLocation(state.location);
- });
- }, [router]);
-
- const adapter: NavigationAdapter = useMemo(
- () => ({
- push: (path: string) => {
- if (tryRouteToOverlay(path, router)) return;
- if (routerLocationPath(router) === path) return;
- if (tryRouteToOtherWorkspace(path)) return;
- if (tryRouteToPinnedNewTab(path)) return;
- router.navigate(path);
- },
- replace: (path: string) => {
- if (tryRouteToOverlay(path, router)) return;
- if (tryRouteToOtherWorkspace(path)) return;
- router.navigate(path, { replace: true });
- },
- back: () => router.navigate(-1),
- pathname: location.pathname,
- searchParams: new URLSearchParams(location.search),
- openInNewTab: (
- path: string,
- title?: string,
- opts?: { activate?: boolean },
- ) => {
- const slug = extractWorkspaceSlug(path);
- const store = useTabStore.getState();
- if (slug && slug !== store.activeWorkspaceSlug) {
- store.switchWorkspace(slug, path);
- return;
- }
- const icon = resolveRouteIcon(path);
- const newId = store.openTab(path, title ?? path, icon);
- if (opts?.activate && newId) {
- store.setActiveTab(newId);
- }
- },
- getShareableUrl: (path: string) => `${appUrl}${path}`,
- }),
- [appUrl, router, location],
- );
-
- return <NavigationProvider value={adapter}>{children}</NavigationProvider>;
-}
diff --git a/apps/desktop/src/renderer/src/platform/tab-coordinator.ts b/apps/desktop/src/renderer/src/platform/tab-coordinator.ts
new file mode 100644
index 0000000000..cdbcc4759b
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/tab-coordinator.ts
@@ -0,0 +1,253 @@
+import type { DataRouter } from "react-router-dom";
+import type { QueryClient } from "@tanstack/react-query";
+import type { ScrollRestorationAdapter } from "@multica/views/platform";
+import { createAppRouter } from "@/routes";
+import {
+ useTabStore,
+ getActiveTab,
+ splitTabUrl,
+ scrollMementoKey,
+} from "@/stores/tab-store";
+
+/**
+ * Tab Coordinator (MUL-4741 Phase 2) — the ONLY writer of the single app
+ * router.
+ *
+ * Architecture: the tab store is the source of truth; the router is a
+ * projection of the active session's URL. The Coordinator subscribes to the
+ * store and *reconciles* the router to `activeSession.url`, stamping every
+ * navigation with a token. All entry points (tab bar clicks, adapter
+ * push/replace, shell back/forward, error recovery) mutate the store — none
+ * of them touch the router. This makes invariant 1 hold by construction:
+ *
+ * - Router location change WITH a pending token → expected, consume it.
+ * - Router location change WITHOUT a pending token → protocol error →
+ * bounded recovery (re-reconcile toward the session URL, capped).
+ *
+ * The router's own history is never used: the Coordinator always navigates
+ * with `replace`, and per-tab back/forward is a session operation over the
+ * session's virtual history stack. A POP therefore can only come from
+ * unforeseen code and is handled by the same protocol-error path.
+ */
+
+let router: DataRouter | null = null;
+let initialized = false;
+
+/** Navigations the Coordinator itself started and hasn't seen commit yet. */
+let pendingTokens = 0;
+
+/** Bounded recovery: consecutive protocol-error recoveries. */
+let recoveryAttempts = 0;
+const MAX_RECOVERY_ATTEMPTS = 5;
+
+/** The active tab host's root element — where mementos are captured from. */
+let activeHostElement: HTMLElement | null = null;
+
+/** Query client for reload()'s current-page-scope invalidation. */
+let queryClient: QueryClient | null = null;
+
+/** Identity of what the host currently shows: slug:tabId:generation. */
+let lastIdentity: string | null = null;
+let lastActiveTabId: string | null = null;
+/** The active session's url as last seen — the route the mounted DOM shows. */
+let lastActiveUrl: string | null = null;
+
+export function getAppRouter(): DataRouter {
+ if (!router) router = createAppRouter();
+ return router;
+}
+
+export function registerActiveHostElement(el: HTMLElement | null): void {
+ activeHostElement = el;
+}
+
+export function registerCoordinatorQueryClient(qc: QueryClient): void {
+ queryClient = qc;
+}
+
+/**
+ * Serves saved scroll offsets back to mounting views (pull-based restore —
+ * see ScrollRestorationProvider in @multica/views/platform). Offsets are
+ * looked up live against the tab's memento, scoped to the route the view is
+ * mounting under, so in-tab back/forward pulls each route's own offsets.
+ */
+export function createScrollRestorationAdapter(
+ tabId: string,
+): ScrollRestorationAdapter {
+ return {
+ get(containerKey) {
+ const state = useTabStore.getState();
+ const active = getActiveTab(state);
+ if (!active || active.id !== tabId) return undefined;
+ const routeKey = splitTabUrl(active.url).pathname;
+ return active.memento.scroll[scrollMementoKey(routeKey, containerKey)];
+ },
+ };
+}
+
+function currentRouterUrl(r: DataRouter): string {
+ const { pathname, search, hash } = r.state.location;
+ return `${pathname}${search ?? ""}${hash ?? ""}`;
+}
+
+function activeSessionUrl(): string | null {
+ return getActiveTab(useTabStore.getState())?.url ?? null;
+}
+
+/**
+ * Drive the router to the active session's URL (or park it at "/" when no
+ * workspace/session is active — the zero-workspace overlay state). Always
+ * `replace`: the router history is a projection, not a record.
+ */
+function reconcile(): void {
+ const r = getAppRouter();
+ const target = activeSessionUrl() ?? "/";
+ if (currentRouterUrl(r) === target) {
+ recoveryAttempts = 0;
+ return;
+ }
+ pendingTokens++;
+ r.navigate(target, { replace: true });
+}
+
+/**
+ * Capture the mounted route's restorable view state. Runs inside the store
+ * subscription, which zustand fires synchronously during `set()` — before
+ * React re-renders — so the outgoing DOM (previous tab, or previous route
+ * of the same tab) is still mounted.
+ *
+ * Scroll containers self-mark with `data-tab-scroll-root` (the attribute
+ * value is the container key, "main" when bare). Containers sitting at 0
+ * are simply absent from the result — the store's per-route REPLACE
+ * semantics turn that absence into "clear the stale offset".
+ */
+function captureScrollEntries(): Record<string, { top: number; height: number }> {
+ const entries: Record<string, { top: number; height: number }> = {};
+ if (!activeHostElement) return entries;
+ const els = activeHostElement.querySelectorAll<HTMLElement>(
+ "[data-tab-scroll-root]",
+ );
+ els.forEach((el) => {
+ if (el.scrollTop <= 0) return;
+ const key = el.getAttribute("data-tab-scroll-root") || "main";
+ entries[key] = { top: el.scrollTop, height: el.scrollHeight };
+ });
+ return entries;
+}
+
+function handleStoreChange(): void {
+ const state = useTabStore.getState();
+ const active = getActiveTab(state);
+ const identity = active
+ ? `${state.activeWorkspaceSlug}:${active.id}:${state.mountGeneration}`
+ : null;
+ const activeUrl = active?.url ?? null;
+
+ // Capture whenever what the DOM currently shows is about to be replaced:
+ // a host switch (tab switch / reload / workspace switch / close) OR an
+ // in-tab navigation (url change on the same tab — back/forward included).
+ // The outgoing DOM belongs to `lastActiveUrl`'s route, so that pathname
+ // scopes the commit.
+ const hostSwitching = identity !== lastIdentity;
+ const inTabNavigation = !hostSwitching && activeUrl !== lastActiveUrl;
+ if (hostSwitching || inTabNavigation) {
+ const outgoingTabId = lastActiveTabId;
+ const outgoingUrl = lastActiveUrl;
+ lastIdentity = identity;
+ lastActiveTabId = active?.id ?? null;
+ lastActiveUrl = activeUrl;
+ if (outgoingTabId && outgoingUrl) {
+ const routeKey = splitTabUrl(outgoingUrl).pathname;
+ // Always commit — REPLACE semantics clear entries for containers that
+ // scrolled back to 0; the store skips the write when nothing changed.
+ useTabStore
+ .getState()
+ .commitScrollMemento(outgoingTabId, routeKey, captureScrollEntries());
+ }
+ }
+
+ reconcile();
+}
+
+function handleReloadGenerationChange(generation: number): void {
+ // RFC: reload = remount + invalidate the current page's query scope.
+ // `type: "active"` limits invalidation to queries with mounted observers —
+ // i.e. exactly the current page — and is explicitly NOT a global cache
+ // invalidation. `refetchType: "none"` avoids fetching into a tree that is
+ // about to unmount; the remounted page refetches its now-stale queries.
+ void generation;
+ queryClient?.invalidateQueries({ type: "active", refetchType: "none" });
+}
+
+/**
+ * Wire the Coordinator: store → router reconciliation and router-side
+ * protocol-error detection. Idempotent — the host calls it on mount.
+ */
+export function initTabCoordinator(): void {
+ if (initialized) return;
+ initialized = true;
+
+ const r = getAppRouter();
+
+ r.subscribe(() => {
+ if (pendingTokens > 0) {
+ // A navigation the Coordinator started. Consume the token.
+ pendingTokens--;
+ recoveryAttempts = 0;
+ return;
+ }
+ // Location changed without a token. If it happens to match the session
+ // (idempotent double-commit), accept silently; otherwise it's a
+ // protocol error — recover toward the session URL, bounded.
+ const url = currentRouterUrl(r);
+ const sessionUrl = activeSessionUrl() ?? "/";
+ if (url === sessionUrl) return;
+ if (recoveryAttempts >= MAX_RECOVERY_ATTEMPTS) {
+ console.error(
+ `[tab-coordinator] giving up recovery after ${MAX_RECOVERY_ATTEMPTS} attempts ` +
+ `(router at "${url}", session at "${sessionUrl}")`,
+ );
+ return;
+ }
+ recoveryAttempts++;
+ console.error(
+ `[tab-coordinator] protocol error: router moved to "${url}" without a ` +
+ `Coordinator token (session at "${sessionUrl}") — recovering ` +
+ `(${recoveryAttempts}/${MAX_RECOVERY_ATTEMPTS})`,
+ );
+ reconcile();
+ });
+
+ let prevGeneration = useTabStore.getState().mountGeneration;
+ useTabStore.subscribe((state) => {
+ if (state.mountGeneration !== prevGeneration) {
+ prevGeneration = state.mountGeneration;
+ handleReloadGenerationChange(state.mountGeneration);
+ }
+ handleStoreChange();
+ });
+
+ // Prime identity tracking and align the router with whatever the store
+ // rehydrated to.
+ const state = useTabStore.getState();
+ const active = getActiveTab(state);
+ lastIdentity = active
+ ? `${state.activeWorkspaceSlug}:${active.id}:${state.mountGeneration}`
+ : null;
+ lastActiveTabId = active?.id ?? null;
+ lastActiveUrl = active?.url ?? null;
+ reconcile();
+}
+
+/** Test-only: reset module state between cases. */
+export function __resetTabCoordinatorForTests(): void {
+ router = null;
+ initialized = false;
+ pendingTokens = 0;
+ recoveryAttempts = 0;
+ activeHostElement = null;
+ queryClient = null;
+ lastIdentity = null;
+ lastActiveTabId = null;
+ lastActiveUrl = null;
+}
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsx
index 7c8faa950f..6a1db5b751 100644
--- a/apps/desktop/src/renderer/src/routes.tsx
+++ b/apps/desktop/src/renderer/src/routes.tsx
@@ -1,10 +1,5 @@
import { useEffect } from "react";
-import {
- createMemoryRouter,
- Navigate,
- Outlet,
- useMatches,
-} from "react-router-dom";
+import { createMemoryRouter, Outlet, useMatches } from "react-router-dom";
import type { RouteObject } from "react-router-dom";
import { IssueDetailPage } from "./pages/issue-detail-page";
import { ProjectDetailPage } from "./pages/project-detail-page";
@@ -121,7 +116,12 @@ export const appRoutes: RouteObject[] = [
path: ":workspaceSlug",
element: <WorkspaceRouteLayout />,
children: [
- { index: true, element: <Navigate to="issues" replace /> },
+ // A bare `/{slug}` URL is normalized to `/{slug}/issues` by
+ // sanitizeTabPath before it ever becomes a session, so the index
+ // route is unreachable in practice; null keeps it a harmless
+ // safety net instead of an in-router <Navigate> (MUL-4741
+ // invariant 1: the router never self-navigates).
+ { index: true, element: null },
{
path: "issues",
element: <IssuesPage />,
@@ -219,9 +219,13 @@ export const appRoutes: RouteObject[] = [
},
];
-/** Create an independent memory router for a tab. */
-export function createTabRouter(initialPath: string) {
+/**
+ * Create THE app router (MUL-4741 single-router session architecture).
+ * There is exactly one instance, owned by the tab Coordinator; it projects
+ * the active tab session's URL and is never navigated by anything else.
+ */
+export function createAppRouter() {
return createMemoryRouter(appRoutes, {
- initialEntries: [initialPath],
+ initialEntries: ["/"],
});
}
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
index 9c2d7d634a..4ccd15ecad 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
@@ -1,28 +1,16 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
-// createTabRouter transitively pulls in route modules that expect a browser
-// router context. For pure store tests we stub it to a minimal disposable.
-const createTabRouterMock = vi.hoisted(() =>
- vi.fn(() => ({
- dispose: vi.fn(),
- state: { location: { pathname: "/" } },
- navigate: vi.fn(),
- subscribe: vi.fn(() => () => {}),
- })),
-);
-vi.mock("../routes", () => ({
- createTabRouter: createTabRouterMock,
-}));
-
import {
sanitizeTabPath,
+ resourceKeyForUrl,
migrateV1ToV2,
migrateV2ToV3,
+ migrateV3ToV4,
useTabStore,
+ getActiveTab,
} from "./tab-store";
beforeEach(() => {
- createTabRouterMock.mockClear();
useTabStore.getState().reset();
});
@@ -57,6 +45,20 @@ describe("sanitizeTabPath", () => {
expect(sanitizeTabPath("/acme-issues/issues")).toBe("/acme-issues/issues");
expect(sanitizeTabPath("/project-x/inbox")).toBe("/project-x/inbox");
});
+
+ it("normalizes a bare workspace url to its default surface (replaces the in-router index redirect)", () => {
+ expect(sanitizeTabPath("/acme")).toBe("/acme/issues");
+ expect(sanitizeTabPath("/acme?welcome=1")).toBe("/acme/issues?welcome=1");
+ });
+});
+
+describe("resourceKeyForUrl", () => {
+ it("is the pathname — search and hash are view state, not identity", () => {
+ expect(resourceKeyForUrl("/acme/issues")).toBe("/acme/issues");
+ expect(resourceKeyForUrl("/acme/issues?filter=a")).toBe("/acme/issues");
+ expect(resourceKeyForUrl("/acme/issues#anchor")).toBe("/acme/issues");
+ expect(resourceKeyForUrl("/acme/issues?filter=a#x")).toBe("/acme/issues");
+ });
});
describe("migrateV1ToV2", () => {
@@ -115,7 +117,12 @@ describe("useTabStore actions", () => {
const s = useTabStore.getState();
expect(s.activeWorkspaceSlug).toBe("acme");
expect(s.byWorkspace.acme.tabs).toHaveLength(1);
- expect(s.byWorkspace.acme.tabs[0].path).toBe("/acme/issues");
+ expect(s.byWorkspace.acme.tabs[0].url).toBe("/acme/issues");
+ expect(s.byWorkspace.acme.tabs[0].resourceKey).toBe("/acme/issues");
+ expect(s.byWorkspace.acme.tabs[0].history).toEqual({
+ stack: ["/acme/issues"],
+ index: 0,
+ });
});
it("switchWorkspace without openPath restores the group's last active tab", () => {
@@ -135,7 +142,7 @@ describe("useTabStore actions", () => {
expect(s.byWorkspace.acme.activeTabId).toBe(acmeProjectsId);
});
- it("switchWorkspace with openPath dedupes into an existing tab with same path", () => {
+ it("switchWorkspace with openPath dedupes into an existing tab with the same resourceKey", () => {
const store = useTabStore.getState();
store.switchWorkspace("acme"); // creates default /acme/issues
store.addTab("/acme/projects", "Projects", "FolderKanban");
@@ -146,7 +153,7 @@ describe("useTabStore actions", () => {
const activeTab = s.byWorkspace.acme.tabs.find(
(t) => t.id === s.byWorkspace.acme.activeTabId,
);
- expect(activeTab?.path).toBe("/acme/issues");
+ expect(activeTab?.url).toBe("/acme/issues");
});
it("switchWorkspace with openPath not matching any tab adds a new tab", () => {
@@ -158,10 +165,10 @@ describe("useTabStore actions", () => {
const activeTab = s.byWorkspace.acme.tabs.find(
(t) => t.id === s.byWorkspace.acme.activeTabId,
);
- expect(activeTab?.path).toBe("/acme/issues/bug-42");
+ expect(activeTab?.url).toBe("/acme/issues/bug-42");
});
- it("openTab dedupes by path within the active workspace", () => {
+ it("openTab dedupes by resourceKey within the active workspace", () => {
const store = useTabStore.getState();
store.switchWorkspace("acme");
const id1 = store.openTab("/acme/projects", "Projects", "FolderKanban");
@@ -170,6 +177,21 @@ describe("useTabStore actions", () => {
expect(useTabStore.getState().byWorkspace.acme.tabs).toHaveLength(2); // default + projects
});
+ it("openTab with a different query focuses the existing tab and keeps its url (RFC §8.2 semantic change)", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme"); // default tab at /acme/issues
+ const defaultTabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+
+ const id = store.openTab("/acme/issues?filter=urgent", "Issues", "ListTodo");
+
+ const s = useTabStore.getState();
+ expect(id).toBe(defaultTabId); // focused, not duplicated
+ expect(s.byWorkspace.acme.tabs).toHaveLength(1);
+ // The existing tab's own view state (url) wins; the incoming filter does
+ // not overwrite it.
+ expect(s.byWorkspace.acme.tabs[0].url).toBe("/acme/issues");
+ });
+
it("closeTab on the last tab in a workspace reseeds the default tab", () => {
const store = useTabStore.getState();
store.switchWorkspace("acme");
@@ -177,37 +199,11 @@ describe("useTabStore actions", () => {
store.closeTab(onlyTabId);
const s = useTabStore.getState();
expect(s.byWorkspace.acme.tabs).toHaveLength(1);
- expect(s.byWorkspace.acme.tabs[0].path).toBe("/acme/issues");
+ expect(s.byWorkspace.acme.tabs[0].url).toBe("/acme/issues");
expect(s.byWorkspace.acme.tabs[0].id).not.toBe(onlyTabId); // fresh tab
});
- it("defers disposing the closed tab router until after the store update", () => {
- vi.useFakeTimers();
- try {
- const store = useTabStore.getState();
- store.switchWorkspace("acme");
- const closedTabId = store.addTab("/acme/settings", "Settings", "Settings");
- const closingTab = useTabStore
- .getState()
- .byWorkspace.acme.tabs.find((t) => t.id === closedTabId);
- const dispose = vi.mocked(closingTab!.router.dispose);
-
- store.closeTab(closedTabId);
-
- expect(dispose).not.toHaveBeenCalled();
- expect(
- useTabStore.getState().byWorkspace.acme.tabs.some((t) => t.id === closedTabId),
- ).toBe(false);
-
- vi.runAllTimers();
-
- expect(dispose).toHaveBeenCalledOnce();
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("ignores router-sync updates from a tab after it has been closed", () => {
+ it("ignores updates addressed to a tab after it has been closed", () => {
const store = useTabStore.getState();
store.switchWorkspace("acme");
const closedTabId = store.addTab("/acme/settings", "Settings", "Settings");
@@ -215,8 +211,10 @@ describe("useTabStore actions", () => {
store.closeTab(closedTabId);
const before = useTabStore.getState().byWorkspace.acme;
- store.updateTab(closedTabId, { path: "/acme/runtimes", icon: "Monitor" });
- store.updateTabHistory(closedTabId, 1, 2);
+ store.updateTab(closedTabId, { title: "Ghost" });
+ store.commitScrollMemento(closedTabId, "/acme/settings", {
+ main: { top: 10, height: 100 },
+ });
expect(useTabStore.getState().byWorkspace.acme).toBe(before);
expect(
@@ -224,14 +222,13 @@ describe("useTabStore actions", () => {
).toBe(false);
});
- it("does not replace the tab group for no-op router-sync updates", () => {
+ it("does not replace the tab group for no-op title-sync updates", () => {
const store = useTabStore.getState();
store.switchWorkspace("acme");
const tab = useTabStore.getState().byWorkspace.acme.tabs[0];
const before = useTabStore.getState().byWorkspace.acme;
- store.updateTab(tab.id, { path: tab.path, icon: tab.icon, title: tab.title });
- store.updateTabHistory(tab.id, tab.historyIndex, tab.historyLength);
+ store.updateTab(tab.id, { title: tab.title, icon: tab.icon });
expect(useTabStore.getState().byWorkspace.acme).toBe(before);
});
@@ -265,7 +262,7 @@ describe("useTabStore actions", () => {
const s = useTabStore.getState();
expect(s.activeWorkspaceSlug).toBe("acme");
expect(s.byWorkspace.acme.tabs).toHaveLength(1);
- expect(s.byWorkspace.acme.tabs[0].path).toBe("/acme/issues");
+ expect(s.byWorkspace.acme.tabs[0].url).toBe("/acme/issues");
});
it("validateWorkspaceSlugs reactivates an existing valid group before seeding", () => {
@@ -287,7 +284,6 @@ describe("useTabStore actions", () => {
// The only persisted group points at a workspace the user has lost access
// to — the stale-tab heal path WorkspaceRouteLayout drives.
store.switchWorkspace("stale");
- const staleRouter = useTabStore.getState().byWorkspace.stale.tabs[0].router;
store.validateWorkspaceSlugs(new Set(["acme"]));
@@ -295,19 +291,19 @@ describe("useTabStore actions", () => {
expect(Object.keys(s.byWorkspace)).toEqual(["acme"]);
expect(s.activeWorkspaceSlug).toBe("acme");
expect(s.byWorkspace.acme.tabs).toHaveLength(1);
- expect(s.byWorkspace.acme.tabs[0].path).toBe("/acme/issues");
- // The dropped stale group's router must be disposed, not leaked.
- expect(staleRouter.dispose).toHaveBeenCalled();
+ expect(s.byWorkspace.acme.tabs[0].url).toBe("/acme/issues");
});
it("reset wipes the whole store", () => {
const store = useTabStore.getState();
store.switchWorkspace("acme");
store.switchWorkspace("butter");
+ store.reloadActiveTab();
store.reset();
const s = useTabStore.getState();
expect(s.activeWorkspaceSlug).toBeNull();
expect(s.byWorkspace).toEqual({});
+ expect(s.mountGeneration).toBe(0);
});
it("setActiveTab across workspaces also flips the active workspace", () => {
@@ -320,39 +316,187 @@ describe("useTabStore actions", () => {
});
});
+describe("navigateActiveSession", () => {
+ it("updates url, resourceKey, icon, and pushes onto the virtual history", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+
+ store.navigateActiveSession("/acme/projects?sort=name");
+
+ const active = getActiveTab(useTabStore.getState())!;
+ expect(active.url).toBe("/acme/projects?sort=name");
+ expect(active.resourceKey).toBe("/acme/projects");
+ expect(active.icon).toBe("FolderKanban");
+ expect(active.history).toEqual({
+ stack: ["/acme/issues", "/acme/projects?sort=name"],
+ index: 1,
+ });
+ });
+
+ it("replace swaps the current history entry instead of pushing", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ store.navigateActiveSession("/acme/projects");
+
+ store.navigateActiveSession("/acme/projects?sort=name", { replace: true });
+
+ const active = getActiveTab(useTabStore.getState())!;
+ expect(active.history).toEqual({
+ stack: ["/acme/issues", "/acme/projects?sort=name"],
+ index: 1,
+ });
+ });
+
+ it("a push after going back truncates the forward stack", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ store.navigateActiveSession("/acme/projects");
+ store.navigateActiveSession("/acme/agents");
+ store.goBack();
+ store.goBack();
+
+ store.navigateActiveSession("/acme/inbox");
+
+ const active = getActiveTab(useTabStore.getState())!;
+ expect(active.history).toEqual({
+ stack: ["/acme/issues", "/acme/inbox"],
+ index: 1,
+ });
+ });
+
+ it("rejects cross-workspace urls (those go through switchWorkspace)", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+
+ store.navigateActiveSession("/butter/issues");
+
+ const active = getActiveTab(useTabStore.getState())!;
+ expect(active.url).toBe("/acme/issues");
+ });
+
+ it("goBack/goForward project the history stack back into the url", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ store.navigateActiveSession("/acme/projects");
+
+ store.goBack();
+ let active = getActiveTab(useTabStore.getState())!;
+ expect(active.url).toBe("/acme/issues");
+ expect(active.history.index).toBe(0);
+
+ store.goForward();
+ active = getActiveTab(useTabStore.getState())!;
+ expect(active.url).toBe("/acme/projects");
+ expect(active.history.index).toBe(1);
+
+ // Bounds: no-ops at the edges.
+ store.goForward();
+ expect(getActiveTab(useTabStore.getState())!.history.index).toBe(1);
+ });
+});
+
+describe("reloadActiveTab", () => {
+ it("bumps mountGeneration and leaves the session untouched", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const before = getActiveTab(useTabStore.getState())!;
+
+ store.reloadActiveTab();
+
+ const s = useTabStore.getState();
+ expect(s.mountGeneration).toBe(1);
+ expect(getActiveTab(s)).toBe(before);
+ });
+
+ it("is a no-op with no active workspace", () => {
+ useTabStore.getState().reloadActiveTab();
+ expect(useTabStore.getState().mountGeneration).toBe(0);
+ });
+});
+
+describe("commitScrollMemento", () => {
+ it("stores route-scoped entries on the addressed tab", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+
+ store.commitScrollMemento(tabId, "/acme/issues", {
+ "board:status:todo": { top: 420, height: 8000 },
+ });
+
+ expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({
+ scroll: { "/acme/issues::board:status:todo": { top: 420, height: 8000 } },
+ });
+ });
+
+ it("REPLACES the route's entries — scrolling back to 0 clears the stale offset", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+
+ store.commitScrollMemento(tabId, "/acme/issues", {
+ list: { top: 500, height: 8000 },
+ });
+ // User scrolled back to top before leaving: the capture has no entry
+ // for this container. The old 500 must not survive.
+ store.commitScrollMemento(tabId, "/acme/issues", {});
+
+ expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento).toEqual({
+ scroll: {},
+ });
+ });
+
+ it("keeps other routes' entries when one route commits", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+
+ store.commitScrollMemento(tabId, "/acme/issues", {
+ list: { top: 500, height: 8000 },
+ });
+ store.commitScrollMemento(tabId, "/acme/issues/bug-42", {
+ main: { top: 120, height: 3000 },
+ });
+
+ expect(useTabStore.getState().byWorkspace.acme.tabs[0].memento.scroll).toEqual({
+ "/acme/issues::list": { top: 500, height: 8000 },
+ "/acme/issues/bug-42::main": { top: 120, height: 3000 },
+ });
+ });
+
+ it("skips the store write when nothing changed", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const tabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+ store.commitScrollMemento(tabId, "/acme/issues", {
+ list: { top: 500, height: 8000 },
+ });
+ const before = useTabStore.getState().byWorkspace.acme;
+
+ store.commitScrollMemento(tabId, "/acme/issues", {
+ list: { top: 500, height: 8000 },
+ });
+
+ expect(useTabStore.getState().byWorkspace.acme).toBe(before);
+ });
+});
+
describe("bulk tab closing", () => {
it("closes other unpinned tabs, preserves pinned tabs, and activates the target", () => {
- vi.useFakeTimers();
- try {
- const store = useTabStore.getState();
- store.switchWorkspace("acme");
- const issuesId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
- const projectsId = store.addTab("/acme/projects", "Projects", "FolderKanban");
- const agentsId = store.addTab("/acme/agents", "Agents", "Bot");
- const settingsId = store.addTab("/acme/settings", "Settings", "Settings");
- store.togglePin(issuesId);
- store.setActiveTab(agentsId);
-
- const before = useTabStore.getState().byWorkspace.acme.tabs;
- const agentsDispose = vi.mocked(before.find((tab) => tab.id === agentsId)!.router.dispose);
- const settingsDispose = vi.mocked(
- before.find((tab) => tab.id === settingsId)!.router.dispose,
- );
-
- store.closeOtherTabs(projectsId);
-
- const group = useTabStore.getState().byWorkspace.acme;
- expect(group.tabs.map((tab) => tab.id)).toEqual([issuesId, projectsId]);
- expect(group.activeTabId).toBe(projectsId);
- expect(agentsDispose).not.toHaveBeenCalled();
- expect(settingsDispose).not.toHaveBeenCalled();
-
- vi.runAllTimers();
- expect(agentsDispose).toHaveBeenCalledOnce();
- expect(settingsDispose).toHaveBeenCalledOnce();
- } finally {
- vi.useRealTimers();
- }
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme");
+ const issuesId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+ const projectsId = store.addTab("/acme/projects", "Projects", "FolderKanban");
+ store.addTab("/acme/agents", "Agents", "Bot");
+ store.addTab("/acme/settings", "Settings", "Settings");
+ store.togglePin(issuesId);
+ store.setActiveTab(useTabStore.getState().byWorkspace.acme.tabs[2].id);
+
+ store.closeOtherTabs(projectsId);
+
+ const group = useTabStore.getState().byWorkspace.acme;
+ expect(group.tabs.map((tab) => tab.id)).toEqual([issuesId, projectsId]);
+ expect(group.activeTabId).toBe(projectsId);
});
it("keeps a surviving active tab when closing other tabs", () => {
@@ -488,7 +632,7 @@ describe("moveTab boundary clamp", () => {
// All unpinned; move agents (2) to position 0.
store.moveTab(2, 0);
const tabs = useTabStore.getState().byWorkspace.acme.tabs;
- expect(tabs.map((t) => t.path)).toEqual([
+ expect(tabs.map((t) => t.url)).toEqual([
"/acme/agents",
"/acme/issues",
"/acme/projects",
@@ -524,3 +668,46 @@ describe("migrateV2ToV3", () => {
expect(v3.activeWorkspaceSlug).toBeNull();
});
});
+
+describe("migrateV3ToV4 (legacy view-state import, MUL-4741)", () => {
+ it("converts path→url and seeds identity, history, and memento", () => {
+ const v3 = {
+ activeWorkspaceSlug: "acme",
+ byWorkspace: {
+ acme: {
+ activeTabId: "t1",
+ tabs: [
+ {
+ id: "t1",
+ path: "/acme/issues",
+ title: "Issues",
+ icon: "ListTodo",
+ pinned: true,
+ },
+ ],
+ },
+ },
+ };
+ const v4 = migrateV3ToV4(v3);
+ expect(v4.activeWorkspaceSlug).toBe("acme");
+ expect(v4.byWorkspace.acme.tabs).toEqual([
+ {
+ id: "t1",
+ url: "/acme/issues",
+ title: "Issues",
+ icon: "ListTodo",
+ pinned: true,
+ history: { stack: ["/acme/issues"], index: 0 },
+ memento: { scroll: {} },
+ },
+ ]);
+ });
+
+ it("handles missing byWorkspace gracefully", () => {
+ const v4 = migrateV3ToV4({
+ activeWorkspaceSlug: null,
+ } as Parameters<typeof migrateV3ToV4>[0]);
+ expect(v4.byWorkspace).toEqual({});
+ expect(v4.activeWorkspaceSlug).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.ts
index e0d6dab861..14b0e841bb 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts
@@ -4,22 +4,57 @@ import { arrayMove } from "@dnd-kit/sortable";
import { createPersistStorage, defaultStorage } from "@multica/core/platform";
import { createSafeId } from "@multica/core/utils";
import { isReservedSlug } from "@multica/core/paths";
-import type { DataRouter } from "react-router-dom";
-import { createTabRouter } from "../routes";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
+//
+// MUL-4741 Phase 2: tabs are *sessions*, not routers. A TabSession is pure
+// serializable state — URL, identity, virtual history, and a memento of
+// restorable view state. The single app router is a projection of the active
+// session, driven exclusively by the tab Coordinator (src/platform/
+// tab-coordinator.ts) which subscribes to this store and reconciles the
+// router to `activeSession.url` with a navigation token. Nothing in this
+// file touches react-router.
+
+export interface TabMemento {
+ /**
+ * Scroll offsets keyed `${routePathname}::${containerKey}` where the
+ * container key is the `data-tab-scroll-root` attribute value ("main"
+ * when bare). Scoping by route lets in-tab back/forward restore each
+ * route's own offsets and stops same-named containers on different routes
+ * from colliding (Linear keys its scroll memory the same way: route +
+ * tab). `height` is the container's scrollHeight at capture time, kept
+ * for diagnostics and future pre-sizing heuristics.
+ */
+ scroll: Record<string, { top: number; height: number }>;
+}
+
+export function emptyMemento(): TabMemento {
+ return { scroll: {} };
+}
+
+export function scrollMementoKey(routeKey: string, containerKey: string): string {
+ return `${routeKey}::${containerKey}`;
+}
-export interface Tab {
+export interface TabSession {
id: string;
- /** Every tab path is workspace-scoped: `/{workspaceSlug}/{route}/...`. */
- path: string;
+ /**
+ * Full tab URL (pathname + search + hash). Every tab URL is
+ * workspace-scoped: `/{workspaceSlug}/{route}/...`.
+ */
+ url: string;
+ /**
+ * Dedup identity: the pathname alone. Search/hash (filters, anchors) are
+ * view state and live in `url`/`memento`, NOT in the identity — opening
+ * `/slug/issues?filter=a` while `/slug/issues?filter=b` exists focuses
+ * the existing tab (RFC §8.2; deliberate semantic change from the old
+ * exact-path dedupe).
+ */
+ resourceKey: string;
title: string;
icon: string;
- router: DataRouter;
- historyIndex: number;
- historyLength: number;
/**
* Pinned tabs render at the left of the tab bar as icon-only, suppress the
* X close button, and turn any `navigation.push()` originating in them into
@@ -28,10 +63,20 @@ export interface Tab {
* a workspace's `tabs` array; `togglePin` / `moveTab` enforce this.
*/
pinned: boolean;
+ /**
+ * Virtual per-tab history. The single router never uses its own history
+ * (the Coordinator always navigates with replace), so back/forward are
+ * session operations: move `index` and project `stack[index]` to `url`.
+ */
+ history: { stack: string[]; index: number };
+ memento: TabMemento;
}
+/** Back-compat alias — external consumers still say `Tab`. */
+export type Tab = TabSession;
+
export interface WorkspaceTabGroup {
- tabs: Tab[];
+ tabs: TabSession[];
/** Must be a valid tab.id in `tabs`; the empty-tabs state is transient only. */
activeTabId: string;
}
@@ -50,23 +95,40 @@ interface TabStore {
/**
* Tab groups keyed by workspace slug. Each slug maps to an independent
* (tabs, activeTabId) pair; switching workspaces swaps the visible set
- * without affecting any other group. Cross-workspace tab leakage — the
- * bug that drove this refactor — is impossible by construction because
- * there is no global tab array anymore.
+ * without affecting any other group. Cross-workspace tab leakage is
+ * impossible by construction because there is no global tab array.
*/
byWorkspace: Record<string, WorkspaceTabGroup>;
+ /**
+ * Bumped by reloadActiveTab. The ActiveTabHost keys its subtree on
+ * `${activeTabId}:${mountGeneration}` so a bump force-remounts the whole
+ * page tree (RFC: reload is a remount, never router.revalidate()).
+ * Deliberately NOT persisted.
+ */
+ mountGeneration: number;
+
/**
* Switch to a workspace.
* - If the group doesn't exist yet, create it with a single default tab.
- * - If `openPath` is given, find a tab with that exact path and activate
+ * - If `openPath` is given, find a tab with that resourceKey and activate
* it; otherwise add a new tab and activate it.
* - If `openPath` is omitted, restore the group's last active tab
* (VSCode / Slack behavior — workspaces resume where you left off).
*/
switchWorkspace: (slug: string, openPath?: string) => void;
- /** Open-or-activate (dedupes by path) a tab in the active workspace. */
- openTab: (path: string, title: string, icon: string) => string;
+ /**
+ * Open-or-activate (dedupes by resourceKey) a tab in the active workspace.
+ * `activate` focuses the opened/existing tab in the SAME store write — a
+ * separate setActiveTab call would give subscribers (and React) two full
+ * passes for one user action.
+ */
+ openTab: (
+ path: string,
+ title: string,
+ icon: string,
+ opts?: { activate?: boolean },
+ ) => string;
/** Always creates a new tab (no dedupe) in the active workspace. */
addTab: (path: string, title: string, icon: string) => string;
/**
@@ -84,17 +146,39 @@ interface TabStore {
* path that "jumps" to a tab belonging to a non-active workspace.
*/
setActiveTab: (tabId: string) => void;
- /** Patch metadata of a tab (router-sync, title-sync). Finds across groups. */
- updateTab: (tabId: string, patch: Partial<Pick<Tab, "path" | "title" | "icon">>) => void;
- /** Patch history tracking of a tab. Finds across groups. */
- updateTabHistory: (tabId: string, historyIndex: number, historyLength: number) => void;
- /** Recreate the active tab's router at the same path after a route-level crash. */
+ /** Patch display metadata of a tab (title-sync). Finds across groups. */
+ updateTab: (tabId: string, patch: Partial<Pick<TabSession, "title" | "icon">>) => void;
+ /**
+ * In-tab navigation: update the active session's url/resourceKey/icon and
+ * its virtual history. This is the ONLY way a session's url changes; the
+ * Coordinator reconciles the router afterwards.
+ */
+ navigateActiveSession: (url: string, opts?: { replace?: boolean }) => void;
+ /** Session-driven back/forward (there is no router history to pop). */
+ goBack: () => void;
+ goForward: () => void;
+ /**
+ * Persist captured scroll offsets for one route of a tab (Coordinator, on
+ * deactivate / before in-tab navigation). REPLACE semantics per route: all
+ * of the route's previous entries are dropped and the given ones written —
+ * so a container scrolled back to 0 (captured as "no entry") clears its
+ * stale offset instead of resurrecting it on the next visit.
+ */
+ commitScrollMemento: (
+ tabId: string,
+ routeKey: string,
+ entries: Record<string, { top: number; height: number }>,
+ ) => void;
+ /**
+ * Force-remount the active tab at the same URL: bump mountGeneration.
+ * Query invalidation for the current page's scope is handled by the
+ * Coordinator (it watches this counter) so this action stays pure state.
+ */
reloadActiveTab: () => void;
/**
* Close the active tab. The always-safe escape from a route-level crash:
- * unlike reloadActiveTab (recreates the same crashing path) or navigating
- * to a "safe" route (which may itself be the route that crashed), closing
- * destroys the crashing router entirely and falls back to a sibling tab
+ * unlike reloadActiveTab (remounts the same crashing URL), closing
+ * destroys the crashing session entirely and falls back to a sibling tab
* (or a reseeded default if it was the last tab).
*/
closeActiveTab: () => void;
@@ -146,7 +230,7 @@ const ROUTE_ICONS: Record<string, string> = {
/**
* Resolve a route icon from a pathname.
*
- * Tab paths are always workspace-scoped: `/{slug}/{route}/...`, so the route
+ * Tab URLs are always workspace-scoped: `/{slug}/{route}/...`, so the route
* segment lives at index 1. Pre-workspace flows (create, invite) are rendered
* by the window overlay, never as tabs.
*
@@ -167,13 +251,33 @@ function extractWorkspaceSlug(path: string): string | null {
}
// ---------------------------------------------------------------------------
-// Path sanitization (defensive)
+// URL helpers
// ---------------------------------------------------------------------------
+/** Split a tab URL into pathname and the search+hash suffix. */
+export function splitTabUrl(url: string): { pathname: string; suffix: string } {
+ const searchIdx = url.indexOf("?");
+ const hashIdx = url.indexOf("#");
+ const cut =
+ searchIdx === -1
+ ? hashIdx
+ : hashIdx === -1
+ ? searchIdx
+ : Math.min(searchIdx, hashIdx);
+ if (cut === -1) return { pathname: url, suffix: "" };
+ return { pathname: url.slice(0, cut), suffix: url.slice(cut) };
+}
+
+/** Dedup identity of a tab URL: its pathname (search/hash are view state). */
+export function resourceKeyForUrl(url: string): string {
+ return splitTabUrl(url).pathname;
+}
+
/**
- * Defensive: catch paths that don't belong in the tab store.
+ * Defensive: catch URLs that don't belong in the tab store, and normalize
+ * the ones that do.
*
- * Two kinds of rejects:
+ * Rejects:
* 1. **Transition paths** (`/workspaces/new`, `/invite/...`). These are
* pre-workspace flows rendered by the window overlay on desktop, not
* tab routes. The navigation adapter normally intercepts these before
@@ -182,19 +286,24 @@ function extractWorkspaceSlug(path: string): string | null {
* was constructed without the workspace prefix. The router would
* interpret `issues` as a workspace slug → NoAccessPage.
*
+ * Normalizes: a bare `/{slug}` (no route segment) becomes `/{slug}/issues` —
+ * the workspace's default surface. This replaces the old in-router
+ * `<Navigate to="issues">` index redirect (MUL-4741 invariant 1: the router
+ * never self-navigates; URLs are normalized before they become sessions).
+ *
* Returns null for rejects (caller decides how to recover — usually by
- * dropping the tab or substituting a default). Unlike the prior design,
- * there is no root "/" sentinel — tabs are always scoped.
+ * dropping the tab or substituting a default).
*/
export function sanitizeTabPath(path: string): string | null {
- const firstSegment = path.split("/").filter(Boolean)[0] ?? "";
+ const { pathname, suffix } = splitTabUrl(path);
+ const segments = pathname.split("/").filter(Boolean);
+ const firstSegment = segments[0] ?? "";
if (!firstSegment) return null;
if (isReservedSlug(firstSegment)) {
// Don't log for known transition paths — these are legitimate inputs
// at the interception boundary (older persisted state or stale callers).
const isTransition = path === "/workspaces/new" || path.startsWith("/invite/");
if (!isTransition) {
- // eslint-disable-next-line no-console
console.warn(
`[tab-store] tab path "${path}" starts with reserved slug "${firstSegment}" — ` +
`caller likely forgot the workspace prefix. Dropping.`,
@@ -202,32 +311,35 @@ export function sanitizeTabPath(path: string): string | null {
}
return null;
}
+ if (segments.length === 1) {
+ return `/${firstSegment}/issues${suffix}`;
+ }
return path;
}
// ---------------------------------------------------------------------------
-// Tab factory
+// Session factory
// ---------------------------------------------------------------------------
function createId(): string {
return createSafeId();
}
-function makeTab(path: string, title: string, icon: string): Tab {
+function makeSession(url: string, title: string, icon: string): TabSession {
return {
id: createId(),
- path,
+ url,
+ resourceKey: resourceKeyForUrl(url),
title,
icon,
- router: createTabRouter(path),
- historyIndex: 0,
- historyLength: 1,
pinned: false,
+ history: { stack: [url], index: 0 },
+ memento: emptyMemento(),
};
}
/** Index of the first unpinned tab in a group (== pinned count). */
-function pinnedBoundary(tabs: Tab[]): number {
+function pinnedBoundary(tabs: TabSession[]): number {
let i = 0;
while (i < tabs.length && tabs[i].pinned) i++;
return i;
@@ -238,9 +350,9 @@ function defaultPathFor(slug: string): string {
return `/${slug}/issues`;
}
-function defaultTabFor(slug: string): Tab {
+function defaultTabFor(slug: string): TabSession {
const path = defaultPathFor(slug);
- return makeTab(path, "Issues", resolveRouteIcon(path));
+ return makeSession(path, "Issues", resolveRouteIcon(path));
}
// ---------------------------------------------------------------------------
@@ -262,10 +374,7 @@ function findTabLocation(
function buildCloseOtherTabsResult(
byWorkspace: Record<string, WorkspaceTabGroup>,
tabId: string,
-): {
- nextByWorkspace: Record<string, WorkspaceTabGroup>;
- closingTabs: Tab[];
-} | null {
+): Record<string, WorkspaceTabGroup> | null {
const hit = findTabLocation(byWorkspace, tabId);
if (!hit) return null;
const { slug, group } = hit;
@@ -281,22 +390,11 @@ function buildCloseOtherTabsResult(
: group.activeTabId;
return {
- nextByWorkspace: {
- ...byWorkspace,
- [slug]: { tabs: nextTabs, activeTabId: nextActiveTabId },
- },
- closingTabs,
+ ...byWorkspace,
+ [slug]: { tabs: nextTabs, activeTabId: nextActiveTabId },
};
}
-function disposeTabRoutersAfterUnmount(tabs: readonly Tab[]) {
- if (tabs.length === 0) return;
- // Let React unmount every closed tab's RouterProvider before disposal.
- window.setTimeout(() => {
- for (const tab of tabs) tab.router.dispose();
- }, 0);
-}
-
// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------
@@ -306,6 +404,7 @@ export const useTabStore = create<TabStore>()(
(set, get) => ({
activeWorkspaceSlug: null,
byWorkspace: {},
+ mountGeneration: 0,
switchWorkspace(slug, openPath) {
// Defensive no-op if slug is empty/invalid — callers like the
@@ -320,11 +419,9 @@ export const useTabStore = create<TabStore>()(
if (!existing) {
// First time entering this workspace — create the group.
- const seedPath =
- desiredPath && sanitizeTabPath(desiredPath) === desiredPath
- ? desiredPath
- : defaultPathFor(slug);
- const tab = makeTab(seedPath, "Issues", resolveRouteIcon(seedPath));
+ const cleanDesired = desiredPath ? sanitizeTabPath(desiredPath) : null;
+ const seedPath = cleanDesired ?? defaultPathFor(slug);
+ const tab = makeSession(seedPath, "Issues", resolveRouteIcon(seedPath));
set({
activeWorkspaceSlug: slug,
byWorkspace: {
@@ -340,7 +437,8 @@ export const useTabStore = create<TabStore>()(
if (desiredPath) {
const clean = sanitizeTabPath(desiredPath);
if (clean) {
- const match = existing.tabs.find((t) => t.path === clean);
+ const key = resourceKeyForUrl(clean);
+ const match = existing.tabs.find((t) => t.resourceKey === key);
if (match) {
set({
activeWorkspaceSlug: slug,
@@ -351,7 +449,7 @@ export const useTabStore = create<TabStore>()(
});
return;
}
- const tab = makeTab(clean, "Issues", resolveRouteIcon(clean));
+ const tab = makeSession(clean, "Issues", resolveRouteIcon(clean));
set({
activeWorkspaceSlug: slug,
byWorkspace: {
@@ -370,14 +468,17 @@ export const useTabStore = create<TabStore>()(
set({ activeWorkspaceSlug: slug });
},
- openTab(path, title, icon) {
+ openTab(path, title, icon, opts) {
const { activeWorkspaceSlug, byWorkspace } = get();
const clean = sanitizeTabPath(path);
if (!activeWorkspaceSlug || !clean) return "";
const group = byWorkspace[activeWorkspaceSlug];
if (!group) return "";
- const existing = group.tabs.find((t) => t.path === clean);
+ // Dedup by resourceKey: the existing tab keeps its own url (its
+ // filters/anchor are its view state); we only focus it.
+ const key = resourceKeyForUrl(clean);
+ const existing = group.tabs.find((t) => t.resourceKey === key);
if (existing) {
set({
byWorkspace: {
@@ -388,13 +489,13 @@ export const useTabStore = create<TabStore>()(
return existing.id;
}
- const tab = makeTab(clean, title, icon);
+ const tab = makeSession(clean, title, icon);
set({
byWorkspace: {
...byWorkspace,
[activeWorkspaceSlug]: {
tabs: [...group.tabs, tab],
- activeTabId: group.activeTabId,
+ activeTabId: opts?.activate === true ? tab.id : group.activeTabId,
},
},
});
@@ -408,7 +509,7 @@ export const useTabStore = create<TabStore>()(
const group = byWorkspace[activeWorkspaceSlug];
if (!group) return "";
- const tab = makeTab(clean, title, icon);
+ const tab = makeSession(clean, title, icon);
set({
byWorkspace: {
...byWorkspace,
@@ -427,8 +528,6 @@ export const useTabStore = create<TabStore>()(
if (!hit) return;
const { slug, group, index } = hit;
- const closing = group.tabs[index];
-
if (group.tabs.length === 1) {
// Last tab in this workspace — reseed a default so the workspace
// always has at least one tab. Closing a workspace as an explicit
@@ -440,7 +539,6 @@ export const useTabStore = create<TabStore>()(
[slug]: { tabs: [fresh], activeTabId: fresh.id },
},
});
- disposeTabRoutersAfterUnmount([closing]);
return;
}
@@ -456,15 +554,13 @@ export const useTabStore = create<TabStore>()(
[slug]: { tabs: nextTabs, activeTabId: nextActiveTabId },
},
});
- disposeTabRoutersAfterUnmount([closing]);
},
closeOtherTabs(tabId) {
const { byWorkspace } = get();
- const result = buildCloseOtherTabsResult(byWorkspace, tabId);
- if (!result) return;
- set({ byWorkspace: result.nextByWorkspace });
- disposeTabRoutersAfterUnmount(result.closingTabs);
+ const next = buildCloseOtherTabsResult(byWorkspace, tabId);
+ if (!next) return;
+ set({ byWorkspace: next });
},
setActiveTab(tabId) {
@@ -488,12 +584,8 @@ export const useTabStore = create<TabStore>()(
if (!hit) return;
const { slug, group, index } = hit;
const current = group.tabs[index];
- const next: Tab = { ...current, ...patch };
- if (
- next.path === current.path &&
- next.title === current.title &&
- next.icon === current.icon
- ) {
+ const next: TabSession = { ...current, ...patch };
+ if (next.title === current.title && next.icon === current.icon) {
return;
}
const nextTabs = [...group.tabs];
@@ -506,21 +598,91 @@ export const useTabStore = create<TabStore>()(
});
},
- updateTabHistory(tabId, historyIndex, historyLength) {
+ navigateActiveSession(url, opts) {
+ const { activeWorkspaceSlug, byWorkspace } = get();
+ if (!activeWorkspaceSlug) return;
+ const group = byWorkspace[activeWorkspaceSlug];
+ if (!group) return;
+ const index = group.tabs.findIndex((t) => t.id === group.activeTabId);
+ if (index < 0) return;
+ const clean = sanitizeTabPath(url);
+ if (!clean) return;
+ // A session never navigates out of its workspace — cross-workspace
+ // pushes go through switchWorkspace at the adapter layer.
+ if (extractWorkspaceSlug(clean) !== activeWorkspaceSlug) return;
+
+ const current = group.tabs[index];
+ if (current.url === clean) return;
+
+ const replace = opts?.replace === true;
+ const stack = replace
+ ? [
+ ...current.history.stack.slice(0, current.history.index),
+ clean,
+ ...current.history.stack.slice(current.history.index + 1),
+ ]
+ : [...current.history.stack.slice(0, current.history.index + 1), clean];
+ const historyIndex = replace
+ ? current.history.index
+ : current.history.index + 1;
+
+ const next: TabSession = {
+ ...current,
+ url: clean,
+ resourceKey: resourceKeyForUrl(clean),
+ icon: resolveRouteIcon(splitTabUrl(clean).pathname),
+ history: { stack, index: historyIndex },
+ };
+ const nextTabs = [...group.tabs];
+ nextTabs[index] = next;
+ set({
+ byWorkspace: {
+ ...byWorkspace,
+ [activeWorkspaceSlug]: { ...group, tabs: nextTabs },
+ },
+ });
+ },
+
+ goBack() {
+ stepHistory(get, set, -1);
+ },
+
+ goForward() {
+ stepHistory(get, set, +1);
+ },
+
+ commitScrollMemento(tabId, routeKey, entries) {
const { byWorkspace } = get();
const hit = findTabLocation(byWorkspace, tabId);
if (!hit) return;
const { slug, group, index } = hit;
const current = group.tabs[index];
- if (
- current.historyIndex === historyIndex &&
- current.historyLength === historyLength
- ) {
- return;
+
+ const prefix = `${routeKey}::`;
+ const nextScroll: TabMemento["scroll"] = {};
+ for (const [key, value] of Object.entries(current.memento.scroll)) {
+ if (!key.startsWith(prefix)) nextScroll[key] = value;
+ }
+ for (const [containerKey, value] of Object.entries(entries)) {
+ nextScroll[scrollMementoKey(routeKey, containerKey)] = value;
}
- const next: Tab = { ...current, historyIndex, historyLength };
+
+ // Skip the write when nothing changed (common: an unscrolled route
+ // captured as empty over an already-empty route scope) — avoids a
+ // re-entrant store tick from inside the Coordinator's subscription.
+ const prevKeys = Object.keys(current.memento.scroll);
+ const nextKeys = Object.keys(nextScroll);
+ const unchanged =
+ prevKeys.length === nextKeys.length &&
+ nextKeys.every((k) => {
+ const prev = current.memento.scroll[k];
+ const next = nextScroll[k];
+ return prev !== undefined && prev.top === next.top && prev.height === next.height;
+ });
+ if (unchanged) return;
+
const nextTabs = [...group.tabs];
- nextTabs[index] = next;
+ nextTabs[index] = { ...current, memento: { scroll: nextScroll } };
set({
byWorkspace: {
...byWorkspace,
@@ -530,27 +692,12 @@ export const useTabStore = create<TabStore>()(
},
reloadActiveTab() {
- const { activeWorkspaceSlug, byWorkspace } = get();
+ const { activeWorkspaceSlug, byWorkspace, mountGeneration } = get();
if (!activeWorkspaceSlug) return;
const group = byWorkspace[activeWorkspaceSlug];
if (!group) return;
- const index = group.tabs.findIndex((t) => t.id === group.activeTabId);
- if (index < 0) return;
- const current = group.tabs[index];
- const nextTabs = [...group.tabs];
- nextTabs[index] = {
- ...current,
- router: createTabRouter(current.path),
- historyIndex: 0,
- historyLength: 1,
- };
- set({
- byWorkspace: {
- ...byWorkspace,
- [activeWorkspaceSlug]: { ...group, tabs: nextTabs },
- },
- });
- window.setTimeout(() => current.router.dispose(), 0);
+ if (!group.tabs.some((t) => t.id === group.activeTabId)) return;
+ set({ mountGeneration: mountGeneration + 1 });
},
closeActiveTab() {
@@ -599,7 +746,7 @@ export const useTabStore = create<TabStore>()(
if (!hit) return;
const { slug, group, index } = hit;
const current = group.tabs[index];
- const nextTab: Tab = { ...current, pinned: !current.pinned };
+ const nextTab: TabSession = { ...current, pinned: !current.pinned };
// Remove from current position, then insert at the new zone boundary:
// pinning → end of pinned zone (just before first unpinned tab)
@@ -633,7 +780,6 @@ export const useTabStore = create<TabStore>()(
nextByWorkspace[slug] = byWorkspace[slug];
} else {
changed = true;
- for (const t of byWorkspace[slug].tabs) t.router.dispose();
}
}
@@ -666,16 +812,12 @@ export const useTabStore = create<TabStore>()(
},
reset() {
- const { byWorkspace } = get();
- for (const slug of Object.keys(byWorkspace)) {
- for (const t of byWorkspace[slug].tabs) t.router.dispose();
- }
- set({ activeWorkspaceSlug: null, byWorkspace: {} });
+ set({ activeWorkspaceSlug: null, byWorkspace: {}, mountGeneration: 0 });
},
}),
{
name: "multica_tabs",
- version: 3,
+ version: 4,
storage: createJSONStorage(() => createPersistStorage(defaultStorage)),
migrate: (persistedState, version) => {
// v1 → v2: flat `tabs` array → per-workspace grouping.
@@ -691,56 +833,75 @@ export const useTabStore = create<TabStore>()(
if (version < 3 && state && typeof state === "object") {
state = migrateV2ToV3(state as V2Persisted);
}
- return state as V3Persisted;
+ // v3 → v4: Tab → TabSession (MUL-4741). One-time import of legacy
+ // view-state: `path` becomes `url`, identity/history/memento are
+ // derived. Routers are no longer part of the model.
+ if (version < 4 && state && typeof state === "object") {
+ state = migrateV3ToV4(state as V3Persisted);
+ }
+ return state as V4Persisted;
},
partialize: (state) => ({
activeWorkspaceSlug: state.activeWorkspaceSlug,
+ // mountGeneration is deliberately excluded: reload pressure must
+ // never persist across restarts.
byWorkspace: Object.fromEntries(
Object.entries(state.byWorkspace).map(([slug, group]) => [
slug,
{
activeTabId: group.activeTabId,
- tabs: group.tabs.map(
- ({
- router: _router,
- historyIndex: _hi,
- historyLength: _hl,
- ...rest
- }) => rest,
- ),
+ tabs: group.tabs.map((t) => ({
+ id: t.id,
+ url: t.url,
+ title: t.title,
+ icon: t.icon,
+ pinned: t.pinned,
+ history: t.history,
+ memento: t.memento,
+ })),
},
]),
),
}),
merge: (persistedState, currentState) => {
- const persisted = persistedState as Partial<V3Persisted> | undefined;
+ const persisted = persistedState as Partial<V4Persisted> | undefined;
if (!persisted?.byWorkspace) return currentState;
const byWorkspace: Record<string, WorkspaceTabGroup> = {};
for (const [slug, pGroup] of Object.entries(persisted.byWorkspace)) {
- const tabs: Tab[] = [];
+ const tabs: TabSession[] = [];
for (const pTab of pGroup.tabs) {
- const clean = sanitizeTabPath(pTab.path);
- // Persisted path may have come from a stale version or a
+ const clean = sanitizeTabPath(pTab.url);
+ // Persisted url may have come from a stale version or a
// manual edit. Drop rather than rewrite so we never silently
- // put users on a path that doesn't match the group's slug.
+ // put users on a url that doesn't match the group's slug.
if (!clean || extractWorkspaceSlug(clean) !== slug) {
- // eslint-disable-next-line no-console
console.warn(
- `[tab-store] dropping persisted tab "${pTab.path}" from ` +
- `group "${slug}" — path/slug mismatch`,
+ `[tab-store] dropping persisted tab "${pTab.url}" from ` +
+ `group "${slug}" — url/slug mismatch`,
);
continue;
}
+ const stack =
+ Array.isArray(pTab.history?.stack) && pTab.history.stack.length > 0
+ ? pTab.history.stack
+ : [clean];
+ const index = Math.min(
+ Math.max(pTab.history?.index ?? stack.length - 1, 0),
+ stack.length - 1,
+ );
tabs.push({
id: pTab.id,
- path: clean,
+ url: clean,
+ resourceKey: resourceKeyForUrl(clean),
title: pTab.title,
icon: pTab.icon,
- router: createTabRouter(clean),
- historyIndex: 0,
- historyLength: 1,
pinned: pTab.pinned === true,
+ history: { stack, index },
+ memento:
+ pTab.memento && typeof pTab.memento.scroll === "object"
+ ? pTab.memento
+ : emptyMemento(),
});
}
if (tabs.length === 0) continue;
@@ -765,6 +926,38 @@ export const useTabStore = create<TabStore>()(
),
);
+function stepHistory(
+ get: () => TabStore,
+ set: (partial: Partial<TabStore>) => void,
+ delta: -1 | 1,
+) {
+ const { activeWorkspaceSlug, byWorkspace } = get();
+ if (!activeWorkspaceSlug) return;
+ const group = byWorkspace[activeWorkspaceSlug];
+ if (!group) return;
+ const index = group.tabs.findIndex((t) => t.id === group.activeTabId);
+ if (index < 0) return;
+ const current = group.tabs[index];
+ const nextIndex = current.history.index + delta;
+ if (nextIndex < 0 || nextIndex >= current.history.stack.length) return;
+ const url = current.history.stack[nextIndex];
+ const next: TabSession = {
+ ...current,
+ url,
+ resourceKey: resourceKeyForUrl(url),
+ icon: resolveRouteIcon(splitTabUrl(url).pathname),
+ history: { ...current.history, index: nextIndex },
+ };
+ const nextTabs = [...group.tabs];
+ nextTabs[index] = next;
+ set({
+ byWorkspace: {
+ ...byWorkspace,
+ [activeWorkspaceSlug]: { ...group, tabs: nextTabs },
+ },
+ });
+}
+
// ---------------------------------------------------------------------------
// Persisted shapes (for migration)
// ---------------------------------------------------------------------------
@@ -816,6 +1009,48 @@ interface V3Persisted {
byWorkspace: Record<string, V3PersistedGroup>;
}
+interface V4PersistedTab {
+ id: string;
+ url: string;
+ title: string;
+ icon: string;
+ pinned: boolean;
+ history: { stack: string[]; index: number };
+ memento: TabMemento;
+}
+
+interface V4PersistedGroup {
+ tabs: V4PersistedTab[];
+ activeTabId: string;
+}
+
+interface V4Persisted {
+ activeWorkspaceSlug: string | null;
+ byWorkspace: Record<string, V4PersistedGroup>;
+}
+
+export function migrateV3ToV4(v3: V3Persisted): V4Persisted {
+ const byWorkspace: Record<string, V4PersistedGroup> = {};
+ for (const [slug, group] of Object.entries(v3.byWorkspace ?? {})) {
+ byWorkspace[slug] = {
+ activeTabId: group.activeTabId,
+ tabs: group.tabs.map((t) => ({
+ id: t.id,
+ url: t.path,
+ title: t.title,
+ icon: t.icon,
+ pinned: t.pinned,
+ history: { stack: [t.path], index: 0 },
+ memento: emptyMemento(),
+ })),
+ };
+ }
+ return {
+ activeWorkspaceSlug: v3.activeWorkspaceSlug ?? null,
+ byWorkspace,
+ };
+}
+
export function migrateV2ToV3(v2: V2Persisted): V3Persisted {
const byWorkspace: Record<string, V3PersistedGroup> = {};
for (const [slug, group] of Object.entries(v2.byWorkspace ?? {})) {
@@ -881,7 +1116,7 @@ export function migrateV1ToV2(v1: Partial<V1Persisted>): V2Persisted {
* need `.getState()`. For React subscriptions prefer the stable selectors
* below.
*/
-export function getActiveTab(s: TabStore): Tab | null {
+export function getActiveTab(s: TabStore): TabSession | null {
if (!s.activeWorkspaceSlug) return null;
const group = s.byWorkspace[s.activeWorkspaceSlug];
if (!group) return null;
@@ -891,13 +1126,12 @@ export function getActiveTab(s: TabStore): Tab | null {
/**
* The active workspace's tab group, or null when no workspace is active.
*
- * Zustand compares selector returns with `Object.is`. Because `updateTab`
- * / `updateTabHistory` replace the group object on every router tick
- * (immutable update), this selector returns a new reference on every
- * router event — that's fine for TabBar which needs to observe tab-list
- * changes, but don't use this selector from components that only care
- * about one primitive (use `useActiveTabHistory` / `useActiveTabRouter`
- * instead).
+ * Zustand compares selector returns with `Object.is`. Because `updateTab` /
+ * `navigateActiveSession` replace the group object on every change
+ * (immutable update), this selector returns a new reference on those
+ * events — that's fine for TabBar which needs to observe tab-list changes,
+ * but don't use this selector from components that only care about one
+ * primitive (use `useActiveTabIdentity` / `useActiveTabHistory` instead).
*/
export function useActiveGroup(): WorkspaceTabGroup | null {
return useTabStore((s) =>
@@ -907,11 +1141,7 @@ export function useActiveGroup(): WorkspaceTabGroup | null {
/**
* Active tab id + active workspace slug as a compact pair. Both primitives
- * are stable across unrelated store updates — e.g. an inactive tab's
- * router tick doesn't churn these, so consumers don't re-render.
- *
- * Useful anywhere you'd previously have reached for `useActiveTab()` and
- * only needed the identity (for memoization, effect deps, ipc).
+ * are stable across unrelated store updates, so consumers don't re-render.
*/
export function useActiveTabIdentity(): { slug: string | null; tabId: string | null } {
const slug = useTabStore((s) => s.activeWorkspaceSlug);
@@ -923,14 +1153,9 @@ export function useActiveTabIdentity(): { slug: string | null; tabId: string | n
return { slug, tabId };
}
-/**
- * Active tab's router — a stable reference across tab updates, because
- * routers are created once per tab and never replaced by `updateTab`.
- * Subscribers only re-render when the active tab *changes*, not on
- * router events within the current tab.
- */
-export function useActiveTabRouter(): DataRouter | null {
- return useTabStore((s) => getActiveTab(s)?.router ?? null);
+/** The active session's url as a primitive (Coordinator, providers). */
+export function useActiveTabUrl(): string | null {
+ return useTabStore((s) => getActiveTab(s)?.url ?? null);
}
/**
@@ -942,7 +1167,11 @@ export function useActiveTabHistory(): {
historyIndex: number;
historyLength: number;
} {
- const historyIndex = useTabStore((s) => getActiveTab(s)?.historyIndex ?? 0);
- const historyLength = useTabStore((s) => getActiveTab(s)?.historyLength ?? 1);
+ const historyIndex = useTabStore(
+ (s) => getActiveTab(s)?.history.index ?? 0,
+ );
+ const historyLength = useTabStore(
+ (s) => getActiveTab(s)?.history.stack.length ?? 1,
+ );
return { historyIndex, historyLength };
}
diff --git a/e2e/comments.spec.ts b/e2e/comments.spec.ts
index 1bd3a0c895..084cbeec83 100644
--- a/e2e/comments.spec.ts
+++ b/e2e/comments.spec.ts
@@ -29,6 +29,12 @@ test.describe("Comments", () => {
// Wait for issue detail to load
await expect(page.locator("text=Properties")).toBeVisible();
+ // The composer renders as a static shell until clicked (readonly-first);
+ // clicking it mounts and focuses the real ProseMirror editor.
+ const shell = page.getByTestId("comment-composer-shell");
+ await expect(shell).toBeVisible();
+ await shell.click();
+
// Type a comment
const commentText = "E2E comment " + Date.now();
const editor = page
@@ -52,12 +58,12 @@ test.describe("Comments", () => {
await expect(page.locator("text=Properties")).toBeVisible();
- // Submit button should be disabled when input is empty
- const editor = page
- .locator('.ProseMirror[data-placeholder="Leave a comment..."], .ProseMirror:has([data-placeholder="Leave a comment..."])')
- .first();
- await expect(editor).toBeVisible();
- const composer = editor.locator("xpath=ancestor::div[contains(@class, 'rounded-lg')][1]");
+ // Submit button should be disabled when input is empty. The composer is a
+ // static shell until clicked (readonly-first) — the disabled state must
+ // hold in shell form too, no activation needed.
+ const shell = page.getByTestId("comment-composer-shell");
+ await expect(shell).toBeVisible();
+ const composer = shell.locator("xpath=ancestor::div[contains(@class, 'rounded-lg')][1]");
const submitBtn = composer.locator("button:has(svg.lucide-arrow-up)").last();
await expect(submitBtn).toBeDisabled();
});
diff --git a/packages/ui/components/ui/context-menu.tsx b/packages/ui/components/ui/context-menu.tsx
index a401cfcb09..c74fe341dd 100644
--- a/packages/ui/components/ui/context-menu.tsx
+++ b/packages/ui/components/ui/context-menu.tsx
@@ -35,11 +35,12 @@ function ContextMenuContent({
alignOffset = 4,
side = "right",
sideOffset = 0,
+ anchor,
...props
}: ContextMenuPrimitive.Popup.Props &
Pick<
ContextMenuPrimitive.Positioner.Props,
- "align" | "alignOffset" | "side" | "sideOffset"
+ "align" | "alignOffset" | "side" | "sideOffset" | "anchor"
>) {
return (
<ContextMenuPrimitive.Portal>
@@ -49,6 +50,7 @@ function ContextMenuContent({
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
+ anchor={anchor}
>
<ContextMenuPrimitive.Popup
data-slot="context-menu-content"
diff --git a/packages/ui/components/ui/sidebar.tsx b/packages/ui/components/ui/sidebar.tsx
index caf523fd7e..3bdd0be3b4 100644
--- a/packages/ui/components/ui/sidebar.tsx
+++ b/packages/ui/components/ui/sidebar.tsx
@@ -5,7 +5,6 @@ import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { useTranslation } from "react-i18next"
-import { motion, useReducedMotion } from "motion/react"
import { useIsMobile } from "@multica/ui/hooks/use-mobile"
import { cn } from "@multica/ui/lib/utils"
@@ -35,6 +34,11 @@ const SIDEBAR_WIDTH_MAX = 360
const SIDEBAR_WIDTH_STORAGE_KEY = "sidebar_width"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
+const SIDEBAR_DRAG_THRESHOLD = 2
+
+function clampSidebarWidth(width: number) {
+ return Math.max(SIDEBAR_WIDTH_MIN, Math.min(SIDEBAR_WIDTH_MAX, width))
+}
type SidebarContextProps = {
state: "expanded" | "collapsed"
@@ -44,13 +48,16 @@ type SidebarContextProps = {
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
- width: number
- setWidth: (width: number) => void
- isResizing: boolean
- setIsResizing: (v: boolean) => void
+}
+
+type SidebarResizeContextProps = {
+ commitWidth: (width: number) => void
}
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
+// Width previews are written directly to the two layout shells during drag.
+// This context only exposes the one committed state transition on pointer-up.
+const SidebarResizeContext = React.createContext<SidebarResizeContextProps | null>(null)
function useSidebar() {
const context = React.use(SidebarContext)
@@ -65,6 +72,15 @@ function useSidebarSafe() {
return React.use(SidebarContext)
}
+function useSidebarResize() {
+ const context = React.use(SidebarResizeContext)
+ if (!context) {
+ throw new Error("useSidebarResize must be used within a SidebarProvider.")
+ }
+
+ return context
+}
+
function SidebarProvider({
defaultOpen = true,
open: openProp,
@@ -82,13 +98,17 @@ function SidebarProvider({
const [openMobile, setOpenMobile] = React.useState(false)
const [width, _setWidth] = React.useState(SIDEBAR_WIDTH_DEFAULT)
- const [isResizing, setIsResizing] = React.useState(false)
React.useEffect(() => {
const stored = localStorage.getItem(SIDEBAR_WIDTH_STORAGE_KEY)
- if (stored) _setWidth(Number(stored))
+ if (stored) {
+ const storedWidth = Number(stored)
+ if (Number.isFinite(storedWidth)) {
+ _setWidth(clampSidebarWidth(storedWidth))
+ }
+ }
}, [])
- const setWidth = React.useCallback((w: number) => {
- const clamped = Math.max(SIDEBAR_WIDTH_MIN, Math.min(SIDEBAR_WIDTH_MAX, w))
+ const commitWidth = React.useCallback((w: number) => {
+ const clamped = clampSidebarWidth(w)
_setWidth(clamped)
localStorage.setItem(SIDEBAR_WIDTH_STORAGE_KEY, String(clamped))
}, [])
@@ -130,33 +150,37 @@ function SidebarProvider({
openMobile,
setOpenMobile,
toggleSidebar,
- width,
- setWidth,
- isResizing,
- setIsResizing,
}),
- [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar, width, setWidth, isResizing, setIsResizing]
+ [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
+ )
+ const resizeContextValue = React.useMemo<SidebarResizeContextProps>(
+ () => ({
+ commitWidth,
+ }),
+ [commitWidth]
)
return (
<SidebarContext.Provider value={contextValue}>
- <div
- data-slot="sidebar-wrapper"
- style={
- {
- "--sidebar-width": `${width}px`,
- "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
- ...style,
- } as React.CSSProperties
- }
- className={cn(
- "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
- className
- )}
- {...props}
- >
- {children}
- </div>
+ <SidebarResizeContext.Provider value={resizeContextValue}>
+ <div
+ data-slot="sidebar-wrapper"
+ style={
+ {
+ "--sidebar-width": `${width}px`,
+ "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
+ ...style,
+ } as React.CSSProperties
+ }
+ className={cn(
+ "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ </SidebarResizeContext.Provider>
</SidebarContext.Provider>
)
}
@@ -174,12 +198,7 @@ function Sidebar({
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}) {
- const { isMobile, state, openMobile, setOpenMobile, isResizing, width } = useSidebar()
- const reducedMotion = useReducedMotion()
- const animateOffcanvas = collapsible === "offcanvas"
- const motionTransition = reducedMotion
- ? { duration: 0 }
- : { type: "spring" as const, stiffness: 420, damping: 38, mass: 0.8 }
+ const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
if (collapsible === "none") {
return (
@@ -232,49 +251,30 @@ function Sidebar({
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
- <motion.div
+ <div
data-slot="sidebar-gap"
className={cn(
- "relative w-(--sidebar-width) bg-transparent",
- !animateOffcanvas && !isResizing && "transition-[width] duration-200 ease-linear",
- !animateOffcanvas && "group-data-[collapsible=offcanvas]:w-0",
+ "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-out motion-reduce:transition-none",
+ "group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
- ? !animateOffcanvas && "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
- : !animateOffcanvas && "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
+ ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
)}
- animate={animateOffcanvas ? { width: state === "collapsed" ? 0 : width } : undefined}
- initial={false}
- transition={motionTransition}
/>
- <motion.div
+ <div
data-slot="sidebar-container"
data-side={side}
className={cn(
- "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) md:flex",
- animateOffcanvas
- ? side === "left"
- ? "left-0"
- : "right-0"
- : "data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
- !animateOffcanvas && !isResizing && "transition-[left,right,width] duration-200 ease-linear",
+ "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-out motion-reduce:transition-none md:flex",
+ "data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
)}
- animate={
- animateOffcanvas
- ? {
- x: state === "collapsed" ? (side === "left" ? -width : width) : 0,
- width,
- }
- : undefined
- }
- initial={false}
- transition={motionTransition}
- {...(props as React.ComponentProps<typeof motion.div>)}
+ {...props}
>
<div
data-sidebar="sidebar"
@@ -283,7 +283,7 @@ function Sidebar({
>
{children}
</div>
- </motion.div>
+ </div>
</div>
)
}
@@ -316,42 +316,127 @@ function SidebarTrigger({
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
- const { toggleSidebar, setWidth, setIsResizing } = useSidebar()
+ const { toggleSidebar } = useSidebar()
+ const { commitWidth } = useSidebarResize()
const { t } = useTranslation("ui")
const toggleLabel = t(($) => $.toggle_sidebar)
const didDragRef = React.useRef(false)
- const dragRef = React.useRef<{ startX: number; startWidth: number } | null>(null)
-
- const onMouseDown = React.useCallback(
- (e: React.MouseEvent) => {
+ const dragRef = React.useRef<{
+ pointerId: number
+ startX: number
+ startWidth: number
+ latestWidth: number
+ direction: 1 | -1
+ wrapperEl: HTMLElement
+ gapEl: HTMLElement
+ containerEl: HTMLElement
+ } | null>(null)
+ const cancelActiveDragRef = React.useRef<(() => void) | null>(null)
+
+ React.useEffect(() => () => cancelActiveDragRef.current?.(), [])
+
+ const onPointerDown = React.useCallback(
+ (e: React.PointerEvent<HTMLButtonElement>) => {
+ if (e.button !== 0 || e.isPrimary === false) return
e.preventDefault()
+ cancelActiveDragRef.current?.()
didDragRef.current = false
- const sidebarEl = (e.target as HTMLElement).closest("[data-slot='sidebar']")
- const containerEl = sidebarEl?.querySelector("[data-slot='sidebar-container']")
- if (!containerEl) return
- dragRef.current = { startX: e.clientX, startWidth: containerEl.getBoundingClientRect().width }
- setIsResizing(true)
-
- const onMouseMove = (ev: MouseEvent) => {
- if (!dragRef.current) return
- didDragRef.current = true
- const delta = ev.clientX - dragRef.current.startX
- setWidth(dragRef.current.startWidth + delta)
+ const railEl = e.currentTarget
+ const sidebarEl = railEl.closest<HTMLElement>("[data-slot='sidebar']")
+ const wrapperEl = railEl.closest<HTMLElement>("[data-slot='sidebar-wrapper']")
+ const gapEl = sidebarEl?.querySelector<HTMLElement>("[data-slot='sidebar-gap']")
+ const containerEl = sidebarEl?.querySelector<HTMLElement>("[data-slot='sidebar-container']")
+ if (!sidebarEl || !wrapperEl || !gapEl || !containerEl) return
+
+ const startWidth = clampSidebarWidth(containerEl.getBoundingClientRect().width)
+ dragRef.current = {
+ pointerId: e.pointerId,
+ startX: e.clientX,
+ startWidth,
+ latestWidth: startWidth,
+ direction: sidebarEl.dataset.side === "right" ? -1 : 1,
+ wrapperEl,
+ gapEl,
+ containerEl,
}
- const onMouseUp = () => {
+
+ wrapperEl.setAttribute("data-sidebar-resizing", "true")
+ document.documentElement.setAttribute("data-sidebar-resizing", "true")
+
+ let finished = false
+ const finishDrag = (mode: "commit" | "cancel") => {
+ if (finished) return
+ finished = true
+
+ document.removeEventListener("pointermove", onPointerMove)
+ document.removeEventListener("pointerup", onPointerUp)
+ document.removeEventListener("pointercancel", onPointerCancel)
+ window.removeEventListener("blur", onWindowBlur)
+ railEl.removeEventListener("lostpointercapture", onLostPointerCapture)
+
+ const drag = dragRef.current
+ if (drag) {
+ if (mode === "commit" && didDragRef.current) {
+ drag.wrapperEl.style.setProperty(
+ "--sidebar-width",
+ `${drag.latestWidth}px`
+ )
+ commitWidth(drag.latestWidth)
+ }
+ drag.gapEl.style.removeProperty("width")
+ drag.containerEl.style.removeProperty("width")
+ drag.wrapperEl.removeAttribute("data-sidebar-resizing")
+ }
+
dragRef.current = null
- setIsResizing(false)
- document.removeEventListener("mousemove", onMouseMove)
- document.removeEventListener("mouseup", onMouseUp)
- document.body.style.cursor = ""
- document.body.style.userSelect = ""
+ cancelActiveDragRef.current = null
+ document.documentElement.removeAttribute("data-sidebar-resizing")
+
+ if (railEl.hasPointerCapture?.(e.pointerId)) {
+ railEl.releasePointerCapture?.(e.pointerId)
+ }
+ }
+
+ const onPointerMove = (event: PointerEvent) => {
+ const drag = dragRef.current
+ if (!drag || event.pointerId !== drag.pointerId) return
+
+ const delta = (event.clientX - drag.startX) * drag.direction
+ if (!didDragRef.current && Math.abs(delta) < SIDEBAR_DRAG_THRESHOLD) {
+ return
+ }
+
+ didDragRef.current = true
+ const nextWidth = clampSidebarWidth(drag.startWidth + delta)
+ if (nextWidth === drag.latestWidth) return
+
+ drag.latestWidth = nextWidth
+ // Only the two layout shells depend on the live width. Direct writes
+ // let the browser coalesce layout at paint time without a React commit
+ // or an inherited custom-property invalidation on the whole app tree.
+ drag.gapEl.style.width = `${nextWidth}px`
+ drag.containerEl.style.width = `${nextWidth}px`
+ }
+ const onPointerUp = (event: PointerEvent) => {
+ if (event.pointerId === e.pointerId) finishDrag("commit")
+ }
+ const onPointerCancel = (event: PointerEvent) => {
+ if (event.pointerId === e.pointerId) finishDrag("cancel")
+ }
+ const onLostPointerCapture = (event: PointerEvent) => {
+ if (event.pointerId === e.pointerId) finishDrag("cancel")
}
- document.addEventListener("mousemove", onMouseMove)
- document.addEventListener("mouseup", onMouseUp)
- document.body.style.cursor = "col-resize"
- document.body.style.userSelect = "none"
+ const onWindowBlur = () => finishDrag("cancel")
+
+ document.addEventListener("pointermove", onPointerMove)
+ document.addEventListener("pointerup", onPointerUp)
+ document.addEventListener("pointercancel", onPointerCancel)
+ window.addEventListener("blur", onWindowBlur)
+ railEl.addEventListener("lostpointercapture", onLostPointerCapture)
+ cancelActiveDragRef.current = () => finishDrag("cancel")
+ railEl.setPointerCapture?.(e.pointerId)
},
- [setWidth, setIsResizing]
+ [commitWidth]
)
const handleClick = React.useCallback(() => {
@@ -366,11 +451,10 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
aria-label={toggleLabel}
tabIndex={-1}
onClick={handleClick}
- onMouseDown={onMouseDown}
+ onPointerDown={onPointerDown}
title={toggleLabel}
className={cn(
- "absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
- "in-data-[side=left]:cursor-col-resize in-data-[side=right]:cursor-col-resize",
+ "absolute inset-y-0 z-20 hidden w-4 touch-none cursor-ew-resize transition-[transform,background-color] ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
diff --git a/packages/ui/components/ui/tooltip.tsx b/packages/ui/components/ui/tooltip.tsx
index a6d020e145..3172605caa 100644
--- a/packages/ui/components/ui/tooltip.tsx
+++ b/packages/ui/components/ui/tooltip.tsx
@@ -31,12 +31,13 @@ function TooltipContent({
sideOffset = 4,
align = "center",
alignOffset = 0,
+ anchor,
children,
...props
}: TooltipPrimitive.Popup.Props &
Pick<
TooltipPrimitive.Positioner.Props,
- "align" | "alignOffset" | "side" | "sideOffset"
+ "align" | "alignOffset" | "side" | "sideOffset" | "anchor"
>) {
return (
<TooltipPrimitive.Portal>
@@ -45,6 +46,7 @@ function TooltipContent({
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
+ anchor={anchor}
className="isolate z-50"
>
<TooltipPrimitive.Popup
diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.css
index ab562383f1..270a38a910 100644
--- a/packages/ui/styles/base.css
+++ b/packages/ui/styles/base.css
@@ -218,6 +218,26 @@
color: var(--sidebar-accent-foreground);
}
+/* Sidebar resizing follows the same cursor contract as
+ * react-resizable-panels: the resize cursor survives leaving the narrow rail
+ * and wins over descendants with their own cursor declarations. Live width is
+ * written directly to the two layout shells, so their toggle transitions must
+ * stay disabled until the gesture finishes. */
+html[data-sidebar-resizing="true"],
+html[data-sidebar-resizing="true"] * {
+ cursor: ew-resize !important;
+ user-select: none !important;
+}
+
+[data-sidebar-resizing="true"] [data-slot="sidebar-gap"],
+[data-sidebar-resizing="true"] [data-slot="sidebar-container"] {
+ transition: none !important;
+}
+
+[data-sidebar-resizing="true"] [data-sidebar="rail"]::after {
+ background-color: var(--sidebar-border);
+}
+
/* Right detail sidebars use react-resizable-panels, which sizes panels by
* updating the outer panel's flex-grow. Animate that property for button
* toggles only; mount-time layout restoration and resize sync should snap
diff --git a/packages/views/common/actor-avatar.tsx b/packages/views/common/actor-avatar.tsx
index 71ac9b066e..3681ae2dd5 100644
--- a/packages/views/common/actor-avatar.tsx
+++ b/packages/views/common/actor-avatar.tsx
@@ -270,9 +270,22 @@ function SquadAvatarHoverCard({
);
}
+// Matches Base UI PreviewCard's OPEN_DELAY, so the emulated first-dwell open
+// below feels identical to the native hover-open.
+const HOVER_CARD_OPEN_DELAY = 600;
+
// Common chrome shared between agent and member hover cards. Keeps focus
// behaviour and width consistent so the two surfaces feel structurally
// parallel — content varies, frame doesn't.
+//
+// The HoverCard (Base UI PreviewCard root + trigger) mounts lazily on first
+// pointerenter/focus: dense surfaces render hundreds of these avatars and the
+// per-instance popup machinery was a measurable slice of surface remount cost.
+// Cold phase renders the same span with identical classes, so the swap is
+// invisible. Because the pointer is already inside the trigger when the real
+// HoverCard mounts, Base UI's own hover-open never fires for that first dwell
+// — a manual timer with the same delay emulates it; afterwards Base UI drives
+// the controlled `open` via `onOpenChange`.
function ActorAvatarHoverCardShell({
content,
children,
@@ -282,6 +295,10 @@ function ActorAvatarHoverCardShell({
}) {
const triggerRef = useRef<HTMLSpanElement>(null);
const [standalone, setStandalone] = useState(false);
+ const [warm, setWarm] = useState(false);
+ const [open, setOpen] = useState(false);
+ const openTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const restoreFocusRef = useRef(false);
useEffect(() => {
const el = triggerRef.current;
@@ -290,16 +307,59 @@ function ActorAvatarHoverCardShell({
setStandalone(!ancestor);
}, []);
+ // A focus-triggered swap unmounts the focused cold span; give focus back to
+ // the real trigger so Escape/blur keep working.
+ useEffect(() => {
+ if (warm && restoreFocusRef.current) {
+ restoreFocusRef.current = false;
+ triggerRef.current?.focus();
+ }
+ }, [warm]);
+
+ const clearOpenTimer = () => {
+ if (openTimerRef.current !== null) {
+ clearTimeout(openTimerRef.current);
+ openTimerRef.current = null;
+ }
+ };
+ useEffect(() => clearOpenTimer, []);
+
+ const tabIndex = standalone ? 0 : -1;
+ const className = standalone
+ ? "inline-flex cursor-pointer rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ : "inline-flex cursor-pointer";
+
+ if (!warm) {
+ return (
+ <span
+ ref={triggerRef}
+ tabIndex={tabIndex}
+ className={className}
+ onPointerEnter={() => {
+ setWarm(true);
+ openTimerRef.current = setTimeout(
+ () => setOpen(true),
+ HOVER_CARD_OPEN_DELAY,
+ );
+ }}
+ onFocus={() => {
+ restoreFocusRef.current = true;
+ setWarm(true);
+ setOpen(true);
+ }}
+ >
+ {children}
+ </span>
+ );
+ }
+
return (
- <HoverCard>
+ <HoverCard open={open} onOpenChange={setOpen}>
<HoverCardTrigger
render={<span ref={triggerRef} />}
- tabIndex={standalone ? 0 : -1}
- className={
- standalone
- ? "inline-flex cursor-pointer rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- : "inline-flex cursor-pointer"
- }
+ tabIndex={tabIndex}
+ className={className}
+ onPointerLeave={clearOpenTimer}
>
{children}
</HoverCardTrigger>
diff --git a/packages/views/common/date-only-picker.tsx b/packages/views/common/date-only-picker.tsx
index e740018b9f..eab2dfc12c 100644
--- a/packages/views/common/date-only-picker.tsx
+++ b/packages/views/common/date-only-picker.tsx
@@ -14,30 +14,16 @@ import {
PopoverContent,
} from "@multica/ui/components/ui/popover";
import { Button } from "@multica/ui/components/ui/button";
+import { DeferredPopup } from "./deferred-popup";
/**
- * Entity-agnostic calendar-day picker: the shared behaviour behind every
- * start/due-date pill (issues, projects, …). It owns the Popover + Calendar +
- * clear wiring and the calendar-day transport ("YYYY-MM-DD", no timezone shift,
- * via @multica/core/issues/date); each entity wraps it to supply only the field
- * name (through `onChange`), the icon, and the localized copy. Keeping this in
- * one place stops the per-entity pills from drifting in behaviour or display
- * formatting.
+ * Default class of the date pill trigger — shared with the deferred lookalike
+ * trigger so the swap on first interaction is pixel-identical.
*/
-export function DateOnlyPicker({
- value,
- onChange,
- icon,
- placeholder,
- clearLabel,
- highlightOverdue = false,
- trigger: customTrigger,
- triggerRender,
- open: controlledOpen,
- onOpenChange: controlledOnOpenChange,
- align = "start",
- defaultOpen = false,
-}: {
+const DATE_TRIGGER_CLASS =
+ "flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors";
+
+interface DateOnlyPickerProps {
/** Selected calendar day ("YYYY-MM-DD") or null. */
value: string | null;
/** Emits the new calendar day, or null when cleared. */
@@ -53,37 +39,105 @@ export function DateOnlyPicker({
/** Fully custom trigger contents (replaces the icon + date/placeholder). */
trigger?: React.ReactNode;
/** Custom trigger element (e.g. a pill button). */
- triggerRender?: React.ReactElement;
+ triggerRender?: React.ReactElement<Record<string, unknown>>;
/** Controlled open state — lets a ⋯ overflow menu reveal + open the pill. */
open?: boolean;
onOpenChange?: (v: boolean) => void;
align?: "start" | "center" | "end";
/** Open the popover on first mount (progressive-disclosure sidebars). */
defaultOpen?: boolean;
-}) {
+}
+
+/**
+ * Entity-agnostic calendar-day picker: the shared behaviour behind every
+ * start/due-date pill (issues, projects, …). It owns the Popover + Calendar +
+ * clear wiring and the calendar-day transport ("YYYY-MM-DD", no timezone shift,
+ * via @multica/core/issues/date); each entity wraps it to supply only the field
+ * name (through `onChange`), the icon, and the localized copy. Keeping this in
+ * one place stops the per-entity pills from drifting in behaviour or display
+ * formatting.
+ *
+ * Uncontrolled usages render a deferred lookalike trigger and mount the
+ * Popover + Calendar machinery on first interaction — the default trigger is
+ * computable from props alone, so every uncontrolled pill defers. See
+ * `DeferredPopup` for why.
+ */
+export function DateOnlyPicker(props: DateOnlyPickerProps) {
+ const canDefer =
+ props.open === undefined &&
+ props.onOpenChange === undefined &&
+ !props.defaultOpen;
+ if (!canDefer) {
+ return <DateOnlyPickerImpl {...props} />;
+ }
+ return (
+ <DeferredPopup
+ trigger={props.trigger ?? <DateTriggerContent {...props} />}
+ triggerRender={props.triggerRender}
+ triggerClassName={DATE_TRIGGER_CLASS}
+ >
+ {(open, onOpenChange) => (
+ <DateOnlyPickerImpl {...props} open={open} onOpenChange={onOpenChange} />
+ )}
+ </DeferredPopup>
+ );
+}
+
+/** Default trigger content, kept identical to what the Impl renders. */
+function DateTriggerContent({
+ value,
+ icon,
+ placeholder,
+ highlightOverdue = false,
+}: Pick<DateOnlyPickerProps, "value" | "icon" | "placeholder" | "highlightOverdue">) {
+ const date = dateOnlyToLocalDate(value);
+ const overdue = highlightOverdue && isPastDateOnly(value);
+ return (
+ <>
+ {icon}
+ {date ? (
+ <span className={overdue ? "text-destructive" : ""}>
+ {formatDateOnly(value, { month: "short", day: "numeric" }, "en-US")}
+ </span>
+ ) : (
+ <span className="text-muted-foreground">{placeholder}</span>
+ )}
+ </>
+ );
+}
+
+function DateOnlyPickerImpl({
+ value,
+ onChange,
+ icon,
+ placeholder,
+ clearLabel,
+ highlightOverdue = false,
+ trigger: customTrigger,
+ triggerRender,
+ open: controlledOpen,
+ onOpenChange: controlledOnOpenChange,
+ align = "start",
+ defaultOpen = false,
+}: DateOnlyPickerProps) {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const open = controlledOpen ?? internalOpen;
const setOpen = controlledOnOpenChange ?? setInternalOpen;
const date = dateOnlyToLocalDate(value);
- const overdue = highlightOverdue && isPastDateOnly(value);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
- className={triggerRender ? undefined : "flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors"}
+ className={triggerRender ? undefined : DATE_TRIGGER_CLASS}
render={triggerRender}
>
{customTrigger ?? (
- <>
- {icon}
- {date ? (
- <span className={overdue ? "text-destructive" : ""}>
- {formatDateOnly(value, { month: "short", day: "numeric" }, "en-US")}
- </span>
- ) : (
- <span className="text-muted-foreground">{placeholder}</span>
- )}
- </>
+ <DateTriggerContent
+ value={value}
+ icon={icon}
+ placeholder={placeholder}
+ highlightOverdue={highlightOverdue}
+ />
)}
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align={align}>
diff --git a/packages/views/common/deferred-popup.tsx b/packages/views/common/deferred-popup.tsx
new file mode 100644
index 0000000000..b4db1b23e0
--- /dev/null
+++ b/packages/views/common/deferred-popup.tsx
@@ -0,0 +1,94 @@
+"use client";
+
+import { cloneElement, useState, type ReactElement, type ReactNode } from "react";
+
+/**
+ * Defers mounting a popup component (Popover/Menu root + trigger machinery)
+ * until the user first interacts with its trigger.
+ *
+ * Dense surfaces (board cards, list rows) mount several pickers per item, and
+ * each one carries a Base UI root/trigger tree plus its own query
+ * subscriptions — even though almost none are ever opened. Rendering a plain
+ * lookalike trigger first and swapping in the real picker on interaction cuts
+ * that per-item mount cost to zero for untouched items (MUL-4474 follow-up:
+ * the tab-switch remount froze the main thread for seconds mostly on these).
+ *
+ * Upgrade triggers — deliberately only events that END a gesture:
+ * - `click` mounts the real component and opens it in one step. Opening on
+ * click matches Base UI's own trigger timing exactly, and because nothing
+ * swaps the element mid-gesture (no pointerenter/pointerdown warming),
+ * every event of the gesture lands on a node that is still attached —
+ * both for real pointers and for synthetic sequences (tests, assistive
+ * tech). The in-flight click is stopped from propagating so the popup's
+ * just-mounted outside-press dismissal doesn't treat it as an outside
+ * click and close the popover in the same breath.
+ * - `Enter`/`Space` do the same for keyboard.
+ *
+ * Only for uncontrolled usages: callers that pass `open`/`onOpenChange`/
+ * `defaultOpen` need the real component from the start.
+ */
+export function DeferredPopup({
+ trigger,
+ triggerRender,
+ triggerClassName,
+ ariaHasPopup = "dialog",
+ children,
+}: {
+ /** Trigger content, matching what the host passes to its popup trigger. */
+ trigger?: ReactNode;
+ /** Custom trigger element, matching the host's `triggerRender` prop. */
+ triggerRender?: ReactElement<Record<string, unknown>>;
+ /**
+ * Class of the host's default trigger element. Must stay byte-identical to
+ * the class the real (non-deferred) trigger renders with, so the swap is
+ * invisible.
+ */
+ triggerClassName?: string;
+ /** ARIA popup kind of the real trigger ("dialog" for popovers, "menu" for
+ * dropdown menus) so the cold trigger reads the same to assistive tech. */
+ ariaHasPopup?: "dialog" | "menu";
+ /** Renders the real component once upgraded. */
+ children: (open: boolean, onOpenChange: (v: boolean) => void) => ReactNode;
+}) {
+ const [mounted, setMounted] = useState(false);
+ const [open, setOpen] = useState(false);
+
+ if (mounted) {
+ return <>{children(open, setOpen)}</>;
+ }
+
+ const mountOpen = () => {
+ setMounted(true);
+ setOpen(true);
+ };
+ const handleKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ e.stopPropagation();
+ mountOpen();
+ }
+ };
+ const handlers = {
+ onClick: (e: React.MouseEvent) => {
+ e.stopPropagation();
+ mountOpen();
+ },
+ onKeyDown: handleKeyDown,
+ "aria-haspopup": ariaHasPopup,
+ };
+
+ if (triggerRender) {
+ // Mirror Base UI's render-prop semantics: the render element's own
+ // children win over the component-level trigger content.
+ if (triggerRender.props.children != null) {
+ return cloneElement(triggerRender, handlers);
+ }
+ return cloneElement(triggerRender, handlers, trigger);
+ }
+
+ return (
+ <button type="button" className={triggerClassName} {...handlers}>
+ {trigger}
+ </button>
+ );
+}
diff --git a/packages/views/common/deferred-tooltip.tsx b/packages/views/common/deferred-tooltip.tsx
new file mode 100644
index 0000000000..ce5e94b13c
--- /dev/null
+++ b/packages/views/common/deferred-tooltip.tsx
@@ -0,0 +1,86 @@
+"use client";
+
+import {
+ cloneElement,
+ useEffect,
+ useRef,
+ useState,
+ type ReactElement,
+ type ReactNode,
+} from "react";
+import { Tooltip, TooltipContent } from "@multica/ui/components/ui/tooltip";
+
+// Matches the ui TooltipProvider default delay so the deferred first-open
+// feels identical to a native tooltip.
+const TOOLTIP_OPEN_DELAY = 200;
+
+/**
+ * Tooltip whose machinery mounts only on first hover.
+ *
+ * Dense grids (board/swimlane column headers) mount hundreds of tooltip
+ * roots that are almost never hovered — a measurable slice of surface mount
+ * cost. This wrapper renders ONLY the trigger element until the pointer
+ * first enters it, then mounts a controlled Tooltip anchored to that same
+ * element.
+ *
+ * Unlike a trigger-swap approach, the trigger element is rendered by this
+ * component in the same tree position before and after warming — its DOM
+ * node is preserved, so mid-gesture events (the hover's own click) never
+ * land on a detached node. Hover open/close is driven here (timer on enter,
+ * close on leave); the popup positions against the trigger via an anchor
+ * ref instead of a Base UI trigger wrapper.
+ */
+export function DeferredTooltip({
+ trigger,
+ content,
+ side,
+}: {
+ /** The visible trigger element (e.g. an icon button). Cloned with hover
+ * handlers and an anchor ref; its own props are preserved. */
+ trigger: ReactElement<Record<string, unknown>>;
+ content: ReactNode;
+ side?: "top" | "bottom" | "left" | "right";
+}) {
+ const anchorRef = useRef<HTMLElement | null>(null);
+ const [warm, setWarm] = useState(false);
+ const [open, setOpen] = useState(false);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const clearTimer = () => {
+ if (timerRef.current !== null) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ };
+ useEffect(() => clearTimer, []);
+
+ const element = cloneElement(trigger, {
+ ref: (el: HTMLElement | null) => {
+ anchorRef.current = el;
+ },
+ onPointerEnter: (e: React.PointerEvent) => {
+ (trigger.props.onPointerEnter as ((e: React.PointerEvent) => void) | undefined)?.(e);
+ setWarm(true);
+ clearTimer();
+ timerRef.current = setTimeout(() => setOpen(true), TOOLTIP_OPEN_DELAY);
+ },
+ onPointerLeave: (e: React.PointerEvent) => {
+ (trigger.props.onPointerLeave as ((e: React.PointerEvent) => void) | undefined)?.(e);
+ clearTimer();
+ setOpen(false);
+ },
+ });
+
+ return (
+ <>
+ {element}
+ {warm && (
+ <Tooltip open={open} onOpenChange={setOpen}>
+ <TooltipContent side={side} anchor={anchorRef}>
+ {content}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </>
+ );
+}
diff --git a/packages/views/common/virtuoso-seed.tsx b/packages/views/common/virtuoso-seed.tsx
new file mode 100644
index 0000000000..16486f3a4d
--- /dev/null
+++ b/packages/views/common/virtuoso-seed.tsx
@@ -0,0 +1,71 @@
+"use client";
+
+import { Fragment, type Key, type ReactNode } from "react";
+
+/**
+ * Upper bound on rows rendered in the first-paint seed ({@link VirtuosoSeed})
+ * and passed as `initialItemCount` to the virtualized issue/inbox lists.
+ *
+ * One screen's worth of rows is enough to fill the viewport on a route-return
+ * remount; the real Virtuoso trims to its measured window on the next frame.
+ * Capped so a large list never pays a full synchronous mount — the crash the
+ * un-capped pre-virtualization path hit on real Desktop (MUL-4750).
+ */
+export const VIRTUOSO_SEED_COUNT = 30;
+
+/**
+ * Non-virtualized fallback for the frame(s) before a Virtuoso's
+ * `customScrollParent` is ready.
+ *
+ * The issue/inbox lists hand Virtuoso the scroll element through a callback
+ * ref that lands in state, so the first render after a remount has
+ * `scrollParent === null` and Virtuoso cannot mount yet. Rendering nothing
+ * there paints an empty card area (group/column headers present, rows blank)
+ * until the ref settles and measurement completes — the flash that got the
+ * MUL-4474 virtualization reverted. Seeding a bounded slice of the real rows
+ * keeps that first frame populated; once the parent is set the list switches
+ * to `<Virtuoso>` with a matching `initialItemCount`, so the handoff is
+ * visually continuous.
+ *
+ * Reuses the caller's own `itemContent`/`computeItemKey`, so a seeded row is
+ * byte-identical to its virtualized counterpart — there is no second render
+ * path to drift.
+ *
+ * With `estimatedItemHeight` set, unseeded rows get a single trailing spacer
+ * sized `remaining × estimate`, so the scroll height (and thus the scrollbar
+ * thumb) approximates the full list from the first frame. Without it, the
+ * seed frame's scroll height is only the seeded rows, and the handoff to
+ * Virtuoso — which spaces out the full count — visibly re-draws the
+ * scrollbar. Pass the same estimate as the Virtuoso's `defaultItemHeight` so
+ * both phases agree until real measurements land.
+ */
+export function VirtuosoSeed<T>({
+ data,
+ itemContent,
+ computeItemKey,
+ count = VIRTUOSO_SEED_COUNT,
+ estimatedItemHeight,
+}: {
+ data: T[];
+ itemContent: (index: number, item: T) => ReactNode;
+ computeItemKey: (index: number, item: T) => Key;
+ count?: number;
+ /** Estimated row height (px, including any per-row gap) used to reserve
+ * scroll height for the rows beyond `count`. */
+ estimatedItemHeight?: number;
+}) {
+ const seeded = data.slice(0, count);
+ const remaining = data.length - seeded.length;
+ return (
+ <>
+ {seeded.map((item, index) => (
+ <Fragment key={computeItemKey(index, item)}>
+ {itemContent(index, item)}
+ </Fragment>
+ ))}
+ {estimatedItemHeight !== undefined && remaining > 0 && (
+ <div aria-hidden style={{ height: remaining * estimatedItemHeight }} />
+ )}
+ </>
+ );
+}
diff --git a/packages/views/editor/code-block-static.test.tsx b/packages/views/editor/code-block-static.test.tsx
index 8d6dfe995c..9f5caf16ed 100644
--- a/packages/views/editor/code-block-static.test.tsx
+++ b/packages/views/editor/code-block-static.test.tsx
@@ -16,6 +16,16 @@ describe("CodeBlockStatic", () => {
expect(code?.textContent).toBe("uv run --extra dev pytest -q");
});
+ it("renders unlabelled code without auto-detected highlight spans", () => {
+ const { container } = render(
+ <CodeBlockStatic language={undefined} body="const answer = 42;" />,
+ );
+
+ const code = container.querySelector("pre.rich-text-editor code");
+ expect(code?.textContent).toBe("const answer = 42;");
+ expect(code?.querySelector("span")).toBeNull();
+ });
+
it("keeps standalone static code blocks under the block-code CSS selectors", () => {
const codeCss = readFileSync("editor/styles/code.css", "utf8");
diff --git a/packages/views/editor/code-block-static.tsx b/packages/views/editor/code-block-static.tsx
index f6c58b49ed..8034bef889 100644
--- a/packages/views/editor/code-block-static.tsx
+++ b/packages/views/editor/code-block-static.tsx
@@ -14,13 +14,11 @@
*/
import { useMemo } from "react";
-import { createLowlight, common } from "lowlight";
import { toHtml } from "hast-util-to-html";
import { cn } from "@multica/ui/lib/utils";
+import { highlightCode } from "./syntax-highlight";
import "./styles/code.css";
-const lowlight = createLowlight(common);
-
interface CodeBlockStaticProps {
language: string | undefined;
body: string;
@@ -31,13 +29,10 @@ export function CodeBlockStatic({ language, body, className }: CodeBlockStaticPr
const html = useMemo(() => {
const code = body.replace(/\n$/, "");
try {
- const tree = language
- ? lowlight.highlight(language, code)
- : lowlight.highlightAuto(code);
+ const tree = highlightCode(code, language);
return toHtml(tree) as string;
} catch {
- // Unknown language tag — fall back to escaped plain text so we don't
- // crash on an esoteric extension.
+ // Keep an unexpected highlighter failure from breaking the preview.
return escapeHtml(code);
}
}, [body, language]);
diff --git a/packages/views/editor/content-editor.test.tsx b/packages/views/editor/content-editor.test.tsx
index bb406ff16d..dd74b312e8 100644
--- a/packages/views/editor/content-editor.test.tsx
+++ b/packages/views/editor/content-editor.test.tsx
@@ -192,6 +192,19 @@ describe("ContentEditor", () => {
);
});
+ it("does not parse the initial defaultValue twice when markdown round-trip canonicalizes it", () => {
+ // useEditor already parsed defaultValue through its `content` option. The
+ // editor's canonical Markdown can legitimately differ from the source, so
+ // that difference alone must not trigger an immediate second setContent.
+ editorState.markdown = "- [ ] canonical task";
+
+ render(
+ <ContentEditor defaultValue={"- [ ] source task\n\ncontinuation"} />,
+ );
+
+ expect(mockSetContent).not.toHaveBeenCalled();
+ });
+
it("does not sync while a file upload is in flight (in-flight upload node must survive external defaultValue changes)", () => {
editorState.markdown = "old content";
const { rerender } = render(<ContentEditor defaultValue="old content" />);
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 1d834cc4f7..9c408bf870 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -61,6 +61,7 @@ import { preprocessMarkdown } from "./utils/preprocess";
import { repairEmptyListItems } from "./utils/repair-list-items";
import { openLink, isMentionHref } from "./utils/link-handler";
import { EditorBubbleMenu } from "./bubble-menu";
+import { posFromAnchor, type TextAnchor } from "./text-anchor";
import { useLinkHover, LinkHoverCard } from "./link-hover-card";
import { AttachmentDownloadProvider } from "./attachment-download-context";
import "katex/dist/katex.min.css";
@@ -165,12 +166,37 @@ interface ContentEditorProps {
* before the modal closes.
*/
flushPendingOnUnmount?: boolean;
+ /**
+ * Called once when the Tiptap instance exists and its initial content is
+ * set (creation is deferred past first paint by `immediatelyRender: false`).
+ * Readonly-first hosts such as comment and reply composers use this as the
+ * signal to swap their static shell for the live editor.
+ */
+ onReady?: () => void;
}
interface ContentEditorRef {
getMarkdown: () => string;
clearContent: () => void;
focus: () => void;
+ /**
+ * Focus and place the caret at the document position under the given
+ * viewport coordinates. Used by readonly-first hosts so the click that
+ * summoned the editor lands the caret where the user clicked, matching
+ * the always-mounted editor's behavior. Falls back to focusing the end
+ * when no position resolves (click below the last line). Must be called
+ * while the editor element is laid out (not display: none).
+ */
+ focusAtCoords: (coords: { x: number; y: number }) => void;
+ /**
+ * Focus and place the caret at the document position a text anchor
+ * resolves to. Preferred over `focusAtCoords` for readonly-first hosts:
+ * the anchor is a logical position ("block N, character M"), so it is
+ * immune to layout differences between the readonly render and the
+ * editor render — which is exactly where pixel coordinates drift on
+ * long documents.
+ */
+ focusAtAnchor: (anchor: TextAnchor) => void;
/** Drop focus from the editor — used by chat after send so the caret
* stops competing with the StatusPill / streaming reply for the user's
* attention. */
@@ -204,6 +230,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
slashCommandMode = "skill",
attachments,
flushPendingOnUnmount = false,
+ onReady,
},
ref,
) {
@@ -216,11 +243,17 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
const onUpdateRef = useRef(onUpdate);
const onSubmitRef = useRef(onSubmit);
const onBlurRef = useRef(onBlur);
+ const onReadyRef = useRef(onReady);
const onUploadFileRef = useRef<
((file: File) => Promise<UploadResult | null>) | undefined
>(undefined);
const mentionContextItemsRef = useRef<MentionItem[]>(mentionContextItems ?? []);
const lastEmittedRef = useRef<string | null>(null);
+ // `content` already consumes the initial defaultValue when Tiptap mounts.
+ // Track the prop separately so the external-sync effect only handles real
+ // changes after mount, not Markdown serializer canonicalization from that
+ // first parse.
+ const lastDefaultValueRef = useRef(defaultValue);
// Live placeholder text. Passed into the Placeholder extension as a getter
// (not a static string) so the plugin re-reads it on every decoration pass —
// the sync effect below updates this ref and nudges a repaint. Tiptap
@@ -299,6 +332,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
onUpdateRef.current = onUpdate;
onSubmitRef.current = onSubmit;
onBlurRef.current = onBlur;
+ onReadyRef.current = onReady;
onUploadFileRef.current = wrappedOnUploadFile;
mentionContextItemsRef.current = mentionContextItems ?? [];
flushPendingOnUnmountRef.current = flushPendingOnUnmount;
@@ -435,6 +469,16 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
},
});
+ // Signal hosts that the deferred editor instance now exists. Fired from a
+ // passive effect (not `onCreate`) so it runs after the commit in which
+ // <EditorContent> attached the editor DOM — callers can measure/focus it.
+ const readyFiredRef = useRef(false);
+ useEffect(() => {
+ if (!editor || readyFiredRef.current) return;
+ readyFiredRef.current = true;
+ onReadyRef.current?.();
+ }, [editor]);
+
// Cleanup on unmount. A pending debounced update is DROPPED by default,
// not flushed — see the `flushPendingOnUnmount` prop doc for why. When the
// owner opted in, emit the markdown cached at `onUpdate` time so a long
@@ -460,6 +504,16 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
useEffect(() => {
if (!editor || editor.isDestroyed) return;
+ const previousDefaultValue = lastDefaultValueRef.current;
+ lastDefaultValueRef.current = defaultValue;
+
+ // The initial defaultValue was already parsed through useEditor's
+ // `content` option (or in onCreate for the chunked path). Comparing that
+ // source Markdown to Tiptap's canonical serialization can differ even
+ // when they represent the same document, and used to cause an immediate
+ // second full parse. Only later prop changes belong to this sync effect.
+ if (defaultValue === previousDefaultValue) return;
+
// Guard 0: never clobber an in-flight upload. An external `defaultValue`
// change can arrive mid-upload — e.g. chat lazy-creates a session on the
// first file upload, which flips `activeSessionId` → the draft key →
@@ -562,6 +616,24 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
// Editor not mounted yet — defer the focus to `onCreate`.
else focusOnReadyRef.current = true;
},
+ focusAtCoords: (coords: { x: number; y: number }) => {
+ if (!editor) {
+ // Editor not mounted yet — degrade to the latched plain focus.
+ focusOnReadyRef.current = true;
+ return;
+ }
+ const pos = editor.view.posAtCoords({ left: coords.x, top: coords.y });
+ if (pos) editor.commands.focus(pos.pos);
+ else editor.commands.focus("end");
+ },
+ focusAtAnchor: (anchor: TextAnchor) => {
+ if (!editor) {
+ // Editor not mounted yet — degrade to the latched plain focus.
+ focusOnReadyRef.current = true;
+ return;
+ }
+ editor.commands.focus(posFromAnchor(editor.state.doc, anchor));
+ },
blur: () => {
editor?.commands.blur();
},
diff --git a/packages/views/editor/extensions/code-block-view.tsx b/packages/views/editor/extensions/code-block-view.tsx
index 3d59f95599..f64e479ab3 100644
--- a/packages/views/editor/extensions/code-block-view.tsx
+++ b/packages/views/editor/extensions/code-block-view.tsx
@@ -65,7 +65,7 @@ function CodeBlockView({ node }: NodeViewProps) {
setView((v) => (v === "preview" ? "source" : "preview"));
return (
- <NodeViewWrapper className="code-block-wrapper group/code relative my-2">
+ <NodeViewWrapper className="code-block-wrapper group/code relative my-3">
{isMermaid && debouncedChart.trim() && (
<div
contentEditable={false}
@@ -88,7 +88,7 @@ function CodeBlockView({ node }: NodeViewProps) {
)}
<div
contentEditable={false}
- className="code-block-header absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100"
+ className="code-block-header absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100 focus-within:opacity-100"
>
{language && (
<span className="text-xs text-muted-foreground select-none">
@@ -123,6 +123,7 @@ function CodeBlockView({ node }: NodeViewProps) {
onClick={handleCopy}
className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
title={t(($) => $.code_block.copy_code)}
+ aria-label={t(($) => $.code_block.copy_code)}
>
{copied ? (
<Check className="h-3.5 w-3.5" />
diff --git a/packages/views/editor/extensions/code.test.ts b/packages/views/editor/extensions/code.test.ts
index a5eb56988e..2635fc20f7 100644
--- a/packages/views/editor/extensions/code.test.ts
+++ b/packages/views/editor/extensions/code.test.ts
@@ -103,3 +103,22 @@ describe("inline code paste rule", () => {
expect(editor.getMarkdown().trim()).toBe("abcd`123`");
});
});
+
+describe("fenced code language", () => {
+ it("keeps a newly-created unlabelled code block unlabelled in Markdown", () => {
+ editor = makeProductionEditor();
+ editor.commands.setContent({
+ type: "doc",
+ content: [
+ {
+ type: "codeBlock",
+ content: [{ type: "text", text: "const answer = 42;" }],
+ },
+ ],
+ });
+
+ expect(editor.getMarkdown().trim()).toBe(
+ ["```", "const answer = 42;", "```"].join("\n"),
+ );
+ });
+});
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 912e6bd93f..1fa8d9b63f 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -22,7 +22,6 @@
import type { RefObject } from "react";
import StarterKit from "@tiptap/starter-kit";
import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
-import { common, createLowlight } from "lowlight";
import Placeholder from "@tiptap/extension-placeholder";
import Link from "@tiptap/extension-link";
import Typography from "@tiptap/extension-typography";
@@ -57,8 +56,7 @@ import { ImageView } from "./image-view";
import { BlockMathExtension, InlineMathExtension } from "./math";
import { HighlightExtension } from "./highlight";
import { AutolinkEmailRepairExtension } from "./autolink-email-repair";
-
-const lowlight = createLowlight(common);
+import { codeLowlight } from "../syntax-highlight";
const LinkExtension = Link.extend({ inclusive: false }).configure({
openOnClick: false,
@@ -192,7 +190,7 @@ export function createEditorExtensions(
addNodeView() {
return ReactNodeViewRenderer(CodeBlockView);
},
- }).configure({ lowlight }),
+ }).configure({ lowlight: codeLowlight }),
// ⚠️ Link MUST appear before markdownPaste in this array.
// linkOnPaste relies on Link's handlePaste plugin firing first;
// markdownPaste's handlePaste is a catch-all that returns true.
diff --git a/packages/views/editor/html-block-preview.tsx b/packages/views/editor/html-block-preview.tsx
index f46adfc4c9..ccf4be50f3 100644
--- a/packages/views/editor/html-block-preview.tsx
+++ b/packages/views/editor/html-block-preview.tsx
@@ -63,9 +63,9 @@ export function HtmlBlockPreview({ html, className }: HtmlBlockPreviewProps) {
setView((v) => (v === "preview" ? "source" : "preview"));
return (
- <div className={cn("code-block-wrapper group/code relative my-2", className)}>
+ <div className={cn("code-block-wrapper group/code relative my-3", className)}>
<div
- className="absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100"
+ className="absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100 focus-within:opacity-100"
>
<span className="text-xs text-muted-foreground select-none">{HTML_LANGUAGE_LABEL}</span>
<button
diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.ts
index 68f6ae587d..263f0992f2 100644
--- a/packages/views/editor/index.ts
+++ b/packages/views/editor/index.ts
@@ -11,6 +11,8 @@ export {
export { ReadonlyContent } from "./readonly-content";
export { useFileDropZone } from "./use-file-drop-zone";
export { FileDropOverlay } from "./file-drop-overlay";
+export { useLazyEditor, type LazyEditorHandle, type LazyFocusTarget } from "./use-lazy-editor";
+export { anchorFromPoint, type TextAnchor } from "./text-anchor";
export { useDownloadAttachment } from "./use-download-attachment";
export { AttachmentDownloadProvider } from "./attachment-download-context";
export {
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index 6c0932825e..a6fb492308 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -310,13 +310,14 @@ describe("ReadonlyContent code styling", () => {
expect(blockCode?.textContent).toBe(literalCode);
});
- it("renders code blocks without a language tag (lowlight highlightAuto fallback)", () => {
- const token = "mul_407ec1e4464b580304362ed749f821901fd7d310";
+ it("renders code blocks without a language tag as plaintext", () => {
+ const token = "const answer = 42;";
const { container } = render(
<ReadonlyContent content={["```", token, "```"].join("\n")} />,
);
const blockCode = container.querySelector("pre code");
expect(blockCode?.textContent?.trim()).toBe(token);
+ expect(blockCode?.querySelector("span")).toBeNull();
});
it("copies the whole fenced code block from the readonly toolbar", async () => {
diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsx
index c31f4d953e..703dcb5842 100644
--- a/packages/views/editor/readonly-content.tsx
+++ b/packages/views/editor/readonly-content.tsx
@@ -28,7 +28,6 @@ import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import rehypeRaw from "rehype-raw";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
-import { createLowlight, common } from "lowlight";
import { toHtml } from "hast-util-to-html";
import { Check, Copy } from "lucide-react";
import { cn } from "@multica/ui/lib/utils";
@@ -49,15 +48,10 @@ import { MermaidDiagram } from "./mermaid-diagram";
import { HtmlBlockPreview } from "./html-block-preview";
import { AttachmentDownloadProvider } from "./attachment-download-context";
import { Attachment as AttachmentRenderer } from "./attachment";
+import { highlightCode } from "./syntax-highlight";
import "katex/dist/katex.min.css";
import "./styles/index.css";
-// ---------------------------------------------------------------------------
-// Lowlight — same engine + language set as Tiptap's CodeBlockLowlight
-// ---------------------------------------------------------------------------
-
-const lowlight = createLowlight(common);
-
// Code fences that the `code` renderer returns as a non-<code> React element
// (Mermaid diagram, HTML preview iframe). The `pre` renderer below unwraps
// these so the default <pre><code> envelope doesn't clamp their styles.
@@ -192,7 +186,13 @@ function getTextContent(node: ReactNode): string {
return "";
}
-function ReadonlyCodeBlock({ children }: { children: ReactNode }) {
+function ReadonlyCodeBlock({
+ children,
+ language,
+}: {
+ children: ReactNode;
+ language?: string;
+}) {
const { t } = useT("editor");
const [copied, setCopied] = useState(false);
const code = useMemo(
@@ -212,6 +212,13 @@ function ReadonlyCodeBlock({ children }: { children: ReactNode }) {
return (
<div className="code-block-wrapper group/code relative my-3">
<div className="absolute top-0 right-0 z-10 flex items-center gap-1.5 px-2 py-1.5 opacity-0 transition-opacity group-hover/code:opacity-100 focus-within:opacity-100">
+ {/* Same hover chrome as the editable code block's header
+ (code-block-view.tsx): language label + copy. */}
+ {language && (
+ <span className="text-xs text-muted-foreground select-none">
+ {language}
+ </span>
+ )}
<button
type="button"
onClick={handleCopy}
@@ -226,7 +233,10 @@ function ReadonlyCodeBlock({ children }: { children: ReactNode }) {
)}
</button>
</div>
- <pre className="!m-0 pr-12">{children}</pre>
+ {/* No extra right padding: `.rich-text-editor pre` outranks utility
+ padding classes anyway, and the editable NodeView uses the same
+ 1rem — keeping them identical keeps line wrapping identical. */}
+ <pre className="!m-0">{children}</pre>
</div>
);
}
@@ -362,9 +372,7 @@ function buildComponents(): Partial<Components> {
// Block code — highlight with lowlight, output hljs classes
const code = String(children).replace(/\n$/, "");
try {
- const tree = lang
- ? lowlight.highlight(lang, code)
- : lowlight.highlightAuto(code);
+ const tree = highlightCode(code, lang);
const html = toHtml(tree);
if (html) {
return (
@@ -399,13 +407,15 @@ function buildComponents(): Partial<Components> {
// Match by exact class token: a substring `includes("language-html")`
// would also fire on neighboring languages like `language-htmlbars`
// and silently strip their <pre> wrapper.
+ let language: string | undefined;
if (isValidElement(children)) {
const childProps = children.props as { className?: string };
if (PRE_UNWRAP_RE.test(childProps.className ?? "")) {
return <>{children}</>;
}
+ language = /language-(\w+)/.exec(childProps.className ?? "")?.[1];
}
- return <ReadonlyCodeBlock>{children}</ReadonlyCodeBlock>;
+ return <ReadonlyCodeBlock language={language}>{children}</ReadonlyCodeBlock>;
},
};
}
diff --git a/packages/views/editor/styles/code.css b/packages/views/editor/styles/code.css
index 62fb266b45..57b936d14a 100644
--- a/packages/views/editor/styles/code.css
+++ b/packages/views/editor/styles/code.css
@@ -32,6 +32,11 @@ pre.rich-text-editor {
border-radius: var(--radius);
padding: 0.75rem 1rem;
margin: 0.75rem 0;
+ /* Long lines wrap, matching the editable code block (its NodeViewContent
+ sets an inline pre-wrap). Without this, readonly blocks scroll while
+ editable blocks wrap and the same document changes shape between the
+ two renderers. overflow-x stays as a fallback for unbreakable tokens. */
+ white-space: pre-wrap;
overflow-x: auto;
}
diff --git a/packages/views/editor/styles/prose.css b/packages/views/editor/styles/prose.css
index ba9e96a716..60bd0bcf81 100644
--- a/packages/views/editor/styles/prose.css
+++ b/packages/views/editor/styles/prose.css
@@ -26,6 +26,16 @@
* box-decoration-break: clone on inline code.
*/
+/* Long unbreakable tokens (paths, URLs, identifiers) wrap mid-word instead
+ of overflowing. Tiptap injects the legacy alias `word-wrap: break-word`
+ on .ProseMirror, so the editable render already behaves this way; without
+ this rule the readonly render keeps such tokens on one line and the two
+ renders wrap the same text differently (machine-diffed: inline code and
+ code blocks gained 1-2 lines in the editor only). */
+.rich-text-editor {
+ overflow-wrap: break-word;
+}
+
/* Headings — compact but with clear visual hierarchy */
.rich-text-editor h1 {
font-size: 1.375rem;
@@ -261,6 +271,11 @@
}
.rich-text-editor table {
+ /* `width`, not just `min-width`: Tiptap stamps an inline
+ `style="min-width: NNpx"` on its tables, which would override a
+ class-level min-width and let editor tables shrink to content while
+ readonly tables stretch full width. */
+ width: 100%;
min-width: 100%;
border-collapse: collapse;
}
@@ -269,7 +284,11 @@
display: none;
}
-.rich-text-editor thead {
+/* Header-row background. Two structures produce header rows: readonly
+ (react-markdown) emits a real <thead>; Tiptap keeps the <th> row inside
+ <tbody>, so the tr:has(> th) arm covers the editable table. */
+.rich-text-editor thead,
+.rich-text-editor tr:has(> th) {
background: color-mix(in srgb, var(--muted) 50%, transparent);
}
@@ -277,6 +296,12 @@
border-top: 1px solid var(--border);
}
+/* Tiptap tables have no <thead>, so their header row is tbody's first row —
+ without this it draws a border-top right against the wrapper's own border. */
+.rich-text-editor table > tbody:first-child > tr:first-child {
+ border-top: 0;
+}
+
.rich-text-editor tr:hover td {
background: color-mix(in srgb, var(--muted) 30%, transparent);
transition: background 0.15s;
@@ -287,6 +312,11 @@
text-align: left;
padding: 0.625rem 1rem;
font-size: 0.875rem;
+ /* Match body-paragraph line-height. Tiptap wraps cell content in <p>
+ (which carries 1.625); the readonly render keeps bare text in the cell,
+ which otherwise inherits the host's text-sm line-height (~1.43) and
+ makes every readonly cell 2.5px shorter per line. */
+ line-height: 1.625;
}
.rich-text-editor th {
diff --git a/packages/views/editor/syntax-highlight.test.ts b/packages/views/editor/syntax-highlight.test.ts
new file mode 100644
index 0000000000..8428969c8a
--- /dev/null
+++ b/packages/views/editor/syntax-highlight.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { codeLowlight, highlightCode } from "./syntax-highlight";
+
+describe("syntax highlighting", () => {
+ it("renders unlabelled code as plaintext instead of auto-detecting a language", () => {
+ const source = "const answer = 42;";
+
+ const tree = codeLowlight.highlightAuto(source);
+
+ expect(tree.data?.language).toBe("plaintext");
+ expect(tree.children).toEqual([{ type: "text", value: source }]);
+ });
+
+ it("keeps highlighting explicitly registered languages", () => {
+ const tree = highlightCode("const answer: number = 42;", "typescript");
+
+ expect(tree.data?.language).toBe("typescript");
+ expect(tree.children.some((child) => child.type === "element")).toBe(true);
+ });
+
+ it("renders unknown language labels as plaintext", () => {
+ const source = "some domain-specific syntax";
+
+ const tree = highlightCode(source, "not-a-registered-language");
+
+ expect(tree.data?.language).toBe("plaintext");
+ expect(tree.children).toEqual([{ type: "text", value: source }]);
+ });
+});
diff --git a/packages/views/editor/syntax-highlight.ts b/packages/views/editor/syntax-highlight.ts
new file mode 100644
index 0000000000..57434d1ad0
--- /dev/null
+++ b/packages/views/editor/syntax-highlight.ts
@@ -0,0 +1,25 @@
+import { common, createLowlight } from "lowlight";
+
+const baseLowlight = createLowlight(common);
+
+/**
+ * Tiptap calls `highlightAuto` whenever a code fence has no registered
+ * language. Auto-detection runs every registered grammar over the full block,
+ * which makes large documents expensive to mount. Preserve the interface but
+ * make that fallback deterministic and cheap: explicit known languages are
+ * still highlighted, while unlabelled or unknown blocks stay plaintext.
+ */
+export const codeLowlight: ReturnType<typeof createLowlight> = {
+ ...baseLowlight,
+ highlightAuto(value) {
+ return baseLowlight.highlight("plaintext", value);
+ },
+};
+
+export function highlightCode(value: string, language?: string) {
+ const normalizedLanguage = language?.trim().toLowerCase();
+
+ return normalizedLanguage && baseLowlight.registered(normalizedLanguage)
+ ? baseLowlight.highlight(normalizedLanguage, value)
+ : baseLowlight.highlight("plaintext", value);
+}
diff --git a/packages/views/editor/text-anchor.test.ts b/packages/views/editor/text-anchor.test.ts
new file mode 100644
index 0000000000..085551df20
--- /dev/null
+++ b/packages/views/editor/text-anchor.test.ts
@@ -0,0 +1,159 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it } from "vitest";
+import { Schema } from "@tiptap/pm/model";
+import { anchorFromPoint, posFromAnchor } from "./text-anchor";
+
+// Minimal schema — enough shape to exercise block walking, inline atoms
+// (mention-like zero-text nodes), leaf text blocks (code), and nested lists.
+const schema = new Schema({
+ nodes: {
+ doc: { content: "block+" },
+ paragraph: { group: "block", content: "inline*" },
+ codeBlock: { group: "block", content: "text*", marks: "" },
+ bulletList: { group: "block", content: "listItem+" },
+ listItem: { content: "paragraph+" },
+ mention: { group: "inline", inline: true, atom: true },
+ text: { group: "inline" },
+ },
+});
+
+const text = (s: string) => schema.text(s);
+const p = (...content: ReturnType<typeof text>[]) =>
+ schema.node("paragraph", null, content);
+
+describe("posFromAnchor", () => {
+ it("lands before the next word or after the previous one, per bias", () => {
+ const doc = schema.node("doc", null, [p(text("hello world"))]);
+ // 5 non-whitespace chars before the caret; the space is ambiguous.
+ expect(posFromAnchor(doc, { block: 0, offset: 5, bias: 1 })).toBe(7); // ▮world
+ expect(posFromAnchor(doc, { block: 0, offset: 5, bias: -1 })).toBe(6); // hello▮
+ });
+
+ it("maps offsets in later blocks past preceding node sizes", () => {
+ const doc = schema.node("doc", null, [p(text("abc")), p(text("defgh"))]);
+ // Mid-word there is no whitespace ambiguity: both biases agree.
+ expect(posFromAnchor(doc, { block: 1, offset: 2, bias: 1 })).toBe(8);
+ expect(posFromAnchor(doc, { block: 1, offset: 2, bias: -1 })).toBe(8);
+ });
+
+ it("skips zero-text inline atoms without counting them", () => {
+ const doc = schema.node("doc", null, [
+ p(text("hi "), schema.node("mention"), text(" yo")),
+ ]);
+ // Doc non-whitespace chars: h i y o. Offset 3 = caret before the "o".
+ expect(posFromAnchor(doc, { block: 0, offset: 3, bias: 1 })).toBe(7);
+ // Offset 4 = past the last one — lands right after it.
+ expect(posFromAnchor(doc, { block: 0, offset: 4, bias: 1 })).toBe(8);
+ });
+
+ it("clamps an overshooting offset to the block's content end", () => {
+ const doc = schema.node("doc", null, [p(text("abc")), p(text("xyz"))]);
+ expect(posFromAnchor(doc, { block: 0, offset: 99, bias: 1 })).toBe(4);
+ });
+
+ it("clamps an out-of-range block index to the document end", () => {
+ const doc = schema.node("doc", null, [p(text("abc"))]);
+ expect(posFromAnchor(doc, { block: 7, offset: 0, bias: 1 })).toBe(
+ doc.content.size,
+ );
+ });
+
+ it("distinguishes line end from next line start in code blocks", () => {
+ const doc = schema.node("doc", null, [
+ p(text("intro")),
+ schema.node("codeBlock", null, [text("line1\nline2")]),
+ ]);
+ // 5 non-whitespace chars ("line1") precede both carets; the \n between
+ // them is whitespace, so only the bias separates the two intents.
+ expect(posFromAnchor(doc, { block: 1, offset: 5, bias: -1 })).toBe(13); // line1▮
+ expect(posFromAnchor(doc, { block: 1, offset: 5, bias: 1 })).toBe(14); // ▮line2
+ });
+});
+
+describe("anchorFromPoint", () => {
+ // `as unknown` sidesteps lib.dom's full CaretPosition shape — the code
+ // under test only reads offsetNode/offset.
+ const docAny = document as unknown as {
+ caretPositionFromPoint?: (x: number, y: number) => {
+ offsetNode: Node;
+ offset: number;
+ } | null;
+ };
+ const originalCaret = docAny.caretPositionFromPoint;
+
+ afterEach(() => {
+ docAny.caretPositionFromPoint = originalCaret;
+ document.body.innerHTML = "";
+ });
+
+ function mount(html: string): HTMLElement {
+ const root = document.createElement("div");
+ root.innerHTML = html;
+ document.body.appendChild(root);
+ return root;
+ }
+
+ it("counts non-whitespace chars before the caret and biases toward text", () => {
+ const root = mount("<p>abc</p><p><strong>de</strong>fgh</p>");
+ const second = root.children[1] as HTMLElement;
+ // Caret one char into "fgh" — mid-word, next char is 'g'.
+ docAny.caretPositionFromPoint = () => ({
+ offsetNode: second.childNodes[1] as Node,
+ offset: 1,
+ });
+ expect(anchorFromPoint(0, 0, root)).toEqual({ block: 1, offset: 3, bias: 1 });
+ });
+
+ it("biases backward when the caret sits at the end of the text", () => {
+ const root = mount("<p>abc</p>");
+ const para = root.children[0] as HTMLElement;
+ docAny.caretPositionFromPoint = () => ({
+ offsetNode: para.firstChild as Node,
+ offset: 3,
+ });
+ expect(anchorFromPoint(0, 0, root)).toEqual({ block: 0, offset: 3, bias: -1 });
+ });
+
+ it("ignores inter-element whitespace artifacts (the list drift bug)", () => {
+ // react-markdown keeps the source newline between <li> elements as a
+ // text node; ProseMirror's doc has no such separator. Non-whitespace
+ // counting must make both sides agree.
+ const root = mount("<ul><li>URL: x</li>\n<li>Title: feat</li></ul>");
+ const li2 = root.querySelector("li:nth-child(2)") as HTMLElement;
+ docAny.caretPositionFromPoint = () => ({
+ offsetNode: li2.firstChild as Node,
+ offset: 7, // "Title: ▮feat"
+ });
+ const anchor = anchorFromPoint(0, 0, root);
+ // "URL:x" (5) + "Title:" (6) — the artifact \n and real spaces excluded.
+ expect(anchor).toEqual({ block: 0, offset: 11, bias: 1 });
+
+ // The same anchor resolves to right before "feat" in the PM doc.
+ const doc = schema.node("doc", null, [
+ schema.node("bulletList", null, [
+ schema.node("listItem", null, [p(text("URL: x"))]),
+ schema.node("listItem", null, [p(text("Title: feat"))]),
+ ]),
+ ]);
+ const pos = posFromAnchor(doc, anchor!);
+ expect(doc.textBetween(pos, pos + 4)).toBe("feat");
+ });
+
+ it("returns null when the caret lands outside the root", () => {
+ const root = mount("<p>abc</p>");
+ const stranger = document.createElement("p");
+ stranger.textContent = "elsewhere";
+ document.body.appendChild(stranger);
+ docAny.caretPositionFromPoint = () => ({
+ offsetNode: stranger.firstChild as Node,
+ offset: 0,
+ });
+ expect(anchorFromPoint(0, 0, root)).toBeNull();
+ });
+
+ it("returns null when no caret API is available", () => {
+ const root = mount("<p>abc</p>");
+ docAny.caretPositionFromPoint = undefined;
+ expect(anchorFromPoint(0, 0, root)).toBeNull();
+ });
+});
diff --git a/packages/views/editor/text-anchor.ts b/packages/views/editor/text-anchor.ts
new file mode 100644
index 0000000000..fcf0dd1825
--- /dev/null
+++ b/packages/views/editor/text-anchor.ts
@@ -0,0 +1,158 @@
+/**
+ * Text-anchor caret mapping between the readonly stand-in and the editor.
+ *
+ * The lazy-editor swap used to land the caret with raw pixel coordinates
+ * (`posAtCoords`), which assumes the readonly render and the Tiptap render
+ * are pixel-identical. They never are on long documents: per-block height
+ * differences (tables, code headers, mention cards) accumulate top-to-bottom,
+ * and NodeViews/images keep reflowing after `onReady` — so clicks landed
+ * lines away from the target. A text anchor sidesteps layout entirely:
+ * record WHICH character of WHICH top-level block was clicked, then resolve
+ * that logical position in the ProseMirror document.
+ *
+ * Offsets count NON-WHITESPACE characters only. The two renderers disagree
+ * about whitespace inside container blocks — react-markdown keeps the HTML
+ * source's inter-element newlines as text nodes ("URL: x\nTitle: y"), while
+ * ProseMirror's textContent concatenates with no separator ("URL: xTitle: y")
+ * — so raw character offsets drift one per list item / nested block. The
+ * non-whitespace character sequence, however, is identical on both sides.
+ * The whitespace ambiguity this creates at word boundaries ("end of this
+ * word" vs "start of the next") is resolved by `bias`, captured from what
+ * the user actually clicked next to.
+ *
+ * Known drift: content the two renderers textify differently (a mention's
+ * display name is text in the readonly render but an atom — zero text — in
+ * the doc) shifts offsets within that one block; resolution clamps to the
+ * block end, so worst case the caret lands earlier in the same block, never
+ * in another block.
+ */
+
+import type { Node as PMNode } from "@tiptap/pm/model";
+
+export interface TextAnchor {
+ /** Index of the top-level block (readonly root child ↔ doc child). */
+ block: number;
+ /** Count of non-whitespace characters before the caret within the block. */
+ offset: number;
+ /**
+ * Which neighbor the caret attaches to when whitespace separates the
+ * offset-th non-whitespace character from the next one: 1 = just before
+ * the next non-whitespace character (user clicked a line/word start),
+ * -1 = just after the previous one (user clicked a line/word end).
+ */
+ bias: 1 | -1;
+}
+
+const NON_WS = /\S/;
+
+function countNonWs(s: string): number {
+ let n = 0;
+ for (let i = 0; i < s.length; i++) if (NON_WS.test(s.charAt(i))) n++;
+ return n;
+}
+
+/**
+ * Resolve a click point inside the readonly render to a text anchor.
+ * `root` is the markdown container whose element children correspond 1:1 to
+ * the document's top-level blocks. Returns null when the point yields no
+ * caret position (unsupported API, click on empty margin below content) —
+ * callers fall back to coordinate focus.
+ */
+export function anchorFromPoint(
+ x: number,
+ y: number,
+ root: HTMLElement,
+): TextAnchor | null {
+ const doc = root.ownerDocument;
+ let node: Node | null = null;
+ let nodeOffset = 0;
+ // Standard API (Chromium/Firefox), then the WebKit legacy one.
+ if (typeof doc.caretPositionFromPoint === "function") {
+ const p = doc.caretPositionFromPoint(x, y);
+ if (p) {
+ node = p.offsetNode;
+ nodeOffset = p.offset;
+ }
+ } else if (typeof doc.caretRangeFromPoint === "function") {
+ const r = doc.caretRangeFromPoint(x, y);
+ if (r) {
+ node = r.startContainer;
+ nodeOffset = r.startOffset;
+ }
+ }
+ if (!node || !root.contains(node) || node === root) return null;
+
+ // Climb to the top-level block (the direct child of `root`).
+ let blockEl: Node = node;
+ while (blockEl.parentNode && blockEl.parentNode !== root) {
+ blockEl = blockEl.parentNode;
+ }
+ if (blockEl.parentNode !== root || blockEl.nodeType !== Node.ELEMENT_NODE) {
+ return null;
+ }
+ const block = Array.prototype.indexOf.call(root.children, blockEl);
+ if (block < 0) return null;
+
+ // Text before the caret within the block. Range.toString() handles both
+ // text-node carets and element carets (offset = child index), and yields
+ // a prefix of the block's textContent — which lets us peek at the char
+ // right after the caret for the bias.
+ const range = doc.createRange();
+ try {
+ range.setStart(blockEl, 0);
+ range.setEnd(node, nodeOffset);
+ } catch {
+ return { block, offset: 0, bias: 1 };
+ }
+ const before = range.toString();
+ const nextChar = (blockEl.textContent ?? "").charAt(before.length);
+ return {
+ block,
+ offset: countNonWs(before),
+ bias: NON_WS.test(nextChar) ? 1 : -1,
+ };
+}
+
+/**
+ * Resolve a text anchor to a ProseMirror position. Out-of-range values clamp
+ * (block → last block, offset → block end) so a stale or drifted anchor still
+ * lands inside the intended block instead of throwing.
+ */
+export function posFromAnchor(doc: PMNode, anchor: TextAnchor): number {
+ if (doc.childCount === 0) return 0;
+ if (anchor.block >= doc.childCount) return doc.content.size;
+ const blockIndex = Math.max(0, anchor.block);
+
+ let blockStart = 0;
+ for (let i = 0; i < blockIndex; i++) blockStart += doc.child(i).nodeSize;
+ const block = doc.child(blockIndex);
+ const contentStart = blockStart + 1;
+
+ const wanted = Math.max(0, anchor.offset);
+ let seen = 0;
+ // Caret position right after the `wanted`-th non-whitespace character
+ // (block content start while none have been passed yet).
+ let afterPrev = contentStart;
+ let resolved: number | null = null;
+ block.descendants((child, pos) => {
+ if (resolved !== null) return false;
+ if (!child.isText) return true;
+ const text = child.text ?? "";
+ for (let i = 0; i < text.length; i++) {
+ if (!NON_WS.test(text.charAt(i))) continue;
+ if (seen === wanted) {
+ // This is the first non-whitespace character AFTER the caret.
+ resolved = anchor.bias === 1 ? contentStart + pos + i : afterPrev;
+ return false;
+ }
+ seen++;
+ afterPrev = contentStart + pos + i + 1;
+ }
+ return true;
+ });
+ if (resolved !== null) return resolved;
+ // Caret past the last non-whitespace character: exact end lands after it;
+ // an overshoot (renderer textified something the doc doesn't, e.g. a
+ // mention label) clamps to the block's content end.
+ return seen === wanted ? afterPrev : blockStart + block.nodeSize - 1;
+}
diff --git a/packages/views/editor/title-editor.tsx b/packages/views/editor/title-editor.tsx
index 2ba4a7eb07..5f70c9616e 100644
--- a/packages/views/editor/title-editor.tsx
+++ b/packages/views/editor/title-editor.tsx
@@ -23,11 +23,24 @@ interface TitleEditorProps {
onSubmit?: () => void;
onBlur?: (value: string) => void;
onChange?: (value: string) => void;
+ /**
+ * Called once when the Tiptap instance exists and its DOM is attached
+ * (creation is deferred past first paint by `immediatelyRender: false`).
+ * Same contract as ContentEditorProps.onReady.
+ */
+ onReady?: () => void;
}
interface TitleEditorRef {
getText: () => string;
focus: () => void;
+ /**
+ * Focus and place the caret at the document position under the given
+ * viewport coordinates — same contract as ContentEditorRef.focusAtCoords,
+ * so readonly-first hosts (useLazyEditor) can treat both editors alike.
+ * Must be called while the editor element is laid out (not display: none).
+ */
+ focusAtCoords: (coords: { x: number; y: number }) => void;
}
// ---------------------------------------------------------------------------
@@ -78,6 +91,7 @@ const TitleEditor = forwardRef<TitleEditorRef, TitleEditorProps>(
onSubmit,
onBlur,
onChange,
+ onReady,
},
ref,
) {
@@ -85,10 +99,12 @@ const TitleEditor = forwardRef<TitleEditorRef, TitleEditorProps>(
const onSubmitRef = useRef(onSubmit);
const onBlurRef = useRef(onBlur);
const onChangeRef = useRef(onChange);
+ const onReadyRef = useRef(onReady);
onSubmitRef.current = onSubmit;
onBlurRef.current = onBlur;
onChangeRef.current = onChange;
+ onReadyRef.current = onReady;
const editor = useEditor({
immediatelyRender: false,
@@ -121,6 +137,16 @@ const TitleEditor = forwardRef<TitleEditorRef, TitleEditorProps>(
},
});
+ // Signal readonly-first hosts that the deferred editor now exists. Fired
+ // from a passive effect so it runs after the commit that attached the
+ // editor DOM — same pattern as ContentEditor.
+ const readyFiredRef = useRef(false);
+ useEffect(() => {
+ if (!editor || readyFiredRef.current) return;
+ readyFiredRef.current = true;
+ onReadyRef.current?.();
+ }, [editor]);
+
// Auto-focus after mount — delay to wait for Dialog open animation
useEffect(() => {
if (autoFocus && editor) {
@@ -175,6 +201,12 @@ const TitleEditor = forwardRef<TitleEditorRef, TitleEditorProps>(
focus: () => {
editor?.commands.focus("end");
},
+ focusAtCoords: (coords: { x: number; y: number }) => {
+ if (!editor) return;
+ const pos = editor.view.posAtCoords({ left: coords.x, top: coords.y });
+ if (pos) editor.commands.focus(pos.pos);
+ else editor.commands.focus("end");
+ },
}));
if (!editor) return null;
diff --git a/packages/views/editor/use-lazy-editor.test.ts b/packages/views/editor/use-lazy-editor.test.ts
new file mode 100644
index 0000000000..26638b144c
--- /dev/null
+++ b/packages/views/editor/use-lazy-editor.test.ts
@@ -0,0 +1,67 @@
+import { describe, it, expect, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import { useLazyEditor, type LazyEditorHandle } from "./use-lazy-editor";
+
+function makeHandle() {
+ return { focus: vi.fn(), focusAtCoords: vi.fn(), uploadFile: vi.fn() };
+}
+
+describe("useLazyEditor", () => {
+ it("starts static, activates on intent, focuses at the click coords once ready", () => {
+ const handle = makeHandle();
+ const editorRef = { current: handle as LazyEditorHandle };
+ const { result } = renderHook(() => useLazyEditor({ editorRef }));
+
+ expect(result.current.active).toBe(false);
+ expect(result.current.ready).toBe(false);
+
+ act(() => result.current.activate({ x: 10, y: 20 }));
+ expect(result.current.active).toBe(true);
+ expect(result.current.ready).toBe(false);
+
+ act(() => result.current.onReady());
+ expect(result.current.ready).toBe(true);
+ expect(handle.focusAtCoords).toHaveBeenCalledWith({ x: 10, y: 20 });
+ });
+
+ it("mounts immediately when initialActive is set (unsent draft)", () => {
+ const editorRef = { current: makeHandle() as LazyEditorHandle };
+ const { result } = renderHook(() => useLazyEditor({ editorRef, initialActive: true }));
+
+ expect(result.current.active).toBe(true);
+ });
+
+ it("queues uploads against the stand-in and flushes them on ready", () => {
+ const handle = makeHandle();
+ const editorRef = { current: handle as LazyEditorHandle };
+ const { result } = renderHook(() => useLazyEditor({ editorRef }));
+
+ const file = new File(["x"], "x.txt", { type: "text/plain" });
+ act(() => result.current.uploadOrQueue([file]));
+ // Queuing summons the editor but must not upload into a dead handle.
+ expect(result.current.active).toBe(true);
+ expect(handle.uploadFile).not.toHaveBeenCalled();
+
+ act(() => result.current.onReady());
+ expect(handle.uploadFile).toHaveBeenCalledWith(file);
+ });
+
+ it("resets to the stand-in during the render that changes resetKey", () => {
+ const editorRef = { current: makeHandle() as LazyEditorHandle };
+ const { result, rerender } = renderHook(
+ ({ key }: { key: string }) => useLazyEditor({ editorRef, resetKey: key }),
+ { initialProps: { key: "issue-1" } },
+ );
+
+ act(() => result.current.activate());
+ act(() => result.current.onReady());
+ expect(result.current.ready).toBe(true);
+
+ // Same-render reset: after the rerender that carries the new key, the
+ // hook must already report the stand-in state — an effect-based reset
+ // would let a keyed editor mount once for the new subject first.
+ rerender({ key: "issue-2" });
+ expect(result.current.active).toBe(false);
+ expect(result.current.ready).toBe(false);
+ });
+});
diff --git a/packages/views/editor/use-lazy-editor.ts b/packages/views/editor/use-lazy-editor.ts
new file mode 100644
index 0000000000..a310b26708
--- /dev/null
+++ b/packages/views/editor/use-lazy-editor.ts
@@ -0,0 +1,159 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
+import type { TextAnchor } from "./text-anchor";
+
+/**
+ * Minimal imperative surface useLazyEditor needs from the wrapped editor.
+ * ContentEditorRef and TitleEditorRef both satisfy it structurally.
+ */
+export interface LazyEditorHandle {
+ focus: () => void;
+ focusAtCoords?: (coords: { x: number; y: number }) => void;
+ focusAtAnchor?: (anchor: TextAnchor) => void;
+ uploadFile?: (file: File) => void;
+}
+
+/**
+ * Where the caret should land after the swap. `anchor` (logical "block N,
+ * character M", layout-independent) wins over the raw click coordinates;
+ * coordinates remain as the fallback for clicks that yield no text anchor
+ * (image, table chrome, margin) and for single-line hosts like the title.
+ */
+export interface LazyFocusTarget {
+ x: number;
+ y: number;
+ anchor?: TextAnchor;
+}
+
+export interface UseLazyEditorOptions {
+ /**
+ * Mount the real editor immediately instead of the static stand-in.
+ * The one legitimate case is an unsent draft: its existence proves edit
+ * intent, and hydrating it into a visible editor matches the pre-lazy
+ * behavior exactly.
+ */
+ initialActive?: boolean;
+ /** The host's own editor ref — used for post-swap focus and queued uploads. */
+ editorRef: RefObject<LazyEditorHandle | null>;
+ /**
+ * When this value changes, the hook returns to the static stand-in DURING
+ * that same render (setState-during-render, React's derived-state pattern)
+ * — not in an effect. An effect-based reset is one commit too late: the
+ * render that carries the new key would still see `active/ready === true`,
+ * visibly mount a keyed editor for the NEW subject, assemble a full Tiptap
+ * instance, and only then throw it away — re-paying the exact main-thread
+ * cost this hook exists to avoid, and blanking the region for a beat.
+ * Hosts that remount per subject (via `key`) don't need this.
+ */
+ resetKey?: unknown;
+}
+
+/**
+ * Shared controller for readonly-first editors (issue title / comment /
+ * reply). Tiptap instantiation costs ~70-460ms per editor on the
+ * main thread, so every always-mounted editor makes opening an issue jankier
+ * (measured: 2-4 editors per open froze the click for 0.4-1.3s). The pattern:
+ *
+ * 1. Render a cheap static stand-in while `!active`.
+ * 2. A click (or queued upload, or Enter on the stand-in) calls `activate`,
+ * which mounts the real editor HIDDEN — the stand-in stays visible so
+ * the content never blanks while Tiptap assembles.
+ * 3. The editor's `onReady` flips `ready`; the host swaps visibility in
+ * that commit, and the effect below (running after that commit, so the
+ * editor is laid out) lands the caret at the activating click's focus
+ * target — text anchor first, raw coordinates as fallback — and
+ * flushes any uploads queued against the stand-in.
+ *
+ * Host render contract:
+ * {lazy.active && <div className={lazy.ready ? undefined : "hidden"}>
+ * <Editor ref={editorRef} onReady={lazy.onReady} ... /></div>}
+ * {!lazy.ready && <StaticStandIn onClick={e => lazy.activate({x: e.clientX, y: e.clientY})} />}
+ *
+ * Hosts that outlive a subject switch without remounting (the web issue
+ * route) must pass `resetKey`; keyed hosts get the reset for free by
+ * remounting.
+ */
+export function useLazyEditor({
+ initialActive = false,
+ editorRef,
+ resetKey,
+}: UseLazyEditorOptions) {
+ const [active, setActive] = useState(initialActive);
+ const [ready, setReady] = useState(false);
+ const focusTargetRef = useRef<LazyFocusTarget | null>(null);
+ const focusPendingRef = useRef(false);
+ const pendingFilesRef = useRef<File[]>([]);
+
+ // Render-phase reset on subject change — see the `resetKey` option doc.
+ const [prevResetKey, setPrevResetKey] = useState(resetKey);
+ if (resetKey !== prevResetKey) {
+ setPrevResetKey(resetKey);
+ setActive(initialActive);
+ setReady(false);
+ focusTargetRef.current = null;
+ focusPendingRef.current = false;
+ pendingFilesRef.current = [];
+ }
+
+ const focusAtTarget = useCallback(
+ (target: LazyFocusTarget | null) => {
+ const handle = editorRef.current;
+ if (!handle) return;
+ if (target?.anchor && handle.focusAtAnchor) handle.focusAtAnchor(target.anchor);
+ else if (target && handle.focusAtCoords) handle.focusAtCoords(target);
+ else handle.focus();
+ },
+ [editorRef],
+ );
+
+ const activate = useCallback(
+ (target?: LazyFocusTarget) => {
+ focusTargetRef.current = target ?? null;
+ focusPendingRef.current = true;
+ setActive(true);
+ // Already swapped in (e.g. keyboard re-activation after a blur):
+ // focus straight away, there is no ready-effect coming.
+ if (ready) {
+ focusPendingRef.current = false;
+ const latched = focusTargetRef.current;
+ focusTargetRef.current = null;
+ focusAtTarget(latched);
+ }
+ },
+ [ready, focusAtTarget],
+ );
+
+ const onReady = useCallback(() => setReady(true), []);
+
+ // Post-swap work — runs after the commit that revealed the ready editor,
+ // so focus targets can resolve against a laid-out, live doc and uploads
+ // insert into it.
+ useEffect(() => {
+ if (!ready) return;
+ if (focusPendingRef.current) {
+ focusPendingRef.current = false;
+ const target = focusTargetRef.current;
+ focusTargetRef.current = null;
+ focusAtTarget(target);
+ }
+ const pending = pendingFilesRef.current;
+ pendingFilesRef.current = [];
+ for (const file of pending) editorRef.current?.uploadFile?.(file);
+ }, [ready, editorRef, focusAtTarget]);
+
+ /** Upload now when the editor is live; otherwise queue and summon it. */
+ const uploadOrQueue = useCallback(
+ (files: File[]) => {
+ if (ready) {
+ for (const file of files) editorRef.current?.uploadFile?.(file);
+ return;
+ }
+ pendingFilesRef.current.push(...files);
+ setActive(true);
+ },
+ [ready, editorRef],
+ );
+
+ return { active, ready, activate, onReady, uploadOrQueue };
+}
diff --git a/packages/views/editor/utils/parse-markdown-chunked.test.ts b/packages/views/editor/utils/parse-markdown-chunked.test.ts
new file mode 100644
index 0000000000..ebdb898be1
--- /dev/null
+++ b/packages/views/editor/utils/parse-markdown-chunked.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ MARKDOWN_CHUNK_THRESHOLD,
+ parseMarkdownChunked,
+} from "./parse-markdown-chunked";
+
+describe("parseMarkdownChunked", () => {
+ it("routes a typical 22k issue through the chunked parse path", () => {
+ expect(MARKDOWN_CHUNK_THRESHOLD).toBeLessThan(22_000);
+ });
+
+ it("keeps ordinary paragraph chunks small enough to avoid quadratic scans", () => {
+ const markdown = Array.from(
+ { length: 240 },
+ (_, index) => `${index}: ${"x".repeat(92)}`,
+ ).join("\n\n");
+ const parsedLengths: number[] = [];
+ const manager = {
+ parse: vi.fn((chunk: string) => {
+ parsedLengths.push(chunk.length);
+ return {
+ type: "doc",
+ content: [{ type: "paragraph", attrs: { sourceLength: chunk.length } }],
+ };
+ }),
+ };
+
+ const result = parseMarkdownChunked(manager, markdown);
+
+ expect(markdown.length).toBeGreaterThan(22_000);
+ expect(manager.parse).toHaveBeenCalled();
+ expect(parsedLengths.length).toBeGreaterThan(1);
+ expect(Math.max(...parsedLengths)).toBeLessThan(6_000);
+ expect(result.content).toHaveLength(parsedLengths.length);
+ });
+});
diff --git a/packages/views/editor/utils/parse-markdown-chunked.ts b/packages/views/editor/utils/parse-markdown-chunked.ts
index 656edea3de..8be8b09efd 100644
--- a/packages/views/editor/utils/parse-markdown-chunked.ts
+++ b/packages/views/editor/utils/parse-markdown-chunked.ts
@@ -5,9 +5,15 @@ import type { JSONContent } from "@tiptap/core";
* one shot. `@tiptap/markdown` parses via `marked`, whose tokenizer is O(n²) in
* document length (measured: 533KB plain text → 61.8s parse, while the following
* ProseMirror setContent is only 40ms). Whole-document parse is the bottleneck;
- * below this threshold the single-parse path is fast enough and stays in use.
+ * Traces from a typical structured 22KB issue showed hundreds of milliseconds
+ * in one parse, so keep the single-parse path only for genuinely small docs.
*/
-export const MARKDOWN_CHUNK_THRESHOLD = 50_000;
+export const MARKDOWN_CHUNK_THRESHOLD = 8_000;
+
+// A smaller parse window matters because the tokenizer cost grows roughly with
+// the square of each chunk's length. 4KB keeps common issue descriptions cheap
+// while still avoiding hundreds of tiny ProseMirror documents.
+export const MARKDOWN_CHUNK_SIZE = 4_000;
export interface MarkdownManagerLike {
parse(markdown: string): JSONContent;
@@ -29,7 +35,7 @@ export interface MarkdownManagerLike {
export function parseMarkdownChunked(
manager: MarkdownManagerLike,
markdown: string,
- chunkSize = 16_000,
+ chunkSize = MARKDOWN_CHUNK_SIZE,
): JSONContent {
const lines = markdown.split("\n");
const chunks: string[] = [];
diff --git a/packages/views/inbox/components/inbox-list.tsx b/packages/views/inbox/components/inbox-list.tsx
new file mode 100644
index 0000000000..14b672e5d8
--- /dev/null
+++ b/packages/views/inbox/components/inbox-list.tsx
@@ -0,0 +1,96 @@
+"use client";
+
+import { useState } from "react";
+import { Virtuoso } from "react-virtuoso";
+import { Inbox } from "lucide-react";
+import type { InboxItem } from "@multica/core/types";
+import { InboxListItem } from "./inbox-list-item";
+import { VirtuosoSeed, VIRTUOSO_SEED_COUNT } from "../../common/virtuoso-seed";
+import { useT } from "../../i18n";
+
+/**
+ * Scrollable, virtualized inbox notification list.
+ *
+ * Owns the scroll container so both the mobile and desktop layouts render an
+ * identical scroller. Rows are virtualized via react-virtuoso so only the
+ * visible window (plus a small overscan) is mounted — the notification list
+ * can grow long and every row otherwise carries an avatar + hover card, so
+ * mounting all of them inflates the tab-switch commit (MUL-4474).
+ *
+ * Virtualization changes exactly one thing: whether an off-screen row is in
+ * the DOM. Selection, hover, archive, and scroll semantics are unchanged —
+ * the row component and the callbacks are the same as the non-virtualized
+ * list. `customScrollParent` keeps Virtuoso reading/writing the existing
+ * `overflow-y-auto` element (same pattern as the issue-detail timeline), so
+ * scroll position behaves exactly as before.
+ *
+ * Known virtualization tradeoff: keyboard Tab only reaches currently-mounted
+ * rows; a keyboard-only user must scroll to bring off-screen rows into the
+ * tab order. The inbox has no custom arrow-key list navigation, so the
+ * practical surface is small, but it is called out for the manual pass.
+ */
+export function InboxList({
+ items,
+ selectedKey,
+ onSelect,
+ onArchive,
+}: {
+ items: InboxItem[];
+ selectedKey: string;
+ onSelect: (item: InboxItem) => void;
+ onArchive: (id: string) => void;
+}) {
+ const { t } = useT("inbox");
+ // Virtuoso's `customScrollParent` wants the actual HTMLElement, not a ref.
+ // A callback ref into state hands the element over once it mounts and
+ // triggers the re-render that lets Virtuoso attach to it.
+ const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);
+
+ if (items.length === 0) {
+ return (
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
+ <Inbox className="mb-3 h-8 w-8 text-muted-foreground/50" />
+ <p className="text-sm">{t(($) => $.list.empty)}</p>
+ </div>
+ </div>
+ );
+ }
+
+ const computeItemKey = (_index: number, item: InboxItem) => item.id;
+ const itemContent = (_index: number, item: InboxItem) => (
+ <InboxListItem
+ item={item}
+ isSelected={(item.issue_id ?? item.id) === selectedKey}
+ onClick={() => onSelect(item)}
+ onArchive={() => onArchive(item.id)}
+ />
+ );
+
+ // While the callback ref hasn't handed the scroll element over yet (the first
+ // render after a remount), seed a bounded slice of real rows so the list
+ // never paints blank; once it's set, mount the Virtuoso with a matching
+ // `initialItemCount` so the measurement frame keeps those rows (MUL-4750).
+ return (
+ <div ref={setScrollEl} className="flex-1 min-h-0 overflow-y-auto">
+ <div className="px-2 py-1">
+ {scrollEl ? (
+ <Virtuoso
+ customScrollParent={scrollEl}
+ data={items}
+ computeItemKey={computeItemKey}
+ initialItemCount={Math.min(items.length, VIRTUOSO_SEED_COUNT)}
+ increaseViewportBy={{ top: 400, bottom: 400 }}
+ itemContent={itemContent}
+ />
+ ) : (
+ <VirtuosoSeed
+ data={items}
+ itemContent={itemContent}
+ computeItemKey={computeItemKey}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 92fe4e844f..749a1aede7 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -52,7 +52,8 @@ import {
} from "@multica/ui/components/ui/dropdown-menu";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
import { PageHeader } from "../../layout/page-header";
-import { InboxListItem, useTimeAgo } from "./inbox-list-item";
+import { useTimeAgo } from "./inbox-list-item";
+import { InboxList } from "./inbox-list";
import { useTypeLabels } from "./inbox-detail-label";
import { getInboxDisplayTitle } from "./inbox-display";
import { useT } from "../../i18n";
@@ -271,23 +272,13 @@ export function InboxPage() {
</PageHeader>
);
- const listBody = items.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
- <Inbox className="mb-3 h-8 w-8 text-muted-foreground/50" />
- <p className="text-sm">{t(($) => $.list.empty)}</p>
- </div>
- ) : (
- <div className="px-2 py-1">
- {items.map((item) => (
- <InboxListItem
- key={item.id}
- item={item}
- isSelected={(item.issue_id ?? item.id) === selectedKey}
- onClick={() => handleSelect(item)}
- onArchive={() => handleArchive(item.id)}
- />
- ))}
- </div>
+ const list = (
+ <InboxList
+ items={items}
+ selectedKey={selectedKey}
+ onSelect={handleSelect}
+ onArchive={handleArchive}
+ />
);
const detailContent = selected?.issue_id ? (
@@ -418,9 +409,7 @@ export function InboxPage() {
return (
<div className="flex flex-1 flex-col min-h-0">
{listHeader}
- <div className="flex-1 min-h-0 overflow-y-auto">
- {listBody}
- </div>
+ {list}
</div>
);
}
@@ -464,9 +453,7 @@ export function InboxPage() {
<ResizablePanel id="list" defaultSize={320} minSize={240} maxSize={480} groupResizeBehavior="preserve-pixel-size">
<div className="flex flex-col border-r h-full">
{listHeader}
- <div className="flex-1 min-h-0 overflow-y-auto">
- {listBody}
- </div>
+ {list}
</div>
</ResizablePanel>
<ResizableHandle />
diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
index 684386cf76..e2c9e6c4b7 100644
--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
@@ -106,7 +106,10 @@ vi.mock("../../../common/actor-avatar", () => ({
// Import after mocks.
import { IssueActionsDropdown } from "../issue-actions-dropdown";
-import { IssueActionsContextMenu } from "../issue-actions-context-menu";
+import {
+ IssueActionsContextMenu,
+ IssueContextMenuProvider,
+} from "../issue-actions-context-menu";
const mockIssue: Issue = {
id: "issue-1",
@@ -256,9 +259,11 @@ describe("IssueActionsContextMenu", () => {
it("renders the menu when the wrapped element receives a contextmenu event", async () => {
render(
wrap(
- <IssueActionsContextMenu issue={mockIssue}>
- <div data-testid="row">Row</div>
- </IssueActionsContextMenu>,
+ <IssueContextMenuProvider>
+ <IssueActionsContextMenu issue={mockIssue}>
+ <div data-testid="row">Row</div>
+ </IssueActionsContextMenu>
+ </IssueContextMenuProvider>,
),
);
diff --git a/packages/views/issues/actions/index.ts b/packages/views/issues/actions/index.ts
index 1b0bf991b9..0e1cfb5427 100644
--- a/packages/views/issues/actions/index.ts
+++ b/packages/views/issues/actions/index.ts
@@ -1,4 +1,7 @@
export { useIssueActions } from "./use-issue-actions";
export type { UseIssueActionsResult } from "./use-issue-actions";
export { IssueActionsDropdown } from "./issue-actions-dropdown";
-export { IssueActionsContextMenu } from "./issue-actions-context-menu";
+export {
+ IssueActionsContextMenu,
+ IssueContextMenuProvider,
+} from "./issue-actions-context-menu";
diff --git a/packages/views/issues/actions/issue-actions-context-menu.tsx b/packages/views/issues/actions/issue-actions-context-menu.tsx
index e053dfb2df..3f7861430d 100644
--- a/packages/views/issues/actions/issue-actions-context-menu.tsx
+++ b/packages/views/issues/actions/issue-actions-context-menu.tsx
@@ -1,10 +1,19 @@
"use client";
-import { useRef, useState, type ReactElement } from "react";
+import {
+ cloneElement,
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useRef,
+ useState,
+ type ReactElement,
+ type ReactNode,
+} from "react";
import type { Issue } from "@multica/core/types";
import {
ContextMenu,
- ContextMenuTrigger,
ContextMenuContent,
} from "@multica/ui/components/ui/context-menu";
import { useIssueActions } from "./use-issue-actions";
@@ -14,36 +23,111 @@ import {
} from "./issue-actions-menu-items";
import { AssigneePicker } from "../components/pickers";
-interface IssueActionsContextMenuProps {
+/**
+ * One shared context menu per surface instead of one Base UI ContextMenu
+ * root per card/row. A board remount used to create N × (MenuRoot + Trigger)
+ * — the single largest slice of the tab-switch freeze — even though at most
+ * one menu is ever open. Items delegate: the per-item wrapper only attaches
+ * an `onContextMenu` that reports (issue, cursor position) up to the
+ * provider's singleton, which anchors the menu at the cursor via a virtual
+ * anchor element.
+ *
+ * Known debt: Base UI's ContextMenuTrigger also opened on touch long-press;
+ * the delegated `contextmenu` event covers right-click (and Android
+ * long-press) but not iOS Safari long-press.
+ */
+
+interface ActiveMenu {
issue: Issue;
- /** A single React element cloned by Base UI as the trigger (via `render` prop). */
- children: ReactElement;
+ position: { x: number; y: number };
}
-export function IssueActionsContextMenu({
- issue,
+type OpenIssueContextMenu = (issue: Issue, event: React.MouseEvent) => void;
+
+const IssueContextMenuContext = createContext<OpenIssueContextMenu | null>(
+ null,
+);
+
+export function IssueContextMenuProvider({
children,
-}: IssueActionsContextMenuProps) {
+}: {
+ children: ReactNode;
+}) {
+ const [active, setActive] = useState<ActiveMenu | null>(null);
+ const [open, setOpen] = useState(false);
+ // The element the user right-clicked. Base UI's per-item trigger used to
+ // stamp `data-popup-open` on it (rows/cards style their "menu is open for
+ // me" state off that attribute). React never renders this attribute, so
+ // managing it imperatively here keeps the affordance without re-rendering
+ // every row on open/close.
+ const triggerElRef = useRef<HTMLElement | null>(null);
+
+ const openMenu = useCallback<OpenIssueContextMenu>((issue, event) => {
+ event.preventDefault();
+ triggerElRef.current?.removeAttribute("data-popup-open");
+ const el = event.currentTarget as HTMLElement;
+ el.setAttribute("data-popup-open", "");
+ triggerElRef.current = el;
+ setActive({ issue, position: { x: event.clientX, y: event.clientY } });
+ setOpen(true);
+ }, []);
+
+ const handleOpenChange = useCallback((v: boolean) => {
+ if (!v) {
+ triggerElRef.current?.removeAttribute("data-popup-open");
+ triggerElRef.current = null;
+ }
+ setOpen(v);
+ }, []);
+
+ return (
+ <IssueContextMenuContext.Provider value={openMenu}>
+ {children}
+ {/* Mounted on first use, kept mounted after (one closed menu root per
+ surface — the popup itself unmounts while closed). */}
+ {active && (
+ <IssueContextMenuSingleton
+ issue={active.issue}
+ position={active.position}
+ open={open}
+ onOpenChange={handleOpenChange}
+ />
+ )}
+ </IssueContextMenuContext.Provider>
+ );
+}
+
+function IssueContextMenuSingleton({
+ issue,
+ position,
+ open,
+ onOpenChange,
+}: ActiveMenu & {
+ open: boolean;
+ onOpenChange: (v: boolean) => void;
+}) {
const actions = useIssueActions(issue);
const [assigneeOpen, setAssigneeOpen] = useState(false);
- // Right-click coordinates captured during contextmenu so the AssigneePicker
- // opens where the context menu just was, instead of jumping to the row's
- // top-left corner. Reset between opens; only consulted while the picker is
- // mounted-open.
- const clickPosRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
- const handleContextMenu = (e: React.MouseEvent) => {
- clickPosRef.current = { x: e.clientX, y: e.clientY };
- };
+ // Point-sized virtual anchor at the right-click position — replaces the
+ // cursor anchor Base UI's own trigger would have registered.
+ const anchor = useMemo(
+ () => ({
+ getBoundingClientRect: () =>
+ DOMRect.fromRect({
+ x: position.x,
+ y: position.y,
+ width: 0,
+ height: 0,
+ }),
+ }),
+ [position.x, position.y],
+ );
return (
<>
- <ContextMenu>
- <ContextMenuTrigger
- render={children}
- onContextMenu={handleContextMenu}
- />
- <ContextMenuContent>
+ <ContextMenu open={open} onOpenChange={(v) => onOpenChange(v)}>
+ <ContextMenuContent anchor={anchor}>
<IssueActionsMenuItems
issue={issue}
actions={actions}
@@ -52,9 +136,9 @@ export function IssueActionsContextMenu({
/>
</ContextMenuContent>
</ContextMenu>
- {/* Mount the picker only once the user actually opens it. Otherwise
- every row in a list/board would subscribe to members/agents/squads
- /frequency queries on mount, multiplying memory + render cost. */}
+ {/* Mount the picker only once the user actually opens it, anchored at
+ the right-click position so it opens where the context menu just
+ was instead of jumping to the row's top-left corner. */}
{assigneeOpen && (
<AssigneePicker
assigneeType={issue.assignee_type}
@@ -67,8 +151,8 @@ export function IssueActionsContextMenu({
aria-hidden
className="pointer-events-none fixed"
style={{
- left: clickPosRef.current.x,
- top: clickPosRef.current.y,
+ left: position.x,
+ top: position.y,
width: 0,
height: 0,
}}
@@ -81,3 +165,41 @@ export function IssueActionsContextMenu({
</>
);
}
+
+interface IssueActionsContextMenuProps {
+ issue: Issue;
+ /** A single React element the menu trigger behavior is grafted onto. */
+ children: ReactElement<{
+ onContextMenu?: (e: React.MouseEvent) => void;
+ className?: string;
+ }>;
+}
+
+/**
+ * Per-item wrapper: clones its child with an `onContextMenu` that opens the
+ * surface-level singleton menu for this issue. Costs one context read — no
+ * menu machinery per item. Requires {@link IssueContextMenuProvider} above
+ * (IssueSurface mounts it).
+ */
+export function IssueActionsContextMenu({
+ issue,
+ children,
+}: IssueActionsContextMenuProps) {
+ const openMenu = useContext(IssueContextMenuContext);
+ if (!openMenu) {
+ throw new Error(
+ "IssueActionsContextMenu requires an IssueContextMenuProvider ancestor",
+ );
+ }
+ const childOnContextMenu = children.props.onContextMenu;
+ const childClassName = children.props.className;
+ return cloneElement(children, {
+ // Base UI's trigger merged `select-none` into the item; keep that so
+ // right-click targets don't become text-selectable.
+ className: childClassName ? `${childClassName} select-none` : "select-none",
+ onContextMenu: (e: React.MouseEvent) => {
+ childOnContextMenu?.(e);
+ openMenu(issue, e);
+ },
+ });
+}
diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsx
index 012b6b876f..b01799ad9a 100644
--- a/packages/views/issues/components/board-column.tsx
+++ b/packages/views/issues/components/board-column.tsx
@@ -1,8 +1,8 @@
"use client";
-import { memo, useMemo, type ReactNode } from "react";
+import { memo, useCallback, useMemo, useState, type ReactNode } from "react";
+import { Virtuoso } from "react-virtuoso";
import { EyeOff, MoreHorizontal, Plus, UserMinus } from "lucide-react";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
import { useDroppable } from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import type {
@@ -25,6 +25,10 @@ import { DraggableBoardCard } from "./board-card";
import type { ChildProgress } from "./list-row";
import { useT } from "../../i18n";
import { ActorAvatar } from "../../common/actor-avatar";
+import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";
+import { DeferredPopup } from "../../common/deferred-popup";
+import { DeferredTooltip } from "../../common/deferred-tooltip";
+import { VirtuosoSeed } from "../../common/virtuoso-seed";
import type { IssueCreateDefaults } from "../surface/types";
// Insertion-position prediction intentionally omitted. The server's
@@ -35,6 +39,37 @@ import type { IssueCreateDefaults } from "../surface/types";
export const BOARD_COL_WIDTH = 280;
export const BOARD_CARD_WIDTH = BOARD_COL_WIDTH - 16 - 8; // col(280) - col p-2(16) - droppable p-1(8)
+// Board cards are ~90-140px tall, so ~10 fill a column viewport — unlike the
+// generic VIRTUOSO_SEED_COUNT (30, sized for 36px list rows). The seed mounts
+// synchronously per column on every surface remount, so oversizing it
+// multiplies straight into tab-switch cost (columns × seed × per-card mount).
+const BOARD_SEED_COUNT = 10;
+
+// Median card height (incl. the 8px pt-2 gap) for pre-measurement scroll
+// sizing only: the seed's trailing spacer and Virtuoso's defaultItemHeight
+// share it so total scroll height — and the scrollbar thumb — stays steady
+// across the seed → Virtuoso handoff instead of jumping when the unseeded
+// rows suddenly get spaced out. Real measurements refine it afterwards.
+const BOARD_CARD_ESTIMATED_HEIGHT = 110;
+
+// Columns at or below this render every card plainly — no Virtuoso, no seed
+// handoff, no estimated heights. Scroll height is then always browser-measured
+// truth, so the column's scrollbar can never jump on mount, route return, or
+// tab restore. Virtualization only pays for itself on large columns (Linear
+// does the same per-column split: `data-virtual-cluster="false"` for small
+// columns, padding-spacer virtualization for big ones). ~30 ≈ 3 viewports of
+// cards; a full plain mount at that size is cheap now that per-card popups
+// mount lazily. Known edge: a load-more append that crosses the threshold
+// swaps the column to the virtualized path, which may adjust the scrollbar
+// once — accepted, since it only happens mid-scroll at the column bottom.
+const BOARD_VIRTUALIZE_THRESHOLD = 30;
+
+// Passed to <Virtuoso components> when the column has no footer. Must be a
+// STABLE object, never `undefined`: an explicit `undefined` prop overwrites
+// react-virtuoso's internal `{}` default and its startup destructure of
+// `EmptyPlaceholder`/`Footer` throws (MUL-4474).
+const EMPTY_VIRTUOSO_COMPONENTS = {};
+
export interface BoardColumnGroup {
id: string;
title: string;
@@ -90,6 +125,53 @@ export const BoardColumn = memo(function BoardColumn({
[issueIds, issueMap],
);
+ // The column's scroll container is both dnd-kit's droppable and Virtuoso's
+ // customScrollParent, so a merged callback ref feeds the element to both.
+ // useDroppable's setNodeRef is stable across renders. Keeping the droppable
+ // on the always-mounted scroll container (not on individual cards) is what
+ // lets cross-column drops survive virtualization — only the cards inside
+ // window in/out of the DOM.
+ const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);
+ // Pull-based scroll restoration (MUL-4741): assign the saved offset at
+ // ref-attach (the seed + estimate spacer give the column a truthful height
+ // on its first commit, so the assignment sticks pre-paint) and feed the
+ // same offset into the Virtuoso as its initial position.
+ const scrollMementoKey = `board:${group.id}`;
+ const restoredScrollTop = useRestoredScrollOffset(scrollMementoKey);
+ const restoreScrollRef = useRestoredScrollRef(scrollMementoKey);
+ const mergedRef = useCallback(
+ (el: HTMLDivElement | null) => {
+ setNodeRef(el);
+ setScrollEl(el);
+ restoreScrollRef(el);
+ },
+ [setNodeRef, restoreScrollRef],
+ );
+ // Infinite-scroll sentinel rides Virtuoso's Footer slot so it sits at the
+ // real end of the virtualized list and its IntersectionObserver still fires
+ // loadMore when scrolled to the bottom.
+ const footerComponents = useMemo(
+ () => (footer ? { Footer: () => <>{footer}</> } : EMPTY_VIRTUOSO_COMPONENTS),
+ [footer],
+ );
+
+ const computeItemKey = (_index: number, issue: Issue) => issue.id;
+ const itemContent = (index: number, issue: Issue) => (
+ // pt-2 on every card but the first reproduces the previous `space-y-2`
+ // gap; padding (not margin) is inside Virtuoso's measured item box so its
+ // height math stays correct.
+ <div className={index === 0 ? undefined : "pt-2"}>
+ <DraggableBoardCard
+ issue={issue}
+ childProgress={childProgressMap?.get(issue.id)}
+ project={
+ issue.project_id ? projectMap?.get(issue.project_id) : undefined
+ }
+ disableSorting={!!sortLabel}
+ />
+ </div>
+ );
+
return (
<div style={{ width: BOARD_COL_WIDTH }} className={`flex shrink-0 flex-col rounded-xl ${cfg?.columnBg ?? "bg-muted/40"} p-2`}>
<div className="mb-2 flex items-center justify-between px-1.5">
@@ -97,45 +179,58 @@ export const BoardColumn = memo(function BoardColumn({
{/* Right: add + menu */}
<div className="flex items-center gap-1">
+ {/* Column-header popups mount lazily: a board/swimlane renders one
+ header per column and almost none of these menus/tooltips are
+ ever opened — eagerly mounting them dominated surface mount
+ cost (DeferredPopup / DeferredTooltip). */}
{status && (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button variant="ghost" size="icon-sm" className="rounded-full text-muted-foreground">
- <MoreHorizontal className="size-3.5" />
- </Button>
- }
- />
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => viewStoreApi.getState().hideStatus(status)}>
- <EyeOff className="size-3.5" />
- {t(($) => $.board.hide_column)}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ <DeferredPopup
+ ariaHasPopup="menu"
+ triggerRender={
+ <Button variant="ghost" size="icon-sm" className="rounded-full text-muted-foreground">
+ <MoreHorizontal className="size-3.5" />
+ </Button>
+ }
+ >
+ {(open, onOpenChange) => (
+ <DropdownMenu open={open} onOpenChange={onOpenChange}>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="ghost" size="icon-sm" className="rounded-full text-muted-foreground">
+ <MoreHorizontal className="size-3.5" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => viewStoreApi.getState().hideStatus(status)}>
+ <EyeOff className="size-3.5" />
+ {t(($) => $.board.hide_column)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </DeferredPopup>
)}
{onCreateIssue && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- className="rounded-full text-muted-foreground"
- onClick={() => {
- const data = {
- ...(group.createData ?? {}),
- ...(projectId ? { project_id: projectId } : {}),
- };
- onCreateIssue(data);
- }}
- >
- <Plus className="size-3.5" />
- </Button>
- }
- />
- <TooltipContent>{t(($) => $.board.add_issue_tooltip)}</TooltipContent>
- </Tooltip>
+ <DeferredTooltip
+ content={t(($) => $.board.add_issue_tooltip)}
+ trigger={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="rounded-full text-muted-foreground"
+ onClick={() => {
+ const data = {
+ ...(group.createData ?? {}),
+ ...(projectId ? { project_id: projectId } : {}),
+ };
+ onCreateIssue(data);
+ }}
+ >
+ <Plus className="size-3.5" />
+ </Button>
+ }
+ />
)}
</div>
</div>
@@ -148,8 +243,12 @@ export const BoardColumn = memo(function BoardColumn({
</div>
)}
<div
- ref={setNodeRef}
- className={`absolute inset-0 space-y-2 overflow-y-auto rounded-lg p-1 transition-colors ${
+ ref={mergedRef}
+ // Per-column scroll registration for the tab session memento
+ // (MUL-4741): the group id is the stable memento key, so every
+ // column's offset survives tab switches/reloads independently.
+ data-tab-scroll-root={scrollMementoKey}
+ className={`absolute inset-0 overflow-y-auto rounded-lg p-1 transition-colors ${
isOver && sortLabel
? "ring-2 ring-brand/25 bg-accent/15"
: isOver
@@ -157,25 +256,62 @@ export const BoardColumn = memo(function BoardColumn({
: ""
}`}
>
- <SortableContext items={issueIds} strategy={verticalListSortingStrategy}>
- {resolvedIssues.map((issue) => (
- <DraggableBoardCard
- key={issue.id}
- issue={issue}
- childProgress={childProgressMap?.get(issue.id)}
- project={
- issue.project_id ? projectMap?.get(issue.project_id) : undefined
- }
- disableSorting={!!sortLabel}
- />
- ))}
- </SortableContext>
- {issueIds.length === 0 && (
- <p className="py-8 text-center text-xs text-muted-foreground">
- {t(($) => $.board.empty_column)}
- </p>
+ {resolvedIssues.length > 0 ? (
+ <SortableContext items={issueIds} strategy={verticalListSortingStrategy}>
+ {resolvedIssues.length <= BOARD_VIRTUALIZE_THRESHOLD ? (
+ /* Small column: plain full render (reusing the same
+ itemContent, so it is byte-identical to the virtualized
+ rows). No handoff, no estimates — see
+ BOARD_VIRTUALIZE_THRESHOLD. The footer (infinite-scroll
+ sentinel) renders at the real end of the flow, where its
+ IntersectionObserver works the same as in Virtuoso's
+ Footer slot. */
+ <>
+ <VirtuosoSeed
+ data={resolvedIssues}
+ itemContent={itemContent}
+ computeItemKey={computeItemKey}
+ count={resolvedIssues.length}
+ />
+ {footer}
+ </>
+ ) : scrollEl ? (
+ <Virtuoso
+ customScrollParent={scrollEl}
+ data={resolvedIssues}
+ computeItemKey={computeItemKey}
+ initialScrollTop={restoredScrollTop}
+ initialItemCount={Math.min(resolvedIssues.length, BOARD_SEED_COUNT)}
+ defaultItemHeight={BOARD_CARD_ESTIMATED_HEIGHT}
+ increaseViewportBy={{ top: 300, bottom: 300 }}
+ components={footerComponents}
+ itemContent={itemContent}
+ />
+ ) : (
+ /* Large column, merged scroll ref not settled yet after a
+ remount: seed a bounded slice of real cards so the column
+ never paints blank; once the ref lands, mount the Virtuoso
+ with a matching `initialItemCount` to survive the
+ measurement frame (MUL-4750). */
+ <VirtuosoSeed
+ data={resolvedIssues}
+ itemContent={itemContent}
+ computeItemKey={computeItemKey}
+ count={BOARD_SEED_COUNT}
+ estimatedItemHeight={BOARD_CARD_ESTIMATED_HEIGHT}
+ />
+ )}
+ </SortableContext>
+ ) : (
+ <>
+ {issueIds.length === 0 && (
+ <p className="py-8 text-center text-xs text-muted-foreground">
+ {t(($) => $.board.empty_column)}
+ </p>
+ )}
+ {footer}
+ </>
)}
- {footer}
</div>
</div>
</div>
diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsx
index b747d389bd..77add6f605 100644
--- a/packages/views/issues/components/board-view.tsx
+++ b/packages/views/issues/components/board-view.tsx
@@ -147,7 +147,7 @@ function buildGroups(
const EMPTY_PROGRESS_MAP = new Map<string, ChildProgress>();
const EMPTY_IDS: string[] = [];
-export function BoardView({
+function BoardViewImpl({
issues,
assigneeGroups,
assigneeGroupQueryKey,
@@ -781,3 +781,11 @@ function BoardHiddenColumnsPanel({
/>
);
}
+
+/**
+ * Memoized: the surface controller re-renders on loading-flag flips (e.g. a
+ * query enabling when the view changes) — without memo every such flip
+ * re-rendered this entire view tree (hundreds of ms). All props are
+ * referentially stable useMemo/useCallback outputs from the controller.
+ */
+export const BoardView = memo(BoardViewImpl);
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index a722ef9f35..2f8dbe60ef 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -23,7 +23,6 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
-import { Collapsible, CollapsibleTrigger, CollapsibleContent } from "@multica/ui/components/ui/collapsible";
import { ActorAvatar } from "../../common/actor-avatar";
import { ReactionBar } from "@multica/ui/components/common/reaction-bar";
import { cn } from "@multica/ui/lib/utils";
@@ -729,7 +728,10 @@ function CommentCardImpl({
const isCollapsed = useCommentCollapseStore((s) => s.isCollapsed(issueId, entry.id));
const toggleCollapse = useCommentCollapseStore((s) => s.toggle);
const open = !isCollapsed;
- const handleOpenChange = useCallback((_open: boolean) => toggleCollapse(issueId, entry.id), [toggleCollapse, issueId, entry.id]);
+ const handleToggle = useCallback(
+ () => toggleCollapse(issueId, entry.id),
+ [toggleCollapse, issueId, entry.id],
+ );
const edit = useEditAttachmentState(issueId, entry, onEdit);
@@ -790,8 +792,7 @@ function CommentCardImpl({
{t(($) => $.comment.resolve.collapse)}
</button>
)}
- <Collapsible open={open} onOpenChange={handleOpenChange}>
- {/* root-section — the sticky header's containing block. It wraps ONLY
+ {/* root-section — the sticky header's containing block. It wraps ONLY
the header + root body, so the header releases the moment you scroll
past the body into the replies (which render OUTSIDE this wrapper).
That is what keeps exactly one header pinned at a time: without this
@@ -805,9 +806,15 @@ function CommentCardImpl({
className="px-4 py-3"
>
<div className="flex items-center gap-2.5">
- <CollapsibleTrigger className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-controls={`comment-body-${entry.id}`}
+ onClick={handleToggle}
+ className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
+ >
<ChevronRight className={cn("h-3.5 w-3.5 transition-transform", open && "rotate-90")} />
- </CollapsibleTrigger>
+ </button>
<ActorAvatar actorType={entry.actor_type} actorId={entry.actor_id} size="md" enableHoverCard showStatusDot />
<span className="shrink-0 cursor-pointer text-sm font-medium">
{getActorName(entry.actor_type, entry.actor_id)}
@@ -904,10 +911,11 @@ function CommentCardImpl({
</div>
</StickyHeaderShell>
- {/* Collapsible body */}
- <CollapsibleContent>
- {/* Parent comment body */}
- <div className="px-4 pt-1 pb-3">
+ {/* Root comment body. Avoid Base UI's Panel here: every mounted panel
+ probes computed styles to detect animations, forcing a style
+ recalculation across long issue-detail documents. */}
+ {open && (
+ <div id={`comment-body-${entry.id}`} className="px-4 pt-1 pb-3">
{edit.editing ? (
<div
{...edit.dropZoneProps}
@@ -992,7 +1000,7 @@ function CommentCardImpl({
</>
)}
</div>
- </CollapsibleContent>
+ )}
</div>
{/* Replies + reply input — rendered OUTSIDE root-section so the root
@@ -1090,7 +1098,6 @@ function CommentCardImpl({
)}
</>
)}
- </Collapsible>
</Card>
);
}
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index 9c344c17f1..a82204f0df 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -1,9 +1,9 @@
-import { forwardRef, useImperativeHandle, useRef, type ReactNode, type Ref } from "react";
+import { forwardRef, useEffect, useImperativeHandle, useRef, type ReactNode, type Ref } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, screen, waitFor } from "@testing-library/react";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
-import { useCommentComposerStore } from "@multica/core/issues/stores";
+import { useCommentComposerStore, useCommentDraftStore } from "@multica/core/issues/stores";
import { renderWithI18n } from "../../test/i18n";
import { CommentInput } from "./comment-input";
import { ReplyInput } from "./reply-input";
@@ -26,7 +26,12 @@ vi.mock("../../common/actor-avatar", () => ({
),
}));
-vi.mock("../../editor", () => ({
+vi.mock("../../editor", async () => ({
+ // The lazy-mount controller is pure React (no Tiptap) — use the real one so
+ // shell → activate → ready flows behave exactly as in production.
+ ...(await vi.importActual<typeof import("../../editor/use-lazy-editor")>(
+ "../../editor/use-lazy-editor",
+ )),
useFileDropZone: () => ({
isDragOver: false,
dropZoneProps: { "data-testid": "drop-zone" },
@@ -38,22 +43,30 @@ vi.mock("../../editor", () => ({
onUpdate,
placeholder,
onUploadFile,
+ onReady,
}: {
defaultValue?: string;
onUpdate?: (markdown: string) => void;
placeholder?: string;
onUploadFile?: (file: File) => Promise<UploadResult | null>;
+ onReady?: () => void;
},
ref: Ref<unknown>,
) {
const valueRef = useRef(defaultValue ?? "");
+ useEffect(() => {
+ onReady?.();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
useImperativeHandle(ref, () => ({
getMarkdown: () => valueRef.current,
clearContent: () => {
valueRef.current = "";
},
focus: () => {},
+ focusAtCoords: () => {},
blur: () => {},
uploadFile: async (file: File) => {
const result = await onUploadFile?.(file);
@@ -114,6 +127,13 @@ function renderReplyInput({
return { ...view, onSubmit };
}
+// Composers render readonly-first: a static shell until clicked (unless an
+// unsent draft exists). Tests that interact with the editor activate it the
+// same way a user does.
+function activateComposer(shellTestId: "comment-composer-shell" | "reply-composer-shell") {
+ fireEvent.click(screen.getByTestId(shellTestId));
+}
+
function getSubmitButton(container: HTMLElement): HTMLButtonElement {
// Submit is always the last button in a composer's action cluster.
const buttons = container.querySelectorAll("button");
@@ -126,12 +146,20 @@ beforeEach(() => {
uploadWithToast.mockReset();
localStorage.clear();
useCommentComposerStore.setState({ sticky: true });
+ // The draft store is a module singleton — a draft left by a previous test
+ // (e.g. the failed-send case) would trip the composers' draft-direct-mount
+ // path and hide the shell the next test expects.
+ useCommentDraftStore.setState({ drafts: {} });
});
describe("comment composers", () => {
it("renders the main comment composer without a manual expand control", () => {
const { container } = renderCommentInput();
+ // Readonly-first: shell shows the placeholder text; clicking mounts the
+ // real editor in place.
+ expect(screen.getByTestId("comment-composer-shell")).toHaveTextContent("Leave a comment...");
+ activateComposer("comment-composer-shell");
expect(screen.getByPlaceholderText("Leave a comment...")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Attach file" })).toBeInTheDocument();
expect(container.querySelectorAll("button")).toHaveLength(2);
@@ -144,6 +172,8 @@ describe("comment composers", () => {
it("renders reply composer without a manual expand control", () => {
const { container } = renderReplyInput();
+ expect(screen.getByTestId("reply-composer-shell")).toHaveTextContent("Leave a reply...");
+ activateComposer("reply-composer-shell");
expect(screen.getByPlaceholderText("Leave a reply...")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Attach file" })).toBeInTheDocument();
expect(container.querySelectorAll("button")).toHaveLength(2);
@@ -156,6 +186,7 @@ describe("comment composers", () => {
it("lets default-size replies grow without a height cap", () => {
const { container } = renderReplyInput({ size: "default" });
+ activateComposer("reply-composer-shell");
expect(screen.getByPlaceholderText("Leave a reply...")).toBeInTheDocument();
expect(container.querySelectorAll("button")).toHaveLength(2);
@@ -166,6 +197,7 @@ describe("comment composers", () => {
it("keeps main comment submission wired after removing expand", async () => {
const { container, onSubmit } = renderCommentInput();
+ activateComposer("comment-composer-shell");
fireEvent.change(screen.getByTestId("editor"), {
target: { value: "hello from composer" },
});
@@ -179,6 +211,7 @@ describe("comment composers", () => {
it("keeps reply submission wired after removing expand", async () => {
const { container, onSubmit } = renderReplyInput();
+ activateComposer("reply-composer-shell");
fireEvent.change(screen.getByTestId("editor"), {
target: { value: "thread reply" },
});
@@ -196,6 +229,7 @@ describe("comment composers", () => {
);
const { container } = renderCommentInput(onSubmit);
+ activateComposer("comment-composer-shell");
fireEvent.change(screen.getByTestId("editor"), { target: { value: "sending" } });
fireEvent.click(getSubmitButton(container));
@@ -219,6 +253,7 @@ describe("comment composers", () => {
const onSubmit = vi.fn().mockResolvedValue(false);
const { container } = renderCommentInput(onSubmit);
+ activateComposer("comment-composer-shell");
fireEvent.change(screen.getByTestId("editor"), { target: { value: "will fail" } });
fireEvent.click(getSubmitButton(container));
@@ -232,6 +267,7 @@ describe("sticky composer preference", () => {
it("caps the editor height while the sticky preference is on (default)", () => {
renderCommentInput();
+ activateComposer("comment-composer-shell");
// The height cap lives on the editor wrapper, not the card shell.
expect(screen.getByTestId("editor").parentElement?.className).toContain("max-h-[40vh]");
});
@@ -240,6 +276,7 @@ describe("sticky composer preference", () => {
useCommentComposerStore.setState({ sticky: false });
renderCommentInput();
+ activateComposer("comment-composer-shell");
expect(screen.getByTestId("editor").parentElement?.className).not.toContain("max-h-[40vh]");
});
});
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index defb001831..b59df228b6 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -2,7 +2,7 @@
import { useRef, useState, useCallback, useEffect } from "react";
import { cn } from "@multica/ui/lib/utils";
-import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay } from "../../editor";
+import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
@@ -44,8 +44,16 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
// resolve text/code/markdown previews that require the attachment id.
const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);
const { uploadWithToast } = useFileUpload(api);
+ // Readonly-first: the composer renders as a same-looking static shell until
+ // the user shows intent (click / keyboard / file drop). An unsent draft is
+ // standing intent — mount the real editor immediately so the draft is
+ // visible and editable, exactly like the pre-lazy behavior.
+ const lazy = useLazyEditor({
+ initialActive: !!initialDraft?.trim(),
+ editorRef,
+ });
const { isDragOver, dropZoneProps } = useFileDropZone({
- onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),
+ onDrop: lazy.uploadOrQueue,
});
// Sticky preference (Settings → Preferences): issue-detail pins this
// composer to the bottom of the scroll viewport when enabled.
@@ -147,6 +155,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
toggle Tiptap's `editable` post-mount (see its docstring), so the
documented way to make it non-interactive is a pointer-events-none +
dimmed wrapper. */}
+ {lazy.active && (
<div
className={cn(
"flex-1 min-h-0 overflow-y-auto px-3 py-2",
@@ -155,12 +164,14 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
// area scrolls internally instead).
sticky && "max-h-[40vh]",
submitting && "pointer-events-none opacity-60",
+ !lazy.ready && "hidden",
)}
aria-busy={submitting || undefined}
>
<ContentEditor
ref={editorRef}
defaultValue={initialDraft}
+ onReady={lazy.onReady}
placeholder={t(($) => $.comment.leave_comment_placeholder)}
onUpdate={(md) => {
setContent(md);
@@ -179,6 +190,33 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
slashCommandMode="command"
/>
</div>
+ )}
+ {/* Static shell — visually clones the empty single-line composer.
+ Real editor mounts (hidden) on first intent; shell stays visible
+ until it's ready so the card never blanks or shifts. */}
+ {!lazy.ready && (
+ <div
+ data-testid="comment-composer-shell"
+ role="button"
+ tabIndex={0}
+ aria-label={t(($) => $.comment.leave_comment_placeholder)}
+ className="flex-1 min-h-0 cursor-text px-3 py-2"
+ onClick={() => lazy.activate()}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ lazy.activate();
+ }
+ }}
+ >
+ {/* rich-text-editor + <p>: the shell line inherits the editor's
+ exact type metrics (line-height 1.625 from prose.css), so the
+ shell→editor swap doesn't shift layout. */}
+ <div className="rich-text-editor text-sm">
+ <p className="text-muted-foreground">{t(($) => $.comment.leave_comment_placeholder)}</p>
+ </div>
+ </div>
+ )}
<div className="absolute bottom-1 left-2 right-28 min-w-0">
<CommentTriggerChips
agents={triggerPreview.agents}
@@ -192,7 +230,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
<FileUploadButton
size="sm"
multiple
- onSelect={(file) => editorRef.current?.uploadFile(file)}
+ onSelect={(file) => lazy.uploadOrQueue([file])}
/>
<SubmitButton
onClick={handleSubmit}
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 9e60e445f5..a57eaaf813 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -1,4 +1,4 @@
-import { forwardRef, useRef, useState, useImperativeHandle } from "react";
+import { forwardRef, useEffect, useRef, useState, useImperativeHandle } from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -12,6 +12,10 @@ const TEST_RESOURCES = { en: { common: enCommon, issues: enIssues } };
const mockViewport = vi.hoisted(() => ({ isMobile: false }));
+// Counts MockContentEditor mounts. This pins the description to exactly one
+// eager editor per issue and catches stale editor reuse across issue switches.
+const contentEditorMounts = vi.hoisted(() => ({ count: 0 }));
+
vi.mock("@multica/ui/hooks/use-mobile", () => ({
useIsMobile: () => mockViewport.isMobile,
}));
@@ -111,7 +115,12 @@ vi.mock("../../navigation", () => ({
}));
// Mock editor components (Tiptap requires real DOM)
-vi.mock("../../editor", () => ({
+vi.mock("../../editor", async () => ({
+ // Real lazy-mount controller (pure React, no Tiptap) so readonly-first
+ // shell → activate → ready flows behave exactly as in production.
+ ...(await vi.importActual<typeof import("../../editor/use-lazy-editor")>(
+ "../../editor/use-lazy-editor",
+ )),
useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
FileDropOverlay: () => null,
// No-op so comment-card's AttachmentList can render without hitting the
@@ -130,15 +139,21 @@ vi.mock("../../editor", () => ({
<div data-testid="readonly-content">{content}</div>
),
ContentEditor: forwardRef(function MockContentEditor(
- { defaultValue, onUpdate, placeholder, flushPendingOnUnmount }: any,
+ { defaultValue, onUpdate, placeholder, flushPendingOnUnmount, onReady }: any,
ref: any,
) {
const valueRef = useRef(defaultValue || "");
const [value, setValue] = useState(defaultValue || "");
+ useEffect(() => {
+ contentEditorMounts.count += 1;
+ onReady?.();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
useImperativeHandle(ref, () => ({
getMarkdown: () => valueRef.current,
clearContent: () => { valueRef.current = ""; setValue(""); },
focus: () => {},
+ focusAtCoords: () => {},
uploadFile: () => {},
}));
return (
@@ -156,14 +171,19 @@ vi.mock("../../editor", () => ({
);
}),
TitleEditor: forwardRef(function MockTitleEditor(
- { defaultValue, placeholder, onBlur, onChange }: any,
+ { defaultValue, placeholder, onBlur, onChange, onReady }: any,
ref: any,
) {
const valueRef = useRef(defaultValue || "");
const [value, setValue] = useState(defaultValue || "");
+ useEffect(() => {
+ onReady?.();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
useImperativeHandle(ref, () => ({
getText: () => valueRef.current,
focus: () => {},
+ focusAtCoords: () => {},
}));
return (
<input
@@ -533,6 +553,7 @@ function hasHighlightedCommentBackground(root: ParentNode | null): boolean {
describe("IssueDetail (shared)", () => {
beforeEach(() => {
vi.clearAllMocks();
+ contentEditorMounts.count = 0;
mockViewport.isMobile = false;
// Default: issue loads successfully
mockApiObj.getIssue.mockResolvedValue(mockIssue);
@@ -564,14 +585,27 @@ describe("IssueDetail (shared)", () => {
).toBe(true);
});
+ it("renders comment bodies without Base UI collapsible panels", async () => {
+ const { container } = renderIssueDetail();
+
+ await screen.findByText("Started working on this");
+
+ expect(
+ container.querySelector('[data-slot="collapsible-content"]'),
+ ).toBeNull();
+ });
+
it("renders issue title and description after loading", async () => {
renderIssueDetail();
- await waitFor(() => {
- expect(screen.getByDisplayValue("Implement authentication")).toBeInTheDocument();
- });
-
- expect(screen.getByDisplayValue("Add JWT auth to the backend")).toBeInTheDocument();
+ // The description is the one eager editor: keeping one renderer avoids the
+ // layout jump caused by swapping a long react-markdown tree for ProseMirror.
+ // Title and comment/reply composers remain readonly-first.
+ expect(await screen.findByDisplayValue("Add JWT auth to the backend")).toBeInTheDocument();
+ expect(screen.getByText("Implement authentication")).toBeInTheDocument();
+ expect(screen.queryByTestId("title-editor")).not.toBeInTheDocument();
+ expect(screen.getAllByTestId("rich-text-editor")).toHaveLength(1);
+ expect(contentEditorMounts.count).toBe(1);
});
it("opts the description editor into the unmount flush", async () => {
@@ -587,6 +621,45 @@ describe("IssueDetail (shared)", () => {
expect(description).toHaveAttribute("data-flush-on-unmount", "true");
});
+ it("remounts the eager description on issue switch without carrying stale content", async () => {
+ // The web route reuses IssueDetail across issues. The keyed description
+ // editor must remount atomically for the new issue while the title remains
+ // on its cheap stand-in.
+ const queryClient = createTestQueryClient();
+ const issue2 = {
+ ...mockIssue,
+ id: "issue-2",
+ title: "Second issue",
+ description: "Second description",
+ };
+ // The cache seed marks the data stale, so the query refetches in the
+ // background — getIssue must answer per-id or the refetch would clobber
+ // issue-2 with issue-1's payload.
+ mockApiObj.getIssue.mockImplementation((issueId: string) =>
+ Promise.resolve(issueId === "issue-2" ? issue2 : mockIssue),
+ );
+ // Pre-seed issue-2 so its first render skips the loading skeleton.
+ queryClient.setQueryData(["issues", "ws-1", "detail", "issue-2"], issue2);
+ const ui = (issueId: string) => (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={queryClient}>
+ <IssueDetail issueId={issueId} />
+ </QueryClientProvider>
+ </I18nProvider>
+ );
+ const { rerender } = render(ui("issue-1"));
+
+ await screen.findByDisplayValue("Add JWT auth to the backend");
+ const mountsBeforeSwitch = contentEditorMounts.count;
+
+ rerender(ui("issue-2"));
+
+ expect(await screen.findByDisplayValue("Second description")).toBeInTheDocument();
+ expect(screen.queryByDisplayValue("Add JWT auth to the backend")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("title-editor")).not.toBeInTheDocument();
+ expect(contentEditorMounts.count).toBe(mountsBeforeSwitch + 1);
+ });
+
it("renders the issue title leaf as a link to the issue detail page", async () => {
renderIssueDetail();
@@ -693,7 +766,7 @@ describe("IssueDetail (shared)", () => {
renderIssueDetail();
await waitFor(() => {
- expect(screen.getByDisplayValue("Implement authentication")).toBeInTheDocument();
+ expect(screen.getByText("Implement authentication")).toBeInTheDocument();
});
expect(screen.queryByTestId("panel-group")).not.toBeInTheDocument();
@@ -1294,11 +1367,7 @@ describe("IssueDetail (shared)", () => {
it("sends empty description when editor is cleared", async () => {
renderIssueDetail();
- await waitFor(() => {
- expect(screen.getByDisplayValue("Add JWT auth to the backend")).toBeInTheDocument();
- });
-
- const editor = screen.getByPlaceholderText("Add description...");
+ const editor = await screen.findByDisplayValue("Add JWT auth to the backend");
fireEvent.change(editor, { target: { value: "" } });
await waitFor(() => {
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 0942dd9cb0..2b5b3e3775 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -31,7 +31,7 @@ import { Button } from "@multica/ui/components/ui/button";
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/ui/components/ui/resizable";
import { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
-import { ContentEditor, type ContentEditorRef, TitleEditor, useFileDropZone, FileDropOverlay } from "../../editor";
+import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import {
Tooltip,
@@ -93,6 +93,7 @@ import { ReactionBar } from "@multica/ui/components/common/reaction-bar";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { api } from "@multica/core/api";
import { useTimeAgo } from "../../i18n";
+import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";
import { cn } from "@multica/ui/lib/utils";
import { ProgressRing } from "./progress-ring";
@@ -786,6 +787,20 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// Virtuoso prop would never receive the element. Callback ref + state fixes
// that: setState triggers the re-render that hands Virtuoso the element.
const [scrollContainerEl, setScrollContainerEl] = useState<HTMLDivElement | null>(null);
+ // Pull-based scroll restoration (MUL-4741): the platform serves the offset
+ // captured when this route was last left. The ref-attach assignment covers
+ // the flat render modes (real heights at commit); the virtualized browsing
+ // mode feeds the offset into Virtuoso's initialScrollTop below so the
+ // list's first render already materializes the rows around it.
+ const restoredScrollTop = useRestoredScrollOffset("main");
+ const restoreScrollRef = useRestoredScrollRef("main");
+ const attachScrollContainer = useCallback(
+ (el: HTMLDivElement | null) => {
+ setScrollContainerEl(el);
+ restoreScrollRef(el);
+ },
+ [restoreScrollRef],
+ );
const [highlightedId, setHighlightedId] = useState<string | null>(null);
// User preference: pin the bottom comment bar to the scroll viewport.
const stickyComposer = useCommentComposerStore((s) => s.sticky);
@@ -1297,8 +1312,15 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
}, [highlightCommentId, items, targetIdx, scrollContainerEl, replyToRoot, expandedResolved, timelineView, toggleResolvedExpand]);
const descEditorRef = useRef<ContentEditorRef>(null);
+ // Keep the description editor mounted from the start. Unlike the empty
+ // composer shells, a long rendered description cannot swap between
+ // react-markdown and ProseMirror without small per-block height differences
+ // accumulating into a visible scroll/layout jump. The chunked Markdown path
+ // keeps this single eager editor affordable; title and composers stay lazy.
+ const titleEditorRef = useRef<TitleEditorRef>(null);
+ const titleLazy = useLazyEditor({ editorRef: titleEditorRef, resetKey: id });
const { isDragOver: descDragOver, dropZoneProps: descDropZoneProps } = useFileDropZone({
- onDrop: (files) => files.forEach((f) => descEditorRef.current?.uploadFile(f)),
+ onDrop: (files) => files.forEach((file) => descEditorRef.current?.uploadFile(file)),
});
// Pending uploads in the description editor. We don't pass `issueId` on
// upload (to avoid orphaning attachments when the user deletes the file
@@ -2051,21 +2073,48 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
the gutter restores symmetry; overlay-scrollbar platforms reserve
nothing and render unchanged. */}
<div
- ref={setScrollContainerEl}
+ ref={attachScrollContainer}
data-tab-scroll-root
className="relative flex-1 overflow-y-auto [scrollbar-gutter:stable_both-edges]"
>
<div className="mx-auto w-full max-w-4xl px-8 py-8">
- <TitleEditor
- key={`title-${id}`}
- defaultValue={issue.title}
- placeholder={t(($) => $.detail.title_placeholder)}
- className="w-full text-2xl font-bold leading-snug tracking-tight"
- onBlur={(value) => {
- const trimmed = value.trim();
- if (trimmed && trimmed !== issue.title) handleUpdateField({ title: trimmed });
- }}
- />
+ {titleLazy.active && (
+ <div className={titleLazy.ready ? undefined : "hidden"}>
+ <TitleEditor
+ key={`title-${id}`}
+ ref={titleEditorRef}
+ defaultValue={issue.title}
+ placeholder={t(($) => $.detail.title_placeholder)}
+ className="w-full text-2xl font-bold leading-snug tracking-tight"
+ onReady={titleLazy.onReady}
+ onBlur={(value) => {
+ const trimmed = value.trim();
+ if (trimmed && trimmed !== issue.title) handleUpdateField({ title: trimmed });
+ }}
+ />
+ </div>
+ )}
+ {!titleLazy.ready && (
+ <div
+ role="button"
+ tabIndex={0}
+ className="w-full cursor-text text-2xl font-bold leading-snug tracking-tight"
+ onClick={(e) => {
+ // A drag-selection (copying the title) must not summon the editor.
+ const sel = window.getSelection();
+ if (sel && !sel.isCollapsed) return;
+ titleLazy.activate({ x: e.clientX, y: e.clientY });
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ titleLazy.activate();
+ }
+ }}
+ >
+ {issue.title}
+ </div>
+ )}
{parentIssue && (
<AppLink
@@ -2351,6 +2400,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
ref={virtuosoRef}
customScrollParent={scrollContainerEl}
data={items}
+ initialScrollTop={restoredScrollTop}
increaseViewportBy={{ top: 800, bottom: 800 }}
computeItemKey={(_i, item) => `${item.kind}:${item.id}`}
skipAnimationFrameInResizeObserver
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index cdb6d35afa..62f59acea0 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -293,16 +293,23 @@ vi.mock("sonner", () => ({
}));
// Mock dnd-kit
-vi.mock("@dnd-kit/core", () => ({
- DndContext: ({ children }: any) => children,
- DragOverlay: () => null,
- PointerSensor: class {},
- useSensor: () => ({}),
- useSensors: () => [],
- useDroppable: () => ({ setNodeRef: vi.fn(), isOver: false }),
- pointerWithin: vi.fn(),
- closestCenter: vi.fn(),
-}));
+vi.mock("@dnd-kit/core", () => {
+ // Real dnd-kit useDroppable returns a referentially stable setNodeRef
+ // (memoized internally). BoardColumn merges it with a state-setting
+ // callback ref for Virtuoso's customScrollParent, so a fresh function each
+ // render would loop the ref detach/reattach. Model the stable identity.
+ const stableSetNodeRef = () => {};
+ return {
+ DndContext: ({ children }: any) => children,
+ DragOverlay: () => null,
+ PointerSensor: class {},
+ useSensor: () => ({}),
+ useSensors: () => [],
+ useDroppable: () => ({ setNodeRef: stableSetNodeRef, isOver: false }),
+ pointerWithin: vi.fn(),
+ closestCenter: vi.fn(),
+ };
+});
vi.mock("@dnd-kit/sortable", () => ({
SortableContext: ({ children }: any) => children,
@@ -336,6 +343,21 @@ vi.mock("@base-ui/react/accordion", () => ({
),
}));
+// Mock react-virtuoso: jsdom has no layout, so the real Virtuoso computes a
+// 0-height viewport and renders nothing (and throws on its resize plumbing).
+// Render every item inline so the virtualized board columns expose their
+// cards to the DOM, matching the non-virtualized behavior these tests assert.
+vi.mock("react-virtuoso", () => ({
+ Virtuoso: ({ data, itemContent, components }: any) => (
+ <div data-testid="virtuoso-mock">
+ {(data ?? []).map((item: any, i: number) => (
+ <div key={i}>{itemContent(i, item)}</div>
+ ))}
+ {components?.Footer ? <components.Footer /> : null}
+ </div>
+ ),
+}));
+
// ---------------------------------------------------------------------------
// Test data
// ---------------------------------------------------------------------------
diff --git a/packages/views/issues/components/list-view.tsx b/packages/views/issues/components/list-view.tsx
index 0e0c60b876..07c6966fc5 100644
--- a/packages/views/issues/components/list-view.tsx
+++ b/packages/views/issues/components/list-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback, useMemo, useEffect, useRef } from "react";
+import { memo, useState, useCallback, useMemo, useEffect, useRef } from "react";
import { ChevronRight, Plus } from "lucide-react";
import { Accordion } from "@base-ui/react/accordion";
import {
@@ -15,7 +15,7 @@ import {
type DragOverEvent,
} from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy, arrayMove } from "@dnd-kit/sortable";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
+import { Virtuoso } from "react-virtuoso";
import { Button } from "@multica/ui/components/ui/button";
import type { Issue, IssueStatus, Project } from "@multica/core/types";
import { useLoadMoreByStatus } from "@multica/core/issues/mutations";
@@ -40,9 +40,24 @@ import {
import type { BoardColumnGroup } from "./board-column";
import { useIssueSurfaceSelection } from "../surface/selection-context";
import type { IssueCreateDefaults } from "../surface/types";
+import { VirtuosoSeed, VIRTUOSO_SEED_COUNT } from "../../common/virtuoso-seed";
+import { DeferredTooltip } from "../../common/deferred-tooltip";
+import { useRestoredScrollRef } from "../../platform";
+
+// List rows are a fixed 36px (h-9). Sharing the estimate between the seed's
+// trailing spacer and Virtuoso's defaultItemHeight keeps the shared
+// scroller's height truthful from the first frame — which both stops the
+// scrollbar from re-drawing across the seed → Virtuoso handoff and lets the
+// restored scrollTop assignment stick at ref-attach (MUL-4741).
+const LIST_ROW_ESTIMATED_HEIGHT = 36;
const EMPTY_PROGRESS_MAP = new Map<string, ChildProgress>();
const EMPTY_IDS: string[] = [];
+// Passed to <Virtuoso components> when there is no Footer. Must be a STABLE
+// object, never `undefined`: react-virtuoso seeds `components` with an internal
+// `{}` default, and an explicit `undefined` prop overwrites that default, so
+// its startup destructure of `EmptyPlaceholder`/`Footer` throws (MUL-4474).
+const EMPTY_VIRTUOSO_COMPONENTS = {};
function buildListGroups(visibleStatuses: IssueStatus[]): BoardColumnGroup[] {
return visibleStatuses.map((status) => ({
@@ -53,7 +68,7 @@ function buildListGroups(visibleStatuses: IssueStatus[]): BoardColumnGroup[] {
}));
}
-export function ListView({
+function ListViewImpl({
issues,
visibleStatuses,
childProgressMap = EMPTY_PROGRESS_MAP,
@@ -294,6 +309,24 @@ export function ListView({
[issues, groups, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, setColumns, columnsRef, isDraggingRef],
);
+ // The single scroll container is shared by every status panel's Virtuoso as
+ // its customScrollParent, so a callback ref hands the element to the panels
+ // once it mounts. Keeping one scroller (rather than one per panel) preserves
+ // the current sticky-header + cross-section scroll behavior; only the rows
+ // inside each expanded panel virtualize.
+ const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);
+ // Pull-based scroll restoration (MUL-4741): assign the saved offset when
+ // the shared scroller attaches — the per-status seeds plus their estimate
+ // spacers give it a truthful height on the first commit.
+ const restoreScrollRef = useRestoredScrollRef("list");
+ const attachScroller = useCallback(
+ (el: HTMLDivElement | null) => {
+ setScrollEl(el);
+ restoreScrollRef(el);
+ },
+ [restoreScrollRef],
+ );
+
const content = (
<Accordion.Root
multiple
@@ -327,6 +360,7 @@ export function ListView({
isExpanded={isExpanded}
sortLabel={sortLabel}
sort={sort}
+ scrollParent={scrollEl}
/>
);
})}
@@ -335,7 +369,7 @@ export function ListView({
if (!dragEnabled) {
return (
- <div className="flex-1 min-h-0 overflow-y-auto p-2 pt-0">
+ <div ref={attachScroller} data-tab-scroll-root="list" className="flex-1 min-h-0 overflow-y-auto p-2 pt-0">
{content}
</div>
);
@@ -349,7 +383,7 @@ export function ListView({
onDragOver={handleDragOver}
onDragEnd={handleDragEnd}
>
- <div className="flex-1 min-h-0 overflow-y-auto p-2 pt-0">
+ <div ref={attachScroller} data-tab-scroll-root="list" className="flex-1 min-h-0 overflow-y-auto p-2 pt-0">
{content}
</div>
@@ -378,6 +412,7 @@ function StatusAccordionItem({
isExpanded,
sortLabel,
sort,
+ scrollParent,
}: {
status: IssueStatus;
issueIds: string[];
@@ -391,6 +426,7 @@ function StatusAccordionItem({
isExpanded: boolean;
sortLabel: string | null;
sort?: IssueSortParam;
+ scrollParent: HTMLElement | null;
}) {
const { t } = useT("issues");
const selection = useIssueSurfaceSelection();
@@ -422,6 +458,69 @@ function StatusAccordionItem({
const disableSorting = !!sortLabel;
+ // The infinite-scroll sentinel rides Virtuoso's Footer so it sits at the true
+ // end of the virtualized rows and still fires loadMore when scrolled to it.
+ const listComponents = useMemo(
+ () =>
+ hasMore
+ ? { Footer: () => <InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} /> }
+ : EMPTY_VIRTUOSO_COMPONENTS,
+ [hasMore, loadMore, isLoading],
+ );
+
+ const computeItemKey = (_index: number, issue: Issue) => issue.id;
+ const itemContent = (_index: number, issue: Issue) =>
+ dragEnabled ? (
+ <DraggableListRow
+ issue={issue}
+ childProgress={childProgressMap.get(issue.id)}
+ project={
+ issue.project_id ? projectMap?.get(issue.project_id) : undefined
+ }
+ disableSorting={disableSorting}
+ />
+ ) : (
+ <ListRow
+ issue={issue}
+ childProgress={childProgressMap.get(issue.id)}
+ project={
+ issue.project_id ? projectMap?.get(issue.project_id) : undefined
+ }
+ />
+ );
+
+ // Rows virtualize into the page's shared scroll parent. Only render when the
+ // section is expanded and non-empty — a Virtuoso in a collapsed (0-height /
+ // hidden) panel has no viewport to measure. While the shared scroll parent
+ // is still null (callback ref not settled after a route-return remount),
+ // seed a bounded slice of real rows so the first painted frame isn't blank;
+ // once it's set, mount the Virtuoso with a matching `initialItemCount` so the
+ // measurement frame keeps those rows instead of flashing empty (MUL-4750).
+ // The droppable, SortableContext, sticky header, and collapse are unchanged;
+ // virtualization only decides whether an off-screen row is in the DOM.
+ const rows =
+ isExpanded && issues.length > 0 ? (
+ scrollParent ? (
+ <Virtuoso
+ customScrollParent={scrollParent}
+ data={issues}
+ computeItemKey={computeItemKey}
+ initialItemCount={Math.min(issues.length, VIRTUOSO_SEED_COUNT)}
+ defaultItemHeight={LIST_ROW_ESTIMATED_HEIGHT}
+ increaseViewportBy={{ top: 400, bottom: 400 }}
+ components={listComponents}
+ itemContent={itemContent}
+ />
+ ) : (
+ <VirtuosoSeed
+ data={issues}
+ itemContent={itemContent}
+ computeItemKey={computeItemKey}
+ estimatedItemHeight={LIST_ROW_ESTIMATED_HEIGHT}
+ />
+ )
+ ) : null;
+
return (
<Accordion.Item value={status} ref={dragEnabled ? setDroppableRef : undefined}>
<Accordion.Header
@@ -454,27 +553,26 @@ function StatusAccordionItem({
</Accordion.Trigger>
{onCreateIssue && (
<div className="pr-2">
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="ghost"
- size="icon-sm"
- className="rounded-full text-muted-foreground opacity-0 group-hover/header:opacity-100 transition-opacity"
- onClick={() => {
- const defaults = {
- status,
- ...(projectId ? { project_id: projectId } : {}),
- };
- onCreateIssue(defaults);
- }}
- />
- }
- >
- <Plus className="size-3.5" />
- </TooltipTrigger>
- <TooltipContent>{t(($) => $.list.add_issue_tooltip)}</TooltipContent>
- </Tooltip>
+ {/* Lazy-mounted tooltip machinery — see DeferredTooltip. */}
+ <DeferredTooltip
+ content={t(($) => $.list.add_issue_tooltip)}
+ trigger={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="rounded-full text-muted-foreground opacity-0 group-hover/header:opacity-100 transition-opacity"
+ onClick={() => {
+ const defaults = {
+ status,
+ ...(projectId ? { project_id: projectId } : {}),
+ };
+ onCreateIssue(defaults);
+ }}
+ >
+ <Plus className="size-3.5" />
+ </Button>
+ }
+ />
</div>
)}
</Accordion.Header>
@@ -482,37 +580,10 @@ function StatusAccordionItem({
{issues.length > 0 ? (
dragEnabled ? (
<SortableContext items={issueIds} strategy={verticalListSortingStrategy}>
- {issues.map((issue) => (
- <DraggableListRow
- key={issue.id}
- issue={issue}
- childProgress={childProgressMap.get(issue.id)}
- project={
- issue.project_id ? projectMap?.get(issue.project_id) : undefined
- }
- disableSorting={disableSorting}
- />
- ))}
- {hasMore && (
- <InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />
- )}
+ {rows}
</SortableContext>
) : (
- <>
- {issues.map((issue) => (
- <ListRow
- key={issue.id}
- issue={issue}
- childProgress={childProgressMap.get(issue.id)}
- project={
- issue.project_id ? projectMap?.get(issue.project_id) : undefined
- }
- />
- ))}
- {hasMore && (
- <InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />
- )}
- </>
+ rows
)
) : (
<p className="py-6 text-center text-xs text-muted-foreground">
@@ -523,3 +594,11 @@ function StatusAccordionItem({
</Accordion.Item>
);
}
+
+/**
+ * Memoized: the surface controller re-renders on loading-flag flips (e.g. a
+ * query enabling when the view changes) — without memo every such flip
+ * re-rendered this entire view tree (hundreds of ms). All props are
+ * referentially stable useMemo/useCallback outputs from the controller.
+ */
+export const ListView = memo(ListViewImpl);
diff --git a/packages/views/issues/components/pickers/assignee-picker.tsx b/packages/views/issues/components/pickers/assignee-picker.tsx
index 4b4f36f13d..0063061274 100644
--- a/packages/views/issues/components/pickers/assignee-picker.tsx
+++ b/packages/views/issues/components/pickers/assignee-picker.tsx
@@ -10,11 +10,13 @@ import { useActorName } from "@multica/core/workspace/hooks";
import { useWorkspaceId } from "@multica/core/hooks";
import { memberListOptions, agentListOptions, squadListOptions, assigneeFrequencyOptions } from "@multica/core/workspace/queries";
import { ActorAvatar } from "../../../common/actor-avatar";
+import { DeferredPopup } from "../../../common/deferred-popup";
import {
PropertyPicker,
PickerItem,
PickerSection,
PickerEmpty,
+ PICKER_TRIGGER_CLASS,
} from "./property-picker";
import { useT } from "../../../i18n";
import { matchesPinyin } from "../../../editor/extensions/pinyin-match";
@@ -37,17 +39,7 @@ export function canAssignAgent(
}).allowed;
}
-export function AssigneePicker({
- assigneeType,
- assigneeId,
- mixed = false,
- onUpdate,
- trigger: customTrigger,
- triggerRender,
- open: controlledOpen,
- onOpenChange: controlledOnOpenChange,
- align,
-}: {
+interface AssigneePickerProps {
assigneeType: IssueAssigneeType | null;
assigneeId: string | null;
/**
@@ -59,11 +51,52 @@ export function AssigneePicker({
mixed?: boolean;
onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
trigger?: React.ReactNode;
- triggerRender?: React.ReactElement;
+ triggerRender?: React.ReactElement<Record<string, unknown>>;
open?: boolean;
onOpenChange?: (v: boolean) => void;
align?: "start" | "center" | "end";
-}) {
+}
+
+/**
+ * Mounting the real picker subscribes to members/agents/squads/frequency
+ * queries — multiplied per board card / list row that cost froze tab
+ * switches. Uncontrolled callers that bring their own trigger content get a
+ * deferred lookalike trigger instead; the picker mounts on first interaction.
+ * The default trigger needs `getActorName` (a members/agents subscription
+ * itself), so trigger-less callers stay eager.
+ */
+export function AssigneePicker(props: AssigneePickerProps) {
+ const canDefer =
+ props.open === undefined &&
+ props.onOpenChange === undefined &&
+ (props.trigger !== undefined || props.triggerRender !== undefined);
+ if (!canDefer) {
+ return <AssigneePickerImpl {...props} />;
+ }
+ return (
+ <DeferredPopup
+ trigger={props.trigger}
+ triggerRender={props.triggerRender}
+ triggerClassName={PICKER_TRIGGER_CLASS}
+ >
+ {(open, onOpenChange) => (
+ <AssigneePickerImpl {...props} open={open} onOpenChange={onOpenChange} />
+ )}
+ </DeferredPopup>
+ );
+}
+
+function AssigneePickerImpl({
+ assigneeType,
+ assigneeId,
+ mixed = false,
+ onUpdate,
+ trigger: customTrigger,
+ triggerRender,
+ open: controlledOpen,
+ onOpenChange: controlledOnOpenChange,
+ align,
+}: AssigneePickerProps) {
const { t } = useT("issues");
const [internalOpen, setInternalOpen] = useState(false);
const open = controlledOpen ?? internalOpen;
diff --git a/packages/views/issues/components/pickers/due-date-picker.tsx b/packages/views/issues/components/pickers/due-date-picker.tsx
index 500c08f174..4c41b40c30 100644
--- a/packages/views/issues/components/pickers/due-date-picker.tsx
+++ b/packages/views/issues/components/pickers/due-date-picker.tsx
@@ -18,7 +18,7 @@ export function DueDatePicker({
dueDate: string | null;
onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
trigger?: React.ReactNode;
- triggerRender?: React.ReactElement;
+ triggerRender?: React.ReactElement<Record<string, unknown>>;
open?: boolean;
onOpenChange?: (v: boolean) => void;
align?: "start" | "center" | "end";
diff --git a/packages/views/issues/components/pickers/priority-picker.tsx b/packages/views/issues/components/pickers/priority-picker.tsx
index d8fe745f3f..d7f968e6f2 100644
--- a/packages/views/issues/components/pickers/priority-picker.tsx
+++ b/packages/views/issues/components/pickers/priority-picker.tsx
@@ -4,19 +4,11 @@ import { useState } from "react";
import type { IssuePriority, UpdateIssueRequest } from "@multica/core/types";
import { PRIORITY_ORDER, PRIORITY_CONFIG } from "@multica/core/issues/config";
import { PriorityIcon } from "../priority-icon";
-import { PropertyPicker, PickerItem } from "./property-picker";
+import { DeferredPopup } from "../../../common/deferred-popup";
+import { PropertyPicker, PickerItem, PICKER_TRIGGER_CLASS } from "./property-picker";
import { useT } from "../../../i18n";
-export function PriorityPicker({
- priority,
- onUpdate,
- trigger: customTrigger,
- triggerRender,
- open: controlledOpen,
- onOpenChange: controlledOnOpenChange,
- align,
- defaultOpen = false,
-}: {
+interface PriorityPickerProps {
/**
* The currently-selected priority, used to check the matching row. `null`
* means "no single current value" (e.g. a batch selection spanning several
@@ -26,14 +18,52 @@ export function PriorityPicker({
priority: IssuePriority | null;
onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
trigger?: React.ReactNode;
- triggerRender?: React.ReactElement;
+ triggerRender?: React.ReactElement<Record<string, unknown>>;
open?: boolean;
onOpenChange?: (v: boolean) => void;
align?: "start" | "center" | "end";
/** Open the picker on first mount. Used by progressive-disclosure
* sidebars so a newly-added field immediately enters edit state. */
defaultOpen?: boolean;
-}) {
+}
+
+/**
+ * Uncontrolled callers that bring their own trigger content (board cards,
+ * list rows) get a deferred lookalike trigger; the popover machinery mounts
+ * on first interaction. See `DeferredPopup` for why.
+ */
+export function PriorityPicker(props: PriorityPickerProps) {
+ const canDefer =
+ props.open === undefined &&
+ props.onOpenChange === undefined &&
+ !props.defaultOpen &&
+ (props.trigger !== undefined || props.triggerRender !== undefined);
+ if (!canDefer) {
+ return <PriorityPickerImpl {...props} />;
+ }
+ return (
+ <DeferredPopup
+ trigger={props.trigger}
+ triggerRender={props.triggerRender}
+ triggerClassName={PICKER_TRIGGER_CLASS}
+ >
+ {(open, onOpenChange) => (
+ <PriorityPickerImpl {...props} open={open} onOpenChange={onOpenChange} />
+ )}
+ </DeferredPopup>
+ );
+}
+
+function PriorityPickerImpl({
+ priority,
+ onUpdate,
+ trigger: customTrigger,
+ triggerRender,
+ open: controlledOpen,
+ onOpenChange: controlledOnOpenChange,
+ align,
+ defaultOpen = false,
+}: PriorityPickerProps) {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const open = controlledOpen ?? internalOpen;
const setOpen = controlledOnOpenChange ?? setInternalOpen;
diff --git a/packages/views/issues/components/pickers/property-picker.tsx b/packages/views/issues/components/pickers/property-picker.tsx
index 0b2ccf6909..c3772e887f 100644
--- a/packages/views/issues/components/pickers/property-picker.tsx
+++ b/packages/views/issues/components/pickers/property-picker.tsx
@@ -18,6 +18,14 @@ import { useT } from "../../../i18n";
const HIGHLIGHT_CLASS = "bg-accent";
const ITEM_SELECTOR = "button[data-picker-item]:not(:disabled)";
+/**
+ * Default class of the picker popover trigger. Shared with the deferred
+ * (pre-mount) lookalike trigger in `DeferredPopup` call sites so the swap on
+ * first interaction is pixel-identical.
+ */
+export const PICKER_TRIGGER_CLASS =
+ "flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden";
+
// ---------------------------------------------------------------------------
// PropertyPicker — generic Popover shell with optional search
// ---------------------------------------------------------------------------
@@ -145,7 +153,7 @@ export function PropertyPicker({
const popoverTrigger = (
<PopoverTrigger
- className={triggerRender ? undefined : "flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden"}
+ className={triggerRender ? undefined : PICKER_TRIGGER_CLASS}
render={triggerRender}
>
{trigger}
diff --git a/packages/views/issues/components/pickers/start-date-picker.tsx b/packages/views/issues/components/pickers/start-date-picker.tsx
index 49c1bcf5a1..956ee5ff14 100644
--- a/packages/views/issues/components/pickers/start-date-picker.tsx
+++ b/packages/views/issues/components/pickers/start-date-picker.tsx
@@ -18,7 +18,7 @@ export function StartDatePicker({
startDate: string | null;
onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
trigger?: React.ReactNode;
- triggerRender?: React.ReactElement;
+ triggerRender?: React.ReactElement<Record<string, unknown>>;
open?: boolean;
onOpenChange?: (v: boolean) => void;
align?: "start" | "center" | "end";
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index 433ed639b0..ceee8366a0 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -1,7 +1,7 @@
"use client";
import { useRef, useState, useCallback, useEffect } from "react";
-import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay } from "../../editor";
+import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { ActorAvatar } from "../../common/actor-avatar";
@@ -71,8 +71,17 @@ function ReplyInput({
// rationale (drives both submit-time attachment_ids and editor previews).
const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);
const { uploadWithToast } = useFileUpload(api);
+ // Readonly-first: static shell until intent; an unsent draft mounts the
+ // real editor immediately (see CommentInput). This is also what keeps the
+ // reply box working across Virtuoso scroll-out — a typed draft rehydrates
+ // into a live editor when the card remounts, an untouched box folds back
+ // to the shell.
+ const lazy = useLazyEditor({
+ initialActive: !!initialDraft?.trim(),
+ editorRef,
+ });
const { isDragOver, dropZoneProps } = useFileDropZone({
- onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),
+ onDrop: lazy.uploadOrQueue,
});
// Flush on tab close / mobile background — same rationale as CommentInput.
@@ -172,16 +181,19 @@ function ReplyInput({
)}
>
{/* Lock the editor while the reply is in flight — see CommentInput. */}
+ {lazy.active && (
<div
className={cn(
"flex-1 min-h-0 overflow-y-auto",
submitting && "pointer-events-none opacity-60",
+ !lazy.ready && "hidden",
)}
aria-busy={submitting || undefined}
>
<ContentEditor
ref={editorRef}
defaultValue={initialDraft}
+ onReady={lazy.onReady}
placeholder={placeholderText}
onUpdate={(md) => {
setContent(md);
@@ -200,6 +212,29 @@ function ReplyInput({
slashCommandMode="command"
/>
</div>
+ )}
+ {/* Static shell — clones the empty single-line reply box (see
+ CommentInput for the pattern). */}
+ {!lazy.ready && (
+ <div
+ data-testid="reply-composer-shell"
+ role="button"
+ tabIndex={0}
+ aria-label={placeholderText}
+ className="flex-1 min-h-0 cursor-text rich-text-editor text-sm"
+ onClick={() => lazy.activate()}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ lazy.activate();
+ }
+ }}
+ >
+ {/* <p> under rich-text-editor: same type metrics as the real
+ editor's empty paragraph — no height jump on swap. */}
+ <p className="text-muted-foreground">{placeholderText}</p>
+ </div>
+ )}
<div className="absolute bottom-0 left-0 right-24 min-w-0">
<CommentTriggerChips
agents={triggerPreview.agents}
@@ -213,7 +248,7 @@ function ReplyInput({
<FileUploadButton
size="sm"
multiple
- onSelect={(file) => editorRef.current?.uploadFile(file)}
+ onSelect={(file) => lazy.uploadOrQueue([file])}
/>
<SubmitButton
onClick={handleSubmit}
diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsx
index 381957e8e8..099ac5ff23 100644
--- a/packages/views/issues/components/swimlane-view.test.tsx
+++ b/packages/views/issues/components/swimlane-view.test.tsx
@@ -2,6 +2,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, act, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { SwimLaneView } from "./swimlane-view";
+import { IssueContextMenuProvider } from "../actions";
+import { ScrollRestorationProvider } from "../../platform";
import type { Issue } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
@@ -252,6 +254,21 @@ vi.mock("@dnd-kit/utilities", () => ({
CSS: { Transform: { toString: () => undefined } },
}));
+// Mock react-virtuoso: jsdom has no layout, so the real Virtuoso renders
+// nothing (and throws on its resize plumbing). Render every lane inline so the
+// virtualized swimlane exposes its lanes/cells/cards to the DOM, matching the
+// non-virtualized behavior these tests assert.
+vi.mock("react-virtuoso", () => ({
+ Virtuoso: ({ data, itemContent, components }: any) => (
+ <div data-testid="virtuoso-mock">
+ {(data ?? []).map((item: any, i: number) => (
+ <div key={i}>{itemContent(i, item)}</div>
+ ))}
+ {components?.Footer ? <components.Footer /> : null}
+ </div>
+ ),
+}));
+
const mockIssues: Issue[] = [
{
id: "parent-1",
@@ -334,7 +351,9 @@ function renderWithI18n(ui: React.ReactNode) {
return render(
<QueryClientProvider client={qc}>
<I18nProvider resources={TEST_RESOURCES} locale="en">
- {ui}
+ {/* Cards delegate their right-click menu to this surface-level
+ provider; IssueSurface mounts it in production. */}
+ <IssueContextMenuProvider>{ui}</IssueContextMenuProvider>
</I18nProvider>
</QueryClientProvider>,
);
@@ -1791,3 +1810,36 @@ describe("SwimLaneView", () => {
expect(screen.queryByText("Batch Sub-issue")).toBeNull();
});
});
+
+describe("SwimLaneView tab-session scroll restoration (MUL-4741)", () => {
+ it("registers the outer scroller for memento capture and restores the saved offset at attach", () => {
+ const adapter = {
+ get: (key: string) =>
+ key === "swimlane" ? { top: 240, height: 2000 } : undefined,
+ };
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+ const { container } = render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider resources={TEST_RESOURCES} locale="en">
+ <IssueContextMenuProvider>
+ <ScrollRestorationProvider adapter={adapter}>
+ <SwimLaneView issues={mockIssues} onMoveIssue={vi.fn()} />
+ </ScrollRestorationProvider>
+ </IssueContextMenuProvider>
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+
+ const scroller = container.querySelector<HTMLElement>(
+ '[data-tab-scroll-root="swimlane"]',
+ );
+ // Capture side: the coordinator scans [data-tab-scroll-root] — without
+ // the marker, leaving the tab never saves the swimlane offset.
+ expect(scroller).not.toBeNull();
+ // Restore side: the ref-attach assignment applies the saved offset
+ // before first paint (jsdom has no layout, so no clamping applies).
+ expect(scroller!.scrollTop).toBe(240);
+ });
+});
diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsx
index 87ffaca3f9..e25db44241 100644
--- a/packages/views/issues/components/swimlane-view.tsx
+++ b/packages/views/issues/components/swimlane-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback, useMemo, useEffect, useRef } from "react";
+import { memo, useState, useCallback, useMemo, useEffect, useRef } from "react";
import {
DndContext,
DragOverlay,
@@ -17,6 +17,7 @@ import {
} from "@dnd-kit/core";
import { SortableContext, useSortable, verticalListSortingStrategy, arrayMove } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
+import { Virtuoso } from "react-virtuoso";
import { ChevronRight, EyeOff, GripVertical, MoreHorizontal, Pencil, Plus } from "lucide-react";
import { useQuery, useQueries, useQueryClient } from "@tanstack/react-query";
import type {
@@ -45,7 +46,6 @@ import { sortIssues } from "../utils/sort";
import { ALL_STATUSES, STATUS_CONFIG } from "@multica/core/issues/config";
import { DraggableBoardCard, BoardCardContent } from "./board-card";
import { StatusIcon } from "./status-icon";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
import { Button } from "@multica/ui/components/ui/button";
import { StatusHeading } from "./status-heading";
import { HiddenColumnsPanel, HiddenColumnRow } from "./hidden-columns-panel";
@@ -53,6 +53,11 @@ import { InfiniteScrollSentinel } from "./infinite-scroll-sentinel";
import { AppLink } from "../../navigation";
import { ProjectIcon } from "../../projects/components/project-icon";
import { ActorAvatar } from "../../common/actor-avatar";
+import { VirtuosoSeed } from "../../common/virtuoso-seed";
+
+import { DeferredPopup } from "../../common/deferred-popup";
+import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";
+import { DeferredTooltip } from "../../common/deferred-tooltip";
import type { ChildProgress } from "./list-row";
import { useT } from "../../i18n";
import type { IssueActivityState } from "../surface/activity";
@@ -61,6 +66,12 @@ import type { IssueCreateDefaults } from "../surface/types";
const COLUMN_WIDTH = 280;
const COLUMN_GAP = 16;
+// A swimlane row (header + one row of card cells) is ~300px+ tall — a
+// viewport fits ~3. The generic VIRTUOSO_SEED_COUNT (30, sized for 36px list
+// rows) made every surface remount synchronously mount up to 30 full lanes
+// (each lane = statuses x cells x cards); 6 covers the viewport with margin.
+const SWIMLANE_LANE_SEED_COUNT = 6;
+
// Hoisted out of SwimLaneView so its reference is stable across renders —
// useQueries' combine option uses it through replaceEqualDeep, but keeping
// the function stable saves the per-render reference check.
@@ -441,7 +452,7 @@ function buildAssigneeLanes(
];
}
-export function SwimLaneView({
+function SwimLaneViewImpl({
issues,
unfilteredIssues,
activeFilters: activeFiltersProp,
@@ -811,6 +822,20 @@ export function SwimLaneView({
);
const [activeIssue, setActiveIssue] = useState<Issue | null>(null);
+ // The outer scroll box is the customScrollParent for the lane Virtuoso.
+ const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);
+ // Pull-based scroll restoration (MUL-4741): same wiring as board/list/
+ // issue-detail — ref-attach assigns the saved offset pre-paint, and the
+ // lane Virtuoso is born at it via initialScrollTop.
+ const restoredScrollTop = useRestoredScrollOffset("swimlane");
+ const restoreScrollRef = useRestoredScrollRef("swimlane");
+ const attachScroller = useCallback(
+ (el: HTMLDivElement | null) => {
+ setScrollEl(el);
+ restoreScrollRef(el);
+ },
+ [restoreScrollRef],
+ );
const isDraggingRef = useRef(false);
// Settle lock: held from drop until the move mutation settles, so a cache
// change that lands mid-flight (e.g. a membership refetch) does not rebuild
@@ -1127,6 +1152,63 @@ export function SwimLaneView({
[sortedStatuses.length, trackWidth],
);
+ // Lanes render in one Virtuoso so only on-screen lanes stay mounted. Pinned
+ // lanes keep their leading position; the SortableContext still wraps the
+ // whole set (its `items` are only the non-pinned lane ids, so reorder is
+ // unchanged), and per-cell droppables live on always-mounted lane cells.
+ const orderedLanes = useMemo(
+ () => [
+ ...laneGroups.filter((g) => g.isPinned),
+ ...laneGroups.filter((g) => !g.isPinned),
+ ],
+ [laneGroups],
+ );
+ const nonPinnedLaneIds = useMemo(
+ () =>
+ laneGroups
+ .filter((g) => !g.isPinned)
+ .map((g) => laneIdFor(swimlaneGrouping, g.rawId)),
+ [laneGroups, swimlaneGrouping],
+ );
+ // Per-status load-more sentinels ride Virtuoso's Footer so they sit at the
+ // true end of the lane list; pt-4 reproduces the previous gap-4.
+ const laneComponents = useMemo(
+ () => ({
+ Footer: () => (
+ <div className="pt-4">
+ <SwimLaneLoadMoreRow
+ sortedStatuses={sortedStatuses}
+ gridStyle={gridStyle}
+ myIssuesOpts={myIssuesOpts}
+ sort={sort}
+ />
+ </div>
+ ),
+ }),
+ [sortedStatuses, gridStyle, myIssuesOpts, sort],
+ );
+
+ const computeLaneKey = (_index: number, lane: LaneGroup) => lane.key;
+ const renderLane = (index: number, lane: LaneGroup) => (
+ <div className={index === 0 ? undefined : "pt-4"}>
+ <DraggableSwimLane
+ lane={lane}
+ grouping={swimlaneGrouping}
+ isCollapsed={collapsedLanes.has(lane.key)}
+ onToggleCollapse={() => toggleLane(lane.key)}
+ localCells={localCells}
+ sortedStatuses={sortedStatuses}
+ issueMap={issueMapRef.current}
+ childProgressMap={childProgressMap}
+ projectMap={projectMap}
+ gridStyle={gridStyle}
+ paths={paths}
+ projectId={projectId}
+ onCreateIssue={onCreateIssue}
+ />
+ </div>
+ );
+
return (
<DndContext
sensors={sensors}
@@ -1135,7 +1217,7 @@ export function SwimLaneView({
onDragOver={handleDragOver}
onDragEnd={handleDragEnd}
>
- <div className="flex flex-1 min-h-0 gap-4 overflow-auto p-4">
+ <div ref={attachScroller} data-tab-scroll-root="swimlane" className="flex flex-1 min-h-0 gap-4 overflow-auto p-4">
<div className="flex shrink-0 flex-col" style={{ width: `${trackWidth}px` }}>
{/* Sticky status header row — visually matches the top of a BoardColumn */}
<div className="sticky top-0 z-10 mb-2 bg-background/95 pb-2 backdrop-blur supports-[backdrop-filter]:bg-background/75">
@@ -1149,96 +1231,87 @@ export function SwimLaneView({
className={`flex items-center justify-between rounded-xl ${cfg?.columnBg ?? "bg-muted/40"} px-3 py-2`}
>
<StatusHeading status={status} count={total} />
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- aria-label={t(($) => $.board.hide_column)}
- className="rounded-full text-muted-foreground"
- >
- <MoreHorizontal className="size-3.5" />
- </Button>
- }
- />
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() => viewStoreApi.getState().hideStatus(status)}
+ {/* Lazy-mounted like the board's column menu — see
+ DeferredPopup. */}
+ <DeferredPopup
+ ariaHasPopup="menu"
+ triggerRender={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.board.hide_column)}
+ className="rounded-full text-muted-foreground"
>
- <EyeOff className="size-3.5" />
- {t(($) => $.board.hide_column)}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ <MoreHorizontal className="size-3.5" />
+ </Button>
+ }
+ >
+ {(open, onOpenChange) => (
+ <DropdownMenu open={open} onOpenChange={onOpenChange}>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.board.hide_column)}
+ className="rounded-full text-muted-foreground"
+ >
+ <MoreHorizontal className="size-3.5" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => viewStoreApi.getState().hideStatus(status)}
+ >
+ <EyeOff className="size-3.5" />
+ {t(($) => $.board.hide_column)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </DeferredPopup>
</div>
);
})}
</div>
</div>
- {/* Lane rows. Pinned lanes (the no-X bucket, and parent-grouping's
- orphan fallback) sit at the top and are non-draggable; the rest
- are wrapped in a SortableContext so users can reorder lanes by
- dragging the grip handle. */}
- <div className="flex flex-col gap-4">
- {laneGroups
- .filter((g) => g.isPinned)
- .map((lane) => (
- <DraggableSwimLane
- key={lane.key}
- lane={lane}
- grouping={swimlaneGrouping}
- isCollapsed={collapsedLanes.has(lane.key)}
- onToggleCollapse={() => toggleLane(lane.key)}
- localCells={localCells}
- sortedStatuses={sortedStatuses}
- issueMap={issueMapRef.current}
- childProgressMap={childProgressMap}
- projectMap={projectMap}
- gridStyle={gridStyle}
- paths={paths}
- projectId={projectId}
- onCreateIssue={onCreateIssue}
- />
- ))}
- <SortableContext
- items={laneGroups
- .filter((g) => !g.isPinned)
- .map((g) => laneIdFor(swimlaneGrouping, g.rawId))}
- strategy={verticalListSortingStrategy}
- >
- {laneGroups
- .filter((g) => !g.isPinned)
- .map((lane) => (
- <DraggableSwimLane
- key={lane.key}
- lane={lane}
- grouping={swimlaneGrouping}
- isCollapsed={collapsedLanes.has(lane.key)}
- onToggleCollapse={() => toggleLane(lane.key)}
- localCells={localCells}
- sortedStatuses={sortedStatuses}
- issueMap={issueMapRef.current}
- childProgressMap={childProgressMap}
- projectMap={projectMap}
- gridStyle={gridStyle}
- paths={paths}
- projectId={projectId}
- onCreateIssue={onCreateIssue}
- />
- ))}
- </SortableContext>
-
- {/* Per-status load-more sentinels — same bucketed cache as Board. */}
- <SwimLaneLoadMoreRow
- sortedStatuses={sortedStatuses}
- gridStyle={gridStyle}
- myIssuesOpts={myIssuesOpts}
- sort={sort}
- />
- </div>
+ {/* Lane rows, virtualized. Pinned lanes (the no-X bucket, and
+ parent-grouping's orphan fallback) keep their leading position and
+ stay non-draggable; the SortableContext still lets the rest reorder
+ by dragging the grip handle (its `items` are only the non-pinned
+ lane ids). Only on-screen lanes stay mounted. */}
+ <SortableContext
+ items={nonPinnedLaneIds}
+ strategy={verticalListSortingStrategy}
+ >
+ {/* Seed a bounded slice of real lanes while the scroll ref hasn't
+ settled after a remount, so the lane area never paints blank; once
+ it's set, mount the Virtuoso with a matching `initialItemCount` to
+ survive the measurement frame (MUL-4750). */}
+ {scrollEl ? (
+ <Virtuoso
+ customScrollParent={scrollEl}
+ data={orderedLanes}
+ computeItemKey={computeLaneKey}
+ initialScrollTop={restoredScrollTop}
+ initialItemCount={Math.min(orderedLanes.length, SWIMLANE_LANE_SEED_COUNT)}
+ increaseViewportBy={{ top: 600, bottom: 600 }}
+ components={laneComponents}
+ itemContent={renderLane}
+ />
+ ) : (
+ <VirtuosoSeed
+ data={orderedLanes}
+ itemContent={renderLane}
+ computeItemKey={computeLaneKey}
+ count={SWIMLANE_LANE_SEED_COUNT}
+ />
+ )}
+ </SortableContext>
</div>
{hiddenStatuses.length > 0 && (
@@ -1375,20 +1448,18 @@ function DraggableSwimLane({
</span>
</button>
{lane.parentIssue && (
- <Tooltip>
- <TooltipTrigger
- render={
- <AppLink
- href={paths.issueDetail(lane.parentIssue.id)}
- aria-label={t(($) => $.swimlane.open_parent)}
- className="inline-flex size-5 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
- >
- <Pencil className="size-3" />
- </AppLink>
- }
- />
- <TooltipContent>{t(($) => $.swimlane.open_parent)}</TooltipContent>
- </Tooltip>
+ <DeferredTooltip
+ content={t(($) => $.swimlane.open_parent)}
+ trigger={
+ <AppLink
+ href={paths.issueDetail(lane.parentIssue.id)}
+ aria-label={t(($) => $.swimlane.open_parent)}
+ className="inline-flex size-5 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
+ >
+ <Pencil className="size-3" />
+ </AppLink>
+ }
+ />
)}
</div>
{/* Cells row — each cell mirrors a BoardColumn body */}
@@ -1502,24 +1573,25 @@ function SwimLaneCell({
</p>
)}
</div>
+ {/* One of these per lane×status cell (~170 on a real swimlane) —
+ eagerly mounted tooltip roots here were the single largest slice
+ of swimlane mount cost. */}
{!readOnly && onCreateIssue && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- aria-label={t(($) => $.board.add_issue_tooltip)}
- className="mt-1 w-full rounded-md text-muted-foreground hover:text-foreground"
- onClick={handleAdd}
- >
- <Plus className="size-3.5" />
- </Button>
- }
- />
- <TooltipContent>{t(($) => $.board.add_issue_tooltip)}</TooltipContent>
- </Tooltip>
+ <DeferredTooltip
+ content={t(($) => $.board.add_issue_tooltip)}
+ trigger={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.board.add_issue_tooltip)}
+ className="mt-1 w-full rounded-md text-muted-foreground hover:text-foreground"
+ onClick={handleAdd}
+ >
+ <Plus className="size-3.5" />
+ </Button>
+ }
+ />
)}
</div>
);
@@ -1584,3 +1656,11 @@ function SwimLaneLoadMoreCell({
if (!hasMore) return <div />;
return <InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />;
}
+
+/**
+ * Memoized: the surface controller re-renders on loading-flag flips (e.g. a
+ * query enabling when the view changes) — without memo every such flip
+ * re-rendered this entire view tree (hundreds of ms). All props are
+ * referentially stable useMemo/useCallback outputs from the controller.
+ */
+export const SwimLaneView = memo(SwimLaneViewImpl);
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index 66ca188788..8d9af9c00c 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -23,6 +23,21 @@ vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => mockWsId.current,
}));
+// The list/board virtualize their rows via react-virtuoso; jsdom has no layout
+// so the real Virtuoso renders nothing (and throws on its resize plumbing).
+// Render items inline so these surface-level loading-semantics assertions still
+// see the issues the virtualized list would show.
+vi.mock("react-virtuoso", () => ({
+ Virtuoso: ({ data, itemContent, components }: any) => (
+ <div data-testid="virtuoso-mock">
+ {(data ?? []).map((item: any, i: number) => (
+ <div key={i}>{itemContent(i, item)}</div>
+ ))}
+ {components?.Footer ? <components.Footer /> : null}
+ </div>
+ ),
+}));
+
const mockAuthUser = { id: "user-1", email: "[email protected]", name: "Test User" };
vi.mock("@multica/core/auth", () => ({
useAuthStore: Object.assign(
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index cf73c98702..c8d5a01b50 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useMemo, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, type ReactNode } from "react";
import { ListTodo, Plus } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
@@ -17,6 +17,7 @@ import { IssuesHeader } from "../components/issues-header";
import { ListView } from "../components/list-view";
import { SwimLaneView } from "../components/swimlane-view";
import { useT } from "../../i18n";
+import { IssueContextMenuProvider } from "../actions";
import { IssueSurfaceActionsProvider } from "./actions-context";
import { IssueSurfaceSelectionProvider } from "./selection-context";
import type { IssueCreateDefaults, IssueSurfaceProps } from "./types";
@@ -60,6 +61,19 @@ export function IssueSurface({
[resolvedSurfaceKey],
);
+ // Every change of this key tears down and remounts the ENTIRE surface
+ // (providers, DnD, all columns/cards) — by design for data-window changes,
+ // but expensive enough that unexpected flips are performance bugs. Dev-only
+ // breadcrumb so a Performance trace showing double mounts can be tied to
+ // the exact key transition.
+ const contentKey = `${wsId}:${issueScopeKey(scope)}`;
+ useEffect(() => {
+ if (process.env.NODE_ENV !== "production") {
+ // eslint-disable-next-line no-console
+ console.warn(`[issue-surface] mount ${contentKey}`);
+ }
+ }, [contentKey]);
+
return (
<ViewStoreProvider store={store}>
{/* Remount on data-window change: the list queries keep the previous
@@ -74,7 +88,7 @@ export function IssueSurface({
workspaces share the same scope key (e.g. "workspace:all"). Keyed
by data identity, not surfaceKey (view-preference identity). */}
<IssueSurfaceContent
- key={`${wsId}:${issueScopeKey(scope)}`}
+ key={contentKey}
scope={scope}
modes={modes}
createDefaults={createDefaults}
@@ -132,6 +146,15 @@ function IssueSurfaceContent({
},
[controller],
);
+ // Stable reference for BoardView's issues: the inline flatMap allocated a
+ // fresh array every render, defeating BoardView's memo.
+ const boardIssues = useMemo(
+ () =>
+ controller.assigneeGroups
+ ? controller.assigneeGroups.flatMap((group) => group.issues)
+ : issues,
+ [controller.assigneeGroups, issues],
+ );
const shouldShowClientEmpty =
!!clientFilter &&
issues.length === 0 &&
@@ -142,6 +165,11 @@ function IssueSurfaceContent({
return (
<IssueSurfaceActionsProvider actions={controller.actions}>
+ {/* One shared right-click menu for every card/row this surface renders
+ — see IssueContextMenuProvider. Inside the actions provider so the
+ singleton's useIssueActions routes updates through surface
+ actions. */}
+ <IssueContextMenuProvider>
<IssueSurfaceSelectionProvider selection={controller.selection}>
{renderHeader ? (
renderHeader(renderContext)
@@ -181,11 +209,7 @@ function IssueSurfaceContent({
<div className={cn("flex flex-col flex-1 min-h-0", contentClassName)}>
{controller.viewMode === "board" && (
<BoardView
- issues={
- controller.assigneeGroups
- ? controller.assigneeGroups.flatMap((group) => group.issues)
- : issues
- }
+ issues={boardIssues}
assigneeGroups={controller.assigneeGroups}
assigneeGroupQueryKey={controller.assigneeGroupQueryKey}
assigneeGroupFilter={controller.assigneeGroupFilter}
@@ -240,6 +264,7 @@ function IssueSurfaceContent({
)}
{shouldShowBatchToolbar && <BatchActionToolbar issues={issues} />}
</IssueSurfaceSelectionProvider>
+ </IssueContextMenuProvider>
</IssueSurfaceActionsProvider>
);
}
diff --git a/packages/views/issues/surface/selection-context.tsx b/packages/views/issues/surface/selection-context.tsx
index 69f5f682a1..2090bf44f5 100644
--- a/packages/views/issues/surface/selection-context.tsx
+++ b/packages/views/issues/surface/selection-context.tsx
@@ -29,7 +29,10 @@ export function useCreateIssueSurfaceSelection(
const [selectedIds, setSelectedIds] = useState(() => new Set<string>());
useEffect(() => {
- setSelectedIds(new Set());
+ // Functional bail: on mount (and on resetKey changes where nothing was
+ // selected) the selection is already empty — swapping in a NEW empty Set
+ // here re-rendered the entire surface once per mount for nothing.
+ setSelectedIds((current) => (current.size === 0 ? current : new Set()));
}, [resetKey]);
const toggle = useCallback((id: string) => {
diff --git a/packages/views/layout/sidebar-resize.test.tsx b/packages/views/layout/sidebar-resize.test.tsx
new file mode 100644
index 0000000000..06796b4f6a
--- /dev/null
+++ b/packages/views/layout/sidebar-resize.test.tsx
@@ -0,0 +1,148 @@
+import { fireEvent } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ Sidebar,
+ SidebarProvider,
+ SidebarRail,
+ useSidebar,
+} from "@multica/ui/components/ui/sidebar";
+import { renderWithI18n } from "../test/i18n";
+
+describe("left sidebar resizing", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ document.documentElement.removeAttribute("data-sidebar-resizing");
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it("previews width directly and commits only when the pointer is released", () => {
+ const stableConsumerRender = vi.fn();
+ const setItem = vi.spyOn(Storage.prototype, "setItem");
+
+ function StableSidebarConsumer() {
+ useSidebar();
+ stableConsumerRender();
+ return null;
+ }
+
+ const { container } = renderWithI18n(
+ <SidebarProvider>
+ <Sidebar>
+ <StableSidebarConsumer />
+ <SidebarRail />
+ </Sidebar>
+ </SidebarProvider>,
+ );
+
+ const wrapper = container.querySelector<HTMLElement>("[data-slot='sidebar-wrapper']")!;
+ const sidebarContainer = container.querySelector<HTMLElement>("[data-slot='sidebar-container']")!;
+ const sidebarGap = container.querySelector<HTMLElement>("[data-slot='sidebar-gap']")!;
+ const sidebar = container.querySelector<HTMLElement>("[data-slot='sidebar']")!;
+ const rail = container.querySelector<HTMLButtonElement>("[data-slot='sidebar-rail']")!;
+ const setPointerCapture = vi.fn();
+ const releasePointerCapture = vi.fn();
+ rail.setPointerCapture = setPointerCapture;
+ rail.hasPointerCapture = vi.fn(() => true);
+ rail.releasePointerCapture = releasePointerCapture;
+
+ vi.spyOn(sidebarContainer, "getBoundingClientRect").mockReturnValue({
+ bottom: 0,
+ height: 0,
+ left: 0,
+ right: 256,
+ top: 0,
+ width: 256,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ });
+
+ fireEvent.pointerDown(rail, {
+ button: 0,
+ clientX: 256,
+ isPrimary: true,
+ pointerId: 7,
+ });
+
+ expect(setPointerCapture).toHaveBeenCalledWith(7);
+ expect(rail).toHaveClass("cursor-ew-resize");
+ expect(wrapper).toHaveAttribute("data-sidebar-resizing", "true");
+ expect(document.documentElement).toHaveAttribute("data-sidebar-resizing", "true");
+
+ fireEvent.pointerMove(document, { buttons: 1, clientX: 280, pointerId: 7 });
+ fireEvent.pointerMove(document, { buttons: 1, clientX: 300, pointerId: 7 });
+
+ expect(sidebarGap.style.width).toBe("300px");
+ expect(sidebarContainer.style.width).toBe("300px");
+ expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("256px");
+ expect(setItem).not.toHaveBeenCalled();
+ expect(stableConsumerRender).toHaveBeenCalledTimes(1);
+
+ fireEvent.pointerUp(document, { pointerId: 7 });
+
+ expect(sidebarGap.style.width).toBe("");
+ expect(sidebarContainer.style.width).toBe("");
+ expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("300px");
+ expect(setItem).toHaveBeenCalledTimes(1);
+ expect(setItem).toHaveBeenCalledWith("sidebar_width", "300");
+ expect(releasePointerCapture).toHaveBeenCalledWith(7);
+ expect(wrapper).not.toHaveAttribute("data-sidebar-resizing");
+ expect(document.documentElement).not.toHaveAttribute("data-sidebar-resizing");
+ expect(stableConsumerRender).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(rail);
+ expect(sidebar).toHaveAttribute("data-state", "expanded");
+ });
+
+ it("restores the committed width and cursor state when pointer capture is cancelled", () => {
+ const setItem = vi.spyOn(Storage.prototype, "setItem");
+ const { container } = renderWithI18n(
+ <SidebarProvider>
+ <Sidebar>
+ <SidebarRail />
+ </Sidebar>
+ </SidebarProvider>,
+ );
+
+ const wrapper = container.querySelector<HTMLElement>("[data-slot='sidebar-wrapper']")!;
+ const sidebarContainer = container.querySelector<HTMLElement>("[data-slot='sidebar-container']")!;
+ const sidebarGap = container.querySelector<HTMLElement>("[data-slot='sidebar-gap']")!;
+ const rail = container.querySelector<HTMLButtonElement>("[data-slot='sidebar-rail']")!;
+ rail.setPointerCapture = vi.fn();
+ rail.hasPointerCapture = vi.fn(() => true);
+ rail.releasePointerCapture = vi.fn();
+
+ vi.spyOn(sidebarContainer, "getBoundingClientRect").mockReturnValue({
+ bottom: 0,
+ height: 0,
+ left: 0,
+ right: 256,
+ top: 0,
+ width: 256,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ });
+
+ fireEvent.pointerDown(rail, {
+ button: 0,
+ clientX: 256,
+ isPrimary: true,
+ pointerId: 8,
+ });
+ fireEvent.pointerMove(document, { buttons: 1, clientX: 320, pointerId: 8 });
+ fireEvent.pointerCancel(document, { pointerId: 8 });
+
+ expect(sidebarGap.style.width).toBe("");
+ expect(sidebarContainer.style.width).toBe("");
+ expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("256px");
+ expect(setItem).not.toHaveBeenCalled();
+ expect(wrapper).not.toHaveAttribute("data-sidebar-resizing");
+ expect(document.documentElement).not.toHaveAttribute("data-sidebar-resizing");
+ });
+});
diff --git a/packages/views/platform/index.ts b/packages/views/platform/index.ts
index c902cfa7ec..1e22cc6001 100644
--- a/packages/views/platform/index.ts
+++ b/packages/views/platform/index.ts
@@ -13,3 +13,9 @@ export {
useLocalDaemonStatus,
type LocalDaemonStatus,
} from "./use-local-daemon-status";
+export {
+ ScrollRestorationProvider,
+ useRestoredScrollOffset,
+ useRestoredScrollRef,
+ type ScrollRestorationAdapter,
+} from "./scroll-restoration";
diff --git a/packages/views/platform/scroll-restoration.tsx b/packages/views/platform/scroll-restoration.tsx
new file mode 100644
index 0000000000..d15eb45c01
--- /dev/null
+++ b/packages/views/platform/scroll-restoration.tsx
@@ -0,0 +1,80 @@
+"use client";
+
+import { createContext, useCallback, useContext, type ReactNode } from "react";
+
+/**
+ * Pull-based scroll restoration channel (MUL-4741 state-restoration
+ * protocol).
+ *
+ * The platform (desktop tab host) captures scroll offsets when a view is
+ * about to go away and serves them back through this context when the view
+ * mounts again. Restoration is an INPUT to the view, not a post-hoc DOM
+ * mutation from outside:
+ *
+ * - virtualized lists feed the offset into `initialScrollTop`, so the
+ * list's first render already materializes the rows around the saved
+ * offset — no "start at top, then jump" and no fighting the list's own
+ * height model;
+ * - plain scroll containers assign the offset in their ref callback at
+ * attach time (pre-paint).
+ *
+ * Container keys mirror the `data-tab-scroll-root` attribute values the
+ * capture side scans for; the platform scopes them per route + tab. On web
+ * (no provider) every lookup returns undefined and views behave as before.
+ */
+export interface ScrollRestorationAdapter {
+ /**
+ * The saved offset for a container key on the current route, or undefined
+ * when there is nothing to restore.
+ */
+ get(containerKey: string): { top: number; height: number } | undefined;
+}
+
+const ScrollRestorationContext = createContext<ScrollRestorationAdapter | null>(
+ null,
+);
+
+export function ScrollRestorationProvider({
+ adapter,
+ children,
+}: {
+ adapter: ScrollRestorationAdapter;
+ children: ReactNode;
+}) {
+ return (
+ <ScrollRestorationContext.Provider value={adapter}>
+ {children}
+ </ScrollRestorationContext.Provider>
+ );
+}
+
+/**
+ * The saved scroll offset for a container key on the current route, or
+ * undefined. Read it once at mount (e.g. into a Virtuoso `initialScrollTop`)
+ * — it reflects the state captured when this route was last left.
+ */
+export function useRestoredScrollOffset(containerKey: string): number | undefined {
+ const adapter = useContext(ScrollRestorationContext);
+ return adapter?.get(containerKey)?.top;
+}
+
+/**
+ * Ref callback for PLAIN (non-virtualized) scroll containers: assigns the
+ * saved offset when the element attaches, which happens during commit —
+ * before paint — so the first visible frame is already at the restored
+ * position. Compose it with other refs via a merged callback.
+ */
+export function useRestoredScrollRef(
+ containerKey: string,
+): (el: HTMLElement | null) => void {
+ const adapter = useContext(ScrollRestorationContext);
+ return useCallback(
+ (el: HTMLElement | null) => {
+ if (!el) return;
+ const saved = adapter?.get(containerKey);
+ if (!saved || saved.top <= 0) return;
+ el.scrollTop = saved.top;
+ },
+ [adapter, containerKey],
+ );
+}
diff --git a/packages/views/projects/components/project-due-date-picker.tsx b/packages/views/projects/components/project-due-date-picker.tsx
index 5147ecd744..1bdab6a52b 100644
--- a/packages/views/projects/components/project-due-date-picker.tsx
+++ b/packages/views/projects/components/project-due-date-picker.tsx
@@ -21,7 +21,7 @@ export function ProjectDueDatePicker({
dueDate: string | null;
onUpdate: (updates: Partial<UpdateProjectRequest>) => void;
/** Custom trigger element (e.g. a pill button in the create modal). */
- triggerRender?: React.ReactElement;
+ triggerRender?: React.ReactElement<Record<string, unknown>>;
align?: "start" | "center" | "end";
/** Controlled open state — lets a ⋯ overflow menu reveal + open the pill. */
open?: boolean;
diff --git a/packages/views/projects/components/project-start-date-picker.tsx b/packages/views/projects/components/project-start-date-picker.tsx
index 63c188d841..321c43c84f 100644
--- a/packages/views/projects/components/project-start-date-picker.tsx
+++ b/packages/views/projects/components/project-start-date-picker.tsx
@@ -23,7 +23,7 @@ export function ProjectStartDatePicker({
startDate: string | null;
onUpdate: (updates: Partial<UpdateProjectRequest>) => void;
/** Custom trigger element (e.g. a pill button in the create modal). */
- triggerRender?: React.ReactElement;
+ triggerRender?: React.ReactElement<Record<string, unknown>>;
align?: "start" | "center" | "end";
/** Controlled open state — lets a ⋯ overflow menu reveal + open the pill. */
open?: boolean;