From 508c35f7b80cd61c0b23abc1e329448af667ee89 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Tue, 17 Nov 2026 19:12:38 -0500
Subject: [PATCH 01/37] 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 | 39 +-
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 | 220 +++-
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 | 138 ++-
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 | 94 +-
.../relay/traffic.integration.test.ts | 81 ++
src/features/relay/transport.ts | 5 +
src/features/relay/unread.test.ts | 41 +
src/features/relay/unread.ts | 39 +-
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, 7828 insertions(+), 190 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 babf77f4c6..2aec0463e3 100644
--- a/browser-host/relay-broker.mjs
+++ b/browser-host/relay-broker.mjs
@@ -361,6 +361,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 99e2ac83db..77a64811bb 100644
--- a/docs/buzz-help.md
+++ b/docs/buzz-help.md
@@ -1145,6 +1145,14 @@ Quitting Buzz also turns it off.
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 c9bf100300..108b61f017 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -1759,6 +1759,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 9c9af75d14..bf0595e36d 100644
--- a/src/features/agents/agent-config-artifacts.ts
+++ b/src/features/agents/agent-config-artifacts.ts
@@ -6,6 +6,7 @@ import { notesOf, noteTags } from "./plugin-notes";
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 =
@@ -223,7 +224,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 05b4711b40..636a3833ec 100644
--- a/src/features/conversation/ComposerAccessories.tsx
+++ b/src/features/conversation/ComposerAccessories.tsx
@@ -7,6 +7,7 @@ import {
useSyncExternalStore,
} from "react";
import type { Contribution } from "../../plugins/contributions";
+import type { Arrangement } from "../messages/arrangement";
import type {
ComposerAccessory,
ComposerAccessoryProps,
@@ -14,13 +15,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,
@@ -58,6 +63,7 @@ export function ComposerAccessories({
;
registry: ContributionReader;
+ arrangement: Arrangement | undefined;
}) {
const current = useRef(props);
useLayoutEffect(() => {
@@ -83,8 +91,22 @@ const OwnedAccessory = memo(function OwnedAccessory({
const canOpenThread = !!props.openThread;
const [commands, setCommands] =
useState<
- Pick
+ Pick<
+ ComposerAccessoryProps,
+ "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;
@@ -100,11 +122,15 @@ const OwnedAccessory = memo(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]);
// Availability is read during render, so it follows this render's host;
// dispatch goes through the committed one. Both end when this mount retires.
const retired = useRef(false);
@@ -124,7 +150,14 @@ const OwnedAccessory = memo(function OwnedAccessory({
);
const Accessory = entry.component;
return commands ? (
-
+
) : (
(props.renderMessageSummary?.() ?? null)
);
diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts
index 91bfd95caa..50f7679bd0 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";
import type { OutgoingMessage } from "../messages/outgoing-message";
@@ -197,6 +198,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;
@@ -224,6 +258,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.
@@ -233,8 +279,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 1bc6eb33f0..4c8c8e5b00 100644
--- a/src/features/conversation/service.test.tsx
+++ b/src/features/conversation/service.test.tsx
@@ -566,6 +566,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 b74eddcc4e..04ba640906 100644
--- a/src/features/conversation/service.tsx
+++ b/src/features/conversation/service.tsx
@@ -437,7 +437,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 7d23144ed5..5c16e2021d 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 eb266118dd..5e005875c6 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 f856be53a5..b39c3bf09e 100644
--- a/src/features/messages/ChannelTimeline.tsx
+++ b/src/features/messages/ChannelTimeline.tsx
@@ -21,7 +21,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 {
@@ -155,6 +158,18 @@ 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;
+const topLevel = (row: ChannelMessage) =>
+ readable(row) && !row.threadRootId && !row.replyParentId;
+/** The newest row by time, wherever a presentation draws it. */
+const newest = (rows: readonly ChannelMessage[]) =>
+ rows.reduce(
+ (latest, row) =>
+ !latest || row.createdAt > latest.createdAt ? row : latest,
+ undefined,
+ );
// Older pages a visit reads unasked to fill a screen its head leaves empty.
const FILL_PAGES = 5;
// A row's content sits below its day divider and byline, and its virtual item
@@ -296,8 +311,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
@@ -325,7 +360,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]);
@@ -334,7 +370,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,
@@ -366,6 +405,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(() => ({}));
@@ -756,6 +800,7 @@ function Timeline({
});
}
const newMessageBoundaryId =
+ !arranged &&
boundaryMatchesVisit &&
newMessageBoundary.captured &&
messageVisit?.active === true &&
@@ -783,7 +828,7 @@ function Timeline({
});
}, []);
const presentation = useActivityPresentation(
- chronologicalRows,
+ arranged ? NO_ROWS : chronologicalRows,
queries.agentActivity,
agentPubkeys,
);
@@ -818,12 +863,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.
@@ -900,7 +954,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 ||
@@ -918,6 +972,7 @@ function Timeline({
: [],
);
const scroller = useRef(null);
+ const readerBar = useRef(null);
const edge = useRef(null);
const activityTail = useRef(null);
useLayoutEffect(() => {
@@ -938,7 +993,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);
@@ -964,12 +1019,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<{
@@ -1247,7 +1305,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;
@@ -1289,7 +1347,7 @@ function Timeline({
navigation,
returning,
rows,
- visibleRows,
+ shownRows,
containedOwners,
activity,
focusesTarget,
@@ -1321,20 +1379,21 @@ function Timeline({
scroller,
settled,
restoring,
- latestMessageId: window.rows
- .filter((row) => !row.membership && !row.huddle)
- .at(-1)?.id,
+ latestMessageId: (display
+ ? newest(display.rows.filter(readable))
+ : window.rows.filter(readable).at(-1)
+ )?.id,
// The channel's read mark stops at its newest top-level post: an "Also
// send to channel" reply at the bottom is not one.
- catchUpMessageId: window.rows
- .filter(
- (row) =>
- !row.membership &&
- !row.huddle &&
- !row.threadRootId &&
- !row.replyParentId,
- )
- .at(-1)?.id,
+ catchUpMessageId: (display
+ ? newest(display.rows.filter(topLevel))
+ : window.rows.filter(topLevel).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.
@@ -1350,6 +1409,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
@@ -1384,6 +1487,7 @@ function Timeline({
inset: readerRow && contentInset(readerRow),
};
const prepend =
+ !swapped &&
!!previous.length &&
(previous[0] !== rows[0]?.id || rows.length !== previous.length) &&
reading.every(
@@ -1724,9 +1828,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)
@@ -1772,7 +1880,7 @@ function Timeline({
const restoreIndex = anchor
? renderedRowIndex(
rows,
- visibleRows,
+ shownRows,
containedOwners.get(anchor.id) ?? anchor.id,
)
: -1;
@@ -1929,7 +2037,7 @@ function Timeline({
};
}, [
rows,
- visibleRows,
+ shownRows,
size,
prepend,
recordPosition,
@@ -1941,6 +2049,8 @@ function Timeline({
latestRequest,
containedOwners,
newMessageBoundaryId,
+ swapped,
+ owner,
]);
// After positioning reads it: a load that ends without rows lands no page.
useLayoutEffect(() => {
@@ -1950,6 +2060,7 @@ function Timeline({
(element: HTMLElement, resume = false) => {
olderDemand.current = false;
if (
+ arranged ||
!handle.current ||
!userScrolled.current ||
window.status !== "ready" ||
@@ -1977,7 +2088,7 @@ function Timeline({
!after.historyLimited &&
!after.error;
},
- [window, queries, channelId],
+ [window, queries, channelId, arranged],
);
useLayoutEffect(() => {
if (olderDemand.current && scroller.current)
@@ -1993,6 +2104,7 @@ function Timeline({
const element = scroller.current;
if (
!element ||
+ arranged ||
!settled.current ||
!follow.current ||
pendingRestore.current === intent.current ||
@@ -2022,6 +2134,7 @@ function Timeline({
targetId,
targetSignal,
revealedSignal,
+ arranged,
]);
// After positioning's frame, and again once Virtua measures estimated rows.
const scheduleFill = useCallback(() => {
@@ -2044,6 +2157,7 @@ function Timeline({
};
}, [scheduleFill, size]);
const gesture = (upward = false) => {
+ placement.cancel();
const restoring = pendingRestore.current === intent.current;
restoredAnchor.current = undefined;
layoutCorrection.current = false;
@@ -2082,7 +2196,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;
@@ -2182,7 +2296,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.
@@ -2208,7 +2322,7 @@ function Timeline({
) : null}
@@ -2257,10 +2371,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 toggleDisclosure = () => {
if (!disclosure) return;
intent.current++;
@@ -2293,18 +2407,21 @@ function Timeline({
)}
stackPrevious={
inside ||
- (!!previousRow &&
+ (!arranged &&
+ !!previousRow &&
!foldedActivity.has(previousRow.id) &&
continuesMessageGroup(previousRow, row))
}
stackNext={
inside ||
presentation.bubbleAnchors.has(row.id) ||
- (row.id === lastPublicMessage?.id &&
+ (!arranged &&
+ row.id === lastPublicMessage?.id &&
row.audience !== "agents" &&
!row.membership &&
row.authorId === liveAgents[0]) ||
- (!!nextRow &&
+ (!arranged &&
+ !!nextRow &&
!foldedActivity.has(nextRow.id) &&
continuesMessageGroup(row, nextRow))
}
@@ -2420,7 +2537,8 @@ function Timeline({
})}
)}
- {!rows.length &&
+ {!arranged &&
+ !rows.length &&
!shownIntro &&
!window.hasMore &&
window.status === "ready" &&
@@ -2449,7 +2567,7 @@ function Timeline({
session={queries}
channelId={channelId}
previousAuthor={
- lastPublicMessage && !lastPublicMessage.membership
+ !arranged && lastPublicMessage && !lastPublicMessage.membership
? lastPublicMessage.authorId
: undefined
}
@@ -2460,5 +2578,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 65dffe4977..db3942da12 100644
--- a/src/features/messages/Messages.module.css
+++ b/src/features/messages/Messages.module.css
@@ -18,6 +18,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;
@@ -32,6 +34,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) => (
+
+ ),
+}));
+
+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}
+ onReply?.(row.id)}>
+ Reply to {row.content}
+
+
+ ),
+}));
+vi.mock("./MessageComposer", () => ({
+ MessageComposer: ({ replyParentId, replyContext }: MessageComposerProps) => (
+
+ ),
+}));
+
+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 281a15196b..f29ca50537 100644
--- a/src/features/messages/ThreadPanel.test.tsx
+++ b/src/features/messages/ThreadPanel.test.tsx
@@ -691,7 +691,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 f8cd2fbffb..efd8f8bedb 100644
--- a/src/features/messages/ThreadPanel.tsx
+++ b/src/features/messages/ThreadPanel.tsx
@@ -21,6 +21,8 @@ import { useMessageSelectionCopy } from "./selection-copy";
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";
@@ -44,6 +46,7 @@ import type { ChannelMessage } from "../relay/contracts";
import { compareMessages } from "../relay/message-order";
import type { RelaySession } from "../relay/session";
import {
+ THREAD_LIMITS,
threadFailure,
type ThreadRetarget,
type ThreadView,
@@ -245,6 +248,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 = {
@@ -680,13 +701,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);
@@ -694,7 +738,7 @@ function ThreadMessages({
}
}
return branches;
- }, [tree, snapshot.replies]);
+ }, [tree, shownReplies]);
const subscribeUnread = useCallback(
(listener: () => void) =>
session.unread.subscribe(
@@ -739,6 +783,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;
@@ -753,19 +815,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);
@@ -779,6 +846,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 positionedLatestRequest = useRef(undefined);
const shown = useRef(active);
@@ -1124,14 +1192,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);
@@ -1166,16 +1234,17 @@ function ThreadMessages({
) {
// Page to the frontier in one read, not one page per decision. Read
// per page: a read synced mid-load can move it.
- if (snapshot.canLoadMore)
+ if (snapshot.canLoadMore && !presented)
void view.loadMore(
() => since ?? session.unread.threadReadThrough(channelId, messageId),
);
- // Past the page limit the first unread reply stays unknown.
+ // 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
@@ -1194,7 +1263,8 @@ function ThreadMessages({
rootTarget,
snapshot,
messageId,
- tree,
+ hostTree,
+ presented,
session.unread,
channelId,
view,
@@ -1208,8 +1278,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:
@@ -1328,26 +1405,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" &&
@@ -1413,12 +1486,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;
@@ -1461,6 +1535,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 (
@@ -1726,6 +1804,7 @@ function ThreadMessages({
expanded,
expandedActivity,
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
@@ -1772,6 +1851,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.
@@ -1830,6 +1910,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;
@@ -1852,6 +1968,7 @@ function ThreadMessages({
}, 1000);
};
const keepReadingPosition = () => {
+ place.cancel();
jumpingToLatest.current = false;
remounted.current = undefined;
if (jumpTimer.current !== undefined) {
@@ -1881,14 +1998,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,
@@ -1915,6 +2033,7 @@ function ThreadMessages({
: publicMessageNeighbor(siblings, index, 1);
const children = tree.children.get(row.id);
const continuation =
+ !presented &&
!!previousReply &&
previousReply !== snapshot.root &&
previousParent === parent &&
@@ -1926,7 +2045,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;
@@ -1976,7 +2095,8 @@ function ThreadMessages({
inside ||
presentation.bubbleAnchors.has(row.id) ||
(joinsLive && row.id === lastMessage?.id) ||
- (!!nextRow &&
+ (!presented &&
+ !!nextRow &&
continuesMessageGroup(row, nextRow) &&
!children?.length)
}
@@ -2035,7 +2155,7 @@ function ThreadMessages({
className={styles.replyItem}
data-layout={continuation ? "continuation" : "thread"}
>
- {!parent && row.id === lineRow && (
+ {!presented && !parent && row.id === lineRow && (
@@ -2044,7 +2164,8 @@ function ThreadMessages({
)}
{/* Not while the root, or history that may hold the parent, loads. */}
- {!parent &&
+ {!presented &&
+ !parent &&
rootId &&
!snapshot.seeking &&
row.replyParentId &&
@@ -2138,7 +2259,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);
// The banner's one line about its target. `plainText` flattens CommonMark,
// replaces control characters and cuts the result at 200 characters; GFM
// that the row renders (strikethrough, tables, task-list boxes) still
@@ -2186,6 +2309,7 @@ function ThreadMessages({
const element = scroller.current;
if (
!element ||
+ presented ||
!olderDemand.current ||
snapshot.direction !== "older" ||
snapshot.status !== "ready" ||
@@ -2201,12 +2325,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 (
@@ -2246,14 +2371,36 @@ function ThreadMessages({
// For a full thread, use display order to break same-second ties.
latestMessageId={
snapshot.root && !subthreadId
- ? snapshot.replies.reduce(
+ ? shownReplies.reduce(
(latest, row) =>
!latest || compareMessages(row, latest) > 0 ? 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;
@@ -2336,7 +2483,7 @@ function ThreadMessages({
tabIndex={0}
>
@@ -2455,7 +2602,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 7e8b21f940..3587ea4797 100644
--- a/src/features/messages/use-reading.test.ts
+++ b/src/features/messages/use-reading.test.ts
@@ -28,10 +28,18 @@ function setup({
strict = false,
latestMessageId = undefined as string | undefined,
catchUpMessageId = undefined as string | undefined,
+ endMessageId = undefined as string | undefined,
+ partial = false,
rootId = undefined as string | undefined,
enabled = true,
concealed = false,
- 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);
@@ -54,8 +62,10 @@ function setup({
// The app's root, a direct body child as in production.
const root = document.createElement("div");
root.append(panel);
- document.body.append(root, 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(root, 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);
@@ -68,6 +78,7 @@ function setup({
row("clipped", 450, 550),
);
const scroller = { current: element };
+ const controls = { current: bar };
const position = { current: settled };
let mutation = () => {};
let attributes: (records: { target: Node }[]) => void = () => {};
@@ -101,17 +112,19 @@ function setup({
// The real lease fences on the manual-unread revision current at creation.
let manual = 0;
const leave = vi.fn();
- const reading = vi.fn((_channel: string, _root?: string, _visit?: object) => {
- const lease = {
- manual,
- view: vi.fn(),
- observe: vi.fn(() => observe()),
- catchUp: vi.fn(async () => {}),
- dispose: vi.fn(),
- };
- leases.push(lease);
- return lease;
- });
+ const reading = vi.fn(
+ (_channel: string, _root?: string, _visit?: object, _partial?: boolean) => {
+ const lease = {
+ manual,
+ view: vi.fn(),
+ observe: vi.fn(() => observe()),
+ catchUp: vi.fn(async () => {}),
+ dispose: vi.fn(),
+ };
+ leases.push(lease);
+ return lease;
+ },
+ );
const session = {
unread: {
sync: () => ({ capability: supported ? "frontier-sync" : "unsupported" }),
@@ -128,6 +141,9 @@ function setup({
settled: position,
latestMessageId,
catchUpMessageId,
+ endMessageId,
+ partial,
+ controls,
rootId,
enabled,
},
@@ -150,6 +166,7 @@ function setup({
composer,
parent,
outside,
+ bar,
session,
reading,
leases,
@@ -203,6 +220,9 @@ function setup({
settled: position,
latestMessageId,
catchUpMessageId,
+ endMessageId,
+ partial,
+ controls,
rootId,
enabled,
}),
@@ -214,6 +234,23 @@ function setup({
settled: position,
latestMessageId: id,
catchUpMessageId,
+ endMessageId,
+ partial,
+ controls,
+ rootId,
+ enabled,
+ }),
+ setPartial: (next: boolean) =>
+ view.rerender({
+ session,
+ channelId: "room",
+ scroller,
+ settled: position,
+ latestMessageId,
+ catchUpMessageId,
+ endMessageId,
+ partial: next,
+ controls,
rootId,
enabled,
}),
@@ -232,7 +269,12 @@ 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);
@@ -612,10 +654,14 @@ 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, _rootId?: string, _visit?: object) =>
- h.reading("next-room"),
+ (
+ _channelId: string,
+ _rootId?: string,
+ _visit?: object,
+ _partial?: boolean,
+ ) => h.reading("next-room"),
);
h.retarget("next-room", {
...h.session,
@@ -626,6 +672,7 @@ it("releases the old channel and session on rerender and only observes the curre
"next-room",
undefined,
{},
+ false,
);
vi.advanceTimersByTime(299);
for (const lease of h.leases) expect(lease.observe).not.toHaveBeenCalled();
@@ -673,7 +720,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 broadcast reply as the bottom row earns dwell but catches up through the top-level post", async () => {
const h = setup({ latestMessageId: "broadcast", catchUpMessageId: "top" });
@@ -754,6 +801,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]?.[3]).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 9c6d23288e..33be3d7730 100644
--- a/src/features/messages/use-reading.ts
+++ b/src/features/messages/use-reading.ts
@@ -36,6 +36,16 @@ type Reading = {
/** The newest row catch-up may read through, when it is not the bottom
* row (a channel's newest top-level post). Defaults to the bottom row. */
catchUpMessageId?: 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;
@@ -63,6 +73,9 @@ export function useReading({
channelId,
latestMessageId,
catchUpMessageId,
+ endMessageId,
+ partial = false,
+ controls,
rootId,
scroller,
settled,
@@ -74,6 +87,7 @@ export function useReading({
// already remeasures in the next frame, so it must not restart observation.
const latestId = useEffectEvent(() => latestMessageId);
const catchUpId = useEffectEvent(() => catchUpMessageId ?? latestMessageId);
+ const endId = useEffectEvent(() => endMessageId ?? latestMessageId);
useEffect(() => {
if (!enabled || !scroller.current) return;
const element: HTMLElement = scroller.current;
@@ -141,7 +155,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 &&
@@ -209,6 +224,7 @@ export function useReading({
};
function bottomId() {
const latest = latestId();
+ const end = endId();
if (
!latest ||
element.scrollHeight - element.clientHeight - element.scrollTop > 1
@@ -223,7 +239,7 @@ export function useReading({
),
].find(
(row) =>
- (row.dataset.messageId ?? row.dataset.previewMessageId) === latest,
+ (row.dataset.messageId ?? row.dataset.previewMessageId) === end,
);
const bounds = row?.getBoundingClientRect();
return bounds &&
@@ -270,7 +286,7 @@ export function useReading({
}
function acquire() {
try {
- const lease = session.unread.reading(channelId, rootId, visit);
+ const lease = session.unread.reading(channelId, rootId, visit, partial);
visited = true;
return lease;
} catch {
@@ -332,7 +348,7 @@ export function useReading({
// A view-only lease keeps that evidence until the next cancellation.
observed.view([], () => false, false);
try {
- handle = session.unread.reading(channelId, rootId, visit);
+ handle = session.unread.reading(channelId, rootId, visit, partial);
handle.view([...visible], viewing);
showing = !!visible.size;
} catch {
@@ -440,6 +456,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 daee9eb70d..56107d1310 100644
--- a/src/features/relay/native.ts
+++ b/src/features/relay/native.ts
@@ -508,6 +508,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;
@@ -1070,6 +1073,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 a4d6a94b89..1ea1e675a5 100644
--- a/src/features/relay/session.ts
+++ b/src/features/relay/session.ts
@@ -90,6 +90,7 @@ import { objectBody } from "./body";
import { agentAudience } from "./audience";
import type {
ChannelList,
+ ChannelMessage,
ChannelReadOptions,
ChannelSummary,
} from "./contracts";
@@ -123,6 +124,7 @@ import { attemptEnded } from "./withdraw";
import type { ReadTransport } from "./transport";
import type { LiveGlobal, LiveSnapshot, LiveSubscription } from "./live";
import {
+ hasEventProof,
hasTag,
type ReadFilter,
type RelayEvent,
@@ -146,9 +148,10 @@ import {
import { createMessages, replyInvocationIntents } from "./messages";
import { createOwnerMentionStore } from "./owner-mentions";
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 {
@@ -189,6 +192,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, or the general statuses read with them.
* The relay stores both per user, not per channel, so no channel access change,
* including a denied channel list, can stale it. */
@@ -352,6 +359,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. */
@@ -457,8 +467,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;
@@ -1421,6 +1437,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,
@@ -2794,13 +2811,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,
@@ -3408,6 +3427,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.
@@ -3498,6 +3520,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 20c066cd3b..d97d90aaa1 100644
--- a/src/features/relay/store.ts
+++ b/src/features/relay/store.ts
@@ -236,6 +236,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;
@@ -349,8 +356,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,
@@ -4279,8 +4286,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(
@@ -4319,6 +4328,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;
@@ -4327,6 +4364,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)
@@ -4769,7 +4807,7 @@ export function createChannelStore(
} else void fillNotices(retained, true);
retained.restored = false;
retained.readAt = head.readAt;
- accept(head.events);
+ accept(head.events, true);
page = head;
const reached = (last: Page) =>
!last.hasMore ||
@@ -4790,7 +4828,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 68f4fbd730..38ee277715 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 9356e84f90..d6847b5a18 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(
@@ -1976,3 +2167,219 @@ it("settles session recovery when a read view with a quiet failure passes its me
view.dispose();
}
});
+
+// 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 c6d173e298..cfda01970f 100644
--- a/src/features/relay/threads.test.ts
+++ b/src/features/relay/threads.test.ts
@@ -1159,8 +1159,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 322f968cb4..3c6e379914 100644
--- a/src/features/relay/threads.ts
+++ b/src/features/relay/threads.ts
@@ -4,6 +4,7 @@ import { readSubthread, subthreadMessages } from "./subthread";
import {
canonicalChannel,
MissingThreadBounds,
+ relayOrder,
threadBounds,
type ThreadCursor,
} from "./thread-window";
@@ -21,16 +22,49 @@ 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 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);
@@ -219,6 +253,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;
@@ -314,19 +350,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[])[]) {
@@ -523,6 +547,7 @@ export function createThreadView({
remote = [];
remoteIds.clear();
staged = [];
+ reach = undefined;
rootId = undefined;
cursor = undefined;
pages = 0;
@@ -547,13 +572,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))) {
+ 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();
advance();
}
@@ -619,6 +673,7 @@ export function createThreadView({
older = false;
failed = undefined;
staged = [];
+ reach = undefined;
shown = undefined;
if (exact) targetStatus = "loading";
if (clear || !canAccess()) {
@@ -1097,6 +1152,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;
@@ -1203,6 +1262,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 5a4a6f6c32..50d2f1cdb0 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 c36ee325bd..c2f12b058a 100644
--- a/src/features/relay/transport.ts
+++ b/src/features/relay/transport.ts
@@ -174,6 +174,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;
@@ -569,6 +572,7 @@ export async function connectBrokerTransport(
channelIdentity?: boolean;
soloMemberRoleUpdates?: boolean;
searchSort?: boolean;
+ windowNewer?: boolean;
artifactSync?: boolean;
sidebarPreferenceWrites?: boolean;
sidebarSectionRemoval?: boolean;
@@ -938,6 +942,7 @@ export async function connectBrokerTransport(
? { workspaceMigration: 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 d6ff825cc3..e8b1845586 100644
--- a/src/features/relay/unread.test.ts
+++ b/src/features/relay/unread.test.ts
@@ -7166,6 +7166,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, 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 writes only the channel frontier while the channel type is unknown", async () => {
const h = setup();
// The roster lists the channel before its metadata says it is a DM.
@@ -8986,3 +9002,28 @@ it("an advance's projected clear keeps a reminder another window marked again me
a.unread.dispose();
}
});
+
+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 400d9f7292..2e5e45b9d7 100644
--- a/src/features/relay/unread.ts
+++ b/src/features/relay/unread.ts
@@ -209,8 +209,16 @@ export interface UnreadCapability {
/** `rootId` names the thread a reader shows, which bounds its DM reads.
* `visit` is one reader's stay in this conversation, across its leases:
* a message marked unread while that visit shows it stays unread until
- * the visit measures it away or `leave`s. Without it, the lease is the visit. */
- reading(channelId: string, rootId?: string, visit?: object): ReadingHandle;
+ * the visit measures it away or `leave`s. Without it, the lease is the visit.
+ * 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,
+ visit?: object,
+ partial?: boolean,
+ ): ReadingHandle;
/** `visit` presents this thread in a pane, whether or not any row counts as
* shown: the thread marked unread during it stays marked through its
* catch-ups until `leave`. Presence reads nothing. */
@@ -420,6 +428,7 @@ export function createUnread({
signingAuthority,
workflowAuthority,
profiles,
+ evidence,
notify = (listener) => listener(),
follows = memoryThreadFollows(),
}: {
@@ -431,6 +440,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;
}) {
@@ -447,6 +459,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,
@@ -650,7 +664,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;
@@ -2911,7 +2925,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) ||
@@ -2937,7 +2951,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");
}
@@ -2967,7 +2981,7 @@ export function createUnread({
}
}
return [...ids].flatMap((id) => {
- const event = events.get(id);
+ const event = knownEvent(id);
return event ? [event] : [];
});
}
@@ -3179,7 +3193,7 @@ export function createUnread({
presenting.set(visit, targetKey({ kind: "thread", channelId, rootId }));
},
leave,
- reading(channelId, rootId, visit) {
+ reading(channelId, rootId, visit, partial = false) {
if (closed || !allowed(channelId) || handles.size >= 64)
throw new Error("Reading handle unavailable");
let active = true;
@@ -3216,12 +3230,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;
@@ -3276,7 +3291,7 @@ export function createUnread({
markedWhileShown.delete(id);
},
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 };
@@ -3535,7 +3550,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),
@@ -3574,7 +3589,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 3516c13545..2be2a03e91 100644
--- a/src/plugins/author.ts
+++ b/src/plugins/author.ts
@@ -106,6 +106,9 @@ export type {
ComposerReplacement,
ComposerAccessory,
ComposerAccessoryProps,
+ ConversationPresentation,
+ PresentationLimits,
+ PresentResult,
ComposerResource,
ComposerCaptureProps,
AttachmentRenderer,
@@ -124,6 +127,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: [] });
+ },
+ };
+}
From 696f31682a9b4b280710172405b84629e1afd2f5 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 02:00:40 -0500
Subject: [PATCH 02/37] refactor(messages): show one reader accessory at a
time, keeping nothing
The arrangement kept every waiting reader accessory's presentation and
promoted the next by order when the shown one left. It now shows the
first accessory to present and stores only whether each other one is
held or ended: a held accessory's presentation turns `none` when the
shown one leaves, and it presents again. The root's own reactions no
longer count against a thread reader's limits: they stay with the
header. The test fixture plugin presents again on `none`, and the
two late thread-window refresh tests share one setup.
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
---
docs/plugin-architecture.md | 9 +-
.../conversation/ComposerAccessories.test.tsx | 9 +-
src/features/conversation/contracts.ts | 9 +-
src/features/messages/arrangement.test.ts | 130 +++++++-----------
src/features/messages/arrangement.ts | 100 +++++---------
src/features/relay/thread-window.test.ts | 70 ++++------
.../fixtures/conversation-arranger/plugin.ts | 5 +
7 files changed, 131 insertions(+), 201 deletions(-)
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index 108b61f017..65088eaed0 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -1775,10 +1775,11 @@ present for reader accessories only.
(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`.
+- The result is `shown`, `held` (another accessory showed first; nothing is
+ kept, and `presentation` turns `none` when that one leaves, so present again),
+ `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.
diff --git a/src/features/conversation/ComposerAccessories.test.tsx b/src/features/conversation/ComposerAccessories.test.tsx
index 4e15d00da9..e628e94c94 100644
--- a/src/features/conversation/ComposerAccessories.test.tsx
+++ b/src/features/conversation/ComposerAccessories.test.tsx
@@ -349,7 +349,7 @@ it("withdraws a reader lane when its accessory unmounts", () => {
});
it.each([false, true])(
- "withdraws a throwing reader lane, revokes its present and promotes the next (StrictMode %s)",
+ "withdraws a throwing reader lane, revokes its present and frees the reader for the next (StrictMode %s)",
(reactStrictMode) => {
const error = vi.spyOn(console, "error").mockImplementation(() => {});
let bombPresent: ComposerAccessoryProps["present"];
@@ -381,10 +381,13 @@ it.each([false, true])(
expect(screen.getByText("spare:held")).toBeTruthy();
act(() => explode());
expect(screen.getByText("a unavailable")).toBeTruthy();
- expect(screen.getByText("spare:shown")).toBeTruthy();
+ expect(screen.getByText("spare:none")).toBeTruthy();
expect(reader.arrangement.status(bomb)).toBe("none");
expect(bombPresent?.(nothing)).toBe("retired");
- expect(reader.arrangement.status(spare)).toBe("shown");
+ act(() => {
+ expect(sparePresent?.(nothing)).toBe("shown");
+ });
+ expect(screen.getByText("spare:shown")).toBeTruthy();
error.mockRestore();
},
);
diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts
index 50f7679bd0..a51c5b4d88 100644
--- a/src/features/conversation/contracts.ts
+++ b/src/features/conversation/contracts.ts
@@ -226,10 +226,11 @@ export type ConversationPresentation = Readonly<{
/** 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. */
+/** `shown`: accepted (`null`, a withdrawal, answers `shown`). `held`: another
+ * accessory showed first; nothing is kept, so present again once `presentation`
+ * is `none`. `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;
diff --git a/src/features/messages/arrangement.test.ts b/src/features/messages/arrangement.test.ts
index eaa8446777..935e26b163 100644
--- a/src/features/messages/arrangement.test.ts
+++ b/src/features/messages/arrangement.test.ts
@@ -92,10 +92,7 @@ function host(
},
};
}
-const lane = (key: string, order?: number): ArrangementLane => ({
- key,
- order,
-});
+const lane = (key: string): ArrangementLane => ({ key });
const reaction = (author: Key, target: EventData, time: number) =>
proven(
signed(author, {
@@ -175,7 +172,8 @@ it("passes parents, open, complete and place through, nested to depth 4", () =>
string,
];
const { arrangement } = host({ rootId: root.id });
- arrangement.present(lane("one"), {
+ const one = lane("one");
+ arrangement.present(one, {
ids: [a, b, c, d, e],
events,
parents: { [b]: a, [c]: b, [d]: c, [e]: d },
@@ -193,7 +191,7 @@ it("passes parents, open, complete and place through, nested to depth 4", () =>
display?.parents?.get(id),
);
expect(tree.ancestors(e)).toEqual([d, c, b, a]);
- arrangement.present(lane("one"), { ids: [a, b], events });
+ arrangement.present(one, { ids: [a, b], events });
expect(arrangement.snapshot()).toMatchObject({
open: [],
complete: false,
@@ -201,7 +199,7 @@ it("passes parents, open, complete and place through, nested to depth 4", () =>
});
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: {} });
+ arrangement.present(one, { ids: [a, b], events, parents: {} });
expect(arrangement.snapshot()?.parents?.size).toBe(0);
});
@@ -271,6 +269,25 @@ it("refuses the 461st row of a thread, the reader's bound", () => {
);
});
+it("holds the root as the header without counting its reactions against the limits", () => {
+ const { root, replies, events } = thread(1);
+ const [a] = replies;
+ const { arrangement } = host({
+ rootId: root.id,
+ limits: { rows: 10, events: 2, bytes: 4 << 20 },
+ });
+ // A page read with the root's aux, as a relay without `root_aux` sends it.
+ const page = [
+ ...events,
+ reaction(other, root, 30),
+ reaction(other, root, 31),
+ ];
+ expect(arrangement.present(lane("a"), { ids: [a.id], events: page })).toBe(
+ "shown",
+ );
+ expect(ids(arrangement.snapshot()?.rows)).toEqual([a.id]);
+});
+
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;
@@ -415,10 +432,11 @@ it("keeps refolding live changes after a re-present that overtook a pending fram
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 one = lane("one");
+ arrangement.present(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 });
+ arrangement.present(one, { ids: [row.id], events });
receive([reaction(viewer, row, 31)], live);
frame();
expect(arrangement.snapshot()?.rows[0]?.reactions[0]?.events).toHaveLength(2);
@@ -438,10 +456,11 @@ it("shows an own pending reply only when named, and follows its delivery", async
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 });
+ const one = lane("one");
+ arrangement.present(one, { ids: [], events });
expect(arrangement.snapshot()?.rows).toEqual([]);
// Named with no events at all.
- arrangement.present(lane("one"), { ids: [id], events: [] });
+ arrangement.present(one, { ids: [id], events: [] });
expect(arrangement.snapshot()?.rows[0]).toMatchObject({
content: "mine",
delivery: "sending",
@@ -454,83 +473,36 @@ it("shows an own pending reply only when named, and follows its delivery", async
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", () => {
+it("shows the first lane to present and holds a later one, keeping nothing, until the shown one leaves or 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",
+ const first = lane("z");
+ const second = lane("a");
+ expect(arrangement.present(first, { ids: [a.id], events })).toBe("shown");
+ expect(arrangement.present(second, { ids: [b.id], events })).toBe("held");
+ // A held lane is still checked, so it learns now that it would not fit.
+ expect(arrangement.present(second, { ids: [b.id, b.id], events })).toBe(
+ "invalid",
);
- scan.length = 0;
+ expect(arrangement.status(second)).toBe("held");
+ // A lane that never presented has no presentation.
+ expect(arrangement.status(lane("b"))).toBe("none");
+ expect(ids(arrangement.snapshot()?.rows)).toEqual([a.id]);
+ // The shown lane withdraws: the host's rows, and the held lane may present.
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.snapshot()).toBeUndefined();
+ expect(arrangement.status(second)).toBe("none");
+ expect(arrangement.present(second, { ids: [b.id], events })).toBe("shown");
+ expect(arrangement.present(first, { ids: [a.id], events })).toBe("held");
+ // Live growth ends the shown lane, which frees the held one too.
+ receive([reaction(other, b, 30), reaction(other, b, 31)], live);
+ receive([reaction(other, b, 32)], live);
expect(arrangement.status(second)).toBe("ended");
+ expect(arrangement.status(first)).toBe("none");
expect(arrangement.snapshot()).toBeUndefined();
});
diff --git a/src/features/messages/arrangement.ts b/src/features/messages/arrangement.ts
index 1ccca13659..6bcc435512 100644
--- a/src/features/messages/arrangement.ts
+++ b/src/features/messages/arrangement.ts
@@ -26,26 +26,20 @@ import { AUX, growAux, inChannel } from "../relay/threads";
* - 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
+ * - SM2, a lane (one reader accessory): none, `shown`, `held` or `ended`. One
+ * lane is shown at a time, the first to present within limits; nothing else
+ * is stored. `present(P)` while another is shown -> `held`, which turns to
+ * none when that one leaves, so the lane presents again. `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.
+ * - SM3, the display: host rows (no lane shown) 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;
-}>;
+/** A reader accessory, by identity. */
+export type ArrangementLane = object;
/** 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. */
@@ -89,7 +83,8 @@ export function createArrangement({
limits: PresentationLimits;
}>) {
let phase: "live" | "leaving" | "retired" = "live";
- const lanes = new Map();
+ /** Lanes not shown that are waiting (`held`) or `ended`. */
+ const lanes = new Map();
let shown: ArrangementLane | undefined;
let evidence: Evidence | undefined;
let display: Display | undefined;
@@ -100,17 +95,6 @@ export function createArrangement({
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,
@@ -145,10 +129,11 @@ export function createArrangement({
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.
+ growAux([...pool.values()], held);
+ // The root, when given, stays beside its replies as the reader's header,
+ // which shows its reactions: they do not count against the limits.
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) {
@@ -232,27 +217,15 @@ export function createArrangement({
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" });
- }
+ /** The shown lane left (`ended`, if it ended): the host's rows again, and
+ * every held lane may present. */
+ function free(ended?: ArrangementLane) {
+ for (const [lane, state] of lanes) if (state === "held") lanes.delete(lane);
+ if (ended) lanes.set(ended, "ended");
release();
emit();
}
- function end() {
- if (shown) lanes.set(shown, { state: "ended" });
- settle();
- }
+ const end = () => free(shown);
function onLive({ events }: LiveBatch) {
const current = evidence;
if (!current) return;
@@ -292,30 +265,23 @@ export function createArrangement({
if (phase === "retired") return "retired";
if (presentation === null) {
lanes.delete(lane);
- if (shown === lane) settle();
+ if (shown === lane) free();
else emit();
return "shown";
}
- const wins = leader(lane) === lane;
- const picked = wins
- ? show(lane, presentation)
- : select(presentation, evidence?.live.values() ?? []);
+ // Checked either way, so a held lane learns now that it would not fit.
+ const held = shown !== undefined && shown !== lane;
+ const picked = held
+ ? select(presentation, evidence?.live.values() ?? [])
+ : show(lane, presentation);
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 },
- });
+ if (held) lanes.set(lane, "held");
+ else lanes.delete(lane);
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";
+ return held ? "held" : "shown";
},
+ status: (lane: ArrangementLane): "none" | "shown" | "held" | "ended" =>
+ shown === lane ? "shown" : (lanes.get(lane) ?? "none"),
/** The shown presentation, or `undefined` for the host's rows. */
snapshot: (): Display | undefined => display,
subscribe(listener: () => void) {
diff --git a/src/features/relay/thread-window.test.ts b/src/features/relay/thread-window.test.ts
index d6847b5a18..74ddfb5702 100644
--- a/src/features/relay/thread-window.test.ts
+++ b/src/features/relay/thread-window.test.ts
@@ -2304,15 +2304,15 @@ it("skips an oversized replay into a view with no page yet, then commits its fir
}
});
-it("admits a live reply inside the pages a refresh has read past the committed cursor", async () => {
+/** After a reconnect, a refresh pages past the committed cursor (the reply at
+ * 3) to the end of the thread; `during` runs while its last page is held. */
+async function refreshPastCursor(
+ during: (h: Awaited>) => void,
+) {
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));
@@ -2333,53 +2333,35 @@ it("admits a live reply inside the pages a refresh has read past the committed c
reconnected = true;
h.traffic.established(channel);
await reached;
- h.traffic.receive([late]);
+ during(h);
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);
+ return h.view.snapshot().replies.map((row) => row.id);
+}
+
+it("admits a live reply inside the pages a refresh has read past the committed cursor", async () => {
+ // Its timestamp places it between two pages the refresh has already read.
+ const late = message(author, channel, "late", 25, [
+ ["e", root.id, "", "reply"],
+ ]);
+ expect(await refreshPastCursor((h) => h.traffic.receive([late]))).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)];
+ const two = at(2);
+ const deletion = signed(author, {
+ kind: 5,
+ content: "",
+ created_at: 500,
+ tags: [["e", two.id]],
});
- 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);
+ expect(
+ await refreshPastCursor((h) => h.traffic.receive([deletion])),
+ ).not.toContain(two.id);
});
diff --git a/tests/fixtures/conversation-arranger/plugin.ts b/tests/fixtures/conversation-arranger/plugin.ts
index 9c0efedbf5..b70ecbbaaf 100644
--- a/tests/fixtures/conversation-arranger/plugin.ts
+++ b/tests/fixtures/conversation-arranger/plugin.ts
@@ -575,6 +575,10 @@ function createArranger(initial: ComposerAccessoryProps) {
message = "Showing fewer rows: the reader reached its limit.";
arrange();
},
+ /** The accessory it waited behind left: present what it is showing. */
+ free() {
+ if (phase.state === "ready" && sort) arrange();
+ },
update(next: ComposerAccessoryProps) {
props = next;
},
@@ -657,6 +661,7 @@ export function apply(ctx: Context) {
);
React.useEffect(() => {
if (props.presentation === "ended") arranger.ended();
+ if (props.presentation === "none") arranger.free();
}, [arranger, props.presentation]);
const noun = props.threadRootId !== undefined ? "replies" : "messages";
const [draft, setDraft] = React.useState("");
From 4b950e841a557e694e4afb9914929f874b13fe4f Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 02:23:13 -0500
Subject: [PATCH 03/37] fix(messages): keep holds out of conversation lookups
and presented places
A held event no longer feeds unread's structural lookup, so a hold
neither resolves a counted reply's root nor saves a fetch. It still
places the message a read or unread mark names, and the captured-read
and thread-read paths now find held rows too.
Leaving a link's visit while rows are presented saves no Back/Forward
place, in the channel and the thread: a presented row is not a place in
the host's rows.
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
.../ChannelTimeline.presentation.test.tsx | 19 ++++++++
src/features/messages/ChannelTimeline.tsx | 2 +-
.../ThreadPanel.presentation.test.tsx | 21 ++++++++-
src/features/messages/ThreadPanel.tsx | 5 +-
src/features/relay/unread.test.ts | 46 ++++++++++++++++++-
src/features/relay/unread.ts | 30 ++++++------
6 files changed, 105 insertions(+), 18 deletions(-)
diff --git a/src/features/messages/ChannelTimeline.presentation.test.tsx b/src/features/messages/ChannelTimeline.presentation.test.tsx
index 113bd22894..11f890214d 100644
--- a/src/features/messages/ChannelTimeline.presentation.test.tsx
+++ b/src/features/messages/ChannelTimeline.presentation.test.tsx
@@ -702,6 +702,25 @@ it("writes no saved place while it presents, and the host's place after it", ()
expect(saved.anchor.id).toBe(h3.id);
});
+it("saves no Back/Forward place for a link's visit left while it presents", () => {
+ // Control: leaving the revealed visit saves where the reader was.
+ const shown = navigationTo(h1.id);
+ const control = mount({ props: { navigation: shown } });
+ for (let pass = 0; pass < 4; pass++) frame();
+ expect(shown.complete).toHaveBeenCalledWith({ status: "opened" });
+ control.unmount();
+ expect(shown.savePosition).toHaveBeenCalled();
+ const navigation = navigationTo(h1.id);
+ const h = mount({ props: { navigation } });
+ for (let pass = 0; pass < 4; pass++) frame();
+ h.present({ ids: [p0.id, p1.id, p2.id] });
+ frame();
+ fireEvent.scroll(scroller());
+ h.unmount();
+ // A presented row is not a place in the host's rows.
+ expect(navigation.savePosition).not.toHaveBeenCalled();
+});
+
it("saves the geometry of the rows shown, never filed as the host's, when it unmounts presenting", () => {
const first = mount();
frame();
diff --git a/src/features/messages/ChannelTimeline.tsx b/src/features/messages/ChannelTimeline.tsx
index b39c3bf09e..afed319709 100644
--- a/src/features/messages/ChannelTimeline.tsx
+++ b/src/features/messages/ChannelTimeline.tsx
@@ -1363,7 +1363,7 @@ function Timeline({
)
return;
return () => {
- if (savedPosition.current)
+ if (savedPosition.current && !arrangedNow.current)
navigation.savePosition(TIMELINE_PLACE, savedPosition.current);
};
}, [navigation, presented]);
diff --git a/src/features/messages/ThreadPanel.presentation.test.tsx b/src/features/messages/ThreadPanel.presentation.test.tsx
index 2d0a9ee62e..73946cfa39 100644
--- a/src/features/messages/ThreadPanel.presentation.test.tsx
+++ b/src/features/messages/ThreadPanel.presentation.test.tsx
@@ -235,8 +235,11 @@ function mount({
{...props}
/>
);
- render(strict ? {element} : element);
+ const rendered = render(
+ strict ? {element} : element,
+ );
return {
+ unmount: () => rendered.unmount(),
view,
thread,
session,
@@ -520,6 +523,22 @@ it("yields a target it does not show: the visit opens, reading starts and the pl
expect(drawn()).toEqual(["root", "a", "b"]);
});
+it("records no Back/Forward place for a visit left while it presents", () => {
+ // Control: leaving the opened thread records where the reader was.
+ const shown = navigationTo(root.id);
+ const control = mount({ replies: [a, b], navigation: shown });
+ fireEvent.scroll(scroller());
+ control.unmount();
+ expect(shown.savePosition).toHaveBeenCalled();
+ const navigation = navigationTo(root.id);
+ const h = mount({ replies: [a, b], navigation });
+ h.present({ ids: [b.id, a.id] });
+ fireEvent.scroll(scroller());
+ h.unmount();
+ // A presented row is not a place in the host's rows.
+ expect(navigation.savePosition).not.toHaveBeenCalled();
+});
+
it("shows activity rows as the plugin lists them, unfolded", () => {
const step = (name: string, at: number) => {
const event = proven(
diff --git a/src/features/messages/ThreadPanel.tsx b/src/features/messages/ThreadPanel.tsx
index efd8f8bedb..3d5c2d304d 100644
--- a/src/features/messages/ThreadPanel.tsx
+++ b/src/features/messages/ThreadPanel.tsx
@@ -1318,6 +1318,9 @@ function ThreadMessages({
// reading first, so an offset the browser dropped meanwhile is never saved.
const leftTree = useRef(tree);
leftTree.current = tree;
+ // A presentation's rows are not the reader's place.
+ const presentedNow = useRef(presented);
+ presentedNow.current = presented;
const withdrawn = useRef<() => void>(undefined);
// biome-ignore lint/correctness/useExhaustiveDependencies: hiding or showing the reader again records its place too.
useLayoutEffect(() => {
@@ -1331,7 +1334,7 @@ function ThreadMessages({
if (!presented) return;
const record = () => {
const reading = resizePosition.current;
- if (!reading) return;
+ if (!reading || presentedNow.current) return;
const id = reading.anchor?.element.dataset.messageId;
navigation.savePosition(
THREAD_PLACE,
diff --git a/src/features/relay/unread.test.ts b/src/features/relay/unread.test.ts
index e8b1845586..4c6cba9df3 100644
--- a/src/features/relay/unread.test.ts
+++ b/src/features/relay/unread.test.ts
@@ -9014,11 +9014,36 @@ it("reads and marks unread a held-only message, never counting or caching it", a
await expect(
h.session.unread.markMessageUnread("room", held.id),
).rejects.toThrow(/evidence/);
- h.session.retain().set([held]);
+ const hold = h.session.retain();
+ hold.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);
+ // A captured read, a thread mark and a thread read find a held-only
+ // reply under a held-only root.
+ const root = eventDto(message(h.alice, "room", "root", 20));
+ const reply = eventDto(
+ message(h.alice, "room", "reply", 21, [["e", root.id, "", "reply"]]),
+ );
+ hold.set([held, root, reply]);
+ await requireCapturedRead(h.session.unread, [reply.id]);
+ await h.session.unread.markThrough(
+ { kind: "thread", channelId: "room", rootId: root.id },
+ reply.id,
+ );
+ expect(h.journal()?.state.frontiers).toMatchObject({
+ [`msg:${reply.id}`]: 21,
+ [`thread:${root.id}`]: 21,
+ });
+ await h.session.unread.prepareThreadRead("room", root.id)();
+ // Viewing a held reply that the thread mark already covers writes nothing.
+ const covered = eventDto(
+ message(h.alice, "room", "covered", 21, [["e", root.id, "", "reply"]]),
+ );
+ hold.set([held, root, reply, covered]);
+ await handle.observe([covered.id]);
+ expect(h.journal()?.state.frontiers).not.toHaveProperty(`msg:${covered.id}`);
// The hold is evidence only: nothing counted, nothing cached for views.
expect(h.snapshot().observedCount).toBe(counted);
expect(
@@ -9027,3 +9052,22 @@ it("reads and marks unread a held-only message, never counting or caching it", a
).toEqual([]);
handle.dispose();
});
+
+it("a hold gives a counted reply no conversation: its root is still fetched", async () => {
+ const h = setup();
+ h.grant("room");
+ const root = eventDto(message(h.viewer, "room", "mine", 11));
+ const reply = message(h.alice, "room", "reply", 12, [
+ ["e", root.id, "", "reply"],
+ ]);
+ h.session.retain().set([root]);
+ h.emit([reply]);
+ h.session.unread.attention("room", reply.id);
+ await vi.waitFor(() =>
+ expect(
+ h.query.mock.calls.flatMap(([filters]) =>
+ filters.flatMap((filter) => filter.ids ?? []),
+ ),
+ ).toContain(root.id),
+ );
+});
diff --git a/src/features/relay/unread.ts b/src/features/relay/unread.ts
index 2e5e45b9d7..3af9eef4b8 100644
--- a/src/features/relay/unread.ts
+++ b/src/features/relay/unread.ts
@@ -664,8 +664,10 @@ 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) => knownEvent(id) ?? lookupEvents.get(id);
- function root(event: RelayEvent): string | undefined {
+ const structural = (id: string) => events.get(id) ?? lookupEvents.get(id);
+ /** Also a held event, only to place a message a read or unread mark names. */
+ const placing = (id: string) => structural(id) ?? evidence?.(id);
+ function root(event: RelayEvent, lookup = structural): string | undefined {
const channel = channelOf(event);
let current = event;
const seen = new Set();
@@ -674,7 +676,7 @@ export function createUnread({
seen.add(current.id);
const reference = threadReference(current);
if (!reference) return current.id;
- const next = structural(reference.rootId);
+ const next = lookup(reference.rootId);
if (!next || !contentKind(next) || channelOf(next) !== channel) return;
current = next;
}
@@ -2936,7 +2938,7 @@ export function createUnread({
)
throw new Error("Verified readable message evidence unavailable");
if (
- (target.kind === "thread" && root(event) !== target.rootId) ||
+ (target.kind === "thread" && root(event, placing) !== target.rootId) ||
(target.kind === "message" && target.messageId !== id)
)
throw new Error("Message does not belong to the read target");
@@ -3407,7 +3409,7 @@ export function createUnread({
reads.state(),
targetKey(target),
channelId,
- threadReference(event) ? root(event) : undefined,
+ threadReference(event) ? root(event, placing) : undefined,
) ?? -1) >= event.created_at
) {
// Shown: its own local reminder ends with no new read mark.
@@ -3601,8 +3603,8 @@ export function createUnread({
key: `msg:${row.id}`,
timestamp: row.created_at,
channelId,
- ...(threadReference(row) && root(row)
- ? { rootId: root(row) }
+ ...(threadReference(row) && root(row, placing)
+ ? { rootId: root(row, placing) }
: {}),
})),
remaining ? undefined : messageForceKey(channelId),
@@ -3622,7 +3624,7 @@ export function createUnread({
},
async markCapturedMessagesRead(messageIds) {
const selected = [...new Set(messageIds)].map((id) => {
- const event = events.get(id);
+ const event = knownEvent(id);
const channelId = event && channelOf(event);
if (!channelId)
throw new Error("Verified readable message evidence unavailable");
@@ -3657,7 +3659,7 @@ export function createUnread({
!closed &&
channelValid.get(channelId)?.() &&
(visits.get(channelId) ?? 0) === visit.get(channelId) &&
- events.get(id) === event &&
+ knownEvent(id) === event &&
!deleted(event) &&
channelOf(event) === channelId;
const valid = () => generation === epoch && selected.every(messageValid);
@@ -3688,8 +3690,8 @@ export function createUnread({
key: `msg:${id}`,
timestamp: event.created_at,
channelId,
- ...(threadReference(event) && root(event)
- ? { rootId: root(event) }
+ ...(threadReference(event) && root(event, placing)
+ ? { rootId: root(event, placing) }
: {}),
});
return serializeChannels(channelIds, async () => {
@@ -3722,8 +3724,8 @@ export function createUnread({
...messageKeys,
...selected.flatMap(({ id, channelId, event }) => [
channelId,
- ...(threadReference(event) && root(event)
- ? [`thread:${root(event)}`]
+ ...(threadReference(event) && root(event, placing)
+ ? [`thread:${root(event, placing)}`]
: []),
`msg:${id}`,
]),
@@ -3861,7 +3863,7 @@ export function createUnread({
const channelValid = channelIntentValid(channelId);
const valid = () =>
channelValid() &&
- events.get(rootId) === selected &&
+ knownEvent(rootId) === selected &&
!deleted(selected) &&
root(selected) === rootId &&
rows.every(
From 0274f453a04c65a3942cf84e1aacab0a38488b84 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 09:21:07 -0500
Subject: [PATCH 04/37] test(messages): wait for the thread panel's placement,
not a sleep
The arranger journey test waited for the host's reads to stop with a
300 ms sleep loop; it now waits until the panel has placed its rows
(`aria-busy` false). The withdraw test expected the place that
`nearestShown` computed, the helper under test; it now states the case
the fixture produces, the first row below the read row that the host
shows, and fails if the reader lands anywhere else.
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
---
.../messages/ThreadPanel.arranger.test.tsx | 41 +++++++++----------
1 file changed, 19 insertions(+), 22 deletions(-)
diff --git a/src/features/messages/ThreadPanel.arranger.test.tsx b/src/features/messages/ThreadPanel.arranger.test.tsx
index 266476a75e..c35b9aee52 100644
--- a/src/features/messages/ThreadPanel.arranger.test.tsx
+++ b/src/features/messages/ThreadPanel.arranger.test.tsx
@@ -2,7 +2,6 @@
import "@testing-library/jest-dom/vitest";
import { Context } from "@deepseek-ai/cordis";
import {
- act,
cleanup,
fireEvent,
render,
@@ -28,7 +27,6 @@ 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";
@@ -176,14 +174,15 @@ 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)));
- }
-};
+/** The host's own rows, once the panel has placed them. */
+const hostRows = () =>
+ waitFor(() => {
+ expect(rowIds().length).toBeGreaterThan(0);
+ expect(screen.getByLabelText("Thread messages")).toHaveAttribute(
+ "aria-busy",
+ "false",
+ );
+ });
/** 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"), {
@@ -193,8 +192,8 @@ const shownTop = () =>
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);
+ await mount(target);
+ await hostRows();
// 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();
@@ -214,13 +213,12 @@ it("returns the host's rows when withdrawn, at the row it was reading or the nea
const { root, groups } = thread;
const target = (groups.one ?? [])[0] as string;
const { relay } = await mount(target);
- await hostRows(relay);
+ await hostRows();
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("");
@@ -240,12 +238,11 @@ it("returns the host's rows when withdrawn, at the row it was reading or the nea
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,
- );
+ // The host does not show the row it was reading, the list's first, so it
+ // keeps the first row below it that the host shows, still 20px down.
+ expect(host).not.toContain(order[0]);
+ const near = order.find((id) => host.includes(id)) as string;
+ expect(scrolled).toBe(100 * (host.indexOf(near) + 1) - 20);
expect(lastReading()).toMatchObject({
partial: false,
endMessageId: undefined,
@@ -253,8 +250,8 @@ it("returns the host's rows when withdrawn, at the row it was reading or the nea
}, 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);
+ await mount(small.root.id, small);
+ await hostRows();
fireEvent.click(screen.getByRole("button", { name: "Top" }));
await waitFor(() => expect(barStatus()).toMatch(/^Replies 1–\d+ of \d+$/), {
timeout: 30_000,
From 39e7c9bb1cc766b8503e6cfcf2e25761de9c7b95 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 13:40:42 -0500
Subject: [PATCH 05/37] refactor(messages): drop the change's prose comments
and return types
Removes the prose comments and annotated return types this change
added, so the code states its own behavior. `FOUNDATION:` comments
stay, and where the change reworded a comment that main already had,
the reworded comment stays. Three imports that only those return types
used are gone. The snapshotRead priority test now waits for a signal
from each read start instead of polling the started list.
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 | 1 -
docs/plugin-architecture.md | 5 +-
.../conversation/ComposerAccessories.tsx | 1 -
.../ChannelTimeline.presentation.test.tsx | 43 ++--------
src/features/messages/ChannelTimeline.tsx | 19 -----
.../messages/ThreadPanel.arranger.test.tsx | 17 ----
.../ThreadPanel.presentation.test.tsx | 35 +-------
src/features/messages/ThreadPanel.tsx | 18 ----
src/features/messages/arrangement.test.ts | 22 +----
src/features/messages/arrangement.ts | 61 +------------
.../messages/arranger-plugin.test.tsx | 61 -------------
src/features/messages/reply-tree.test.ts | 5 +-
src/features/messages/use-reading.test.ts | 3 -
src/features/relay/session-hold.test.ts | 26 +++---
src/features/relay/session.ts | 26 ------
src/features/relay/store.ts | 4 -
src/features/relay/thread-window.test.ts | 17 ----
src/features/relay/thread-window.ts | 3 -
src/features/relay/threads.ts | 11 ---
.../relay/traffic.integration.test.ts | 6 --
src/features/relay/unread.test.ts | 4 -
src/features/relay/unread.ts | 2 -
.../conversation-arranger/fixtures.ts | 15 +---
.../fixtures/conversation-arranger/plugin.ts | 85 ++-----------------
tests/fixtures/conversation-arranger/relay.ts | 30 ++-----
25 files changed, 47 insertions(+), 473 deletions(-)
diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs
index 2aec0463e3..d6035e7f29 100644
--- a/browser-host/relay-broker.mjs
+++ b/browser-host/relay-broker.mjs
@@ -361,7 +361,6 @@ 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"),
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index 65088eaed0..790afb616c 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -1808,7 +1808,10 @@ Three session capabilities serve a plugin that scans:
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.
+ reader uses one and the plugin uses one. `retain()` throws when no slot is
+ free, and `set` throws past the bound and keeps the previous events. A cache
+ clear empties the hold; the handle stays valid until `dispose()` or the
+ session closes.
- `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
diff --git a/src/features/conversation/ComposerAccessories.tsx b/src/features/conversation/ComposerAccessories.tsx
index 636a3833ec..bc8c51da29 100644
--- a/src/features/conversation/ComposerAccessories.tsx
+++ b/src/features/conversation/ComposerAccessories.tsx
@@ -100,7 +100,6 @@ const OwnedAccessory = memo(function OwnedAccessory({
arrangement?.subscribe ?? noSubscription,
() => arrangement?.status(entry),
);
- // An unmounted accessory shows nothing.
useLayoutEffect(
() => () => {
arrangement?.present(entry, null);
diff --git a/src/features/messages/ChannelTimeline.presentation.test.tsx b/src/features/messages/ChannelTimeline.presentation.test.tsx
index 11f890214d..42bfcb7e18 100644
--- a/src/features/messages/ChannelTimeline.presentation.test.tsx
+++ b/src/features/messages/ChannelTimeline.presentation.test.tsx
@@ -46,12 +46,9 @@ vi.mock("./TypingIndicator", () => ({
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 {
@@ -102,11 +99,9 @@ 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];
@@ -159,7 +154,6 @@ beforeEach(() => {
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)
@@ -189,7 +183,7 @@ afterEach(() => {
const readerEntry = (
component: Contribution["component"],
-): Contribution => ({
+) => ({
id: "arranger",
key: "test:arranger",
pluginId: "test",
@@ -225,13 +219,9 @@ function mount({
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);
@@ -249,7 +239,7 @@ function mount({
owners.push(owner);
owner.session.channels.ensure("c");
callbacks.receive([roster(relay, "c", [viewer.pubkey], T)]);
- const rowsOf = (events: readonly EventData[]): readonly ChannelMessage[] =>
+ const rowsOf = (events: readonly EventData[]) =>
owner.session.foldRows("c", events);
let current = hostWindow(rows ?? rowsOf(hostEvents), windowExtra);
const loadOlder = vi.fn();
@@ -312,7 +302,6 @@ function mount({
retained,
latest,
rowsOf,
- /** The host's window changes. */
setWindow(next: Partial) {
current = { ...current, ...next };
view.rerender(tree());
@@ -338,7 +327,6 @@ function mount({
},
};
}
-/** Runs the animation frames queued so far, as the browser would next. */
const frame = () =>
act(() => {
for (const [id, callback] of [...frames]) {
@@ -346,7 +334,6 @@ const frame = () =>
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,
@@ -477,7 +464,6 @@ it("shows the channel intro under a presentation only when it is complete", () =
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();
@@ -507,8 +493,6 @@ it("draws no day divider and merges no rows while it presents, and the host's ag
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 }) =>
@@ -516,7 +500,6 @@ it("draws no day divider and merges no rows while it presents, and the host's ag
);
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",
@@ -527,7 +510,6 @@ it("draws no day divider and merges no rows while it presents, and the host's ag
]);
});
-/** 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}`,
@@ -564,7 +546,6 @@ it("folds no agent activity under a presentation, and folds the host's again aft
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");
@@ -572,7 +553,6 @@ it("draws no unread line, Jump or arrival count under a presentation, and counts
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();
@@ -582,20 +562,18 @@ it("draws no unread line, Jump or arrival count under a presentation, and counts
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.
+ scrolled = 250;
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.
+ scrolled = 250;
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();
});
@@ -614,7 +592,6 @@ it("places a named row at the top of the view", () => {
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);
});
@@ -632,9 +609,8 @@ it("returns the host's rows at the anchor on a withdraw, reading nothing from th
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.
+ scrolled = 250;
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();
});
@@ -645,7 +621,6 @@ it.each([false, true])(
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],
@@ -662,7 +637,7 @@ it.each([false, true])(
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.
+ scrolled = 400;
viewport.first = 4;
h.present({ ids: [p0.id, h4.id, h5.id] });
expect(viewport.shifts).not.toContain(true);
@@ -697,13 +672,11 @@ it("writes no saved place while it presents, and the host's place after it", ()
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 no Back/Forward place for a link's visit left while it presents", () => {
- // Control: leaving the revealed visit saves where the reader was.
const shown = navigationTo(h1.id);
const control = mount({ props: { navigation: shown } });
for (let pass = 0; pass < 4; pass++) frame();
@@ -717,7 +690,6 @@ it("saves no Back/Forward place for a link's visit left while it presents", () =
frame();
fireEvent.scroll(scroller());
h.unmount();
- // A presented row is not a place in the host's rows.
expect(navigation.savePosition).not.toHaveBeenCalled();
});
@@ -725,12 +697,10 @@ it("saves the geometry of the rows shown, never filed as the host's, when it unm
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();
@@ -758,7 +728,6 @@ it("reads only the rows shown while it is partial, and catches up at its end row
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);
diff --git a/src/features/messages/ChannelTimeline.tsx b/src/features/messages/ChannelTimeline.tsx
index afed319709..3dd5f499ae 100644
--- a/src/features/messages/ChannelTimeline.tsx
+++ b/src/features/messages/ChannelTimeline.tsx
@@ -158,12 +158,10 @@ 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;
const topLevel = (row: ChannelMessage) =>
readable(row) && !row.threadRootId && !row.replyParentId;
-/** The newest row by time, wherever a presentation draws it. */
const newest = (rows: readonly ChannelMessage[]) =>
rows.reduce(
(latest, row) =>
@@ -311,8 +309,6 @@ function Timeline({
startsThreads = true,
}: ChannelTimelineProps) {
useMessageSelectionCopy();
- // 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,
@@ -320,10 +316,7 @@ function Timeline({
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 = (
@@ -868,8 +861,6 @@ function Timeline({
(navigation?.target.kind === "conversation" && !returning
? navigation.target.messageId
: undefined);
- // 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 &&
@@ -1019,7 +1010,6 @@ function Timeline({
ids: ReadonlySet;
floor: number;
paging: boolean;
- /** The presentation these rows belong to; undefined for the host's. */
owner: number | undefined;
}>({
order: [],
@@ -1389,8 +1379,6 @@ function Timeline({
? newest(display.rows.filter(topLevel))
: window.rows.filter(topLevel).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,
@@ -1409,8 +1397,6 @@ 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;
@@ -1421,7 +1407,6 @@ function Timeline({
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(
@@ -1447,7 +1432,6 @@ function Timeline({
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 },
@@ -1830,8 +1814,6 @@ function Timeline({
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 &&
@@ -2582,7 +2564,6 @@ function Timeline({
{arrangement && extensions?.accessories ? (
- {/* Above the scroller, never inside it. */}
[0];
const readingProps: ReadingProps[] = [];
vi.mock("./use-reading", () => ({
@@ -76,7 +72,6 @@ afterEach(async () => {
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(
@@ -115,7 +110,6 @@ const rowIds = () =>
"[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 ?? "",
@@ -169,12 +163,10 @@ async function mount(messageId: string, fixture = thread) {
});
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 the panel has placed them. */
const hostRows = () =>
waitFor(() => {
expect(rowIds().length).toBeGreaterThan(0);
@@ -183,7 +175,6 @@ const hostRows = () =>
"false",
);
});
-/** 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,
@@ -194,7 +185,6 @@ it("opens a thread at a row the host never loaded, ranks by Top, and leaves the
const target = (groups.one ?? [])[0] as string;
await mount(target);
await hostRows();
- // 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();
@@ -202,7 +192,6 @@ it("opens a thread at a row the host never loaded, ranks by Top, and leaves the
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),
@@ -216,14 +205,11 @@ it("returns the host's rows when withdrawn, at the row it was reading or the nea
await hostRows();
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 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(
() => {
@@ -238,8 +224,6 @@ it("returns the host's rows when withdrawn, at the row it was reading or the nea
expect(drawn()[0]).toBe(root.id);
expect(host).not.toContain(order.at(-1));
expect(relay.reads).toHaveLength(reads);
- // The host does not show the row it was reading, the list's first, so it
- // keeps the first row below it that the host shows, still 20px down.
expect(host).not.toContain(order[0]);
const near = order.find((id) => host.includes(id)) as string;
expect(scrolled).toBe(100 * (host.indexOf(near) + 1) - 20);
@@ -256,7 +240,6 @@ it("reads a thread it shows whole through to its last row", async () => {
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),
diff --git a/src/features/messages/ThreadPanel.presentation.test.tsx b/src/features/messages/ThreadPanel.presentation.test.tsx
index 73946cfa39..6d523b000b 100644
--- a/src/features/messages/ThreadPanel.presentation.test.tsx
+++ b/src/features/messages/ThreadPanel.presentation.test.tsx
@@ -73,7 +73,6 @@ 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];
@@ -91,7 +90,6 @@ afterEach(() => {
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;
@@ -127,7 +125,7 @@ beforeEach(() => {
const readerEntry = (
component: Contribution["component"],
-): Contribution => ({
+) => ({
id: "arranger",
key: "test:arranger",
pluginId: "test",
@@ -146,15 +144,12 @@ function mount({
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);
@@ -172,7 +167,7 @@ function mount({
owners.push(owner);
owner.session.channels.ensure("c");
callbacks.receive([roster(relay, "c", [viewer.pubkey], T)]);
- const rowsOf = (events: readonly EventData[]): readonly ChannelMessage[] =>
+ const rowsOf = (events: readonly EventData[]) =>
owner.session.foldRows("c", events, root.id);
const [rootRow] = rowsOf([root]) as [ChannelMessage];
let published: ThreadSnapshot = {
@@ -211,7 +206,6 @@ function mount({
const entries = [
readerEntry((accessory) => {
latest.current = accessory;
- // Every commit, as a plugin reacting to whatever else changed.
useLayoutEffect(() => {
onProps?.(accessory);
});
@@ -245,7 +239,6 @@ function mount({
session,
latest,
rowsOf,
- /** The host's view publishes a new state. */
publish(next: Partial) {
published = { ...published, ...next };
act(() => {
@@ -273,7 +266,6 @@ function mount({
},
};
}
-/** 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,
@@ -308,7 +300,6 @@ it("mounts the reader bar outside the composer, so a read-only thread has it too
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,
@@ -331,7 +322,6 @@ it("nests rows under their display parents, opening the branches it lists once e
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],
@@ -345,7 +335,6 @@ it("nests rows under their display parents, opening the branches it lists once e
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({
@@ -354,7 +343,6 @@ it("nests rows under their display parents, opening the branches it lists once e
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],
@@ -386,13 +374,10 @@ it("never loads more of the host's history while it presents", () => {
},
});
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"]);
});
@@ -439,7 +424,6 @@ it("leaves out the unread line and the earlier-reply note while it presents", ()
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(
@@ -462,8 +446,6 @@ it("draws no day divider and merges no rows while it presents", () => {
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");
@@ -482,7 +464,6 @@ it("replies to a presented row the host never loaded", () => {
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();
@@ -524,7 +505,6 @@ it("yields a target it does not show: the visit opens, reading starts and the pl
});
it("records no Back/Forward place for a visit left while it presents", () => {
- // Control: leaving the opened thread records where the reader was.
const shown = navigationTo(root.id);
const control = mount({ replies: [a, b], navigation: shown });
fireEvent.scroll(scroller());
@@ -535,7 +515,6 @@ it("records no Back/Forward place for a visit left while it presents", () => {
h.present({ ids: [b.id, a.id] });
fireEvent.scroll(scroller());
h.unmount();
- // A presented row is not a place in the host's rows.
expect(navigation.savePosition).not.toHaveBeenCalled();
});
@@ -570,7 +549,6 @@ it("starts reading when an inline reveal's row is not shown", () => {
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);
@@ -583,7 +561,6 @@ it("wires a partial presentation's reading: its end row, its newest row, its bar
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 },
@@ -597,10 +574,8 @@ it("wires a partial presentation's reading: its end row, its newest row, its bar
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();
@@ -616,7 +591,6 @@ it("places a presentation by its place intent", () => {
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 },
@@ -643,12 +617,9 @@ it("holds a place named by a presentation made at mount until its rows are drawn
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);
});
@@ -710,8 +681,6 @@ it("unmounts the reader and revokes its present when the view drops its root, as
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.tsx b/src/features/messages/ThreadPanel.tsx
index 3d5c2d304d..569573988a 100644
--- a/src/features/messages/ThreadPanel.tsx
+++ b/src/features/messages/ThreadPanel.tsx
@@ -248,8 +248,6 @@ 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;
@@ -701,16 +699,12 @@ function ThreadMessages({
const current = view.snapshot();
return current.status === "ready" ? current.root : undefined;
}, [view]);
- // 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(
@@ -783,8 +777,6 @@ 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(() => {
@@ -792,7 +784,6 @@ function ThreadMessages({
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; ) {
@@ -1278,8 +1269,6 @@ function ThreadMessages({
setInlineReveal(request.signal);
return () => request.abort();
}, [revealSelected, revealRequest]);
- // 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 &&
@@ -1318,7 +1307,6 @@ function ThreadMessages({
// reading first, so an offset the browser dropped meanwhile is never saved.
const leftTree = useRef(tree);
leftTree.current = tree;
- // A presentation's rows are not the reader's place.
const presentedNow = useRef(presented);
presentedNow.current = presented;
const withdrawn = useRef<() => void>(undefined);
@@ -1916,13 +1904,11 @@ function ThreadMessages({
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]));
@@ -2001,7 +1987,6 @@ 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(
presented ? [] : chronologicalSiblings,
activitySnapshot,
@@ -2381,13 +2366,10 @@ function ThreadMessages({
)?.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 && (
{
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 };
@@ -83,7 +81,6 @@ function host(
arrangement,
seen,
frames,
- /** The one animation frame that follows. */
frame() {
for (const [id, run] of [...frames]) {
frames.delete(id);
@@ -92,7 +89,7 @@ function host(
},
};
}
-const lane = (key: string): ArrangementLane => ({ key });
+const lane = (key: string) => ({ key });
const reaction = (author: Key, target: EventData, time: number) =>
proven(
signed(author, {
@@ -121,7 +118,6 @@ function thread(count = 3) {
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 [
@@ -198,7 +194,6 @@ it("passes parents, open, complete and place through, nested to depth 4", () =>
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(one, { ids: [a, b], events, parents: {} });
expect(arrangement.snapshot()?.parents?.size).toBe(0);
});
@@ -217,7 +212,6 @@ it("refuses duplicate ids and too many rows, events or bytes, and keeps what it
"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");
@@ -237,7 +231,6 @@ it("refuses duplicate ids and too many rows, events or bytes, and keeps what it
"limit",
);
expect(small.arrangement.snapshot()).toBeUndefined();
- // Any malformed field is refused before anything changes.
const before = arrangement.snapshot();
for (const bad of [
{ ids: "x" },
@@ -276,7 +269,6 @@ it("holds the root as the header without counting its reactions against the limi
rootId: root.id,
limits: { rows: 10, events: 2, bytes: 4 << 20 },
});
- // A page read with the root's aux, as a relay without `root_aux` sends it.
const page = [
...events,
reaction(other, root, 30),
@@ -300,7 +292,6 @@ it("applies a live reaction and its deletion (two hops) to a row it was given by
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);
@@ -343,7 +334,6 @@ it("ends when live growth passes the limits, never trims, and shows again on a n
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);
@@ -360,7 +350,6 @@ it("swaps its one hold in place: a full session still re-presents, and a withdra
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 }),
@@ -435,7 +424,6 @@ it("keeps refolding live changes after a re-present that overtook a pending fram
const one = lane("one");
arrangement.present(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(one, { ids: [row.id], events });
receive([reaction(viewer, row, 31)], live);
frame();
@@ -459,7 +447,6 @@ it("shows an own pending reply only when named, and follows its delivery", async
const one = lane("one");
arrangement.present(one, { ids: [], events });
expect(arrangement.snapshot()?.rows).toEqual([]);
- // Named with no events at all.
arrangement.present(one, { ids: [id], events: [] });
expect(arrangement.snapshot()?.rows[0]).toMatchObject({
content: "mine",
@@ -484,21 +471,17 @@ it("shows the first lane to present and holds a later one, keeping nothing, unti
const second = lane("a");
expect(arrangement.present(first, { ids: [a.id], events })).toBe("shown");
expect(arrangement.present(second, { ids: [b.id], events })).toBe("held");
- // A held lane is still checked, so it learns now that it would not fit.
expect(arrangement.present(second, { ids: [b.id, b.id], events })).toBe(
"invalid",
);
expect(arrangement.status(second)).toBe("held");
- // A lane that never presented has no presentation.
expect(arrangement.status(lane("b"))).toBe("none");
expect(ids(arrangement.snapshot()?.rows)).toEqual([a.id]);
- // The shown lane withdraws: the host's rows, and the held lane may present.
arrangement.present(first, null);
expect(arrangement.snapshot()).toBeUndefined();
expect(arrangement.status(second)).toBe("none");
expect(arrangement.present(second, { ids: [b.id], events })).toBe("shown");
expect(arrangement.present(first, { ids: [a.id], events })).toBe("held");
- // Live growth ends the shown lane, which frees the held one too.
receive([reaction(other, b, 30), reaction(other, b, 31)], live);
receive([reaction(other, b, 32)], live);
expect(arrangement.status(second)).toBe("ended");
@@ -522,7 +505,6 @@ it("keeps a presentation through a StrictMode replay and retires after a real un
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();
@@ -568,7 +550,6 @@ it("holds one pending place until it is applied, replaced by a later one, cancel
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();
@@ -577,7 +558,6 @@ it("holds one pending place until it is applied, replaced by a later one, 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();
diff --git a/src/features/messages/arrangement.ts b/src/features/messages/arrangement.ts
index 6bcc435512..4e7f663d87 100644
--- a/src/features/messages/arrangement.ts
+++ b/src/features/messages/arrangement.ts
@@ -8,7 +8,6 @@ import {
import type {
ConversationPresentation,
PresentationLimits,
- PresentResult,
} from "../conversation/contracts";
import { listByteSize } from "../relay/budget";
import type { ChannelMessage } from "../relay/contracts";
@@ -18,26 +17,6 @@ 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, `shown`, `held` or `ended`. One
- * lane is shown at a time, the first to present within limits; nothing else
- * is stored. `present(P)` while another is shown -> `held`, which turns to
- * none when that one leaves, so the lane presents again. `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.
- * - SM3, the display: host rows (no lane shown) 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.
- */
/** A reader accessory, by identity. */
export type ArrangementLane = object;
/** The rows a reader shows in place of the host's, while a lane is shown. */
@@ -54,12 +33,10 @@ export type Display = Readonly<{
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[];
};
@@ -83,7 +60,6 @@ export function createArrangement({
limits: PresentationLimits;
}>) {
let phase: "live" | "leaving" | "retired" = "live";
- /** Lanes not shown that are waiting (`held`) or `ended`. */
const lanes = new Map();
let shown: ArrangementLane | undefined;
let evidence: Evidence | undefined;
@@ -95,14 +71,12 @@ export function createArrangement({
const emit = () => {
for (const listener of [...listeners]) listener();
};
- /** 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) ||
@@ -120,8 +94,6 @@ export function createArrangement({
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);
@@ -130,8 +102,6 @@ export function createArrangement({
if (wanted.has(event.id) && !AUX.has(event.kind) && event.kind !== 39007)
held.set(event.id, event);
growAux([...pool.values()], held);
- // The root, when given, stays beside its replies as the reader's header,
- // which shows its reactions: they do not count against the limits.
const root = pool.get(rootId ?? "");
if (root) held.set(root.id, root);
return exceeds(held, limits) ? "limit" : { events: held };
@@ -142,7 +112,6 @@ export function createArrangement({
.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) ?? []),
);
@@ -159,7 +128,6 @@ export function createArrangement({
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;
@@ -170,8 +138,6 @@ export function createArrangement({
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;
@@ -180,7 +146,6 @@ export function createArrangement({
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";
}
@@ -195,7 +160,6 @@ export function createArrangement({
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;
@@ -217,8 +181,6 @@ export function createArrangement({
watch();
return picked;
}
- /** The shown lane left (`ended`, if it ended): the host's rows again, and
- * every held lane may present. */
function free(ended?: ArrangementLane) {
for (const [lane, state] of lanes) if (state === "held") lanes.delete(lane);
if (ended) lanes.set(ended, "ended");
@@ -229,7 +191,6 @@ export function createArrangement({
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);
@@ -241,7 +202,6 @@ export function createArrangement({
}
refold();
}
- /** A fold at most once per frame, from live aux, the outbox or profiles. */
function refold() {
const current = evidence;
if (!current || cancelFrame) return;
@@ -257,11 +217,10 @@ export function createArrangement({
}
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);
@@ -269,7 +228,6 @@ export function createArrangement({
else emit();
return "shown";
}
- // Checked either way, so a held lane learns now that it would not fit.
const held = shown !== undefined && shown !== lane;
const picked = held
? select(presentation, evidence?.live.values() ?? [])
@@ -280,22 +238,18 @@ export function createArrangement({
emit();
return held ? "held" : "shown";
},
- status: (lane: ArrangementLane): "none" | "shown" | "held" | "ended" =>
+ status: (lane: ArrangementLane) =>
shown === lane ? "shown" : (lanes.get(lane) ?? "none"),
- /** The shown presentation, or `undefined` for the host's rows. */
- snapshot: (): Display | undefined => display,
+ snapshot: () => 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";
@@ -402,12 +356,7 @@ export function createPlace() {
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 {
+ take(shown: (id: string) => boolean, fallback: "start" | "end" = "start") {
const intent = pending;
pending = undefined;
if (!intent) return held;
@@ -420,7 +369,6 @@ export function createPlace() {
}
return held;
},
- /** The held placement was applied, or can never be. */
done() {
held = undefined;
},
@@ -447,7 +395,6 @@ export function usePlace(
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]);
diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx
index db0adf9964..fac4c7fcb2 100644
--- a/src/features/messages/arranger-plugin.test.tsx
+++ b/src/features/messages/arranger-plugin.test.tsx
@@ -44,12 +44,6 @@ 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 () => {
@@ -77,8 +71,6 @@ const PLUGIN = {
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();
@@ -106,7 +98,6 @@ function oracle(events: readonly EventData[], rootId?: string) {
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))
@@ -118,14 +109,12 @@ function oracle(events: readonly EventData[], rootId?: string) {
)
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),
);
@@ -135,7 +124,6 @@ function oracle(events: readonly EventData[], rootId?: string) {
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);
@@ -165,10 +153,8 @@ const reactionTo = async (
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;
};
@@ -273,10 +259,8 @@ async function mount({ fixture, rootId, windowNewer, probe, targetId }: Mount) {
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]) {
@@ -284,7 +268,6 @@ async function mount({ fixture, rootId, windowNewer, probe, targetId }: Mount) {
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 },
@@ -295,9 +278,7 @@ async function mount({ fixture, rootId, windowNewer, probe, targetId }: Mount) {
},
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,
};
}
@@ -311,7 +292,6 @@ const ready = (h: Harness) =>
},
{ 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());
@@ -339,7 +319,6 @@ it("ranks a 2,000-reply thread by Top from background reads, leaving the host's
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,
@@ -369,7 +348,6 @@ it("ranks a 2,000-reply thread by Top from background reads, leaving the host's
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
@@ -380,26 +358,21 @@ it("ranks a 2,000-reply thread by Top from background reads, leaving the host's
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);
@@ -422,7 +395,6 @@ it("folds every reaction, edit and deletion of the thread as the oracle counts t
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(
@@ -447,7 +419,6 @@ it("presents a thread that fits whole as complete", async () => {
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();
});
@@ -463,9 +434,7 @@ it("grows a Top window from 200 to 460 rows, the most a thread reader shows, and
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(() => {
@@ -473,11 +442,9 @@ it("grows a Top window from 200 to 460 rows, the most a thread reader shows, and
});
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 },
@@ -515,7 +482,6 @@ it("pages a Top list past the reader's 460 rows, each page the oracle's slice, a
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));
@@ -527,15 +493,12 @@ it("filters every row by its edited text, in any case, whatever the scan had rea
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,
@@ -544,12 +507,10 @@ it("filters every row by its edited text, in any case, whatever the scan had rea
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);
@@ -560,7 +521,6 @@ it("filters every row by its edited text, in any case, whatever the scan had rea
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([]);
@@ -577,7 +537,6 @@ it("reaches the last reply of an Oldest list by Next, reading forward as it goes
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");
@@ -602,7 +561,6 @@ it("re-ranks when a reaction lands on a row that is not shown", async () => {
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)
@@ -638,7 +596,6 @@ it("hides a shown row when its deletion arrives live", async () => {
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)));
});
@@ -651,13 +608,11 @@ it("keeps the viewer's own reply in view from sending to seen, then ranks it as
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);
@@ -671,7 +626,6 @@ it("paints Oldest first from the reads its first window needs and pages forward
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({
@@ -705,7 +659,6 @@ it("reads a thread through older pages alone when the relay has no newer windows
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);
@@ -742,7 +695,6 @@ it("nests replies under their shown parents and opens the branches that hold the
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);
@@ -777,7 +729,6 @@ it("waits behind another arrangement and shows when that one leaves", async () =
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);
@@ -794,7 +745,6 @@ it("shows fewer rows when live growth ends its presentation", async () => {
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(
@@ -805,7 +755,6 @@ it("shows fewer rows when live growth ends its presentation", async () => {
),
);
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(
@@ -823,9 +772,6 @@ it("reads the whole thread again after a reconnect once it is visible, and is no
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),
@@ -851,8 +797,6 @@ it("reads the whole thread again after a reconnect once it is visible, and is no
] 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")
@@ -882,7 +826,6 @@ it("keeps an Oldest list in order when replies arrive before the read reaches th
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, {
@@ -900,7 +843,6 @@ it("keeps an Oldest list in order when replies arrive before the read reaches th
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);
@@ -912,7 +854,6 @@ it("keeps an Oldest list in order when replies arrive before the read reaches th
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(() =>
@@ -966,7 +907,6 @@ it("ranks a 5,000-row channel by top reacted from verified windows, without touc
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);
@@ -994,7 +934,6 @@ it("ranks a new live message in a channel's Top list", async () => {
}),
])) 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)),
);
diff --git a/src/features/messages/reply-tree.test.ts b/src/features/messages/reply-tree.test.ts
index 205ac31231..9d0866ff52 100644
--- a/src/features/messages/reply-tree.test.ts
+++ b/src/features/messages/reply-tree.test.ts
@@ -144,10 +144,10 @@ it("lifts unknown, later, self and root display parents, so a cycle breaks at it
);
const display: Record = {
b: "missing",
- c: "f", // later
+ c: "f",
d: "d",
e: "root",
- f: "c", // with c -> f, a cycle; f nests under the earlier c
+ f: "c",
};
const tree = replyTree(rows, "root", (id) => display[id]);
expect(tree.children.get(undefined)?.map(({ id }) => id)).toEqual([
@@ -160,7 +160,6 @@ it("lifts unknown, later, self and root display parents, so a cycle breaks at it
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", () => {
diff --git a/src/features/messages/use-reading.test.ts b/src/features/messages/use-reading.test.ts
index 3587ea4797..dc7137e3b7 100644
--- a/src/features/messages/use-reading.test.ts
+++ b/src/features/messages/use-reading.test.ts
@@ -62,7 +62,6 @@ function setup({
// The app's root, a direct body child as in production.
const root = document.createElement("div");
root.append(panel);
- // The list's reader bar, beside it outside any reading surface.
const bar = document.createElement("button");
document.body.append(root, composer, parent, outside, bar);
({ element, composer, parent, outside, header, bar })[focus].focus();
@@ -807,7 +806,6 @@ it("an arranged list's end row at the bottom catches up through the newest row",
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();
@@ -839,7 +837,6 @@ it("a list that turns partial mid-dwell drops its complete leases before they ca
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]?.[3]).toBe(true);
diff --git a/src/features/relay/session-hold.test.ts b/src/features/relay/session-hold.test.ts
index 0ec718cf24..4758e2146a 100644
--- a/src/features/relay/session-hold.test.ts
+++ b/src/features/relay/session-hold.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, expect, it, vi } from "vitest";
+import { afterEach, expect, it } from "vitest";
import { createRelaySession } from "./session";
import { CHANNEL_LIMITS } from "./store";
import { eventDto, type EventData, type RelayEvent } from "./events";
@@ -21,7 +21,6 @@ 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) {
@@ -221,7 +220,6 @@ it("holds only proven events of channels the viewer can read", () => {
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/,
);
@@ -262,7 +260,6 @@ it("holds up to a byte bound, keeps the previous set past it, and shares the vie
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(
@@ -288,6 +285,14 @@ it("holds up to a byte bound, keeps the previous set past it, and shares the vie
it("passes snapshotRead priority to the reader, so a background scan queues behind foreground reads", async () => {
const started: { kind: number; priority?: string; release(): void }[] = [];
+ let onStart = () => {};
+ const startedReads = (count: number) =>
+ new Promise((resolve) => {
+ onStart = () => {
+ if (started.length >= count) resolve();
+ };
+ onStart();
+ });
const owner = createRelaySession({
viewer: viewer.pubkey,
relayAuthor: relay.pubkey,
@@ -295,13 +300,14 @@ it("passes snapshotRead priority to the reader, so a background scan queues behi
query: (filters, _signal, _id, priority) => {
const kind = filters[0]?.kinds?.[0] ?? 0;
if (kind < 30001) return Promise.resolve([]);
- return new Promise((resolve) =>
+ return new Promise((resolve) => {
started.push({
kind,
...(priority ? { priority } : {}),
release: () => resolve([]),
- }),
- );
+ });
+ onStart();
+ });
},
});
owners.push(owner);
@@ -309,17 +315,17 @@ it("passes snapshotRead priority to the reader, so a background scan queues behi
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));
+ await startedReads(1);
const next = read(filter(30002), { priority: "background" });
const foreground = read(filter(30003), {});
- await vi.waitFor(() => expect(started).toHaveLength(2));
+ await startedReads(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));
+ await startedReads(3);
expect(started[2]?.kind).toBe(30002);
for (const item of started) item.release();
await Promise.all([next, foreground]);
diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts
index 1ea1e675a5..60b329845b 100644
--- a/src/features/relay/session.ts
+++ b/src/features/relay/session.ts
@@ -192,8 +192,6 @@ 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, or the general statuses read with them.
@@ -359,8 +357,6 @@ 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;
@@ -3427,8 +3423,6 @@ 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
@@ -3520,19 +3514,12 @@ 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 &&
@@ -3553,7 +3540,6 @@ export function createRelaySession(
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(
@@ -3585,18 +3571,6 @@ export function createRelaySession(
: 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");
diff --git a/src/features/relay/store.ts b/src/features/relay/store.ts
index d97d90aaa1..ad8fc12861 100644
--- a/src/features/relay/store.ts
+++ b/src/features/relay/store.ts
@@ -4328,10 +4328,6 @@ 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) {
diff --git a/src/features/relay/thread-window.test.ts b/src/features/relay/thread-window.test.ts
index 74ddfb5702..49d608a1d6 100644
--- a/src/features/relay/thread-window.test.ts
+++ b/src/features/relay/thread-window.test.ts
@@ -142,7 +142,6 @@ it("keeps the older binding when direction and root aux are explicit defaults",
"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);
@@ -161,9 +160,6 @@ it("binds a forward page that leaves root aux out as the relay's vector", async
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",
@@ -187,7 +183,6 @@ describe("forward thread pages", () => {
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(
@@ -269,7 +264,6 @@ describe("forward thread pages", () => {
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/,
);
@@ -2168,14 +2162,11 @@ it("settles session recovery when a read view with a quiet failure passes its me
}
});
-// 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)),
);
@@ -2206,7 +2197,6 @@ it.each(["live traffic", "a session readPage scan"])(
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([
@@ -2252,12 +2242,10 @@ it("admits a reply at the cursor's second only when its id is at or below the cu
).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",
@@ -2304,8 +2292,6 @@ it("skips an oversized replay into a view with no page yet, then commits its fir
}
});
-/** After a reconnect, a refresh pages past the committed cursor (the reply at
- * 3) to the end of the thread; `during` runs while its last page is held. */
async function refreshPastCursor(
during: (h: Awaited>) => void,
) {
@@ -2343,7 +2329,6 @@ async function refreshPastCursor(
}
it("admits a live reply inside the pages a refresh has read past the committed cursor", async () => {
- // Its timestamp places it between two pages the refresh has already read.
const late = message(author, channel, "late", 25, [
["e", root.id, "", "reply"],
]);
@@ -2352,8 +2337,6 @@ it("admits a live reply inside the pages a refresh has read past the committed c
);
});
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 two = at(2);
const deletion = signed(author, {
kind: 5,
diff --git a/src/features/relay/thread-window.ts b/src/features/relay/thread-window.ts
index ccb272900f..0633d4cae4 100644
--- a/src/features/relay/thread-window.ts
+++ b/src/features/relay/thread-window.ts
@@ -28,7 +28,6 @@ export function threadAuthority(origin: string) {
.replace(/\.$/, "");
}
-/** The request cursor in the filter's own direction. */
const requestCursor = (filter: ReadFilter) =>
filter.direction === "newer"
? filter.after === undefined
@@ -172,8 +171,6 @@ export async function verifyThreadWindows(
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.ts b/src/features/relay/threads.ts
index 3c6e379914..ce561e1f00 100644
--- a/src/features/relay/threads.ts
+++ b/src/features/relay/threads.ts
@@ -253,7 +253,6 @@ 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;
@@ -572,12 +571,6 @@ 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" ||
@@ -586,7 +579,6 @@ export function createThreadView({
!isReply(event)
)
return false;
- // A run reading past the committed cursor admits up to its own reach.
const edge =
reach === null
? undefined
@@ -604,7 +596,6 @@ export function createThreadView({
const incoming = related(fresh);
if (!incoming.length) return;
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)) {
@@ -1152,8 +1143,6 @@ 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
diff --git a/src/features/relay/traffic.integration.test.ts b/src/features/relay/traffic.integration.test.ts
index 50d2f1cdb0..2541a2a185 100644
--- a/src/features/relay/traffic.integration.test.ts
+++ b/src/features/relay/traffic.integration.test.ts
@@ -706,8 +706,6 @@ 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),
@@ -736,8 +734,6 @@ it("keeps a channel scan below the window's floor from limiting its history, and
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,
@@ -770,8 +766,6 @@ it("shows catch-up rows below the window's floor once the catch-up moves it", as
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();
diff --git a/src/features/relay/unread.test.ts b/src/features/relay/unread.test.ts
index 4c6cba9df3..974f573fb6 100644
--- a/src/features/relay/unread.test.ts
+++ b/src/features/relay/unread.test.ts
@@ -9020,8 +9020,6 @@ it("reads and marks unread a held-only message, never counting or caching it", a
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);
- // A captured read, a thread mark and a thread read find a held-only
- // reply under a held-only root.
const root = eventDto(message(h.alice, "room", "root", 20));
const reply = eventDto(
message(h.alice, "room", "reply", 21, [["e", root.id, "", "reply"]]),
@@ -9037,14 +9035,12 @@ it("reads and marks unread a held-only message, never counting or caching it", a
[`thread:${root.id}`]: 21,
});
await h.session.unread.prepareThreadRead("room", root.id)();
- // Viewing a held reply that the thread mark already covers writes nothing.
const covered = eventDto(
message(h.alice, "room", "covered", 21, [["e", root.id, "", "reply"]]),
);
hold.set([held, root, reply, covered]);
await handle.observe([covered.id]);
expect(h.journal()?.state.frontiers).not.toHaveProperty(`msg:${covered.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()
diff --git a/src/features/relay/unread.ts b/src/features/relay/unread.ts
index 3af9eef4b8..b9d7f2fc42 100644
--- a/src/features/relay/unread.ts
+++ b/src/features/relay/unread.ts
@@ -459,7 +459,6 @@ 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
@@ -665,7 +664,6 @@ export function createUnread({
`${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);
- /** Also a held event, only to place a message a read or unread mark names. */
const placing = (id: string) => structural(id) ?? evidence?.(id);
function root(event: RelayEvent, lookup = structural): string | undefined {
const channel = channelOf(event);
diff --git a/tests/fixtures/conversation-arranger/fixtures.ts b/tests/fixtures/conversation-arranger/fixtures.ts
index 4f6930dbcd..3e648f29aa 100644
--- a/tests/fixtures/conversation-arranger/fixtures.ts
+++ b/tests/fixtures/conversation-arranger/fixtures.ts
@@ -18,8 +18,6 @@ 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) =>
@@ -64,10 +62,7 @@ export type Fixture = Readonly<{
* 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 {
+export async function threadFixture(count = 2000, seed = 7) {
const random = seeded(seed);
const raw: Event[] = [];
const rootAt = T - 100;
@@ -82,7 +77,6 @@ export async function threadFixture(
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, {
@@ -141,7 +135,6 @@ export async function threadFixture(
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]))) {
@@ -166,7 +159,6 @@ export async function threadFixture(
),
);
}
- // 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);
@@ -183,10 +175,7 @@ export async function threadFixture(
/** 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 {
+export async function channelFixture(count = 5000, seed = 11) {
const random = seeded(seed);
const raw: Event[] = [];
const rows: Event[] = [];
diff --git a/tests/fixtures/conversation-arranger/plugin.ts b/tests/fixtures/conversation-arranger/plugin.ts
index b70ecbbaaf..1ba10cbf0a 100644
--- a/tests/fixtures/conversation-arranger/plugin.ts
+++ b/tests/fixtures/conversation-arranger/plugin.ts
@@ -9,17 +9,6 @@ import type {
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";
@@ -27,16 +16,10 @@ 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]);
@@ -71,15 +54,13 @@ export type View = Readonly<{
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 => ({
+const cursorOf = (row: ChannelMessage) => ({
created_at: row.createdAt,
id: row.id,
});
@@ -89,16 +70,11 @@ function createArranger(initial: ComposerAccessoryProps) {
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;
@@ -106,9 +82,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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;
@@ -141,8 +114,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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();
@@ -154,15 +125,13 @@ function createArranger(initial: ComposerAccessoryProps) {
}
}
- /** 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 filters = lanes.map(([lane, cursor]) => {
const newer = lane === "newer";
return {
"#h": [props.channelId],
@@ -174,7 +143,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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 }),
@@ -199,7 +167,6 @@ function createArranger(initial: ComposerAccessoryProps) {
);
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;
@@ -214,8 +181,6 @@ function createArranger(initial: ComposerAccessoryProps) {
: 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) {
@@ -232,8 +197,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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 {
@@ -249,18 +212,13 @@ function createArranger(initial: ComposerAccessoryProps) {
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()) {
@@ -269,9 +227,6 @@ function createArranger(initial: ComposerAccessoryProps) {
}
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 = () =>
@@ -280,7 +235,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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;
@@ -292,7 +246,6 @@ function createArranger(initial: ComposerAccessoryProps) {
: 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)]) : [],
);
@@ -303,7 +256,6 @@ function createArranger(initial: ComposerAccessoryProps) {
(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 : []),
@@ -311,10 +263,8 @@ function createArranger(initial: ComposerAccessoryProps) {
];
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))
@@ -364,7 +314,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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;
@@ -385,7 +334,6 @@ function createArranger(initial: ComposerAccessoryProps) {
...(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);
}
@@ -420,9 +368,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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;
@@ -431,15 +376,10 @@ function createArranger(initial: ComposerAccessoryProps) {
forward = undefined;
try {
hold?.set([]);
- } catch {
- // An empty hold always fits.
- }
+ } catch {}
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;
@@ -458,12 +398,8 @@ function createArranger(initial: ComposerAccessoryProps) {
}
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 (
@@ -508,8 +444,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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;
@@ -534,7 +468,6 @@ function createArranger(initial: ComposerAccessoryProps) {
}
const api = {
- /** Starts, or restarts, a sort from its first window. */
start(next: Sort) {
sort = next;
size = PAGE;
@@ -542,7 +475,6 @@ function createArranger(initial: ComposerAccessoryProps) {
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";
@@ -551,13 +483,11 @@ function createArranger(initial: ComposerAccessoryProps) {
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);
@@ -568,14 +498,12 @@ function createArranger(initial: ComposerAccessoryProps) {
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();
},
- /** The accessory it waited behind left: present what it is showing. */
free() {
if (phase.state === "ready" && sort) arrange();
},
@@ -596,9 +524,7 @@ function createArranger(initial: ComposerAccessoryProps) {
if (events.size) {
try {
holdAll();
- } catch {
- // The scan is kept; it is held again on its next read.
- }
+ } catch {}
}
},
dispose() {
@@ -615,7 +541,7 @@ function createArranger(initial: ComposerAccessoryProps) {
listeners.delete(listener);
};
},
- snapshot(): View {
+ snapshot() {
const more = !!sort && scanned === false && forward !== null;
const next = offset() + taken < total || more;
cached ??= Object.freeze({
@@ -646,7 +572,6 @@ export function apply(ctx: Context) {
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));
diff --git a/tests/fixtures/conversation-arranger/relay.ts b/tests/fixtures/conversation-arranger/relay.ts
index 7510b8176a..aa038ae9e6 100644
--- a/tests/fixtures/conversation-arranger/relay.ts
+++ b/tests/fixtures/conversation-arranger/relay.ts
@@ -29,14 +29,6 @@ import {
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. */
@@ -54,7 +46,7 @@ export function mint(
created_at: number;
tags: string[][];
},
-): Event {
+) {
const fields = { ...template, pubkey: key.pubkey };
return { ...fields, id: getEventHash(fields), sig: "0".repeat(128) };
}
@@ -63,7 +55,7 @@ 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 {
+export async function prove(events: readonly Event[]) {
const native = prover.native;
if (!native) throw new Error("no native verifier");
const settled = await native.settle(events.map((e) => native.prepare(e)));
@@ -84,7 +76,7 @@ export function seeded(seed: number) {
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
-export function shuffled(items: readonly T[], random: () => number): T[] {
+export function shuffled(items: readonly T[], random: () => number) {
const out = [...items];
for (let i = out.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
@@ -101,7 +93,6 @@ export type ReadRecord = {
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. */
@@ -128,7 +119,6 @@ export function createWorld(events: readonly RelayEvent[] = []) {
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);
@@ -138,7 +128,6 @@ export function createWorld(events: readonly RelayEvent[] = []) {
}
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) ?? []);
@@ -151,11 +140,7 @@ export function createWorld(events: readonly RelayEvent[] = []) {
}
export type World = ReturnType;
-/** The rows after `cursor` in the filter's own direction. */
-function after(
- rows: readonly RelayEvent[],
- filter: ReadFilter,
-): readonly RelayEvent[] {
+function after(rows: readonly RelayEvent[], filter: ReadFilter) {
if (filter.direction === "newer") {
const at = filter.after;
return at === undefined
@@ -177,7 +162,6 @@ function after(
);
}
-/** A relay-signed bounds event, proven. */
async function bound(
relay: Key,
kind: 39006 | 39007,
@@ -206,7 +190,7 @@ export function createRelay(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 {
+ async function answer(filter: ReadFilter) {
if (filter.ids) return filter.ids.flatMap((id) => world.byId.get(id) ?? []);
if (filter.kinds?.includes(39002) || filter.kinds?.includes(39000))
return [members, channelMeta];
@@ -282,7 +266,6 @@ export function createRelay(options: {
),
];
}
- // A repair read: aux that name these rows since a time.
if (filter["#e"])
return world
.auxOf(filter["#e"])
@@ -361,12 +344,9 @@ export function openSession(options: {
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: [] });
},
From 1a382485d14b2f0358574db696e51ef1bb1706f3 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 13:44:05 -0500
Subject: [PATCH 06/37] test(messages): drop the arranger tests' raised
timeouts
Each arranger test finishes in under two seconds on an idle machine,
inside vitest's default per-test limit, so the per-test 30-120 second
limits only delayed a failure. The fixture-building hooks keep theirs.
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
---
src/features/messages/ThreadPanel.arranger.test.tsx | 6 +++---
src/features/messages/arranger-plugin.test.tsx | 10 +++++-----
2 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/src/features/messages/ThreadPanel.arranger.test.tsx b/src/features/messages/ThreadPanel.arranger.test.tsx
index 2f4d3d592d..2b97cbb296 100644
--- a/src/features/messages/ThreadPanel.arranger.test.tsx
+++ b/src/features/messages/ThreadPanel.arranger.test.tsx
@@ -196,7 +196,7 @@ it("opens a thread at a row the host never loaded, ranks by Top, and leaves the
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;
@@ -231,7 +231,7 @@ it("returns the host's rows when withdrawn, at the row it was reading or the nea
partial: false,
endMessageId: undefined,
});
-}, 30_000);
+});
it("reads a thread it shows whole through to its last row", async () => {
await mount(small.root.id, small);
@@ -246,4 +246,4 @@ it("reads a thread it shows whole through to its last row", async () => {
});
fireEvent.click(screen.getByRole("button", { name: "Buzz order" }));
expect(lastReading().endMessageId).toBeUndefined();
-}, 30_000);
+});
diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx
index fac4c7fcb2..d35dae44b5 100644
--- a/src/features/messages/arranger-plugin.test.tsx
+++ b/src/features/messages/arranger-plugin.test.tsx
@@ -551,7 +551,7 @@ it("reaches the last reply of an Oldest list by Next, reading forward as it goes
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;
@@ -819,7 +819,7 @@ it("reads the whole thread again after a reconnect once it is visible, and is no
.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;
@@ -852,7 +852,7 @@ it("keeps an Oldest list in order when replies arrive before the read reaches th
);
}
expect(h.shown().slice(-30)).toEqual(idsOf(late));
-}, 60_000);
+});
async function hostChannel(h: Harness) {
void h.session.channels.refresh?.(CHANNEL);
@@ -941,7 +941,7 @@ it("ranks a new live message in a channel's Top list", async () => {
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 });
@@ -968,4 +968,4 @@ it("pages a channel's Top list past the reader's 2,400 rows", async () => {
h.click("Next");
await statusIs(h, replies(4801, 5000, 5000, "Messages"));
expect(h.shown()).toEqual(idsOf(want.top.slice(4800)));
-}, 120_000);
+});
From dfa0ddc2c39cb65b1a914ab9c2eec03e56737bdd Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 14:57:44 -0500
Subject: [PATCH 07/37] test(messages): find the arranger tests' thread rows by
tag name
The tests' getBoundingClientRect stub places each row by its index in
the thread list, and it found that list with a document-wide selector
query on every call. Under jsdom that query took most of the two slow
tests' time: about 1.9 s each on a separate Linux machine and up to
4.1 s on CI. The stub now reads the list's articles, which the mocked
MessageRow renders, and each test takes about 0.6 s. In a check run,
both lookups returned the same rows at all 525 calls.
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
---
src/features/messages/ThreadPanel.arranger.test.tsx | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/features/messages/ThreadPanel.arranger.test.tsx b/src/features/messages/ThreadPanel.arranger.test.tsx
index 2b97cbb296..a018bf97d1 100644
--- a/src/features/messages/ThreadPanel.arranger.test.tsx
+++ b/src/features/messages/ThreadPanel.arranger.test.tsx
@@ -106,9 +106,9 @@ beforeEach(() => {
const rowIds = () =>
[
- ...document.querySelectorAll(
- "[data-thread-rows] ol [data-message-id]",
- ),
+ ...(document
+ .querySelector("[data-thread-rows] ol")
+ ?.getElementsByTagName("article") ?? []),
].map((row) => row.dataset.messageId ?? "");
const drawn = () =>
[...document.querySelectorAll("[data-thread-rows] article")].map(
From 5536e64577be56a1f545614473d2ff8f1ccb70fe Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 21:48:52 -0500
Subject: [PATCH 08/37] refactor(arranger): drop root_aux from thread window
reads
The relay no longer takes `root_aux`, so every thread window page with
`include_aux: true` carries the root's reactions, edits and deletions
along with its rows'. The reference plugin keeps them once, and they
change no ranking, because the root is not one of the rows it arranges.
The binding vector drops its trailing `root_aux` element, the fixture
relay's thread aux is the two-hop closure of the root and the page's
rows, as the relay's is, and the plugin guide no longer mentions the
flag.
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
---
docs/plugin-architecture.md | 5 ++---
src/features/messages/arranger-plugin.test.tsx | 10 +---------
src/features/relay/events.ts | 4 +---
src/features/relay/thread-window.test.ts | 14 +++++---------
src/features/relay/thread-window.ts | 1 -
src/features/relay/transport.ts | 2 +-
tests/fixtures/conversation-arranger/plugin.ts | 8 +-------
tests/fixtures/conversation-arranger/relay.ts | 5 +----
8 files changed, 12 insertions(+), 37 deletions(-)
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index 790afb616c..d529699a6a 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -1819,9 +1819,8 @@ Three session capabilities serve a plugin that scans:
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.
+from the previous page's cursor. Without it, read older pages only; the final
+rows are the same and the scan is slower.
The scan pattern:
diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx
index d35dae44b5..5ace0eb706 100644
--- a/src/features/messages/arranger-plugin.test.tsx
+++ b/src/features/messages/arranger-plugin.test.tsx
@@ -354,18 +354,12 @@ it("ranks a 2,000-reply thread by Top from background reads, leaving the host's
.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,
);
const pages = h.answers.filter((page) => page.some((e) => e.kind === 39007));
expect(pages).toHaveLength(6);
expect(h.answers.flat().every(hasEventProof)).toBe(true);
- expect(
- h.answers
- .flat()
- .some((e) => e.kind === REACTION && marked(e, "e").includes(root.id)),
- ).toBe(false);
expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200)));
expect(want.score(h.shown()[0] as string)).toBe(20);
@@ -631,7 +625,6 @@ it("paints Oldest first from the reads its first window needs and pages forward
expect(page).toMatchObject({
thread_window: true,
direction: "newer",
- root_aux: false,
});
expect(page?.after).toBeUndefined();
expect(reads.every(({ priority }) => priority === "background")).toBe(true);
@@ -642,7 +635,7 @@ it("paints Oldest first from the reads its first window needs and pages forward
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).toMatchObject({ direction: "newer" });
expect(next?.after).toBeDefined();
expect(next?.after_id).toBeDefined();
});
@@ -662,7 +655,6 @@ it("reads a thread through older pages alone when the relay has no newer windows
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)));
});
diff --git a/src/features/relay/events.ts b/src/features/relay/events.ts
index c589d36260..7e9cf99033 100644
--- a/src/features/relay/events.ts
+++ b/src/features/relay/events.ts
@@ -46,12 +46,10 @@ export type ReadFilter = Readonly<{
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. */
+ * `newer` pages oldest first from `after`/`after_id`. */
direction?: "older" | "newer";
after?: number;
after_id?: string;
- root_aux?: boolean;
thread_cursor?: number;
thread_cursor_id?: string;
}>;
diff --git a/src/features/relay/thread-window.test.ts b/src/features/relay/thread-window.test.ts
index 49d608a1d6..3cfdf0deff 100644
--- a/src/features/relay/thread-window.test.ts
+++ b/src/features/relay/thread-window.test.ts
@@ -144,11 +144,10 @@ it("keeps the older binding when direction and root aux are explicit defaults",
);
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: "older" })).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 () => {
+it("binds a forward page as the relay's vector", async () => {
const filter: ReadFilter = {
thread_window: true,
"#h": [channel],
@@ -158,16 +157,15 @@ it("binds a forward page that leaves root aux out as the relay's vector", async
direction: "newer",
after: 5,
after_id: "ef".repeat(32),
- root_aux: false,
};
- 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"]`;
+ const canonical = `["tw",1,"newer","relay.example","${"ab".repeat(32)}","${channel}","${"cd".repeat(32)}",50,100,[9],[5,"${"ef".repeat(32)}"],false]`;
expect(createHash("sha256").update(canonical).digest("hex")).toBe(
- "a417629c808147bf1592cab56498fd1137bda02e04450ba5aa6fc15d39d63c73",
+ "121bd4071006f4578547bba5c39ea6f733905fd5b67b6b09f88261e61a62075f",
);
expect(
await threadBinding(filter, "https://relay.example", "ab".repeat(32)),
).toBe(
- "tw:1:a417629c808147bf1592cab56498fd1137bda02e04450ba5aa6fc15d39d63c73",
+ "tw:1:121bd4071006f4578547bba5c39ea6f733905fd5b67b6b09f88261e61a62075f",
);
});
describe("forward thread pages", () => {
@@ -181,7 +179,6 @@ describe("forward thread pages", () => {
direction: "newer",
after: at.created_at,
after_id: at.id,
- root_aux: false,
};
const newerBound = (filter: ReadFilter, content: Record) => {
const digest = createHash("sha256")
@@ -199,7 +196,6 @@ describe("forward thread pages", () => {
[9],
filter.after === undefined ? null : [filter.after, filter.after_id],
false,
- ...(filter.root_aux === false ? ["root_aux:false"] : []),
]),
)
.digest("hex");
diff --git a/src/features/relay/thread-window.ts b/src/features/relay/thread-window.ts
index 0633d4cae4..8c67d32a5e 100644
--- a/src/features/relay/thread-window.ts
+++ b/src/features/relay/thread-window.ts
@@ -58,7 +58,6 @@ export async function threadBinding(
[...new Set(filter.kinds)].sort((a, b) => a - b),
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",
diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts
index c2f12b058a..72495e3748 100644
--- a/src/features/relay/transport.ts
+++ b/src/features/relay/transport.ts
@@ -175,7 +175,7 @@ export interface ReadTransport {
* `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`. */
+ * accept `direction: "newer"`. */
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. */
diff --git a/tests/fixtures/conversation-arranger/plugin.ts b/tests/fixtures/conversation-arranger/plugin.ts
index 1ba10cbf0a..a4666a67ae 100644
--- a/tests/fixtures/conversation-arranger/plugin.ts
+++ b/tests/fixtures/conversation-arranger/plugin.ts
@@ -129,7 +129,6 @@ function createArranger(initial: ComposerAccessoryProps) {
lanes: readonly (readonly [Lane, Cursor | undefined])[],
signal: AbortSignal,
) {
- const windowed = props.session.windowNewer === true;
const root = rootId();
const filters = lanes.map(([lane, cursor]) => {
const newer = lane === "newer";
@@ -139,12 +138,7 @@ function createArranger(initial: ComposerAccessoryProps) {
limit: PAGE,
include_aux: true,
...(root
- ? {
- thread_window: true,
- "#e": [root],
- depth_limit: 100,
- ...(windowed ? { root_aux: false as const } : {}),
- }
+ ? { thread_window: true, "#e": [root], depth_limit: 100 }
: { top_level: true }),
...(newer ? { direction: "newer" as const } : {}),
...(cursor
diff --git a/tests/fixtures/conversation-arranger/relay.ts b/tests/fixtures/conversation-arranger/relay.ts
index aa038ae9e6..733c7e16cb 100644
--- a/tests/fixtures/conversation-arranger/relay.ts
+++ b/tests/fixtures/conversation-arranger/relay.ts
@@ -206,10 +206,7 @@ export function createRelay(options: {
return [
...shown,
...(filter.include_aux
- ? [
- ...world.closure(shown.map((e) => e.id)),
- ...(filter.root_aux === false ? [] : world.auxOf([roots])),
- ]
+ ? world.closure([roots, ...shown.map((e) => e.id)])
: []),
await bound(
relay,
From 015457414828a37bb01ef3532f13f3d9aa146050 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 22:19:36 -0500
Subject: [PATCH 09/37] feat(arranger): read a heavy root's reply aux by id
when the relay refuses
A thread page's aux closure includes the root's reactions, edits and
deletions on every page, and both lanes of a request scan them. The
relay counts every row a request's windows and their aux read against
one 8,192-row budget and answers 503 past it, so a root with a few
thousand reactions made every Top scan fail.
When a thread page with its closure gets a 503, the reference plugin
reads that page again with `include_aux: false`, then reads its replies'
reactions, edits and deletions with `#e` reads of their ids, paged with
`until` and `before_id` until a page comes back empty. It keeps doing so
for that root, so a rescan never makes the relay refuse the same work
again. Other threads keep the closure, which reads on each page's own
session.
The fixture relay models the budget, answers `#e` reads in pages and
leaves out events their author deleted, as the relay does. The plugin
guide gives both ways to read a thread's aux.
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
---
docs/plugin-architecture.md | 6 +-
.../messages/arranger-plugin.test.tsx | 57 +++++++++++-
.../fixtures/conversation-arranger/plugin.ts | 90 +++++++++++++++----
tests/fixtures/conversation-arranger/relay.ts | 44 +++++++--
4 files changed, 170 insertions(+), 27 deletions(-)
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index d529699a6a..dccf16bd62 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -1826,7 +1826,11 @@ 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.
+ bounded and are not a place to hold a scan. A thread page's aux closure
+ repeats the root's aux; if the relay refuses a page (503) for a root with
+ many reactions, read that thread with `include_aux: false` and its replies'
+ reactions, edits and deletions with `#e` reads of their ids, paged with
+ `until` and `before_id` until a page comes back empty.
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.
diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx
index 5ace0eb706..febbaf6d62 100644
--- a/src/features/messages/arranger-plugin.test.tsx
+++ b/src/features/messages/arranger-plugin.test.tsx
@@ -157,12 +157,21 @@ type Mount = {
windowNewer?: boolean;
probe?: boolean;
targetId?: string;
+ windowRows?: number;
};
-async function mount({ fixture, rootId, windowNewer, probe, targetId }: Mount) {
+async function mount({
+ fixture,
+ rootId,
+ windowNewer,
+ probe,
+ targetId,
+ windowRows,
+}: Mount) {
const world = createWorld(fixture.events);
const relay = openSession({
world,
...(windowNewer === undefined ? {} : { windowNewer }),
+ ...(windowRows === undefined ? {} : { windowRows }),
});
const answers: (readonly RelayEvent[])[] = [];
const read = relay.session.snapshotRead;
@@ -373,6 +382,52 @@ it("ranks a 2,000-reply thread by Top from background reads, leaving the host's
expect(h.session.channels.window(CHANNEL)).toEqual(window);
});
+it("reads a heavy root's replies' reactions by id once the relay refuses its pages' aux", async () => {
+ const { root } = thread;
+ const onRoot = await prove(
+ Array.from({ length: 500 }, (_, i) =>
+ mint(thread.reactors[i % thread.reactors.length] as never, {
+ kind: REACTION,
+ content: "👍",
+ created_at: root.created_at + 1 + i,
+ tags: [
+ ["h", CHANNEL],
+ ["e", root.id],
+ ],
+ }),
+ ),
+ );
+ const heavy = { ...thread, events: [...thread.events, ...onRoot] };
+ const want = oracle(heavy.events, root.id);
+ const h = await mount({ fixture: heavy, rootId: root.id, windowRows: 1200 });
+ const before = h.reads.length;
+ h.click("Top");
+ await ready(h);
+
+ const filters = h.scanReads(before).flatMap(({ filters }) => filters);
+ const windows = filters.filter((filter) => filter.thread_window);
+ expect(windows.map((filter) => filter.include_aux)).toEqual([
+ true,
+ true,
+ ...windows.slice(2).map(() => false),
+ ]);
+ expect(windows.slice(0, 2)).toEqual(
+ windows.slice(2, 4).map((filter) => ({ ...filter, include_aux: true })),
+ );
+ const pages = h.answers.filter((page) => page.some((e) => e.kind === 39007));
+ const aux = filters.filter((filter) => !filter.thread_window && filter["#e"]);
+ expect(new Set(aux.flatMap((filter) => filter["#e"] ?? []))).toEqual(
+ new Set(
+ pages
+ .flat()
+ .filter((e) => e.kind === 9 && e.id !== root.id)
+ .map((e) => e.id),
+ ),
+ );
+ expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200)));
+ expect(want.score(h.shown()[0] as string)).toBe(20);
+});
+
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);
diff --git a/tests/fixtures/conversation-arranger/plugin.ts b/tests/fixtures/conversation-arranger/plugin.ts
index a4666a67ae..d19e4ca537 100644
--- a/tests/fixtures/conversation-arranger/plugin.ts
+++ b/tests/fixtures/conversation-arranger/plugin.ts
@@ -23,6 +23,7 @@ const SMALLEST = 20;
const JITTER_MS = 10_000;
const BOUNDS = { thread: 39007, channel: 39006 } as const;
const AUX = new Set([5, 7, 40003]);
+const AUX_PAGE = 500;
/** The scan's whole life, as one value. A new sort, a withdraw or unmount aborts `scanning`. */
type Phase =
@@ -74,6 +75,7 @@ function createArranger(initial: ComposerAccessoryProps) {
let starts = [0];
const events = new Map();
let hold: Hold | undefined;
+ let closureRefused: string | undefined;
let scanned = false;
let forward: Cursor | null | undefined;
let shown = 0;
@@ -125,30 +127,71 @@ function createArranger(initial: ComposerAccessoryProps) {
}
}
+ async function replyAux(ids: readonly string[], signal: AbortSignal) {
+ const found: RelayEvent[] = [];
+ let cursor: Cursor | undefined;
+ while (ids.length) {
+ const page = await read(
+ [
+ {
+ kinds: [5, 7, 9005, 40003],
+ "#e": [...ids],
+ limit: AUX_PAGE,
+ ...(cursor
+ ? { until: cursor.created_at, before_id: cursor.id }
+ : {}),
+ },
+ ],
+ signal,
+ );
+ const last = page.reduce(
+ (end, event) => (!end || inOrder(event, end) < 0 ? event : end),
+ undefined,
+ );
+ if (!last) return found;
+ if (cursor && inOrder(last, cursor) >= 0)
+ throw new Error("The relay did not page reactions");
+ found.push(...page);
+ cursor = { created_at: last.created_at, id: last.id };
+ }
+ return found;
+ }
+
async function pages(
lanes: readonly (readonly [Lane, Cursor | undefined])[],
signal: AbortSignal,
) {
const root = rootId();
- const filters = lanes.map(([lane, cursor]) => {
- const newer = lane === "newer";
- return {
- "#h": [props.channelId],
- kinds: [9],
- limit: PAGE,
- include_aux: true,
- ...(root
- ? { thread_window: true, "#e": [root], depth_limit: 100 }
- : { 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);
+ let closure = !root || closureRefused !== root;
+ const windows = () =>
+ lanes.map(([lane, cursor]) => {
+ const newer = lane === "newer";
+ return {
+ "#h": [props.channelId],
+ kinds: [9],
+ limit: PAGE,
+ include_aux: closure,
+ ...(root
+ ? { thread_window: true, "#e": [root], depth_limit: 100 }
+ : { 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 }
+ : {}),
+ };
+ });
+ let answer: readonly RelayEvent[];
+ try {
+ answer = await read(windows(), signal);
+ } catch (error) {
+ if (!root || !closure || (error as { status?: unknown }).status !== 503)
+ throw error;
+ closureRefused = root;
+ closure = false;
+ answer = await read(windows(), signal);
+ }
const bodies = answer
.filter((event) => event.kind === kindOfBounds())
.map(
@@ -160,6 +203,15 @@ function createArranger(initial: ComposerAccessoryProps) {
},
);
keep(answer);
+ if (!closure)
+ keep(
+ await replyAux(
+ answer
+ .filter((event) => event.kind === 9 && event.id !== root)
+ .map((event) => event.id),
+ signal,
+ ),
+ );
return lanes.map(([lane]) => {
const body = bodies.find((b) => (b.direction ?? "older") === lane);
if (!body) throw new Error("The relay sent no window bounds");
diff --git a/tests/fixtures/conversation-arranger/relay.ts b/tests/fixtures/conversation-arranger/relay.ts
index 733c7e16cb..b72f9977e4 100644
--- a/tests/fixtures/conversation-arranger/relay.ts
+++ b/tests/fixtures/conversation-arranger/relay.ts
@@ -4,6 +4,7 @@ import type {
ReadFilter,
RelayEvent,
} from "../../../src/features/relay/events";
+import { ReadError } from "../../../src/features/relay/errors";
import { createEventVerifier } from "../../../src/features/relay/events";
import {
newReadJournal,
@@ -91,6 +92,7 @@ export type ReadRecord = {
};
const auxKinds = new Set([REACTION, EDIT, DELETION]);
+const WINDOW_ROWS = 8192;
const targetsOf = (event: EventData) =>
event.tags.flatMap(([name, id]) => (name === "e" && id ? [id] : []));
const ascending = (a: EventData, b: EventData) => relayOrder(a, b);
@@ -134,6 +136,10 @@ export function createWorld(events: readonly RelayEvent[] = []) {
return [...new Map([...first, ...second].map((e) => [e.id, e])).values()];
},
auxOf: (ids: readonly string[]) => ids.flatMap((id) => aux.get(id) ?? []),
+ deleted: (event: RelayEvent) =>
+ (aux.get(event.id) ?? []).some(
+ (e) => e.kind === 5 && e.pubkey === event.pubkey,
+ ),
};
world.add(events);
return world;
@@ -185,8 +191,11 @@ export function createRelay(options: {
relay: Key;
/** Reads held back until released, for ordering tests. */
hold?: (filters: readonly ReadFilter[]) => Promise | undefined;
+ /** The rows one request's thread windows may read, with their aux. */
+ windowRows?: number;
}) {
const { world, viewer, relay } = options;
+ const windowRows = options.windowRows ?? WINDOW_ROWS;
const reads: ReadRecord[] = [];
const members = roster(relay, CHANNEL, [viewer.pubkey], 1);
const channelMeta = metadata(relay, CHANNEL, "Arranger fixture", 1);
@@ -263,11 +272,21 @@ export function createRelay(options: {
),
];
}
- if (filter["#e"])
- return world
- .auxOf(filter["#e"])
- .filter((e) => e.created_at >= (filter.since ?? 0))
- .slice(0, page);
+ if (filter["#e"]) {
+ const kinds = new Set(filter.kinds ?? []);
+ const found = new Map(
+ world
+ .auxOf(filter["#e"])
+ .filter(
+ (e) =>
+ (!kinds.size || kinds.has(e.kind)) &&
+ e.created_at >= (filter.since ?? 0) &&
+ !world.deleted(e),
+ )
+ .map((e) => [e.id, e]),
+ );
+ return after([...found.values()].sort(ascending), filter).slice(0, page);
+ }
return [];
}
const transport: ReadTransport = {
@@ -279,7 +298,19 @@ export function createRelay(options: {
reads.push({ filters, priority });
await options.hold?.(filters);
if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
- return (await Promise.all(filters.map(answer))).flat();
+ const answers = await Promise.all(filters.map(answer));
+ const rows = answers.reduce(
+ (sum, events, i) =>
+ filters[i]?.thread_window ? sum + events.length - 1 : sum,
+ 0,
+ );
+ if (rows > windowRows)
+ throw new ReadError(
+ "unavailable",
+ "thread window exceeds its row budget",
+ 503,
+ );
+ return answers.flat();
},
};
return { transport, reads, members, channelMeta };
@@ -292,6 +323,7 @@ export function openSession(options: {
viewer?: Key;
relay?: Key;
hold?: (filters: readonly ReadFilter[]) => Promise | undefined;
+ windowRows?: number;
}) {
const viewer = options.viewer ?? keypair();
const relay = options.relay ?? keypair();
From ed7a1aeda6d9f9caba217214a23e970d07cd050a Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 22:38:56 -0500
Subject: [PATCH 10/37] fix(arranger): scope the heavy-root aux reads as the
closure does
Read replies' aux in the channel by #h, plus kind 5 and 9005 deletions
that carry no h tag, hold each page as it arrives so a live deletion of
an event already read is kept, and remember a root's refusal only after
its fallback page completes. Follow kind 9005 live.
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
docs/plugin-architecture.md | 9 +-
.../messages/arranger-plugin.test.tsx | 124 ++++++++++++++----
.../fixtures/conversation-arranger/plugin.ts | 75 ++++++-----
tests/fixtures/conversation-arranger/relay.ts | 11 +-
4 files changed, 156 insertions(+), 63 deletions(-)
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index dccf16bd62..1e66b46c04 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -1828,9 +1828,12 @@ The scan pattern:
with `readPage`: it feeds the host's own views and unread counts, which are
bounded and are not a place to hold a scan. A thread page's aux closure
repeats the root's aux; if the relay refuses a page (503) for a root with
- many reactions, read that thread with `include_aux: false` and its replies'
- reactions, edits and deletions with `#e` reads of their ids, paged with
- `until` and `before_id` until a page comes back empty.
+ many reactions, read that thread with `include_aux: false`. Then read its
+ replies' reactions, edits and deletions with `#e` reads of their ids, as the
+ closure does: one read names the channel in `#h`, and one reads kinds 5 and
+ 9005 without it, for deletions that carry no `h` tag. Page each with `until`
+ and `before_id` until a page comes back empty, and hold each page as it
+ arrives, so that a live deletion of an event already read is not dropped.
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.
diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx
index febbaf6d62..cb6820ef26 100644
--- a/src/features/messages/arranger-plugin.test.tsx
+++ b/src/features/messages/arranger-plugin.test.tsx
@@ -19,6 +19,7 @@ import * as arranger from "../../../tests/fixtures/conversation-arranger/plugin"
import {
CHANNEL,
createWorld,
+ DELETION,
EDIT,
mint,
openSession,
@@ -75,7 +76,7 @@ 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)
+ if (event.kind === 5 || event.kind === 9005)
for (const id of marked(event, "e"))
if (byId.get(id)?.pubkey === event.pubkey) deleted.add(id);
const rows = events.filter(
@@ -158,6 +159,8 @@ type Mount = {
probe?: boolean;
targetId?: string;
windowRows?: number;
+ namedOnly?: boolean;
+ hold?: Parameters[0]["hold"];
};
async function mount({
fixture,
@@ -166,12 +169,16 @@ async function mount({
probe,
targetId,
windowRows,
+ namedOnly,
+ hold,
}: Mount) {
const world = createWorld(fixture.events);
const relay = openSession({
world,
...(windowNewer === undefined ? {} : { windowNewer }),
...(windowRows === undefined ? {} : { windowRows }),
+ ...(namedOnly === undefined ? {} : { namedOnly }),
+ ...(hold === undefined ? {} : { hold }),
});
const answers: (readonly RelayEvent[])[] = [];
const read = relay.session.snapshotRead;
@@ -383,7 +390,7 @@ it("ranks a 2,000-reply thread by Top from background reads, leaving the host's
});
it("reads a heavy root's replies' reactions by id once the relay refuses its pages' aux", async () => {
- const { root } = thread;
+ const { root, authors, reactors } = thread;
const onRoot = await prove(
Array.from({ length: 500 }, (_, i) =>
mint(thread.reactors[i % thread.reactors.length] as never, {
@@ -397,11 +404,73 @@ it("reads a heavy root's replies' reactions by id once the relay refuses its pag
}),
),
);
- const heavy = { ...thread, events: [...thread.events, ...onRoot] };
- const want = oracle(heavy.events, root.id);
- const h = await mount({ fixture: heavy, rootId: root.id, windowRows: 1200 });
+ const best = oracle(thread.events, root.id).top[0] as RelayEvent;
+ const unscoped = await prove([
+ mint(authors.find((key) => key.pubkey === best.pubkey) as never, {
+ kind: DELETION,
+ content: "",
+ created_at: T + 20_000,
+ tags: [["e", best.id]],
+ }),
+ ]);
+ const heavy = {
+ ...thread,
+ events: [...thread.events, ...onRoot, ...unscoped],
+ };
+ let paused!: () => void;
+ let release: (() => void) | undefined;
+ const held = new Promise((resolve) => {
+ paused = resolve;
+ });
+ const h = await mount({
+ fixture: heavy,
+ rootId: root.id,
+ windowRows: 1200,
+ namedOnly: true,
+ hold: (filters) =>
+ !release &&
+ filters.some(
+ (filter) => !filter.thread_window && filter["#h"] && filter.until,
+ )
+ ? new Promise((resolve) => {
+ release = resolve;
+ paused();
+ })
+ : undefined,
+ });
const before = h.reads.length;
h.click("Top");
+ await held;
+ const page = h.answers.at(-1) ?? [];
+ const counts = new Map();
+ for (const event of page)
+ if (event.kind === REACTION) {
+ const target = event.tags.find(([name]) => name === "e")?.[1] as string;
+ counts.set(target, (counts.get(target) ?? 0) + 1);
+ }
+ const [most] = [...counts].sort((a, b) => b[1] - a[1])[0] ?? [];
+ const gone = await prove(
+ page
+ .filter(
+ (event) =>
+ event.kind === REACTION && event.tags.some(([, id]) => id === most),
+ )
+ .map((event) =>
+ mint(reactors.find((key) => key.pubkey === event.pubkey) as never, {
+ kind: DELETION,
+ content: "",
+ created_at: T + 30_000,
+ tags: [
+ ["h", CHANNEL],
+ ["e", event.id],
+ ],
+ }),
+ ),
+ );
+ h.world.add(gone);
+ h.heard(...gone);
+ h.flush();
+ release?.();
await ready(h);
const filters = h.scanReads(before).flatMap(({ filters }) => filters);
@@ -414,7 +483,9 @@ it("reads a heavy root's replies' reactions by id once the relay refuses its pag
expect(windows.slice(0, 2)).toEqual(
windows.slice(2, 4).map((filter) => ({ ...filter, include_aux: true })),
);
- const pages = h.answers.filter((page) => page.some((e) => e.kind === 39007));
+ const pages = h.answers.filter((answer) =>
+ answer.some((e) => e.kind === 39007),
+ );
const aux = filters.filter((filter) => !filter.thread_window && filter["#e"]);
expect(new Set(aux.flatMap((filter) => filter["#e"] ?? []))).toEqual(
new Set(
@@ -424,6 +495,11 @@ it("reads a heavy root's replies' reactions by id once the relay refuses its pag
.map((e) => e.id),
),
);
+ const want = oracle([...heavy.events, ...gone], root.id);
+ expect(want.top.slice(0, 200)).not.toEqual(
+ oracle(heavy.events, root.id).top.slice(0, 200),
+ );
+ expect(h.shown()).not.toContain(best.id);
expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200)));
expect(want.score(h.shown()[0] as string)).toBe(20);
});
@@ -622,29 +698,31 @@ it("re-ranks when a reaction lands on a row that is not shown", async () => {
expect(h.arrangement.snapshot()?.rows[0]?.reactions).not.toHaveLength(0);
});
-it("hides a shown row when its deletion arrives live", async () => {
+it("hides shown rows when their deletions arrive 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],
- ],
+ const shown = h.shown().slice(0, 2);
+ const gone = await prove(
+ [5, 9005].map((kind, i) => {
+ const row = events.find((event) => event.id === shown[i]) as RelayEvent;
+ return mint(authors.find((key) => key.pubkey === row.pubkey) as never, {
+ kind,
+ content: "",
+ created_at: T + 20_000,
+ tags: [
+ ["h", CHANNEL],
+ ["e", row.id],
+ ],
+ });
}),
- ]);
- h.heard(gone as RelayEvent);
+ );
+ h.heard(...gone);
h.flush();
- const want = oracle([...events, gone as RelayEvent], root.id);
- await waitFor(() => expect(h.shown()).not.toContain(first));
+ const want = oracle([...events, ...gone], root.id);
+ await waitFor(() => expect(h.shown()).not.toContain(shown[0]));
+ expect(h.shown()).not.toContain(shown[1]);
expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200)));
});
diff --git a/tests/fixtures/conversation-arranger/plugin.ts b/tests/fixtures/conversation-arranger/plugin.ts
index d19e4ca537..1b78e016f2 100644
--- a/tests/fixtures/conversation-arranger/plugin.ts
+++ b/tests/fixtures/conversation-arranger/plugin.ts
@@ -22,7 +22,7 @@ const HEADROOM = 200;
const SMALLEST = 20;
const JITTER_MS = 10_000;
const BOUNDS = { thread: 39007, channel: 39006 } as const;
-const AUX = new Set([5, 7, 40003]);
+const AUX = new Set([5, 7, 9005, 40003]);
const AUX_PAGE = 500;
/** The scan's whole life, as one value. A new sort, a withdraw or unmount aborts `scanning`. */
@@ -128,33 +128,37 @@ function createArranger(initial: ComposerAccessoryProps) {
}
async function replyAux(ids: readonly string[], signal: AbortSignal) {
- const found: RelayEvent[] = [];
- let cursor: Cursor | undefined;
- while (ids.length) {
- const page = await read(
- [
- {
- kinds: [5, 7, 9005, 40003],
- "#e": [...ids],
- limit: AUX_PAGE,
- ...(cursor
- ? { until: cursor.created_at, before_id: cursor.id }
- : {}),
- },
- ],
- signal,
- );
- const last = page.reduce(
- (end, event) => (!end || inOrder(event, end) < 0 ? event : end),
- undefined,
- );
- if (!last) return found;
- if (cursor && inOrder(last, cursor) >= 0)
- throw new Error("The relay did not page reactions");
- found.push(...page);
- cursor = { created_at: last.created_at, id: last.id };
+ if (!ids.length) return;
+ for (const scope of [
+ { kinds: [5, 7, 9005, 40003], "#h": [props.channelId] },
+ { kinds: [5, 9005] },
+ ]) {
+ let cursor: Cursor | undefined;
+ for (;;) {
+ const page = await read(
+ [
+ {
+ ...scope,
+ "#e": [...ids],
+ limit: AUX_PAGE,
+ ...(cursor
+ ? { until: cursor.created_at, before_id: cursor.id }
+ : {}),
+ },
+ ],
+ signal,
+ );
+ const last = page.reduce(
+ (end, event) => (!end || inOrder(event, end) < 0 ? event : end),
+ undefined,
+ );
+ if (!last) break;
+ if (cursor && inOrder(last, cursor) >= 0)
+ throw new Error("The relay did not page reactions");
+ keep(page);
+ cursor = { created_at: last.created_at, id: last.id };
+ }
}
- return found;
}
async function pages(
@@ -188,7 +192,6 @@ function createArranger(initial: ComposerAccessoryProps) {
} catch (error) {
if (!root || !closure || (error as { status?: unknown }).status !== 503)
throw error;
- closureRefused = root;
closure = false;
answer = await read(windows(), signal);
}
@@ -203,15 +206,15 @@ function createArranger(initial: ComposerAccessoryProps) {
},
);
keep(answer);
- if (!closure)
- keep(
- await replyAux(
- answer
- .filter((event) => event.kind === 9 && event.id !== root)
- .map((event) => event.id),
- signal,
- ),
+ if (!closure) {
+ await replyAux(
+ answer
+ .filter((event) => event.kind === 9 && event.id !== root)
+ .map((event) => event.id),
+ signal,
);
+ closureRefused = root;
+ }
return lanes.map(([lane]) => {
const body = bodies.find((b) => (b.direction ?? "older") === lane);
if (!body) throw new Error("The relay sent no window bounds");
diff --git a/tests/fixtures/conversation-arranger/relay.ts b/tests/fixtures/conversation-arranger/relay.ts
index b72f9977e4..e29616f15b 100644
--- a/tests/fixtures/conversation-arranger/relay.ts
+++ b/tests/fixtures/conversation-arranger/relay.ts
@@ -193,6 +193,8 @@ export function createRelay(options: {
hold?: (filters: readonly ReadFilter[]) => Promise | undefined;
/** The rows one request's thread windows may read, with their aux. */
windowRows?: number;
+ /** A channel that a read reaches only by naming it in `#h`. */
+ namedOnly?: boolean;
}) {
const { world, viewer, relay } = options;
const windowRows = options.windowRows ?? WINDOW_ROWS;
@@ -274,6 +276,7 @@ export function createRelay(options: {
}
if (filter["#e"]) {
const kinds = new Set(filter.kinds ?? []);
+ const named = filter["#h"];
const found = new Map(
world
.auxOf(filter["#e"])
@@ -281,7 +284,12 @@ export function createRelay(options: {
(e) =>
(!kinds.size || kinds.has(e.kind)) &&
e.created_at >= (filter.since ?? 0) &&
- !world.deleted(e),
+ !world.deleted(e) &&
+ (named
+ ? e.tags.some(
+ ([name, id]) => name === "h" && named.includes(id ?? ""),
+ )
+ : !options.namedOnly || !e.tags.some(([name]) => name === "h")),
)
.map((e) => [e.id, e]),
);
@@ -324,6 +332,7 @@ export function openSession(options: {
relay?: Key;
hold?: (filters: readonly ReadFilter[]) => Promise | undefined;
windowRows?: number;
+ namedOnly?: boolean;
}) {
const viewer = options.viewer ?? keypair();
const relay = options.relay ?? keypair();
From 39c56d6bb636bce186f771a92316966273bd3439 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 22:49:51 -0500
Subject: [PATCH 11/37] docs(plugins): say a busy thread's page can be refused,
not only a heavy root's
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
docs/plugin-architecture.md | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index 1e66b46c04..a27d440877 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -1827,8 +1827,9 @@ 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. A thread page's aux closure
- repeats the root's aux; if the relay refuses a page (503) for a root with
- many reactions, read that thread with `include_aux: false`. Then read its
+ repeats the root's aux, and one request's windows share the relay's scan
+ budget; if the relay refuses a busy thread's page (503), read that thread
+ with `include_aux: false`. Then read its
replies' reactions, edits and deletions with `#e` reads of their ids, as the
closure does: one read names the channel in `#h`, and one reads kinds 5 and
9005 without it, for deletions that carry no `h` tag. Page each with `until`
From 61a850d8854a8c3b7f8c846378b3a4158f2694ee Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Wed, 18 Nov 2026 22:55:41 -0500
Subject: [PATCH 12/37] test(arranger): serve 9005 deletions from the fixture
relay and test an h-less one in the fallback
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
.../messages/arranger-plugin.test.tsx | 24 ++++++++++++-------
tests/fixtures/conversation-arranger/relay.ts | 2 +-
2 files changed, 16 insertions(+), 10 deletions(-)
diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx
index cb6820ef26..812ac87874 100644
--- a/src/features/messages/arranger-plugin.test.tsx
+++ b/src/features/messages/arranger-plugin.test.tsx
@@ -404,15 +404,20 @@ it("reads a heavy root's replies' reactions by id once the relay refuses its pag
}),
),
);
- const best = oracle(thread.events, root.id).top[0] as RelayEvent;
- const unscoped = await prove([
- mint(authors.find((key) => key.pubkey === best.pubkey) as never, {
- kind: DELETION,
- content: "",
- created_at: T + 20_000,
- tags: [["e", best.id]],
- }),
- ]);
+ const [best, next] = oracle(thread.events, root.id).top.slice(0, 2) as [
+ RelayEvent,
+ RelayEvent,
+ ];
+ const unscoped = await prove(
+ [best, next].map((row, i) =>
+ mint(authors.find((key) => key.pubkey === row.pubkey) as never, {
+ kind: i ? 9005 : DELETION,
+ content: "",
+ created_at: T + 20_000,
+ tags: [["e", row.id]],
+ }),
+ ),
+ );
const heavy = {
...thread,
events: [...thread.events, ...onRoot, ...unscoped],
@@ -500,6 +505,7 @@ it("reads a heavy root's replies' reactions by id once the relay refuses its pag
oracle(heavy.events, root.id).top.slice(0, 200),
);
expect(h.shown()).not.toContain(best.id);
+ expect(h.shown()).not.toContain(next.id);
expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200)));
expect(want.score(h.shown()[0] as string)).toBe(20);
});
diff --git a/tests/fixtures/conversation-arranger/relay.ts b/tests/fixtures/conversation-arranger/relay.ts
index e29616f15b..a56f8040d3 100644
--- a/tests/fixtures/conversation-arranger/relay.ts
+++ b/tests/fixtures/conversation-arranger/relay.ts
@@ -91,7 +91,7 @@ export type ReadRecord = {
priority: string | undefined;
};
-const auxKinds = new Set([REACTION, EDIT, DELETION]);
+const auxKinds = new Set([REACTION, EDIT, DELETION, 9005]);
const WINDOW_ROWS = 8192;
const targetsOf = (event: EventData) =>
event.tags.flatMap(([name, id]) => (name === "e" && id ? [id] : []));
From c37dc23f61d7583d5e3ce1d5c19273b2cdd9f7a4 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Thu, 19 Nov 2026 12:46:56 -0500
Subject: [PATCH 13/37] fix(relay): keep streamed replies in a thread view past
its cursor
A thread view dropped live and replayed replies older than its oldest
page, so a reply from a skewed clock, or one sent while the client was
away, never showed. Mark every subscription delivery as streamed and
pass that to session observers; only finite reads (readPage and
snapshotRead scans) stay limited to the view's window.
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
src/features/relay/session.ts | 8 +-
src/features/relay/thread-window.test.ts | 108 ++++++++++++-----------
src/features/relay/threads.ts | 4 +-
3 files changed, 65 insertions(+), 55 deletions(-)
diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts
index 60b329845b..5ded121c96 100644
--- a/src/features/relay/session.ts
+++ b/src/features/relay/session.ts
@@ -349,7 +349,9 @@ export function createRelaySession(
revision: number;
incoming?: "replay" | "live";
}>(4096, 8 * 1024 * 1024);
- const observations = new Set<(events: readonly RelayEvent[]) => void>();
+ const observations = new Set<
+ (events: readonly RelayEvent[], stream: boolean) => void
+ >();
const incomingListeners = new Set();
const liveEventListeners = new Set();
const replayListeners = new Set();
@@ -962,6 +964,7 @@ export function createRelaySession(
) => void,
signal?: AbortSignal,
incomingPhase?: "replay" | "live",
+ stream = false,
): readonly RelayEvent[] {
if (closed) return [];
// Authority precedes every projection, even in a batch containing both a
@@ -1033,7 +1036,7 @@ export function createRelaySession(
if (channelTraffic) channels.accept(visible);
for (const listener of observations) {
if (closed || epoch !== accessEpoch) return;
- listener(visible);
+ listener(visible, stream);
}
},
visible.length,
@@ -4223,6 +4226,7 @@ export function createRelaySession(
undefined,
undefined,
provenance?.channelId ? provenance.phase : undefined,
+ true,
);
// Completion subscribers can synchronously clear, revoke or retire this
// live delivery. Do not admit its remaining pulses into the new lifetime.
diff --git a/src/features/relay/thread-window.test.ts b/src/features/relay/thread-window.test.ts
index 3cfdf0deff..5870e23e63 100644
--- a/src/features/relay/thread-window.test.ts
+++ b/src/features/relay/thread-window.test.ts
@@ -2185,63 +2185,52 @@ const headOnly = (filter: ReadFilter) =>
)
.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);
- 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]],
- }),
+it("keeps a view ready with the same rows when a session readPage scan carries 2,000 replies older than its cursor", async () => {
+ const h = await setup(headOnly);
+ await h.view.refresh();
+ const before = h.view.snapshot().replies;
+ expect(before).toHaveLength(10);
+ 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 } : {}),
+ },
]);
- 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);
- },
-);
+ 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 () => {
+it("admits a read reply at the cursor's second only when its id is at or below the cursor's, any legacy diff, and every streamed reply", 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);
- const h = await setup((filter) =>
- filter.ids ? [root] : [newer, mid, bounds(filter, cursorOf(mid))],
- );
- await h.view.refresh();
const diff = signed(author, {
kind: 40008,
content: "diff",
@@ -2251,10 +2240,27 @@ it("admits a reply at the cursor's second only when its id is at or below the cu
["e", root.id, "", "reply"],
],
});
- h.traffic.receive([low, high, diff]);
+ const h = await setup((filter) =>
+ filter.ids
+ ? [root]
+ : filter.thread_window
+ ? [newer, mid, bounds(filter, cursorOf(mid))]
+ : [low, high, diff],
+ );
+ await h.view.refresh();
+ await h.session.readPage([
+ { kinds: [9, 40008], "#h": [channel], "#e": [root.id], limit: 10 },
+ ]);
expect(h.view.snapshot().replies.map((row) => row.id)).toEqual(
[diff, low, mid, newer].map((row) => row.id),
);
+ const skewed = replyAt("from a clock 90 s behind", 45);
+ const missed = replyAt("sent while this client was away", 44);
+ h.traffic.receive([skewed]);
+ h.traffic.receive([missed], { phase: "replay", channelId: channel });
+ expect(h.view.snapshot().replies.map((row) => row.id)).toEqual(
+ [diff, missed, skewed, 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 () => {
diff --git a/src/features/relay/threads.ts b/src/features/relay/threads.ts
index ce561e1f00..6d1dd64277 100644
--- a/src/features/relay/threads.ts
+++ b/src/features/relay/threads.ts
@@ -587,10 +587,10 @@ export function createThreadView({
: cursor;
return !!edge && relayOrder(event, edge) < 0;
};
- function receive(events: readonly RelayEvent[]) {
+ function receive(events: readonly RelayEvent[], stream = false) {
if (disposed || !canAccess() || (!rootId && !exact)) return;
const fresh = events.filter(
- (event) => !remoteIds.has(event.id) && !beyond(event),
+ (event) => !remoteIds.has(event.id) && (stream || !beyond(event)),
);
if (!fresh.length) return;
const incoming = related(fresh);
From 28c6879a6398376df8db282be390e42b6b9efe7f Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Thu, 19 Nov 2026 12:47:01 -0500
Subject: [PATCH 14/37] fix(reader): reveal a link's hidden target and read
collapsed branches row by row
When a presentation leaves out the message a link or inline reveal
opened, the reader now withdraws it once per request, so the host
reveals the target. A presentation made after the target was revealed,
or a second one that leaves it out, stays, and the visit completes.
Background and returning visits never withdraw.
A presentation with collapsed branches leaves rows out, so reading
stays row by row until every branch is open.
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
src/features/conversation/contracts.ts | 4 +-
.../ChannelTimeline.presentation.test.tsx | 24 +++++--
src/features/messages/ChannelTimeline.tsx | 14 +++-
.../ThreadPanel.presentation.test.tsx | 66 +++++++++++++++++--
src/features/messages/ThreadPanel.tsx | 31 +++++++--
src/features/messages/arrangement.ts | 3 +
6 files changed, 124 insertions(+), 18 deletions(-)
diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts
index a51c5b4d88..4d839b429f 100644
--- a/src/features/conversation/contracts.ts
+++ b/src/features/conversation/contracts.ts
@@ -265,7 +265,9 @@ export type ComposerAccessoryProps = Readonly<{
| ((presentation: ConversationPresentation | null) => PresentResult)
| undefined;
/** Reader placement only: this accessory's presentation, `ended` once live
- * growth passed `limits`, until it presents again. */
+ * growth passed `limits`, until it presents again. `none` after `shown`
+ * without a withdrawal of its own: the reader took its rows back to show a
+ * message they leave out, as a link's target. */
presentation?: "none" | "shown" | "held" | "ended" | undefined;
/** Reader placement only. */
limits?: PresentationLimits | undefined;
diff --git a/src/features/messages/ChannelTimeline.presentation.test.tsx b/src/features/messages/ChannelTimeline.presentation.test.tsx
index 42bfcb7e18..7bb5847109 100644
--- a/src/features/messages/ChannelTimeline.presentation.test.tsx
+++ b/src/features/messages/ChannelTimeline.presentation.test.tsx
@@ -688,6 +688,7 @@ it("saves no Back/Forward place for a link's visit left while it presents", () =
for (let pass = 0; pass < 4; pass++) frame();
h.present({ ids: [p0.id, p1.id, p2.id] });
frame();
+ expect(h.latest.current?.presentation).toBe("shown");
fireEvent.scroll(scroller());
h.unmount();
expect(navigation.savePosition).not.toHaveBeenCalled();
@@ -706,14 +707,29 @@ it("saves the geometry of the rows shown, never filed as the host's, when it unm
expect(viewport.caches.at(-1)).toBeUndefined();
});
-it("yields a target the presentation leaves out: the navigation opens, and the plugin sees the target", () => {
+it("takes its rows back to reveal a link's target they leave out, and keeps the next presentation that leaves it out", () => {
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?.presentation).toBe("none");
expect(h.latest.current?.targetId).toBe(h1.id);
+ expect(navigation.complete).not.toHaveBeenCalled();
+ h.present({ ids: [p0.id, p1.id] });
+ expect(h.latest.current?.presentation).toBe("shown");
+ expect(navigation.complete).toHaveBeenCalledExactlyOnceWith({
+ status: "opened",
+ });
+});
+
+it("reveals a link's target after taking back the rows that left it out", () => {
+ const navigation = navigationTo(h1.id);
+ const h = mount({ props: { navigation } });
+ h.present({ ids: [p0.id, p1.id] });
+ for (let pass = 0; pass < 4; pass++) frame();
+ expect(navigation.complete).toHaveBeenCalledExactlyOnceWith({
+ status: "opened",
+ });
+ expect(h.latest.current?.presentation).toBe("none");
});
it("leaves a target the presentation shows to the host's reveal", () => {
diff --git a/src/features/messages/ChannelTimeline.tsx b/src/features/messages/ChannelTimeline.tsx
index 3dd5f499ae..12baeec383 100644
--- a/src/features/messages/ChannelTimeline.tsx
+++ b/src/features/messages/ChannelTimeline.tsx
@@ -866,9 +866,6 @@ function Timeline({
!!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.
@@ -1275,6 +1272,17 @@ function Timeline({
complete: completeTarget,
hold: holdTarget,
});
+ const withdrawnFor = useRef(undefined);
+ useLayoutEffect(() => {
+ if (!targetHidden || !targetSignal || revealedSignal === targetSignal)
+ return;
+ if (withdrawnFor.current === targetSignal)
+ navigation?.complete({ status: "opened" });
+ else {
+ withdrawnFor.current = targetSignal;
+ arrangement?.withdraw();
+ }
+ }, [targetHidden, targetSignal, revealedSignal, navigation, arrangement]);
// A return restores its visit's place the way an opening restores the
// channel's, whether the timeline mounts for it or showed another visit. The
// visit still presented only completes. A place whose row isn't loaded opens
diff --git a/src/features/messages/ThreadPanel.presentation.test.tsx b/src/features/messages/ThreadPanel.presentation.test.tsx
index 6d523b000b..6e188e3e48 100644
--- a/src/features/messages/ThreadPanel.presentation.test.tsx
+++ b/src/features/messages/ThreadPanel.presentation.test.tsx
@@ -6,6 +6,7 @@ import {
fireEvent,
render,
screen,
+ waitFor,
} from "@testing-library/react";
import { StrictMode, useLayoutEffect } from "react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
@@ -486,7 +487,10 @@ it("hides the jump button and keeps the arrivals count off while it presents", (
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 rowOf = (h: ReturnType, event: EventData) =>
+ h.rowsOf([root, event]).find((row) => row.id === event.id);
+
+it("takes its rows back to reveal a link's target they leave out, then keeps rows that leave it out", async () => {
const navigation = navigationTo(d.id);
const h = mount({
replies: [d],
@@ -495,13 +499,53 @@ it("yields a target it does not show: the visit opens, reading starts and the pl
snapshot: { targetStatus: "loading" },
});
expect(h.latest.current?.targetId).toBe(d.id);
+ h.present({ ids: [a.id, b.id] });
+ expect(h.latest.current?.presentation).toBe("none");
+ expect(drawn()).toEqual(["root", "d"]);
expect(navigation.complete).not.toHaveBeenCalled();
+ h.publish({ targetStatus: "ready", target: rowOf(h, d) });
+ await waitFor(() =>
+ expect(navigation.complete).toHaveBeenCalledExactlyOnceWith({
+ status: "opened",
+ }),
+ );
+ expect(lastReading().settled.current).toBe(true);
+ h.present({ ids: [a.id, b.id] });
+ expect(h.latest.current?.presentation).toBe("shown");
+ expect(drawn()).toEqual(["root", "a", "b"]);
+});
+
+it("keeps a second presentation that leaves out a link's target, and opens the visit", () => {
+ const navigation = navigationTo(d.id);
+ const h = mount({
+ replies: [d],
+ navigation,
+ props: { messageId: d.id },
+ snapshot: { targetStatus: "loading" },
+ });
h.present({ ids: [a.id, b.id] });
+ h.present({ ids: [a.id, b.id] });
+ expect(h.latest.current?.presentation).toBe("shown");
+ expect(drawn()).toEqual(["root", "a", "b"]);
expect(navigation.complete).toHaveBeenCalledExactlyOnceWith({
status: "opened",
});
expect(lastReading().settled.current).toBe(true);
- expect(drawn()).toEqual(["root", "a", "b"]);
+});
+
+it("leaves a background panel's rows in place when they leave out its link's target", () => {
+ const navigation = navigationTo(d.id);
+ const h = mount({
+ replies: [d],
+ navigation,
+ props: { messageId: d.id, active: false },
+ snapshot: { targetStatus: "loading" },
+ });
+ h.present({ ids: [a.id, b.id] });
+ expect(h.latest.current?.presentation).toBe("shown");
+ expect(navigation.complete).toHaveBeenCalledExactlyOnceWith({
+ status: "opened",
+ });
});
it("records no Back/Forward place for a visit left while it presents", () => {
@@ -543,7 +587,7 @@ it("shows activity rows as the plugin lists them, unfolded", () => {
).toHaveLength(0);
});
-it("starts reading when an inline reveal's row is not shown", () => {
+it("takes its rows back for an inline reveal's row they leave out, and reads once it is revealed", async () => {
const h = mount({
replies: [d],
props: { messageId: d.id, revealSelected: true, revealRequest: 1 },
@@ -551,10 +595,12 @@ it("starts reading when an inline reveal's row is not shown", () => {
});
expect(lastReading().settled.current).toBe(false);
h.present({ ids: [a.id, b.id] });
- expect(lastReading().settled.current).toBe(true);
+ expect(h.latest.current?.presentation).toBe("none");
+ h.publish({ targetStatus: "ready", target: rowOf(h, d) });
+ await waitFor(() => expect(lastReading().settled.current).toBe(true));
});
-it("wires a partial presentation's reading: its end row, its newest row, its bar", () => {
+it("wires a presentation's reading: its end row, its newest row, its bar, and row by row while partial or collapsed", () => {
const h = mount({ replies: [d] });
expect(lastReading()).toMatchObject({
partial: false,
@@ -576,6 +622,16 @@ it("wires a partial presentation's reading: its end row, its newest row, its bar
);
fireEvent.click(screen.getByRole("button", { name: /Collapse 1 reply/ }));
expect(lastReading().endMessageId).toBe(a.id);
+ h.present({
+ ids: [a.id, b.id, c.id, d.id],
+ parents: { [d.id]: c.id },
+ complete: true,
+ });
+ expect(lastReading()).toMatchObject({ partial: true, endMessageId: c.id });
+ fireEvent.click(
+ screen.getByRole("button", { name: /1 reply/, expanded: false }),
+ );
+ expect(lastReading()).toMatchObject({ partial: false, endMessageId: d.id });
h.present({ ids: [a.id, b.id, c.id, d.id], complete: true });
expect(lastReading()).toMatchObject({ partial: false, endMessageId: d.id });
h.withdraw();
diff --git a/src/features/messages/ThreadPanel.tsx b/src/features/messages/ThreadPanel.tsx
index 569573988a..5e8d84b8a3 100644
--- a/src/features/messages/ThreadPanel.tsx
+++ b/src/features/messages/ThreadPanel.tsx
@@ -792,6 +792,11 @@ function ThreadMessages({
}
return end;
}, [tree, expanded]);
+ const collapsed =
+ presented &&
+ [...tree.children.keys()].some(
+ (id) => id !== undefined && !expanded.has(id),
+ );
const resolveName = useChannelIdentityNames(session, channelId);
const senderName = (row: ChannelMessage) => {
const id = row.workflowOwnerId ?? row.authorId;
@@ -1273,9 +1278,10 @@ function ThreadMessages({
!!display &&
messageId !== resolvedRoot &&
!display.rows.some((row) => row.id === messageId);
- const revealSignal = targetHidden
- ? undefined
- : (inlineReveal ?? (positionedVisit ? undefined : navigation?.signal));
+ const requested =
+ inlineReveal ?? (positionedVisit ? undefined : navigation?.signal);
+ const revealSignal = targetHidden ? undefined : requested;
+ const withdrawnFor = useRef(undefined);
const revealed = useMessageReveal({
scroller,
focus:
@@ -1526,7 +1532,20 @@ function ThreadMessages({
revealed.current = navigation.signal;
navigation.complete({ status: "opened" });
}
- if (navigation && targetHidden && revealed.current !== navigation.signal) {
+ if (
+ targetHidden &&
+ active &&
+ requested &&
+ revealed.current !== requested &&
+ withdrawnFor.current !== requested
+ ) {
+ withdrawnFor.current = requested;
+ arrangement?.withdraw();
+ } else if (
+ navigation &&
+ targetHidden &&
+ revealed.current !== navigation.signal
+ ) {
revealed.current = navigation.signal;
navigation.complete({ status: "opened" });
}
@@ -1796,6 +1815,8 @@ function ThreadMessages({
expandedActivity,
boundary,
targetHidden,
+ requested,
+ arrangement,
]);
// 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
@@ -2367,7 +2388,7 @@ function ThreadMessages({
: undefined
}
endMessageId={presented ? endRow : undefined}
- partial={!!display && !display.complete}
+ partial={!!display && (!display.complete || collapsed)}
controls={readerBar}
/>
{arrangement && extensions?.accessories && (
diff --git a/src/features/messages/arrangement.ts b/src/features/messages/arrangement.ts
index 4e7f663d87..21d16603af 100644
--- a/src/features/messages/arrangement.ts
+++ b/src/features/messages/arrangement.ts
@@ -238,6 +238,9 @@ export function createArrangement({
emit();
return held ? "held" : "shown";
},
+ withdraw() {
+ if (shown) free();
+ },
status: (lane: ArrangementLane) =>
shown === lane ? "shown" : (lanes.get(lane) ?? "none"),
snapshot: () => display,
From cf5a9e28eb1d24a67b92f655a16fee58d31c6d05 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Thu, 19 Nov 2026 12:47:04 -0500
Subject: [PATCH 15/37] fix(arranger): stage live holds and re-read rows that
commit late
The reference plugin added live rows to its cache before the session
accepted the hold, so a refused hold left the cache over its bound and
every later hold failed. Stage them until the hold accepts. Stop and
release the scan when the reader takes its rows back.
Before a scan counts as exact, read the conversation's messages again
from the first page's time less NIP-CW's 960 s allowance, so a row that
commits behind the walk's cursor is found. The fixture relay now serves
plain message reads with since, and stamps bounds with its clock.
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
.../messages/arranger-plugin.test.tsx | 88 ++++++++-
.../fixtures/conversation-arranger/plugin.ts | 180 +++++++++++-------
tests/fixtures/conversation-arranger/relay.ts | 15 +-
3 files changed, 214 insertions(+), 69 deletions(-)
diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx
index 812ac87874..5070dbbbce 100644
--- a/src/features/messages/arranger-plugin.test.tsx
+++ b/src/features/messages/arranger-plugin.test.tsx
@@ -26,6 +26,7 @@ import {
prove,
REACTION,
T,
+ type World,
} from "../../../tests/fixtures/conversation-arranger/relay";
import { ComposerAccessories } from "../conversation/ComposerAccessories";
import type {
@@ -364,7 +365,7 @@ it("ranks a 2,000-reply thread by Top from background reads, leaving the host's
await ready(h);
const reads = h.scanReads(before);
- expect(reads).toHaveLength(7);
+ expect(reads).toHaveLength(8);
expect(reads.every(({ priority }) => priority === "background")).toBe(true);
const windows = reads
.flatMap(({ filters }) => filters)
@@ -491,7 +492,10 @@ it("reads a heavy root's replies' reactions by id once the relay refuses its pag
const pages = h.answers.filter((answer) =>
answer.some((e) => e.kind === 39007),
);
- const aux = filters.filter((filter) => !filter.thread_window && filter["#e"]);
+ const aux = filters.filter(
+ (filter) =>
+ !filter.thread_window && filter["#e"] && !filter.kinds?.includes(9),
+ );
expect(new Set(aux.flatMap((filter) => filter["#e"] ?? []))).toEqual(
new Set(
pages
@@ -791,7 +795,7 @@ it("reads a thread through older pages alone when the relay has no newer windows
h.click("Top");
await ready(h);
const reads = h.scanReads(before);
- expect(reads).toHaveLength(11);
+ expect(reads).toHaveLength(12);
const filters = reads.flatMap(({ filters }) => filters);
expect(filters.some((f) => f.direction === "newer")).toBe(false);
expect(h.shown()).toEqual(idsOf(want.top.slice(0, 200)));
@@ -846,6 +850,18 @@ it("leaves its place, and the reader's own rows, when withdrawn", async () => {
expect(h.arrangement.status(h.lane() as never)).toBe("none");
});
+it("stops and lets its rows go when the reader takes them back", async () => {
+ const { root } = thread;
+ const h = await mount({ fixture: thread, rootId: root.id });
+ h.click("Top");
+ await ready(h);
+ expect(h.arrangement.status(h.lane() as never)).toBe("shown");
+ act(() => h.arrangement.withdraw());
+ await waitFor(() => expect(h.status()).toBe(""));
+ expect(h.arrangement.snapshot()).toBeUndefined();
+ 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);
@@ -985,6 +1001,70 @@ it("keeps an Oldest list in order when replies arrive before the read reaches th
expect(h.shown().slice(-30)).toEqual(idsOf(late));
});
+it("counts a reply that commits while the read runs with a time the read had passed", async () => {
+ const { events, root, authors } = thread;
+ const [late] = (await prove([
+ mint(authors[0] as never, {
+ kind: 9,
+ content: "committed while the read ran",
+ created_at: Math.floor(Date.now() / 1000) - 100,
+ tags: [
+ ["h", CHANNEL],
+ ["e", root.id, "", "reply"],
+ ],
+ }),
+ ])) as [RelayEvent];
+ let world: World | undefined;
+ let windows = 0;
+ const h = await mount({
+ fixture: thread,
+ rootId: root.id,
+ hold: (filters) => {
+ if (world && filters.some((f) => f.thread_window) && ++windows === 2)
+ world.add([late]);
+ return undefined;
+ },
+ });
+ world = h.world;
+ h.click("Top");
+ await ready(h);
+ expect(windows).toBeGreaterThan(2);
+ await statusIs(
+ h,
+ replies(1, 200, oracle([...events, late], root.id).rows.length),
+ );
+});
+
+it("keeps what it holds when the session refuses a live reply, and takes the next one", async () => {
+ const { events, root, authors } = thread;
+ const h = await mount({ fixture: thread, rootId: root.id });
+ h.click("Top");
+ await ready(h);
+ const reply = (content: string, at: number) =>
+ mint(authors[0] as never, {
+ kind: 9,
+ content,
+ created_at: at,
+ tags: [
+ ["h", CHANNEL],
+ ["e", root.id, "", "reply"],
+ ],
+ });
+ const [huge, small] = (await prove([
+ reply("x".repeat(8 * 1024 * 1024), T + 40_000),
+ reply("small", T + 40_001),
+ ])) as [RelayEvent, RelayEvent];
+ h.heard(huge);
+ await statusIs(h, /Cannot hold this conversation/);
+ h.heard(small);
+ h.click("Top");
+ await statusIs(
+ h,
+ replies(1, 200, oracle([...events, small], root.id).rows.length),
+ );
+ expect(h.shown()).not.toContain(huge.id);
+});
+
async function hostChannel(h: Harness) {
void h.session.channels.refresh?.(CHANNEL);
await waitFor(() =>
@@ -1038,7 +1118,7 @@ it("ranks a 5,000-row channel by top reacted from verified windows, without touc
const reads = h.scanReads(before);
expect(reads.every(({ priority }) => priority === "background")).toBe(true);
- expect(reads).toHaveLength(25);
+ expect(reads).toHaveLength(26);
const pages = h.answers.filter((page) => page.some((e) => e.kind === 39006));
expect(pages).toHaveLength(25);
expect(h.answers.flat().every(hasEventProof)).toBe(true);
diff --git a/tests/fixtures/conversation-arranger/plugin.ts b/tests/fixtures/conversation-arranger/plugin.ts
index 1b78e016f2..0b2371719a 100644
--- a/tests/fixtures/conversation-arranger/plugin.ts
+++ b/tests/fixtures/conversation-arranger/plugin.ts
@@ -24,6 +24,7 @@ const JITTER_MS = 10_000;
const BOUNDS = { thread: 39007, channel: 39006 } as const;
const AUX = new Set([5, 7, 9005, 40003]);
const AUX_PAGE = 500;
+const LATE_SECS = 960;
/** The scan's whole life, as one value. A new sort, a withdraw or unmount aborts `scanning`. */
type Phase =
@@ -78,6 +79,7 @@ function createArranger(initial: ComposerAccessoryProps) {
let closureRefused: string | undefined;
let scanned = false;
let forward: Cursor | null | undefined;
+ let walkStart: number | undefined;
let shown = 0;
let taken = 0;
let total = 0;
@@ -111,20 +113,61 @@ function createArranger(initial: ComposerAccessoryProps) {
function keep(more: readonly RelayEvent[]) {
const kind = kindOfBounds();
+ const fresh = new Map();
for (const event of more)
if (event.kind !== kind && !events.has(event.id))
- events.set(event.id, event);
- holdAll();
+ fresh.set(event.id, event);
+ holdAll([...fresh.values()]);
}
- function holdAll() {
+ function holdAll(more: readonly RelayEvent[] = []) {
try {
hold ??= props.session.retain();
- hold.set([...events.values()]);
+ hold.set([...events.values(), ...more]);
} catch (error) {
throw new Error(
`Cannot hold this conversation: ${(error as Error).message}`,
);
}
+ for (const event of more) events.set(event.id, event);
+ }
+ function forget() {
+ events.clear();
+ scanned = false;
+ forward = undefined;
+ walkStart = undefined;
+ lost = false;
+ hold?.dispose();
+ hold = undefined;
+ }
+
+ async function drain(
+ filter: ReadFilter,
+ signal: AbortSignal,
+ take: (page: readonly RelayEvent[]) => void,
+ ) {
+ let cursor: Cursor | undefined;
+ for (;;) {
+ const page = await read(
+ [
+ {
+ ...filter,
+ ...(cursor
+ ? { until: cursor.created_at, before_id: cursor.id }
+ : {}),
+ },
+ ],
+ signal,
+ );
+ const last = page.reduce(
+ (end, event) => (!end || inOrder(event, end) < 0 ? event : end),
+ undefined,
+ );
+ if (!last) return;
+ if (cursor && inOrder(last, cursor) >= 0)
+ throw new Error("The relay did not page this read");
+ take(page);
+ cursor = { created_at: last.created_at, id: last.id };
+ }
}
async function replyAux(ids: readonly string[], signal: AbortSignal) {
@@ -132,33 +175,36 @@ function createArranger(initial: ComposerAccessoryProps) {
for (const scope of [
{ kinds: [5, 7, 9005, 40003], "#h": [props.channelId] },
{ kinds: [5, 9005] },
- ]) {
- let cursor: Cursor | undefined;
- for (;;) {
- const page = await read(
- [
- {
- ...scope,
- "#e": [...ids],
- limit: AUX_PAGE,
- ...(cursor
- ? { until: cursor.created_at, before_id: cursor.id }
- : {}),
- },
- ],
- signal,
- );
- const last = page.reduce(
- (end, event) => (!end || inOrder(event, end) < 0 ? event : end),
- undefined,
- );
- if (!last) break;
- if (cursor && inOrder(last, cursor) >= 0)
- throw new Error("The relay did not page reactions");
- keep(page);
- cursor = { created_at: last.created_at, id: last.id };
- }
- }
+ ])
+ await drain({ ...scope, "#e": [...ids], limit: AUX_PAGE }, signal, keep);
+ }
+ async function overlap(signal: AbortSignal) {
+ const root = rootId();
+ const fresh: string[] = [];
+ await drain(
+ {
+ kinds: [9],
+ "#h": [props.channelId],
+ ...(root ? { "#e": [root] } : {}),
+ since: (walkStart ?? 0) - LATE_SECS,
+ limit: PAGE,
+ },
+ signal,
+ (page) => {
+ const rows = root
+ ? page
+ : page.filter(
+ (event) =>
+ !event.tags.some(
+ ([name, , , marker]) => name === "e" && marker === "reply",
+ ),
+ );
+ for (const event of rows)
+ if (event.id !== root && !events.has(event.id)) fresh.push(event.id);
+ keep(rows);
+ },
+ );
+ await replyAux(fresh, signal);
}
async function pages(
@@ -187,6 +233,7 @@ function createArranger(initial: ComposerAccessoryProps) {
};
});
let answer: readonly RelayEvent[];
+ const requested = Math.floor(Date.now() / 1000);
try {
answer = await read(windows(), signal);
} catch (error) {
@@ -195,16 +242,20 @@ function createArranger(initial: ComposerAccessoryProps) {
closure = false;
answer = await read(windows(), 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;
- },
- );
+ const stamped = answer.filter((event) => event.kind === kindOfBounds());
+ walkStart = Math.min(
+ walkStart ?? requested,
+ requested,
+ ...stamped.map((event) => event.created_at),
+ );
+ const bodies = stamped.map(
+ (event) =>
+ JSON.parse(event.content) as {
+ direction?: Lane;
+ has_more: boolean;
+ next_cursor: Cursor | null;
+ },
+ );
keep(answer);
if (!closure) {
await replyAux(
@@ -255,6 +306,7 @@ function createArranger(initial: ComposerAccessoryProps) {
emit();
}
}
+ await overlap(signal);
scanned = true;
}
@@ -274,7 +326,9 @@ function createArranger(initial: ComposerAccessoryProps) {
[forward] = await pages([["newer", forward ?? undefined]], signal);
emit();
}
- scanned = forward === null;
+ if (forward !== null) return;
+ await overlap(signal);
+ scanned = true;
}
const reachesAll = () =>
sort === "top" || filter !== "" || props.session.windowNewer !== true;
@@ -419,13 +473,7 @@ function createArranger(initial: ComposerAccessoryProps) {
function rescan() {
repair = undefined;
- lost = false;
- events.clear();
- scanned = false;
- forward = undefined;
- try {
- hold?.set([]);
- } catch {}
+ forget();
if (sort) refresh();
else emit();
}
@@ -449,33 +497,30 @@ function createArranger(initial: ComposerAccessoryProps) {
function onLive({ events: heard }: { events: readonly RelayEvent[] }) {
if (!sort && !events.size) return;
const root = rootId();
- let added = 0;
+ const fresh = new Map();
+ const known = (id: string) => events.has(id) || fresh.has(id);
for (const event of heard)
if (
event.kind === 9 &&
- !events.has(event.id) &&
+ !known(event.id) &&
event.tags.some(([name, id]) =>
root
? name === "e" && id === root
: name === "h" && id === props.channelId,
)
- ) {
- events.set(event.id, event);
- added++;
- }
+ )
+ fresh.set(event.id, event);
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;
+ !known(event.id) &&
+ auxTargets(event).some(known)
+ )
+ fresh.set(event.id, event);
+ if (!fresh.size) return;
try {
- holdAll();
+ holdAll([...fresh.values()]);
} catch (error) {
if (sort) fail(error, sort);
return;
@@ -490,6 +535,7 @@ function createArranger(initial: ComposerAccessoryProps) {
filter = "";
starts = [0];
shown = 0;
+ forget();
emit();
}
@@ -556,6 +602,7 @@ function createArranger(initial: ComposerAccessoryProps) {
free() {
if (phase.state === "ready" && sort) arrange();
},
+ stop,
update(next: ComposerAccessoryProps) {
props = next;
},
@@ -633,9 +680,14 @@ export function apply(ctx: Context) {
arranger.snapshot,
arranger.snapshot,
);
+ const was = React.useRef(props.presentation);
React.useEffect(() => {
+ const before = was.current;
+ was.current = props.presentation;
if (props.presentation === "ended") arranger.ended();
- if (props.presentation === "none") arranger.free();
+ if (props.presentation !== "none") return;
+ if (before === "shown") arranger.stop();
+ else arranger.free();
}, [arranger, props.presentation]);
const noun = props.threadRootId !== undefined ? "replies" : "messages";
const [draft, setDraft] = React.useState("");
diff --git a/tests/fixtures/conversation-arranger/relay.ts b/tests/fixtures/conversation-arranger/relay.ts
index a56f8040d3..8d6356038b 100644
--- a/tests/fixtures/conversation-arranger/relay.ts
+++ b/tests/fixtures/conversation-arranger/relay.ts
@@ -121,6 +121,7 @@ export function createWorld(events: readonly RelayEvent[] = []) {
sorted.clear();
},
byId,
+ messages: () => [...top, ...[...replies.values()].flat()].sort(ascending),
rows(root?: string) {
const key = root ?? "";
let list = sorted.get(key);
@@ -178,7 +179,7 @@ async function bound(
mint(relay, {
kind,
content: JSON.stringify(body),
- created_at: T,
+ created_at: Math.floor(Date.now() / 1000),
tags,
}),
]);
@@ -274,6 +275,18 @@ export function createRelay(options: {
),
];
}
+ if (
+ filter.kinds?.length === 1 &&
+ filter.kinds[0] === 9 &&
+ filter["#h"]?.includes(CHANNEL)
+ ) {
+ const rows = roots ? world.rows(roots) : world.messages();
+ const since = filter.since ?? 0;
+ return after(
+ rows.filter((e) => e.created_at >= since && !world.deleted(e)),
+ filter,
+ ).slice(0, page);
+ }
if (filter["#e"]) {
const kinds = new Set(filter.kinds ?? []);
const named = filter["#h"];
From bf4a57bf6e8d4568d30163baa4336860849e4ad3 Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Thu, 19 Nov 2026 12:48:26 -0500
Subject: [PATCH 16/37] test(reader): keep rows that leave out a target already
revealed
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
.../ThreadPanel.presentation.test.tsx | 26 +++++++++++++++++--
1 file changed, 24 insertions(+), 2 deletions(-)
diff --git a/src/features/messages/ThreadPanel.presentation.test.tsx b/src/features/messages/ThreadPanel.presentation.test.tsx
index 6e188e3e48..997974af1a 100644
--- a/src/features/messages/ThreadPanel.presentation.test.tsx
+++ b/src/features/messages/ThreadPanel.presentation.test.tsx
@@ -101,7 +101,12 @@ beforeEach(() => {
disconnect() {}
},
);
- HTMLElement.prototype.scrollIntoView = vi.fn();
+ HTMLElement.prototype.scrollIntoView = vi.fn(function (this: HTMLElement) {
+ const at = [
+ ...document.querySelectorAll("[data-thread-rows] ol [data-message-id]"),
+ ].indexOf(this);
+ if (at >= 0) scrolled = Math.max(0, Math.min(100 * (at + 1), 3400));
+ });
HTMLElement.prototype.scrollTo = vi.fn();
vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(600);
vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(4000);
@@ -490,7 +495,7 @@ it("hides the jump button and keeps the arrivals count off while it presents", (
const rowOf = (h: ReturnType, event: EventData) =>
h.rowsOf([root, event]).find((row) => row.id === event.id);
-it("takes its rows back to reveal a link's target they leave out, then keeps rows that leave it out", async () => {
+it("takes its rows back to reveal a link's target they leave out", async () => {
const navigation = navigationTo(d.id);
const h = mount({
replies: [d],
@@ -510,9 +515,26 @@ it("takes its rows back to reveal a link's target they leave out, then keeps row
}),
);
expect(lastReading().settled.current).toBe(true);
+});
+
+it("keeps rows that leave out a link's target the reader already revealed", async () => {
+ const navigation = navigationTo(d.id);
+ const h = mount({
+ replies: [d],
+ navigation,
+ props: { messageId: d.id },
+ snapshot: { targetStatus: "loading" },
+ });
+ h.publish({ targetStatus: "ready", target: rowOf(h, d) });
+ await waitFor(() =>
+ expect(navigation.complete).toHaveBeenCalledExactlyOnceWith({
+ status: "opened",
+ }),
+ );
h.present({ ids: [a.id, b.id] });
expect(h.latest.current?.presentation).toBe("shown");
expect(drawn()).toEqual(["root", "a", "b"]);
+ expect(navigation.complete).toHaveBeenCalledOnce();
});
it("keeps a second presentation that leaves out a link's target, and opens the visit", () => {
From eae34d4c7e3810b3a5f0871e4a8c7f0b818e53ac Mon Sep 17 00:00:00 2001
From: LordMelkor
Date: Thu, 19 Nov 2026 13:11:49 -0500
Subject: [PATCH 17/37] refactor(relay): leave thread and channel window
admission as main has it
The arranger reads through snapshotRead, which never reaches the views'
accept paths, so the admission changes served no caller in this change.
Co-authored-by: Clod
Co-Authored-By: Claude Opus 5.5
Signed-off-by: LordMelkor
---
src/features/relay/session.ts | 8 +-
src/features/relay/store.ts | 35 +---
src/features/relay/thread-window.test.ts | 194 ------------------
src/features/relay/threads.test.ts | 10 +-
src/features/relay/threads.ts | 34 +--
.../relay/traffic.integration.test.ts | 75 -------
6 files changed, 10 insertions(+), 346 deletions(-)
diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts
index 5ded121c96..60b329845b 100644
--- a/src/features/relay/session.ts
+++ b/src/features/relay/session.ts
@@ -349,9 +349,7 @@ export function createRelaySession(
revision: number;
incoming?: "replay" | "live";
}>(4096, 8 * 1024 * 1024);
- const observations = new Set<
- (events: readonly RelayEvent[], stream: boolean) => void
- >();
+ const observations = new Set<(events: readonly RelayEvent[]) => void>();
const incomingListeners = new Set();
const liveEventListeners = new Set();
const replayListeners = new Set