diff --git a/src/bundled/channels/ChannelsPage.context.test.tsx b/src/bundled/channels/ChannelsPage.context.test.tsx index b4d3b36474..bdec85189b 100644 --- a/src/bundled/channels/ChannelsPage.context.test.tsx +++ b/src/bundled/channels/ChannelsPage.context.test.tsx @@ -3,7 +3,13 @@ import "@testing-library/jest-dom/vitest"; import { act, cleanup, render } from "@testing-library/react"; import type { ComponentProps, ReactElement } from "react"; import { afterEach, beforeAll, beforeEach, expect, it, vi } from "vitest"; +import type { + ComposerAccessory, + ComposerAccessoryProps, + ConversationExtensions, +} from "../../features/conversation/contracts"; import { composerDOMFixture } from "../../features/messages/composer-testing"; +import type { Contribution } from "../../plugins/contributions"; import { createNavigationController } from "../../features/navigation/controller"; import { createMemoryHistory } from "../../features/navigation/history"; import type { PageNavigation } from "../../features/navigation/service"; @@ -137,7 +143,15 @@ function page(filter: ReadFilter, history: readonly RelayEvent[]) { * `root: false`, absent from its history. Alpha's older pages wait for * `release()`. A `cached` session has only alpha's saved head until * `connect()`. */ -async function channelsPage({ root = true, cached = false } = {}) { +async function channelsPage({ + root = true, + cached = false, + extensions, +}: { + root?: boolean; + cached?: boolean; + extensions?: ConversationExtensions; +} = {}) { const { viewer, authority, reply, newer, channels } = fixture; const alpha = [...(root ? [fixture.root] : []), reply, ...newer]; const held: ((error?: Error) => void)[] = []; @@ -274,6 +288,7 @@ async function channelsPage({ root = true, cached = false } = {}) { panels={panels} navigator={navigator} navigation={navigation} + extensions={extensions} /> ); @@ -336,7 +351,29 @@ const timeline = (channelId: string) => document.querySelector(`[data-channel-timeline="${channelId}"]`); it("holds the list from the visit's start, then reveals the root beside the thread", async () => { - const h = await channelsPage(); + const readerProps: ComposerAccessoryProps[] = []; + const entries: readonly Contribution[] = [ + { + id: "arranger", + key: "test:arranger", + pluginId: "test", + revision: "one", + title: "Arranger", + placement: "reader", + component(props) { + readerProps.push(props); + return null; + }, + }, + ]; + const none: readonly never[] = []; + const empty = { snapshot: () => none, subscribe: () => () => {} }; + const extensions: ConversationExtensions = { + accessories: { snapshot: () => entries, subscribe: () => () => {} }, + tools: empty, + inline: empty, + }; + const h = await channelsPage({ extensions }); const first = h.visit(h.inChannel(), "visit"); h.go(first); await vi.waitFor(() => expect(h.held).toHaveLength(1)); @@ -359,6 +396,11 @@ it("holds the list from the visit's start, then reveals the root beside the thre }, }), ); + const channelProps = readerProps.filter((props) => !props.threadRootId); + expect(channelProps.length).toBeGreaterThan(0); + expect( + channelProps.every((props) => props.linkedMessageId === undefined), + ).toBe(true); }); it("opens the timeline at its usual place when the root is not in its history", async () => { diff --git a/src/features/conversation/ComposerAccessories.test.tsx b/src/features/conversation/ComposerAccessories.test.tsx index 270ce9f5a4..e628e94c94 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,194 @@ 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 frees the reader for 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:none")).toBeTruthy(); + expect(reader.arrangement.status(bomb)).toBe("none"); + expect(bombPresent?.(nothing)).toBe("retired"); + act(() => { + expect(sparePresent?.(nothing)).toBe("shown"); + }); + expect(screen.getByText("spare:shown")).toBeTruthy(); + 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..bc8c51da29 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,21 @@ 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), + ); + useLayoutEffect( + () => () => { + arrangement?.present(entry, null); + }, + [arrangement, entry], + ); useLayoutEffect(() => { let live = true; const session = props.session; @@ -100,11 +121,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 +149,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 ffa05a6447..335afe29ae 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"; @@ -200,6 +201,41 @@ 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, plus other events in `events` + * within its limits as deletion evidence, 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`: 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; scope: string; @@ -227,6 +263,20 @@ 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. `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; + /** Reader placement only: the row a followed link opened this visit on. */ + linkedMessageId?: 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. @@ -236,8 +286,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 34a3c0d983..765edcabde 100644 --- a/src/features/conversation/service.test.tsx +++ b/src/features/conversation/service.test.tsx @@ -596,6 +596,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 025afa7c3b..ac05a444eb 100644 --- a/src/features/conversation/service.tsx +++ b/src/features/conversation/service.tsx @@ -467,7 +467,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..29cb637b9e --- /dev/null +++ b/src/features/messages/ChannelTimeline.presentation.test.tsx @@ -0,0 +1,1004 @@ +// @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, + signed, +} 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[], + first: 0, + scrollToIndex: vi.fn(), +})); +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)); +const hostEvents = ["h0", "h1", "h2", "h3", "h4", "h5"].map((name, index) => + post(name, T + 60 * index), +); +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)); + }, + }); + 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.useRealTimers(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + delete (HTMLElement.prototype as Partial).scrollTop; +}); + +const readerEntry = ( + component: Contribution["component"], +) => ({ + 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; + onProps?: (props: ComposerAccessoryProps) => void; + fold?: RelaySession["foldRows"]; + rows?: readonly ChannelMessage[]; + 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[]) => + owner.session.foldRows("c", events); + let current = hostWindow(rows ?? rowsOf(hostEvents), windowExtra); + const loadOlder = vi.fn(); + const newerLoads: string[] = []; + 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, + loadNewer(id: string) { + newerLoads.push(id); + }, + window: () => current, + }, + } as RelaySession); + const latest: { current?: ComposerAccessoryProps } = {}; + const entries = [ + readerEntry((accessory) => { + latest.current = accessory; + useLayoutEffect(() => { + onProps?.(accessory); + }); + return ; + }), + ]; + 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, + receive: callbacks.receive, + loadOlder, + newerLoads, + retained, + latest, + rowsOf, + 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); + }); + }, + }; +} +const frame = () => + act(() => { + for (const [id, callback] of [...frames]) { + frames.delete(id); + callback(0); + } + }); +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.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(300); + const h = mount({ window: { hasMore: true } }); + h.present({ ids: [p0.id, p1.id] }); + for (let pass = 0; pass < 4; pass++) frame(); + act(() => { + vi.advanceTimersByTime(50); + }); + expect(h.loadOlder).not.toHaveBeenCalled(); + h.withdraw(); + for (let pass = 0; pass < 4; pass++) frame(); + act(() => { + vi.advanceTimersByTime(50); + }); + 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(); + 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"]); + const marks = () => + [...document.querySelectorAll("li[data-message-id]")].map( + ({ dataset }) => + `${dataset.day ?? "-"} ${dataset.stacked ?? "-"} ${dataset.stackNext ?? "-"}`, + ); + expect(marks()).toEqual(["- - -", "- - -", "- - -", "- - -"]); + h.withdraw(); + expect(marks()).toEqual([ + "true - true", + "- true true", + "- true true", + "- true true", + "- true true", + "- true -", + ]); +}); + +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("folds no relayed run under a presentation, and folds the host's again after it", () => { + const relayed = updates(3).map(({ audience: _audience, ...row }) => ({ + ...row, + relayedFrom: { agent: "zerk", verified: true }, + })); + const h = mount({ rows: relayed, fold: () => relayed }); + const run = () => + screen.queryByRole("button", { name: /^Show 3 messages by zerk\./ }); + expect(run()).toBeVisible(); + h.present({ ids: relayed.map((row) => row.id).reverse(), events: [] }); + expect(drawn()).toEqual(["activity-2", "activity-1", "activity-0"]); + expect(run()).toBeNull(); + h.withdraw(); + expect(run()).toBeVisible(); +}); + +it("draws no unread line, Jump or arrival count under a presentation, and counts none when it ends", () => { + const h = mount(); + frame(); + 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(); + h.withdraw(); + frame(); + expect(screen.getByText("Jump to latest")).toBeVisible(); + expect(screen.queryByText(/new message/)).toBeNull(); +}); + +it("hides Jump to latest and skips newer-page loads for a detached window while it presents", () => { + const h = mount({ window: { hasNewer: true } }); + frame(); + expect(scroller()).toHaveAttribute("data-jump-visible", "true"); + expect(screen.getByText("Jump to latest").closest("[inert]")).toBeNull(); + 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(); + scrolled = 3400; + fireEvent.scroll(scroller()); + expect(h.newerLoads).toEqual([]); + h.withdraw(); + frame(); + expect(scroller()).toHaveAttribute("data-jump-visible", "true"); + expect(screen.getByText("Jump to latest").closest("[inert]")).toBeNull(); + scrolled = 3400; + fireEvent.scroll(scroller()); + expect(h.newerLoads).toEqual(["c"]); +}); + +it("does not follow new pages after an end withdraw into a detached window", () => { + const h = mount({ window: { hasNewer: true } }); + frame(); + h.present({ ids: [p0.id, p1.id, p2.id] }); + frame(); + viewport.scrollToIndex.mockClear(); + h.withdraw(); + frame(); + expect(viewport.scrollToIndex).toHaveBeenCalledTimes(1); + expect(placed()).toEqual([5, { align: "end" }]); + expect(scroller()).toHaveAttribute("data-jump-visible", "true"); + viewport.scrollToIndex.mockClear(); + h.setWindow({ + rows: [...h.rowsOf(hostEvents), ...h.rowsOf([p0])], + hasNewer: true, + }); + frame(); + expect(viewport.scrollToIndex).not.toHaveBeenCalled(); +}); + +it("holds the anchor row where it was when a presentation shows it", () => { + const h = mount(); + frame(); + 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(); + 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; + h.present({ ids: [h0.id, h1.id, h3.id, h4.id] }); + 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); + 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; + h.withdraw(); + 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(); + 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; + 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(); + 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", () => { + 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(); + expect(h.latest.current?.presentation).toBe("shown"); + fireEvent.scroll(scroller()); + h.unmount(); + 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(); + first.unmount(); + const second = mount({ again: first }); + expect(viewport.caches.at(-1)).toEqual([[], 40]); + second.present({ ids: [p0.id, p1.id] }); + second.unmount(); + viewport.caches.length = 0; + mount({ again: first }); + expect(viewport.caches.at(-1)).toBeUndefined(); +}); + +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(h.latest.current?.presentation).toBe("none"); + 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", () => { + 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().latestMessageId).toBe(h5.id); + h.present({ ids: [p2.id, p0.id, p1.id] }); + expect(lastReading().partial).toBe(true); + expect(lastReading().latestMessageId).toBe(p1.id); + expect(lastReading().catchUpMessageId).toBe(p2.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().latestMessageId).toBe(h5.id); + expect(lastReading().catchUpMessageId).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"); +}); + +it("transfers focus to a surviving row or history region when a presentation or live update removes the focused row, without stealing focus from reader-bar controls", async () => { + const h = mount(); + const initial = row(h1) as HTMLElement; + initial.tabIndex = -1; + initial.focus(); + expect(document.activeElement).toBe(initial); + + initial.dispatchEvent( + new FocusEvent("focusout", { bubbles: true, relatedTarget: null }), + ); + h.present({ ids: [p0.id, p1.id, p2.id] }); + expect(document.activeElement).toBe(row(p0)); + + const dropP0 = eventDto( + signed(other, { + kind: 5, + content: "", + created_at: T + 2000, + tags: [ + ["h", "c"], + ["e", p0.id], + ], + }), + ); + act(() => { + h.receive([dropP0], { phase: "live", channelId: "c" }); + }); + row(p0)?.dispatchEvent( + new FocusEvent("focusout", { bubbles: true, relatedTarget: null }), + ); + frame(); + expect(drawn()).toEqual(["p1", "p2"]); + expect(document.activeElement).toBe(row(p1)); + + h.present({ ids: [p2.id] }); + expect(document.activeElement).toBe(row(p2)); + + h.present({ ids: [] }); + expect(document.activeElement).toBe(scroller()); + + h.present({ ids: [p1.id, p2.id] }); + const barControl = screen.getByRole("button", { name: "bar" }); + const focusedP1 = row(p1) as HTMLElement; + focusedP1.tabIndex = -1; + focusedP1.focus(); + barControl.focus(); + h.present({ ids: [p2.id] }); + expect(document.activeElement).toBe(barControl); + + const blurredP2 = row(p2) as HTMLElement; + blurredP2.tabIndex = -1; + blurredP2.focus(); + blurredP2.blur(); + await Promise.resolve(); + expect(document.activeElement).toBe(document.body); + h.present({ ids: [p1.id] }); + expect(document.activeElement).toBe(document.body); + + h.present({ ids: [p1.id, p2.id] }); + const surviving = row(p2) as HTMLElement; + const transient = document.createElement("button"); + surviving.append(transient); + transient.focus(); + transient.remove(); + expect(document.activeElement).toBe(document.body); + h.present({ ids: [p1.id, p2.id] }); + expect(document.activeElement).toBe(document.body); +}); + +it("skips membership notice rows when recovering focus after a presented row disappears", () => { + const notice: ChannelMessage = { + id: "join-1", + channelId: "c", + authorId: other.pubkey, + createdAt: T + 1050, + content: "", + mentions: [], + attachments: [], + reactions: [], + participants: [], + replyCount: 0, + membership: { + type: "member_joined", + actor: viewer.pubkey, + target: other.pubkey, + }, + }; + const sample = (h: ReturnType) => { + const [r0, r2] = h.rowsOf([p0, p2]) as [ChannelMessage, ChannelMessage]; + return [r0, notice, r2]; + }; + let rowsToFold: readonly ChannelMessage[] = []; + const h = mount({ fold: () => rowsToFold }); + rowsToFold = sample(h); + h.present({ ids: [p0.id, notice.id, p2.id], events: [] }); + expect( + document.querySelector(`[data-message-id="${notice.id}"]`), + ).toBeInTheDocument(); + const focusedP0 = row(p0) as HTMLElement; + focusedP0.tabIndex = -1; + focusedP0.focus(); + expect(document.activeElement).toBe(focusedP0); + + h.present({ ids: [notice.id, p2.id], events: [] }); + expect(document.activeElement).toBe(row(p2)); + + h.present({ ids: [notice.id], events: [] }); + expect(document.activeElement).toBe(scroller()); +}); + +it("keeps focus on a linked row when the first hiding presentation withdraws, then recovers to a presented neighbor on a second hiding presentation", () => { + const firstNav = navigationTo(h1.id); + const first = mount({ props: { navigation: firstNav } }); + expect(first.latest.current?.linkedMessageId).toBe(h1.id); + frame(); + frame(); + expect(document.activeElement).toBe(row(h1)); + first.present({ ids: [p0.id, p1.id] }); + expect(first.latest.current?.presentation).toBe("none"); + expect(firstNav.complete).not.toHaveBeenCalled(); + for (let pass = 0; pass < 4; pass++) frame(); + expect(firstNav.complete).toHaveBeenCalledExactlyOnceWith({ + status: "opened", + }); + expect(document.activeElement).toBe(row(h1)); + first.unmount(); + + const secondNav = navigationTo(h1.id); + const second = mount({ props: { navigation: secondNav } }); + frame(); + frame(); + expect(document.activeElement).toBe(row(h1)); + second.present({ ids: [p0.id, p1.id] }); + expect(second.latest.current?.presentation).toBe("none"); + frame(); + frame(); + expect(document.activeElement).toBe(row(h1)); + second.present({ ids: [p0.id, p1.id] }); + expect(second.latest.current?.presentation).toBe("shown"); + expect(secondNav.complete).toHaveBeenCalledExactlyOnceWith({ + status: "opened", + }); + expect(document.activeElement).toBe(row(p0)); +}); diff --git a/src/features/messages/ChannelTimeline.restore.test.tsx b/src/features/messages/ChannelTimeline.restore.test.tsx index 602abc2761..06aa50b42a 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 b18e30d20e..b0edc4b224 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, })); @@ -225,7 +226,7 @@ function setup({ ]); } }; - const element = { + const element = Object.assign(new EventTarget(), { clientWidth: 1124, clientHeight: 668, scrollHeight: 3706, @@ -245,7 +246,7 @@ function setup({ getBoundingClientRect: () => ({ top: y + 32, bottom: y + 80 }), }), })), - }; + }); const handle = { scrollOffset: 3038, scrollSize: 3649.5, diff --git a/src/features/messages/ChannelTimeline.tsx b/src/features/messages/ChannelTimeline.tsx index 83a6da9912..a942c44224 100644 --- a/src/features/messages/ChannelTimeline.tsx +++ b/src/features/messages/ChannelTimeline.tsx @@ -22,7 +22,15 @@ 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 { + readerMode, + useArrangement, + usePlace, + usePresentedFocusRecovery, +} from "./arrangement"; import type { RelaySession } from "../relay/session"; import type { MessageAttention } from "../relay/unread"; import { @@ -164,6 +172,9 @@ function subscribeDocumentActive(listener: () => void) { }; } const TIMELINE_PLACE = "timeline"; +const NO_ROWS: readonly ChannelMessage[] = Object.freeze([]); +const byTime = (rows: readonly ChannelMessage[]) => + [...rows].sort((a, b) => a.createdAt - b.createdAt); /** Run `callback` once the main thread is idle: within 500ms, or after 50ms * without idle callbacks. Returns a cancel. */ function afterIdle(callback: () => void) { @@ -333,8 +344,23 @@ function Timeline({ [onOpenLink, inView, viewRoot], ); useMessageSelectionCopy(); - const shownIntro = - !window.hasMore && !window.historyLimited ? intro : undefined; + const [arrangement, display] = useArrangement({ + session: queries, + channelId, + rootId: undefined, + limits: CHANNEL_LIMITS, + channel: !transient, + }); + const mode = readerMode(display); + const modeNow = useRef(mode); + modeNow.current = mode; + const shownIntro = ( + display + ? display.complete + : !window.hasMore && !window.historyLimited + ) + ? intro + : undefined; const [initialPosition] = useState(() => transient ? null @@ -362,7 +388,12 @@ 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 || + !modeNow.current.hostNavigation || + revision === written.current + ) + return; if (writeView(scope, `scroll:${channelId}`, place)) written.current = revision; }, [channelId, scope, transient]); @@ -371,7 +402,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, @@ -403,6 +437,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(() => ({})); @@ -793,6 +832,7 @@ function Timeline({ }); } const newMessageBoundaryId = + mode.chronologicalChrome && boundaryMatchesVisit && newMessageBoundary.captured && messageVisit?.active === true && @@ -819,8 +859,9 @@ function Timeline({ return next; }); }, []); + const foldable = mode.chronologicalChrome ? chronologicalRows : NO_ROWS; const presentation = useActivityPresentation( - chronologicalRows, + foldable, queries.agentActivity, agentPubkeys, ); @@ -828,9 +869,9 @@ function Timeline({ const activity = useMemo( () => [ ...presentation.groups, - ...relayedRuns(chronologicalRows, newMessageBoundaryId), + ...relayedRuns(foldable, newMessageBoundaryId), ], - [presentation.groups, chronologicalRows, newMessageBoundaryId], + [presentation.groups, foldable, newMessageBoundaryId], ); const stableActivity = useStableRowActivity(chronologicalRows); const rowsById = useMemo( @@ -855,12 +896,16 @@ 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; + const targetHidden = + mode.presented && + !!requestedId && + renderedRowIndex(rows, shownRows, requestedId) < 0; + const targetId = targetHidden ? undefined : requestedId; const lastPublicMessage = publicMessageNeighbor(rows, rows.length, -1); const intent = useRef(0); // Keep expansion pending with scroll restoration until the saved row arrives. @@ -937,7 +982,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 || @@ -955,6 +1000,7 @@ function Timeline({ : [], ); const scroller = useRef(null); + const readerBar = useRef(null); const edge = useRef(null); const activityTail = useRef(null); useLayoutEffect(() => { @@ -975,7 +1021,8 @@ 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 || !mode.chronologicalChrome ? 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); @@ -1001,6 +1048,7 @@ function Timeline({ ids: ReadonlySet; floor: number; paging: boolean; + owner: number | undefined; /** Detached from the head: rows it reads in are history. */ detached: boolean; }>({ @@ -1009,6 +1057,7 @@ function Timeline({ ids: new Set(), floor: 0, paging: false, + owner: undefined, detached: false, }); // The reader's anchor row and its offset before this render's rows. @@ -1128,7 +1177,11 @@ function Timeline({ position.bottom = true; // Restoration can scroll before Virtua measures rows beneath the anchor, // briefly reaching the estimated bottom. Only reader input may follow. - if (restoredAnchor.current || detached.current) position.bottom = false; + if ( + restoredAnchor.current || + (modeNow.current.hostNavigation && detached.current) + ) + position.bottom = false; if (pendingRestore.current !== intent.current) savedPosition.current = position; follow.current = position.bottom; @@ -1281,6 +1334,31 @@ function Timeline({ complete: completeTarget, hold: holdTarget, }); + const withdrawnFor = useRef(undefined); + const [withdrawnSignal, setWithdrawnSignal] = useState(); + const willWithdraw = + targetHidden && + !!requestedId && + !!targetSignal && + !targetSignal.aborted && + revealedSignal !== targetSignal && + withdrawnSignal !== targetSignal; + useLayoutEffect(() => { + if ( + !targetHidden || + !targetSignal || + targetSignal.aborted || + revealedSignal === targetSignal + ) + return; + if (withdrawnFor.current === targetSignal) + navigation?.complete({ status: "opened" }); + else { + withdrawnFor.current = targetSignal; + setWithdrawnSignal(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 @@ -1301,7 +1379,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; @@ -1343,7 +1421,7 @@ function Timeline({ navigation, returning, rows, - visibleRows, + shownRows, containedOwners, activity, focusesTarget, @@ -1359,7 +1437,7 @@ function Timeline({ ) return; return () => { - if (savedPosition.current) + if (savedPosition.current && modeNow.current.hostNavigation) navigation.savePosition(TIMELINE_PLACE, savedPosition.current); }; }, [navigation, presented]); @@ -1375,12 +1453,12 @@ function Timeline({ scroller, settled, restoring, - latestMessageId: window.rows + latestMessageId: (display ? rows : window.rows) .filter((row) => !row.membership && !row.huddle) .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 + catchUpMessageId: (display ? byTime(display.rows) : window.rows) .filter( (row) => !row.membership && @@ -1389,6 +1467,8 @@ function Timeline({ !row.replyParentId, ) .at(-1)?.id, + partial: mode.partialReading, + 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. @@ -1404,6 +1484,55 @@ function Timeline({ !boundaryCandidate.awaitingRepair && !(awayPending && !boundaryPending), }); + 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(() => { + 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; + const followEnd = + at === "end" && !(owner === undefined && detached.current); + intent.current++; + savedPosition.current = + at === "end" + ? { bottom: followEnd } + : { bottom: false, anchor: { id: rows[index]?.id ?? "", y } }; + pendingRestore.current = at === "end" ? undefined : intent.current; + follow.current = followEnd; + settled.current = false; + restoredAnchor.current = undefined; + measuredPosition.current = null; + handle.current?.scrollToIndex( + index, + at === "end" ? { align: "end" } : { align: "start", offset: -y }, + ); + }, [arrangement, display, owner, rows, placement, size.edgeHeight]); + usePresentedFocusRecovery( + scroller, + arrangement !== undefined, + display, + rows, + willWithdraw ? requestedId : undefined, + ); // 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 @@ -1439,6 +1568,7 @@ function Timeline({ inset: readerRow && contentInset(readerRow), }; const prepend = + !swapped && !!previous.length && (previous[0] !== rows[0]?.id || rows.length !== previous.length) && reading.every( @@ -1828,10 +1958,13 @@ function Timeline({ ids: new Set(rows.map((row) => row.id)), floor: rows[0]?.createdAt ?? 0, paging: loadingOlder.current, + owner, detached: detached.current, }; if ( arrivals > 0 && + mode.hostNavigation && + !swapped && previousIds.size > 0 && !follow.current && (!targetId || revealedSignal === targetSignal) @@ -1881,7 +2014,7 @@ function Timeline({ const restoreIndex = anchor ? renderedRowIndex( rows, - visibleRows, + shownRows, containedOwners.get(anchor.id) ?? anchor.id, ) : -1; @@ -1893,7 +2026,7 @@ function Timeline({ pendingRestore.current === scheduledIntent && renderedRowIndex( rows, - visibleRows, + shownRows, containedOwners.get(pending.id) ?? pending.id, ) >= 0 ) @@ -2051,7 +2184,7 @@ function Timeline({ }; }, [ rows, - visibleRows, + shownRows, size, prepend, recordPosition, @@ -2063,6 +2196,9 @@ function Timeline({ latestRequest, containedOwners, newMessageBoundaryId, + swapped, + owner, + mode.hostNavigation, ]); // After positioning reads it: a load that ends without rows lands no page. useLayoutEffect(() => { @@ -2089,12 +2225,14 @@ function Timeline({ // A read-ahead the reader scrolls into reach of is theirs now, and // survives leaving the channel as their own reads do. if ( + mode.hostNavigation && window.loadingOlder && userScrolled.current && element.scrollTop < ahead.distance ) fillReading.current = false; if ( + !mode.hostNavigation || !handle.current || !userScrolled.current || window.status !== "ready" || @@ -2127,7 +2265,7 @@ function Timeline({ !after.historyLimited && !after.error; }, - [window, queries, channelId], + [window, queries, channelId, mode.hostNavigation], ); useLayoutEffect(() => { if (olderDemand.current && scroller.current) @@ -2136,6 +2274,7 @@ function Timeline({ // A detached window reads the rows above it as the reader nears its end. const loadNearBottom = (element: HTMLElement) => { if ( + !mode.hostNavigation || !window.hasNewer || window.loadingNewer || window.error || @@ -2181,6 +2320,7 @@ function Timeline({ const element = scroller.current; if ( !element || + !mode.hostNavigation || !settled.current || pendingReveal.current || (targetId && revealedSignal !== targetSignal) || @@ -2231,6 +2371,7 @@ function Timeline({ targetId, targetSignal, revealedSignal, + mode.hostNavigation, ]); // After positioning's frame, and again once Virtua measures estimated rows. // The first read waits until the opening paint's work is done. @@ -2259,6 +2400,7 @@ function Timeline({ }; }, [scheduleFill, size]); const gesture = (upward = false) => { + placement.cancel(); const restoring = pendingRestore.current === intent.current; restoredAnchor.current = undefined; layoutCorrection.current = false; @@ -2289,7 +2431,8 @@ function Timeline({ loadNearTop(scroller.current); }; // A detached window always leads to the latest rows. - const jumpVisible = showJumpToLatest || !!window.hasNewer; + const jumpVisible = + mode.chronologicalChrome && (showJumpToLatest || !!window.hasNewer); const feed = (
    {shownIntro} {edgeError && {edgeError}} - {window.historyLimited ? ( + {!mode.chronologicalChrome ? null : window.historyLimited ? ( History window limit reached ) : window.hasMore && queries.channels.cachedOnly ? ( You can load older messages once Buzz reconnects. @@ -2477,10 +2620,10 @@ function Timeline({ ? rows[index + 1] : publicMessageNeighbor(rows, index, 1); const day = - index === 0 - ? true - : calendarDay(rows[index - 1]?.createdAt ?? 0) !== - calendarDay(row.createdAt); + mode.chronologicalChrome && + (index === 0 || + calendarDay(rows[index - 1]?.createdAt ?? 0) !== + calendarDay(row.createdAt)); const toggleDisclosure = () => { if (!disclosure) return; intent.current++; @@ -2513,18 +2656,21 @@ function Timeline({ )} stackPrevious={ inside || - (!!previousRow && + (mode.chronologicalChrome && + !!previousRow && !foldedActivity.has(previousRow.id) && continuesMessageGroup(previousRow, row)) } stackNext={ inside || presentation.bubbleAnchors.has(row.id) || - (row.id === lastPublicMessage?.id && + (mode.chronologicalChrome && + row.id === lastPublicMessage?.id && row.audience !== "agents" && !row.membership && row.authorId === liveAgents[0]) || - (!!nextRow && + (mode.chronologicalChrome && + !!nextRow && !foldedActivity.has(nextRow.id) && continuesMessageGroup(row, nextRow)) } @@ -2644,7 +2790,8 @@ function Timeline({ })} )} - {!rows.length && + {mode.chronologicalChrome && + !rows.length && !shownIntro && !window.hasMore && window.status === "ready" && @@ -2673,7 +2820,9 @@ function Timeline({ session={queries} channelId={channelId} previousAuthor={ - lastPublicMessage && !lastPublicMessage.membership + mode.chronologicalChrome && + lastPublicMessage && + !lastPublicMessage.membership ? lastPublicMessage.authorId : undefined } @@ -2684,5 +2833,30 @@ function Timeline({
    ); - return {feed}; + return ( + + {arrangement && extensions?.accessories ? ( +
    +
    + canOpenLink?.(target) ?? false} + open={onOpenLink} + /> +
    + {feed} +
    + ) : ( + feed + )} +
    + ); } diff --git a/src/features/messages/Messages.module.css b/src/features/messages/Messages.module.css index 79fc5abb9a..f67918acf5 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); @@ -2523,6 +2546,44 @@ html[data-keyboard-navigation] .replyBranchCollapse:focus-visible { --reply-spine-offset: calc(0px - var(--space-2)); } } +/* In an inline thread sheet, the header overlays the panel at z-index 2. + When the reader bar has controls, start them where the header's material + ends and drop the duplicate top clearance on the history below. */ +[data-details-sheet-surface][data-height="content"][data-contained-composer] +.readerBar:not(:empty) { + margin-top: calc( + var(--sheet-header-height) + + var(--space-3) - + var(--space-1) + ); +} +[data-details-sheet-surface][data-height="content"][data-contained-composer] + .readerBar:not(:empty) + + .threadHistoryFrame + > .threadHistory { + padding-top: calc(var(--space-4) - var(--space-3) - var(--space-half)); + scroll-padding-top: 0; +} +[data-details-sheet-surface][data-height="content"][data-contained-composer] + .readerBar:not(:empty) + + .threadHistoryFrame + > .threadHistory + [data-new-messages-boundary] { + scroll-margin-top: 0; +} +[data-details-sheet-surface][data-height="content"][data-contained-composer] + .readerBar:not(:empty) + + .threadHistoryFrame + > .threadHistory:has(> .threadLoading) { + min-height: calc(4 * var(--space-16)); +} +[data-details-sheet-surface][data-height="content"][data-contained-composer] + .readerBar:not(:empty) + + .threadHistoryFrame + .threadLoading { + min-height: calc(4 * var(--space-16)); + padding-top: var(--space-4); +} .spoiler { display: inline-block; diff --git a/src/features/messages/ReplyBranch.tsx b/src/features/messages/ReplyBranch.tsx index ae641812f1..514e8aeb10 100644 --- a/src/features/messages/ReplyBranch.tsx +++ b/src/features/messages/ReplyBranch.tsx @@ -71,6 +71,24 @@ export function ReplyBranch({ ]); }; }, []); + const summaryRef = useCallback((button: HTMLButtonElement | null) => { + summaryButton.current = button; + if (!button) return; + return () => { + if (summaryButton.current === button) summaryButton.current = null; + if (document.activeElement !== button) return; + const branch = button.closest("[data-depth]"); + recoverFocus(button, [ + messageBox(branch?.querySelector("[data-message-id]")), + messageBox( + branch?.parentElement + ?.closest("[data-depth]") + ?.querySelector("[data-message-id]"), + ), + threadHistory(button), + ]); + }; + }, []); // The thread line vanishes when live updates remove its replies or branch. const collapseRef = useCallback((button: HTMLButtonElement | null) => { if (!button) return; @@ -99,7 +117,7 @@ export function ReplyBranch({ {hasReplies && !open && (
    +
    + + ), +})); +vi.mock("./MessageComposer", () => ({ + MessageComposer: ({ + replyParentId, + replyContext, + editMessages, + }: MessageComposerProps) => ( +
    row.content).join(",")} + > + {replyContext} +
    + ), +})); + +const viewer = keypair(); +const other = keypair(); +const relay = keypair(); +const T = 1_700_000_000; +const DAY = 86_400; +const proven = (event: RelayEvent): EventData => eventDto(event); +const root = proven(message(other, "c", "root", T)); +const replyEvent = (name: string, at: number): EventData => + proven(message(other, "c", name, at, [["e", root.id, "", "reply"]])); +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; +}); + +let scrolled = 0; +beforeEach(() => { + scrolled = 0; + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + disconnect() {} + }, + ); + 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); + 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"], +) => ({ + id: "arranger", + key: "test:arranger", + pluginId: "test", + revision: "one", + title: "Arranger", + placement: "reader", + component, +}); + +function mount({ + replies = [], + snapshot = {}, + props = {}, + strict = false, + onProps, + navigation, + unread = {}, + fold, +}: { + replies?: readonly EventData[]; + snapshot?: Partial; + props?: Partial; + strict?: boolean; + onProps?: (props: ComposerAccessoryProps) => void; + navigation?: PageNavigation; + unread?: Partial>; + fold?: RelaySession["foldRows"]; +} = {}) { + 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[]) => + 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, + ...(fold ? { foldRows: fold } : {}), + thread, + unread: { ...owner.session.unread, ...unread }, + } as RelaySession; + const latest: { current?: ComposerAccessoryProps } = {}; + const registry = { + snapshot: () => entries, + subscribe: () => () => {}, + }; + const entries = [ + readerEntry((accessory) => { + latest.current = accessory; + useLayoutEffect(() => { + onProps?.(accessory); + }); + return ; + }), + ]; + const element = ( + {}} + active + onOpenLink={() => false} + extensions={ + { accessories: registry } as unknown as ConversationExtensions + } + navigation={navigation} + {...props} + /> + ); + const rendered = render( + strict ? {element} : element, + ); + return { + unmount: () => rendered.unmount(), + view, + thread, + session, + receive: callbacks.receive, + latest, + rowsOf, + 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); + }); + }, + }; +} +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, panel?: "members") => + ({ + entryId: "visit", + target: { + version: 1, + kind: "conversation", + channelId: "c", + messageId, + threadRootId: root.id, + ...(panel ? { panel } : {}), + 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); + 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 }, + }); + 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"]); + 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"]); + 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] }); + 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(); + 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(); + 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], + }); + 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(); + 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(); +}); + +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", async () => { + 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] }); + 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); +}); + +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", () => { + 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); +}); + +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", () => { + 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(); + expect(navigation.savePosition).not.toHaveBeenCalled(); +}); + +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("folds no relayed run under a presentation, and folds the host's again after it", () => { + let relayed: ChannelMessage[] = []; + const h = mount({ replies: [a, b, c], fold: () => relayed }); + relayed = h + .rowsOf([a, b, c]) + .map((row) => ({ ...row, relayedFrom: { agent: "zerk", verified: true } })); + h.publish({ replies: relayed }); + const run = () => + screen.queryByRole("button", { name: /^Show 3 messages by zerk\./ }); + expect(run()).toBeVisible(); + h.present({ ids: [c.id, a.id, b.id] }); + expect(drawn()).toEqual(["root", "c", "a", "b"]); + expect(run()).toBeNull(); + h.withdraw(); + expect(run()).toBeVisible(); +}); + +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 }, + snapshot: { targetStatus: "loading" }, + }); + expect(lastReading().settled.current).toBe(false); + h.present({ ids: [a.id, b.id] }); + 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 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, + latestMessageId: d.id, + catchUpMessageId: undefined, + }); + h.present({ + ids: [c.id, a.id, b.id], + parents: { [b.id]: a.id }, + open: [a.id], + }); + expect(lastReading()).toMatchObject({ + partial: true, + latestMessageId: b.id, + catchUpMessageId: c.id, + }); + expect(lastReading().controls?.current).toBe( + screen.getByText("bar").parentElement, + ); + fireEvent.click(screen.getByRole("button", { name: /Collapse 1 reply/ })); + expect(lastReading().latestMessageId).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, latestMessageId: c.id }); + fireEvent.click( + screen.getByRole("button", { name: /1 reply/, expanded: false }), + ); + expect(lastReading()).toMatchObject({ + partial: false, + latestMessageId: d.id, + }); + h.present({ ids: [a.id, b.id, c.id, d.id], complete: true }); + expect(lastReading()).toMatchObject({ + partial: false, + latestMessageId: d.id, + }); + h.withdraw(); + expect(lastReading()).toMatchObject({ + partial: false, + latestMessageId: d.id, + catchUpMessageId: undefined, + }); +}); + +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); + 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] }); + scrolled = 150; + h.present({ ids: [d.id, a.id, b.id, c.id] }); + expect(scrolled).toBe(250); + 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"]); + h.publish({ status: "idle", root: undefined, replies: [] }); + expect(screen.queryByText("bar")).toBeNull(); + expect(present?.({ ids: [a.id], events: [a] })).toBe("retired"); +}); + +it("keeps editMessages chronological, suppresses arrival counts, and settles reading while presented", () => { + const h = mount({ + replies: [a, b], + snapshot: { direction: "forward", canLoadMore: true }, + }); + expect(readingProps.at(-1)?.settled.current).toBe(false); + h.present({ ids: [c.id, b.id, a.id], place: "start" }); + expect(readingProps.at(-1)?.settled.current).toBe(true); + expect(screen.getByLabelText("Composer")).toHaveAttribute( + "data-edit-messages", + "root,a,b,c", + ); + h.publish({ + replies: h.rowsOf([root, a, b, d]).slice(1), + canLoadMore: false, + }); + h.publish({ + replies: h.rowsOf([root, a, b, c, d]).slice(1), + canLoadMore: false, + }); + scrolled = 150; + h.withdraw(); + expect( + screen.getByRole("button", { name: "Jump to latest" }), + ).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /new message/i })).toBeNull(); +}); + +it("transfers focus when a presentation or live deletion removes the focused reply, without stealing focus from reader-bar controls", () => { + vi.useFakeTimers(); + const rowBox = (event: EventData) => + document.querySelector( + `[data-message-id="${event.id}"] > [data-layout]`, + ); + + const h = mount({ replies: [a, b, c] }); + expect(h.latest.current?.linkedMessageId).toBeUndefined(); + const initial = rowBox(a) as HTMLElement; + initial.tabIndex = -1; + initial.focus(); + expect(document.activeElement).toBe(initial); + + h.present({ ids: [b.id, c.id] }); + expect(document.activeElement).toBe(rowBox(b)); + + const dropB = eventDto( + signed(other, { + kind: 5, + content: "", + created_at: T + 50, + tags: [ + ["h", "c"], + ["e", b.id], + ], + }), + ); + scrolled = 0; + act(() => { + h.receive([dropB], { phase: "live", channelId: "c" }); + }); + rowBox(b)?.dispatchEvent( + new FocusEvent("focusout", { bubbles: true, relatedTarget: null }), + ); + act(() => { + vi.advanceTimersToNextFrame(); + }); + expect(drawn()).toEqual(["root", "c"]); + expect(document.activeElement).toBe(rowBox(c)); + expect(scrolled).toBe(0); + + h.present({ ids: [] }); + expect(document.activeElement).toBe(scroller()); + + h.present({ ids: [a.id, c.id] }); + const barControl = screen.getByRole("button", { name: "bar" }); + const focusedA = rowBox(a) as HTMLElement; + focusedA.tabIndex = -1; + focusedA.focus(); + barControl.focus(); + h.present({ ids: [c.id] }); + expect(document.activeElement).toBe(barControl); +}); + +it("transfers focus when removing a collapsed reply branch or its nested replies, keeping keyboard selection active", async () => { + const rowBox = (event: EventData) => + document.querySelector( + `[data-message-id="${event.id}"] > [data-layout]`, + ); + + const h = mount({ replies: [d] }); + h.present({ + ids: [a.id, b.id, c.id, d.id], + parents: { [b.id]: a.id, [c.id]: a.id }, + }); + const summary = screen.getByRole("button", { name: /View 2 replies/ }); + summary.focus(); + expect(document.activeElement).toBe(summary); + summary.dispatchEvent( + new FocusEvent("focusout", { bubbles: true, relatedTarget: null }), + ); + h.present({ ids: [d.id] }); + expect(document.activeElement).toBe(rowBox(d)); + await Promise.resolve(); + + h.present({ + ids: [a.id, b.id, c.id, d.id], + parents: { [b.id]: a.id, [c.id]: a.id }, + }); + const branchSummary = screen.getByRole("button", { name: /View 2 replies/ }); + branchSummary.focus(); + expect(document.activeElement).toBe(branchSummary); + h.present({ ids: [a.id, d.id] }); + await Promise.resolve(); + expect(document.activeElement).toBe(rowBox(a)); + + fireEvent.keyDown(scroller(), { key: "ArrowDown" }); + expect(document.activeElement).toBe(rowBox(d)); +}); + +it("keeps uninterrupted focus on a pending linked reply through withdrawal and missing-anchor fallback, while recovering on pending deletion", () => { + const rowEl = (event: EventData) => + document.querySelector(`[data-message-id="${event.id}"]`); + const rowBox = (event: EventData) => + document.querySelector( + `[data-message-id="${event.id}"] > [data-layout]`, + ); + + const rootNav = navigationTo(root.id); + const rootOpen = mount({ + replies: [a, d, b], + navigation: rootNav, + props: { messageId: root.id }, + }); + expect(rootOpen.latest.current?.linkedMessageId).toBeUndefined(); + rootOpen.unmount(); + + const membersOpen = mount({ + replies: [a, d, b], + navigation: navigationTo(d.id, "members"), + props: { messageId: d.id, tabbed: true }, + }); + expect(membersOpen.latest.current?.linkedMessageId).toBeUndefined(); + membersOpen.unmount(); + + const linked = mount({ + replies: [a, d, b], + navigation: navigationTo(d.id), + props: { messageId: d.id }, + snapshot: { targetStatus: "loading" }, + }); + expect(linked.latest.current?.linkedMessageId).toBe(d.id); + const targetBefore = rowEl(d) as HTMLElement; + targetBefore.tabIndex = -1; + targetBefore.focus(); + linked.present({ ids: [a.id, b.id] }); + expect(linked.latest.current?.presentation).toBe("none"); + expect(rowEl(d)).toBe(targetBefore); + expect(document.activeElement).toBe(targetBefore); + linked.unmount(); + + vi.useFakeTimers(); + const pendingDelete = mount({ + replies: [a, b], + navigation: navigationTo(d.id), + props: { messageId: d.id }, + snapshot: { targetStatus: "loading" }, + }); + pendingDelete.present({ + ids: [a.id, d.id, b.id], + events: [root, a, d, b], + }); + const focusedD = rowBox(d) as HTMLElement; + focusedD.tabIndex = -1; + focusedD.focus(); + act(() => { + pendingDelete.receive( + [ + eventDto( + signed(other, { + kind: 5, + content: "", + created_at: T + 70, + tags: [ + ["h", "c"], + ["e", d.id], + ], + }), + ), + ], + { phase: "live", channelId: "c" }, + ); + }); + focusedD.dispatchEvent( + new FocusEvent("focusout", { bubbles: true, relatedTarget: null }), + ); + act(() => { + vi.advanceTimersToNextFrame(); + }); + pendingDelete.publish({ targetStatus: "unavailable", target: undefined }); + expect(document.activeElement).toBe(rowBox(b)); + pendingDelete.unmount(); + vi.useRealTimers(); + + const savedNav = navigationTo(d.id); + const restored = mount({ + replies: [a, d, b], + navigation: { + ...savedNav, + traversal: true, + position: (key) => + key === "thread" + ? { anchor: { id: a.id, top: 0, ancestors: [] } } + : undefined, + }, + props: { messageId: d.id }, + snapshot: { targetStatus: "ready", target: undefined }, + }); + expect(restored.latest.current?.linkedMessageId).toBeUndefined(); + restored.unmount(); + + const missingAnchorNav = navigationTo(d.id); + const fallback = mount({ + replies: [a, d, b], + navigation: { + ...missingAnchorNav, + traversal: true, + position: (key) => + key === "thread" + ? { anchor: { id: c.id, top: 0, ancestors: [] } } + : undefined, + }, + props: { messageId: d.id }, + snapshot: { targetStatus: "loading" }, + }); + fallback.publish({ targetStatus: "ready", target: rowOf(fallback, d) }); + expect(fallback.latest.current?.linkedMessageId).toBe(d.id); + const fallbackBefore = rowEl(d) as HTMLElement; + fallbackBefore.tabIndex = -1; + fallbackBefore.focus(); + fallback.present({ ids: [a.id, b.id] }); + expect(fallback.latest.current?.presentation).toBe("none"); + expect(rowEl(d)).toBe(fallbackBefore); + expect(document.activeElement).toBe(fallbackBefore); +}); diff --git a/src/features/messages/ThreadPanel.test.tsx b/src/features/messages/ThreadPanel.test.tsx index 0f855dbaee..ab4dd01b19 100644 --- a/src/features/messages/ThreadPanel.test.tsx +++ b/src/features/messages/ThreadPanel.test.tsx @@ -699,7 +699,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 6cb652f085..e34f6f9cb1 100644 --- a/src/features/messages/ThreadPanel.tsx +++ b/src/features/messages/ThreadPanel.tsx @@ -28,6 +28,13 @@ import { useMessageSelectionCopy } from "./selection-copy"; import { ReplySummary } from "./ReplySummary"; import { ReplyBranch } from "./ReplyBranch"; import { replyTree } from "./reply-tree"; +import { + readerMode, + useArrangement, + usePlace, + usePresentedFocusRecovery, +} 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"; @@ -51,6 +58,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, @@ -263,6 +271,22 @@ type ThreadPlace = { anchor?: { id: string; top: number; ancestors: readonly string[] }; }; const THREAD_PLACE = "thread"; +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 = { @@ -704,13 +728,64 @@ function ThreadMessages({ const current = view.snapshot(); return current.status === "ready" ? current.root : undefined; }, [view]); - const tree = useMemo( + const [lostPlace, setLostPlace] = useState(); + const returning = + !!navigation?.traversal && + lostPlace !== navigation.signal && + navigation.position(THREAD_PLACE) !== undefined; + const rootTarget = + navigation?.target.kind === "conversation" && + navigation.target.threadRootId === messageId; + const positionedVisit = rootTarget || returning; + const [inlineReveal, setInlineReveal] = useState(); + // biome-ignore lint/correctness/useExhaustiveDependencies: each reveal request needs its own signal. + useEffect(() => { + if (!revealSelected) return; + const request = new AbortController(); + setInlineReveal(request.signal); + return () => request.abort(); + }, [revealSelected, revealRequest]); + const [revealedSignal, setRevealedSignal] = useState(); + const [withdrawnSignal, setWithdrawnSignal] = useState(); + const requested = + inlineReveal ?? (positionedVisit ? undefined : navigation?.signal); + const [arrangement, presented] = useArrangement({ + session, + channelId, + rootId: subthreadId ? undefined : resolvedRoot, + limits: THREAD_LIMITS, + }); + const targetHidden = + !!presented && + messageId !== resolvedRoot && + !presented.rows.some((row) => row.id === messageId); + const exactPending = + active && !!requested && !requested.aborted && revealedSignal !== requested; + const willWithdraw = + targetHidden && exactPending && withdrawnSignal !== requested; + const display = willWithdraw ? undefined : presented; + const mode = readerMode(display); + const modeNow = useRef(mode); + modeNow.current = mode; + 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); @@ -718,7 +793,7 @@ function ThreadMessages({ } } return branches; - }, [tree, snapshot.replies]); + }, [tree, shownReplies]); const subscribeUnread = useCallback( (listener: () => void) => session.unread.subscribe( @@ -773,6 +848,26 @@ function ThreadMessages({ ) : undefined; const replyParent = useReplyTarget(session, scope, targetKey); + 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]); + 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 collapsed = + mode.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; @@ -787,19 +882,30 @@ 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], + ); + const editRows = useMemo(() => { + if (!display) return hostRows; + const byId = new Map(hostRows.map((row) => [row.id, row])); + for (const row of display.rows) byId.set(row.id, row); + return [...byId.values()].sort(compareMessages); + }, [display, 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); @@ -813,6 +919,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); @@ -881,11 +988,6 @@ function ThreadMessages({ ); // Back/Forward to a visit with a recorded place returns there instead of // replaying its opening, unless that place can no longer be shown. - const [lostPlace, setLostPlace] = useState(); - const returning = - !!navigation?.traversal && - lostPlace !== navigation.signal && - navigation.position(THREAD_PLACE) !== undefined; const restoredVisit = useRef(undefined); // The row Back/Forward restored. If it joins a folded group later, as a // relay does once its owner verifies, that group opens once to keep it shown; @@ -961,10 +1063,14 @@ function ThreadMessages({ container.scrollTop : undefined; }, [selectedRow]); + const revealSignal = targetHidden ? undefined : requested; + const revealSignalRef = useRef(revealSignal); + revealSignalRef.current = revealSignal; const completeTarget = useCallback(() => { // Exact lookup can finish before context. Preserve this row's reading // position through prepended history without refocusing it after opening. targetAnchor.current = selectedOffset(); + if (revealSignalRef.current) setRevealedSignal(revealSignalRef.current); setInitialPositioned(true); captureResizePosition(); readingSettled.current = true; @@ -1015,11 +1121,6 @@ function ThreadMessages({ return new Set([...current, ...ancestors]); }); }, [tree, messageId, navigation, revealRequest]); - const rootTarget = - navigation?.target.kind === "conversation" && - navigation.target.threadRootId === messageId; - // Ordinary opens are positioned, not revealed; so is a return to a saved place. - const positionedVisit = rootTarget || returning; // Reopening an already-shown thread selects nothing new, so its reader needs // a focus handoff to start reading. First positioning leaves the opening's // tab/composer focus handoff alone. @@ -1136,7 +1237,9 @@ function ThreadMessages({ snapshot.readKind === "older" || (!(snapshot.root && snapshot.direction) && (snapshot.status !== "ready" || - (snapshot.direction !== "older" && snapshot.canLoadMore))) + (mode.hostNavigation && + snapshot.direction !== "older" && + snapshot.canLoadMore))) ) return; // An inactive reader reads nothing. Shown, it is a preview and gets no @@ -1158,14 +1261,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); @@ -1200,16 +1303,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 && mode.hostNavigation) 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 @@ -1228,34 +1332,21 @@ function ThreadMessages({ rootTarget, snapshot, messageId, - tree, + hostTree, + mode.hostNavigation, session.unread, channelId, view, threadUnread, ]); - const [inlineReveal, setInlineReveal] = useState(); - // biome-ignore lint/correctness/useExhaustiveDependencies: each reveal request needs its own signal. - useEffect(() => { - if (!revealSelected) return; - const request = new AbortController(); - setInlineReveal(request.signal); - return () => request.abort(); - }, [revealSelected, revealRequest]); - const revealSignal = - inlineReveal ?? (positionedVisit ? undefined : navigation?.signal); + const withdrawnFor = useRef(undefined); + const membersVisit = + navigation?.target.kind === "conversation" && + navigation.target.panel === "members"; const revealed = useMessageReveal({ scroller, - focus: - revealFocus !== false && - !( - navigation?.target.kind === "conversation" && - navigation.target.panel === "members" - ), - mark: !( - navigation?.target.kind === "conversation" && - navigation.target.panel === "members" - ), + focus: revealFocus !== false && !membersVisit, + mark: !membersVisit, settled: positioned, messageId, signal: active ? revealSignal : undefined, @@ -1288,7 +1379,7 @@ function ThreadMessages({ if (!presented) return; const record = () => { const reading = resizePosition.current; - if (!reading) return; + if (!reading || !modeNow.current.hostNavigation) return; const id = reading.anchor?.element.dataset.messageId; navigation.savePosition( THREAD_PLACE, @@ -1380,26 +1471,29 @@ 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) ?? [], + mode.chronologicalChrome ? (tree.children.get(undefined) ?? []) : [], activitySnapshot, agentPubkeys, rootId, undefined, - loadedRows, + hostRows, ), - [tree, activitySnapshot, agentPubkeys, rootId, loadedRows], + [ + tree, + mode.chronologicalChrome, + activitySnapshot, + agentPubkeys, + rootId, + hostRows, + ], ); const liveAgents = useLiveConversationAgents(session, channelId, rootId); const lastMessage = publicMessageNeighbor(rows, rows.length, -1); const joinsLive = + mode.chronologicalChrome && !!lastMessage && !lastMessage.membership && lastMessage.audience !== "agents" && @@ -1482,12 +1576,13 @@ function ThreadMessages({ // Only legacy traversal is eager. Strict windows open at the newest page. useEffect(() => { if ( + mode.hostNavigation && snapshot.direction !== "older" && snapshot.status === "ready" && snapshot.canLoadMore ) void view.loadMore(); - }, [view, snapshot]); + }, [view, snapshot, mode.hostNavigation]); useLayoutEffect(() => { const previous = previousReplies.current; const complete = snapshot.status === "ready" && !snapshot.canLoadMore; @@ -1511,7 +1606,7 @@ function ThreadMessages({ ), complete: true, }; - if (arrivals > 0 && !follow.current) + if (modeNow.current.hostNavigation && arrivals > 0 && !follow.current) setNewMessageCount((count) => count + arrivals); }, [snapshot.status, snapshot.canLoadMore, snapshot.replies]); // biome-ignore lint/correctness/useExhaustiveDependencies: Rendered rows/profiles change scroll height; sending is explicit navigation intent. @@ -1528,6 +1623,27 @@ function ThreadMessages({ revealed.current !== navigation.signal ) { revealed.current = navigation.signal; + setRevealedSignal(navigation.signal); + navigation.complete({ status: "opened" }); + } + if ( + targetHidden && + active && + requested && + !requested.aborted && + revealed.current !== requested && + withdrawnFor.current !== requested + ) { + withdrawnFor.current = requested; + setWithdrawnSignal(requested); + arrangement?.withdraw(); + } else if ( + navigation && + targetHidden && + revealed.current !== navigation.signal + ) { + revealed.current = navigation.signal; + setRevealedSignal(navigation.signal); navigation.complete({ status: "opened" }); } // A mounted ordinary thread acknowledges the visit before slow history can @@ -1555,7 +1671,9 @@ function ThreadMessages({ (!positioned.current && !(snapshot.root && snapshot.direction) && (snapshot.status !== "ready" || - (snapshot.direction !== "older" && snapshot.canLoadMore))) || + (!mode.presented && + snapshot.direction !== "older" && + snapshot.canLoadMore))) || (!positioned.current && unreadBoundary === undefined && !openLatest) ) return; @@ -1617,6 +1735,7 @@ function ThreadMessages({ .find((row) => row); if (anchor && !row) { revealed.current = undefined; + setRevealedSignal(undefined); setLostPlace(navigation.signal); return; } @@ -1802,6 +1921,10 @@ function ThreadMessages({ expanded, expandedActivity, boundary, + targetHidden, + requested, + arrangement, + mode.presented, ]); // 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 @@ -1835,7 +1958,9 @@ function ThreadMessages({ return; if ( snapshot.status === "ready" && - (snapshot.direction === "older" || !snapshot.canLoadMore) + (mode.presented || + snapshot.direction === "older" || + !snapshot.canLoadMore) ) { readingSettled.current = true; readingPositioned(scroller.current); @@ -1848,6 +1973,8 @@ function ThreadMessages({ revealed, snapshot, unreadBoundary, + targetHidden, + mode.presented, ]); // 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. @@ -1906,6 +2033,46 @@ function ThreadMessages({ observer.observe(end); return () => observer.disconnect(); }, [active, initialPositioned, captureResizePosition, selectedOffset]); + const place = usePlace(arrangement, () => anchorAt(scroller.current)); + useLayoutEffect(() => { + const element = scroller.current; + 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") { + 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, + ]); + usePresentedFocusRecovery( + scroller, + arrangement !== undefined, + display, + shownReplies, + ); const jumpToLatest = () => { const element = scroller.current; if (!element) return; @@ -1928,6 +2095,7 @@ function ThreadMessages({ }, 1000); }; const keepReadingPosition = () => { + place.cancel(); jumpingToLatest.current = false; remounted.current = undefined; if (jumpTimer.current !== undefined) { @@ -1957,18 +2125,19 @@ function ThreadMessages({ ); if (parent === undefined && snapshot.root) requestRows.set(snapshot.root.id, snapshot.root); + const foldable = mode.chronologicalChrome ? chronologicalSiblings : []; const presentation = activityPresentation( - chronologicalSiblings, + foldable, 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, - ...relayedRuns(chronologicalSiblings, lineRow ?? undefined), + ...relayedRuns(foldable, lineRow ?? undefined), ].filter((group) => group.ids.every((id) => !tree.children.get(id)?.length), ); @@ -1991,6 +2160,7 @@ function ThreadMessages({ : publicMessageNeighbor(siblings, index, 1); const children = tree.children.get(row.id); const continuation = + mode.chronologicalChrome && !!previousReply && previousReply !== snapshot.root && previousParent === parent && @@ -2002,7 +2172,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 = mode.chronologicalChrome && previousDay !== currentDay; previousDay = currentDay; previousReply = children?.length && !expanded.has(row.id) ? undefined : row; @@ -2052,7 +2222,8 @@ function ThreadMessages({ inside || presentation.bubbleAnchors.has(row.id) || (joinsLive && row.id === lastMessage?.id) || - (!!nextRow && + (mode.chronologicalChrome && + !!nextRow && continuesMessageGroup(row, nextRow) && !children?.length) } @@ -2111,7 +2282,7 @@ function ThreadMessages({ className={styles.replyItem} data-layout={continuation ? "continuation" : "thread"} > - {!parent && row.id === lineRow && ( + {mode.chronologicalChrome && !parent && row.id === lineRow && (

    )} {/* Not while the root, or history that may hold the parent, loads. */} - {!parent && + {mode.chronologicalChrome && + !parent && rootId && !snapshot.seeking && row.replyParentId && @@ -2216,7 +2388,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); // A target kept from an earlier reader is judged once this one has read the // thread. Until then the reply box waits: it neither says the target is // gone nor sends to it. @@ -2272,6 +2446,7 @@ function ThreadMessages({ const element = scroller.current; if ( !element || + !mode.hostNavigation || !olderDemand.current || snapshot.direction !== "older" || snapshot.status !== "ready" || @@ -2287,12 +2462,14 @@ function ThreadMessages({ const selectionNotice = selectionFailure && !snapshot.error ? selectionFailure : undefined; const showOlderPageStatus = + mode.chronologicalChrome && snapshot.direction === "older" && snapshot.readKind === "older" && !!snapshot.root; const targetUnavailable = snapshot.targetStatus === "unavailable" && !selectionNotice; - const historyError = !!snapshot.error && !showOlderPageStatus; + const historyError = + mode.chronologicalChrome && !!snapshot.error && !showOlderPageStatus; const focusArchivedHistory = useCallback(() => { const history = scroller.current; if ( @@ -2317,6 +2494,11 @@ function ThreadMessages({ void view.loadMore(); } else void view.refresh(); }; + const newestReply = shownReplies.reduce( + (latest, row) => + !latest || compareMessages(row, latest) > 0 ? row : latest, + undefined, + )?.id; return ( ( - (latest, row) => - !latest || compareMessages(row, latest) > 0 ? row : latest, - undefined, - )?.id + ? mode.presented + ? endRow + : newestReply : undefined } + catchUpMessageId={mode.presented ? newestReply : undefined} + partial={mode.partialReading || collapsed} + controls={readerBar} /> + {arrangement && extensions?.accessories && ( +
    + canOpenLink?.(target) ?? false} + open={openViewLink} + /> +
    + )} {/* The reader's scrollport, with its edge material for a sheet. */}
    { if (!positioned.current) return; const element = event.currentTarget; @@ -2428,7 +2637,7 @@ function ThreadMessages({ tabIndex={0} > @@ -2547,7 +2756,7 @@ function ThreadMessages({ : "Couldn’t open that message."}

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

    Thread history limit reached.

    )} {(historyError || (targetUnavailable && snapshot.root)) && ( @@ -2664,7 +2873,7 @@ function ThreadMessages({ ) ) } - editMessages={rows} + editMessages={editRows} focusRequest={pendingReplyFocus ?? 0} autoFocus={autoFocus ?? false} onOpenLink={onOpenLink} diff --git a/src/features/messages/arrangement.test.ts b/src/features/messages/arrangement.test.ts new file mode 100644 index 0000000000..38b2162f24 --- /dev/null +++ b/src/features/messages/arrangement.test.ts @@ -0,0 +1,868 @@ +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 type { LiveCallbacks } from "../relay/live"; +import { + flush, + keypair, + message, + roster, + scriptedTransport, + signed, + type Key, +} from "../relay/testing"; +import { + applyLiveEvents, + createArrangement, + createPlace, + focusRecoveryTarget, + nearestShown, + placeIntent, + readerMode, + selectEvidence, +} 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(); +}); +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, + frame() { + for (const [id, run] of [...frames]) { + frames.delete(id); + run(); + } + }, + }; +} +const lane = (key: string) => ({ key }); +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}`), + ); + 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 }); + const one = lane("one"); + arrangement.present(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(one, { ids: [a, b], events }); + expect(arrangement.snapshot()).toMatchObject({ + open: [], + complete: false, + place: "keep", + }); + expect(arrangement.snapshot()?.parents).toBeUndefined(); + arrangement.present(one, { ids: [a, b], events, parents: {} }); + expect(arrangement.snapshot()?.parents?.size).toBe(0); +}); + +it("refuses duplicate ids and too many 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); + 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(); + 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 more ids than its row limit, and keeps what it shows", () => { + const { root } = thread(0); + const { arrangement } = host({ + rootId: root.id, + limits: { rows: 2, events: 2000, bytes: 4 << 20 }, + }); + const first = lane("one"); + expect(arrangement.present(first, { ids: ["x", "y"], events: [] })).toBe( + "shown", + ); + const shown = arrangement.snapshot(); + expect(arrangement.present(first, { ids: ["x", "y", "z"], events: [] })).toBe( + "limit", + ); + expect(arrangement.snapshot()).toBe(shown); +}); + +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 }, + }); + 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; + 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); + 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(); + 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"); + 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 }); + const one = lane("one"); + arrangement.present(one, { ids: [row.id], events }); + receive([reaction(other, row, 30)], live); + arrangement.present(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 ?? ""; + const one = lane("one"); + arrangement.present(one, { ids: [], events }); + expect(arrangement.snapshot()?.rows).toEqual([]); + arrangement.present(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 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("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"); + expect(arrangement.present(second, { ids: [b.id, b.id], events })).toBe( + "invalid", + ); + expect(arrangement.status(second)).toBe("held"); + expect(arrangement.status(lane("b"))).toBe("none"); + expect(ids(arrangement.snapshot()?.rows)).toEqual([a.id]); + 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"); + 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(); +}); + +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(); + 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); + const second = lane("b"); + expect(arrangement.present(second, { ids: [a.id], events })).toBe("held"); + expect(seen).toHaveLength(3); + arrangement.present(second, null); + expect(arrangement.status(second)).toBe("none"); + expect(arrangement.snapshot()?.revision).toBe(2); + expect(seen).toHaveLength(4); + arrangement.present(first, null); + expect(arrangement.snapshot()).toBeUndefined(); + expect(seen).toHaveLength(5); + arrangement.present(lane("never"), null); + expect(seen).toHaveLength(5); +}); + +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"); + 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"); + 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", + }); +}); + +it("keeps live reactions on the thread root out of the reply presentation budget", () => { + const { root, replies, events } = thread(1); + const [a] = replies; + const { arrangement, receive } = host({ + rootId: root.id, + limits: { rows: 10, events: 2, bytes: 4 << 20 }, + }); + const first = lane("a"); + expect(arrangement.present(first, { ids: [a.id], events })).toBe("shown"); + receive([reaction(other, root, 30), reaction(viewer, root, 31)], live); + expect(arrangement.status(first)).toBe("shown"); + expect(ids(arrangement.snapshot()?.rows)).toEqual([a.id]); +}); + +it("preserves non-presented target evidence so a multi-target deletion still hides a presented row", () => { + const { root, replies, events } = thread(2); + const [a, b] = replies; + const both = deletion(other, [a.id, b.id], 30); + const { arrangement } = host({ rootId: root.id }); + expect( + arrangement.present(lane("one"), { + ids: [a.id], + events: [...events, both], + }), + ).toBe("shown"); + expect(arrangement.snapshot()?.rows).toEqual([]); +}); + +it("admits a named pending own send's verified echo so live reactions attach to it", async () => { + const { root } = thread(0); + let resolvePublish!: () => void; + let published!: RelayEvent; + const { arrangement, session, receive, frame } = host({ + rootId: root.id, + publish: (event) => { + published = event; + return new Promise((resolve) => { + resolvePublish = resolve; + }); + }, + }); + receive([root]); + await session.outbox?.ready(); + session.messages.reply("c", root.id, "mine"); + const pendingId = session.outbox?.snapshot()[0]?.event.id ?? ""; + arrangement.present(lane("one"), { ids: [pendingId], events: [root] }); + await flush(); + resolvePublish(); + await flush(); + receive([published], live); + receive([reaction(other, published, published.created_at + 1)], live); + frame(); + expect(arrangement.snapshot()?.rows[0]).toMatchObject({ + id: pendingId, + content: "mine", + }); + expect(arrangement.snapshot()?.rows[0]?.reactions).toHaveLength(1); +}); + +it("downgrades complete when a new live in-scope row arrives, keeping revision and ignoring replays", () => { + const { root, replies, events } = thread(1); + const [a] = replies; + const { arrangement, receive } = host({ rootId: root.id }); + arrangement.present(lane("one"), { + ids: [a.id], + events, + complete: true, + }); + const before = arrangement.snapshot(); + expect(before?.complete).toBe(true); + const replayed = reply(other, root, 40, "replayed"); + receive([replayed], { phase: "replay", channelId: "c" }); + expect(arrangement.snapshot()?.complete).toBe(true); + const outside = proven(message(other, "c", "top-level", 41)); + receive([outside], live); + expect(arrangement.snapshot()?.complete).toBe(true); + const arriving = reply(other, root, 42, "late"); + receive([arriving], live); + expect(arrangement.snapshot()?.complete).toBe(false); + expect(arrangement.snapshot()?.revision).toBe(before?.revision); +}); + +it("selectEvidence, applyLiveEvents and readerMode stay pure over plain values", () => { + const { root, replies, events } = thread(1); + const [a] = replies; + const scope = { channelId: "c", rootId: root.id, limits: wide }; + const picked = selectEvidence( + { ids: [a.id], events, complete: true }, + new Map(), + scope, + ); + expect(typeof picked).toBe("object"); + if (typeof picked === "string") throw new Error("expected selection"); + const rootReaction = reaction(other, root, 50); + expect( + applyLiveEvents(picked.evidence, true, [rootReaction], false, scope), + ).toEqual({ kind: "noop" }); + const late = reply(other, root, 51, "new"); + const next = applyLiveEvents(picked.evidence, true, [late], false, scope); + expect(next).toMatchObject({ + kind: "updated", + complete: false, + refold: false, + }); + expect(readerMode(undefined)).toEqual({ + presented: false, + chronologicalChrome: true, + hostNavigation: true, + partialReading: false, + }); + expect( + readerMode({ + rows: [], + parents: undefined, + open: [], + complete: false, + place: "keep", + revision: 1, + }), + ).toEqual({ + presented: true, + chronologicalChrome: false, + hostNavigation: false, + partialReading: true, + }); + expect( + readerMode({ + rows: [], + parents: undefined, + open: [], + complete: true, + place: "keep", + revision: 1, + }).partialReading, + ).toBe(false); +}); + +it("hides a presented row when a delayed live multi-target deletion also names an omitted snapshot reply or root reaction", () => { + const { root, replies, events } = thread(2); + const [a, b] = replies; + const rootReact = reaction(other, root, 25); + const { arrangement, receive, frame } = host({ rootId: root.id }); + const one = lane("one"); + expect( + arrangement.present(one, { ids: [a.id], events: [...events, rootReact] }), + ).toBe("shown"); + expect(ids(arrangement.snapshot()?.rows)).toEqual([a.id]); + receive([deletion(other, [a.id, b.id], 30)], live); + frame(); + expect(arrangement.snapshot()?.rows).toEqual([]); + expect(arrangement.present(one, { ids: [a.id], events: [root, a] })).toBe( + "shown", + ); + expect(arrangement.snapshot()?.rows).toEqual([]); + const mixed = host({ rootId: root.id }); + expect( + mixed.arrangement.present(lane("mixed"), { + ids: [a.id], + events: [root, a, rootReact], + }), + ).toBe("shown"); + mixed.receive([deletion(other, [a.id, rootReact.id], 31)], live); + mixed.frame(); + expect(mixed.arrangement.snapshot()?.rows).toEqual([]); +}); + +it("keeps a deleted row hidden when a displayed co-target is omitted on same-owner re-present", () => { + const { root, replies, events } = thread(2); + const [a, b] = replies; + const { arrangement, receive, frame } = host({ rootId: root.id }); + const one = lane("one"); + expect(arrangement.present(one, { ids: [a.id, b.id], events })).toBe("shown"); + receive([deletion(other, [a.id, b.id], 30)], live); + frame(); + expect(arrangement.snapshot()?.rows).toEqual([]); + expect(arrangement.present(one, { ids: [a.id], events: [root, a] })).toBe( + "shown", + ); + expect(arrangement.snapshot()?.rows).toEqual([]); +}); + +it("preserves omitted snapshot deletion evidence across same-owner re-presents with slimmer events", () => { + const { root, replies, events } = thread(2); + const [a, b] = replies; + const { arrangement, receive, frame } = host({ rootId: root.id }); + const one = lane("one"); + expect(arrangement.present(one, { ids: [a.id], events })).toBe("shown"); + expect( + arrangement.present(one, { + ids: [a.id], + events: [root, a], + place: "start", + }), + ).toBe("shown"); + receive([deletion(other, [a.id, b.id], 30)], live); + frame(); + expect(arrangement.snapshot()?.rows).toEqual([]); +}); + +it("reserves live headroom when admitting candidates and ends cleanly once held evidence passes limits", () => { + const full = thread(3); + const fullHost = host({ + rootId: full.root.id, + limits: { rows: 10, events: 4, bytes: 4 << 20 }, + }); + const fullLane = lane("full"); + expect( + fullHost.arrangement.present(fullLane, { + ids: [full.replies[0].id], + events: full.events, + }), + ).toBe("shown"); + fullHost.receive([reaction(other, full.replies[0], 30)], live); + expect(fullHost.arrangement.status(fullLane)).toBe("shown"); + + 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 one = lane("one"); + expect(arrangement.present(one, { ids: [a.id], events })).toBe("shown"); + receive([reaction(other, a, 30)], live); + expect(arrangement.status(one)).toBe("shown"); + receive([reaction(viewer, a, 31)], live); + expect(arrangement.status(one)).toBe("ended"); + expect(arrangement.snapshot()).toBeUndefined(); + expect(arrangement.present(one, { ids: [a.id], events })).toBe("shown"); + receive([reaction(other, a, 32)], live); + expect(arrangement.status(one)).toBe("shown"); + receive([deletion(other, [a.id, b.id], 33)], live); + expect(arrangement.status(one)).toBe("ended"); + expect(arrangement.snapshot()).toBeUndefined(); +}); + +it("keeps a re-ranked row and falls back to named placement, first mounted row, or undefined for focus recovery", () => { + const mounted = (ids: readonly string[]) => { + const set = new Set(ids); + return (id: string) => set.has(id); + }; + expect( + focusRecoveryTarget(["a", "b"], "b", ["b", "a"], mounted(["b", "a"])), + ).toBe("b"); + expect( + focusRecoveryTarget( + ["h0", "h1"], + "h1", + ["p0", "p1"], + mounted(["p0", "p1"]), + "p1", + ), + ).toBe("p1"); + expect( + focusRecoveryTarget( + ["h0", "h1"], + "h1", + ["p0", "p1"], + mounted(["p0", "p1"]), + ), + ).toBe("p0"); + expect(focusRecoveryTarget(["a"], "a", [], mounted([]))).toBeUndefined(); +}); diff --git a/src/features/messages/arrangement.ts b/src/features/messages/arrangement.ts new file mode 100644 index 0000000000..a18cde880c --- /dev/null +++ b/src/features/messages/arrangement.ts @@ -0,0 +1,842 @@ +import { + useEffect, + useEffectEvent, + useLayoutEffect, + useMemo, + useRef, + useSyncExternalStore, + type RefObject, +} from "react"; +import type { + ConversationPresentation, + PresentationLimits, +} 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 { channelRowKind } from "../relay/membership"; +import { shareMessageRows } from "../relay/row-identity"; +import type { RelaySession } from "../relay/session"; +import { threadReference } from "../relay/thread-reference"; +import { AUX, growAux, inChannel } from "../relay/threads"; + +/** 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. */ + 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; +}>; +/** Pure evidence state for one presentation. `root` and visibility + * `dependencies` stay outside `tracked` so live auxiliaries on the header or + * unpresented targets never grow the presentation's budget. */ +export type EvidenceState = Readonly<{ + ids: readonly string[]; + tracked: ReadonlyMap; + dependencies: ReadonlyMap; + candidates: ReadonlyMap; + root: EventData | undefined; + live: ReadonlyMap; +}>; +type Scope = Readonly<{ + channelId: string; + rootId?: string | undefined; + limits: PresentationLimits; +}>; +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; + +/** Canonical event set passed to `foldRows`. */ +export function allEvidence(state: EvidenceState) { + const all = new Map(state.tracked); + for (const [id, event] of state.dependencies) + if (!all.has(id)) all.set(id, event); + if (state.root && !all.has(state.root.id)) all.set(state.root.id, state.root); + return all; +} + +/** Event set held in `session.retain()`: active evidence plus bounded + * non-presented candidates so live multi-target auxiliaries pass session + * visibility without depending on an external plugin hold. */ +export function heldEvidence(state: EvidenceState) { + const held = allEvidence(state); + for (const [id, event] of state.candidates) + if (!held.has(id)) held.set(id, event); + return held; +} + +function collectDependencies( + tracked: ReadonlyMap, + pool: ReadonlyMap, + rootId: string | undefined, + initial?: ReadonlyMap, +) { + const dependencies = new Map(initial); + let frontier = [...tracked.values()].filter((event) => AUX.has(event.kind)); + for (let hop = 0; hop < 2 && frontier.length; hop++) { + const next: EventData[] = []; + for (const event of frontier) + for (const [name, targetId] of event.tags) { + if ( + name !== "e" || + !targetId || + targetId === rootId || + tracked.has(targetId) || + dependencies.has(targetId) + ) + continue; + const target = pool.get(targetId); + if (!target) continue; + dependencies.set(targetId, target); + if (AUX.has(target.kind)) next.push(target); + } + frontier = next; + } + return dependencies; +} + +function inReaderScope( + event: EventData, + channelId: string, + rootId: string | undefined, +) { + if ( + !channelRowKind(event.kind) || + event.id === rootId || + !inChannel(event, channelId) + ) + return false; + const ref = threadReference(event); + return rootId !== undefined + ? ref?.rootId === rootId + : !ref || + event.tags.some( + ([name, value]) => name === "broadcast" && value === "1", + ); +} + +function candidateLimits(limits: PresentationLimits) { + const reserveEvents = Number.isFinite(limits.events) + ? Math.min(200, Math.floor(limits.events / 4)) + : 0; + const reserveBytes = Math.min(256 * 1024, Math.floor(limits.bytes / 8)); + return { + rows: limits.rows, + events: Math.max(0, limits.events - reserveEvents), + bytes: Math.max(0, limits.bytes - reserveBytes), + }; +} + +function boundCandidates( + sources: Iterable, + exclude: (id: string) => boolean, + base: ReadonlyMap, + limits: PresentationLimits, +) { + const candidates = new Map(); + const baseCount = base.size; + if (baseCount >= limits.events) return candidates; + let bytes = listByteSize([...base.values()]); + if (bytes >= limits.bytes) return candidates; + for (const event of sources) { + if (baseCount + candidates.size >= limits.events) break; + if (exclude(event.id) || candidates.has(event.id)) continue; + const size = listByteSize([event]) - 2; + const totalCount = baseCount + candidates.size + 1; + const nextBytes = bytes + (totalCount > 1 ? 1 : 0) + size; + if (nextBytes > limits.bytes) continue; + candidates.set(event.id, event); + bytes = nextBytes; + if (bytes >= limits.bytes) break; + } + return candidates; +} + +/** Validate a presentation and build its pure evidence closure. */ +export function selectEvidence( + presentation: ConversationPresentation, + priorLive: ReadonlyMap, + { channelId, rootId, limits }: Scope, + priorHeld?: ReadonlyMap, +) { + if (!isObject(presentation)) return "invalid" as const; + const { ids, events, parents, open, complete, place } = presentation; + 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" as const; + if (ids.length > limits.rows) return "limit" as const; + const wanted = new Set(ids); + const pool = new Map(); + for (const event of [...events, ...priorLive.values()]) + if (AUX.has(event.kind) || inChannel(event, channelId)) + pool.set(event.id, event); + const tracked = new Map(); + for (const event of pool.values()) + if ( + wanted.has(event.id) && + event.id !== rootId && + !AUX.has(event.kind) && + event.kind !== 39007 + ) + tracked.set(event.id, event); + growAux([...pool.values()], tracked); + const hasTrackedAux = [...tracked.values()].some((event) => + AUX.has(event.kind), + ); + const dependencies = hasTrackedAux + ? collectDependencies( + tracked, + priorHeld?.size ? new Map([...priorHeld, ...pool]) : pool, + rootId, + ) + : new Map(); + const root = rootId ? pool.get(rootId) : undefined; + const base: EvidenceState = { + ids: [...ids], + tracked, + dependencies, + candidates: new Map(), + root, + live: new Map([...priorLive].filter(([id]) => tracked.has(id))), + }; + const all = allEvidence(base); + if (exceeds(all, limits)) return "limit" as const; + const poolRows: EventData[] = []; + const poolAux: EventData[] = []; + for (const event of pool.values()) + (AUX.has(event.kind) ? poolAux : poolRows).push(event); + const priorRows: EventData[] = []; + const priorAux: EventData[] = []; + if (priorHeld?.size) + for (const event of priorHeld.values()) + (AUX.has(event.kind) ? priorAux : priorRows).push(event); + const candidates = boundCandidates( + priorHeld?.size + ? [...poolRows, ...priorRows, ...poolAux, ...priorAux] + : [...poolRows, ...poolAux], + (id) => id === rootId || all.has(id), + all, + candidateLimits(limits), + ); + const evidence: EvidenceState = { ...base, candidates }; + return { + evidence, + all, + held: heldEvidence(evidence), + parents: parents + ? new Map( + Object.entries(parents).filter( + ([, parent]) => typeof parent === "string", + ), + ) + : undefined, + open: [...(open ?? [])], + complete: complete === true, + place: place ?? "keep", + }; +} + +/** Admit live events into an active presentation: verified echoes of named + * pending rows, two-hop auxiliaries of tracked rows only (never `root`), their + * multi-target dependencies, and completeness downgrade on new unpresented rows. */ +export function applyLiveEvents( + state: EvidenceState, + complete: boolean, + batch: readonly RelayEvent[], + replay: boolean, + { channelId, rootId, limits }: Scope, +) { + const wanted = new Set(state.ids); + const tracked = new Map(state.tracked); + const live = new Map(state.live); + let nextComplete = complete; + let trackedChanged = false; + for (const event of batch) { + if ( + wanted.has(event.id) && + event.id !== rootId && + !tracked.has(event.id) && + !AUX.has(event.kind) && + event.kind !== 39007 && + inChannel(event, channelId) + ) { + tracked.set(event.id, event); + live.set(event.id, event); + trackedChanged = true; + } else if ( + nextComplete && + !replay && + !wanted.has(event.id) && + inReaderScope(event, channelId, rootId) + ) + nextComplete = false; + } + const addedAux = growAux(batch, tracked); + for (const event of addedAux) live.set(event.id, event); + const dependencies = addedAux.length + ? collectDependencies( + tracked, + new Map([ + ...state.candidates, + ...batch.map((event) => [event.id, event] as const), + ]), + rootId, + state.dependencies, + ) + : state.dependencies; + const refold = + trackedChanged || + addedAux.length > 0 || + dependencies.size !== state.dependencies.size; + if (!refold && nextComplete === complete) return { kind: "noop" as const }; + const base: EvidenceState = { ...state, tracked, dependencies, live }; + const all = allEvidence(base); + if (!refold) + return { + kind: "updated" as const, + evidence: base, + all, + held: heldEvidence(base), + complete: nextComplete, + refold: false, + }; + const candidates = new Map(); + for (const [id, event] of state.candidates) + if (id !== rootId && !all.has(id)) candidates.set(id, event); + const evidence: EvidenceState = { ...base, candidates }; + const held = heldEvidence(evidence); + if (exceeds(held, limits)) return { kind: "exceeded" as const }; + return { + kind: "updated" as const, + evidence, + all, + held, + complete: nextComplete, + refold: true, + }; +} + +/** Derived host-behavior switches for a reader while a presentation shows. */ +export function readerMode(display: Display | undefined) { + const presented = display !== undefined; + return { + presented, + chronologicalChrome: !presented, + hostNavigation: !presented, + partialReading: presented && !display.complete, + } as const; +} + +type Hold = ReturnType; +type ActivePresentation = { + readonly hold: Hold; + evidence: EvidenceState; + rows: readonly ChannelMessage[]; +}; + +export type Arrangement = ReturnType; +export function createArrangement({ + session, + channelId, + rootId, + limits, +}: Readonly<{ + session: RelaySession; + channelId: string; + rootId?: string | undefined; + limits: PresentationLimits; +}>) { + const scope: Scope = { channelId, rootId, limits }; + let phase: "live" | "leaving" | "retired" = "live"; + const lanes = new Map(); + let shown: ArrangementLane | undefined; + let active: ActivePresentation | 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(); + }; + function fold( + current: ActivePresentation, + all = allEvidence(current.evidence), + ) { + const folded = new Map( + session + .foldRows(channelId, [...all.values()], rootId) + .map((row) => [row.id, row]), + ); + const rows = current.evidence.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?.(); + }; + } + function release() { + active?.hold.dispose(); + active = undefined; + shown = undefined; + display = undefined; + stopWatching?.(); + stopWatching = undefined; + cancelFrame?.(); + cancelFrame = undefined; + } + function show(lane: ArrangementLane, presentation: ConversationPresentation) { + const picked = selectEvidence( + presentation, + active?.evidence.live ?? new Map(), + scope, + active ? heldEvidence(active.evidence) : undefined, + ); + if (typeof picked === "string") return picked; + let hold = active?.hold; + try { + hold ??= session.retain(); + hold.set([...picked.held.values()]); + } catch { + if (!active) hold?.dispose(); + return "limit"; + } + const next: ActivePresentation = { + hold, + evidence: picked.evidence, + rows: active?.rows ?? [], + }; + next.rows = fold(next, picked.all); + active = next; + cancelFrame?.(); + cancelFrame = undefined; + shown = lane; + revision += 1; + display = Object.freeze({ + rows: next.rows, + parents: picked.parents, + open: picked.open, + complete: picked.complete, + place: picked.place, + revision, + }); + watch(); + return picked; + } + function free(ended?: ArrangementLane) { + for (const [lane, state] of lanes) if (state === "held") lanes.delete(lane); + if (ended) lanes.set(ended, "ended"); + release(); + emit(); + } + const end = () => free(shown); + function onLive({ events, replay }: LiveBatch) { + const current = active; + if (!current || !display) return; + const result = applyLiveEvents( + current.evidence, + display.complete, + events, + replay === true, + scope, + ); + if (result.kind === "noop") return; + if (result.kind === "exceeded") return end(); + if (result.refold) { + try { + current.hold.set([...result.held.values()]); + } catch { + return end(); + } + } + current.evidence = result.evidence; + if (result.complete !== display.complete) { + display = Object.freeze({ ...display, complete: result.complete }); + emit(); + } + if (result.refold) refold(); + } + function refold() { + const current = active; + if (!current || cancelFrame) return; + const id = requestAnimationFrame(() => { + cancelFrame = undefined; + const rows = fold(current); + if (current !== active || !display || rows === current.rows) return; + current.rows = rows; + display = Object.freeze({ ...display, rows }); + emit(); + }); + cancelFrame = () => cancelAnimationFrame(id); + } + return { + limits, + present( + lane: ArrangementLane, + presentation: ConversationPresentation | null, + ) { + if (phase === "retired") return "retired"; + if (presentation === null) { + const had = lanes.delete(lane); + if (shown === lane) free(); + else if (had) emit(); + return "shown"; + } + const held = shown !== undefined && shown !== lane; + const picked = held + ? selectEvidence( + presentation, + active?.evidence.live ?? new Map(), + scope, + ) + : show(lane, presentation); + if (typeof picked === "string") return picked; + if (held) lanes.set(lane, "held"); + else lanes.delete(lane); + emit(); + return held ? "held" : "shown"; + }, + withdraw() { + if (shown) free(); + }, + status: (lane: ArrangementLane) => + shown === lane ? "shown" : (lanes.get(lane) ?? "none"), + snapshot: () => display, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + attach() { + if (phase === "leaving") phase = "live"; + }, + 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; + }, + take(shown: (id: string) => boolean, fallback: "start" | "end" = "start") { + 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; + }, + 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" }, + ); + }; + capture(undefined); + return arrangement.subscribe(() => capture(read())); + }, [arrangement, place]); + return place; +} + +export function focusRecoveryTarget( + previousOrder: readonly string[], + removedId: string, + nextOrder: readonly string[], + mounted: (id: string) => boolean, + preferredId?: string, +) { + const neighbor = nearestShown( + { id: removedId, top: 0, order: previousOrder }, + mounted, + ); + if (neighbor !== undefined) return neighbor; + if (preferredId !== undefined && mounted(preferredId)) return preferredId; + return nextOrder.find(mounted); +} + +function focusMessageRow(row: HTMLElement) { + const target = + row.querySelector(":scope > [data-layout]") ?? row; + if (!target.hasAttribute("tabindex")) target.tabIndex = -1; + target.focus({ preventScroll: true }); +} + +export function usePresentedFocusRecovery( + scroller: RefObject, + enabled: boolean, + display: Display | undefined, + rows: readonly { id: string; membership?: unknown }[], + pendingRevealId?: string, +) { + const focused = useRef<{ id: string; node: HTMLElement } | undefined>( + undefined, + ); + const previous = useRef<{ + presented: boolean; + order: readonly string[]; + }>({ presented: false, order: [] }); + useLayoutEffect(() => { + const element = scroller.current; + if (!enabled || !element) { + focused.current = undefined; + return; + } + const readRow = (node: EventTarget | null) => { + if (!(node instanceof HTMLElement)) return undefined; + const message = node.closest("[data-message-id]"); + if (message?.dataset.messageId) + return { id: message.dataset.messageId, node: message }; + const activity = node.closest("[data-activity-group-id]"); + if (activity?.dataset.activityGroupId) + return { id: activity.dataset.activityGroupId, node: activity }; + const branch = node.closest("[data-depth]"); + const branchMessage = + branch?.firstElementChild?.querySelector( + "[data-message-id]", + ); + if (branchMessage?.dataset.messageId) + return { id: branchMessage.dataset.messageId, node: branchMessage }; + return undefined; + }; + const current = element.ownerDocument.activeElement; + if (current && element.contains(current)) + focused.current = readRow(current); + const onFocusIn = (event: FocusEvent) => { + focused.current = readRow(event.target); + }; + const onFocusOut = (event: FocusEvent) => { + const next = + event.relatedTarget instanceof Node ? event.relatedTarget : null; + if (next) { + if (!element.contains(next)) focused.current = undefined; + return; + } + const captured = focused.current; + if (!captured) return; + queueMicrotask(() => { + if (focused.current === captured) focused.current = undefined; + }); + }; + element.addEventListener("focusin", onFocusIn); + element.addEventListener("focusout", onFocusOut); + return () => { + element.removeEventListener("focusin", onFocusIn); + element.removeEventListener("focusout", onFocusOut); + }; + }, [scroller, enabled]); + useLayoutEffect(() => { + const presented = display !== undefined; + const nextOrder = rows.map((row) => row.id); + const prior = previous.current; + previous.current = { presented, order: nextOrder }; + if (!enabled || (!prior.presented && !presented)) return; + const element = scroller.current; + const lost = focused.current; + if (!element || !lost || element.closest("[inert]")) return; + const doc = element.ownerDocument; + const active = doc.activeElement; + const dropped = + !active || + active === doc.body || + active === doc.documentElement || + !active.isConnected; + if (!dropped) { + if (!element.contains(active)) focused.current = undefined; + return; + } + if (lost.node.isConnected && !lost.node.closest("[inert], [hidden]")) { + focused.current = undefined; + return; + } + if (pendingRevealId !== undefined && lost.id === pendingRevealId) { + focused.current = undefined; + return; + } + const selectableOrder = rows.flatMap((row) => + row.membership ? [] : [row.id], + ); + const selectableIds = new Set(selectableOrder); + const mounted = new Map(); + for (const node of element.querySelectorAll( + "[data-message-id]", + )) { + const id = node.dataset.messageId; + if (id && selectableIds.has(id) && !node.closest("[inert], [hidden]")) + mounted.set(id, node); + } + const preferred = + typeof display?.place === "object" ? display.place.id : undefined; + const nextId = focusRecoveryTarget( + prior.order, + lost.id, + selectableOrder, + (id) => mounted.has(id), + preferred, + ); + const nextRow = nextId !== undefined ? mounted.get(nextId) : undefined; + if (nextId !== undefined && nextRow) { + focusMessageRow(nextRow); + focused.current = { id: nextId, node: nextRow }; + } else { + focused.current = undefined; + element.focus({ preventScroll: true }); + } + }, [scroller, enabled, display, rows, pendingRevealId]); +} diff --git a/src/features/messages/arranger-plugin.test.tsx b/src/features/messages/arranger-plugin.test.tsx new file mode 100644 index 0000000000..9c0a929f64 --- /dev/null +++ b/src/features/messages/arranger-plugin.test.tsx @@ -0,0 +1,1273 @@ +// @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, + DELETION, + EDIT, + mint, + openSession, + prove, + REACTION, + T, + type Bound, + type World, +} 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 ReadFilter, + 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"; + +let thread: Fixture & { root: RelayEvent }; +let channel: Fixture; +beforeAll(async () => { + thread = await threadFixture(); + channel = await channelFixture(); +}, 60_000); + +const cleanups: (() => Promise | unknown)[] = []; +afterEach(async () => { + vi.useRealTimers(); + 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] : [])); +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 || event.kind === 9005) + 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; + 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); + } + const matching = (order: readonly EventData[], needle: string) => + order.filter((row) => + (edits.get(row.id) ?? row).content + .toLowerCase() + .includes(needle.toLowerCase()), + ); + 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; +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; + rootId?: string | undefined; + probe?: boolean; + windowRows?: number; + namedOnly?: boolean; + hold?: Parameters[0]["hold"]; + bounds?: Parameters[0]["bounds"]; +}; +async function mount({ + fixture, + rootId, + probe, + windowRows, + namedOnly, + hold, + bounds, +}: Mount) { + const world = createWorld(fixture.events); + const relay = openSession({ + world, + ...(windowRows === undefined ? {} : { windowRows }), + ...(namedOnly === undefined ? {} : { namedOnly }), + ...(hold === undefined ? {} : { hold }), + ...(bounds === undefined ? {} : { bounds }), + }); + 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, + shown: () => idsOf(arrangement.snapshot()?.rows ?? []), + heard: (...events: RelayEvent[]) => act(() => relay.hear(...events)), + flush: () => + act(() => { + for (const [id, run] of [...frames]) { + frames.delete(id); + run(); + } + }), + 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, + scanReads: (since: number) => relay.reads.slice(since), + holds: () => holds, + }; +} +type Harness = Awaited>; + +const ready = (h: Harness) => + waitFor( + () => { + expect(h.status()).not.toMatch(/Reading/); + expect(h.arrangement.snapshot()).toBeDefined(); + }, + { timeout: 30_000 }, + ); +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"), + ); + 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); + expect(reads).toHaveLength(13); + expect(reads.every(({ priority }) => priority === "background")).toBe(true); + const windows = reads + .flatMap(({ filters }) => filters) + .filter((filter) => filter.thread_window); + expect(windows).toHaveLength(11); + const pages = h.answers.filter((page) => page.some((e) => e.kind === 39007)); + expect(pages).toHaveLength(11); + 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.arrangement.snapshot()?.place).toBe("start"); + expect(h.arrangement.snapshot()?.complete).toBe(false); + expect(h.status()).toBe(replies(1, 200, want.rows.length + 1)); + + expect(hostState(view)).toEqual(host); + expect(h.recent()).toEqual(recent); + expect(h.unread()).toEqual(unread); + 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, authors, reactors } = 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 [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], + }; + let paused!: () => void; + let release: (() => void) | undefined; + const held = new Promise((resolve) => { + paused = resolve; + }); + const h = await mount({ + fixture: heavy, + rootId: root.id, + windowRows: 600, + 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] + .filter(([id]) => id !== best.id && id !== next.id) + .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); + const windows = filters.filter((filter) => filter.thread_window); + expect(windows.map((filter) => filter.include_aux)).toEqual([ + true, + ...windows.slice(1).map(() => false), + ]); + expect(windows[0]).toEqual({ ...windows[1], include_aux: true }); + const pages = h.answers.filter((answer) => + answer.some((e) => e.kind === 39007), + ); + 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 + .flat() + .filter((e) => e.kind === 9 && e.id !== root.id) + .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()).not.toContain(next.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); + 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)); + } + 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); + expect(screen.queryByRole("button", { name: "More" })).toBeNull(); +}); + +it("stops calling a whole thread complete once its connection drops", async () => { + const small = await threadFixture(100); + const h = await mount({ fixture: small, rootId: small.root.id }); + act(() => h.connection("connected")); + h.click("Top"); + await ready(h); + expect(h.arrangement.snapshot()?.complete).toBe(true); + const shown = h.shown(); + act(() => h.connection("retrying")); + await waitFor(() => expect(h.arrangement.snapshot()?.complete).toBe(false)); + expect(h.shown()).toEqual(shown); +}); + +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))); + expect(h.reads).toHaveLength(reads); + 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); + expect(h.arrangement.limits).toEqual(THREAD_LIMITS); +}); + +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"); + } + 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 }); + + h.click("Oldest"); + await ready(h); + expect(h.status()).toBe(replies(1, 200, want.rows.length)); + const gizmo = want.matching(want.oldest, "gizmo"); + expect(gizmo.length).toBeGreaterThan(50); + expect(gizmo.length).toBeLessThan(200); + 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)); + + h.click("Top"); + await statusIs(h, replies(1, gizmo.length, gizmo.length)); + expect(h.shown()).toEqual(idsOf(want.matching(want.top, "gizmo"))); + + 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))); + + 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 from the scanned replies", 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 statusIs(h, replies(1, 460, total)); + const afterScan = h.reads.length; + for (const from of [461, 921, 1381]) { + h.click("Next"); + await statusIs(h, replies(from, from + 459, total)); + 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(h.reads).toHaveLength(afterScan); + expect(screen.queryByRole("button", { name: "Next" })).toBeNull(); +}); + +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(); + 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 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 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); + h.flush(); + 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))); +}); + +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")); + 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); + h.heard(h.publications[0]?.event as RelayEvent); + await waitFor(() => expect(own()).toBeUndefined()); + expect(h.shown()).toHaveLength(200); +}); + +it("sorts a 2,000-reply thread Oldest first from older thread windows and grows the window on More", 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); + expect(reads).toHaveLength(12); + const [firstPage] = reads[1]?.filters ?? []; + expect(firstPage).toMatchObject({ thread_window: true, limit: 200 }); + expect(firstPage?.until).toBeUndefined(); + const [secondPage] = reads[2]?.filters ?? []; + expect(secondPage?.until).toBeDefined(); + expect(secondPage?.before_id).toBeDefined(); + 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); + + const afterScan = h.reads.length; + h.click("More"); + await waitFor(() => expect(h.shown()).toHaveLength(460)); + expect(h.shown()).toEqual(idsOf(want.oldest.slice(0, 460))); + expect(h.reads).toHaveLength(afterScan); +}); + +it("keeps the reader's place when the filter changes, and starts a new sort at the top", async () => { + const { events, root } = thread; + const want = oracle(events, root.id); + const h = await mount({ fixture: thread, rootId: root.id }); + h.click("Top"); + await ready(h); + expect(h.arrangement.snapshot()?.place).toBe("start"); + const gizmo = want.matching(want.top, "gizmo"); + find("gizmo"); + await statusIs(h, replies(1, gizmo.length, gizmo.length)); + expect(h.arrangement.snapshot()?.place).toBe("keep"); + find(""); + await statusIs(h, replies(1, 200, want.rows.length)); + expect(h.arrangement.snapshot()?.place).toBe("keep"); + h.click("Oldest"); + await waitFor( + () => expect(h.shown()).toEqual(idsOf(want.oldest.slice(0, 200))), + { timeout: 30_000 }, + ); + expect(h.arrangement.snapshot()?.place).toBe("start"); +}); + +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, + ]), + ); + 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("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); + 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, + }); + 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(); + 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); + 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)}+`); + 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; + vi.spyOn(Math, "random").mockReturnValue(0); + const visibility = vi + .spyOn(document, "visibilityState", "get") + .mockReturnValue("hidden"); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + act(() => h.connection("connected")); + await act(() => vi.advanceTimersByTimeAsync(10_000)); + vi.useRealTimers(); + 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); +}); + +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); + 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; + 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)); +}); + +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(() => + 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("sorts a 5,000-row channel Oldest first from verified older windows", 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(26); + expect(reads.every(({ priority }) => priority === "background")).toBe(true); + expect(reads[0]?.filters).toMatchObject([{ top_level: true, limit: 200 }]); + expect(reads[0]?.filters[0]?.until).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); + 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); + 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); + 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))); +}); + +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))); +}); + +const spent = { has_more: false, next_cursor: null }; +it.each<[string, boolean, (made: Bound, filter: ReadFilter) => Bound[]]>([ + [ + "another page's bound", + false, + (made, filter) => + filter.until === undefined + ? [made] + : [ + { + tags: [ + ["h", CHANNEL], + ["d", `${CHANNEL}:head`], + ], + body: spent, + }, + ], + ], + [ + "a second bound for one page", + false, + (made) => [{ ...made, body: spent }, made], + ], + [ + "a surplus bound for a cursor nobody asked for", + false, + (made) => [ + made, + { + ...made, + tags: [ + ["h", CHANNEL], + ["d", `${CHANNEL}:1:${"a".repeat(64)}`], + ], + }, + ], + ], + [ + "a bound with an extra tag", + false, + (made) => [{ ...made, tags: [...made.tags, ["e", "a".repeat(64)]] }], + ], + [ + "has_more that contradicts its cursor", + false, + (made) => [{ ...made, body: { ...made.body, has_more: false } }], + ], + [ + "a cursor that does not advance", + false, + (made, filter) => + filter.until === undefined + ? [made] + : [ + { + ...made, + body: { + ...made.body, + next_cursor: { created_at: filter.until, id: filter.before_id }, + }, + }, + ], + ], + [ + "a thread bound for another request", + true, + (made) => [ + { + ...made, + tags: [ + ["d", `tw:1:${"0".repeat(64)}`], + ...made.tags.filter(([name]) => name !== "d"), + ], + }, + ], + ], +])( + "fails the scan on %s, and leaves the host's rows", + async (_, inThread, bounds) => { + const h = await mount( + inThread + ? { fixture: thread, rootId: thread.root.id, bounds } + : { fixture: channel, bounds }, + ); + h.click("Top"); + const reason = inThread + ? "Thread window bounds are invalid" + : "The relay sent invalid window bounds"; + await waitFor(() => expect(h.status()).toBe(`Scan failed: ${reason}`), { + timeout: 30_000, + }); + expect(h.arrangement.snapshot()).toBeUndefined(); + }, +); diff --git a/src/features/messages/reply-tree.test.ts b/src/features/messages/reply-tree.test.ts index c4ccf705cb..9d0866ff52 100644 --- a/src/features/messages/reply-tree.test.ts +++ b/src/features/messages/reply-tree.test.ts @@ -129,3 +129,47 @@ 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", + d: "d", + e: "root", + f: "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([]); + 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..4148a66567 100644 --- a/src/features/messages/use-reading.test.ts +++ b/src/features/messages/use-reading.test.ts @@ -28,10 +28,17 @@ function setup({ strict = false, latestMessageId = undefined as string | undefined, catchUpMessageId = 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 +61,9 @@ 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(); + 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 +76,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 +110,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 +139,8 @@ function setup({ settled: position, latestMessageId, catchUpMessageId, + partial, + controls, rootId, enabled, }, @@ -150,6 +163,7 @@ function setup({ composer, parent, outside, + bar, session, reading, leases, @@ -203,6 +217,8 @@ function setup({ settled: position, latestMessageId, catchUpMessageId, + partial, + controls, rootId, enabled, }), @@ -214,6 +230,21 @@ function setup({ settled: position, latestMessageId: id, catchUpMessageId, + partial, + controls, + rootId, + enabled, + }), + setPartial: (next: boolean) => + view.rerender({ + session, + channelId: "room", + scroller, + settled: position, + latestMessageId, + catchUpMessageId, + partial: next, + controls, rootId, enabled, }), @@ -232,7 +263,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 +648,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 +666,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 +714,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 +795,54 @@ it("a historical viewport or a bottom reached only at dwell end cannot catch up" ); }); +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); + 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("a list that turns partial keeps its visit and replaces only its leases", async () => { + const h = setup({ latestMessageId: "visible", rootId: "thread" }); + const visit = h.reading.mock.calls[0]?.[2]; + expect(visit).toBeDefined(); + h.setPartial(true); + h.setPartial(false); + await vi.advanceTimersByTimeAsync(300); + expect(h.session.unread.leave).not.toHaveBeenCalled(); + expect(h.reading.mock.calls.map((call) => call[3])).toContain(true); + for (const call of h.reading.mock.calls) expect(call[2]).toBe(visit); + expect(h.dwelled()?.observe).toHaveBeenCalledWith(["visible"]); +}); +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..cc1c4c1f1e 100644 --- a/src/features/messages/use-reading.ts +++ b/src/features/messages/use-reading.ts @@ -1,4 +1,4 @@ -import { useEffect, useEffectEvent, type RefObject } from "react"; +import { useEffect, useEffectEvent, useRef, type RefObject } from "react"; import type { RelaySession } from "../relay/session"; import type { ReadingHandle } from "../relay/unread"; import { useMessageEditScope } from "./MessageEditScope"; @@ -36,6 +36,12 @@ 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; + /** 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 +69,8 @@ export function useReading({ channelId, latestMessageId, catchUpMessageId, + partial = false, + controls, rootId, scroller, settled, @@ -74,6 +82,8 @@ 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 isPartial = useEffectEvent(() => partial); + const onPartial = useRef<((next: boolean) => void) | undefined>(undefined); useEffect(() => { if (!enabled || !scroller.current) return; const element: HTMLElement = scroller.current; @@ -88,6 +98,7 @@ export function useReading({ // or the reader departs. Returning is a new visit. let visit = {}; let visited = false; + let leased = isPartial(); // Whether the visit's last completed measurement showed any row. let showing = false; function depart() { @@ -141,7 +152,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 && @@ -270,7 +282,7 @@ export function useReading({ } function acquire() { try { - const lease = session.unread.reading(channelId, rootId, visit); + const lease = session.unread.reading(channelId, rootId, visit, leased); visited = true; return lease; } catch { @@ -332,7 +344,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, leased); handle.view([...visible], viewing); showing = !!visible.size; } catch { @@ -412,6 +424,12 @@ export function useReading({ }); const resize = new ResizeObserver(reflow); resize.observe(element); + onPartial.current = (next) => { + if (next === leased) return; + leased = next; + stop(); + schedule(); + }; present(); schedule(); return () => { @@ -440,6 +458,8 @@ export function useReading({ settled, restoring, composer, + controls, enabled, ]); + useEffect(() => onPartial.current?.(partial), [partial]); } diff --git a/src/features/relay/session-hold.test.ts b/src/features/relay/session-hold.test.ts new file mode 100644 index 0000000000..f596088d2d --- /dev/null +++ b/src/features/relay/session-hold.test.ts @@ -0,0 +1,358 @@ +import { afterEach, expect, it } 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(); +}); +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]); + 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]); + 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 }[] = []; + 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, + 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([]), + }); + onStart(); + }); + }, + }); + 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 startedReads(1); + const next = read(filter(30002), { priority: "background" }); + const foreground = read(filter(30003), {}); + await startedReads(2); + expect(started.map(({ kind, priority }) => [kind, priority])).toEqual([ + [30001, "background"], + [30003, "foreground"], + ]); + started[0]?.release(); + await scan; + await startedReads(3); + expect(started[2]?.kind).toBe(30002); + for (const item of started) item.release(); + await Promise.all([next, foreground]); +}); + +it("deletes a held-only sent-to-channel copy when deleting its original reply", async () => { + const published: RelayEvent[] = []; + const { session } = setup(async (event) => { + published.push(event); + }); + await session.outbox?.ready(); + const root = proven(message(other, "c", "root", 10)); + const original = proven(reply(viewer, root, 11, "mine")); + const copy = proven( + message(viewer, "c", "mine", 12, [["buzz:copy-of", original.id]]), + ); + const hold = session.retain(); + hold.set([root, original, copy]); + session.messages.remove([original.id]); + await flush(); + await flush(); + const deletedTargets = published + .filter((event) => event.kind === 5) + .flatMap((event) => + event.tags.flatMap(([name, id]) => (name === "e" && id ? [id] : [])), + ); + expect(deletedTargets).toContain(original.id); + expect(deletedTargets).toContain(copy.id); + hold.dispose(); +}); diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index d1032557ed..16c50f7f12 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -90,6 +90,7 @@ import { objectBody } from "./body"; import { agentAudience, detailsBrief, messageAudience } 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,8 @@ 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; +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 +357,7 @@ export function createRelaySession( const pendingConfirmation = new Set(); const refreshers = new Set<() => Promise>(); const views = new Map<() => void, (clear?: boolean) => void>(); + 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 +463,17 @@ 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 heldEvents() { + return [...holds].flatMap((held) => [...held.values()]); + } 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 +1436,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, @@ -3149,6 +3165,7 @@ export function createRelaySession( ...recent.entries().map(([, item]) => item.event), ...retainedThreadEvents(), ...retainedChannelEvents(), + ...heldEvents(), ] .filter((event) => event.tags.some( @@ -3510,6 +3527,97 @@ export function createRelaySession( }; }, }, + foldRows( + channelId: string, + events: readonly EventData[], + rootId?: string, + ): readonly ChannelMessage[] { + if (closed || !canAccess(channelId)) return []; + 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, + 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; + }); + }, + 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 e1ce0ef8f9..cd9e6ddb5d 100644 --- a/src/features/relay/store.ts +++ b/src/features/relay/store.ts @@ -261,6 +261,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; @@ -395,8 +402,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, diff --git a/src/features/relay/threads.ts b/src/features/relay/threads.ts index 322f968cb4..fdf0f30340 100644 --- a/src/features/relay/threads.ts +++ b/src/features/relay/threads.ts @@ -21,16 +21,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); @@ -314,19 +347,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[])[]) { diff --git a/src/features/relay/unread.test.ts b/src/features/relay/unread.test.ts index 0b261725ce..21fc165eda 100644 --- a/src/features/relay/unread.test.ts +++ b/src/features/relay/unread.test.ts @@ -7204,6 +7204,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. @@ -9024,3 +9040,101 @@ 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/); + 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); + expect(h.session.unread.attention("room", held.id).forced).toBe(true); + expect( + h.session.unread.snapshot({ + kind: "message", + channelId: "room", + messageId: held.id, + }).manual, + ).toBe("local-only"); + await h.session.unread.markMessageRead("room", held.id); + expect(h.session.unread.attention("room", held.id).forced).toBe(false); + expect( + h.session.unread.snapshot({ + kind: "message", + channelId: "room", + messageId: held.id, + }).manual, + ).toBe("none"); + 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)(); + 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}`); + expect(h.snapshot().observedCount).toBe(counted); + expect( + h.session.observe([{ kinds: [9], "#h": ["room"], limit: 10 }]).snapshot() + .events, + ).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), + ); +}); + +it("complete DM reading advances the DM frontier through a held-only witness newer than counted rows", async () => { + const h = setup(); + h.grant("dm"); + h.emit([metadata(h.relay, "dm", "DM", 11, [["t", "dm"]])]); + const counted = message(h.alice, "dm", "older", 20); + h.emit([counted]); + await h.session.unread.ensure(); + const heldNewer = eventDto(message(h.alice, "dm", "newer-held", 50)); + const hold = h.session.retain(); + hold.set([heldNewer]); + const handle = h.session.unread.reading("dm"); + await handle.observe([heldNewer.id]); + expect(h.journal()?.state.frontiers.dm).toBe(50); + handle.dispose(); + hold.dispose(); +}); diff --git a/src/features/relay/unread.ts b/src/features/relay/unread.ts index 5d530754e3..26889c471c 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. */ @@ -424,6 +432,7 @@ export function createUnread({ signingAuthority, workflowAuthority, profiles, + evidence, notify = (listener) => listener(), follows = memoryThreadFollows(), }: { @@ -435,6 +444,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; }) { @@ -451,6 +463,7 @@ export function createUnread({ let refresh: Promise | undefined; const lifetime = new AbortController(); const events = new Map(); + 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, @@ -655,7 +668,8 @@ 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); - function root(event: RelayEvent): string | undefined { + 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(); @@ -664,7 +678,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; } @@ -1233,8 +1247,28 @@ export function createUnread({ if (closed || !allowed(channelId)) return unknown; indexEvidence(); const event = events.get(messageId); - if (!event || channelOf(event) !== channelId || !contentKind(event)) - return unknown; + if (!event || channelOf(event) !== channelId || !contentKind(event)) { + const held = evidence?.(messageId); + if ( + !held || + channelOf(held) !== channelId || + !contentKind(held) || + deleted(held) + ) + return unknown; + return Object.freeze({ + status: "ineligible", + unread: false, + forced: + !agentAudience(held) && + (forcedMessages.get(channelId)?.has(messageId) ?? false), + viewing: [...views.values()].some( + (view) => + view.channelId === channelId && + view.visible(messageId, view.ids.has(messageId)), + ), + }); + } const entry = byChannel .get(channelId) ?.find((row) => row.event.id === messageId); @@ -1298,9 +1332,12 @@ export function createUnread({ const event = target.kind === "thread" ? structural(target.rootId) - : events.get(target.messageId); + : knownEvent(target.messageId); return ( !!event && + (target.kind === "thread" || + events.has(target.messageId) || + !deleted(event)) && channelOf(event) === target.channelId && contentKind(event) ); @@ -2920,7 +2957,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) || @@ -2931,7 +2968,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"); @@ -2946,7 +2983,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"); } @@ -2976,7 +3013,7 @@ export function createUnread({ } } return [...ids].flatMap((id) => { - const event = events.get(id); + const event = knownEvent(id); return event ? [event] : []; }); } @@ -2995,7 +3032,11 @@ export function createUnread({ * message or a reply in another thread): one frontier cannot skip that * message, so the thread's later replies stay unread too. Per-message unread * intent never stops it, since an advance leaves that message unread. */ - function dmCut(channelId: string, rootId: string | undefined) { + function dmCut( + channelId: string, + rootId: string | undefined, + witnessAt = -1, + ) { indexEvidence(); const rows = byChannel.get(channelId) ?? []; const state = reads.state(); @@ -3010,7 +3051,10 @@ export function createUnread({ afterFrontier(row, state, true) ? Math.min(cut, row.event.created_at - 1) : cut, - rows.reduce((newest, row) => Math.max(newest, row.event.created_at), -1), + rows.reduce( + (newest, row) => Math.max(newest, row.event.created_at), + witnessAt, + ), ); } // Capture evidence and time once per click, including every channel in a sweep. @@ -3188,7 +3232,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; @@ -3225,12 +3269,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; @@ -3239,7 +3284,7 @@ export function createUnread({ } catch { continue; } - const cut = dmCut(channelId, rootId); + const cut = dmCut(channelId, rootId, event.created_at); dmRead = (reads.state().frontiers[channelId] ?? -1) < cut || manual(channelId) @@ -3285,7 +3330,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 }; @@ -3401,7 +3446,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. @@ -3544,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)); const finishPending = trackPendingForcedMessages( channelId, rows.map((row) => row.id), @@ -3583,7 +3628,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)); @@ -3595,8 +3640,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), @@ -3616,7 +3661,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"); @@ -3651,7 +3696,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); @@ -3682,8 +3727,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 () => { @@ -3716,8 +3761,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}`, ]), @@ -3855,7 +3900,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( diff --git a/src/plugins/author.ts b/src/plugins/author.ts index 5858abc81c..5efbd3d387 100644 --- a/src/plugins/author.ts +++ b/src/plugins/author.ts @@ -111,6 +111,9 @@ export type { ComposerReplacement, ComposerAccessory, ComposerAccessoryProps, + ConversationPresentation, + PresentationLimits, + PresentResult, ComposerResource, ComposerCaptureProps, AttachmentRenderer, @@ -129,6 +132,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/browser/inline-threads.spec.mjs b/tests/browser/inline-threads.spec.mjs index 6b691fd8a2..5b945ff24a 100644 --- a/tests/browser/inline-threads.spec.mjs +++ b/tests/browser/inline-threads.spec.mjs @@ -1,6 +1,6 @@ import { test, expect } from "./fixture.mjs"; import { hoverMessage } from "./message-actions.mjs"; -import { clickRow, open, settle } from "./timeline.mjs"; +import { activate, clickRow, open, settle } from "./timeline.mjs"; // Browser-only: the inline thread and details are dialogs on the conversation // visit. Only real history events, layout around a composer and the composer's @@ -471,3 +471,366 @@ test.describe("Sending", () => { await expect(detailsSheet(page)).toHaveCount(0); }); }); + +const presentedTest = test.extend({ + pluginFixtures: true, + threadPlacement: "inline", + enabledPlugins: ["fixture.thread-arrangement"], +}); + +presentedTest.describe("Presented focus", () => { + const threadHistory = (scope) => + scope.getByRole("region", { name: "Thread messages", exact: true }); + const arrangementStatus = (scope) => + scope.getByRole("status", { name: "Arrangement status", exact: true }); + const rowInReader = (history, id) => + history.evaluate((section, messageId) => { + const row = section.querySelector(`[data-message-id="${messageId}"]`); + const s = section.getBoundingClientRect(); + const r = row?.getBoundingClientRect(); + return !!r && r.bottom > s.top && r.top < s.bottom; + }, id); + + const presentRows = (scope) => + scope.getByRole("button", { name: "Present rows", exact: true }); + + presentedTest( + "deleting a focused presented reply in an inline thread keeps the surviving focused row in view", + async ({ page, app }) => { + const [root] = roots(app); + const replies = []; + for (let index = 0; index < 80; index++) { + const content = + index === 79 + ? `Jump to ` + : `Presented reply ${index}: ${"Synthetic history line. ".repeat(3)}`; + replies.push( + app.append( + "primary", + "alpha", + content, + false, + true, + root.id, + undefined, + [], + root.created_at + index + 10, + ), + ); + } + const target = replies[40]; + const survivor = replies[41]; + const linkReply = replies[79]; + app.append("primary", "alpha", "Channel tail", false, true); + + await open(page, app); + await clickRow(page, viewThread(page, root)); + await expect(sheet(page)).toBeVisible(); + await page.evaluate( + ({ events, rememberTopId }) => { + window.fixtureArrangement = { events, rememberTopId }; + }, + { events: replies, rememberTopId: linkReply.id }, + ); + await presentRows(sheet(page)).click(); + await expect(arrangementStatus(sheet(page))).toHaveText("Arranged: 80"); + + const history = threadHistory(sheet(page)); + const linkRow = history.locator(`[data-message-id="${linkReply.id}"]`); + await linkRow.scrollIntoViewIfNeeded(); + await page.evaluate(() => { + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + let armed = true; + window.__releaseRemembered = () => release(); + window.fixtureArrangementBeforePresent = () => { + if (!armed) return Promise.resolve(); + armed = false; + return gate; + }; + }); + await activate(linkRow.getByRole("link")); + await expect(sheet(page)).toBeVisible(); + const reopenedHistory = threadHistory(sheet(page)); + const targetRow = reopenedHistory.locator( + `[data-message-id="${target.id}"]`, + ); + await expect( + targetRow.locator( + '[data-highlight-surface][class*="messageHighlight"]', + ), + ).toBeVisible(); + await expect(targetRow).toBeFocused(); + await page.evaluate(() => window.__releaseRemembered?.()); + await expect(arrangementStatus(sheet(page))).toHaveText("Arranged: 80"); + expect(await rowInReader(reopenedHistory, target.id)).toBe(true); + await expect(targetRow).toBeInViewport(); + await settle(page, reopenedHistory); + expect(await rowInReader(reopenedHistory, target.id)).toBe(true); + await expect(targetRow).toBeInViewport(); + + app.deleteTarget(target); + await expect(targetRow).toHaveCount(0); + const survivorRow = reopenedHistory.locator( + `[data-message-id="${survivor.id}"]`, + ); + await expect(survivorRow.locator(":scope > [data-layout]")).toBeFocused(); + await settle(page, reopenedHistory); + + expect(await rowInReader(reopenedHistory, survivor.id)).toBe(true); + await expect(survivorRow).toBeInViewport(); + + const scrolledAway = reopenedHistory.locator( + `[data-message-id="${replies[75].id}"]`, + ); + await scrolledAway.scrollIntoViewIfNeeded(); + await settle(page, reopenedHistory); + expect(await rowInReader(reopenedHistory, survivor.id)).toBe(false); + expect(await rowInReader(reopenedHistory, replies[75].id)).toBe(true); + const pluginTarget = replies[5]; + await page.evaluate( + ({ events, placeId }) => { + window.fixtureArrangement = { + events, + place: { id: placeId }, + }; + }, + { + events: replies.filter((row) => row.id !== target.id), + placeId: pluginTarget.id, + }, + ); + await presentRows(sheet(page)).click(); + await expect(arrangementStatus(sheet(page))).toHaveText("Arranged: 79"); + await settle(page, reopenedHistory); + expect(await rowInReader(reopenedHistory, pluginTarget.id)).toBe(true); + await expect( + reopenedHistory.locator(`[data-message-id="${pluginTarget.id}"]`), + ).toBeInViewport(); + }, + ); + + presentedTest( + "following a link to a reply hidden by a remembered presentation keeps focus on the linked reply after withdrawal", + async ({ page, app }) => { + const [root] = roots(app); + const replies = Array.from({ length: 80 }, (_, index) => + app.append( + "primary", + "alpha", + `Filtered reply ${index}`, + false, + true, + root.id, + undefined, + [], + root.created_at + index + 10, + ), + ); + const target = replies[2]; + const filtered = replies.filter((row) => row.id !== target.id); + const linkMessage = app.append( + "primary", + "alpha", + `Jump to `, + false, + true, + ); + await open(page, app); + await clickRow(page, viewThread(page, root)); + await expect(sheet(page)).toBeVisible(); + await page.evaluate( + ({ events, rememberTopId }) => { + window.fixtureArrangement = { events, rememberTopId }; + }, + { events: filtered, rememberTopId: replies[70].id }, + ); + await presentRows(sheet(page)).click(); + await expect(arrangementStatus(sheet(page))).toHaveText("Arranged: 79"); + await expect( + threadHistory(sheet(page)).locator(`[data-message-id="${target.id}"]`), + ).toHaveCount(0); + await page.keyboard.press("Escape"); + await expect(sheet(page)).toHaveCount(0); + + await page.evaluate((targetId) => { + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + let armed = true; + window.fixtureArrangementBeforePresent = () => { + if (!armed) return Promise.resolve(); + armed = false; + return gate; + }; + const onFocusIn = (event) => { + const node = event.target instanceof Element ? event.target : null; + const row = node?.closest?.("[data-message-id]"); + if (row?.getAttribute("data-message-id") === targetId) { + document.removeEventListener("focusin", onFocusIn, true); + release(); + } + }; + document.addEventListener("focusin", onFocusIn, true); + }, target.id); + + await activate( + page + .locator( + `[data-channel-timeline] [data-message-id="${linkMessage.id}"]`, + ) + .getByRole("link"), + ); + await expect(sheet(page)).toBeVisible(); + const history = threadHistory(sheet(page)); + const targetRow = history.locator(`[data-message-id="${target.id}"]`); + await expect(arrangementStatus(sheet(page))).toHaveText( + "Showing the linked reply in Buzz order", + ); + await expect( + targetRow.locator( + '[data-highlight-surface][class*="messageHighlight"]', + ), + ).toBeVisible(); + await expect(targetRow).toBeInViewport(); + await expect(targetRow).toBeFocused(); + }, + ); + + presentedTest( + "plugin placement applies after a second hiding presentation in an inline sheet and after a failed exact lookup", + async ({ page, app }) => { + const [root] = roots(app); + const replies = Array.from({ length: 80 }, (_, index) => + app.append( + "primary", + "alpha", + `Placement reply ${index}: ${"Synthetic history line. ".repeat(3)}`, + false, + true, + root.id, + undefined, + [], + root.created_at + index + 10, + ), + ); + const target = replies[2]; + const deletedTarget = replies[40]; + const secondPlace = replies[65]; + const failedPlace = replies[60]; + const filtered = replies.filter((row) => row.id !== target.id); + const linkHidden = app.append( + "primary", + "alpha", + `Hidden link `, + false, + true, + ); + const linkDeleted = app.append( + "primary", + "alpha", + `Missing link `, + false, + true, + ); + + await open(page, app); + await clickRow(page, viewThread(page, root)); + await expect(sheet(page)).toBeVisible(); + await page.evaluate( + ({ events, rememberTopId, placeId }) => { + window.fixtureArrangement = { + events, + rememberTopId, + onWithdraw: { events, place: { id: placeId } }, + }; + }, + { + events: filtered, + rememberTopId: replies[70].id, + placeId: secondPlace.id, + }, + ); + await presentRows(sheet(page)).click(); + await expect(arrangementStatus(sheet(page))).toHaveText("Arranged: 79"); + await page.keyboard.press("Escape"); + await expect(sheet(page)).toHaveCount(0); + + await page.evaluate((targetId) => { + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + let armed = true; + window.fixtureArrangementBeforePresent = () => { + if (!armed) return Promise.resolve(); + armed = false; + return gate; + }; + const onFocusIn = (event) => { + const node = event.target instanceof Element ? event.target : null; + const row = node?.closest?.("[data-message-id]"); + if (row?.getAttribute("data-message-id") === targetId) { + document.removeEventListener("focusin", onFocusIn, true); + release(); + } + }; + document.addEventListener("focusin", onFocusIn, true); + }, target.id); + + await activate( + page + .locator( + `[data-channel-timeline] [data-message-id="${linkHidden.id}"]`, + ) + .getByRole("link"), + ); + await expect(sheet(page)).toBeVisible(); + await expect(arrangementStatus(sheet(page))).toHaveText("Arranged: 79"); + const secondHistory = threadHistory(sheet(page)); + await settle(page, secondHistory); + expect(await rowInReader(secondHistory, secondPlace.id)).toBe(true); + await expect( + secondHistory.locator(`[data-message-id="${secondPlace.id}"]`), + ).toBeInViewport(); + + await page.keyboard.press("Escape"); + await expect(sheet(page)).toHaveCount(0); + + app.deleteTarget(deletedTarget); + await activate( + page + .locator( + `[data-channel-timeline] [data-message-id="${linkDeleted.id}"]`, + ) + .getByRole("link"), + ); + await expect(sheet(page)).toBeVisible(); + await expect( + sheet(page).getByText("Selected message unavailable.", { exact: true }), + ).toBeVisible(); + const remaining = replies.filter((row) => row.id !== deletedTarget.id); + await page.evaluate( + ({ events, placeId }) => { + window.fixtureArrangement = { + events, + place: { id: placeId }, + onWithdraw: { events, place: { id: placeId } }, + }; + }, + { events: remaining, placeId: failedPlace.id }, + ); + await presentRows(sheet(page)).click(); + await expect(arrangementStatus(sheet(page))).toHaveText("Arranged: 79"); + const failedHistory = threadHistory(sheet(page)); + await settle(page, failedHistory); + expect(await rowInReader(failedHistory, failedPlace.id)).toBe(true); + await expect( + failedHistory.locator(`[data-message-id="${failedPlace.id}"]`), + ).toBeInViewport(); + }, + ); +}); diff --git a/tests/browser/plugin-fixtures.tsx b/tests/browser/plugin-fixtures.tsx index 169096d0a5..c22c5a3b4a 100644 --- a/tests/browser/plugin-fixtures.tsx +++ b/tests/browser/plugin-fixtures.tsx @@ -3,13 +3,24 @@ import { soloRegionFixture } from "./solo-region-fixture"; import { companionPlugins } from "./companion-fixture"; import * as shortcutCounter from "../../examples/plugins/shortcut-counter/plugin.js"; import shortcutManifest from "../../examples/plugins/shortcut-counter/manifest.json"; -import { useEffect, useState, useSyncExternalStore } from "react"; +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, + useSyncExternalStore, +} from "react"; import { flushSync } from "react-dom"; import type { BundledPlugin } from "../../src/plugins/manager"; import type { Navigation } from "../../src/features/navigation/controller"; import type { PageProps } from "../../src/features/pages/service"; import type { PageNavigation } from "../../src/features/navigation/service"; -import type { PageTabTarget } from "../../src/features/conversation/contracts"; +import type { + ComposerAccessoryProps, + PageTabTarget, +} from "../../src/features/conversation/contracts"; +import { eventsDto, type RelayEvent } from "../../src/features/relay/events"; import type { RelayData } from "../../src/features/relay/service"; import { PanelSubview } from "../../src/features/panels/PanelSubview"; import { FolderOpenIcon } from "../../src/shared/design-system/icons"; @@ -69,6 +80,8 @@ declare global { fixtureRelay?: RelayData; revocationProbe?: "complete" | "resolve"; revocationAccepted?: boolean; + fixtureArrangement?: FixtureArrangement; + fixtureArrangementBeforePresent?: () => Promise; } } declare module "@deepseek-ai/cordis" { @@ -138,7 +151,153 @@ const fill = (background: string, zIndex?: number) => () => (
    ); +type FixtureArrangement = { + events: RelayEvent[]; + ids?: string[]; + place?: "start" | "keep" | { id: string }; + rememberTopId?: string; + onWithdraw?: FixtureArrangement; +}; + +const threadArrangementMemory = new Map(); + +function ThreadArrangementBar(props: ComposerAccessoryProps) { + const { + channelId, + threadRootId, + linkedMessageId, + session, + present, + presentation, + } = props; + const key = `${channelId}:${threadRootId ?? ""}`; + const [status, setStatus] = useState(""); + const active = useRef(undefined); + const wasPresentation = useRef(presentation); + const presentRef = useRef(present); + presentRef.current = present; + const linkedRef = useRef(linkedMessageId); + linkedRef.current = linkedMessageId; + + const apply = useCallback( + ( + next: FixtureArrangement, + place: "start" | "keep" | { id: string } = next.place ?? "start", + ) => { + const proven = eventsDto(next.events); + const ids = next.ids ?? proven.map((event) => event.id); + active.current = { ...next, events: proven, ids }; + const result = presentRef.current?.({ + ids, + events: proven, + complete: true, + place, + }); + if (result === "shown") setStatus(`Arranged: ${ids.length}`); + }, + [], + ); + + useLayoutEffect(() => { + const previous = wasPresentation.current; + wasPresentation.current = presentation; + if (previous === "shown" && presentation === "none") { + const followup = active.current?.onWithdraw; + active.current = undefined; + threadArrangementMemory.delete(key); + setStatus("Showing the linked reply in Buzz order"); + if (followup) apply(followup, followup.place ?? "start"); + } + }, [apply, key, presentation]); + + useEffect(() => { + if (!threadRootId || !present) return; + const saved = threadArrangementMemory.get(key); + if (!saved) return; + let cancelled = false; + void (async () => { + const gate = window.fixtureArrangementBeforePresent; + if (gate) await gate(); + if (cancelled) return; + const ids = saved.ids ?? saved.events.map((event) => event.id); + const linked = linkedRef.current; + const place = linked + ? ids.includes(linked) + ? { id: linked } + : "start" + : saved.rememberTopId + ? { id: saved.rememberTopId } + : "start"; + apply(saved, place); + })(); + return () => { + cancelled = true; + }; + }, [apply, key, present, threadRootId]); + + useEffect(() => { + if (!threadRootId) return; + return session.subscribeLive(({ events }) => { + const current = active.current; + if (!current) return; + const deleted = new Set(); + for (const event of events) { + if (event.kind !== 5) continue; + for (const [name, target] of event.tags) + if (name === "e" && target) deleted.add(target); + } + if (!deleted.size) return; + const remaining = current.events.filter( + (event) => !deleted.has(event.id), + ); + if (remaining.length === current.events.length) return; + const ids = current.ids?.filter((id) => !deleted.has(id)); + apply({ ...current, events: remaining, ids }, "keep"); + }); + }, [apply, session, threadRootId]); + + if (!threadRootId || !present) return null; + return ( +
    + + + {status} + +
    + ); +} + export const fixturePlugins: readonly BundledPlugin[] = [ + { + manifest: { + id: "fixture.thread-arrangement", + name: "Thread arrangement fixture", + apiVersion: 1, + }, + enabledByDefault: false, + module: { + inject: ["conversation"], + apply(ctx) { + ctx.conversation.registerAccessory({ + id: "arrange", + title: "Thread arrangement", + placement: "reader", + component: ThreadArrangementBar, + }); + }, + }, + }, soloRegionFixture, { manifest: { diff --git a/tests/fixtures/conversation-arranger/fixtures.ts b/tests/fixtures/conversation-arranger/fixtures.ts new file mode 100644 index 0000000000..3e648f29aa --- /dev/null +++ b/tests/fixtures/conversation-arranger/fixtures.ts @@ -0,0 +1,225 @@ +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); + +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) { + 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; + 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)); + 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, + ), + ); + } + 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) { + 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..544373cef1 --- /dev/null +++ b/tests/fixtures/conversation-arranger/plugin.ts @@ -0,0 +1,756 @@ +import type { + ChannelMessage, + ComposerAccessoryProps, + Context, + ConversationPresentation, + EventData, + ReadFilter, + RelayEvent, + RelaySession, +} from "../../../src/plugins/author"; + +export const inject = ["react", "conversation"]; + +type Sort = "top" | "oldest"; +type Cursor = { created_at: number; id: string }; +type Hold = ReturnType; + +const PAGE = 200; +const MORE = 260; +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, 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 = + | { 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] : [])); +const inOrder = (a: Cursor, b: Cursor) => + a.created_at - b.created_at || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0); +const exactTags = (event: EventData, tags: readonly (readonly string[])[]) => + event.tags.length === tags.length && + tags.every( + ([name, value]) => + event.tags.filter( + (tag) => tag.length === 2 && tag[0] === name && tag[1] === value, + ).length === 1, + ); +const invalidBounds = () => new Error("The relay sent invalid window bounds"); +const parsed = (content: string) => { + let body: unknown; + try { + body = JSON.parse(content); + } catch { + throw invalidBounds(); + } + if (typeof body !== "object" || body === null || Array.isArray(body)) + throw invalidBounds(); + return body as Record; +}; +const cursorOrNull = (value: unknown) => { + if (value == null) return null; + const { created_at, id } = value as Partial; + if ( + typeof created_at !== "number" || + !Number.isSafeInteger(created_at) || + created_at < 0 || + typeof id !== "string" || + !/^[0-9a-f]{64}$/.test(id) + ) + throw invalidBounds(); + return { created_at, id }; +}; +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) => ({ + 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; + let filter = ""; + let starts = [0]; + const events = new Map(); + let hold: Hold | undefined; + let closureRefused: string | undefined; + let scanned = false; + let walkStart: number | undefined; + let shown = 0; + let taken = 0; + let total = 0; + let message = ""; + let stops: (() => void)[] = []; + let queued = false; + 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(); + const fresh = new Map(); + for (const event of more) + if (event.kind !== kind && !events.has(event.id)) + fresh.set(event.id, event); + holdAll([...fresh.values()]); + } + function holdAll(more: readonly RelayEvent[] = []) { + try { + hold ??= props.session.retain(); + 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; + 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) { + if (!ids.length) return; + for (const scope of [ + { kinds: [5, 7, 9005, 40003], "#h": [props.channelId] }, + { kinds: [5, 9005] }, + ]) + 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 page(cursor: Cursor | undefined, signal: AbortSignal) { + const root = rootId(); + let closure = !root || closureRefused !== root; + const window = () => + [ + { + "#h": [props.channelId], + kinds: [9], + limit: PAGE, + include_aux: closure, + ...(root + ? { thread_window: true, "#e": [root], depth_limit: 100 } + : { top_level: true }), + ...(cursor ? { until: cursor.created_at, before_id: cursor.id } : {}), + }, + ] satisfies ReadFilter[]; + let answer: readonly RelayEvent[]; + const requested = Math.floor(Date.now() / 1000); + try { + answer = await read(window(), signal); + } catch (error) { + if (!root || !closure || (error as { status?: unknown }).status !== 503) + throw error; + closure = false; + answer = await read(window(), signal); + } + const stamped = answer.filter((event) => event.kind === kindOfBounds()); + if (stamped.length !== 1) throw invalidBounds(); + const threadBoundsVerifiedByHost = Boolean(root); + const at = cursor ? `${cursor.created_at}:${cursor.id}` : "head"; + const d = `${props.channelId}:${at}`; + const matching = stamped.flatMap((event) => { + if ( + event.pubkey !== props.session.relayAuthor || + (!threadBoundsVerifiedByHost && + !exactTags(event, [ + ["d", d], + ["h", props.channelId], + ])) + ) + return []; + const body = parsed(event.content); + return (body.direction ?? "older") === "older" ? [{ event, body }] : []; + }); + const [bound] = matching; + if ( + matching.length !== 1 || + !bound || + typeof bound.body.has_more !== "boolean" + ) + throw invalidBounds(); + const to = cursorOrNull(bound.body.next_cursor); + if ( + bound.body.has_more !== (to !== null) || + (to && cursor && inOrder(to, cursor) >= 0) + ) + throw invalidBounds(); + walkStart = Math.min( + walkStart ?? requested, + requested, + bound.event.created_at, + ); + keep(answer); + if (!closure) { + await replyAux( + answer + .filter((event) => event.kind === 9 && event.id !== root) + .map((event) => event.id), + signal, + ); + closureRefused = root; + } + return to; + } + const rootRead = (signal: AbortSignal) => { + const root = rootId(); + return root && !events.has(root) + ? read([{ ids: [root], "#h": [props.channelId], limit: 1 }], signal).then( + keep, + ) + : undefined; + }; + + async function scanAll(signal: AbortSignal) { + await rootRead(signal); + let cursor: Cursor | null | undefined; + while (cursor !== null) { + cursor = await page(cursor, signal); + emit(); + } + await overlap(signal); + scanned = true; + } + + const countRows = () => + [...events.values()].filter((e) => e.kind === 9 && e.id !== rootId()) + .length; + const enough = () => scanned; + const load = (signal: AbortSignal) => scanAll(signal); + + function arrange(place?: ConversationPresentation["place"]) { + const { present, limits } = 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)); + 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)), + ); + const pinned = sort === "top" ? mine : []; + const tail = sort === "top" ? [] : mine; + while (starts.length > 1 && offset() >= rest.length) starts.pop(); + const from = offset(); + 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 = rest.slice(from, from + Math.min(size, room)); + for (const row of [...pinned, ...window, ...tail]) { + const c = costOf(row); + if ( + chosen.length >= limits.rows || + (chosen.length > 0 && + (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])); + 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 = rest.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) { + 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) { + if (phase.state === "scanning") phase.abort.abort(); + phase = { + state: "failed", + sort: next, + message: error instanceof Error ? error.message : String(error), + }; + emit(); + } + + function rescan() { + repair = undefined; + forget(); + if (sort) refresh(); + else emit(); + } + 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(); + schedule(); + } + scheduleRescan(); + } + + function onLive({ events: heard }: { events: readonly RelayEvent[] }) { + if (!sort && !events.size) return; + const root = rootId(); + const fresh = new Map(); + const known = (id: string) => events.has(id) || fresh.has(id); + for (const event of heard) + if ( + event.kind === 9 && + !known(event.id) && + event.tags.some(([name, id]) => + root + ? name === "e" && id === root + : name === "h" && id === props.channelId, + ) + ) + fresh.set(event.id, event); + for (let hop = 0; hop < 2; hop++) + for (const event of heard) + if ( + AUX.has(event.kind) && + !known(event.id) && + auxTargets(event).some(known) + ) + fresh.set(event.id, event); + if (!fresh.size) return; + try { + holdAll([...fresh.values()]); + } 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; + forget(); + emit(); + } + + 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 = { + start(next: Sort) { + sort = next; + size = PAGE; + starts = [0]; + message = ""; + refresh("start"); + }, + find(text: string) { + filter = text.trim(); + sort ??= "oldest"; + size = PAGE; + starts = [0]; + message = ""; + refresh(); + }, + more() { + if (phase.state !== "ready") return; + size = Math.min(size + MORE, props.limits?.rows ?? size + MORE); + refresh(); + }, + 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(); + }, + ended() { + if (phase.state !== "ready") return; + size = Math.max(SMALLEST, Math.floor(shown / 2)); + message = "Showing fewer rows: the reader reached its limit."; + arrange(); + }, + free() { + if (phase.state === "ready" && sort) arrange(); + }, + stop, + 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 {} + } + }, + 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() { + const next = offset() + taken < total; + 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), + [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, + ); + 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") return; + if (before === "shown") arranger.stop(); + else arranger.free(); + }, [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..ea92b9658c --- /dev/null +++ b/tests/fixtures/conversation-arranger/relay.ts @@ -0,0 +1,391 @@ +import { getEventHash, type Event } from "nostr-tools"; +import type { + EventData, + ReadFilter, + RelayEvent, +} from "../../../src/features/relay/events"; +import { ReadError } from "../../../src/features/relay/errors"; +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 { threadBinding } from "../../../src/features/relay/thread-window"; +import { + keypair, + roster, + metadata, + signed, + type Key, +} from "../../../src/features/relay/testing"; + +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[][]; + }, +) { + 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[]) { + 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) { + 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, 9005]); +const WINDOW_ROWS = 8192; +const targetsOf = (event: EventData) => + event.tags.flatMap(([name, id]) => (name === "e" && id ? [id] : [])); +const ascending = (a: EventData, b: EventData) => + a.created_at - b.created_at || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0); + +/** 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, + messages: () => [...top, ...[...replies.values()].flat()].sort(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; + }, + 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) ?? []), + deleted: (event: RelayEvent) => + (aux.get(event.id) ?? []).some( + (e) => e.kind === 5 && e.pubkey === event.pubkey, + ), + }; + world.add(events); + return world; +} +export type World = ReturnType; + +function after(rows: readonly RelayEvent[], filter: ReadFilter) { + 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 ?? "")), + ); +} + +export type Bound = { tags: string[][]; body: Record }; + +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: Math.floor(Date.now() / 1000), + 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; + /** 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; + /** The bounds a window answer carries in place of the true one, as a faulty relay sends. */ + bounds?: (made: Bound, filter: ReadFilter) => Bound[]; +}) { + const { world, viewer, relay } = options; + const bounds = (kind: 39006 | 39007, filter: ReadFilter, made: Bound) => + Promise.all( + (options.bounds?.(made, filter) ?? [made]).map(({ tags, body }) => + bound(relay, kind, tags, body), + ), + ); + 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); + 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]; + 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 binding = await threadBinding(filter, ORIGIN, viewer.pubkey); + return [ + ...shown, + ...(filter.include_aux + ? world.closure([roots, ...shown.map((e) => e.id)]) + : []), + ...(await bounds(39007, filter, { + tags: [ + ["d", binding], + ["h", CHANNEL], + ["e", roots], + ], + body: { + version: 1, + direction: "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 cursor = + filter.until === undefined + ? "head" + : `${filter.until}:${filter.before_id}`; + return [ + ...shown, + ...(filter.include_aux ? world.closure(shown.map((e) => e.id)) : []), + ...(await bounds(39006, filter, { + tags: [ + ["h", CHANNEL], + ["d", `${CHANNEL}:${cursor}`], + ], + body: { + has_more: more, + next_cursor: + more && last + ? { created_at: last.created_at, id: last.id } + : null, + }, + })), + ]; + } + 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"]; + 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) && + (named + ? e.tags.some( + ([name, id]) => name === "h" && named.includes(id ?? ""), + ) + : !options.namedOnly || !e.tags.some(([name]) => name === "h")), + ) + .map((e) => [e.id, e]), + ); + return after([...found.values()].sort(ascending), filter).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"); + 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 }; +} + +/** A session on a fixture relay, with a writer whose publication the test releases. */ +export function openSession(options: { + world: World; + viewer?: Key; + relay?: Key; + hold?: (filters: readonly ReadFilter[]) => Promise | undefined; + windowRows?: number; + namedOnly?: boolean; + bounds?: (made: Bound, filter: ReadFilter) => Bound[]; +}) { + 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, + 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, + hear(...events: readonly RelayEvent[]) { + traffic.receive(events, live); + }, + connection(status: LiveSnapshot["status"]) { + traffic.state({ status, routes: [] }); + }, + }; +}