Skip to content

: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.

perf(desktop): fetch cloud transcripts as tail windows (#86107)

Charles Vienb15003b800a9
diff --git a/products/desktop/apps/mobile/src/features/tasks/api.ts b/products/desktop/apps/mobile/src/features/tasks/api.ts
index 1a45407bf8bf..64f25e8cd95a 100644
--- a/products/desktop/apps/mobile/src/features/tasks/api.ts
+++ b/products/desktop/apps/mobile/src/features/tasks/api.ts
@@ -9,7 +9,6 @@ import type {
import { fetch } from "expo/fetch";
import {
authedFetch,
- createTimeoutSignal,
getAccessToken,
getBaseUrl,
getProjectId,
@@ -365,49 +364,6 @@ export async function sendCloudCommand(
return data?.result;
}
-export interface SessionLogsPage {
- entries: StoredLogEntry[];
- hasMore: boolean;
-}
-
-export async function fetchSessionLogs(
- taskId: string,
- runId: string,
- options: { limit?: number; offset?: number } = {},
-): Promise<SessionLogsPage> {
- return withRetry(
- async () => {
- const baseUrl = getBaseUrl();
- const projectId = getProjectId();
-
- const params = new URLSearchParams({
- limit: String(options.limit ?? 5000),
- offset: String(options.offset ?? 0),
- });
-
- const response = await authedFetch(
- `${baseUrl}/api/projects/${projectId}/tasks/${taskId}/runs/${runId}/session_logs/?${params}`,
- { signal: createTimeoutSignal(10_000) },
- );
-
- if (!response.ok) {
- throw new HttpError(
- response.status,
- response.statusText,
- "Failed to fetch session logs",
- );
- }
-
- const entries = (await response.json()) as StoredLogEntry[];
- return {
- entries,
- hasMore: response.headers.get("X-Has-More") === "true",
- };
- },
- { shouldRetry: isRetryableError },
- );
-}
-
export interface StreamCloudTaskOptions {
lastEventId?: string | null;
startLatest?: boolean;
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index 9dd48c6fc511..2269b534960d 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -315,51 +315,6 @@ describe("PostHogAPIClient", () => {
);
});
- it("uses the configured fetch implementation for task log URLs", async () => {
- const fetch = vi
- .fn()
- .mockResolvedValue(
- new Response(
- '{"type":"notification","timestamp":"2026-07-21T00:00:00Z"}\n',
- { status: 200 },
- ),
- );
- const client = new PostHogAPIClient(
- "http://localhost:8000",
- async () => "token",
- async () => "token",
- 123,
- { fetch },
- );
- vi.spyOn(client, "getTask").mockResolvedValue({
- id: "task-1",
- task_number: 1,
- slug: "task-1",
- title: "Task",
- description: "Task",
- created_at: "2026-07-21T00:00:00Z",
- updated_at: "2026-07-21T00:00:00Z",
- origin_product: "user_created",
- latest_run: {
- id: "run-1",
- task: "task-1",
- team: 123,
- branch: null,
- status: "in_progress",
- log_url: "https://logs.posthog.test/run-1.jsonl",
- error_message: null,
- output: null,
- state: {},
- created_at: "2026-07-21T00:00:00Z",
- updated_at: "2026-07-21T00:00:00Z",
- completed_at: null,
- },
- });
-
- await expect(client.getTaskLogs("task-1")).resolves.toHaveLength(1);
- expect(fetch).toHaveBeenCalledWith("https://logs.posthog.test/run-1.jsonl");
- });
-
it.each([
{
label: "desktop default",
@@ -2139,7 +2094,7 @@ describe("PostHogAPIClient", () => {
});
});
- describe("getTaskRunSessionLogs", () => {
+ describe("getTaskRunSessionLogsResult", () => {
function makeClient(fetch: ReturnType<typeof vi.fn>) {
const client = new PostHogAPIClient(
"http://localhost:8000",
@@ -2203,11 +2158,9 @@ describe("PostHogAPIClient", () => {
const fetch = vi.fn().mockResolvedValue(page(makeEntries(3, "a"), false));
const client = makeClient(fetch);
- const result = await client.getTaskRunSessionLogs(
- "task-1",
- "run-1",
- options,
- );
+ const result = (
+ await client.getTaskRunSessionLogsResult("task-1", "run-1", options)
+ ).entries;
expect(result).toHaveLength(3);
expect(fetch).toHaveBeenCalledTimes(1);
@@ -2224,9 +2177,11 @@ describe("PostHogAPIClient", () => {
.mockResolvedValueOnce(page(makeEntries(10, "c"), false));
const client = makeClient(fetch);
- const result = await client.getTaskRunSessionLogs("task-1", "run-1", {
- limit: 100000,
- });
+ const result = (
+ await client.getTaskRunSessionLogsResult("task-1", "run-1", {
+ limit: 100000,
+ })
+ ).entries;
expect(result).toHaveLength(210);
expect(fetch).toHaveBeenCalledTimes(3);
@@ -2247,9 +2202,11 @@ describe("PostHogAPIClient", () => {
.mockResolvedValueOnce(page(makeEntries(1000, "b"), true));
const client = makeClient(fetch);
- const result = await client.getTaskRunSessionLogs("task-1", "run-1", {
- limit: 6000,
- });
+ const result = (
+ await client.getTaskRunSessionLogsResult("task-1", "run-1", {
+ limit: 6000,
+ })
+ ).entries;
expect(result).toHaveLength(6000);
expect(fetch).toHaveBeenCalledTimes(2);
@@ -2266,7 +2223,7 @@ describe("PostHogAPIClient", () => {
.mockResolvedValueOnce(page(makeEntries(5, "b"), false));
const client = makeClient(fetch);
- await client.getTaskRunSessionLogs("task-1", "run-1", {
+ await client.getTaskRunSessionLogsResult("task-1", "run-1", {
limit: 100000,
after: "2026-07-01T00:00:00Z",
});
@@ -2496,9 +2453,11 @@ describe("PostHogAPIClient", () => {
});
const client = makeClient(fetch);
- const result = await client.getTaskRunSessionLogs("task-1", "run-1", {
- limit: 100000,
- });
+ const result = (
+ await client.getTaskRunSessionLogsResult("task-1", "run-1", {
+ limit: 100000,
+ })
+ ).entries;
expect(result).toHaveLength(10);
expect(fetch).toHaveBeenCalledTimes(1);
@@ -2508,9 +2467,11 @@ describe("PostHogAPIClient", () => {
const fetch = vi.fn().mockResolvedValue(page([], true));
const client = makeClient(fetch);
- const result = await client.getTaskRunSessionLogs("task-1", "run-1", {
- limit: 100000,
- });
+ const result = (
+ await client.getTaskRunSessionLogsResult("task-1", "run-1", {
+ limit: 100000,
+ })
+ ).entries;
expect(result).toHaveLength(0);
expect(fetch).toHaveBeenCalledTimes(1);
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index ab84b3e768e4..45fab8306970 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -1597,7 +1597,6 @@ export class PostHogAPIClient {
private api: ReturnType<typeof createApiClient>;
private _teamId: number | null = null;
private githubConnectFrom: string;
- private readonly fetch: FetchImplementation;
private readonly apiHost: string;
constructor(
@@ -1610,7 +1609,6 @@ export class PostHogAPIClient {
const baseUrl = apiHost.endsWith("/") ? apiHost.slice(0, -1) : apiHost;
this.apiHost = baseUrl;
this.githubConnectFrom = options.githubConnectFrom ?? "posthog_code";
- this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
this.api = createApiClient(
buildApiFetcher({
getAccessToken,
@@ -3718,15 +3716,6 @@ export class PostHogAPIClient {
}
}
- async getTaskRunSessionLogs(
- taskId: string,
- runId: string,
- options?: { limit?: number; after?: string },
- ): Promise<StoredLogEntry[]> {
- return (await this.getTaskRunSessionLogsResult(taskId, runId, options))
- .entries;
- }
-
// AbortController + setTimeout because Hermes, which runs this client on
// mobile, has no AbortSignal.timeout.
private async fetchSessionLogsPage(
@@ -3853,39 +3842,6 @@ export class PostHogAPIClient {
}
}
- async getTaskLogs(taskId: string): Promise<StoredLogEntry[]> {
- try {
- const task = await this.getTask(taskId);
- const logUrl = task?.latest_run?.log_url;
-
- if (!logUrl) {
- return [];
- }
-
- const response = await this.fetch(logUrl);
-
- if (!response.ok) {
- log.warn(
- `Failed to fetch logs: ${response.status} ${response.statusText}`,
- );
- return [];
- }
-
- const content = await response.text();
-
- if (!content.trim()) {
- return [];
- }
- return content
- .trim()
- .split("\n")
- .map((line) => JSON.parse(line) as StoredLogEntry);
- } catch (err) {
- log.warn("Failed to fetch task logs from latest run", err);
- return [];
- }
- }
-
async getIntegrations() {
const teamId = await this.getTeamId();
return this.getIntegrationsForProject(teamId);
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts b/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
index 0fa453e573da..0a73160117b9 100644
--- a/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
+++ b/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts
@@ -59,6 +59,13 @@ const STREAM_END_EVENT_NAME = "stream-end";
interface SessionLogsPage {
entries: StoredLogEntry[];
hasMore: boolean;
+ matchingCount: number | null;
+}
+
+interface SessionLogsWindow {
+ entries: StoredLogEntry[];
+ windowStart: number;
+ chainTotal: number;
}
interface CloudTaskConnectionError {
@@ -436,6 +443,13 @@ export interface CloudTaskEngineDependencies {
logger: RootLogger;
mcpRelayExecutor?: McpRelayExecutor | null;
streamFetch?: CloudTaskFetch;
+ /**
+ * Cap on the entries a snapshot carries, for hosts that page older history
+ * in from `windowStart`. Left out, a snapshot carries the whole chain: a
+ * host that renders a snapshot as the complete transcript would otherwise
+ * lose everything behind the window.
+ */
+ transcriptTailWindow?: number;
}
export type CloudTaskFetch = (
@@ -456,6 +470,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
private readonly analytics: IAnalytics;
private readonly mcpRelayExecutor: McpRelayExecutor | null;
private readonly streamFetch: CloudTaskFetch;
+ private readonly transcriptTailWindow: number | undefined;
constructor({
auth,
@@ -463,12 +478,14 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
logger,
mcpRelayExecutor = null,
streamFetch = globalThis.fetch.bind(globalThis),
+ transcriptTailWindow,
}: CloudTaskEngineDependencies) {
super();
this.auth = auth;
this.analytics = analytics;
this.mcpRelayExecutor = mcpRelayExecutor;
this.streamFetch = streamFetch;
+ this.transcriptTailWindow = transcriptTailWindow;
this.log = logger.scope("cloud-task");
}
@@ -1127,14 +1144,20 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
}
if (isTerminalStatus(run.status)) {
- let historicalEntries = await this.fetchAllSessionLogs(watcher);
- if (historicalEntries?.length === 0 && run.log_url) {
- historicalEntries = await this.fetchArchivedLogs(run.log_url);
+ let window = await this.fetchSessionLogsWindow(watcher);
+ // A terminal run whose persisted chain comes back empty can still have
+ // a complete archived log (persistence raced teardown); fall back to it
+ // rather than emitting an empty final transcript.
+ if (window?.entries.length === 0 && run.log_url) {
+ const archived = await this.fetchArchivedLogs(run.log_url);
+ window = archived
+ ? { entries: archived, windowStart: 0, chainTotal: archived.length }
+ : null;
}
const terminalWatcher = this.watchers.get(key);
if (!terminalWatcher || terminalWatcher !== watcher) return;
if (watcher.failed) return;
- if (!historicalEntries) {
+ if (!window) {
this.failWatcher(key, {
title: "Failed to load task history",
message:
@@ -1144,14 +1167,15 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
return;
}
- watcher.totalEntryCount = historicalEntries.length;
+ watcher.totalEntryCount = window.chainTotal;
watcher.hasEmittedSnapshot = true;
this.emit(CloudTaskEvent.Update, {
taskId: watcher.taskId,
runId: watcher.runId,
kind: "snapshot",
- newEntries: historicalEntries,
+ newEntries: window.entries,
totalEntryCount: watcher.totalEntryCount,
+ ...(window.windowStart > 0 ? { windowStart: window.windowStart } : {}),
status: watcher.lastStatus ?? undefined,
stage: watcher.lastStage,
output: watcher.lastOutput,
@@ -1167,11 +1191,11 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
watcher.bufferedLogBatches = [];
void this.connectSse(key, { startLatest: true });
- const historicalEntries = await this.fetchAllSessionLogs(watcher);
+ const window = await this.fetchSessionLogsWindow(watcher);
const bootstrappingWatcher = this.watchers.get(key);
if (!bootstrappingWatcher || bootstrappingWatcher !== watcher) return;
if (watcher.failed) return;
- if (!historicalEntries) {
+ if (!window) {
this.failWatcher(key, {
title: "Failed to load cloud run history",
message:
@@ -1184,15 +1208,16 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
// Flush any pending live entries into the bootstrap buffer before snapshot.
this.flushLogBatch(key);
- watcher.totalEntryCount = historicalEntries.length;
+ watcher.totalEntryCount = window.chainTotal;
watcher.hasEmittedSnapshot = true;
this.emit(CloudTaskEvent.Update, {
taskId: watcher.taskId,
runId: watcher.runId,
kind: "snapshot",
- newEntries: historicalEntries,
+ newEntries: window.entries,
totalEntryCount: watcher.totalEntryCount,
+ ...(window.windowStart > 0 ? { windowStart: window.windowStart } : {}),
status: watcher.lastStatus ?? undefined,
stage: watcher.lastStage,
output: watcher.lastOutput,
@@ -1202,7 +1227,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
});
watcher.isBootstrapping = false;
- this.drainBufferedLogBatches(key, historicalEntries);
+ this.drainBufferedLogBatches(key, window.entries);
if (watcher.failed) {
return;
@@ -1855,13 +1880,23 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
const watcher = this.watchers.get(key);
if (!watcher || watcher.failed) return;
- const historicalEntries = await this.fetchAllSessionLogs(watcher);
+ // The merge below drops emitted entries it finds in the fetched history,
+ // so the window must reach back over everything this watcher already
+ // emitted; anything older than the window would be re-appended as
+ // "missing" at the wrong position. Sizing the window by the emitted count
+ // alone leaves no room for entries that reached the chain without being
+ // emitted (a read-leg switch drops the cursor), which push the oldest
+ // emitted entry out the back, so anchor on the offset instead.
+ const window = await this.fetchSessionLogsWindow(watcher, {
+ coverFromOffset:
+ watcher.totalEntryCount - watcher.emittedLogEntries.length,
+ });
const currentWatcher = this.watchers.get(key);
if (!currentWatcher || currentWatcher !== watcher || watcher.failed) {
return;
}
- if (!historicalEntries) {
+ if (!window) {
this.log.warn("Cloud task snapshot replay failed", {
taskId: watcher.taskId,
runId: watcher.runId,
@@ -1871,12 +1906,13 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
const { snapshotEntries, missingEmittedEntries } =
this.mergeHistoricalAndEmittedEntries(
- historicalEntries,
+ window.entries,
watcher.emittedLogEntries,
);
watcher.emittedLogEntries = missingEmittedEntries;
- if (snapshotEntries.length > watcher.totalEntryCount) {
- watcher.totalEntryCount = snapshotEntries.length;
+ const snapshotTotal = window.windowStart + snapshotEntries.length;
+ if (snapshotTotal > watcher.totalEntryCount) {
+ watcher.totalEntryCount = snapshotTotal;
}
this.emit(CloudTaskEvent.Update, {
@@ -1884,7 +1920,8 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
runId: watcher.runId,
kind: "snapshot",
newEntries: snapshotEntries,
- totalEntryCount: snapshotEntries.length,
+ totalEntryCount: snapshotTotal,
+ ...(window.windowStart > 0 ? { windowStart: window.windowStart } : {}),
status: watcher.lastStatus ?? undefined,
stage: watcher.lastStage,
output: watcher.lastOutput,
@@ -2188,11 +2225,12 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
private async fetchSessionLogsPage(
watcher: WatcherState,
offset: number,
+ limit: number = SESSION_LOG_PAGE_LIMIT,
): Promise<SessionLogsPage | null> {
const url = new URL(
`${watcher.apiHost}/api/projects/${watcher.teamId}/tasks/${watcher.taskId}/runs/${watcher.runId}/session_logs/`,
);
- url.searchParams.set("limit", SESSION_LOG_PAGE_LIMIT.toString());
+ url.searchParams.set("limit", limit.toString());
url.searchParams.set("offset", offset.toString());
try {
@@ -2220,9 +2258,17 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
}
const raw = await authedResponse.text();
+ // Number(null) is 0, so an absent header must stay null.
+ const matchingHeader = authedResponse.headers.get("X-Matching-Count");
+ const matchingCount =
+ matchingHeader === null ? null : Number(matchingHeader);
return {
entries: JSON.parse(raw) as StoredLogEntry[],
hasMore: authedResponse.headers.get("X-Has-More") === "true",
+ matchingCount:
+ matchingCount !== null && Number.isFinite(matchingCount)
+ ? matchingCount
+ : null,
};
} catch (error) {
this.log.warn("Cloud task session logs fetch error", {
@@ -2237,9 +2283,10 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
private async fetchAllSessionLogs(
watcher: WatcherState,
+ seedEntries: StoredLogEntry[] = [],
): Promise<StoredLogEntry[] | null> {
- const entries: StoredLogEntry[] = [];
- let offset = 0;
+ const entries: StoredLogEntry[] = [...seedEntries];
+ let offset = entries.length;
while (true) {
const page = await this.fetchSessionLogsPage(watcher, offset);
@@ -2256,6 +2303,71 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
}
}
+ /**
+ * A one-entry probe learns the chain total from X-Matching-Count without
+ * downloading a page an oversized log would throw away, then only the
+ * newest `transcriptTailWindow` entries are fetched; the renderer pages in
+ * older history on scroll. Hosts without a tail window, and servers that
+ * don't report the total, get the full walk continued from the probe's
+ * page. `coverFromOffset` pulls the window start down to a chain offset the
+ * caller needs covered. Null on failure.
+ */
+ private async fetchSessionLogsWindow(
+ watcher: WatcherState,
+ options: { coverFromOffset?: number } = {},
+ ): Promise<SessionLogsWindow | null> {
+ const tailWindow = this.transcriptTailWindow;
+ const probe = await this.fetchSessionLogsPage(watcher, 0, 1);
+ if (!probe) return null;
+ if (!probe.hasMore) {
+ return {
+ entries: probe.entries,
+ windowStart: 0,
+ chainTotal: probe.entries.length,
+ };
+ }
+ if (tailWindow === undefined || probe.matchingCount === null) {
+ const all = await this.fetchAllSessionLogs(watcher, probe.entries);
+ return all
+ ? { entries: all, windowStart: 0, chainTotal: all.length }
+ : null;
+ }
+ const tailStart = Math.max(
+ 0,
+ Math.min(
+ probe.matchingCount - tailWindow,
+ options.coverFromOffset ?? Number.POSITIVE_INFINITY,
+ ),
+ );
+ const entries: 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 in the window.
+ let chainEnd = probe.matchingCount;
+ while (offset < chainEnd) {
+ const page = await this.fetchSessionLogsPage(
+ watcher,
+ offset,
+ Math.min(SESSION_LOG_PAGE_LIMIT, chainEnd - offset),
+ );
+ if (!page) return null;
+ if (page.entries.length === 0) break;
+ entries.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_LOG_PAGE_LIMIT;
+ }
+ }
+ return {
+ entries,
+ windowStart: tailStart,
+ chainTotal: tailStart + entries.length,
+ };
+ }
+
private async fetchArchivedLogs(
logUrl: string,
): Promise<StoredLogEntry[] | null> {
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts b/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts
index cfc226b398d4..4e08e4e29ca3 100644
--- a/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts
+++ b/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts
@@ -1,3 +1,4 @@
+import { TRANSCRIPT_TAIL_WINDOW } from "@posthog/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CloudTaskEvent } from "./schemas";
@@ -111,6 +112,7 @@ describe("CloudTaskEngine", () => {
analytics: analyticsMock as never,
logger: loggerMock,
streamFetch: fetchRouter,
+ transcriptTailWindow: TRANSCRIPT_TAIL_WINDOW,
});
mockNetFetch.mockReset();
mockStreamFetch.mockReset();
@@ -354,6 +356,279 @@ describe("CloudTaskEngine", () => {
);
});
+ it.each([
+ { name: "active", status: "in_progress" as const },
+ { name: "terminal", status: "completed" as const },
+ ])(
+ "bootstraps a long $name run from the tail window with the chain total",
+ async ({ status }) => {
+ const updates: unknown[] = [];
+ service.on(CloudTaskEvent.Update, (payload) => updates.push(payload));
+
+ const chain = Array.from({ length: 4500 }, (_, i) => ({
+ type: "notification",
+ timestamp: "2026-01-01T00:00:00Z",
+ notification: { jsonrpc: "2.0", method: `entry-${i}` },
+ }));
+ const tailStart = chain.length - TRANSCRIPT_TAIL_WINDOW;
+ const logRequests: Array<{ offset: number; limit: number }> = [];
+ mockNetFetch.mockImplementation((input: string | URL | Request) => {
+ const url = new URL(
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url,
+ );
+ if (!url.pathname.includes("/session_logs/")) {
+ return Promise.resolve(
+ createJsonResponse({
+ id: "run-1",
+ status,
+ stage: null,
+ output: null,
+ error_message: null,
+ branch: null,
+ updated_at: "2026-01-01T00:00:00Z",
+ }),
+ );
+ }
+ const offset = Number(url.searchParams.get("offset") ?? "0");
+ const limit = Number(url.searchParams.get("limit"));
+ logRequests.push({ offset, limit });
+ const page = chain.slice(offset, offset + limit);
+ return Promise.resolve(
+ createJsonResponse(page, 200, {
+ "X-Has-More": String(offset + page.length < chain.length),
+ "X-Matching-Count": String(chain.length),
+ }),
+ );
+ });
+ mockStreamFetch.mockResolvedValue(createOpenSseResponse(""));
+
+ service.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ });
+
+ await waitFor(() =>
+ updates.some((u) => (u as { kind?: string }).kind === "snapshot"),
+ );
+
+ const snapshot = updates.find(
+ (u) => (u as { kind?: string }).kind === "snapshot",
+ ) as {
+ newEntries: unknown[];
+ totalEntryCount: number;
+ windowStart?: number;
+ };
+ expect(snapshot.windowStart).toBe(tailStart);
+ expect(snapshot.totalEntryCount).toBe(chain.length);
+ expect(snapshot.newEntries).toHaveLength(TRANSCRIPT_TAIL_WINDOW);
+ expect(snapshot.newEntries[0]).toEqual(chain[tailStart]);
+ expect(logRequests).toEqual([
+ { offset: 0, limit: 1 },
+ { offset: tailStart, limit: TRANSCRIPT_TAIL_WINDOW },
+ ]);
+ },
+ );
+
+ it("sends a host without a tail window the whole chain", async () => {
+ const scopedLog = {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+ // A host that renders a snapshot as the complete transcript, with no way
+ // to page older history in, must not be handed a window.
+ const unwindowedService = createCloudTaskEngine({
+ auth: mockAuthService as never,
+ analytics: { track: vi.fn() } as never,
+ logger: { ...scopedLog, scope: vi.fn(() => scopedLog) },
+ streamFetch: fetchRouter,
+ });
+ const updates: unknown[] = [];
+ unwindowedService.on(CloudTaskEvent.Update, (payload) =>
+ updates.push(payload),
+ );
+
+ const chain = Array.from({ length: TRANSCRIPT_TAIL_WINDOW + 500 }, () => ({
+ type: "notification",
+ timestamp: "2026-01-01T00:00:00Z",
+ notification: { jsonrpc: "2.0", method: "_posthog/console" },
+ }));
+ mockNetFetch.mockImplementation((input: string | URL | Request) => {
+ const url = new URL(
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url,
+ );
+ if (!url.pathname.includes("/session_logs/")) {
+ return Promise.resolve(
+ createJsonResponse({
+ id: "run-1",
+ status: "in_progress",
+ stage: null,
+ output: null,
+ error_message: null,
+ branch: null,
+ updated_at: "2026-01-01T00:00:00Z",
+ }),
+ );
+ }
+ const offset = Number(url.searchParams.get("offset") ?? "0");
+ const limit = Number(url.searchParams.get("limit"));
+ const page = chain.slice(offset, offset + limit);
+ return Promise.resolve(
+ createJsonResponse(page, 200, {
+ "X-Has-More": String(offset + page.length < chain.length),
+ "X-Matching-Count": String(chain.length),
+ }),
+ );
+ });
+ mockStreamFetch.mockResolvedValue(createOpenSseResponse(""));
+
+ unwindowedService.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ });
+
+ await waitFor(() =>
+ updates.some((u) => (u as { kind?: string }).kind === "snapshot"),
+ );
+
+ const snapshot = updates.find(
+ (u) => (u as { kind?: string }).kind === "snapshot",
+ ) as { newEntries: unknown[]; windowStart?: number };
+ expect(snapshot.windowStart).toBeUndefined();
+ expect(snapshot.newEntries).toHaveLength(chain.length);
+ unwindowedService.unwatchAll();
+ });
+
+ it("replays a window that still covers entries the chain grew past", async () => {
+ const scopedLog = {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+ const smallWindowService = createCloudTaskEngine({
+ auth: mockAuthService as never,
+ analytics: { track: vi.fn() } as never,
+ logger: { ...scopedLog, scope: vi.fn(() => scopedLog) },
+ streamFetch: fetchRouter,
+ transcriptTailWindow: 3,
+ });
+ const updates: unknown[] = [];
+ smallWindowService.on(CloudTaskEvent.Update, (payload) =>
+ updates.push(payload),
+ );
+
+ const entry = (message: string): Record<string, unknown> => ({
+ type: "notification",
+ timestamp: "2026-01-01T00:00:00Z",
+ notification: {
+ jsonrpc: "2.0",
+ method: "_posthog/console",
+ params: { sessionId: "run-1", level: "info", message },
+ },
+ });
+ const streamed = ["live-1", "live-2", "live-3"].map(entry);
+ // Persisted without ever being emitted: a read-leg switch drops the
+ // stream cursor and leaves the next snapshot to cover the gap.
+ const unemitted = ["gap-1", "gap-2"].map(entry);
+ const chain = [entry("history-0")];
+
+ mockNetFetch.mockImplementation((input: string | URL | Request) => {
+ const url = new URL(
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url,
+ );
+ if (!url.pathname.includes("/session_logs/")) {
+ return Promise.resolve(
+ createJsonResponse({
+ id: "run-1",
+ status: "in_progress",
+ stage: null,
+ output: null,
+ error_message: null,
+ branch: null,
+ updated_at: "2026-01-01T00:00:00Z",
+ }),
+ );
+ }
+ const offset = Number(url.searchParams.get("offset") ?? "0");
+ const limit = Number(url.searchParams.get("limit"));
+ const page = chain.slice(offset, offset + limit);
+ return Promise.resolve(
+ createJsonResponse(page, 200, {
+ "X-Has-More": String(offset + page.length < chain.length),
+ "X-Matching-Count": String(chain.length),
+ }),
+ );
+ });
+ mockStreamFetch.mockResolvedValue(
+ createOpenSseResponse(
+ streamed
+ .map((e, i) => `id: ${i + 1}\ndata: ${JSON.stringify(e)}\n\n`)
+ .join(""),
+ ),
+ );
+
+ smallWindowService.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ });
+
+ await waitFor(() =>
+ updates.some(
+ (u) => (u as { totalEntryCount?: number }).totalEntryCount === 4,
+ ),
+ );
+
+ chain.push(...streamed, ...unemitted);
+ smallWindowService.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ });
+
+ await waitFor(() =>
+ updates.some(
+ (u) =>
+ (u as { kind?: string }).kind === "snapshot" &&
+ (u as { windowStart?: number }).windowStart !== undefined,
+ ),
+ );
+
+ const replayed = updates.find(
+ (u) =>
+ (u as { kind?: string }).kind === "snapshot" &&
+ (u as { windowStart?: number }).windowStart !== undefined,
+ ) as {
+ newEntries: unknown[];
+ totalEntryCount: number;
+ windowStart: number;
+ };
+ expect(replayed.windowStart).toBe(1);
+ expect(replayed.newEntries).toEqual(chain.slice(1));
+ expect(replayed.totalEntryCount).toBe(chain.length);
+ smallWindowService.unwatchAll();
+ });
+
it("replays a resumed run stream so hydration cannot miss its live tail", async () => {
const updates: unknown[] = [];
service.on(CloudTaskEvent.Update, (payload) => updates.push(payload));
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task.ts b/products/desktop/packages/core/src/cloud-task/cloud-task.ts
index 1e2003d85a1d..b1ced3f888d1 100644
--- a/products/desktop/packages/core/src/cloud-task/cloud-task.ts
+++ b/products/desktop/packages/core/src/cloud-task/cloud-task.ts
@@ -3,6 +3,7 @@ import {
ANALYTICS_SERVICE,
type IAnalytics,
} from "@posthog/platform/analytics";
+import { TRANSCRIPT_TAIL_WINDOW } from "@posthog/shared";
import { inject, injectable, optional, preDestroy } from "inversify";
import { CloudTaskEngine } from "./cloud-task-engine";
import {
@@ -25,7 +26,14 @@ export class CloudTaskService extends CloudTaskEngine {
@optional()
mcpRelayExecutor: McpRelayExecutor | null = null,
) {
- super({ auth, analytics, logger, mcpRelayExecutor });
+ // The desktop renderer pages older history in from `windowStart`.
+ super({
+ auth,
+ analytics,
+ logger,
+ mcpRelayExecutor,
+ transcriptTailWindow: TRANSCRIPT_TAIL_WINDOW,
+ });
}
@preDestroy()
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 0aee3b7e1218..f9ca7a8bf023 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -48,6 +48,7 @@ import {
sessionSupportsNativeSteer,
type TaskRunArtifact,
type TaskRunStatus,
+ TRANSCRIPT_TAIL_WINDOW,
} from "@posthog/shared";
import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";
import {
@@ -268,9 +269,6 @@ interface CloudHydrationResult {
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;
@@ -6439,17 +6437,25 @@ export class SessionService {
const watcher = this.cloudTaskWatchers.get(taskId);
const resumeHistoryCountOffset =
watcher?.runId === runId ? (watcher.resumeHistoryCountOffset ?? 0) : 0;
- const normalizedUpdate: CloudTaskUpdatePayload =
+ let normalizedUpdate: CloudTaskUpdatePayload = update;
+ if (
resumeHistoryCountOffset > 0 &&
(update.kind === "logs" || update.kind === "snapshot")
- ? {
- ...update,
- totalEntryCount: Math.max(
- 0,
- update.totalEntryCount - resumeHistoryCountOffset,
- ),
- }
- : update;
+ ) {
+ normalizedUpdate = {
+ ...update,
+ totalEntryCount: Math.max(
+ 0,
+ update.totalEntryCount - resumeHistoryCountOffset,
+ ),
+ };
+ // The offset makes the count leaf-relative while windowStart stays
+ // chain-relative; a windowed commit would mix the two units, so gaps
+ // on resume watchers keep falling back to the reconciler.
+ if (normalizedUpdate.kind === "snapshot") {
+ normalizedUpdate.windowStart = undefined;
+ }
+ }
// Evaluate staleness before handleCloudTaskUpdate mutates cloudStatus:
// a late non-terminal update must not re-notify after the run settled.
const isStaleNonTerminalStatus = this.isStaleNonTerminalCloudUpdate(
@@ -6706,7 +6712,7 @@ 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.
+ * TRANSCRIPT_TAIL_WINDOW entries are fetched; older pages load on scroll.
* Null on failure.
*/
private async fetchChainTranscriptWindow(
@@ -6738,7 +6744,10 @@ export class SessionService {
chainTotal: result.truncatedHeadCount + result.entries.length,
};
}
- const tailStart = Math.max(0, probe.matchingCount - INITIAL_TAIL_WINDOW);
+ const tailStart = Math.max(
+ 0,
+ probe.matchingCount - TRANSCRIPT_TAIL_WINDOW,
+ );
const tail: StoredLogEntry[] = [];
let offset = tailStart;
// The probe's count is a snapshot, and a run whose log is still being
@@ -7000,9 +7009,37 @@ export class SessionService {
}
}
} else {
- const parsed = await this.fetchSessionLogs(logUrl, taskRunId);
- rawEntries = parsed.rawEntries;
- liveStreamLineCount = parsed.totalLineCount;
+ // The local cache read is free and offline-safe, so it keeps priority;
+ // a cache miss fetches only the newest window of the persisted chain
+ // instead of the whole log file. The full S3 read survives as the
+ // fallback for old servers and auth that is still restoring.
+ const local = await this.fetchSessionLogs(undefined, taskRunId);
+ if (local.rawEntries.length > 0) {
+ rawEntries = local.rawEntries;
+ liveStreamLineCount = local.totalLineCount;
+ } else {
+ const authStatus = await this.getAuthCredentialsStatus();
+ const window =
+ authStatus.kind === "ready"
+ ? await this.fetchChainTranscriptWindow(
+ authStatus.auth.client,
+ taskId,
+ taskRunId,
+ )
+ : null;
+ // An empty persisted chain can trail an S3 log that already has
+ // entries (persistence lag), so only a non-empty window short-circuits
+ // the full read.
+ if (window && window.entries.length > 0) {
+ transcriptWindow = window;
+ rawEntries = window.entries;
+ liveStreamLineCount = window.chainTotal;
+ } else {
+ const parsed = await this.fetchSessionLogs(logUrl, taskRunId);
+ rawEntries = parsed.rawEntries;
+ liveStreamLineCount = parsed.totalLineCount;
+ }
+ }
}
const session = this.d.store.getSessionByTaskId(taskId);
@@ -7061,8 +7098,12 @@ export class SessionService {
const hasOptimisticUserPrompt = session.optimisticItems.some(
(item) => item.type === "user_message",
);
+ // A windowed transcript legitimately lacks its head prompt (it sits
+ // behind the window), so the placeholder only seeds when the head is
+ // actually visible; resume seeds are tail placeholders and unaffected.
if (
!isTerminalRun &&
+ (isResumeRun || windowStart === 0) &&
!hasCurrentRunUserPrompt &&
!hasOptimisticUserPrompt &&
seedContent?.trim()
@@ -8373,6 +8414,20 @@ export class SessionService {
this.updatePromptStateFromEvents(taskRunId, newEvents, {
isLive: update.kind === "logs",
});
+ } else if (
+ update.kind === "snapshot" &&
+ update.windowStart !== undefined &&
+ update.windowStart > 0
+ ) {
+ // A gap below a windowed snapshot lies entirely behind the window
+ // (the window always reaches the chain's end), so the window itself
+ // is the authoritative fill; older entries stay loadable on scroll.
+ // The reconciler's full-log fetch stays for gaps in live batches.
+ this.commitWindowedCloudSnapshot(
+ taskRunId,
+ update.newEntries,
+ update.windowStart,
+ );
} else {
this.cloudLogGapReconciler.reconcile({
taskId: update.taskId,
@@ -8863,6 +8918,31 @@ export class SessionService {
this.updatePromptStateFromEvents(taskRunId, events);
}
+ private commitWindowedCloudSnapshot(
+ taskRunId: string,
+ entries: StoredLogEntry[],
+ windowStart: number,
+ ): void {
+ const events = convertStoredEntriesToEvents(entries, undefined, {
+ taskRunId,
+ startEntryIndex: windowStart,
+ });
+ if (hasSessionPromptEvent(events)) {
+ this.d.store.clearTailOptimisticItems(taskRunId);
+ }
+ this.cloudRunIdleTracker.delete(taskRunId);
+ // Moving the window start also trips loadOlderCloudTranscript's
+ // stale-window guard if a prepend was in flight, instead of duplicating
+ // entries this commit already covers.
+ this.d.store.updateSession(taskRunId, {
+ events,
+ isCloud: true,
+ processedLineCount: windowStart + entries.length,
+ transcriptWindowStart: windowStart,
+ });
+ this.updatePromptStateFromEvents(taskRunId, events);
+ }
+
private getSessionByRunId(taskRunId: string): AgentSession | undefined {
const sessions = this.d.store.getSessions();
return sessions[taskRunId];
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index 52aa8327bbbe..c0ad51f66374 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -461,6 +461,10 @@ export interface CloudTaskSnapshotUpdate extends CloudTaskUpdateBase {
kind: "snapshot";
newEntries: StoredLogEntry[];
totalEntryCount: number;
+ /** Chain index of newEntries[0] when the snapshot is a tail window rather
+ * than the full history; older entries page in on demand. Absent means
+ * the snapshot starts at the head of the chain. */
+ windowStart?: number;
status?: TaskRunStatus;
stage?: string | null;
output?: Record<string, unknown> | null;
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 1f0deec33194..b078e739c00e 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -323,6 +323,7 @@ export {
type SessionStatus,
sendableQueuePrefixLength,
sessionSupportsNativeSteer,
+ TRANSCRIPT_TAIL_WINDOW,
} from "./sessions";
export type {
SignalReportOrderingField,
diff --git a/products/desktop/packages/shared/src/sessions.ts b/products/desktop/packages/shared/src/sessions.ts
index 8d5933a29e66..2626e0202e16 100644
--- a/products/desktop/packages/shared/src/sessions.ts
+++ b/products/desktop/packages/shared/src/sessions.ts
@@ -14,6 +14,9 @@ import type { AcpMessage } from "./session-events";
export type { Adapter };
+/** Entries the first paint of a big transcript renders; the rest pages in on scroll. */
+export const TRANSCRIPT_TAIL_WINDOW = 2000;
+
export type PermissionRequest = Omit<RequestPermissionRequest, "sessionId"> & {
taskRunId: string;
receivedAt: number;
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
index 3b08ab6cd71a..f00f8733f722 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -136,7 +136,6 @@ const mockAuthenticatedClient = vi.hoisted(() => ({
finalizeTaskStagedArtifactUploads: vi.fn(),
presignTaskRunArtifact: vi.fn(),
startGithubUserIntegrationConnect: vi.fn(),
- getTaskRunSessionLogs: vi.fn(),
getTaskRunSessionLogsResult: vi.fn(),
getTaskRunSessionLogsPage: vi.fn(),
}));
@@ -498,7 +497,6 @@ describe("SessionService", () => {
mockGetIsOnline.mockReturnValue(true);
mockGetConfigOptionByCategory.mockReturnValue(undefined);
mockBuildAuthenticatedClient.mockReturnValue(mockAuthenticatedClient);
- mockAuthenticatedClient.getTaskRunSessionLogs.mockResolvedValue([]);
mockSessionConfigStore.getPersistedConfigOptions.mockReturnValue(undefined);
mockAdapterFns.getAdapter.mockReturnValue(undefined);
mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({
@@ -1940,6 +1938,204 @@ describe("SessionService", () => {
);
});
+ it("hydrates an uncached in-progress run from the transcript window, not the full log", 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,
+ });
+ mockTrpcLogs.readLocalLogs.query.mockResolvedValue("");
+ 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,
+ };
+ },
+ );
+
+ service.watchCloudTask(
+ "task-123",
+ "run-123",
+ "https://api.anthropic.com",
+ 123,
+ undefined,
+ "https://example.com/logs/run-123",
+ "do the thing",
+ "claude",
+ undefined,
+ undefined,
+ undefined,
+ "in_progress",
+ );
+
+ await vi.waitFor(() => {
+ expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(
+ "run-123",
+ expect.objectContaining({
+ transcriptWindowStart: 10000,
+ cloudTranscriptEntryCount: 12000,
+ processedLineCount: 12000,
+ }),
+ );
+ });
+ expect(mockTrpcLogs.fetchS3Logs.query).not.toHaveBeenCalled();
+ // The run's prompt sits behind the window, not missing; a pinned
+ // placeholder would double it once older pages load.
+ expect(
+ mockSessionStoreSetters.appendOptimisticItem,
+ ).not.toHaveBeenCalled();
+ });
+
+ it("commits a windowed snapshot at its offset instead of refetching the whole log", () => {
+ const service = getSessionService();
+ const session = createMockSession({
+ taskId: "task-123",
+ taskRunId: "run-123",
+ cloudStatus: "in_progress",
+ isCloud: true,
+ events: [],
+ processedLineCount: 0,
+ });
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);
+ mockSessionStoreSetters.getSessions.mockReturnValue({
+ "run-123": session,
+ });
+ 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,
+ );
+
+ const subscribeOptions = mockTrpcCloudTask.onUpdate.subscribe.mock
+ .calls[0][1] as {
+ onData: (update: unknown) => void;
+ };
+ const windowEntries = [
+ { timestamp: "2024-01-01T00:00:00Z", notification: {} },
+ { timestamp: "2024-01-01T00:00:01Z", notification: {} },
+ ];
+ subscribeOptions.onData({
+ kind: "snapshot",
+ taskId: "task-123",
+ runId: "run-123",
+ newEntries: windowEntries,
+ totalEntryCount: 5000,
+ windowStart: 4998,
+ });
+
+ expect(mockConvertStoredEntriesToEvents).toHaveBeenCalledWith(
+ windowEntries,
+ undefined,
+ { taskRunId: "run-123", startEntryIndex: 4998 },
+ );
+ expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(
+ "run-123",
+ expect.objectContaining({
+ transcriptWindowStart: 4998,
+ processedLineCount: 5000,
+ }),
+ );
+ expect(mockTrpcLogs.fetchS3Logs.query).not.toHaveBeenCalled();
+ });
+
+ it("keeps paged-in older history when a windowed snapshot overlaps the transcript", () => {
+ const service = getSessionService();
+ const session = createMockSession({
+ taskId: "task-123",
+ taskRunId: "run-123",
+ cloudStatus: "in_progress",
+ isCloud: true,
+ events: [],
+ processedLineCount: 5000,
+ transcriptWindowStart: 4000,
+ });
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);
+ mockSessionStoreSetters.getSessions.mockReturnValue({
+ "run-123": session,
+ });
+ 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,
+ );
+
+ const subscribeOptions = mockTrpcCloudTask.onUpdate.subscribe.mock
+ .calls[0][1] as {
+ onData: (update: unknown) => void;
+ };
+ const windowEntries = Array.from({ length: 4 }, (_, i) => ({
+ timestamp: `2024-01-01T00:00:0${i}Z`,
+ notification: {},
+ }));
+ subscribeOptions.onData({
+ kind: "snapshot",
+ taskId: "task-123",
+ runId: "run-123",
+ newEntries: windowEntries,
+ totalEntryCount: 5002,
+ windowStart: 4998,
+ });
+
+ expect(mockSessionStoreSetters.appendEvents).toHaveBeenCalledWith(
+ "run-123",
+ expect.any(Array),
+ 5002,
+ );
+ expect(mockSessionStoreSetters.updateSession).not.toHaveBeenCalledWith(
+ "run-123",
+ expect.objectContaining({ events: expect.anything() }),
+ );
+ expect(mockSessionStoreSetters.updateSession).not.toHaveBeenCalledWith(
+ "run-123",
+ expect.objectContaining({ transcriptWindowStart: expect.anything() }),
+ );
+ });
+
it("waits out a restoring auth before hydrating instead of bailing", async () => {
const service = getSessionService();
const session = createMockSession({
@@ -2203,7 +2399,6 @@ describe("SessionService", () => {
mockSessionStoreSetters.getSessions.mockReturnValue({
"run-123": session,
});
- mockAuthenticatedClient.getTaskRunSessionLogs.mockResolvedValue([]);
mockTrpcLogs.readLocalLogs.query.mockResolvedValue("");
mockTrpcLogs.fetchS3Logs.query.mockResolvedValue(
JSON.stringify({
@@ -2279,7 +2474,6 @@ describe("SessionService", () => {
mockSessionStoreSetters.getSessions.mockReturnValue({
"run-123": session,
});
- mockAuthenticatedClient.getTaskRunSessionLogs.mockResolvedValue([]);
mockTrpcLogs.readLocalLogs.query.mockResolvedValue("");
mockTrpcLogs.fetchS3Logs.query.mockResolvedValue("");