:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): paginate cloud transcripts with on-demand history (#82988)
Charles Vien3d0d6679cbe3
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.tsindex 1b6aff898246..e9cf38793c7d 100644--- a/products/desktop/packages/api-client/src/posthog-client.test.ts+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts@@ -2222,6 +2222,22 @@ describe("PostHogAPIClient", () => {).toBeInstanceOf(AbortSignal);});+ it("reports a null matching count when the header is absent", async () => {+ const fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => makeEntries(10, "a"),+ headers: new Headers({ "X-Has-More": "true" }),+ });+ const client = makeClient(fetch);++ const result = await client.getTaskRunSessionLogsPage("task-1", "run-1", {+ limit: 10,+ });++ expect(result.matchingCount).toBeNull();+ expect(result.hasMore).toBe(true);+ });+it("does not retry a definite client error", async () => {const fetch = vi.fn().mockRejectedValue(new ApiRequestError(404, "{}"));const client = makeClient(fetch);diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 904484adc745..d0689209cca5 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -230,6 +230,12 @@ type SessionLogsPage =| { ok: true; entries: StoredLogEntry[]; headers: Headers }| { ok: false; status: number; statusText: string };+export interface TaskRunSessionLogsPage {+ entries: StoredLogEntry[];+ hasMore: boolean;+ matchingCount: number | null;+}+export interface TaskListOptions {repository?: string;createdBy?: number;@@ -3734,6 +3740,45 @@ export class PostHogAPIClient {}}+ async getTaskRunSessionLogsPage(+ taskId: string,+ runId: string,+ options: { limit: number; offset?: number; after?: string },+ ): Promise<TaskRunSessionLogsPage> {+ const teamId = await this.getTeamId();+ const path = `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/session_logs/`;+ const url = new URL(`${this.api.baseUrl}${path}`);+ url.searchParams.set("limit", String(options.limit));+ if (options.offset) {+ url.searchParams.set("offset", String(options.offset));+ }+ if (options.after) {+ url.searchParams.set("after", options.after);+ }+ const page = await this.fetchSessionLogsPage(+ url,+ path,+ options.offset ?? 0,+ );+ if (!page.ok) {+ throw new Error(+ `Failed to fetch session logs page at offset ${options.offset ?? 0}: ${page.status} ${page.statusText}`,+ );+ }+ // Number(null) is 0, so an absent header must stay null.+ const matchingHeader = page.headers.get("X-Matching-Count");+ const matchingCount =+ matchingHeader === null ? null : Number(matchingHeader);+ return {+ entries: page.entries,+ hasMore: page.headers.get("X-Has-More") === "true",+ matchingCount:+ matchingCount !== null && Number.isFinite(matchingCount)+ ? matchingCount+ : null,+ };+ }+async getTaskRunSessionLogsResult(taskId: string,runId: string,@@ -3743,46 +3788,28 @@ export class PostHogAPIClient {const entries: StoredLogEntry[] = [];let truncatedHeadCount = 0;try {- const teamId = await this.getTeamId();- const path = `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/session_logs/`;let offset = 0;let isFirstPage = true;while (entries.length < maxEntries) {- const url = new URL(`${this.api.baseUrl}${path}`);- url.searchParams.set(- "limit",- String(- Math.min(SESSION_LOGS_MAX_PAGE_SIZE, maxEntries - entries.length),+ const page = await this.getTaskRunSessionLogsPage(taskId, runId, {+ limit: Math.min(+ SESSION_LOGS_MAX_PAGE_SIZE,+ maxEntries - entries.length,),- );- if (offset > 0) {- url.searchParams.set("offset", String(offset));- }- if (options?.after) {- url.searchParams.set("after", options.after);- }- const page = await this.fetchSessionLogsPage(url, path, offset);-- if (!page.ok) {- log.warn(- `Failed to fetch session logs page at offset ${offset}: ${page.status} ${page.statusText}`,- );- return { entries, complete: false, truncatedHeadCount };- }-+ offset,+ after: options?.after,+ });if (isFirstPage) {isFirstPage = false;- const matchingCount = Number(page.headers.get("X-Matching-Count"));- if (Number.isFinite(matchingCount) && matchingCount > maxEntries) {+ if (page.matchingCount !== null && page.matchingCount > maxEntries) {// Restart from the tail so the newest maxEntries survive the cap.- truncatedHeadCount = matchingCount - maxEntries;+ truncatedHeadCount = page.matchingCount - maxEntries;offset = truncatedHeadCount;continue;}}entries.push(...page.entries);- const hasMore = page.headers.get("X-Has-More") === "true";- if (!hasMore || page.entries.length === 0) {+ if (!page.hasMore || page.entries.length === 0) {return { entries, complete: true, truncatedHeadCount };}offset += page.entries.length;diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex cb56f8737a5d..12253645b9a4 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -10,10 +10,12 @@ import type {SessionUpdate,} from "@agentclientprotocol/sdk";import { requestErrorStatus } from "@posthog/api-client/fetcher";-import type {- CreateResourceCommentRequest,- ResourceComment,- TaskRunSessionLogsResult,+import {+ type CreateResourceCommentRequest,+ type PostHogAPIClient,+ type ResourceComment,+ SESSION_LOGS_MAX_PAGE_SIZE,+ type TaskRunSessionLogsResult,} from "@posthog/api-client/posthog-client";import {type AcpMessage,@@ -224,6 +226,27 @@ interface CloudHydrationResult {liveStreamLineCount: number;}+const CLOUD_HYDRATION_MAX_ENTRIES = 100_000;++/** Entries the first paint of a big transcript renders; the rest pages in on scroll. */+const INITIAL_TAIL_WINDOW = 2000;++/** How long hydration waits for auth to finish restoring before giving up. */+const AUTH_RESTORE_WAIT_MS = 30_000;+const AUTH_RESTORE_POLL_MS = 250;++interface ChainTranscriptWindow {+ entries: StoredLogEntry[];+ /** Absolute index in the chain log of `entries[0]`. */+ windowStart: number;+ chainTotal: number;+}++type SessionLogsClient = Pick<+ PostHogAPIClient,+ "getTaskRunSessionLogsPage" | "getTaskRunSessionLogsResult"+>;+interface CloudTaskWatcher {runId: string;apiHost: string;@@ -1688,6 +1711,7 @@ export class SessionService {private silenceCheckHandle: ReturnType<typeof setInterval> | null = null;/** Active cloud task watchers, keyed by taskId */private cloudTaskWatchers = new Map<string, CloudTaskWatcher>();+ private olderTranscriptLoads = new Set<string>();private cloudLogGapReconciler: CloudLogGapReconciler;/** Maps toolCallId → cloud requestId for routing permission responses */private cloudPermissionRequestIds = new Map<string, string>();@@ -6431,6 +6455,9 @@ export class SessionService {if (existing) {return existing;}+ if (hydrationMode === "terminal-chain") {+ this.d.store.updateSession(taskRunId, { isHydratingTranscript: true });+ }const hydration = this.performCloudTaskSessionHydration(taskId,taskRunId,@@ -6451,6 +6478,14 @@ export class SessionService {if (this.cloudHydrationPromises.get(hydrationKey) === hydration) {this.cloudHydrationPromises.delete(hydrationKey);}+ if (+ hydrationMode === "terminal-chain" &&+ this.d.store.getSessions()[taskRunId]+ ) {+ this.d.store.updateSession(taskRunId, {+ isHydratingTranscript: false,+ });+ }});return hydration;}@@ -6522,6 +6557,153 @@ export class SessionService {}}+ /**+ * A one-entry probe learns the chain total without downloading a page an+ * oversized log would throw away, then only the newest+ * INITIAL_TAIL_WINDOW entries are fetched; older pages load on scroll.+ * Null on failure.+ */+ private async fetchChainTranscriptWindow(+ client: SessionLogsClient,+ taskId: string,+ taskRunId: string,+ ): Promise<ChainTranscriptWindow | null> {+ try {+ const probe = await client.getTaskRunSessionLogsPage(taskId, taskRunId, {+ limit: 1,+ });+ if (!probe.hasMore) {+ return {+ entries: probe.entries,+ windowStart: 0,+ chainTotal: probe.entries.length,+ };+ }+ if (probe.matchingCount === null) {+ const result = await client.getTaskRunSessionLogsResult(+ taskId,+ taskRunId,+ { limit: CLOUD_HYDRATION_MAX_ENTRIES },+ );+ if (!result.complete) return null;+ return {+ entries: result.entries,+ windowStart: result.truncatedHeadCount,+ chainTotal: result.truncatedHeadCount + result.entries.length,+ };+ }+ const tailStart = Math.max(0, probe.matchingCount - INITIAL_TAIL_WINDOW);+ const tail: StoredLogEntry[] = [];+ let offset = tailStart;+ // The probe's count is a snapshot, and a run whose log is still being+ // persisted grows behind it. Following the server's own end-of-log signal+ // as well keeps those newest entries from going missing until a restart —+ // older-history paging only moves backward, so nothing else recovers them.+ let chainEnd = probe.matchingCount;+ while (offset < chainEnd && tail.length < CLOUD_HYDRATION_MAX_ENTRIES) {+ const page = await client.getTaskRunSessionLogsPage(taskId, taskRunId, {+ limit: Math.min(SESSION_LOGS_MAX_PAGE_SIZE, chainEnd - offset),+ offset,+ });+ if (page.entries.length === 0) break;+ tail.push(...page.entries);+ offset += page.entries.length;+ if (page.matchingCount !== null && page.matchingCount > chainEnd) {+ chainEnd = page.matchingCount;+ } else if (offset >= chainEnd && page.hasMore) {+ chainEnd = offset + SESSION_LOGS_MAX_PAGE_SIZE;+ }+ }+ const chainTotal = tailStart + tail.length;+ if (tailStart > 0) {+ this.d.log.info("Hydrating cloud transcript tail window", {+ taskId,+ taskRunId,+ windowStart: tailStart,+ chainTotal,+ });+ }+ return {+ entries: tail,+ windowStart: tailStart,+ chainTotal,+ };+ } catch (error) {+ this.d.log.warn("Cloud transcript window fetch failed", {+ taskId,+ taskRunId,+ error,+ });+ return null;+ }+ }++ /**+ * Prepend the page of chain history just above the hydrated window.+ * Driven by the thread scrolling near the top; one page per call.+ */+ async loadOlderCloudTranscript(taskId: string): Promise<void> {+ const session = this.d.store.getSessionByTaskId(taskId);+ if (!session?.isCloud) return;+ const taskRunId = session.taskRunId;+ const windowStart = session.transcriptWindowStart ?? 0;+ if (windowStart <= 0 || this.olderTranscriptLoads.has(taskRunId)) return;+ this.olderTranscriptLoads.add(taskRunId);+ this.d.store.updateSession(taskRunId, { isLoadingOlderTranscript: true });+ try {+ const authStatus = await this.getAuthCredentialsStatus();+ if (authStatus.kind !== "ready") return;++ const pageStart = Math.max(0, windowStart - SESSION_LOGS_MAX_PAGE_SIZE);+ const older: StoredLogEntry[] = [];+ let offset = pageStart;+ while (offset < windowStart) {+ const page = await authStatus.auth.client.getTaskRunSessionLogsPage(+ taskId,+ taskRunId,+ {+ limit: Math.min(SESSION_LOGS_MAX_PAGE_SIZE, windowStart - offset),+ offset,+ },+ );+ if (page.entries.length === 0) break;+ older.push(...page.entries.slice(0, windowStart - offset));+ offset += page.entries.length;+ }+ if (older.length === 0) return;++ const current = this.d.store.getSessionByTaskId(taskId);+ if (!current || current.taskRunId !== taskRunId) return;+ if ((current.transcriptWindowStart ?? 0) !== windowStart) return;++ const olderEvents = convertStoredEntriesToEvents(older);+ this.d.store.updateSession(taskRunId, {+ events: [...olderEvents, ...current.events],+ transcriptWindowStart: windowStart - older.length,+ });+ this.d.log.info("Older cloud transcript page loaded", {+ taskId,+ taskRunId,+ pageStart,+ loadedCount: older.length,+ });+ } catch (error) {+ this.d.log.warn("Older cloud transcript page load failed", {+ taskId,+ taskRunId,+ windowStart,+ error,+ });+ } finally {+ this.olderTranscriptLoads.delete(taskRunId);+ if (this.d.store.getSessions()[taskRunId]) {+ this.d.store.updateSession(taskRunId, {+ isLoadingOlderTranscript: false,+ });+ }+ }+ }+private async performCloudTaskSessionHydration(taskId: string,taskRunId: string,@@ -6533,9 +6715,11 @@ export class SessionService {let rawEntries: StoredLogEntry[];let liveStreamLineCount: number;let resumeLeafEntryStartIndex: number | undefined;- // How many entries the tail fetch dropped off the front of rawEntries. The- // stream cursors count from the start of the chain, and the engine's own- // totals still include those entries, so they have to be added back.+ let transcriptWindow: ChainTranscriptWindow | null = null;+ // How many entries a capped fetch dropped off the front of rawEntries on+ // paths that produce no window. The stream cursors count from the start of+ // the chain, and the engine's own totals still include those entries, so+ // they have to be added back.let truncatedHeadCount = 0;const resumeFromRunId =typeof runState?.resume_from_run_id === "string"@@ -6548,19 +6732,25 @@ export class SessionService {// active; otherwise a renderer restart hydrates only the final run.// Non-resume in-progress runs keep using the single-run log so hydrate// cannot race the live stream and double the active turn.- const authStatus = await this.getAuthCredentialsStatus();+ // Boot reaches here while auth is still restoring; bailing would leave+ // the thread blank until something happens to re-trigger hydration.+ const authStatus = await this.awaitAuthCredentialsSettled();if (authStatus.kind !== "ready") {+ this.d.log.warn("Cloud session hydration skipped without credentials", {+ taskId,+ taskRunId,+ auth: authStatus.kind,+ });return;}if (resumeFromRunId) {if (isTerminalStatus(runStatus)) {- const result =- await authStatus.auth.client.getTaskRunSessionLogsResult(- taskId,- taskRunId,- { limit: 100000 },- );- if (!result.complete) {+ const window = await this.fetchChainTranscriptWindow(+ authStatus.auth.client,+ taskId,+ taskRunId,+ );+ if (!window) {this.d.log.warn("Resume session log hydration was incomplete", {taskId,taskRunId,@@ -6568,9 +6758,8 @@ export class SessionService {});return;}- this.logHydrationTruncation(taskId, taskRunId, result);- rawEntries = result.entries;- truncatedHeadCount = result.truncatedHeadCount;+ transcriptWindow = window;+ rawEntries = window.entries;const markedLeafStart = rawEntries.findIndex((entry) => getEntryTaskRunMarker(entry) === taskRunId,);@@ -6585,12 +6774,12 @@ export class SessionService {authStatus.auth.client.getTaskRunSessionLogsResult(taskId,resumeFromRunId,- { limit: 100000 },+ { limit: CLOUD_HYDRATION_MAX_ENTRIES },),authStatus.auth.client.getTaskRunSessionLogsResult(taskId,taskRunId,- { limit: 100000 },+ { limit: CLOUD_HYDRATION_MAX_ENTRIES },),]);if (!ancestorResult.complete || !currentRunResult.complete) {@@ -6636,28 +6825,28 @@ export class SessionService {);}} else {- const result = await authStatus.auth.client.getTaskRunSessionLogsResult(+ const window = await this.fetchChainTranscriptWindow(+ authStatus.auth.client,taskId,taskRunId,- { limit: 100000 },);- if (!result.complete) {+ if (!window) {this.d.log.warn("Session log hydration was incomplete", {taskId,taskRunId,});return;}- this.logHydrationTruncation(taskId, taskRunId, result);- rawEntries = result.entries;- truncatedHeadCount = result.truncatedHeadCount;- liveStreamLineCount = rawEntries.length;+ transcriptWindow = window;+ rawEntries = window.entries;+ liveStreamLineCount = window.chainTotal;// A terminal run whose persisted chain comes back empty can still// have a complete S3 session log (persistence raced teardown); fall// back to it rather than hydrating an empty final transcript.if (rawEntries.length === 0 && logUrl) {const parsed = await this.fetchSessionLogs(logUrl, taskRunId);if (parsed.rawEntries.length > 0) {+ transcriptWindow = null;rawEntries = parsed.rawEntries;truncatedHeadCount = 0;liveStreamLineCount = parsed.totalLineCount;@@ -6675,11 +6864,26 @@ export class SessionService {return;}- let events = convertStoredEntriesToEvents(rawEntries, undefined, {- taskRunId,- startEntryIndex: 0,- firstPositionedEntryIndex: resumeLeafEntryStartIndex,- });+ const chainTotal =+ transcriptWindow?.chainTotal ?? rawEntries.length + truncatedHeadCount;+ const windowStart = transcriptWindow?.windowStart ?? 0;+ // Resume positions are leaf-relative; windowed single runs offset by the+ // window start. A truncated resume window that lost its leaf marker stays+ // unpositioned rather than mislabeled from index 0.+ const positionOptions = isResumeRun+ ? windowStart === 0 || resumeLeafEntryStartIndex !== undefined+ ? {+ taskRunId,+ startEntryIndex: 0,+ firstPositionedEntryIndex: resumeLeafEntryStartIndex,+ }+ : undefined+ : { taskRunId, startEntryIndex: windowStart };+ let events = convertStoredEntriesToEvents(+ rawEntries,+ undefined,+ positionOptions,+ );if (isResumeRun && session.events.length > 0) {const inheritedEvents = reconcileLiveEventsWithHydratedEvents(session.events,@@ -6740,12 +6944,11 @@ export class SessionService {};}- const chainEntryCount = rawEntries.length + truncatedHeadCount;// If live updates already populated a processed count, don't overwrite// that newer state with the persisted baseline fetched during startup.// Terminal hydration is different: it is the final transcript, so apply// it whenever the persisted chain has more lines than the local stream.- const effectiveLineCount = Math.max(liveStreamLineCount, chainEntryCount);+ const effectiveLineCount = Math.max(liveStreamLineCount, chainTotal);const alreadyApplied = isTerminalRun? (session.processedLineCount ?? 0) >= effectiveLineCount: session.processedLineCount !== undefined &&@@ -6755,7 +6958,7 @@ export class SessionService {this.surfacePersistedPendingPermissions(taskRunId, rawEntries);this.pendingPermissionHydratedRuns.add(taskRunId);return {- historyEntryCount: chainEntryCount,+ historyEntryCount: chainTotal,liveStreamLineCount: session.processedLineCount ?? liveStreamLineCount,};}@@ -6773,7 +6976,8 @@ export class SessionService {events,isCloud: true,logUrl: logUrl ?? session.logUrl,- cloudTranscriptEntryCount: chainEntryCount,+ cloudTranscriptEntryCount: chainTotal,+ transcriptWindowStart: windowStart,// Terminal hydration records the whole chain as processed so nothing// re-applies it; live resume runs keep the leaf-stream cursor.processedLineCount: isTerminalRun@@ -6790,7 +6994,7 @@ export class SessionService {this.clearTerminalCloudPromptState(taskRunId);}return {- historyEntryCount: chainEntryCount,+ historyEntryCount: chainTotal,liveStreamLineCount,};}@@ -8077,6 +8281,19 @@ export class SessionService {}}+ /** Poll auth out of its boot-time "restoring" state, bounded so a broken+ * restore can't hold callers forever. */+ private async awaitAuthCredentialsSettled(): Promise<AuthCredentialsStatus> {+ const deadline = Date.now() + AUTH_RESTORE_WAIT_MS;+ for (;;) {+ const status = await this.getAuthCredentialsStatus();+ if (status.kind !== "restoring" || Date.now() >= deadline) return status;+ await new Promise<void>((resolve) =>+ setTimeout(resolve, AUTH_RESTORE_POLL_MS),+ );+ }+ }+private async getAuthCredentialsStatus(): Promise<AuthCredentialsStatus> {const authState = await this.d.fetchAuthState();// `bootstrapComplete === false` also covers the pre-initialize window where@@ -8275,11 +8492,16 @@ export class SessionService {this.d.store.clearTailOptimisticItems(taskRunId);}this.cloudRunIdleTracker.delete(taskRunId);+ // The reconciled log is the complete chain, so any hydration window is+ // gone; resetting the window start also trips loadOlderCloudTranscript's+ // stale-window guard if a prepend was in flight, instead of duplicating+ // entries the reconcile already committed.this.d.store.updateSession(taskRunId, {events,isCloud: true,logUrl,processedLineCount,+ transcriptWindowStart: 0,});this.updatePromptStateFromEvents(taskRunId, events);}diff --git a/products/desktop/packages/core/src/sessions/sessionStore.ts b/products/desktop/packages/core/src/sessions/sessionStore.tsindex ddb1aff9f7f9..90bbda9957de 100644--- a/products/desktop/packages/core/src/sessions/sessionStore.ts+++ b/products/desktop/packages/core/src/sessions/sessionStore.ts@@ -145,6 +145,7 @@ export const sessionStoreSetters = {if (session && session.events.length > 0) {session.events = [];session.processedLineCount = 0;+ session.transcriptWindowStart = 0;}});},@@ -152,6 +153,10 @@ export const sessionStoreSetters = {/*** Replace a session's transcript in place (rehydration after eviction),* preserving its live status/config. No-op if the session is gone.+ *+ * The restore reads a whole log rather than a window, so it also retires any+ * paging index: left behind, it would offer to prepend chain entries the+ * restored transcript already holds.*/restoreEvents: (taskRunId: string,@@ -164,6 +169,7 @@ export const sessionStoreSetters = {for (const event of events) Object.freeze(event);session.events = events;session.processedLineCount = lineCount;+ session.transcriptWindowStart = 0;}});},diff --git a/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts b/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.tsindex da27d09f9c41..ff04eccb72fc 100644--- a/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts@@ -51,6 +51,26 @@ describe("evictEvents / restoreEvents", () => {expect(Object.isFrozen(s.events[0])).toBe(true);});+ it.each([+ ["evictEvents", () => sessionStoreSetters.evictEvents(RUN)],+ [+ "restoreEvents",+ () =>+ sessionStoreSetters.restoreEvents(+ RUN,+ [{ ts: 2, message: {} } as unknown as AcpMessage],+ 7,+ ),+ ],+ ])("%s retires the older-history paging index", (_name, transition) => {+ seedWithEvents();+ sessionStoreSetters.updateSession(RUN, { transcriptWindowStart: 10_000 });++ transition();++ expect(sessionStore.getState().sessions[RUN].transcriptWindowStart).toBe(0);+ });+it("appendEvents and replaceOptimisticWithEvent freeze each stored event", () => {seedWithEvents();sessionStoreSetters.replaceOptimisticWithEvent(RUN, {diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts b/products/desktop/packages/core/src/sessions/sessionViewState.test.tsindex 1e218fe246da..a6a685fddb6a 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.test.ts@@ -71,6 +71,26 @@ describe("deriveSessionViewState", () => {expect(state.isCloudRunNotTerminal).toBe(true);});+ it.each([+ { isHydratingTranscript: true, expected: true },+ { isHydratingTranscript: undefined, expected: false },+ ])(+ "shows an empty terminal thread as initializing only while its transcript hydrates (hydrating: $isHydratingTranscript)",+ ({ isHydratingTranscript, expected }) => {+ const session = makeSession("completed");+ session.isHydratingTranscript = isHydratingTranscript;++ const state = deriveSessionViewState(+ session,+ makeTask("completed"),+ null,+ true,+ );++ expect(state.isInitializing).toBe(expected);+ },+ );+it("treats not_started as a non-terminal cloud state", () => {const state = deriveSessionViewState(undefined,diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.ts b/products/desktop/packages/core/src/sessions/sessionViewState.tsindex a41c356550e6..26c5b5e4c2eb 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.ts@@ -51,8 +51,12 @@ export function deriveSessionViewState(const isNewSessionWithInitialPrompt =!task.latest_run?.id && !!task.description;const isResumingExistingSession = !!task.latest_run?.id;+ const isHydratingEmptyTranscript =+ isCloud && events.length === 0 && (session?.isHydratingTranscript ?? false);const isInitializing = isCloud- ? !hasError && (!session || (events.length === 0 && isCloudRunNotTerminal))+ ? isHydratingEmptyTranscript ||+ (!hasError &&+ (!session || (events.length === 0 && isCloudRunNotTerminal))): !session ||(session.status === "connecting" && events.length === 0) ||(session.status === "connected" &&diff --git a/products/desktop/packages/shared/src/sessions.ts b/products/desktop/packages/shared/src/sessions.tsindex dbf6449db6bd..8d5933a29e66 100644--- a/products/desktop/packages/shared/src/sessions.ts+++ b/products/desktop/packages/shared/src/sessions.ts@@ -65,6 +65,11 @@ export interface AgentSession {logUrl?: string;/** Full cloud transcript entry count across the resume chain. */cloudTranscriptEntryCount?: number;+ /** Absolute chain index of the first hydrated entry; >0 while older history is not loaded. */+ transcriptWindowStart?: number;+ isLoadingOlderTranscript?: boolean;+ /** True while the terminal transcript is being fetched, so an empty thread shows as loading. */+ isHydratingTranscript?: boolean;/** Leaf-run cursor used to reconcile live cloud log updates. */processedLineCount?: number;framework?: "claude";diff --git a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsxindex 76acb6f94114..d2f74705ddb9 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx@@ -99,6 +99,10 @@ export interface ConversationViewProps {* plain Up/Down presses (caret at the input boundary) to it.*/promptRecallRef?: RefObject<PromptRecallHandler | null>;+ /** See `SharedChatThreadProps.olderHistoryCursor`. */+ olderHistoryCursor?: number;+ isLoadingOlderHistory?: boolean;+ onLoadOlderHistory?: () => void;}export function ConversationView({diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsxindex b0a674c5bf8a..a11263ec2792 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx@@ -258,6 +258,17 @@ export function SessionView({const currentModeId = modeOption?.currentValue;const handoffInProgress = useSessionHandoffInProgress(taskId);const showInlineBanner = hasError && errorRetryable && events.length > 0;+ const olderHistoryCursor = useSessionSelector(taskId, (session) =>+ isCloud ? (session?.transcriptWindowStart ?? 0) : 0,+ );+ const isLoadingOlderHistory = useSessionSelector(+ taskId,+ (session) => session?.isLoadingOlderTranscript ?? false,+ );+ const handleLoadOlderHistory = useCallback(() => {+ if (!taskId) return;+ void sessionService.loadOlderCloudTranscript(taskId);+ }, [sessionService, taskId]);useEffect(() => {if (!taskId) return;@@ -724,6 +735,9 @@ export function SessionView({compact={compact}scrollX={false}promptRecallRef={promptRecallRef}+ olderHistoryCursor={olderHistoryCursor}+ isLoadingOlderHistory={isLoadingOlderHistory}+ onLoadOlderHistory={handleLoadOlderHistory}/><PlanStatusBar plan={latestPlan} />diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.tsindex a30dec595b65..be3387b905d5 100644--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts@@ -215,6 +215,31 @@ describe("buildConversationItems", () => {]);});+ it("keeps item ids stable when older history is prepended", () => {+ const older: AcpMessage[] = [+ userPromptMsg(1, 1, "first question"),+ agentMessageMsg(2, "first reply"),+ promptResponseMsg(3, 1),+ userPromptMsg(4, 2, "second question"),+ agentMessageMsg(5, "second reply"),+ promptResponseMsg(6, 2),+ ];+ const tail: AcpMessage[] = [+ userPromptMsg(10, 3, "later question"),+ agentMessageMsg(11, "later reply"),+ consoleMsg(12, "later tool output"),+ promptResponseMsg(13, 3),+ ];++ const tailIds = buildConversationItems(tail, null).items.map((i) => i.id);+ const fullIds = buildConversationItems([...older, ...tail], null).items.map(+ (i) => i.id,+ );++ expect(tailIds.length).toBeGreaterThan(0);+ expect(fullIds.slice(-tailIds.length)).toEqual(tailIds);+ });+it("clears the compacting spinner on a successful completion status, without duplicating the row", () => {// A successful compaction sends a terminal `status: compacting, isComplete:// true`. It must flip the existing status row, not append a second one.@@ -1063,6 +1088,27 @@ describe("buildConversationItems", () => {expect(distinctContexts.size).toBe(4);});+ it("keeps item ids distinct across implicit turns that share a timestamp", () => {+ // Entries with a missing or unparseable timestamp all resolve to one `ts`.+ // The virtualizer keys its measurement cache and its prepend anchor on the+ // item id, so a duplicate anchors older history onto the wrong row.+ const events = [+ userPromptMsg(1, 1, "use a monitor"),+ agentMessageMsg(2, "Monitor is running."),+ turnCompleteMsg(3),+ agentMessageMsg(10, "ping 1 received."),+ backgroundTurnCompleteMsg(10),+ agentMessageMsg(10, "ping 2 received."),+ backgroundTurnCompleteMsg(10),+ ];++ const ids = buildConversationItems(events, true).items.map(+ (item) => item.id,+ );++ expect(new Set(ids).size).toBe(ids.length);+ });+it("computes a real duration for an implicit turn once a background reply completes it", () => {const events = [userPromptMsg(1, 1, "use a monitor"),diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.tsindex 70b15dcee623..940a23de43a9 100644--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts@@ -118,6 +118,8 @@ interface TurnState {context: TurnContext;gitAction: ReturnType<typeof parseGitActionMessage>;itemCount: number;+ /** Per-turn so item ids survive older-history prepends; the virtualized thread anchors on them. */+ nextItemId: number;}export interface ItemBuilder {@@ -131,7 +133,6 @@ export interface ItemBuilder {shellExecutes: Map<string, { item: UserShellExecute; index: number }>;isCompacting: boolean;isClearing: boolean;- nextId: () => number;/** Progress cards keyed by the backend-supplied `group` id. The first event* for a group opens the card inline where it arrived; every subsequent* event for the same id mutates the same card, regardless of which turn is@@ -156,7 +157,6 @@ export interface ItemBuilder {}export function createItemBuilder(): ItemBuilder {- let idCounter = 0;return {items: [],currentTurn: null,@@ -165,7 +165,6 @@ export function createItemBuilder(): ItemBuilder {shellExecutes: new Map(),isCompacting: false,isClearing: false,- nextId: () => idCounter++,progressCards: new Map(),lowestTouchedProgressIndex: Number.POSITIVE_INFINITY,completedToolCallCount: 0,@@ -237,7 +236,7 @@ function pushItem(b: ItemBuilder, update: RenderItem, ts?: number) {turn.itemCount++;b.items.push({type: "session_update",- id: `${turn.id}-item-${b.nextId()}`,+ id: `${turn.id}-item-${turn.nextItemId++}`,update,turnContext: turn.context,timestamp: ts,@@ -566,6 +565,7 @@ function handlePromptRequest(context,gitAction,itemCount: 0,+ nextItemId: 0,};b.pendingPrompts.set(msg.id, b.currentTurn);@@ -979,7 +979,9 @@ function ensureImplicitTurn(b: ItemBuilder, ts: number) {if (b.currentTurn && !b.currentTurn.isComplete) return;b.currentTurnStartIndex = b.items.length;- const turnId = `turn-${ts}-implicit`;+ // Entries with a missing or unparseable timestamp all share one `ts`, so the+ // item index is what keeps two implicit turns from emitting the same item ids.+ const turnId = `turn-${ts}-implicit-${b.currentTurnStartIndex}`;const toolCalls = new Map<string, ToolCall>();const childItems = new Map<string, ConversationItem[]>();const context: TurnContext = {@@ -998,6 +1000,7 @@ function ensureImplicitTurn(b: ItemBuilder, ts: number) {context,gitAction: { isGitAction: false, actionType: null, prompt: "" },itemCount: 0,+ nextItemId: 0,};}@@ -1034,7 +1037,7 @@ function pushChildItem(b: ItemBuilder, parentId: string, update: RenderItem) {turn.itemCount++;children.push({type: "session_update",- id: `${turn.id}-child-${b.nextId()}`,+ id: `${turn.id}-child-${turn.nextItemId++}`,update,turnContext: turn.context,});@@ -1080,7 +1083,7 @@ function appendTextChunkToChildren(turn.itemCount++;children.push({type: "session_update",- id: `${turn.id}-child-${b.nextId()}`,+ id: `${turn.id}-child-${turn.nextItemId++}`,update: { ...update, content: { ...update.content } },turnContext: turn.context,});diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsxindex e7de2631a307..7f310b5449c5 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx@@ -1244,6 +1244,13 @@ interface SharedChatThreadProps {taskId?: string;footerState?: Omit<BuildResult, "items">;hasPendingPermission?: boolean;+ /**+ * Chain index of the oldest loaded entry; 0 means the whole transcript is loaded. Above 0 the+ * thread renders windowed regardless of length, because only that body survives a prepend.+ */+ olderHistoryCursor?: number;+ isLoadingOlderHistory?: boolean;+ onLoadOlderHistory?: () => void;}export interface ChatThreadProps extends SharedChatThreadProps {@@ -1342,6 +1349,9 @@ function ChatThreadRenderer({footerState,hasPendingPermission,promptRecallRef,+ olderHistoryCursor = 0,+ isLoadingOlderHistory,+ onLoadOlderHistory,}: ChatThreadRendererProps) {const diffWorkerFactory = useService<DiffWorkerFactory>(DIFF_WORKER_FACTORY);const diffsPoolOptions = useMemo(@@ -1370,11 +1380,15 @@ function ChatThreadRenderer({// stays there for the life of this mount (see CHAT_THREAD_VIRTUALIZATION_THRESHOLD). Long// sessions start virtualized from the first render; a live session flips once mid-stream,// resuming from the scroll state the non-virtualized body recorded.+ //+ // A pageable transcript is windowed however short it is: prepending older history shifts the+ // non-virtualized body's ordinal keys, which rebinds mounted rows to older content and loses the+ // reader's place (see {@link keyTurnRows}).const flatCount = useMemo(() => countFlatRows(rows), [rows]);- const [virtualized, setVirtualized] = useState(- () => flatCount > CHAT_THREAD_VIRTUALIZATION_THRESHOLD,- );- if (!virtualized && flatCount > CHAT_THREAD_VIRTUALIZATION_THRESHOLD) {+ const needsWindowing =+ flatCount > CHAT_THREAD_VIRTUALIZATION_THRESHOLD || olderHistoryCursor > 0;+ const [virtualized, setVirtualized] = useState(() => needsWindowing);+ if (!virtualized && needsWindowing) {setVirtualized(true);}const flatRows = useMemo(@@ -1538,6 +1552,9 @@ function ChatThreadRenderer({footer={footer}renderNav={renderNav}resumeRef={threadResumeRef}+ olderHistoryCursor={olderHistoryCursor}+ isLoadingOlderHistory={isLoadingOlderHistory}+ onLoadOlderHistory={onLoadOlderHistory}/>) : (<>diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/MessageMinimap.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/MessageMinimap.tsxindex 700c39269ba6..1216770057e3 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/MessageMinimap.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/MessageMinimap.tsx@@ -14,7 +14,9 @@ import {} from "@posthog/ui/primitives/OverflowTickerText";import { useCallback, useMemo, useRef, useState } from "react";-/** Ticks drawn in the collapsed rail. Older turns fall off the top so the rail stays small. */+/** Ticks drawn in the collapsed rail. The tick window slides with the reading+ * position so the current turn always has a tick, wherever it sits in the+ * loaded history. */const MAX_TICKS = 12;const MAX_LABEL_LENGTH = 200;/** Message length (chars) at which a tick reaches full width. */@@ -136,6 +138,19 @@ export function MessageMinimap({return result;}, [items]);+ const railEntries = useMemo<MinimapEntry[]>(() => {+ if (entries.length <= MAX_TICKS) return entries;+ const anchorIndex = entries.findIndex(+ (entry) => entry.id === currentAnchorId,+ );+ if (anchorIndex === -1) return entries.slice(-MAX_TICKS);+ const start = Math.min(+ Math.max(0, anchorIndex - Math.floor(MAX_TICKS / 2)),+ entries.length - MAX_TICKS,+ );+ return entries.slice(start, start + MAX_TICKS);+ }, [entries, currentAnchorId]);+const handleOpenChange = useCallback((nextOpen: boolean) => {if (!nextOpen) reopenBlockedUntil.current = Date.now() + 250;setOpen(nextOpen);@@ -178,7 +193,7 @@ export function MessageMinimap({"focus-visible:outline-(--accent-8) focus-visible:outline-2 focus-visible:outline-offset-1",)}>- {entries.slice(-MAX_TICKS).map((entry) => (+ {railEntries.map((entry) => (<spankey={entry.id}aria-hidden="true"diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsxindex a67db1d1149d..34843c723ab8 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/VirtualThreadScrollBody.tsx@@ -10,6 +10,7 @@ import {computeStickyAnchor,type FlatThreadRow,FOLLOWING_END,+ nextOlderHistoryLoadState,nextThreadFollowState,SCROLL_PREVIOUS_ITEM_PEEK,SCROLL_UP_KEYS,@@ -301,6 +302,9 @@ export function VirtualThreadScrollBody({onUserInteract,renderNav,resumeRef,+ olderHistoryCursor = 0,+ isLoadingOlderHistory = false,+ onLoadOlderHistory,}: {items: ConversationItem[];flatRows: FlatThreadRow[];@@ -317,6 +321,13 @@ export function VirtualThreadScrollBody({renderNav?: (jumpToMessage: (id: string) => boolean) => ReactNode;/** Where the non-virtualized body left off, read once when this body takes over mid-session. */resumeRef: RefObject<ThreadScrollResume>;+ /**+ * Chain index of the oldest loaded entry; 0 means the whole transcript is loaded. Doubles as the+ * loader's progress signal, because it only moves when a page actually lands.+ */+ olderHistoryCursor?: number;+ isLoadingOlderHistory?: boolean;+ onLoadOlderHistory?: () => void;}) {const viewportRef = useRef<HTMLDivElement | null>(null);const footerRef = useRef<HTMLDivElement | null>(null);@@ -339,6 +350,46 @@ export function VirtualThreadScrollBody({getItemKey: (index) => flatRows[index]?.key ?? index,});+ const loadOlderArmedRef = useRef(false);+ const canLoadOlderRef = useRef(false);+ const isLoadingOlderRef = useRef(isLoadingOlderHistory);+ isLoadingOlderRef.current = isLoadingOlderHistory;+ const onLoadOlderHistoryRef = useRef(onLoadOlderHistory);+ useEffect(() => {+ onLoadOlderHistoryRef.current = onLoadOlderHistory;+ }, [onLoadOlderHistory]);++ const maybeLoadOlderHistory = useCallback(() => {+ const el = viewportRef.current;+ if (!el) return;+ const next = nextOlderHistoryLoadState(loadOlderArmedRef.current, {+ canLoad: canLoadOlderRef.current,+ isLoading: isLoadingOlderRef.current,+ scrollTop: el.scrollTop,+ maxScrollTop: el.scrollHeight - el.clientHeight,+ });+ loadOlderArmedRef.current = next.armed;+ if (next.load) onLoadOlderHistoryRef.current?.();+ }, []);++ // Arming belongs to the scroll handler, so one gesture buys one page. This+ // only covers what a gesture cannot reach: the first cursor the body sees, and+ // a viewport parked with no scroll room, which emits no scroll events at all.+ // Arming on every cursor move would instead chain page after page, because a+ // page of collapsed tool rows lands the viewport back inside the threshold.+ useEffect(() => {+ const canLoad = olderHistoryCursor > 0 && onLoadOlderHistory != null;+ const becameAvailable = canLoad && !canLoadOlderRef.current;+ canLoadOlderRef.current = canLoad;+ if (!canLoad) {+ loadOlderArmedRef.current = false;+ return;+ }+ if (becameAvailable) loadOlderArmedRef.current = true;+ const id = window.setTimeout(maybeLoadOlderHistory, 250);+ return () => window.clearTimeout(id);+ }, [olderHistoryCursor, onLoadOlderHistory, maybeLoadOlderHistory]);+const { followRef, leaveEnd, settleAtEnd, settleToIndex } = useSettleControls(virtualizer,viewportRef,@@ -404,9 +455,10 @@ export function VirtualThreadScrollBody({const sample = sampleThreadScroll(el, lastScrollTopRef.current);lastScrollTopRef.current = el.scrollTop;followRef.current = nextThreadFollowState(followRef.current, sample);+ maybeLoadOlderHistory();}scheduleStickyRecompute();- }, [scheduleStickyRecompute, followRef]);+ }, [scheduleStickyRecompute, followRef, maybeLoadOlderHistory]);useFollowBottom({virtualizer,@@ -429,6 +481,11 @@ export function VirtualThreadScrollBody({onJump={jumpToMessage}anchorId={stickyState.anchorId}/>+ {isLoadingOlderHistory && (+ <div className="-translate-x-1/2 pointer-events-none absolute top-2 left-1/2 z-10 rounded-full border border-(--gray-5) bg-(--gray-2) px-3 py-1 text-(--gray-11) text-xs">+ Loading earlier messages…+ </div>+ )}<ChatMessageScrollerViewportref={viewportRef}onScroll={handleScroll}diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.tsindex 55d89e4ce4c2..535777dfcbe0 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts@@ -7,7 +7,9 @@ import {countFlatRows,flattenTurnRows,keyTurnRows,+ nextOlderHistoryLoadState,nextThreadFollowState,+ OLDER_HISTORY_LOAD_THRESHOLD_PX,type StickyAnchorEntry,sampleThreadScroll,type ThreadScrollSample,@@ -96,21 +98,31 @@ describe("keyTurnRows", () => {});describe("flattenTurnRows", () => {- it("passes standalone rows through with ordinal keys for user messages", () => {+ it("keys standalone rows by their content-derived ids", () => {const rows: TurnRow[] = [userMessage("u1"),{ type: "git_action", id: "g1", actionType: "commit" as never },userMessage("u2"),];const flat = flattenTurnRows(rows);- expect(flat.map((r) => r.key)).toEqual([- "user-turn-0",- "g1",- "user-turn-1",- ]);+ expect(flat.map((r) => r.key)).toEqual(["u1", "g1", "u2"]);expect(flat.every((r) => !r.inTurn && !r.isTrailingInTurn)).toBe(true);});+ it("keeps a row's key unchanged when older rows are prepended", () => {+ const tail: TurnRow[] = [+ userMessage("u2"),+ agentTurn("a", [sessionUpdate("a1")]),+ ];+ const before = flattenTurnRows(tail);+ const after = flattenTurnRows([+ userMessage("u1"),+ agentTurn("b", [sessionUpdate("b1")]),+ ...tail,+ ]);+ expect(after.slice(2).map((r) => r.key)).toEqual(before.map((r) => r.key));+ });+it("flattens an agent turn to one row per item, flagging only the last as trailing", () => {const a = sessionUpdate("a");const b = toolGroup("b", [sessionUpdate("b1"), sessionUpdate("b2")]);@@ -119,7 +131,7 @@ describe("flattenTurnRows", () => {userMessage("u1"),agentTurn("a", [a, b, c]),]);- expect(flat.map((r) => r.key)).toEqual(["user-turn-0", "a", "b", "c"]);+ expect(flat.map((r) => r.key)).toEqual(["u1", "a", "b", "c"]);expect(flat.map((r) => r.inTurn)).toEqual([false, true, true, true]);expect(flat.map((r) => r.isTrailingInTurn)).toEqual([false,@@ -292,6 +304,96 @@ describe("nextThreadFollowState", () => {});});+describe("nextOlderHistoryLoadState", () => {+ const AT_TOP = 0;+ const AWAY = OLDER_HISTORY_LOAD_THRESHOLD_PX + 1;+ // Enough room to scroll back out of the threshold band, so a gesture is possible.+ const SCROLLABLE = OLDER_HISTORY_LOAD_THRESHOLD_PX * 4;++ it.each([+ [+ "spends the armed gesture on reaching the threshold",+ true,+ {+ canLoad: true,+ isLoading: false,+ scrollTop: AT_TOP,+ maxScrollTop: SCROLLABLE,+ },+ { armed: false, load: true },+ ],+ [+ "will not retry a failed load while the viewport stays at the top",+ false,+ {+ canLoad: true,+ isLoading: false,+ scrollTop: AT_TOP,+ maxScrollTop: SCROLLABLE,+ },+ { armed: false, load: false },+ ],+ [+ "will not chain a second page after one lands at the top",+ false,+ {+ canLoad: true,+ isLoading: false,+ scrollTop: OLDER_HISTORY_LOAD_THRESHOLD_PX,+ maxScrollTop: SCROLLABLE,+ },+ { armed: false, load: false },+ ],+ [+ "re-arms once the reader scrolls back out of the threshold",+ false,+ {+ canLoad: true,+ isLoading: false,+ scrollTop: AWAY,+ maxScrollTop: SCROLLABLE,+ },+ { armed: true, load: false },+ ],+ [+ "holds the armed gesture while a page is still in flight",+ true,+ {+ canLoad: true,+ isLoading: true,+ scrollTop: AT_TOP,+ maxScrollTop: SCROLLABLE,+ },+ { armed: true, load: false },+ ],+ [+ "keeps paging a window that leaves the viewport nothing to scroll",+ false,+ { canLoad: true, isLoading: false, scrollTop: AT_TOP, maxScrollTop: 0 },+ { armed: false, load: true },+ ],+ [+ "re-arms at the bottom of a window too short to clear the threshold",+ false,+ { canLoad: true, isLoading: false, scrollTop: 300, maxScrollTop: 300 },+ { armed: true, load: false },+ ],+ [+ "disarms once the whole transcript is loaded",+ true,+ {+ canLoad: false,+ isLoading: false,+ scrollTop: AT_TOP,+ maxScrollTop: SCROLLABLE,+ },+ { armed: false, load: false },+ ],+ ])("%s", (_name, armed, input, expected) => {+ expect(nextOlderHistoryLoadState(armed, input)).toEqual(expected);+ });+});+describe("sampleThreadScroll", () => {// Scroll range is 0..1500.const viewport = (scrollTop: number) => ({diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.tsindex 69e9353e4b0b..e75748d5fa23 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts@@ -73,8 +73,10 @@ export interface ThreadScrollResume {*/export interface FlatThreadRow {/**- * Stable list key. User messages are keyed by ordinal so the optimistic->real id swap of a- * just-sent message doesn't remount its row (same scheme as the non-virtualized path).+ * Stable list key: the row's content-derived item id, so keys survive older-history prepends+ * and the end-anchored virtualizer holds the viewport. The optimistic->real swap of a just-sent+ * user message remounts its row, which this engine absorbs; the non-virtualized scroller cannot+ * (see {@link keyTurnRows}).*/key: string;item: ThreadItem;@@ -105,10 +107,57 @@ export function completedTurnTimestamp(turn: AgentTurn): number | undefined {return undefined;}+/** Viewport distance from the top of the loaded window that triggers an older-history page load. */+export const OLDER_HISTORY_LOAD_THRESHOLD_PX = 800;++export interface OlderHistoryLoadState {+ /** Whether reaching the threshold should still spend a page load. */+ armed: boolean;+ /** Whether to request a page now. */+ load: boolean;+}++/**+ * Whether the older-history loader fires, and what it is armed for next.+ *+ * One page per gesture, where the gesture is the viewport re-entering the threshold band. A load+ * that fails or comes back empty leaves the cursor where it was, so nothing re-arms the loader until+ * the reader scrolls back out and in — otherwise the arming timer would retry a failing request+ * every few hundred milliseconds for as long as the thread sat near the top.+ *+ * A window that does not fill the viewport is the one case with no gesture to wait for: it emits no+ * scroll events at all, so it stays armed and keeps paging until there is something to scroll. A+ * window that fills it but stays shorter than the band re-arms on reaching the bottom instead,+ * since `scrollTop` there can never clear the band.+ */+export function nextOlderHistoryLoadState(+ armed: boolean,+ input: {+ canLoad: boolean;+ isLoading: boolean;+ scrollTop: number;+ /** Largest `scrollTop` the viewport can reach; 0 when the window does not fill it. */+ maxScrollTop: number;+ },+): OlderHistoryLoadState {+ if (!input.canLoad) return { armed: false, load: false };+ if (input.scrollTop > OLDER_HISTORY_LOAD_THRESHOLD_PX) {+ return { armed: true, load: false };+ }+ if (input.isLoading) return { armed, load: false };+ if (input.maxScrollTop <= 0) return { armed: false, load: true };+ // A window shorter than the band never lets `scrollTop` clear it, so reaching the bottom is the+ // only gesture the reader has left. A landed page never leaves them there, so this cannot chain.+ if (input.scrollTop >= input.maxScrollTop) {+ return { armed: true, load: false };+ }+ if (!armed) return { armed, load: false };+ return { armed: false, load: true };+}+/** Flatten turn rows into the windowed row list (see {@link FlatThreadRow}). */export function flattenTurnRows(rows: TurnRow[]): FlatThreadRow[] {const out: FlatThreadRow[] = [];- let userTurn = 0;for (const row of rows) {if (row.type === "agent_turn") {const timestamp = completedTurnTimestamp(row);@@ -132,7 +181,7 @@ export function flattenTurnRows(rows: TurnRow[]): FlatThreadRow[] {continue;}out.push({- key: row.type === "user_message" ? `user-turn-${userTurn++}` : row.id,+ key: row.id,item: row,inTurn: false,isTrailingInTurn: false,@@ -181,7 +230,9 @@ function turnRowKeyPrefix(row: TurnRow): string | null {* jumps to the oldest one the engine has not already scrolled to, which on the first such remount* is the start of the conversation.*- * Rows are only ever appended, so an ordinal is stable for the life of the row.+ * Rows are only ever appended here, so an ordinal is stable for the life of the row. A transcript+ * that can page older history renders windowed instead, precisely because a prepend would shift+ * every ordinal after it.*/export function keyTurnRows(rows: TurnRow[]): KeyedTurnRow[] {const ordinals = new Map<string, number>();diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex 953d0e65d6e0..8560ddd14fb4 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -138,6 +138,7 @@ const mockAuthenticatedClient = vi.hoisted(() => ({startGithubUserIntegrationConnect: vi.fn(),getTaskRunSessionLogs: vi.fn(),getTaskRunSessionLogsResult: vi.fn(),+ getTaskRunSessionLogsPage: vi.fn(),}));type MockAuthenticatedClient = typeof mockAuthenticatedClient;@@ -502,6 +503,11 @@ describe("SessionService", () => {complete: true,truncatedHeadCount: 0,});+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockResolvedValue({+ entries: [],+ hasMore: false,+ matchingCount: 0,+ });mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(undefined);mockSessionStoreSetters.getSessions.mockReturnValue({});mockAuth.fetchAuthState.mockResolvedValue({@@ -1719,10 +1725,10 @@ describe("SessionService", () => {},} as AcpMessage,];- mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockResolvedValue({entries: finalEntries,- complete: true,- truncatedHeadCount: 0,+ hasMore: false,+ matchingCount: finalEntries.length,});mockConvertStoredEntriesToEvents.mockReturnValueOnce(finalEvents);@@ -1758,8 +1764,8 @@ describe("SessionService", () => {expect(onStatusChange).not.toHaveBeenCalled();await vi.waitFor(() => {expect(- mockAuthenticatedClient.getTaskRunSessionLogsResult,- ).toHaveBeenCalledWith("task-123", "run-123", { limit: 100000 });+ mockAuthenticatedClient.getTaskRunSessionLogsPage,+ ).toHaveBeenCalledWith("task-123", "run-123", { limit: 1 });});expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith("run-123",@@ -1784,6 +1790,13 @@ describe("SessionService", () => {mockSessionStoreSetters.getSessions.mockReturnValue({"run-123": session,});+ // Without a matching-count header the window fetch falls back to the+ // capped sequential fetch, which is the path that reports a dropped head.+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockResolvedValue({+ entries: [{ timestamp: "2024-01-01T00:00:00Z", notification: {} }],+ hasMore: true,+ matchingCount: null,+ });mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({entries: [{ timestamp: "2024-01-01T00:00:00Z", notification: {} },@@ -1821,6 +1834,359 @@ describe("SessionService", () => {});});+ it("renders the tail of an oversized chain and loads older pages on demand", async () => {+ const service = getSessionService();+ const session = createMockSession({+ taskId: "task-123",+ taskRunId: "run-123",+ cloudStatus: "in_progress",+ isCloud: true,+ events: [],+ });+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);+ mockSessionStoreSetters.getSessions.mockReturnValue({+ "run-123": session,+ });+ const chainEntries = Array.from({ length: 12000 }, (_, i) => ({+ timestamp: `2024-01-01T00:00:${String(i % 60).padStart(2, "0")}Z`,+ notification: { method: `entry-${i}` },+ }));+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockImplementation(+ async (+ _taskId: string,+ _runId: string,+ options: { limit: number; offset?: number },+ ) => {+ const offset = options.offset ?? 0;+ const entries = chainEntries.slice(offset, offset + options.limit);+ return {+ entries,+ hasMore: offset + entries.length < chainEntries.length,+ matchingCount: chainEntries.length,+ };+ },+ );+ mockConvertStoredEntriesToEvents.mockImplementation(+ (entries: unknown[]) =>+ entries.map(+ (_, i) =>+ ({+ type: "acp_message",+ ts: i,+ message: { jsonrpc: "2.0", method: "session/update" },+ }) as AcpMessage,+ ),+ );++ service.watchCloudTask(+ "task-123",+ "run-123",+ "https://api.anthropic.com",+ 123,+ undefined,+ "https://example.com/logs/run-123",+ undefined,+ "claude",+ undefined,+ undefined,+ undefined,+ "completed",+ );++ await vi.waitFor(() => {+ expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(+ "run-123",+ expect.objectContaining({+ transcriptWindowStart: 10000,+ cloudTranscriptEntryCount: 12000,+ }),+ );+ });+ expect(mockConvertStoredEntriesToEvents).toHaveBeenCalledWith(+ chainEntries.slice(10000),+ undefined,+ { taskRunId: "run-123", startEntryIndex: 10000 },+ );+ const hydrationOffsets = new Set(+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mock.calls.map(+ (call) => (call[2] as { offset?: number }).offset ?? 0,+ ),+ );+ expect(hydrationOffsets).toEqual(new Set([0, 10000]));++ const hydrated = createMockSession({+ taskId: "task-123",+ taskRunId: "run-123",+ cloudStatus: "completed",+ isCloud: true,+ events: [],+ transcriptWindowStart: 10000,+ });+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(hydrated);+ await service.loadOlderCloudTranscript("task-123");++ expect(+ mockAuthenticatedClient.getTaskRunSessionLogsPage,+ ).toHaveBeenLastCalledWith("task-123", "run-123", {+ limit: 5000,+ offset: 5000,+ });+ expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(+ "run-123",+ expect.objectContaining({ transcriptWindowStart: 5000 }),+ );+ });++ it("waits out a restoring auth before hydrating instead of bailing", async () => {+ const service = getSessionService();+ const session = createMockSession({+ taskId: "task-123",+ taskRunId: "run-123",+ cloudStatus: "completed",+ isCloud: true,+ events: [],+ });+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);+ mockSessionStoreSetters.getSessions.mockReturnValue({+ "run-123": session,+ });+ mockAuth.fetchAuthState.mockResolvedValueOnce({+ status: "restoring",+ bootstrapComplete: false,+ });+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockResolvedValue({+ entries: [{ timestamp: "2024-01-01T00:00:00Z", notification: {} }],+ hasMore: false,+ matchingCount: 1,+ });++ service.watchCloudTask(+ "task-123",+ "run-123",+ "https://api.anthropic.com",+ 123,+ undefined,+ "https://example.com/logs/run-123",+ undefined,+ "claude",+ undefined,+ undefined,+ undefined,+ "completed",+ );++ await vi.waitFor(+ () => {+ expect(+ mockAuthenticatedClient.getTaskRunSessionLogsPage,+ ).toHaveBeenCalledWith("task-123", "run-123", { limit: 1 });+ },+ { timeout: 2000 },+ );+ });++ it("follows the log past a probe count the run grew behind", async () => {+ const service = getSessionService();+ const session = createMockSession({+ taskId: "task-123",+ taskRunId: "run-123",+ cloudStatus: "completed",+ isCloud: true,+ events: [],+ });+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);+ mockSessionStoreSetters.getSessions.mockReturnValue({+ "run-123": session,+ });+ // The probe sees 30 entries; terminal log persistence lands 10 more while+ // the tail page is in flight.+ const chainEntries = Array.from({ length: 40 }, (_, i) => ({+ timestamp: `2024-01-01T00:00:${String(i % 60).padStart(2, "0")}Z`,+ notification: { method: `entry-${i}` },+ }));+ let probed = false;+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockImplementation(+ async (+ _taskId: string,+ _runId: string,+ options: { limit: number; offset?: number },+ ) => {+ const offset = options.offset ?? 0;+ const visible = probed ? chainEntries.length : 30;+ probed = true;+ const entries = chainEntries.slice(offset, offset + options.limit);+ return {+ entries,+ hasMore: offset + entries.length < visible,+ matchingCount: visible,+ };+ },+ );++ service.watchCloudTask(+ "task-123",+ "run-123",+ "https://api.anthropic.com",+ 123,+ undefined,+ "https://example.com/logs/run-123",+ undefined,+ "claude",+ undefined,+ undefined,+ undefined,+ "completed",+ );++ await vi.waitFor(() => {+ expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(+ "run-123",+ expect.objectContaining({+ transcriptWindowStart: 0,+ cloudTranscriptEntryCount: 40,+ }),+ );+ });+ });++ it("falls back to the sequential fetch when the server omits the matching count", async () => {+ const service = getSessionService();+ const session = createMockSession({+ taskId: "task-123",+ taskRunId: "run-123",+ cloudStatus: "in_progress",+ isCloud: true,+ events: [],+ });+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);+ mockSessionStoreSetters.getSessions.mockReturnValue({+ "run-123": session,+ });+ const chainEntries = Array.from({ length: 3 }, (_, i) => ({+ timestamp: `2024-01-01T00:00:0${i}Z`,+ notification: { method: `entry-${i}` },+ }));+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockResolvedValue({+ entries: chainEntries.slice(0, 1),+ hasMore: true,+ matchingCount: null,+ });+ mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({+ entries: chainEntries,+ complete: true,+ truncatedHeadCount: 0,+ });++ service.watchCloudTask(+ "task-123",+ "run-123",+ "https://api.anthropic.com",+ 123,+ undefined,+ "https://example.com/logs/run-123",+ undefined,+ "claude",+ undefined,+ undefined,+ undefined,+ "completed",+ );++ await vi.waitFor(() => {+ expect(+ mockAuthenticatedClient.getTaskRunSessionLogsResult,+ ).toHaveBeenCalledWith("task-123", "run-123", { limit: 100000 });+ });+ expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(+ "run-123",+ expect.objectContaining({+ transcriptWindowStart: 0,+ cloudTranscriptEntryCount: 3,+ }),+ );+ });++ it("recovers from a failed older-page fetch and can retry", async () => {+ const service = getSessionService();+ const session = createMockSession({+ taskId: "task-123",+ taskRunId: "run-123",+ cloudStatus: "completed",+ isCloud: true,+ events: [],+ transcriptWindowStart: 5000,+ });+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);+ mockSessionStoreSetters.getSessions.mockReturnValue({+ "run-123": session,+ });+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockRejectedValue(+ new Error("network down"),+ );++ await service.loadOlderCloudTranscript("task-123");++ expect(mockSessionStoreSetters.updateSession).toHaveBeenLastCalledWith(+ "run-123",+ { isLoadingOlderTranscript: false },+ );+ expect(mockSessionStoreSetters.updateSession).not.toHaveBeenCalledWith(+ "run-123",+ expect.objectContaining({ events: expect.anything() }),+ );++ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockResolvedValue({+ entries: Array.from({ length: 5000 }, () => ({+ timestamp: "2024-01-01T00:00:00Z",+ notification: {},+ })),+ hasMore: true,+ matchingCount: null,+ });+ await service.loadOlderCloudTranscript("task-123");+ expect(+ mockAuthenticatedClient.getTaskRunSessionLogsPage,+ ).toHaveBeenCalledTimes(2);+ });++ it("discards an older page when the window moved while it was in flight", async () => {+ const service = getSessionService();+ const sessionAtFetch = createMockSession({+ taskId: "task-123",+ taskRunId: "run-123",+ cloudStatus: "completed",+ isCloud: true,+ events: [],+ transcriptWindowStart: 5000,+ });+ const sessionAfterMove = createMockSession({+ taskId: "task-123",+ taskRunId: "run-123",+ cloudStatus: "completed",+ isCloud: true,+ events: [],+ transcriptWindowStart: 2000,+ });+ mockSessionStoreSetters.getSessionByTaskId+ .mockReturnValueOnce(sessionAtFetch)+ .mockReturnValue(sessionAfterMove);+ mockSessionStoreSetters.getSessions.mockReturnValue({+ "run-123": sessionAtFetch,+ });+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockResolvedValue({+ entries: [{ timestamp: "2024-01-01T00:00:00Z", notification: {} }],+ hasMore: true,+ matchingCount: null,+ });++ await service.loadOlderCloudTranscript("task-123");++ expect(mockSessionStoreSetters.updateSession).not.toHaveBeenCalledWith(+ "run-123",+ expect.objectContaining({ events: expect.anything() }),+ );+ });+it("falls back to the run log URL when terminal chain hydration is empty", async () => {const service = getSessionService();const session = createMockSession({@@ -2021,8 +2387,8 @@ describe("SessionService", () => {// instead of being deduped onto the in-flight resume-chain hydration.await vi.waitFor(() => {expect(- mockAuthenticatedClient.getTaskRunSessionLogsResult,- ).toHaveBeenCalledTimes(3);+ mockAuthenticatedClient.getTaskRunSessionLogsPage,+ ).toHaveBeenCalledWith("task-123", "run-123", { limit: 1 });});resolveFirstHydration({entries: [],@@ -3618,6 +3984,7 @@ describe("SessionService", () => {isCloud: true,logUrl: "https://logs.example.com/run-123",processedLineCount: 14,+ transcriptWindowStart: 0,}),);});@@ -4234,63 +4601,64 @@ describe("SessionService", () => {mockSessionStoreSetters.getSessions.mockReturnValue({"run-123": completedSession,});- mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({- complete: true,- truncatedHeadCount: 0,- entries: [- {- type: "notification",- notification: {- method: "_posthog/sdk_session",- params: {- taskRunId: "run-123",- sessionId: "acp-session-1",- adapter: "claude",- },+ const pendingQuestionEntries = [+ {+ type: "notification",+ notification: {+ method: "_posthog/sdk_session",+ params: {+ taskRunId: "run-123",+ sessionId: "acp-session-1",+ adapter: "claude",},},- {- type: "notification",- notification: {- method: "_posthog/run_started",- params: {- sessionId: "acp-session-1",- runId: "run-123",- taskId: "task-123",- },+ },+ {+ type: "notification",+ notification: {+ method: "_posthog/run_started",+ params: {+ sessionId: "acp-session-1",+ runId: "run-123",+ taskId: "task-123",},},- {- type: "notification",- notification: {- method: "_posthog/permission_request",- params: {- requestId: "request-1",- toolCall: {- toolCallId: "tool-1",- title: "What animal do you prefer?",- kind: "other",- _meta: {- codeToolKind: "question",- questions: [- {- question: "What animal do you prefer?",- options: [- { label: "cats", description: "Cats" },- { label: "dogs", description: "Dogs" },- ],- },- ],- },+ },+ {+ type: "notification",+ notification: {+ method: "_posthog/permission_request",+ params: {+ requestId: "request-1",+ toolCall: {+ toolCallId: "tool-1",+ title: "What animal do you prefer?",+ kind: "other",+ _meta: {+ codeToolKind: "question",+ questions: [+ {+ question: "What animal do you prefer?",+ options: [+ { label: "cats", description: "Cats" },+ { label: "dogs", description: "Dogs" },+ ],+ },+ ],},- options: [- { optionId: "option_0", name: "cats", kind: "allow_once" },- { optionId: "option_1", name: "dogs", kind: "allow_once" },- ],},+ options: [+ { optionId: "option_0", name: "cats", kind: "allow_once" },+ { optionId: "option_1", name: "dogs", kind: "allow_once" },+ ],},},- ],+ },+ ];+ mockAuthenticatedClient.getTaskRunSessionLogsPage.mockResolvedValue({+ entries: pendingQuestionEntries,+ hasMore: false,+ matchingCount: pendingQuestionEntries.length,});service.watchCloudTask(