mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
623eb3685f | ||
|
|
91be92fa69 |
+17
-4
@@ -202,10 +202,23 @@ 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.
|
||||
|
||||
An agent counts as archived when the active list omits it, when its row has an archive timestamp,
|
||||
or when the workspace list omits its workspace. The workspace check matters because a workspace
|
||||
archive can complete while one of its agents keeps a row with no archive timestamp. Until a list
|
||||
first hydrates, it marks no agent as archived. 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 {
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -7,9 +7,17 @@ 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,
|
||||
WorkspaceDescriptorPayload,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { FetchAgentsEntry } from "@getpaseo/client/internal/daemon-client";
|
||||
import { AgentDirectoryReplica } from "@/runtime/directory-sync/agent-replica";
|
||||
import { WorkspaceDirectoryReplica } from "@/runtime/directory-sync/workspace-replica";
|
||||
import type { CachedTimeline } from "@/runtime/replica-cache";
|
||||
import {
|
||||
normalizeWorkspaceDescriptor,
|
||||
selectAgentTimelineState,
|
||||
selectAgentTimelineTurnPresentation,
|
||||
selectAgentTurnPresentation,
|
||||
@@ -1802,3 +1810,365 @@ describe("SQLite baseline restoration", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("archived timeline lifetime", () => {
|
||||
const ACTIVE = "active-agent";
|
||||
const OTHER = "other-agent";
|
||||
const ARCHIVED = "archived-agent";
|
||||
/** An agent whose row never got its archive timestamp, in a workspace that was archived. */
|
||||
const IN_ARCHIVED_WORKSPACE = "agent-in-archived-workspace";
|
||||
const WORKSPACE = "workspace";
|
||||
const ARCHIVED_WORKSPACE = "archived-workspace";
|
||||
const openOwners: ViewedTimelineOwner[] = [];
|
||||
afterEach(() => {
|
||||
for (const owner of openOwners.splice(0)) owner.dispose();
|
||||
});
|
||||
|
||||
function agentPayload(
|
||||
id: string,
|
||||
archivedAt?: string,
|
||||
workspaceId: string = WORKSPACE,
|
||||
): AgentSnapshotPayload {
|
||||
return {
|
||||
id,
|
||||
workspaceId,
|
||||
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,
|
||||
);
|
||||
const workspaces = new WorkspaceDirectoryReplica(SERVER_ID);
|
||||
workspaces.commitSnapshot(
|
||||
{
|
||||
workspaces: new Map([[WORKSPACE, normalizeWorkspaceDescriptor(workspaceDescriptor())]]),
|
||||
projects: new Map(),
|
||||
},
|
||||
[],
|
||||
);
|
||||
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"),
|
||||
);
|
||||
}
|
||||
if (agentId === IN_ARCHIVED_WORKSPACE) {
|
||||
directory.submitTimelineAgent(
|
||||
directory.captureTimeline(agentId),
|
||||
agentPayload(agentId, undefined, ARCHIVED_WORKSPACE),
|
||||
);
|
||||
}
|
||||
owner.applyTimelineResponse(historyPage(agentId));
|
||||
return { hasNewer: false, endCursor: null };
|
||||
},
|
||||
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
|
||||
reportError: () => undefined,
|
||||
},
|
||||
});
|
||||
owner.setConnected(true);
|
||||
openOwners.push(owner);
|
||||
return {
|
||||
directory,
|
||||
workspaces,
|
||||
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 workspaceDescriptor(): WorkspaceDescriptorPayload {
|
||||
return {
|
||||
id: WORKSPACE,
|
||||
projectId: "project",
|
||||
projectDisplayName: "project",
|
||||
projectRootPath: "/repo",
|
||||
workspaceDirectory: "/repo",
|
||||
projectKind: "git",
|
||||
workspaceKind: "worktree",
|
||||
name: WORKSPACE,
|
||||
title: WORKSPACE,
|
||||
status: "done",
|
||||
activityAt: null,
|
||||
statusEnteredAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
};
|
||||
}
|
||||
|
||||
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]);
|
||||
});
|
||||
|
||||
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]);
|
||||
});
|
||||
|
||||
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([]);
|
||||
});
|
||||
|
||||
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([]);
|
||||
});
|
||||
|
||||
it("releases hidden timelines of a removed workspace whose agent rows still look active", 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.workspaces.removeWorkspaceSnapshot(WORKSPACE);
|
||||
|
||||
expect(timelineStatus(OTHER)).toBe("synced");
|
||||
expect(residentAgentIds()).toEqual([OTHER]);
|
||||
host.view([]);
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
it("releases a History chat whose unarchived row belongs to an archived workspace", async () => {
|
||||
const host = openHost([ACTIVE]);
|
||||
host.view([IN_ARCHIVED_WORKSPACE]);
|
||||
await expect.poll(() => timelineStatus(IN_ARCHIVED_WORKSPACE)).toBe("synced");
|
||||
|
||||
host.view([]);
|
||||
|
||||
expect(timelineStatus(IN_ARCHIVED_WORKSPACE)).toBe("cold");
|
||||
expect(residentAgentIds()).toEqual([]);
|
||||
});
|
||||
|
||||
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]);
|
||||
});
|
||||
|
||||
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([]);
|
||||
});
|
||||
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,40 @@ 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 ||
|
||||
session?.workspaces !== observedSession?.workspaces ||
|
||||
session?.hasHydratedWorkspaces !== observedSession?.hasHydratedWorkspaces;
|
||||
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 +589,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 +601,38 @@ export function createViewedTimelineOwner(input: {
|
||||
streamQueue.flushAgent(agentId);
|
||||
},
|
||||
dispose() {
|
||||
stopObservingArchive();
|
||||
streamQueue.dispose({ flush: true });
|
||||
sync.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* An agent is archived once the hydrated active list lacks it, its row carries an archive
|
||||
* timestamp, or the hydrated workspace list lacks its workspace. Workspace archive can leave
|
||||
* an agent row without a timestamp. Until a list hydrates, it rules nothing out.
|
||||
*/
|
||||
function isAgentArchived(session: SessionState | undefined, agentId: string): boolean {
|
||||
if (!session?.hasHydratedAgents) return false;
|
||||
const agent = session.agents.get(agentId) ?? session.agentDetails.get(agentId);
|
||||
if (!agent || agent.archivedAt != null) return true;
|
||||
return (
|
||||
session.hasHydratedWorkspaces &&
|
||||
agent.workspaceId !== undefined &&
|
||||
!session.workspaces.has(agent.workspaceId)
|
||||
);
|
||||
}
|
||||
|
||||
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 +696,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 +876,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 +1169,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);
|
||||
|
||||
Reference in New Issue
Block a user