Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(desktop): tab presentation by object identity (MUL-4370) (#5661)
Naiyuan Qing2f111037d21b
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsxindex d00732fc78..6d2258bc63 100644--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx@@ -3,8 +3,7 @@ import { ChevronLeft, ChevronRight } from "lucide-react";import { motion } from "motion/react";import { cn } from "@multica/ui/lib/utils";import { useTabHistory } from "@/hooks/use-tab-history";-import { useActiveTitleSync } from "@/hooks/use-tab-sync";-import { useTabStore, resolveRouteIcon } from "@/stores/tab-store";+import { useTabStore } from "@/stores/tab-store";import {SidebarProvider,SidebarTrigger,@@ -153,9 +152,10 @@ function useInternalLinkHandler() {const handler = (e: Event) => {const path = (e as CustomEvent).detail?.path;if (!path) return;- const icon = resolveRouteIcon(path);const store = useTabStore.getState();- const tabId = store.openTab(path, path, icon);+ // Empty seed title — the tab bar derives the real title from the URL and+ // cache; a raw path would flash before that resolves.+ const tabId = store.openTab(path, "");store.setActiveTab(tabId);};window.addEventListener("multica:navigate", handler);@@ -209,7 +209,6 @@ function DesktopInboxBridge() {export function DesktopShell() {useInternalLinkHandler();- useActiveTitleSync();useNativeNavigationGestures();// Reactive read of current workspace slug from the platform singleton.diff --git a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx b/apps/desktop/src/renderer/src/components/tab-bar.test.tsxindex 271d0c60df..46274ced6a 100644--- a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx+++ b/apps/desktop/src/renderer/src/components/tab-bar.test.tsx@@ -10,10 +10,8 @@ import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";type MockTab = {id: string;- path: string;- url?: string;+ url: string;title: string;- icon: string;pinned: boolean;};@@ -23,8 +21,8 @@ const state = vi.hoisted(() => ({acme: {activeTabId: "tA",tabs: [- { id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: false },- { id: "tB", path: "/acme/projects", title: "Projects", icon: "ListTodo", pinned: false },+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: false },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },] as MockTab[],},} as Record<string, { activeTabId: string; tabs: MockTab[] }>,@@ -33,7 +31,8 @@ const state = vi.hoisted(() => ({closeOtherTabs: vi.fn<(tabId: string) => void>(),setActiveTab: vi.fn<(tabId: string) => void>(),moveTab: vi.fn<(from: number, to: number) => void>(),- addTab: vi.fn<(path: string, title: string, icon: string) => string>(),+ addTab: vi.fn<(path: string, title: string) => string>(),+ updateTab: vi.fn<(tabId: string, patch: { title?: string }) => void>(),openIssueWindow: vi.fn(),}));@@ -51,6 +50,7 @@ vi.mock("@/stores/tab-store", () => {setActiveTab: state.setActiveTab,moveTab: state.moveTab,addTab: state.addTab,+ updateTab: state.updateTab,};const useTabStore = Object.assign((selector?: (s: typeof store) => unknown) =>@@ -61,11 +61,12 @@ vi.mock("@/stores/tab-store", () => {state.activeWorkspaceSlug? (state.byWorkspace[state.activeWorkspaceSlug] ?? null): null;- const resolveRouteIcon = () => "ListTodo";- return { useTabStore, useActiveGroup, resolveRouteIcon };+ return { useTabStore, useActiveGroup };});-vi.mock("@multica/core/paths", () => ({+vi.mock("@multica/core/paths", async (importOriginal) => ({+ // Spread the real module so pure helpers (parseTabSubject etc.) keep working.+ ...(await importOriginal<typeof import("@multica/core/paths")>()),paths: {workspace: (slug: string) => ({issues: () => `/${slug}/issues`,@@ -73,6 +74,23 @@ vi.mock("@multica/core/paths", () => ({},}));+// The tab bar's presentation (URL/cache → visual + title) is covered by the+// views tab-presentation tests. Here we stub it so the strip-behavior tests+// (overflow, pin, close, context menu) don't need the whole query stack. By+// default `title` mirrors the persisted tab title (matching the real hook's+// fallback); a test can set `pres.title` to simulate a resolved title that+// differs, to exercise the active-tab persist effect.+const pres = vi.hoisted(() => ({ title: null as string | null }));+vi.mock("@multica/views/layout", () => ({+ useTabPresentation: (_url: string, fallbackTitle?: string) => ({+ visual: { kind: "icon", icon: "ListTodo" },+ title: pres.title ?? fallbackTitle ?? "",+ }),+ ResourceLeadingVisual: ({ visual }: { visual: { kind: string; icon?: string } }) => (+ <span data-testid="tab-leading" data-visual-kind={visual.kind} data-icon={visual.icon} />+ ),+}));+import { TabBar } from "./tab-bar";function reset() {@@ -81,8 +99,8 @@ function reset() {acme: {activeTabId: "tA",tabs: [- { id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: false },- { id: "tB", path: "/acme/projects", title: "Projects", icon: "ListTodo", pinned: false },+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: false },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },],},};@@ -92,7 +110,9 @@ function reset() {state.setActiveTab.mockReset();state.moveTab.mockReset();state.addTab.mockReset();+ state.updateTab.mockReset();state.openIssueWindow.mockReset();+ pres.title = null;}beforeEach(() => {@@ -125,8 +145,8 @@ afterAll(() => vi.unstubAllGlobals());describe("TabBar hover action buttons", () => {it("renders a Pin button on every unpinned tab and an Unpin button on every pinned tab", () => {state.byWorkspace.acme.tabs = [- { id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: true },- { id: "tB", path: "/acme/projects", title: "Projects", icon: "ListTodo", pinned: false },+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: true },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },];const { getAllByLabelText } = render(<TabBar />);expect(getAllByLabelText("Unpin tab")).toHaveLength(1);@@ -142,8 +162,8 @@ describe("TabBar hover action buttons", () => {it("clicking the Unpin button on a pinned tab calls togglePin", () => {state.byWorkspace.acme.tabs = [- { id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: true },- { id: "tB", path: "/acme/projects", title: "Projects", icon: "ListTodo", pinned: false },+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: true },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },];const { getByLabelText } = render(<TabBar />);fireEvent.click(getByLabelText("Unpin tab"));@@ -152,8 +172,8 @@ describe("TabBar hover action buttons", () => {it("hides the X close button on a pinned tab but keeps it on an unpinned tab", () => {state.byWorkspace.acme.tabs = [- { id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: true },- { id: "tB", path: "/acme/projects", title: "Projects", icon: "ListTodo", pinned: false },+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: true },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },];const { queryAllByLabelText } = render(<TabBar />);// Only the unpinned tab exposes a Close affordance — pinned tab requires@@ -163,28 +183,66 @@ describe("TabBar hover action buttons", () => {it("keeps the full title visible on a pinned tab (no icon-only collapse)", () => {state.byWorkspace.acme.tabs = [- { id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: true },+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: true },];const { getByLabelText } = render(<TabBar />);const pinnedTab = getByLabelText("Issues (pinned)");expect(within(pinnedTab).getByText("Issues")).toBeTruthy();});- it("renders the Pin glyph as the leading icon on a pinned tab and the route icon on an unpinned tab", () => {+ // MUL-4370: each tab renders the shared ResourceLeadingVisual keyed off its+ // URL. (Which visual/title a URL resolves to is covered by the views+ // tab-presentation tests; here we only assert the strip wires it in.)+ it("renders the resource leading visual for every tab", () => {+ state.byWorkspace.acme.tabs = [+ { id: "tA", url: "/acme/autopilots", title: "Autopilots", pinned: false },+ { id: "tB", url: "/acme/projects/proj-1", title: "Project", pinned: false },+ ];+ const { getByLabelText } = render(<TabBar />);+ expect(+ getByLabelText("Autopilots").querySelector('[data-testid="tab-leading"]'),+ ).toBeTruthy();+ expect(+ getByLabelText("Project").querySelector('[data-testid="tab-leading"]'),+ ).toBeTruthy();+ });++ // Pin is a secondary state, not an identity: a pinned tab keeps its resource+ // leading visual rather than collapsing to a Pin glyph (PRD).+ it("keeps the resource leading visual on a pinned tab (pin does not replace it)", () => {state.byWorkspace.acme.tabs = [- { id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: true },- { id: "tB", path: "/acme/projects", title: "Projects", icon: "ListTodo", pinned: false },+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: true },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },];const { getByLabelText } = render(<TabBar />);const pinnedTab = getByLabelText("Issues (pinned)");- const unpinnedTab = getByLabelText("Projects");- // lucide-react renders the icon name into the class list. The leading- // slot icon is size-3.5; the hover Pin/Unpin action button is size-2.5,- // so we qualify on size to avoid matching the action glyph.- expect(pinnedTab.querySelector(".lucide-pin.size-3\\.5")).toBeTruthy();- expect(pinnedTab.querySelector(".lucide-list-todo")).toBeNull();- expect(unpinnedTab.querySelector(".lucide-list-todo.size-3\\.5")).toBeTruthy();- expect(unpinnedTab.querySelector(".lucide-pin.size-3\\.5")).toBeNull();+ // The leading slot is the resource visual (size-3.5), not a Pin glyph. The+ // only Pin lives in the size-2.5 hover action button.+ expect(pinnedTab.querySelector('[data-testid="tab-leading"]')).toBeTruthy();+ expect(pinnedTab.querySelector(".lucide-pin.size-3\\.5")).toBeNull();+ });+});++describe("TabBar active-tab title persistence", () => {+ it("persists the resolved title only for the active tab", () => {+ pres.title = "MUL-1: Fixed";+ state.byWorkspace.acme.tabs = [+ { id: "tA", url: "/acme/issues/i1", title: "Issues", pinned: false },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },+ ];+ state.byWorkspace.acme.activeTabId = "tA";+ render(<TabBar />);+ expect(state.updateTab).toHaveBeenCalledWith("tA", { title: "MUL-1: Fixed" });+ expect(state.updateTab).not.toHaveBeenCalledWith("tB", expect.anything());+ expect(state.updateTab).toHaveBeenCalledTimes(1);+ });++ it("does not re-persist when the resolved title already matches (no loop)", () => {+ // Active tab's persisted title equals the resolved title.+ pres.title = "Issues";+ state.byWorkspace.acme.activeTabId = "tA"; // tA.title === "Issues"+ render(<TabBar />);+ expect(state.updateTab).not.toHaveBeenCalled();});});@@ -192,9 +250,8 @@ describe("TabBar overflow", () => {it("keeps tabs readable in a bounded horizontal scroller", () => {state.byWorkspace.acme.tabs = Array.from({ length: 8 }, (_, index) => ({id: `t${index}`,- path: `/acme/tab-${index}`,+ url: `/acme/tab-${index}`,title: `Tab ${index}`,- icon: "ListTodo",pinned: index === 0,}));@@ -251,9 +308,8 @@ describe("TabBar overflow", () => {it("scrolls only the tab strip when the active tab moves out of view", () => {state.byWorkspace.acme.tabs = Array.from({ length: 6 }, (_, index) => ({id: `t${index}`,- path: `/acme/tab-${index}`,+ url: `/acme/tab-${index}`,title: `Tab ${index}`,- icon: "ListTodo",pinned: false,}));state.byWorkspace.acme.activeTabId = "t0";@@ -287,9 +343,8 @@ describe("TabBar overflow", () => {it("smoothly reveals a newly added active tab", () => {state.byWorkspace.acme.tabs = Array.from({ length: 6 }, (_, index) => ({id: `t${index}`,- path: `/acme/tab-${index}`,+ url: `/acme/tab-${index}`,title: `Tab ${index}`,- icon: "ListTodo",pinned: false,}));state.byWorkspace.acme.activeTabId = "t0";@@ -327,9 +382,8 @@ describe("TabBar overflow", () => {...state.byWorkspace.acme.tabs,{id: "t6",- path: "/acme/tab-6",+ url: "/acme/tab-6",title: "Tab 6",- icon: "ListTodo",pinned: false,},];@@ -347,9 +401,8 @@ describe("TabBar overflow", () => {it("keeps background additions offscreen and acknowledges them at the edge", () => {state.byWorkspace.acme.tabs = Array.from({ length: 6 }, (_, index) => ({id: `t${index}`,- path: `/acme/tab-${index}`,+ url: `/acme/tab-${index}`,title: `Tab ${index}`,- icon: "ListTodo",pinned: false,}));state.byWorkspace.acme.activeTabId = "t0";@@ -385,9 +438,8 @@ describe("TabBar overflow", () => {...state.byWorkspace.acme.tabs,{id: "t6",- path: "/acme/tab-6",+ url: "/acme/tab-6",title: "Tab 6",- icon: "ListTodo",pinned: false,},];@@ -407,10 +459,8 @@ describe("TabBar context menu", () => {state.byWorkspace.acme.tabs = [{id: "tA",- path: "/acme/issues/issue-1",url: "/acme/issues/issue-1?comment=comment-1",title: "MUL-1: Fix tabs",- icon: "ListTodo",pinned: false,},];@@ -429,10 +479,8 @@ describe("TabBar context menu", () => {state.byWorkspace.acme.tabs = [{id: "tA",- path: "/acme/issues",url: "/acme/issues",title: "Issues",- icon: "ListTodo",pinned: false,},];@@ -446,9 +494,9 @@ describe("TabBar context menu", () => {it("closes other tabs from the context menu", async () => {state.byWorkspace.acme.tabs = [- { id: "tA", path: "/acme/issues", title: "Issues", icon: "ListTodo", pinned: true },- { id: "tB", path: "/acme/projects", title: "Projects", icon: "ListTodo", pinned: false },- { id: "tC", path: "/acme/agents", title: "Agents", icon: "Bot", pinned: false },+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: true },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },+ { id: "tC", url: "/acme/agents", title: "Agents", pinned: false },];const { findByText, getByLabelText } = render(<TabBar />);diff --git a/apps/desktop/src/renderer/src/components/tab-bar.tsx b/apps/desktop/src/renderer/src/components/tab-bar.tsxindex 15797258c0..4ab9f3688e 100644--- a/apps/desktop/src/renderer/src/components/tab-bar.tsx+++ b/apps/desktop/src/renderer/src/components/tab-bar.tsx@@ -7,22 +7,7 @@ import {type RefObject,} from "react";import { motion, useReducedMotion } from "motion/react";-import {- Inbox,- CircleUser,- ListTodo,- Bot,- Monitor,- BookOpenText,- Settings,- X,- Plus,- Pin,- PinOff,- ListX,- AppWindow,- type LucideIcon,-} from "lucide-react";+import { X, Plus, Pin, PinOff, ListX, AppWindow } from "lucide-react";import {DndContext,PointerSensor,@@ -50,25 +35,14 @@ import {} from "@multica/ui/components/ui/context-menu";import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";import { cn } from "@multica/ui/lib/utils";-import {- useTabStore,- useActiveGroup,- resolveRouteIcon,- type Tab,-} from "@/stores/tab-store";+import { useTabStore, useActiveGroup, type Tab } from "@/stores/tab-store";import { paths } from "@multica/core/paths";+import {+ useTabPresentation,+ ResourceLeadingVisual,+} from "@multica/views/layout";import { parseIssueWindowPath } from "../../../shared/issue-window";-const TAB_ICONS: Record<string, LucideIcon> = {- Inbox,- CircleUser,- ListTodo,- Bot,- Monitor,- BookOpenText,- Settings,-};-const TAB_SCROLL_FADE_SIZE = 24;const TAB_ENTRY_EASE = [0.22, 1, 0.36, 1] as const;@@ -195,8 +169,25 @@ function SortableTabItem({const closeTab = useTabStore((s) => s.closeTab);const closeOtherTabs = useTabStore((s) => s.closeOtherTabs);const togglePin = useTabStore((s) => s.togglePin);+ const updateTab = useTabStore((s) => s.updateTab);const issueWindowPath = parseIssueWindowPath(tab.url);+ // The tab's leading visual and title are derived live from its URL and the+ // query cache — a resource's own icon/status/avatar and its real title,+ // updated as the cache updates. `tab.title` is only a persisted first-frame+ // fallback. See @multica/views useTabPresentation.+ const { visual, title } = useTabPresentation(tab.url, tab.title);++ // Persist the active tab's resolved title so it survives as the next+ // session's first-frame fallback. The tab strip itself always renders the+ // live resolved `title`; `tab.title` is just the persisted seed. This+ // replaces the old document.title → MutationObserver → tab.title path (the OS+ // window title stays page-driven via useDocumentTitle).+ useEffect(() => {+ if (!isActive) return;+ if (tab.title !== title) updateTab(tab.id, { title });+ }, [isActive, title, tab.id, tab.title, updateTab]);+const {attributes,listeners,@@ -206,12 +197,10 @@ function SortableTabItem({isDragging,} = useSortable({ id: tab.id });- // Pinned tabs swap the route icon for a Pin glyph as the static "I am- // pinned" indicator (RFC §3 D1v-iv FINAL). The route information is still- // present in the title, and this avoids a hard left accent border that read- // as visually heavy in light mode.- const LeadingIcon = tab.pinned ? Pin : TAB_ICONS[tab.icon];-+ // Pin is a secondary interaction state, not an identity: a pinned tab keeps+ // its resource visual (a project's icon, an issue's status, an actor's+ // avatar) rather than collapsing to a Pin glyph. Pinned-ness is conveyed by+ // position, the suppressed close button, and the hover Pin/Unpin action.const style = {transform: CSS.Transform.toString(transform),transition,@@ -242,14 +231,15 @@ function SortableTabItem({if (!issueWindowPath) return;void window.desktopAPI.openIssueWindow({path: issueWindowPath.path,- title: tab.title,+ title,});};// Pinned tabs keep their full title (RFC §3 D1v-ii FINAL). The only visual- // differences vs. unpinned tabs are the leading Pin icon (swapped in above)- // and the suppressed X (closing requires explicit Unpin). Pin/Unpin is- // reachable via the hover action button below and the right-click menu.+ // differences vs. unpinned tabs are the suppressed X (closing requires+ // explicit Unpin) — the leading visual is the resource's own identity, same+ // as an unpinned tab. Pin/Unpin is reachable via the hover action button+ // below and the right-click menu.const showCloseButton = !tab.pinned && !isOnly;const [isEntering, setIsEntering] = useState(isNew && !shouldReduceMotion);const [showAddedHighlight, setShowAddedHighlight] = useState(isNew);@@ -266,10 +256,10 @@ function SortableTabItem({{...attributes}{...listeners}onClick={handleClick}- aria-label={tab.pinned ? `${tab.title} (pinned)` : tab.title}+ aria-label={tab.pinned ? `${title} (pinned)` : title}data-tab-active={isActive ? "true" : undefined}data-tab-entering={isEntering ? "true" : undefined}- title={tab.pinned ? `${tab.title} (pinned)` : undefined}+ title={tab.pinned ? `${title} (pinned)` : undefined}style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}className={cn("group relative flex size-full min-w-0 items-center gap-1.5 px-2.5 text-xs transition-colors",@@ -280,7 +270,7 @@ function SortableTabItem({isDragging && "opacity-60",)}>- {LeadingIcon && <LeadingIcon className="size-3.5 shrink-0" />}+ <ResourceLeadingVisual visual={visual} /><spanclassName="min-w-0 flex-1 overflow-hidden whitespace-nowrap text-left"style={{@@ -288,7 +278,7 @@ function SortableTabItem({WebkitMaskImage: "linear-gradient(to right, black calc(100% - 12px), transparent)",}}>- {tab.title}+ {title}</span><spanonClick={handleTogglePin}@@ -499,7 +489,7 @@ function NewTabButton() {const activeSlug = useTabStore.getState().activeWorkspaceSlug;if (!activeSlug) return;const path = paths.workspace(activeSlug).issues();- const tabId = addTab(path, "Issues", resolveRouteIcon(path));+ const tabId = addTab(path, "Issues");if (tabId) setActiveTab(tabId);};diff --git a/apps/desktop/src/renderer/src/hooks/use-tab-sync.ts b/apps/desktop/src/renderer/src/hooks/use-tab-sync.tsdeleted file mode 100644index 74520a7029..0000000000--- a/apps/desktop/src/renderer/src/hooks/use-tab-sync.ts+++ /dev/null@@ -1,32 +0,0 @@-import { useEffect } from "react";-import { useTabStore } from "@/stores/tab-store";--/**- * Watches document.title via MutationObserver and updates the active tab's- * title. Pages set document.title via TitleSync (route handle.title) or- * useDocumentTitle(). This observer picks up the change and syncs it to- * the tab store.- */-export function useActiveTitleSync() {- useEffect(() => {- const observer = new MutationObserver(() => {- const title = document.title;- if (!title) return;- const state = useTabStore.getState();- if (!state.activeWorkspaceSlug) return;- const group = state.byWorkspace[state.activeWorkspaceSlug];- if (!group) return;- const activeTab = group.tabs.find((t) => t.id === group.activeTabId);- if (activeTab && activeTab.title !== title) {- state.updateTab(activeTab.id, { title });- }- });-- const titleEl = document.querySelector("title");- if (titleEl) {- observer.observe(titleEl, { childList: true, characterData: true, subtree: true });- }-- return () => observer.disconnect();- }, []);-}diff --git a/apps/desktop/src/renderer/src/pages/autopilot-detail-page.tsx b/apps/desktop/src/renderer/src/pages/autopilot-detail-page.tsxindex 5c0c4e5f08..633d9f2392 100644--- a/apps/desktop/src/renderer/src/pages/autopilot-detail-page.tsx+++ b/apps/desktop/src/renderer/src/pages/autopilot-detail-page.tsx@@ -10,7 +10,8 @@ export function AutopilotDetailPage() {const wsId = useWorkspaceId();const { data } = useQuery(autopilotDetailOptions(wsId, id!));- useDocumentTitle(data ? `⚡ ${data.autopilot.title}` : "Autopilot");+ // Plain text only — no leading ⚡ glyph in the title (MUL-4370).+ useDocumentTitle(data ? data.autopilot.title : "Autopilot");if (!id) return null;return <AutopilotDetail autopilotId={id} />;diff --git a/apps/desktop/src/renderer/src/pages/project-detail-page.tsx b/apps/desktop/src/renderer/src/pages/project-detail-page.tsxindex a476ebf40f..6762de6cc7 100644--- a/apps/desktop/src/renderer/src/pages/project-detail-page.tsx+++ b/apps/desktop/src/renderer/src/pages/project-detail-page.tsx@@ -10,7 +10,9 @@ export function ProjectDetailPage() {const wsId = useWorkspaceId();const { data: project } = useQuery(projectDetailOptions(wsId, id!));- useDocumentTitle(project ? `${project.icon || "📁"} ${project.title}` : "Project");+ // Plain text only — the project's icon is shown by the tab's leading visual,+ // not concatenated into the title (MUL-4370).+ useDocumentTitle(project ? project.title : "Project");if (!id) return null;return <ProjectDetail projectId={id} />;diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex c7649c1e1c..b88d617f63 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -7,7 +7,6 @@ import { useAuthStore } from "@multica/core/auth";import { isReservedSlug } from "@multica/core/paths";import {useTabStore,- resolveRouteIcon,getActiveTab,splitTabUrl,useActiveTabUrl,@@ -118,8 +117,7 @@ function tryRouteToPinnedNewTab(path: string): boolean {const newPathname = splitTabUrl(path).pathname;if (currentPathname === newPathname) return false;- const icon = resolveRouteIcon(path);- store.openTab(path, path, icon, { activate: true });+ store.openTab(path, "", { activate: true });return true;}@@ -191,8 +189,7 @@ export function DesktopNavigationProvider({store.switchWorkspace(slug, path);return;}- const icon = resolveRouteIcon(path);- store.openTab(path, title ?? path, icon, { activate: opts?.activate });+ store.openTab(path, title ?? "", { activate: opts?.activate });},getShareableUrl: (path: string) => `${appUrl}${path}`,}),diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.tsindex 4ccd15ecad..15026369cd 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts@@ -6,8 +6,10 @@ import {migrateV1ToV2,migrateV2ToV3,migrateV3ToV4,+ mergePersistedTabs,useTabStore,getActiveTab,+ type WorkspaceTabGroup,} from "./tab-store";beforeEach(() => {@@ -128,7 +130,7 @@ describe("useTabStore actions", () => {it("switchWorkspace without openPath restores the group's last active tab", () => {const store = useTabStore.getState();store.switchWorkspace("acme");- store.addTab("/acme/projects", "Projects", "FolderKanban");+ store.addTab("/acme/projects", "Projects");const acmeProjectsId = useTabStore.getState().byWorkspace.acme.tabs[1].id;store.setActiveTab(acmeProjectsId);@@ -145,7 +147,7 @@ describe("useTabStore actions", () => {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");+ store.addTab("/acme/projects", "Projects");store.switchWorkspace("acme", "/acme/issues");const s = useTabStore.getState();@@ -171,8 +173,8 @@ describe("useTabStore actions", () => {it("openTab dedupes by resourceKey within the active workspace", () => {const store = useTabStore.getState();store.switchWorkspace("acme");- const id1 = store.openTab("/acme/projects", "Projects", "FolderKanban");- const id2 = store.openTab("/acme/projects", "Projects", "FolderKanban");+ const id1 = store.openTab("/acme/projects", "Projects");+ const id2 = store.openTab("/acme/projects", "Projects");expect(id1).toBe(id2);expect(useTabStore.getState().byWorkspace.acme.tabs).toHaveLength(2); // default + projects});@@ -182,7 +184,7 @@ describe("useTabStore actions", () => {store.switchWorkspace("acme"); // default tab at /acme/issuesconst defaultTabId = useTabStore.getState().byWorkspace.acme.tabs[0].id;- const id = store.openTab("/acme/issues?filter=urgent", "Issues", "ListTodo");+ const id = store.openTab("/acme/issues?filter=urgent", "Issues");const s = useTabStore.getState();expect(id).toBe(defaultTabId); // focused, not duplicated@@ -206,7 +208,7 @@ describe("useTabStore actions", () => {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");+ const closedTabId = store.addTab("/acme/settings", "Settings");store.closeTab(closedTabId);const before = useTabStore.getState().byWorkspace.acme;@@ -228,7 +230,7 @@ describe("useTabStore actions", () => {const tab = useTabStore.getState().byWorkspace.acme.tabs[0];const before = useTabStore.getState().byWorkspace.acme;- store.updateTab(tab.id, { title: tab.title, icon: tab.icon });+ store.updateTab(tab.id, { title: tab.title });expect(useTabStore.getState().byWorkspace.acme).toBe(before);});@@ -317,7 +319,7 @@ describe("useTabStore actions", () => {});describe("navigateActiveSession", () => {- it("updates url, resourceKey, icon, and pushes onto the virtual history", () => {+ it("updates url, resourceKey, and pushes onto the virtual history", () => {const store = useTabStore.getState();store.switchWorkspace("acme");@@ -326,7 +328,6 @@ describe("navigateActiveSession", () => {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,@@ -486,9 +487,9 @@ describe("bulk tab closing", () => {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");+ const projectsId = store.addTab("/acme/projects", "Projects");+ store.addTab("/acme/agents", "Agents");+ store.addTab("/acme/settings", "Settings");store.togglePin(issuesId);store.setActiveTab(useTabStore.getState().byWorkspace.acme.tabs[2].id);@@ -503,9 +504,9 @@ describe("bulk tab closing", () => {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");+ const projectsId = store.addTab("/acme/projects", "Projects");+ store.addTab("/acme/agents", "Agents");+ store.addTab("/acme/settings", "Settings");store.togglePin(issuesId);store.setActiveTab(issuesId);@@ -534,8 +535,8 @@ describe("togglePin", () => {it("moves a newly-pinned tab to the start of the pinned zone", () => {const store = useTabStore.getState();store.switchWorkspace("acme"); // creates default unpinned tab at index 0- store.addTab("/acme/projects", "Projects", "FolderKanban");- store.addTab("/acme/agents", "Agents", "Bot");+ store.addTab("/acme/projects", "Projects");+ store.addTab("/acme/agents", "Agents");const agentsId = useTabStore.getState().byWorkspace.acme.tabs[2].id;store.togglePin(agentsId);@@ -549,8 +550,8 @@ describe("togglePin", () => {it("appends a second pinned tab after the first pinned tab", () => {const store = useTabStore.getState();store.switchWorkspace("acme");- store.addTab("/acme/projects", "Projects", "FolderKanban");- store.addTab("/acme/agents", "Agents", "Bot");+ store.addTab("/acme/projects", "Projects");+ store.addTab("/acme/agents", "Agents");const projectsId = useTabStore.getState().byWorkspace.acme.tabs[1].id;const agentsId = useTabStore.getState().byWorkspace.acme.tabs[2].id;@@ -571,7 +572,7 @@ describe("togglePin", () => {it("returns an unpinned tab to the start of the unpinned zone", () => {const store = useTabStore.getState();store.switchWorkspace("acme");- store.addTab("/acme/projects", "Projects", "FolderKanban");+ store.addTab("/acme/projects", "Projects");const issuesId = useTabStore.getState().byWorkspace.acme.tabs[0].id;const projectsId = useTabStore.getState().byWorkspace.acme.tabs[1].id;@@ -590,8 +591,8 @@ describe("moveTab boundary clamp", () => {it("clamps a pinned-tab move so it never crosses into the unpinned zone", () => {const store = useTabStore.getState();store.switchWorkspace("acme");- store.addTab("/acme/projects", "Projects", "FolderKanban");- store.addTab("/acme/agents", "Agents", "Bot");+ store.addTab("/acme/projects", "Projects");+ store.addTab("/acme/agents", "Agents");const issuesId = useTabStore.getState().byWorkspace.acme.tabs[0].id;store.togglePin(issuesId); // [issues(pinned), projects, agents]@@ -607,8 +608,8 @@ describe("moveTab boundary clamp", () => {it("clamps an unpinned-tab move so it never crosses into the pinned zone", () => {const store = useTabStore.getState();store.switchWorkspace("acme");- store.addTab("/acme/projects", "Projects", "FolderKanban");- store.addTab("/acme/agents", "Agents", "Bot");+ store.addTab("/acme/projects", "Projects");+ store.addTab("/acme/agents", "Agents");const issuesId = useTabStore.getState().byWorkspace.acme.tabs[0].id;const agentsId = useTabStore.getState().byWorkspace.acme.tabs[2].id;@@ -626,8 +627,8 @@ describe("moveTab boundary clamp", () => {it("reorders freely within the same zone", () => {const store = useTabStore.getState();store.switchWorkspace("acme");- store.addTab("/acme/projects", "Projects", "FolderKanban");- store.addTab("/acme/agents", "Agents", "Bot");+ store.addTab("/acme/projects", "Projects");+ store.addTab("/acme/agents", "Agents");// All unpinned; move agents (2) to position 0.store.moveTab(2, 0);@@ -690,12 +691,13 @@ describe("migrateV3ToV4 (legacy view-state import, MUL-4741)", () => {};const v4 = migrateV3ToV4(v3);expect(v4.activeWorkspaceSlug).toBe("acme");+ // `icon` is intentionally absent: it is derived from the url at render+ // time, so a legacy payload's icon name is never carried forward.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: {} },@@ -711,3 +713,54 @@ describe("migrateV3ToV4 (legacy view-state import, MUL-4741)", () => {expect(v4.activeWorkspaceSlug).toBeNull();});});++describe("mergePersistedTabs (rehydration, MUL-4370)", () => {+ const emptyState = (): {+ activeWorkspaceSlug: string | null;+ byWorkspace: Record<string, WorkspaceTabGroup>;+ } => ({ activeWorkspaceSlug: null, byWorkspace: {} });++ function persistedTab(url: string, extra: Record<string, unknown> = {}) {+ return {+ id: "t1",+ url,+ title: "Tab",+ pinned: false,+ history: { stack: [url], index: 0 },+ memento: { scroll: {} },+ ...extra,+ };+ }++ function rehydrate(tab: Record<string, unknown>) {+ return mergePersistedTabs(+ {+ activeWorkspaceSlug: "acme",+ byWorkspace: { acme: { activeTabId: "t1", tabs: [tab] } },+ },+ emptyState(),+ ).byWorkspace.acme.tabs[0];+ }++ // A user who opened /acme/autopilots on an older build has "ListTodo"+ // persisted for it. Carrying that value forward is what kept the tab bar+ // showing the wrong icon after upgrade, while the sidebar showed the new+ // one. The session must not hold an icon at all.+ it("does not carry a stale persisted icon into the session", () => {+ const tab = rehydrate(persistedTab("/acme/autopilots", { icon: "ListTodo" }));+ expect(tab).not.toHaveProperty("icon");+ expect(tab.url).toBe("/acme/autopilots");+ });++ it("ignores an unknown or corrupted persisted icon", () => {+ const tab = rehydrate(persistedTab("/acme/projects", { icon: "NotARealIcon" }));+ expect(tab).not.toHaveProperty("icon");+ expect(tab.url).toBe("/acme/projects");+ });++ it("rehydrates payloads with no icon field at all", () => {+ const tab = rehydrate(persistedTab("/acme/squads"));+ expect(tab).not.toHaveProperty("icon");+ expect(tab.url).toBe("/acme/squads");+ });+});diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.tsindex 14b0e841bb..ab68bb2800 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts@@ -54,7 +54,6 @@ export interface TabSession {*/resourceKey: string;title: string;- icon: string;/*** 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@@ -126,11 +125,10 @@ interface TabStore {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;+ addTab: (path: string, title: string) => string;/*** Close a tab. Finds it across all workspaces (callers like the X button* only know the tab id, not the owning workspace). If this is the last@@ -147,10 +145,10 @@ interface TabStore {*/setActiveTab: (tabId: string) => void;/** Patch display metadata of a tab (title-sync). Finds across groups. */- updateTab: (tabId: string, patch: Partial<Pick<TabSession, "title" | "icon">>) => void;+ updateTab: (tabId: string, patch: Partial<Pick<TabSession, "title">>) => 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+ * In-tab navigation: update the active session's url/resourceKey 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;@@ -212,34 +210,14 @@ interface TabStore {}// ----------------------------------------------------------------------------// Route → icon mapping (title comes from document.title, not from here)+// Session identity helpers// -----------------------------------------------------------------------------const ROUTE_ICONS: Record<string, string> = {- inbox: "Inbox",- "my-issues": "CircleUser",- issues: "ListTodo",- projects: "FolderKanban",- autopilots: "ListTodo",- agents: "Bot",- runtimes: "Monitor",- skills: "BookOpenText",- settings: "Settings",-};--/**- * Resolve a route icon from a pathname.- *- * 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.- *- * Title is NOT determined here — it comes from document.title.- */-export function resolveRouteIcon(pathname: string): string {- const segments = pathname.split("/").filter(Boolean);- return ROUTE_ICONS[segments[1] ?? ""] ?? "ListTodo";-}+//+// A tab's icon is NOT part of this model. It is derived from `tab.url` at+// render time via `routeIconForPath` (@multica/views/layout), which shares the+// route → icon map in `@multica/core/paths` with the sidebar nav — so the two+// surfaces cannot drift, and no stale icon can survive in persisted state.+// Title is likewise not determined here; it comes from document.title./** Extract the leading workspace slug from a path, or null if the path* isn't workspace-scoped (global path, root, or empty). */@@ -325,13 +303,12 @@ function createId(): string {return createSafeId();}-function makeSession(url: string, title: string, icon: string): TabSession {+function makeSession(url: string, title: string): TabSession {return {id: createId(),url,resourceKey: resourceKeyForUrl(url),title,- icon,pinned: false,history: { stack: [url], index: 0 },memento: emptyMemento(),@@ -352,7 +329,7 @@ function defaultPathFor(slug: string): string {function defaultTabFor(slug: string): TabSession {const path = defaultPathFor(slug);- return makeSession(path, "Issues", resolveRouteIcon(path));+ return makeSession(path, "Issues");}// ---------------------------------------------------------------------------@@ -421,7 +398,7 @@ export const useTabStore = create<TabStore>()(// First time entering this workspace — create the group.const cleanDesired = desiredPath ? sanitizeTabPath(desiredPath) : null;const seedPath = cleanDesired ?? defaultPathFor(slug);- const tab = makeSession(seedPath, "Issues", resolveRouteIcon(seedPath));+ const tab = makeSession(seedPath, "Issues");set({activeWorkspaceSlug: slug,byWorkspace: {@@ -449,7 +426,7 @@ export const useTabStore = create<TabStore>()(});return;}- const tab = makeSession(clean, "Issues", resolveRouteIcon(clean));+ const tab = makeSession(clean, "Issues");set({activeWorkspaceSlug: slug,byWorkspace: {@@ -468,7 +445,7 @@ export const useTabStore = create<TabStore>()(set({ activeWorkspaceSlug: slug });},- openTab(path, title, icon, opts) {+ openTab(path, title, opts) {const { activeWorkspaceSlug, byWorkspace } = get();const clean = sanitizeTabPath(path);if (!activeWorkspaceSlug || !clean) return "";@@ -489,7 +466,7 @@ export const useTabStore = create<TabStore>()(return existing.id;}- const tab = makeSession(clean, title, icon);+ const tab = makeSession(clean, title);set({byWorkspace: {...byWorkspace,@@ -502,14 +479,14 @@ export const useTabStore = create<TabStore>()(return tab.id;},- addTab(path, title, icon) {+ addTab(path, title) {const { activeWorkspaceSlug, byWorkspace } = get();const clean = sanitizeTabPath(path);if (!activeWorkspaceSlug || !clean) return "";const group = byWorkspace[activeWorkspaceSlug];if (!group) return "";- const tab = makeSession(clean, title, icon);+ const tab = makeSession(clean, title);set({byWorkspace: {...byWorkspace,@@ -585,7 +562,7 @@ export const useTabStore = create<TabStore>()(const { slug, group, index } = hit;const current = group.tabs[index];const next: TabSession = { ...current, ...patch };- if (next.title === current.title && next.icon === current.icon) {+ if (next.title === current.title) {return;}const nextTabs = [...group.tabs];@@ -630,7 +607,6 @@ export const useTabStore = create<TabStore>()(...current,url: clean,resourceKey: resourceKeyForUrl(clean),- icon: resolveRouteIcon(splitTabUrl(clean).pathname),history: { stack, index: historyIndex },};const nextTabs = [...group.tabs];@@ -854,7 +830,6 @@ export const useTabStore = create<TabStore>()(id: t.id,url: t.url,title: t.title,- icon: t.icon,pinned: t.pinned,history: t.history,memento: t.memento,@@ -863,69 +838,92 @@ export const useTabStore = create<TabStore>()(]),),}),- merge: (persistedState, currentState) => {- 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: TabSession[] = [];- for (const pTab of pGroup.tabs) {- 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 url that doesn't match the group's slug.- if (!clean || extractWorkspaceSlug(clean) !== slug) {- console.warn(- `[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,- url: clean,- resourceKey: resourceKeyForUrl(clean),- title: pTab.title,- icon: pTab.icon,- pinned: pTab.pinned === true,- history: { stack, index },- memento:- pTab.memento && typeof pTab.memento.scroll === "object"- ? pTab.memento- : emptyMemento(),- });- }- if (tabs.length === 0) continue;- // Enforce the "pinned first" invariant on rehydration in case a- // user (or a buggy older write) persisted the pinned tabs out of- // order. Stable sort preserves intra-group order.- tabs.sort((a, b) => (a.pinned === b.pinned ? 0 : a.pinned ? -1 : 1));- const activeTabId = tabs.some((t) => t.id === pGroup.activeTabId)- ? pGroup.activeTabId- : tabs[0].id;- byWorkspace[slug] = { tabs, activeTabId };- }-- const activeWorkspaceSlug =- persisted.activeWorkspaceSlug && byWorkspace[persisted.activeWorkspaceSlug]- ? persisted.activeWorkspaceSlug- : (Object.keys(byWorkspace)[0] ?? null);-- return { ...currentState, byWorkspace, activeWorkspaceSlug };- },+ merge: (persistedState, currentState) =>+ mergePersistedTabs(persistedState, currentState),},),);+/** The persisted slice of the store — what `merge` reads and rebuilds. */+interface PersistedTabState {+ activeWorkspaceSlug: string | null;+ byWorkspace: Record<string, WorkspaceTabGroup>;+}++/**+ * Rebuild live sessions from a persisted payload.+ *+ * Every persisted field is treated as untrusted: urls are re-sanitized and+ * checked against their group's slug, history indices are clamped, and a+ * missing memento is replaced. Fields that are *derivable* are not read at+ * all — notably `icon`, which older builds persisted and which may name the+ * icon a route used to have. The tab bar computes the icon from `url`, so a+ * stale or unknown persisted name cannot survive rehydration.+ *+ * Exported for tests; production calls it through the persist `merge` hook.+ */+export function mergePersistedTabs<T extends PersistedTabState>(+ persistedState: unknown,+ currentState: T,+): T {+ 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: TabSession[] = [];+ for (const pTab of pGroup.tabs) {+ 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 url that doesn't match the group's slug.+ if (!clean || extractWorkspaceSlug(clean) !== slug) {+ console.warn(+ `[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,+ url: clean,+ resourceKey: resourceKeyForUrl(clean),+ title: pTab.title,+ pinned: pTab.pinned === true,+ history: { stack, index },+ memento:+ pTab.memento && typeof pTab.memento.scroll === "object"+ ? pTab.memento+ : emptyMemento(),+ });+ }+ if (tabs.length === 0) continue;+ // Enforce the "pinned first" invariant on rehydration in case a+ // user (or a buggy older write) persisted the pinned tabs out of+ // order. Stable sort preserves intra-group order.+ tabs.sort((a, b) => (a.pinned === b.pinned ? 0 : a.pinned ? -1 : 1));+ const activeTabId = tabs.some((t) => t.id === pGroup.activeTabId)+ ? pGroup.activeTabId+ : tabs[0].id;+ byWorkspace[slug] = { tabs, activeTabId };+ }++ const activeWorkspaceSlug =+ persisted.activeWorkspaceSlug && byWorkspace[persisted.activeWorkspaceSlug]+ ? persisted.activeWorkspaceSlug+ : (Object.keys(byWorkspace)[0] ?? null);++ return { ...currentState, byWorkspace, activeWorkspaceSlug };+}+function stepHistory(get: () => TabStore,set: (partial: Partial<TabStore>) => void,@@ -945,7 +943,6 @@ function stepHistory(...current,url,resourceKey: resourceKeyForUrl(url),- icon: resolveRouteIcon(splitTabUrl(url).pathname),history: { ...current.history, index: nextIndex },};const nextTabs = [...group.tabs];@@ -1013,7 +1010,14 @@ interface V4PersistedTab {id: string;url: string;title: string;- icon: string;+ /**+ * Legacy. v4 payloads written before route icons became derived state still+ * carry an icon name, and that name can be stale (a tab opened on an older+ * build kept whatever the route mapped to then). It is never read on+ * rehydration — the tab bar derives the icon from `url` — and `partialize`+ * drops it on the next write.+ */+ icon?: string;pinned: boolean;history: { stack: string[]; index: number };memento: TabMemento;@@ -1034,11 +1038,13 @@ export function migrateV3ToV4(v3: V3Persisted): V4Persisted {for (const [slug, group] of Object.entries(v3.byWorkspace ?? {})) {byWorkspace[slug] = {activeTabId: group.activeTabId,+ // `icon` is deliberately not carried over: it is derived from the url+ // at render time, and a v3 payload's icon may predate the current+ // route → icon map.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(),diff --git a/packages/core/paths/index.ts b/packages/core/paths/index.tsindex 172af2bdca..f89d529304 100644--- a/packages/core/paths/index.ts+++ b/packages/core/paths/index.ts@@ -1,6 +1,34 @@export { paths, isGlobalPath } from "./paths";export type { WorkspacePaths } from "./paths";export { RESERVED_SLUGS, isReservedSlug } from "./reserved-slugs";+export {+ WORKSPACE_PAGES,+ DEFAULT_ROUTE_ICON_NAME,+ resolveRouteIconName,+ pageForSegment,+} from "./route-icons";+export type {+ RouteIconName,+ NavLabelKey,+ WorkspacePageKey,+ WorkspacePage,+} from "./route-icons";+export {+ parseTabSubject,+ tabSubjectKey,+} from "./tab-subject";+export type { TabSubject, TabActorType } from "./tab-subject";+export {+ resolveTabPresentation,+ DEFAULT_TAB_VISUAL,+} from "./tab-presentation";+export type {+ TabVisual,+ TabTitleSpec,+ TabPresentation,+ TabEntityData,+ TabLabelKey,+} from "./tab-presentation";export { resolvePostAuthDestination, useHasOnboarded } from "./resolve";export {WorkspaceSlugProvider,diff --git a/packages/core/paths/route-icons.test.ts b/packages/core/paths/route-icons.test.tsnew file mode 100644index 0000000000..55b56fe820--- /dev/null+++ b/packages/core/paths/route-icons.test.ts@@ -0,0 +1,82 @@+import { describe, it, expect } from "vitest";+import { paths } from "./paths";+import {+ WORKSPACE_PAGES,+ DEFAULT_ROUTE_ICON_NAME,+ resolveRouteIconName,+ pageForSegment,+ type WorkspacePageKey,+} from "./route-icons";++// Guards the class of bug where a workspace nav route exists but has no+// explicit page entry, so it silently falls back to the default (ListTodo) and+// visually diverges from the rest of the UI. Every parameterless workspace+// route that shows up in the sidebar/tab bar must map to a WORKSPACE_PAGES+// entry.+describe("workspace page coverage", () => {+ // `root` aliases `issues` (same segment) and is never rendered as its own+ // nav item; the parameterized detail routes are resources, not pages.+ const EXCLUDED_METHODS = new Set(["root"]);+ const KNOWN_SEGMENTS = new Set(+ (Object.keys(WORKSPACE_PAGES) as WorkspacePageKey[]).map(+ (k) => WORKSPACE_PAGES[k].segment,+ ),+ );++ it("every parameterless workspace route segment maps to a page", () => {+ const ws = paths.workspace("acme") as unknown as Record<string, () => string>;+ const missing: string[] = [];++ for (const [method, fn] of Object.entries(ws)) {+ if (typeof fn !== "function" || fn.length !== 0) continue;+ if (EXCLUDED_METHODS.has(method)) continue;+ const segment = fn().split("/").filter(Boolean)[1] ?? "";+ if (!KNOWN_SEGMENTS.has(segment)) missing.push(`${method} → "${segment}"`);+ }++ expect(+ missing,+ `these nav routes have no page entry (would fall back to ${DEFAULT_ROUTE_ICON_NAME}): ${missing.join(", ")}`,+ ).toEqual([]);+ });+});++describe("pageForSegment", () => {+ it("maps a known segment to its page key", () => {+ expect(pageForSegment("projects")).toBe("projects");+ expect(pageForSegment("my-issues")).toBe("myIssues");+ expect(pageForSegment("settings")).toBe("settings");+ });++ it("returns null for an unknown segment", () => {+ expect(pageForSegment("not-a-page")).toBeNull();+ expect(pageForSegment("")).toBeNull();+ });+});++describe("resolveRouteIconName", () => {+ it("resolves a page path to its page icon", () => {+ expect(resolveRouteIconName("/acme/projects")).toBe("FolderKanban");+ expect(resolveRouteIconName("/acme/autopilots")).toBe("Zap");+ expect(resolveRouteIconName("/acme/chat")).toBe("MessageSquare");+ expect(resolveRouteIconName("/acme/squads")).toBe("Users");+ expect(resolveRouteIconName("/acme/usage")).toBe("BarChart3");+ expect(resolveRouteIconName("/acme/my-issues")).toBe("CircleUser");+ });++ it("gives sub-routes their parent page icon (sidebar semantics)", () => {+ expect(resolveRouteIconName("/acme/projects/proj-123")).toBe("FolderKanban");+ expect(resolveRouteIconName("/acme/issues/bug-42")).toBe("ListTodo");+ });++ it("ignores the workspace slug and any query/hash", () => {+ expect(resolveRouteIconName("/other-team/projects?x=1#y")).toBe("FolderKanban");+ });++ it("falls back to the default for unknown or too-short paths", () => {+ expect(resolveRouteIconName("/acme/unknown-route")).toBe(DEFAULT_ROUTE_ICON_NAME);+ expect(resolveRouteIconName("/acme")).toBe(DEFAULT_ROUTE_ICON_NAME);+ expect(resolveRouteIconName("/")).toBe(DEFAULT_ROUTE_ICON_NAME);+ expect(resolveRouteIconName("")).toBe(DEFAULT_ROUTE_ICON_NAME);+ });+});diff --git a/packages/core/paths/route-icons.ts b/packages/core/paths/route-icons.tsnew file mode 100644index 0000000000..c113e2490a--- /dev/null+++ b/packages/core/paths/route-icons.ts@@ -0,0 +1,135 @@+/**+ * Registry of workspace navigation *pages* and their icons.+ *+ * A "page" here is a collection or tool surface that has no specific resource+ * of its own — Issues, Projects, Settings, etc. Its icon is a stable, static+ * choice keyed by the URL route segment (`/{slug}/{segment}/...`).+ *+ * This is the source of truth the sidebar nav uses (via `resolveRouteIconName`+ * / `routeIconForPath`). The desktop tab bar goes further and derives a full+ * *presentation* (which may be a resource's own icon/avatar/status rather than+ * a page icon) — see `tab-subject.ts` and `tab-presentation.ts`, which build on+ * this registry for the page case.+ *+ * Icon values are *names*, not React components, so this module stays+ * React-free and safe inside `@multica/core`. The name → component registry+ * lives in `packages/views/layout/route-icon-components.tsx`; its+ * `Record<RouteIconName, LucideIcon>` type makes a missing component a compile+ * error.+ */++/** Every icon name a nav page or a tab type-icon can resolve to. */+export type RouteIconName =+ | "Inbox"+ | "MessageSquare"+ | "CircleUser"+ | "ListTodo"+ | "FolderKanban"+ | "Zap"+ | "Bot"+ | "Users"+ | "BarChart3"+ | "Monitor"+ | "Server"+ | "BookOpenText"+ | "Settings"+ | "File"+ | "FileText"+ | "FileImage"+ | "FileCode"+ | "FileArchive"+ | "FileAudio"+ | "FileVideo"+ | "FileQuestion";++/** i18n label key (under the `layout.nav` namespace) for a page. */+export type NavLabelKey =+ | "inbox"+ | "chat"+ | "my_issues"+ | "issues"+ | "projects"+ | "autopilots"+ | "agents"+ | "squads"+ | "usage"+ | "runtimes"+ | "skills"+ | "settings";++/** Stable identifier for each workspace navigation page. */+export type WorkspacePageKey =+ | "inbox"+ | "chat"+ | "myIssues"+ | "issues"+ | "projects"+ | "autopilots"+ | "agents"+ | "squads"+ | "usage"+ | "runtimes"+ | "skills"+ | "settings";++export interface WorkspacePage {+ /** Route segment at index 1 of `/{slug}/{segment}/...`. */+ segment: string;+ /** Static page icon. */+ icon: RouteIconName;+ /** `layout.nav.<navKey>` — the localized page name. */+ navKey: NavLabelKey;+}++/**+ * Single source of truth for workspace nav pages. Keep aligned with the nav+ * destinations in paths.ts and the sidebar nav groups.+ */+export const WORKSPACE_PAGES: Record<WorkspacePageKey, WorkspacePage> = {+ inbox: { segment: "inbox", icon: "Inbox", navKey: "inbox" },+ chat: { segment: "chat", icon: "MessageSquare", navKey: "chat" },+ myIssues: { segment: "my-issues", icon: "CircleUser", navKey: "my_issues" },+ issues: { segment: "issues", icon: "ListTodo", navKey: "issues" },+ projects: { segment: "projects", icon: "FolderKanban", navKey: "projects" },+ autopilots: { segment: "autopilots", icon: "Zap", navKey: "autopilots" },+ agents: { segment: "agents", icon: "Bot", navKey: "agents" },+ squads: { segment: "squads", icon: "Users", navKey: "squads" },+ usage: { segment: "usage", icon: "BarChart3", navKey: "usage" },+ runtimes: { segment: "runtimes", icon: "Monitor", navKey: "runtimes" },+ skills: { segment: "skills", icon: "BookOpenText", navKey: "skills" },+ settings: { segment: "settings", icon: "Settings", navKey: "settings" },+};++/** Reverse lookup: route segment → page key. */+const PAGE_BY_SEGMENT: Record<string, WorkspacePageKey> = Object.fromEntries(+ (Object.keys(WORKSPACE_PAGES) as WorkspacePageKey[]).map((key) => [+ WORKSPACE_PAGES[key].segment,+ key,+ ]),+);++/** The page whose route segment is `segment`, or null if none matches. */+export function pageForSegment(segment: string): WorkspacePageKey | null {+ return PAGE_BY_SEGMENT[segment] ?? null;+}++/** Fallback icon name used when a path's route segment has no explicit page. */+export const DEFAULT_ROUTE_ICON_NAME: RouteIconName = "ListTodo";++/**+ * Resolve the *page* icon name for a workspace-scoped path or full tab URL.+ *+ * Nav and page paths are `/{slug}/{segment}/...`, so the route segment lives+ * at index 1; any search/hash suffix is ignored. Sub-routes keep the parent+ * page's icon. Returns {@link DEFAULT_ROUTE_ICON_NAME} for unknown or+ * too-short paths, so the result is always a renderable name.+ *+ * This is the sidebar/nav entry point. The tab bar does NOT use this for+ * resource detail routes — it resolves a richer presentation instead.+ */+export function resolveRouteIconName(path: string): RouteIconName {+ const pathname = path.split(/[?#]/)[0] ?? "";+ const segment = pathname.split("/").filter(Boolean)[1] ?? "";+ const page = pageForSegment(segment);+ return page ? WORKSPACE_PAGES[page].icon : DEFAULT_ROUTE_ICON_NAME;+}diff --git a/packages/core/paths/tab-presentation.test.ts b/packages/core/paths/tab-presentation.test.tsnew file mode 100644index 0000000000..7b9f4ee44a--- /dev/null+++ b/packages/core/paths/tab-presentation.test.ts@@ -0,0 +1,226 @@+import { describe, it, expect } from "vitest";+import { parseTabSubject } from "./tab-subject";+import {+ resolveTabPresentation,+ iconForAttachment,+ type TabEntityData,+} from "./tab-presentation";++// External-visible contract: (URL, cached data) → (visual, title). Tests the+// combination, not the internal component tree — exactly the surface the PRD+// pins down.+function present(url: string, data: TabEntityData = {}) {+ return resolveTabPresentation(parseTabSubject(url), data);+}++describe("resolveTabPresentation — pages", () => {+ it("uses the page icon and localized page name", () => {+ expect(present("/acme/issues")).toEqual({+ visual: { kind: "icon", icon: "ListTodo" },+ title: { kind: "nav", navKey: "issues" },+ });+ expect(present("/acme/projects")).toEqual({+ visual: { kind: "icon", icon: "FolderKanban" },+ title: { kind: "nav", navKey: "projects" },+ });+ });+});++describe("resolveTabPresentation — direct resources", () => {+ it("issue shows live status + identifier:title, pending shows type label", () => {+ expect(present("/acme/issues/i1")).toEqual({+ visual: { kind: "issue-status", status: null },+ title: { kind: "tab", tabKey: "issue" },+ });+ expect(+ present("/acme/issues/i1", {+ issue: { identifier: "MUL-1", title: "Fix", status: "in_progress" },+ }),+ ).toEqual({+ visual: { kind: "issue-status", status: "in_progress" },+ title: { kind: "text", text: "MUL-1: Fix" },+ });+ });++ it("project shows its own icon + title, pending shows default glyph + label", () => {+ expect(present("/acme/projects/p1")).toEqual({+ visual: { kind: "project-icon", icon: null },+ title: { kind: "tab", tabKey: "project" },+ });+ expect(+ present("/acme/projects/p1", { project: { icon: "🚀", title: "Apollo" } }),+ ).toEqual({+ visual: { kind: "project-icon", icon: "🚀" },+ title: { kind: "text", text: "Apollo" },+ });+ });++ it("actor shows avatar visual and resolved name", () => {+ expect(present("/acme/agents/ag1")).toEqual({+ visual: { kind: "actor", actorType: "agent", id: "ag1" },+ title: { kind: "tab", tabKey: "agent" },+ });+ expect(present("/acme/members/m1", { actorName: "Ada" })).toEqual({+ visual: { kind: "actor", actorType: "member", id: "m1" },+ title: { kind: "text", text: "Ada" },+ });+ expect(present("/acme/squads/sq1")).toEqual({+ visual: { kind: "actor", actorType: "squad", id: "sq1" },+ title: { kind: "tab", tabKey: "squad" },+ });+ });++ it("autopilot / skill / machine / runtime use a type icon + name", () => {+ expect(present("/acme/autopilots/a1", { autopilot: { title: "Nightly" } })).toEqual({+ visual: { kind: "icon", icon: "Zap" },+ title: { kind: "text", text: "Nightly" },+ });+ expect(present("/acme/skills/s1", { skill: { name: "Deploy" } })).toEqual({+ visual: { kind: "icon", icon: "BookOpenText" },+ title: { kind: "text", text: "Deploy" },+ });+ expect(present("/acme/runtimes/m1", { machine: { name: "Mac Studio" } })).toEqual({+ visual: { kind: "icon", icon: "Monitor" },+ title: { kind: "text", text: "Mac Studio" },+ });+ expect(+ present("/acme/runtimes/m1/runtime/r1", { runtime: { name: "cloud-1" } }),+ ).toEqual({+ visual: { kind: "icon", icon: "Server" },+ title: { kind: "text", text: "cloud-1" },+ });+ });++ it("attachment shows the filename and a matching file icon, falling back only when missing", () => {+ // Filename present (from ?name=) → title is the filename, icon matches type.+ expect(present("/acme/attachments/att1/preview?name=report.pdf")).toEqual({+ visual: { kind: "icon", icon: "FileText" },+ title: { kind: "text", text: "report.pdf" },+ });+ expect(present("/acme/attachments/att1/preview?name=diagram.png").visual).toEqual({+ kind: "icon",+ icon: "FileImage",+ });+ expect(present("/acme/attachments/att1/preview?name=app.tsx").visual).toEqual({+ kind: "icon",+ icon: "FileCode",+ });+ // Missing filename → generic File icon + "Attachment" label.+ expect(present("/acme/attachments/att1/preview")).toEqual({+ visual: { kind: "icon", icon: "File" },+ title: { kind: "tab", tabKey: "attachment" },+ });+ // Unknown / extensionless → generic File, but still shows the filename.+ expect(present("/acme/attachments/att1/preview?name=LICENSE")).toEqual({+ visual: { kind: "icon", icon: "File" },+ title: { kind: "text", text: "LICENSE" },+ });+ });++ it("never borrows the Issues icon while a resource is loading", () => {+ // A pending issue uses issue-status (not the ListTodo page icon); a pending+ // project uses project-icon; neither is the generic page fallback.+ expect(present("/acme/issues/i1").visual).toEqual({+ kind: "issue-status",+ status: null,+ });+ expect(present("/acme/projects/p1").visual).toEqual({+ kind: "project-icon",+ icon: null,+ });+ });+});++describe("resolveTabPresentation — containers keep their icon, title tracks selection", () => {+ it("inbox: icon is always Inbox; title is the selected item or Inbox", () => {+ expect(present("/acme/inbox")).toEqual({+ visual: { kind: "icon", icon: "Inbox" },+ title: { kind: "nav", navKey: "inbox" },+ });+ // Selected but not yet resolved → still Inbox, never a stale title.+ expect(present("/acme/inbox?issue=MUL-9")).toEqual({+ visual: { kind: "icon", icon: "Inbox" },+ title: { kind: "nav", navKey: "inbox" },+ });+ // Selected issue → Inbox icon + issue title (distinct from a direct issue,+ // which would show a status icon).+ expect(+ present("/acme/inbox?issue=MUL-9", {+ inboxSelection: { kind: "issue", identifier: "MUL-9", title: "Bug" },+ }),+ ).toEqual({+ visual: { kind: "icon", icon: "Inbox" },+ title: { kind: "text", text: "MUL-9: Bug" },+ });+ // Selected non-issue notification → its display title.+ expect(+ present("/acme/inbox?issue=n1", {+ inboxSelection: { kind: "item", title: "Quick create failed" },+ }),+ ).toEqual({+ visual: { kind: "icon", icon: "Inbox" },+ title: { kind: "text", text: "Quick create failed" },+ });+ });++ it("chat: icon is always MessageSquare; title is the session or Chat", () => {+ expect(present("/acme/chat")).toEqual({+ visual: { kind: "icon", icon: "MessageSquare" },+ title: { kind: "nav", navKey: "chat" },+ });+ // New-chat draft (?agent=) has no session yet → stays Chat.+ expect(present("/acme/chat?agent=ag1")).toEqual({+ visual: { kind: "icon", icon: "MessageSquare" },+ title: { kind: "nav", navKey: "chat" },+ });+ expect(+ present("/acme/chat?session=s1", { chatSessionTitle: "Deploy plan" }),+ ).toEqual({+ visual: { kind: "icon", icon: "MessageSquare" },+ title: { kind: "text", text: "Deploy plan" },+ });+ // Selected session still loading → Chat, not empty.+ expect(present("/acme/chat?session=s1")).toEqual({+ visual: { kind: "icon", icon: "MessageSquare" },+ title: { kind: "nav", navKey: "chat" },+ });+ });+});++describe("resolveTabPresentation — flow and unknown", () => {+ it("create-agent flow uses the agent icon and a flow label", () => {+ expect(present("/acme/agents/new")).toEqual({+ visual: { kind: "icon", icon: "Bot" },+ title: { kind: "tab", tabKey: "create_agent" },+ });+ });++ it("unknown route uses a neutral icon and label, never Issues", () => {+ expect(present("/acme/mystery")).toEqual({+ visual: { kind: "icon", icon: "FileQuestion" },+ title: { kind: "tab", tabKey: "unknown" },+ });+ });+});++describe("iconForAttachment", () => {+ it("maps extensions to file-type icons", () => {+ expect(iconForAttachment("a.png")).toBe("FileImage");+ expect(iconForAttachment("clip.MP4")).toBe("FileVideo");+ expect(iconForAttachment("song.mp3")).toBe("FileAudio");+ expect(iconForAttachment("bundle.zip")).toBe("FileArchive");+ expect(iconForAttachment("main.ts")).toBe("FileCode");+ expect(iconForAttachment("notes.md")).toBe("FileText");+ });++ it("is case-insensitive on the extension", () => {+ expect(iconForAttachment("PHOTO.JPEG")).toBe("FileImage");+ });++ it("falls back to the generic File icon", () => {+ expect(iconForAttachment(null)).toBe("File");+ expect(iconForAttachment("LICENSE")).toBe("File"); // no extension+ expect(iconForAttachment("archive.")).toBe("File"); // trailing dot+ expect(iconForAttachment("data.unknownext")).toBe("File");+ });+});diff --git a/packages/core/paths/tab-presentation.ts b/packages/core/paths/tab-presentation.tsnew file mode 100644index 0000000000..49c055ee45--- /dev/null+++ b/packages/core/paths/tab-presentation.ts@@ -0,0 +1,234 @@+/**+ * Pure presentation resolver for desktop tabs.+ *+ * Given a {@link TabSubject} (what the tab points at) and whatever entity data+ * is currently available from cache, produce the tab's leading *visual* and its+ * *title* spec. This is the single place the "what should this tab look like"+ * decision lives — icon and title no longer come from two unrelated code paths.+ *+ * It is pure and React-free: the visual is a descriptor (rendered by+ * `@multica/views`' `ResourceLeadingVisual`) and the title is a spec that is+ * either literal text or a localization key (localized by the view layer).+ * Keeping it pure makes the whole "URL + data → icon + title" matrix unit+ * testable without React, which is exactly what the tab behavior needs guarded.+ *+ * Missing entity data is a first-class state: a resource whose data has not+ * loaded yet renders a stable type icon and a type label, never a wrong or+ * empty identity, and never borrows the Issues icon.+ */+import type { IssueStatus } from "../types";+import {+ WORKSPACE_PAGES,+ type NavLabelKey,+ type RouteIconName,+} from "./route-icons";+import type { TabActorType, TabSubject } from "./tab-subject";++/** The leading visual a tab should render. */+export type TabVisual =+ /** A static Lucide icon (page icon or resourceless type icon). */+ | { kind: "icon"; icon: RouteIconName }+ /** An issue's live status glyph. `null` while the issue is loading. */+ | { kind: "issue-status"; status: IssueStatus | null }+ /** A project's own icon. `null` falls back to the default project glyph. */+ | { kind: "project-icon"; icon: string | null }+ /** An actor's avatar, resolved by the view layer from `actorType`+`id`. */+ | { kind: "actor"; actorType: TabActorType; id: string };++/** Localization keys under the `layout.tab` namespace for tab type labels. */+export type TabLabelKey =+ | "issue"+ | "project"+ | "autopilot"+ | "agent"+ | "member"+ | "squad"+ | "skill"+ | "machine"+ | "runtime"+ | "attachment"+ | "create_agent"+ | "unknown";++/** How a tab's title should be produced. */+export type TabTitleSpec =+ /** Fully resolved literal text (a resource's own name/title). */+ | { kind: "text"; text: string }+ /** A page name — localize via `layout.nav.<navKey>`. */+ | { kind: "nav"; navKey: NavLabelKey }+ /** A type label (loading / flow / unknown) — localize via `layout.tab.<tabKey>`. */+ | { kind: "tab"; tabKey: TabLabelKey };++export interface TabPresentation {+ visual: TabVisual;+ title: TabTitleSpec;+}++/** Resolved inbox selection, as computed by the view layer from cache. */+export type InboxSelectionData =+ | { kind: "issue"; identifier: string; title: string }+ | { kind: "item"; title: string };++/**+ * Entity data the view layer has resolved from cache for the tab's subject.+ * Every field is optional: `undefined` means "not loaded yet" and yields the+ * pending (type-label + type-icon) presentation.+ */+export interface TabEntityData {+ issue?: { identifier: string; title: string; status: IssueStatus };+ project?: { icon: string | null; title: string };+ autopilot?: { title: string };+ /** Resolved display name for an actor subject. */+ actorName?: string;+ skill?: { name: string };+ machine?: { name: string };+ runtime?: { name: string };+ /** Resolved chat session title (already includes the "New chat" fallback). */+ chatSessionTitle?: string;+ /** Resolved inbox selection (issue identifier/title or item title). */+ inboxSelection?: InboxSelectionData;+}++/** Neutral visual used when nothing better can be resolved. */+export const DEFAULT_TAB_VISUAL: TabVisual = { kind: "icon", icon: "FileQuestion" };++/** Literal text if non-empty, otherwise the given type label. */+function textOr(text: string | undefined | null, tabKey: TabLabelKey): TabTitleSpec {+ const trimmed = text?.trim();+ return trimmed ? { kind: "text", text: trimmed } : { kind: "tab", tabKey };+}++const ACTOR_LABEL: Record<TabActorType, TabLabelKey> = {+ agent: "agent",+ member: "member",+ squad: "squad",+};++// Extension → file-type icon. The preview URL only carries the filename, so the+// extension is the available signal; anything unrecognized uses the generic+// File glyph.+const EXTENSION_ICON: Record<string, RouteIconName> = {};+const registerExtensions = (icon: RouteIconName, exts: string[]) => {+ for (const ext of exts) EXTENSION_ICON[ext] = icon;+};+registerExtensions("FileImage", [+ "png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "heic",+]);+registerExtensions("FileVideo", ["mp4", "mov", "webm", "mkv", "avi", "m4v"]);+registerExtensions("FileAudio", ["mp3", "wav", "ogg", "flac", "m4a", "aac"]);+registerExtensions("FileArchive", ["zip", "tar", "gz", "tgz", "rar", "7z", "bz2"]);+registerExtensions("FileCode", [+ "js", "jsx", "ts", "tsx", "json", "yaml", "yml", "py", "go", "rs",+ "java", "c", "h", "cpp", "cc", "rb", "php", "swift", "kt", "sh", "css", "scss",+]);+registerExtensions("FileText", [+ "txt", "md", "markdown", "pdf", "doc", "docx", "csv", "log",+ "html", "htm", "xml", "rtf", "odt",+]);++/** Choose the file icon for an attachment from its filename, else generic File. */+export function iconForAttachment(filename: string | null): RouteIconName {+ if (!filename) return "File";+ const dot = filename.lastIndexOf(".");+ if (dot < 0 || dot === filename.length - 1) return "File";+ const ext = filename.slice(dot + 1).toLowerCase();+ return EXTENSION_ICON[ext] ?? "File";+}++/**+ * Resolve a subject + available data into the tab's leading visual and title.+ * Exhaustive over every {@link TabSubject} kind so a new route/resource type+ * forces an explicit presentation choice rather than a silent default.+ */+export function resolveTabPresentation(+ subject: TabSubject,+ data: TabEntityData = {},+): TabPresentation {+ switch (subject.kind) {+ case "page": {+ const page = WORKSPACE_PAGES[subject.page];+ return {+ visual: { kind: "icon", icon: page.icon },+ title: { kind: "nav", navKey: page.navKey },+ };+ }+ case "issue":+ return {+ visual: { kind: "issue-status", status: data.issue?.status ?? null },+ title: data.issue+ ? { kind: "text", text: `${data.issue.identifier}: ${data.issue.title}` }+ : { kind: "tab", tabKey: "issue" },+ };+ case "project":+ return {+ visual: { kind: "project-icon", icon: data.project?.icon ?? null },+ title: textOr(data.project?.title, "project"),+ };+ case "autopilot":+ return {+ visual: { kind: "icon", icon: "Zap" },+ title: textOr(data.autopilot?.title, "autopilot"),+ };+ case "actor":+ return {+ visual: { kind: "actor", actorType: subject.actorType, id: subject.id },+ title: textOr(data.actorName, ACTOR_LABEL[subject.actorType]),+ };+ case "skill":+ return {+ visual: { kind: "icon", icon: "BookOpenText" },+ title: textOr(data.skill?.name, "skill"),+ };+ case "machine":+ return {+ visual: { kind: "icon", icon: "Monitor" },+ title: textOr(data.machine?.name, "machine"),+ };+ case "runtime":+ return {+ visual: { kind: "icon", icon: "Server" },+ title: textOr(data.runtime?.name, "runtime"),+ };+ case "attachment":+ // The preview URL carries the filename (`?name=`), so use it for the+ // title and pick a matching file icon from its extension. Only fall back+ // to the generic File glyph + "Attachment" label when it's missing.+ return {+ visual: { kind: "icon", icon: iconForAttachment(subject.filename) },+ title: subject.filename+ ? { kind: "text", text: subject.filename }+ : { kind: "tab", tabKey: "attachment" },+ };+ case "inbox": {+ // The container icon never changes; only the title tracks the selection.+ const sel = subject.selectedKey ? data.inboxSelection : undefined;+ let title: TabTitleSpec;+ if (!sel) {+ title = { kind: "nav", navKey: "inbox" };+ } else if (sel.kind === "issue") {+ title = { kind: "text", text: `${sel.identifier}: ${sel.title}` };+ } else {+ const text = sel.title.trim();+ title = text ? { kind: "text", text } : { kind: "nav", navKey: "inbox" };+ }+ return { visual: { kind: "icon", icon: "Inbox" }, title };+ }+ case "chat": {+ const title: TabTitleSpec =+ subject.sessionId && data.chatSessionTitle?.trim()+ ? { kind: "text", text: data.chatSessionTitle.trim() }+ : { kind: "nav", navKey: "chat" };+ return { visual: { kind: "icon", icon: "MessageSquare" }, title };+ }+ case "flow":+ return {+ visual: { kind: "icon", icon: "Bot" },+ title: { kind: "tab", tabKey: "create_agent" },+ };+ case "unknown":+ return {+ visual: DEFAULT_TAB_VISUAL,+ title: { kind: "tab", tabKey: "unknown" },+ };+ }+}diff --git a/packages/core/paths/tab-subject.test.ts b/packages/core/paths/tab-subject.test.tsnew file mode 100644index 0000000000..6c734807f2--- /dev/null+++ b/packages/core/paths/tab-subject.test.ts@@ -0,0 +1,111 @@+import { describe, it, expect } from "vitest";+import { parseTabSubject, tabSubjectKey, type TabSubject } from "./tab-subject";++describe("parseTabSubject", () => {+ // Table-driven over every desktop workspace route, including collection vs+ // detail, the /new flow, nested runtime, container query selection, and+ // unknown paths. A new route type that isn't handled here will surface as+ // `unknown` — which the presentation layer renders neutrally, never as Issues.+ const cases: Array<[string, TabSubject]> = [+ // Collection / tool pages+ ["/acme/issues", { kind: "page", page: "issues" }],+ ["/acme/my-issues", { kind: "page", page: "myIssues" }],+ ["/acme/projects", { kind: "page", page: "projects" }],+ ["/acme/autopilots", { kind: "page", page: "autopilots" }],+ ["/acme/agents", { kind: "page", page: "agents" }],+ ["/acme/squads", { kind: "page", page: "squads" }],+ ["/acme/usage", { kind: "page", page: "usage" }],+ ["/acme/runtimes", { kind: "page", page: "runtimes" }],+ ["/acme/skills", { kind: "page", page: "skills" }],+ ["/acme/settings", { kind: "page", page: "settings" }],+ // Resource details+ ["/acme/issues/bug-1", { kind: "issue", id: "bug-1" }],+ ["/acme/projects/p1", { kind: "project", id: "p1" }],+ ["/acme/autopilots/a1", { kind: "autopilot", id: "a1" }],+ ["/acme/skills/s1", { kind: "skill", id: "s1" }],+ ["/acme/attachments/att1/preview", { kind: "attachment", id: "att1", filename: null }],+ [+ "/acme/attachments/att1/preview?name=report.pdf",+ { kind: "attachment", id: "att1", filename: "report.pdf" },+ ],+ [+ "/acme/attachments/att1/preview?name=my%20photo.png",+ { kind: "attachment", id: "att1", filename: "my photo.png" },+ ],+ // Actors+ ["/acme/agents/ag1", { kind: "actor", actorType: "agent", id: "ag1" }],+ ["/acme/members/m1", { kind: "actor", actorType: "member", id: "m1" }],+ ["/acme/squads/sq1", { kind: "actor", actorType: "squad", id: "sq1" }],+ // Flow — /new must win over the actor detail pattern+ ["/acme/agents/new", { kind: "flow", flow: "create-agent" }],+ // Runtime machine vs nested runtime+ ["/acme/runtimes/machine-1", { kind: "machine", machineId: "machine-1" }],+ [+ "/acme/runtimes/machine-1/runtime/rt-2",+ { kind: "runtime", machineId: "machine-1", runtimeId: "rt-2" },+ ],+ // Containers — selection (and archived sub-list) live in the query string+ ["/acme/inbox", { kind: "inbox", selectedKey: null, archived: false }],+ ["/acme/inbox?issue=MUL-9", { kind: "inbox", selectedKey: "MUL-9", archived: false }],+ ["/acme/inbox?view=archived", { kind: "inbox", selectedKey: null, archived: true }],+ [+ "/acme/inbox?view=archived&issue=MUL-9",+ { kind: "inbox", selectedKey: "MUL-9", archived: true },+ ],+ ["/acme/chat", { kind: "chat", sessionId: null }],+ ["/acme/chat?session=sess-1", { kind: "chat", sessionId: "sess-1" }],+ ["/acme/chat?agent=ag-1", { kind: "chat", sessionId: null }],+ // Members list route does not exist+ ["/acme/members", { kind: "unknown" }],+ // Unknown / too short+ ["/acme/nope", { kind: "unknown" }],+ ["/acme", { kind: "unknown" }],+ ["/", { kind: "unknown" }],+ ["", { kind: "unknown" }],+ ];++ it.each(cases)("parses %s", (url, expected) => {+ expect(parseTabSubject(url)).toEqual(expected);+ });++ it("ignores hash fragments", () => {+ expect(parseTabSubject("/acme/issues/bug-1#comment-3")).toEqual({+ kind: "issue",+ id: "bug-1",+ });+ expect(parseTabSubject("/acme/chat?session=s1#x")).toEqual({+ kind: "chat",+ sessionId: "s1",+ });+ });++ it("keeps sub-route ids at index 2 (issue filters/anchors don't leak)", () => {+ expect(parseTabSubject("/acme/issues/bug-1?comment=c1")).toEqual({+ kind: "issue",+ id: "bug-1",+ });+ });+});++describe("tabSubjectKey", () => {+ it("is stable for the same subject and distinct across selections", () => {+ expect(tabSubjectKey({ kind: "issue", id: "x" })).toBe("issue:x");+ expect(tabSubjectKey({ kind: "chat", sessionId: null })).toBe("chat:");+ expect(tabSubjectKey({ kind: "chat", sessionId: "s1" })).toBe("chat:s1");+ expect(+ tabSubjectKey({ kind: "actor", actorType: "member", id: "m1" }),+ ).toBe("actor:member:m1");+ });++ it("distinguishes archived inbox and the attachment filename", () => {+ expect(tabSubjectKey({ kind: "inbox", selectedKey: "k", archived: false })).toBe(+ "inbox:inbox:k",+ );+ expect(tabSubjectKey({ kind: "inbox", selectedKey: "k", archived: true })).toBe(+ "inbox:archived:k",+ );+ expect(+ tabSubjectKey({ kind: "attachment", id: "a1", filename: "x.pdf" }),+ ).toBe("attachment:a1:x.pdf");+ });+});diff --git a/packages/core/paths/tab-subject.ts b/packages/core/paths/tab-subject.tsnew file mode 100644index 0000000000..3837b0806b--- /dev/null+++ b/packages/core/paths/tab-subject.ts@@ -0,0 +1,169 @@+/**+ * Semantic target resolver for desktop tabs.+ *+ * A tab points at a URL, but what a tab *is* — a collection page, a specific+ * resource, a container with a selected item, a creation flow, or something+ * unrecognized — is what decides how it should look (icon + title). This module+ * turns a URL into that semantic {@link TabSubject}. It is pure: no React, no+ * Lucide, no query — only URL parsing. The visual/title mapping lives in+ * `tab-presentation.ts`; the React glue lives in `@multica/views`.+ *+ * Workspace URLs are `/{slug}/{segment}/...`. The slug is index 0, the route+ * segment index 1, and any resource id index 2. Container selection (Inbox,+ * Chat) rides in the query string, so it is parsed too — the URL is the single+ * source of truth for what a tab has open, including which item.+ */+import { pageForSegment, type WorkspacePageKey } from "./route-icons";++export type TabActorType = "agent" | "member" | "squad";++export type TabSubject =+ /** A collection or tool page with no specific resource. */+ | { kind: "page"; page: WorkspacePageKey }+ /** A single issue detail. */+ | { kind: "issue"; id: string }+ /** A single project detail. */+ | { kind: "project"; id: string }+ /** A single autopilot detail. */+ | { kind: "autopilot"; id: string }+ /** An agent / member / squad detail (has an avatar identity). */+ | { kind: "actor"; actorType: TabActorType; id: string }+ /** A single skill detail. */+ | { kind: "skill"; id: string }+ /** A runtime machine detail. */+ | { kind: "machine"; machineId: string }+ /** A runtime nested under a machine. */+ | { kind: "runtime"; machineId: string; runtimeId: string }+ /** An attachment preview. `filename` is the `?name=` hint, or null. */+ | { kind: "attachment"; id: string; filename: string | null }+ /**+ * The Inbox container; `selectedKey` is the `?issue=` selection or null,+ * `archived` is the `?view=archived` sub-list (its own list/cache).+ */+ | { kind: "inbox"; selectedKey: string | null; archived: boolean }+ /** The Chat container; `sessionId` is the `?session=` selection or null. */+ | { kind: "chat"; sessionId: string | null }+ /** A creation flow that has not produced a resource yet. */+ | { kind: "flow"; flow: "create-agent" }+ /** An unrecognized URL. Never impersonate a real page. */+ | { kind: "unknown" };++/** Split a URL into its `/`-separated pathname segments and its query params. */+function splitUrl(url: string): { segments: string[]; query: URLSearchParams } {+ const hashIdx = url.indexOf("#");+ const withoutHash = hashIdx === -1 ? url : url.slice(0, hashIdx);+ const queryIdx = withoutHash.indexOf("?");+ const pathname = queryIdx === -1 ? withoutHash : withoutHash.slice(0, queryIdx);+ const search = queryIdx === -1 ? "" : withoutHash.slice(queryIdx + 1);+ return {+ segments: pathname.split("/").filter(Boolean),+ query: new URLSearchParams(search),+ };+}++/**+ * Resolve a workspace tab URL into a {@link TabSubject}.+ *+ * Only recognizes workspace-scoped URLs (`/{slug}/{segment}/...`). Anything+ * shorter, empty, or with an unknown segment resolves to `{ kind: "unknown" }`+ * — never to a default page, so an unrecognized tab is visibly neutral rather+ * than masquerading as Issues.+ */+export function parseTabSubject(url: string): TabSubject {+ const { segments, query } = splitUrl(url);+ // segments[0] is the workspace slug; the route segment is at index 1.+ const segment = segments[1] ?? "";+ const id = segments[2] ?? "";++ switch (segment) {+ case "issues":+ return id ? { kind: "issue", id } : { kind: "page", page: "issues" };+ case "my-issues":+ return { kind: "page", page: "myIssues" };+ case "projects":+ return id ? { kind: "project", id } : { kind: "page", page: "projects" };+ case "autopilots":+ return id ? { kind: "autopilot", id } : { kind: "page", page: "autopilots" };+ case "agents":+ if (id === "new") return { kind: "flow", flow: "create-agent" };+ return id+ ? { kind: "actor", actorType: "agent", id }+ : { kind: "page", page: "agents" };+ case "members":+ // No members collection route exists; only `/members/:id`.+ return id ? { kind: "actor", actorType: "member", id } : { kind: "unknown" };+ case "squads":+ return id+ ? { kind: "actor", actorType: "squad", id }+ : { kind: "page", page: "squads" };+ case "usage":+ return { kind: "page", page: "usage" };+ case "inbox":+ return {+ kind: "inbox",+ selectedKey: query.get("issue") || null,+ archived: query.get("view") === "archived",+ };+ case "chat":+ return { kind: "chat", sessionId: query.get("session") || null };+ case "runtimes":+ if (!id) return { kind: "page", page: "runtimes" };+ // `/runtimes/:machineId/runtime/:runtimeId` — nested runtime.+ if (segments[3] === "runtime" && segments[4]) {+ return { kind: "runtime", machineId: id, runtimeId: segments[4] };+ }+ return { kind: "machine", machineId: id };+ case "skills":+ return id ? { kind: "skill", id } : { kind: "page", page: "skills" };+ case "settings":+ return { kind: "page", page: "settings" };+ case "attachments":+ // `/attachments/:id/preview?name=<filename>`.+ return id+ ? { kind: "attachment", id, filename: query.get("name") || null }+ : { kind: "unknown" };+ default: {+ // A bare `/{slug}` (no route segment) is normalized to the default+ // surface elsewhere; treat any other unknown segment as unknown so it+ // does not silently borrow a page's identity.+ const page = pageForSegment(segment);+ return page ? { kind: "page", page } : { kind: "unknown" };+ }+ }+}++/**+ * A stable string identity for a subject, useful as a memo/render key. Distinct+ * subjects that should render the same visual share a key; a selection change+ * inside a container changes it.+ */+export function tabSubjectKey(subject: TabSubject): string {+ switch (subject.kind) {+ case "page":+ return `page:${subject.page}`;+ case "issue":+ return `issue:${subject.id}`;+ case "project":+ return `project:${subject.id}`;+ case "autopilot":+ return `autopilot:${subject.id}`;+ case "actor":+ return `actor:${subject.actorType}:${subject.id}`;+ case "skill":+ return `skill:${subject.id}`;+ case "machine":+ return `machine:${subject.machineId}`;+ case "runtime":+ return `runtime:${subject.machineId}:${subject.runtimeId}`;+ case "attachment":+ return `attachment:${subject.id}:${subject.filename ?? ""}`;+ case "inbox":+ return `inbox:${subject.archived ? "archived" : "inbox"}:${subject.selectedKey ?? ""}`;+ case "chat":+ return `chat:${subject.sessionId ?? ""}`;+ case "flow":+ return `flow:${subject.flow}`;+ case "unknown":+ return "unknown";+ }+}diff --git a/packages/views/layout/app-sidebar.test.tsx b/packages/views/layout/app-sidebar.test.tsxindex 9ddcfa881f..4d4b19555d 100644--- a/packages/views/layout/app-sidebar.test.tsx+++ b/packages/views/layout/app-sidebar.test.tsx@@ -112,7 +112,11 @@ vi.mock("@multica/core/chat", () => ({{ getState: () => chatStore.current },),}));-vi.mock("@multica/core/paths", () => ({+vi.mock("@multica/core/paths", async (importOriginal) => ({+ // Spread the real module so pure helpers (resolveRouteIconName, used by the+ // nav to derive each item's icon from its href) stay intact; only the+ // workspace/context hooks below are stubbed to control routes in tests.+ ...(await importOriginal<typeof import("@multica/core/paths")>()),paths: { workspace: (slug: string) => ({ issues: () => `/${slug}/issues` }) },useCurrentWorkspace: () => ({ id: "ws-1", name: "Acme", slug: "acme" }),useWorkspacePaths: () => ({diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsxindex 841b2bfb46..c3bb84a818 100644--- a/packages/views/layout/app-sidebar.tsx+++ b/packages/views/layout/app-sidebar.tsx@@ -17,25 +17,13 @@ import {import { SortableContext, verticalListSortingStrategy, useSortable, arrayMove } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import {- Inbox,- MessageSquare,- ListTodo,- Bot,- Monitor,ChevronDown,ChevronRight,- Settings,LogOut,Plus,Check,- BookOpenText,SquarePen,- CircleUser,- FolderKanban,- BarChart3,X,- Zap,- Users,} from "lucide-react";import { WorkspaceAvatar } from "../workspace/workspace-avatar";import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";@@ -86,6 +74,7 @@ import { projectDetailOptions } from "@multica/core/projects/queries";import type { PinnedItem } from "@multica/core/types";import { useLogout } from "../auth";import { ProjectIcon } from "../projects/components/project-icon";+import { routeIconForPath } from "./route-icon-components";import { useT } from "../i18n";import {useShortcut,@@ -129,7 +118,8 @@ type NavKey =| "skills"| "settings";-// Static schema (key + icon) — labels resolved at render via useT("layout").+// Static schema (key only) — labels resolved at render via useT("layout"),+// icons derived from the destination path via routeIconForPath.type NavLabelKey =| "inbox"| "chat"@@ -144,25 +134,28 @@ type NavLabelKey =| "skills"| "settings";-const personalNav: { key: NavKey; labelKey: NavLabelKey; icon: typeof Inbox }[] = [- { key: "inbox", labelKey: "inbox", icon: Inbox },- { key: "chat", labelKey: "chat", icon: MessageSquare },- { key: "myIssues", labelKey: "my_issues", icon: CircleUser },+// Nav icons are NOT declared here: they are derived from each item's+// destination path at render time, so the sidebar and the desktop tab bar+// always agree. See route-icon-components.tsx.+const personalNav: { key: NavKey; labelKey: NavLabelKey }[] = [+ { key: "inbox", labelKey: "inbox" },+ { key: "chat", labelKey: "chat" },+ { key: "myIssues", labelKey: "my_issues" },];-const workspaceNav: { key: NavKey; labelKey: NavLabelKey; icon: typeof Inbox }[] = [- { key: "issues", labelKey: "issues", icon: ListTodo },- { key: "projects", labelKey: "projects", icon: FolderKanban },- { key: "autopilots", labelKey: "autopilots", icon: Zap },- { key: "agents", labelKey: "agents", icon: Bot },- { key: "squads", labelKey: "squads", icon: Users },- { key: "usage", labelKey: "usage", icon: BarChart3 },+const workspaceNav: { key: NavKey; labelKey: NavLabelKey }[] = [+ { key: "issues", labelKey: "issues" },+ { key: "projects", labelKey: "projects" },+ { key: "autopilots", labelKey: "autopilots" },+ { key: "agents", labelKey: "agents" },+ { key: "squads", labelKey: "squads" },+ { key: "usage", labelKey: "usage" },];-const configureNav: { key: NavKey; labelKey: NavLabelKey; icon: typeof Inbox }[] = [- { key: "runtimes", labelKey: "runtimes", icon: Monitor },- { key: "skills", labelKey: "skills", icon: BookOpenText },- { key: "settings", labelKey: "settings", icon: Settings },+const configureNav: { key: NavKey; labelKey: NavLabelKey }[] = [+ { key: "runtimes", labelKey: "runtimes" },+ { key: "skills", labelKey: "skills" },+ { key: "settings", labelKey: "settings" },];function DraftDot() {@@ -670,6 +663,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }<SidebarMenu className="gap-0.5">{personalNav.map((item) => {const href = p[item.key]();+ const Icon = routeIconForPath(href);const isActive = isNavActive(pathname, href);return (<SidebarMenuItem key={item.key}>@@ -678,7 +672,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }render={<AppLink href={href} />}className="text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground">- <item.icon />+ <Icon /><span>{t(($) => $.nav[item.labelKey])}</span>{item.key === "inbox" && unreadCount > 0 && (<CappedNumberFlow@@ -743,6 +737,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }<SidebarMenu className="gap-0.5">{workspaceNav.map((item) => {const href = p[item.key]();+ const Icon = routeIconForPath(href);const isActive = !isActivePinnedRoute && isNavActive(pathname, href);return (<SidebarMenuItem key={item.key}>@@ -751,7 +746,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }render={<AppLink href={href} />}className="text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground">- <item.icon />+ <Icon /><span>{t(($) => $.nav[item.labelKey])}</span></SidebarMenuButton></SidebarMenuItem>@@ -767,6 +762,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }<SidebarMenu className="gap-0.5">{configureNav.map((item) => {const href = p[item.key]();+ const Icon = routeIconForPath(href);const isActive = isNavActive(pathname, href);return (<SidebarMenuItem key={item.key}>@@ -775,7 +771,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }render={<AppLink href={href} />}className="text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground">- <item.icon />+ <Icon /><span>{t(($) => $.nav[item.labelKey])}</span></SidebarMenuButton></SidebarMenuItem>diff --git a/packages/views/layout/index.ts b/packages/views/layout/index.tsindex d667266029..992eda5971 100644--- a/packages/views/layout/index.ts+++ b/packages/views/layout/index.ts@@ -4,6 +4,12 @@ export {CollectionPageHeaderAction,CollectionPageState,} from "./collection-page";+export { ROUTE_ICON_COMPONENTS, routeIconForPath } from "./route-icon-components";+export {+ useTabPresentation,+ ResourceLeadingVisual,+} from "./tab-presentation";+export type { TabPresentationResult } from "./tab-presentation";export { DashboardGuard } from "./dashboard-guard";export { DashboardLayout } from "./dashboard-layout";export { useDashboardGuard } from "./use-dashboard-guard";diff --git a/packages/views/layout/route-icon-components.test.tsx b/packages/views/layout/route-icon-components.test.tsxnew file mode 100644index 0000000000..82323b08c4--- /dev/null+++ b/packages/views/layout/route-icon-components.test.tsx@@ -0,0 +1,39 @@+import { describe, it, expect } from "vitest";+import { paths, WORKSPACE_PAGES, DEFAULT_ROUTE_ICON_NAME } from "@multica/core/paths";+import { ROUTE_ICON_COMPONENTS, routeIconForPath } from "./route-icon-components";++describe("ROUTE_ICON_COMPONENTS", () => {+ it("has a component for every page icon", () => {+ const missing = Object.values(WORKSPACE_PAGES)+ .map((page) => page.icon)+ .filter((name) => !ROUTE_ICON_COMPONENTS[name]);+ expect(missing).toEqual([]);+ });+});++describe("routeIconForPath", () => {+ // The invariant this whole contract exists for (MUL-4370): the sidebar and+ // the desktop tab bar both resolve from a path, so the same route can never+ // render two different icons.+ it("gives a route the same component wherever it is rendered", () => {+ const p = paths.workspace("acme");+ for (const href of [p.projects(), p.autopilots(), p.chat(), p.squads(), p.usage()]) {+ // Sidebar passes the bare nav href; a tab passes its own url, which for+ // a sub-route carries extra segments.+ expect(routeIconForPath(`${href}/some-id`)).toBe(routeIconForPath(href));+ }+ });++ it("resolves distinct components for distinct routes", () => {+ const p = paths.workspace("acme");+ expect(routeIconForPath(p.projects())).not.toBe(routeIconForPath(p.issues()));+ expect(routeIconForPath(p.autopilots())).not.toBe(routeIconForPath(p.issues()));+ });++ it("returns the default component instead of undefined for an unknown route", () => {+ expect(routeIconForPath("/acme/not-a-route")).toBe(+ ROUTE_ICON_COMPONENTS[DEFAULT_ROUTE_ICON_NAME],+ );+ expect(routeIconForPath("")).toBe(ROUTE_ICON_COMPONENTS[DEFAULT_ROUTE_ICON_NAME]);+ });+});diff --git a/packages/views/layout/route-icon-components.tsx b/packages/views/layout/route-icon-components.tsxnew file mode 100644index 0000000000..0173bebf2f--- /dev/null+++ b/packages/views/layout/route-icon-components.tsx@@ -0,0 +1,72 @@+import {+ Inbox,+ MessageSquare,+ CircleUser,+ ListTodo,+ FolderKanban,+ Zap,+ Bot,+ Users,+ BarChart3,+ Monitor,+ Server,+ BookOpenText,+ Settings,+ File,+ FileText,+ FileImage,+ FileCode,+ FileArchive,+ FileAudio,+ FileVideo,+ FileQuestion,+ type LucideIcon,+} from "lucide-react";+import { resolveRouteIconName, type RouteIconName } from "@multica/core/paths";++/**+ * Icon name → component registry: the rendering half of the route icon+ * contract defined in `@multica/core/paths`.+ *+ * Every {@link RouteIconName} must have an entry — the `Record` type makes a+ * missing key a compile error.+ */+export const ROUTE_ICON_COMPONENTS: Record<RouteIconName, LucideIcon> = {+ Inbox,+ MessageSquare,+ CircleUser,+ ListTodo,+ FolderKanban,+ Zap,+ Bot,+ Users,+ BarChart3,+ Monitor,+ Server,+ BookOpenText,+ Settings,+ File,+ FileText,+ FileImage,+ FileCode,+ FileArchive,+ FileAudio,+ FileVideo,+ FileQuestion,+};++/**+ * Resolve the icon component for a workspace-scoped path or full tab URL.+ *+ * This is the only entry point navigation surfaces should use: it takes the+ * path they already have rather than an icon name, so no caller has to hold,+ * persist, or cast an icon name. `resolveRouteIconName` always returns a+ * valid name and the registry is total, so the result is never undefined — an+ * unknown route falls back to the default icon instead of rendering nothing.+ *+ * The sidebar nav and the desktop tab bar both call this, which is what keeps+ * a route's icon identical in both places.+ */+export function routeIconForPath(path: string): LucideIcon {+ return ROUTE_ICON_COMPONENTS[resolveRouteIconName(path)];+}diff --git a/packages/views/layout/tab-presentation.test.tsx b/packages/views/layout/tab-presentation.test.tsxnew file mode 100644index 0000000000..733acd3d19--- /dev/null+++ b/packages/views/layout/tab-presentation.test.tsx@@ -0,0 +1,261 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import type { ReactNode } from "react";+import { render, renderHook } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { issueDetailOptions } from "@multica/core/issues/queries";+import { projectDetailOptions } from "@multica/core/projects/queries";+import { chatSessionsOptions } from "@multica/core/chat/queries";+import {+ inboxListOptions,+ archivedInboxListOptions,+} from "@multica/core/inbox/queries";+import { agentListOptions } from "@multica/core/workspace/queries";+import { runtimeListOptions } from "@multica/core/runtimes/queries";++// Mutable workspace stub so a test can simulate "workspace not resolved yet".+const ws = vi.hoisted(() => ({ current: { id: "ws1", slug: "acme" } as { id: string; slug: string } | null }));++vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/paths")>()),+ useCurrentWorkspace: () => ws.current,+}));++vi.mock("../i18n", async () => {+ const layout = (await import("../locales/en/layout.json")).default;+ const chat = (await import("../locales/en/chat.json")).default;+ const bundles: Record<string, unknown> = { layout, chat };+ return {+ useT: (ns: string) => ({+ t: (select: (b: Record<string, unknown>) => string) =>+ select(bundles[ns] as Record<string, unknown>),+ }),+ };+});++// ActorAvatar reaches into workspace directory queries; the hook returns a+// descriptor (not the rendered avatar), so the render test stubs it.+vi.mock("../common/actor-avatar", () => ({+ ActorAvatar: ({ actorType, actorId }: { actorType: string; actorId: string }) => (+ <span data-testid="actor-avatar" data-actor={`${actorType}:${actorId}`} />+ ),+}));++import { useTabPresentation, ResourceLeadingVisual } from "./tab-presentation";++function makeClient() {+ return new QueryClient({ defaultOptions: { queries: { retry: false } } });+}++function seed(qc: QueryClient) {+ qc.setQueryData(issueDetailOptions("ws1", "i1").queryKey, {+ id: "i1",+ identifier: "MUL-1",+ title: "Fix login",+ status: "in_progress",+ } as never);+ qc.setQueryData(issueDetailOptions("ws1", "i9").queryKey, {+ id: "i9",+ identifier: "MUL-9",+ title: "Crash",+ status: "todo",+ } as never);+ qc.setQueryData(projectDetailOptions("ws1", "p1").queryKey, {+ id: "p1",+ icon: "🚀",+ title: "Apollo",+ } as never);+ qc.setQueryData(chatSessionsOptions("ws1").queryKey, [+ { id: "s1", title: "Deploy plan", status: "active" },+ { id: "s2", title: " ", status: "active" },+ ] as never);+ qc.setQueryData(inboxListOptions("ws1").queryKey, [+ { id: "n1", issue_id: "i9", title: "Assigned to you", type: "issue_assigned" },+ { id: "n2", issue_id: null, title: "Quick create failed", type: "quick_create_failed" },+ ] as never);+ // Archived list is a distinct cache; these items are NOT in the main list.+ qc.setQueryData(archivedInboxListOptions("ws1").queryKey, [+ { id: "a1", issue_id: "i1", title: "Old assignment", type: "issue_assigned" },+ { id: "a2", issue_id: null, title: "Archived note", type: "quick_create_failed" },+ ] as never);+ qc.setQueryData(agentListOptions("ws1").queryKey, [+ { id: "ag1", name: "Robby", avatar_url: null },+ ] as never);+ qc.setQueryData(runtimeListOptions("ws1").queryKey, [+ { id: "rt1", name: "Claude (host)", custom_name: "Prod Box", status: "online" },+ ] as never);+}++function presentationOf(url: string, fallback?: string) {+ const qc = makeClient();+ seed(qc);+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ return renderHook(() => useTabPresentation(url, fallback), { wrapper }).result+ .current;+}++beforeEach(() => {+ ws.current = { id: "ws1", slug: "acme" };+});++describe("useTabPresentation — live from cache", () => {+ it("page: page icon + localized page name", () => {+ expect(presentationOf("/acme/issues")).toEqual({+ visual: { kind: "icon", icon: "ListTodo" },+ title: "Issues",+ });+ });++ it("issue: live status glyph + identifier:title", () => {+ expect(presentationOf("/acme/issues/i1")).toEqual({+ visual: { kind: "issue-status", status: "in_progress" },+ title: "MUL-1: Fix login",+ });+ });++ it("project: own icon + title", () => {+ expect(presentationOf("/acme/projects/p1")).toEqual({+ visual: { kind: "project-icon", icon: "🚀" },+ title: "Apollo",+ });+ });++ it("actor: avatar visual + resolved name", () => {+ expect(presentationOf("/acme/agents/ag1")).toEqual({+ visual: { kind: "actor", actorType: "agent", id: "ag1" },+ title: "Robby",+ });+ });++ it("machine tab uses the runtime's custom name over the raw daemon name", () => {+ expect(presentationOf("/acme/runtimes/rt1")).toEqual({+ visual: { kind: "icon", icon: "Monitor" },+ title: "Prod Box",+ });+ });++ it("chat container: MessageSquare icon + session title", () => {+ expect(presentationOf("/acme/chat?session=s1")).toEqual({+ visual: { kind: "icon", icon: "MessageSquare" },+ title: "Deploy plan",+ });+ });++ it("chat container: blank session title uses the New chat fallback", () => {+ expect(presentationOf("/acme/chat?session=s2").title).toBe("New chat");+ });++ it("chat container: no session stays Chat", () => {+ expect(presentationOf("/acme/chat")).toEqual({+ visual: { kind: "icon", icon: "MessageSquare" },+ title: "Chat",+ });+ });++ it("inbox container: selected issue shows Inbox icon + issue title", () => {+ // Selection key is issue_id ?? id — n1 links issue i9.+ expect(presentationOf("/acme/inbox?issue=i9")).toEqual({+ visual: { kind: "icon", icon: "Inbox" },+ title: "MUL-9: Crash",+ });+ });++ it("inbox container: selected non-issue shows its display title", () => {+ expect(presentationOf("/acme/inbox?issue=n2")).toEqual({+ visual: { kind: "icon", icon: "Inbox" },+ title: "Quick create failed",+ });+ });++ it("archived inbox: selected issue resolves against the archived list", () => {+ // a1 lives only in the archived list; without ?view=archived it must NOT+ // resolve (title stays Inbox), and with it, it resolves to i1's title.+ expect(presentationOf("/acme/inbox?issue=i1").title).toBe("Inbox");+ expect(presentationOf("/acme/inbox?view=archived&issue=i1")).toEqual({+ visual: { kind: "icon", icon: "Inbox" },+ title: "MUL-1: Fix login",+ });+ });++ it("archived inbox: selected non-issue resolves against the archived list", () => {+ expect(presentationOf("/acme/inbox?view=archived&issue=a2")).toEqual({+ visual: { kind: "icon", icon: "Inbox" },+ title: "Archived note",+ });+ });++ it("attachment: filename from ?name= drives the title and file icon", () => {+ expect(presentationOf("/acme/attachments/att1/preview?name=diagram.png")).toEqual({+ visual: { kind: "icon", icon: "FileImage" },+ title: "diagram.png",+ });+ // Missing filename → generic File + localized "Attachment".+ expect(presentationOf("/acme/attachments/att1/preview")).toEqual({+ visual: { kind: "icon", icon: "File" },+ title: "Attachment",+ });+ });+});++describe("useTabPresentation — pending / fallback", () => {+ it("pending issue keeps the issue-status slot and uses the persisted fallback", () => {+ expect(presentationOf("/acme/issues/unloaded", "MUL-7: Prior")).toEqual({+ visual: { kind: "issue-status", status: null },+ title: "MUL-7: Prior",+ });+ });++ it("pending issue with no fallback shows the localized type label, not Issues", () => {+ const p = presentationOf("/acme/issues/unloaded");+ expect(p.visual).toEqual({ kind: "issue-status", status: null });+ expect(p.title).toBe("Issue");+ });++ it("unknown route is neutral, never Issues", () => {+ expect(presentationOf("/acme/mystery")).toEqual({+ visual: { kind: "icon", icon: "FileQuestion" },+ title: "Unknown page",+ });+ });++ it("actor falls back to a type icon before the workspace resolves", () => {+ ws.current = null;+ expect(presentationOf("/acme/agents/ag1").visual).toEqual({+ kind: "icon",+ icon: "Bot",+ });+ });+});++describe("ResourceLeadingVisual", () => {+ it("renders a project icon with its emoji", () => {+ const { getByText } = render(+ <ResourceLeadingVisual visual={{ kind: "project-icon", icon: "🚀" }} />,+ );+ expect(getByText("🚀")).toBeTruthy();+ });++ it("renders a status glyph for an issue", () => {+ const { container } = render(+ <ResourceLeadingVisual visual={{ kind: "issue-status", status: "done" }} />,+ );+ expect(container.querySelector("svg")).toBeTruthy();+ });++ it("renders the actor avatar for an actor visual", () => {+ const { getByTestId } = render(+ <ResourceLeadingVisual+ visual={{ kind: "actor", actorType: "agent", id: "ag1" }}+ />,+ );+ expect(getByTestId("actor-avatar").getAttribute("data-actor")).toBe("agent:ag1");+ });++ it("renders a lucide icon for a plain icon visual", () => {+ const { container } = render(+ <ResourceLeadingVisual visual={{ kind: "icon", icon: "Inbox" }} />,+ );+ expect(container.querySelector("svg")).toBeTruthy();+ });+});diff --git a/packages/views/layout/tab-presentation.tsx b/packages/views/layout/tab-presentation.tsxnew file mode 100644index 0000000000..bd2beb94fd--- /dev/null+++ b/packages/views/layout/tab-presentation.tsx@@ -0,0 +1,301 @@+"use client";++import { useMemo } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ parseTabSubject,+ resolveTabPresentation,+ useCurrentWorkspace,+ type TabSubject,+ type TabVisual,+ type TabTitleSpec,+ type TabEntityData,+ type TabLabelKey,+} from "@multica/core/paths";+import { issueDetailOptions } from "@multica/core/issues/queries";+import { projectDetailOptions } from "@multica/core/projects/queries";+import { autopilotDetailOptions } from "@multica/core/autopilots/queries";+import {+ skillDetailOptions,+ agentListOptions,+ memberListOptions,+ squadListOptions,+} from "@multica/core/workspace/queries";+import { runtimeListOptions } from "@multica/core/runtimes/queries";+import { runtimeDisplayName } from "@multica/core/runtimes";+import { chatSessionsOptions } from "@multica/core/chat/queries";+import {+ inboxListOptions,+ archivedInboxListOptions,+} from "@multica/core/inbox/queries";+import { cn } from "@multica/ui/lib/utils";+import { StatusIcon } from "../issues/components";+import { ProjectIcon } from "../projects/components/project-icon";+import { ActorAvatar } from "../common/actor-avatar";+import { getInboxDisplayTitle } from "../inbox/components/inbox-display";+import { useT } from "../i18n";+import { ROUTE_ICON_COMPONENTS } from "./route-icon-components";++/**+ * Desktop tab presentation: turn a tab URL into a leading visual and a title,+ * live from the query cache. This is the view half of the contract whose pure+ * core is `@multica/core/paths` (`parseTabSubject` + `resolveTabPresentation`).+ *+ * Cache-only reads: every query in `useTabEntityData` is `enabled: false`. It+ * observes whatever the pages/directory already loaded and re-renders when that+ * data changes, so an open tab's icon/title stay in sync (project renamed,+ * issue status changed, chat session retitled) without amplifying requests. A+ * resource that has not loaded yet renders a stable type fallback until its+ * page fills the cache.+ *+ * The one exception is an actor tab's avatar: `ResourceLeadingVisual` renders+ * `ActorAvatar`, which loads the (workspace-global, sidebar-warmed) member /+ * agent / squad directories itself. That is intentional — it resolves the+ * avatar and, in turn, the name this hook reads from the same lists.+ */++// Placeholder id for a detail query that this tab doesn't need — its key is+// never populated, so the read returns undefined without any fetch.+const NONE = "__tab_presentation_none__";++// Resource kinds where a persisted title is a good first-frame fallback while+// the live data loads. Flow/unknown/attachment always use their type label.+const PENDING_RESOURCE_KEYS: ReadonlySet<TabLabelKey> = new Set<TabLabelKey>([+ "issue",+ "project",+ "autopilot",+ "agent",+ "member",+ "squad",+ "skill",+ "machine",+ "runtime",+]);++/** Gather cached entity data for a subject. All reads are cache-only. */+function useTabEntityData(subject: TabSubject, wsId: string): TabEntityData {+ const { t: chatT } = useT("chat");++ // Read both inbox lists cache-only; the archived view keeps its own list, so+ // an archived selection has to resolve against the archived cache — the same+ // list the InboxPage populates when `?view=archived` is active.+ const inboxList = useQuery({ ...inboxListOptions(wsId), enabled: false }).data;+ const archivedInboxList = useQuery({+ ...archivedInboxListOptions(wsId),+ enabled: false,+ }).data;+ const activeInboxList =+ subject.kind === "inbox" && subject.archived ? archivedInboxList : inboxList;+ const inboxItem =+ subject.kind === "inbox" && subject.selectedKey+ ? (activeInboxList?.find(+ (i) => (i.issue_id ?? i.id) === subject.selectedKey,+ ) ?? null)+ : null;++ // One issue query serves both a direct issue tab and an inbox-selected issue.+ const issueId =+ subject.kind === "issue"+ ? subject.id+ : (inboxItem?.issue_id ?? "");+ const issue = useQuery({+ ...issueDetailOptions(wsId, issueId || NONE),+ enabled: false,+ }).data;++ const project = useQuery({+ ...projectDetailOptions(wsId, subject.kind === "project" ? subject.id : NONE),+ enabled: false,+ }).data;+ const autopilot = useQuery({+ ...autopilotDetailOptions(+ wsId,+ subject.kind === "autopilot" ? subject.id : NONE,+ ),+ enabled: false,+ }).data;+ const skill = useQuery({+ ...skillDetailOptions(wsId, subject.kind === "skill" ? subject.id : NONE),+ enabled: false,+ }).data;++ const agents = useQuery({ ...agentListOptions(wsId), enabled: false }).data;+ const members = useQuery({ ...memberListOptions(wsId), enabled: false }).data;+ const squads = useQuery({ ...squadListOptions(wsId), enabled: false }).data;+ const runtimes = useQuery({ ...runtimeListOptions(wsId), enabled: false }).data;+ const sessions = useQuery({ ...chatSessionsOptions(wsId), enabled: false }).data;++ const data: TabEntityData = {};+ switch (subject.kind) {+ case "issue":+ if (issue) {+ data.issue = {+ identifier: issue.identifier,+ title: issue.title,+ status: issue.status,+ };+ }+ break;+ case "project":+ if (project) data.project = { icon: project.icon, title: project.title };+ break;+ case "autopilot":+ if (autopilot) data.autopilot = { title: autopilot.autopilot.title };+ break;+ case "skill":+ if (skill) data.skill = { name: skill.name };+ break;+ case "actor": {+ const name =+ subject.actorType === "agent"+ ? agents?.find((a) => a.id === subject.id)?.name+ : subject.actorType === "member"+ ? members?.find((m) => m.user_id === subject.id)?.name+ : squads?.find((s) => s.id === subject.id)?.name;+ if (name) data.actorName = name;+ break;+ }+ case "machine": {+ const rt = runtimes?.find((r) => r.id === subject.machineId);+ if (rt) data.machine = { name: runtimeDisplayName(rt) };+ break;+ }+ case "runtime": {+ const rt = runtimes?.find((r) => r.id === subject.runtimeId);+ if (rt) data.runtime = { name: runtimeDisplayName(rt) };+ break;+ }+ case "chat":+ if (subject.sessionId) {+ const s = sessions?.find((x) => x.id === subject.sessionId);+ if (s) data.chatSessionTitle = s.title?.trim() || chatT(($) => $.window.untitled);+ }+ break;+ case "inbox":+ if (inboxItem) {+ if (inboxItem.issue_id && issue) {+ data.inboxSelection = {+ kind: "issue",+ identifier: issue.identifier,+ title: issue.title,+ };+ } else if (!inboxItem.issue_id) {+ data.inboxSelection = {+ kind: "item",+ title: getInboxDisplayTitle(inboxItem),+ };+ }+ }+ break;+ }+ return data;+}++/** Localize a title spec, preferring a persisted fallback while pending. */+function useTabTitle(spec: TabTitleSpec, fallbackTitle?: string): string {+ const { t: layoutT } = useT("layout");+ switch (spec.kind) {+ case "text":+ return spec.text;+ case "nav":+ return layoutT(($) => $.nav[spec.navKey]);+ case "tab": {+ if (PENDING_RESOURCE_KEYS.has(spec.tabKey)) {+ const clean = fallbackTitle?.trim();+ if (clean) return clean;+ }+ return layoutT(($) => $.tab[spec.tabKey]);+ }+ }+}++export interface TabPresentationResult {+ visual: TabVisual;+ title: string;+}++/**+ * Resolve a tab URL into its live leading visual and title.+ *+ * `fallbackTitle` (the tab's persisted title) is used only as a first-frame+ * fallback for a still-loading resource; once the cache resolves, the live+ * presentation wins.+ */+export function useTabPresentation(+ url: string,+ fallbackTitle?: string,+): TabPresentationResult {+ const subject = useMemo(() => parseTabSubject(url), [url]);+ const ws = useCurrentWorkspace();+ const wsId = ws?.id ?? "";+ const data = useTabEntityData(subject, wsId);+ const { visual, title: titleSpec } = resolveTabPresentation(subject, data);+ const title = useTabTitle(titleSpec, fallbackTitle);++ // The actor avatar resolves through workspace directory queries and throws+ // if rendered before the workspace exists. Until it does, show a type icon.+ const safeVisual: TabVisual =+ visual.kind === "actor" && !wsId+ ? {+ kind: "icon",+ icon:+ visual.actorType === "squad"+ ? "Users"+ : visual.actorType === "member"+ ? "CircleUser"+ : "Bot",+ }+ : visual;++ return { visual: safeVisual, title };+}++/**+ * Render a tab's leading visual into a fixed 16×16 slot so the tab never+ * reflows when the visual resolves from a type fallback to the real identity.+ * Shared by the desktop tab bar (and reusable by any resource row that wants+ * the same identity rules).+ */+export function ResourceLeadingVisual({+ visual,+ className,+}: {+ visual: TabVisual;+ className?: string;+}) {+ let inner: React.ReactNode;+ switch (visual.kind) {+ case "icon": {+ const Icon = ROUTE_ICON_COMPONENTS[visual.icon];+ inner = <Icon className="size-3.5" />;+ break;+ }+ case "issue-status":+ // A null status (loading) renders StatusIcon's neutral fallback glyph.+ inner = <StatusIcon status={visual.status ?? ""} className="size-3.5" />;+ break;+ case "project-icon":+ inner = <ProjectIcon project={{ icon: visual.icon }} size="sm" />;+ break;+ case "actor":+ inner = (+ <ActorAvatar+ actorType={visual.actorType}+ actorId={visual.id}+ size="xs"+ profileLink={false}+ />+ );+ break;+ }+ return (+ <span+ className={cn(+ "flex size-4 shrink-0 items-center justify-center",+ className,+ )}+ >+ {inner}+ </span>+ );+}diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.jsonindex 7b5cafa663..bf814d15af 100644--- a/packages/views/locales/en/layout.json+++ b/packages/views/locales/en/layout.json@@ -13,6 +13,20 @@"skills": "Skills","settings": "Settings"},+ "tab": {+ "issue": "Issue",+ "project": "Project",+ "autopilot": "Autopilot",+ "agent": "Agent",+ "member": "Member",+ "squad": "Squad",+ "skill": "Skill",+ "machine": "Machine",+ "runtime": "Runtime",+ "attachment": "Attachment",+ "create_agent": "Create Agent",+ "unknown": "Unknown page"+ },"help": {"trigger": "Help","docs": "Docs",diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.jsonindex c9f111e816..9bf755b82a 100644--- a/packages/views/locales/ja/layout.json+++ b/packages/views/locales/ja/layout.json@@ -13,6 +13,20 @@"skills": "スキル","settings": "設定"},+ "tab": {+ "issue": "イシュー",+ "project": "プロジェクト",+ "autopilot": "オートパイロット",+ "agent": "エージェント",+ "member": "メンバー",+ "squad": "スクワッド",+ "skill": "スキル",+ "machine": "マシン",+ "runtime": "ランタイム",+ "attachment": "添付ファイル",+ "create_agent": "エージェントを作成",+ "unknown": "不明なページ"+ },"help": {"trigger": "ヘルプ","docs": "ドキュメント",diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.jsonindex 8d6b392951..b42412ff0e 100644--- a/packages/views/locales/ko/layout.json+++ b/packages/views/locales/ko/layout.json@@ -13,6 +13,20 @@"skills": "스킬","settings": "설정"},+ "tab": {+ "issue": "이슈",+ "project": "프로젝트",+ "autopilot": "오토파일럿",+ "agent": "에이전트",+ "member": "멤버",+ "squad": "스쿼드",+ "skill": "스킬",+ "machine": "머신",+ "runtime": "런타임",+ "attachment": "첨부파일",+ "create_agent": "에이전트 만들기",+ "unknown": "알 수 없는 페이지"+ },"help": {"trigger": "도움말","docs": "문서",diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.jsonindex 3e696f1a70..983fbc8033 100644--- a/packages/views/locales/zh-Hans/layout.json+++ b/packages/views/locales/zh-Hans/layout.json@@ -13,6 +13,20 @@"skills": "Skills","settings": "设置"},+ "tab": {+ "issue": "Issue",+ "project": "项目",+ "autopilot": "自动化",+ "agent": "智能体",+ "member": "成员",+ "squad": "小队",+ "skill": "Skill",+ "machine": "机器",+ "runtime": "运行时",+ "attachment": "附件",+ "create_agent": "创建智能体",+ "unknown": "未知页面"+ },"help": {"trigger": "帮助","docs": "文档",diff --git a/packages/views/package.json b/packages/views/package.jsonindex dd63d1649f..566edee0f5 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -38,6 +38,7 @@"./workspace/welcome-after-onboarding": "./workspace/welcome-after-onboarding.tsx","./workspace/use-workspace-seen": "./workspace/use-workspace-seen.ts","./layout": "./layout/index.ts",+ "./layout/route-icon-components": "./layout/route-icon-components.tsx","./auth": "./auth/index.ts","./search": "./search/index.ts","./chat": "./chat/index.ts",diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsxindex 60e08b9128..f1a866babf 100644--- a/packages/views/search/search-command.test.tsx+++ b/packages/views/search/search-command.test.tsx@@ -160,7 +160,10 @@ vi.mock("@multica/core", () => ({useWorkspaceId: () => "ws-test",}));-vi.mock("@multica/core/paths", () => ({+vi.mock("@multica/core/paths", async (importOriginal) => ({+ // Spread the real module so pure helpers (resolveRouteIconName, used to+ // derive each nav page's icon from its href) stay intact.+ ...(await importOriginal<typeof import("@multica/core/paths")>()),useWorkspacePaths: () => ({inbox: () => "/ws-test/inbox",myIssues: () => "/ws-test/my-issues",diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsxindex f10b33fc6b..f4a8dda491 100644--- a/packages/views/search/search-command.tsx+++ b/packages/views/search/search-command.tsx@@ -11,18 +11,11 @@ import {MessageSquare,Plus,SearchIcon,- Inbox,- CircleUser,ListChevronsDownUp,ListChevronsUpDown,- ListTodo,- FolderKanban,- Bot,Monitor,Moon,Sun,- BookOpenText,- Settings,type LucideIcon,} from "lucide-react";import { Command as CommandPrimitive } from "cmdk";@@ -52,6 +45,7 @@ import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import { StatusIcon } from "../issues/components";import { resolvedThreadRootIds, rootCommentIds } from "../issues/components/thread-utils";import { ProjectIcon } from "../projects/components/project-icon";+import { routeIconForPath } from "../layout/route-icon-components";import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";import type { ProjectStatus } from "@multica/core/types";import { ActorAvatar } from "../common/actor-avatar";@@ -85,10 +79,12 @@ type NavKey =| "skills"| "settings";+// No `icon` field: like the sidebar nav, a page's icon is derived from its+// destination path via routeIconForPath, so all navigation surfaces show the+// same icon for the same route.interface NavPage {key: NavKey;label: string;- icon: LucideIcon;keywords: string[];}@@ -148,14 +144,14 @@ interface SearchResults {export function SearchCommand() {const { t } = useT("search");const navPages: NavPage[] = [- { key: "inbox", label: t(($) => $.pages.inbox), icon: Inbox, keywords: ["inbox", "notifications", "收件箱"] },- { key: "myIssues", label: t(($) => $.pages.my_issues), icon: CircleUser, keywords: ["my", "issues", "assigned", "我的"] },- { key: "issues", label: t(($) => $.pages.issues), icon: ListTodo, keywords: ["issues", "tasks", "bugs"] },- { key: "projects", label: t(($) => $.pages.projects), icon: FolderKanban, keywords: ["projects", "kanban", "项目"] },- { key: "agents", label: t(($) => $.pages.agents), icon: Bot, keywords: ["agents", "bots", "ai"] },- { key: "runtimes", label: t(($) => $.pages.runtimes), icon: Monitor, keywords: ["runtimes", "environments"] },- { key: "skills", label: t(($) => $.pages.skills), icon: BookOpenText, keywords: ["skills", "library"] },- { key: "settings", label: t(($) => $.pages.settings), icon: Settings, keywords: ["settings", "config", "preferences", "设置"] },+ { key: "inbox", label: t(($) => $.pages.inbox), keywords: ["inbox", "notifications", "收件箱"] },+ { key: "myIssues", label: t(($) => $.pages.my_issues), keywords: ["my", "issues", "assigned", "我的"] },+ { key: "issues", label: t(($) => $.pages.issues), keywords: ["issues", "tasks", "bugs"] },+ { key: "projects", label: t(($) => $.pages.projects), keywords: ["projects", "kanban", "项目"] },+ { key: "agents", label: t(($) => $.pages.agents), keywords: ["agents", "bots", "ai"] },+ { key: "runtimes", label: t(($) => $.pages.runtimes), keywords: ["runtimes", "environments"] },+ { key: "skills", label: t(($) => $.pages.skills), keywords: ["skills", "library"] },+ { key: "settings", label: t(($) => $.pages.settings), keywords: ["settings", "config", "preferences", "设置"] },];const { push, pathname, getShareableUrl } = useNavigation();const open = useSearchStore((s) => s.open);@@ -533,19 +529,22 @@ export function SearchCommand() {<div className="px-3 py-1.5 text-xs font-medium text-muted-foreground">{t(($) => $.groups.pages)}</div>- {filteredPages.map((page) => (+ {filteredPages.map((page) => {+ const PageIcon = routeIconForPath(p[page.key]());+ return (<CommandPrimitive.Itemkey={page.key}value={`page:${page.key}`}onSelect={() => handlePageSelect(page.key)}className="flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent">- <page.icon className="size-4 shrink-0 text-muted-foreground" />+ <PageIcon className="size-4 shrink-0 text-muted-foreground" /><span className="truncate"><HighlightText text={page.label} query={query} /></span></CommandPrimitive.Item>- ))}+ );+ })}</CommandPrimitive.Group>)}