Skip to content

Commit 079a874

Browse files
authored
feat: revalidate cached chat history with cursor deltas (#125606)
* feat(gateway): add cursor catch-up to chat history * feat(ui): revalidate cached transcripts via history cursor * fix(ui): stop append-miss stubs clobbering persisted snapshots * fix(gateway): fence history delta cursor to projected events * fix: repair cursor delta landing gates
1 parent cb5e1d2 commit 079a874

31 files changed

Lines changed: 1838 additions & 242 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19569,6 +19569,7 @@ public struct DevicePairSetupDeliveryUncertainEvent: Codable, Sendable {
1956919569
public struct ChatHistoryParams: Codable, Sendable {
1957019570
public let sessionkey: String
1957119571
public let agentid: String?
19572+
public let cursor: String?
1957219573
public let limit: Int?
1957319574
public let offset: Int?
1957419575
public let messageid: String?
@@ -19578,6 +19579,7 @@ public struct ChatHistoryParams: Codable, Sendable {
1957819579
public init(
1957919580
sessionkey: String,
1958019581
agentid: String? = nil,
19582+
cursor: String? = nil,
1958119583
limit: Int? = nil,
1958219584
offset: Int? = nil,
1958319585
messageid: String? = nil,
@@ -19586,6 +19588,7 @@ public struct ChatHistoryParams: Codable, Sendable {
1958619588
{
1958719589
self.sessionkey = sessionkey
1958819590
self.agentid = agentid
19591+
self.cursor = cursor
1958919592
self.limit = limit
1959019593
self.offset = offset
1959119594
self.messageid = messageid
@@ -19596,6 +19599,7 @@ public struct ChatHistoryParams: Codable, Sendable {
1959619599
private enum CodingKeys: String, CodingKey {
1959719600
case sessionkey = "sessionKey"
1959819601
case agentid = "agentId"
19602+
case cursor
1959919603
case limit
1960019604
case offset
1960119605
case messageid = "messageId"
@@ -19604,6 +19608,54 @@ public struct ChatHistoryParams: Codable, Sendable {
1960419608
}
1960519609
}
1960619610

19611+
public struct ChatHistoryDeltaResult: Codable, Sendable {
19612+
public let kind: String
19613+
public let messages: [AnyCodable]
19614+
public let deltacursor: String
19615+
public let sessioninfo: AnyCodable
19616+
public let agentslist: AnyCodable?
19617+
public let metadata: AnyCodable?
19618+
19619+
public init(
19620+
kind: String,
19621+
messages: [AnyCodable],
19622+
deltacursor: String,
19623+
sessioninfo: AnyCodable,
19624+
agentslist: AnyCodable? = nil,
19625+
metadata: AnyCodable? = nil)
19626+
{
19627+
self.kind = kind
19628+
self.messages = messages
19629+
self.deltacursor = deltacursor
19630+
self.sessioninfo = sessioninfo
19631+
self.agentslist = agentslist
19632+
self.metadata = metadata
19633+
}
19634+
19635+
private enum CodingKeys: String, CodingKey {
19636+
case kind
19637+
case messages
19638+
case deltacursor = "deltaCursor"
19639+
case sessioninfo = "sessionInfo"
19640+
case agentslist = "agentsList"
19641+
case metadata
19642+
}
19643+
}
19644+
19645+
public struct ChatHistoryResetResult: Codable, Sendable {
19646+
public let kind: String
19647+
19648+
public init(
19649+
kind: String)
19650+
{
19651+
self.kind = kind
19652+
}
19653+
19654+
private enum CodingKeys: String, CodingKey {
19655+
case kind
19656+
}
19657+
}
19658+
1960719659
public struct ChatMetadataParams: Codable, Sendable {
1960819660
public let agentid: String?
1960919661

@@ -21387,6 +21439,37 @@ public enum ScopeUpgradeResult: Codable, Sendable {
2138721439
}
2138821440
}
2138921441

21442+
public enum ChatHistoryCursorResult: Codable, Sendable {
21443+
case delta(ChatHistoryDeltaResult)
21444+
case reset(ChatHistoryResetResult)
21445+
21446+
private enum CodingKeys: String, CodingKey {
21447+
case discriminator = "kind"
21448+
}
21449+
21450+
public init(from decoder: Decoder) throws {
21451+
let container = try decoder.container(keyedBy: CodingKeys.self)
21452+
let discriminator = try container.decode(String.self, forKey: .discriminator)
21453+
switch discriminator {
21454+
case "delta": self = try .delta(ChatHistoryDeltaResult(from: decoder))
21455+
case "reset": self = try .reset(ChatHistoryResetResult(from: decoder))
21456+
default:
21457+
throw DecodingError.dataCorruptedError(
21458+
forKey: .discriminator,
21459+
in: container,
21460+
debugDescription: "Unknown ChatHistoryCursorResult discriminator value"
21461+
)
21462+
}
21463+
}
21464+
21465+
public func encode(to encoder: Encoder) throws {
21466+
switch self {
21467+
case .delta(let value): try value.encode(to: encoder)
21468+
case .reset(let value): try value.encode(to: encoder)
21469+
}
21470+
}
21471+
}
21472+
2139021473
public enum ChatEvent: Codable, Sendable {
2139121474
case status(ChatStatusEvent)
2139221475
case delta(ChatDeltaEvent)

‎config/assertion-safety-baseline.txt‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2761,7 +2761,7 @@ src/config/sessions/session-accessor.sqlite-archive.ts 3
27612761
src/config/sessions/session-accessor.sqlite-archive.worker.ts 7
27622762
src/config/sessions/session-accessor.sqlite-canonical-inventory.ts 1
27632763
src/config/sessions/session-accessor.sqlite-checkpoint.ts 3
2764-
src/config/sessions/session-accessor.sqlite-delta.ts 3
2764+
src/config/sessions/session-accessor.sqlite-delta.ts 2
27652765
src/config/sessions/session-accessor.sqlite-entry-availability.ts 1
27662766
src/config/sessions/session-accessor.sqlite-entry-cache.ts 3
27672767
src/config/sessions/session-accessor.sqlite-entry.ts 1
@@ -3081,7 +3081,7 @@ src/gateway/server-resident-registry.ts 1
30813081
src/gateway/server-restart-sentinel-agent-delivery.ts 3
30823082
src/gateway/server-runtime-handles.ts 11
30833083
src/gateway/server-runtime-state-prepare.ts 2
3084-
src/gateway/server-session-events.ts 4
3084+
src/gateway/server-session-events.ts 1
30853085
src/gateway/server-startup-bootstrap.ts 1
30863086
src/gateway/server-startup-config-helpers.ts 1
30873087
src/gateway/server-startup-config.ts 1
@@ -4168,7 +4168,7 @@ ui/src/pages/chat/chat-command-executor.ts 1
41684168
ui/src/pages/chat/chat-composer-capability-host.ts 4
41694169
ui/src/pages/chat/chat-gateway.ts 2
41704170
ui/src/pages/chat/chat-history-retry.ts 1
4171-
ui/src/pages/chat/chat-history.ts 6
4171+
ui/src/pages/chat/chat-history.ts 5
41724172
ui/src/pages/chat/chat-page-retained-sessions.ts 1
41734173
ui/src/pages/chat/chat-page.ts 1
41744174
ui/src/pages/chat/chat-pane-board.ts 2
@@ -4184,7 +4184,7 @@ ui/src/pages/chat/chat-send-composer.ts 1
41844184
ui/src/pages/chat/chat-send-request.ts 1
41854185
ui/src/pages/chat/chat-send-timing.ts 6
41864186
ui/src/pages/chat/chat-session-companion.ts 5
4187-
ui/src/pages/chat/chat-state-events.ts 8
4187+
ui/src/pages/chat/chat-state-events.ts 6
41884188
ui/src/pages/chat/chat-state-page.ts 5
41894189
ui/src/pages/chat/chat-state-route.ts 1
41904190
ui/src/pages/chat/chat-thread-build.ts 2

‎docs/gateway/protocol.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,6 +660,7 @@ methods. Treat this as feature discovery, not a full enumeration of
660660
- `sessions.reset`, `sessions.delete`, and `sessions.compact` perform session maintenance.
661661
- `sessions.get` returns the full stored session row.
662662
- 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.
663+
Tail responses can include an opaque `deltaCursor`. Pass it back as `cursor` to `chat.history` or `chat.startup` instead of `offset` or `messageId`. A successful catch-up returns `{ kind: "delta", messages, deltaCursor, sessionInfo }`; replay each `messages` entry through the same reducer as a live `session.message` payload. `{ kind: "reset" }` means the cursor is invalid, stale, belongs to another session, crossed a reset or compaction, or is too far behind; fetch a normal tail page. Catch-up never returns a partial page or continuation: more than 200 raw events or the 1 MB payload budget resets to a tail fetch.
663664
- `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.
664665
- `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.
665666
- `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"`. Modern clients, especially clients that persist or retry a steer, should also pass the active `expectedRunId`; the Gateway binds it to one exact run so a retry cannot reach a successor. Older targetless `queueMode: "steer"` requests remain accepted only as a leaf-bound compatibility path: they must pass the active operation's immutable `expectedLeafEntryId` (or deliberate `null` for an authoritative empty transcript), and can reject with `details.reason: "active-leaf-changed"` when the leaf, owner, freshness, or injection capability cannot be proven. Other interactive sends may pass `expectedLeafEntryId` to reject if another client switched transcript branches first.

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Value } from "typebox/value";
33
import { describe, expect, it } from "vitest";
44
import {
55
ChatEventSchema,
6+
ChatHistoryCursorResultSchema,
67
ChatHistoryParamsSchema,
78
ChatSendParamsSchema,
89
ChatStatusEventSchema,
@@ -22,6 +23,24 @@ describe("ChatHistoryParamsSchema", () => {
2223

2324
expect(Value.Check(ChatHistoryParamsSchema, { ...request, limit: 1000 })).toBe(true);
2425
expect(Value.Check(ChatHistoryParamsSchema, { ...request, limit: 1001 })).toBe(false);
26+
expect(Value.Check(ChatHistoryParamsSchema, { ...request, cursor: "" })).toBe(true);
27+
});
28+
});
29+
30+
describe("ChatHistoryCursorResultSchema", () => {
31+
const sessionInfo = { key: "agent:main:main" };
32+
33+
it("accepts only the closed delta and reset outcomes", () => {
34+
const delta = {
35+
kind: "delta",
36+
messages: [],
37+
deltaCursor: "cursor-2",
38+
sessionInfo,
39+
};
40+
expect(Value.Check(ChatHistoryCursorResultSchema, delta)).toBe(true);
41+
expect(Value.Check(ChatHistoryCursorResultSchema, { kind: "reset" })).toBe(true);
42+
expect(Value.Check(ChatHistoryCursorResultSchema, { ...delta, extra: true })).toBe(false);
43+
expect(Value.Check(ChatHistoryCursorResultSchema, { kind: "reset", messages: [] })).toBe(false);
2544
});
2645
});
2746

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,39 @@ export const LogsTailResultSchema = closedObject({
2626
export const ChatHistoryParamsSchema = closedObject({
2727
sessionKey: NonEmptyString,
2828
agentId: Type.Optional(NonEmptyString),
29+
cursor: Type.Optional(Type.String()),
2930
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: CHAT_HISTORY_MAX_ENTRIES })),
3031
offset: Type.Optional(Type.Integer({ minimum: 0 })),
3132
messageId: Type.Optional(NonEmptyString),
3233
sessionId: Type.Optional(NonEmptyString),
3334
maxChars: Type.Optional(Type.Integer({ minimum: 1, maximum: 500_000 })),
3435
});
3536

37+
/**
38+
* Bounded forward catch-up response. Clients replay `messages` as `session.message`
39+
* payloads. There is no continuation loop: more than 200 raw events or the byte
40+
* budget returns `reset`, and the client fetches a fresh tail page.
41+
*/
42+
export const ChatHistoryDeltaResultSchema = closedObject({
43+
kind: Type.Literal("delta"),
44+
messages: Type.Array(Type.Unknown()),
45+
deltaCursor: Type.String(),
46+
sessionInfo: Type.Unknown(),
47+
agentsList: Type.Optional(Type.Unknown()),
48+
metadata: Type.Optional(Type.Unknown()),
49+
});
50+
51+
/** Normal cursor discontinuity; clients recover with a fresh tail request. */
52+
export const ChatHistoryResetResultSchema = closedObject({
53+
kind: Type.Literal("reset"),
54+
});
55+
56+
/** Closed cursor outcome union. */
57+
export const ChatHistoryCursorResultSchema = Type.Union([
58+
ChatHistoryDeltaResultSchema,
59+
ChatHistoryResetResultSchema,
60+
]);
61+
3662
/** Lightweight chat metadata request; optional agent scope keeps selector state explicit. */
3763
export const ChatMetadataParamsSchema = closedObject({
3864
agentId: Type.Optional(NonEmptyString),

‎packages/gateway-protocol/src/schema/protocol-schema-fragment-plugins-lifecycle.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ export const PluginLifecycleProtocolSchemas = {
5959
DevicePairSetupCompletedEvent: devices.DevicePairSetupCompletedEventSchema,
6060
DevicePairSetupDeliveryUncertainEvent: devices.DevicePairSetupDeliveryUncertainEventSchema,
6161
ChatHistoryParams: logsChat.ChatHistoryParamsSchema,
62+
ChatHistoryDeltaResult: logsChat.ChatHistoryDeltaResultSchema,
63+
ChatHistoryResetResult: logsChat.ChatHistoryResetResultSchema,
64+
ChatHistoryCursorResult: logsChat.ChatHistoryCursorResultSchema,
6265
ChatMetadataParams: logsChat.ChatMetadataParamsSchema,
6366
ChatMessageGetParams: logsChat.ChatMessageGetParamsSchema,
6467
ChatMessageGetResult: logsChat.ChatMessageGetResultSchema,

‎src/agents/agent-bundle-mcp-runtime.test.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ async function writeListToolsMcpServer(params: {
103103
hangToolCallsUntilRestartMarkerPath?: string;
104104
notifyListChangedOnInitialized?: boolean;
105105
notifyListChangedAfterFirstList?: boolean;
106+
notifyListChangedReleasePath?: string;
106107
notifyListChangedBeforeEveryListResponse?: boolean;
107108
exitOnListCall?: number;
108109
listToolsMethodNotFound?: boolean;
@@ -140,6 +141,7 @@ const hangToolCallsUntilRestartMarkerPath = ${JSON.stringify(
140141
)};
141142
const notifyListChangedOnInitialized = ${params.notifyListChangedOnInitialized === true};
142143
const notifyListChangedAfterFirstList = ${params.notifyListChangedAfterFirstList === true};
144+
const notifyListChangedReleasePath = ${JSON.stringify(params.notifyListChangedReleasePath)};
143145
const notifyListChangedBeforeEveryListResponse = ${params.notifyListChangedBeforeEveryListResponse === true};
144146
const exitOnListCall = ${params.exitOnListCall ?? 0};
145147
const listToolsMethodNotFound = ${params.listToolsMethodNotFound === true};
@@ -278,8 +280,20 @@ function handle(message) {
278280
},
279281
});
280282
if (notifyListChangedAfterFirstList && currentListCount === 1) {
281-
log("notify tools/list_changed");
282-
send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
283+
void (async () => {
284+
while (notifyListChangedReleasePath) {
285+
const released = await fs
286+
.access(notifyListChangedReleasePath)
287+
.then(() => true)
288+
.catch(() => false);
289+
if (released) {
290+
break;
291+
}
292+
await new Promise((resolve) => setTimeout(resolve, 10));
293+
}
294+
log("notify tools/list_changed");
295+
send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
296+
})();
283297
}
284298
};
285299
void (async () => {
@@ -1794,11 +1808,13 @@ process.on("SIGINT", shutdown);`,
17941808
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "bundle-mcp-refresh-exit-"));
17951809
const serverPath = path.join(tempDir, "server.mjs");
17961810
const logPath = path.join(tempDir, "server.log");
1811+
const notifyReleasePath = path.join(tempDir, "notify.release");
17971812
await writeListToolsMcpServer({
17981813
filePath: serverPath,
17991814
logPath,
18001815
capabilities: { tools: { listChanged: true } },
18011816
notifyListChangedAfterFirstList: true,
1817+
notifyListChangedReleasePath: notifyReleasePath,
18021818
exitOnListCall: 2,
18031819
});
18041820

@@ -1817,6 +1833,7 @@ process.on("SIGINT", shutdown);`,
18171833

18181834
try {
18191835
expect((await runtime.getCatalog()).tools).toHaveLength(1);
1836+
await fs.writeFile(notifyReleasePath, "release", "utf8");
18201837
await waitForFileText(logPath, "notify tools/list_changed", LIST_TOOLS_SERVER_LOG_TIMEOUT_MS);
18211838
await waitForPredicate(
18221839
() => runtime.peekCatalog() === null,

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export type SessionTranscriptMessageEvent = {
4747

4848
export type SessionTranscriptMessageEventPage = {
4949
activeLeafEntryId?: string | null;
50+
deltaCursor?: string;
5051
events: SessionTranscriptMessageEvent[];
5152
totalMessages: number;
5253
};

0 commit comments

Comments
 (0)