Compare commits

..
Author SHA1 Message Date
LiebeLee fcac35d3b9 fix(timeline): recover from rewind epoch changes instead of dropping rows (#8794)
A rewind mints a new timeline epoch on the daemon. A client that misses the
agent.timeline.replacement invalidation then sees every subsequent live row in
the new epoch, and the sequencing gate dropped those rows with no recovery: the
chat stayed on pre-rewind history forever while the new epoch streamed.

Treat an epoch mismatch on a live row like a sequence gap. The app asks for
catch-up from its own cursor, the daemon answers a stale-epoch request with a
reset tail, and the existing destructive replacement installs current history.
The seq 1 fast path stays as is.
2026-11-26 10:07:49 +00:00
6 changed files with 147 additions and 53 deletions
+5
View File
@@ -61,6 +61,11 @@ the chat and its replica cache would keep only the end of the reply. A recovery
running catch-up starts after whatever that catch-up applied, because the app applies a forward page
row by row and an older cursor repeats rows.
A live row whose epoch differs from the local cursor is a rewind or replacement this client never
saw as an invalidation, not a stale row. The app recovers like a gap: it asks `after` its own
cursor, and the daemon answers that stale epoch with a reset tail. Dropping the rows instead would
leave the chat on pre-rewind history while the new epoch streams.
Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog.
Opening or resuming an agent fetches the latest available turns with a soft target of 40
@@ -97,11 +97,6 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
await test.step("Turning Tailscale off and back on settles over a slow connection", async () => {
await disableTailscale(page, address);
await enableTailscale(page);
await expectTailscaleAddress(page, address);
});
restoreSpeed();
});
+18 -37
View File
@@ -108,7 +108,6 @@ export async function enableTailscale(page: Page): Promise<void> {
await expect(toggle).not.toBeChecked();
await toggle.click();
await expect(toggle).toBeChecked();
await expect(toggle).toBeEnabled();
}
export async function expectTailscaleAddress(page: Page, address: string): Promise<void> {
@@ -143,7 +142,6 @@ export async function disableTailscale(page: Page, address: string): Promise<voi
await expect(toggle).toBeEnabled();
await toggle.click();
await expect(toggle).not.toBeChecked();
await expect(toggle).toBeEnabled();
await expect(tailscaleAddressRow(page, address)).toHaveCount(0);
await expectHostUnreachableAt(address);
}
@@ -309,8 +307,7 @@ export async function expectTailscaleRowLoadsOn(
/**
* Holds every message between the app and the host on `port` for `ms` in each direction, as on a
* slow network. The returned function brings the connection back to full speed and flushes any
* queued messages.
* slow network. The returned function brings the connection back to full speed.
*/
export async function slowConnectionToHost(
page: Page,
@@ -318,29 +315,30 @@ export async function slowConnectionToHost(
ms: number,
): Promise<() => void> {
let delay = ms;
const flushers = new Set<() => void>();
await page.routeWebSocket(wsRoutePatternForPort(String(port)), (app) => {
const host = app.connectToServer();
const appToHost = deliverInOrderAfter(
() => delay,
(message) => host.send(message),
app.onMessage(
deliverInOrderAfter(
() => delay,
(message) => host.send(message),
),
);
const hostToApp = deliverInOrderAfter(
() => delay,
(message) => app.send(message),
host.onMessage(
deliverInOrderAfter(
() => delay,
(message) => app.send(message),
),
);
flushers.add(appToHost.flushNow);
flushers.add(hostToApp.flushNow);
app.onMessage(appToHost.enqueue);
host.onMessage(hostToApp.enqueue);
});
return () => {
delay = 0;
for (const flushNow of flushers) flushNow();
};
}
function deliverInOrderAfter(delay: () => number, deliver: (message: string | Buffer) => void) {
function deliverInOrderAfter(
delay: () => number,
deliver: (message: string | Buffer) => void,
): (message: string | Buffer) => void {
const queue: { at: number; message: string | Buffer }[] = [];
let timer: ReturnType<typeof setTimeout> | null = null;
const flush = () => {
@@ -348,26 +346,9 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu
while (queue[0] && queue[0].at <= Date.now()) deliver(queue.shift()!.message);
if (queue[0]) timer = setTimeout(flush, queue[0].at - Date.now());
};
return {
enqueue: (message: string | Buffer) => {
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
if (!timer) flush();
},
flushNow: () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
while (queue[0]) {
const next = queue.shift()!;
try {
deliver(next.message);
} catch {
queue.length = 0;
break;
}
}
},
return (message) => {
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
if (!timer) flush();
};
}
+106
View File
@@ -204,6 +204,112 @@ describe("viewed timeline persistence", () => {
}
});
it("replaces pre-rewind history when a live row arrives in a new epoch", async () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
applySynced(AGENT_ID, 5);
const readTimelineState = () => {
const timeline = selectAgentTimelineState(
useSessionStore.getState().sessions[SERVER_ID],
AGENT_ID,
);
return {
status: timeline.status,
texts:
timeline.status === "cold"
? []
: timeline.items.flatMap((entry) =>
entry.kind === "assistant_message" ? [entry.text] : [],
),
};
};
const fetches: Array<{
direction: string;
cursor?: { epoch: string; seq: number };
}> = [];
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage: { readTimeline: async () => undefined, commitTimeline: () => undefined },
prepareAgent: async () => undefined,
});
const owner = 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, request) => {
fetches.push(request);
if (request.direction !== "after") return { hasNewer: false, endCursor: null };
// A cursor from the pre-rewind epoch makes the daemon reset to its current tail.
owner.applyTimelineResponse({
requestId: "rewind-reset",
agentId: AGENT_ID,
agent: null,
direction: "tail",
projection: "projected",
epoch: "epoch-2",
reset: true,
staleCursor: true,
gap: false,
window: { minSeq: 1, maxSeq: 2, nextSeq: 3 },
startCursor: { epoch: "epoch-2", seq: 1 },
endCursor: { epoch: "epoch-2", seq: 2 },
entries: [
{
provider: "codex",
item: { type: "assistant_message", text: "after rewind" },
timestamp: "2026-08-26T10:05:00.000Z",
seqStart: 1,
seqEnd: 2,
sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }],
collapsed: [],
},
],
hasOlder: false,
hasNewer: false,
error: null,
});
return { hasNewer: false, endCursor: { epoch: "epoch-2", seq: 2 } };
},
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
reportError: () => undefined,
},
});
try {
owner.setConnected(true);
owner.replaceVisibleAgentIds("test", [AGENT_ID]);
await expect.poll(() => fetches.length).toBe(1);
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "assistant_message", text: "new prompt reply" },
} as AgentStreamEventPayload,
seq: 6,
epoch: "epoch-2",
timestamp: new Date("2026-08-26T10:06:00.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
await expect.poll(() => fetches.length).toBe(2);
expect(fetches[1]).toMatchObject({
direction: "after",
cursor: { epoch: "epoch-1", seq: 5 },
});
await expect.poll(readTimelineState).toEqual({
status: "synced",
texts: ["after rewind"],
});
} finally {
owner.dispose();
}
});
it("shares an in-flight cache preparation with the viewed owner", async () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
let release!: (value: CachedTimeline) => void;
@@ -3834,7 +3834,7 @@ describe("processAgentStreamEvent", () => {
expect(result.sideEffects).toEqual([]);
});
it("drops timeline event with epoch mismatch", () => {
it("requests authoritative recovery when a live row has a different epoch", () => {
const existingCursor: TimelineCursor = {
epoch: "epoch-1",
startSeq: 1,
@@ -3852,7 +3852,9 @@ describe("processAgentStreamEvent", () => {
expect(result.cursorChanged).toBe(false);
expect(result.changedTail).toBe(false);
expect(result.changedHead).toBe(false);
expect(result.sideEffects).toEqual([]);
expect(result.sideEffects).toEqual([
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 5 } },
]);
});
it("resets visible timeline when a new epoch starts at seq 1", () => {
@@ -1545,7 +1545,20 @@ function processTimelineSequencingGate(input: {
cursorChanged: true,
};
}
if (decision === "gap") {
if (decision === "drop_epoch" && seq === 1) {
return {
...base,
nextTimelineCursor: { epoch, startSeq: seq, endSeq: seq },
cursorChanged: true,
resetLiveTimeline: true,
};
}
// A gap and an epoch change both mean the local cursor cannot certify the next row.
// The epoch case is a rewind or replacement this client did not observe as an
// invalidation; the daemon answers an `after` request carrying the stale epoch with a
// reset tail, which installs current history. Dropping those rows would leave the chat
// on pre-rewind history while the new epoch streams.
if (decision === "gap" || decision === "drop_epoch") {
return {
...base,
shouldApplyStreamEvent: false,
@@ -1559,14 +1572,6 @@ function processTimelineSequencingGate(input: {
],
};
}
if (decision === "drop_epoch" && seq === 1) {
return {
...base,
nextTimelineCursor: { epoch, startSeq: seq, endSeq: seq },
cursorChanged: true,
resetLiveTimeline: true,
};
}
return {
...base,
shouldApplyStreamEvent: false,