Reports

#8021 · Cached message navigation can remain hidden

Bug Priority: Medium Effort: Low threads · 2026-11-22 · GitHub issue

Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro

Trusted main commit: 796cdcc0f4bf8a55e23664035c54e8db6fe9d272. Same agent repeated the reproduction in a second clean checkout; this is not an independent review.

1. TL;DR

A link to a newer message can be classified as missing while the cached timeline is being refreshed. That terminal path records the navigation as handled, but does not record it as settled. When the reply subsequently arrives, the reveal flag becomes pending and the timeline renderer hides its rows; the handled guard then prevents the reveal from running. Two regression tests fail on unchanged main in two separate checkouts. A small hook-only production fix waits for the exact thread timeline query to finish and settles missing targets as well as successful reveals.

2. Claims vs findings

ClaimFindingEvidence
A stale cached window can reject a valid newer message link.VerifiedThe real timeline controller, real React Query lifecycle and navigation hook reproduce the race with a deferred SDK response.
Rows can be loaded yet remain hidden indefinitely.VerifiedBoth tests receive the target row, but observe pending=true instead of false. A real browser harness shows visibility:hidden with two rows in the DOM after refresh.
The missing-target terminal path does not settle reveal state.VerifiedSource at the recorded commit and a separate regression that adds a row after a terminal missing-target result.
Exact toast timing, reported app version, desktop and mobile variants, and reload workaround.Not separately verifiedThis investigation exercises source main in jsdom and a desktop Chromium hook harness, not the installed release or every app platform.

3. Environment

4. Minimal reproduction

  1. Clone the public repository and select the exact trusted base.
  2. Install the existing dependencies and build the SDK prerequisites. Download the report's own test-only patch, then apply it.
  3. Run the existing app test project through Turbo. The first new case seeds a cached row at seq 1, opens a link to seq 2, and completes a deferred refresh with seq 2. The second resolves an initially missing link, then delivers its row through the query cache.
git clone https://github.com/get-bb/bb.git bb-8021
cd bb-8021
git checkout 796cdcc0f4bf8a55e23664035c54e8db6fe9d272
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk
curl -fsSL https://get-bb.github.io/reports/issues/8021/repro/regression-tests.patch -o /tmp/8021-tests.patch
git apply /tmp/8021-tests.patch
pnpm exec turbo run test --filter=@bb/app -- src/components/thread/timeline/useThreadTimelineController.test.tsx

Expected: completing the refresh reveals and scrolls to seq 2 without a false missing-message toast. A terminal missing link must never re-hide the list when rows change.

Actual on the trusted base (both checkouts):

FAIL reveals a message newer than the cached timeline after refreshing
AssertionError: expected true to be false
FAIL keeps a missing message link settled when later rows contain its target
AssertionError: expected true to be false
Tests  2 failed | 32 passed (34)

Both failures occur after the controller has received the target row, at the assertions on the real hook's pending result. The test stubs only the SDK transport; it does not replace the query owner, controller, router, navigation hook, or database.

Test-only patch · Complete test file · Browser harness source

Complete regression test file, including existing fixtures and imports
// @vitest-environment jsdom

import {
  act,
  cleanup,
  render,
  renderHook,
  waitFor,
} from "@testing-library/react";
import {
  Profiler,
  useLayoutEffect,
  type ProfilerOnRenderCallback,
  type ReactNode,
} from "react";
import { MemoryRouter } from "react-router-dom";
import type { QueryClient } from "@tanstack/react-query";
import type {
  ThreadTimelineResponse,
  TimelineUserConversationRow,
} from "@bb/server-contract";
import { createDeferredPromise, type DeferredPromise } from "@bb/test-helpers";
import {
  afterEach,
  beforeEach,
  describe,
  expect,
  it,
  onTestFinished,
  vi,
} from "vitest";
import {
  BottomAnchorContext,
  type BottomAnchorContextValue,
} from "@/components/ui/bottom-anchored-scroll-body.js";
import { BbHttpError, sdk } from "@/lib/sdk";
import { appToast } from "@/components/ui/app-toast";
import { threadTimelineQueryKey } from "@/hooks/queries/query-keys";
import { applyThreadTimelineSignal } from "@/hooks/cache-owners/thread-timeline-push-owner";
import {
  hasThreadTimelineUnseenEvents,
  markThreadTimelineUnseenEvents,
} from "@/hooks/cache-owners/thread-timeline-unseen-events";
import { createQueryClientTestHarness } from "@/test/queryClientTestHarness";
import { systemRow } from "@/test/fixtures/thread-timeline-rows";
import { useAutoLoadOlderRows } from "./useAutoLoadOlderRows";
import {
  SearchMessageLocationProvider,
  useScrollToSearchedMessage,
} from "./useScrollToSearchedMessage";
import {
  TIMELINE_CONTROLLER_PROPS_WITHOUT_ROWS,
  useThreadTimelineController,
  type UseThreadTimelineControllerResult,
} from "./useThreadTimelineController";
import { makeThreadTimelineResponse as makeTimelineResponse } from "@/test/fixtures/thread-responses";
import { createQueryNotificationScheduler } from "@/test/queryNotificationScheduler";
import { ScrollPositionKeeper } from "@/components/ui/scroll-position-keeper";

const notifications = createQueryNotificationScheduler();

beforeEach(() => notifications.install());

const readTimelineQueryResultKeys = vi.hoisted(() => new Set<PropertyKey>());

vi.mock("@/lib/sdk", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@/lib/sdk")>();
  return {
    ...actual,
    sdk: { threads: { timeline: vi.fn() } },
  };
});

vi.mock("@/hooks/queries/thread-panel-queries", async (importOriginal) => {
  const actual =
    await importOriginal<
      typeof import("@/hooks/queries/thread-panel-queries")
    >();
  return {
    ...actual,
    useThreadTimeline: (...args: Parameters<typeof actual.useThreadTimeline>) =>
      new Proxy(actual.useThreadTimeline(...args), {
        get(target, key, receiver) {
          readTimelineQueryResultKeys.add(key);
          return Reflect.get(target, key, receiver);
        },
      }),
  };
});

vi.mock("@/hooks/useRealtimeSubscription", () => ({
  useThreadDetailRealtimeSubscription: vi.fn(),
  useThreadTimelineRealtimeSubscription: vi.fn(),
}));

vi.mock("@/hooks/useServerConnectionState", () => ({
  useServerConnectionState: () => "connected",
}));

afterEach(() => {
  cleanup();
  notifications.restore();
  vi.mocked(sdk.threads.timeline).mockReset();
  vi.clearAllMocks();
  vi.unstubAllGlobals();
  readTimelineQueryResultKeys.clear();
});

const TIMELINE_QUERY_KEY = threadTimelineQueryKey("thread-1");

function makeUserRow(
  id: string,
  sourceSeq: number,
): TimelineUserConversationRow {
  return {
    id,
    kind: "conversation",
    role: "user",
    threadId: "thread-1",
    turnId: null,
    sourceSeqStart: sourceSeq,
    sourceSeqEnd: sourceSeq,
    messageSeq: sourceSeq,
    startedAt: 1,
    createdAt: 1,
    text: "hello",
    mentions: [],
    attachments: null,
    initiator: "user",
    senderThreadId: null,
    systemMessageKind: "unlabeled",
    systemMessageSubject: null,
    turnRequest: { isGrouped: false, kind: "message", status: "accepted" },
  };
}

const contextClearRow = systemRow({
  id: "context-clear-10",
  seq: 10,
  title: "Context cleared",
  detail: null,
});
const newestLoadedRow = makeUserRow("thread-1:user-seed:1", 1);
const olderPageRow = makeUserRow("thread-1:user-seed:0", 0);
const realtimeRow = makeUserRow("thread-1:user-seed:2", 2);

function rowIds(controller: UseThreadTimelineControllerResult): string[] {
  return controller.timelineRows.map((row) => row.id);
}

function makeServerError(): BbHttpError {
  return new BbHttpError({
    body: null,
    code: null,
    message: "Server error",
    status: 500,
  });
}

async function renderControllerWithPendingOlderPage() {
  const olderPage = createDeferredPromise<ThreadTimelineResponse>();
  vi.mocked(sdk.threads.timeline)
    .mockResolvedValueOnce(
      makeTimelineResponse({
        rows: [newestLoadedRow],
        maxSeq: 1,
        timelinePage: {
          historySnapshot: "snapshot-1",
          olderCursor: { anchorId: newestLoadedRow.id, anchorSeq: 1 },
          olderRowsSourceSeqEnd: null,
        },
      }),
    )
    .mockReturnValueOnce(olderPage.promise);

  const { queryClient, wrapper } = createQueryClientTestHarness();
  const { result } = renderHook(
    () => useThreadTimelineController({ threadId: "thread-1" }),
    { wrapper },
  );
  await waitFor(() => {
    expect(result.current.hasOlderTimelineRows).toBe(true);
  });

  let olderRequest: Promise<void> = Promise.resolve();
  act(() => {
    olderRequest = result.current.loadOlderTimelineRows();
  });
  await waitFor(() => {
    expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
  });

  const settleOlderPage = async () => {
    olderPage.resolve(
      makeTimelineResponse({
        rows: [olderPageRow],
        maxSeq: 1,
        timelinePage: { historySnapshot: "snapshot-1" },
      }),
    );
    await act(async () => {
      await olderRequest;
    });
  };
  const failOlderPage = async (error: BbHttpError) => {
    olderPage.reject(error);
    await act(async () => {
      await expect(olderRequest).rejects.toBe(error);
    });
  };
  const publishLatest = (response: ThreadTimelineResponse) => {
    act(() => {
      queryClient.setQueryData(TIMELINE_QUERY_KEY, response);
    });
  };

  return { failOlderPage, publishLatest, result, settleOlderPage };
}

function makeSameSnapshotRealtimeResponse(): ThreadTimelineResponse {
  return makeTimelineResponse({
    rows: [newestLoadedRow, realtimeRow],
    maxSeq: 2,
    timelinePage: {
      historySnapshot: "snapshot-1",
      olderCursor: { anchorId: newestLoadedRow.id, anchorSeq: 1 },
      olderRowsSourceSeqEnd: null,
    },
  });
}

function installAutoLoadEnvironment() {
  const scrollElement = document.createElement("div");
  const sentinel = document.createElement("div");
  document.body.append(sentinel);
  vi.spyOn(scrollElement, "getBoundingClientRect").mockReturnValue(
    new DOMRect(0, 0, 100, 500),
  );
  vi.spyOn(sentinel, "getBoundingClientRect").mockReturnValue(
    new DOMRect(0, 10, 100, 10),
  );
  const positionKeeper = new ScrollPositionKeeper({
    bottomThresholdPx: 4,
    deferWritesWhileScrolling: false,
    getContentElement: () => null,
    getFloorElement: () => null,
    getFooterElement: () => null,
    getScrollElement: () => scrollElement,
    getTopLevelRows: () => [],
    initiallyAttached: false,
  });
  const anchor: BottomAnchorContextValue = {
    positionKeeper,
    holdContentPosition: vi.fn(),
    getScrollElement: () => scrollElement,
    isAtBottom: false,
    scrollElementIntoView: vi.fn(),
    scrollToBottom: vi.fn(),
  };
  const emitIntersection = () => {
    positionKeeper.reconcile();
  };
  return { anchor, emitIntersection, sentinel };
}

function renderControllerWithAutoLoad(anchor: BottomAnchorContextValue) {
  const { queryClient, wrapper: queryWrapper } = createQueryClientTestHarness();
  const wrapper = ({ children }: { children: ReactNode }) =>
    queryWrapper({
      children: (
        <BottomAnchorContext.Provider value={anchor}>
          {children}
        </BottomAnchorContext.Provider>
      ),
    });
  const { result } = renderHook(
    () => {
      const timeline = useThreadTimelineController({ threadId: "thread-1" });
      const autoLoad = useAutoLoadOlderRows({
        hasOlderTimelineRows: timeline.hasOlderTimelineRows,
        isLoadingOlderTimelineRows: timeline.isLoadingOlderTimelineRows,
        onLoadOlderRows: timeline.loadOlderTimelineRows,
      });
      return { autoLoad, timeline };
    },
    { wrapper },
  );
  return { queryClient, result };
}

async function withReactSchedulerOutsideAct(
  run: () => Promise<void>,
): Promise<void> {
  const previousActEnvironment: unknown = Reflect.get(
    globalThis,
    "IS_REACT_ACT_ENVIRONMENT",
  );
  Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", false);
  try {
    await run();
  } finally {
    Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", previousActEnvironment);
  }
}

interface ProfiledController {
  latest: () => UseThreadTimelineControllerResult;
  profilerCommitCount: () => number;
}

function renderProfiledController(
  wrapper: (props: { children: ReactNode }) => ReactNode,
): ProfiledController {
  const latestResult: { current: UseThreadTimelineControllerResult | null } = {
    current: null,
  };
  let profilerCommits = 0;
  const onRender: ProfilerOnRenderCallback = () => {
    profilerCommits += 1;
  };

  function ControllerHost() {
    const controller = useThreadTimelineController({ threadId: "thread-1" });
    useLayoutEffect(() => {
      latestResult.current = controller;
    });
    return null;
  }

  render(
    <Profiler id="timeline-controller" onRender={onRender}>
      <ControllerHost />
    </Profiler>,
    { wrapper },
  );

  return {
    latest: () => {
      if (latestResult.current === null) {
        throw new Error("The timeline controller has not committed yet");
      }
      return latestResult.current;
    },
    profilerCommitCount: () => profilerCommits,
  };
}

function flushQueryNotifications(): Promise<void> {
  return notifications.flush();
}

async function renderSettledController(
  wrapper: (props: { children: ReactNode }) => ReactNode,
  expectedRowIds: string[],
): Promise<ProfiledController> {
  const view = renderProfiledController(wrapper);
  await waitFor(() => {
    expect(view.latest().timelineLoading).toBe(false);
    expect(rowIds(view.latest())).toEqual(expectedRowIds);
  });
  await flushQueryNotifications();
  return view;
}

function startTimelineRefetch(queryClient: QueryClient): void {
  act(() => {
    void queryClient.refetchQueries({ queryKey: TIMELINE_QUERY_KEY });
  });
}

function markTimelineHasNewEvents(queryClient: QueryClient): void {
  markThreadTimelineUnseenEvents(queryClient, "thread-1", 2);
  void queryClient.invalidateQueries({
    queryKey: TIMELINE_QUERY_KEY,
    refetchType: "none",
  });
}

describe("useThreadTimelineController", () => {
  it("keeps the thread's loaded older pages when its timeline mounts again", async () => {
    const olderRow = makeUserRow("thread-1:user-seed:1", 1);
    const latestRow = makeUserRow("thread-1:user-seed:10", 10);
    const latestPage = makeTimelineResponse({
      rows: [latestRow],
      maxSeq: 10,
      timelinePage: {
        historySnapshot: "snapshot-1",
        olderCursor: { anchorId: "cursor-10", anchorSeq: 10 },
        olderRowsSourceSeqEnd: null,
      },
    });
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(latestPage)
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [olderRow],
          maxSeq: 10,
          timelinePage: { historySnapshot: "snapshot-1" },
        }),
      )
      .mockResolvedValue(latestPage);
    const { wrapper } = createQueryClientTestHarness();
    const first = renderHook(
      () => useThreadTimelineController({ threadId: "thread-1" }),
      { wrapper },
    );
    await waitFor(() => {
      expect(first.result.current.hasOlderTimelineRows).toBe(true);
    });
    await act(async () => {
      await first.result.current.loadOlderTimelineRows();
    });
    first.unmount();

    const second = renderHook(
      () => useThreadTimelineController({ threadId: "thread-1" }),
      { wrapper },
    );

    expect(rowIds(second.result.current)).toEqual([olderRow.id, latestRow.id]);
    expect(second.result.current.hasOlderTimelineRows).toBe(false);
  });

  it("replaces loaded rows when realtime data starts a new context epoch", async () => {
    const oldRow = makeUserRow("thread-1:user-seed:1", 1);
    vi.mocked(sdk.threads.timeline).mockResolvedValue(
      makeTimelineResponse({ rows: [oldRow], maxSeq: 1 }),
    );

    const { queryClient, wrapper } = createQueryClientTestHarness();
    const { result } = renderHook(
      () => useThreadTimelineController({ threadId: "thread-1" }),
      { wrapper },
    );
    await waitFor(() => {
      expect(rowIds(result.current)).toEqual([oldRow.id]);
    });

    act(() => {
      queryClient.setQueryData(
        TIMELINE_QUERY_KEY,
        makeTimelineResponse({
          contextBoundarySeq: 10,
          maxSeq: 10,
          rows: [contextClearRow],
        }),
      );
    });

    await waitFor(() => {
      expect(result.current.contextBoundarySeq).toBe(10);
      expect(rowIds(result.current)).toEqual([contextClearRow.id]);
    });
  });

  it.each([
    [
      "a context reset changes the surface",
      {
        contextBoundarySeq: 10,
        timelinePage: { historySnapshot: "snapshot-1" },
      },
    ],
    [
      "latest changes the history snapshot",
      { timelinePage: { historySnapshot: "snapshot-2" } },
    ],
  ])(
    "discards an in-flight older page when %s",
    async (_label, latestOverrides) => {
      const { publishLatest, result, settleOlderPage } =
        await renderControllerWithPendingOlderPage();

      publishLatest(
        makeTimelineResponse({
          ...latestOverrides,
          maxSeq: 10,
          rows: [contextClearRow],
        }),
      );
      await waitFor(() => {
        expect(rowIds(result.current)).toEqual([contextClearRow.id]);
      });
      await settleOlderPage();

      expect(rowIds(result.current)).toEqual([contextClearRow.id]);
    },
  );

  it("replaces loaded older rows when the finished turn display changes", async () => {
    const olderRow = makeUserRow("thread-1:user-seed:1", 1);
    const latestRow = makeUserRow("thread-1:user-seed:10", 10);
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(
        makeTimelineResponse({
          completedTurnDisplay: "flat",
          rows: [latestRow],
          maxSeq: 10,
          timelinePage: {
            historySnapshot: "snapshot-flat",
            olderCursor: { anchorId: "cursor-10", anchorSeq: 10 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      )
      .mockResolvedValueOnce(
        makeTimelineResponse({
          completedTurnDisplay: "flat",
          rows: [olderRow],
          maxSeq: 10,
          timelinePage: { historySnapshot: "snapshot-flat" },
        }),
      );

    const { queryClient, wrapper } = createQueryClientTestHarness();
    const { result } = renderHook(
      () => useThreadTimelineController({ threadId: "thread-1" }),
      { wrapper },
    );
    await waitFor(() => {
      expect(result.current.hasOlderTimelineRows).toBe(true);
    });
    await act(async () => {
      await result.current.loadOlderTimelineRows();
    });
    expect(rowIds(result.current)).toEqual([olderRow.id, latestRow.id]);

    act(() => {
      queryClient.setQueryData(
        TIMELINE_QUERY_KEY,
        makeTimelineResponse({
          completedTurnDisplay: "collapse",
          rows: [latestRow],
          maxSeq: 10,
          timelinePage: {
            historySnapshot: "snapshot-collapse",
            olderRowsSourceSeqEnd: 1,
            olderCursor: { anchorId: "cursor-10-collapse", anchorSeq: 10 },
          },
        }),
      );
    });

    await waitFor(() => {
      expect(rowIds(result.current)).toEqual([latestRow.id]);
    });
    expect(result.current.hasOlderTimelineRows).toBe(true);
  });

  it("keeps older rows and applies an in-flight older page while realtime refreshes advance the snapshot", async () => {
    const olderRow = makeUserRow("thread-1:user-seed:1", 1);
    const latestRow = makeUserRow("thread-1:user-seed:10", 10);
    const streamingRow = makeUserRow("thread-1:user-seed:11", 11);
    let resolveOlder: (value: ThreadTimelineResponse) => void = () => {};
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [latestRow],
          maxSeq: 10,
          timelinePage: {
            historySnapshot: "snapshot-10",
            olderCursor: { anchorId: "cursor-10", anchorSeq: 10 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      )
      .mockImplementationOnce(
        () =>
          new Promise<ThreadTimelineResponse>((resolve) => {
            resolveOlder = resolve;
          }),
      );

    const { queryClient, wrapper } = createQueryClientTestHarness();
    const { result } = renderHook(
      () => useThreadTimelineController({ threadId: "thread-1" }),
      { wrapper },
    );
    await waitFor(() => {
      expect(result.current.hasOlderTimelineRows).toBe(true);
    });

    let olderRequest: Promise<void> = Promise.resolve();
    act(() => {
      olderRequest = result.current.loadOlderTimelineRows();
    });
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
    });
    act(() => {
      queryClient.setQueryData(
        threadTimelineQueryKey("thread-1"),
        makeTimelineResponse({
          rows: [latestRow, streamingRow],
          maxSeq: 11,
          timelinePage: {
            historySnapshot: "snapshot-11",
            olderRowsSourceSeqEnd: null,
            olderCursor: { anchorId: "cursor-11", anchorSeq: 10 },
          },
        }),
      );
    });
    await waitFor(() => {
      expect(result.current.timelineRows.map((row) => row.id)).toEqual([
        latestRow.id,
        streamingRow.id,
      ]);
    });

    resolveOlder(
      makeTimelineResponse({
        rows: [olderRow],
        maxSeq: 10,
        timelinePage: { historySnapshot: "snapshot-10" },
      }),
    );
    await act(async () => {
      await olderRequest;
    });

    expect(result.current.timelineRows.map((row) => row.id)).toEqual([
      olderRow.id,
      latestRow.id,
      streamingRow.id,
    ]);
    expect(result.current.hasOlderTimelineRows).toBe(false);

    act(() => {
      queryClient.setQueryData(
        threadTimelineQueryKey("thread-1"),
        makeTimelineResponse({
          rows: [latestRow, { ...streamingRow, sourceSeqEnd: 12 }],
          maxSeq: 12,
          timelinePage: {
            historySnapshot: "snapshot-12",
            olderRowsSourceSeqEnd: null,
            olderCursor: { anchorId: "cursor-12", anchorSeq: 10 },
          },
        }),
      );
    });
    await waitFor(() => {
      expect(result.current.timelineRows[2]?.sourceSeqEnd).toBe(12);
    });
    expect(result.current.timelineRows.map((row) => row.id)).toEqual([
      olderRow.id,
      latestRow.id,
      streamingRow.id,
    ]);
  });

  it("keeps an initial timeline refetch in loading state instead of showing the previous error", async () => {
    const refetch = createDeferredPromise<ThreadTimelineResponse>();
    vi.mocked(sdk.threads.timeline)
      .mockRejectedValueOnce(makeServerError())
      .mockReturnValueOnce(refetch.promise);

    const { queryClient, wrapper } = createQueryClientTestHarness();
    const { result } = renderHook(
      () => useThreadTimelineController({ threadId: "thread-1" }),
      { wrapper },
    );

    await waitFor(() => {
      expect(result.current.timelineError).toBeInstanceOf(BbHttpError);
    });

    startTimelineRefetch(queryClient);

    await waitFor(() => {
      expect(result.current.timelineLoading).toBe(true);
    });
    expect(result.current.timelineError).toBeNull();

    refetch.resolve(makeTimelineResponse());

    await waitFor(() => {
      expect(result.current.timelineLoading).toBe(false);
      expect(result.current.timelineError).toBeNull();
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
    });
  });

  it.each([
    ["before", true],
    ["after", false],
  ])(
    "keeps an older page that resolves %s a same-snapshot realtime update",
    async (_order, olderPageFirst) => {
      const { publishLatest, result, settleOlderPage } =
        await renderControllerWithPendingOlderPage();
      const publishRealtimeUpdate = async () => {
        publishLatest(makeSameSnapshotRealtimeResponse());
        await waitFor(() => {
          expect(rowIds(result.current)).toContain(realtimeRow.id);
        });
      };

      if (olderPageFirst) {
        await settleOlderPage();
        await publishRealtimeUpdate();
      } else {
        await publishRealtimeUpdate();
        await settleOlderPage();
      }

      expect(rowIds(result.current)).toEqual([
        olderPageRow.id,
        newestLoadedRow.id,
        realtimeRow.id,
      ]);
      expect(result.current.hasOlderTimelineRows).toBe(false);
    },
  );

  it("rejects a failed older page so the caller can offer a retry", async () => {
    const { failOlderPage, result } =
      await renderControllerWithPendingOlderPage();
    expect(result.current.isLoadingOlderTimelineRows).toBe(true);

    await failOlderPage(makeServerError());

    expect(result.current.isLoadingOlderTimelineRows).toBe(false);
    expect(result.current.hasOlderTimelineRows).toBe(true);
    expect(rowIds(result.current)).toEqual([newestLoadedRow.id]);
  });

  it("replaces an applied older page when a later realtime update changes the history snapshot", async () => {
    const { publishLatest, result, settleOlderPage } =
      await renderControllerWithPendingOlderPage();

    await settleOlderPage();
    expect(rowIds(result.current)).toEqual([
      olderPageRow.id,
      newestLoadedRow.id,
    ]);
    publishLatest(
      makeTimelineResponse({
        rows: [contextClearRow],
        maxSeq: 10,
        timelinePage: {
          historySnapshot: "snapshot-2",
          olderCursor: { anchorId: contextClearRow.id, anchorSeq: 10 },
          olderRowsSourceSeqEnd: null,
        },
      }),
    );

    await waitFor(() => {
      expect(rowIds(result.current)).toEqual([contextClearRow.id]);
    });
    expect(result.current.hasOlderTimelineRows).toBe(true);
  });

  it("adopts the refetched latest cursor after a stale older-page cursor", async () => {
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [newestLoadedRow],
          maxSeq: 1,
          timelinePage: {
            historySnapshot: "snapshot-1",
            olderCursor: { anchorId: newestLoadedRow.id, anchorSeq: 1 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      )
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [olderPageRow],
          maxSeq: 1,
          timelinePage: {
            historySnapshot: "snapshot-1",
            olderCursor: { anchorId: olderPageRow.id, anchorSeq: 0 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      )
      .mockRejectedValueOnce(
        new BbHttpError({
          body: null,
          code: "invalid_request",
          message: "Stale timeline cursor",
          status: 400,
        }),
      )
      .mockResolvedValueOnce(makeSameSnapshotRealtimeResponse())
      .mockReturnValueOnce(new Promise(() => {}));

    const { wrapper } = createQueryClientTestHarness();
    const { result } = renderHook(
      () => useThreadTimelineController({ threadId: "thread-1" }),
      { wrapper },
    );
    await waitFor(() => {
      expect(result.current.hasOlderTimelineRows).toBe(true);
    });
    await act(async () => {
      await result.current.loadOlderTimelineRows();
    });
    expect(rowIds(result.current)).toEqual([
      olderPageRow.id,
      newestLoadedRow.id,
    ]);

    await act(async () => {
      await result.current.loadOlderTimelineRows();
    });

    await waitFor(() => {
      expect(rowIds(result.current)).toEqual([
        olderPageRow.id,
        newestLoadedRow.id,
        realtimeRow.id,
      ]);
    });
    const timelineRequests = vi.mocked(sdk.threads.timeline).mock.calls;
    expect(timelineRequests[2]?.[0]).toMatchObject({
      beforeAnchorId: olderPageRow.id,
      beforeAnchorSeq: "0",
    });
    expect(timelineRequests[3]?.[0]).toMatchObject({ afterTag: "timeline-1" });
    expect(result.current.isLoadingOlderTimelineRows).toBe(false);
    expect(result.current.hasOlderTimelineRows).toBe(true);

    act(() => {
      void result.current.loadOlderTimelineRows();
    });
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(5);
    });
    expect(vi.mocked(sdk.threads.timeline).mock.calls[4]?.[0]).toMatchObject({
      beforeAnchorId: newestLoadedRow.id,
      beforeAnchorSeq: "1",
    });
  });

  it("keeps auto-loading when an older page settles before its loading state renders", async () => {
    const { anchor, emitIntersection, sentinel } = installAutoLoadEnvironment();
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [realtimeRow],
          maxSeq: 2,
          timelinePage: {
            historySnapshot: "snapshot-1",
            olderCursor: { anchorId: realtimeRow.id, anchorSeq: 2 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      )
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [newestLoadedRow],
          maxSeq: 2,
          timelinePage: {
            historySnapshot: "snapshot-1",
            olderCursor: { anchorId: newestLoadedRow.id, anchorSeq: 1 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      )
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [olderPageRow],
          maxSeq: 2,
          timelinePage: {
            historySnapshot: "snapshot-1",
            olderCursor: null,
            olderRowsSourceSeqEnd: null,
          },
        }),
      );

    const { result } = renderControllerWithAutoLoad(anchor);
    await waitFor(() => {
      expect(result.current.timeline.hasOlderTimelineRows).toBe(true);
    });
    act(() => {
      result.current.autoLoad.sentinelRef(sentinel);
    });

    await withReactSchedulerOutsideAct(async () => {
      emitIntersection();
      await waitFor(() => {
        expect(result.current.timeline.hasOlderTimelineRows).toBe(false);
      });
    });

    expect(sdk.threads.timeline).toHaveBeenCalledTimes(3);
    expect(rowIds(result.current.timeline)).toEqual([
      olderPageRow.id,
      newestLoadedRow.id,
      realtimeRow.id,
    ]);
  });

  it("loads older history for a message link and reports a removed message as not found", async () => {
    const toastSpy = vi.spyOn(appToast, "message").mockReturnValue("toast-1");
    onTestFinished(() => toastSpy.mockRestore());
    const adjacentMessageRow = {
      ...makeUserRow("thread-1:user-seed:5", 5),
      sourceSeqStart: 4,
    };
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [makeUserRow("thread-1:user-seed:3", 3), adjacentMessageRow],
          maxSeq: 5,
          timelinePage: {
            historySnapshot: "snapshot-1",
            olderCursor: { anchorId: "thread-1:user-seed:3", anchorSeq: 3 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      )
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [newestLoadedRow],
          maxSeq: 5,
          timelinePage: {
            historySnapshot: "snapshot-1",
            olderCursor: null,
            olderRowsSourceSeqEnd: null,
          },
        }),
      );
    const { wrapper: queryWrapper } = createQueryClientTestHarness();
    const wrapper = ({ children }: { children: ReactNode }) =>
      queryWrapper({
        children: (
          <MemoryRouter
            initialEntries={["/projects/proj-1/threads/thread-1#msg=4"]}
          >
            <SearchMessageLocationProvider threadId="thread-1">
              {children}
            </SearchMessageLocationProvider>
          </MemoryRouter>
        ),
      });
    const { result } = renderHook(
      () => {
        const timeline = useThreadTimelineController({ threadId: "thread-1" });
        useScrollToSearchedMessage(timeline.timelineRows, "thread-1", {
          hasOlderRows: timeline.hasOlderTimelineRows,
          isLoadingOlderRows: timeline.isLoadingOlderTimelineRows,
          onLoadOlderRows: timeline.loadOlderTimelineRows,
          reportsMissingTarget: true,
        });
        return timeline;
      },
      { wrapper },
    );

    await waitFor(() => {
      expect(toastSpy).toHaveBeenCalledWith(
        "Message not found",
        expect.anything(),
      );
    });
    expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
    expect(rowIds(result.current)).toEqual([
      newestLoadedRow.id,
      "thread-1:user-seed:3",
      adjacentMessageRow.id,
    ]);
    expect(toastSpy).toHaveBeenCalledTimes(1);
  });

  it("reveals a message newer than the cached timeline after refreshing", async () => {
    const toastSpy = vi.spyOn(appToast, "message").mockReturnValue("toast-1");
    onTestFinished(() => toastSpy.mockRestore());
    const refresh = createDeferredPromise<ThreadTimelineResponse>();
    vi.mocked(sdk.threads.timeline).mockReturnValueOnce(refresh.promise);
    const { queryClient, wrapper: queryWrapper } = createQueryClientTestHarness(
      { queries: { staleTime: 0 } },
    );
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ rows: [newestLoadedRow], maxSeq: 1 }),
    );
    const wrapper = ({ children }: { children: ReactNode }) =>
      queryWrapper({
        children: (
          <MemoryRouter initialEntries={["/threads/thread-1#msg=2"]}>
            <SearchMessageLocationProvider threadId="thread-1">
              {children}
            </SearchMessageLocationProvider>
          </MemoryRouter>
        ),
      });
    const scrollIntoView = vi.fn();
    const renderedTarget = document.createElement("div");
    renderedTarget.setAttribute("data-timeline-row-id", realtimeRow.id);
    renderedTarget.scrollIntoView = scrollIntoView;
    onTestFinished(() => renderedTarget.remove());
    const { result } = renderHook(
      () => {
        const timeline = useThreadTimelineController({ threadId: "thread-1" });
        const pending = useScrollToSearchedMessage(
          timeline.timelineRows,
          "thread-1",
          { reportsMissingTarget: true },
        );
        return { pending, rows: rowIds(timeline) };
      },
      { wrapper },
    );

    await waitFor(() => expect(sdk.threads.timeline).toHaveBeenCalledOnce());
    document.body.appendChild(renderedTarget);
    await act(async () => {
      refresh.resolve(
        makeTimelineResponse({
          rows: [newestLoadedRow, realtimeRow],
          maxSeq: 2,
        }),
      );
    });
    await waitFor(() => expect(result.current.rows).toContain(realtimeRow.id));
    await waitFor(() => expect(result.current.pending).toBe(false));
    expect(scrollIntoView).toHaveBeenCalledWith({
      block: "start",
      inline: "nearest",
    });
    expect(toastSpy).not.toHaveBeenCalled();
  });

  it("keeps a missing message link settled when later rows contain its target", async () => {
    const toastSpy = vi.spyOn(appToast, "message").mockReturnValue("toast-1");
    onTestFinished(() => toastSpy.mockRestore());
    const { queryClient, wrapper: queryWrapper } = createQueryClientTestHarness(
      { queries: { staleTime: Infinity } },
    );
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ rows: [newestLoadedRow], maxSeq: 1 }),
    );
    const wrapper = ({ children }: { children: ReactNode }) =>
      queryWrapper({
        children: (
          <MemoryRouter initialEntries={["/threads/thread-1#msg=2"]}>
            <SearchMessageLocationProvider threadId="thread-1">
              {children}
            </SearchMessageLocationProvider>
          </MemoryRouter>
        ),
      });
    const { result } = renderHook(
      () => {
        const timeline = useThreadTimelineController({ threadId: "thread-1" });
        const pending = useScrollToSearchedMessage(
          timeline.timelineRows,
          "thread-1",
          { reportsMissingTarget: true },
        );
        return { pending, rows: rowIds(timeline) };
      },
      { wrapper },
    );

    await waitFor(() => expect(toastSpy).toHaveBeenCalledOnce());
    expect(result.current.pending).toBe(false);
    act(() => {
      queryClient.setQueryData(
        TIMELINE_QUERY_KEY,
        makeTimelineResponse({
          rows: [newestLoadedRow, realtimeRow],
          maxSeq: 2,
        }),
      );
    });
    await waitFor(() => expect(result.current.rows).toContain(realtimeRow.id));
    expect(result.current.pending).toBe(false);
    expect(toastSpy).toHaveBeenCalledOnce();
  });

  it("reveals an accepted steer from a link to its request seq", async () => {
    const toastSpy = vi.spyOn(appToast, "message").mockReturnValue("toast-1");
    onTestFinished(() => toastSpy.mockRestore());
    const steerRow: TimelineUserConversationRow = {
      ...makeUserRow("thread-1:user-seed:5", 7),
      messageSeq: 5,
      turnRequest: { isGrouped: false, kind: "steer", status: "accepted" },
    };
    const { queryClient, wrapper: queryWrapper } = createQueryClientTestHarness(
      { queries: { staleTime: Infinity } },
    );
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({
        rows: [makeUserRow("thread-1:user-seed:3", 3), steerRow],
        maxSeq: 8,
      }),
    );
    const wrapper = ({ children }: { children: ReactNode }) =>
      queryWrapper({
        children: (
          <MemoryRouter
            initialEntries={["/projects/proj-1/threads/thread-1#msg=5"]}
          >
            <SearchMessageLocationProvider threadId="thread-1">
              {children}
            </SearchMessageLocationProvider>
          </MemoryRouter>
        ),
      });
    const scrollIntoView = vi.fn();
    const renderedTarget = document.createElement("div");
    renderedTarget.setAttribute("data-timeline-row-id", steerRow.id);
    renderedTarget.scrollIntoView = scrollIntoView;
    document.body.appendChild(renderedTarget);
    onTestFinished(() => renderedTarget.remove());

    renderHook(
      () => {
        const timeline = useThreadTimelineController({ threadId: "thread-1" });
        useScrollToSearchedMessage(timeline.timelineRows, "thread-1", {
          hasOlderRows: timeline.hasOlderTimelineRows,
          isLoadingOlderRows: timeline.isLoadingOlderTimelineRows,
          onLoadOlderRows: timeline.loadOlderTimelineRows,
          reportsMissingTarget: true,
        });
        return timeline;
      },
      { wrapper },
    );

    await waitFor(() => {
      expect(scrollIntoView).toHaveBeenCalledWith({
        block: "start",
        inline: "nearest",
      });
    });
    expect(toastSpy).not.toHaveBeenCalled();
  });

  it("retries revealing a searched row when a realtime update changes only top-level fields", async () => {
    const { queryClient, wrapper: queryWrapper } = createQueryClientTestHarness(
      { queries: { staleTime: Infinity } },
    );
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ rows: [newestLoadedRow], maxSeq: 1 }),
    );
    const wrapper = ({ children }: { children: ReactNode }) =>
      queryWrapper({
        children: (
          <MemoryRouter
            initialEntries={[
              {
                pathname: "/thread",
                state: { searchMessageSeq: 1, searchThreadId: "thread-1" },
              },
            ]}
          >
            <SearchMessageLocationProvider threadId="thread-1">
              {children}
            </SearchMessageLocationProvider>
          </MemoryRouter>
        ),
      });
    const { result } = renderHook(
      () => {
        const timeline = useThreadTimelineController({ threadId: "thread-1" });
        useScrollToSearchedMessage(timeline.timelineRows, "thread-1", {
          hasOlderRows: timeline.hasOlderTimelineRows,
          isLoadingOlderRows: timeline.isLoadingOlderTimelineRows,
          onLoadOlderRows: timeline.loadOlderTimelineRows,
        });
        return timeline;
      },
      { wrapper },
    );
    expect(rowIds(result.current)).toEqual([newestLoadedRow.id]);
    const scrollIntoView = vi.fn();
    const renderedTarget = document.createElement("div");
    renderedTarget.setAttribute("data-timeline-row-id", newestLoadedRow.id);
    renderedTarget.scrollIntoView = scrollIntoView;
    document.body.appendChild(renderedTarget);

    try {
      act(() => {
        queryClient.setQueryData(
          TIMELINE_QUERY_KEY,
          makeTimelineResponse({
            activeThinking: {
              id: "thinking-1",
              startedAt: 2,
              text: "Thinking",
              updatedAt: 2,
            },
            rows: [{ ...newestLoadedRow }],
            maxSeq: 2,
          }),
        );
      });

      await waitFor(() => {
        expect(scrollIntoView).toHaveBeenCalledWith({
          block: "start",
          inline: "nearest",
        });
      });
      expect(result.current.activeThinking?.id).toBe("thinking-1");
    } finally {
      renderedTarget.remove();
    }
  });

  it("restarts auto-load with the new cursor after a discarded older page settles", async () => {
    const { anchor, emitIntersection, sentinel } = installAutoLoadEnvironment();
    const discardedPage = createDeferredPromise<ThreadTimelineResponse>();
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(
        makeTimelineResponse({
          rows: [newestLoadedRow],
          maxSeq: 1,
          timelinePage: {
            historySnapshot: "snapshot-1",
            olderCursor: { anchorId: newestLoadedRow.id, anchorSeq: 1 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      )
      .mockReturnValueOnce(discardedPage.promise)
      .mockReturnValueOnce(new Promise(() => {}));

    const { queryClient, result } = renderControllerWithAutoLoad(anchor);
    await waitFor(() => {
      expect(result.current.timeline.hasOlderTimelineRows).toBe(true);
    });
    act(() => {
      result.current.autoLoad.sentinelRef(sentinel);
    });
    act(emitIntersection);
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
    });
    expect(vi.mocked(sdk.threads.timeline).mock.calls[1]?.[0]).toMatchObject({
      beforeAnchorId: newestLoadedRow.id,
      beforeAnchorSeq: "1",
    });

    act(() => {
      queryClient.setQueryData(
        TIMELINE_QUERY_KEY,
        makeTimelineResponse({
          rows: [contextClearRow],
          maxSeq: 10,
          timelinePage: {
            historySnapshot: "snapshot-2",
            olderCursor: { anchorId: contextClearRow.id, anchorSeq: 10 },
            olderRowsSourceSeqEnd: null,
          },
        }),
      );
    });
    await waitFor(() => {
      expect(rowIds(result.current.timeline)).toEqual([contextClearRow.id]);
    });
    expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);

    await act(async () => {
      discardedPage.resolve(
        makeTimelineResponse({
          rows: [olderPageRow],
          maxSeq: 1,
          timelinePage: { historySnapshot: "snapshot-1" },
        }),
      );
    });

    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(3);
    });
    expect(vi.mocked(sdk.threads.timeline).mock.calls[2]?.[0]).toMatchObject({
      beforeAnchorId: contextClearRow.id,
      beforeAnchorSeq: "10",
      threadId: "thread-1",
    });
    expect(rowIds(result.current.timeline)).toEqual([contextClearRow.id]);
  });
});

describe("useThreadTimelineController commits", () => {
  it.each([
    {
      outcome: "structurally equal data",
      settle: (refetch: DeferredPromise<ThreadTimelineResponse>) =>
        refetch.resolve(
          makeTimelineResponse({ rows: [{ ...newestLoadedRow }], maxSeq: 1 }),
        ),
      commits: 0,
      expectedRowIds: [newestLoadedRow.id],
      activeThinkingId: undefined,
    },
    {
      outcome: "new rows and top-level fields",
      settle: (refetch: DeferredPromise<ThreadTimelineResponse>) =>
        refetch.resolve(
          makeTimelineResponse({
            activeThinking: {
              id: "thinking-1",
              startedAt: 2,
              text: "Considering the request",
              updatedAt: 2,
            },
            maxSeq: 2,
            rows: [newestLoadedRow, realtimeRow],
          }),
        ),
      commits: 1,
      expectedRowIds: [newestLoadedRow.id, realtimeRow.id],
      activeThinkingId: "thinking-1",
    },
    {
      outcome: "an error",
      settle: (refetch: DeferredPromise<ThreadTimelineResponse>) =>
        refetch.reject(makeServerError()),
      commits: 1,
      expectedRowIds: [newestLoadedRow.id],
      activeThinkingId: undefined,
    },
  ])(
    "commits only for changed data when a refetch of a timeline with rows settles with $outcome",
    async ({ activeThinkingId, commits, expectedRowIds, settle }) => {
      const refetch = createDeferredPromise<ThreadTimelineResponse>();
      vi.mocked(sdk.threads.timeline)
        .mockResolvedValueOnce(
          makeTimelineResponse({ rows: [newestLoadedRow], maxSeq: 1 }),
        )
        .mockReturnValueOnce(refetch.promise);
      const { queryClient, wrapper } = createQueryClientTestHarness();
      const view = await renderSettledController(wrapper, [newestLoadedRow.id]);
      const settledCommitCount = view.profilerCommitCount();

      startTimelineRefetch(queryClient);
      await waitFor(() => {
        expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
      });
      await flushQueryNotifications();
      expect(queryClient.isFetching({ queryKey: TIMELINE_QUERY_KEY })).toBe(1);
      expect(view.profilerCommitCount()).toBe(settledCommitCount);

      await act(async () => {
        settle(refetch);
      });
      await flushQueryNotifications();

      expect(queryClient.isFetching({ queryKey: TIMELINE_QUERY_KEY })).toBe(0);
      expect(view.profilerCommitCount() - settledCommitCount).toBe(commits);
      expect(rowIds(view.latest())).toEqual(expectedRowIds);
      expect(view.latest().activeThinking?.id).toBe(activeThinkingId);
    },
  );

  it("keeps a loaded empty timeline out of the loading state while it refetches", async () => {
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(makeTimelineResponse())
      .mockReturnValueOnce(new Promise(() => {}));
    const { queryClient, wrapper } = createQueryClientTestHarness();
    const view = await renderSettledController(wrapper, []);

    startTimelineRefetch(queryClient);
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
    });
    await flushQueryNotifications();

    expect(queryClient.isFetching({ queryKey: TIMELINE_QUERY_KEY })).toBe(1);
    expect(view.latest().timelineLoading).toBe(false);
  });

  it("reads only query result properties covered by the notify lists", async () => {
    vi.mocked(sdk.threads.timeline).mockResolvedValueOnce(
      makeTimelineResponse({ rows: [newestLoadedRow], maxSeq: 1 }),
    );
    const { wrapper } = createQueryClientTestHarness();
    await renderSettledController(wrapper, [newestLoadedRow.id]);

    const coveredKeys = new Set<PropertyKey>([
      ...TIMELINE_CONTROLLER_PROPS_WITHOUT_ROWS,
      "refetch",
    ]);
    expect(readTimelineQueryResultKeys.size).toBeGreaterThan(0);
    expect(
      [...readTimelineQueryResultKeys].filter((key) => !coveredKeys.has(key)),
    ).toEqual([]);
  });

  it("commits once on mount with a cached timeline and shows its rows and cursor", async () => {
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({
        maxSeq: 1,
        rows: [newestLoadedRow],
        timelinePage: {
          olderCursor: { anchorId: newestLoadedRow.id, anchorSeq: 1 },
          historySnapshot: "snapshot-1",
          olderRowsSourceSeqEnd: null,
        },
      }),
    );

    const view = renderProfiledController(wrapper);
    await flushQueryNotifications();

    expect(sdk.threads.timeline).not.toHaveBeenCalled();
    expect(view.profilerCommitCount()).toBe(1);
    expect(rowIds(view.latest())).toEqual([newestLoadedRow.id]);
    expect(view.latest().hasOlderTimelineRows).toBe(true);
  });
  it("reports catching up while the mount refetch of a timeline with new events runs", async () => {
    const refetch = createDeferredPromise<ThreadTimelineResponse>();
    vi.mocked(sdk.threads.timeline).mockReturnValueOnce(refetch.promise);
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    markTimelineHasNewEvents(queryClient);

    const view = renderProfiledController(wrapper);
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(1);
    });
    expect(view.latest().isCatchingUpTimeline).toBe(true);
    expect(view.latest().timelineLoading).toBe(false);
    expect(rowIds(view.latest())).toEqual([newestLoadedRow.id]);

    await act(async () => {
      refetch.resolve(
        makeTimelineResponse({
          maxSeq: 2,
          rows: [newestLoadedRow, realtimeRow],
        }),
      );
    });
    await waitFor(() => {
      expect(view.latest().isCatchingUpTimeline).toBe(false);
    });
    expect(rowIds(view.latest())).toEqual([newestLoadedRow.id, realtimeRow.id]);

    vi.mocked(sdk.threads.timeline).mockReturnValueOnce(new Promise(() => {}));
    startTimelineRefetch(queryClient);
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
    });
    await flushQueryNotifications();
    expect(view.latest().isCatchingUpTimeline).toBe(false);
  });
  it("reports catching up when returning to a thread before another thread's fetch settles", async () => {
    const otherThreadFetch = createDeferredPromise<ThreadTimelineResponse>();
    const returnFetch = createDeferredPromise<ThreadTimelineResponse>();
    vi.mocked(sdk.threads.timeline)
      .mockResolvedValueOnce(
        makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
      )
      .mockReturnValueOnce(otherThreadFetch.promise)
      .mockReturnValueOnce(returnFetch.promise);
    const { queryClient, wrapper } = createQueryClientTestHarness();
    const { result, rerender } = renderHook(
      ({ threadId }: { threadId: string }) =>
        useThreadTimelineController({ threadId }),
      { initialProps: { threadId: "thread-1" }, wrapper },
    );
    await waitFor(() => {
      expect(rowIds(result.current)).toEqual([newestLoadedRow.id]);
    });

    rerender({ threadId: "thread-2" });
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(2);
    });
    act(() => {
      queryClient.setQueryData(
        TIMELINE_QUERY_KEY,
        makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
      );
      markTimelineHasNewEvents(queryClient);
    });

    rerender({ threadId: "thread-1" });
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(3);
    });
    expect(result.current.isCatchingUpTimeline).toBe(true);

    await act(async () => {
      returnFetch.resolve(
        makeTimelineResponse({
          maxSeq: 2,
          rows: [newestLoadedRow, realtimeRow],
        }),
      );
    });
    await waitFor(() => {
      expect(result.current.isCatchingUpTimeline).toBe(false);
    });
  });

  it("reports catching up when a hidden timeline with new events is enabled", async () => {
    const refetch = createDeferredPromise<ThreadTimelineResponse>();
    vi.mocked(sdk.threads.timeline).mockReturnValueOnce(refetch.promise);
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    markTimelineHasNewEvents(queryClient);
    const { result, rerender } = renderHook(
      ({ enabled }: { enabled: boolean }) =>
        useThreadTimelineController({ enabled, threadId: "thread-1" }),
      { initialProps: { enabled: false }, wrapper },
    );
    expect(result.current.isCatchingUpTimeline).toBe(false);

    rerender({ enabled: true });
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(1);
    });
    expect(result.current.isCatchingUpTimeline).toBe(true);
  });
  it("does not report catching up when a cached timeline is only stale by age", async () => {
    vi.mocked(sdk.threads.timeline).mockReturnValueOnce(new Promise(() => {}));
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
      { updatedAt: 0 },
    );

    const view = renderProfiledController(wrapper);
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(1);
    });
    await flushQueryNotifications();
    expect(view.latest().isCatchingUpTimeline).toBe(false);
  });
  it("does not report catching up for a timeline invalidated without unseen events", async () => {
    vi.mocked(sdk.threads.timeline).mockReturnValueOnce(new Promise(() => {}));
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    void queryClient.invalidateQueries({
      queryKey: TIMELINE_QUERY_KEY,
      refetchType: "none",
    });

    const view = renderProfiledController(wrapper);
    await waitFor(() => {
      expect(sdk.threads.timeline).toHaveBeenCalledTimes(1);
    });
    await flushQueryNotifications();
    expect(view.latest().isCatchingUpTimeline).toBe(false);
  });

  it("keeps a timeline stale when a completed fetch does not include the known event", async () => {
    vi.mocked(sdk.threads.timeline).mockResolvedValueOnce(
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    markTimelineHasNewEvents(queryClient);
    const view = renderProfiledController(wrapper);
    await waitFor(() => expect(queryClient.isFetching()).toBe(0));
    expect(view.latest().isCatchingUpTimeline).toBe(true);
    expect(hasThreadTimelineUnseenEvents(queryClient, "thread-1")).toBe(true);
  });

  it("clears unseen events once the catch-up fetch succeeds", async () => {
    vi.mocked(sdk.threads.timeline).mockResolvedValueOnce(
      makeTimelineResponse({
        maxSeq: 2,
        rows: [newestLoadedRow, realtimeRow],
      }),
    );
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    markTimelineHasNewEvents(queryClient);

    const view = renderProfiledController(wrapper);
    await waitFor(() => {
      expect(rowIds(view.latest())).toEqual([
        newestLoadedRow.id,
        realtimeRow.id,
      ]);
    });
    expect(hasThreadTimelineUnseenEvents(queryClient, "thread-1")).toBe(false);
  });

  it("stops catching up when a push without row changes covers the unseen events", async () => {
    vi.mocked(sdk.threads.timeline).mockResolvedValueOnce(
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    const view = await renderSettledController(wrapper, [newestLoadedRow.id]);

    act(() => {
      markThreadTimelineUnseenEvents(queryClient, "thread-1", 3);
      queryClient.setQueryData(
        TIMELINE_QUERY_KEY,
        makeTimelineResponse({
          maxSeq: 2,
          rows: [newestLoadedRow, realtimeRow],
        }),
      );
    });
    await flushQueryNotifications();
    expect(view.latest().isCatchingUpTimeline).toBe(true);

    act(() => {
      applyThreadTimelineSignal(queryClient, {
        type: "thread-timeline",
        target: {
          kind: "thread-timeline",
          threadId: "thread-1",
          segmentLimit: null,
          deferContent: true,
        },
        timeline: makeTimelineResponse({
          maxSeq: 3,
          rows: [newestLoadedRow, realtimeRow],
        }),
      });
    });
    await flushQueryNotifications();
    expect(view.latest().isCatchingUpTimeline).toBe(false);
  });

  it("starts catching up when unseen events arrive without a timeline change", async () => {
    vi.mocked(sdk.threads.timeline).mockResolvedValueOnce(
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    const { queryClient, wrapper } = createQueryClientTestHarness();
    queryClient.setQueryData(
      TIMELINE_QUERY_KEY,
      makeTimelineResponse({ maxSeq: 1, rows: [newestLoadedRow] }),
    );
    const view = await renderSettledController(wrapper, [newestLoadedRow.id]);

    act(() => {
      markThreadTimelineUnseenEvents(queryClient, "thread-1", 2);
    });
    expect(view.latest().isCatchingUpTimeline).toBe(true);
  });
});

Actual browser evidence

The harness imports the unchanged real hook and toast implementation, seeds the exact timeline query key, and exposes a button that completes a deferred query. Its border and row text are harness presentation; the visibility style directly consumes the same hook result as the real timeline renderer. No screenshot or test output is fabricated.

Before the simulated refresh: one cached row, query in flight, reveal pending false
Before completing refresh: cached row is visible and reveal has already been treated as missing.
After completing refresh: query complete, two rows loaded, reveal pending true, timeline blank
After clicking the refresh button: two rows are loaded, but pending=true leaves the bordered timeline blank. The button remains focused from the click.
Browser DOM probe after refresh:
{ visibility: 'hidden', rows: 2 }

5. Root cause

Target classification, pending calculation and handled guard:

  const loadedRange = useMemo(() => getRowsSeqRange(rows), [rows]);
  const targetIsOlderThanLoadedRows =
    loadedRange !== null && targetSeq !== null && targetSeq < loadedRange.max;
  const targetIsMissing =
    targetLeafRow === null &&
    loadedRange !== null &&
    (targetMatch === "message" || targetIsOlderThanLoadedRows);
  const canLoadOlderTarget = targetIsOlderThanLoadedRows && hasOlderRows;
  const isInitialRevealPending =
    reportsMissingTarget &&
    initialLocationKey !== null &&
    initialLocationKey === targetLocationKey &&
    settledLocationKey !== initialLocationKey &&
    !(targetIsMissing && !canLoadOlderTarget && !isLoadingOlderRows);

  useEffect(() => {
    if (
      targetLocationKey === null ||
      targetMatch === null ||
      targetSeq === null ||
      handledKeyRef.current === targetLocationKey
    ) {

For an exact message match, the existence of any loaded range is sufficient to classify an absent row as missing; no latest-page refresh state is consulted. The terminal effect then sets only the handled ref:

Missing-target terminal branch:

      if (
        reportsMissingTarget &&
        targetIsMissing &&
        !canLoadOlderTarget &&
        !isLoadingOlderRows
      ) {
        handledKeyRef.current = targetLocationKey;
        appToast.message("Message not found", {
          description:
            "It may have been removed by an edit or hidden by a context clear.",
        });
      }

When the query later supplies the row, targetIsMissing becomes false and removes the temporary exception from isInitialRevealPending. settledLocationKey remains null, while handledKeyRef stops the effect from revealing the row. The real renderer applies visibility:hidden whenever this pending result is true. This is a navigation lifecycle inconsistency, not missing server data or a virtualizer dropping the row.

6. Proposed fix and verification

Subscribe to fetching state for the exact threadTimeline query only when this hook reports a navigation target. Defer missing-target resolution until the refresh finishes. Schedule the terminal missing notification on a cancellable animation frame so committed row/query notifications can reconcile; guard it against navigation changes. Mark that terminal location settled as well as handled, keeping late row updates from hiding the list again. Existing older-history loading and successful reveal behavior remain intact.

The implementation changes one existing timeline hook and its existing regression test file: 2 files, 140 changed text lines (134 additions + 6 deletions). No dependency, generated file, stored data, public API, daemon protocol, security, or product-policy change is involved.

After fix:
Test Files  4 passed (4)
Tests  90 passed (90)

pnpm exec turbo run typecheck lint --filter=@bb/app
Tasks: 7 successful, 7 total
Found 0 warnings and 0 errors.

pnpm exec oxfmt --check [the two changed files]
All matched files use the correct format.
git diff --check
(exit 0)

The four executed suites own the controller/navigation lifecycle, timeline actions, offscreen/windowed reveal and timeline surface controls. The new tests fail on the base for the intended pending-state reason and pass with the fix.

7. Verification: second clean checkout

Created a detached temporary worktree at the same full SHA with clean production code, installed from the frozen lockfile, built SDK prerequisites, and copied only our regression test file. The same agent repeated the exact Turbo test command there. The result was again 2 failed | 32 passed (34), with both failures at pending=false assertions after the target had arrived. This corroborates the final mechanism without relying on the reporter's scripts or bundled-code interpretation.

Verification correction: the refresh case explicitly sets staleTime=0. An early exploratory draft inherited the app's two-second fresh-cache default and did not start its requested refresh; that draft's result was discarded. Both linked final pre-fix logs use the corrected test and fail for the intended reveal-state defect.

First trusted-base run · Second clean run · Post-fix suites · Typecheck and lint

8. Related issues and pull requests

No open PR linked to #8021 was present in issue cross-reference metadata or the repository's open-PR search when this investigation and fix began. Nearby thread issues were reviewed for label conventions; no other issue's behavior is claimed fixed.

9. Appendix and limits

Issue content was treated solely as untrusted claims. Its proposed changes and commands were not executed or copied. Reproduction and repair were designed from trusted main source. The SDK prerequisite build repaired an initial full-build failure caused by missing generated SDK runtime entrypoints; the subsequent app build completed. No unrelated code was changed.

Relevant command sequence:
git fetch https://github.com/get-bb/bb.git main:refs/remotes/origin/main
git switch -c slopcop/issue-8021 origin/main
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build
pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk
pnpm exec turbo run build --filter=@bb/app
git worktree add --detach [fresh temporary checkout] 796cdcc0f4bf8a55e23664035c54e8db6fe9d272
[repeat frozen install, SDK prerequisites and pre-fix regression command]
pnpm exec turbo run test --filter=@bb/app -- src/components/thread/timeline/useThreadTimelineController.test.tsx src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx src/components/thread/timeline/ThreadTimelineRows.windowing.test.tsx src/components/thread/timeline/ThreadTimelineSurface.test.tsx
pnpm exec turbo run typecheck lint --filter=@bb/app
pnpm exec oxfmt --check apps/app/src/components/thread/timeline/useScrollToSearchedMessage.ts apps/app/src/components/thread/timeline/useThreadTimelineController.test.tsx
git diff --check
git diff --numstat origin/main

Limits: no complete installed-app journey, mobile Safari, desktop app packaging, real provider process, or exact 100 ms timing assertion. The live browser artifact proves the real source hook's visibility state; integration tests prove its actual controller/query behavior. No independent reviewer or workflow was used.