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.

fix(desktop): rebuild the cloud run watch on a trimmed stream cursor (#101105)

Alessandro Pogliaghidf10f512e79a
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 e65fc5b86f63..4dc30f90be7f 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
@@ -47,6 +47,18 @@ const EVENT_BATCH_FLUSH_MS = 16;
const EVENT_BATCH_MAX_SIZE = 50;
const SESSION_LOG_PAGE_LIMIT = 5_000;
const ARCHIVED_LOG_FETCH_TIMEOUT_MS = 15_000;
+const BOOTSTRAP_FETCH_TIMEOUT_MS = 30_000;
+const BOOTSTRAP_FETCH_ATTEMPTS = 3;
+const BOOTSTRAP_FETCH_RETRY_DELAY_MS = 1_000;
+
+function createBootstrapTimeout(): { signal: AbortSignal; clear: () => void } {
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () => controller.abort(),
+ BOOTSTRAP_FETCH_TIMEOUT_MS,
+ );
+ return { signal: controller.signal, clear: () => clearTimeout(timer) };
+}
const MAX_HANDLED_RELAY_REQUEST_IDS = 1_000;
const MCP_RELAY_METHODS_WITHOUT_APPROVAL = new Set([
"initialize",
@@ -61,6 +73,7 @@ const MCP_RELAY_METHODS_WITHOUT_APPROVAL = new Set([
// Authoritative end-of-stream sentinel, matched on the SSE event name (event.event, not data.type).
// The client stops on it without consulting run status.
const STREAM_END_EVENT_NAME = "stream-end";
+const END_EVENT_NAME = "end";
interface SessionLogsPage {
entries: StoredLogEntry[];
@@ -167,14 +180,19 @@ interface WatcherState {
isBootstrapping: boolean;
hasEmittedSnapshot: boolean;
bufferedLogBatches: StoredLogEntry[][];
+ replayDedupMatcher: HistoricalEntryMatcher | null;
// Live entries emitted since the last snapshot, retained so a re-subscribe snapshot can reconcile
// entries the server has not persisted yet. emitCurrentSnapshot trims this to the still-missing
- // set; with no re-subscribe it holds the run's emitted entries until the watch ends.
+ // set; with no re-subscribe it holds the run's emitted entries until the watch ends, capped at
+ // the tail window so a rebuild never has to reach back over the whole run.
emittedLogEntries: StoredLogEntry[];
+ emittedFromEntryCount: number;
failed: boolean;
needsPostBootstrapReconnect: boolean;
needsStopAfterBootstrap: boolean;
streamEnded: boolean;
+ needsResync: boolean;
+ pendingStreamWindowReplay: boolean;
// Consumes one automatic re-bootstrap recovery; re-armed by a data event or healthy connection.
selfHealAttempted: boolean;
// Both streamBaseUrl and streamReadToken non-null => read via the agent-proxy; either null => Django.
@@ -331,6 +349,14 @@ function relayApprovalRequest(
};
}
+function isResyncEndEvent(data: unknown): boolean {
+ return (
+ typeof data === "object" &&
+ data !== null &&
+ (data as { type?: string }).type === "resync"
+ );
+}
+
function isKeepaliveEvent(event: SseEvent): boolean {
return (
event.event === "keepalive" ||
@@ -444,6 +470,70 @@ function filterEntriesNotInFrequencyMap(
});
}
+function parseAgentEventId(
+ eventId: string,
+): { boot: string; sequence: number } | null {
+ const match = /^(.+)-(\d+)$/.exec(eventId);
+ if (!match) {
+ return null;
+ }
+ const sequence = Number(match[2]);
+ return Number.isSafeInteger(sequence) ? { boot: match[1], sequence } : null;
+}
+
+class HistoricalEntryMatcher {
+ private readonly counts: Map<string, number>;
+ private readonly coveredIds = new Set<string>();
+ private readonly coveredRanges = new Map<
+ string,
+ Array<{ first: number; last: number }>
+ >();
+
+ constructor(historicalEntries: StoredLogEntry[]) {
+ this.counts = buildEntryFrequencyMap(historicalEntries);
+ for (const entry of historicalEntries) {
+ if (Array.isArray(entry.covered_event_ids)) {
+ for (const covered of entry.covered_event_ids) {
+ if (typeof covered === "string") this.coveredIds.add(covered);
+ }
+ }
+ if (typeof entry.event_id !== "string") continue;
+ this.coveredIds.add(entry.event_id);
+ if (typeof entry.first_event_id !== "string") continue;
+ this.coveredIds.add(entry.first_event_id);
+ const first = parseAgentEventId(entry.first_event_id);
+ const last = parseAgentEventId(entry.event_id);
+ if (
+ first &&
+ last &&
+ first.boot === last.boot &&
+ first.sequence <= last.sequence
+ ) {
+ const ranges = this.coveredRanges.get(first.boot) ?? [];
+ ranges.push({ first: first.sequence, last: last.sequence });
+ this.coveredRanges.set(first.boot, ranges);
+ }
+ }
+ }
+
+ filterUnmatched(entries: StoredLogEntry[]): StoredLogEntry[] {
+ return filterEntriesNotInFrequencyMap(
+ entries.filter((entry) => !this.coversEventId(entry.event_id)),
+ this.counts,
+ );
+ }
+
+ private coversEventId(eventId: string | undefined): boolean {
+ if (!eventId) return false;
+ if (this.coveredIds.has(eventId)) return true;
+ const parsed = parseAgentEventId(eventId);
+ if (!parsed) return false;
+ return (this.coveredRanges.get(parsed.boot) ?? []).some(
+ ({ first, last }) => first <= parsed.sequence && parsed.sequence <= last,
+ );
+ }
+}
+
function extractSandboxAlive(
state: Record<string, unknown> | null | undefined,
): boolean | null | undefined {
@@ -1079,9 +1169,12 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
watcher.failed = false;
watcher.pendingLogEntries = [];
watcher.bufferedLogBatches = [];
+ watcher.replayDedupMatcher = null;
watcher.needsPostBootstrapReconnect = false;
watcher.needsStopAfterBootstrap = false;
watcher.streamEnded = false;
+ watcher.needsResync = false;
+ watcher.pendingStreamWindowReplay = false;
watcher.selfHealAttempted = false;
watcher.lastEventId = null;
watcher.lastEventIdLeg = null;
@@ -1092,6 +1185,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
// snapshot re-delivers history, so no dedup state is lost.
watcher.seenEventIds.clear();
watcher.totalEntryCount = 0;
+ watcher.resumeFromEntryCount = null;
watcher.isBootstrapping = false;
watcher.streamTargetResolved = false;
watcher.streamBaseUrl = null;
@@ -1315,11 +1409,15 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
isBootstrapping: false,
hasEmittedSnapshot: false,
bufferedLogBatches: [],
+ replayDedupMatcher: null,
emittedLogEntries: [],
+ emittedFromEntryCount: 0,
failed: false,
needsPostBootstrapReconnect: false,
needsStopAfterBootstrap: false,
streamEnded: false,
+ needsResync: false,
+ pendingStreamWindowReplay: false,
selfHealAttempted: false,
streamTargetResolved: false,
streamBaseUrl: null,
@@ -1360,7 +1458,32 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
this.log.info("Cloud task watcher stopped", { key });
}
- private async bootstrapWatcher(key: string): Promise<void> {
+ private async retryBootstrapFetch<T>(
+ key: string,
+ watcher: WatcherState,
+ fetchOnce: () => Promise<T | null>,
+ ): Promise<T | null> {
+ for (let attempt = 1; ; attempt += 1) {
+ const result = await fetchOnce();
+ if (result) return result;
+ if (
+ attempt >= BOOTSTRAP_FETCH_ATTEMPTS ||
+ this.watchers.get(key) !== watcher ||
+ watcher.failed
+ ) {
+ return null;
+ }
+ await new Promise((resolve) =>
+ setTimeout(resolve, BOOTSTRAP_FETCH_RETRY_DELAY_MS * attempt),
+ );
+ if (this.watchers.get(key) !== watcher || watcher.failed) return null;
+ }
+ }
+
+ private async bootstrapWatcher(
+ key: string,
+ options: { coverFromOffset?: number } = {},
+ ): Promise<void> {
const watcher = this.watchers.get(key);
if (!watcher) return;
@@ -1368,7 +1491,9 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
watcher.needsPostBootstrapReconnect = false;
watcher.needsStopAfterBootstrap = false;
- const run = await this.fetchTaskRun(watcher);
+ const run = await this.retryBootstrapFetch(key, watcher, () =>
+ this.fetchTaskRun(watcher),
+ );
const currentWatcher = this.watchers.get(key);
if (!currentWatcher || currentWatcher !== watcher) return;
if (watcher.failed) return;
@@ -1398,7 +1523,9 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
}
if (isTerminalStatus(run.status)) {
- let window = await this.fetchSessionLogsWindow(watcher);
+ let window = await this.retryBootstrapFetch(key, watcher, () =>
+ 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.
@@ -1421,6 +1548,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
return;
}
+ const rebuilt = watcher.hasEmittedSnapshot;
watcher.totalEntryCount = window.chainTotal;
watcher.hasEmittedSnapshot = true;
this.emit(CloudTaskEvent.Update, {
@@ -1430,6 +1558,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
newEntries: window.entries,
totalEntryCount: watcher.totalEntryCount,
...(window.windowStart > 0 ? { windowStart: window.windowStart } : {}),
+ ...(rebuilt ? { rebuilt: true } : {}),
status: watcher.lastStatus ?? undefined,
stage: watcher.lastStage,
output: watcher.lastOutput,
@@ -1441,11 +1570,21 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
return;
}
+ const replayingStreamWindow = watcher.pendingStreamWindowReplay;
watcher.isBootstrapping = true;
watcher.bufferedLogBatches = [];
- void this.connectSse(key, { startLatest: true });
+ void this.connectSse(key, {
+ startLatest: !replayingStreamWindow,
+ });
- const window = await this.fetchSessionLogsWindow(watcher);
+ const window = await this.retryBootstrapFetch(key, watcher, () =>
+ this.fetchSessionLogsWindow(
+ watcher,
+ options.coverFromOffset === undefined
+ ? {}
+ : { coverFromOffset: options.coverFromOffset },
+ ),
+ );
const bootstrappingWatcher = this.watchers.get(key);
if (!bootstrappingWatcher || bootstrappingWatcher !== watcher) return;
if (watcher.failed) return;
@@ -1462,16 +1601,35 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
// Flush any pending live entries into the bootstrap buffer before snapshot.
this.flushLogBatch(key);
- watcher.totalEntryCount = window.chainTotal;
+ const { snapshotEntries, missingEmittedEntries } =
+ this.mergeHistoricalAndEmittedEntries(
+ window.entries,
+ watcher.emittedLogEntries,
+ );
+ const rebuilt = watcher.hasEmittedSnapshot;
+ if (rebuilt) {
+ this.log.info("Cloud task watcher rebuilt from history", {
+ key,
+ windowStart: window.windowStart,
+ historyEntries: window.entries.length,
+ emittedEntries: watcher.emittedLogEntries.length,
+ retainedEmittedEntries: missingEmittedEntries.length,
+ bufferedBatches: watcher.bufferedLogBatches.length,
+ });
+ }
+ watcher.emittedLogEntries = missingEmittedEntries;
+ watcher.emittedFromEntryCount = window.windowStart + window.entries.length;
+ watcher.totalEntryCount = window.windowStart + snapshotEntries.length;
watcher.hasEmittedSnapshot = true;
this.emit(CloudTaskEvent.Update, {
taskId: watcher.taskId,
runId: watcher.runId,
kind: "snapshot",
- newEntries: window.entries,
+ newEntries: snapshotEntries,
totalEntryCount: watcher.totalEntryCount,
...(window.windowStart > 0 ? { windowStart: window.windowStart } : {}),
+ ...(rebuilt ? { rebuilt: true } : {}),
status: watcher.lastStatus ?? undefined,
stage: watcher.lastStage,
output: watcher.lastOutput,
@@ -1480,8 +1638,15 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
...sandboxAlivePayload(watcher),
});
+ const snapshotMatcher =
+ replayingStreamWindow || watcher.bufferedLogBatches.length > 0
+ ? new HistoricalEntryMatcher(snapshotEntries)
+ : null;
watcher.isBootstrapping = false;
- this.drainBufferedLogBatches(key, window.entries);
+ watcher.replayDedupMatcher = replayingStreamWindow ? snapshotMatcher : null;
+ if (snapshotMatcher) {
+ this.drainBufferedLogBatches(key, snapshotMatcher);
+ }
if (watcher.failed) {
return;
@@ -1646,6 +1811,9 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
// Captured after the leg-switch drop so they reflect what this connection actually sends.
watcher.connSentLastEventId = watcher.lastEventId;
const startLatest = Boolean(options?.startLatest && !watcher.lastEventId);
+ if (startLatest) {
+ watcher.replayDedupMatcher = null;
+ }
const url = new URL(
usingProxy
? `${base}/v1/runs/${encodeURIComponent(watcher.runId)}/stream`
@@ -1656,6 +1824,9 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
if (startLatest) {
url.searchParams.set("start", "latest");
}
+ if (usingProxy) {
+ url.searchParams.set("resync", "1");
+ }
const headers: Record<string, string> = {
Accept: "text/event-stream",
};
@@ -1931,6 +2102,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
if (event.id) {
watcher.lastEventId = event.id;
watcher.lastEventIdLeg = watcher.streamLeg;
+ watcher.pendingStreamWindowReplay = false;
}
if (event.event === "error") {
@@ -1952,6 +2124,19 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
// backend-error budget, which only a real data event below resets.
watcher.reconnectAttempts = 0;
+ if (event.event === END_EVENT_NAME) {
+ if (isResyncEndEvent(event.data)) {
+ this.log.info("Cloud task stream resume position trimmed, rebuilding", {
+ key,
+ lastEventId: watcher.lastEventId,
+ });
+ watcher.lastEventId = null;
+ watcher.lastEventIdLeg = null;
+ watcher.needsResync = true;
+ }
+ return null;
+ }
+
if (isKeepaliveEvent(event)) {
return null;
}
@@ -2052,14 +2237,22 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
watcher.batchFlushTimeoutId = null;
}
- const entries = watcher.pendingLogEntries;
+ const pending = watcher.pendingLogEntries;
watcher.pendingLogEntries = [];
if (watcher.isBootstrapping) {
- watcher.bufferedLogBatches.push(entries);
+ watcher.bufferedLogBatches.push(pending);
return;
}
+ let entries = pending;
+ const replayMatcher = watcher.replayDedupMatcher;
+ if (replayMatcher) {
+ entries = replayMatcher.filterUnmatched(pending);
+ if (entries.length === 0) return;
+ watcher.replayDedupMatcher = null;
+ }
+
watcher.totalEntryCount += entries.length;
this.rememberEmittedLogEntries(watcher, entries);
@@ -2074,23 +2267,21 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
private drainBufferedLogBatches(
key: string,
- historicalEntries: StoredLogEntry[],
+ matcher: HistoricalEntryMatcher,
): void {
const watcher = this.watchers.get(key);
if (!watcher || watcher.bufferedLogBatches.length === 0) return;
- const historicalCounts = buildEntryFrequencyMap(historicalEntries);
-
for (const entries of watcher.bufferedLogBatches) {
- const dedupedEntries = filterEntriesNotInFrequencyMap(
- entries,
- historicalCounts,
- );
+ const dedupedEntries = matcher.filterUnmatched(entries);
if (dedupedEntries.length === 0) {
continue;
}
+ if (watcher.replayDedupMatcher === matcher) {
+ watcher.replayDedupMatcher = null;
+ }
watcher.totalEntryCount += dedupedEntries.length;
this.rememberEmittedLogEntries(watcher, dedupedEntries);
this.emit(CloudTaskEvent.Update, {
@@ -2110,6 +2301,12 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
entries: StoredLogEntry[],
): void {
watcher.emittedLogEntries.push(...entries);
+ const retentionLimit = this.transcriptTailWindow;
+ if (retentionLimit === undefined) return;
+ const excess = watcher.emittedLogEntries.length - retentionLimit;
+ if (excess <= 0) return;
+ watcher.emittedLogEntries.splice(0, excess);
+ watcher.emittedFromEntryCount += excess;
}
private mergeHistoricalAndEmittedEntries(
@@ -2123,11 +2320,9 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
return { snapshotEntries: historicalEntries, missingEmittedEntries: [] };
}
- const historicalCounts = buildEntryFrequencyMap(historicalEntries);
- const missingEmittedEntries = filterEntriesNotInFrequencyMap(
- emittedEntries,
- historicalCounts,
- );
+ const missingEmittedEntries = new HistoricalEntryMatcher(
+ historicalEntries,
+ ).filterUnmatched(emittedEntries);
return {
snapshotEntries: [...historicalEntries, ...missingEmittedEntries],
@@ -2147,8 +2342,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
// 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,
+ coverFromOffset: watcher.emittedFromEntryCount,
});
const currentWatcher = this.watchers.get(key);
if (!currentWatcher || currentWatcher !== watcher || watcher.failed) {
@@ -2169,6 +2363,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
watcher.emittedLogEntries,
);
watcher.emittedLogEntries = missingEmittedEntries;
+ watcher.emittedFromEntryCount = window.windowStart + window.entries.length;
const snapshotTotal = window.windowStart + snapshotEntries.length;
if (snapshotTotal > watcher.totalEntryCount) {
watcher.totalEntryCount = snapshotTotal;
@@ -2222,6 +2417,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
watcher.isBootstrapping = false;
watcher.pendingLogEntries = [];
watcher.bufferedLogBatches = [];
+ watcher.replayDedupMatcher = null;
if (watcher.reconnectTimeoutId) {
clearTimeout(watcher.reconnectTimeoutId);
@@ -2330,7 +2526,9 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
currentWatcher.reconnectTimeoutId = null;
void this.connectSse(key, {
startLatest:
- currentWatcher.isBootstrapping || currentWatcher.hasEmittedSnapshot,
+ (currentWatcher.isBootstrapping ||
+ currentWatcher.hasEmittedSnapshot) &&
+ !currentWatcher.pendingStreamWindowReplay,
});
}, delay);
}
@@ -2352,6 +2550,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
// Bootstrap owns the snapshot lifecycle: stopping mid-bootstrap would discard the backlog and
// buffered live entries. Record intent and let bootstrap finish.
if (watcher.isBootstrapping) {
+ watcher.needsResync = false;
if (watcher.streamEnded || !reconnectOnDisconnect) {
watcher.needsStopAfterBootstrap = true;
} else {
@@ -2367,6 +2566,14 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
return;
}
+ if (watcher.needsResync) {
+ const coverFromOffset = watcher.emittedFromEntryCount;
+ this.resetWatcherForRebootstrap(watcher);
+ watcher.pendingStreamWindowReplay = true;
+ void this.bootstrapWatcher(key, { coverFromOffset });
+ return;
+ }
+
// Legacy mode (old server): no sentinel, so poll run status on disconnect to decide stop vs
// reconnect. The reconnect budgets keep the new semantics, so self-heal stays active here too.
if (!watcher.durableStreamEnabled && reconnectOnDisconnect) {
@@ -2493,11 +2700,13 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
url.searchParams.set("limit", limit.toString());
url.searchParams.set("offset", offset.toString());
+ const timeout = createBootstrapTimeout();
try {
const authedResponse = await this.auth.authenticatedFetch(
url.toString(),
{
method: "GET",
+ signal: timeout.signal,
},
);
@@ -2538,6 +2747,8 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
error,
});
return null;
+ } finally {
+ timeout.clear();
}
}
@@ -2658,7 +2869,7 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
watcher: WatcherState,
signal: AbortSignal,
): Promise<void> {
- const url = `${watcher.apiHost}/api/projects/${watcher.teamId}/tasks/${watcher.taskId}/runs/${watcher.runId}/stream_token/`;
+ const url = `${watcher.apiHost}/api/projects/${watcher.teamId}/tasks/${watcher.taskId}/runs/${watcher.runId}/stream_token/?resync=1`;
try {
const response = await this.auth.authenticatedFetch(url, {
method: "GET",
@@ -2724,9 +2935,11 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
): Promise<TaskRunResponse | null> {
const url = `${watcher.apiHost}/api/projects/${watcher.teamId}/tasks/${watcher.taskId}/runs/${watcher.runId}/`;
+ const timeout = createBootstrapTimeout();
try {
const authedResponse = await this.auth.authenticatedFetch(url, {
method: "GET",
+ signal: timeout.signal,
});
if (!authedResponse.ok) {
@@ -2752,6 +2965,8 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {
error,
});
return null;
+ } finally {
+ timeout.clear();
}
}
}
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 135eb1576f87..cbd1b1a5bdfa 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
@@ -77,6 +77,29 @@ function createOpenSseResponse(payload: string, status = 200): Response {
});
}
+function createControlledSseResponse(): {
+ response: Response;
+ push: (payload: string) => void;
+ close: () => void;
+} {
+ const encoder = new TextEncoder();
+ let controller!: ReadableStreamDefaultController<Uint8Array>;
+ const stream = new ReadableStream<Uint8Array>({
+ start(c) {
+ controller = c;
+ },
+ });
+
+ return {
+ response: new Response(stream, {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ }),
+ push: (payload: string) => controller.enqueue(encoder.encode(payload)),
+ close: () => controller.close(),
+ };
+}
+
async function waitFor(
predicate: () => boolean,
timeoutMs = 2_000,
@@ -261,6 +284,42 @@ describe("CloudTaskEngine", () => {
},
},
},
+ {
+ type: "notification",
+ timestamp: "2026-01-01T00:00:02Z",
+ event_id: "boot-2",
+ first_event_id: "boot-1",
+ covered_event_ids: 5 as unknown as string[],
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "agent_message",
+ content: { type: "text", text: "hi there" },
+ },
+ },
+ },
+ },
+ {
+ type: "notification",
+ timestamp: "2026-01-01T00:00:05Z",
+ event_id: "boot-6",
+ covered_event_ids: ["boot-4"],
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "tool-7",
+ status: "completed",
+ },
+ },
+ },
+ },
],
200,
{ "X-Has-More": "false" },
@@ -269,7 +328,7 @@ describe("CloudTaskEngine", () => {
mockStreamFetch.mockResolvedValueOnce(
createOpenSseResponse(
- 'id: 1\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:01Z","notification":{"jsonrpc":"2.0","method":"_posthog/console","params":{"sessionId":"run-1","level":"info","message":"hello"}}}\n\nid: 2\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:02Z","notification":{"jsonrpc":"2.0","method":"_posthog/console","params":{"sessionId":"run-1","level":"info","message":"live tail"}}}\n\n',
+ 'id: 1\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:01Z","notification":{"jsonrpc":"2.0","method":"_posthog/console","params":{"sessionId":"run-1","level":"info","message":"hello"}}}\n\nid: 2\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:02Z","notification":{"jsonrpc":"2.0","method":"_posthog/console","params":{"sessionId":"run-1","level":"info","message":"live tail"}}}\n\nid: 3\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:02Z","event_id":"boot-1","notification":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"run-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"hi "}}}}}\n\nid: 4\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:03Z","event_id":"boot-2","notification":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"run-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"there"}}}}}\n\nid: 5\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:04Z","event_id":"boot-3","notification":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"run-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"!"}}}}}\n\nid: 6\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:05Z","event_id":"boot-4","notification":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"run-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"tool-7","status":"in_progress"}}}}\n\nid: 7\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:05Z","event_id":"boot-5","notification":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"run-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"tool-8","status":"in_progress"}}}}\n\nid: 8\ndata: {"type":"notification","timestamp":"2026-01-01T00:00:05Z","event_id":"boot-6","notification":{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"run-1","update":{"sessionUpdate":"tool_call_update","toolCallId":"tool-7","status":"completed"}}}}\n\n',
),
);
@@ -314,8 +373,44 @@ describe("CloudTaskEngine", () => {
},
},
},
+ {
+ type: "notification",
+ timestamp: "2026-01-01T00:00:02Z",
+ event_id: "boot-2",
+ first_event_id: "boot-1",
+ covered_event_ids: 5,
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "agent_message",
+ content: { type: "text", text: "hi there" },
+ },
+ },
+ },
+ },
+ {
+ type: "notification",
+ timestamp: "2026-01-01T00:00:05Z",
+ event_id: "boot-6",
+ covered_event_ids: ["boot-4"],
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "tool-7",
+ status: "completed",
+ },
+ },
+ },
+ },
],
- totalEntryCount: 2,
+ totalEntryCount: 4,
status: "in_progress",
stage: "build",
output: null,
@@ -340,8 +435,41 @@ describe("CloudTaskEngine", () => {
},
},
},
+ {
+ type: "notification",
+ timestamp: "2026-01-01T00:00:04Z",
+ event_id: "boot-3",
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "!" },
+ },
+ },
+ },
+ },
+ {
+ type: "notification",
+ timestamp: "2026-01-01T00:00:05Z",
+ event_id: "boot-5",
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "tool-8",
+ status: "in_progress",
+ },
+ },
+ },
+ },
],
- totalEntryCount: 3,
+ totalEntryCount: 7,
},
]);
@@ -1547,6 +1675,608 @@ describe("CloudTaskEngine", () => {
);
});
+ it.each([
+ { name: "fresh", resumeFromEntryCount: undefined, logFetches: 2 },
+ { name: "resumed", resumeFromEntryCount: 3, logFetches: 1 },
+ ])(
+ "rebuilds a $name watch from history when the proxy reports a trimmed resume position",
+ async ({ resumeFromEntryCount, logFetches }) => {
+ vi.useFakeTimers();
+
+ const updates: unknown[] = [];
+ service.on(CloudTaskEvent.Update, (payload) => updates.push(payload));
+
+ mockStreamTokenFetch.mockImplementation(() =>
+ Promise.resolve(
+ createJsonResponse({
+ token: "proxy-token",
+ stream_base_url: "https://proxy.example",
+ }),
+ ),
+ );
+
+ let sessionLogsFetches = 0;
+ mockNetFetch.mockImplementation((input: string | Request) => {
+ const url = typeof input === "string" ? input : input.url;
+ if (url.includes("/session_logs/")) {
+ sessionLogsFetches += 1;
+ return Promise.resolve(
+ createJsonResponse([], 200, { "X-Has-More": "false" }),
+ );
+ }
+ return Promise.resolve(
+ createJsonResponse({
+ id: "run-1",
+ status: "in_progress",
+ stage: null,
+ output: null,
+ error_message: null,
+ branch: "main",
+ updated_at: "2026-01-01T00:00:00Z",
+ }),
+ );
+ });
+
+ mockStreamFetch
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ 'id: 5-0\ndata: {"type":"notification","method":"session/update"}\n\n',
+ ),
+ ),
+ )
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ 'event: end\ndata: {"type":"resync","reason":"trimmed"}\n\n',
+ ),
+ ),
+ )
+ .mockImplementation(() => Promise.resolve(createOpenSseResponse("")));
+
+ service.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ resumeFromEntryCount,
+ });
+
+ await waitFor(() => mockStreamFetch.mock.calls.length >= 3, 20_000);
+
+ expect(String(mockStreamTokenFetch.mock.calls[0][0])).toContain(
+ "stream_token/?resync=1",
+ );
+ const [resumeUrl, resumeInit] = mockStreamFetch.mock.calls[1];
+ expect(String(resumeUrl)).toContain("resync=1");
+ expect(
+ (resumeInit?.headers as Record<string, string>)["Last-Event-ID"],
+ ).toBe("5-0");
+
+ const [rebuiltUrl, rebuiltInit] = mockStreamFetch.mock.calls[2];
+ expect(String(rebuiltUrl)).not.toContain("start=latest");
+ expect(
+ (rebuiltInit?.headers as Record<string, string>)["Last-Event-ID"],
+ ).toBeUndefined();
+ expect(sessionLogsFetches).toBe(logFetches);
+ expect(mockStreamTokenFetch.mock.calls.length).toBe(2);
+ const snapshots = updates.filter(
+ (u) => (u as { kind?: string }).kind === "snapshot",
+ ) as Array<{ newEntries: unknown[]; rebuilt?: boolean }>;
+ expect(snapshots).toHaveLength(logFetches);
+ expect(snapshots[snapshots.length - 1]).toMatchObject({
+ rebuilt: true,
+ newEntries: [{ type: "notification", method: "session/update" }],
+ });
+ expect(snapshots[0].rebuilt).toBe(logFetches === 1 ? true : undefined);
+ expect(
+ updates.some((u) => (u as { kind?: string }).kind === "error"),
+ ).toBe(false);
+ },
+ );
+
+ it("rebuilds from a bounded window that still covers every retained live entry", async () => {
+ vi.useFakeTimers();
+
+ const updates: unknown[] = [];
+ service.on(CloudTaskEvent.Update, (payload) => updates.push(payload));
+
+ mockStreamTokenFetch.mockImplementation(() =>
+ Promise.resolve(
+ createJsonResponse({
+ token: "proxy-token",
+ stream_base_url: "https://proxy.example",
+ }),
+ ),
+ );
+
+ const liveCount = TRANSCRIPT_TAIL_WINDOW + 100;
+ const chain = Array.from({ length: liveCount }, (_, i) => ({
+ type: "notification",
+ timestamp: "2026-01-01T00:00:00Z",
+ event_id: `boot-${i}`,
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: `tool-${i}`,
+ status: "completed",
+ },
+ },
+ },
+ }));
+ let persistedCount = 0;
+ let probes = 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: "main",
+ updated_at: "2026-01-01T00:00:00Z",
+ }),
+ );
+ }
+ const offset = Number(url.searchParams.get("offset") ?? "0");
+ const limit = Number(url.searchParams.get("limit"));
+ if (offset === 0 && limit === 1) {
+ probes += 1;
+ persistedCount = probes === 1 ? 0 : chain.length;
+ }
+ const page = chain.slice(
+ offset,
+ Math.min(offset + limit, persistedCount),
+ );
+ return Promise.resolve(
+ createJsonResponse(page, 200, {
+ "X-Has-More": String(offset + page.length < persistedCount),
+ "X-Matching-Count": String(persistedCount),
+ }),
+ );
+ });
+
+ const liveFrames = chain
+ .map((entry, i) => `id: ${i + 1}\ndata: ${JSON.stringify(entry)}\n\n`)
+ .join("");
+ mockStreamFetch
+ .mockImplementationOnce(() =>
+ Promise.resolve(createSseResponse(liveFrames)),
+ )
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ 'event: end\ndata: {"type":"resync","reason":"trimmed"}\n\n',
+ ),
+ ),
+ )
+ .mockImplementation(() => Promise.resolve(createOpenSseResponse("")));
+
+ service.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ });
+
+ await waitFor(
+ () =>
+ updates.filter(
+ (u) =>
+ (u as { kind?: string; rebuilt?: boolean }).kind === "snapshot" &&
+ (u as { rebuilt?: boolean }).rebuilt === true,
+ ).length === 1,
+ 20_000,
+ );
+
+ const rebuilt = updates.filter(
+ (u) => (u as { rebuilt?: boolean }).rebuilt === true,
+ ) as Array<{
+ newEntries: unknown[];
+ totalEntryCount: number;
+ windowStart?: number;
+ }>;
+ const windowStart = liveCount - TRANSCRIPT_TAIL_WINDOW;
+ expect(rebuilt[0].windowStart).toBe(windowStart);
+ expect(rebuilt[0].newEntries).toEqual(chain.slice(windowStart));
+ expect(rebuilt[0].totalEntryCount).toBe(chain.length);
+ });
+
+ it("drops replayed entries the rebuilt snapshot already covers", async () => {
+ vi.useFakeTimers();
+
+ const updates: unknown[] = [];
+ service.on(CloudTaskEvent.Update, (payload) => updates.push(payload));
+
+ mockStreamTokenFetch.mockImplementation(() =>
+ Promise.resolve(
+ createJsonResponse({
+ token: "proxy-token",
+ stream_base_url: "https://proxy.example",
+ }),
+ ),
+ );
+
+ const entry = (i: number) => ({
+ type: "notification",
+ timestamp: "2026-01-01T00:00:00Z",
+ event_id: `boot-${i}`,
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: `tool-${i}`,
+ status: "completed",
+ },
+ },
+ },
+ });
+ const chain = [entry(0), entry(1), entry(2)];
+
+ let persistedCount = 0;
+ let probes = 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: "main",
+ updated_at: "2026-01-01T00:00:00Z",
+ }),
+ );
+ }
+ const offset = Number(url.searchParams.get("offset") ?? "0");
+ const limit = Number(url.searchParams.get("limit"));
+ if (offset === 0 && limit === 1) {
+ probes += 1;
+ persistedCount = probes === 1 ? 0 : chain.length;
+ }
+ const page = chain.slice(
+ offset,
+ Math.min(offset + limit, persistedCount),
+ );
+ return Promise.resolve(
+ createJsonResponse(page, 200, {
+ "X-Has-More": String(offset + page.length < persistedCount),
+ "X-Matching-Count": String(persistedCount),
+ }),
+ );
+ });
+
+ const replays: Array<{ push: (payload: string) => void }> = [];
+ mockStreamFetch
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ chain
+ .map((e, i) => `id: ${i + 1}\ndata: ${JSON.stringify(e)}\n\n`)
+ .join(""),
+ ),
+ ),
+ )
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ 'event: end\ndata: {"type":"resync","reason":"trimmed"}\n\n',
+ ),
+ ),
+ )
+ .mockImplementation(() => {
+ const replay = createControlledSseResponse();
+ replays.push(replay);
+ return Promise.resolve(replay.response);
+ });
+
+ service.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ });
+
+ await waitFor(
+ () => updates.some((u) => (u as { rebuilt?: boolean }).rebuilt === true),
+ 20_000,
+ );
+
+ const rebuilt = updates.find(
+ (u) => (u as { rebuilt?: boolean }).rebuilt === true,
+ ) as { newEntries: unknown[]; totalEntryCount: number };
+ expect(rebuilt.newEntries).toEqual(chain);
+ expect(rebuilt.totalEntryCount).toBe(chain.length);
+
+ const afterSnapshot = updates.length;
+ replays[replays.length - 1].push(
+ `id: 9\ndata: ${JSON.stringify(chain[1])}\n\n`,
+ );
+ await vi.advanceTimersByTimeAsync(200);
+ expect(
+ updates
+ .slice(afterSnapshot)
+ .filter((u) => (u as { kind?: string }).kind === "logs"),
+ ).toEqual([]);
+
+ const fresh = entry(3);
+ replays[replays.length - 1].push(
+ `id: 10\ndata: ${JSON.stringify(fresh)}\n\n`,
+ );
+ await waitFor(
+ () =>
+ updates
+ .slice(afterSnapshot)
+ .some((u) => (u as { kind?: string }).kind === "logs"),
+ 20_000,
+ );
+ const live = updates
+ .slice(afterSnapshot)
+ .filter((u) => (u as { kind?: string }).kind === "logs") as Array<{
+ newEntries: unknown[];
+ totalEntryCount: number;
+ }>;
+ expect(live).toHaveLength(1);
+ expect(live[0].newEntries).toEqual([fresh]);
+ expect(live[0].totalEntryCount).toBe(chain.length + 1);
+ });
+
+ it("keeps replay deduplication across a reconnect that resumes from the cursor", async () => {
+ vi.useFakeTimers();
+
+ const updates: unknown[] = [];
+ service.on(CloudTaskEvent.Update, (payload) => updates.push(payload));
+
+ mockStreamTokenFetch.mockImplementation(() =>
+ Promise.resolve(
+ createJsonResponse({
+ token: "proxy-token",
+ stream_base_url: "https://proxy.example",
+ }),
+ ),
+ );
+
+ const entry = (i: number) => ({
+ type: "notification",
+ timestamp: "2026-01-01T00:00:00Z",
+ event_id: `boot-${i}`,
+ notification: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ sessionId: "run-1",
+ update: {
+ sessionUpdate: "tool_call_update",
+ toolCallId: `tool-${i}`,
+ status: "completed",
+ },
+ },
+ },
+ });
+ const chain = [entry(0), entry(1), entry(2)];
+
+ let persistedCount = 0;
+ let probes = 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: "main",
+ updated_at: "2026-01-01T00:00:00Z",
+ }),
+ );
+ }
+ const offset = Number(url.searchParams.get("offset") ?? "0");
+ const limit = Number(url.searchParams.get("limit"));
+ if (offset === 0 && limit === 1) {
+ probes += 1;
+ persistedCount = probes === 1 ? 0 : chain.length;
+ }
+ const page = chain.slice(
+ offset,
+ Math.min(offset + limit, persistedCount),
+ );
+ return Promise.resolve(
+ createJsonResponse(page, 200, {
+ "X-Has-More": String(offset + page.length < persistedCount),
+ "X-Matching-Count": String(persistedCount),
+ }),
+ );
+ });
+
+ const replays: Array<{
+ push: (payload: string) => void;
+ close: () => void;
+ }> = [];
+ mockStreamFetch
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ chain
+ .map((e, i) => `id: ${i + 1}\ndata: ${JSON.stringify(e)}\n\n`)
+ .join(""),
+ ),
+ ),
+ )
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ 'event: end\ndata: {"type":"resync","reason":"trimmed"}\n\n',
+ ),
+ ),
+ )
+ .mockImplementation(() => {
+ const replay = createControlledSseResponse();
+ replays.push(replay);
+ return Promise.resolve(replay.response);
+ });
+
+ service.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ });
+
+ await waitFor(
+ () => updates.some((u) => (u as { rebuilt?: boolean }).rebuilt === true),
+ 20_000,
+ );
+ const afterSnapshot = updates.length;
+ const streamCallsAtSnapshot = mockStreamFetch.mock.calls.length;
+
+ replays[replays.length - 1].push(
+ `id: 20\ndata: ${JSON.stringify(chain[0])}\n\n`,
+ );
+ await vi.advanceTimersByTimeAsync(200);
+ replays[replays.length - 1].close();
+
+ await waitFor(
+ () => mockStreamFetch.mock.calls.length > streamCallsAtSnapshot,
+ 20_000,
+ );
+ const [resumedUrl, resumedInit] =
+ mockStreamFetch.mock.calls[streamCallsAtSnapshot];
+ expect(String(resumedUrl)).not.toContain("start=latest");
+ expect(
+ (resumedInit?.headers as Record<string, string>)["Last-Event-ID"],
+ ).toBe("20");
+
+ replays[replays.length - 1].push(
+ `id: 21\ndata: ${JSON.stringify(chain[1])}\n\n`,
+ );
+ await vi.advanceTimersByTimeAsync(200);
+
+ expect(
+ updates
+ .slice(afterSnapshot)
+ .filter((u) => (u as { kind?: string }).kind === "logs"),
+ ).toEqual([]);
+
+ const fresh = entry(3);
+ replays[replays.length - 1].push(
+ `id: 22\ndata: ${JSON.stringify(fresh)}\n\n`,
+ );
+ await waitFor(
+ () =>
+ updates
+ .slice(afterSnapshot)
+ .some((u) => (u as { kind?: string }).kind === "logs"),
+ 20_000,
+ );
+ const live = updates
+ .slice(afterSnapshot)
+ .filter((u) => (u as { kind?: string }).kind === "logs") as Array<{
+ newEntries: unknown[];
+ totalEntryCount: number;
+ }>;
+ expect(live).toHaveLength(1);
+ expect(live[0].newEntries).toEqual([fresh]);
+ expect(live[0].totalEntryCount).toBe(chain.length + 1);
+ });
+
+ it("keeps replaying the stream window when the rebuilt connection dies before its first event", async () => {
+ vi.useFakeTimers();
+
+ mockStreamTokenFetch.mockImplementation(() =>
+ Promise.resolve(
+ createJsonResponse({
+ token: "proxy-token",
+ stream_base_url: "https://proxy.example",
+ }),
+ ),
+ );
+
+ mockNetFetch.mockImplementation((input: string | Request) => {
+ const url = typeof input === "string" ? input : input.url;
+ if (url.includes("/session_logs/")) {
+ return Promise.resolve(
+ createJsonResponse([], 200, { "X-Has-More": "false" }),
+ );
+ }
+ return Promise.resolve(
+ createJsonResponse({
+ id: "run-1",
+ status: "in_progress",
+ stage: null,
+ output: null,
+ error_message: null,
+ branch: "main",
+ updated_at: "2026-01-01T00:00:00Z",
+ }),
+ );
+ });
+
+ mockStreamFetch
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ 'id: 5-0\ndata: {"type":"notification","method":"session/update"}\n\n',
+ ),
+ ),
+ )
+ .mockImplementationOnce(() =>
+ Promise.resolve(
+ createSseResponse(
+ 'event: end\ndata: {"type":"resync","reason":"trimmed"}\n\n',
+ ),
+ ),
+ )
+ .mockImplementationOnce(() => Promise.resolve(createSseResponse("")))
+ .mockImplementation(() => Promise.resolve(createOpenSseResponse("")));
+
+ service.watch({
+ taskId: "task-1",
+ runId: "run-1",
+ apiHost: "https://app.example.com",
+ teamId: 2,
+ });
+
+ await waitFor(() => mockStreamFetch.mock.calls.length >= 4, 20_000);
+
+ const [retriedUrl, retriedInit] = mockStreamFetch.mock.calls[3];
+ expect(String(retriedUrl)).not.toContain("start=latest");
+ expect(
+ (retriedInit?.headers as Record<string, string>)["Last-Event-ID"],
+ ).toBeUndefined();
+ });
+
it("drops the resume position when the stream leg changes", async () => {
vi.useFakeTimers();
diff --git a/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts b/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts
index 32caaaf8a0cd..d4ed6100ba5c 100644
--- a/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts
+++ b/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts
@@ -93,7 +93,11 @@ function snapshotUpdate(
};
}
-function createHarness(isTaskAuthor = true, initialPrompt?: string) {
+function createHarness(
+ isTaskAuthor = true,
+ initialPrompt?: string,
+ resume?: { ancestorRunId: string; ancestorEntryCount: number },
+) {
const sessions: Record<string, AgentSession> = {};
const store = {
getSessions: () => sessions,
@@ -148,6 +152,13 @@ function createHarness(isTaskAuthor = true, initialPrompt?: string) {
});
},
),
+ removeOptimisticItems: (taskRunId: string, ids: string[]) => {
+ const session = sessions[taskRunId];
+ if (!session) return;
+ session.optimisticItems = session.optimisticItems.filter(
+ (item) => !ids.includes(item.id),
+ );
+ },
replaceOptimisticWithEvent: vi.fn(),
clearMessageQueue: vi.fn(),
};
@@ -197,6 +208,10 @@ function createHarness(isTaskAuthor = true, initialPrompt?: string) {
enqueueSpeech,
taskViewedApi: { markActivity },
getPersistedConfigOptions: () => undefined,
+ fetchAuthState: vi
+ .fn()
+ .mockResolvedValue({ status: "authenticated", bootstrapComplete: true }),
+ createAuthenticatedClient: () => undefined,
setPersistedConfigOptions: vi.fn(),
adapterStore: {
getAdapter: () => undefined,
@@ -233,7 +248,22 @@ function createHarness(isTaskAuthor = true, initialPrompt?: string) {
const service = new SessionService(deps);
if (initialPrompt) service.rememberInitialCloudPrompt(TASK_ID, initialPrompt);
- service.watchCloudTask(TASK_ID, RUN_ID, "https://us.posthog.com", 1);
+ service.watchCloudTask(
+ TASK_ID,
+ RUN_ID,
+ "https://us.posthog.com",
+ 1,
+ undefined,
+ undefined,
+ undefined,
+ "claude",
+ undefined,
+ undefined,
+ resume?.ancestorEntryCount,
+ undefined,
+ undefined,
+ resume ? { resume_from_run_id: resume.ancestorRunId } : undefined,
+ );
if (!onUpdate) throw new Error("watchCloudTask did not subscribe");
const session = sessions[RUN_ID];
if (session) session.isTaskAuthor = isTaskAuthor;
@@ -325,6 +355,232 @@ describe("cloud task update notifications", () => {
expect(harness.enqueueSpeech).not.toHaveBeenCalled();
});
+ it("replaces the transcript with a rebuilt snapshot instead of dropping it as caught up", () => {
+ const harness = createHarness();
+ const chunk = (text: string, eventId: string): StoredLogEntry => ({
+ type: "notification",
+ event_id: eventId,
+ notification: {
+ method: "session/update",
+ params: {
+ sessionId: RUN_ID,
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text },
+ },
+ },
+ },
+ });
+ const prompt: StoredLogEntry = {
+ type: "notification",
+ event_id: "b-0",
+ notification: {
+ id: 7,
+ method: "session/prompt",
+ params: {
+ sessionId: RUN_ID,
+ prompt: [{ type: "text", text: "Say hello" }],
+ },
+ },
+ };
+ harness.sendUpdate(
+ logsUpdate(
+ [prompt, chunk("Hel", "b-1"), chunk("lo", "b-2"), chunk(" wor", "b-3")],
+ 4,
+ ),
+ );
+ expect(harness.session.processedLineCount).toBe(4);
+
+ harness.sendUpdate({
+ ...snapshotUpdate(
+ [
+ prompt,
+ {
+ type: "notification",
+ event_id: "b-4",
+ first_event_id: "b-1",
+ notification: {
+ method: "session/update",
+ params: {
+ sessionId: RUN_ID,
+ update: {
+ sessionUpdate: "agent_message",
+ content: { type: "text", text: "Hello world" },
+ },
+ },
+ },
+ },
+ ],
+ 2,
+ ),
+ rebuilt: true,
+ } as CloudTaskUpdatePayload);
+
+ expect(harness.session.processedLineCount).toBe(2);
+ const texts = harness.session.events.map((event) =>
+ JSON.stringify(event.message),
+ );
+ expect(texts.filter((t) => t.includes("Hello world"))).toHaveLength(1);
+ expect(texts.some((t) => t.includes('"Hel"'))).toBe(false);
+
+ harness.sendUpdate(logsUpdate([turnComplete()], 3));
+ expect(harness.session.processedLineCount).toBe(3);
+ });
+
+ it("retires the optimistic prompt echoed by a rebuilt snapshot that shrinks the transcript", () => {
+ const harness = createHarness();
+ const prompt = (
+ text: string,
+ id: number,
+ eventId: string,
+ ): StoredLogEntry => ({
+ type: "notification",
+ event_id: eventId,
+ notification: {
+ id,
+ method: "session/prompt",
+ params: { sessionId: RUN_ID, prompt: [{ type: "text", text }] },
+ },
+ });
+ const chunk = (text: string, eventId: string): StoredLogEntry => ({
+ type: "notification",
+ event_id: eventId,
+ notification: {
+ method: "session/update",
+ params: {
+ sessionId: RUN_ID,
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text },
+ },
+ },
+ },
+ });
+
+ harness.sendUpdate(
+ logsUpdate(
+ [
+ prompt("Say hello", 7, "b-0"),
+ chunk("Hel", "b-1"),
+ chunk("lo", "b-2"),
+ chunk("!", "b-3"),
+ ],
+ 4,
+ ),
+ );
+ expect(harness.session.processedLineCount).toBe(4);
+
+ harness.session.optimisticItems.push({
+ type: "user_message",
+ id: "optimistic-follow-up",
+ content: "Say it again",
+ timestamp: Date.now(),
+ pinToTop: false,
+ });
+
+ harness.sendUpdate({
+ ...snapshotUpdate(
+ [
+ prompt("Say hello", 7, "b-0"),
+ {
+ type: "notification",
+ event_id: "b-3",
+ first_event_id: "b-1",
+ notification: {
+ method: "session/update",
+ params: {
+ sessionId: RUN_ID,
+ update: {
+ sessionUpdate: "agent_message",
+ content: { type: "text", text: "Hello!" },
+ },
+ },
+ },
+ },
+ prompt("Say it again", 8, "b-4"),
+ ],
+ 3,
+ ),
+ rebuilt: true,
+ } as CloudTaskUpdatePayload);
+
+ expect(harness.session.processedLineCount).toBe(3);
+ expect(harness.session.optimisticItems).toEqual([]);
+ });
+
+ it("keeps a resumed run's counts leaf-relative across a rebuilt snapshot", async () => {
+ const ancestorEntryCount = 3;
+ const harness = createHarness(true, undefined, {
+ ancestorRunId: "run-0",
+ ancestorEntryCount,
+ });
+ const message = (text: string, eventId: string): StoredLogEntry => ({
+ type: "notification",
+ event_id: eventId,
+ notification: {
+ method: "session/update",
+ params: {
+ sessionId: RUN_ID,
+ update: {
+ sessionUpdate: "agent_message",
+ content: { type: "text", text },
+ },
+ },
+ },
+ });
+ const ancestorTail = [
+ message("Ancestor two", "a-1"),
+ message("Ancestor three", "a-2"),
+ ];
+ const leaf = [
+ message("Leaf one", "c-0"),
+ message("Leaf two", "c-1"),
+ message("Leaf three", "c-2"),
+ message("Leaf four", "c-3"),
+ ];
+
+ harness.sendUpdate(logsUpdate(leaf, ancestorEntryCount + leaf.length));
+ await vi.waitFor(() =>
+ expect(harness.session.processedLineCount).toBe(leaf.length),
+ );
+
+ harness.sendUpdate({
+ ...snapshotUpdate(
+ [...ancestorTail, ...leaf],
+ 1 + ancestorTail.length + leaf.length,
+ ),
+ windowStart: 1,
+ rebuilt: true,
+ } as CloudTaskUpdatePayload);
+
+ expect(harness.session.processedLineCount).toBe(leaf.length);
+ expect(harness.session.transcriptWindowStart).toBe(1);
+
+ harness.sendUpdate(
+ logsUpdate(
+ [message("Leaf five", "c-4")],
+ ancestorEntryCount + leaf.length + 1,
+ ),
+ );
+
+ expect(harness.session.processedLineCount).toBe(leaf.length + 1);
+ expect(harness.session.transcriptWindowStart).toBe(1);
+ const texts = harness.session.events.map((event) =>
+ JSON.stringify(event.message),
+ );
+ for (const text of [
+ "Ancestor two",
+ "Ancestor three",
+ "Leaf one",
+ "Leaf two",
+ "Leaf three",
+ "Leaf four",
+ "Leaf five",
+ ]) {
+ expect(texts.some((t) => t.includes(text))).toBe(true);
+ }
+ });
+
it("does not notify for turn_completes replayed in a snapshot", () => {
const harness = createHarness();
diff --git a/products/desktop/packages/core/src/sessions/sessionEvents.test.ts b/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
index 4dc8d49f6915..4fcbf2431f47 100644
--- a/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
@@ -18,6 +18,7 @@ import {
isFatalSessionError,
promptReferencesAbsoluteFolder,
selectEchoedOptimisticItemIds,
+ selectEchoedOptimisticItemIdsAfterRebuild,
selectUnseededPendingFollowups,
} from "./sessionEvents";
@@ -328,6 +329,79 @@ describe("selectEchoedOptimisticItemIds", () => {
});
});
+describe("selectEchoedOptimisticItemIdsAfterRebuild", () => {
+ const promptLog = (
+ texts: string[],
+ options: { taskRunId?: string; startEntryIndex?: number } = {},
+ ): AcpMessage[] =>
+ convertStoredEntriesToEvents(
+ texts.map((text) => ({
+ type: "notification",
+ notification: {
+ id: 1,
+ method: "session/prompt",
+ params: { prompt: [{ type: "text", text }] },
+ },
+ })) as StoredLogEntry[],
+ undefined,
+ {
+ taskRunId: options.taskRunId ?? "run-1",
+ startEntryIndex: options.startEntryIndex ?? 0,
+ },
+ );
+ const tailItem = (id: string, content: string): OptimisticItem => ({
+ type: "user_message",
+ id,
+ content,
+ timestamp: 1,
+ pinToTop: false,
+ });
+
+ it("drops a bubble the rebuild echoes beyond what the committed events carry", () => {
+ expect(
+ selectEchoedOptimisticItemIdsAfterRebuild(
+ [tailItem("o1", "yes")],
+ promptLog(["carry on", "yes"]),
+ promptLog(["carry on"]),
+ { taskRunId: "run-1", firstEntryIndex: 0 },
+ ),
+ ).toEqual(["o1"]);
+ });
+
+ it("keeps a bubble whose echo the committed events already carry", () => {
+ expect(
+ selectEchoedOptimisticItemIdsAfterRebuild(
+ [tailItem("o1", "yes")],
+ promptLog(["carry on", "yes"]),
+ promptLog(["carry on", "yes"]),
+ { taskRunId: "run-1", firstEntryIndex: 0 },
+ ),
+ ).toEqual([]);
+ });
+
+ it("drops a bubble an ancestor run's matching prompt would otherwise consume", () => {
+ expect(
+ selectEchoedOptimisticItemIdsAfterRebuild(
+ [tailItem("o1", "yes")],
+ promptLog(["yes"]),
+ promptLog(["yes"], { taskRunId: "ancestor-run" }),
+ { taskRunId: "run-1", firstEntryIndex: 0 },
+ ),
+ ).toEqual(["o1"]);
+ });
+
+ it("drops a bubble a prompt below the rebuilt window would otherwise consume", () => {
+ expect(
+ selectEchoedOptimisticItemIdsAfterRebuild(
+ [tailItem("o1", "yes")],
+ promptLog(["yes"], { startEntryIndex: 40 }),
+ promptLog(["yes"]),
+ { taskRunId: "run-1", firstEntryIndex: 40 },
+ ),
+ ).toEqual(["o1"]);
+ });
+});
+
describe("selectUnseededPendingFollowups", () => {
const promptLog = (...texts: string[]): AcpMessage[] =>
convertStoredEntriesToEvents(
diff --git a/products/desktop/packages/core/src/sessions/sessionEvents.ts b/products/desktop/packages/core/src/sessions/sessionEvents.ts
index fb9019272aff..79bd40528a0e 100644
--- a/products/desktop/packages/core/src/sessions/sessionEvents.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEvents.ts
@@ -504,18 +504,19 @@ export function isSteerPromptParams(params: unknown): boolean {
* echoes. Pinned bubbles are left alone: the initial prompt is deduped against
* its echo by the merge layer, which upgrades it with the server's timestamp.
*/
-export function selectEchoedOptimisticItemIds(
- optimisticItems: OptimisticItem[],
+function countPromptEchoes(
events: AcpMessage[],
firstUnseenEntryIndex: number,
-): string[] {
+ taskRunId?: string,
+): Map<string, number> {
const echoCounts = new Map<string, number>();
for (const event of events) {
const msg = event.message;
if (!isJsonRpcRequest(msg) || msg.method !== "session/prompt") continue;
- const entryIndex = getStoredLogEventPosition(event)?.entryIndex;
- if (entryIndex === undefined || entryIndex < firstUnseenEntryIndex)
+ const position = getStoredLogEventPosition(event);
+ if (position === undefined || position.entryIndex < firstUnseenEntryIndex)
continue;
+ if (taskRunId !== undefined && position.taskRunId !== taskRunId) continue;
const blocks = (msg.params as { prompt?: ContentBlock[] } | undefined)
?.prompt;
if (!blocks?.length) continue;
@@ -524,6 +525,13 @@ export function selectEchoedOptimisticItemIds(
}).text.trim();
echoCounts.set(text, (echoCounts.get(text) ?? 0) + 1);
}
+ return echoCounts;
+}
+
+function selectItemsMatchingEchoes(
+ optimisticItems: OptimisticItem[],
+ echoCounts: Map<string, number>,
+): string[] {
if (echoCounts.size === 0) return [];
const echoed: string[] = [];
@@ -538,6 +546,40 @@ export function selectEchoedOptimisticItemIds(
return echoed;
}
+export function selectEchoedOptimisticItemIds(
+ optimisticItems: OptimisticItem[],
+ events: AcpMessage[],
+ firstUnseenEntryIndex: number,
+): string[] {
+ return selectItemsMatchingEchoes(
+ optimisticItems,
+ countPromptEchoes(events, firstUnseenEntryIndex),
+ );
+}
+
+export function selectEchoedOptimisticItemIdsAfterRebuild(
+ optimisticItems: OptimisticItem[],
+ events: AcpMessage[],
+ committedEvents: AcpMessage[],
+ rebuiltWindow: { taskRunId: string; firstEntryIndex: number },
+): string[] {
+ const { taskRunId, firstEntryIndex } = rebuiltWindow;
+ const echoCounts = countPromptEchoes(events, firstEntryIndex, taskRunId);
+ for (const [text, committed] of countPromptEchoes(
+ committedEvents,
+ firstEntryIndex,
+ taskRunId,
+ )) {
+ const remaining = (echoCounts.get(text) ?? 0) - committed;
+ if (remaining > 0) {
+ echoCounts.set(text, remaining);
+ } else {
+ echoCounts.delete(text);
+ }
+ }
+ return selectItemsMatchingEchoes(optimisticItems, echoCounts);
+}
+
export function selectUnseededPendingFollowups(
pending: PendingFollowupMessage[],
events: AcpMessage[],
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 0472976679e6..782037bfdabf 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -131,6 +131,7 @@ import {
normalizePromptToBlocks,
promptReferencesAbsoluteFolder,
selectEchoedOptimisticItemIds,
+ selectEchoedOptimisticItemIdsAfterRebuild,
selectUnseededPendingFollowups,
shellExecutesToContextBlocks,
} from "./sessionEvents";
@@ -6956,9 +6957,10 @@ export class SessionService {
cloudTranscriptEntryCount: update.totalEntryCount,
});
}
- const watcher = this.cloudTaskWatchers.get(taskId);
- const resumeHistoryCountOffset =
- watcher?.runId === runId ? (watcher.resumeHistoryCountOffset ?? 0) : 0;
+ const resumeHistoryCountOffset = this.resumeHistoryCountOffsetFor(
+ taskId,
+ runId,
+ );
let normalizedUpdate: CloudTaskUpdatePayload = update;
if (
resumeHistoryCountOffset > 0 &&
@@ -6973,8 +6975,9 @@ export class SessionService {
};
// 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") {
+ // on resume watchers keep falling back to the reconciler. A rebuilt
+ // snapshot commits each unit separately, so it keeps its window.
+ if (normalizedUpdate.kind === "snapshot" && !normalizedUpdate.rebuilt) {
normalizedUpdate.windowStart = undefined;
}
}
@@ -8705,13 +8708,24 @@ export class SessionService {
const session = this.d.store.getSessions()[taskRunId];
const currentCount = session?.processedLineCount ?? 0;
const expectedCount = update.totalEntryCount;
- const plan = classifyCloudLogAppend(
- currentCount,
- expectedCount,
- update.newEntries.length,
- );
+ const plan =
+ update.kind === "snapshot" && update.rebuilt
+ ? ({ kind: "rebuild" } as const)
+ : classifyCloudLogAppend(
+ currentCount,
+ expectedCount,
+ update.newEntries.length,
+ );
- if (plan.kind === "caught-up") {
+ if (plan.kind === "rebuild" && update.kind === "snapshot") {
+ this.commitWindowedCloudSnapshot(
+ taskRunId,
+ update.newEntries,
+ update.windowStart ?? 0,
+ expectedCount,
+ this.resumeHistoryCountOffsetFor(update.taskId, update.runId),
+ );
+ } else if (plan.kind === "caught-up") {
// Already caught up — skip duplicate entries
} else if (plan.kind === "append-tail") {
this.appendCloudTailEvents(
@@ -8736,6 +8750,8 @@ export class SessionService {
taskRunId,
update.newEntries,
update.windowStart,
+ undefined,
+ this.resumeHistoryCountOffsetFor(update.taskId, update.runId),
);
} else {
if (update.kind === "logs" && session) {
@@ -9249,6 +9265,24 @@ export class SessionService {
}
}
+ private clearEchoedOptimisticItemsAfterRebuild(
+ taskRunId: string,
+ events: AcpMessage[],
+ firstEntryIndex: number,
+ ): void {
+ const session = this.getSessionByRunId(taskRunId);
+ if (!session?.optimisticItems.length) return;
+ const echoed = selectEchoedOptimisticItemIdsAfterRebuild(
+ session.optimisticItems,
+ events,
+ session.events,
+ { taskRunId, firstEntryIndex },
+ );
+ if (echoed.length > 0) {
+ this.d.store.removeOptimisticItems(taskRunId, echoed);
+ }
+ }
+
private appendCloudTailEvents(
taskRunId: string,
entries: StoredLogEntry[],
@@ -9323,16 +9357,31 @@ export class SessionService {
this.updatePromptStateFromEvents(taskRunId, events);
}
+ private resumeHistoryCountOffsetFor(taskId: string, runId: string): number {
+ const watcher = this.cloudTaskWatchers.get(taskId);
+ return watcher?.runId === runId
+ ? (watcher.resumeHistoryCountOffset ?? 0)
+ : 0;
+ }
+
private commitWindowedCloudSnapshot(
taskRunId: string,
entries: StoredLogEntry[],
windowStart: number,
+ processedLineCount?: number,
+ ancestorEntryCount = 0,
): void {
+ const startEntryIndex = Math.max(0, windowStart - ancestorEntryCount);
const events = convertStoredEntriesToEvents(entries, undefined, {
taskRunId,
- startEntryIndex: windowStart,
+ startEntryIndex,
+ firstPositionedEntryIndex: Math.max(0, ancestorEntryCount - windowStart),
});
- this.clearEchoedTailOptimisticItems(taskRunId, events);
+ this.clearEchoedOptimisticItemsAfterRebuild(
+ taskRunId,
+ events,
+ startEntryIndex,
+ );
this.cloudRunIdleTracker.delete(taskRunId);
// Moving the window start also trips loadOlderCloudTranscript's
// stale-window guard if a prepend was in flight, instead of duplicating
@@ -9340,7 +9389,7 @@ export class SessionService {
this.d.store.updateSession(taskRunId, {
events,
isCloud: true,
- processedLineCount: windowStart + entries.length,
+ processedLineCount: processedLineCount ?? windowStart + entries.length,
transcriptWindowStart: windowStart,
});
this.updatePromptStateFromEvents(taskRunId, events);
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index b7bd461c4ca1..907742eb8500 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -593,6 +593,7 @@ export interface CloudTaskSnapshotUpdate extends CloudTaskUpdateBase {
* than the full history; older entries page in on demand. Absent means
* the snapshot starts at the head of the chain. */
windowStart?: number;
+ rebuilt?: boolean;
status?: TaskRunStatus;
stage?: string | null;
output?: Record<string, unknown> | null;
diff --git a/products/desktop/packages/shared/src/session-events.ts b/products/desktop/packages/shared/src/session-events.ts
index 1e3a76010169..f9026df68e30 100644
--- a/products/desktop/packages/shared/src/session-events.ts
+++ b/products/desktop/packages/shared/src/session-events.ts
@@ -81,6 +81,7 @@ export interface StoredLogEntry {
timestamp?: string;
/** Shared identity with the entry's Redis stream copy, when stamped */
event_id?: string;
+ first_event_id?: string;
covered_event_ids?: string[];
event?: AgentConversationEvent;
notification?: {
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 1d5f081a6b81..ec04a6d29c7c 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -2149,7 +2149,11 @@ describe("SessionService", () => {
expect(mockConvertStoredEntriesToEvents).toHaveBeenCalledWith(
windowEntries,
undefined,
- { taskRunId: "run-123", startEntryIndex: 4998 },
+ {
+ taskRunId: "run-123",
+ startEntryIndex: 4998,
+ firstPositionedEntryIndex: 0,
+ },
);
expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(
"run-123",