Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8636 feat(workspace): pin workspaces to the top of the switcher (#9974)
小妍儿 ✨ee8604de4741
diff --git a/e2e/workspace-pinning.spec.ts b/e2e/workspace-pinning.spec.tsnew file mode 100644index 0000000000..14774f60ba--- /dev/null+++ b/e2e/workspace-pinning.spec.ts@@ -0,0 +1,71 @@+import { test, expect } from "@playwright/test";+import pg from "pg";+import { TestApiClient } from "./fixtures";++test("workspace unread stays visible before pinning and after unpinning", async ({ page }, testInfo) => {+ const viewer = new TestApiClient();+ const owner = new TestApiClient();+ const run = `${Date.now()}-${process.pid}`;+ const viewerEmail = `workspace-pin-viewer-${run}@localhost`;+ const login = await viewer.login(viewerEmail, "Workspace pin viewer");+ const home = await viewer.ensureWorkspace("Pin home", `pin-home-${run}`);+ await viewer.markUserOnboarded();+ await owner.login(`workspace-pin-owner-${run}@localhost`, "Workspace pin owner");+ const target = await owner.ensureWorkspace("Pin target", `pin-target-${run}`);+ try {+ await owner.addMemberByEmail(viewerEmail);+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ try {+ await db.query(+ `INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, title)+ VALUES ($1, 'member', $2, 'mention', 'Workspace unread regression')`,+ [target.id, login.user.id],+ );+ } finally {+ await db.end();+ }+ await page.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, viewer.getToken());+ await page.setViewportSize({ width: 1280, height: 820 });+ await page.goto(`/${home.slug}/issues`, { waitUntil: "domcontentloaded" });+ const trigger = page.getByRole("button", { name: "Switch workspace" });+ await expect(trigger).toBeVisible({ timeout: 30000 });+ await trigger.click();+ const menu = page.getByRole("menu");+ const row = menu.getByRole("menuitem", { name: /Pin target/ });+ const dot = row.locator(".bg-brand");+ // A DOM-only assertion misses the inline span collapsing to zero size.+ await expect(dot).toBeVisible();+ const setPin = async (label: string) => {+ await row.hover();+ const response = page.waitForResponse((response) =>+ response.url().endsWith(`/api/workspaces/${target.id}/pin`)+ && response.request().method() === "PUT",+ );+ await row.getByRole("button", { name: label, exact: true }).click();+ expect((await response).status()).toBe(200);+ await expect(menu).toBeVisible();+ await expect(page).toHaveURL(new RegExp(`/${home.slug}/issues$`));+ };+ await setPin("Pin workspace");+ await page.mouse.move(600, 450);+ await expect(row.locator(".icon-pin.fill-current.text-brand")).toBeVisible();+ await setPin("Unpin workspace");+ await page.mouse.move(600, 450);+ await expect(dot).toBeVisible();+ await page.keyboard.press("Escape");+ await page.reload({ waitUntil: "domcontentloaded" });+ await trigger.click();+ await expect(dot).toBeVisible();+ await page.screenshot({+ path: testInfo.outputPath("workspace-unread-restored.png"),+ clip: { x: 0, y: 0, width: 620, height: 470 },+ });+ } finally {+ await owner.deleteWorkspace();+ await viewer.deleteWorkspace();+ }+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 31094de4ce..5f8aa54753 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -513,6 +513,8 @@ import {EMPTY_SHARE_LINK,EMPTY_SHARE_LINK_INFO,EMPTY_JOIN_SHARE_LINK_RESPONSE,+ WorkspaceListItemSchema,+ WorkspacePinnedSchema,type IssueView,type IssueViewPreference,type CreateIssueViewRequest,@@ -3152,7 +3154,17 @@ export class ApiClient {// Workspacesasync listWorkspaces(): Promise<Workspace[]> {- return this.fetch("/api/workspaces");+ const raw = await this.fetch<unknown>("/api/workspaces");+ return parseWithFallback(raw, WorkspaceListItemSchema.array(), [] as Workspace[], {+ endpoint: "GET /api/workspaces",+ }) as Workspace[];+ }++ async setWorkspacePinned(id: string, pinned: boolean): Promise<{ pinned_at: string | null }> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${id}/pin`, {+ method: "PUT", body: JSON.stringify({ pinned }),+ });+ return parseWithFallback(raw, WorkspacePinnedSchema, { pinned_at: null }, { endpoint: "PUT /api/workspaces/{id}/pin" });}async getWorkspace(id: string): Promise<Workspace> {diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 2eea5fe34b..6c138bc637 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -24,6 +24,20 @@ afterEach(() => {// app in past incidents. The contract is: a malformed response degrades to// an empty/safe shape, never throws into React.describe("ApiClient schema fallback", () => {+ describe("workspace pin responses", () => {+ it("defaults missing or malformed pinned_at to null and falls back on malformed lists", async () => {+ const ws = { id: "ws-1", name: "One", slug: "one", description: null, context: null, settings: {}, repos: [], issue_prefix: "ONE", avatar_url: null, created_at: "2026-01-01", updated_at: "2026-01-01" };+ const client = new ApiClient("https://api.example.test");+ stubFetchJson([ws, { ...ws, id: "ws-2", pinned_at: 123 }]);+ expect((await client.listWorkspaces()).map((item) => item.pinned_at)).toEqual([null, null]);+ stubFetchJson({ invalid: true });+ await expect(client.listWorkspaces()).resolves.toEqual([]);+ stubFetchJson({ pinned_at: 123 });+ await expect(client.setWorkspacePinned("ws-1", true)).resolves.toEqual({ pinned_at: null });+ expect(vi.mocked(fetch).mock.calls[0]?.[1]).toMatchObject({ method: "PUT", body: JSON.stringify({ pinned: true }) });+ });+ });+describe("GitHub repository import", () => {it("falls back safely when installation or repository responses are malformed", async () => {stubFetchJson({ installations: "not-an-array", configured: true });diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 5b3b0ef3ec..40cf1283a0 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -4055,3 +4055,17 @@ export const EMPTY_LIST_LARK_INSTALLATIONS_RESPONSE: ListLarkInstallationsResponinstallations: [],configured: false,};++// Only `pinned_at` is new here; every other field keeps its pre-schema+// leniency so one odd workspace can never empty the whole switcher.+export const WorkspaceListItemSchema = z.object({+ id: z.string(),+ name: z.string(),+ slug: z.string(),+ created_at: z.string(),+ pinned_at: z.iso.datetime({ offset: true }).nullable().optional().catch(null).default(null),+}).loose();++export const WorkspacePinnedSchema = z.object({+ pinned_at: z.iso.datetime({ offset: true }).nullable().catch(null),+});diff --git a/packages/core/types/workspace.ts b/packages/core/types/workspace.tsindex 0ee5f836c8..d1c8583d67 100644--- a/packages/core/types/workspace.ts+++ b/packages/core/types/workspace.ts@@ -17,6 +17,7 @@ export interface Workspace {avatar_url: string | null;created_at: string;updated_at: string;+ pinned_at?: string | null;}/**diff --git a/packages/core/workspace/mutations.test.tsx b/packages/core/workspace/mutations.test.tsxindex c70b86e1f7..c8aef95a53 100644--- a/packages/core/workspace/mutations.test.tsx+++ b/packages/core/workspace/mutations.test.tsx@@ -14,6 +14,7 @@ import {useCreateWorkspace,useDeleteWorkspace,useLeaveWorkspace,+ useSetWorkspacePinned,useUpdateWorkspaceMcpServer,} from "./mutations";@@ -388,3 +389,30 @@ describe("useLeaveWorkspace", () => {expect(forgetLocalSearchIndex).toHaveBeenCalledWith("ws-3");});});++describe("useSetWorkspacePinned", () => {+ it("reorders optimistically, preserves existing pin time, and rolls back failure", async () => {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const setWorkspacePinned = vi.fn<(_: string, __: boolean) => Promise<{ pinned_at: string | null }>>();+ setApiInstance({ setWorkspacePinned } as unknown as ApiClient);+ const first = makeWorkspace("first", "first");+ const second = { ...makeWorkspace("second", "second"), created_at: "2026-02-01T00:00:00Z" };+ qc.setQueryData(workspaceKeys.list(), [first, second]);+ let resolve!: (value: { pinned_at: string | null }) => void;+ setWorkspacePinned.mockImplementationOnce(() => new Promise((res) => { resolve = res; }));+ const { result } = renderHook(() => useSetWorkspacePinned(), { wrapper: createWrapper(qc) });+ let pending!: Promise<unknown>;+ await act(async () => { pending = result.current.mutateAsync({ workspaceId: "second", pinned: true }); await new Promise((res) => setTimeout(res, 0)); });+ expect(qc.getQueryData<Workspace[]>(workspaceKeys.list())?.[0]?.id).toBe("second");+ await act(async () => { resolve({ pinned_at: "2026-03-01T00:00:00Z" }); await pending; });+ expect(qc.getQueryData<Workspace[]>(workspaceKeys.list())?.[0]?.pinned_at).toBe("2026-03-01T00:00:00Z");+ setWorkspacePinned.mockResolvedValueOnce({ pinned_at: "2026-03-01T00:00:00Z" });+ await act(async () => { await result.current.mutateAsync({ workspaceId: "second", pinned: true }); });+ expect(qc.getQueryData<Workspace[]>(workspaceKeys.list())?.[0]?.pinned_at).toBe("2026-03-01T00:00:00Z");+ setWorkspacePinned.mockRejectedValueOnce(new Error("failed"));+ await act(async () => { await expect(result.current.mutateAsync({ workspaceId: "second", pinned: false })).rejects.toThrow("failed"); });+ expect(qc.getQueryData<Workspace[]>(workspaceKeys.list())?.[0]?.pinned_at).toBe("2026-03-01T00:00:00Z");+ expect(qc.getQueryState(workspaceKeys.list())?.isInvalidated).toBe(true);+ qc.clear();+ });+});diff --git a/packages/core/workspace/mutations.ts b/packages/core/workspace/mutations.tsindex 02ab3a0255..5efa6a2ec2 100644--- a/packages/core/workspace/mutations.ts+++ b/packages/core/workspace/mutations.ts@@ -5,6 +5,7 @@ import { api } from "../api";import { defaultStorage } from "../platform/storage";import { clearWorkspaceStorage } from "../platform/storage-cleanup";import { workspaceKeys } from "./queries";+import { sortWorkspaces } from "./sort-workspaces";import {markWorkspaceDeletePending,unmarkWorkspaceDeletePending,@@ -168,3 +169,30 @@ export function useRemoveAgentMcpServer(agentId: string) {return useAgentMcpMutation(agentId, (serverId: string) =>api.removeAgentMcpServer(agentId, serverId));}++export function useSetWorkspacePinned() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: ({ workspaceId, pinned }: { workspaceId: string; pinned: boolean }) =>+ api.setWorkspacePinned(workspaceId, pinned),+ onMutate: async ({ workspaceId, pinned }) => {+ await qc.cancelQueries({ queryKey: workspaceKeys.list() });+ const previous = qc.getQueryData<Workspace[]>(workspaceKeys.list());+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), (old) => old && sortWorkspaces(+ old.map((ws) => ws.id === workspaceId+ ? { ...ws, pinned_at: pinned ? ws.pinned_at ?? new Date().toISOString() : null }+ : ws),+ ));+ return { previous };+ },+ onSuccess: (data, { workspaceId }) => {+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), (old) => old && sortWorkspaces(+ old.map((ws) => ws.id === workspaceId ? { ...ws, pinned_at: data.pinned_at } : ws),+ ));+ },+ onError: (_error, _vars, context) => {+ if (context?.previous) qc.setQueryData(workspaceKeys.list(), context.previous);+ },+ onSettled: () => { void qc.invalidateQueries({ queryKey: workspaceKeys.list() }); },+ });+}diff --git a/packages/core/workspace/sort-workspaces.test.ts b/packages/core/workspace/sort-workspaces.test.tsnew file mode 100644index 0000000000..9f1528cfeb--- /dev/null+++ b/packages/core/workspace/sort-workspaces.test.ts@@ -0,0 +1,11 @@+// @vitest-environment node+import { expect, it } from "vitest";+import { sortWorkspaces } from "./sort-workspaces";+import type { Workspace } from "../types";++it("sorts pinned newest first and unpinned oldest first without mutating input", () => {+ const ws = (id: string, created_at: string, pinned_at: string | null = null) => ({ id, created_at, pinned_at }) as Workspace;+ const input = [ws("late", "2026-02-01"), ws("early", "2026-01-01"), ws("old-pin", "2026-01-01", "2026-03-01"), ws("new-pin", "2026-01-01", "2026-04-01")];+ expect(sortWorkspaces(input).map((item) => item.id)).toEqual(["new-pin", "old-pin", "early", "late"]);+ expect(input[0]?.id).toBe("late");+});diff --git a/packages/core/workspace/sort-workspaces.ts b/packages/core/workspace/sort-workspaces.tsnew file mode 100644index 0000000000..7bdb7429b3--- /dev/null+++ b/packages/core/workspace/sort-workspaces.ts@@ -0,0 +1,10 @@+import type { Workspace } from "../types";++export function sortWorkspaces(workspaces: Workspace[]): Workspace[] {+ return [...workspaces].sort((a, b) => {+ if (a.pinned_at && b.pinned_at) return b.pinned_at.localeCompare(a.pinned_at);+ if (a.pinned_at) return -1;+ if (b.pinned_at) return 1;+ return a.created_at.localeCompare(b.created_at);+ });+}diff --git a/packages/views/layout/rail-workspaces.test.tsx b/packages/views/layout/rail-workspaces.test.tsxindex 3146b18239..0c23af548f 100644--- a/packages/views/layout/rail-workspaces.test.tsx+++ b/packages/views/layout/rail-workspaces.test.tsx@@ -4,13 +4,14 @@ import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";import { renderWithI18n } from "../test/i18n";import { RailWorkspaces } from "./rail-workspaces";-type Ws = { id: string; name: string; slug: string; avatar_url: string | null };+type Ws = { id: string; name: string; slug: string; avatar_url: string | null; pinned_at?: string | null };const state = vi.hoisted(() => ({workspaces: [] as Ws[],invitations: [] as { id: string; workspace_id: string; workspace_name?: string; inviter_name?: string }[],summary: [] as { workspace_id: string; count: number }[],accept: vi.fn(),+ setPinned: vi.fn(),decline: vi.fn(),invalidateQueries: vi.fn(),mutations: [] as Array<Record<string, unknown>>,@@ -19,6 +20,10 @@ const state = vi.hoisted(() => ({workspacesInOtherWindows: undefined as undefined | (() => string[]),}));+vi.mock("@multica/core/workspace/mutations", () => ({+ useSetWorkspacePinned: () => ({ mutate: state.setPinned }),+}));+vi.mock("@multica/core/config", () => ({useConfigStore: (selector: (s: { workspaceCreationDisabled: boolean }) => unknown) =>selector({ workspaceCreationDisabled: state.workspaceCreationDisabled }),@@ -95,6 +100,7 @@ beforeEach(() => {state.invitations = [];state.summary = [];state.mutations.length = 0;+ state.setPinned.mockClear();state.workspaceCreationDisabled = false;state.openWorkspaceInNewWindow = undefined;state.workspacesInOtherWindows = undefined;@@ -113,6 +119,42 @@ describe("RailWorkspaces", () => {expect(within(menu).getByRole("menuitem", { name: /WS 3$/ })).toHaveAttribute("href", "/ws3/issues");});+ it("marks pinned workspaces and offers a pin control without navigating", async () => {+ state.workspaces = [{ ...ws(2), pinned_at: "2026-04-01T00:00:00Z" }, ws(1), ws(3)];+ state.summary = [{ workspace_id: "ws-2", count: 1 }];+ renderWithI18n(<RailWorkspaces />);+ const menu = await openMenu();+ const rows = within(menu).getAllByRole("menuitem").filter((item) => item.getAttribute("href")?.endsWith("/issues"));+ expect(rows.map((item) => item.getAttribute("href"))).toEqual(["/ws2/issues", "/active/issues", "/ws3/issues"]);+ const pinned = within(menu).getByRole("menuitem", { name: /WS 2/ });+ expect(pinned.querySelector(".text-brand")).toBeInTheDocument();+ const button = within(pinned).getByRole("button", { name: "Unpin workspace" });+ fireEvent.mouseOver(pinned);+ expect(fireEvent.click(button)).toBe(false);+ expect(state.setPinned).toHaveBeenCalledWith({ workspaceId: "ws-2", pinned: false });+ expect(within(screen.getByRole("menu")).getByRole("menuitem", { name: /WS 2/ })).toBeInTheDocument();+ expect(within(menu).getAllByRole("button", { name: "Pin workspace" })).toHaveLength(2);+ });++ it("uses unread tone for pins and keeps the current check beside its pin", async () => {+ state.workspaces = [{ ...ws(1), pinned_at: "2026-03-01T00:00:00Z" }, { ...ws(2), pinned_at: "2026-02-01T00:00:00Z" }, ws(3)];+ state.summary = [{ workspace_id: "ws-3", count: 2 }];+ renderWithI18n(<RailWorkspaces />);+ const menu = await openMenu();+ const current = within(menu).getByRole("menuitem", { name: /Active WS/ });+ expect(current.querySelector(".icon-check")).toBeInTheDocument();+ expect(current.querySelector(".icon-pin.fill-current.text-muted-foreground")).toBeInTheDocument();+ const pinned = within(menu).getByRole("menuitem", { name: /WS 2/ });+ expect(pinned.querySelector(".icon-pin.fill-current.text-muted-foreground")).toBeInTheDocument();+ const unread = within(menu).getByRole("menuitem", { name: /WS 3/ });+ expect(unread.querySelector(".bg-brand")).toBeInTheDocument();+ const button = within(unread).getByRole("button", { name: "Pin workspace" });+ expect(button).toHaveClass("text-brand");+ expect(button.querySelector(".fill-current")).toBeNull();+ fireEvent.mouseOver(unread);+ expect(button).toHaveClass("group-hover/workspace:opacity-100");+ });+it("dots the switcher while another workspace has unread inbox items", async () => {state.summary = [{ workspace_id: "ws-2", count: 3 }];renderWithI18n(<RailWorkspaces />);@@ -158,10 +200,15 @@ describe("RailWorkspaces", () => {state.workspaces = [ws(1), ws(2), ws(3)];});- it("opens a workspace in a new window from its row button without following the row link", async () => {+ it("keeps pin and new-window actions separate without following the row link", async () => {renderWithI18n(<RailWorkspaces />);const menu = await openMenu();- const button = within(row(menu, /WS 3/)).getByRole("button", { name: "Open in new window" });+ const target = row(menu, /WS 3/);+ fireEvent.click(within(target).getByRole("button", { name: "Pin workspace" }));+ expect(state.setPinned).toHaveBeenCalledWith({ workspaceId: "ws-3", pinned: true });+ expect(state.openWorkspaceInNewWindow).not.toHaveBeenCalled();+ expect(menu).toBeInTheDocument();+ const button = within(target).getByRole("button", { name: "Open in new window" });const notPrevented = fireEvent.click(button);expect(state.openWorkspaceInNewWindow).toHaveBeenCalledWith("ws3");@@ -194,7 +241,7 @@ describe("RailWorkspaces", () => {const shown = row(menu, /WS 2/);expect(within(shown).getByText("Other window")).toBeInTheDocument();expect(within(row(menu, /WS 3/)).queryByText("Other window")).toBeNull();- expect(within(shown).queryByRole("button")).toBeNull();+ expect(within(shown).queryByRole("button", { name: "Open in new window" })).toBeNull();expect(within(row(menu, /WS 3/)).getByRole("button", { name: "Open in new window" })).toBeInTheDocument();fireEvent.click(shown, { shiftKey: true });expect(state.openWorkspaceInNewWindow).not.toHaveBeenCalled();@@ -203,7 +250,7 @@ describe("RailWorkspaces", () => {it("offers no new window for the current workspace", async () => {renderWithI18n(<RailWorkspaces />);const menu = await openMenu();- expect(within(row(menu, /Active WS/)).queryByRole("button")).toBeNull();+ expect(within(row(menu, /Active WS/)).queryByRole("button", { name: "Open in new window" })).toBeNull();});it("offers no new windows on web", async () => {diff --git a/packages/views/layout/rail-workspaces.tsx b/packages/views/layout/rail-workspaces.tsxindex 41c2322c50..bccd3a4598 100644--- a/packages/views/layout/rail-workspaces.tsx+++ b/packages/views/layout/rail-workspaces.tsx@@ -2,7 +2,7 @@import { useMemo, useState, type MouseEvent } from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { AppWindow, ArrowBigUp, Check, Plus } from "@multica/ui/icons";+import { AppWindow, ArrowBigUp, Check, Pin, Plus } from "@multica/ui/icons";import { api } from "@multica/core/api";import { useConfigStore } from "@multica/core/config";import {@@ -17,6 +17,7 @@ import {workspaceKeys,workspaceListOptions,} from "@multica/core/workspace/queries";+import { useSetWorkspacePinned } from "@multica/core/workspace/mutations";import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";import {DropdownMenu,@@ -89,6 +90,26 @@ function NewWindowButton({ onOpen }: { onOpen: () => void }) {);}+/**+ * Pin toggle that takes the trailing status slot on hover/highlight. Its tone+ * follows the row's unread state, so pinning never hides the unread signal.+ */+function PinButton({ pinned, unread, onToggle }: { pinned: boolean; unread: boolean; onToggle: () => void }) {+ const { t } = useT("layout");+ const label = pinned ? t(($) => $.rail.unpin_workspace) : t(($) => $.rail.pin_workspace);+ return (+ <TooltipHint label={label} side="right">+ <button type="button" aria-label={label} tabIndex={0}+ className={cn("absolute inset-0 flex items-center justify-center rounded-md opacity-0 group-hover/workspace:opacity-100 group-data-highlighted/workspace:opacity-100 focus-visible:opacity-100 hover:bg-surface-selected", unread ? "text-brand" : "text-muted-foreground")}+ onClick={(event) => { event.preventDefault(); event.stopPropagation(); onToggle(); }}+ onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") event.stopPropagation(); }}+ >+ <Pin className={cn("size-4", pinned && "fill-current")} />+ </button>+ </TooltipHint>+ );+}+// A text tag rather than a window glyph, so it never reads as the row// button that opens a new window.function OtherWindowMarker() {@@ -194,6 +215,7 @@ export function RailWorkspaces() {});const unreadIds = useMemo(() => unreadWorkspaceIds(unreadSummary), [unreadSummary]);const actions = useInvitationActions(invitations);+ const setPinned = useSetWorkspacePinned();const { openWorkspaceInNewWindow, workspacesInOtherWindows } = useNavigation();// Read when the menu opens: other windows switch workspaces independently.const [inOtherWindows, setInOtherWindows] = useState(EMPTY_SLUGS);@@ -258,7 +280,15 @@ export function RailWorkspaces() {><WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" /><span className="min-w-0 flex-1 truncate">{ws.name}</span>- {isCurrent ? <Check /> : unreadIds.has(ws.id) && <UnreadDot />}+ {isCurrent && <Check />}+ <span className="relative flex size-5 shrink-0 items-center justify-center">+ <span className="flex group-hover/workspace:opacity-0 group-data-highlighted/workspace:opacity-0">+ {ws.pinned_at ? (+ <Pin className={cn("size-4 fill-current", !isCurrent && unreadIds.has(ws.id) ? "text-brand" : "text-muted-foreground")} />+ ) : !isCurrent && unreadIds.has(ws.id) ? <UnreadDot /> : null}+ </span>+ <PinButton pinned={!!ws.pinned_at} unread={!isCurrent && unreadIds.has(ws.id)} onToggle={() => setPinned.mutate({ workspaceId: ws.id, pinned: !ws.pinned_at })} />+ </span>{inOtherWindow && <OtherWindowMarker />}{openInNewWindow && <NewWindowButton onOpen={openInNewWindow} />}</DropdownMenuItem>diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.jsonindex 4bee456459..a463dd0f3f 100644--- a/packages/views/locales/en/layout.json+++ b/packages/views/locales/en/layout.json@@ -92,6 +92,8 @@"autopilots": "Auto","switch_workspace": "Switch workspace","invitation_from": "{{name}} invited you",+ "pin_workspace": "Pin workspace",+ "unpin_workspace": "Unpin workspace","open_in_new_window": "Open in new window","open_in_new_window_click": "Click","open_in_other_window": "Already open in another window",diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.jsonindex 884cb4b110..0f10477866 100644--- a/packages/views/locales/es/layout.json+++ b/packages/views/locales/es/layout.json@@ -92,6 +92,8 @@"autopilots": "Auto","switch_workspace": "Cambiar de espacio de trabajo","invitation_from": "{{name}} te ha invitado",+ "pin_workspace": "Fijar espacio de trabajo",+ "unpin_workspace": "Desfijar espacio de trabajo","open_in_new_window": "Abrir en una ventana nueva","open_in_new_window_click": "Clic","open_in_other_window": "Ya está abierto en otra ventana",diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.jsonindex 8cb1da894b..ea8b73f9d0 100644--- a/packages/views/locales/fr/layout.json+++ b/packages/views/locales/fr/layout.json@@ -92,6 +92,8 @@"autopilots": "Auto","switch_workspace": "Changer d'espace de travail","invitation_from": "{{name}} vous a invité",+ "pin_workspace": "Épingler l’espace de travail",+ "unpin_workspace": "Désépingler l’espace de travail","open_in_new_window": "Ouvrir dans une nouvelle fenêtre","open_in_new_window_click": "Clic","open_in_other_window": "Déjà ouvert dans une autre fenêtre",diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.jsonindex 1713b6ad98..0bfd30841c 100644--- a/packages/views/locales/ja/layout.json+++ b/packages/views/locales/ja/layout.json@@ -92,6 +92,8 @@"autopilots": "自動化","switch_workspace": "ワークスペースを切り替え","invitation_from": "{{name}} さんから招待されています",+ "pin_workspace": "ワークスペースをピン留め",+ "unpin_workspace": "ピン留めを解除","open_in_new_window": "新しいウィンドウで開く","open_in_new_window_click": "クリック","open_in_other_window": "別のウィンドウで開いています",diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.jsonindex 260ca5a2b5..c5797b16ed 100644--- a/packages/views/locales/ko/layout.json+++ b/packages/views/locales/ko/layout.json@@ -92,6 +92,8 @@"autopilots": "자동화","switch_workspace": "워크스페이스 전환","invitation_from": "{{name}} 님이 초대했습니다",+ "pin_workspace": "작업 공간 고정",+ "unpin_workspace": "고정 해제","open_in_new_window": "새 창에서 열기","open_in_new_window_click": "클릭","open_in_other_window": "다른 창에서 열려 있음",diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.jsonindex 7123c53c3e..2350e808a4 100644--- a/packages/views/locales/zh-Hans/layout.json+++ b/packages/views/locales/zh-Hans/layout.json@@ -92,6 +92,8 @@"autopilots": "自动化","switch_workspace": "切换工作区","invitation_from": "{{name}} 邀请你加入",+ "pin_workspace": "置顶工作区",+ "unpin_workspace": "取消置顶","open_in_new_window": "在新窗口打开","open_in_new_window_click": "点击","open_in_other_window": "已在其他窗口打开",diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.jsonindex c0ea98fe15..abbcea9501 100644--- a/packages/views/locales/zh-Hant/layout.json+++ b/packages/views/locales/zh-Hant/layout.json@@ -92,6 +92,8 @@"autopilots": "自動化","switch_workspace": "切換工作區","invitation_from": "{{name}} 邀請你加入",+ "pin_workspace": "置頂工作區",+ "unpin_workspace": "取消置頂","open_in_new_window": "在新視窗開啟","open_in_new_window_click": "點擊","open_in_other_window": "已在其他視窗開啟",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex a1d632755f..f92744e804 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1768,6 +1768,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Group(func(r chi.Router) {r.Use(middleware.RequireWorkspaceMemberFromURL(queries, "id"))r.Get("/", h.GetWorkspace)+ r.Put("/pin", h.SetWorkspacePinned)r.Get("/members", h.ListMembersWithUser)r.Post("/leave", h.LeaveWorkspace)r.Get("/invitations", h.ListWorkspaceInvitations)diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 123aa6edd0..ef23a82fb8 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -107,6 +107,7 @@ type WorkspaceResponse struct {AvatarURL *string `json:"avatar_url"`CreatedAt string `json:"created_at"`UpdatedAt string `json:"updated_at"`+ PinnedAt *string `json:"pinned_at,omitempty"`}func (h *Handler) workspaceToResponse(w db.Workspace) WorkspaceResponse {@@ -171,12 +172,57 @@ func (h *Handler) ListWorkspaces(w http.ResponseWriter, r *http.Request) {resp := make([]WorkspaceResponse, len(workspaces))for i, ws := range workspaces {- resp[i] = h.workspaceToResponse(ws)+ resp[i] = h.workspaceToResponse(db.Workspace{+ ID: ws.ID, Name: ws.Name, Slug: ws.Slug, Description: ws.Description,+ Settings: ws.Settings, CreatedAt: ws.CreatedAt, UpdatedAt: ws.UpdatedAt,+ Context: ws.Context, Repos: ws.Repos, IssuePrefix: ws.IssuePrefix,+ IssueCounter: ws.IssueCounter, AvatarUrl: ws.AvatarUrl,+ AttributionFailClosed: ws.AttributionFailClosed,+ })+ if ws.PinnedAt.Valid {+ pinnedAt := timestampToString(ws.PinnedAt)+ resp[i].PinnedAt = &pinnedAt+ }}writeJSON(w, http.StatusOK, resp)}+func (h *Handler) SetWorkspacePinned(w http.ResponseWriter, r *http.Request) {+ id, ok := parseUUIDOrBadRequest(w, workspaceIDFromURL(r, "id"), "workspace id")+ if !ok {+ return+ }+ member, ok := h.workspaceMember(w, r, uuidToString(id))+ if !ok {+ return+ }+ var req struct {+ Pinned *bool `json:"pinned"`+ }+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Pinned == nil {+ writeError(w, http.StatusBadRequest, "pinned must be a boolean")+ return+ }+ pinnedAt, err := h.Queries.SetWorkspacePinned(r.Context(), db.SetWorkspacePinnedParams{+ WorkspaceID: id, UserID: member.UserID, Pinned: *req.Pinned,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "workspace not found")+ return+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update workspace pin")+ return+ }+ var result *string+ if pinnedAt.Valid {+ value := timestampToString(pinnedAt)+ result = &value+ }+ writeJSON(w, http.StatusOK, map[string]any{"pinned_at": result})+}+func (h *Handler) GetWorkspace(w http.ResponseWriter, r *http.Request) {id := workspaceIDFromURL(r, "id")idUUID, ok := parseUUIDOrBadRequest(w, id, "workspace id")diff --git a/server/internal/handler/workspace_pin_test.go b/server/internal/handler/workspace_pin_test.gonew file mode 100644index 0000000000..81f83a4c40--- /dev/null+++ b/server/internal/handler/workspace_pin_test.go@@ -0,0 +1,81 @@+package handler++import (+ "net/http"+ "testing"+ "time"++ "github.com/google/uuid"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestWorkspacePinIsPerMemberAndOrdersList(t *testing.T) {+ suffix := uuid.NewString()+ first := dbfx.Workspace(t, "First", "pin-first-"+suffix, testutil.Cols{"created_at": time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)})+ second := dbfx.Workspace(t, "Second", "pin-second-"+suffix, testutil.Cols{"created_at": time.Date(2025, 2, 1, 0, 0, 0, 0, time.UTC)})+ third := dbfx.Workspace(t, "Third", "pin-third-"+suffix, testutil.Cols{"created_at": time.Date(2025, 3, 1, 0, 0, 0, 0, time.UTC)})+ other := dbfx.User(t, "Other pin user", "pin-other-"+suffix+"@example.test")+ for _, id := range []string{first, second, third} {+ dbfx.Member(t, id, testUserID, "member")+ dbfx.Member(t, id, other, "member")+ }+ pin := func(user, id string, pinned bool) *string {+ t.Helper()+ req := withURLParam(newRequestAs(user, http.MethodPut, "/api/workspaces/"+id+"/pin", map[string]any{"pinned": pinned}), "id", id)+ var got struct {+ PinnedAt *string `json:"pinned_at"`+ }+ testutil.Call(t, testHandler.SetWorkspacePinned, req).Want(http.StatusOK).JSON(&got)+ return got.PinnedAt+ }+ list := func(user string) []WorkspaceResponse {+ t.Helper()+ var got []WorkspaceResponse+ testutil.Call(t, testHandler.ListWorkspaces, newRequestAs(user, http.MethodGet, "/api/workspaces", nil)).Want(http.StatusOK).JSON(&got)+ return got+ }+ assertRelative := func(got []WorkspaceResponse, ids ...string) {+ t.Helper()+ seen := make([]string, 0, len(ids))+ for _, item := range got {+ for _, id := range ids {+ if item.ID == id {+ seen = append(seen, id)+ }+ }+ }+ for i, id := range ids {+ if i >= len(seen) || seen[i] != id {+ t.Fatalf("relative order = %v, want %v", seen, ids)+ }+ }+ }+ assertRelative(list(testUserID), first, second, third)+ stamp := pin(testUserID, first, true)+ if stamp == nil {+ t.Fatal("pin did not return a timestamp")+ }+ if again := pin(testUserID, first, true); again == nil || *again != *stamp {+ t.Fatalf("repeat pin changed time: %v -> %v", stamp, again)+ }+ if pin(testUserID, second, true) == nil {+ t.Fatal("second pin missing timestamp")+ }+ assertRelative(list(testUserID), second, first, third)+ assertRelative(list(other), first, second, third)+ if pin(testUserID, second, false) != nil {+ t.Fatal("unpin should return null")+ }+ assertRelative(list(testUserID), first, second, third)+ pin(other, third, true)+ assertRelative(list(other), third, first, second)+ assertRelative(list(testUserID), first, second, third)+ outsider := dbfx.User(t, "Pin outsider", "pin-outsider-"+suffix+"@example.test")+ req := withURLParam(newRequestAs(outsider, http.MethodPut, "/api/workspaces/"+first+"/pin", map[string]any{"pinned": true}), "id", first)+ testutil.Call(t, testHandler.SetWorkspacePinned, req).Want(http.StatusNotFound)+ bad := withURLParam(newRequest(http.MethodPut, "/api/workspaces/not-uuid/pin", map[string]any{"pinned": true}), "id", "not-uuid")+ testutil.Call(t, testHandler.SetWorkspacePinned, bad).Want(http.StatusBadRequest)+ missing := withURLParam(newRequest(http.MethodPut, "/api/workspaces/"+first+"/pin", map[string]any{}), "id", first)+ testutil.Call(t, testHandler.SetWorkspacePinned, missing).Want(http.StatusBadRequest)+}diff --git a/server/migrations/616_member_pinned.down.sql b/server/migrations/616_member_pinned.down.sqlnew file mode 100644index 0000000000..4c3442ebba--- /dev/null+++ b/server/migrations/616_member_pinned.down.sql@@ -0,0 +1 @@+ALTER TABLE member DROP COLUMN IF EXISTS pinned_at;diff --git a/server/migrations/616_member_pinned.up.sql b/server/migrations/616_member_pinned.up.sqlnew file mode 100644index 0000000000..8615b71e77--- /dev/null+++ b/server/migrations/616_member_pinned.up.sql@@ -0,0 +1 @@+ALTER TABLE member ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;diff --git a/server/pkg/db/generated/member.sql.go b/server/pkg/db/generated/member.sql.goindex ec381f1147..b1551a6d64 100644--- a/server/pkg/db/generated/member.sql.go+++ b/server/pkg/db/generated/member.sql.go@@ -14,7 +14,7 @@ import (const createMember = `-- name: CreateMember :oneINSERT INTO member (workspace_id, user_id, role)VALUES ($1, $2, $3)-RETURNING id, workspace_id, user_id, role, created_at+RETURNING id, workspace_id, user_id, role, created_at, pinned_at`type CreateMemberParams struct {@@ -32,6 +32,7 @@ func (q *Queries) CreateMember(ctx context.Context, arg CreateMemberParams) (Mem&i.UserID,&i.Role,&i.CreatedAt,+ &i.PinnedAt,)return i, err}@@ -46,7 +47,7 @@ func (q *Queries) DeleteMember(ctx context.Context, id pgtype.UUID) error {}const getMember = `-- name: GetMember :one-SELECT id, workspace_id, user_id, role, created_at FROM member+SELECT id, workspace_id, user_id, role, created_at, pinned_at FROM memberWHERE id = $1`@@ -59,12 +60,13 @@ func (q *Queries) GetMember(ctx context.Context, id pgtype.UUID) (Member, error)&i.UserID,&i.Role,&i.CreatedAt,+ &i.PinnedAt,)return i, err}const getMemberByUserAndWorkspace = `-- name: GetMemberByUserAndWorkspace :one-SELECT id, workspace_id, user_id, role, created_at FROM member+SELECT id, workspace_id, user_id, role, created_at, pinned_at FROM memberWHERE user_id = $1 AND workspace_id = $2`@@ -82,6 +84,7 @@ func (q *Queries) GetMemberByUserAndWorkspace(ctx context.Context, arg GetMember&i.UserID,&i.Role,&i.CreatedAt,+ &i.PinnedAt,)return i, err}@@ -127,7 +130,7 @@ func (q *Queries) GetRealtimeMemberships(ctx context.Context, arg GetRealtimeMem}const listMembers = `-- name: ListMembers :many-SELECT id, workspace_id, user_id, role, created_at FROM member+SELECT id, workspace_id, user_id, role, created_at, pinned_at FROM memberWHERE workspace_id = $1ORDER BY created_at ASC`@@ -147,6 +150,7 @@ func (q *Queries) ListMembers(ctx context.Context, workspaceID pgtype.UUID) ([]M&i.UserID,&i.Role,&i.CreatedAt,+ &i.PinnedAt,); err != nil {return nil, err}@@ -236,7 +240,7 @@ func (q *Queries) ListWorkspaceManagerUserIDs(ctx context.Context, workspaceID pconst updateMemberRole = `-- name: UpdateMemberRole :oneUPDATE member SET role = $2WHERE id = $1-RETURNING id, workspace_id, user_id, role, created_at+RETURNING id, workspace_id, user_id, role, created_at, pinned_at`type UpdateMemberRoleParams struct {@@ -253,6 +257,7 @@ func (q *Queries) UpdateMemberRole(ctx context.Context, arg UpdateMemberRolePara&i.UserID,&i.Role,&i.CreatedAt,+ &i.PinnedAt,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex c013de83fd..303482873a 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1231,6 +1231,7 @@ type Member struct {UserID pgtype.UUID `json:"user_id"`Role string `json:"role"`CreatedAt pgtype.Timestamptz `json:"created_at"`+ PinnedAt pgtype.Timestamptz `json:"pinned_at"`}type MemberDelegationDay struct {diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex 224775b994..703ea3f302 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -348,22 +348,39 @@ func (q *Queries) ListDaemonWorkspaces(ctx context.Context, userID pgtype.UUID)const listWorkspaces = `-- name: ListWorkspaces :manySELECT w.id, w.name, w.slug, w.description, w.settings,w.created_at, w.updated_at, w.context, w.repos,- w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed+ w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed, m.pinned_atFROM member mJOIN workspace w ON w.id = m.workspace_idWHERE m.user_id = $1-ORDER BY w.created_at ASC+ORDER BY m.pinned_at DESC NULLS LAST, w.created_at ASC`-func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Workspace, error) {+type ListWorkspacesRow struct {+ ID pgtype.UUID `json:"id"`+ Name string `json:"name"`+ Slug string `json:"slug"`+ Description pgtype.Text `json:"description"`+ Settings []byte `json:"settings"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ Context pgtype.Text `json:"context"`+ Repos []byte `json:"repos"`+ IssuePrefix string `json:"issue_prefix"`+ IssueCounter int32 `json:"issue_counter"`+ AvatarUrl pgtype.Text `json:"avatar_url"`+ AttributionFailClosed bool `json:"attribution_fail_closed"`+ PinnedAt pgtype.Timestamptz `json:"pinned_at"`+}++func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]ListWorkspacesRow, error) {rows, err := q.db.Query(ctx, listWorkspaces, userID)if err != nil {return nil, err}defer rows.Close()- items := []Workspace{}+ items := []ListWorkspacesRow{}for rows.Next() {- var i Workspace+ var i ListWorkspacesRowif err := rows.Scan(&i.ID,&i.Name,@@ -378,6 +395,7 @@ func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Wor&i.IssueCounter,&i.AvatarUrl,&i.AttributionFailClosed,+ &i.PinnedAt,); err != nil {return nil, err}@@ -433,6 +451,26 @@ func (q *Queries) LockWorkspaceForDelete(ctx context.Context, id pgtype.UUID) (preturn id_2, err}+const setWorkspacePinned = `-- name: SetWorkspacePinned :one+UPDATE member+SET pinned_at = CASE WHEN $1::bool THEN COALESCE(pinned_at, now()) ELSE NULL END+WHERE workspace_id = $2 AND user_id = $3+RETURNING pinned_at+`++type SetWorkspacePinnedParams struct {+ Pinned bool `json:"pinned"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++func (q *Queries) SetWorkspacePinned(ctx context.Context, arg SetWorkspacePinnedParams) (pgtype.Timestamptz, error) {+ row := q.db.QueryRow(ctx, setWorkspacePinned, arg.Pinned, arg.WorkspaceID, arg.UserID)+ var pinned_at pgtype.Timestamptz+ err := row.Scan(&pinned_at)+ return pinned_at, err+}+const updateWorkspace = `-- name: UpdateWorkspace :oneUPDATE workspace SETname = COALESCE($2, name),diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sqlindex d86ac43f1a..281b973564 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -1,11 +1,11 @@-- name: ListWorkspaces :manySELECT w.id, w.name, w.slug, w.description, w.settings,w.created_at, w.updated_at, w.context, w.repos,- w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed+ w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed, m.pinned_atFROM member mJOIN workspace w ON w.id = m.workspace_idWHERE m.user_id = $1-ORDER BY w.created_at ASC;+ORDER BY m.pinned_at DESC NULLS LAST, w.created_at ASC;-- name: ListDaemonWorkspaces :many-- Daemons only need the membership set and display name to discover which@@ -240,3 +240,9 @@ cleared_client_usage_workspace AS (UPDATE client_usage_daily SET workspace_id = NULL WHERE workspace_id = $1)DELETE FROM workspace WHERE workspace.id = $1;++-- name: SetWorkspacePinned :one+UPDATE member+SET pinned_at = CASE WHEN @pinned::bool THEN COALESCE(pinned_at, now()) ELSE NULL END+WHERE workspace_id = @workspace_id AND user_id = @user_id+RETURNING pinned_at;