Skip to content

Commit 5014839

Browse files
fix(ui): abort stale destructive session confirmations on reconnect (#124254)
* fix(ui): abort stale destructive session confirmations on reconnect SessionDataController retires the session-mutation scope on reconnect, capability replacement, and host disconnect, but left any open destructive confirmation dialog in place. If the operator confirmed after reconnect the action silently no-opped, and the dialog's global lock stayed held until manually dismissed. Give SessionDataController an AbortController owned by the mutation epoch, abort it whenever the epoch advances, and expose the signal on SidebarSessionMutationScope. Wire it into every scope-bound confirm dialog: batch delete, single delete, cloud-worker stop, preserved- worktree removal, and session-group delete. confirm-dialog.ts already tears down its modal and releases the lock on an aborted signal, so a stale dialog now dismisses itself instead of surviving the reconnect. Fixes #124227 * fix(ui): abort chat-header confirms too and surface a retry notice The sidebar epoch-abort wiring left the chat-header delete/fork/archive path uncovered: it builds its own SidebarSessionMutationScope from connectionGeneration but never handed it a signal, so a header confirm left open across a reconnect kept the shared confirmation lock forever. Give ChatPaneBase its own AbortController, retire it everywhere connectionGeneration advances (reconnect and pane teardown), and wire the signal into the header's captured scope, matching SessionDataController's controller for the sidebar. Separately, resolving an aborted confirm to `false` looked identical to an ordinary cancel, so the operator's lost intent vanished silently. Reorder every destructive confirm site to check scope staleness ahead of the `confirmed` guard and show the existing "Gateway connection replaced ... Try again." toast on abort, matching the pattern deleteSessionGroup already used for the same race. This also fixes a regression the PR had introduced in a pre-existing main test (app-sidebar.test.ts's "keeps a reconnected group delete retryable after its confirm opened"), which is what failed checks-node-compact-large-22 and checks-ui on the previous head.
1 parent 878236c commit 5014839

11 files changed

Lines changed: 186 additions & 10 deletions

‎ui/src/components/app-sidebar-session-types.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,11 @@ export type SidebarSessionMutationScope = {
183183
sessions: SessionCapability;
184184
client: GatewayBrowserClient;
185185
selectedAgentId: string;
186+
// Owner-scoped abort signal for this epoch's destructive confirmations. A
187+
// retired epoch aborts it so any open dialog dismisses itself instead of
188+
// surviving a reconnect; scopes built outside SessionDataController may
189+
// leave this unset and keep their own stale-guard behavior.
190+
signal?: AbortSignal;
186191
};
187192

188193
export type SidebarSessionMutationResult = "completed" | "failed" | "stale";

‎ui/src/components/session-data-controller.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,10 @@ export class SessionDataController implements ReactiveController, SessionCatalog
9797
private gatewayConnected = false;
9898
// Bind mutation completions to one epoch so stale failures cannot cross reconnects.
9999
private sessionMutationEpoch = 0;
100+
// Owns the abort signal handed to every epoch-scoped destructive confirm dialog.
101+
// Retiring the epoch aborts it so a dialog open across a reconnect dismisses
102+
// itself instead of confirming into a mutation scope that no longer applies.
103+
private sessionMutationAbortController = new AbortController();
100104
private readonly scroll = new SessionDataScrollController(() => this.notify());
101105
private approvalBadgeQueue: ApplicationContext<RouteId>["overlays"]["snapshot"]["approvalQueue"] =
102106
[];
@@ -721,6 +725,10 @@ export class SessionDataController implements ReactiveController, SessionCatalog
721725
private invalidateSessionMutations(): void {
722726
this.sessionMutationEpoch += 1;
723727
this.sessionMutationError = null;
728+
// Dismiss any confirm dialog still open under the retired epoch before a
729+
// new one can be issued; otherwise it stays modal until manually closed.
730+
this.sessionMutationAbortController.abort();
731+
this.sessionMutationAbortController = new AbortController();
724732
this.notify();
725733
}
726734

@@ -743,6 +751,7 @@ export class SessionDataController implements ReactiveController, SessionCatalog
743751
sessions: context.sessions,
744752
client,
745753
selectedAgentId: this.host.selectedAgentIdForSessions(),
754+
signal: this.sessionMutationAbortController.signal,
746755
};
747756
}
748757

‎ui/src/components/session-organizer-batch-mutations.test.ts‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ import type {
88
import { GatewayRequestError, type GatewayBrowserClient } from "../api/gateway.ts";
99
import type { ApplicationGatewaySnapshot } from "../app/gateway.ts";
1010
import { loadSettings, patchSettings } from "../app/settings.ts";
11+
import { t } from "../i18n/index.ts";
1112
import type { SessionCapability } from "../lib/sessions/index.ts";
13+
import { showToast } from "../lib/toast.ts";
1214
import {
1315
answerConfirmDialog,
1416
installDialogPolyfill,
@@ -22,10 +24,13 @@ import { patchSessionRows } from "./session-organizer-batch-mutations.ts";
2224
import type { SessionOrganizerControllerHost } from "./session-organizer-controller.ts";
2325
import {
2426
deleteSession,
27+
deleteSessionGroup,
2528
deleteSessionsBatch,
2629
stopCloudWorker,
2730
} from "./session-organizer-operations.runtime.ts";
2831

32+
vi.mock("../lib/toast.ts", () => ({ showToast: vi.fn() }));
33+
2934
function sessionRow(index: number): SidebarRecentSession {
3035
return {
3136
key: `agent:main:batch-${index}`,
@@ -48,6 +53,10 @@ function createHarness(
4853
) {
4954
let current = params.current ?? true;
5055
let requestCount = 0;
56+
// Mirrors SessionDataController's own controller: retiring the scope aborts
57+
// it so a dialog wired to `scope.signal` dismisses itself for real, and
58+
// renewing stands in for the next `beginSessionMutation()` after a reconnect.
59+
let abortController = new AbortController();
5160
const request = vi.fn(async (_method: string, rawParams?: unknown, _options?: unknown) => {
5261
const patchParams = rawParams as SessionsPatchManyParams;
5362
const requestFailure = params.requestFailure;
@@ -88,6 +97,7 @@ function createHarness(
8897
const refreshTheme = vi.fn();
8998
const deleteMany = vi.fn(async () => ({ deleted: [], errors: [], preservedWorktrees: [] }));
9099
const deleteOne = vi.fn(async () => ({ deleted: true }));
100+
const groupsDelete = vi.fn(async () => "completed" as const);
91101
const scope = {
92102
epoch: 1,
93103
context: { agents: { state: { agentsList: null } }, theme: { refresh: refreshTheme } },
@@ -96,9 +106,11 @@ function createHarness(
96106
refreshReplacement,
97107
delete: deleteOne,
98108
deleteMany,
109+
groupsDelete,
99110
} as unknown as SessionCapability,
100111
client,
101112
selectedAgentId: "main",
113+
signal: abortController.signal,
102114
} as unknown as SidebarSessionMutationScope;
103115
const publishSessionMutationError = vi.fn();
104116
const pruneSidebarSessionEntry = vi.fn();
@@ -116,6 +128,7 @@ function createHarness(
116128
return {
117129
deleteMany,
118130
deleteOne,
131+
groupsDelete,
119132
host,
120133
pruneSidebarSessionEntry,
121134
publishSessionMutationError,
@@ -126,6 +139,13 @@ function createHarness(
126139
// Stands in for a reconnect or agent switch landing while a confirm is open.
127140
retireScope: () => {
128141
current = false;
142+
abortController.abort();
143+
},
144+
// Stands in for the next beginSessionMutation() a reconnect issues.
145+
renewScope: () => {
146+
current = true;
147+
abortController = new AbortController();
148+
scope.signal = abortController.signal;
129149
},
130150
scope,
131151
};
@@ -394,7 +414,7 @@ describe("patchSessionRows", () => {
394414
type OperationsHarness = ReturnType<typeof createHarness>;
395415

396416
const destructiveHarness = {
397-
methods: ["sessions.delete", "sessions.reclaim"],
417+
methods: ["sessions.delete", "sessions.reclaim", "sessions.groups.delete"],
398418
scopes: ["operator.write", "operator.admin"],
399419
};
400420

@@ -412,17 +432,26 @@ const destructiveOperations = [
412432
run: (harness: OperationsHarness) =>
413433
deleteSessionsBatch(harness.host, [sessionRow(0), sessionRow(1)], harness.scope),
414434
mutation: (harness: OperationsHarness) => harness.deleteMany,
435+
staleMessage: t("sessionsView.deleteSessionsStale", { count: "2" }),
415436
},
416437
{
417438
name: "session delete",
418439
run: (harness: OperationsHarness) => deleteSession(harness.host, sessionRow(0), harness.scope),
419440
mutation: (harness: OperationsHarness) => harness.deleteOne,
441+
staleMessage: t("sessionsView.deleteSessionStale", { session: sessionRow(0).label }),
420442
},
421443
{
422444
name: "cloud worker stop",
423445
run: (harness: OperationsHarness) =>
424446
stopCloudWorker(harness.host, cloudWorkerRow(false), harness.scope),
425447
mutation: (harness: OperationsHarness) => harness.request,
448+
staleMessage: t("sessionsView.stopCloudWorkerStale", { session: cloudWorkerRow(false).label }),
449+
},
450+
{
451+
name: "session-group delete",
452+
run: (harness: OperationsHarness) => deleteSessionGroup(harness.host, "Group A", harness.scope),
453+
mutation: (harness: OperationsHarness) => harness.groupsDelete,
454+
staleMessage: t("sessionsView.deleteGroupStale", { group: "Group A" }),
426455
},
427456
] as const;
428457

@@ -431,6 +460,7 @@ describe("session organizer destructive confirmations", () => {
431460

432461
beforeEach(() => {
433462
restoreDialogPolyfill = installDialogPolyfill();
463+
vi.mocked(showToast).mockClear();
434464
});
435465

436466
afterEach(() => {
@@ -466,20 +496,38 @@ describe("session organizer destructive confirmations", () => {
466496

467497
expect(operation.mutation(harness)).not.toHaveBeenCalled();
468498
expect(harness.publishSessionMutationError).not.toHaveBeenCalled();
499+
// An ordinary cancel is expected UX and needs no announcement; only a
500+
// reconnect-driven abort earns the retry notice below.
501+
expect(showToast).not.toHaveBeenCalled();
469502
});
470503

471504
it.each(destructiveOperations)(
472-
"abandons the $name when the connection is replaced while its confirm is open",
505+
"aborts the $name confirm and releases the lock for a fresh one when the connection is replaced while it is open",
473506
async (operation) => {
474507
const harness = createHarness(destructiveHarness);
475508

476509
const pending = operation.run(harness);
477-
const actions = await waitForConfirmDialogActions();
510+
await waitForConfirmDialogActions();
478511
harness.retireScope();
479-
answerConfirmDialog(actions, "confirm");
480512
await pending;
481513

482514
expect(operation.mutation(harness)).not.toHaveBeenCalled();
515+
// The stale dialog must dismiss itself, not merely stop sending its request.
516+
expect(document.body.querySelector("openclaw-modal-dialog")).toBeNull();
517+
// The abort resolves the dialog to `false`, same as a user cancel, so the
518+
// operator needs a distinct, visible outcome or their lost intent reads
519+
// as a click that simply did nothing.
520+
expect(showToast).toHaveBeenCalledWith({ message: operation.staleMessage });
521+
522+
// A fresh confirmation (the reconnect's own retry) must be able to open
523+
// immediately; a stale dialog holding the shared lock would block it.
524+
harness.renewScope();
525+
const reopened = operation.run(harness);
526+
const freshActions = await waitForConfirmDialogActions();
527+
answerConfirmDialog(freshActions, "confirm");
528+
await reopened;
529+
530+
expect(operation.mutation(harness)).toHaveBeenCalledOnce();
483531
},
484532
);
485533

@@ -503,6 +551,11 @@ describe("session organizer destructive confirmations", () => {
503551

504552
expect(harness.request).not.toHaveBeenCalled();
505553
expect(harness.replaceCurrentSession).not.toHaveBeenCalled();
554+
// The session delete already landed; the worktree just stays put, same as
555+
// the no-access branch, so the operator learns where it went.
556+
expect(showToast).toHaveBeenCalledWith({
557+
message: t("sessionsView.deletePreservedWorktrees", { count: "1", branches: "feature" }),
558+
});
506559
});
507560

508561
it("skips the delete confirm entirely once the operator opted out", async () => {

‎ui/src/components/session-organizer-catalog.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,14 +100,18 @@ export async function deleteSessionGroup(
100100
message: t("sessionsView.deleteGroupConfirm"),
101101
confirmLabel: t("common.delete"),
102102
danger: true,
103+
signal: scope.signal,
103104
});
104-
if (!confirmed) {
105-
return false;
106-
}
105+
// Checked ahead of `confirmed`: a retired scope aborts the dialog to `false`
106+
// too, so without this order the operator's lost intent would look like an
107+
// ordinary cancel instead of the reconnect that actually dropped it.
107108
if (!host.sessionData.isSessionMutationScopeCurrent(scope)) {
108109
showToast({ message: t("sessionsView.deleteGroupStale", { group }) });
109110
return false;
110111
}
112+
if (!confirmed) {
113+
return false;
114+
}
111115
try {
112116
const outcome = await scope.sessions.groupsDelete(group);
113117
return outcome === "completed" && host.sessionData.isSessionMutationScopeCurrent(scope);

‎ui/src/components/session-organizer-operations.runtime.ts‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,10 +276,18 @@ export async function deleteSessionsBatch(
276276
confirmLabel: t("common.delete"),
277277
danger: true,
278278
skipPreference: sessionDeleteSkipPreference(scope),
279+
signal: scope.signal,
279280
});
280281
// A reconnect or a replaced sessions capability can land while the modal is
281282
// open, so the captured scope is revalidated before any delete leaves here.
282-
if (!confirmed || !host.sessionData.isSessionMutationScopeCurrent(scope)) {
283+
// Checked ahead of `confirmed`: a retired scope aborts the dialog to `false`
284+
// too, so without this order the operator's lost intent would look like an
285+
// ordinary cancel instead of the reconnect that actually dropped it.
286+
if (!host.sessionData.isSessionMutationScopeCurrent(scope)) {
287+
showToast({ message: t("sessionsView.deleteSessionsStale", { count: String(rows.length) }) });
288+
return;
289+
}
290+
if (!confirmed) {
283291
return;
284292
}
285293
const requests = rows.map((row) => ({
@@ -503,8 +511,16 @@ export async function stopCloudWorker(
503511
message: t("sessionsView.stopCloudWorkerConfirm", { session: session.label }),
504512
confirmLabel: t("sessionsView.stopCloudWorkerConfirmAction"),
505513
danger: true,
514+
signal: scope.signal,
506515
});
507-
if (!confirmed || !host.sessionData.isSessionMutationScopeCurrent(scope)) {
516+
// Checked ahead of `confirmed`: a retired scope aborts the dialog to `false`
517+
// too, so without this order the operator's lost intent would look like an
518+
// ordinary cancel instead of the reconnect that actually dropped it.
519+
if (!host.sessionData.isSessionMutationScopeCurrent(scope)) {
520+
showToast({ message: t("sessionsView.stopCloudWorkerStale", { session: session.label }) });
521+
return;
522+
}
523+
if (!confirmed) {
508524
return;
509525
}
510526
if (!requireSessionMutationAccess(host, scope, stopAction)) {
@@ -546,8 +562,16 @@ export async function deleteSession(
546562
confirmLabel: t("common.delete"),
547563
danger: true,
548564
...(options.offerSkip ? { skipPreference: sessionDeleteSkipPreference(scope) } : {}),
565+
signal: scope.signal,
549566
});
550-
if (!confirmed || !host.sessionData.isSessionMutationScopeCurrent(scope)) {
567+
// Checked ahead of `confirmed`: a retired scope aborts the dialog to `false`
568+
// too, so without this order the operator's lost intent would look like an
569+
// ordinary cancel instead of the reconnect that actually dropped it.
570+
if (!host.sessionData.isSessionMutationScopeCurrent(scope)) {
571+
showToast({ message: t("sessionsView.deleteSessionStale", { session: session.label }) });
572+
return;
573+
}
574+
if (!confirmed) {
551575
return;
552576
}
553577
const agentId = parseAgentSessionKey(session.key)?.agentId ?? scope.selectedAgentId;
@@ -597,10 +621,19 @@ export async function deleteSession(
597621
message: t("sessionsView.deletePreservedWorktreeConfirm", { branch: preserved.branch }),
598622
confirmLabel: t("common.remove"),
599623
danger: true,
624+
signal: scope.signal,
600625
});
601626
// Cancel needs this guard too: the delete already landed, so a scope
602627
// retired while the modal was open must not drive the navigation below.
628+
// A retired scope leaves the worktree exactly like the no-access branch
629+
// above, so it earns the same visible outcome instead of vanishing quietly.
603630
if (!host.sessionData.isSessionMutationScopeCurrent(scope)) {
631+
showToast({
632+
message: t("sessionsView.deletePreservedWorktrees", {
633+
count: "1",
634+
branches: preserved.branch,
635+
}),
636+
});
604637
return;
605638
}
606639
if (removeWorktree) {

‎ui/src/i18n/locales/en.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -997,11 +997,16 @@ export const en: TranslationMap = {
997997
stopCloudWorker: "Stop cloud worker…",
998998
stopCloudWorkerConfirm: 'Stop the cloud worker for "{session}"?',
999999
stopCloudWorkerConfirmAction: "Stop worker",
1000+
stopCloudWorkerStale:
1001+
'Gateway connection replaced before the cloud worker for "{session}" was stopped. Try again.',
10001002
cloudWorkerStopResult: 'Cloud worker for "{session}" is {state}.',
10011003
deleteSessionMenu: "Delete…",
10021004
deleteSessionCount: "Delete {count}…",
10031005
deleteSessionConfirm: 'Delete "{session}" and its transcript?',
1006+
deleteSessionStale: 'Gateway connection replaced before "{session}" was deleted. Try again.',
10041007
deleteSessionsConfirm: "Delete {count} sessions and their transcripts?",
1008+
deleteSessionsStale:
1009+
"Gateway connection replaced before {count} sessions were deleted. Try again.",
10051010
deleteSelectedConfirmOne:
10061011
"Delete 1 session?\n\nThis will delete the session entry and archive its transcript.",
10071012
deleteSelectedConfirm:

‎ui/src/pages/chat/chat-pane-base.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,13 @@ export abstract class ChatPaneBase extends OpenClawLightDomElement {
119119
this.activeChanged(value);
120120
}
121121
protected activeChanged(_active: boolean): void {}
122+
// Call wherever connectionGeneration itself advances (reconnect, capability
123+
// replacement, pane teardown) so a header confirm dialog open across that
124+
// boundary dismisses itself instead of confirming into a retired scope.
125+
protected retireHeaderSessionMutations(): void {
126+
this.headerSessionMutationAbortController.abort();
127+
this.headerSessionMutationAbortController = new AbortController();
128+
}
122129
@property({ attribute: false }) draft?: string;
123130
@property({ attribute: false }) focusComposer = false;
124131
@property({ attribute: false }) routeFace: BoardFace = "chat";
@@ -171,6 +178,11 @@ export abstract class ChatPaneBase extends OpenClawLightDomElement {
171178
protected boardProviderLease: (BoardProviderLease & { sessionKey: string }) | undefined;
172179
protected boardProviderLifecycleConnected = false;
173180
protected connectionGeneration = 0;
181+
// Owns the abort signal handed to header-scoped destructive confirm dialogs.
182+
// Retiring it alongside every connectionGeneration bump lets a dialog open
183+
// across a reconnect or pane teardown dismiss itself, matching
184+
// SessionDataController's own epoch-scoped controller for the sidebar.
185+
protected headerSessionMutationAbortController = new AbortController();
174186
@litState() protected headerEditing = false;
175187
@litState() protected headerRenameValue = "";
176188
@litState() protected headerPlatform: string | null = null;

‎ui/src/pages/chat/chat-pane-context.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ export abstract class ChatPaneContext extends ChatPaneLifecycle {
224224
// A reconnect can retain the browser client. Keep async ownership tied
225225
// to the logical connection, not only the transport object identity.
226226
this.connectionGeneration += 1;
227+
this.retireHeaderSessionMutations();
227228
invalidateChatAvatarCache(state);
228229
invalidateAssistantIdentityCache(state.client);
229230
state.assistantIdentityRequestVersion += 1;

‎ui/src/pages/chat/chat-pane-lifecycle.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -614,6 +614,7 @@ export abstract class ChatPaneLifecycle extends ChatPaneSessionCreation {
614614
this.paneResizeObserver?.disconnect();
615615
this.paneResizeObserver = null;
616616
this.connectionGeneration += 1;
617+
this.retireHeaderSessionMutations();
617618
this.deferredSessionHydrationRequestVersion += 1;
618619
this.sessionDiscussionPanels.clear();
619620
this.taskSuggestionsRequestVersion += 1;

‎ui/src/pages/chat/chat-pane-session-menu.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ export abstract class ChatPaneSessionMenu extends ChatPaneContext {
226226
sessions: this.context.sessions,
227227
client,
228228
selectedAgentId: this.context.agentSelection.state.selectedId ?? "main",
229+
signal: this.headerSessionMutationAbortController.signal,
229230
};
230231
}
231232

0 commit comments

Comments
 (0)