mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
fix(timeline): keep history on reopen, fail deletes that leave it, read only prompts for the outline
- Opening a stored agent with no provider session ran the fresh-create cleanup, which deleted its saved timeline. Now that history survives a restart, that open erased it; the record-based open now clears only the previous session's runtime state. - The delete RPC removed the registry record first and swallowed a failed history delete, replying agent_deleted while the transcript stayed on disk with no record to retry from. History now goes first and a failure reaches the client as rpc_error with the agent still listed. - The chat outline built its prompt index from every active row, which on SQLite decodes all replies and tool output. Backends now return the active prompt rows, which the rewind and import paths already read.
This commit is contained in:
@@ -46,8 +46,11 @@ deleting the agent, or a provider removing one of its own children, deletes hist
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Deleting the agent deletes its history and every child's, retired ones
|
||||
included.
|
||||
without its provider. Opening a stored agent that has no provider session to resume starts its
|
||||
first session on the same history.
|
||||
- **Delete** removes the agent's history and every child's, retired ones included, before the
|
||||
agent record. If the history cannot be removed, the request fails and the agent stays listed, so
|
||||
the user can delete it again.
|
||||
|
||||
`epoch` is the stored history's identity, minted once when the history is created.
|
||||
|
||||
|
||||
@@ -7058,6 +7058,47 @@ test("an internal agent's history stays out of the daemon database", async () =>
|
||||
expect(storedAgents).toEqual([visible.id]);
|
||||
});
|
||||
|
||||
test("reopening an agent the provider never gave a session keeps its saved history", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-reopen-without-session-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
const database = openTestTimelineDatabase();
|
||||
function startDaemon(): { manager: AgentManager; storage: AgentStorage } {
|
||||
const storage = new AgentStorage(storagePath, logger);
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
registry: storage,
|
||||
timeline: createStoredAgentTimeline(database),
|
||||
logger,
|
||||
});
|
||||
return { manager, storage };
|
||||
}
|
||||
const first = startDaemon();
|
||||
const agent = await first.manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const reply: AgentTimelineItem = { type: "assistant_message", text: "kept across restarts" };
|
||||
await first.manager.appendTimelineItem(agent.id, reply);
|
||||
await first.manager.closeAgent(agent.id);
|
||||
await first.manager.flush();
|
||||
const record = await first.storage.get(agent.id);
|
||||
if (!record) throw new Error("Created agent was not persisted");
|
||||
await first.storage.upsert({ ...record, persistence: null });
|
||||
|
||||
const second = startDaemon();
|
||||
onTestFinished(async () => {
|
||||
await second.manager.closeAgent(agent.id);
|
||||
await second.manager.flush();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
await ensureAgentLoaded(agent.id, {
|
||||
agentManager: second.manager,
|
||||
agentStorage: second.storage,
|
||||
logger,
|
||||
});
|
||||
|
||||
expect(await second.manager.getTimeline(agent.id)).toEqual([reply]);
|
||||
});
|
||||
|
||||
test("markAgentUnread restores error attention on a read errored agent", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
|
||||
@@ -1580,6 +1580,12 @@ export class AgentManager {
|
||||
return await this.timeline.readRows({ agentId: id });
|
||||
}
|
||||
|
||||
/** The agent's active prompt rows, without reading its replies or tool output. */
|
||||
async getTimelinePromptRows(id: string): Promise<AgentTimelineRow[]> {
|
||||
await this.requireHistory(id);
|
||||
return await this.timeline.readPromptRows({ agentId: id });
|
||||
}
|
||||
|
||||
/** The timeline head of a loaded agent, or null when this agent is not loaded. Never loads. */
|
||||
async getLoadedTimelineHead(id: string): Promise<TimelineHead | null> {
|
||||
if (!this.getAgent(id)) return null;
|
||||
@@ -1713,14 +1719,20 @@ export class AgentManager {
|
||||
`Agent ${resolvedAgentId} references unavailable provider '${record.provider}'`,
|
||||
);
|
||||
}
|
||||
return this.createAgentInternal(config, resolvedAgentId, {
|
||||
labels: record.labels,
|
||||
metadata: record.metadata,
|
||||
workspaceId: record.workspaceId,
|
||||
owner: record.owner,
|
||||
background: record.background,
|
||||
env: record.launchEnv,
|
||||
});
|
||||
return this.createAgentInternal(
|
||||
config,
|
||||
resolvedAgentId,
|
||||
{
|
||||
labels: record.labels,
|
||||
metadata: record.metadata,
|
||||
workspaceId: record.workspaceId,
|
||||
owner: record.owner,
|
||||
background: record.background,
|
||||
env: record.launchEnv,
|
||||
},
|
||||
// The stored agent's history is still its own; registration keeps it.
|
||||
{ history: "keep" },
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -1739,6 +1751,7 @@ export class AgentManager {
|
||||
config: AgentSessionConfig,
|
||||
resolvedAgentId: string,
|
||||
options: CreateAgentOptions,
|
||||
{ history }: { history: "discard" | "keep" } = { history: "discard" },
|
||||
): Promise<ManagedAgent> {
|
||||
this.assertAcceptingAgentRegistrations();
|
||||
config = this.withConvertedOptions(config);
|
||||
@@ -1762,7 +1775,8 @@ export class AgentManager {
|
||||
};
|
||||
options = { ...options, env: request.env, metadata: request.metadata ?? options.metadata };
|
||||
}
|
||||
await this.deleteAgentState(resolvedAgentId);
|
||||
if (history === "keep") this.discardRuntimeState(resolvedAgentId);
|
||||
else await this.deleteAgentState(resolvedAgentId);
|
||||
const { storedConfig, launchConfig, paseoToolPolicy } = await this.prepareSessionConfig(
|
||||
config,
|
||||
resolvedAgentId,
|
||||
@@ -5254,9 +5268,14 @@ export class AgentManager {
|
||||
|
||||
private async discardRetainedAgentState(agentId: string): Promise<void> {
|
||||
const removed = await this.providerSubagents.deleteParent(agentId);
|
||||
this.discardRuntimeState(agentId);
|
||||
for (const event of removed) this.publishProviderSubagent(event);
|
||||
}
|
||||
|
||||
/** What a previous session of the agent left in this process; its saved history stays. */
|
||||
private discardRuntimeState(agentId: string): void {
|
||||
this.paseoToolPolicies.delete(agentId);
|
||||
this.detachPluginTools(agentId);
|
||||
for (const event of removed) this.publishProviderSubagent(event);
|
||||
this.clearProviderBackgroundWork(agentId);
|
||||
}
|
||||
|
||||
|
||||
@@ -239,7 +239,7 @@ export class AgentTimeline {
|
||||
if (head.rewind) return { kind: "rewind_open" };
|
||||
const plan = planProviderHistory({
|
||||
rows: await this.backendFor(scope).readRows(scope),
|
||||
prompts: await this.backendFor(scope).prompts(scope),
|
||||
prompts: await this.prompts(scope),
|
||||
provider: entries.map(providerHistoryEntry),
|
||||
});
|
||||
if (plan.kind !== "append") return plan;
|
||||
@@ -394,6 +394,11 @@ export class AgentTimeline {
|
||||
return this.run(scope, () => this.backendFor(scope).readRows(scope));
|
||||
}
|
||||
|
||||
/** The active user prompt rows, without reading replies or tool output. */
|
||||
readPromptRows(scope: TimelineScope): Promise<ProjectedTimelineRow[]> {
|
||||
return this.run(scope, () => this.backendFor(scope).promptRows(scope));
|
||||
}
|
||||
|
||||
lastItem(scope: TimelineScope): Promise<AgentTimelineItem | null> {
|
||||
return this.run(scope, () => this.backendFor(scope).lastItem(scope));
|
||||
}
|
||||
@@ -415,9 +420,7 @@ export class AgentTimeline {
|
||||
return this.run(scope, async () => {
|
||||
const head = await this.requireHead(scope);
|
||||
if (head.rewind) throw new TimelineRewindPendingError(head.rewind);
|
||||
const target = (await this.backendFor(scope).prompts(scope)).find(
|
||||
(prompt) => prompt.messageId === messageId,
|
||||
);
|
||||
const target = (await this.prompts(scope)).find((prompt) => prompt.messageId === messageId);
|
||||
if (!target) throw new TimelineRewindTargetError(messageId);
|
||||
const intent: TimelineRewindIntent = {
|
||||
id: randomUUID(),
|
||||
@@ -464,11 +467,7 @@ export class AgentTimeline {
|
||||
return this.run(scope, async () => {
|
||||
const intent = (await this.requireHead(scope)).rewind;
|
||||
if (intent?.id !== intentId) return { kind: "absent" };
|
||||
return judgeRewindEvidence(
|
||||
intent,
|
||||
await this.backendFor(scope).prompts(scope),
|
||||
providerPromptIds,
|
||||
);
|
||||
return judgeRewindEvidence(intent, await this.prompts(scope), providerPromptIds);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -486,10 +485,7 @@ export class AgentTimeline {
|
||||
const intent = head.rewind;
|
||||
if (intent?.id !== intentId) return { kind: "absent" };
|
||||
if (!intent.cut) throw new Error("Cannot complete a rewind before its provider outcome");
|
||||
const retireFromSeq = resolveRetireFromSeq(
|
||||
intent,
|
||||
await this.backendFor(scope).prompts(scope),
|
||||
);
|
||||
const retireFromSeq = resolveRetireFromSeq(intent, await this.prompts(scope));
|
||||
if (retireFromSeq === null) throw new TimelineRewindBoundaryError(intent);
|
||||
const result = await this.backendFor(scope).retire(scope, {
|
||||
retireFromSeq,
|
||||
@@ -557,6 +553,10 @@ export class AgentTimeline {
|
||||
return this.memoryAgents.has(scope.agentId) ? this.memory : this.backend;
|
||||
}
|
||||
|
||||
private async prompts(scope: TimelineScope): Promise<TimelinePrompt[]> {
|
||||
return (await this.backendFor(scope).promptRows(scope)).map(toTimelinePrompt);
|
||||
}
|
||||
|
||||
/** An agent stays in memory until its history is deleted. */
|
||||
private retain(scope: TimelineScope, options: TimelineRetention): void {
|
||||
if (options.inMemory && scope.subagentId === undefined) this.memoryAgents.add(scope.agentId);
|
||||
@@ -705,3 +705,13 @@ function sizeKey(scope: TimelineScope): string {
|
||||
function submittedPromptId(item: AgentTimelineItem): string | null {
|
||||
return item.type === "user_message" && item.clientMessageId ? item.clientMessageId : null;
|
||||
}
|
||||
|
||||
function toTimelinePrompt(row: ProjectedTimelineRow): TimelinePrompt {
|
||||
const item = row.item as Extract<AgentTimelineItem, { type: "user_message" }>;
|
||||
return {
|
||||
seqStart: row.seqStart,
|
||||
messageId: item.messageId,
|
||||
providerMessageId: row.providerMessageId,
|
||||
submitted: item.clientMessageId !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ export interface TimelineRewindIntent {
|
||||
}
|
||||
|
||||
/** An active user prompt: what a rewind addresses. */
|
||||
/** What the timeline knows about an active prompt row; see `toTimelinePrompt`. */
|
||||
export interface TimelinePrompt {
|
||||
seqStart: number;
|
||||
messageId: string | undefined;
|
||||
@@ -119,8 +120,8 @@ export interface AgentTimelineBackend {
|
||||
): MaybePromise<TimelineBackendAppendResult>;
|
||||
/** Whether a new entry would land on retired history (see `TimelineProjection.isRetired`). */
|
||||
isRetired(scope: TimelineScope, entry: TimelineEntry): MaybePromise<boolean>;
|
||||
/** Active user prompts in display order. */
|
||||
prompts(scope: TimelineScope): MaybePromise<TimelinePrompt[]>;
|
||||
/** Active user prompt rows in display order, read without the rest of the history. */
|
||||
promptRows(scope: TimelineScope): MaybePromise<ProjectedTimelineRow[]>;
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): MaybePromise<TimelineHead>;
|
||||
/**
|
||||
* Allocates the next sequence number for a retirement of the active rows anchored at or after
|
||||
|
||||
@@ -15,7 +15,6 @@ import type {
|
||||
TimelineChild,
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelinePrompt,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
@@ -142,18 +141,11 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
return this.requireState(scope).projection.isRetired(entry);
|
||||
}
|
||||
|
||||
prompts(scope: TimelineScope): TimelinePrompt[] {
|
||||
const prompts: TimelinePrompt[] = [];
|
||||
for (const row of this.requireState(scope).projection.getRows()) {
|
||||
if (row.item.type !== "user_message") continue;
|
||||
prompts.push({
|
||||
seqStart: row.seqStart,
|
||||
messageId: row.item.messageId,
|
||||
providerMessageId: row.providerMessageId,
|
||||
submitted: row.item.clientMessageId !== undefined,
|
||||
});
|
||||
}
|
||||
return prompts;
|
||||
promptRows(scope: TimelineScope): ProjectedTimelineRow[] {
|
||||
return this.requireState(scope)
|
||||
.projection.getRows()
|
||||
.filter((row) => row.item.type === "user_message")
|
||||
.map(cloneRow);
|
||||
}
|
||||
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): TimelineHead {
|
||||
|
||||
@@ -29,7 +29,6 @@ import type {
|
||||
TimelineChild,
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelinePrompt,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
@@ -240,25 +239,17 @@ export class SqliteTimelineBackend implements AgentTimelineBackend {
|
||||
});
|
||||
}
|
||||
|
||||
prompts(scope: TimelineScope): TimelinePrompt[] {
|
||||
promptRows(scope: TimelineScope): ProjectedTimelineRow[] {
|
||||
return this.database.read((sql) => {
|
||||
const { id } = requireScope(sql, scope);
|
||||
// A prompt's text is in its row; only streamed text rows keep chunks beside it.
|
||||
return sql
|
||||
.all<RowRecord>(
|
||||
`SELECT seq_start, item_type, row FROM timeline_rows WHERE ${ACTIVE} ` +
|
||||
"AND item_type = 'user_message' ORDER BY seq_start",
|
||||
id,
|
||||
)
|
||||
.map((record) => {
|
||||
const row = parseRow(record);
|
||||
const item = row.item as Extract<AgentTimelineItem, { type: "user_message" }>;
|
||||
return {
|
||||
seqStart: row.seqStart,
|
||||
messageId: item.messageId,
|
||||
providerMessageId: row.providerMessageId,
|
||||
submitted: item.clientMessageId !== undefined,
|
||||
};
|
||||
});
|
||||
.map(parseRow);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ describe("SQLite timeline backend against the memory backend", () => {
|
||||
const identity = String(random(6));
|
||||
const text = `${scenario}-${step}`;
|
||||
if (roll === 0) {
|
||||
const prompts = memory.prompts(scope);
|
||||
const prompts = memory.promptRows(scope);
|
||||
if (prompts.length > 0) {
|
||||
const retireFromSeq = prompts[random(prompts.length)].seqStart;
|
||||
const results = backends.map((backend) =>
|
||||
@@ -196,7 +196,7 @@ function expectSameHistory(
|
||||
expect(sqlite.head(target)).toEqual(memory.head(target));
|
||||
expect(sqlite.readRows(target)).toEqual(memory.readRows(target));
|
||||
expect(sqlite.retiredRows(target)).toEqual(memory.retiredRows(target));
|
||||
expect(sqlite.prompts(target)).toEqual(memory.prompts(target));
|
||||
expect(sqlite.promptRows(target)).toEqual(memory.promptRows(target));
|
||||
expect(sqlite.lastItem(target)).toEqual(memory.lastItem(target));
|
||||
expect(sqlite.lastAssistantMessage(target)).toEqual(memory.lastAssistantMessage(target));
|
||||
const maxSeq = memory.head(target)!.seq;
|
||||
@@ -420,6 +420,10 @@ describe("SQLite timeline reads", () => {
|
||||
expect(backend.fetch(scope, options).rows.length).toBeGreaterThanOrEqual(20);
|
||||
expect(database.rowsRead, JSON.stringify(options)).toBeLessThan(150);
|
||||
}
|
||||
// The chat outline lists every prompt; it reads none of the 1,000 other rows.
|
||||
database.rowsRead = 0;
|
||||
expect(backend.promptRows(scope)).toHaveLength(500);
|
||||
expect(database.rowsRead).toBeLessThanOrEqual(501);
|
||||
for (const read of [
|
||||
() => backend.head(scope),
|
||||
() => backend.lastItem(scope),
|
||||
|
||||
@@ -20,7 +20,6 @@ import type {
|
||||
TimelineChild,
|
||||
TimelineEntry,
|
||||
TimelineHead,
|
||||
TimelinePrompt,
|
||||
TimelineRewindIntent,
|
||||
TimelineScope,
|
||||
TimelineSeed,
|
||||
@@ -109,8 +108,8 @@ export class DeferredTimelineBackend implements AgentTimelineBackend {
|
||||
isRetired(scope: TimelineScope, entry: TimelineEntry): Promise<boolean> {
|
||||
return this.defer(() => this.inner.isRetired(scope, entry));
|
||||
}
|
||||
prompts(scope: TimelineScope): Promise<TimelinePrompt[]> {
|
||||
return this.defer(() => this.inner.prompts(scope));
|
||||
promptRows(scope: TimelineScope): Promise<ProjectedTimelineRow[]> {
|
||||
return this.defer(() => this.inner.promptRows(scope));
|
||||
}
|
||||
setRewind(scope: TimelineScope, rewind: TimelineRewindIntent | null): Promise<TimelineHead> {
|
||||
return this.defer(() => this.inner.setRewind(scope, rewind));
|
||||
|
||||
@@ -2,6 +2,7 @@ import { MockLoadTestAgentClient } from "./agent/providers/mock-load-test-agent.
|
||||
import { createPaseoApi } from "@getpaseo/client";
|
||||
import type { AgentManager } from "./agent/agent-manager.js";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
@@ -1423,6 +1424,34 @@ test("archive and delete replies retain their historical names and reach only th
|
||||
}
|
||||
});
|
||||
|
||||
test("a delete that cannot remove the agent's history fails and can be retried", async () => {
|
||||
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
|
||||
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
// A second connection to the daemon's database makes the history delete fail.
|
||||
const database = new DatabaseSync(path.join(daemon.paseoHome, "paseo.db"));
|
||||
try {
|
||||
await admin.connect();
|
||||
const agent = await admin.createAgent({ provider: "codex", cwd: daemon.staticDir });
|
||||
database.exec(`CREATE TRIGGER refuse_history_delete BEFORE DELETE ON timeline_scopes
|
||||
BEGIN SELECT RAISE(ABORT, 'disk I/O error'); END`);
|
||||
|
||||
await expect(admin.deleteAgent(agent.id)).rejects.toThrow("disk I/O error");
|
||||
const afterFailure = await admin.fetchAgents();
|
||||
expect(afterFailure.entries.map((entry) => entry.agent.id)).toEqual([agent.id]);
|
||||
|
||||
database.exec("DROP TRIGGER refuse_history_delete");
|
||||
await admin.deleteAgent(agent.id);
|
||||
expect((await admin.fetchAgents()).entries).toEqual([]);
|
||||
expect(
|
||||
database.prepare("SELECT agent_id FROM timeline_scopes WHERE agent_id = ?").all(agent.id),
|
||||
).toEqual([]);
|
||||
} finally {
|
||||
database.close();
|
||||
await admin.close();
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Hub bootstrap sends its server ID before the producer's synchronous snapshot", async () => {
|
||||
const daemon = await createTestPaseoDaemon({ mcpEnabled: false });
|
||||
const admin = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
|
||||
@@ -3884,14 +3884,12 @@ export class Session {
|
||||
// durable snapshot, otherwise an in-flight background write can recreate it.
|
||||
await this.agentManager.flush();
|
||||
|
||||
try {
|
||||
await this.agentStorage.remove(agentId);
|
||||
await this.agentManager.deleteAgentState(agentId);
|
||||
// Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply.
|
||||
if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent);
|
||||
} catch (error) {
|
||||
this.sessionLogger.error({ err: error, agentId }, `Failed to fully delete agent ${agentId}`);
|
||||
}
|
||||
// History goes before the record: if it cannot be removed, the request fails and the record
|
||||
// stays, so the user still sees the agent and can delete it again.
|
||||
await this.agentManager.deleteAgentState(agentId);
|
||||
await this.agentStorage.remove(agentId);
|
||||
// Directory removal is daemon-wide; agent_deleted below stays a source-scoped RPC reply.
|
||||
if (knownAgent) this.agentManager.notifyAgentRemoved(knownAgent);
|
||||
|
||||
this.emit({
|
||||
type: "agent_deleted",
|
||||
@@ -8905,7 +8903,7 @@ export class Session {
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.loadAgentHistoryPayload(msg.agentId);
|
||||
const rows = await this.agentManager.getTimelineRows(msg.agentId);
|
||||
const rows = await this.agentManager.getTimelinePromptRows(msg.agentId);
|
||||
const timeline = await this.agentManager.fetchTimeline(msg.agentId, {
|
||||
direction: "tail",
|
||||
limit: 1,
|
||||
|
||||
Reference in New Issue
Block a user