Skip to content

Commit 7e09412

Browse files
authored
fix(gateway): keep same-sequence history rows reachable (#124145)
* fix(gateway): preserve same-sequence history rows * fix(gateway): close interleaved history groups
1 parent c77ee5b commit 7e09412

3 files changed

Lines changed: 222 additions & 19 deletions

File tree

‎src/gateway/session-history-state.test.ts‎

Lines changed: 55 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -325,26 +325,63 @@ describe("SessionHistorySseState", () => {
325325
).toBe(true);
326326
});
327327

328-
test("keeps cursors when a paginated history page starts with a message-tool mirror", () => {
329-
const snapshot = buildSessionHistorySnapshot({
330-
rawMessages: [
331-
userTextMessage("reply here", 1),
332-
{
333-
role: "assistant",
334-
content: [messageToolCall("call-message-cursor", "Cursor-visible reply.")],
335-
__openclaw: { seq: 2 },
336-
},
337-
messageToolResult("call-message-cursor", "cursor", 3),
338-
assistantTextMessage("NO_REPLY", 4),
339-
],
328+
test("keeps same-sequence projected rows reachable across cursor pages", () => {
329+
const rawMessages = [
330+
userTextMessage("send both here", 1),
331+
{
332+
role: "assistant" as const,
333+
content: [
334+
messageToolCall("call-message-first", "First visible reply."),
335+
messageToolCall("call-message-second", "Second visible reply."),
336+
],
337+
__openclaw: { seq: 2 },
338+
},
339+
messageToolResult("call-message-first", "first", 3),
340+
messageToolResult("call-message-second", "second", 4),
341+
assistantTextMessage("NO_REPLY", 5),
342+
];
343+
344+
const newest = buildSessionHistorySnapshot({ rawMessages, limit: 1 }).history;
345+
expect(newest.messages).toMatchObject([
346+
{ role: "toolResult", toolCallId: "call-message-first", __openclaw: { seq: 3 } },
347+
{ role: "toolResult", toolCallId: "call-message-second", __openclaw: { seq: 4 } },
348+
{
349+
role: "assistant",
350+
content: [{ text: "First visible reply." }],
351+
openclawMessageToolMirror: { toolCallId: "call-message-first" },
352+
__openclaw: { seq: 3 },
353+
},
354+
{
355+
role: "assistant",
356+
content: [{ text: "Second visible reply." }],
357+
openclawMessageToolMirror: { toolCallId: "call-message-second" },
358+
__openclaw: { seq: 4 },
359+
},
360+
]);
361+
expect(newest.nextCursor).toBe("3");
362+
363+
const middle = buildSessionHistorySnapshot({
364+
rawMessages,
340365
limit: 1,
341-
});
366+
cursor: newest.nextCursor,
367+
}).history;
368+
expect(middle.messages).toMatchObject([
369+
{
370+
role: "assistant",
371+
content: [{ id: "call-message-first" }, { id: "call-message-second" }],
372+
__openclaw: { seq: 2 },
373+
},
374+
]);
375+
expect(middle.nextCursor).toBe("2");
342376

343-
expect(snapshot.history.nextCursor).toBe("3");
344-
expect(snapshot.history.messages[0]?.["__openclaw"]?.seq).toBe(3);
345-
expect(
346-
(snapshot.history.messages[0] as { content?: Array<{ text?: string }> }).content?.[0]?.text,
347-
).toBe("Cursor-visible reply.");
377+
const oldest = buildSessionHistorySnapshot({
378+
rawMessages,
379+
limit: 1,
380+
cursor: middle.nextCursor,
381+
}).history;
382+
expect(oldest.messages).toEqual([userTextMessage("send both here", 1)]);
383+
expect(oldest.hasMore).toBe(false);
384+
expect(oldest.nextCursor).toBeUndefined();
348385
});
349386

350387
test("does not coerce partial cursor values", () => {

‎src/gateway/session-history-state.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,26 @@ function paginateSessionMessages(
145145
endExclusive = messages.length;
146146
}
147147
}
148-
const start = typeof limit === "number" && limit > 0 ? Math.max(0, endExclusive - limit) : 0;
148+
let start = typeof limit === "number" && limit > 0 ? Math.max(0, endExclusive - limit) : 0;
149+
// Projection can interleave several rows from the same transcript records.
150+
// Close the page over their seq groups because the public cursor cannot split one.
151+
const pageSeqs = new Set(
152+
messages.slice(start, endExclusive).map(resolveMessageSeq).filter(Boolean),
153+
);
154+
const gapSeqs = new Set<number>();
155+
for (let index = start - 1; index >= 0; index--) {
156+
const seq = resolveMessageSeq(messages[index]);
157+
if (seq === undefined) {
158+
continue;
159+
}
160+
gapSeqs.add(seq);
161+
if (!pageSeqs.has(seq)) {
162+
continue;
163+
}
164+
start = index;
165+
gapSeqs.forEach((gapSeq) => pageSeqs.add(gapSeq));
166+
gapSeqs.clear();
167+
}
149168
const paginatedMessages = messages.slice(start, endExclusive);
150169
const firstSeq = resolveMessageSeq(paginatedMessages[0]);
151170
return buildPaginatedSessionHistory({

‎src/gateway/sessions-history-http.test.ts‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,20 @@ type SessionHistoryBody = {
297297
hasMore?: boolean;
298298
};
299299

300+
function sessionHistoryRowIdentity(message: unknown): string {
301+
const record = requireRecord(message, "session history row");
302+
const metadata = requireRecord(record["__openclaw"], "session history row metadata");
303+
const firstContent = Array.isArray(record.content)
304+
? requireRecord(record.content[0], "session history row content")
305+
: undefined;
306+
const label =
307+
(typeof firstContent?.text === "string" ? firstContent.text : undefined) ??
308+
(typeof firstContent?.id === "string" ? firstContent.id : undefined) ??
309+
(typeof record.toolCallId === "string" ? record.toolCallId : "");
310+
const kind = record.openclawMessageToolMirror ? "mirror" : String(record.role);
311+
return `${String(metadata.seq)}:${kind}:${label}`;
312+
}
313+
300314
async function readSessionHistoryBody(
301315
port: number,
302316
sessionKey: string,
@@ -1068,6 +1082,139 @@ describe("session history HTTP endpoints", () => {
10681082
});
10691083
});
10701084

1085+
test("keeps same-sequence SQLite projection rows reachable over REST and SSE", async () => {
1086+
const storePath = await createSessionStoreFile();
1087+
const sessionId = "sess-same-sequence";
1088+
const sessionKey = "agent:main:main";
1089+
const sharedTimestamp = Date.UTC(2026, 7, 15, 9, 30, 0);
1090+
await writeSessionStore({
1091+
entries: { main: { sessionId, updatedAt: sharedTimestamp } },
1092+
storePath,
1093+
});
1094+
await replaceTranscriptEvents({ agentId: AGENT_ID, sessionId, sessionKey, storePath }, [
1095+
{ type: "session", version: 1, id: sessionId },
1096+
{
1097+
id: "history-user",
1098+
message: {
1099+
role: "user",
1100+
content: [{ type: "text", text: "reply here" }],
1101+
timestamp: sharedTimestamp,
1102+
},
1103+
},
1104+
{
1105+
id: "history-tool-call",
1106+
message: {
1107+
...makeTranscriptAssistantMessage({ text: "" }),
1108+
content: [
1109+
{
1110+
type: "toolCall",
1111+
id: "call-message-first",
1112+
name: "message",
1113+
arguments: { action: "send", message: "First visible reply." },
1114+
},
1115+
{
1116+
type: "toolCall",
1117+
id: "call-message-second",
1118+
name: "message",
1119+
arguments: { action: "send", message: "Second visible reply." },
1120+
},
1121+
],
1122+
timestamp: sharedTimestamp,
1123+
},
1124+
},
1125+
{
1126+
id: "history-tool-result-first",
1127+
message: {
1128+
role: "toolResult",
1129+
toolName: "message",
1130+
toolCallId: "call-message-first",
1131+
content: { ok: true, messageId: "same-sequence-first" },
1132+
timestamp: sharedTimestamp,
1133+
},
1134+
},
1135+
{
1136+
id: "history-tool-result-second",
1137+
message: {
1138+
role: "toolResult",
1139+
toolName: "message",
1140+
toolCallId: "call-message-second",
1141+
content: { ok: true, messageId: "same-sequence-second" },
1142+
timestamp: sharedTimestamp,
1143+
},
1144+
},
1145+
{
1146+
id: "history-hidden-control",
1147+
message: {
1148+
...makeTranscriptAssistantMessage({ text: "NO_REPLY" }),
1149+
timestamp: sharedTimestamp,
1150+
},
1151+
},
1152+
]);
1153+
1154+
await withGatewayHarness(async (harness) => {
1155+
const firstPage = await readSessionHistoryBody(harness.port, sessionKey, {
1156+
query: "?limit=1",
1157+
});
1158+
expect(firstPage.messages?.map(sessionHistoryRowIdentity)).toEqual([
1159+
"3:toolResult:call-message-first",
1160+
"4:toolResult:call-message-second",
1161+
"3:mirror:First visible reply.",
1162+
"4:mirror:Second visible reply.",
1163+
]);
1164+
expect(firstPage.hasMore).toBe(true);
1165+
expect(firstPage.nextCursor).toBe("3");
1166+
1167+
const stream = await openSessionHistorySse(harness.port, sessionKey, {
1168+
query: "?limit=1",
1169+
});
1170+
try {
1171+
const event = await readSseEvent(stream.reader, stream.streamState);
1172+
expect(event.event).toBe("history");
1173+
const data = event.data as SessionHistoryBody;
1174+
expect(data.messages?.map(sessionHistoryRowIdentity)).toEqual(
1175+
firstPage.messages?.map(sessionHistoryRowIdentity),
1176+
);
1177+
expect(data).toMatchObject({ hasMore: true, nextCursor: "3" });
1178+
} finally {
1179+
await stream.reader.cancel();
1180+
}
1181+
1182+
const pages: SessionHistoryBody[] = [firstPage];
1183+
const seenCursors = new Set<string>();
1184+
let cursor = firstPage.nextCursor;
1185+
while (cursor) {
1186+
expect(seenCursors.has(cursor)).toBe(false);
1187+
seenCursors.add(cursor);
1188+
const page = await readSessionHistoryBody(harness.port, sessionKey, {
1189+
query: `?limit=1&cursor=${encodeURIComponent(cursor)}`,
1190+
});
1191+
pages.push(page);
1192+
cursor = page.hasMore ? page.nextCursor : undefined;
1193+
}
1194+
1195+
const chronologicalRows = pages.toReversed().flatMap((page) => page.messages ?? []);
1196+
expect(chronologicalRows.map(sessionHistoryRowIdentity)).toEqual([
1197+
"1:user:reply here",
1198+
"2:assistant:call-message-first",
1199+
"3:toolResult:call-message-first",
1200+
"4:toolResult:call-message-second",
1201+
"3:mirror:First visible reply.",
1202+
"4:mirror:Second visible reply.",
1203+
]);
1204+
expect(
1205+
chronologicalRows.map((message) => requireRecord(message, "history timestamp").timestamp),
1206+
).toEqual(Array.from({ length: 6 }, () => sharedTimestamp));
1207+
expect(
1208+
pages
1209+
.flatMap((page) => page.messages ?? [])
1210+
.some((message) => sessionHistoryRowIdentity(message).includes("NO_REPLY")),
1211+
).toBe(false);
1212+
expect(seenCursors).toEqual(new Set(["3", "2"]));
1213+
expect(pages.at(-1)).toMatchObject({ hasMore: false });
1214+
expect(pages.at(-1)?.nextCursor).toBeUndefined();
1215+
});
1216+
});
1217+
10711218
test("keeps older SQLite history reachable past an all-silent bounded tail", async () => {
10721219
const storePath = await createSessionStoreFile();
10731220
const sessionId = "sess-silent-tail";

0 commit comments

Comments
 (0)