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(tasks): render live cloud log tail while a transcript gap reconciles (#87041)

Alessandro Pogliaghi9da40d7069f7
diff --git a/products/desktop/packages/core/src/sessions/cloudLogGap.test.ts b/products/desktop/packages/core/src/sessions/cloudLogGap.test.ts
index 7ecc53209165..c670453ab225 100644
--- a/products/desktop/packages/core/src/sessions/cloudLogGap.test.ts
+++ b/products/desktop/packages/core/src/sessions/cloudLogGap.test.ts
@@ -95,35 +95,89 @@ describe("classifyCloudLogGap", () => {
});
});
- it("commits best-effort on a stable repeated deficit", () => {
+ it.each([
+ {
+ name: "waits with a fresh deficit on the first short fetch",
+ totalLineCount: 7,
+ previousDeficiency: undefined,
+ expected: {
+ kind: "wait",
+ deficiency: {
+ expectedCount: 10,
+ observedLineCount: 7,
+ stalledPasses: 0,
+ },
+ },
+ },
+ {
+ name: "counts a stalled pass when the deficit repeats exactly",
+ totalLineCount: 7,
+ previousDeficiency: {
+ expectedCount: 10,
+ observedLineCount: 7,
+ stalledPasses: 0,
+ },
+ expected: {
+ kind: "wait",
+ deficiency: {
+ expectedCount: 10,
+ observedLineCount: 7,
+ stalledPasses: 1,
+ },
+ },
+ },
+ {
+ name: "counts a stalled pass when the expected count grows without new lines",
+ totalLineCount: 7,
+ previousDeficiency: {
+ expectedCount: 9,
+ observedLineCount: 7,
+ stalledPasses: 1,
+ },
+ expected: {
+ kind: "wait",
+ deficiency: {
+ expectedCount: 10,
+ observedLineCount: 7,
+ stalledPasses: 2,
+ },
+ },
+ },
+ {
+ name: "resets the stall count when the deficit shrinks",
+ totalLineCount: 9,
+ previousDeficiency: {
+ expectedCount: 10,
+ observedLineCount: 7,
+ stalledPasses: 2,
+ },
+ expected: {
+ kind: "wait",
+ deficiency: {
+ expectedCount: 10,
+ observedLineCount: 9,
+ stalledPasses: 0,
+ },
+ },
+ },
+ {
+ name: "escapes to best-effort after enough stalled passes",
+ totalLineCount: 7,
+ previousDeficiency: {
+ expectedCount: 10,
+ observedLineCount: 7,
+ stalledPasses: 2,
+ },
+ expected: {
+ kind: "commit-best-effort",
+ processedLineCount: 10,
+ reason: "no-progress",
+ },
+ },
+ ])("$name", ({ totalLineCount, previousDeficiency, expected }) => {
expect(
- classifyCloudLogGap({
- ...base,
- totalLineCount: 7,
- previousDeficiency: { expectedCount: 10, observedLineCount: 7 },
- }),
- ).toEqual({
- kind: "commit-best-effort",
- processedLineCount: 10,
- reason: "stable-deficit",
- });
- });
-
- it("waits when short but the deficit is new (likely lag)", () => {
- expect(classifyCloudLogGap({ ...base, totalLineCount: 7 })).toEqual({
- kind: "wait",
- deficiency: { expectedCount: 10, observedLineCount: 7 },
- });
- });
-
- it("waits when the previous deficit differs from the current one", () => {
- expect(
- classifyCloudLogGap({
- ...base,
- totalLineCount: 7,
- previousDeficiency: { expectedCount: 10, observedLineCount: 5 },
- }),
- ).toMatchObject({ kind: "wait" });
+ classifyCloudLogGap({ ...base, totalLineCount, previousDeficiency }),
+ ).toEqual(expected);
});
});
diff --git a/products/desktop/packages/core/src/sessions/cloudLogGap.ts b/products/desktop/packages/core/src/sessions/cloudLogGap.ts
index 1a4d851e0a82..c11312f7b614 100644
--- a/products/desktop/packages/core/src/sessions/cloudLogGap.ts
+++ b/products/desktop/packages/core/src/sessions/cloudLogGap.ts
@@ -19,8 +19,11 @@ export interface CloudLogGapReconcileRequest {
export interface CloudLogGapDeficiency {
expectedCount: number;
observedLineCount: number;
+ stalledPasses: number;
}
+const CLOUD_LOG_GAP_STALLED_PASS_LIMIT = 3;
+
/**
* Coalesce a queued reconcile request with a newer one, widening the range to
* cover both (lowest currentCount, highest expectedCount) and concatenating
@@ -81,7 +84,7 @@ export type CloudLogGapAction =
| {
kind: "commit-best-effort";
processedLineCount: number;
- reason: "parse-failure" | "stable-deficit";
+ reason: "parse-failure" | "no-progress";
}
| { kind: "wait"; deficiency: CloudLogGapDeficiency };
@@ -102,8 +105,9 @@ export interface CloudLogGapInput {
* Decide what to do after a reconcile fetch:
* - `already-current`: the store already caught up; drop any tracked deficit.
* - `fill`: the fetch covered the gap; commit everything it returned.
- * - `commit-best-effort`: the gap is unrecoverable (parse failure or a stable
- * repeat of the same deficit); commit what we have and stop looping.
+ * - `commit-best-effort`: the gap is unrecoverable (parse failure, or the
+ * deficit stopped shrinking across several passes); commit what we have and
+ * stop looping.
* - `wait`: still short, but likely lag; record the deficit and retry later.
*/
export function classifyCloudLogGap(
@@ -125,20 +129,35 @@ export function classifyCloudLogGap(
return { kind: "fill", processedLineCount: totalLineCount };
}
- const sameDeficiencyAsBefore =
- previousDeficiency?.expectedCount === expectedCount &&
- previousDeficiency?.observedLineCount === totalLineCount;
+ if (parseFailureCount > 0) {
+ return {
+ kind: "commit-best-effort",
+ processedLineCount: expectedCount,
+ reason: "parse-failure",
+ };
+ }
+
+ const stalledPasses =
+ previousDeficiency !== undefined &&
+ expectedCount - totalLineCount >=
+ previousDeficiency.expectedCount - previousDeficiency.observedLineCount
+ ? previousDeficiency.stalledPasses + 1
+ : 0;
- if (parseFailureCount > 0 || sameDeficiencyAsBefore) {
+ if (stalledPasses >= CLOUD_LOG_GAP_STALLED_PASS_LIMIT) {
return {
kind: "commit-best-effort",
processedLineCount: expectedCount,
- reason: parseFailureCount > 0 ? "parse-failure" : "stable-deficit",
+ reason: "no-progress",
};
}
return {
kind: "wait",
- deficiency: { expectedCount, observedLineCount: totalLineCount },
+ deficiency: {
+ expectedCount,
+ observedLineCount: totalLineCount,
+ stalledPasses,
+ },
};
}
diff --git a/products/desktop/packages/core/src/sessions/cloudLogGapReconciler.test.ts b/products/desktop/packages/core/src/sessions/cloudLogGapReconciler.test.ts
index 5e1bbeb022b2..9c7bebaea320 100644
--- a/products/desktop/packages/core/src/sessions/cloudLogGapReconciler.test.ts
+++ b/products/desktop/packages/core/src/sessions/cloudLogGapReconciler.test.ts
@@ -144,7 +144,7 @@ describe("CloudLogGapReconciler", () => {
);
});
- it("commits best-effort once the same deficit repeats", async () => {
+ it("commits best-effort once the deficit stops shrinking for enough passes", async () => {
const { deps, commit } = createDeps({
fetch: {
rawEntries: [entry("a")],
@@ -154,9 +154,11 @@ describe("CloudLogGapReconciler", () => {
});
const reconciler = new CloudLogGapReconciler(deps);
- reconciler.reconcile(request());
- await tick();
- expect(commit).not.toHaveBeenCalled();
+ for (let pass = 0; pass < 3; pass += 1) {
+ reconciler.reconcile(request());
+ await tick();
+ expect(commit).not.toHaveBeenCalled();
+ }
reconciler.reconcile(request());
await tick();
diff --git a/products/desktop/packages/core/src/sessions/sessionEvents.test.ts b/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
index e5aa01e7b82e..917c26370189 100644
--- a/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
@@ -6,6 +6,7 @@ import { makeAttachmentUri } from "./promptContent";
import {
collapseSupersededToolCallUpdates,
convertStoredEntriesToEvents,
+ dropEventsCoveredByTail,
extractUserPromptsFromEvents,
hasSessionPromptEvent,
hasSessionPromptEventForTaskRun,
@@ -230,6 +231,50 @@ describe("hasSessionPromptEvent", () => {
});
});
+describe("dropEventsCoveredByTail", () => {
+ const noteEntry = (method: string): StoredLogEntry =>
+ ({
+ type: "notification",
+ notification: { jsonrpc: "2.0", method },
+ }) as unknown as StoredLogEntry;
+
+ const positionedEvents = (
+ taskRunId: string,
+ startEntryIndex: number,
+ methods: string[],
+ ): AcpMessage[] =>
+ convertStoredEntriesToEvents(methods.map(noteEntry), undefined, {
+ taskRunId,
+ startEntryIndex,
+ });
+
+ it("returns undefined when no existing event is covered by the tail", () => {
+ const events = [
+ ...positionedEvents("run-1", 0, ["a", "b"]),
+ ...positionedEvents("other-run", 5, ["c"]),
+ { type: "acp_message", ts: 1, message: {} } as unknown as AcpMessage,
+ ];
+ expect(dropEventsCoveredByTail(events, "run-1", 2)).toBeUndefined();
+ });
+
+ it("drops the run's events at or after the tail start and keeps the rest", () => {
+ const kept = positionedEvents("run-1", 0, ["a", "b"]);
+ const covered = positionedEvents("run-1", 3, ["c", "d"]);
+ const otherRun = positionedEvents("other-run", 3, ["e"]);
+ const unpositioned = {
+ type: "acp_message",
+ ts: 1,
+ message: {},
+ } as unknown as AcpMessage;
+ const result = dropEventsCoveredByTail(
+ [...kept, unpositioned, ...covered, ...otherRun],
+ "run-1",
+ 3,
+ );
+ expect(result).toEqual([...kept, unpositioned, ...otherRun]);
+ });
+});
+
describe("convertStoredEntriesToEvents — imported user prompts", () => {
const userChunkEntry = (
text: string,
diff --git a/products/desktop/packages/core/src/sessions/sessionEvents.ts b/products/desktop/packages/core/src/sessions/sessionEvents.ts
index 814606586cdf..1af709fadd02 100644
--- a/products/desktop/packages/core/src/sessions/sessionEvents.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEvents.ts
@@ -47,6 +47,23 @@ export function getStoredLogEventPosition(
return storedLogEventPositions.get(event);
}
+export function dropEventsCoveredByTail(
+ events: AcpMessage[],
+ taskRunId: string,
+ startEntryIndex: number,
+): AcpMessage[] | undefined {
+ const isCovered = (event: AcpMessage): boolean => {
+ const position = storedLogEventPositions.get(event);
+ return (
+ position !== undefined &&
+ position.taskRunId === taskRunId &&
+ position.entryIndex >= startEntryIndex
+ );
+ };
+ if (!events.some(isCovered)) return undefined;
+ return events.filter((event) => !isCovered(event));
+}
+
function recordStoredLogEventPosition(
event: AcpMessage,
position: StoredLogEventPosition | undefined,
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index ae494c8fead3..7b2331f05ebc 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -109,6 +109,7 @@ import {
convertStoredEntriesToEvents,
createConversationClearedEvents,
createUserShellExecuteEvent,
+ dropEventsCoveredByTail,
extractPromptText,
getStoredLogEventPosition,
getUserShellExecutesSinceLastPrompt,
@@ -6826,10 +6827,14 @@ export class SessionService {
if (!result) return;
const watcher = this.cloudTaskWatchers.get(taskId);
if (!watcher || watcher.runId !== taskRunId) return;
- watcher.resumeHistoryCountOffset = Math.max(
+ const offset = Math.max(
0,
result.historyEntryCount - result.liveStreamLineCount,
);
+ if (offset === 0 && watcher.resumeHistoryCountOffset) {
+ return;
+ }
+ watcher.resumeHistoryCountOffset = offset;
}
private logHydrationTruncation(
@@ -8538,22 +8543,15 @@ export class SessionService {
if (plan.kind === "caught-up") {
// Already caught up — skip duplicate entries
} else if (plan.kind === "append-tail") {
- const entriesToAppend = update.newEntries.slice(-plan.tailCount);
- const newEvents = convertStoredEntriesToEvents(
- entriesToAppend,
- undefined,
+ this.appendCloudTailEvents(
+ taskRunId,
+ update.newEntries.slice(-plan.tailCount),
+ expectedCount,
{
- taskRunId,
- startEntryIndex: expectedCount - entriesToAppend.length,
+ processedLineCount: expectedCount,
+ isLive: update.kind === "logs",
},
);
- if (hasSessionPromptEvent(newEvents)) {
- this.d.store.clearTailOptimisticItems(taskRunId);
- }
- this.d.store.appendEvents(taskRunId, newEvents, expectedCount);
- this.updatePromptStateFromEvents(taskRunId, newEvents, {
- isLive: update.kind === "logs",
- });
} else if (
update.kind === "snapshot" &&
update.windowStart !== undefined &&
@@ -8569,6 +8567,16 @@ export class SessionService {
update.windowStart,
);
} else {
+ if (update.kind === "logs" && session) {
+ this.appendCloudTailEvents(
+ taskRunId,
+ update.newEntries,
+ expectedCount,
+ {
+ isLive: true,
+ },
+ );
+ }
this.cloudLogGapReconciler.reconcile({
taskId: update.taskId,
taskRunId,
@@ -9030,16 +9038,66 @@ export class SessionService {
}
}
+ private appendCloudTailEvents(
+ taskRunId: string,
+ entries: StoredLogEntry[],
+ expectedCount: number,
+ options: { processedLineCount?: number; isLive: boolean },
+ ): void {
+ const startEntryIndex = Math.max(0, expectedCount - entries.length);
+ const events = convertStoredEntriesToEvents(entries, undefined, {
+ taskRunId,
+ startEntryIndex,
+ });
+ if (events.length === 0) return;
+ if (hasSessionPromptEvent(events)) {
+ this.d.store.clearTailOptimisticItems(taskRunId);
+ }
+ const existingEvents = this.getSessionByRunId(taskRunId)?.events;
+ const keptEvents = existingEvents
+ ? dropEventsCoveredByTail(existingEvents, taskRunId, startEntryIndex)
+ : undefined;
+ if (keptEvents) {
+ this.d.store.updateSession(taskRunId, {
+ events: [...keptEvents, ...events],
+ ...(options.processedLineCount !== undefined
+ ? { processedLineCount: options.processedLineCount }
+ : {}),
+ });
+ } else {
+ this.d.store.appendEvents(taskRunId, events, options.processedLineCount);
+ }
+ this.updatePromptStateFromEvents(taskRunId, events, {
+ isLive: options.isLive,
+ });
+ }
+
private commitReconciledCloudEvents(
taskRunId: string,
rawEntries: StoredLogEntry[],
logUrl: string | undefined,
processedLineCount: number,
): void {
- const events = convertStoredEntriesToEvents(rawEntries, undefined, {
+ let events = convertStoredEntriesToEvents(rawEntries, undefined, {
taskRunId,
startEntryIndex: 0,
});
+ const liveEvents = this.getSessionByRunId(taskRunId)?.events ?? [];
+ let firstPositionedIndex = liveEvents.findIndex(
+ (event) => getStoredLogEventPosition(event) !== undefined,
+ );
+ if (firstPositionedIndex === -1) {
+ firstPositionedIndex = liveEvents.length;
+ }
+ const ancestorPrefix = liveEvents.slice(0, firstPositionedIndex);
+ const liveRunEvents = liveEvents.slice(firstPositionedIndex);
+ events = [
+ ...ancestorPrefix,
+ ...events,
+ ...(liveRunEvents.length
+ ? reconcileLiveEventsWithHydratedEvents(liveRunEvents, events)
+ : []),
+ ];
if (hasSessionPromptEvent(events)) {
this.d.store.clearTailOptimisticItems(taskRunId);
}
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 42dd750fda3f..30c0fc7597a7 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -404,6 +404,7 @@ vi.mock("@posthog/core/sessions/sessionEvents", async () => {
return {
collapseSupersededToolCallUpdates: actual.collapseSupersededToolCallUpdates,
convertStoredEntriesToEvents: mockConvertStoredEntriesToEvents,
+ dropEventsCoveredByTail: actual.dropEventsCoveredByTail,
createUserPromptEvent: vi.fn((prompt, ts) => ({
type: "acp_message",
ts,
@@ -4305,7 +4306,7 @@ describe("SessionService", () => {
expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(
"run-123",
expect.objectContaining({
- events: [],
+ events: existingSession.events,
isCloud: true,
logUrl: "https://logs.example.com/run-123",
processedLineCount: 14,
@@ -4397,7 +4398,7 @@ describe("SessionService", () => {
expect(mockSessionStoreSetters.appendEvents).not.toHaveBeenCalled();
});
- it("queues a pending cloud log gap when stale fetches can't fill it, without appending", async () => {
+ it("queues a pending cloud log gap when stale fetches can't fill it, keeping the live tail", async () => {
const service = getSessionService();
let sessionState = createMockSession({
taskRunId: "run-123",
@@ -4425,7 +4426,8 @@ describe("SessionService", () => {
sessionState = {
...sessionState,
events: [...sessionState.events, ...events],
- processedLineCount,
+ processedLineCount:
+ processedLineCount ?? sessionState.processedLineCount,
};
},
);
@@ -4503,13 +4505,9 @@ describe("SessionService", () => {
await vi.waitFor(() => {
expect(mockTrpcLogs.readLocalLogs.query).toHaveBeenCalledTimes(2);
});
- // Stale fetches can't fill the gap; we must NOT append the snapshot's
- // tail slice (positions [expectedCount-N, expectedCount]) on top of an
- // events array that's still at processedLineCount=5 — that path used
- // to corrupt the array with duplicates/gaps and ratchet
- // processedLineCount past entries we don't actually have, leading to
- // unbounded growth on long-running cloud runs.
- expect(mockSessionStoreSetters.appendEvents).not.toHaveBeenCalled();
+ expect(mockSessionStoreSetters.appendEvents).toHaveBeenCalledTimes(2);
+ expect(sessionState.processedLineCount).toBe(5);
+ expect(sessionState.events).toHaveLength(4);
});
const setupReconcileLoopTest = (logContent: string) => {
@@ -4580,26 +4578,27 @@ describe("SessionService", () => {
});
});
- it("breaks the reconcile loop after a repeated stable deficiency", async () => {
+ it("breaks the reconcile loop once the deficit stops shrinking", async () => {
const { subscribeOptions } = setupReconcileLoopTest(
Array.from({ length: 8 }, () => validLine).join("\n"),
);
- subscribeOptions.onData({
- kind: "logs",
- taskId: "task-123",
- runId: "run-123",
- totalEntryCount: 14,
- newEntries: [newEntry],
- });
- await vi.waitFor(() => {
- expect(mockTrpcLogs.fetchS3Logs.query).toHaveBeenCalledTimes(1);
- });
-
- expect(mockSessionStoreSetters.updateSession).not.toHaveBeenCalledWith(
- "run-123",
- expect.objectContaining({ processedLineCount: 14 }),
- );
+ for (let pass = 1; pass <= 3; pass += 1) {
+ subscribeOptions.onData({
+ kind: "logs",
+ taskId: "task-123",
+ runId: "run-123",
+ totalEntryCount: 14,
+ newEntries: [newEntry],
+ });
+ await vi.waitFor(() => {
+ expect(mockTrpcLogs.fetchS3Logs.query).toHaveBeenCalledTimes(pass);
+ });
+ expect(mockSessionStoreSetters.updateSession).not.toHaveBeenCalledWith(
+ "run-123",
+ expect.objectContaining({ processedLineCount: 14 }),
+ );
+ }
subscribeOptions.onData({
kind: "logs",