Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8558: fix(sidebar): open an unread issue on its newest unread run (#9887)
Jiayuan Zhang8de3af982aff
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 53af0e1581..7f35f31e33 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -82,11 +82,14 @@ import { parseWithFallback } from "./schema";describe("IssueUnreadPageSchema", () => {const endpoint = "GET /api/issues/unread";- it("defaults a missing agent_id and next_cursor to null", () => {+ it("defaults missing run fields and next_cursor to null", () => {const parsed = parseWithFallback({items: [- { issue_id: "i-1", outcome: "completed", agent_id: "a-1", created_at: "2026-01-01T00:00:00Z" },+ {+ issue_id: "i-1", outcome: "completed", agent_id: "a-1", task_id: "t-1", comment_id: "c-1",+ created_at: "2026-01-01T00:00:00Z",+ },{ issue_id: "i-2", outcome: "manual", created_at: "2026-01-01T00:00:00Z", extra: true },],},@@ -94,9 +97,9 @@ describe("IssueUnreadPageSchema", () => {EMPTY_ISSUE_UNREAD_PAGE,{ endpoint },);- expect(parsed.items.map((u) => [u.issue_id, u.agent_id])).toEqual([- ["i-1", "a-1"],- ["i-2", null],+ expect(parsed.items.map((u) => [u.issue_id, u.agent_id, u.task_id, u.comment_id])).toEqual([+ ["i-1", "a-1", "t-1", "c-1"],+ ["i-2", null, null, null],]);expect(parsed.next_cursor).toBeNull();});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex bae7b5cdd7..e66b084a2c 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2776,6 +2776,8 @@ export const IssueUnreadPageSchema = zissue_id: z.string(),outcome: z.string(),agent_id: z.string().nullish().transform((v) => v ?? null),+ task_id: z.string().nullish().transform((v) => v ?? null),+ comment_id: z.string().nullish().transform((v) => v ?? null),created_at: z.string(),}).loose(),diff --git a/packages/core/issues/unread.test.tsx b/packages/core/issues/unread.test.tsxindex 0f9ff80bab..8d5b61f8b4 100644--- a/packages/core/issues/unread.test.tsx+++ b/packages/core/issues/unread.test.tsx@@ -8,7 +8,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { createQueryClient } from "../query-client";import { api } from "../api";import type { IssueUnread } from "../types";-import { refreshIssueUnread, useIssueUnread } from "./unread";+import { issueUnreadTarget, refreshIssueUnread, useIssueUnread } from "./unread";vi.mock("../api", () => ({ api: { listIssueUnread: vi.fn() } }));@@ -16,11 +16,22 @@ const unread: IssueUnread = {issue_id: "issue-1",outcome: "completed",agent_id: "agent-1",+ task_id: "task-1",+ comment_id: "comment-1",created_at: "2026-10-31T10:00:00Z",};afterEach(() => vi.resetAllMocks());+describe("issueUnreadTarget", () => {+ it("points at the run's last comment, else the run, and nowhere for a manual mark", () => {+ expect(issueUnreadTarget(unread)).toBe("comment-1");+ expect(issueUnreadTarget({ ...unread, comment_id: null })).toBe("task-1");+ expect(issueUnreadTarget({ ...unread, outcome: "manual", agent_id: null, task_id: null, comment_id: null })).toBeNull();+ expect(issueUnreadTarget(null)).toBeNull();+ });+});+describe("refreshIssueUnread", () => {it("is not answered by a first load that started before the change", async () => {const client = createQueryClient();diff --git a/packages/core/issues/unread.ts b/packages/core/issues/unread.tsindex 48be9f8bdc..e1794c8498 100644--- a/packages/core/issues/unread.ts+++ b/packages/core/issues/unread.ts@@ -31,6 +31,14 @@ export async function refreshIssueUnread(qc: QueryClient, wsId: string) {await qc.invalidateQueries({ queryKey });}+/**+ * The timeline item an unread mark points at: the last comment its run left,+ * or the run itself when it left none. `null` for a manual mark.+ */+export function issueUnreadTarget(unread: IssueUnread | null): string | null {+ return unread?.comment_id ?? unread?.task_id ?? null;+}+/** The viewer's unread mark on one issue, or `null` when it is read. */export function useIssueUnread(wsId: string, issueId: string): IssueUnread | null {const select = useCallback(@@ -60,7 +68,10 @@ function useSetIssueUnread(wsId: string, unread: boolean) {const has = old.some((item) => item.issue_id === issueId);if (!unread) return has ? old.filter((item) => item.issue_id !== issueId) : old;if (has) return old;- return [{ issue_id: issueId, outcome: "manual", agent_id: null, created_at: new Date().toISOString() }, ...old];+ return [{+ issue_id: issueId, outcome: "manual", agent_id: null, task_id: null, comment_id: null,+ created_at: new Date().toISOString(),+ }, ...old];});return { prev };},diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.tsindex 696c0fcfaf..7465c34465 100644--- a/packages/core/types/issue.ts+++ b/packages/core/types/issue.ts@@ -162,12 +162,16 @@ export interface IssueSourceContext {/*** An issue with an agent result the viewer has not seen yet* (`GET /api/issues/unread`). `outcome` is `completed` | `failed` for a run, or- * `manual` when the viewer marked it unread; `agent_id` is null for manual.+ * `manual` when the viewer marked it unread; `agent_id` and `task_id` are null+ * for manual. `comment_id` is the last comment that run left on the issue, null+ * when it left none.*/export interface IssueUnread {issue_id: string;outcome: string;agent_id: string | null;+ task_id: string | null;+ comment_id: string | null;created_at: string;}diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex 712c831ec6..ffdbd39a59 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -983,7 +983,7 @@ export function AgentRunComment({ run, standalone = false, commentProps, enterinreturn (<div ref={motionRef} data-run-slot-id={run.task.id}data-run-comment-id={!reply ? run.task.id : undefined}- id={!standalone && slotEntry ? `comment-${slotEntry.id}` : undefined}+ id={!standalone ? `comment-${slotEntry?.id ?? run.task.id}` : undefined}className={cn("transition-colors duration-700", standalone ? !reply && "rounded-xl border" : "border-t border-border/50", !reply && "py-1.5",highlighted ? highlightedCommentBackgroundClass : standalone && !reply && "bg-card")}>{commentProps && reply ? standalone ? (diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 5a47c0d03a..3355619689 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -2513,6 +2513,53 @@ describe("IssueDetail (shared)", () => {expect(hasHighlightedCommentBackground(reply)).toBe(false);});+ it("lands on a run that left no comment by its task id", async () => {+ const taskId = "7c1f3a9e-2b4d-4e8a-9f60-0a1b2c3d4e5f";+ const task: AgentTask = {+ id: taskId, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",+ status: "failed", priority: 0, created_at: "2026-01-18T00:00:00Z",+ started_at: "2026-01-18T00:00:01Z", dispatched_at: "2026-01-18T00:00:01Z",+ completed_at: "2026-01-18T00:05:00Z", result: null, error: "go test timed out",+ delivered_comment_ids: [],+ };+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);++ renderIssueDetailWithHighlight(taskId);++ await waitFor(() => {+ expect(hasHighlightedCommentBackground(document.getElementById(`comment-${taskId}`))).toBe(true);+ });+ });++ it.each([+ ["an open thread", "open"],+ ["a thread whose root is resolved", "root"],+ ["a thread a later reply resolved", "reply"],+ ])("unfolds and lands on a run that left no comment in %s", async (_case, fold) => {+ const taskId = "7c1f3a9e-2b4d-4e8a-9f60-0a1b2c3d4e5f";+ const root = { ...mockTimeline[0]!, id: "run-thread-root", parent_id: null,+ resolved_at: fold === "root" ? "2026-01-19T00:00:00Z" : null };+ const trigger = { ...mockTimeline[0]!, id: "run-trigger", parent_id: root.id,+ content: "Please run this check", created_at: "2026-01-18T00:00:00Z" };+ const resolution = { ...trigger, id: "run-resolution", content: "Resolved",+ resolved_at: "2026-01-19T00:00:00Z", created_at: "2026-01-19T00:00:00Z" };+ const task: AgentTask = {+ id: taskId, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",+ status: "failed", priority: 0, created_at: "2026-01-18T00:00:00Z",+ started_at: "2026-01-18T00:00:01Z", dispatched_at: "2026-01-18T00:00:01Z",+ completed_at: "2026-01-18T00:05:00Z", result: null, error: "go test timed out",+ trigger_comment_id: trigger.id, delivered_comment_ids: [trigger.id],+ };+ mockApiObj.listTimeline.mockResolvedValue([root, trigger, ...(fold === "reply" ? [resolution] : [])]);+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);++ renderIssueDetailWithHighlight(taskId);++ await waitFor(() => {+ expect(hasHighlightedCommentBackground(document.getElementById(`comment-${taskId}`))).toBe(true);+ });+ });+it("still scrolls when the timeline is ready before the issue (regression for inbox click)", async () => {// Reproduces the inbox-click race: timeline data is in the cache// before the issue resolves. While loading is true, IssueDetaildiff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex f4c8e84302..dbf2a1f316 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -1826,16 +1826,29 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trreturn map;}, [timelineView.threadReplies]);+ // Thread root of a deep-link target. A run that left no comment is addressed+ // by its task id and sits in a slot inside the thread it answers, so it+ // unfolds and scrolls with that thread exactly like a reply does.+ const highlightRootId = useMemo(() => {+ if (!highlightCommentId) return undefined;+ const replyRoot = replyToRoot.get(highlightCommentId);+ if (replyRoot) return replyRoot;+ for (const [rootId, runs] of commentRuns) {+ if (runs.some((run) => run.task.id === highlightCommentId)) return rootId;+ }+ return undefined;+ }, [highlightCommentId, replyToRoot, commentRuns]);+// Deep-link target index in the flat items array. For root comments this is- // a direct findIndex hit; for reply ids we look up the enclosing root.+ // a direct findIndex hit; for replies and threaded runs we look up the+ // enclosing root.const targetIdx = useMemo(() => {if (!highlightCommentId) return -1;const direct = items.findIndex((it) => it.id === highlightCommentId);if (direct >= 0) return direct;- const rootId = replyToRoot.get(highlightCommentId);- if (!rootId) return -1;- return items.findIndex((it) => it.id === rootId);- }, [items, highlightCommentId, replyToRoot]);+ if (!highlightRootId) return -1;+ return items.findIndex((it) => it.id === highlightRootId);+ }, [items, highlightCommentId, highlightRootId]);// One entry per comment thread (folded resolved bars included), activity// groups skipped. Derived from the same flat `items` array Virtuoso renders@@ -2267,9 +2280,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// virtualization), so every comment id is in the DOM by the time this// effect runs after commit.//- // For a reply inside a folded resolved thread, the reply is not in items- // (only the resolved-bar root is). Auto-expand the thread first; the- // effect re-runs once items re-flatten.+ // For a reply or threaded run inside a folded resolved thread, the target+ // is not in items (only the resolved-bar root is). Auto-expand the thread+ // first; the effect re-runs once items re-flatten.//// `scrollContainerEl` is in deps because the component early-returns a// loading skeleton while the issue query is pending. The scroll-container@@ -2294,7 +2307,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trreturn;}- const rootId = replyToRoot.get(highlightCommentId);+ const rootId = highlightRootId;if (rootId && rootId !== highlightCommentId) {// Root resolved → the whole thread is a folded bar.const rootItem = items[targetIdx];@@ -2373,7 +2386,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trcancelAnimationFrame(rafId);clearTimeout(fade);};- }, [highlightCommentId, highlightRequestToken, id, writeViewState, items, targetIdx, scrollContainerEl, replyToRoot, expandedResolved, timelineView, toggleResolvedExpand]);+ }, [highlightCommentId, highlightRequestToken, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand]);const descEditorRef = useRef<ContentEditorRef>(null);const descriptionEditingRef = useRef(false);@@ -3087,11 +3100,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// Shared row renderer for both timeline render modes (flat / virtualized).// The wrapper `id="comment-..."` is the deep-link target — equivalent to- // a native `<a href="#comment-...">` anchor.+ // a native `<a href="#comment-...">` anchor. A run that left no comment is+ // addressed by its task id, which the sidebar's unread link lands on.const renderItem = (_i: number, item: TimelineItem): React.ReactElement => {if (item.kind === "run") {const reply = item.entry;- return <div className="pb-3" id={reply ? `comment-${reply.id}` : undefined}>+ return <div className="pb-3" id={`comment-${item.id}`}>{reply?.resolved_at && !expandedResolved.has(reply.id) ? <ResolvedThreadBarentry={reply} replies={timelineView.threadReplies.get(reply.id) ?? EMPTY_REPLIES}onExpand={() => toggleResolvedExpand(reply.id, true)} /> : <AgentRunComment run={item.run} entering={enteringRunIds.has(item.run.task.id)} standalonediff --git a/packages/views/issues/hooks/use-mark-issue-read-while-viewing.test.tsx b/packages/views/issues/hooks/use-mark-issue-read-while-viewing.test.tsxindex 5d7448370a..222a13f940 100644--- a/packages/views/issues/hooks/use-mark-issue-read-while-viewing.test.tsx+++ b/packages/views/issues/hooks/use-mark-issue-read-while-viewing.test.tsx@@ -15,6 +15,8 @@ const completed: IssueUnread = {issue_id: "issue-1",outcome: "completed",agent_id: "agent-1",+ task_id: "task-1",+ comment_id: "comment-1",created_at: "2026-10-31T10:00:00Z",};diff --git a/packages/views/layout/panels/pinned-section.tsx b/packages/views/layout/panels/pinned-section.tsxindex 25b2f1180e..b360a54182 100644--- a/packages/views/layout/panels/pinned-section.tsx+++ b/packages/views/layout/panels/pinned-section.tsx@@ -38,6 +38,7 @@ import {SIDEBAR_SHIMMER_CLASS,SidebarIssueStatus,issueRowMenuOpenClass,+ unreadIssueHref,useIssueAgentState,} from "./sidebar-tree";@@ -341,7 +342,7 @@ function PinRow({return (<SortablePinItempin={pin}- href={href}+ href={unreadIssueHref(href, unread)}onUnpin={onUnpin}label={issue.title}active={active}diff --git a/packages/views/layout/panels/sidebar-tree.test.tsx b/packages/views/layout/panels/sidebar-tree.test.tsxindex e950e0731c..7924fa932f 100644--- a/packages/views/layout/panels/sidebar-tree.test.tsx+++ b/packages/views/layout/panels/sidebar-tree.test.tsx@@ -5,7 +5,8 @@ import { describe, expect, it, vi } from "vitest";import { agentTaskSnapshotOptions } from "@multica/core/agents";import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";import { issueKeys } from "@multica/core/issues/queries";-import type { AgentTask, Issue, ListIssuesParams } from "@multica/core/types";+import { issueUnreadOptions } from "@multica/core/issues/unread";+import type { AgentTask, Issue, IssueUnread, ListIssuesParams } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";import { IssueContextMenuProvider } from "../../issues/actions";import { SidebarIssueList } from "./sidebar-tree";@@ -57,6 +58,9 @@ vi.mock("../../navigation", () => ({),}));vi.mock("../../issues/components/status-icon", () => ({ StatusIcon: () => <span /> }));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: () => "Lambda" }),+}));vi.mock("../../agents/components/agent-avatar-stack", () => ({AgentAvatarStack: ({ agentIds }: { agentIds: string[] }) => <span data-testid="agents">{agentIds.join(",")}</span>,}));@@ -74,11 +78,13 @@ function renderList({total = 18,params = PARAMS,tasks = [],+ unread = [],onCollapse = vi.fn(),}: {total?: number;params?: ListIssuesParams | null;tasks?: Partial<AgentTask>[];+ unread?: IssueUnread[];onCollapse?: () => void;} = {}) {const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });@@ -87,6 +93,7 @@ function renderList({qc.setQueryData(issueKeys.sidebar("ws-1", SOURCE, PARAMS, limit), { issues: all.slice(0, limit), total });}qc.setQueryData(agentTaskSnapshotOptions("ws-1").queryKey, tasks as AgentTask[]);+ qc.setQueryData(issueUnreadOptions("ws-1").queryKey, unread);renderWithI18n(<QueryClientProvider client={qc}><IssueContextMenuProvider variant="sidebar">@@ -107,6 +114,24 @@ function renderList({const rows = () => screen.getAllByRole("link");describe("SidebarIssueList", () => {+ it("opens an unread issue on what its run left", () => {+ const run = { outcome: "completed", agent_id: "agent-1", created_at: "2026-11-03T10:00:00Z" };+ renderList({+ unread: [+ { ...run, issue_id: "issue-1", task_id: "task-1", comment_id: "comment-1" },+ { ...run, issue_id: "issue-3", outcome: "failed", task_id: "task-3", comment_id: null },+ { ...run, issue_id: "issue-4", outcome: "manual", agent_id: null, task_id: null, comment_id: null },+ ],+ });+ expect(rows().map((row) => row.getAttribute("href"))).toEqual([+ "/acme/issues/issue-1#comment-comment-1",+ "/acme/issues/issue-2",+ "/acme/issues/issue-3#comment-task-3",+ "/acme/issues/issue-4",+ "/acme/issues/issue-5",+ ]);+ });+it("loads more in steps, then shows less", () => {renderList();expect(rows()).toHaveLength(5);diff --git a/packages/views/layout/panels/sidebar-tree.tsx b/packages/views/layout/panels/sidebar-tree.tsxindex 754bfeec24..4827bce8d6 100644--- a/packages/views/layout/panels/sidebar-tree.tsx+++ b/packages/views/layout/panels/sidebar-tree.tsx@@ -12,7 +12,7 @@ import { issueStatusCategory } from "@multica/core/issues";import { issueDetailOptions, sidebarIssuesOptions } from "@multica/core/issues/queries";import { SIDEBAR_FIRST_PAGE, SIDEBAR_PAGE_STEP, type SidebarIssuesRequest } from "@multica/core/issues/sidebar-list";import { useSidebarKeptStore } from "@multica/core/issues/stores/sidebar-kept-store";-import { useIssueUnread } from "@multica/core/issues/unread";+import { issueUnreadTarget, useIssueUnread } from "@multica/core/issues/unread";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";import type { AgentTask, Issue, IssueUnread, ListIssuesParams } from "@multica/core/types";@@ -409,6 +409,12 @@ function SidebarStatusPicker({);}+/** An unread issue opens on what its run left instead of at the top. */+export function unreadIssueHref(href: string, unread: IssueUnread | null): string {+ const target = issueUnreadTarget(unread);+ return target ? `${href}#comment-${target}` : href;+}+/** An agent result the viewer has not seen yet. It takes the avatar's place* once the run ends, so the two never show together. */export function IssueUnreadDot({ unread }: { unread: IssueUnread }) {@@ -470,7 +476,7 @@ const SidebarIssueRow = memo(function SidebarIssueRow({className="size-3"/><AppLink- href={href}+ href={unreadIssueHref(href, unread)}newTabTitle={issue.title}aria-current={active ? "page" : undefined}onKeyDown={onKeyDown}diff --git a/server/internal/handler/issue_unread.go b/server/internal/handler/issue_unread.goindex 45ce2be3cd..920c2c51f7 100644--- a/server/internal/handler/issue_unread.go+++ b/server/internal/handler/issue_unread.go@@ -10,11 +10,14 @@ import (// IssueUnreadResponse is an issue with an agent result the caller has not seen// yet. outcome is completed | failed, or manual when the caller marked it-// unread themselves; agent_id is null for manual.+// unread themselves; agent_id and task_id are null for manual. comment_id is+// the last comment that run left on the issue, null when it left none.type IssueUnreadResponse struct {IssueID string `json:"issue_id"`Outcome string `json:"outcome"`AgentID *string `json:"agent_id"`+ TaskID *string `json:"task_id"`+ CommentID *string `json:"comment_id"`CreatedAt string `json:"created_at"`}@@ -64,6 +67,8 @@ func (h *Handler) ListIssueUnread(w http.ResponseWriter, r *http.Request) {IssueID: uuidToString(row.IssueID),Outcome: row.Outcome,AgentID: uuidToPtr(row.AgentID),+ TaskID: uuidToPtr(row.TaskID),+ CommentID: uuidToPtr(row.CommentID),CreatedAt: timestampToString(row.CreatedAt),}}diff --git a/server/internal/handler/issue_unread_test.go b/server/internal/handler/issue_unread_test.goindex 3e69b664bf..a09a10a20c 100644--- a/server/internal/handler/issue_unread_test.go+++ b/server/internal/handler/issue_unread_test.go@@ -1,10 +1,12 @@package handlerimport (+ "fmt""net/http""net/url""testing"+ "github.com/google/uuid""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -51,7 +53,8 @@ func TestIssueUnreadMarkAndClear(t *testing.T) {setIssueUnreadAs(t, testUserID, issueID, true).Want(http.StatusOK)setIssueUnreadAs(t, testUserID, issueID, true).Want(http.StatusOK)items := listIssueUnreadAs(t, testUserID)- if len(items) != 1 || items[0].IssueID != issueID || items[0].Outcome != "manual" || items[0].AgentID != nil {+ if len(items) != 1 || items[0].IssueID != issueID || items[0].Outcome != "manual" || items[0].AgentID != nil ||+ items[0].TaskID != nil || items[0].CommentID != nil {t.Fatalf("want one manual unread row for the issue, got %+v", items)}@@ -62,6 +65,41 @@ func TestIssueUnreadMarkAndClear(t *testing.T) {}}+func TestIssueUnreadPointsAtTheRunsLastComment(t *testing.T) {+ userID := dbfx.User(t, "Unread Landing", "[email protected]")+ dbfx.Member(t, testWorkspaceID, userID, "member")+ dbfx.Cleanup(t, `DELETE FROM issue_unread WHERE user_id = $1`, userID)+ withComments := dbfx.Issue(t, "unread run with comments")+ silent := dbfx.Issue(t, "unread run without comments")+ elsewhere := dbfx.Issue(t, "issue the run also commented on")+ runID, silentRunID := uuid.NewString(), uuid.NewString()++ at := func(minutesAgo int) testutil.Raw {+ return testutil.Raw(fmt.Sprintf("now() - interval '%d minutes'", minutesAgo))+ }+ dbfx.Comment(t, withComments, "progress", testutil.Cols{"source_task_id": runID, "created_at": at(5)})+ result := dbfx.Comment(t, withComments, "result", testutil.Cols{"source_task_id": runID, "created_at": at(4)})+ dbfx.Comment(t, withComments, "deleted", testutil.Cols{"source_task_id": runID, "created_at": at(3), "deleted_at": at(2)})+ dbfx.Comment(t, withComments, "someone else", testutil.Cols{"created_at": at(2)})+ dbfx.Comment(t, elsewhere, "same run, other issue", testutil.Cols{"source_task_id": runID, "created_at": at(1)})++ dbfx.Exec(t, `+INSERT INTO issue_unread (workspace_id, user_id, issue_id, outcome, task_id)+VALUES ($1, $2, $3, 'completed', $4), ($1, $2, $5, 'failed', $6)`,+ testWorkspaceID, userID, withComments, runID, silent, silentRunID)++ byIssue := map[string]IssueUnreadResponse{}+ for _, item := range listIssueUnreadAs(t, userID) {+ byIssue[item.IssueID] = item+ }+ if got := byIssue[withComments]; got.TaskID == nil || *got.TaskID != runID || got.CommentID == nil || *got.CommentID != result {+ t.Fatalf("want the run's last live comment on this issue %s, got %+v", result, got)+ }+ if got := byIssue[silent]; got.TaskID == nil || *got.TaskID != silentRunID || got.CommentID != nil {+ t.Fatalf("want the run id and no comment for a run that left none, got %+v", got)+ }+}+func TestIssueUnreadIsPerUser(t *testing.T) {issueID := dbfx.Issue(t, "issue unread per user")dbfx.Cleanup(t, `DELETE FROM issue_unread WHERE issue_id = $1`, issueID)diff --git a/server/pkg/db/generated/issue_unread.sql.go b/server/pkg/db/generated/issue_unread.sql.goindex c7938c10bf..5e7abf1c95 100644--- a/server/pkg/db/generated/issue_unread.sql.go+++ b/server/pkg/db/generated/issue_unread.sql.go@@ -12,15 +12,24 @@ import ()const listIssueUnread = `-- name: ListIssueUnread :many-SELECT issue_id, outcome, agent_id, created_at-FROM issue_unread-WHERE workspace_id = $1- AND user_id = $2+SELECT u.issue_id, u.outcome, u.agent_id, u.task_id, u.created_at, run_comment.id AS comment_id+FROM issue_unread u+LEFT JOIN LATERAL (+ SELECT c.id+ FROM comment c+ WHERE c.issue_id = u.issue_id+ AND c.source_task_id = u.task_id+ AND c.deleted_at IS NULL+ ORDER BY c.created_at DESC, c.id DESC+ LIMIT 1+) run_comment ON true+WHERE u.workspace_id = $1+ AND u.user_id = $2AND ($3::timestamptz IS NULL- OR (created_at, issue_id) < ($3::timestamptz, $4::uuid)+ OR (u.created_at, u.issue_id) < ($3::timestamptz, $4::uuid))-ORDER BY created_at DESC, issue_id DESC+ORDER BY u.created_at DESC, u.issue_id DESCLIMIT $5`@@ -36,12 +45,17 @@ type ListIssueUnreadRow struct {IssueID pgtype.UUID `json:"issue_id"`Outcome string `json:"outcome"`AgentID pgtype.UUID `json:"agent_id"`+ TaskID pgtype.UUID `json:"task_id"`CreatedAt pgtype.Timestamptz `json:"created_at"`+ CommentID pgtype.UUID `json:"comment_id"`}// One page of the caller's unread issues in one workspace, newest first. Pages// continue strictly after the (created_at, issue_id) of the previous page's// last row, so every row is reachable however many there are.+// comment_id is the last live comment the unread run posted on this issue: where+// opening the issue from the sidebar lands. The run just ended, so its comment+// is among the issue's newest and the newest-first timeline index finds it fast.func (q *Queries) ListIssueUnread(ctx context.Context, arg ListIssueUnreadParams) ([]ListIssueUnreadRow, error) {rows, err := q.db.Query(ctx, listIssueUnread,arg.WorkspaceID,@@ -61,7 +75,9 @@ func (q *Queries) ListIssueUnread(ctx context.Context, arg ListIssueUnreadParams&i.IssueID,&i.Outcome,&i.AgentID,+ &i.TaskID,&i.CreatedAt,+ &i.CommentID,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/issue_unread.sql b/server/pkg/db/queries/issue_unread.sqlindex 1154537d86..2e0da2b504 100644--- a/server/pkg/db/queries/issue_unread.sql+++ b/server/pkg/db/queries/issue_unread.sql@@ -24,15 +24,27 @@ RETURNING workspace_id, user_id;-- One page of the caller's unread issues in one workspace, newest first. Pages-- continue strictly after the (created_at, issue_id) of the previous page's-- last row, so every row is reachable however many there are.-SELECT issue_id, outcome, agent_id, created_at-FROM issue_unread-WHERE workspace_id = sqlc.arg(workspace_id)- AND user_id = sqlc.arg(user_id)+-- comment_id is the last live comment the unread run posted on this issue: where+-- opening the issue from the sidebar lands. The run just ended, so its comment+-- is among the issue's newest and the newest-first timeline index finds it fast.+SELECT u.issue_id, u.outcome, u.agent_id, u.task_id, u.created_at, run_comment.id AS comment_id+FROM issue_unread u+LEFT JOIN LATERAL (+ SELECT c.id+ FROM comment c+ WHERE c.issue_id = u.issue_id+ AND c.source_task_id = u.task_id+ AND c.deleted_at IS NULL+ ORDER BY c.created_at DESC, c.id DESC+ LIMIT 1+) run_comment ON true+WHERE u.workspace_id = sqlc.arg(workspace_id)+ AND u.user_id = sqlc.arg(user_id)AND (sqlc.narg(before_created_at)::timestamptz IS NULL- OR (created_at, issue_id) < (sqlc.narg(before_created_at)::timestamptz, sqlc.narg(before_issue_id)::uuid)+ OR (u.created_at, u.issue_id) < (sqlc.narg(before_created_at)::timestamptz, sqlc.narg(before_issue_id)::uuid))-ORDER BY created_at DESC, issue_id DESC+ORDER BY u.created_at DESC, u.issue_id DESCLIMIT sqlc.arg(page_limit);-- name: MarkIssueRead :execrows