Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(desktop): per-tab memory router with Activity-based state preservation
Naiyuan Qinga4383e051f43
diff --git a/apps/desktop/src/renderer/src/components/tab-content.tsx b/apps/desktop/src/renderer/src/components/tab-content.tsxnew file mode 100644index 0000000000..ff644644a3--- /dev/null+++ b/apps/desktop/src/renderer/src/components/tab-content.tsx@@ -0,0 +1,43 @@+import { Activity, useEffect } from "react";+import { RouterProvider } from "react-router-dom";+import { useTabStore } from "@/stores/tab-store";+import { TabNavigationProvider } from "@/platform/navigation";+import { useTabRouterSync } from "@/hooks/use-tab-router-sync";++/** Inner wrapper rendered inside each tab's RouterProvider. */+function TabRouterInner({ tabId }: { tabId: string }) {+ const tab = useTabStore((s) => s.tabs.find((t) => t.id === tabId));+ useTabRouterSync(tabId, tab!.router);+ return null;+}++/**+ * Renders all tabs using Activity for state preservation.+ * Only the active tab is visible; hidden tabs keep their DOM and React state.+ */+export function TabContent() {+ const tabs = useTabStore((s) => s.tabs);+ const activeTabId = useTabStore((s) => s.activeTabId);++ // Sync document.title when switching tabs+ useEffect(() => {+ const tab = tabs.find((t) => t.id === activeTabId);+ if (tab) document.title = tab.title;+ }, [activeTabId, tabs]);++ return (+ <>+ {tabs.map((tab) => (+ <Activity+ key={tab.id}+ mode={tab.id === activeTabId ? "visible" : "hidden"}+ >+ <TabNavigationProvider router={tab.router}>+ <RouterProvider router={tab.router} />+ <TabRouterInner tabId={tab.id} />+ </TabNavigationProvider>+ </Activity>+ ))}+ </>+ );+}diff --git a/apps/desktop/src/renderer/src/hooks/use-history-stack.ts b/apps/desktop/src/renderer/src/hooks/use-history-stack.tsdeleted file mode 100644index 386b6032d7..0000000000--- a/apps/desktop/src/renderer/src/hooks/use-history-stack.ts+++ /dev/null@@ -1,57 +0,0 @@-import { useState, useEffect, useRef, useCallback } from "react";-import { useLocation } from "react-router-dom";--export function useNavigationHistory() {- const [canGoBack, setCanGoBack] = useState(false);- const [canGoForward, setCanGoForward] = useState(false);- const location = useLocation();-- const seqRef = useRef(1);- const maxSeqRef = useRef(1);- const isNavRef = useRef(false);-- // Seed initial entry + listen for popstate (browser back/forward)- useEffect(() => {- window.history.replaceState({ seq: 1 }, "");-- const handlePopState = (event: PopStateEvent) => {- const seq = (event.state?.seq as number) ?? 0;- seqRef.current = seq;- setCanGoBack(seq > 1);- setCanGoForward(seq < maxSeqRef.current);- };-- window.addEventListener("popstate", handlePopState);- return () => window.removeEventListener("popstate", handlePopState);- }, []);-- // Stamp seq on each new navigation- useEffect(() => {- // Skip if this was our own goBack/goForward call- if (isNavRef.current) {- isNavRef.current = false;- return;- }-- const nextSeq = seqRef.current + 1;- seqRef.current = nextSeq;- maxSeqRef.current = nextSeq;- window.history.replaceState({ seq: nextSeq }, "");- setCanGoBack(nextSeq > 1);- setCanGoForward(false);- }, [location]);-- const goBack = useCallback(() => {- if (!canGoBack) return;- isNavRef.current = true;- window.history.back();- }, [canGoBack]);-- const goForward = useCallback(() => {- if (!canGoForward) return;- isNavRef.current = true;- window.history.forward();- }, [canGoForward]);-- return { canGoBack, canGoForward, goBack, goForward };-}diff --git a/apps/desktop/src/renderer/src/hooks/use-tab-history.ts b/apps/desktop/src/renderer/src/hooks/use-tab-history.tsnew file mode 100644index 0000000000..ecdf06261c--- /dev/null+++ b/apps/desktop/src/renderer/src/hooks/use-tab-history.ts@@ -0,0 +1,40 @@+import { useCallback } from "react";+import type { DataRouter } from "react-router-dom";+import { useTabStore } 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 tab's history state.+ * Replaces the old global useNavigationHistory() hook.+ */+export function useTabHistory() {+ // Return the actual tab object from the store — stable reference.+ // Do NOT create a new object in the selector (causes infinite re-renders).+ const activeTab = useTabStore((s) =>+ s.tabs.find((t) => t.id === s.activeTabId),+ );++ const canGoBack = (activeTab?.historyIndex ?? 0) > 0;+ const canGoForward =+ (activeTab?.historyIndex ?? 0) < (activeTab?.historyLength ?? 1) - 1;++ const goBack = useCallback(() => {+ if (!activeTab || activeTab.historyIndex <= 0) return;+ popDirectionHints.set(activeTab.router, "back");+ activeTab.router.navigate(-1);+ }, [activeTab]);++ const goForward = useCallback(() => {+ if (!activeTab || activeTab.historyIndex >= activeTab.historyLength - 1)+ return;+ popDirectionHints.set(activeTab.router, "forward");+ activeTab.router.navigate(1);+ }, [activeTab]);++ 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.tsnew file mode 100644index 0000000000..0f4bfbd0d3--- /dev/null+++ b/apps/desktop/src/renderer/src/hooks/use-tab-router-sync.ts@@ -0,0 +1,49 @@+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/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex 1f5ea32ee9..7ebeb862f4 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -1,33 +1,116 @@-import { useNavigate, useLocation } from "react-router-dom";+import { useEffect, useMemo, useState } from "react";+import type { DataRouter } from "react-router-dom";import {NavigationProvider,type NavigationAdapter,} from "@multica/views/navigation";+import { useAuthStore } from "@multica/core/auth";import { useTabStore, resolveRouteIcon } from "@/stores/tab-store";+/**+ * Root-level navigation provider for components outside the per-tab RouterProviders+ * (sidebar, search dialog, modals, etc.).+ *+ * Reads from the active tab's memory router via router.subscribe().+ * Does NOT use any react-router hooks — it's above all RouterProviders.+ */export function DesktopNavigationProvider({children,}: {children: React.ReactNode;}) {- const navigate = useNavigate();- const location = useLocation();-- const adapter: NavigationAdapter = {- push: (path) => navigate(path),- replace: (path) => navigate(path, { replace: true }),- back: () => navigate(-1),- pathname: location.pathname,- searchParams: new URLSearchParams(location.search),- openInNewTab: (path, title?) => {- const icon = resolveRouteIcon(path);- const store = useTabStore.getState();- const tabId = store.openTab(path, title ?? path, icon);- store.setActiveTab(tabId);- navigate(path);- },- getShareableUrl: (path) => `https://www.multica.ai${path}`,- };+ const activeTab = useTabStore((s) => s.tabs.find((t) => t.id === s.activeTabId));+ const [pathname, setPathname] = useState(activeTab?.path ?? "/issues");++ // Subscribe to the active tab's router for pathname updates+ useEffect(() => {+ if (!activeTab) return;+ setPathname(activeTab.router.state.location.pathname);+ return activeTab.router.subscribe((state) => {+ setPathname(state.location.pathname);+ });+ }, [activeTab?.id]); // eslint-disable-line react-hooks/exhaustive-deps++ const adapter: NavigationAdapter = useMemo(+ () => ({+ push: (path: string) => {+ if (path === "/login") {+ // DashboardGuard token expired — force back to login screen+ useAuthStore.getState().logout();+ return;+ }+ const tab = useTabStore.getState().tabs.find(+ (t) => t.id === useTabStore.getState().activeTabId,+ );+ tab?.router.navigate(path);+ },+ replace: (path: string) => {+ const tab = useTabStore.getState().tabs.find(+ (t) => t.id === useTabStore.getState().activeTabId,+ );+ tab?.router.navigate(path, { replace: true });+ },+ back: () => {+ const tab = useTabStore.getState().tabs.find(+ (t) => t.id === useTabStore.getState().activeTabId,+ );+ tab?.router.navigate(-1);+ },+ pathname,+ searchParams: new URLSearchParams(),+ openInNewTab: (path: string, title?: string) => {+ const icon = resolveRouteIcon(path);+ const store = useTabStore.getState();+ const tabId = store.openTab(path, title ?? path, icon);+ store.setActiveTab(tabId);+ },+ getShareableUrl: (path: string) => `https://www.multica.ai${path}`,+ }),+ [pathname],+ );++ return <NavigationProvider value={adapter}>{children}</NavigationProvider>;+}++/**+ * 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 [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) => router.navigate(path),+ replace: (path: string) => router.navigate(path, { replace: true }),+ back: () => router.navigate(-1),+ pathname: location.pathname,+ searchParams: new URLSearchParams(location.search),+ openInNewTab: (path: string, title?: string) => {+ const icon = resolveRouteIcon(path);+ const store = useTabStore.getState();+ const newTabId = store.openTab(path, title ?? path, icon);+ store.setActiveTab(newTabId);+ },+ getShareableUrl: (path: string) => `https://www.multica.ai${path}`,+ }),+ [router, location],+ );return <NavigationProvider value={adapter}>{children}</NavigationProvider>;}diff --git a/apps/desktop/src/renderer/src/router.tsx b/apps/desktop/src/renderer/src/router.tsxdeleted file mode 100644index e5ae084eaf..0000000000--- a/apps/desktop/src/renderer/src/router.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { createHashRouter, Navigate, Outlet, useMatches } from "react-router-dom";-import { useEffect } from "react";-import { DesktopLayout } from "./components/desktop-layout";-import { DesktopLoginPage } from "./pages/login";-import { IssueDetailPage } from "./pages/issue-detail-page";-// Extracted pages from @multica/views-import { IssuesPage } from "@multica/views/issues/components";-import { MyIssuesPage } from "@multica/views/my-issues";-import { RuntimesPage } from "@multica/views/runtimes";-import { SkillsPage } from "@multica/views/skills";-import { AgentsPage } from "@multica/views/agents";-import { InboxPage } from "@multica/views/inbox";-import { SettingsPage } from "@multica/views/settings";--/**- * Sets document.title from the deepest matched route's handle.title.- * The tab system observes document.title via MutationObserver.- * Pages with dynamic titles (e.g. issue detail) override by setting- * document.title directly via useDocumentTitle().- */-function TitleSync() {- const matches = useMatches();- const title = [...matches]- .reverse()- .find((m) => (m.handle as { title?: string })?.title)- ?.handle as { title?: string } | undefined;-- useEffect(() => {- if (title?.title) document.title = title.title;- }, [title?.title]);-- return null;-}--/** Wrapper that renders route children + TitleSync */-function PageShell() {- return (- <>- <TitleSync />- <Outlet />- </>- );-}--export const router = createHashRouter([- {- path: "/",- element: <DesktopLayout />,- children: [- {- element: <PageShell />,- children: [- { index: true, element: <Navigate to="/issues" replace /> },- { path: "issues", element: <IssuesPage />, handle: { title: "Issues" } },- { path: "issues/:id", element: <IssueDetailPage />, handle: { title: "Issue" } },- { path: "my-issues", element: <MyIssuesPage />, handle: { title: "My Issues" } },- { path: "runtimes", element: <RuntimesPage />, handle: { title: "Runtimes" } },- { path: "skills", element: <SkillsPage />, handle: { title: "Skills" } },- { path: "agents", element: <AgentsPage />, handle: { title: "Agents" } },- { path: "inbox", element: <InboxPage />, handle: { title: "Inbox" } },- { path: "settings", element: <SettingsPage />, handle: { title: "Settings" } },- ],- },- ],- },- { path: "/login", element: <DesktopLoginPage /> },-]);diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsxnew file mode 100644index 0000000000..32a25b1539--- /dev/null+++ b/apps/desktop/src/renderer/src/routes.tsx@@ -0,0 +1,99 @@+import { useEffect } from "react";+import {+ createMemoryRouter,+ Navigate,+ 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";+import { IssuesPage } from "@multica/views/issues/components";+import { ProjectsPage } from "@multica/views/projects/components";+import { MyIssuesPage } from "@multica/views/my-issues";+import { RuntimesPage } from "@multica/views/runtimes";+import { SkillsPage } from "@multica/views/skills";+import { AgentsPage } from "@multica/views/agents";+import { InboxPage } from "@multica/views/inbox";+import { SettingsPage } from "@multica/views/settings";++/**+ * Sets document.title from the deepest matched route's handle.title.+ * The tab system observes document.title via MutationObserver.+ * Pages with dynamic titles (e.g. issue detail) override by setting+ * document.title directly via useDocumentTitle().+ */+function TitleSync() {+ const matches = useMatches();+ const title = [...matches]+ .reverse()+ .find((m) => (m.handle as { title?: string })?.title)+ ?.handle as { title?: string } | undefined;++ useEffect(() => {+ if (title?.title) document.title = title.title;+ }, [title?.title]);++ return null;+}++/** Wrapper that renders route children + TitleSync */+function PageShell() {+ return (+ <>+ <TitleSync />+ <Outlet />+ </>+ );+}++/** Route definitions shared by all tabs (no layout wrapper). */+export const appRoutes: RouteObject[] = [+ {+ element: <PageShell />,+ children: [+ { index: true, element: <Navigate to="/issues" replace /> },+ { path: "issues", element: <IssuesPage />, handle: { title: "Issues" } },+ {+ path: "issues/:id",+ element: <IssueDetailPage />,+ handle: { title: "Issue" },+ },+ {+ path: "projects",+ element: <ProjectsPage />,+ handle: { title: "Projects" },+ },+ {+ path: "projects/:id",+ element: <ProjectDetailPage />,+ handle: { title: "Project" },+ },+ {+ path: "my-issues",+ element: <MyIssuesPage />,+ handle: { title: "My Issues" },+ },+ {+ path: "runtimes",+ element: <RuntimesPage />,+ handle: { title: "Runtimes" },+ },+ { path: "skills", element: <SkillsPage />, handle: { title: "Skills" } },+ { path: "agents", element: <AgentsPage />, handle: { title: "Agents" } },+ { path: "inbox", element: <InboxPage />, handle: { title: "Inbox" } },+ {+ path: "settings",+ element: <SettingsPage />,+ handle: { title: "Settings" },+ },+ ],+ },+];++/** Create an independent memory router for a tab. */+export function createTabRouter(initialPath: string) {+ return createMemoryRouter(appRoutes, {+ initialEntries: [initialPath],+ });+}diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.tsindex eeb69bd502..2a495d5115 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts@@ -1,4 +1,6 @@import { create } from "zustand";+import type { DataRouter } from "react-router-dom";+import { createTabRouter } from "../routes";// ---------------------------------------------------------------------------// Types@@ -9,6 +11,9 @@ export interface Tab {path: string;title: string;icon: string;+ router: DataRouter;+ historyIndex: number;+ historyLength: number;}interface TabStore {@@ -19,12 +24,14 @@ interface TabStore {openTab: (path: string, title: string, icon: string) => string;/** Always create a new tab (no dedup). Returns the tab id. */addTab: (path: string, title: string, icon: string) => string;- /** Close a tab. Returns the path to navigate to if active tab changed, or null. */- closeTab: (tabId: string) => string | null;+ /** Close a tab. Disposes router. */+ closeTab: (tabId: string) => void;/** Switch to a tab by id. */setActiveTab: (tabId: string) => void;- /** Update the active tab's metadata. */- updateActiveTab: (path: string, title: string, icon: string) => void;+ /** Update a tab's metadata (path, title, icon — partial). */+ updateTab: (tabId: string, patch: Partial<Pick<Tab, "path" | "title" | "icon">>) => void;+ /** Update a tab's history tracking. */+ updateTabHistory: (tabId: string, historyIndex: number, historyLength: number) => void;}// ---------------------------------------------------------------------------@@ -35,6 +42,7 @@ const ROUTE_ICONS: Record<string, string> = {"/inbox": "Inbox","/my-issues": "CircleUser","/issues": "ListTodo",+ "/projects": "FolderKanban","/agents": "Bot","/runtimes": "Monitor","/skills": "BookOpenText",@@ -43,7 +51,10 @@ const ROUTE_ICONS: Record<string, string> = {/** Resolve a route icon. Title is NOT determined here — it comes from document.title. */export function resolveRouteIcon(pathname: string): string {- return ROUTE_ICONS[pathname] ?? (pathname.startsWith("/issues/") ? "ListTodo" : "ListTodo");+ return ROUTE_ICONS[pathname]+ ?? (pathname.startsWith("/issues/") ? "ListTodo" : undefined)+ ?? (pathname.startsWith("/projects/") ? "FolderKanban" : undefined)+ ?? "ListTodo";}// ---------------------------------------------------------------------------@@ -56,12 +67,19 @@ function createId(): string {return crypto.randomUUID();}-const initialTab: Tab = {- id: createId(),- path: DEFAULT_PATH,- title: "Issues",- icon: resolveRouteIcon(DEFAULT_PATH),-};+function makeTab(path: string, title: string, icon: string): Tab {+ return {+ id: createId(),+ path,+ title,+ icon,+ router: createTabRouter(path),+ historyIndex: 0,+ historyLength: 1,+ };+}++const initialTab = makeTab(DEFAULT_PATH, "Issues", resolveRouteIcon(DEFAULT_PATH));export const useTabStore = create<TabStore>((set, get) => ({tabs: [initialTab],@@ -72,13 +90,13 @@ export const useTabStore = create<TabStore>((set, get) => ({const existing = tabs.find((t) => t.path === path);if (existing) return existing.id;- const tab: Tab = { id: createId(), path, title, icon };+ const tab = makeTab(path, title, icon);set({ tabs: [...tabs, tab] });return tab.id;},addTab(path, title, icon) {- const tab: Tab = { id: createId(), path, title, icon };+ const tab = makeTab(path, title, icon);set((s) => ({ tabs: [...s.tabs, tab] }));return tab.id;},@@ -86,38 +104,47 @@ export const useTabStore = create<TabStore>((set, get) => ({closeTab(tabId) {const { tabs, activeTabId } = get();+ const closingTab = tabs.find((t) => t.id === tabId);+// Never close the last tab — replace with defaultif (tabs.length === 1) {- const fresh: Tab = { id: createId(), path: DEFAULT_PATH, title: "Issues", icon: resolveRouteIcon(DEFAULT_PATH) };+ closingTab?.router.dispose();+ const fresh = makeTab(DEFAULT_PATH, "Issues", resolveRouteIcon(DEFAULT_PATH));set({ tabs: [fresh], activeTabId: fresh.id });- return fresh.path;+ return;}const idx = tabs.findIndex((t) => t.id === tabId);- if (idx === -1) return null;+ if (idx === -1) return;+ closingTab?.router.dispose();const next = tabs.filter((t) => t.id !== tabId);if (tabId === activeTabId) {const newActive = next[Math.min(idx, next.length - 1)];set({ tabs: next, activeTabId: newActive.id });- return newActive.path;+ } else {+ set({ tabs: next });}-- set({ tabs: next });- return null;},setActiveTab(tabId) {set({ activeTabId: tabId });},- updateActiveTab(path, title, icon) {- const { tabs, activeTabId } = get();- set({- tabs: tabs.map((t) =>- t.id === activeTabId ? { ...t, path, title, icon } : t,+ updateTab(tabId, patch) {+ set((s) => ({+ tabs: s.tabs.map((t) =>+ t.id === tabId ? { ...t, ...patch } : t,+ ),+ }));+ },++ updateTabHistory(tabId, historyIndex, historyLength) {+ set((s) => ({+ tabs: s.tabs.map((t) =>+ t.id === tabId ? { ...t, historyIndex, historyLength } : t,),- });+ }));},}));