Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6458: feat(issue-statuses): sync the status catalog over the realtime channel (#7287)
Bohan Jiang9900e966866a
diff --git a/packages/core/issue-statuses/mutations.test.tsx b/packages/core/issue-statuses/mutations.test.tsxnew file mode 100644index 0000000000..6c904cdbb8--- /dev/null+++ b/packages/core/issue-statuses/mutations.test.tsx@@ -0,0 +1,373 @@+/**+ * @vitest-environment jsdom+ */+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import { issueKeys } from "../issues/queries";+import type { IssueStatusEntry, ListIssueStatusesResponse } from "../types";+import {+ useArchiveIssueStatus,+ useCreateIssueStatus,+ useReorderIssueStatuses,+ useUpdateIssueStatus,+} from "./mutations";+import { issueStatusKeys } from "./queries";++vi.mock("../hooks", () => ({ useWorkspaceId: () => "ws-1" }));++const CATEGORIES = [+ "backlog",+ "todo",+ "in_progress",+ "in_review",+ "done",+ "cancelled",+ "blocked",+] as const;++function entry(overrides: Partial<IssueStatusEntry> & { id: string }): IssueStatusEntry {+ return {+ workspace_id: "ws-1",+ key: overrides.id,+ name: overrides.id,+ description: "",+ category: "in_review",+ color: "#6366f1",+ is_system: false,+ position: 1,+ archived_at: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++const builtInReview = entry({+ id: "builtin-in-review",+ key: "in_review",+ name: "In Review",+ is_system: true,+ position: 0,+});++function catalog(statuses: IssueStatusEntry[]): ListIssueStatusesResponse {+ return { statuses, categories: [...CATEGORIES], total: statuses.length };+}++function wrapper(qc: QueryClient) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;+ };+}++function createClient() {+ return new QueryClient({ defaultOptions: { queries: { retry: false } } });+}++function cached(qc: QueryClient) {+ return qc.getQueryData<ListIssueStatusesResponse>(issueStatusKeys.list("ws-1"));+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++/**+ * What a completed realtime refetch does to the cache: replaces it wholesale+ * with whatever the server answered, including writes this client never made.+ */+function realtimeRefetchLands(qc: QueryClient, response: ListIssueStatusesResponse) {+ qc.setQueryData<ListIssueStatusesResponse>(issueStatusKeys.list("ws-1"), response);+}++describe("issue status catalog mutations", () => {+ afterEach(() => vi.restoreAllMocks());++ // The realtime `issue_status:changed` event refreshes this catalog in every+ // tab, the writing one included. A second invalidate here would make the+ // admin who did the writing the only client that reads the catalog twice.+ // (MUL-6458)+ it("leaves the catalog refresh to the realtime event on a successful write", async () => {+ const qc = createClient();+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview]));+ const invalidate = vi.spyOn(qc, "invalidateQueries");+ setApiInstance({+ createIssueStatus: vi.fn(async () => entry({ id: "qa", key: "qa", name: "QA" })),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useCreateIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ name: "QA", category: "in_review", color: "#6366f1" }));+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ const catalogInvalidations = invalidate.mock.calls.filter(+ ([filters]) => (filters?.queryKey as string[] | undefined)?.[0] === "issue-statuses",+ );+ expect(catalogInvalidations).toHaveLength(0);+ });++ it("still refetches the catalog when a write fails", async () => {+ const qc = createClient();+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview]));+ const invalidate = vi.spyOn(qc, "invalidateQueries");+ setApiInstance({+ createIssueStatus: vi.fn(async () => {+ throw new Error("409");+ }),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useCreateIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ name: "QA", category: "in_review", color: "#6366f1" }));+ await waitFor(() => expect(result.current.isError).toBe(true));++ expect(invalidate).toHaveBeenCalledWith({ queryKey: issueStatusKeys.all("ws-1") });+ });++ // Without the sort, a created status lands at the end of the array while the+ // server puts it inside its category — and nothing corrects that until the+ // realtime refetch lands, which is exactly the window the user is looking at.+ it("sorts a created status into its category instead of appending it", async () => {+ const qc = createClient();+ const done = entry({ id: "builtin-done", key: "done", category: "done", is_system: true, position: 0 });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview, done]));+ setApiInstance({+ createIssueStatus: vi.fn(async () => entry({ id: "qa", key: "qa", name: "QA" })),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useCreateIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ name: "QA", category: "in_review", color: "#6366f1" }));+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(cached(qc)?.statuses.map((s) => s.id)).toEqual(["builtin-in-review", "qa", "builtin-done"]);+ expect(cached(qc)?.total).toBe(3);+ });++ // `parseWithFallback` degrades a malformed response to an empty stub. Writing+ // that would put a blank row in the picker until the realtime refetch lands.+ it("ignores a create response that degraded to the empty schema fallback", async () => {+ const qc = createClient();+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview]));+ setApiInstance({+ createIssueStatus: vi.fn(async () => entry({ id: "", key: "", name: "", position: 0 })),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useCreateIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ name: "QA", category: "in_review", color: "#6366f1" }));+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(cached(qc)?.statuses).toEqual([builtInReview]);+ });++ // A rename changes a label the boards resolve from THIS catalog at render+ // time, so nothing cached under the issues scope can be stale. Refetching it+ // meant one word cost a workspace-wide board/list/table refetch. (MUL-6458)+ it("does not refetch the issue caches when a status is renamed", async () => {+ const qc = createClient();+ const qa = entry({ id: "qa", key: "qa", name: "QA" });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview, qa]));+ const invalidate = vi.spyOn(qc, "invalidateQueries");+ setApiInstance({+ updateIssueStatus: vi.fn(async () => ({ ...qa, name: "Quality Gate" })),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useUpdateIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ id: "qa", name: "Quality Gate" }));+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(invalidate).not.toHaveBeenCalledWith({ queryKey: issueKeys.all("ws-1") });+ });++ it("shows a rename immediately and rolls it back when the write fails", async () => {+ const qc = createClient();+ const qa = entry({ id: "qa", key: "qa", name: "QA" });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview, qa]));+ const write = deferred<IssueStatusEntry>();+ setApiInstance({+ updateIssueStatus: vi.fn(() => write.promise),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useUpdateIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ id: "qa", name: "Quality Gate" }));+ await waitFor(() =>+ expect(cached(qc)?.statuses.find((s) => s.id === "qa")?.name).toBe("Quality Gate"),+ );++ await act(async () => {+ write.resolve(Promise.reject(new Error("409")) as unknown as IssueStatusEntry);+ });+ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(cached(qc)?.statuses.find((s) => s.id === "qa")?.name).toBe("QA");+ });++ // The two channels are independent, and the realtime refresh is debounced, so+ // "someone else's later write is already in the cache when my response lands"+ // is a legal ordering — not a rare interleaving. Installing the response body+ // here would roll the catalog back to a state no further event corrects, in+ // exactly the concurrent-editing scenario this feature exists for. (MUL-6458)+ it("does not let a slow rename response overwrite a newer catalog", async () => {+ const qc = createClient();+ const qa = entry({ id: "qa", key: "qa", name: "QA" });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview, qa]));+ const write = deferred<IssueStatusEntry>();+ setApiInstance({+ updateIssueStatus: vi.fn(() => write.promise),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useUpdateIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ id: "qa", name: "Quality Gate" }));+ // The optimistic patch shows first — the ordering under test is what+ // happens AFTER it, not a race with it.+ await waitFor(() =>+ expect(cached(qc)?.statuses.find((s) => s.id === "qa")?.name).toBe("Quality Gate"),+ );++ // Another admin renames the same row afterwards; this client's refetch+ // picks their version up while our own response is still in flight.+ realtimeRefetchLands(+ qc,+ catalog([builtInReview, { ...qa, name: "Ready for QA", updated_at: "2026-03-03T00:00:00Z" }]),+ );++ await act(async () => {+ write.resolve({ ...qa, name: "Quality Gate", updated_at: "2026-02-02T00:00:00Z" });+ });+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(cached(qc)?.statuses.find((s) => s.id === "qa")?.name).toBe("Ready for QA");+ });++ // Same ordering, worse blast radius: reorder answers with the WHOLE catalog,+ // so one late response would revert every concurrent edit at once — here, a+ // status another admin created while the drag was in flight.+ it("does not let a slow reorder response overwrite a newer catalog", async () => {+ const qc = createClient();+ const first = entry({ id: "qa", key: "qa", position: 1 });+ const second = entry({ id: "sec", key: "sec", position: 2 });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview, first, second]));+ const write = deferred<ListIssueStatusesResponse>();+ setApiInstance({+ reorderIssueStatuses: vi.fn(() => write.promise),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useReorderIssueStatuses(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ category: "in_review", ordered: [second, first] }));+ // The drag shows immediately, without waiting for the round trip.+ await waitFor(() =>+ expect(cached(qc)?.statuses.map((s) => s.id)).toEqual(["builtin-in-review", "sec", "qa"]),+ );++ const third = entry({ id: "third", key: "third", position: 3 });+ realtimeRefetchLands(+ qc,+ catalog([builtInReview, { ...second, position: 1 }, { ...first, position: 2 }, third]),+ );++ await act(async () => {+ write.resolve(catalog([builtInReview, { ...second, position: 1 }, { ...first, position: 2 }]));+ });+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(cached(qc)?.statuses.map((s) => s.id)).toEqual([+ "builtin-in-review",+ "sec",+ "qa",+ "third",+ ]);+ });++ it("restores the pre-drag order when a reorder fails", async () => {+ const qc = createClient();+ const first = entry({ id: "qa", key: "qa", position: 1 });+ const second = entry({ id: "sec", key: "sec", position: 2 });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview, first, second]));+ setApiInstance({+ reorderIssueStatuses: vi.fn(async () => {+ throw new Error("409");+ }),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useReorderIssueStatuses(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ category: "in_review", ordered: [second, first] }));+ await waitFor(() => expect(result.current.isError).toBe(true));++ expect(cached(qc)?.statuses.map((s) => s.id)).toEqual(["builtin-in-review", "qa", "sec"]);+ });++ // An archived status stays in the cache on purpose: issues still sitting on+ // it resolve their name, color and category through it.+ it("keeps an archived status in the catalog with its archived_at set", async () => {+ const qc = createClient();+ const qa = entry({ id: "qa", key: "qa", name: "QA" });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview, qa]));+ setApiInstance({+ archiveIssueStatus: vi.fn(async () => ({ ...qa, archived_at: "2026-02-02T00:00:00Z" })),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useArchiveIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate("qa"));+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(cached(qc)?.statuses.find((s) => s.id === "qa")?.archived_at).toBe("2026-02-02T00:00:00Z");+ expect(cached(qc)?.total).toBe(2);+ });++ // Archiving is terminal, so the FLAG is safe to apply to whatever row the+ // cache holds. The rest of the returned row is not: a rename that landed+ // while the archive was in flight would be reverted by a whole-row install.+ it("archives without reverting a rename that landed meanwhile", async () => {+ const qc = createClient();+ const qa = entry({ id: "qa", key: "qa", name: "QA" });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview, qa]));+ const write = deferred<IssueStatusEntry>();+ setApiInstance({+ archiveIssueStatus: vi.fn(() => write.promise),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useArchiveIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate("qa"));++ realtimeRefetchLands(qc, catalog([builtInReview, { ...qa, name: "Ready for QA" }]));++ await act(async () => {+ write.resolve({ ...qa, archived_at: "2026-02-02T00:00:00Z" });+ });+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ const stored = cached(qc)?.statuses.find((s) => s.id === "qa");+ expect(stored?.name).toBe("Ready for QA");+ expect(stored?.archived_at).toBe("2026-02-02T00:00:00Z");+ });++ // The only way this client already holds the created id is a refetch that+ // read it back — so its copy is never older than this response.+ it("does not re-insert a created status the catalog already picked up", async () => {+ const qc = createClient();+ const created = entry({ id: "qa", key: "qa", name: "QA" });+ qc.setQueryData(issueStatusKeys.list("ws-1"), catalog([builtInReview]));+ const write = deferred<IssueStatusEntry>();+ setApiInstance({+ createIssueStatus: vi.fn(() => write.promise),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useCreateIssueStatus(), { wrapper: wrapper(qc) });+ act(() => result.current.mutate({ name: "QA", category: "in_review", color: "#6366f1" }));++ realtimeRefetchLands(qc, catalog([builtInReview, { ...created, name: "QA (renamed)" }]));++ await act(async () => {+ write.resolve(created);+ });+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(cached(qc)?.statuses.map((s) => s.name)).toEqual(["In Review", "QA (renamed)"]);+ expect(cached(qc)?.total).toBe(2);+ });+});diff --git a/packages/core/issue-statuses/mutations.ts b/packages/core/issue-statuses/mutations.tsindex 565a01b65e..041d9ffefa 100644--- a/packages/core/issue-statuses/mutations.ts+++ b/packages/core/issue-statuses/mutations.ts@@ -2,7 +2,6 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { api } from "../api";import { useWorkspaceId } from "../hooks";import { compareIssueStatusEntries, issueStatusKeys } from "./queries";-import { issueKeys } from "../issues/queries";import type {CreateIssueStatusRequest,IssueStatusCategory,@@ -14,19 +13,87 @@ import type {/*** Catalog mutations (MUL-6243).*- * The catalog query is cached for 5 minutes and read by every surface that- * renders a status label, so each mutation invalidates it explicitly rather- * than waiting for staleness. A rename or recolor also invalidates the issues- * scope: a status's name is resolved from the catalog at render time, but the- * board/list caches hold the rows whose labels have to re-render.+ * No mutation invalidates the catalog on success. The refresh is the+ * `issue_status:changed` realtime event, which reaches the writing tab as well+ * as every other one, so a catalog edit costs each client exactly ONE catalog+ * read. Invalidating here too would make the admin who did the writing the+ * only client that reads it twice. (MUL-6458)+ *+ * That refetch is what CONVERGES the cache, and it is ordered correctly by+ * construction: the event is published after the write commits, so the refetch+ * it triggers can only read post-commit state.+ *+ * Which is why no mutation writes its RESPONSE BODY into the cache. A response+ * is authoritative for the row as of that write, not as of now — and the two+ * channels are independent, so a slow response can land after a refetch that+ * already picked up someone else's later write and quietly roll the catalog+ * back to a state nothing will correct. Every local write below is instead+ * something that stays true no matter what else has landed in between:+ *+ * - an optimistic field patch (rename, recolor, reorder),+ * - an insert of a row nobody else can have seen yet (create),+ * - a monotonic flag (archive — there is no unarchive endpoint, and the server+ * refuses to edit an archived row, so setting it can never be stale).+ *+ * On FAILURE the invalidate stays, and it is not symmetry for its own sake: a+ * 409 usually means this client's catalog is the stale thing — someone else+ * took the name, or archived the row that was being dragged.*/-function useCatalogInvalidation() {+function useCatalogCache() {const qc = useQueryClient();const wsId = useWorkspaceId();+ const listKey = issueStatusKeys.list(wsId);++ const writeStatuses = (+ update: (statuses: IssueStatusEntry[]) => IssueStatusEntry[] | null,+ totalDelta = 0,+ ) => {+ qc.setQueryData<ListIssueStatusesResponse>(listKey, (old) => {+ if (!old) return old;+ const statuses = update(old.statuses);+ if (!statuses) return old;+ return {+ ...old,+ statuses: statuses.sort(compareIssueStatusEntries),+ total: old.total + totalDelta,+ };+ });+ };+return {qc,- wsId,+ listKey,+ /**+ * Adds a freshly created status to the cached catalog.+ *+ * Skipped when the id is already there, which is not just a duplicate+ * guard: the only way this client can already hold the row is a refetch+ * that read it back — possibly after someone else edited it — so the copy+ * in the cache is never older than the one in this response.+ *+ * Sorted, because `position` and `category` decide where a row renders and+ * appending would put a new In Review status below the Done rows.+ */+ insertEntry: (entry: IssueStatusEntry) => {+ // A response that failed schema validation degrades to an empty stub+ // (`parseWithFallback`). Writing it would put a blank row in the picker;+ // leaving the cache alone lets the realtime refetch supply the truth.+ if (!entry?.id) return;+ writeStatuses(+ (statuses) =>+ statuses.some((s) => s.id === entry.id) ? null : [...statuses, entry],+ 1,+ );+ },+ /** Applies a field patch to one cached row, leaving the rest of it alone. */+ patchEntry: (id: string, patch: Partial<IssueStatusEntry>) => {+ writeStatuses((statuses) =>+ statuses.some((s) => s.id === id)+ ? statuses.map((s) => (s.id === id ? { ...s, ...patch } : s))+ : null,+ );+ },invalidate: () => {qc.invalidateQueries({ queryKey: issueStatusKeys.all(wsId) });},@@ -34,17 +101,11 @@ function useCatalogInvalidation() {}export function useCreateIssueStatus() {- const { qc, wsId, invalidate } = useCatalogInvalidation();+ const { insertEntry, invalidate } = useCatalogCache();return useMutation({mutationFn: (data: CreateIssueStatusRequest) => api.createIssueStatus(data),- onSuccess: (entry) => {- qc.setQueryData<ListIssueStatusesResponse>(issueStatusKeys.list(wsId), (old) =>- old && !old.statuses.some((s) => s.id === entry.id)- ? { ...old, statuses: [...old.statuses, entry], total: old.total + 1 }- : old,- );- },- onSettled: invalidate,+ onSuccess: insertEntry,+ onError: invalidate,});}@@ -53,32 +114,29 @@ export function useCreateIssueStatus() {* Without it, dragging a row to reorder would snap back for the round-trip.*/export function useUpdateIssueStatus() {- const { qc, wsId, invalidate } = useCatalogInvalidation();+ const { qc, listKey, patchEntry, invalidate } = useCatalogCache();return useMutation({mutationFn: ({ id, ...data }: { id: string } & UpdateIssueStatusRequest) =>api.updateIssueStatus(id, data),onMutate: async ({ id, ...data }) => {- const listKey = issueStatusKeys.list(wsId);await qc.cancelQueries({ queryKey: listKey });const previous = qc.getQueryData<ListIssueStatusesResponse>(listKey);- qc.setQueryData<ListIssueStatusesResponse>(listKey, (old) =>- old- ? {- ...old,- statuses: old.statuses.map((s) => (s.id === id ? { ...s, ...data } : s)),- }- : old,- );- return { previous, listKey };+ patchEntry(id, data);+ return { previous };},+ // Nothing on success. The optimistic patch already shows the change, the+ // realtime refetch settles it, and installing the response snapshot here+ // is exactly what could roll a concurrent edit back (see the note above).+ //+ // A rename also deliberately does NOT invalidate the issues scope. An issue+ // row stores the status KEY; its name and color are resolved from this+ // catalog at render time (`useStatusLabel`, `colorOf`), so no cached issue+ // field can go stale here — refreshing the catalog is what repaints the+ // boards. The old invalidate refetched every board, list and table in the+ // workspace to change one word. (MUL-6458)onError: (_err, _vars, ctx) => {- if (ctx?.previous && ctx.listKey) qc.setQueryData(ctx.listKey, ctx.previous);- },- onSettled: () => {+ if (ctx?.previous) qc.setQueryData(listKey, ctx.previous);invalidate();- // Issue rows render the catalog's name/color, so a rename has to reach- // the cached lists too.- qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });},});}@@ -89,10 +147,22 @@ export function useUpdateIssueStatus() {* would read as success.*/export function useArchiveIssueStatus() {- const { invalidate } = useCatalogInvalidation();+ const { patchEntry, invalidate } = useCatalogCache();return useMutation({mutationFn: (id: string) => api.archiveIssueStatus(id),- onSettled: invalidate,+ // Only `archived_at`, never the whole returned row. Archiving is terminal —+ // there is no unarchive, and the server refuses to edit an archived status+ // — so the flag stays true whatever else landed in the cache meanwhile,+ // while a full snapshot would revert a rename that raced this archive.+ //+ // The row itself stays: issues still sitting on it resolve their name,+ // color and category through it. `activeStatuses` is what hides it from+ // pickers.+ onSuccess: (entry) => {+ if (!entry?.id) return;+ patchEntry(entry.id, { archived_at: entry.archived_at });+ },+ onError: invalidate,});}@@ -107,7 +177,7 @@ export function useArchiveIssueStatus() {* at 0 and never moves.*/export function useReorderIssueStatuses() {- const { qc, wsId, invalidate } = useCatalogInvalidation();+ const { qc, listKey, invalidate } = useCatalogCache();return useMutation({mutationFn: ({category,@@ -117,7 +187,6 @@ export function useReorderIssueStatuses() {ordered: IssueStatusEntry[];}) => api.reorderIssueStatuses(category, ordered.map((entry) => entry.id)),onMutate: async ({ ordered }) => {- const listKey = issueStatusKeys.list(wsId);await qc.cancelQueries({ queryKey: listKey });const previous = qc.getQueryData<ListIssueStatusesResponse>(listKey);const positionById = new Map(ordered.map((e, index) => [e.id, index + 1]));@@ -136,11 +205,15 @@ export function useReorderIssueStatuses() {}: old,);- return { previous, listKey };+ return { previous };},+ // Reorder answers with the FULL catalog, and that is precisely why the+ // response is not installed: a whole-table snapshot that arrives late+ // overwrites every row, so ONE slow reorder response would roll back every+ // concurrent edit the refetch had already picked up.onError: (_err, _vars, ctx) => {- if (ctx?.previous && ctx.listKey) qc.setQueryData(ctx.listKey, ctx.previous);+ if (ctx?.previous) qc.setQueryData(listKey, ctx.previous);+ invalidate();},- onSettled: invalidate,});}diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex 27f4a96836..952b95a069 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -12,6 +12,7 @@ import { chatKeys } from "../chat/queries";import { workspaceWorkingAgentsKeys } from "../agents/queries";import { workspaceKeys } from "../workspace/queries";import { dingtalkKeys } from "../dingtalk/queries";+import { issueStatusKeys } from "../issue-statuses/queries";import {markWorkspaceDeletePending,unmarkWorkspaceDeletePending,@@ -119,8 +120,8 @@ describe("useRealtimeSync — ws instance change", () => {// (16 workspace-scoped [incl. property definitions] + 6 per-issue// prefixes + the workspace working-agents projection + 5 per-chat// prefixes + 1 workspaceKeys.list() + 1 cross-workspace inbox unread- // summary = 30 calls)- expect(invalidateSpy).toHaveBeenCalledTimes(30);+ // summary = 31 calls)+ expect(invalidateSpy).toHaveBeenCalledTimes(31);});it("does not re-invalidate when rerendered with the same ws instance", () => {@@ -154,6 +155,9 @@ describe("useRealtimeSync — ws instance change", () => {expect(calls).toContainEqual(["chat", "ws-1"]);expect(calls).toContainEqual(["labels", "ws-1"]);expect(calls).toContainEqual(["workspaces", "ws-1", "invitations"]);+ // A catalog edit made while this client was disconnected is otherwise+ // invisible for the query's whole 5-minute staleTime.+ expect(calls).toContainEqual(issueStatusKeys.all("ws-1"));});it("invalidates per-issue caches (no wsId in key) on ws instance change", () => {@@ -237,6 +241,30 @@ describe("useRealtimeSync — ws instance change", () => {});});+ it("refetches the status catalog after an admin changes it elsewhere", async () => {+ const ws = createMockWs();+ renderHook(() => useRealtimeSync(ws, stores), {+ wrapper: createWrapper(qc),+ });+ const onAny = vi.mocked(ws.onAny).mock.calls[0]?.[0];+ expect(onAny).toBeDefined();++ onAny!({ type: "issue_status:changed", payload: { action: "created" } } as never);+ await new Promise((resolve) => setTimeout(resolve, 120));++ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: issueStatusKeys.all("ws-1"),+ });+ // Deliberately NOT the issue caches. A row stores the status KEY; its name,+ // color and category are resolved from the catalog at render time, so no+ // cached issue field can go stale here. Dragging every board and list along+ // would turn one admin rename into a workspace-wide refetch storm on every+ // connected client. (MUL-6458)+ expect(invalidateSpy).not.toHaveBeenCalledWith({+ queryKey: issueKeys.all("ws-1"),+ });+ });+it("invalidates DingTalk group routes after a route update event", async () => {const ws = createMockWs();renderHook(() => useRealtimeSync(ws, stores), {diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 5e506b81ed..18117f694a 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -16,6 +16,7 @@ import { autopilotKeys } from "../autopilots/queries";import { runtimeKeys } from "../runtimes/queries";import { labelKeys } from "../labels/queries";import { propertyKeys } from "../properties/queries";+import { issueStatusKeys } from "../issue-statuses/queries";import {agentTaskSnapshotKeys,workspaceWorkingAgentsKeys,@@ -658,6 +659,10 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {qc.invalidateQueries({ queryKey: chatKeys.all(wsId) });qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });+ // A catalog edit missed while disconnected would otherwise sit behind the+ // 5-minute staleTime — long enough to offer a status the server already+ // archived, or to keep painting its old name.+ qc.invalidateQueries({ queryKey: issueStatusKeys.all(wsId) });}// Cross-workspace, so outside the wsId guard: a reconnect may have missed// inbox events from any workspace, so re-pull the switcher-dot summary.@@ -810,6 +815,20 @@ export function useRealtimeSync(qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });}},+ // The issue status catalog (MUL-6243). An admin edits it in the settings+ // page; every other tab and device is rendering statuses out of it.+ //+ // Invalidate only — the event carries no entry to merge. Issue caches are+ // deliberately NOT dragged along: a row stores the status KEY, and its+ // name, color and category are resolved from this catalog at render time+ // (`useStatusLabel`, `colorOf`), so refetching the catalog is what makes a+ // rename repaint. Pulling every board and list with it would turn one+ // admin rename into a workspace-wide refetch storm on every connected+ // client. (MUL-6458)+ issue_status: () => {+ const wsId = getCurrentWsId();+ if (wsId) qc.invalidateQueries({ queryKey: issueStatusKeys.all(wsId) });+ },pin: () => {const wsId = getCurrentWsId();const userId = authStore.getState().user?.id;diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 48bf7a9fb2..dd9c56b38b 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -77,6 +77,7 @@ export type WSEventType =| "issue_properties:changed"| "property:created"| "property:updated"+ | "issue_status:changed"| "pin:created"| "pin:deleted"| "pin:reordered"@@ -148,6 +149,22 @@ export interface PropertyChangedPayload {property: IssueProperty;}+/**+ * The workspace issue status catalog changed (MUL-6243).+ *+ * One event covers all four writes because clients answer them the same way:+ * re-read the catalog. It deliberately carries no entry — merging a row out of+ * an event would have to be reconciled against writes this client never saw,+ * and the catalog is small enough that a refetch is both simpler and safer.+ *+ * `action` is advisory: it makes the frame self-describing in devtools. Nothing+ * routes on it, so a future write verb this client has never heard of still+ * refreshes the catalog correctly.+ */+export interface IssueStatusChangedPayload {+ action?: "created" | "updated" | "archived" | "reordered";+}+export interface AgentStatusPayload {agent: Agent;}@@ -531,6 +548,7 @@ export interface WSEventPayloadMap {"issue_properties:changed": IssuePropertiesChangedPayload;"property:created": PropertyChangedPayload;"property:updated": PropertyChangedPayload;+ "issue_status:changed": IssueStatusChangedPayload;"issue_reaction:added": IssueReactionAddedPayload;"issue_reaction:removed": IssueReactionRemovedPayload;"comment:created": CommentCreatedPayload;diff --git a/server/internal/handler/issue_status.go b/server/internal/handler/issue_status.goindex 79a58005eb..781010c0ed 100644--- a/server/internal/handler/issue_status.go+++ b/server/internal/handler/issue_status.go@@ -15,6 +15,7 @@ import ("github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol")// Issue status catalog API (MUL-6243).@@ -125,7 +126,8 @@ func (h *Handler) CreateIssueStatus(w http.ResponseWriter, r *http.Request) {if !ok {return}- if _, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin"); !ok {+ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")+ if !ok {return}@@ -194,6 +196,7 @@ func (h *Handler) CreateIssueStatus(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to create issue status")return}+ h.publishIssueStatusChanged(workspaceID, member, "created")writeJSON(w, http.StatusCreated, issueStatusToResponse(entry))}@@ -201,7 +204,7 @@ func (h *Handler) CreateIssueStatus(w http.ResponseWriter, r *http.Request) {// immutable in v1 — name and color included — so the default workspace looks// and behaves identically for everyone who never opens this settings page.func (h *Handler) UpdateIssueStatus(w http.ResponseWriter, r *http.Request) {- entry, wsUUID, ok := h.loadIssueStatusForAdmin(w, r)+ entry, wsUUID, member, ok := h.loadIssueStatusForAdmin(w, r)if !ok {return}@@ -275,14 +278,16 @@ func (h *Handler) UpdateIssueStatus(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to update issue status")return}+ h.publishIssueStatusChanged(uuidToString(wsUUID), member, "updated")writeJSON(w, http.StatusOK, issueStatusToResponse(updated))}-// ArchiveIssueStatus retires a custom status. It refuses while any issue still-// sits on the status: silently rewriting those issues would change their-// machine semantics with no audit trail, so the caller migrates them first.+// ArchiveIssueStatus retires a custom status from FUTURE assignment. Issues+// already on it are deliberately left alone — see the note on the transaction+// below, which is also what makes "no new issue can be assigned an archived+// status" exact rather than approximate.func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {- entry, wsUUID, ok := h.loadIssueStatusForAdmin(w, r)+ entry, wsUUID, member, ok := h.loadIssueStatusForAdmin(w, r)if !ok {return}@@ -340,23 +345,29 @@ func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to archive issue status")return}+ // After the commit, never before: an event that announced a change the+ // transaction then rolled back would have every other tab re-read the+ // catalog and cache the pre-archive row as the new truth.+ h.publishIssueStatusChanged(uuidToString(wsUUID), member, "archived")writeJSON(w, http.StatusOK, issueStatusToResponse(archived))}// loadIssueStatusForAdmin resolves the {id} path param inside the caller's-// workspace and enforces the owner/admin gate.-func (h *Handler) loadIssueStatusForAdmin(w http.ResponseWriter, r *http.Request) (db.IssueStatus, pgtype.UUID, bool) {+// workspace and enforces the owner/admin gate. The member it resolved is+// returned so the write can name its actor on the realtime event.+func (h *Handler) loadIssueStatusForAdmin(w http.ResponseWriter, r *http.Request) (db.IssueStatus, pgtype.UUID, db.Member, bool) {workspaceID := h.resolveWorkspaceID(r)wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")if !ok {- return db.IssueStatus{}, pgtype.UUID{}, false+ return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false}- if _, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin"); !ok {- return db.IssueStatus{}, pgtype.UUID{}, false+ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")+ if !ok {+ return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false}idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "issue status id")if !ok {- return db.IssueStatus{}, pgtype.UUID{}, false+ return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false}entry, err := h.Queries.GetIssueStatusEntryByID(r.Context(), db.GetIssueStatusEntryByIDParams{ID: idUUID,@@ -365,13 +376,26 @@ func (h *Handler) loadIssueStatusForAdmin(w http.ResponseWriter, r *http.Requestif err != nil {if errors.Is(err, pgx.ErrNoRows) {writeError(w, http.StatusNotFound, "issue status not found")- return db.IssueStatus{}, pgtype.UUID{}, false+ return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false}slog.Warn("load issue status failed", append(logger.RequestAttrs(r), "error", err)...)writeError(w, http.StatusInternalServerError, "failed to load issue status")- return db.IssueStatus{}, pgtype.UUID{}, false+ return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false}- return entry, wsUUID, true+ return entry, wsUUID, member, true+}++// publishIssueStatusChanged announces that the workspace catalog moved.+//+// One event for every write (see protocol.EventIssueStatusChanged): clients+// re-read the catalog, they do not merge the payload. Nothing about the+// changed row travels here on purpose — a client that merged an entry out of+// an event would have to reconcile it against a concurrent write it cannot+// see, and the catalog is a handful of rows to re-read.+func (h *Handler) publishIssueStatusChanged(workspaceID string, actor db.Member, action string) {+ h.publish(protocol.EventIssueStatusChanged, workspaceID, "member", uuidToString(actor.UserID), map[string]any{+ "action": action,+ })}// ReorderIssueStatusesRequest carries one category's custom statuses in their@@ -406,7 +430,8 @@ func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {if !ok {return}- if _, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin"); !ok {+ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")+ if !ok {return}@@ -543,6 +568,7 @@ func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")return}+ h.publishIssueStatusChanged(workspaceID, member, "reordered")resp := make([]IssueStatusResponse, len(entries))for i, e := range entries {diff --git a/server/internal/handler/issue_status_test.go b/server/internal/handler/issue_status_test.goindex e3ec18ebd3..79d4df39a3 100644--- a/server/internal/handler/issue_status_test.go+++ b/server/internal/handler/issue_status_test.go@@ -14,6 +14,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -1232,3 +1233,109 @@ func TestBackgroundEventCarriesCustomStatusCategory(t *testing.T) {t.Errorf("status = %v, want the custom key verbatim", authoritative["status"])}}++// TestCatalogWritesAnnounceThemselves pins the realtime contract for the status+// catalog (MUL-6458): every write that changes it publishes exactly one+// workspace-scoped event, and a write that changes nothing publishes none.+//+// One event type covers all four writes because every client answers them the+// same way — re-read the catalog. What the assertions below are really+// protecting is the routing: an event with an empty WorkspaceID is dropped by+// the SubscribeAll forwarder without a word, so the catalog would look+// synchronized in tests and silently never reach another tab.+func TestCatalogWritesAnnounceThemselves(t *testing.T) {+ ctx := context.Background()+ seedTestCatalog(t)+ withCustomIssueStatusesFlag(t, testHandler, true)++ changes := make(chan events.Event, 8)+ testHandler.Bus.Subscribe(protocol.EventIssueStatusChanged, func(e events.Event) {+ select {+ case changes <- e:+ default:+ }+ })++ expectChange := func(t *testing.T, action string) {+ t.Helper()+ select {+ case e := <-changes:+ if e.WorkspaceID != testWorkspaceID {+ t.Errorf("event workspace_id = %q, want %q — an event without one never "++ "reaches a client", e.WorkspaceID, testWorkspaceID)+ }+ if e.ActorType != "member" || e.ActorID == "" {+ t.Errorf("event actor = %q/%q, want the acting member", e.ActorType, e.ActorID)+ }+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ t.Fatalf("event payload shape: %T", e.Payload)+ }+ if payload["action"] != action {+ t.Errorf("event action = %v, want %q", payload["action"], action)+ }+ case <-time.After(3 * time.Second):+ t.Fatalf("no issue_status:changed event for %s — other tabs keep the stale catalog "++ "until its 5 minute staleTime expires", action)+ }+ }+ expectNoChange := func(t *testing.T) {+ t.Helper()+ select {+ case e := <-changes:+ t.Fatalf("unexpected issue_status:changed event: %v", e.Payload)+ case <-time.After(300 * time.Millisecond):+ }+ }++ var created IssueStatusResponse+ testutil.Call(t, testHandler.CreateIssueStatus,+ newRequest(http.MethodPost, "/api/issue-statuses", map[string]any{+ "name": "Realtime Gate", "category": issuestatus.InReview, "color": "#123456",+ })).Want(http.StatusCreated).JSON(&created)+ dbfx.Cleanup(t, `DELETE FROM issue_status WHERE id = $1`, parseUUID(created.ID))+ expectChange(t, "created")++ testutil.Call(t, testHandler.UpdateIssueStatus, withURLParam(+ newRequest(http.MethodPatch, "/api/issue-statuses/"+created.ID, map[string]any{"name": "Renamed Gate"}),+ "id", created.ID)).Want(http.StatusOK)+ expectChange(t, "updated")++ // Reorder demands EVERY active custom status in the category, so the+ // payload is read back rather than assumed — a status left over from+ // another test would otherwise turn this into a 409.+ active, err := testHandler.Queries.ListActiveCustomIssueStatusEntries(ctx, db.ListActiveCustomIssueStatusEntriesParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ Category: issuestatus.InReview,+ })+ if err != nil {+ t.Fatalf("list active custom statuses: %v", err)+ }+ ids := make([]string, len(active))+ for i, entry := range active {+ ids[i] = uuidToString(entry.ID)+ }+ if code := reorderVia(t, issuestatus.InReview, ids).Code; code != http.StatusOK {+ t.Fatalf("reorder: %d", code)+ }+ expectChange(t, "reordered")++ entry, err := testHandler.Queries.GetIssueStatusEntryByID(ctx, db.GetIssueStatusEntryByIDParams{+ ID: parseUUID(created.ID),+ WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil {+ t.Fatalf("reload created status: %v", err)+ }+ if code := archiveStatusVia(t, entry); code != http.StatusOK {+ t.Fatalf("archive: %d", code)+ }+ expectChange(t, "archived")++ // Archiving an already-archived status is a 200 no-op. Announcing it would+ // have every other client re-read a catalog that did not move.+ if code := archiveStatusVia(t, entry); code != http.StatusOK {+ t.Fatalf("second archive: %d", code)+ }+ expectNoChange(t)+}diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex ea29a5f8ef..02090c8a1e 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -109,6 +109,15 @@ const (EventPropertyUpdated = "property:updated"EventIssuePropertiesChanged = "issue_properties:changed"+ // Issue status catalog events (MUL-6243). ONE event for all four writes+ // — create, edit, archive, reorder — rather than a verb per write, because+ // the catalog is read as a whole table and every client answers all four+ // the same way: re-read it. Splitting it would mint four contracts that no+ // consumer can tell apart, and reorder has no single row to name anyway.+ // The `action` in the payload is advisory (it makes a frame in devtools+ // self-describing); nothing routes on it.+ EventIssueStatusChanged = "issue_status:changed"+// Pin eventsEventPinCreated = "pin:created"EventPinDeleted = "pin:deleted"