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): bound background transcript memory (#85303)

Alessandro Pogliaghid5b3f4457878
diff --git a/products/desktop/packages/core/src/sessions/sessionEventResidency.test.ts b/products/desktop/packages/core/src/sessions/sessionEventResidency.test.ts
index 2c2413562bb7..79d6a9b2a988 100644
--- a/products/desktop/packages/core/src/sessions/sessionEventResidency.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEventResidency.test.ts
@@ -5,6 +5,8 @@ import { sessionStore, sessionStoreSetters } from "./sessionStore";
const RUN = "run-res";
const TASK = "task-res";
+const SECOND_RUN = "run-res-2";
+const SECOND_TASK = "task-res-2";
const GRACE_MS = 20_000;
const LOG_LINE = JSON.stringify({
@@ -21,7 +23,10 @@ const LOG_LINE = JSON.stringify({
},
});
-function makeService(readLocalLogs = vi.fn().mockResolvedValue("")) {
+function makeService(
+ readLocalLogs = vi.fn().mockResolvedValue(""),
+ getTaskRunSessionLogsPage = vi.fn(),
+): SessionService {
const deps = {
store: sessionStoreSetters,
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
@@ -30,6 +35,16 @@ function makeService(readLocalLogs = vi.fn().mockResolvedValue("")) {
taskViewedApi: { markActivity: vi.fn() },
getPersistedConfigOptions: () => undefined,
setPersistedConfigOptions: vi.fn(),
+ fetchAuthState: vi.fn().mockResolvedValue({
+ status: "authenticated",
+ bootstrapComplete: true,
+ cloudRegion: "us",
+ currentProjectId: 1,
+ }),
+ createAuthenticatedClient: vi.fn().mockReturnValue({
+ getTaskRunSessionLogsPage,
+ getTaskRunSessionLogsResult: vi.fn(),
+ }),
trpc: {
agent: {
onSessionEvent: { subscribe: () => ({ unsubscribe: vi.fn() }) },
@@ -42,98 +57,256 @@ function makeService(readLocalLogs = vi.fn().mockResolvedValue("")) {
return new SessionService(deps);
}
-function seed(status: SessionStatus, isPromptPending = false) {
+interface SeedOptions {
+ taskRunId?: string;
+ taskId?: string;
+ status: SessionStatus;
+ isPromptPending?: boolean;
+ cloudStatus?: AgentSession["cloudStatus"];
+ isHydratingTranscript?: boolean;
+ withEvents?: boolean;
+}
+
+function seedSession({
+ taskRunId = RUN,
+ taskId = TASK,
+ status,
+ isPromptPending = false,
+ cloudStatus,
+ isHydratingTranscript,
+ withEvents = true,
+}: SeedOptions): void {
sessionStoreSetters.setSession({
- taskRunId: RUN,
- taskId: TASK,
+ taskRunId,
+ taskId,
events: [],
messageQueue: [],
pendingPermissions: new Map(),
+ optimisticItems: [],
status,
isPromptPending,
+ isCloud: cloudStatus !== undefined,
+ cloudStatus,
+ isHydratingTranscript,
} as unknown as AgentSession);
- sessionStoreSetters.appendEvents(RUN, [{ ts: 1, message: {} } as never]);
+ if (withEvents) {
+ sessionStoreSetters.appendEvents(taskRunId, [
+ { ts: 1, message: {} } as never,
+ ]);
+ }
}
-const events = () => sessionStore.getState().sessions[RUN]?.events ?? [];
+function events(taskRunId = RUN): AgentSession["events"] {
+ return sessionStore.getState().sessions[taskRunId]?.events ?? [];
+}
+
+function background(service: SessionService, taskId = TASK): void {
+ service.scheduleEventEviction(taskId);
+ vi.advanceTimersByTime(GRACE_MS);
+}
+
+function overflowBackgroundLru(service: SessionService): void {
+ seedSession({
+ taskRunId: SECOND_RUN,
+ taskId: SECOND_TASK,
+ status: "disconnected",
+ });
+ background(service, SECOND_TASK);
+}
describe("session transcript residency", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => {
+ vi.clearAllTimers();
vi.useRealTimers();
- sessionStoreSetters.removeSession(RUN);
+ sessionStoreSetters.clearAll();
});
- it("evicts a disconnected, idle session after the grace window", () => {
+ it("keeps the previous disconnected transcript warm", () => {
const service = makeService();
- seed("disconnected");
- service.scheduleEventEviction(TASK);
+ seedSession({ status: "disconnected" });
+
+ background(service);
expect(events()).toHaveLength(1);
- vi.advanceTimersByTime(GRACE_MS);
- expect(events()).toHaveLength(0);
});
- it("never evicts a connected session", () => {
+ it("never backgrounds an active connected session", () => {
const service = makeService();
- seed("connected");
- service.scheduleEventEviction(TASK);
+ seedSession({ status: "connected" });
+
+ background(service);
- vi.advanceTimersByTime(GRACE_MS);
expect(events()).toHaveLength(1);
});
- it("never evicts a session with a prompt in flight", () => {
+ it("never backgrounds an active cloud run reported disconnected mid-run", () => {
const service = makeService();
- seed("disconnected", true);
- service.scheduleEventEviction(TASK);
+ seedSession({ status: "disconnected", cloudStatus: "in_progress" });
+
+ background(service);
+ overflowBackgroundLru(service);
+
+ expect(events(RUN)).toHaveLength(1);
+ });
+
+ it("keeps the previous completed cloud transcript warm", () => {
+ const service = makeService();
+ seedSession({ status: "connected", cloudStatus: "completed" });
+
+ background(service);
- vi.advanceTimersByTime(GRACE_MS);
expect(events()).toHaveLength(1);
});
- it("ensureEventsLoaded cancels a pending eviction", () => {
+ it("never backgrounds a session with a prompt in flight", () => {
const service = makeService();
- seed("disconnected");
+ seedSession({ status: "disconnected", isPromptPending: true });
+
+ background(service);
+
+ expect(events()).toHaveLength(1);
+ });
+
+ it("ensureEventsLoaded cancels pending backgrounding", async () => {
+ const service = makeService();
+ seedSession({ status: "disconnected" });
service.scheduleEventEviction(TASK);
- void service.ensureEventsLoaded(TASK); // return to the view before grace
+ await service.ensureEventsLoaded(TASK);
vi.advanceTimersByTime(GRACE_MS);
+
expect(events()).toHaveLength(1);
});
- it("rehydrates an evicted transcript from disk on return", async () => {
+ it("evicts the least recently viewed transcript when the LRU overflows", () => {
+ const service = makeService();
+ seedSession({ status: "disconnected" });
+ background(service);
+
+ overflowBackgroundLru(service);
+
+ expect(events(RUN)).toHaveLength(0);
+ expect(events(SECOND_RUN)).toHaveLength(1);
+ });
+
+ it.each([
+ { label: "reconnected", revive: { status: "connected" as SessionStatus } },
+ { label: "prompt in flight", revive: { isPromptPending: true } },
+ ])(
+ "does not evict a cached transcript that went live again ($label)",
+ ({ revive }) => {
+ const service = makeService();
+ seedSession({ status: "disconnected" });
+ background(service);
+
+ sessionStoreSetters.updateSession(RUN, revive);
+
+ overflowBackgroundLru(service);
+
+ expect(events(RUN)).toHaveLength(1);
+ expect(events(SECOND_RUN)).toHaveLength(1);
+ },
+ );
+
+ it("keeps back-and-forth navigation warm", async () => {
const readLocalLogs = vi.fn().mockResolvedValue(LOG_LINE);
const service = makeService(readLocalLogs);
- seed("disconnected");
+ seedSession({ status: "disconnected" });
+ background(service);
+ seedSession({
+ taskRunId: SECOND_RUN,
+ taskId: SECOND_TASK,
+ status: "disconnected",
+ });
- service.scheduleEventEviction(TASK);
- vi.advanceTimersByTime(GRACE_MS);
- expect(events()).toHaveLength(0);
+ await service.ensureEventsLoaded(TASK);
+ background(service, SECOND_TASK);
+ await service.ensureEventsLoaded(SECOND_TASK);
+
+ expect(events(RUN)).toHaveLength(1);
+ expect(events(SECOND_RUN)).toHaveLength(1);
+ expect(readLocalLogs).not.toHaveBeenCalled();
+ });
+
+ it("rehydrates an LRU-evicted transcript from disk on return", async () => {
+ const readLocalLogs = vi.fn().mockResolvedValue(LOG_LINE);
+ const service = makeService(readLocalLogs);
+ seedSession({ status: "disconnected" });
+ background(service);
+ overflowBackgroundLru(service);
await service.ensureEventsLoaded(TASK);
+
expect(readLocalLogs).toHaveBeenCalledWith({ taskRunId: RUN });
expect(events()).toHaveLength(1);
});
- it("retries rehydration after a failed log read instead of stranding it", async () => {
+ it("rehydrates a completed cloud transcript through its run chain", async () => {
+ const getTaskRunSessionLogsPage = vi.fn().mockResolvedValue({
+ entries: [JSON.parse(LOG_LINE)],
+ hasMore: false,
+ matchingCount: 1,
+ });
+ const readLocalLogs = vi.fn().mockResolvedValue("");
+ const service = makeService(readLocalLogs, getTaskRunSessionLogsPage);
+ seedSession({ status: "connected", cloudStatus: "completed" });
+ background(service);
+ overflowBackgroundLru(service);
+
+ await service.ensureEventsLoaded(TASK);
+
+ expect(getTaskRunSessionLogsPage).toHaveBeenCalledWith(TASK, RUN, {
+ limit: 1,
+ });
+ expect(readLocalLogs).not.toHaveBeenCalled();
+ expect(events()).toHaveLength(1);
+ });
+
+ it("enters the LRU after a terminal transcript hydrates past the grace window", () => {
+ const service = makeService();
+ seedSession({ status: "connected", cloudStatus: "completed" });
+ background(service);
+
+ seedSession({
+ taskRunId: SECOND_RUN,
+ taskId: SECOND_TASK,
+ status: "connected",
+ cloudStatus: "completed",
+ isHydratingTranscript: true,
+ withEvents: false,
+ });
+ background(service, SECOND_TASK);
+
+ expect(events(RUN)).toHaveLength(1);
+ expect(events(SECOND_RUN)).toHaveLength(0);
+
+ sessionStoreSetters.updateSession(SECOND_RUN, {
+ isHydratingTranscript: false,
+ });
+ sessionStoreSetters.appendEvents(SECOND_RUN, [
+ { ts: 1, message: {} } as never,
+ ]);
+
+ vi.advanceTimersByTime(GRACE_MS);
+
+ expect(events(SECOND_RUN)).toHaveLength(1);
+ expect(events(RUN)).toHaveLength(0);
+ });
+
+ it("retries rehydration after a failed log read", async () => {
const readLocalLogs = vi
.fn()
.mockRejectedValueOnce(new Error("transient"))
.mockResolvedValueOnce(LOG_LINE);
const service = makeService(readLocalLogs);
- seed("disconnected");
-
- service.scheduleEventEviction(TASK);
- vi.advanceTimersByTime(GRACE_MS);
- expect(events()).toHaveLength(0);
+ seedSession({ status: "disconnected" });
+ background(service);
+ overflowBackgroundLru(service);
- // First visit: the log read throws — the transcript stays empty but the
- // run is re-marked evicted so a later visit can retry.
await service.ensureEventsLoaded(TASK);
expect(events()).toHaveLength(0);
- // Second visit: the read succeeds and the transcript is restored.
await service.ensureEventsLoaded(TASK);
expect(events()).toHaveLength(1);
expect(readLocalLogs).toHaveBeenCalledTimes(2);
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index db6a23cd5201..9136c03979b7 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -200,13 +200,8 @@ interface SteeredTurn {
taskRunId: string;
promptId: number | null;
}
-/**
- * A backgrounded session's transcript is freed this long after it stops being
- * viewed, and reloaded from disk on return. Only disconnected (idle, no live
- * subscription) sessions are eligible, so no streamed event can append to an
- * evicted transcript.
- */
const SESSION_EVENT_EVICT_GRACE_MS = 20_000;
+const MAX_RESIDENT_BACKGROUND_TRANSCRIPTS = 1;
/**
* On open, paint the last this-many bytes of the log immediately so a big
* transcript shows its latest turns in tens of ms, while the authoritative
@@ -2366,6 +2361,7 @@ export class SessionService {
this.unsubscribeFromChannel(taskRunId);
this.cancelEventEviction(taskRunId);
this.evictedRunIds.delete(taskRunId);
+ this.residentBackgroundRunIds.delete(taskRunId);
this.d.store.removeSession(taskRunId);
this.cloudRunIdleTracker.delete(taskRunId);
this.cloudLogGapReconciler.forgetDeficiency(taskRunId);
@@ -2886,42 +2882,47 @@ export class SessionService {
/** taskRunIds whose transcript was freed and must be reloaded on next view. */
private evictedRunIds = new Set<string>();
+ private residentBackgroundRunIds = new Set<string>();
private eventEvictionTimers = new Map<
string,
ReturnType<typeof setTimeout>
>();
- /**
- * Called when a task's transcript becomes visible. Cancels any pending
- * eviction and, if the transcript was freed while backgrounded, reloads it
- * from disk — but only if a reconnect hasn't already refilled it.
- */
async ensureEventsLoaded(taskId: string): Promise<void> {
const session = this.d.store.getSessionByTaskId(taskId);
if (!session) return;
const { taskRunId } = session;
this.cancelEventEviction(taskRunId);
+ this.residentBackgroundRunIds.delete(taskRunId);
if (!this.evictedRunIds.has(taskRunId)) return;
try {
if (session.events.length === 0) {
- const { rawEntries, totalLineCount } = await this.fetchSessionLogs(
- session.logUrl,
- taskRunId,
- );
- // A reconnect may have refilled events while we awaited the log read;
- // only restore if the transcript is still empty for the same run.
- const fresh = this.d.store.getSessionByTaskId(taskId);
- if (
- fresh?.taskRunId === taskRunId &&
- fresh.events.length === 0 &&
- rawEntries.length > 0
- ) {
- this.d.store.restoreEvents(
+ if (session.isCloud && isTerminalStatus(session.cloudStatus)) {
+ await this.hydrateCloudTaskSessionFromLogs(
+ taskId,
taskRunId,
- convertStoredEntriesToEvents(rawEntries),
- totalLineCount,
+ session.logUrl,
+ undefined,
+ session.cloudStatus,
);
+ } else {
+ const { rawEntries, totalLineCount } = await this.fetchSessionLogs(
+ session.logUrl,
+ taskRunId,
+ );
+ const fresh = this.d.store.getSessionByTaskId(taskId);
+ if (
+ fresh?.taskRunId === taskRunId &&
+ fresh.events.length === 0 &&
+ rawEntries.length > 0
+ ) {
+ this.d.store.restoreEvents(
+ taskRunId,
+ convertStoredEntriesToEvents(rawEntries),
+ totalLineCount,
+ );
+ }
}
}
// Clear the evicted flag only once the transcript is populated — restored
@@ -2940,34 +2941,63 @@ export class SessionService {
}
}
- /**
- * Called when a task's transcript stops being visible. Schedules its
- * transcript to be freed after a grace period, if it's still a settled,
- * disconnected background session by then.
- */
scheduleEventEviction(taskId: string): void {
const session = this.d.store.getSessionByTaskId(taskId);
if (!session) return;
const { taskRunId } = session;
if (this.eventEvictionTimers.has(taskRunId)) return;
+ this.armEventEvictionTimer(taskRunId);
+ }
+
+ private isTranscriptEvictable(
+ session: AgentSession | undefined,
+ ): session is AgentSession {
+ if (!session || session.isPromptPending) return false;
+ // A cloud run's `status` can read "disconnected" while the run is still
+ // alive (cloud handoff and SSE-retry both write it), so a cloud transcript
+ // is only safe to release once its `cloudStatus` is terminal, mirroring
+ // isSessionIdle. Local runs still key off `status`.
+ return session.isCloud
+ ? isTerminalStatus(session.cloudStatus)
+ : session.status === "disconnected";
+ }
+ private armEventEvictionTimer(taskRunId: string): void {
const timer = setTimeout(() => {
this.eventEvictionTimers.delete(taskRunId);
const current = this.d.store.getSessions()[taskRunId];
- if (
- !current ||
- current.status !== "disconnected" ||
- current.isPromptPending ||
- current.events.length === 0
- ) {
+ if (!this.isTranscriptEvictable(current)) {
return;
}
- this.evictedRunIds.add(taskRunId);
- this.d.store.evictEvents(taskRunId);
+ if (current.events.length === 0) {
+ if (current.isHydratingTranscript) {
+ this.armEventEvictionTimer(taskRunId);
+ }
+ return;
+ }
+ this.residentBackgroundRunIds.delete(taskRunId);
+ this.residentBackgroundRunIds.add(taskRunId);
+ this.trimBackgroundTranscripts();
}, SESSION_EVENT_EVICT_GRACE_MS);
this.eventEvictionTimers.set(taskRunId, timer);
}
+ private trimBackgroundTranscripts(): void {
+ while (
+ this.residentBackgroundRunIds.size > MAX_RESIDENT_BACKGROUND_TRANSCRIPTS
+ ) {
+ const oldestRunId = this.residentBackgroundRunIds.values().next().value;
+ if (oldestRunId === undefined) return;
+ this.residentBackgroundRunIds.delete(oldestRunId);
+ const session = this.d.store.getSessions()[oldestRunId];
+ if (!this.isTranscriptEvictable(session) || session.events.length === 0) {
+ continue;
+ }
+ this.evictedRunIds.add(oldestRunId);
+ this.d.store.evictEvents(oldestRunId);
+ }
+ }
+
private cancelEventEviction(taskRunId: string): void {
const timer = this.eventEvictionTimers.get(taskRunId);
if (timer !== undefined) {
@@ -3128,6 +3158,7 @@ export class SessionService {
for (const timer of this.eventEvictionTimers.values()) clearTimeout(timer);
this.eventEvictionTimers.clear();
this.evictedRunIds.clear();
+ this.residentBackgroundRunIds.clear();
this.connectingTasks.clear();
this.localRepoPaths.clear();
this.localRecoveryAttempts.clear();