Skip to content

Commit 238c797

Browse files
authored
feat(chat): native session scroll-back with offset paging and import-aware history (#105688)
* feat(chat): native session scroll-back with import-aware history paging * fix(chat): page imported session history * fix(chat): restore terminal import snapshots * fix(chat): gate cli import resolver on ignore flag to stop history recursion * fix(chat): correct scroll-back types and drop orphaned recent-messages reader
1 parent e3163d1 commit 238c797

17 files changed

Lines changed: 1495 additions & 129 deletions

‎scripts/deadcode-exports.baseline.mjs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3731,7 +3731,6 @@ export const KNIP_UNUSED_EXPORT_BASELINE = [
37313731
"src/gateway/chat-tool-titles.ts: ToolTitleRequestItem",
37323732
"src/gateway/cli-session-history.ts: mergeImportedChatHistoryMessages",
37333733
"src/gateway/cli-session-history.ts: readClaudeCliSessionMessages",
3734-
"src/gateway/cli-session-history.ts: resolveClaudeCliBindingSessionId",
37353734
"src/gateway/cli-session-history.ts: resolveClaudeCliSessionFilePath",
37363735
"src/gateway/client-bootstrap.ts: resolveGatewayUrlOverrideSource",
37373736
"src/gateway/client-start-readiness.ts: GatewayClientStartable",
@@ -3981,7 +3980,6 @@ export const KNIP_UNUSED_EXPORT_BASELINE = [
39813980
"src/gateway/session-utils.ts: readFirstUserMessageFromTranscript",
39823981
"src/gateway/session-utils.ts: readLatestRecentSessionUsageFromTranscriptAsync",
39833982
"src/gateway/session-utils.ts: readLatestSessionUsageFromTranscriptAsync",
3984-
"src/gateway/session-utils.ts: readRecentSessionMessagesAsync",
39853983
"src/gateway/session-utils.ts: readRecentSessionMessagesWithStatsAsync",
39863984
"src/gateway/session-utils.ts: readRecentSessionTranscriptLines",
39873985
"src/gateway/session-utils.ts: readRecentSessionUsageFromTranscript",

‎src/gateway/cli-session-history.claude.ts‎

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ function resolveClaudeCliPromptTextCandidates(
264264
function parseClaudeCliHistoryEntry(
265265
entry: ClaudeCliProjectEntry,
266266
cliSessionId: string,
267+
sourceLineNumber: number,
267268
toolNameRegistry: ToolNameRegistry,
268269
options: {
269270
reseedMode: "recover" | "preserve";
@@ -280,10 +281,12 @@ function parseClaudeCliHistoryEntry(
280281
}
281282

282283
const timestamp = resolveTimestampMs(entry.timestamp);
284+
const externalId = normalizeOptionalString(entry.uuid);
283285
const baseMeta = {
286+
id: externalId ?? `${CLAUDE_CLI_PROVIDER}:${cliSessionId}:line:${sourceLineNumber}`,
284287
importedFrom: CLAUDE_CLI_PROVIDER,
285288
cliSessionId,
286-
...(normalizeOptionalString(entry.uuid) ? { externalId: entry.uuid } : {}),
289+
...(externalId ? { externalId } : {}),
287290
};
288291

289292
let content =
@@ -449,16 +452,24 @@ export function readClaudeCliSessionMessages(params: {
449452
: undefined,
450453
inspectedFirstUser: false,
451454
};
452-
for (const line of content.split(/\r?\n/)) {
455+
const lines = content.split(/\r?\n/);
456+
for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
457+
const line = lines[lineIndex] ?? "";
453458
if (!line.trim()) {
454459
continue;
455460
}
456461
try {
457462
const parsed = JSON.parse(line) as ClaudeCliProjectEntry;
458-
const message = parseClaudeCliHistoryEntry(parsed, params.cliSessionId, toolNameRegistry, {
459-
reseedMode: "recover",
460-
reseedState,
461-
});
463+
const message = parseClaudeCliHistoryEntry(
464+
parsed,
465+
params.cliSessionId,
466+
lineIndex + 1,
467+
toolNameRegistry,
468+
{
469+
reseedMode: "recover",
470+
reseedState,
471+
},
472+
);
462473
if (message) {
463474
messages.push(message);
464475
}
@@ -535,7 +546,9 @@ export function readClaudeCliFallbackSeed(params: {
535546
let windowedTurns: TranscriptLikeMessage[] = [];
536547
const toolNameRegistry: ToolNameRegistry = new Map();
537548

538-
for (const line of content.split(/\r?\n/)) {
549+
const lines = content.split(/\r?\n/);
550+
for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
551+
const line = lines[lineIndex] ?? "";
539552
if (!line.trim()) {
540553
continue;
541554
}
@@ -563,9 +576,15 @@ export function readClaudeCliFallbackSeed(params: {
563576
continue;
564577
}
565578

566-
const message = parseClaudeCliHistoryEntry(parsed, params.cliSessionId, toolNameRegistry, {
567-
reseedMode: "preserve",
568-
});
579+
const message = parseClaudeCliHistoryEntry(
580+
parsed,
581+
params.cliSessionId,
582+
lineIndex + 1,
583+
toolNameRegistry,
584+
{
585+
reseedMode: "preserve",
586+
},
587+
);
569588
if (message) {
570589
windowedTurns.push(message);
571590
}

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
mergeImportedChatHistoryMessages,
1212
readClaudeCliFallbackSeed,
1313
readClaudeCliSessionMessages,
14+
resolveChatHistoryWithCliSessionImports,
1415
resolveClaudeCliSessionFilePath,
1516
} from "./cli-session-history.js";
1617
import { expectRecordFields, requireRecord } from "./test-helpers.assertions.js";
@@ -183,6 +184,7 @@ describe("cli session history", () => {
183184
});
184185
expect(String(messages[0]?.content)).toContain("[Thu 2026-03-26 16:29 GMT] hi");
185186
expectFields(messages[0]?.["__openclaw"], {
187+
id: "user-1",
186188
importedFrom: "claude-cli",
187189
externalId: "user-1",
188190
cliSessionId: sessionId,
@@ -199,6 +201,7 @@ describe("cli session history", () => {
199201
cacheRead: 22,
200202
});
201203
expectFields(messages[1]?.["__openclaw"], {
204+
id: "assistant-1",
202205
importedFrom: "claude-cli",
203206
externalId: "assistant-1",
204207
cliSessionId: sessionId,
@@ -225,6 +228,27 @@ describe("cli session history", () => {
225228
});
226229
});
227230

231+
it("assigns stable source-line ids when Claude entries have no uuid", async () => {
232+
await withClaudeProjectsDir(async ({ homeDir, sessionId, filePath }) => {
233+
await fs.writeFile(
234+
filePath,
235+
JSON.stringify({
236+
type: "user",
237+
timestamp: "2026-03-26T16:29:54.800Z",
238+
message: { role: "user", content: "stable fallback" },
239+
}),
240+
"utf-8",
241+
);
242+
243+
const importedId = (message: Record<string, unknown> | undefined) =>
244+
(message?.["__openclaw"] as { id?: string } | undefined)?.id;
245+
const first = readClaudeCliSessionMessages({ cliSessionId: sessionId, homeDir });
246+
const second = readClaudeCliSessionMessages({ cliSessionId: sessionId, homeDir });
247+
expect(importedId(first[0])).toBe(`claude-cli:${sessionId}:line:1`);
248+
expect(importedId(second[0])).toBe(importedId(first[0]));
249+
});
250+
});
251+
228252
it("recovers the current user text from legacy reseed envelopes", async () => {
229253
await withClaudeProjectsDir(async ({ homeDir, sessionId, filePath }) => {
230254
const reseedPrompt = buildLegacyReseedPrompt();
@@ -942,6 +966,25 @@ describe("cli session history", () => {
942966
});
943967
});
944968

969+
it("does not mark a fully deduplicated Claude transcript as imported", async () => {
970+
await withClaudeProjectsDir(async ({ homeDir, sessionId }) => {
971+
const localMessages = readClaudeCliSessionMessages({ cliSessionId: sessionId, homeDir });
972+
const result = resolveChatHistoryWithCliSessionImports({
973+
entry: {
974+
sessionId: "openclaw-session",
975+
updatedAt: Date.now(),
976+
cliSessionBindings: { "claude-cli": { sessionId } },
977+
},
978+
provider: "claude-cli",
979+
localMessages,
980+
homeDir,
981+
});
982+
983+
expect(result.imported).toBe(false);
984+
expect(result.messages).toBe(localMessages);
985+
});
986+
});
987+
945988
it("falls back to legacy cliSessionIds when bindings are absent", async () => {
946989
await withClaudeProjectsDir(async ({ homeDir, sessionId }) => {
947990
const messages = augmentChatHistoryWithCliSessionImports({

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

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,22 @@ export {
2424
};
2525
export type { ClaudeCliFallbackSeed };
2626

27-
/** Augments local chat history with bound Claude CLI session messages when applicable. */
28-
export function augmentChatHistoryWithCliSessionImports(params: {
27+
type CliSessionHistoryAugmentation = {
28+
messages: unknown[];
29+
imported: boolean;
30+
};
31+
32+
/** Resolves chat history plus whether a bound external transcript was actually incorporated. */
33+
export function resolveChatHistoryWithCliSessionImports(params: {
2934
entry: SessionEntry | undefined;
3035
provider?: string;
3136
localMessages: unknown[];
3237
homeDir?: string;
33-
}): unknown[] {
38+
}): CliSessionHistoryAugmentation {
3439
const cliSessionBinding = getCliSessionBinding(params.entry, CLAUDE_CLI_PROVIDER);
3540
const cliSessionId = cliSessionBinding?.sessionId;
3641
if (!cliSessionId) {
37-
return params.localMessages;
42+
return { messages: params.localMessages, imported: false };
3843
}
3944

4045
const normalizedProvider = normalizeProviderId(params.provider ?? "");
@@ -44,7 +49,7 @@ export function augmentChatHistoryWithCliSessionImports(params: {
4449
normalizedProvider !== ANTHROPIC_PROVIDER &&
4550
params.localMessages.length > 0
4651
) {
47-
return params.localMessages;
52+
return { messages: params.localMessages, imported: false };
4853
}
4954

5055
const importedMessages = readClaudeCliSessionMessages({
@@ -53,8 +58,21 @@ export function augmentChatHistoryWithCliSessionImports(params: {
5358
localSessionId: params.entry?.sessionId,
5459
reseedReceipt: cliSessionBinding.reseedReceipt,
5560
});
56-
return mergeImportedChatHistoryMessages({
61+
if (importedMessages.length === 0) {
62+
return { messages: params.localMessages, imported: false };
63+
}
64+
const messages = mergeImportedChatHistoryMessages({
5765
localMessages: params.localMessages,
5866
importedMessages,
5967
});
68+
return messages.length > params.localMessages.length
69+
? { messages, imported: true }
70+
: { messages: params.localMessages, imported: false };
71+
}
72+
73+
/** Augments local chat history with bound Claude CLI session messages when applicable. */
74+
export function augmentChatHistoryWithCliSessionImports(
75+
params: Parameters<typeof resolveChatHistoryWithCliSessionImports>[0],
76+
): unknown[] {
77+
return resolveChatHistoryWithCliSessionImports(params).messages;
6078
}

0 commit comments

Comments
 (0)