Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(inbox): open a notification at the entry it is about (MUL-9340) (#10679)
Jiayuan Zhang845c9dd463e9
diff --git a/apps/mobile/components/issue/timeline-list.test.ts b/apps/mobile/components/issue/timeline-list.test.tsnew file mode 100644index 0000000000..6c794f74e3--- /dev/null+++ b/apps/mobile/components/issue/timeline-list.test.ts@@ -0,0 +1,178 @@+// @vitest-environment node+import type { ReactElement } from "react";+import type { Issue, TimelineEntry } from "@multica/core/types";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TimelineList } from "./timeline-list";++// Mobile has no React renderer, so a minimal hook runner drives the real+// component: state, refs, memos and effects with dependency checks, and+// re-renders until state settles.+const runner = vi.hoisted(() => {+ type Slot = { value?: unknown; deps?: readonly unknown[]; cleanup?: (() => void) | void };+ const slots: Slot[] = [];+ let cursor = 0;+ let dirty = false;+ let pending: { slot: Slot; effect: () => (() => void) | void }[] = [];++ const changed = (slot: Slot, deps?: readonly unknown[]) =>+ !deps || !slot.deps || deps.length !== slot.deps.length || deps.some((dep, i) => !Object.is(dep, slot.deps![i]));+ const next = (): Slot => (slots[cursor++] ??= {});++ const hooks = {+ useState<T>(initial: T | (() => T)) {+ const slot = next();+ if (!("value" in slot)) slot.value = typeof initial === "function" ? (initial as () => T)() : initial;+ const set = (update: T | ((prev: T) => T)) => {+ const value = typeof update === "function" ? (update as (prev: T) => T)(slot.value as T) : update;+ if (Object.is(value, slot.value)) return;+ slot.value = value;+ dirty = true;+ };+ return [slot.value as T, set] as const;+ },+ useRef<T>(initial: T) {+ const slot = next();+ if (!("value" in slot)) slot.value = { current: initial };+ return slot.value as { current: T };+ },+ useMemo<T>(create: () => T, deps: readonly unknown[]) {+ const slot = next();+ if (changed(slot, deps)) {+ slot.value = create();+ slot.deps = deps;+ }+ return slot.value as T;+ },+ useCallback<T>(callback: T, deps: readonly unknown[]) {+ return hooks.useMemo(() => callback, deps);+ },+ useEffect(effect: () => (() => void) | void, deps?: readonly unknown[]) {+ const slot = next();+ if (!changed(slot, deps)) return;+ slot.deps = deps;+ pending.push({ slot, effect });+ },+ };++ function render<P>(component: (props: P) => unknown, props: P) {+ let output: unknown;+ for (let pass = 0; pass < 10; pass++) {+ cursor = 0;+ dirty = false;+ output = component(props);+ const effects = pending;+ pending = [];+ for (const { slot, effect } of effects) {+ slot.cleanup?.();+ slot.cleanup = effect();+ }+ if (!dirty) return output;+ }+ throw new Error("render did not settle");+ }++ function reset() {+ for (const slot of slots) slot.cleanup?.();+ slots.length = 0;+ pending = [];+ }++ return { hooks, render, reset };+});++vi.mock("react", async (importOriginal) => ({+ ...await importOriginal<typeof import("react")>(),+ ...runner.hooks,+}));+vi.mock("react-native", () => ({+ ActivityIndicator: "ActivityIndicator", Pressable: "Pressable", RefreshControl: "RefreshControl", View: "View",+}));+vi.mock("@shopify/flash-list", () => ({ FlashList: "FlashList" }));+vi.mock("@expo/vector-icons", () => ({ Ionicons: "Ionicons" }));+vi.mock("@tanstack/react-query", () => ({ useQuery: () => ({ data: [] }) }));+vi.mock("@/components/ui/text", () => ({ Text: "Text" }));+vi.mock("./issue-header-card", () => ({ IssueHeaderCard: "IssueHeaderCard" }));+vi.mock("./issue-description", () => ({ IssueDescription: "IssueDescription" }));+vi.mock("./issue-reaction-row", () => ({ IssueReactionRow: "IssueReactionRow" }));+vi.mock("./activity-row", () => ({ ActivityRow: "ActivityRow" }));+vi.mock("./comment-card", () => ({ CommentCard: "CommentCard" }));+vi.mock("@/data/stores/last-viewed-store", () => ({+ useLastViewedStore: Object.assign(+ (select: (state: unknown) => unknown) => select({ markViewed: vi.fn() }),+ { getState: () => ({ getLastViewed: () => undefined }) },+ ),+}));+vi.mock("@/lib/markdown/image-sequence", () => ({ ImageSequenceProvider: "ImageSequenceProvider" }));+vi.mock("@/data/queries/issues", () => ({ issueAttachmentsOptions: () => ({}) }));+vi.mock("@/data/workspace-store", () => ({+ useWorkspaceStore: (select: (state: unknown) => unknown) => select({ currentWorkspaceId: "workspace-1" }),+}));+vi.mock("@/lib/use-color-scheme", () => ({ useColorScheme: () => ({ colorScheme: "light" }) }));+vi.mock("@/lib/theme", () => ({ THEME: { light: {} } }));+vi.mock("@/lib/i18n", () => ({ useT: () => ({ t: (key: string) => key }) }));+vi.mock("@/data/comment-select-store", () => ({+ useCommentSelectStore: (select: (state: unknown) => unknown) => select({ selectingId: null }),+}));++type Element = ReactElement<{ children?: unknown; data?: unknown[]; renderItem?: (info: { item: unknown }) => Element; highlightedCommentId?: string | null }>;++const root: TimelineEntry = {+ type: "comment", id: "root", actor_type: "member", actor_id: "user-1", content: "Earlier comment",+ parent_id: null, created_at: "2026-11-15T17:00:00Z", updated_at: "2026-11-15T17:00:00Z",+};+const notice: TimelineEntry = {+ ...root, id: "failure-notice", actor_type: "agent", actor_id: "agent-1", comment_type: "system",+ source_task_id: "task-1", parent_id: "root", created_at: "2026-11-15T17:01:00Z",+};++function findList(node: unknown): Element | undefined {+ if (!node || typeof node !== "object") return undefined;+ if (Array.isArray(node)) {+ for (const child of node) {+ const found = findList(child);+ if (found) return found;+ }+ return undefined;+ }+ const element = node as Element;+ if (element.type === "FlashList") return element;+ return findList(element.props?.children);+}++function open(entries: TimelineEntry[], nonce = "tap-1") {+ const tree = runner.render(TimelineList, {+ issue: { id: "issue-1", identifier: "MUL-1", description: "" } as Issue,+ entries,+ timelineLoading: false,+ refreshing: false,+ onRefresh: () => {},+ highlightCommentId: "task-1",+ highlightNonce: nonce,+ });+ const list = findList(tree)!;+ return {+ rows: list.props.data!.length,+ highlight: list.props.renderItem!({ item: list.props.data![0] }).props.highlightedCommentId,+ };+}++describe("TimelineList deep-link highlight", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => {+ runner.reset();+ vi.useRealTimers();+ });++ it("highlights a failure notice that arrives in a thread after a cached timeline opens", () => {+ expect(open([root])).toEqual({ rows: 1, highlight: null });+ expect(open([root, notice])).toEqual({ rows: 1, highlight: "failure-notice" });+ });++ it("highlights once per opening", () => {+ expect(open([root, notice]).highlight).toBe("failure-notice");+ vi.advanceTimersByTime(5000);+ expect(open([root, notice]).highlight).toBeNull();+ expect(open([root, { ...notice }]).highlight).toBeNull();+ expect(open([root, notice], "tap-2").highlight).toBe("failure-notice");+ });+});diff --git a/apps/mobile/components/issue/timeline-list.tsx b/apps/mobile/components/issue/timeline-list.tsxindex 7911cd559e..909a894333 100644--- a/apps/mobile/components/issue/timeline-list.tsx+++ b/apps/mobile/components/issue/timeline-list.tsx@@ -39,6 +39,7 @@ import { useColorScheme } from "@/lib/use-color-scheme";import { THEME } from "@/lib/theme";import { useT } from "@/lib/i18n";import { useCommentSelectStore } from "@/data/comment-select-store";+import { resolveTimelineHighlight } from "@/lib/inbox-display";interface Props {issue: Issue;@@ -129,7 +130,8 @@ export function TimelineList({// Gates single-shot per (commentId, nonce) tuple. Re-tap from inbox// bumps the nonce → ref no longer matches → effect re-fires.const lastStampRef = useRef<string | null>(null);- const [highlightedId, setHighlightedId] = useState<string | null>(null);+ const [highlight, setHighlight] = useState<{ id: string; stamp: string } | null>(null);+ const highlightedId = highlight?.id ?? null;// ── "New since last view" divider ─────────────────────────────────────// Snapshot the last-viewed timestamp ONCE on mount. Subsequent WS@@ -149,17 +151,30 @@ export function TimelineList({}, [data, lastViewedSnapshot]);const dividerScrolledPastRef = useRef(false);+ // A cached timeline can open without the target and gain it on refresh,+ // possibly as a reply that leaves the row count unchanged, so the+ // highlight is consumed only once its row exists.+ const highlightTarget = useMemo(+ () =>+ highlightCommentId && entries+ ? resolveTimelineHighlight(entries, highlightCommentId)+ : null,+ [entries, highlightCommentId],+ );+useEffect(() => {- if (!highlightCommentId || data.length === 0) return;+ if (!highlightCommentId || !highlightTarget) return;const stamp = `${highlightCommentId}:${highlightNonce ?? ""}`;if (lastStampRef.current === stamp) return;lastStampRef.current = stamp;+ setHighlight({ id: highlightTarget, stamp });+ }, [highlightCommentId, highlightNonce, highlightTarget]);- setHighlightedId(highlightCommentId);-- const fade = setTimeout(() => setHighlightedId(null), HIGHLIGHT_HOLD_MS);+ useEffect(() => {+ if (!highlight) return;+ const fade = setTimeout(() => setHighlight(null), HIGHLIGHT_HOLD_MS);return () => clearTimeout(fade);- }, [highlightCommentId, highlightNonce, data.length]);+ }, [highlight]);// ── New-comment-while-reading chip ────────────────────────────────────// After landing, if WS appends new entries while the user is NOT at thediff --git a/apps/mobile/lib/inbox-display.test.ts b/apps/mobile/lib/inbox-display.test.tsindex 5639e05be4..c5a6174b1a 100644--- a/apps/mobile/lib/inbox-display.test.ts+++ b/apps/mobile/lib/inbox-display.test.ts@@ -1,11 +1,12 @@import { describe, expect, it } from "vitest";-import type { InboxItem } from "@multica/core/types";+import type { InboxItem, TimelineEntry } from "@multica/core/types";import {deduplicateInboxItems,getAutopilotQuotaBody,getInboxDisplayTitle,getInboxNavigationTarget,getInboxNoticeBody,+ resolveTimelineHighlight,} from "./inbox-display";function item(overrides: Partial<InboxItem>): InboxItem {@@ -71,6 +72,66 @@ describe("deduplicateInboxItems", () => {]);expect(read[0]?.details?.comment_id).toBe("comment-2");});++ it("anchors an unread failed run at the run, and no unread entry at nothing", () => {+ const failed = deduplicateInboxItems([+ item({ id: "read", read: true, created_at: "2026-06-15T08:00:00Z", details: { comment_id: "comment-1" } }),+ item({ id: "failed", type: "task_failed", created_at: "2026-06-15T08:02:00Z", details: { task_id: "task-1" } }),+ ]);+ expect(failed[0]?.details?.comment_id).toBe("task-1");++ const status = deduplicateInboxItems([+ item({ id: "read", read: true, created_at: "2026-06-15T08:00:00Z", details: { comment_id: "comment-1" } }),+ item({ id: "status", type: "status_changed", created_at: "2026-06-15T08:02:00Z", details: { to: "in_review" } }),+ ]);+ expect(status[0]?.details?.comment_id).toBeUndefined();+ });++ it("lets an unread reply lead over an earlier unread reaction", () => {+ const merged = deduplicateInboxItems([+ item({ id: "reaction", type: "reaction_added", created_at: "2026-06-15T08:00:00Z", details: { comment_id: "old-comment" } }),+ item({ id: "reply", created_at: "2026-06-15T08:02:00Z", details: { comment_id: "comment-2" } }),+ ]);+ expect(merged[0]?.details?.comment_id).toBe("comment-2");+ });++ it("gives an unread app request no target, since mobile renders no requests", () => {+ const [row] = deduplicateInboxItems([+ item({ id: "comment", read: true, created_at: "2026-06-15T08:00:00Z", details: { comment_id: "comment-1" } }),+ item({ id: "app", type: "app_action_requested", created_at: "2026-06-15T08:02:00Z", details: { request_id: "request-1" } }),+ ]);+ expect(getInboxNavigationTarget(row!, "acme", "tap")?.params).toMatchObject({ id: "issue-1", highlight: undefined });+ });++ it("navigates a failed run's notification with its task id", () => {+ const [row] = deduplicateInboxItems([+ item({ id: "failed", type: "task_failed", created_at: "2026-06-15T08:02:00Z", details: { task_id: "task-1" } }),+ ]);+ expect(getInboxNavigationTarget(row!, "acme", "tap")?.params).toMatchObject({ highlight: "task-1" });+ });+});++describe("resolveTimelineHighlight", () => {+ const comment = (overrides: Partial<TimelineEntry>): TimelineEntry => ({+ type: "comment", id: "comment-1", actor_type: "member", actor_id: "user-1", content: "",+ parent_id: null, created_at: "2026-06-15T08:00:00Z", updated_at: "2026-06-15T08:00:00Z", ...overrides,+ });++ it("keeps an id the timeline has", () => {+ expect(resolveTimelineHighlight([comment({ id: "comment-1" })], "comment-1")).toBe("comment-1");+ });++ it("lands a task id on the failure notice its run posted", () => {+ const entries = [+ comment({ id: "agent-reply", actor_type: "agent", source_task_id: "task-1", comment_type: "comment" }),+ comment({ id: "notice", actor_type: "agent", source_task_id: "task-1", comment_type: "system" }),+ ];+ expect(resolveTimelineHighlight(entries, "task-1")).toBe("notice");+ });++ it("leaves a task id with nothing posted unmatched", () => {+ expect(resolveTimelineHighlight([comment({ id: "comment-1" })], "task-1")).toBeNull();+ });});describe("getInboxDisplayTitle", () => {diff --git a/apps/mobile/lib/inbox-display.ts b/apps/mobile/lib/inbox-display.tsindex 62ab293676..aea82d04e5 100644--- a/apps/mobile/lib/inbox-display.ts+++ b/apps/mobile/lib/inbox-display.ts@@ -6,7 +6,7 @@* the title a user sees in the mobile inbox MUST match what they see on* web for the same item. When the web version changes, sync this file.*/-import type { InboxItem } from "@multica/core/types";+import type { InboxItem, TimelineEntry } from "@multica/core/types";import { i18n } from "@/lib/i18n/singleton";function formatResetAt(value: string | undefined): string {@@ -135,6 +135,26 @@ export function getInboxNavigationTarget(return null;}+/**+ * The timeline row a deep-link `highlight` lands on. A failed run's+ * notification names its task; mobile renders no run rows, so the run shows+ * only as the failure notice it posted, and the link lands there. Null+ * while the timeline has no such row — a cached timeline may not have it+ * yet, and a run that posted nothing never will.+ */+export function resolveTimelineHighlight(+ entries: readonly TimelineEntry[],+ highlight: string,+): string | null {+ if (entries.some((entry) => entry.id === highlight)) return highlight;+ const posted = entries.filter(+ (entry) => entry.type === "comment" && entry.source_task_id === highlight,+ );+ return (+ posted.find((entry) => entry.comment_type === "system") ?? posted.at(-1)+ )?.id ?? null;+}+/*** Deduplicate inbox items by issue_id (Linear-style: one entry per issue).*@@ -149,8 +169,12 @@ export function getInboxNavigationTarget(* 2. Group by `issue_id` (fall back to `id` for items with no issue* attached — e.g. quick_create_failed).* 3. In each group, keep the newest by `created_at`.- * 4. Anchor the row where the reader left off: the oldest unread- * `comment_id` in the group, or the newest one once all are read.+ * 4. Anchor the row (`details.comment_id`) on the timeline entry it opens+ * at, as web's `withCommentAnchor` does: unread, the oldest unread+ * comment or failed run, a reaction only when nothing else unread has+ * one, and none when no unread notification has an entry; read, the+ * newest notification's entry. Mobile renders no app requests, so+ * unlike web an app request row gets no target of its own.* 5. Sort the result newest-first.*/export function deduplicateInboxItems(items: InboxItem[]): InboxItem[] {@@ -171,21 +195,28 @@ export function deduplicateInboxItems(items: InboxItem[]): InboxItem[] {const newest = group[0];if (!newest) continue;- const hasComment = (item: InboxItem) => !!item.details?.comment_id;- const commentId = (- group.findLast((item) => item.read !== true && hasComment(item)) ??- group.find(hasComment)- )?.details?.comment_id;+ const target = (item: InboxItem) =>+ item.details?.comment_id ||+ (item.type === "task_failed" ? item.details?.task_id : undefined) ||+ undefined;+ const unread = group.filter((item) => item.read !== true);+ const anchor =+ unread.length > 0+ ? (unread.findLast(+ (item) => item.type !== "reaction_added" && !!target(item),+ ) ?? unread.findLast((item) => !!target(item)))+ : group.find((item) => !!target(item));+ const anchorId = anchor ? target(anchor) : undefined;- if (commentId && newest.details?.comment_id !== commentId) {- merged.push({- ...newest,- details: { ...(newest.details ?? {}), comment_id: commentId },- });+ if (anchorId === newest.details?.comment_id) {+ merged.push(newest);continue;}-- merged.push(newest);+ const { comment_id: _dropped, ...details } = newest.details ?? {};+ merged.push({+ ...newest,+ details: anchorId ? { ...details, comment_id: anchorId } : details,+ });}return merged.sort((a, b) =>diff --git a/apps/mobile/vitest.config.ts b/apps/mobile/vitest.config.tsindex c0986b63e6..ccc612f1fb 100644--- a/apps/mobile/vitest.config.ts+++ b/apps/mobile/vitest.config.ts@@ -13,8 +13,9 @@ import path from "node:path";//// Co-located test files (foo.ts + foo.test.ts) match how the rest of the// monorepo organises vitest suites.-// The run cancel button and inbox have headless callback/prop tests with-// native modules mocked; these do not verify native rendering.+// The run cancel button, inbox and timeline list have headless+// callback/prop tests with native modules mocked; these do not verify+// native rendering.// App configuration tests also run here to cover native prebuild options// across environment variants without loading React Native.export default defineConfig({@@ -32,6 +33,7 @@ export default defineConfig({"data/**/*.test.ts","components/issue/run-cancel-button.test.ts","components/inbox/inbox-screen.test.ts",+ "components/issue/timeline-list.test.ts",],passWithNoTests: true,},diff --git a/packages/core/inbox/group.ts b/packages/core/inbox/group.tsindex 4589ec4091..6727926cb5 100644--- a/packages/core/inbox/group.ts+++ b/packages/core/inbox/group.ts@@ -19,19 +19,37 @@ export function groupInboxRows(items: readonly InboxItem[]): InboxItem[][] {}/**- * The row a group renders as, opening where the reader left off: the oldest- * unread comment, so the thread reads forward from there, or the newest- * comment once the issue is read. An app notification lands on its own- * request instead, so it never borrows one.+ * The timeline entry a notification is about: its comment, or the failed run+ * it reports, which the timeline addresses by task id like a comment.+ */+function inboxTimelineTarget(item: InboxItem): string | undefined {+ if (item.details?.comment_id) return item.details.comment_id;+ if (item.type === "task_failed" && item.details?.task_id) return item.details.task_id;+ return undefined;+}++/**+ * The row a group renders as, with `details.comment_id` naming the timeline+ * entry it opens at. Unread, it opens at the oldest unread comment or run, so+ * the issue reads forward from there; a reaction leads only when nothing+ * else unread has an entry, since the comment it marks is usually old.+ * Unread with no entry at all (a status change, an assignment), it opens+ * where the reader left off rather than at a comment already read. Read, it+ * opens at the newest notification's entry. An app notification lands on its+ * own request instead, so it never borrows one.*/export function withCommentAnchor(row: InboxItem, group: readonly InboxItem[]): InboxItem {if (row.type.startsWith("app_") && row.details?.request_id) return row;- const hasComment = (item: InboxItem) => !!item.details?.comment_id;+ const unread = group.filter((item) => item.read !== true);const anchor =- group.findLast((item) => item.read !== true && hasComment(item)) ?? group.find(hasComment);- const commentId = anchor?.details?.comment_id;- if (!commentId || commentId === row.details?.comment_id) return row;- return { ...row, details: { ...(row.details ?? {}), comment_id: commentId } };+ unread.length > 0+ ? (unread.findLast((item) => item.type !== "reaction_added" && !!inboxTimelineTarget(item)) ??+ unread.findLast((item) => !!inboxTimelineTarget(item)))+ : group.find((item) => !!inboxTimelineTarget(item));+ const target = anchor ? inboxTimelineTarget(anchor) : undefined;+ if (target === row.details?.comment_id) return row;+ const { comment_id: _dropped, ...details } = row.details ?? {};+ return { ...row, details: target ? { ...details, comment_id: target } : details };}/** One row per issue: its newest notification. Newest group first. */diff --git a/packages/core/inbox/queries.test.ts b/packages/core/inbox/queries.test.tsindex 52f06bdd8a..9056003947 100644--- a/packages/core/inbox/queries.test.ts+++ b/packages/core/inbox/queries.test.ts@@ -100,6 +100,58 @@ describe("deduplicateInboxItems", () => {expect(merged[0]?.details?.comment_id).toBe("comment-2");});+ it("opens an unread notification with no comment where the reader left off, not at a read comment", () => {+ const merged = deduplicateInboxItems([+ item({ id: "read-comment", read: true, created_at: "2026-06-15T08:00:00Z", details: { comment_id: "comment-1" } }),+ item({ id: "status", type: "status_changed", created_at: "2026-06-15T08:02:00Z", details: { from: "todo", to: "in_review" } }),+ ]);++ expect(merged[0]?.id).toBe("status");+ expect(merged[0]?.details).toEqual({ from: "todo", to: "in_review" });+ });++ it("drops the row's own read comment when only a notification without one is unread", () => {+ const merged = deduplicateInboxItems([+ item({ id: "status", type: "status_changed", created_at: "2026-06-15T08:00:00Z", details: { to: "in_review" } }),+ item({ id: "read-comment", read: true, created_at: "2026-06-15T08:02:00Z", details: { comment_id: "comment-1" } }),+ ]);++ expect(merged[0]?.id).toBe("read-comment");+ expect(merged[0]?.details).toEqual({});+ });++ it("opens an unread failed run at the run", () => {+ const merged = deduplicateInboxItems([+ item({ id: "read-comment", read: true, created_at: "2026-06-15T08:00:00Z", details: { comment_id: "comment-1" } }),+ item({ id: "failed", type: "task_failed", created_at: "2026-06-15T08:02:00Z", details: { task_id: "task-1" } }),+ ]);++ expect(merged[0]?.details).toEqual({ task_id: "task-1", comment_id: "task-1" });+ });++ it("leaves a reaction to lead only when nothing else unread has an entry", () => {+ const withReply = deduplicateInboxItems([+ item({ id: "reaction", type: "reaction_added", created_at: "2026-06-15T08:00:00Z", details: { emoji: "👍", comment_id: "old-comment" } }),+ item({ id: "reply", created_at: "2026-06-15T08:02:00Z", details: { comment_id: "comment-2" } }),+ ]);+ expect(withReply[0]?.details?.comment_id).toBe("comment-2");++ const alone = deduplicateInboxItems([+ item({ id: "reaction", type: "reaction_added", created_at: "2026-06-15T08:00:00Z", details: { emoji: "👍", comment_id: "old-comment" } }),+ item({ id: "status", type: "status_changed", created_at: "2026-06-15T08:02:00Z", details: { to: "in_review" } }),+ ]);+ expect(alone[0]?.details?.comment_id).toBe("old-comment");+ });++ it("opens a read issue at the newest notification's entry, a reaction included", () => {+ const merged = deduplicateInboxItems([+ item({ id: "reply", read: true, created_at: "2026-06-15T08:00:00Z", details: { comment_id: "comment-2" } }),+ item({ id: "reaction", type: "reaction_added", read: true, created_at: "2026-06-15T08:02:00Z", details: { emoji: "👍", comment_id: "old-comment" } }),+ ]);++ expect(merged[0]?.details?.comment_id).toBe("old-comment");+ });+it("drops archived rows so an optimistic archive leaves the list at once", () => {const merged = deduplicateInboxItems([item({ id: "active", issue_id: "issue-1" }),diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 5ac2551881..87c3362580 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -2100,6 +2100,53 @@ describe("IssueDetail (shared)", () => {await waitFor(() => expect(container.querySelector(`#comment-failure-notice [data-run-id="${task.id}"]`)).not.toBeNull());expectStatedOnce(container.querySelector("#comment-failure-notice") as HTMLElement);});++ // A task_failed notification names the task (MUL-9340); the run renders+ // under its notice's id when it left one, and under the task id otherwise.+ describe("lands a failed run's notification", () => {+ const taskId = failedRun().id;++ it.each(["failure-notice", taskId])("in a thread with a notice, through %s", async (target) => {+ const root = mockTimeline[0]!;+ const task = failedRun({ trigger_comment_id: root.id, delivered_comment_ids: [root.id] });+ mockApiObj.listTimeline.mockResolvedValue([root, notice(task, root.id)]);+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);+ const { container } = renderIssueDetailWithHighlight(target);++ await waitFor(() => expect(container.querySelector("#comment-failure-notice [data-run-id]")).not.toBeNull());+ await waitFor(() => expect(hasHighlightedCommentBackground(container.querySelector("#comment-failure-notice"))).toBe(true));+ });++ it("in a thread without a notice, through the task id", async () => {+ const root = mockTimeline[0]!;+ const task = failedRun({ trigger_comment_id: root.id, delivered_comment_ids: [root.id] });+ mockApiObj.listTimeline.mockResolvedValue([root]);+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);+ const { container } = renderIssueDetailWithHighlight(task.id);++ await waitFor(() => expect(container.querySelector(`#comment-${task.id}`)).not.toBeNull());+ await waitFor(() => expect(hasHighlightedCommentBackground(container.querySelector(`#comment-${task.id}`))).toBe(true));+ });++ it("at the top level with a notice, through the task id", async () => {+ const task = failedRun();+ mockApiObj.listTimeline.mockResolvedValue([...mockTimeline, notice(task, null)]);+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);+ const { container } = renderIssueDetailWithHighlight(task.id);++ await waitFor(() => expect(container.querySelector(`#comment-failure-notice [data-run-comment-id="${task.id}"]`)).not.toBeNull());+ await waitFor(() => expect(hasHighlightedCommentBackground(container.querySelector("#comment-failure-notice"))).toBe(true));+ });++ it("at the top level without a notice, through the task id", async () => {+ const task = failedRun();+ mockApiObj.listTasksByIssue.mockResolvedValue([task]);+ const { container } = renderIssueDetailWithHighlight(task.id);++ await waitFor(() => expect(container.querySelector(`#comment-${task.id}`)).not.toBeNull());+ await waitFor(() => expect(hasHighlightedCommentBackground(container.querySelector(`#comment-${task.id}`))).toBe(true));+ });+ });});// Details is creator + immutable timestamps, so it ranks below thediff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 14cfabdbbd..e266b59f15 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -1995,29 +1995,47 @@ 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(() => {+ // The anchor a deep-link target renders under. A failed run's notification+ // names its task, but a run that left a reply (its failure notice included)+ // renders under the reply's id, in a thread slot and at the top level alike.+ const highlightTargetId = useMemo(() => {if (!highlightCommentId) return undefined;- const replyRoot = replyToRoot.get(highlightCommentId);+ const topLevel = items.find((it) => it.kind === "run" && it.run.task.id === highlightCommentId);+ if (topLevel) return topLevel.id;+ for (const runs of commentRuns.values()) {+ const run = runs.find((candidate) => candidate.task.id === highlightCommentId);+ if (!run) continue;+ const reply = run.hasReply && run.commentId+ ? displayTimeline.find((entry) => entry.id === run.commentId)+ : undefined;+ return reply && !isDeletedComment(reply) ? reply.id : run.task.id;+ }+ return highlightCommentId;+ }, [highlightCommentId, items, commentRuns, displayTimeline]);++ // Thread root of a deep-link target. A run 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 (!highlightTargetId) return undefined;+ const replyRoot = replyToRoot.get(highlightTargetId);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]);+ }, [highlightTargetId, highlightCommentId, replyToRoot, commentRuns]);// Deep-link target index in the flat items array. For root comments this is// 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 (!highlightTargetId) return -1;+ const direct = items.findIndex((it) => it.id === highlightTargetId);if (direct >= 0) return direct;if (!highlightRootId) return -1;return items.findIndex((it) => it.id === highlightRootId);- }, [items, highlightCommentId, highlightRootId]);+ }, [items, highlightTargetId, highlightRootId]);// One entry per comment thread (folded resolved bars included), activity// groups skipped. Derived from the same flat `items` array Virtuoso renders@@ -2083,11 +2101,17 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = truserId: user?.id,resetKey: id,});- const pendingHighlight = !!highlightCommentId && consumedHighlightId !== highlightCommentId;+ const timelineReady = !issueLoading && !timelineLoading && !commentTasksLoading;+ // A target the loaded timeline lacks (its comment was deleted) has nothing+ // to land on, so the issue opens where the reader left off instead of at+ // the top. If it arrives later, the landing still runs.+ const highlightMissing = timelineReady && targetIdx < 0;+ const pendingHighlight =+ !!highlightCommentId && consumedHighlightId !== highlightCommentId && !highlightMissing;const { pending: readingAnchor, complete: completeAnchorRestore } = useIssueTimelineAnchor({containerKey: scrollContainerKey,container: scrollContainerEl,- ready: !issueLoading && !timelineLoading && !commentTasksLoading,+ ready: timelineReady,skipRestore: isPeek || pendingHighlight,});useEffect(() => {@@ -2555,7 +2579,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trreturn;}- const rootId = highlightRootId ?? highlightCommentId;+ const targetId = highlightTargetId ?? highlightCommentId;+ const rootId = highlightRootId ?? targetId;const collapse = useCommentCollapseStore.getState();if (collapse.isCollapsed(id, rootId)) collapse.toggle(id, rootId);if (rootId) {@@ -2572,7 +2597,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trrootItem.entry,timelineView.threadReplies.get(rootId) ?? EMPTY_REPLIES,);- if (resolution.kind === "reply" && resolution.resolutionId !== highlightCommentId) {+ if (resolution.kind === "reply" && resolution.resolutionId !== targetId) {toggleResolvedExpand(rootId, true);return;}@@ -2583,9 +2608,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// carries has no anchor to scroll to and no row to flash. Land on the// comment above where it was; the id itself stays this landing's identity// for the guards and the memento below.- const threadRootId = rootId ?? highlightCommentId;+ const threadRootId = rootId ?? targetId;const landingId = commentLandingTarget(- highlightCommentId,+ targetId,threadRootId,timelineView.threadReplies.get(threadRootId) ?? EMPTY_REPLIES,);@@ -2628,7 +2653,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trinterruptedLandingRef.current = highlightCommentId;}};- }, [highlightCommentId, highlightRequestToken, activeDeliverableJump, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand, isFlatTimeline, measuredTimelineId, timelineLoading, commentTasksLoading, flashJumpTarget]);+ }, [highlightCommentId, highlightTargetId, highlightRequestToken, activeDeliverableJump, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand, isFlatTimeline, measuredTimelineId, timelineLoading, commentTasksLoading, flashJumpTarget]);const descEditorRef = useRef<ContentEditorRef>(null);const descriptionEditingRef = useRef(false);diff --git a/packages/views/issues/hooks/use-issue-timeline-anchor.test.tsx b/packages/views/issues/hooks/use-issue-timeline-anchor.test.tsxnew file mode 100644index 0000000000..508bb2ac3d--- /dev/null+++ b/packages/views/issues/hooks/use-issue-timeline-anchor.test.tsx@@ -0,0 +1,53 @@+import type { ReactNode } from "react";+import { renderHook } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { ScrollRestorationProvider } from "../../platform/scroll-restoration";+import { useIssueTimelineAnchor } from "./use-issue-timeline-anchor";++const saved = { commentId: "comment-1", offset: 40 };++function wrapper({ children }: { children: ReactNode }) {+ return (+ <ScrollRestorationProvider+ adapter={{+ get: () => undefined,+ getViewState: (key) => (key === "timeline-anchor:issue-1" ? JSON.stringify(saved) : undefined),+ setViewState: () => {},+ }}+ >+ {children}+ </ScrollRestorationProvider>+ );+}++function render(initial: { ready: boolean; skipRestore: boolean }) {+ return renderHook(+ (props: { ready: boolean; skipRestore: boolean }) =>+ useIssueTimelineAnchor({ containerKey: "issue-1", container: null, ...props }),+ { initialProps: initial, wrapper },+ );+}++describe("useIssueTimelineAnchor", () => {+ it("restores the reading position when a landing turns out to have no target", () => {+ const { result, rerender } = render({ ready: false, skipRestore: true });+ expect(result.current.pending).toBeNull();++ rerender({ ready: true, skipRestore: false });+ expect(result.current.pending).toEqual(saved);+ });++ it("drops the reading position for a landing that had a target, even once it is consumed", () => {+ const { result, rerender } = render({ ready: false, skipRestore: true });+ rerender({ ready: true, skipRestore: true });+ expect(result.current.pending).toBeNull();++ rerender({ ready: true, skipRestore: false });+ expect(result.current.pending).toBeNull();+ });++ it("restores the reading position when nothing lands", () => {+ const { result } = render({ ready: true, skipRestore: false });+ expect(result.current.pending).toEqual(saved);+ });+});diff --git a/packages/views/issues/hooks/use-issue-timeline-anchor.ts b/packages/views/issues/hooks/use-issue-timeline-anchor.tsindex e11d4620ce..d91478e4ba 100644--- a/packages/views/issues/hooks/use-issue-timeline-anchor.ts+++ b/packages/views/issues/hooks/use-issue-timeline-anchor.ts@@ -32,9 +32,11 @@ export function useIssueTimelineAnchor({const snapshot = snapshotRef.current;// A fresh notification selection owns the landing, even after it marks its// highlight consumed. It must not revive the previous reading position.- if (skipRestore) snapshot.anchor = null;+ // Dropped only once the timeline is ready: until then a landing can still+ // turn out to have no target, and the reader's place is the fallback.+ if (skipRestore && ready) snapshot.anchor = null;const [completed, setCompleted] = useState<AnchorSnapshot | null>(null);- const pending = completed !== snapshot ? snapshot.anchor : null;+ const pending = !skipRestore && completed !== snapshot ? snapshot.anchor : null;const complete = useCallback(() => setCompleted(snapshot), [snapshot]);useEffect(() => {diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex 0000fbdff6..e56e2d8787 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -1310,6 +1310,7 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {}agentID, _ := payload["agent_id"].(string)issueID, _ := payload["issue_id"].(string)+ taskID, _ := payload["task_id"].(string)if issueID == "" {return}@@ -1325,6 +1326,13 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {exclude[agentID] = true}+ // The task id lets opening the notification land on the failed run+ // in the issue's timeline.+ details := emptyDetails+ if taskID != "" {+ details, _ = json.Marshal(map[string]string{"task_id": taskID})+ }+notifySubscribers(ctx, queries, bus, issueID, issue.Status, e.WorkspaceID,events.Event{Type: e.Type,@@ -1334,7 +1342,7 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {},exclude, "task_failed", "action_required",issue.Title, "",- emptyDetails)+ details)})}diff --git a/server/cmd/server/notification_listeners_test.go b/server/cmd/server/notification_listeners_test.goindex 4df5e0115d..244b5bb454 100644--- a/server/cmd/server/notification_listeners_test.go+++ b/server/cmd/server/notification_listeners_test.go@@ -2,6 +2,7 @@ package mainimport ("context"+ "encoding/json""strings""testing"@@ -869,6 +870,13 @@ func TestNotification_TaskFailed(t *testing.T) {if creatorItems[0].Severity != "action_required" {t.Fatalf("expected severity 'action_required', got %q", creatorItems[0].Severity)}+ var details map[string]string+ if err := json.Unmarshal(creatorItems[0].Details, &details); err != nil {+ t.Fatalf("unmarshal details: %v", err)+ }+ if details["task_id"] != "00000000-0000-0000-0000-bbbbbbbbbbbb" {+ t.Fatalf("expected details to name the failed task, got %v", details)+ }}// TestNotification_PriorityChanged verifies that all subscribers except the actor