Keep agent timelines stable from submission through resume (#2718)
* Reapply: Stop completed turns from appearing stuck (#2484) * Reapply: Keep older chat history and image previews stable (#2490) * Lock timeline layout stability with user-driven specs Two reds reproduce the reported jank: - new agent, first prompt: the row paints at top=100 then jumps to 144 through authoritative hydration, because the draft tab and the agent panel each render their own AgentStreamView for the same logical row. - long loaded timeline, submit: scrollHeight collapses 10793 -> 9111 mid-turn, because splitOrderedTail reclassifies measured rows into the virtualized segment where the virtualizer falls back to estimateStreamItemHeight. Also restores centered timeline rows: the pagination anchor wrapper introduced in #2490 was a plain block div, which broke alignSelf: center. * Measure the turn footer blink from when the footer appears Bounding the window at the prompt row conflated two things: the footer arriving a frame after the row, and the footer leaving the layout and coming back. Bounded from the footer's first frame, the blink still reproduces, so the footer-ownership race is real rather than a sampling artifact. * Rename the shadowed prompt row binding in the frame recorder * fix(desktop): allow concurrent worktree dev instances Desktop terminals can inherit another instance's profile path and debugging flags. Scope the profile to the current dev root and select an available debugging port so instances do not share global runtime state. * fix(desktop): expose development providers in dev builds Desktop-managed daemons inherited no Paseo runtime mode, so dev builds constructed the production provider registry. Mark unpackaged internal launches as development while continuing to force packaged launches to production. * fix(timeline): stabilize optimistic turn layout Keep initial history loading dormant until user intent and preserve active-turn layout across delayed transport updates. Add painted-frame coverage for optimistic timeline transitions. * fix(timeline): preserve optimistic prompts through hydration Canonical replacement relied on a transport submission record that can settle before a provider echoes the user row. Keep presentation continuity owned by the unreconciled row while destructive history replacement remains governed by active transactions. * fix(timeline): make submitted prompts canonical Submission settlement previously depended on status updates that could arrive after the optimistic row. Persist every accepted prompt in the canonical timeline and keep the footer active until RPC and canonical acknowledgement converge. * fix(timeline): stop older history pages repeating entries Backward pagination counted source sequence rows, so page boundaries inside a merged projected item could return that item repeatedly. Count projected entries and advance from their display anchors instead, with server and browser regressions covering the contract. * fix(timeline): resume agents from the latest history Use a bounded tail probe on resume so long background runs appear atomically instead of replaying every missed page. Preserve unchanged views, reconcile local/live rows, and keep skipped history reachable through backward pagination. * fix(timeline): reconcile turn state after missed updates Turn completion events can be missed while an agent timeline is unsubscribed, leaving footer activity stale even after the directory reports idle. Reconcile the single-owned turn lifecycle from authoritative resume snapshots while preserving newer live evidence. * test(timeline): cover running state across refresh Protect the hydration boundary where directory state must restore consistent tab, composer, and footer activity. Expose the running indicator semantically so the regression checks user-visible state instead of spinner implementation details. * fix(timeline): keep history loading geometry stable Reserve a fixed history-start gutter regardless of pagination state so showing or hiding the loader cannot shift timeline content. * fix(timeline): keep turn activity coherent Derive footer, tab, and composer activity from one lifecycle and submission projection. Idle directory transitions now request an authoritative resume so missed terminal events converge without treating directory delivery order as turn authority. * fix(tests): align checks with runtime boundaries * fix(desktop): stop dev app surviving its terminal Electron was detached from the desktop runner, allowing it to outlive a stopped workspace terminal with broken output pipes and retain the single-instance lock. Keep Electron owned by the runner and preserve explicit process-group cleanup for detached child trees. * fix(timeline): preserve activity through turn handoff Correlate lifecycle events and snapshots with daemon-owned turn identity, and keep optimistic submissions active until their canonical row arrives. This prevents stale updates and RPC timing from exposing a false idle state. * refactor(timeline): remove submission timing state * fix(timeline): restore prompt identity on resume * fix(timeline): exclude attachments from canonical prompt text Structured provider prompts can include hidden history attachments before the user's text. Persist only plain prompt blocks so authoritative user messages match what the composer displayed while provider input remains unchanged. * refactor(agent): remove unused pending-run message identity * fix(desktop): let Chromium allocate the debugging port * refactor(agent): remove impossible finalized-turn tracking * fix(timeline): load history after keyboard scrolling Treat observed upward displacement as user intent so keyboard and scrollbar navigation can wake dormant pagination. * test(server): preserve accepted turn stream order The manager-owned accepted turn boundary intentionally precedes coalesced output. Assert that lifecycle event explicitly while retaining the timeline-before-terminal ordering contract. * test(app): scope sidebar fixtures by identity Shared E2E daemon state may contain unrelated projects. Keep stale-route coverage tied to its named missing project and drag only the two rows seeded by the reorder spec. * fix(timeline): gate prompt revisions by client capability * fix(timeline): finalize canonical prompt delivery Treat provider identity as a single stored-row transition so legacy clients receive one deliverable canonical prompt. Release identity-pending rows before later foreground output or the current terminal while preserving stale-turn isolation. * fix(server): preserve legacy prompt pagination * fix(timeline): keep assistant block identity stable Assign canonical block IDs during live promotion so terminal finalization cannot remount image-bearing rows. * fix(timeline): apply covered revisions during resume append Run the exact canonical revision pass before overlapping resume pages append newer rows, while leaving cursor advancement to the incremental path. * fix(server): preserve queued agent transitions Project each queued live snapshot before awaiting stored metadata so later lifecycle state cannot overwrite an earlier transition. * fix(server): snapshot queued agent updates Capture each live agent payload before it enters the per-agent queue so shared nested state cannot change while an earlier storage read is pending. * docs(app): date agent turn compatibility cleanup * refactor(timeline): mint submitted prompt identity at acceptance Canonical prompt rows now keep one immutable wire identity while provider identity remains internal for rewind translation. This removes the unreleased same-sequence revision and legacy projection contract. * refactor(app): remove prompt revision reconciliation Submitted prompt rows are immutable on the wire, so resume and live reducers no longer need to apply already-covered same-sequence updates. * test(app): cover submitted prompt rewind roundtrip * docs(timeline): describe immutable submitted prompt identity Provider echoes now enrich daemon-internal identity only; wire rows keep their acceptance-time identity and rewind performs the provider translation. * test(server): validate mock rewind targets Reject unknown provider message IDs so app rewind coverage exercises wire-to-provider identity translation. * fix(server): validate rewind before interrupting * fix(server): omit rewind identity for daemon prompts * test(app): guard rewind eligibility and rejection * fix(server): preserve prompt identity across hydration * refactor(timeline): remove stale revision remnants * Revert "fix(server): preserve prompt identity across hydration" This reverts commit 6adcf7e5b0bc8601761af59b461a746cb5e395fa. * fix(timeline): settle missed submission acknowledgements
This commit is contained in:
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -2,54 +2,14 @@ import { describe, expect, test } from "vitest";
|
||||
import { TIMELINE_FETCH_PAGE_SIZE } from "@/timeline/timeline-fetch-policy";
|
||||
import {
|
||||
isTimelineCatchUpComplete,
|
||||
planInitialAgentTimelineSync,
|
||||
planResumeTimelineSync,
|
||||
isTimelineResumeSnapshotAuthoritative,
|
||||
planTimelineOlderFetch,
|
||||
planTimelineTailFetch,
|
||||
} from "./timeline-sync-plan";
|
||||
|
||||
describe("timeline sync planning", () => {
|
||||
test("initial open without an authoritative cursor loads a bounded tail page", () => {
|
||||
const plan = planInitialAgentTimelineSync({
|
||||
cursor: undefined,
|
||||
hasAuthoritativeHistory: false,
|
||||
});
|
||||
|
||||
expect(plan).toEqual({
|
||||
direction: "tail",
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "projected",
|
||||
});
|
||||
});
|
||||
|
||||
test("initial open with an authoritative cursor catches up after the cursor", () => {
|
||||
const plan = planInitialAgentTimelineSync({
|
||||
cursor: { epoch: "epoch-1", startSeq: 1, endSeq: 42 },
|
||||
hasAuthoritativeHistory: true,
|
||||
});
|
||||
|
||||
expect(plan).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-1", seq: 42 },
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "projected",
|
||||
});
|
||||
});
|
||||
|
||||
test("resume with a cursor catches up after the cursor", () => {
|
||||
const plan = planResumeTimelineSync({
|
||||
cursor: { epoch: "epoch-1", startSeq: 1, endSeq: 100 },
|
||||
});
|
||||
|
||||
expect(plan).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-1", seq: 100 },
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "projected",
|
||||
});
|
||||
});
|
||||
|
||||
test("resume without a cursor loads a bounded tail page", () => {
|
||||
const plan = planResumeTimelineSync({ cursor: undefined });
|
||||
test("agent synchronization checks a bounded tail page", () => {
|
||||
const plan = planTimelineTailFetch();
|
||||
|
||||
expect(plan).toEqual({
|
||||
direction: "tail",
|
||||
@@ -74,4 +34,28 @@ describe("timeline sync planning", () => {
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("only tail and completed forward pages carry an authoritative resume snapshot", () => {
|
||||
expect(
|
||||
isTimelineResumeSnapshotAuthoritative({
|
||||
direction: "tail",
|
||||
hasNewer: false,
|
||||
error: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isTimelineResumeSnapshotAuthoritative({
|
||||
direction: "after",
|
||||
hasNewer: false,
|
||||
error: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isTimelineResumeSnapshotAuthoritative({
|
||||
direction: "before",
|
||||
hasNewer: false,
|
||||
error: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,12 +5,6 @@ export interface TimelineSyncCursor {
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export interface AgentTimelineCursorRange {
|
||||
epoch: string;
|
||||
startSeq: number;
|
||||
endSeq: number;
|
||||
}
|
||||
|
||||
export interface ProjectedTimelineTailFetchPlan {
|
||||
direction: "tail";
|
||||
limit: number;
|
||||
@@ -40,27 +34,6 @@ export type ProjectedTimelineForwardFetchPlan =
|
||||
| ProjectedTimelineTailFetchPlan
|
||||
| ProjectedTimelineAfterFetchPlan;
|
||||
|
||||
export function planInitialAgentTimelineSync(input: {
|
||||
cursor: AgentTimelineCursorRange | undefined;
|
||||
hasAuthoritativeHistory: boolean;
|
||||
}): ProjectedTimelineForwardFetchPlan {
|
||||
if (input.hasAuthoritativeHistory && input.cursor) {
|
||||
return planTimelineCatchUpAfter({ epoch: input.cursor.epoch, seq: input.cursor.endSeq });
|
||||
}
|
||||
|
||||
return planTimelineTailFetch();
|
||||
}
|
||||
|
||||
export function planResumeTimelineSync(input: {
|
||||
cursor: AgentTimelineCursorRange | undefined;
|
||||
}): ProjectedTimelineForwardFetchPlan {
|
||||
if (input.cursor) {
|
||||
return planTimelineCatchUpAfter({ epoch: input.cursor.epoch, seq: input.cursor.endSeq });
|
||||
}
|
||||
|
||||
return planTimelineTailFetch();
|
||||
}
|
||||
|
||||
export function planTimelineCatchUpAfter(cursor: TimelineSyncCursor) {
|
||||
return {
|
||||
direction: "after",
|
||||
@@ -98,3 +71,12 @@ export function isTimelineCatchUpComplete(input: {
|
||||
|
||||
return input.direction !== "after" || !input.hasNewer;
|
||||
}
|
||||
|
||||
export function isTimelineResumeSnapshotAuthoritative(input: {
|
||||
direction: "tail" | "before" | "after";
|
||||
hasNewer: boolean;
|
||||
error: string | null;
|
||||
}): boolean {
|
||||
if (input.error || input.direction === "before") return false;
|
||||
return input.direction === "tail" || !input.hasNewer;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { reduceTurnLiveness, resolveTurnPresentation, TURN_LIVENESS_IDLE } from "./turn-liveness";
|
||||
|
||||
describe("turn activity", () => {
|
||||
const startedAt = new Date("2026-07-31T10:00:00.000Z");
|
||||
|
||||
it("ignores a terminal event for another turn", () => {
|
||||
const open = reduceTurnLiveness(TURN_LIVENESS_IDLE, {
|
||||
type: "stream_open",
|
||||
turn: { turnId: "turn-2", startedAt },
|
||||
});
|
||||
|
||||
expect(reduceTurnLiveness(open, { type: "stream_close", turnId: "turn-1" })).toBe(open);
|
||||
});
|
||||
|
||||
it("replaces activity from an authoritative snapshot", () => {
|
||||
const open = reduceTurnLiveness(TURN_LIVENESS_IDLE, {
|
||||
type: "stream_open",
|
||||
turn: { turnId: "turn-1", startedAt },
|
||||
});
|
||||
|
||||
expect(reduceTurnLiveness(open, { type: "snapshot", activeTurn: null })).toEqual(
|
||||
TURN_LIVENESS_IDLE,
|
||||
);
|
||||
});
|
||||
|
||||
it("opens an autonomous turn from an authoritative snapshot", () => {
|
||||
expect(
|
||||
reduceTurnLiveness(TURN_LIVENESS_IDLE, {
|
||||
type: "snapshot",
|
||||
activeTurn: { turnId: "autonomous-turn-1", startedAt },
|
||||
}),
|
||||
).toEqual({
|
||||
phase: "open",
|
||||
turnId: "autonomous-turn-1",
|
||||
startedAt,
|
||||
cancellationRequestId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not let an old cancel completion clear the current request", () => {
|
||||
const first = reduceTurnLiveness(TURN_LIVENESS_IDLE, {
|
||||
type: "cancellation_started",
|
||||
requestId: 1,
|
||||
});
|
||||
const second = reduceTurnLiveness(first, { type: "cancellation_started", requestId: 2 });
|
||||
|
||||
expect(reduceTurnLiveness(second, { type: "cancellation_settled", requestId: 1 })).toBe(second);
|
||||
});
|
||||
|
||||
it("keeps cancellation pending across submission-to-turn handoff", () => {
|
||||
const canceling = reduceTurnLiveness(TURN_LIVENESS_IDLE, {
|
||||
type: "cancellation_started",
|
||||
requestId: 1,
|
||||
});
|
||||
|
||||
expect(
|
||||
reduceTurnLiveness(canceling, {
|
||||
type: "stream_open",
|
||||
turn: { turnId: "turn-1", startedAt },
|
||||
}),
|
||||
).toEqual({
|
||||
phase: "open",
|
||||
turnId: "turn-1",
|
||||
startedAt,
|
||||
cancellationRequestId: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps submission-only activity untimed", () => {
|
||||
expect(resolveTurnPresentation(TURN_LIVENESS_IDLE, true)).toEqual({
|
||||
isActive: true,
|
||||
isCancelling: false,
|
||||
startedAt: null,
|
||||
turnId: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
export interface ActiveTurnIdentity {
|
||||
turnId: string | null;
|
||||
startedAt: Date | null;
|
||||
}
|
||||
|
||||
export type TurnLiveness =
|
||||
| { phase: "idle"; cancellationRequestId: number | null }
|
||||
| {
|
||||
phase: "open";
|
||||
turnId: string | null;
|
||||
startedAt: Date | null;
|
||||
cancellationRequestId: number | null;
|
||||
};
|
||||
|
||||
export type TurnLivenessTransition =
|
||||
| { type: "snapshot"; activeTurn: ActiveTurnIdentity | null }
|
||||
| { type: "stream_open"; turn: ActiveTurnIdentity }
|
||||
| { type: "stream_close"; turnId: string | null }
|
||||
| { type: "cancellation_started"; requestId: number }
|
||||
| { type: "cancellation_settled"; requestId: number }
|
||||
| { type: "destructive_close" };
|
||||
|
||||
export const TURN_LIVENESS_IDLE: TurnLiveness = {
|
||||
phase: "idle",
|
||||
cancellationRequestId: null,
|
||||
};
|
||||
|
||||
export function readTurnLiveness(
|
||||
turns: ReadonlyMap<string, TurnLiveness>,
|
||||
agentId: string,
|
||||
): TurnLiveness {
|
||||
return turns.get(agentId) ?? TURN_LIVENESS_IDLE;
|
||||
}
|
||||
|
||||
export function applyTurnLivenessTransition(
|
||||
turns: ReadonlyMap<string, TurnLiveness>,
|
||||
agentId: string,
|
||||
transition: TurnLivenessTransition | readonly TurnLivenessTransition[],
|
||||
): Map<string, TurnLiveness> {
|
||||
const current = readTurnLiveness(turns, agentId);
|
||||
const transitions = Array.isArray(transition) ? transition : [transition];
|
||||
const next = transitions.reduce(reduceTurnLiveness, current);
|
||||
if (next === current) return turns as Map<string, TurnLiveness>;
|
||||
const updated = new Map(turns);
|
||||
if (next.phase === "idle" && next.cancellationRequestId === null) updated.delete(agentId);
|
||||
else updated.set(agentId, next);
|
||||
return updated;
|
||||
}
|
||||
|
||||
export interface TurnPresentation {
|
||||
isActive: boolean;
|
||||
isCancelling: boolean;
|
||||
startedAt: Date | null;
|
||||
turnId: string | null;
|
||||
}
|
||||
|
||||
export function resolveTurnPresentation(
|
||||
liveness: TurnLiveness,
|
||||
hasActiveSubmission: boolean,
|
||||
): TurnPresentation {
|
||||
if (liveness.phase === "open") {
|
||||
return {
|
||||
isActive: true,
|
||||
isCancelling: liveness.cancellationRequestId !== null,
|
||||
startedAt: liveness.startedAt,
|
||||
turnId: liveness.turnId,
|
||||
};
|
||||
}
|
||||
return {
|
||||
isActive: hasActiveSubmission,
|
||||
isCancelling: liveness.cancellationRequestId !== null,
|
||||
startedAt: null,
|
||||
turnId: null,
|
||||
};
|
||||
}
|
||||
|
||||
function closeTurn(current: TurnLiveness, turnId: string | null): TurnLiveness {
|
||||
// COMPAT(agentTurnIdentity): added in v0.2.6, remove after 2027-01-31 once daemon floor >= v0.2.6.
|
||||
const targetsDifferentIdentifiedTurn =
|
||||
current.phase === "open" &&
|
||||
turnId !== null &&
|
||||
current.turnId !== null &&
|
||||
turnId !== current.turnId;
|
||||
return targetsDifferentIdentifiedTurn ? current : TURN_LIVENESS_IDLE;
|
||||
}
|
||||
|
||||
function openTurn(current: TurnLiveness, activeTurn: ActiveTurnIdentity): TurnLiveness {
|
||||
// COMPAT(agentTurnIdentity): added in v0.2.6, remove after 2027-01-31 once daemon floor >= v0.2.6.
|
||||
const sameTurn =
|
||||
current.phase === "open" &&
|
||||
((activeTurn.turnId !== null && current.turnId === activeTurn.turnId) ||
|
||||
(activeTurn.turnId === null && current.turnId === null));
|
||||
return {
|
||||
phase: "open",
|
||||
turnId: activeTurn.turnId,
|
||||
startedAt: sameTurn ? (current.startedAt ?? activeTurn.startedAt) : activeTurn.startedAt,
|
||||
cancellationRequestId:
|
||||
sameTurn || current.phase === "idle" ? current.cancellationRequestId : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceTurnLiveness(
|
||||
current: TurnLiveness,
|
||||
transition: TurnLivenessTransition,
|
||||
): TurnLiveness {
|
||||
if (transition.type === "destructive_close") return TURN_LIVENESS_IDLE;
|
||||
|
||||
if (transition.type === "cancellation_started") {
|
||||
if (current.cancellationRequestId === transition.requestId) return current;
|
||||
return { ...current, cancellationRequestId: transition.requestId };
|
||||
}
|
||||
|
||||
if (transition.type === "cancellation_settled") {
|
||||
if (current.cancellationRequestId !== transition.requestId) return current;
|
||||
return { ...current, cancellationRequestId: null };
|
||||
}
|
||||
|
||||
if (transition.type === "stream_close") {
|
||||
return closeTurn(current, transition.turnId);
|
||||
}
|
||||
|
||||
const activeTurn = transition.type === "snapshot" ? transition.activeTurn : transition.turn;
|
||||
if (!activeTurn) return TURN_LIVENESS_IDLE;
|
||||
return openTurn(current, activeTurn);
|
||||
}
|
||||
@@ -22,34 +22,17 @@ function assistant(id: string, timestamp: Date): StreamItem {
|
||||
}
|
||||
|
||||
describe("deriveStreamTurnTiming", () => {
|
||||
it("reserves a running footer for an optimistic prompt before the host starts the turn", () => {
|
||||
const optimisticPrompt = {
|
||||
...user("optimistic", new Date("2026-05-15T00:00:00.000Z")),
|
||||
optimistic: true as const,
|
||||
};
|
||||
it("starts elapsed time from the submitted prompt", () => {
|
||||
const submittedAt = new Date("2026-05-15T00:00:00.000Z");
|
||||
|
||||
const timing = deriveStreamTurnTiming({
|
||||
agentStatus: "idle",
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: submittedAt,
|
||||
tail: [],
|
||||
head: [optimisticPrompt],
|
||||
head: [user("submitted", submittedAt)],
|
||||
});
|
||||
|
||||
assert.equal(timing.isActive, true);
|
||||
});
|
||||
|
||||
it("does not start elapsed time from an optimistic prompt", () => {
|
||||
const optimisticPrompt = {
|
||||
...user("optimistic", new Date("2026-05-15T00:00:00.000Z")),
|
||||
optimistic: true as const,
|
||||
};
|
||||
|
||||
const timing = deriveStreamTurnTiming({
|
||||
agentStatus: "running",
|
||||
tail: [],
|
||||
head: [optimisticPrompt],
|
||||
});
|
||||
|
||||
assert.equal(timing.runningStartedAt, null);
|
||||
assert.equal(timing.runningStartedAt, submittedAt);
|
||||
});
|
||||
|
||||
it("uses the last user message as the running turn start", () => {
|
||||
@@ -57,7 +40,8 @@ describe("deriveStreamTurnTiming", () => {
|
||||
const secondUserAt = new Date("2026-05-15T00:01:00.000Z");
|
||||
|
||||
const timing = deriveStreamTurnTiming({
|
||||
agentStatus: "running",
|
||||
isTurnActive: true,
|
||||
activeTurnStartedAt: secondUserAt,
|
||||
tail: [
|
||||
user("u1", firstUserAt),
|
||||
assistant("a1", new Date("2026-05-15T00:00:05.000Z")),
|
||||
@@ -75,7 +59,8 @@ describe("deriveStreamTurnTiming", () => {
|
||||
const assistantAt = new Date("2026-05-15T00:00:07.000Z");
|
||||
|
||||
const timing = deriveStreamTurnTiming({
|
||||
agentStatus: "idle",
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
tail: [
|
||||
user("u1", userAt),
|
||||
assistant("a1", assistantAt),
|
||||
@@ -97,7 +82,8 @@ describe("deriveStreamTurnTiming", () => {
|
||||
const lastAssistantAt = new Date("2026-05-15T00:00:07.000Z");
|
||||
|
||||
const timing = deriveStreamTurnTiming({
|
||||
agentStatus: "idle",
|
||||
isTurnActive: false,
|
||||
activeTurnStartedAt: null,
|
||||
tail: [
|
||||
user("u1", userAt),
|
||||
assistant("a1", firstAssistantAt),
|
||||
|
||||
@@ -9,18 +9,16 @@ export interface TurnTiming {
|
||||
export interface StreamTurnTiming {
|
||||
byAssistantId: Map<string, TurnTiming>;
|
||||
runningStartedAt: Date | null;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
export function deriveStreamTurnTiming(params: {
|
||||
agentStatus: string;
|
||||
isTurnActive: boolean;
|
||||
activeTurnStartedAt: Date | null;
|
||||
tail: StreamItem[];
|
||||
head: StreamItem[];
|
||||
}): StreamTurnTiming {
|
||||
const byAssistantId = new Map<string, TurnTiming>();
|
||||
let currentUserAt: Date | null = null;
|
||||
let currentAuthoritativeUserAt: Date | null = null;
|
||||
let currentUserIsOptimistic = false;
|
||||
let currentLastItemAt: Date | null = null;
|
||||
let currentAssistantIds: string[] = [];
|
||||
|
||||
@@ -42,8 +40,6 @@ export function deriveStreamTurnTiming(params: {
|
||||
if (item.kind === "user_message") {
|
||||
flushCompletedTurn();
|
||||
currentUserAt = item.timestamp;
|
||||
currentAuthoritativeUserAt = item.optimistic ? null : item.timestamp;
|
||||
currentUserIsOptimistic = item.optimistic === true;
|
||||
currentLastItemAt = null;
|
||||
currentAssistantIds = [];
|
||||
return;
|
||||
@@ -64,15 +60,13 @@ export function deriveStreamTurnTiming(params: {
|
||||
visitItem(item);
|
||||
}
|
||||
|
||||
const isRunning = params.agentStatus === "running";
|
||||
const runningStartedAt = isRunning ? currentAuthoritativeUserAt : null;
|
||||
if (params.agentStatus !== "running") {
|
||||
const runningStartedAt = params.isTurnActive ? params.activeTurnStartedAt : null;
|
||||
if (!params.isTurnActive) {
|
||||
flushCompletedTurn();
|
||||
}
|
||||
|
||||
return {
|
||||
byAssistantId,
|
||||
runningStartedAt,
|
||||
isActive: isRunning || currentUserIsOptimistic,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -48,8 +48,6 @@ class TimelineWorld {
|
||||
this.releaseMembershipWaiter();
|
||||
return result.promise;
|
||||
},
|
||||
readCursor: (agentId) => this.cursors.get(agentId),
|
||||
hasAuthoritativeHistory: (agentId) => this.authoritativeHistory.has(agentId),
|
||||
fetchPage: async (agentId, request) => {
|
||||
const result = deferred<{
|
||||
hasNewer: boolean;
|
||||
@@ -95,21 +93,10 @@ class TimelineWorld {
|
||||
agentId: string;
|
||||
resolve(fetch: TimelineFetch): void;
|
||||
}> = [];
|
||||
private readonly cursors = new Map<string, { epoch: string; startSeq: number; endSeq: number }>();
|
||||
private readonly authoritativeHistory = new Set<string>();
|
||||
private readonly errorWaiters: Array<(message: string) => void> = [];
|
||||
private readonly scheduled: Array<{ task: () => void; delayMs: number }> = [];
|
||||
private readonly retryWaiters: Array<(retry: () => void) => void> = [];
|
||||
|
||||
setCursor(agentId: string, endSeq: number): void {
|
||||
this.cursors.set(agentId, { epoch: `epoch-${agentId}`, startSeq: 1, endSeq });
|
||||
this.authoritativeHistory.add(agentId);
|
||||
}
|
||||
|
||||
setLiveCursor(agentId: string, endSeq: number): void {
|
||||
this.cursors.set(agentId, { epoch: `epoch-${agentId}`, startSeq: 1, endSeq });
|
||||
}
|
||||
|
||||
nextMembership(): Promise<MembershipRequest> {
|
||||
const request = this.memberships.shift();
|
||||
if (request) return Promise.resolve(request);
|
||||
@@ -178,9 +165,8 @@ test("keeps hidden agents subscribed for thirty seconds", () => {
|
||||
expect(VIEWED_TIMELINE_UNSUBSCRIBE_GRACE_MS).toBe(30_000);
|
||||
});
|
||||
|
||||
test("uses a tail fetch when a live cursor is not authoritative", async () => {
|
||||
test("uses a tail fetch when an agent becomes visible", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.setLiveCursor("agent-a", 9);
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
const membership = await world.nextMembership();
|
||||
@@ -191,6 +177,63 @@ test("uses a tail fetch when a live cursor is not authoritative", async () => {
|
||||
fetch.respond({ hasNewer: false });
|
||||
});
|
||||
|
||||
test("a gap absorbed by a running tail is recovered after the tail completes", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
const membership = await world.nextMembership();
|
||||
membership.succeed();
|
||||
const tail = await world.nextFetch("agent-a");
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 9 });
|
||||
|
||||
world.expectNoPendingFetch();
|
||||
tail.respond({ hasNewer: false });
|
||||
|
||||
const recovery = await world.nextFetch("agent-a");
|
||||
expect(recovery.request).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 9 },
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
});
|
||||
recovery.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
});
|
||||
|
||||
test("an idle reconciliation waits for an in-flight tail and fetches a fresh snapshot", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
const membership = await world.nextMembership();
|
||||
membership.succeed();
|
||||
const initialTail = await world.nextFetch("agent-a");
|
||||
|
||||
world.sync.reconcileAgent("agent-a");
|
||||
|
||||
world.expectNoPendingFetch();
|
||||
initialTail.respond({ hasNewer: false });
|
||||
|
||||
const reconciliation = await world.nextFetch("agent-a");
|
||||
expect(reconciliation.request).toEqual({
|
||||
direction: "tail",
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
});
|
||||
reconciliation.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
});
|
||||
|
||||
test("does not reconcile an agent outside the viewed membership", () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
|
||||
world.sync.reconcileAgent("agent-a");
|
||||
|
||||
world.expectNoPendingFetch();
|
||||
world.expectNoPendingMembership();
|
||||
});
|
||||
|
||||
test("unchanged visible-set publication does not cancel paged catch-up", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
@@ -364,6 +407,7 @@ test("gap recovery supersedes completed catch-up and pages through the current t
|
||||
membership.succeed();
|
||||
const initial = await world.nextFetch("agent-a");
|
||||
initial.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||
const gapPage = await world.nextFetch("agent-a");
|
||||
@@ -395,6 +439,7 @@ test("repeated recovery for the same running gap reuses the in-flight fetch", as
|
||||
membership.succeed();
|
||||
const initial = await world.nextFetch("agent-a");
|
||||
initial.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
const cursor = { epoch: "epoch-agent-a", endSeq: 10 };
|
||||
world.sync.recoverGap("agent-a", cursor);
|
||||
@@ -656,6 +701,7 @@ test("legacy delivery skips subscription RPCs while retaining visibility catch-u
|
||||
world.expectNoPendingMembership();
|
||||
const initial = await world.nextFetch("agent-a");
|
||||
initial.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||
const recovery = await world.nextFetch("agent-a");
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import type { AgentTimelineCursorState } from "@/stores/session-store";
|
||||
import {
|
||||
planInitialAgentTimelineSync,
|
||||
planResumeTimelineSync,
|
||||
planTimelineCatchUpAfter,
|
||||
planTimelineTailFetch,
|
||||
type ProjectedTimelineForwardFetchPlan,
|
||||
} from "./timeline-sync-plan";
|
||||
|
||||
@@ -14,8 +12,6 @@ interface TimelinePageResult {
|
||||
interface ViewedTimelineSyncPorts {
|
||||
initialDeliveryMode: TimelineDeliveryMode;
|
||||
setSubscription(agentIds: string[]): Promise<void>;
|
||||
readCursor(agentId: string): AgentTimelineCursorState | undefined;
|
||||
hasAuthoritativeHistory(agentId: string): boolean;
|
||||
fetchPage(
|
||||
agentId: string,
|
||||
request: ProjectedTimelineForwardFetchPlan,
|
||||
@@ -37,6 +33,7 @@ export interface ViewedTimelineSync extends ViewedTimelineUiBridge {
|
||||
setActive(active: boolean): void;
|
||||
setConnected(connected: boolean): void;
|
||||
setDeliveryMode(mode: TimelineDeliveryMode): void;
|
||||
reconcileAgent(agentId: string): void;
|
||||
recoverGap(agentId: string, cursor: { epoch: string; endSeq: number }): void;
|
||||
dispose(): void;
|
||||
}
|
||||
@@ -62,19 +59,29 @@ function isSameCatchUpRequest(
|
||||
return left.cursor.epoch === right.cursor.epoch && left.cursor.seq === right.cursor.seq;
|
||||
}
|
||||
|
||||
function shouldKeepCurrentCatchUp(input: {
|
||||
type CatchUpDecision = "keep" | "keep-and-park" | "replace";
|
||||
|
||||
function decideCatchUp(input: {
|
||||
current: CatchUpState | undefined;
|
||||
request: ProjectedTimelineForwardFetchPlan | undefined;
|
||||
request: ProjectedTimelineForwardFetchPlan;
|
||||
supersede: boolean;
|
||||
}): boolean {
|
||||
if (!input.current) return false;
|
||||
}): CatchUpDecision {
|
||||
if (!input.current) return "replace";
|
||||
if (input.supersede) {
|
||||
return (
|
||||
if (
|
||||
input.current.status === "running" &&
|
||||
isSameCatchUpRequest(input.current.request, input.request)
|
||||
);
|
||||
) {
|
||||
return "keep";
|
||||
}
|
||||
if (input.current.status === "running" && input.current.request?.direction === "tail") {
|
||||
return "keep-and-park";
|
||||
}
|
||||
return "replace";
|
||||
}
|
||||
return input.current.status === "running" || input.current.status === "complete";
|
||||
return input.current.status === "running" || input.current.status === "complete"
|
||||
? "keep"
|
||||
: "replace";
|
||||
}
|
||||
|
||||
function normalizeAgentIds(agentIds: string[]): string[] {
|
||||
@@ -89,7 +96,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
const sources = new Map<string, string[]>();
|
||||
const catchUps = new Map<string, CatchUpState>();
|
||||
const catchUpGenerations = new Map<string, number>();
|
||||
const pendingGaps = new Map<string, ProjectedTimelineForwardFetchPlan>();
|
||||
// Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or parked.
|
||||
// Acknowledgement and tail completion are the only drain points.
|
||||
const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>();
|
||||
const lingeringRemovals = new Map<string, () => void>();
|
||||
const visibilityCatchUpPending = new Set<string>();
|
||||
const visibilityCatchUpErrors = new Set<string>();
|
||||
@@ -137,7 +146,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
catchUpGenerations.set(agentId, (catchUpGenerations.get(agentId) ?? 0) + 1);
|
||||
catchUps.get(agentId)?.cancelRetry?.();
|
||||
catchUps.delete(agentId);
|
||||
pendingGaps.delete(agentId);
|
||||
pendingCatchUps.delete(agentId);
|
||||
};
|
||||
|
||||
const fetchUntilCurrent = async (
|
||||
@@ -174,6 +183,11 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
throw new Error(`Timeline page for ${agentId} hasNewer without an end cursor`);
|
||||
}
|
||||
catchUps.set(agentId, { generation, status: "complete" });
|
||||
const pendingCatchUp = pendingCatchUps.get(agentId);
|
||||
if (pendingCatchUp) {
|
||||
startCatchUp(agentId, { request: pendingCatchUp, supersede: true });
|
||||
return;
|
||||
}
|
||||
setVisibilityCatchUpReady(agentId);
|
||||
} catch (error) {
|
||||
if (catchUps.get(agentId)?.generation === generation) {
|
||||
@@ -198,31 +212,34 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
) => {
|
||||
const { request, supersede = false } = options;
|
||||
if (!connected || !isDesired(agentId) || !isAcknowledged(agentId)) {
|
||||
if (request) pendingGaps.set(agentId, request);
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
const nextRequest = request ?? planTimelineTailFetch();
|
||||
const current = catchUps.get(agentId);
|
||||
if (shouldKeepCurrentCatchUp({ current, request, supersede })) {
|
||||
const decision = decideCatchUp({ current, request: nextRequest, supersede });
|
||||
if (decision === "keep-and-park") {
|
||||
pendingCatchUps.set(agentId, nextRequest);
|
||||
return;
|
||||
}
|
||||
if (decision === "keep") {
|
||||
return;
|
||||
}
|
||||
current?.cancelRetry?.();
|
||||
const generation = (catchUpGenerations.get(agentId) ?? 0) + 1;
|
||||
catchUpGenerations.set(agentId, generation);
|
||||
catchUps.set(agentId, { generation, status: "running", request });
|
||||
pendingGaps.delete(agentId);
|
||||
const cursor = ports.readCursor(agentId);
|
||||
const nextRequest =
|
||||
request ??
|
||||
(ports.hasAuthoritativeHistory(agentId)
|
||||
? planResumeTimelineSync({ cursor })
|
||||
: planInitialAgentTimelineSync({ cursor, hasAuthoritativeHistory: false }));
|
||||
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
|
||||
pendingCatchUps.delete(agentId);
|
||||
void fetchUntilCurrent(agentId, generation, nextRequest);
|
||||
};
|
||||
|
||||
const startAcknowledgedCatchUps = () => {
|
||||
for (const agentId of acknowledged) {
|
||||
const gap = pendingGaps.get(agentId);
|
||||
startCatchUp(agentId, { request: gap, supersede: Boolean(gap) });
|
||||
const pendingCatchUp = pendingCatchUps.get(agentId);
|
||||
startCatchUp(agentId, {
|
||||
request: pendingCatchUp,
|
||||
supersede: Boolean(pendingCatchUp),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -432,6 +449,15 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
if (deliveryMode === "selective" && connected) void reconcileMembership();
|
||||
else if (connected) startAcknowledgedCatchUps();
|
||||
},
|
||||
reconcileAgent(agentId) {
|
||||
if (!isDesired(agentId)) return;
|
||||
const request = planTimelineTailFetch();
|
||||
if (catchUps.get(agentId)?.status === "running") {
|
||||
pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
startCatchUp(agentId, { request, supersede: true });
|
||||
},
|
||||
recoverGap(agentId, cursor) {
|
||||
if (!isDesired(agentId)) return;
|
||||
startCatchUp(agentId, {
|
||||
|
||||
Reference in New Issue
Block a user