Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(comments): thread-aware list with composite cursor (MUL-2340) (#2787)
Bohan Jiang6f5fbb781313
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 2a5ef921a9..ff357acc36 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -309,6 +309,10 @@ func init() {// issue comment listissueCommentListCmd.Flags().String("output", "table", "Output format: table or json")issueCommentListCmd.Flags().String("since", "", "Only return comments created after this timestamp (RFC3339)")+ issueCommentListCmd.Flags().String("thread", "", "Comment UUID — return the thread containing this comment (root + every descendant). May be a root or a reply id.")+ issueCommentListCmd.Flags().Int("recent", 0, "Return the N most recently active threads (root + descendants per thread). Use --before/--before-id from the previous response to scroll to older threads.")+ issueCommentListCmd.Flags().String("before", "", "Thread cursor: last_activity_at (RFC3339Nano). Read from the X-Multica-Next-Before response header; must be paired with --before-id.")+ issueCommentListCmd.Flags().String("before-id", "", "Thread cursor: root comment UUID. Read from the X-Multica-Next-Before-Id response header; must be paired with --before.")// issue runsissueRunsCmd.Flags().String("output", "table", "Output format: table or json")@@ -921,9 +925,51 @@ func runIssueCommentList(cmd *cobra.Command, args []string) error {return fmt.Errorf("resolve issue: %w", err)}+ since, _ := cmd.Flags().GetString("since")+ thread, _ := cmd.Flags().GetString("thread")+ recent, _ := cmd.Flags().GetInt("recent")+ // Flags().Changed distinguishes "user did not pass --recent" from+ // "user explicitly passed --recent 0" (or a negative value). The+ // GetInt zero-value collapses both cases, which would otherwise+ // cause us to silently drop an invalid value and fall back to the+ // default unparameterized list — exactly the drift Elon flagged in+ // the PR #2787 second review.+ recentSet := cmd.Flags().Changed("recent")+ before, _ := cmd.Flags().GetString("before")+ beforeID, _ := cmd.Flags().GetString("before-id")++ // Mirror the server-side combination rules client-side so the user gets+ // a clear local error instead of a 400 round-trip. These match the+ // validation in handler.ListComments (server/internal/handler/comment.go).+ if recentSet && recent <= 0 {+ return fmt.Errorf("--recent must be a positive integer")+ }+ if thread != "" && recentSet {+ return fmt.Errorf("--thread and --recent are mutually exclusive")+ }+ if thread != "" && (before != "" || beforeID != "") {+ return fmt.Errorf("--thread cannot be combined with --before / --before-id")+ }+ if (before == "") != (beforeID == "") {+ return fmt.Errorf("--before and --before-id must be set together (composite cursor for stable pagination)")+ }+ if before != "" && !recentSet {+ return fmt.Errorf("--before / --before-id require --recent (cursor scrolls within a recent window)")+ }+params := url.Values{}- if v, _ := cmd.Flags().GetString("since"); v != "" {- params.Set("since", v)+ if since != "" {+ params.Set("since", since)+ }+ if thread != "" {+ params.Set("thread", thread)+ }+ if recentSet {+ params.Set("recent", fmt.Sprintf("%d", recent))+ }+ if before != "" {+ params.Set("before", before)+ params.Set("before_id", beforeID)}path := "/api/issues/" + issueRef.ID + "/comments"@@ -932,10 +978,20 @@ func runIssueCommentList(cmd *cobra.Command, args []string) error {}var comments []map[string]any- if err := client.GetJSON(ctx, path, &comments); err != nil {+ respHeaders, err := client.GetJSONWithHeaders(ctx, path, &comments)+ if err != nil {return fmt.Errorf("list comments: %w", err)}fmt.Fprintf(os.Stderr, "Showing %d comments.\n", len(comments))+ // Under --recent the server emits a thread cursor in headers when there+ // is likely an older page. Surface it on stderr so an operator (and the+ // agent prompt update that follows this PR) can scroll deeper without+ // having to dig into the raw HTTP response.+ if nb := respHeaders.Get("X-Multica-Next-Before"); nb != "" {+ if nbid := respHeaders.Get("X-Multica-Next-Before-Id"); nbid != "" {+ fmt.Fprintf(os.Stderr, "Next thread cursor: --before %s --before-id %s\n", nb, nbid)+ }+ }output, _ := cmd.Flags().GetString("output")if output == "json" {diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 478d90014a..2165d02c79 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -1498,6 +1498,106 @@ func TestIssueSubscriberMutationBody(t *testing.T) {}}+// newIssueCommentListTestCmd mirrors the flag set wired in main.init() for+// the comment list command. We replicate it here so the runIssueCommentList+// guards can be exercised in isolation — the real command tree pulls in the+// daemon init path.+func newIssueCommentListTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "list"}+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("since", "", "")+ cmd.Flags().String("thread", "", "")+ cmd.Flags().Int("recent", 0, "")+ cmd.Flags().String("before", "", "")+ cmd.Flags().String("before-id", "", "")+ return cmd+}++// TestRunIssueCommentListFlagGuards locks the CLI-side flag combination+// matrix. Two behaviours matter here:+//+// - --recent 0 / --recent -3 must error rather than silently fall back to+// the default list path. Previously `recent > 0` collapsed "not passed"+// and "passed an invalid value" into the same branch; using+// Flags().Changed("recent") distinguishes them so an explicit non-+// positive value is rejected.+// - --before / --before-id without --recent must error. Before this fix+// the cursor would be sent to the server but ignored because RecentN=0,+// so callers asking for "comments before X" got the full timeline.+//+// All four cases must fail before any HTTP round-trip — verified by an+// httptest server that fatals if /api/issues/<key>/comments is hit.+func TestRunIssueCommentListFlagGuards(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // resolveIssueRef hits GET /api/issues/<ref>; everything else means+ // the guard let an invalid combination through to the wire.+ if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/issues/") && !strings.Contains(r.URL.Path, "/comments") {+ json.NewEncoder(w).Encode(map[string]any{+ "id": "issue-1",+ "identifier": "MUL-1",+ })+ return+ }+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.String())+ http.Error(w, "unexpected", http.StatusInternalServerError)+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cases := []struct {+ name string+ setup func(c *cobra.Command)+ wantMsg string+ }{+ {+ name: "explicit zero recent rejected",+ setup: func(c *cobra.Command) {+ _ = c.Flags().Set("recent", "0")+ },+ wantMsg: "--recent must be a positive integer",+ },+ {+ name: "negative recent rejected",+ setup: func(c *cobra.Command) {+ _ = c.Flags().Set("recent", "-3")+ },+ wantMsg: "--recent must be a positive integer",+ },+ {+ name: "before + before-id without recent rejected",+ setup: func(c *cobra.Command) {+ _ = c.Flags().Set("before", "2026-01-01T00:00:00Z")+ _ = c.Flags().Set("before-id", "00000000-0000-0000-0000-000000000001")+ },+ wantMsg: "--before / --before-id require --recent",+ },+ {+ name: "thread + recent still rejected when --recent explicit zero", // also covers the Changed() path+ setup: func(c *cobra.Command) {+ _ = c.Flags().Set("thread", "00000000-0000-0000-0000-000000000001")+ _ = c.Flags().Set("recent", "5")+ },+ wantMsg: "--thread and --recent are mutually exclusive",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ cmd := newIssueCommentListTestCmd()+ tc.setup(cmd)+ err := runIssueCommentList(cmd, []string{"MUL-1"})+ if err == nil {+ t.Fatalf("expected error containing %q, got nil", tc.wantMsg)+ }+ if !strings.Contains(err.Error(), tc.wantMsg) {+ t.Fatalf("error = %q, want substring %q", err.Error(), tc.wantMsg)+ }+ })+ }+}+func TestValidIssueStatuses(t *testing.T) {expected := map[string]bool{"backlog": true,diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex f1b360cec9..1626a2ed4a 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -5,6 +5,7 @@ import ("encoding/json""log/slog""net/http"+ "strconv""time""github.com/go-chi/chi/v5"@@ -66,6 +67,42 @@ func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments [// number of rows on a single issue.const commentHardCap = 2000+// ListComments returns comments for an issue. The default behaviour is+// unchanged — full chronological dump capped at commentHardCap — so existing+// callers and the desktop UI keep working as-is. Three optional query params+// give agent-style readers a thread-aware view that scales to long issues+// without dragging every prior comment into context:+//+// - thread=<comment-uuid> — return the root of the thread containing this+// comment plus every descendant. The anchor may be a root or any reply;+// the server walks up to the root via a recursive CTE, so callers do not+// need to know whether the id they have is a root.+// - recent=<N> — return the N most recently active threads (root + every+// descendant per thread). A thread's recency is MAX(created_at) across+// the whole subtree, so a stale-but-recently-replied thread ranks ahead+// of an active-but-quiet one. Row-based "newest N comments" is+// deliberately NOT exposed — it surfaces unrelated thread tails and+// hides relevant history (#2340).+// - before=<RFC3339> + before-id=<uuid> — thread cursor. The pair points at+// a thread's (last_activity_at, root_id); the next page returns threads+// strictly less recent. Both must be set together — a timestamp-only+// cursor cannot tie-break two threads whose last_activity falls in the+// same microsecond. The cursor for the next page is emitted via the+// X-Multica-Next-Before / X-Multica-Next-Before-Id response headers.+//+// Combination rules (kept narrow on purpose — Elon flagged the matrix risk):+//+// - thread is exclusive with recent and before/before-id. Asking for "the+// most recent N within thread X" or "thread X but only before T" mixes+// two different navigation models and is rejected with 400.+// - thread may combine with since (incremental polling of one thread).+// - recent may combine with before/before-id (scroll older threads) and+// with since (recent activity in a window).+// - since may combine with anything except (thread + recent / before).+//+// The response body is always chronological (oldest → newest); under recent+// that means threads are listed oldest-active first and the freshest thread+// sits at the tail, closest to "now" in an agent prompt.func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {issueID := chi.URLParam(r, "id")issue, ok := h.loadIssueForUser(w, r, issueID)@@ -73,57 +110,305 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {return}- // Only `since` is honoured — used by the CLI's `--since` agent-polling- // flow to fetch incremental comments. The previous limit/offset cursor- // was ripped out (#1929): time-based pagination breaks reply threads,- // and at the actual data sizes there is no win from paging.+ q := r.URL.Query()+var sinceTime pgtype.Timestamptz- if v := r.URL.Query().Get("since"); v != "" {- t, err := time.Parse(time.RFC3339, v)+ if v := q.Get("since"); v != "" {+ t, err := time.Parse(time.RFC3339Nano, v)if err != nil {- writeError(w, http.StatusBadRequest, "invalid since parameter; expected RFC3339 format")- return+ // Fall back to RFC3339 for backwards-compat with the original CLI.+ t, err = time.Parse(time.RFC3339, v)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid since parameter; expected RFC3339 format")+ return+ }}sinceTime = pgtype.Timestamptz{Time: t, Valid: true}}- var comments []db.Comment- var err error- if sinceTime.Valid {- comments, err = h.Queries.ListCommentsSinceForIssue(r.Context(), db.ListCommentsSinceForIssueParams{- IssueID: issue.ID,- WorkspaceID: issue.WorkspaceID,- CreatedAt: sinceTime,- Limit: commentHardCap,- })- } else {- comments, err = h.Queries.ListCommentsForIssue(r.Context(), db.ListCommentsForIssueParams{- IssueID: issue.ID,- WorkspaceID: issue.WorkspaceID,- Limit: commentHardCap,- })+ threadStr := q.Get("thread")+ recentStr := q.Get("recent")+ beforeTimeStr := q.Get("before")+ beforeIDStr := q.Get("before_id")+ if beforeIDStr == "" {+ // Accept hyphenated alias to match CLI flag convention.+ beforeIDStr = q.Get("before-id")}- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to list comments")++ // --- combination validation ----------------------------------------+ if threadStr != "" && recentStr != "" {+ writeError(w, http.StatusBadRequest, "thread and recent are mutually exclusive")+ return+ }+ if threadStr != "" && (beforeTimeStr != "" || beforeIDStr != "") {+ writeError(w, http.StatusBadRequest, "thread cannot be combined with before / before_id")+ return+ }+ if (beforeTimeStr == "") != (beforeIDStr == "") {+ writeError(w, http.StatusBadRequest, "before and before_id must be set together (composite cursor)")+ return+ }+ // Cursor only makes sense as "scroll older within a recent window". A+ // cursor without `recent` would otherwise be silently dropped by+ // fetchCommentsForList and fall back to the default / since path —+ // returning a full timeline that the caller did not ask for. Reject+ // loudly so the API surface matches the documented semantics.+ if beforeTimeStr != "" && recentStr == "" {+ writeError(w, http.StatusBadRequest, "before / before_id require recent (cursor scrolls within a recent window)")return}- commentIDs := make([]pgtype.UUID, len(comments))- for i, c := range comments {+ // --- parse cursor / recent ----------------------------------------+ var beforeCursor pgtype.Timestamptz+ var beforeUUID pgtype.UUID+ hasCursor := false+ if beforeTimeStr != "" {+ t, err := time.Parse(time.RFC3339Nano, beforeTimeStr)+ if err != nil {+ t, err = time.Parse(time.RFC3339, beforeTimeStr)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid before parameter; expected RFC3339 format")+ return+ }+ }+ beforeCursor = pgtype.Timestamptz{Time: t, Valid: true}+ uuid, perr := util.ParseUUID(beforeIDStr)+ if perr != nil {+ writeError(w, http.StatusBadRequest, "invalid before_id parameter; expected UUID")+ return+ }+ beforeUUID = uuid+ hasCursor = true+ }++ recentN := 0+ if recentStr != "" {+ n, err := strconv.Atoi(recentStr)+ if err != nil || n <= 0 {+ writeError(w, http.StatusBadRequest, "invalid recent parameter; expected positive integer")+ return+ }+ if n > commentHardCap {+ n = commentHardCap+ }+ recentN = n+ }++ result, err := h.fetchCommentsForList(r.Context(), fetchCommentsArgs{+ Issue: issue,+ Since: sinceTime,+ ThreadAnchor: threadStr,+ RecentN: recentN,+ HasCursor: hasCursor,+ BeforeAt: beforeCursor,+ BeforeID: beforeUUID,+ })+ if err != nil {+ switch err {+ case errCommentThreadNotFound:+ writeError(w, http.StatusNotFound, "thread anchor not found in this issue")+ return+ case errCommentThreadBadID:+ writeError(w, http.StatusBadRequest, "invalid thread parameter; expected UUID")+ return+ default:+ writeError(w, http.StatusInternalServerError, "failed to list comments")+ return+ }+ }++ commentIDs := make([]pgtype.UUID, len(result.Comments))+ for i, c := range result.Comments {commentIDs[i] = c.ID}grouped := h.groupReactions(r, commentIDs)groupedAtt := h.groupAttachments(r, commentIDs)- resp := make([]CommentResponse, len(comments))- for i, c := range comments {+ resp := make([]CommentResponse, len(result.Comments))+ for i, c := range result.Comments {cid := uuidToString(c.ID)resp[i] = commentToResponse(c, grouped[cid], groupedAtt[cid])}+ // Emit the next thread cursor as response headers when the recent page is+ // likely not the last one (returned a full page of threads). Headers stay+ // out of the JSON body so the default flat-array response shape — which+ // the desktop UI and existing callers depend on — is unchanged.+ if result.NextBefore != "" && result.NextBeforeID != "" {+ w.Header().Set("X-Multica-Next-Before", result.NextBefore)+ w.Header().Set("X-Multica-Next-Before-Id", result.NextBeforeID)+ }+writeJSON(w, http.StatusOK, resp)}+// fetchCommentsArgs bundles the parsed query params so fetchCommentsForList+// stays readable. Sentinel errors below let the caller turn DB-layer outcomes+// into the right HTTP status without leaking SQL details.+type fetchCommentsArgs struct {+ Issue db.Issue+ Since pgtype.Timestamptz+ ThreadAnchor string+ RecentN int+ HasCursor bool+ BeforeAt pgtype.Timestamptz+ BeforeID pgtype.UUID+}++// fetchCommentsResult carries both the materialised comments and (for the+// recent/thread-grouped path) the cursor to use for the next page. Cursor+// fields are empty strings when there is no next page or the path does not+// support cursors.+type fetchCommentsResult struct {+ Comments []db.Comment+ NextBefore string+ NextBeforeID string+}++var (+ errCommentThreadNotFound = &commentFetchError{"thread anchor not found"}+ errCommentThreadBadID = &commentFetchError{"invalid thread anchor id"}+)++type commentFetchError struct{ msg string }++func (e *commentFetchError) Error() string { return e.msg }++func (h *Handler) fetchCommentsForList(ctx context.Context, args fetchCommentsArgs) (fetchCommentsResult, error) {+ issue := args.Issue++ // Thread-scoped read. Server resolves the anchor → root via recursive+ // CTE, so we don't have to assume two-layer flat threads here.+ if args.ThreadAnchor != "" {+ anchor, err := util.ParseUUID(args.ThreadAnchor)+ if err != nil {+ return fetchCommentsResult{}, errCommentThreadBadID+ }+ rows, err := h.Queries.ListThreadCommentsForIssue(ctx, db.ListThreadCommentsForIssueParams{+ AnchorID: anchor,+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ RowLimit: commentHardCap,+ })+ if err != nil {+ return fetchCommentsResult{}, err+ }+ if len(rows) == 0 {+ return fetchCommentsResult{}, errCommentThreadNotFound+ }+ out := make([]db.Comment, 0, len(rows))+ for _, r := range rows {+ if args.Since.Valid && !r.CreatedAt.Time.After(args.Since.Time) {+ continue+ }+ out = append(out, db.Comment{+ ID: r.ID,+ IssueID: r.IssueID,+ AuthorType: r.AuthorType,+ AuthorID: r.AuthorID,+ Content: r.Content,+ Type: r.Type,+ CreatedAt: r.CreatedAt,+ UpdatedAt: r.UpdatedAt,+ ParentID: r.ParentID,+ WorkspaceID: r.WorkspaceID,+ ResolvedAt: r.ResolvedAt,+ ResolvedByType: r.ResolvedByType,+ ResolvedByID: r.ResolvedByID,+ })+ }+ return fetchCommentsResult{Comments: out}, nil+ }++ // Thread-grouped recent read: N most recently active threads.+ if args.RecentN > 0 {+ rows, err := h.Queries.ListRecentThreadCommentsForIssue(ctx, db.ListRecentThreadCommentsForIssueParams{+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ HasCursor: args.HasCursor,+ BeforeAt: args.BeforeAt,+ BeforeID: args.BeforeID,+ ThreadLimit: int32(args.RecentN),+ })+ if err != nil {+ return fetchCommentsResult{}, err+ }++ // The SQL already orders rows by (last_activity_at ASC, root_id ASC,+ // created_at ASC, id ASC), so the OLDEST-active thread sits at the+ // head and the FRESHEST thread at the tail. Walk the rows once to:+ // 1. Strip the thread-metadata columns down to db.Comment for the+ // caller (uniform shape across paths).+ // 2. Count distinct threads in the page so we know whether a "next+ // older page" is likely to exist.+ // 3. Capture the head thread's (last_activity_at, root_id) — that+ // is the cursor for the next page (next page = threads strictly+ // less recent than this one).+ comments := make([]db.Comment, 0, len(rows))+ var headRoot pgtype.UUID+ var headLast pgtype.Timestamptz+ seenRoot := map[string]struct{}{}+ for _, r := range rows {+ if !headRoot.Valid {+ headRoot = r.ThreadRootID+ headLast = r.ThreadLastActivityAt+ }+ seenRoot[uuidToString(r.ThreadRootID)] = struct{}{}+ // Since filter on the recent path: drop comments older than+ // `since`. Done in-memory so we keep the thread-grouped+ // semantics from the query (don't pre-filter rows before the+ // MAX(created_at) ranking — that would silently downgrade a+ // thread whose most recent activity falls inside the window).+ if args.Since.Valid && !r.CreatedAt.Time.After(args.Since.Time) {+ continue+ }+ comments = append(comments, db.Comment{+ ID: r.ID,+ IssueID: r.IssueID,+ AuthorType: r.AuthorType,+ AuthorID: r.AuthorID,+ Content: r.Content,+ Type: r.Type,+ CreatedAt: r.CreatedAt,+ UpdatedAt: r.UpdatedAt,+ ParentID: r.ParentID,+ WorkspaceID: r.WorkspaceID,+ ResolvedAt: r.ResolvedAt,+ ResolvedByType: r.ResolvedByType,+ ResolvedByID: r.ResolvedByID,+ })+ }++ // Only emit a cursor when the page is full. Fewer threads than+ // requested ⇒ the SELECT exhausted matching threads, so there is+ // no older page to scroll to.+ out := fetchCommentsResult{Comments: comments}+ if len(seenRoot) >= args.RecentN && headRoot.Valid && headLast.Valid {+ out.NextBefore = headLast.Time.UTC().Format(time.RFC3339Nano)+ out.NextBeforeID = uuidToString(headRoot)+ }+ return out, nil+ }++ // Default + since paths preserved verbatim (no behavioural change for+ // existing callers).+ if args.Since.Valid {+ comments, err := h.Queries.ListCommentsSinceForIssue(ctx, db.ListCommentsSinceForIssueParams{+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ CreatedAt: args.Since,+ Limit: commentHardCap,+ })+ return fetchCommentsResult{Comments: comments}, err+ }+ comments, err := h.Queries.ListCommentsForIssue(ctx, db.ListCommentsForIssueParams{+ IssueID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ Limit: commentHardCap,+ })+ return fetchCommentsResult{Comments: comments}, err+}+type CreateCommentRequest struct {Content string `json:"content"`Type string `json:"type"`diff --git a/server/internal/handler/comment_list_test.go b/server/internal/handler/comment_list_test.gonew file mode 100644index 0000000000..eb24487c28--- /dev/null+++ b/server/internal/handler/comment_list_test.go@@ -0,0 +1,578 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strconv"+ "testing"+ "time"++ "github.com/google/uuid"+)++// cursorQuery builds a properly URL-encoded query string for the recent ++// thread-cursor path. RFC3339Nano timestamps contain `:` and may contain `+`,+// both of which need escaping so they survive `(*url.URL).Query()` parsing on+// the server side.+//+// `before` and `beforeID` here name a *thread* (last_activity_at, root_id),+// not a single row — the recent path is thread-grouped (#2340).+func cursorQuery(recent int, before, beforeID string) string {+ v := url.Values{}+ if recent > 0 {+ v.Set("recent", strconv.Itoa(recent))+ }+ if before != "" {+ v.Set("before", before)+ }+ if beforeID != "" {+ v.Set("before_id", beforeID)+ }+ return v.Encode()+}++// nextThreadCursor reads the (before, before-id) headers the recent path+// emits when there is likely an older page to scroll to. Empty pair means+// the server signalled "no more threads".+func nextThreadCursor(w *httptest.ResponseRecorder) (string, string) {+ return w.Header().Get("X-Multica-Next-Before"), w.Header().Get("X-Multica-Next-Before-Id")+}++// commentListFixture seeds an issue with a known comment graph for the+// thread / recent / cursor tests. The shape:+//+// root1 (oldest)+// ├── r1a+// └── r1b+// └── r1b1 (nested reply — defends Elon's point 2: recursive root walk)+// root2 (newer, separate thread)+// ├── r2a+// └── r2b (newest overall)+//+// Each comment is inserted with an explicit created_at so ordering and+// cursor behavior are deterministic.+type commentListFixture struct {+ IssueID string+ Root1 string+ R1a string+ R1b string+ R1b1 string+ Root2 string+ R2a string+ R2b string+ Base time.Time+}++func newCommentListFixture(t *testing.T) commentListFixture {+ t.Helper()+ ctx := context.Background()++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title)+ VALUES ($1, 'member', $2, $3)+ RETURNING id+ `, testWorkspaceID, testUserID, "comment list fixture").Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ base := time.Now().UTC().Add(-1 * time.Hour).Truncate(time.Second)++ insert := func(parent *string, offset time.Duration, body string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, created_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5, $6)+ RETURNING id+ `, issueID, testWorkspaceID, testUserID, body, parent, base.Add(offset)).Scan(&id); err != nil {+ t.Fatalf("insert comment %q: %v", body, err)+ }+ return id+ }++ root1 := insert(nil, 0, "root1")+ r1a := insert(&root1, 1*time.Minute, "r1a")+ r1b := insert(&root1, 2*time.Minute, "r1b")+ r1b1 := insert(&r1b, 3*time.Minute, "r1b1") // nested reply: parent is a reply, not a root+ root2 := insert(nil, 10*time.Minute, "root2")+ r2a := insert(&root2, 11*time.Minute, "r2a")+ r2b := insert(&root2, 12*time.Minute, "r2b")++ return commentListFixture{+ IssueID: issueID,+ Root1: root1, R1a: r1a, R1b: r1b, R1b1: r1b1,+ Root2: root2, R2a: r2a, R2b: r2b,+ Base: base,+ }+}++func decodeComments(t *testing.T, body []byte) []CommentResponse {+ t.Helper()+ var resp []CommentResponse+ if err := json.Unmarshal(body, &resp); err != nil {+ t.Fatalf("decode comments: %v", err)+ }+ return resp+}++func listComments(t *testing.T, issueID, query string) (*httptest.ResponseRecorder, []CommentResponse) {+ t.Helper()+ w := httptest.NewRecorder()+ url := "/api/issues/" + issueID + "/comments"+ if query != "" {+ url += "?" + query+ }+ r := newRequest("GET", url, nil)+ r = withURLParam(r, "id", issueID)+ testHandler.ListComments(w, r)+ if w.Code != http.StatusOK {+ return w, nil+ }+ return w, decodeComments(t, w.Body.Bytes())+}++func ids(rows []CommentResponse) []string {+ out := make([]string, len(rows))+ for i, c := range rows {+ out[i] = c.ID+ }+ return out+}++func eqIDs(t *testing.T, got, want []string, ctx string) {+ t.Helper()+ if len(got) != len(want) {+ t.Fatalf("%s: ids len got=%d want=%d\ngot=%v\nwant=%v", ctx, len(got), len(want), got, want)+ }+ for i := range got {+ if got[i] != want[i] {+ t.Fatalf("%s: ids[%d] got=%s want=%s\ngot=%v\nwant=%v", ctx, i, got[i], want[i], got, want)+ }+ }+}++// TestListComments_DefaultPreservesChronologicalOrder is a guard against+// silent regressions in the unparameterized list path — agents and the UI+// both depend on chronological order.+func TestListComments_DefaultPreservesChronologicalOrder(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ _, rows := listComments(t, fx.IssueID, "")+ want := []string{fx.Root1, fx.R1a, fx.R1b, fx.R1b1, fx.Root2, fx.R2a, fx.R2b}+ eqIDs(t, ids(rows), want, "default order")+}++// TestListComments_ThreadResolvesFromAnyAnchor proves Elon's point 2:+// regardless of whether the anchor is a root, a direct reply, or a nested+// reply (parent_id points at another reply), the server walks up to the+// thread root and returns root + every descendant.+func TestListComments_ThreadResolvesFromAnyAnchor(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ wantThread1 := []string{fx.Root1, fx.R1a, fx.R1b, fx.R1b1}++ t.Run("anchor is root", func(t *testing.T) {+ _, rows := listComments(t, fx.IssueID, "thread="+fx.Root1)+ eqIDs(t, ids(rows), wantThread1, "anchor=root1")+ })++ t.Run("anchor is direct reply", func(t *testing.T) {+ _, rows := listComments(t, fx.IssueID, "thread="+fx.R1a)+ eqIDs(t, ids(rows), wantThread1, "anchor=r1a (direct reply)")+ })++ t.Run("anchor is nested reply", func(t *testing.T) {+ // r1b1.parent_id = r1b, which itself is a reply. The recursive CTE+ // must climb root1 → r1b → r1b1 to resolve the root.+ _, rows := listComments(t, fx.IssueID, "thread="+fx.R1b1)+ eqIDs(t, ids(rows), wantThread1, "anchor=r1b1 (nested reply)")+ })++ t.Run("anchor in other thread returns only that thread", func(t *testing.T) {+ _, rows := listComments(t, fx.IssueID, "thread="+fx.R2a)+ eqIDs(t, ids(rows), []string{fx.Root2, fx.R2a, fx.R2b}, "anchor=r2a")+ })+}++// TestListComments_ThreadAnchorErrors covers the user-facing error surface+// for the thread path. The unknown-anchor case is what catches the typical+// "agent pasted a stale UUID" footgun — the server returns 404 instead of+// silently returning an empty list (which would otherwise be+// indistinguishable from a deleted thread).+func TestListComments_ThreadAnchorErrors(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ t.Run("non-uuid thread returns 400", func(t *testing.T) {+ w, _ := listComments(t, fx.IssueID, "thread=not-a-uuid")+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ })++ t.Run("unknown thread anchor returns 404", func(t *testing.T) {+ w, _ := listComments(t, fx.IssueID, "thread=00000000-0000-0000-0000-000000000001")+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+ })+}++// TestListComments_RecentReturnsMostRecentlyActiveThreads pins the+// thread-grouped semantics from #2340. Row-based "newest N comments" would+// have surfaced [root2, r2a, r2b] for N=3 — a single thread's tail. The+// thread-grouped path treats the unit as a thread (root + descendants) and+// ranks threads by MAX(created_at) over the subtree, so:+//+// - recent=1 → the single freshest-active thread (root2 thread) fully+// expanded, oldest-active thread suppressed.+// - recent=2 → both threads, with the older-active thread first so the+// freshest sits at the prompt tail (closest to "now").+func TestListComments_RecentReturnsMostRecentlyActiveThreads(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ t.Run("recent=1 returns the freshest-active thread fully", func(t *testing.T) {+ _, rows := listComments(t, fx.IssueID, "recent=1")+ eqIDs(t, ids(rows), []string{fx.Root2, fx.R2a, fx.R2b}, "recent=1")+ })++ t.Run("recent=2 returns both threads, older-active first", func(t *testing.T) {+ _, rows := listComments(t, fx.IssueID, "recent=2")+ // Threads sorted by (last_activity_at ASC, root_id ASC):+ // root1 thread (last_activity = base + 3m via r1b1) FIRST+ // root2 thread (last_activity = base + 12m via r2b) SECOND+ // In-thread ordering is chronological.+ want := []string{fx.Root1, fx.R1a, fx.R1b, fx.R1b1, fx.Root2, fx.R2a, fx.R2b}+ eqIDs(t, ids(rows), want, "recent=2")+ })+}++// TestListComments_RecentRanksStaleThreadAheadIfRecentlyReplied makes the+// MAX(created_at) ranking explicit: a thread whose root is old but which has+// a fresh reply must outrank a thread whose root is newer but quiet. Without+// this, "recent" decays into "most recent root" and misses the very signal+// that thread-grouping was meant to surface.+func TestListComments_RecentRanksStaleThreadAheadIfRecentlyReplied(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title)+ VALUES ($1, 'member', $2, $3) RETURNING id+ `, testWorkspaceID, testUserID, "stale-but-fresh fixture").Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ base := time.Now().UTC().Add(-1 * time.Hour).Truncate(time.Second)+ insert := func(parent *string, offset time.Duration, body string) string {+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, created_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5, $6) RETURNING id+ `, issueID, testWorkspaceID, testUserID, body, parent, base.Add(offset)).Scan(&id); err != nil {+ t.Fatalf("insert: %v", err)+ }+ return id+ }++ // Stale-then-fresh: oldRoot was created at t=0 but received a reply at+ // t=30m. quietRoot was created at t=15m and never replied.+ oldRoot := insert(nil, 0, "oldRoot")+ quietRoot := insert(nil, 15*time.Minute, "quietRoot")+ freshReply := insert(&oldRoot, 30*time.Minute, "freshReply")++ _, rows := listComments(t, issueID, "recent=1")+ // Expected: only the oldRoot thread (oldRoot + freshReply). The+ // quietRoot thread is suppressed because its last_activity_at is older+ // than oldRoot's, even though its root was created later.+ eqIDs(t, ids(rows), []string{oldRoot, freshReply}, "recent=1 picks freshly replied stale thread")+ _ = quietRoot+}++// TestListComments_RecentEmitsThreadCursorWhenPageFull pins the header+// contract: a full page (threads in response == --recent N) emits the+// next-page cursor; an underfilled page emits nothing. The cursor points at+// the OLDEST thread in the page — that is the upper bound for the next+// (older) page.+func TestListComments_RecentEmitsThreadCursorWhenPageFull(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ t.Run("underfilled page emits no cursor", func(t *testing.T) {+ // recent=5 with only 2 threads available — server has nothing older+ // to offer. No cursor headers means the client stops paginating.+ w, _ := listComments(t, fx.IssueID, "recent=5")+ nb, nbid := nextThreadCursor(w)+ if nb != "" || nbid != "" {+ t.Fatalf("expected no cursor, got before=%q before_id=%q", nb, nbid)+ }+ })++ t.Run("full page emits cursor pointing at oldest thread in page", func(t *testing.T) {+ // recent=1: page is full (1 thread returned, 1 requested). Cursor+ // must point at the (last_activity_at, root_id) of the only thread+ // in the page so the next request can fetch older threads.+ w, _ := listComments(t, fx.IssueID, "recent=1")+ nb, nbid := nextThreadCursor(w)+ if nbid != fx.Root2 {+ t.Fatalf("cursor before_id = %q, want %q (root2 — newest thread)", nbid, fx.Root2)+ }+ if nb == "" {+ t.Fatalf("cursor before is empty; expected RFC3339Nano timestamp")+ }+ if _, err := time.Parse(time.RFC3339Nano, nb); err != nil {+ t.Fatalf("cursor before = %q is not RFC3339Nano: %v", nb, err)+ }+ })+}++// TestListComments_RecentWithThreadCursorScrollsOlderThreads walks the issue+// thread-by-thread using the cursor the server emits. Pinning this avoids+// the row-based regression where a "newest N comments" cursor would interleave+// rows from multiple threads and skip thread membership across pages.+func TestListComments_RecentWithThreadCursorScrollsOlderThreads(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ // Page 1: newest thread = root2.+ w1, page1 := listComments(t, fx.IssueID, "recent=1")+ eqIDs(t, ids(page1), []string{fx.Root2, fx.R2a, fx.R2b}, "page1 = root2 thread")+ nb, nbid := nextThreadCursor(w1)+ if nb == "" || nbid != fx.Root2 {+ t.Fatalf("page1 cursor = (%q, %q), want (non-empty, %q)", nb, nbid, fx.Root2)+ }++ // Page 2: cursor points at root2 → server returns the next older thread+ // (root1). All of root1's descendants come along.+ w2, page2 := listComments(t, fx.IssueID, cursorQuery(1, nb, nbid))+ eqIDs(t, ids(page2), []string{fx.Root1, fx.R1a, fx.R1b, fx.R1b1}, "page2 = root1 thread")++ // Page 3: cursor points at root1 → no older threads exist, page is+ // empty AND no cursor is emitted.+ nb2, nbid2 := nextThreadCursor(w2)+ if nb2 == "" || nbid2 != fx.Root1 {+ t.Fatalf("page2 cursor = (%q, %q), want (non-empty, %q)", nb2, nbid2, fx.Root1)+ }+ w3, page3 := listComments(t, fx.IssueID, cursorQuery(1, nb2, nbid2))+ if len(page3) != 0 {+ t.Fatalf("page3: expected empty (no older threads), got %d rows: %v", len(page3), ids(page3))+ }+ nb3, nbid3 := nextThreadCursor(w3)+ if nb3 != "" || nbid3 != "" {+ t.Fatalf("page3 cursor = (%q, %q), want both empty (end-of-list)", nb3, nbid3)+ }+}++// TestListComments_ThreadCursorStableUnderSameLastActivity locks the+// tie-break invariant for the thread cursor. Three threads with identical+// last_activity_at must paginate one-at-a-time without skips or duplicates,+// because (last_activity_at, root_id) — not just last_activity_at — is the+// total order. A timestamp-only cursor would either drop one thread or+// surface the same thread twice when ties land in the same microsecond.+func TestListComments_ThreadCursorStableUnderSameLastActivity(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title)+ VALUES ($1, 'member', $2, $3) RETURNING id+ `, testWorkspaceID, testUserID, "thread tie-break fixture").Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ ts := time.Now().UTC().Add(-30 * time.Minute).Truncate(time.Millisecond)+ insertRoot := func(body string) string {+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5) RETURNING id+ `, issueID, testWorkspaceID, testUserID, body, ts).Scan(&id); err != nil {+ t.Fatalf("insert: %v", err)+ }+ return id+ }+ a := insertRoot("a")+ b := insertRoot("b")+ c := insertRoot("c")++ // All three threads have last_activity_at = ts (each root is also the+ // thread's only comment). Order is (ts, root_id) — UUID lex tie-break.+ // Build canonical order by sorting the root ids and reversing (the SQL+ // orders DESC for selection).+ sorted := []string{a, b, c}+ for i := 0; i < len(sorted); i++ {+ for j := i + 1; j < len(sorted); j++ {+ if sorted[i] > sorted[j] {+ sorted[i], sorted[j] = sorted[j], sorted[i]+ }+ }+ }+ // Newest-first selection walks UUIDs DESC, so the page-1 thread is the+ // largest UUID; response is then ordered ASC (oldest-active first =+ // smallest-UUID-among-current-page) — with recent=1 there's only one+ // thread per page so the body shows that thread alone.+ wantOrder := []string{sorted[2], sorted[1], sorted[0]}++ var got []string+ w, page := listComments(t, issueID, "recent=1")+ if len(page) != 1 {+ t.Fatalf("page1: expected 1 thread (1 row), got %d", len(page))+ }+ got = append(got, page[0].ID)++ for i := 0; i < 2; i++ {+ nb, nbid := nextThreadCursor(w)+ if nb == "" || nbid == "" {+ t.Fatalf("page %d: missing cursor headers", i+1)+ }+ w, page = listComments(t, issueID, cursorQuery(1, nb, nbid))+ if len(page) != 1 {+ t.Fatalf("page %d: expected 1 thread (1 row), got %d", i+2, len(page))+ }+ got = append(got, page[0].ID)+ }++ eqIDs(t, got, wantOrder, "paginated walk")+}++// TestListComments_FlagCombinationRules locks Elon's point 4. The matrix is+// tiny on purpose — the goal is to ensure conflicting flags are rejected+// loudly at the API surface so the CLI's local validation cannot drift.+func TestListComments_FlagCombinationRules(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ cases := []struct {+ name string+ query string+ status int+ }{+ {+ name: "thread + recent rejected",+ query: "thread=" + fx.Root1 + "&recent=5",+ status: http.StatusBadRequest,+ },+ {+ name: "thread + before rejected",+ query: (func() string {+ v := url.Values{}+ v.Set("thread", fx.Root1)+ v.Set("before", time.Now().UTC().Format(time.RFC3339))+ v.Set("before_id", uuid.NewString())+ return v.Encode()+ })(),+ status: http.StatusBadRequest,+ },+ {+ name: "before without before_id rejected",+ query: (func() string {+ v := url.Values{}+ v.Set("recent", "5")+ v.Set("before", time.Now().UTC().Format(time.RFC3339))+ return v.Encode()+ })(),+ status: http.StatusBadRequest,+ },+ {+ name: "before_id without before rejected",+ query: (func() string {+ v := url.Values{}+ v.Set("recent", "5")+ v.Set("before_id", uuid.NewString())+ return v.Encode()+ })(),+ status: http.StatusBadRequest,+ },+ {+ name: "before + before_id without recent rejected",+ // Cursor without --recent used to fall through to the default /+ // since path and silently return the full timeline (the gap Elon+ // called out in the PR #2787 second review). The 400 here pins+ // the documented "cursor scrolls within a recent window" rule.+ query: (func() string {+ v := url.Values{}+ v.Set("before", time.Now().UTC().Format(time.RFC3339))+ v.Set("before_id", uuid.NewString())+ return v.Encode()+ })(),+ status: http.StatusBadRequest,+ },+ {+ name: "zero recent rejected",+ query: "recent=0",+ status: http.StatusBadRequest,+ },+ {+ name: "negative recent rejected",+ query: "recent=-3",+ status: http.StatusBadRequest,+ },+ {+ name: "non-numeric recent rejected",+ query: "recent=lots",+ status: http.StatusBadRequest,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ w, _ := listComments(t, fx.IssueID, tc.query)+ if w.Code != tc.status {+ t.Fatalf("query=%q\n got=%d want=%d body=%s", tc.query, w.Code, tc.status, w.Body.String())+ }+ })+ }+}++// TestListComments_ThreadWithSinceFiltersWithinThread proves the allowed+// combination from the rules: `thread + since` returns only comments in+// that thread newer than `since`. The since filter is applied in-memory+// after the thread CTE so the root membership semantics stay intact.+func TestListComments_ThreadWithSinceFiltersWithinThread(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ fx := newCommentListFixture(t)++ // since = base+1m30s → drop root1, r1a; keep r1b, r1b1.+ v := url.Values{}+ v.Set("thread", fx.Root1)+ v.Set("since", fx.Base.Add(90*time.Second).UTC().Format(time.RFC3339Nano))+ _, rows := listComments(t, fx.IssueID, v.Encode())+ eqIDs(t, ids(rows), []string{fx.R1b, fx.R1b1}, "thread+since")+}diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex 526f3d9fbb..9456db4000 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -287,6 +287,252 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListCommentreturn items, nil}+const listRecentThreadCommentsForIssue = `-- name: ListRecentThreadCommentsForIssue :many+WITH RECURSIVE membership(id, root_id, comment_created_at) AS (+ -- Each root maps to itself.+ SELECT c.id, c.id AS root_id, c.created_at+ FROM comment c+ WHERE c.issue_id = $1+ AND c.workspace_id = $2+ AND c.parent_id IS NULL+ UNION ALL+ -- Each descendant inherits its parent's root_id.+ SELECT c.id, m.root_id, c.created_at+ FROM comment c+ JOIN membership m ON c.parent_id = m.id+ WHERE c.issue_id = $1+ AND c.workspace_id = $2+),+thread_stats AS (+ SELECT root_id, MAX(comment_created_at)::timestamptz AS last_activity_at+ FROM membership+ GROUP BY root_id+),+picked AS (+ SELECT ts.root_id, ts.last_activity_at+ FROM thread_stats ts+ WHERE (+ $3::boolean = FALSE+ OR (ts.last_activity_at, ts.root_id) < ($4::timestamptz, $5::uuid)+ )+ ORDER BY ts.last_activity_at DESC, ts.root_id DESC+ LIMIT $6+)+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,+ p.root_id AS thread_root_id,+ p.last_activity_at AS thread_last_activity_at+FROM picked p+JOIN membership m ON m.root_id = p.root_id+JOIN comment c ON c.id = m.id+ORDER BY p.last_activity_at ASC, p.root_id ASC, c.created_at ASC, c.id ASC+`++type ListRecentThreadCommentsForIssueParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ HasCursor bool `json:"has_cursor"`+ BeforeAt pgtype.Timestamptz `json:"before_at"`+ BeforeID pgtype.UUID `json:"before_id"`+ ThreadLimit int32 `json:"thread_limit"`+}++type ListRecentThreadCommentsForIssueRow struct {+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ParentID pgtype.UUID `json:"parent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`+ ResolvedByType pgtype.Text `json:"resolved_by_type"`+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`+ ThreadRootID pgtype.UUID `json:"thread_root_id"`+ ThreadLastActivityAt pgtype.Timestamptz `json:"thread_last_activity_at"`+}++// Returns the N most recently active threads (root + every descendant) rather+// than the N most recent rows. A thread's "last activity" is MAX(created_at)+// over its whole subtree; threads are ranked by (last_activity_at DESC,+// root_id DESC) and the top N are expanded.+//+// Why thread-grouped instead of row-recent: with row-recent the newest 20+// comments can come from 8 different threads — the agent sees 8 unrelated+// tails. With thread-grouped the agent sees N complete conversational arcs,+// which matches how a human reads an issue (#2340).+//+// Response ordering:+//+// threads: (thread_last_activity_at ASC, root_id ASC)+// in-thread: (created_at ASC, id ASC)+//+// So the oldest-active thread appears first and the most recently-active+// thread is at the tail, closest to "now" in an agent prompt.+//+// Cursor scrolls back through threads. When @has_cursor=TRUE only threads+// with (last_activity_at, root_id) < (@before_at, @before_id) are eligible.+// The cursor is a THREAD cursor — both values identify a thread (its last+// activity timestamp and its root comment id), not a single row.+//+// The recursive `membership` CTE labels each comment with its thread root by+// walking down from every root. It does not assume any maximum nesting depth,+// which preserves correctness even if the schema ever allows reply-of-reply+// (the agent path in TaskService.createAgentComment collapses to root today,+// but the user-facing CreateComment handler does not enforce it).+func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg ListRecentThreadCommentsForIssueParams) ([]ListRecentThreadCommentsForIssueRow, error) {+ rows, err := q.db.Query(ctx, listRecentThreadCommentsForIssue,+ arg.IssueID,+ arg.WorkspaceID,+ arg.HasCursor,+ arg.BeforeAt,+ arg.BeforeID,+ arg.ThreadLimit,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListRecentThreadCommentsForIssueRow{}+ for rows.Next() {+ var i ListRecentThreadCommentsForIssueRow+ if err := rows.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ &i.ResolvedAt,+ &i.ResolvedByType,+ &i.ResolvedByID,+ &i.ThreadRootID,+ &i.ThreadLastActivityAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listThreadCommentsForIssue = `-- name: ListThreadCommentsForIssue :many+WITH RECURSIVE root_of AS (+ -- Walk up from the anchor until parent_id IS NULL.+ SELECT c.id, c.parent_id+ FROM comment c+ WHERE c.id = $2 AND c.issue_id = $3 AND c.workspace_id = $4+ UNION ALL+ SELECT p.id, p.parent_id+ FROM comment p+ JOIN root_of r ON p.id = r.parent_id+),+thread_root AS (+ SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1+),+descendants AS (+ -- Start from the root, then keep adding any comment whose parent is+ -- already in the set. Cycle-safe under PK constraint (a comment cannot+ -- be its own ancestor).+ SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id+ FROM comment c+ JOIN thread_root tr ON c.id = tr.id+ UNION+ SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id+ FROM comment c+ JOIN descendants d ON c.parent_id = d.id+ WHERE c.issue_id = $3 AND c.workspace_id = $4+)+SELECT id, issue_id, author_type, author_id, content, type,+ created_at, updated_at, parent_id, workspace_id,+ resolved_at, resolved_by_type, resolved_by_id+FROM descendants+ORDER BY created_at ASC, id ASC+LIMIT $1+`++type ListThreadCommentsForIssueParams struct {+ RowLimit int32 `json:"row_limit"`+ AnchorID pgtype.UUID `json:"anchor_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++type ListThreadCommentsForIssueRow struct {+ ID pgtype.UUID `json:"id"`+ IssueID pgtype.UUID `json:"issue_id"`+ AuthorType string `json:"author_type"`+ AuthorID pgtype.UUID `json:"author_id"`+ Content string `json:"content"`+ Type string `json:"type"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ParentID pgtype.UUID `json:"parent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`+ ResolvedByType pgtype.Text `json:"resolved_by_type"`+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`+}++// Returns the root of the thread containing @anchor_id plus every descendant+// (recursive — defends against any future deeper nesting; today's data is two+// layers because the CreateComment path collapses replies to root, but the+// schema does not enforce that). @anchor_id may itself be a root or a reply.+// Output is chronological so it can be fed straight to the agent.+func (q *Queries) ListThreadCommentsForIssue(ctx context.Context, arg ListThreadCommentsForIssueParams) ([]ListThreadCommentsForIssueRow, error) {+ rows, err := q.db.Query(ctx, listThreadCommentsForIssue,+ arg.RowLimit,+ arg.AnchorID,+ arg.IssueID,+ arg.WorkspaceID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListThreadCommentsForIssueRow{}+ for rows.Next() {+ var i ListThreadCommentsForIssueRow+ if err := rows.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ &i.ResolvedAt,+ &i.ResolvedByType,+ &i.ResolvedByID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const resolveComment = `-- name: ResolveComment :oneUPDATE comment SETresolved_at = COALESCE(resolved_at, now()),diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex ae90a04405..069923cc3e 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -15,6 +15,116 @@ WHERE issue_id = $1 AND workspace_id = $2 AND created_at > $3ORDER BY created_at ASC, id ASCLIMIT $4;+-- name: ListThreadCommentsForIssue :many+-- Returns the root of the thread containing @anchor_id plus every descendant+-- (recursive — defends against any future deeper nesting; today's data is two+-- layers because the CreateComment path collapses replies to root, but the+-- schema does not enforce that). @anchor_id may itself be a root or a reply.+-- Output is chronological so it can be fed straight to the agent.+WITH RECURSIVE root_of AS (+ -- Walk up from the anchor until parent_id IS NULL.+ SELECT c.id, c.parent_id+ FROM comment c+ WHERE c.id = @anchor_id AND c.issue_id = @issue_id AND c.workspace_id = @workspace_id+ UNION ALL+ SELECT p.id, p.parent_id+ FROM comment p+ JOIN root_of r ON p.id = r.parent_id+),+thread_root AS (+ SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1+),+descendants AS (+ -- Start from the root, then keep adding any comment whose parent is+ -- already in the set. Cycle-safe under PK constraint (a comment cannot+ -- be its own ancestor).+ SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id+ FROM comment c+ JOIN thread_root tr ON c.id = tr.id+ UNION+ SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id+ FROM comment c+ JOIN descendants d ON c.parent_id = d.id+ WHERE c.issue_id = @issue_id AND c.workspace_id = @workspace_id+)+SELECT id, issue_id, author_type, author_id, content, type,+ created_at, updated_at, parent_id, workspace_id,+ resolved_at, resolved_by_type, resolved_by_id+FROM descendants+ORDER BY created_at ASC, id ASC+LIMIT @row_limit;++-- name: ListRecentThreadCommentsForIssue :many+-- Returns the N most recently active threads (root + every descendant) rather+-- than the N most recent rows. A thread's "last activity" is MAX(created_at)+-- over its whole subtree; threads are ranked by (last_activity_at DESC,+-- root_id DESC) and the top N are expanded.+--+-- Why thread-grouped instead of row-recent: with row-recent the newest 20+-- comments can come from 8 different threads — the agent sees 8 unrelated+-- tails. With thread-grouped the agent sees N complete conversational arcs,+-- which matches how a human reads an issue (#2340).+--+-- Response ordering:+-- threads: (thread_last_activity_at ASC, root_id ASC)+-- in-thread: (created_at ASC, id ASC)+-- So the oldest-active thread appears first and the most recently-active+-- thread is at the tail, closest to "now" in an agent prompt.+--+-- Cursor scrolls back through threads. When @has_cursor=TRUE only threads+-- with (last_activity_at, root_id) < (@before_at, @before_id) are eligible.+-- The cursor is a THREAD cursor — both values identify a thread (its last+-- activity timestamp and its root comment id), not a single row.+--+-- The recursive `membership` CTE labels each comment with its thread root by+-- walking down from every root. It does not assume any maximum nesting depth,+-- which preserves correctness even if the schema ever allows reply-of-reply+-- (the agent path in TaskService.createAgentComment collapses to root today,+-- but the user-facing CreateComment handler does not enforce it).+WITH RECURSIVE membership(id, root_id, comment_created_at) AS (+ -- Each root maps to itself.+ SELECT c.id, c.id AS root_id, c.created_at+ FROM comment c+ WHERE c.issue_id = @issue_id+ AND c.workspace_id = @workspace_id+ AND c.parent_id IS NULL+ UNION ALL+ -- Each descendant inherits its parent's root_id.+ SELECT c.id, m.root_id, c.created_at+ FROM comment c+ JOIN membership m ON c.parent_id = m.id+ WHERE c.issue_id = @issue_id+ AND c.workspace_id = @workspace_id+),+thread_stats AS (+ SELECT root_id, MAX(comment_created_at)::timestamptz AS last_activity_at+ FROM membership+ GROUP BY root_id+),+picked AS (+ SELECT ts.root_id, ts.last_activity_at+ FROM thread_stats ts+ WHERE (+ @has_cursor::boolean = FALSE+ OR (ts.last_activity_at, ts.root_id) < (@before_at::timestamptz, @before_id::uuid)+ )+ ORDER BY ts.last_activity_at DESC, ts.root_id DESC+ LIMIT @thread_limit+)+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type,+ c.created_at, c.updated_at, c.parent_id, c.workspace_id,+ c.resolved_at, c.resolved_by_type, c.resolved_by_id,+ p.root_id AS thread_root_id,+ p.last_activity_at AS thread_last_activity_at+FROM picked p+JOIN membership m ON m.root_id = p.root_id+JOIN comment c ON c.id = m.id+ORDER BY p.last_activity_at ASC, p.root_id ASC, c.created_at ASC, c.id ASC;+-- name: CountComments :oneSELECT count(*) FROM commentWHERE issue_id = $1 AND workspace_id = $2;