Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(web): bound retained room messages and defer html fragment iframes

jeffrey27a79e809b65
diff --git a/apps/web/src/features/rooms/chat/message-html-fragment.test.tsx b/apps/web/src/features/rooms/chat/message-html-fragment.test.tsx
index 20c33fbc..20d359ac 100644
--- a/apps/web/src/features/rooms/chat/message-html-fragment.test.tsx
+++ b/apps/web/src/features/rooms/chat/message-html-fragment.test.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { writeClipboardText } from "@/lib/clipboard";
@@ -78,6 +78,59 @@ describe("MessageHtmlFragment", () => {
});
});
+ it("creates the iframe only once the fragment nears the viewport", () => {
+ let enter: () => void = () => {};
+ const observe = vi.fn();
+ const disconnect = vi.fn();
+ const init = vi.fn();
+ vi.stubGlobal(
+ "IntersectionObserver",
+ class {
+ constructor(
+ callback: IntersectionObserverCallback,
+ options: IntersectionObserverInit,
+ ) {
+ init(options);
+ enter = () =>
+ callback(
+ [{ isIntersecting: true } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ observe = observe;
+ disconnect = disconnect;
+ },
+ );
+ try {
+ const { container } = render(
+ <div style={{ overflowY: "auto" }} data-testid="scroller">
+ <MessageHtmlFragment html="<p>Widget</p>" title="Deferred widget" />
+ </div>,
+ );
+ // The margin applies to the timeline scroller, not the page viewport.
+ expect(init).toHaveBeenCalledWith({
+ root: screen.getByTestId("scroller"),
+ rootMargin: "600px 0px",
+ });
+
+ expect(container.querySelector("iframe")).toBeNull();
+ expect(screen.getByRole("img", { name: "Deferred widget" })).toHaveStyle({
+ height: "50px",
+ });
+ expect(observe).toHaveBeenCalledOnce();
+
+ act(() => enter());
+
+ expect(screen.getByTitle("Deferred widget").tagName).toBe("IFRAME");
+ expect(
+ screen.queryByRole("img", { name: "Deferred widget" }),
+ ).not.toBeInTheDocument();
+ expect(disconnect).toHaveBeenCalled();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
it("names downloaded SVG fragments from the message title", () => {
expect(
fragmentDownloadFileName(
diff --git a/apps/web/src/features/rooms/chat/message-html-fragment.tsx b/apps/web/src/features/rooms/chat/message-html-fragment.tsx
index 1bace1f9..3da28fd0 100644
--- a/apps/web/src/features/rooms/chat/message-html-fragment.tsx
+++ b/apps/web/src/features/rooms/chat/message-html-fragment.tsx
@@ -4,7 +4,7 @@ import {
MoreHorizontalIcon,
Tick02Icon,
} from "@hugeicons/core-free-icons";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Icon } from "@/components/ui/icon";
import { writeClipboardText } from "@/lib/clipboard";
@@ -59,9 +59,50 @@ export function HtmlFragmentFrame({
widgetHtml: string;
}) {
const frameRef = useRef<HTMLIFrameElement>(null);
+ const hostRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(minFragmentHeight);
// The width cap the fragment declares, if any; otherwise the chat width.
const [contentWidth, setContentWidth] = useState<number | null>(null);
+ // Each fragment is a script-running document. Create it only when it nears
+ // the viewport, so a long history does not start every widget at once.
+ const [nearViewport, setNearViewport] = useState(
+ () => typeof IntersectionObserver === "undefined",
+ );
+
+ useEffect(() => {
+ const host = hostRef.current;
+ if (nearViewport || !host) return;
+ // rootMargin only widens the root's own box, so the timeline scroller
+ // must be the root; with the page viewport the margin would be clipped.
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ observer.disconnect();
+ setNearViewport(true);
+ }
+ },
+ { root: scrollingAncestor(host), rootMargin: "600px 0px" },
+ );
+ observer.observe(host);
+ return () => observer.disconnect();
+ }, [nearViewport]);
+
+ // A fragment that loads above the visible area grows the content under it;
+ // keep what the reader is looking at in place, as browser scroll anchoring
+ // is off in the timeline.
+ const renderedHeightRef = useRef(height);
+ useLayoutEffect(() => {
+ const delta = height - renderedHeightRef.current;
+ renderedHeightRef.current = height;
+ const host = hostRef.current;
+ if (!delta || !host) return;
+ const scroller = scrollingAncestor(host);
+ if (!scroller) return;
+ const previousBottom = host.getBoundingClientRect().bottom - delta;
+ if (previousBottom <= scroller.getBoundingClientRect().top) {
+ scroller.scrollTop += delta;
+ }
+ }, [height]);
useEffect(() => {
const onMessage = (event: MessageEvent) => {
@@ -91,28 +132,51 @@ export function HtmlFragmentFrame({
// width narrower gets a frame that hugs it (plus the 1px border on
// each side).
className="group relative my-2 max-w-full"
+ ref={hostRef}
style={{
width: contentWidth
? `min(${contentWidth + 2}px, var(--chat-card-width))`
: "var(--chat-card-width)",
}}
>
- <iframe
- className="block w-full rounded-xl border border-app-border bg-app-surface shadow-[var(--chat-card-shadow)]"
- data-html-fragment=""
- ref={frameRef}
- sandbox="allow-scripts"
- srcDoc={source}
- // The reported height is the content's; the 1px border on each side
- // comes on top, so the fragment shows in full without a scrollbar.
- style={{ height: height + 2 }}
- title={title}
- />
+ {nearViewport ? (
+ <iframe
+ className="block w-full rounded-xl border border-app-border bg-app-surface shadow-[var(--chat-card-shadow)]"
+ data-html-fragment=""
+ ref={frameRef}
+ sandbox="allow-scripts"
+ srcDoc={source}
+ // The reported height is the content's; the 1px border on each side
+ // comes on top, so the fragment shows in full without a scrollbar.
+ style={{ height: height + 2 }}
+ title={title}
+ />
+ ) : (
+ <div
+ aria-label={title}
+ className="w-full rounded-xl border border-app-border bg-app-surface shadow-[var(--chat-card-shadow)]"
+ data-html-fragment-placeholder=""
+ role="img"
+ style={{ height: height + 2 }}
+ />
+ )}
<FragmentHostActions html={widgetHtml} title={title} />
</div>
);
}
+function scrollingAncestor(element: HTMLElement) {
+ for (
+ let parent = element.parentElement;
+ parent;
+ parent = parent.parentElement
+ ) {
+ const { overflowY } = getComputedStyle(parent);
+ if (overflowY === "auto" || overflowY === "scroll") return parent;
+ }
+ return null;
+}
+
function FragmentHostActions({ html, title }: { html: string; title: string }) {
const rootRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
diff --git a/apps/web/src/features/rooms/chat/room-message-window.test.tsx b/apps/web/src/features/rooms/chat/room-message-window.test.tsx
new file mode 100644
index 00000000..ec6d4eb5
--- /dev/null
+++ b/apps/web/src/features/rooms/chat/room-message-window.test.tsx
@@ -0,0 +1,123 @@
+import { QueryClient } from "@tanstack/react-query";
+import { renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ ROOM_MESSAGE_RETAINED_LIMIT,
+ planRoomMessageWindowTrim,
+ useRoomMessageWindowTrim,
+} from "./room-message-window";
+
+function page(from: number, count: number) {
+ return {
+ items: Array.from({ length: count }, (_, index) => `m${from + index}`),
+ page: { has_more: true, next_cursor: `m${from}` },
+ };
+}
+
+function history(sizes: number[]) {
+ // Newest page first, as TeamHub returns them.
+ let next = sizes.reduce((sum, size) => sum + size, 0);
+ const pages = sizes.map((size) => {
+ next -= size;
+ return page(next, size);
+ });
+ return {
+ pages,
+ pageParams: pages.map((_, index) =>
+ index === 0 ? undefined : pages[index - 1]!.page.next_cursor,
+ ),
+ };
+}
+
+describe("planRoomMessageWindowTrim", () => {
+ it("keeps history within the limit untouched", () => {
+ expect(planRoomMessageWindowTrim(history([50, 50, 50, 50]))).toEqual({
+ kind: "none",
+ });
+ });
+
+ it("drops older pages beyond the limit with their page params", () => {
+ const data = history([51, 50, 50, 50, 50]);
+ const plan = planRoomMessageWindowTrim(data);
+
+ expect(plan.kind).toBe("drop-older-pages");
+ if (plan.kind === "none") return;
+ expect(plan.data.pages).toEqual(data.pages.slice(0, 3));
+ expect(plan.data.pageParams).toEqual(data.pageParams.slice(0, 3));
+ // The last kept page still continues into the dropped history.
+ expect(plan.data.pages.at(-1)!.page.next_cursor).toBe(data.pageParams[3]);
+ });
+
+ it("refetches the newest page once live appends alone outgrow the limit", () => {
+ const data = history([ROOM_MESSAGE_RETAINED_LIMIT + 1, 50]);
+ const plan = planRoomMessageWindowTrim(data);
+
+ expect(plan).toEqual({
+ kind: "refetch-newest",
+ data: { pages: [data.pages[0]], pageParams: [undefined] },
+ });
+ });
+});
+
+describe("useRoomMessageWindowTrim", () => {
+ const queryKey = ["teamhub", "t", "room", "r", "messages"];
+
+ function setup(
+ sizes: number[],
+ canTrim: boolean,
+ state: { fetchStatus?: "fetching"; status?: "error" } = {},
+ ) {
+ const queryClient = new QueryClient();
+ queryClient.setQueryData(queryKey, history(sizes));
+ queryClient.getQueryCache().find({ queryKey })!.setState(state);
+ const refetch = vi
+ .spyOn(queryClient, "refetchQueries")
+ .mockResolvedValue(undefined);
+ renderHook(() =>
+ useRoomMessageWindowTrim({
+ canTrim: () => canTrim,
+ messageCount: sizes.reduce((sum, size) => sum + size, 0),
+ queryClient,
+ queryKey,
+ }),
+ );
+ return {
+ pageCount: () =>
+ queryClient.getQueryData<{ pages: unknown[] }>(queryKey)!.pages.length,
+ refetch,
+ };
+ }
+
+ it("keeps everything while the reader is in history or a link is open", () => {
+ const { pageCount, refetch } = setup([50, 50, 50, 50, 50], false);
+ expect(pageCount()).toBe(5);
+ expect(refetch).not.toHaveBeenCalled();
+ });
+
+ it("drops older pages while following the newest Message", () => {
+ const { pageCount, refetch } = setup([50, 50, 50, 50, 50], true);
+ expect(pageCount()).toBe(4);
+ expect(refetch).not.toHaveBeenCalled();
+ });
+
+ it("refetches an oversized newest page instead of inventing a cursor", () => {
+ const { pageCount, refetch } = setup([250, 50], true);
+ expect(pageCount()).toBe(1);
+ expect(refetch).toHaveBeenCalledWith({ exact: true, queryKey });
+ });
+
+ it("waits while an older page loads", () => {
+ const { pageCount, refetch } = setup([50, 50, 50, 50, 50], true, {
+ fetchStatus: "fetching",
+ });
+ expect(pageCount()).toBe(5);
+ expect(refetch).not.toHaveBeenCalled();
+ });
+
+ it("does not refetch after a failed read", () => {
+ const { pageCount, refetch } = setup([250, 50], true, { status: "error" });
+ expect(pageCount()).toBe(2);
+ expect(refetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/rooms/chat/room-message-window.ts b/apps/web/src/features/rooms/chat/room-message-window.ts
new file mode 100644
index 00000000..b6e2b69c
--- /dev/null
+++ b/apps/web/src/features/rooms/chat/room-message-window.ts
@@ -0,0 +1,94 @@
+import type {
+ InfiniteData,
+ QueryClient,
+ QueryKey,
+} from "@tanstack/react-query";
+import { useEffect } from "react";
+
+/**
+ * Messages a Room timeline keeps loaded while the reader follows the newest
+ * Message. A tab left open in a busy Room would otherwise keep every Message
+ * it ever loaded or received, with its DOM, decoded images and HTML fragments.
+ * Dropped history loads again through "load older" when the reader scrolls up.
+ */
+export const ROOM_MESSAGE_RETAINED_LIMIT = 200;
+
+type MessagePages<TPage extends { items: readonly unknown[] }> = InfiniteData<
+ TPage,
+ unknown
+>;
+
+export type RoomMessageWindowTrim<TPage extends { items: readonly unknown[] }> =
+ | { kind: "none" }
+ /** Keep the newest pages; the last kept page's cursor still continues them. */
+ | { kind: "drop-older-pages"; data: MessagePages<TPage> }
+ /**
+ * The newest page alone outgrew the limit through live appends. Its cursor
+ * points before its oldest item, so dropping items would leave a gap; keep
+ * only that page and refetch it so TeamHub issues a cursor for the newest
+ * page. Live Messages newer than the response survive the refetch merge.
+ */
+ | { kind: "refetch-newest"; data: MessagePages<TPage> };
+
+/** Plans how to bring loaded Room history back within `limit` Messages. */
+export function planRoomMessageWindowTrim<
+ TPage extends { items: readonly unknown[] },
+>(
+ data: MessagePages<TPage>,
+ limit = ROOM_MESSAGE_RETAINED_LIMIT,
+): RoomMessageWindowTrim<TPage> {
+ const total = data.pages.reduce((sum, page) => sum + page.items.length, 0);
+ if (total <= limit || data.pages.length === 0) return { kind: "none" };
+ let kept = 0;
+ let count = 0;
+ for (const page of data.pages) {
+ if (kept > 0 && count + page.items.length > limit) break;
+ count += page.items.length;
+ kept += 1;
+ }
+ const trimmed = {
+ pages: data.pages.slice(0, kept),
+ pageParams: data.pageParams.slice(0, kept),
+ };
+ return count <= limit
+ ? { kind: "drop-older-pages", data: trimmed }
+ : { kind: "refetch-newest", data: trimmed };
+}
+
+/**
+ * Applies {@link planRoomMessageWindowTrim} after the loaded Message count
+ * changes, when no page is loading, the last read did not fail, and `canTrim`
+ * allows it. `canTrim` is read only on a count change, so it must read live
+ * state (refs, DOM) rather than values captured by an earlier render.
+ */
+export function useRoomMessageWindowTrim({
+ canTrim,
+ messageCount,
+ queryClient,
+ queryKey,
+}: {
+ canTrim: () => boolean;
+ messageCount: number;
+ queryClient: QueryClient;
+ queryKey: QueryKey;
+}) {
+ const queryHash = JSON.stringify(queryKey);
+ useEffect(() => {
+ if (messageCount <= ROOM_MESSAGE_RETAINED_LIMIT) return;
+ const state = queryClient.getQueryState(queryKey);
+ if (state?.fetchStatus !== "idle" || state.status === "error") return;
+ if (!canTrim()) return;
+ const data =
+ queryClient.getQueryData<MessagePages<{ items: readonly unknown[] }>>(
+ queryKey,
+ );
+ if (!data) return;
+ const plan = planRoomMessageWindowTrim(data);
+ if (plan.kind === "none") return;
+ queryClient.setQueryData(queryKey, plan.data);
+ if (plan.kind === "refetch-newest") {
+ void queryClient.refetchQueries({ exact: true, queryKey });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- the key is compared by value and canTrim reads refs
+ }, [messageCount, queryClient, queryHash]);
+}
diff --git a/apps/web/src/features/rooms/chat/use-room-chat-timeline-actions.ts b/apps/web/src/features/rooms/chat/use-room-chat-timeline-actions.ts
index dae5bfc6..84ae05ae 100644
--- a/apps/web/src/features/rooms/chat/use-room-chat-timeline-actions.ts
+++ b/apps/web/src/features/rooms/chat/use-room-chat-timeline-actions.ts
@@ -9,6 +9,7 @@ import { tenantRoomsQueryKey } from "../room-queries";
import { preloadUnifiedDocumentPage } from "../documents/document-route-preload";
import type { MessageComposition } from "./message-composer";
import { useRoomMessagePresentations } from "./room-message-presentations";
+import { useRoomMessageWindowTrim } from "./room-message-window";
import { replaceLoadedRoomMessage } from "./room-projection";
import { useFocusComposerOnEntry } from "./use-focus-composer-on-entry";
import { usePrefetchPanelAfterPaint } from "./use-prefetch-panel-after-paint";
@@ -36,7 +37,9 @@ export function useRoomChatTimelineActions(
actorItems,
client,
linkedMessage,
+ linkedMessageId,
messages,
+ messagesQuery,
navigate,
navigation,
openPanelTab,
@@ -188,6 +191,23 @@ export function useRoomChatTimelineActions(
)
void loadOlderMessages();
};
+ // Trim only while the reader follows the newest Message. A linked Message
+ // or a reader scrolled into history keeps every loaded page until the next
+ // Message count change finds them following again. A timeline shorter than
+ // five viewports is never trimmed, so the short-timeline loader below cannot
+ // load the dropped page back in a loop.
+ useRoomMessageWindowTrim({
+ canTrim: () =>
+ !linkedMessageId &&
+ timeline.initialScrollReady &&
+ timeline.isFollowingLatest() &&
+ !!timeline.timelineElement &&
+ timeline.timelineElement.scrollHeight >
+ 5 * timeline.timelineElement.clientHeight,
+ messageCount: orderedMessages.length,
+ queryClient,
+ queryKey: messagesQuery.queryKey,
+ });
const timelineViewport = timeline.timelineElement;
useEffect(() => {
if (
diff --git a/apps/web/src/features/rooms/chat/use-room-timeline-scroll.ts b/apps/web/src/features/rooms/chat/use-room-timeline-scroll.ts
index 28cea20c..d3d73f8a 100644
--- a/apps/web/src/features/rooms/chat/use-room-timeline-scroll.ts
+++ b/apps/web/src/features/rooms/chat/use-room-timeline-scroll.ts
@@ -249,9 +249,19 @@ export function useRoomTimelineScroll({
shouldAutoFollowRef.current = true;
}
+ /** Whether the reader follows the newest Message rather than history. */
+ function isFollowingLatest() {
+ return (
+ timelineElement !== null &&
+ pendingPrependRef.current === null &&
+ shouldAutoFollowRef.current
+ );
+ }
+
return {
cancelOlderMessagesIfUnchanged,
initialScrollReady,
+ isFollowingLatest,
pinToLatest,
prepareForOlderMessages,
recordTimelineScroll,
diff --git a/apps/web/src/features/rooms/room-queries.test.ts b/apps/web/src/features/rooms/room-queries.test.ts
index 66a4f856..c43a2685 100644
--- a/apps/web/src/features/rooms/room-queries.test.ts
+++ b/apps/web/src/features/rooms/room-queries.test.ts
@@ -29,6 +29,8 @@ import {
tenantAgentsQueryOptions,
tenantRoomsQueryOptions,
} from "./room-queries";
+import { appendRoomMessage } from "./chat/room-projection";
+import { planRoomMessageWindowTrim } from "./chat/room-message-window";
describe("Room query scope", () => {
it("reuses a recent Message snapshot on remount and still refreshes on invalidation", async () => {
@@ -483,6 +485,81 @@ describe("Room query scope", () => {
});
describe("Room Message query reconciliation", () => {
+ it("trims live-grown history through a refetch that keeps a real cursor and newer live Messages", async () => {
+ const runtime = createTestTeamHubRuntime();
+ const id = (index: number) => `message-${String(index).padStart(3, "0")}`;
+ let serverCount = 300;
+ runtime.server.on("GET", "/v0/rooms/{roomId}/messages", ({ query }) => {
+ const cursor = query.get("cursor");
+ const end = cursor
+ ? Number(cursor.slice("message-".length)) - 1
+ : serverCount;
+ const start = Math.max(1, end - 49);
+ return {
+ items: Array.from({ length: end - start + 1 }, (_, offset) =>
+ message(id(start + offset)),
+ ),
+ page:
+ start > 1
+ ? { has_more: true, next_cursor: id(start) }
+ : { has_more: false },
+ snapshot_room_seq: serverCount,
+ };
+ });
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const options = roomMessagesInfiniteQueryOptions(
+ runtime.client,
+ "tenant-northstar",
+ "room-all",
+ );
+ const observer = new InfiniteQueryObserver(queryClient, options);
+ const unsubscribe = observer.subscribe(() => undefined);
+ try {
+ await observer.refetch();
+ // Live delivery appends 160 Messages TeamHub also stores, then one the
+ // refetch response does not include yet.
+ for (let index = 301; index <= 460; index += 1) {
+ appendRoomMessage(queryClient, options.queryKey, message(id(index)));
+ }
+ serverCount = 460;
+ appendRoomMessage(queryClient, options.queryKey, message(id(461)));
+
+ const plan = planRoomMessageWindowTrim(
+ queryClient.getQueryData<InfiniteData<TeamHubMessagePage>>(
+ options.queryKey,
+ )!,
+ );
+ expect(plan.kind).toBe("refetch-newest");
+ queryClient.setQueryData(
+ options.queryKey,
+ plan.kind === "none" ? undefined : plan.data,
+ );
+ await queryClient.refetchQueries({
+ exact: true,
+ queryKey: options.queryKey,
+ });
+
+ const ids = () =>
+ observer
+ .getCurrentResult()
+ .data!.pages.slice()
+ .reverse()
+ .flatMap((page) => page.items.map((item) => item.id));
+ expect(ids()).toEqual(
+ Array.from({ length: 51 }, (_, offset) => id(411 + offset)),
+ );
+
+ await observer.fetchNextPage();
+ expect(ids()[0]).toBe(id(361));
+ expect(ids()).toHaveLength(101);
+ } finally {
+ unsubscribe();
+ queryClient.clear();
+ }
+ });
+
it("keeps a newer cached card when an older in-flight query resolves", async () => {
const runtime = createTestTeamHubRuntime();