Fix mobile agent timeline catch-up
This commit is contained in:
@@ -14,7 +14,12 @@ import {
|
||||
type TimelineReducerSideEffect,
|
||||
} from "@/timeline/session-stream-reducers";
|
||||
import { useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
import { TIMELINE_FETCH_PAGE_SIZE } from "@/timeline/timeline-fetch-policy";
|
||||
import {
|
||||
isTimelineCatchUpComplete,
|
||||
planResumeTimelineSync,
|
||||
planTimelineCatchUpAfter,
|
||||
planTimelineCatchUpFollowUp,
|
||||
} from "@/timeline/timeline-sync-plan";
|
||||
import type { AgentAttachment, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { parseServerInfoStatusPayload } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
@@ -500,6 +505,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
const revalidationTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const revalidationInFlightRef = useRef<Promise<void> | null>(null);
|
||||
const revalidationQueuedRef = useRef(false);
|
||||
const timelineCatchUpInFlightRef = useRef<Set<string>>(new Set());
|
||||
const wasConnectedRef = useRef(isConnected);
|
||||
const audioOutputBuffersRef = useRef<Map<string, BufferedAudioChunk[]>>(new Map());
|
||||
const activeAudioGroupsRef = useRef<Set<string>>(new Set());
|
||||
@@ -746,6 +752,27 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
}, AUTHORITATIVE_REVALIDATION_DEBOUNCE_MS);
|
||||
}, [client, flushAuthoritativeRevalidation, isConnected]);
|
||||
|
||||
const requestCanonicalCatchUp = useCallback(
|
||||
(agentId: string, cursor: { epoch: string; endSeq: number }) => {
|
||||
const request = planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq });
|
||||
const key = `${agentId}:${request.cursor.epoch}:${request.cursor.seq}`;
|
||||
const inFlight = timelineCatchUpInFlightRef.current;
|
||||
if (inFlight.has(key)) {
|
||||
return;
|
||||
}
|
||||
inFlight.add(key);
|
||||
void client
|
||||
.fetchAgentTimeline(agentId, request)
|
||||
.catch((error) => {
|
||||
console.warn("[Session] failed to fetch canonical catch-up timeline", agentId, error);
|
||||
})
|
||||
.finally(() => {
|
||||
inFlight.delete(key);
|
||||
});
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
const handleAppResumed = useCallback(
|
||||
(awayMs: number) => {
|
||||
scheduleAuthoritativeRevalidation();
|
||||
@@ -754,15 +781,19 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
const agentId = session?.focusedAgentId;
|
||||
if (agentId) {
|
||||
void client
|
||||
.fetchAgentTimeline(agentId, {
|
||||
direction: "tail",
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
})
|
||||
.catch((error) => {
|
||||
const plan = planResumeTimelineSync({
|
||||
cursor: session?.agentTimelineCursor.get(agentId),
|
||||
});
|
||||
if (plan.direction === "after") {
|
||||
requestCanonicalCatchUp(agentId, {
|
||||
epoch: plan.cursor.epoch,
|
||||
endSeq: plan.cursor.seq,
|
||||
});
|
||||
} else {
|
||||
void client.fetchAgentTimeline(agentId, plan).catch((error) => {
|
||||
console.warn("[Session] failed to fetch tail timeline on resume", agentId, error);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -771,7 +802,13 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
}
|
||||
bumpHistorySyncGeneration(serverId);
|
||||
},
|
||||
[bumpHistorySyncGeneration, client, scheduleAuthoritativeRevalidation, serverId],
|
||||
[
|
||||
bumpHistorySyncGeneration,
|
||||
client,
|
||||
requestCanonicalCatchUp,
|
||||
scheduleAuthoritativeRevalidation,
|
||||
serverId,
|
||||
],
|
||||
);
|
||||
|
||||
// Client activity tracking (heartbeat, push token registration)
|
||||
@@ -1018,22 +1055,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
[serverId, upsertWorkspaceSetupProgress],
|
||||
);
|
||||
|
||||
const requestCanonicalCatchUp = useCallback(
|
||||
(agentId: string, cursor: { epoch: string; endSeq: number }) => {
|
||||
void client
|
||||
.fetchAgentTimeline(agentId, {
|
||||
direction: "after",
|
||||
cursor: { epoch: cursor.epoch, seq: cursor.endSeq },
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("[Session] failed to fetch canonical catch-up timeline", agentId, error);
|
||||
});
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
const applyTimelineResponse = useCallback(
|
||||
(
|
||||
payload: Extract<
|
||||
@@ -1043,8 +1064,13 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
) => {
|
||||
const agentId = payload.agentId;
|
||||
const initKey = getInitKey(serverId, agentId);
|
||||
const catchUpComplete = isTimelineCatchUpComplete({
|
||||
direction: payload.direction,
|
||||
hasNewer: payload.hasNewer,
|
||||
error: payload.error,
|
||||
});
|
||||
const shouldMarkAuthoritativeHistoryApplied =
|
||||
payload.direction === "tail" || payload.direction === "after";
|
||||
payload.direction === "tail" || (payload.direction === "after" && catchUpComplete);
|
||||
|
||||
// Read current store state
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
@@ -1114,6 +1140,19 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
applyAgentUpdatePayload,
|
||||
});
|
||||
|
||||
const followUp = planTimelineCatchUpFollowUp({
|
||||
direction: payload.direction,
|
||||
hasNewer: payload.hasNewer,
|
||||
endCursor: payload.endCursor,
|
||||
error: payload.error,
|
||||
});
|
||||
if (followUp?.direction === "after") {
|
||||
requestCanonicalCatchUp(agentId, {
|
||||
epoch: followUp.cursor.epoch,
|
||||
endSeq: followUp.cursor.seq,
|
||||
});
|
||||
}
|
||||
|
||||
finalizeTimelineApplication({
|
||||
result,
|
||||
agentId,
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
getInitKey,
|
||||
rejectInitDeferred,
|
||||
} from "@/utils/agent-initialization";
|
||||
import { TIMELINE_FETCH_PAGE_SIZE } from "@/timeline/timeline-fetch-policy";
|
||||
import { planInitialAgentTimelineSync, planTimelineTailFetch } from "@/timeline/timeline-sync-plan";
|
||||
|
||||
export const INIT_TIMEOUT_MS = 30_000;
|
||||
|
||||
@@ -32,19 +32,7 @@ export function ensureAgentIsInitialized(input: EnsureAgentIsInitializedInput):
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
const cursor = session?.agentTimelineCursor.get(agentId);
|
||||
const hasAuthoritativeHistory = session?.agentAuthoritativeHistoryApplied.get(agentId) === true;
|
||||
const timelineRequest =
|
||||
hasAuthoritativeHistory && cursor
|
||||
? {
|
||||
direction: "after" as const,
|
||||
cursor: { epoch: cursor.epoch, seq: cursor.endSeq },
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical" as const,
|
||||
}
|
||||
: {
|
||||
direction: "tail" as const,
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical" as const,
|
||||
};
|
||||
const timelineRequest = planInitialAgentTimelineSync({ cursor, hasAuthoritativeHistory });
|
||||
|
||||
const deferred = createInitDeferred(key, timelineRequest.direction);
|
||||
const timeoutId = setTimeout(() => {
|
||||
@@ -87,11 +75,7 @@ export async function refreshAgent(input: RefreshAgentInput): Promise<void> {
|
||||
|
||||
try {
|
||||
await client.refreshAgent(agentId);
|
||||
await client.fetchAgentTimeline(agentId, {
|
||||
direction: "tail",
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
});
|
||||
await client.fetchAgentTimeline(agentId, planTimelineTailFetch());
|
||||
} catch (error) {
|
||||
setAgentInitializing(agentId, false);
|
||||
throw error;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback } from "react";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { useSessionStore, type AgentTimelineCursorState } from "@/stores/session-store";
|
||||
import { TIMELINE_FETCH_PAGE_SIZE } from "@/timeline/timeline-fetch-policy";
|
||||
import { planTimelineOlderFetch } from "@/timeline/timeline-sync-plan";
|
||||
|
||||
export interface LoadOlderAgentHistoryClient {
|
||||
fetchAgentTimeline: (
|
||||
@@ -40,12 +40,10 @@ export async function loadOlderAgentHistory(
|
||||
|
||||
setInFlight(true);
|
||||
try {
|
||||
await client.fetchAgentTimeline(agentId, {
|
||||
direction: "before",
|
||||
cursor: { epoch: cursor.epoch, seq: cursor.startSeq },
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
});
|
||||
await client.fetchAgentTimeline(
|
||||
agentId,
|
||||
planTimelineOlderFetch({ epoch: cursor.epoch, seq: cursor.startSeq }),
|
||||
);
|
||||
} catch (error) {
|
||||
(logger ?? console).warn("[Timeline] failed to load older agent history", agentId, error);
|
||||
toast?.show("Couldn't load older history", {
|
||||
|
||||
@@ -919,6 +919,24 @@ describe("processTimelineResponse", () => {
|
||||
expect(result.clearInitializing).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps init open while an after catch-up page has newer rows", () => {
|
||||
const result = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
isInitializing: true,
|
||||
hasActiveInitDeferred: true,
|
||||
initRequestDirection: "after",
|
||||
payload: {
|
||||
...baseTimelineInput.payload,
|
||||
direction: "after",
|
||||
hasNewer: true,
|
||||
entries: [],
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.initResolution).toBe(null);
|
||||
expect(result.clearInitializing).toBe(false);
|
||||
});
|
||||
|
||||
it("does not resolve init when directions differ (before vs after)", () => {
|
||||
const result = processTimelineResponse({
|
||||
...baseTimelineInput,
|
||||
|
||||
@@ -167,12 +167,14 @@ function deriveBootstrapTailTimelinePolicy({
|
||||
|
||||
function shouldResolveTimelineInit({
|
||||
hasActiveInitDeferred,
|
||||
hasNewer,
|
||||
isInitializing,
|
||||
initRequestDirection,
|
||||
responseDirection,
|
||||
reset,
|
||||
}: {
|
||||
hasActiveInitDeferred: boolean;
|
||||
hasNewer: boolean;
|
||||
isInitializing: boolean;
|
||||
initRequestDirection: InitRequestDirection;
|
||||
responseDirection: TimelineDirection;
|
||||
@@ -184,6 +186,9 @@ function shouldResolveTimelineInit({
|
||||
if (reset) {
|
||||
return true;
|
||||
}
|
||||
if (responseDirection === "after" && hasNewer) {
|
||||
return false;
|
||||
}
|
||||
return responseDirection === initRequestDirection;
|
||||
}
|
||||
|
||||
@@ -652,12 +657,16 @@ export function processTimelineResponse(
|
||||
// ------------------------------------------------------------------
|
||||
const shouldResolveDeferredInit = shouldResolveTimelineInit({
|
||||
hasActiveInitDeferred,
|
||||
hasNewer: payload.hasNewer,
|
||||
isInitializing,
|
||||
initRequestDirection,
|
||||
responseDirection: payload.direction,
|
||||
reset: payload.reset,
|
||||
});
|
||||
const clearInitializing = shouldResolveDeferredInit || (isInitializing && !hasActiveInitDeferred);
|
||||
const timelineResponseComplete = payload.direction !== "after" || !payload.hasNewer;
|
||||
const clearInitializing =
|
||||
(shouldResolveDeferredInit || (isInitializing && !hasActiveInitDeferred)) &&
|
||||
timelineResponseComplete;
|
||||
|
||||
const initResolution: "resolve" | "reject" | null = shouldResolveDeferredInit ? "resolve" : null;
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { TIMELINE_FETCH_PAGE_SIZE } from "@/timeline/timeline-fetch-policy";
|
||||
import {
|
||||
isTimelineCatchUpComplete,
|
||||
planInitialAgentTimelineSync,
|
||||
planResumeTimelineSync,
|
||||
planTimelineCatchUpFollowUp,
|
||||
planTimelineOlderFetch,
|
||||
} 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: "canonical",
|
||||
});
|
||||
});
|
||||
|
||||
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: "canonical",
|
||||
});
|
||||
});
|
||||
|
||||
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: "canonical",
|
||||
});
|
||||
});
|
||||
|
||||
test("resume without a cursor loads a bounded tail page", () => {
|
||||
const plan = planResumeTimelineSync({ cursor: undefined });
|
||||
|
||||
expect(plan).toEqual({
|
||||
direction: "tail",
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
});
|
||||
});
|
||||
|
||||
test("older history loads one bounded page before the start cursor", () => {
|
||||
const plan = planTimelineOlderFetch({ epoch: "epoch-1", seq: 25 });
|
||||
|
||||
expect(plan).toEqual({
|
||||
direction: "before",
|
||||
cursor: { epoch: "epoch-1", seq: 25 },
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
});
|
||||
});
|
||||
|
||||
test("catch-up keeps paging while the daemon reports newer rows", () => {
|
||||
const plan = planTimelineCatchUpFollowUp({
|
||||
direction: "after",
|
||||
hasNewer: true,
|
||||
endCursor: { epoch: "epoch-1", seq: 200 },
|
||||
error: null,
|
||||
});
|
||||
|
||||
expect(plan).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-1", seq: 200 },
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
});
|
||||
});
|
||||
|
||||
test("catch-up finishes when the daemon reports no newer rows", () => {
|
||||
const plan = planTimelineCatchUpFollowUp({
|
||||
direction: "after",
|
||||
hasNewer: false,
|
||||
endCursor: { epoch: "epoch-1", seq: 200 },
|
||||
error: null,
|
||||
});
|
||||
|
||||
expect(plan).toBeNull();
|
||||
expect(isTimelineCatchUpComplete({ direction: "after", hasNewer: false, error: null })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { TIMELINE_FETCH_PAGE_SIZE } from "@/timeline/timeline-fetch-policy";
|
||||
|
||||
export interface TimelineSyncCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export interface AgentTimelineCursorRange {
|
||||
epoch: string;
|
||||
startSeq: number;
|
||||
endSeq: number;
|
||||
}
|
||||
|
||||
export interface CanonicalTimelineTailFetchPlan {
|
||||
direction: "tail";
|
||||
limit: number;
|
||||
projection: "canonical";
|
||||
}
|
||||
|
||||
export interface CanonicalTimelineAfterFetchPlan {
|
||||
direction: "after";
|
||||
cursor: TimelineSyncCursor;
|
||||
limit: number;
|
||||
projection: "canonical";
|
||||
}
|
||||
|
||||
export interface CanonicalTimelineBeforeFetchPlan {
|
||||
direction: "before";
|
||||
cursor: TimelineSyncCursor;
|
||||
limit: number;
|
||||
projection: "canonical";
|
||||
}
|
||||
|
||||
export type CanonicalTimelineFetchPlan =
|
||||
| CanonicalTimelineTailFetchPlan
|
||||
| CanonicalTimelineAfterFetchPlan
|
||||
| CanonicalTimelineBeforeFetchPlan;
|
||||
|
||||
export type CanonicalTimelineForwardFetchPlan =
|
||||
| CanonicalTimelineTailFetchPlan
|
||||
| CanonicalTimelineAfterFetchPlan;
|
||||
|
||||
export function planInitialAgentTimelineSync(input: {
|
||||
cursor: AgentTimelineCursorRange | undefined;
|
||||
hasAuthoritativeHistory: boolean;
|
||||
}): CanonicalTimelineForwardFetchPlan {
|
||||
if (input.hasAuthoritativeHistory && input.cursor) {
|
||||
return planTimelineCatchUpAfter({ epoch: input.cursor.epoch, seq: input.cursor.endSeq });
|
||||
}
|
||||
|
||||
return planTimelineTailFetch();
|
||||
}
|
||||
|
||||
export function planResumeTimelineSync(input: {
|
||||
cursor: AgentTimelineCursorRange | undefined;
|
||||
}): CanonicalTimelineForwardFetchPlan {
|
||||
if (input.cursor) {
|
||||
return planTimelineCatchUpAfter({ epoch: input.cursor.epoch, seq: input.cursor.endSeq });
|
||||
}
|
||||
|
||||
return planTimelineTailFetch();
|
||||
}
|
||||
|
||||
export function planTimelineCatchUpAfter(cursor: TimelineSyncCursor) {
|
||||
return {
|
||||
direction: "after",
|
||||
cursor,
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function planTimelineTailFetch() {
|
||||
return {
|
||||
direction: "tail",
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function planTimelineOlderFetch(cursor: TimelineSyncCursor) {
|
||||
return {
|
||||
direction: "before",
|
||||
cursor,
|
||||
limit: TIMELINE_FETCH_PAGE_SIZE,
|
||||
projection: "canonical",
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function planTimelineCatchUpFollowUp(input: {
|
||||
direction: "tail" | "before" | "after";
|
||||
hasNewer: boolean;
|
||||
endCursor: TimelineSyncCursor | null;
|
||||
error: string | null;
|
||||
}): CanonicalTimelineAfterFetchPlan | null {
|
||||
if (input.error || input.direction !== "after" || !input.hasNewer || !input.endCursor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return planTimelineCatchUpAfter(input.endCursor);
|
||||
}
|
||||
|
||||
export function isTimelineCatchUpComplete(input: {
|
||||
direction: "tail" | "before" | "after";
|
||||
hasNewer: boolean;
|
||||
error: string | null;
|
||||
}): boolean {
|
||||
if (input.error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return input.direction !== "after" || !input.hasNewer;
|
||||
}
|
||||
Reference in New Issue
Block a user