fix(app): release archived chat timelines once nobody shows them

Archiving an agent or its workspace removed it from the active list but left its
transcript in the session store until reload, and so did opening an archived chat
from History and leaving it.

The viewed-timeline owner now owns transcript lifetime: an active agent's
transcript stays resident while hidden, so switching tabs needs no fetch; an
archived agent's transcript stays only while its chat is shown. Late history
pages, live events, and cache reads for a released chat are dropped, and the
chat leaves the opened chats so showing it again catches up afresh. Active-list
reconciliation still keeps the transcript, preserving the History invariant
from #4736.

Refs #6477
This commit is contained in:
Mohamed Boudra
2026-11-26 02:25:15 +01:00
parent e51bb7b8cd
commit 91be92fa69
7 changed files with 449 additions and 18 deletions
+14 -4
View File
@@ -202,10 +202,20 @@ owner wraps cached preparation, network catch-up, accepted timeline application,
behind one interface. React supplies transport and projection operations without selecting a cache
path or issuing a separate persistence notification.
Active-agent list reconciliation does not own transcript lifetime. An archived agent's fresh
history response can arrive before the active-list response that omits it. Clearing history there
would discard accepted rows while the viewed owner still considers them synchronized. Entity
deletion clears the transcript; list membership changes do not.
The viewed-timeline owner also owns how long a transcript stays in memory. An active agent's
transcript stays resident while its chat is hidden, so switching back to it needs no fetch. An
archived agent's transcript stays resident only while its chat is shown, for example when it is
opened from History. When an agent is archived, or the active list drops it because its workspace
was archived, the owner releases the transcript unless the chat is shown. It also releases the
transcript when the chat stops being shown. A released chat leaves the opened chats. When it is
shown again, it reads the replica cache and catches up again. A history page, live event, or cache
read that arrives after the release is dropped.
The active-list reconciliation does not release transcripts itself. An archived agent's fresh
history response can arrive before the active-list response that omits it, while the chat is
open in History. Clearing history there would discard rows the user is reading. Until the active
list first hydrates, no agent is known to be archived, and every transcript stays. Deleting the
agent clears the transcript.
Removing the host from the registry is the destructive boundary: it stops the runtime and clears the
session and host-scoped setup state together.
@@ -201,15 +201,9 @@ export class AgentStoreProjection {
useDraftStore.getState().clearDraftInput({
draftKey: buildDraftStoreKey({ serverId: this.serverId, agentId }),
});
// Only entity deletion destroys the transcript. A filtered active-list
// response can arrive after a fresh history response for an archived agent.
const store = useSessionStore.getState();
const removeKey = withoutAgent(agentId);
store.setAgentTimelineCursor(this.serverId, removeKey);
store.setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
store.setAgentAuthoritativeHistoryApplied(this.serverId, agentId, false);
store.setAgentStreamTail(this.serverId, removeKey);
store.clearAgentStreamHead(this.serverId, agentId);
// Leaving the active list does not release the transcript: an archived chat open in
// History stays readable. The viewed timeline owner releases it once nobody shows it.
useSessionStore.getState().releaseAgentTimeline(this.serverId, agentId);
}
archive(agentId: string, archivedAt: string): Agent | null {
+31
View File
@@ -603,6 +603,8 @@ interface SessionStoreActions {
message: UserMessageItem,
) => boolean;
clearAgentStreamHead: (serverId: string, agentId: string) => void;
/** Drops every piece of one chat's resident transcript: rows, cursors, paging and sync marks. */
releaseAgentTimeline: (serverId: string, agentId: string) => void;
setAgentTimelineCursor: (
serverId: string,
state:
@@ -1342,6 +1344,35 @@ export const useSessionStore = create<SessionStore>()(
});
},
releaseAgentTimeline: (serverId, agentId) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) return prev;
const timelineKeys = [
"agentStreamTail",
"agentStreamHead",
"agentTasks",
"agentTimelineCursor",
"agentTimelineUnsettledTurn",
"agentTimelineHasOlder",
"agentTimelineHasNewer",
"agentTimelineOlderFetchInFlight",
"agentHistorySyncGeneration",
"agentAuthoritativeHistoryApplied",
] as const satisfies readonly (keyof SessionState)[];
let next: SessionState | null = null;
for (const key of timelineKeys) {
const current: Map<string, unknown> = session[key];
if (!current.has(agentId)) continue;
const without = new Map(current);
without.delete(agentId);
next = { ...(next ?? session), [key]: without };
}
if (!next) return prev;
return { ...prev, sessions: { ...prev.sessions, [serverId]: next } };
});
},
setAgentTimelineCursor: (serverId, state) => {
set((prev) => {
const session = prev.sessions[serverId];
@@ -165,6 +165,7 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti
const sync = createViewedTimelineSync({
replaceDemandedAgentIds: () => undefined,
prepare: async () => undefined,
isArchived: () => false,
canCheckFreshness: () => false,
applyCurrentTimeline: () => undefined,
observe: (agentIds) => {
+297 -1
View File
@@ -7,7 +7,9 @@ import {
} from "@/runtime/replica-cache/row-store-sqlite";
import { afterEach, describe, expect, it } from "vitest";
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import type { AgentSnapshotPayload, AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import type { FetchAgentsEntry } from "@getpaseo/client/internal/daemon-client";
import { AgentDirectoryReplica } from "@/runtime/directory-sync/agent-replica";
import type { CachedTimeline } from "@/runtime/replica-cache";
import {
selectAgentTimelineState,
@@ -1802,3 +1804,297 @@ describe("SQLite baseline restoration", () => {
}
});
});
describe("archived timeline lifetime", () => {
const ACTIVE = "active-agent";
const OTHER = "other-agent";
const ARCHIVED = "archived-agent";
function agentPayload(id: string, archivedAt?: string): AgentSnapshotPayload {
return {
id,
provider: "codex",
cwd: "/repo",
model: null,
createdAt: "2026-07-17T00:00:00.000Z",
updatedAt: "2026-07-17T00:01:00.000Z",
lastUserMessageAt: null,
status: "idle",
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
currentModeId: null,
availableModes: [],
pendingPermissions: [],
persistence: null,
title: id,
labels: {},
...(archivedAt ? { archivedAt } : {}),
};
}
function directoryEntry(id: string): FetchAgentsEntry {
return {
agent: agentPayload(id),
project: {
projectKey: "/repo",
projectName: "repo",
checkout: {
cwd: "/repo",
isGit: false,
currentBranch: null,
remoteUrl: null,
worktreeRoot: null,
isPaseoOwnedWorktree: false,
mainRepoRoot: null,
},
},
};
}
function historyPage(agentId: string): TimelineResponsePayload {
return {
requestId: `tail-${agentId}`,
agentId,
agent: null,
direction: "tail",
projection: "projected",
reset: false,
epoch: "epoch-1",
window: { minSeq: 1, maxSeq: 1, nextSeq: 2 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 1 },
entries: [
{
provider: "codex",
item: { type: "assistant_message", text: `history of ${agentId}` },
timestamp: "2026-08-26T10:00:00.000Z",
seqStart: 1,
seqEnd: 1,
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
collapsed: [],
},
],
error: null,
hasNewer: false,
hasOlder: false,
staleCursor: false,
gap: false,
};
}
/**
* A host with an active directory and a viewed-timeline owner. Fetches reach the store the
* way the host runtime delivers them: the agent row first, then the page, whether or not
* the catch-up that asked for it is still current.
*/
function openHost(
activeAgentIds: string[],
storage: TimelineReplicaStorage = {
readTimeline: async () => undefined,
commitTimeline: () => undefined,
},
) {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const directory = new AgentDirectoryReplica(
SERVER_ID,
() => undefined,
() => undefined,
);
directory.commitSnapshot(activeAgentIds.map(directoryEntry), []);
const fetches: string[] = [];
const held = new Map<string, () => void>();
const holding = new Set<string>();
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage,
prepareAgent: async () => undefined,
});
const owner: ViewedTimelineOwner = createViewedTimelineOwner({
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => false,
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
readCursor: () => undefined,
fetchPage: async (agentId) => {
fetches.push(agentId);
if (holding.has(agentId)) {
await new Promise<void>((resolve) => held.set(agentId, resolve));
}
if (agentId === ARCHIVED) {
directory.submitTimelineAgent(
directory.captureTimeline(agentId),
agentPayload(agentId, "2026-09-11T00:00:00.000Z"),
);
}
owner.applyTimelineResponse(historyPage(agentId));
return { hasNewer: false, endCursor: null };
},
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
reportError: () => undefined,
},
});
owner.setConnected(true);
return {
directory,
owner,
fetches,
view(agentIds: string[]) {
owner.replaceVisibleAgentIds("workspace", agentIds);
},
hold(agentId: string) {
holding.add(agentId);
},
async deliverHeld(agentId: string) {
await expect.poll(() => held.has(agentId)).toBe(true);
held.get(agentId)?.();
await new Promise((resolve) => setTimeout(resolve, 0));
},
};
}
function timelineStatus(agentId: string): string {
return selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], agentId).status;
}
function residentAgentIds(): string[] {
const session = useSessionStore.getState().sessions[SERVER_ID];
if (!session) return [];
return [
...new Set([
...session.agentStreamTail.keys(),
...session.agentStreamHead.keys(),
...session.agentTimelineCursor.keys(),
...session.agentAuthoritativeHistoryApplied.keys(),
...session.agentTimelineHasOlder.keys(),
...session.agentTimelineHasNewer.keys(),
...session.agentHistorySyncGeneration.keys(),
]),
].sort();
}
it("keeps hidden active chats cached and switches back without a fetch", async () => {
const host = openHost([ACTIVE, OTHER]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.view([OTHER]);
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
host.view([ACTIVE]);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(timelineStatus(ACTIVE)).toBe("synced");
expect(timelineStatus(OTHER)).toBe("synced");
expect(host.fetches).toEqual([ACTIVE, OTHER]);
host.owner.dispose();
});
it("releases a hidden chat's timeline when its agent is archived", async () => {
const host = openHost([ACTIVE, OTHER]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.view([OTHER]);
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
host.directory.applyDelta({ kind: "remove", agentId: ACTIVE });
expect(timelineStatus(ACTIVE)).toBe("cold");
expect(residentAgentIds()).toEqual([OTHER]);
host.owner.dispose();
});
it("releases an archived chat's timeline once its tab is no longer shown", async () => {
const host = openHost([ACTIVE]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.directory.archive(ACTIVE, "2026-09-11T00:00:00.000Z");
expect(timelineStatus(ACTIVE)).toBe("synced");
host.view([]);
expect(timelineStatus(ACTIVE)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
host.owner.dispose();
});
it("releases every timeline of a workspace when the active list drops its agents", async () => {
const host = openHost([ACTIVE, OTHER]);
host.view([ACTIVE]);
await expect.poll(() => timelineStatus(ACTIVE)).toBe("synced");
host.view([OTHER]);
await expect.poll(() => timelineStatus(OTHER)).toBe("synced");
host.view([]);
host.directory.commitSnapshot([], []);
expect(residentAgentIds()).toEqual([]);
host.owner.dispose();
});
it("keeps an archived chat open from History through active-list syncs and releases it on leave", async () => {
const host = openHost([ACTIVE]);
host.view([ARCHIVED]);
await expect.poll(() => timelineStatus(ARCHIVED)).toBe("synced");
host.directory.commitSnapshot([directoryEntry(ACTIVE)], []);
host.directory.applyDelta({ kind: "remove", agentId: ARCHIVED });
expect(timelineStatus(ARCHIVED)).toBe("synced");
host.view([]);
expect(timelineStatus(ARCHIVED)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
host.view([ARCHIVED]);
await expect.poll(() => timelineStatus(ARCHIVED)).toBe("synced");
expect(host.fetches).toEqual([ARCHIVED, ARCHIVED]);
host.owner.dispose();
});
it("ignores a History read that answers after the archived chat was left", async () => {
const host = openHost([ACTIVE]);
host.hold(ARCHIVED);
host.view([ARCHIVED]);
await expect.poll(() => host.fetches).toEqual([ARCHIVED]);
host.view([]);
await host.deliverHeld(ARCHIVED);
expect(timelineStatus(ARCHIVED)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
host.owner.dispose();
});
it("does not paint a cached archived chat back after it was left", async () => {
let finishRead!: () => void;
const readStarted = new Promise<void>((resolve) => {
finishRead = resolve;
});
let reading = false;
const host = openHost([ACTIVE], {
readTimeline: async (_serverId, agentId) => {
reading = true;
await readStarted;
return { ...cachedTimeline(), agentId };
},
commitTimeline: () => undefined,
});
host.view([ARCHIVED]);
await expect.poll(() => reading).toBe(true);
host.view([]);
finishRead();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(timelineStatus(ARCHIVED)).toBe("cold");
expect(residentAgentIds()).toEqual([]);
host.owner.dispose();
});
});
@@ -208,6 +208,7 @@ class TimelineWorld {
},
onCatchUpOwed: () => undefined,
onCatchUpSettled: () => undefined,
isArchived: () => false,
prepare: async (agentId) => {
this.cacheRequests.push(agentId);
this.cacheRequestWaiters.shift()?.(agentId);
@@ -11,6 +11,7 @@ import {
useSessionStore,
type AgentTimelineCursorState,
type AgentTimelineState,
type SessionState,
} from "@/stores/session-store";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
@@ -102,6 +103,8 @@ export interface TimelineReplica {
timelineUpdated(agentId: string): void;
catchUpOwed(agentId: string): void;
catchUpSettled(agentId: string): void;
/** Forgets a released chat's cached range, so showing it again reads the cache afresh. */
release(agentId: string): void;
}
class TimelineReplicaOwner implements TimelineReplica {
@@ -187,6 +190,10 @@ class TimelineReplicaOwner implements TimelineReplica {
if (this.preparations.has(agentId)) this.settledDuringPreparation.add(agentId);
useSessionStore.getState().setAgentTimelineUnsettledTurn(this.serverId, agentId, null);
}
release(agentId: string): void {
this.cachedRanges.delete(agentId);
}
}
export function createTimelineReplica(input: {
@@ -375,6 +382,11 @@ function buildCurrentTimelinePage(
export interface ViewedTimelineSyncPorts {
prepare(agentId: string): Promise<void>;
/**
* Whether the agent left the active list: it, or its workspace, is archived. A hidden chat
* of an archived agent leaves the opened chats, so showing it again reads it afresh.
*/
isArchived(agentId: string): boolean;
replaceDemandedAgentIds(agentIds: string[]): void;
/** Whether the daemon answers with each cursor's freshness in the subscribe response. */
canCheckFreshness(): boolean;
@@ -447,9 +459,17 @@ export interface ViewedTimelineSync extends ViewedTimelineUiBridge {
dispose(): void;
}
/** What the timeline owner needs from membership beyond the UI-facing surface. */
export interface ViewedTimelineMembership extends ViewedTimelineSync {
isVisible(agentId: string): boolean;
/** Re-reads `isArchived` for the opened chats, after the active list changed. */
archiveChanged(): void;
}
export type ViewedTimelineOwnerPorts = Omit<
ViewedTimelineSyncPorts,
| "prepare"
| "isArchived"
| "replaceDemandedAgentIds"
| "onCatchUpEnded"
| "onCatchUpOwed"
@@ -477,8 +497,14 @@ export function createViewedTimelineOwner(input: {
ports: ViewedTimelineOwnerPorts;
}): ViewedTimelineOwner {
const forcedTailReplacements = new Set<string>();
const isArchived = (agentId: string) =>
isAgentArchived(useSessionStore.getState().sessions[input.serverId], agentId);
// Active chats stay resident while hidden so switching back needs no fetch. An archived
// chat is resident only while it is shown, as when it is open from History.
const isResident = (agentId: string) => sync.isVisible(agentId) || !isArchived(agentId);
const sync = createViewedTimelineSync({
...input.ports,
isArchived,
fetchLatestTail: async (agentId) => {
forcedTailReplacements.add(agentId);
try {
@@ -487,7 +513,11 @@ export function createViewedTimelineOwner(input: {
forcedTailReplacements.delete(agentId);
}
},
prepare: (agentId) => input.replica.prepare(agentId),
prepare: async (agentId) => {
await input.replica.prepare(agentId);
// A cache read that lands after its archived chat was left paints a chat nobody shows.
releaseHiddenArchivedTimelines();
},
readCursor: (agentId) => input.replica.readCursor(agentId) ?? input.ports.readCursor(agentId),
replaceDemandedAgentIds: input.replaceDemandedAgentIds,
applyCurrentTimeline: (agentId) => {
@@ -514,9 +544,38 @@ export function createViewedTimelineOwner(input: {
recoverTimelineGap: (agentId, cursor) => sync.recoverGap(agentId, cursor),
onCommitted: (agentId) => input.replica.timelineUpdated(agentId),
});
const releaseHiddenArchivedTimelines = () => {
const session = useSessionStore.getState().sessions[input.serverId];
if (!session) return;
for (const agentId of selectResidentTimelineAgentIds(session)) {
if (isResident(agentId)) continue;
streamQueue.flushAgent(agentId);
input.replica.release(agentId);
useSessionStore.getState().releaseAgentTimeline(input.serverId, agentId);
}
};
// Archiving an agent or its workspace reaches this host as the agent leaving the active list.
let observedSession = useSessionStore.getState().sessions[input.serverId];
const stopObservingArchive = useSessionStore.subscribe((state) => {
const session = state.sessions[input.serverId];
const changed =
session?.agents !== observedSession?.agents ||
session?.agentDetails !== observedSession?.agentDetails ||
session?.hasHydratedAgents !== observedSession?.hasHydratedAgents;
observedSession = session;
if (!changed) return;
sync.archiveChanged();
releaseHiddenArchivedTimelines();
});
return {
...sync,
replaceVisibleAgentIds(sourceId, agentIds) {
sync.replaceVisibleAgentIds(sourceId, agentIds);
releaseHiddenArchivedTimelines();
},
applyTimelineResponse(receivedPayload) {
// A read that answers after its archived chat was released must not bring it back.
if (!isResident(receivedPayload.agentId)) return;
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
const accepted = applyAuthoritativeTimelineResponse({
serverId: input.serverId,
@@ -528,6 +587,7 @@ export function createViewedTimelineOwner(input: {
if (accepted) input.replica.timelineUpdated(payload.agentId);
},
applyStreamEvent(agentId, event) {
if (!isResident(agentId)) return;
streamQueue.enqueue(agentId, event);
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
if (turnLiveness.length === 0) return;
@@ -539,12 +599,29 @@ export function createViewedTimelineOwner(input: {
streamQueue.flushAgent(agentId);
},
dispose() {
stopObservingArchive();
streamQueue.dispose({ flush: true });
sync.dispose();
},
};
}
/** Until the active list has hydrated, no agent is known to have left it. */
function isAgentArchived(session: SessionState | undefined, agentId: string): boolean {
if (!session?.hasHydratedAgents) return false;
const agent = session.agents.get(agentId) ?? session.agentDetails.get(agentId);
return !agent || agent.archivedAt != null;
}
function selectResidentTimelineAgentIds(session: SessionState): Set<string> {
return new Set([
...session.agentStreamTail.keys(),
...session.agentStreamHead.keys(),
...session.agentTimelineCursor.keys(),
...session.agentAuthoritativeHistoryApplied.keys(),
]);
}
const MAX_HIDDEN_CATCH_UPS = 2;
type CatchUpStatus = "running" | "complete" | "error";
@@ -608,7 +685,7 @@ function sameAgentIds(left: string[], right: string[]): boolean {
return left.length === right.length && left.every((agentId, index) => agentId === right[index]);
}
export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): ViewedTimelineSync {
export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): ViewedTimelineMembership {
const sources = new Map<string, string[]>();
const catchUps = new Map<string, CatchUpState>();
const catchUpGenerations = new Map<string, number>();
@@ -788,10 +865,12 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const ensureCacheLoaded = (agentId: string): void => {
if (loadedCache.has(agentId) || cacheLoads.has(agentId)) return;
const load = ports
const load: Promise<void> = ports
.prepare(agentId)
.catch((error) => ports.reportError(error))
.finally(() => {
// A released chat forgot this load; showing it again starts its own.
if (cacheLoads.get(agentId) !== load) return;
cacheLoads.delete(agentId);
loadedCache.add(agentId);
const pending = pendingCatchUps.get(agentId);
@@ -1079,10 +1158,29 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
};
const publishVisibleMembership = () => {
commitDesiredMembership(normalizeAgentIds([...openedAgentIds, ...visibleAgentIds()]));
const visible = visibleAgentIds();
const kept = openedAgentIds.filter(
(agentId) => visible.includes(agentId) || !ports.isArchived(agentId),
);
if (kept.length !== openedAgentIds.length) {
for (const agentId of openedAgentIds) {
if (kept.includes(agentId)) continue;
loadedCache.delete(agentId);
cacheLoads.delete(agentId);
}
openedAgentIds = kept;
}
commitDesiredMembership(normalizeAgentIds([...openedAgentIds, ...visible]));
};
return {
isVisible(agentId) {
for (const agentIds of sources.values()) if (agentIds.includes(agentId)) return true;
return false;
},
archiveChanged() {
publishVisibleMembership();
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);