fix: make session resume atomic across restarts
This commit is contained in:
@@ -134,6 +134,60 @@ test("an already-active same-session Resume preserves its EventSource and store"
|
||||
expect(useSessionStore.getState().activityLog).toEqual(before);
|
||||
});
|
||||
|
||||
test("a false then true pair of concurrent Resume completions preserves the cold stream", async () => {
|
||||
let resumeCalls = 0;
|
||||
let releaseCold!: () => void;
|
||||
let releaseAlreadyActive!: () => void;
|
||||
let markColdStarted!: () => void;
|
||||
let markAlreadyActiveStarted!: () => void;
|
||||
const coldStarted = new Promise<void>((resolve) => { markColdStarted = resolve; });
|
||||
const alreadyActiveStarted = new Promise<void>((resolve) => { markAlreadyActiveStarted = resolve; });
|
||||
const coldReleased = new Promise<void>((resolve) => { releaseCold = resolve; });
|
||||
const alreadyActiveReleased = new Promise<void>((resolve) => { releaseAlreadyActive = resolve; });
|
||||
server.use(
|
||||
http.post("http://localhost:8787/sessions/:id/resume", async () => {
|
||||
resumeCalls += 1;
|
||||
if (resumeCalls === 1) {
|
||||
markColdStarted();
|
||||
await coldReleased;
|
||||
return resumeResult("s1", false);
|
||||
}
|
||||
markAlreadyActiveStarted();
|
||||
await alreadyActiveReleased;
|
||||
return resumeResult("s1", true);
|
||||
}),
|
||||
http.get("http://localhost:8787/sessions/:id", () =>
|
||||
HttpResponse.json({ id: "s1", status: "open", phase: 1 })),
|
||||
);
|
||||
wrap();
|
||||
await userEvent.click(await screen.findByText("Attiva uno"));
|
||||
const resumeButton = await screen.findByRole("button", { name: /resume/i });
|
||||
|
||||
await userEvent.click(resumeButton);
|
||||
await coldStarted;
|
||||
await userEvent.click(resumeButton);
|
||||
await alreadyActiveStarted;
|
||||
expect(resumeCalls).toBe(2);
|
||||
|
||||
releaseCold();
|
||||
await waitFor(() => expect(FakeEventSource.instances).toHaveLength(1));
|
||||
const stream = FakeEventSource.instances[0];
|
||||
act(() => stream.emitNamed(
|
||||
"ui_request",
|
||||
{ type: "ui_request", ui_request: { id: "cold-gate", widget: "select" } },
|
||||
"1",
|
||||
));
|
||||
const before = useSessionStore.getState().activityLog.map((entry) => ({ ...entry }));
|
||||
|
||||
releaseAlreadyActive();
|
||||
await waitFor(() => expect(screen.queryByText("Domanda originale")).not.toBeInTheDocument());
|
||||
|
||||
expect(FakeEventSource.instances).toHaveLength(1);
|
||||
expect(stream.closed).toBe(false);
|
||||
expect(useSessionStore.getState().pendingWidget?.id).toBe("cold-gate");
|
||||
expect(useSessionStore.getState().activityLog).toEqual(before);
|
||||
});
|
||||
|
||||
test("cold same-session Resume keeps the old stream until success then receives post-clear events once", async () => {
|
||||
server.use(
|
||||
http.post("http://localhost:8787/sessions/:id/resume", () =>
|
||||
@@ -146,7 +200,7 @@ test("cold same-session Resume keeps the old stream until success then receives
|
||||
await userEvent.click(await screen.findByRole("button", { name: /resume/i }));
|
||||
await waitFor(() => expect(FakeEventSource.instances).toHaveLength(1));
|
||||
const first = FakeEventSource.instances[0];
|
||||
act(() => first.emitNamed("info", { type: "info", text: "Before cold Resume" }, "7"));
|
||||
act(() => first.emitNamed("info", { type: "info", text: "Before cold Resume" }, "900"));
|
||||
|
||||
let releaseResume!: () => void;
|
||||
let markStarted!: () => void;
|
||||
@@ -168,7 +222,7 @@ test("cold same-session Resume keeps the old stream until success then receives
|
||||
expect(useSessionStore.getState().activityLog).toContainEqual({
|
||||
kind: "status", phase: "F1", text: "Before cold Resume", level: "info",
|
||||
});
|
||||
act(() => first.emitNamed("text_delta", { type: "text_delta", text: "Still attached" }, "8"));
|
||||
act(() => first.emitNamed("text_delta", { type: "text_delta", text: "Still attached" }, "901"));
|
||||
expect(useSessionStore.getState().transcript).toEqual([
|
||||
{ role: "assistant", text: "Still attached" },
|
||||
]);
|
||||
@@ -177,7 +231,7 @@ test("cold same-session Resume keeps the old stream until success then receives
|
||||
await waitFor(() => expect(FakeEventSource.instances).toHaveLength(2));
|
||||
expect(first.closed).toBe(true);
|
||||
const replacement = FakeEventSource.instances[1];
|
||||
expect(replacement.url).toContain("/sessions/s1/events?lastEventId=8");
|
||||
expect(replacement.url).toBe("http://localhost:8787/sessions/s1/events");
|
||||
expect(useSessionStore.getState().transcript).toEqual([]);
|
||||
expect(useSessionStore.getState().activityLog).toEqual([
|
||||
{ kind: "lifecycle", phase: null, text: "Resuming session" },
|
||||
@@ -186,7 +240,7 @@ test("cold same-session Resume keeps the old stream until success then receives
|
||||
act(() => replacement.emitNamed(
|
||||
"text_delta",
|
||||
{ type: "text_delta", text: "Post-resume delivery" },
|
||||
"9",
|
||||
"1",
|
||||
));
|
||||
expect(useSessionStore.getState().transcript).toEqual([
|
||||
{ role: "assistant", text: "Post-resume delivery" },
|
||||
@@ -199,8 +253,8 @@ test("cold same-session Resume keeps the old stream until success then receives
|
||||
ui_request: { id: "post-resume-gate", widget: "select", title: "Review once" },
|
||||
};
|
||||
act(() => {
|
||||
replacement.emitNamed("ui_request", gate, "10");
|
||||
replacement.emitNamed("ui_request", gate, "11");
|
||||
replacement.emitNamed("ui_request", gate, "2");
|
||||
replacement.emitNamed("ui_request", gate, "3");
|
||||
});
|
||||
expect(useSessionStore.getState().pendingWidget?.id).toBe("post-resume-gate");
|
||||
expect(useSessionStore.getState().activityLog.filter((entry) => entry.kind === "gate"))
|
||||
|
||||
@@ -32,7 +32,8 @@ import { useEffect, useMemo, useRef, useState } from "react";
|
||||
*/
|
||||
export function AppShell() {
|
||||
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
|
||||
const [streamGeneration, setStreamGeneration] = useState(0);
|
||||
const activeSessionIdRef = useRef<string | null>(null);
|
||||
const [streamCursorResetEpoch, setStreamCursorResetEpoch] = useState(0);
|
||||
const [creatingSession, setCreatingSession] = useState(false);
|
||||
const [awaitingQuestion, setAwaitingQuestion] = useState(false);
|
||||
const { data: sessions = [] } = useQuery<SessionSummary[]>({
|
||||
@@ -65,6 +66,12 @@ export function AppShell() {
|
||||
const selectedSessions = sessions.filter((session) => selectedSessionIds.has(session.id));
|
||||
const allSessionsSelected = sessions.length > 0 && selectedSessions.length === sessions.length;
|
||||
|
||||
function selectActiveSession(id: string | null) {
|
||||
// Keep async Resume completions synchronized before React commits the state update.
|
||||
activeSessionIdRef.current = id;
|
||||
setActiveSessionId(id);
|
||||
}
|
||||
|
||||
// A background refresh can remove a session (for example from another browser).
|
||||
// Keep the local selection aligned with the authoritative list.
|
||||
useEffect(() => {
|
||||
@@ -100,9 +107,9 @@ export function AppShell() {
|
||||
});
|
||||
}
|
||||
async function doResume(id: string) {
|
||||
const reconnectSameSession = activeSessionId === id;
|
||||
try {
|
||||
const result = await resumeSession(id);
|
||||
const reconnectSameSession = activeSessionIdRef.current === id;
|
||||
setPanelSession(null);
|
||||
setAwaitingQuestion(false);
|
||||
|
||||
@@ -115,11 +122,11 @@ export function AppShell() {
|
||||
recordLifecycle("Resuming session");
|
||||
setAgentActive(true);
|
||||
}
|
||||
setActiveSessionId(id);
|
||||
// The backend has now completed clear/rebind. Recreate a same-id source with its cursor;
|
||||
// switching ids naturally creates a new source and resets the cursor in the stream hook.
|
||||
selectActiveSession(id);
|
||||
// A cold runtime starts a fresh SSE id sequence. Recreate a same-id source only after
|
||||
// Resume succeeds, and explicitly discard the old runtime's cursor.
|
||||
if (!result.alreadyActive && reconnectSameSession) {
|
||||
setStreamGeneration((value) => value + 1);
|
||||
setStreamCursorResetEpoch((value) => value + 1);
|
||||
}
|
||||
|
||||
// Paint the persisted re-entry phase while the replacement stream starts replaying.
|
||||
@@ -182,7 +189,7 @@ export function AppShell() {
|
||||
targets.filter((_, index) => results[index].status === "fulfilled").map((session) => session.id),
|
||||
);
|
||||
if (deletedIds.has(panelSession?.id ?? "")) setPanelSession(null);
|
||||
if (deletedIds.has(activeSessionId ?? "")) { resetSession(); setActiveSessionId(null); }
|
||||
if (deletedIds.has(activeSessionId ?? "")) { resetSession(); selectActiveSession(null); }
|
||||
setSelectedSessionIds((current) => new Set([...current].filter((id) => !deletedIds.has(id))));
|
||||
refresh();
|
||||
if (deletedIds.size !== targets.length) {
|
||||
@@ -226,7 +233,7 @@ export function AppShell() {
|
||||
// session sits idle or a gate awaits the reviewer (pendingWidget).
|
||||
const running = working && !finalized;
|
||||
|
||||
useSessionStream(activeSessionId, streamGeneration);
|
||||
useSessionStream(activeSessionId, 0, streamCursorResetEpoch);
|
||||
|
||||
// A backend "session_exit" system event (e.g. the replay server emitting it
|
||||
// when the reviewer picks "Esci") asks us to leave the live session view and
|
||||
@@ -240,7 +247,7 @@ export function AppShell() {
|
||||
// Never let a streamed event terminate the managed Pi child. Only the
|
||||
// explicit “Stop & save” action is allowed to call /close.
|
||||
resetSession();
|
||||
setActiveSessionId(null);
|
||||
selectActiveSession(null);
|
||||
setAwaitingQuestion(false);
|
||||
}
|
||||
// The final workflow turn ends with the session already finalized on disk:
|
||||
@@ -254,7 +261,7 @@ export function AppShell() {
|
||||
resetSession();
|
||||
setAwaitingQuestion(true);
|
||||
setCreatingSession(false);
|
||||
setActiveSessionId(null);
|
||||
selectActiveSession(null);
|
||||
// Best effort only: session creation keeps the authoritative readiness gate.
|
||||
// Composer focus is deliberately independent of this network request.
|
||||
void prewarmRuntime().catch(() => undefined);
|
||||
@@ -269,7 +276,7 @@ export function AppShell() {
|
||||
function finishSessionCreation(id: string) {
|
||||
// React batches these updates, preserving the provisional view and timer
|
||||
// while useSessionStream opens the durable session's SSE channel.
|
||||
setActiveSessionId(id);
|
||||
selectActiveSession(id);
|
||||
setCreatingSession(false);
|
||||
setAwaitingQuestion(false);
|
||||
refresh();
|
||||
@@ -287,7 +294,7 @@ export function AppShell() {
|
||||
await closeSession(activeSessionId);
|
||||
} finally {
|
||||
resetSession();
|
||||
setActiveSessionId(null);
|
||||
selectActiveSession(null);
|
||||
setAwaitingQuestion(false);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user