Skip to content

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

Go

MUL-8438 feat(sidebar): unread dot for finished agent runs (#9759)

Jiayuan Zhang79568902d845
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index b202332fd3..9a8353ca53 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -55,6 +55,7 @@ import type {
InboxItem,
InboxWorkspaceUnread,
IssueSubscriber,
+ IssueUnread,
Comment,
CommentTriggerPreview,
IssueTriggerPreview,
@@ -408,6 +409,8 @@ import {
EMPTY_CREATE_FEEDBACK_RESPONSE,
InboxUnreadSummarySchema,
EMPTY_INBOX_UNREAD_SUMMARY,
+ IssueUnreadPageSchema,
+ EMPTY_ISSUE_UNREAD_PAGE,
InboxItemListSchema,
ArchivedInboxPageSchema,
ArchivedInboxFacetsSchema,
@@ -2913,6 +2916,30 @@ export class ApiClient {
return task;
}
+ /** Every unread mark, across all pages: a row missing here reads as "read". */
+ async listIssueUnread(): Promise<IssueUnread[]> {
+ const items: IssueUnread[] = [];
+ let cursor: string | null = null;
+ do {
+ const query: string = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
+ const raw = await this.fetch<unknown>(`/api/issues/unread${query}`);
+ const page = parseWithFallback(raw, IssueUnreadPageSchema, EMPTY_ISSUE_UNREAD_PAGE, {
+ endpoint: "GET /api/issues/unread",
+ });
+ items.push(...page.items);
+ cursor = page.next_cursor === cursor ? null : page.next_cursor;
+ } while (cursor);
+ return items;
+ }
+
+ async markIssueRead(issueId: string): Promise<void> {
+ await this.fetch(`/api/issues/${issueId}/read`, { method: "POST" });
+ }
+
+ async markIssueUnread(issueId: string): Promise<void> {
+ await this.fetch(`/api/issues/${issueId}/unread`, { method: "POST" });
+ }
+
// Inbox
async listInbox(): Promise<InboxItem[]> {
const raw = await this.fetch<unknown>("/api/inbox");
diff --git a/packages/core/api/issue-unread.test.ts b/packages/core/api/issue-unread.test.ts
new file mode 100644
index 0000000000..341fd2de07
--- /dev/null
+++ b/packages/core/api/issue-unread.test.ts
@@ -0,0 +1,36 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ApiClient } from "./client";
+
+afterEach(() => vi.unstubAllGlobals());
+
+const mark = (issueId: string) => ({
+ issue_id: issueId,
+ outcome: "completed",
+ agent_id: "agent-1",
+ created_at: "2026-10-31T10:00:00Z",
+});
+
+describe("listIssueUnread", () => {
+ it("follows next_cursor until the last page", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(Response.json({ items: [mark("i-1"), mark("i-2")], next_cursor: "c 1|x" }))
+ .mockResolvedValueOnce(Response.json({ items: [mark("i-3")], next_cursor: null }));
+ vi.stubGlobal("fetch", fetch);
+
+ const items = await new ApiClient("https://api.example.test").listIssueUnread();
+
+ expect(items.map((item) => item.issue_id)).toEqual(["i-1", "i-2", "i-3"]);
+ expect(fetch.mock.calls.map(([url]) => new URL(url).searchParams.get("cursor"))).toEqual([null, "c 1|x"]);
+ });
+
+ it("stops when a page repeats the cursor it was asked for", async () => {
+ const fetch = vi.fn().mockImplementation(async () => Response.json({ items: [], next_cursor: "same" }));
+ vi.stubGlobal("fetch", fetch);
+
+ await new ApiClient("https://api.example.test").listIssueUnread();
+
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index ae8aa624a4..c57de7d3e6 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -74,8 +74,41 @@ import {
EMPTY_LIST_ISSUE_STATUSES_RESPONSE,
EMPTY_ISSUE_STATUS_ENTRY,
} from "./schemas";
+import { IssueUnreadPageSchema, EMPTY_ISSUE_UNREAD_PAGE } from "./schemas";
import { parseWithFallback } from "./schema";
+describe("IssueUnreadPageSchema", () => {
+ const endpoint = "GET /api/issues/unread";
+
+ it("defaults a missing agent_id 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-2", outcome: "manual", created_at: "2026-01-01T00:00:00Z", extra: true },
+ ],
+ },
+ 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.next_cursor).toBeNull();
+ });
+
+ it("falls back to an empty last page for a malformed body", () => {
+ expect(parseWithFallback({ items: "nope" }, IssueUnreadPageSchema, EMPTY_ISSUE_UNREAD_PAGE, { endpoint })).toEqual(
+ EMPTY_ISSUE_UNREAD_PAGE,
+ );
+ expect(parseWithFallback(null, IssueUnreadPageSchema, EMPTY_ISSUE_UNREAD_PAGE, { endpoint })).toEqual(
+ EMPTY_ISSUE_UNREAD_PAGE,
+ );
+ });
+});
+
const baseIssue = {
id: "11111111-1111-1111-1111-111111111111",
workspace_id: "ws-1",
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index eab96a1a32..1d5f357beb 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -55,6 +55,7 @@ import type {
IssuePullRequestsResponse,
InboxItem,
InboxWorkspaceUnread,
+ IssueUnread,
Label,
MemberWithUser,
IssueProperty,
@@ -2760,6 +2761,31 @@ export const InboxUnreadSummarySchema = z.array(
export const EMPTY_INBOX_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];
+// The viewer's unread issues (`/api/issues/unread` GET), behind the sidebar's
+// unread dot. `outcome` stays a string so a future kind still lights the dot;
+// on malformed JSON parseWithFallback returns the empty list, which hides it.
+
+export const IssueUnreadPageSchema = z
+ .object({
+ items: z.array(
+ z
+ .object({
+ issue_id: z.string(),
+ outcome: z.string(),
+ agent_id: z.string().nullish().transform((v) => v ?? null),
+ created_at: z.string(),
+ })
+ .loose(),
+ ),
+ next_cursor: z.string().nullish().transform((v) => v ?? null),
+ })
+ .loose();
+
+export const EMPTY_ISSUE_UNREAD_PAGE: { items: IssueUnread[]; next_cursor: string | null } = {
+ items: [],
+ next_cursor: null,
+};
+
// Inbox items (`/api/inbox` and `/api/inbox/archived` GET).
// Lenient per the usual rules: `severity` / `type` / `recipient_type` stay
// `z.string()` so a notification kind this client doesn't know yet still
diff --git a/packages/core/issues/unread.test.tsx b/packages/core/issues/unread.test.tsx
new file mode 100644
index 0000000000..0f9ff80bab
--- /dev/null
+++ b/packages/core/issues/unread.test.tsx
@@ -0,0 +1,46 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+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";
+
+vi.mock("../api", () => ({ api: { listIssueUnread: vi.fn() } }));
+
+const unread: IssueUnread = {
+ issue_id: "issue-1",
+ outcome: "completed",
+ agent_id: "agent-1",
+ created_at: "2026-10-31T10:00:00Z",
+};
+
+afterEach(() => vi.resetAllMocks());
+
+describe("refreshIssueUnread", () => {
+ it("is not answered by a first load that started before the change", async () => {
+ const client = createQueryClient();
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ let resolveInitial!: (items: IssueUnread[]) => void;
+ vi.mocked(api.listIssueUnread)
+ .mockImplementationOnce(() => new Promise((resolve) => (resolveInitial = resolve)))
+ .mockResolvedValue([unread]);
+
+ const { result } = renderHook(() => useIssueUnread("ws-1", "issue-1"), { wrapper });
+ await waitFor(() => expect(api.listIssueUnread).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ const refreshed = refreshIssueUnread(client, "ws-1");
+ resolveInitial([]);
+ await refreshed;
+ });
+
+ await waitFor(() => expect(result.current).toEqual(unread));
+ client.clear();
+ });
+});
diff --git a/packages/core/issues/unread.ts b/packages/core/issues/unread.ts
new file mode 100644
index 0000000000..48be9f8bdc
--- /dev/null
+++ b/packages/core/issues/unread.ts
@@ -0,0 +1,82 @@
+import { useCallback } from "react";
+import { queryOptions, useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import type { IssueUnread } from "../types";
+
+/**
+ * The viewer's issues with an agent result they have not seen yet. Kept outside
+ * `issueKeys` so the broad issue invalidations do not refetch it; it changes
+ * only on the viewer's own `issue_unread:changed` events and writes.
+ */
+export const issueUnreadKeys = {
+ all: (wsId: string) => ["issue-unread", wsId] as const,
+};
+
+export function issueUnreadOptions(wsId: string) {
+ return queryOptions({
+ queryKey: issueUnreadKeys.all(wsId),
+ queryFn: () => api.listIssueUnread(),
+ });
+}
+
+/**
+ * Re-reads the unread list after a server-side change. Cancels first: an
+ * invalidation during the list's first load is otherwise answered by the
+ * request already on the wire, which predates the change, and with
+ * `staleTime: Infinity` nothing asks again (see `refreshInboxQuery`).
+ */
+export async function refreshIssueUnread(qc: QueryClient, wsId: string) {
+ const queryKey = issueUnreadKeys.all(wsId);
+ await qc.cancelQueries({ queryKey });
+ await qc.invalidateQueries({ queryKey });
+}
+
+/** 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(
+ (items: IssueUnread[]) => items.find((item) => item.issue_id === issueId) ?? null,
+ [issueId],
+ );
+ const { data = null } = useQuery({ ...issueUnreadOptions(wsId), select, enabled: !!issueId });
+ return data;
+}
+
+function useSetIssueUnread(wsId: string, unread: boolean) {
+ const qc = useQueryClient();
+ const key = issueUnreadKeys.all(wsId);
+ return useMutation({
+ mutationFn: (issueId: string) => (unread ? api.markIssueUnread(issueId) : api.markIssueRead(issueId)),
+ // Both writes are idempotent. A 4xx will not change on retry.
+ retry: (failures, err) => {
+ const status = (err as { status?: number }).status;
+ return failures < 2 && (status === undefined || status >= 500);
+ },
+ retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 8000),
+ onMutate: async (issueId) => {
+ await qc.cancelQueries({ queryKey: key });
+ const prev = qc.getQueryData<IssueUnread[]>(key);
+ qc.setQueryData<IssueUnread[]>(key, (old) => {
+ if (!old) return old;
+ 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 { prev };
+ },
+ onError: (_err, _issueId, ctx) => {
+ if (ctx?.prev) qc.setQueryData(key, ctx.prev);
+ },
+ onSettled: () => {
+ void qc.invalidateQueries({ queryKey: key });
+ },
+ });
+}
+
+export function useMarkIssueRead(wsId: string) {
+ return useSetIssueUnread(wsId, false);
+}
+
+export function useMarkIssueUnread(wsId: string) {
+ return useSetIssueUnread(wsId, true);
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 7c3f2edece..3a74a37668 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -48,6 +48,7 @@
"./issues/comment-deletion": "./issues/comment-deletion.ts",
"./issues/comment-trigger-outcomes": "./issues/comment-trigger-outcomes.ts",
"./issues/run-steering": "./issues/run-steering.ts",
+ "./issues/unread": "./issues/unread.ts",
"./issues/date": "./issues/date.ts",
"./issues/ws-updaters": "./issues/ws-updaters.ts",
"./issues/sidebar-list": "./issues/sidebar-list.ts",
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 49eda9834a..b2ab463a73 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -133,12 +133,13 @@ describe("useRealtimeSync — ws instance change", () => {
// (19 workspace-scoped [incl. property definitions, workflows, saved views
// and view preferences] + 6 per-issue prefixes + the workspace
// working-agents projection + 5 per-chat prefixes + 1 workspaceKeys.list()
- // + 1 cross-workspace inbox unread summary = 34 calls).
+ // + 1 cross-workspace inbox unread summary + 1 issue unread marks = 35
+ // calls).
//
// Awaited rather than counted synchronously: the inbox unread summary
// refresh cancels any in-flight request before invalidating (see
// onInboxSummaryInvalidate), so that one lands after the synchronous ones.
- await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(34));
+ await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(35));
});
it("does not re-invalidate when rerendered with the same ws instance", () => {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index b4cebc61dc..0e7ad896f5 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -12,6 +12,7 @@ import { defaultStorage } from "../platform/storage";
import { getCurrentWsId, getCurrentSlug } from "../platform/workspace-storage";
import { issueKeys } from "../issues/queries";
import { isSidebarTableRequest, type SidebarIssuesRequest } from "../issues/sidebar-list";
+import { refreshIssueUnread } from "../issues/unread";
import { projectKeys } from "../projects/queries";
import { pinKeys } from "../pins/queries";
import { autopilotKeys } from "../autopilots/queries";
@@ -88,6 +89,7 @@ import type {
IssueDeletedPayload,
IssueAttachmentsChangedPayload,
IssueLabelsChangedPayload,
+ IssueUnreadChangedPayload,
IssueMetadataChangedPayload,
IssuePropertiesChangedPayload,
InboxNewPayload,
@@ -649,6 +651,7 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {
const wsId = getCurrentWsId();
if (wsId) {
qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
+ void refreshIssueUnread(qc, wsId);
// Through the inbox's own entry point, not a plain invalidate: a reconnect
// can land during the list's first load, and a plain invalidate would be
// answered by the request already on the wire (see refreshInboxQuery).
@@ -1075,7 +1078,7 @@ export function useRealtimeSync(
// Event types handled by specific handlers below -- skip generic refresh
const specificEvents = new Set([
"workspace:updated",
- "issue:updated", "issue:created", "issue:deleted", "issue_attachments:changed", "issue_labels:changed", "issue_metadata:changed", "issue_properties:changed", "property:created", "property:updated", "inbox:new",
+ "issue:updated", "issue:created", "issue:deleted", "issue_attachments:changed", "issue_labels:changed", "issue_unread:changed", "issue_metadata:changed", "issue_properties:changed", "property:created", "property:updated", "inbox:new",
"comment:created", "comment:updated", "comment:deleted",
"comment:resolved", "comment:unresolved",
"activity:created",
@@ -1162,6 +1165,12 @@ export function useRealtimeSync(
if (wsId) onIssueLabelsChanged(qc, wsId, issue_id, labels ?? [], issue_revision);
});
+ // Personal; may belong to a workspace other than the open one.
+ const unsubIssueUnreadChanged = ws.on("issue_unread:changed", (p) => {
+ const { workspace_id } = p as IssueUnreadChangedPayload;
+ if (workspace_id) void refreshIssueUnread(qc, workspace_id);
+ });
+
const unsubIssueAttachmentsChanged = ws.on("issue_attachments:changed", (p) => {
const { issue_id, issue_revision } = p as IssueAttachmentsChangedPayload;
if (!issue_id) return;
@@ -1856,6 +1865,7 @@ export function useRealtimeSync(
unsubIssueDeleted();
unsubIssueAttachmentsChanged();
unsubIssueLabelsChanged();
+ unsubIssueUnreadChanged();
unsubIssueMetadataChanged();
unsubIssuePropertiesChanged();
unsubPropertyChanged.forEach((unsub) => unsub());
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index a6f7c1f087..c86a40912b 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -75,6 +75,7 @@ export type WSEventType =
| "label:updated"
| "label:deleted"
| "issue_labels:changed"
+ | "issue_unread:changed"
| "issue_metadata:changed"
| "issue_properties:changed"
| "property:created"
@@ -235,6 +236,15 @@ export interface InboxUnarchivedPayload {
recipient_id: string;
}
+/** Personal: the recipient's unread mark on an issue changed. Workspace-tagged
+ * because personal events reach every connection the user has. */
+export interface IssueUnreadChangedPayload {
+ workspace_id: string;
+ recipient_id: string;
+ issue_id: string;
+ unread: boolean;
+}
+
export interface InboxBatchReadPayload {
recipient_id: string;
count: number;
@@ -608,6 +618,7 @@ export interface WSEventPayloadMap {
"issue:deleted": IssueDeletedPayload;
"issue_attachments:changed": IssueAttachmentsChangedPayload;
"issue_labels:changed": IssueLabelsChangedPayload;
+ "issue_unread:changed": IssueUnreadChangedPayload;
"issue_properties:changed": IssuePropertiesChangedPayload;
"property:created": PropertyChangedPayload;
"property:updated": PropertyChangedPayload;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index faa956c9c2..e89c4aabbd 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -1,5 +1,6 @@
export type { Issue, IssueStatus, BuiltInIssueStatus, IssuePriority, IssueAssigneeType, IssueMetadata, IssueMetadataValue, IssueReaction, SourceContextAttachment, SourceContextAuthor, SourceContextIssueSnapshot, SourceContextCommentSnapshot, SourceContextSnapshot, SourceContextLimitUsage, SourceContextPreview, SourceContextAuthorState, IssueSourceContext,
IssueDuplicateOf,
+ IssueUnread,
} from "./issue";
export type {
IssueStatusCategory,
diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.ts
index dfe71f30ea..696c0fcfaf 100644
--- a/packages/core/types/issue.ts
+++ b/packages/core/types/issue.ts
@@ -159,6 +159,18 @@ export interface IssueSourceContext {
snapshot: SourceContextSnapshot;
}
+/**
+ * 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.
+ */
+export interface IssueUnread {
+ issue_id: string;
+ outcome: string;
+ agent_id: string | null;
+ created_at: string;
+}
+
/** The original a duplicate points at: enough to link it and show its status. */
export interface IssueDuplicateOf {
id: string;
diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
index 65dd233464..6f1dd7cbd2 100644
--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
@@ -132,6 +132,9 @@ const { apiMocks, copyTextMock } = vi.hoisted(() => ({
listIssueWorkflows: vi.fn(),
listProjects: vi.fn(),
getAgentTaskSnapshot: vi.fn(),
+ listIssueUnread: vi.fn(),
+ markIssueRead: vi.fn(),
+ markIssueUnread: vi.fn(),
},
copyTextMock: vi.fn(),
}));
@@ -205,6 +208,12 @@ beforeEach(() => {
apiMocks.listProjects.mockResolvedValue({ projects: [] });
apiMocks.getAgentTaskSnapshot.mockReset();
apiMocks.getAgentTaskSnapshot.mockResolvedValue([]);
+ apiMocks.listIssueUnread.mockReset();
+ apiMocks.listIssueUnread.mockResolvedValue([]);
+ apiMocks.markIssueRead.mockReset();
+ apiMocks.markIssueRead.mockResolvedValue({ unread: false });
+ apiMocks.markIssueUnread.mockReset();
+ apiMocks.markIssueUnread.mockResolvedValue({ unread: true });
cancelRunMock.mockReset();
cancelRunMock.mockResolvedValue(undefined);
updateIssueMock.mockReset();
@@ -583,6 +592,7 @@ describe("Sidebar variant (MUL-8425)", () => {
"AssigneeTest User",
"Open in new tab",
"Pin to sidebar",
+ "Mark as unread",
"Copy link",
"Copy identifier",
]);
@@ -591,6 +601,23 @@ describe("Sidebar variant (MUL-8425)", () => {
expect(listTasksByIssueMock).not.toHaveBeenCalled();
});
+ it("marks an unread issue as read", async () => {
+ apiMocks.listIssueUnread.mockResolvedValue([
+ { issue_id: "issue-1", outcome: "completed", agent_id: "agent-1", created_at: "2026-01-01T00:00:00Z" },
+ ]);
+ openSidebarMenu();
+ fireEvent.click(await screen.findByText("Mark as read"));
+
+ await waitFor(() => expect(apiMocks.markIssueRead).toHaveBeenCalledWith("issue-1"));
+ });
+
+ it("marks a read issue as unread", async () => {
+ openSidebarMenu();
+ fireEvent.click(await screen.findByText("Mark as unread"));
+
+ await waitFor(() => expect(apiMocks.markIssueUnread).toHaveBeenCalledWith("issue-1"));
+ });
+
it("shows Unassigned when nobody owns the issue", async () => {
openSidebarMenu();
expect(await screen.findByText("Unassigned")).toBeInTheDocument();
diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsx
index c10e4d9a4b..dc7d2827d1 100644
--- a/packages/views/issues/actions/issue-actions-menu-items.tsx
+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx
@@ -9,6 +9,7 @@ import {
Calendar,
CalendarClock,
Check,
+ CircleDot,
CircleEqual,
ExternalLink,
FolderOpen,
@@ -34,6 +35,7 @@ import {
PRIORITY_CONFIG,
} from "@multica/core/issues/config";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueUnread, useMarkIssueRead, useMarkIssueUnread } from "@multica/core/issues/unread";
import { useActorName } from "@multica/core/workspace/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { stepHandsOff, workflowAllowsStatus, workflowStep } from "@multica/core/issue-workflows";
@@ -141,6 +143,9 @@ export function IssueActionsMenuItems({
updateField({ status });
};
const { categoryOf, colorOf, iconOf } = useIssueStatuses(wsId);
+ const unread = useIssueUnread(wsId, sidebar ? issue.id : "");
+ const { mutate: markRead } = useMarkIssueRead(wsId);
+ const { mutate: markUnread } = useMarkIssueUnread(wsId);
const {
isPinned,
updateField,
@@ -410,6 +415,18 @@ export function IssueActionsMenuItems({
)}
{isPinned ? t(($) => $.actions.unpin_from_sidebar) : t(($) => $.actions.pin_to_sidebar)}
</P.Item>
+ {sidebar &&
+ (unread ? (
+ <P.Item onClick={() => markRead(issue.id)}>
+ <Check className="h-3.5 w-3.5" />
+ {t(($) => $.actions.mark_read)}
+ </P.Item>
+ ) : (
+ <P.Item onClick={() => markUnread(issue.id)}>
+ <CircleDot className="h-3.5 w-3.5" />
+ {t(($) => $.actions.mark_unread)}
+ </P.Item>
+ ))}
<P.Item onClick={copyLink}>
<Link2 className="h-3.5 w-3.5" />
{t(($) => $.actions.copy_link)}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index d95043228c..fb029b2164 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -165,6 +165,7 @@ import {
import { useIssueTimeline } from "../hooks/use-issue-timeline";
import { useIssueReactions } from "../hooks/use-issue-reactions";
import { useIssueSubscribers } from "../hooks/use-issue-subscribers";
+import { useMarkIssueReadWhileViewing } from "../hooks/use-mark-issue-read-while-viewing";
import { ReactionBar } from "@multica/ui/components/common/reaction-bar";
import { useLocale, useTimeAgo } from "../../i18n";
import {
@@ -1553,6 +1554,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
return cached?.description != null ? cached : undefined;
},
});
+ useMarkIssueReadWhileViewing(wsId, issue?.id ?? "");
const descriptionSourceId = `description:${id}`;
const descriptionAnnotations = useCommentAnnotations({
draftKey: `new:${id}`,
diff --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.tsx
new file mode 100644
index 0000000000..5d7448370a
--- /dev/null
+++ b/packages/views/issues/hooks/use-mark-issue-read-while-viewing.test.tsx
@@ -0,0 +1,80 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createQueryClient } from "@multica/core/query-client";
+import { api } from "@multica/core/api";
+import { issueUnreadKeys } from "@multica/core/issues/unread";
+import type { IssueUnread } from "@multica/core/types";
+import { useMarkIssueReadWhileViewing } from "./use-mark-issue-read-while-viewing";
+
+vi.mock("@multica/core/api", () => ({ api: { listIssueUnread: vi.fn(), markIssueRead: vi.fn() } }));
+vi.mock("../../common/use-app-foreground", () => ({ useAppForeground: () => true }));
+
+const completed: IssueUnread = {
+ issue_id: "issue-1",
+ outcome: "completed",
+ agent_id: "agent-1",
+ created_at: "2026-10-31T10:00:00Z",
+};
+
+let client: ReturnType<typeof createQueryClient>;
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+);
+
+beforeEach(() => {
+ client = createQueryClient();
+});
+
+afterEach(() => {
+ client.clear();
+ vi.resetAllMocks();
+});
+
+describe("useMarkIssueReadWhileViewing", () => {
+ it("does not resubmit when the write fails and the mark rolls back", async () => {
+ client.setQueryData(issueUnreadKeys.all("ws-1"), [completed]);
+ vi.mocked(api.listIssueUnread).mockResolvedValue([completed]);
+ vi.mocked(api.markIssueRead).mockImplementation(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ throw Object.assign(new Error("forbidden"), { status: 403 });
+ });
+
+ renderHook(() => useMarkIssueReadWhileViewing("ws-1", "issue-1"), { wrapper });
+ await waitFor(() => expect(api.markIssueRead).toHaveBeenCalled());
+ await act(() => new Promise((resolve) => setTimeout(resolve, 200)));
+
+ expect(api.markIssueRead).toHaveBeenCalledTimes(1);
+ });
+
+ it("clears a newer mark that arrives while the issue stays open", async () => {
+ client.setQueryData(issueUnreadKeys.all("ws-1"), [completed]);
+ vi.mocked(api.listIssueUnread).mockResolvedValue([]);
+ vi.mocked(api.markIssueRead).mockResolvedValue(undefined);
+
+ renderHook(() => useMarkIssueReadWhileViewing("ws-1", "issue-1"), { wrapper });
+ await waitFor(() => expect(api.markIssueRead).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(api.listIssueUnread).toHaveBeenCalled());
+
+ act(() => {
+ client.setQueryData(issueUnreadKeys.all("ws-1"), [{ ...completed, created_at: "2026-10-31T10:05:00Z" }]);
+ });
+ await waitFor(() => expect(api.markIssueRead).toHaveBeenCalledTimes(2));
+ });
+
+ it("keeps a mark set by hand while the issue is open", async () => {
+ client.setQueryData(issueUnreadKeys.all("ws-1"), []);
+ vi.mocked(api.listIssueUnread).mockResolvedValue([]);
+
+ renderHook(() => useMarkIssueReadWhileViewing("ws-1", "issue-1"), { wrapper });
+ act(() => {
+ client.setQueryData(issueUnreadKeys.all("ws-1"), [
+ { ...completed, outcome: "manual", agent_id: null, created_at: "2026-10-31T10:05:00Z" },
+ ]);
+ });
+ await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
+
+ expect(api.markIssueRead).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/issues/hooks/use-mark-issue-read-while-viewing.ts b/packages/views/issues/hooks/use-mark-issue-read-while-viewing.ts
new file mode 100644
index 0000000000..3f36c4229c
--- /dev/null
+++ b/packages/views/issues/hooks/use-mark-issue-read-while-viewing.ts
@@ -0,0 +1,44 @@
+import { useCallback, useEffect, useRef } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { issueUnreadOptions, useMarkIssueRead } from "@multica/core/issues/unread";
+import type { IssueUnread } from "@multica/core/types";
+import { useAppForeground } from "../../common/use-app-foreground";
+
+/**
+ * Clears the viewer's unread mark while the issue is on screen: when it is
+ * opened, and when a run ends while it stays open. A mark the viewer set by
+ * hand while the issue is open is kept, or "Mark as unread" would undo itself.
+ * Nothing is cleared while the app is in the background.
+ *
+ * Each unread mark is cleared at most once per viewing. A failed write rolls
+ * the cache back to that same mark; trying again on it would loop. The
+ * mutation's own retries cover transient failures, and a newer mark (another
+ * run ending) or reopening the issue tries again.
+ */
+export function useMarkIssueReadWhileViewing(wsId: string, issueId: string) {
+ const foreground = useAppForeground();
+ const select = useCallback(
+ (items: IssueUnread[]) => items.find((item) => item.issue_id === issueId) ?? null,
+ [issueId],
+ );
+ const { data: unread = null, isSuccess } = useQuery({
+ ...issueUnreadOptions(wsId),
+ select,
+ enabled: !!issueId,
+ });
+ const { mutate: markRead } = useMarkIssueRead(wsId);
+ const viewedIssueId = useRef<string | null>(null);
+ const clearedMark = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (!issueId || !isSuccess || !foreground) return;
+ const opening = viewedIssueId.current !== issueId;
+ viewedIssueId.current = issueId;
+ if (opening) clearedMark.current = null;
+ if (!unread || (!opening && unread.outcome === "manual")) return;
+ const mark = `${unread.outcome}|${unread.created_at}`;
+ if (clearedMark.current === mark) return;
+ clearedMark.current = mark;
+ markRead(issueId);
+ }, [issueId, isSuccess, foreground, unread, markRead]);
+}
diff --git a/packages/views/layout/panels/pinned-section.tsx b/packages/views/layout/panels/pinned-section.tsx
index dd82bb96dc..25b2f1180e 100644
--- a/packages/views/layout/panels/pinned-section.tsx
+++ b/packages/views/layout/panels/pinned-section.tsx
@@ -23,6 +23,7 @@ import { projectDetailOptions } from "@multica/core/projects/queries";
import { pinListOptions } from "@multica/core/pins/queries";
import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";
import { useDeletePin, useReorderPins } from "@multica/core/pins/mutations";
+import { useIssueUnread } from "@multica/core/issues/unread";
import { useWorkspacePaths, type WorkspacePaths } from "@multica/core/paths";
import type { Issue, PinnedItem } from "@multica/core/types";
import { AppLink } from "../../navigation";
@@ -33,6 +34,7 @@ import { PANEL_ROW_CLASS, PanelList, PanelSection, isPathWithin, panelRowStateCl
import {
ISSUE_ROW_LINK_CLASS,
IssueAgentBadge,
+ IssueUnreadDot,
SIDEBAR_SHIMMER_CLASS,
SidebarIssueStatus,
issueRowMenuOpenClass,
@@ -189,6 +191,7 @@ function SortablePinItem({
iconNode,
active,
running = false,
+ unread = false,
trailing,
onNavigate,
issue,
@@ -201,6 +204,8 @@ function SortablePinItem({
active: boolean;
/** Shimmers the label while an agent works on the pinned issue. */
running?: boolean;
+ /** Brightens the label while the issue has an unread agent result. */
+ unread?: boolean;
trailing?: React.ReactNode;
/** Runs on a real click (not a drag-release) before navigation. */
onNavigate?: () => void;
@@ -242,7 +247,10 @@ function SortablePinItem({
}}
className={cn(ISSUE_ROW_LINK_CLASS, "gap-2.5")}
>
- <ShimmerText active={running} className={cn("min-w-0 flex-1 truncate", SIDEBAR_SHIMMER_CLASS)}>
+ <ShimmerText
+ active={running}
+ className={cn("min-w-0 flex-1 truncate", SIDEBAR_SHIMMER_CLASS, unread && "text-foreground")}
+ >
{label}
</ShimmerText>
{/* Holds the same right-edge slot as a tree row's avatars, and yields
@@ -308,6 +316,7 @@ function PinRow({
}) {
const isIssue = pin.item_type === "issue";
const agents = useIssueAgentState(wsId, isIssue ? pin.item_id : "");
+ const unread = useIssueUnread(wsId, isIssue ? pin.item_id : "");
const statusCatalog = useIssueStatuses(wsId);
const statusLabel = useStatusLabel(wsId);
const issueQuery = useQuery({ ...issueDetailOptions(wsId, pin.item_id), enabled: isIssue });
@@ -337,7 +346,8 @@ function PinRow({
label={issue.title}
active={active}
running={!!agents?.running}
- trailing={agents && <IssueAgentBadge agents={agents} />}
+ unread={!agents && !!unread}
+ trailing={agents ? <IssueAgentBadge agents={agents} /> : unread && <IssueUnreadDot unread={unread} />}
issue={issue}
iconNode={
<SidebarIssueStatus
diff --git a/packages/views/layout/panels/sidebar-tree.tsx b/packages/views/layout/panels/sidebar-tree.tsx
index b489266c42..754bfeec24 100644
--- a/packages/views/layout/panels/sidebar-tree.tsx
+++ b/packages/views/layout/panels/sidebar-tree.tsx
@@ -5,14 +5,17 @@ import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { ChevronDown, ChevronRight, ChevronUp } from "@multica/ui/icons";
import { cn } from "@multica/ui/lib/utils";
import { ShimmerText } from "@multica/ui/components/common/shimmer-text";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";
import { agentTaskSnapshotOptions } from "@multica/core/agents";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
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 { useWorkspacePaths } from "@multica/core/paths";
-import type { AgentTask, Issue, ListIssuesParams } from "@multica/core/types";
+import { useActorName } from "@multica/core/workspace/hooks";
+import type { AgentTask, Issue, IssueUnread, ListIssuesParams } from "@multica/core/types";
import { AppLink } from "../../navigation";
import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";
import { StatusIcon } from "../../issues/components/status-icon";
@@ -22,7 +25,7 @@ import { useIssueActions } from "../../issues/actions/use-issue-actions";
import { selectIssueTasks } from "../../issues/surface/activity";
import { useStatusLabel } from "../../issues/utils/status-label";
import { DeferredPopup } from "../../common/deferred-popup";
-import { useT } from "../../i18n";
+import { useT, useTimeAgo } from "../../i18n";
import { PANEL_ROW_CLASS, panelRowStateClass } from "../panel-nav";
/** A working agent's issue title: dimmer at rest and a wider highlight than
@@ -406,7 +409,34 @@ function SidebarStatusPicker({
);
}
-/** The title shimmers while an agent runs on the issue; queued agents show dimmed. */
+/** 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 }) {
+ const { t } = useT("issues");
+ const timeAgo = useTimeAgo();
+ const { getActorName } = useActorName();
+ const label =
+ unread.outcome === "manual" || !unread.agent_id
+ ? t(($) => $.agent_activity.unread_manual)
+ : unread.outcome === "failed"
+ ? t(($) => $.agent_activity.unread_failed, { agent: getActorName("agent", unread.agent_id), time: timeAgo(unread.created_at) })
+ : t(($) => $.agent_activity.unread_completed, { agent: getActorName("agent", unread.agent_id), time: timeAgo(unread.created_at) });
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span role="img" aria-label={label} className="flex size-4 shrink-0 items-center justify-center">
+ <span className="size-2 rounded-full bg-brand" />
+ </span>
+ }
+ />
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+/** The title shimmers while an agent runs on the issue; queued agents show
+ * dimmed. Once the run ends, an unread result shows a dot and a brighter title. */
const SidebarIssueRow = memo(function SidebarIssueRow({
wsId,
issue,
@@ -427,6 +457,7 @@ const SidebarIssueRow = memo(function SidebarIssueRow({
onKeyDown: (event: React.KeyboardEvent) => void;
}) {
const agents = useIssueAgentState(wsId, issue.id);
+ const unread = useIssueUnread(wsId, issue.id);
return (
<IssueActionsContextMenu issue={issue}>
@@ -445,10 +476,13 @@ const SidebarIssueRow = memo(function SidebarIssueRow({
onKeyDown={onKeyDown}
className={ISSUE_ROW_LINK_CLASS}
>
- <ShimmerText active={!!agents?.running} className={cn("min-w-0 flex-1 truncate", SIDEBAR_SHIMMER_CLASS)}>
+ <ShimmerText
+ active={!!agents?.running}
+ className={cn("min-w-0 flex-1 truncate", SIDEBAR_SHIMMER_CLASS, !agents && unread && "text-foreground")}
+ >
{issue.title}
</ShimmerText>
- {agents && <IssueAgentBadge agents={agents} />}
+ {agents ? <IssueAgentBadge agents={agents} /> : unread && <IssueUnreadDot unread={unread} />}
</AppLink>
</div>
</IssueActionsContextMenu>
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 8444a1b3ef..affc48a39d 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -765,6 +765,9 @@
"hover_header_queued_other": "{{count}} queued agents",
"status_running": "Working",
"status_queued": "Queued",
+ "unread_completed": "{{agent}} finished · {{time}}",
+ "unread_failed": "{{agent}}'s run failed · {{time}}",
+ "unread_manual": "Marked as unread",
"empty_hover": "No agents working right now",
"unknown_hover": "Agents working: not loaded yet",
"filter_active_label": "Viewing issues with agents working",
@@ -964,6 +967,8 @@
"open_in_new_tab": "Open in new tab",
"pin_to_sidebar": "Pin to sidebar",
"unpin_from_sidebar": "Unpin from sidebar",
+ "mark_read": "Mark as read",
+ "mark_unread": "Mark as unread",
"copy_link": "Copy link",
"copy_workdir_path": "Copy local workdir path",
"copy_project_directory_path": "Copy project directory path",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index db12abc471..411b028963 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -765,6 +765,9 @@
"hover_header_queued_other": "{{count}} agents en attente",
"status_running": "Au travail",
"status_queued": "En file d'attente",
+ "unread_completed": "{{agent}} a terminé · {{time}}",
+ "unread_failed": "L'exécution de {{agent}} a échoué · {{time}}",
+ "unread_manual": "Marqué comme non lu",
"empty_hover": "Aucun agent au travail pour l'instant",
"unknown_hover": "Agents au travail : pas encore chargé",
"filter_active_label": "Affichage des tâches avec des agents au travail",
@@ -964,6 +967,8 @@
"open_in_new_tab": "Ouvrir dans un nouvel onglet",
"pin_to_sidebar": "Épingler à la barre latérale",
"unpin_from_sidebar": "Détacher de la barre latérale",
+ "mark_read": "Marquer comme lu",
+ "mark_unread": "Marquer comme non lu",
"copy_link": "Copier le lien",
"copy_workdir_path": "Copier le chemin du répertoire de travail local",
"copy_project_directory_path": "Copier le chemin du répertoire du projet",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index c686b95547..78ab930414 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -739,6 +739,9 @@
"hover_header_queued_other": "待機中のエージェント {{count}} 件",
"status_running": "作業中",
"status_queued": "待機中",
+ "unread_completed": "{{agent}} の実行が完了 · {{time}}",
+ "unread_failed": "{{agent}} の実行が失敗 · {{time}}",
+ "unread_manual": "未読にしました",
"empty_hover": "現在作業中のエージェントはありません",
"unknown_hover": "作業中のエージェント: まだ読み込まれていません",
"filter_active_label": "エージェントが作業中のタスクを表示中",
@@ -919,6 +922,8 @@
"open_in_new_tab": "新しいタブで開く",
"pin_to_sidebar": "サイドバーにピン留め",
"unpin_from_sidebar": "サイドバーのピン留めを解除",
+ "mark_read": "既読にする",
+ "mark_unread": "未読にする",
"copy_link": "リンクをコピー",
"copy_workdir_path": "ローカルの作業ディレクトリのパスをコピー",
"copy_project_directory_path": "プロジェクトディレクトリのパスをコピー",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index f9def70f53..69f5f61743 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -739,6 +739,9 @@
"hover_header_queued_other": "대기 중인 에이전트 {{count}}개",
"status_running": "작업 중",
"status_queued": "대기 중",
+ "unread_completed": "{{agent}} 실행 완료 · {{time}}",
+ "unread_failed": "{{agent}} 실행 실패 · {{time}}",
+ "unread_manual": "읽지 않음으로 표시됨",
"empty_hover": "현재 작업 중인 에이전트가 없습니다",
"unknown_hover": "작업 중인 에이전트: 아직 불러오지 않았습니다",
"filter_active_label": "에이전트가 작업 중인 태스크만 보는 중",
@@ -919,6 +922,8 @@
"open_in_new_tab": "새 탭에서 열기",
"pin_to_sidebar": "사이드바에 고정",
"unpin_from_sidebar": "사이드바 고정 해제",
+ "mark_read": "읽음으로 표시",
+ "mark_unread": "읽지 않음으로 표시",
"copy_link": "링크 복사",
"copy_workdir_path": "로컬 작업 디렉터리 경로 복사",
"copy_project_directory_path": "프로젝트 디렉터리 경로 복사",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index e9f5e0686f..d8fc80f8c4 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -739,6 +739,9 @@
"hover_header_queued_other": "{{count}} 个智能体排队中",
"status_running": "正在工作",
"status_queued": "排队中",
+ "unread_completed": "{{agent}} 已完成运行 · {{time}}",
+ "unread_failed": "{{agent}} 运行失败 · {{time}}",
+ "unread_manual": "已标为未读",
"empty_hover": "当前没有智能体在工作",
"unknown_hover": "工作中的智能体:尚未加载",
"filter_active_label": "正在查看有智能体在工作的任务",
@@ -919,6 +922,8 @@
"open_in_new_tab": "在新标签页打开",
"pin_to_sidebar": "固定到侧边栏",
"unpin_from_sidebar": "从侧边栏取消固定",
+ "mark_read": "标为已读",
+ "mark_unread": "标为未读",
"copy_link": "复制链接",
"copy_workdir_path": "复制本地 workdir 路径",
"copy_project_directory_path": "复制项目目录路径",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 83d32d53d8..7fc38da716 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -739,6 +739,9 @@
"hover_header_queued_other": "{{count}} 個智慧體排隊中",
"status_running": "正在工作",
"status_queued": "排隊中",
+ "unread_completed": "{{agent}} 已完成執行 · {{time}}",
+ "unread_failed": "{{agent}} 執行失敗 · {{time}}",
+ "unread_manual": "已標為未讀",
"empty_hover": "當前沒有智慧體在工作",
"unknown_hover": "工作中的智慧體:尚未載入",
"filter_active_label": "正在檢視有智慧體在工作的任務",
@@ -919,6 +922,8 @@
"open_in_new_tab": "在新標籤頁開啟",
"pin_to_sidebar": "固定到側邊欄",
"unpin_from_sidebar": "從側邊欄取消固定",
+ "mark_read": "標為已讀",
+ "mark_unread": "標為未讀",
"copy_link": "複製連結",
"copy_workdir_path": "複製本地 workdir 路徑",
"copy_project_directory_path": "複製專案目錄路徑",
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 27f91651aa..b0af47a8c8 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -190,6 +190,7 @@ var concurrentIndexCleanups = map[string]string{
"488_maintenance_job_active_index": "idx_maintenance_job_active",
"587_cloud_agent_connection_provider_index": "cloud_agent_connection_provider_index",
"590_member_delegation_day_unique_index": "member_delegation_day_user_date_uidx",
+ "598_issue_unread_unique_index": "issue_unread_workspace_user_issue_uidx",
"035_task_queue_issue_id_index": "idx_agent_task_queue_issue_id",
"067_task_queue_claim_candidate_index": "idx_agent_task_queue_claim_candidates",
"074_task_usage_updated_at_index": "idx_task_usage_updated_at",
diff --git a/server/cmd/server/issue_unread_listeners.go b/server/cmd/server/issue_unread_listeners.go
new file mode 100644
index 0000000000..29f0169875
--- /dev/null
+++ b/server/cmd/server/issue_unread_listeners.go
@@ -0,0 +1,70 @@
+package main
+
+import (
+ "context"
+ "log/slog"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// registerIssueUnreadListeners marks an issue unread for its subscribed members
+// when an agent run on it ends, and tells each of them so their sidebar
+// refetches. A failed attempt with a retry pending is not an end.
+func registerIssueUnreadListeners(bus *events.Bus, queries *db.Queries) {
+ ctx := context.Background()
+
+ bus.Subscribe(protocol.EventTaskCompleted, func(e events.Event) {
+ markIssueUnreadForRun(ctx, bus, queries, e, "completed")
+ })
+
+ bus.Subscribe(protocol.EventTaskFailed, func(e events.Event) {
+ payload, _ := e.Payload.(map[string]any)
+ if retryPending, _ := payload["retry_pending"].(bool); retryPending {
+ return
+ }
+ markIssueUnreadForRun(ctx, bus, queries, e, "failed")
+ })
+}
+
+func markIssueUnreadForRun(ctx context.Context, bus *events.Bus, queries *db.Queries, e events.Event, outcome string) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ issueID, _ := payload["issue_id"].(string)
+ issueUUID, err := util.ParseUUID(issueID)
+ if err != nil {
+ return
+ }
+ agentID, _ := payload["agent_id"].(string)
+ taskID, _ := payload["task_id"].(string)
+
+ rows, err := queries.MarkIssueUnreadForSubscribers(ctx, db.MarkIssueUnreadForSubscribersParams{
+ Outcome: outcome,
+ AgentID: optionalUUID(agentID),
+ TaskID: optionalUUID(taskID),
+ IssueID: issueUUID,
+ })
+ if err != nil {
+ slog.Error("issue unread: failed to mark subscribers", "issue_id", issueID, "error", err)
+ return
+ }
+ for _, row := range rows {
+ workspaceID := util.UUIDToString(row.WorkspaceID)
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueUnreadChanged,
+ WorkspaceID: workspaceID,
+ ActorType: "agent",
+ ActorID: agentID,
+ Payload: map[string]any{
+ "workspace_id": workspaceID,
+ "recipient_id": util.UUIDToString(row.UserID),
+ "issue_id": issueID,
+ "unread": true,
+ },
+ })
+ }
+}
diff --git a/server/cmd/server/issue_unread_listeners_test.go b/server/cmd/server/issue_unread_listeners_test.go
new file mode 100644
index 0000000000..184fc18665
--- /dev/null
+++ b/server/cmd/server/issue_unread_listeners_test.go
@@ -0,0 +1,98 @@
+package main
+
+import (
+ "context"
+ "slices"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func issueUnreadRows(t *testing.T, issueID string) map[string][2]string {
+ t.Helper()
+ rows, err := testPool.Query(context.Background(),
+ `SELECT user_id::text, outcome, COALESCE(task_id::text, '') FROM issue_unread WHERE issue_id = $1`, issueID)
+ if err != nil {
+ t.Fatalf("query issue_unread: %v", err)
+ }
+ defer rows.Close()
+ got := map[string][2]string{}
+ for rows.Next() {
+ var userID, outcome, taskID string
+ if err := rows.Scan(&userID, &outcome, &taskID); err != nil {
+ t.Fatalf("scan issue_unread: %v", err)
+ }
+ got[userID] = [2]string{outcome, taskID}
+ }
+ return got
+}
+
+func TestIssueUnread_RunEndMarksSubscribedMembers(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerIssueUnreadListeners(bus, queries)
+
+ emails := []string{
+ }
+ t.Cleanup(func() {
+ for _, email := range emails {
+ cleanupTestUser(t, email)
+ }
+ })
+ subscriber := createNotificationMember(t, emails[0])
+ delegated := createNotificationMember(t, emails[1])
+ optedOut := createNotificationMember(t, emails[2])
+ outsider := createTestUser(t, emails[3])
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue_unread WHERE issue_id = $1`, issueID)
+ cleanupTestIssue(t, issueID)
+ })
+ const agentID = "00000000-0000-4000-8000-0000000000a1"
+ addTestSubscriber(t, issueID, "member", subscriber, "manual")
+ addTestSubscriber(t, issueID, "member", delegated, "delegated")
+ addTestSubscriber(t, issueID, "member", optedOut, "manual")
+ addTestSubscriber(t, issueID, "member", outsider, "manual")
+ addTestSubscriber(t, issueID, "agent", agentID, "manual")
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE issue_subscriber SET unsubscribed_at = now() WHERE issue_id = $1 AND user_id = $2`, issueID, optedOut); err != nil {
+ t.Fatalf("opt out: %v", err)
+ }
+
+ var notified []string
+ bus.Subscribe(protocol.EventIssueUnreadChanged, func(e events.Event) {
+ payload := e.Payload.(map[string]any)
+ notified = append(notified, payload["recipient_id"].(string))
+ })
+ runEnded := func(eventType, taskID string, extra map[string]any) {
+ payload := map[string]any{"issue_id": issueID, "agent_id": agentID, "task_id": taskID}
+ for k, v := range extra {
+ payload[k] = v
+ }
+ bus.Publish(events.Event{Type: eventType, WorkspaceID: testWorkspaceID, Payload: payload})
+ }
+
+ runEnded(protocol.EventTaskFailed, "00000000-0000-4000-8000-0000000000b1", map[string]any{"retry_pending": true})
+ if got := issueUnreadRows(t, issueID); len(got) != 0 {
+ t.Fatalf("a failed attempt with a retry pending marked the issue unread: %v", got)
+ }
+
+ runEnded(protocol.EventTaskCompleted, "00000000-0000-4000-8000-0000000000b2", nil)
+ got := issueUnreadRows(t, issueID)
+ if len(got) != 1 || got[subscriber][0] != "completed" {
+ t.Fatalf("want only the active member subscriber marked completed, got %v", got)
+ }
+ if !slices.Equal(notified, []string{subscriber}) {
+ t.Fatalf("want issue_unread:changed for the subscriber only, got %v", notified)
+ }
+
+ runEnded(protocol.EventTaskFailed, "00000000-0000-4000-8000-0000000000b3", map[string]any{"retry_pending": false})
+ if row := issueUnreadRows(t, issueID)[subscriber]; row != [2]string{"failed", "00000000-0000-4000-8000-0000000000b3"} {
+ t.Fatalf("a later run should replace the unread row's run details, got %v", row)
+ }
+}
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.go
index 03d5ae17a4..48ce90cd57 100644
--- a/server/cmd/server/listeners.go
+++ b/server/cmd/server/listeners.go
@@ -109,6 +109,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
protocol.EventInboxBatchArchived: true,
protocol.EventInvitationCreated: true,
protocol.EventInvitationRevoked: true,
+ protocol.EventIssueUnreadChanged: true,
}
// Helper: marshal event and send to a specific user.
@@ -139,10 +140,12 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
})
// inbox:read, inbox:archived, inbox:unarchived, inbox:batch-read,
- // inbox:batch-archived — extract recipient from top-level payload
+ // inbox:batch-archived, issue_unread:changed — extract recipient from
+ // top-level payload
for _, eventType := range []string{
protocol.EventInboxRead, protocol.EventInboxArchived, protocol.EventInboxUnarchived,
protocol.EventInboxBatchRead, protocol.EventInboxBatchArchived,
+ protocol.EventIssueUnreadChanged,
} {
bus.Subscribe(eventType, func(e events.Event) {
payload, ok := e.Payload.(map[string]any)
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index c07e63edbf..96c33532c7 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -615,6 +615,7 @@ func main() {
registerSubscriberListeners(bus, pool)
registerActivityListeners(bus, queries)
registerNotificationListeners(bus, queries)
+ registerIssueUnreadListeners(bus, queries)
metricsConfig := obsmetrics.ConfigFromEnv()
var metricsServer *http.Server
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 054d925fb1..794c93c156 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2041,6 +2041,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/child-progress", h.ChildIssueProgress)
r.Get("/children", h.ListChildrenByParents)
r.Get("/grouped", h.ListGroupedIssues)
+ // The caller's issues with an agent result they have not seen
+ // yet; backs the sidebar's unread dot.
+ r.Get("/unread", h.ListIssueUnread)
r.Get("/", h.ListIssues)
// POST twin of GET /api/issues for oversized filter sets
// (agents-working ids facet) — see QueryIssues.
@@ -2064,6 +2067,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/subscribe", h.SubscribeToIssue)
r.Post("/unsubscribe", h.UnsubscribeFromIssue)
r.Post("/unsubscribe/subtree", h.UnsubscribeFromIssueSubtree)
+ r.Post("/read", h.MarkIssueRead)
+ r.Post("/unread", h.MarkIssueUnread)
r.Get("/wakeups", h.ListIssueWakeups)
r.Post("/wakeups", h.CreateIssueWakeup)
r.Put("/wakeups/{wakeupID}", h.CreateIssueWakeup)
diff --git a/server/internal/handler/issue_unread.go b/server/internal/handler/issue_unread.go
new file mode 100644
index 0000000000..45ce2be3cd
--- /dev/null
+++ b/server/internal/handler/issue_unread.go
@@ -0,0 +1,120 @@
+package handler
+
+import (
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// 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.
+type IssueUnreadResponse struct {
+ IssueID string `json:"issue_id"`
+ Outcome string `json:"outcome"`
+ AgentID *string `json:"agent_id"`
+ CreatedAt string `json:"created_at"`
+}
+
+const issueUnreadPageSize = 500
+
+// ListIssueUnread returns one page of the caller's unread issues in the
+// current workspace, newest first. next_cursor is set while more remain; the
+// client reads every page, since a missing row would read as "read".
+func (h *Handler) ListIssueUnread(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, ctxWorkspaceID(r.Context()), "workspace id")
+ if !ok {
+ return
+ }
+ params := db.ListIssueUnreadParams{
+ WorkspaceID: wsUUID,
+ UserID: parseUUID(userID),
+ PageLimit: int32(issueUnreadPageSize + 1),
+ }
+ if cursor := r.URL.Query().Get("cursor"); cursor != "" {
+ params.BeforeCreatedAt, params.BeforeIssueID = parseTranscriptCursor(cursor)
+ if !params.BeforeCreatedAt.Valid {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return
+ }
+ }
+
+ rows, err := h.Queries.ListIssueUnread(r.Context(), params)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list unread issues")
+ return
+ }
+ var nextCursor *string
+ if len(rows) > issueUnreadPageSize {
+ rows = rows[:issueUnreadPageSize]
+ last := rows[len(rows)-1]
+ cursor := transcriptCursor(last.CreatedAt.Time, last.IssueID)
+ nextCursor = &cursor
+ }
+
+ items := make([]IssueUnreadResponse, len(rows))
+ for i, row := range rows {
+ items[i] = IssueUnreadResponse{
+ IssueID: uuidToString(row.IssueID),
+ Outcome: row.Outcome,
+ AgentID: uuidToPtr(row.AgentID),
+ CreatedAt: timestampToString(row.CreatedAt),
+ }
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"items": items, "next_cursor": nextCursor})
+}
+
+// MarkIssueRead clears the caller's unread mark on an issue.
+func (h *Handler) MarkIssueRead(w http.ResponseWriter, r *http.Request) {
+ h.setIssueUnread(w, r, false)
+}
+
+// MarkIssueUnread marks an issue unread for the caller.
+func (h *Handler) MarkIssueUnread(w http.ResponseWriter, r *http.Request) {
+ h.setIssueUnread(w, r, true)
+}
+
+func (h *Handler) setIssueUnread(w http.ResponseWriter, r *http.Request, unread bool) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+
+ params := db.MarkIssueReadParams{
+ WorkspaceID: issue.WorkspaceID,
+ UserID: parseUUID(userID),
+ IssueID: issue.ID,
+ }
+ var changed int64
+ var err error
+ if unread {
+ changed, err = h.Queries.MarkIssueUnreadManually(r.Context(), db.MarkIssueUnreadManuallyParams(params))
+ } else {
+ changed, err = h.Queries.MarkIssueRead(r.Context(), params)
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update unread state")
+ return
+ }
+
+ if changed > 0 {
+ workspaceID := uuidToString(issue.WorkspaceID)
+ h.publish(protocol.EventIssueUnreadChanged, workspaceID, "member", userID, map[string]any{
+ "workspace_id": workspaceID,
+ "recipient_id": userID,
+ "issue_id": uuidToString(issue.ID),
+ "unread": unread,
+ })
+ }
+ writeJSON(w, http.StatusOK, map[string]bool{"unread": unread})
+}
diff --git a/server/internal/handler/issue_unread_test.go b/server/internal/handler/issue_unread_test.go
new file mode 100644
index 0000000000..3e69b664bf
--- /dev/null
+++ b/server/internal/handler/issue_unread_test.go
@@ -0,0 +1,127 @@
+package handler
+
+import (
+ "net/http"
+ "net/url"
+ "testing"
+
+ "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"
+)
+
+type issueUnreadList struct {
+ Items []IssueUnreadResponse `json:"items"`
+ NextCursor *string `json:"next_cursor"`
+}
+
+func listIssueUnreadPageAs(t *testing.T, userID, cursor string) issueUnreadList {
+ t.Helper()
+ var out issueUnreadList
+ req := newRequestAs(userID, "GET", "/api/issues/unread?cursor="+url.QueryEscape(cursor), nil)
+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))
+ testutil.Call(t, testHandler.ListIssueUnread, req).
+ Want(http.StatusOK).JSON(&out)
+ return out
+}
+
+func listIssueUnreadAs(t *testing.T, userID string) []IssueUnreadResponse {
+ t.Helper()
+ page := listIssueUnreadPageAs(t, userID, "")
+ if page.NextCursor != nil {
+ t.Fatalf("expected a single page, got next_cursor %q", *page.NextCursor)
+ }
+ return page.Items
+}
+
+func setIssueUnreadAs(t *testing.T, userID, issueID string, unread bool) *testutil.Response {
+ t.Helper()
+ h, verb := testHandler.MarkIssueRead, "read"
+ if unread {
+ h, verb = testHandler.MarkIssueUnread, "unread"
+ }
+ req := withURLParam(newRequestAs(userID, "POST", "/api/issues/"+issueID+"/"+verb, nil), "id", issueID)
+ return testutil.Call(t, h, req)
+}
+
+func TestIssueUnreadMarkAndClear(t *testing.T) {
+ issueID := dbfx.Issue(t, "issue unread round trip")
+ dbfx.Cleanup(t, `DELETE FROM issue_unread WHERE issue_id = $1`, issueID)
+
+ 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 {
+ t.Fatalf("want one manual unread row for the issue, got %+v", items)
+ }
+
+ setIssueUnreadAs(t, testUserID, issueID, false).Want(http.StatusOK)
+ setIssueUnreadAs(t, testUserID, issueID, false).Want(http.StatusOK)
+ if items := listIssueUnreadAs(t, testUserID); len(items) != 0 {
+ t.Fatalf("want no unread rows after mark read, got %+v", items)
+ }
+}
+
+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)
+ otherID := dbfx.User(t, "Unread Other", "[email protected]")
+ dbfx.Member(t, testWorkspaceID, otherID, "member")
+
+ setIssueUnreadAs(t, testUserID, issueID, true).Want(http.StatusOK)
+ if items := listIssueUnreadAs(t, otherID); len(items) != 0 {
+ t.Fatalf("another member saw the caller's unread mark: %+v", items)
+ }
+ setIssueUnreadAs(t, otherID, issueID, false).Want(http.StatusOK)
+ if items := listIssueUnreadAs(t, testUserID); len(items) != 1 {
+ t.Fatalf("another member's mark-read cleared the caller's mark: %+v", items)
+ }
+}
+
+func TestIssueUnreadRejectsIssueInAnotherWorkspace(t *testing.T) {
+ otherWorkspaceID := dbfx.Workspace(t, "Unread Other WS", "issue-unread-other-ws")
+ issueID := dbfx.Issue(t, "foreign issue", testutil.Cols{"workspace_id": otherWorkspaceID})
+ dbfx.Cleanup(t, `DELETE FROM issue_unread WHERE issue_id = $1`, issueID)
+
+ setIssueUnreadAs(t, testUserID, issueID, true).Want(http.StatusNotFound)
+ if n := dbfx.Count(t, `SELECT count(*) FROM issue_unread WHERE issue_id = $1`, issueID); n != 0 {
+ t.Fatalf("an issue in another workspace was marked unread")
+ }
+}
+
+func TestIssueUnreadPagesReachEveryRow(t *testing.T) {
+ userID := dbfx.User(t, "Unread Pages", "[email protected]")
+ dbfx.Member(t, testWorkspaceID, userID, "member")
+ dbfx.Cleanup(t, `DELETE FROM issue_unread WHERE user_id = $1`, userID)
+ // Rows share timestamps in pairs, so a page boundary can fall between two
+ // rows with the same created_at.
+ const total = 2*issueUnreadPageSize + 1
+ dbfx.Exec(t, `
+INSERT INTO issue_unread (workspace_id, user_id, issue_id, outcome, created_at)
+SELECT $1, $2, gen_random_uuid(), 'completed', now() - (n / 2) * interval '1 second'
+FROM generate_series(1, $3::int) AS n`, testWorkspaceID, userID, total)
+
+ seen := map[string]bool{}
+ cursor, pages := "", 0
+ for {
+ page := listIssueUnreadPageAs(t, userID, cursor)
+ pages++
+ for _, item := range page.Items {
+ if seen[item.IssueID] {
+ t.Fatalf("issue %s returned on two pages", item.IssueID)
+ }
+ seen[item.IssueID] = true
+ }
+ if page.NextCursor == nil {
+ break
+ }
+ cursor = *page.NextCursor
+ }
+ if pages != 3 || len(seen) != total {
+ t.Fatalf("want %d rows over 3 pages, got %d rows over %d pages", total, len(seen), pages)
+ }
+
+ req := newRequestAs(userID, "GET", "/api/issues/unread?cursor=nope", nil)
+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))
+ testutil.Call(t, testHandler.ListIssueUnread, req).Want(http.StatusBadRequest)
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index d08fe18ba9..3d34fd9782 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -91,6 +91,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"issue_workflow": workspaceDelete,
"issue_subscriber": workspaceDelete,
"issue_to_label": workspaceDelete,
+ "issue_unread": workspaceDelete,
"issue_vcs_pull_request": workspaceDelete,
"lark_binding_token": workspaceDelete,
"lark_chat_session_binding": workspaceDelete,
diff --git a/server/migrations/597_issue_unread.down.sql b/server/migrations/597_issue_unread.down.sql
new file mode 100644
index 0000000000..9788441749
--- /dev/null
+++ b/server/migrations/597_issue_unread.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS issue_unread;
diff --git a/server/migrations/597_issue_unread.up.sql b/server/migrations/597_issue_unread.up.sql
new file mode 100644
index 0000000000..570b654c02
--- /dev/null
+++ b/server/migrations/597_issue_unread.up.sql
@@ -0,0 +1,21 @@
+-- An agent result on an issue that a member has not seen yet (MUL-8438). Backs
+-- the sidebar's unread dot. A row is written for each subscribed member when an
+-- agent run on the issue ends, and removed when the member opens the issue.
+-- Rows exist only while unread, so the table stays small and starts empty: no
+-- issue lights up for runs that ended before this shipped.
+--
+-- outcome: completed | failed (from the run), or manual (marked unread by the
+-- member). agent_id and task_id name the run, and are null for manual.
+--
+-- No foreign keys; issue and workspace deletion remove these rows in the
+-- application deletion graph. Readers join current members. The primary key is
+-- built concurrently in 598/599, following member_delegation_day (589-591).
+CREATE TABLE IF NOT EXISTS issue_unread (
+ workspace_id UUID NOT NULL,
+ user_id UUID NOT NULL,
+ issue_id UUID NOT NULL,
+ outcome TEXT NOT NULL CHECK (outcome IN ('completed', 'failed', 'manual')),
+ agent_id UUID,
+ task_id UUID,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/598_issue_unread_unique_index.down.sql b/server/migrations/598_issue_unread_unique_index.down.sql
new file mode 100644
index 0000000000..2729d3bb0a
--- /dev/null
+++ b/server/migrations/598_issue_unread_unique_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS issue_unread_workspace_user_issue_uidx;
diff --git a/server/migrations/598_issue_unread_unique_index.up.sql b/server/migrations/598_issue_unread_unique_index.up.sql
new file mode 100644
index 0000000000..d2d34a079c
--- /dev/null
+++ b/server/migrations/598_issue_unread_unique_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS issue_unread_workspace_user_issue_uidx ON issue_unread (workspace_id, user_id, issue_id);
diff --git a/server/migrations/599_issue_unread_primary_key.down.sql b/server/migrations/599_issue_unread_primary_key.down.sql
new file mode 100644
index 0000000000..d19504d558
--- /dev/null
+++ b/server/migrations/599_issue_unread_primary_key.down.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_unread DROP CONSTRAINT IF EXISTS issue_unread_pkey;
diff --git a/server/migrations/599_issue_unread_primary_key.up.sql b/server/migrations/599_issue_unread_primary_key.up.sql
new file mode 100644
index 0000000000..e4866bbc13
--- /dev/null
+++ b/server/migrations/599_issue_unread_primary_key.up.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_unread ADD CONSTRAINT issue_unread_pkey PRIMARY KEY USING INDEX issue_unread_workspace_user_issue_uidx;
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index aa355c849c..63bc619a77 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -504,6 +504,9 @@ cleared_pr_automation AS (
),
cleared_pr_exclusions AS (
DELETE FROM issue_pull_request_exclusion WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_unread AS (
+ DELETE FROM issue_unread WHERE issue_id IN (SELECT target.id FROM target)
)
DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target)
`
diff --git a/server/pkg/db/generated/issue_unread.sql.go b/server/pkg/db/generated/issue_unread.sql.go
new file mode 100644
index 0000000000..c7938c10bf
--- /dev/null
+++ b/server/pkg/db/generated/issue_unread.sql.go
@@ -0,0 +1,174 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: issue_unread.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const listIssueUnread = `-- name: ListIssueUnread :many
+SELECT issue_id, outcome, agent_id, created_at
+FROM issue_unread
+WHERE workspace_id = $1
+ AND user_id = $2
+ AND (
+ $3::timestamptz IS NULL
+ OR (created_at, issue_id) < ($3::timestamptz, $4::uuid)
+ )
+ORDER BY created_at DESC, issue_id DESC
+LIMIT $5
+`
+
+type ListIssueUnreadParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ BeforeCreatedAt pgtype.Timestamptz `json:"before_created_at"`
+ BeforeIssueID pgtype.UUID `json:"before_issue_id"`
+ PageLimit int32 `json:"page_limit"`
+}
+
+type ListIssueUnreadRow struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ Outcome string `json:"outcome"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+// 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.
+func (q *Queries) ListIssueUnread(ctx context.Context, arg ListIssueUnreadParams) ([]ListIssueUnreadRow, error) {
+ rows, err := q.db.Query(ctx, listIssueUnread,
+ arg.WorkspaceID,
+ arg.UserID,
+ arg.BeforeCreatedAt,
+ arg.BeforeIssueID,
+ arg.PageLimit,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListIssueUnreadRow{}
+ for rows.Next() {
+ var i ListIssueUnreadRow
+ if err := rows.Scan(
+ &i.IssueID,
+ &i.Outcome,
+ &i.AgentID,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const markIssueRead = `-- name: MarkIssueRead :execrows
+DELETE FROM issue_unread
+WHERE workspace_id = $1 AND user_id = $2 AND issue_id = $3
+`
+
+type MarkIssueReadParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+}
+
+func (q *Queries) MarkIssueRead(ctx context.Context, arg MarkIssueReadParams) (int64, error) {
+ result, err := q.db.Exec(ctx, markIssueRead, arg.WorkspaceID, arg.UserID, arg.IssueID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const markIssueUnreadForSubscribers = `-- name: MarkIssueUnreadForSubscribers :many
+INSERT INTO issue_unread (workspace_id, user_id, issue_id, outcome, agent_id, task_id, created_at)
+SELECT i.workspace_id, s.user_id, i.id, $1::text, $2::uuid, $3::uuid, now()
+FROM issue i
+JOIN issue_subscriber s
+ ON s.issue_id = i.id
+ AND s.user_type = 'member'
+ AND s.unsubscribed_at IS NULL
+ AND s.reason <> 'delegated'
+JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = s.user_id
+WHERE i.id = $4
+ON CONFLICT (workspace_id, user_id, issue_id) DO UPDATE
+SET outcome = EXCLUDED.outcome,
+ agent_id = EXCLUDED.agent_id,
+ task_id = EXCLUDED.task_id,
+ created_at = EXCLUDED.created_at
+RETURNING workspace_id, user_id
+`
+
+type MarkIssueUnreadForSubscribersParams struct {
+ Outcome string `json:"outcome"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+}
+
+type MarkIssueUnreadForSubscribersRow struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// An agent run on the issue ended: mark it unread for every active member
+// subscriber who is still in the workspace. Delegated subscriptions (sub-issues
+// an agent filed under the member's issue) are the reduced notification tier
+// and do not light the sidebar. A newer run replaces the row's run details.
+func (q *Queries) MarkIssueUnreadForSubscribers(ctx context.Context, arg MarkIssueUnreadForSubscribersParams) ([]MarkIssueUnreadForSubscribersRow, error) {
+ rows, err := q.db.Query(ctx, markIssueUnreadForSubscribers,
+ arg.Outcome,
+ arg.AgentID,
+ arg.TaskID,
+ arg.IssueID,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []MarkIssueUnreadForSubscribersRow{}
+ for rows.Next() {
+ var i MarkIssueUnreadForSubscribersRow
+ if err := rows.Scan(&i.WorkspaceID, &i.UserID); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const markIssueUnreadManually = `-- name: MarkIssueUnreadManually :execrows
+INSERT INTO issue_unread (workspace_id, user_id, issue_id, outcome)
+VALUES ($1, $2, $3, 'manual')
+ON CONFLICT (workspace_id, user_id, issue_id) DO NOTHING
+`
+
+type MarkIssueUnreadManuallyParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+}
+
+// Keeps an existing row: an unread run result already says more than "manual".
+func (q *Queries) MarkIssueUnreadManually(ctx context.Context, arg MarkIssueUnreadManuallyParams) (int64, error) {
+ result, err := q.db.Exec(ctx, markIssueUnreadManually, arg.WorkspaceID, arg.UserID, arg.IssueID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index d544c0c01d..d1217d63b1 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1008,6 +1008,16 @@ type IssueToLabel struct {
LabelID pgtype.UUID `json:"label_id"`
}
+type IssueUnread struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ 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"`
+}
+
type IssueVcsPullRequest struct {
IssueID pgtype.UUID `json:"issue_id"`
PullRequestID pgtype.UUID `json:"pull_request_id"`
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 2d067d0f47..622bc421de 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -241,6 +241,9 @@ WITH deleted_wakeup_receipts AS (
deleted_child_events AS (
DELETE FROM issue_child_event WHERE workspace_id=$1
),
+deleted_unread AS (
+ DELETE FROM issue_unread WHERE workspace_id=$1
+),
deleted_issues AS (
DELETE FROM issue WHERE issue.workspace_id = $1
),
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 2eea06f260..ac608905c6 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -501,6 +501,9 @@ cleared_pr_automation AS (
),
cleared_pr_exclusions AS (
DELETE FROM issue_pull_request_exclusion WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_unread AS (
+ DELETE FROM issue_unread WHERE issue_id IN (SELECT target.id FROM target)
)
DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);
diff --git a/server/pkg/db/queries/issue_unread.sql b/server/pkg/db/queries/issue_unread.sql
new file mode 100644
index 0000000000..1154537d86
--- /dev/null
+++ b/server/pkg/db/queries/issue_unread.sql
@@ -0,0 +1,46 @@
+-- name: MarkIssueUnreadForSubscribers :many
+-- An agent run on the issue ended: mark it unread for every active member
+-- subscriber who is still in the workspace. Delegated subscriptions (sub-issues
+-- an agent filed under the member's issue) are the reduced notification tier
+-- and do not light the sidebar. A newer run replaces the row's run details.
+INSERT INTO issue_unread (workspace_id, user_id, issue_id, outcome, agent_id, task_id, created_at)
+SELECT i.workspace_id, s.user_id, i.id, sqlc.arg(outcome)::text, sqlc.narg(agent_id)::uuid, sqlc.narg(task_id)::uuid, now()
+FROM issue i
+JOIN issue_subscriber s
+ ON s.issue_id = i.id
+ AND s.user_type = 'member'
+ AND s.unsubscribed_at IS NULL
+ AND s.reason <> 'delegated'
+JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = s.user_id
+WHERE i.id = sqlc.arg(issue_id)
+ON CONFLICT (workspace_id, user_id, issue_id) DO UPDATE
+SET outcome = EXCLUDED.outcome,
+ agent_id = EXCLUDED.agent_id,
+ task_id = EXCLUDED.task_id,
+ created_at = EXCLUDED.created_at
+RETURNING workspace_id, user_id;
+
+-- name: ListIssueUnread :many
+-- 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)
+ 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)
+ )
+ORDER BY created_at DESC, issue_id DESC
+LIMIT sqlc.arg(page_limit);
+
+-- name: MarkIssueRead :execrows
+DELETE FROM issue_unread
+WHERE workspace_id = $1 AND user_id = $2 AND issue_id = $3;
+
+-- name: MarkIssueUnreadManually :execrows
+-- Keeps an existing row: an unread run result already says more than "manual".
+INSERT INTO issue_unread (workspace_id, user_id, issue_id, outcome)
+VALUES ($1, $2, $3, 'manual')
+ON CONFLICT (workspace_id, user_id, issue_id) DO NOTHING;
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 9f6972cfb1..14b9ef8dd9 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -559,6 +559,9 @@ WITH deleted_wakeup_receipts AS (
deleted_child_events AS (
DELETE FROM issue_child_event WHERE workspace_id=$1
),
+deleted_unread AS (
+ DELETE FROM issue_unread WHERE workspace_id=$1
+),
deleted_issues AS (
DELETE FROM issue WHERE issue.workspace_id = $1
),
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 427d3f706b..42c318c894 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -8,6 +8,8 @@ const (
EventIssueDeleted = "issue:deleted"
EventIssueMetadataChanged = "issue_metadata:changed"
EventIssueAttachmentsChanged = "issue_attachments:changed"
+ // Personal: one member's unread mark on an issue changed (MUL-8438).
+ EventIssueUnreadChanged = "issue_unread:changed"
// Comment events
EventCommentCreated = "comment:created"