From 2966a32a9d157e59a9a7d9daa2e2cf77c45ae8eb Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 19:12:38 -0500 Subject: [PATCH] feat(messages): let a plugin sort, filter and page a reader's rows Give plugins the general capability to arrange a thread's replies or a channel's timeline in place, while the feature (sorts, filters, window size, paging, wording) lives in the plugin. Core hooks: - `session.foldRows(channelId, events, rootId?)`: the rows the readers fold from proven events, with the viewer's own pending sends and delivery state. - `session.retain()`: one `{ set, dispose }` hold of proven, visible events so live edits, reactions and deletions of scanned rows pass visibility. It grants no access and feeds no cache, unread count or view; unread uses it as evidence. - `snapshotRead(filters, { priority: "background" })` and `session.windowNewer` for relays that page NIP-CW windows oldest first. - A `"reader"` accessory placement with `present({ ids, events, parents?, open?, complete?, place? })`, `presentation`, `limits` and `targetId`. The thread and channel readers show a presentation with their own controls, limits and reading, draw no day dividers or grouped rows while it shows, and return to the host rows at the reader's place on withdraw. Window admission fixes: live replies inside pages a running read has fetched are admitted, channel page verification is scoped to the window's channel, a list that turns partial retakes its reading leases, and display parents nest only under earlier rows. A test-only reference plugin sorts (Top, Oldest), filters across every scanned row and pages past the reader's limits over a 2,000-reply thread and a 5,000-row channel. Made with human guidance from the maintainer driving this work. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- browser-host/relay-broker.mjs | 4 + docs/buzz-help.md | 8 + docs/plugin-architecture.md | 102 ++ src/features/agents/agent-config-artifacts.ts | 3 +- .../conversation/ComposerAccessories.test.tsx | 198 +++- .../conversation/ComposerAccessories.tsx | 35 +- src/features/conversation/contracts.ts | 51 +- src/features/conversation/service.test.tsx | 31 + src/features/conversation/service.tsx | 2 +- .../ChannelTimeline.presentation.test.tsx | 776 +++++++++++++ .../messages/ChannelTimeline.restore.test.tsx | 60 + .../messages/ChannelTimeline.test.tsx | 1 + src/features/messages/ChannelTimeline.tsx | 204 +++- src/features/messages/Messages.module.css | 23 + .../messages/ThreadPanel.arranger.test.tsx | 269 +++++ .../ThreadPanel.presentation.test.tsx | 699 +++++++++++ src/features/messages/ThreadPanel.test.tsx | 2 +- src/features/messages/ThreadPanel.tsx | 219 +++- src/features/messages/arrangement.test.ts | 637 ++++++++++ src/features/messages/arrangement.ts | 489 ++++++++ .../messages/arranger-plugin.test.tsx | 1032 +++++++++++++++++ src/features/messages/reply-tree.test.ts | 45 + src/features/messages/reply-tree.ts | 31 +- src/features/messages/use-reading.test.ts | 107 +- src/features/messages/use-reading.ts | 26 +- src/features/relay/events.ts | 7 + src/features/relay/native.ts | 4 + src/features/relay/reader.test.ts | 30 +- src/features/relay/reader.ts | 2 + src/features/relay/session-hold.test.ts | 338 ++++++ src/features/relay/session.ts | 151 ++- src/features/relay/store.ts | 50 +- src/features/relay/testing.ts | 1 + src/features/relay/thread-window.test.ts | 411 ++++++- src/features/relay/thread-window.ts | 48 +- src/features/relay/threads.test.ts | 10 +- src/features/relay/threads.ts | 96 +- .../relay/traffic.integration.test.ts | 81 ++ src/features/relay/transport.ts | 5 + src/features/relay/unread.test.ts | 41 + src/features/relay/unread.ts | 34 +- src/features/relay/window.test.ts | 191 ++- src/features/relay/window.ts | 59 +- src/plugins/author.ts | 11 + .../conversation-arranger/fixtures.ts | 236 ++++ .../fixtures/conversation-arranger/plugin.ts | 730 ++++++++++++ tests/fixtures/conversation-arranger/relay.ts | 374 ++++++ 47 files changed, 7792 insertions(+), 172 deletions(-) create mode 100644 src/features/messages/ChannelTimeline.presentation.test.tsx create mode 100644 src/features/messages/ThreadPanel.arranger.test.tsx create mode 100644 src/features/messages/ThreadPanel.presentation.test.tsx create mode 100644 src/features/messages/arrangement.test.ts create mode 100644 src/features/messages/arrangement.ts create mode 100644 src/features/messages/arranger-plugin.test.tsx create mode 100644 src/features/relay/session-hold.test.ts create mode 100644 tests/fixtures/conversation-arranger/fixtures.ts create mode 100644 tests/fixtures/conversation-arranger/plugin.ts create mode 100644 tests/fixtures/conversation-arranger/relay.ts diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index e94a0442d4..80bee74250 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -348,6 +348,10 @@ async function relayAuthority(fetch, relay) { searchSort: Array.isArray(nip11.supported_extensions) && nip11.supported_extensions.includes("buzz-search-sort"), + // NIP-CW: windows page `newer`, and thread pages may leave out `root_aux`. + windowNewer: + Array.isArray(nip11.supported_extensions) && + nip11.supported_extensions.includes("buzz-window-newer"), ...(readSnapshotCommunity(nip11.read_state_snapshot) ? { readStateCommunity: readSnapshotCommunity(nip11.read_state_snapshot) } : {}), diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 9a040f6e7b..e0e8fcbe42 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1003,6 +1003,14 @@ and are asked to sign in again in Buzz. header actions come from the plugin. Closing a side tab keeps the main view. Plugins can also make their panels available as conversation detail links. Back and Forward restore these visits. Close retires the closed panel's visits. +- **Sorting a thread or channel**: a plugin can add a bar above the messages, + such as Top replies or From the start. While it shows rows, Buzz keeps its own + new-messages line, earlier-replies note, Jump button and arrival count off, and + marks as read only the rows you view, unless the plugin shows the whole + conversation. A thread's original message stays above the rows. Reactions and + deletions apply as they arrive. The plugin's own control, or removing the + plugin, returns Buzz's rows at the row you were reading. Replying to a row + still answers the message it was written to. - **Close tabs or the window (macOS)**: ⌘W closes the active tab. With no tab to close, it closes the window while Buzz and running agents stay open. Reopen Buzz from the Dock. ⌘⇧W clears the current channel's tabs without diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 4faae646e8..f998073e25 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -1581,6 +1581,108 @@ The persistent sidebar reads the same session activity snapshot for its quiet ma it owns presentation, not capture or an additional activity lease. This is a host-matched preview addition, not cross-version capability negotiation. +### Arranging a reader + +An accessory with `placement: "reader"` mounts in the bar above a thread's or a +channel's messages, outside their scroller, so an archived, guest or read-only +conversation has it too. It gets the composer props, plus these. They are +present for reader accessories only. + +- `present(presentation | null)` shows rows in place of the host's, or withdraws + them (`null` answers `shown`). `ids` are the rows in display order: replies in + a thread, top-level rows in a channel. `events` are proven events, usually from + `snapshotRead`; the reader keeps the rows `ids` names with their edits, + reactions and deletions, and adds live ones itself. Optional: `parents` (thread + only, display only: the earlier presented row each row nests under), `open` + (branches shown open), `complete` (`ids` hold every row, so reaching the end + reads it; otherwise only the rows viewed are marked read) and `place` + (`"keep"` by default, `"start"` or `{ id }`). +- The result is `shown`, `held` (another accessory in order is showing; this one + waits and shows when that one leaves), `limit` (more than `limits`, or the + reader cannot hold it now; the previous presentation stays), `invalid` + (duplicate ids or a malformed field) or `retired`. +- `presentation` is `none`, `shown`, `held` or `ended`. `ended` means live + growth passed `limits`; the reader never trims, because a trim could bring a + deleted row back. +- `limits` are `{ rows, events, bytes }`: 460 rows, 2,000 events and 4 MiB in a + thread, and 2,400 rows and 8 MiB in a channel (no event count). `targetId` is + the message the reader was opened to, if any. + +The host owns everything else. While a presentation shows, the reader draws its +rows with the ordinary message controls, keeps its own unread line, earlier-reply +note, jump button and arrival count off, never pages its own history, and takes +reading from the rows drawn: a list that is not `complete` reads only the rows +viewed. A withdrawal, a removed or failing accessory, or an unmount returns the +host's rows at the row the person was reading, or the nearest one still shown, +with no host read. In a thread the root is always the reader's header, above the +arranged replies: a plugin cannot hide or move it, and `ids` never includes it. +A reply to a row nested under a display parent still answers its signed parent. +The sort, filter, window size, layout and wording belong to the plugin. + +Three session capabilities serve a plugin that scans: + +- `session.snapshotRead(filters, { signal, priority })` is a fresh, verified read + that feeds no projection, cache, unread count or view. Use + `priority: "background"` so a long scan queues behind foreground reads. +- `session.retain()` returns `{ set(events), dispose() }`: one hold of proven, + visible events, up to 8 MiB. A held event lets its live edits, reactions and + deletions reach `subscribeLive`, which a row from `snapshotRead` alone would + not. It grants no access and changes no cache, `recent` or unread. A hold is + one view slot of the 64 that `observe` and thread views share; a presenting + reader uses one and the plugin uses one. +- `session.foldRows(channelId, events, rootId?)` folds proven events into rows: + stateless, with the viewer's own pending sends and their delivery state, and `[]` + for a denied channel or a closed session. With `rootId` it folds the root and + its replies; the plugin leaves the root out of `ids`. + +On a relay that advertises `buzz-window-newer` (`session.windowNewer`), a window +read can also page oldest first with `direction: "newer"` and `after`/`after_id` +from the previous page's cursor, and a thread read can pass `root_aux: false`, +because the reader already shows the root and its reactions. Without it, read +older pages only; the final rows are the same and the scan is slower. + +The scan pattern: + +1. Read with `snapshotRead`, `priority: "background"`, pages of 200. Never page + with `readPage`: it feeds the host's own views and unread counts, which are + bounded and are not a place to hold a scan. +2. Keep what was read in one `retain()` hold and fold with `foldRows`. Rank from + the folded rows, such as the distinct accounts that reacted; the definition of + a score is the plugin's. +3. Present a small first window (200 rows), and grow it on demand. A reader shows + one window of at most 460 rows (2,400 in a channel), so reach the rest by + presenting the next or previous slice of the ranked list with `place: "start"`. + Oldest first needs no full scan: the first window paints from the first pages, + and each "Next" reads on. Ranking and filtering need every row: finish the scan + first, or say it is still reading, so a result never depends on what happened + to load. +4. Leave headroom under `limits` for live reactions, edits and deletions of the + rows shown (a few hundred events). A presentation that fits exactly ends on + its first reaction. +5. Pin what the person must see (their own pending sends, `targetId`), and let + the rest follow the sort. Their rows fold from the outbox with delivery state. +6. On `ended`, present a smaller slice, such as half as many rows, and say so. +7. Changes made while the live connection is down (`session.live`) may never + arrive: a reaction to a row that is not shown, or a deletion of any age. Once + it drops, the result is no longer exact; say so. A relay restart reconnects + every viewer at once, so read again only while the window is visible, after a + random wait of up to 10 seconds, and do not retry a failed read on a timer. + The reader keeps the shown rows live until the new read presents. + +Known limits. A live, exact "Top" needs every reply's events held, which fits a +few thousand replies in memory; a 50,000-reply thread is about 250 pages and 65 MB +per viewer. Past the 8 MiB hold bound, a plugin can still rank exactly at scan time +(`foldRows` is stateless), but live changes then reach only the rows it holds. The +reference plugin below holds everything it reads, so past that bound it stops with +an error instead. A true live "Top" at that size needs a +relay-ranked query, which is a separate relay capability. A scan through +`readPage` is trimmed: a thread view admits only rows inside its own verified +window, so the view stays ready, but the rows past it are dropped, and unread +keeps its own session-wide bound. The test plugin +`tests/fixtures/conversation-arranger/plugin.ts` (not shipped) is a reference: a +Top and Oldest arranger with a text filter and Next and Previous paging, tested +over a 2,000-reply thread and a 5,000-row channel. + ### Channel-header launchers A panel may additionally contribute `channelLauncher: ComponentType`. diff --git a/src/features/agents/agent-config-artifacts.ts b/src/features/agents/agent-config-artifacts.ts index 8d268e1f32..f4b8ff6291 100644 --- a/src/features/agents/agent-config-artifacts.ts +++ b/src/features/agents/agent-config-artifacts.ts @@ -5,6 +5,7 @@ import { PublishRejected } from "../relay/outbox"; import type { RelayWriter } from "../relay/transport"; import type { EventData, ReadFilter, RelayEvent } from "../relay/events"; +import type { Priority } from "../relay/reader"; export const ARTIFACT_KIND = 45010; export type ArtifactType = @@ -211,7 +212,7 @@ export const signedEventBytes = (event: RelayEvent) => * stand in for it. */ export type SnapshotRead = ( filters: readonly ReadFilter[], - options: { signal?: AbortSignal | undefined }, + options: { signal?: AbortSignal | undefined; priority?: Priority }, ) => Promise; /** The explicit current-heads query. The relay's artifact parser takes only diff --git a/src/features/conversation/ComposerAccessories.test.tsx b/src/features/conversation/ComposerAccessories.test.tsx index 270ce9f5a4..4e15d00da9 100644 --- a/src/features/conversation/ComposerAccessories.test.tsx +++ b/src/features/conversation/ComposerAccessories.test.tsx @@ -1,8 +1,14 @@ // @vitest-environment jsdom import { afterEach, expect, it, vi } from "vitest"; import { act, cleanup, render, screen } from "@testing-library/react"; -import { useLayoutEffect } from "react"; -import type { ComposerAccessoryProps, ComposerAccessory } from "./contracts"; +import { useLayoutEffect, useRef, useState } from "react"; +import type { + ComposerAccessoryProps, + ComposerAccessory, + ConversationPresentation, + PresentResult, +} from "./contracts"; +import { createArrangement } from "../messages/arrangement"; import type { Contribution } from "../../plugins/contributions"; import { ComposerAccessories } from "./ComposerAccessories"; import type { RelaySession } from "../relay/session"; @@ -211,3 +217,191 @@ it("gives only one decorator the host summary and restores the fallback on remov expect(screen.getAllByRole("button", { name: "6 replies" })).toHaveLength(1); expect(screen.queryByText("Activity preview")).toBeNull(); }); + +const nothing: ConversationPresentation = { ids: [], events: [] }; +const fakeSession = () => + ({ + retain: () => ({ set() {}, dispose() {} }), + foldRows: () => [], + subscribeLive: () => () => {}, + profiles: { subscribe: () => () => {} }, + }) as unknown as RelaySession; +const readerEntry = ( + key: string, + component: Contribution["component"], + order?: number, +): Contribution => ({ + id: key, + key: `test:${key}`, + pluginId: "test", + revision: "one", + title: key, + placement: "reader", + ...(order === undefined ? {} : { order }), + component, +}); +function readerHost() { + const session = fakeSession(); + const arrangement = createArrangement({ + session, + channelId: "channel", + limits: { rows: 10, events: 10, bytes: 1000 }, + }); + let entries: Contribution[] = []; + const listeners = new Set<() => void>(); + const registry = { + snapshot: () => entries, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }; + const props = { + registry, + placement: "reader" as const, + arrangement, + session, + scope: "scope", + channelId: "channel", + open: () => true, + canOpen: () => true, + }; + return { + arrangement, + props, + session, + set(next: Contribution[]) { + entries = next; + act(() => { + for (const listener of listeners) listener(); + }); + }, + }; +} + +it("gives a reader accessory present, its status and the limits, never the host, and revokes present", () => { + let latest!: ComposerAccessoryProps; + const entry = readerEntry("one", (props) => { + useLayoutEffect(() => { + latest = props; + }); + return null; + }); + const reader = readerHost(); + reader.set([entry]); + const view = render(); + expect("arrangement" in latest).toBe(false); + expect(latest.limits).toBe(reader.arrangement.limits); + expect(latest.presentation).toBe("none"); + let result: PresentResult | undefined; + act(() => { + result = latest.present?.(nothing); + }); + expect(result).toBe("shown"); + expect(latest.presentation).toBe("shown"); + const original = latest.present; + const replaced = fakeSession(); + view.rerender(); + expect(original?.(nothing)).toBe("retired"); + expect(latest.present?.(nothing)).toBe("shown"); + const current = latest.present; + reader.set([]); + expect(current?.(nothing)).toBe("retired"); + expect(latest.present?.(nothing)).toBe("retired"); +}); + +it("gives no present to a reader accessory without a host, or to other placements", () => { + let latest!: ComposerAccessoryProps; + const component = (props: ComposerAccessoryProps) => { + useLayoutEffect(() => { + latest = props; + }); + return null; + }; + const reader = readerHost(); + reader.set([readerEntry("one", component)]); + const { arrangement: _, ...without } = reader.props; + render(); + expect(latest.present).toBeUndefined(); + expect(latest.presentation).toBeUndefined(); + cleanup(); + reader.set([{ ...readerEntry("one", component), placement: "composer" }]); + render(); + expect(latest.present).toBeUndefined(); +}); + +it("withdraws a reader lane when its accessory unmounts", () => { + let present: ComposerAccessoryProps["present"]; + const reader = readerHost(); + reader.set([ + readerEntry("a", (props) => { + present = props.present; + return null; + }), + ]); + const view = render(); + act(() => { + present?.(nothing); + }); + expect(reader.arrangement.snapshot()).toBeDefined(); + view.unmount(); + expect(reader.arrangement.snapshot()).toBeUndefined(); +}); + +it.each([false, true])( + "withdraws a throwing reader lane, revokes its present and promotes the next (StrictMode %s)", + (reactStrictMode) => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + let bombPresent: ComposerAccessoryProps["present"]; + let explode!: () => void; + function Bomb(props: ComposerAccessoryProps) { + const [broken, setBroken] = useState(false); + explode = () => setBroken(true); + if (broken) throw new Error("boom"); + useLayoutEffect(() => { + bombPresent = props.present; + }); + return bomb; + } + let sparePresent: ComposerAccessoryProps["present"]; + const reader = readerHost(); + const [bomb, spare] = [ + readerEntry("a", Bomb, 0), + readerEntry("b", (props) => { + sparePresent = props.present; + return {`spare:${props.presentation}`}; + }), + ] as const; + reader.set([bomb, spare]); + render(, { reactStrictMode }); + act(() => { + bombPresent?.(nothing); + sparePresent?.(nothing); + }); + expect(screen.getByText("spare:held")).toBeTruthy(); + act(() => explode()); + expect(screen.getByText("a unavailable")).toBeTruthy(); + expect(screen.getByText("spare:shown")).toBeTruthy(); + expect(reader.arrangement.status(bomb)).toBe("none"); + expect(bombPresent?.(nothing)).toBe("retired"); + expect(reader.arrangement.status(spare)).toBe("shown"); + error.mockRestore(); + }, +); + +it("keeps a reader lane presented once, in a layout effect, through a StrictMode replay", () => { + function Once(props: ComposerAccessoryProps) { + const done = useRef(false); + useLayoutEffect(() => { + if (done.current) return; + done.current = true; + props.present?.(nothing); + }, [props.present]); + return {`once:${props.presentation}`}; + } + const reader = readerHost(); + reader.set([readerEntry("a", Once)]); + render(, { reactStrictMode: true }); + expect(screen.getByText("once:shown")).toBeTruthy(); + expect(reader.arrangement.snapshot()).toBeDefined(); +}); diff --git a/src/features/conversation/ComposerAccessories.tsx b/src/features/conversation/ComposerAccessories.tsx index fdf5422061..51f1a04652 100644 --- a/src/features/conversation/ComposerAccessories.tsx +++ b/src/features/conversation/ComposerAccessories.tsx @@ -1,5 +1,6 @@ import { useLayoutEffect, useRef, useState, useSyncExternalStore } from "react"; import type { Contribution } from "../../plugins/contributions"; +import type { Arrangement } from "../messages/arrangement"; import type { ComposerAccessory, ComposerAccessoryProps, @@ -7,13 +8,17 @@ import type { } from "./contracts"; import { ContributionBoundary, contributionKey } from "./ContributionBoundary"; +const noSubscription = () => () => {}; export function ComposerAccessories({ registry, placement, + arrangement, ...props }: ComposerAccessoryProps & { registry: ContributionReader; placement?: ComposerAccessory["placement"]; + /** Reader placement: the host the accessories present to. Never given to them. */ + arrangement?: Arrangement | undefined; }) { const entries = useSyncExternalStore( registry.subscribe, @@ -51,6 +56,7 @@ export function ComposerAccessories({ ; registry: ContributionReader; + arrangement: Arrangement | undefined; }) { const current = useRef(props); useLayoutEffect(() => { @@ -78,9 +86,20 @@ function OwnedAccessory({ useState< Pick< ComposerAccessoryProps, - "canOpen" | "open" | "openThread" | "onFocusedRemoval" + "canOpen" | "open" | "openThread" | "onFocusedRemoval" | "present" > >(); + const presentation = useSyncExternalStore( + arrangement?.subscribe ?? noSubscription, + () => arrangement?.status(entry), + ); + // An unmounted accessory shows nothing. + useLayoutEffect( + () => () => { + arrangement?.present(entry, null); + }, + [arrangement, entry], + ); useLayoutEffect(() => { let live = true; const session = props.session; @@ -97,14 +116,24 @@ function OwnedAccessory({ openThread: canOpenThread ? () => active() && (current.current.openThread?.() ?? false) : undefined, + present: arrangement + ? (presented) => + active() ? arrangement.present(entry, presented) : "retired" + : undefined, }); return () => { live = false; }; - }, [entry, registry, props.session, canOpenThread]); + }, [entry, registry, props.session, canOpenThread, arrangement]); const Accessory = entry.component; return commands ? ( - + ) : ( (props.renderMessageSummary?.() ?? null) ); diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index 581a5a4941..3c20be137e 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -3,6 +3,7 @@ import type { ComponentType, ReactElement, ReactNode, Ref } from "react"; import type { Contribution, MatchOrder } from "../../plugins/contributions"; import type { VoiceRecording } from "../relay/voice-media"; import type { Attachment, ChannelMessage } from "../relay/contracts"; +import type { EventData } from "../relay/events"; import type { RelaySession } from "../relay/session"; import type { ComposerSession } from "../messages/composer-session"; @@ -193,6 +194,39 @@ export type MessageSummaryActivity = Readonly<{ label: string; ref: Ref; }>; +/** Rows a reader shows from a plugin at once: a memory and DOM bound, not a policy. */ +export type PresentationLimits = Readonly<{ + rows: number; + /** Events held for the rows: their edits, reactions and deletions too. + * Infinity where the reader has no event count bound (a channel). */ + events: number; + bytes: number; +}>; +/** What a plugin asks a reader to show in place of the host's rows. */ +export type ConversationPresentation = Readonly<{ + /** Rows in display order: replies in a thread (the root stays the reader's + * header), top-level rows in a channel. Ids that do not fold are skipped; + * own pending sends need no events. */ + ids: readonly string[]; + /** Proven events (e.g. from `snapshotRead`); the reader keeps the rows named by + * `ids` and their edits, reactions and deletions, and adds live ones itself. */ + events: readonly EventData[]; + /** Thread only, display only: the earlier presented row each row nests under. + * Unknown, later or cyclic parents put the row at the top level. Absent: Buzz's branches. */ + parents?: Readonly>; + /** Branches shown open; the reader keeps the user's later toggles. */ + open?: readonly string[]; + /** `ids` hold every row of the conversation: reaching the end reads it. + * Otherwise only the rows viewed are read. */ + complete?: boolean; + /** Default "keep": the first visible row stays where it was. */ + place?: "keep" | "start" | Readonly<{ id: string }>; +}>; +/** `shown` or `held`: accepted (`null`, a withdrawal, answers `shown`); only + * the first accessory in order shows. `limit`: more than the reader's limits, or + * the reader cannot hold it now; the previous presentation stays. `invalid`: + * duplicate ids. `retired`: the reader, or this accessory, is gone. */ +export type PresentResult = "shown" | "held" | "limit" | "invalid" | "retired"; export type ComposerAccessoryProps = Readonly<{ session: RelaySession; scope: string; @@ -220,6 +254,18 @@ export type ComposerAccessoryProps = Readonly<{ openThread?: (() => boolean) | undefined; /** Return keyboard focus to a stable host control when a focused accessory retires. */ onFocusedRemoval?: (() => void) | undefined; + /** Reader placement only: shows these rows in place of the host's, or `null` + * withdraws them. Absent where the reader shows no presentation. */ + present?: + | ((presentation: ConversationPresentation | null) => PresentResult) + | undefined; + /** Reader placement only: this accessory's presentation, `ended` once live + * growth passed `limits`, until it presents again. */ + presentation?: "none" | "shown" | "held" | "ended" | undefined; + /** Reader placement only. */ + limits?: PresentationLimits | undefined; + /** Reader placement only: the message this reader was opened to show, if any. */ + targetId?: string | undefined; /** Presentation only; the host re-resolves targets. No editor or access grant. */ canOpen(target: string): boolean; /** False after contribution removal or the originating composer retires. @@ -229,8 +275,9 @@ export type ComposerAccessoryProps = Readonly<{ }>; export type ComposerAccessory = Readonly<{ /** Defaults to the composer. Message accessories sit beside reactions; - * response accessories occupy an incoming row after the triggering message. */ - placement?: "composer" | "message" | "response"; + * response accessories occupy an incoming row after the triggering message; + * reader accessories sit in the reader's bar and may present its rows. */ + placement?: "composer" | "message" | "response" | "reader"; /** Opt into decorating the message summary; only the first ordered owner wins. */ decoratesMessageSummary?: boolean; id: string; diff --git a/src/features/conversation/service.test.tsx b/src/features/conversation/service.test.tsx index 621140d3a1..60a262169b 100644 --- a/src/features/conversation/service.test.tsx +++ b/src/features/conversation/service.test.tsx @@ -477,6 +477,37 @@ it("owns accessories through disable, replacement and failed activation", async expect(broken.service.accessories.snapshot()).toHaveLength(0); }); +it("accepts the reader accessory placement and refuses an unknown one", async () => { + let refused: unknown; + const h = harness({ + inject: ["conversation"], + apply(ctx) { + ctx.conversation.registerAccessory({ + id: "bar", + title: "Bar", + placement: "reader", + component: Component, + }); + try { + ctx.conversation.registerAccessory({ + id: "bad", + title: "Bad", + placement: "sidebar" as "reader", + component: Component, + }); + } catch (error) { + refused = error; + } + }, + }); + h.runtime.reconcile([h.plugin]); + await vi.waitFor(() => + expect(h.service.accessories.snapshot()).toHaveLength(1), + ); + expect(h.service.accessories.snapshot()[0]?.placement).toBe("reader"); + expect(String(refused)).toMatch(/Invalid accessory placement/); +}); + it("retires plugin chat menu contributions when their plugin is disabled", async () => { const h = harness({ inject: ["conversation"], diff --git a/src/features/conversation/service.tsx b/src/features/conversation/service.tsx index b4c52ea808..3d3d79b6b7 100644 --- a/src/features/conversation/service.tsx +++ b/src/features/conversation/service.tsx @@ -387,7 +387,7 @@ export class ConversationService extends Service implements Conversation { validate(value); if ( value.placement !== undefined && - !["composer", "message", "response"].includes(value.placement) + !["composer", "message", "response", "reader"].includes(value.placement) ) throw new Error("Invalid accessory placement"); this.accessoryEntries.register(this.ctx, value); diff --git a/src/features/messages/ChannelTimeline.presentation.test.tsx b/src/features/messages/ChannelTimeline.presentation.test.tsx new file mode 100644 index 0000000000..113bd22894 --- /dev/null +++ b/src/features/messages/ChannelTimeline.presentation.test.tsx @@ -0,0 +1,776 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; +import { StrictMode, useLayoutEffect, type ReactNode } from "react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { stubAvatarBrowserApis } from "../agents/avatar-testing"; +import type { Contribution } from "../../plugins/contributions"; +import type { + ComposerAccessory, + ComposerAccessoryProps, + ConversationExtensions, + ConversationPresentation, + PresentResult, +} from "../conversation/contracts"; +import type { PageNavigation } from "../navigation/service"; +import type { ChannelMessage, ChannelWindow } from "../relay/contracts"; +import { eventDto, type EventData, type RelayEvent } from "../relay/events"; +import type { LiveCallbacks } from "../relay/live"; +import { createRelaySession, type RelaySession } from "../relay/session"; +import { keypair, message, roster, scriptedTransport } from "../relay/testing"; +import { ChannelTimeline, type ChannelTimelineProps } from "./ChannelTimeline"; +import type { MessageRowProps } from "./MessageRow"; +import type { useReading } from "./use-reading"; + +stubAvatarBrowserApis(); + +type ReadingProps = Parameters[0]; +const readingProps: ReadingProps[] = []; +vi.mock("./use-reading", () => ({ + useReading: (props: ReadingProps) => { + readingProps.push(props); + }, + readingPositioned: () => {}, + readingDocumentActive: () => true, +})); +vi.mock("./TypingIndicator", () => ({ + TypingIndicator: () =>

typing tail

, + useLiveConversationAgents: () => [], +})); +const viewport = vi.hoisted(() => ({ + caches: [] as unknown[], + shifts: [] as unknown[], + /** The index of the first row in view. */ + first: 0, + scrollToIndex: vi.fn(), +})); +// The virtualizer's public contract, as in the viewport suite: the timeline +// owns its refs, render and effect order. +vi.mock("virtua", async () => { + const { forwardRef, useImperativeHandle } = await import("react"); + return { + Virtualizer: forwardRef(function Virtualizer( + { + children, + cache, + shift, + }: { children: ReactNode; cache?: unknown; shift?: boolean }, + ref, + ) { + viewport.caches.push(cache); + viewport.shifts.push(shift); + useImperativeHandle( + ref, + () => ({ + viewportSize: 600, + cache: [[], 40], + findItemIndex: () => viewport.first, + getItemOffset: () => 0, + scrollTo: vi.fn(), + scrollToIndex: viewport.scrollToIndex, + }), + [], + ); + return
    {children}
; + }), + }; +}); +vi.mock("./MessageRow", () => ({ + MessageRow: ({ row, day, stackPrevious, stackNext }: MessageRowProps) => ( +
  • + {row.content} +
  • + ), +})); + +const viewer = keypair(); +const other = keypair(); +const relay = keypair(); +const T = 1_700_000_000; +const DAY = 86_400; +const proven = (event: RelayEvent): EventData => eventDto(event); +const post = (name: string, at: number) => + proven(message(other, "c", name, at)); +/** Six rows the host's window holds, a minute apart. */ +const hostEvents = ["h0", "h1", "h2", "h3", "h4", "h5"].map((name, index) => + post(name, T + 60 * index), +); +/** Rows the host never loaded. */ +const [p0, p1, p2] = ["p0", "p1", "p2"].map((name, index) => + post(name, T + 1000 + 60 * index), +) as [EventData, EventData, EventData]; +const named = new Map( + [...hostEvents, p0, p1, p2].map((event) => [event.id, event.content]), +); +const [h0, h1, h2, h3, h4, h5] = hostEvents as [ + EventData, + EventData, + EventData, + EventData, + EventData, + EventData, +]; + +const owners: ReturnType[] = []; +let scrolled = 0; +let frames = new Map(); +beforeEach(() => { + scrolled = 0; + frames = new Map(); + viewport.caches.length = 0; + viewport.shifts.length = 0; + viewport.first = 0; + viewport.scrollToIndex.mockClear(); + let id = 0; + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { + frames.set(++id, callback); + return id; + }); + vi.stubGlobal("cancelAnimationFrame", (handle: number) => + frames.delete(handle), + ); + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + disconnect() {} + }, + ); + HTMLElement.prototype.scrollIntoView = vi.fn(); + HTMLElement.prototype.scrollTo = vi.fn(); + vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(800); + vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(600); + vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(4000); + Object.defineProperty(HTMLElement.prototype, "scrollTop", { + configurable: true, + get: () => scrolled, + set(value: number) { + scrolled = Math.max(0, Math.min(value, 3400)); + }, + }); + /** Rows lie 100px apart in the order drawn; the edge above them is 40px. */ + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation( + function (this: HTMLElement) { + if (this.dataset.messageId !== undefined) + return new DOMRect( + 0, + 100 * + [...document.querySelectorAll("[data-message-id]")].indexOf(this) - + scrolled, + 500, + 80, + ); + if (this.dataset.messageScroller !== undefined) + return new DOMRect(0, 0, 800, 600); + return new DOMRect(0, 0, 800, 40); + }, + ); +}); +afterEach(() => { + cleanup(); + for (const owner of owners.splice(0)) owner.dispose(); + readingProps.length = 0; + localStorage.clear(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + delete (HTMLElement.prototype as Partial).scrollTop; +}); + +const readerEntry = ( + component: Contribution["component"], +): Contribution => ({ + id: "arranger", + key: "test:arranger", + pluginId: "test", + revision: "one", + title: "Arranger", + placement: "reader", + component, +}); +const hostWindow = ( + rows: readonly ChannelMessage[], + extra: Partial = {}, +): ChannelWindow => ({ + channelId: "c", + status: "ready", + freshness: "verified", + hasMore: false, + loadingOlder: false, + historyLimited: false, + error: undefined, + rows, + ...extra, +}); + +function mount({ + window: windowExtra = {}, + props = {}, + strict = false, + onProps, + fold, + rows, + again, +}: { + window?: Partial; + props?: Partial; + strict?: boolean; + /** Runs in the accessory's layout effect, as a plugin presenting at mount. */ + onProps?: (props: ComposerAccessoryProps) => void; + /** Replaces the session's fold, for rows events cannot make. */ + fold?: RelaySession["foldRows"]; + /** The host window's rows; default the six host events. */ + rows?: readonly ChannelMessage[]; + /** Mounts on the session of an earlier mount, as a return to the channel. */ + again?: { session: RelaySession }; +} = {}) { + const wire = scriptedTransport(viewer.pubkey, relay.pubkey); + let callbacks!: LiveCallbacks; + const owner = createRelaySession( + { + ...wire.transport, + subscribe(next) { + callbacks = next; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { outboxStorage: { load: () => [], save() {} } }, + ); + owners.push(owner); + owner.session.channels.ensure("c"); + callbacks.receive([roster(relay, "c", [viewer.pubkey], T)]); + const rowsOf = (events: readonly EventData[]): readonly ChannelMessage[] => + owner.session.foldRows("c", events); + let current = hostWindow(rows ?? rowsOf(hostEvents), windowExtra); + const loadOlder = vi.fn(); + const retained = { taken: 0, disposed: 0 }; + const session = + again?.session ?? + ({ + ...owner.session, + ...(fold ? { foldRows: fold } : {}), + retain() { + retained.taken++; + const hold = owner.session.retain(); + return { + set: hold.set, + dispose() { + retained.disposed++; + hold.dispose(); + }, + }; + }, + channels: { + ...owner.session.channels, + loadOlder, + window: () => current, + }, + } as RelaySession); + const latest: { current?: ComposerAccessoryProps } = {}; + const entries = [ + readerEntry((accessory) => { + latest.current = accessory; + useLayoutEffect(() => { + onProps?.(accessory); + }); + return bar; + }), + ]; + const extensions = { + accessories: { snapshot: () => entries, subscribe: () => () => {} }, + } as unknown as ConversationExtensions; + const tree = () => { + const element = ( + false} + {...props} + /> + ); + return strict ? {element} : element; + }; + const view = render(tree()); + return { + ...view, + session, + loadOlder, + retained, + latest, + rowsOf, + /** The host's window changes. */ + setWindow(next: Partial) { + current = { ...current, ...next }; + view.rerender(tree()); + }, + present( + presentation: Partial & { + ids: readonly string[]; + }, + ) { + let result: PresentResult | undefined; + act(() => { + result = latest.current?.present?.({ + events: [...hostEvents, p0, p1, p2], + ...presentation, + }); + }); + return result; + }, + withdraw() { + act(() => { + latest.current?.present?.(null); + }); + }, + }; +} +/** Runs the animation frames queued so far, as the browser would next. */ +const frame = () => + act(() => { + for (const [id, callback] of [...frames]) { + frames.delete(id); + callback(0); + } + }); +/** The messages drawn, in order. */ +const drawn = () => + [...document.querySelectorAll("li[data-message-id]")].map( + (row) => named.get(row.dataset.messageId ?? "") ?? row.dataset.messageId, + ); +const scroller = () => + screen.getByRole("region", { name: "Channel message history" }); +const lastReading = () => readingProps.at(-1) as ReadingProps; +const placed = () => viewport.scrollToIndex.mock.lastCall; +const row = (event: EventData) => + document.querySelector(`[data-message-id="${event.id}"]`); +const navigationTo = (messageId: string) => + ({ + entryId: "visit", + target: { + version: 1, + kind: "conversation", + channelId: "c", + messageId, + scope: { + viewer: viewer.pubkey, + communityOrigin: "https://fixture.invalid", + }, + }, + signal: new AbortController().signal, + complete: vi.fn(() => true), + resolve: vi.fn(() => true), + forSession: vi.fn(), + position: vi.fn(), + savePosition: vi.fn(), + passThrough: () => () => {}, + }) as PageNavigation; + +it("mounts the reader bar above the scroller in one column, and draws the presented rows in ids order, then the host's again", () => { + const h = mount(); + const bar = screen.getByText("bar").parentElement as HTMLElement; + expect(scroller().contains(bar)).toBe(false); + expect(bar.parentElement).toBe(scroller().parentElement); + expect( + bar.compareDocumentPosition(scroller()) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + expect(drawn()).toEqual(["h0", "h1", "h2", "h3", "h4", "h5"]); + expect(h.present({ ids: [p1.id, h4.id, p0.id] })).toBe("shown"); + expect(drawn()).toEqual(["p1", "h4", "p0"]); + h.withdraw(); + expect(drawn()).toEqual(["h0", "h1", "h2", "h3", "h4", "h5"]); +}); + +it("keeps the in-flow tail while it presents", () => { + const h = mount(); + h.present({ ids: [p0.id] }); + expect(screen.getByText("typing tail")).toBeVisible(); +}); + +it("leaves the host's layout alone with no reader bar to hold", () => { + const h = mount(); + h.unmount(); + const bare = render( + false} + />, + ); + expect( + bare.container.querySelector("[data-channel-timeline]"), + ).not.toBeNull(); + expect(bare.container.firstElementChild).toBe( + bare.container.querySelector("[data-channel-timeline]"), + ); +}); + +it("builds no host for a transient timeline, so nothing can present to it", () => { + const h = mount({ props: { transient: true } }); + expect(screen.queryByText("bar")).toBeNull(); + expect(h.latest.current).toBeUndefined(); +}); + +it("pages the host's history as ever when nothing presents", () => { + const h = mount({ window: { hasMore: true } }); + fireEvent.click(screen.getByRole("button", { name: "Load older messages" })); + expect(h.loadOlder).toHaveBeenCalledTimes(1); + h.loadOlder.mockClear(); + fireEvent.wheel(scroller(), { deltaY: -100 }); + expect(h.loadOlder).toHaveBeenCalledTimes(1); +}); + +it("never pages the host's history while it presents: not by gesture, not by the edge button", () => { + const h = mount({ window: { hasMore: true } }); + h.present({ ids: [p0.id, p1.id] }); + expect( + screen.queryByRole("button", { name: "Load older messages" }), + ).toBeNull(); + fireEvent.wheel(scroller(), { deltaY: -100 }); + fireEvent.keyDown(scroller(), { key: "Home" }); + frame(); + expect(h.loadOlder).not.toHaveBeenCalled(); + h.withdraw(); + expect( + screen.getByRole("button", { name: "Load older messages" }), + ).toBeVisible(); +}); + +it("fills a short screen from older history only when nothing presents", () => { + vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(300); + const h = mount({ window: { hasMore: true } }); + for (let pass = 0; pass < 4; pass++) frame(); + expect(h.loadOlder).toHaveBeenCalled(); +}); + +it("shows the host's edge errors and limit notice only for the host's rows", () => { + const h = mount({ + window: { hasMore: true, error: "Could not load", historyLimited: true }, + }); + expect(screen.getByRole("alert")).toHaveTextContent("Could not load"); + expect(screen.getByText("History window limit reached")).toBeVisible(); + h.present({ ids: [p0.id] }); + expect(screen.queryByRole("alert")).toBeNull(); + expect(screen.queryByText("History window limit reached")).toBeNull(); +}); + +it("shows the channel intro under a presentation only when it is complete", () => { + const intro =

    Start of the channel

    ; + const h = mount({ props: { intro } }); + expect(screen.getByText("Start of the channel")).toBeVisible(); + h.present({ ids: [p0.id] }); + expect(screen.queryByText("Start of the channel")).toBeNull(); + h.present({ ids: [p0.id], complete: true }); + expect(screen.getByText("Start of the channel")).toBeVisible(); + // Not shown while the host's window has more above it either. + h.setWindow({ hasMore: true }); + expect(screen.getByText("Start of the channel")).toBeVisible(); + h.withdraw(); + expect(screen.queryByText("Start of the channel")).toBeNull(); +}); + +it("says nothing of an empty conversation for a presentation that shows no row", () => { + const h = mount({ rows: [] }); + expect(screen.getByText("No messages yet.")).toBeVisible(); + h.present({ ids: [] }); + expect(screen.queryByText("No messages yet.")).toBeNull(); +}); + +it("draws no day divider and merges no rows while it presents, and the host's again after it", () => { + const author = (name: string, at: number) => post(name, at); + const late = author("late", T + 3 * DAY); + const early = author("early", T + DAY); + const earlyNext = author("earlyNext", T + DAY + 60); + const earlyLast = author("earlyLast", T + DAY + 30); + named.set(late.id, "late"); + named.set(early.id, "early"); + named.set(earlyNext.id, "earlyNext"); + named.set(earlyLast.id, "earlyLast"); + const h = mount(); + h.present({ + ids: [late.id, early.id, earlyNext.id, earlyLast.id], + events: [late, early, earlyNext, earlyLast], + }); + expect(drawn()).toEqual(["late", "early", "earlyNext", "earlyLast"]); + // The order is the plugin's: a divider would date the wrong rows, and + // "earlyNext" would merge into "early" across whatever the plugin left out. + const marks = () => + [...document.querySelectorAll("li[data-message-id]")].map( + ({ dataset }) => + `${dataset.day ?? "-"} ${dataset.stacked ?? "-"} ${dataset.stackNext ?? "-"}`, + ); + expect(marks()).toEqual(["- - -", "- - -", "- - -", "- - -"]); + h.withdraw(); + // The host's six rows, one author a minute apart: one day, one bubble. + expect(marks()).toEqual([ + "true - true", + "- true true", + "- true true", + "- true true", + "- true true", + "- true -", + ]); +}); + +/** The nine updates one agent posted, as the chat folds them when it is the host's. */ +const updates = (count: number): ChannelMessage[] => + Array.from({ length: count }, (_, index) => ({ + id: `activity-${index}`, + channelId: "c", + authorId: "agent", + audience: "agents", + createdAt: 100 + index, + content: `Update ${index}`, + mentions: [], + attachments: [], + reactions: [], + participants: [], + replyCount: 0, + })); + +it("folds no agent activity under a presentation, and folds the host's again after it", () => { + const agentRows = updates(9); + const h = mount({ + rows: agentRows, + props: { chatPresentation: true }, + fold: () => agentRows, + }); + expect(screen.queryByText("Update 3")).toBeNull(); + expect( + screen.getByRole("button", { name: /Show activity history/ }), + ).toBeVisible(); + h.present({ ids: agentRows.map((agent) => agent.id), events: [] }); + expect(screen.getByText("Update 3")).toBeVisible(); + expect(screen.queryByRole("button", { name: /activity history/ })).toBeNull(); + h.withdraw(); + expect(screen.queryByText("Update 3")).toBeNull(); +}); + +it("draws no unread line, Jump or arrival count under a presentation, and counts none when it ends", () => { + const h = mount(); + frame(); + // Reading above the bottom: the Jump button shows. + scrolled = 0; + fireEvent.scroll(scroller()); + expect(scroller()).toHaveAttribute("data-jump-visible", "true"); + h.present({ ids: [p0.id, p1.id, p2.id] }); + frame(); + expect(scroller()).not.toHaveAttribute("data-jump-visible"); + expect(screen.getByText("Jump to latest").closest("[inert]")).not.toBeNull(); + // A live arrival while presented counts for no one. + h.withdraw(); + frame(); + expect(screen.getByText("Jump to latest")).toBeVisible(); + expect(screen.queryByText(/new message/)).toBeNull(); +}); + +it("holds the anchor row where it was when a presentation shows it", () => { + const h = mount(); + frame(); + scrolled = 250; // h2 is the first row in view, 50px above the edge. + h.present({ ids: [h5.id, h4.id, h3.id, h2.id, h1.id, h0.id] }); + expect(placed()).toEqual([3, { align: "start", offset: 50 }]); + h.withdraw(); + // Back in the host's order, the row at the top of the presented list. + expect(placed()?.[1]).toEqual({ align: "start", offset: expect.any(Number) }); +}); + +it("hands the place to the nearest row still shown when a filter hides the anchor", () => { + const h = mount(); + frame(); + scrolled = 250; // The anchor is h2. + h.present({ ids: [h0.id, h1.id, h3.id, h4.id] }); + // h3 takes h2's place, 50px above the edge. + expect(placed()).toEqual([2, { align: "start", offset: 50 }]); + expect(row(h3)).not.toBeNull(); +}); + +it("places the start of a presentation at the top", () => { + const h = mount(); + frame(); + scrolled = 250; + h.present({ ids: [p0.id, p1.id, p2.id], place: "start" }); + expect(placed()).toEqual([0, { align: "start", offset: -40 }]); +}); + +it("places a named row at the top of the view", () => { + const h = mount(); + frame(); + h.present({ ids: [p0.id, p1.id, p2.id], place: { id: p1.id } }); + const [index, options] = placed() as [number, { offset: number }]; + expect(index).toBe(1); + // No -0: the row sits exactly at the top. + expect(options.offset + 0).toBe(0); +}); + +it("follows the end when a withdraw finds no row the host also shows", () => { + const h = mount(); + frame(); + h.present({ ids: [p0.id, p1.id, p2.id] }); + frame(); + h.withdraw(); + expect(placed()).toEqual([5, { align: "end" }]); +}); + +it("returns the host's rows at the anchor on a withdraw, reading nothing from the host", () => { + const h = mount({ window: { hasMore: true } }); + frame(); + h.present({ ids: [h5.id, h4.id, h3.id, h2.id, h1.id, h0.id] }); + frame(); + scrolled = 250; // In the presented list: h3 is first in view. + h.withdraw(); + // h3 is the host's fourth row; it keeps its 50px. + expect(placed()).toEqual([3, { align: "start", offset: 50 }]); + expect(h.loadOlder).not.toHaveBeenCalled(); +}); + +it.each([false, true])( + "applies a place at the commit unless reader input comes first (input first: %s)", + (inputFirst) => { + const h = mount(); + frame(); + viewport.scrollToIndex.mockClear(); + // The presentation is made, and the reader acts before it commits. + act(() => { + h.latest.current?.present?.({ + events: [p0, p1], + ids: [p0.id, p1.id], + place: "start", + }); + if (inputFirst) fireEvent.wheel(scroller(), { deltaY: 100 }); + }); + expect(drawn()).toEqual(["p0", "p1"]); + expect(viewport.scrollToIndex.mock.calls.length > 0).toBe(!inputFirst); + }, +); + +it("draws a presentation's rows without shifting the reader when it ends where the host's rows do", () => { + const h = mount(); + frame(); + scrolled = 400; // Only the host's last two rows are in view. + viewport.first = 4; + h.present({ ids: [p0.id, h4.id, h5.id] }); + expect(viewport.shifts).not.toContain(true); +}); + +it("counts no arrivals when a presentation ends over rows the host holds", () => { + const h = mount(); + frame(); + scrolled = 250; + h.present({ ids: [h5.id, h4.id, h3.id, h2.id, h1.id, h0.id] }); + frame(); + h.withdraw(); + frame(); + expect(screen.queryByText(/new message/)).toBeNull(); +}); + +it("writes no saved place while it presents, and the host's place after it", () => { + const key = 'buzz-view.v1:["scope","scroll:c"]'; + const h = mount(); + frame(); + scrolled = 250; + h.present({ ids: [p0.id, p1.id, p2.id] }); + frame(); + fireEvent.scroll(scroller()); + h.unmount(); + expect(localStorage.getItem(key)).toBeNull(); + const again = mount(); + frame(); + scrolled = 250; + again.present({ ids: [h5.id, h4.id, h3.id, h2.id, h1.id, h0.id] }); + frame(); + again.withdraw(); + frame(); + again.unmount(); + // The place names a row of the host's, never a presented one. + const saved = JSON.parse(localStorage.getItem(key) ?? "null"); + expect(saved.anchor.id).toBe(h3.id); +}); + +it("saves the geometry of the rows shown, never filed as the host's, when it unmounts presenting", () => { + const first = mount(); + frame(); + first.unmount(); + // Control: a return with the same rows takes the saved sizes. + const second = mount({ again: first }); + expect(viewport.caches.at(-1)).toEqual([[], 40]); + second.present({ ids: [p0.id, p1.id] }); + second.unmount(); + // Sizes measured for the presented rows are wrong for the host's. + viewport.caches.length = 0; + mount({ again: first }); + expect(viewport.caches.at(-1)).toBeUndefined(); +}); + +it("yields a target the presentation leaves out: the navigation opens, and the plugin sees the target", () => { + const navigation = navigationTo(h1.id); + const h = mount({ props: { navigation } }); + h.present({ ids: [p0.id, p1.id] }); + expect(navigation.complete).toHaveBeenCalledWith({ status: "opened" }); + expect(h.latest.current?.targetId).toBe(h1.id); + h.withdraw(); + expect(h.latest.current?.targetId).toBe(h1.id); +}); + +it("leaves a target the presentation shows to the host's reveal", () => { + const navigation = navigationTo(p1.id); + const h = mount({ props: { navigation } }); + h.present({ ids: [p0.id, p1.id] }); + expect(navigation.complete).not.toHaveBeenCalled(); +}); + +it("reads only the rows shown while it is partial, and catches up at its end row once complete", () => { + const h = mount(); + expect(lastReading().partial).toBe(false); + expect(lastReading().endMessageId).toBeUndefined(); + expect(lastReading().latestMessageId).toBe(h5.id); + // Newest by time, last by position: the end the dwell catches up at. + h.present({ ids: [p2.id, p0.id, p1.id] }); + expect(lastReading().partial).toBe(true); + expect(lastReading().latestMessageId).toBe(p2.id); + expect(lastReading().endMessageId).toBe(p1.id); + const bar = screen.getByText("bar").parentElement; + expect(lastReading().controls?.current).toBe(bar); + h.present({ ids: [p2.id, p0.id, p1.id], complete: true }); + expect(lastReading().partial).toBe(false); + h.withdraw(); + expect(lastReading().endMessageId).toBeUndefined(); + expect(lastReading().latestMessageId).toBe(h5.id); +}); + +it("retires the presentation when the timeline goes: its hold is released", async () => { + const h = mount(); + h.present({ ids: [p0.id] }); + expect(h.retained).toEqual({ taken: 1, disposed: 0 }); + h.unmount(); + await act(async () => {}); + expect(h.retained).toEqual({ taken: 1, disposed: 1 }); +}); + +it("keeps a presentation through a StrictMode replay", async () => { + const h = mount({ + strict: true, + onProps: (props) => { + if (props.presentation === "none") + props.present?.({ ids: [p0.id], events: [p0] }); + }, + }); + await act(async () => {}); + expect(drawn()).toEqual(["p0"]); + expect(h.latest.current?.presentation).toBe("shown"); +}); diff --git a/src/features/messages/ChannelTimeline.restore.test.tsx b/src/features/messages/ChannelTimeline.restore.test.tsx index 9270e55a32..c66ea0af75 100644 --- a/src/features/messages/ChannelTimeline.restore.test.tsx +++ b/src/features/messages/ChannelTimeline.restore.test.tsx @@ -19,6 +19,11 @@ import { readView, writeView } from "../../shared/view-state"; import { MessageManagement } from "./MessageManagement"; import type { PageNavigation } from "../navigation/service"; import type { JsonValue } from "../navigation/targets"; +import type { + ComposerAccessoryProps, + ConversationExtensions, +} from "../conversation/contracts"; +import { eventDto } from "../relay/events"; // Real React lifecycle; only the virtualizer's imperative layout boundary is // modeled here. Browser journeys retain the actual same-message/4px contract. @@ -466,6 +471,7 @@ function boundaryFixture({ reading = false } = {}) { presented = true, // What the store reports instead of a ready, verified page. state: Partial = {}, + extensions?: ConversationExtensions, ) { const window: ChannelWindow = { channelId, @@ -492,6 +498,7 @@ function boundaryFixture({ reading = false } = {}) { viewer={viewer.pubkey} queries={session} window={window} + extensions={extensions} onOpenLink={() => false} /> ) : ( @@ -673,6 +680,59 @@ it("waits for entry and unread evidence before selecting a verified entry bounda expect(screen.queryByText("Own message", { exact: true })).not.toBeNull(); }); +it("draws no unread line while a presentation shows other rows, and draws it again after", async () => { + const h = boundaryFixture(); + const events = ["Read", "First unread", "Later unread"].map((text, index) => + message(h.peer, "c", text, index + 1), + ); + const [read, first, later] = events.map((event) => h.row(event)) as [ + ChannelMessage, + ChannelMessage, + ChannelMessage, + ]; + h.unreadIds.add(first.id); + h.unreadIds.add(later.id); + h.completeReadStateSnapshot(); + h.publish(); + let accessory: ComposerAccessoryProps | undefined; + const reader = (entries: readonly unknown[]) => ({ + snapshot: () => entries, + subscribe: () => () => {}, + }); + const extensions = { + inline: reader([]), + tools: reader([]), + accessories: reader([ + { + id: "arranger", + key: "test:arranger", + pluginId: "test", + revision: "one", + title: "Arranger", + placement: "reader", + component: (props: ComposerAccessoryProps) => { + accessory = props; + return null; + }, + }, + ]), + } as unknown as ConversationExtensions; + render(h.tree("c", [read, first, later], false, true, true, {}, extensions)); + await h.completeEntry(); + expect(divider()).toBeTruthy(); + act(() => { + accessory?.present?.({ + ids: [later.id, first.id, read.id], + events: events.map(eventDto), + }); + }); + expect(screen.queryByRole("separator", { name: "New messages" })).toBeNull(); + act(() => { + accessory?.present?.(null); + }); + expect(divider()).toBeTruthy(); +}); + const divider = () => screen.getByRole("separator", { name: "New messages" }); const precedes = (earlier: Node, later: Node) => !!(earlier.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING); diff --git a/src/features/messages/ChannelTimeline.test.tsx b/src/features/messages/ChannelTimeline.test.tsx index 6a802972e0..82f3dec29f 100644 --- a/src/features/messages/ChannelTimeline.test.tsx +++ b/src/features/messages/ChannelTimeline.test.tsx @@ -104,6 +104,7 @@ vi.mock("react", async (original) => ({ }, useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => snapshot(), + useEffectEvent: (callback: unknown) => callback, // Rendered outside a provider, as the timeline's direct calls are. useContext: () => undefined, })); diff --git a/src/features/messages/ChannelTimeline.tsx b/src/features/messages/ChannelTimeline.tsx index 57361c1836..baec38d114 100644 --- a/src/features/messages/ChannelTimeline.tsx +++ b/src/features/messages/ChannelTimeline.tsx @@ -20,7 +20,10 @@ import { useStableRowActivity, } from "./activity-presentation"; import { DayDivider } from "./MessageTimestamp"; +import { ComposerAccessories } from "../conversation/ComposerAccessories"; import type { ConversationExtensions } from "../conversation/contracts"; +import { CHANNEL_LIMITS } from "../relay/store"; +import { useArrangement, usePlace } from "./arrangement"; import type { RelaySession } from "../relay/session"; import type { MessageAttention } from "../relay/unread"; import { @@ -153,6 +156,9 @@ function subscribeDocumentActive(listener: () => void) { }; } const TIMELINE_PLACE = "timeline"; +// Activity folding reads list order as time: off while a presentation shows. +const NO_ROWS: readonly ChannelMessage[] = Object.freeze([]); +const readable = (row: ChannelMessage) => !row.membership && !row.huddle; // Older pages a visit reads unasked to fill a screen its head leaves empty. const FILL_PAGES = 5; function positionAt( @@ -280,8 +286,28 @@ function Timeline({ startsThreads = true, }: ChannelTimelineProps) { useMessageSelectionCopy(); - const shownIntro = - !window.hasMore && !window.historyLimited ? intro : undefined; + // A plugin's rows replace the host's while it presents. What reads the host's + // own history (its unread line, arrivals, paging) keeps the host's rows. + const [arrangement, display] = useArrangement({ + session: queries, + channelId, + rootId: undefined, + limits: CHANNEL_LIMITS, + channel: !transient, + }); + // A presentation's order is its own, so no row merges into another's bubble + // or sits under a day divider; each row's header carries its date. + const arranged = !!display; + // Read when a place is saved; a presentation's rows are not the reader's place. + const arrangedNow = useRef(false); + arrangedNow.current = arranged; + const shownIntro = ( + display + ? display.complete + : !window.hasMore && !window.historyLimited + ) + ? intro + : undefined; const [initialPosition] = useState(() => transient ? null @@ -306,7 +332,8 @@ function Timeline({ // A bottom place restores at the latest message; its row is noise. const place = position?.bottom ? { bottom: true } : position; const revision = JSON.stringify(place); - if (transient || revision === written.current) return; + if (transient || arrangedNow.current || revision === written.current) + return; if (writeView(scope, `scroll:${channelId}`, place)) written.current = revision; }, [channelId, scope, transient]); @@ -315,7 +342,10 @@ function Timeline({ // for them: the saved IndexedDB head precedes the network head and notice // rows. The reader follows the bottom meanwhile; their input retires it. const pendingRestore = useRef(undefined); - const profiles = useRowProfiles(queries.profiles, window.rows); + const profiles = useRowProfiles( + queries.profiles, + display?.rows ?? window.rows, + ); // Archived and read-only conversations have no composer to start one in. const composerless = useHeaderChannel( queries.channels, @@ -347,6 +377,11 @@ function Timeline({ () => membershipRows(visibleRows), [visibleRows], ); + const shownRows = display?.rows ?? visibleRows; + const rows = useMemo( + () => (display ? membershipRows(display.rows) : chronologicalRows), + [display, chronologicalRows], + ); const messageVisit = useMessageVisit(queries, channelId); const ownsMessageVisit = messageVisit !== undefined && messageVisit !== null; const [timelineVisit] = useState(() => ({})); @@ -737,6 +772,7 @@ function Timeline({ }); } const newMessageBoundaryId = + !arranged && boundaryMatchesVisit && newMessageBoundary.captured && messageVisit?.active === true && @@ -764,7 +800,7 @@ function Timeline({ }); }, []); const presentation = useActivityPresentation( - chronologicalRows, + arranged ? NO_ROWS : chronologicalRows, queries.agentActivity, agentPubkeys, ); @@ -792,12 +828,21 @@ function Timeline({ !!navigation?.traversal && lostPlace !== navigation.signal && navigation.position(TIMELINE_PLACE) !== undefined; - const targetId = + const requestedId = inlineTarget?.messageId ?? (navigation?.target.kind === "conversation" && !returning ? navigation.target.messageId : undefined); - const rows = chronologicalRows; + // A presentation may leave the opened message out: its reveal has nothing to + // show, so it yields (completing as opened) and the plugin sees `requestedId`. + const targetHidden = + arranged && + !!requestedId && + renderedRowIndex(rows, shownRows, requestedId) < 0; + const targetId = targetHidden ? undefined : requestedId; + useLayoutEffect(() => { + if (targetHidden) navigation?.complete({ status: "opened" }); + }, [targetHidden, navigation]); const lastPublicMessage = publicMessageNeighbor(rows, rows.length, -1); const intent = useRef(0); // Keep expansion pending with scroll restoration until the saved row arrives. @@ -874,7 +919,7 @@ function Timeline({ }, [rows, focusedActivityId]); // Only read at mount and unmount, so build it on demand. const signature = () => - `${geometrySignature(visibleRows, profiles, resolveName)}:${JSON.stringify([...foldedActivity].sort())}`; + `${geometrySignature(shownRows, profiles, resolveName)}:${JSON.stringify([...foldedActivity].sort())}`; // Mount the saved boundary before restoration measures its divider inset. const keptIndices = rows.flatMap((row, index) => row.id === focusedMessageId || @@ -892,6 +937,7 @@ function Timeline({ : [], ); const scroller = useRef(null); + const readerBar = useRef(null); const edge = useRef(null); const activityTail = useRef(null); useLayoutEffect(() => { @@ -912,7 +958,7 @@ function Timeline({ // history edge does not repeat the reason. Recovery does not retry older // history, and paging stops on a failed read, so Retry stays either way. const { recovering } = useRecovery(queries.recovery); - const edgeError = recovering ? undefined : window.error; + const edgeError = recovering || arranged ? undefined : window.error; // Keep pagination space through EOF so removing its control cannot change // Virtua's start margin in the same measurement cycle as a prepend. const [reserveHistorySpace, setReserveHistorySpace] = useState(false); @@ -938,12 +984,15 @@ function Timeline({ ids: ReadonlySet; floor: number; paging: boolean; + /** The presentation these rows belong to; undefined for the host's. */ + owner: number | undefined; }>({ order: [], containedOwners: new Map(), ids: new Set(), floor: 0, paging: false, + owner: undefined, }); // The reader's anchor row and its offset before this render's rows. const reader = useRef<{ id: string | undefined; top: number; y: number }>({ @@ -1210,7 +1259,7 @@ function Timeline({ if ( place.anchor && !place.bottom && - renderedRowIndex(rows, visibleRows, containedOwners.get(id) ?? id) < 0 + renderedRowIndex(rows, shownRows, containedOwners.get(id) ?? id) < 0 ) { setLostPlace(navigation.signal); return; @@ -1252,7 +1301,7 @@ function Timeline({ navigation, returning, rows, - visibleRows, + shownRows, containedOwners, activity, focusesTarget, @@ -1284,9 +1333,21 @@ function Timeline({ scroller, settled, restoring, - latestMessageId: window.rows - .filter((row) => !row.membership && !row.huddle) - .at(-1)?.id, + latestMessageId: (display + ? display.rows + .filter(readable) + .reduce( + (latest, row) => + !latest || row.createdAt > latest.createdAt ? row : latest, + undefined, + ) + : window.rows.filter(readable).at(-1) + )?.id, + // A presentation's list order is its own: the last row drawn is the end a + // dwell catches up at, and rows it leaves out stay unread. + endMessageId: display ? rows.filter(readable).at(-1)?.id : undefined, + partial: !!display && !display.complete, + controls: readerBar, // Reading before the entry boundary settles would erase the evidence it // waits for: catch-up reads every loaded row and observe the unread ones, // and either advances the read revision that settles it with no line. @@ -1302,6 +1363,50 @@ function Timeline({ !boundaryCandidate.awaitingRepair && !(awayPending && !boundaryPending), }); + // Where the reader was when the rows changed owner: kept, or sent to an end by + // the presentation's `place`. Applied once, before the hold effect reads it. + const placement = usePlace(arrangement, () => { + const element = scroller.current; + const anchor = element ? positionAt(element).anchor : undefined; + return ( + anchor && { id: anchor.id, top: anchor.y, order: edges.current.order } + ); + }); + const owner = display?.revision; + const swapped = edges.current.owner !== owner; + useLayoutEffect(() => { + // A presentation made in this commit's layout effects reaches its rows in the next. + if (arrangement?.snapshot() !== display || !rows.length) return; + const ids = new Set(rows.map((row) => row.id)); + const at = placement.take( + (id) => ids.has(id), + owner === undefined ? "end" : "start", + ); + if (!at) return; + placement.done(); + const index = + at === "end" + ? rows.length - 1 + : at === "start" + ? 0 + : rows.findIndex((row) => row.id === at.id); + const y = at === "start" ? size.edgeHeight : at === "end" ? 0 : at.top; + intent.current++; + savedPosition.current = + at === "end" + ? { bottom: true } + : { bottom: false, anchor: { id: rows[index]?.id ?? "", y } }; + pendingRestore.current = at === "end" ? undefined : intent.current; + follow.current = at === "end"; + settled.current = false; + restoredAnchor.current = undefined; + measuredPosition.current = null; + // Before paint; positioning then keeps it through late measurement. + handle.current?.scrollToIndex( + index, + at === "end" ? { align: "end" } : { align: "start", offset: -y }, + ); + }, [arrangement, display, owner, rows, placement, size.edgeHeight]); // Shift keeps the distance from the end, so it holds the reader only while // the rows from their first visible item to the end are kept. Relay pages // break same-second ties by id, rows by send time: a page can land below the @@ -1326,6 +1431,7 @@ function Timeline({ y: retained?.y ?? savedPosition.current?.anchor?.y ?? 0, }; const prepend = + !swapped && !!previous.length && (previous[0] !== rows[0]?.id || rows.length !== previous.length) && reading.every( @@ -1648,9 +1754,13 @@ function Timeline({ ids: new Set(rows.map((row) => row.id)), floor: rows[0]?.createdAt ?? 0, paging: loadingOlder.current, + owner, }; + // Another row set's arrivals are not the reader's: none in the commit that + // changes owner. A presentation's own ids are fixed until it presents again. if ( arrivals > 0 && + !swapped && previousIds.size > 0 && !follow.current && (!targetId || revealedSignal === targetSignal) @@ -1696,7 +1806,7 @@ function Timeline({ const restoreIndex = anchor ? renderedRowIndex( rows, - visibleRows, + shownRows, containedOwners.get(anchor.id) ?? anchor.id, ) : -1; @@ -1831,7 +1941,7 @@ function Timeline({ }; }, [ rows, - visibleRows, + shownRows, size, prepend, recordPosition, @@ -1842,6 +1952,8 @@ function Timeline({ revealMessageId, containedOwners, newMessageBoundaryId, + swapped, + owner, ]); // After positioning reads it: a load that ends without rows lands no page. useLayoutEffect(() => { @@ -1851,6 +1963,7 @@ function Timeline({ (element: HTMLElement, resume = false) => { olderDemand.current = false; if ( + arranged || !handle.current || !userScrolled.current || window.status !== "ready" || @@ -1878,7 +1991,7 @@ function Timeline({ !after.historyLimited && !after.error; }, - [window, queries, channelId], + [window, queries, channelId, arranged], ); useLayoutEffect(() => { if (olderDemand.current && scroller.current) @@ -1894,6 +2007,7 @@ function Timeline({ const element = scroller.current; if ( !element || + arranged || !settled.current || !follow.current || pendingRestore.current === intent.current || @@ -1923,6 +2037,7 @@ function Timeline({ targetId, targetSignal, revealedSignal, + arranged, ]); // After positioning's frame, and again once Virtua measures estimated rows. const scheduleFill = useCallback(() => { @@ -1945,6 +2060,7 @@ function Timeline({ }; }, [scheduleFill, size]); const gesture = (upward = false) => { + placement.cancel(); const restoring = pendingRestore.current === intent.current; restoredAnchor.current = undefined; layoutCorrection.current = false; @@ -1983,7 +2099,7 @@ function Timeline({ data-channel-timeline={channelId} data-activity-history-scope="" data-buzz-launch-pending={launchPending ? "settling" : undefined} - data-jump-visible={showJumpToLatest || undefined} + data-jump-visible={(!arranged && showJumpToLatest) || undefined} onWheel={(event) => gesture(event.deltaY < 0 && !event.ctrlKey)} onTouchStart={(event) => { touchY.current = event.touches[0]?.clientY; @@ -2081,7 +2197,7 @@ function Timeline({ > {shownIntro} {edgeError && {edgeError}} - {window.historyLimited ? ( + {arranged ? null : window.historyLimited ? ( History window limit reached ) : window.hasMore && queries.channels.cachedOnly ? ( You can load older messages once Buzz reconnects. @@ -2107,7 +2223,7 @@ function Timeline({ ) : null} @@ -2156,10 +2272,10 @@ function Timeline({ ? rows[index + 1] : publicMessageNeighbor(rows, index, 1); const day = - index === 0 - ? true - : calendarDay(rows[index - 1]?.createdAt ?? 0) !== - calendarDay(row.createdAt); + !arranged && + (index === 0 || + calendarDay(rows[index - 1]?.createdAt ?? 0) !== + calendarDay(row.createdAt)); const renderMessage = (row: ChannelMessage, inside = false) => { return ( )} - {!rows.length && + {!arranged && + !rows.length && !shownIntro && !window.hasMore && window.status === "ready" && @@ -2329,7 +2449,7 @@ function Timeline({ session={queries} channelId={channelId} previousAuthor={ - lastPublicMessage && !lastPublicMessage.membership + !arranged && lastPublicMessage && !lastPublicMessage.membership ? lastPublicMessage.authorId : undefined } @@ -2341,5 +2461,29 @@ function Timeline({ ); - return {feed}; + return ( + + {arrangement && extensions?.accessories ? ( +
    + {/* Above the scroller, never inside it. */} +
    + canOpenLink?.(target) ?? false} + open={onOpenLink} + /> +
    + {feed} +
    + ) : ( + feed + )} +
    + ); } diff --git a/src/features/messages/Messages.module.css b/src/features/messages/Messages.module.css index 1d66add834..b9fdaf6a10 100644 --- a/src/features/messages/Messages.module.css +++ b/src/features/messages/Messages.module.css @@ -5,6 +5,8 @@ position: relative; container-type: inline-size; container-name: messages; + /* The reader bar aligns with the thread's narrower message inset. */ + --reader-bar-inset: var(--space-4); min-width: 0; min-height: 0; overflow: hidden; @@ -19,6 +21,27 @@ box-shadow: none; background: transparent; } +/* Plugin controls above a reader's messages, outside their scroller, inset as + the messages are. */ +.readerBar { + display: flex; + flex: none; + flex-wrap: wrap; + align-items: center; + gap: var(--space-1) var(--space-2); + padding: var(--space-1) var(--reader-bar-inset, var(--space-panel-inset)); +} +.readerBar:empty { + display: none; +} +/* A channel timeline with its reader bar above the scroller. */ +.timelineColumn { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + min-height: 0; +} .feed { --message-hover-inset: var(--space-panel-inset); --timeline-measure: var(--buzz-message-width, 52rem); diff --git a/src/features/messages/ThreadPanel.arranger.test.tsx b/src/features/messages/ThreadPanel.arranger.test.tsx new file mode 100644 index 0000000000..266476a75e --- /dev/null +++ b/src/features/messages/ThreadPanel.arranger.test.tsx @@ -0,0 +1,269 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { Context } from "@deepseek-ai/cordis"; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import React from "react"; +import { afterEach, beforeAll, beforeEach, expect, it, vi } from "vitest"; +import { + threadFixture, + type Fixture, +} from "../../../tests/fixtures/conversation-arranger/fixtures"; +import * as arranger from "../../../tests/fixtures/conversation-arranger/plugin"; +import { + CHANNEL, + createWorld, + openSession, +} from "../../../tests/fixtures/conversation-arranger/relay"; +import type { PluginModule } from "../../plugins/api"; +import { PluginRuntime } from "../../plugins/runtime"; +import type { ConversationExtensions } from "../conversation/contracts"; +import { ConversationService } from "../conversation/service"; +import type { RelayEvent } from "../relay/events"; +import type { MessageComposerProps } from "./MessageComposer"; +import type { MessageRowProps } from "./MessageRow"; +import { nearestShown } from "./arrangement"; +import { ThreadPanel } from "./ThreadPanel"; +import type { Reading } from "./use-reading"; + +// The arranger plugin in the real thread panel: a real session over a fixture +// relay, the host's own thread view, and the real reader. Rows are cheap +// stand-ins, so the timings here are the reader's, not a row's own cost. + +type ReadingProps = Parameters[0]; +const readingProps: ReadingProps[] = []; +vi.mock("./use-reading", () => ({ + Reading: (props: ReadingProps) => { + readingProps.push(props); + return null; + }, + readingPositioned: () => {}, +})); +vi.mock("./TypingIndicator", () => ({ + TypingIndicator: () => null, + useLiveConversationAgents: () => [], +})); +vi.mock("./MessageRow", () => ({ + MessageRow: ({ row }: MessageRowProps) => ( +
    + {row.content} +
    + ), +})); +vi.mock("./MessageComposer", () => ({ + MessageComposer: ({ replyContext }: MessageComposerProps) => ( +
    {replyContext}
    + ), +})); + +let thread: Fixture & { root: RelayEvent }; +let small: Fixture & { root: RelayEvent }; +beforeAll(async () => { + thread = await threadFixture(); + small = await threadFixture(100); +}, 60_000); + +const cleanups: (() => Promise | unknown)[] = []; +let scrolled = 0; +afterEach(async () => { + cleanup(); + vi.restoreAllMocks(); + readingProps.length = 0; + delete (HTMLElement.prototype as Partial).scrollTop; + for (const dispose of cleanups.splice(0)) await dispose(); +}); +/** Rows lay out 100px apart in the order drawn, the first at 100. */ +beforeEach(() => { + scrolled = 0; + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + disconnect() {} + }, + ); + HTMLElement.prototype.scrollIntoView = vi.fn(); + HTMLElement.prototype.scrollTo = vi.fn(); + vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(600); + vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue( + 40_000, + ); + Object.defineProperty(HTMLElement.prototype, "scrollTop", { + configurable: true, + get: () => scrolled, + set(value: number) { + scrolled = Math.max(0, Math.min(value, 39_400)); + }, + }); + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation( + function (this: HTMLElement) { + if (this.dataset.messageId === undefined) + return new DOMRect(0, 0, 500, 600); + const at = rowIds().indexOf(this.dataset.messageId); + return new DOMRect(0, (at < 0 ? 0 : 100 * (at + 1)) - scrolled, 500, 50); + }, + ); +}); + +const rowIds = () => + [ + ...document.querySelectorAll( + "[data-thread-rows] ol [data-message-id]", + ), + ].map((row) => row.dataset.messageId ?? ""); +/** Every message drawn, in order, root first. */ +const drawn = () => + [...document.querySelectorAll("[data-thread-rows] article")].map( + (row) => row.dataset.messageId ?? "", + ); +const lastReading = () => readingProps.at(-1) as ReadingProps; + +const PLUGIN = { + manifest: { id: "test.arranger", name: "Arranger", apiVersion: 1 as const }, + enabled: true, + source: "external" as const, + revision: "one", + previous: null, + reloadable: true, + error: null, +}; + +async function mount(messageId: string, fixture = thread) { + const relay = openSession({ world: createWorld(fixture.events) }); + const module: PluginModule = { + inject: ["react", "conversation"], + apply: (ctx) => arranger.apply(ctx as never), + }; + const root = new Context(); + root.provide("react", React); + const runtime = new PluginRuntime(root, async () => module); + const service = new ConversationService(root); + runtime.reconcile([PLUGIN]); + await waitFor(() => expect(service.accessories.snapshot()).toHaveLength(1)); + render( + {}} + active + onOpenLink={() => false} + extensions={ + { + accessories: service.accessories, + } as unknown as ConversationExtensions + } + />, + ); + cleanups.push(async () => { + cleanup(); + await runtime.dispose(); + await root.fiber.dispose(); + relay.owner.dispose(); + }); + return { relay }; +} +/** The arranger's own status line, apart from the panel's. */ +const barStatus = () => + screen + .getByRole("toolbar", { name: "Arrange rows" }) + .querySelector("[role=status]")?.textContent; +/** The host's own rows, once its reads have stopped. */ +const hostRows = async (relay: { reads: readonly unknown[] }) => { + await waitFor(() => expect(rowIds().length).toBeGreaterThan(0)); + for (let before = -1; before !== relay.reads.length; ) { + before = relay.reads.length; + await act(() => new Promise((done) => setTimeout(done, 300))); + } +}; +/** Top's 200 rows and the one row the reader was opened to. */ +const shownTop = () => + waitFor(() => expect(barStatus()).toBe("Replies 1–200 of 1,899"), { + timeout: 30_000, + }); + +it("opens a thread at a row the host never loaded, ranks by Top, and leaves the row first with the reader on it", async () => { + const { root, groups } = thread; + const target = (groups.one ?? [])[0] as string; + const { relay } = await mount(target); + await hostRows(relay); + // Not one of the host's rows, nor will Top rank it among the first 200. + fireEvent.click(screen.getByRole("button", { name: "Top" })); + await shownTop(); + const rows = drawn(); + expect(rows[0]).toBe(root.id); + expect(rows[1]).toBe(target); + expect(rows).toHaveLength(202); + expect(scrolled).toBe(100); + // Reading takes only what is drawn: a partial list, read through its last row. + expect(lastReading()).toMatchObject({ + partial: true, + endMessageId: rows.at(-1), + }); +}, 30_000); + +it("returns the host's rows when withdrawn, at the row it was reading or the nearest one still shown, with no host read", async () => { + const { root, groups } = thread; + const target = (groups.one ?? [])[0] as string; + const { relay } = await mount(target); + await hostRows(relay); + fireEvent.click(screen.getByRole("button", { name: "Top" })); + await shownTop(); + // Reading the first row of the list, 20px below the top edge. + scrolled = 80; + const order = rowIds(); + const anchor = { id: order[0] as string, top: 20, order }; + const reads = relay.reads.length; + fireEvent.click(screen.getByRole("button", { name: "Buzz order" })); + expect(barStatus()).toBe(""); + // Placing a row inside a closed branch opens the branch: wait until the rows + // and the place stop moving. + let last = ""; + await waitFor( + () => { + const now = `${rowIds().join()}@${scrolled}`; + const settled = now === last; + last = now; + expect(settled).toBe(true); + }, + { interval: 100 }, + ); + const host = rowIds(); + expect(drawn()[0]).toBe(root.id); + expect(host).not.toContain(order.at(-1)); + expect(relay.reads).toHaveLength(reads); + // The row it was reading if the host shows it, else the nearest that it shows, + // else the end. + const near = nearestShown(anchor, (id) => host.includes(id)); + expect(scrolled).toBe( + near === undefined ? 39_400 : 100 * (host.indexOf(near) + 1) - 20, + ); + expect(lastReading()).toMatchObject({ + partial: false, + endMessageId: undefined, + }); +}, 30_000); + +it("reads a thread it shows whole through to its last row", async () => { + const { relay } = await mount(small.root.id, small); + await hostRows(relay); + fireEvent.click(screen.getByRole("button", { name: "Top" })); + await waitFor(() => expect(barStatus()).toMatch(/^Replies 1–\d+ of \d+$/), { + timeout: 30_000, + }); + // The list holds every reply: reaching its end reads the thread. + expect(lastReading()).toMatchObject({ + partial: false, + endMessageId: drawn().at(-1), + }); + fireEvent.click(screen.getByRole("button", { name: "Buzz order" })); + expect(lastReading().endMessageId).toBeUndefined(); +}, 30_000); diff --git a/src/features/messages/ThreadPanel.presentation.test.tsx b/src/features/messages/ThreadPanel.presentation.test.tsx new file mode 100644 index 0000000000..2d0a9ee62e --- /dev/null +++ b/src/features/messages/ThreadPanel.presentation.test.tsx @@ -0,0 +1,699 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; +import { StrictMode, useLayoutEffect } from "react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import type { Contribution } from "../../plugins/contributions"; +import type { + ComposerAccessory, + ComposerAccessoryProps, + ConversationExtensions, + ConversationPresentation, + PresentResult, +} from "../conversation/contracts"; +import type { ChannelMessage } from "../relay/contracts"; +import { eventDto, type EventData, type RelayEvent } from "../relay/events"; +import type { LiveCallbacks } from "../relay/live"; +import { createRelaySession, type RelaySession } from "../relay/session"; +import type { ThreadSnapshot, ThreadView } from "../relay/threads"; +import { keypair, message, roster, scriptedTransport } from "../relay/testing"; +import type { PageNavigation } from "../navigation/service"; +import type { MessageComposerProps } from "./MessageComposer"; +import type { MessageRowProps } from "./MessageRow"; +import { ThreadPanel, type ThreadPanelProps } from "./ThreadPanel"; +import type { Reading } from "./use-reading"; + +type ReadingProps = Parameters[0]; +const readingProps: ReadingProps[] = []; +vi.mock("./use-reading", () => ({ + Reading: (props: ReadingProps) => { + readingProps.push(props); + return null; + }, + readingPositioned: () => {}, +})); +vi.mock("./TypingIndicator", () => ({ + TypingIndicator: () => null, + useLiveConversationAgents: () => [], +})); +vi.mock("./MessageRow", () => ({ + MessageRow: ({ row, onReply, day, stackPrevious }: MessageRowProps) => ( +
    + {row.content} + +
    + ), +})); +vi.mock("./MessageComposer", () => ({ + MessageComposer: ({ replyParentId, replyContext }: MessageComposerProps) => ( +
    + {replyContext} +
    + ), +})); + +const viewer = keypair(); +const other = keypair(); +const relay = keypair(); +const T = 1_700_000_000; +const DAY = 86_400; +const proven = (event: RelayEvent): EventData => eventDto(event); +const root = proven(message(other, "c", "root", T)); +const replyEvent = (name: string, at: number): EventData => + proven(message(other, "c", name, at, [["e", root.id, "", "reply"]])); +// The plugin's rows; the host's own view never loads them. +const [a, b, c, d] = ["a", "b", "c", "d"].map((name, index) => + replyEvent(name, T + 10 + index), +) as [EventData, EventData, EventData, EventData]; +const named = new Map( + [root, a, b, c, d].map((event) => [event.id, event.content]), +); + +const owners: ReturnType[] = []; +afterEach(() => { + cleanup(); + for (const owner of owners.splice(0)) owner.dispose(); + readingProps.length = 0; + vi.restoreAllMocks(); + vi.useRealTimers(); + delete (HTMLElement.prototype as Partial).scrollTop; +}); + +/** Rows lay out 100px apart in the order drawn, the first at 100. */ +let scrolled = 0; +beforeEach(() => { + scrolled = 0; + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + disconnect() {} + }, + ); + HTMLElement.prototype.scrollIntoView = vi.fn(); + HTMLElement.prototype.scrollTo = vi.fn(); + vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(600); + vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(4000); + Object.defineProperty(HTMLElement.prototype, "scrollTop", { + configurable: true, + get: () => scrolled, + set(value: number) { + scrolled = Math.max(0, Math.min(value, 3400)); + }, + }); + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation( + function (this: HTMLElement) { + if (this.dataset.messageId === undefined) + return new DOMRect(0, 0, 500, 600); + const at = [ + ...document.querySelectorAll("[data-thread-rows] ol [data-message-id]"), + ].indexOf(this); + return new DOMRect(0, (at < 0 ? 0 : 100 * (at + 1)) - scrolled, 500, 50); + }, + ); +}); + +const readerEntry = ( + component: Contribution["component"], +): Contribution => ({ + id: "arranger", + key: "test:arranger", + pluginId: "test", + revision: "one", + title: "Arranger", + placement: "reader", + component, +}); + +function mount({ + replies = [], + snapshot = {}, + props = {}, + strict = false, + onProps, + navigation, + unread = {}, +}: { + /** What the host's own view loaded. */ + replies?: readonly EventData[]; + snapshot?: Partial; + props?: Partial; + strict?: boolean; + /** Runs in the accessory's layout effect, as a plugin presenting at mount. */ + onProps?: (props: ComposerAccessoryProps) => void; + navigation?: PageNavigation; + /** Replaces parts of the session's unread owner. */ + unread?: Partial>; +} = {}) { + const wire = scriptedTransport(viewer.pubkey, relay.pubkey); + let callbacks!: LiveCallbacks; + const owner = createRelaySession( + { + ...wire.transport, + subscribe(next) { + callbacks = next; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { outboxStorage: { load: () => [], save() {} } }, + ); + owners.push(owner); + owner.session.channels.ensure("c"); + callbacks.receive([roster(relay, "c", [viewer.pubkey], T)]); + const rowsOf = (events: readonly EventData[]): readonly ChannelMessage[] => + owner.session.foldRows("c", events, root.id); + const [rootRow] = rowsOf([root]) as [ChannelMessage]; + let published: ThreadSnapshot = { + status: "ready", + root: rootRow, + replies: rowsOf([root, ...replies]).filter((row) => row.id !== root.id), + error: undefined, + canLoadMore: false, + limited: false, + direction: "older", + ...snapshot, + }; + const listeners = new Set<() => void>(); + const view = { + snapshot: () => published, + subscribe: (listener: () => void) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + refresh: vi.fn(async () => {}), + loadMore: vi.fn(async () => {}), + retarget: vi.fn(async () => "selected" as const), + dispose: vi.fn(), + } satisfies ThreadView; + const thread = vi.fn(() => view); + const session = { + ...owner.session, + thread, + unread: { ...owner.session.unread, ...unread }, + } as RelaySession; + const latest: { current?: ComposerAccessoryProps } = {}; + const registry = { + snapshot: () => entries, + subscribe: () => () => {}, + }; + const entries = [ + readerEntry((accessory) => { + latest.current = accessory; + // Every commit, as a plugin reacting to whatever else changed. + useLayoutEffect(() => { + onProps?.(accessory); + }); + return bar; + }), + ]; + const element = ( + {}} + active + onOpenLink={() => false} + extensions={ + { accessories: registry } as unknown as ConversationExtensions + } + navigation={navigation} + {...props} + /> + ); + render(strict ? {element} : element); + return { + view, + thread, + session, + latest, + rowsOf, + /** The host's view publishes a new state. */ + publish(next: Partial) { + published = { ...published, ...next }; + act(() => { + for (const listener of listeners) listener(); + }); + }, + present( + presentation: Partial & { + ids: readonly string[]; + }, + ) { + let result: PresentResult | undefined; + act(() => { + result = latest.current?.present?.({ + events: [a, b, c, d], + ...presentation, + }); + }); + return result; + }, + withdraw() { + act(() => { + latest.current?.present?.(null); + }); + }, + }; +} +/** The messages drawn, in order, root first. */ +const drawn = () => + [...document.querySelectorAll("[data-thread-rows] article")].map( + (row) => named.get(row.dataset.messageId ?? "") ?? row.dataset.messageId, + ); +const scroller = () => screen.getByRole("region", { name: "Thread messages" }); +const lastReading = () => readingProps.at(-1) as ReadingProps; +const navigationTo = (messageId: string) => + ({ + entryId: "visit", + target: { + version: 1, + kind: "conversation", + channelId: "c", + messageId, + threadRootId: root.id, + scope: { + viewer: viewer.pubkey, + communityOrigin: "https://fixture.invalid", + }, + }, + signal: new AbortController().signal, + complete: vi.fn(() => true), + resolve: vi.fn(() => true), + forSession: vi.fn(), + position: vi.fn(), + savePosition: vi.fn(), + passThrough: () => () => {}, + }) as PageNavigation; + +it("mounts the reader bar outside the composer, so a read-only thread has it too", () => { + mount({ props: { soloConversation: true } }); + expect(screen.queryByRole("region", { name: "Composer" })).toBeNull(); + const bar = screen.getByText("bar").parentElement as HTMLElement; + expect(lastReading().controls?.current).toBe(bar); + // Above the messages, outside their scroller. + expect(scroller().contains(bar)).toBe(false); + expect( + bar.compareDocumentPosition(scroller()) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); +}); + +it("draws the presented replies in ids order under the root, then the host's again", () => { + const h = mount({ replies: [d] }); + expect(drawn()).toEqual(["root", "d"]); + expect(h.present({ ids: [c.id, a.id, b.id] })).toBe("shown"); + expect(drawn()).toEqual(["root", "c", "a", "b"]); + expect(h.latest.current?.presentation).toBe("shown"); + h.withdraw(); + expect(drawn()).toEqual(["root", "d"]); +}); + +it("nests rows under their display parents, opening the branches it lists once each", () => { + const h = mount(); + h.present({ + ids: [a.id, b.id, c.id], + parents: { [b.id]: a.id, [c.id]: b.id }, + }); + // Branches start closed. + expect(drawn()).toEqual(["root", "a"]); + h.present({ + ids: [a.id, b.id, c.id], + parents: { [b.id]: a.id, [c.id]: b.id }, + open: [a.id], + }); + expect(drawn()).toEqual(["root", "a", "b"]); + h.present({ + ids: [a.id, b.id, c.id], + parents: { [b.id]: a.id, [c.id]: b.id }, + open: [a.id, b.id], + }); + expect(drawn()).toEqual(["root", "a", "b", "c"]); + // The reader's own collapse stands when a presentation lists it again. + fireEvent.click(screen.getByRole("button", { name: /Collapse 2 replies/ })); + expect(drawn()).toEqual(["root", "a"]); + h.present({ + ids: [a.id, b.id, c.id], + parents: { [b.id]: a.id, [c.id]: b.id }, + open: [a.id, b.id], + }); + expect(drawn()).toEqual(["root", "a"]); + // Until it stops listing the branch and lists it anew. + h.present({ ids: [a.id, b.id, c.id], parents: { [b.id]: a.id } }); + h.present({ + ids: [a.id, b.id, c.id], + parents: { [b.id]: a.id }, + open: [a.id], + }); + expect(drawn()).toEqual(["root", "a", "b", "c"]); +}); + +it("puts a row with an unknown or later parent at the top level", () => { + const h = mount(); + h.present({ + ids: [a.id, b.id, c.id], + parents: { [a.id]: b.id, [b.id]: "ghost" }, + }); + expect(drawn()).toEqual(["root", "a", "b", "c"]); +}); + +it("never loads more of the host's history while it presents", () => { + const unreadIds = new Set([d.id]); + const h = mount({ + snapshot: { canLoadMore: true, readKind: "older" }, + unread: { + attention: (_channel: string, id: string) => ({ + unread: unreadIds.has(id), + forced: false, + }), + threadReadThrough: () => -1, + }, + }); + h.present({ ids: [a.id, b.id] }); + // The older page lands. With unread known in the host's rows, the unread + // line would page back to find its place. + h.publish({ replies: h.rowsOf([root, d]).slice(1), readKind: undefined }); + fireEvent.wheel(scroller(), { deltaY: -100 }); + fireEvent.keyDown(scroller(), { key: "Home" }); + expect(h.view.loadMore).not.toHaveBeenCalled(); + // The decision is made without it, so the reader is not left waiting. + expect(scroller()).not.toHaveAttribute("data-positioning"); + expect(drawn()).toEqual(["root", "a", "b"]); +}); + +it("pages the host's history as ever when nothing presents", () => { + const h = mount({ + replies: [d], + snapshot: { canLoadMore: true }, + unread: { + attention: () => ({ unread: true, forced: false }), + threadReadThrough: () => -1, + }, + }); + expect(h.view.loadMore).toHaveBeenCalled(); +}); + +it("does not page a legacy traversal while it presents", () => { + const h = mount({ snapshot: { direction: "forward", canLoadMore: true } }); + expect(h.view.loadMore).toHaveBeenCalled(); + h.view.loadMore.mockClear(); + h.present({ ids: [a.id] }); + h.publish({ canLoadMore: true }); + expect(h.view.loadMore).not.toHaveBeenCalled(); +}); + +it("leaves out the unread line and the earlier-reply note while it presents", () => { + const orphan: EventData = proven( + message(other, "c", "orphan", T + 20, [ + ["e", root.id, "", "root"], + ["e", "f".repeat(64), "", "reply"], + ]), + ); + named.set(orphan.id, "orphan"); + const h = mount({ + replies: [orphan], + unread: { + attention: (_channel: string, id: string) => ({ + unread: id === orphan.id, + forced: false, + }), + }, + }); + expect( + screen.getByText("Earlier reply unavailable in loaded history."), + ).toBeVisible(); + expect(document.querySelector("[data-new-messages-boundary]")).not.toBeNull(); + // The same row, shown by a plugin. + h.present({ ids: [orphan.id, a.id], events: [orphan, a] }); + expect(drawn()).toEqual(["root", "orphan", "a"]); + expect( + screen.queryByText("Earlier reply unavailable in loaded history."), + ).toBeNull(); + expect(document.querySelector("[data-new-messages-boundary]")).toBeNull(); + h.withdraw(); + expect(document.querySelector("[data-new-messages-boundary]")).not.toBeNull(); +}); + +it("draws no day divider and merges no rows while it presents", () => { + const later = replyEvent("later", T + 2 * DAY); + const early = replyEvent("early", T + 60); + const soon = replyEvent("soon", T + 120); + named.set(later.id, "later"); + named.set(early.id, "early"); + named.set(soon.id, "soon"); + const h = mount(); + h.present({ + ids: [later.id, early.id, soon.id], + events: [later, early, soon], + }); + // The order is the plugin's: a divider would date the wrong rows, and + // "soon" would merge into "early" across whatever the plugin left out. + for (const name of ["later", "early", "soon"]) { + const row = screen.getByText(name).closest("article") as HTMLElement; + expect(row).not.toHaveAttribute("data-day"); + expect(row).not.toHaveAttribute("data-stack-previous"); + } +}); + +it("replies to a presented row the host never loaded", () => { + const h = mount(); + h.present({ ids: [a.id] }); + fireEvent.click(screen.getByRole("button", { name: "Reply to a" })); + expect(screen.getByRole("region", { name: "Composer" })).toHaveAttribute( + "data-parent", + a.id, + ); + expect(screen.queryByText("Reply target is no longer available.")).toBeNull(); + expect(screen.getByText(/Replying to/)).toBeVisible(); + h.withdraw(); + // Its row is gone with the presentation, as any vanished target is. + expect( + screen.getByText("Reply target is no longer available."), + ).toBeVisible(); +}); + +it("hides the jump button and keeps the arrivals count off while it presents", () => { + const h = mount({ replies: [d] }); + h.present({ ids: [a.id, b.id] }); + act(() => { + scrolled = 1000; + fireEvent.scroll(scroller()); + }); + expect(screen.queryByRole("button", { name: /Jump to latest/ })).toBeNull(); + expect(scroller()).not.toHaveAttribute("data-jump-visible"); + h.withdraw(); + act(() => { + scrolled = 1000; + fireEvent.scroll(scroller()); + }); + expect(screen.getByRole("button", { name: /Jump to latest/ })).toBeVisible(); +}); + +it("yields a target it does not show: the visit opens, reading starts and the plugin sees the id", () => { + const navigation = navigationTo(d.id); + const h = mount({ + replies: [d], + navigation, + props: { messageId: d.id }, + snapshot: { targetStatus: "loading" }, + }); + expect(h.latest.current?.targetId).toBe(d.id); + expect(navigation.complete).not.toHaveBeenCalled(); + h.present({ ids: [a.id, b.id] }); + expect(navigation.complete).toHaveBeenCalledExactlyOnceWith({ + status: "opened", + }); + expect(lastReading().settled.current).toBe(true); + expect(drawn()).toEqual(["root", "a", "b"]); +}); + +it("shows activity rows as the plugin lists them, unfolded", () => { + const step = (name: string, at: number) => { + const event = proven( + message(other, "c", name, at, [ + ["e", root.id, "", "reply"], + ["audience", "agents"], + ]), + ); + named.set(event.id, name); + return event; + }; + const [one, two] = [step("one", T + 30), step("two", T + 31)] as [ + EventData, + EventData, + ]; + const h = mount({ replies: [one, two] }); + const folded = screen.queryAllByRole("button", { name: /activity history/i }); + expect(folded).not.toHaveLength(0); + h.present({ ids: [two.id, one.id], events: [one, two] }); + expect(drawn()).toEqual(["root", "two", "one"]); + expect( + screen.queryAllByRole("button", { name: /activity history/i }), + ).toHaveLength(0); +}); + +it("starts reading when an inline reveal's row is not shown", () => { + const h = mount({ + replies: [d], + props: { messageId: d.id, revealSelected: true, revealRequest: 1 }, + snapshot: { targetStatus: "loading" }, + }); + // Its reveal is still waiting for the row. + expect(lastReading().settled.current).toBe(false); + h.present({ ids: [a.id, b.id] }); + expect(lastReading().settled.current).toBe(true); +}); + +it("wires a partial presentation's reading: its end row, its newest row, its bar", () => { + const h = mount({ replies: [d] }); + expect(lastReading()).toMatchObject({ + partial: false, + endMessageId: undefined, + latestMessageId: d.id, + }); + // Rows out of time order: the end is the last drawn, the latest the newest. + h.present({ + ids: [c.id, a.id, b.id], + parents: { [b.id]: a.id }, + open: [a.id], + }); + expect(lastReading()).toMatchObject({ + partial: true, + endMessageId: b.id, + latestMessageId: c.id, + }); + expect(lastReading().controls?.current).toBe( + screen.getByText("bar").parentElement, + ); + // A branch closed by the reader is not the last row drawn. + fireEvent.click(screen.getByRole("button", { name: /Collapse 1 reply/ })); + expect(lastReading().endMessageId).toBe(a.id); + // A list that holds the whole thread reads it to the end. + h.present({ ids: [a.id, b.id, c.id, d.id], complete: true }); + expect(lastReading()).toMatchObject({ partial: false, endMessageId: d.id }); + h.withdraw(); + expect(lastReading()).toMatchObject({ + partial: false, + endMessageId: undefined, + latestMessageId: d.id, + }); +}); + +it("places a presentation by its place intent", () => { + const h = mount({ replies: [a] }); + scrolled = 1500; + h.present({ ids: [b.id, c.id], place: "start" }); + expect(scrolled).toBe(0); + // A named row is brought to the top, opening the branch that holds it. + h.present({ + ids: [b.id, c.id], + parents: { [c.id]: b.id }, + place: { id: c.id }, + }); + expect(drawn()).toEqual(["root", "b", "c"]); + expect(scrolled).toBe(200); +}); + +it("holds a place named by a presentation made at mount until its rows are drawn", () => { + mount({ + onProps(accessory) { + if (accessory.presentation === "none") + accessory.present?.({ + ids: [b.id, a.id], + events: [a, b], + place: { id: a.id }, + }); + }, + }); + expect(drawn()).toEqual(["root", "b", "a"]); + expect(scrolled).toBe(200); +}); + +it("keeps the first visible row where it was, or the nearest one still shown", () => { + const h = mount({ replies: [a, b, c] }); + // `b` is the first row in view, 50px down. + scrolled = 150; + h.present({ ids: [d.id, a.id, b.id, c.id] }); + // It now sits 100px lower; keeping brings it back to 50px. + expect(scrolled).toBe(250); + // Without that row, the nearest one still shown takes its place. + h.present({ ids: [c.id, d.id] }); + expect(scrolled).toBe(50); +}); + +it("returns the host's rows at the anchor with no host read", () => { + const h = mount({ replies: [a, b, c] }); + const reads = () => [ + h.thread.mock.calls.length, + h.view.refresh.mock.calls.length, + h.view.loadMore.mock.calls.length, + ]; + const before = reads(); + scrolled = 150; + h.present({ ids: [d.id, c.id, b.id] }); + expect(scrolled).toBe(250); + h.withdraw(); + expect(drawn()).toEqual(["root", "a", "b", "c"]); + expect(scrolled).toBe(150); + expect(reads()).toEqual(before); +}); + +it("holds a place until the presented rows commit, when a host update lands with the presentation", () => { + let present = false; + const h = mount({ + replies: [a], + onProps(accessory) { + if (present && accessory.presentation === "none") + accessory.present?.({ + ids: [b.id, a.id], + events: [a, b], + place: { id: b.id }, + }); + }, + }); + present = true; + h.publish({ replies: h.rowsOf([root, a, c]).slice(1) }); + expect(drawn()).toEqual(["root", "b", "a"]); + expect(scrolled).toBe(100); +}); + +it("shows a presentation made at mount, once, under StrictMode", () => { + mount({ + strict: true, + onProps(accessory) { + if (accessory.presentation === "none") + accessory.present?.({ + ids: [b.id, a.id], + events: [a, b], + place: "start", + }); + }, + }); + expect(drawn()).toEqual(["root", "b", "a"]); + expect(scrolled).toBe(0); +}); + +it("unmounts the reader and revokes its present when the view drops its root, as a cache clear does", () => { + const h = mount({ replies: [a] }); + h.present({ ids: [b.id, a.id] }); + const present = h.latest.current?.present; + expect(drawn()).toEqual(["root", "b", "a"]); + // A cache clear empties every hold; the view purges and loses its root, so no + // presenting reader is left without live evidence. + h.publish({ status: "idle", root: undefined, replies: [] }); + expect(screen.queryByText("bar")).toBeNull(); + expect(present?.({ ids: [a.id], events: [a] })).toBe("retired"); +}); diff --git a/src/features/messages/ThreadPanel.test.tsx b/src/features/messages/ThreadPanel.test.tsx index a12927d02d..b28c0c89be 100644 --- a/src/features/messages/ThreadPanel.test.tsx +++ b/src/features/messages/ThreadPanel.test.tsx @@ -687,7 +687,7 @@ it("scopes its reading leases to its thread while the original is unavailable", // In a DM, the thread it opened bounds what its reads may cover. expect(reading.mock.calls).not.toHaveLength(0); for (const call of reading.mock.calls) - expect(call).toEqual(["channel", row.id]); + expect(call).toEqual(["channel", row.id, false]); }); it("leaves a sibling reply it hides unread while a DM reply's original is unavailable", async () => { // The real unread owner, so a dwell's DM read lands in its journal. diff --git a/src/features/messages/ThreadPanel.tsx b/src/features/messages/ThreadPanel.tsx index 5ad943c84c..07e84cd080 100644 --- a/src/features/messages/ThreadPanel.tsx +++ b/src/features/messages/ThreadPanel.tsx @@ -20,6 +20,8 @@ import { SelectionQuote } from "./SelectionQuote"; import { ReplySummary } from "./ReplySummary"; import { ReplyBranch } from "./ReplyBranch"; import { replyTree } from "./reply-tree"; +import { useArrangement, usePlace } from "./arrangement"; +import { ComposerAccessories } from "../conversation/ComposerAccessories"; import { useChannelIdentityNames } from "../identity-names/react"; import { formatPublicKey } from "../../shared/identity/public-key"; import { Button } from "../../shared/design-system/ui/Button"; @@ -42,6 +44,7 @@ import type { ConversationExtensions } from "../conversation/contracts"; import type { ChannelMessage } from "../relay/contracts"; import type { RelaySession } from "../relay/session"; import { + THREAD_LIMITS, threadFailure, type ThreadRetarget, type ThreadView, @@ -227,6 +230,24 @@ type ThreadPlace = { anchor?: { id: string; top: number; ancestors: readonly string[] }; }; const THREAD_PLACE = "thread"; +/** The first reply in view, its offset from the scroller's top, and the replies + * drawn, in order: what a place intent keeps when the rows change owner. */ +function anchorAt(element: HTMLElement | null) { + if (!element) return undefined; + const top = element.getBoundingClientRect().top; + const rows = [ + ...element.querySelectorAll("ol [data-message-id]"), + ]; + const row = rows.find((row) => row.getBoundingClientRect().bottom > top); + const id = row?.dataset.messageId; + return row && id + ? { + id, + top: row.getBoundingClientRect().top - top, + order: rows.flatMap((row) => row.dataset.messageId ?? []), + } + : undefined; +} /** Reader lifetime follows the open thread; navigation owns only a reveal request. */ function RetainedThreadPanel(props: ThreadPanelProps) { type Opening = { @@ -647,13 +668,36 @@ function ThreadMessages({ const current = view.snapshot(); return current.status === "ready" ? current.root : undefined; }, [view]); - const tree = useMemo( + // A plugin's rows replace the host's while it presents. What reads the host's + // own history (its unread line, arrivals, paging) keeps the host's rows. + const [arrangement, display] = useArrangement({ + session, + channelId, + rootId: resolvedRoot, + limits: THREAD_LIMITS, + }); + // A presentation's order is its own, so no row merges into another's bubble + // or sits under a day divider; each row's header carries its date. + const presented = !!display; + const shownReplies = display?.rows ?? snapshot.replies; + const hostTree = useMemo( () => replyTree(snapshot.replies, snapshot.root?.id), [snapshot.replies, snapshot.root?.id], ); + const tree = useMemo( + () => + display + ? replyTree( + display.rows, + resolvedRoot, + display.parents && ((id) => display.parents?.get(id)), + ) + : hostTree, + [display, hostTree, resolvedRoot], + ); const branchReplies = useMemo(() => { const branches = new Map(); - for (const reply of snapshot.replies) { + for (const reply of shownReplies) { for (const ancestor of tree.ancestors(reply.id)) { const replies = branches.get(ancestor) ?? []; replies.push(reply); @@ -661,7 +705,7 @@ function ThreadMessages({ } } return branches; - }, [tree, snapshot.replies]); + }, [tree, shownReplies]); const subscribeUnread = useCallback( (listener: () => void) => session.unread.subscribe( @@ -705,6 +749,24 @@ function ThreadMessages({ }, [messageId, navigation?.signal, revealRequest, snapshot.replies, tree]); const [expanded, setExpanded] = useState>(new Set()); const [replyParent, setReplyParent] = useState(); + // A presentation opens the branches it lists, once each: the reader's later + // toggles stand until a presentation lists a branch it had not listed before. + const listedOpen = useRef>(new Set()); + const open = display?.open; + useLayoutEffect(() => { + const fresh = (open ?? []).filter((id) => !listedOpen.current.has(id)); + listedOpen.current = new Set(open); + if (fresh.length) setExpanded((current) => new Set([...current, ...fresh])); + }, [open]); + // The last row drawn, pre-order through the branches shown open. + const endRow = useMemo(() => { + let end: string | undefined; + for (let level = tree.children.get(undefined); level?.length; ) { + end = level.at(-1)?.id; + level = end && expanded.has(end) ? tree.children.get(end) : undefined; + } + return end; + }, [tree, expanded]); const resolveName = useChannelIdentityNames(session, channelId); const senderName = (row: ChannelMessage) => { const id = row.workflowOwnerId ?? row.authorId; @@ -719,19 +781,24 @@ function ThreadMessages({ (root.workflowOwnerId ?? root.authorId) === session.viewer ? "Reply in thread" : `Reply in thread to ${senderName(root)}`; - const rows = useMemo( + const hostRows = useMemo( () => snapshot.root ? [snapshot.root, ...snapshot.replies] : snapshot.replies, [snapshot.root, snapshot.replies], ); + const rows = useMemo( + () => + display && snapshot.root ? [snapshot.root, ...display.rows] : hostRows, + [display, snapshot.root, hostRows], + ); // Remembered agents follow the viewer's latest message here, not the root. // Undefined until the first page lands: the seeded root is not yet the thread. const threadSeed = useMemo( () => snapshot.status === "ready" - ? rows.filter((row) => row.authorId === session.viewer).at(-1) + ? hostRows.filter((row) => row.authorId === session.viewer).at(-1) : undefined, - [snapshot.status, rows, session.viewer], + [snapshot.status, hostRows, session.viewer], ); const authors = [...new Set(rows.flatMap(rowProfileIds))].sort().join(":"); const profileGeneration = useProfileGeneration(session.profiles); @@ -745,6 +812,7 @@ function ThreadMessages({ const profiles = useRowProfiles(session.profiles, rows); const agentPubkeys = useKnownAgentPubkeys(session, profiles); const scroller = useRef(null); + const readerBar = useRef(null); const positioned = useRef(false); const shown = useRef(active); const readingSettled = useRef(false); @@ -1050,14 +1118,14 @@ function ThreadMessages({ return ( attention.unread || attention.forced || - (tree.children.get(row.id) ?? []).some(unread) + (hostTree.children.get(row.id) ?? []).some(unread) ); }; - const first = (tree.children.get(undefined) ?? []).find(unread); + const first = (hostTree.children.get(undefined) ?? []).find(unread); // A requested read time follows a read of the whole thread, so a nested // unread reply shows no new count: reveal it, as a reply target is. const nested = (row: ChannelMessage): ChannelMessage | undefined => { - for (const child of tree.children.get(row.id) ?? []) { + for (const child of hostTree.children.get(row.id) ?? []) { const attention = session.unread.attention(channelId, child.id, since); if (attention.unread || attention.forced) return child; const found = nested(child); @@ -1090,13 +1158,14 @@ function ThreadMessages({ oldest.createdAt > (since ?? session.unread.threadReadThrough(channelId, messageId))) ) { - if (snapshot.canLoadMore) void view.loadMore(); - // Past the page limit the first unread reply stays unknown. + if (snapshot.canLoadMore && !presented) void view.loadMore(); + // Past the page limit, or while a presentation shows, the first unread + // reply stays unknown. else setBoundary({ ...boundary, id: null }); return; } if (revealed) { - const ancestors = tree.ancestors(revealed.id); + const ancestors = hostTree.ancestors(revealed.id); setExpanded((current) => ancestors.every((id) => current.has(id)) ? current @@ -1114,7 +1183,8 @@ function ThreadMessages({ rootTarget, snapshot, messageId, - tree, + hostTree, + presented, session.unread, channelId, view, @@ -1128,8 +1198,15 @@ function ThreadMessages({ setInlineReveal(request.signal); return () => request.abort(); }, [revealSelected, revealRequest]); - const revealSignal = - inlineReveal ?? (positionedVisit ? undefined : navigation?.signal); + // A presentation may leave the opened message out: its reveal has nothing to + // show, so it yields (completing as opened) and the plugin sees `targetId`. + const targetHidden = + !!display && + messageId !== resolvedRoot && + !display.rows.some((row) => row.id === messageId); + const revealSignal = targetHidden + ? undefined + : (inlineReveal ?? (positionedVisit ? undefined : navigation?.signal)); const revealed = useMessageReveal({ scroller, focus: @@ -1248,26 +1325,22 @@ function ThreadMessages({ // branches do not mount their rows. // Each displayed level is projected alone, but a signed claim may name a // request loaded at another level. - const loadedRows = useMemo( - () => - snapshot.root ? [snapshot.root, ...snapshot.replies] : snapshot.replies, - [snapshot.root, snapshot.replies], - ); const rootReplies = useMemo( () => activityPresentation( - tree.children.get(undefined) ?? [], + presented ? [] : (tree.children.get(undefined) ?? []), activitySnapshot, agentPubkeys, rootId, undefined, - loadedRows, + hostRows, ), - [tree, activitySnapshot, agentPubkeys, rootId, loadedRows], + [tree, presented, activitySnapshot, agentPubkeys, rootId, hostRows], ); const liveAgents = useLiveConversationAgents(session, channelId, rootId); const lastMessage = publicMessageNeighbor(rows, rows.length, -1); const joinsLive = + !presented && !!lastMessage && !lastMessage.membership && lastMessage.audience !== "agents" && @@ -1333,12 +1406,13 @@ function ThreadMessages({ // Only legacy traversal is eager. Strict windows open at the newest page. useEffect(() => { if ( + !presented && snapshot.direction !== "older" && snapshot.status === "ready" && snapshot.canLoadMore ) void view.loadMore(); - }, [view, snapshot]); + }, [view, snapshot, presented]); useLayoutEffect(() => { const previous = previousReplies.current; const complete = snapshot.status === "ready" && !snapshot.canLoadMore; @@ -1381,6 +1455,10 @@ function ThreadMessages({ revealed.current = navigation.signal; navigation.complete({ status: "opened" }); } + if (navigation && targetHidden && revealed.current !== navigation.signal) { + revealed.current = navigation.signal; + navigation.complete({ status: "opened" }); + } // A mounted ordinary thread acknowledges the visit before slow history can // exhaust navigation's deadline. Positioning still waits for bounded loading. if ( @@ -1573,6 +1651,7 @@ function ThreadMessages({ tree, expanded, boundary, + targetHidden, ]); // The effect above re-pins only when thread data changes. A growing composer // shrinks this viewport, late media grows rows and a join error grows the end @@ -1619,6 +1698,7 @@ function ThreadMessages({ revealed, snapshot, unreadBoundary, + targetHidden, ]); // An own send can land in the middle of a branch, not at the list bottom. // biome-ignore lint/correctness/useExhaustiveDependencies: Retry DOM lookup after history or branch visibility changes. @@ -1674,6 +1754,42 @@ function ThreadMessages({ observer.observe(end); return () => observer.disconnect(); }, [active, initialPositioned, captureResizePosition, selectedOffset]); + const place = usePlace(arrangement, () => anchorAt(scroller.current)); + useLayoutEffect(() => { + const element = scroller.current; + // A presentation made in this commit's layout effects reaches its rows in the next. + if (arrangement?.snapshot() !== display) return; + const shown = new Set(shownReplies.map((reply) => reply.id)); + const at = place.take((id) => shown.has(id), display ? "start" : "end"); + if (!element || !at) return; + if (typeof at === "object") { + // A row inside a closed branch opens it first; one never drawn is dropped. + const closed = tree.ancestors(at.id).filter((id) => !expanded.has(id)); + if (closed.length) { + setExpanded((current) => new Set([...current, ...closed])); + return; + } + const row = element.querySelector( + `[data-message-id="${at.id}"]`, + ); + if (row) + correctScrollTop( + element, + readingDrift(element, { element: row, top: at.top }), + ); + } else element.scrollTop = at === "start" ? 0 : element.scrollHeight; + follow.current = at === "end"; + place.done(); + captureResizePosition(); + }, [ + arrangement, + display, + shownReplies, + tree, + expanded, + place, + captureResizePosition, + ]); const jumpToLatest = () => { const element = scroller.current; if (!element) return; @@ -1696,6 +1812,7 @@ function ThreadMessages({ }, 1000); }; const keepReadingPosition = () => { + place.cancel(); jumpingToLatest.current = false; if (jumpTimer.current !== undefined) { clearTimeout(jumpTimer.current); @@ -1724,14 +1841,15 @@ function ThreadMessages({ ); if (parent === undefined && snapshot.root) requestRows.set(snapshot.root.id, snapshot.root); + // Activity folding reads list order as time: off while a presentation shows. const presentation = activityPresentation( - chronologicalSiblings, + presented ? [] : chronologicalSiblings, activitySnapshot, agentPubkeys, parent ?? rootId, // A failure with replies needs its own visible branch controls. (failure) => !tree.children.get(failure.id)?.length, - loadedRows, + hostRows, ); const groups = presentation.groups.filter((group) => group.ids.every((id) => !tree.children.get(id)?.length), @@ -1753,6 +1871,7 @@ function ThreadMessages({ : publicMessageNeighbor(siblings, index, 1); const children = tree.children.get(row.id); const continuation = + !presented && !!previousReply && previousReply !== snapshot.root && previousParent === parent && @@ -1764,7 +1883,7 @@ function ThreadMessages({ ); // A collapsed branch breaks bubble grouping, not calendar continuity. const currentDay = new Date(row.createdAt * 1000).toDateString(); - const day = previousDay !== currentDay; + const day = !presented && previousDay !== currentDay; previousDay = currentDay; previousReply = children?.length && !expanded.has(row.id) ? undefined : row; @@ -1814,7 +1933,8 @@ function ThreadMessages({ inside || presentation.bubbleAnchors.has(row.id) || (joinsLive && row.id === lastMessage?.id) || - (!!nextRow && + (!presented && + !!nextRow && continuesMessageGroup(row, nextRow) && !children?.length) } @@ -1854,7 +1974,7 @@ function ThreadMessages({ className={styles.replyItem} data-layout={continuation ? "continuation" : "thread"} > - {!parent && row.id === unreadBoundary && ( + {!presented && !parent && row.id === unreadBoundary && (

    )} - {!parent && + {!presented && + !parent && row.replyParentId && row.replyParentId !== rootId && !requestRows.has(row.replyParentId) && ( @@ -1950,7 +2071,9 @@ function ThreadMessages({ ); }); } - const selectedParent = snapshot.replies.find((row) => row.id === replyParent); + const selectedParent = + snapshot.replies.find((row) => row.id === replyParent) ?? + display?.rows.find((row) => row.id === replyParent); const captureOlderAnchor = (element: HTMLElement) => { follow.current = false; const row = [ @@ -1972,6 +2095,7 @@ function ThreadMessages({ const element = scroller.current; if ( !element || + presented || !olderDemand.current || snapshot.direction !== "older" || snapshot.status !== "ready" || @@ -1987,12 +2111,13 @@ function ThreadMessages({ const selectionNotice = selectionFailure && !snapshot.error ? selectionFailure : undefined; const showOlderPageStatus = + !presented && snapshot.direction === "older" && snapshot.readKind === "older" && !!snapshot.root; const targetUnavailable = snapshot.targetStatus === "unavailable" && !selectionNotice; - const historyError = !!snapshot.error && !showOlderPageStatus; + const historyError = !presented && !!snapshot.error && !showOlderPageStatus; const focusArchivedHistory = useCallback(() => { const history = scroller.current; if ( @@ -2031,14 +2156,36 @@ function ThreadMessages({ // observe rows individually; an absent root must not mean channel catch-up. latestMessageId={ snapshot.root - ? snapshot.replies.reduce( + ? shownReplies.reduce( (latest, row) => !latest || row.createdAt > latest.createdAt ? row : latest, undefined, )?.id : undefined } + // A presentation's list order is its own: the last row rendered is the + // end a dwell catches up at, and rows it leaves out stay unread. + endMessageId={presented ? endRow : undefined} + partial={!!display && !display.complete} + controls={readerBar} /> + {/* Outside the composer, so every viewer sees the bar the composer hides from. */} + {arrangement && extensions?.accessories && ( +
    + canOpenLink?.(target) ?? false} + open={onOpenLink} + /> +
    + )}
    { if (!positioned.current) return; const element = event.currentTarget; @@ -2121,7 +2268,7 @@ function ThreadMessages({ tabIndex={0} > @@ -2240,7 +2387,7 @@ function ThreadMessages({ : "Couldn’t open that message."}

    )} - {snapshot.limited && !snapshot.error && ( + {!presented && snapshot.limited && !snapshot.error && (

    Thread history limit reached.

    )} {(historyError || (targetUnavailable && snapshot.root)) && ( diff --git a/src/features/messages/arrangement.test.ts b/src/features/messages/arrangement.test.ts new file mode 100644 index 0000000000..eaa8446777 --- /dev/null +++ b/src/features/messages/arrangement.test.ts @@ -0,0 +1,637 @@ +import { afterEach, expect, it, vi } from "vitest"; +import type { PresentationLimits } from "../conversation/contracts"; +import { eventDto, type EventData, type RelayEvent } from "../relay/events"; +import { PublishRejected } from "../relay/outbox"; +import { createRelaySession } from "../relay/session"; +import { THREAD_LIMITS } from "../relay/threads"; +import type { LiveCallbacks } from "../relay/live"; +import { + flush, + keypair, + message, + roster, + scriptedTransport, + signed, + type Key, +} from "../relay/testing"; +import { + createArrangement, + createPlace, + nearestShown, + placeIntent, + type ArrangementLane, +} from "./arrangement"; +import { replyTree } from "./reply-tree"; + +const viewer = keypair(), + other = keypair(), + relay = keypair(); +const owners: ReturnType[] = []; +afterEach(() => { + for (const owner of owners.splice(0)) owner.dispose(); + vi.unstubAllGlobals(); +}); +/** An event as a verified read returns it: the only kind with proof. */ +const proven = (event: RelayEvent) => eventDto(event); +const live = { phase: "live" as const, channelId: "c" }; +const wide: PresentationLimits = { rows: 460, events: 2000, bytes: 4 << 20 }; + +function setup(publish: (event: RelayEvent) => Promise) { + const wire = scriptedTransport(viewer.pubkey, relay.pubkey); + let callbacks!: LiveCallbacks; + const owner = createRelaySession( + { + ...wire.transport, + writer: { sign: async (template) => signed(viewer, template), publish }, + subscribe(next) { + callbacks = next; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { outboxStorage: { load: () => [], save() {} } }, + ); + owners.push(owner); + owner.session.channels.ensure("c"); + callbacks.receive([roster(relay, "c", [viewer.pubkey], 1)]); + return { session: owner.session, receive: callbacks.receive }; +} +function host( + options: { + rootId?: string; + limits?: PresentationLimits; + publish?: (event: RelayEvent) => Promise; + } = {}, +) { + const world = setup(options.publish ?? (() => new Promise(() => {}))); + const frames = new Map void>(); + let handle = 0; + vi.stubGlobal("requestAnimationFrame", (run: () => void) => { + frames.set(++handle, run); + return handle; + }); + vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id)); + const arrangement = createArrangement({ + session: world.session, + channelId: "c", + rootId: options.rootId, + limits: options.limits ?? wide, + }); + const seen: unknown[] = []; + arrangement.subscribe(() => seen.push(arrangement.snapshot())); + return { + ...world, + arrangement, + seen, + frames, + /** The one animation frame that follows. */ + frame() { + for (const [id, run] of [...frames]) { + frames.delete(id); + run(); + } + }, + }; +} +const lane = (key: string, order?: number): ArrangementLane => ({ + key, + order, +}); +const reaction = (author: Key, target: EventData, time: number) => + proven( + signed(author, { + kind: 7, + content: "👍", + created_at: time, + tags: [ + ["h", "c"], + ["e", target.id], + ], + }), + ); +const deletion = (author: Key, targets: readonly string[], time: number) => + proven( + signed(author, { + kind: 5, + content: "", + created_at: time, + tags: [["h", "c"], ...targets.map((id) => ["e", id])], + }), + ); +const reply = (author: Key, root: EventData, time: number, text = "r") => + proven(message(author, "c", text, time, [["e", root.id, "", "reply"]])); +function thread(count = 3) { + const root = proven(message(other, "c", "root", 10)); + const replies = Array.from({ length: count }, (_, index) => + reply(other, root, 11 + index, `reply ${index}`), + ); + // Typed as the most the tests destructure. + return { + root, + replies: replies as unknown as [ + RelayEvent, + RelayEvent, + RelayEvent, + RelayEvent, + RelayEvent, + RelayEvent, + ], + events: [root, ...replies], + }; +} +const ids = (rows: readonly { id: string }[] | undefined) => + rows?.map((row) => row.id); + +it("shows the named rows in ids order, skipping ids that do not fold and the root", () => { + const { root, replies, events } = thread(); + const { arrangement } = host({ rootId: root.id }); + const [a, b, c] = replies; + expect( + arrangement.present(lane("one"), { + ids: [c?.id, root.id, "unknown", a?.id, b?.id] as string[], + events, + }), + ).toBe("shown"); + expect(ids(arrangement.snapshot()?.rows)).toEqual([c?.id, a?.id, b?.id]); +}); + +it("shows top-level rows of a channel and drops replies", () => { + const { root, replies, events } = thread(1); + const second = proven(message(other, "c", "second", 30)); + const { arrangement } = host(); + arrangement.present(lane("one"), { + ids: [second.id, replies[0]?.id ?? "", root.id], + events: [...events, second], + }); + expect(ids(arrangement.snapshot()?.rows)).toEqual([second.id, root.id]); +}); + +it("passes parents, open, complete and place through, nested to depth 4", () => { + const { root, replies, events } = thread(5); + const [a, b, c, d, e] = replies.map((row) => row.id) as [ + string, + string, + string, + string, + string, + ]; + const { arrangement } = host({ rootId: root.id }); + arrangement.present(lane("one"), { + ids: [a, b, c, d, e], + events, + parents: { [b]: a, [c]: b, [d]: c, [e]: d }, + open: [b], + complete: true, + place: { id: c }, + }); + const display = arrangement.snapshot(); + expect(display).toMatchObject({ + open: [b], + complete: true, + place: { id: c }, + }); + const tree = replyTree(display?.rows ?? [], root.id, (id) => + display?.parents?.get(id), + ); + expect(tree.ancestors(e)).toEqual([d, c, b, a]); + arrangement.present(lane("one"), { ids: [a, b], events }); + expect(arrangement.snapshot()).toMatchObject({ + open: [], + complete: false, + place: "keep", + }); + expect(arrangement.snapshot()?.parents).toBeUndefined(); + // An empty record is a request for a flat list, not for the reader's branches. + arrangement.present(lane("one"), { ids: [a, b], events, parents: {} }); + expect(arrangement.snapshot()?.parents?.size).toBe(0); +}); + +it("refuses duplicate ids and too many rows, events or bytes, and keeps what it shows", () => { + const { root, replies, events } = thread(); + const [a, b] = replies; + const { arrangement } = host({ + rootId: root.id, + limits: { rows: 460, events: 4, bytes: 4 << 20 }, + }); + const first = lane("one"); + expect(arrangement.present(first, { ids: [a.id], events })).toBe("shown"); + const shown = arrangement.snapshot(); + expect(arrangement.present(first, { ids: [b.id, b.id], events })).toBe( + "invalid", + ); + expect(arrangement.snapshot()).toBe(shown); + // The root and three replies are at the limit; a fourth reply is past it. + expect( + arrangement.present(first, { ids: replies.map((row) => row.id), events }), + ).toBe("shown"); + const more = reply(other, root, 40); + expect( + arrangement.present(first, { + ids: [...replies, more].map((row) => row.id), + events: [...events, more], + }), + ).toBe("limit"); + expect(arrangement.snapshot()?.rows).toHaveLength(3); + const small = host({ + rootId: root.id, + limits: { rows: 460, events: 2000, bytes: 100 }, + }); + expect(small.arrangement.present(first, { ids: [a.id], events })).toBe( + "limit", + ); + expect(small.arrangement.snapshot()).toBeUndefined(); + // Any malformed field is refused before anything changes. + const before = arrangement.snapshot(); + for (const bad of [ + { ids: "x" }, + { open: 1 }, + { parents: [] }, + { complete: "yes" }, + { place: null }, + { place: "end" }, + { place: { id: 1 } }, + ]) + expect( + arrangement.present(first, { ids: [a.id], events, ...bad } as never), + ).toBe("invalid"); + expect(arrangement.present(first, undefined as never)).toBe("invalid"); + expect(arrangement.snapshot()).toBe(before); +}); + +it("refuses the 461st row of a thread, the reader's bound", () => { + const { root } = thread(0); + const { arrangement } = host({ rootId: root.id, limits: THREAD_LIMITS }); + const names = (count: number) => + Array.from({ length: count }, (_, index) => `row-${index}`); + const first = lane("one"); + expect(arrangement.present(first, { ids: names(460), events: [] })).toBe( + "shown", + ); + expect(arrangement.present(first, { ids: names(461), events: [] })).toBe( + "limit", + ); +}); + +it("applies a live reaction and its deletion (two hops) to a row it was given by snapshot, with no re-present", () => { + const { root, replies, events } = thread(1); + const [row] = replies; + const { arrangement, receive, frame } = host({ rootId: root.id }); + arrangement.present(lane("one"), { ids: [row.id], events }); + const first = reaction(other, row, 30); + receive([first], live); + frame(); + expect(arrangement.snapshot()?.rows[0]?.reactions).toHaveLength(1); + receive([deletion(other, [first.id], 31)], live); + frame(); + expect(arrangement.snapshot()?.rows[0]?.reactions).toHaveLength(0); + // It never adds a row: a new live reply is not shown. + receive([reply(other, root, 32, "late")], live); + frame(); + expect(arrangement.snapshot()?.rows).toHaveLength(1); +}); + +it("applies a NIP-09 deletion that has no h tag, by snapshot and live, as the readers do", () => { + const { root, replies, events } = thread(2); + const [first, second] = replies; + const bare = (target: EventData, time: number) => + proven( + signed(other, { + kind: 5, + content: "", + created_at: time, + tags: [["e", target.id]], + }), + ); + const { arrangement, receive, frame } = host({ rootId: root.id }); + arrangement.present(lane("one"), { + ids: [first.id, second.id], + events: [...events, bare(first, 30)], + }); + expect(ids(arrangement.snapshot()?.rows)).toEqual([second.id]); + receive([bare(second, 31)], live); + frame(); + expect(arrangement.snapshot()?.rows).toEqual([]); +}); + +it("ends when live growth passes the limits, never trims, and shows again on a new present", () => { + const { root, replies, events } = thread(1); + const [row] = replies; + const { arrangement, receive, session } = host({ + rootId: root.id, + limits: { rows: 10, events: 4, bytes: 4 << 20 }, + }); + const first = lane("one"); + arrangement.present(first, { ids: [row.id], events }); + receive([reaction(other, row, 30), reaction(viewer, row, 31)], live); + expect(arrangement.status(first)).toBe("shown"); + receive([reaction(other, row, 32)], live); + expect(arrangement.status(first)).toBe("ended"); + expect(arrangement.snapshot()).toBeUndefined(); + // Its hold is gone: the row's live reactions are dropped again. + const heard: RelayEvent[] = []; + session.subscribeLive((batch) => heard.push(...batch.events)); + receive([reaction(other, row, 33)], live); + expect(heard).toHaveLength(0); + expect(arrangement.present(first, { ids: [row.id], events })).toBe("shown"); + expect(arrangement.status(first)).toBe("shown"); +}); + +it("swaps its one hold in place: a full session still re-presents, and a withdraw frees the slot", () => { + const { root, replies, events } = thread(2); + const { arrangement, session } = host({ rootId: root.id }); + const first = lane("one"); + const others = Array.from({ length: 63 }, () => session.retain()); + expect( + arrangement.present(first, { ids: [replies[0]?.id ?? ""], events }), + ).toBe("shown"); + // No free view slot is left, and a second hold would need one. + expect(() => session.retain()).toThrow(/capacity/); + expect( + arrangement.present(first, { ids: [replies[1]?.id ?? ""], events }), + ).toBe("shown"); + expect(arrangement.present(first, null)).toBe("shown"); + expect(() => session.retain()).not.toThrow(); + for (const hold of others) hold.dispose(); +}); + +it("answers limit when no view slot is free, and keeps what it showed", () => { + const { root, replies, events } = thread(1); + const { arrangement, session } = host({ rootId: root.id }); + const holds = Array.from({ length: 64 }, () => session.retain()); + expect( + arrangement.present(lane("one"), { ids: [replies[0]?.id ?? ""], events }), + ).toBe("limit"); + expect(arrangement.snapshot()).toBeUndefined(); + for (const hold of holds) hold.dispose(); +}); + +it("keeps live aux for ids that stay presented, and drops it for ids that do not", () => { + const { root, replies, events } = thread(2); + const [a, b] = replies; + const { arrangement, receive, frame } = host({ rootId: root.id }); + const first = lane("one"); + arrangement.present(first, { ids: [a.id, b.id], events }); + receive([reaction(other, a, 30)], live); + frame(); + arrangement.present(first, { ids: [b.id, a.id], events }); + expect(arrangement.snapshot()?.rows[1]?.reactions).toHaveLength(1); + arrangement.present(first, { ids: [b.id], events }); + arrangement.present(first, { ids: [a.id], events }); + expect(arrangement.snapshot()?.rows[0]?.reactions).toHaveLength(0); +}); + +it("keeps row identity across a refold that changed nothing for them", () => { + const { root, replies, events } = thread(2); + const [a, b] = replies; + const { arrangement, receive, frame } = host({ rootId: root.id }); + arrangement.present(lane("one"), { ids: [a.id, b.id], events }); + const before = arrangement.snapshot()?.rows; + receive([reaction(other, a, 30)], live); + frame(); + const after = arrangement.snapshot()?.rows; + expect(after?.[0]).not.toBe(before?.[0]); + expect(after?.[1]).toBe(before?.[1]); +}); + +it("refolds at most once per frame, whatever changes", async () => { + const { root, replies, events } = thread(1); + const [row] = replies; + const { arrangement, receive, frames, seen, session } = host({ + rootId: root.id, + }); + arrangement.present(lane("one"), { ids: [row.id], events }); + await session.outbox?.ready(); + seen.length = 0; + receive([reaction(other, row, 30)], live); + receive([reaction(viewer, row, 31)], live); + session.messages.react(row.id, "🎉"); + expect(frames.size).toBe(1); + expect(seen).toHaveLength(0); + for (const run of [...frames.values()]) run(); + expect(seen).toHaveLength(1); + expect(arrangement.snapshot()?.rows[0]?.reactions.length).toBeGreaterThan(1); +}); + +it("keeps refolding live changes after a re-present that overtook a pending frame", () => { + const { root, replies, events } = thread(1); + const [row] = replies; + const { arrangement, receive, frame } = host({ rootId: root.id }); + arrangement.present(lane("one"), { ids: [row.id], events }); + receive([reaction(other, row, 30)], live); + // The re-present folds at once, so the frame the first reaction asked for is moot. + arrangement.present(lane("one"), { ids: [row.id], events }); + receive([reaction(viewer, row, 31)], live); + frame(); + expect(arrangement.snapshot()?.rows[0]?.reactions[0]?.events).toHaveLength(2); +}); + +it("shows an own pending reply only when named, and follows its delivery", async () => { + let reject!: () => void; + const { root, events } = thread(0); + const { arrangement, session, receive, frame } = host({ + rootId: root.id, + publish: () => + new Promise((_, fail) => { + reject = () => fail(new PublishRejected("refused")); + }), + }); + receive([root]); + await session.outbox?.ready(); + session.messages.reply("c", root.id, "mine"); + const id = session.outbox?.snapshot()[0]?.event.id ?? ""; + arrangement.present(lane("one"), { ids: [], events }); + expect(arrangement.snapshot()?.rows).toEqual([]); + // Named with no events at all. + arrangement.present(lane("one"), { ids: [id], events: [] }); + expect(arrangement.snapshot()?.rows[0]).toMatchObject({ + content: "mine", + delivery: "sending", + }); + await flush(); + reject(); + await flush(); + await flush(); + frame(); + expect(arrangement.snapshot()?.rows[0]?.delivery).toBe("failed"); +}); + +it("shows the first lane by order then key, holds the rest and promotes on withdraw", () => { + const { root, replies, events } = thread(2); + const [a, b] = replies; + const { arrangement } = host({ rootId: root.id }); + const late = lane("a", 5); + const early = lane("z", 1); + expect(arrangement.present(late, { ids: [a.id], events })).toBe("shown"); + expect(arrangement.present(early, { ids: [b.id], events })).toBe("shown"); + expect(arrangement.status(late)).toBe("held"); + expect(arrangement.status(early)).toBe("shown"); + expect(ids(arrangement.snapshot()?.rows)).toEqual([b.id]); + const tied = lane("b", 5); + expect(arrangement.present(tied, { ids: [a.id], events })).toBe("held"); + expect(arrangement.present(early, null)).toBe("shown"); + expect(arrangement.status(early)).toBe("none"); + // `a` before `b` among equal orders. + expect(arrangement.status(late)).toBe("shown"); + expect(arrangement.status(tied)).toBe("held"); + arrangement.present(late, null); + arrangement.present(tied, null); + expect(arrangement.snapshot()).toBeUndefined(); +}); + +it("promotes a held lane when the shown one ends", () => { + const { root, replies, events } = thread(2); + const [a, b] = replies; + const { arrangement, receive } = host({ + rootId: root.id, + limits: { rows: 10, events: 4, bytes: 4 << 20 }, + }); + const first = lane("a"); + const second = lane("b"); + arrangement.present(first, { ids: [a.id], events }); + arrangement.present(second, { ids: [b.id], events }); + receive([reaction(other, a, 30), reaction(other, a, 31)], live); + receive([reaction(other, a, 32)], live); + expect(arrangement.status(first)).toBe("ended"); + expect(arrangement.status(second)).toBe("shown"); + expect(ids(arrangement.snapshot()?.rows)).toEqual([b.id]); +}); + +it("keeps its own copy of what a held lane selected, not the plugin's whole read", () => { + const { root, replies, events } = thread(3); + const [a, b] = replies; + const { arrangement } = host({ rootId: root.id }); + const first = lane("a"); + const second = lane("b"); + arrangement.present(first, { ids: [a.id], events }); + // The plugin's read, which it reuses as its buffer once it has presented. + const scan = [...events, reaction(other, b, 30)]; + expect(arrangement.present(second, { ids: [b.id], events: scan })).toBe( + "held", + ); + scan.length = 0; + arrangement.present(first, null); + expect(arrangement.status(second)).toBe("shown"); + const [row] = arrangement.snapshot()?.rows ?? []; + expect(row?.id).toBe(b.id); + expect(row?.reactions).toHaveLength(1); +}); + +it("ends a promoted lane that no longer fits, and falls back to the host's rows", () => { + const { root, replies, events } = thread(1); + const [a] = replies; + const { arrangement, receive } = host({ + rootId: root.id, + limits: { rows: 10, events: 4, bytes: 4 << 20 }, + }); + const first = lane("a"); + const second = lane("b"); + // Both name the row, so the live reactions that ended `first` count for `second`. + arrangement.present(first, { ids: [a.id], events }); + arrangement.present(second, { ids: [a.id], events }); + receive([reaction(other, a, 30), reaction(other, a, 31)], live); + receive([reaction(other, a, 32)], live); + expect(arrangement.status(first)).toBe("ended"); + expect(arrangement.status(second)).toBe("ended"); + expect(arrangement.snapshot()).toBeUndefined(); +}); + +it("keeps a presentation through a StrictMode replay and retires after a real unmount", async () => { + const { root, replies, events } = thread(1); + const [a] = replies; + const { arrangement, receive, session } = host({ rootId: root.id }); + const first = lane("a"); + arrangement.present(first, { ids: [a.id], events }); + arrangement.retire(); + arrangement.attach(); + await Promise.resolve(); + expect(arrangement.status(first)).toBe("shown"); + expect(arrangement.present(first, { ids: [a.id], events })).toBe("shown"); + const heard: RelayEvent[] = []; + session.subscribeLive((batch) => heard.push(...batch.events)); + receive([reaction(other, a, 30)], live); + expect(heard).toHaveLength(1); + arrangement.retire(); + // Still open to a replay until the commit ends. + expect(arrangement.status(first)).toBe("shown"); + await Promise.resolve(); + expect(arrangement.snapshot()).toBeUndefined(); + expect(arrangement.status(first)).toBe("none"); + expect(arrangement.present(first, { ids: [a.id], events })).toBe("retired"); + arrangement.attach(); + expect(arrangement.present(first, { ids: [a.id], events })).toBe("retired"); + receive([reaction(other, a, 31)], live); + expect(heard).toHaveLength(1); +}); + +it("tells a subscriber each change of display and lane status, and no more", () => { + const { root, replies, events } = thread(1); + const [a] = replies; + const { arrangement, seen } = host({ rootId: root.id }); + const first = lane("a"); + arrangement.present(first, { ids: [a.id], events }); + expect(seen).toHaveLength(1); + expect(arrangement.snapshot()?.revision).toBe(1); + arrangement.present(first, { ids: [a.id], events }); + expect(arrangement.snapshot()?.revision).toBe(2); + arrangement.present(first, null); + expect(arrangement.snapshot()).toBeUndefined(); + expect(seen).toHaveLength(3); +}); + +const order = ["a", "b", "c", "d", "e"]; +const anchor = (id: string) => ({ id, top: 12, order }); + +it("finds the nearest shown row to a kept anchor, preferring the row below", () => { + expect(nearestShown(anchor("c"), () => true)).toBe("c"); + expect(nearestShown(anchor("c"), (id) => id !== "c")).toBe("d"); + expect(nearestShown(anchor("c"), (id) => ["a", "b"].includes(id))).toBe("b"); + expect(nearestShown(anchor("c"), (id) => id === "a")).toBe("a"); + expect(nearestShown(anchor("c"), () => false)).toBeUndefined(); + expect(nearestShown(anchor("zz"), () => true)).toBeUndefined(); +}); + +it("holds one pending place until it is applied, replaced by a later one, cancelled by input", () => { + const place = createPlace(); + const all = () => true; + expect(place.take(all)).toBeUndefined(); + place.capture({ kind: "end" }); + place.capture({ kind: "start" }); + expect(place.take(all)).toBe("start"); + // Held until done: a row in a closed branch needs another commit to place. + expect(place.take(() => false)).toBe("start"); + place.done(); + expect(place.take(all)).toBeUndefined(); + place.capture({ kind: "end" }); + place.cancel(); + expect(place.take(all)).toBeUndefined(); + place.capture({ kind: "end" }); + expect(place.take(all)).toBe("end"); + // A capture drops a placement not yet applied. + place.capture({ kind: "keep", ...anchor("c") }); + expect(place.take((id) => id === "d")).toEqual({ id: "d", top: 12 }); + place.cancel(); + expect(place.take(all)).toBeUndefined(); + place.capture({ kind: "keep", ...anchor("c") }); + expect(place.take(() => false)).toBe("start"); + place.done(); + place.capture({ kind: "keep", ...anchor("c") }); + expect(place.take(() => false, "end")).toBe("end"); + place.done(); + place.capture({ kind: "reveal", id: "b" }); + expect(place.take((id) => id === "b")).toEqual({ id: "b", top: 0 }); + place.done(); + place.capture({ kind: "reveal", id: "b" }); + expect(place.take(() => false)).toBeUndefined(); +}); + +it("maps a presentation's place to an intent, keeping the anchor by default", () => { + expect(placeIntent("keep", anchor("c"))).toEqual({ + kind: "keep", + ...anchor("c"), + }); + expect(placeIntent("keep", undefined)).toEqual({ kind: "start" }); + expect(placeIntent("start", anchor("c"))).toEqual({ kind: "start" }); + expect(placeIntent({ id: "b" }, anchor("c"))).toEqual({ + kind: "reveal", + id: "b", + }); +}); diff --git a/src/features/messages/arrangement.ts b/src/features/messages/arrangement.ts new file mode 100644 index 0000000000..1ccca13659 --- /dev/null +++ b/src/features/messages/arrangement.ts @@ -0,0 +1,489 @@ +import { + useEffect, + useEffectEvent, + useLayoutEffect, + useMemo, + useSyncExternalStore, +} from "react"; +import type { + ConversationPresentation, + PresentationLimits, + PresentResult, +} from "../conversation/contracts"; +import { listByteSize } from "../relay/budget"; +import type { ChannelMessage } from "../relay/contracts"; +import type { EventData, RelayEvent } from "../relay/events"; +import type { LiveBatch } from "../relay/incoming"; +import { shareMessageRows } from "../relay/row-identity"; +import type { RelaySession } from "../relay/session"; +import { AUX, growAux, inChannel } from "../relay/threads"; + +/** + * Core-internal host that shows a plugin's rows in a reader (never exported to + * plugins). One host per reader mount, keyed by session, channel and thread. + * + * Four state machines, each a union below: + * - SM1, the host: `live -> leaving -> retired`. `retire` only starts `leaving`, + * which a StrictMode replay's `attach` cancels in the same commit; the + * microtask after it tears down. `retired` is final and answers `retired`. + * - SM2, a lane (one reader accessory): none (no entry), `holding` or `ended`. + * `present(P)` within limits -> `holding`; `present(null)` or unmount -> none; + * live growth past the limits -> `ended` (until it presents again). A + * boundary error unmounts the accessory, which withdraws it and revokes its + * `present`, so a failed lane needs no state of its own. The shown lane is the + * first `holding` one by `(order, key)`; the rest are held, and the next is + * promoted when the shown one leaves. + * - SM3, the display: host rows (no `holding` lane) or the shown lane's rows + * with its evidence. Live evidence grows in place; growth past the limits ends + * the lane and is never trimmed (a trim could bring a deleted row back). + * - SM4, the place intent, below: at most one pending. + */ +type LaneState = + | Readonly<{ state: "holding"; presentation: ConversationPresentation }> + | Readonly<{ state: "ended" }>; +/** Contributions fit: the order the accessories already have. */ +export type ArrangementLane = Readonly<{ + key: string; + order?: number | undefined; +}>; +/** The rows a reader shows in place of the host's, while a lane is shown. */ +export type Display = Readonly<{ + /** The rows named by `ids` that fold, in `ids` order. */ + rows: readonly ChannelMessage[]; + /** Display parents; a reader nests with `replyTree(rows, rootId, parents.get)`. + * Absent: the reader's own branches; an empty map: every row at the top level. */ + parents: ReadonlyMap | undefined; + open: readonly string[]; + complete: boolean; + place: NonNullable; + /** Changes with each presentation, not with live updates of its rows. */ + revision: number; +}>; +type Hold = ReturnType; +/** The shown lane's evidence: what the hold keeps and what the fold reads. */ +type Evidence = { + readonly hold: Hold; + readonly ids: readonly string[]; + readonly events: Map; + /** Live aux seen, kept for ids that stay presented. */ + readonly live: Map; + rows: readonly ChannelMessage[]; +}; +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); +const exceeds = ( + events: ReadonlyMap, + l: PresentationLimits, +) => events.size > l.events || listByteSize([...events.values()]) > l.bytes; + +export type Arrangement = ReturnType; +export function createArrangement({ + session, + channelId, + rootId, + limits, +}: Readonly<{ + session: RelaySession; + channelId: string; + rootId?: string | undefined; + limits: PresentationLimits; +}>) { + let phase: "live" | "leaving" | "retired" = "live"; + const lanes = new Map(); + let shown: ArrangementLane | undefined; + let evidence: Evidence | undefined; + let display: Display | undefined; + let revision = 0; + let stopWatching: (() => void) | undefined; + let cancelFrame: (() => void) | undefined; + const listeners = new Set<() => void>(); + const emit = () => { + for (const listener of [...listeners]) listener(); + }; + const rank = (lane: ArrangementLane) => + Number.isFinite(lane.order) ? (lane.order as number) : 0; + const before = (a: ArrangementLane, b: ArrangementLane) => + rank(a) - rank(b) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0); + /** The first holding lane by `(order, key)`, counting `candidate` as holding. */ + function leader(candidate?: ArrangementLane) { + let best = candidate; + for (const [lane, { state }] of lanes) + if (state === "holding" && (!best || before(lane, best) < 0)) best = lane; + return best; + } + /** The ids' rows and their aux from `live` and the plugin's events, or why not. */ + function select( + presentation: ConversationPresentation, + live: Iterable, + ) { + if (!isObject(presentation)) return "invalid"; + const { ids, events, parents, open, complete, place } = presentation; + // Everything `show` reads is checked here, so a bad one changes nothing. + if ( + !Array.isArray(ids) || + !Array.isArray(events) || + ids.some((id) => typeof id !== "string") || + new Set(ids).size !== ids.length || + (parents !== undefined && !isObject(parents)) || + (open !== undefined && !Array.isArray(open)) || + (complete !== undefined && typeof complete !== "boolean") || + (place !== undefined && + place !== "keep" && + place !== "start" && + !(isObject(place) && typeof place.id === "string")) + ) + return "invalid"; + if (ids.length > limits.rows) return "limit"; + const wanted = new Set(ids); + const pool = new Map(); + // Rows need this channel's tag; aux joins by reference, as the readers + // admit it (a NIP-09 deletion may carry no `h`). + for (const event of [...events, ...live]) + if (AUX.has(event.kind) || inChannel(event, channelId)) + pool.set(event.id, event); + const held = new Map(); + for (const event of pool.values()) + if (wanted.has(event.id) && !AUX.has(event.kind) && event.kind !== 39007) + held.set(event.id, event); + // The root, when given, stays beside its replies as the reader's header. + const root = pool.get(rootId ?? ""); + if (root) held.set(root.id, root); + growAux([...pool.values()], held); + return exceeds(held, limits) ? "limit" : { events: held }; + } + function fold(current: Evidence) { + const folded = new Map( + session + .foldRows(channelId, [...current.events.values()], rootId) + .map((row) => [row.id, row]), + ); + // The root stays the reader's header, never a presented row. + const rows = current.ids.flatMap((id) => + id === rootId ? [] : (folded.get(id) ?? []), + ); + return shareMessageRows(current.rows, rows); + } + function watch() { + if (stopWatching) return; + const stops = [ + session.subscribeLive(onLive, { replay: true }), + session.outbox?.subscribe(refold), + session.profiles.subscribe(refold), + ]; + stopWatching = () => { + for (const stop of stops) stop?.(); + }; + } + /** Stops showing: the display is the host's, and nothing is held or watched. */ + function release() { + evidence?.hold.dispose(); + evidence = undefined; + shown = undefined; + display = undefined; + stopWatching?.(); + stopWatching = undefined; + cancelFrame?.(); + cancelFrame = undefined; + } + /** Shows `lane`'s presentation: select, hold (one swap, so evidence never has a + * gap), fold. A reason leaves everything as it was; otherwise the selection. */ + function show(lane: ArrangementLane, presentation: ConversationPresentation) { + const picked = select(presentation, evidence?.live.values() ?? []); + if (typeof picked === "string") return picked; + let hold = evidence?.hold; + try { + hold ??= session.retain(); + hold.set([...picked.events.values()]); + } catch { + // No free view slot, or past the byte bound: it does not fit. + if (!evidence) hold?.dispose(); + return "limit"; + } + const live = new Map( + [...(evidence?.live ?? [])].filter(([id]) => picked.events.has(id)), + ); + evidence = { + hold, + ids: [...presentation.ids], + ...picked, + live, + rows: evidence?.rows ?? [], + }; + evidence.rows = fold(evidence); + // This fold is current, so a frame asked for by the old evidence is moot. + cancelFrame?.(); + cancelFrame = undefined; + shown = lane; + revision += 1; + display = Object.freeze({ + rows: evidence.rows, + parents: presentation.parents + ? new Map( + Object.entries(presentation.parents).filter( + ([, parent]) => typeof parent === "string", + ), + ) + : undefined, + open: [...(presentation.open ?? [])], + complete: presentation.complete === true, + place: presentation.place ?? "keep", + revision, + }); + watch(); + return picked; + } + /** The shown lane left: promote the next holding one, which ends if it no + * longer fits, or fall back to the host's rows. */ + function settle() { + for (let next = leader(); next; next = leader()) { + const lane = lanes.get(next); + if ( + lane?.state === "holding" && + typeof show(next, lane.presentation) !== "string" + ) { + emit(); + return; + } + lanes.set(next, { state: "ended" }); + } + release(); + emit(); + } + function end() { + if (shown) lanes.set(shown, { state: "ended" }); + settle(); + } + function onLive({ events }: LiveBatch) { + const current = evidence; + if (!current) return; + // growAux adds only aux that reaches a held event, never a row. + const added = growAux(events, current.events); + if (!added.length) return; + for (const event of added) current.live.set(event.id, event); + if (exceeds(current.events, limits)) return end(); + try { + current.hold.set([...current.events.values()]); + } catch { + return end(); + } + refold(); + } + /** A fold at most once per frame, from live aux, the outbox or profiles. */ + function refold() { + const current = evidence; + if (!current || cancelFrame) return; + const id = requestAnimationFrame(() => { + cancelFrame = undefined; + const rows = fold(current); + if (current !== evidence || !display || rows === current.rows) return; + current.rows = rows; + display = Object.freeze({ ...display, rows }); + emit(); + }); + cancelFrame = () => cancelAnimationFrame(id); + } + return { + limits, + /** `lane` shows `presentation`, or withdraws with `null` (answering `shown`). */ + present( + lane: ArrangementLane, + presentation: ConversationPresentation | null, + ): PresentResult { + if (phase === "retired") return "retired"; + if (presentation === null) { + lanes.delete(lane); + if (shown === lane) settle(); + else emit(); + return "shown"; + } + const wins = leader(lane) === lane; + const picked = wins + ? show(lane, presentation) + : select(presentation, evidence?.live.values() ?? []); + if (typeof picked === "string") return picked; + // Only what was selected is kept, and selecting from it again gives the + // same rows: the plugin's whole read is not held. + const events = [...picked.events.values()]; + lanes.set(lane, { + state: "holding", + presentation: { ...presentation, events }, + }); + emit(); + return wins ? "shown" : "held"; + }, + status(lane: ArrangementLane): "none" | "shown" | "held" | "ended" { + const state = lanes.get(lane)?.state; + if (state === "holding") return shown === lane ? "shown" : "held"; + return state === "ended" ? "ended" : "none"; + }, + /** The shown presentation, or `undefined` for the host's rows. */ + snapshot: (): Display | undefined => display, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + /** A mount, or its StrictMode replay: cancels a pending retire. */ + attach() { + if (phase === "leaving") phase = "live"; + }, + /** An unmount, or the first half of a StrictMode replay: tears down after + * the commit unless `attach` follows. */ + retire() { + if (phase !== "live") return; + phase = "leaving"; + queueMicrotask(() => { + if (phase !== "leaving") return; + phase = "retired"; + lanes.clear(); + release(); + emit(); + }); + }, + }; +} + +const noSubscription = () => () => {}; +/** A reader's host and what it shows now. A thread's host exists once its root + * does: until then no row could fold beside it. A channel's (`channel`) needs + * no root. */ +export function useArrangement( + options: Readonly<{ + session: RelaySession; + channelId: string; + rootId: string | undefined; + limits: PresentationLimits; + channel?: boolean; + }>, +) { + const { session, channelId, rootId, limits, channel } = options; + const arrangement = useMemo( + () => + rootId || channel + ? createArrangement({ session, channelId, rootId, limits }) + : undefined, + [session, channelId, rootId, limits, channel], + ); + useEffect(() => { + arrangement?.attach(); + return () => arrangement?.retire(); + }, [arrangement]); + const display = useSyncExternalStore( + arrangement?.subscribe ?? noSubscription, + () => arrangement?.snapshot(), + ); + return [arrangement, display] as const; +} + +/** Where a reader's view was: the row at its top, `top` px below the edge, among + * the rows in view order. */ +export type PlaceAnchor = Readonly<{ + id: string; + top: number; + order: readonly string[]; +}>; +/** SM4, the one pending place for a reader: none (`undefined`), or one of + * these, captured synchronously at commit and consumed once in the layout + * effect. A new capture replaces it; a user scroll or key input cancels it. */ +export type PlaceIntent = + | Readonly<{ kind: "keep" } & PlaceAnchor> + | Readonly<{ kind: "start" }> + | Readonly<{ kind: "end" }> + | Readonly<{ kind: "reveal"; id: string }>; +/** What to do: put row `id` `top` px below the edge, or go to an end. */ +export type Placement = Readonly<{ id: string; top: number }> | "start" | "end"; + +/** The nearest row to the anchor that is still shown, preferring the row below on a tie. */ +export function nearestShown( + anchor: PlaceAnchor, + shown: (id: string) => boolean, +) { + const index = anchor.order.indexOf(anchor.id); + if (index < 0) return undefined; + for (let distance = 0; distance < anchor.order.length; distance++) + for (const at of [index + distance, index - distance]) { + const id = anchor.order[at]; + if (id !== undefined && shown(id)) return id; + } + return undefined; +} + +/** The intent a presentation's `place` asks for, given where the view was. A + * withdraw is `"keep"`. With no anchor there is nothing to keep: the start. */ +export function placeIntent( + place: Display["place"], + anchor: PlaceAnchor | undefined, +): PlaceIntent { + if (place === "start") return { kind: "start" }; + if (place === "keep") + return anchor ? { kind: "keep", ...anchor } : { kind: "start" }; + return { kind: "reveal", id: place.id }; +} + +/** SM4's holder: `none -> intent -> placement -> none`. A capture replaces + * whatever is held; `take` resolves the intent once into a placement that stays + * until `done` (a row in a closed branch needs another commit); input cancels. */ +export function createPlace() { + let pending: PlaceIntent | undefined; + let held: Placement | undefined; + return { + capture(intent: PlaceIntent) { + pending = intent; + held = undefined; + }, + cancel() { + pending = undefined; + held = undefined; + }, + /** The placement to apply now, if any. `keep` goes to the nearest shown row, + * else `fallback`. A `reveal` of a row not shown places nothing. */ + take( + shown: (id: string) => boolean, + fallback: "start" | "end" = "start", + ): Placement | undefined { + const intent = pending; + pending = undefined; + if (!intent) return held; + if (intent.kind === "start" || intent.kind === "end") held = intent.kind; + else if (intent.kind === "reveal") + held = shown(intent.id) ? { id: intent.id, top: 0 } : undefined; + else { + const id = nearestShown(intent, shown); + held = id === undefined ? fallback : { id, top: intent.top }; + } + return held; + }, + /** The held placement was applied, or can never be. */ + done() { + held = undefined; + }, + }; +} + +/** A reader's place keeper. The anchor is read from the rows being replaced: + * `anchor` runs as the host announces a change, before the commit. A withdraw + * with nothing in view follows the end, as an opening does. */ +export function usePlace( + arrangement: Arrangement | undefined, + anchor: () => PlaceAnchor | undefined, +) { + const place = useMemo(createPlace, []); + const read = useEffectEvent(anchor); + useLayoutEffect(() => { + if (!arrangement) return; + let seen: number | undefined; + const capture = (at: PlaceAnchor | undefined) => { + const next = arrangement.snapshot(); + if (next?.revision === seen) return; + seen = next?.revision; + place.capture( + next || at ? placeIntent(next?.place ?? "keep", at) : { kind: "end" }, + ); + }; + // Presenting already, from before this reader could watch: no old rows. + capture(undefined); + return arrangement.subscribe(() => capture(read())); + }, [arrangement, place]); + return place; +} diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx new file mode 100644 index 0000000000..db0adf9964 --- /dev/null +++ b/src/features/messages/arranger-plugin.test.tsx @@ -0,0 +1,1032 @@ +// @vitest-environment jsdom +import { Context } from "@deepseek-ai/cordis"; +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import React, { useLayoutEffect } from "react"; +import { afterEach, beforeAll, expect, it, vi } from "vitest"; +import { + channelFixture, + threadFixture, + type Fixture, +} from "../../../tests/fixtures/conversation-arranger/fixtures"; +import * as arranger from "../../../tests/fixtures/conversation-arranger/plugin"; +import { + CHANNEL, + createWorld, + EDIT, + mint, + openSession, + prove, + REACTION, + T, +} from "../../../tests/fixtures/conversation-arranger/relay"; +import { ComposerAccessories } from "../conversation/ComposerAccessories"; +import type { + ComposerAccessoryProps, + PresentResult, +} from "../conversation/contracts"; +import { ConversationService } from "../conversation/service"; +import type { PluginModule } from "../../plugins/api"; +import { PluginRuntime } from "../../plugins/runtime"; +import { + hasEventProof, + type EventData, + type RelayEvent, +} from "../relay/events"; +import { CHANNEL_LIMITS } from "../relay/store"; +import type { RelaySession } from "../relay/session"; +import { THREAD_LIMITS } from "../relay/threads"; +import { createArrangement } from "./arrangement"; + +// The test plugin stands in for an installed one: it is loaded through the +// plugin runtime, mounted in the reader slot of a real arrangement host over a +// real relay session, and reads a fixture relay through the real reader. What +// it shows is checked against an oracle built from the raw events, not from +// `foldRows`. + +let thread: Fixture & { root: RelayEvent }; +let channel: Fixture; +beforeAll(async () => { + thread = await threadFixture(); + channel = await channelFixture(); +}, 60_000); + +const cleanups: (() => Promise | unknown)[] = []; +afterEach(async () => { + cleanup(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + for (const dispose of cleanups.splice(0)) await dispose(); +}); + +const PLUGIN = { + manifest: { id: "test.arranger", name: "Arranger", apiVersion: 1 as const }, + enabled: true, + source: "external" as const, + revision: "one", + previous: null, + reloadable: true, + error: null, +}; + +const marked = (event: EventData, name: string) => + event.tags.flatMap(([tag, id]) => (tag === name && id ? [id] : [])); +/** What the rows should be, counted from the raw events by hand: deletions by + * the author of their target, reactions counted per account. */ +function oracle(events: readonly EventData[], rootId?: string) { + const byId = new Map(events.map((event) => [event.id, event])); + const deleted = new Set(); + for (const event of events) + if (event.kind === 5) + for (const id of marked(event, "e")) + if (byId.get(id)?.pubkey === event.pubkey) deleted.add(id); + const rows = events.filter( + (event) => + event.kind === 9 && + event.id !== rootId && + !deleted.has(event.id) && + (rootId + ? marked(event, "e").includes(rootId) + : marked(event, "e").length === 0), + ); + const reactors = new Map>( + rows.map((row) => [row.id, new Set()]), + ); + const reactions = new Map(rows.map((row) => [row.id, 0])); + for (const event of events) + if (event.kind === REACTION && !deleted.has(event.id)) + for (const id of marked(event, "e")) { + reactors.get(id)?.add(event.pubkey); + if (reactions.has(id)) reactions.set(id, (reactions.get(id) ?? 0) + 1); + } + const score = (id: string) => reactors.get(id)?.size ?? 0; + // The latest edit by a row's own author replaces its text. + const edits = new Map(); + for (const event of events) + if (event.kind === EDIT && !deleted.has(event.id)) + for (const id of marked(event, "e")) { + const last = edits.get(id); + if ( + byId.get(id)?.pubkey === event.pubkey && + (!last || last.created_at < event.created_at) + ) + edits.set(id, event); + } + /** The rows of `order` whose text, as edited, contains `needle` in any case. */ + const matching = (order: readonly EventData[], needle: string) => + order.filter((row) => + (edits.get(row.id) ?? row).content + .toLowerCase() + .includes(needle.toLowerCase()), + ); + /** The relay's `newer` order: created_at ascending, id descending. */ + const oldest = [...rows].sort( + (a, b) => a.created_at - b.created_at || (a.id < b.id ? 1 : -1), + ); + const top = [...rows].sort( + (a, b) => score(b.id) - score(a.id) || (a.id < b.id ? -1 : 1), + ); + return { rows, score, reactions, oldest, top, deleted, matching }; +} +const count = new Intl.NumberFormat("en-US").format; +/** The arranger's position text; a `+` after the total marks rows still unread. */ +const replies = (from: number, to: number, total: number, noun = "Replies") => + `${noun} ${count(from)}–${count(to)} of ${count(total)}`; +const idsOf = (rows: readonly { id: string }[]) => rows.map((row) => row.id); +const distinct = (row: { + reactions: readonly { events: readonly { authorId: string }[] }[]; +}) => + new Set(row.reactions.flatMap((group) => group.events.map((e) => e.authorId))) + .size; +const reactionTo = async ( + key: (typeof thread.reactors)[number], + target: string, + at: number, +) => + ( + await prove([ + mint(key, { + kind: REACTION, + content: "👍", + created_at: at, + tags: [ + ["h", CHANNEL], + ["e", target], + ], + }), + ]) + )[0] as RelayEvent; + +type Mount = { + fixture: Fixture; + /** A thread (its root and replies) or the channel's top level. */ + rootId?: string | undefined; + windowNewer?: boolean; + /** A second reader accessory, ordered first, for presenting by hand. */ + probe?: boolean; + targetId?: string; +}; +async function mount({ fixture, rootId, windowNewer, probe, targetId }: Mount) { + const world = createWorld(fixture.events); + const relay = openSession({ + world, + ...(windowNewer === undefined ? {} : { windowNewer }), + }); + const answers: (readonly RelayEvent[])[] = []; + const read = relay.session.snapshotRead; + let holds = 0; + const session = { + ...relay.session, + retain: () => { + holds++; + return relay.session.retain(); + }, + ...(read + ? { + snapshotRead: (...args: Parameters) => + read(...args).then((events) => { + answers.push(events); + return events; + }), + } + : {}), + } as RelaySession; + const frames = new Map void>(); + let frameId = 0; + vi.stubGlobal("requestAnimationFrame", (run: () => void) => { + frames.set(++frameId, run); + return frameId; + }); + vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id)); + const arrangement = createArrangement({ + session, + channelId: CHANNEL, + rootId, + limits: rootId ? THREAD_LIMITS : CHANNEL_LIMITS, + }); + const handle: { probe?: ComposerAccessoryProps } = {}; + const module: PluginModule = { + inject: ["react", "conversation"], + apply(ctx) { + arranger.apply(ctx as never); + if (probe) + ctx.conversation.registerAccessory({ + id: "probe", + title: "Probe", + placement: "reader", + order: -1, + component: function Probe(props) { + useLayoutEffect(() => { + handle.probe = props; + }); + return null; + }, + }); + }, + }; + const root = new Context(); + root.provide("react", React); + const runtime = new PluginRuntime(root, async () => module); + const service = new ConversationService(root); + runtime.reconcile([PLUGIN]); + await waitFor(() => + expect(service.accessories.snapshot()).toHaveLength(probe ? 2 : 1), + ); + const view = render( + true} + open={() => true} + />, + ); + cleanups.push(async () => { + view.unmount(); + await runtime.dispose(); + await root.fiber.dispose(); + relay.owner.dispose(); + }); + const unreadTarget = rootId + ? ({ kind: "thread", channelId: CHANNEL, rootId } as const) + : ({ kind: "channel", channelId: CHANNEL } as const); + return { + ...relay, + world, + session, + arrangement, + answers, + handle, + lane: () => + service.accessories.snapshot().find((entry) => entry.id === "arranger"), + click: (name: string) => + fireEvent.click(screen.getByRole("button", { name })), + status: () => screen.getByRole("status").textContent, + /** What the reader shows now, by id. */ + shown: () => idsOf(arrangement.snapshot()?.rows ?? []), + heard: (...events: RelayEvent[]) => act(() => relay.hear(...events)), + /** The refold a live change waits for, once per frame. */ + flush: () => + act(() => { + for (const [id, run] of [...frames]) { + frames.delete(id); + run(); + } + }), + /** What the host's own history holds: nothing a scan reads is in it. */ + recent() { + const recent = relay.session.observe([ + { "#h": [CHANNEL], kinds: [9, 7, 5, 40003], limit: 10_000 }, + ]); + const ids = idsOf(recent.snapshot().events).sort(); + recent.dispose(); + return ids; + }, + unread: () => relay.session.unread.snapshot(unreadTarget), + unreadTarget, + /** The reads the scan made, apart from the host view's own. */ + scanReads: (since: number) => relay.reads.slice(since), + /** Evidence holds the plugin has taken. */ + holds: () => holds, + }; +} +type Harness = Awaited>; + +const ready = (h: Harness) => + waitFor( + () => { + expect(h.status()).not.toMatch(/Reading/); + expect(h.arrangement.snapshot()).toBeDefined(); + }, + { timeout: 30_000 }, + ); +/** The host's own reader: the thread view the panel runs beside the plugin. */ +async function hostView(h: Harness, rootId: string) { + const view = h.owner.session.thread(CHANNEL, rootId); + cleanups.push(() => view.dispose()); + await view.refresh(); + await waitFor(() => expect(view.snapshot().status).toBe("ready")); + return view; +} +const hostState = (view: ReturnType) => { + const { status, root, replies, canLoadMore, limited } = view.snapshot(); + return { + status, + root: root?.id, + replies: idsOf(replies), + canLoadMore, + limited, + }; +}; + +it("ranks a 2,000-reply thread by Top from background reads, leaving the host's view alone", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const h = await mount({ fixture: thread, rootId: root.id }); + const view = await hostView(h, root.id); + void h.session.channels.refresh?.(CHANNEL); + await waitFor(() => + expect(h.session.channels.window(CHANNEL).status).toBe("ready"), + ); + // One reply arrives live and is marked unread: something for a scan to wipe. + const [fresh] = await prove([ + mint(thread.authors[0] as never, { + kind: 9, + content: "fresh", + created_at: T + 60_000, + tags: [ + ["h", CHANNEL], + ["e", root.id, "", "reply"], + ], + }), + ]); + cleanups.push(h.session.unread.subscribe(h.unreadTarget, () => {})); + h.world.add([fresh as RelayEvent]); + h.heard(fresh as RelayEvent); + await h.session.unread.markMessageUnread(CHANNEL, (fresh as RelayEvent).id); + const host = hostState(view); + const recent = h.recent(); + const unread = h.unread(); + const window = h.session.channels.window(CHANNEL); + expect(host.replies.length).toBeGreaterThan(0); + expect(recent.length).toBeGreaterThan(0); + expect(unread.observedCount).toBeGreaterThan(0); + expect(window.rows.length).toBeGreaterThan(0); + const before = h.reads.length; + + h.click("Top"); + await ready(h); + + const reads = h.scanReads(before); + // Six rounds of both ends at once, after the root: seven reads. + expect(reads).toHaveLength(7); + expect(reads.every(({ priority }) => priority === "background")).toBe(true); + const windows = reads + .flatMap(({ filters }) => filters) + .filter((filter) => filter.thread_window); + expect(windows).toHaveLength(12); + expect(windows.every((filter) => filter.root_aux === false)).toBe(true); + expect(windows.filter((filter) => filter.direction === "newer")).toHaveLength( + 6, + ); + // Every page arrived through the reader's verification, bounds included. + const pages = h.answers.filter((page) => page.some((e) => e.kind === 39007)); + expect(pages).toHaveLength(6); + expect(h.answers.flat().every(hasEventProof)).toBe(true); + // The header's reactions are the reader's to show: no page carried them. + expect( + h.answers + .flat() + .some((e) => e.kind === REACTION && marked(e, "e").includes(root.id)), + ).toBe(false); + + // The ranking is the oracle's: 10 rows of 20 accounts, 50 of 5, then ties by id. + expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200))); + expect(want.score(h.shown()[0] as string)).toBe(20); + expect(h.arrangement.snapshot()?.place).toBe("start"); + expect(h.arrangement.snapshot()?.complete).toBe(false); + // The oracle's rows, and the reply that arrived live before the scan. + expect(h.status()).toBe(replies(1, 200, want.rows.length + 1)); + + // The host reads as it did: same view, same recent events, same unread, same window. + expect(hostState(view)).toEqual(host); + expect(h.recent()).toEqual(recent); + expect(h.unread()).toEqual(unread); + expect(h.session.channels.window(CHANNEL)).toEqual(window); +}); + +it("folds every reaction, edit and deletion of the thread as the oracle counts them", async () => { + const { events, root, groups } = thread; + const want = oracle(events, root.id); + const h = await mount({ fixture: thread, rootId: root.id }); + const rows = h.session.foldRows(CHANNEL, events, root.id); + expect( + idsOf(rows) + .filter((id) => id !== root.id) + .sort(), + ).toEqual(idsOf(want.rows).sort()); + for (const row of rows.filter((r) => r.id !== root.id)) { + expect(distinct(row)).toBe(want.score(row.id)); + expect( + row.reactions.reduce((sum, group) => sum + group.events.length, 0), + ).toBe(want.reactions.get(row.id)); + } + // Each group the fixture built folds as designed. + const folded = new Map(rows.map((row) => [row.id, row])); + expect(groups.deleted?.every((id) => !folded.has(id))).toBe(true); + expect( + groups.top20?.every((id) => distinct(folded.get(id) as never) === 20), + ).toBe(true); + expect( + groups.twice?.every((id) => distinct(folded.get(id) as never) === 1), + ).toBe(true); + expect( + groups.cancelled?.every((id) => distinct(folded.get(id) as never) === 0), + ).toBe(true); + expect( + groups.edited?.every((id) => folded.get(id)?.content.endsWith("(edited)")), + ).toBe(true); +}); + +it("presents a thread that fits whole as complete", async () => { + const small = await threadFixture(100); + const want = oracle(small.events, small.root.id); + const h = await mount({ fixture: small, rootId: small.root.id }); + h.click("Top"); + await ready(h); + expect(h.shown()).toEqual(idsOf(want.top)); + expect(h.arrangement.snapshot()?.complete).toBe(true); + // Nothing more to show or read. + expect(screen.queryByRole("button", { name: "More" })).toBeNull(); +}); + +it("grows a Top window from 200 to 460 rows, the most a thread reader shows, and refuses 461", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const h = await mount({ fixture: thread, rootId: root.id, probe: true }); + h.click("Top"); + await ready(h); + expect(h.shown()).toHaveLength(200); + const reads = h.reads.length; + + h.click("More"); + await waitFor(() => expect(h.shown()).toHaveLength(460)); + expect(h.shown()).toEqual(idsOf(want.top.slice(0, 460))); + // The rows were read already: growing reads nothing. + expect(h.reads).toHaveLength(reads); + // The plugin's 460 are within the reader's bounds; a probe's 461 are not. + const ids = idsOf(want.rows.slice(0, 461)); + let result: PresentResult | undefined; + act(() => { + result = h.handle.probe?.present?.({ ids, events }); + }); + expect(result).toBe("limit"); + expect(h.shown()).toHaveLength(460); + // The plugin's budget leaves room under the event bound for live aux. + expect(h.arrangement.limits).toEqual(THREAD_LIMITS); +}); + +/** Types into the bar's filter and submits it, as a person would. */ +const find = (text: string) => { + fireEvent.change(screen.getByRole("searchbox", { name: "Filter replies" }), { + target: { value: text }, + }); + fireEvent.submit(screen.getByRole("search")); +}; +const statusIs = (h: Harness, text: string | RegExp) => + waitFor( + () => + typeof text === "string" + ? expect(h.status()).toBe(text) + : expect(h.status()).toMatch(text), + { timeout: 30_000 }, + ); + +it("pages a Top list past the reader's 460 rows, each page the oracle's slice, and back", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const total = want.rows.length; + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Top"); + await ready(h); + expect(screen.queryByRole("button", { name: "Previous" })).toBeNull(); + h.click("More"); + await statusIs(h, replies(1, 460, total)); + const pages: [number, number][] = [ + [461, 920], + [921, 1380], + [1381, 1840], + [1841, total], + ]; + for (const [from, to] of pages) { + h.click("Next"); + await statusIs(h, replies(from, to, total)); + expect(h.shown()).toEqual(idsOf(want.top.slice(from - 1, to))); + expect(h.arrangement.snapshot()?.place).toBe("start"); + } + // The last window has no Next; Previous steps back through the same slices. + expect(screen.queryByRole("button", { name: "Next" })).toBeNull(); + h.click("Previous"); + await statusIs(h, replies(1381, 1840, total)); + expect(h.shown()).toEqual(idsOf(want.top.slice(1380, 1840))); +}); + +it("filters every row by its edited text, in any case, whatever the scan had read, then pages the matches in the current sort", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const h = await mount({ fixture: thread, rootId: root.id }); + + // An Oldest view has read only its first windows: filtering finishes the scan. + h.click("Oldest"); + await ready(h); + expect(h.status()).toMatch(/\+$/); + const gizmo = want.matching(want.oldest, "gizmo"); + expect(gizmo.length).toBeGreaterThan(50); + expect(gizmo.length).toBeLessThan(200); + // Some matches lie past anything it had read (two pages of 200), and some + // replies that said it were edited away, which only the folded text shows. + expect(gizmo.some((row) => want.oldest.indexOf(row) >= 600)).toBe(true); + expect( + want.rows.filter((row) => /gizmo/i.test(row.content)).length, + ).toBeGreaterThan(gizmo.length); + find("GIZMO"); + await statusIs(h, replies(1, gizmo.length, gizmo.length)); + expect(h.shown()).toEqual(idsOf(gizmo)); + + // The same filter ranks by Top. + h.click("Top"); + await statusIs(h, replies(1, gizmo.length, gizmo.length)); + expect(h.shown()).toEqual(idsOf(want.matching(want.top, "gizmo"))); + + // A filter with more matches than a window pages like the whole list. + find("reply 1"); + const many = want.matching(want.top, "reply 1"); + expect(many.length).toBeGreaterThan(920); + await statusIs(h, replies(1, 200, many.length)); + h.click("More"); + await statusIs(h, replies(1, 460, many.length)); + h.click("Next"); + await statusIs(h, replies(461, 920, many.length)); + expect(h.shown()).toEqual(idsOf(many.slice(460, 920))); + + // Nothing matches; clearing shows every row again. + find("no such words"); + await statusIs(h, "No replies match"); + expect(h.shown()).toEqual([]); + find(""); + await statusIs(h, replies(1, 200, want.rows.length)); +}); + +it("reaches the last reply of an Oldest list by Next, reading forward as it goes", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const total = want.rows.length; + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Oldest"); + await ready(h); + h.click("More"); + await waitFor(() => expect(h.shown()).toHaveLength(460)); + // It has read only as far as the windows reach. + expect(h.status()).toMatch(/\+$/); + for (const from of [461, 921, 1381]) { + h.click("Next"); + await statusIs( + h, + new RegExp(`^Replies ${count(from)}–[\\d,]+ of [\\d,]+\\+?$`), + ); + expect(h.shown()).toEqual(idsOf(want.oldest.slice(from - 1, from + 459))); + } + h.click("Next"); + await statusIs(h, replies(1841, total, total)); + expect(h.shown()).toEqual(idsOf(want.oldest.slice(1840))); + expect(h.shown().at(-1)).toBe(want.oldest.at(-1)?.id); + expect(screen.queryByRole("button", { name: "Next" })).toBeNull(); +}, 60_000); + +it("re-ranks when a reaction lands on a row that is not shown", async () => { + const { events, root, groups, reactors } = thread; + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Top"); + await ready(h); + const shown = new Set(h.shown()); + const quiet = (groups.one ?? []).find((id) => !shown.has(id)) as string; + expect(quiet).toBeDefined(); + // Thirty accounts react to it: more than any shown row has. + const live = await Promise.all( + reactors + .slice(0, 30) + .map((key, i) => reactionTo(key, quiet, T + 20_000 + i)), + ); + h.heard(...live); + const want = oracle([...events, ...live], root.id); + await waitFor(() => expect(h.shown()[0]).toBe(quiet)); + expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200))); + expect(h.arrangement.snapshot()?.rows[0]?.reactions).not.toHaveLength(0); +}); + +it("hides a shown row when its deletion arrives live", async () => { + const { events, root, authors } = thread; + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Top"); + await ready(h); + const [first] = h.shown() as [string]; + const row = events.find((event) => event.id === first) as RelayEvent; + const author = authors.find((key) => key.pubkey === row.pubkey); + const [gone] = await prove([ + mint(author as never, { + kind: 5, + content: "", + created_at: T + 20_000, + tags: [ + ["h", CHANNEL], + ["e", first], + ], + }), + ]); + h.heard(gone as RelayEvent); + h.flush(); + const want = oracle([...events, gone as RelayEvent], root.id); + await waitFor(() => expect(h.shown()).not.toContain(first)); + // The next row takes its place. + expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200))); +}); + +it("keeps the viewer's own reply in view from sending to seen, then ranks it as any row", async () => { + const { root } = thread; + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Top"); + await ready(h); + const own = () => + h.arrangement.snapshot()?.rows.find((row) => row.content === "mine"); + void h.owner.session.messages.reply(CHANNEL, root.id, "mine"); + await waitFor(() => expect(own()?.delivery).toBe("sending")); + // Pinned above the 200 ranked rows, which keep their number. + expect(h.shown()[0]).toBe(own()?.id); + expect(h.shown()).toHaveLength(201); + h.publications[0]?.accept(); + await waitFor(() => expect(own()?.delivery).toBe("accepted")); + expect(h.shown()[0]).toBe(own()?.id); + // The relay echoes it back: it is an ordinary row now, with no reactions. + h.heard(h.publications[0]?.event as RelayEvent); + await waitFor(() => expect(own()).toBeUndefined()); + expect(h.shown()).toHaveLength(200); +}); + +it("paints Oldest first from the reads its first window needs and pages forward from where it stopped", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const h = await mount({ fixture: thread, rootId: root.id }); + const before = h.reads.length; + h.click("Oldest"); + await ready(h); + const reads = h.scanReads(before); + // The root, then pages from the thread's start until 200 replies survive deletion. + expect(reads).toHaveLength(3); + const [page] = reads[1]?.filters ?? []; + expect(page).toMatchObject({ + thread_window: true, + direction: "newer", + root_aux: false, + }); + expect(page?.after).toBeUndefined(); + expect(reads.every(({ priority }) => priority === "background")).toBe(true); + expect(h.shown()).toEqual(idsOf(want.oldest.slice(0, 200))); + expect(h.arrangement.snapshot()?.complete).toBe(false); + + h.click("More"); + await waitFor(() => expect(h.shown()).toHaveLength(460)); + expect(h.shown()).toEqual(idsOf(want.oldest.slice(0, 460))); + const next = h.scanReads(before).at(-1)?.filters[0]; + expect(next).toMatchObject({ direction: "newer", root_aux: false }); + expect(next?.after).toBeDefined(); + expect(next?.after_id).toBeDefined(); +}); + +it("reads a thread through older pages alone when the relay has no newer windows", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const h = await mount({ + fixture: thread, + rootId: root.id, + windowNewer: false, + }); + const before = h.reads.length; + h.click("Top"); + await ready(h); + const reads = h.scanReads(before); + // The root, then ten pages of 200 from the newest. + expect(reads).toHaveLength(11); + const filters = reads.flatMap(({ filters }) => filters); + expect(filters.some((f) => f.direction === "newer")).toBe(false); + expect(filters.some((f) => f.root_aux !== undefined)).toBe(false); + expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200))); +}); + +it("shows the row it was opened to first and places the reader on it", async () => { + const { events, root, groups } = thread; + const want = oracle(events, root.id); + const target = (groups.one ?? [])[0] as string; + const h = await mount({ fixture: thread, rootId: root.id, targetId: target }); + h.click("Top"); + await ready(h); + expect(h.shown()[0]).toBe(target); + expect(h.shown().slice(1)).toEqual( + idsOf(want.top.filter((row) => row.id !== target).slice(0, 200)), + ); + expect(h.arrangement.snapshot()?.place).toEqual({ id: target }); +}); + +it("nests replies under their shown parents and opens the branches that hold them", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Oldest"); + await ready(h); + const display = h.arrangement.snapshot(); + const shown = h.shown(); + const parents = display?.parents as ReadonlyMap; + const signed = new Map( + want.rows.map((row) => [ + row.id, + marked(row, "e").length > 1 ? marked(row, "e")[1] : undefined, + ]), + ); + // A row nests where its signed parent is shown above it; none nests under a row that is not. + expect(parents.size).toBeGreaterThan(50); + for (const [id, parent] of parents) { + expect(signed.get(id)).toBe(parent); + expect(shown.indexOf(parent)).toBeGreaterThanOrEqual(0); + expect(shown.indexOf(parent)).toBeLessThan(shown.indexOf(id)); + } + expect(new Set(display?.open)).toEqual(new Set(parents.values())); +}); + +it("leaves its place, and the reader's own rows, when withdrawn", async () => { + const { root } = thread; + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Top"); + await ready(h); + h.click("Buzz order"); + await waitFor(() => expect(h.arrangement.snapshot()).toBeUndefined()); + expect(h.status()).toBe(""); + expect(h.arrangement.status(h.lane() as never)).toBe("none"); +}); + +it("waits behind another arrangement and shows when that one leaves", async () => { + const { events, root, rows } = thread; + const want = oracle(events, root.id); + const h = await mount({ fixture: thread, rootId: root.id, probe: true }); + const first = idsOf(rows.slice(0, 3)); + let result: PresentResult | undefined; + act(() => { + result = h.handle.probe?.present?.({ ids: first, events }); + }); + expect(result).toBe("shown"); + h.click("Top"); + await waitFor(() => expect(h.status()).toMatch(/waiting/), { + timeout: 30_000, + }); + // The probe's rows stay. + expect(h.shown().sort()).toEqual([...first].sort()); + act(() => { + h.handle.probe?.present?.(null); + }); + await waitFor(() => expect(h.shown()).toHaveLength(200)); + expect(h.status()).toBe(replies(1, 200, want.rows.length)); +}); + +it("shows fewer rows when live growth ends its presentation", async () => { + const { root, reactors } = thread; + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Top"); + await ready(h); + h.click("More"); + await waitFor(() => expect(h.shown()).toHaveLength(460)); + const rows = h.shown(); + // Past the 2,000 events the reader holds, from rows it shows. + const live = await Promise.all( + Array.from({ length: 400 }, (_, i) => + reactionTo( + reactors[i % reactors.length] as never, + rows[i % rows.length] as string, + T + 30_000 + i, + ), + ), + ); + h.heard(...live); + // It re-presents half as many, and says so. + await waitFor(() => expect(h.shown()).toHaveLength(230)); + expect(h.arrangement.status(h.lane() as never)).toBe("shown"); + expect(h.status()).toBe( + `${replies(1, 230, oracle(thread.events, root.id).rows.length)} Showing fewer rows: the reader reached its limit.`, + ); +}); + +it("reads the whole thread again after a reconnect once it is visible, and is not exact until it has", async () => { + const { events, root, groups, reactors, authors } = thread; + const h = await mount({ fixture: thread, rootId: root.id }); + act(() => h.connection("connected")); + h.click("Top"); + await ready(h); + const total = oracle(events, root.id).rows.length; + await statusIs(h, replies(1, 200, total)); + act(() => h.connection("retrying")); + await statusIs(h, `${replies(1, 200, total)}+`); + // What the stream never delivered while it was down, whatever its age: forty + // accounts react to a reply that is not shown, and the first shown row's + // author deletes it. + const [first] = h.shown() as [string]; + const quiet = (groups.one ?? []).find( + (id) => !h.shown().includes(id), + ) as string; + const author = authors.find( + (key) => key.pubkey === events.find((event) => event.id === first)?.pubkey, + ); + const missed = [ + ...(await Promise.all( + reactors.map((key, i) => reactionTo(key, quiet, T + 30_000 + i)), + )), + ...(await prove([ + mint(author as never, { + kind: 5, + content: "", + created_at: T + 100, + tags: [ + ["h", CHANNEL], + ["e", first], + ], + }), + ])), + ] as RelayEvent[]; + h.world.add(missed); + const before = h.reads.length; + // The wait is random: take the shortest. A hidden window reads nothing + // until it is shown. + vi.spyOn(Math, "random").mockReturnValue(0); + const visibility = vi + .spyOn(document, "visibilityState", "get") + .mockReturnValue("hidden"); + act(() => h.connection("connected")); + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + expect(h.reads.length).toBe(before); + expect(h.status()).toBe(`${replies(1, 200, total)}+`); + visibility.mockReturnValue("visible"); + act(() => { + document.dispatchEvent(new Event("visibilitychange")); + }); + const want = oracle([...events, ...missed], root.id); + await statusIs(h, replies(1, 200, want.rows.length)); + expect(h.shown()[0]).toBe(quiet); + expect(h.shown()).not.toContain(first); + expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200))); + const scan = h + .scanReads(before) + .filter(({ filters }) => filters.some((f) => f.thread_window)); + expect(scan.length).toBeGreaterThan(0); + expect(scan.every(({ priority }) => priority === "background")).toBe(true); +}, 60_000); + +it("keeps an Oldest list in order when replies arrive before the read reaches them", async () => { + const { events, root, authors } = thread; + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Oldest"); + await ready(h); + // More new replies than the read is ahead of the next window. + const late = (await prove( + Array.from({ length: 30 }, (_, i) => + mint(authors[i % authors.length] as never, { + kind: 9, + content: `late reply ${i}`, + created_at: T + 40_000 + i, + tags: [ + ["h", CHANNEL], + ["e", root.id, "", "reply"], + ], + }), + ), + )) as RelayEvent[]; + h.world.add(late); + h.heard(...late); + const want = oracle([...events, ...late], root.id); + const total = want.rows.length; + // Each window is the oracle's slice: the new replies come last, not early. + for (let from = 201; from <= total; from += 200) { + h.click("Next"); + const to = Math.min(from + 199, total); + await waitFor( + () => expect(h.shown()).toEqual(idsOf(want.oldest.slice(from - 1, to))), + { timeout: 30_000 }, + ); + } + expect(h.shown().slice(-30)).toEqual(idsOf(late)); +}, 60_000); + +/** The host's own channel window, loaded, with three live rows, one marked unread. */ +async function hostChannel(h: Harness) { + void h.session.channels.refresh?.(CHANNEL); + await waitFor(() => + expect(h.session.channels.window(CHANNEL).status).toBe("ready"), + ); + const live = await prove( + [1, 2, 3].map((n) => + mint(channel.authors[0] as never, { + kind: 9, + content: `live ${n}`, + created_at: T + 50_000 + n, + tags: [["h", CHANNEL]], + }), + ), + ); + cleanups.push(h.session.unread.subscribe(h.unreadTarget, () => {})); + h.heard(...live); + await h.session.unread.markMessageUnread(CHANNEL, (live[0] as RelayEvent).id); + expect(h.unread().observedCount).toBeGreaterThan(0); +} + +it("paints a channel from the start after one read", async () => { + const want = oracle(channel.events); + const h = await mount({ fixture: channel }); + await hostChannel(h); + const before = h.reads.length; + h.click("Oldest"); + await ready(h); + const reads = h.scanReads(before); + expect(reads).toHaveLength(1); + expect(reads[0]?.priority).toBe("background"); + expect(reads[0]?.filters).toMatchObject([ + { top_level: true, direction: "newer", limit: 200 }, + ]); + expect(reads[0]?.filters[0]?.after).toBeUndefined(); + expect(h.shown()).toEqual(idsOf(want.oldest.slice(0, 200))); + expect(h.arrangement.snapshot()?.complete).toBe(false); +}); + +it("ranks a 5,000-row channel by top reacted from verified windows, without touching the host's history or unread", async () => { + const want = oracle(channel.events); + const h = await mount({ fixture: channel }); + await hostChannel(h); + const window = h.session.channels.window(CHANNEL); + const unread = h.unread(); + const recent = h.recent(); + const before = h.reads.length; + + h.click("Top"); + await ready(h); + + const reads = h.scanReads(before); + expect(reads.every(({ priority }) => priority === "background")).toBe(true); + // 5,000 rows, 200 to a page: 25 windows, each with the relay's signed bounds. + expect(reads).toHaveLength(25); + const pages = h.answers.filter((page) => page.some((e) => e.kind === 39006)); + expect(pages).toHaveLength(25); + expect(h.answers.flat().every(hasEventProof)).toBe(true); + expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200))); + expect(want.score(h.shown()[0] as string)).toBe(20); + + expect(h.session.channels.window(CHANNEL).historyLimited).toBeFalsy(); + expect(h.session.channels.window(CHANNEL)).toEqual(window); + expect(h.unread()).toEqual(unread); + expect(h.recent()).toEqual(recent); +}); + +it("ranks a new live message in a channel's Top list", async () => { + const { events, authors, reactors } = channel; + const h = await mount({ fixture: channel }); + h.click("Top"); + await ready(h); + const [fresh] = (await prove([ + mint(authors[0] as never, { + kind: 9, + content: "a new message", + created_at: T + 60_000, + tags: [["h", CHANNEL]], + }), + ])) as [RelayEvent]; + h.heard(fresh); + // Forty accounts react: more than any row has. + const reactions = await Promise.all( + reactors.map((key, i) => reactionTo(key, fresh.id, T + 60_001 + i)), + ); + h.heard(...reactions); + const want = oracle([...events, fresh, ...reactions]); + await waitFor(() => expect(h.shown()[0]).toBe(fresh.id)); + expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200))); +}, 60_000); + +it("holds nothing from a channel's live messages before a sort is chosen", async () => { + const h = await mount({ fixture: channel }); + await hostChannel(h); + expect(h.holds()).toBe(0); + h.click("Top"); + await ready(h); + expect(h.holds()).toBeGreaterThan(0); +}); + +it("pages a channel's Top list past the reader's 2,400 rows", async () => { + const want = oracle(channel.events); + const h = await mount({ fixture: channel }); + h.click("Top"); + await ready(h); + for (const size of [460, 720, 980, 1240, 1500, 1760, 2020, 2280, 2400]) { + h.click("More"); + await statusIs(h, replies(1, size, 5000, "Messages")); + } + expect(screen.queryByRole("button", { name: "More" })).toBeNull(); + h.click("Next"); + await statusIs(h, replies(2401, 4800, 5000, "Messages")); + expect(h.shown()).toEqual(idsOf(want.top.slice(2400, 4800))); + h.click("Next"); + await statusIs(h, replies(4801, 5000, 5000, "Messages")); + expect(h.shown()).toEqual(idsOf(want.top.slice(4800))); +}, 120_000); diff --git a/src/features/messages/reply-tree.test.ts b/src/features/messages/reply-tree.test.ts index c4ccf705cb..205ac31231 100644 --- a/src/features/messages/reply-tree.test.ts +++ b/src/features/messages/reply-tree.test.ts @@ -129,3 +129,48 @@ it("preserves normal nesting for edited failure messages and messages with attac const tree = replyTree([request, edited, attachment], "root"); expect(tree.children.get(request.id)).toEqual([edited, attachment]); }); + +it("nests given display parents to any depth, over signed ancestry", () => { + const rows = ["a", "b", "c", "d", "e"].map((id) => row(id, "root")); + const display: Record = { b: "a", c: "b", d: "c", e: "d" }; + const tree = replyTree(rows, "root", (id) => display[id]); + expect(tree.children.get(undefined)?.map(({ id }) => id)).toEqual(["a"]); + expect(tree.children.get("d")?.map(({ id }) => id)).toEqual(["e"]); + expect(tree.ancestors("e")).toEqual(["d", "c", "b", "a"]); +}); +it("lifts unknown, later, self and root display parents, so a cycle breaks at its later row", () => { + const rows = ["a", "b", "c", "d", "e", "f"].map((id) => + row(id, id === "a" ? "root" : "a"), + ); + const display: Record = { + b: "missing", + c: "f", // later + d: "d", + e: "root", + f: "c", // with c -> f, a cycle; f nests under the earlier c + }; + const tree = replyTree(rows, "root", (id) => display[id]); + expect(tree.children.get(undefined)?.map(({ id }) => id)).toEqual([ + "a", + "b", + "c", + "d", + "e", + ]); + expect(tree.children.get("c")?.map(({ id }) => id)).toEqual(["f"]); + expect(tree.ancestors("f")).toEqual(["c"]); + expect(tree.ancestors("c")).toEqual([]); + // Signed ancestry is not used: no row nests under "a". + expect(tree.children.get("a")).toBeUndefined(); +}); +it("keeps execution-failure captions where display parents put them", () => { + const request = row("request", "root"); + const notice: ChannelMessage = { + ...row("failure", request.id), + notice: "execution-failure", + }; + const tree = replyTree([request, notice], "root", (id) => + id === notice.id ? request.id : undefined, + ); + expect(tree.children.get(request.id)).toEqual([notice]); +}); diff --git a/src/features/messages/reply-tree.ts b/src/features/messages/reply-tree.ts index db0ae98f1f..74165cd322 100644 --- a/src/features/messages/reply-tree.ts +++ b/src/features/messages/reply-tree.ts @@ -4,8 +4,16 @@ import type { ChannelMessage } from "../relay/contracts"; * A forest of the available history, never a claim that all parents were loaded. * Branches are one level deep: a reply to a nested reply joins its branch, in * order, so continuing a conversation never drifts further in. + * + * `displayParent` replaces those branches with given parents, to any depth: + * a row nests under its parent only when the parent is an earlier row, so an + * unknown, later, self or cyclic parent puts it at the top level. */ -export function replyTree(rows: readonly ChannelMessage[], rootId?: string) { +export function replyTree( + rows: readonly ChannelMessage[], + rootId?: string, + displayParent?: (id: string) => string | undefined, +) { const byId = new Map(rows.map((row) => [row.id, row])); const parentOf = (row: ChannelMessage | undefined) => { const parent = row?.replyParentId; @@ -23,7 +31,21 @@ export function replyTree(rows: readonly ChannelMessage[], rootId?: string) { }; const parents = new Map(); const children = new Map(); - for (const row of rows) { + const place = (row: ChannelMessage, parent: string | undefined) => { + if (parent) parents.set(row.id, parent); + const siblings = children.get(parent) ?? []; + siblings.push(row); + children.set(parent, siblings); + }; + const index = new Map( + displayParent ? rows.map((row, at) => [row.id, at]) : [], + ); + for (const [at, row] of rows.entries()) { + if (displayParent) { + const parent = displayParent(row.id); + place(row, (index.get(parent ?? "") ?? at) < at ? parent : undefined); + continue; + } let parent = parentOf(row); if (parent === rootId || !parent || !byId.has(parent)) parent = undefined; // Malformed ancestry must not hide rows or recurse forever. @@ -43,10 +65,7 @@ export function replyTree(rows: readonly ChannelMessage[], rootId?: string) { if (!next || next === rootId || !byId.has(next)) break; parent = next; } - if (parent) parents.set(row.id, parent); - const siblings = children.get(parent) ?? []; - siblings.push(row); - children.set(parent, siblings); + place(row, parent); } return { children, diff --git a/src/features/messages/use-reading.test.ts b/src/features/messages/use-reading.test.ts index 9e69e8df78..ecef5a90a8 100644 --- a/src/features/messages/use-reading.test.ts +++ b/src/features/messages/use-reading.test.ts @@ -27,9 +27,17 @@ function setup({ settled = true, strict = false, latestMessageId = undefined as string | undefined, + endMessageId = undefined as string | undefined, + partial = false, rootId = undefined as string | undefined, enabled = true, - focus = "element" as "element" | "composer" | "parent" | "outside" | "header", + focus = "element" as + | "element" + | "composer" + | "parent" + | "outside" + | "header" + | "bar", } = {}) { vi.useFakeTimers(); vi.spyOn(document, "hasFocus").mockReturnValue(focused); @@ -48,8 +56,10 @@ function setup({ panel.dataset.readingSurface = ""; const header = document.createElement("button"); panel.append(header, element); - document.body.append(panel, composer, parent, outside); - ({ element, composer, parent, outside, header })[focus].focus(); + // The list's reader bar, beside it outside any reading surface. + const bar = document.createElement("button"); + document.body.append(panel, composer, parent, outside, bar); + ({ element, composer, parent, outside, header, bar })[focus].focus(); vi.spyOn(element, "getClientRects").mockReturnValue([ new DOMRect(0, 0, 500, 500), ] as unknown as DOMRectList); @@ -62,6 +72,7 @@ function setup({ row("clipped", 450, 550), ); const scroller = { current: element }; + const controls = { current: bar }; const position = { current: settled }; let mutation = () => {}; const disconnected = vi.fn(); @@ -92,7 +103,7 @@ function setup({ let observe = async () => {}; // The real lease fences on the manual-unread revision current at creation. let manual = 0; - const reading = vi.fn(() => { + const reading = vi.fn((..._call: readonly unknown[]) => { const lease = { manual, view: vi.fn(), @@ -116,6 +127,9 @@ function setup({ scroller, settled: position, latestMessageId, + endMessageId, + partial, + controls, rootId, enabled, }, @@ -138,6 +152,7 @@ function setup({ composer, parent, outside, + bar, session, reading, leases, @@ -165,6 +180,9 @@ function setup({ scroller, settled: position, latestMessageId, + endMessageId, + partial, + controls, rootId, enabled, }), @@ -175,6 +193,22 @@ function setup({ scroller, settled: position, latestMessageId: id, + endMessageId, + partial, + controls, + rootId, + enabled, + }), + setPartial: (next: boolean) => + view.rerender({ + session, + channelId: "room", + scroller, + settled: position, + latestMessageId, + endMessageId, + partial: next, + controls, rootId, enabled, }), @@ -193,7 +227,7 @@ function row(id: string, top: number, bottom: number) { } it("reports only fully visible settled evidence after dwell, not mounted overscan", () => { const h = setup(); - expect(h.reading).toHaveBeenCalledExactlyOnceWith("room", undefined); + expect(h.reading).toHaveBeenCalledExactlyOnceWith("room", undefined, false); vi.advanceTimersByTime(299); expect(h.leases[0]?.observe).not.toHaveBeenCalled(); vi.advanceTimersByTime(1); @@ -572,14 +606,18 @@ it("releases the old channel and session on rerender and only observes the curre h.retarget("next-room"); expect(h.leases[0]?.dispose).toHaveBeenCalledOnce(); expect(oldValidity("visible", true)).toBe(false); - expect(h.reading).toHaveBeenLastCalledWith("next-room", undefined); + expect(h.reading).toHaveBeenLastCalledWith("next-room", undefined, false); const nextReading = vi.fn((_channelId: string) => h.reading()); h.retarget("next-room", { ...h.session, unread: { ...h.session.unread, reading: nextReading }, }); expect(h.leases[1]?.dispose).toHaveBeenCalledOnce(); - expect(nextReading).toHaveBeenCalledExactlyOnceWith("next-room", undefined); + expect(nextReading).toHaveBeenCalledExactlyOnceWith( + "next-room", + undefined, + false, + ); vi.advanceTimersByTime(299); for (const lease of h.leases) expect(lease.observe).not.toHaveBeenCalled(); vi.advanceTimersByTime(1); @@ -626,7 +664,7 @@ it("bottom dwell catches up through the newest row, including a tall clipped row ); // Its leases name the thread, which bounds what a DM read may cover. for (const call of h.reading.mock.calls) - expect(call).toEqual(["room", "thread"]); + expect(call).toEqual(["room", "thread", false]); }); it("a new latest message keeps observation and catches up after its row is measured", async () => { const h = setup({ latestMessageId: "bottom" }); @@ -672,6 +710,59 @@ it("a historical viewport or a bottom reached only at dwell end cannot catch up" ); }); +it("an arranged list's end row at the bottom catches up through the newest row", async () => { + const h = setup({ + latestMessageId: "newest", + endMessageId: "bottom", + rootId: "thread", + }); + // The newest row is ranked above, out of view. + h.setRows([row("newest", -300, -200), row("bottom", 400, 500)]); + h.mutation(); + vi.advanceTimersToNextFrame(); + await vi.advanceTimersByTimeAsync(300); + expect(h.dwelled()?.catchUp).toHaveBeenCalledExactlyOnceWith( + "newest", + "thread", + ); +}); +it("a partial list takes partial leases, which read only the rows shown", async () => { + const h = setup({ latestMessageId: "visible", partial: true }); + await vi.advanceTimersByTimeAsync(300); + expect(h.reading.mock.calls.length).toBeGreaterThan(0); + for (const call of h.reading.mock.calls) + expect(call).toEqual(["room", undefined, true]); + expect(h.dwelled()?.observe).toHaveBeenCalledWith(["visible"]); +}); +it("a list that turns partial mid-dwell drops its complete leases before they catch up", async () => { + const h = setup({ latestMessageId: "bottom", rootId: "thread" }); + h.setRows([row("bottom", 100, 200)]); + h.mutation(); + vi.advanceTimersToNextFrame(); + await vi.advanceTimersByTimeAsync(150); + const complete = h.leases.length; + expect(complete).toBeGreaterThan(0); + h.setPartial(true); + for (const lease of h.leases.slice(0, complete)) + expect(lease.dispose).toHaveBeenCalled(); + h.mutation(); + vi.advanceTimersToNextFrame(); + await vi.advanceTimersByTimeAsync(300); + // Only partial leases reach the dwell's end, and those never catch up. + h.leases.forEach((lease, index) => { + if (lease.catchUp.mock.calls.length) + expect(h.reading.mock.calls[index]?.[2]).toBe(true); + }); + for (const call of h.reading.mock.calls.slice(complete)) + expect(call).toEqual(["room", "thread", true]); + expect(h.dwelled()?.observe).toHaveBeenCalledWith(["bottom"]); +}); +it("using the list's reader bar earns dwell", () => { + const h = setup({ focus: "bar" }); + vi.advanceTimersByTime(300); + expect(h.dwelled()?.observe).toHaveBeenCalledWith(["visible"]); +}); + it("settled notification starts dwell without changed rows, focus or geometry", () => { const h = setup({ focus: "header", settled: false }); vi.advanceTimersByTime(300); diff --git a/src/features/messages/use-reading.ts b/src/features/messages/use-reading.ts index 69d4419d6b..3dc60fcfce 100644 --- a/src/features/messages/use-reading.ts +++ b/src/features/messages/use-reading.ts @@ -17,6 +17,16 @@ type Reading = { session: RelaySession; channelId: string; latestMessageId?: string | undefined; + /** The row at the list's end when it is not the latest, as under an + * arrangement: dwelling on it at the bottom catches up through + * `latestMessageId`. */ + endMessageId?: string | undefined; + /** True while the list leaves unread rows out of what it shows: it reads + * only the rows shown, and never catches up. */ + partial?: boolean | undefined; + /** The list's reader bar: using its controls is reading the list, as + * typing in its composer is. */ + controls?: RefObject | undefined; /** The thread this list shows: its bottom catches up that thread, and its * DM reads stop before unread messages it does not show. */ rootId?: string | undefined; @@ -43,6 +53,9 @@ export function useReading({ session, channelId, latestMessageId, + endMessageId, + partial = false, + controls, rootId, scroller, settled, @@ -53,6 +66,7 @@ export function useReading({ // Read at measurement time: a new latest message mutates the list, which // already remeasures in the next frame, so it must not restart observation. const latestId = useEffectEvent(() => latestMessageId); + const endId = useEffectEvent(() => endMessageId ?? latestMessageId); useEffect(() => { if (!enabled || !scroller.current) return; const element: HTMLElement = scroller.current; @@ -91,7 +105,8 @@ export function useReading({ ?.closest("[data-panel-workspace]") ?.closest("[data-reading-thread]") ?.contains(node) || - !!composer?.current?.contains(node)); + !!composer?.current?.contains(node) || + !!controls?.current?.contains(node)); // Everything but geometry, so an event can check it without a layout. const ready = () => !stopped && @@ -159,6 +174,7 @@ export function useReading({ }; function bottomId() { const latest = latestId(); + const end = endId(); if ( !latest || element.scrollHeight - element.clientHeight - element.scrollTop > 1 @@ -167,7 +183,7 @@ export function useReading({ const viewport = element.getBoundingClientRect(); const row = [ ...element.querySelectorAll("[data-message-id]"), - ].find((row) => row.dataset.messageId === latest); + ].find((row) => row.dataset.messageId === end); const bounds = row?.getBoundingClientRect(); return bounds && bounds.height > 0 && @@ -213,7 +229,7 @@ export function useReading({ } function acquire() { try { - return session.unread.reading(channelId, rootId); + return session.unread.reading(channelId, rootId, partial); } catch { return undefined; // Membership may disappear between commit and observation. } @@ -265,7 +281,7 @@ export function useReading({ // A view-only lease keeps that evidence until the next cancellation. observed.view([], () => false); try { - handle = session.unread.reading(channelId, rootId); + handle = session.unread.reading(channelId, rootId, partial); handle.view([...visible], viewing); } catch { handle = undefined; @@ -335,6 +351,8 @@ export function useReading({ settled, restoring, composer, + controls, + partial, enabled, ]); } diff --git a/src/features/relay/events.ts b/src/features/relay/events.ts index 591660759e..c589d36260 100644 --- a/src/features/relay/events.ts +++ b/src/features/relay/events.ts @@ -45,6 +45,13 @@ export type ReadFilter = Readonly<{ feed_types?: readonly string[]; thread_window?: boolean; depth_limit?: number; + /** NIP-CW windows, only for relays advertising `buzz-window-newer`: + * `newer` pages oldest first from `after`/`after_id`, and `root_aux: false` + * leaves the root's aux out of a thread page. */ + direction?: "older" | "newer"; + after?: number; + after_id?: string; + root_aux?: boolean; thread_cursor?: number; thread_cursor_id?: string; }>; diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts index dc49283ef1..36f2287f8c 100644 --- a/src/features/relay/native.ts +++ b/src/features/relay/native.ts @@ -460,6 +460,9 @@ export async function connectNativeTransport( const searchSort = Array.isArray(info.supported_extensions) && info.supported_extensions.includes("buzz-search-sort"); + const windowNewer = + Array.isArray(info.supported_extensions) && + info.supported_extensions.includes("buzz-window-newer"); const artifacts = info.artifacts as | { sync?: { version?: unknown } } | undefined; @@ -974,6 +977,7 @@ export async function connectNativeTransport( nativeAttachmentUpload(origin, file, signal, progress), ...(channelIdentity ? { channelIdentity: true as const } : {}), ...(searchSort ? { searchSort: true as const } : {}), + ...(windowNewer ? { windowNewer: true as const } : {}), ...(artifactSync ? { artifactSync: true as const } : {}), verifiedProfiles: verifiedProfileAuthority(info), async readVerifiedProfileAuthority(signal) { diff --git a/src/features/relay/reader.test.ts b/src/features/relay/reader.test.ts index 5df1f8e027..7772ca8d40 100644 --- a/src/features/relay/reader.test.ts +++ b/src/features/relay/reader.test.ts @@ -1,10 +1,14 @@ import { afterEach, expect, it, vi } from "vitest"; import { createRelayReader } from "./reader"; -import { flush, scriptedTransport } from "./testing"; +import { bounds, flush, keypair, message, scriptedTransport } from "./testing"; +import { windowFilter } from "./window"; const owners: ReturnType[] = []; -function setup(options: Parameters[1] = {}) { - const scripted = scriptedTransport("viewer", "relay"); +function setup( + options: Parameters[1] = {}, + relayAuthor = "relay", +) { + const scripted = scriptedTransport("viewer", relayAuthor); const owner = createRelayReader(scripted.transport, options); owners.push(owner); return { ...scripted, ...owner, read: owner.reader.read }; @@ -464,3 +468,23 @@ it("gives large reads their own deadline; a joining read keeps it", async () => await failures; expect(wire.signal?.aborted).toBe(true); }); +it("returns a channel page with its verified bound and rejects one whose bound is not the relay's", async () => { + const relay = keypair(), + impostor = keypair(); + const channelId = "11111111-1111-1111-1111-111111111111"; + const { read, next } = setup({}, relay.pubkey); + const row = message(keypair(), channelId, "hi", 10); + const bound = bounds(relay, channelId, "head", { + has_more: false, + next_cursor: null, + }); + const valid = read([windowFilter(channelId, null)]); + next().respond([row, bound]); + expect(await valid).toEqual([row, bound]); + const forged = read([windowFilter(channelId, null)]); + next().respond([ + row, + bounds(impostor, channelId, "head", { has_more: false, next_cursor: null }), + ]); + await expect(forged).rejects.toThrow(/invalid window bounds/); +}); diff --git a/src/features/relay/reader.ts b/src/features/relay/reader.ts index 785c63ffcb..bdd13a030c 100644 --- a/src/features/relay/reader.ts +++ b/src/features/relay/reader.ts @@ -1,6 +1,7 @@ import { isSidebarPreferencesBatch } from "./sidebar-preferences"; import { isWorkflowDefinitionBatch } from "../workflows/queries"; import { verifyThreadWindows } from "./thread-window"; +import { verifyChannelWindows } from "./window"; import { yieldToHost } from "./yield"; import { createRelayProfiler, type RelayProfiler } from "./profiling"; import type { ReadFilter, RelayEvent } from "./events"; @@ -220,6 +221,7 @@ export function createRelayReader( transport.viewer, transport.relayAuthor, ); + verifyChannelWindows(job.filters, events, transport.relayAuthor); finish(job, Object.freeze([...events])); }) .catch((error) => failed(job, error)); diff --git a/src/features/relay/session-hold.test.ts b/src/features/relay/session-hold.test.ts new file mode 100644 index 0000000000..0ec718cf24 --- /dev/null +++ b/src/features/relay/session-hold.test.ts @@ -0,0 +1,338 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { createRelaySession } from "./session"; +import { CHANNEL_LIMITS } from "./store"; +import { eventDto, type EventData, type RelayEvent } from "./events"; +import { PublishRejected } from "./outbox"; +import type { LiveCallbacks } from "./live"; +import { + flush, + keypair, + message, + roster, + scriptedTransport, + signed, + type Key, +} from "./testing"; + +const viewer = keypair(), + other = keypair(), + relay = keypair(); +const owners: ReturnType[] = []; +afterEach(() => { + for (const owner of owners.splice(0)) owner.dispose(); +}); +/** An event as a verified read returns it: the only kind with proof. */ +const proven = (event: RelayEvent) => eventDto(event); +const live = { phase: "live" as const, channelId: "c" }; +function setup(publish: (event: RelayEvent) => Promise) { + const wire = scriptedTransport(viewer.pubkey, relay.pubkey); + let callbacks!: LiveCallbacks; + const owner = createRelaySession( + { + ...wire.transport, + writer: { sign: async (template) => signed(viewer, template), publish }, + subscribe(next) { + callbacks = next; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { outboxStorage: { load: () => [], save() {} } }, + ); + owners.push(owner); + owner.session.channels.ensure("c"); + callbacks.receive([roster(relay, "c", [viewer.pubkey], 1)]); + return { owner, session: owner.session, receive: callbacks.receive }; +} +const pending = () => setup(() => new Promise(() => {})); +const reaction = (author: Key, target: EventData, time: number) => + signed(author, { + kind: 7, + content: "👍", + created_at: time, + tags: [ + ["h", "c"], + ["e", target.id], + ], + }); +const reply = ( + author: Key, + root: EventData, + time: number, + text = "r", + parent: EventData = root, +) => + message( + author, + "c", + text, + time, + parent === root + ? [["e", root.id, "", "reply"]] + : [ + ["e", root.id, "", "root"], + ["e", parent.id, "", "reply"], + ], + ); +const edit = (author: Key, target: EventData, text: string, time: number) => + signed(author, { + kind: 40003, + content: text, + created_at: time, + tags: [ + ["h", "c"], + ["e", target.id], + ], + }); +const deletion = (author: Key, targets: readonly string[], time = 20) => + signed(author, { + kind: 5, + content: "", + created_at: time, + tags: [["h", "c"], ...targets.map((id) => ["e", id])], + }); + +it("folds only proven events: a copied or raw event is dropped", () => { + const { session } = pending(); + const root = proven(message(other, "c", "root", 10)); + const copied = { ...proven(message(other, "c", "copied", 11)) }; + const raw = message(other, "c", "raw", 12); + expect( + session.foldRows("c", [root, copied, raw]).map((row) => row.id), + ).toEqual([root.id]); +}); + +it("drops an auxiliary event that names a target it cannot see", () => { + const { session } = pending(); + const root = proven(message(other, "c", "root", 10)); + const unseen = "ab".repeat(32); + const both = proven(deletion(other, [root.id, unseen])); + const only = proven(deletion(other, [root.id])); + expect(session.foldRows("c", [root, both])).toHaveLength(1); + expect(session.foldRows("c", [root, only])).toHaveLength(0); +}); + +it("adds this device's own pending reply and reaction with delivery state", () => { + const { session, receive } = pending(); + const root = proven(message(other, "c", "root", 10)); + receive([root]); + session.messages.reply("c", root.id, "mine"); + session.messages.react(root.id, "👍"); + const [top] = session.foldRows("c", [root]); + expect(top?.replyCount).toBe(1); + expect(top?.participants).toContain(viewer.pubkey); + expect(top?.reactions).toHaveLength(1); + const thread = session.foldRows("c", [root], root.id); + expect(thread).toHaveLength(2); + expect(thread[1]).toMatchObject({ content: "mine", delivery: "sending" }); +}); + +it("keeps a failed own reply, counted as pending, and leaves out a failed own reaction", async () => { + const { session, receive } = setup(async () => { + throw new PublishRejected("refused"); + }); + const root = proven(message(other, "c", "root", 10)); + receive([root]); + session.messages.reply("c", root.id, "mine"); + session.messages.react(root.id, "👍"); + await flush(); + await flush(); + expect(session.outbox?.snapshot().map((item) => item.delivery)).toEqual([ + "failed", + "failed", + ]); + const [top] = session.foldRows("c", [root]); + expect(top?.replyCount).toBe(1); + expect(top?.reactions).toEqual([]); + expect(session.foldRows("c", [root], root.id)[1]).toMatchObject({ + content: "mine", + delivery: "failed", + }); +}); + +it("scopes a thread fold to its root, and a channel fold to top-level rows", () => { + const { session } = pending(); + const one = proven(message(other, "c", "one", 10)); + const two = proven(message(other, "c", "two", 11)); + const first = proven(reply(other, one, 12)); + const second = proven(reply(other, two, 13)); + const all = [one, two, first, second]; + expect(session.foldRows("c", all).map((row) => row.id)).toEqual([ + one.id, + two.id, + ]); + expect(session.foldRows("c", all, one.id).map((row) => row.id)).toEqual([ + one.id, + first.id, + ]); +}); + +it("folds nothing for a denied channel or a closed session", () => { + const { owner, session, receive } = pending(); + receive([roster(relay, "elsewhere", [other.pubkey], 1)]); + const hidden = proven(message(other, "elsewhere", "hidden", 10)); + expect(session.foldRows("elsewhere", [hidden])).toEqual([]); + const mine = proven(message(other, "c", "mine", 10)); + expect(session.foldRows("c", [mine])).toHaveLength(1); + owner.dispose(); + expect(session.foldRows("c", [mine])).toEqual([]); +}); + +it("folds the same rows as a thread view for the same events", () => { + const { session, receive } = pending(); + const root = proven(message(other, "c", "root", 10)); + const first = proven(reply(other, root, 11, "first")); + const second = proven(reply(viewer, root, 12, "second", first)); + const doomed = proven(reply(other, root, 13, "doomed")); + const events = [ + root, + first, + second, + doomed, + proven(edit(other, first, "first, edited", 14)), + proven(reaction(viewer, second, 15)), + proven(deletion(other, [doomed.id], 16)), + ]; + receive(events); + const { root: shown, replies } = session.thread("c", root.id).snapshot(); + expect(replies).toHaveLength(2); + expect(session.foldRows("c", events, root.id)).toEqual([shown, ...replies]); +}); + +it("drops a live reaction on a snapshotRead-only row until it is held, then drops it again", () => { + const { session, receive } = pending(); + const row = proven(message(other, "c", "row", 10)); + const heard: RelayEvent[] = []; + session.subscribeLive((batch) => heard.push(...batch.events)); + receive([reaction(other, row, 20)], live); + expect(heard).toHaveLength(0); + const hold = session.retain(); + hold.set([row]); + const held = reaction(other, row, 21); + receive([held], live); + expect(heard.map((event) => event.id)).toEqual([held.id]); + hold.dispose(); + receive([reaction(other, row, 22)], live); + expect(heard).toHaveLength(1); +}); + +it("holds only proven events of channels the viewer can read", () => { + const { session, receive } = pending(); + receive([roster(relay, "secret", [other.pubkey], 1)]); + const secret = proven(message(other, "secret", "hidden", 10)); + const raw = message(other, "c", "raw", 11); + session.retain().set([secret, raw]); + // A held event would let react find its target. + expect(() => session.messages.react(secret.id, "👍")).toThrow( + /Load the message/, + ); + expect(() => session.messages.react(raw.id, "👍")).toThrow( + /Load the message/, + ); +}); + +it("lets edit and react find a held-only row until access changes", async () => { + const { session, receive } = pending(); + await session.outbox?.ready(); + const mine = proven(message(viewer, "c", "mine", 10)); + expect(() => session.messages.react(mine.id, "👍")).toThrow( + /Load the message/, + ); + session.retain().set([mine]); + expect(session.messages.react(mine.id, "👍")).toBeTruthy(); + expect(session.messages.edit(mine.id, "edited", mine.id)).toBeTruthy(); + receive([roster(relay, "c", [], 2)]); + expect(() => session.messages.react(mine.id, "👍")).toThrow( + /Load the message/, + ); +}); + +it("empties a hold on a cache clear", async () => { + const { owner, session } = pending(); + const mine = proven(message(viewer, "c", "mine", 10)); + session.retain().set([mine]); + expect(session.messages.react(mine.id, "👍")).toBeTruthy(); + await owner.clearCache(); + expect(() => session.messages.react(mine.id, "👍")).toThrow( + /Load the message/, + ); +}); + +it("holds up to a byte bound, keeps the previous set past it, and shares the view slots", () => { + const { owner, session, receive } = pending(); + const row = proven(message(other, "c", "row", 10)); + const hold = session.retain(); + hold.set([row]); + // The hold's bound is a channel window's: 8 MiB. + const big = Array.from({ length: 5 }, (_, index) => + proven( + message( + other, + "c", + "x".repeat(Math.ceil(CHANNEL_LIMITS.bytes / 4)), + 20 + index, + ), + ), + ); + expect(() => hold.set(big)).toThrow(/byte bound/); + const heard: RelayEvent[] = []; + session.subscribeLive((batch) => heard.push(...batch.events)); + receive([reaction(other, row, 30)], live); + expect(heard).toHaveLength(1); + const rest = Array.from({ length: 63 }, () => session.retain()); + expect(() => session.retain()).toThrow(/capacity/); + rest[0]?.dispose(); + expect(() => session.retain()).not.toThrow(); + owner.dispose(); + expect(() => session.retain()).toThrow(/capacity/); +}); + +it("passes snapshotRead priority to the reader, so a background scan queues behind foreground reads", async () => { + const started: { kind: number; priority?: string; release(): void }[] = []; + const owner = createRelaySession({ + viewer: viewer.pubkey, + relayAuthor: relay.pubkey, + media: () => undefined, + query: (filters, _signal, _id, priority) => { + const kind = filters[0]?.kinds?.[0] ?? 0; + if (kind < 30001) return Promise.resolve([]); + return new Promise((resolve) => + started.push({ + kind, + ...(priority ? { priority } : {}), + release: () => resolve([]), + }), + ); + }, + }); + owners.push(owner); + const read = owner.session.snapshotRead; + if (!read) throw new Error("snapshotRead unavailable"); + const filter = (kind: number) => [{ kinds: [kind], limit: 10 }]; + const scan = read(filter(30001), { priority: "background" }); + await vi.waitFor(() => expect(started).toHaveLength(1)); + const next = read(filter(30002), { priority: "background" }); + const foreground = read(filter(30003), {}); + await vi.waitFor(() => expect(started).toHaveLength(2)); + expect(started.map(({ kind, priority }) => [kind, priority])).toEqual([ + [30001, "background"], + [30003, "foreground"], + ]); + started[0]?.release(); + await scan; + await vi.waitFor(() => expect(started).toHaveLength(3)); + expect(started[2]?.kind).toBe(30002); + for (const item of started) item.release(); + await Promise.all([next, foreground]); +}); + +it("reports the relay's buzz-window-newer capability", () => { + const wire = scriptedTransport(viewer.pubkey, relay.pubkey); + for (const windowNewer of [true, undefined]) { + const owner = createRelaySession({ + ...wire.transport, + ...(windowNewer ? { windowNewer } : {}), + }); + owners.push(owner); + expect(owner.session.windowNewer).toBe(windowNewer === true); + } +}); diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index e8878448a2..3ba8d7a854 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -85,6 +85,7 @@ import { objectBody } from "./body"; import { agentAudience } from "./audience"; import type { ChannelList, + ChannelMessage, ChannelReadOptions, ChannelSummary, } from "./contracts"; @@ -111,6 +112,7 @@ import { attemptEnded } from "./withdraw"; import type { ReadTransport } from "./transport"; import type { LiveGlobal, LiveSnapshot, LiveSubscription } from "./live"; import { + hasEventProof, hasTag, type ReadFilter, type RelayEvent, @@ -129,9 +131,10 @@ import { relayPartition, transportPartition } from "./partition"; import { browserThreadFollows } from "./thread-follows"; import { createMessages } from "./messages"; import { retryRead } from "./read-retry"; -import { messageAuthor } from "./fold"; +import { foldMessages, messageAuthor } from "./fold"; +import { threadReference } from "./thread-reference"; import { createThreadView, resumeAfter, type ThreadResume } from "./threads"; -import { ByteLru } from "./budget"; +import { ByteLru, listByteSize } from "./budget"; import { createRelayProfiler } from "./profiling"; import { liveRecoveryStatus } from "./live-recovery"; import { @@ -172,6 +175,10 @@ export const ROSTER_BACKSTOP_INTERVAL = 15 * 60_000; * no signal: a channel the relay pruned from a batch, or a dropped fan-out. */ export const UNREAD_BACKSTOP_INTERVAL = 15 * 60_000; +/** The most one `retain` handle holds, in serialized event bytes: the bound + * of the shared cache and of a channel's retained window. */ +const RETAIN_MAX_BYTES = 8 * 1024 * 1024; + /** A read of named authors' profiles only. Profiles do not depend on channels, * so no channel access change, including a denied channel list, can stale it. */ function isProfileFilter(filter: ReadFilter) { @@ -318,6 +325,9 @@ export function createRelaySession( const pendingConfirmation = new Set(); const refreshers = new Set<() => Promise>(); const views = new Map<() => void, (clear?: boolean) => void>(); + /** Each `retain` handle's events: evidence for visibility and lookups, never + * counted, cached or shown. A handle is one view slot. */ + const holds = new Set>(); const threads = new Set>(); /** Recently closed threads, so reopening one shows it at once. Memory only; * dropped with any access change. */ @@ -416,8 +426,14 @@ export function createRelaySession( canAccess(thread.channelId) ? thread.events() : [], ); } + function heldEvent(id: string) { + for (const held of holds) { + const event = held.get(id); + if (event) return event; + } + } function retainedEvent(id: string) { - return retainedThreadEvent(id) ?? retainedChannelEvent(id); + return retainedThreadEvent(id) ?? retainedChannelEvent(id) ?? heldEvent(id); } const canReadRemote = (id: string) => !options.cachedOnly && canAccess(id) && !channels.queries.get?.(id)?.cached; @@ -1315,6 +1331,7 @@ export function createRelaySession( profiles: profiles.queries, reads, channels: channels.queries, + evidence: heldEvent, // Repair owns evidence only, not timeline/history ingestion. The shared // scheduler and verified transport stay shared; unread fences access epochs. reader: requests.reader, @@ -2489,13 +2506,15 @@ export function createRelaySession( relayAuthor: transport?.relayAuthor, /** NIP-AP config artifacts: the relay's own verified answer, never merged * with live or local outgoing events or fed to any projection, and a - * kind-45010 writer when the host has one. Each read starts fresh. */ + * kind-45010 writer when the host has one. Each read starts fresh. With + * `priority: "background"` a long scan queues behind foreground reads. */ snapshotRead: transport - ? (((filters, { signal }) => - relayRead( - filters, - signal ? { signal, fresh: true } : { fresh: true }, - )) satisfies SnapshotRead) + ? (((filters, { signal, priority }) => + relayRead(filters, { + fresh: true, + ...(signal ? { signal } : {}), + ...(priority ? { priority } : {}), + })) satisfies SnapshotRead) : undefined, configArtifactWriter: transport?.configArtifacts, workflowAuthority: transport?.archiveAuthority, @@ -3084,6 +3103,9 @@ export function createRelaySession( }, /** Whether read() search filters may ask for `search_sort: "newest"`. */ searchSort: transport?.searchSort === true, + /** Whether thread and channel windows may ask for `direction: "newer"` + * and thread pages for `root_aux: false` (`buzz-window-newer`). */ + windowNewer: transport?.windowNewer === true, /** NIP-AR sync: an exact, kept-current set of current artifacts for a * filter that names its channels with `#h`. Status `unsupported` means * this relay has no sync; use read() with `artifact: "current"` instead. @@ -3174,6 +3196,117 @@ export function createRelaySession( }; }, }, + /** The rows Buzz's readers fold from these events: proven events plus this + * device's own intent in the conversation (with delivery state), visible ones + * only, with edits, reactions and deletions applied, in the readers' order. + * With `rootId`, the thread fold: the root and its replies. Stateless: it + * reads no relay and keeps no cache or view. Denied or closed: `[]`. */ + foldRows( + channelId: string, + events: readonly EventData[], + rootId?: string, + ): readonly ChannelMessage[] { + if (closed || !canAccess(channelId)) return []; + // Failed edits, reactions and deletions never changed the content; a + // failed message stays, for same-event retry. + const own = rawLocal().filter( + ({ event, delivery }) => + event.kind !== PRODUCT_FEEDBACK_KIND && + event.tags.some(([name, id]) => name === "h" && id === channelId) && + (delivery !== "failed" || [9, 40002, 40008].includes(event.kind)), + ); + const inputs = new Map(); + for (const event of events) + if (hasEventProof(event)) inputs.set(event.id, event); + for (const { event } of own) inputs.set(event.id, event); + const all = [...inputs.values()]; + const delivered = new Map(own.map((item) => [item.event.id, item])); + return foldMessages( + channelId, + transport?.relayAuthor ?? "", + all.filter(visibility(all)), + { + includeReplies: rootId !== undefined, + signingAuthority: transport?.archiveAuthority, + agentOwner: profiles.queries.owner, + // As a channel view counts them: own replies the relay has not yet. + pendingReplies: + rootId === undefined + ? new Set( + own + .filter( + ({ event, delivery }) => + (delivery === "sending" || delivery === "failed") && + threadReference(event)?.rootId, + ) + .map(({ event }) => event.id), + ) + : undefined, + }, + ) + .filter( + (row) => + rootId === undefined || + row.id === rootId || + row.threadRootId === rootId, + ) + .map((row) => { + const item = delivered.get(row.id); + return item + ? Object.freeze({ + ...row, + delivery: item.delivery, + deliveryError: item.error, + }) + : row; + }); + }, + /** One holder's evidence hold: `set` replaces the events held. A held event + * lets its live edits, reactions and deletions pass visibility (so they reach + * `observe` views and `subscribeLive`), and edit, react and read marking find + * it, though nothing else retains it (a `snapshotRead` row, say). Only proven, + * visible events are held. It grants no access: every reference is still + * checked, on `set` and on each access change. It never takes part in + * `accept`, so it changes no cache, unread count or other view. + * + * One handle is one view slot of the 64 `observe` and thread views share; + * this throws as `observe` does when none is free. `set` throws past + * `RETAIN_MAX_BYTES` and keeps the previous events. A cache clear empties the + * hold (the handle stays valid); `dispose`, and closing the session, end it. */ + retain() { + if (closed || views.size >= 64) + throw new Error("Relay view capacity unavailable"); + const held = new Map(); + holds.add(held); + const dispose = () => { + holds.delete(held); + held.clear(); + views.delete(dispose); + }; + views.set(dispose, (clear = false) => { + if (clear) held.clear(); + else { + const visible = visibility([...held.values()]); + for (const event of [...held.values()]) + if (!visible(event)) held.delete(event.id); + } + }); + return Object.freeze({ + set(events: readonly EventData[]) { + if (!holds.has(held)) return; + const proven = events.filter(hasEventProof) as RelayEvent[]; + const visible = visibility(proven); + const next = new Map( + proven.filter(visible).map((event) => [event.id, event]), + ); + if (listByteSize([...next.values()]) > RETAIN_MAX_BYTES) + throw new RangeError("Relay hold byte bound exceeded"); + held.clear(); + for (const [id, event] of next) held.set(id, event); + }, + dispose, + }); + }, /** An owned retained event view, not a replacement query snapshot. Limits bound * requests, not retained results. Ranked search/feed filters require read(). * Subscribe, refresh and dispose with the plugin's scope. */ diff --git a/src/features/relay/store.ts b/src/features/relay/store.ts index fe78f59fc7..afa3be020c 100644 --- a/src/features/relay/store.ts +++ b/src/features/relay/store.ts @@ -219,6 +219,13 @@ const publicRank = (name: string, needle: string, exact?: boolean) => : matchRank(name, needle); /** How long a completed read answers a repeated trigger without asking again. */ export const FRESH_FOR = 60_000; +/** The most a channel's retained history holds. The store counts rows and bytes, + * not events. */ +export const CHANNEL_LIMITS = Object.freeze({ + rows: 2400, + events: Number.POSITIVE_INFINITY, + bytes: 8 * 1024 * 1024, +}); /** Pages a reconnect catch-up reads back from the head before it gives up on * reaching the rows the reader kept across the disconnect. */ const CATCH_UP_PAGES = 5; @@ -308,8 +315,8 @@ export function createChannelStore( persistence, maxHeadBytes = 4 * 1024 * 1024, maxHeads = 64, - maxHistoryRows = 2400, - maxHistoryBytes = 8 * 1024 * 1024, + maxHistoryRows = CHANNEL_LIMITS.rows, + maxHistoryBytes = CHANNEL_LIMITS.bytes, maxPublicDirectory = PUBLIC_CHANNEL_DIRECTORY, publicDirectoryPage = PUBLIC_CHANNEL_PAGE, now = Date.now, @@ -4121,8 +4128,10 @@ export function createChannelStore( void fetchProfiles(state.snapshot.rows.slice(-12)); } }); - /** Verified traffic shares the same fold as reads and local intent. Window bounds remain read-owned. */ - function accept(events: readonly RelayEvent[]) { + /** Verified traffic shares the same fold as reads and local intent. Window bounds remain read-owned. + * A window's own catch-up pages pass `ownPages`: they move its floor + * themselves, so rows below the old floor are theirs to add. */ + function accept(events: readonly RelayEvent[], ownPages = false) { if (disposed || !transport) return; const generation = epoch; const changedChannels = new Set( @@ -4161,6 +4170,34 @@ export function createChannelStore( if (disposed || generation !== epoch) return; if (!authorized(state.channelId)) continue; const ids = new Set(state.events.map((event) => event.id)); + // Rows below the floor wait for their page while history remains (the + // display rule in `setWindow`), and so do edits, reactions and + // deletions of only those rows: else the history budget would trim + // the window for a scan it never showed. + const below = new Set(); + const floor = state.floor; + if (!ownPages && state.snapshot.hasMore && floor !== undefined) { + for (const event of events) + if ( + channelRowKind(event.kind) && + event.created_at < floor && + !ids.has(event.id) && + event.tags.some( + ([name, id]) => name === "h" && id === state.channelId, + ) + ) + below.add(event.id); + for (let hop = 0; hop < 2 && below.size; hop++) + for (const event of events) { + if (channelRowKind(event.kind) || below.has(event.id)) continue; + const targets = event.tags.filter(([name]) => name === "e"); + if ( + targets.length && + targets.every(([, id]) => below.has(id ?? "")) + ) + below.add(event.id); + } + } const incomingIds = new Set(ids); const incoming: RelayEvent[] = []; let changed = true; @@ -4169,6 +4206,7 @@ export function createChannelStore( for (const event of events) { if ( incomingIds.has(event.id) || + below.has(event.id) || !( channelRowKind(event.kind) || [40003, 5, 9005, 7, 39005].includes(event.kind) @@ -4601,7 +4639,7 @@ export function createChannelStore( throw new DOMException("Stale live catch-up", "AbortError"); retained.restored = false; retained.readAt = head.readAt; - accept(head.events); + accept(head.events, true); page = head; const reached = (last: Page) => !last.hasMore || @@ -4622,7 +4660,7 @@ export function createChannelStore( ).page; if (!valid()) throw new DOMException("Stale live catch-up", "AbortError"); - accept(page.events); + accept(page.events, true); contiguous = reached(page); } if (!valid()) diff --git a/src/features/relay/testing.ts b/src/features/relay/testing.ts index 54aae7e18a..d07b9dc32c 100644 --- a/src/features/relay/testing.ts +++ b/src/features/relay/testing.ts @@ -91,6 +91,7 @@ export function bounds( body: { has_more: boolean; next_cursor: { created_at: number; id: string } | null; + direction?: string; }, ): RelayEvent { return signed(relay, { diff --git a/src/features/relay/thread-window.test.ts b/src/features/relay/thread-window.test.ts index 86f55a537d..09ebfec19a 100644 --- a/src/features/relay/thread-window.test.ts +++ b/src/features/relay/thread-window.test.ts @@ -1,11 +1,16 @@ import { createHash } from "node:crypto"; -import { assert, afterEach, expect, it, vi } from "vitest"; +import { assert, afterEach, describe, expect, it, vi } from "vitest"; import { createRelaySession } from "./session"; import { connectBrokerTransport } from "./transport"; import type { ReadFilter, RelayEvent } from "./events"; import type { LiveCallbacks } from "./live"; import { keypair, message, roster, signed } from "./testing"; -import { threadBinding, threadAuthority } from "./thread-window"; +import { + type ThreadCursor, + threadAuthority, + threadBinding, + verifyThreadWindows, +} from "./thread-window"; import { createThreadView, type ThreadResume } from "./threads"; const channel = "00000000-0000-0000-0000-000000000000"; @@ -123,6 +128,192 @@ it("matches the Rust binding vector and normalized authority, including IPv6 and ); expect(threadAuthority("http://[::1]:3000")).toBe("[::1]:3000"); }); +it("keeps the older binding when direction and root aux are explicit defaults", async () => { + const filter: ReadFilter = { + thread_window: true, + "#h": [channel], + "#e": ["ab".repeat(32)], + kinds: [9], + limit: 50, + }; + const binding = (patch: Partial) => + threadBinding( + { ...filter, ...patch }, + "https://relay.example", + "ab".repeat(32), + ); + // buzz-core thread_window::tests::binding_normalizes_defaults_and_binds_every_argument + const expected = + "tw:1:5252322dfd797ddb1d5f1150acd4cf914b9fc09e39bcf3048d25aed514b3546d"; + expect(await binding({ direction: "older", root_aux: true })).toBe(expected); + expect(await binding({ root_aux: false })).not.toBe(expected); + expect(await binding({ direction: "newer" })).not.toBe(expected); +}); +it("binds a forward page that leaves root aux out as the relay's vector", async () => { + const filter: ReadFilter = { + thread_window: true, + "#h": [channel], + "#e": ["cd".repeat(32)], + kinds: [9], + limit: 50, + direction: "newer", + after: 5, + after_id: "ef".repeat(32), + root_aux: false, + }; + // buzz-core thread_window::tests::binding_encodes_direction_cursor_and_root_aux_as_specified + // (relay 90c63a56b). The digest is sha256 of the vector's canonical array, + // computed outside this code base. + const canonical = `["tw",1,"newer","relay.example","${"ab".repeat(32)}","${channel}","${"cd".repeat(32)}",50,100,[9],[5,"${"ef".repeat(32)}"],false,"root_aux:false"]`; + expect(createHash("sha256").update(canonical).digest("hex")).toBe( + "a417629c808147bf1592cab56498fd1137bda02e04450ba5aa6fc15d39d63c73", + ); + expect( + await threadBinding(filter, "https://relay.example", "ab".repeat(32)), + ).toBe( + "tw:1:a417629c808147bf1592cab56498fd1137bda02e04450ba5aa6fc15d39d63c73", + ); +}); +describe("forward thread pages", () => { + const at = { created_at: 10, id: "b".repeat(64) }; + const forward: ReadFilter = { + thread_window: true, + "#h": [channel], + "#e": [root.id], + kinds: [9], + limit: 50, + direction: "newer", + after: at.created_at, + after_id: at.id, + root_aux: false, + }; + // Independent encoder for a `newer` bound, as NIP-CW specifies it. + const newerBound = (filter: ReadFilter, content: Record) => { + const digest = createHash("sha256") + .update( + JSON.stringify([ + "tw", + 1, + "newer", + "relay.example:8443", + viewer.pubkey, + channel, + root.id, + filter.limit, + 100, + [9], + filter.after === undefined ? null : [filter.after, filter.after_id], + false, + ...(filter.root_aux === false ? ["root_aux:false"] : []), + ]), + ) + .digest("hex"); + return signed(relay, { + kind: 39007, + tags: [ + ["d", `tw:1:${digest}`], + ["h", channel], + ["e", root.id], + ], + content: JSON.stringify({ version: 1, ...content }), + }); + }; + const verify = (filter: ReadFilter, bound: RelayEvent) => + verifyThreadWindows([filter], [bound], origin, viewer.pubkey, relay.pubkey); + it("accept a newer bound that moves forward in relay order", async () => { + for (const next of [ + { created_at: 11, id: "f".repeat(64) }, + { created_at: 10, id: "a".repeat(64) }, + null, + ]) + await expect( + verify( + forward, + newerBound(forward, { + direction: "newer", + has_more: next !== null, + next_cursor: next, + }), + ), + ).resolves.toBeUndefined(); + const { after: _a, after_id: _b, ...head } = forward; + await expect( + verify( + head, + newerBound(head, { + direction: "newer", + has_more: true, + next_cursor: at, + }), + ), + ).resolves.toBeUndefined(); + }); + it("reject a direction mismatch either way", async () => { + await expect( + verify( + forward, + newerBound(forward, { + direction: "older", + has_more: false, + next_cursor: null, + }), + ), + ).rejects.toThrow(/bounds are invalid/); + const older: ReadFilter = { + thread_window: true, + "#h": [channel], + "#e": [root.id], + kinds: [9], + limit: 50, + }; + await expect( + verify(older, bounds(older, null, { direction: "newer" })), + ).rejects.toThrow(/bounds are invalid/); + // An older bound for a newer request misses its binding. + await expect(verify(forward, bounds(older))).rejects.toThrow( + /bounds are invalid/, + ); + }); + it.each([ + { created_at: 9, id: "b".repeat(64) }, + { created_at: 10, id: "b".repeat(64) }, + { created_at: 10, id: "c".repeat(64) }, + ])("reject a newer cursor that does not advance (%o)", async (next) => { + await expect( + verify( + forward, + newerBound(forward, { + direction: "newer", + has_more: true, + next_cursor: next, + }), + ), + ).rejects.toThrow(/bounds are invalid/); + }); + it.each([ + { next: { created_at: 11, id: "b".repeat(64) }, advances: false }, + { next: { created_at: 10, id: "b".repeat(64) }, advances: false }, + { next: { created_at: 10, id: "a".repeat(64) }, advances: false }, + { next: { created_at: 10, id: "c".repeat(64) }, advances: true }, + { next: { created_at: 9, id: "a".repeat(64) }, advances: true }, + ])( + "keep the older advance check (next $next.created_at)", + async ({ next, advances }) => { + const older: ReadFilter = { + thread_window: true, + "#h": [channel], + "#e": [root.id], + kinds: [9], + limit: 50, + until: at.created_at, + before_id: at.id, + }; + const result = verify(older, bounds(older, next)); + if (advances) await expect(result).resolves.toBeUndefined(); + else await expect(result).rejects.toThrow(/bounds are invalid/); + }, + ); +}); it("pages 303 tied replies newest-first, deduplicates live rows and repairs retained overlays", async () => { const rows = Array.from({ length: 303 }, (_, n) => reply(n)); const newest = [...rows].sort( @@ -1055,3 +1246,219 @@ it("accepts and echoes chrono's inclusive maximum cursor", async () => { canLoadMore: false, }); }); + +// A view's window is its committed pages, in the relay's full order. Rows +// past its cursor belong to the next older page, whatever read carried them. +const replyAt = (content: string, created_at: number) => + message(author, channel, content, created_at, [["e", root.id, "", "reply"]]); +const newestPage = Array.from({ length: 10 }, (_, n) => + replyAt(`head ${n}`, 1000 + n), +); +// Signed once: 2,000 replies older than the newest page's cursor. +const olderScan = Array.from({ length: 2000 }, (_, n) => + replyAt(`older ${n}`, 2 + Math.floor(n / 4)), +); +const pageCursor = cursorOf(newestPage[0] as RelayEvent); +const scanOrder = [...olderScan].sort( + (a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id), +); +const headOnly = (filter: ReadFilter) => + filter.ids + ? [root] + : filter.thread_window + ? [...newestPage, bounds(filter, pageCursor)] + : scanOrder + .filter( + (e) => + filter.until === undefined || + e.created_at < filter.until || + (e.created_at === filter.until && + e.id > (filter.before_id ?? "")), + ) + .slice(0, filter.limit); + +it.each(["live traffic", "a session readPage scan"])( + "keeps a view ready with the same rows when %s carries 2,000 replies older than its cursor", + async (source) => { + const h = await setup(headOnly); + await h.view.refresh(); + const before = h.view.snapshot().replies; + expect(before).toHaveLength(10); + if (source === "live traffic") h.traffic.receive(olderScan); + // A plugin pages the scan; the relay serves at most 500 per read. + else + for (let cursor: ThreadCursor | undefined, n = 0; n < 4; n++) { + const { events } = await h.session.readPage([ + { + kinds: [9], + "#h": [channel], + "#e": [root.id], + limit: 500, + ...(cursor + ? { until: cursor.created_at, before_id: cursor.id } + : {}), + }, + ]); + cursor = events.at(-1); + } + expect(h.view.snapshot()).toMatchObject({ + status: "ready", + error: undefined, + limited: false, + }); + expect(h.view.snapshot().replies).toBe(before); + const live = replyAt("live", 2000); + const held = newestPage[3] as RelayEvent; + h.traffic.receive([live]); + h.traffic.receive([ + signed(author, { + kind: 5, + content: "", + created_at: 2001, + tags: [["e", held.id]], + }), + ]); + const ids = h.view.snapshot().replies.map((row) => row.id); + expect(ids).toContain(live.id); + expect(ids).not.toContain(held.id); + expect(ids).toHaveLength(10); + }, +); + +it("admits a reply at the cursor's second only when its id is at or below the cursor's, and any legacy diff", async () => { + const tied = Array.from({ length: 3 }, (_, n) => + replyAt(`tied ${n}`, 50), + ).sort((a, b) => a.id.localeCompare(b.id)); + const [low, mid, high] = tied as [RelayEvent, RelayEvent, RelayEvent]; + const newer = replyAt("newer", 60); + // Older pages run `created_at DESC, id ASC`: the cursor ends mid-second. + const h = await setup((filter) => + filter.ids ? [root] : [newer, mid, bounds(filter, cursorOf(mid))], + ); + await h.view.refresh(); + // Strict pages never return a legacy diff, so one past the cursor stays. + const diff = signed(author, { + kind: 40008, + content: "diff", + created_at: 40, + tags: [ + ["h", channel], + ["e", root.id, "", "reply"], + ], + }); + h.traffic.receive([low, high, diff]); + expect(h.view.snapshot().replies.map((row) => row.id)).toEqual( + [diff, low, mid, newer].map((row) => row.id), + ); +}); + +it("skips an oversized replay into a view with no page yet, then commits its first page", async () => { + const thread = createThreadView({ + channelId: channel, + messageId: root.id, + relayAuthor: relay.pubkey, + reader: { + read: async ([filter]) => (filter ? headOnly(filter) : []), + }, + seed: root, + local: undefined, + canAccess: () => true, + visible: (events) => events, + notify: (listener) => listener(), + }); + try { + thread.receive([...olderScan, ...newestPage]); + expect(thread.view.snapshot()).toMatchObject({ error: undefined }); + await thread.view.refresh(); + expect(thread.view.snapshot()).toMatchObject({ + status: "ready", + error: undefined, + canLoadMore: true, + }); + expect(thread.view.snapshot().replies.map((row) => row.id)).toEqual( + newestPage.map((row) => row.id), + ); + } finally { + thread.view.dispose(); + } +}); + +it("admits a live reply inside the pages a refresh has read past the committed cursor", async () => { + const one = at(1), + two = at(2), + three = at(3), + four = at(4); + // Its timestamp places it between two pages the refresh has already read. + const late = message(author, channel, "late", 25, [ + ["e", root.id, "", "reply"], + ]); + let reconnected = false; + let release!: () => void; + const paused = new Promise((resolve) => (release = resolve)); + let reading!: () => void; + const reached = new Promise((resolve) => (reading = resolve)); + const h = await setup(async (filter) => { + if (filter.ids) return [root]; + if (!reconnected) return [three, bounds(filter, cursorOf(three))]; + if (filter.until === undefined) + return [four, bounds(filter, cursorOf(four))]; + if (filter.until === four.created_at) + return [two, bounds(filter, cursorOf(two))]; + reading(); + await paused; + return [one, bounds(filter)]; + }); + await h.view.refresh(); + reconnected = true; + h.traffic.established(channel); + await reached; + h.traffic.receive([late]); + release(); + await vi.waitFor(() => { + expect(h.view.snapshot()).toMatchObject({ status: "ready" }); + expect(h.view.snapshot().replies.map((row) => row.id)).toContain(one.id); + }); + expect(h.view.snapshot().replies.map((row) => row.id)).toContain(late.id); +}); +it("keeps a live deletion of a row a refresh reads past the committed cursor", async () => { + // The held reply is gone after the drop, so the refresh pages past the + // window it had, to the end of the thread. + const one = at(1), + two = at(2), + three = at(3), + four = at(4); + let reconnected = false; + let release!: () => void; + const paused = new Promise((resolve) => (release = resolve)); + let reading!: () => void; + const reached = new Promise((resolve) => (reading = resolve)); + const h = await setup(async (filter) => { + if (filter.ids) return [root]; + if (!reconnected) return [three, bounds(filter, cursorOf(three))]; + if (filter.until === undefined) + return [four, bounds(filter, cursorOf(four))]; + if (filter.until === four.created_at) + return [two, bounds(filter, cursorOf(two))]; + reading(); + await paused; + return [one, bounds(filter)]; + }); + await h.view.refresh(); + reconnected = true; + h.traffic.established(channel); + await reached; + h.traffic.receive([ + signed(author, { + kind: 5, + content: "", + created_at: 500, + tags: [["e", two.id]], + }), + ]); + release(); + await vi.waitFor(() => { + expect(h.view.snapshot()).toMatchObject({ status: "ready" }); + expect(h.view.snapshot().replies.map((row) => row.id)).toContain(one.id); + }); + expect(h.view.snapshot().replies.map((row) => row.id)).not.toContain(two.id); +}); diff --git a/src/features/relay/thread-window.ts b/src/features/relay/thread-window.ts index 281b7a9dde..ccb272900f 100644 --- a/src/features/relay/thread-window.ts +++ b/src/features/relay/thread-window.ts @@ -28,16 +28,28 @@ export function threadAuthority(origin: string) { .replace(/\.$/, ""); } -/** NIP-CW thread-mode v1, identical to buzz-core::thread_window::Request::binding. */ +/** The request cursor in the filter's own direction. */ +const requestCursor = (filter: ReadFilter) => + filter.direction === "newer" + ? filter.after === undefined + ? undefined + : { created_at: filter.after, id: filter.after_id ?? "" } + : filter.until === undefined + ? undefined + : { created_at: filter.until, id: filter.before_id ?? "" }; + +/** NIP-CW thread-mode v1, identical to buzz-core::thread_window::Request::binding. + * Default options keep the original array, so older bindings are unchanged. */ export async function threadBinding( filter: ReadFilter, origin: string, viewer: string, ) { + const cursor = requestCursor(filter); const canonical = JSON.stringify([ "tw", 1, - "older", + filter.direction ?? "older", threadAuthority(origin), viewer, filter["#h"]?.[0], @@ -45,8 +57,9 @@ export async function threadBinding( filter.limit, filter.depth_limit ?? 100, [...new Set(filter.kinds)].sort((a, b) => a - b), - filter.until === undefined ? null : [filter.until, filter.before_id], + cursor ? [cursor.created_at, cursor.id] : null, filter.include_aux ?? false, + ...(filter.root_aux === false ? ["root_aux:false"] : []), ]); const digest = await crypto.subtle.digest( "SHA-256", @@ -60,14 +73,25 @@ export async function threadBinding( ); } -export function threadBounds(event: RelayEvent): { +/** Relay window order, oldest first: `created_at ASC, id DESC`. Older pages + * run its exact reverse. */ +export function relayOrder(a: ThreadCursor, b: ThreadCursor) { + return ( + a.created_at - b.created_at || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0) + ); +} + +export function threadBounds( + event: RelayEvent, + direction: "older" | "newer" = "older", +): { hasMore: boolean; cursor: ThreadCursor | null; } { const body = objectBody(event.content); if ( body?.version !== 1 || - body.direction !== "older" || + body.direction !== direction || typeof body.has_more !== "boolean" ) throw invalid(); @@ -145,14 +169,12 @@ export async function verifyThreadWindows( ) ) throw invalid(); - const { cursor } = threadBounds(bound); - if ( - cursor && - filter.until !== undefined && - (cursor.created_at > filter.until || - (cursor.created_at === filter.until && - cursor.id <= (filter.before_id ?? ""))) - ) + const newer = filter.direction === "newer"; + const { cursor } = threadBounds(bound, newer ? "newer" : "older"); + const from = requestCursor(filter); + // The next cursor advances in the request's order: older is + // `created_at DESC, id ASC`, newer its exact reverse. + if (cursor && from && relayOrder(cursor, from) * (newer ? 1 : -1) <= 0) throw invalid(); } } diff --git a/src/features/relay/threads.test.ts b/src/features/relay/threads.test.ts index 5b4ef6d737..ca91ee26df 100644 --- a/src/features/relay/threads.test.ts +++ b/src/features/relay/threads.test.ts @@ -1076,8 +1076,16 @@ it.each(["live", "read"])( expect(thread.events()).toContain(tombstone); expect(thread.events()).toHaveLength(1003); - // The cap still applies to messages, even after summary compaction. + // The cap still applies to messages, even after summary compaction, + // once a page is committed. With none, there is no window to overflow: + // the batch waits for the first page. thread.receive(overflow); + if (source === "live") { + expect(thread.view.snapshot()).toMatchObject({ error: undefined }); + expect(thread.view.snapshot().replies).toHaveLength(999); + expect(thread.events()).toHaveLength(1003); + return; + } expect(thread.view.snapshot()).toMatchObject({ status: "error", limited: true, diff --git a/src/features/relay/threads.ts b/src/features/relay/threads.ts index 196747433e..c6c47a37f1 100644 --- a/src/features/relay/threads.ts +++ b/src/features/relay/threads.ts @@ -2,6 +2,7 @@ import { isRetryableRead, retryRead } from "./read-retry"; import { canonicalChannel, MissingThreadBounds, + relayOrder, threadBounds, type ThreadCursor, } from "./thread-window"; @@ -18,18 +19,51 @@ import { compareMessages, MessageClock } from "./message-order"; import { shareMessageRows } from "./row-identity"; import { RESUME_READ_AGE } from "./live"; -const AUX = new Set([5, 7, 9005, 40003, 39005, 39006]); +/** Kinds that change or answer a row (edits, reactions, deletions, summaries, + * bounds) and are never rows themselves. */ +export const AUX = new Set([5, 7, 9005, 40003, 39005, 39006]); const PAGE_SIZE = 50; const INITIAL_WINDOW_SIZE = 10; const MAX_PAGES = 10; const MAX_EVENTS = 2000; const MAX_BYTES = 4 * 1024 * 1024; +/** The most a thread view holds, which is the most ThreadPanel shows at once: + * its first window plus the older pages it can load. */ +export const THREAD_LIMITS = Object.freeze({ + rows: INITIAL_WINDOW_SIZE + (MAX_PAGES - 1) * PAGE_SIZE, + events: MAX_EVENTS, + bytes: MAX_BYTES, +}); /** The relay's `thread_window` row allowlist excludes legacy diffs (kind 40008). */ const STRICT_WINDOW_KINDS = [9, 40002]; const contentKind = (event: EventData) => [9, 40002, 40008].includes(event.kind); -const inChannel = (event: EventData, channelId: string) => +export const inChannel = (event: EventData, channelId: string) => event.tags.some(([name, value]) => name === "h" && value === channelId); +/** Adds to `result` the aux in `events` that reach it, or `known`, within two + * hops: a reaction, edit or deletion of a row, then a deletion of that. Never + * adds a row. Returns what it added. */ +export function growAux( + events: readonly T[], + result: Map, + known: ReadonlySet = new Set(), +) { + const added: T[] = []; + for (let hop = 0; hop < 2; hop++) + for (const event of events) + if ( + AUX.has(event.kind) && + !result.has(event.id) && + event.tags.some( + ([name, id]) => + name === "e" && (result.has(id ?? "") || known.has(id ?? "")), + ) + ) { + result.set(event.id, event); + added.push(event); + } + return added; +} /** Relay thread-cursor order (seconds, id); rendered order is `compareMessages`. */ const compare = (a: ThreadCursor, b: ThreadCursor) => a.created_at - b.created_at || a.id.localeCompare(b.id); @@ -197,6 +231,8 @@ export function createThreadView({ let remote: readonly RelayEvent[] = []; let remoteIds = new Set(); let staged: readonly RelayEvent[] = []; + /** How far a running read has fetched; `null` once it read to the end. */ + let reach: ThreadCursor | null | undefined; let selectionStaged: readonly RelayEvent[] = []; let selectionController: AbortController | undefined; let selectionRevision = 0; @@ -277,19 +313,7 @@ export function createThreadView({ ]); const result = new Map(rows.map((event) => [event.id, event])); // Aux closure includes deletion of an auxiliary, not just direct row overlays. - for (let hop = 0; hop < 2; hop++) { - for (const event of events) { - if (!AUX.has(event.kind) || result.has(event.id)) continue; - if ( - event.tags.some( - ([name, value]) => name === "e" && ids.has(value ?? ""), - ) - ) { - result.set(event.id, event); - ids.add(event.id); - } - } - } + growAux(events, result, ids); return [...result.values()]; } function union(...batches: readonly (readonly RelayEvent[])[]) { @@ -430,6 +454,7 @@ export function createThreadView({ remote = []; remoteIds.clear(); staged = []; + reach = undefined; rootId = undefined; cursor = undefined; pages = 0; @@ -452,15 +477,42 @@ export function createThreadView({ } return true; } + /** A reply past the committed cursor belongs to the next older page. + * Admission follows the view's window: unwindowed (no page yet) and + * complete (older, no cursor) admit every related row; windowed (older, + * cursor) admits rows up to the cursor (or a running read's reach), legacy + * diffs, which no strict page returns, and aux of held rows; legacy walks + * forward, so live rows are always inside it. */ + const beyond = (event: RelayEvent) => { + if ( + mode !== "older" || + !cursor || + !STRICT_WINDOW_KINDS.includes(event.kind) || + !isReply(event) + ) + return false; + // A run reading past the committed cursor admits up to its own reach. + const edge = + reach === null + ? undefined + : reach && relayOrder(reach, cursor) < 0 + ? reach + : cursor; + return !!edge && relayOrder(event, edge) < 0; + }; function receive(events: readonly RelayEvent[]) { if (disposed || !canAccess() || (!rootId && !exact)) return; - const fresh = events.filter((event) => !remoteIds.has(event.id)); + const fresh = events.filter( + (event) => !remoteIds.has(event.id) && !beyond(event), + ); if (!fresh.length) return; const incoming = related(fresh); if (!incoming.length) return; - if (retain(union(remote, incoming))) { - publish(); - } + const next = union(remote, incoming); + // No page committed: no window to overflow; the first page decides. + if (!pages && (next.length > MAX_EVENTS || listByteSize(next) > MAX_BYTES)) + return; + if (retain(next)) publish(); } if (seed && canAccess() && contentKind(seed) && inChannel(seed, channelId)) { rootId = threadReference(seed)?.rootId ?? seed.id; @@ -498,6 +550,7 @@ export function createThreadView({ again = false; older = false; staged = []; + reach = undefined; shown = undefined; if (exact) targetStatus = "loading"; if (clear || !canAccess()) { @@ -908,6 +961,10 @@ export function createThreadView({ retain(fetched); return; } + // Rows read past the committed cursor wait for the commit; until + // then a live edit, deletion or reply among them must still land. + staged = fetched; + reach = nextCursor ?? null; // Only strict bounds prove exhaustion. Legacy short pages may be filtered // after LIMIT, so an empty continuation means merely no more returned. more = bounds ? bounds.hasMore : replies.length > 0; @@ -971,6 +1028,7 @@ export function createThreadView({ owned.abort(); if (controller === owned) { staged = []; + reach = undefined; controller = undefined; if (again && !disposed) { const established = again === "established"; diff --git a/src/features/relay/traffic.integration.test.ts b/src/features/relay/traffic.integration.test.ts index 02793c6b45..1c2df45d6c 100644 --- a/src/features/relay/traffic.integration.test.ts +++ b/src/features/relay/traffic.integration.test.ts @@ -49,6 +49,7 @@ function fixture( result: ReturnType>; }[] = []; let resetTraffic = () => {}; + let establishChannel = (_channelId: string) => {}; let incoming!: (events: readonly RelayEvent[]) => void; const stop = vi.fn(); const accepted = new Map(); @@ -65,6 +66,11 @@ function fixture( callbacks.state({ status: "connected", routes: [] }); callbacks.established(); }; + establishChannel = (channelId) => { + callbacks.state({ status: "retrying", routes: [] }); + callbacks.state({ status: "connected", routes: [] }); + callbacks.established(channelId); + }; return { update() {}, retry() {}, dispose: stop }; }, writer: { @@ -150,6 +156,7 @@ function fixture( stop, emit: (events: readonly RelayEvent[]) => incoming(events), reconnect: () => resetTraffic(), + reestablish: (channelId: string) => establishChannel(channelId), staleRead: () => (stale = deferred()), async open() { owner.session.channels.ensureList(); @@ -699,6 +706,80 @@ it("persists queued intent even if the session closes before asynchronous storag expect(sign).not.toHaveBeenCalled(); }); +// A window holds rows from its floor up while older history remains; rows +// below wait for their page, whatever read or traffic carried them. +const windowHistory = () => + Array.from({ length: 40 }, (_, n) => + message(other, "c", `row ${n}`, 100 + n), + ); + +it("keeps a channel scan below the window's floor from limiting its history, and still admits head rows", async () => { + const history = windowHistory(); + const held = history[30] as RelayEvent; + const big = (target: RelayEvent) => + signed(other, { + kind: 7, + content: "x".repeat(12_000), + created_at: 50, + tags: [ + ["h", "c"], + ["e", target.id], + ], + }); + const h = fixture([...history], { + maxHistoryRows: 25, + maxHistoryBytes: 32 * 1024, + }); + await h.open(); + const window = () => h.session.channels.window("c"); + expect(window().hasMore).toBe(true); + expect(window().historyLimited).toBeFalsy(); + const before = window().rows.map((row) => row.id); + expect(before).toHaveLength(20); + // Rows and large reactions on them, all below the floor, beside a + // reaction on a held row. + const scanned = history.slice(0, 20); + h.transport.query = async () => [ + ...scanned, + ...scanned.slice(0, 3).map(big), + signed(other, { + kind: 7, + content: "+", + created_at: 50, + tags: [ + ["h", "c"], + ["e", held.id], + ], + }), + ]; + await h.session.read([{ kinds: [9, 7], "#h": ["c"], until: 120, limit: 40 }]); + expect(window().historyLimited).toBeFalsy(); + expect(window().rows.map((row) => row.id)).toEqual(before); + expect( + window().rows.find((row) => row.id === held.id)?.reactions, + ).toMatchObject([{ content: "+" }]); + const head = message(other, "c", "live head", 500); + h.emit([head]); + expect(window().rows.at(-1)?.id).toBe(head.id); + expect(window().historyLimited).toBeFalsy(); +}); + +it("shows catch-up rows below the window's floor once the catch-up moves it", async () => { + const history = windowHistory(); + const h = fixture(history); + await h.open(); + const window = () => h.session.channels.window("c"); + expect(window().rows.map((row) => row.createdAt)[0]).toBe(120); + // The newest rows are gone after the drop: the head page reaches below + // the floor the window had. + history.splice(25); + h.reestablish("c"); + for (let i = 0; i < 10; i++) await flush(); + expect(window().rows.map((row) => row.createdAt)).toEqual( + Array.from({ length: 35 }, (_, n) => 105 + n), + ); +}); + it("continues incoming traffic at the history budget and applies live membership revocation", async () => { const h = fixture( [message(other, "c", "one", 1), message(other, "c", "two", 2)], diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index 47fa63cd7f..86d43d78ad 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -166,6 +166,9 @@ export interface ReadTransport { /** The relay advertises `buzz-search-sort`: bridge search accepts * `search_sort: "newest"`. Older relays silently rank by relevance. */ readonly searchSort?: true; + /** The relay advertises `buzz-window-newer`: thread and channel windows + * accept `direction: "newer"` and thread pages accept `root_aux: false`. */ + readonly windowNewer?: true; /** The relay advertises NIP-AR sync (`artifacts.sync.version` 1 in NIP-11): * a REQ with `"artifact": "current"` streams a complete set, then live heads. */ readonly artifactSync?: true; @@ -556,6 +559,7 @@ export async function connectBrokerTransport( channelKit?: boolean; channelIdentity?: boolean; searchSort?: boolean; + windowNewer?: boolean; artifactSync?: boolean; sidebarPreferenceWrites?: boolean; sidebarSectionRemoval?: boolean; @@ -917,6 +921,7 @@ export async function connectBrokerTransport( ? { channelIdentity: true as const } : {}), ...(session.searchSort === true ? { searchSort: true as const } : {}), + ...(session.windowNewer === true ? { windowNewer: true as const } : {}), ...(session.artifactSync === true ? { artifactSync: true as const } : {}), ...(session.channelKit ? { diff --git a/src/features/relay/unread.test.ts b/src/features/relay/unread.test.ts index d1ab9a79b1..d87af0141d 100644 --- a/src/features/relay/unread.test.ts +++ b/src/features/relay/unread.test.ts @@ -6481,6 +6481,22 @@ it("catch-up in a DM reads the whole DM, so its channel mark replaces message ma expect(h.session.unread.attention("room", bottom.id).unread).toBe(false); }); +it("a partial reader in a DM reads only the messages it observes and never catches up", async () => { + const h = setup(); + h.grant("room"); + h.emit([channelMetadata(h, "dm")]); + const shown = message(h.alice, "room", "shown", 11); + const hidden = message(h.alice, "room", "hidden", 13); + h.emit([shown, hidden]); + const lease = h.session.unread.reading("room", undefined, true); + await lease.observe([shown.id]); + await lease.catchUp(hidden.id); + lease.dispose(); + expect(h.session.unread.attention("room", shown.id).unread).toBe(false); + expect(h.session.unread.attention("room", hidden.id).unread).toBe(true); + expect(h.journal()?.state.frontiers).toEqual({ [`msg:${shown.id}`]: 11 }); +}); + it("catch-up keeps message marks while the channel type is unknown", async () => { const h = setup(); // The roster lists the channel before its metadata says it is a DM. @@ -7579,3 +7595,28 @@ it("inactive entry sees nothing until the open visit resumes", async () => { expect(h.journal()?.state.frontiers[`seen:msg:${mention.id}`]).toBe(100), ); }); + +it("reads and marks unread a held-only message, never counting or caching it", async () => { + const h = setup(); + h.grant("room"); + await h.session.unread.ensure(); + const counted = h.snapshot().observedCount; + const held = eventDto(message(h.alice, "room", "held", 12)); + const handle = h.session.unread.reading("room"); + await expect(handle.observe([held.id])).rejects.toThrow(/evidence/); + await expect( + h.session.unread.markMessageUnread("room", held.id), + ).rejects.toThrow(/evidence/); + h.session.retain().set([held]); + await handle.observe([held.id]); + expect(h.journal()?.state.frontiers).toEqual({ [`msg:${held.id}`]: 12 }); + await h.session.unread.markMessageUnread("room", held.id); + await h.session.unread.markMessageRead("room", held.id); + // The hold is evidence only: nothing counted, nothing cached for views. + expect(h.snapshot().observedCount).toBe(counted); + expect( + h.session.observe([{ kinds: [9], "#h": ["room"], limit: 10 }]).snapshot() + .events, + ).toEqual([]); + handle.dispose(); +}); diff --git a/src/features/relay/unread.ts b/src/features/relay/unread.ts index af8f7e8d3c..1084e93111 100644 --- a/src/features/relay/unread.ts +++ b/src/features/relay/unread.ts @@ -174,8 +174,11 @@ export interface UnreadCapability { revision(): number; /** Access/cache/connection retirement fence. */ generation(): number; - /** `rootId` names the thread a reader shows, which bounds its DM reads. */ - reading(channelId: string, rootId?: string): ReadingHandle; + /** `rootId` names the thread a reader shows, which bounds its DM reads. + * A `partial` reader leaves unread rows out of what it shows: it reads + * only the rows it observes, never a DM through its newest message, and + * never catches up. */ + reading(channelId: string, rootId?: string, partial?: boolean): ReadingHandle; /** Whether the viewer follows this canonical root: an explicit choice, * otherwise writing or replying anywhere in its thread. */ following(channelId: string, rootId: string): boolean; @@ -339,6 +342,7 @@ export function createUnread({ signingAuthority, workflowAuthority, profiles, + evidence, notify = (listener) => listener(), follows = memoryThreadFollows(), }: { @@ -350,6 +354,9 @@ export function createUnread({ signingAuthority?: string; workflowAuthority?: string | undefined; profiles?: ProfileQueries; + /** Events held elsewhere (the session's `retain` holds). They let a read or + * unread mark name a message this unread never counted, and are never counted. */ + evidence?: (id: string) => RelayEvent | undefined; notify?: (listener: () => void) => void; follows?: ThreadFollowStorage; }) { @@ -366,6 +373,8 @@ export function createUnread({ let refresh: Promise | undefined; const lifetime = new AbortController(); const events = new Map(); + /** Counted evidence, else a held event that is never counted. */ + const knownEvent = (id: string) => events.get(id) ?? evidence?.(id); // Per repair batch (its channel IDs): the newest created_at a complete read of // it returned. `events` only grows until a reset below, so a later repair needs // just what is newer; every path that empties or shrinks `events` clears this, @@ -541,7 +550,7 @@ export function createUnread({ const keyFor = (target: ReadTarget) => `${target.channelId}:${targetKey(target)}`; /** Counted evidence, or a fetched parent/root kept only for structure. */ - const structural = (id: string) => events.get(id) ?? lookupEvents.get(id); + const structural = (id: string) => knownEvent(id) ?? lookupEvents.get(id); function root(event: RelayEvent): string | undefined { const channel = channelOf(event); let current = event; @@ -2488,7 +2497,7 @@ export function createUnread({ } function requireMessage(target: ReadTarget, id: string) { targetKey(target); - const event = events.get(id); + const event = knownEvent(id); if ( closed || !allowed(target.channelId) || @@ -2514,7 +2523,7 @@ export function createUnread({ /** Coordination between agents has no unread state, so no unread intent * may be saved for it. */ function refuseAgentCoordination(messageId: string) { - const event = events.get(messageId); + const event = knownEvent(messageId); if (event && agentAudience(event)) throw new Error("Messages between agents cannot be marked unread"); } @@ -2544,7 +2553,7 @@ export function createUnread({ } } return [...ids].flatMap((id) => { - const event = events.get(id); + const event = knownEvent(id); return event ? [event] : []; }); } @@ -2742,7 +2751,7 @@ export function createUnread({ saved = next; followsChanged(changed); }, - reading(channelId, rootId) { + reading(channelId, rootId, partial = false) { if (closed || !allowed(channelId) || handles.size >= 64) throw new Error("Reading handle unavailable"); let active = true; @@ -2770,12 +2779,13 @@ export function createUnread({ // is no backlog to keep. A thread reader stops before unread messages it // does not show (`dmCut`). One lease is one earned dwell, so its catchUp // and observe share the first cutoff: a message arriving between them - // waits for the next dwell. Returns undefined outside DMs. + // waits for the next dwell. Returns undefined outside DMs and for a + // partial reader. let dmRead: Promise | undefined; const readDm = ( witnesses: readonly Readonly<{ target: ReadTarget; id: string }>[], ) => { - if (!isDm(channelId)) return undefined; + if (partial || !isDm(channelId)) return undefined; if (dmRead) return dmRead; for (const { target, id } of witnesses) { let event: RelayEvent; @@ -2823,7 +2833,7 @@ export function createUnread({ }); }, async catchUp(id: string, rootId?: string) { - if (!valid()) return; + if (partial || !valid()) return; const target = rootId ? { kind: "thread" as const, channelId, rootId } : { kind: "channel" as const, channelId }; @@ -3074,7 +3084,7 @@ export function createUnread({ generation === epoch && (visits.get(channelId) ?? 0) === visit && allowed(channelId) && - rows.every((row) => events.get(row.id) === row && !deleted(row)); + rows.every((row) => knownEvent(row.id) === row && !deleted(row)); const finishPending = trackPendingForcedMessages( channelId, rows.map((row) => row.id), @@ -3112,7 +3122,7 @@ export function createUnread({ generation === epoch && (visits.get(channelId) ?? 0) === visit && allowed(channelId) && - rows.every((row) => events.get(row.id) === row && !deleted(row)); + rows.every((row) => knownEvent(row.id) === row && !deleted(row)); if (!valid()) throw new Error("Unread channel visit expired"); const forced = forcedMessages.get(channelId); const ids = new Set(rows.map((row) => row.id)); diff --git a/src/features/relay/window.test.ts b/src/features/relay/window.test.ts index 20afcd200f..103a529cad 100644 --- a/src/features/relay/window.test.ts +++ b/src/features/relay/window.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from "vitest"; -import { noticeFilter, parseWindow, windowFilter } from "./window"; +import { + noticeFilter, + parseWindow, + verifyChannelWindows, + windowFilter, +} from "./window"; import { bounds, keypair, message } from "./testing"; const relay = keypair(), @@ -134,3 +139,187 @@ it("advances valid equal-time composite history cursors deterministically", () = ]); expect(page.cursor).toEqual({ createdAt: 10, eventId: nextId }); }); + +describe("forward window pages", () => { + const at = { createdAt: 10, eventId: "b".repeat(64) }; + const done = { has_more: false, next_cursor: null }; + it("accept only the bound of their own lane and direction", () => { + expect( + parseWindow( + channel, + at, + relay.pubkey, + [ + bounds(relay, channel, `newer:10:${at.eventId}`, { + ...done, + direction: "newer", + }), + ], + true, + ), + ).toMatchObject({ hasMore: false }); + expect(() => + parseWindow( + channel, + at, + relay.pubkey, + [bounds(relay, channel, `10:${at.eventId}`, done)], + true, + ), + ).toThrow(/invalid window bounds/); + expect(() => + parseWindow( + channel, + at, + relay.pubkey, + [bounds(relay, channel, `newer:10:${at.eventId}`, done)], + true, + ), + ).toThrow(/malformed/); + expect(() => + parseWindow(channel, null, relay.pubkey, [ + bounds(relay, channel, "newer:head", { ...done, direction: "newer" }), + ]), + ).toThrow(/invalid window bounds/); + expect(() => + parseWindow(channel, null, relay.pubkey, [ + bounds(relay, channel, "head", { ...done, direction: "newer" }), + ]), + ).toThrow(/malformed/); + }); + it.each([ + { newer: false, next: { created_at: 9, id: at.eventId }, advances: true }, + { + newer: false, + next: { created_at: 10, id: "c".repeat(64) }, + advances: true, + }, + { + newer: false, + next: { created_at: 10, id: "a".repeat(64) }, + advances: false, + }, + { newer: false, next: { created_at: 10, id: at.eventId }, advances: false }, + { newer: false, next: { created_at: 11, id: at.eventId }, advances: false }, + { newer: true, next: { created_at: 11, id: at.eventId }, advances: true }, + { + newer: true, + next: { created_at: 10, id: "a".repeat(64) }, + advances: true, + }, + { + newer: true, + next: { created_at: 10, id: "c".repeat(64) }, + advances: false, + }, + { newer: true, next: { created_at: 9, id: at.eventId }, advances: false }, + { newer: true, next: { created_at: 10, id: at.eventId }, advances: false }, + ])( + "a cursor must move on in relay order (newer $newer, next $next.created_at)", + ({ newer, next, advances }) => { + const parse = () => + parseWindow( + channel, + at, + relay.pubkey, + [ + bounds(relay, channel, `${newer ? "newer:" : ""}10:${at.eventId}`, { + has_more: true, + next_cursor: next, + ...(newer ? { direction: "newer" } : {}), + }), + ], + newer, + ); + if (advances) + expect(parse().cursor).toEqual({ + createdAt: next.created_at, + eventId: next.id, + }); + else expect(parse).toThrow(/does not advance/); + }, + ); +}); + +describe("reader verification of channel pages", () => { + const at = { createdAt: 10, eventId: "b".repeat(64) }; + const done = { has_more: false, next_cursor: null }; + const older = windowFilter(channel, at); + const forward = { + ...windowFilter(channel, null), + direction: "newer" as const, + after: at.createdAt, + after_id: at.eventId, + }; + const olderBound = bounds(relay, channel, `10:${at.eventId}`, done); + const forwardBound = bounds(relay, channel, `newer:10:${at.eventId}`, { + ...done, + direction: "newer", + }); + const verify = + ( + filters: Parameters[0], + events: Parameters[1], + ) => + () => + verifyChannelWindows(filters, events, relay.pubkey); + it("passes valid pages of both lanes and ignores reads without top_level", () => { + const row = message(author, channel, "hi", 10); + expect(verify([older], [row, olderBound])).not.toThrow(); + expect(verify([forward], [row, forwardBound])).not.toThrow(); + expect(verify([older, forward], [olderBound, forwardBound])).not.toThrow(); + expect( + verify([{ kinds: [9], "#h": [channel], limit: 5 }], [row]), + ).not.toThrow(); + }); + it("rejects a missing, duplicated, foreign, wrong-lane or stray bound", () => { + expect(verify([older], [])).toThrow(/invalid window bounds/); + expect(verify([older], [olderBound, olderBound])).toThrow( + /invalid window bounds/, + ); + expect( + verify([older], [bounds(impostor, channel, `10:${at.eventId}`, done)]), + ).toThrow(/invalid window bounds/); + expect( + verify( + [older], + [olderBound, bounds(impostor, channel, `10:${at.eventId}`, done)], + ), + ).toThrow(/invalid window bounds/); + expect(verify([forward], [olderBound])).toThrow(/invalid window bounds/); + expect(verify([older], [forwardBound])).toThrow(/invalid window bounds/); + expect( + verify([older], [olderBound, bounds(relay, "other", "head", done)]), + ).toThrow(/invalid window bounds/); + expect( + verify( + [{ kinds: [9], "#h": [channel], limit: 5 }, older], + [olderBound, forwardBound], + ), + ).toThrow(/invalid window bounds/); + }); + it("rejects a page that does not advance and a filter without exactly one channel", () => { + expect( + verify( + [forward], + [ + bounds(relay, channel, `newer:10:${at.eventId}`, { + has_more: true, + next_cursor: { created_at: 9, id: at.eventId }, + direction: "newer", + }), + ], + ), + ).toThrow(/does not advance/); + const { "#h": _h, ...unscoped } = older; + expect(verify([unscoped], [olderBound])).toThrow(/invalid window bounds/); + expect( + verify([{ ...older, "#h": [channel, "other"] }], [olderBound]), + ).toThrow(/invalid window bounds/); + }); + it("rejects two windows a single bound cannot tell apart", () => { + expect( + verify([older, { ...older, limit: 5 }], [olderBound, olderBound]), + ).toThrow(/invalid window bounds/); + }); +}); diff --git a/src/features/relay/window.ts b/src/features/relay/window.ts index bfb819fdaf..f41789a846 100644 --- a/src/features/relay/window.ts +++ b/src/features/relay/window.ts @@ -1,6 +1,7 @@ import { CHANNEL_ROW_KINDS } from "./membership"; import { isObject, objectBody } from "./body"; import { hasTag, type ReadFilter, type RelayEvent } from "./events"; +import { relayOrder, type ThreadCursor } from "./thread-window"; export type WindowCursor = Readonly<{ createdAt: number; eventId: string }>; export type WindowPage = Readonly<{ @@ -50,16 +51,19 @@ export function noticeFilter( }; } /** The relay answers each served window with exactly one signed kind 39006 bounds event. Anything else is rejected; - * an absent or malformed bound must never be mistaken for "no more history". */ + * an absent or malformed bound must never be mistaken for "no more history". + * A `newer` page (oldest first) has its own `:newer:` lane and direction. */ export function parseWindow( channelId: string, cursor: WindowCursor | null, relayAuthor: string, events: readonly RelayEvent[], + newer = false, ): WindowPage { + const lane = newer ? `${channelId}:newer` : channelId; const suffix = cursor - ? `${channelId}:${cursor.createdAt}:${cursor.eventId}` - : `${channelId}:head`; + ? `${lane}:${cursor.createdAt}:${cursor.eventId}` + : `${lane}:head`; const bounds = events.filter( (event) => event.kind === 39006 && @@ -71,7 +75,8 @@ export function parseWindow( if (bounds.length !== 1 || !bound) throw new Error("Channel history response has invalid window bounds"); const body = objectBody(bound.content); - if (!body) throw new Error("Channel history bounds are malformed"); + if (!body || body.direction !== (newer ? "newer" : undefined)) + throw new Error("Channel history bounds are malformed"); if (typeof body.has_more !== "boolean") throw new Error("Channel history bounds omit has_more"); const next = body.next_cursor; @@ -87,14 +92,11 @@ export function parseWindow( ) throw new Error("Channel history cursor is malformed"); nextCursor = { createdAt: next.created_at, eventId: next.id }; - // History order is descending timestamp, then ascending id. Equal-time - // pages must move to a lexically greater id; a repeated cursor is not progress. - if ( - cursor && - (nextCursor.createdAt > cursor.createdAt || - (nextCursor.createdAt === cursor.createdAt && - nextCursor.eventId <= cursor.eventId)) - ) + // History order is descending timestamp, then ascending id; forward + // pages run the reverse. Equal-time pages must move on by id; a repeated + // cursor is not progress. + const from = cursor && { created_at: cursor.createdAt, id: cursor.eventId }; + if (from && relayOrder(next as ThreadCursor, from) * (newer ? 1 : -1) <= 0) throw new Error("Channel history cursor does not advance"); } if (body.has_more !== (nextCursor !== null)) @@ -105,3 +107,36 @@ export function parseWindow( cursor: nextCursor, }; } + +/** Runs on signature-verified finite results BEFORE session admission: each + * `top_level` filter names one channel and is answered by exactly one valid + * bound of its own lane and cursor, and no other 39006 rides along. A bound + * binds only channel, lane and cursor, so two such filters for the same ones + * cannot be told apart and are rejected. */ +export function verifyChannelWindows( + filters: readonly ReadFilter[], + events: readonly RelayEvent[], + relayAuthor: string, +) { + const windows = filters.filter((filter) => filter.top_level === true); + if (!windows.length) return; + const invalid = () => + new Error("Channel history response has invalid window bounds"); + for (const filter of windows) { + const [channelId, ...extra] = filter["#h"] ?? []; + if (!channelId || extra.length) throw invalid(); + const newer = filter.direction === "newer"; + const [at, id] = newer + ? [filter.after, filter.after_id] + : [filter.until, filter.before_id]; + parseWindow( + channelId, + at === undefined ? null : { createdAt: at, eventId: id ?? "" }, + relayAuthor, + events, + newer, + ); + } + if (events.filter((event) => event.kind === 39006).length !== windows.length) + throw invalid(); +} diff --git a/src/plugins/author.ts b/src/plugins/author.ts index 38145a58fd..2e2df2b525 100644 --- a/src/plugins/author.ts +++ b/src/plugins/author.ts @@ -87,6 +87,9 @@ export type { ComposerReplacement, ComposerAccessory, ComposerAccessoryProps, + ConversationPresentation, + PresentationLimits, + PresentResult, ComposerResource, ComposerCaptureProps, AttachmentRenderer, @@ -103,6 +106,14 @@ export type { TargetOpener, } from "../features/conversation/contracts"; export type { RelayData, RelaySnapshot } from "../features/relay/service"; +export type { RelaySession } from "../features/relay/session"; +export type { + EventData, + ReadFilter, + RelayEvent, +} from "../features/relay/events"; +export type { ReadOptions } from "../features/relay/reader"; +export type { ChannelMessage } from "../features/relay/contracts"; export type { ArtifactSyncFilter, ArtifactSyncSnapshot, diff --git a/tests/fixtures/conversation-arranger/fixtures.ts b/tests/fixtures/conversation-arranger/fixtures.ts new file mode 100644 index 0000000000..4f6930dbcd --- /dev/null +++ b/tests/fixtures/conversation-arranger/fixtures.ts @@ -0,0 +1,236 @@ +import type { Event } from "nostr-tools"; +import type { RelayEvent } from "../../../src/features/relay/events"; +import { keypair, type Key } from "../../../src/features/relay/testing"; +import { + CHANNEL, + DELETION, + EDIT, + REACTION, + T, + mint, + prove, + seeded, + shuffled, +} from "./relay"; + +/** Distinct accounts that react; the most one row can have is this many. */ +export const REACTORS = 40; +const authors = Array.from({ length: 8 }, keypair); +const reactors = Array.from({ length: REACTORS }, keypair); + +/** One message in twenty says "Gizmo", so a filter for "gizmo" matches 5% of + * rows, ignoring case. An edit replaces the whole text. */ +const said = (word: string, i: number) => + i % 20 === 3 ? `${word} ${i} Gizmo` : `${word} ${i}`; +const tag = (id: string, marker?: string) => + marker ? ["e", id, "", marker] : ["e", id]; +const reactionOf = (key: Key, target: string, at: number) => + mint(key, { + kind: REACTION, + content: "👍", + created_at: at, + tags: [["h", CHANNEL], tag(target)], + }); +const deletionOf = (key: Key, target: string, at: number) => + mint(key, { + kind: DELETION, + content: "", + created_at: at, + tags: [["h", CHANNEL], tag(target)], + }); +const editOf = (key: Key, target: string, text: string, at: number) => + mint(key, { + kind: EDIT, + content: text, + created_at: at, + tags: [["h", CHANNEL], tag(target)], + }); + +export type Fixture = Readonly<{ + /** Every event, proven, in creation order. */ + events: readonly RelayEvent[]; + /** The rows (replies of the thread, or top-level rows) in creation order. */ + rows: readonly RelayEvent[]; + root?: RelayEvent; + /** Row ids by what was done to them. */ + groups: Readonly>; + authors: readonly Key[]; + reactors: readonly Key[]; +}>; + +/** A thread of 2,000 replies and about 5,200 events. Replies are written four to + * a second, so their timestamps tie; most nest under an earlier reply. Distinct + * reactors per reply are: ten replies 20, fifty 5, four hundred 2; then 500 with + * 1, 250 whose one reactor reacted twice, 200 whose reaction was deleted, 230 + * edited, 100 deleted (each with two reactions) and the rest untouched. Twenty + * of the 2-reactor replies are also edited. */ +export async function threadFixture( + count = 2000, + seed = 7, +): Promise { + const random = seeded(seed); + const raw: Event[] = []; + const rootAt = T - 100; + const rootEvent = mint(authors[0] as Key, { + kind: 9, + content: "The thread root", + created_at: rootAt, + tags: [["h", CHANNEL]], + }); + raw.push(rootEvent); + const replies: Event[] = []; + const replyKeys: Key[] = []; + for (let i = 0; i < count; i++) { + const author = authors[i % authors.length] as Key; + // Every fifth reply answers the root; others an earlier reply, up to six back. + const parentIndex = i % 5 === 0 ? -1 : Math.max(0, i - 1 - (i % 6)); + const parent = i > 0 && parentIndex >= 0 ? replies[parentIndex] : undefined; + const event = mint(author, { + kind: 9, + content: said("reply", i), + created_at: T + Math.floor(i / 4), + tags: [ + ["h", CHANNEL], + ...(parent + ? [tag(rootEvent.id, "root"), tag(parent.id, "reply")] + : [tag(rootEvent.id, "reply")]), + ], + }); + replies.push(event); + replyKeys.push(author); + raw.push(event); + } + const order = shuffled( + Array.from({ length: count }, (_, i) => i), + random, + ); + const take = (from: number, n: number) => order.slice(from, from + n); + const groups: Record = {}; + const group = (name: string, indexes: readonly number[]) => { + groups[name] = indexes.map((i) => (replies[i] as Event).id); + return indexes; + }; + const react = (i: number, k: number, at = 1) => + reactionOf( + reactors[(i * 3 + k) % REACTORS] as Key, + (replies[i] as Event).id, + (replies[i] as Event).created_at + at, + ); + const edit = (i: number) => + editOf( + replyKeys[i] as Key, + (replies[i] as Event).id, + `reply ${i} (edited)`, + (replies[i] as Event).created_at + 50, + ); + const scale = count / 2000; + const sizes = [10, 50, 400, 500, 250, 200, 230, 100].map((n) => + Math.round(n * scale), + ) as [number, number, number, number, number, number, number, number]; + let at = 0; + const next = (n: number) => { + const slice = take(at, n); + at += n; + return slice; + }; + for (const i of group("top20", next(sizes[0]))) + for (let k = 0; k < 20; k++) raw.push(react(i, k)); + for (const i of group("top5", next(sizes[1]))) + for (let k = 0; k < 5; k++) raw.push(react(i, k)); + const twos = group("top2", next(sizes[2])); + for (const i of twos) for (let k = 0; k < 2; k++) raw.push(react(i, k)); + for (const i of twos.slice(0, Math.round(20 * scale))) raw.push(edit(i)); + for (const i of group("one", next(sizes[3]))) raw.push(react(i, 0)); + // The same account reacts twice: two events, one reactor. + for (const i of group("twice", next(sizes[4]))) + raw.push(react(i, 0), react(i, 0, 2)); + for (const i of group("cancelled", next(sizes[5]))) { + const reaction = react(i, 0); + raw.push( + reaction, + deletionOf( + reactors[(i * 3) % REACTORS] as Key, + reaction.id, + reaction.created_at + 100, + ), + ); + } + for (const i of group("edited", next(sizes[6]))) raw.push(edit(i)); + for (const i of group("deleted", next(sizes[7]))) { + raw.push(react(i, 0), react(i, 1)); + raw.push( + deletionOf( + replyKeys[i] as Key, + (replies[i] as Event).id, + (replies[i] as Event).created_at + 60, + ), + ); + } + // The root has reactions of its own, which a page can leave out. + for (let k = 0; k < 5; k++) + raw.push(reactionOf(reactors[k] as Key, rootEvent.id, rootAt + 1)); + const events = await prove(raw); + const byId = new Map(events.map((e) => [e.id, e])); + return { + events, + rows: replies.map((e) => byId.get(e.id) as RelayEvent), + root: byId.get(rootEvent.id) as RelayEvent, + groups, + authors, + reactors, + }; +} + +/** A channel of `count` top-level rows and 3,000 reactions (at the default size): + * 20 rows with 20 distinct reactors, 200 with 5 and 800 with 2. */ +export async function channelFixture( + count = 5000, + seed = 11, +): Promise { + const random = seeded(seed); + const raw: Event[] = []; + const rows: Event[] = []; + for (let i = 0; i < count; i++) + rows.push( + mint(authors[i % authors.length] as Key, { + kind: 9, + content: said("row", i), + created_at: T + Math.floor(i / 4), + tags: [["h", CHANNEL]], + }), + ); + raw.push(...rows); + const order = shuffled( + Array.from({ length: count }, (_, i) => i), + random, + ); + const groups: Record = {}; + let at = 0; + for (const [name, n, reacting] of [ + ["top20", 20, 20], + ["top5", 200, 5], + ["top2", 800, 2], + ] as const) { + const indexes = order.slice(at, at + n); + at += n; + groups[name] = indexes.map((i) => (rows[i] as Event).id); + for (const i of indexes) + for (let k = 0; k < reacting; k++) + raw.push( + reactionOf( + reactors[(i * 3 + k) % REACTORS] as Key, + (rows[i] as Event).id, + (rows[i] as Event).created_at + 1, + ), + ); + } + const events = await prove(raw); + const byId = new Map(events.map((e) => [e.id, e])); + return { + events, + rows: rows.map((e) => byId.get(e.id) as RelayEvent), + groups, + authors, + reactors, + }; +} diff --git a/tests/fixtures/conversation-arranger/plugin.ts b/tests/fixtures/conversation-arranger/plugin.ts new file mode 100644 index 0000000000..9c0efedbf5 --- /dev/null +++ b/tests/fixtures/conversation-arranger/plugin.ts @@ -0,0 +1,730 @@ +import type { + ChannelMessage, + ComposerAccessoryProps, + Context, + ConversationPresentation, + EventData, + ReadFilter, + RelayEvent, + RelaySession, +} from "../../../src/plugins/author"; + +// Test-only installed-plugin-shaped module (never shipped): a Reddit-style +// arranger for the reader. It uses only `ctx` and the author types, and owns +// everything a user would name: the sorts, a text filter, the window size, +// "More", "Next" and "Previous" (the reader shows one window of its ranked list +// at a time, so any row is reachable), the layout of nested replies, the status +// and failure text, and the scan. +// +// The core gives it five things: `snapshotRead` (with background priority) for +// the scan, `retain` to keep what it read live, `foldRows` to fold it, the +// `newer` windows and `root_aux: false`, and `present` to show rows in the +// reader. Everything else here is its own. +export const inject = ["react", "conversation"]; + +type Sort = "top" | "oldest"; +type Cursor = { created_at: number; id: string }; +type Lane = "older" | "newer"; +type Hold = ReturnType; + +/** Rows per page read, and in the first window. */ +const PAGE = 200; +/** Rows a "More" adds, up to the most the reader shows (460 in a thread). */ +const MORE = 260; +/** Live reactions, edits and deletions the shown rows may still gain, under `limits`. */ +const HEADROOM = 200; +/** The smallest slice it re-presents after `ended` or `limit`. */ +const SMALLEST = 20; +/** The wait before reading again after a reconnect is up to this long, the + * spread Buzz gives its own reconnects, so a fleet does not read in step. */ +const JITTER_MS = 10_000; +const BOUNDS = { thread: 39007, channel: 39006 } as const; +const AUX = new Set([5, 7, 40003]); + +/** The scan's whole life, as one value. A new sort, a withdraw or unmount aborts `scanning`. */ +type Phase = + | { state: "idle" } + | { state: "scanning"; sort: Sort; abort: AbortController } + | { state: "ready"; sort: Sort } + | { state: "failed"; sort: Sort; message: string }; + +export type View = Readonly<{ + phase: Phase["state"]; + sort: Sort | undefined; + /** Rows read so far. */ + read: number; + /** Rows in the window it last presented, pinned rows included. */ + shown: number; + /** The ranked rows the window shows are `from + 1` to `to` of `total`. */ + from: number; + to: number; + /** Rows that match the filter; only those read so far until `exact`. */ + total: number; + exact: boolean; + /** The window can grow, or move to the next or the previous one. */ + more: boolean; + next: boolean; + previous: boolean; + filter: string; + message: string; +}>; + +const auxTargets = (event: EventData) => + event.tags.flatMap(([name, id]) => (name === "e" && id ? [id] : [])); +/** The relay's `newer` order: created_at ascending, id descending. */ +const inOrder = (a: Cursor, b: Cursor) => + a.created_at - b.created_at || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0); +/** Distinct accounts that reacted: its own definition of a score. */ +const score = (row: ChannelMessage) => + new Set(row.reactions.flatMap((r) => r.events.map((e) => e.authorId))).size; +const pending = (row: ChannelMessage) => + row.delivery !== undefined && row.delivery !== "seen"; +const cursorOf = (row: ChannelMessage): Cursor => ({ + created_at: row.createdAt, + id: row.id, +}); + +function createArranger(initial: ComposerAccessoryProps) { + let props = initial; + let phase: Phase = { state: "idle" }; + let sort: Sort | undefined; + let size = PAGE; + /** The text a row's content must contain, ignoring case; "" shows every row. */ + let filter = ""; + /** Where each window began in the ranked list; the last is the current one. */ + let starts = [0]; + /** The events read so far, and held so their live aux reaches it. */ + const events = new Map(); + let hold: Hold | undefined; + /** Every row has been read. */ + let scanned = false; + /** The next `newer` page of an oldest-first view: undefined, its head; null, its end. */ + let forward: Cursor | null | undefined; + let shown = 0; + let taken = 0; + let total = 0; + let message = ""; + let stops: (() => void)[] = []; + let queued = false; + /** The live connection, and whether it dropped after rows were read: changes + * made while it was down may never reach the plugin, so what it read is no + * longer exact until it reads again (`rescan`, after a reconnect). */ + let connected = false; + let lost = false; + let repair: ReturnType | undefined; + let cached: View | undefined; + const listeners = new Set<() => void>(); + const emit = () => { + cached = undefined; + for (const listener of [...listeners]) listener(); + }; + const rootId = () => props.threadRootId; + const offset = () => starts.at(-1) ?? 0; + const kindOfBounds = () => (rootId() ? BOUNDS.thread : BOUNDS.channel); + const read = (filters: ReadFilter[], signal?: AbortSignal) => { + const snapshot = props.session.snapshotRead; + if (!snapshot) throw new Error("This connection cannot scan"); + return snapshot(filters, { + priority: "background", + ...(signal ? { signal } : {}), + }); + }; + const rows = () => + props.session + .foldRows(props.channelId, [...events.values()], rootId()) + .filter((row) => row.id !== rootId()); + + function keep(more: readonly RelayEvent[]) { + const kind = kindOfBounds(); + for (const event of more) + if (event.kind !== kind && !events.has(event.id)) + events.set(event.id, event); + holdAll(); + } + /** The hold keeps everything read, so a live reaction on a row it does not + * show still reaches `subscribeLive`. */ + function holdAll() { + try { + hold ??= props.session.retain(); + hold.set([...events.values()]); + } catch (error) { + throw new Error( + `Cannot hold this conversation: ${(error as Error).message}`, + ); + } + } + + /** One read of a page for each lane asked (two thread lanes ride one read); + * returns each lane's cursor to continue from, null at its end. */ + async function pages( + lanes: readonly (readonly [Lane, Cursor | undefined])[], + signal: AbortSignal, + ) { + const windowed = props.session.windowNewer === true; + const root = rootId(); + const filters = lanes.map(([lane, cursor]): ReadFilter => { + const newer = lane === "newer"; + return { + "#h": [props.channelId], + kinds: [9], + limit: PAGE, + include_aux: true, + ...(root + ? { + thread_window: true, + "#e": [root], + depth_limit: 100, + // The reader's header already shows the root and its reactions. + ...(windowed ? { root_aux: false as const } : {}), + } + : { top_level: true }), + ...(newer ? { direction: "newer" as const } : {}), + ...(cursor + ? newer + ? { after: cursor.created_at, after_id: cursor.id } + : { until: cursor.created_at, before_id: cursor.id } + : {}), + }; + }); + const answer = await read(filters, signal); + const bodies = answer + .filter((event) => event.kind === kindOfBounds()) + .map( + (event) => + JSON.parse(event.content) as { + direction?: Lane; + has_more: boolean; + next_cursor: Cursor | null; + }, + ); + keep(answer); + return lanes.map(([lane]) => { + // An older bound names no direction. + const body = bodies.find((b) => (b.direction ?? "older") === lane); + if (!body) throw new Error("The relay sent no window bounds"); + return body.has_more ? body.next_cursor : null; + }); + } + const rootRead = (signal: AbortSignal) => { + const root = rootId(); + return root && !events.has(root) + ? read([{ ids: [root], "#h": [props.channelId], limit: 1 }], signal).then( + keep, + ) + : undefined; + }; + + /** Reads every row: both ends of a thread at once until they meet, else older + * pages to the end. */ + async function scanAll(signal: AbortSignal) { + await rootRead(signal); + if (rootId() && props.session.windowNewer === true) { + let older: Cursor | null | undefined; + let newer: Cursor | null | undefined; + for (;;) { + const [o, n] = await pages( + [ + ["older", older ?? undefined], + ["newer", newer ?? undefined], + ], + signal, + ); + older = o; + newer = n; + emit(); + // A lane that ran out walked the whole thread; the lanes are done once + // the newer one reaches what the older one has read. + if (!o || !n || inOrder(n, o) >= 0) break; + } + } else { + let cursor: Cursor | null | undefined; + while (cursor !== null) { + [cursor] = await pages([["older", cursor ?? undefined]], signal); + emit(); + } + } + scanned = true; + } + + const countRows = () => + [...events.values()].filter((e) => e.kind === 9 && e.id !== rootId()) + .length; + /** The rows an oldest-first window ends at. */ + const windowEnd = () => offset() + size; + /** A row an oldest-first read has reached without a gap: at or before its + * cursor. A live row past the cursor waits until the read reaches it. */ + const reached = (row: ChannelMessage) => + scanned || + forward === null || + (forward !== undefined && inOrder(cursorOf(row), forward) <= 0); + /** Rows read so far that are not its own sends, folded as the window will be. */ + const readRows = () => + rows().filter((row) => !pending(row) && reached(row)).length; + /** An oldest-first view reads forward from the start, as far as its window needs. */ + async function scanForward(signal: AbortSignal) { + await rootRead(signal); + while (forward !== null && readRows() < windowEnd()) { + [forward] = await pages([["newer", forward ?? undefined]], signal); + emit(); + } + scanned = forward === null; + } + /** Ranking and filtering need every row, so a result is never partial because of + * what happened to load. An oldest-first window reads forward only as far as it + * reaches (without `buzz-window-newer` it cannot, so it reads it all). */ + const reachesAll = () => + sort === "top" || filter !== "" || props.session.windowNewer !== true; + const enough = () => + scanned || + (!reachesAll() && (forward === null || readRows() >= windowEnd())); + const load = (signal: AbortSignal) => + reachesAll() ? scanAll(signal) : scanForward(signal); + + /** Presents the window for the current sort. */ + function arrange(place?: ConversationPresentation["place"]) { + const { present, limits, targetId } = props; + if (!present || !limits || !sort || phase.state !== "ready") return; + const all = [...events.values()]; + const folded = rows(); + const needle = filter.toLowerCase(); + const matching = needle + ? folded.filter((row) => row.content.toLowerCase().includes(needle)) + : folded; + const mine = matching.filter(pending); + const rest = matching.filter((row) => !pending(row) && reached(row)); + // Each row's score once, not once per comparison. + const scores = new Map( + sort === "top" ? rest.map((row) => [row.id, score(row)]) : [], + ); + rest.sort( + sort === "top" + ? (a, b) => + (scores.get(b.id) ?? 0) - (scores.get(a.id) ?? 0) || + (a.id < b.id ? -1 : 1) + : (a, b) => inOrder(cursorOf(a), cursorOf(b)), + ); + // Its own sends stay in view; so does the message the reader opened to. + const target = rest.find((row) => row.id === targetId); + const pinned = [ + ...(sort === "top" ? mine : []), + ...(target ? [target] : []), + ]; + const tail = sort === "top" ? [] : mine; + const queue = rest.filter((row) => row !== target); + // A window past the end (rows were deleted, the filter narrowed) steps back. + while (starts.length > 1 && offset() >= queue.length) starts.pop(); + const from = offset(); + // The window leaves headroom under the reader's limits for live aux. + const auxByTarget = new Map(); + for (const event of all) + if (AUX.has(event.kind)) + for (const id of auxTargets(event)) + auxByTarget.set(id, [...(auxByTarget.get(id) ?? []), event]); + const cost = new Map(); + const costOf = (row: ChannelMessage) => { + let value = cost.get(row.id); + if (!value) { + const first = auxByTarget.get(row.id) ?? []; + const group = [ + events.get(row.id), + ...first, + ...first.flatMap((e) => auxByTarget.get(e.id) ?? []), + ].filter((e): e is RelayEvent => !!e); + value = { + events: group.length, + bytes: group.reduce((sum, e) => sum + JSON.stringify(e).length, 0), + }; + cost.set(row.id, value); + } + return value; + }; + const spare = { + events: Number.isFinite(limits.events) + ? limits.events - HEADROOM - 1 + : Infinity, + bytes: limits.bytes - 256 * 1024, + }; + const chosen: ChannelMessage[] = []; + let count = 0; + let bytes = 0; + const room = Math.max(0, limits.rows - pinned.length - tail.length); + const window = queue.slice(from, from + Math.min(size, room)); + for (const row of [...pinned, ...window, ...tail]) { + const c = costOf(row); + if ( + chosen.length >= limits.rows || + count + c.events > spare.events || + bytes + c.bytes > spare.bytes + ) + break; + chosen.push(row); + count += c.events; + bytes += c.bytes; + } + const ids = chosen.map((row) => row.id); + const inWindow = new Set(window); + const at = new Map(ids.map((id, index) => [id, index])); + // A reply nests under its signed parent when that parent is shown above it. + const parents: Record = {}; + for (const row of chosen) { + const parent = row.replyParentId; + const above = parent === undefined ? undefined : at.get(parent); + if (parent && above !== undefined && above < (at.get(row.id) ?? 0)) + parents[row.id] = parent; + } + const open = [...new Set(Object.values(parents))]; + const complete = scanned && !lost && chosen.length === folded.length; + total = queue.length; + taken = chosen.filter((row) => inWindow.has(row)).length; + const result = present({ + ids, + events: all, + parents, + open, + complete, + ...(place ? { place } : {}), + }); + if (result === "limit" && size > SMALLEST) { + // Over a bound it could not see: show half as many. + size = Math.max(SMALLEST, Math.floor(chosen.length / 2)); + return arrange(place); + } + if (result === "retired") return stop(); + if (result === "invalid" || result === "limit") { + phase = { + state: "failed", + sort, + message: `Cannot show rows (${result})`, + }; + } else { + shown = ids.length; + } + emit(); + } + + function schedule() { + if (queued) return; + queued = true; + queueMicrotask(() => { + queued = false; + arrange(); + }); + } + + function fail(error: unknown, next: Sort) { + phase = { + state: "failed", + sort: next, + message: error instanceof Error ? error.message : String(error), + }; + emit(); + } + + /** After a reconnect: forget what was read and read it again, keeping the + * window. The reader keeps showing (and updating) the rows it was given until + * the new read presents. */ + function rescan() { + repair = undefined; + lost = false; + events.clear(); + scanned = false; + forward = undefined; + try { + hold?.set([]); + } catch { + // An empty hold always fits. + } + if (sort) refresh(); + else emit(); + } + /** The one way a lost read is read again: while connected and visible + * (most open panes are not), after a random wait. A failed read stays + * failed until the person picks a sort again. */ + function scheduleRescan() { + clearTimeout(repair); + repair = undefined; + if (lost && connected && document.visibilityState !== "hidden") + repair = setTimeout(rescan, Math.random() * JITTER_MS); + } + function onConnection() { + const now = props.session.live.snapshot().status === "connected"; + if (now === connected) return; + connected = now; + if (!now && events.size && !lost) { + lost = true; + emit(); + } + scheduleRescan(); + } + + function onLive({ events: heard }: { events: readonly RelayEvent[] }) { + // Nothing read, nothing to keep: a scan reads what arrives meanwhile. + if (!sort && !events.size) return; + const root = rootId(); + // A new reply to this thread, or any new message of this channel (the fold + // keeps only its top level); then the aux of what it holds, two hops (a + // reaction, then its deletion), so one batch can carry a row and its aux. + let added = 0; + for (const event of heard) + if ( + event.kind === 9 && + !events.has(event.id) && + event.tags.some(([name, id]) => + root + ? name === "e" && id === root + : name === "h" && id === props.channelId, + ) + ) { + events.set(event.id, event); + added++; + } + for (let hop = 0; hop < 2; hop++) + for (const event of heard) + if ( + AUX.has(event.kind) && + !events.has(event.id) && + auxTargets(event).some((id) => events.has(id)) + ) { + events.set(event.id, event); + added++; + } + if (!added) return; + try { + holdAll(); + } catch (error) { + if (sort) fail(error, sort); + return; + } + schedule(); + } + + function stop() { + if (phase.state === "scanning") phase.abort.abort(); + phase = { state: "idle" }; + sort = undefined; + filter = ""; + starts = [0]; + shown = 0; + emit(); + } + + /** Reads what the view needs, then presents it: one flow for every change of + * sort, filter and window. A newer change aborts the one still reading. */ + function refresh(place?: ConversationPresentation["place"]) { + if (!sort) return; + const current = sort; + if (phase.state === "scanning") phase.abort.abort(); + if (enough()) { + phase = { state: "ready", sort: current }; + return arrange(place); + } + const abort = new AbortController(); + phase = { state: "scanning", sort: current, abort }; + emit(); + void load(abort.signal).then( + () => { + if (abort.signal.aborted) return; + phase = { state: "ready", sort: current }; + arrange(place); + }, + (error) => { + if (!abort.signal.aborted) fail(error, current); + }, + ); + } + + const api = { + /** Starts, or restarts, a sort from its first window. */ + start(next: Sort) { + sort = next; + size = PAGE; + starts = [0]; + message = ""; + refresh(props.targetId ? { id: props.targetId } : "start"); + }, + /** Filters the rows, case-insensitively, from the first window of the current sort. */ + find(text: string) { + filter = text.trim(); + sort ??= "oldest"; + size = PAGE; + starts = [0]; + message = ""; + refresh(props.targetId ? { id: props.targetId } : "start"); + }, + /** Grows the window, reading further forward when the rows are not there yet. */ + more() { + if (phase.state !== "ready") return; + size = Math.min(size + MORE, props.limits?.rows ?? size + MORE); + refresh(); + }, + /** Moves the window to the rows after it, or back to the ones before. */ + page(step: 1 | -1) { + if (phase.state !== "ready") return; + if (step === 1) starts.push(offset() + taken); + else if (starts.length > 1) starts.pop(); + refresh("start"); + }, + withdraw() { + props.present?.(null); + stop(); + }, + /** Live growth passed the reader's limits: it ended this presentation. */ + ended() { + if (phase.state !== "ready") return; + size = Math.max(SMALLEST, Math.floor(shown / 2)); + message = "Showing fewer rows: the reader reached its limit."; + arrange(); + }, + update(next: ComposerAccessoryProps) { + props = next; + }, + attach() { + const session = props.session; + stops = [ + session.subscribeLive(onLive), + session.live.subscribe(onConnection), + session.outbox?.subscribe(schedule) ?? (() => {}), + () => document.removeEventListener("visibilitychange", scheduleRescan), + ]; + document.addEventListener("visibilitychange", scheduleRescan); + connected = session.live.snapshot().status === "connected"; + scheduleRescan(); + if (events.size) { + try { + holdAll(); + } catch { + // The scan is kept; it is held again on its next read. + } + } + }, + dispose() { + for (const stopListening of stops.splice(0)) stopListening(); + if (phase.state === "scanning") phase.abort.abort(); + clearTimeout(repair); + repair = undefined; + hold?.dispose(); + hold = undefined; + }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + snapshot(): View { + const more = !!sort && scanned === false && forward !== null; + const next = offset() + taken < total || more; + cached ??= Object.freeze({ + phase: phase.state, + sort, + read: countRows(), + shown, + from: offset(), + to: offset() + taken, + total, + exact: scanned && !lost, + more: next && size < (props.limits?.rows ?? size), + next, + previous: starts.length > 1, + filter, + message: phase.state === "failed" ? phase.message : message, + }); + return cached; + }, + }; + return api; +} + +export function apply(ctx: Context) { + const React = ctx.react; + const h = React.createElement; + + function Bar(props: ComposerAccessoryProps) { + const arranger = React.useMemo( + () => createArranger(props), + // A new conversation is a new scan. + [props.session, props.channelId, props.threadRootId], + ); + React.useLayoutEffect(() => arranger.update(props)); + React.useEffect(() => { + arranger.attach(); + return () => arranger.dispose(); + }, [arranger]); + const view = React.useSyncExternalStore( + arranger.subscribe, + arranger.snapshot, + arranger.snapshot, + ); + React.useEffect(() => { + if (props.presentation === "ended") arranger.ended(); + }, [arranger, props.presentation]); + const noun = props.threadRootId !== undefined ? "replies" : "messages"; + const [draft, setDraft] = React.useState(""); + React.useEffect(() => setDraft(view.filter), [view.filter]); + const button = (label: string, run: () => void, pressed?: boolean) => + h( + "button", + { + type: "button", + onClick: run, + ...(pressed === undefined ? {} : { "aria-pressed": pressed }), + }, + label, + ); + const count = new Intl.NumberFormat("en-US").format; + const where = view.total + ? `${noun[0]?.toUpperCase()}${noun.slice(1)} ${count(view.from + 1)}–${count(view.to)} of ${count(view.total)}${view.exact ? "" : "+"}` + : `No ${noun}${view.filter ? " match" : ""}`; + const ready = view.phase === "ready"; + return h( + "div", + { role: "toolbar", "aria-label": "Arrange rows" }, + button("Oldest", () => arranger.start("oldest"), view.sort === "oldest"), + button("Top", () => arranger.start("top"), view.sort === "top"), + h( + "form", + { + role: "search", + onSubmit: (event: { preventDefault(): void }) => { + event.preventDefault(); + arranger.find(draft); + }, + }, + h("input", { + type: "search", + "aria-label": `Filter ${noun}`, + value: draft, + onChange: (event: { target: { value: string } }) => + setDraft(event.target.value), + }), + ), + ready && view.previous + ? button("Previous", () => arranger.page(-1)) + : null, + ready && view.next ? button("Next", () => arranger.page(1)) : null, + ready && view.more ? button("More", () => arranger.more()) : null, + view.phase === "failed" && view.sort + ? button("Retry", () => arranger.start(view.sort as Sort)) + : null, + view.sort ? button("Buzz order", () => arranger.withdraw()) : null, + h( + "span", + { role: "status" }, + view.phase === "scanning" + ? `Reading… ${view.read} rows` + : view.phase === "failed" + ? `Scan failed: ${view.message}` + : view.sort + ? `${where}${props.presentation === "held" ? " (waiting)" : ""} ${view.message}`.trim() + : "", + ), + ); + } + + ctx.conversation.registerAccessory({ + id: "arranger", + title: "Arranger", + placement: "reader", + component: Bar, + }); +} diff --git a/tests/fixtures/conversation-arranger/relay.ts b/tests/fixtures/conversation-arranger/relay.ts new file mode 100644 index 0000000000..7510b8176a --- /dev/null +++ b/tests/fixtures/conversation-arranger/relay.ts @@ -0,0 +1,374 @@ +import { getEventHash, type Event } from "nostr-tools"; +import type { + EventData, + ReadFilter, + RelayEvent, +} from "../../../src/features/relay/events"; +import { createEventVerifier } from "../../../src/features/relay/events"; +import { + newReadJournal, + readJournal, + type ReadJournal, +} from "../../../src/features/relay/read-state-storage"; +import { createRelaySession } from "../../../src/features/relay/session"; +import type { + LiveCallbacks, + LiveSnapshot, +} from "../../../src/features/relay/live"; +import type { ReadTransport } from "../../../src/features/relay/transport"; +import { threadReference } from "../../../src/features/relay/thread-reference"; +import { + relayOrder, + threadBinding, +} from "../../../src/features/relay/thread-window"; +import { + keypair, + roster, + metadata, + signed, + type Key, +} from "../../../src/features/relay/testing"; + +// Test-only relay for the arranger plugin. It answers the reads a plugin makes +// through `snapshotRead`: root lookups, thread windows (`older` and `newer`, +// with `root_aux`) and top-level channel windows, each with the signed bounds +// event the reader verifies. Fixture events are minted with real ids but a +// zeroed signature, and proven by a verifier whose signature check is stubbed: +// signature checking is the transport's, covered by `event-proof.test.ts`, and +// real signing of 5,000+ events would only slow this test. + +export const CHANNEL = "5b0c8a4e-6c2e-4a3b-9d1f-0a1b2c3d4e5f"; +export const ORIGIN = "https://relay.example"; +/** Fixture clock: every created_at is relative to this. */ +export const T = 1_700_000_000; +export const REACTION = 7; +export const EDIT = 40003; +export const DELETION = 5; + +/** An event with its real id and an unchecked signature. */ +export function mint( + key: Key, + template: { + kind: number; + content: string; + created_at: number; + tags: string[][]; + }, +): Event { + const fields = { ...template, pubkey: key.pubkey }; + return { ...fields, id: getEventHash(fields), sig: "0".repeat(128) }; +} + +const prover = createEventVerifier(1 << 16, async (claims) => + claims.map(() => true), +); +/** Gives events the proof a verified read gives them. */ +export async function prove(events: readonly Event[]): Promise { + const native = prover.native; + if (!native) throw new Error("no native verifier"); + const settled = await native.settle(events.map((e) => native.prepare(e))); + return settled.map((event) => { + if (!event) throw new Error("fixture event refused"); + return event; + }); +} + +/** A seeded generator, so a fixture is the same every run. */ +export function seeded(seed: number) { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} +export function shuffled(items: readonly T[], random: () => number): T[] { + const out = [...items]; + for (let i = out.length - 1; i > 0; i--) { + const j = Math.floor(random() * (i + 1)); + [out[i], out[j]] = [out[j] as T, out[i] as T]; + } + return out; +} + +export type ReadRecord = { + filters: readonly ReadFilter[]; + priority: string | undefined; +}; + +const auxKinds = new Set([REACTION, EDIT, DELETION]); +const targetsOf = (event: EventData) => + event.tags.flatMap(([name, id]) => (name === "e" && id ? [id] : [])); +/** A page's rows in the relay's `newer` order: created_at ascending, id descending. */ +const ascending = (a: EventData, b: EventData) => relayOrder(a, b); + +/** The world a relay serves: proven events, indexed. */ +export function createWorld(events: readonly RelayEvent[] = []) { + const byId = new Map(); + const aux = new Map(); + const replies = new Map(); + const top: RelayEvent[] = []; + const sorted = new Map(); + const world = { + add(more: readonly RelayEvent[]) { + for (const event of more) { + if (byId.has(event.id)) continue; + byId.set(event.id, event); + if (auxKinds.has(event.kind)) + for (const id of targetsOf(event)) + aux.set(id, [...(aux.get(id) ?? []), event]); + else if (event.kind === 9) { + const root = threadReference(event)?.rootId; + if (root) replies.set(root, [...(replies.get(root) ?? []), event]); + else top.push(event); + } + } + sorted.clear(); + }, + byId, + /** Rows of a thread (`root`) or the top level, by `ascending`. */ + rows(root?: string) { + const key = root ?? ""; + let list = sorted.get(key); + if (!list) { + list = [...(root ? (replies.get(root) ?? []) : top)].sort(ascending); + sorted.set(key, list); + } + return list; + }, + /** Aux reaching `ids` in one hop, then aux reaching those (a deletion of a reaction). */ + closure(ids: readonly string[]) { + const first = ids.flatMap((id) => aux.get(id) ?? []); + const second = first.flatMap((event) => aux.get(event.id) ?? []); + return [...new Map([...first, ...second].map((e) => [e.id, e])).values()]; + }, + auxOf: (ids: readonly string[]) => ids.flatMap((id) => aux.get(id) ?? []), + }; + world.add(events); + return world; +} +export type World = ReturnType; + +/** The rows after `cursor` in the filter's own direction. */ +function after( + rows: readonly RelayEvent[], + filter: ReadFilter, +): readonly RelayEvent[] { + if (filter.direction === "newer") { + const at = filter.after; + return at === undefined + ? rows + : rows.filter( + (e) => + e.created_at > at || + (e.created_at === at && e.id < (filter.after_id ?? "")), + ); + } + const until = filter.until; + const newestFirst = [...rows].reverse(); + return until === undefined + ? newestFirst + : newestFirst.filter( + (e) => + e.created_at < until || + (e.created_at === until && e.id > (filter.before_id ?? "")), + ); +} + +/** A relay-signed bounds event, proven. */ +async function bound( + relay: Key, + kind: 39006 | 39007, + tags: string[][], + body: Record, +) { + const [event] = await prove([ + mint(relay, { + kind, + content: JSON.stringify(body), + created_at: T, + tags, + }), + ]); + return event as RelayEvent; +} + +export function createRelay(options: { + world: World; + viewer: Key; + relay: Key; + /** Reads held back until released, for ordering tests. */ + hold?: (filters: readonly ReadFilter[]) => Promise | undefined; +}) { + const { world, viewer, relay } = options; + const reads: ReadRecord[] = []; + const members = roster(relay, CHANNEL, [viewer.pubkey], 1); + const channelMeta = metadata(relay, CHANNEL, "Arranger fixture", 1); + async function answer(filter: ReadFilter): Promise { + if (filter.ids) return filter.ids.flatMap((id) => world.byId.get(id) ?? []); + if (filter.kinds?.includes(39002) || filter.kinds?.includes(39000)) + return [members, channelMeta]; + const page = Math.min(filter.limit, 500); + const [roots] = filter["#e"] ?? []; + if (filter.thread_window && roots) { + const rows = after(world.rows(roots), filter).slice(0, page + 1); + const shown = rows.slice(0, page); + const more = rows.length > shown.length; + const last = shown.at(-1); + const newer = filter.direction === "newer"; + const binding = await threadBinding(filter, ORIGIN, viewer.pubkey); + return [ + ...shown, + ...(filter.include_aux + ? [ + ...world.closure(shown.map((e) => e.id)), + ...(filter.root_aux === false ? [] : world.auxOf([roots])), + ] + : []), + await bound( + relay, + 39007, + [ + ["d", binding], + ["h", CHANNEL], + ["e", roots], + ], + { + version: 1, + direction: newer ? "newer" : "older", + has_more: more, + next_cursor: + more && last + ? { created_at: last.created_at, id: last.id } + : null, + }, + ), + ]; + } + if (filter.top_level) { + const rows = after(world.rows(), filter).slice(0, page + 1); + const shown = rows.slice(0, page); + const more = rows.length > shown.length; + const last = shown.at(-1); + const newer = filter.direction === "newer"; + const lane = newer ? "newer:" : ""; + const cursor = newer + ? filter.after === undefined + ? "head" + : `${filter.after}:${filter.after_id}` + : filter.until === undefined + ? "head" + : `${filter.until}:${filter.before_id}`; + return [ + ...shown, + ...(filter.include_aux ? world.closure(shown.map((e) => e.id)) : []), + await bound( + relay, + 39006, + [ + ["h", CHANNEL], + ["d", `${CHANNEL}:${lane}${cursor}`], + ], + { + has_more: more, + next_cursor: + more && last + ? { created_at: last.created_at, id: last.id } + : null, + ...(newer ? { direction: "newer" } : {}), + }, + ), + ]; + } + // A repair read: aux that name these rows since a time. + if (filter["#e"]) + return world + .auxOf(filter["#e"]) + .filter((e) => e.created_at >= (filter.since ?? 0)) + .slice(0, page); + return []; + } + const transport: ReadTransport = { + viewer: viewer.pubkey, + relayAuthor: relay.pubkey, + scope: ORIGIN, + media: () => undefined, + async query(filters, signal, _id, priority) { + reads.push({ filters, priority }); + await options.hold?.(filters); + if (signal?.aborted) throw new DOMException("Aborted", "AbortError"); + return (await Promise.all(filters.map(answer))).flat(); + }, + }; + return { transport, reads, members, channelMeta }; +} + +/** A session on a fixture relay, with a writer whose publication the test releases. */ +export function openSession(options: { + world: World; + windowNewer?: boolean; + viewer?: Key; + relay?: Key; + hold?: (filters: readonly ReadFilter[]) => Promise | undefined; +}) { + const viewer = options.viewer ?? keypair(); + const relay = options.relay ?? keypair(); + const fixture = createRelay({ ...options, viewer, relay }); + let traffic!: LiveCallbacks; + let journal: ReadJournal = newReadJournal(); + const publications: { + event: RelayEvent; + accept(): void; + reject(error: unknown): void; + }[] = []; + const owner = createRelaySession( + { + ...fixture.transport, + ...(options.windowNewer === false ? {} : { windowNewer: true as const }), + writer: { + sign: async (template) => signed(viewer, template), + publish: (event) => + new Promise((accept, reject) => + publications.push({ event, accept, reject }), + ), + }, + subscribe(callbacks) { + traffic = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { + outboxStorage: { load: () => [], save() {} }, + readStateStorage: { + capture: async () => structuredClone(journal), + async update(change) { + journal = readJournal(change(journal), viewer.pubkey); + return journal; + }, + close() {}, + }, + }, + ); + owner.session.channels.ensure(CHANNEL); + traffic.receive([fixture.members, fixture.channelMeta]); + const live = { phase: "live" as const, channelId: CHANNEL }; + return { + ...fixture, + owner, + session: owner.session, + viewer, + relay, + publications, + /** Hears an event as the live stream delivers it. */ + hear(...events: readonly RelayEvent[]) { + traffic.receive(events, live); + }, + /** Reports the live connection's status, as the transport does when it + * drops and when it connects again. */ + connection(status: LiveSnapshot["status"]) { + traffic.state({ status, routes: [] }); + }, + }; +}