diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index c953a409b..3317c41ca 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -43,7 +43,7 @@ export const GUIDE_TOPICS: ReadonlyArray = [ "archive", "restart", ], - body: `A thread is one conversation with an agent in a project. Threads are listed in the sidebar; one that needs you, finished or failed says so there. In a narrow window the sidebar floats over the thread instead of sitting beside it: the sidebar button at the top left, or Cmd+B (Ctrl+B on Windows and Linux), opens it, and picking a thread or clicking the thread puts it away. + body: `A thread is one conversation with an agent in a project. Threads are listed in the sidebar; one that needs you, finished or failed says so there. In a narrow window the sidebar floats over the thread instead of sitting beside it: the sidebar button at the top left, or Cmd+B (Ctrl+B on Windows and Linux), opens it, and picking a thread or clicking the thread puts it away. A thread you scrolled up in opens where you left it when you come back, until Threadlines reloads; one that finished, failed or needs you since then opens at the end. The sliders button beside the project picker at the top of the sidebar groups the list by project or computer and sorts it: recent activity, newest, oldest, title, or a custom order. In the custom order you drag rows to arrange them, or use Move up and Move down in a thread's menu, and only you move a row; new threads go to the bottom, and the same button can reset the order. Pinned threads stay above a thin line in every sort, under a project's lead chat, which comes first. When the list is grouped, drag a group's header to move the whole group, in any sort; its menu has Move up, Move down and Use automatic order. These orders are kept per device, so a phone has its own. diff --git a/apps/web/src/components/ChatView.browser-harness.tsx b/apps/web/src/components/ChatView.browser-harness.tsx index e0a93d6a9..c38510d67 100644 --- a/apps/web/src/components/ChatView.browser-harness.tsx +++ b/apps/web/src/components/ChatView.browser-harness.tsx @@ -117,6 +117,7 @@ import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test import { DEFAULT_CLIENT_SETTINGS } from "@threadlines/contracts/settings"; import { resetTestPage } from "../lib/testPage.browser-harness"; +import { forgetThreadScrollExcept } from "../threadScrollMemory"; export const THREAD_ID = "thread-browser-test" as ThreadId; export const THREAD_TITLE = "Browser test thread"; @@ -3204,6 +3205,8 @@ export async function dispatchInputKey( await waitForLayout(); } +const NO_THREADS: ReadonlySet = new Set(); + export async function mountChatView(options: { viewport: ViewportSpec; snapshot: OrchestrationReadModel; @@ -3214,6 +3217,8 @@ export async function mountChatView(options: { /** Mount under StrictMode, as main.tsx does, so mount-time effect cleanups run. */ strictMode?: boolean; }): Promise { + // Where chats were left lives for the page; each mount starts with none. + forgetThreadScrollExcept(NO_THREADS); fixture = buildFixture(options.snapshot); options.configureFixture?.(fixture); customWsRpcResolver = options.resolveRpc ?? null; @@ -3258,6 +3263,7 @@ export async function mountChatView(options: { const cleanup = async () => { customWsRpcResolver = null; await finishCleanupStep("React's unmount", screen.unmount()); + forgetThreadScrollExcept(NO_THREADS); host.remove(); await finishCleanupStep("the animation frames after unmount", waitForLayout()); }; diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index 16b332f04..d379ecc27 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -36,7 +36,7 @@ import { __setEnvironmentApiOverrideForTests, } from "../environmentApi"; import { getClientSettings, updateSettings } from "../hooks/useSettings"; -import { readAfterEachPaint } from "../lib/frameProbe.browser-harness"; +import { nextFrames, readAfterEachPaint } from "../lib/frameProbe.browser-harness"; import { isMacPlatform } from "../lib/utils"; import { useThreadSelectionStore } from "../threadSelectionStore"; import { useUiStateStore } from "../uiStateStore"; @@ -239,6 +239,130 @@ describe("ChatView (full app): sidebar", () => { } }); + // Scroll memory (threadScrollMemory): a chat left above the end opens there + // again, from its first drawn frame; left at the end, or with news, it + // opens at the end; a find target wins. + const SCROLL_OTHER_THREAD = "thread-scroll-memory-other" as ThreadId; + const mountTwoThreads = () => + mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: addThreadToSnapshot( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-scroll-memory-target" as MessageId, + targetText: "scroll memory target", + }), + SCROLL_OTHER_THREAD, + ), + }); + const chatList = () => document.querySelector('[data-chat-messages-list="true"]'); + const listAtEnd = (list: HTMLElement) => + list.scrollTop + list.clientHeight >= list.scrollHeight - 2; + const rowTop = (list: HTMLElement, rowId: string) => { + const row = list.querySelector(`[data-timeline-row-id="${rowId}"]`); + return row === null ? null : row.getBoundingClientRect().top - list.getBoundingClientRect().top; + }; + const firstRowInView = (list: HTMLElement) => { + const listTop = list.getBoundingClientRect().top; + return [...list.querySelectorAll("[data-timeline-row-id]")].find( + (row) => row.getBoundingClientRect().bottom > listTop + 24, + )?.dataset.timelineRowId; + }; + const openThread = ( + mounted: Awaited>, + threadId: ThreadId, + search?: Record, + ) => + mounted.router.navigate({ + to: "/$environmentId/$threadId", + params: { environmentId: LOCAL_ENVIRONMENT_ID, threadId }, + ...(search ? { search } : {}), + }); + /** Opens the long chat at the end, then leaves it scrolled to its middle or its end. */ + const leaveLongChat = async ( + mounted: Awaited>, + where: "middle" | "end", + ) => { + const list = await waitForElement(chatList, "The chat should show its messages."); + await vi.waitFor(() => expect(listAtEnd(list)).toBe(true), { timeout: 5_000 }); + if (where === "middle") { + // Scrolled up by the wheel, as a reader leaves the end. + for (let step = 0; step < 6; step += 1) { + list.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -300 })); + list.scrollTop -= 300; + await nextFrames(2); + } + await vi.waitFor(() => expect(listAtEnd(list)).toBe(false)); + await nextFrames(4); + } + const rowId = firstRowInView(list)!; + const top = rowTop(list, rowId)!; + await openThread(mounted, SCROLL_OTHER_THREAD); + await vi.waitFor(() => expect(document.querySelector("[data-timeline-row-id]")).toBeNull()); + return { rowId, top }; + }; + + it("opens a chat where it was left, from the first frame it draws", async () => { + const mounted = await mountTwoThreads(); + try { + const left = await leaveLongChat(mounted, "middle"); + // Every frame the long chat draws on the way back. + const frames: { top: number | null; atEnd: boolean }[] = []; + const stop = readAfterEachPaint(() => { + const list = chatList(); + if (list?.querySelector("[data-timeline-row-id]")) { + frames.push({ top: rowTop(list, left.rowId), atEnd: listAtEnd(list) }); + } + }); + await openThread(mounted, THREAD_ID); + await vi.waitFor(() => expect(frames.length).toBeGreaterThan(5), { timeout: 5_000 }); + stop(); + expect(frames.every((frame) => frame.top !== null && !frame.atEnd)).toBe(true); + expect(Math.abs(frames.at(-1)!.top! - left.top)).toBeLessThanOrEqual(2); + // Above the end, the way back down is offered as usual. + await expect.element(page.getByRole("button", { name: "Scroll to bottom" })).toBeVisible(); + } finally { + await mounted.cleanup(); + } + }); + + it("opens a chat left at its end at the end, and one with news at the end too", async () => { + const mounted = await mountTwoThreads(); + try { + await leaveLongChat(mounted, "end"); + await openThread(mounted, THREAD_ID); + await vi.waitFor(() => expect(listAtEnd(chatList()!)).toBe(true), { timeout: 5_000 }); + + // Left mid-history, then it came to need the user while away. + await leaveLongChat(mounted, "middle"); + setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, THREAD_ID, "needs-you"); + await openThread(mounted, THREAD_ID); + await vi.waitFor(() => expect(listAtEnd(chatList()!)).toBe(true), { timeout: 5_000 }); + } finally { + await mounted.cleanup(); + } + }); + + it("opens at a find target rather than where the chat was left", async () => { + const mounted = await mountTwoThreads(); + try { + await leaveLongChat(mounted, "middle"); + await openThread(mounted, THREAD_ID, { focusMessageId: "msg-user-1", focusQuery: "" }); + await vi.waitFor( + () => { + const list = chatList()!; + const top = rowTop(list, "msg-user-1"); + expect(top).not.toBeNull(); + // The target sits about a third of the way down, as find puts it. + expect(top! / list.clientHeight).toBeGreaterThan(0.1); + expect(top! / list.clientHeight).toBeLessThan(0.6); + }, + { timeout: 5_000 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("shows the project's lead chat, and its menu stops it or names another thread instead", async () => { const otherThreadId = "thread-lead-other" as ThreadId; const withThreads = addThreadToSnapshot( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index b276c2071..2f220c8a7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -153,6 +153,7 @@ import { import { selectEnvironmentState, selectProjectsAcrossEnvironments, + selectSidebarThreadSummaryByRef, selectThreadDetailLoaded, selectThreadByRef, selectThreadExistsByRef, @@ -161,6 +162,8 @@ import { useStore, } from "../store"; import { readLeadProjectName } from "../leadChat"; +import { threadHasNewsForUser } from "./Sidebar.logic"; +import { readThreadScroll } from "../threadScrollMemory"; import { FamilyTabs, useFamilyTabsShown } from "./chat/FamilyTabs"; import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; import { useUiStateStore } from "../uiStateStore"; @@ -1210,6 +1213,19 @@ export default function ChatView(props: ChatViewProps) { ? selectThreadSeenAt(store, routeThreadKey, serverThread?.lastSeenAt) : undefined, ); + // Something new to show in this thread, read before opening it marks it + // seen: then its chat opens at the end, not where it was left. + const activeThreadHasNews = useStore((store) => { + if (routeKind !== "server") return false; + const summary = selectSidebarThreadSummaryByRef(store, routeThreadRef); + return summary !== undefined && threadHasNewsForUser(summary, activeThreadSeenAt); + }); + // Held stable: the timeline is memoized, and reads this only when it mounts. + const timelineScrollMemory = useMemo( + () => + routeKind === "server" ? { threadKey: routeThreadKey, hasNews: activeThreadHasNews } : null, + [activeThreadHasNews, routeKind, routeThreadKey], + ); const settings = useSettings(); const { updateSettings } = useUpdateSettings(); const suppressCrossProviderWarning = settings.suppressCrossProviderSwitchWarning ?? false; @@ -4944,7 +4960,14 @@ export default function ChatView(props: ChatViewProps) { const isThreadEntry = layoutStickThreadIdRef.current !== activeThreadId; layoutStickThreadIdRef.current = activeThreadId; if (!activeThreadId) return; - if (isThreadEntry && timelineSearchTargetRef.current) return; + // Opening at a find target, or where the chat was left (the timeline read + // and kept or dropped that place as it rendered): not at the end. + if ( + isThreadEntry && + (timelineSearchTargetRef.current || readThreadScroll(routeThreadKey) !== null) + ) { + return; + } if (!isAtEndRef.current && !isLegendListVisiblyAtEnd(legendListRef.current)) { return; } @@ -4978,6 +5001,7 @@ export default function ChatView(props: ChatViewProps) { infrastructureComposerNotices.length, providerSendPreflight, providerStatusNoticeVisible, + routeThreadKey, terminalState.terminalHeight, terminalState.terminalOpen, threadErrorNoticeVisible, @@ -9020,6 +9044,7 @@ export default function ChatView(props: ChatViewProps) { mcpAuthReconnectStatusByServerName={activeMcpAuthReconnectStatusByServerName} onRunMcpAuthReconnect={runMcpAuthReconnect} onIsAtEndChange={onIsAtEndChange} + scrollMemory={timelineScrollMemory} onVisibleTurnIdsChange={handleVisibleTurnIdsChange} searchTarget={timelineSearchTarget} planScrollTarget={planScrollTarget} diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 6904b1b8b..3b592ca18 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -16,6 +16,7 @@ import { THREAD_STATUS_DOT_CLASSES, resolveSeenThreadStatus, resolveThreadStatusPill, + threadHasNewsForUser, shouldClearThreadSelectionOnMouseDown, sortProjectsForSidebar, THREAD_JUMP_HINT_SHOW_DELAY_MS, @@ -389,6 +390,40 @@ describe("isContextMenuPointerDown", () => { }); }); +describe("threadHasNewsForUser", () => { + const failed = { + hasActionableProposedPlan: false, + hasPendingApprovals: false, + hasPendingUserInput: false, + interactionMode: "default" as const, + latestTurn: null, + session: { + provider: ProviderDriverKind.make("codex"), + status: "error" as const, + createdAt: "2026-03-09T10:00:00.000Z", + updatedAt: "2026-03-09T11:00:00.000Z", + orchestrationStatus: "error" as const, + pendingBackgroundTaskCount: 0, + }, + }; + + it("counts a failure until it is seen, and a question while it waits", () => { + expect(threadHasNewsForUser(failed, "2026-03-09T10:30:00.000Z")).toBe(true); + // Seen since it failed: the chat may open where it was left. + expect(threadHasNewsForUser(failed, "2026-03-09T11:30:00.000Z")).toBe(false); + expect( + threadHasNewsForUser( + { + ...failed, + hasPendingUserInput: true, + session: { ...failed.session, status: "running", orchestrationStatus: "running" }, + }, + "2026-03-09T11:30:00.000Z", + ), + ).toBe(true); + }); +}); + describe("resolveThreadStatusPill", () => { const baseThread = { hasActionableProposedPlan: false, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 56efa585e..93a0f2dcc 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -481,6 +481,26 @@ export function isNeedsUserStatus(status: ThreadStatusPill | null): boolean { return status !== null && NEEDS_USER_STATUSES.has(status.label); } +/** + * Whether opening the thread now shows the user something new: an answer or a + * failure they haven't seen since `seenAt`, or an approval or question waiting + * on them (a failure already seen is not news). The + * chat then opens at the end, not where it was left (threadScrollMemory), + * since opening it marks it seen. + */ +export function threadHasNewsForUser( + thread: ThreadStatusInput, + seenAt: string | null | undefined, +): boolean { + return ( + hasUnseenCompletionSince(thread, seenAt) || + hasUnseenSessionFailureSince(thread, seenAt) || + isWaitingOnUserStatus( + resolveThreadStatusPill({ thread: { ...thread, lastVisitedAt: undefined } }), + ) + ); +} + /** * The single word a row spends on status. Only states that stop the agent and * hand the thread back earn one; in-flight work reads as "working" with its @@ -1718,9 +1738,14 @@ const NEEDS_YOU_NOW: ReadonlySet = new Set([ "Awaiting Input", ]); +/** An approval or a question waits on the user (a failure, seen or not, is not one). */ +export function isWaitingOnUserStatus(status: ThreadStatusPill | null): boolean { + return status !== null && NEEDS_YOU_NOW.has(status.label); +} + /** A child that is waiting on the user's answer: never folded out of sight. */ export function isChildThreadNeedingYou(entry: InboxFamilyStatus): boolean { - return !entry.isDone && entry.status !== null && NEEDS_YOU_NOW.has(entry.status.label); + return !entry.isDone && isWaitingOnUserStatus(entry.status); } const IN_FLIGHT: ReadonlySet = new Set([ diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 153306a04..782472a5f 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -155,6 +155,14 @@ import { type ThreadStartCall, } from "../../childThreads"; import { selectEnvironmentState, useStore } from "../../store"; +import { + anchorFromListPlace, + forgetThreadScroll, + type InitialScroll, + initialScrollForThread, + readThreadScroll, + rememberThreadScroll, +} from "../../threadScrollMemory"; import { remoteChildStanding, remoteChildStatusText, @@ -842,6 +850,13 @@ interface MessagesTimelineProps { mcpAuthReconnectStatusByServerName?: ReadonlyMap; onRunMcpAuthReconnect?: (action: McpAuthReconnectAction) => void; onIsAtEndChange: (isAtEnd: boolean) => void; + /** + * Remember where this chat was left and open it there next time + * (threadScrollMemory). `hasNews`: the thread has something new to show + * the user, so it opens at the end and its place is dropped. Absent: no + * memory (drafts). + */ + scrollMemory?: { readonly threadKey: string; readonly hasNews: boolean } | null | undefined; /** The turns on screen and a few rows past either edge, reported as the * reader scrolls; the chat fetches older turns' steps from it. */ onVisibleTurnIdsChange?: ((turnIds: ReadonlyArray) => void) | undefined; @@ -943,6 +958,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ mcpAuthReconnectStatusByServerName = EMPTY_MCP_AUTH_RECONNECT_STATUS, onRunMcpAuthReconnect: onRunMcpAuthReconnectProp, onIsAtEndChange, + scrollMemory = null, onVisibleTurnIdsChange, searchTarget = null, planScrollTarget = null, @@ -1174,7 +1190,31 @@ export const MessagesTimeline = memo(function MessagesTimeline({ : -1, [rows, searchTarget], ); - const initialAutoStickToBottom = searchTargetRowIndex < 0; + // Where this chat opens (threadScrollMemory), decided as it mounts, before + // opening it marks the thread seen. Something new to show drops the place. + const [opensAtRememberedPlace] = useState(() => { + if (scrollMemory === null) return false; + if (scrollMemory.hasNews) { + forgetThreadScroll(scrollMemory.threadKey); + return false; + } + return readThreadScroll(scrollMemory.threadKey) !== null; + }); + // The remembered row, found once the rows are here; only the list's first + // mount opens there (a later remount is the end following itself). + const [rememberedScroll, setRememberedScroll] = useState(null); + if (opensAtRememberedPlace && rememberedScroll === null && rows.length > 0) { + setRememberedScroll( + initialScrollForThread({ + threadKey: scrollMemory!.threadKey, + hasNews: false, + indexOfRowKey: (rowKey) => rows.findIndex((row) => row.id === rowKey), + }), + ); + } + const initialAnchor = + searchTargetRowIndex < 0 && rememberedScroll?.kind === "anchor" ? rememberedScroll : null; + const initialAutoStickToBottom = searchTargetRowIndex < 0 && !opensAtRememberedPlace; const [autoStickToBottom, setAutoStickToBottom] = useState(initialAutoStickToBottom); const autoStickToBottomRef = useRef(initialAutoStickToBottom); const upwardScrollDetectorRef = useRef(createUpwardScrollDetector()); @@ -1183,6 +1223,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({ null, ); const [legendListEpoch, setLegendListEpoch] = useState(0); + // Where the list opens on this mount: a remembered row, or (null) the end + // or a find target. A rebuilt list (a later epoch) opens at the end. + const openingAnchor = legendListEpoch === 0 ? initialAnchor : null; + const opensAtAnchor = openingAnchor !== null; const lastHandledStickToBottomRequestKeyRef = useRef(stickToBottomRequestKey); const previousActiveTurnInProgressRef = useRef(activeTurnInProgress); const userScrollLockTimerRef = useRef(null); @@ -1226,6 +1270,51 @@ export const MessagesTimeline = memo(function MessagesTimeline({ return estimateTimelineRowHeight(row, timelineWidthRef.current); }, []); + // The remembered row was gone: the chat opens at the end, following it. + useLayoutEffect(() => { + if (rememberedScroll?.kind === "end" && searchTargetRowIndex < 0) { + setAutoStickToBottomState(true); + } + }, [rememberedScroll, searchTargetRowIndex, setAutoStickToBottomState]); + + // Where the chat was when it is left, read once from the list then: the + // anchor, or nothing at the end. Nothing is written while scrolling. + const scrollMemoryKey = scrollMemory?.threadKey ?? null; + useLayoutEffect(() => { + if (scrollMemoryKey === null) return; + return () => { + // Runs once, when the timeline is left. The list is read then, not + // when this ran: a pinned list is rebuilt when a turn settles, and an + // emptied chat has none. Layout cleanups run before the list leaves + // the page, so its rows are still drawn. The offset is read from the + // screen, not from the list's positions, which leave out its header + // and padding. + const list = listRef.current; + const state = list?.getState?.(); + const node = list?.getScrollableNode?.(); + if (!state || !(node instanceof HTMLElement)) { + forgetThreadScroll(scrollMemoryKey); + return; + } + const firstRowKey = (state.data[state.start] as MessagesTimelineRow | undefined)?.id; + const rowElement = + firstRowKey === undefined + ? null + : node.querySelector(`[data-timeline-row-id="${CSS.escape(firstRowKey)}"]`); + rememberThreadScroll( + scrollMemoryKey, + anchorFromListPlace({ + isAtEnd: state.isAtEnd, + firstRowKey, + viewTopBelowRowTop: + rowElement === null + ? undefined + : node.getBoundingClientRect().top - rowElement.getBoundingClientRect().top, + }), + ); + }; + }, [listRef, scrollMemoryKey]); + const assignLegendListRef = useCallback( (instance: LegendListRef | null) => { listRef.current = instance; @@ -1799,7 +1888,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ ]); useEffect(() => { - if (!legendListReady || !hasRows || searchTargetRowIndex >= 0) { + if (!legendListReady || !hasRows || searchTargetRowIndex >= 0 || opensAtAnchor) { return; } @@ -1811,6 +1900,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ hasRows, legendListEpoch, legendListReady, + opensAtAnchor, routeThreadKey, searchTargetRowIndex, stickToBottomUnlessHeld, @@ -2121,10 +2211,17 @@ export const MessagesTimeline = memo(function MessagesTimeline({ renderItem={renderItem} estimatedItemSize={90} getEstimatedItemSize={getEstimatedItemSize} - initialScrollAtEnd={searchTargetRowIndex < 0} + initialScrollAtEnd={searchTargetRowIndex < 0 && !opensAtAnchor} {...(searchTargetRowIndex >= 0 ? { initialScrollIndex: { index: searchTargetRowIndex, viewPosition: 0.35 } } - : {})} + : openingAnchor !== null + ? { + initialScrollIndex: { + index: openingAnchor.index, + viewOffset: -openingAnchor.offsetPx, + }, + } + : {})} maintainScrollAtEnd={ searchTargetRowIndex < 0 && ((autoStickToBottom && !listHeld) || stickToBottomRequestPending) diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index d3d6d9272..061fa8474 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -121,6 +121,7 @@ import { deriveLogicalProjectKeyFromSettings, derivePhysicalProjectKey, } from "../../logicalProject"; +import { forgetThreadScroll, forgetThreadScrollExcept } from "../../threadScrollMemory"; import { getClientSettings } from "~/hooks/useSettings"; import { useOptimisticThreadMessagesStore } from "~/optimisticThreadMessages"; @@ -1235,6 +1236,7 @@ function reconcileSnapshotDerivedState() { draftThreadKeys: useComposerDraftStore.getState().listDraftThreadKeys(), }); useTerminalStateStore.getState().removeOrphanedTerminalStates(activeThreadKeys); + forgetThreadScrollExcept(activeThreadKeys); } /** @@ -1323,7 +1325,9 @@ function applyRecoveredEventBatch( } } for (const threadId of batchEffects.removeTerminalStateThreadIds) { - useTerminalStateStore.getState().removeTerminalState(scopeThreadRef(environmentId, threadId)); + const threadRef = scopeThreadRef(environmentId, threadId); + useTerminalStateStore.getState().removeTerminalState(threadRef); + forgetThreadScroll(scopedThreadKey(threadRef)); } threadDetails.reconcileEvictionForEnvironment(environmentId); @@ -1433,6 +1437,7 @@ function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: En threadDetails.warmNonIdle(environmentId, [event.thread]); if (previousThread?.archivedAt === null && event.thread.archivedAt !== null && threadRef) { useTerminalStateStore.getState().removeTerminalState(threadRef); + forgetThreadScroll(scopedThreadKey(threadRef)); } // The shell carries every thread, including ones with no detail stream // open, so a server-held merge that ends off screen is seen here too. @@ -1456,6 +1461,7 @@ function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: En useComposerDraftStore.getState().clearDraftThread(threadRef); useUiStateStore.getState().clearThreadUi(scopedThreadKey(threadRef)); useTerminalStateStore.getState().removeTerminalState(threadRef); + forgetThreadScroll(scopedThreadKey(threadRef)); } syncThreadUiFromStore(); return; diff --git a/apps/web/src/threadScrollMemory.test.ts b/apps/web/src/threadScrollMemory.test.ts new file mode 100644 index 000000000..2be7bcaf0 --- /dev/null +++ b/apps/web/src/threadScrollMemory.test.ts @@ -0,0 +1,66 @@ +import { afterEach, describe, expect, it } from "vite-plus/test"; + +import { + THREAD_SCROLL_MEMORY_LIMIT, + anchorFromListPlace, + forgetThreadScroll, + initialScrollForThread, + readThreadScroll, + rememberThreadScroll, +} from "./threadScrollMemory"; + +const used = new Set(); +const remember = (key: string, rowKey = "row-1", offsetPx = 40) => { + used.add(key); + rememberThreadScroll(key, { rowKey, offsetPx }); +}; + +afterEach(() => { + for (const key of used) forgetThreadScroll(key); + used.clear(); +}); + +describe("threadScrollMemory", () => { + it("keeps the most recently left threads, dropping the one left longest ago", () => { + for (let index = 0; index < THREAD_SCROLL_MEMORY_LIMIT; index += 1) { + remember(`thread-${index}`); + } + // Left again, thread-0 is now the newest. + remember("thread-0"); + remember("thread-new"); + + expect(readThreadScroll("thread-0")).not.toBeNull(); + expect(readThreadScroll("thread-1")).toBeNull(); + expect(readThreadScroll("thread-new")).not.toBeNull(); + }); + + it("forgets a chat left at its end", () => { + remember("thread-a"); + const place = { firstRowKey: "row-9", viewTopBelowRowTop: 12 }; + rememberThreadScroll("thread-a", anchorFromListPlace({ ...place, isAtEnd: true })); + expect(readThreadScroll("thread-a")).toBeNull(); + + rememberThreadScroll("thread-a", anchorFromListPlace({ ...place, isAtEnd: false })); + expect(readThreadScroll("thread-a")).toEqual({ rowKey: "row-9", offsetPx: 12 }); + }); + + it("opens at the remembered row, or at the end when there is news or the row is gone", () => { + const indexOfRowKey = (rowKey: string) => ["row-0", "row-1", "row-2"].indexOf(rowKey); + + remember("thread-a", "row-2", 30); + expect( + initialScrollForThread({ threadKey: "thread-a", hasNews: false, indexOfRowKey }), + ).toEqual({ kind: "anchor", index: 2, offsetPx: 30 }); + + expect(initialScrollForThread({ threadKey: "thread-a", hasNews: true, indexOfRowKey })).toEqual( + { kind: "end" }, + ); + expect(readThreadScroll("thread-a")).toBeNull(); + + remember("thread-b", "row-reverted"); + expect( + initialScrollForThread({ threadKey: "thread-b", hasNews: false, indexOfRowKey }), + ).toEqual({ kind: "end" }); + expect(readThreadScroll("thread-b")).toBeNull(); + }); +}); diff --git a/apps/web/src/threadScrollMemory.ts b/apps/web/src/threadScrollMemory.ts new file mode 100644 index 000000000..0a06cb26a --- /dev/null +++ b/apps/web/src/threadScrollMemory.ts @@ -0,0 +1,108 @@ +/** + * Where each thread's chat was scrolled to when it was left, so coming back + * (by tab, sidebar, palette, back or forward) opens it there instead of at + * the end. In memory only, per window: a reload opens every chat at the end. + * + * What is kept is an anchor, not a pixel offset: the key of the row at the + * top of the view and how far into that row the view starts. The chat is a + * virtualized list whose rows change height and grow, so a raw scroll + * position would land somewhere else. + * + * The timeline reads the anchor once when it mounts and writes it once when + * it is left; nothing here runs while scrolling. + */ + +/** The row at the top of the view, and how far into it the view starts. */ +export interface ScrollAnchor { + readonly rowKey: string; + readonly offsetPx: number; +} + +/** Threads remembered at once; the one left longest ago goes first. */ +export const THREAD_SCROLL_MEMORY_LIMIT = 300; + +// Insertion order is recency: a write moves the thread to the end. +const anchors = new Map(); + +/** + * Keeps where `threadKey` was left, or forgets it (null): a chat left at the + * end is not remembered, so it opens at the end and follows new output. + */ +export function rememberThreadScroll(threadKey: string, anchor: ScrollAnchor | null): void { + anchors.delete(threadKey); + if (anchor === null) return; + anchors.set(threadKey, anchor); + while (anchors.size > THREAD_SCROLL_MEMORY_LIMIT) { + const oldest = anchors.keys().next().value; + if (oldest === undefined) break; + anchors.delete(oldest); + } +} + +/** Where `threadKey` was left, if it was left above the end. */ +export function readThreadScroll(threadKey: string): ScrollAnchor | null { + return anchors.get(threadKey) ?? null; +} + +export function forgetThreadScroll(threadKey: string): void { + anchors.delete(threadKey); +} + +/** + * Keeps only the threads in `activeThreadKeys`: after a full thread list + * arrives (a reconnect), threads archived or deleted meanwhile are forgotten. + */ +export function forgetThreadScrollExcept(activeThreadKeys: ReadonlySet): void { + for (const threadKey of anchors.keys()) { + if (!activeThreadKeys.has(threadKey)) anchors.delete(threadKey); + } +} + +/** Where a list is, as the anchor is read from it. */ +export interface ListPlace { + /** The list is at its end (LegendList's own `isAtEnd`). */ + readonly isAtEnd: boolean; + /** The key of the first row in view; undefined when there is none. */ + readonly firstRowKey: string | undefined; + /** + * How far the top of the view is below that row's top, in pixels, as drawn + * on screen; undefined when the row is not drawn. + */ + readonly viewTopBelowRowTop: number | undefined; +} + +/** The anchor a list's place amounts to; null at the end or when it can't be read. */ +export function anchorFromListPlace(place: ListPlace): ScrollAnchor | null { + if (place.isAtEnd || place.firstRowKey === undefined) return null; + const offset = place.viewTopBelowRowTop; + if (offset === undefined || !Number.isFinite(offset)) return null; + return { rowKey: place.firstRowKey, offsetPx: Math.max(0, Math.round(offset)) }; +} + +/** How a chat opens: at the end (following it), or at a remembered row. */ +export type InitialScroll = + | { readonly kind: "end" } + | { readonly kind: "anchor"; readonly index: number; readonly offsetPx: number }; + +/** + * Where a chat opens when it is opened. A find target is handled before + * this. The end, and the anchor forgotten, when: + * - nothing was remembered (it was left at the end, or never left); + * - the thread has something new to show (`hasNews`: an unseen completion or + * failure, or a status that needs the user), since opening it marks it seen; + * - the remembered row is gone (a revert, a rewrite). + */ +export function initialScrollForThread(input: { + readonly threadKey: string; + readonly hasNews: boolean; + readonly indexOfRowKey: (rowKey: string) => number; +}): InitialScroll { + const anchor = readThreadScroll(input.threadKey); + if (anchor === null) return { kind: "end" }; + const index = input.hasNews ? -1 : input.indexOfRowKey(anchor.rowKey); + if (index < 0) { + forgetThreadScroll(input.threadKey); + return { kind: "end" }; + } + return { kind: "anchor", index, offsetPx: anchor.offsetPx }; +} diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md index 336d5b031..1e914bdc8 100644 --- a/docs/design/lead-chat.md +++ b/docs/design/lead-chat.md @@ -128,8 +128,9 @@ Words below are the on-screen words. Copy follows the repo's copy rules (no em d A thread that started other threads, and each thread it started, show one row of tabs under the chat header: the parent first, then its threads. Clicking a tab opens that -thread, the same full chat as today with its own message box, scroll position and -draft. The point is that the user never loses their place: the lead (or any parent) is +thread, the same full chat as today with its own message box and draft. It opens +where it was left (see scroll memory in `apps/web/src/threadScrollMemory.ts`), or at the +end when it was left there or has news. The point is that the user never loses their place: the lead (or any parent) is always one click away, and so is every thread it started. - **Which threads.** Exactly the members the sidebar shows for that parent's open