mirror of
https://github.com/block/buzz.git
synced 2026-10-30 22:11:36 +00:00
Prepared by Brain on Wes’s behalf. ## Summary Reduce startup request amplification and let quota-refused background work recover without changing relay quotas or bypassing the existing Send gate. - Coalesce nest regeneration into one worker plus the latest pending generation. Keep the stale-write fence; bound the archive read so an old workspace cannot strand newer work. - Claim pending channel subscriptions before awaiting setup; cancel removed/unmounted entries and preserve still-owned subscriptions across reconnect handoff. - Recheck extended cooldown deadlines before retry dispatch; distinguish an explicit zero-second hint from a missing hint. - Recover native finite/unread queries within their original caller deadline and a three-retry budget, preserving verified unique events, complete filters and terminal errors. - Pace renderer initial/live-CLOSED REQs at one per 250ms: visible channel and explicitly interactive TTS/read-state/observer owners first, then live-only auxiliaries, then background history. Publication and finite queries bypass this queue. Reconnect replay now promotes explicit interactive owners alongside the visible channel with stable registration-order ties; its existing capped batches and cooldown remain intact. **Scope at `867495426`:** 39 source/test files, including 15 production files (+665/-235) and 24 test/fixture files. The diagnostic recorder, HTTP instrumentation, trace launcher and raw captures are deliberately excluded. No profile reset, grouping, quota increase or new global scheduler. ## Before / after evidence These are observations from instrumented, human-operated development Tauri/Vite runs against a production relay, plus explicitly identified controlled regressions—not a packaged-release startup benchmark. | Measurement | Before | After | Evidence boundary | | --- | --- | --- | --- | | Archive snapshot requests (kind 13535) | 290 | 3 | Recorder-only baseline → nest-only intermediate candidate; unequal 67.436s / 39.273s captures and hydration differences | | Archive responses: HTTP 200 / 429 | 277 / 13 | 3 / 0 | Same baseline/nest-only captures; not a claim that all quota pressure disappeared | | Successful archive responses’ advertised content-length sum | 21,208,505 bytes | 229,695 bytes | Header values, not actual transferred bytes | | 154-channel StrictMode replay | 308 REQs | 154 REQs | Controlled real React hook → real session → mocked Tauri transport regression | | Add one channel while 154 setups are pending | 309 REQs | 155 REQs | Same production-boundary regression; ordinary mount remains 154 → 154 | | Broad renderer request burst / spacing | 110 broad REQs within 10.766ms in pre-drain capture | 250.061ms minimum / 252.131ms median between broad REQ writes in final longer capture | Different attended runs; pacing rather than a universal request-rate cap | | Native unread query outcomes | Baseline: 8 EOSE / 146 quota CLOSED out of 154 queries | Final longer run: all 156 observed queries reach EOSE; eight refused queries each recover after two refusals | Different runs/workloads; query completion, not badge rendering | ### Timing metrics | Observation | Measured value | | --- | ---: | | Baseline’s two accepted chat EVENT socket writes → positive OK | 173.340ms / 85.556ms | | Nest-only intermediate candidate’s two accepted writes → positive OK | 277.854ms / 78.775ms | | Final candidate, short run, accepted chat writes → positive OK | 80.636ms / 77.506ms | | Final candidate, longer run, accepted chat writes → positive OK | 120.712ms / 86.895ms | | Last initial EOSE among 163 observed broad channel registrations, longer run | 64.550s after trace start | | Last EOSE among 156 observed native unread queries, longer run | 73.972s after trace start | | Native retry waits after 3s then 0s hints, longer run | 3000.7–3002.8ms, then 2001.5–2002.6ms | | Renderer finite-query retry after a 2s hint, longer run | 2061.365ms | Both Sends in each final run were accepted, with no recorded negative OK. Every quota-refused query in the longer run subsequently completed the same query. Its two Sends happened early (17.878s and 21.655s), not near the end. These small samples do not support a percentage latency improvement. **Tradeoffs and limits** - 296 background subscriptions imply about 74s of paced registration before extra cooldowns/high-priority work. The longer capture observed 163 registrations; it did not independently enumerate the expected membership set or record a queue-empty marker. - This is not a global 4-REQ/s cap: finite queries, native requests and reconnect replay are outside the drain and still share relay quota. Quota refusals recover rather than disappear. - Socket-write → OK starts after composer submission and any publisher gate wait. No click-to-visible, launch-to-usable or badge-paint latency is claimed. - Native EOSE is not proof of command return, classification, React state application or visible unread badges. Existing per-channel kinds, since floors, limits, h-less routing, unread lease/scope guard and eight-query concurrency remain intact. - The attended measurements belong to the instrumented candidate, not a fresh release run of this fixes-only commit. At the initial packaging checkpoint (`1bf3d060`), eighteen of twenty files were byte-identical; the other two removed diagnostic gate calls and isolated the nest test’s temporary paths. The subsequent interactive priority/reconnect and readiness fixes have controlled hook/session/browser evidence, not another attended voice/performance run. ### Evidence provenance (captures retained locally, not uploaded) | Capture | SHA-256 | | --- | --- | | Baseline `STARTUP_20260921T194814Z_98811.jsonl` | `f4f0a89ad9aea91084bd6a7432510488166de4cbc906600d88c26d557f380994` | | Nest-only `STARTUP_20260921T202610Z_28642.jsonl` | `ce517b02a3f717c36d96b36bb8616e8fa80b03b12b356bacfd40475925ea3f3e` | | Final short `STARTUP_20260922T013628Z_13506.jsonl` | `bfea6f3cf80cd7b7e4e676632a3df2f16271fade5bfa0edec72b7bcbbe7839ff` | | Final longer `STARTUP_20260922T014637Z_15846.jsonl` | `f4abece613d108c4c2fe3cb808e633a0486bdc9993ca92323822dc00c3fae6ec` | Final instrumented build fingerprint: `b0b4fc27d793c3e643f4e10289b5afdb4620ee2e13a8b33fa0595dd3417fd5ca`. All observed dropped-record counters in these final captures were zero. Source manifests and offline correlation analyses are retained locally; no raw captures, profile data or agent sessions are part of this PR. ## Validation Current head: `86749542657a60abdfe82eed5cc576d3e162fe5d`, based on `77729abfb692b25a0f4ec4a69add86af2e32c0dd`. Review follow-ups: - `8842dbd8`: explicit interactive TTS admission using the existing main-window owner, independent of companion/timeline selection. Real-hook/session/IPC coverage with 296 cold owners proves initial and CLOSED priority, unchanged filters/cooldown/pacing, background progress and deduplicated speech. - `8cb088106`: reconnect preserves interactive priority even with no visible channel. Stable ordering among foreground ties; real hook/session reconnect regressions cover cooldown, capped batching, all 297 owners, deduplication and unmount cancellation. Independent reviewer mutation restored the prior replay implementation, failed both reconnect rows, then passed the restored candidate. - `68e76d7c`: read-state and observer reuse interactive priority. Stop and ModelPicker wait on the existing observer owner inside send callbacks, after installing result listeners/deadlines. No new owner, timer or scheduler; inherited CLOSED/fallback/error semantics remain, rather than a new strict EOSE guarantee. The real Stop panel browser probe holds observer IPC across the click and checks observer-before-control order and correlated outcome. ModelPicker component ordering is source-reviewed only. - Mock live admission now replays matching stored history with per-filter time/limit constraints, deduplication, untagged auxiliary channel fallback and authoritative explicit h-tags. Kind-specific fixture admission waits and retry-resolving hover actions fix startup-dependent test setup without weakening event/badge assertions. - `48e9c0dad` and `867495426`: steady-state scroll-prepend setup observes live admission, subsequent head dispatch, successful/idle query completion and initial bottom geometry. Phase-2 genuine-growth and ≤32px anchor assertions are unchanged. This isolates steady-state prepending: it **does not fix or certify production early-scroll/head-reset behavior**. Current validation: - Normal push hooks at `867495426`: **6,582/6,582 renderer tests**, zero failed/skipped/cancelled; lint/static checks, typecheck and differential file-size gate passed. Native source is unchanged from the earlier checkpoint; no new native run is claimed for these renderer/test follow-ups. - E2E build passed at `48e9c0dad` plus the exact subsequently committed test-only delta (spec blob `469be2eed868c677ba80b859cc871208000fee60`). The completed affected-smoke run passed **153/153** across agent-control, badge, entity links, messaging, profile status and scroll history; the full scroll file additionally passed twice (**36/36**). No full CI-smoke pass is claimed from this six-file local run. - Pinky independently reviewed production and test follow-ups, including the final scroll spec blob `469be2eed868c677ba80b859cc871208000fee60`, with no blocking finding. Review is source evidence, not an independent test run. - **Not merge-ready:** new-head required CI must complete, exact-range security review requires authorization, and GitHub currently reports REVIEW_REQUIRED; fresh exact-head reviewer approval is still needed. No approval, dismissal or merge performed. No new packaged/native audio, launch-to-usable or badge-paint observation is claimed. Initial fixes-only checkpoint validation (`1bf3d06024d284a63326fdd353baced0842aeb81`): - Pre-commit formatting hooks passed; worktree clean. - Renderer package hooks: 6,570 tests passed, zero failed/skipped/cancelled; lint/static checks, TypeScript and differential file-size gate passed. - Native package hook passed: default and mesh-enabled all-target Clippy, then the complete native workspace test suite. App library: 3,222 passed / 0 failed / 19 ignored; terminal/integration suites passed. The real nest trigger/stalled-body test passed on macOS. - Independent whole-change source review: no blocking findings at this commit; all 20 file hashes matched the committed blobs and review/validation manifests. - Regression coverage includes real hook/session cancellation, StrictMode/membership re-entry, reconnect ownership, extended/zero cooldowns, burst pacing, auxiliary readiness (including EOSE before IPC settles), native socket refusal/retry/deadline/cancellation, unread fetch/classification and real nest trigger/HTTP/file persistence. - Earlier isolated renderer mutations that started readiness before enqueue or removed auxiliary priority each failed the real presence regression; restored controls passed. No native mutation claim. - Nest fixture uses explicit app-data/nest paths instead of assuming Windows known-folder APIs obey HOME/APPDATA. Windows runtime execution is not claimed; CI/build results remain separate. Originating conversation: buzz://message?channel=46ced308-71df-495d-a144-4ebf08334703&id=bc43c3422a3b0b2141268d0fa149b898421c824992b662aed8b73c4eee50404f No approval or merge recommendation is implied by opening this PR. --------- Signed-off-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz> Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
631 lines
20 KiB
TypeScript
631 lines
20 KiB
TypeScript
import { expect, test, type Page } from "@playwright/test";
|
|
|
|
import { installMockBridge } from "../helpers/bridge";
|
|
|
|
const RELAY_URL = "ws://localhost:3000";
|
|
const OTHER_RELAY_URL = "ws://localhost:3001";
|
|
const OWNER_PUBKEY = "deadbeef".repeat(8);
|
|
const STALE_COMMUNITY_PUBKEY = "cafebabe".repeat(8);
|
|
const MATCHING_HASH = "mock-hash";
|
|
const READ_DELAY_MS = 600;
|
|
const SNAPSHOT_FRAME_DELAY_MS = 3_000;
|
|
|
|
function snapshotKey(relayUrl: string, ownerPubkey = OWNER_PUBKEY) {
|
|
return `buzz-channels.v1:${relayUrl}:${ownerPubkey.toLowerCase()}`;
|
|
}
|
|
|
|
function makeSnapshotChannel(index: number, prefix = "snapshot") {
|
|
return {
|
|
id: `${prefix}-${index}`,
|
|
name: `${prefix}-${String(index).padStart(2, "0")}`,
|
|
channelType: "stream",
|
|
visibility: "open",
|
|
description: "",
|
|
topic: null,
|
|
purpose: null,
|
|
memberCount: 1,
|
|
memberPubkeys: [OWNER_PUBKEY],
|
|
lastMessageAt: null,
|
|
archivedAt: null,
|
|
participants: [],
|
|
participantPubkeys: [],
|
|
isMember: true,
|
|
ttlSeconds: null,
|
|
ttlDeadline: null,
|
|
};
|
|
}
|
|
|
|
const FULL_SNAPSHOT = Array.from({ length: 14 }, (_, index) =>
|
|
makeSnapshotChannel(index),
|
|
);
|
|
const SNAPSHOT_DIAGNOSTIC_MARK = "buzz:sidebar:snapshot-diagnostic";
|
|
const FULL_SIDEBAR_PAINT_MARK = "buzz:sidebar:full-list-painted";
|
|
const BOOT_TO_FULL_SIDEBAR_MEASURE = "buzz:sidebar:boot-to-full-list-painted";
|
|
|
|
function snapshotIntegrity(
|
|
ownerPubkey: string,
|
|
hash: string,
|
|
channels: ReturnType<typeof makeSnapshotChannel>[],
|
|
) {
|
|
const value = JSON.stringify([ownerPubkey.toLowerCase(), hash, channels]);
|
|
let result = 0x811c9dc5;
|
|
for (let index = 0; index < value.length; index += 1) {
|
|
result ^= value.charCodeAt(index);
|
|
result = Math.imul(result, 0x01000193);
|
|
}
|
|
return (result >>> 0).toString(16).padStart(8, "0");
|
|
}
|
|
|
|
type SnapshotDiagnostics = {
|
|
ageMs: number;
|
|
channelCount: number;
|
|
presence: "absent" | "invalid" | "present";
|
|
serializedBytes: number;
|
|
};
|
|
|
|
async function getSnapshotDiagnostic(page: Page) {
|
|
return page.evaluate((name) => {
|
|
const entry = performance.getEntriesByName(name).at(-1) as
|
|
| PerformanceMark
|
|
| undefined;
|
|
return entry?.detail as SnapshotDiagnostics | undefined;
|
|
}, SNAPSHOT_DIAGNOSTIC_MARK);
|
|
}
|
|
|
|
async function getFullSidebarMeasure(page: Page) {
|
|
return page.evaluate(
|
|
({ markName, measureName }) => ({
|
|
markCount: performance.getEntriesByName(markName).length,
|
|
measure: performance.getEntriesByName(measureName).at(-1)?.duration,
|
|
}),
|
|
{
|
|
markName: FULL_SIDEBAR_PAINT_MARK,
|
|
measureName: BOOT_TO_FULL_SIDEBAR_MEASURE,
|
|
},
|
|
);
|
|
}
|
|
|
|
async function seedSnapshot(
|
|
page: Page,
|
|
options: {
|
|
channels?: ReturnType<typeof makeSnapshotChannel>[];
|
|
hash: string;
|
|
keyOwnerPubkey?: string;
|
|
ownerPubkey?: string;
|
|
relayUrl?: string;
|
|
},
|
|
) {
|
|
const channels = options.channels ?? FULL_SNAPSHOT;
|
|
const ownerPubkey = options.ownerPubkey ?? OWNER_PUBKEY;
|
|
await page.addInitScript(
|
|
({ channels, hash, integrity, key, ownerPubkey }) => {
|
|
window.localStorage.setItem(
|
|
key,
|
|
JSON.stringify({
|
|
version: 2,
|
|
updatedAt: Date.now(),
|
|
ownerPubkey,
|
|
hash,
|
|
channels,
|
|
integrity,
|
|
}),
|
|
);
|
|
},
|
|
{
|
|
channels,
|
|
hash: options.hash,
|
|
integrity: snapshotIntegrity(ownerPubkey, options.hash, channels),
|
|
key: snapshotKey(
|
|
options.relayUrl ?? RELAY_URL,
|
|
options.keyOwnerPubkey ?? ownerPubkey,
|
|
),
|
|
ownerPubkey,
|
|
},
|
|
);
|
|
}
|
|
|
|
async function seedCommunities(page: Page, communityPubkey = OWNER_PUBKEY) {
|
|
await page.addInitScript(
|
|
({ communityPubkey, relayA, relayB }) => {
|
|
const communities = [
|
|
{
|
|
id: "community-a",
|
|
name: "Alpha",
|
|
relayUrl: relayA,
|
|
pubkey: communityPubkey,
|
|
addedAt: "2026-01-01T00:00:00.000Z",
|
|
},
|
|
{
|
|
id: "community-b",
|
|
name: "Bravo",
|
|
relayUrl: relayB,
|
|
pubkey: communityPubkey,
|
|
addedAt: "2026-01-02T00:00:00.000Z",
|
|
},
|
|
];
|
|
window.localStorage.setItem(
|
|
"buzz-communities",
|
|
JSON.stringify(communities),
|
|
);
|
|
window.localStorage.setItem(
|
|
"buzz-active-community-id",
|
|
communities[0].id,
|
|
);
|
|
},
|
|
{ communityPubkey, relayA: RELAY_URL, relayB: OTHER_RELAY_URL },
|
|
);
|
|
}
|
|
|
|
async function getChannelsPayloads(page: Page) {
|
|
return page.evaluate(() =>
|
|
(window.__BUZZ_E2E_COMMAND_LOG__ ?? [])
|
|
.filter((entry) => entry.command === "get_channels")
|
|
.map((entry) => entry.payload as { knownHash?: unknown }),
|
|
);
|
|
}
|
|
|
|
async function mutateDisplayedChannels(page: Page, channelName: string) {
|
|
await page.evaluate((name) => {
|
|
const queryClient = window.__BUZZ_E2E_QUERY_CLIENT__ as
|
|
| {
|
|
setQueryData: (
|
|
queryKey: readonly string[],
|
|
updater: (
|
|
channels: ReturnType<typeof makeSnapshotChannel>[] | undefined,
|
|
) => ReturnType<typeof makeSnapshotChannel>[],
|
|
) => unknown;
|
|
}
|
|
| undefined;
|
|
if (!queryClient) {
|
|
throw new Error("E2E query client seam is not installed.");
|
|
}
|
|
queryClient.setQueryData(["channels"], (channels) => {
|
|
const template = channels?.[0];
|
|
if (!template) {
|
|
throw new Error("Displayed channel cache is empty.");
|
|
}
|
|
return [...channels, { ...template, id: "optimistic-channel", name }];
|
|
});
|
|
}, channelName);
|
|
}
|
|
|
|
async function readPersistedSnapshot(page: Page) {
|
|
return page.evaluate((key) => {
|
|
const raw = window.localStorage.getItem(key);
|
|
if (!raw) return null;
|
|
const snapshot = JSON.parse(raw) as {
|
|
channels: Array<{ name: string }>;
|
|
hash: string;
|
|
};
|
|
return {
|
|
channelNames: snapshot.channels.map((channel) => channel.name),
|
|
hash: snapshot.hash,
|
|
};
|
|
}, snapshotKey(RELAY_URL));
|
|
}
|
|
|
|
async function trackSnapshotRows(page: Page) {
|
|
await page.addInitScript(() => {
|
|
const testWindow = window as Window & {
|
|
__BUZZ_E2E_SNAPSHOT_ROWS_SEEN__?: string[];
|
|
};
|
|
const seen: string[] = [];
|
|
testWindow.__BUZZ_E2E_SNAPSHOT_ROWS_SEEN__ = seen;
|
|
const record = (node: Node) => {
|
|
if (!(node instanceof Element)) return;
|
|
const rows = node.matches('[data-channel-id^="snapshot-"]')
|
|
? [node]
|
|
: Array.from(node.querySelectorAll('[data-channel-id^="snapshot-"]'));
|
|
for (const row of rows) {
|
|
const id = row.getAttribute("data-channel-id");
|
|
if (id && !seen.includes(id)) seen.push(id);
|
|
}
|
|
};
|
|
new MutationObserver((records) => {
|
|
for (const mutation of records) {
|
|
for (const node of mutation.addedNodes) record(node);
|
|
}
|
|
}).observe(document, { childList: true, subtree: true });
|
|
});
|
|
}
|
|
|
|
async function getTrackedSnapshotRows(page: Page) {
|
|
return page.evaluate(
|
|
() =>
|
|
(
|
|
window as Window & {
|
|
__BUZZ_E2E_SNAPSHOT_ROWS_SEEN__?: string[];
|
|
}
|
|
).__BUZZ_E2E_SNAPSHOT_ROWS_SEEN__ ?? [],
|
|
);
|
|
}
|
|
|
|
test("cold boot paints the complete snapshot, sends its hash, and revalidates", async ({
|
|
page,
|
|
}) => {
|
|
await seedSnapshot(page, { hash: MATCHING_HASH });
|
|
await installMockBridge(page, {
|
|
channelsReadDelayMs: SNAPSHOT_FRAME_DELAY_MS,
|
|
honorChannelsKnownHash: true,
|
|
});
|
|
|
|
const navigationStartedAt = performance.now();
|
|
await page.goto("/");
|
|
const rows = page.locator('[data-channel-id^="snapshot-"]');
|
|
await expect(rows).toHaveCount(FULL_SNAPSHOT.length, { timeout: 2_000 });
|
|
const snapshotPaintedAt = performance.now();
|
|
expect(snapshotPaintedAt - navigationStartedAt).toBeLessThan(
|
|
SNAPSHOT_FRAME_DELAY_MS,
|
|
);
|
|
await expect(page.getByTestId("sidebar-loading")).toHaveCount(0);
|
|
await expect
|
|
.poll(() => getChannelsPayloads(page))
|
|
.toEqual([{ knownHash: MATCHING_HASH }]);
|
|
await expect
|
|
.poll(() => getSnapshotDiagnostic(page))
|
|
.toMatchObject({
|
|
channelCount: FULL_SNAPSHOT.length,
|
|
presence: "present",
|
|
});
|
|
const diagnostics = await getSnapshotDiagnostic(page);
|
|
expect(diagnostics?.serializedBytes).toBeGreaterThan(0);
|
|
expect(diagnostics?.ageMs).toBeGreaterThanOrEqual(0);
|
|
|
|
// The persisted data is deliberately stale: it paints immediately but still
|
|
// validates. The delayed matching response leaves a deterministic snapshot
|
|
// frame, then not-modified must not shrink the list.
|
|
await expect(rows).toHaveCount(FULL_SNAPSHOT.length);
|
|
await expect
|
|
.poll(() => getFullSidebarMeasure(page))
|
|
.toEqual({
|
|
markCount: expect.any(Number),
|
|
measure: expect.any(Number),
|
|
});
|
|
expect((await getFullSidebarMeasure(page)).markCount).toBeGreaterThan(0);
|
|
|
|
const liveSettledAt = performance.now();
|
|
console.info(
|
|
`[sidebar-snapshot] firstPaint=${Math.round(snapshotPaintedAt - navigationStartedAt)}ms snapshotToLive=${Math.round(liveSettledAt - snapshotPaintedAt)}ms rows=${FULL_SNAPSHOT.length}`,
|
|
);
|
|
});
|
|
|
|
test("matching not-modified preserves display mutations without persisting them", async ({
|
|
page,
|
|
}) => {
|
|
const optimisticName = "optimistic-local-channel";
|
|
await seedSnapshot(page, { hash: MATCHING_HASH });
|
|
await installMockBridge(page, { honorChannelsKnownHash: true });
|
|
await page.goto("/");
|
|
|
|
await expect(page.locator('[data-channel-id^="snapshot-"]')).toHaveCount(
|
|
FULL_SNAPSHOT.length,
|
|
);
|
|
await expect
|
|
.poll(() =>
|
|
page.evaluate(() =>
|
|
window.__BUZZ_E2E_QUERY_CLIENT__?.getQueryState(["channels"]),
|
|
),
|
|
)
|
|
.toMatchObject({ fetchStatus: "idle", status: "success" });
|
|
|
|
// Exercise the mutation during a real revalidation, not a race between boot
|
|
// rendering and a fixed response delay. The cold-boot test covers first paint.
|
|
await page.evaluate(() => {
|
|
window.__BUZZ_E2E_DEFER_NEXT_CHANNELS_READ__?.();
|
|
void window.__BUZZ_E2E_QUERY_CLIENT__?.invalidateQueries({
|
|
queryKey: ["channels"],
|
|
exact: true,
|
|
});
|
|
});
|
|
await expect
|
|
.poll(() => page.evaluate(() => window.__BUZZ_E2E_CHANNELS_READ_PENDING__))
|
|
.toBe(1);
|
|
await mutateDisplayedChannels(page, optimisticName);
|
|
await expect(
|
|
page.locator('[data-channel-id="optimistic-channel"]'),
|
|
).toBeVisible();
|
|
|
|
expect(
|
|
await page.evaluate(() => window.__BUZZ_E2E_RELEASE_CHANNELS_READ__?.()),
|
|
).toBe(1);
|
|
// Invocation logging only proves the request started. Wait for the query to
|
|
// consume its response before checking either display state or persistence.
|
|
await expect
|
|
.poll(() =>
|
|
page.evaluate(() =>
|
|
window.__BUZZ_E2E_QUERY_CLIENT__?.getQueryState(["channels"]),
|
|
),
|
|
)
|
|
.toMatchObject({ fetchStatus: "idle", status: "success" });
|
|
expect(await getChannelsPayloads(page)).toEqual([
|
|
{ knownHash: MATCHING_HASH },
|
|
{ knownHash: MATCHING_HASH },
|
|
]);
|
|
await expect
|
|
.poll(() => readPersistedSnapshot(page))
|
|
.toEqual({
|
|
channelNames: FULL_SNAPSHOT.map((channel) => channel.name),
|
|
hash: MATCHING_HASH,
|
|
});
|
|
await expect(
|
|
page.locator('[data-channel-id="optimistic-channel"]'),
|
|
).toBeVisible();
|
|
expect((await readPersistedSnapshot(page))?.channelNames).not.toContain(
|
|
optimisticName,
|
|
);
|
|
});
|
|
|
|
test("first-ever boot without a snapshot sends null and shows loading", async ({
|
|
page,
|
|
}) => {
|
|
await installMockBridge(page, { channelsReadDelayMs: READ_DELAY_MS });
|
|
await page.goto("/");
|
|
|
|
await expect(page.getByTestId("sidebar-loading")).toBeVisible({
|
|
timeout: 500,
|
|
});
|
|
await expect(page.locator('[data-channel-id^="snapshot-"]')).toHaveCount(0);
|
|
await expect
|
|
.poll(() => getChannelsPayloads(page))
|
|
.toEqual([{ knownHash: null }]);
|
|
await expect
|
|
.poll(() => getSnapshotDiagnostic(page))
|
|
.toMatchObject({
|
|
channelCount: 0,
|
|
presence: "absent",
|
|
serializedBytes: 0,
|
|
});
|
|
await expect(page.getByTestId("channel-general")).toBeVisible();
|
|
await expect
|
|
.poll(() => getFullSidebarMeasure(page))
|
|
.toEqual({
|
|
markCount: expect.any(Number),
|
|
measure: expect.any(Number),
|
|
});
|
|
expect((await getFullSidebarMeasure(page)).markCount).toBeGreaterThan(0);
|
|
});
|
|
|
|
test("a different identity's snapshot is ignored", async ({ page }) => {
|
|
await seedSnapshot(page, {
|
|
hash: "foreign-hash",
|
|
keyOwnerPubkey: OWNER_PUBKEY,
|
|
ownerPubkey: STALE_COMMUNITY_PUBKEY,
|
|
});
|
|
await installMockBridge(page, { channelsReadDelayMs: READ_DELAY_MS });
|
|
await page.goto("/");
|
|
|
|
await expect(page.getByTestId("sidebar-loading")).toBeVisible({
|
|
timeout: 500,
|
|
});
|
|
await expect(page.locator('[data-channel-id^="snapshot-"]')).toHaveCount(0);
|
|
await expect
|
|
.poll(() => getChannelsPayloads(page))
|
|
.toEqual([{ knownHash: null }]);
|
|
await expect
|
|
.poll(() => getSnapshotDiagnostic(page))
|
|
.toMatchObject({
|
|
channelCount: 0,
|
|
presence: "invalid",
|
|
});
|
|
await expect(page.getByTestId("channel-general")).toBeVisible();
|
|
});
|
|
|
|
test("display-only community pubkey cannot expose another identity's snapshot", async ({
|
|
page,
|
|
}) => {
|
|
await seedSnapshot(page, {
|
|
hash: "stale-community-identity-hash",
|
|
ownerPubkey: STALE_COMMUNITY_PUBKEY,
|
|
});
|
|
await trackSnapshotRows(page);
|
|
await installMockBridge(
|
|
page,
|
|
{ channelsReadDelayMs: READ_DELAY_MS },
|
|
{ skipCommunitySeed: true },
|
|
);
|
|
await seedCommunities(page, STALE_COMMUNITY_PUBKEY);
|
|
await page.goto("/");
|
|
|
|
await expect(page.getByTestId("channel-general")).toBeVisible();
|
|
expect(await getTrackedSnapshotRows(page)).toEqual([]);
|
|
const payloads = await getChannelsPayloads(page);
|
|
expect(payloads).toEqual([{ knownHash: null }]);
|
|
expect(payloads).not.toContainEqual({
|
|
knownHash: "stale-community-identity-hash",
|
|
});
|
|
});
|
|
|
|
test("partial hash/list write fails toward a full fetch", async ({ page }) => {
|
|
await seedSnapshot(page, { hash: MATCHING_HASH });
|
|
await page.addInitScript((key) => {
|
|
const raw = window.localStorage.getItem(key);
|
|
if (!raw) return;
|
|
const snapshot = JSON.parse(raw) as { hash: string };
|
|
window.localStorage.setItem(
|
|
key,
|
|
JSON.stringify({ ...snapshot, hash: "newer-partial-hash" }),
|
|
);
|
|
}, snapshotKey(RELAY_URL));
|
|
await installMockBridge(page, {
|
|
channelsReadDelayMs: READ_DELAY_MS,
|
|
honorChannelsKnownHash: true,
|
|
});
|
|
await page.goto("/");
|
|
|
|
await expect(page.getByTestId("sidebar-loading")).toBeVisible({
|
|
timeout: 500,
|
|
});
|
|
await expect(page.locator('[data-channel-id^="snapshot-"]')).toHaveCount(0);
|
|
await expect
|
|
.poll(() => getChannelsPayloads(page))
|
|
.toEqual([{ knownHash: null }]);
|
|
await expect
|
|
.poll(() => getSnapshotDiagnostic(page))
|
|
.toMatchObject({
|
|
channelCount: 0,
|
|
presence: "invalid",
|
|
});
|
|
await expect(page.getByTestId("channel-general")).toBeVisible();
|
|
await expect(page.locator('[data-channel-id^="snapshot-"]')).toHaveCount(0);
|
|
});
|
|
|
|
test("unexpected not-modified response retries without a hash", async ({
|
|
page,
|
|
}) => {
|
|
await installMockBridge(page, {
|
|
channelsNotModifiedResponses: 1,
|
|
});
|
|
await page.goto("/");
|
|
|
|
await expect(page.getByTestId("channel-general")).toBeVisible();
|
|
await expect
|
|
.poll(() => getChannelsPayloads(page))
|
|
.toEqual([{ knownHash: null }, { knownHash: null }]);
|
|
});
|
|
|
|
test("mismatched not-modified hash falls back to a full list", async ({
|
|
page,
|
|
}) => {
|
|
await seedSnapshot(page, { hash: "persisted-stale-hash" });
|
|
await installMockBridge(page, {
|
|
channelsReadDelayMs: READ_DELAY_MS,
|
|
channelsNotModifiedResponses: 1,
|
|
});
|
|
await page.goto("/");
|
|
|
|
const snapshotRows = page.locator('[data-channel-id^="snapshot-"]');
|
|
await expect(snapshotRows).toHaveCount(FULL_SNAPSHOT.length, {
|
|
timeout: 500,
|
|
});
|
|
await expect
|
|
.poll(() => getChannelsPayloads(page))
|
|
.toEqual([{ knownHash: "persisted-stale-hash" }, { knownHash: null }]);
|
|
|
|
// The stale snapshot may provide the immediate boot frame, but an impossible
|
|
// not-modified hash/list pairing must never survive as the settled result.
|
|
await expect(page.getByTestId("channel-general")).toBeVisible();
|
|
await expect(snapshotRows).toHaveCount(0);
|
|
await expect
|
|
.poll(() =>
|
|
page.evaluate((key) => {
|
|
const raw = window.localStorage.getItem(key);
|
|
if (!raw) return null;
|
|
const snapshot = JSON.parse(raw) as {
|
|
channels: Array<{ name: string }>;
|
|
hash: string;
|
|
};
|
|
return {
|
|
hash: snapshot.hash,
|
|
hasGeneral: snapshot.channels.some(
|
|
(channel) => channel.name === "general",
|
|
),
|
|
hasSnapshotRow: snapshot.channels.some((channel) =>
|
|
channel.name.startsWith("snapshot-"),
|
|
),
|
|
};
|
|
}, snapshotKey(RELAY_URL)),
|
|
)
|
|
.toEqual({ hash: MATCHING_HASH, hasGeneral: true, hasSnapshotRow: false });
|
|
});
|
|
|
|
test("hash mismatch replaces the snapshot with the full live list", async ({
|
|
page,
|
|
}) => {
|
|
await seedSnapshot(page, { hash: "stale-hash" });
|
|
await trackSnapshotRows(page);
|
|
await installMockBridge(page, {
|
|
channelsReadDelayMs: READ_DELAY_MS,
|
|
honorChannelsKnownHash: true,
|
|
});
|
|
await page.goto("/");
|
|
|
|
// Observe the boot frame even if live revalidation finishes before the
|
|
// test runner gets its next turn; cold-boot coverage separately times paint.
|
|
await expect
|
|
.poll(() => getTrackedSnapshotRows(page))
|
|
.toEqual(FULL_SNAPSHOT.map((channel) => channel.id));
|
|
await expect
|
|
.poll(() => getChannelsPayloads(page))
|
|
.toEqual([{ knownHash: "stale-hash" }]);
|
|
await expect(page.getByTestId("channel-general")).toBeVisible();
|
|
await expect(page.locator('[data-channel-id^="snapshot-"]')).toHaveCount(0);
|
|
await expect
|
|
.poll(() =>
|
|
page.evaluate((key) => {
|
|
const raw = window.localStorage.getItem(key);
|
|
if (!raw) return null;
|
|
const snapshot = JSON.parse(raw) as {
|
|
channels: Array<{ name: string }>;
|
|
hash: string;
|
|
};
|
|
return {
|
|
hash: snapshot.hash,
|
|
hasGeneral: snapshot.channels.some(
|
|
(channel) => channel.name === "general",
|
|
),
|
|
hasSnapshotRow: snapshot.channels.some((channel) =>
|
|
channel.name.startsWith("snapshot-"),
|
|
),
|
|
};
|
|
}, snapshotKey(RELAY_URL)),
|
|
)
|
|
.toEqual({ hash: MATCHING_HASH, hasGeneral: true, hasSnapshotRow: false });
|
|
});
|
|
|
|
test("community switch validates a stale relay snapshot and replaces it", async ({
|
|
page,
|
|
}) => {
|
|
const switchedSnapshot = Array.from({ length: 6 }, (_, index) =>
|
|
makeSnapshotChannel(index, "switched"),
|
|
);
|
|
await seedSnapshot(page, {
|
|
channels: switchedSnapshot,
|
|
hash: "stale-community-hash",
|
|
relayUrl: OTHER_RELAY_URL,
|
|
});
|
|
await installMockBridge(
|
|
page,
|
|
{
|
|
channelsReadDelayMs: READ_DELAY_MS,
|
|
honorChannelsKnownHash: true,
|
|
},
|
|
{ skipCommunitySeed: true },
|
|
);
|
|
await seedCommunities(page);
|
|
await page.goto("/");
|
|
await expect(page.getByTestId("app-sidebar")).toBeVisible();
|
|
|
|
const payloadCountBeforeSwitch = (await getChannelsPayloads(page)).length;
|
|
await page.getByTestId("community-rail-button-community-b").click();
|
|
const switchedRows = page.locator('[data-channel-id^="switched-"]');
|
|
await expect(switchedRows).toHaveCount(switchedSnapshot.length, {
|
|
timeout: 500,
|
|
});
|
|
await expect
|
|
.poll(async () =>
|
|
(await getChannelsPayloads(page)).slice(payloadCountBeforeSwitch).at(0),
|
|
)
|
|
.toEqual({ knownHash: "stale-community-hash" });
|
|
|
|
await expect(page.getByTestId("channel-general")).toBeVisible();
|
|
await expect(switchedRows).toHaveCount(0);
|
|
await expect
|
|
.poll(() =>
|
|
page.evaluate((key) => {
|
|
const raw = window.localStorage.getItem(key);
|
|
if (!raw) return null;
|
|
const snapshot = JSON.parse(raw) as {
|
|
channels: Array<{ name: string }>;
|
|
hash: string;
|
|
};
|
|
return {
|
|
hash: snapshot.hash,
|
|
hasGeneral: snapshot.channels.some(
|
|
(channel) => channel.name === "general",
|
|
),
|
|
};
|
|
}, snapshotKey(OTHER_RELAY_URL)),
|
|
)
|
|
.toEqual({ hash: MATCHING_HASH, hasGeneral: true });
|
|
});
|