Skip to content

Commit c519e01

Browse files
authored
feat(gateway): chat.send expectedLeafEntryId precondition keeps stale panes off switched branches (#113073)
1 parent 73d279c commit c519e01

44 files changed

Lines changed: 1606 additions & 868 deletions

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/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4916,6 +4916,7 @@ public struct SessionRow: Codable, Sendable {
49164916
public let lastinteractionat: Double?
49174917
public let status: AnyCodable?
49184918
public let lastrunerror: String?
4919+
public let activeleafentryid: AnyCodable?
49194920
public let spawnedby: String?
49204921
public let parentsessionkey: String?
49214922
public let controlownersessionkey: String?
@@ -4970,6 +4971,7 @@ public struct SessionRow: Codable, Sendable {
49704971
lastinteractionat: Double? = nil,
49714972
status: AnyCodable? = nil,
49724973
lastrunerror: String? = nil,
4974+
activeleafentryid: AnyCodable? = nil,
49734975
spawnedby: String? = nil,
49744976
parentsessionkey: String? = nil,
49754977
controlownersessionkey: String? = nil,
@@ -5023,6 +5025,7 @@ public struct SessionRow: Codable, Sendable {
50235025
self.lastinteractionat = lastinteractionat
50245026
self.status = status
50255027
self.lastrunerror = lastrunerror
5028+
self.activeleafentryid = activeleafentryid
50265029
self.spawnedby = spawnedby
50275030
self.parentsessionkey = parentsessionkey
50285031
self.controlownersessionkey = controlownersessionkey
@@ -5078,6 +5081,7 @@ public struct SessionRow: Codable, Sendable {
50785081
case lastinteractionat = "lastInteractionAt"
50795082
case status
50805083
case lastrunerror = "lastRunError"
5084+
case activeleafentryid = "activeLeafEntryId"
50815085
case spawnedby = "spawnedBy"
50825086
case parentsessionkey = "parentSessionKey"
50835087
case controlownersessionkey = "controlOwnerSessionKey"
@@ -16328,6 +16332,7 @@ public struct ChatSendParams: Codable, Sendable {
1632816332
public let systeminputprovenance: [String: AnyCodable]?
1632916333
public let systemprovenancereceipt: String?
1633016334
public let suppresscommandinterpretation: Bool?
16335+
public let expectedleafentryid: AnyCodable?
1633116336
public let expectedsessionroutingcontract: String?
1633216337
public let idempotencykey: String
1633316338

@@ -16352,6 +16357,7 @@ public struct ChatSendParams: Codable, Sendable {
1635216357
systeminputprovenance: [String: AnyCodable]? = nil,
1635316358
systemprovenancereceipt: String? = nil,
1635416359
suppresscommandinterpretation: Bool? = nil,
16360+
expectedleafentryid: AnyCodable? = nil,
1635516361
expectedsessionroutingcontract: String? = nil,
1635616362
idempotencykey: String)
1635716363
{
@@ -16375,6 +16381,7 @@ public struct ChatSendParams: Codable, Sendable {
1637516381
self.systeminputprovenance = systeminputprovenance
1637616382
self.systemprovenancereceipt = systemprovenancereceipt
1637716383
self.suppresscommandinterpretation = suppresscommandinterpretation
16384+
self.expectedleafentryid = expectedleafentryid
1637816385
self.expectedsessionroutingcontract = expectedsessionroutingcontract
1637916386
self.idempotencykey = idempotencykey
1638016387
}
@@ -16399,6 +16406,7 @@ public struct ChatSendParams: Codable, Sendable {
1639916406
systeminputprovenance: [String: AnyCodable]? = nil,
1640016407
systemprovenancereceipt: String? = nil,
1640116408
suppresscommandinterpretation: Bool? = nil,
16409+
expectedleafentryid: AnyCodable? = nil,
1640216410
expectedsessionroutingcontract: String? = nil,
1640316411
idempotencykey: String)
1640416412
{
@@ -16423,6 +16431,7 @@ public struct ChatSendParams: Codable, Sendable {
1642316431
systeminputprovenance: systeminputprovenance,
1642416432
systemprovenancereceipt: systemprovenancereceipt,
1642516433
suppresscommandinterpretation: suppresscommandinterpretation,
16434+
expectedleafentryid: expectedleafentryid,
1642616435
expectedsessionroutingcontract: expectedsessionroutingcontract,
1642716436
idempotencykey: idempotencykey)
1642816437
}
@@ -16448,6 +16457,7 @@ public struct ChatSendParams: Codable, Sendable {
1644816457
case systeminputprovenance = "systemInputProvenance"
1644916458
case systemprovenancereceipt = "systemProvenanceReceipt"
1645016459
case suppresscommandinterpretation = "suppressCommandInterpretation"
16460+
case expectedleafentryid = "expectedLeafEntryId"
1645116461
case expectedsessionroutingcontract = "expectedSessionRoutingContract"
1645216462
case idempotencykey = "idempotencyKey"
1645316463
}

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,7 @@ methods. Treat this as feature discovery, not a full enumeration of
584584
- Chat execution still uses `chat.history`, `chat.send`, `chat.abort`, and `chat.inject`. `chat.history` is display-normalized for UI clients: inline directive tags are stripped from visible text, plain-text tool-call XML payloads (`<tool_call>...</tool_call>`, `<function_call>...</function_call>`, `<tool_calls>...</tool_calls>`, `<function_calls>...</function_calls>`, and truncated tool-call blocks) and leaked ASCII/full-width model control tokens are stripped, pure silent-token assistant rows (exact `NO_REPLY` / `no_reply`) are omitted, and oversized rows can be replaced with placeholders.
585585
- `chat.message.get` is the additive bounded full-message reader for a single visible transcript entry. Pass `sessionKey`, optional `agentId` when session selection is agent-scoped, and a transcript `messageId` previously surfaced through `chat.history`; the gateway returns the same display-normalized projection without the lightweight history truncation cap when the stored entry is still available and not oversized.
586586
- `chat.toolTitles` returns short purpose titles for tool calls rendered in the Control UI (batched, max 24 items with bounded inputs). The feature is opt-in via `gateway.controlUi.toolTitles` (default off); disabled gateways answer `{ titles: {}, disabled: true }` with no model call so clients stop asking. When enabled, titles use standard utility-model routing: an explicitly configured `utilityModel` (an operator decision that, like all utility tasks, may send bounded task content to the chosen provider), else the session provider's declared small-model default so no new egress destination appears implicitly; an empty `utilityModel` disables them entirely. Titles never fall back to the primary model. Results cache in the per-agent state database keyed by tool name + input, so repeated views never re-bill the same calls.
587-
- `chat.send` accepts one-turn `fastMode: "auto"` to use fast mode for model calls started before the auto cutoff, then start later retry, fallback, tool-result, or continuation calls without fast mode. The cutoff defaults to 60 seconds (`DEFAULT_FAST_MODE_AUTO_ON_SECONDS`) and can be configured per model with `agents.defaults.models["<provider>/<model>"].params.fastAutoOnSeconds`. A `chat.send` caller can pass one-turn `fastAutoOnSeconds` to override the cutoff for that request. Pass `queueMode` (`steer`, `followup`, `collect`, or `interrupt`) to override the stored queue mode for this request only; explicit Control UI steer actions use `queueMode: "steer"`.
587+
- `chat.send` accepts one-turn `fastMode: "auto"` to use fast mode for model calls started before the auto cutoff, then start later retry, fallback, tool-result, or continuation calls without fast mode. The cutoff defaults to 60 seconds (`DEFAULT_FAST_MODE_AUTO_ON_SECONDS`) and can be configured per model with `agents.defaults.models["<provider>/<model>"].params.fastAutoOnSeconds`. A `chat.send` caller can pass one-turn `fastAutoOnSeconds` to override the cutoff for that request. Pass `queueMode` (`steer`, `followup`, `collect`, or `interrupt`) to override the stored queue mode for this request only; explicit Control UI steer actions use `queueMode: "steer"`. Interactive clients can pass `expectedLeafEntryId` with the active transcript-branch leaf they display, or `null` for an authoritative empty transcript; the Gateway rejects the send with `details.reason: "active-leaf-changed"` if another client switched branches first.
588588

589589
</Accordion>
590590

‎docs/web/webchat.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ Status: the macOS/iOS SwiftUI chat UI talks directly to the Gateway WebSocket. N
2828
- `chat.history` follows the active transcript branch for append-only session files, so abandoned rewrite branches and superseded prompt copies are not rendered in WebChat.
2929
- Compaction entries render as a "Compacted history" divider explaining that the compacted transcript is preserved as a checkpoint, with an action to open session checkpoints (branch or restore, when permissions allow).
3030
- Control UI remembers the backing Gateway `sessionId` returned by `chat.history` and includes it on follow-up `chat.send` calls, so reconnects and page refreshes continue the same stored conversation unless the user starts or resets a session.
31+
- Foreground sends also include the displayed branch's leaf from the rendered history as `expectedLeafEntryId`; if another client switched branches first, Control UI parks the message for review and refreshes the transcript instead of posting it to the new branch. Reconnect and restored-outbox replays intentionally omit this precondition after reconciling current history.
3132
- `chat.send` takes an idempotency key (Control UI uses the run id); the Gateway dedupes repeated requests that reuse the same key, so retried or duplicate in-flight submits for the same session/message/attachments do not create a second run.
3233
- Replying to a specific message (right-click → Reply) sends the target's transcript id as `replyToId` on `chat.send`. The Gateway resolves that message from session history and hydrates the same channel-agnostic reply context metadata Discord replies use: agents see `has_reply_context` plus the untrusted "Reply target of current user message" block with sender label and body. (Webchat prompts keep volatile conversation ids such as `reply_to_id` suppressed, per the existing byte-stable prompt policy for direct webchat sessions.) Reply targets without a persisted transcript id (for example pending sends) fall back to an inline quote in the message body.
3334
- Workspace startup files and pending `BOOTSTRAP.md` instructions are supplied through the agent system prompt's `# Project Context` section, not copied into the WebChat user message. If bootstrap content is truncated, the system prompt gets a short "Bootstrap Context Notice" instead; detailed counts and config knobs stay on diagnostic surfaces.

‎packages/gateway-protocol/src/schema/logs-chat.test.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Gateway Protocol tests cover typed chat stream events.
22
import { Value } from "typebox/value";
33
import { describe, expect, it } from "vitest";
4-
import { ChatEventSchema, ChatStatusEventSchema } from "./logs-chat.js";
4+
import { ChatEventSchema, ChatSendParamsSchema, ChatStatusEventSchema } from "./logs-chat.js";
55

66
const statusEvent = {
77
runId: "run-1",
@@ -22,3 +22,19 @@ describe("ChatStatusEventSchema", () => {
2222
expect(Value.Check(ChatStatusEventSchema, { ...statusEvent, detail: "Loading" })).toBe(false);
2323
});
2424
});
25+
26+
describe("ChatSendParamsSchema", () => {
27+
const send = {
28+
sessionKey: "agent:main:main",
29+
message: "hello",
30+
idempotencyKey: "run-1",
31+
};
32+
33+
it("accepts an expected active leaf while remaining closed", () => {
34+
expect(Value.Check(ChatSendParamsSchema, { ...send, expectedLeafEntryId: "leaf-1" })).toBe(
35+
true,
36+
);
37+
expect(Value.Check(ChatSendParamsSchema, { ...send, expectedLeafEntryId: null })).toBe(true);
38+
expect(Value.Check(ChatSendParamsSchema, { ...send, unknown: true })).toBe(false);
39+
});
40+
});

‎packages/gateway-protocol/src/schema/logs-chat.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,9 @@ export const ChatSendParamsSchema = closedObject({
118118
systemInputProvenance: Type.Optional(InputProvenanceSchema),
119119
systemProvenanceReceipt: Type.Optional(Type.String()),
120120
suppressCommandInterpretation: Type.Optional(Type.Boolean()),
121+
// Client's believed active-branch leaf entry id. A mismatch with the
122+
// session's current active leaf rejects the send so stale views cannot post elsewhere.
123+
expectedLeafEntryId: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
121124
expectedSessionRoutingContract: Type.Optional(NonEmptyString),
122125
idempotencyKey: NonEmptyString,
123126
});

‎packages/gateway-protocol/src/schema/sessions-row.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,19 @@ describe("SessionRowSchema", () => {
77
const row = {
88
key: "agent:main:main",
99
kind: "global",
10+
activeLeafEntryId: "leaf-rendered",
1011
createdActor: { type: "human", id: "profile-ada", label: "Ada" },
1112
archivedBy: { type: "human", id: "profile-bob", label: "Bob" },
1213
visibility: "suggest",
1314
sharingRole: "owner",
1415
};
1516
const roundTripped = structuredClone(row);
1617

18+
expect(SessionRowSchema.properties.activeLeafEntryId).toBeDefined();
1719
expect(Value.Check(SessionRowSchema, roundTripped)).toBe(true);
20+
expect(Value.Check(SessionRowSchema, { ...roundTripped, activeLeafEntryId: null })).toBe(true);
1821
expect(roundTripped).toMatchObject({
22+
activeLeafEntryId: "leaf-rendered",
1923
archivedBy: { type: "human", id: "profile-bob", label: "Bob" },
2024
visibility: "suggest",
2125
sharingRole: "owner",

‎packages/gateway-protocol/src/schema/sessions-row.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ export const SessionRowSchema = Type.Object(
5252
]),
5353
),
5454
lastRunError: Type.Optional(Type.String()),
55+
activeLeafEntryId: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
5556
spawnedBy: Type.Optional(Type.String()),
5657
parentSessionKey: Type.Optional(Type.String()),
5758
controlOwnerSessionKey: Type.Optional(Type.String()),

‎src/config/sessions/session-accessor.message-cut.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import {
22
forkSqliteSessionAtMessage,
33
listSqliteSessionBranches,
4+
resolveSessionTranscriptActiveLeafEntryId as resolveSqliteSessionTranscriptActiveLeafEntryId,
45
rewindSqliteSessionToMessage,
56
switchSqliteSessionBranch,
67
} from "./session-accessor.sqlite.js";
8+
import type { TranscriptEvent } from "./session-accessor.types.js";
79
import type {
810
SessionBranchListParams,
911
SessionBranchListResult,
@@ -19,6 +21,12 @@ export async function listSessionBranches(
1921
return await listSqliteSessionBranches(params);
2022
}
2123

24+
export function resolveSessionTranscriptActiveLeafEntryId(
25+
events: readonly TranscriptEvent[],
26+
): string | undefined {
27+
return resolveSqliteSessionTranscriptActiveLeafEntryId(events);
28+
}
29+
2230
export async function rewindSessionToMessage(
2331
params: SessionMessageCutMutationParams,
2432
): Promise<SessionMessageCutMutationResult> {

‎src/config/sessions/session-accessor.sqlite-active-events.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db
1111
import { appendTranscriptEvent, persistSessionTranscriptTurn } from "./session-accessor.js";
1212
import {
1313
readRecentSessionTranscriptMessageEvents,
14+
readSessionTranscriptActiveLeafEvents,
1415
readSessionTranscriptMessageAnchorPage,
1516
readSessionTranscriptMessageEventById,
1617
readSessionTranscriptMessageEventCount,
@@ -109,6 +110,9 @@ describe("SQLite active transcript event projection", () => {
109110
"root",
110111
"active",
111112
]);
113+
expect(readSessionTranscriptActiveLeafEvents(scope)).toEqual([
114+
expect.objectContaining({ id: "active" }),
115+
]);
112116
expect(page.events.map((entry) => entry.seq)).toEqual([1, 2]);
113117
expect(page.totalMessages).toBe(2);
114118
expect(
@@ -287,6 +291,16 @@ describe("SQLite active transcript event projection", () => {
287291
firstKeptEntryId: "old",
288292
tokensBefore: 10,
289293
});
294+
expect(
295+
readRecentSessionTranscriptMessageEvents(scope, {
296+
maxBytes: 1_024,
297+
maxLines: 1,
298+
maxMessages: 1,
299+
}).activeLeafEntryId,
300+
).toBe("newer-compaction");
301+
expect(readSessionTranscriptActiveLeafEvents(scope)).toEqual([
302+
expect.objectContaining({ id: "newer-compaction" }),
303+
]);
290304
expect(readSessionTranscriptMessageEventCount(scope)).toBe(5);
291305
expect(readSessionTranscriptMessageEventById(scope, "old")).toBeDefined();
292306
});

‎src/config/sessions/session-accessor.sqlite-active-events.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ export type SessionTranscriptMessageEvent = {
5959
};
6060

6161
export type SessionTranscriptMessageEventPage = {
62+
activeLeafEntryId?: string | null;
6263
events: SessionTranscriptMessageEvent[];
6364
totalMessages: number;
6465
};
@@ -271,6 +272,37 @@ export function readSessionTranscriptMessageEvents(
271272
});
272273
}
273274

275+
/** Reads the projected active leaf without materializing the transcript. */
276+
export function readSessionTranscriptActiveLeafEvents(
277+
scope: SessionTranscriptReadScope,
278+
): TranscriptEvent[] {
279+
return withCurrentProjectionSnapshot(scope, (projection) => {
280+
const leafEventId = projection.state.leafEventId;
281+
if (!leafEventId) {
282+
return [];
283+
}
284+
const db = getActiveTranscriptKysely(projection.database);
285+
const row = executeSqliteQueryTakeFirstSync(
286+
projection.database.db,
287+
db
288+
.selectFrom("transcript_event_identities as identity")
289+
.innerJoin("transcript_events as event", (join) =>
290+
join
291+
.onRef("event.session_id", "=", "identity.session_id")
292+
.onRef("event.seq", "=", "identity.seq"),
293+
)
294+
.select("event.event_json")
295+
.where("identity.session_id", "=", projection.resolved.sessionId)
296+
.where("identity.event_id", "=", leafEventId)
297+
.limit(1),
298+
);
299+
if (!row) {
300+
throw new Error(`Active transcript leaf event is missing: ${leafEventId}`);
301+
}
302+
return [JSON.parse(row.event_json) as TranscriptEvent];
303+
});
304+
}
305+
274306
/** Reads one append-stable forward page from the materialized active-message projection. */
275307
export function readSessionTranscriptVisibleMessageDelta(
276308
scope: SessionTranscriptReadScope,
@@ -452,7 +484,11 @@ export function readRecentSessionTranscriptMessageEvents(
452484
Math.floor(Number.isFinite(options.maxLines) ? options.maxLines : 0),
453485
);
454486
if (maxMessages === 0 || maxLines === 0) {
455-
return { events: [], totalMessages: visible.total };
487+
return {
488+
activeLeafEntryId: projection.state.leafEventId,
489+
events: [],
490+
totalMessages: visible.total,
491+
};
456492
}
457493
const maxBytes = Math.max(
458494
1024,
@@ -477,6 +513,7 @@ export function readRecentSessionTranscriptMessageEvents(
477513
bytes += eventBytes;
478514
}
479515
return {
516+
activeLeafEntryId: projection.state.leafEventId,
480517
events: selected.toReversed(),
481518
totalMessages: visible.total,
482519
};
@@ -502,6 +539,7 @@ export function readSessionTranscriptMessageEventPage(
502539
const endExclusive = Math.max(0, totalMessages - offset);
503540
const start = Math.max(0, endExclusive - maxMessages);
504541
return {
542+
activeLeafEntryId: projection.state.leafEventId,
505543
events: readVisibleMessageRange(projection, start, endExclusive),
506544
totalMessages,
507545
};

0 commit comments

Comments
 (0)