Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5198: Restore server-backed issue table grouping (MUL-5100) (#5817)

Multica Eve8065cead8553
diff --git a/docs/plans/2026-07-17-001-feat-issue-table-server-query-plan.md b/docs/plans/2026-07-17-001-feat-issue-table-server-query-plan.md
new file mode 100644
index 0000000000..d3003923b0
--- /dev/null
+++ b/docs/plans/2026-07-17-001-feat-issue-table-server-query-plan.md
@@ -0,0 +1,1167 @@
+---
+title: Issue Table Server Query and Grouping - Plan
+type: feat
+date: 2026-07-17
+topic: issue-table-server-query
+artifact_contract: ce-unified-plan/v1
+artifact_readiness: implementation-ready
+product_contract_source: product-and-code-audit
+execution: code
+---
+
+# Issue Table Server Query and Grouping - Plan
+
+> 本文定义 Table View 的目标产品语义、前后端边界和分阶段实施方案。核心目标不是提高当前的 `1000` 上限,而是移除“前端必须拥有完整结果集才能 Group/Hierarchy”的架构前提。
+
+> **Implementation status (2026-07-22):** 新 Table 路径的 canonical compiler、U2–U3、U5–U7,以及 U8 的 exact facets / cache invalidation 已落地;标准字段和默认 position keyset 顺序所需 concurrent indexes 已加入。Rows 先裁 page,再只为当前页解析 hierarchy;默认 position 续页额外提供可下推的 cursor range bound,避免深页从 workspace 索引起点线性过滤。Assignee 显示名在 actor 聚合后解析;无自身 active filter 的标准 facets 在批量请求中用 `GROUPING SETS` 共享一次 base scan。Legacy GET handlers 尚未迁入同一 compiler。Table 采用 hard cutover,新旧客户端仍可分别使用 additive table endpoints 与 legacy endpoints,不维护两套前端 Table truth。当前显式导出由浏览器遍历同一 rows Query Spec,并在 schema fallback、fingerprint/cursor 漂移、重复行或最终数量不等于首屏 total 时 fail closed;非默认/自定义属性排序仍可能扫描并排序完整 membership,由 query timeout 限损;server-stream / async export job、observability、100k/1m staging SLO 与 browser network smoke 属于后续收口项。
+
+## Goal Capsule
+
+- **Objective:** 让 Table 的 Filter、Search、Sort、Group、Hierarchy、Count 和 Export 对任意规模的结果集都保持正确,不再因结果数量改变产品行为。
+- **Product authority:** 本文的 Product Contract。实现不得以“已加载窗口”“浏览器内存上限”重新定义 Group、Hierarchy 或 Count 的语义。
+- **Primary user outcome:** 用户选择 Group 后,无论查询命中 10、1,001 还是 100,000 个 issue,都能立即看到准确的 Group Header 和 Count,并按需加载组内行。
+- **Execution profile:** Go backend + `packages/core` 查询层 + `packages/views` Table 渲染层的跨层改造;保留现有 flat/list/board API 作为兼容路径。
+- **Rollout:** 当前 Web/Desktop Table hard cutover 到 additive server Table endpoints;API 错误不得静默 fallback 到前端分组。旧客户端继续使用未删除的 legacy endpoints。
+- **Stop conditions:** U1–U8 完成;后端、core、views 测试通过;1001+ issue 场景浏览器验证通过;无自动全量物化;性能与一致性验收项达标。
+- **Open blockers:** 无产品决策 blocker。自定义属性 Group 的 100k 数据性能必须在 rollout 前用 `EXPLAIN (ANALYZE, BUFFERS)` 验证,但不阻塞标准字段实现。
+
+---
+
+## 1. Executive Decision
+
+采用一套后端权威的 `IssueTableQuerySpec`,所有需要对完整结果集求真的能力都从该 Query Spec 派生:
+
+- 后端负责 membership、search、sort、group membership、group count、hierarchy membership、facet count 和 aggregate;当前导出由前端遍历同一 server-authoritative rows query,后续可迁到 server-stream/job。
+- 前端负责 view mode、columns、column width、collapsed groups、collapsed parents、selection、density 和虚拟滚动。
+- Group Header 与 Rows 分开查询:Header 返回准确 Count;Rows 按展开且进入视口的 group/parent branch 使用 cursor 加载。
+- Group membership 默认取 issue 自己的字段,不再根据“是否完整加载”改用根父项字段。
+- Hierarchy 只嵌套“父子都命中当前 Query Spec 且 group key 相同”的关系;跨组或父项未命中的子项作为该组根行显示。
+- 第一版不支持 `multi_select` Group;仍支持它作为 Filter 和 Column。
+- 现有 `TABLE_STRUCTURE_MAX_WINDOW = 1000` 及其结构暂停逻辑在新路径稳定后删除,不改成更大的数字。
+
+目标数据流:
+
+```text
+View state
+ ├─ Query state: scope/filter/search/sort/group/hierarchy
+ │ └─ POST /api/issues/table/groups → exact group headers/counts
+ │ └─ POST /api/issues/table/rows → cursor-paged root/child rows
+ │ └─ POST /api/issues/table/facets → exact filter facets
+ │ └─ export replays table/rows pages → same server membership, fail closed
+ └─ Presentation state: columns/collapse/selection/density
+ └─ frontend render + virtualization
+```
+
+目标职责矩阵:
+
+| Capability | Target owner | Reason |
+|---|---|---|
+| Scope / Filter / Search | Backend | 决定完整 membership、total 和 export |
+| Sort / stable pagination | Backend | 必须跨 pages 保持全局顺序 |
+| Group membership / order / count | Backend | 必须对完整结果集求真 |
+| Hierarchy membership / child count | Backend | 父项可能不在当前客户端 window |
+| Facet count / aggregate | Backend | loaded rows 不能代表全集 |
+| Export | Backend membership + frontend orchestration(当前) | 显式导出逐页读取同一 rows query;fingerprint/cursor/schema 漂移或最终数量不等于首屏 total 时拒绝生成部分 CSV。server stream/job 为后续优化 |
+| View mode / columns / width / density | Frontend | 只改变呈现,不改变 membership |
+| Group / parent collapse | Frontend | 个人交互状态,决定哪些 branch 需要请求 |
+| Selection | Frontend | 当前交互 session 状态;membership 变化时清理 |
+| Saved View persistence | Backend(follow-up) | 团队共享、权限、跨设备和 URL identity |
+
+---
+
+## 2. Product Contract
+
+### 2.1 Problem Frame
+
+当前 Table 从 `GET /api/issues` 获取每页 100 条平铺数据。`tableGrouping` 和 `tableHierarchy` 不进入后端请求,而是在 `TableView` 中对已加载数组执行 `buildIssueTableRows`。
+
+为了让分组和父子树“看起来完整”,Table 在结果不超过 1000 时自动拉完所有 offset pages;超过 1000 时又把 Group 和 Hierarchy 强制改成 `none/false`。因此同一个用户动作的产品语义会随结果数量变化:
+
+- 999 条:Group 生效,但浏览器自动下载全部数据。
+- 1001 条:相同 Group 选择不生效,只显示一条弱提示。
+- Filter 缩窄到 1000 以下:Group 又自动恢复。
+- Hierarchy 开启时,子 issue 在窗口未完成前按自己字段归组,完成后改按根父项字段归组,行会跳组。
+
+这不是性能优化,而是查询责任放错层级后的行为不一致。
+
+### 2.2 Non-negotiable Invariants
+
+- **R1 — Result-size independence.** Group/Hierarchy 是否可用不得由结果数量决定。
+- **R2 — One query, one membership.** Table rows、group counts、facet counts、selection membership、export 必须使用同一个 Query Spec。
+- **R3 — Server-authoritative grouping.** Group membership 和 Count 必须由后端基于完整结果集计算;前端不得用 loaded rows 推断完整 Group。
+- **R4 — Bounded client window.** 首屏和滚动只加载视口需要的 pages/branches;不得因 Group、Hierarchy、Count 或 working chip 自动下载完整结果集。
+- **R5 — Stable semantics.** 同一 issue 的 group key 不得因分页加载进度变化。
+- **R6 — Explicit unsupported state.** 不支持的字段必须从 UI capability 中移除,或返回明确错误;不得允许用户选中后静默 no-op。
+- **R7 — Exact counts.** Group Header、Filter facet 和 Aggregate 标注为精确值时,必须来自后端完整查询集。
+- **R8 — No silent fallback.** 新路径请求失败时显示错误与 Retry,不得回退到 loaded-row grouping。
+- **R9 — Realtime correctness.** 会改变 membership、sort、group 或 hierarchy 的写入必须使相关查询失效并重新求真。
+- **R10 — Shareable query shape.** Query Spec 必须可序列化,以便后续 Saved View、URL 和 Export 复用;不得绑定 React component state。
+
+### 2.3 Query Semantics
+
+#### Filter
+
+- 空数组表示该维度不过滤。
+- 同一维度内 OR,不同维度间 AND。
+- `include_no_assignee` / `include_no_project` 与选中值做 OR。
+- Custom property filter 维持现有语义:同定义内 OR,定义间 AND。
+- `working_only` 由后端通过运行中 task membership 求值;新 Query Spec 不再要求浏览器发送全部 running issue IDs。
+- `include_sub_issues=false` 是 Query membership,后端使用 `parent_issue_id IS NULL`。
+- Search、Filter、Scope 共同决定唯一 membership 集合。
+
+#### Sort
+
+- V1 UI 保持单字段 Sort;API 使用单个 `{field, direction}` 对象。
+- `position` 表示 manual order,canonicalization 固定为 ascending;客户端传入的 descending 不改变语义。
+- 后端自动追加稳定 tie-break:`created_at DESC, id DESC`。
+- Hierarchy 开启时,Sort 应用于每一层的 siblings,而不是把所有 descendants 做一次全局排序。
+- Sparse date/property 值固定 `NULLS LAST`,升降序均一致。
+
+#### Group
+
+V1 支持:
+
+- `none`
+- `status`
+- `assignee`
+- `property:<id>`,仅 active `select` / `checkbox`
+
+V1 不支持:
+
+- `multi_select`:一个 issue 可能属于多个值,涉及重复行、unique total、batch selection 和 export 语义。
+- `text` / `url` / `number` / `date`:高基数 group 暂不作为首发能力。
+- archived/unknown property:返回 `unsupported_group_field`,前端清理 stale persisted value 并提示用户。
+
+Group membership 使用 issue 自己的值:
+
+- Status:`issue.status`。
+- Assignee:`assignee_type + assignee_id`;NULL 进入 `unassigned`。
+- Select:active option ID 正常成组;缺失值进入 `no-value`;引用已删除 option 的 stale value 进入单独的 `unavailable-value` group,不能和真正未填写合并。
+- Checkbox:`false`、`true`、`no-value` 是三个不同 group。
+
+只返回非空 group。Group order:
+
+- Status:使用 `ALL_STATUSES` 的 canonical order。
+- Assignee:按 display name case-insensitive 排序,再以 actor type/id tie-break;unassigned 最后。
+- Select:按 definition config option order;`unavailable-value`、`no-value` 依次排在最后。
+- Checkbox:false、true、no-value。
+
+#### Hierarchy
+
+Hierarchy 与 Group 同时存在时使用以下稳定规则:
+
+1. 父 issue 和子 issue 都必须命中当前 Query Spec。
+2. 两者 group key 必须相同。
+3. 同时满足时,子 issue 可嵌套在父 issue 下。
+4. 父项未命中、父项属于另一 group、或父项不存在时,子 issue 在自己的 group 中作为 root row 渲染。
+5. 不自动注入未命中的 ancestor context row;这样 total、selection 和 export 都只包含真正命中的 issue。
+6. 每个 row 返回当前查询下的 `direct_child_count`;子分支在展开/进入视口时按需加载。
+
+该规则避免“Todo 子项因为父项是 Backlog 而出现在 Backlog group”这种 group label 与 row value 冲突,也避免当前实现按加载完整度改变规则。
+
+#### Collapse and Selection
+
+- `collapsedGroups`、`collapsedParents` 保留为前端/个人状态。
+- 折叠 group 不请求 group rows。
+- 折叠 parent 不请求 child rows。
+- Selection 只包含真实 issue IDs,不包含 group headers 或 loading placeholders。
+- Query membership 改变时清理 selection;仅 Sort 改变时保留 selection,延续现有规则。
+
+### 2.4 Facet Count Semantics
+
+Filter 菜单中的数量采用 disjunctive faceting:
+
+- 计算某个维度的候选值时,保留 scope、search 和其他 filter dimensions。
+- 暂时排除当前 dimension 自身,再分别计算各 candidate count。
+- 已选值即使 count=0 仍返回,以便用户看到并移除。
+- Response 中的 counts 按 contract 即为精确值,不另设 `exact` 标记;超时或不可用时整个维度显示 loading/unknown,不显示 loaded-row 近似值。
+
+### 2.5 Toolbar Information Architecture
+
+Desktop Table header 调整为第一层能力:
+
+```text
+Filter · Sort: Title ↑ · Group: Status · Columns · Table
+```
+
+- `Sort` trigger 只承载排序,不再用 “Title” 入口承载 Group/Hierarchy/Columns。
+- `Group` trigger 始终展示当前字段;`None` 时可只显示 “Group”。
+- `Columns` 和 `Hierarchy` 放入 Table Display 菜单。
+- Mobile 可保留合并 Display popover,但 active Group 必须在 trigger/badge 中可见。
+- 新请求加载时保留上一组 headers 作为 placeholder,并显示 refreshing 状态;不闪回 ungrouped table。
+
+### 2.6 Acceptance Examples
+
+- **AE1 — 1001+ issues.** Given 查询命中 1,001 个 issue,When Group=Status,Then 所有非空 status headers 与准确 counts 出现,网络不会自动请求 11 个 flat pages。
+- **AE2 — Large assignee cardinality.** Given 10,000 个 issue、2,000 个 assignee groups,When 打开 Table,Then group headers 自身 cursor 分页;只为展开且进入视口的 groups 获取 rows。
+- **AE3 — Group count parity.** Given Filter=Priority High,When Group=Assignee,Then group counts 之和等于 Query total,且 Export 使用相同 membership。
+- **AE4 — Cross-group child.** Given parent.status=Todo、child.status=Done,且两者都命中,When Group=Status + Hierarchy on,Then child 作为 Done group 的 root row,不嵌套在 Todo parent 下。
+- **AE5 — Missing parent.** Given child 命中而 parent 不命中,Then child 作为自己的 group root;total 不加入 parent。
+- **AE6 — Same-group hierarchy.** Given parent/child 都是 Todo 且都命中,When 展开 parent,Then child 在 parent 下出现,child page 可继续 cursor 加载。
+- **AE7 — Multi-select property.** Given property type is multi_select,Then Group menu 不显示它;Filter 和 Column 仍可用。
+- **AE8 — Realtime regroup.** Given issue 从 Todo 改到 Done,Then loaded row 可立即 optimistic patch,随后 Todo/Done headers、counts 和 branches 失效并重新求真。
+- **AE9 — Error behavior.** Given group rows 请求失败,Then 对应 branch 显示 Retry;Table 不显示 loaded-row derived group。
+- **AE10 — Stale property.** Given persisted group references archived property,Then API 返回 structured unsupported error,前端切回 Group=None 并给出一次性说明。
+
+### 2.7 Scope Boundaries
+
+**本计划交付:**
+
+- Canonical Table Query Spec。
+- Server-backed group headers/counts。
+- Cursor-paged root/child rows。
+- Status、Assignee、Select、Checkbox Group。
+- Hierarchy lazy branches。
+- Exact filter facets。
+- Query-consistent export(当前复用 rows cursor;server stream/job 后续实现)。
+- Toolbar 信息架构调整。
+- Realtime cache correctness。
+- Hard-cutover compatibility、observability 和 rollout 验证。
+
+**后续能力,接口预留但不在首发:**
+
+- Multi-select Group。
+- 多字段 Group / nested Group。
+- 多字段 Sort。
+- text/number/date 高基数 Group。
+- Group aggregate footer 的 Sum/Average/Min/Max;V1 只完成 count 和现有 calculation state 清理。
+- Saved View 服务端实体、权限和团队共享。
+- Web URL 编码的临时 view overrides。
+- Board/List/Swimlane 全部切到同一 Query API;本计划先保证 Table。
+
+---
+
+## 3. Current-State Code Map
+
+### 3.1 Frontend State and Controls
+
+- `packages/core/issues/stores/view-store.ts`
+ - `tableGrouping`、`tableHierarchy`、collapsed groups/parents、columns 都在 Zustand。
+ - `viewStorePersistOptions` 把这些状态存入 workspace-aware local storage。
+ - `tableHierarchy` 默认 `true`,因此当前 Table 即使不 Group 也可能触发全量自动加载。
+- `packages/views/issues/components/issues-header.tsx`
+ - Display trigger 显示当前 Sort label,却同时容纳 Group、Hierarchy、Sort、Sub-issues 和 Columns。
+ - `tableGroupableProperties` 当前包含 `select`、`multi_select`、`checkbox`。
+ - Filter option counts 来自 `scopedIssues`;Table 未完成分页时 `facetCountsExact=false`,因此隐藏 counts。
+- `packages/views/issues/surface/use-issue-surface-controller.ts`
+ - 将 Filter/Search/Sort 编译成 `IssueFlatFilter + IssueSortParam`。
+ - 不读取 `tableGrouping` 作为查询参数,因此 Group 不进入 query key/API。
+ - Table Search 是本地 state + 250ms debounce。
+- `packages/core/issues/stores/surface-view-store.ts`
+ - View 状态按 surface key 存在本地 registry,不可分享。
+
+### 3.2 Table Data and Structure
+
+- `packages/core/issues/queries.ts`
+ - `ISSUE_FLAT_PAGE_SIZE = 100`。
+ - `issueFlatListOptions` 使用 offset infinite query。
+ - `fetchAllFlatPages` 用于 Export,在浏览器循环到 total。
+ - `scope === "all"` 时前端分别拉 assigned/created/involved,再合并去重。
+- `packages/views/issues/surface/use-issue-surface-data.ts`
+ - Table 使用 `useInfiniteQuery(issueSurfaceFlatOptions)`,再 flatten pages。
+ - 后端已经执行的 Filter 又在 loaded rows 上执行一次 `applyIssueFilters`。
+ - working chip 为了精确 scope 又维护第二个最多 1000 的 materialized window。
+- `packages/views/issues/components/table-view-model.ts`
+ - `TABLE_STRUCTURE_MAX_WINDOW = 1000`。
+ - `buildIssueTableRows` 在浏览器执行 Group/Hierarchy。
+ - complete hierarchy 下,group key 来自根 ancestor;incomplete window 下来自 issue 自己。
+- `packages/views/issues/components/table-view.tsx`
+ - Group/Hierarchy wanted 时连续 `fetchNextPage()`。
+ - total>1000 时把有效 Group/Hierarchy 强制关闭。
+ - Group count 使用 loaded `group.issues.length`。
+
+### 3.3 Backend
+
+- `server/internal/handler/issue.go::ListIssues`
+ - 支持 Table 的 status/priority/actor/project/label/property/date/search/top-level/ids filters。
+ - 执行 server sort、`LIMIT/OFFSET` 和独立 `COUNT(*)`。
+ - 每页 limit clamp 到 100。
+- `server/internal/handler/issue.go::QueryIssues`
+ - 只是 `GET /api/issues` 的 POST twin,接收 string map,解决大量 IDs 的 request-line 限制。
+- `server/internal/handler/issue.go::ListGroupedIssues`
+ - 后端分组雏形,只接受 `group_by=assignee`。
+ - 使用 `COUNT(*) OVER (PARTITION BY...)` 和 `ROW_NUMBER()`,offset/limit 对每组生效。
+ - 只服务 Board assignee grouping,Table 不调用。
+- `server/internal/handler/property.go`
+ - 已有 property filter compiler 和 typed property sort expression。
+- Existing indexes
+ - Workspace、status、assignee、parent、project、title trigram、properties GIN 已存在,但 assignee/parent 缺少 workspace-leading composite index。
+
+### 3.4 Root Cause
+
+`tableGrouping` 和 `tableHierarchy` 不属于服务器 query contract,导致:
+
+1. 后端只能返回平铺 pages。
+2. 前端要准确 Group/Tree 就必须拥有完整 membership。
+3. 完整 membership 与无限数据规模冲突。
+4. 1000 上限成为防止 unbounded download 的防护栏。
+5. 防护栏又被呈现成产品限制。
+
+因此修复点是 query contract,不是 Table render function,也不是把上限改大。
+
+---
+
+## 4. Target Query Contract
+
+### 4.1 Canonical Type
+
+TypeScript 形态;Go 使用等价 tagged structs:
+
+```ts
+type IssueTableScope =
+ | { kind: "workspace"; assignee_types?: IssueAssigneeType[] }
+ | { kind: "project"; project_id: string }
+ | { kind: "assignee"; actor: IssueActorRef }
+ | { kind: "creator"; actor: IssueActorRef }
+ | {
+ kind: "my";
+ relation: "assigned" | "created" | "involved" | "any";
+ };
+
+interface IssueTableFilters {
+ statuses?: IssueStatus[];
+ priorities?: IssuePriority[];
+ assignees?: IssueActorRef[];
+ include_no_assignee?: boolean;
+ creators?: IssueActorRef[];
+ project_ids?: string[];
+ include_no_project?: boolean;
+ label_ids?: string[];
+ properties?: Record<string, string[]>;
+ date?: {
+ field: "created_at" | "updated_at";
+ start: string;
+ end: string;
+ };
+ working_only?: boolean;
+ include_sub_issues?: boolean;
+}
+
+interface IssueTableQuerySpec {
+ scope: IssueTableScope;
+ filters: IssueTableFilters;
+ search?: string;
+ sort: {
+ field: SortField;
+ direction: "asc" | "desc";
+ };
+}
+
+type IssueTableGroupSpec =
+ | { kind: "none" }
+ | { kind: "status" }
+ | { kind: "assignee" }
+ | { kind: "property"; property_id: string };
+```
+
+设计约束:
+
+- `workspace_id` 继续由现有 workspace resolution/middleware 决定,不信任 body 中的任意 workspace ID。
+- `scope.kind="my"` 使用当前 authenticated user;body 不接受 user ID,防止查询其他用户的 personal relation scope。
+- Query Spec canonicalize 后生成 SHA-256 fingerprint;cursor 携带 version + fingerprint。
+- 所有 arrays 在 fingerprint 前排序/去重;语义顺序字段(如 status order)不直接使用客户端顺序。
+- 空值规范化为字段缺失,避免等价 query 产生不同 cache key/fingerprint。
+
+### 4.2 Endpoint: Group Headers
+
+`POST /api/issues/table/groups`
+
+Request:
+
+```json
+{
+ "query": {
+ "scope": { "kind": "workspace" },
+ "filters": { "statuses": ["todo", "in_progress"] },
+ "sort": { "field": "title", "direction": "asc" }
+ },
+ "group": { "kind": "status" },
+ "page": { "limit": 100, "cursor": null }
+}
+```
+
+Response:
+
+```json
+{
+ "query_fingerprint": "sha256:...",
+ "total": 18342,
+ "groups": [
+ {
+ "key": "status:todo",
+ "value": { "kind": "status", "status": "todo" },
+ "count": 5210
+ }
+ ],
+ "next_cursor": null
+}
+```
+
+Group value 是 tagged union:
+
+```ts
+type IssueTableGroupValue =
+ | { kind: "status"; status: IssueStatus }
+ | { kind: "assignee"; actor: IssueActorRef | null }
+ | {
+ kind: "property";
+ property_id: string;
+ value: string | boolean | null;
+ value_state: "value" | "unavailable" | "unset";
+ };
+```
+
+`value` 仅在 `value_state="value"` 时承载 active option/checkbox value;`unset` 与 `unavailable` 使用不同 stable group key,即使 response 中 value 为 null 也不会合并。
+
+Notes:
+
+- `total` 是 Query membership 的 unique issue 数量。
+- Group counts 之和必须等于 `total`,因为 V1 每个 issue 只属于一个 group。
+- Group headers 本身 cursor 分页,limit default/max 为 100。
+- Group label 由前端根据 locale/catalog 渲染;后端可在 assignee group SQL 中按 display name 排序,但不把 localized label 当 identity。
+
+### 4.3 Endpoint: Rows and Child Branches
+
+`POST /api/issues/table/rows`
+
+Request:
+
+```json
+{
+ "query": { "...": "same IssueTableQuerySpec" },
+ "group": { "kind": "status" },
+ "group_key": "status:todo",
+ "hierarchy": { "enabled": true },
+ "parent_id": null,
+ "page": { "limit": 50, "cursor": null }
+}
+```
+
+- `parent_id=null + hierarchy=true`:返回该 group 的 root rows。
+- `parent_id=<id> + hierarchy=true`:返回该 parent 的 direct matching/same-group children。
+- `hierarchy=false`:`parent_id` 必须为空,返回 group 中的平铺 rows。
+- `group.kind=none`:`group_key` 必须为空,同一 endpoint 支持 ungrouped Table。
+
+Response:
+
+```json
+{
+ "query_fingerprint": "sha256:...",
+ "group_key": "status:todo",
+ "parent_id": null,
+ "total": 0,
+ "rows": [
+ {
+ "issue": { "id": "...", "title": "..." },
+ "direct_child_count": 3
+ }
+ ],
+ "branch_total": 1,
+ "next_cursor": "opaque-cursor"
+}
+```
+
+`total` 只在 `group.kind=none`、`parent_id=null` 的首页返回整个 Query membership;续页、grouped branch 和 child branch 返回 `0`,grouped header 使用 groups response 的 `total`/`count`。`branch_total` 为兼容响应结构保留,值等于当前页 `rows.length`,不是权威 branch count;这两个约束避免 rows endpoint 为每个 branch/page 额外执行全量 COUNT。
+
+### 4.4 Cursor Design
+
+不继续扩展 offset pagination。Cursor 使用 base64url JSON envelope:
+
+```json
+{
+ "v": 1,
+ "query": "sha256:...",
+ "group_key": "status:todo",
+ "parent_id": null,
+ "sort_is_null": false,
+ "sort_value": "Example title",
+ "created_at": "2026-07-17T10:00:00Z",
+ "id": "uuid"
+}
+```
+
+- Cursor fields 全部经过类型验证并只作为 bind args,绝不拼接用户值到 SQL。
+- Cursor fingerprint 与当前 canonical Query Spec 不一致时返回 `409 cursor_query_mismatch`。
+- 默认 `position ASC, created_at DESC, id DESC` 保留精确的混合方向谓词,同时增加语义冗余的 `position >= cursor.position` index bound,使 PostgreSQL 可直接 seek 到深页位置;不能改成普通 row-value 比较,因为 position 不保证唯一且 tie-break 方向相反。
+- Cursor 不代表跨请求数据库 snapshot。每个响应是当次 transaction/read snapshot;实时写入通过 WS invalidation 触发 refetch。
+- Keyset 可避免普通 insert 下 offset shift 的重复/遗漏;如果某行的 sort/group 值在翻页期间变化,它可能跨过 cursor,WS invalidation 是最终一致性的修复机制。
+- Group header cursor 使用 group order rank/display sort key/stable group key,而不是 row sort cursor。
+
+### 4.5 Endpoint: Facets
+
+`POST /api/issues/table/facets`
+
+Request 复用 Query Spec,并声明需要的 facets:
+
+```json
+{
+ "query": { "...": "IssueTableQuerySpec" },
+ "facets": [{ "kind": "status" }],
+ "include_total": false
+}
+```
+
+Response 返回 query fingerprint、query total,以及每个 facet 的 kind、可选 property ID 和 `{key,count}` values。`include_total` 省略时默认为 `true`,保留原 endpoint contract;筛选选项不消费 query total,因此前端传 `false`,跳过额外 COUNT。
+
+Table 初始渲染不请求 facets。用户打开某个标准字段或 custom property 的筛选子菜单时,只请求该维度;关闭筛选菜单后停用查询。这样一次正常交互最多执行当前维度的聚合,不会在每次 Table mount / realtime invalidation 时依次扫描全部标准字段和工作区 properties。
+
+API 仍支持批量 `facets[]`。对于没有自身 active filter、因而与 base query 共享同一 membership 的 status / priority / assignee / creator / project 维度,server 使用一条 `GROUP BY GROUPING SETS` 查询,并可把 base total 作为空 grouping set 同批返回。存在自身 active filter 的维度必须使用“排除自身 filter”的独立 universe;label join 与 custom-property 展开也继续独立查询,避免改变 exact disjunctive facet 语义。
+
+前端不再用 `scopedIssues` 计算 Table facet counts;Board/List 在统一 Query API 前可保留现有行为。
+
+### 4.6 Endpoint: Export
+
+V1 不新增独立 export endpoint。显式导出在浏览器中使用与 Table 相同的 Query Spec,逐页调用 `POST /api/issues/table/rows`:
+
+- 导出固定使用 `group=none`、`hierarchy=false`,因此只输出 query membership 中的真实 issue 行,不受 viewport、collapsed state 或 loaded branches 影响。
+- 每一页必须保持相同的非空 `query_fingerprint`,cursor 必须前进,issue ID 不得重复;结束时唯一 issue 数必须等于首屏 `total`(续页 `total=0`)。
+- Response schema fallback、fingerprint 漂移、cursor loop、重复 issue 或最终数量不一致时 fail closed,不生成可能截断或混合 snapshot 的 CSV。
+- CSV formula injection protection沿用 `escapeCsvCell`。
+- Server-stream / async export job 是大规模导出的后续优化;迁移时仍须复用同一 Query Spec 和上述一致性语义。
+
+### 4.7 Error Contract
+
+```json
+{
+ "error": "unsupported_group",
+ "code": "property_type_unsupported",
+ "message": "This property type cannot be used for grouping."
+}
+```
+
+- `400`:shape、UUID、limit、date range、cursor envelope 等非法;body 使用现有 `{ "error": "..." }` contract。
+- `409`:cursor 与 query/group/parent 不匹配。
+- `422 unsupported_group`:unknown/archived/unsupported property 或 group kind;机器可读原因在顶层 `code`。
+- `500/504`:受控 query failure/timeout,body 沿用 handler 的顶层 error contract。
+
+前端对 branch 错误局部展示 Retry;group header 冷启动错误展示 Table-level Retry。
+
+---
+
+## 5. Backend Design
+
+### 5.1 Shared Filter Compiler
+
+新建 `server/internal/handler/issue_query_filter.go`,抽出 canonical filter representation 和 SQL builder:
+
+```go
+type issueQueryFilter struct {
+ Scope issueTableScope
+ Statuses []string
+ Priorities []string
+ Assignees []issueActorFilter
+ IncludeNoAssignee bool
+ Creators []issueActorFilter
+ ProjectIDs []pgtype.UUID
+ IncludeNoProject bool
+ LabelIDs []pgtype.UUID
+ Properties [][]json.RawMessage
+ Date *issueDateFilter
+ Search string
+ WorkingOnly bool
+ IncludeSubIssues bool
+}
+```
+
+Builder 返回:
+
+```go
+type issueQuerySQL struct {
+ Where string
+ Args []any
+}
+```
+
+要求:
+
+- 新 JSON decoder、legacy GET query decoder、现有 POST twin 都编译到同一 canonical struct。
+- `ListIssues` 的 ordinary paged path 和 `ListGroupedIssues` 逐步改用同一 builder,避免新旧 endpoint filter drift。
+- `open_only` 和 `scheduled` 的特殊路径不强行塞进 Table contract;保留现有分支。
+- `my relation=any` 在 SQL 中做 assigned OR created OR involved,不再前端三次全量请求合并。
+- `working_only` 使用 `EXISTS` 查询 running tasks;不得把 WS snapshot IDs 作为 canonical membership。
+- 所有动态 column/expression 只能来自枚举或后端解析过的 active property definition。
+
+### 5.2 Group Capability Resolver
+
+新建 `server/internal/handler/issue_table_group.go`:
+
+```go
+type resolvedIssueGroup struct {
+ Kind string
+ PropertyID *pgtype.UUID
+ PropertyType string
+ GroupExpr string
+ GroupPredicate func(value issueGroupValue, addArg func(any) string) string
+ OrderExpr string
+}
+```
+
+- Static kind 使用固定 SQL expression。
+- Property kind 先通过 workspace-scoped catalog 查询确认 active/type。
+- UUID 重新序列化后才允许嵌入 JSONB extraction expression;group value 始终 bind。
+- Group key 是后端编码的稳定 identity,不直接当 SQL fragment。
+- Stale select option 单独进入 stable stale/no-value bucket;不要丢行。
+
+### 5.3 Group Header Query
+
+逻辑 SQL:
+
+```sql
+WITH filtered AS (
+ SELECT i.*, <group_expr> AS group_value
+ FROM issue i
+ WHERE <canonical_where>
+), grouped AS (
+ SELECT group_value, COUNT(*) AS issue_count
+ FROM filtered
+ GROUP BY group_value
+)
+SELECT group_value, issue_count
+FROM grouped
+WHERE <group_cursor_predicate>
+ORDER BY <semantic_group_order>, <stable_group_key>
+LIMIT $limit_plus_one;
+```
+
+`total` 可由 `SUM(issue_count) OVER ()` 返回,避免第二次 count。若 group cursor 后的 page 会使 window sum 只覆盖剩余行,则在 cursor 前的 grouped CTE 上计算 total,再外层分页。
+
+Assignee display order 需要 workspace-scoped actor name projection。优先复用现有 member/agent/squad lookup;unassigned 明确排最后。
+
+### 5.4 Row/Hierarchy Query
+
+逻辑分两步:
+
+1. `filtered_group`:完整 Query membership + requested group predicate。
+2. `branch`:根据 hierarchy/parent 选择 roots 或 direct children。
+
+Root 判定:
+
+```sql
+NOT EXISTS (
+ SELECT 1
+ FROM filtered_group parent
+ WHERE parent.id = child.parent_issue_id
+)
+```
+
+因为 `filtered_group` 已经限定同 group,父项未命中或不同 group 时 child 自动成为 root。
+
+Direct child branch:
+
+```sql
+child.parent_issue_id = $parent_id
+AND EXISTS (
+ SELECT 1 FROM filtered_group parent
+ WHERE parent.id = $parent_id
+)
+```
+
+`direct_child_count` 在当前 Query/group 下批量计算,不能 N+1:
+
+```sql
+LEFT JOIN (
+ SELECT parent_issue_id, COUNT(*) AS child_count
+ FROM filtered_group
+ GROUP BY parent_issue_id
+) cc ON cc.parent_issue_id = row.id
+```
+
+Sort/keyset 在 branch 层执行。Hierarchy off 时直接对 `filtered_group` 做 keyset pagination。
+
+### 5.5 Index Plan
+
+先用 production-like 数据执行 EXPLAIN,再创建必要索引。预期至少需要:
+
+```sql
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_assignee
+ ON issue (workspace_id, assignee_type, assignee_id);
+```
+
+```sql
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_parent
+ ON issue (workspace_id, parent_issue_id);
+```
+
+如果 `working_only EXISTS` 计划不能稳定使用现有 issue-id index,再增加:
+
+```sql
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_running_issue
+ ON agent_task_queue (issue_id)
+ WHERE status = 'running' AND issue_id IS NOT NULL;
+```
+
+仓库规则:每个 concurrent index 单独一个、只含单 statement 的 migration;不添加 FK/cascade。
+
+Custom property Group 使用 `i.properties -> '<definition-id>'`。现有 `jsonb_path_ops` GIN 适合 containment Filter,但不能直接加速任意 key 的 GROUP BY。Rollout gate:
+
+- 先验证 100k issue / 20 active properties 上 select/checkbox group p95。
+- 若不能达到 SLO,不通过提高客户端上限解决;后续引入无 FK 的 normalized `issue_property_value` projection,并在 property mutation transaction 中双写。
+- normalized projection 是性能 contingency,不作为首发前置,除非 EXPLAIN 明确证明必须。
+
+### 5.6 Query Limits and Safety
+
+- Group header limit default/max 100。
+- Row/child limit default 50、max 100。
+- Search 长度、property filter definitions/values 复用现有 bounds。
+- Query context deadline 初始 5s;超时返回 structured `query_timeout`。
+- Cursor decode 后限制 envelope 大小和 field lengths。
+- 所有 scope 继续经过 `RequireWorkspaceMember`,并复用 `resolveWorkspaceID`。
+- Query logs 记录 kind、group kind、hierarchy、limit、duration、returned count、timeout;不记录 search text、issue title 或 raw property values。
+
+---
+
+## 6. Frontend Design
+
+### 6.1 Core Types and API
+
+修改:
+
+- `packages/core/types/api.ts`
+ - `IssueTableQuerySpec`
+ - groups/rows/facets request/response tagged unions
+- `packages/core/api/schemas.ts`
+ - 对所有新 response 使用 Zod schema;不要 raw cast。
+- `packages/core/api/client.ts`
+ - `listIssueTableGroups`
+ - `listIssueTableRows`
+ - `getIssueTableFacets`
+ - export 复用 `listIssueTableRows`
+- `packages/core/issues/queries.ts`
+ - 新 query key prefix:`issueKeys.tableQueryAll(wsId)`。
+ - group headers key 包含 canonical query + group。
+ - row branch key 包含 query + group + groupKey + hierarchy + parentId。
+
+Query key 中不得放 cursor;React Query infinite page param 单独管理 cursor。
+
+### 6.2 Surface Query Compilation
+
+在 `packages/core/issues/surface/` 新建 pure compiler:
+
+```ts
+buildIssueTableQuerySpec(
+ scope: IssueSurfaceScope,
+ viewState: IssueViewState,
+ search: string,
+): IssueTableQuerySpec
+```
+
+职责:
+
+- 将 `IssueSurfaceQueryPlan` 转为 typed scope,而不是散落到 flat/grouped params。
+- 将 date/property filters、showSubIssues、workingOnly 编译到同一 spec。
+- `my/all` 编译为 `{kind:"my", relation:"any"}`,不再调用 `fetchAllMyFlatIssues`。
+- Stale property filters 在 catalog settled 后移除,延续现有 cold-catalog guard。
+- Canonicalize arrays,以稳定 React Query key 和后端 fingerprint。
+
+### 6.3 Table Query Hooks
+
+建议新建 `packages/views/issues/surface/use-issue-table-data.ts`,避免继续扩大 `use-issue-surface-data.ts`。
+
+提供:
+
+- `useIssueTableGroups(spec, group)`:group headers infinite query。
+- `useIssueTableBranch(spec, group, groupKey, hierarchy, parentId)`:单 branch infinite query。
+- `useIssueTableFacets(spec)`:按打开的 filter submenu 懒加载。
+- export controller:使用 `group=none` / `hierarchy=false` 遍历 rows cursor,并执行完整性校验。
+
+加载规则:
+
+- Group=None:只加载 root/flat top branch。
+- Group!=None:先加载 group headers。
+- Collapsed group:不 mount branch query。
+- Expanded group:仅当 header/loading placeholder 接近 viewport 时 enable root branch。
+- Expanded parent:仅当 parent 可见且未 collapsed 时 enable child branch。
+- 不存在任何“为了 count/structure 自动 while(hasNextPage) fetch”的 effect。
+
+### 6.4 Render Model
+
+替换当前 `buildIssueTableRows(issues)` 的全数组模型,改为由 server branches 组装 display rows:
+
+```ts
+type IssueTableDisplayRow =
+ | { kind: "group"; descriptor: IssueTableGroupDescriptor }
+ | { kind: "issue"; issue: Issue; depth: number; childCount: number }
+ | { kind: "branch-loading"; key: string; depth: number }
+ | { kind: "branch-error"; key: string; depth: number };
+```
+
+- Frontend只做 flatten 已加载 branch tree,不重新计算 group key/membership/count。
+- Group count 始终取 descriptor.count。
+- `depth` 由 branch parent 链计算,不依赖后端返回全树。
+- DataTable 继续 virtualization;动态 branch 插入后由 virtualizer remeasure。
+- Shift range selection 只覆盖当前可见且已加载 issue rows,行为在 UI copy/测试中明确。
+- “Loaded X / Total” 改为 “Visible X · Total Y”;X 是当前已加载真实 issue 数,不暗示完整加载。
+
+### 6.5 View State
+
+保留前端:
+
+- `viewMode`
+- `tableColumns` / width / order
+- `tableCollapsedGroups`
+- `tableCollapsedParents`
+- selection
+- density(未来)
+
+进入 Query Spec:
+
+- filters
+- search
+- sort
+- `tableGrouping`
+- `tableHierarchy`
+- showSubIssues
+
+`tableCalculation` 当前没有生产消费者:本计划中从 persist state 和 dead helper 清理,或在 Aggregate 单独立项前保持 hidden 但不得展示不准确结果。
+
+Web 后续通过 app-level NavigationAdapter 把 query state 编码到 URL;`packages/views` 不引入 `next/*`。
+
+### 6.6 Cache and Realtime
+
+新 query prefix:
+
+```ts
+issueKeys.tableQueryAll(wsId)
+```
+
+第一版采用 correctness-first invalidation:
+
+- Issue create/delete:invalidate workspace table query prefix。
+- Issue update:先 patch 所有 loaded row branches 中的 issue snapshot。
+- 如果 changed dimensions 影响任何 query 的 filter/sort/group/hierarchy,invalidate 对应 table query keys。
+- Assignee/status/property/parent/project/label/title/date 改动均可能改变至少一个 Table query;利用 query key 中的 spec 做 predicate,无法证明安全时失效。
+- Group header counts 永远通过 refetch 修正,不在客户端猜 source/destination count delta。
+- Mutation optimistic update 失败时 rollback row snapshots;现有 `cache-coordinator` 模式继续复用。
+
+后续可优化为只 invalid source/destination group,但首发不以复杂 delta logic 换取少一次 refetch。
+
+### 6.7 Deployment Strategy
+
+本次不引入 frontend-public release flag,也不在同一客户端保留双 Table 数据路径:
+
+- 新 Table endpoints 是 additive API;老 Web/Desktop 客户端继续使用 legacy endpoints。
+- 新客户端的 Table membership/structure 始终使用新 API;API error 显示 Retry,不 fallback 到 loaded-row Group。
+- 回滚以回滚 Web/Desktop build 为单位,后端 additive endpoints 和 indexes 可保留,不涉及数据回迁。
+- Board/List 仍使用原有 API;它们不在本次 hard cutover 范围内。
+
+---
+
+## 7. Implementation Units
+
+### U1. Canonical Query Spec and Shared Filter Compiler
+
+- **Goal:** 所有 Table endpoint 和 legacy list path 可复用同一 membership compiler。
+- **Requirements:** R2、R5、R10。
+- **Dependencies:** none。
+- **Files:**
+ - `server/internal/handler/issue_query_filter.go`(new)
+ - `server/internal/handler/issue.go`
+ - `server/internal/handler/issue_table_filters_test.go`
+ - `server/internal/handler/issue_involves_test.go`
+- **Approach:** 定义 Go Query Spec、canonicalization、scope/filter validation、where/args builder;把 ordinary `ListIssues` 和 `ListGroupedIssues` 的重复 filter fragments 接到 builder。保留 `open_only/scheduled` 特殊路径。
+- **Critical test scenarios:** legacy GET 与新 canonical spec 在所有现有 Table filters 上返回相同 membership;my relation any 去重;workspace isolation;empty/no-value semantics;property/date/search parity。
+- **Verification:** 现有 handler issue tests 全绿;新增 compiler table tests 覆盖每个 dimension。
+
+### U2. Group Resolver and Group Headers API
+
+- **Goal:** 后端返回准确、可分页的 group headers/counts。
+- **Requirements:** R1、R3、R6、R7。
+- **Dependencies:** U1。
+- **Files:**
+ - `server/internal/handler/issue_table_group.go`(new)
+ - `server/internal/handler/issue_table_query.go`(new)
+ - `server/internal/handler/issue_table_query_test.go`(new)
+ - `server/cmd/server/router.go`
+ - `server/internal/featureflags/keys.go`
+- **Approach:** 实现 status/assignee/select/checkbox resolver;group semantic order;group header keyset cursor;structured errors;flag gate。
+- **Critical test scenarios:** 1,001 seeded issues;count sum=total;unassigned/no-value;select option order;checkbox false/true/null;archived/unknown/multi-select rejection;2-page group cursor 无重无漏。
+- **Verification:** Go integration tests;EXPLAIN standard groups on 100k fixture。
+
+### U3. Cursor-paged Rows and Lazy Hierarchy API
+
+- **Goal:** 支持 ungrouped/grouped flat rows、root rows 和 direct child branches。
+- **Requirements:** R1、R4、R5。
+- **Dependencies:** U1、U2。
+- **Files:**
+ - `server/internal/handler/issue_table_query.go`
+ - `server/internal/handler/issue_table_cursor.go`(new)
+ - `server/internal/handler/issue_table_query_test.go`
+- **Approach:** 实现 typed cursor、query fingerprint、stable keyset、same-query same-group hierarchy、page row counts/direct child counts。
+- **Critical test scenarios:** title/date/property/position asc+desc;NULLS LAST;created_at ties;cursor mismatch;same-group child;cross-group child;filtered-out parent;deep tree branch loading;parent moved between groups。
+- **Verification:** 反复分页结果与一次性 SQL baseline ID set 相同;race/update scenario 通过 invalidation contract 测试。
+
+### U4. Indexes and Performance Gate
+
+- **Goal:** 标准字段 group/rows/hierarchy 达到 rollout SLO。
+- **Requirements:** R4。
+- **Dependencies:** U2、U3 query shape settled。
+- **Files:**
+ - next available single-statement migrations for workspace-assignee/workspace-parent
+ - optional running-task partial index migration
+ - EXPLAIN notes appended to this plan or linked benchmark artifact
+- **Approach:** production-like 100k/1m fixtures EXPLAIN;只为证明确有收益的 indexes 建 migration;每个 index 单文件 `CREATE INDEX CONCURRENTLY`。
+- **Verification:** 无 sequential global scan;workspace predicate 生效;group header p95<500ms、rows p95<300ms 的 staging 指标目标。
+
+### U5. Core API, Schemas, Query Keys and Surface Compiler
+
+- **Goal:** 提供类型安全、可缓存的新 Table repository。
+- **Requirements:** R2、R10。
+- **Dependencies:** U2、U3 contract stable。
+- **Files:**
+ - `packages/core/types/api.ts`
+ - `packages/core/api/schemas.ts`
+ - `packages/core/api/client.ts`
+ - `packages/core/issues/queries.ts`
+ - `packages/core/issues/surface/query-plan.ts`
+ - `packages/core/issues/surface/repository.ts`
+ - new compiler/tests under `packages/core/issues/surface/`
+- **Approach:** typed union + Zod parse;canonical key builder;group/branch infinite query options;my any scope 不再走三次 full fetch。
+- **Critical test scenarios:** schema defaults不得把 malformed group value 伪装成 empty success;query keys 隔离 group/parent/hierarchy;canonical array order;POST body exactness;response enum 向前兼容。
+- **Verification:** core unit tests、API schema tests、typecheck。
+
+### U6. Table Data Hook and Server-backed Renderer
+
+- **Goal:** Table 不再物化完整 window,也不再前端求 Group/Hierarchy truth。
+- **Requirements:** R1–R5、R8。
+- **Dependencies:** U3、U5。
+- **Files:**
+ - `packages/views/issues/surface/use-issue-table-data.ts`(new)
+ - `packages/views/issues/surface/use-issue-surface-controller.ts`
+ - `packages/views/issues/surface/use-issue-surface-data.ts`
+ - `packages/views/issues/surface/issue-surface.tsx`
+ - `packages/views/issues/components/table-view.tsx`
+ - `packages/views/issues/components/table-view-model.ts`
+ - related tests
+- **Approach:** group headers + viewport-enabled branch hooks;display row flatten;per-branch error/loading;visible/total copy;保留 TanStack virtualization。
+- **Removal:** 新路径删除 `TABLE_STRUCTURE_MAX_WINDOW`、`shouldAutoLoadNextWindowPage`、structure suspension copy/effects;不再对 Group/Hierarchy 调 `fetchNextFlatPage`。
+- **Critical test scenarios:** total=1001 group 仍生效;collapsed group zero row requests;expand visible parent只发对应 branch;branch retry;selection忽略 placeholders;switch group保留 placeholder但不显示旧 group 为新 group。
+- **Verification:** views tests、typecheck、browser network trace 无 auto-materialization。
+
+### U7. Header Controls and Capability UX
+
+- **Goal:** Group、Sort、Columns 的产品入口与实际能力一致。
+- **Requirements:** R6 及 Toolbar contract。
+- **Dependencies:** U5、U6。
+- **Files:**
+ - `packages/views/issues/components/issues-header.tsx`
+ - `packages/core/issues/stores/view-store.ts`
+ - `packages/views/locales/{en,zh-Hans,ja,ko}/issues.json`
+ - header/surface tests
+- **Approach:** desktop 拆分 Sort/Group/Columns;移除 multi-select group option;active group持续可见;stale property清理提示;修复 Filter trigger 内嵌不可键盘操作的 clear control。
+- **Critical test scenarios:** group trigger label;keyboard navigation;mobile merged display;archived property fallback;all four locales;sort icon accessible label。
+- **Verification:** component tests + browser keyboard/accessibility smoke。
+
+### U8. Facets, Export, Realtime and Compatibility
+
+- **Goal:** 所有 Table 衍生能力复用相同 Query Spec,并安全发布。
+- **Requirements:** R2、R7–R10。
+- **Dependencies:** U5、U6。
+- **Files:**
+ - backend facets handler and tests
+ - `packages/core/issues/cache-coordinator.ts`
+ - `packages/core/issues/ws-updaters.ts`
+ - `packages/views/issues/surface/use-issue-table-data.ts`
+ - analytics/observability touchpoints
+- **Approach:** exact disjunctive facets;rows-based fail-closed export;table query prefix invalidation;row optimistic patch;additive endpoint compatibility。
+- **Critical test scenarios:** group/facet/export membership parity;export cursor/fingerprint/schema drift 与 final-total mismatch;create/delete/update invalidation;property edit regroup;offline/5xx retry;old desktop client继续使用旧 endpoints。
+- **Verification:** core WS/cache tests、integration tests、staging rollout dashboards。
+
+### Sequencing
+
+```text
+U1
+ └─ U2
+ ├─ U3
+ │ └─ U4
+ └─ U5
+ └─ U6
+ ├─ U7
+ └─ U8
+```
+
+U2/U3/U4 可由 backend owner 连续完成;U5 可在 API schema freeze 后与 U3 并行;U6 只有在 hierarchy contract 和 cursor tests 稳定后切换。
+
+---
+
+## 8. Rollout and Compatibility
+
+### 8.1 Compatibility
+
+- 保留 `GET /api/issues`、`POST /api/issues/query`、`GET /api/issues/grouped`。
+- 老 Web/Desktop 客户端继续使用旧 API,不受新 response 影响。
+- 新前端的 Table 直接使用新 endpoints;Board/List 以及老客户端保持原有 API。
+- 新 endpoint 不改变数据库 schema,除性能 indexes 外无数据 migration。
+
+### 8.2 Validation Cohorts
+
+1. Local/dev:功能与测试完成。
+2. Internal workspace:收集 group/rows query duration、error、timeout、branch request fan-out。
+3. 10% cloud workspaces:重点观察大 workspace、自定义 property group。
+4. 100% cloud:发布新 Web/Desktop build。
+5. 至少一个 desktop release 周期后,再评估 legacy endpoint 和旧 client grouping 的退休窗口。
+
+### 8.3 Rollback
+
+- 回滚 Web/Desktop build 即回到旧 Table 数据路径;旧 endpoints 全程保留。
+- Rollback 不删除 index;concurrent indexes 可在后续独立 migration 决定是否移除。
+- 新 Table API 的单次请求失败只显示 Retry,不按请求级别自动 fallback,避免同一 session 同时存在两套 Group truth。
+
+### 8.4 Observability
+
+Backend structured fields:
+
+- endpoint: groups/rows/facets
+- group_kind
+- hierarchy
+- scope_kind
+- duration_ms
+- db_rows_returned
+- group_count/branch_count
+- timeout/error_code
+- cursor_present
+
+Frontend events:
+
+- table_group_changed
+- table_group_headers_loaded/failed
+- table_branch_loaded/failed
+- table_export_started/completed/failed
+
+不得记录 search text、issue title、raw property values、assignee display name。
+
+---
+
+## 9. Test and Verification Matrix
+
+### Backend Integration
+
+- 每种 filter dimension 与 group 组合。
+- `my relation=any` 的 assigned/created/involved OR + dedupe。
+- status/assignee/select/checkbox group identity/order/count。
+- 1001、10k、100k fixture 的 counts 和 pages。
+- group header cursor、row cursor、child cursor。
+- asc/desc/null/tie cases。
+- hierarchy same-group/cross-group/missing-parent/deep tree。
+- workspace isolation 与 actor/property stale input。
+- malformed cursor、query mismatch、limit clamp、timeout。
+- running_only membership。
+
+### Core Unit
+
+- Query Spec canonicalization。
+- Scope compiler。
+- Query key separation。
+- Zod parse/fallback failure behavior。
+- API request serialization。
+- Cache invalidation predicate。
+- WS create/update/delete handling。
+
+### Views Unit
+
+- Group header exact count display。
+- No auto-fetch of all groups/pages。
+- Collapse/expand query enablement。
+- Branch flatten depth。
+- Loading/error placeholders。
+- Selection range over visible issue rows only。
+- Group/Sort/Columns controls and keyboard semantics。
+- Stale property fallback。
+- Four locales。
+
+### Browser Smoke
+
+1. Seed/prepare a workspace with >1000 issues。
+2. 打开 Network panel,进入 Table。
+3. 切换 Group=Status、Assignee、Select、Checkbox。
+4. 验证首屏只请求 headers 与可见 branches,不出现连续 offset page loop。
+5. 折叠/展开 group 与 parent,验证 branch requests。
+6. 修改 status/assignee/property,验证 row optimistic update 后 counts/refetch 正确。
+7. Filter/Search/Sort 后验证 group totals 与 Export parity。
+8. Keyboard 操作 Filter/Sort/Group/Columns/Table controls。
+
+### Performance SLO
+
+在 staging production-like Postgres 数据上:
+
+- Standard group headers p95 < 500ms,p99 < 1s。
+- Row/child page p95 < 300ms,p99 < 800ms。
+- Table first interactive 不随 total 线性增长。
+- 浏览器自动加载 issue rows 上限为当前可见 branch pages,不超过 2 pages/branch prefetch。
+- Group header request memory 不随 issue count在应用层线性增长;聚合发生在数据库。
+- Custom property group 若不达标,flag cohort 不扩大,触发 normalized projection contingency。
+
+不要在 CI 以 wall-clock assertion 执行 SLO;CI 验证逻辑正确性,SLO 由可重复 benchmark/staging telemetry 验证。
+
+---
+
+## 10. Risks and Mitigations
+
+### Risk A — Shared filter compiler refactor causes legacy drift
+
+- **Mitigation:** 先建立 legacy GET 与 canonical spec 的 golden parity tests,再逐段替换;保留特殊 open/scheduled 分支。
+
+### Risk B — Dynamic property group scans large JSONB windows
+
+- **Mitigation:** flag cohort、query deadline、EXPLAIN gate;必要时 normalized property-value projection,不回退客户端 materialization。
+
+### Risk C — Hierarchy branch queries重复评估完整 filtered set
+
+- **Mitigation:** workspace-leading parent index;用 CTE/derived query 让 planner复用;对可见 parent 才请求;观察 branch fan-out;必要时批量 children endpoint。
+
+### Risk D — Realtime updates cause count flicker或跨 cursor遗漏
+
+- **Mitigation:** optimistic patch只改善单元格即时性;任何 shape-changing field 都 invalidate server queries;不猜 count delta。
+
+### Risk E — 高基数 Assignee groups 产生过多 HTTP requests
+
+- **Mitigation:** headers cursor;collapsed/viewport enablement;首发监测 fan-out。若 p95 session fan-out过高,增加 batched branch request,而不改变 Query Spec。
+
+### Risk F — Old persisted multi-select grouping
+
+- **Mitigation:** catalog settled 后 capability validation;一次性降级为 none + toast;不要把 multi-select组合值继续发送到 API。
+
+### Risk G — Feature flag造成双路径维护时间过长
+
+- **Mitigation:** 在 rollout 中写明 retirement milestone;100% 后一个 desktop release 周期内删除旧 client structure path。
+
+---
+
+## 11. Definition of Done
+
+- [x] Result >1000 时 Group/Hierarchy 不暂停、不消失。
+- [x] Group counts 来自后端完整 Query membership。
+- [x] Group/row/child headers 和 rows 均使用 cursor pagination。
+- [x] Table 不存在自动 materialize entire window 的 effect。
+- [x] Multi-select property 不在 Group capability 中出现。
+- [x] Filter、Search、Sort、Group、Hierarchy、Facet、Export 使用同一 Query Spec。
+- [x] `my/all` 不再前端三次全量获取合并。
+- [x] Working-only 不再通过浏览器发送全部 running IDs。
+- [x] Cross-group hierarchy semantics 与本文一致并有 integration tests。
+- [x] Realtime shape changes invalidate server group truth。
+- [x] Toolbar 独立显示 Sort/Group/Columns/View,active Group 可见。
+- [x] 新 API 有 structured errors、query deadlines 和 safe cursors。
+- [x] 必要 indexes 以单 statement concurrent migrations 落地。
+- [ ] Go、core、views tests 与 typecheck 通过。
+- [ ] 1001+ issue browser smoke 和 network trace 通过。
+- [ ] Staging SLO 和 custom-property EXPLAIN gate 通过。
+- [ ] Rollout/rollback/flag retirement owner 明确。
+
+---
+
+## 12. Primary Source Map
+
+- Frontend view state: `packages/core/issues/stores/view-store.ts`
+- Per-surface persistence: `packages/core/issues/stores/surface-view-store.ts`
+- Query keys and flat pagination: `packages/core/issues/queries.ts`
+- Surface repository: `packages/core/issues/surface/repository.ts`
+- Surface query compilation: `packages/views/issues/surface/use-issue-surface-controller.ts`
+- Surface data selection: `packages/views/issues/surface/use-issue-surface-data.ts`
+- Table structure/render: `packages/views/issues/components/table-view-model.ts`, `table-view.tsx`
+- Header controls/facet counts: `packages/views/issues/components/issues-header.tsx`
+- API types/schemas/client: `packages/core/types/api.ts`, `packages/core/api/schemas.ts`, `packages/core/api/client.ts`
+- Backend flat/grouped handlers: `server/internal/handler/issue.go`
+- Property filter/sort compiler: `server/internal/handler/property.go`
+- Routes: `server/cmd/server/router.go`
+- Cache/realtime: `packages/core/issues/cache-coordinator.ts`, `packages/core/issues/ws-updaters.ts`
+- Backend tests: `server/internal/handler/issue_table_filters_test.go`, `issue_grouped_test.go`, `issue_sort_test.go`, `issue_involves_test.go`
+- Frontend tests: `packages/views/issues/components/table-view-model.test.ts`, `table-group-row.test.tsx`, `packages/views/issues/surface/use-issue-surface-controller.test.tsx`, `issue-surface.test.tsx`
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index 09b8a2f690..6b000a1fa4 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -19,12 +19,39 @@ interface TestWorkspace {
slug: string;
}
+export type TestIssueStatus =
+ | "backlog"
+ | "todo"
+ | "in_progress"
+ | "in_review"
+ | "done"
+ | "blocked"
+ | "cancelled";
+
+export type TestIssuePriority = "urgent" | "high" | "medium" | "low" | "none";
+
+export interface TestTableIssueSeed {
+ title: string;
+ status?: TestIssueStatus;
+ priority?: TestIssuePriority;
+ parentIssueId?: string | null;
+ position?: number;
+}
+
+export interface TestTableIssue {
+ id: string;
+ title: string;
+ status: TestIssueStatus;
+ number: number;
+}
+
export class TestApiClient {
private token: string | null = null;
private workspaceSlug: string | null = null;
private workspaceId: string | null = null;
private email: string | null = null;
private createdIssueIds: string[] = [];
+ private seededIssueIds: string[] = [];
async login(email: string, name: string) {
const client = new pg.Client(DATABASE_URL);
@@ -167,12 +194,143 @@ export class TestApiClient {
return issue;
}
+ /**
+ * Insert a large, deterministic issue fixture in one transaction.
+ *
+ * Browser E2E coverage for cursor-backed Table views needs 1,000+ rows,
+ * which would make setup itself dominate the test if every row went through
+ * the HTTP create endpoint. These rows intentionally contain no dependent
+ * records; cleanup deletes exactly the returned IDs from the isolated E2E
+ * workspace.
+ */
+ async seedTableIssues(rows: TestTableIssueSeed[]): Promise<TestTableIssue[]> {
+ if (rows.length === 0) return [];
+ if (!this.workspaceId || !this.email) {
+ throw new Error("Cannot seed table issues before login and workspace setup");
+ }
+
+ const client = new pg.Client(DATABASE_URL);
+ await client.connect();
+ try {
+ await client.query("BEGIN");
+ const userResult = await client.query<{ id: string }>(
+ `SELECT id FROM "user" WHERE email = $1`,
+ [this.email],
+ );
+ const creatorId = userResult.rows[0]?.id;
+ if (!creatorId) {
+ throw new Error(`Cannot resolve E2E creator for ${this.email}`);
+ }
+
+ const counterResult = await client.query<{ issue_counter: number }>(
+ `
+ UPDATE workspace
+ SET issue_counter = issue_counter + $2
+ WHERE id = $1
+ RETURNING issue_counter
+ `,
+ [this.workspaceId, rows.length],
+ );
+ const finalCounter = Number(counterResult.rows[0]?.issue_counter);
+ if (!Number.isFinite(finalCounter)) {
+ throw new Error(`Cannot reserve issue numbers for workspace ${this.workspaceId}`);
+ }
+ const firstNumber = finalCounter - rows.length + 1;
+
+ const inserted = await client.query<TestTableIssue>(
+ `
+ INSERT INTO issue (
+ workspace_id,
+ title,
+ status,
+ priority,
+ creator_type,
+ creator_id,
+ parent_issue_id,
+ position,
+ number
+ )
+ SELECT
+ $1::uuid,
+ fixture.title,
+ fixture.status,
+ fixture.priority,
+ 'member',
+ $2::uuid,
+ fixture.parent_issue_id,
+ fixture.position,
+ fixture.number
+ FROM unnest(
+ $3::text[],
+ $4::text[],
+ $5::text[],
+ $6::uuid[],
+ $7::double precision[],
+ $8::integer[]
+ ) WITH ORDINALITY AS fixture(
+ title,
+ status,
+ priority,
+ parent_issue_id,
+ position,
+ number,
+ ordinal
+ )
+ ORDER BY fixture.ordinal
+ RETURNING id, title, status, number
+ `,
+ [
+ this.workspaceId,
+ creatorId,
+ rows.map((row) => row.title),
+ rows.map((row) => row.status ?? "backlog"),
+ rows.map((row) => row.priority ?? "none"),
+ rows.map((row) => row.parentIssueId ?? null),
+ rows.map((row, index) => row.position ?? index + 1),
+ rows.map((_row, index) => firstNumber + index),
+ ],
+ );
+ await client.query("COMMIT");
+ this.seededIssueIds.push(...inserted.rows.map((row) => row.id));
+ return inserted.rows;
+ } catch (error) {
+ await client.query("ROLLBACK");
+ throw error;
+ } finally {
+ await client.end();
+ }
+ }
+
async deleteIssue(id: string) {
await this.authedFetch(`/api/issues/${id}`, { method: "DELETE" });
}
+ async updateIssue(id: string, updates: Record<string, unknown>) {
+ const res = await this.authedFetch(`/api/issues/${id}`, {
+ method: "PUT",
+ body: JSON.stringify(updates),
+ });
+ if (!res.ok) {
+ throw new Error(`update issue failed: ${res.status} ${await res.text()}`);
+ }
+ return res.json();
+ }
+
/** Clean up all issues created during this test. */
async cleanup() {
+ if (this.seededIssueIds.length > 0 && this.workspaceId) {
+ const client = new pg.Client(DATABASE_URL);
+ await client.connect();
+ try {
+ await client.query(
+ `DELETE FROM issue WHERE workspace_id = $1 AND id = ANY($2::uuid[])`,
+ [this.workspaceId, this.seededIssueIds],
+ );
+ } finally {
+ await client.end();
+ }
+ this.seededIssueIds = [];
+ }
for (const id of this.createdIssueIds) {
try {
await this.deleteIssue(id);
diff --git a/e2e/issue-table.spec.ts b/e2e/issue-table.spec.ts
new file mode 100644
index 0000000000..cb80bbeb42
--- /dev/null
+++ b/e2e/issue-table.spec.ts
@@ -0,0 +1,417 @@
+import {
+ expect,
+ test,
+ type Page,
+ type Request,
+ type Response,
+} from "@playwright/test";
+import { createTestApi, loginAsDefault, reloadAppPage } from "./helpers";
+import type { TestApiClient, TestTableIssueSeed } from "./fixtures";
+
+type TableRequestBody = {
+ group?: { kind?: string };
+ group_key?: string | null;
+ parent_id?: string | null;
+ page?: { limit?: number; cursor?: string | null };
+};
+
+type TableGroupsResponse = {
+ total: number;
+ groups: Array<{
+ key: string;
+ count: number;
+ value: { kind: string; status?: string };
+ }>;
+};
+
+type TableRowsResponse = {
+ total: number;
+ next_cursor: string | null;
+ rows: Array<{
+ issue: { id: string; title: string; status: string };
+ direct_child_count: number;
+ }>;
+};
+
+function apiPath(request: Request) {
+ return new URL(request.url()).pathname;
+}
+
+function tableBody(request: Request): TableRequestBody {
+ return (request.postDataJSON() ?? {}) as TableRequestBody;
+}
+
+async function switchToTable(page: Page) {
+ const currentView = page.getByRole("button", { name: "Board", exact: true });
+ await expect(currentView).toBeVisible();
+ await currentView.click();
+ const tableOption = page.getByRole("menuitemradio", {
+ name: "Table",
+ exact: true,
+ });
+ await tableOption.click();
+ await expect(
+ page.getByRole("button", { name: "Table", exact: true }),
+ ).toBeVisible();
+ await expect(tableOption).toBeHidden();
+}
+
+async function groupByStatus(page: Page) {
+ await page.getByRole("button", { name: "Group", exact: true }).click();
+ const statusOption = page.getByRole("menuitemradio", {
+ name: "Status",
+ exact: true,
+ });
+ await statusOption.click();
+ await expect(
+ page.getByRole("button", { name: "Group: Status", exact: true }),
+ ).toBeVisible();
+ await expect(statusOption).toBeHidden();
+}
+
+test.describe("Issue Table server grouping", () => {
+ test.describe.configure({ timeout: 120000 });
+
+ let api: TestApiClient;
+
+ test.beforeEach(async ({ page }) => {
+ api = await createTestApi();
+ await loginAsDefault(page);
+ });
+
+ test.afterEach(async () => {
+ await api?.cleanup();
+ });
+
+ test("groups 1,001 issues exactly without materializing the full result", async ({
+ page,
+ }) => {
+ const run = Date.now();
+ const seeds: TestTableIssueSeed[] = Array.from({ length: 1001 }, (_, index) => ({
+ title: `E2E Table Large ${run} ${index.toString().padStart(4, "0")}`,
+ status: index < 501 ? "backlog" : index < 801 ? "todo" : "done",
+ position: index + 1,
+ }));
+ await api.seedTableIssues(seeds);
+ await reloadAppPage(page);
+
+ const tableRowRequests: TableRequestBody[] = [];
+ const legacyMembershipRequests: string[] = [];
+ let lastObservedRequestAt = Date.now();
+ const collectRequest = (request: Request) => {
+ const path = apiPath(request);
+ if (path === "/api/issues/table/rows") {
+ lastObservedRequestAt = Date.now();
+ tableRowRequests.push(tableBody(request));
+ }
+ if (path === "/api/issues" || path === "/api/issues/query") {
+ lastObservedRequestAt = Date.now();
+ legacyMembershipRequests.push(request.url());
+ }
+ };
+
+ page.on("request", collectRequest);
+ // The page initially mounts Board, whose seven status buckets may still
+ // be finishing when the header becomes interactive. Observe that startup
+ // traffic, wait for it to settle, then clear it while keeping the listener
+ // installed so any request caused by the Table switch is captured.
+ await expect
+ .poll(() => Date.now() - lastObservedRequestAt, {
+ timeout: 5000,
+ intervals: [100, 200, 300],
+ })
+ .toBeGreaterThan(750);
+ tableRowRequests.length = 0;
+ legacyMembershipRequests.length = 0;
+ lastObservedRequestAt = Date.now();
+ await switchToTable(page);
+ const groupsResponsePromise = page.waitForResponse(
+ (response) =>
+ apiPath(response.request()) === "/api/issues/table/groups" &&
+ response.status() === 200,
+ );
+ await groupByStatus(page);
+
+ const groupsResponse = await groupsResponsePromise;
+ const groups = (await groupsResponse.json()) as TableGroupsResponse;
+ expect(groups.total).toBe(1001);
+ expect(
+ Object.fromEntries(groups.groups.map((group) => [group.key, group.count])),
+ ).toEqual({
+ "status:backlog": 501,
+ "status:todo": 300,
+ "status:done": 200,
+ });
+
+ const backlogGroup = page
+ .getByRole("row")
+ .filter({ hasText: "Backlog" })
+ .first();
+ await expect(backlogGroup).toContainText("501");
+ await expect(page.getByText(/Loaded \d+ of 1001/)).toBeVisible();
+ await expect(
+ page.getByText(/Grouping and hierarchy are paused/),
+ ).toHaveCount(0);
+
+ await expect
+ .poll(() => Date.now() - lastObservedRequestAt, {
+ timeout: 5000,
+ intervals: [100, 200, 300],
+ })
+ .toBeGreaterThan(750);
+ page.off("request", collectRequest);
+ expect(legacyMembershipRequests).toEqual([]);
+ expect(tableRowRequests.length).toBeGreaterThan(0);
+ expect(tableRowRequests.length).toBeLessThan(8);
+ expect(
+ tableRowRequests.every(
+ (body) =>
+ (body.page?.limit ?? 0) <= 50 &&
+ (body.page?.cursor === null || body.page?.cursor === undefined),
+ ),
+ ).toBe(true);
+ });
+
+ test("keeps same-group children nested and cross-group children at the group root", async ({
+ page,
+ }) => {
+ const run = Date.now();
+ const parentTitle = `E2E Hierarchy Parent ${run}`;
+ const sameGroupTitle = `E2E Hierarchy Same Group ${run}`;
+ const crossGroupTitle = `E2E Hierarchy Cross Group ${run}`;
+ const [parent] = await api.seedTableIssues([
+ { title: parentTitle, status: "todo", position: 1 },
+ ]);
+ if (!parent) throw new Error("Hierarchy parent fixture was not created");
+ await api.seedTableIssues([
+ {
+ title: sameGroupTitle,
+ status: "todo",
+ parentIssueId: parent.id,
+ position: 1,
+ },
+ {
+ title: crossGroupTitle,
+ status: "done",
+ parentIssueId: parent.id,
+ position: 2,
+ },
+ ]);
+ await reloadAppPage(page);
+ await switchToTable(page);
+
+ const todoRootPromise = page.waitForResponse((response) => {
+ if (apiPath(response.request()) !== "/api/issues/table/rows") return false;
+ const body = tableBody(response.request());
+ return (
+ body.group_key === "status:todo" &&
+ body.parent_id === null &&
+ response.status() === 200
+ );
+ });
+ const todoChildrenPromise = page.waitForResponse((response) => {
+ if (apiPath(response.request()) !== "/api/issues/table/rows") return false;
+ const body = tableBody(response.request());
+ return body.parent_id === parent.id && response.status() === 200;
+ });
+ const doneRootPromise = page.waitForResponse((response) => {
+ if (apiPath(response.request()) !== "/api/issues/table/rows") return false;
+ const body = tableBody(response.request());
+ return (
+ body.group_key === "status:done" &&
+ body.parent_id === null &&
+ response.status() === 200
+ );
+ });
+
+ await groupByStatus(page);
+ const [todoRootResponse, todoChildrenResponse, doneRootResponse] =
+ await Promise.all([
+ todoRootPromise,
+ todoChildrenPromise,
+ doneRootPromise,
+ ]);
+ const todoRoot = (await todoRootResponse.json()) as TableRowsResponse;
+ const todoChildren =
+ (await todoChildrenResponse.json()) as TableRowsResponse;
+ const doneRoot = (await doneRootResponse.json()) as TableRowsResponse;
+
+ expect(todoRoot.total).toBe(3);
+ expect(todoRoot.rows).toEqual([
+ expect.objectContaining({
+ issue: expect.objectContaining({ id: parent.id, title: parentTitle }),
+ direct_child_count: 1,
+ }),
+ ]);
+ expect(todoChildren.rows.map((row) => row.issue.title)).toEqual([
+ sameGroupTitle,
+ ]);
+ expect(doneRoot.rows.map((row) => row.issue.title)).toEqual([
+ crossGroupTitle,
+ ]);
+
+ const sameGroupRow = page
+ .getByRole("row")
+ .filter({ hasText: sameGroupTitle });
+ const crossGroupRow = page
+ .getByRole("row")
+ .filter({ hasText: crossGroupTitle });
+ await expect(sameGroupRow).toBeVisible();
+ await expect(crossGroupRow).toBeVisible();
+ await expect(
+ sameGroupRow.getByRole("button", { name: sameGroupTitle }).locator(".."),
+ ).toHaveCSS("padding-left", "18px");
+ await expect(
+ crossGroupRow.getByRole("button", { name: crossGroupTitle }).locator(".."),
+ ).toHaveCSS("padding-left", "0px");
+ });
+
+ test("drops stale branch cursors after a realtime sort-boundary update", async ({
+ page,
+ }) => {
+ const run = Date.now();
+ const seeds = await api.seedTableIssues(
+ Array.from({ length: 60 }, (_, index) => ({
+ title: `E2E Table Cursor ${run} ${index.toString().padStart(2, "0")}`,
+ status: "todo" as const,
+ position: index + 1,
+ })),
+ );
+ const moved = seeds.at(-1);
+ if (!moved) throw new Error("Cursor fixture was not created");
+ await reloadAppPage(page);
+
+ const firstHeadPromise = page.waitForResponse((response) => {
+ if (apiPath(response.request()) !== "/api/issues/table/rows") return false;
+ const body = tableBody(response.request());
+ return (
+ body.group?.kind === "none" &&
+ (body.page?.cursor === null || body.page?.cursor === undefined) &&
+ response.status() === 200
+ );
+ });
+ await switchToTable(page);
+ const firstHead = (await (await firstHeadPromise).json()) as TableRowsResponse;
+ const staleCursor = firstHead.next_cursor;
+ expect(staleCursor).toBeTruthy();
+
+ const firstTailPromise = page.waitForResponse((response) => {
+ if (apiPath(response.request()) !== "/api/issues/table/rows") return false;
+ const body = tableBody(response.request());
+ return body.page?.cursor === staleCursor && response.status() === 200;
+ });
+ const tableScroller = page.locator("table").locator("..");
+ await tableScroller.evaluate((element) => {
+ element.scrollTop = element.scrollHeight;
+ });
+ await firstTailPromise;
+ await expect(page.getByText("Loaded 60 of 60", { exact: true })).toBeVisible();
+
+ const postUpdateResponses: Array<{
+ body: TableRequestBody;
+ payload: TableRowsResponse;
+ }> = [];
+ const collectResponse = async (response: Response) => {
+ if (
+ apiPath(response.request()) !== "/api/issues/table/rows" ||
+ response.status() !== 200
+ ) {
+ return;
+ }
+ postUpdateResponses.push({
+ body: tableBody(response.request()),
+ payload: (await response.json()) as TableRowsResponse,
+ });
+ };
+ page.on("response", collectResponse);
+ await api.updateIssue(moved.id, { position: 0 });
+
+ await expect
+ .poll(
+ () =>
+ postUpdateResponses.find(
+ ({ body }) =>
+ body.page?.cursor === null || body.page?.cursor === undefined,
+ )?.payload.next_cursor,
+ { timeout: 10000 },
+ )
+ .not.toBeUndefined();
+ const freshHead = postUpdateResponses.find(
+ ({ body }) =>
+ body.page?.cursor === null || body.page?.cursor === undefined,
+ )?.payload;
+ const freshCursor = freshHead?.next_cursor;
+ expect(freshCursor).toBeTruthy();
+ expect(freshCursor).not.toBe(staleCursor);
+
+ await tableScroller.evaluate((element) => {
+ element.scrollTop = element.scrollHeight;
+ });
+ await expect
+ .poll(
+ () =>
+ postUpdateResponses.find(
+ ({ body }) => body.page?.cursor === freshCursor,
+ )?.payload,
+ { timeout: 10000 },
+ )
+ .not.toBeUndefined();
+ const freshTail = postUpdateResponses.find(
+ ({ body }) => body.page?.cursor === freshCursor,
+ )?.payload;
+ const refreshedIds = [
+ ...(freshHead?.rows ?? []),
+ ...(freshTail?.rows ?? []),
+ ].map((row) => row.issue.id);
+ expect(new Set(refreshedIds).size).toBe(60);
+ expect(refreshedIds).toContain(moved.id);
+ await expect(page.getByText("Loaded 60 of 60", { exact: true })).toBeVisible();
+ page.off("response", collectResponse);
+ });
+
+ test("shows a branch-level retry and never falls back to client grouping", async ({
+ page,
+ }) => {
+ const title = `E2E Table Branch Retry ${Date.now()}`;
+ await api.seedTableIssues([{ title, status: "todo", position: 1 }]);
+ await reloadAppPage(page);
+
+ let allowRows = false;
+ let forcedFailures = 0;
+ await page.route("**/api/issues/table/rows", async (route) => {
+ const body = tableBody(route.request());
+ if (
+ body.group?.kind === "status" &&
+ body.group_key === "status:todo" &&
+ !allowRows
+ ) {
+ forcedFailures += 1;
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: "forced_e2e_failure",
+ message: "Forced Table branch failure",
+ }),
+ });
+ return;
+ }
+ await route.continue();
+ });
+
+ await switchToTable(page);
+ await groupByStatus(page);
+ const retry = page.getByRole("button", {
+ name: "Loading more failed — Retry",
+ exact: true,
+ });
+ await expect(retry).toBeVisible({ timeout: 20000 });
+ await expect(page.getByText(title)).toHaveCount(0);
+ expect(forcedFailures).toBeGreaterThan(0);
+
+ allowRows = true;
+ await retry.click();
+ await expect(page.getByText(title)).toBeVisible({ timeout: 10000 });
+ await expect(retry).toHaveCount(0);
+ });
+});
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index cef0974e5c..522d6f7319 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -5,6 +5,230 @@ afterEach(() => {
vi.unstubAllGlobals();
});
+describe("ApiClient server Table query", () => {
+ it("posts the canonical query to the group and branch endpoints", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ query_fingerprint: "sha256:query",
+ total: 1001,
+ groups: [
+ {
+ key: "status:todo",
+ value: { kind: "status", status: "todo" },
+ count: 1001,
+ },
+ ],
+ next_cursor: null,
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ query_fingerprint: "sha256:query",
+ group_key: "status:todo",
+ parent_id: null,
+ total: 0,
+ rows: [],
+ branch_total: 0,
+ next_cursor: "next-page",
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ query_fingerprint: "sha256:query",
+ total: 1001,
+ facets: [
+ {
+ kind: "status",
+ values: [
+ { key: "todo", count: 501 },
+ { key: "done", count: 500 },
+ ],
+ },
+ ],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ const query = {
+ scope: { kind: "workspace" as const },
+ filters: { priorities: ["high" as const] },
+ sort: { field: "title" as const, direction: "asc" as const },
+ };
+
+ await expect(
+ client.listIssueTableGroups({
+ query,
+ group: { kind: "status" },
+ page: { limit: 100, cursor: null },
+ }),
+ ).resolves.toMatchObject({ total: 1001, groups: [{ count: 1001 }] });
+ await expect(
+ client.listIssueTableRows({
+ query,
+ group: { kind: "status" },
+ group_key: "status:todo",
+ hierarchy: { enabled: true },
+ parent_id: null,
+ page: { limit: 50, cursor: null },
+ }),
+ ).resolves.toMatchObject({ branch_total: 0, next_cursor: "next-page" });
+ await expect(
+ client.listIssueTableFacets({
+ query,
+ facets: [{ kind: "status" }],
+ }),
+ ).resolves.toMatchObject({
+ total: 1001,
+ facets: [{ values: [{ key: "todo", count: 501 }, { key: "done", count: 500 }] }],
+ });
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ "https://api.example.test/api/issues/table/groups",
+ "https://api.example.test/api/issues/table/rows",
+ "https://api.example.test/api/issues/table/facets",
+ ]);
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ method: "POST",
+ body: expect.stringContaining('"kind":"status"'),
+ });
+ });
+
+ it("falls back safely when Table responses are malformed", async () => {
+ const fetchMock = vi.fn().mockImplementation(() =>
+ Promise.resolve(
+ new Response(JSON.stringify({ total: "not-a-number" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ const query = {
+ scope: { kind: "workspace" as const },
+ filters: {},
+ sort: { field: "position" as const, direction: "asc" as const },
+ };
+
+ await expect(
+ client.listIssueTableGroups({
+ query,
+ group: { kind: "status" },
+ page: { limit: 100, cursor: null },
+ }),
+ ).resolves.toEqual({
+ query_fingerprint: "",
+ total: 0,
+ groups: [],
+ next_cursor: null,
+ });
+ await expect(
+ client.listIssueTableRows({
+ query,
+ group: { kind: "none" },
+ group_key: null,
+ hierarchy: { enabled: true },
+ parent_id: null,
+ page: { limit: 50, cursor: null },
+ }),
+ ).resolves.toEqual({
+ query_fingerprint: "",
+ group_key: null,
+ parent_id: null,
+ total: 0,
+ rows: [],
+ branch_total: 0,
+ next_cursor: null,
+ });
+ await expect(
+ client.listIssueTableFacets({
+ query,
+ facets: [{ kind: "status" }],
+ }),
+ ).resolves.toEqual({
+ query_fingerprint: "",
+ total: 0,
+ facets: [],
+ });
+ });
+
+ it("preserves future Table status and actor enum values", async () => {
+ const responses = [
+ {
+ query_fingerprint: "sha256:future-status",
+ total: 1,
+ groups: [
+ {
+ key: "status:paused",
+ value: { kind: "status", status: "paused" },
+ count: 1,
+ },
+ ],
+ next_cursor: null,
+ },
+ {
+ query_fingerprint: "sha256:future-actor",
+ total: 1,
+ groups: [
+ {
+ key: "service:bot-1",
+ value: {
+ kind: "assignee",
+ actor: { type: "service", id: "bot-1" },
+ },
+ count: 1,
+ },
+ ],
+ next_cursor: null,
+ },
+ ];
+ const fetchMock = vi.fn().mockImplementation(() =>
+ Promise.resolve(
+ new Response(JSON.stringify(responses.shift()), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ const query = {
+ scope: { kind: "workspace" as const },
+ filters: {},
+ sort: { field: "position" as const, direction: "asc" as const },
+ };
+
+ await expect(
+ client.listIssueTableGroups({ query, group: { kind: "status" } }),
+ ).resolves.toMatchObject({
+ total: 1,
+ groups: [{ value: { kind: "status", status: "paused" } }],
+ });
+ await expect(
+ client.listIssueTableGroups({ query, group: { kind: "assignee" } }),
+ ).resolves.toMatchObject({
+ total: 1,
+ groups: [
+ { value: { kind: "assignee", actor: { type: "service", id: "bot-1" } } },
+ ],
+ });
+ });
+});
+
describe("ApiClient label response schemas", () => {
it("falls back safely for malformed label catalog, label, and resource responses", async () => {
const fetchMock = vi.fn().mockImplementation(() =>
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index c9568c04d1..2e21e06c86 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -12,6 +12,12 @@ import type {
UpdateMemberRequest,
ListIssuesParams,
ListGroupedIssuesParams,
+ IssueTableFacetsRequest,
+ IssueTableFacetsResponse,
+ IssueTableGroupsRequest,
+ IssueTableGroupsResponse,
+ IssueTableRowsRequest,
+ IssueTableRowsResponse,
Agent,
CreateAgentRequest,
AgentTemplate,
@@ -190,6 +196,9 @@ import {
EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE,
EMPTY_AGENT_BUILDER_SESSION,
EMPTY_GROUPED_ISSUES_RESPONSE,
+ EMPTY_ISSUE_TABLE_FACETS_RESPONSE,
+ EMPTY_ISSUE_TABLE_GROUPS_RESPONSE,
+ EMPTY_ISSUE_TABLE_ROWS_RESPONSE,
EMPTY_LIST_ISSUES_RESPONSE,
EMPTY_SEARCH_ISSUES_RESPONSE,
EMPTY_SEARCH_PROJECTS_RESPONSE,
@@ -203,6 +212,9 @@ import {
AppConfigSchema,
type AppConfigResponse,
GroupedIssuesResponseSchema,
+ IssueTableFacetsResponseSchema,
+ IssueTableGroupsResponseSchema,
+ IssueTableRowsResponseSchema,
ListAutopilotsResponseSchema,
EMPTY_LIST_AUTOPILOTS_RESPONSE,
AutopilotRunSchema,
@@ -680,6 +692,45 @@ export class ApiClient {
});
}
+ async listIssueTableGroups(params: IssueTableGroupsRequest): Promise<IssueTableGroupsResponse> {
+ const raw = await this.fetch<unknown>("/api/issues/table/groups", {
+ method: "POST",
+ body: JSON.stringify(params),
+ });
+ return parseWithFallback(
+ raw,
+ IssueTableGroupsResponseSchema,
+ EMPTY_ISSUE_TABLE_GROUPS_RESPONSE,
+ { endpoint: "POST /api/issues/table/groups" },
+ );
+ }
+
+ async listIssueTableRows(params: IssueTableRowsRequest): Promise<IssueTableRowsResponse> {
+ const raw = await this.fetch<unknown>("/api/issues/table/rows", {
+ method: "POST",
+ body: JSON.stringify(params),
+ });
+ return parseWithFallback(
+ raw,
+ IssueTableRowsResponseSchema,
+ EMPTY_ISSUE_TABLE_ROWS_RESPONSE,
+ { endpoint: "POST /api/issues/table/rows" },
+ );
+ }
+
+ async listIssueTableFacets(params: IssueTableFacetsRequest): Promise<IssueTableFacetsResponse> {
+ const raw = await this.fetch<unknown>("/api/issues/table/facets", {
+ method: "POST",
+ body: JSON.stringify(params),
+ });
+ return parseWithFallback(
+ raw,
+ IssueTableFacetsResponseSchema,
+ EMPTY_ISSUE_TABLE_FACETS_RESPONSE,
+ { endpoint: "POST /api/issues/table/facets" },
+ );
+ }
+
async searchIssues(params: { q: string; limit?: number; offset?: number; include_closed?: boolean; signal?: AbortSignal }): Promise<SearchIssuesResponse> {
const search = new URLSearchParams({ q: params.q });
if (params.limit !== undefined) search.set("limit", String(params.limit));
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 1daf79e20a..4ad49a066e 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -26,6 +26,9 @@ import type {
IssueProperty,
ListPropertiesResponse,
IssuePropertiesResponse,
+ IssueTableFacetsResponse,
+ IssueTableGroupsResponse,
+ IssueTableRowsResponse,
ListIssuesResponse,
ListLabelsResponse,
ListWebhookDeliveriesResponse,
@@ -566,6 +569,98 @@ export const EMPTY_GROUPED_ISSUES_RESPONSE: GroupedIssuesResponse = {
groups: [],
};
+const IssueTableActorRefSchema = z.object({
+ // Server-driven enums stay open so installed desktop clients survive a
+ // backend that introduces another actor kind.
+ type: z.string(),
+ id: z.string(),
+}).loose();
+
+const IssueTableGroupValueSchema = z.discriminatedUnion("kind", [
+ z.object({
+ kind: z.literal("status"),
+ status: z.string(),
+ }).loose(),
+ z.object({
+ kind: z.literal("assignee"),
+ actor: IssueTableActorRefSchema.nullable(),
+ }).loose(),
+ z.object({
+ kind: z.literal("property"),
+ property_id: z.string(),
+ value: z.union([z.string(), z.boolean(), z.null()]).optional(),
+ value_state: z.enum(["value", "unavailable", "unset"]),
+ }).loose(),
+]);
+
+const IssueTableGroupDescriptorSchema = z.object({
+ key: z.string(),
+ value: IssueTableGroupValueSchema,
+ count: z.number(),
+}).loose();
+
+export const IssueTableGroupsResponseSchema = z.object({
+ query_fingerprint: z.string(),
+ total: z.number(),
+ groups: z.array(IssueTableGroupDescriptorSchema).default([]),
+ next_cursor: z.string().nullable().default(null),
+}).loose();
+
+export const EMPTY_ISSUE_TABLE_GROUPS_RESPONSE: IssueTableGroupsResponse = {
+ query_fingerprint: "",
+ total: 0,
+ groups: [],
+ next_cursor: null,
+};
+
+const IssueTableRowSchema = z.object({
+ issue: IssueSchema,
+ direct_child_count: z.number().default(0),
+}).loose();
+
+export const IssueTableRowsResponseSchema = z.object({
+ query_fingerprint: z.string(),
+ group_key: z.string().nullable().default(null),
+ parent_id: z.string().nullable().default(null),
+ total: z.number(),
+ rows: z.array(IssueTableRowSchema).default([]),
+ branch_total: z.number(),
+ next_cursor: z.string().nullable().default(null),
+}).loose();
+
+export const EMPTY_ISSUE_TABLE_ROWS_RESPONSE: IssueTableRowsResponse = {
+ query_fingerprint: "",
+ group_key: null,
+ parent_id: null,
+ total: 0,
+ rows: [],
+ branch_total: 0,
+ next_cursor: null,
+};
+
+const IssueTableFacetValueSchema = z.object({
+ key: z.string(),
+ count: z.number(),
+}).loose();
+
+const IssueTableFacetSchema = z.object({
+ kind: z.enum(["status", "priority", "assignee", "creator", "project", "label", "property"]),
+ property_id: z.string().optional(),
+ values: z.array(IssueTableFacetValueSchema).default([]),
+}).loose();
+
+export const IssueTableFacetsResponseSchema = z.object({
+ query_fingerprint: z.string(),
+ total: z.number(),
+ facets: z.array(IssueTableFacetSchema).default([]),
+}).loose();
+
+export const EMPTY_ISSUE_TABLE_FACETS_RESPONSE: IssueTableFacetsResponse = {
+ query_fingerprint: "",
+ total: 0,
+ facets: [],
+};
+
const SubscriberSchema = z.object({
issue_id: z.string(),
user_type: z.string(),
diff --git a/packages/core/issues/cache-coordinator.test.ts b/packages/core/issues/cache-coordinator.test.ts
index 5791687e42..1adff02398 100644
--- a/packages/core/issues/cache-coordinator.test.ts
+++ b/packages/core/issues/cache-coordinator.test.ts
@@ -9,7 +9,12 @@ import {
import { issueChangedDims } from "./surface/membership";
import { issueKeys, type IssueSortParam } from "./queries";
import { inboxKeys } from "../inbox/queries";
-import type { InboxItem, Issue, ListIssuesCache } from "../types";
+import type {
+ InboxItem,
+ Issue,
+ IssueTableRowsResponse,
+ ListIssuesCache,
+} from "../types";
const WS_ID = "ws-1";
const sort: IssueSortParam = { sort_by: "position", sort_direction: undefined };
@@ -57,6 +62,22 @@ const flatSearchKey = issueKeys.flat(
{ q: "Issue 1" },
sort,
);
+const tableRowKey = [
+ ...issueKeys.tableRows(
+ WS_ID,
+ {
+ scope: { kind: "workspace" },
+ filters: {},
+ sort: { field: "position", direction: "asc" },
+ },
+ { kind: "none" },
+ null,
+ false,
+ null,
+ ),
+ "page",
+ null,
+] as const;
const updatedSort: IssueSortParam = {
sort_by: "updated_at",
sort_direction: "desc",
@@ -191,6 +212,33 @@ describe("applyIssueChange", () => {
).toBe("Issue 1");
});
+ it("patches and rolls back loaded server Table rows", () => {
+ const snapshot: IssueTableRowsResponse = {
+ query_fingerprint: "sha256:table",
+ group_key: null,
+ parent_id: null,
+ total: 1,
+ rows: [{ issue: issue(), direct_child_count: 0 }],
+ branch_total: 1,
+ next_cursor: null,
+ };
+ qc.setQueryData(tableRowKey, snapshot);
+
+ const patch = { title: "optimistic table title" };
+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {
+ changed: issueChangedDims(patch, issue()),
+ baseIssue: issue(),
+ });
+
+ expect(
+ qc.getQueryData<IssueTableRowsResponse>(tableRowKey)?.rows[0]?.issue.title,
+ ).toBe("optimistic table title");
+ expect(result.prevTableRows).toEqual([[tableRowKey, snapshot]]);
+
+ rollbackIssueChange(qc, WS_ID, "issue-1", result);
+ expect(qc.getQueryData(tableRowKey)).toEqual(snapshot);
+ });
+
it("marks only flat windows whose sort or facet depends on the changed field", () => {
for (const key of [
flatKey,
diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.ts
index 192c12316a..1bf4be6d37 100644
--- a/packages/core/issues/cache-coordinator.ts
+++ b/packages/core/issues/cache-coordinator.ts
@@ -28,11 +28,13 @@ import {
import type {
InboxItem,
Issue,
+ IssueTableRowsResponse,
ListIssuesCache,
ListIssuesResponse,
} from "../types";
export type IssueFlatCache = InfiniteData<ListIssuesResponse, number>;
+export type IssueTableRowCache = IssueTableRowsResponse;
/**
* IssueCacheCoordinator — the one rules table for how a single issue change
@@ -82,6 +84,7 @@ export interface IssueCacheChangeResult {
* {@link rollbackIssueChange} from onError. */
prevLists: [QueryKey, ListIssuesCache][];
prevFlatLists: [QueryKey, IssueFlatCache][];
+ prevTableRows: [QueryKey, IssueTableRowCache][];
prevDetail: Issue | undefined;
prevInboxList: InboxItem[] | undefined;
/** Loaded list keys whose server result may have drifted (membership
@@ -141,6 +144,20 @@ function flatListEntries(
);
}
+function tableRowEntries(
+ qc: QueryClient,
+ wsId: string,
+): [QueryKey, IssueTableRowCache][] {
+ return qc
+ .getQueriesData<unknown>({ queryKey: issueKeys.tableAll(wsId) })
+ .filter(
+ (entry): entry is [QueryKey, IssueTableRowCache] =>
+ !!entry[1] &&
+ typeof entry[1] === "object" &&
+ Array.isArray((entry[1] as IssueTableRowCache).rows),
+ );
+}
+
function flatContractFromKey(key: QueryKey): {
scope: string | undefined;
filter: IssueFlatFilter;
@@ -260,6 +277,7 @@ export function applyIssueChange(
const { changed, baseIssue } = opts;
const prevLists: [QueryKey, ListIssuesCache][] = [];
const prevFlatLists: [QueryKey, IssueFlatCache][] = [];
+ const prevTableRows: [QueryKey, IssueTableRowCache][] = [];
const staleKeys: QueryKey[] = [];
let prevIssue: Issue | undefined = baseIssue;
@@ -383,6 +401,24 @@ export function applyIssueChange(
}
}
+ // Table branch pages are partial server-owned projections, so membership,
+ // counts and ordering still reconcile through the existing tableAll
+ // invalidation on settle. The entity snapshot inside every loaded row is
+ // determinate, though: patch it immediately so inline edits never flash the
+ // old title/status/assignee while the authoritative branch refetch runs.
+ for (const [key, data] of tableRowEntries(qc, wsId)) {
+ let found: Issue | undefined;
+ const rows = data.rows.map((row) => {
+ if (row.issue.id !== id) return row;
+ found = row.issue;
+ return { ...row, issue: { ...row.issue, ...patch } };
+ });
+ if (!found) continue;
+ if (!prevIssue) prevIssue = found;
+ prevTableRows.push([key, data]);
+ qc.setQueryData<IssueTableRowCache>(key, { ...data, rows });
+ }
+
const prevDetail = qc.getQueryData<Issue>(issueKeys.detail(wsId, id));
if (prevDetail) {
qc.setQueryData<Issue>(issueKeys.detail(wsId, id), {
@@ -403,6 +439,7 @@ export function applyIssueChange(
return {
prevLists,
prevFlatLists,
+ prevTableRows,
prevDetail,
prevInboxList,
staleKeys,
@@ -418,7 +455,11 @@ export function rollbackIssueChange(
id: string,
result: Pick<
IssueCacheChangeResult,
- "prevLists" | "prevFlatLists" | "prevDetail" | "prevInboxList"
+ | "prevLists"
+ | "prevFlatLists"
+ | "prevTableRows"
+ | "prevDetail"
+ | "prevInboxList"
>,
) {
for (const [key, snapshot] of result.prevLists) {
@@ -427,6 +468,9 @@ export function rollbackIssueChange(
for (const [key, snapshot] of result.prevFlatLists) {
qc.setQueryData(key, snapshot);
}
+ for (const [key, snapshot] of result.prevTableRows) {
+ qc.setQueryData(key, snapshot);
+ }
if (result.prevDetail !== undefined) {
qc.setQueryData(issueKeys.detail(wsId, id), result.prevDetail);
}
diff --git a/packages/core/issues/delete-cache.ts b/packages/core/issues/delete-cache.ts
index 69657a7346..0a9013a884 100644
--- a/packages/core/issues/delete-cache.ts
+++ b/packages/core/issues/delete-cache.ts
@@ -206,6 +206,7 @@ export function cleanupDeletedIssueCaches(
qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
// Project Gantt cache lives outside `myAll`, so it needs an explicit
// refresh when an issue is removed — the deleted row may have been a
// scheduled bar visible right now.
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 8dfe277a98..4f09bcd39d 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -16,6 +16,7 @@ import {
invalidateStaleListKeys,
rollbackIssueChange,
type IssueFlatCache,
+ type IssueTableRowCache,
} from "./cache-coordinator";
import { issueChangedDims } from "./surface/membership";
import {
@@ -208,6 +209,7 @@ export function useCreateIssue() {
onSettled: () => {
qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });
@@ -235,6 +237,7 @@ export function useUpdateIssue() {
qc.cancelQueries({ queryKey: issueKeys.list(wsId) });
qc.cancelQueries({ queryKey: issueKeys.myAll(wsId) });
qc.cancelQueries({ queryKey: issueKeys.flatAll(wsId) });
+ qc.cancelQueries({ queryKey: issueKeys.tableAll(wsId) });
if (patch.status !== undefined) {
qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });
}
@@ -349,6 +352,7 @@ export function useUpdateIssue() {
vars.status !== undefined ||
Object.prototype.hasOwnProperty.call(vars, "project_id"),
});
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
if (ctx) {
invalidateStaleListKeys(qc, ctx.change.staleKeys);
}
@@ -465,6 +469,7 @@ export function useDeleteIssue() {
onSettled: (_data, _err, _id, ctx) => {
qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });
@@ -492,6 +497,7 @@ export function useBatchUpdateIssues() {
await qc.cancelQueries({ queryKey: issueKeys.list(wsId) });
await qc.cancelQueries({ queryKey: issueKeys.myAll(wsId) });
await qc.cancelQueries({ queryKey: issueKeys.flatAll(wsId) });
+ await qc.cancelQueries({ queryKey: issueKeys.tableAll(wsId) });
if (patch.status !== undefined) {
await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });
}
@@ -504,6 +510,10 @@ export function useBatchUpdateIssues() {
// first snapshot per key is pristine for rollback.
const prevListByHash = new Map<string, [QueryKey, ListIssuesCache]>();
const prevFlatListByHash = new Map<string, [QueryKey, IssueFlatCache]>();
+ const prevTableRowByHash = new Map<
+ string,
+ [QueryKey, IssueTableRowCache]
+ >();
const prevDetailById = new Map<string, Issue>();
let prevInboxList: InboxItem[] | undefined;
const staleKeys: QueryKey[] = [];
@@ -523,6 +533,12 @@ export function useBatchUpdateIssues() {
prevFlatListByHash.set(hash, [key, snapshot]);
}
}
+ for (const [key, snapshot] of change.prevTableRows) {
+ const hash = hashKey(key);
+ if (!prevTableRowByHash.has(hash)) {
+ prevTableRowByHash.set(hash, [key, snapshot]);
+ }
+ }
if (change.prevDetail) prevDetailById.set(id, change.prevDetail);
if (prevInboxList === undefined && change.prevInboxList !== undefined) {
prevInboxList = change.prevInboxList;
@@ -552,6 +568,7 @@ export function useBatchUpdateIssues() {
return {
prevLists: [...prevListByHash.values()],
prevFlatLists: [...prevFlatListByHash.values()],
+ prevTableRows: [...prevTableRowByHash.values()],
prevDetailById,
prevInboxList,
staleKeys,
@@ -570,6 +587,11 @@ export function useBatchUpdateIssues() {
qc.setQueryData(key, snapshot);
}
}
+ if (ctx?.prevTableRows) {
+ for (const [key, snapshot] of ctx.prevTableRows) {
+ qc.setQueryData(key, snapshot);
+ }
+ }
if (ctx?.prevDetailById) {
for (const [id, snapshot] of ctx.prevDetailById) {
qc.setQueryData(issueKeys.detail(wsId, id), snapshot);
@@ -598,6 +620,7 @@ export function useBatchUpdateIssues() {
_vars.updates.status !== undefined ||
Object.prototype.hasOwnProperty.call(_vars.updates, "project_id"),
});
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
if (ctx) {
invalidateStaleListKeys(qc, ctx.staleKeys);
}
@@ -733,6 +756,7 @@ export function useBatchDeleteIssues() {
onSettled: (_data, _err, _ids, ctx) => {
qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index c744945f12..ecda86ff67 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -9,6 +9,11 @@ import type {
GroupedIssuesResponse,
Issue,
IssueStatus,
+ IssueTableFacetsRequest,
+ IssueTableGroupSpec,
+ IssueTableGroupsRequest,
+ IssueTableQuerySpec,
+ IssueTableRowsRequest,
ListGroupedIssuesParams,
ListIssuesParams,
ListIssuesCache,
@@ -47,6 +52,31 @@ export const issueKeys = {
filter: IssueFlatFilter,
sort?: IssueSortParam,
) => [...issueKeys.flatAll(wsId), "export", scope, filter, sort ?? {}] as const,
+ tableAll: (wsId: string) => [...issueKeys.all(wsId), "table-query"] as const,
+ tableGroups: (
+ wsId: string,
+ query: IssueTableQuerySpec,
+ group: IssueTableGroupsRequest["group"],
+ ) => [...issueKeys.tableAll(wsId), "groups", query, group] as const,
+ tableFacets: (
+ wsId: string,
+ request: IssueTableFacetsRequest,
+ ) => [...issueKeys.tableAll(wsId), "facets", request] as const,
+ tableRows: (
+ wsId: string,
+ query: IssueTableQuerySpec,
+ group: IssueTableGroupSpec,
+ groupKey: string | null,
+ hierarchy: boolean,
+ parentId: string | null,
+ ) => [
+ ...issueKeys.tableAll(wsId),
+ "rows",
+ query,
+ group,
+ groupKey,
+ { hierarchy, parentId },
+ ] as const,
assigneeGroupsAll: (wsId: string) =>
[...issueKeys.all(wsId), "assignee-groups"] as const,
assigneeGroups: (wsId: string, filter: AssigneeGroupedIssuesFilter) =>
@@ -379,6 +409,69 @@ export function issueFlatListOptions(
});
}
+export function issueTableGroupsOptions(
+ wsId: string,
+ query: IssueTableQuerySpec,
+ group: IssueTableGroupsRequest["group"],
+) {
+ return infiniteQueryOptions({
+ queryKey: issueKeys.tableGroups(wsId, query, group),
+ initialPageParam: null as string | null,
+ queryFn: ({ pageParam }) =>
+ api.listIssueTableGroups({
+ query,
+ group,
+ page: { limit: 100, cursor: pageParam },
+ }),
+ getNextPageParam: (lastPage) => lastPage.next_cursor ?? undefined,
+ placeholderData: keepPreviousData,
+ retry: false,
+ });
+}
+
+/** One independently-addressable Table branch page.
+ *
+ * Table keeps every cursor page under its own query key so a refreshed head
+ * can detach stale tail cursors before their responses land. Keep the request,
+ * key shape, transition placeholder, and retry policy together here — the
+ * dynamic branch graph in views should not duplicate this API contract. */
+export function issueTableRowPageOptions(
+ wsId: string,
+ request: IssueTableRowsRequest,
+) {
+ const cursor = request.page?.cursor ?? null;
+ return queryOptions({
+ queryKey: [
+ ...issueKeys.tableRows(
+ wsId,
+ request.query,
+ request.group,
+ request.group_key,
+ request.hierarchy.enabled,
+ request.parent_id,
+ ),
+ "page",
+ cursor,
+ ] as const,
+ queryFn: () => api.listIssueTableRows(request),
+ placeholderData: keepPreviousData,
+ retry: false,
+ // Dynamic useQueries observers can detach/reinstall as sibling branches
+ // enter the viewport. An errored page stays errored until explicit Retry.
+ refetchOnMount: false,
+ });
+}
+
+export function issueTableFacetsOptions(
+ wsId: string,
+ request: IssueTableFacetsRequest,
+) {
+ return queryOptions({
+ queryKey: issueKeys.tableFacets(wsId, request),
+ queryFn: () => api.listIssueTableFacets(request),
+ });
+}
+
export function issueFlatExportOptions(
wsId: string,
scope: string,
diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.ts
index 4943876f63..8609a21804 100644
--- a/packages/core/issues/ws-updaters.test.ts
+++ b/packages/core/issues/ws-updaters.test.ts
@@ -27,6 +27,7 @@ import type {
Issue,
IssueReaction,
IssueLabelsResponse,
+ IssueTableRowsResponse,
IssueSubscriber,
IssueUsageSummary,
Label,
@@ -105,6 +106,35 @@ function makeListCache(...issues: Issue[]): ListIssuesCache {
};
}
+const tableRowKey = [
+ ...issueKeys.tableRows(
+ WS_ID,
+ {
+ scope: { kind: "workspace" },
+ filters: {},
+ sort: { field: "position", direction: "asc" },
+ },
+ { kind: "none" },
+ null,
+ false,
+ null,
+ ),
+ "page",
+ null,
+] as const;
+
+function seedTableRow(qc: QueryClient, issue = baseIssue) {
+ qc.setQueryData<IssueTableRowsResponse>(tableRowKey, {
+ query_fingerprint: "sha256:table",
+ group_key: null,
+ parent_id: null,
+ total: 1,
+ rows: [{ issue, direct_child_count: 0 }],
+ branch_total: 1,
+ next_cursor: null,
+ });
+}
+
function makeTask(issueId = ISSUE_ID): AgentTask {
return {
id: `task-${issueId}`,
@@ -151,11 +181,12 @@ describe("onIssueLabelsChanged", () => {
expect(qc.getQueryData(labelKeys.byIssue(WS_ID, ISSUE_ID))).toBeUndefined();
});
- it("still patches the list and detail caches", () => {
+ it("still patches the list, Table row, and detail caches", () => {
qc.setQueryData<ListIssuesCache>(issueKeys.list(WS_ID), {
byStatus: { todo: { issues: [baseIssue], total: 1 } },
});
qc.setQueryData<Issue>(issueKeys.detail(WS_ID, ISSUE_ID), baseIssue);
+ seedTableRow(qc);
onIssueLabelsChanged(qc, WS_ID, ISSUE_ID, [labelB]);
@@ -164,6 +195,10 @@ describe("onIssueLabelsChanged", () => {
const detail = qc.getQueryData<Issue>(issueKeys.detail(WS_ID, ISSUE_ID));
expect(detail?.labels).toEqual([labelB]);
+ expect(
+ qc.getQueryData<IssueTableRowsResponse>(tableRowKey)?.rows[0]?.issue
+ .labels,
+ ).toEqual([labelB]);
});
it("patches the Project Gantt cache so label filters react in place", () => {
@@ -263,6 +298,10 @@ describe("onIssueMetadataChanged", () => {
},
},
});
+ seedTableRow(qc, {
+ ...baseIssue,
+ metadata: { pr_number: 1, stale: "yes" },
+ });
onIssueMetadataChanged(qc, WS_ID, ISSUE_ID, { pr_number: 2 });
@@ -270,6 +309,10 @@ describe("onIssueMetadataChanged", () => {
expect(detail?.metadata).toEqual({ pr_number: 2 });
const list = qc.getQueryData<ListIssuesCache>(issueKeys.list(WS_ID));
expect(list?.byStatus.todo?.issues[0]?.metadata).toEqual({ pr_number: 2 });
+ expect(
+ qc.getQueryData<IssueTableRowsResponse>(tableRowKey)?.rows[0]?.issue
+ .metadata,
+ ).toEqual({ pr_number: 2 });
});
it("leaves untouched caches as undefined (no spurious writes)", () => {
@@ -354,6 +397,7 @@ describe("issue property snapshots", () => {
pages: [{ issues: [baseIssue], total: 1 }],
pageParams: [0],
});
+ seedTableRow(qc);
patchIssueProperties(qc, WS_ID, ISSUE_ID, { estimate: 3 });
@@ -362,6 +406,10 @@ describe("issue property snapshots", () => {
qc.getQueryData<{ pages: { issues: Issue[] }[] }>(flatKey)?.pages[0]
?.issues[0]?.properties,
).toEqual({ estimate: 3 });
+ expect(
+ qc.getQueryData<IssueTableRowsResponse>(tableRowKey)?.rows[0]?.issue
+ .properties,
+ ).toEqual({ estimate: 3 });
onIssuePropertiesChanged(qc, WS_ID, ISSUE_ID, { estimate: 4 });
diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.ts
index a8576dbe32..134f4aadca 100644
--- a/packages/core/issues/ws-updaters.ts
+++ b/packages/core/issues/ws-updaters.ts
@@ -15,7 +15,14 @@ import {
patchIssueInBuckets,
} from "./cache-helpers";
import { cleanupDeletedIssueCaches } from "./delete-cache";
-import type { Issue, IssueLabelsResponse, IssueMetadata, IssuePropertyValues, Label } from "../types";
+import type {
+ Issue,
+ IssueLabelsResponse,
+ IssueMetadata,
+ IssuePropertyValues,
+ IssueTableRowsResponse,
+ Label,
+} from "../types";
import type { ListIssuesCache } from "../types";
function patchIssueInFlatCaches(
@@ -60,6 +67,35 @@ function patchIssueInChildrenCaches(
}
}
+function patchIssueInTableCaches(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ patch: Partial<Issue>,
+) {
+ for (const [key, data] of qc.getQueriesData<unknown>({
+ queryKey: issueKeys.tableAll(wsId),
+ })) {
+ if (
+ !data ||
+ typeof data !== "object" ||
+ !Array.isArray((data as IssueTableRowsResponse).rows)
+ ) {
+ continue;
+ }
+ const page = data as IssueTableRowsResponse;
+ if (!page.rows.some((row) => row.issue.id === issueId)) continue;
+ qc.setQueryData<IssueTableRowsResponse>(key, {
+ ...page,
+ rows: page.rows.map((row) =>
+ row.issue.id === issueId
+ ? { ...row, issue: { ...row.issue, ...patch } }
+ : row,
+ ),
+ });
+ }
+}
+
function findIssueInFlatCaches(
qc: QueryClient,
wsId: string,
@@ -86,6 +122,7 @@ export function onIssueCreated(
}
qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
if (issue.project_id) {
@@ -175,6 +212,9 @@ export function onIssueUpdated(
statusOrProjectChanged:
issue.status !== undefined || issue.project_id !== undefined,
});
+ // Group counts, branch membership and hierarchy are server-owned. Never
+ // guess deltas from a partial branch; refetch the active Table queries.
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
// Invalidate old parent's children (issue was removed from it)
if (oldParentId) {
@@ -230,6 +270,7 @@ export function patchIssueLabels(
if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { labels }));
}
patchIssueInFlatCaches(qc, wsId, issueId, { labels });
+ patchIssueInTableCaches(qc, wsId, issueId, { labels });
qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
old ? { ...old, labels } : old,
);
@@ -266,6 +307,7 @@ export function invalidateIssueLabelDerivatives(qc: QueryClient, wsId: string) {
qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
qc.invalidateQueries({
queryKey: issueKeys.flatAll(wsId),
predicate: (query) =>
@@ -296,6 +338,7 @@ export function onIssueMetadataChanged(
if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { metadata }));
}
patchIssueInFlatCaches(qc, wsId, issueId, { metadata });
+ patchIssueInTableCaches(qc, wsId, issueId, { metadata });
qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
old ? { ...old, metadata } : old,
);
@@ -305,6 +348,9 @@ export function onIssueMetadataChanged(
// 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);
+ // Server-backed Table counts, membership and cursor boundaries may also
+ // depend on metadata-driven timestamps, so refresh its query graph too.
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
}
/**
@@ -330,6 +376,7 @@ export function onIssuePropertiesChanged(
// staleTime:Infinity (clean-room review F2).
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
invalidatePropertyWindowQueries(qc, wsId);
// A property write also bumps issue.updated_at server-side
// (SetIssuePropertyValue / DeleteIssuePropertyValue). invalidatePropertyWindow
@@ -353,6 +400,7 @@ export function patchIssueProperties(
if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { properties }));
}
patchIssueInFlatCaches(qc, wsId, issueId, { properties });
+ patchIssueInTableCaches(qc, wsId, issueId, { properties });
qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
old ? { ...old, properties } : old,
);
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index a282a9d2e5..dbf5b3e1fa 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -7,6 +7,7 @@ import type { ReactNode } from "react";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import type { WSClient } from "../api/ws-client";
import { defaultStorage } from "../platform/storage";
+import { issueKeys } from "../issues/queries";
import { workspaceKeys } from "../workspace/queries";
import {
markWorkspaceDeletePending,
@@ -195,6 +196,56 @@ describe("useRealtimeSync — ws instance change", () => {
});
});
+describe("useRealtimeSync — Table server membership invalidation", () => {
+ let qc: QueryClient;
+ let stores: RealtimeSyncStores;
+
+ beforeEach(() => {
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ stores = createStores();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("invalidates Table queries after a task lifecycle event", () => {
+ vi.useFakeTimers();
+ const ws = createMockWs();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ renderHook(() => useRealtimeSync(ws, stores), {
+ wrapper: createWrapper(qc),
+ });
+ const onAny = vi.mocked(ws.onAny).mock.calls[0]?.[0];
+ expect(onAny).toBeDefined();
+
+ onAny!({ type: "task:completed", payload: {} } as never);
+ vi.advanceTimersByTime(100);
+
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: issueKeys.tableAll("ws-1"),
+ });
+ });
+
+ it("invalidates Table queries after a property definition changes", () => {
+ const ws = createMockWs();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ renderHook(() => useRealtimeSync(ws, stores), {
+ wrapper: createWrapper(qc),
+ });
+ const propertyUpdated = vi
+ .mocked(ws.on)
+ .mock.calls.find(([event]) => event === "property:updated")?.[1];
+ expect(propertyUpdated).toBeDefined();
+
+ (propertyUpdated as (payload: unknown) => void)({});
+
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: issueKeys.tableAll("ws-1"),
+ });
+ });
+});
+
describe("useRealtimeSync — workspace:deleted self-initiated suppression", () => {
let qc: QueryClient;
let stores: RealtimeSyncStores;
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 9c2fee09e4..a40533c416 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -695,6 +695,11 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (!wsId) return;
qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.list(wsId) });
+ // Table's working_only predicate is evaluated from task lifecycle
+ // state on the server. Without invalidating its server-owned graph,
+ // rows/groups/facets can remain permanently stale (global staleTime
+ // is Infinity) after a task starts or reaches a terminal state.
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
// 30d activity series shares the same lifecycle signal — any task
// completion / failure shifts the histogram. (Dispatch alone
// doesn't change a completed_at-anchored series, but invalidating
@@ -855,7 +860,12 @@ export function useRealtimeSync(
const unsubPropertyChanged = ["property:created", "property:updated"].map((event) =>
ws.on(event as "property:created" | "property:updated", () => {
const wsId = getCurrentWsId();
- if (wsId) qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
+ if (wsId) {
+ qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
+ // Group order, supported group types, and unavailable option values
+ // are derived from the property definition, not just issue rows.
+ qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
+ }
}),
);
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index a69933a948..7cd50670c9 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -219,6 +219,160 @@ export interface GroupedIssuesResponse {
groups: IssueAssigneeGroup[];
}
+// Server-authoritative Table query contract. Membership, grouping and counts
+// are evaluated against the complete result set; the browser only owns view
+// state such as collapsed groups/parents.
+export type IssueTableScope =
+ | { kind: "workspace"; assignee_types?: IssueAssigneeType[] }
+ | { kind: "project"; project_id: string }
+ | { kind: "assignee"; actor: IssueActorRef }
+ | { kind: "creator"; actor: IssueActorRef }
+ | { kind: "my"; relation: "assigned" | "created" | "involved" | "any" };
+
+export interface IssueTableFilters {
+ statuses?: IssueStatus[];
+ priorities?: IssuePriority[];
+ assignees?: IssueActorRef[];
+ include_no_assignee?: boolean;
+ creators?: IssueActorRef[];
+ project_ids?: string[];
+ include_no_project?: boolean;
+ label_ids?: string[];
+ properties?: Record<string, string[]>;
+ date?: {
+ field: "created_at" | "updated_at";
+ start: string;
+ end: string;
+ };
+ working_only?: boolean;
+ include_sub_issues?: boolean;
+}
+
+export type IssueTableSortField =
+ | "position"
+ | "status"
+ | "priority"
+ | "title"
+ | "created_at"
+ | "updated_at"
+ | "start_date"
+ | "due_date"
+ | `property:${string}`;
+
+export interface IssueTableQuerySpec {
+ scope: IssueTableScope;
+ filters: IssueTableFilters;
+ search?: string;
+ sort: {
+ field: IssueTableSortField;
+ direction: "asc" | "desc";
+ };
+}
+
+export type IssueTableGroupSpec =
+ | { kind: "none" }
+ | { kind: "status" }
+ | { kind: "assignee" }
+ | { kind: "property"; property_id: string };
+
+/** Response-side actor reference. Kept open for forward compatibility: an
+ * installed desktop client may receive a new actor kind from a newer server. */
+export interface IssueTableActorRef {
+ type: string;
+ id: string;
+}
+
+export type IssueTableGroupValue =
+ | { kind: "status"; status: string }
+ | { kind: "assignee"; actor: IssueTableActorRef | null }
+ | {
+ kind: "property";
+ property_id: string;
+ value?: string | boolean | null;
+ value_state: "value" | "unavailable" | "unset";
+ };
+
+export interface IssueTableGroupDescriptor {
+ key: string;
+ value: IssueTableGroupValue;
+ count: number;
+}
+
+export interface IssueTablePageRequest {
+ limit?: number;
+ cursor?: string | null;
+}
+
+export interface IssueTableGroupsRequest {
+ query: IssueTableQuerySpec;
+ group: Exclude<IssueTableGroupSpec, { kind: "none" }>;
+ page?: IssueTablePageRequest;
+}
+
+export interface IssueTableGroupsResponse {
+ query_fingerprint: string;
+ total: number;
+ groups: IssueTableGroupDescriptor[];
+ next_cursor: string | null;
+}
+
+export interface IssueTableRowsRequest {
+ query: IssueTableQuerySpec;
+ group: IssueTableGroupSpec;
+ group_key: string | null;
+ hierarchy: { enabled: boolean };
+ parent_id: string | null;
+ page?: IssueTablePageRequest;
+}
+
+export interface IssueTableRow {
+ issue: Issue;
+ direct_child_count: number;
+}
+
+export interface IssueTableRowsResponse {
+ query_fingerprint: string;
+ group_key: string | null;
+ parent_id: string | null;
+ total: number;
+ rows: IssueTableRow[];
+ branch_total: number;
+ next_cursor: string | null;
+}
+
+export type IssueTableFacetSpec =
+ | { kind: "status" }
+ | { kind: "priority" }
+ | { kind: "assignee" }
+ | { kind: "creator" }
+ | { kind: "project" }
+ | { kind: "label" }
+ | { kind: "property"; property_id: string };
+
+export interface IssueTableFacetsRequest {
+ query: IssueTableQuerySpec;
+ facets: IssueTableFacetSpec[];
+ /** Existing callers default to true. Count-only UIs can skip the extra scan. */
+ include_total?: boolean;
+}
+
+export interface IssueTableFacetValue {
+ key: string;
+ count: number;
+}
+
+export interface IssueTableFacet {
+ kind: IssueTableFacetSpec["kind"];
+ property_id?: string;
+ values: IssueTableFacetValue[];
+}
+
+export interface IssueTableFacetsResponse {
+ query_fingerprint: string;
+ total: number;
+ facets: IssueTableFacet[];
+}
+
/** Per-status bucket in the paginated issue cache. `total` is the server count (all pages), not the length of `issues`. */
export interface IssueStatusBucket {
issues: Issue[];
diff --git a/packages/views/editor/mermaid-diagram.test.tsx b/packages/views/editor/mermaid-diagram.test.tsx
index ab21df2c66..f8093ede8b 100644
--- a/packages/views/editor/mermaid-diagram.test.tsx
+++ b/packages/views/editor/mermaid-diagram.test.tsx
@@ -127,32 +127,39 @@ async function expectViewerStaysClosed() {
}
describe("MermaidDiagram theme changes", () => {
- it("keeps the viewer open and preserves zoom when the theme flips", async () => {
- render(<MermaidDiagram chart={CHART} />);
- await openViewer();
-
- fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
- const zoomed = currentScale();
- expect(zoomed).toBeGreaterThan(0.8);
-
- // Flip the theme the way the app does; the component observes documentElement
- // and re-renders the diagram with new theme colors.
- await act(async () => {
- document.documentElement.classList.add("dark");
- // Let the MutationObserver callback and the async re-render settle.
- await Promise.resolve();
- });
-
- await waitFor(() => {
- expect(mermaidRenderMock.mock.calls.length).toBeGreaterThan(1);
- });
-
- // The viewer previously unmounted here: the re-render cleared the rendered
- // document to null before the new one arrived, closing the dialog and
- // throwing away the user's zoom and position mid-read.
- expect(screen.getByRole("application")).toBeInTheDocument();
- expect(currentScale()).toBeCloseTo(zoomed, 5);
- });
+ it(
+ "keeps the viewer open and preserves zoom when the theme flips",
+ async () => {
+ render(<MermaidDiagram chart={CHART} />);
+ await openViewer();
+
+ fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
+ const zoomed = currentScale();
+ expect(zoomed).toBeGreaterThan(0.8);
+
+ // Flip the theme the way the app does; the component observes documentElement
+ // and re-renders the diagram with new theme colors.
+ await act(async () => {
+ document.documentElement.classList.add("dark");
+ // Let the MutationObserver callback and the async re-render settle.
+ await Promise.resolve();
+ });
+
+ await waitFor(() => {
+ expect(mermaidRenderMock.mock.calls.length).toBeGreaterThan(1);
+ });
+
+ // The viewer previously unmounted here: the re-render cleared the rendered
+ // document to null before the new one arrived, closing the dialog and
+ // throwing away the user's zoom and position mid-read.
+ expect(screen.getByRole("application")).toBeInTheDocument();
+ expect(currentScale()).toBeCloseTo(zoomed, 5);
+ },
+ // Dialog portal setup and the MutationObserver callback can be starved while
+ // the full views suite shares a saturated CI runner. Keep the larger budget
+ // local to this integration-style test instead of weakening the suite default.
+ 15_000,
+ );
it("never blanks the diagram while the themed re-render is still in flight", async () => {
render(<MermaidDiagram chart={CHART} />);
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index 3b3f063e53..2b0c4d685f 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -13,6 +13,7 @@ import {
FolderKanban,
FolderMinus,
List,
+ Rows3,
SignalHigh,
SlidersHorizontal,
X,
@@ -59,7 +60,12 @@ import { projectListOptions } from "@multica/core/projects/queries";
import { labelListOptions } from "@multica/core/labels/queries";
import { propertyListOptions } from "@multica/core/properties";
import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
-import type { IssueProperty } from "@multica/core/types";
+import type {
+ Issue,
+ IssueProperty,
+ IssueTableFacetSpec,
+ IssueTableFacetsResponse,
+} from "@multica/core/types";
import { ProjectIcon } from "../../projects/components/project-icon";
import { ActorAvatar } from "../../common/actor-avatar";
import { PropertyIcon } from "../../common/property-icon";
@@ -69,7 +75,6 @@ import {
GROUPING_OPTIONS,
SWIMLANE_GROUPINGS,
CARD_PROPERTY_OPTIONS,
- TABLE_SYSTEM_COLUMNS,
type ActorFilterValue,
type IssueDateField,
type IssueDateFilter,
@@ -86,11 +91,11 @@ import {
type IssuesScope,
} from "@multica/core/issues/stores/issues-scope-store";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
-import type { Issue } from "@multica/core/types";
import { useT } from "../../i18n";
import { matchesPinyin } from "../../editor/extensions/pinyin-match";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
import { WorkspaceAgentWorkingChip } from "./workspace-agent-working-chip";
+import { TableColumnPicker } from "./table-view";
type LocalDateRange = {
from: Date | undefined;
@@ -144,7 +149,10 @@ const DATE_FIELD_LABEL_KEY: Record<IssueDateField, "date_field_created" | "date_
* render at count > 0) without touching the option lists themselves. */
const NO_COUNT_ISSUES: Issue[] = [];
-function useIssueCounts(allIssues: Issue[]) {
+function useIssueCounts(
+ allIssues: Issue[],
+ serverFacets?: IssueTableFacetsResponse,
+) {
return useMemo(() => {
const status = new Map<string, number>();
const priority = new Map<string, number>();
@@ -158,6 +166,42 @@ function useIssueCounts(allIssues: Issue[]) {
let noAssignee = 0;
let noProject = 0;
+ if (serverFacets) {
+ for (const facet of serverFacets.facets) {
+ const target =
+ facet.kind === "status"
+ ? status
+ : facet.kind === "priority"
+ ? priority
+ : facet.kind === "assignee"
+ ? assignee
+ : facet.kind === "creator"
+ ? creator
+ : facet.kind === "project"
+ ? project
+ : facet.kind === "label"
+ ? label
+ : null;
+ if (facet.kind === "property" && facet.property_id) {
+ property.set(
+ facet.property_id,
+ new Map(facet.values.map((value) => [value.key, value.count])),
+ );
+ continue;
+ }
+ for (const value of facet.values) {
+ if (facet.kind === "assignee" && value.key === "__none__") {
+ noAssignee = value.count;
+ } else if (facet.kind === "project" && value.key === "__none__") {
+ noProject = value.count;
+ } else {
+ target?.set(value.key, value.count);
+ }
+ }
+ }
+ return { status, priority, assignee, creator, noAssignee, project, noProject, label, property };
+ }
+
for (const issue of allIssues) {
status.set(issue.status, (status.get(issue.status) ?? 0) + 1);
priority.set(issue.priority, (priority.get(issue.priority) ?? 0) + 1);
@@ -206,7 +250,7 @@ function useIssueCounts(allIssues: Issue[]) {
}
return { status, priority, assignee, creator, noAssignee, project, noProject, label, property };
- }, [allIssues]);
+ }, [allIssues, serverFacets]);
}
// ---------------------------------------------------------------------------
@@ -756,6 +800,8 @@ export function IssuesHeader({
onDateFilterChange,
isRefreshing = false,
facetCountsExact = true,
+ tableFacetCounts,
+ onTableFacetChange,
}: {
scopedIssues: Issue[];
/** The rows the agents-working filter would leave on screen — undefined
@@ -768,6 +814,8 @@ export function IssuesHeader({
isRefreshing?: boolean;
/** See IssueDisplayControls.facetCountsExact. */
facetCountsExact?: boolean;
+ tableFacetCounts?: IssueTableFacetsResponse;
+ onTableFacetChange?: (facet: IssueTableFacetSpec | null) => void;
}) {
const { t } = useT("issues");
const scope = useIssuesScopeStore((s) => s.scope);
@@ -862,6 +910,8 @@ export function IssuesHeader({
dateFilter={dateFilter}
onDateFilterChange={onDateFilterChange}
facetCountsExact={facetCountsExact}
+ tableFacetCounts={tableFacetCounts}
+ onTableFacetChange={onTableFacetChange}
/>
<ViewRefreshIndicator active={isRefreshing} />
</div>
@@ -877,6 +927,8 @@ export function IssueDisplayControls({
dateFilter = null,
onDateFilterChange,
facetCountsExact = true,
+ tableFacetCounts,
+ onTableFacetChange,
}: {
scopedIssues: Issue[];
hideViewToggle?: boolean;
@@ -887,16 +939,17 @@ export function IssueDisplayControls({
// fall back to List if the option were exposed there. Keep Gantt opt-in.
allowGantt?: boolean;
/**
- * Whether `scopedIssues` covers the surface's full window. The table's
- * offset pagination hands us only the loaded pages — presenting counts
- * derived from a partial window as per-option totals under-reports
- * (round-2 review P2#3), so the badges are suppressed until the window is
- * complete. Filter OPTIONS are unaffected; they come from the
- * member/agent/project/label directories.
+ * Whether `scopedIssues` covers the surface's full window. Table does not
+ * pass loaded branch rows here; it supplies `tableFacetCounts` from the
+ * backend instead, so badges remain exact without downloading all issues.
*/
facetCountsExact?: boolean;
+ tableFacetCounts?: IssueTableFacetsResponse;
+ onTableFacetChange?: (facet: IssueTableFacetSpec | null) => void;
}) {
const { t } = useT("issues");
+ const [tableGroupMenuOpen, setTableGroupMenuOpen] = useState(false);
+ const [viewMenuOpen, setViewMenuOpen] = useState(false);
const viewMode = useViewStore((s) => s.viewMode);
const statusFilters = useViewStore((s) => s.statusFilters);
const priorityFilters = useViewStore((s) => s.priorityFilters);
@@ -913,7 +966,6 @@ export function IssueDisplayControls({
const grouping = useViewStore((s) => s.grouping);
const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);
const cardProperties = useViewStore((s) => s.cardProperties);
- const tableColumns = useViewStore((s) => s.tableColumns);
const tableGrouping = useViewStore((s) => s.tableGrouping ?? "none");
const tableHierarchy = useViewStore((s) => s.tableHierarchy ?? true);
const showSubIssues = useViewStore((s) => s.showSubIssues);
@@ -944,17 +996,14 @@ export function IssueDisplayControls({
const tableGroupableProperties = useMemo(
() =>
workspaceProperties.filter((p) =>
- ["select", "multi_select", "checkbox"].includes(p.type),
+ ["select", "checkbox"].includes(p.type),
),
[workspaceProperties],
);
- const visibleTableColumns = useMemo(
- () => new Set(tableColumns.map((column) => column.key)),
- [tableColumns],
- );
const counts = useIssueCounts(
facetCountsExact ? scopedIssues : NO_COUNT_ISSUES,
+ tableFacetCounts,
);
const showDateFilter = !!onDateFilterChange;
@@ -1048,7 +1097,11 @@ export function IssueDisplayControls({
return (
<div className="flex shrink-0 items-center gap-1">
{/* Filter */}
- <DropdownMenu>
+ <DropdownMenu
+ onOpenChange={(open) => {
+ if (!open) onTableFacetChange?.(null);
+ }}
+ >
<Tooltip>
<DropdownMenuTrigger
render={
@@ -1072,22 +1125,6 @@ export function IssueDisplayControls({
{hasActiveFilters && (
<span className="tabular-nums md:hidden">{activeFilterCount}</span>
)}
- {hasActiveFilters && (
- <span
- role="button"
- tabIndex={-1}
- className="-mr-1 ml-0.5 hidden rounded-sm p-0.5 hover:bg-white/20 md:inline-flex"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- act.clearFilters();
- onDateFilterChange?.(null);
- }}
- onPointerDown={(e) => e.stopPropagation()}
- >
- <X className="size-3" />
- </span>
- )}
</Button>
}
/>
@@ -1097,7 +1134,11 @@ export function IssueDisplayControls({
</Tooltip>
<DropdownMenuContent align="end" className="w-auto">
{/* Status */}
- <DropdownMenuSub>
+ <DropdownMenuSub
+ onOpenChange={(open) =>
+ onTableFacetChange?.(open ? { kind: "status" } : null)
+ }
+ >
<DropdownMenuSubTrigger>
<CircleDot className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_status)}</span>
@@ -1133,7 +1174,11 @@ export function IssueDisplayControls({
</DropdownMenuSub>
{/* Priority */}
- <DropdownMenuSub>
+ <DropdownMenuSub
+ onOpenChange={(open) =>
+ onTableFacetChange?.(open ? { kind: "priority" } : null)
+ }
+ >
<DropdownMenuSubTrigger>
<SignalHigh className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_priority)}</span>
@@ -1189,7 +1234,11 @@ export function IssueDisplayControls({
)}
{/* Assignee */}
- <DropdownMenuSub>
+ <DropdownMenuSub
+ onOpenChange={(open) =>
+ onTableFacetChange?.(open ? { kind: "assignee" } : null)
+ }
+ >
<DropdownMenuSubTrigger>
<User className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_assignee)}</span>
@@ -1213,7 +1262,11 @@ export function IssueDisplayControls({
</DropdownMenuSub>
{/* Creator */}
- <DropdownMenuSub>
+ <DropdownMenuSub
+ onOpenChange={(open) =>
+ onTableFacetChange?.(open ? { kind: "creator" } : null)
+ }
+ >
<DropdownMenuSubTrigger>
<UserPen className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_creator)}</span>
@@ -1234,7 +1287,11 @@ export function IssueDisplayControls({
</DropdownMenuSub>
{/* Project */}
- <DropdownMenuSub>
+ <DropdownMenuSub
+ onOpenChange={(open) =>
+ onTableFacetChange?.(open ? { kind: "project" } : null)
+ }
+ >
<DropdownMenuSubTrigger>
<FolderKanban className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_project)}</span>
@@ -1257,7 +1314,11 @@ export function IssueDisplayControls({
</DropdownMenuSub>
{/* Label */}
- <DropdownMenuSub>
+ <DropdownMenuSub
+ onOpenChange={(open) =>
+ onTableFacetChange?.(open ? { kind: "label" } : null)
+ }
+ >
<DropdownMenuSubTrigger>
<Tag className="size-3.5" />
<span className="flex-1">{t(($) => $.filters.section_label)}</span>
@@ -1281,7 +1342,16 @@ export function IssueDisplayControls({
{filterableProperties.map((property) => {
const selected = propertyFilters[property.id] ?? [];
return (
- <DropdownMenuSub key={property.id}>
+ <DropdownMenuSub
+ key={property.id}
+ onOpenChange={(open) =>
+ onTableFacetChange?.(
+ open
+ ? { kind: "property", property_id: property.id }
+ : null,
+ )
+ }
+ >
<DropdownMenuSubTrigger>
{property.icon ? (
<PropertyIcon property={property} className="size-3.5 text-xs" />
@@ -1324,6 +1394,108 @@ export function IssueDisplayControls({
</DropdownMenuContent>
</DropdownMenu>
+ {hasActiveFilters && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.filters.reset)}
+ onClick={() => {
+ act.clearFilters();
+ onDateFilterChange?.(null);
+ }}
+ className="hidden text-muted-foreground md:inline-flex"
+ >
+ <X className="size-3.5" />
+ </Button>
+ }
+ />
+ <TooltipContent side="bottom">
+ {t(($) => $.filters.reset)}
+ </TooltipContent>
+ </Tooltip>
+ )}
+
+ {viewMode === "table" && (
+ <DropdownMenu
+ open={tableGroupMenuOpen}
+ onOpenChange={setTableGroupMenuOpen}
+ >
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ className={controlButtonClass}
+ >
+ <Rows3 className="size-3.5" />
+ <span className="hidden md:inline">
+ {effectiveTableGrouping === "none"
+ ? t(($) => $.table.group_label)
+ : t(($) => $.table.group_active, {
+ group: tableGroupingLabel,
+ })}
+ </span>
+ <ChevronDown className="size-3 text-muted-foreground" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-auto min-w-48">
+ <DropdownMenuRadioGroup
+ value={effectiveTableGrouping}
+ onValueChange={(value) => {
+ act.setTableGrouping(value as TableGrouping);
+ setTableGroupMenuOpen(false);
+ }}
+ >
+ <DropdownMenuRadioItem value="none">
+ {t(($) => $.table.group_none)}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="status">
+ {t(($) => $.table.columns.status)}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="assignee">
+ {t(($) => $.table.columns.assignee)}
+ </DropdownMenuRadioItem>
+ {tableGroupableProperties.map((property) => (
+ <DropdownMenuRadioItem
+ key={property.id}
+ value={`property:${property.id}`}
+ >
+ <PropertyIcon
+ property={property}
+ className="size-3.5 text-xs"
+ />
+ <span>{property.name}</span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+
+ {viewMode === "table" && (
+ <TableColumnPicker
+ properties={workspaceProperties}
+ trigger={
+ <Button
+ variant="outline"
+ size="sm"
+ className={controlButtonClass}
+ >
+ <Columns3 className="size-3.5" />
+ <span className="hidden md:inline">
+ {t(($) => $.table.columns.section)}
+ </span>
+ <ChevronDown className="size-3 text-muted-foreground" />
+ </Button>
+ }
+ />
+ )}
+
{/* Display settings */}
<Popover>
<Tooltip>
@@ -1433,55 +1605,6 @@ export function IssueDisplayControls({
onCheckedChange={() => act.toggleTableHierarchy()}
/>
</label>
- <div className="mt-3">
- <span className="text-xs font-medium text-muted-foreground">
- {t(($) => $.table.group_label)}
- </span>
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="outline"
- size="sm"
- className="mt-1.5 w-full justify-between text-xs"
- >
- {tableGroupingLabel}
- <ChevronDown className="size-3 text-muted-foreground" />
- </Button>
- }
- />
- <DropdownMenuContent align="start" className="w-auto min-w-48">
- <DropdownMenuRadioGroup
- value={effectiveTableGrouping}
- onValueChange={(value) =>
- act.setTableGrouping(value as TableGrouping)
- }
- >
- <DropdownMenuRadioItem value="none">
- {t(($) => $.table.group_none)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="status">
- {t(($) => $.table.columns.status)}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem value="assignee">
- {t(($) => $.table.columns.assignee)}
- </DropdownMenuRadioItem>
- {tableGroupableProperties.map((property) => (
- <DropdownMenuRadioItem
- key={property.id}
- value={`property:${property.id}`}
- >
- <PropertyIcon
- property={property}
- className="size-3.5 text-xs"
- />
- <span>{property.name}</span>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
</div>
)}
@@ -1547,71 +1670,7 @@ export function IssueDisplayControls({
/>
</label>
- {viewMode === "table" ? (
- <div className="max-h-80 overflow-y-auto px-3 py-2.5">
- <span className="text-xs font-medium text-muted-foreground">
- {t(($) => $.table.columns.section)}
- </span>
- <p className="mt-2 text-xs text-muted-foreground">
- {t(($) => $.table.columns.system_section)}
- </p>
- <div className="mt-1.5 space-y-2">
- {TABLE_SYSTEM_COLUMNS.map((key) => (
- <label
- key={key}
- className={
- key === "title"
- ? "flex items-center justify-between"
- : "flex cursor-pointer items-center justify-between"
- }
- >
- <span className="text-sm">
- {t(($) => $.table.columns[key])}
- </span>
- <Switch
- size="sm"
- checked={visibleTableColumns.has(key)}
- disabled={key === "title"}
- onCheckedChange={() => act.toggleTableColumn(key)}
- />
- </label>
- ))}
- </div>
- {workspaceProperties.length > 0 && (
- <>
- <p className="mt-3 text-xs text-muted-foreground">
- {t(($) => $.table.columns.property_section)}
- </p>
- <div className="mt-1.5 space-y-2">
- {workspaceProperties.map((property) => {
- const key = `property:${property.id}` as const;
- return (
- <label
- key={property.id}
- className="flex cursor-pointer items-center justify-between gap-3"
- >
- <span className="flex min-w-0 items-center gap-1.5 truncate text-sm">
- <PropertyIcon
- property={property}
- className="size-3.5 text-xs"
- />
- <span className="truncate">{property.name}</span>
- </span>
- <Switch
- size="sm"
- checked={visibleTableColumns.has(key)}
- onCheckedChange={() =>
- act.toggleTableColumn(key)
- }
- />
- </label>
- );
- })}
- </div>
- </>
- )}
- </div>
- ) : (
+ {viewMode !== "table" && (
<div className="px-3 py-2.5">
<span className="text-xs font-medium text-muted-foreground">
{t(($) => $.display.card_properties_section)}
@@ -1659,7 +1718,7 @@ export function IssueDisplayControls({
this surface doesn't render Gantt, fall back to "list" so the
trigger icon matches what's actually on screen. */}
{!hideViewToggle && (
- <DropdownMenu>
+ <DropdownMenu open={viewMenuOpen} onOpenChange={setViewMenuOpen}>
<Tooltip>
<DropdownMenuTrigger
render={
@@ -1709,7 +1768,13 @@ export function IssueDisplayControls({
<DropdownMenuGroup>
<DropdownMenuLabel>{t(($) => $.view.section)}</DropdownMenuLabel>
</DropdownMenuGroup>
- <DropdownMenuRadioGroup value={viewMode} onValueChange={(v) => act.setViewMode(v as ViewMode)}>
+ <DropdownMenuRadioGroup
+ value={viewMode}
+ onValueChange={(v) => {
+ act.setViewMode(v as ViewMode);
+ setViewMenuOpen(false);
+ }}
+ >
<DropdownMenuRadioItem value="board">
<Columns3 />
{t(($) => $.view.board)}
diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsx
index 18070a6427..919638b7be 100644
--- a/packages/views/issues/components/issues-page.tsx
+++ b/packages/views/issues/components/issues-page.tsx
@@ -1,7 +1,11 @@
"use client";
import { ListTodo } from "lucide-react";
-import type { Issue } from "@multica/core/types";
+import type {
+ Issue,
+ IssueTableFacetSpec,
+ IssueTableFacetsResponse,
+} from "@multica/core/types";
import { useIssuesScopeStore } from "@multica/core/issues/stores/issues-scope-store";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
import { PageHeader } from "../../layout/page-header";
@@ -14,11 +18,15 @@ function IssuesSurfaceHeader({
workingIssues,
isRefreshing,
facetCountsExact,
+ tableFacetCounts,
+ onTableFacetChange,
}: {
issues: Issue[];
workingIssues: Issue[] | undefined;
isRefreshing: boolean;
facetCountsExact: boolean;
+ tableFacetCounts?: IssueTableFacetsResponse;
+ onTableFacetChange: (facet: IssueTableFacetSpec | null) => void;
}) {
const dateFilter = useViewStore((s) => s.dateFilter);
const setDateFilter = useViewStore((s) => s.setDateFilter);
@@ -31,6 +39,8 @@ function IssuesSurfaceHeader({
onDateFilterChange={setDateFilter}
isRefreshing={isRefreshing}
facetCountsExact={facetCountsExact}
+ tableFacetCounts={tableFacetCounts}
+ onTableFacetChange={onTableFacetChange}
/>
);
}
@@ -55,9 +65,9 @@ export function IssuesPage() {
issues={controller.surfaceIssues}
workingIssues={workingIssues}
isRefreshing={controller.isRefreshing}
- facetCountsExact={
- !(controller.viewMode === "table" && controller.hasNextFlatPage)
- }
+ facetCountsExact={controller.viewMode !== "table"}
+ tableFacetCounts={controller.tableFacetCounts}
+ onTableFacetChange={controller.setActiveTableFacet}
/>
)}
renderEmpty={() => (
diff --git a/packages/views/issues/components/table-view-editing.test.tsx b/packages/views/issues/components/table-view-editing.test.tsx
index 14a13ba5b2..40bef2d63d 100644
--- a/packages/views/issues/components/table-view-editing.test.tsx
+++ b/packages/views/issues/components/table-view-editing.test.tsx
@@ -9,14 +9,26 @@
* TYPES, so React remounted every cell and the just-opened picker closed.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cleanup, render, screen, within } from "@testing-library/react";
+import {
+ act,
+ cleanup,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { setApiInstance } from "@multica/core/api";
import type { ApiClient } from "@multica/core/api/client";
+import { issueKeys } from "@multica/core/issues/queries";
import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
import { getIssueSurfaceViewStore } from "@multica/core/issues/stores/surface-view-store";
-import type { Issue } from "@multica/core/types";
+import type {
+ Issue,
+ IssueTableQuerySpec,
+ IssueTableRowsResponse,
+} from "@multica/core/types";
import { renderWithI18n } from "../../test/i18n";
import { IssueSurfaceSelectionProvider } from "../surface/selection-context";
import type { IssueSurfaceSelection } from "../surface/selection-context";
@@ -142,13 +154,19 @@ const selection: IssueSurfaceSelection = {
clear: () => {},
};
+const serverQuery: IssueTableQuerySpec = {
+ scope: { kind: "workspace" },
+ filters: {},
+ sort: { field: "position", direction: "asc" },
+};
+
+let serverIssues: Issue[] = [];
+
function Harness({
- issues,
childProgressMap,
surfaceKey,
onCreateIssue = () => {},
}: {
- issues: Issue[];
childProgressMap: Map<string, ChildProgress>;
surfaceKey: string;
onCreateIssue?: (defaults: IssueCreateDefaults) => void;
@@ -157,17 +175,13 @@ function Harness({
<ViewStoreProvider store={getIssueSurfaceViewStore(surfaceKey)}>
<IssueSurfaceSelectionProvider selection={selection}>
<TableView
- issues={issues}
+ serverQuery={serverQuery}
childProgressMap={childProgressMap}
- fetchNextPage={() => Promise.resolve()}
- hasNextPage={false}
- isFetchingNextPage={false}
- windowError={false}
- total={issues.length}
search=""
onSearchChange={() => {}}
+ onLoadedIssuesChange={() => {}}
onCreateIssue={onCreateIssue}
- exportIssues={() => Promise.resolve(issues)}
+ exportIssues={() => Promise.resolve(serverIssues)}
resolveExportLookups={() =>
Promise.resolve({
projectMap: new Map(),
@@ -202,6 +216,18 @@ describe("TableView cell editors under data refresh", () => {
listAgents: async () => [],
listSquads: async () => [],
getAssigneeFrequency: async () => [],
+ listIssueTableRows: async () => ({
+ query_fingerprint: "test",
+ group_key: null,
+ parent_id: null,
+ total: serverIssues.length,
+ rows: serverIssues.map((issue) => ({
+ issue,
+ direct_child_count: 0,
+ })),
+ branch_total: serverIssues.length,
+ next_cursor: null,
+ }),
} as unknown as ApiClient);
});
@@ -219,13 +245,13 @@ describe("TableView cell editors under data refresh", () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const issueA = makeIssue("a", "Alpha task", "todo");
const issueB = makeIssue("b", "Beta task", "in_progress");
+ serverIssues = [issueA, issueB];
const progress1 = new Map<string, ChildProgress>();
const surfaceKey = `test-surface-${Math.floor(Math.random() * 1e9)}`;
const view = renderWithI18n(
<QueryClientProvider client={queryClient}>
<Harness
- issues={[issueA, issueB]}
childProgressMap={progress1}
surfaceKey={surfaceKey}
/>
@@ -234,6 +260,7 @@ describe("TableView cell editors under data refresh", () => {
const identifiers = () =>
screen.getAllByText(/^MUL-/).map((node) => node.textContent);
+ await screen.findByText("MUL-a");
expect(identifiers()).toEqual(["MUL-a", "MUL-b"]);
// Open the status picker on row A: its cell trigger shows "Todo".
@@ -246,20 +273,39 @@ describe("TableView cell editors under data refresh", () => {
// childProgressMap. The popup must stay open and the structure must hold
// (frozen order) so the anchor row cannot move away mid-interaction.
const refreshedA = { ...issueA, title: "Alpha task (updated)" };
+ serverIssues = [issueB, refreshedA];
view.rerender(
<QueryClientProvider client={queryClient}>
<Harness
- issues={[issueB, refreshedA]}
childProgressMap={new Map<string, ChildProgress>()}
surfaceKey={surfaceKey}
/>
</QueryClientProvider>,
);
+ act(() => {
+ queryClient.setQueriesData<IssueTableRowsResponse>(
+ { queryKey: issueKeys.tableAll("ws-1") },
+ (previous) =>
+ previous
+ ? {
+ ...previous,
+ total: serverIssues.length,
+ branch_total: serverIssues.length,
+ rows: serverIssues.map((issue) => ({
+ issue,
+ direct_child_count: 0,
+ })),
+ }
+ : previous,
+ );
+ });
- expect(screen.getByRole("button", { name: /Backlog/ })).toBeTruthy();
- expect(identifiers()).toEqual(["MUL-a", "MUL-b"]);
- // …while the VALUES inside the frozen rows keep tracking the live data.
- expect(screen.getByText("Alpha task (updated)")).toBeTruthy();
+ await waitFor(() => {
+ expect(screen.getByRole("button", { name: /Backlog/ })).toBeTruthy();
+ expect(identifiers()).toEqual(["MUL-a", "MUL-b"]);
+ // …while the VALUES inside the frozen rows keep tracking live data.
+ expect(screen.getByText("Alpha task (updated)")).toBeTruthy();
+ });
// Selecting a value closes the editor; the deferred live order applies.
await user.click(screen.getByRole("button", { name: /Backlog/ }));
@@ -274,11 +320,11 @@ describe("TableView cell editors under data refresh", () => {
...makeIssue("a", "Alpha task", "todo"),
project_id: "project-1",
};
+ serverIssues = [issue];
renderWithI18n(
<QueryClientProvider client={queryClient}>
<Harness
- issues={[issue]}
childProgressMap={new Map()}
surfaceKey={`test-create-sub-issue-${Math.floor(Math.random() * 1e9)}`}
onCreateIssue={onCreateIssue}
@@ -286,7 +332,7 @@ describe("TableView cell editors under data refresh", () => {
</QueryClientProvider>,
);
- const row = screen.getByText("MUL-a").closest("tr")!;
+ const row = (await screen.findByText("MUL-a")).closest("tr")!;
await user.click(
within(row).getByRole("button", { name: "Create sub-issue" }),
);
@@ -300,11 +346,11 @@ describe("TableView cell editors under data refresh", () => {
it("opens title and row clicks in a foreground Desktop tab", async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
+ serverIssues = [makeIssue("a", "Alpha task", "todo")];
renderWithI18n(
<QueryClientProvider client={queryClient}>
<Harness
- issues={[makeIssue("a", "Alpha task", "todo")]}
childProgressMap={new Map()}
surfaceKey={`test-new-tab-${Math.floor(Math.random() * 1e9)}`}
/>
@@ -335,11 +381,11 @@ describe("TableView cell editors under data refresh", () => {
const windowOpen = vi.fn();
vi.stubGlobal("open", windowOpen);
navigationState.hasOpenInNewTab = false;
+ serverIssues = [makeIssue("a", "Alpha task", "todo")];
renderWithI18n(
<QueryClientProvider client={queryClient}>
<Harness
- issues={[makeIssue("a", "Alpha task", "todo")]}
childProgressMap={new Map()}
surfaceKey={`test-browser-tab-${Math.floor(Math.random() * 1e9)}`}
/>
diff --git a/packages/views/issues/components/table-view-model.test.ts b/packages/views/issues/components/table-view-model.test.ts
index 202b81b0d3..f60126b432 100644
--- a/packages/views/issues/components/table-view-model.test.ts
+++ b/packages/views/issues/components/table-view-model.test.ts
@@ -1,14 +1,10 @@
import { describe, expect, it } from "vitest";
-import type { Issue, IssueProperty } from "@multica/core/types";
+import type { Issue } from "@multica/core/types";
import {
- TABLE_STRUCTURE_MAX_WINDOW,
buildIssueTableCsv,
- buildIssueTableRows,
calculateIssueTableColumn,
getIssueTableSelectionRange,
- isTableStructureSuspended,
refreshFrozenTableRows,
- shouldAutoLoadNextWindowPage,
type IssueTableDisplayRow,
} from "./table-view-model";
@@ -42,205 +38,6 @@ function makeIssue(id: string, overrides: Partial<Issue> = {}): Issue {
};
}
-function makeProperty(
- id: string,
- type: string,
- options: IssueProperty["config"]["options"] = [],
-): IssueProperty {
- return {
- id,
- workspace_id: "ws-1",
- name: id,
- type,
- config: { options },
- position: 0,
- archived: false,
- created_at: "2026-01-01T00:00:00Z",
- updated_at: "2026-01-01T00:00:00Z",
- };
-}
-
-const baseOptions = {
- grouping: "none" as const,
- properties: [] as IssueProperty[],
- collapsedGroups: new Set<string>(),
- collapsedParents: new Set<string>(),
- hierarchy: true,
- windowComplete: true,
- getActorName: (_type: string, id: string) => id,
- getStatusLabel: (status: Issue["status"]) => status,
- noValueLabel: "No value",
- unassignedLabel: "Unassigned",
- trueLabel: "Yes",
- falseLabel: "No",
-};
-
-describe("isTableStructureSuspended", () => {
- it("suspends structure only above the ceiling; unknown totals do not suspend", () => {
- expect(isTableStructureSuspended(0)).toBe(false);
- expect(isTableStructureSuspended(TABLE_STRUCTURE_MAX_WINDOW)).toBe(false);
- expect(isTableStructureSuspended(TABLE_STRUCTURE_MAX_WINDOW + 1)).toBe(true);
- });
-});
-
-describe("shouldAutoLoadNextWindowPage", () => {
- const base = {
- windowWanted: true,
- total: 500,
- loadedCount: 100,
- hasNextPage: true,
- isFetchingNextPage: false,
- hasError: false,
- };
-
- it("advances only while structure is wanted, healthy, and under the ceiling", () => {
- expect(shouldAutoLoadNextWindowPage(base)).toBe(true);
- expect(
- shouldAutoLoadNextWindowPage({ ...base, windowWanted: false }),
- ).toBe(false);
- expect(shouldAutoLoadNextWindowPage({ ...base, hasNextPage: false })).toBe(
- false,
- );
- expect(
- shouldAutoLoadNextWindowPage({ ...base, isFetchingNextPage: true }),
- ).toBe(false);
- });
-
- it("stops permanently on a fetch error instead of refiring (request storm)", () => {
- // After a failed page fetch, hasNextPage stays true and
- // isFetchingNextPage returns to false — exactly the state that used to
- // re-trigger the loop forever.
- expect(shouldAutoLoadNextWindowPage({ ...base, hasError: true })).toBe(
- false,
- );
- });
-
- it("hard-stops at the ceiling even when a stale total says otherwise", () => {
- // page 1 reported total=900 (under the ceiling) but the window has since
- // grown to 50,000: the fresh total suspends...
- expect(
- shouldAutoLoadNextWindowPage({ ...base, total: 50_000 }),
- ).toBe(false);
- // ...and independently of ANY reported total, the loaded count is an
- // absolute stop at the ceiling — page 3 must never be requested once
- // 1,000 rows are in memory.
- expect(
- shouldAutoLoadNextWindowPage({
- ...base,
- total: 900,
- loadedCount: TABLE_STRUCTURE_MAX_WINDOW,
- }),
- ).toBe(false);
- });
-});
-
-describe("buildIssueTableRows", () => {
- it("renders a parent before its children and honors parent collapse", () => {
- const parent = makeIssue("issue-1");
- const child = makeIssue("issue-2", { parent_issue_id: parent.id });
-
- const expanded = buildIssueTableRows([child, parent], baseOptions);
- expect(
- expanded.map((row) =>
- row.kind === "issue" ? [row.issue.id, row.depth] : row.key,
- ),
- ).toEqual([
- ["issue-1", 0],
- ["issue-2", 1],
- ]);
-
- const collapsed = buildIssueTableRows([child, parent], {
- ...baseOptions,
- collapsedParents: new Set([parent.id]),
- });
- expect(collapsed.map((row) => row.key)).toEqual([parent.id]);
- });
-
- it("suspends hierarchy and parent-based grouping while the window is incomplete", () => {
- const parent = makeIssue("issue-1", { status: "done" });
- const child = makeIssue("issue-2", {
- parent_issue_id: parent.id,
- status: "todo",
- });
-
- // Nesting derived from loaded pages re-parents rows as later pages
- // arrive; rows must stay in flat sort order until the window completes.
- const flat = buildIssueTableRows([child, parent], {
- ...baseOptions,
- windowComplete: false,
- });
- expect(
- flat.map((row) =>
- row.kind === "issue" ? [row.issue.id, row.depth] : row.key,
- ),
- ).toEqual([
- ["issue-2", 0],
- ["issue-1", 0],
- ]);
-
- // Grouped: the child buckets by its OWN status instead of climbing to
- // the parent, so its group cannot change when the parent pages in.
- const grouped = buildIssueTableRows([child, parent], {
- ...baseOptions,
- grouping: "status",
- windowComplete: false,
- });
- expect(grouped.map((row) => row.key)).toEqual([
- "status:todo",
- child.id,
- "status:done",
- parent.id,
- ]);
- });
-
- it("keeps a hierarchy together under the parent custom-property group", () => {
- const environment = makeProperty("environment", "select", [
- { id: "web", name: "Web", color: "#000000" },
- { id: "mobile", name: "Mobile", color: "#ffffff" },
- ]);
- const parent = makeIssue("issue-1", {
- properties: { environment: "web" },
- });
- const child = makeIssue("issue-2", {
- parent_issue_id: parent.id,
- properties: { environment: "mobile" },
- });
-
- const rows = buildIssueTableRows([parent, child], {
- ...baseOptions,
- grouping: "property:environment",
- properties: [environment],
- });
-
- expect(rows[0]).toMatchObject({ kind: "group", label: "Web", count: 2 });
- expect(rows.map((row) => row.key)).toEqual([
- "property:environment:web",
- parent.id,
- child.id,
- ]);
- });
-
- it("orders status groups canonically and honors group collapse", () => {
- const rows = buildIssueTableRows(
- [
- makeIssue("issue-1", { status: "done" }),
- makeIssue("issue-2", { status: "backlog" }),
- ],
- {
- ...baseOptions,
- grouping: "status",
- collapsedGroups: new Set(["status:backlog"]),
- },
- );
-
- expect(rows.map((row) => row.key)).toEqual([
- "status:backlog",
- "status:done",
- "issue-1",
- ]);
- });
-});
-
describe("getIssueTableSelectionRange", () => {
const issueIds = ["issue-1", "issue-2", "issue-3", "issue-4"];
@@ -278,14 +75,31 @@ describe("refreshFrozenTableRows", () => {
const staleB = makeIssue("issue-2", { title: "Stale B" });
const snapshot: IssueTableDisplayRow[] = [
groupRow,
- { kind: "issue", key: staleA.id, issue: staleA, depth: 0, hasChildren: true, collapsed: false },
- { kind: "issue", key: staleB.id, issue: staleB, depth: 1, hasChildren: false, collapsed: false },
+ {
+ kind: "issue",
+ key: staleA.id,
+ issue: staleA,
+ depth: 0,
+ hasChildren: true,
+ collapsed: false,
+ },
+ {
+ kind: "issue",
+ key: staleB.id,
+ issue: staleB,
+ depth: 1,
+ hasChildren: false,
+ collapsed: false,
+ },
];
const liveA = makeIssue("issue-1", { title: "Live A" });
const refreshed = refreshFrozenTableRows(
snapshot,
- new Map([[liveA.id, liveA], [staleB.id, staleB]]),
+ new Map([
+ [liveA.id, liveA],
+ [staleB.id, staleB],
+ ]),
);
expect(refreshed.map((row) => row.key)).toEqual([
@@ -298,7 +112,6 @@ describe("refreshFrozenTableRows", () => {
depth: 0,
hasChildren: true,
});
- // Identical live object → the snapshot row is reused untouched.
expect(refreshed[2]).toBe(snapshot[2]);
expect(refreshed[0]).toBe(groupRow);
});
@@ -306,7 +119,14 @@ describe("refreshFrozenTableRows", () => {
it("keeps the stale issue when it vanished from the live window", () => {
const stale = makeIssue("issue-9", { title: "Deleted remotely" });
const snapshot: IssueTableDisplayRow[] = [
- { kind: "issue", key: stale.id, issue: stale, depth: 0, hasChildren: false, collapsed: false },
+ {
+ kind: "issue",
+ key: stale.id,
+ issue: stale,
+ depth: 0,
+ hasChildren: false,
+ collapsed: false,
+ },
];
const refreshed = refreshFrozenTableRows(snapshot, new Map());
diff --git a/packages/views/issues/components/table-view-model.ts b/packages/views/issues/components/table-view-model.ts
index f211652e34..ca6bb5bbf2 100644
--- a/packages/views/issues/components/table-view-model.ts
+++ b/packages/views/issues/components/table-view-model.ts
@@ -1,69 +1,21 @@
-import { ALL_STATUSES } from "@multica/core/issues/config";
import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
import type {
TableCalculation,
TableColumnKey,
- TableGrouping,
} from "@multica/core/issues/stores/view-store";
import type {
Issue,
- IssueProperty,
IssuePropertyValue,
} from "@multica/core/types";
-/**
- * Ceiling for the whole-window structure features (grouping, hierarchy).
- * Both are only truthful over a COMPLETE window, and completing the window
- * means materializing every offset page — at 100 rows/page an unbounded
- * materialize would issue total/100 sequential GETs and pin every entity in
- * memory (grouping is persisted view state, so it would re-run on every
- * visit). Below the ceiling the table auto-loads the ~10 remaining pages;
- * above it, structure features suspend with an explicit notice instead of
- * triggering an unbounded download.
- */
-export const TABLE_STRUCTURE_MAX_WINDOW = 1000;
-
-/** True when the window is too large for grouping/hierarchy — see
- * TABLE_STRUCTURE_MAX_WINDOW. `total` is the server-reported window size
- * (0 while unknown, which must NOT suspend: an unknown window is handled
- * by the windowComplete gate, not this ceiling). */
-export function isTableStructureSuspended(total: number): boolean {
- return total > TABLE_STRUCTURE_MAX_WINDOW;
-}
-
-/**
- * Single decision point for EVERY auto-pagination loop over a table window —
- * the structure materialization loop and the working (ids-facet) window
- * loop. The two share the main table's query cache when the agents-working
- * filter is on, so a loop that skipped these gates would re-open the very
- * ceiling the other just enforced (round-5 review P1). Every gate exists
- * because its absence was a concrete failure mode:
- *
- * - `hasError`: a page that keeps failing leaves `hasNextPage` true and
- * `isFetchingNextPage` false after each attempt, so an ungated effect
- * refires forever — a silent request storm
- * (round-4 review P1#1). Terminal errors stop the loop; resuming is an
- * explicit user Retry.
- * - `loadedCount`: an ABSOLUTE stop at the ceiling, independent of any
- * server-reported total. The suspension check alone is not a hard limit
- * when totals drift between pages — a stale small page-1 total kept the
- * ceiling open while pagination advanced toward a much larger real window
- * (round-4 review P1#2).
- * - `total` must be the FRESHEST page's total (pagination itself advances on
- * the latest page), for the same reason.
- */
-export function shouldAutoLoadNextWindowPage(input: {
- windowWanted: boolean;
- total: number;
- loadedCount: number;
- hasNextPage: boolean;
- isFetchingNextPage: boolean;
- hasError: boolean;
-}): boolean {
- if (!input.windowWanted || input.hasError) return false;
- if (isTableStructureSuspended(input.total)) return false;
- if (input.loadedCount >= TABLE_STRUCTURE_MAX_WINDOW) return false;
- return input.hasNextPage && !input.isFetchingNextPage;
+/** Export must fail closed when paged Table responses cannot prove that the
+ * complete query window was collected. The UI translates this marker instead
+ * of exposing a protocol detail to users. */
+export class IssueTableExportIntegrityError extends Error {
+ constructor() {
+ super("Table export response was incomplete");
+ this.name = "IssueTableExportIntegrityError";
+ }
}
export type IssueTableDisplayRow =
@@ -81,33 +33,16 @@ export type IssueTableDisplayRow =
depth: number;
hasChildren: boolean;
collapsed: boolean;
+ }
+ | {
+ kind: "load_more";
+ key: string;
+ label: string;
+ loading: boolean;
+ autoLoad?: boolean;
+ onLoad?: () => void;
};
-export interface BuildIssueTableRowsOptions {
- grouping: TableGrouping;
- properties: IssueProperty[];
- collapsedGroups: ReadonlySet<string>;
- collapsedParents: ReadonlySet<string>;
- hierarchy: boolean;
- /**
- * Whether `issues` is the FULL window (no unfetched pages). Hierarchy
- * nesting and parent-based group assignment only apply to a complete
- * window: deriving structure from loaded pages re-parents rows as later
- * pages arrive — a child renders as root, then jumps under its parent /
- * into another group mid-scroll (round-2 review P2#3). While incomplete,
- * rows stay in flat sort order and group by their own fields, which is
- * stable under pagination; the tree assembles once, when the data is all
- * there.
- */
- windowComplete: boolean;
- getActorName: (type: string, id: string) => string;
- getStatusLabel: (status: Issue["status"]) => string;
- noValueLabel: string;
- unassignedLabel: string;
- trueLabel: string;
- falseLabel: string;
-}
-
export function getIssueTableSelectionRange(
issueIds: string[],
anchorId: string | null,
@@ -123,213 +58,6 @@ export function getIssueTableSelectionRange(
return issueIds.slice(start, end + 1);
}
-function propertyValueLabel(
- property: IssueProperty | undefined,
- value: IssuePropertyValue | undefined,
- labels: Pick<
- BuildIssueTableRowsOptions,
- "noValueLabel" | "trueLabel" | "falseLabel"
- >,
-) {
- if (!property || value === undefined) return labels.noValueLabel;
- const propertyOptions = property.config.options ?? [];
- if (property.type === "select") {
- return (
- propertyOptions.find((option) => option.id === value)?.name ??
- labels.noValueLabel
- );
- }
- if (property.type === "multi_select") {
- const ids = Array.isArray(value) ? value : [];
- const names = propertyOptions
- .filter((option) => ids.includes(option.id))
- .map((option) => option.name);
- return names.length > 0 ? names.join(", ") : labels.noValueLabel;
- }
- if (property.type === "checkbox") {
- return value === true ? labels.trueLabel : labels.falseLabel;
- }
- return String(value);
-}
-
-function groupDescriptor(
- issue: Issue,
- options: BuildIssueTableRowsOptions,
-) {
- if (options.grouping === "status") {
- return {
- key: `status:${issue.status}`,
- label: options.getStatusLabel(issue.status),
- };
- }
- if (options.grouping === "assignee") {
- if (!issue.assignee_type || !issue.assignee_id) {
- return { key: "assignee:none", label: options.unassignedLabel };
- }
- return {
- key: `assignee:${issue.assignee_type}:${issue.assignee_id}`,
- label: options.getActorName(issue.assignee_type, issue.assignee_id),
- };
- }
- const propertyId = propertyIdFromViewKey(options.grouping);
- if (propertyId) {
- const property = options.properties.find((item) => item.id === propertyId);
- const value = issue.properties[propertyId];
- const label = propertyValueLabel(
- property,
- value,
- options,
- );
- const valueKey = Array.isArray(value)
- ? [...value].sort().join(",")
- : value === undefined
- ? "none"
- : String(value);
- return { key: `property:${propertyId}:${valueKey}`, label };
- }
- return { key: "none", label: "" };
-}
-
-function hierarchyRows(
- issues: Issue[],
- collapsedParents: ReadonlySet<string>,
- hierarchy: boolean,
-) {
- if (!hierarchy) {
- return issues.map<IssueTableDisplayRow>((issue) => ({
- kind: "issue",
- key: issue.id,
- issue,
- depth: 0,
- hasChildren: false,
- collapsed: false,
- }));
- }
-
- const issueIds = new Set(issues.map((issue) => issue.id));
- const children = new Map<string, Issue[]>();
- for (const issue of issues) {
- if (!issue.parent_issue_id || !issueIds.has(issue.parent_issue_id)) continue;
- const siblings = children.get(issue.parent_issue_id) ?? [];
- siblings.push(issue);
- children.set(issue.parent_issue_id, siblings);
- }
- const roots = issues.filter(
- (issue) => !issue.parent_issue_id || !issueIds.has(issue.parent_issue_id),
- );
- const rows: IssueTableDisplayRow[] = [];
- const visited = new Set<string>();
-
- const markHiddenDescendantsVisited = (issue: Issue) => {
- for (const child of children.get(issue.id) ?? []) {
- if (visited.has(child.id)) continue;
- visited.add(child.id);
- markHiddenDescendantsVisited(child);
- }
- };
-
- const visit = (issue: Issue, depth: number) => {
- if (visited.has(issue.id)) return;
- visited.add(issue.id);
- const issueChildren = children.get(issue.id) ?? [];
- const collapsed = collapsedParents.has(issue.id);
- rows.push({
- kind: "issue",
- key: issue.id,
- issue,
- depth,
- hasChildren: issueChildren.length > 0,
- collapsed,
- });
- if (collapsed) {
- // The final orphan/cycle recovery pass below must not resurrect rows
- // intentionally hidden under a collapsed parent.
- markHiddenDescendantsVisited(issue);
- return;
- }
- for (const child of issueChildren) visit(child, depth + 1);
- };
-
- for (const root of roots) visit(root, 0);
- // Cycles and cross-page orphans degrade to top-level rows instead of
- // disappearing from the table.
- for (const issue of issues) visit(issue, 0);
- return rows;
-}
-
-export function buildIssueTableRows(
- issues: Issue[],
- options: BuildIssueTableRowsOptions,
-): IssueTableDisplayRow[] {
- // See BuildIssueTableRowsOptions.windowComplete — parent-derived structure
- // is only trustworthy (and stable) once every page is loaded.
- const applyHierarchy = options.hierarchy && options.windowComplete;
- if (options.grouping === "none") {
- return hierarchyRows(
- issues,
- options.collapsedParents,
- applyHierarchy,
- );
- }
-
- const issueById = new Map(issues.map((issue) => [issue.id, issue]));
- const groupSource = (issue: Issue) => {
- if (!applyHierarchy) return issue;
- let current = issue;
- const seen = new Set<string>();
- while (current.parent_issue_id && !seen.has(current.id)) {
- seen.add(current.id);
- const parent = issueById.get(current.parent_issue_id);
- if (!parent) break;
- current = parent;
- }
- return current;
- };
-
- const groups = new Map<string, { label: string; issues: Issue[] }>();
- for (const issue of issues) {
- const descriptor = groupDescriptor(groupSource(issue), options);
- const group = groups.get(descriptor.key) ?? {
- label: descriptor.label,
- issues: [],
- };
- group.issues.push(issue);
- groups.set(descriptor.key, group);
- }
-
- const entries = [...groups.entries()];
- if (options.grouping === "status") {
- const rank = new Map(
- ALL_STATUSES.map((status, index) => [`status:${status}`, index]),
- );
- entries.sort(
- ([a], [b]) => (rank.get(a) ?? Number.MAX_SAFE_INTEGER) - (rank.get(b) ?? Number.MAX_SAFE_INTEGER),
- );
- }
-
- const rows: IssueTableDisplayRow[] = [];
- for (const [key, group] of entries) {
- const collapsed = options.collapsedGroups.has(key);
- rows.push({
- kind: "group",
- key,
- label: group.label,
- count: group.issues.length,
- collapsed,
- });
- if (!collapsed) {
- rows.push(
- ...hierarchyRows(
- group.issues,
- options.collapsedParents,
- applyHierarchy,
- ),
- );
- }
- }
- return rows;
-}
-
/**
* Refresh the issue objects inside a frozen row snapshot. While a cell editor
* popup is open the table renders a structural snapshot (row order, grouping,
@@ -350,7 +78,6 @@ export function refreshFrozenTableRows(
return live && live !== row.issue ? { ...row, issue: live } : row;
});
}
-
function columnValue(
issue: Issue,
columnKey: TableColumnKey,
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index f27b658b4b..d6d195f3d6 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -63,11 +63,17 @@ import {
} from "@multica/ui/components/ui/dropdown-menu";
import {
TableCell,
- TableFooter,
TableRow,
} from "@multica/ui/components/ui/table";
import { cn } from "@multica/ui/lib/utils";
+import { ApiError } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
+import { ALL_STATUSES } from "@multica/core/issues/config";
+import {
+ issueKeys,
+ issueTableGroupsOptions,
+ issueTableRowPageOptions,
+} from "@multica/core/issues/queries";
import {
TABLE_SYSTEM_COLUMNS,
propertyIdFromViewKey,
@@ -88,10 +94,21 @@ import type {
Issue,
IssueProperty,
IssuePropertyValue,
+ IssueStatus,
+ IssueTableGroupDescriptor,
+ IssueTableGroupSpec,
+ IssueTableQuerySpec,
+ IssueTableRowsResponse,
Project,
UpdateIssueRequest,
} from "@multica/core/types";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ useInfiniteQuery,
+ useQueries,
+ useQuery,
+ useQueryClient,
+ type UseQueryResult,
+} from "@tanstack/react-query";
import { ActorAvatar } from "../../common/actor-avatar";
import { LabelChip } from "../../labels/label-chip";
import { useNavigation } from "../../navigation";
@@ -112,11 +129,9 @@ import {
import { CustomPropertyValueEditor } from "./pickers/custom-property-picker";
import {
buildIssueTableCsv,
- buildIssueTableRows,
getIssueTableSelectionRange,
- isTableStructureSuspended,
+ IssueTableExportIntegrityError,
refreshFrozenTableRows,
- shouldAutoLoadNextWindowPage,
type IssueTableDisplayRow,
} from "./table-view-model";
import type { ChildProgress } from "./list-row";
@@ -126,17 +141,11 @@ const SELECT_COLUMN_ID = "__select";
const ADD_COLUMN_ID = "__add";
type TableViewProps = {
- issues: Issue[];
+ serverQuery: IssueTableQuerySpec;
childProgressMap: Map<string, ChildProgress>;
- fetchNextPage: () => Promise<unknown>;
- hasNextPage: boolean;
- isFetchingNextPage: boolean;
- /** The window query is in error state — page auto-advance (structure loop
- * AND scroll sentinel) must stop and hand control to the explicit Retry. */
- windowError: boolean;
- total: number;
search: string;
onSearchChange: (query: string) => void;
+ onLoadedIssuesChange: (issues: Issue[]) => void;
onCreateIssue: (defaults: IssueCreateDefaults) => void;
exportIssues: () => Promise<Issue[]>;
resolveExportLookups: (needs: {
@@ -148,6 +157,100 @@ type TableViewProps = {
}>;
};
+type ServerBranch = {
+ key: string;
+ groupKey: string | null;
+ parentId: string | null;
+ ancestorIds: string[];
+ cursors: Array<string | null>;
+};
+
+type ServerBranchState = {
+ identity: string;
+ structureIdentity: string;
+ branches: Map<string, ServerBranch>;
+};
+
+type ServerBranchPageTarget = {
+ branch: ServerBranch;
+ cursor: string | null;
+};
+
+type ServerBranchData = {
+ rows: IssueTableRowsResponse["rows"];
+ total: number;
+ nextCursor: string | null;
+ headUpdatedAt: number;
+ headFetching: boolean;
+ loading: boolean;
+ error: boolean;
+ placeholder: boolean;
+};
+
+type LoadedIssueState = {
+ membershipIdentity: string;
+ issues: Map<string, Issue>;
+};
+
+function serverBranchKey(groupKey: string | null, parentId: string | null) {
+ return `${groupKey ?? "ungrouped"}::${parentId ?? "root"}`;
+}
+
+function sameStringArray(left: string[], right: string[]) {
+ return (
+ left.length === right.length &&
+ left.every((value, index) => value === right[index])
+ );
+}
+
+/** Rebase the branch graph synchronously when a query changes.
+ *
+ * Filters/search/sort keep the same group/hierarchy structure, so preserving
+ * branch identities while resetting every cursor to the head lets React Query
+ * show the previous rows during the new request. A real structure change
+ * (group kind or hierarchy) discards incompatible group/parent identities. */
+function rebaseServerBranchState(
+ previous: ServerBranchState,
+ identity: string,
+ structureIdentity: string,
+ usesServerGrouping: boolean,
+): ServerBranchState {
+ if (previous.identity === identity) return previous;
+
+ const branches =
+ previous.structureIdentity === structureIdentity
+ ? new Map(
+ [...previous.branches].map(([key, branch]) => [
+ key,
+ { ...branch, cursors: [null] },
+ ]),
+ )
+ : new Map<string, ServerBranch>();
+
+ if (!usesServerGrouping) {
+ const key = serverBranchKey(null, null);
+ if (!branches.has(key)) {
+ branches.set(key, {
+ key,
+ groupKey: null,
+ parentId: null,
+ ancestorIds: [],
+ cursors: [null],
+ });
+ }
+ }
+
+ return { identity, structureIdentity, branches };
+}
+
+function tableGroupSpec(grouping: string): IssueTableGroupSpec {
+ if (grouping === "status") return { kind: "status" };
+ if (grouping === "assignee") return { kind: "assignee" };
+ const propertyId = propertyIdFromViewKey(grouping);
+ if (propertyId) return { kind: "property", property_id: propertyId };
+ return { kind: "none" };
+}
+
type ColumnLabelKey =
| "title"
| "identifier"
@@ -1075,15 +1178,11 @@ function IssueTableBodyCell({
}
export function TableView({
- issues,
+ serverQuery,
childProgressMap,
- fetchNextPage,
- hasNextPage,
- isFetchingNextPage,
- windowError,
- total,
search,
onSearchChange,
+ onLoadedIssuesChange,
onCreateIssue,
exportIssues,
resolveExportLookups,
@@ -1096,7 +1195,10 @@ export function TableView({
const actions = useIssueSurfaceActionsOptional();
const selection = useIssueSurfaceSelection();
const { getActorName } = useActorName();
- const { data: properties = [] } = useQuery(propertyListOptions(wsId));
+ const {
+ data: properties = [],
+ isSuccess: propertyCatalogSettled,
+ } = useQuery(propertyListOptions(wsId));
const propertyById = useMemo(
() => new Map(properties.map((property) => [property.id, property])),
[properties],
@@ -1105,11 +1207,21 @@ export function TableView({
() => new Set(properties.map((property) => property.id)),
[properties],
);
+ const groupablePropertyIds = useMemo(
+ () =>
+ new Set(
+ properties
+ .filter((property) => ["select", "checkbox"].includes(property.type))
+ .map((property) => property.id),
+ ),
+ [properties],
+ );
const tableColumns = useViewStore((state) => state.tableColumns);
const toggleTableColumn = useViewStore((state) => state.toggleTableColumn);
const reorderTableColumn = useViewStore((state) => state.reorderTableColumn);
const setTableColumnWidth = useViewStore((state) => state.setTableColumnWidth);
const tableGrouping = useViewStore((state) => state.tableGrouping);
+ const setTableGrouping = useViewStore((state) => state.setTableGrouping);
const tableCollapsedGroups = useViewStore((state) => state.tableCollapsedGroups);
const toggleTableGroupCollapsed = useViewStore(
(state) => state.toggleTableGroupCollapsed,
@@ -1131,50 +1243,640 @@ export function TableView({
const groupingPropertyId = propertyIdFromViewKey(tableGrouping);
const effectiveTableGrouping =
- groupingPropertyId && !activePropertyIds.has(groupingPropertyId)
+ groupingPropertyId &&
+ propertyCatalogSettled &&
+ !groupablePropertyIds.has(groupingPropertyId)
? "none"
: tableGrouping;
+ useEffect(() => {
+ if (
+ !groupingPropertyId ||
+ !propertyCatalogSettled ||
+ groupablePropertyIds.has(groupingPropertyId)
+ ) {
+ return;
+ }
+ setTableGrouping("none");
+ toast.info(t(($) => $.table.group_property_unavailable));
+ }, [
+ groupablePropertyIds,
+ groupingPropertyId,
+ propertyCatalogSettled,
+ setTableGrouping,
+ t,
+ ]);
- // Grouping and hierarchy are whole-window statements, so the window must
- // be materialized for them — but only under an explicit ceiling: grouping
- // is persisted view state and hierarchy is on by default, so an unbounded
- // loop would re-download entire large workspaces on every visit (round-3
- // review P1#1). Below the ceiling the remaining pages load sequentially
- // (one per completed fetch — flipping the toggles off stops the loop),
- // which also makes hierarchy apply without scrolling to the last page
- // (round-3 P1#2). Above the ceiling both features suspend silently; the
- // window keeps the one-page-per-scroll sentinel.
- // Advancement gates (error stop, hard loaded-count ceiling, fresh total)
- // live in shouldAutoLoadNextWindowPage — see its doc for the failure
- // modes each gate closes (round-4 review P1#1/P1#2).
- const structureSuspended = isTableStructureSuspended(total);
- const structureWanted = effectiveTableGrouping !== "none" || tableHierarchy;
- const structureGrouping = structureSuspended ? "none" : effectiveTableGrouping;
- const structureHierarchy = tableHierarchy && !structureSuspended;
- const loadedCount = issues.length;
+ const serverGroupSpec = useMemo(
+ () => tableGroupSpec(effectiveTableGrouping),
+ [effectiveTableGrouping],
+ );
+ const usesServerGrouping = serverGroupSpec.kind !== "none";
+ const serverGroupsRequestGroup =
+ serverGroupSpec.kind === "none"
+ ? ({ kind: "status" } as const)
+ : serverGroupSpec;
+ const serverGroupsQuery = useInfiniteQuery({
+ ...issueTableGroupsOptions(
+ wsId,
+ serverQuery,
+ serverGroupsRequestGroup,
+ ),
+ enabled: usesServerGrouping,
+ });
+ const {
+ data: serverGroupsData,
+ isPending: serverGroupsPending,
+ isError: serverGroupsError,
+ hasNextPage: hasNextServerGroupPage,
+ isFetchingNextPage: fetchingNextServerGroupPage,
+ refetch: refetchServerGroups,
+ fetchNextPage: fetchNextServerGroupPage,
+ } = serverGroupsQuery;
useEffect(() => {
+ const body =
+ serverGroupsQuery.error instanceof ApiError &&
+ serverGroupsQuery.error.body &&
+ typeof serverGroupsQuery.error.body === "object"
+ ? (serverGroupsQuery.error.body as { error?: unknown })
+ : null;
if (
- shouldAutoLoadNextWindowPage({
- windowWanted: structureWanted,
- total,
- loadedCount,
- hasNextPage,
- isFetchingNextPage,
- hasError: windowError,
- })
+ serverGroupsQuery.error instanceof ApiError &&
+ serverGroupsQuery.error.status === 422 &&
+ body?.error === "unsupported_group"
) {
- void fetchNextPage();
+ setTableGrouping("none");
+ toast.info(t(($) => $.table.group_property_unavailable));
}
+ }, [serverGroupsQuery.error, setTableGrouping, t]);
+ const serverGroups = useMemo(
+ () => serverGroupsData?.pages.flatMap((page) => page.groups) ?? [],
+ [serverGroupsData?.pages],
+ );
+ const serverIdentity = useMemo(
+ () => JSON.stringify([serverQuery, serverGroupSpec, tableHierarchy]),
+ [serverGroupSpec, serverQuery, tableHierarchy],
+ );
+ const serverStructureIdentity = useMemo(
+ () => JSON.stringify([serverGroupSpec, tableHierarchy]),
+ [serverGroupSpec, tableHierarchy],
+ );
+ const collapsedGroupSet = useMemo(
+ () => new Set(tableCollapsedGroups),
+ [tableCollapsedGroups],
+ );
+ const collapsedParentSet = useMemo(
+ () => new Set(tableCollapsedParents),
+ [tableCollapsedParents],
+ );
+ const [serverBranchState, setServerBranchState] =
+ useState<ServerBranchState>({
+ identity: "",
+ structureIdentity: "",
+ branches: new Map(),
+ });
+
+ const rebasedServerBranchState = useMemo(
+ () =>
+ rebaseServerBranchState(
+ serverBranchState,
+ serverIdentity,
+ serverStructureIdentity,
+ usesServerGrouping,
+ ),
+ [
+ serverBranchState,
+ serverIdentity,
+ serverStructureIdentity,
+ usesServerGrouping,
+ ],
+ );
+
+ // Commit the synchronous rebase after render. Consumers use the derived
+ // state above immediately, so a filter/search/sort transition never has an
+ // empty frame while this effect catches state up.
+ useEffect(() => {
+ if (rebasedServerBranchState !== serverBranchState) {
+ setServerBranchState(rebasedServerBranchState);
+ }
+ }, [rebasedServerBranchState, serverBranchState]);
+
+ const activeServerBranches = rebasedServerBranchState.branches;
+ const serverBranchPlaceholderRef = useRef(
+ new Map<string, IssueTableRowsResponse>(),
+ );
+ const serverBranchPageTargets = useMemo<ServerBranchPageTarget[]>(
+ () =>
+ [...activeServerBranches.values()].flatMap((branch) =>
+ branch.cursors.map((cursor) => ({ branch, cursor })),
+ ),
+ [activeServerBranches],
+ );
+ // useQueries compares and installs the supplied query list in an effect.
+ // Keeping this array stable prevents a settled branch from being installed
+ // again on every render (which can otherwise create a render loop once the
+ // virtualized table starts measuring rows).
+ const serverBranchQueries = useMemo(
+ () =>
+ serverBranchPageTargets.map(({ branch, cursor }) => {
+ const placeholder =
+ cursor === null
+ ? serverBranchPlaceholderRef.current.get(
+ `${serverStructureIdentity}:${branch.key}`,
+ )
+ : undefined;
+ return {
+ ...issueTableRowPageOptions(wsId, {
+ query: serverQuery,
+ group: serverGroupSpec,
+ group_key: branch.groupKey,
+ hierarchy: { enabled: tableHierarchy },
+ parent_id: branch.parentId,
+ page: { limit: 50, cursor },
+ }),
+ // QueriesObserver replaces observers by query hash, so
+ // keepPreviousData alone cannot bridge a changed table query inside
+ // useQueries. Retain the last settled head per structural branch to
+ // keep the previous table painted while the new query is pending.
+ ...(placeholder ? { placeholderData: () => placeholder } : {}),
+ enabled:
+ (branch.groupKey === null ||
+ !collapsedGroupSet.has(branch.groupKey)) &&
+ !branch.ancestorIds.some((id) => collapsedParentSet.has(id)),
+ };
+ }),
+ [
+ collapsedGroupSet,
+ collapsedParentSet,
+ serverBranchPageTargets,
+ serverGroupSpec,
+ serverQuery,
+ serverStructureIdentity,
+ tableHierarchy,
+ wsId,
+ ],
+ );
+ const combineServerBranchQueries = useCallback(
+ (results: Array<UseQueryResult<IssueTableRowsResponse, Error>>) => {
+ const byBranch: Record<string, ServerBranchData> = {};
+ for (let index = 0; index < serverBranchPageTargets.length; index += 1) {
+ const target = serverBranchPageTargets[index];
+ const result = results[index];
+ if (!target || !result) continue;
+ const current = byBranch[target.branch.key] ?? {
+ rows: [],
+ total: 0,
+ nextCursor: null,
+ headUpdatedAt: 0,
+ headFetching: false,
+ loading: false,
+ error: false,
+ placeholder: false,
+ };
+ const page = result.data;
+ if (page) {
+ current.rows.push(...page.rows);
+ if (target.cursor === null) current.total = page.total;
+ current.nextCursor = page.next_cursor;
+ }
+ if (target.cursor === null) {
+ current.headUpdatedAt = result.dataUpdatedAt;
+ current.headFetching = result.isFetching;
+ }
+ current.loading ||= result.isPending || result.isFetching;
+ current.error ||= result.isError;
+ current.placeholder ||= result.isPlaceholderData;
+ byBranch[target.branch.key] = current;
+ }
+ return byBranch;
+ },
+ [serverBranchPageTargets],
+ );
+ // `combine` is structurally shared by React Query. It must return only plain
+ // objects/arrays: Map instances and freshly-created retry closures cannot be
+ // shared, and make useQueries publish a different snapshot on every render.
+ const serverBranchData = useQueries({
+ queries: serverBranchQueries,
+ combine: combineServerBranchQueries,
+ });
+
+ useEffect(() => {
+ const next = new Map<string, IssueTableRowsResponse>();
+ for (const branch of activeServerBranches.values()) {
+ const key = `${serverStructureIdentity}:${branch.key}`;
+ const data = serverBranchData[branch.key];
+ if (!data || data.placeholder || data.loading || data.error) {
+ const previous = serverBranchPlaceholderRef.current.get(key);
+ if (previous) next.set(key, previous);
+ continue;
+ }
+ next.set(key, {
+ query_fingerprint: "__table_placeholder__",
+ group_key: branch.groupKey,
+ parent_id: branch.parentId,
+ total: data.total,
+ rows: data.rows,
+ branch_total: data.rows.length,
+ next_cursor: null,
+ });
+ }
+ // Bound placeholders to the active structural graph. Sort/filter/search
+ // transitions reuse these entries; old group/property configurations do
+ // not accumulate for the lifetime of the Table component.
+ serverBranchPlaceholderRef.current = next;
}, [
- fetchNextPage,
- hasNextPage,
- isFetchingNextPage,
- loadedCount,
- structureWanted,
- total,
- windowError,
+ activeServerBranches,
+ serverBranchData,
+ serverStructureIdentity,
]);
+ // Re-derive ancestry from the current row graph after realtime re-parenting.
+ // Branch keys are parent ids, so an existing branch can move under a new
+ // collapsed ancestor without being re-activated by the viewport sentinel.
+ useEffect(() => {
+ const desiredAncestors = new Map<string, string[]>();
+ const visited = new Set<string>();
+ const visit = (
+ groupKey: string | null,
+ parentId: string | null,
+ ancestors: string[],
+ ) => {
+ const key = serverBranchKey(groupKey, parentId);
+ if (visited.has(key)) return;
+ visited.add(key);
+ desiredAncestors.set(key, ancestors);
+ for (const row of serverBranchData[key]?.rows ?? []) {
+ if (row.direct_child_count > 0) {
+ visit(groupKey, row.issue.id, [...ancestors, row.issue.id]);
+ }
+ }
+ };
+
+ if (usesServerGrouping) {
+ for (const group of serverGroups) visit(group.key, null, []);
+ } else {
+ visit(null, null, []);
+ }
+
+ setServerBranchState((previous) => {
+ if (previous.identity !== serverIdentity) return previous;
+ let branches: Map<string, ServerBranch> | null = null;
+ for (const [key, ancestors] of desiredAncestors) {
+ const branch = previous.branches.get(key);
+ if (!branch || sameStringArray(branch.ancestorIds, ancestors)) continue;
+ branches ??= new Map(previous.branches);
+ branches.set(key, { ...branch, ancestorIds: ancestors });
+ }
+ return branches ? { ...previous, branches } : previous;
+ });
+ }, [serverBranchData, serverGroups, serverIdentity, usesServerGrouping]);
+
+ const activateServerBranch = useCallback(
+ (
+ groupKey: string | null,
+ parentId: string | null,
+ ancestorIds: string[],
+ ) => {
+ setServerBranchState((previous) => {
+ if (previous.identity !== serverIdentity) return previous;
+ const key = serverBranchKey(groupKey, parentId);
+ const existing = previous.branches.get(key);
+ if (existing && sameStringArray(existing.ancestorIds, ancestorIds)) {
+ return previous;
+ }
+ const branches = new Map(previous.branches);
+ branches.set(
+ key,
+ existing
+ ? { ...existing, ancestorIds }
+ : {
+ key,
+ groupKey,
+ parentId,
+ ancestorIds,
+ cursors: [null],
+ },
+ );
+ return { ...previous, branches };
+ });
+ },
+ [serverIdentity],
+ );
+
+ // A broad Table invalidation refetches every active page. As soon as the
+ // head starts refreshing, every later cursor is obsolete; discard them
+ // before their concurrent responses can create a duplicate or missing row.
+ // The revision check is a second line of defence for clients that restore a
+ // refreshed head directly into the cache without exposing a fetching frame.
+ const branchHeadRevisionRef = useRef<Record<string, number>>({});
+ useEffect(() => {
+ const previousRevisions = branchHeadRevisionRef.current;
+ const nextRevisions: Record<string, number> = {};
+ const branchesToTrim = new Set<string>();
+ for (const [key, branch] of activeServerBranches) {
+ const revision = serverBranchData[key]?.headUpdatedAt ?? 0;
+ if (revision === 0) continue;
+ nextRevisions[key] = revision;
+ const seen = previousRevisions[key];
+ if (
+ branch.cursors.length > 1 &&
+ (serverBranchData[key]?.headFetching ||
+ (seen !== undefined && seen !== revision))
+ ) {
+ branchesToTrim.add(key);
+ }
+ }
+ // Keep only the current query's active branches. This bounds the revision
+ // bookkeeping across long sessions with many filter/search identities.
+ branchHeadRevisionRef.current = nextRevisions;
+ if (branchesToTrim.size === 0) return;
+
+ setServerBranchState((previous) => {
+ if (previous.identity !== serverIdentity) return previous;
+ let branches: Map<string, ServerBranch> | null = null;
+ for (const [key, branch] of previous.branches) {
+ if (branchesToTrim.has(key)) {
+ branches ??= new Map(previous.branches);
+ branches.set(key, { ...branch, cursors: [null] });
+ }
+ }
+ return branches ? { ...previous, branches } : previous;
+ });
+ }, [activeServerBranches, serverBranchData, serverIdentity]);
+
+ const loadNextServerBranchPage = useCallback(
+ (branchKey: string, cursor: string) => {
+ setServerBranchState((previous) => {
+ if (previous.identity !== serverIdentity) return previous;
+ const branch = previous.branches.get(branchKey);
+ if (!branch || branch.cursors.includes(cursor)) return previous;
+ const branches = new Map(previous.branches);
+ branches.set(branchKey, {
+ ...branch,
+ cursors: [...branch.cursors, cursor],
+ });
+ return { ...previous, branches };
+ });
+ },
+ [serverIdentity],
+ );
+
+ const retryServerBranch = useCallback(
+ (branchKey: string) => {
+ const branch = activeServerBranches.get(branchKey);
+ if (!branch) return;
+ void queryClient.refetchQueries({
+ queryKey: issueKeys.tableRows(
+ wsId,
+ serverQuery,
+ serverGroupSpec,
+ branch.groupKey,
+ tableHierarchy,
+ branch.parentId,
+ ),
+ exact: false,
+ type: "active",
+ });
+ },
+ [
+ activeServerBranches,
+ queryClient,
+ serverGroupSpec,
+ serverQuery,
+ tableHierarchy,
+ wsId,
+ ],
+ );
+
+ const serverGroupLabel = useCallback(
+ (descriptor: IssueTableGroupDescriptor) => {
+ const value = descriptor.value;
+ if (value.kind === "status") {
+ if (ALL_STATUSES.includes(value.status as IssueStatus)) {
+ return t(($) => $.status[value.status as IssueStatus]);
+ }
+ // Installed clients can receive a status introduced by a newer
+ // backend. Keep the group usable instead of collapsing the response
+ // to the schema fallback or rendering an empty label.
+ return value.status;
+ }
+ if (value.kind === "assignee") {
+ return value.actor
+ ? getActorName(value.actor.type, value.actor.id)
+ : t(($) => $.table.unassigned);
+ }
+ if (value.value_state === "unset") return t(($) => $.table.no_value);
+ if (value.value_state === "unavailable") {
+ return t(($) => $.table.value_unavailable);
+ }
+ const property = propertyById.get(value.property_id);
+ if (typeof value.value === "boolean") {
+ return value.value
+ ? t(($) => $.pickers.custom_property.true_label)
+ : t(($) => $.pickers.custom_property.false_label);
+ }
+ return (
+ property?.config.options?.find((option) => option.id === value.value)
+ ?.name ?? String(value.value ?? "")
+ );
+ },
+ [getActorName, propertyById, t],
+ );
+
+ const serverDisplayRows = useMemo<IssueTableDisplayRow[]>(() => {
+ const result: IssueTableDisplayRow[] = [];
+ const seenIssueIds = new Set<string>();
+ const appendBranch = (
+ groupKey: string | null,
+ parentId: string | null,
+ depth: number,
+ ancestorIds: string[],
+ ) => {
+ const key = serverBranchKey(groupKey, parentId);
+ const data = serverBranchData[key];
+ if (!data) {
+ const registered = activeServerBranches.has(key);
+ result.push({
+ kind: "load_more",
+ key: `${registered ? "loading" : "activate"}:${key}`,
+ label: t(($) => $.table.loading_branch),
+ loading: registered,
+ autoLoad: !registered,
+ onLoad: registered
+ ? undefined
+ : () => activateServerBranch(groupKey, parentId, ancestorIds),
+ });
+ return;
+ }
+ if (data.rows.length === 0 && data.loading) {
+ result.push({
+ kind: "load_more",
+ key: `loading:${key}`,
+ label: t(($) => $.table.loading_branch),
+ loading: true,
+ });
+ }
+ for (const row of data.rows) {
+ // A realtime move can briefly leave the same entity in old and new
+ // branch caches. Render the first authoritative position only; duplicate
+ // ids otherwise create duplicate React keys and duplicate selection.
+ if (seenIssueIds.has(row.issue.id)) continue;
+ seenIssueIds.add(row.issue.id);
+ const collapsed = collapsedParentSet.has(row.issue.id);
+ result.push({
+ kind: "issue",
+ key: row.issue.id,
+ issue: row.issue,
+ depth,
+ hasChildren: tableHierarchy && row.direct_child_count > 0,
+ collapsed,
+ });
+ if (tableHierarchy && row.direct_child_count > 0 && !collapsed) {
+ appendBranch(groupKey, row.issue.id, depth + 1, [
+ ...ancestorIds,
+ row.issue.id,
+ ]);
+ }
+ }
+ if (data.error) {
+ result.push({
+ kind: "load_more",
+ key: `retry:${key}`,
+ label: t(($) => $.table.load_more_failed_retry),
+ loading: false,
+ onLoad: () => retryServerBranch(key),
+ });
+ } else if (data.nextCursor) {
+ const nextCursor = data.nextCursor;
+ result.push({
+ kind: "load_more",
+ key: `more:${key}:${nextCursor}`,
+ label: t(($) => $.table.load_more),
+ loading: data.loading,
+ autoLoad: true,
+ onLoad: () => loadNextServerBranchPage(key, nextCursor),
+ });
+ }
+ };
+
+ if (usesServerGrouping) {
+ for (const descriptor of serverGroups) {
+ const collapsed = collapsedGroupSet.has(descriptor.key);
+ result.push({
+ kind: "group",
+ key: descriptor.key,
+ label: serverGroupLabel(descriptor),
+ count: descriptor.count,
+ collapsed,
+ });
+ if (!collapsed) appendBranch(descriptor.key, null, 0, []);
+ }
+ } else {
+ appendBranch(null, null, 0, []);
+ }
+ if (
+ usesServerGrouping &&
+ serverGroups.length === 0 &&
+ serverGroupsPending
+ ) {
+ result.push({
+ kind: "load_more",
+ key: "loading:groups",
+ label: t(($) => $.table.loading_branch),
+ loading: true,
+ });
+ } else if (usesServerGrouping && serverGroupsError) {
+ result.push({
+ kind: "load_more",
+ key: "retry:groups",
+ label: t(($) => $.table.load_failed_retry),
+ loading: false,
+ onLoad: () => void refetchServerGroups(),
+ });
+ } else if (usesServerGrouping && hasNextServerGroupPage) {
+ result.push({
+ kind: "load_more",
+ key: "more:groups",
+ label: t(($) => $.table.load_more),
+ loading: fetchingNextServerGroupPage,
+ autoLoad: true,
+ onLoad: () => void fetchNextServerGroupPage(),
+ });
+ }
+ return result;
+ }, [
+ collapsedGroupSet,
+ collapsedParentSet,
+ activeServerBranches,
+ activateServerBranch,
+ loadNextServerBranchPage,
+ retryServerBranch,
+ serverBranchData,
+ serverGroupLabel,
+ serverGroups,
+ serverGroupsPending,
+ serverGroupsError,
+ hasNextServerGroupPage,
+ fetchingNextServerGroupPage,
+ refetchServerGroups,
+ fetchNextServerGroupPage,
+ t,
+ tableHierarchy,
+ usesServerGrouping,
+ ]);
+
+ const tableMembershipIdentity = useMemo(
+ () =>
+ JSON.stringify([
+ serverQuery.scope,
+ serverQuery.filters,
+ serverQuery.search ?? "",
+ ]),
+ [serverQuery.filters, serverQuery.scope, serverQuery.search],
+ );
+ const authoritativeLoadedIssues = useMemo(() => {
+ const byId = new Map<string, Issue>();
+ for (const branch of Object.values(serverBranchData)) {
+ // Previous-data placeholders keep the old table painted during a query
+ // transition, but they are not members of the new filter/search window.
+ if (branch.placeholder) continue;
+ for (const row of branch.rows) byId.set(row.issue.id, row.issue);
+ }
+ return [...byId.values()];
+ }, [serverBranchData]);
+ const [loadedIssueState, setLoadedIssueState] = useState<LoadedIssueState>({
+ membershipIdentity: tableMembershipIdentity,
+ issues: new Map(),
+ });
+ useEffect(() => {
+ setLoadedIssueState((previous) => {
+ const reset = previous.membershipIdentity !== tableMembershipIdentity;
+ const issues = reset
+ ? new Map<string, Issue>()
+ : new Map(previous.issues);
+ let changed = reset;
+ for (const issue of authoritativeLoadedIssues) {
+ if (issues.get(issue.id) !== issue) {
+ issues.set(issue.id, issue);
+ changed = true;
+ }
+ }
+ return changed
+ ? { membershipIdentity: tableMembershipIdentity, issues }
+ : previous;
+ });
+ }, [authoritativeLoadedIssues, tableMembershipIdentity]);
+ const loadedIssues = useMemo(
+ () =>
+ loadedIssueState.membershipIdentity === tableMembershipIdentity
+ ? [...loadedIssueState.issues.values()]
+ : [],
+ [
+ loadedIssueState.issues,
+ loadedIssueState.membershipIdentity,
+ tableMembershipIdentity,
+ ],
+ );
+
const visibleColumnConfigs = useMemo(
() =>
tableColumns.filter((column) => {
@@ -1184,60 +1886,31 @@ export function TableView({
[activePropertyIds, tableColumns],
);
- const liveDisplayRows = useMemo(
- () =>
- buildIssueTableRows(issues, {
- grouping: structureGrouping,
- properties,
- collapsedGroups: new Set(tableCollapsedGroups),
- collapsedParents: new Set(tableCollapsedParents),
- hierarchy: structureHierarchy,
- windowComplete: !hasNextPage,
- getActorName,
- getStatusLabel: (status) => t(($) => $.status[status]),
- noValueLabel: t(($) => $.table.no_value),
- unassignedLabel: t(($) => $.table.unassigned),
- trueLabel: t(($) => $.pickers.custom_property.true_label),
- falseLabel: t(($) => $.pickers.custom_property.false_label),
- }),
- [
- getActorName,
- hasNextPage,
- issues,
- properties,
- t,
- tableCollapsedGroups,
- tableCollapsedParents,
- structureGrouping,
- structureHierarchy,
- ],
- );
-
// While a cell editor popup / rename input is open, hold the row structure
- // still: window materialization, the end-of-load hierarchy assembly, and
- // realtime refetches all rebuild the row list, and a reorder can move the
- // anchor row out of the virtualized render window — unmounting the cell and
- // closing the popup the user just opened (MUL-5108). The snapshot freezes
- // ORDER only; issue objects inside the rows keep tracking the live cache so
- // the open editor reflects optimistic updates. Live structure snaps back
- // the moment the editor closes. Ref writes happen during render on purpose:
- // the snapshot must be captured from the same render that flips `editing`
- // on, and both branches are idempotent under StrictMode double-render.
+ // still: server branch pagination and realtime refetches can rebuild or
+ // reorder the row list, moving the anchor row out of the virtualized render
+ // window and closing the popup the user just opened (MUL-5108). The snapshot
+ // freezes ORDER only; issue objects inside the rows keep tracking live
+ // server-query data so the open editor reflects optimistic updates. Live
+ // structure snaps back the moment the editor closes. Ref writes happen
+ // during render on purpose: the snapshot must be captured from the same
+ // render that flips `editing` on, and both branches are idempotent under
+ // StrictMode double-render.
const frozenRowsRef = useRef<IssueTableDisplayRow[] | null>(null);
if (editingCellKey === null) frozenRowsRef.current = null;
else if (frozenRowsRef.current === null)
- frozenRowsRef.current = liveDisplayRows;
+ frozenRowsRef.current = serverDisplayRows;
const frozenRows = frozenRowsRef.current;
const issueById = useMemo(
- () => new Map(issues.map((issue) => [issue.id, issue])),
- [issues],
+ () => new Map(authoritativeLoadedIssues.map((issue) => [issue.id, issue])),
+ [authoritativeLoadedIssues],
);
const displayRows = useMemo(
() =>
- frozenRows && frozenRows !== liveDisplayRows
+ frozenRows && frozenRows !== serverDisplayRows
? refreshFrozenTableRows(frozenRows, issueById)
- : liveDisplayRows,
- [frozenRows, issueById, liveDisplayRows],
+ : serverDisplayRows,
+ [frozenRows, issueById, serverDisplayRows],
);
const visibleIssueIds = useMemo(
() =>
@@ -1246,9 +1919,12 @@ export function TableView({
.map((row) => row.issue.id),
[displayRows],
);
+ useEffect(() => {
+ onLoadedIssuesChange(loadedIssues);
+ }, [loadedIssues, onLoadedIssuesChange]);
const selectedIssues = useMemo(
- () => issues.filter((issue) => selection.selectedIds.has(issue.id)),
- [issues, selection.selectedIds],
+ () => loadedIssues.filter((issue) => selection.selectedIds.has(issue.id)),
+ [loadedIssues, selection.selectedIds],
);
const handleIssueSelection = useCallback(
(issueId: string, shiftKey: boolean) => {
@@ -1538,38 +2214,17 @@ export function TableView({
toast.success(t(($) => $.table.export_success, { count: rows.length }));
} catch (error) {
toast.error(
- error instanceof Error ? error.message : t(($) => $.table.export_failed),
+ error instanceof Error &&
+ !(error instanceof IssueTableExportIntegrityError) &&
+ error.message
+ ? error.message
+ : t(($) => $.table.export_failed),
);
} finally {
setExporting(null);
}
};
- const footer = (
- <TableFooter className="border-0 bg-transparent">
- <TableRow className="h-px border-0 hover:bg-transparent">
- <TableCell
- colSpan={table.getVisibleLeafColumns().length}
- className="h-px p-0"
- >
- <InfiniteScrollSentinel
- onVisible={() => {
- // A failed window stops implicit loading too — otherwise every
- // visibility transition retries into the same failure. The
- // toolbar Retry is the explicit resume path.
- if (hasNextPage && !isFetchingNextPage && !windowError) {
- void fetchNextPage();
- }
- }}
- loading={false}
- rootMargin="320px"
- className="h-px w-px"
- />
- </TableCell>
- </TableRow>
- </TableFooter>
- );
-
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center gap-2 border-b px-3 py-1.5">
@@ -1579,17 +2234,7 @@ export function TableView({
placeholder={t(($) => $.table.search_placeholder)}
clearLabel={t(($) => $.table.search_clear)}
/>
- <span className="mr-auto min-w-0 truncate text-xs text-muted-foreground">
- {windowError && hasNextPage && (
- <button
- type="button"
- onClick={() => void fetchNextPage()}
- className="text-destructive underline-offset-2 hover:underline"
- >
- {t(($) => $.table.load_more_failed_retry)}
- </button>
- )}
- </span>
+ <span className="mr-auto" />
<DropdownMenu>
<DropdownMenuTrigger
render={
@@ -1637,7 +2282,6 @@ export function TableView({
>
<DataTable
table={table}
- footer={footer}
virtualizeRows
emptyMessage={t(($) => $.table.empty)}
onRowClick={(row) => {
@@ -1646,14 +2290,52 @@ export function TableView({
}
}}
renderRow={(row) => {
- if (row.original.kind !== "group") return null;
- return (
- <IssueTableGroupRow
- group={row.original}
- colSpan={table.getVisibleLeafColumns().length}
- onToggle={() => toggleTableGroupCollapsed(row.original.key)}
- />
- );
+ if (row.original.kind === "group") {
+ return (
+ <IssueTableGroupRow
+ group={row.original}
+ colSpan={table.getVisibleLeafColumns().length}
+ onToggle={() => toggleTableGroupCollapsed(row.original.key)}
+ />
+ );
+ }
+ if (row.original.kind === "load_more") {
+ const loadMoreRow = row.original;
+ return (
+ <TableRow className="hover:bg-transparent">
+ <TableCell
+ colSpan={table.getVisibleLeafColumns().length}
+ className="relative h-9 px-4 py-1"
+ >
+ {loadMoreRow.autoLoad &&
+ loadMoreRow.onLoad &&
+ !loadMoreRow.loading && (
+ <InfiniteScrollSentinel
+ onVisible={loadMoreRow.onLoad}
+ loading={false}
+ rootMargin="240px"
+ className="absolute inset-y-0 left-0 w-px"
+ />
+ )}
+ <button
+ type="button"
+ disabled={loadMoreRow.loading || !loadMoreRow.onLoad}
+ onClick={(event) => {
+ event.stopPropagation();
+ loadMoreRow.onLoad?.();
+ }}
+ className="sticky left-4 flex items-center gap-2 text-xs text-muted-foreground enabled:hover:text-foreground disabled:cursor-default"
+ >
+ {loadMoreRow.loading && (
+ <Loader2 className="size-3.5 animate-spin" />
+ )}
+ {loadMoreRow.label}
+ </button>
+ </TableCell>
+ </TableRow>
+ );
+ }
+ return null;
}}
className="min-h-0 flex-1"
/>
diff --git a/packages/views/issues/components/workspace-agent-working-chip.tsx b/packages/views/issues/components/workspace-agent-working-chip.tsx
index 19e384f198..e88347620c 100644
--- a/packages/views/issues/components/workspace-agent-working-chip.tsx
+++ b/packages/views/issues/components/workspace-agent-working-chip.tsx
@@ -30,11 +30,9 @@ interface WorkspaceAgentWorkingChipProps {
// from the render pipeline instead of re-deriving it from the task snapshot
// is what keeps that judgement in step with the list (MUL-4884).
//
- // `undefined` means the scope is UNKNOWN — the table's ids-facet window is
- // still resolving, failed, or is too large to materialize. The chip then
- // shows an indeterminate "—" instead of a number: publishing a count from
- // some other, incomplete window would be a precise-looking wrong answer
- // (round-5 review P2). The toggle keeps working in that state.
+ // `undefined` means the scope is UNKNOWN. Table deliberately does not
+ // materialize all cursor branches just to derive this decoration, so the
+ // chip shows an indeterminate "—" while the toggle remains available.
workingIssues: readonly Issue[] | undefined;
}
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index 9d50f7d3e2..fd648b5b31 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -2,7 +2,14 @@
* @vitest-environment jsdom
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { setApiInstance } from "@multica/core/api";
import type { ApiClient } from "@multica/core/api/client";
@@ -10,6 +17,7 @@ import { pruneIssueSurfaceViewStates } from "@multica/core/issues/stores/surface
import type {
AgentTask,
Issue,
+ IssueTableRowsRequest,
ListIssuesParams,
ListIssuesResponse,
} from "@multica/core/types";
@@ -19,6 +27,7 @@ import { IssueSurface } from "./issue-surface";
// does not remount its children on switch, so the surface must handle the
// wsId change itself.
const mockWsId = vi.hoisted(() => ({ current: "ws-1" }));
+const mockTranslate = vi.hoisted(() => vi.fn(() => "translated"));
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => mockWsId.current,
}));
@@ -38,6 +47,18 @@ vi.mock("react-virtuoso", () => ({
),
}));
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: ({ count, estimateSize }: any) => ({
+ getVirtualItems: () =>
+ Array.from({ length: count }, (_, index) => ({
+ index,
+ start: index * estimateSize(),
+ end: (index + 1) * estimateSize(),
+ })),
+ getTotalSize: () => count * estimateSize(),
+ }),
+}));
+
const mockAuthUser = { id: "user-1", email: "[email protected]", name: "Test User" };
vi.mock("@multica/core/auth", () => ({
useAuthStore: Object.assign(
@@ -53,7 +74,7 @@ vi.mock("@multica/core/auth", () => ({
vi.mock("../../i18n", () => ({
// TableView also reads `i18n.language` for its date formatting.
- useT: () => ({ t: () => "translated", i18n: { language: "en" } }),
+ useT: () => ({ t: mockTranslate, i18n: { language: "en" } }),
useTimeAgo: () => () => "now",
}));
@@ -256,6 +277,7 @@ describe("IssueSurface — table pagination ownership", () => {
beforeEach(() => {
qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
listIssues = vi.fn(() => never<ListIssuesResponse>());
+ mockTranslate.mockClear();
pruneIssueSurfaceViewStates([]);
mockWsId.current = "ws-1";
// jsdom has no IntersectionObserver; the table footer sentinel constructs
@@ -279,13 +301,7 @@ describe("IssueSurface — table pagination ownership", () => {
vi.restoreAllMocks();
});
- it("requests each offset exactly once while the agents-working filter is on", async () => {
- // With the filter on, the working window IS the main table window (same
- // query key). The data hook's chip loop and TableView's structure loop
- // used to both answer the same render snapshot with fetchNextPage(),
- // and the default cancel/restart semantics doubled every offset's HTTP
- // request (round-6 review R1). Ownership now belongs to the structure
- // loop alone, and all auto callers use cancelRefetch: false.
+ it("does not materialize the legacy offset window and starts one cursor root branch", async () => {
const { getIssueSurfaceViewStore } = await import(
"@multica/core/issues/stores/surface-view-store"
);
@@ -299,23 +315,11 @@ describe("IssueSurface — table pagination ownership", () => {
...makeIssue(`run-${index}`, `Running ${index}`, "pt"),
status: "in_progress" as const,
}));
- const idsOffsets: number[] = [];
- listIssues.mockImplementation((params?: ListIssuesParams) => {
- // A PRESENT-but-empty ids facet is the pre-snapshot state and returns
- // an empty window (server semantics) — only the real running-set key's
- // offsets count toward the uniqueness assertion.
- if (params?.ids && params.ids.length > 0) {
- const offset = params.offset ?? 0;
- idsOffsets.push(offset);
- return Promise.resolve({
- issues: runningIssues.slice(offset, offset + 100),
- total: runningIssues.length,
- });
- }
- return Promise.resolve({ issues: [], total: 0 });
- });
+ const listIssueTableRows = vi.fn(() => never());
setApiInstance({
listIssues,
+ listIssueTableRows,
+ listIssueTableFacets: vi.fn(() => never()),
listGroupedIssues: vi.fn(() => never()),
listProjects: vi.fn(() => never()),
getAgentTaskSnapshot: vi.fn(() =>
@@ -347,12 +351,293 @@ describe("IssueSurface — table pagination ownership", () => {
</QueryClientProvider>,
);
- // The structure loop (hierarchy is on by default, 250 ≤ ceiling)
- // materializes the window without user interaction.
- await waitFor(() => expect(idsOffsets).toContain(200), { timeout: 5000 });
- // Let any straggling (buggy) second responder fire before asserting.
- await new Promise((resolve) => setTimeout(resolve, 100));
+ await waitFor(() => expect(listIssueTableRows).toHaveBeenCalledTimes(1));
+ expect(listIssueTableRows).toHaveBeenCalledWith(
+ expect.objectContaining({
+ group: { kind: "none" },
+ group_key: null,
+ parent_id: null,
+ query: expect.objectContaining({
+ filters: expect.objectContaining({ working_only: true }),
+ }),
+ }),
+ );
+ expect(listIssues).not.toHaveBeenCalled();
+ });
+
+ it("keeps loaded rows when a continuation page reports zero", async () => {
+ const { getIssueSurfaceViewStore } = await import(
+ "@multica/core/issues/stores/surface-view-store"
+ );
+ const store = getIssueSurfaceViewStore("project:pt-pages");
+ store.getState().setViewMode("table");
+ const first = makeIssue("page-1", "First cursor row", "pt-pages");
+ const second = makeIssue("page-2", "Second cursor row", "pt-pages");
+ const listIssueTableRows = vi.fn((request: IssueTableRowsRequest) =>
+ Promise.resolve(
+ request.page?.cursor == null
+ ? {
+ query_fingerprint: "sha256:pages",
+ group_key: null,
+ parent_id: null,
+ total: 2,
+ rows: [{ issue: first, direct_child_count: 0 }],
+ branch_total: 1,
+ next_cursor: "cursor-2",
+ }
+ : {
+ query_fingerprint: "sha256:pages",
+ group_key: null,
+ parent_id: null,
+ total: 0,
+ rows: [{ issue: second, direct_child_count: 0 }],
+ branch_total: 1,
+ next_cursor: null,
+ },
+ ),
+ );
+ setApiInstance({
+ listIssues,
+ listIssueTableRows,
+ listIssueTableFacets: vi.fn(() => never()),
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => Promise.resolve([])),
+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),
+ getChildIssueProgress: vi.fn(() => Promise.resolve([])),
+ listProperties: vi.fn(() => Promise.resolve({ properties: [] })),
+ listMembers: vi.fn(() => Promise.resolve([])),
+ listAgents: vi.fn(() => Promise.resolve([])),
+ listSquads: vi.fn(() => Promise.resolve([])),
+ } as unknown as ApiClient);
+
+ render(
+ <QueryClientProvider client={qc}>
+ <IssueSurface
+ scope={{ type: "project", projectId: "pt-pages" }}
+ modes={["table"]}
+ renderHeader={() => null}
+ batchToolbar="never"
+ />
+ </QueryClientProvider>,
+ );
+
+ await screen.findByText("First cursor row");
+ const loadMoreButton = document.querySelector<HTMLButtonElement>(
+ "tbody button.sticky",
+ );
+ expect(loadMoreButton).not.toBeNull();
+ fireEvent.click(loadMoreButton!);
- expect([...idsOffsets].sort((a, b) => a - b)).toEqual([0, 100, 200]);
+ await screen.findByText("Second cursor row");
+ expect(listIssueTableRows).toHaveBeenCalledWith(
+ expect.objectContaining({ page: { limit: 50, cursor: "cursor-2" } }),
+ );
+ expect(screen.getByText("First cursor row")).toBeInTheDocument();
+ });
+
+ it("feeds loaded Table rows to the shared batch toolbar", async () => {
+ const { getIssueSurfaceViewStore } = await import(
+ "@multica/core/issues/stores/surface-view-store"
+ );
+ const store = getIssueSurfaceViewStore("project:pt-batch");
+ store.getState().setViewMode("table");
+ const issue = makeIssue("table-selected", "Loaded Table issue", "pt-batch");
+
+ setApiInstance({
+ listIssues,
+ listIssueTableRows: vi.fn(() =>
+ Promise.resolve({
+ query_fingerprint: "sha256:table-batch",
+ group_key: null,
+ parent_id: null,
+ total: 1,
+ rows: [{ issue, direct_child_count: 0 }],
+ branch_total: 1,
+ next_cursor: null,
+ }),
+ ),
+ listIssueTableFacets: vi.fn(() => never()),
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => Promise.resolve([])),
+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),
+ getChildIssueProgress: vi.fn(() => Promise.resolve([])),
+ listProperties: vi.fn(() => Promise.resolve({ properties: [] })),
+ listMembers: vi.fn(() => Promise.resolve([])),
+ listAgents: vi.fn(() => Promise.resolve([])),
+ listSquads: vi.fn(() => Promise.resolve([])),
+ } as unknown as ApiClient);
+
+ const { container } = render(
+ <QueryClientProvider client={qc}>
+ <IssueSurface
+ scope={{ type: "project", projectId: "pt-batch" }}
+ modes={["table"]}
+ renderHeader={() => null}
+ batchToolbar="always"
+ />
+ </QueryClientProvider>,
+ );
+
+ await screen.findByText("Loaded Table issue");
+ const checkboxes = screen.getAllByRole("checkbox");
+ fireEvent.click(checkboxes[1]!);
+
+ await waitFor(() => {
+ expect(container.querySelector(".fixed.bottom-6")).not.toBeNull();
+ });
+ });
+
+ it("keeps the previous Table rows painted while a new sort is loading", async () => {
+ const { getIssueSurfaceViewStore } = await import(
+ "@multica/core/issues/stores/surface-view-store"
+ );
+ const store = getIssueSurfaceViewStore("project:pt-sort-transition");
+ store.getState().setViewMode("table");
+ const issue = makeIssue(
+ "table-sort-placeholder",
+ "Table row kept during sort",
+ "pt-sort-transition",
+ );
+ const listIssueTableRows = vi.fn((request: IssueTableRowsRequest) =>
+ request.query.sort.field === "position"
+ ? Promise.resolve({
+ query_fingerprint: "sha256:initial-sort",
+ group_key: null,
+ parent_id: null,
+ total: 1,
+ rows: [{ issue, direct_child_count: 0 }],
+ branch_total: 1,
+ next_cursor: null,
+ })
+ : never(),
+ );
+ setApiInstance({
+ listIssues,
+ listIssueTableRows,
+ listIssueTableFacets: vi.fn(() => never()),
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => Promise.resolve([])),
+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),
+ getChildIssueProgress: vi.fn(() => Promise.resolve([])),
+ listProperties: vi.fn(() => Promise.resolve({ properties: [] })),
+ listMembers: vi.fn(() => Promise.resolve([])),
+ listAgents: vi.fn(() => Promise.resolve([])),
+ listSquads: vi.fn(() => Promise.resolve([])),
+ } as unknown as ApiClient);
+
+ render(
+ <QueryClientProvider client={qc}>
+ <IssueSurface
+ scope={{ type: "project", projectId: "pt-sort-transition" }}
+ modes={["table"]}
+ renderHeader={() => null}
+ batchToolbar="never"
+ />
+ </QueryClientProvider>,
+ );
+
+ await screen.findByText("Table row kept during sort");
+ act(() => store.getState().setSortBy("title"));
+ await waitFor(() => expect(listIssueTableRows).toHaveBeenCalledTimes(2));
+ expect(screen.getByText("Table row kept during sort")).toBeInTheDocument();
+ });
+
+ it("keeps selected Table rows in the batch universe after their group collapses", async () => {
+ const { getIssueSurfaceViewStore } = await import(
+ "@multica/core/issues/stores/surface-view-store"
+ );
+ const store = getIssueSurfaceViewStore("project:pt-collapsed-batch");
+ store.getState().setViewMode("table");
+ store.getState().setTableGrouping("status");
+ const issue = makeIssue(
+ "table-collapsed-selected",
+ "Selected issue in collapsed group",
+ "pt-collapsed-batch",
+ );
+
+ vi.stubGlobal(
+ "IntersectionObserver",
+ class {
+ private readonly callback: IntersectionObserverCallback;
+ constructor(callback: IntersectionObserverCallback) {
+ this.callback = callback;
+ }
+ observe(target: Element) {
+ this.callback(
+ [{ isIntersecting: true, target } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ unobserve() {}
+ disconnect() {}
+ takeRecords() {
+ return [];
+ }
+ root = null;
+ rootMargin = "0px";
+ thresholds = [0];
+ },
+ );
+
+ setApiInstance({
+ listIssues,
+ listIssueTableGroups: vi.fn(() =>
+ Promise.resolve({
+ query_fingerprint: "sha256:collapsed-groups",
+ total: 1,
+ groups: [
+ {
+ key: "status:todo",
+ value: { kind: "status", status: "todo" },
+ count: 1,
+ },
+ ],
+ next_cursor: null,
+ }),
+ ),
+ listIssueTableRows: vi.fn(() =>
+ Promise.resolve({
+ query_fingerprint: "sha256:collapsed-rows",
+ group_key: "status:todo",
+ parent_id: null,
+ total: 1,
+ rows: [{ issue, direct_child_count: 0 }],
+ branch_total: 1,
+ next_cursor: null,
+ }),
+ ),
+ listIssueTableFacets: vi.fn(() => never()),
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => Promise.resolve([])),
+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),
+ getChildIssueProgress: vi.fn(() => Promise.resolve([])),
+ listProperties: vi.fn(() => Promise.resolve({ properties: [] })),
+ listMembers: vi.fn(() => Promise.resolve([])),
+ listAgents: vi.fn(() => Promise.resolve([])),
+ listSquads: vi.fn(() => Promise.resolve([])),
+ } as unknown as ApiClient);
+
+ const { container } = render(
+ <QueryClientProvider client={qc}>
+ <IssueSurface
+ scope={{ type: "project", projectId: "pt-collapsed-batch" }}
+ modes={["table"]}
+ renderHeader={() => null}
+ batchToolbar="always"
+ />
+ </QueryClientProvider>,
+ );
+
+ await screen.findByText("Selected issue in collapsed group");
+ fireEvent.click(screen.getAllByRole("checkbox")[1]!);
+ await waitFor(() => {
+ expect(container.querySelector(".fixed.bottom-6")).not.toBeNull();
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "translated1" }));
+ await waitFor(() => {
+ expect(screen.queryByText("Selected issue in collapsed group")).toBeNull();
+ });
+ expect(container.querySelector(".fixed.bottom-6")).not.toBeNull();
});
});
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index be2c3f5844..0359d68e60 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useMemo, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { ListTodo, Plus } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
@@ -33,7 +33,7 @@ export interface IssueSurfaceRenderContext {
/** The rows the agents-working filter would leave on screen, with this
* surface's `clientFilter` applied — headers feed it to the working chip
* so the chip's count is the post-click row count (MUL-4884). Undefined
- * means the set is UNKNOWN (table window resolving / failed / too large);
+ * means the set is UNKNOWN (not materialized by the server-backed Table);
* the chip renders an indeterminate state instead of a number. */
workingIssues: Issue[] | undefined;
}
@@ -76,7 +76,6 @@ export function IssueSurface({
const contentKey = `${wsId}:${issueScopeKey(scope)}`;
useEffect(() => {
if (process.env.NODE_ENV !== "production") {
- // eslint-disable-next-line no-console
console.warn(`[issue-surface] mount ${contentKey}`);
}
}, [contentKey]);
@@ -124,12 +123,23 @@ function IssueSurfaceContent({
contentClassName,
}: Omit<IssueSurfaceComponentProps, "surfaceKey">) {
const { t } = useT("projects");
- const { t: tIssues } = useT("issues");
const controller = useIssueSurfaceController({
scope,
modes,
createDefaults,
});
+ const [tableLoadedIssues, setTableLoadedIssues] = useState<Issue[]>([]);
+ const handleTableLoadedIssuesChange = useCallback((next: Issue[]) => {
+ setTableLoadedIssues((current) =>
+ current.length === next.length &&
+ current.every((issue, index) => issue === next[index])
+ ? current
+ : next,
+ );
+ }, []);
+ useEffect(() => {
+ if (controller.viewMode !== "table") setTableLoadedIssues([]);
+ }, [controller.viewMode]);
const issues = useMemo(
() =>
clientFilter
@@ -201,8 +211,10 @@ function IssueSurfaceContent({
allowGantt={controller.allowGantt}
isRefreshing={controller.isRefreshing}
facetCountsExact={
- !(controller.viewMode === "table" && controller.hasNextFlatPage)
+ controller.viewMode !== "table"
}
+ tableFacetCounts={controller.tableFacetCounts}
+ onTableFacetChange={controller.setActiveTableFacet}
/>
)}
{controller.isLoading ? (
@@ -211,21 +223,6 @@ function IssueSurfaceContent({
) : (
<IssueSurfaceSkeleton mode={controller.viewMode} />
)
- ) : controller.viewMode === "table" && controller.flatWindowColdError ? (
- // A cold-load failure is NOT an empty workspace: rendering the
- // create-issue empty state here misreports a 5xx/offline as "no
- // issues" and leaves no recovery path, since TableView (and its
- // load-more Retry) never mounts without data (round-5 review P2).
- <div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-muted-foreground">
- <p className="text-sm">{tIssues(($) => $.table.load_failed)}</p>
- <Button
- variant="outline"
- size="sm"
- onClick={() => void controller.refetchFlatWindow()}
- >
- {tIssues(($) => $.table.load_failed_retry)}
- </Button>
- </div>
) : controller.isEmpty || shouldShowClientEmpty ? (
renderEmpty ? (
renderEmpty(renderContext)
@@ -281,15 +278,11 @@ function IssueSurfaceContent({
)}
{controller.viewMode === "table" && (
<TableView
- issues={issues}
+ serverQuery={controller.tableQuerySpec}
childProgressMap={controller.childProgressMap}
- fetchNextPage={controller.fetchNextFlatPage}
- hasNextPage={controller.hasNextFlatPage}
- isFetchingNextPage={controller.isFetchingNextFlatPage}
- windowError={controller.flatWindowError}
- total={controller.flatTotal}
search={controller.tableSearch}
onSearchChange={controller.setTableSearch}
+ onLoadedIssuesChange={handleTableLoadedIssuesChange}
onCreateIssue={openCreateIssue}
exportIssues={controller.exportTableIssues}
resolveExportLookups={controller.resolveTableExportLookups}
@@ -318,7 +311,13 @@ function IssueSurfaceContent({
)}
</div>
)}
- {shouldShowBatchToolbar && <BatchActionToolbar issues={issues} />}
+ {shouldShowBatchToolbar && (
+ <BatchActionToolbar
+ issues={
+ controller.viewMode === "table" ? tableLoadedIssues : issues
+ }
+ />
+ )}
</IssueSurfaceSelectionProvider>
</IssueContextMenuProvider>
</IssueSurfaceActionsProvider>
diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
index 3ec50f2527..c0ec3cc5b2 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx
+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
@@ -22,6 +22,7 @@ import type {
ListIssuesResponse,
} from "@multica/core/types";
import { useIssueSurfaceController } from "./use-issue-surface-controller";
+import { IssueTableExportIntegrityError } from "../components/table-view-model";
function makeIssue(
overrides: Partial<Issue> & Pick<Issue, "id" | "status">,
@@ -489,7 +490,7 @@ describe("useIssueSurfaceController", () => {
await waitFor(() => expect(result.current.isRefreshing).toBe(false));
});
- it("debounces table search and sends it with the server-side flat window", async () => {
+ it("debounces table search into the canonical server query without fetching the legacy flat window", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setViewMode("table");
listIssues.mockResolvedValue({ issues: [], total: 0 });
@@ -503,30 +504,158 @@ describe("useIssueSurfaceController", () => {
{ wrapper: makeWrapper(qc, "project:p1") },
);
- await waitFor(() => expect(result.current.isLoading).toBe(false));
listIssues.mockClear();
act(() => result.current.setTableSearch(" Release train "));
expect(result.current.tableSearch).toBe(" Release train ");
- expect(listIssues).not.toHaveBeenCalledWith(
- expect.objectContaining({ q: "Release train" }),
+ expect(result.current.tableQuerySpec.search).toBeUndefined();
+ await waitFor(() =>
+ expect(result.current.tableQuerySpec.search).toBe("Release train"),
+ );
+ expect(listIssues).not.toHaveBeenCalled();
+ expect(result.current.isEmpty).toBe(false);
+ });
+
+ it("loads only the Table facet whose filter submenu is active", async () => {
+ const store = getIssueSurfaceViewStore("project:p1");
+ store.getState().setViewMode("table");
+ const listIssueTableFacets = vi.fn().mockResolvedValue({
+ query_fingerprint: "sha256:facets",
+ total: 0,
+ facets: [{ kind: "status", values: [{ key: "todo", count: 2 }] }],
+ });
+ setApiInstance({
+ listIssues,
+ listIssueTableFacets,
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => never()),
+ listProperties: vi.fn(() => Promise.resolve({ properties: [] })),
+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),
+ getChildIssueProgress: vi.fn(() => Promise.resolve([])),
+ } as unknown as ApiClient);
+
+ const { result } = renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "project", projectId: "p1" },
+ modes: ["table"],
+ }),
+ { wrapper: makeWrapper(qc, "project:p1") },
);
+ expect(listIssueTableFacets).not.toHaveBeenCalled();
+ act(() => result.current.setActiveTableFacet({ kind: "status" }));
+ await waitFor(() => expect(listIssueTableFacets).toHaveBeenCalledTimes(1));
+ expect(listIssueTableFacets).toHaveBeenCalledWith(
+ expect.objectContaining({
+ facets: [{ kind: "status" }],
+ include_total: false,
+ }),
+ );
await waitFor(() =>
- expect(listIssues).toHaveBeenCalledWith(
- expect.objectContaining({
- project_id: "p1",
- q: "Release train",
- limit: 100,
- offset: 0,
+ expect(result.current.tableFacetCounts?.facets[0]?.kind).toBe("status"),
+ );
+
+ act(() => result.current.setActiveTableFacet(null));
+ expect(result.current.tableFacetCounts).toBeUndefined();
+ });
+
+ it("fails Table export closed when schema fallback would truncate the CSV", async () => {
+ const store = getIssueSurfaceViewStore("project:p1");
+ store.getState().setViewMode("table");
+ const listIssueTableRows = vi.fn(() =>
+ Promise.resolve({
+ query_fingerprint: "",
+ group_key: null,
+ parent_id: null,
+ total: 0,
+ rows: [],
+ branch_total: 0,
+ next_cursor: null,
+ }),
+ );
+ setApiInstance({
+ listIssues,
+ listIssueTableRows,
+ listIssueTableFacets: vi.fn(() => never()),
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => never()),
+ listProperties: vi.fn(() => Promise.resolve({ properties: [] })),
+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),
+ getChildIssueProgress: vi.fn(() => Promise.resolve([])),
+ } as unknown as ApiClient);
+
+ const { result } = renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "project", projectId: "p1" },
+ modes: ["table"],
}),
- ),
+ { wrapper: makeWrapper(qc, "project:p1") },
+ );
+
+ await expect(result.current.exportTableIssues()).rejects.toBeInstanceOf(
+ IssueTableExportIntegrityError,
+ );
+ });
+
+ it("exports every stable cursor page exactly once", async () => {
+ const store = getIssueSurfaceViewStore("project:p1");
+ store.getState().setViewMode("table");
+ const first = makeIssue({ id: "issue-1", status: "todo" });
+ const second = makeIssue({ id: "issue-2", status: "done" });
+ const listIssueTableRows = vi
+ .fn()
+ .mockResolvedValueOnce({
+ query_fingerprint: "sha256:export",
+ group_key: null,
+ parent_id: null,
+ total: 2,
+ rows: [{ issue: first, direct_child_count: 0 }],
+ branch_total: 2,
+ next_cursor: "cursor-2",
+ })
+ .mockResolvedValueOnce({
+ query_fingerprint: "sha256:export",
+ group_key: null,
+ parent_id: null,
+ total: 0,
+ rows: [{ issue: second, direct_child_count: 0 }],
+ branch_total: 1,
+ next_cursor: null,
+ });
+ setApiInstance({
+ listIssues,
+ listIssueTableRows,
+ listIssueTableFacets: vi.fn(() => never()),
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => never()),
+ listProperties: vi.fn(() => Promise.resolve({ properties: [] })),
+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),
+ getChildIssueProgress: vi.fn(() => Promise.resolve([])),
+ } as unknown as ApiClient);
+
+ const { result } = renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "project", projectId: "p1" },
+ modes: ["table"],
+ }),
+ { wrapper: makeWrapper(qc, "project:p1") },
+ );
+
+ await expect(result.current.exportTableIssues()).resolves.toEqual([
+ first,
+ second,
+ ]);
+ expect(listIssueTableRows).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ page: { limit: 100, cursor: "cursor-2" } }),
);
- expect(result.current.isEmpty).toBe(false);
});
- it("sends the agents-working filter as a server ids facet so later pages can match", async () => {
+ it("sends the agents-working filter as a backend predicate without sending running ids", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setViewMode("table");
store.getState().toggleAgentRunningFilter();
@@ -543,7 +672,7 @@ describe("useIssueSurfaceController", () => {
getChildIssueProgress: vi.fn(() => never()),
} as unknown as ApiClient);
- renderHook(
+ const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "project", projectId: "p1" },
@@ -552,29 +681,16 @@ describe("useIssueSurfaceController", () => {
{ wrapper: makeWrapper(qc, "project:p1") },
);
- // Before the task snapshot lands the running set is empty — the facet
- // must still be PRESENT (ids: []) so the server returns an empty window
- // instead of every issue.
- await waitFor(() =>
- expect(listIssues).toHaveBeenCalledWith(
- expect.objectContaining({ project_id: "p1", ids: [] }),
- ),
- );
- // Once the snapshot resolves, the window re-keys to the running set.
- await waitFor(() =>
- expect(listIssues).toHaveBeenCalledWith(
- expect.objectContaining({ project_id: "p1", ids: ["issue-running"] }),
- ),
- );
+ expect(result.current.tableQuerySpec.filters.working_only).toBe(true);
+ expect(listIssues).not.toHaveBeenCalled();
});
- it("resolves the working-chip scope from the ids window even while the filter is off", async () => {
+ it("keeps the table working-chip scope unknown without materializing a second issue window", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setViewMode("table");
const running = makeIssue({ id: "issue-running", status: "in_progress" });
- // The running issue lives beyond the loaded page (main window returns
- // nothing); only the ids-facet query can see it. A chip scoped to loaded
- // rows would report 0 here while the filter itself would find the issue.
+ // A running issue may live in an unopened cursor branch. The header must
+ // stay unknown instead of deriving a false zero from visible rows.
listIssues.mockImplementation((params?: ListIssuesParams) =>
Promise.resolve(
params?.ids
@@ -603,18 +719,11 @@ describe("useIssueSurfaceController", () => {
{ wrapper: makeWrapper(qc, "project:p1") },
);
- await waitFor(() => {
- expect(
- result.current.workingScopeIssues?.map((issue) => issue.id),
- ).toEqual(["issue-running"]);
- });
- // The main table window itself stayed unrestricted — the filter is off.
- expect(listIssues).toHaveBeenCalledWith(
- expect.objectContaining({ project_id: "p1", limit: 100, offset: 0 }),
- );
+ await waitFor(() => expect(result.current.workingScopeIssues).toBeUndefined());
+ expect(listIssues).not.toHaveBeenCalled();
});
- it("reports the LATEST page's total so a stale first page cannot re-open the structure ceiling", async () => {
+ it("does not subscribe Table to the legacy offset window", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setViewMode("table");
// page 1 claims a small window (under the ceiling); by page 2 the real
@@ -643,14 +752,12 @@ describe("useIssueSurfaceController", () => {
{ wrapper: makeWrapper(qc, "project:p1") },
);
- await waitFor(() => expect(result.current.flatTotal).toBe(900));
- await act(async () => {
- await result.current.fetchNextFlatPage();
- });
- await waitFor(() => expect(result.current.flatTotal).toBe(50_000));
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.isEmpty).toBe(false);
+ expect(listIssues).not.toHaveBeenCalled();
});
- it("materializes the working window past page one so the chip scope is complete", async () => {
+ it("does not materialize a multi-page working window for Table chrome", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setViewMode("table");
// 101 running issues spread over two pages: presenting page 1 alone as
@@ -695,12 +802,11 @@ describe("useIssueSurfaceController", () => {
{ wrapper: makeWrapper(qc, "project:p1") },
);
- await waitFor(() => {
- expect(result.current.workingScopeIssues).toHaveLength(101);
- });
+ await waitFor(() => expect(result.current.workingScopeIssues).toBeUndefined());
+ expect(listIssues).not.toHaveBeenCalled();
});
- it("never materializes an over-ceiling working window and presents its scope as unknown", async () => {
+ it("never starts a legacy working-window request, regardless of result size", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setViewMode("table");
// The working window shares the MAIN table cache key while the filter is
@@ -744,16 +850,17 @@ describe("useIssueSurfaceController", () => {
{ wrapper: makeWrapper(qc, "project:p1") },
);
- await waitFor(() => expect(idsCalls.length).toBeGreaterThan(0));
- // Give any (buggy) auto-loop a chance to fire before asserting.
+ // Give any accidental auto-loop a chance to fire before asserting.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
- expect(idsCalls).toEqual([0]);
- expect(result.current.workingScopeIssues).toBeUndefined();
+ expect(idsCalls).toEqual([]);
+ await waitFor(() =>
+ expect(result.current.workingScopeIssues).toBeUndefined(),
+ );
});
- it("presents the scope as unknown while a re-keyed working window is still resolving", async () => {
+ it("keeps the Table activity scope unknown across task-snapshot rekeys", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setViewMode("table");
// Running set A resolves to a complete window; then the set changes to B
@@ -795,11 +902,10 @@ describe("useIssueSurfaceController", () => {
{ wrapper: makeWrapper(qc, "project:p1") },
);
- await waitFor(() => {
- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual([
- "run-A",
- ]);
- });
+ await waitFor(() =>
+ expect(result.current.workingScopeIssues).toBeUndefined(),
+ );
+ expect(listIssues).not.toHaveBeenCalled();
// The running set moves to B; B's ids window never resolves in this test.
snapshotIssueId = "run-B";
@@ -814,7 +920,7 @@ describe("useIssueSurfaceController", () => {
});
});
- it("treats a cold-load failure as an error state, not an empty workspace", async () => {
+ it("leaves Table empty/error ownership to the server-backed renderer", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setViewMode("table");
listIssues.mockRejectedValue(new Error("boom"));
@@ -828,12 +934,9 @@ describe("useIssueSurfaceController", () => {
{ wrapper: makeWrapper(qc, "project:p1") },
);
- await waitFor(() => expect(result.current.flatWindowColdError).toBe(true));
- // A failed fetch proves nothing about the window: claiming empty here
- // swaps a 5xx/offline for a "create your first issue" screen (round-5
- // review P2).
+ // The legacy list endpoint is not part of Table rendering anymore.
+ expect(listIssues).not.toHaveBeenCalled();
expect(result.current.isEmpty).toBe(false);
- expect(result.current.flatWindowError).toBe(true);
});
it("clears surface selection when the membership window changes (filters, search)", async () => {
diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.ts
index 3690ca750c..cea17e3d66 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.ts
+++ b/packages/views/issues/surface/use-issue-surface-controller.ts
@@ -1,34 +1,38 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useQuery } from "@tanstack/react-query";
import type { QueryKey } from "@tanstack/react-query";
+import { api } from "@multica/core/api";
import type {
Issue,
IssueAssigneeGroup,
IssueStatus,
+ IssueTableFacetSpec,
+ IssueTableFacetsResponse,
+ IssueTableQuerySpec,
Project,
} from "@multica/core/types";
import { useWorkspaceId } from "@multica/core/hooks";
import { dateOnlyToLocalDate } from "@multica/core/issues/date";
import type {
AssigneeGroupedIssuesFilter,
- IssueFlatFilter,
IssueSortParam,
MyIssuesFilter,
} from "@multica/core/issues/queries";
+import { issueTableFacetsOptions } from "@multica/core/issues/queries";
import {
buildIssueSurfaceQueryPlan,
type IssueSurfaceQueryPlan,
} from "@multica/core/issues/surface/query-plan";
import type { IssueScope } from "@multica/core/issues/surface/scope";
-import { issueSurfaceFlatExportOptions } from "@multica/core/issues/surface/repository";
import type { IssueDateFilter, SortField } from "@multica/core/issues/stores/view-store";
import { propertyListOptions } from "@multica/core/properties";
import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
import type { IssueFilters } from "../utils/filter";
import type { ChildProgress } from "../components/list-row";
+import { IssueTableExportIntegrityError } from "../components/table-view-model";
import type { IssueSurfaceMode } from "./types";
import { useIssueSurfaceActivity, type IssueSurfaceActivity } from "./activity";
import type { IssueSurfaceActions } from "./actions-context";
@@ -87,17 +91,13 @@ export interface IssueSurfaceController {
projectMap: Map<string, Project>;
childProgressMap: Map<string, ChildProgress>;
}>;
- fetchNextFlatPage: () => Promise<unknown>;
- hasNextFlatPage: boolean;
- isFetchingNextFlatPage: boolean;
- flatTotal: number;
- /** See IssueSurfaceData.flatWindowError. */
- flatWindowError: boolean;
- /** See IssueSurfaceData.flatWindowColdError. */
- flatWindowColdError: boolean;
- /** See IssueSurfaceData.refetchFlatWindow. */
- refetchFlatWindow: () => Promise<unknown>;
tableSearch: string;
+ /** Canonical server-owned Table membership. */
+ tableQuerySpec: IssueTableQuerySpec;
+ /** Exact disjunctive counts for the active Table filter submenu. */
+ tableFacetCounts?: IssueTableFacetsResponse;
+ /** Load one Table facet when its filter submenu is opened. */
+ setActiveTableFacet: (facet: IssueTableFacetSpec | null) => void;
setTableSearch: (query: string) => void;
exportTableIssues: () => Promise<Issue[]>;
isLoading: boolean;
@@ -151,7 +151,6 @@ export function useIssueSurfaceController({
createDefaults,
}: UseIssueSurfaceControllerInput): IssueSurfaceController {
const wsId = useWorkspaceId();
- const queryClient = useQueryClient();
const queryPlan = useMemo<IssueSurfaceQueryPlan>(
() => buildIssueSurfaceQueryPlan(scope),
[scope],
@@ -268,62 +267,124 @@ export function useIssueSurfaceController({
const { projectFilters: viewProjectFilters, includeNoProject: viewIncludeNoProject } =
projectFilterState;
- // The agents-working filter is a live client-side signal (WS-driven task
- // snapshot), but the table window is server-paginated — filtering loaded
- // pages would permanently hide matches on unfetched pages (round-2 review
- // P1#1). Send the running set as a server `ids` facet instead: total,
- // pagination, and export all see the same window, and snapshot changes
- // re-key the query. An EMPTY set is sent as an empty facet (empty window),
- // never dropped.
const activity = useIssueSurfaceActivity();
- const sortedRunningIds = useMemo(
- () => [...activity.runningIssueIds].sort(),
- [activity.runningIssueIds],
- );
- const baseTableFacets = useMemo<IssueFlatFilter>(
+ const tableQuerySpec = useMemo<IssueTableQuerySpec>(() => {
+ let queryScope: IssueTableQuerySpec["scope"];
+ switch (scope.type) {
+ case "workspace":
+ queryScope = {
+ kind: "workspace",
+ ...(scope.actorKind === "members"
+ ? { assignee_types: ["member" as const] }
+ : scope.actorKind === "agents"
+ ? { assignee_types: ["agent" as const, "squad" as const] }
+ : {}),
+ };
+ break;
+ case "project":
+ queryScope = { kind: "project", project_id: scope.projectId };
+ break;
+ case "my":
+ queryScope = {
+ kind: "my",
+ relation: scope.relation === "all" ? "any" : scope.relation,
+ };
+ break;
+ case "actor":
+ queryScope = {
+ kind: scope.relation === "assigned" ? "assignee" : "creator",
+ actor: { type: scope.actorType, id: scope.actorId },
+ };
+ break;
+ case "team":
+ throw new Error("Team issue scope is not supported by the Table query");
+ }
+
+ const date =
+ dateParams.date_field && dateParams.date_start && dateParams.date_end
+ ? {
+ field: dateParams.date_field,
+ start: dateParams.date_start,
+ end: dateParams.date_end,
+ }
+ : undefined;
+ return {
+ scope: queryScope,
+ filters: {
+ ...(statusFilters.length > 0 ? { statuses: statusFilters } : {}),
+ ...(priorityFilters.length > 0 ? { priorities: priorityFilters } : {}),
+ ...(assigneeFilters.length > 0 ? { assignees: assigneeFilters } : {}),
+ ...(includeNoAssignee ? { include_no_assignee: true } : {}),
+ ...(creatorFilters.length > 0 ? { creators: creatorFilters } : {}),
+ ...(viewProjectFilters.length > 0
+ ? { project_ids: viewProjectFilters }
+ : {}),
+ ...(viewIncludeNoProject ? { include_no_project: true } : {}),
+ ...(labelFilters.length > 0 ? { label_ids: labelFilters } : {}),
+ ...(Object.keys(effectivePropertyFilters).length > 0
+ ? { properties: effectivePropertyFilters }
+ : {}),
+ ...(date ? { date } : {}),
+ ...(agentRunningFilter ? { working_only: true } : {}),
+ include_sub_issues: showSubIssues,
+ },
+ ...(debouncedTableSearch ? { search: debouncedTableSearch } : {}),
+ sort: {
+ field: sort.sort_by ?? "position",
+ direction: sort.sort_direction ?? "asc",
+ },
+ };
+ }, [
+ agentRunningFilter,
+ assigneeFilters,
+ creatorFilters,
+ dateParams,
+ debouncedTableSearch,
+ effectivePropertyFilters,
+ includeNoAssignee,
+ labelFilters,
+ priorityFilters,
+ scope,
+ showSubIssues,
+ sort.sort_by,
+ sort.sort_direction,
+ statusFilters,
+ viewIncludeNoProject,
+ viewProjectFilters,
+ ]);
+
+ const [activeTableFacet, setActiveTableFacet] =
+ useState<IssueTableFacetSpec | null>(null);
+ const tableFacetRequest = useMemo(
() => ({
- ...(debouncedTableSearch ? { q: debouncedTableSearch } : {}),
- ...(statusFilters.length > 0 ? { statuses: statusFilters } : {}),
- ...(priorityFilters.length > 0 ? { priorities: priorityFilters } : {}),
- ...(assigneeFilters.length > 0
- ? { assignee_filters: assigneeFilters }
- : {}),
- ...(includeNoAssignee ? { include_no_assignee: true } : {}),
- ...(creatorFilters.length > 0
- ? { creator_filters: creatorFilters }
- : {}),
- ...(viewProjectFilters.length > 0
- ? { project_ids: viewProjectFilters }
- : {}),
- ...(viewIncludeNoProject ? { include_no_project: true } : {}),
- ...(labelFilters.length > 0 ? { label_ids: labelFilters } : {}),
- ...(showSubIssues === false ? { top_level_only: true } : {}),
+ query: tableQuerySpec,
+ // The endpoint requires at least one facet. This fallback is never
+ // fetched while activeTableFacet is null; it only keeps the request
+ // shape total for React Query's option factory.
+ facets: [activeTableFacet ?? { kind: "status" as const }],
+ // Filter option badges do not consume the query-wide total; rows/groups
+ // already own the displayed Table total.
+ include_total: false,
}),
- [
- assigneeFilters,
- creatorFilters,
- debouncedTableSearch,
- includeNoAssignee,
- labelFilters,
- priorityFilters,
- showSubIssues,
- statusFilters,
- viewIncludeNoProject,
- viewProjectFilters,
- ],
+ [activeTableFacet, tableQuerySpec],
);
- // The running-restricted variant of the window. It IS the table window
- // while the filter is on; while the filter is off the data hook still
- // subscribes to it (same query key, so toggling the filter hits a warm
- // cache) to give the working chip its authoritative in-window count —
- // deriving that count from loaded rows says "0 working" whenever the only
- // running issue sits on an unfetched page (round-3 review P2#3).
- const workingFacets = useMemo<IssueFlatFilter>(
- () => ({ ...baseTableFacets, ids: sortedRunningIds }),
- [baseTableFacets, sortedRunningIds],
+ const tableFacetsQuery = useQuery({
+ ...issueTableFacetsOptions(wsId, tableFacetRequest),
+ // Counts are only visible inside one open filter submenu. Eagerly loading
+ // every custom-property facet made a Table mount issue up to 47 SQL
+ // statements and repeatedly scan the issue table after invalidation.
+ enabled: usesTable && activeTableFacet !== null,
+ });
+ useEffect(() => {
+ if (!usesTable) setActiveTableFacet(null);
+ }, [usesTable]);
+ const requestActiveTableFacet = useCallback(
+ (facet: IssueTableFacetSpec | null) => {
+ setActiveTableFacet(usesTable ? facet : null);
+ },
+ [usesTable],
);
- const tableFacets = agentRunningFilter ? workingFacets : baseTableFacets;
// Selection is only meaningful within the current membership window: batch
// actions act on selected ids while export/common-field consumers intersect
@@ -380,8 +441,6 @@ export function useIssueSurfaceController({
usesTable,
ganttShowCompleted,
sort,
- tableFacets,
- workingFacets,
activity,
statusFilters,
priorityFilters,
@@ -401,36 +460,82 @@ export function useIssueSurfaceController({
});
const exportTableIssues = useCallback(async () => {
- const exportIssues = await queryClient.fetchQuery(
- issueSurfaceFlatExportOptions(wsId, queryPlan, sort, tableFacets),
- );
- return data.filterIssuesForExport(exportIssues);
- }, [data, queryClient, queryPlan, sort, tableFacets, wsId]);
+ const issues: Issue[] = [];
+ const seenIssueIds = new Set<string>();
+ const seenCursors = new Set<string>();
+ let fingerprint: string | null = null;
+ let expectedTotal: number | null = null;
+ let cursor: string | null = null;
+ do {
+ if (cursor !== null) {
+ if (seenCursors.has(cursor)) throw new IssueTableExportIntegrityError();
+ seenCursors.add(cursor);
+ }
+ const page = await api.listIssueTableRows({
+ query: tableQuerySpec,
+ group: { kind: "none" },
+ group_key: null,
+ hierarchy: { enabled: false },
+ parent_id: null,
+ page: { limit: 100, cursor },
+ });
+ // parseWithFallback deliberately protects interactive views from schema
+ // drift with an empty response. Export must fail closed instead: an empty
+ // fingerprint is the fallback sentinel and must never create a truncated
+ // CSV that looks successful.
+ if (!page.query_fingerprint) throw new IssueTableExportIntegrityError();
+ fingerprint ??= page.query_fingerprint;
+ if (cursor === null) expectedTotal = page.total;
+ if (
+ page.query_fingerprint !== fingerprint ||
+ page.group_key !== null ||
+ page.parent_id !== null
+ ) {
+ throw new IssueTableExportIntegrityError();
+ }
+ for (const row of page.rows) {
+ if (seenIssueIds.has(row.issue.id)) {
+ throw new IssueTableExportIntegrityError();
+ }
+ seenIssueIds.add(row.issue.id);
+ issues.push(row.issue);
+ }
+ cursor = page.next_cursor;
+ } while (cursor);
+ if (issues.length !== (expectedTotal ?? 0)) {
+ throw new IssueTableExportIntegrityError();
+ }
+ return issues;
+ }, [tableQuerySpec]);
const { actions, openCreateIssue, moveIssue } = useIssueSurfaceActions({
createDefaults: resolvedCreateDefaults,
});
- const { filterIssuesForExport: _filterIssuesForExport, ...surfaceData } = data;
-
return {
scopeKey,
projectId,
createDefaults: resolvedCreateDefaults,
viewMode: effectiveViewMode,
allowGantt: allowedModes.has("gantt") && !!projectId,
- ...surfaceData,
+ ...data,
// Keep TableView mounted for an empty search result so its local search
// control remains available to refine or clear the query. Include the
// debounced value as well to avoid a brief empty-screen flash while a
// cleared query is waiting to re-fetch the unsearched window.
isEmpty:
- surfaceData.isEmpty &&
+ data.isEmpty &&
!(usesTable && (tableSearch.trim() || debouncedTableSearch)),
sort,
actions,
selection,
tableSearch,
+ tableQuerySpec,
+ tableFacetCounts:
+ usesTable && activeTableFacet !== null
+ ? tableFacetsQuery.data
+ : undefined,
+ setActiveTableFacet: requestActiveTableFacet,
setTableSearch,
openCreateIssue,
moveIssue,
diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.ts
index 4407370347..7bf35aeb98 100644
--- a/packages/views/issues/surface/use-issue-surface-data.ts
+++ b/packages/views/issues/surface/use-issue-surface-data.ts
@@ -1,8 +1,7 @@
"use client";
-import { useCallback, useEffect, useMemo } from "react";
+import { useCallback, useMemo } from "react";
import {
- useInfiniteQuery,
useQuery,
type QueryKey,
} from "@tanstack/react-query";
@@ -12,13 +11,11 @@ import { projectListOptions } from "@multica/core/projects/queries";
import {
childIssueProgressOptions,
type AssigneeGroupedIssuesFilter,
- type IssueFlatFilter,
type IssueSortParam,
type MyIssuesFilter,
} from "@multica/core/issues/queries";
import {
issueSurfaceAssigneeGroupsOptions,
- issueSurfaceFlatOptions,
issueSurfaceGanttOptions,
issueSurfaceListOptions,
} from "@multica/core/issues/surface/repository";
@@ -30,7 +27,6 @@ import {
type IssueFilterState,
type IssueFilters,
} from "../utils/filter";
-import { shouldAutoLoadNextWindowPage } from "../components/table-view-model";
import type { ChildProgress } from "../components/list-row";
import type { IssueSurfaceActivity } from "./activity";
@@ -65,13 +61,10 @@ export interface IssueSurfaceData {
projectIssues: Issue[];
issues: Issue[];
swimlaneIssues: Issue[];
- /** The rows the agents-working filter would leave on screen — or
- * `undefined` when that set is genuinely UNKNOWN (table mode while the
- * ids-facet window is still resolving, failed, or too large to
- * materialize). Consumers must present unknown as unknown; substituting
- * another incomplete window would publish a precise-looking wrong number
- * (round-5 review P2). See the `workingScopeIssues` memo for why the known
- * case is a projection of the render pipeline. */
+ /** The rows the agents-working filter would leave on screen. `undefined`
+ * means the set is genuinely unknown: Table membership is server-owned,
+ * and the activity chip must not reconstruct a complete issue window just
+ * to decorate the header. */
workingScopeIssues: Issue[] | undefined;
filteredGanttIssues: Issue[];
assigneeGroups?: IssueAssigneeGroup[];
@@ -94,23 +87,6 @@ export interface IssueSurfaceData {
projectMap: Map<string, Project>;
childProgressMap: Map<string, ChildProgress>;
}>;
- fetchNextFlatPage: () => Promise<unknown>;
- hasNextFlatPage: boolean;
- isFetchingNextFlatPage: boolean;
- flatTotal: number;
- /** The flat window query is in error state (initial or next-page fetch,
- * retries exhausted). Auto-advance loops MUST stop on this — re-firing
- * after every failed attempt is a request storm — and surface an explicit
- * Retry instead. */
- flatWindowError: boolean;
- /** The flat window failed before producing ANY data (cold load, retries
- * exhausted). This is NOT an empty workspace: isEmpty stays false and the
- * surface must render an error state with a Retry instead of the
- * create-issue empty state (round-5 review P2). */
- flatWindowColdError: boolean;
- /** Explicit recovery for flatWindowColdError — refetches the flat window. */
- refetchFlatWindow: () => Promise<unknown>;
- filterIssuesForExport: (issues: Issue[]) => Issue[];
isLoading: boolean;
/** The window's data is being revalidated while the previous snapshot is
* shown as a placeholder (sort/date change, or any grouped-board filter
@@ -129,8 +105,6 @@ export function useIssueSurfaceData({
usesTable,
ganttShowCompleted,
sort,
- tableFacets,
- workingFacets,
activity,
statusFilters,
priorityFilters,
@@ -155,11 +129,6 @@ export function useIssueSurfaceData({
* rows without it, so the working scope has to honour it too. */
ganttShowCompleted: boolean;
sort: IssueSortParam;
- tableFacets: IssueFlatFilter;
- /** tableFacets restricted to the running set (ids facet) — the working
- * chip's authoritative scope, and the table window itself while the
- * agents-working filter is on (identical query key in that state). */
- workingFacets: IssueFlatFilter;
/** Owned by the controller so the agents-working facet and the client
* display filters read the same task snapshot. */
activity: IssueSurfaceActivity;
@@ -225,97 +194,7 @@ export function useIssueSurfaceData({
...issueSurfaceGanttOptions(wsId, projectId ?? ""),
enabled: usesGantt,
});
- const flatIssuesQuery = useInfiniteQuery({
- ...issueSurfaceFlatOptions(wsId, queryPlan, sort, tableFacets),
- enabled: usesTable,
- });
-
- const flatIssues = useMemo(
- () =>
- flatIssuesQuery.data?.pages.flatMap((page) => page.issues) ??
- EMPTY_ISSUES,
- [flatIssuesQuery.data?.pages],
- );
- const { fetchNextPage: fetchNextFlatPage } = flatIssuesQuery;
- const fetchNextFlatPageNoCancel = useCallback(
- () => fetchNextFlatPage({ cancelRefetch: false }),
- [fetchNextFlatPage],
- );
- // The LATEST page's total, not page 1's: totals drift while concurrent
- // writes land, and the pagination protocol itself advances on the latest
- // page's total — a consumer holding page 1's stale (smaller) total while
- // hasNextPage kept advancing is how the structure ceiling stopped being a
- // hard limit (round-4 review P1#2).
- const flatPages = flatIssuesQuery.data?.pages;
- const flatTotal = flatPages?.[flatPages.length - 1]?.total ?? 0;
-
- // Running-restricted window — the table branch of the workingScopeIssues
- // projection below. While the agents-working filter is on this observer
- // shares the main flat query's key (one fetch); while it is off, it keeps
- // the filter's window warm and gives the chip its authoritative scope.
const hasRunningIssues = activity.runningIssueIds.size > 0;
- const workingWindowEnabled = usesTable && hasRunningIssues;
- const workingWindowQuery = useInfiniteQuery({
- ...issueSurfaceFlatOptions(wsId, queryPlan, sort, workingFacets),
- enabled: workingWindowEnabled,
- });
- // Materialize the running window ONLY under the same hard gates as the
- // structure loop — while the agents-working filter is on this query IS the
- // main table window (shared key), so an ungated chip-driven loop would
- // stuff the main cache past the very ceiling TableView just enforced, and
- // the running set has no server-side size bound (round-5 review P1). Under
- // the gates the loop is bounded: an over-ceiling window stops after page 1
- // (fresh total > ceiling) and presents as UNKNOWN instead of a number; an
- // error stops the loop the same way.
- //
- // Ownership: this effect drives the query ONLY while the filter is OFF
- // (background chip scope). Once the filter is on, the shared query already
- // has pagination owners — TableView's structure loop and the scroll
- // sentinel — and a second responder issuing fetchNextPage() from the same
- // render snapshot cancel/restarts the first one's fetch. The abandoned
- // HTTP request is not abortable (the queryFn does not thread AbortSignal),
- // so every offset would be requested twice (round-6 review R1).
- const {
- hasNextPage: workingWindowHasNext,
- isFetchingNextPage: workingWindowFetchingNext,
- isError: workingWindowError,
- isPlaceholderData: workingWindowIsPlaceholder,
- fetchNextPage: fetchNextWorkingWindowPage,
- } = workingWindowQuery;
- const workingWindowPages = workingWindowQuery.data?.pages;
- const workingWindowTotal =
- workingWindowPages?.[workingWindowPages.length - 1]?.total ?? 0;
- const workingWindowLoaded = useMemo(
- () =>
- workingWindowPages?.reduce((count, page) => count + page.issues.length, 0) ??
- 0,
- [workingWindowPages],
- );
- useEffect(() => {
- if (
- shouldAutoLoadNextWindowPage({
- windowWanted: workingWindowEnabled && !agentRunningFilter,
- total: workingWindowTotal,
- loadedCount: workingWindowLoaded,
- hasNextPage: workingWindowHasNext,
- isFetchingNextPage: workingWindowFetchingNext,
- hasError: workingWindowError,
- })
- ) {
- // cancelRefetch: false — if some other observer already has a fetch in
- // flight for this query, do nothing rather than cancel/restart it.
- void fetchNextWorkingWindowPage({ cancelRefetch: false });
- }
- }, [
- agentRunningFilter,
- fetchNextWorkingWindowPage,
- workingWindowEnabled,
- workingWindowError,
- workingWindowFetchingNext,
- workingWindowHasNext,
- workingWindowLoaded,
- workingWindowTotal,
- ]);
const bucketedIssues = useMemo(() => {
return usesAssigneeBoard
? (assigneeGroupsQuery.data?.groups.flatMap((group) => group.issues) ?? [])
@@ -331,7 +210,7 @@ export function useIssueSurfaceData({
const surfaceIssues = usesGantt
? ganttIssues
: usesTable
- ? flatIssues
+ ? EMPTY_ISSUES
: bucketedIssues;
const baseFilterState = useMemo<IssueFilterState>(
@@ -367,11 +246,6 @@ export function useIssueSurfaceData({
() => applyIssueFilters(surfaceIssues, baseFilterState, filterContext),
[baseFilterState, filterContext, surfaceIssues],
);
- const filterIssuesForExport = useCallback(
- (exportIssues: Issue[]) =>
- applyIssueFilters(exportIssues, baseFilterState, filterContext),
- [baseFilterState, filterContext],
- );
const statuslessFilterState = useMemo<IssueFilterState>(
() => ({
@@ -437,10 +311,8 @@ export function useIssueSurfaceData({
// IssueSurface renders:
// - gantt → the canvas set (scheduled + dated + showCompleted)
// - assignee board → the grouped response, not the flat list
- // - table → the ids-facet window (the query the filter itself
- // runs) — the table's offset pages are only a SLICE of its window, so
- // a loaded-rows projection says "nothing working" whenever the running
- // issues sit on unfetched pages (round-3 review P2#3)
+ // - table → unknown unless the running set is empty; Table uses
+ // server cursor branches and never materializes a second full window
// - board / list / swimlane → the flat filtered list
//
// Swimlane deliberately has no branch: SwimLaneView draws its cards from
@@ -469,33 +341,14 @@ export function useIssueSurfaceData({
).flatMap((group) => group.issues);
}
if (usesTable) {
- // The table's loaded pages are only a SLICE of its window, so no
- // fallback to them can honestly claim a precise working set. The scope
- // is either the COMPLETE ids-facet window (fetched to the end for THIS
- // key, no error), an empty running set (trivially complete without a
- // request), or UNKNOWN — resolving, failed, or over the
- // materialization ceiling (round-5 review P2). Consumers render
- // unknown as unknown; they never get a number to mis-present.
- //
- // Placeholder data is explicitly EXCLUDED from completeness: on a
- // re-key (running set or facet change) keepPreviousData shows the OLD
- // key's window, and pairing those rows with the NEW task snapshot
- // publishes a precise-looking number for a scope nobody fetched —
- // including re-publishing a ceiling-capped old window as if it were
- // complete (round-6 review P2#1). While the new key resolves, the
- // scope is unknown.
+ // Table membership is server-owned and cursor paged. Do not rebuild a
+ // second complete issue window merely to decorate the activity chip:
+ // that was the final hidden auto-materialization loop behind the old
+ // 1,000-row ceiling. An empty task set is trivially known; otherwise
+ // keep the chip indeterminate until a bounded server facet supplies
+ // the matching task/issue projection.
if (!hasRunningIssues) return EMPTY_ISSUES;
- const workingWindowComplete =
- workingWindowQuery.data !== undefined &&
- !workingWindowIsPlaceholder &&
- !workingWindowHasNext &&
- !workingWindowError;
- if (!workingWindowComplete) return undefined;
- return applyIssueFilters(
- workingWindowQuery.data.pages.flatMap((page) => page.issues),
- { ...baseFilterState, workingOnly: true },
- filterContext,
- );
+ return undefined;
}
return applyIssueFilters(
surfaceIssues,
@@ -516,10 +369,6 @@ export function useIssueSurfaceData({
usesAssigneeBoard,
usesGantt,
usesTable,
- workingWindowError,
- workingWindowHasNext,
- workingWindowIsPlaceholder,
- workingWindowQuery.data,
]);
const {
@@ -621,7 +470,7 @@ export function useIssueSurfaceData({
: usesGantt
? ganttIssuesQuery.isLoading
: usesTable
- ? flatIssuesQuery.isLoading
+ ? false
: statusIssuesQuery.isLoading;
// Placeholder-backed revalidation of the ACTIVE query only. First loads are
@@ -632,7 +481,7 @@ export function useIssueSurfaceData({
: usesGantt
? false
: usesTable
- ? flatIssuesQuery.isPlaceholderData
+ ? false
: statusIssuesQuery.isPlaceholderData;
return {
@@ -658,19 +507,6 @@ export function useIssueSurfaceData({
childProgressMap,
projectMap,
resolveTableExportLookups,
- // cancelRefetch: false — the structure loop and the scroll sentinel are
- // independent responders on this query; the default cancel/restart
- // semantics turn a same-snapshot double call into a duplicated HTTP
- // request, because the abandoned fetch is not abortable (the queryFn
- // does not thread AbortSignal) (round-6 review R1).
- fetchNextFlatPage: fetchNextFlatPageNoCancel,
- hasNextFlatPage: flatIssuesQuery.hasNextPage ?? false,
- isFetchingNextFlatPage: flatIssuesQuery.isFetchingNextPage,
- flatTotal,
- flatWindowError: flatIssuesQuery.isError,
- flatWindowColdError: flatIssuesQuery.isError && flatIssuesQuery.data === undefined,
- refetchFlatWindow: flatIssuesQuery.refetch,
- filterIssuesForExport,
isLoading,
isRefreshing,
// isEmpty asserts "this window has no issues". The board/list/swimlane
@@ -679,15 +515,12 @@ export function useIssueSurfaceData({
// window is empty, so never claim it (same "uncertain → don't assert"
// rule as surface membership). GanttView renders its own accurate
// "no scheduled issues" empty state instead of the generic create-issue
- // one. A FAILED table fetch proves nothing either: total defaults to 0
- // after a cold-load error, and claiming empty there swaps a 5xx/offline
- // for a "create your first issue" screen with no recovery path (round-5
- // review P2) — only a successful zero-result window is empty.
+ // one. Table owns its own branch-level loading, empty and retry states,
+ // so this shared legacy surface projection never asserts Table empty.
isEmpty:
!isLoading &&
!usesGantt &&
- (usesTable
- ? !flatIssuesQuery.isError && flatTotal === 0
- : surfaceIssues.length === 0),
+ !usesTable &&
+ surfaceIssues.length === 0,
};
}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index c5466cd7bb..1197ac8acf 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -128,9 +128,14 @@
"load_failed": "Failed to load issues.",
"load_failed_retry": "Retry",
"load_more_failed_retry": "Loading more failed — Retry",
+ "load_more": "Load more",
+ "loading_branch": "Loading…",
+ "value_unavailable": "Unavailable value",
+ "group_property_unavailable": "The grouped property is no longer available. Grouping was cleared.",
"hierarchy": "Hierarchy",
"hierarchy_description": "Nest sub-issues beneath their parents",
"group_label": "Group",
+ "group_active": "Group: {{group}}",
"group_none": "No grouping",
"export": "Export",
"export_all": "Export all",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 39a822b8d7..ee6db35179 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -126,9 +126,14 @@
"load_failed": "イシューを読み込めませんでした。",
"load_failed_retry": "再試行",
"load_more_failed_retry": "続きの読み込みに失敗しました — 再試行",
+ "load_more": "さらに読み込む",
+ "loading_branch": "読み込み中…",
+ "value_unavailable": "利用できない値",
+ "group_property_unavailable": "グループ化に使っていたプロパティは利用できないため、グループ化を解除しました。",
"hierarchy": "階層",
"hierarchy_description": "サブイシューを親イシューの下に入れ子で表示",
"group_label": "グループ",
+ "group_active": "グループ:{{group}}",
"group_none": "グループ化なし",
"export": "エクスポート",
"export_all": "すべてエクスポート",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 2839f3b8d0..0f02cf480d 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -126,9 +126,14 @@
"load_failed": "이슈를 불러오지 못했습니다.",
"load_failed_retry": "다시 시도",
"load_more_failed_retry": "추가 항목을 불러오지 못했습니다 — 다시 시도",
+ "load_more": "더 불러오기",
+ "loading_branch": "불러오는 중…",
+ "value_unavailable": "사용할 수 없는 값",
+ "group_property_unavailable": "그룹화에 사용한 속성을 더 이상 사용할 수 없어 그룹화를 해제했습니다.",
"hierarchy": "계층",
"hierarchy_description": "하위 이슈를 상위 이슈 아래에 중첩해 표시",
"group_label": "그룹",
+ "group_active": "그룹: {{group}}",
"group_none": "그룹화 안 함",
"export": "내보내기",
"export_all": "모두 내보내기",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 9fae18b921..24f5b84705 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -126,9 +126,14 @@
"load_failed": "加载 issue 失败。",
"load_failed_retry": "重试",
"load_more_failed_retry": "加载更多失败——重试",
+ "load_more": "加载更多",
+ "loading_branch": "加载中…",
+ "value_unavailable": "不可用的值",
+ "group_property_unavailable": "用于分组的属性已不可用,分组已清除。",
"hierarchy": "层级",
"hierarchy_description": "将子 issue 嵌套显示在父 issue 下方",
"group_label": "分组",
+ "group_active": "分组:{{group}}",
"group_none": "不分组",
"export": "导出",
"export_all": "导出全部",
diff --git a/packages/views/my-issues/components/my-issues-header.tsx b/packages/views/my-issues/components/my-issues-header.tsx
index 4da0c40d03..77cc4b631d 100644
--- a/packages/views/my-issues/components/my-issues-header.tsx
+++ b/packages/views/my-issues/components/my-issues-header.tsx
@@ -10,7 +10,11 @@ import {
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
-import type { Issue } from "@multica/core/types";
+import type {
+ Issue,
+ IssueTableFacetSpec,
+ IssueTableFacetsResponse,
+} from "@multica/core/types";
import type { MyIssuesScope } from "@multica/core/issues/stores/my-issues-view-store";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
import { useT } from "../../i18n";
@@ -27,6 +31,8 @@ export function MyIssuesHeader({
onScopeChange,
isRefreshing = false,
facetCountsExact = true,
+ tableFacetCounts,
+ onTableFacetChange,
}: {
allIssues: Issue[];
/** The rows the agents-working filter would leave on screen — undefined
@@ -38,6 +44,8 @@ export function MyIssuesHeader({
isRefreshing?: boolean;
/** See IssueDisplayControls.facetCountsExact. */
facetCountsExact?: boolean;
+ tableFacetCounts?: IssueTableFacetsResponse;
+ onTableFacetChange: (facet: IssueTableFacetSpec | null) => void;
}) {
const { t } = useT("my-issues");
const { t: tIssues } = useT("issues");
@@ -121,6 +129,8 @@ export function MyIssuesHeader({
<IssueDisplayControls
scopedIssues={allIssues}
facetCountsExact={facetCountsExact}
+ tableFacetCounts={tableFacetCounts}
+ onTableFacetChange={onTableFacetChange}
/>
<ViewRefreshIndicator active={isRefreshing} />
</div>
diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsx
index a1055131fe..c0dd7fd00a 100644
--- a/packages/views/my-issues/components/my-issues-page.tsx
+++ b/packages/views/my-issues/components/my-issues-page.tsx
@@ -45,9 +45,9 @@ export function MyIssuesPage() {
scope={scope}
onScopeChange={setScope}
isRefreshing={controller.isRefreshing}
- facetCountsExact={
- !(controller.viewMode === "table" && controller.hasNextFlatPage)
- }
+ facetCountsExact={controller.viewMode !== "table"}
+ tableFacetCounts={controller.tableFacetCounts}
+ onTableFacetChange={controller.setActiveTableFacet}
/>
)}
renderEmpty={() => (
diff --git a/packages/views/skills/components/runtime-local-skill-import-panel.test.tsx b/packages/views/skills/components/runtime-local-skill-import-panel.test.tsx
index 1cb30d02a7..3ca717d9a5 100644
--- a/packages/views/skills/components/runtime-local-skill-import-panel.test.tsx
+++ b/packages/views/skills/components/runtime-local-skill-import-panel.test.tsx
@@ -54,6 +54,20 @@ vi.mock("sonner", () => ({
},
}));
+vi.mock("motion/react", () => ({
+ AnimatePresence: ({ children }: { children: ReactNode }) => children,
+ motion: {
+ div: ({
+ children,
+ className,
+ }: {
+ children: ReactNode;
+ className?: string;
+ }) => <div className={className}>{children}</div>,
+ },
+ useReducedMotion: () => true,
+}));
+
import { RuntimeLocalSkillImportPanel } from "./runtime-local-skill-import-panel";
function I18nWrapper({ children }: { children: ReactNode }) {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index f4d8b0f2e5..b9b3389acd 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1034,6 +1034,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Issues
r.Route("/api/issues", func(r chi.Router) {
+ r.Post("/table/groups", h.ListIssueTableGroups)
+ r.Post("/table/rows", h.ListIssueTableRows)
+ r.Post("/table/facets", h.ListIssueTableFacets)
r.Get("/search", h.SearchIssues)
r.Get("/child-progress", h.ChildIssueProgress)
r.Get("/children", h.ListChildrenByParents)
diff --git a/server/internal/handler/issue_table_facets.go b/server/internal/handler/issue_table_facets.go
new file mode 100644
index 0000000000..8023e7fee1
--- /dev/null
+++ b/server/internal/handler/issue_table_facets.go
@@ -0,0 +1,367 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "sort"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+ "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"
+)
+
+// The workspace property catalog is capped at 20 active definitions. Six
+// built-in dimensions plus that catalog fit under this guard with headroom,
+// while preventing a single request from scheduling hundreds of sequential
+// aggregation scans inside one snapshot transaction.
+const issueTableMaxFacets = 32
+
+type issueTableFacetValueResponse struct {
+ Key string `json:"key"`
+ Count int64 `json:"count"`
+}
+
+type issueTableFacetResponse struct {
+ Kind string `json:"kind"`
+ PropertyID string `json:"property_id,omitempty"`
+ Values []issueTableFacetValueResponse `json:"values"`
+}
+
+type issueTableFacetsResponse struct {
+ QueryFingerprint string `json:"query_fingerprint"`
+ Total int64 `json:"total"`
+ Facets []issueTableFacetResponse `json:"facets"`
+}
+
+func issueTableQueryWithoutFacet(input issueTableQuerySpec, facet issueTableFacetSpec) issueTableQuerySpec {
+ output := input
+ output.Filters = input.Filters
+ if input.Filters.Properties != nil {
+ output.Filters.Properties = make(map[string][]string, len(input.Filters.Properties))
+ for propertyID, values := range input.Filters.Properties {
+ output.Filters.Properties[propertyID] = append([]string(nil), values...)
+ }
+ }
+
+ switch facet.Kind {
+ case "status":
+ output.Filters.Statuses = nil
+ case "priority":
+ output.Filters.Priorities = nil
+ case "assignee":
+ output.Filters.Assignees = nil
+ output.Filters.IncludeNoAssignee = false
+ case "creator":
+ output.Filters.Creators = nil
+ case "project":
+ output.Filters.ProjectIDs = nil
+ output.Filters.IncludeNoProject = false
+ case "label":
+ output.Filters.LabelIDs = nil
+ case "property":
+ delete(output.Filters.Properties, facet.PropertyID)
+ }
+ return output
+}
+
+func issueTableFacetIdentity(facet issueTableFacetSpec) string {
+ if facet.Kind == "property" {
+ return "property:" + facet.PropertyID
+ }
+ return facet.Kind
+}
+
+func issueTableBaseFacetExpression(query issueTableQuerySpec, facet issueTableFacetSpec) (string, bool) {
+ switch facet.Kind {
+ case "status":
+ return "i.status", len(query.Filters.Statuses) == 0
+ case "priority":
+ return "i.priority", len(query.Filters.Priorities) == 0
+ case "assignee":
+ return "CASE WHEN i.assignee_type IS NULL OR i.assignee_id IS NULL THEN '__none__' ELSE i.assignee_type || ':' || i.assignee_id::text END", len(query.Filters.Assignees) == 0 && !query.Filters.IncludeNoAssignee
+ case "creator":
+ return "i.creator_type || ':' || i.creator_id::text", len(query.Filters.Creators) == 0
+ case "project":
+ return "COALESCE(i.project_id::text, '__none__')", len(query.Filters.ProjectIDs) == 0 && !query.Filters.IncludeNoProject
+ default:
+ return "", false
+ }
+}
+
+func (h *Handler) issueTableBaseFacetQuery(
+ w http.ResponseWriter,
+ r *http.Request,
+ base issueTableSQL,
+ requestQuery issueTableQuerySpec,
+ facets []issueTableFacetSpec,
+ includeTotal bool,
+) (map[string]issueTableFacetResponse, int64, bool) {
+ markerCases := make([]string, 0, len(facets))
+ valueCases := make([]string, 0, len(facets))
+ groupingSets := make([]string, 0, len(facets)+1)
+ responses := make(map[string]issueTableFacetResponse, len(facets))
+ for _, facet := range facets {
+ expression, ok := issueTableBaseFacetExpression(requestQuery, facet)
+ if !ok {
+ writeIssueTableQueryFailure(w, r, "failed to batch table facets")
+ return nil, 0, false
+ }
+ identity := issueTableFacetIdentity(facet)
+ markerCases = append(markerCases, fmt.Sprintf("WHEN GROUPING(%s) = 0 THEN '%s'", expression, identity))
+ valueCases = append(valueCases, fmt.Sprintf("WHEN GROUPING(%s) = 0 THEN (%s)::text", expression, expression))
+ groupingSets = append(groupingSets, "("+expression+")")
+ responses[identity] = issueTableFacetResponse{
+ Kind: facet.Kind,
+ PropertyID: facet.PropertyID,
+ Values: []issueTableFacetValueResponse{},
+ }
+ }
+ if includeTotal {
+ groupingSets = append(groupingSets, "()")
+ }
+
+ query := fmt.Sprintf(`SELECT CASE %s ELSE '__total__' END,
+ CASE %s ELSE '' END,
+ COUNT(*)::bigint
+FROM issue i
+WHERE %s
+GROUP BY GROUPING SETS (%s)`, strings.Join(markerCases, " "), strings.Join(valueCases, " "), base.where, strings.Join(groupingSets, ", "))
+ rows, err := h.DB.Query(r.Context(), query, base.args...)
+ if err != nil {
+ slog.Warn("ListIssueTableFacets batch query failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to list table facets")
+ return nil, 0, false
+ }
+ defer rows.Close()
+
+ var total int64
+ for rows.Next() {
+ var identity string
+ var value string
+ var count int64
+ if err := rows.Scan(&identity, &value, &count); err != nil {
+ writeIssueTableQueryFailure(w, r, "failed to list table facets")
+ return nil, 0, false
+ }
+ if identity == "__total__" {
+ total = count
+ continue
+ }
+ response, ok := responses[identity]
+ if !ok {
+ writeIssueTableQueryFailure(w, r, "failed to list table facets")
+ return nil, 0, false
+ }
+ response.Values = append(response.Values, issueTableFacetValueResponse{Key: value, Count: count})
+ responses[identity] = response
+ }
+ if err := rows.Err(); err != nil {
+ writeIssueTableQueryFailure(w, r, "failed to list table facets")
+ return nil, 0, false
+ }
+ for identity, response := range responses {
+ sort.Slice(response.Values, func(i, j int) bool {
+ return strings.Compare(response.Values[i].Key, response.Values[j].Key) < 0
+ })
+ responses[identity] = response
+ }
+ return responses, total, true
+}
+
+func (h *Handler) issueTableFacetQuery(w http.ResponseWriter, r *http.Request, requestQuery issueTableQuerySpec, facet issueTableFacetSpec) (issueTableFacetResponse, bool) {
+ response := issueTableFacetResponse{Kind: facet.Kind, PropertyID: facet.PropertyID, Values: []issueTableFacetValueResponse{}}
+ compiled, ok := h.compileIssueTableQuery(w, r, issueTableQueryWithoutFacet(requestQuery, facet))
+ if !ok {
+ return response, false
+ }
+
+ query := ""
+ switch facet.Kind {
+ case "status":
+ query = fmt.Sprintf(`SELECT i.status, COUNT(*)::bigint FROM issue i WHERE %s GROUP BY i.status`, compiled.where)
+ case "priority":
+ query = fmt.Sprintf(`SELECT i.priority, COUNT(*)::bigint FROM issue i WHERE %s GROUP BY i.priority`, compiled.where)
+ case "assignee":
+ query = fmt.Sprintf(`SELECT CASE WHEN i.assignee_type IS NULL OR i.assignee_id IS NULL THEN '__none__' ELSE i.assignee_type || ':' || i.assignee_id::text END, COUNT(*)::bigint FROM issue i WHERE %s GROUP BY 1`, compiled.where)
+ case "creator":
+ query = fmt.Sprintf(`SELECT i.creator_type || ':' || i.creator_id::text, COUNT(*)::bigint FROM issue i WHERE %s GROUP BY 1`, compiled.where)
+ case "project":
+ query = fmt.Sprintf(`SELECT COALESCE(i.project_id::text, '__none__'), COUNT(*)::bigint FROM issue i WHERE %s GROUP BY 1`, compiled.where)
+ case "label":
+ query = fmt.Sprintf(`SELECT itl.label_id::text, COUNT(DISTINCT i.id)::bigint FROM issue i JOIN issue_to_label itl ON itl.issue_id = i.id WHERE %s GROUP BY itl.label_id`, compiled.where)
+ case "property":
+ propertyID, err := util.ParseUUID(facet.PropertyID)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid facets.property_id")
+ return response, false
+ }
+ property, err := h.Queries.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{
+ ID: propertyID,
+ WorkspaceID: compiled.workspaceID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeIssueTableUnsupportedGroup(w, "property_not_found", "The faceted property no longer exists.")
+ return response, false
+ }
+ slog.Warn("resolve table facet property failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to resolve table facet")
+ return response, false
+ }
+ if property.ArchivedAt.Valid {
+ writeIssueTableUnsupportedGroup(w, "property_archived", "The faceted property is archived.")
+ return response, false
+ }
+ propertyKey := "'" + util.UUIDToString(property.ID) + "'"
+ switch property.Type {
+ case "select":
+ query = fmt.Sprintf(`SELECT i.properties ->> %s, COUNT(*)::bigint FROM issue i WHERE %s AND jsonb_typeof(i.properties -> %s) = 'string' GROUP BY 1`, propertyKey, compiled.where, propertyKey)
+ case "multi_select":
+ query = fmt.Sprintf(`SELECT property_value.value, COUNT(DISTINCT i.id)::bigint FROM issue i JOIN LATERAL jsonb_array_elements_text(CASE WHEN jsonb_typeof(i.properties -> %s) = 'array' THEN i.properties -> %s ELSE '[]'::jsonb END) AS property_value(value) ON TRUE WHERE %s GROUP BY property_value.value`, propertyKey, propertyKey, compiled.where)
+ case "checkbox":
+ query = fmt.Sprintf(`SELECT i.properties ->> %s, COUNT(*)::bigint FROM issue i WHERE %s AND jsonb_typeof(i.properties -> %s) = 'boolean' GROUP BY 1`, propertyKey, compiled.where, propertyKey)
+ default:
+ writeIssueTableUnsupportedGroup(w, "property_type_unsupported", "This property type cannot be used as a filter facet.")
+ return response, false
+ }
+ default:
+ writeError(w, http.StatusBadRequest, "invalid facets.kind")
+ return response, false
+ }
+
+ rows, err := h.DB.Query(r.Context(), query, compiled.args...)
+ if err != nil {
+ slog.Warn("ListIssueTableFacets query failed", append(logger.RequestAttrs(r), "facet", issueTableFacetIdentity(facet), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to list table facets")
+ return response, false
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var value string
+ var count int64
+ if err := rows.Scan(&value, &count); err != nil {
+ writeIssueTableQueryFailure(w, r, "failed to list table facets")
+ return response, false
+ }
+ response.Values = append(response.Values, issueTableFacetValueResponse{Key: value, Count: count})
+ }
+ if err := rows.Err(); err != nil {
+ writeIssueTableQueryFailure(w, r, "failed to list table facets")
+ return response, false
+ }
+ sort.Slice(response.Values, func(i, j int) bool {
+ return strings.Compare(response.Values[i].Key, response.Values[j].Key) < 0
+ })
+ return response, true
+}
+
+func (h *Handler) ListIssueTableFacets(w http.ResponseWriter, r *http.Request) {
+ if h.DB == nil {
+ writeError(w, http.StatusInternalServerError, "database is unavailable")
+ return
+ }
+ var request issueTableFacetsRequest
+ if !decodeIssueTableJSON(w, r, &request) {
+ return
+ }
+ if len(request.Facets) == 0 || len(request.Facets) > issueTableMaxFacets {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("facets must contain between 1 and %d entries", issueTableMaxFacets))
+ return
+ }
+ r, cancel := withIssueTableQueryTimeout(r)
+ defer cancel()
+ snapshot, tx, err := h.beginIssueTableSnapshot(r.Context())
+ if err != nil {
+ slog.Warn("ListIssueTableFacets snapshot failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to start table query")
+ return
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback(context.Background())
+ }
+ }()
+ h = snapshot
+
+ base, ok := h.compileIssueTableQuery(w, r, request.Query)
+ if !ok {
+ return
+ }
+
+ seen := make(map[string]struct{}, len(request.Facets))
+ normalizedFacets := make([]issueTableFacetSpec, len(request.Facets))
+ for index, facet := range request.Facets {
+ facet.Kind = strings.TrimSpace(facet.Kind)
+ facet.PropertyID = strings.TrimSpace(facet.PropertyID)
+ identity := issueTableFacetIdentity(facet)
+ if _, exists := seen[identity]; exists {
+ writeError(w, http.StatusBadRequest, "duplicate table facet")
+ return
+ }
+ seen[identity] = struct{}{}
+ normalizedFacets[index] = facet
+ }
+
+ includeTotal := request.IncludeTotal == nil || *request.IncludeTotal
+ batchFacets := make([]issueTableFacetSpec, 0, len(normalizedFacets))
+ individualIndexes := make([]int, 0, len(normalizedFacets))
+ for index, facet := range normalizedFacets {
+ if _, batchable := issueTableBaseFacetExpression(request.Query, facet); batchable {
+ batchFacets = append(batchFacets, facet)
+ } else {
+ individualIndexes = append(individualIndexes, index)
+ }
+ }
+
+ responses := make([]issueTableFacetResponse, len(normalizedFacets))
+ var total int64
+ totalResolved := false
+ if len(batchFacets) > 0 {
+ batched, batchTotal, ok := h.issueTableBaseFacetQuery(w, r, base, request.Query, batchFacets, includeTotal)
+ if !ok {
+ return
+ }
+ for index, facet := range normalizedFacets {
+ if response, exists := batched[issueTableFacetIdentity(facet)]; exists {
+ responses[index] = response
+ }
+ }
+ if includeTotal {
+ total = batchTotal
+ totalResolved = true
+ }
+ }
+ if includeTotal && !totalResolved {
+ if err := h.DB.QueryRow(r.Context(), fmt.Sprintf("SELECT COUNT(*)::bigint FROM issue i WHERE %s", base.where), base.args...).Scan(&total); err != nil {
+ slog.Warn("ListIssueTableFacets total failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to count table facets")
+ return
+ }
+ }
+ for _, index := range individualIndexes {
+ resolved, ok := h.issueTableFacetQuery(w, r, request.Query, normalizedFacets[index])
+ if !ok {
+ return
+ }
+ responses[index] = resolved
+ }
+
+ response := issueTableFacetsResponse{
+ QueryFingerprint: base.fingerprint,
+ Total: total,
+ Facets: responses,
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ slog.Warn("ListIssueTableFacets snapshot commit failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to finish table query")
+ return
+ }
+ committed = true
+ writeJSON(w, http.StatusOK, response)
+}
diff --git a/server/internal/handler/issue_table_group.go b/server/internal/handler/issue_table_group.go
new file mode 100644
index 0000000000..9a3ac82559
--- /dev/null
+++ b/server/internal/handler/issue_table_group.go
@@ -0,0 +1,488 @@
+package handler
+
+import (
+ "context"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "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"
+)
+
+type issueTableGroupValueResponse struct {
+ Kind string `json:"kind"`
+ Status string `json:"status,omitempty"`
+ Actor *issueTableActorRef `json:"actor"`
+ PropertyID string `json:"property_id,omitempty"`
+ Value any `json:"value,omitempty"`
+ ValueState string `json:"value_state,omitempty"`
+}
+
+type issueTableGroupDescriptorResponse struct {
+ Key string `json:"key"`
+ Value issueTableGroupValueResponse `json:"value"`
+ Count int64 `json:"count"`
+}
+
+type issueTableGroupsResponse struct {
+ QueryFingerprint string `json:"query_fingerprint"`
+ Total int64 `json:"total"`
+ Groups []issueTableGroupDescriptorResponse `json:"groups"`
+ NextCursor *string `json:"next_cursor"`
+}
+
+type resolvedIssueTableGroup struct {
+ kind string
+ propertyID string
+ propertyType string
+ groupExpr string
+ groupSortExpr string
+ activeOptionOrder []string
+ activeOptions map[string]struct{}
+}
+
+func issueTableGroupIdentity(group issueTableGroupSpec) string {
+ if group.Kind == "property" {
+ return "group:property:" + group.PropertyID
+ }
+ return "group:" + group.Kind
+}
+
+func (h *Handler) resolveIssueTableGroup(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, group issueTableGroupSpec, allowNone bool) (resolvedIssueTableGroup, bool) {
+ switch group.Kind {
+ case "none":
+ if !allowNone {
+ writeError(w, http.StatusBadRequest, "group.kind=none is not valid for group headers")
+ return resolvedIssueTableGroup{}, false
+ }
+ return resolvedIssueTableGroup{kind: "none"}, true
+ case "status":
+ return resolvedIssueTableGroup{kind: "status", groupExpr: "i.status"}, true
+ case "assignee":
+ return resolvedIssueTableGroup{
+ kind: "assignee",
+ groupExpr: "CASE WHEN i.assignee_type IS NULL OR i.assignee_id IS NULL THEN '__unassigned__' ELSE i.assignee_type || ':' || i.assignee_id::text END",
+ // groupSortExpr runs after issues have been reduced to one row per
+ // actor. Resolving display names before GROUP BY executes one lookup
+ // per issue and turns large assignee groups into an N+1 query plan.
+ groupSortExpr: `LOWER(COALESCE(CASE split_part(group_value, ':', 1)
+ WHEN 'member' THEN (SELECT u.name FROM "user" u WHERE u.id = split_part(group_value, ':', 2)::uuid)
+ WHEN 'agent' THEN (SELECT a.name FROM agent a WHERE a.workspace_id = $1 AND a.id = split_part(group_value, ':', 2)::uuid)
+ WHEN 'squad' THEN (SELECT s.name FROM squad s WHERE s.workspace_id = $1 AND s.id = split_part(group_value, ':', 2)::uuid)
+END, ''))`,
+ }, true
+ case "property":
+ propertyUUID, err := util.ParseUUID(group.PropertyID)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid group.property_id")
+ return resolvedIssueTableGroup{}, false
+ }
+ property, err := h.Queries.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{
+ ID: propertyUUID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeIssueTableUnsupportedGroup(w, "property_not_found", "The grouped property no longer exists.")
+ return resolvedIssueTableGroup{}, false
+ }
+ slog.Warn("resolve table group property failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to resolve table group")
+ return resolvedIssueTableGroup{}, false
+ }
+ if property.ArchivedAt.Valid {
+ writeIssueTableUnsupportedGroup(w, "property_archived", "The grouped property is archived.")
+ return resolvedIssueTableGroup{}, false
+ }
+ propertyID := util.UUIDToString(property.ID)
+ quotedKey := "'" + propertyID + "'"
+ resolved := resolvedIssueTableGroup{
+ kind: "property",
+ propertyID: propertyID,
+ propertyType: property.Type,
+ activeOptions: map[string]struct{}{},
+ }
+ switch property.Type {
+ case "select":
+ config := parsePropertyConfig(property.Config)
+ resolved.activeOptionOrder = make([]string, 0, len(config.Options))
+ for _, option := range config.Options {
+ resolved.activeOptions[option.ID] = struct{}{}
+ resolved.activeOptionOrder = append(resolved.activeOptionOrder, "value:"+option.ID)
+ }
+ resolved.groupExpr = fmt.Sprintf(`CASE
+ WHEN NOT (i.properties ? %s) THEN 'unset:'
+ WHEN jsonb_typeof(i.properties -> %s) = 'string' AND i.properties ->> %s = ANY(%%s::text[]) THEN 'value:' || (i.properties ->> %s)
+ WHEN jsonb_typeof(i.properties -> %s) = 'string' THEN 'unavailable:' || (i.properties ->> %s)
+ ELSE 'unavailable:'
+END`, quotedKey, quotedKey, quotedKey, quotedKey, quotedKey, quotedKey)
+ case "checkbox":
+ resolved.groupExpr = fmt.Sprintf(`CASE
+ WHEN NOT (i.properties ? %s) THEN 'unset:'
+ WHEN jsonb_typeof(i.properties -> %s) = 'boolean' THEN 'value:' || (i.properties ->> %s)
+ ELSE 'unavailable:'
+END`, quotedKey, quotedKey, quotedKey)
+ default:
+ writeIssueTableUnsupportedGroup(w, "property_type_unsupported", "This property type cannot be used for grouping.")
+ return resolvedIssueTableGroup{}, false
+ }
+ return resolved, true
+ default:
+ writeIssueTableUnsupportedGroup(w, "group_kind_unsupported", "This group type is not supported.")
+ return resolvedIssueTableGroup{}, false
+ }
+}
+
+func writeIssueTableUnsupportedGroup(w http.ResponseWriter, code, message string) {
+ writeJSON(w, http.StatusUnprocessableEntity, map[string]any{
+ "error": "unsupported_group",
+ "code": code,
+ "message": message,
+ })
+}
+
+func (group resolvedIssueTableGroup) expression(addArg func(any) string) string {
+ if group.kind == "property" && group.propertyType == "select" {
+ active := make([]string, 0, len(group.activeOptions))
+ for value := range group.activeOptions {
+ active = append(active, value)
+ }
+ return fmt.Sprintf(group.groupExpr, addArg(active))
+ }
+ return group.groupExpr
+}
+
+func (group resolvedIssueTableGroup) sortExpression() string {
+ if group.groupSortExpr != "" {
+ return group.groupSortExpr
+ }
+ return "group_value"
+}
+
+func (group resolvedIssueTableGroup) orderExpression(addArg func(any) string) string {
+ switch group.kind {
+ case "status":
+ return "CASE group_value WHEN 'backlog' THEN 0 WHEN 'todo' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'in_review' THEN 3 WHEN 'done' THEN 4 WHEN 'blocked' THEN 5 WHEN 'cancelled' THEN 6 ELSE 7 END"
+ case "assignee":
+ return "CASE WHEN group_value = '__unassigned__' THEN 1 ELSE 0 END"
+ case "property":
+ if group.propertyType == "select" {
+ ref := addArg(group.activeOptionOrder)
+ return fmt.Sprintf("CASE WHEN group_value LIKE 'value:%%' THEN COALESCE(array_position(%s::text[], group_value), 100000) WHEN group_value LIKE 'unavailable:%%' THEN 100001 ELSE 100002 END", ref)
+ }
+ return "CASE group_value WHEN 'value:false' THEN 0 WHEN 'value:true' THEN 1 WHEN 'unavailable:' THEN 2 ELSE 3 END"
+ default:
+ return "0"
+ }
+}
+
+func (group resolvedIssueTableGroup) descriptor(raw string, count int64) (issueTableGroupDescriptorResponse, error) {
+ descriptor := issueTableGroupDescriptorResponse{Count: count}
+ switch group.kind {
+ case "status":
+ if !issueTableContainsString(validIssueStatuses, raw) {
+ return descriptor, fmt.Errorf("unexpected status group value %q", raw)
+ }
+ descriptor.Key = "status:" + raw
+ descriptor.Value = issueTableGroupValueResponse{Kind: "status", Status: raw}
+ case "assignee":
+ descriptor.Value.Kind = "assignee"
+ if raw == "__unassigned__" {
+ descriptor.Key = "assignee:unassigned"
+ return descriptor, nil
+ }
+ parts := strings.SplitN(raw, ":", 2)
+ if len(parts) != 2 || !isIssueActorType(parts[0]) {
+ return descriptor, fmt.Errorf("unexpected assignee group value %q", raw)
+ }
+ if _, err := util.ParseUUID(parts[1]); err != nil {
+ return descriptor, fmt.Errorf("unexpected assignee group value %q", raw)
+ }
+ descriptor.Key = "assignee:" + raw
+ descriptor.Value.Actor = &issueTableActorRef{Type: parts[0], ID: parts[1]}
+ case "property":
+ state, rawValue, ok := strings.Cut(raw, ":")
+ if !ok {
+ return descriptor, fmt.Errorf("unexpected property group value %q", raw)
+ }
+ encoded := base64.RawURLEncoding.EncodeToString([]byte(rawValue))
+ descriptor.Key = "property:" + group.propertyID + ":" + state + ":" + encoded
+ descriptor.Value = issueTableGroupValueResponse{
+ Kind: "property",
+ PropertyID: group.propertyID,
+ }
+ switch state {
+ case "unset":
+ descriptor.Value.ValueState = "unset"
+ case "unavailable":
+ descriptor.Value.ValueState = "unavailable"
+ case "value":
+ descriptor.Value.ValueState = "value"
+ if group.propertyType == "checkbox" {
+ value, err := strconv.ParseBool(rawValue)
+ if err != nil {
+ return descriptor, fmt.Errorf("unexpected checkbox group value %q", rawValue)
+ }
+ descriptor.Value.Value = value
+ } else {
+ descriptor.Value.Value = rawValue
+ }
+ default:
+ return descriptor, fmt.Errorf("unexpected property group state %q", state)
+ }
+ default:
+ return descriptor, fmt.Errorf("unsupported group kind %q", group.kind)
+ }
+ return descriptor, nil
+}
+
+func (group resolvedIssueTableGroup) predicate(w http.ResponseWriter, key string, addArg func(any) string) (string, bool) {
+ switch group.kind {
+ case "none":
+ if key != "" {
+ writeError(w, http.StatusBadRequest, "group_key must be empty when group.kind=none")
+ return "", false
+ }
+ return "TRUE", true
+ case "status":
+ const prefix = "status:"
+ if !strings.HasPrefix(key, prefix) || !issueTableContainsString(validIssueStatuses, strings.TrimPrefix(key, prefix)) {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ return fmt.Sprintf("i.status = %s::text", addArg(strings.TrimPrefix(key, prefix))), true
+ case "assignee":
+ const prefix = "assignee:"
+ if !strings.HasPrefix(key, prefix) {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ raw := strings.TrimPrefix(key, prefix)
+ if raw == "unassigned" {
+ return "i.assignee_type IS NULL AND i.assignee_id IS NULL", true
+ }
+ parts := strings.SplitN(raw, ":", 2)
+ if len(parts) != 2 || !isIssueActorType(parts[0]) {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ id, err := util.ParseUUID(parts[1])
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ return fmt.Sprintf("i.assignee_type = %s::text AND i.assignee_id = %s::uuid", addArg(parts[0]), addArg(id)), true
+ case "property":
+ prefix := "property:" + group.propertyID + ":"
+ if !strings.HasPrefix(key, prefix) {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ rest := strings.TrimPrefix(key, prefix)
+ state, encoded, ok := strings.Cut(rest, ":")
+ if !ok {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ decoded, err := base64.RawURLEncoding.DecodeString(encoded)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ value := string(decoded)
+ keySQL := "'" + group.propertyID + "'"
+ switch state {
+ case "unset":
+ if value != "" {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ return fmt.Sprintf("NOT (i.properties ? %s)", keySQL), true
+ case "value":
+ if group.propertyType == "select" {
+ if _, exists := group.activeOptions[value]; !exists {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ return fmt.Sprintf("jsonb_typeof(i.properties -> %s) = 'string' AND i.properties ->> %s = %s::text", keySQL, keySQL, addArg(value)), true
+ }
+ if value != "true" && value != "false" {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ return fmt.Sprintf("jsonb_typeof(i.properties -> %s) = 'boolean' AND i.properties ->> %s = %s::text", keySQL, keySQL, addArg(value)), true
+ case "unavailable":
+ if group.propertyType == "select" && value != "" {
+ return fmt.Sprintf("jsonb_typeof(i.properties -> %s) = 'string' AND i.properties ->> %s = %s::text", keySQL, keySQL, addArg(value)), true
+ }
+ return fmt.Sprintf("i.properties ? %s AND jsonb_typeof(i.properties -> %s) <> %s::text", keySQL, keySQL, addArg(map[string]string{"select": "string", "checkbox": "boolean"}[group.propertyType])), true
+ default:
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ default:
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+}
+
+func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {
+ if h.DB == nil {
+ writeError(w, http.StatusInternalServerError, "database is unavailable")
+ return
+ }
+ var request issueTableGroupsRequest
+ if !decodeIssueTableJSON(w, r, &request) {
+ return
+ }
+ r, cancel := withIssueTableQueryTimeout(r)
+ defer cancel()
+ snapshot, tx, err := h.beginIssueTableSnapshot(r.Context())
+ if err != nil {
+ slog.Warn("ListIssueTableGroups snapshot failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to start table query")
+ return
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback(context.Background())
+ }
+ }()
+ h = snapshot
+ limit, cursor, ok := normalizeIssueTablePage(w, request.Page)
+ if !ok {
+ return
+ }
+ compiled, ok := h.compileIssueTableQuery(w, r, request.Query)
+ if !ok {
+ return
+ }
+ group, ok := h.resolveIssueTableGroup(w, r, compiled.workspaceID, request.Group, false)
+ if !ok {
+ return
+ }
+ groupIdentity := issueTableGroupIdentity(request.Group)
+ if !issueTableCursorMatches(w, cursor, compiled.fingerprint, &groupIdentity, nil) {
+ return
+ }
+
+ args := append([]any(nil), compiled.args...)
+ addArg := func(value any) string {
+ args = append(args, value)
+ return "$" + strconv.Itoa(len(args))
+ }
+ groupExpr := group.expression(addArg)
+ groupSortExpr := group.sortExpression()
+ orderExpr := group.orderExpression(addArg)
+ cursorPredicate := "TRUE"
+ if cursor != nil {
+ if cursor.GroupOrder == nil || cursor.GroupSortKey == nil || cursor.GroupCursorKey == nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return
+ }
+ orderRef := addArg(*cursor.GroupOrder)
+ sortRef := addArg(*cursor.GroupSortKey)
+ keyRef := addArg(*cursor.GroupCursorKey)
+ cursorPredicate = fmt.Sprintf(`(group_order > %[1]s::int OR (
+ group_order = %[1]s::int AND (
+ group_sort > %[2]s::text OR (group_sort = %[2]s::text AND group_value > %[3]s::text)
+ )
+))`, orderRef, sortRef, keyRef)
+ }
+ limitRef := addArg(limit + 1)
+ query := fmt.Sprintf(`WITH grouped AS (
+ SELECT %s AS group_value, COUNT(*)::bigint AS issue_count
+ FROM issue i
+ WHERE %s
+ GROUP BY 1
+ ), sorted AS (
+ SELECT group_value, issue_count, (%s)::text AS group_sort
+ FROM grouped
+ ), ranked AS (
+ SELECT group_value, issue_count, group_sort, (%s)::int AS group_order,
+ SUM(issue_count) OVER ()::bigint AS total
+ FROM sorted
+ )
+ SELECT group_value, issue_count, group_sort, group_order, total
+ FROM ranked
+ WHERE %s
+ ORDER BY group_order ASC, group_sort ASC, group_value ASC
+ LIMIT %s`, groupExpr, compiled.where, groupSortExpr, orderExpr, cursorPredicate, limitRef)
+
+ rows, err := h.DB.Query(r.Context(), query, args...)
+ if err != nil {
+ slog.Warn("ListIssueTableGroups query failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to list table groups")
+ return
+ }
+ defer rows.Close()
+
+ groups := make([]issueTableGroupDescriptorResponse, 0, limit+1)
+ orders := make([]int, 0, limit+1)
+ sortValues := make([]string, 0, limit+1)
+ values := make([]string, 0, limit+1)
+ var total int64
+ for rows.Next() {
+ var raw string
+ var count int64
+ var sortValue string
+ var order int
+ if err := rows.Scan(&raw, &count, &sortValue, &order, &total); err != nil {
+ writeIssueTableQueryFailure(w, r, "failed to list table groups")
+ return
+ }
+ descriptor, err := group.descriptor(raw, count)
+ if err != nil {
+ slog.Warn("ListIssueTableGroups descriptor failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to resolve table group")
+ return
+ }
+ groups = append(groups, descriptor)
+ orders = append(orders, order)
+ sortValues = append(sortValues, sortValue)
+ values = append(values, raw)
+ }
+ if err := rows.Err(); err != nil {
+ writeIssueTableQueryFailure(w, r, "failed to list table groups")
+ return
+ }
+ rows.Close()
+
+ var nextCursor *string
+ if len(groups) > limit {
+ groups = groups[:limit]
+ lastOrder := orders[limit-1]
+ lastSort := sortValues[limit-1]
+ lastKey := values[limit-1]
+ nextCursor = encodeIssueTableCursor(issueTableCursor{
+ Version: 1,
+ QueryFingerprint: compiled.fingerprint,
+ GroupKey: &groupIdentity,
+ GroupOrder: &lastOrder,
+ GroupSortKey: &lastSort,
+ GroupCursorKey: &lastKey,
+ })
+ }
+ response := issueTableGroupsResponse{
+ QueryFingerprint: compiled.fingerprint,
+ Total: total,
+ Groups: groups,
+ NextCursor: nextCursor,
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ slog.Warn("ListIssueTableGroups snapshot commit failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to finish table query")
+ return
+ }
+ committed = true
+ writeJSON(w, http.StatusOK, response)
+}
diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.go
new file mode 100644
index 0000000000..fb8c0755d1
--- /dev/null
+++ b/server/internal/handler/issue_table_query.go
@@ -0,0 +1,591 @@
+package handler
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const (
+ issueTableDefaultPageSize = 50
+ issueTableMaxPageSize = 100
+ issueTableQueryTimeout = 8 * time.Second
+)
+
+func withIssueTableQueryTimeout(r *http.Request) (*http.Request, context.CancelFunc) {
+ ctx, cancel := context.WithTimeout(r.Context(), issueTableQueryTimeout)
+ return r.WithContext(ctx), cancel
+}
+
+func (h *Handler) beginIssueTableSnapshot(ctx context.Context) (*Handler, pgx.Tx, error) {
+ if h.TxStarter == nil {
+ return nil, nil, errors.New("transaction starter is unavailable")
+ }
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ if _, err := tx.Exec(ctx, "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); err != nil {
+ _ = tx.Rollback(context.Background())
+ return nil, nil, err
+ }
+ snapshot := *h
+ snapshot.DB = tx
+ snapshot.Queries = db.New(tx)
+ return &snapshot, tx, nil
+}
+
+func writeIssueTableQueryFailure(w http.ResponseWriter, r *http.Request, message string) {
+ if errors.Is(r.Context().Err(), context.DeadlineExceeded) {
+ writeJSON(w, http.StatusGatewayTimeout, map[string]any{
+ "error": "query_timeout",
+ "message": "The table query took too long. Narrow the filters and retry.",
+ })
+ return
+ }
+ writeError(w, http.StatusInternalServerError, message)
+}
+
+type issueTableActorRef struct {
+ Type string `json:"type"`
+ ID string `json:"id"`
+}
+
+type issueTableScope struct {
+ Kind string `json:"kind"`
+ AssigneeTypes []string `json:"assignee_types,omitempty"`
+ ProjectID string `json:"project_id,omitempty"`
+ Actor *issueTableActorRef `json:"actor,omitempty"`
+ Relation string `json:"relation,omitempty"`
+}
+
+type issueTableDateFilterRequest struct {
+ Field string `json:"field"`
+ Start string `json:"start"`
+ End string `json:"end"`
+}
+
+type issueTableFiltersRequest struct {
+ Statuses []string `json:"statuses,omitempty"`
+ Priorities []string `json:"priorities,omitempty"`
+ Assignees []issueTableActorRef `json:"assignees,omitempty"`
+ IncludeNoAssignee bool `json:"include_no_assignee,omitempty"`
+ Creators []issueTableActorRef `json:"creators,omitempty"`
+ ProjectIDs []string `json:"project_ids,omitempty"`
+ IncludeNoProject bool `json:"include_no_project,omitempty"`
+ LabelIDs []string `json:"label_ids,omitempty"`
+ Properties map[string][]string `json:"properties,omitempty"`
+ Date *issueTableDateFilterRequest `json:"date,omitempty"`
+ WorkingOnly bool `json:"working_only,omitempty"`
+ IncludeSubIssues *bool `json:"include_sub_issues,omitempty"`
+}
+
+type issueTableSortRequest struct {
+ Field string `json:"field"`
+ Direction string `json:"direction"`
+}
+
+type issueTableQuerySpec struct {
+ Scope issueTableScope `json:"scope"`
+ Filters issueTableFiltersRequest `json:"filters"`
+ Search string `json:"search,omitempty"`
+ Sort issueTableSortRequest `json:"sort"`
+}
+
+type issueTableGroupSpec struct {
+ Kind string `json:"kind"`
+ PropertyID string `json:"property_id,omitempty"`
+}
+
+type issueTablePageRequest struct {
+ Limit int `json:"limit,omitempty"`
+ Cursor *string `json:"cursor,omitempty"`
+}
+
+type issueTableHierarchyRequest struct {
+ Enabled bool `json:"enabled"`
+}
+
+type issueTableGroupsRequest struct {
+ Query issueTableQuerySpec `json:"query"`
+ Group issueTableGroupSpec `json:"group"`
+ Page issueTablePageRequest `json:"page"`
+}
+
+type issueTableRowsRequest struct {
+ Query issueTableQuerySpec `json:"query"`
+ Group issueTableGroupSpec `json:"group"`
+ GroupKey *string `json:"group_key"`
+ Hierarchy issueTableHierarchyRequest `json:"hierarchy"`
+ ParentID *string `json:"parent_id"`
+ Page issueTablePageRequest `json:"page"`
+}
+
+type issueTableFacetSpec struct {
+ Kind string `json:"kind"`
+ PropertyID string `json:"property_id,omitempty"`
+}
+
+type issueTableFacetsRequest struct {
+ Query issueTableQuerySpec `json:"query"`
+ Facets []issueTableFacetSpec `json:"facets"`
+ IncludeTotal *bool `json:"include_total,omitempty"`
+}
+
+type issueTableSQL struct {
+ where string
+ args []any
+ fingerprint string
+ workspaceID pgtype.UUID
+}
+
+type issueTableCursor struct {
+ Version int `json:"v"`
+ QueryFingerprint string `json:"query"`
+ GroupKey *string `json:"group_key,omitempty"`
+ ParentID *string `json:"parent_id,omitempty"`
+ GroupOrder *int `json:"group_order,omitempty"`
+ GroupSortKey *string `json:"group_sort_key,omitempty"`
+ GroupCursorKey *string `json:"group_cursor_key,omitempty"`
+ BranchIdentity string `json:"branch_identity,omitempty"`
+ SortValue *string `json:"sort_value,omitempty"`
+ SortIsNull bool `json:"sort_is_null,omitempty"`
+ RowCreatedAt string `json:"row_created_at,omitempty"`
+ RowID string `json:"row_id,omitempty"`
+}
+
+func decodeIssueTableJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(dst); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid issue table query: "+err.Error())
+ return false
+ }
+ if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
+ writeError(w, http.StatusBadRequest, "invalid issue table query: request must contain one JSON object")
+ return false
+ }
+ return true
+}
+
+func normalizeIssueTablePage(w http.ResponseWriter, page issueTablePageRequest) (int, *issueTableCursor, bool) {
+ limit := page.Limit
+ if limit == 0 {
+ limit = issueTableDefaultPageSize
+ }
+ if limit < 1 || limit > issueTableMaxPageSize {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("page.limit must be between 1 and %d", issueTableMaxPageSize))
+ return 0, nil, false
+ }
+ if page.Cursor == nil || strings.TrimSpace(*page.Cursor) == "" {
+ return limit, nil, true
+ }
+ decoded, err := base64.RawURLEncoding.DecodeString(*page.Cursor)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return 0, nil, false
+ }
+ var cursor issueTableCursor
+ if err := json.Unmarshal(decoded, &cursor); err != nil || cursor.Version != 1 {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return 0, nil, false
+ }
+ return limit, &cursor, true
+}
+
+func encodeIssueTableCursor(cursor issueTableCursor) *string {
+ encoded, err := json.Marshal(cursor)
+ if err != nil {
+ return nil
+ }
+ value := base64.RawURLEncoding.EncodeToString(encoded)
+ return &value
+}
+
+func issueTableCursorMatches(w http.ResponseWriter, cursor *issueTableCursor, fingerprint string, groupKey, parentID *string) bool {
+ if cursor == nil {
+ return true
+ }
+ if cursor.QueryFingerprint != fingerprint || !equalOptionalString(cursor.GroupKey, groupKey) || !equalOptionalString(cursor.ParentID, parentID) {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "cursor_query_mismatch",
+ "message": "cursor does not belong to this table query",
+ })
+ return false
+ }
+ return true
+}
+
+func equalOptionalString(a, b *string) bool {
+ if a == nil || b == nil {
+ return a == nil && b == nil
+ }
+ return *a == *b
+}
+
+func canonicalIssueTableFingerprint(workspaceID string, spec issueTableQuerySpec) (string, error) {
+ normalized := spec
+ normalized.Search = strings.TrimSpace(normalized.Search)
+ normalized.Scope.AssigneeTypes = sortedUniqueStrings(normalized.Scope.AssigneeTypes)
+ normalized.Filters.Statuses = sortedUniqueStrings(normalized.Filters.Statuses)
+ normalized.Filters.Priorities = sortedUniqueStrings(normalized.Filters.Priorities)
+ normalized.Filters.ProjectIDs = sortedUniqueStrings(normalized.Filters.ProjectIDs)
+ normalized.Filters.LabelIDs = sortedUniqueStrings(normalized.Filters.LabelIDs)
+ normalized.Filters.Assignees = sortedUniqueActors(normalized.Filters.Assignees)
+ normalized.Filters.Creators = sortedUniqueActors(normalized.Filters.Creators)
+ for key, values := range normalized.Filters.Properties {
+ normalized.Filters.Properties[key] = sortedUniqueStrings(values)
+ }
+ encoded, err := json.Marshal(struct {
+ WorkspaceID string `json:"workspace_id"`
+ Query issueTableQuerySpec `json:"query"`
+ }{
+ WorkspaceID: workspaceID,
+ Query: normalized,
+ })
+ if err != nil {
+ return "", err
+ }
+ digest := sha256.Sum256(encoded)
+ return "sha256:" + hex.EncodeToString(digest[:]), nil
+}
+
+func sortedUniqueStrings(values []string) []string {
+ if len(values) == 0 {
+ return nil
+ }
+ seen := make(map[string]struct{}, len(values))
+ result := make([]string, 0, len(values))
+ for _, value := range values {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ continue
+ }
+ if _, exists := seen[value]; exists {
+ continue
+ }
+ seen[value] = struct{}{}
+ result = append(result, value)
+ }
+ sort.Strings(result)
+ if len(result) == 0 {
+ return nil
+ }
+ return result
+}
+
+func sortedUniqueActors(values []issueTableActorRef) []issueTableActorRef {
+ seen := make(map[string]issueTableActorRef, len(values))
+ for _, value := range values {
+ key := value.Type + ":" + value.ID
+ seen[key] = value
+ }
+ keys := make([]string, 0, len(seen))
+ for key := range seen {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ result := make([]issueTableActorRef, 0, len(keys))
+ for _, key := range keys {
+ result = append(result, seen[key])
+ }
+ if len(result) == 0 {
+ return nil
+ }
+ return result
+}
+
+func issueTableContainsString(values []string, candidate string) bool {
+ for _, value := range values {
+ if value == candidate {
+ return true
+ }
+ }
+ return false
+}
+
+func parseIssueTableUUIDList(w http.ResponseWriter, values []string, field string) ([]pgtype.UUID, bool) {
+ result := make([]pgtype.UUID, 0, len(values))
+ for _, raw := range values {
+ parsed, err := util.ParseUUID(raw)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid "+field)
+ return nil, false
+ }
+ result = append(result, parsed)
+ }
+ return result, true
+}
+
+func parseIssueTableActor(w http.ResponseWriter, actor issueTableActorRef, field string) (issueActorFilter, bool) {
+ if !isIssueActorType(actor.Type) {
+ writeError(w, http.StatusBadRequest, "invalid "+field)
+ return issueActorFilter{}, false
+ }
+ id, err := util.ParseUUID(actor.ID)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid "+field)
+ return issueActorFilter{}, false
+ }
+ return issueActorFilter{actorType: actor.Type, actorID: id}, true
+}
+
+func appendIssueTableInvolvedPredicate(where []string, addArg func(any) string, userID pgtype.UUID) []string {
+ ref := addArg(userID)
+ return append(where, fmt.Sprintf(`(
+ (i.assignee_type = 'agent' AND i.assignee_id IN (
+ SELECT a.id FROM agent a
+ WHERE a.workspace_id = $1
+ AND a.owner_id = %[1]s::uuid
+ ))
+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (
+ SELECT sm.squad_id
+ FROM squad_member sm
+ JOIN squad s ON s.id = sm.squad_id
+ WHERE s.workspace_id = $1
+ AND sm.member_type = 'member'
+ AND sm.member_id = %[1]s::uuid
+ UNION
+ SELECT s.id
+ FROM squad s
+ JOIN agent a ON a.id = s.leader_id
+ WHERE s.workspace_id = $1
+ AND a.workspace_id = $1
+ AND a.owner_id = %[1]s::uuid
+ UNION
+ SELECT sm.squad_id
+ FROM squad_member sm
+ JOIN squad s ON s.id = sm.squad_id
+ JOIN agent a ON a.id = sm.member_id
+ WHERE s.workspace_id = $1
+ AND sm.member_type = 'agent'
+ AND a.workspace_id = $1
+ AND a.owner_id = %[1]s::uuid
+ ))
+)`, ref))
+}
+
+func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request, spec issueTableQuerySpec) (issueTableSQL, bool) {
+ workspaceID := h.resolveWorkspaceID(r)
+ workspaceUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace_id")
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ fingerprint, err := canonicalIssueTableFingerprint(util.UUIDToString(workspaceUUID), spec)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to canonicalize table query")
+ return issueTableSQL{}, false
+ }
+
+ where := []string{"i.workspace_id = $1"}
+ args := []any{workspaceUUID}
+ addArg := func(value any) string {
+ args = append(args, value)
+ return "$" + strconv.Itoa(len(args))
+ }
+
+ for _, status := range spec.Filters.Statuses {
+ if !issueTableContainsString(validIssueStatuses, status) {
+ writeError(w, http.StatusBadRequest, "invalid filters.statuses")
+ return issueTableSQL{}, false
+ }
+ }
+ if len(spec.Filters.Statuses) > 0 {
+ where = append(where, fmt.Sprintf("i.status = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Filters.Statuses))))
+ }
+ for _, priority := range spec.Filters.Priorities {
+ if !issueTableContainsString(validIssuePriorities, priority) {
+ writeError(w, http.StatusBadRequest, "invalid filters.priorities")
+ return issueTableSQL{}, false
+ }
+ }
+ if len(spec.Filters.Priorities) > 0 {
+ where = append(where, fmt.Sprintf("i.priority = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Filters.Priorities))))
+ }
+
+ switch spec.Scope.Kind {
+ case "workspace":
+ for _, actorType := range spec.Scope.AssigneeTypes {
+ if !isIssueActorType(actorType) {
+ writeError(w, http.StatusBadRequest, "invalid scope.assignee_types")
+ return issueTableSQL{}, false
+ }
+ }
+ if len(spec.Scope.AssigneeTypes) > 0 {
+ where = append(where, fmt.Sprintf("i.assignee_type = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Scope.AssigneeTypes))))
+ }
+ case "project":
+ projectID, err := util.ParseUUID(spec.Scope.ProjectID)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid scope.project_id")
+ return issueTableSQL{}, false
+ }
+ where = append(where, fmt.Sprintf("i.project_id = %s::uuid", addArg(projectID)))
+ case "assignee":
+ if spec.Scope.Actor == nil {
+ writeError(w, http.StatusBadRequest, "scope.actor is required")
+ return issueTableSQL{}, false
+ }
+ actor, ok := parseIssueTableActor(w, *spec.Scope.Actor, "scope.actor")
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ where = append(where, fmt.Sprintf("i.assignee_type = %s::text AND i.assignee_id = %s::uuid", addArg(actor.actorType), addArg(actor.actorID)))
+ case "creator":
+ if spec.Scope.Actor == nil {
+ writeError(w, http.StatusBadRequest, "scope.actor is required")
+ return issueTableSQL{}, false
+ }
+ actor, ok := parseIssueTableActor(w, *spec.Scope.Actor, "scope.actor")
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ where = append(where, fmt.Sprintf("i.creator_type = %s::text AND i.creator_id = %s::uuid", addArg(actor.actorType), addArg(actor.actorID)))
+ case "my":
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ userUUID, err := util.ParseUUID(userID)
+ if err != nil {
+ writeError(w, http.StatusUnauthorized, "user not authenticated")
+ return issueTableSQL{}, false
+ }
+ relation := spec.Scope.Relation
+ if relation == "" {
+ relation = "any"
+ }
+ switch relation {
+ case "assigned":
+ where = append(where, fmt.Sprintf("i.assignee_type = 'member' AND i.assignee_id = %s::uuid", addArg(userUUID)))
+ case "created":
+ where = append(where, fmt.Sprintf("i.creator_type = 'member' AND i.creator_id = %s::uuid", addArg(userUUID)))
+ case "involved":
+ where = appendIssueTableInvolvedPredicate(where, addArg, userUUID)
+ case "any":
+ assignedRef := addArg(userUUID)
+ createdRef := addArg(userUUID)
+ involved := appendIssueTableInvolvedPredicate(nil, addArg, userUUID)[0]
+ where = append(where, fmt.Sprintf("((i.assignee_type = 'member' AND i.assignee_id = %s::uuid) OR (i.creator_type = 'member' AND i.creator_id = %s::uuid) OR %s)", assignedRef, createdRef, involved))
+ default:
+ writeError(w, http.StatusBadRequest, "invalid scope.relation")
+ return issueTableSQL{}, false
+ }
+ default:
+ writeError(w, http.StatusBadRequest, "invalid scope.kind")
+ return issueTableSQL{}, false
+ }
+
+ if len(spec.Filters.Assignees) > 0 || spec.Filters.IncludeNoAssignee {
+ ors := make([]string, 0, len(spec.Filters.Assignees)+1)
+ for _, value := range spec.Filters.Assignees {
+ actor, ok := parseIssueTableActor(w, value, "filters.assignees")
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ ors = append(ors, fmt.Sprintf("(i.assignee_type = %s::text AND i.assignee_id = %s::uuid)", addArg(actor.actorType), addArg(actor.actorID)))
+ }
+ if spec.Filters.IncludeNoAssignee {
+ ors = append(ors, "(i.assignee_type IS NULL AND i.assignee_id IS NULL)")
+ }
+ where = append(where, "("+strings.Join(ors, " OR ")+")")
+ }
+
+ if len(spec.Filters.Creators) > 0 {
+ ors := make([]string, 0, len(spec.Filters.Creators))
+ for _, value := range spec.Filters.Creators {
+ actor, ok := parseIssueTableActor(w, value, "filters.creators")
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ ors = append(ors, fmt.Sprintf("(i.creator_type = %s::text AND i.creator_id = %s::uuid)", addArg(actor.actorType), addArg(actor.actorID)))
+ }
+ where = append(where, "("+strings.Join(ors, " OR ")+")")
+ }
+
+ projectIDs, ok := parseIssueTableUUIDList(w, spec.Filters.ProjectIDs, "filters.project_ids")
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ if len(projectIDs) > 0 || spec.Filters.IncludeNoProject {
+ ors := make([]string, 0, 2)
+ if len(projectIDs) > 0 {
+ ors = append(ors, fmt.Sprintf("i.project_id = ANY(%s::uuid[])", addArg(projectIDs)))
+ }
+ if spec.Filters.IncludeNoProject {
+ ors = append(ors, "i.project_id IS NULL")
+ }
+ where = append(where, "("+strings.Join(ors, " OR ")+")")
+ }
+
+ labelIDs, ok := parseIssueTableUUIDList(w, spec.Filters.LabelIDs, "filters.label_ids")
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ if len(labelIDs) > 0 {
+ where = append(where, fmt.Sprintf("EXISTS (SELECT 1 FROM issue_to_label itl WHERE itl.issue_id = i.id AND itl.label_id = ANY(%s::uuid[]))", addArg(labelIDs)))
+ }
+
+ if len(spec.Filters.Properties) > 0 {
+ raw, err := json.Marshal(spec.Filters.Properties)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid filters.properties")
+ return issueTableSQL{}, false
+ }
+ compiled, ok := parsePropertiesFilterParam(w, string(raw))
+ if !ok {
+ return issueTableSQL{}, false
+ }
+ if len(compiled) > 0 {
+ where = append(where, propertiesFilterPredicate(compiled, addArg))
+ }
+ }
+
+ if spec.Filters.Date != nil {
+ column := ""
+ switch spec.Filters.Date.Field {
+ case "created_at", "updated_at":
+ column = spec.Filters.Date.Field
+ default:
+ writeError(w, http.StatusBadRequest, "invalid filters.date.field")
+ return issueTableSQL{}, false
+ }
+ start, startErr := time.Parse(time.RFC3339Nano, spec.Filters.Date.Start)
+ end, endErr := time.Parse(time.RFC3339Nano, spec.Filters.Date.End)
+ if startErr != nil || endErr != nil || !start.Before(end) {
+ writeError(w, http.StatusBadRequest, "invalid filters.date range")
+ return issueTableSQL{}, false
+ }
+ where = append(where, fmt.Sprintf("i.%s >= %s AND i.%s < %s", column, addArg(start), column, addArg(end)))
+ }
+
+ if spec.Filters.WorkingOnly {
+ where = append(where, "EXISTS (SELECT 1 FROM agent_task_queue atq WHERE atq.issue_id = i.id AND atq.status = 'running')")
+ }
+ if spec.Filters.IncludeSubIssues != nil && !*spec.Filters.IncludeSubIssues {
+ where = append(where, "i.parent_issue_id IS NULL")
+ }
+ where = appendIssueTableSearchFilter(where, addArg, spec.Search)
+
+ return issueTableSQL{
+ where: strings.Join(where, " AND "),
+ args: args,
+ fingerprint: fingerprint,
+ workspaceID: workspaceUUID,
+ }, true
+}
diff --git a/server/internal/handler/issue_table_query_test.go b/server/internal/handler/issue_table_query_test.go
new file mode 100644
index 0000000000..0066d2751b
--- /dev/null
+++ b/server/internal/handler/issue_table_query_test.go
@@ -0,0 +1,921 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+)
+
+type issueTableEnrichmentFailTxStarter struct {
+ inner txStarter
+ labelCalls *int
+ tableQueryCalls *int
+ facetQueryCalls *int
+ rowQuerySQL *string
+ groupQuerySQL *string
+}
+
+func (s issueTableEnrichmentFailTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.inner.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &issueTableEnrichmentFailTx{
+ Tx: tx,
+ labelCalls: s.labelCalls,
+ tableQueryCalls: s.tableQueryCalls,
+ facetQueryCalls: s.facetQueryCalls,
+ rowQuerySQL: s.rowQuerySQL,
+ groupQuerySQL: s.groupQuerySQL,
+ }, nil
+}
+
+type issueTableEnrichmentFailTx struct {
+ pgx.Tx
+ labelCalls *int
+ tableQueryCalls *int
+ facetQueryCalls *int
+ rowQuerySQL *string
+ groupQuerySQL *string
+}
+
+func (tx *issueTableEnrichmentFailTx) recordTableQuery(sql string) {
+ if tx.tableQueryCalls != nil {
+ if strings.Contains(sql, "page AS MATERIALIZED (") ||
+ strings.Contains(sql, "SELECT COUNT(*)::bigint FROM issue i WHERE") {
+ *tx.tableQueryCalls = *tx.tableQueryCalls + 1
+ }
+ }
+ if tx.facetQueryCalls != nil && strings.Contains(sql, "GROUP BY GROUPING SETS") {
+ *tx.facetQueryCalls = *tx.facetQueryCalls + 1
+ }
+ if tx.rowQuerySQL != nil && strings.Contains(sql, "page AS MATERIALIZED (") {
+ *tx.rowQuerySQL = sql
+ }
+ if tx.groupQuerySQL != nil && strings.Contains(sql, "WITH grouped AS (") {
+ *tx.groupQuerySQL = sql
+ }
+}
+
+func (tx *issueTableEnrichmentFailTx) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
+ tx.recordTableQuery(sql)
+ if strings.Contains(sql, "ListLabelsForIssues") {
+ *tx.labelCalls = *tx.labelCalls + 1
+ // A real PostgreSQL statement error poisons the transaction until
+ // rollback. Before enrichment moved after Commit, this turned the
+ // otherwise successful row window into a 500.
+ _, err := tx.Tx.Exec(ctx, "SELECT * FROM issue_table_missing_enrichment_relation")
+ return nil, err
+ }
+ return tx.Tx.Query(ctx, sql, args...)
+}
+
+func (tx *issueTableEnrichmentFailTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ tx.recordTableQuery(sql)
+ return tx.Tx.QueryRow(ctx, sql, args...)
+}
+
+func TestCanonicalIssueTableFingerprintNormalizesSetLikeArrays(t *testing.T) {
+ left := issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace", AssigneeTypes: []string{"agent", "member", "agent"}},
+ Filters: issueTableFiltersRequest{
+ Statuses: []string{"todo", "backlog", "todo"},
+ ProjectIDs: []string{"b", "a"},
+ },
+ Sort: issueTableSortRequest{Field: "title", Direction: "asc"},
+ }
+ right := issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace", AssigneeTypes: []string{"member", "agent"}},
+ Filters: issueTableFiltersRequest{
+ Statuses: []string{"backlog", "todo"},
+ ProjectIDs: []string{"a", "b"},
+ },
+ Sort: issueTableSortRequest{Field: "title", Direction: "asc"},
+ }
+ leftFingerprint, err := canonicalIssueTableFingerprint("workspace-1", left)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rightFingerprint, err := canonicalIssueTableFingerprint("workspace-1", right)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if leftFingerprint != rightFingerprint {
+ t.Fatalf("equivalent table queries produced different fingerprints: %s != %s", leftFingerprint, rightFingerprint)
+ }
+}
+
+func TestCanonicalIssueTableFingerprintBindsWorkspace(t *testing.T) {
+ spec := issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "workspace"},
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ }
+ left, err := canonicalIssueTableFingerprint("workspace-1", spec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ right, err := canonicalIssueTableFingerprint("workspace-2", spec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if left == right {
+ t.Fatal("equivalent queries in different workspaces produced the same fingerprint")
+ }
+}
+
+func TestIssueTableCursorRejectsAnotherQuery(t *testing.T) {
+ groupKey := "status:todo"
+ cursor := issueTableCursor{
+ Version: 1,
+ QueryFingerprint: "sha256:old",
+ GroupKey: &groupKey,
+ }
+ w := httptest.NewRecorder()
+ if issueTableCursorMatches(w, &cursor, "sha256:new", &groupKey, nil) {
+ t.Fatal("cursor from another query unexpectedly matched")
+ }
+ if w.Code != http.StatusConflict {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusConflict)
+ }
+}
+
+func TestIssueTablePositionCursorIncludesIndexableLowerBound(t *testing.T) {
+ cursorValue := "90000"
+ cursor := issueTableCursor{
+ SortValue: &cursorValue,
+ RowCreatedAt: "2026-01-01T00:00:00Z",
+ RowID: "00000000-0000-4000-8000-000000000001",
+ }
+ args := make([]any, 0, 3)
+ predicate, ok := (resolvedIssueTableSort{
+ expression: "i.position",
+ direction: "asc",
+ castType: "double precision",
+ }).cursorPredicate(httptest.NewRecorder(), &cursor, func(value any) string {
+ args = append(args, value)
+ return fmt.Sprintf("$%d", len(args))
+ })
+ if !ok {
+ t.Fatal("valid position cursor was rejected")
+ }
+ if !strings.Contains(predicate, "i.position >= $3::double precision") {
+ t.Fatalf("position cursor is missing its indexable lower bound: %s", predicate)
+ }
+}
+
+func TestIssueTableRowsCommitsBeforeBestEffortEnrichment(t *testing.T) {
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, $2)
+ RETURNING id
+ `, testWorkspaceID, fmt.Sprintf("Table enrichment %d", suffix)).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE project_id = $1`, projectID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+
+ var issueNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(
+ issue_counter,
+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)
+ ) + 1
+ WHERE id = $1
+ RETURNING issue_counter
+ `, testWorkspaceID).Scan(&issueNumber); err != nil {
+ t.Fatalf("reserve issue number: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, status, priority, creator_type, creator_id,
+ position, number, project_id
+ )
+ VALUES ($1, 'table-enrichment', 'todo', 'none', 'member', $2, 1, $3, $4)
+ `, testWorkspaceID, testUserID, issueNumber, projectID); err != nil {
+ t.Fatalf("seed issue: %v", err)
+ }
+
+ labelCalls := 0
+ tableQueryCalls := 0
+ rowQuerySQL := ""
+ handler := *testHandler
+ handler.TxStarter = issueTableEnrichmentFailTxStarter{
+ inner: testHandler.TxStarter,
+ labelCalls: &labelCalls,
+ tableQueryCalls: &tableQueryCalls,
+ rowQuerySQL: &rowQuerySQL,
+ }
+ recorder := httptest.NewRecorder()
+ handler.ListIssueTableRows(recorder, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{
+ Query: issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ },
+ Group: issueTableGroupSpec{Kind: "none"},
+ Hierarchy: issueTableHierarchyRequest{Enabled: false},
+ Page: issueTablePageRequest{Limit: 10},
+ }))
+
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("rows status = %d: %s", recorder.Code, recorder.Body.String())
+ }
+ if labelCalls != 0 {
+ t.Fatalf("best-effort labels ran inside snapshot transaction %d times", labelCalls)
+ }
+ var response issueTableRowsResponse
+ if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {
+ t.Fatalf("decode rows: %v", err)
+ }
+ if len(response.Rows) != 1 {
+ t.Fatalf("rows = %d, want 1", len(response.Rows))
+ }
+ if response.Total != 1 || response.BranchTotal != 1 {
+ t.Fatalf("unexpected root counts: total=%d branch_total=%d", response.Total, response.BranchTotal)
+ }
+ if tableQueryCalls != 2 {
+ t.Fatalf("ungrouped root head executed %d table queries, want 2", tableQueryCalls)
+ }
+ if !strings.Contains(rowQuerySQL, "WITH page AS MATERIALIZED") ||
+ strings.Contains(rowQuerySQL, "membership AS") ||
+ strings.Contains(rowQuerySQL, "FROM membership child") {
+ t.Fatalf("flat rows query must page directly without hierarchy work:\n%s", rowQuerySQL)
+ }
+}
+
+func TestIssueTableStatusGroupingOverOneThousandRows(t *testing.T) {
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, $2)
+ RETURNING id
+ `, testWorkspaceID, fmt.Sprintf("Server table grouping %d", suffix)).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE project_id = $1`, projectID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+
+ var finalNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(
+ issue_counter,
+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)
+ ) + 1001
+ WHERE id = $1
+ RETURNING issue_counter
+ `, testWorkspaceID).Scan(&finalNumber); err != nil {
+ t.Fatalf("reserve issue numbers: %v", err)
+ }
+ firstNumber := finalNumber - 1000
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, status, priority, creator_type, creator_id,
+ position, number, project_id
+ )
+ SELECT $1, 'server-table-' || n::text,
+ CASE WHEN n <= 501 THEN 'todo' ELSE 'done' END,
+ 'none', 'member', $2, n::double precision,
+ $3 + n - 1, $4
+ FROM generate_series(1, 1001) AS n
+ `, testWorkspaceID, testUserID, firstNumber, projectID); err != nil {
+ t.Fatalf("seed issues: %v", err)
+ }
+
+ query := issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},
+ Filters: issueTableFiltersRequest{},
+ Sort: issueTableSortRequest{Field: "title", Direction: "asc"},
+ }
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest("POST", "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "status"},
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("groups status = %d: %s", w.Code, w.Body.String())
+ }
+ var groups issueTableGroupsResponse
+ if err := json.NewDecoder(w.Body).Decode(&groups); err != nil {
+ t.Fatalf("decode groups: %v", err)
+ }
+ if groups.Total != 1001 {
+ t.Fatalf("total = %d, want 1001", groups.Total)
+ }
+ counts := map[string]int64{}
+ for _, group := range groups.Groups {
+ counts[group.Key] = group.Count
+ }
+ if counts["status:todo"] != 501 || counts["status:done"] != 500 {
+ t.Fatalf("unexpected group counts: %#v", counts)
+ }
+ firstGroupPageRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(firstGroupPageRecorder, newRequest("POST", "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "status"},
+ Page: issueTablePageRequest{Limit: 1},
+ }))
+ var firstGroupPage issueTableGroupsResponse
+ if firstGroupPageRecorder.Code != http.StatusOK {
+ t.Fatalf("first group page status = %d: %s", firstGroupPageRecorder.Code, firstGroupPageRecorder.Body.String())
+ }
+ if err := json.NewDecoder(firstGroupPageRecorder.Body).Decode(&firstGroupPage); err != nil {
+ t.Fatalf("decode first group page: %v", err)
+ }
+ if len(firstGroupPage.Groups) != 1 || firstGroupPage.NextCursor == nil {
+ t.Fatalf("unexpected first group page: %#v", firstGroupPage)
+ }
+ secondGroupPageRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(secondGroupPageRecorder, newRequest("POST", "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "status"},
+ Page: issueTablePageRequest{Limit: 1, Cursor: firstGroupPage.NextCursor},
+ }))
+ var secondGroupPage issueTableGroupsResponse
+ if secondGroupPageRecorder.Code != http.StatusOK {
+ t.Fatalf("second group page status = %d: %s", secondGroupPageRecorder.Code, secondGroupPageRecorder.Body.String())
+ }
+ if err := json.NewDecoder(secondGroupPageRecorder.Body).Decode(&secondGroupPage); err != nil {
+ t.Fatalf("decode second group page: %v", err)
+ }
+ if len(secondGroupPage.Groups) != 1 || secondGroupPage.Groups[0].Key == firstGroupPage.Groups[0].Key || secondGroupPage.Total != 1001 {
+ t.Fatalf("group keyset pagination mismatch: first=%#v second=%#v", firstGroupPage, secondGroupPage)
+ }
+
+ groupKey := "status:todo"
+ labelCalls := 0
+ tableQueryCalls := 0
+ rowsHandler := *testHandler
+ rowsHandler.TxStarter = issueTableEnrichmentFailTxStarter{
+ inner: testHandler.TxStarter,
+ labelCalls: &labelCalls,
+ tableQueryCalls: &tableQueryCalls,
+ }
+ rowsRecorder := httptest.NewRecorder()
+ rowsHandler.ListIssueTableRows(rowsRecorder, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "status"},
+ GroupKey: &groupKey,
+ Hierarchy: issueTableHierarchyRequest{Enabled: false},
+ Page: issueTablePageRequest{Limit: 50},
+ }))
+ if rowsRecorder.Code != http.StatusOK {
+ t.Fatalf("rows status = %d: %s", rowsRecorder.Code, rowsRecorder.Body.String())
+ }
+ var rows issueTableRowsResponse
+ if err := json.NewDecoder(rowsRecorder.Body).Decode(&rows); err != nil {
+ t.Fatalf("decode rows: %v", err)
+ }
+ if rows.Total != 0 || rows.BranchTotal != 50 || len(rows.Rows) != 50 || rows.NextCursor == nil {
+ t.Fatalf("unexpected rows page: total=%d branch_total=%d rows=%d cursor=%v", rows.Total, rows.BranchTotal, len(rows.Rows), rows.NextCursor)
+ }
+ if tableQueryCalls != 1 {
+ t.Fatalf("grouped root head executed %d table queries, want 1", tableQueryCalls)
+ }
+ firstPageIDs := make(map[string]struct{}, len(rows.Rows))
+ for _, row := range rows.Rows {
+ firstPageIDs[row.Issue.ID] = struct{}{}
+ }
+ secondRowsRecorder := httptest.NewRecorder()
+ rowsHandler.ListIssueTableRows(secondRowsRecorder, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "status"},
+ GroupKey: &groupKey,
+ Hierarchy: issueTableHierarchyRequest{Enabled: false},
+ Page: issueTablePageRequest{Limit: 50, Cursor: rows.NextCursor},
+ }))
+ if secondRowsRecorder.Code != http.StatusOK {
+ t.Fatalf("second rows status = %d: %s", secondRowsRecorder.Code, secondRowsRecorder.Body.String())
+ }
+ var secondRows issueTableRowsResponse
+ if err := json.NewDecoder(secondRowsRecorder.Body).Decode(&secondRows); err != nil {
+ t.Fatalf("decode second rows: %v", err)
+ }
+ if secondRows.Total != 0 || secondRows.BranchTotal != 50 || len(secondRows.Rows) != 50 {
+ t.Fatalf("unexpected grouped continuation: total=%d branch_total=%d rows=%d", secondRows.Total, secondRows.BranchTotal, len(secondRows.Rows))
+ }
+ if tableQueryCalls != 2 {
+ t.Fatalf("grouped continuation executed %d cumulative table queries, want 2", tableQueryCalls)
+ }
+ for _, row := range secondRows.Rows {
+ if _, duplicate := firstPageIDs[row.Issue.ID]; duplicate {
+ t.Fatalf("keyset cursor repeated issue %s across pages", row.Issue.ID)
+ }
+ }
+
+ ungroupedRecorder := httptest.NewRecorder()
+ rowsHandler.ListIssueTableRows(ungroupedRecorder, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "none"},
+ Hierarchy: issueTableHierarchyRequest{Enabled: false},
+ Page: issueTablePageRequest{Limit: 50},
+ }))
+ if ungroupedRecorder.Code != http.StatusOK {
+ t.Fatalf("ungrouped rows status = %d: %s", ungroupedRecorder.Code, ungroupedRecorder.Body.String())
+ }
+ var ungroupedRows issueTableRowsResponse
+ if err := json.NewDecoder(ungroupedRecorder.Body).Decode(&ungroupedRows); err != nil {
+ t.Fatalf("decode ungrouped rows: %v", err)
+ }
+ if ungroupedRows.Total != 1001 || ungroupedRows.BranchTotal != 50 || len(ungroupedRows.Rows) != 50 || ungroupedRows.NextCursor == nil {
+ t.Fatalf("unexpected ungrouped root head: total=%d branch_total=%d rows=%d cursor=%v", ungroupedRows.Total, ungroupedRows.BranchTotal, len(ungroupedRows.Rows), ungroupedRows.NextCursor)
+ }
+ if tableQueryCalls != 4 {
+ t.Fatalf("ungrouped root head executed %d cumulative table queries, want 4", tableQueryCalls)
+ }
+
+ ungroupedNextRecorder := httptest.NewRecorder()
+ rowsHandler.ListIssueTableRows(ungroupedNextRecorder, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "none"},
+ Hierarchy: issueTableHierarchyRequest{Enabled: false},
+ Page: issueTablePageRequest{Limit: 50, Cursor: ungroupedRows.NextCursor},
+ }))
+ if ungroupedNextRecorder.Code != http.StatusOK {
+ t.Fatalf("ungrouped continuation status = %d: %s", ungroupedNextRecorder.Code, ungroupedNextRecorder.Body.String())
+ }
+ var ungroupedNext issueTableRowsResponse
+ if err := json.NewDecoder(ungroupedNextRecorder.Body).Decode(&ungroupedNext); err != nil {
+ t.Fatalf("decode ungrouped continuation: %v", err)
+ }
+ if ungroupedNext.Total != 0 || ungroupedNext.BranchTotal != 50 || len(ungroupedNext.Rows) != 50 {
+ t.Fatalf("unexpected ungrouped continuation: total=%d branch_total=%d rows=%d", ungroupedNext.Total, ungroupedNext.BranchTotal, len(ungroupedNext.Rows))
+ }
+ if tableQueryCalls != 5 {
+ t.Fatalf("ungrouped continuation executed %d cumulative table queries, want 5", tableQueryCalls)
+ }
+
+ for _, sortCase := range []issueTableSortRequest{
+ {Field: "status", Direction: "desc"},
+ {Field: "created_at", Direction: "desc"},
+ {Field: "due_date", Direction: "asc"},
+ } {
+ sortQuery := query
+ sortQuery.Sort = sortCase
+ fetchPage := func(cursor *string) issueTableRowsResponse {
+ t.Helper()
+ recorder := httptest.NewRecorder()
+ testHandler.ListIssueTableRows(recorder, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{
+ Query: sortQuery,
+ Group: issueTableGroupSpec{Kind: "status"},
+ GroupKey: &groupKey,
+ Hierarchy: issueTableHierarchyRequest{Enabled: false},
+ Page: issueTablePageRequest{Limit: 10, Cursor: cursor},
+ }))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("%s cursor page status = %d: %s", sortCase.Field, recorder.Code, recorder.Body.String())
+ }
+ var response issueTableRowsResponse
+ if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {
+ t.Fatalf("decode %s cursor page: %v", sortCase.Field, err)
+ }
+ return response
+ }
+ first := fetchPage(nil)
+ if len(first.Rows) != 10 || first.NextCursor == nil {
+ t.Fatalf("%s first cursor page is incomplete", sortCase.Field)
+ }
+ seen := make(map[string]struct{}, len(first.Rows))
+ for _, row := range first.Rows {
+ seen[row.Issue.ID] = struct{}{}
+ }
+ second := fetchPage(first.NextCursor)
+ if len(second.Rows) != 10 {
+ t.Fatalf("%s second cursor page length = %d", sortCase.Field, len(second.Rows))
+ }
+ for _, row := range second.Rows {
+ if _, duplicate := seen[row.Issue.ID]; duplicate {
+ t.Fatalf("%s keyset cursor repeated issue %s", sortCase.Field, row.Issue.ID)
+ }
+ }
+ }
+
+ filteredQuery := query
+ filteredQuery.Filters.Statuses = []string{"todo"}
+ facetsRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableFacets(facetsRecorder, newRequest("POST", "/api/issues/table/facets", issueTableFacetsRequest{
+ Query: filteredQuery,
+ Facets: []issueTableFacetSpec{{Kind: "status"}},
+ }))
+ if facetsRecorder.Code != http.StatusOK {
+ t.Fatalf("facets status = %d: %s", facetsRecorder.Code, facetsRecorder.Body.String())
+ }
+ var facets issueTableFacetsResponse
+ if err := json.NewDecoder(facetsRecorder.Body).Decode(&facets); err != nil {
+ t.Fatalf("decode facets: %v", err)
+ }
+ if facets.Total != 501 || len(facets.Facets) != 1 {
+ t.Fatalf("unexpected filtered facet response: total=%d facets=%d", facets.Total, len(facets.Facets))
+ }
+ facetCounts := map[string]int64{}
+ for _, value := range facets.Facets[0].Values {
+ facetCounts[value.Key] = value.Count
+ }
+ if facetCounts["todo"] != 501 || facetCounts["done"] != 500 {
+ t.Fatalf("status facet must ignore its own active filter: %#v", facetCounts)
+ }
+
+ includeTotal := false
+ facetCountQueries := 0
+ facetsHandler := *testHandler
+ facetsHandler.TxStarter = issueTableEnrichmentFailTxStarter{
+ inner: testHandler.TxStarter,
+ tableQueryCalls: &facetCountQueries,
+ }
+ noTotalRecorder := httptest.NewRecorder()
+ facetsHandler.ListIssueTableFacets(noTotalRecorder, newRequest("POST", "/api/issues/table/facets", issueTableFacetsRequest{
+ Query: filteredQuery,
+ Facets: []issueTableFacetSpec{{Kind: "status"}},
+ IncludeTotal: &includeTotal,
+ }))
+ if noTotalRecorder.Code != http.StatusOK {
+ t.Fatalf("facets without total status = %d: %s", noTotalRecorder.Code, noTotalRecorder.Body.String())
+ }
+ var noTotal issueTableFacetsResponse
+ if err := json.NewDecoder(noTotalRecorder.Body).Decode(&noTotal); err != nil {
+ t.Fatalf("decode facets without total: %v", err)
+ }
+ if noTotal.Total != 0 || len(noTotal.Facets) != 1 {
+ t.Fatalf("unexpected facets without total: %#v", noTotal)
+ }
+ if facetCountQueries != 0 {
+ t.Fatalf("include_total=false executed %d total count queries, want 0", facetCountQueries)
+ }
+
+ batchFacetQueries := 0
+ batchTotalQueries := 0
+ batchHandler := *testHandler
+ batchHandler.TxStarter = issueTableEnrichmentFailTxStarter{
+ inner: testHandler.TxStarter,
+ facetQueryCalls: &batchFacetQueries,
+ tableQueryCalls: &batchTotalQueries,
+ }
+ batchRecorder := httptest.NewRecorder()
+ batchHandler.ListIssueTableFacets(batchRecorder, newRequest("POST", "/api/issues/table/facets", issueTableFacetsRequest{
+ Query: query,
+ Facets: []issueTableFacetSpec{
+ {Kind: "status"},
+ {Kind: "priority"},
+ {Kind: "assignee"},
+ {Kind: "creator"},
+ {Kind: "project"},
+ },
+ }))
+ if batchRecorder.Code != http.StatusOK {
+ t.Fatalf("batch facets status = %d: %s", batchRecorder.Code, batchRecorder.Body.String())
+ }
+ var batchResponse issueTableFacetsResponse
+ if err := json.NewDecoder(batchRecorder.Body).Decode(&batchResponse); err != nil {
+ t.Fatalf("decode batch facets: %v", err)
+ }
+ if batchResponse.Total != 1001 || len(batchResponse.Facets) != 5 {
+ t.Fatalf("unexpected batch facets response: total=%d facets=%d", batchResponse.Total, len(batchResponse.Facets))
+ }
+ if batchFacetQueries != 1 || batchTotalQueries != 0 {
+ t.Fatalf("batch facets executed grouping queries=%d total queries=%d, want 1 and 0", batchFacetQueries, batchTotalQueries)
+ }
+ batchCounts := make(map[string]map[string]int64, len(batchResponse.Facets))
+ for _, facet := range batchResponse.Facets {
+ counts := make(map[string]int64, len(facet.Values))
+ for _, value := range facet.Values {
+ counts[value.Key] = value.Count
+ }
+ batchCounts[facet.Kind] = counts
+ }
+ if batchCounts["status"]["todo"] != 501 || batchCounts["status"]["done"] != 500 ||
+ batchCounts["priority"]["none"] != 1001 ||
+ batchCounts["assignee"]["__none__"] != 1001 ||
+ batchCounts["creator"]["member:"+testUserID] != 1001 ||
+ batchCounts["project"][projectID] != 1001 {
+ t.Fatalf("unexpected batched facet counts: %#v", batchCounts)
+ }
+
+ mixedRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableFacets(mixedRecorder, newRequest("POST", "/api/issues/table/facets", issueTableFacetsRequest{
+ Query: filteredQuery,
+ Facets: []issueTableFacetSpec{{Kind: "status"}, {Kind: "priority"}},
+ }))
+ if mixedRecorder.Code != http.StatusOK {
+ t.Fatalf("mixed facets status = %d: %s", mixedRecorder.Code, mixedRecorder.Body.String())
+ }
+ var mixedResponse issueTableFacetsResponse
+ if err := json.NewDecoder(mixedRecorder.Body).Decode(&mixedResponse); err != nil {
+ t.Fatalf("decode mixed facets: %v", err)
+ }
+ if mixedResponse.Total != 501 || len(mixedResponse.Facets) != 2 ||
+ mixedResponse.Facets[0].Kind != "status" || mixedResponse.Facets[1].Kind != "priority" {
+ t.Fatalf("unexpected mixed facets response: %#v", mixedResponse)
+ }
+ mixedCounts := make(map[string]map[string]int64, len(mixedResponse.Facets))
+ for _, facet := range mixedResponse.Facets {
+ counts := make(map[string]int64, len(facet.Values))
+ for _, value := range facet.Values {
+ counts[value.Key] = value.Count
+ }
+ mixedCounts[facet.Kind] = counts
+ }
+ if mixedCounts["status"]["todo"] != 501 || mixedCounts["status"]["done"] != 500 ||
+ mixedCounts["priority"]["none"] != 501 {
+ t.Fatalf("mixed facets lost disjunctive semantics: %#v", mixedCounts)
+ }
+}
+
+func TestIssueTableAssigneeNamesResolveAfterGrouping(t *testing.T) {
+ ctx := context.Background()
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, 'Server table assignee grouping')
+ RETURNING id
+ `, testWorkspaceID).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE project_id = $1`, projectID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+
+ var finalNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(
+ issue_counter,
+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)
+ ) + 2
+ WHERE id = $1
+ RETURNING issue_counter
+ `, testWorkspaceID).Scan(&finalNumber); err != nil {
+ t.Fatalf("reserve issue numbers: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, status, priority, assignee_type, assignee_id,
+ creator_type, creator_id, position, number, project_id
+ )
+ VALUES
+ ($1, 'Assigned row', 'todo', 'none', 'member', $2, 'member', $2, 1, $3, $4),
+ ($1, 'Unassigned row', 'todo', 'none', NULL, NULL, 'member', $2, 2, $3 + 1, $4)
+ `, testWorkspaceID, testUserID, finalNumber-1, projectID); err != nil {
+ t.Fatalf("seed issues: %v", err)
+ }
+
+ groupQuerySQL := ""
+ handler := *testHandler
+ handler.TxStarter = issueTableEnrichmentFailTxStarter{
+ inner: testHandler.TxStarter,
+ groupQuerySQL: &groupQuerySQL,
+ }
+ recorder := httptest.NewRecorder()
+ handler.ListIssueTableGroups(recorder, newRequest("POST", "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ },
+ Group: issueTableGroupSpec{Kind: "assignee"},
+ Page: issueTablePageRequest{Limit: 10},
+ }))
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("groups status = %d: %s", recorder.Code, recorder.Body.String())
+ }
+ var response issueTableGroupsResponse
+ if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {
+ t.Fatalf("decode groups: %v", err)
+ }
+ counts := make(map[string]int64, len(response.Groups))
+ for _, group := range response.Groups {
+ counts[group.Key] = group.Count
+ }
+ if counts["assignee:member:"+testUserID] != 1 || counts["assignee:unassigned"] != 1 {
+ t.Fatalf("unexpected assignee groups: %#v", counts)
+ }
+ sortedAt := strings.Index(groupQuerySQL, "), sorted AS (")
+ nameLookupAt := strings.Index(groupQuerySQL, `SELECT u.name FROM "user" u`)
+ if sortedAt < 0 || nameLookupAt < sortedAt {
+ t.Fatalf("assignee names must resolve after actor aggregation:\n%s", groupQuerySQL)
+ }
+}
+
+func TestIssueTableHierarchyDoesNotCrossGroups(t *testing.T) {
+ ctx := context.Background()
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, 'Server table cross-group hierarchy')
+ RETURNING id
+ `, testWorkspaceID).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE project_id = $1`, projectID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+
+ var finalNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(
+ issue_counter,
+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)
+ ) + 2
+ WHERE id = $1
+ RETURNING issue_counter
+ `, testWorkspaceID).Scan(&finalNumber); err != nil {
+ t.Fatalf("reserve issue numbers: %v", err)
+ }
+ var parentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, status, priority, creator_type, creator_id,
+ position, number, project_id
+ )
+ VALUES ($1, 'Todo parent', 'todo', 'none', 'member', $2, 1, $3, $4)
+ RETURNING id
+ `, testWorkspaceID, testUserID, finalNumber-1, projectID).Scan(&parentID); err != nil {
+ t.Fatalf("create parent: %v", err)
+ }
+ var childID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, status, priority, creator_type, creator_id,
+ parent_issue_id, position, number, project_id
+ )
+ VALUES ($1, 'Done child', 'done', 'none', 'member', $2, $3, 2, $4, $5)
+ RETURNING id
+ `, testWorkspaceID, testUserID, parentID, finalNumber, projectID).Scan(&childID); err != nil {
+ t.Fatalf("create child: %v", err)
+ }
+
+ query := issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},
+ Filters: issueTableFiltersRequest{},
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ }
+ rowQuerySQL := ""
+ rowsHandler := *testHandler
+ rowsHandler.TxStarter = issueTableEnrichmentFailTxStarter{
+ inner: testHandler.TxStarter,
+ rowQuerySQL: &rowQuerySQL,
+ }
+ listGroup := func(groupKey string) issueTableRowsResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ rowsHandler.ListIssueTableRows(w, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "status"},
+ GroupKey: &groupKey,
+ Hierarchy: issueTableHierarchyRequest{Enabled: true},
+ Page: issueTablePageRequest{Limit: 50},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("list %s: status=%d body=%s", groupKey, w.Code, w.Body.String())
+ }
+ var response issueTableRowsResponse
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode %s: %v", groupKey, err)
+ }
+ return response
+ }
+
+ doneRows := listGroup("status:done")
+ if len(doneRows.Rows) != 1 || doneRows.Rows[0].Issue.ID != childID {
+ t.Fatalf("done child must become a root in its own group: %#v", doneRows.Rows)
+ }
+ todoRows := listGroup("status:todo")
+ if len(todoRows.Rows) != 1 || todoRows.Rows[0].Issue.ID != parentID {
+ t.Fatalf("todo group root mismatch: %#v", todoRows.Rows)
+ }
+ if todoRows.Rows[0].DirectChildCount != 0 {
+ t.Fatalf("cross-group child leaked into todo parent count: %d", todoRows.Rows[0].DirectChildCount)
+ }
+ if !strings.Contains(rowQuerySQL, "membership AS NOT MATERIALIZED") ||
+ !strings.Contains(rowQuerySQL, "page AS MATERIALIZED") ||
+ !strings.Contains(rowQuerySQL, "(SELECT parent.id FROM membership parent") ||
+ strings.Contains(rowQuerySQL, "NOT EXISTS (SELECT 1 FROM membership parent") ||
+ strings.Contains(rowQuerySQL, "child_counts AS") {
+ t.Fatalf("hierarchy rows query must preserve ordered paging and page-local counts:\n%s", rowQuerySQL)
+ }
+}
+
+func TestIssueTableHierarchyRootKeysetPagination(t *testing.T) {
+ ctx := context.Background()
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, 'Server table hierarchy pagination')
+ RETURNING id
+ `, testWorkspaceID).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE project_id = $1`, projectID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+
+ var finalNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(
+ issue_counter,
+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)
+ ) + 3
+ WHERE id = $1
+ RETURNING issue_counter
+ `, testWorkspaceID).Scan(&finalNumber); err != nil {
+ t.Fatalf("reserve issue numbers: %v", err)
+ }
+ rows, err := testPool.Query(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, status, priority, creator_type, creator_id,
+ position, number, project_id
+ )
+ SELECT $1, 'Hierarchy root ' || n::text, 'todo', 'none', 'member', $2,
+ n::double precision, $3 + n - 1, $4
+ FROM generate_series(1, 3) AS n
+ ORDER BY n
+ RETURNING id
+ `, testWorkspaceID, testUserID, finalNumber-2, projectID)
+ if err != nil {
+ t.Fatalf("seed hierarchy roots: %v", err)
+ }
+ expectedIDs := make(map[string]struct{}, 3)
+ for rows.Next() {
+ var issueID string
+ if err := rows.Scan(&issueID); err != nil {
+ rows.Close()
+ t.Fatalf("scan hierarchy root: %v", err)
+ }
+ expectedIDs[issueID] = struct{}{}
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ t.Fatalf("seed hierarchy roots: %v", err)
+ }
+ rows.Close()
+
+ query := issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},
+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},
+ }
+ fetchPage := func(cursor *string) issueTableRowsResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableRows(w, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "none"},
+ Hierarchy: issueTableHierarchyRequest{Enabled: true},
+ Page: issueTablePageRequest{Limit: 2, Cursor: cursor},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("list hierarchy roots: status=%d body=%s", w.Code, w.Body.String())
+ }
+ var response issueTableRowsResponse
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode hierarchy roots: %v", err)
+ }
+ return response
+ }
+
+ first := fetchPage(nil)
+ if first.Total != 3 || len(first.Rows) != 2 || first.NextCursor == nil {
+ t.Fatalf("unexpected first hierarchy page: total=%d rows=%d cursor=%v", first.Total, len(first.Rows), first.NextCursor)
+ }
+ second := fetchPage(first.NextCursor)
+ if second.Total != 0 || len(second.Rows) != 1 || second.NextCursor != nil {
+ t.Fatalf("unexpected second hierarchy page: total=%d rows=%d cursor=%v", second.Total, len(second.Rows), second.NextCursor)
+ }
+
+ seenIDs := make(map[string]struct{}, 3)
+ for _, page := range []issueTableRowsResponse{first, second} {
+ for _, row := range page.Rows {
+ if _, duplicate := seenIDs[row.Issue.ID]; duplicate {
+ t.Fatalf("hierarchy root %s repeated across pages", row.Issue.ID)
+ }
+ seenIDs[row.Issue.ID] = struct{}{}
+ }
+ }
+ if len(seenIDs) != len(expectedIDs) {
+ t.Fatalf("reachable hierarchy roots = %d, want %d", len(seenIDs), len(expectedIDs))
+ }
+ for issueID := range expectedIDs {
+ if _, ok := seenIDs[issueID]; !ok {
+ t.Fatalf("hierarchy root %s was not reachable through pagination", issueID)
+ }
+ }
+}
diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.go
new file mode 100644
index 0000000000..c4680ac76c
--- /dev/null
+++ b/server/internal/handler/issue_table_rows.go
@@ -0,0 +1,465 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "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"
+)
+
+type issueTableRowResponse struct {
+ Issue IssueResponse `json:"issue"`
+ DirectChildCount int64 `json:"direct_child_count"`
+}
+
+type issueTableRowsResponse struct {
+ QueryFingerprint string `json:"query_fingerprint"`
+ GroupKey *string `json:"group_key"`
+ ParentID *string `json:"parent_id"`
+ Total int64 `json:"total"`
+ Rows []issueTableRowResponse `json:"rows"`
+ BranchTotal int64 `json:"branch_total"` // Current page size; retained for response compatibility.
+ NextCursor *string `json:"next_cursor"`
+}
+
+type resolvedIssueTableSort struct {
+ expression string
+ direction string
+ castType string
+ nullsLast bool
+}
+
+func (sort resolvedIssueTableSort) orderBy() string {
+ orderBy := sort.expression + " " + strings.ToUpper(sort.direction)
+ if sort.nullsLast {
+ orderBy += " NULLS LAST"
+ }
+ return orderBy + ", i.created_at DESC, i.id DESC"
+}
+
+func (sort resolvedIssueTableSort) cursorPredicate(w http.ResponseWriter, cursor *issueTableCursor, addArg func(any) string) (string, bool) {
+ if cursor == nil {
+ return "TRUE", true
+ }
+ createdAt, err := time.Parse(time.RFC3339Nano, cursor.RowCreatedAt)
+ if err != nil || cursor.RowID == "" {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ rowID, err := util.ParseUUID(cursor.RowID)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ createdRef := addArg(createdAt)
+ idRef := addArg(rowID)
+ tie := fmt.Sprintf("(i.created_at < %s::timestamptz OR (i.created_at = %s::timestamptz AND i.id < %s::uuid))", createdRef, createdRef, idRef)
+ if cursor.SortIsNull {
+ if !sort.nullsLast || cursor.SortValue != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ return fmt.Sprintf("(%s IS NULL AND %s)", sort.expression, tie), true
+ }
+ if cursor.SortValue == nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ switch sort.castType {
+ case "integer":
+ if _, err := strconv.ParseInt(*cursor.SortValue, 10, 64); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ case "double precision", "numeric":
+ if _, err := strconv.ParseFloat(*cursor.SortValue, 64); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ case "timestamptz":
+ if _, err := time.Parse(time.RFC3339Nano, *cursor.SortValue); err != nil {
+ if _, postgresErr := time.Parse("2006-01-02 15:04:05.999999999Z07", *cursor.SortValue); postgresErr != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ }
+ case "date":
+ if _, err := time.Parse("2006-01-02", *cursor.SortValue); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return "", false
+ }
+ }
+ valueRef := addArg(*cursor.SortValue)
+ valueExpr := fmt.Sprintf("%s::%s", valueRef, sort.castType)
+ comparison := ">"
+ if sort.direction == "desc" {
+ comparison = "<"
+ }
+ predicate := fmt.Sprintf("(%s %s %s OR (%s = %s AND %s))", sort.expression, comparison, valueExpr, sort.expression, valueExpr, tie)
+ if sort.expression == "i.position" {
+ // The exact mixed-direction keyset predicate is not itself indexable.
+ // This redundant lower bound lets PostgreSQL start the default position
+ // index at the cursor instead of filtering every preceding index entry.
+ predicate = fmt.Sprintf("(%s >= %s AND %s)", sort.expression, valueExpr, predicate)
+ }
+ if sort.nullsLast {
+ predicate = fmt.Sprintf("(%s IS NULL OR %s)", sort.expression, predicate)
+ }
+ return predicate, true
+}
+
+func (h *Handler) issueTableOrderBy(w http.ResponseWriter, r *http.Request, workspaceID string, sortRequest issueTableSortRequest) (resolvedIssueTableSort, bool) {
+ sortField := strings.TrimSpace(sortRequest.Field)
+ if sortField == "" {
+ sortField = "position"
+ }
+ resolved := resolvedIssueTableSort{
+ expression: "i.position",
+ direction: "asc",
+ castType: "double precision",
+ }
+ switch sortField {
+ case "position":
+ case "title":
+ resolved.expression = "i.title"
+ resolved.castType = "text"
+ case "created_at", "updated_at":
+ resolved.expression = "i." + sortField
+ resolved.castType = "timestamptz"
+ case "start_date", "due_date":
+ resolved.expression = "i." + sortField
+ resolved.castType = "date"
+ resolved.nullsLast = true
+ case "status":
+ resolved.expression = "CASE i.status WHEN 'backlog' THEN 0 WHEN 'todo' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'in_review' THEN 3 WHEN 'done' THEN 4 WHEN 'blocked' THEN 5 WHEN 'cancelled' THEN 6 ELSE 7 END"
+ resolved.castType = "integer"
+ case "priority":
+ resolved.expression = "CASE i.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END"
+ resolved.castType = "integer"
+ default:
+ expr, handled, err := h.propertySortExpr(r, workspaceID, sortField)
+ if !handled {
+ writeError(w, http.StatusBadRequest, "invalid query.sort.field")
+ return resolvedIssueTableSort{}, false
+ }
+ if err != nil {
+ if strings.HasPrefix(err.Error(), "resolve sort property:") {
+ slog.Warn("resolve table sort property failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to resolve table sort")
+ } else {
+ writeError(w, http.StatusBadRequest, err.Error())
+ }
+ return resolvedIssueTableSort{}, false
+ }
+ if expr != "" {
+ resolved.expression = expr
+ resolved.castType = "text"
+ if strings.Contains(expr, "::numeric") {
+ resolved.castType = "numeric"
+ }
+ resolved.nullsLast = true
+ }
+ }
+
+ direction := strings.ToLower(strings.TrimSpace(sortRequest.Direction))
+ if direction == "" {
+ direction = "asc"
+ }
+ if direction != "asc" && direction != "desc" {
+ writeError(w, http.StatusBadRequest, "invalid query.sort.direction")
+ return resolvedIssueTableSort{}, false
+ }
+ if sortField != "position" && resolved.expression != "i.position" {
+ resolved.direction = direction
+ }
+ return resolved, true
+}
+
+func normalizeIssueTableGroupKey(w http.ResponseWriter, group issueTableGroupSpec, groupKey *string) (*string, bool) {
+ if group.Kind == "none" {
+ if groupKey != nil && strings.TrimSpace(*groupKey) != "" {
+ writeError(w, http.StatusBadRequest, "group_key must be empty when group.kind=none")
+ return nil, false
+ }
+ return nil, true
+ }
+ if groupKey == nil || strings.TrimSpace(*groupKey) == "" {
+ writeError(w, http.StatusBadRequest, "group_key is required")
+ return nil, false
+ }
+ normalized := strings.TrimSpace(*groupKey)
+ return &normalized, true
+}
+
+func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {
+ if h.DB == nil {
+ writeError(w, http.StatusInternalServerError, "database is unavailable")
+ return
+ }
+ baseHandler := h
+ var request issueTableRowsRequest
+ if !decodeIssueTableJSON(w, r, &request) {
+ return
+ }
+ r, cancel := withIssueTableQueryTimeout(r)
+ defer cancel()
+ snapshot, tx, err := h.beginIssueTableSnapshot(r.Context())
+ if err != nil {
+ slog.Warn("ListIssueTableRows snapshot failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to start table query")
+ return
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback(context.Background())
+ }
+ }()
+ h = snapshot
+ limit, cursor, ok := normalizeIssueTablePage(w, request.Page)
+ if !ok {
+ return
+ }
+ groupKey, ok := normalizeIssueTableGroupKey(w, request.Group, request.GroupKey)
+ if !ok {
+ return
+ }
+ if !request.Hierarchy.Enabled && request.ParentID != nil {
+ writeError(w, http.StatusBadRequest, "parent_id requires hierarchy.enabled=true")
+ return
+ }
+ compiled, ok := h.compileIssueTableQuery(w, r, request.Query)
+ if !ok {
+ return
+ }
+ if !issueTableCursorMatches(w, cursor, compiled.fingerprint, groupKey, request.ParentID) {
+ return
+ }
+ branchIdentity := issueTableGroupIdentity(request.Group) + ":hierarchy=" + strconv.FormatBool(request.Hierarchy.Enabled)
+ if cursor != nil && cursor.BranchIdentity != branchIdentity {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "cursor_query_mismatch",
+ "message": "cursor does not belong to this table branch",
+ })
+ return
+ }
+ group, ok := h.resolveIssueTableGroup(w, r, compiled.workspaceID, request.Group, true)
+ if !ok {
+ return
+ }
+ resolvedSort, ok := h.issueTableOrderBy(w, r, util.UUIDToString(compiled.workspaceID), request.Query.Sort)
+ if !ok {
+ return
+ }
+
+ args := append([]any(nil), compiled.args...)
+ addArg := func(value any) string {
+ args = append(args, value)
+ return "$" + strconv.Itoa(len(args))
+ }
+ predicateKey := ""
+ if groupKey != nil {
+ predicateKey = *groupKey
+ }
+ groupPredicate, ok := group.predicate(w, predicateKey, addArg)
+ if !ok {
+ return
+ }
+ branchPredicate := "TRUE"
+ if request.Hierarchy.Enabled {
+ if request.ParentID == nil {
+ // Keep parent membership as a scalar lookup. NOT EXISTS is equivalent
+ // semantically, but PostgreSQL turns it into a full hash anti-join and
+ // loses the ordered workspace index before LIMIT.
+ branchPredicate = "i.parent_issue_id IS NULL OR (SELECT parent.id FROM membership parent WHERE parent.id = i.parent_issue_id) IS NULL"
+ } else {
+ parentUUID, err := util.ParseUUID(*request.ParentID)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid parent_id")
+ return
+ }
+ parentRef := addArg(parentUUID)
+ branchPredicate = fmt.Sprintf("i.parent_issue_id = %s::uuid AND EXISTS (SELECT 1 FROM membership parent WHERE parent.id = %s::uuid)", parentRef, parentRef)
+ }
+ }
+ cursorPredicate, ok := resolvedSort.cursorPredicate(w, cursor, addArg)
+ if !ok {
+ return
+ }
+ limitRef := addArg(limit + 1)
+
+ // Pick the requested page before computing hierarchy metadata. The old query
+ // materialized every matching issue and aggregated every parent before LIMIT,
+ // which made a 51-row page spill the entire workspace membership to disk.
+ // NOT MATERIALIZED lets PostgreSQL push parent_id/id predicates into issue and
+ // use the parent indexes for child branches and per-page child counts.
+ ctePrefix := "WITH "
+ pageSource := "issue"
+ pagePredicate := fmt.Sprintf("(%s) AND (%s)", compiled.where, groupPredicate)
+ if request.Hierarchy.Enabled {
+ ctePrefix += fmt.Sprintf(`membership AS NOT MATERIALIZED (
+ SELECT i.*
+ FROM issue i
+ WHERE %s AND (%s)
+), `, compiled.where, groupPredicate)
+ pageSource = "membership"
+ pagePredicate = branchPredicate
+ }
+ cte := fmt.Sprintf(`%spage AS MATERIALIZED (
+ SELECT i.*, (%s)::text AS table_sort_key
+ FROM %s i
+ WHERE (%s) AND %s
+ ORDER BY %s
+ LIMIT %s
+)`, ctePrefix, resolvedSort.expression, pageSource, pagePredicate, cursorPredicate, resolvedSort.orderBy(), limitRef)
+ childCountExpr := "0::bigint"
+ if request.Hierarchy.Enabled {
+ childCountExpr = "(SELECT COUNT(*)::bigint FROM membership child WHERE child.parent_issue_id = i.id)"
+ }
+
+ query := fmt.Sprintf(`%s
+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
+ i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at,
+ i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties,
+ %s AS direct_child_count, i.table_sort_key
+ FROM page i
+ ORDER BY %s`, cte, childCountExpr, resolvedSort.orderBy())
+
+ rows, err := h.DB.Query(r.Context(), query, args...)
+ if err != nil {
+ slog.Warn("ListIssueTableRows query failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to list table rows")
+ return
+ }
+ defer rows.Close()
+
+ type scannedRow struct {
+ issue db.ListIssuesRow
+ childCount int64
+ sortKey pgtype.Text
+ }
+ scanned := make([]scannedRow, 0, limit+1)
+ for rows.Next() {
+ var row scannedRow
+ if err := rows.Scan(
+ &row.issue.ID,
+ &row.issue.WorkspaceID,
+ &row.issue.Title,
+ &row.issue.Description,
+ &row.issue.Status,
+ &row.issue.Priority,
+ &row.issue.AssigneeType,
+ &row.issue.AssigneeID,
+ &row.issue.CreatorType,
+ &row.issue.CreatorID,
+ &row.issue.ParentIssueID,
+ &row.issue.Position,
+ &row.issue.StartDate,
+ &row.issue.DueDate,
+ &row.issue.CreatedAt,
+ &row.issue.UpdatedAt,
+ &row.issue.Number,
+ &row.issue.ProjectID,
+ &row.issue.Metadata,
+ &row.issue.Stage,
+ &row.issue.Properties,
+ &row.childCount,
+ &row.sortKey,
+ ); err != nil {
+ writeIssueTableQueryFailure(w, r, "failed to list table rows")
+ return
+ }
+ scanned = append(scanned, row)
+ }
+ if err := rows.Err(); err != nil {
+ writeIssueTableQueryFailure(w, r, "failed to list table rows")
+ return
+ }
+ rows.Close()
+
+ // Only the ungrouped root head consumes a query-wide total. Group headers
+ // get their exact totals from /groups; child branches and continuation pages
+ // must not pay for a full-membership COUNT.
+ var total int64
+ if cursor == nil && request.Group.Kind == "none" && request.ParentID == nil {
+ if err := h.DB.QueryRow(r.Context(), fmt.Sprintf("SELECT COUNT(*)::bigint FROM issue i WHERE %s", compiled.where), compiled.args...).Scan(&total); err != nil {
+ slog.Warn("ListIssueTableRows total count failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to count table rows")
+ return
+ }
+ }
+
+ var nextCursor *string
+ if len(scanned) > limit {
+ scanned = scanned[:limit]
+ last := scanned[len(scanned)-1]
+ var sortValue *string
+ if last.sortKey.Valid {
+ value := last.sortKey.String
+ sortValue = &value
+ }
+ nextCursor = encodeIssueTableCursor(issueTableCursor{
+ Version: 1,
+ QueryFingerprint: compiled.fingerprint,
+ GroupKey: groupKey,
+ ParentID: request.ParentID,
+ BranchIdentity: branchIdentity,
+ SortValue: sortValue,
+ SortIsNull: !last.sortKey.Valid,
+ RowCreatedAt: last.issue.CreatedAt.Time.UTC().Format(time.RFC3339Nano),
+ RowID: util.UUIDToString(last.issue.ID),
+ })
+ }
+
+ // The row window, optional root total and cursor are the authoritative snapshot. Commit
+ // it before the best-effort display enrichment below: PostgreSQL aborts a
+ // transaction after any statement error, so running getIssuePrefix or
+ // labelsByIssue inside the snapshot would turn their intentionally tolerated
+ // failures into a fatal Commit error for the entire page.
+ if err := tx.Commit(r.Context()); err != nil {
+ slog.Warn("ListIssueTableRows snapshot commit failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to finish table query")
+ return
+ }
+ committed = true
+
+ prefix := baseHandler.getIssuePrefix(r.Context(), compiled.workspaceID)
+ issueIDs := make([]pgtype.UUID, len(scanned))
+ for index, row := range scanned {
+ issueIDs[index] = row.issue.ID
+ }
+ labelsByIssue := baseHandler.labelsByIssue(r.Context(), compiled.workspaceID, issueIDs)
+ responseRows := make([]issueTableRowResponse, len(scanned))
+ for index, row := range scanned {
+ issue := issueListRowToResponse(row.issue, prefix)
+ labels := labelsByIssue[issue.ID]
+ if labels == nil {
+ labels = []LabelResponse{}
+ }
+ issue.Labels = &labels
+ responseRows[index] = issueTableRowResponse{
+ Issue: issue,
+ DirectChildCount: row.childCount,
+ }
+ }
+
+ response := issueTableRowsResponse{
+ QueryFingerprint: compiled.fingerprint,
+ GroupKey: groupKey,
+ ParentID: request.ParentID,
+ Total: total,
+ Rows: responseRows,
+ BranchTotal: int64(len(responseRows)),
+ NextCursor: nextCursor,
+ }
+ writeJSON(w, http.StatusOK, response)
+}
diff --git a/server/migrations/203_issue_workspace_assignee_index.down.sql b/server/migrations/203_issue_workspace_assignee_index.down.sql
new file mode 100644
index 0000000000..2befa8f934
--- /dev/null
+++ b/server/migrations/203_issue_workspace_assignee_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_workspace_assignee;
diff --git a/server/migrations/203_issue_workspace_assignee_index.up.sql b/server/migrations/203_issue_workspace_assignee_index.up.sql
new file mode 100644
index 0000000000..1e696b27ed
--- /dev/null
+++ b/server/migrations/203_issue_workspace_assignee_index.up.sql
@@ -0,0 +1,5 @@
+-- Server-side Table grouping filters by workspace before grouping assignees.
+-- Keep the concurrent build isolated so writes to the hot issue table remain
+-- available while existing workspaces are indexed.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_assignee
+ ON issue (workspace_id, assignee_type, assignee_id);
diff --git a/server/migrations/204_issue_workspace_parent_index.down.sql b/server/migrations/204_issue_workspace_parent_index.down.sql
new file mode 100644
index 0000000000..1a567cabb3
--- /dev/null
+++ b/server/migrations/204_issue_workspace_parent_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_workspace_parent;
diff --git a/server/migrations/204_issue_workspace_parent_index.up.sql b/server/migrations/204_issue_workspace_parent_index.up.sql
new file mode 100644
index 0000000000..bafb61130e
--- /dev/null
+++ b/server/migrations/204_issue_workspace_parent_index.up.sql
@@ -0,0 +1,4 @@
+-- Root/child Table branches always resolve hierarchy inside one workspace.
+-- The existing parent-only index cannot prune another workspace first.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_parent
+ ON issue (workspace_id, parent_issue_id);
diff --git a/server/migrations/205_issue_workspace_position_index.down.sql b/server/migrations/205_issue_workspace_position_index.down.sql
new file mode 100644
index 0000000000..8a10ef495c
--- /dev/null
+++ b/server/migrations/205_issue_workspace_position_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_workspace_position;
diff --git a/server/migrations/205_issue_workspace_position_index.up.sql b/server/migrations/205_issue_workspace_position_index.up.sql
new file mode 100644
index 0000000000..69218648cb
--- /dev/null
+++ b/server/migrations/205_issue_workspace_position_index.up.sql
@@ -0,0 +1,4 @@
+-- Serve the Table API's default keyset order without scanning and sorting the
+-- entire workspace on every page.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_position
+ ON issue (workspace_id, position, created_at DESC, id DESC);