diff --git a/desktop/src-tauri/src/commands/messages_tests.rs b/desktop/src-tauri/src/commands/messages_tests.rs index b875ebca7..3a469a025 100644 --- a/desktop/src-tauri/src/commands/messages_tests.rs +++ b/desktop/src-tauri/src/commands/messages_tests.rs @@ -1,4 +1,19 @@ use super::*; +use nostr::{EventBuilder, Kind, Tag}; + +fn thread_page_event(kind: u32, content: &str, root: Option<&str>) -> Event { + let tags = root + .map(|root| vec![Tag::parse(["e", root]).expect("valid root tag")]) + .unwrap_or_default(); + EventBuilder::new(Kind::Custom(kind as u16), content) + .tags(tags) + .sign_with_keys(&Keys::generate()) + .expect("test event should sign") +} + +fn bounds_event(root: &str, content: &str) -> Event { + thread_page_event(buzz_core_pkg::kind::KIND_THREAD_BOUNDS, content, Some(root)) +} #[test] fn marker_author_scope_validates_scope_and_required_pubkey() { @@ -186,6 +201,91 @@ fn thread_replies_filter_pages_with_composite_cursor() { ); } +#[test] +fn thread_page_parser_accepts_valid_empty_and_non_empty_pages() { + let empty = thread_page::parse( + vec![bounds_event( + "root", + r#"{"has_more":false,"next_cursor":null}"#, + )], + "root", + ) + .expect("valid terminal page should parse"); + assert!(empty.events.is_empty()); + assert!(!empty.has_more); + assert!(empty.next_cursor.is_none()); + + let reply = thread_page_event(9, "reply", Some("root")); + let reply_id = reply.id.to_hex(); + let page = thread_page::parse( + vec![ + reply, + bounds_event( + "root", + r#"{"has_more":true,"next_cursor":{"created_at":1700000000,"id":"cursor-id"}}"#, + ), + ], + "root", + ) + .expect("valid continuing page should parse"); + assert_eq!(page.events.len(), 1); + assert_eq!(page.events[0]["id"], serde_json::json!(reply_id)); + assert!(page.has_more); + let cursor = page.next_cursor.expect("continuing page needs a cursor"); + assert_eq!(cursor.created_at, 1_700_000_000); + assert_eq!(cursor.event_id, "cursor-id"); +} + +#[test] +fn thread_page_parser_rejects_missing_duplicate_and_wrong_root_bounds() { + let reply = thread_page_event(9, "reply", Some("root")); + assert!(thread_page::parse(vec![reply], "root") + .err() + .expect("missing bounds must fail closed") + .contains("omitted")); + + let terminal = r#"{"has_more":false,"next_cursor":null}"#; + assert!(thread_page::parse( + vec![ + bounds_event("root", terminal), + bounds_event("root", terminal) + ], + "root", + ) + .err() + .expect("duplicate bounds must fail closed") + .contains("multiple")); + + assert!( + thread_page::parse(vec![bounds_event("other-root", terminal)], "root") + .err() + .expect("mismatched root must fail closed") + .contains("does not match") + ); +} + +#[test] +fn thread_page_parser_rejects_malformed_and_inconsistent_bounds() { + assert!( + thread_page::parse(vec![bounds_event("root", "not-json")], "root") + .err() + .expect("malformed bounds must fail closed") + .contains("Invalid thread bounds") + ); + + for content in [ + r#"{"has_more":true,"next_cursor":null}"#, + r#"{"has_more":false,"next_cursor":{"created_at":1700000000,"id":"cursor-id"}}"#, + ] { + assert!( + thread_page::parse(vec![bounds_event("root", content)], "root") + .err() + .expect("cursor presence must agree with has_more") + .contains("disagree") + ); + } +} + #[test] fn stored_managed_agent_auth_tag_trims_blank_values() { assert_eq!( diff --git a/desktop/src/testing/e2eBridge.ts b/desktop/src/testing/e2eBridge.ts index 5847f0319..645ac4bf4 100644 --- a/desktop/src/testing/e2eBridge.ts +++ b/desktop/src/testing/e2eBridge.ts @@ -341,6 +341,8 @@ type E2eConfig = { threadRepliesDelayMs?: number; /** Hold the first continuation page until the E2E release seam is called. */ holdThreadRepliesPage2?: boolean; + /** Hold the second continuation page until the E2E release seam is called. */ + holdThreadRepliesPage3?: boolean; usersBatchDelayMs?: number; /** Delay (ms) applied only to initial channel-window requests. */ initialChannelWindowDelayMs?: number; @@ -1123,8 +1125,10 @@ declare global { requestId: number; startedAt: number; }>; - /** Release the held thread continuation page in the disposable A/B probe. */ + /** Release the held first thread continuation page. */ __BUZZ_E2E_RELEASE_THREAD_PAGE_2__?: () => void; + /** Release the held second thread continuation page. */ + __BUZZ_E2E_RELEASE_THREAD_PAGE_3__?: () => void; /** Release a mock media proxy held at port 0 and return its ready port. */ __BUZZ_E2E_RELEASE_MEDIA_PROXY__?: () => number; /** Release mock send events that were stored but withheld from live subscribers. */ @@ -4757,17 +4761,22 @@ async function handleGetThreadReplies( event_id: page[page.length - 1].id, } : null; - if ( - config?.mock?.holdThreadRepliesPage2 && - args.cursor && + const requestNumber = window.__BUZZ_E2E_MESSAGE_REQUEST_LOG__?.filter( (request) => request.command === "get_thread_replies", - ).length === 2 && - window.__BUZZ_E2E_RELEASE_THREAD_PAGE_2__ === undefined - ) { + ).length ?? 0; + const holdReleaseKey = + config?.mock?.holdThreadRepliesPage2 && args.cursor && requestNumber === 2 + ? "__BUZZ_E2E_RELEASE_THREAD_PAGE_2__" + : config?.mock?.holdThreadRepliesPage3 && + args.cursor && + requestNumber === 3 + ? "__BUZZ_E2E_RELEASE_THREAD_PAGE_3__" + : null; + if (holdReleaseKey && window[holdReleaseKey] === undefined) { await new Promise((resolve) => { - window.__BUZZ_E2E_RELEASE_THREAD_PAGE_2__ = () => { - delete window.__BUZZ_E2E_RELEASE_THREAD_PAGE_2__; + window[holdReleaseKey] = () => { + delete window[holdReleaseKey]; resolve(); }; }); diff --git a/desktop/tests/e2e/message-performance.spec.ts b/desktop/tests/e2e/message-performance.spec.ts index 5c5713ed7..cb8f0f65b 100644 --- a/desktop/tests/e2e/message-performance.spec.ts +++ b/desktop/tests/e2e/message-performance.spec.ts @@ -409,6 +409,15 @@ test("401-reply thread paints page 1, preserves a live arrival, and converges", await expect(panel.getByTestId("message-thread-replies-loading")).toHaveCount( 0, ); + const threadBody = panel.getByTestId("message-thread-body"); + await expect + .poll(() => + threadBody.evaluate( + (element) => + element.scrollHeight - element.clientHeight - element.scrollTop, + ), + ) + .toBeLessThanOrEqual(2); const liveReply = await page.evaluate((parentEventId) => { const emit = window.__BUZZ_E2E_EMIT_MOCK_MESSAGE__; @@ -480,4 +489,125 @@ test("401-reply thread paints page 1, preserves a live arrival, and converges", total: 402, unique: 402, }); + await expect + .poll(() => + threadBody.evaluate( + (element) => + element.scrollHeight - element.clientHeight - element.scrollTop, + ), + ) + .toBeLessThanOrEqual(2); +}); + +test("later-page thread target settles and survives subsequent prepends", async ({ + page, +}) => { + await installMockBridge(page, { + holdThreadRepliesPage2: true, + holdThreadRepliesPage3: true, + threadRepliesDelayMs: 25, + }); + await page.goto("/"); + await page.getByTestId("channel-general").click(); + await expect(page.getByTestId("chat-title")).toHaveText("general"); + + const seeded = await page.evaluate(() => { + const emit = window.__BUZZ_E2E_EMIT_MOCK_MESSAGE__; + if (!emit) throw new Error("mock message emitter is unavailable"); + const root = emit({ channelName: "random", content: "Target thread root" }); + const replies = Array.from({ length: 401 }, (_, index) => + emit({ + channelName: "random", + content: `Target thread reply ${index}`, + createdAt: 1_700_100_000 + index, + parentEventId: root.id, + }), + ); + return { rootId: root.id, targetId: replies[150].id }; + }); + + await page.getByTestId("channel-random").click(); + await expect(page.getByTestId("chat-title")).toHaveText("random"); + const root = page.locator(`[data-message-id="${seeded.rootId}"]`); + await expect(root).toBeVisible(); + const panel = await openThread(root, page); + await expect + .poll(() => readMessageRequests(page, "get_thread_replies")) + .toHaveLength(2); + await expect( + panel.locator(`[data-message-id="${seeded.targetId}"]`), + ).toHaveCount(0); + await page.evaluate(() => window.__BUZZ_E2E_RELEASE_THREAD_PAGE_2__?.()); + await expect + .poll(async () => { + const requests = await readMessageRequests(page, "get_thread_replies"); + return requests.length === 3 && requests[2]?.endedAt === null; + }) + .toBe(true); + + // Aim at the old reply only after page 2 makes it available. This exercises + // the same route target state used by deep links while page 3 is still held. + await page.evaluate(({ rootId, targetId }) => { + const hash = window.location.hash.replace(/^#/, "") || "/"; + const [path, query = ""] = hash.split("?"); + const params = new URLSearchParams(query); + params.set("messageId", targetId); + params.set("thread", rootId); + window.history.pushState( + {}, + "", + `${window.location.pathname}#${path}?${params}`, + ); + window.dispatchEvent(new HashChangeEvent("hashchange")); + window.dispatchEvent(new PopStateEvent("popstate")); + }, seeded); + + const target = panel.locator(`[data-message-id="${seeded.targetId}"]`); + const body = panel.getByTestId("message-thread-body"); + await expect + .poll(async () => { + if (!(await target.count())) return false; + return body.evaluate((element, targetId) => { + const row = element.querySelector( + `[data-message-id="${CSS.escape(targetId)}"]`, + ); + if (!row) return false; + const bodyRect = element.getBoundingClientRect(); + const rowRect = row.getBoundingClientRect(); + return rowRect.top >= bodyRect.top && rowRect.bottom <= bodyRect.bottom; + }, seeded.targetId); + }) + .toBe(true); + + // Page 3 is now held after page 2 exposed and settled the target. Releasing + // it prepends more history; the target must remain the visible anchor. + await expect + .poll(async () => { + const requests = await readMessageRequests(page, "get_thread_replies"); + return requests.length === 3 && requests[2]?.endedAt === null; + }) + .toBe(true); + await page.evaluate(() => window.__BUZZ_E2E_RELEASE_THREAD_PAGE_3__?.()); + await expect + .poll(async () => { + const requests = await readMessageRequests(page, "get_thread_replies"); + return ( + requests.length === 3 && + requests.every((request) => request.endedAt !== null) + ); + }) + .toBe(true); + await expect + .poll(() => + body.evaluate((element, targetId) => { + const row = element.querySelector( + `[data-message-id="${CSS.escape(targetId)}"]`, + ); + if (!row) return false; + const bodyRect = element.getBoundingClientRect(); + const rowRect = row.getBoundingClientRect(); + return rowRect.top >= bodyRect.top && rowRect.bottom <= bodyRect.bottom; + }, seeded.targetId), + ) + .toBe(true); }); diff --git a/desktop/tests/helpers/bridge.ts b/desktop/tests/helpers/bridge.ts index 8df2325c4..1f68c76df 100644 --- a/desktop/tests/helpers/bridge.ts +++ b/desktop/tests/helpers/bridge.ts @@ -295,6 +295,8 @@ type MockBridgeOptions = { threadRepliesDelayMs?: number; /** Hold page 2 until the E2E release seam is called. */ holdThreadRepliesPage2?: boolean; + /** Hold page 3 until the E2E release seam is called. */ + holdThreadRepliesPage3?: boolean; usersBatchDelayMs?: number; /** Delay (ms) for initial channel-window requests. */ initialChannelWindowDelayMs?: number;