Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): live-resort board/list on updated_at drift (MUL-5016) (#5671)
Bohan Jiangd3fac023c91a
diff --git a/packages/core/issues/cache-coordinator.test.ts b/packages/core/issues/cache-coordinator.test.tsindex 4018283df7..5791687e42 100644--- a/packages/core/issues/cache-coordinator.test.ts+++ b/packages/core/issues/cache-coordinator.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";import { QueryClient, hashKey } from "@tanstack/react-query";import {applyIssueChange,+ invalidateUpdatedAtSortedIssueLists,rollbackIssueChange,type IssueFlatCache,} from "./cache-coordinator";@@ -56,6 +57,29 @@ const flatSearchKey = issueKeys.flat({ q: "Issue 1" },sort,);+const updatedSort: IssueSortParam = {+ sort_by: "updated_at",+ sort_direction: "desc",+};+const wsUpdatedKey = issueKeys.listSorted(WS_ID, updatedSort);+const myAllUpdatedKey = issueKeys.myListSorted(WS_ID, "all", {}, updatedSort);+const flatUpdatedSortKey = issueKeys.flat(+ WS_ID,+ "workspace:all",+ {},+ updatedSort,+);+// Assignee-grouped boards fold the sort into their filter bag+// (issueAssigneeGroupsOptions does `{ ...filter, ...sort }`).+const assigneeGroupsUpdatedKey = issueKeys.assigneeGroups(WS_ID, {+ ...updatedSort,+});+const assigneeGroupsPositionKey = issueKeys.assigneeGroups(WS_ID, {+ sort_by: "position",+});+const myAssigneeGroupsUpdatedKey = issueKeys.myAssigneeGroups(WS_ID, "all", {+ ...updatedSort,+});function makeIssue(idx: number, overrides: Partial<Issue> = {}): Issue {return {@@ -214,6 +238,41 @@ describe("applyIssueChange", () => {expect(result.staleKeys.map(hashKey)).toContain(hashKey(flatSearchKey));});+ it("same-status field edit re-sorts an updated_at-sorted board but not a position-sorted one", () => {+ // Same card loaded in a position-sorted board and an updated_at-sorted one.+ qc.setQueryData<ListIssuesCache>(wsKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(wsUpdatedKey, bucketed([issue()]));++ const patch = { priority: "high" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ // The card is patched in place in both (no status/position move).+ expect(ids(qc, wsKey, "todo")).toEqual(["issue-1"]);+ expect(ids(qc, wsUpdatedKey, "todo")).toEqual(["issue-1"]);+ // Only the updated_at-sorted board is marked for a server re-sort; the+ // edit advanced updated_at so its loaded slot drifted.+ const stale = result.staleKeys.map(hashKey);+ expect(stale).toContain(hashKey(wsUpdatedKey));+ expect(stale).not.toContain(hashKey(wsKey));+ });++ it("marks an updated_at-sorted board stale even when the edited card is beyond its window", () => {+ // Card not in the loaded window (empty bucket, non-zero total): an edit+ // that bumps updated_at can still surface it, so the key must refetch.+ qc.setQueryData<ListIssuesCache>(myAllUpdatedKey, bucketed([], 3));++ const patch = { title: "renamed" };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ expect(result.staleKeys.map(hashKey)).toContain(hashKey(myAllUpdatedKey));+ });+it("status change: rebuckets loaded cards, patches inbox, adjusts counts for absent-but-member lists", () => {qc.setQueryData<ListIssuesCache>(wsKey, bucketed([issue()]));// p1 list loaded but the card is beyond its loaded window — the change@@ -463,3 +522,65 @@ describe("applyIssueChange", () => {expect(result.staleKeys.map(hashKey)).not.toContain(hashKey(groupedKey));});});++describe("invalidateUpdatedAtSortedIssueLists", () => {+ let qc: QueryClient;++ beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ });++ afterEach(() => {+ qc.clear();+ });++ it("invalidates only the updated_at-sorted board, myList, and flat keys", () => {+ // Two boards, two flat windows: one pair sorted by position, one by+ // updated_at. Only the updated_at pair should be refetched.+ qc.setQueryData<ListIssuesCache>(wsKey, bucketed([makeIssue(1)]));+ qc.setQueryData<ListIssuesCache>(wsUpdatedKey, bucketed([makeIssue(1)]));+ qc.setQueryData<ListIssuesCache>(myAllUpdatedKey, bucketed([makeIssue(1)]));+ qc.setQueryData<IssueFlatCache>(flatKey, {+ pages: [{ issues: [makeIssue(1)], total: 1 }],+ pageParams: [0],+ });+ qc.setQueryData<IssueFlatCache>(flatUpdatedSortKey, {+ pages: [{ issues: [makeIssue(1)], total: 1 }],+ pageParams: [0],+ });++ invalidateUpdatedAtSortedIssueLists(qc, WS_ID);++ expect(qc.getQueryState(wsUpdatedKey)?.isInvalidated).toBe(true);+ expect(qc.getQueryState(myAllUpdatedKey)?.isInvalidated).toBe(true);+ expect(qc.getQueryState(flatUpdatedSortKey)?.isInvalidated).toBe(true);+ expect(qc.getQueryState(wsKey)?.isInvalidated).toBe(false);+ expect(qc.getQueryState(flatKey)?.isInvalidated).toBe(false);+ });++ it("invalidates updated_at-sorted assignee-grouped boards (workspace + My Issues)", () => {+ // Grouped boards carry the sort inside their filter bag, not a standalone+ // sort key — they must still re-sort under "Updated date".+ qc.setQueryData(assigneeGroupsUpdatedKey, { groups: [] });+ qc.setQueryData(myAssigneeGroupsUpdatedKey, { groups: [] });+ qc.setQueryData(assigneeGroupsPositionKey, { groups: [] });++ invalidateUpdatedAtSortedIssueLists(qc, WS_ID);++ expect(qc.getQueryState(assigneeGroupsUpdatedKey)?.isInvalidated).toBe(true);+ expect(qc.getQueryState(myAssigneeGroupsUpdatedKey)?.isInvalidated).toBe(+ true,+ );+ expect(qc.getQueryState(assigneeGroupsPositionKey)?.isInvalidated).toBe(+ false,+ );+ });++ it("is a no-op when no updated_at-sorted list is loaded", () => {+ qc.setQueryData<ListIssuesCache>(wsKey, bucketed([makeIssue(1)]));++ invalidateUpdatedAtSortedIssueLists(qc, WS_ID);++ expect(qc.getQueryState(wsKey)?.isInvalidated).toBe(false);+ });+});diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.tsindex 65d8503684..192c12316a 100644--- a/packages/core/issues/cache-coordinator.ts+++ b/packages/core/issues/cache-coordinator.ts@@ -94,19 +94,27 @@ export interface IssueCacheChangeResult {}/** The server contract a bucketed list key encodes. `myListSorted` keys are- * `["issues", wsId, "my", scope, filter, sort]`; the workspace list carries- * no filter. The `byStatus` shape check upstream keeps grouped/flat caches- * under the same prefixes out of this path. */-function listContractFromKey(- key: QueryKey,-): { scope: string | undefined; filter: MyIssuesFilter } {+ * `["issues", wsId, "my", scope, filter, sort]`; the workspace list is+ * `["issues", wsId, "list", sort]` and carries no filter. The `byStatus`+ * shape check upstream keeps grouped/flat caches under the same prefixes out+ * of this path. */+function listContractFromKey(key: QueryKey): {+ scope: string | undefined;+ filter: MyIssuesFilter;+ sort: IssueSortParam;+} {if (key[2] === "my") {return {scope: typeof key[3] === "string" ? key[3] : undefined,filter: (key[4] ?? {}) as MyIssuesFilter,+ sort: (key[5] ?? {}) as IssueSortParam,};}- return { scope: undefined, filter: {} };+ return {+ scope: undefined,+ filter: {},+ sort: (key[3] ?? {}) as IssueSortParam,+ };}function bucketedListEntries(@@ -154,6 +162,19 @@ function patchFieldChanged<K extends keyof Issue>(return !base || !Object.is(patch[field], base[field]);}+/** Whether the patch changes at least one issue field relative to `base`.+ * Every persisted edit also advances `updated_at` server-side even though the+ * optimistic request payload does not carry that timestamp, so this doubles+ * as "did updated_at advance" for `updated_at`-sorted surfaces. */+function patchChangesAnyIssueField(+ patch: Partial<Issue>,+ base: Issue | undefined,+): boolean {+ return Object.keys(patch).some((field) =>+ patchFieldChanged(patch, base, field as keyof Issue),+ );+}+/** Whether a patch can change a flat window's membership or ordering. A* loaded row is always patched optimistically; only windows whose server* contract depends on the changed field need the follow-up refetch. */@@ -164,9 +185,7 @@ function flatWindowNeedsReconcile(changed: IssueChangedDims,) {const { scope, filter, sort } = flatContractFromKey(key);- const anyIssueFieldChanged = Object.keys(patch).some((field) =>- patchFieldChanged(patch, base, field as keyof Issue),- );+ const anyIssueFieldChanged = patchChangesAnyIssueField(patch, base);if (listFilterDependsOn(scope, filter, changed)) return true;if (filter.q && patchFieldChanged(patch, base, "title")) return true;@@ -245,10 +264,23 @@ export function applyIssueChange(let prevIssue: Issue | undefined = baseIssue;for (const [key, data] of bucketedListEntries(qc, wsId)) {- const { scope, filter } = listContractFromKey(key);+ const { scope, filter, sort } = listContractFromKey(key);const loc = findIssueLocation(data, id);const filterTouched = listFilterDependsOn(scope, filter, changed);+ // "Updated date" sort: every persisted edit advances updated_at, but the+ // optimistic patch carries no server timestamp and a loaded card keeps its+ // slot, so the board has drifted out of order. The right slot is server+ // knowledge — mark the key stale so the refetch re-sorts it. This mirrors+ // the updated_at case in flatWindowNeedsReconcile and, like it, does not+ // gate on this list's membership (an off-window member should surface too).+ if (+ sort.sort_by === "updated_at" &&+ patchChangesAnyIssueField(patch, loc?.issue ?? baseIssue)+ ) {+ staleKeys.push(key);+ }+if (loc) {if (!prevIssue) prevIssue = loc.issue;let next: ListIssuesCache;@@ -422,6 +454,42 @@ export function invalidateIssueDerivatives(}}+/** True when any object part of a query key encodes an "Updated date" ordering+ * (`sort_by: "updated_at"`). Bucketed status boards and flat tables keep the+ * sort in a standalone bag; assignee-grouped boards merge it into their filter+ * bag (see `issueAssigneeGroupsOptions`). Scanning every object part matches+ * all of those surfaces — workspace and My Issues — with one rule. */+function queryKeyHasUpdatedAtSort(key: QueryKey): boolean {+ return key.some(+ (part) =>+ !!part &&+ typeof part === "object" &&+ !Array.isArray(part) &&+ (part as Record<string, unknown>).sort_by === "updated_at",+ );+}++/**+ * Refetch every loaded issue list/board ordered by "Updated date" so a card+ * whose `updated_at` just advanced re-sorts to its true slot. Used by events+ * that bump `updated_at` without carrying the new timestamp or a field patch:+ * `comment:created` (MUL-5009) and the property/metadata WS events, all of+ * which advance the issue's `updated_at` server-side but bypass the+ * coordinator's field-diff path. Covers status boards, flat tables, AND+ * assignee-grouped boards (workspace + My Issues); only `updated_at`-sorted+ * keys are touched. The refetch is authoritative (server order + tie-breaks),+ * which also surfaces a touched card sitting beyond the loaded window.+ */+export function invalidateUpdatedAtSortedIssueLists(+ qc: QueryClient,+ wsId: string,+): void {+ qc.invalidateQueries({+ queryKey: issueKeys.all(wsId),+ predicate: (query) => queryKeyHasUpdatedAtSort(query.queryKey),+ });+}+/** Invalidate the stale keys reported by {@link applyIssueChange}, deduped —* a batch over N issues can report the same key N times. */export function invalidateStaleListKeys(qc: QueryClient, staleKeys: QueryKey[]) {diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.tsindex e135907c75..143f6986a2 100644--- a/packages/core/issues/ws-updaters.test.ts+++ b/packages/core/issues/ws-updaters.test.ts@@ -240,6 +240,23 @@ describe("onIssueMetadataChanged", () => {expect(qc.getQueryData(issueKeys.detail(WS_ID, ISSUE_ID))).toBeUndefined();expect(qc.getQueryData(issueKeys.list(WS_ID))).toBeUndefined();});++ it("re-sorts an updated_at-sorted board but not a position-sorted one", () => {+ // A metadata write bumps updated_at server-side (MUL-5016), so a board+ // sorted by "Updated date" must refetch; a position-sorted board must not.+ const boardUpdatedKey = issueKeys.listSorted(WS_ID, {+ sort_by: "updated_at",+ sort_direction: "desc",+ });+ const boardPositionKey = issueKeys.listSorted(WS_ID, { sort_by: "position" });+ qc.setQueryData<ListIssuesCache>(boardUpdatedKey, makeListCache(baseIssue));+ qc.setQueryData<ListIssuesCache>(boardPositionKey, makeListCache(baseIssue));++ onIssueMetadataChanged(qc, WS_ID, ISSUE_ID, { foo: "bar" });++ expectInvalidated(qc, boardUpdatedKey);+ expect(qc.getQueryState(boardPositionKey)?.isInvalidated).toBe(false);+ });});describe("issue property snapshots", () => {@@ -268,6 +285,29 @@ describe("issue property snapshots", () => {expectInvalidated(qc, flatKey);});++ it("re-sorts an updated_at-sorted board but not a position-sorted one after commit", () => {+ // A property write also bumps updated_at server-side (MUL-5016), so a board+ // sorted by "Updated date" (no property param) must refetch on commit while+ // a position-sorted board stays put.+ const qc = new QueryClient();+ const boardUpdatedKey = issueKeys.listSorted(WS_ID, {+ sort_by: "updated_at",+ sort_direction: "desc",+ });+ const boardPositionKey = issueKeys.listSorted(WS_ID, { sort_by: "position" });+ qc.setQueryData<ListIssuesCache>(boardUpdatedKey, makeListCache(baseIssue));+ qc.setQueryData<ListIssuesCache>(boardPositionKey, makeListCache(baseIssue));++ // Optimistic leg patches only — no premature refetch of either board.+ patchIssueProperties(qc, WS_ID, ISSUE_ID, { estimate: 3 });+ expect(qc.getQueryState(boardUpdatedKey)?.isInvalidated).toBe(false);++ onIssuePropertiesChanged(qc, WS_ID, ISSUE_ID, { estimate: 4 });++ expectInvalidated(qc, boardUpdatedKey);+ expect(qc.getQueryState(boardPositionKey)?.isInvalidated).toBe(false);+ });});describe("project progress invalidation", () => {diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.tsindex 1d57e3f578..3fdd1df6e0 100644--- a/packages/core/issues/ws-updaters.ts+++ b/packages/core/issues/ws-updaters.ts@@ -6,6 +6,7 @@ import {applyIssueChange,invalidateIssueDerivatives,invalidateStaleListKeys,+ invalidateUpdatedAtSortedIssueLists,type IssueFlatCache,} from "./cache-coordinator";import {@@ -270,6 +271,11 @@ export function onIssueMetadataChanged(old ? { ...old, metadata } : old,);qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });+ // A metadata write bumps issue.updated_at server-side (SetIssueMetadataKey /+ // DeleteIssueMetadataKey), but the patches above keep each card's slot, so a+ // board/table sorted by "Updated date" would stay in the old order. This+ // event is server-committed, so refetch those keys to re-sort (MUL-5016).+ invalidateUpdatedAtSortedIssueLists(qc, wsId);}/**@@ -292,6 +298,13 @@ export function onIssuePropertiesChanged(qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });invalidatePropertyWindowQueries(qc, wsId);+ // A property write also bumps issue.updated_at server-side+ // (SetIssuePropertyValue / DeleteIssuePropertyValue). invalidatePropertyWindow+ // Queries only refetches property-filtered/-sorted windows, so a status board+ // or flat table sorted by "Updated date" (no property param) would keep the+ // old order. Refetch those too. Only committed callers reach here (WS event ++ // mutation onSuccess); the optimistic leg uses patchIssueProperties (MUL-5016).+ invalidateUpdatedAtSortedIssueLists(qc, wsId);}/** Patch only deterministic entity snapshots. Optimistic mutation legs usediff --git a/packages/core/realtime/use-realtime-sync-comment.test.tsx b/packages/core/realtime/use-realtime-sync-comment.test.tsxnew file mode 100644index 0000000000..56e4489edc--- /dev/null+++ b/packages/core/realtime/use-realtime-sync-comment.test.tsx@@ -0,0 +1,118 @@+/**+ * @vitest-environment jsdom+ */+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook } from "@testing-library/react";+import type { ReactNode } from "react";+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import type { WSClient } from "../api/ws-client";+import { issueKeys, type IssueSortParam } from "../issues/queries";+import type { ListIssuesCache } from "../types";+import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";++vi.mock("../platform/workspace-storage", () => ({+ getCurrentWsId: () => "ws-1",+ getCurrentSlug: () => "test-ws",+}));++vi.mock("../paths", () => ({+ useHasOnboarded: () => true,+ resolvePostAuthDestination: () => "/",+}));++// Records every ws.on handler by event name so a test can fire one directly.+function createRecordingWs(): {+ ws: WSClient;+ handlers: Record<string, (p: unknown) => void>;+} {+ const handlers: Record<string, (p: unknown) => void> = {};+ const ws = {+ on: vi.fn((event: string, handler: (p: unknown) => void) => {+ handlers[event] = handler;+ return () => {};+ }),+ onAny: vi.fn(() => () => {}),+ onReconnect: vi.fn(() => () => {}),+ } as unknown as WSClient;+ return { ws, handlers };+}++function createStores(): RealtimeSyncStores {+ return {+ authStore: Object.assign(() => ({}), {+ getState: () => ({ user: { id: "u1" } }),+ subscribe: () => () => {},+ setState: () => {},+ destroy: () => {},+ }),+ } as unknown as RealtimeSyncStores;+}++function createWrapper(qc: QueryClient) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;+ };+}++const updatedSort: IssueSortParam = {+ sort_by: "updated_at",+ sort_direction: "desc",+};+const positionSort: IssueSortParam = { sort_by: "position" };+const updatedBoardKey = issueKeys.listSorted("ws-1", updatedSort);+const positionBoardKey = issueKeys.listSorted("ws-1", positionSort);++function bucketed(): ListIssuesCache {+ return { byStatus: { todo: { issues: [], total: 1 } } };+}++describe("useRealtimeSync — comment:created re-sorts Updated date lists", () => {+ let qc: QueryClient;++ beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ });++ afterEach(() => {+ qc.clear();+ vi.clearAllMocks();+ });++ it("invalidates the updated_at-sorted board but leaves the position board", () => {+ qc.setQueryData<ListIssuesCache>(updatedBoardKey, bucketed());+ qc.setQueryData<ListIssuesCache>(positionBoardKey, bucketed());+ qc.setQueryData(issueKeys.timeline("issue-1"), []);++ const { ws, handlers } = createRecordingWs();+ renderHook(() => useRealtimeSync(ws, createStores()), {+ wrapper: createWrapper(qc),+ });++ handlers["comment:created"]?.({+ comment: { id: "c1", issue_id: "issue-1" },+ });++ expect(qc.getQueryState(updatedBoardKey)?.isInvalidated).toBe(true);+ expect(qc.getQueryState(positionBoardKey)?.isInvalidated).toBe(false);+ // The per-issue timeline is still invalidated as before.+ expect(+ qc.getQueryState(issueKeys.timeline("issue-1"))?.isInvalidated,+ ).toBe(true);+ });++ it("ignores a comment event with no issue_id", () => {+ qc.setQueryData<ListIssuesCache>(updatedBoardKey, bucketed());++ const { handlers } = (() => {+ const rec = createRecordingWs();+ renderHook(() => useRealtimeSync(rec.ws, createStores()), {+ wrapper: createWrapper(qc),+ });+ return rec;+ })();++ handlers["comment:created"]?.({ comment: { id: "c1" } });++ expect(qc.getQueryState(updatedBoardKey)?.isInvalidated).toBe(false);+ });+});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 4bc3d2b5a3..9c2fee09e4 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -33,6 +33,7 @@ import {onIssuePropertiesChanged,onIssueMetadataChanged,} from "../issues/ws-updaters";+import { invalidateUpdatedAtSortedIssueLists } from "../issues/cache-coordinator";import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";import { inboxKeys } from "../inbox/queries";import {@@ -889,7 +890,15 @@ export function useRealtimeSync(const unsubCommentCreated = ws.on("comment:created", (p) => {const { comment } = p as CommentCreatedPayload;- if (comment?.issue_id) invalidateTimeline(comment.issue_id);+ if (!comment?.issue_id) return;+ invalidateTimeline(comment.issue_id);+ // A new comment bumps the parent issue's updated_at server-side+ // (MUL-5009), so any open board/list sorted by "Updated date" has+ // drifted. Refetch just those keys to re-sort the commented card into+ // place; every other sort is untouched. Only comment:created bumps+ // updated_at, so the other comment events below deliberately do not.+ const wsId = getCurrentWsId();+ if (wsId) invalidateUpdatedAtSortedIssueLists(qc, wsId);});const unsubCommentUpdated = ws.on("comment:updated", (p) => {