Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): preserve activity log event positions when loading history (#991)
Generd9b04809fa2d
diff --git a/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts b/src/web/src/components/community/bots/bot-activity-modal.dom.test.tsindex 661dc84b1..1f596a314 100644--- a/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts+++ b/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts@@ -34,6 +34,7 @@ const {}))let scrollDescriptor: PropertyDescriptor | undefinedlet bodyHeight = 300+let deferScrollEvents = falselet rowHeights = new Map<string, number>()let bodyResizeObservers: Array<{ callback: ResizeObserverCallback; elements: Set<Element> }> = []@@ -150,7 +151,7 @@ function scrollBody(renderer: ReturnType<typeof render>, offset: number) {}function eventTop(renderer: ReturnType<typeof render>, id: string) {- return renderer.container.querySelector<HTMLElement>(`[data-activity-event-id="${id}"]`)!.getBoundingClientRect().top+ return renderer.container.querySelector<HTMLElement>(`[data-activity-event-id="${id}"] activity-row`)!.getBoundingClientRect().top}function events(count: number, day = "2026-08-27") {@@ -200,6 +201,7 @@ describe("BotActivityModal CommunitySheet contract", () => {fetchNextPage.mockResolvedValue({ isError: false, data: { pages: [{ events: [] }] } })sheetProps.current = nullbodyHeight = 300+ deferScrollEvents = falserowHeights = new Map()bodyResizeObservers = []vi.useFakeTimers()@@ -217,8 +219,10 @@ describe("BotActivityModal CommunitySheet contract", () => {})const isRoot = (node: HTMLElement) => node.dataset.testid === "activity-body"const rowHeight = (node: HTMLElement) => {+ if (node.closest("[data-activity-date]")) return 33const row = node.closest<HTMLElement>("[data-activity-row-key]")- return row?.dataset.activityRowKey?.includes(":date:") ? 24 : rowHeights.get(row?.dataset.activityEventId ?? "") ?? 44+ const body = rowHeights.get(row?.dataset.activityEventId ?? "") ?? 44+ return body + (node === row && row.querySelector("[data-activity-date]") ? 33 : 0)}vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockImplementation(function (this: HTMLElement) { return isRoot(this) ? bodyHeight : rowHeight(this) })vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(function (this: HTMLElement) { return this.clientHeight })@@ -230,14 +234,20 @@ describe("BotActivityModal CommunitySheet contract", () => {vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {const row = this.closest<HTMLElement>("[data-activity-row-key]")const root = this.closest<HTMLElement>('[data-testid="activity-body"]')- const start = Number.parseFloat(row?.style.transform.match(/translateY\((-?[\d.]+)px\)/)?.[1] ?? "0")- return DOMRect.fromRect({ width: 672, height: this.clientHeight, y: isRoot(this) ? 0 : start - (root?.scrollTop ?? 0) })+ const transform = row?.style.transform ?? ""+ const start = transform.startsWith("translate3d(")+ ? Number.parseFloat(transform.split(",")[1])+ : Number.parseFloat(transform.match(/translateY\((-?[\d.]+)px\)/)?.[1] ?? "0")+ const suffix = row && this.closest("[data-activity-date]") ? rowHeights.get(row.dataset.activityEventId ?? "") ?? 44 : 0+ const sticky = this.closest("[data-activity-sticky-date]")+ return DOMRect.fromRect({ width: 672, height: this.clientHeight, y: isRoot(this) || sticky ? 0 : start + suffix - (root?.scrollTop ?? 0) })})scrollDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollTo")Object.defineProperty(HTMLElement.prototype, "scrollTo", { configurable: true, value: function (this: HTMLElement, options: ScrollToOptions | number) {if (typeof options === "number") returnthis.scrollTop = Math.max(0, Math.min(options.top ?? this.scrollTop, this.scrollHeight - this.clientHeight))- this.dispatchEvent(new Event("scroll"))+ if (deferScrollEvents) window.setTimeout(() => this.dispatchEvent(new Event("scroll")), 0)+ else this.dispatchEvent(new Event("scroll"))} })})afterEach(() => {@@ -328,7 +338,9 @@ describe("BotActivityModal CommunitySheet contract", () => {event("old", "2026-08-26T12:00:00.000Z"),]const populated = renderModal().renderer- expect(populated.container.querySelectorAll('[data-activity-row-key*="date:"]')).toHaveLength(2)+ expect(populated.container.querySelectorAll("[data-activity-date]")).toHaveLength(2)+ expect(populated.container.querySelectorAll("[data-activity-row-key]")).toHaveLength(2)+ expect(populated.container.querySelector('[data-activity-row-key*="date:"]')).toBeNull()expect([...populated.container.querySelectorAll("activity-row")].map((row) => row.getAttribute("data-event-id"))).toEqual(["old", "new"])@@ -404,6 +416,36 @@ describe("BotActivityModal CommunitySheet contract", () => {expect(renderer.container.querySelector('[data-event-id="event-119"]')).toBeInTheDocument()})+ it("selects the new bot's latest event when the mounted modal switches identity", () => {+ auditState.events = events(120)+ const { renderer } = renderModal()+ scrollBody(renderer, 100)+ auditState.events = events(80).map(item => ({ ...item, id: `other-${item.id}` }))+ updateModal(renderer, { bot: { ...bot, id: "bot-2", name: "Other Bot" } })+ const root = renderer.getByTestId("activity-body")+ expect(auditHook).toHaveBeenLastCalledWith("bot-2")+ expect(root.scrollTop).toBe(root.scrollHeight - root.clientHeight)+ expect(renderer.container.querySelector('[data-event-id="other-event-79"]')).toBeInTheDocument()+ expect(renderer.container.querySelector('[data-activity-row-key^="bot-1:"]')).toBeNull()+ expect(renderer.container.querySelector('[data-event-id="event-0"]')).toBeNull()+ })++ it("keeps a reading event through viewport resize and a cross-day live append", () => {+ auditState.events = events(120)+ const { renderer } = renderModal()+ scrollBody(renderer, 600)+ const top = eventTop(renderer, "event-15")+ const date = renderer.container.querySelector("[data-activity-sticky-date]")!.getAttribute("data-activity-sticky-date")+ resizeBody(240)+ expect(eventTop(renderer, "event-15")).toBe(top)+ auditState.events = [...auditState.events, event("next-day", "2026-08-28T12:00:00.000Z")]+ updateModal(renderer)+ expect(eventTop(renderer, "event-15")).toBe(top)+ expect(renderer.container.querySelector("[data-activity-sticky-date]")!.getAttribute("data-activity-sticky-date")).toBe(date)+ scrollBody(renderer, 10_000)+ expect(renderer.container.querySelector('[data-event-id="next-day"]')).toBeInTheDocument()+ })+it("does not restore a completed request from before the modal reopened", async () => {auditState.events = events(30)auditState.hasNextPage = true@@ -483,7 +525,7 @@ describe("BotActivityModal CommunitySheet contract", () => {act(() => vi.advanceTimersByTime(500))expect(fetchNextPage).not.toHaveBeenCalled()const root = renderer.getByTestId("activity-body")- expect(renderer.container.querySelector('[data-activity-row-key*="date:"]')).toBeInTheDocument()+ expect(renderer.container.querySelector("[data-activity-sticky-date]")).toBeInTheDocument()act(() => root.scrollTo({ top: 340 }))expect(root.scrollTop).toBeGreaterThan(160)expect(fetchNextPage).toHaveBeenCalledOnce()@@ -520,18 +562,101 @@ describe("BotActivityModal CommunitySheet contract", () => {expect(renderer.queryByRole("button", { name: "Retry older" })).not.toBeInTheDocument()})- it("keeps the native date row at the top on a same-day prepend and the event anchor after leaving the header", async () => {- auditState.events = events(30)+ it.each([+ { crossDay: false, offset: 0, measuredHeight: 44 },+ { crossDay: false, offset: 80, measuredHeight: 44 },+ { crossDay: true, offset: 0, measuredHeight: 44 },+ { crossDay: true, offset: 80, measuredHeight: 44 },+ { crossDay: false, offset: 0, measuredHeight: 33 },+ { crossDay: false, offset: 80, measuredHeight: 33 },+ { crossDay: true, offset: 0, measuredHeight: 33 },+ { crossDay: true, offset: 80, measuredHeight: 33 },+ ])("keeps actual event content through two older pages at $offset, cross-day $crossDay, measured $measuredHeight", async ({ crossDay, offset, measuredHeight }) => {+ auditState.events = events(50)+ for (const item of auditState.events) rowHeights.set(item.id, measuredHeight)auditState.hasNextPage = trueconst { renderer } = renderModal()- const root = scrollBody(renderer, 0)- const header = renderer.container.querySelector<HTMLElement>('[data-activity-row-key*="date:"]')!- const key = header.dataset.activityRowKey- auditState.events = [...auditState.events, event("earlier", "2026-08-27T11:59:00.000Z")]- auditState.hasNextPage = false- updateModal(renderer)- expect(root.scrollTop).toBe(0)- expect(renderer.container.querySelector('[data-activity-row-key*="date:"]')).toHaveAttribute("data-activity-row-key", key)- expect(renderer.container.querySelector('[data-activity-event-id="earlier"]')).toBeInTheDocument()+ for (const [index, target] of [offset, 80].entries()) {+ const completePage = prepareOlderPage()+ const root = scrollBody(renderer, target)+ const anchor = [...renderer.container.querySelectorAll<HTMLElement>("activity-row")].find(row => {+ const rect = row.getBoundingClientRect()+ return rect.top >= 33 && rect.bottom <= root.clientHeight+ })!+ const id = anchor.closest<HTMLElement>("[data-activity-event-id]")!.dataset.activityEventId!+ const top = anchor.getBoundingClientRect().top+ const visibleDate = renderer.container.querySelector("[data-activity-sticky-date]")!.getAttribute("data-activity-sticky-date")+ expect(fetchNextPage).toHaveBeenCalledTimes(index + 1)+ auditState.isFetchingNextPage = true+ updateModal(renderer)+ const start = Date.parse(crossDay ? `2026-08-${26 - index}T12:00:00.000Z` : `2026-08-27T${11 - index}:00:00.000Z`)+ const page = Array.from({ length: 50 }, (_, ordinal) => event(`older-${index}-${ordinal}`, new Date(start + ordinal * 60_000).toISOString()))+ for (const item of page) rowHeights.set(item.id, measuredHeight)+ auditState.events = [...auditState.events, ...page]+ auditState.isFetchingNextPage = false+ updateModal(renderer)+ await completePage(page)+ expect(eventTop(renderer, id)).toBe(top)+ expect(root.scrollTop).toBeGreaterThan(target)+ expect(fetchNextPage).toHaveBeenCalledTimes(index + 1)+ expect(renderer.container.querySelector("[data-activity-sticky-date]")).toHaveAttribute("data-activity-sticky-date", visibleDate)+ for (const row of renderer.container.querySelectorAll<HTMLElement>("[data-activity-row-key]")) {+ expect(row.dataset.activityEventId).toBeTruthy()+ expect(row.dataset.activityRowKey).toBe(`bot-1:event:${row.dataset.activityEventId}`)+ }+ }+ })++ it.each([+ { crossDay: false, offset: 0, measuredHeight: 44 },+ { crossDay: false, offset: 80, measuredHeight: 44 },+ { crossDay: true, offset: 0, measuredHeight: 44 },+ { crossDay: true, offset: 80, measuredHeight: 44 },+ { crossDay: false, offset: 0, measuredHeight: 33 },+ { crossDay: false, offset: 80, measuredHeight: 33 },+ { crossDay: true, offset: 0, measuredHeight: 33 },+ { crossDay: true, offset: 80, measuredHeight: 33 },+ ])("keeps event Y with deferred scroll events at $offset, cross-day $crossDay, measured $measuredHeight", ({ crossDay, offset, measuredHeight }) => {+ deferScrollEvents = true+ auditState.events = events(50)+ for (const item of auditState.events) rowHeights.set(item.id, measuredHeight)+ const { renderer } = renderModal()+ act(() => vi.advanceTimersByTime(500))+ for (const [index, target] of [offset, 80].entries()) {+ const root = scrollBody(renderer, target)+ expect(root.scrollTop).toBe(target)+ const anchor = [...renderer.container.querySelectorAll<HTMLElement>("activity-row")].find(row => {+ const rect = row.getBoundingClientRect()+ return rect.top >= 33 && rect.bottom <= root.clientHeight+ })!+ const id = anchor.closest<HTMLElement>("[data-activity-event-id]")!.dataset.activityEventId!+ const top = anchor.getBoundingClientRect().top+ const start = Date.parse(crossDay ? `2026-08-${26 - index}T12:00:00.000Z` : `2026-08-27T${11 - index}:00:00.000Z`)+ const page = Array.from({ length: 50 }, (_, ordinal) => event(`deferred-${index}-${ordinal}`, new Date(start + ordinal * 60_000).toISOString()))+ for (const item of page) rowHeights.set(item.id, measuredHeight)+ auditState.events = [...auditState.events, ...page]+ auditState.loadedPageCount += 1+ updateModal(renderer)+ expect(eventTop(renderer, id)).toBe(top)+ expect(root.scrollTop).toBeGreaterThan(target)+ expect(fetchNextPage).not.toHaveBeenCalled()+ }})+++ it("updates the visible date at a payload boundary before the native range changes", () => {+ deferScrollEvents = true+ auditState.events = [...events(10), ...events(40, "2026-08-28").map(item => ({ ...item, id: `next-${item.id}` }))]+ const { renderer } = renderModal()+ act(() => vi.advanceTimersByTime(500))+ const root = renderer.getByTestId("activity-body")+ fireEvent.wheel(root, { deltaY: 434 })+ act(() => { root.scrollTo({ top: 434 }); vi.advanceTimersByTime(0) })+ expect(root.scrollTop).toBe(434)+ expect(renderer.container.querySelector("[data-activity-sticky-date]")).toHaveAttribute("data-activity-sticky-date", "2026-7-27")+ act(() => { root.scrollTo({ top: 444 }); vi.advanceTimersByTime(0) })+ expect(root.scrollTop).toBe(444)+ expect(renderer.container.querySelector("[data-activity-sticky-date]")).toHaveAttribute("data-activity-sticky-date", "2026-7-28")+ })+})diff --git a/src/web/src/components/community/bots/bot-activity-modal.tsx b/src/web/src/components/community/bots/bot-activity-modal.tsxindex 7d33b92e7..0b0c9a5e0 100644--- a/src/web/src/components/community/bots/bot-activity-modal.tsx+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx@@ -1,20 +1,19 @@"use client"-import { useCallback, useLayoutEffect, useMemo, useRef } from "react"+import { useCallback, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from "react"import { useAtom, useCreateAtom } from "@tanstack/react-store"-import { defaultRangeExtractor, useVirtualizer, type Range } from "@tanstack/react-virtual"+import { useVirtualizer } from "@tanstack/react-virtual"import { useVirtualCursorPagination } from "@/hooks/community/use-virtual-cursor-pagination"import { AgentAvatar } from "@/components/avatar"import { CommunitySheet } from "@/components/community/shell/community-sheet"import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"-import {- useBotAuditLog,- type AuditEvent,-} from "@/hooks/community/use-bot-audit-log"+import { useBotAuditLog } from "@/hooks/community/use-bot-audit-log"import type { BotSummary } from "@/hooks/community/use-bots"import { tid } from "@/lib/community/testids"import { BotActivityRow } from "./bot-activity-row"+const DAY_DIVIDER_HEIGHT = 33+export function BotActivityModal({bot,open,@@ -55,7 +54,10 @@ export function BotActivityModal({})}, [events])- const rows = useMemo(() => flattenActivityRows(chronological, bot?.id ?? ""), [chronological, bot?.id])+ const dateAfter = useMemo(() => chronological.map((event, index) => {+ const next = chronological[index + 1]+ return next && dayKey(next.createdAt) !== dayKey(event.createdAt) ? next.createdAt : null+ }), [chronological])const [scrollRoot, setScrollRoot] = useAtom(useCreateAtom<HTMLDivElement | null>(null))const [initialized, setInitialized] = useAtom(useCreateAtom(false))const setLogBody = useCallback((element: HTMLDivElement | null) => {@@ -66,29 +68,22 @@ export function BotActivityModal({}setScrollRoot(element)}, [setScrollRoot])- const stickyIndexes = useMemo(() => rows.flatMap((row, index) => row.kind === "date" ? [index] : []), [rows])- const activeStickyIndexRef = useRef<number | null>(null)- const getItemKey = useCallback((index: number) => rows[index].key, [rows])- const estimateSize = useCallback((index: number) => rows[index].kind === "date" ? 24 : 44, [rows])- const rangeExtractor = useCallback((range: Range) => {- const active = [...stickyIndexes].reverse().find((index) => index <= range.startIndex) ?? null- activeStickyIndexRef.current = active- return [...new Set([- ...(active === null ? [] : [active]),- ...defaultRangeExtractor(range),- ])].sort((a, b) => a - b)- }, [stickyIndexes])+ const getItemKey = useCallback((index: number) => `${bot?.id ?? ""}:event:${chronological[index].id}`, [chronological, bot?.id])+ const estimateSize = useCallback((index: number) => 44 + (dateAfter[index] ? DAY_DIVIDER_HEIGHT : 0), [dateAfter])+ const visibleDateListener = useRef<(() => void) | undefined>(undefined)+ const notifyVisibleDate = useCallback(() => visibleDateListener.current?.(), [])// eslint-disable-next-line react-hooks/incompatible-library -- supported TanStack Virtual imperative adapterconst virtualizer = useVirtualizer({- useFlushSync: false,- count: rows.length,+ directDomUpdates: true,+ onChange: notifyVisibleDate,+ count: chronological.length,getScrollElement: () => scrollRoot,getItemKey,estimateSize,- rangeExtractor,anchorTo: "end",followOnAppend: initialized,scrollEndThreshold: 80,+ paddingStart: DAY_DIVIDER_HEIGHT,paddingEnd: 12,overscan: 8,enabled: scrollRoot !== null,@@ -103,20 +98,29 @@ export function BotActivityModal({virtualizer.scrollToEnd()setInitialized(true)})+ const subscribeVisibleDate = useCallback((listener: () => void) => {+ visibleDateListener.current = listener+ scrollRoot?.addEventListener("scroll", listener)+ return () => {+ if (visibleDateListener.current === listener) visibleDateListener.current = undefined+ scrollRoot?.removeEventListener("scroll", listener)+ }+ }, [scrollRoot])+ const getVisibleDate = useCallback(() => {+ const items = virtualizer.getVirtualItems()+ const offset = (virtualizer.scrollOffset ?? 0) + DAY_DIVIDER_HEIGHT+ const item = items.find(row => row.end - (dateAfter[row.index] ? DAY_DIVIDER_HEIGHT : 0) > offset)+ ?? items.at(-1)+ return chronological[item?.index ?? 0]?.createdAt ?? ""+ }, [virtualizer, dateAfter, chronological])+ const visibleDate = useSyncExternalStore(subscribeVisibleDate, getVisibleDate, getVisibleDate)const virtualItems = virtualizer.getVirtualItems()- const range = virtualizer.range- const paginationItems = useMemo(() => {- if (!range) return []- const indexes = new Set(defaultRangeExtractor({ ...range, count: rows.length, overscan: virtualizer.options.overscan }))- return virtualItems.filter(item => indexes.has(item.index))- }, [range, rows.length, virtualItems, virtualizer])- const paginationVirtualizer = useMemo(() => ({ getVirtualItems: () => paginationItems }), [paginationItems])const loadOlder = useCallback(() => {void fetchNextPage({ cancelRefetch: false })}, [fetchNextPage])useVirtualCursorPagination({- virtualizer: paginationVirtualizer,- count: rows.length,+ virtualizer,+ count: chronological.length,enabled: open && initialized && Boolean(scrollRoot?.clientHeight),hasMore: hasNextPage,isFetching: isFetching || isFetchingNextPage,@@ -162,34 +166,36 @@ export function BotActivityModal({) : undefined}contentTestId={tid.botActivityModal}bodyRef={setLogBody}- bodyClassName="bg-background p-0 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:outline-none"+ bodyClassName="bg-background p-0 [overflow-anchor:none] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:outline-none">{isLoading && chronological.length === 0 ? (<SkeletonRows />) : chronological.length === 0 ? (<EmptyState />) : (- <div style={{ height: virtualizer.getTotalSize(), position: "relative", width: "100%" }}>- {virtualizer.getVirtualItems().map((virtualRow) => {- const row = rows[virtualRow.index]- const sticky = row.kind === "date" && virtualRow.index === activeStickyIndexRef.current+ <div ref={virtualizer.containerRef} style={{ position: "relative", width: "100%" }}>+ <div className="sticky top-0 z-10" data-activity-sticky-date={dayKey(visibleDate)}>+ <DayDivider date={visibleDate} />+ </div>+ {virtualItems.map((virtualRow) => {+ const event = chronological[virtualRow.index]+ const nextDate = dateAfter[virtualRow.index]return (<divkey={virtualRow.key}ref={virtualizer.measureElement}data-index={virtualRow.index}- data-activity-row-key={row.key}- data-activity-event-id={row.kind === "event" ? row.event.id : undefined}+ data-activity-row-key={virtualRow.key}+ data-activity-event-id={event.id}style={{- position: sticky ? "sticky" : "absolute",+ position: "absolute",top: 0,left: 0,width: "100%",- zIndex: row.kind === "date" ? 10 : undefined,- transform: sticky ? undefined : `translateY(${virtualRow.start}px)`,}}>- {row.kind === "event" ? <BotActivityRow event={row.event} /> : <DayDivider label={row.label} />}+ <BotActivityRow event={event} />+ {nextDate && <DayDivider date={nextDate} />}</div>)})}@@ -199,11 +205,15 @@ export function BotActivityModal({)}-function DayDivider({ label }: { label: string }) {+function DayDivider({ date }: { date: string }) {return (- <div className="border-b border-border/40 bg-background/95 px-4 py-1 backdrop-blur supports-backdrop-filter:bg-background/80">+ <div+ data-activity-date={dayKey(date)}+ className="border-b border-border/40 bg-background/95 px-4 py-1 backdrop-blur supports-backdrop-filter:bg-background/80"+ style={{ height: DAY_DIVIDER_HEIGHT }}+ ><span className="font-mono text-[10px] font-medium uppercase tracking-wider text-muted-foreground">- {label}+ {formatDayLabel(date)}</span></div>)@@ -237,25 +247,6 @@ function EmptyState() {)}-type ActivityRow =- | { kind: "date"; key: string; label: string }- | { kind: "event"; key: string; event: AuditEvent }--function flattenActivityRows(events: AuditEvent[], botId: string): ActivityRow[] {- if (events.length === 0) return []- const rows: ActivityRow[] = []- let previousDay: string | undefined- for (const event of events) {- const key = dayKey(event.createdAt)- if (key !== previousDay) {- rows.push({ kind: "date", key: `${botId}:date:${key}`, label: formatDayLabel(event.createdAt) })- previousDay = key- }- rows.push({ kind: "event", key: `${botId}:event:${event.id}`, event })- }- return rows-}-function dayKey(iso: string): string {const d = new Date(iso)return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.tsindex e3f6550fc..4c34f02c3 100644--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts@@ -252,44 +252,51 @@ async function waitForDialogEntrance(page: Page) {await lightbox.evaluate((element, ids) => {const dialog = element.closest<HTMLElement>("[data-slot='dialog-content']")if (!dialog) throw new Error("lightbox dialog content disappeared")- return Promise.all(dialog.getAnimations().map((animation) => animation.finished))- .then(() => new Promise<void>((resolveStable, rejectStable) => {- let previous = ""- let unchangedFrames = 0- let observedFrames = 0- const sample = () => {- const container = document.querySelector<HTMLElement>(`[data-testid="${ids.container}"]`)- if (!container) {- rejectStable(new Error("lightbox container disappeared"))- return- }- // The failed-original state intentionally unmounts the original- // image. Sample whichever image layers currently exist; each test- // phase separately asserts its required layer before measuring.- const nodes = [- container,- document.querySelector<HTMLElement>(`[data-testid="${ids.thumbnail}"]`),- document.querySelector<HTMLElement>(`[data-testid="${ids.original}"]`),- ].filter((node): node is HTMLElement => node !== null)- const current = nodes.map((node) => {- const rect = node.getBoundingClientRect()- return [rect.x, rect.y, rect.width, rect.height].join(":")- }).join("|")- unchangedFrames = current === previous ? unchangedFrames + 1 : 0- previous = current- observedFrames += 1- if (unchangedFrames >= 1) {- resolveStable()- return- }- if (observedFrames >= 120) {- rejectStable(new Error("lightbox geometry did not stabilize within 120 animation frames"))- return- }- requestAnimationFrame(sample)+ return new Promise<void>((resolveStable, rejectStable) => {+ let previous = ""+ let unchangedFrames = 0+ let observedFrames = 0+ const sample = () => {+ if (!dialog.isConnected) {+ rejectStable(new Error("lightbox dialog content disappeared"))+ return+ }+ const container = document.querySelector<HTMLElement>(`[data-testid="${ids.container}"]`)+ if (!container) {+ rejectStable(new Error("lightbox container disappeared"))+ return+ }+ // The failed-original state intentionally unmounts the original+ // image. Sample whichever image layers currently exist; each test+ // phase separately asserts its required layer before measuring.+ const nodes = [+ container,+ document.querySelector<HTMLElement>(`[data-testid="${ids.thumbnail}"]`),+ document.querySelector<HTMLElement>(`[data-testid="${ids.original}"]`),+ ].filter((node): node is HTMLElement => node !== null)+ const current = nodes.map((node) => {+ const rect = node.getBoundingClientRect()+ return [rect.x, rect.y, rect.width, rect.height].join(":")+ }).join("|")+ const animating = dialog.getAnimations({ subtree: true }).some((animation) => (+ Number.isFinite(animation.effect?.getComputedTiming().endTime)+ && (animation.pending || animation.playState === "running" || animation.playState === "paused")+ ))+ unchangedFrames = !animating && current === previous ? unchangedFrames + 1 : 0+ previous = animating ? "" : current+ observedFrames += 1+ if (unchangedFrames >= 1) {+ resolveStable()+ return+ }+ if (observedFrames >= 120) {+ rejectStable(new Error("lightbox geometry did not stabilize within 120 animation frames"))+ return}requestAnimationFrame(sample)- }))+ }+ requestAnimationFrame(sample)+ })}, {container: tid.imageLightbox,thumbnail: tid.imageLightboxThumbnail,diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.tsindex c47ec350e..16df5df59 100644--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts@@ -1,6 +1,6 @@import { createRequire } from "module"import { resolve } from "path"-import type { Locator, Page, TestInfo } from "@playwright/test"+import type { Locator, Page, Route, TestInfo, WebSocket as BrowserSocket } from "@playwright/test"import { test, expect } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"@@ -906,8 +906,10 @@ let caseJourneyFailure2Present = falseawait expect(sticker).toContainText(`Long marked task ${suffix}`)await expect(sticker).not.toContainText("**Long marked task")await expect(sticker.locator("time")).toHaveCount(3)- await expect(sticker.locator("p").filter({ hasText: `Long marked task ${suffix}` }))- .toHaveCSS("-webkit-line-clamp", "2")+ const markedMessageBody = sticker.locator("p").filter({ hasText: `Long marked task ${suffix}` })+ await expect(markedMessageBody).toHaveText(`Long marked task ${suffix} ${"with enough detail to require a second line ".repeat(5).trim()}`)+ await expect(markedMessageBody.locator('[data-streamdown="strong"]')).toHaveText(`Long marked task ${suffix}`)+ await expect(markedMessageBody).toHaveCSS("-webkit-line-clamp", "none")expect(ownerMarkRequests.length).toBeGreaterThan(0)machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "running" }))const stop = alice.page.getByTestId(tid.botMarkStickerStop)@@ -959,7 +961,7 @@ let caseJourneyFailure2Present = false.toHaveCount(3)await attachPageScreenshot(testInfo, "bot-mark-sticker-marks-mobile-dark", alice.page)await sticker.getByRole("tab", { name: "Thoughts" }).click()- await sticker.getByRole("button", { name: "Open activity log 11", exact: true }).click()+ await sticker.getByText("Open activity log 11", { exact: true }).click()await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}`))await gotoAfterUserWsAuth(alice.page, route)await openBotProfile(alice.page, botName)@@ -986,10 +988,7 @@ let caseJourneyFailure2Present = false"data-placement",/^(right|left|top|bottom)$/,)- const openActivity = sticker.getByRole("button", {- name: "Open activity log 11",- exact: true,- })+ const openActivity = auditRows.filter({ hasText: "Open activity log 11" }).getByTitle("Open full audit log")await openActivity.focus()await expect(openActivity).toBeFocused()await openActivity.press("Enter")@@ -1115,3 +1114,480 @@ test("CommunitySheet footers keep four consumers horizontal and intrinsic at 390await expectFooterGeometry(page, fileName, ["Download"], width)}})++type ActivityAnchorPage = {+ events: Array<{ id: string; createdAt: string }>+ nextCursor: { beforeCreatedAt: string; beforeId: string } | null+}++async function activityAnchorSnapshot(scroller: Locator) {+ return scroller.evaluate(element => {+ const root = element.getBoundingClientRect()+ return {+ scrollTop: element.scrollTop,+ scrollHeight: element.scrollHeight,+ clientHeight: element.clientHeight,+ overflowAnchor: getComputedStyle(element).overflowAnchor,+ events: [...element.querySelectorAll<HTMLElement>("[data-activity-event-id]")].flatMap(wrapper => {+ const body = wrapper.firstElementChild+ if (!(body instanceof HTMLElement)) return []+ const rect = body.getBoundingClientRect()+ return [{ id: wrapper.dataset.activityEventId!, top: rect.top - root.top, bottom: rect.bottom - root.top, height: rect.height }]+ }),+ }+ })+}++async function settleActivityPosition(scroller: Locator, target: number) {+ return scroller.evaluate(async (element, target) => {+ const samples: Array<{ scrollTop: number; scrollHeight: number; clientHeight: number; events: Array<{ id: string; top: number; bottom: number }> }> = []+ let previous = ""+ let stableFrames = 0+ for (let frame = 0; frame < 120; frame += 1) {+ await new Promise<void>(resolveFrame => requestAnimationFrame(() => resolveFrame()))+ if (!element.isConnected) return { settled: false, samples }+ const root = element.getBoundingClientRect()+ const sample = {+ scrollTop: element.scrollTop,+ scrollHeight: element.scrollHeight,+ clientHeight: element.clientHeight,+ events: [...element.querySelectorAll<HTMLElement>("[data-activity-event-id]")].flatMap(wrapper => {+ const body = wrapper.firstElementChild+ if (!(body instanceof HTMLElement)) return []+ const rect = body.getBoundingClientRect()+ return [{ id: wrapper.dataset.activityEventId!, top: rect.top - root.top, bottom: rect.bottom - root.top }]+ }),+ }+ samples.push(sample)+ const signature = JSON.stringify(sample)+ stableFrames = Math.abs(sample.scrollTop - target) <= 1 && sample.events.length > 0 && signature === previous ? stableFrames + 1 : 0+ if (stableFrames === 2) return { settled: true, samples }+ previous = signature+ }+ return { settled: false, samples }+ }, target)+}++async function gateOlderActivityPages(page: Page, botId: string, caseResources: CaseResources) {+ const entries: Array<{ url: string; release: (status?: 503) => void }> = []+ const running = new Set<Promise<void>>()+ let closing = false+ const matches = (url: URL) => url.pathname === `/api/community/bots/${botId}/audit-log`+ const handler = (route: Route) => {+ const url = new URL(route.request().url())+ if (!url.searchParams.has("beforeId")) return route.continue()+ if (closing) return route.abort("failed")+ let release!: (status?: 503) => void+ const ready = new Promise<503 | undefined>(resolveGate => { release = resolveGate })+ const operation = (async () => {+ const status = await ready+ if (page.isClosed()) return+ if (closing) await route.abort("failed")+ else if (status) await route.fulfill({ status, contentType: "application/json", body: JSON.stringify({ error: "Injected Activity older-page failure" }) })+ else await route.continue()+ })()+ entries.push({ url: url.toString(), release })+ running.add(operation)+ return operation.finally(() => running.delete(operation))+ }+ const owned = caseResources.own(entries, async () => {+ closing = true+ for (const entry of entries) entry.release()+ await Promise.all(running)+ if (!page.isClosed()) await page.unroute(matches, handler)+ })+ await page.route(matches, handler)+ return { entries, close: () => owned.close() }+}++type ActivityJsonRequest = Awaited<ReturnType<typeof prepareCase>>["jsonRequest"]++async function seedActivityHistory({ machine, botId, suffix, scenario, caseResources, jsonRequest, testInfo }: {+ machine: ReturnType<typeof connectMachine>+ botId: string+ suffix: string+ scenario: "same-day" | "cross-day"+ caseResources: CaseResources+ jsonRequest: ActivityJsonRequest+ testInfo: TestInfo+}) {+ const now = new Date()+ const start = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 5, 12)+ const history = Array.from({ length: 200 }, (_, index) => ({+ id: `bae_anchor_${suffix}_${String(index).padStart(3, "0")}`,+ createdAt: new Date(start + (scenario === "cross-day" ? Math.floor(index / 60) * 86_400_000 + index % 60 * 1_000 : index * 1_000)).toISOString(),+ }))+ const acknowledged = new Set<string>()+ const acknowledgements: Array<{ type: string; eventId: string }> = []+ const expectedIds = new Set(history.map(event => event.id))+ const onMessage = (raw: unknown) => {+ const frame = JSON.parse(String(raw)) as { type?: string; eventId?: string }+ if (frame.type === "bot_audit_event_ack" && frame.eventId && expectedIds.has(frame.eventId)) {+ acknowledged.add(frame.eventId)+ acknowledgements.push({ type: frame.type, eventId: frame.eventId })+ }+ }+ const listener = caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })+ machine.socket.on("message", onMessage)+ for (const event of history) machine.socket.send(JSON.stringify({+ type: "bot_audit_event",+ eventId: event.id,+ occurredAt: event.createdAt,+ agentId: botId,+ sessionId: `anchor-session-${suffix}`,+ launchId: `anchor-launch-${suffix}`,+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },+ }))+ await expect.poll(() => acknowledged.size, { timeout: 30_000 }).toBe(history.length)+ await listener.close()+ const headPath = `/api/community/bots/${botId}/audit-log?limit=50`+ const head = await jsonRequest<ActivityAnchorPage>("alice", headPath)+ await testInfo.attach("activity-history-backend", {+ body: JSON.stringify({ botId, scenario, history, acknowledgements, headPath, head }),+ contentType: "application/json",+ })+ expect(head.events.map(event => ({ id: event.id, createdAt: event.createdAt }))).toEqual(history.slice(-50).reverse())+ expect(head.nextCursor).toEqual({ beforeCreatedAt: history[150].createdAt, beforeId: history[150].id })+ return history+}++function observeActivityFrames(page: Page, caseResources: CaseResources) {+ const frames: Array<{ id: string; botId: string; createdAt: string }> = []+ const onSocket = (socket: BrowserSocket) => {+ const onFrame = ({ payload }: { payload: string | Buffer }) => {+ let frame: { type?: string; id?: string; botId?: string; createdAt?: string }+ try { frame = JSON.parse(String(payload)) } catch { return }+ if (frame.type === "community:bot.audit_event" && frame.id && frame.botId && frame.createdAt) {+ frames.push({ id: frame.id, botId: frame.botId, createdAt: frame.createdAt })+ }+ }+ socket.on("framereceived", onFrame)+ caseResources.own(socket, async captured => { captured.off("framereceived", onFrame) })+ }+ page.on("websocket", onSocket)+ caseResources.own(onSocket, async captured => { page.off("websocket", captured) })+ return frames+}++async function publishActivityReset({ machine, botId, suffix, id, createdAt, frames, caseResources, jsonRequest, testInfo }: {+ machine: ReturnType<typeof connectMachine>+ botId: string+ suffix: string+ id: string+ createdAt: string+ frames: ReturnType<typeof observeActivityFrames>+ caseResources: CaseResources+ jsonRequest: ActivityJsonRequest+ testInfo: TestInfo+}) {+ let acknowledged = false+ const onMessage = (raw: unknown) => {+ const frame = JSON.parse(String(raw)) as { type?: string; eventId?: string }+ if (frame.type === "bot_audit_event_ack" && frame.eventId === id) acknowledged = true+ }+ const listener = caseResources.own(onMessage, async captured => { machine.socket.off("message", captured) })+ machine.socket.on("message", onMessage)+ machine.socket.send(JSON.stringify({+ type: "bot_audit_event", eventId: id, occurredAt: createdAt, agentId: botId,+ sessionId: `anchor-session-${suffix}`, launchId: `anchor-launch-${suffix}`,+ event: { kind: "session_reset", payload: { trigger: "idle_timeout" } },+ }))+ await expect.poll(() => acknowledged).toBe(true)+ await listener.close()+ await expect.poll(() => frames.some(frame => frame.id === id && frame.botId === botId && frame.createdAt === createdAt)).toBe(true)+ const cursor = new URLSearchParams({ limit: "50", beforeCreatedAt: new Date(Date.parse(createdAt) + 1).toISOString(), beforeId: id })+ const path = `/api/community/bots/${botId}/audit-log?${cursor}`+ const persisted = await jsonRequest<ActivityAnchorPage>("alice", path)+ await testInfo.attach(`activity-live-${id}`, {+ body: JSON.stringify({ id, botId, createdAt, acknowledged, received: frames.filter(frame => frame.id === id), path, persisted }),+ contentType: "application/json",+ })+ expect(persisted.events[0]).toMatchObject({ id, createdAt })+}++async function expectActivityPosition(scroller: Locator, anchor: { id: string; top: number }) {+ await expect.poll(async () => {+ const snapshot = await activityAnchorSnapshot(scroller)+ const kept = snapshot.events.find(event => event.id === anchor.id)+ return kept ? Math.abs(kept.top - anchor.top) : Number.POSITIVE_INFINITY+ }).toBeLessThanOrEqual(1)+}++async function visibleActivityAnchor(scroller: Locator) {+ const snapshot = await activityAnchorSnapshot(scroller)+ const anchor = snapshot.events.find(event => event.top >= 32 && event.bottom <= snapshot.clientHeight)+ expect(anchor).toBeDefined()+ return anchor!+}++for (const scenario of ["same-day", "cross-day"] as const) {+ for (const width of [1280, 390] as const) {+ test(`Activity ${scenario} older pages preserve real event positions at ${width}`, async ({ caseActors, caseResources }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice"])+ const { pairMachine, createBot, jsonRequest } = await prepareCase(actors, caseResources)+ const { credential, machineId } = await pairMachine()+ const suffix = Date.now().toString(36)+ const botId = await createBot(machineId, `Anchor ${scenario} ${width} ${suffix}`)+ const machine = connectMachine(credential, caseResources)+ await machine.opened+ let gate: Awaited<ReturnType<typeof gateOlderActivityPages>> | undefined+ let journeyFailure: unknown+ let journeyFailurePresent = false+ const positioning: Array<{ page: number; target: number; deltaY: number; olderRequests: string[] } & Awaited<ReturnType<typeof settleActivityPosition>>> = []+ try {+ const history = await seedActivityHistory({ machine, botId, suffix, scenario, caseResources, jsonRequest, testInfo })+ const { page } = await actors.asUser("alice", { viewport: { width, height: 900 }, colorScheme: width === 390 ? "dark" : "light" })+ gate = await gateOlderActivityPages(page, botId, caseResources)+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ const sheet = page.getByTestId(tid.botActivityModal)+ await settleSheet(sheet)+ const scroller = sheet.getByRole("region", { name: "Activity log", exact: true })+ await expect(scroller).toHaveCount(1)+ await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ for (const [index, target] of [0, 80].entries()) {+ await scroller.hover()+ await page.mouse.wheel(0, -1_000_000)+ const zeroPosition = await settleActivityPosition(scroller, 0)+ positioning.push({ page: index + 1, target: 0, deltaY: -1_000_000, olderRequests: gate.entries.map(entry => entry.url), ...zeroPosition })+ expect(zeroPosition.settled, "physical zero and rendered geometry settle before choosing the reading position").toBe(true)+ if (target > 0) {+ await page.mouse.wheel(0, target)+ const nearTopPosition = await settleActivityPosition(scroller, target)+ positioning.push({ page: index + 1, target, deltaY: target, olderRequests: gate.entries.map(entry => entry.url), ...nearTopPosition })+ expect(nearTopPosition.settled, "physical near-top target and rendered geometry settle without another wheel").toBe(true)+ }+ await expect.poll(async () => Math.abs(await scroller.evaluate(element => element.scrollTop) - target)).toBeLessThanOrEqual(1)+ await expect.poll(() => gate!.entries.length).toBe(index + 1)+ const pending = gate.entries[index]+ const cursor = history[150 - index * 50]+ const url = new URL(pending.url)+ expect(url.searchParams.get("limit")).toBe("50")+ expect(url.searchParams.get("beforeId")).toBe(cursor.id)+ expect(url.searchParams.get("beforeCreatedAt")).toBe(cursor.createdAt)+ const before = await activityAnchorSnapshot(scroller)+ expect(Math.abs(before.scrollTop - target), "physical target at retained snapshot").toBeLessThanOrEqual(1)+ expect(before.overflowAnchor).toBe("none")+ const anchor = before.events.find(event => event.top >= 32 && event.bottom <= before.clientHeight)+ expect(anchor).toBeDefined()+ await attachPageScreenshot(testInfo, `activity-anchor-${scenario}-${width}-before-page-${index + 1}`, page)+ const atRelease = await activityAnchorSnapshot(scroller)+ expect(Math.abs(atRelease.scrollTop - target), "physical target at response release").toBeLessThanOrEqual(1)+ const releaseAnchor = atRelease.events.find(event => event.id === anchor!.id)+ expect(releaseAnchor).toBeDefined()+ expect(Math.abs(releaseAnchor!.top - anchor!.top), "named event at response release").toBeLessThanOrEqual(1)+ const [response] = await Promise.all([+ page.waitForResponse(value => value.url() === pending.url && value.request().method() === "GET"),+ Promise.resolve().then(() => pending.release()),+ ])+ expect(response.status()).toBe(200)+ const body = await response.json() as ActivityAnchorPage+ expect(body.events.map(event => ({ id: event.id, createdAt: event.createdAt })))+ .toEqual(history.slice(100 - index * 50, 150 - index * 50).reverse())+ expect(body.nextCursor).not.toBeNull()+ await expect.poll(() => scroller.evaluate(element => element.scrollHeight)).toBeGreaterThan(before.scrollHeight + 300)+ try {+ await expect.poll(async () => {+ const after = await activityAnchorSnapshot(scroller)+ const kept = after.events.find(event => event.id === anchor!.id)+ return kept ? Math.abs(kept.top - anchor!.top) : Number.POSITIVE_INFINITY+ }).toBeLessThanOrEqual(1)+ await scroller.evaluate(() => new Promise<void>(resolveFrame => {+ requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolveFrame())))+ }))+ await expectActivityPosition(scroller, anchor!)+ expect(gate.entries).toHaveLength(index + 1)+ } finally {+ await testInfo.attach(`activity-anchor-${scenario}-${width}-page-${index + 1}`, {+ body: JSON.stringify({ scenario, width, target, anchor, request: pending.url, returnedIds: body.events.map(event => event.id), before, atRelease, after: await activityAnchorSnapshot(scroller), olderRequestCount: gate.entries.length }),+ contentType: "application/json",+ })+ await attachPageScreenshot(testInfo, `activity-anchor-${scenario}-${width}-page-${index + 1}`, page)+ }+ }+ } catch (error) { journeyFailure = error; journeyFailurePresent = true; throw error } finally {+ const exitErrors: unknown[] = []+ try { await gate?.close() } catch (error) { exitErrors.push(error) }+ try { await machine.close() } catch (error) { exitErrors.push(error) }+ try {+ await testInfo.attach(`activity-anchor-${scenario}-${width}-positioning`, {+ body: JSON.stringify({ responseReleaseTargets: [0, 80], requestStartPosition: "not asserted; the gate can hold a request during the zero-position step", positioning }),+ contentType: "application/json",+ })+ } catch (error) { exitErrors.push(error) }+ if (exitErrors.length) throw new AggregateError(journeyFailurePresent ? [journeyFailure, ...exitErrors] : exitErrors, "Activity journey, cleanup or evidence retention failed")+ }+ })+ }+}++for (const width of [1280, 390] as const) {+ test(`Activity recovery, live reading and reopen preserve event ownership at ${width}`, async ({ caseActors, caseResources }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice"])+ const { pairMachine, createBot, jsonRequest } = await prepareCase(actors, caseResources)+ const suffix = Date.now().toString(36)+ const { credential, machineId } = await pairMachine()+ const botId = await createBot(machineId, `Recovery ${width} ${suffix}`)+ const machine = connectMachine(credential, caseResources)+ let gate: Awaited<ReturnType<typeof gateOlderActivityPages>> | undefined+ let journeyFailure: unknown+ let journeyFailurePresent = false+ const steps: Array<Record<string, unknown>> = []+ try {+ await machine.opened+ const history = await seedActivityHistory({ machine, botId, suffix, scenario: "same-day", caseResources, jsonRequest, testInfo })+ const { page } = await actors.asUser("alice", { viewport: { width, height: 900 }, colorScheme: width === 390 ? "dark" : "light" })+ const frames = observeActivityFrames(page, caseResources)+ gate = await gateOlderActivityPages(page, botId, caseResources)+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ const sheet = page.getByTestId(tid.botActivityModal)+ await settleSheet(sheet)+ const scroller = sheet.getByRole("region", { name: "Activity log", exact: true })+ await expect(scroller).toHaveCSS("overflow-anchor", "none")+ const record = async (phase: string) => {+ steps.push({ phase, snapshot: await activityAnchorSnapshot(scroller), olderRequests: gate!.entries.map(entry => entry.url) })+ await attachPageScreenshot(testInfo, `activity-recovery-${width}-${phase}`, page)+ }+ await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ await scroller.hover()+ await page.mouse.wheel(0, -1_000_000)+ await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBe(0)+ await expect.poll(() => gate!.entries.length).toBe(1)+ const anchor = await visibleActivityAnchor(scroller)+ const cursor = history[150]+ await record("before-error")+ for (const index of [0, 1]) {+ await expect.poll(() => gate!.entries.length).toBe(index + 1)+ const pending = gate.entries[index]+ const url = new URL(pending.url)+ expect(url.searchParams.get("beforeId")).toBe(cursor.id)+ expect(url.searchParams.get("beforeCreatedAt")).toBe(cursor.createdAt)+ const atRelease = await activityAnchorSnapshot(scroller)+ steps.push({ phase: `before-error-release-${index + 1}`, snapshot: atRelease })+ expect(atRelease.scrollTop, "physical target before injected error").toBe(0)+ const releaseAnchor = atRelease.events.find(event => event.id === anchor.id)+ expect(releaseAnchor).toBeDefined()+ expect(Math.abs(releaseAnchor!.top - anchor.top)).toBeLessThanOrEqual(1)+ const [response] = await Promise.all([+ page.waitForResponse(value => value.url() === pending.url),+ Promise.resolve().then(() => pending.release(503)),+ ])+ expect(response.status()).toBe(503)+ steps.push({ phase: `injected-error-${index + 1}`, url: pending.url, status: response.status() })+ }+ const retry = sheet.getByRole("button", { name: "Retry older", exact: true })+ await expect(retry).toBeEnabled()+ await expectActivityPosition(scroller, anchor)+ await scroller.evaluate(() => new Promise<void>(resolveFrame => {+ requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolveFrame())))+ }))+ expect(gate.entries).toHaveLength(2)+ await record("failed-and-stopped")+ await retry.click()+ await expect.poll(() => gate!.entries.length).toBe(3)+ expect(gate.entries[2].url).toBe(gate.entries[0].url)+ const beforeRecovery = await activityAnchorSnapshot(scroller)+ steps.push({ phase: "before-recovery-release", snapshot: beforeRecovery })+ expect(beforeRecovery.scrollTop, "physical target before recovery").toBe(0)+ const recoveryAnchor = beforeRecovery.events.find(event => event.id === anchor.id)+ expect(recoveryAnchor).toBeDefined()+ expect(Math.abs(recoveryAnchor!.top - anchor.top)).toBeLessThanOrEqual(1)+ const [recovered] = await Promise.all([+ page.waitForResponse(value => value.url() === gate!.entries[2].url && value.status() === 200),+ Promise.resolve().then(() => gate!.entries[2].release()),+ ])+ const recoveredBody = await recovered.json() as ActivityAnchorPage+ expect(recoveredBody.events.map(event => ({ id: event.id, createdAt: event.createdAt }))).toEqual(history.slice(100, 150).reverse())+ expect(recoveredBody.nextCursor).toEqual({ beforeCreatedAt: history[100].createdAt, beforeId: history[100].id })+ steps.push({ phase: "recovery-response", status: recovered.status(), body: recoveredBody })+ await expect.poll(() => scroller.evaluate(element => element.scrollHeight)).toBeGreaterThan(beforeRecovery.scrollHeight + 300)+ await expect(retry).toHaveCount(0)+ await expectActivityPosition(scroller, anchor)+ expect(gate.entries).toHaveLength(3)+ await record("recovered")+ const publish = (label: string, createdAt: string) => publishActivityReset({+ machine, botId, suffix, id: `bae_${label}_${suffix}`, createdAt, frames, caseResources, jsonRequest, testInfo,+ })+ const liveId = `bae_history_${suffix}`+ const liveTime = Date.parse(history[199].createdAt) + 86_400_000+ await publish("history", new Date(liveTime).toISOString())+ await expectActivityPosition(scroller, anchor)+ await expect(scroller.locator(`[data-activity-event-id="${liveId}"]`)).toHaveCount(0)+ await record("live-while-reading")+ await publish("late", new Date(Date.parse(history[140].createdAt) + 500).toISOString())+ await expectActivityPosition(scroller, anchor)+ await record("late-interleave")+ await page.setViewportSize({ width, height: 760 })+ await expectActivityPosition(scroller, anchor)+ await record("resized")+ const beforeTakeover = await scroller.evaluate(element => element.scrollTop)+ await scroller.hover()+ await page.mouse.wheel(0, 150)+ await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBeGreaterThan(beforeTakeover + 100)+ const readerAnchor = await visibleActivityAnchor(scroller)+ expect(readerAnchor.id).not.toBe(anchor.id)+ await publish("reader", new Date(liveTime + 1_000).toISOString())+ await expectActivityPosition(scroller, readerAnchor)+ await record("reader-takeover")+ await scroller.hover()+ await page.mouse.wheel(0, 1_000_000)+ await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ const tailId = `bae_tail_${suffix}`+ await publish("tail", new Date().toISOString())+ await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()+ await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ await expect(scroller.locator("[data-activity-date]").filter({ hasText: /^Today$/ }).last()).toBeVisible()+ await record("tail-follow")+ await gate.close()+ steps.push({ phase: "older-control-retired-before-navigation", requests: gate.entries.map(entry => entry.url) })+ await sheet.getByRole("button", { name: "Close", exact: true }).click()+ await expect(sheet).toHaveCount(0)+ await expect(page).toHaveURL("/c/me/bots")+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ await settleSheet(sheet)+ await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()+ await expect.poll(() => scroller.evaluate(element => element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)+ await record("reopened")+ const otherBotId = await createBot(machineId, `Other ${width} ${suffix}`)+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${otherBotId}`)+ await settleSheet(sheet)+ const otherId = `bae_other_${suffix}`+ await publishActivityReset({ machine, botId: otherBotId, suffix, id: otherId, createdAt: new Date().toISOString(), frames, caseResources, jsonRequest, testInfo })+ await expect(scroller.locator(`[data-activity-event-id="${otherId}"]`)).toBeVisible()+ await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toHaveCount(0)+ await record("other-bot")+ gate = await gateOlderActivityPages(page, botId, caseResources)+ steps.push({ phase: "pending-control-installed-before-return" })+ await gotoAfterUserWsAuth(page, `/c/me/bots?audit=${botId}`)+ await settleSheet(sheet)+ await expect(scroller.locator(`[data-activity-event-id="${tailId}"]`)).toBeVisible()+ const requestsBeforeWheel = gate.entries.length+ await scroller.hover()+ await page.mouse.wheel(0, -1_000_000)+ await expect.poll(() => gate!.entries.length).toBe(1)+ const pendingUrl = gate.entries[0].url+ const pendingSearch = new URL(pendingUrl).searchParams+ const pendingCursor = history.find(event => event.id === pendingSearch.get("beforeId"))+ expect(pendingCursor).toBeDefined()+ expect(pendingSearch.get("beforeCreatedAt")).toBe(pendingCursor!.createdAt)+ expect(pendingSearch.get("limit")).toBe("50")+ await expect(sheet).toBeVisible()+ steps.push({ phase: "owned-pending-route-ready", requestsBeforeWheel, url: pendingUrl, cursor: pendingCursor, snapshot: await activityAnchorSnapshot(scroller) })+ const failed = page.waitForEvent("requestfailed", { predicate: request => request.url() === pendingUrl })+ await gate.close()+ const aborted = await failed+ expect(aborted.failure()?.errorText).toBeTruthy()+ steps.push({ phase: "owned-pending-route-exit", url: aborted.url(), failure: aborted.failure() })+ await sheet.getByRole("button", { name: "Close", exact: true }).click()+ await expect(sheet).toHaveCount(0)+ await attachPageScreenshot(testInfo, `activity-recovery-${width}-closed`, page)+ } catch (error) { journeyFailure = error; journeyFailurePresent = true; throw error } finally {+ await testInfo.attach(`activity-recovery-${width}-steps`, { body: JSON.stringify({ width, botId, steps }), contentType: "application/json" })+ try {+ await gate?.close()+ await machine.close()+ } catch (cleanupError) { if (journeyFailurePresent) throw new AggregateError([journeyFailure, cleanupError], "Journey and resource exit both failed"); throw cleanupError }+ }+ })+}