Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(timeline): cursor-paginated timeline to stop long-issue freeze (#1968) (#2128)
Naiyuan Qingba147708a6d8
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex f5e8e95184..1cb238b34b 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -42,7 +42,8 @@ import type {RuntimeLocalSkillListRequest,CreateRuntimeLocalSkillImportRequest,RuntimeLocalSkillImportRequest,- TimelineEntry,+ TimelinePage,+ TimelinePageParam,AssigneeFrequencyEntry,TaskMessagePayload,Attachment,@@ -494,8 +495,17 @@ export class ApiClient {});}- async listTimeline(issueId: string): Promise<TimelineEntry[]> {- return this.fetch(`/api/issues/${issueId}/timeline`);+ async listTimeline(+ issueId: string,+ pageParam: TimelinePageParam = { mode: "latest" },+ limit = 50,+ ): Promise<TimelinePage> {+ const params = new URLSearchParams();+ params.set("limit", String(limit));+ if (pageParam.mode === "before") params.set("before", pageParam.cursor);+ else if (pageParam.mode === "after") params.set("after", pageParam.cursor);+ else if (pageParam.mode === "around") params.set("around", pageParam.id);+ return this.fetch(`/api/issues/${issueId}/timeline?${params.toString()}`);}async getAssigneeFrequency(): Promise<AssigneeFrequencyEntry[]> {diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex f9bddbd3ac..d3419c7e45 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -23,6 +23,12 @@ import type {ListIssuesCache,} from "../types";import type { TimelineEntry, IssueSubscriber, Reaction } from "../types";+import {+ mapAllEntries,+ filterAllEntries,+ prependToLatestPage,+ type TimelineCacheData,+} from "./timeline-cache";// ---------------------------------------------------------------------------// Shared mutation variable types — used by both mutation hooks and@@ -312,26 +318,27 @@ export function useCreateComment(issueId: string) {attachmentIds?: string[];}) => api.createComment(issueId, content, type, parentId, attachmentIds),onSuccess: (comment) => {- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),- (old) => {- if (!old) return old;- const entry: TimelineEntry = {- type: "comment",- id: comment.id,- actor_type: comment.author_type,- actor_id: comment.author_id,- content: comment.content,- parent_id: comment.parent_id,- comment_type: comment.type,- reactions: comment.reactions ?? [],- attachments: comment.attachments ?? [],- created_at: comment.created_at,- updated_at: comment.updated_at,- };- if (old.some((e) => e.id === comment.id)) return old;- return [...old, entry];- },+ // Write into every paginated timeline cache that's currently at-latest+ // (around-mode caches viewing older windows skip silently inside+ // prependToLatestPage). Both the latest cache and any open around-mode+ // window that has been scrolled all the way to the live tail get the+ // optimistic entry; everything else falls back to invalidation.+ const entry: TimelineEntry = {+ type: "comment",+ id: comment.id,+ actor_type: comment.author_type,+ actor_id: comment.author_id,+ content: comment.content,+ parent_id: comment.parent_id,+ comment_type: comment.type,+ reactions: comment.reactions ?? [],+ attachments: comment.attachments ?? [],+ created_at: comment.created_at,+ updated_at: comment.updated_at,+ };+ qc.setQueriesData<TimelineCacheData>(+ { queryKey: ["issues", "timeline", issueId] },+ (old) => prependToLatestPage(old, entry),);},onSettled: () => {@@ -346,18 +353,27 @@ export function useUpdateComment(issueId: string) {mutationFn: ({ commentId, content }: { commentId: string; content: string }) =>api.updateComment(commentId, content),onMutate: async ({ commentId, content }) => {- await qc.cancelQueries({ queryKey: issueKeys.timeline(issueId) });- const prev = qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId));- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),+ await qc.cancelQueries({ queryKey: ["issues", "timeline", issueId] });+ // Snapshot every open timeline cache (latest + any around windows) so+ // an error rollback restores them all atomically.+ const prevSnapshots = qc.getQueriesData<TimelineCacheData>({+ queryKey: ["issues", "timeline", issueId],+ });+ qc.setQueriesData<TimelineCacheData>(+ { queryKey: ["issues", "timeline", issueId] },(old) =>- old?.map((e) => (e.id === commentId ? { ...e, content } : e)),+ mapAllEntries(old, (e) =>+ e.id === commentId ? { ...e, content } : e,+ ),);- return { prev };+ return { prevSnapshots };},onError: (_err, _vars, ctx) => {- if (ctx?.prev)- qc.setQueryData(issueKeys.timeline(issueId), ctx.prev);+ if (ctx?.prevSnapshots) {+ for (const [key, prev] of ctx.prevSnapshots) {+ qc.setQueryData(key, prev);+ }+ }},onSettled: () => {qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });@@ -370,33 +386,45 @@ export function useDeleteComment(issueId: string) {return useMutation({mutationFn: (commentId: string) => api.deleteComment(commentId),onMutate: async (commentId) => {- await qc.cancelQueries({ queryKey: issueKeys.timeline(issueId) });- const prev = qc.getQueryData<TimelineEntry[]>(issueKeys.timeline(issueId));+ await qc.cancelQueries({ queryKey: ["issues", "timeline", issueId] });+ const prevSnapshots = qc.getQueriesData<TimelineCacheData>({+ queryKey: ["issues", "timeline", issueId],+ });- // Cascade: collect all child comment IDs+ // Cascade: collect all child comment IDs across every loaded page.const toRemove = new Set<string>([commentId]);- if (prev) {+ for (const [, data] of prevSnapshots) {+ if (!data) continue;let changed = true;while (changed) {changed = false;- for (const e of prev) {- if (e.parent_id && toRemove.has(e.parent_id) && !toRemove.has(e.id)) {- toRemove.add(e.id);- changed = true;+ for (const page of data.pages) {+ for (const e of page.entries) {+ if (+ e.parent_id &&+ toRemove.has(e.parent_id) &&+ !toRemove.has(e.id)+ ) {+ toRemove.add(e.id);+ changed = true;+ }}}}}- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),- (old) => old?.filter((e) => !toRemove.has(e.id)),+ qc.setQueriesData<TimelineCacheData>(+ { queryKey: ["issues", "timeline", issueId] },+ (old) => filterAllEntries(old, (e) => toRemove.has(e.id)),);- return { prev };+ return { prevSnapshots };},onError: (_err, _id, ctx) => {- if (ctx?.prev)- qc.setQueryData(issueKeys.timeline(issueId), ctx.prev);+ if (ctx?.prevSnapshots) {+ for (const [key, prev] of ctx.prevSnapshots) {+ qc.setQueryData(key, prev);+ }+ }},onSettled: () => {qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex f36952ac43..0c7cf15307 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -1,6 +1,12 @@-import { queryOptions } from "@tanstack/react-query";+import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";import { api } from "../api";-import type { IssueStatus, ListIssuesParams, ListIssuesCache } from "../types";+import type {+ IssueStatus,+ ListIssuesParams,+ ListIssuesCache,+ TimelinePage,+ TimelinePageParam,+} from "../types";import { BOARD_STATUSES } from "./config";export const issueKeys = {@@ -17,7 +23,15 @@ export const issueKeys = {[...issueKeys.all(wsId), "children", id] as const,childProgress: (wsId: string) =>[...issueKeys.all(wsId), "child-progress"] as const,- timeline: (issueId: string) => ["issues", "timeline", issueId] as const,+ /**+ * Cursor-paginated timeline cache. Around-mode lookups use a separate cache+ * (keyed by the anchor id) so an Inbox-jump fetch does not pollute the+ * default latest-page cache that the regular issue list path consumes.+ */+ timeline: (issueId: string, around?: string | null) =>+ around+ ? (["issues", "timeline", issueId, "around", around] as const)+ : (["issues", "timeline", issueId] as const),reactions: (issueId: string) => ["issues", "reactions", issueId] as const,subscribers: (issueId: string) =>["issues", "subscribers", issueId] as const,@@ -126,10 +140,40 @@ export function childIssuesOptions(wsId: string, id: string) {});}-export function issueTimelineOptions(issueId: string) {- return queryOptions({- queryKey: issueKeys.timeline(issueId),- queryFn: () => api.listTimeline(issueId),+/**+ * Infinite-query options for the cursor-paginated timeline. The first page is+ * either the latest 50 entries (no `around`) or a 50-wide window centered on+ * the given comment/activity id (Inbox jump path). `getNextPageParam` walks+ * older; `getPreviousPageParam` walks newer.+ */+export function issueTimelineInfiniteOptions(+ issueId: string,+ around?: string | null,+) {+ return infiniteQueryOptions<+ TimelinePage,+ Error,+ { pages: TimelinePage[]; pageParams: TimelinePageParam[] },+ readonly unknown[],+ TimelinePageParam+ >({+ queryKey: issueKeys.timeline(issueId, around ?? null),+ initialPageParam: around+ ? ({ mode: "around", id: around } as TimelinePageParam)+ : ({ mode: "latest" } as TimelinePageParam),+ queryFn: ({ pageParam }) => api.listTimeline(issueId, pageParam),+ // Walk older: append a page below the current oldest (last entry of the+ // last loaded page). undefined = no more older entries.+ getNextPageParam: (lastPage) =>+ lastPage.has_more_before && lastPage.next_cursor+ ? ({ mode: "before", cursor: lastPage.next_cursor } as TimelinePageParam)+ : undefined,+ // Walk newer: prepend a page above the current newest (first entry of the+ // first loaded page). undefined = at the latest, no newer to fetch.+ getPreviousPageParam: (firstPage) =>+ firstPage.has_more_after && firstPage.prev_cursor+ ? ({ mode: "after", cursor: firstPage.prev_cursor } as TimelinePageParam)+ : undefined,});}diff --git a/packages/core/issues/timeline-cache.ts b/packages/core/issues/timeline-cache.tsnew file mode 100644index 0000000000..b1affd561c--- /dev/null+++ b/packages/core/issues/timeline-cache.ts@@ -0,0 +1,73 @@+import type { InfiniteData } from "@tanstack/react-query";+import type {+ TimelineEntry,+ TimelinePage,+ TimelinePageParam,+} from "../types";++/** Shape of the cursor-paginated timeline cache. Exported so consumers (the+ * hook, mutations, tests) all reference the same type. */+export type TimelineCacheData = InfiniteData<TimelinePage, TimelinePageParam>;++/** Map fn over every entry across every page, preserving page identity for+ * any page whose entries don't change so React.memo on CommentCard isn't+ * defeated by gratuitous reference churn. */+export function mapAllEntries(+ data: TimelineCacheData | undefined,+ fn: (e: TimelineEntry) => TimelineEntry,+): TimelineCacheData | undefined {+ if (!data) return data;+ let pagesChanged = false;+ const pages = data.pages.map((page) => {+ let entriesChanged = false;+ const entries = page.entries.map((e) => {+ const next = fn(e);+ if (next !== e) entriesChanged = true;+ return next;+ });+ if (!entriesChanged) return page;+ pagesChanged = true;+ return { ...page, entries };+ });+ if (!pagesChanged) return data;+ return { ...data, pages };+}++/** Filter out entries matching the predicate from every page. */+export function filterAllEntries(+ data: TimelineCacheData | undefined,+ predicate: (e: TimelineEntry) => boolean,+): TimelineCacheData | undefined {+ if (!data) return data;+ let pagesChanged = false;+ const pages = data.pages.map((page) => {+ const entries = page.entries.filter((e) => !predicate(e));+ if (entries.length === page.entries.length) return page;+ pagesChanged = true;+ return { ...page, entries };+ });+ if (!pagesChanged) return data;+ return { ...data, pages };+}++/** Prepend a new entry to the latest page (pages[0]). Caller must verify+ * the cache is at-latest before calling — otherwise the entry is hidden+ * behind a "show newer" gap and shouldn't be injected. Returns the data+ * unchanged if the cache is not at-latest or the entry already exists. */+export function prependToLatestPage(+ data: TimelineCacheData | undefined,+ entry: TimelineEntry,+): TimelineCacheData | undefined {+ if (!data || data.pages.length === 0) return data;+ const first = data.pages[0];+ if (!first) return data;+ if (first.has_more_after) return data; // not at latest; skip silently+ if (first.entries.some((e) => e.id === entry.id)) return data;+ return {+ ...data,+ pages: [+ { ...first, entries: [entry, ...first.entries] },+ ...data.pages.slice(1),+ ],+ };+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 443fed8919..004c9fac45 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -24,6 +24,7 @@"./issues": "./issues/index.ts","./issues/queries": "./issues/queries.ts","./issues/mutations": "./issues/mutations.ts",+ "./issues/timeline-cache": "./issues/timeline-cache.ts","./issues/ws-updaters": "./issues/ws-updaters.ts","./issues/config": "./issues/config/index.ts","./issues/config/status": "./issues/config/status.ts",diff --git a/packages/core/types/activity.ts b/packages/core/types/activity.tsindex b857cffc6c..bf43b9bf61 100644--- a/packages/core/types/activity.ts+++ b/packages/core/types/activity.ts@@ -26,3 +26,24 @@ export interface TimelineEntry {/** Set by frontend coalescing when consecutive identical activities are merged. */coalesced_count?: number;}++/**+ * Cursor-paginated timeline page. Entries are newest-first+ * (created_at DESC, id DESC). Cursors are opaque base64 strings — pass them+ * back unchanged via TimelinePageParam.+ */+export interface TimelinePage {+ entries: TimelineEntry[];+ next_cursor: string | null;+ prev_cursor: string | null;+ has_more_before: boolean;+ has_more_after: boolean;+ /** Set only in around-id mode; index of the anchor entry within `entries`. */+ target_index?: number;+}++export type TimelinePageParam =+ | { mode: "latest" }+ | { mode: "before"; cursor: string }+ | { mode: "after"; cursor: string }+ | { mode: "around"; id: string };diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 44564f9b20..c3093c9fea 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -41,7 +41,12 @@ export type { InboxItem, InboxSeverity, InboxItemType } from "./inbox";export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";export type { Comment, CommentType, CommentAuthorType, Reaction } from "./comment";export type { Label, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse } from "./label";-export type { TimelineEntry, AssigneeFrequencyEntry } from "./activity";+export type {+ TimelineEntry,+ TimelinePage,+ TimelinePageParam,+ AssigneeFrequencyEntry,+} from "./activity";export type { IssueSubscriber } from "./subscriber";export type * from "./events";export type * from "./api";diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 5f63783a91..d21fa3f195 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -175,7 +175,13 @@ vi.mock("../../projects/components/project-picker", () => ({// Mock apiconst mockApiObj = vi.hoisted(() => ({getIssue: vi.fn(),- listTimeline: vi.fn().mockResolvedValue([]),+ listTimeline: vi.fn().mockResolvedValue({+ entries: [],+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+ }),listComments: vi.fn().mockResolvedValue([]),createComment: vi.fn(),updateComment: vi.fn(),@@ -381,7 +387,18 @@ describe("IssueDetail (shared)", () => {mockViewport.isMobile = false;// Default: issue loads successfullymockApiObj.getIssue.mockResolvedValue(mockIssue);- mockApiObj.listTimeline.mockResolvedValue(mockTimeline);+ // Cursor-paginated timeline endpoint returns a TimelinePage. The DESC+ // order is required because the hook reverses pages → ASC for the UI.+ const descTimeline = [...mockTimeline].sort((a, b) =>+ b.created_at.localeCompare(a.created_at),+ );+ mockApiObj.listTimeline.mockResolvedValue({+ entries: descTimeline,+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+ });mockApiObj.listIssueReactions.mockResolvedValue([]);mockApiObj.listIssueSubscribers.mockResolvedValue([]);mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 9ce37aacb9..733f06b45c 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -152,6 +152,23 @@ function formatTokenCount(n: number): string {return String(n);}+function TimelineSkeleton() {+ return (+ <div className="mt-4 flex flex-col gap-3">+ {[0, 1].map((i) => (+ <div key={i} className="flex gap-3 p-4">+ <Skeleton className="h-10 w-10 shrink-0 rounded-full" />+ <div className="flex-1 space-y-2">+ <Skeleton className="h-4 w-32" />+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-4/5" />+ </div>+ </div>+ ))}+ </div>+ );+}+// ---------------------------------------------------------------------------// Props// ---------------------------------------------------------------------------@@ -260,9 +277,14 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// Custom hooks — encapsulate timeline, reactions, subscribersconst {- timeline, submitComment, submitReply,+ timeline, loading: timelineLoading,+ submitComment, submitReply,editComment, deleteComment, toggleReaction: handleToggleReaction,- } = useIssueTimeline(id, user?.id);+ hasMoreOlder, hasMoreNewer,+ isFetchingOlder, isFetchingNewer,+ fetchOlder, fetchNewer, jumpToLatest,+ isAtLatest, newEntriesBelowCount,+ } = useIssueTimeline(id, user?.id, { around: highlightCommentId ?? null });// Memoized timeline grouping. The same Map / groups references are reused// across re-renders that don't change `timeline`, so React.memo on@@ -974,6 +996,25 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr<AgentLiveCard key={id} issueId={id} />{/* Timeline entries */}+ {timelineLoading && timelineView.groups.length === 0 ? (+ <TimelineSkeleton />+ ) : (+ <>+ {hasMoreOlder && (+ <div className="my-4 flex items-center gap-3">+ <div className="h-px flex-1 bg-border" />+ <button+ onClick={fetchOlder}+ disabled={isFetchingOlder}+ className="text-xs text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50"+ >+ {isFetchingOlder+ ? t(($) => $.timeline.loading)+ : t(($) => $.timeline.show_older)}+ </button>+ <div className="h-px flex-1 bg-border" />+ </div>+ )}<div className="mt-4 flex flex-col gap-3">{timelineView.groups.map((group) => {if (group.type === "comment") {@@ -1043,6 +1084,35 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr);})}</div>+ {(hasMoreNewer || !isAtLatest) && (+ <div className="mt-4 flex items-center justify-center gap-4">+ {hasMoreNewer && (+ <button+ onClick={fetchNewer}+ disabled={isFetchingNewer}+ className="text-xs text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50"+ >+ {isFetchingNewer+ ? t(($) => $.timeline.loading)+ : t(($) => $.timeline.show_newer)}+ </button>+ )}+ {!isAtLatest && (+ <button+ onClick={jumpToLatest}+ className="text-xs font-medium text-foreground hover:text-foreground/80 transition-colors"+ >+ {newEntriesBelowCount > 0+ ? t(($) => $.timeline.jump_to_latest_with_count, {+ count: newEntriesBelowCount,+ })+ : t(($) => $.timeline.jump_to_latest)}+ </button>+ )}+ </div>+ )}+ </>+ )}{/* Bottom comment input — no avatar, full width */}<div className="mt-4">diff --git a/packages/views/issues/hooks/use-issue-timeline.test.tsx b/packages/views/issues/hooks/use-issue-timeline.test.tsxindex 95e7403d85..5d285fd7a6 100644--- a/packages/views/issues/hooks/use-issue-timeline.test.tsx+++ b/packages/views/issues/hooks/use-issue-timeline.test.tsx@@ -1,5 +1,5 @@-import { describe, it, expect, vi } from "vitest";-import { renderHook } from "@testing-library/react";+import { describe, it, expect, vi, beforeEach } from "vitest";+import { renderHook, act } from "@testing-library/react";// Mock @multica/core/issues/mutations to mimic TanStack Query v5's contract:// useMutation returns a fresh result wrapper on every render, but the@@ -14,6 +14,10 @@ const stableHandles = vi.hoisted(() => ({toggleMutate: vi.fn(),}));+// WS event registry — captured handlers per event name so tests can simulate+// server pushes by invoking them directly.+const wsHandlers = vi.hoisted(() => new Map<string, (payload: unknown) => void>());+vi.mock("@multica/core/issues/mutations", () => ({useCreateComment: () => ({mutateAsync: stableHandles.createMutateAsync,@@ -38,34 +42,73 @@ vi.mock("@multica/core/issues/mutations", () => ({}));vi.mock("@multica/core/issues/queries", () => ({- issueTimelineOptions: (id: string) => ({- queryKey: ["issues", id, "timeline"],- queryFn: () => [],+ issueTimelineInfiniteOptions: (id: string, around?: string | null) => ({+ queryKey: around+ ? ["issues", "timeline", id, "around", around]+ : ["issues", "timeline", id],+ queryFn: () => Promise.resolve(emptyPage()),+ initialPageParam: { mode: "latest" as const },+ getNextPageParam: () => undefined,+ getPreviousPageParam: () => undefined,}),issueKeys: {- timeline: (id: string) => ["issues", id, "timeline"],+ timeline: (id: string, around?: string | null) =>+ around+ ? ["issues", "timeline", id, "around", around]+ : ["issues", "timeline", id],},}));+// Hoisted state controllable from tests — represents what useInfiniteQuery+// would return for the current render.+const queryState = vi.hoisted(() => ({+ // by default: at-latest with one page that has no newer entries.+ data: undefined as unknown,+ isLoading: false,+}));++function emptyPage() {+ return {+ entries: [],+ next_cursor: null,+ prev_cursor: null,+ has_more_before: false,+ has_more_after: false,+ };+}+vi.mock("@tanstack/react-query", async () => {const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query",);return {...actual,- useQuery: () => ({ data: [], isLoading: false }),+ useInfiniteQuery: () => ({+ data: queryState.data,+ isLoading: queryState.isLoading,+ fetchNextPage: vi.fn(),+ fetchPreviousPage: vi.fn(),+ hasNextPage: false,+ hasPreviousPage: false,+ isFetchingNextPage: false,+ isFetchingPreviousPage: false,+ }),useQueryClient: () => ({invalidateQueries: vi.fn(),setQueryData: vi.fn(),- cancelQueries: vi.fn(),+ setQueriesData: vi.fn(),getQueryData: vi.fn(),+ getQueriesData: vi.fn(() => []),+ cancelQueries: vi.fn(),}),useMutationState: () => [],};});vi.mock("@multica/core/realtime", () => ({- useWSEvent: vi.fn(),+ useWSEvent: (event: string, handler: (payload: unknown) => void) => {+ wsHandlers.set(event, handler);+ },useWSReconnect: vi.fn(),}));@@ -75,7 +118,16 @@ vi.mock("sonner", () => ({import { useIssueTimeline } from "./use-issue-timeline";-describe("useIssueTimeline callback stability", () => {+describe("useIssueTimeline", () => {+ beforeEach(() => {+ wsHandlers.clear();+ queryState.data = {+ pages: [{ ...emptyPage(), has_more_after: false }],+ pageParams: [{ mode: "latest" }],+ };+ queryState.isLoading = false;+ });+// CommentCard is wrapped in React.memo (perf fix for long timelines, see// multica#1968). The memo only pays off if the callbacks passed down keep// the same identity across unrelated parent re-renders. TanStack Query v5@@ -100,10 +152,167 @@ describe("useIssueTimeline callback stability", () => {expect(result.current.editComment).toBe(first.editComment);expect(result.current.deleteComment).toBe(first.deleteComment);expect(result.current.toggleReaction).toBe(first.toggleReaction);- // submitComment intentionally also depends on `submitting` — it's only- // wired into <CommentInput>, not CommentCard, so its identity isn't a- // memo-stability concern. Still, with no submission in flight it should- // be stable too.expect(result.current.submitComment).toBe(first.submitComment);});++ it("flattens DESC pages into ASC timeline order", () => {+ queryState.data = {+ pages: [+ // Latest page: DESC.+ {+ ...emptyPage(),+ entries: [+ { type: "comment", id: "c3", actor_type: "member", actor_id: "u", created_at: "2026-05-06T03:00:00Z" },+ { type: "comment", id: "c2", actor_type: "member", actor_id: "u", created_at: "2026-05-06T02:00:00Z" },+ ],+ has_more_after: false,+ },+ // Older page: also DESC.+ {+ ...emptyPage(),+ entries: [+ { type: "comment", id: "c1", actor_type: "member", actor_id: "u", created_at: "2026-05-06T01:00:00Z" },+ ],+ },+ ],+ pageParams: [{ mode: "latest" }, { mode: "before", cursor: "x" }],+ };+ const { result } = renderHook(() => useIssueTimeline("issue-1", "user-1"));+ const ids = result.current.timeline.map((e) => e.id);+ // ASC: oldest at top, newest at bottom.+ expect(ids).toEqual(["c1", "c2", "c3"]);+ });++ it("reports isAtLatest=true when first page has no newer entries", () => {+ queryState.data = {+ pages: [{ ...emptyPage(), has_more_after: false }],+ pageParams: [{ mode: "latest" }],+ };+ const { result } = renderHook(() => useIssueTimeline("issue-1", "user-1"));+ expect(result.current.isAtLatest).toBe(true);+ expect(result.current.newEntriesBelowCount).toBe(0);+ });++ it("bumps newEntriesBelowCount when comment:created arrives while not at latest", () => {+ // Around-mode page: the user is reading older history, so has_more_after=true.+ queryState.data = {+ pages: [{ ...emptyPage(), has_more_after: true }],+ pageParams: [{ mode: "around", id: "anchor" }],+ };+ const { result } = renderHook(() =>+ useIssueTimeline("issue-1", "user-1", { around: "anchor" }),+ );+ expect(result.current.isAtLatest).toBe(false);+ expect(result.current.newEntriesBelowCount).toBe(0);++ const handler = wsHandlers.get("comment:created");+ expect(handler).toBeDefined();+ act(() => {+ handler!({+ comment: {+ id: "new-c",+ issue_id: "issue-1",+ author_type: "member",+ author_id: "u",+ content: "hi",+ parent_id: null,+ created_at: "2026-05-06T05:00:00Z",+ updated_at: "2026-05-06T05:00:00Z",+ type: "comment",+ reactions: [],+ attachments: [],+ },+ });+ });+ expect(result.current.newEntriesBelowCount).toBe(1);+ });++ it("does NOT bump newEntriesBelowCount when at-latest (entry should land in cache instead)", () => {+ queryState.data = {+ pages: [{ ...emptyPage(), has_more_after: false }],+ pageParams: [{ mode: "latest" }],+ };+ const { result } = renderHook(() => useIssueTimeline("issue-1", "user-1"));+ const handler = wsHandlers.get("comment:created");+ act(() => {+ handler!({+ comment: {+ id: "new-c",+ issue_id: "issue-1",+ author_type: "member",+ author_id: "u",+ content: "hi",+ parent_id: null,+ created_at: "2026-05-06T05:00:00Z",+ updated_at: "2026-05-06T05:00:00Z",+ type: "comment",+ reactions: [],+ attachments: [],+ },+ });+ });+ expect(result.current.newEntriesBelowCount).toBe(0);+ });++ it("ignores WS events for other issues", () => {+ queryState.data = {+ pages: [{ ...emptyPage(), has_more_after: true }],+ pageParams: [{ mode: "around", id: "anchor" }],+ };+ const { result } = renderHook(() =>+ useIssueTimeline("issue-1", "user-1", { around: "anchor" }),+ );+ const handler = wsHandlers.get("comment:created");+ act(() => {+ handler!({+ comment: {+ id: "x",+ issue_id: "different-issue",+ author_type: "member",+ author_id: "u",+ content: "",+ parent_id: null,+ created_at: "",+ updated_at: "",+ type: "comment",+ reactions: [],+ attachments: [],+ },+ });+ });+ expect(result.current.newEntriesBelowCount).toBe(0);+ });++ it("jumpToLatest clears newEntriesBelowCount", () => {+ queryState.data = {+ pages: [{ ...emptyPage(), has_more_after: true }],+ pageParams: [{ mode: "around", id: "anchor" }],+ };+ const { result } = renderHook(() =>+ useIssueTimeline("issue-1", "user-1", { around: "anchor" }),+ );+ const handler = wsHandlers.get("comment:created");+ act(() => {+ handler!({+ comment: {+ id: "n",+ issue_id: "issue-1",+ author_type: "member",+ author_id: "u",+ content: "",+ parent_id: null,+ created_at: "",+ updated_at: "",+ type: "comment",+ reactions: [],+ attachments: [],+ },+ });+ });+ expect(result.current.newEntriesBelowCount).toBe(1);+ act(() => {+ result.current.jumpToLatest();+ });+ expect(result.current.newEntriesBelowCount).toBe(0);+ });});diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.tsindex ae374f2366..123203e10f 100644--- a/packages/views/issues/hooks/use-issue-timeline.ts+++ b/packages/views/issues/hooks/use-issue-timeline.ts@@ -1,8 +1,16 @@"use client";import { useEffect, useRef, useState, useCallback, useMemo } from "react";-import { useQuery, useQueryClient, useMutationState } from "@tanstack/react-query";-import type { Comment, TimelineEntry, Reaction } from "@multica/core/types";+import {+ useInfiniteQuery,+ useQueryClient,+ useMutationState,+} from "@tanstack/react-query";+import type {+ Comment,+ TimelineEntry,+ Reaction,+} from "@multica/core/types";import type {CommentCreatedPayload,CommentUpdatedPayload,@@ -11,7 +19,16 @@ import type {ReactionAddedPayload,ReactionRemovedPayload,} from "@multica/core/types";-import { issueTimelineOptions, issueKeys } from "@multica/core/issues/queries";+import {+ issueTimelineInfiniteOptions,+ issueKeys,+} from "@multica/core/issues/queries";+import {+ mapAllEntries,+ filterAllEntries,+ prependToLatestPage,+ type TimelineCacheData,+} from "@multica/core/issues/timeline-cache";import {useCreateComment,useUpdateComment,@@ -23,6 +40,8 @@ import { useWSEvent, useWSReconnect } from "@multica/core/realtime";import { toast } from "sonner";import { useT } from "../../i18n";+type TLData = TimelineCacheData;+function commentToTimelineEntry(c: Comment): TimelineEntry {return {type: "comment",@@ -39,29 +58,77 @@ function commentToTimelineEntry(c: Comment): TimelineEntry {};}-export function useIssueTimeline(issueId: string, userId?: string) {+export interface UseIssueTimelineOptions {+ /** Anchor the initial fetch on this entry id (Inbox jump path). When set,+ * the first page is centered on the target instead of the latest 50. */+ around?: string | null;+}++export function useIssueTimeline(+ issueId: string,+ userId?: string,+ options: UseIssueTimelineOptions = {},+) {const { t } = useT("issues");const qc = useQueryClient();- const { data: timeline = [], isLoading: loading } = useQuery(- issueTimelineOptions(issueId),- );++ // Internal anchor state. Starts as the caller's around prop; jumpToLatest+ // clears it. A new around prop (e.g. user clicks a different inbox item)+ // resets it via the effect below.+ const [around, setAround] = useState<string | null>(options.around ?? null);+ useEffect(() => {+ if (options.around) setAround(options.around);+ }, [options.around]);++ const query = useInfiniteQuery(issueTimelineInfiniteOptions(issueId, around));+ const {+ data,+ isLoading: loading,+ fetchNextPage,+ fetchPreviousPage,+ hasNextPage,+ hasPreviousPage,+ isFetchingNextPage,+ isFetchingPreviousPage,+ } = query;++ // isAtLatest is the cache-invariant we use to decide where WS-delivered+ // entries belong. It's true when the FIRST loaded page reports no newer+ // entries on the server — i.e. the user is looking at the live tail.+ const isAtLatest = data?.pages[0]?.has_more_after === false;+const [submitting, setSubmitting] = useState(false);+ const [newEntriesBelowCount, setNewEntriesBelowCount] = useState(0);++ // Flatten pages → ASC array for the legacy UI consumer. pages are DESC+ // newest-first; the consumer (issue-detail.tsx) renders chronologically+ // (oldest at top). Concat → DESC; reverse once at the end → ASC.+ const timeline = useMemo<TimelineEntry[]>(() => {+ if (!data) return [];+ const flat: TimelineEntry[] = [];+ for (const page of data.pages) {+ for (const entry of page.entries) flat.push(entry);+ }+ return flat.reverse();+ }, [data]);- // TanStack Query v5 returns a fresh result wrapper from useMutation on- // every render, but the mutate / mutateAsync functions inside are stable- // across renders. Pull just the stable handles so the useCallback- // identities below do not flip on every parent re-render — listing the- // whole mutation object would defeat React.memo on CommentCard.+ // Stable mutation handles. TanStack v5 returns a fresh result wrapper from+ // useMutation per render, but the inner mutateAsync / mutate functions are+ // stable. Pull just those so the useCallback identities downstream don't+ // flip on every parent re-render — listing the whole mutation object would+ // defeat React.memo on CommentCard.const { mutateAsync: createComment } = useCreateComment(issueId);const { mutateAsync: updateComment } = useUpdateComment(issueId);const { mutateAsync: deleteCommentAsync } = useDeleteComment(issueId);const { mutate: toggleCommentReaction } = useToggleCommentReaction(issueId);- // Reconnect recovery+ // Reconnect recovery: drop the cache so the next render refetches the+ // latest page from scratch. We don't try to reconcile diffs over a+ // possibly-long disconnect — easier to start fresh.useWSReconnect(useCallback(() => {- qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId) });- }, [qc, issueId]),+ qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId, around) });+ }, [qc, issueId, around]),);// --- WS event handlers ---@@ -72,18 +139,17 @@ export function useIssueTimeline(issueId: string, userId?: string) {(payload: unknown) => {const { comment } = payload as CommentCreatedPayload;if (comment.issue_id !== issueId) return;- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),- (old) => {- if (!old) return old;- if (old.some((e) => e.id === comment.id)) return old;- return [...old, commentToTimelineEntry(comment)].sort(- (a, b) => a.created_at.localeCompare(b.created_at),- );- },- );+ if (isAtLatest) {+ qc.setQueryData<TLData>(issueKeys.timeline(issueId, around), (old: TLData | undefined) =>+ prependToLatestPage(old, commentToTimelineEntry(comment)),+ );+ } else {+ // Reading older history — don't yank scroll position. Surface a+ // counter so the UI can offer "jump to latest (N new)".+ setNewEntriesBelowCount((c) => c + 1);+ }},- [qc, issueId],+ [qc, issueId, around, isAtLatest],),);@@ -92,17 +158,14 @@ export function useIssueTimeline(issueId: string, userId?: string) {useCallback((payload: unknown) => {const { comment } = payload as CommentUpdatedPayload;- if (comment.issue_id === issueId) {- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),- (old) =>- old?.map((e) =>- e.id === comment.id ? commentToTimelineEntry(comment) : e,- ),- );- }+ if (comment.issue_id !== issueId) return;+ qc.setQueryData<TLData>(issueKeys.timeline(issueId, around), (old: TLData | undefined) =>+ mapAllEntries(old, (e) =>+ e.id === comment.id ? commentToTimelineEntry(comment) : e,+ ),+ );},- [qc, issueId],+ [qc, issueId, around],),);@@ -111,32 +174,32 @@ export function useIssueTimeline(issueId: string, userId?: string) {useCallback((payload: unknown) => {const { comment_id, issue_id } = payload as CommentDeletedPayload;- if (issue_id === issueId) {- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),- (old) => {- if (!old) return old;- const idsToRemove = new Set<string>([comment_id]);- let added = true;- while (added) {- added = false;- for (const e of old) {- if (- e.parent_id &&- idsToRemove.has(e.parent_id) &&- !idsToRemove.has(e.id)- ) {- idsToRemove.add(e.id);- added = true;- }+ if (issue_id !== issueId) return;+ // Cascade through replies. Walk pages collectively; a reply may live+ // on a different page than its parent.+ qc.setQueryData<TLData>(issueKeys.timeline(issueId, around), (old: TLData | undefined) => {+ if (!old) return old;+ const idsToRemove = new Set<string>([comment_id]);+ let changed = true;+ while (changed) {+ changed = false;+ for (const page of old.pages) {+ for (const e of page.entries) {+ if (+ e.parent_id &&+ idsToRemove.has(e.parent_id) &&+ !idsToRemove.has(e.id)+ ) {+ idsToRemove.add(e.id);+ changed = true;}}- return old.filter((e) => !idsToRemove.has(e.id));- },- );- }+ }+ }+ return filterAllEntries(old, (e) => idsToRemove.has(e.id));+ });},- [qc, issueId],+ [qc, issueId, around],),);@@ -148,18 +211,15 @@ export function useIssueTimeline(issueId: string, userId?: string) {if (p.issue_id !== issueId) return;const entry = p.entry;if (!entry || !entry.id) return;- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),- (old) => {- if (!old) return old;- if (old.some((e) => e.id === entry.id)) return old;- return [...old, entry].sort(- (a, b) => a.created_at.localeCompare(b.created_at),- );- },- );+ if (isAtLatest) {+ qc.setQueryData<TLData>(issueKeys.timeline(issueId, around), (old: TLData | undefined) =>+ prependToLatestPage(old, entry),+ );+ } else {+ setNewEntriesBelowCount((c) => c + 1);+ }},- [qc, issueId],+ [qc, issueId, around, isAtLatest],),);@@ -169,18 +229,16 @@ export function useIssueTimeline(issueId: string, userId?: string) {(payload: unknown) => {const { reaction, issue_id } = payload as ReactionAddedPayload;if (issue_id !== issueId) return;- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),- (old) =>- old?.map((e) => {- if (e.id !== reaction.comment_id) return e;- const existing = e.reactions ?? [];- if (existing.some((r) => r.id === reaction.id)) return e;- return { ...e, reactions: [...existing, reaction] };- }),+ qc.setQueryData<TLData>(issueKeys.timeline(issueId, around), (old: TLData | undefined) =>+ mapAllEntries(old, (e) => {+ if (e.id !== reaction.comment_id) return e;+ const existing = e.reactions ?? [];+ if (existing.some((r) => r.id === reaction.id)) return e;+ return { ...e, reactions: [...existing, reaction] };+ }),);},- [qc, issueId],+ [qc, issueId, around],),);@@ -190,29 +248,45 @@ export function useIssueTimeline(issueId: string, userId?: string) {(payload: unknown) => {const p = payload as ReactionRemovedPayload;if (p.issue_id !== issueId) return;- qc.setQueryData<TimelineEntry[]>(- issueKeys.timeline(issueId),- (old) =>- old?.map((e) => {- if (e.id !== p.comment_id) return e;- return {- ...e,- reactions: (e.reactions ?? []).filter(- (r) =>- !(- r.emoji === p.emoji &&- r.actor_type === p.actor_type &&- r.actor_id === p.actor_id- ),- ),- };- }),+ qc.setQueryData<TLData>(issueKeys.timeline(issueId, around), (old: TLData | undefined) =>+ mapAllEntries(old, (e) => {+ if (e.id !== p.comment_id) return e;+ return {+ ...e,+ reactions: (e.reactions ?? []).filter(+ (r) =>+ !(+ r.emoji === p.emoji &&+ r.actor_type === p.actor_type &&+ r.actor_id === p.actor_id+ ),+ ),+ };+ }),);},- [qc, issueId],+ [qc, issueId, around],),);+ // --- Page navigation ---++ const fetchOlder = useCallback(() => {+ if (hasNextPage && !isFetchingNextPage) fetchNextPage();+ }, [hasNextPage, isFetchingNextPage, fetchNextPage]);++ const fetchNewer = useCallback(() => {+ if (hasPreviousPage && !isFetchingPreviousPage) fetchPreviousPage();+ }, [hasPreviousPage, isFetchingPreviousPage, fetchPreviousPage]);++ const jumpToLatest = useCallback(() => {+ // Drop any anchor + prefetched windows. The latest cache (around=null)+ // may be cold; an invalidate forces a fresh fetch on next render.+ setAround(null);+ setNewEntriesBelowCount(0);+ qc.invalidateQueries({ queryKey: issueKeys.timeline(issueId, null) });+ }, [qc, issueId]);+// --- Mutation functions ---const submitComment = useCallback(@@ -269,9 +343,9 @@ export function useIssueTimeline(issueId: string, userId?: string) {[deleteCommentAsync, t],);- // --- Optimistic UI derivation for comment reactions ---- // Instead of writing temp data into the cache (which races with WS events),- // derive optimistic state at render time from pending mutation variables.+ // --- Optimistic UI for comment reactions ---+ // Derive at render time from pending mutation variables instead of writing+ // temp data into the cache (which would race with WS events).const pendingReactionVars = useMutationState({filters: {@@ -295,10 +369,8 @@ export function useIssueTimeline(issueId: string, userId?: string) {for (const vars of pendingForEntry) {if (!vars) continue;if (vars.existing) {- // Pending removalreactions = reactions.filter((r) => r.id !== vars.existing!.id);} else {- // Pending add — skip if server already has it (WS arrived first)const alreadyExists = reactions.some((r) =>r.emoji === vars.emoji &&@@ -324,10 +396,10 @@ export function useIssueTimeline(issueId: string, userId?: string) {});}, [timeline, pendingReactionVars, userId]);- // Read timeline through a ref so toggleReaction's identity does not change- // on every WS event. Without this, every memoized CommentCard down-tree- // would re-render on each timeline mutation, defeating the React.memo cost- // savings on long timelines (see Inbox-freeze fix).+ // toggleReaction reads from a ref so its identity does not change with+ // every WS event. Without this every memoized CommentCard down-tree would+ // re-render on each timeline mutation, defeating the React.memo cost+ // savings on long timelines (#1968).const timelineRef = useRef(timeline);useEffect(() => {timelineRef.current = timeline;@@ -336,7 +408,6 @@ export function useIssueTimeline(issueId: string, userId?: string) {const toggleReaction = useCallback(async (commentId: string, emoji: string) => {if (!userId) return;- // Read from server timeline (not optimistic) to find the real reactionconst entry = timelineRef.current.find((e) => e.id === commentId);const existing: Reaction | undefined = (entry?.reactions ?? []).find((r) =>@@ -349,6 +420,19 @@ export function useIssueTimeline(issueId: string, userId?: string) {[userId, toggleCommentReaction],);+ // Around-mode anchor index (target_index from server, applied within the+ // first page). Translated to a flat-array index: the array is reversed+ // (DESC pages → ASC flat), so the offset within page[0] becomes+ // (totalEntries - 1) - target_index.+ const targetFlatIndex = useMemo(() => {+ if (!data || data.pages.length === 0) return null;+ const first = data.pages[0];+ if (!first || first.target_index == null) return null;+ let total = 0;+ for (const p of data.pages) total += p.entries.length;+ return total - 1 - first.target_index;+ }, [data]);+return {timeline: optimisticTimeline,loading,@@ -358,5 +442,16 @@ export function useIssueTimeline(issueId: string, userId?: string) {editComment,deleteComment,toggleReaction,+ // Pagination controls (new)+ hasMoreOlder: hasNextPage,+ hasMoreNewer: hasPreviousPage,+ isFetchingOlder: isFetchingNextPage,+ isFetchingNewer: isFetchingPreviousPage,+ fetchOlder,+ fetchNewer,+ jumpToLatest,+ isAtLatest: isAtLatest === true,+ newEntriesBelowCount,+ targetFlatIndex,};}diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex ba60cbb306..d7260635fb 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -129,6 +129,13 @@"link_copied": "Link copied","link_copy_failed": "Failed to copy link"},+ "timeline": {+ "show_older": "Show older",+ "show_newer": "Show newer",+ "loading": "Loading...",+ "jump_to_latest": "Jump to latest",+ "jump_to_latest_with_count": "Jump to latest · {{count}} new"+ },"activity": {"created": "created this issue","self_assigned": "self-assigned this issue",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 1b1a720933..eba4181683 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -128,6 +128,13 @@"link_copied": "已复制链接","link_copy_failed": "复制链接失败"},+ "timeline": {+ "show_older": "显示更早",+ "show_newer": "显示更晚",+ "loading": "加载中…",+ "jump_to_latest": "跳到最新",+ "jump_to_latest_with_count": "跳到最新 · {{count}} 条新动态"+ },"activity": {"created": "创建了这个 issue","self_assigned": "把这个 issue 分配给了自己",diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 7ba8ae517f..e5fcd77c16 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -255,7 +255,7 @@ func init() {// issue comment listissueCommentListCmd.Flags().String("output", "table", "Output format: table or json")- issueCommentListCmd.Flags().Int("limit", 0, "Maximum number of comments to return (0 = all)")+ issueCommentListCmd.Flags().Int("limit", 50, "Maximum number of comments to return (0 = server default of 50, max ~100 depending on server)")issueCommentListCmd.Flags().Int("offset", 0, "Number of comments to skip")issueCommentListCmd.Flags().String("since", "", "Only return comments created after this timestamp (RFC3339)")diff --git a/server/cmd/server/activity_listeners_test.go b/server/cmd/server/activity_listeners_test.goindex 197b90b51a..a0523546fb 100644--- a/server/cmd/server/activity_listeners_test.go+++ b/server/cmd/server/activity_listeners_test.go@@ -12,16 +12,18 @@ import ("github.com/multica-ai/multica/server/pkg/protocol")-// listActivitiesForIssue is a test helper that fetches all activity_log records for an issue.+// listActivitiesForIssue is a test helper that fetches up to 100 activity_log+// records for an issue using the keyset query that backs the cursor-paginated+// timeline endpoint. The unbounded ListActivities was removed when the+// timeline switched to cursor pagination (#1968 root fix).func listActivitiesForIssue(t *testing.T, queries *db.Queries, issueID string) []db.ActivityLog {t.Helper()- activities, err := queries.ListActivities(context.Background(), db.ListActivitiesParams{+ activities, err := queries.ListActivitiesLatest(context.Background(), db.ListActivitiesLatestParams{IssueID: util.MustParseUUID(issueID),Limit: 100,- Offset: 0,})if err != nil {- t.Fatalf("ListActivities: %v", err)+ t.Fatalf("ListActivitiesLatest: %v", err)}return activities}diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 18723aa505..3d732f997c 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -27,6 +27,7 @@ func BuildPrompt(task Task) string {b.WriteString("You are running as a local coding agent for a Multica workspace.\n\n")fmt.Fprintf(&b, "Your assigned issue ID is: %s\n\n", task.IssueID)fmt.Fprintf(&b, "Start by running `multica issue get %s --output json` to understand your task, then complete it.\n", task.IssueID)+ fmt.Fprintf(&b, "If you need comment history, `multica issue comment list %s` returns the latest 50 by default — pass --limit or --since to scope older windows. Long issues can have thousands of comments; do not fetch everything blindly.\n", task.IssueID)return b.String()}@@ -120,6 +121,7 @@ func buildCommentPrompt(task Task) string {}}fmt.Fprintf(&b, "Start by running `multica issue get %s --output json` to understand your task, then decide how to proceed.\n\n", task.IssueID)+ fmt.Fprintf(&b, "If you need comment history, `multica issue comment list %s` returns the latest 50 by default — pass --limit or --since to scope older windows. Long issues can have thousands of comments; do not fetch everything blindly.\n\n", task.IssueID)b.WriteString(execenv.BuildCommentReplyInstructions(task.IssueID, task.TriggerCommentID))return b.String()}diff --git a/server/internal/handler/activity.go b/server/internal/handler/activity.goindex 79e4c337ff..a6f16b6005 100644--- a/server/internal/handler/activity.go+++ b/server/internal/handler/activity.go@@ -1,11 +1,16 @@package handlerimport (+ "encoding/base64""encoding/json"+ "errors""net/http""sort"+ "strconv"+ "time""github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -33,8 +38,76 @@ type TimelineEntry struct {Attachments []AttachmentResponse `json:"attachments,omitempty"`}-// ListTimeline returns a merged, chronologically-sorted timeline of activities-// and comments for a given issue.+// TimelineResponse wraps the cursor-paginated timeline. Entries are sorted+// newest-first (created_at DESC, id DESC). NextCursor / PrevCursor are opaque+// strings; clients pass them back as ?before= / ?after= without inspection.+// HasMoreBefore indicates more entries older than the last in the page;+// HasMoreAfter indicates more entries newer than the first in the page.+type TimelineResponse struct {+ Entries []TimelineEntry `json:"entries"`+ NextCursor *string `json:"next_cursor"`+ PrevCursor *string `json:"prev_cursor"`+ HasMoreBefore bool `json:"has_more_before"`+ HasMoreAfter bool `json:"has_more_after"`+ // TargetIndex is set only in ?around=<id> mode, locating the anchor entry+ // within Entries so the client can scroll/highlight without searching.+ TargetIndex *int `json:"target_index,omitempty"`+}++const (+ timelineDefaultLimit = 50+ timelineMaxLimit = 100+)++// timelineCursor encodes a (created_at, id) keyset position as opaque base64+// JSON. The format is intentionally hidden from clients so future schema+// evolution (e.g. switching to a sequence column) can replace the cursor+// payload without breaking API consumers.+type timelineCursor struct {+ CreatedAt time.Time `json:"t"`+ ID string `json:"i"`+}++func encodeTimelineCursor(t pgtype.Timestamptz, id pgtype.UUID) string {+ c := timelineCursor{CreatedAt: t.Time, ID: uuidToString(id)}+ b, _ := json.Marshal(c)+ return base64.RawURLEncoding.EncodeToString(b)+}++func decodeTimelineCursor(s string) (pgtype.Timestamptz, pgtype.UUID, error) {+ raw, err := base64.RawURLEncoding.DecodeString(s)+ if err != nil {+ return pgtype.Timestamptz{}, pgtype.UUID{}, err+ }+ var c timelineCursor+ if err := json.Unmarshal(raw, &c); err != nil {+ return pgtype.Timestamptz{}, pgtype.UUID{}, err+ }+ id, err := parseUUIDStrict(c.ID)+ if err != nil {+ return pgtype.Timestamptz{}, pgtype.UUID{}, err+ }+ return pgtype.Timestamptz{Time: c.CreatedAt, Valid: true}, id, nil+}++// parseUUIDStrict mirrors util.ParseUUID but returns a pgtype.UUID directly+// without panicking on bad input. Used for cursor decoding where invalid data+// is a 400, not a 500.+func parseUUIDStrict(s string) (pgtype.UUID, error) {+ var u pgtype.UUID+ if err := u.Scan(s); err != nil {+ return pgtype.UUID{}, err+ }+ if !u.Valid {+ return pgtype.UUID{}, errors.New("invalid uuid")+ }+ return u, nil+}++// ListTimeline returns a cursor-paginated, newest-first slice of the issue+// timeline (comments + activities merged). The query string accepts at most+// one of: ?before=<cursor>, ?after=<cursor>, ?around=<entry_id>. With none,+// the latest page is returned.func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {id := chi.URLParam(r, "id")issue, ok := h.loadIssueForUser(w, r, id)@@ -42,58 +115,361 @@ func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {return}- activities, err := h.Queries.ListActivities(r.Context(), db.ListActivitiesParams{- IssueID: issue.ID,- Limit: 200,- Offset: 0,+ q := r.URL.Query()+ limit := timelineDefaultLimit+ if raw := q.Get("limit"); raw != "" {+ n, err := strconv.Atoi(raw)+ if err != nil || n <= 0 {+ writeError(w, http.StatusBadRequest, "invalid limit")+ return+ }+ if n > timelineMaxLimit {+ writeError(w, http.StatusBadRequest, "limit exceeds maximum of 100")+ return+ }+ limit = n+ }++ before, after, around := q.Get("before"), q.Get("after"), q.Get("around")+ modes := 0+ for _, s := range []string{before, after, around} {+ if s != "" {+ modes+++ }+ }+ if modes > 1 {+ writeError(w, http.StatusBadRequest, "before, after, and around are mutually exclusive")+ return+ }++ switch {+ case around != "":+ h.listTimelineAround(w, r, issue, around, limit)+ case before != "":+ h.listTimelineBefore(w, r, issue, before, limit)+ case after != "":+ h.listTimelineAfter(w, r, issue, after, limit)+ default:+ h.listTimelineLatest(w, r, issue, limit)+ }+}++// listTimelineLatest fetches the most recent <limit> entries (no cursor).+// Both tables are queried for <limit> rows each; the merge picks the top+// <limit> overall. Any item the merge didn't include cannot rank higher than+// the worst kept item in either pool, so this is exact, not approximate.+func (h *Handler) listTimelineLatest(w http.ResponseWriter, r *http.Request, issue db.Issue, limit int) {+ ctx := r.Context()+ comments, err := h.Queries.ListCommentsLatest(ctx, db.ListCommentsLatestParams{+ IssueID: issue.ID, WorkspaceID: issue.WorkspaceID, Limit: int32(limit),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list comments")+ return+ }+ activities, err := h.Queries.ListActivitiesLatest(ctx, db.ListActivitiesLatestParams{+ IssueID: issue.ID, Limit: int32(limit),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list activities")+ return+ }++ entries := h.mergeTimelineDesc(r, comments, activities, limit)+ resp := TimelineResponse{Entries: entries}+ // has_more_before: the page is full → there are likely more older. If the+ // page is partial it means we hit the bottom of one or both tables.+ resp.HasMoreBefore = len(entries) >= limit && (len(comments) >= limit || len(activities) >= limit)+ if resp.HasMoreBefore && len(entries) > 0 {+ c := encodeTimelineCursor(entryTimestamp(entries[len(entries)-1]), entryID(entries[len(entries)-1]))+ resp.NextCursor = &c+ }+ if len(entries) > 0 {+ c := encodeTimelineCursor(entryTimestamp(entries[0]), entryID(entries[0]))+ resp.PrevCursor = &c+ }+ // has_more_after is always false on the latest page by definition.+ writeJSON(w, http.StatusOK, resp)+}++func (h *Handler) listTimelineBefore(w http.ResponseWriter, r *http.Request, issue db.Issue, cursor string, limit int) {+ ctx := r.Context()+ t, id, err := decodeTimelineCursor(cursor)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid cursor")+ return+ }++ comments, err := h.Queries.ListCommentsBefore(ctx, db.ListCommentsBeforeParams{+ IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,+ Column3: t, Column4: id, Limit: int32(limit),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list comments")+ return+ }+ activities, err := h.Queries.ListActivitiesBefore(ctx, db.ListActivitiesBeforeParams{+ IssueID: issue.ID, Column2: t, Column3: id, Limit: int32(limit),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list activities")+ return+ }++ entries := h.mergeTimelineDesc(r, comments, activities, limit)+ resp := TimelineResponse{+ Entries: entries,+ HasMoreAfter: true, // we're paging older from a known position, so newer exists+ }+ resp.HasMoreBefore = len(entries) >= limit && (len(comments) >= limit || len(activities) >= limit)+ if resp.HasMoreBefore && len(entries) > 0 {+ c := encodeTimelineCursor(entryTimestamp(entries[len(entries)-1]), entryID(entries[len(entries)-1]))+ resp.NextCursor = &c+ }+ if len(entries) > 0 {+ c := encodeTimelineCursor(entryTimestamp(entries[0]), entryID(entries[0]))+ resp.PrevCursor = &c+ }+ writeJSON(w, http.StatusOK, resp)+}++func (h *Handler) listTimelineAfter(w http.ResponseWriter, r *http.Request, issue db.Issue, cursor string, limit int) {+ ctx := r.Context()+ t, id, err := decodeTimelineCursor(cursor)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid cursor")+ return+ }++ comments, err := h.Queries.ListCommentsAfter(ctx, db.ListCommentsAfterParams{+ IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,+ Column3: t, Column4: id, Limit: int32(limit),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list comments")+ return+ }+ activities, err := h.Queries.ListActivitiesAfter(ctx, db.ListActivitiesAfterParams{+ IssueID: issue.ID, Column2: t, Column3: id, Limit: int32(limit),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list activities")+ return+ }++ // Both queries returned ASC (older→newer). Merge ASC, take the limit+ // closest to the cursor (i.e. the oldest of the "after" set), then+ // reverse to DESC for the response.+ entries := h.mergeTimelineAscThenReverse(r, comments, activities, limit)+ resp := TimelineResponse{Entries: entries, HasMoreBefore: true}+ resp.HasMoreAfter = len(entries) >= limit && (len(comments) >= limit || len(activities) >= limit)+ if resp.HasMoreAfter && len(entries) > 0 {+ c := encodeTimelineCursor(entryTimestamp(entries[0]), entryID(entries[0]))+ resp.PrevCursor = &c+ }+ if len(entries) > 0 {+ c := encodeTimelineCursor(entryTimestamp(entries[len(entries)-1]), entryID(entries[len(entries)-1]))+ resp.NextCursor = &c+ }+ writeJSON(w, http.StatusOK, resp)+}++// listTimelineAround anchors a window of size <limit> on a target entry,+// returning roughly half before and half after plus the target itself.+// This is the Inbox-jump / deep-link path: the target entry can be deep in+// the timeline, but the response is bounded so the browser never freezes.+func (h *Handler) listTimelineAround(w http.ResponseWriter, r *http.Request, issue db.Issue, targetID string, limit int) {+ ctx := r.Context()+ target, err := parseUUIDStrict(targetID)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid around id")+ return+ }++ // Resolve the target's (created_at, id). It can be either a comment or+ // an activity; we don't ask the client to disambiguate.+ var anchorTime pgtype.Timestamptz+ var anchorID pgtype.UUID+ if c, cErr := h.Queries.GetCommentInWorkspace(ctx, db.GetCommentInWorkspaceParams{+ ID: target, WorkspaceID: issue.WorkspaceID,+ }); cErr == nil && c.IssueID == issue.ID {+ anchorTime, anchorID = c.CreatedAt, c.ID+ } else if a, aErr := h.Queries.GetActivity(ctx, target); aErr == nil &&+ a.IssueID == issue.ID && a.WorkspaceID == issue.WorkspaceID {+ anchorTime, anchorID = a.CreatedAt, a.ID+ } else {+ // Neither comment nor activity matched (or wrong workspace/issue).+ // Don't leak existence — return 404 like other resource lookups.+ if cErr != nil && !errors.Is(cErr, pgx.ErrNoRows) {+ writeError(w, http.StatusInternalServerError, "failed to resolve target")+ return+ }+ writeError(w, http.StatusNotFound, "timeline entry not found")+ return+ }++ half := limit / 2+ if half < 1 {+ half = 1+ }+ beforeLimit := half+ afterLimit := limit - half - 1 // -1 for the anchor itself+ if afterLimit < 0 {+ afterLimit = 0+ }++ // Older half: keyset Before (anchor exclusive).+ olderComments, err := h.Queries.ListCommentsBefore(ctx, db.ListCommentsBeforeParams{+ IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,+ Column3: anchorTime, Column4: anchorID, Limit: int32(beforeLimit),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list comments")+ return+ }+ olderActivities, err := h.Queries.ListActivitiesBefore(ctx, db.ListActivitiesBeforeParams{+ IssueID: issue.ID, Column2: anchorTime, Column3: anchorID, Limit: int32(beforeLimit),})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list activities")return}+ olderEntries := h.mergeTimelineDesc(r, olderComments, olderActivities, beforeLimit)- comments, err := h.Queries.ListComments(r.Context(), db.ListCommentsParams{- IssueID: issue.ID,- WorkspaceID: issue.WorkspaceID,+ // Newer half: keyset After (anchor exclusive).+ newerComments, err := h.Queries.ListCommentsAfter(ctx, db.ListCommentsAfterParams{+ IssueID: issue.ID, WorkspaceID: issue.WorkspaceID,+ Column3: anchorTime, Column4: anchorID, Limit: int32(afterLimit),})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list comments")return}+ newerActivities, err := h.Queries.ListActivitiesAfter(ctx, db.ListActivitiesAfterParams{+ IssueID: issue.ID, Column2: anchorTime, Column3: anchorID, Limit: int32(afterLimit),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list activities")+ return+ }+ newerEntries := h.mergeTimelineAscThenReverse(r, newerComments, newerActivities, afterLimit)- timeline := make([]TimelineEntry, 0, len(activities)+len(comments))+ // Build the anchor entry inline using the existing single-entry path.+ anchorEntry, ok := h.fetchSingleEntry(r, issue, target)+ if !ok {+ writeError(w, http.StatusInternalServerError, "failed to fetch anchor")+ return+ }++ // Final stitch: newer (DESC) + anchor + older (DESC).+ entries := make([]TimelineEntry, 0, len(newerEntries)+1+len(olderEntries))+ entries = append(entries, newerEntries...)+ entries = append(entries, anchorEntry)+ entries = append(entries, olderEntries...)+ targetIdx := len(newerEntries)++ resp := TimelineResponse{+ Entries: entries,+ HasMoreBefore: len(olderComments) >= beforeLimit || len(olderActivities) >= beforeLimit,+ HasMoreAfter: len(newerComments) >= afterLimit || len(newerActivities) >= afterLimit,+ TargetIndex: &targetIdx,+ }+ if resp.HasMoreBefore {+ c := encodeTimelineCursor(entryTimestamp(entries[len(entries)-1]), entryID(entries[len(entries)-1]))+ resp.NextCursor = &c+ }+ if resp.HasMoreAfter {+ c := encodeTimelineCursor(entryTimestamp(entries[0]), entryID(entries[0]))+ resp.PrevCursor = &c+ }+ writeJSON(w, http.StatusOK, resp)+}++// fetchSingleEntry materializes a single TimelineEntry (comment or activity)+// for the around-mode anchor. Reactions/attachments come from the same batch+// helpers so the rendering is identical to the merge path.+func (h *Handler) fetchSingleEntry(r *http.Request, issue db.Issue, id pgtype.UUID) (TimelineEntry, bool) {+ ctx := r.Context()+ if c, err := h.Queries.GetCommentInWorkspace(ctx, db.GetCommentInWorkspaceParams{+ ID: id, WorkspaceID: issue.WorkspaceID,+ }); err == nil && c.IssueID == issue.ID {+ return h.commentsToEntries(r, []db.Comment{c})[0], true+ }+ if a, err := h.Queries.GetActivity(ctx, id); err == nil &&+ a.IssueID == issue.ID && a.WorkspaceID == issue.WorkspaceID {+ return activityToEntry(a), true+ }+ return TimelineEntry{}, false+}+// mergeTimelineDesc takes comments + activities sorted DESC by (created_at, id)+// and returns the top <limit> merged entries, also DESC. Items the merge does+// not include cannot rank higher than the worst kept item in either pool, so+// the result is exact.+func (h *Handler) mergeTimelineDesc(r *http.Request, comments []db.Comment, activities []db.ActivityLog, limit int) []TimelineEntry {+ out := make([]TimelineEntry, 0, len(comments)+len(activities))+ out = append(out, h.commentsToEntries(r, comments)...)for _, a := range activities {- action := a.Action- actorType := ""- if a.ActorType.Valid {- actorType = a.ActorType.String+ out = append(out, activityToEntry(a))+ }+ sort.Slice(out, func(i, j int) bool {+ if out[i].CreatedAt != out[j].CreatedAt {+ return out[i].CreatedAt > out[j].CreatedAt}- timeline = append(timeline, TimelineEntry{- Type: "activity",- ID: uuidToString(a.ID),- ActorType: actorType,- ActorID: uuidToString(a.ActorID),- Action: &action,- Details: a.Details,- CreatedAt: timestampToString(a.CreatedAt),- })+ return out[i].ID > out[j].ID+ })+ if len(out) > limit {+ out = out[:limit]}+ return out+}- // Fetch reactions and attachments for all comments in one batch.- commentIDs := make([]pgtype.UUID, len(comments))+// mergeTimelineAscThenReverse takes comments + activities sorted ASC by+// (created_at, id) — the natural shape of an "after" keyset query — picks+// the <limit> closest to the cursor (i.e. earliest of the after-set), and+// returns them DESC for response consistency.+func (h *Handler) mergeTimelineAscThenReverse(r *http.Request, comments []db.Comment, activities []db.ActivityLog, limit int) []TimelineEntry {+ out := make([]TimelineEntry, 0, len(comments)+len(activities))+ out = append(out, h.commentsToEntries(r, comments)...)+ for _, a := range activities {+ out = append(out, activityToEntry(a))+ }+ sort.Slice(out, func(i, j int) bool {+ if out[i].CreatedAt != out[j].CreatedAt {+ return out[i].CreatedAt < out[j].CreatedAt+ }+ return out[i].ID < out[j].ID+ })+ if len(out) > limit {+ out = out[:limit]+ }+ // Reverse to DESC.+ for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {+ out[i], out[j] = out[j], out[i]+ }+ return out+}++// commentsToEntries fetches reactions + attachments for the given comments in+// one batch each and returns enriched TimelineEntry slices preserving order.+func (h *Handler) commentsToEntries(r *http.Request, comments []db.Comment) []TimelineEntry {+ if len(comments) == 0 {+ return nil+ }+ ids := make([]pgtype.UUID, len(comments))for i, c := range comments {- commentIDs[i] = c.ID+ ids[i] = c.ID}- grouped := h.groupReactions(r, commentIDs)- groupedAtt := h.groupAttachments(r, commentIDs)+ reactions := h.groupReactions(r, ids)+ attachments := h.groupAttachments(r, ids)- for _, c := range comments {+ out := make([]TimelineEntry, len(comments))+ for i, c := range comments {content := c.ContentcommentType := c.TypeupdatedAt := timestampToString(c.UpdatedAt)cid := uuidToString(c.ID)- timeline = append(timeline, TimelineEntry{+ out[i] = TimelineEntry{Type: "comment",ID: cid,ActorType: c.AuthorType,@@ -103,17 +479,41 @@ func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {ParentID: uuidToPtr(c.ParentID),CreatedAt: timestampToString(c.CreatedAt),UpdatedAt: &updatedAt,- Reactions: grouped[cid],- Attachments: groupedAtt[cid],- })+ Reactions: reactions[cid],+ Attachments: attachments[cid],+ }}+ return out+}- // Sort chronologically (ascending by created_at)- sort.Slice(timeline, func(i, j int) bool {- return timeline[i].CreatedAt < timeline[j].CreatedAt- })+func activityToEntry(a db.ActivityLog) TimelineEntry {+ action := a.Action+ actorType := ""+ if a.ActorType.Valid {+ actorType = a.ActorType.String+ }+ return TimelineEntry{+ Type: "activity",+ ID: uuidToString(a.ID),+ ActorType: actorType,+ ActorID: uuidToString(a.ActorID),+ Action: &action,+ Details: a.Details,+ CreatedAt: timestampToString(a.CreatedAt),+ }+}++// entryTimestamp / entryID extract the cursor components for an emitted+// TimelineEntry. CreatedAt is already an RFC3339 string at this point;+// re-parse it for cursor encoding.+func entryTimestamp(e TimelineEntry) pgtype.Timestamptz {+ t, _ := time.Parse(time.RFC3339Nano, e.CreatedAt)+ return pgtype.Timestamptz{Time: t, Valid: true}+}- writeJSON(w, http.StatusOK, timeline)+func entryID(e TimelineEntry) pgtype.UUID {+ id, _ := parseUUIDStrict(e.ID)+ return id}// AssigneeFrequencyEntry represents how often a user assigns to a specific target.diff --git a/server/internal/handler/activity_test.go b/server/internal/handler/activity_test.goindex 0bf1f1a7e0..e4d9de9556 100644--- a/server/internal/handler/activity_test.go+++ b/server/internal/handler/activity_test.go@@ -3,21 +3,40 @@ package handlerimport ("context""encoding/json"+ "fmt""net/http""net/http/httptest""strings""testing"-- db "github.com/multica-ai/multica/server/pkg/db/generated"+ "time")-func TestListTimeline_MergedAndSorted(t *testing.T) {- ctx := context.Background()+// fetchTimeline issues a GET /timeline request with the given query string and+// returns the decoded TimelineResponse + HTTP status.+func fetchTimeline(t *testing.T, issueID, query string) (TimelineResponse, int) {+ t.Helper()+ url := "/api/issues/" + issueID + "/timeline"+ if query != "" {+ url += "?" + query+ }+ w := httptest.NewRecorder()+ req := newRequest("GET", url, nil)+ req = withURLParam(req, "id", issueID)+ testHandler.ListTimeline(w, req)+ var resp TimelineResponse+ if w.Code == http.StatusOK {+ json.NewDecoder(w.Body).Decode(&resp)+ }+ return resp, w.Code+}- // Create an issue+// createIssueForTimeline returns a freshly-created issue id and registers a+// cleanup so its timeline rows are deleted after the test.+func createIssueForTimeline(t *testing.T, title string) string {+ t.Helper()w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "Timeline test issue",+ "title": title,"status": "todo",})testHandler.CreateIssue(w, req)@@ -26,367 +45,239 @@ func TestListTimeline_MergedAndSorted(t *testing.T) {}var issue IssueResponsejson.NewDecoder(w.Body).Decode(&issue)- issueID := issue.ID-t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, issueID)- testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issueID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, issue.ID)+ testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issue.ID)+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issue.ID)})+ return issue.ID+}- // Create an activity record directly in DB- _, err := testHandler.Queries.CreateActivity(ctx, db.CreateActivityParams{- WorkspaceID: parseUUID(testWorkspaceID),- IssueID: parseUUID(issueID),- ActorType: strToText("member"),- ActorID: parseUUID(testUserID),- Action: "created",- Details: []byte("{}"),- })- if err != nil {- t.Fatalf("CreateActivity: %v", err)+// seedTimelineEntries inserts <commentN> comments + <activityN> activities for+// the given issue with descending timestamps (oldest first → newest last) so+// callers can reason about ordering. Returns the inserted comment + activity+// IDs in the order they were inserted (chronologically ascending).+func seedTimelineEntries(t *testing.T, issueID string, commentN, activityN int) (commentIDs, activityIDs []string) {+ t.Helper()+ ctx := context.Background()+ base := time.Now().UTC().Add(-time.Duration(commentN+activityN) * time.Minute)++ for i := 0; i < commentN; i++ {+ var id string+ ts := base.Add(time.Duration(i) * time.Minute)+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at, updated_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5, $5)+ RETURNING id+ `, issueID, testWorkspaceID, testUserID, fmt.Sprintf("comment %d", i), ts).Scan(&id); err != nil {+ t.Fatalf("seed comment %d: %v", i, err)+ }+ commentIDs = append(commentIDs, id)+ }+ for i := 0; i < activityN; i++ {+ var id string+ ts := base.Add(time.Duration(commentN+i) * time.Minute)+ if err := testPool.QueryRow(ctx, `+ INSERT INTO activity_log (workspace_id, issue_id, actor_type, actor_id, action, details, created_at)+ VALUES ($1, $2, 'member', $3, 'status_changed', '{"from":"todo","to":"in_progress"}'::jsonb, $4)+ RETURNING id+ `, testWorkspaceID, issueID, testUserID, ts).Scan(&id); err != nil {+ t.Fatalf("seed activity %d: %v", i, err)+ }+ activityIDs = append(activityIDs, id)}+ return+}- // Create a comment- w = httptest.NewRecorder()- req = newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{- "content": "Timeline test comment",- })- req = withURLParam(req, "id", issueID)- testHandler.CreateComment(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())- }+func TestListTimeline_DefaultLatestPage(t *testing.T) {+ issueID := createIssueForTimeline(t, "Latest page test")+ seedTimelineEntries(t, issueID, 60, 60) // 120 total; default limit is 50- // Fetch timeline- w = httptest.NewRecorder()- req = newRequest("GET", "/api/issues/"+issueID+"/timeline", nil)- req = withURLParam(req, "id", issueID)- testHandler.ListTimeline(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ListTimeline: expected 200, got %d: %s", w.Code, w.Body.String())+ resp, code := fetchTimeline(t, issueID, "")+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d", code)}-- var timeline []TimelineEntry- json.NewDecoder(w.Body).Decode(&timeline)- if len(timeline) != 2 {- t.Fatalf("expected 2 timeline entries, got %d", len(timeline))+ if len(resp.Entries) != 50 {+ t.Fatalf("expected 50 entries on default page, got %d", len(resp.Entries))}-- // First entry should be the activity (created earlier)- if timeline[0].Type != "activity" {- t.Fatalf("expected first entry type 'activity', got %q", timeline[0].Type)+ if !resp.HasMoreBefore {+ t.Fatalf("expected has_more_before=true with 120 total entries")}- if *timeline[0].Action != "created" {- t.Fatalf("expected action 'created', got %q", *timeline[0].Action)+ if resp.HasMoreAfter {+ t.Fatalf("latest page must report has_more_after=false")}-- // Second entry should be the comment- if timeline[1].Type != "comment" {- t.Fatalf("expected second entry type 'comment', got %q", timeline[1].Type)+ if resp.NextCursor == nil {+ t.Fatalf("expected next_cursor on full page")}- if *timeline[1].Content != "Timeline test comment" {- t.Fatalf("expected comment content 'Timeline test comment', got %q", *timeline[1].Content)+ // DESC order: first entry's timestamp must be >= last entry's.+ if resp.Entries[0].CreatedAt < resp.Entries[len(resp.Entries)-1].CreatedAt {+ t.Fatalf("expected DESC order, first=%s last=%s",+ resp.Entries[0].CreatedAt, resp.Entries[len(resp.Entries)-1].CreatedAt)}}-func TestListTimeline_ChronologicalOrder(t *testing.T) {- ctx := context.Background()-- // Create an issue- w := httptest.NewRecorder()- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "Timeline order test issue",- "status": "todo",- })- testHandler.CreateIssue(w, req)- var issue IssueResponse- json.NewDecoder(w.Body).Decode(&issue)- issueID := issue.ID-- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, issueID)- testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issueID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)- })+func TestListTimeline_BeforeCursorWalksOlder(t *testing.T) {+ issueID := createIssueForTimeline(t, "Before cursor test")+ seedTimelineEntries(t, issueID, 30, 30) // 60 total- // Create comment first- w = httptest.NewRecorder()- req = newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{- "content": "First comment",- })- req = withURLParam(req, "id", issueID)- testHandler.CreateComment(w, req)-- // Then create an activity after the comment- _, err := testHandler.Queries.CreateActivity(ctx, db.CreateActivityParams{- WorkspaceID: parseUUID(testWorkspaceID),- IssueID: parseUUID(issueID),- ActorType: strToText("member"),- ActorID: parseUUID(testUserID),- Action: "status_changed",- Details: []byte(`{"from":"todo","to":"in_progress"}`),- })- if err != nil {- t.Fatalf("CreateActivity: %v", err)+ first, _ := fetchTimeline(t, issueID, "limit=20")+ if len(first.Entries) != 20 {+ t.Fatalf("first page: expected 20, got %d", len(first.Entries))}-- // Fetch timeline- w = httptest.NewRecorder()- req = newRequest("GET", "/api/issues/"+issueID+"/timeline", nil)- req = withURLParam(req, "id", issueID)- testHandler.ListTimeline(w, req)-- var timeline []TimelineEntry- json.NewDecoder(w.Body).Decode(&timeline)- if len(timeline) != 2 {- t.Fatalf("expected 2 entries, got %d", len(timeline))+ if first.NextCursor == nil {+ t.Fatalf("first page should have next_cursor")}- // Entries should be in chronological order- if timeline[0].CreatedAt > timeline[1].CreatedAt {- t.Fatalf("timeline not in chronological order: %s > %s", timeline[0].CreatedAt, timeline[1].CreatedAt)+ second, code := fetchTimeline(t, issueID, "limit=20&before="+*first.NextCursor)+ if code != http.StatusOK {+ t.Fatalf("second page: expected 200, got %d", code)+ }+ if len(second.Entries) != 20 {+ t.Fatalf("second page: expected 20, got %d", len(second.Entries))+ }+ if !second.HasMoreAfter {+ t.Fatalf("second page must report has_more_after=true (we paged backward)")+ }+ // No overlap: oldest of first page must be strictly newer than newest of second.+ firstTail := first.Entries[len(first.Entries)-1]+ secondHead := second.Entries[0]+ if firstTail.CreatedAt < secondHead.CreatedAt {+ t.Fatalf("pages overlap: firstTail=%s secondHead=%s",+ firstTail.CreatedAt, secondHead.CreatedAt)}}-func TestCreateComment_WithParentID(t *testing.T) {- ctx := context.Background()-- // Create an issue- w := httptest.NewRecorder()- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "Reply test issue",- })- testHandler.CreateIssue(w, req)- var issue IssueResponse- json.NewDecoder(w.Body).Decode(&issue)- issueID := issue.ID-- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issueID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)- })+func TestListTimeline_AfterCursorWalksNewer(t *testing.T) {+ issueID := createIssueForTimeline(t, "After cursor test")+ seedTimelineEntries(t, issueID, 30, 30)- // Create parent comment- w = httptest.NewRecorder()- req = newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{- "content": "Parent comment",- })- req = withURLParam(req, "id", issueID)- testHandler.CreateComment(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateComment (parent): expected 201, got %d: %s", w.Code, w.Body.String())+ first, _ := fetchTimeline(t, issueID, "limit=20")+ if first.NextCursor == nil {+ t.Fatalf("first page should have next_cursor")}- var parentComment CommentResponse- json.NewDecoder(w.Body).Decode(&parentComment)-- // Create reply with parent_id- w = httptest.NewRecorder()- req = newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{- "content": "Reply to parent",- "parent_id": parentComment.ID,- })- req = withURLParam(req, "id", issueID)- testHandler.CreateComment(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateComment (reply): expected 201, got %d: %s", w.Code, w.Body.String())+ older, _ := fetchTimeline(t, issueID, "limit=20&before="+*first.NextCursor)+ if older.PrevCursor == nil {+ t.Fatalf("older page should have prev_cursor")}- var replyComment CommentResponse- json.NewDecoder(w.Body).Decode(&replyComment)- if replyComment.ParentID == nil {- t.Fatal("expected reply to have parent_id set")+ // Walk back forward: ?after=older.prev_cursor should land on entries+ // newer than the older page's newest, i.e. overlap with first page.+ newer, code := fetchTimeline(t, issueID, "limit=20&after="+*older.PrevCursor)+ if code != http.StatusOK {+ t.Fatalf("after page: expected 200, got %d", code)}- if *replyComment.ParentID != parentComment.ID {- t.Fatalf("expected parent_id %q, got %q", parentComment.ID, *replyComment.ParentID)+ if len(newer.Entries) == 0 {+ t.Fatalf("after page should not be empty")}-- // Verify parent comment has no parent_id- if parentComment.ParentID != nil {- t.Fatalf("expected parent comment to have nil parent_id, got %q", *parentComment.ParentID)+ if !newer.HasMoreBefore {+ t.Fatalf("after page must report has_more_before=true")}}-func TestCreateComment_AgentWithWrongParentRejected(t *testing.T) {- ctx := context.Background()+func TestListTimeline_AroundAnchorsOnTarget(t *testing.T) {+ issueID := createIssueForTimeline(t, "Around test")+ commentIDs, _ := seedTimelineEntries(t, issueID, 50, 0)+ // commentIDs[0] is the OLDEST. Pick the 2nd-oldest as the anchor — far+ // from the latest page so we can verify around mode actually works.+ target := commentIDs[1]- // Find the fixture agent + its runtime.- var agentID, runtimeID string- if err := testPool.QueryRow(ctx,- `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND name = $2`,- testWorkspaceID, "Handler Test Agent",- ).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("find test agent: %v", err)+ resp, code := fetchTimeline(t, issueID, "around="+target+"&limit=20")+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d", code)}-- // Two issues: A hosts the comment-triggered task; B exists to prove the- // guard is scoped to the task's own issue and does not block cross-issue- // agent activity. (The CLI stamps X-Task-ID on every request, so an agent- // legitimately commenting on another issue must still succeed.)- createIssue := func(title string) string {- w := httptest.NewRecorder()- r := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title})- testHandler.CreateIssue(w, r)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue(%s): %d: %s", title, w.Code, w.Body.String())- }- var issue IssueResponse- json.NewDecoder(w.Body).Decode(&issue)- return issue.ID+ if resp.TargetIndex == nil {+ t.Fatalf("expected target_index in around mode")}- issueA := createIssue("agent parent guard test — issue A")- issueB := createIssue("agent parent guard test — issue B")-- var freshTaskID string- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, freshTaskID)- testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id IN ($1, $2)`, issueA, issueB)- testPool.Exec(ctx, `DELETE FROM issue WHERE id IN ($1, $2)`, issueA, issueB)- })-- postComment := func(t *testing.T, issueID string, body map[string]any, headers map[string]string) *httptest.ResponseRecorder {- t.Helper()- w := httptest.NewRecorder()- r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)- r = withURLParam(r, "id", issueID)- for k, v := range headers {- r.Header.Set(k, v)- }- testHandler.CreateComment(w, r)- return w+ if len(resp.Entries) == 0 || resp.Entries[*resp.TargetIndex].ID != target {+ t.Fatalf("target_index does not point at target id; got %s",+ resp.Entries[*resp.TargetIndex].ID)}-- w := postComment(t, issueA, map[string]any{"content": "stale comment"}, nil)- if w.Code != http.StatusCreated {- t.Fatalf("create stale parent: %d: %s", w.Code, w.Body.String())+ // Should have entries on both sides of the anchor (the 2nd-oldest has+ // 1 older + many newer).+ if !resp.HasMoreAfter {+ t.Fatalf("around 2nd-oldest should report has_more_after=true")}- var staleParent CommentResponse- json.NewDecoder(w.Body).Decode(&staleParent)+}- w = postComment(t, issueA, map[string]any{"content": "fresh comment"}, nil)- if w.Code != http.StatusCreated {- t.Fatalf("create fresh parent: %d: %s", w.Code, w.Body.String())- }- var freshParent CommentResponse- json.NewDecoder(w.Body).Decode(&freshParent)+func TestListTimeline_AroundUnknownTarget(t *testing.T) {+ issueID := createIssueForTimeline(t, "Around 404 test")+ seedTimelineEntries(t, issueID, 5, 0)- // Comment-triggered task bound to issueA.- if err := testPool.QueryRow(ctx,- `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id)- VALUES ($1, $2, $3, 'queued', 0, $4) RETURNING id`,- agentID, runtimeID, issueA, freshParent.ID,- ).Scan(&freshTaskID); err != nil {- t.Fatalf("insert fresh task: %v", err)+ bogus := "00000000-0000-0000-0000-000000000001"+ _, code := fetchTimeline(t, issueID, "around="+bogus)+ if code != http.StatusNotFound {+ t.Fatalf("expected 404 for unknown anchor, got %d", code)}+}- agentHeaders := map[string]string{"X-Agent-ID": agentID, "X-Task-ID": freshTaskID}+func TestListTimeline_LimitOverMaxRejected(t *testing.T) {+ issueID := createIssueForTimeline(t, "Limit cap test")+ seedTimelineEntries(t, issueID, 1, 0)- // Same issue + wrong parent → 409.- w = postComment(t, issueA,- map[string]any{"content": "drifted reply", "parent_id": staleParent.ID},- agentHeaders,- )- if w.Code != http.StatusConflict {- t.Fatalf("expected 409 when agent replies with wrong parent, got %d: %s", w.Code, w.Body.String())- }- if !strings.Contains(w.Body.String(), freshParent.ID) {- t.Fatalf("expected error body to reference the correct trigger comment id, got %s", w.Body.String())+ _, code := fetchTimeline(t, issueID, "limit=500")+ if code != http.StatusBadRequest {+ t.Fatalf("expected 400 for limit=500, got %d", code)}+}- // Same issue + no parent → 409 (must reply to trigger).- w = postComment(t, issueA,- map[string]any{"content": "no parent"},- agentHeaders,- )- if w.Code != http.StatusConflict {- t.Fatalf("expected 409 when agent replies with no parent, got %d", w.Code)- }+func TestListTimeline_MutuallyExclusiveCursorParams(t *testing.T) {+ issueID := createIssueForTimeline(t, "Mutex test")+ seedTimelineEntries(t, issueID, 1, 0)- // Same issue + correct parent → 201.- w = postComment(t, issueA,- map[string]any{"content": "correct reply", "parent_id": freshParent.ID},- agentHeaders,- )- if w.Code != http.StatusCreated {- t.Fatalf("expected 201 when agent replies with matching parent, got %d: %s", w.Code, w.Body.String())+ _, code := fetchTimeline(t, issueID, "before=abc&after=def")+ if code != http.StatusBadRequest {+ t.Fatalf("before+after should 400, got %d", code)}+}- // Cross-issue: agent carries X-Task-ID (bound to issueA) but comments on- // issueB. The guard must NOT fire — this is the cross-issue regression- // covering the fix for gpt-boy's review.- w = postComment(t, issueB,- map[string]any{"content": "cross-issue note"},- agentHeaders,- )- if w.Code != http.StatusCreated {- t.Fatalf("agent posting on a different issue should not be blocked by its current task's trigger, got %d: %s", w.Code, w.Body.String())+func TestListTimeline_InvalidCursorRejected(t *testing.T) {+ issueID := createIssueForTimeline(t, "Bad cursor test")+ seedTimelineEntries(t, issueID, 1, 0)++ _, code := fetchTimeline(t, issueID, "before=not-base64-json")+ if code != http.StatusBadRequest {+ t.Fatalf("invalid cursor should 400, got %d", code)}}-func TestCommentWithParentID_AppearsInTimeline(t *testing.T) {+func TestListTimeline_MergedCommentAndActivity(t *testing.T) {+ issueID := createIssueForTimeline(t, "Merge test")ctx := context.Background()- // Create an issue- w := httptest.NewRecorder()- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{- "title": "Timeline reply test",- })- testHandler.CreateIssue(w, req)- var issue IssueResponse- json.NewDecoder(w.Body).Decode(&issue)- issueID := issue.ID+ // Use explicit, well-separated timestamps so the DESC ordering assertion+ // is deterministic regardless of clock granularity.+ older := time.Now().UTC().Add(-2 * time.Hour)+ newer := older.Add(1 * time.Hour)- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, issueID)- testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issueID)- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)- })-- // Create parent comment- w = httptest.NewRecorder()- req = newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{- "content": "Parent in timeline",- })- req = withURLParam(req, "id", issueID)- testHandler.CreateComment(w, req)- var parent CommentResponse- json.NewDecoder(w.Body).Decode(&parent)-- // Create reply- w = httptest.NewRecorder()- req = newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{- "content": "Reply in timeline",- "parent_id": parent.ID,- })- req = withURLParam(req, "id", issueID)- testHandler.CreateComment(w, req)-- // Fetch timeline- w = httptest.NewRecorder()- req = newRequest("GET", "/api/issues/"+issueID+"/timeline", nil)- req = withURLParam(req, "id", issueID)- testHandler.ListTimeline(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ListTimeline: expected 200, got %d: %s", w.Code, w.Body.String())+ // Older row: activity.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO activity_log (workspace_id, issue_id, actor_type, actor_id, action, details, created_at)+ VALUES ($1, $2, 'member', $3, 'created', '{}'::jsonb, $4)+ `, testWorkspaceID, issueID, testUserID, older); err != nil {+ t.Fatalf("seed activity: %v", err)}-- var timeline []TimelineEntry- json.NewDecoder(w.Body).Decode(&timeline)- if len(timeline) != 2 {- t.Fatalf("expected 2 timeline entries, got %d", len(timeline))+ // Newer row: comment.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at, updated_at)+ VALUES ($1, $2, 'member', $3, 'merge test comment', 'comment', $4, $4)+ `, issueID, testWorkspaceID, testUserID, newer); err != nil {+ t.Fatalf("seed comment: %v", err)}- // Find the reply entry- var found bool- for _, entry := range timeline {- if entry.Type == "comment" && entry.ParentID != nil && *entry.ParentID == parent.ID {- found = true- if *entry.Content != "Reply in timeline" {- t.Fatalf("expected reply content 'Reply in timeline', got %q", *entry.Content)- }- }+ resp, code := fetchTimeline(t, issueID, "")+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d", code)+ }+ if len(resp.Entries) != 2 {+ t.Fatalf("expected 2 entries, got %d", len(resp.Entries))+ }+ // DESC: comment (newer) at index 0, activity (older) at index 1.+ if resp.Entries[0].Type != "comment" || resp.Entries[1].Type != "activity" {+ t.Fatalf("merge order wrong: got %s/%s, want comment/activity",+ resp.Entries[0].Type, resp.Entries[1].Type)}- if !found {- t.Fatal("expected to find reply with parent_id in timeline")+ if !strings.Contains(*resp.Entries[0].Content, "merge test") {+ t.Fatalf("comment content lost in merge: %v", resp.Entries[0].Content)}}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex a77b21a4f9..e586f945cf 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -96,8 +96,19 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {var comments []db.Commentvar err error+ // When neither limit nor offset is specified, default to the most recent+ // 50 comments. The previous behavior returned every comment unbounded,+ // which let an agent or browser call accidentally pull thousands of rows+ // (see issue #1968). Callers that want everything must opt in with a+ // large explicit --limit; a 100-cap on the server side stays in place via+ // the timeline endpoint, but this endpoint is used by humans + the CLI+ // where the cap is the documented 50 default.+ if !hasPagination {+ limit = 50+ hasPagination = true+ }switch {- case sinceTime.Valid && hasPagination:+ case sinceTime.Valid:if limit == 0 {limit = 50}@@ -108,18 +119,7 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {Limit: limit,Offset: offset,})- case sinceTime.Valid:- // Apply a server-side cap to prevent unbounded result sets when- // --since is used without --limit.- comments, err = h.Queries.ListCommentsSincePaginated(r.Context(), db.ListCommentsSincePaginatedParams{- IssueID: issue.ID,- WorkspaceID: issue.WorkspaceID,- CreatedAt: sinceTime,- Limit: 500,- Offset: 0,- })- hasPagination = true- case hasPagination:+ default:if limit == 0 {limit = 50}@@ -129,11 +129,6 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {Limit: limit,Offset: offset,})- default:- comments, err = h.Queries.ListComments(r.Context(), db.ListCommentsParams{- IssueID: issue.ID,- WorkspaceID: issue.WorkspaceID,- })}if err != nil {writeError(w, http.StatusInternalServerError, "failed to list comments")diff --git a/server/migrations/068_timeline_keyset_index.down.sql b/server/migrations/068_timeline_keyset_index.down.sqlnew file mode 100644index 0000000000..e7f25f0db5--- /dev/null+++ b/server/migrations/068_timeline_keyset_index.down.sql@@ -0,0 +1,8 @@+CREATE INDEX IF NOT EXISTS idx_comment_issue+ ON comment (issue_id);++CREATE INDEX IF NOT EXISTS idx_activity_log_issue+ ON activity_log (issue_id);++DROP INDEX IF EXISTS idx_comment_issue_keyset;+DROP INDEX IF EXISTS idx_activity_log_issue_keyset;diff --git a/server/migrations/068_timeline_keyset_index.up.sql b/server/migrations/068_timeline_keyset_index.up.sqlnew file mode 100644index 0000000000..a2b62a3fb6--- /dev/null+++ b/server/migrations/068_timeline_keyset_index.up.sql@@ -0,0 +1,21 @@+-- Composite indexes that back the cursor-paginated timeline endpoint.+-- The keyset query shape is "WHERE issue_id = $1 AND (created_at, id) < ($2, $3)+-- ORDER BY created_at DESC, id DESC LIMIT $4". With (issue_id, created_at DESC,+-- id DESC) the planner can serve this as an index-only scan with no sort.+-- The leading issue_id column also covers the simple "WHERE issue_id = $1"+-- lookups, making the previous single-column idx_comment_issue and+-- idx_activity_log_issue redundant.+--+-- Not using CREATE INDEX CONCURRENTLY because the migration runner wraps+-- multi-statement files in an implicit transaction, which conflicts with+-- CONCURRENTLY. For pre-production scale this brief lock is acceptable; if+-- this ever needs to run on a hot prod table, do it as a one-off ops step.++CREATE INDEX IF NOT EXISTS idx_comment_issue_keyset+ ON comment (issue_id, created_at DESC, id DESC);++CREATE INDEX IF NOT EXISTS idx_activity_log_issue_keyset+ ON activity_log (issue_id, created_at DESC, id DESC);++DROP INDEX IF EXISTS idx_comment_issue;+DROP INDEX IF EXISTS idx_activity_log_issue;diff --git a/server/pkg/db/generated/activity.sql.go b/server/pkg/db/generated/activity.sql.goindex c491fba8b0..f3e6f20ba9 100644--- a/server/pkg/db/generated/activity.sql.go+++ b/server/pkg/db/generated/activity.sql.go@@ -97,21 +97,143 @@ func (q *Queries) CreateActivity(ctx context.Context, arg CreateActivityParams)return i, err}-const listActivities = `-- name: ListActivities :many+const getActivity = `-- name: GetActivity :one+SELECT id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at FROM activity_log+WHERE id = $1+`++// Used by the around-id mode of ListTimeline to resolve an entry to its+// (created_at, id) cursor when the entry is an activity.+func (q *Queries) GetActivity(ctx context.Context, id pgtype.UUID) (ActivityLog, error) {+ row := q.db.QueryRow(ctx, getActivity, id)+ var i ActivityLog+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.ActorType,+ &i.ActorID,+ &i.Action,+ &i.Details,+ &i.CreatedAt,+ )+ return i, err+}++const listActivitiesAfter = `-- name: ListActivitiesAfter :many+SELECT id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at FROM activity_log+WHERE issue_id = $1+ AND (created_at, id) > ($2::timestamptz, $3::uuid)+ORDER BY created_at ASC, id ASC+LIMIT $4+`++type ListActivitiesAfterParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ Column2 pgtype.Timestamptz `json:"column_2"`+ Column3 pgtype.UUID `json:"column_3"`+ Limit int32 `json:"limit"`+}++func (q *Queries) ListActivitiesAfter(ctx context.Context, arg ListActivitiesAfterParams) ([]ActivityLog, error) {+ rows, err := q.db.Query(ctx, listActivitiesAfter,+ arg.IssueID,+ arg.Column2,+ arg.Column3,+ arg.Limit,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ActivityLog{}+ for rows.Next() {+ var i ActivityLog+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.ActorType,+ &i.ActorID,+ &i.Action,+ &i.Details,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listActivitiesBefore = `-- name: ListActivitiesBefore :many+SELECT id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at FROM activity_log+WHERE issue_id = $1+ AND (created_at, id) < ($2::timestamptz, $3::uuid)+ORDER BY created_at DESC, id DESC+LIMIT $4+`++type ListActivitiesBeforeParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ Column2 pgtype.Timestamptz `json:"column_2"`+ Column3 pgtype.UUID `json:"column_3"`+ Limit int32 `json:"limit"`+}++func (q *Queries) ListActivitiesBefore(ctx context.Context, arg ListActivitiesBeforeParams) ([]ActivityLog, error) {+ rows, err := q.db.Query(ctx, listActivitiesBefore,+ arg.IssueID,+ arg.Column2,+ arg.Column3,+ arg.Limit,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ActivityLog{}+ for rows.Next() {+ var i ActivityLog+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.ActorType,+ &i.ActorID,+ &i.Action,+ &i.Details,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listActivitiesLatest = `-- name: ListActivitiesLatest :manySELECT id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at FROM activity_logWHERE issue_id = $1-ORDER BY created_at ASC-LIMIT $2 OFFSET $3+ORDER BY created_at DESC, id DESC+LIMIT $2`-type ListActivitiesParams struct {+type ListActivitiesLatestParams struct {IssueID pgtype.UUID `json:"issue_id"`Limit int32 `json:"limit"`- Offset int32 `json:"offset"`}-func (q *Queries) ListActivities(ctx context.Context, arg ListActivitiesParams) ([]ActivityLog, error) {- rows, err := q.db.Query(ctx, listActivities, arg.IssueID, arg.Limit, arg.Offset)+// Top N activities for an issue, newest first. Used by the cursor-paginated+// timeline endpoint to assemble the latest page.+func (q *Queries) ListActivitiesLatest(ctx context.Context, arg ListActivitiesLatestParams) ([]ActivityLog, error) {+ rows, err := q.db.Query(ctx, listActivitiesLatest, arg.IssueID, arg.Limit)if err != nil {return nil, err}diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex b43594ff17..e49120f129 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -173,19 +173,134 @@ func (q *Queries) HasAgentRepliedInThread(ctx context.Context, arg HasAgentReplireturn has_replied, err}-const listComments = `-- name: ListComments :many+const listCommentsAfter = `-- name: ListCommentsAfter :manySELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id FROM commentWHERE issue_id = $1 AND workspace_id = $2-ORDER BY created_at ASC+ AND (created_at, id) > ($3::timestamptz, $4::uuid)+ORDER BY created_at ASC, id ASC+LIMIT $5+`++type ListCommentsAfterParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Column3 pgtype.Timestamptz `json:"column_3"`+ Column4 pgtype.UUID `json:"column_4"`+ Limit int32 `json:"limit"`+}++// Keyset pagination: comments newer than ($3, $4) tuple. Returns ASC because+// "newer" pagination naturally walks forward in time; the merge layer+// normalizes to the response order.+func (q *Queries) ListCommentsAfter(ctx context.Context, arg ListCommentsAfterParams) ([]Comment, error) {+ rows, err := q.db.Query(ctx, listCommentsAfter,+ arg.IssueID,+ arg.WorkspaceID,+ arg.Column3,+ arg.Column4,+ arg.Limit,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Comment{}+ for rows.Next() {+ var i Comment+ if err := rows.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listCommentsBefore = `-- name: ListCommentsBefore :many+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id FROM comment+WHERE issue_id = $1 AND workspace_id = $2+ AND (created_at, id) < ($3::timestamptz, $4::uuid)+ORDER BY created_at DESC, id DESC+LIMIT $5`-type ListCommentsParams struct {+type ListCommentsBeforeParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Column3 pgtype.Timestamptz `json:"column_3"`+ Column4 pgtype.UUID `json:"column_4"`+ Limit int32 `json:"limit"`+}++// Keyset pagination: comments older than ($3, $4) tuple. Returns DESC so the+// caller can stitch pages without re-sorting.+func (q *Queries) ListCommentsBefore(ctx context.Context, arg ListCommentsBeforeParams) ([]Comment, error) {+ rows, err := q.db.Query(ctx, listCommentsBefore,+ arg.IssueID,+ arg.WorkspaceID,+ arg.Column3,+ arg.Column4,+ arg.Limit,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Comment{}+ for rows.Next() {+ var i Comment+ if err := rows.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listCommentsLatest = `-- name: ListCommentsLatest :many+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id FROM comment+WHERE issue_id = $1 AND workspace_id = $2+ORDER BY created_at DESC, id DESC+LIMIT $3+`++type ListCommentsLatestParams struct {IssueID pgtype.UUID `json:"issue_id"`WorkspaceID pgtype.UUID `json:"workspace_id"`+ Limit int32 `json:"limit"`}-func (q *Queries) ListComments(ctx context.Context, arg ListCommentsParams) ([]Comment, error) {- rows, err := q.db.Query(ctx, listComments, arg.IssueID, arg.WorkspaceID)+// Top N comments for an issue, newest first. Backs the default cursor+// pagination entry point (no cursor → return the most recent page).+func (q *Queries) ListCommentsLatest(ctx context.Context, arg ListCommentsLatestParams) ([]Comment, error) {+ rows, err := q.db.Query(ctx, listCommentsLatest, arg.IssueID, arg.WorkspaceID, arg.Limit)if err != nil {return nil, err}diff --git a/server/pkg/db/queries/activity.sql b/server/pkg/db/queries/activity.sqlindex 91a180cc5d..7e390bcfb1 100644--- a/server/pkg/db/queries/activity.sql+++ b/server/pkg/db/queries/activity.sql@@ -1,8 +1,30 @@--- name: ListActivities :many+-- name: ListActivitiesLatest :many+-- Top N activities for an issue, newest first. Used by the cursor-paginated+-- timeline endpoint to assemble the latest page.SELECT * FROM activity_logWHERE issue_id = $1-ORDER BY created_at ASC-LIMIT $2 OFFSET $3;+ORDER BY created_at DESC, id DESC+LIMIT $2;++-- name: ListActivitiesBefore :many+SELECT * FROM activity_log+WHERE issue_id = $1+ AND (created_at, id) < ($2::timestamptz, $3::uuid)+ORDER BY created_at DESC, id DESC+LIMIT $4;++-- name: ListActivitiesAfter :many+SELECT * FROM activity_log+WHERE issue_id = $1+ AND (created_at, id) > ($2::timestamptz, $3::uuid)+ORDER BY created_at ASC, id ASC+LIMIT $4;++-- name: GetActivity :one+-- Used by the around-id mode of ListTimeline to resolve an entry to its+-- (created_at, id) cursor when the entry is an activity.+SELECT * FROM activity_log+WHERE id = $1;-- name: CreateActivity :oneINSERT INTO activity_log (diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex 3d63a543ed..bec31910aa 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -1,8 +1,3 @@--- name: ListComments :many-SELECT * FROM comment-WHERE issue_id = $1 AND workspace_id = $2-ORDER BY created_at ASC;--- name: ListCommentsPaginated :manySELECT * FROM commentWHERE issue_id = $1 AND workspace_id = $2@@ -20,6 +15,33 @@ WHERE issue_id = $1 AND workspace_id = $2 AND created_at > $3ORDER BY created_at ASCLIMIT $4 OFFSET $5;+-- name: ListCommentsLatest :many+-- Top N comments for an issue, newest first. Backs the default cursor+-- pagination entry point (no cursor → return the most recent page).+SELECT * FROM comment+WHERE issue_id = $1 AND workspace_id = $2+ORDER BY created_at DESC, id DESC+LIMIT $3;++-- name: ListCommentsBefore :many+-- Keyset pagination: comments older than ($3, $4) tuple. Returns DESC so the+-- caller can stitch pages without re-sorting.+SELECT * FROM comment+WHERE issue_id = $1 AND workspace_id = $2+ AND (created_at, id) < ($3::timestamptz, $4::uuid)+ORDER BY created_at DESC, id DESC+LIMIT $5;++-- name: ListCommentsAfter :many+-- Keyset pagination: comments newer than ($3, $4) tuple. Returns ASC because+-- "newer" pagination naturally walks forward in time; the merge layer+-- normalizes to the response order.+SELECT * FROM comment+WHERE issue_id = $1 AND workspace_id = $2+ AND (created_at, id) > ($3::timestamptz, $4::uuid)+ORDER BY created_at ASC, id ASC+LIMIT $5;+-- name: CountComments :oneSELECT count(*) FROM commentWHERE issue_id = $1 AND workspace_id = $2;