fix(feed): an optimistic write outlives only the server answers older than it
A reset wrote a position mask over the cached list, so a replay's saved position stayed hidden: a reopen resumed at 0 and its first checkpoint wrote over the progress. The reset now writes 0 into the cache, where the player's closing patch writes the next one. Overrides carry their write order, and a landing refetch drops only those written before it set out. The player session ends after the modal unmounts, so a clip auto-marked watched as it closes still refetches the list.
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// The feed's optimistic layer: a card shows what was just written to it until the server's own answer
|
||||
// lands. Which answers count is the rule pinned here: a refetch that LANDS (for what was written
|
||||
// before it set out), a filter change; never an append of the next page. A mark made while a refetch
|
||||
// was in flight is newer than its answer, and dropping it put a card marked watched back into an
|
||||
// Unwatched view. The grid is a stub that shows what Feed hands it.
|
||||
import { describe, it, expect, vi, beforeAll, afterEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor, cleanup, act } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("react-i18next")>()),
|
||||
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "en" } }),
|
||||
}));
|
||||
vi.mock("./wizardContext", () => ({ useWizard: () => ({ openWizard: vi.fn() }) }));
|
||||
vi.mock("./VirtualFeed", () => ({
|
||||
default: ({
|
||||
items,
|
||||
onState,
|
||||
fetchNextPage,
|
||||
}: {
|
||||
items: { id: string; status: string }[];
|
||||
onState: (id: string, status: string) => void;
|
||||
fetchNextPage: (o: object) => unknown;
|
||||
}) => (
|
||||
<ol aria-label="results">
|
||||
{items.map((v) => (
|
||||
<li key={v.id}>
|
||||
<span>{`${v.id}:${v.status}`}</span>
|
||||
<button onClick={() => onState(v.id, "watched")}>watch {v.id}</button>
|
||||
</li>
|
||||
))}
|
||||
<button onClick={() => void fetchNextPage({})}>more</button>
|
||||
</ol>
|
||||
),
|
||||
}));
|
||||
|
||||
import Feed from "./Feed";
|
||||
import { api, DEFAULT_TAG_MODES, type FeedFilters, type Video } from "../lib/api";
|
||||
import { qk } from "../lib/queryKeys";
|
||||
|
||||
beforeAll(() => {
|
||||
class Stub {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
takeRecords() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
globalThis.ResizeObserver ??= Stub as unknown as typeof ResizeObserver;
|
||||
globalThis.IntersectionObserver ??= Stub as unknown as typeof IntersectionObserver;
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const FILTERS: FeedFilters = {
|
||||
tags: [],
|
||||
tagModes: DEFAULT_TAG_MODES,
|
||||
channelIds: [],
|
||||
q: "",
|
||||
sort: "newest",
|
||||
scope: "my",
|
||||
includeNormal: true,
|
||||
includeShorts: false,
|
||||
includeLive: false,
|
||||
show: "all",
|
||||
};
|
||||
|
||||
const video = (id: string) =>
|
||||
({
|
||||
id,
|
||||
title: id,
|
||||
channel_id: "UCx",
|
||||
channel_title: "Channel",
|
||||
status: "new",
|
||||
position_seconds: 0,
|
||||
duration_seconds: 600,
|
||||
published_at: "2026-01-01T00:00:00Z",
|
||||
watch_url: `https://www.youtube.com/watch?v=${id}`,
|
||||
}) as unknown as Video;
|
||||
|
||||
// The server never takes the mark in these tests: whatever a list shows as "watched" is the override.
|
||||
const page = (ids: string[], next: string | null = null) =>
|
||||
({ items: ids.map(video), next_cursor: next }) as never;
|
||||
|
||||
function mount(feed: ReturnType<typeof vi.fn>) {
|
||||
vi.spyOn(api, "feed").mockImplementation(feed as never);
|
||||
vi.spyOn(api, "feedSummary").mockResolvedValue({ count: 1, facets: {} } as never);
|
||||
vi.spyOn(api, "setState").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
qc.setQueryData(qk.me(), { id: 1, can_write: true, prefs: {} });
|
||||
const ui = (filters: FeedFilters) => (
|
||||
<QueryClientProvider client={qc}>
|
||||
<Feed
|
||||
filters={filters}
|
||||
setFilters={() => {}}
|
||||
view="cards"
|
||||
setView={() => {}}
|
||||
canRead
|
||||
ytSearch={null}
|
||||
onYtSearch={() => {}}
|
||||
onExitYtSearch={() => {}}
|
||||
/>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
const r = render(ui(FILTERS));
|
||||
return { qc, rerender: (f: FeedFilters) => r.rerender(ui(f)) };
|
||||
}
|
||||
|
||||
const settle = () => act(() => new Promise((r) => setTimeout(r, 20)));
|
||||
|
||||
describe("Feed — optimistic overrides", () => {
|
||||
it("give way to a refetch that lands after them", async () => {
|
||||
let answer: (v: unknown) => void = () => {};
|
||||
const feed = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(page(["v1"]))
|
||||
.mockImplementationOnce(() => new Promise((r) => (answer = r)));
|
||||
const { qc } = mount(feed);
|
||||
fireEvent.click(await screen.findByText("watch v1"));
|
||||
await screen.findByText("v1:watched");
|
||||
act(() => void qc.invalidateQueries({ queryKey: qk.feed() }));
|
||||
await waitFor(() => expect(feed).toHaveBeenCalledTimes(2));
|
||||
await settle();
|
||||
await act(async () => answer(page(["v1"])));
|
||||
await waitFor(() => expect(screen.getByText("v1:new")).toBeTruthy());
|
||||
});
|
||||
|
||||
it("keep a mark made while the refetch was in flight", async () => {
|
||||
let answer: (v: unknown) => void = () => {};
|
||||
const feed = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(page(["v1"]))
|
||||
.mockImplementationOnce(() => new Promise((r) => (answer = r)));
|
||||
const { qc } = mount(feed);
|
||||
await screen.findByText("v1:new");
|
||||
act(() => void qc.invalidateQueries({ queryKey: qk.feed() }));
|
||||
await waitFor(() => expect(feed).toHaveBeenCalledTimes(2));
|
||||
await settle();
|
||||
fireEvent.click(screen.getByText("watch v1"));
|
||||
await screen.findByText("v1:watched");
|
||||
// The answer the server gave before it heard of the mark.
|
||||
await act(async () => answer(page(["v1"])));
|
||||
await settle();
|
||||
expect(screen.getByText("v1:watched")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("survive an append of the next page", async () => {
|
||||
let answer: (v: unknown) => void = () => {};
|
||||
const feed = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(page(["v1"], "c1"))
|
||||
.mockImplementationOnce(() => new Promise((r) => (answer = r)));
|
||||
mount(feed);
|
||||
fireEvent.click(await screen.findByText("watch v1"));
|
||||
await screen.findByText("v1:watched");
|
||||
fireEvent.click(screen.getByText("more"));
|
||||
await waitFor(() => expect(feed).toHaveBeenCalledTimes(2));
|
||||
await settle();
|
||||
await act(async () => answer(page(["v2"])));
|
||||
await screen.findByText("v2:new");
|
||||
await settle();
|
||||
expect(screen.getByText("v1:watched")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("are dropped by a change of the filters", async () => {
|
||||
const { rerender } = mount(vi.fn().mockResolvedValue(page(["v1"])));
|
||||
fireEvent.click(await screen.findByText("watch v1"));
|
||||
await screen.findByText("v1:watched");
|
||||
rerender({ ...FILTERS });
|
||||
await waitFor(() => expect(screen.getByText("v1:new")).toBeTruthy());
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user