Skip to content

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

Go
215 KB
Raw Blame
import { forwardRef, useEffect, useRef, useState, useImperativeHandle } from "react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { AgentTask, Attachment, InboxItem, Issue, IssueStatusEntry, Label, TimelineEntry } from "@multica/core/types";
import { issueKeys } from "@multica/core/issues/queries";
import { issueStatusKeys } from "@multica/core/issue-statuses";
import { I18nProvider } from "@multica/core/i18n/react";
import { ApiError } from "@multica/core/api/client";
import { toast } from "sonner";
import { useResolvedExpandStore } from "@multica/core/issues/stores/resolved-expand-store";
import { useCommentCollapseStore } from "@multica/core/issues/stores";
import {
  DEFAULT_SUB_ISSUE_ROW_PROPERTIES,
  useSubIssueDisplayStore,
} from "@multica/core/issues/stores/sub-issue-display-store";
import enAgents from "../../locales/en/agents.json";
import enCommon from "../../locales/en/common.json";
import enInbox from "../../locales/en/inbox.json";
import enIssues from "../../locales/en/issues.json";
import { useIssueSidebarSectionsStore } from "@multica/core/issues/stores/issue-sidebar-sections-store";
import { useSubIssuesCollapseStore } from "@multica/core/issues/stores/sub-issues-collapse-store";
import { configureShortcutPlatform } from "@multica/core/shortcuts";
import { useAppearanceStore } from "@multica/core/appearance";
import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";

const TEST_RESOURCES = { en: { agents: enAgents, common: enCommon, inbox: enInbox, issues: enIssues } };

const mockViewport = vi.hoisted(() => ({ isMobile: false }));
const mockLocalDirectoryHint = vi.hoisted(() => vi.fn());
vi.mock("../../projects/components/local-directory-hint", () => ({
  LocalDirectoryHint: (props: unknown) => {
    mockLocalDirectoryHint(props);
    return null;
  },
}));

// Counts MockContentEditor mounts. This pins the description to exactly one
// eager editor per issue and catches stale editor reuse across issue switches.
const contentEditorMounts = vi.hoisted(() => ({ count: 0 }));
// Every ReadonlyContent render, by content. A comment card renders its body
// through it, so this counts card renders without reaching into the card.
const readonlyContentRenders = vi.hoisted(() => [] as string[]);
const descriptionSelectionAction = vi.hoisted(() => ({ current: undefined as { label: string; onSelect: () => void } | undefined }));
// Stable empty-attachments reference: the real store returns a shared constant
// so the `useCommentDraftStore(s => s.getAttachments(key))` selector keeps a
// stable identity. A fresh `[]` per call would loop useSyncExternalStore.
const emptyDraftAttachments = vi.hoisted(() => [] as unknown[]);

vi.mock("@multica/ui/hooks/use-mobile", () => ({
  useIsMobile: () => mockViewport.isMobile,
}));

// useWorkspaceId() derives from useCurrentWorkspace (relative import inside
// @multica/core/hooks.tsx). vi.mock("@multica/core/paths") only intercepts
// the bare-specifier, not the internal relative import. Mock the hooks module
// directly so the bridge hook returns the test UUID.
vi.mock("@multica/core/hooks", () => ({
  useWorkspaceId: () => "ws-1",
}));

// ---------------------------------------------------------------------------
// Mocks
// ---------------------------------------------------------------------------

// Mock @multica/core/auth
const mockAuthUser = { id: "user-1", email: "[email protected]", name: "Test User" };
vi.mock("@multica/core/auth", () => ({
  useAuthStore: Object.assign(
    (selector?: any) => {
      const state = { user: mockAuthUser, isAuthenticated: true };
      return selector ? selector(state) : state;
    },
    { getState: () => ({ user: mockAuthUser, isAuthenticated: true }) },
  ),
  registerAuthStore: vi.fn(),
  createAuthStore: vi.fn(),
}));

// Mock @multica/core/workspace/hooks
vi.mock("@multica/core/workspace/hooks", () => ({
  useActorName: () => ({
    getMemberName: (id: string) => (id === "user-1" ? "Test User" : "Unknown"),
    getAgentName: (id: string) => (id === "agent-1" ? "Claude Agent" : "Unknown Agent"),
    getActorName: (type: string, id: string) => {
      if (type === "member" && id === "user-1") return "Test User";
      if (type === "agent" && id === "agent-1") return "Claude Agent";
      return "Unknown";
    },
    getActorInitials: (type: string) => (type === "member" ? "TU" : "CA"),
    getActorAvatarUrl: () => null,
  }),
}));

// Mock workspace queries
vi.mock("@multica/core/workspace/queries", () => ({
  memberListOptions: () => ({
    queryKey: ["workspaces", "ws-1", "members"],
    queryFn: () => mockApiObj.listMembers(),
  }),
  agentListOptions: () => ({
    queryKey: ["workspaces", "ws-1", "agents"],
    queryFn: () => mockApiObj.listAgents(),
  }),
  squadListOptions: () => ({
    queryKey: ["workspaces", "ws-1", "squads"],
    queryFn: () => Promise.resolve([]),
  }),
  workspaceListOptions: () => ({
    queryKey: ["workspaces"],
    queryFn: () => Promise.resolve([{ id: "ws-1", name: "Test WS", slug: "test" }]),
  }),
}));

// Mock @multica/core/paths — after the URL-driven workspace refactor,
// useCurrentWorkspace / useWorkspacePaths derive from the workspace slug in
// URL Context. Tests don't mount a real route, so we short-circuit to fixtures.
vi.mock("@multica/core/paths", async () => {
  const actual = await vi.importActual<typeof import("@multica/core/paths")>(
    "@multica/core/paths",
  );
  return {
    ...actual,
    useCurrentWorkspace: () => ({ id: "ws-1", name: "Test WS", slug: "test" }),
    useWorkspacePaths: () => actual.paths.workspace("test"),
  };
});

const settingsPush = vi.hoisted(() => vi.fn());

// Mock navigation
vi.mock("../../navigation", async () => ({
  // Real hold hook (pure React) the header's Inbox actions read through.
  ...(await vi.importActual<typeof import("../../navigation/use-held-until-arrival")>(
    "../../navigation/use-held-until-arrival",
  )),
  // Forwards ref: the header wraps the link in `TruncatedTooltip`, which
  // measures the anchor it clones, exactly as the real AppLink supports.
  AppLink: forwardRef<HTMLAnchorElement, any>(function MockAppLink(
    { children, href, ...props },
    ref,
  ) {
    return (
      <a ref={ref} href={href} {...props}>
        {children}
      </a>
    );
  }),
  useNavigation: () => ({
    push: settingsPush,
    pathname: "/issues/issue-1",
    getShareableUrl: (p: string) => `https://app.multica.com${p}`,
  }),
  useBackOrReplace: () => vi.fn(),
  NavigationProvider: ({ children }: { children: React.ReactNode }) => children,
}));

// Mock editor components (Tiptap requires real DOM)
vi.mock("../../editor", async () => ({
  // Real lazy-mount controller (pure React, no Tiptap) so readonly-first
  // shell → activate → ready flows behave exactly as in production.
  ...(await vi.importActual<typeof import("../../editor/use-lazy-editor")>(
    "../../editor/use-lazy-editor",
  )),
  // Real submit gate (pure React) — see comment-composers.test.tsx.
  ...(await vi.importActual<typeof import("../../editor/use-upload-gate")>(
    "../../editor/use-upload-gate",
  )),
  // Real await-then-render submit hook (pure React) so comment/reply/edit
  // composers run the production submit path.
  ...(await vi.importActual<typeof import("../../editor/use-composer-submit")>(
    "../../editor/use-composer-submit",
  )),
  useEditorUpload: () => ({
    uploadWithToast: vi.fn(),
    upload: vi.fn(),
    uploading: false,
  }),
  useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
  FileDropOverlay: () => null,
  // No-op so comment-card's AttachmentList can render without hitting the
  // real API singleton; tests that care about download wiring should write
  // dedicated specs against `use-download-attachment.test.tsx`.
  useDownloadAttachment: () => vi.fn(),
  // Inert preview hook — comment-card's AttachmentList uses it to gate the
  // Eye button. Dedicated coverage lives in attachment-preview-modal.test.tsx.
  useAttachmentPreview: () => ({
    open: vi.fn(),
    tryOpen: () => false,
    modal: null,
  }),
  // Pass-through: the detail page wraps its column in the preview-sequence
  // provider, but paging between files is covered in
  // preview-sequence-context.test.tsx against the real provider.
  PreviewSequenceProvider: ({ children }: { children: React.ReactNode }) =>
    children,
  usePreviewSequence: () => ({ openAt: () => false }),
  collectPreviewSequence: () => [],
  // The real provider is plain context; attachment-thumbnail.test.tsx covers it.
  ...(await vi.importActual<typeof import("../../editor/image-thumbnails-context")>(
    "../../editor/image-thumbnails-context",
  )),
  // Comment attachments render as their filename — the viewer and file cards
  // have their own suites.
  AttachmentDownloadProvider: ({ children }: { children: React.ReactNode }) =>
    children,
  Attachment: ({ attachment }: { attachment: { filename?: string } }) => (
    <span data-testid="comment-attachment">{attachment.filename}</span>
  ),
  isPreviewable: () => false,
  ReadonlyContent: ({ content }: { content: string }) => {
    readonlyContentRenders.push(content);
    return <div data-testid="readonly-content">{content}</div>;
  },
  ContentEditor: forwardRef(function MockContentEditor(
    {
      defaultValue,
      value: syncedValue,
      onUpdate,
      placeholder,
      flushPendingOnUnmount,
      onReady,
      selectionAction,
    }: any,
    ref: any,
  ) {
    const initialValue = syncedValue ?? defaultValue ?? "";
    if (syncedValue !== undefined) descriptionSelectionAction.current = selectionAction;
    const valueRef = useRef(initialValue);
    const baseRef = useRef(initialValue);
    const [editorValue, setEditorValue] = useState(initialValue);
    // Mirrors the real editor's dirty guard: once the user has typed, an
    // external `value` change is refused so it cannot clobber unsaved bytes.
    // Only the imperative adoptContent channel lands after that point.
    const dirtyRef = useRef(false);
    useEffect(() => {
      contentEditorMounts.count += 1;
      onReady?.();
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    useEffect(() => {
      if (syncedValue === undefined || dirtyRef.current) return;
      valueRef.current = syncedValue;
      baseRef.current = syncedValue;
      setEditorValue(syncedValue);
    }, [syncedValue]);
    useImperativeHandle(ref, () => ({
      getMarkdown: () => valueRef.current,
      clearContent: () => {
        valueRef.current = "";
        dirtyRef.current = false;
        setEditorValue("");
      },
      // The real handle applies content the `value` prop cannot land (a dirty
      // editor refuses external syncs) and does so without emitting an update.
      adoptContent: (markdown: string) => {
        valueRef.current = markdown;
        baseRef.current = markdown;
        dirtyRef.current = false;
        setEditorValue(markdown);
      },
      focus: () => {},
      focusAtCoords: () => {},
      // The top-level composer blurs after a posted comment (afterAccepted).
      blur: () => {},
      // Read by the submit-time upload gate; no uploads are exercised here.
      hasActiveUploads: () => false,
      // Placeholder rebuild contract: the real handle draws a card for an
      // upload the document is not showing and reports whether it landed.
      // Mocks track ids only — no document to draw into.
      insertUploadPlaceholder: () => true,
      settleUploadPlaceholder: () => false,
      uploadFile: () => {},
    }));
    return (
      <textarea
        value={editorValue}
        onChange={(e) => {
          valueRef.current = e.target.value;
          dirtyRef.current = true;
          setEditorValue(e.target.value);
          onUpdate?.(e.target.value, baseRef.current);
        }}
        placeholder={placeholder}
        data-testid="rich-text-editor"
        data-flush-on-unmount={flushPendingOnUnmount ? "true" : undefined}
      />
    );
  }),
  TitleEditor: forwardRef(function MockTitleEditor(
    { defaultValue, placeholder, onBlur, onChange, onReady }: any,
    ref: any,
  ) {
    const valueRef = useRef(defaultValue || "");
    const [value, setValue] = useState(defaultValue || "");
    useEffect(() => {
      onReady?.();
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    useImperativeHandle(ref, () => ({
      getText: () => valueRef.current,
      focus: () => {},
      focusAtCoords: () => {},
    }));
    return (
      <input
        value={value}
        onChange={(e) => {
          valueRef.current = e.target.value;
          setValue(e.target.value);
          onChange?.(e.target.value);
        }}
        onBlur={() => onBlur?.(valueRef.current)}
        placeholder={placeholder}
        data-testid="title-editor"
      />
    );
  }),
}));

// Mock common components
vi.mock("../../common/actor-avatar", () => ({
  ActorAvatar: ({ actorType, actorId }: any) => (
    <span data-testid="actor-avatar">
      {actorType}:{actorId}
    </span>
  ),
}));

vi.mock("../../projects/components/project-picker", () => ({
  ProjectPicker: () => <span data-testid="project-picker">Project</span>,
}));

// Mock api
const mockApiObj = vi.hoisted(() => ({
  getBaseUrl: () => "",
  getIssue: vi.fn(),
  listTimeline: vi.fn().mockResolvedValue([]),
  listComments: vi.fn().mockResolvedValue([]),
  createComment: vi.fn(),
  updateComment: vi.fn(),
  deleteComment: vi.fn(),
  deleteIssue: vi.fn(),
  updateIssue: vi.fn(),
  listIssueSubscribers: vi.fn().mockResolvedValue([]),
  subscribeToIssue: vi.fn().mockResolvedValue(undefined),
  unsubscribeFromIssue: vi.fn().mockResolvedValue(undefined),
  unsubscribeFromIssueSubtree: vi.fn().mockResolvedValue(undefined),
  listTasksByIssue: vi.fn().mockResolvedValue([]),
  rerunIssue: vi.fn(),
  listTaskMessages: vi.fn().mockResolvedValue([]),
  listChildIssues: vi.fn().mockResolvedValue({ issues: [] }),
  getChildIssueProgress: vi.fn().mockResolvedValue({ progress: [] }),
  getAgentTaskSnapshot: vi.fn().mockResolvedValue([]),
  // The sub-issues header chip reads this narrowed to the parent issue.
  getWorkspaceWorkingAgents: vi.fn().mockResolvedValue([]),
  listProperties: vi.fn().mockResolvedValue({ properties: [], total: 0 }),
  listIssues: vi.fn().mockResolvedValue({ issues: [], total: 0 }),
  uploadFile: vi.fn(),
  listIssueReactions: vi.fn().mockResolvedValue([]),
  addIssueReaction: vi.fn(),
  removeIssueReaction: vi.fn(),
  listAttachments: vi.fn().mockResolvedValue([]),
  addCommentReaction: vi.fn(),
  removeCommentReaction: vi.fn(),
  listMembers: vi.fn().mockResolvedValue([{ user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" }]),
  listAgents: vi.fn().mockResolvedValue([]),
  getAgent: vi.fn().mockResolvedValue(null),
  listRuntimes: vi.fn().mockResolvedValue([]),
  getProject: vi.fn(),
  listProjects: vi.fn().mockResolvedValue({ projects: [] }),
  listIssueSystemWakeups: vi.fn().mockResolvedValue([]),
  listPins: vi.fn().mockResolvedValue([]),
  createIssueCollabTicket: vi.fn().mockResolvedValue({ enabled: false }),
}));

vi.mock("@multica/core/api", () => ({
  api: mockApiObj,
  getApi: () => mockApiObj,
  setApiInstance: vi.fn(),
  errorCode: (error: unknown) =>
    typeof error === "object" && error !== null && "body" in error
      ? (error as { body?: { code?: string } }).body?.code
      : undefined,
}));

// Mock issue config
// Use the real status configuration so category fixtures cannot drift.

// Mock recent issues store
const mockRecordVisit = vi.fn();
vi.mock("@multica/core/issues/stores", async () => ({
  // Real store, not a stub: resolved-thread expand/collapse behavior under
  // test runs through it. Deep import keeps the persisted sibling stores
  // (which need localStorage) out of this mock.
  ...(await vi.importActual<
    typeof import("@multica/core/issues/stores/resolved-expand-store")
  >("@multica/core/issues/stores/resolved-expand-store")),
  // Real store: sub-issue display tests drive it with setState, and the
  // component reads it through the barrel — both must hit the same instance.
  ...(await vi.importActual<
    typeof import("@multica/core/issues/stores/sub-issue-display-store")
  >("@multica/core/issues/stores/sub-issue-display-store")),
  // Real store, in-memory (no localStorage): backs the sub-issues section's
  // collapsed state.
  ...(await vi.importActual<
    typeof import("@multica/core/issues/stores/sub-issues-collapse-store")
  >("@multica/core/issues/stores/sub-issues-collapse-store")),
  // Real store, in-memory: the sidebar reads its section order and visibility.
  ...(await vi.importActual<
    typeof import("@multica/core/issues/stores/issue-sidebar-sections-store")
  >("@multica/core/issues/stores/issue-sidebar-sections-store")),
  useRecentIssuesStore: Object.assign(
    (selector?: any) => {
      const state = { byWorkspace: {}, recordVisit: mockRecordVisit, pruneWorkspaces: vi.fn() };
      return selector ? selector(state) : state;
    },
    {
      getState: () => ({
        byWorkspace: {},
        recordVisit: mockRecordVisit,
        pruneWorkspaces: vi.fn(),
      }),
    },
  ),
  selectRecentIssues: () => () => [],
  // Reactive in-memory stand-in: a quick-jump to a reply reopens a thread the
  // reader collapsed, so the card has to re-render when `toggle` runs.
  useCommentCollapseStore: (await vi.importActual<typeof import("zustand")>("zustand")).create<{
    collapsedByIssue: Record<string, string[]>;
    isCollapsed: (issueId: string, commentId: string) => boolean;
    toggle: (issueId: string, commentId: string) => void;
  }>()((set, get) => ({
    collapsedByIssue: {},
    isCollapsed: (issueId, commentId) => get().collapsedByIssue[issueId]?.includes(commentId) ?? false,
    toggle: (issueId, commentId) =>
      set((s) => {
        const current = s.collapsedByIssue[issueId] ?? [];
        return {
          collapsedByIssue: {
            ...s.collapsedByIssue,
            [issueId]: current.includes(commentId)
              ? current.filter((c) => c !== commentId)
              : [...current, commentId],
          },
        };
      }),
  })),
  useCommentDraftStore: Object.assign(
    (selector?: any) => {
      const state = {
        drafts: {} as Record<string, { content: string; attachments: unknown[]; updatedAt: number }>,
        getDraft: () => undefined,
        getAnnotations: () => emptyDraftAttachments,
        getAttachments: () => emptyDraftAttachments,
        getUploads: () => emptyDraftAttachments,
        setDraft: () => {},
        setAttachments: () => {},
        addUpload: () => {},
        settleUpload: () => {},
        failUpload: () => {},
        removeUpload: () => {},
        clearDraft: () => {},
      };
      return selector ? selector(state) : state;
    },
    {
      getState: () => ({
        drafts: {} as Record<string, { content: string; attachments: unknown[]; updatedAt: number }>,
        getDraft: () => undefined,
        getAnnotations: () => emptyDraftAttachments,
        getAttachments: () => emptyDraftAttachments,
        getUploads: () => emptyDraftAttachments,
        setDraft: () => {},
        setAttachments: () => {},
        addUpload: () => {},
        settleUpload: () => {},
        failUpload: () => {},
        removeUpload: () => {},
        clearDraft: () => {},
      }),
    },
  ),
  useCommentComposerStore: Object.assign(
    (selector?: any) => {
      const state = { sticky: true, runningAgentReply: "steer", toggleSticky: () => {} };
      return selector ? selector(state) : state;
    },
    {
      getState: () => ({ sticky: true, runningAgentReply: "steer", toggleSticky: () => {} }),
    },
  ),
}));

// Mock react-virtuoso: jsdom has no real layout, so the real Virtuoso would
// compute a 0-height viewport and render nothing. Most tests render every item;
// the windowed regression requires index navigation to mount an offscreen row.
//
// scrollIntoViewSpy: the deep-link effect no longer calls native
// scrollIntoView (it drives the timeline container's scrollTop directly to
// avoid scrolling ancestor overflow:hidden boxes — see issue-detail.tsx). We
// keep a no-op stub on the prototype so any stray scrollIntoView call from
// other components doesn't throw; deep-link tests assert the highlight
// background instead, which is mechanism-independent and observable without
// layout.
const scrollIntoViewSpy = vi.hoisted(() => vi.fn());
const scrollToIndexSpy = vi.hoisted(() => vi.fn());
const scrollIntoViewIndexSpy = vi.hoisted(() => vi.fn());
const mockVirtualWindow = vi.hoisted(() => ({
  enabled: false, delayedViewport: false, lateScrollReset: false, offscreenViewport: false, contentSettlesAbove: false, pendingSizeCorrection: false, holdAtIndex: false,
  targetId: "", targetHeight: 100, scrollParent: null as HTMLElement | null,
}));

vi.mock("react-virtuoso", () => ({
  Virtuoso: forwardRef(function MockVirtuoso(
    { data, itemContent, computeItemKey, customScrollParent, initialScrollTop, totalListHeightChanged }: {
      data: unknown[];
      itemContent: (i: number, item: unknown) => unknown;
      computeItemKey: (i: number, item: unknown) => React.Key;
      customScrollParent?: HTMLElement;
      initialScrollTop?: number;
      totalListHeightChanged?: (height: number) => void;
    },
    ref: any,
  ) {
    const [windowStart, setWindowStart] = useState(0);
    // Like Virtuoso, scroll to `initialScrollTop` once the rows are in, counted
    // from the list's own top: under `customScrollParent` that adds whatever
    // sits above the list (here a description 500px tall).
    useEffect(() => {
      if (initialScrollTop === undefined || !customScrollParent) return;
      const timer = window.setTimeout(() => { customScrollParent.scrollTop = initialScrollTop + 500; }, 100);
      return () => window.clearTimeout(timer);
    }, [initialScrollTop, customScrollParent]);
    const correctionTimer = useRef<ReturnType<typeof setInterval> | null>(null);
    useEffect(() => {
      if (!mockVirtualWindow.holdAtIndex || !customScrollParent) return;
      correctionTimer.current = setInterval(() => { customScrollParent.scrollTop = 0; }, 10);
      return () => { if (correctionTimer.current) clearInterval(correctionTimer.current); };
    }, [customScrollParent]);
    const viewportMeasured = useRef(!mockVirtualWindow.delayedViewport && !mockVirtualWindow.offscreenViewport);
    useEffect(() => {
      const measured = () => {
        viewportMeasured.current = true;
        totalListHeightChanged?.(1000);
      };
      if (mockVirtualWindow.offscreenViewport && customScrollParent) {
        const list = document.querySelector('[data-testid="virtuoso-mock"]')?.parentElement;
        if (list) list.getBoundingClientRect = () => new DOMRect(0, 1000 - customScrollParent.scrollTop, 400, 100);
        // Content above the list can still grow once after the first reveal
        // and push the list back out of view before it measures.
        let settled = !mockVirtualWindow.contentSettlesAbove;
        const timer = window.setInterval(() => {
          if (customScrollParent.scrollTop <= 0) return;
          if (!settled) { settled = true; customScrollParent.scrollTop = 0; return; }
          window.clearInterval(timer);
          measured();
        }, 10);
        return () => window.clearInterval(timer);
      }
      if (!mockVirtualWindow.delayedViewport) { measured(); return; }
      const timer = window.setTimeout(measured, 100);
      return () => window.clearTimeout(timer);
    }, [totalListHeightChanged, customScrollParent]);
    useEffect(() => {
      if ((!mockVirtualWindow.lateScrollReset && !mockVirtualWindow.holdAtIndex) || !customScrollParent) return;
      mockVirtualWindow.scrollParent = customScrollParent;
      Object.defineProperty(customScrollParent, "clientHeight", { configurable: true, value: 200 });
      customScrollParent.getBoundingClientRect = () => new DOMRect(0, 0, 400, 200);
      const target = document.getElementById(`comment-${mockVirtualWindow.targetId}`);
      if (target) {
        target.getBoundingClientRect = () => new DOMRect(0, 250 - customScrollParent.scrollTop, 400, mockVirtualWindow.targetHeight);
        const row = target.closest<HTMLElement>("[data-item-index]");
        if (row) row.getBoundingClientRect = () => new DOMRect(0, -customScrollParent.scrollTop, 400, 500);
      }
    }, [customScrollParent, windowStart, data]);
    const jump = (location: { index: number; offset?: number; done?: () => void }) => {
      if (location.offset !== undefined && customScrollParent && mockVirtualWindow.holdAtIndex) {
        if (correctionTimer.current) clearInterval(correctionTimer.current);
        customScrollParent.scrollTop = location.offset;
      }
      if (mockVirtualWindow.enabled && viewportMeasured.current) setWindowStart(Math.max(0, location.index - 2));
      if (mockVirtualWindow.lateScrollReset && customScrollParent) {
        window.setTimeout(() => { customScrollParent.scrollTop = location.offset ?? 0; location.done?.(); }, 80);
      } else if (!mockVirtualWindow.pendingSizeCorrection && !mockVirtualWindow.holdAtIndex) location.done?.();
    };
    useImperativeHandle(ref, () => ({
      scrollIntoView: (location: { index: number; done?: () => void }) => {
        scrollIntoViewIndexSpy(location);
        jump(location);
      },
      scrollToIndex: (location: { index: number }) => {
        scrollToIndexSpy(location);
        jump(location);
      },
    }));
    const start = mockVirtualWindow.enabled ? windowStart : 0;
    const visible = mockVirtualWindow.enabled ? data.slice(start, start + 8) : data;
    return (
      <div data-testid="virtuoso-mock">
        {visible.map((item, i) => (
          <div key={computeItemKey(start + i, item)} data-item-index={start + i}>{itemContent(start + i, item) as React.ReactElement}</div>
        ))}
      </div>
    );
  }),
}));

// jsdom's HTMLElement.prototype.scrollIntoView is a no-op stub; replace it
// with a spy so the deep-link effect's call can be observed.
beforeEach(() => {
  mockVirtualWindow.enabled = false;
  mockVirtualWindow.pendingSizeCorrection = false;
  mockVirtualWindow.holdAtIndex = false;
  mockVirtualWindow.delayedViewport = false;
  mockVirtualWindow.offscreenViewport = false;
  mockVirtualWindow.contentSettlesAbove = false;
  mockVirtualWindow.lateScrollReset = false;
  mockVirtualWindow.targetId = "";
  mockVirtualWindow.targetHeight = 100;
  mockVirtualWindow.scrollParent = null;
  scrollIntoViewIndexSpy.mockClear();
  scrollIntoViewSpy.mockClear();
  scrollToIndexSpy.mockClear();
  Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
    configurable: true,
    writable: true,
    value: scrollIntoViewSpy,
  });
  // The resolved-expand store is module-global (not per-mount like the old
  // useState); reset so one test's expansions can't leak into the next.
  useResolvedExpandStore.setState({ expandedByIssue: {} });
  useCommentCollapseStore.setState({ collapsedByIssue: {} });
});

// Mock modals
const mockOpenModal = vi.hoisted(() => vi.fn());
vi.mock("@multica/core/modals", () => ({
  useModalStore: Object.assign(
    (selector?: (state: { open: typeof mockOpenModal }) => unknown) => {
      const state = { open: mockOpenModal };
      return selector ? selector(state) : state;
    },
    { getState: () => ({ open: mockOpenModal }) },
  ),
}));

// Mock core/hooks/use-file-upload
vi.mock("@multica/core/hooks/use-file-upload", () => ({
  useFileUpload: () => ({ uploadWithToast: vi.fn().mockResolvedValue("https://example.com/file.png") }),
}));

// Mock realtime
vi.mock("@multica/core/realtime", () => ({
  useWSEvent: vi.fn(),
  useWSReconnect: vi.fn(),
  useWS: () => ({ subscribe: vi.fn(() => () => {}), onReconnect: vi.fn(() => () => {}) }),
  WSProvider: ({ children }: { children: React.ReactNode }) => children,
  useRealtimeSync: () => {},
}));

// Mock sonner
vi.mock("sonner", () => ({
  toast: { error: vi.fn(), success: vi.fn() },
}));

// Mock react-resizable-panels (used by @multica/ui/components/ui/resizable)
vi.mock("react-resizable-panels", () => ({
  Group: ({ children, ...props }: any) => <div data-testid="panel-group" {...props}>{children}</div>,
  Panel: ({ children, ...props }: any) => <div data-testid="panel" {...props}>{children}</div>,
  Separator: ({ children, ...props }: any) => <div data-testid="panel-handle" {...props}>{children}</div>,
  useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
  usePanelRef: () => ({ current: { isCollapsed: () => false, expand: vi.fn(), collapse: vi.fn() } }),
}));

// ---------------------------------------------------------------------------
// Test data
// ---------------------------------------------------------------------------

const mockIssue: Issue = {
  id: "issue-1",
  workspace_id: "ws-1",
  number: 1,
  identifier: "TES-1",
  title: "Implement authentication",
  description: "Add JWT auth to the backend",
  status: "in_progress",
  priority: "high",
  assignee_type: "member",
  assignee_id: "user-1",
  creator_type: "member",
  creator_id: "user-1",
  parent_issue_id: null,
  project_id: null,
  position: 0,
  stage: null,
  start_date: null,
  due_date: "2026-06-01T00:00:00Z",
  metadata: {},
  properties: {},
  created_at: "2026-01-15T00:00:00Z",
  updated_at: "2026-01-20T00:00:00Z",
  revision: 3,
};

const mockTimeline: TimelineEntry[] = [
  {
    type: "comment",
    id: "comment-1",
    actor_type: "member",
    actor_id: "user-1",
    content: "Started working on this",
    parent_id: null,
    created_at: "2026-01-16T00:00:00Z",
    updated_at: "2026-01-16T00:00:00Z",
    comment_type: "comment",
  },
  {
    type: "comment",
    id: "comment-2",
    actor_type: "agent",
    actor_id: "agent-1",
    content: "I can help with this",
    parent_id: null,
    created_at: "2026-01-17T00:00:00Z",
    updated_at: "2026-01-17T00:00:00Z",
    comment_type: "comment",
  },
];

// ---------------------------------------------------------------------------
// Import component under test (after mocks)
// ---------------------------------------------------------------------------

import { IssueDetail, groupSubIssuesByStage } from "./issue-detail";
import { InboxArchiveButton, InboxOpenBar } from "../../inbox/components/inbox-bar";
import { ScrollRestorationProvider, type ScrollRestorationAdapter } from "../../platform";
import { READING_COLUMN } from "../../layout/reading-column";
import {
  IssueSurfaceSelectionProvider,
  useCreateIssueSurfaceSelection,
} from "../surface/selection-context";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

const READING_COLUMN_SELECTOR = READING_COLUMN.split(" ").map((cls) => `.${CSS.escape(cls)}`).join("");

function createTestQueryClient() {
  return new QueryClient({
    defaultOptions: {
      queries: { retry: false, gcTime: 0 },
      mutations: { retry: false },
    },
  });
}

function renderIssueDetail(issueId = "issue-1") {
  const queryClient = createTestQueryClient();
  return render(
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <QueryClientProvider client={queryClient}>
        <IssueDetail issueId={issueId} />
      </QueryClientProvider>
    </I18nProvider>,
  );
}

/**
 * Renders with the workspace status catalog already in cache, so custom
 * statuses resolve to their real name, category and color. Seeding the query
 * (rather than stubbing the hook) keeps the shipped resolvers in the path; the
 * generous staleTime on the catalog query means it is never refetched. Every
 * other test runs without it — the cold-catalog case. (MUL-6243)
 */
function renderIssueDetailWithStatusCatalog(
  entries: IssueStatusEntry[],
  issueId = "issue-1",
) {
  const queryClient = createTestQueryClient();
  queryClient.setQueryData(issueStatusKeys.list("ws-1"), { statuses: entries });
  return render(
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <QueryClientProvider client={queryClient}>
        <IssueDetail issueId={issueId} />
      </QueryClientProvider>
    </I18nProvider>,
  );
}

function renderIssueDetailWithHighlight(
  highlightCommentId: string,
  issueId = "issue-1",
  options: { seedTimeline?: boolean } = {},
) {
  const queryClient = createTestQueryClient();
  if (options.seedTimeline) {
    // Pre-populate the timeline cache so the first render sees timeline.length>0.
    // This reproduces the inbox-click race: timeline data is available before
    // the issue itself has finished loading, so the effect that scrolls to
    // the comment fires once with `loading=true` (skeleton still rendered,
    // no comment DOM) and must re-fire when `loading` flips to false.
    queryClient.setQueryData(["issues", "timeline", issueId], mockTimeline);
  }
  const result = render(
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <QueryClientProvider client={queryClient}>
        <IssueDetail issueId={issueId} highlightCommentId={highlightCommentId} />
      </QueryClientProvider>
    </I18nProvider>,
  );
  return { ...result, queryClient };
}

const highlightedCommentBackgroundClass =
  "bg-[color-mix(in_srgb,var(--card)_95%,var(--brand)_5%)]";

function hasHighlightedCommentBackground(root: ParentNode | null): boolean {
  if (!root) return false;

  const elements = root instanceof Element
    ? [root, ...Array.from(root.querySelectorAll("[class]"))]
    : Array.from(root.querySelectorAll("[class]"));

  return elements.some(
    (el) => typeof el.className === "string" && el.className.includes(highlightedCommentBackgroundClass),
  );
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------


// Timeline thread rows render inside a stable wrapper (MUL-9409), so row order
// and adjacency are compared at the wrapper level.
function threadRow(el: Element): Element {
  return el.closest("[data-thread-row]") ?? el;
}
describe("IssueDetail (shared)", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    contentEditorMounts.count = 0;
    readonlyContentRenders.length = 0;
    descriptionSelectionAction.current = undefined;
    mockViewport.isMobile = false;
    // Default: issue loads successfully
    mockApiObj.getIssue.mockResolvedValue(mockIssue);
    mockApiObj.listPins.mockResolvedValue([]);
    // /timeline returns the entries flat in chronological order (oldest first).
    mockApiObj.listTimeline.mockResolvedValue(mockTimeline);
    mockApiObj.listAttachments.mockResolvedValue([]);
    mockApiObj.listComments.mockResolvedValue([]);
    mockApiObj.listIssueReactions.mockResolvedValue([]);
    mockApiObj.listIssueSubscribers.mockResolvedValue([]);
    mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });
    mockApiObj.getChildIssueProgress.mockResolvedValue({ progress: [] });
    mockApiObj.listIssueSystemWakeups.mockResolvedValue([]);
    mockApiObj.getAgentTaskSnapshot.mockResolvedValue([]);
    mockApiObj.getWorkspaceWorkingAgents.mockResolvedValue([]);
    mockApiObj.listProperties.mockResolvedValue({ properties: [], total: 0 });
    mockApiObj.listIssues.mockResolvedValue({ issues: [], total: 0 });
    mockApiObj.listTasksByIssue.mockResolvedValue([]);
    mockApiObj.listTaskMessages.mockResolvedValue([]);
    mockApiObj.rerunIssue.mockResolvedValue({ id: "task-rerun" });
    mockApiObj.listMembers.mockResolvedValue([
      { user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" },
    ]);
    mockApiObj.listAgents.mockResolvedValue([]);
    // Reset project mock — individual tests override per case. Default fixture
    // has project_id: null so getProject is not invoked.
    mockApiObj.getProject.mockReset();
    useIssueSidebarSectionsStore.getState().reset();
  });

  it("passes the issue's agent assignment to the local-directory hint", async () => {
    const agent = { id: "agent-vue", name: "Vue developer", runtime_id: "runtime-vue" };
    mockApiObj.getIssue.mockResolvedValue({
      ...mockIssue,
      project_id: "proj-1",
      assignee_type: "agent",
      assignee_id: agent.id,
    });
    mockApiObj.getProject.mockResolvedValue({ id: "proj-1", name: "Demo" });
    mockApiObj.listAgents.mockResolvedValue([agent]);

    renderIssueDetail();

    await waitFor(() => expect(mockLocalDirectoryHint).toHaveBeenCalledWith({
      projectId: "proj-1",
      assignedAgent: agent,
    }));
  });

  it("counts comment files as deliverables, a re-upload once as v2, never the description's (MUL-7649)", async () => {
    const file = (id: string, over: Partial<Attachment>): Attachment => ({
      id,
      workspace_id: "ws-1",
      issue_id: "issue-1",
      comment_id: null,
      chat_session_id: null,
      chat_message_id: null,
      uploader_type: "agent",
      uploader_id: "agent-1",
      filename: "report.md",
      url: `https://cdn.example.test/${id}`,
      download_url: `https://cdn.example.test/${id}`,
      markdown_url: `https://cdn.example.test/${id}`,
      content_type: "text/markdown",
      size_bytes: 2048,
      created_at: "2026-01-16T00:00:00Z",
      ...over,
    });
    const brief = file("brief", { filename: "brief.pdf", content_type: "application/pdf", uploader_type: "member" });
    const v1 = file("report-v1", { comment_id: "comment-1" });
    const v2 = file("report-v2", { comment_id: "comment-2", created_at: "2026-01-17T00:00:00Z" });
    mockApiObj.getIssue.mockResolvedValue({ ...mockIssue, description: "!file[brief.pdf](https://cdn.example.test/brief)" });
    mockApiObj.listAttachments.mockResolvedValue([brief, v1, v2]);
    mockApiObj.listTimeline.mockResolvedValue([
      { ...mockTimeline[0]!, attachments: [v1] },
      { ...mockTimeline[1]!, attachments: [v2] },
    ]);

    renderIssueDetail();

    const header = await screen.findByRole("button", { name: /^Deliverables/ });
    expect(screen.getByRole("button", { name: "report.md, version 2" })).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "View 1 deliverable" })).toBeInTheDocument();
    expect(screen.queryByRole("button", { name: "brief.pdf" })).toBeNull();
    fireEvent.click(header);
    expect(header).toHaveTextContent("1");
  });

  it("keeps images from comments outside the loaded history in deliverables", async () => {
    const image: Attachment = { id: "historical-chart", workspace_id: "ws-1", issue_id: "issue-1", comment_id: "older-comment",
      chat_session_id: null, chat_message_id: null, uploader_type: "agent", uploader_id: "agent-1",
      filename: "historical-chart.png", content_type: "image/png", size_bytes: 100,
      url: "/chart.png", download_url: "/chart.png", markdown_url: "/chart.png", created_at: "2026-01-01T00:00:00Z",
      comment_author_type: "agent", comment_author_id: "agent-1", comment_created_at: "2026-01-01T00:00:00Z" };
    mockApiObj.listTimeline.mockResolvedValue([]);
    // The issue attachment list alone supplies the historical file and its origin.
    mockApiObj.listAttachments.mockResolvedValue([image]);
    const root = {
      id: "older-root", issue_id: "issue-1", author_type: "agent", author_id: "agent-1",
      content: "Historical image discussion", type: "comment", parent_id: null,
      created_at: image.created_at, updated_at: image.created_at, reactions: [], attachments: [],
      resolved_at: null, resolved_by_type: null, resolved_by_id: null,
    };
    mockApiObj.listComments.mockResolvedValue([root, {
      ...root, id: "older-comment", parent_id: root.id,
      content: "Historical chart explanation", attachments: [image],
    }]);
    renderIssueDetail();
    expect(await screen.findByRole("button", { name: "historical-chart.png" })).toBeInTheDocument();
    fireEvent.click(screen.getByRole("button", { name: "View 1 deliverable" }));
    expect(await screen.findByTitle("historical-chart.png")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Show in comments" })).toBeInTheDocument();
    expect(mockApiObj.listComments).not.toHaveBeenCalled();
    fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));
    await waitFor(() => expect(hasHighlightedCommentBackground(
      document.getElementById("comment-older-comment"),
    )).toBe(true));
    expect(mockApiObj.listComments).toHaveBeenCalledWith("issue-1", { thread: "older-comment" });
    expect(screen.getByText("Historical chart explanation")).toBeInTheDocument();
    expect(screen.queryByRole("dialog", { name: /deliverables$/ })).toBeNull();
  });

  it.each([100, 1200])("keeps a %i-pixel deliverable reply visible while the virtual list corrects its size", async (height) => {
    mockVirtualWindow.enabled = true;
    mockVirtualWindow.holdAtIndex = true;
    mockVirtualWindow.targetId = "image-reply";
    mockVirtualWindow.targetHeight = height;
    const history = Array.from({ length: 120 }, (_, index) => ({
      ...mockTimeline[0]!, id: `history-${index}`, parent_id: null, source_task_id: undefined,
      content: `Historical comment ${index}`,
      created_at: new Date(Date.UTC(2026, 0, 1, 0, index)).toISOString(),
    }));
    const root = history[115]!;
    const image: Attachment = { id: "deep-image", workspace_id: "ws-1", issue_id: "issue-1",
      comment_id: "image-reply", chat_session_id: null, chat_message_id: null,
      uploader_type: "agent", uploader_id: "agent-1", filename: "deep-image.png",
      content_type: "image/png", size_bytes: 100, url: "/image.png", download_url: "/image.png",
      markdown_url: "/image.png", created_at: root.created_at };
    mockApiObj.listTimeline.mockResolvedValue([...history, {
      ...root, id: "image-reply", parent_id: root.id, content: "Deep image explanation", attachments: [image],
    }]);
    mockApiObj.listTasksByIssue.mockResolvedValue([]);
    renderIssueDetail();
    fireEvent.click(await screen.findByRole("button", { name: "View 1 deliverable" }));
    fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));
    await waitFor(() => expect(hasHighlightedCommentBackground(
      document.getElementById("comment-image-reply"),
    )).toBe(true));
    await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 150)); });
    expect(mockVirtualWindow.scrollParent?.scrollTop).toBe(height === 100 ? 200 : 234);
    expect(document.querySelectorAll('[id^="comment-history-"]').length).toBeLessThanOrEqual(8);
    expect(mockApiObj.listComments).not.toHaveBeenCalled();
    const jumps = scrollIntoViewIndexSpy.mock.calls.length;
    fireEvent.click(screen.getByRole("button", { name: "View 1 deliverable" }));
    fireEvent.click(screen.getByRole("button", { name: "Show in comments" }));
    await waitFor(() => expect(scrollIntoViewIndexSpy.mock.calls.length).toBeGreaterThan(jumps));
  });

  it("finds text in comments the timeline has not mounted, without mounting the history (MUL-9538)", async () => {
    mockVirtualWindow.enabled = true;
    const history = Array.from({ length: 40 }, (_, index) => ({
      ...mockTimeline[0]!, id: `history-${index}`, parent_id: null, source_task_id: undefined,
      content: index === 30 ? "The **needle** is in this one" : `Historical comment ${index}`,
      created_at: new Date(Date.UTC(2026, 0, 1, 0, index)).toISOString(),
    }));
    mockApiObj.listTimeline.mockResolvedValue(history);
    mockApiObj.listTasksByIssue.mockResolvedValue([]);
    // Find only answers in a visible page; jsdom lays nothing out.
    const rects = vi.spyOn(HTMLElement.prototype, "getClientRects")
      .mockReturnValue([new DOMRect(0, 0, 1, 1)] as unknown as DOMRectList);
    // jsdom's user agent names the host OS, which would make the find chord
    // Cmd+F on a Mac host.
    configureShortcutPlatform("linux");
    try {
      renderIssueDetail();
      await screen.findByText("Historical comment 0");

      fireEvent.keyDown(document, { key: "f", code: "KeyF", ctrlKey: true });
      fireEvent.change(await screen.findByRole("textbox", { name: "Find in issue..." }), { target: { value: "needle" } });

      // Counted from the comment's Markdown while it is not mounted.
      await waitFor(() => expect(screen.getByRole("search")).toHaveTextContent("1/1"));
      // Landing on it mounts that comment, not the history before it.
      await waitFor(() => expect(scrollIntoViewIndexSpy).toHaveBeenCalledWith(expect.objectContaining({ index: 30 })));
      await waitFor(() => expect(document.getElementById("comment-history-30")).not.toBeNull());
      expect(document.querySelectorAll('[id^="comment-history-"]').length).toBeLessThanOrEqual(8);
      expect(screen.getByTestId("virtuoso-mock")).toBeInTheDocument();
    } finally {
      rects.mockRestore();
      configureShortcutPlatform(null);
    }
  });

  it("opens source-context creation from both a root comment and a reply", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      { ...mockTimeline[0], id: "source-root", parent_id: null },
      { ...mockTimeline[1], id: "source-reply", parent_id: "source-root" },
    ]);
    const { container } = renderIssueDetail();
    await screen.findByText("Started working on this");

    const menuButton = (commentId: string) => Array.from(
      container.querySelectorAll<HTMLButtonElement>('button[aria-label="Comment actions"]'),
    )
      .find((button): button is HTMLButtonElement => button?.closest("[id^='comment-']")?.id === `comment-${commentId}`);
    await waitFor(() => expect(menuButton("source-root")).toBeTruthy());
    await waitFor(() => expect(menuButton("source-reply")).toBeTruthy());

    fireEvent.click(menuButton("source-root")!);
    const branchAction = await screen.findByText("Create sub-issue from here");
    expect(branchAction.closest('[role="menuitem"]')?.querySelector(".icon-message-square-plus")).toBeInTheDocument();
    fireEvent.click(branchAction);
    expect(mockOpenModal).toHaveBeenLastCalledWith("quick-create-issue", expect.objectContaining({
      anchor_comment_id: "source-root",
      parent_issue_id: "issue-1",
    }));

    fireEvent.click(menuButton("source-reply")!);
    fireEvent.click(await screen.findByText("Create sub-issue from here"));
    expect(mockOpenModal).toHaveBeenLastCalledWith("quick-create-issue", expect.objectContaining({
      anchor_comment_id: "source-reply",
      parent_issue_id: "issue-1",
    }));
  });

  it("does not offer source-context creation for system comments", async () => {
    mockApiObj.listTimeline.mockResolvedValue([{
      ...mockTimeline[0],
      id: "system-comment",
      comment_type: "system",
    }]);
    const { container } = renderIssueDetail();
    await screen.findByText("Started working on this");

    const menuButton = Array.from(
      container.querySelectorAll<HTMLButtonElement>('button[aria-label="Comment actions"]'),
    ).find((button) => button.closest("[id^='comment-']")?.id === "comment-system-comment");
    expect(menuButton).toBeTruthy();
    fireEvent.click(menuButton!);

    expect(screen.queryByText("Create sub-issue from here")).not.toBeInTheDocument();
  });

  it("keeps an embedded host's sidebar closed while loading", () => {
    mockApiObj.getIssue.mockReturnValue(new Promise(() => {}));
    const queryClient = createTestQueryClient();
    const view = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueDetail issueId="issue-1" defaultSidebarOpen={false} />
        </QueryClientProvider>
      </I18nProvider>,
    );
    expect(view.container.querySelector(".w-80.border-l")).toBeNull();
    view.unmount();
    queryClient.clear();
  });

  it("shows loading skeleton while data is loading", () => {
    // Make the API hang to keep loading state
    mockApiObj.getIssue.mockReturnValue(new Promise(() => {}));
    renderIssueDetail();

    expect(
      screen.getAllByRole("generic").some((el) => el.getAttribute("data-slot") === "skeleton"),
    ).toBe(true);
  });

  it("sizes the skeleton and the loaded column from the same reading container", async () => {
    // The column's cap is relative to its scroller (`cqi`), so both scrollers
    // have to be the container or the skeleton and the loaded column resolve
    // the same clamp against different widths and jump when content mounts.
    mockApiObj.getIssue.mockReturnValue(new Promise(() => {}));
    const loadingRender = renderIssueDetail();
    const skeletonColumn = loadingRender.container.querySelector(READING_COLUMN_SELECTOR);
    expect(skeletonColumn).toBeTruthy();
    expect(skeletonColumn!.parentElement).toHaveClass("@container");
    loadingRender.unmount();

    mockApiObj.getIssue.mockResolvedValue(mockIssue);
    const { container } = renderIssueDetail();
    await waitFor(() => {
      expect(screen.getByText("Implement authentication")).toBeInTheDocument();
    });
    const column = container.querySelector(READING_COLUMN_SELECTOR);
    expect(column).toBeTruthy();
    expect(column!.parentElement).toHaveClass("@container");
  });

  it("gives the skeleton the same horizontal gutters as the loaded column", async () => {
    // The skeleton is the loaded column's stand-in, so a gutter change has to
    // land on both or the column jumps sideways at the moment the issue
    // arrives. Horizontal only: the loaded column also reserves the chat
    // launcher's corner at its bottom, which the skeleton has no scroll to
    // reach.
    const horizontalGutters = (el: Element | null) =>
      (el?.className ?? "")
        .split(/\s+/)
        .filter((cls) => /(^|:)px-/.test(cls))
        .sort();

    mockApiObj.getIssue.mockReturnValue(new Promise(() => {}));
    const loadingRender = renderIssueDetail();
    const skeletonGutters = horizontalGutters(
      loadingRender.container.querySelector(READING_COLUMN_SELECTOR),
    );
    loadingRender.unmount();

    mockApiObj.getIssue.mockResolvedValue(mockIssue);
    const { container } = renderIssueDetail();
    await waitFor(() => {
      expect(screen.getByText("Implement authentication")).toBeInTheDocument();
    });

    // Non-empty guard: without it a renamed column class passes vacuously.
    expect(skeletonGutters.length).toBeGreaterThan(0);
    expect(skeletonGutters).toEqual(
      horizontalGutters(container.querySelector(READING_COLUMN_SELECTOR)),
    );
  });

  it("wires the description selection toolbar to annotation collection", async () => {
    renderIssueDetail();
    await screen.findByDisplayValue("Add JWT auth to the backend");
    expect(descriptionSelectionAction.current?.label).toBe("Add to comment");
    expect(descriptionSelectionAction.current?.onSelect).toBeTypeOf("function");
  });

  it("renders issue title and description after loading", async () => {
    renderIssueDetail();

    // The description is the one eager editor: keeping one renderer avoids the
    // layout jump caused by swapping a long react-markdown tree for ProseMirror.
    // Title and comment/reply composers remain readonly-first.
    expect(await screen.findByDisplayValue("Add JWT auth to the backend")).toBeInTheDocument();
    expect(screen.getByText("Implement authentication")).toBeInTheDocument();
    expect(screen.queryByTestId("title-editor")).not.toBeInTheDocument();
    expect(screen.getAllByTestId("rich-text-editor")).toHaveLength(1);
    expect(contentEditorMounts.count).toBe(1);
  });

  it("reconciles a cached list snapshot so source context appears on first entry", async () => {
    const sourceContext: NonNullable<Issue["source_context"]> = {
      id: "context-1",
      version: 1,
      usage: "read_only_historical_background",
      captured_at: "2026-08-21T12:00:00Z",
      display_state: "unchanged",
      source_issue_state: "unchanged",
      comment_thread_state: "unchanged",
      anchor_comment_state: "available",
      can_open_current_source: true,
      current_source: {
        issue_id: "source-issue",
        anchor_comment_id: "source-comment",
        identifier: "TES-7",
      },
      source_author_state: [],
      snapshot: {
        version: 1,
        captured_by_user_id: "user-1",
        captured_at: "2026-08-21T12:00:00Z",
        source_issue: {
          id: "source-issue",
          identifier: "TES-7",
          number: 7,
          title: "Source issue",
          description: "Source description",
          created_at: "2026-08-20T00:00:00Z",
          updated_at: "2026-08-21T00:00:00Z",
          revision: 2,
          attachments: [],
        },
        anchor_comment_id: "source-comment",
        comment_thread: [
          {
            id: "source-comment",
            parent_id: null,
            type: "comment",
            content: "Source comment",
            author: { type: "member", id: "user-1", name: "Test User" },
            created_at: "2026-08-21T01:00:00Z",
            updated_at: "2026-08-21T01:00:00Z",
            revision: 1,
            attachments: [],
          },
        ],
      },
    };
    const cachedWithoutDetailOnlyContext: Issue = {
      ...mockIssue,
      parent_issue_id: "source-issue",
    };
    const authoritativeDetail: Issue = {
      ...cachedWithoutDetailOnlyContext,
      source_context: sourceContext,
    };
    const parentIssue: Issue = {
      ...mockIssue,
      id: "source-issue",
      identifier: "TES-7",
      number: 7,
      title: "Source issue",
      parent_issue_id: null,
    };
    const queryClient = new QueryClient({
      defaultOptions: {
        queries: { retry: false, gcTime: 0, staleTime: Infinity },
        mutations: { retry: false },
      },
    });
    queryClient.setQueryData(
      ["issues", "ws-1", "detail", "issue-1"],
      cachedWithoutDetailOnlyContext,
    );
    mockApiObj.getIssue.mockImplementation((issueId: string) =>
      Promise.resolve(issueId === "source-issue" ? parentIssue : authoritativeDetail),
    );

    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueDetail issueId="issue-1" />
        </QueryClientProvider>
      </I18nProvider>,
    );

    const snapshotAction = await screen.findByRole("button", { name: "Context snapshot" });
    const summary = snapshotAction.closest<HTMLElement>('[data-slot="source-context-summary"]');
    expect(summary).toHaveTextContent("Sub-issue of");
    expect(within(summary!).getByRole("link", { name: "TES-7 Source issue" })).toBeInTheDocument();
    // The summary replaces the plain parent row rather than adding a second one.
    expect(screen.getAllByText("Sub-issue of")).toHaveLength(1);
    expect(screen.queryByText(/From TES-7/)).not.toBeInTheDocument();
    expect(mockApiObj.getIssue).toHaveBeenCalledWith("issue-1");
  });

  it("opts the description editor into the unmount flush", async () => {
    // Closing the issue modal must save the description the user last saw —
    // ContentEditor drops pending debounced updates on unmount by default
    // (so cancelled comment drafts aren't resurrected), and only this
    // explicit opt-in keeps a paste-then-close from losing the image
    // markdown and its attachment_ids bind (MUL-3254). The flush behavior
    // itself is covered in content-editor.test.tsx; this pins the wiring.
    renderIssueDetail();

    const description = await screen.findByDisplayValue("Add JWT auth to the backend");
    expect(description).toHaveAttribute("data-flush-on-unmount", "true");
  });

  it("remounts the eager description on issue switch without carrying stale content", async () => {
    // The web route reuses IssueDetail across issues. The keyed description
    // editor must remount atomically for the new issue while the title remains
    // on its cheap stand-in.
    const queryClient = createTestQueryClient();
    const issue2 = {
      ...mockIssue,
      id: "issue-2",
      title: "Second issue",
      description: "Second description",
    };
    // The cache seed marks the data stale, so the query refetches in the
    // background — getIssue must answer per-id or the refetch would clobber
    // issue-2 with issue-1's payload.
    mockApiObj.getIssue.mockImplementation((issueId: string) =>
      Promise.resolve(issueId === "issue-2" ? issue2 : mockIssue),
    );
    // Pre-seed issue-2 so its first render skips the loading skeleton.
    queryClient.setQueryData(["issues", "ws-1", "detail", "issue-2"], issue2);
    const ui = (issueId: string) => (
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueDetail issueId={issueId} />
        </QueryClientProvider>
      </I18nProvider>
    );
    const { rerender } = render(ui("issue-1"));

    await screen.findByDisplayValue("Add JWT auth to the backend");
    const mountsBeforeSwitch = contentEditorMounts.count;

    rerender(ui("issue-2"));

    expect(await screen.findByDisplayValue("Second description")).toBeInTheDocument();
    expect(screen.queryByDisplayValue("Add JWT auth to the backend")).not.toBeInTheDocument();
    expect(screen.queryByTestId("title-editor")).not.toBeInTheDocument();
    expect(contentEditorMounts.count).toBe(mountsBeforeSwitch + 1);
  });

  it("renders the issue title leaf as a link to the issue detail page", async () => {
    renderIssueDetail();

    // The breadcrumb leaf is the whole "identifier + title" string wrapped in a
    // single link to the issue's own detail route (used to open the full page
    // from the inline Inbox pane). A bare issue has no ancestor crumbs.
    const leaf = await screen.findByText("TES-1 Implement authentication");
    expect(leaf.closest("a")).toHaveAttribute("href", "/test/issues/TES-1");
  });

  it("omits the project breadcrumb segment when the issue has no project_id", async () => {
    // Default fixture has project_id: null.
    renderIssueDetail();

    // Leaf renders once loaded; a bare issue has no ancestor crumbs at all.
    await screen.findByText("TES-1 Implement authentication");

    // Project is never fetched and no project crumb appears.
    expect(mockApiObj.getProject).not.toHaveBeenCalled();
    expect(screen.queryByText("Marketing site refresh")).not.toBeInTheDocument();
  });

  it("renders the project breadcrumb segment when the issue belongs to a project", async () => {
    mockApiObj.getIssue.mockResolvedValue({ ...mockIssue, project_id: "p-1" });
    mockApiObj.getProject.mockResolvedValue({
      id: "p-1",
      workspace_id: "ws-1",
      title: "Marketing site refresh",
      description: null,
      icon: "🚀",
      status: "in_progress",
      priority: "none",
      lead_type: null,
      lead_id: null,
      created_at: "2026-01-01T00:00:00Z",
      updated_at: "2026-01-01T00:00:00Z",
      issue_count: 0,
      done_count: 0,
      resource_count: 0,
    });

    renderIssueDetail();

    const projectLink = await screen.findByText("Marketing site refresh");
    // The whole project segment is a single AppLink pointing at the project
    // detail route under the active workspace slug.
    expect(projectLink.closest("a")).toHaveAttribute("href", "/test/projects/p-1");
  });

  it("renders properties sidebar with all core rows plus set optional rows", async () => {
    renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText("Properties")).toBeInTheDocument();
    });

    // Core rows — always rendered regardless of whether the issue has a value.
    expect(screen.getByText("Status")).toBeInTheDocument();
    expect(screen.getByText("Assignee")).toBeInTheDocument();
    // Project is optional: the fixture has none, so its row waits in Add property.
    expect(screen.queryByTestId("project-picker")).not.toBeInTheDocument();
    // priority="high" + due_date are set in the fixture, so both optional rows show.
    expect(screen.getByText("Priority")).toBeInTheDocument();
    expect(screen.getByText("Due date")).toBeInTheDocument();
    // No labels are attached in the fixture — the Labels optional row
    // must stay hidden by default.
    expect(screen.queryByText("Labels")).not.toBeInTheDocument();
    // Parent issue lives in its own section and only renders when the
    // issue actually has a parent — the fixture has none.
    expect(screen.queryByText("Parent issue")).not.toBeInTheDocument();
    // The "+ Add property" affordance is always offered while any
    // optional field is still hidden.
    expect(screen.getByRole("button", { name: "Add property" })).toBeInTheDocument();
  });

  it("hides every optional property row when none are set", async () => {
    // Override the default fixture: nothing optional set.
    mockApiObj.getIssue.mockResolvedValue({
      ...mockIssue,
      priority: "none",
      start_date: null,
      due_date: null,
    });

    renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText("Properties")).toBeInTheDocument();
    });

    expect(screen.queryByText("Priority")).not.toBeInTheDocument();
    expect(screen.queryByText("Due date")).not.toBeInTheDocument();
    expect(screen.queryByText("Labels")).not.toBeInTheDocument();
    expect(screen.queryByTestId("project-picker")).not.toBeInTheDocument();
    // No parent → no standalone Parent issue section either.
    expect(screen.queryByText("Parent issue")).not.toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Add property" })).toBeInTheDocument();
  });

  it("shows the Project row once the issue has a project, and offers it otherwise", async () => {
    mockApiObj.getProject.mockResolvedValue({ id: "proj-1", name: "Demo" });
    mockApiObj.getIssue.mockResolvedValue({ ...mockIssue, project_id: "proj-1" });
    const { unmount } = renderIssueDetail();
    expect(await screen.findByTestId("project-picker")).toBeInTheDocument();
    unmount();

    mockApiObj.getIssue.mockResolvedValue(mockIssue);
    renderIssueDetail();
    fireEvent.click(await screen.findByRole("button", { name: "Add property" }));
    expect(await screen.findByRole("button", { name: "Project" })).toBeInTheDocument();
  });

  it("keeps the Properties header free of add and settings buttons", async () => {
    renderIssueDetail();
    const disclosure = await screen.findByRole("button", { name: "Properties" });
    const header = disclosure.parentElement!;
    expect(within(header).queryByRole("button", { name: "Add property" })).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: "Properties options" })).not.toBeInTheDocument();
    // Folding the section hides the inline Add property row with the rest of the grid.
    fireEvent.click(disclosure);
    expect(screen.queryByRole("button", { name: "Add property" })).not.toBeInTheDocument();
  });

  it("adds an optional field from the inline Add property row and closes the popover", async () => {
    renderIssueDetail();
    fireEvent.click(await screen.findByRole("button", { name: "Add property" }));
    fireEvent.click(await screen.findByRole("button", { name: "Start date" }));
    // The popover closes (its other options are gone) and the new row is rendered.
    await waitFor(() => expect(screen.queryByRole("button", { name: "Labels" })).not.toBeInTheDocument());
    expect(screen.getAllByText("Start date")[0]).toBeVisible();
  });

  it("uses a non-resizable layout with the sidebar sheet closed by default on mobile", async () => {
    mockViewport.isMobile = true;

    renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText("Implement authentication")).toBeInTheDocument();
    });

    expect(screen.queryByTestId("panel-group")).not.toBeInTheDocument();
    expect(screen.queryByText("Properties")).not.toBeInTheDocument();
  });

  // The peek's close button lives in the host's trailing controls, so every
  // state the peek can show must carry them (review of #8886).
  function renderPeek(issueId = "issue-1") {
    const queryClient = createTestQueryClient();
    return render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueDetail
            issueId={issueId}
            variant="peek"
            onDelete={() => {}}
            leadingAction={<span data-testid="peek-nav" />}
            trailingActions={<button type="button">Close preview</button>}
          />
        </QueryClientProvider>
      </I18nProvider>,
    );
  }

  it("keeps the peek's host controls while the issue is loading", () => {
    mockApiObj.getIssue.mockReturnValue(new Promise(() => {}));
    renderPeek();
    expect(screen.getByTestId("peek-nav")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Close preview" })).toBeInTheDocument();
  });

  it("keeps the peek's host controls when the issue cannot be loaded", async () => {
    mockApiObj.getIssue.mockRejectedValue(new ApiError("Not found", 404, "Not Found"));
    renderPeek("nonexistent-id");
    await waitFor(() => {
      expect(
        screen.getByText("This issue does not exist or has been deleted in this workspace."),
      ).toBeInTheDocument();
    });
    expect(screen.getByRole("button", { name: "Close preview" })).toBeInTheDocument();
  });

  it("renders the peek variant as one column with property pills and host actions", async () => {
    const queryClient = createTestQueryClient();
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueDetail
            issueId="issue-1"
            variant="peek"
            leadingAction={<span data-testid="peek-nav" />}
            trailingActions={<button type="button">Close preview</button>}
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    await waitFor(() => {
      expect(screen.getByText("Implement authentication")).toBeInTheDocument();
    });

    // No resizable sidebar: the properties become pills under the title.
    expect(screen.queryByTestId("panel-group")).not.toBeInTheDocument();
    expect(screen.queryByText("Properties")).not.toBeInTheDocument();
    expect(screen.getByTestId("project-picker")).toBeInTheDocument();
    expect(screen.getByText("High")).toBeInTheDocument();
    // The host's controls replace the sidebar toggle.
    expect(screen.getByTestId("peek-nav")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Close preview" })).toBeInTheDocument();
    // The header leaf names the issue by identifier only — the title is right below.
    expect(screen.getByRole("link", { name: mockIssue.identifier })).toBeInTheDocument();
  });

  it("reveals the header's clipped identifier and title on hover", async () => {
    renderIssueDetail();
    await screen.findByText("Implement authentication");

    const link = screen.getByRole("link", { name: `${mockIssue.identifier} ${mockIssue.title}` });
    // jsdom never lays out the header: model the clip the actions leave the leaf.
    const leaf = link.firstElementChild as HTMLElement;
    leaf.style.overflowX = "hidden";
    Object.defineProperties(leaf, {
      scrollWidth: { configurable: true, value: 320 },
      clientWidth: { configurable: true, value: 100 },
    });

    vi.useFakeTimers();
    try {
      fireEvent.pointerEnter(link, { pointerType: "mouse" });
      await act(async () => { vi.advanceTimersByTime(550); });
    } finally {
      vi.useRealTimers();
    }

    expect(document.querySelector("[data-slot=tooltip-content]"))
      .toHaveTextContent(`${mockIssue.identifier} ${mockIssue.title}`);
  });

  describe("Inbox bar", () => {
    const inboxItem: InboxItem = {
      id: "n-1",
      workspace_id: "ws-1",
      recipient_type: "member",
      recipient_id: "user-1",
      actor_type: "member",
      actor_id: "user-1",
      type: "new_comment",
      severity: "info",
      issue_id: "issue-1",
      title: "Implement authentication",
      body: "Ready for review.",
      issue_status: "in_progress",
      issue_priority: "none",
      read: true,
      archived: false,
      created_at: "2026-01-15T00:00:00Z",
      details: null,
    };
    function renderWithArchive(onArchive: () => void = () => {}, { item = inboxItem as InboxItem | null } = {}) {
      const queryClient = createTestQueryClient();
      return render(
        <I18nProvider locale="en" resources={TEST_RESOURCES}>
          <QueryClientProvider client={queryClient}>
            <IssueDetail
              issueId="issue-1"
              inbox={{
                item: item ?? undefined,
                bar: (issueActions) =>
                  item ? (
                    <InboxOpenBar issueActions={issueActions}>
                      <InboxArchiveButton onClick={onArchive} />
                    </InboxOpenBar>
                  ) : null,
              }}
            />
          </QueryClientProvider>
        </I18nProvider>,
      );
    }

    it("opens the issue page on its own, with no Inbox crumb in the header", async () => {
      const { container } = renderWithArchive();

      const open = await screen.findByRole("button", { name: enIssues.detail.open_issue_page });
      expect(open).toHaveAttribute("href", "/test/issues/TES-1");
      expect(container.querySelector('header a[href="/test/inbox"]')).toBeNull();
    });

    it("leaves the issue page without either", async () => {
      renderIssueDetail();

      await screen.findByRole("button", { name: enCommon.more_actions });
      expect(screen.queryByRole("button", { name: enIssues.detail.open_issue_page })).not.toBeInTheDocument();
      expect(screen.queryByRole("button", { name: enInbox.context_menu.archive })).not.toBeInTheDocument();
    });

    it("moves status and assignee into the page header while the properties sidebar is closed", async () => {
      const { container } = renderIssueDetail();

      const toggle = await screen.findByRole("button", { name: enIssues.detail.sidebar_tooltip });
      expect(container.querySelector('[data-testid="issue-header-actions"]')).toBeNull();

      fireEvent.click(toggle);
      const headerActions = await waitFor(() => {
        const el = container.querySelector<HTMLElement>('[data-testid="issue-header-actions"]');
        expect(el).not.toBeNull();
        return el!;
      });
      expect(headerActions.closest("header")).not.toBeNull();
      expect(within(headerActions).getByText(enIssues.status.in_progress)).toBeInTheDocument();
    });

    it("floats the notification's actions above the composer, after the issue's own", async () => {
      const { container } = renderWithArchive();

      const archive = await screen.findByRole("button", { name: enInbox.context_menu.archive });
      expect(archive.closest("header")).toBeNull();
      const bar = archive.closest<HTMLElement>("[data-inbox-bar]")!;
      expect(bar.closest("[data-composer-dock]")).not.toBeNull();
      expect(within(bar).queryByText(enInbox.labels.commented)).toBeNull();
      expect(within(bar).getByText(enIssues.status.in_progress)).toBeInTheDocument();
      expect(container.querySelector("header")).not.toHaveTextContent(enInbox.context_menu.archive);
      expect(screen.queryByRole("button", { name: "Mark as done" })).not.toBeInTheDocument();
    });

    it("gives the group its own room above a composer that rides the timeline, clear of the last comment", async () => {
      mockViewport.isMobile = true;
      const { container } = renderWithArchive();

      const archive = await screen.findByRole("button", { name: enInbox.context_menu.archive });
      const anchor = archive.closest("[data-composer-dock]")!.parentElement!;
      const composer = container.querySelector("[data-mc='comment-composer']")?.parentElement;
      // The group sits on the anchor, which keeps the room above it (mt-14)
      // and stops just short of the composer (mt-3); pinned, it holds off the
      // viewport bottom.
      expect(anchor).toHaveClass("sticky", "h-0", "mt-14");
      expect(anchor.nextElementSibling).toBe(composer);
      expect(composer).toHaveClass("mt-3");
      expect(composer).not.toHaveClass("sticky");
    });

    it("archives the notification without changing the issue's status", async () => {
      const onArchive = vi.fn();
      renderWithArchive(onArchive);

      fireEvent.click(await screen.findByRole("button", { name: enInbox.context_menu.archive }));
      expect(onArchive).toHaveBeenCalledTimes(1);
      expect(mockApiObj.updateIssue).not.toHaveBeenCalled();
    });

    it("shows no bar for a notification already archived", async () => {
      renderWithArchive(() => {}, { item: null });

      await screen.findByRole("button", { name: enCommon.more_actions });
      expect(screen.queryByRole("button", { name: enInbox.context_menu.archive })).not.toBeInTheDocument();
    });

    describe("advancing to the next notification", () => {
      const entering = (container: HTMLElement) => container.querySelector("[class*='animate-inbox-enter']");
      async function advance() {
        useInboxSelectionStore.getState().recordTransition("ws-1", "issue-1", "next");
        const view = renderWithArchive();
        await screen.findByRole("button", { name: enCommon.more_actions });
        await waitFor(() => expect(useInboxSelectionStore.getState().transitionByWorkspace["ws-1"]).toBeUndefined());
        return view;
      }
      afterEach(() => {
        useAppearanceStore.getState().reset();
        vi.unstubAllGlobals();
      });

      it("slides the issue in from the direction of travel", async () => {
        const { container } = await advance();
        expect(entering(container)).toHaveClass("animate-inbox-enter-next");
      });

      it("shows the issue at once with the Appearance Reduce motion switch", async () => {
        useAppearanceStore.getState().set({ reduceMotion: true });
        const { container } = await advance();
        expect(entering(container)).toBeNull();
      });

      it("shows the issue at once with the system reduced-motion setting", async () => {
        vi.stubGlobal("matchMedia", vi.fn((query: string) => ({
          matches: query === "(prefers-reduced-motion: reduce)",
          addEventListener: vi.fn(),
          removeEventListener: vi.fn(),
        })));
        const { container } = await advance();
        expect(entering(container)).toBeNull();
      });
    });

    it("keeps pinning in the more-actions menu rather than the header", async () => {
      mockApiObj.listPins.mockResolvedValue([
        {
          id: "pin-1",
          workspace_id: "ws-1",
          user_id: "user-1",
          item_type: "issue",
          item_id: "issue-1",
          position: 0,
          created_at: "2026-01-15T00:00:00Z",
        },
      ]);
      renderIssueDetail();

      fireEvent.click(await screen.findByRole("button", { name: enCommon.more_actions }));
      expect(
        await screen.findByRole("menuitem", { name: enIssues.actions.unpin_from_sidebar }),
      ).toBeInTheDocument();
      expect(
        screen.queryByRole("button", { name: enIssues.actions.unpin_from_sidebar }),
      ).not.toBeInTheDocument();
    });
  });

  it("pins the comment composer to the scroll viewport on a wide screen", async () => {
    const { container } = renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText("Implement authentication")).toBeInTheDocument();
    });

    // `bottom-0` is unique to the composer wrapper — the sticky affordances
    // inside the timeline (comment headers, resolve bars) all pin to `top-0`.
    expect(container.querySelector(".sticky.bottom-0")).not.toBeNull();
  });

  it("lets the composer ride the end of the timeline on mobile", async () => {
    // A pinned composer on a phone sits on the chat launcher's corner at every
    // scroll position, and the part it covers is its own send button.
    mockViewport.isMobile = true;

    const { container } = renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText("Implement authentication")).toBeInTheDocument();
    });

    expect(container.querySelector(".sticky.bottom-0")).toBeNull();
  });

  it("realigns after Virtuoso measures the newly posted row", async () => {
    mockApiObj.createComment.mockResolvedValue({
      id: "comment-new",
      issue_id: "issue-1",
      content: "A new update",
      author_type: "member",
      author_id: "user-1",
      parent_id: null,
      type: "comment",
      created_at: "2026-08-13T00:00:00Z",
      updated_at: "2026-08-13T00:00:00Z",
    });
    renderIssueDetail();

    await screen.findByText("Implement authentication");
    fireEvent.click(screen.getByTestId("comment-composer-shell"));
    const editor = await screen.findByPlaceholderText("Leave a comment...");
    fireEvent.change(editor, { target: { value: "A new update" } });
    const composer = editor.closest<HTMLElement>("[aria-busy], .relative.flex.flex-col.rounded-lg")!;
    fireEvent.click(within(composer).getByRole("button", { name: "Send" }));

    expect(scrollToIndexSpy).not.toHaveBeenCalled();
    await waitFor(() => {
      expect(scrollToIndexSpy).toHaveBeenCalledTimes(2);
    });
    expect(scrollToIndexSpy).toHaveBeenNthCalledWith(1, { index: 2, align: "end", offset: 0 });
    expect(scrollToIndexSpy).toHaveBeenNthCalledWith(2, { index: 2, align: "end", offset: 0 });
    expect(scrollIntoViewSpy).not.toHaveBeenCalled();
  });

  it("keeps metadata collapsed by default when the bag has keys", async () => {
    mockApiObj.getIssue.mockResolvedValue({
      ...mockIssue,
      metadata: {
        pr_url: "https://example.com/pr/1",
        pipeline_status: "running",
      },
    });

    renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByRole("button", { name: /^Metadata\b/ })).toBeInTheDocument();
    });

    // Keys stay hidden until the section is expanded.
    expect(screen.queryByText("pr_url")).not.toBeInTheDocument();
    expect(screen.queryByText("pipeline_status")).not.toBeInTheDocument();
  });

  it("expands metadata inline from the shared sidebar header", async () => {
    mockApiObj.getIssue.mockResolvedValue({
      ...mockIssue,
      metadata: { pipeline_status: "running" },
    });
    renderIssueDetail();
    fireEvent.click(await screen.findByRole("button", { name: /^Metadata\b/ }));
    expect(screen.getByText("pipeline_status")).toBeVisible();
    expect(screen.getByText("running")).toBeVisible();
    expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
  });

  it("hides the Metadata button entirely when the bag is empty", async () => {
    // Default fixture already has metadata: {}, asserted explicitly here.
    renderIssueDetail();

    await screen.findByTestId("issue-sidebar-footer");

    expect(screen.queryByRole("button", { name: /^Metadata\b/ })).not.toBeInTheDocument();
  });

  // Mapping edge cases live in comment-runs.test.ts; this verifies the shipped
  // IssueDetail -> CommentCard -> metadata card wiring as server caches change.
  it("keeps execution in an agent block before and after its persisted reply arrives", async () => {
    const taskId = "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc";
    const task: AgentTask = {
      id: taskId, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status: "queued", priority: 0, created_at: "2026-01-16T00:00:00Z",
      started_at: null, dispatched_at: null, completed_at: null, result: null, error: null,
      trigger_comment_id: "comment-1", delivered_comment_ids: [],
    };
    const root = mockTimeline[0]!;
    mockApiObj.listTimeline.mockResolvedValue([]);
    mockApiObj.listTasksByIssue.mockResolvedValue([task]);
    mockApiObj.listTaskMessages.mockResolvedValue([
      { task_id: taskId, issue_id: "issue-1", seq: 1, type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } },
    ]);
    const client = createTestQueryClient();
    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={client}>
          <IssueDetail issueId="issue-1" defaultSidebarOpen={false} />
        </QueryClientProvider>
      </I18nProvider>,
    );
    await waitFor(() => expect(client.getQueryData(issueKeys.tasks("issue-1"))).toEqual([task]));
    await waitFor(() => expect(client.getQueryData(issueKeys.timeline("issue-1"))).toEqual([]));
    expect(container.querySelector(`[data-run-id="${taskId}"]`)).toBeNull();
    mockApiObj.listTimeline.mockResolvedValue([root]);
    act(() => client.setQueryData(issueKeys.timeline("issue-1"), [root]));
    await screen.findByText("Waiting for an available agent.");
    const userBlock = container.querySelector(`#root-comment-body-${root.id}`)!.parentElement!;
    const agentBlock = container.querySelector(`[data-run-comment-id="${taskId}"]`)!;
    expect(agentBlock).not.toBeNull();
    expect(userBlock.contains(agentBlock)).toBe(false);
    expect(threadRow(agentBlock).parentElement).toBe(userBlock.parentElement);
    expect(agentBlock.querySelector(`[data-run-id="${taskId}"]`)).not.toBeNull();
    const running: AgentTask = { ...task, status: "running", started_at: task.created_at, delivered_comment_ids: [root.id] };
    act(() => client.setQueryData(issueKeys.tasks("issue-1"), [running]));
    await screen.findByText("pnpm test");
    expect(container.querySelector(`[data-run-comment-id="${taskId}"]`)).toBe(agentBlock);
    expect(userBlock.querySelector("[data-run-id]")).toBeNull();

    fireEvent.click(within(agentBlock as HTMLElement).getByRole("button", { name: /View activity/ }));
    await within(agentBlock as HTMLElement).findByRole("button", { name: "Open full log" });

    const reply: TimelineEntry = {
      ...mockTimeline[1]!, id: "run-reply", parent_id: root.id, source_task_id: taskId,
      content: "Review complete. The navigation is ready.",
    };
    const completed: AgentTask = { ...running, status: "completed", completed_at: "2026-01-16T00:01:00Z" };
    mockApiObj.listTasksByIssue.mockResolvedValue([running]);
    mockApiObj.listTimeline.mockResolvedValue([root, reply]);
    act(() => {
      client.setQueryData(issueKeys.timeline("issue-1"), [root, reply]);
    });
    const body = await screen.findByText(reply.content!);
    const replyRow = container.querySelector("#comment-run-reply")!;
    await waitFor(() => expect(within(replyRow as HTMLElement).getByRole("button", { name: "Open full log" })).toBeInTheDocument());
    expect(within(replyRow as HTMLElement).queryByText("Completed")).not.toBeInTheDocument();
    const run = replyRow.querySelector(`[data-run-id="${taskId}"]`)!;
    expect(run.querySelector('[data-slot="card"]')).toBeNull();
    expect(container.querySelectorAll(`[data-run-id="${taskId}"]`)).toHaveLength(1);
    expect(run.contains(body)).toBe(false);
    expect(replyRow.contains(body)).toBe(true);
    expect(container.querySelector(`[data-run-comment-id="${taskId}"]`)).toBeNull();
    expect(userBlock.querySelector("[data-run-id]")).toBeNull();
    expect(within(replyRow as HTMLElement).queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
    expect(within(run as HTMLElement).queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
    const logButton = within(run as HTMLElement).getByRole("button", { name: "Open full log" });
    expect(logButton.closest("[data-comment-block]")?.querySelector("[data-run-summary-row]")).toBeNull();
    mockApiObj.listTasksByIssue.mockResolvedValue([completed]);
    act(() => client.setQueryData(issueKeys.tasks("issue-1"), [completed]));
    await waitFor(() => expect(within(run as HTMLElement).queryByRole("button", { name: "Stop" })).not.toBeInTheDocument());
    expect(within(run as HTMLElement).getByRole("button", { name: "Open full log" })).toBe(logButton);
    fireEvent.click(within(run as HTMLElement).getByRole("button", { name: "Open full log" }));
    await screen.findByRole("dialog");
    expect(mockApiObj.listTaskMessages).toHaveBeenCalledWith(taskId);
  });

  it("places one coalesced queued block after the batch's latest reply", async () => {
    const root = mockTimeline[0]!;
    const first = { ...mockTimeline[1]!, id: "queued-first", parent_id: root.id,
      content: "First queued instruction", created_at: "2026-01-16T00:00:01Z" };
    const latest = { ...first, id: "queued-latest", content: "Latest queued instruction",
      created_at: "2026-01-16T00:00:02Z" };
    const task: AgentTask = {
      id: "4a2e8d1c-7f9b-4e2a-9c1d-123456789abd", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status: "queued", priority: 0, created_at: root.created_at,
      started_at: null, dispatched_at: null, completed_at: null, result: null, error: null,
      trigger_comment_id: latest.id, coalesced_comment_ids: [first.id], delivered_comment_ids: [],
    };
    mockApiObj.listTimeline.mockResolvedValue([root, first, latest]);
    mockApiObj.listTasksByIssue.mockResolvedValue([task]);
    const { container } = renderIssueDetail();

    await screen.findByText("Waiting for an available agent.");
    const run = container.querySelector(`[data-run-comment-id="${task.id}"]`)!;
    expect(run).not.toBeNull();
    const latestComment = container.querySelector(`#comment-${latest.id}`);
    const firstComment = container.querySelector(`#comment-${first.id}`);
    expect(latestComment).not.toBeNull();
    expect(firstComment).not.toBeNull();
    expect(threadRow(latestComment!).nextElementSibling).toBe(threadRow(run));
    expect(threadRow(firstComment!).nextElementSibling).not.toBe(threadRow(run));
  });

  it("keeps the running block after its delivered comment and one queued block after later replies", async () => {
    const root = mockTimeline[0]!;
    const first = { ...mockTimeline[1]!, id: "successor-first", parent_id: root.id,
      content: "First successor instruction", created_at: "2026-01-16T00:00:01Z" };
    const latest = { ...first, id: "successor-latest", content: "Latest successor instruction",
      created_at: "2026-01-16T00:00:02Z" };
    const running: AgentTask = {
      id: "4a2e8d1c-7f9b-4e2a-9c1d-123456789ab0", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status: "running", priority: 0, created_at: root.created_at,
      started_at: root.created_at, dispatched_at: root.created_at, completed_at: null, result: null, error: null,
      trigger_comment_id: root.id, delivered_comment_ids: [root.id],
    };
    const queued: AgentTask = {
      ...running,
      id: "4a2e8d1c-7f9b-4e2a-9c1d-123456789ab1",
      status: "queued", started_at: null, dispatched_at: null,
      trigger_comment_id: latest.id, coalesced_comment_ids: [first.id], delivered_comment_ids: [],
    };
    mockApiObj.listTimeline.mockResolvedValue([root, first, latest]);
    mockApiObj.listTasksByIssue.mockResolvedValue([running, queued]);
    const { container } = renderIssueDetail();

    await waitFor(() => {
      expect(container.querySelector(`[data-run-comment-id="${running.id}"]`)).not.toBeNull();
      expect(container.querySelector(`[data-run-comment-id="${queued.id}"]`)).not.toBeNull();
    });
    const rootContent = container.querySelector(`[data-comment-content="${root.id}"]`);
    const runningBlock = container.querySelector(`[data-run-comment-id="${running.id}"]`);
    const firstComment = container.querySelector(`#comment-${first.id}`);
    const latestComment = container.querySelector(`#comment-${latest.id}`);
    const queuedBlock = container.querySelector(`[data-run-comment-id="${queued.id}"]`);
    expect(rootContent).not.toBeNull();
    expect(runningBlock).not.toBeNull();
    expect(firstComment).not.toBeNull();
    expect(latestComment).not.toBeNull();
    expect(queuedBlock).not.toBeNull();
    expect(rootContent!.compareDocumentPosition(runningBlock!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    expect(runningBlock!.compareDocumentPosition(firstComment!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    expect(firstComment!.compareDocumentPosition(latestComment!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    expect(threadRow(latestComment!).nextElementSibling).toBe(threadRow(queuedBlock!));
    expect(container.querySelectorAll(`[data-run-comment-id="${queued.id}"]`)).toHaveLength(1);
  });

  it.each([null, "comment-1"])("shows an assignment reply once in its run slot when posted under %s", async (parentId) => {
    const task: AgentTask = {
      id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status: "queued", priority: 0, created_at: "2026-01-16T00:00:00Z",
      started_at: null, dispatched_at: null, completed_at: null, result: null, error: null,
      delivered_comment_ids: [],
    };
    const existing = { ...mockTimeline[0]!, id: "comment-1" };
    mockApiObj.listTimeline.mockResolvedValue([existing]);
    mockApiObj.listTasksByIssue.mockResolvedValue([task]);
    mockApiObj.listTaskMessages.mockResolvedValue([
      { task_id: task.id, issue_id: "issue-1", seq: 1, type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } },
    ]);
    const queryClient = createTestQueryClient();
    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueDetail issueId="issue-1" defaultSidebarOpen={false} />
        </QueryClientProvider>
      </I18nProvider>,
    );
    await screen.findByText("Waiting for an available agent.");
    expect(container.querySelector(`[data-run-comment-id="${task.id}"]`)).not.toBeNull();
    const assignmentSlot = container.querySelector(`[data-run-slot-id="${task.id}"]`);
    const running: AgentTask = { ...task, status: "running", started_at: task.created_at };
    act(() => queryClient.setQueryData(issueKeys.tasks("issue-1"), [running]));
    await screen.findByText("pnpm test");
    expect(container.querySelectorAll(`[data-run-id="${task.id}"]`)).toHaveLength(1);
    const reply: TimelineEntry = {
      ...mockTimeline[1]!, id: "assignment-reply", parent_id: parentId, source_task_id: task.id,
      content: "Assignment complete.", created_at: "2026-01-16T00:01:00Z",
    };
    const completed: AgentTask = { ...running, status: "completed", completed_at: reply.created_at };
    mockApiObj.listTasksByIssue.mockResolvedValue([running]);
    mockApiObj.listTimeline.mockResolvedValue([existing, reply]);
    act(() => {
      queryClient.setQueryData(issueKeys.timeline("issue-1"), [existing, reply]);
    });
    await waitFor(() => expect(screen.getAllByText(reply.content!)).toHaveLength(1));
    await waitFor(() => expect(container.querySelector(`[data-run-comment-id="${task.id}"]`)).toBeNull());
    const replyBlock = container.querySelector("#comment-assignment-reply")!;
    const parentBlock = container.querySelector("#comment-comment-1")!;
    if (parentId) {
      expect(parentBlock).toContainElement(replyBlock as HTMLElement);
      expect(parentBlock.querySelector(`[data-run-slot-id="${task.id}"]`)).not.toBeNull();
    } else {
      expect(parentBlock).not.toContainElement(replyBlock as HTMLElement);
      expect(container.querySelector(`[data-run-slot-id="${task.id}"]`)).toBe(assignmentSlot);
    }
    expect(replyBlock.querySelector(`[data-run-id="${task.id}"]`)).not.toBeNull();
    expect(container.querySelectorAll(`[data-run-id="${task.id}"]`)).toHaveLength(1);
    const headerLog = within(replyBlock as HTMLElement).getByRole("button", { name: "Open full log" });
    expect(replyBlock.querySelector("[data-run-summary-row]")).toBeNull();
    expect(within(replyBlock as HTMLElement).queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
    mockApiObj.listTasksByIssue.mockResolvedValue([completed]);
    act(() => queryClient.setQueryData(issueKeys.tasks("issue-1"), [completed]));
    await waitFor(() => expect(within(replyBlock as HTMLElement).queryByRole("button", { name: "Stop" })).not.toBeInTheDocument());
    expect(within(replyBlock as HTMLElement).getByRole("button", { name: "Open full log" })).toBe(headerLog);
  });

  it("keeps each queued run after its request and moves it in place to its reply's time", async () => {
    const root = mockTimeline[0]!;
    const second = { ...root, id: "request-two", parent_id: root.id, content: "Second request", created_at: "2026-01-16T00:00:02Z" };
    const third = { ...root, id: "request-three", parent_id: root.id, content: "Third request", created_at: "2026-01-16T00:00:04Z" };
    const tasks: AgentTask[] = [root, second, third].map((trigger, index) => ({
      id: `ba2e8d1c-7f9b-4e2a-9c1d-123456789ab${index}`, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status: "queued", priority: 0, created_at: trigger.created_at,
      started_at: null, dispatched_at: null, completed_at: null, result: null, error: null,
      trigger_comment_id: trigger.id, delivered_comment_ids: [],
    }));
    let timeline = [root, second, third];
    mockApiObj.listTimeline.mockResolvedValue(timeline);
    mockApiObj.listTasksByIssue.mockResolvedValue(tasks);
    const client = createTestQueryClient();
    const { container } = render(<I18nProvider locale="en" resources={TEST_RESOURCES}>
      <QueryClientProvider client={client}><IssueDetail issueId="issue-1" defaultSidebarOpen={false} /></QueryClientProvider>
    </I18nProvider>);
    await waitFor(() => expect(container.querySelectorAll('[data-run-slot-id]')).toHaveLength(3));
    const slots = tasks.map((task) => container.querySelector(`[data-run-slot-id="${task.id}"]`)!);
    const [secondRow, thirdRow] = [second, third].map((request) => container.querySelector(`#comment-${request.id}`)!);
    expect(threadRow(secondRow!).previousElementSibling).toBe(threadRow(slots[0]!));
    expect(threadRow(secondRow!).nextElementSibling).toBe(threadRow(slots[1]!));
    expect(threadRow(thirdRow!).nextElementSibling).toBe(threadRow(slots[2]!));
    fireEvent.click(within(slots[0] as HTMLElement).getByRole("button", { name: /View activity/ }));
    await within(slots[0] as HTMLElement).findByText("No activity recorded yet.");
    for (const index of [0, 1]) {
      const reply: TimelineEntry = { ...mockTimeline[1]!, id: `answer-${index}`, parent_id: index === 0 ? null : root.id,
        source_task_id: tasks[index]!.id, content: `Answer ${index}`, created_at: `2026-01-16T00:01:0${index}Z` };
      tasks[index] = { ...tasks[index]!, status: "completed", completed_at: reply.created_at,
        delivered_comment_ids: [tasks[index]!.trigger_comment_id!] };
      timeline = [...timeline, reply];
      mockApiObj.listTasksByIssue.mockResolvedValue([...tasks]);
      mockApiObj.listTimeline.mockResolvedValue(timeline);
      act(() => {
        client.setQueryData(issueKeys.tasks("issue-1"), [...tasks]);
        client.setQueryData(issueKeys.timeline("issue-1"), timeline);
      });
      await screen.findByText(reply.content!);
      expect(container.querySelector(`[data-run-slot-id="${tasks[index]!.id}"]`)).toBe(slots[index]);
      expect(slots[index]!.textContent).toContain(reply.content);
      expect(container.querySelectorAll(`[data-run-id="${tasks[index]!.id}"]`)).toHaveLength(1);
    }
    expect(within(slots[0] as HTMLElement).getByRole("button", { name: "Open full log" })).toBeInTheDocument();
    expect(within(slots[0] as HTMLElement).queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
    // Answers land at their own time, after the requests; the queued run
    // stays with its request.
    expect(threadRow(thirdRow!).nextElementSibling).toBe(threadRow(slots[2]!));
    expect(threadRow(slots[2]!).nextElementSibling).toBe(threadRow(slots[0]!));
    expect(threadRow(slots[0]!).nextElementSibling).toBe(threadRow(slots[1]!));
    expect(container.querySelector(`[data-run-slot-id="${tasks[2]!.id}"]`)).toBe(slots[2]);
    expect(within(slots[2] as HTMLElement).getByText("Waiting for an available agent.")).toBeInTheDocument();
  });

  it("keeps a downstream run in the thread after its triggering agent reply is projected there", async () => {
    const root = mockTimeline[0]!;
    const first: AgentTask = { id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789ab0", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status: "completed", priority: 0, created_at: root.created_at, started_at: root.created_at, dispatched_at: null,
      completed_at: "2026-01-16T00:01:00Z", result: null, error: null, trigger_comment_id: root.id };
    const answer = { ...mockTimeline[1]!, id: "answer-a", parent_id: null, source_task_id: first.id, content: "Agent A response" };
    const second: AgentTask = { ...first, id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789ab1", agent_id: "agent-2", status: "queued",
      started_at: null, completed_at: null, trigger_comment_id: answer.id };
    mockApiObj.listTimeline.mockResolvedValue([root, answer]);
    mockApiObj.listTasksByIssue.mockResolvedValue([first, second]);
    const { container } = renderIssueDetail();
    await screen.findByText(answer.content);
    await waitFor(() => expect(container.querySelectorAll(`[data-run-id="${second.id}"]`)).toHaveLength(1));
    expect(container.querySelector(`#comment-${root.id}`)?.querySelector(`[data-run-id="${second.id}"]`)).not.toBeNull();
  });

  // MUL-7628: Elon was asked first but replied last; his review used to render
  // under the request, above the rest of the thread.
  it("orders thread replies by send time and quotes the request a late reply answers", async () => {
    const root = mockTimeline[0]!;
    const request = (id: string, content: string, created_at: string): TimelineEntry =>
      ({ ...root, id, parent_id: root.id, content, created_at, updated_at: created_at });
    const askElon = request("ask-elon", "Review the code", "2026-01-16T00:15:32Z");
    const askSteve = request("ask-steve", "CI is failing", "2026-01-16T00:15:41Z");
    const run = (id: string, trigger: TimelineEntry): AgentTask => ({
      id, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1", status: "completed", priority: 0,
      created_at: trigger.created_at, started_at: trigger.created_at, dispatched_at: trigger.created_at,
      completed_at: "2026-01-16T00:40:00Z", result: null, error: null,
      trigger_comment_id: trigger.id, delivered_comment_ids: [trigger.id],
    });
    const elon = run("ba2e8d1c-7f9b-4e2a-9c1d-123456789ab0", askElon);
    const steve = run("ba2e8d1c-7f9b-4e2a-9c1d-123456789ab1", askSteve);
    const answer = (id: string, task: AgentTask, content: string, created_at: string): TimelineEntry =>
      ({ ...mockTimeline[1]!, id, parent_id: root.id, source_task_id: task.id, content, created_at, updated_at: created_at });
    mockApiObj.listTimeline.mockResolvedValue([root, askElon, askSteve,
      answer("steve-fixed", steve, "Fixed the CI failure", "2026-01-16T00:23:41Z"),
      answer("elon-review", elon, "Review complete", "2026-01-16T00:32:29Z"),
      request("follow-up", "Fix it, then ask for another review", "2026-01-16T00:35:05Z")]);
    mockApiObj.listTasksByIssue.mockResolvedValue([elon, steve]);
    const { container } = renderIssueDetail();

    await screen.findByText("Review complete");
    const order = ["ask-elon", "ask-steve", "steve-fixed", "elon-review", "follow-up"].map((id) => `comment-${id}`);
    expect(Array.from(container.querySelectorAll("[id]"), (element) => element.id).filter((id) => order.includes(id)))
      .toEqual(order);
    const review = container.querySelector("#comment-elon-review") as HTMLElement;
    const quote = within(review).getByRole("button", { name: "Replying to Test User: Review the code" });
    expect(within(container.querySelector("#comment-steve-fixed") as HTMLElement).queryByText(/Replying to/)).toBeNull();
    fireEvent.click(quote);
    expect(container.querySelector("#comment-ask-elon")?.className).toContain(highlightedCommentBackgroundClass);
  });

  it.each(["failed", "cancelled"] as const)("keeps a %s run outside the user reply that triggered it", async (status) => {
    const root = mockTimeline[0]!;
    const trigger = { ...root, id: "user-reply", parent_id: root.id, content: "Please try this task" };
    const task: AgentTask = {
      id: "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status, priority: 0, created_at: "2026-01-16T00:00:00Z",
      started_at: null, dispatched_at: null, completed_at: "2026-01-16T00:01:00Z", result: null, error: null,
      trigger_comment_id: trigger.id, delivered_comment_ids: [],
    };
    mockApiObj.listTimeline.mockResolvedValue([root, trigger]);
    mockApiObj.listTasksByIssue.mockResolvedValue([task]);
    const { container } = renderIssueDetail();
    await screen.findByText(trigger.content);
    await waitFor(() => expect(container.querySelector(`[data-run-comment-id="${task.id}"]`)).not.toBeNull());
    const userReply = container.querySelector("#comment-user-reply")!;
    const agentBlock = container.querySelector(`[data-run-comment-id="${task.id}"]`)!;
    expect(userReply.contains(agentBlock)).toBe(false);
    expect(threadRow(userReply).nextElementSibling).toBe(threadRow(agentBlock));
    expect(within(agentBlock as HTMLElement).getByRole("button", { name: "Retry run" })).toBeInTheDocument();
    expect(container.querySelectorAll(`[data-run-id="${task.id}"]`)).toHaveLength(1);
  });

  it("jumps from a header chip row to the run's block in its thread", async () => {
    const root = mockTimeline[0]!;
    const task: AgentTask = {
      id: "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status: "running", priority: 0, created_at: "2026-01-16T00:00:00Z",
      started_at: "2026-01-16T00:00:00Z", dispatched_at: null, completed_at: null, result: null, error: null,
      trigger_comment_id: root.id, delivered_comment_ids: [root.id],
    };
    mockApiObj.listTimeline.mockResolvedValue([root]);
    mockApiObj.listTasksByIssue.mockResolvedValue([task]);
    const { container } = renderIssueDetail();
    await waitFor(() => expect(container.querySelector(`[data-run-slot-id="${task.id}"]`)).not.toBeNull());
    const block = container.querySelector(`[data-run-slot-id="${task.id}"]`)!;
    expect(block.className).not.toContain(highlightedCommentBackgroundClass);

    fireEvent.click(screen.getByRole("button", { name: "Claude Agent is working" }));
    fireEvent.click(await screen.findByRole("button", { name: /Go to run/ }));

    expect(scrollToIndexSpy).toHaveBeenLastCalledWith({ index: expect.any(Number), align: "start", offset: -16 });
    await waitFor(() => expect(block.className).toContain(highlightedCommentBackgroundClass));
  });

  describe("a run's failure notice (MUL-7692)", () => {
    const failedRun = (overrides: Partial<AgentTask> = {}): AgentTask => ({
      id: "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
      status: "failed", failure_reason: "cancelled", error: "task cancelled by server", priority: 0,
      created_at: "2026-01-18T00:00:00Z", dispatched_at: "2026-01-18T00:00:01Z", started_at: "2026-01-18T00:00:02Z",
      completed_at: "2026-01-18T00:12:58Z", result: null, ...overrides,
    });
    const notice = (task: AgentTask, parent_id: string | null): TimelineEntry => ({
      type: "comment", id: "failure-notice", actor_type: "agent", actor_id: "agent-1", content: "task cancelled by server",
      parent_id, created_at: "2026-01-18T00:12:58Z", updated_at: "2026-01-18T00:12:58Z", comment_type: "system",
      source_task_id: task.id,
    });
    const expectStatedOnce = (slot: HTMLElement) => {
      expect(within(slot).getByText("Cancelled by the system")).toBeInTheDocument();
      expect(within(slot).queryByText("task cancelled by server")).not.toBeInTheDocument();
      expect(within(slot).queryByText("Failed")).not.toBeInTheDocument();
      // Once in the timeline. The sidebar's execution log lists the latest
      // runs with their own row actions, which is a separate surface.
      const timelineRetries = screen
        .getAllByRole("button", { name: "Retry run" })
        .filter((button) => !button.closest(".\\@container\\/execution-log"));
      expect(timelineRetries).toHaveLength(1);
    };

    it("renders the run block in the notice's thread slot and retries that run", async () => {
      const root = mockTimeline[0]!;
      const trigger = { ...root, id: "user-reply", parent_id: root.id, content: "Please try this task" };
      const task = failedRun({ trigger_comment_id: trigger.id, delivered_comment_ids: [trigger.id] });
      mockApiObj.listTimeline.mockResolvedValue([root, trigger, notice(task, trigger.id)]);
      mockApiObj.listTasksByIssue.mockResolvedValue([task]);
      const { container } = renderIssueDetail();

      await waitFor(() => expect(container.querySelector("#comment-failure-notice [data-run-id]")).not.toBeNull());
      const slot = container.querySelector("#comment-failure-notice") as HTMLElement;
      expect(slot.getAttribute("data-run-comment-id")).toBe(task.id);
      expectStatedOnce(slot);
      fireEvent.click(within(slot).getByRole("button", { name: "Retry run" }));
      await waitFor(() => expect(mockApiObj.rerunIssue).toHaveBeenCalledWith("issue-1", task.id));
    });

    it("renders a top-level notice as the run block", async () => {
      const task = failedRun();
      mockApiObj.listTimeline.mockResolvedValue([...mockTimeline, notice(task, null)]);
      mockApiObj.listTasksByIssue.mockResolvedValue([task]);
      const { container } = renderIssueDetail();

      await waitFor(() => expect(container.querySelector(`[data-run-comment-id="${task.id}"]`)).not.toBeNull());
      expectStatedOnce(container.querySelector("#comment-failure-notice") as HTMLElement);
    });

    it("keeps a replied-to notice as its thread, without the raw body", async () => {
      const task = failedRun();
      const reply: TimelineEntry = { ...mockTimeline[0]!, id: "reply-to-notice", parent_id: "failure-notice",
        content: "Retrying after the deploy", created_at: "2026-01-18T00:20:00Z", updated_at: "2026-01-18T00:20:00Z" };
      mockApiObj.listTimeline.mockResolvedValue([...mockTimeline, notice(task, null), reply]);
      mockApiObj.listTasksByIssue.mockResolvedValue([task]);
      const { container } = renderIssueDetail();

      await screen.findByText("Retrying after the deploy");
      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));
      });
    });
  });

  // Creator and dates are one line under every section, not a section.
  it("closes the sidebar with a one-line creation footer after the sections", async () => {
    mockApiObj.listTasksByIssue.mockResolvedValue([
      {
        id: "task-past",
        agent_id: "agent-1",
        runtime_id: "runtime-1",
        issue_id: "issue-1",
        status: "completed",
        priority: 0,
        dispatched_at: null,
        started_at: "2026-06-08T08:00:00Z",
        completed_at: "2026-06-08T08:05:00Z",
        result: null,
        error: null,
        created_at: "2026-06-08T08:00:00Z",
        trigger_summary: "Started from comment",
      },
    ]);

    renderIssueDetail();

    const executionLog = await screen.findByText("Execution log");
    const footer = await screen.findByTestId("issue-sidebar-footer");
    expect(footer).toHaveTextContent(/^Created by Test User · Jan 1[45]$/);
    expect(screen.queryByText("Details")).not.toBeInTheDocument();
    expect(
      executionLog.compareDocumentPosition(footer) & Node.DOCUMENT_POSITION_FOLLOWING,
    ).toBeTruthy();
  });

  it("keeps an unsaved comment mounted when the primary background refresh fails", async () => {
    const queryClient = createTestQueryClient();
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueDetail issueId="issue-1" />
        </QueryClientProvider>
      </I18nProvider>,
    );
    await screen.findByText("Implement authentication");
    fireEvent.click(screen.getByTestId("comment-composer-shell"));
    const editor = await screen.findByPlaceholderText("Leave a comment...");
    fireEvent.change(editor, { target: { value: "Unsaved synthetic comment" } });
    mockApiObj.getIssue.mockRejectedValue(new ApiError("unavailable", 503, "Unavailable"));
    await act(async () => {
      await queryClient.refetchQueries({ queryKey: issueKeys.detail("ws-1", "issue-1"), exact: true });
    });
    expect(queryClient.getQueryState(issueKeys.detail("ws-1", "issue-1"))?.status).toBe("error");
    expect(editor).toBeInTheDocument();
    expect(editor).toHaveValue("Unsaved synthetic comment");
    expect(screen.queryByText("Could not load issue.")).not.toBeInTheDocument();
  });

  it("shows 'not found' message when issue does not exist", async () => {
    mockApiObj.getIssue.mockRejectedValue(new ApiError("Not found", 404, "Not Found"));

    renderIssueDetail("nonexistent-id");

    await waitFor(() => {
      expect(
        screen.getByText("This issue does not exist or has been deleted in this workspace."),
      ).toBeInTheDocument();
    });
  });

  it("shows 'Back' button when issue is not found and no onDelete prop", async () => {
    mockApiObj.getIssue.mockRejectedValue(new ApiError("Not found", 404, "Not Found"));

    renderIssueDetail("nonexistent-id");

    await waitFor(() => {
      expect(screen.getByText("Back")).toBeInTheDocument();
    });
  });

  it("renders comments from timeline", async () => {
    renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText("Started working on this")).toBeInTheDocument();
    });

    expect(screen.getByText("I can help with this")).toBeInTheDocument();
  });

  // Comment cards are memoized so page state that has nothing to do with the
  // timeline does not re-render every comment on a long issue. Any handler the
  // page hands to the cards must keep its identity across such renders.
  it("does not re-render comment cards when unrelated page state changes", async () => {
    renderIssueDetail();
    await screen.findByText("I can help with this");
    const properties = await screen.findByRole("button", { name: "Properties" });

    const commentBodies = new Set(mockTimeline.map((entry) => entry.content));
    const cardRenders = () =>
      readonlyContentRenders.filter((content) => commentBodies.has(content)).length;
    const before = cardRenders();

    fireEvent.click(properties);

    expect(cardRenders()).toBe(before);
  });

  it("prefers timeline identity when the actor is absent from the member directory", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "comment",
        id: "former-member-comment",
        actor_type: "member",
        actor_id: "former-user-1",
        actor_name: "Former Member",
        actor_avatar_url: "https://profiles.example.com/former.png",
        content: "Authored before leaving",
        parent_id: null,
        created_at: "2026-01-18T00:00:00Z",
        updated_at: "2026-01-18T00:00:00Z",
        comment_type: "comment",
      },
    ]);

    renderIssueDetail();

    await screen.findByText("Authored before leaving");
    expect(screen.getByText("Former Member")).toBeInTheDocument();
  });

  it("reruns the source task from an agent failure comment", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      ...mockTimeline,
      {
        type: "comment",
        id: "comment-failed-task",
        actor_type: "agent",
        actor_id: "agent-1",
        content: "API Error: 500 Internal server error",
        parent_id: null,
        created_at: "2026-01-18T00:00:00Z",
        updated_at: "2026-01-18T00:00:00Z",
        comment_type: "system",
        source_task_id: "task-failed",
      },
    ]);

    renderIssueDetail();

    await screen.findByText("API Error: 500 Internal server error");
    fireEvent.click(screen.getByRole("button", { name: "Retry run" }));

    await waitFor(() => {
      expect(mockApiObj.rerunIssue).toHaveBeenCalledWith("issue-1", "task-failed");
    });
  });

  it("does not show retry for child-done system comments", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      ...mockTimeline,
      {
        type: "comment",
        id: "comment-child-done",
        actor_type: "system",
        actor_id: "00000000-0000-0000-0000-000000000000",
        content: "Sub-issue MUL-123 is done.",
        parent_id: null,
        created_at: "2026-01-18T00:00:00Z",
        updated_at: "2026-01-18T00:00:00Z",
        comment_type: "system",
      },
    ]);

    renderIssueDetail();

    await screen.findByText("Sub-issue MUL-123 is done.");
    expect(screen.queryByRole("button", { name: "Retry run" })).not.toBeInTheDocument();
  });

  it("does not show retry for successful agent task comments", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      ...mockTimeline,
      {
        type: "comment",
        id: "comment-successful-task",
        actor_type: "agent",
        actor_id: "agent-1",
        content: "Finished the requested work.",
        parent_id: null,
        created_at: "2026-01-18T00:00:00Z",
        updated_at: "2026-01-18T00:00:00Z",
        comment_type: "comment",
        source_task_id: "task-success",
      },
    ]);

    renderIssueDetail();

    await screen.findByText("Finished the requested work.");
    expect(screen.queryByRole("button", { name: "Retry run" })).not.toBeInTheDocument();
  });

  it("does not show retry for agent system comments without a source task", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      ...mockTimeline,
      {
        type: "comment",
        id: "comment-agent-system",
        actor_type: "agent",
        actor_id: "agent-1",
        content: "System coordination update.",
        parent_id: null,
        created_at: "2026-01-18T00:00:00Z",
        updated_at: "2026-01-18T00:00:00Z",
        comment_type: "system",
      },
    ]);

    renderIssueDetail();

    await screen.findByText("System coordination update.");
    expect(screen.queryByRole("button", { name: "Retry run" })).not.toBeInTheDocument();
  });

  describe("an issue an agent created for a member (#7995)", () => {
    const created = (actorType: "agent" | "member", actorId: string): TimelineEntry => ({
      type: "activity",
      id: "act-created",
      actor_type: actorType,
      actor_id: actorId,
      action: "created",
      details: {},
      created_at: "2026-01-15T00:00:00Z",
    });

    it("names the requester in the created entry and under the creator", async () => {
      mockApiObj.getIssue.mockResolvedValue({
        ...mockIssue,
        creator_type: "agent",
        creator_id: "agent-1",
        requester_id: "user-1",
      });
      mockApiObj.listTimeline.mockResolvedValue([created("agent", "agent-1")]);

      renderIssueDetail();

      expect(await screen.findByText("created this issue on behalf of Test User")).toBeInTheDocument();
      expect(screen.getByTestId("issue-sidebar-footer")).toHaveTextContent(/^Created by Claude Agent for Test User · Jan 1[45]$/);
      expect(screen.queryByText("Requested by")).not.toBeInTheDocument();
    });

    it.each([
      { creatorType: "agent", creatorId: "agent-1", requesterId: null },
      { creatorType: "agent", creatorId: "agent-1", requesterId: undefined },
      { creatorType: "member", creatorId: "user-1", requesterId: "user-1" },
    ] as const)("keeps plain creation for $creatorType with requester $requesterId", async ({ creatorType, creatorId, requesterId }) => {
      mockApiObj.getIssue.mockResolvedValue({
        ...mockIssue,
        creator_type: creatorType,
        creator_id: creatorId,
        requester_id: requesterId,
      });
      mockApiObj.listTimeline.mockResolvedValue([created(creatorType, creatorId)]);

      renderIssueDetail();

      expect(await screen.findByText("created this issue")).toBeInTheDocument();
      expect(screen.getByTestId("issue-sidebar-footer")).not.toHaveTextContent(" for ");
      expect(screen.queryByText("Requested by")).not.toBeInTheDocument();
    });

    it("uses the existing member-name fallback when the requester is unavailable", async () => {
      mockApiObj.getIssue.mockResolvedValue({
        ...mockIssue,
        creator_type: "agent",
        creator_id: "agent-1",
        requester_id: "former-member",
      });
      mockApiObj.listTimeline.mockResolvedValue([created("agent", "agent-1")]);

      renderIssueDetail();

      expect(await screen.findByText("created this issue on behalf of Unknown")).toBeInTheDocument();
      expect(screen.getByTestId("issue-sidebar-footer")).toHaveTextContent("for Unknown");
    });
  });

  it("collapses non-trailing activity blocks and expands the last one by default", async () => {
    // Timeline shape:
    //   [activities: status_changed, priority_changed] ← block A (older)
    //   [comment-1]
    //   [activities: due_date_changed]                  ← block B (latest)
    // Block A should be collapsed; block B should be expanded.
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "activity",
        id: "act-1",
        actor_type: "member",
        actor_id: "user-1",
        action: "status_changed",
        details: { from: "todo", to: "in_progress" },
        created_at: "2026-01-16T00:00:00Z",
      },
      {
        type: "activity",
        id: "act-2",
        actor_type: "member",
        actor_id: "user-1",
        action: "priority_changed",
        details: { from: "low", to: "high" },
        created_at: "2026-01-16T01:00:00Z",
      },
      {
        type: "comment",
        id: "comment-1",
        actor_type: "member",
        actor_id: "user-1",
        content: "Talking it through",
        parent_id: null,
        created_at: "2026-01-17T00:00:00Z",
        updated_at: "2026-01-17T00:00:00Z",
        comment_type: "comment",
      },
      {
        type: "activity",
        id: "act-3",
        actor_type: "member",
        actor_id: "user-1",
        action: "due_date_changed",
        details: { to: "2026-02-01T00:00:00Z" },
        created_at: "2026-01-18T00:00:00Z",
      },
    ] as TimelineEntry[]);

    renderIssueDetail();

    // Latest block (single activity) is expanded — its rendered text is visible.
    await waitFor(() => {
      expect(screen.getByText(/set due date to/i)).toBeInTheDocument();
    });

    // Older block is collapsed: shows the summary, hides the individual entries.
    expect(screen.getByText("2 activities")).toBeInTheDocument();
    expect(screen.queryByText(/changed status/i)).not.toBeInTheDocument();
    expect(screen.queryByText(/changed priority/i)).not.toBeInTheDocument();

    // Clicking the summary expands the older block.
    fireEvent.click(screen.getByText("2 activities"));
    await waitFor(() => {
      expect(screen.getByText(/changed status/i)).toBeInTheDocument();
    });
    expect(screen.getByText(/changed priority/i)).toBeInTheDocument();
  });

  // Duplicate marks (MUL-7349) name another issue; the identifier is a link
  // to it, and a mark removed because its original was deleted is plain text.
  it("links a duplicate mark to the issue it names", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "activity",
        id: "act-dup-marked",
        actor_type: "member",
        actor_id: "user-1",
        action: "duplicate_marked",
        details: { original_id: "issue-9", original_identifier: "MUL-9" },
        created_at: "2026-01-16T00:00:00Z",
      },
      {
        type: "activity",
        id: "act-dup-unmarked",
        actor_type: "member",
        actor_id: "user-1",
        action: "duplicate_unmarked",
        details: { original_id: "issue-8", original_identifier: "MUL-8", reason: "original_deleted" },
        created_at: "2026-01-16T00:00:30Z",
      },
      {
        type: "activity",
        id: "act-dup-reopened",
        actor_type: "member",
        actor_id: "user-1",
        action: "duplicate_unmarked",
        details: { original_id: "issue-9", original_identifier: "MUL-9", to: "todo" },
        created_at: "2026-01-16T00:01:00Z",
      },
    ]);
    renderIssueDetail();

    const links = await screen.findAllByRole("link", { name: "MUL-9" });
    expect(links[0]?.getAttribute("href")).toBe("/test/issues/issue-9");
    expect(screen.getByText(/^marked this issue as a duplicate of/i)).toBeInTheDocument();
    expect(screen.getByText(/removed the duplicate mark \(MUL-8 was deleted\)/i)).toBeInTheDocument();
    expect(screen.queryByRole("link", { name: "MUL-8" })).not.toBeInTheDocument();
    // Reopening replaces the status row, so the unmarked row says where it went.
    expect(screen.getByText(/and moved it to Todo/i)).toBeInTheDocument();
    expect(screen.getAllByRole("link", { name: "MUL-9" })).toHaveLength(2);
  });

  // MUL-7429: an automatic status change says why, and the per-issue switch
  // shows on the timeline.
  it("explains PR merge automation activity", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "activity",
        id: "act-pr-done",
        actor_type: "system",
        actor_id: null,
        action: "status_changed",
        details: { from: "in_progress", to: "done", source: "pr_automation", pull_requests: "#12, #19" },
        created_at: "2026-01-18T00:00:00Z",
      },
      {
        type: "activity",
        id: "act-pr-off",
        actor_type: "member",
        actor_id: "user-1",
        action: "pr_auto_complete_changed",
        details: { disabled: true },
        created_at: "2026-01-18T01:00:00Z",
      },
    ] as unknown as TimelineEntry[]);

    renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText(/after every linked PR merged \(#12, #19\)/i)).toBeInTheDocument();
    });
    expect(screen.getByText(/set this issue to keep its status when PRs merge/i)).toBeInTheDocument();
  });

  // MUL-7680: the child-done system rule's comment is the woken agent's
  // instruction; people read one timeline line that can reveal it.
  it("renders activity rows with unknown status values without crashing", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "activity",
        id: "act-unknown-status",
        actor_type: "member",
        actor_id: "user-1",
        action: "status_changed",
        details: { from: "todo", to: "mystery_status" },
        created_at: "2026-01-18T00:00:00Z",
      },
    ] as TimelineEntry[]);

    renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText(/from Todo to mystery_status/i)).toBeInTheDocument();
    });
  });

  // -------------------------------------------------------------------------
  // MUL-6413 — the activity glyph is per CATEGORY, so a move into a custom
  // status drew the icon of the built-in it sits beside: "In Review → Awaiting
  // Response" repainted identically and read as though nothing had moved.
  // Colour is what carries a custom status's own identity.
  // -------------------------------------------------------------------------

  const IN_REVIEW_BUILT_IN: IssueStatusEntry = {
    id: "in_review",
    workspace_id: "ws-1",
    key: "in_review",
    name: "In Review",
    description: "",
    category: "started",
    color: "#8b5cf6",
    is_system: true,
    position: 0,
    archived_at: null,
    created_at: "",
    updated_at: "",
  };

  const AWAITING_RESPONSE: IssueStatusEntry = {
    ...IN_REVIEW_BUILT_IN,
    id: "awaiting_response",
    key: "awaiting_response",
    name: "Awaiting Response",
    color: "#ff0000",
    is_system: false,
    position: 1,
  };

  function statusChangeIcon(to: string): SVGElement {
    const row = screen.getByText(new RegExp(`to ${to}$`, "i")).closest("div")
      ?.parentElement;
    const icon = row?.querySelector("svg");
    if (!icon) throw new Error(`no status glyph for the "${to}" activity row`);
    return icon;
  }

  it("paints a status-change activity in the custom status's own colour", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "activity",
        id: "act-custom-status",
        actor_type: "member",
        actor_id: "user-1",
        action: "status_changed",
        details: { from: "in_review", to: "awaiting_response" },
        created_at: "2026-01-18T00:00:00Z",
      },
    ] as TimelineEntry[]);

    renderIssueDetailWithStatusCatalog([IN_REVIEW_BUILT_IN, AWAITING_RESPONSE]);

    await waitFor(() => {
      expect(
        screen.getByText(/from In Review to Awaiting Response/i),
      ).toBeInTheDocument();
    });
    expect(statusChangeIcon("Awaiting Response").style.color).toBe("var(--palette-red, #ff0000)");
  });

  it("leaves a built-in status-change activity on its semantic token colour", async () => {
    // The catalog seeds a colour for the built-ins too, but those are theme
    // tokens in the UI — painting the seeded hex would hard-code one theme.
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "activity",
        id: "act-built-in-status",
        actor_type: "member",
        actor_id: "user-1",
        action: "status_changed",
        details: { from: "in_progress", to: "in_review" },
        created_at: "2026-01-18T00:00:00Z",
      },
    ] as TimelineEntry[]);

    renderIssueDetailWithStatusCatalog([IN_REVIEW_BUILT_IN, AWAITING_RESPONSE]);

    await waitFor(() => {
      expect(screen.getByText(/from In Progress to In Review/i)).toBeInTheDocument();
    });
    const icon = statusChangeIcon("In Review");
    expect(icon.style.color).toBe("");
    expect(icon.getAttribute("class")).toContain("text-status-in-review");
  });

  it("truncates the trailing activity block to the most recent 8 entries with a show-more toggle", async () => {
    // 10 activities, all in the trailing block (no comment after them, so it's
    // the trailing block by definition). Alternating action types so the
    // 2-minute coalesce window never merges consecutive entries — we end up
    // with 10 distinct rows.
    const trailingBlock: TimelineEntry[] = [
      { type: "activity", id: "act-1", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "todo", to: "in_progress" }, created_at: "2026-01-18T00:00:00Z" },
      { type: "activity", id: "act-2", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "low", to: "medium" }, created_at: "2026-01-18T00:01:00Z" },
      { type: "activity", id: "act-3", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "in_progress", to: "in_review" }, created_at: "2026-01-18T00:02:00Z" },
      { type: "activity", id: "act-4", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "medium", to: "high" }, created_at: "2026-01-18T00:03:00Z" },
      { type: "activity", id: "act-5", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "in_review", to: "done" }, created_at: "2026-01-18T00:04:00Z" },
      { type: "activity", id: "act-6", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "high", to: "urgent" }, created_at: "2026-01-18T00:05:00Z" },
      { type: "activity", id: "act-7", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "done", to: "blocked" }, created_at: "2026-01-18T00:06:00Z" },
      { type: "activity", id: "act-8", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "urgent", to: "low" }, created_at: "2026-01-18T00:07:00Z" },
      { type: "activity", id: "act-9", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "blocked", to: "todo" }, created_at: "2026-01-18T00:08:00Z" },
      { type: "activity", id: "act-10", actor_type: "member", actor_id: "user-1", action: "due_date_changed", details: { to: "2026-02-01T00:00:00Z" }, created_at: "2026-01-18T00:09:00Z" },
    ] as TimelineEntry[];
    mockApiObj.listTimeline.mockResolvedValue(trailingBlock);

    renderIssueDetail();

    // In the truncated default state the "N activities" collapse header
    // stays hidden — the "Show N more" link is the only control we want
    // to expose for a glance at recent activity.
    await waitFor(() => {
      expect(screen.getByText("Show 2 more activities")).toBeInTheDocument();
    });
    expect(screen.queryByText("10 activities")).not.toBeInTheDocument();

    // Only the 8 most recent entries (act-3..act-10) are rendered by default.
    // act-1 and act-2 are folded behind the show-more line.
    expect(screen.getByText(/from In Progress to In Review/i)).toBeInTheDocument(); // act-3
    expect(screen.getByText(/set due date to/i)).toBeInTheDocument(); // act-10
    expect(screen.queryByText(/from Todo to In Progress/i)).not.toBeInTheDocument(); // act-1
    expect(screen.queryByText(/from Low to Medium/i)).not.toBeInTheDocument(); // act-2

    // Clicking the toggle reveals the older entries in place and brings the
    // full "N activities" header back (so the user can fold the block).
    fireEvent.click(screen.getByText("Show 2 more activities"));
    await waitFor(() => {
      expect(screen.getByText(/from Todo to In Progress/i)).toBeInTheDocument();
    });
    expect(screen.getByText(/from Low to Medium/i)).toBeInTheDocument();
    expect(screen.getByText(/set due date to/i)).toBeInTheDocument();
    expect(screen.getByText("10 activities")).toBeInTheDocument();
    expect(screen.queryByText(/Show \d+ more activit/i)).not.toBeInTheDocument();
  });

  it("does not show the show-more toggle when the trailing block has 8 or fewer entries", async () => {
    const trailingBlock: TimelineEntry[] = [
      { type: "activity", id: "act-1", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "todo", to: "in_progress" }, created_at: "2026-01-18T00:00:00Z" },
      { type: "activity", id: "act-2", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "low", to: "high" }, created_at: "2026-01-18T00:01:00Z" },
      { type: "activity", id: "act-3", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "in_progress", to: "in_review" }, created_at: "2026-01-18T00:02:00Z" },
      { type: "activity", id: "act-4", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "high", to: "urgent" }, created_at: "2026-01-18T00:03:00Z" },
      { type: "activity", id: "act-5", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "in_review", to: "done" }, created_at: "2026-01-18T00:04:00Z" },
      { type: "activity", id: "act-6", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "urgent", to: "low" }, created_at: "2026-01-18T00:05:00Z" },
      { type: "activity", id: "act-7", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "done", to: "blocked" }, created_at: "2026-01-18T00:06:00Z" },
      { type: "activity", id: "act-8", actor_type: "member", actor_id: "user-1", action: "due_date_changed", details: { to: "2026-02-01T00:00:00Z" }, created_at: "2026-01-18T00:07:00Z" },
    ] as TimelineEntry[];
    mockApiObj.listTimeline.mockResolvedValue(trailingBlock);

    renderIssueDetail();

    await waitFor(() => {
      expect(screen.getByText("8 activities")).toBeInTheDocument();
    });
    // Every one of the 8 entries should be visible — the trailing block fits
    // exactly within the limit, so no "Show N more activities" line appears.
    expect(screen.getByText(/from Todo to In Progress/i)).toBeInTheDocument();
    expect(screen.getByText(/from Low to High/i)).toBeInTheDocument();
    expect(screen.getByText(/from In Progress to In Review/i)).toBeInTheDocument();
    expect(screen.getByText(/from High to Urgent/i)).toBeInTheDocument();
    expect(screen.getByText(/from In Review to Done/i)).toBeInTheDocument();
    expect(screen.getByText(/from Urgent to Low/i)).toBeInTheDocument();
    expect(screen.getByText(/from Done to Blocked/i)).toBeInTheDocument();
    expect(screen.getByText(/set due date to/i)).toBeInTheDocument();
    expect(screen.queryByText(/Show \d+ more activit/i)).not.toBeInTheDocument();
  });

  it("expanding a non-trailing block shows every entry — only the trailing block truncates older ones", async () => {
    // Non-trailing block (10 activities) + comment + trailing block (1 activity).
    // Manually expanding the older block must reveal all 10 entries — the
    // truncate-to-8 rule applies only to the trailing block.
    const timeline: TimelineEntry[] = [
      { type: "activity", id: "old-1", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "backlog", to: "todo" }, created_at: "2026-01-16T00:00:00Z" },
      { type: "activity", id: "old-2", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "none", to: "low" }, created_at: "2026-01-16T00:01:00Z" },
      { type: "activity", id: "old-3", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "todo", to: "in_progress" }, created_at: "2026-01-16T00:02:00Z" },
      { type: "activity", id: "old-4", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "low", to: "medium" }, created_at: "2026-01-16T00:03:00Z" },
      { type: "activity", id: "old-5", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "in_progress", to: "in_review" }, created_at: "2026-01-16T00:04:00Z" },
      { type: "activity", id: "old-6", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "medium", to: "high" }, created_at: "2026-01-16T00:05:00Z" },
      { type: "activity", id: "old-7", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "in_review", to: "done" }, created_at: "2026-01-16T00:06:00Z" },
      { type: "activity", id: "old-8", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "high", to: "urgent" }, created_at: "2026-01-16T00:07:00Z" },
      { type: "activity", id: "old-9", actor_type: "member", actor_id: "user-1", action: "status_changed", details: { from: "done", to: "blocked" }, created_at: "2026-01-16T00:08:00Z" },
      { type: "activity", id: "old-10", actor_type: "member", actor_id: "user-1", action: "priority_changed", details: { from: "urgent", to: "low" }, created_at: "2026-01-16T00:09:00Z" },
      {
        type: "comment", id: "comment-mid", actor_type: "member", actor_id: "user-1",
        content: "Splitting the blocks", parent_id: null,
        created_at: "2026-01-17T00:00:00Z", updated_at: "2026-01-17T00:00:00Z",
        comment_type: "comment",
      },
      { type: "activity", id: "last-1", actor_type: "member", actor_id: "user-1", action: "due_date_changed", details: { to: "2026-02-01T00:00:00Z" }, created_at: "2026-01-18T00:00:00Z" },
    ] as TimelineEntry[];
    mockApiObj.listTimeline.mockResolvedValue(timeline);

    renderIssueDetail();

    // The older block defaults to collapsed; its summary reports 10.
    await waitFor(() => {
      expect(screen.getByText("10 activities")).toBeInTheDocument();
    });
    // None of the older entries are rendered before expansion.
    expect(screen.queryByText(/from Backlog to Todo/i)).not.toBeInTheDocument();

    // Expand the older block by clicking its summary line.
    fireEvent.click(screen.getByText("10 activities"));

    // Every one of the 10 entries should now be visible — even though the
    // block has more than 8 entries, the truncate-to-8 rule does not apply
    // to non-trailing blocks, so no "Show N more activities" line appears.
    await waitFor(() => {
      expect(screen.getByText(/from Backlog to Todo/i)).toBeInTheDocument();
    });
    expect(screen.getByText(/from No priority to Low/i)).toBeInTheDocument();
    expect(screen.getByText(/from Todo to In Progress/i)).toBeInTheDocument();
    expect(screen.getByText(/from Low to Medium/i)).toBeInTheDocument();
    expect(screen.getByText(/from In Progress to In Review/i)).toBeInTheDocument();
    expect(screen.getByText(/from Medium to High/i)).toBeInTheDocument();
    expect(screen.getByText(/from In Review to Done/i)).toBeInTheDocument();
    expect(screen.getByText(/from High to Urgent/i)).toBeInTheDocument();
    expect(screen.getByText(/from Done to Blocked/i)).toBeInTheDocument();
    expect(screen.getByText(/from Urgent to Low/i)).toBeInTheDocument();
    expect(screen.queryByText(/Show \d+ more activit/i)).not.toBeInTheDocument();
  });

  it("does not mount offscreen reply bodies in a long discussion", async () => {
    vi.stubGlobal("IntersectionObserver", class {
      observe() {} unobserve() {} disconnect() {}
    });
    const root = { ...mockTimeline[0]!, id: "long-thread-root", parent_id: null, content: "Long discussion root" };
    const replies = Array.from({ length: 200 }, (_, index) => ({
      ...root, id: `offscreen-reply-${index}`, parent_id: root.id, content: `Offscreen body ${index}`,
    }));
    mockApiObj.listTimeline.mockResolvedValue([root, ...replies]);
    mockApiObj.listTasksByIssue.mockResolvedValue([]);
    try {
      renderIssueDetail();
      await screen.findByText("Long discussion root");
      expect(document.getElementById("comment-offscreen-reply-199")).not.toBeNull();
      expect(screen.queryByText("Offscreen body 199")).toBeNull();
      expect(readonlyContentRenders.filter((body) => body.startsWith("Offscreen body"))).toHaveLength(0);
    } finally { vi.unstubAllGlobals(); }
  });

  describe("highlightCommentId scroll-to-comment", () => {
    it.each([
      { kind: "root", delayedViewport: false, lateScrollReset: false },
      { kind: "reply", delayedViewport: false, lateScrollReset: false },
      { kind: "root", delayedViewport: true, lateScrollReset: false },
      { kind: "reply", delayedViewport: false, lateScrollReset: true },
      { kind: "reply", delayedViewport: false, lateScrollReset: false, offscreenViewport: true },
      { kind: "reply", delayedViewport: false, lateScrollReset: false, offscreenViewport: true, contentSettlesAbove: true },
      { kind: "reply", delayedViewport: false, lateScrollReset: false, pendingSizeCorrection: true },
      { kind: "reply", delayedViewport: false, lateScrollReset: false, holdAtIndex: true },
    ])("keeps long history virtualized for a $kind (late viewport: $delayedViewport, late scroll: $lateScrollReset, below fold: $offscreenViewport, settling above: $contentSettlesAbove)", async ({ kind, delayedViewport, lateScrollReset, offscreenViewport, contentSettlesAbove, pendingSizeCorrection, holdAtIndex }) => {
      mockVirtualWindow.holdAtIndex = !!holdAtIndex;
      mockVirtualWindow.pendingSizeCorrection = !!pendingSizeCorrection;
      mockVirtualWindow.enabled = true;
      mockVirtualWindow.delayedViewport = delayedViewport;
      mockVirtualWindow.offscreenViewport = !!offscreenViewport;
      mockVirtualWindow.contentSettlesAbove = !!contentSettlesAbove;
      mockVirtualWindow.lateScrollReset = lateScrollReset;
      const history = Array.from({ length: 120 }, (_, index) => ({
        ...mockTimeline[0]!,
        id: `history-${index}`,
        parent_id: null,
        source_task_id: undefined,
        content: `Historical comment ${index}`,
        created_at: new Date(Date.UTC(2026, 0, 1, 0, index)).toISOString(),
      }));
      const root = history[115]!;
      const target = kind === "root" ? root : {
        ...root,
        id: "deep-reply",
        parent_id: root.id,
        content: "Offscreen reply target",
      };
      mockVirtualWindow.targetId = target.id;
      mockApiObj.listTimeline.mockResolvedValue(kind === "root" ? history : [...history, target]);
      mockApiObj.listTasksByIssue.mockResolvedValue([]);
      renderIssueDetailWithHighlight(target.id);

      // Wait phase by phase: page boot (issue + timeline queries, first
      // commit), the jump mounting the target row, then the landing frames.
      // On a loaded runner the three together outrun one waitFor's budget.
      await screen.findByTestId("virtuoso-mock");
      await waitFor(() => expect(document.getElementById(`comment-${target.id}`)).not.toBeNull());
      await waitFor(() => expect(hasHighlightedCommentBackground(
        document.getElementById(`comment-${target.id}`),
      )).toBe(true));
      if (lateScrollReset || holdAtIndex) {
        await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 150)); });
        expect(mockVirtualWindow.scrollParent?.scrollTop).toBe(200);
      }
      expect(screen.queryByTestId("virtuoso-mock")).not.toBeNull();
      expect(document.querySelectorAll('[id^="comment-history-"]').length).toBeLessThanOrEqual(8);
      expect(document.getElementById("comment-history-0")).toBeNull();
      expect(scrollIntoViewIndexSpy).toHaveBeenCalledWith(expect.objectContaining({ index: 115 }));
    });

    it("waits for run grouping before consuming the comment landing", async () => {
      let finishTasks!: (tasks: AgentTask[]) => void;
      mockApiObj.listTasksByIssue.mockReturnValue(new Promise<AgentTask[]>((resolve) => { finishTasks = resolve; }));
      renderIssueDetailWithHighlight("comment-2");
      await waitFor(() => expect(document.getElementById("comment-comment-2")).not.toBeNull());
      await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 60)); });
      const landedBeforeGrouping = hasHighlightedCommentBackground(document.getElementById("comment-comment-2"));
      await act(async () => { finishTasks([]); });
      await waitFor(() => expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-2"))).toBe(true));
      expect(landedBeforeGrouping).toBe(false);
    });

    describe("on a route that already recorded the landing", () => {
      function renderOverLandedRoute(props: Partial<React.ComponentProps<typeof IssueDetail>> = {}) {
        mockApiObj.listTasksByIssue.mockResolvedValue([]);
        const viewState = new Map([["highlight:issue-1", "comment-2"]]);
        const adapter: ScrollRestorationAdapter = {
          get: () => undefined,
          getViewState: (key) => viewState.get(key),
          setViewState: (key, value) => {
            if (value === undefined) viewState.delete(key);
            else viewState.set(key, value);
          },
        };
        render(
          <I18nProvider locale="en" resources={TEST_RESOURCES}>
            <QueryClientProvider client={createTestQueryClient()}>
              <ScrollRestorationProvider adapter={adapter}>
                <IssueDetail issueId="issue-1" highlightCommentId="comment-2" {...props} />
              </ScrollRestorationProvider>
            </QueryClientProvider>
          </I18nProvider>,
        );
      }

      it("does not replay it when the view merely remounts", async () => {
        renderOverLandedRoute();
        await waitFor(() => expect(document.getElementById("comment-comment-2")).not.toBeNull());
        await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 100)); });
        expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-2"))).toBe(false);
      });

      // MUL-9492: a Work panel click on another page cannot clear the issue
      // route's record before it navigates there.
      it("lands a pending request anyway and reports it", async () => {
        const onHighlightLanded = vi.fn();
        renderOverLandedRoute({ highlightRequestToken: 3, highlightRequestPending: true, onHighlightLanded });
        await waitFor(() => expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-2"))).toBe(true));
        expect(onHighlightLanded).toHaveBeenCalledTimes(1);
      });
    });

    // MUL-9959: the reading position is the comment at the viewport's centre,
    // found as its nearest `[id^="comment-"]` ancestor. The root comment's
    // body sat in between with id `comment-body-<id>`, so a reader in the
    // middle of a comment's text saved "body-<id>", which matches no comment,
    // and the tab came back at the top.
    it("saves the reading position against the comment whose body is at the viewport's centre", async () => {
      mockApiObj.listTasksByIssue.mockResolvedValue([]);
      const anchors: string[] = [];
      const adapter: ScrollRestorationAdapter = {
        get: () => undefined,
        getViewState: () => undefined,
        setViewState: (key, value) => {
          if (key === "timeline-anchor:main:issue-1" && value) anchors.push(value);
        },
      };
      const rect = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
        return this.hasAttribute("data-tab-scroll-root") ? new DOMRect(0, 0, 400, 200) : new DOMRect(0, 0, 0, 0);
      });
      const hadElementFromPoint = "elementFromPoint" in document;
      const originalElementFromPoint = document.elementFromPoint;
      let centre: Element | null = null;
      document.elementFromPoint = () => centre;
      try {
        render(
          <I18nProvider locale="en" resources={TEST_RESOURCES}>
            <QueryClientProvider client={createTestQueryClient()}>
              <ScrollRestorationProvider adapter={adapter}>
                <IssueDetail issueId="issue-1" />
              </ScrollRestorationProvider>
            </QueryClientProvider>
          </I18nProvider>,
        );
        centre = await screen.findByText("Started working on this");
        fireEvent.scroll(centre.closest("[data-tab-scroll-root]")!);
        await waitFor(() => expect(anchors.length).toBeGreaterThan(0));
        expect(JSON.parse(anchors.at(-1)!)).toMatchObject({ commentId: "comment-1" });
      } finally {
        rect.mockRestore();
        if (hadElementFromPoint) document.elementFromPoint = originalElementFromPoint;
        else delete (document as { elementFromPoint?: unknown }).elementFromPoint;
      }
    });

    // MUL-9959: the timeline's Virtuoso took the page's saved offset as its
    // `initialScrollTop`, which it counts from the list's top, so a reader in
    // the description came back a description's height further down.
    it("returns to the saved offset of a page scrolled in the description", async () => {
      mockApiObj.listTasksByIssue.mockResolvedValue([]);
      const adapter: ScrollRestorationAdapter = {
        get: (key) => (key === "main:issue-1" ? { top: 300, height: 2000 } : undefined),
      };
      render(
        <I18nProvider locale="en" resources={TEST_RESOURCES}>
          <QueryClientProvider client={createTestQueryClient()}>
            <ScrollRestorationProvider adapter={adapter}>
              <IssueDetail issueId="issue-1" />
            </ScrollRestorationProvider>
          </QueryClientProvider>
        </I18nProvider>,
      );
      const comment = await screen.findByText("Started working on this");
      await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 200)); });
      expect(comment.closest<HTMLElement>("[data-tab-scroll-root]")!.scrollTop).toBe(300);
    });

    it("restarts a comment landing that a timeline update cancels while it is still aligning", async () => {
      mockApiObj.listTasksByIssue.mockResolvedValue([]);
      // The anchor keeps moving for 300ms, like reply heights settling, so the
      // alignment loop is still running when the update arrives.
      let driftStart = 0;
      const drift = () => {
        driftStart ||= performance.now();
        return Math.min(performance.now() - driftStart, 300);
      };
      // The update lands between two frames of the alignment loop, after its
      // second measurement of the mounted anchor. Timing it from the test
      // instead raced the loop on slow CI runners.
      let interrupt: (() => void) | null = null;
      let alignedReads = 0;
      let interrupted = false;
      const rect = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
        const container = this.closest<HTMLElement>("[data-tab-scroll-root]");
        if (this === container) return new DOMRect(0, 0, 400, 200);
        if (this.id === "comment-comment-2" && container) {
          if (this.dataset.virtualThreadMounted !== "false" && ++alignedReads === 2 && interrupt) {
            const update = interrupt;
            setTimeout(() => {
              update();
              interrupted = true;
            }, 0);
          }
          return new DOMRect(0, 250 + drift() - container.scrollTop, 400, 100);
        }
        return new DOMRect(0, 0, 0, 0);
      });
      try {
        const { queryClient } = renderIssueDetailWithHighlight("comment-2");
        interrupt = () =>
          act(() => {
            queryClient.setQueryData<TimelineEntry[]>(["issues", "timeline", "issue-1"], (old) => [
              ...(old ?? []),
              { ...mockTimeline[0]!, id: "comment-late", content: "Arrived mid-landing", created_at: "2026-01-18T00:00:00Z" },
            ]);
          });
        await waitFor(() => expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-2"))).toBe(true));
        await waitFor(() => expect(interrupted).toBe(true));
        const container = document.querySelector<HTMLElement>("[data-tab-scroll-root]")!;
        // 250 + 300 drift - 16 top gap: where the comment sits once settled.
        await waitFor(() => expect(container.scrollTop).toBe(534), { timeout: 2000 });
      } finally {
        rect.mockRestore();
      }
    });

    it("does not restart a comment landing after the user scrolls away and another thread receives a reply", async () => {
      mockApiObj.listTasksByIssue.mockResolvedValue([]);
      let driftStart = 0;
      const drift = () => {
        driftStart ||= performance.now();
        return Math.min(performance.now() - driftStart, 300);
      };
      let userScrolled = false;
      const rect = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
        const container = this.closest<HTMLElement>("[data-tab-scroll-root]");
        if (this === container) return new DOMRect(0, 0, 400, 200);
        if (this.id === "comment-comment-2" && container) {
          return new DOMRect(0, 250 + drift() - container.scrollTop, 400, 100);
        }
        return new DOMRect(0, 0, 0, 0);
      });
      try {
        const { queryClient } = renderIssueDetailWithHighlight("comment-2");
        await waitFor(() => expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-2"))).toBe(true));
        const container = document.querySelector<HTMLElement>("[data-tab-scroll-root]")!;

        // User scrolls up to read/annotate an earlier thread before landing settles.
        container.scrollTop = 40;
        container.dispatchEvent(new Event("wheel"));
        userScrolled = true;

        // An agent posts a new reply in another thread, rebuilding timeline items.
        act(() => {
          queryClient.setQueryData<TimelineEntry[]>(["issues", "timeline", "issue-1"], (old) => [
            ...(old ?? []),
            {
              ...mockTimeline[0]!,
              id: "agent-reply-other-thread",
              parent_id: "comment-2",
              actor_type: "agent",
              actor_id: "agent-1",
              content: "Fast agent reply in thread 2",
              created_at: "2026-01-18T00:00:00Z",
            },
          ]);
        });
        await act(async () => { await new Promise((resolve) => window.setTimeout(resolve, 120)); });
        expect(userScrolled).toBe(true);
        expect(container.scrollTop).toBe(40);
      } finally {
        rect.mockRestore();
      }
    });

    it("folds an assignment reply with its resolved parent and unfolds that thread for a notification", async () => {
      const run: AgentTask = { id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
        kind: "direct", status: "completed", priority: 0, created_at: "2026-01-16T00:00:00Z", started_at: null, dispatched_at: null,
        completed_at: "2026-01-16T00:01:00Z", result: null, error: null, delivered_comment_ids: [] };
      const root = { ...mockTimeline[0]!, resolved_at: "2026-01-17T00:00:00Z" };
      const target = { ...mockTimeline[1]!, id: "assigned-reply", parent_id: root.id, source_task_id: run.id,
        content: "Assignment reply in the resolved discussion" };
      mockApiObj.listTimeline.mockResolvedValue([root, target]);
      mockApiObj.listTasksByIssue.mockResolvedValue([run]);
      const client = createTestQueryClient();
      const { container, rerender } = render(<I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={client}>
          <IssueDetail issueId="issue-1" />
        </QueryClientProvider>
      </I18nProvider>);
      await screen.findByRole("button", { name: /2 resolved comments/ });
      expect(container.querySelector(`#comment-${target.id}`)).toBeNull();

      rerender(<I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={client}>
          <IssueDetail issueId="issue-1" highlightCommentId={target.id} />
        </QueryClientProvider>
      </I18nProvider>);
      await waitFor(() => expect(container.querySelector(`#comment-${target.id}`))
        .toHaveClass(highlightedCommentBackgroundClass));
      expect(container.querySelector(`#comment-${root.id}`))
        .toContainElement(container.querySelector(`#comment-${target.id}`) as HTMLElement);
      expect(screen.getAllByText(target.content)).toHaveLength(1);
      expect(container.querySelectorAll(`[data-run-id="${run.id}"]`)).toHaveLength(1);
      expect(within(container.querySelector(`#comment-${target.id}`) as HTMLElement)
        .getByRole("button", { name: "Open full log" })).toBeInTheDocument();
    });

    it.each(["root", "reply"])("unfolds an assignment run with a resolved %s when a notification targets a hidden reply", async (resolved) => {
      const run: AgentTask = { id: "ba2e8d1c-7f9b-4e2a-9c1d-123456789abc", agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
        status: "completed", priority: 0, created_at: "2026-01-16T00:00:00Z", started_at: null, dispatched_at: null,
        completed_at: "2026-01-16T00:01:00Z", result: null, error: null, delivered_comment_ids: [] };
      const root = { ...mockTimeline[1]!, id: "assigned-answer", parent_id: null, source_task_id: run.id,
        content: "Assignment answer", resolved_at: resolved === "root" ? "2026-01-17T00:00:00Z" : null };
      const target = { ...mockTimeline[0]!, id: "hidden-target", parent_id: root.id, content: "Hidden notification target" };
      const resolution = { ...target, id: "resolution", content: "Resolved reply", resolved_at: "2026-01-17T00:00:00Z" };
      mockApiObj.listTimeline.mockResolvedValue([root, target, ...(resolved === "reply" ? [resolution] : [])]);
      mockApiObj.listTasksByIssue.mockResolvedValue([run]);
      renderIssueDetailWithHighlight(target.id);
      await waitFor(() => expect(document.getElementById(`comment-${target.id}`)).not.toBeNull());
      await waitFor(() => expect(document.getElementById(`comment-${target.id}`)).toHaveClass(highlightedCommentBackgroundClass));
    });
    it("lands on the reply above a deleted one when a notification targets it", async () => {
      // A deleted reply renders nothing (#8296 keeps its row only so its own
      // replies keep a parent), so the id the notification carries has no
      // anchor left. The landing rule's matrix lives in
      // packages/core/issues/comment-deletion.test.ts.
      const root = { ...mockTimeline[0]!, id: "thread-root", parent_id: null };
      const previous = { ...mockTimeline[1]!, id: "reply-before", parent_id: root.id,
        content: "Still here", created_at: "2026-01-18T00:00:00Z" };
      const target = { ...mockTimeline[1]!, id: "deleted-reply", parent_id: root.id,
        content: "", deleted_at: "2026-01-19T00:00:00Z", created_at: "2026-01-19T00:00:00Z" };
      const kept = { ...mockTimeline[1]!, id: "reply-under-deleted", parent_id: target.id,
        content: "Kept below it", created_at: "2026-01-20T00:00:00Z" };
      mockApiObj.listTimeline.mockResolvedValue([root, previous, target, kept]);
      mockApiObj.listTasksByIssue.mockResolvedValue([]);
      renderIssueDetailWithHighlight(target.id);

      await waitFor(() => expect(
        hasHighlightedCommentBackground(document.getElementById(`comment-${previous.id}`)),
      ).toBe(true));
      // The tombstone itself never renders, so nothing waits on its anchor.
      expect(document.getElementById(`comment-${target.id}`)).toBeNull();
    });

    it("scrolls to the highlighted comment after both issue and timeline finish loading", async () => {
      renderIssueDetailWithHighlight("comment-2");

      // Wait for the requested row to mount before checking its highlight.
      await waitFor(() => {
        expect(
          document.getElementById("comment-comment-2"),
        ).not.toBeNull();
      });

      // The deep-link effect lands on AND highlights the target comment: it
      // drives the timeline container's scrollTop directly (jsdom has no
      // layout, so the scroll itself isn't observable here) and applies the
      // brand highlight background. Assert the user-facing highlight.
      await waitFor(() => {
        expect(
          hasHighlightedCommentBackground(document.getElementById("comment-comment-2")),
        ).toBe(true);
      });
    });

    it("highlights only the target root comment, not the whole thread", async () => {
      mockApiObj.listTimeline.mockResolvedValue([
        {
          type: "comment",
          id: "comment-root",
          actor_type: "member",
          actor_id: "user-1",
          content: "Root target",
          parent_id: null,
          created_at: "2026-01-18T00:00:00Z",
          updated_at: "2026-01-18T00:00:00Z",
          comment_type: "comment",
        } as TimelineEntry,
        {
          type: "comment",
          id: "reply-under-root",
          actor_type: "member",
          actor_id: "user-1",
          content: "Reply should stay neutral",
          parent_id: "comment-root",
          created_at: "2026-01-18T01:00:00Z",
          updated_at: "2026-01-18T01:00:00Z",
          comment_type: "comment",
        } as TimelineEntry,
      ]);

      renderIssueDetailWithHighlight("comment-root");

      await waitFor(() => {
        expect(document.getElementById("comment-comment-root")).not.toBeNull();
      });
      await waitFor(() => {
        expect(
          hasHighlightedCommentBackground(document.getElementById("comment-comment-root")),
        ).toBe(true);
      });

      const reply = document.getElementById("comment-reply-under-root");
      expect(reply).not.toBeNull();
      expect(hasHighlightedCommentBackground(reply)).toBe(false);
    });

    it("lands on a run that left no comment by its task id", async () => {
      const taskId = "7c1f3a9e-2b4d-4e8a-9f60-0a1b2c3d4e5f";
      const task: AgentTask = {
        id: taskId, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
        status: "failed", priority: 0, created_at: "2026-01-18T00:00:00Z",
        started_at: "2026-01-18T00:00:01Z", dispatched_at: "2026-01-18T00:00:01Z",
        completed_at: "2026-01-18T00:05:00Z", result: null, error: "go test timed out",
        delivered_comment_ids: [],
      };
      mockApiObj.listTasksByIssue.mockResolvedValue([task]);

      renderIssueDetailWithHighlight(taskId);

      await waitFor(() => {
        expect(hasHighlightedCommentBackground(document.getElementById(`comment-${taskId}`))).toBe(true);
      });
    });

    it.each([
      ["an open thread", "open"],
      ["a thread whose root is resolved", "root"],
      ["a thread a later reply resolved", "reply"],
    ])("unfolds and lands on a run that left no comment in %s", async (_case, fold) => {
      const taskId = "7c1f3a9e-2b4d-4e8a-9f60-0a1b2c3d4e5f";
      const root = { ...mockTimeline[0]!, id: "run-thread-root", parent_id: null,
        resolved_at: fold === "root" ? "2026-01-19T00:00:00Z" : null };
      const trigger = { ...mockTimeline[0]!, id: "run-trigger", parent_id: root.id,
        content: "Please run this check", created_at: "2026-01-18T00:00:00Z" };
      const resolution = { ...trigger, id: "run-resolution", content: "Resolved",
        resolved_at: "2026-01-19T00:00:00Z", created_at: "2026-01-19T00:00:00Z" };
      const task: AgentTask = {
        id: taskId, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1",
        status: "failed", priority: 0, created_at: "2026-01-18T00:00:00Z",
        started_at: "2026-01-18T00:00:01Z", dispatched_at: "2026-01-18T00:00:01Z",
        completed_at: "2026-01-18T00:05:00Z", result: null, error: "go test timed out",
        trigger_comment_id: trigger.id, delivered_comment_ids: [trigger.id],
      };
      mockApiObj.listTimeline.mockResolvedValue([root, trigger, ...(fold === "reply" ? [resolution] : [])]);
      mockApiObj.listTasksByIssue.mockResolvedValue([task]);

      renderIssueDetailWithHighlight(taskId);

      await waitFor(() => {
        expect(hasHighlightedCommentBackground(document.getElementById(`comment-${taskId}`))).toBe(true);
      });
    });

    it("still scrolls when the timeline is ready before the issue (regression for inbox click)", async () => {
      // Reproduces the inbox-click race: timeline data is in the cache
      // before the issue resolves. While loading is true, IssueDetail
      // renders the loading skeleton (the timeline never mounts), so no
      // scroll/highlight can fire. After the issue resolves, the timeline
      // mounts and the deep-link effect lands on + highlights the comment.
      let resolveIssue: (value: Issue) => void = () => {};
      const issuePromise = new Promise<Issue>((resolve) => {
        resolveIssue = resolve;
      });
      mockApiObj.getIssue.mockReturnValue(issuePromise);

      renderIssueDetailWithHighlight("comment-2", "issue-1", { seedTimeline: true });

      expect(
        document.getElementById("comment-comment-2"),
      ).toBeNull();
      // Nothing highlighted while the loading skeleton is up.
      expect(hasHighlightedCommentBackground(document)).toBe(false);

      resolveIssue(mockIssue);

      await waitFor(() => {
        expect(
          document.getElementById("comment-comment-2"),
        ).not.toBeNull();
      });
      await waitFor(() => {
        expect(
          hasHighlightedCommentBackground(document.getElementById("comment-comment-2")),
        ).toBe(true);
      });
    });

    it("holds the composer back until a landing on cached data puts its target on screen (MUL-9538)", async () => {
      const queryClient = createTestQueryClient();
      queryClient.setQueryData(issueKeys.detail("ws-1", "issue-1"), mockIssue);
      queryClient.setQueryData(issueKeys.timeline("issue-1"), mockTimeline);
      queryClient.setQueryData(issueKeys.tasks("issue-1"), []);
      render(
        <I18nProvider locale="en" resources={TEST_RESOURCES}>
          <QueryClientProvider client={queryClient}>
            <IssueDetail issueId="issue-1" highlightCommentId="comment-2" />
          </QueryClientProvider>
        </I18nProvider>,
      );

      // The landing frame renders the target, not the composer below it.
      expect(document.getElementById("comment-comment-2")).not.toBeNull();
      expect(screen.queryByTestId("comment-composer-shell")).toBeNull();

      await waitFor(() => expect(
        hasHighlightedCommentBackground(document.getElementById("comment-comment-2")),
      ).toBe(true));
      expect(await screen.findByTestId("comment-composer-shell")).toBeInTheDocument();
    });

    it("holds the composer for an Inbox landing whose comment arrives a render later (MUL-9538)", async () => {
      const queryClient = createTestQueryClient();
      queryClient.setQueryData(issueKeys.detail("ws-1", "issue-1"), mockIssue);
      queryClient.setQueryData(issueKeys.timeline("issue-1"), mockTimeline);
      queryClient.setQueryData(issueKeys.tasks("issue-1"), []);
      const page = (highlightCommentId?: string) => (
        <I18nProvider locale="en" resources={TEST_RESOURCES}>
          <QueryClientProvider client={queryClient}>
            <IssueDetail issueId="issue-1" highlightRequestPending highlightCommentId={highlightCommentId} />
          </QueryClientProvider>
        </I18nProvider>
      );
      // Web reads the comment from the URL fragment, which the router writes
      // after the page's first render.
      const { rerender } = render(page());
      expect(screen.queryByTestId("comment-composer-shell")).toBeNull();
      rerender(page("comment-2"));
      expect(screen.queryByTestId("comment-composer-shell")).toBeNull();

      await waitFor(() => expect(
        hasHighlightedCommentBackground(document.getElementById("comment-comment-2")),
      ).toBe(true));
      expect(await screen.findByTestId("comment-composer-shell")).toBeInTheDocument();
    });

    it("lets the composer in at once when an Inbox landing names no comment", async () => {
      const queryClient = createTestQueryClient();
      queryClient.setQueryData(issueKeys.detail("ws-1", "issue-1"), mockIssue);
      queryClient.setQueryData(issueKeys.timeline("issue-1"), mockTimeline);
      queryClient.setQueryData(issueKeys.tasks("issue-1"), []);
      render(
        <I18nProvider locale="en" resources={TEST_RESOURCES}>
          <QueryClientProvider client={queryClient}>
            <IssueDetail issueId="issue-1" highlightRequestPending />
          </QueryClientProvider>
        </I18nProvider>,
      );
      // Within a frame, well before the hold's upper bound.
      expect(await screen.findByTestId("comment-composer-shell", {}, { timeout: 200 })).toBeInTheDocument();
    });

    it("renders the composer while a deep link's timeline is still loading", async () => {
      mockApiObj.listTimeline.mockReturnValue(new Promise(() => {}));
      renderIssueDetailWithHighlight("comment-2");
      expect(await screen.findByTestId("comment-composer-shell")).toBeInTheDocument();
    });

    it("auto-expands a folded resolved thread when deep-link target is a reply inside it", async () => {
      // Seed a timeline where comment-3 is resolved (so it renders as a
      // resolved-bar by default) and has a reply, reply-1, whose id is the
      // deep-link target. The reply is not in the flat items array — only
      // the resolved-bar root is. The effect must detect this, expand the
      // thread, then on re-run scroll to the reply's id="comment-reply-1" node.
      const timelineWithResolvedThread: TimelineEntry[] = [
        ...mockTimeline,
        {
          type: "comment",
          id: "comment-3",
          actor_type: "member",
          actor_id: "user-1",
          content: "Resolved root",
          parent_id: null,
          created_at: "2026-01-18T00:00:00Z",
          updated_at: "2026-01-18T00:00:00Z",
          comment_type: "comment",
          resolved_at: "2026-01-19T00:00:00Z",
        } as TimelineEntry,
        {
          type: "comment",
          id: "reply-1",
          actor_type: "member",
          actor_id: "user-1",
          content: "Reply inside resolved thread",
          parent_id: "comment-3",
          created_at: "2026-01-18T01:00:00Z",
          updated_at: "2026-01-18T01:00:00Z",
          comment_type: "comment",
        } as TimelineEntry,
      ];
      mockApiObj.listTimeline.mockResolvedValue(timelineWithResolvedThread);

      const queryClient = createTestQueryClient();
      render(
        <I18nProvider locale="en" resources={TEST_RESOURCES}>
          <QueryClientProvider client={queryClient}>
            <IssueDetail issueId="issue-1" highlightCommentId="reply-1" />
          </QueryClientProvider>
        </I18nProvider>,
      );

      // After expansion, the reply must appear in the DOM (inside the now
      // -unfolded CommentCard) and the deep-link effect must land on + highlight
      // it. The reply highlight renders as a computed bg tint on its row (see
      // CommentCard's reply branch), so assert the row carries the brand tint.
      await waitFor(() => {
        expect(
          document.getElementById("comment-reply-1"),
        ).not.toBeNull();
      });
      await waitFor(() => {
        expect(
          document.getElementById("comment-reply-1")?.className,
        ).toContain("bg-[color-mix(in_srgb,var(--card)_95%,var(--brand)_5%)]");
      });
    });
  });

  it("marks a reply-resolved thread as resolved on the quick-jump rail", async () => {
    // A resolution on a REPLY leaves the thread expanded, so it flattens to a
    // plain `comment` item, not a `resolved-bar`. The rail must still read it
    // as resolved — proof the flag comes from deriveThreadResolution and not
    // from the fold state.
    mockApiObj.listTimeline.mockResolvedValue([
      ...mockTimeline,
      {
        type: "comment",
        id: "reply-1",
        actor_type: "member",
        actor_id: "user-1",
        content: "That fixed it",
        parent_id: "comment-1",
        created_at: "2026-01-18T00:00:00Z",
        updated_at: "2026-01-18T00:00:00Z",
        comment_type: "comment",
        resolved_at: "2026-01-19T00:00:00Z",
      } as TimelineEntry,
    ]);

    renderIssueDetail();

    await waitFor(() => {
      expect(
        screen.getByRole("button", { name: "Started working on this (resolved)" }),
      ).toBeInTheDocument();
    });
    expect(screen.getByRole("button", { name: "I can help with this" })).toBeInTheDocument();
  });

  describe("quick-jump rail replies", () => {
    const highlightTint = "bg-[color-mix(in_srgb,var(--card)_95%,var(--brand)_5%)]";

    it("unfolds a resolved thread and lands on the reply picked from the rail", async () => {
      mockApiObj.listTimeline.mockResolvedValue([
        ...mockTimeline,
        {
          type: "comment",
          id: "comment-3",
          actor_type: "member",
          actor_id: "user-1",
          content: "Resolved root",
          parent_id: null,
          created_at: "2026-01-18T00:00:00Z",
          updated_at: "2026-01-18T00:00:00Z",
          comment_type: "comment",
          resolved_at: "2026-01-19T00:00:00Z",
        } as TimelineEntry,
        {
          type: "comment",
          id: "reply-1",
          actor_type: "member",
          actor_id: "user-1",
          content: "Reply inside resolved thread",
          parent_id: "comment-3",
          created_at: "2026-01-18T01:00:00Z",
          updated_at: "2026-01-18T01:00:00Z",
          comment_type: "comment",
        } as TimelineEntry,
      ]);

      renderIssueDetail();

      const nav = await screen.findByRole("navigation", { name: "Quick navigation" });
      expect(document.getElementById("comment-reply-1")).toBeNull();
      expect(within(nav).queryByRole("button", { name: /: Reply inside resolved thread$/ })).toBeNull();
      act(() => within(nav).getByRole("button", { name: "Resolved root (resolved)" }).focus());
      fireEvent.click(
        within(nav.parentElement!).getByRole("button", { name: "Show 1 reply" }),
        { detail: 0 },
      );
      fireEvent.click(within(nav).getByRole("button", { name: /: Reply inside resolved thread$/ }));

      await waitFor(() => {
        expect(document.getElementById("comment-reply-1")?.className).toContain(highlightTint);
      });
      expect(useResolvedExpandStore.getState().expandedByIssue["issue-1"]?.has("comment-3")).toBe(true);
    });

    // "Show in comments" for a file shares the rail's path, so a file posted
    // in a reply is reachable whatever hides that reply (MUL-7649).
    it("reopens a collapsed thread when a file's reply is located from the overview", async () => {
      useCommentCollapseStore.setState({ collapsedByIssue: { "issue-1": ["comment-1"] } });
      const csv: Attachment = {
        id: "csv",
        workspace_id: "ws-1",
        issue_id: "issue-1",
        comment_id: "reply-2",
        chat_session_id: null,
        chat_message_id: null,
        uploader_type: "agent",
        uploader_id: "agent-1",
        filename: "latency.csv",
        url: "https://cdn.example.test/csv",
        download_url: "https://cdn.example.test/csv",
        markdown_url: "https://cdn.example.test/csv",
        content_type: "text/csv",
        size_bytes: 2048,
        created_at: "2026-01-16T01:00:00Z",
      };
      mockApiObj.listTimeline.mockResolvedValue([
        ...mockTimeline,
        {
          type: "comment",
          id: "reply-2",
          actor_type: "member",
          actor_id: "user-1",
          content: "Latency numbers attached",
          parent_id: "comment-1",
          created_at: "2026-01-16T01:00:00Z",
          updated_at: "2026-01-16T01:00:00Z",
          comment_type: "comment",
          attachments: [csv],
        } as TimelineEntry,
      ]);

      renderIssueDetail();

      fireEvent.click(await screen.findByRole("button", { name: "View 1 deliverable" }));
      const overview = await screen.findByRole("dialog", { name: /deliverables$/ });
      expect(document.getElementById("comment-reply-2")).toBeNull();
      fireEvent.click(within(overview).getByRole("button", { name: "Show in comments" }));

      await waitFor(() => {
        expect(document.getElementById("comment-reply-2")?.className).toContain(highlightTint);
      });
      expect(useCommentCollapseStore.getState().isCollapsed("issue-1", "comment-1")).toBe(false);
    });

    it("unfolds a resolved thread when a file on its root is located from the overview", async () => {
      const pdf: Attachment = {
        id: "pdf",
        workspace_id: "ws-1",
        issue_id: "issue-1",
        comment_id: "comment-3",
        chat_session_id: null,
        chat_message_id: null,
        uploader_type: "member",
        uploader_id: "user-1",
        filename: "spec.pdf",
        url: "https://cdn.example.test/pdf",
        download_url: "https://cdn.example.test/pdf",
        markdown_url: "https://cdn.example.test/pdf",
        content_type: "application/pdf",
        size_bytes: 2048,
        created_at: "2026-01-18T00:00:00Z",
      };
      mockApiObj.listTimeline.mockResolvedValue([
        ...mockTimeline,
        {
          type: "comment",
          id: "comment-3",
          actor_type: "member",
          actor_id: "user-1",
          content: "Spec attached",
          parent_id: null,
          created_at: "2026-01-18T00:00:00Z",
          updated_at: "2026-01-18T00:00:00Z",
          comment_type: "comment",
          resolved_at: "2026-01-19T00:00:00Z",
          attachments: [pdf],
        } as TimelineEntry,
      ]);

      renderIssueDetail();

      fireEvent.click(await screen.findByRole("button", { name: "View 1 deliverable" }));
      const overview = await screen.findByRole("dialog", { name: /deliverables$/ });
      fireEvent.click(within(overview).getByRole("button", { name: "Show in comments" }));

      await waitFor(() => {
        expect(useResolvedExpandStore.getState().expandedByIssue["issue-1"]?.has("comment-3")).toBe(true);
      });
      await waitFor(() => {
        expect(hasHighlightedCommentBackground(document.getElementById("comment-comment-3"))).toBe(true);
      });
    });

    it("reopens a thread the reader collapsed before landing on its reply", async () => {
      useCommentCollapseStore.setState({ collapsedByIssue: { "issue-1": ["comment-1"] } });
      mockApiObj.listTimeline.mockResolvedValue([
        ...mockTimeline,
        {
          type: "comment",
          id: "reply-2",
          actor_type: "member",
          actor_id: "user-1",
          content: "Pushed a fix",
          parent_id: "comment-1",
          created_at: "2026-01-16T01:00:00Z",
          updated_at: "2026-01-16T01:00:00Z",
          comment_type: "comment",
        } as TimelineEntry,
      ]);

      renderIssueDetail();

      const nav = await screen.findByRole("navigation", { name: "Quick navigation" });
      expect(document.getElementById("comment-reply-2")).toBeNull();
      fireEvent.click(within(nav).getByRole("button", { name: /: Pushed a fix$/ }));

      await waitFor(() => {
        expect(document.getElementById("comment-reply-2")?.className).toContain(highlightTint);
      });
      expect(useCommentCollapseStore.getState().isCollapsed("issue-1", "comment-1")).toBe(false);
    });
  });

  it("sends empty description when editor is cleared", async () => {
    renderIssueDetail();

    const editor = await screen.findByDisplayValue("Add JWT auth to the backend");
    fireEvent.change(editor, { target: { value: "" } });

    await waitFor(() => {
      expect(mockApiObj.updateIssue).toHaveBeenCalledWith(
        "issue-1",
        expect.objectContaining({
          description: "",
          description_base: "Add JWT auth to the backend",
        }),
      );
    });
  });

  // Descriptions are last-write-wins (MUL-6971). The baseline still ships as
  // channel-media merge metadata, but a rejected save no longer opens a compare
  // panel — that panel fired on the editor's own autosave and wedged the
  // session, and the title/comment editors keep the compare flow they can
  // actually satisfy.
  it("keeps editing after a failed description save without a compare panel", async () => {
    mockApiObj.updateIssue.mockRejectedValueOnce({
      body: { code: "revision_conflict" },
    });
    renderIssueDetail();

    const editor = await screen.findByDisplayValue("Add JWT auth to the backend");
    fireEvent.focus(editor);
    fireEvent.change(editor, { target: { value: "My local description" } });

    await waitFor(() =>
      expect(mockApiObj.updateIssue).toHaveBeenCalledWith(
        "issue-1",
        expect.objectContaining({
          description: "My local description",
          description_base: "Add JWT auth to the backend",
        }),
      ),
    );
    // The compare panel's own actions — still rendered for a title conflict,
    // so their absence is about the description, not a missing translation.
    expect(
      screen.queryByRole("button", { name: "Keep my version" }),
    ).not.toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "Use the latest version" }),
    ).not.toBeInTheDocument();
    expect(screen.getByDisplayValue("My local description")).toBeVisible();

    // The save gate reopened: the next edit still reaches the server.
    fireEvent.change(editor, { target: { value: "My next description" } });
    await waitFor(() =>
      expect(mockApiObj.updateIssue).toHaveBeenLastCalledWith(
        "issue-1",
        expect.objectContaining({ description: "My next description" }),
      ),
    );
  });

  it("serializes description saves and rebases the queued draft on submitted content", async () => {
    let resolveFirst!: (issue: Issue) => void;
    const firstSave = new Promise<Issue>((resolve) => {
      resolveFirst = resolve;
    });
    mockApiObj.updateIssue
      .mockReturnValueOnce(firstSave)
      .mockResolvedValueOnce({
        ...mockIssue,
        description: "Second local description",
        revision: 5,
      });
    renderIssueDetail();

    const editor = await screen.findByDisplayValue("Add JWT auth to the backend");
    fireEvent.focus(editor);
    fireEvent.change(editor, { target: { value: "First local description" } });
    await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(1));
    fireEvent.change(editor, { target: { value: "Second local description" } });
    expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(1);

    await act(async () => {
      resolveFirst({ ...mockIssue, description: "First local description", revision: 4 });
      await firstSave;
    });

    await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(2));
    expect(mockApiObj.updateIssue).toHaveBeenNthCalledWith(
      2,
      "issue-1",
      expect.objectContaining({
        description: "Second local description",
        description_base: "First local description",
      }),
    );
  });

  it("ignores a late description callback after switching issues", async () => {
    const queryClient = createTestQueryClient();
    const issue2: Issue = {
      ...mockIssue,
      id: "issue-2",
      identifier: "TES-2",
      description: "Second issue description",
      revision: 8,
    };
    queryClient.setQueryData(["issues", "ws-1", "detail", "issue-2"], issue2);
    mockApiObj.getIssue.mockImplementation((issueId: string) =>
      Promise.resolve(issueId === "issue-2" ? issue2 : mockIssue),
    );

    let resolveFirst!: (issue: Issue) => void;
    const firstSave = new Promise<Issue>((resolve) => {
      resolveFirst = resolve;
    });
    mockApiObj.updateIssue
      .mockReturnValueOnce(firstSave)
      .mockResolvedValueOnce({ ...issue2, description: "Issue two draft", revision: 9 });

    const ui = (issueId: string) => (
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={queryClient}>
          <IssueDetail issueId={issueId} />
        </QueryClientProvider>
      </I18nProvider>
    );
    const { rerender } = render(ui("issue-1"));

    const issueOneEditor = await screen.findByDisplayValue("Add JWT auth to the backend");
    fireEvent.focus(issueOneEditor);
    fireEvent.change(issueOneEditor, {
      target: { value: "Issue one draft" },
    });
    await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(1));

    rerender(ui("issue-2"));
    const issueTwoEditor = await screen.findByDisplayValue("Second issue description");
    fireEvent.focus(issueTwoEditor);
    fireEvent.change(issueTwoEditor, {
      target: { value: "Issue two draft" },
    });
    await waitFor(() => expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(2));
    expect(mockApiObj.updateIssue).toHaveBeenNthCalledWith(
      2,
      "issue-2",
      expect.objectContaining({ description_base: "Second issue description" }),
    );

    await act(async () => {
      resolveFirst({ ...mockIssue, description: "Issue one draft", revision: 4 });
      await firstSave;
    });

    expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(2);
    expect(screen.getByDisplayValue("Issue two draft")).toBeVisible();
  });

  it("keeps a title draft visible when its captured content conflicts", async () => {
    mockApiObj.updateIssue.mockRejectedValueOnce({
      body: { code: "revision_conflict" },
    });
    renderIssueDetail();

    fireEvent.click(await screen.findByRole("button", { name: "Implement authentication" }));
    const editor = await screen.findByTestId("title-editor");
    fireEvent.change(editor, { target: { value: "My local title" } });
    fireEvent.blur(editor);

    await waitFor(() =>
      expect(mockApiObj.updateIssue).toHaveBeenCalledWith(
        "issue-1",
        expect.objectContaining({
          title: "My local title",
          title_base: "Implement authentication",
        }),
      ),
    );
    expect(
      await screen.findByText("The title was changed concurrently. Compare both versions."),
    ).toBeVisible();
    expect(screen.getAllByText("My local title").length).toBeGreaterThan(0);
    expect(screen.getByDisplayValue("My local title")).toBeVisible();
  });

  it("restores the server title when the user takes the latest version", async () => {
    mockApiObj.updateIssue.mockRejectedValueOnce({
      body: { code: "revision_conflict" },
    });
    renderIssueDetail();

    fireEvent.click(await screen.findByRole("button", { name: "Implement authentication" }));
    const editor = await screen.findByTestId("title-editor");
    fireEvent.change(editor, { target: { value: "My local title" } });
    fireEvent.blur(editor);

    expect(
      await screen.findByText("The title was changed concurrently. Compare both versions."),
    ).toBeVisible();
    const callsBeforeDiscard = mockApiObj.updateIssue.mock.calls.length;

    fireEvent.click(screen.getByRole("button", { name: "Use the latest version" }));

    await waitFor(() =>
      expect(
        screen.queryByText("The title was changed concurrently. Compare both versions."),
      ).not.toBeInTheDocument(),
    );
    // TitleEditor takes its text at mount, so the remount is what puts the
    // server title back — see titleResetToken.
    expect(await screen.findByDisplayValue("Implement authentication")).toBeVisible();
    // Taking the server version is local-only: the server already holds it.
    expect(mockApiObj.updateIssue).toHaveBeenCalledTimes(callsBeforeDiscard);
  });

  it("returns to the issue title and description from the outline", async () => {
    // Destination behavior is covered by thread-minimap.test.tsx; this tests the scroller wiring.
    mockApiObj.listTimeline.mockResolvedValue([mockTimeline.find((entry) => entry.type === "comment")!]);
    const { container } = renderIssueDetail();
    const tick = await screen.findByRole("button", { name: "Issue description" });
    const scroller = container.querySelector<HTMLDivElement>("[data-tab-scroll-root]")!;
    scroller.scrollTop = 800;
    fireEvent.click(tick);
    expect(scroller.scrollTop).toBe(0);
  });

  describe("sub-issues list", () => {
    beforeEach(() => {
      useSubIssuesCollapseStore.setState({ collapsedIssueIds: new Set() });
      useSubIssueDisplayStore.setState({
        rowProperties: { ...DEFAULT_SUB_ISSUE_ROW_PROPERTIES },
        rowPropertyIds: [],
      });
    });

    const label = (id: string, name: string): Label => ({
      id,
      workspace_id: "ws-1",
      resource_type: "issue",
      name,
      color: "#3b82f6",
      created_at: "2026-01-01T00:00:00Z",
      updated_at: "2026-01-01T00:00:00Z",
    });

    const subIssue = (overrides: Partial<Issue>): Issue => ({
      ...mockIssue,
      parent_issue_id: "issue-1",
      assignee_type: null,
      assignee_id: null,
      due_date: null,
      priority: "none",
      ...overrides,
    });

    const inlineChildren = () => within(document.querySelector<HTMLElement>('[class~="group/sub-issues"]')!);
    const findInlineChild = (title: string) => waitFor(() => inlineChildren().getByText(title));

    it("lists sub-issues in the main column only, with the system wakeup beside its heading", async () => {
      mockApiObj.listChildIssues.mockResolvedValue({
        issues: [subIssue({ id: "child-open", identifier: "TES-11", title: "Open destination", status: "todo" })],
      });
      mockApiObj.listIssueSystemWakeups.mockResolvedValue([{
        id: "rule", revision: 1, default_instruction: "Advance the next stage.", customized: false, paused_reason: null,
        rule: "child_done", workspace_default: true, enabled: true, instruction: "", staged: false, stage: null, total: 1, remaining: 1,
        waiting: ["TES-11"], target: { type: "agent", id: "agent-1", name: "Claude Agent" }, blocked: "",
      }]);
      const { container } = renderIssueDetail();
      await findInlineChild("Open destination");
      expect(container.querySelector('[data-issue-sidebar-section="sub_issues"]')).toBeNull();
      const section = container.querySelector<HTMLElement>('[class~="group/sub-issues"]')!;
      expect(await within(section).findByRole("button", { name: "Wakes Claude Agent when all finish" })).toBeInTheDocument();
    });

    it("jumps from the outline to the expanded sub-issues section without comments", async () => {
      // Preview/order behavior lives in thread-minimap.test.tsx; this tests the real section.
      mockApiObj.listTimeline.mockResolvedValue([]);
      mockApiObj.listChildIssues.mockResolvedValue({
        issues: [subIssue({ id: "child-1", title: "Child destination" })],
      });
      const { container } = renderIssueDetail();
      await findInlineChild("Child destination");
      const section = container.querySelector<HTMLDivElement>(".group\\/sub-issues")!;
      fireEvent.click(within(section).getByRole("button", { name: "Sub-issues" }));
      expect(within(section).queryByText("Child destination")).not.toBeInTheDocument();

      const scroller = container.querySelector<HTMLDivElement>("[data-tab-scroll-root]")!;
      scroller.scrollTop = 600;
      vi.spyOn(scroller, "getBoundingClientRect").mockReturnValue({ top: 100 } as DOMRect);
      vi.spyOn(section, "getBoundingClientRect").mockReturnValue({ top: -200 } as DOMRect);
      fireEvent.click(within(screen.getByRole("navigation", { name: "Quick navigation" }))
        .getByRole("button", { name: "Sub-issues" }));

      expect(await findInlineChild("Child destination")).toBeInTheDocument();
      await waitFor(() => expect(scroller.scrollTop).toBe(284));
    });

    it("renders priority, labels, due date and nested progress on rows", async () => {
      mockApiObj.listChildIssues.mockResolvedValue({
        issues: [
          subIssue({
            id: "child-1",
            number: 11,
            identifier: "TES-11",
            title: "Fix login flow",
            priority: "urgent",
            labels: [label("l1", "backend"), label("l2", "auth")],
            // Past date-only value → overdue styling on an open issue.
            due_date: "2020-01-01",
          }),
          subIssue({
            id: "child-2",
            number: 12,
            identifier: "TES-12",
            title: "Ship dashboards",
          }),
        ],
      });
      mockApiObj.getChildIssueProgress.mockResolvedValue({
        progress: [{ parent_issue_id: "child-1", done: 1, total: 3 }],
      });

      renderIssueDetail();

      await findInlineChild("Fix login flow");
      // Label chips ride inside the row link.
      expect(screen.getByText("backend")).toBeInTheDocument();
      expect(screen.getByText("auth")).toBeInTheDocument();
      // Nested own-children progress for child-1 only (header shows 0/2).
      expect(await screen.findByText("1/3")).toBeInTheDocument();
      // Overdue open issue renders its due date in the destructive tone.
      const due = screen.getByText("Jan 1");
      expect(due.closest("span")?.className).toContain("text-destructive");
      // Bare row shows no due date / no progress chip of its own.
      const bareRow = inlineChildren().getByText("Ship dashboards").closest("a");
      expect(bareRow?.textContent).not.toContain("/");
    });

    it("hides fields the user toggled off in the display preference", async () => {
      useSubIssueDisplayStore.setState({
        rowProperties: {
          ...DEFAULT_SUB_ISSUE_ROW_PROPERTIES,
          labels: false,
          dueDate: false,
        },
      });
      mockApiObj.listChildIssues.mockResolvedValue({
        issues: [
          subIssue({
            id: "child-1",
            number: 11,
            identifier: "TES-11",
            title: "Fix login flow",
            labels: [label("l1", "backend")],
            due_date: "2020-01-01",
          }),
        ],
      });

      renderIssueDetail();

      await findInlineChild("Fix login flow");
      expect(screen.queryByText("backend")).not.toBeInTheDocument();
      expect(screen.queryByText("Jan 1")).not.toBeInTheDocument();
    });

    it("renders opted-in custom property chips on rows that carry a value", async () => {
      const estimate = {
        id: "prop-1",
        workspace_id: "ws-1",
        name: "Estimate",
        type: "text",
        config: {},
        position: 0,
        archived: false,
        created_at: "2026-01-01T00:00:00Z",
        updated_at: "2026-01-01T00:00:00Z",
      };
      mockApiObj.listProperties.mockResolvedValue({
        properties: [estimate],
        total: 1,
      });
      useSubIssueDisplayStore.setState({ rowPropertyIds: ["prop-1"] });
      mockApiObj.listChildIssues.mockResolvedValue({
        issues: [
          subIssue({
            id: "child-1",
            number: 11,
            identifier: "TES-11",
            title: "Fix login flow",
            properties: { "prop-1": "Sprint 3" },
          }),
          subIssue({
            id: "child-2",
            number: 12,
            identifier: "TES-12",
            title: "Ship dashboards",
          }),
        ],
      });

      renderIssueDetail();

      await findInlineChild("Fix login flow");
      // Chip renders only on the row that has a value for the property.
      expect(await screen.findByText("Sprint 3")).toBeInTheDocument();
      expect(screen.getAllByText("Sprint 3")).toHaveLength(1);
    });

    it("drives the inline batch toolbar from row checkboxes inside a surface peek", async () => {
      mockApiObj.listChildIssues.mockResolvedValue({
        issues: [
          subIssue({ id: "child-1", number: 11, identifier: "TES-11", title: "Fix login flow" }),
          subIssue({ id: "child-2", number: 12, identifier: "TES-12", title: "Ship dashboards" }),
        ],
      });
      function SurfaceHost() {
        const selection = useCreateIssueSurfaceSelection("surface");
        return (
          <IssueSurfaceSelectionProvider selection={selection}>
            <IssueDetail issueId="issue-1" />
          </IssueSurfaceSelectionProvider>
        );
      }
      render(
        <I18nProvider locale="en" resources={TEST_RESOURCES}>
          <QueryClientProvider client={createTestQueryClient()}>
            <SurfaceHost />
          </QueryClientProvider>
        </I18nProvider>,
      );

      fireEvent.click(await screen.findByRole("checkbox", { name: "Select TES-11" }));
      expect(await screen.findByText("1 selected")).toBeInTheDocument();

      fireEvent.click(screen.getByRole("checkbox", { name: "Select all sub-issues" }));
      expect(await screen.findByText("2 selected")).toBeInTheDocument();
      expect(screen.getByRole("checkbox", { name: "Select TES-12" })).toBeChecked();
    });

    it("mutes the due date on done sub-issues even when past", async () => {
      mockApiObj.listChildIssues.mockResolvedValue({
        issues: [
          subIssue({
            id: "child-1",
            number: 11,
            identifier: "TES-11",
            title: "Wrapped up",
            status: "done",
            due_date: "2020-01-01",
          }),
        ],
      });

      renderIssueDetail();

      await findInlineChild("Wrapped up");
      const due = screen.getByText("Jan 1");
      expect(due.closest("span")?.className).not.toContain("text-destructive");
      expect(due.closest("span")?.className).toContain("text-muted-foreground");
    });
  });

  // Deliberately drives the real Base UI DropdownMenu rather than a stub: the
  // bug these tests pin (MUL-5710) was a handler wired to `onSelect`, which
  // typechecks because Menu.Item's props extend the whole div attribute set,
  // then lands on the DOM as the native text-selection event and never fires.
  // Only the real menu reproduces that; any hand-rolled mock hides it.
  describe("unsubscribe menu", () => {
    const subscribedAsMember = [
      {
        issue_id: "issue-1",
        user_type: "member" as const,
        user_id: "user-1",
        reason: "manual" as const,
        created_at: "2026-01-01T00:00:00Z",
      },
    ];

    beforeEach(() => {
      mockApiObj.listIssueSubscribers.mockResolvedValue(subscribedAsMember);
      // The menu only exists when there is a sub-tree for its second item to
      // act on. A childless issue renders a direct button instead — covered
      // by the "no sub-issues" tests below (MUL-5714).
      mockApiObj.listChildIssues.mockResolvedValue({
        issues: [{ ...mockIssue, id: "child-1", parent_issue_id: "issue-1" }],
      });
    });

    // Base UI portals the popup onto document.body; RTL unmounts it, but wipe
    // the body too so a leftover portal can't duplicate menu item names.
    afterEach(() => {
      document.body.innerHTML = "";
    });

    async function openUnsubscribeMenu() {
      renderIssueDetail();
      fireEvent.click(await screen.findByText("Unsubscribe"));
      return screen.findByRole("menu");
    }

    it("unsubscribes the current member when the single-issue item is clicked", async () => {
      await openUnsubscribeMenu();

      fireEvent.click(
        screen.getByRole("menuitem", { name: "Unsubscribe from this issue" }),
      );

      await waitFor(() =>
        expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalledWith(
          "issue-1",
          "user-1",
          "member",
        ),
      );
      expect(mockApiObj.unsubscribeFromIssueSubtree).not.toHaveBeenCalled();
    });

    it("unsubscribes from the whole subtree when the subtree item is clicked", async () => {
      await openUnsubscribeMenu();

      fireEvent.click(
        screen.getByRole("menuitem", {
          name: "Unsubscribe from this issue and its sub-issues",
        }),
      );

      await waitFor(() =>
        expect(mockApiObj.unsubscribeFromIssueSubtree).toHaveBeenCalledWith(
          "issue-1",
          "user-1",
          "member",
        ),
      );
      expect(mockApiObj.unsubscribeFromIssue).not.toHaveBeenCalled();
    });

    it("still offers the menu while the child count is unknown", async () => {
      // Children never resolve, so the component cannot yet tell a childless
      // issue from one with a sub-tree. The menu is the safe answer: unlike
      // the direct button it never picks an opt-out scope for the user.
      mockApiObj.listChildIssues.mockReturnValue(new Promise(() => {}));
      renderIssueDetail();

      const control = await screen.findByText("Unsubscribe");

      expect(control.getAttribute("aria-haspopup")).toBe("menu");
    });
  });

  // The reported bug: on an issue with no sub-issues the only way to leave was
  // a menu whose second item pointed at a sub-tree that does not exist
  // (MUL-5714).
  describe("unsubscribe without sub-issues", () => {
    const subscribedAsMember = [
      {
        issue_id: "issue-1",
        user_type: "member" as const,
        user_id: "user-1",
        reason: "manual" as const,
        created_at: "2026-01-01T00:00:00Z",
      },
    ];

    beforeEach(() => {
      mockApiObj.listIssueSubscribers.mockResolvedValue(subscribedAsMember);
      mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });
    });

    afterEach(() => {
      document.body.innerHTML = "";
    });

    // The label is the same either way, so aria-haspopup is what separates the
    // menu trigger from the plain button. The subscribers query resolves first,
    // so the control is briefly the trigger before the child count settles —
    // wait for the collapsed form rather than grabbing the first match.
    async function findDirectUnsubscribeButton() {
      return waitFor(() => {
        const el = screen.getByText("Unsubscribe");
        expect(el.getAttribute("aria-haspopup")).toBeNull();
        return el;
      });
    }

    it("unsubscribes in one click, with no menu", async () => {
      renderIssueDetail();

      fireEvent.click(await findDirectUnsubscribeButton());

      await waitFor(() =>
        expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalledWith(
          "issue-1",
          "user-1",
          "member",
        ),
      );
      expect(screen.queryByRole("menu")).toBeNull();
    });

    // The scope choice, pinned. RemoveIssueSubscriber writes
    // opt_out_scope='issue'; the subtree route writes 'subtree', which also
    // blocks FUTURE children from re-subscribing the user. Collapsing the menu
    // must not quietly upgrade a one-issue opt-out into a whole-tree one
    // (server/pkg/db/queries/subscriber.sql).
    it("uses the root-only route, never the subtree one", async () => {
      renderIssueDetail();

      fireEvent.click(await findDirectUnsubscribeButton());

      await waitFor(() =>
        expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalled(),
      );
      expect(mockApiObj.unsubscribeFromIssueSubtree).not.toHaveBeenCalled();
    });

    it("sends one request for a rapid double-click", async () => {
      let release: (() => void) | undefined;
      mockApiObj.unsubscribeFromIssue.mockReturnValue(
        new Promise<void>((resolve) => {
          release = () => resolve();
        }),
      );
      renderIssueDetail();
      const button = await findDirectUnsubscribeButton();

      // Same tick, no await between. React Query flushes isPending in a
      // microtask, so `disabled` has not landed yet and the second click still
      // reaches an enabled button — the in-flight guard is what stops it. Two
      // overlapping toggles is the one case the mutation's whole-list snapshot
      // cannot survive: the second snapshots the first one's optimistic patch
      // and rolls back to it (MUL-5714).
      fireEvent.click(button);
      fireEvent.click(button);

      // Both handlers already ran synchronously; only the request dispatch is
      // async. So once any call has landed, the count is final.
      await waitFor(() =>
        expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalled(),
      );
      expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalledTimes(1);
      release?.();
    });

    it("disables the button while the toggle is in flight, then reports failure", async () => {
      let reject: ((err: Error) => void) | undefined;
      mockApiObj.unsubscribeFromIssue.mockReturnValue(
        new Promise<void>((_resolve, rej) => {
          reject = (err) => rej(err);
        }),
      );
      renderIssueDetail();
      const button = await findDirectUnsubscribeButton();

      fireEvent.click(button);

      await waitFor(() =>
        expect((button as HTMLButtonElement).disabled).toBe(true),
      );

      reject?.(new Error("boom"));

      // The optimistic patch rolls itself back, restoring the exact row the
      // user started from — without this message that is indistinguishable
      // from a button that never fired.
      await waitFor(() =>
        expect(toast.error).toHaveBeenCalledWith(
          enIssues.detail.subscription_update_failed,
        ),
      );
      await waitFor(() =>
        expect((button as HTMLButtonElement).disabled).toBe(false),
      );
    });
  });

  // Before the subscribers query resolves the hook's list defaults to empty,
  // which reads as "not subscribed" for everyone. Rendering that default
  // showed a Subscribe button to people who were already subscribed, and a
  // click landing in that window sent a subscribe instead of the unsubscribe
  // they meant (MUL-5714).
  describe("subscription inherited from the project", () => {
    beforeEach(() => {
      mockApiObj.listIssueSubscribers.mockResolvedValue([
        {
          issue_id: "issue-1",
          user_type: "member" as const,
          user_id: "user-1",
          reason: "project" as const,
          created_at: "2026-01-01T00:00:00Z",
        },
      ]);
      mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });
    });

    afterEach(() => {
      document.body.innerHTML = "";
    });

    it("labels the project source and leaves only this issue", async () => {
      renderIssueDetail();

      expect(await screen.findByText("Via project")).toBeInTheDocument();
      const button = await waitFor(() => {
        const el = screen.getByText("Unsubscribe");
        expect(el.getAttribute("aria-haspopup")).toBeNull();
        return el;
      });
      fireEvent.click(button);

      await waitFor(() =>
        expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalledWith(
          "issue-1",
          "user-1",
          "member",
        ),
      );
      expect(mockApiObj.unsubscribeFromIssueSubtree).not.toHaveBeenCalled();
    });
  });

  describe("subscription state before the query resolves", () => {
    afterEach(() => {
      document.body.innerHTML = "";
    });

    it("renders no subscribe control while subscribers are loading", async () => {
      mockApiObj.listIssueSubscribers.mockReturnValue(new Promise(() => {}));
      renderIssueDetail();

      // Wait for the issue itself, so this asserts on a rendered page rather
      // than on the loading skeleton.
      await screen.findByText("Implement authentication");

      expect(screen.queryByText("Subscribe")).toBeNull();
      expect(screen.queryByText("Unsubscribe")).toBeNull();
    });

    it("renders Subscribe once the query says the user is not subscribed", async () => {
      mockApiObj.listIssueSubscribers.mockResolvedValue([]);
      renderIssueDetail();

      expect(await screen.findByText("Subscribe")).toBeTruthy();
    });
  });

  // Same cold-cache hazard as the Subscribe button, but worse to act on. Every
  // checkbox here is drawn from the subscribers list, so an unresolved query
  // renders everyone — including people who ARE subscribed — as unchecked.
  // Clicking one of those rows sends an explicit subscribe, which rewrites the
  // target's reason to 'manual' and clears any opt-out scope
  // (server/pkg/db/queries/subscriber.sql), discarding a delegated
  // subscription or a deliberate opt-out (MUL-5714).
  describe("subscriber picker before the query resolves", () => {
    // The picker sits next to the subscribe control in the Activity header.
    // Anchor on the heading, not on that control — the whole point of these
    // cases is that it is not rendered yet.
    async function openSubscriberPicker() {
      const heading = await screen.findByText("Activity");
      const header = heading.parentElement?.parentElement;
      const trigger = header?.querySelector('[data-trigger="popover"]');
      if (!trigger) throw new Error("subscriber picker trigger not found");
      fireEvent.click(trigger);
      return waitFor(() => {
        const content = document.querySelector('[data-slot="popover-content"]');
        if (!content) throw new Error("picker did not open");
        return content;
      });
    }

    function memberRow(content: Element) {
      const row = Array.from(
        content.querySelectorAll('[data-slot="command-item"]'),
      ).find((el) => el.textContent?.includes("Test User"));
      if (!row) throw new Error("member row not found");
      return row;
    }

    it("disables the rows while subscribers are loading", async () => {
      mockApiObj.listIssueSubscribers.mockReturnValue(new Promise(() => {}));
      renderIssueDetail();

      const row = memberRow(await openSubscriberPicker());

      expect(row.getAttribute("data-disabled")).toBe("true");

      fireEvent.click(row);

      expect(mockApiObj.subscribeToIssue).not.toHaveBeenCalled();
      expect(mockApiObj.unsubscribeFromIssue).not.toHaveBeenCalled();
    });

    it("disables the rows when the subscribers query failed", async () => {
      mockApiObj.listIssueSubscribers.mockRejectedValue(new Error("boom"));
      renderIssueDetail();

      const row = memberRow(await openSubscriberPicker());

      expect(row.getAttribute("data-disabled")).toBe("true");

      fireEvent.click(row);

      expect(mockApiObj.subscribeToIssue).not.toHaveBeenCalled();
      expect(mockApiObj.unsubscribeFromIssue).not.toHaveBeenCalled();
    });

    it("enables the rows once the query has a real answer", async () => {
      mockApiObj.listIssueSubscribers.mockResolvedValue([]);
      renderIssueDetail();
      // Wait for the resolved state before opening, so this is not just the
      // pending case passing by accident.
      await screen.findByText("Subscribe");

      const row = memberRow(await openSubscriberPicker());

      expect(row.getAttribute("data-disabled")).not.toBe("true");

      fireEvent.click(row);

      await waitFor(() =>
        expect(mockApiObj.subscribeToIssue).toHaveBeenCalledWith(
          "issue-1",
          "user-1",
          "member",
        ),
      );
    });
  });

  // A guest changes only its own subscription (MUL-9869): it sees who follows
  // the issue, but gets no picker that would subscribe someone else.
  it("shows a guest the subscribers without the picker", async () => {
    mockApiObj.listMembers.mockResolvedValue([
      { user_id: "user-1", name: "Test User", email: "[email protected]", role: "guest" },
    ]);
    mockApiObj.listIssueSubscribers.mockResolvedValue([
      {
        issue_id: "issue-1",
        user_type: "agent" as const,
        user_id: "agent-1",
        reason: "manual" as const,
        created_at: "2026-01-01T00:00:00Z",
      },
    ]);
    renderIssueDetail();

    expect(await screen.findByText("Subscribe")).toBeTruthy();
    const header = (await screen.findByText("Activity")).parentElement?.parentElement;
    await waitFor(() => expect(header?.querySelector('[data-slot="avatar-group"]')).not.toBeNull());
    expect(header?.querySelector('[data-trigger="popover"]')).toBeNull();
    document.body.innerHTML = "";
  });

  it("keeps the initial assignment block before a later mention and its run (MUL-7632)", async () => {
    const assignment: AgentTask = {
      id: "initial-assignment", agent_id: "agent-1", runtime_id: "rt-1", issue_id: "issue-1",
      kind: "direct", status: "running", priority: 0,
      created_at: "2026-01-16T00:00:00Z", started_at: "2026-01-16T00:00:00Z",
      dispatched_at: null, completed_at: null, result: null, error: null, delivered_comment_ids: [],
    };
    mockApiObj.listTimeline.mockResolvedValue([]);
    mockApiObj.listTasksByIssue.mockResolvedValue([assignment]);
    const client = createTestQueryClient();
    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={client}>
          <IssueDetail issueId="issue-1" defaultSidebarOpen={false} />
        </QueryClientProvider>
      </I18nProvider>,
    );
    await waitFor(() => expect(container.querySelector('[data-run-slot-id="initial-assignment"]')).not.toBeNull());
    const initialSlot = container.querySelector('[data-run-slot-id="initial-assignment"]')!;
    const mention: TimelineEntry = {
      type: "comment", id: "later-mention", actor_type: "member", actor_id: "user-1",
      content: "Please handle the other task", parent_id: null, created_at: "2026-01-16T00:01:00Z",
    };
    const mentionedRun: AgentTask = {
      ...assignment, id: "mentioned-run", agent_id: "agent-2", trigger_comment_id: mention.id,
      created_at: "2026-01-16T00:01:01Z", delivered_comment_ids: [mention.id],
    };
    mockApiObj.listTimeline.mockResolvedValue([mention]);
    mockApiObj.listTasksByIssue.mockResolvedValue([assignment, mentionedRun]);
    act(() => {
      client.setQueryData(issueKeys.timeline("issue-1"), [mention]);
      client.setQueryData(issueKeys.tasks("issue-1"), [assignment, mentionedRun]);
    });
    await screen.findByText(mention.content!);
    await waitFor(() => expect(container.querySelector('[data-run-id="mentioned-run"]')).not.toBeNull());
    expect(container.querySelector('[data-run-slot-id="initial-assignment"]')).toBe(initialSlot);
    const mentionBlock = container.querySelector("#comment-later-mention")!;
    expect(initialSlot.compareDocumentPosition(mentionBlock) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    expect(mentionBlock.querySelector('[data-run-id="mentioned-run"]')).not.toBeNull();
  });

  // MUL-7211 regression: a standalone run's published reply belongs at the
  // reply's own time. It used to render in the run's ENQUEUE slot while the
  // card showed the reply time, pushing it above every comment written while
  // the run worked. Ordering matrix lives in comment-runs.test.ts.
  it("renders an assignment run's reply after the comments it followed", async () => {
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "comment", id: "midway", actor_type: "member", actor_id: "user-1",
        content: "Remember the E2E pass", parent_id: null,
        created_at: "2026-01-17T00:00:00Z", updated_at: "2026-01-17T00:00:00Z", comment_type: "comment",
      },
      {
        type: "comment", id: "run-reply", actor_type: "agent", actor_id: "agent-1",
        content: "step1 done", parent_id: null, source_task_id: "task-early",
        created_at: "2026-01-18T00:00:00Z", updated_at: "2026-01-18T00:00:00Z", comment_type: "comment",
      },
    ]);
    mockApiObj.listTasksByIssue.mockResolvedValue([{
      id: "task-early", agent_id: "agent-1", runtime_id: "rt-1", issue_id: "issue-1",
      kind: "issue", status: "completed", priority: 0,
      dispatched_at: "2026-01-16T00:00:00Z", started_at: "2026-01-16T00:00:00Z",
      completed_at: "2026-01-18T00:00:00Z", result: { comment: "step1 done" }, error: null,
      created_at: "2026-01-16T00:00:00Z", delivered_comment_ids: [],
    }]);

    const { container } = renderIssueDetail();
    await screen.findByText("Remember the E2E pass");
    await screen.findByText("step1 done");

    const rendered = Array.from(container.querySelectorAll("[id^='comment-']")).map((el) => el.id);
    expect(rendered.indexOf("comment-midway")).toBeLessThan(rendered.indexOf("comment-run-reply"));
  });

  // MUL-7548 regression: a comment-triggered run that posts several comments
  // used to render its latest one first — the run slot after the trigger held
  // only the latest, and the earlier ones followed it (or stayed top-level).
  // Each comment reads at its own time, so a reply written between two of the
  // run's comments stays between them (MUL-7628).
  it.each([
    { placement: "top-level", parentId: null },
    { placement: "in the trigger's thread", parentId: "confirm" },
  ])("renders every comment of a run in posting order when posted $placement", async ({ parentId }) => {
    const agentComment = (id: string, content: string, created_at: string): TimelineEntry => ({
      type: "comment", id, actor_type: "agent", actor_id: "agent-1", content, parent_id: parentId,
      source_task_id: "task-steps", created_at, updated_at: created_at, comment_type: "comment",
    });
    mockApiObj.listTimeline.mockResolvedValue([
      {
        type: "comment", id: "confirm", actor_type: "member", actor_id: "user-1",
        content: "Confirmed", parent_id: null,
        created_at: "2026-01-17T00:00:00Z", updated_at: "2026-01-17T00:00:00Z", comment_type: "comment",
      },
      agentComment("step2", "Step 2 done", "2026-01-17T00:10:00Z"),
      {
        type: "comment", id: "aside", actor_type: "member", actor_id: "user-1",
        content: "Check the tests too", parent_id: "confirm",
        created_at: "2026-01-17T00:15:00Z", updated_at: "2026-01-17T00:15:00Z", comment_type: "comment",
      },
      agentComment("step3", "Step 3 done", "2026-01-17T00:20:00Z"),
    ]);
    mockApiObj.listTasksByIssue.mockResolvedValue([{
      id: "task-steps", agent_id: "agent-1", runtime_id: "rt-1", issue_id: "issue-1",
      kind: "issue", status: "running", priority: 0,
      dispatched_at: "2026-01-17T00:00:01Z", started_at: "2026-01-17T00:00:01Z",
      completed_at: null, result: null, error: null,
      created_at: "2026-01-17T00:00:01Z", trigger_comment_id: "confirm", delivered_comment_ids: ["confirm"],
    }]);

    const { container } = renderIssueDetail();
    await screen.findByText("Step 2 done");
    await screen.findByText("Step 3 done");

    const rendered = Array.from(container.querySelectorAll("[id^='comment-']")).map((el) => el.id)
      .filter((id) => ["comment-confirm", "comment-step2", "comment-aside", "comment-step3"].includes(id));
    expect(rendered).toEqual(["comment-confirm", "comment-step2", "comment-aside", "comment-step3"]);
  });

});

describe("groupSubIssuesByStage", () => {
  const child = (id: string, stage: number | null): Issue => ({
    ...mockIssue,
    id,
    parent_issue_id: "parent-1",
    stage,
  });

  it("returns a single null-stage group when nothing is staged", () => {
    const groups = groupSubIssuesByStage([child("a", null), child("b", null)]);
    expect(groups).toHaveLength(1);
    expect(groups[0]?.stage).toBeNull();
    expect(groups[0]?.items.map((i) => i.id)).toEqual(["a", "b"]);
  });

  it("orders staged groups ascending with the unstaged group last", () => {
    const groups = groupSubIssuesByStage([
      child("s2", 2),
      child("u", null),
      child("s1a", 1),
      child("s1b", 1),
    ]);
    expect(groups.map((g) => g.stage)).toEqual([1, 2, null]);
    expect(groups[0]?.items.map((i) => i.id)).toEqual(["s1a", "s1b"]);
    expect(groups[2]?.items.map((i) => i.id)).toEqual(["u"]);
  });

  it("omits the unstaged group when every child is staged", () => {
    const groups = groupSubIssuesByStage([child("s1", 1), child("s2", 2)]);
    expect(groups.map((g) => g.stage)).toEqual([1, 2]);
  });
});