Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7978: feat(search): switch workspaces from the Mod+K palette (#9195)
Timbd046606048b
diff --git a/apps/desktop/src/renderer/src/platform/navigation.test.tsx b/apps/desktop/src/renderer/src/platform/navigation.test.tsxindex fdddff40d9..52f3bdd651 100644--- a/apps/desktop/src/renderer/src/platform/navigation.test.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.test.tsx@@ -142,6 +142,50 @@ describe("push", () => {expect(getActiveTab(s)?.url).toBe("/butter/inbox");});+ // The workspace switchers (sidebar dropdown, Mod+K palette) push the+ // target's Issues root, which is where web lands. On desktop that resumes+ // the workspace where the user left it instead. NoAccessPage recovers with+ // replace() to the same kind of path, so both methods are covered.+ it.each(["push", "replace"] as const)(+ "%s to another workspace's Issues root restores its last active tab",+ (method) => {+ const store = useTabStore.getState();+ store.switchWorkspace("butter", "/butter/projects");+ store.switchWorkspace("acme");+ const getAdapter = renderProvider();++ getAdapter()[method]("/butter/issues");++ const s = useTabStore.getState();+ expect(s.activeWorkspaceSlug).toBe("butter");+ expect(getActiveTab(s)?.url).toBe("/butter/projects");+ expect(s.byWorkspace.butter.tabs.map((t) => t.url)).toEqual([+ "/butter/projects",+ ]);+ },+ );++ it("lands on Issues when switching to a workspace with no tabs yet", () => {+ const getAdapter = renderProvider();++ getAdapter().push("/butter/issues");++ expect(getActiveTab(useTabStore.getState())?.url).toBe("/butter/issues");+ });++ it("still opens a deeper cross-workspace path under Issues", () => {+ const store = useTabStore.getState();+ store.switchWorkspace("butter", "/butter/projects");+ store.switchWorkspace("acme");+ const getAdapter = renderProvider();++ getAdapter().push("/butter/issues/BUT-1");++ expect(getActiveTab(useTabStore.getState())?.url).toBe(+ "/butter/issues/BUT-1",+ );+ });+it("logs out instead of navigating for /login", () => {const getAdapter = renderProvider();diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex 95408f7b31..b469b05dfd 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -5,7 +5,7 @@ import {type NavigationAdapter,} from "@multica/views/navigation";import { useAuthStore } from "@multica/core/auth";-import { isReservedSlug } from "@multica/core/paths";+import { isReservedSlug, paths } from "@multica/core/paths";import {useTabStore,getActiveTab,@@ -86,13 +86,18 @@ function tryRouteToOverlay(path: string): boolean {* invite-accept flow — they all call `useNavigation().push(path)` with a* full workspace URL, and on desktop we translate "target slug differs* from active" into "switch the tab-group that's visible in the TabBar".+ *+ * The target's bare Issues root (what the workspace switchers send, and where+ * web lands) resumes the workspace's last active tab instead, or Issues if it+ * has none. Any deeper path opens exactly that path.*/function tryRouteToOtherWorkspace(path: string): boolean {const targetSlug = extractWorkspaceSlug(path);if (!targetSlug) return false;const { activeWorkspaceSlug, switchWorkspace } = useTabStore.getState();if (targetSlug === activeWorkspaceSlug) return false;- switchWorkspace(targetSlug, path);+ const resume = path === paths.workspace(targetSlug).issues();+ switchWorkspace(targetSlug, resume ? undefined : path);return true;}diff --git a/packages/views/locales/en/search.json b/packages/views/locales/en/search.jsonindex 75ddb7b1be..64a1294dac 100644--- a/packages/views/locales/en/search.json+++ b/packages/views/locales/en/search.json@@ -9,7 +9,8 @@"projects": "Projects","issues": "Issues","cancelled": "Cancelled",- "recent": "Recent"+ "recent": "Recent",+ "workspaces": "Workspaces"},"commands": {"current_theme_aria": "Current theme",diff --git a/packages/views/locales/fr/search.json b/packages/views/locales/fr/search.jsonindex 5278fe3975..ea7ee02b9f 100644--- a/packages/views/locales/fr/search.json+++ b/packages/views/locales/fr/search.json@@ -9,7 +9,8 @@"projects": "Projets","issues": "Tâches","cancelled": "Annulés",- "recent": "Récents"+ "recent": "Récents",+ "workspaces": "Espaces de travail"},"commands": {"current_theme_aria": "Thème actuel",diff --git a/packages/views/locales/ja/search.json b/packages/views/locales/ja/search.jsonindex 8c01965030..3e51019bf7 100644--- a/packages/views/locales/ja/search.json+++ b/packages/views/locales/ja/search.json@@ -9,7 +9,8 @@"projects": "プロジェクト","issues": "タスク","cancelled": "キャンセル済み",- "recent": "最近の項目"+ "recent": "最近の項目",+ "workspaces": "ワークスペース"},"commands": {"current_theme_aria": "現在のテーマ",diff --git a/packages/views/locales/ko/search.json b/packages/views/locales/ko/search.jsonindex 4c6770991e..c4159ea288 100644--- a/packages/views/locales/ko/search.json+++ b/packages/views/locales/ko/search.json@@ -9,7 +9,8 @@"projects": "프로젝트","issues": "태스크","cancelled": "취소됨",- "recent": "최근 항목"+ "recent": "최근 항목",+ "workspaces": "워크스페이스"},"commands": {"current_theme_aria": "현재 테마",diff --git a/packages/views/locales/zh-Hans/search.json b/packages/views/locales/zh-Hans/search.jsonindex e62e4ee088..e5539b16f5 100644--- a/packages/views/locales/zh-Hans/search.json+++ b/packages/views/locales/zh-Hans/search.json@@ -9,7 +9,8 @@"projects": "项目","issues": "任务","cancelled": "已取消",- "recent": "最近"+ "recent": "最近",+ "workspaces": "工作区"},"commands": {"current_theme_aria": "当前主题",diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsxindex 50bb39633d..f94b8c966c 100644--- a/packages/views/search/search-command.test.tsx+++ b/packages/views/search/search-command.test.tsx@@ -4,7 +4,7 @@ import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";vi.mock("@multica/core/issue-statuses/hooks", () => ({useIssueStatuses: () => buildIssueStatusCatalog([]),}));-import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";import { I18nProvider } from "@multica/core/i18n/react";@@ -83,6 +83,8 @@ const {mockMembers,mockAgents,mockSquads,+ mockWorkspaces,+ mockUnreadSummary,mockOpenModal,mockToastSuccess,mockClipboardWrite,@@ -127,6 +129,18 @@ const {avatar_url: string | null;}>,},+ mockWorkspaces: {+ current: [] as Array<{+ id: string;+ name: string;+ slug: string;+ avatar_url: string | null;+ created_at: string;+ }>,+ },+ mockUnreadSummary: {+ current: [] as Array<{ workspace_id: string; count: number }>,+ },mockOpenModal: vi.fn(),mockToastSuccess: vi.fn(),mockClipboardWrite: vi.fn(() => Promise.resolve()),@@ -244,6 +258,12 @@ vi.mock("@multica/core/workspace/queries", () => ({memberListOptions: () => ({ queryKey: ["workspaces", "ws-test", "members"] }),agentListOptions: () => ({ queryKey: ["workspaces", "ws-test", "agents"] }),squadListOptions: () => ({ queryKey: ["workspaces", "ws-test", "squads"] }),+ workspaceListOptions: () => ({ queryKey: ["workspaces", "list"] }),+}));++vi.mock("@multica/core/inbox/queries", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/inbox/queries")>()),+ inboxUnreadSummaryOptions: () => ({ queryKey: ["inbox", "unread-summary"] }),}));vi.mock("@multica/core/modals", () => ({@@ -264,6 +284,12 @@ function resolveIssue(key: readonly unknown[]) {vi.mock("@tanstack/react-query", () => ({useQuery: (opts: { queryKey: readonly unknown[]; enabled?: boolean }) => {const key = opts.queryKey;+ if (key[0] === "workspaces" && key[1] === "list") {+ return { data: mockWorkspaces.current };+ }+ if (key[0] === "inbox" && key[1] === "unread-summary") {+ return { data: mockUnreadSummary.current };+ }if (key[0] === "workspaces" && key[2] === "members") {return { data: mockMembers.current };}@@ -318,6 +344,8 @@ describe("SearchCommand", () => {mockAllIssues.current = [];mockAgents.current = [];mockSquads.current = [];+ mockWorkspaces.current = [];+ mockUnreadSummary.current = [];mockSetTheme.mockReset();mockTheme.current = "system";mockPathname.current = "/ws-test/issues";@@ -564,6 +592,94 @@ describe("SearchCommand", () => {expect(useSearchStore.getState().open).toBe(false);});+ describe("workspace switching", () => {+ // Server order is created_at ascending, which is also the sidebar+ // switcher's order. "Zeta Labs" is the oldest, so an alphabetical re-sort+ // would put it last. The current workspace ("ws-test") has "workspace" in+ // its name, so the bare keyword would match it if it weren't excluded.+ beforeEach(() => {+ mockWorkspaces.current = [+ {+ id: "ws-zeta",+ name: "Zeta Labs",+ slug: "zeta",+ avatar_url: null,+ created_at: "2025-01-01T00:00:00Z",+ },+ {+ id: "ws-test",+ name: "Test Workspace",+ slug: "ws-test",+ avatar_url: null,+ created_at: "2025-06-01T00:00:00Z",+ },+ {+ id: "ws-acme",+ name: "Acme Corp",+ slug: "acme-hq",+ avatar_url: null,+ created_at: "2026-01-01T00:00:00Z",+ },+ ];+ mockUnreadSummary.current = [+ { workspace_id: "ws-acme", count: 2 },+ { workspace_id: "ws-test", count: 5 },+ ];+ });++ const workspaceRows = () =>+ within(screen.getByRole("group", { name: "Workspaces" })).getAllByRole(+ "option",+ );++ it("hides the Workspaces group on an empty query", () => {+ renderSearch();++ expect(screen.queryByText("Workspaces")).not.toBeInTheDocument();+ });++ it("matches a workspace by name and switches to it by slug on Enter", async () => {+ const user = userEvent.setup();+ renderSearch();+ const input = screen.getByPlaceholderText("Type a command or search...");++ await user.type(input, "me co");+ await waitFor(() => {+ expect(workspaceRows().map((row) => row.textContent)).toEqual([+ expect.stringContaining("Acme Corp"),+ ]);+ });++ await user.clear(input);+ await user.type(input, "acme-hq");+ await waitFor(() => expect(workspaceRows()).toHaveLength(1));+ fireEvent.keyDown(input, { key: "Enter" });++ expect(mockPush).toHaveBeenCalledWith("/acme-hq/issues");+ expect(useSearchStore.getState().open).toBe(false);+ });++ it('lists every other workspace for "workspace", oldest first, with unread dots', async () => {+ const user = userEvent.setup();+ renderSearch();++ await user.type(+ screen.getByPlaceholderText("Type a command or search..."),+ "workspace",+ );++ await waitFor(() => {+ expect(workspaceRows().map((row) => row.textContent)).toEqual([+ expect.stringContaining("Zeta Labs"),+ expect.stringContaining("Acme Corp"),+ ]);+ });+ const [zeta, acme] = workspaceRows();+ expect(within(zeta!).queryByTestId("workspace-unread-dot")).toBeNull();+ expect(within(acme!).getByTestId("workspace-unread-dot")).toBeInTheDocument();+ });+ });+it("renders recent issues from query cache joined with store visit records", () => {mockRecentItems.current = [{ id: "issue-1", visitedAt: 1000 },diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsxindex b31e80905c..1edadcb495 100644--- a/packages/views/search/search-command.tsx+++ b/packages/views/search/search-command.tsx@@ -23,9 +23,11 @@ import { Command as CommandPrimitive } from "cmdk";import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import type {+ InboxWorkspaceUnread,MemberWithUser,SearchIssueResult,SearchProjectResult,+ Workspace,} from "@multica/core/types";import { isLocalSearchReady, searchIssues, searchProjects } from "@multica/core/search-index";import { partitionAggregatedSearchResults } from "@multica/core/search/cancelled-rank";@@ -39,15 +41,17 @@ import {import { issueDetailOptions, issueTimelineOptions } from "@multica/core/issues/queries";import { useWorkspaceId } from "@multica/core";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";-import { useWorkspacePaths, WORKSPACE_PAGES } from "@multica/core/paths";+import { paths, useWorkspacePaths, WORKSPACE_PAGES } from "@multica/core/paths";import type { WorkspacePageKey, WorkspacePaths } from "@multica/core/paths";import { useModalStore } from "@multica/core/modals";import { createShortcutChord } from "@multica/core/shortcuts";-import { memberListOptions } from "@multica/core/workspace/queries";+import { memberListOptions, workspaceListOptions } from "@multica/core/workspace/queries";+import { inboxUnreadSummaryOptions, unreadWorkspaceIds } from "@multica/core/inbox/queries";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 { WorkspaceAvatar } from "../workspace/workspace-avatar";import { useProjectStatusLabels } from "../projects/components/labels";import { routeIconForPath } from "../layout/route-icon-components";import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";@@ -144,6 +148,20 @@ function matchesRow(label: string, keywords: string[], query: string) {);}+// Hidden aliases for the Workspaces group, prefix-matched like page keywords:+// typing "workspace" lists every workspace the user can switch to.+const WORKSPACE_KEYWORDS = ["switch", "workspace"];++function matchesWorkspace(workspace: Workspace, query: string) {+ return (+ matchesRow(workspace.name, WORKSPACE_KEYWORDS, query) ||+ workspace.slug.toLowerCase().includes(query)+ );+}++const EMPTY_WORKSPACES: Workspace[] = [];+const EMPTY_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];+function matchesMember(member: MemberWithUser, query: string) {return (member.name.toLowerCase().includes(query) ||@@ -353,6 +371,13 @@ export function SearchCommand() {const p: WorkspacePaths = useWorkspacePaths();const { theme, setTheme } = useTheme();const { data: members = [] } = useQuery(memberListOptions(wsId));+ // Both are account-level cache entries the sidebar's workspace switcher+ // already holds, so the Workspaces group adds no requests of its own.+ const { data: workspaces = EMPTY_WORKSPACES } = useQuery(workspaceListOptions());+ const { data: unreadSummary = EMPTY_UNREAD_SUMMARY } = useQuery(+ inboxUnreadSummaryOptions(),+ );+ const unreadWsIds = useMemo(() => unreadWorkspaceIds(unreadSummary), [unreadSummary]);// Resolve each recent issue via its cached detail entry. Recent items are// typically already in the detail cache because the user has opened them;@@ -561,10 +586,20 @@ export function SearchCommand() {.slice(0, 10);}, [members, query]);+ // The current workspace is never a switch target, so a single-workspace user+ // never sees the group. The list keeps the server's created_at order, the+ // same order as the sidebar switcher.+ const filteredWorkspaces = useMemo(() => {+ const q = query.trim().toLowerCase();+ if (!q) return [];+ return workspaces.filter((ws) => ws.id !== wsId && matchesWorkspace(ws, q));+ }, [workspaces, wsId, query]);+const hasResults =results.issues.length > 0 ||results.projects.length > 0 ||- filteredMembers.length > 0;+ filteredMembers.length > 0 ||+ filteredWorkspaces.length > 0;// Rows answering an earlier query are still painted while the next request// is in flight — that is what keeps the list from strobing on every@@ -707,6 +742,16 @@ export function SearchCommand() {[intentNavigate, consumeIntent, setOpen, p],);+ // Web lands on the target's Issues; the desktop adapter reads this same+ // push as "resume the workspace's last active tab".+ const handleWorkspaceSelect = useCallback(+ (slug: string) => {+ intentNavigate(paths.workspace(slug).issues(), consumeIntent());+ setOpen(false);+ },+ [intentNavigate, consumeIntent, setOpen],+ );+return (<Dialog open={open} onOpenChange={setOpen}><DialogContent@@ -839,6 +884,35 @@ export function SearchCommand() {</CommandPrimitive.Group>)}+ {filteredWorkspaces.length > 0 && (+ <CommandPrimitive.Group+ heading={t(($) => $.groups.workspaces)}+ className={GROUP_CLASS}+ >+ {filteredWorkspaces.map((ws) => (+ <CommandPrimitive.Item+ key={ws.id}+ value={`workspace:${ws.id}`}+ onSelect={() => handleWorkspaceSelect(ws.slug)}+ className="flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"+ >+ <WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" />+ <span className="min-w-0 flex-1 truncate">+ <HighlightText text={ws.name} query={query} />+ </span>+ {/* Same dot the sidebar switcher puts on a workspace with+ unread inbox items. */}+ {unreadWsIds.has(ws.id) && (+ <span+ data-testid="workspace-unread-dot"+ className="size-2 shrink-0 rounded-full bg-brand"+ />+ )}+ </CommandPrimitive.Item>+ ))}+ </CommandPrimitive.Group>+ )}+{/*Spinner only while there is nothing to look at. isLoading flipson the keystroke, before the 300ms debounce even fires, so