Skip to content

Commit 09be104

Browse files
authored
fix(sessions): deleted sessions remain visible during worker cleanup (#132233)
* fix(sessions): delete immediately and safely reclaim workers Remove confirmed selections optimistically, retain canonical generation ownership across stale responses and reconnects, and reconcile failures without restoring old navigation. Share archive/delete lifecycle drains and safely reclaim worker workspaces before deletion commits. Preserve exact caller, session, and placement authority through asynchronous cleanup. Fixes #132057. * test(sessions): align fixtures with canonical deletion ownership Use real session capability publications, support independent subscribers, assert postcommit placement retirement, and distinguish selected threads from the configured main session in browser fixtures. Preserve archived-action and geometry assertions. * fix(sessions): bind delete events to the removed generation Carry deleted session identity from lifecycle results, skip current-row enrichment for deletion broadcasts, and reconcile key-only notifications without purging a replacement. Cover delayed events, incognito reset, and the real RPC-to-broadcast boundary. Record the final measured startup baseline within the approved adjustment.
1 parent f0ade2d commit 09be104

87 files changed

Lines changed: 3546 additions & 1475 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatGatewayRequest.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -412,7 +412,7 @@ public enum OpenClawChatGatewayRequests {
412412
return OpenClawChatGatewayRequest(
413413
method: "sessions.delete",
414414
params: params,
415-
timeoutMs: self.mutationTimeoutMs)
415+
timeoutMs: self.archiveMutationTimeoutMs)
416416
}
417417

418418
public static func forkSession(

‎apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatGatewayRequestTests.swift‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ struct ChatGatewayRequestTests {
305305
#expect(delete.params["name"]?.value as? String == "Personal")
306306
}
307307

308-
@Test func `rename clear archive and fork use session mutation contracts`() {
308+
@Test func `rename clear archive delete and fork use session mutation contracts`() {
309309
let rename = OpenClawChatGatewayRequests.patchSession(
310310
sessionKey: "agent:main:child",
311311
agentID: nil,
@@ -335,11 +335,16 @@ struct ChatGatewayRequestTests {
335335
let fork = OpenClawChatGatewayRequests.forkSession(
336336
parentSessionKey: "agent:main:child",
337337
agentID: nil)
338+
let delete = OpenClawChatGatewayRequests.deleteSession(
339+
sessionKey: "agent:main:child",
340+
agentID: nil)
338341

339342
#expect(rename.params["label"]?.value is NSNull)
340343
#expect(archive.params["archived"]?.value as? Bool == true)
341344
#expect(archive.params["expectedSessionId"]?.value as? String == "session-child")
342345
#expect(archive.timeoutMs == 600_000)
346+
#expect(delete.method == "sessions.delete")
347+
#expect(delete.timeoutMs == 600_000)
343348
#expect(restore.params["expectedSessionId"]?.value as? String == "session-child")
344349
#expect(restore.timeoutMs == 15000)
345350
#expect(fork.method == "sessions.create")
@@ -391,7 +396,8 @@ struct ChatGatewayRequestTests {
391396
#expect(request.params["thinking"]?.value as? String == "low")
392397
#expect(request.params["timeoutMs"] == nil)
393398
let encoded = try JSONEncoder().encode(request.params["attachments"])
394-
#expect(String(decoding: encoded, as: UTF8.self).contains("a.png"))
399+
let json = try #require(String(bytes: encoded, encoding: .utf8))
400+
#expect(json.contains("a.png"))
395401
}
396402

397403
@Test func `send request omits inherited thinking override`() {

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2960,7 +2960,6 @@ src/gateway/server-methods/session-catalog.ts 5
29602960
src/gateway/server-methods/session-create-initial-turn.ts 2
29612961
src/gateway/server-methods/session-recovery-continuation.ts 1
29622962
src/gateway/server-methods/sessions-abort.ts 3
2963-
src/gateway/server-methods/sessions-archive-lifecycle.ts 3
29642963
src/gateway/server-methods/sessions-compact.ts 1
29652964
src/gateway/server-methods/sessions-create.ts 1
29662965
src/gateway/server-methods/sessions-messaging.ts 11
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"startupJsGzipBytes": 344714,
3-
"reason": "Revert queued-send transcript bubbles (#131909) per operator live review; fresh pnpm ui:build measures 344714 B. Retain the 512 B growth allowance, 64 B build variance, and 350 KiB baseline ceiling.",
2+
"startupJsGzipBytes": 345606,
3+
"reason": "Generation-safe optimistic session deletion (#132233, fixing #132057); measured 345606 B after current-main integration, below the maintainer-approved 347323 B baseline; hard cap and allowances unchanged",
44
"updatedAt": "2026-08-29"
55
}

‎docs/gateway/cloud-workers.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ ordinary reconcile-first move instead.
361361

362362
When the work is complete and no turn is running, choose **Stop cloud worker…** from the same chip. The Gateway performs one final workspace reconciliation before it destroys the environment. A placement already in `draining` or `reconciling` is finishing teardown; wait for its badge to become `reclaimed` before resetting or deleting the session. Starting another turn after reclaim provisions a replacement worker only while its original cloud profile remains configured for the same provider; deleting that profile prevents new cloud allocation.
363363

364-
Archiving a non-main cloud-worker session with an active placement also performs this safe stop and reclaim before the Gateway records it as archived. If the placement is still transitioning or failed without proof that its environment is gone, the session remains unarchived; wait for the placement to settle, then retry. Restoring the session retains the reclaimed placement metadata so the next turn can dispatch a fresh worker with the same workspace profile.
364+
Archiving or deleting a non-main cloud-worker session with an active placement first interrupts and drains its current work, then safely reclaims the worker. The Gateway records the archive or deletion only after final reconciliation and safe teardown succeed. If reclaim is unavailable, fails, or the placement is transitioning or failed without proof that its environment is gone, the operation reports an error and retains the session and recovery state; it never force-discards unsynced work. Restoring an archived session retains reclaimed placement metadata so the next turn can dispatch a fresh worker with the same workspace profile.
365365

366366
For a broken or runaway cloud environment, an administrator can call the admin-only `environments.destroy` method with `{ "force": true }` as a last resort. Forced teardown durably marks the placement failed and abandons any unreconciled remote result before destroying the environment.
367367

@@ -401,7 +401,7 @@ The Gateway owns the canonical session transcript in both modes. Worker-turn com
401401

402402
Worker-turn live previews are snapshots of the current assistant message. Corrections, shorter previews, and empty replacements update that message without replaying or erasing earlier messages in the turn. Explicit commentary is kept out of answer text, including when its phase arrives at message completion. Live previews are bounded and can be dropped after stream degradation; the committed transcript remains authoritative.
403403

404-
Workspace state has a wider loss window. A completed turn reconciles cloud files before releasing its claim, and **Stop cloud worker…** performs one final reconciliation before destroying the machine. Changes made between reconciliations exist only on the box and can be lost. Session deletion does not synchronize an active placement: it must first be stopped or archived. Deletion then snapshots the already-reconciled managed worktree under `refs/openclaw/snapshots/` before removing it.
404+
Workspace state has a wider loss window. A completed turn reconciles cloud files before releasing its claim, and **Stop cloud worker…**, archiving, or deleting a session performs final reconciliation before destroying an active worker. Changes made between reconciliations exist only on the box and can be lost if that box disappears. Deletion proceeds only after safe reclaim succeeds, then snapshots the reconciled managed worktree under `refs/openclaw/snapshots/` before removing it. A failed safe reclaim retains the session and unsynced recovery state and reports an error.
405405

406406
After a failed placement, redispatch the session and retry the turn. A reclaimed placement redispatches automatically on the next turn. The next turn rebuilds model context from the Gateway transcript, so it continues from the messages that crossed the durability boundary.
407407

‎docs/gateway/protocol.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -807,7 +807,11 @@ count.
807807
- `sessions.changed`: session index or metadata changed. Active-run fields use the
808808
same aggregate and complete-exact semantics as `sessions.list`; `activeRunIds: null`
809809
clears cached exact identities to unavailable, omission leaves the cache unchanged,
810-
and an array replaces it.
810+
and an array replaces it. Delete notifications from `sessions.delete` and incognito
811+
reset carry the removed generation's `sessionId`, without a current-row snapshot.
812+
Clients must not delete a replacement with a different ID. A key-only delete event
813+
or a rowless global notification invalidates the canonical session list; it does
814+
not identify the current generation as deleted.
811815
- `presence`: system presence snapshot updates.
812816
- `tick`: periodic keepalive/liveness event.
813817
- `health`: gateway health snapshot update.

‎docs/web/control-ui.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,8 @@ Session previews are hidden by default for compact, single-line rows. Enable **S
256256

257257
**Mark as unread** creates a reminder that remains unread while the current chat stays open, including while a run streams or completes. Leave and reopen the session, or choose **Mark as read**, to clear it.
258258

259+
**Delete** removes the confirmed selection from loaded session lists immediately and leaves any deleted conversation that is open. The Gateway finishes deletion in the background, safely stopping and reclaiming an attached cloud worker first. If deletion fails, the affected session can reappear with an error; other successful deletions and any navigation you made in the meantime are preserved. Browser drafts are retired only after deletion is confirmed, not while the request is pending.
260+
259261
**Rename** in the sidebar, chat header, and Sessions page targets the session you started editing. If that session is deleted and recreated at the same key before you save, the edit is rejected instead of renaming the replacement. Reopen Rename on the current session to try again. Resetting the conversation keeps the same session identity and does not invalidate the edit.
260262

261263
**New group** from the sidebar, chat header, or Sessions page keeps the original session selection while the dialog is open and the group is being saved. A deleted or replaced session is not moved; an error is shown and the new group remains available. For a sidebar multi-selection, sessions that still exist can move even if another target fails. Paging a selected session out of the visible list does not cancel its move.

‎src/cli/gateway-rpc.runtime.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,9 @@ describe("callGatewayFromCliRuntime", () => {
180180
});
181181

182182
it("passes strict integer timeouts to the gateway call", async () => {
183-
await callGatewayFromCliRuntime("cron.status", { timeout: "15000" });
183+
await callGatewayFromCliRuntime("cron.status", { timeout: "15000" }, undefined, {
184+
defaultTimeoutMs: 10 * 60_000,
185+
});
184186

185187
expect(callGatewayMock).toHaveBeenCalledWith(
186188
expect.objectContaining({

‎src/commands/sessions-lifecycle.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ describe("sessions lifecycle commands", () => {
262262
deleteTranscript: true,
263263
archivedOnly: true,
264264
},
265-
{ defaultTimeoutMs: 30_000 },
265+
{ defaultTimeoutMs: 10 * 60_000 },
266266
);
267267
expect(runtime.writeJson).toHaveBeenCalledWith(
268268
{

‎src/commands/sessions-lifecycle.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ async function runSessionsLifecycleCommand(
331331
deleteTranscript: true,
332332
...(session.archived === true ? { archivedOnly: true } : {}),
333333
},
334-
{ defaultTimeoutMs: 30_000 },
334+
{ defaultTimeoutMs: SESSION_ARCHIVE_REQUEST_TIMEOUT_MS },
335335
)) as SessionsDeleteResult;
336336
if (!response.deleted) {
337337
results[index] = notFoundResult(session.key, agent);

0 commit comments

Comments
 (0)