Files
fusion/packages/dashboard/app/hooks/__tests__/useLiveTranscript.resync.test.ts
gsxdsm f26cbedf4f fix(dashboard): close the code-review findings on the mobile tab-discard work
An 11-reviewer pass over f157bf7460..f5163d8351 found defects in the mobile
tab-discard change set itself. This fixes them.

Silent data loss (the recurring defect class):
- AgentDetailView reconnect refetched limit:100 and replaced wholesale, so 380
  displayed lines vanished with no "Load older" and no indicator; it now
  reconciles through the shared logStreamReconcile helper.
- useActivityLog.loadMore past the cap discarded the page it had just fetched
  while advancing the cursor and leaving hasMore true, so the feed silently
  stopped paginating behind a live-looking button.
- useAgentLogs: loadMore and resyncFromServer had no mutual exclusion, a
  no-overlap resync discarded explicitly paged-back history, a resync outliving
  the reconnect delay left an unmarked gap, and the live-tail trim could evict
  the gap marker itself.
- useLiveTranscript's resync overwrote live entries that raced the refetch.

The premise itself was not fully delivered:
- useProjects, useNodes, and useMeshState never called clearInterval, so they
  polled the whole time the tab was hidden. useProjects is mounted for the
  entire session, so the page never went idle -- the primary mechanism this
  work depends on. All three now use the shared visibility gate.
- sse-bus fired onReconnect twice per reconnect cycle and fanned out ~28
  subscribers in one tick, against a ~6-connection-per-origin cap on a waking
  radio. The successful open is now the single authority, and the fan-out uses
  the same exported stagger primitive as the polling path rather than a second
  copy of the slot formula.
- A channel first subscribed during the hidden window opened a live EventSource
  and keepalive; suspension is now a module-level condition openChannel
  consults, and a channel opened inside the grace window re-arms it.

Credentials and correctness:
- The service worker persisted every GET /api/* to durable Cache Storage,
  including /api/settings with daemonToken, githubAuthToken, gitlabAuthToken
  and ntfyAccessToken in plaintext, with no exclusion and no purge path --
  "Clear all cached data" only walked localStorage. Now gated, bounded, and
  genuinely purgeable.
- useTasks cleared its own snapshot when the mount revalidation failed on a
  waking radio, so the board blanked and the next restore was empty too.
  Suspension-class failures no longer destroy the cache.
- A single-row SSE update reset lastFetchTimeMs to now while an hours-old
  hydrated snapshot was on screen, re-marking every in-progress card stuck.
- ListView's "Select all visible tasks" acted on the full filtered set while
  only 50 rows rendered, so a bulk delete reached rows the operator could not
  see. Column's search window reset keyed on a boolean, so refining a query
  kept the expanded window.

Tests that could not fail:
- App.test.tsx mocked TerminalModal as isOpen ? <div/> : null, making the
  unmount-on-close invariant unobservable; MockEventSource kept its listeners
  after close(), so cases passed with their onReconnect handlers deleted.
- The SSE resync ratchet scanned only hooks/, exempting ~13 component call
  sites -- the exact regression it exists to prevent.
- MissionControlPanel's bespoke poll and the xterm scrollback constants and
  WebGL disposal had no coverage at all.

Verified: tsc -p tsconfig.app.json clean, pnpm lint clean, pnpm
check:changesets clean, 877 tests passing across 36 scoped files.
Known unrelated red: MailboxView.test.tsx's FN-8407 CSS guard fails at HEAD
too -- this diff adds no @media rule and no .mailbox-view--mobile selector,
the only two things that assertion inspects. Left alone deliberately.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 11:17:52 -07:00

177 lines
5.6 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderHook, act } from "@testing-library/react";
/*
FNXC:TaskTranscript 2026-07-26-20:05:
Reconnect-resync coverage for the live transcript. `/api/tasks/:id/logs/stream` replays nothing, so
the refetched page is the ONLY recovery path — and a page fetched while the live tail is still
running is a snapshot from before those lines. The invariant: a resync may not delete an entry that
arrived during its own fetch, and may not render an entry twice when it is in both the page and the
stream.
*/
const { sseOptions } = vi.hoisted(() => ({
sseOptions: {
current: null as null | {
onReconnect?: () => void;
events: Record<string, (e: MessageEvent) => void>;
},
},
}));
vi.mock("../../sse-bus", () => ({
subscribeSse: vi.fn((_url: string, opts: never) => {
sseOptions.current = opts;
return () => {};
}),
}));
vi.mock("../../api", () => ({
fetchAgentLogsWithMeta: vi.fn(),
}));
import { useLiveTranscript } from "../useLiveTranscript";
import * as apiModule from "../../api";
const mockFetchAgentLogsWithMeta = vi.mocked(apiModule.fetchAgentLogsWithMeta);
function serverEntry(text: string, timestamp: string) {
return { taskId: "FN-001", type: "text" as const, text, timestamp };
}
function emitLog(text: string, timestamp: string) {
sseOptions.current?.events["agent:log"]({
data: JSON.stringify({ type: "text", text, timestamp }),
} as MessageEvent);
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
describe("useLiveTranscript reconnect resync", () => {
beforeEach(() => {
vi.useFakeTimers();
sseOptions.current = null;
mockFetchAgentLogsWithMeta.mockReset();
});
afterEach(() => {
vi.useRealTimers();
});
it("replaces the buffer with the persisted tail on reconnect (newest first)", async () => {
mockFetchAgentLogsWithMeta.mockResolvedValue({
entries: [serverEntry("older", "2026-01-01T00:00:01Z"), serverEntry("newer", "2026-01-01T00:00:02Z")],
total: 2,
hasMore: false,
});
const { result } = renderHook(() => useLiveTranscript("FN-001"));
await act(async () => {
sseOptions.current?.onReconnect?.();
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.entries.map((entry) => entry.text)).toEqual(["newer", "older"]);
});
it("keeps live entries that raced the resync fetch", async () => {
const page = deferred<{ entries: ReturnType<typeof serverEntry>[]; total: number; hasMore: boolean }>();
mockFetchAgentLogsWithMeta.mockReturnValue(page.promise as never);
const { result } = renderHook(() => useLiveTranscript("FN-001"));
act(() => {
sseOptions.current?.onReconnect?.();
});
// Streams in WHILE the authoritative page is still in flight. The page below predates it.
act(() => {
emitLog("raced-live-entry", "2026-01-01T00:00:09Z");
});
await act(async () => {
page.resolve({
entries: [serverEntry("persisted-1", "2026-01-01T00:00:01Z"), serverEntry("persisted-2", "2026-01-01T00:00:02Z")],
total: 2,
hasMore: false,
});
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.entries.map((entry) => entry.text)).toEqual([
"raced-live-entry",
"persisted-2",
"persisted-1",
]);
});
it("renders an entry once when it is in both the page and the live stream", async () => {
const page = deferred<{ entries: ReturnType<typeof serverEntry>[]; total: number; hasMore: boolean }>();
mockFetchAgentLogsWithMeta.mockReturnValue(page.promise as never);
const { result } = renderHook(() => useLiveTranscript("FN-001"));
act(() => {
sseOptions.current?.onReconnect?.();
});
act(() => {
emitLog("persisted-2", "2026-01-01T00:00:02Z");
});
await act(async () => {
page.resolve({
entries: [serverEntry("persisted-1", "2026-01-01T00:00:01Z"), serverEntry("persisted-2", "2026-01-01T00:00:02Z")],
total: 2,
hasMore: false,
});
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.entries.map((entry) => entry.text)).toEqual(["persisted-2", "persisted-1"]);
});
it("flushes parked entries and retries when the resync fetch fails", async () => {
const failing = deferred<never>();
mockFetchAgentLogsWithMeta.mockReturnValueOnce(failing.promise as never);
mockFetchAgentLogsWithMeta.mockResolvedValue({
entries: [serverEntry("persisted-1", "2026-01-01T00:00:01Z")],
total: 1,
hasMore: false,
});
const { result } = renderHook(() => useLiveTranscript("FN-001"));
act(() => {
sseOptions.current?.onReconnect?.();
});
act(() => {
emitLog("live-during-failed-fetch", "2026-01-01T00:00:09Z");
});
await act(async () => {
failing.reject(new Error("offline"));
await vi.advanceTimersByTimeAsync(0);
});
// The parked entry is rendered, not dropped, even though the page never arrived.
expect(result.current.entries.map((entry) => entry.text)).toEqual(["live-during-failed-fetch"]);
expect(mockFetchAgentLogsWithMeta).toHaveBeenCalledTimes(1);
// Bounded ladder retries without waiting for another reconnect.
await act(async () => {
await vi.advanceTimersByTimeAsync(5_000);
});
expect(mockFetchAgentLogsWithMeta).toHaveBeenCalledTimes(2);
expect(result.current.entries.map((entry) => entry.text)).toEqual(["persisted-1"]);
});
});