Skip to content

Commit 97dbc44

Browse files
committed
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 ec4359c commit 97dbc44

22 files changed

Lines changed: 320 additions & 56 deletions
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/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.

‎src/gateway/server-methods/session-change-event.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,26 @@ describe("sessions.changed coalescing", () => {
124124
});
125125
});
126126

127+
it.each([false, true])("never samples a replacement for a delete (trailing: %s)", (trailing) => {
128+
const context = createContext();
129+
const sessionKey = "agent:main:chat";
130+
if (trailing) {
131+
emitSessionsChanged(context, { reason: "update", sessionKey });
132+
}
133+
mocks.loadRow.mockClear();
134+
const deletion = { reason: "delete", sessionKey, sessionId: "generation-a", agentId: "main" };
135+
emitSessionsChanged(context, deletion);
136+
mocks.rowLabel = "replacement-b";
137+
vi.advanceTimersByTime(100);
138+
const payload = vi.mocked(context.broadcastToConnIds).mock.calls.at(-1)?.[1];
139+
expect(payload).toEqual({
140+
...deletion,
141+
agentId: "main",
142+
ts: expect.any(Number),
143+
});
144+
expect(mocks.loadRow).not.toHaveBeenCalled();
145+
});
146+
127147
it("keeps different session keys independent", () => {
128148
const context = createContext();
129149

‎src/gateway/server-methods/session-change-event.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type { GatewayRequestContext } from "./types.js";
1414

1515
type SessionChangedPayload = {
1616
sessionKey?: string;
17+
sessionId?: string;
1718
agentId?: string;
1819
reason: string;
1920
compacted?: boolean;
@@ -76,7 +77,9 @@ function broadcastSessionsChanged(
7677
...(eventAgentId ? { agentId: eventAgentId } : {}),
7778
ts: Date.now(),
7879
};
80+
// A deletion describes the removed generation, never the row now occupying its key.
7981
if (
82+
payload.reason === "delete" ||
8083
!payload.sessionKey ||
8184
!routingAgentId ||
8285
(!eventAgentId && !compatibilityOwnerAgentId && !parseAgentSessionKey(payload.sessionKey))

‎src/gateway/server-methods/sessions-delete.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,7 @@ export const sessionDeleteHandlers: GatewayRequestHandlers = {
386386
if (deleted) {
387387
emitSessionsChanged(context, {
388388
sessionKey: target.canonicalKey,
389+
sessionId: deletion.deletedSessionId,
389390
agentId: target.agentId,
390391
reason: "delete",
391392
});

‎src/gateway/server-methods/sessions-mutations.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -358,10 +358,10 @@ export const sessionMutationHandlers: GatewayRequestHandlers = {
358358
}
359359
if ("incognitoDeleted" in result) {
360360
respond(true, { ok: true, key: result.key, deleted: true }, undefined);
361-
// The session is gone, not reset: clients drop rows and navigate away
362-
// only on "delete" (a non-delete reason merges a rowless no-op event).
363361
emitSessionsChanged(context, {
364362
sessionKey: result.key,
363+
agentId: result.agentId,
364+
sessionId: result.deletedSessionId,
365365
reason: "delete",
366366
});
367367
return;

‎src/gateway/server-session-events.test.ts‎

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,18 @@ function createHandler(
109109
return { broadcastToConnIds, handler };
110110
}
111111

112+
const ownerGoal = {
113+
schemaVersion: 1 as const,
114+
id: "goal-ops",
115+
objective: "Ops only",
116+
status: "active" as const,
117+
createdAt: 1,
118+
updatedAt: 2,
119+
tokenStart: 0,
120+
tokensUsed: 3,
121+
continuationTurns: 0,
122+
};
123+
112124
const PRIVATE_SESSION_FIELDS =
113125
"agentId session message owner goal status hasActiveRun activeRunIds model responseUsage".split(
114126
" ",
@@ -147,7 +159,6 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
147159
loadGatewaySessionRowMock.mockReturnValue(sessionRow);
148160
readSessionMessageCountAsyncMock.mockResolvedValue(undefined);
149161
resolveTranscriptSessionKeyBySessionIdMock.mockReturnValue(undefined);
150-
loadGatewaySessionRowMock.mockReturnValue(sessionRow);
151162
runtimeConfigState.value = {};
152163
sessionRow.key = "agent:main:main";
153164
sessionRow.thinkingLevel = "ultra";
@@ -586,17 +597,7 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
586597
])("$name", async ({ agentId }) => {
587598
runtimeConfigState.value = fixedStoreRuntimeConfig("ops", ["ops", "research"]);
588599
sessionRow.key = "global";
589-
const goal = {
590-
schemaVersion: 1 as const,
591-
id: "goal-ops",
592-
objective: "Ops only",
593-
status: "active" as const,
594-
createdAt: 1,
595-
updatedAt: 2,
596-
tokenStart: 0,
597-
tokensUsed: 3,
598-
continuationTurns: 0,
599-
};
600+
const goal = { ...ownerGoal };
600601
loadGatewaySessionRowMock.mockReturnValue({ ...sessionRow, goal });
601602
const getSessionMessageSubscribers = vi.fn((sessionKey: string) =>
602603
sessionKey === "global"
@@ -933,6 +934,23 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
933934
});
934935

935936
describe("createLifecycleEventBroadcastHandler", () => {
937+
it("keeps delayed key-only deletes as invalidations without borrowing a replacement", () => {
938+
const broadcastToConnIds = vi.fn();
939+
const handler = createLifecycleEventBroadcastHandler({
940+
broadcastToConnIds,
941+
sessionEventSubscribers: { getAll: () => new Set(["observer"]) },
942+
chatAbortControllers: new Map(),
943+
});
944+
handler({ sessionKey: sessionRow.key, reason: "delete" });
945+
expect(broadcastToConnIds).toHaveBeenCalledWith(
946+
"sessions.changed",
947+
{ sessionKey: sessionRow.key, agentId: "main", reason: "delete", ts: expect.any(Number) },
948+
new Set(["observer"]),
949+
expect.any(Object),
950+
);
951+
expect(loadGatewaySessionRowMock).not.toHaveBeenCalled();
952+
});
953+
936954
beforeEach(() => {
937955
vi.clearAllMocks();
938956
resolveEmbeddedAgentRunProgressStateMock.mockReturnValue(undefined);
@@ -1002,17 +1020,7 @@ describe("createLifecycleEventBroadcastHandler", () => {
10021020
])("$name", ({ agentId }) => {
10031021
runtimeConfigState.value = fixedStoreRuntimeConfig("ops", ["ops", "research"]);
10041022
sessionRow.key = "global";
1005-
const goal = {
1006-
schemaVersion: 1 as const,
1007-
id: "goal-ops",
1008-
objective: "Ops only",
1009-
status: "active" as const,
1010-
createdAt: 1,
1011-
updatedAt: 2,
1012-
tokenStart: 0,
1013-
tokensUsed: 3,
1014-
continuationTurns: 0,
1015-
};
1023+
const goal = { ...ownerGoal };
10161024
loadGatewaySessionRowMock.mockReturnValue({ ...sessionRow, goal });
10171025
const activeRun = {
10181026
...createActiveRun(true),

‎src/gateway/server-session-events.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,10 +404,20 @@ export function createLifecycleEventBroadcastHandler(params: {
404404
agentScope,
405405
);
406406
const broadcastOptions = { ...privateBroadcastScope, dropIfSlow: true };
407-
if (!routingAgentId || (!eventAgentId && !compatibilityOwnerAgentId)) {
407+
// Key-only lifecycle deletes invalidate membership; a later row is not deletion evidence.
408+
if (
409+
event.reason === "delete" ||
410+
!routingAgentId ||
411+
(!eventAgentId && !compatibilityOwnerAgentId)
412+
) {
408413
params.broadcastToConnIds(
409414
"sessions.changed",
410-
{ sessionKey: event.sessionKey, reason: event.reason, ts: Date.now() },
415+
{
416+
sessionKey: event.sessionKey,
417+
...(eventAgentId ? { agentId: eventAgentId } : {}),
418+
reason: event.reason,
419+
ts: Date.now(),
420+
},
411421
connIds,
412422
broadcastOptions,
413423
);

‎src/gateway/server.sessions.delete-state-lifecycle.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,42 @@ afterEach(() => {
6464
closeOpenClawStateDatabaseForTest();
6565
});
6666

67+
test("sessions.delete broadcasts the removed generation after a replacement appears", async () => {
68+
const { storePath } = await createSessionStoreDir();
69+
const sessionKey = "agent:main:event-generation";
70+
await writeSessionStore({ entries: { [sessionKey]: sessionStoreEntry("generation-a") } });
71+
const broadcast = vi.fn();
72+
const deleted = await directSessionReq(
73+
"sessions.delete",
74+
{ key: sessionKey },
75+
{
76+
coercePayload: (payload) => {
77+
replaceSessionEntrySync({ sessionKey, storePath }, sessionStoreEntry("generation-b"));
78+
return payload;
79+
},
80+
context: {
81+
broadcastToConnIds: broadcast,
82+
getSessionEventSubscriberConnIds: () => new Set(["observer"]),
83+
},
84+
},
85+
);
86+
expect(deleted).toMatchObject({ ok: true, payload: { deleted: true } });
87+
expect(loadSessionEntry({ sessionKey, storePath })?.sessionId).toBe("generation-b");
88+
expect(broadcast.mock.calls.map(([event, payload]) => ({ event, payload }))).toEqual([
89+
{
90+
event: "sessions.changed",
91+
payload: {
92+
sessionKey,
93+
agentId: "main",
94+
sessionId: "generation-a",
95+
reason: "delete",
96+
ts: expect.any(Number),
97+
},
98+
},
99+
{ event: "sessions.changed", payload: { reason: "delete", ts: expect.any(Number) } },
100+
]);
101+
});
102+
67103
test("sessions.delete removes the session board from its agent database", async () => {
68104
const { dir } = await createSessionStoreDir();
69105
await writeSingleLineSession(dir, "sess-board", "hello");

‎src/gateway/server.sessions.reset-hooks.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -573,7 +573,13 @@ test("sessions.reset of an incognito session broadcasts a delete, not a reset",
573573
expect(reset.payload?.deleted).toBe(true);
574574
// The row is gone; only reason "delete" makes clients drop it and navigate away.
575575
expect(broadcast.mock.calls[0]?.[0]).toBe("sessions.changed");
576-
expect(broadcast.mock.calls[0]?.[1]).toEqual(expect.objectContaining({ reason: "delete" }));
576+
expect(broadcast.mock.calls[0]?.[1]).toEqual({
577+
sessionKey: reset.payload?.key,
578+
agentId: "main",
579+
sessionId: "sess-incognito",
580+
reason: "delete",
581+
ts: expect.any(Number),
582+
});
577583
});
578584

579585
test("sessions.reset emits enriched session_end and session_start hooks", async () => {

0 commit comments

Comments
 (0)