fix(web): close stale structured sockets
This commit is contained in:
@@ -235,6 +235,28 @@ describe("structured connection: turn/composer gating", () => {
|
||||
conn.dispose();
|
||||
});
|
||||
|
||||
it("ignores a submission failure after disposal", async () => {
|
||||
let reject!: (error: unknown) => void;
|
||||
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
|
||||
() => new Promise((_, rejectPromise) => { reject = rejectPromise; }),
|
||||
);
|
||||
const ws = new FakeSocket();
|
||||
const conn = mount({ sockets: [ws] });
|
||||
ws.open();
|
||||
ws.emit({ type: "reduced_state", state: idleState });
|
||||
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
|
||||
input.value = "do not restore";
|
||||
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
|
||||
conn.dispose();
|
||||
input.value = "detached draft";
|
||||
reject(new Error("late failure"));
|
||||
await Promise.resolve().then(() => Promise.resolve());
|
||||
|
||||
expect(input.value).toBe("detached draft");
|
||||
expect(conn.el.querySelector(".structured-error")).toBeNull();
|
||||
});
|
||||
|
||||
it("cancels the active turn via the cancel button", () => {
|
||||
const ws = new FakeSocket();
|
||||
const conn = mount({ sockets: [ws] });
|
||||
@@ -378,6 +400,8 @@ describe("structured connection: reconnection/error/loading", () => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("shows connecting, then connected, then reconnecting with backoff, and rebuilds from the fresh snapshot", () => {
|
||||
const first = new FakeSocket();
|
||||
const second = new FakeSocket();
|
||||
@@ -488,6 +512,70 @@ describe("structured connection: reconnection/error/loading", () => {
|
||||
conn.dispose();
|
||||
});
|
||||
|
||||
it("cancels pending backoff when acceptance forces reconciliation", async () => {
|
||||
let accept!: () => void;
|
||||
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
|
||||
() => new Promise((resolve) => { accept = resolve; }),
|
||||
);
|
||||
const first = new FakeSocket();
|
||||
const second = new FakeSocket();
|
||||
const reconciliation = new FakeSocket();
|
||||
const duplicate = new FakeSocket();
|
||||
const conn = mount({
|
||||
sockets: [first, second, reconciliation, duplicate],
|
||||
shouldReconnect: () => true,
|
||||
});
|
||||
first.open();
|
||||
first.emit({ type: "reduced_state", state: idleState });
|
||||
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
|
||||
input.value = "accepted during backoff";
|
||||
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
|
||||
first.drop();
|
||||
vi.advanceTimersByTime(1000);
|
||||
second.drop();
|
||||
accept();
|
||||
await Promise.resolve().then(() => Promise.resolve());
|
||||
|
||||
expect(reconciliation.onopen).not.toBeNull();
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(duplicate.onopen).toBeNull();
|
||||
|
||||
reconciliation.open();
|
||||
reconciliation.emit({ type: "reduced_state", state: idleState });
|
||||
expect(input.disabled).toBe(false);
|
||||
conn.dispose();
|
||||
expect(reconciliation.closed).toBe(true);
|
||||
});
|
||||
|
||||
it("does not reconcile when submission acceptance arrives after disposal", async () => {
|
||||
let accept!: () => void;
|
||||
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
|
||||
() => new Promise((resolve) => { accept = resolve; }),
|
||||
);
|
||||
const first = new FakeSocket();
|
||||
const second = new FakeSocket();
|
||||
const late = new FakeSocket();
|
||||
const conn = mount({ sockets: [first, second, late], shouldReconnect: () => true });
|
||||
first.open();
|
||||
first.emit({ type: "reduced_state", state: idleState });
|
||||
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
|
||||
input.value = "accepted after disposal";
|
||||
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
|
||||
first.drop();
|
||||
vi.advanceTimersByTime(1000);
|
||||
second.open();
|
||||
second.emit({ type: "reduced_state", state: idleState });
|
||||
conn.dispose();
|
||||
accept();
|
||||
await Promise.resolve().then(() => Promise.resolve());
|
||||
vi.advanceTimersByTime(60_000);
|
||||
|
||||
expect(second.closed).toBe(true);
|
||||
expect(late.onopen).toBeNull();
|
||||
});
|
||||
|
||||
it("reports a daemon rejection reason and does not schedule a retry", () => {
|
||||
const only = new FakeSocket();
|
||||
const conn = mount({ sockets: [only], shouldReconnect: () => true });
|
||||
|
||||
+56
-27
@@ -114,6 +114,7 @@ export function createStructuredConnection(
|
||||
let acceptedSubmission: { generation: number; socketGeneration: number } | null = null;
|
||||
let socketGeneration = 0;
|
||||
let stateSocketGeneration = 0;
|
||||
let disposed = false;
|
||||
|
||||
function lastRowIdOfKind(kind: TranscriptRowKind): string | null {
|
||||
for (let i = rows.length - 1; i >= 0; i--) if (rows[i].kind === kind) return rows[i].id;
|
||||
@@ -143,7 +144,7 @@ export function createStructuredConnection(
|
||||
// request was in flight (superseded, cancelled, answered elsewhere),
|
||||
// the state-driven re-render already replaced the row; reviving
|
||||
// buttons on it would be reviving a decision that no longer applies.
|
||||
if (rowId === pendingApprovalRowId) {
|
||||
if (!disposed && rowId === pendingApprovalRowId) {
|
||||
showError(String(e));
|
||||
throw e;
|
||||
}
|
||||
@@ -297,7 +298,11 @@ export function createStructuredConnection(
|
||||
renderComposerState();
|
||||
sendStructuredPrompt(sessionId, text).then(
|
||||
() => {
|
||||
if (generation !== submissionGeneration || awaitingBeginGeneration !== generation) return;
|
||||
if (
|
||||
disposed
|
||||
|| generation !== submissionGeneration
|
||||
|| awaitingBeginGeneration !== generation
|
||||
) return;
|
||||
const acceptanceSocketGeneration = socketGeneration;
|
||||
acceptedSubmission = { generation, socketGeneration: acceptanceSocketGeneration };
|
||||
// A replacement socket may have captured idle before the POST claimed
|
||||
@@ -305,7 +310,7 @@ export function createStructuredConnection(
|
||||
if (acceptanceSocketGeneration > submissionSocketGeneration) reconnectForReconciliation();
|
||||
},
|
||||
(e: unknown) => {
|
||||
if (generation !== submissionGeneration) return;
|
||||
if (disposed || generation !== submissionGeneration) return;
|
||||
if (awaitingBeginGeneration === generation) awaitingBeginGeneration = null;
|
||||
if (input.value === "") {
|
||||
input.value = text;
|
||||
@@ -318,7 +323,9 @@ export function createStructuredConnection(
|
||||
});
|
||||
cancelBtn.addEventListener("click", () => {
|
||||
clearError();
|
||||
cancelStructuredTurn(sessionId).catch((e: unknown) => showError(String(e)));
|
||||
cancelStructuredTurn(sessionId).catch((e: unknown) => {
|
||||
if (!disposed) showError(String(e));
|
||||
});
|
||||
});
|
||||
|
||||
// ---- narrow-pane rail collapse (a split pane, not just the viewport) ----
|
||||
@@ -331,39 +338,59 @@ export function createStructuredConnection(
|
||||
|
||||
// ---- live worktree/git-status rail data ----
|
||||
const unsubscribeStore = store?.subscribe((catalog: CatalogState) => {
|
||||
if (disposed) return;
|
||||
latestSession = catalog.sessions.get(sessionId);
|
||||
renderRailNow();
|
||||
});
|
||||
|
||||
// ---- socket lifecycle ----
|
||||
let ws: WebSocket;
|
||||
let ws: WebSocket | null = null;
|
||||
let reconnectMs = INITIAL_RECONNECT_MS;
|
||||
let reconnectTimer: number | null = null;
|
||||
let disposed = false;
|
||||
|
||||
function reconnectForReconciliation(): void {
|
||||
const stale = ws;
|
||||
stale.onopen = null;
|
||||
stale.onmessage = null;
|
||||
stale.onerror = null;
|
||||
stale.onclose = null;
|
||||
function cancelReconnect(): void {
|
||||
if (reconnectTimer === null) return;
|
||||
window.clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
|
||||
function closeCurrentSocket(): void {
|
||||
const socket = ws;
|
||||
ws = null;
|
||||
if (!socket) return;
|
||||
socket.onopen = null;
|
||||
socket.onmessage = null;
|
||||
socket.onerror = null;
|
||||
socket.onclose = null;
|
||||
try {
|
||||
stale.close();
|
||||
socket.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function reconnectForReconciliation(): void {
|
||||
if (disposed) return;
|
||||
cancelReconnect();
|
||||
closeCurrentSocket();
|
||||
setConnState("reconnecting…", "connecting");
|
||||
connect();
|
||||
}
|
||||
|
||||
function connect(): void {
|
||||
if (disposed) return;
|
||||
cancelReconnect();
|
||||
closeCurrentSocket();
|
||||
const connectionGeneration = ++socketGeneration;
|
||||
ws = socketFactory(sessionId);
|
||||
ws.onopen = () => {
|
||||
const socket = socketFactory(sessionId);
|
||||
ws = socket;
|
||||
socket.onopen = () => {
|
||||
if (disposed || ws !== socket) return;
|
||||
reconnectMs = INITIAL_RECONNECT_MS;
|
||||
setConnState("connected", "open");
|
||||
};
|
||||
ws.onmessage = (ev) => {
|
||||
socket.onmessage = (ev) => {
|
||||
if (disposed || ws !== socket) return;
|
||||
if (typeof ev.data !== "string") return;
|
||||
let msg: StructuredEvent;
|
||||
try {
|
||||
@@ -384,20 +411,25 @@ export function createStructuredConnection(
|
||||
break;
|
||||
}
|
||||
};
|
||||
ws.onerror = () => setConnState("error", "error");
|
||||
ws.onclose = (ev) => {
|
||||
socket.onerror = () => {
|
||||
if (disposed || ws !== socket) return;
|
||||
setConnState("error", "error");
|
||||
};
|
||||
socket.onclose = (ev) => {
|
||||
if (disposed || ws !== socket) return;
|
||||
ws = null;
|
||||
const reason = ev.reason?.trim();
|
||||
if (ev.code >= 4000 && reason && !disposed) {
|
||||
if (ev.code >= 4000 && reason) {
|
||||
setConnState(reason, "error");
|
||||
showError(`cannot attach: ${reason}`);
|
||||
return;
|
||||
}
|
||||
if (disposed) return;
|
||||
if (opts.shouldReconnect?.(sessionId, ev.code)) {
|
||||
const delay = Math.min(reconnectMs, MAX_RECONNECT_MS);
|
||||
setConnState("reconnecting…", "connecting");
|
||||
reconnectTimer = window.setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
if (disposed) return;
|
||||
reconnectMs = Math.min(reconnectMs * 2, MAX_RECONNECT_MS);
|
||||
connect();
|
||||
}, delay);
|
||||
@@ -423,7 +455,7 @@ export function createStructuredConnection(
|
||||
const focusOnMount = mountOpts?.focus !== false;
|
||||
const token = ++mountToken;
|
||||
requestAnimationFrame(() => {
|
||||
if (token !== mountToken) return; // parked/remounted since this was scheduled
|
||||
if (disposed || token !== mountToken) return; // parked/remounted since this was scheduled
|
||||
if (focusOnMount && !input.disabled) input.focus();
|
||||
});
|
||||
},
|
||||
@@ -440,14 +472,11 @@ export function createStructuredConnection(
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
if (reconnectTimer !== null) window.clearTimeout(reconnectTimer);
|
||||
mountToken++;
|
||||
cancelReconnect();
|
||||
resizeObserver.disconnect();
|
||||
unsubscribeStore?.();
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
closeCurrentSocket();
|
||||
el.remove();
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user