Skip to content

Commit 569b767

Browse files
committed
perf(history): reuse prepared display and session facts
1 parent 48b0857 commit 569b767

22 files changed

Lines changed: 382 additions & 257 deletions

‎src/chat/transcript-display-position.ts‎

Lines changed: 68 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ export type TranscriptDisplayPosition = z.infer<typeof positionSchema>;
2525
export function readTranscriptDisplayPosition(
2626
value: unknown,
2727
): TranscriptDisplayPosition | undefined {
28+
if (!asOptionalRecord(value)) {
29+
return undefined;
30+
}
2831
const parsed = positionSchema.safeParse(value);
2932
return parsed.success ? parsed.data : undefined;
3033
}
@@ -34,71 +37,86 @@ export function composeTranscriptDisplay<T>(
3437
values: T[],
3538
messageFor: (value: T) => unknown = (value) => value,
3639
): T[] {
37-
type Row = { value: T; position: TranscriptDisplayPosition };
3840
const output: T[] = [];
39-
let segment: Row[] = [];
41+
let start = 0;
42+
let positions: TranscriptDisplayPosition[] = [];
43+
let activities: number[] = [];
44+
let previousStableSeq: number | undefined;
45+
let monotonic = true;
4046
const flush = () => {
41-
const rows = segment;
42-
segment = [];
43-
const stable = rows.filter((row) => !row.position.activity);
44-
const monotonic = stable.every((row, index) => {
45-
const previous = stable[index - 1];
46-
return !previous || previous.position.rawSeq <= row.position.rawSeq;
47-
});
48-
const activities = rows.flatMap((row) =>
49-
row.position.activity ? [{ ...row, activity: row.position.activity }] : [],
50-
);
51-
if (!monotonic || activities.length === 0) {
52-
for (const row of rows) {
53-
output.push(row.value);
54-
}
47+
if (positions.length === 0) {
48+
return;
49+
}
50+
const current = positions;
51+
const activityIndexes = activities;
52+
const recompose = monotonic && activityIndexes.length > 0;
53+
positions = [];
54+
activities = [];
55+
previousStableSeq = undefined;
56+
monotonic = true;
57+
if (!recompose) {
5558
return;
5659
}
57-
const ordered = activities.toSorted((left, right) => {
58-
const a = left.activity.afterRawSeq;
59-
const b = right.activity.afterRawSeq;
60+
// Positions index the collected output tail. Detach only segments that need
61+
// recomposition, preserving each value captured by the message selector.
62+
const selected = output.splice(start);
63+
const ordered = activityIndexes.toSorted((left, right) => {
64+
const a = current[left]!.activity!.afterRawSeq;
65+
const b = current[right]!.activity!.afterRawSeq;
6066
if (a === b) {
61-
return left.position.rawSeq - right.position.rawSeq;
67+
return current[left]!.rawSeq - current[right]!.rawSeq;
6268
}
6369
if (a === null) {
6470
return -1;
6571
}
6672
return b === null ? 1 : a - b;
6773
});
68-
const iterator = ordered.values();
69-
let next = iterator.next();
74+
let next = 0;
7075
const emitGap = (beforeRawSeq?: number) => {
71-
const cohorts = new Map<string, { firstSeq: number; rows: typeof activities }>();
72-
while (!next.done) {
73-
const row = next.value;
74-
const afterRawSeq = row.activity.afterRawSeq;
75-
if (beforeRawSeq !== undefined && afterRawSeq !== null && afterRawSeq >= beforeRawSeq) {
76+
let cohorts: Map<string, { firstSeq: number; rows: number[] }> | undefined;
77+
while (next < ordered.length) {
78+
const index = ordered[next]!;
79+
const position = current[index]!;
80+
const activity = position.activity!;
81+
if (
82+
beforeRawSeq !== undefined &&
83+
activity.afterRawSeq !== null &&
84+
activity.afterRawSeq >= beforeRawSeq
85+
) {
7686
break;
7787
}
78-
let cohort = cohorts.get(row.activity.scopeId);
88+
cohorts ??= new Map();
89+
let cohort = cohorts.get(activity.scopeId);
7990
if (!cohort) {
80-
cohort = { firstSeq: row.position.rawSeq, rows: [] };
81-
cohorts.set(row.activity.scopeId, cohort);
91+
cohort = { firstSeq: position.rawSeq, rows: [] };
92+
cohorts.set(activity.scopeId, cohort);
8293
}
83-
cohort.firstSeq = Math.min(cohort.firstSeq, row.position.rawSeq);
84-
cohort.rows.push(row);
85-
next = iterator.next();
94+
cohort.firstSeq = Math.min(cohort.firstSeq, position.rawSeq);
95+
cohort.rows.push(index);
96+
next += 1;
97+
}
98+
if (!cohorts) {
99+
return;
86100
}
87101
// Scope cohorts keep a total order; comparing ordinals only for matching
88102
// scopes inside one comparator would be non-transitive across attempts.
89103
for (const cohort of [...cohorts.values()].toSorted((a, b) => a.firstSeq - b.firstSeq)) {
90104
const sorted = cohort.rows.toSorted(
91105
(a, b) =>
92-
a.activity.startOrder - b.activity.startOrder || a.position.rawSeq - b.position.rawSeq,
106+
current[a]!.activity!.startOrder - current[b]!.activity!.startOrder ||
107+
current[a]!.rawSeq - current[b]!.rawSeq,
93108
);
94-
for (const row of sorted) {
95-
output.push(row.value);
109+
for (const index of sorted) {
110+
output.push(selected[index]!);
96111
}
97112
}
98113
};
99-
for (const row of stable) {
100-
emitGap(row.position.rawSeq);
101-
output.push(row.value);
114+
for (let index = 0; index < current.length; index += 1) {
115+
const position = current[index]!;
116+
if (!position.activity) {
117+
emitGap(position.rawSeq);
118+
output.push(selected[index]!);
119+
}
102120
}
103121
emitGap();
104122
};
@@ -110,12 +128,21 @@ export function composeTranscriptDisplay<T>(
110128
if (!position) {
111129
flush();
112130
output.push(value);
131+
start = output.length;
113132
continue;
114133
}
115-
if (segment.at(-1)?.position.source !== position.source) {
134+
if (positions.at(-1)?.source !== position.source) {
116135
flush();
136+
start = output.length;
137+
}
138+
if (position.activity) {
139+
activities.push(positions.length);
140+
} else {
141+
monotonic &&= previousStableSeq === undefined || previousStableSeq <= position.rawSeq;
142+
previousStableSeq = position.rawSeq;
117143
}
118-
segment.push({ value, position });
144+
positions.push(position);
145+
output.push(value);
119146
}
120147
flush();
121148
return output.every((value, index) => value === values[index]) ? values : output;

‎src/config/sessions/session-accessor.entry.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ export function resolveSessionEntryCandidateTarget(
239239
return {
240240
agentId: resolvedAgentId,
241241
candidateKey,
242-
entry: structuredClone(resolved.existing),
242+
entry: resolved.existing,
243243
persisted: true,
244244
sessionKey: resolved.normalizedKey,
245245
};
@@ -387,11 +387,9 @@ export function listSessionEntriesCore(scope: SessionEntryListScope = {}): Sessi
387387
}
388388

389389
/**
390-
* Borrowed keyed view over one resolved store for synchronous read-only hot paths.
391-
* Unlike loadSessionEntry, `get` is a raw exact persisted-key probe with no alias
392-
* or canonical-key resolution. The first probe materializes one validated store
393-
* snapshot; later probes and `entries` reuse its parsed rows. Rows are borrowed,
394-
* not cloned: callers must not mutate them and must drop the view before any await.
390+
* Synchronous read view: `get` queries one exact persisted key without alias resolution;
391+
* `entries` reuses a validated store snapshot. List rows and their nested values are
392+
* borrowed: callers must not mutate them and must drop the view before any await.
395393
*/
396394
export function openSessionEntryReadView(
397395
scope: Omit<SessionEntryListScope, "clone" | "readConsistency"> = {},

‎src/config/sessions/session-accessor.sqlite-entry-availability.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import {
1313
readExactSessionEntryRowValidated,
1414
} from "./session-accessor.sqlite-entry-store.js";
1515
import {
16-
cloneSessionEntry,
1716
getSessionKysely,
1817
resolveSqliteReadScope,
1918
resolveSqliteScope,
@@ -87,7 +86,7 @@ export function loadExactSessionEntryReadOnlyResult(
8786
found: true,
8887
value: {
8988
sessionKey,
90-
entry: scope.clone === false ? result.value.entry : cloneSessionEntry(result.value.entry),
89+
entry: result.value.entry,
9190
},
9291
};
9392
}

‎src/config/sessions/session-accessor.sqlite-entry-store.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ export type ResolvedSessionEntryRow = {
7575
row: SessionEntryRow;
7676
};
7777

78+
/** Decodes a fresh owned entry, including its nested JSON, owner and participant values. */
7879
export function parseReadableSqliteSessionEntryRow(
7980
database: Pick<OpenClawAgentDatabase, "db">,
8081
row: Pick<SessionEntryRow, "current_session_id" | "entry_json" | "session_key" | "updated_at"> &

‎src/config/sessions/session-accessor.sqlite-entry.ts‎

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,8 @@ export function resolveSessionEntry(
115115
database: Pick<OpenClawAgentDatabase, "agentId" | "db" | "path">,
116116
): ResolvedSqliteSessionEntry => {
117117
const selected = readSessionEntryRow(database, resolved.sessionKey);
118-
const existing = selected?.entry;
119118
return {
120-
existing: existing
121-
? scope.clone === false
122-
? existing
123-
: cloneSessionEntry(existing)
124-
: undefined,
119+
existing: selected?.entry,
125120
legacyKeys: [],
126121
normalizedKey: resolved.sessionKey,
127122
};
@@ -154,9 +149,7 @@ export function loadExactSessionEntry(scope: SessionAccessScope): ExactSessionEn
154149
const resolved = resolveSqliteScope(scope);
155150
const database = openOpenClawAgentDatabase(toDatabaseOptions(resolved));
156151
const entry = readExactSessionEntryRowValidated(database, sessionKey)?.entry;
157-
return entry
158-
? { sessionKey, entry: scope.clone === false ? entry : cloneSessionEntry(entry) }
159-
: undefined;
152+
return entry ? { sessionKey, entry } : undefined;
160153
}
161154

162155
/** Lists persisted session keys without materializing their entry JSON. */
@@ -190,7 +183,7 @@ export function loadExactSessionEntryReadOnly(
190183
return result.found && result.value
191184
? {
192185
sessionKey,
193-
entry: scope.clone === false ? result.value : cloneSessionEntry(result.value),
186+
entry: result.value,
194187
}
195188
: undefined;
196189
}
@@ -220,14 +213,7 @@ export function listSessionChildEntriesReadOnly(scope: SessionAccessScope): Sess
220213
return [];
221214
}
222215
const entry = parseReadableSqliteSessionEntryRow(database, row);
223-
return entry
224-
? [
225-
{
226-
sessionKey: row.session_key,
227-
entry: scope.clone === false ? entry : cloneSessionEntry(entry),
228-
},
229-
]
230-
: [];
216+
return entry ? [{ sessionKey: row.session_key, entry }] : [];
231217
});
232218
}, toDatabaseOptions(resolved));
233219
return result.found ? result.value : [];

‎src/config/sessions/session-accessor.types.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export type ResolvedSessionEntryCandidateTarget = {
111111
agentId: string;
112112
/** Candidate key that selected the result, or the fallback key. */
113113
candidateKey: string;
114-
/** Session metadata cloned from storage or from the synthesized fallback. */
114+
/** Fresh owned session metadata, or a clone of the synthesized fallback. */
115115
entry: SessionEntry;
116116
/** False only for synthesized fallback entries that have not been written. */
117117
persisted: boolean;

‎src/gateway/chat-display-projection.core.ts‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,12 @@ type ChatDisplayProjectionOptions = {
4343
streamErrorFallbackPending?: boolean;
4444
};
4545

46-
function projectCurrentUserProfileAvatars(
47-
messages: Array<Record<string, unknown>>,
48-
resolveDisplay: CurrentUserProfileDisplayResolver | undefined,
49-
): Array<Record<string, unknown>> {
50-
if (!resolveDisplay) {
51-
return messages;
52-
}
46+
/** Keep profile display reads local to one history page or event projection operation. */
47+
export function createCurrentUserProfileMessageProjector(
48+
resolveDisplay: CurrentUserProfileDisplayResolver,
49+
) {
5350
const displayBySenderId = new Map<string, CurrentUserProfileDisplay>();
54-
let changed = false;
55-
const projected = messages.map((message) => {
51+
return (message: Record<string, unknown>): Record<string, unknown> => {
5652
if (message.role !== "user") {
5753
return message;
5854
}
@@ -79,7 +75,6 @@ function projectCurrentUserProfileAvatars(
7975
) {
8076
return message;
8177
}
82-
changed = true;
8378
return {
8479
...message,
8580
__openclaw: {
@@ -88,6 +83,22 @@ function projectCurrentUserProfileAvatars(
8883
senderProfileAvatarUrl: display.avatarUrl,
8984
},
9085
};
86+
};
87+
}
88+
89+
function projectCurrentUserProfileAvatars(
90+
messages: Array<Record<string, unknown>>,
91+
resolveDisplay: CurrentUserProfileDisplayResolver | undefined,
92+
): Array<Record<string, unknown>> {
93+
if (!resolveDisplay) {
94+
return messages;
95+
}
96+
const project = createCurrentUserProfileMessageProjector(resolveDisplay);
97+
let changed = false;
98+
const projected = messages.map((message) => {
99+
const row = project(message);
100+
changed ||= row !== message;
101+
return row;
91102
});
92103
return changed ? projected : messages;
93104
}

‎src/gateway/chat-display-projection.history.ts‎

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -233,14 +233,17 @@ function isDisplayHiddenProjectedMessage(message: Record<string, unknown>): bool
233233
return message.role === "custom" && message.customType === OPENCLAW_RUNTIME_CONTEXT_CUSTOM_TYPE;
234234
}
235235

236-
function shouldHideProjectedHistoryMessage(message: Record<string, unknown>): boolean {
236+
function shouldHideProjectedHistoryMessage(
237+
message: Record<string, unknown>,
238+
roleContent: RoleContentMessage | null,
239+
heartbeatUser: boolean,
240+
): boolean {
237241
if (isDisplayHiddenProjectedMessage(message)) {
238242
return true;
239243
}
240244
if (isProjectedSessionsSendForwardedMessage(message)) {
241245
return false;
242246
}
243-
const roleContent = asRoleContentMessage(message);
244247
if (!roleContent) {
245248
return false;
246249
}
@@ -260,10 +263,7 @@ function shouldHideProjectedHistoryMessage(message: Record<string, unknown>): bo
260263
if (roleContent.role === "assistant" && isEmptyTextOnlyContent(message.content ?? message.text)) {
261264
return false;
262265
}
263-
if (isHeartbeatUserMessage(roleContent, HEARTBEAT_PROMPT)) {
264-
return true;
265-
}
266-
return isHeartbeatOkResponse(roleContent);
266+
return heartbeatUser || isHeartbeatOkResponse(roleContent);
267267
}
268268

269269
/** Identifies the hidden native input that starts a heartbeat-driven turn. */
@@ -386,13 +386,14 @@ export function filterVisibleProjectedHistoryMessages(
386386
continue;
387387
}
388388
const currentRoleContent = asRoleContentMessage(current);
389-
const next = messages[i + 1];
389+
const heartbeatUser = Boolean(
390+
currentRoleContent && isHeartbeatUserMessage(currentRoleContent, HEARTBEAT_PROMPT),
391+
);
392+
const next = heartbeatUser ? messages[i + 1] : undefined;
390393
const nextRoleContent = next ? asRoleContentMessage(next) : null;
391394
if (
392-
currentRoleContent &&
393395
next &&
394396
nextRoleContent &&
395-
isHeartbeatUserMessage(currentRoleContent, HEARTBEAT_PROMPT) &&
396397
isHeartbeatOkResponse(nextRoleContent) &&
397398
!isProjectedSessionsSendForwardedMessage(next)
398399
) {
@@ -401,9 +402,9 @@ export function filterVisibleProjectedHistoryMessages(
401402
i++;
402403
continue;
403404
}
404-
if (shouldHideProjectedHistoryMessage(current)) {
405+
if (shouldHideProjectedHistoryMessage(current, currentRoleContent, heartbeatUser)) {
405406
changed = true;
406-
pendingTurnBoundary ||= isHeartbeatHistoryTurnBoundaryMessage(current);
407+
pendingTurnBoundary ||= heartbeatUser && !isSessionsSendInterSessionUserMessage(current);
407408
continue;
408409
}
409410
if (

‎src/gateway/chat-display-projection.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Public chat display projection facade.
22
export { augmentChatHistoryWithCanvasBlocks } from "./chat-display-projection.canvas.js";
33
export {
4+
createCurrentUserProfileMessageProjector,
45
projectChatDisplayMessage,
56
projectChatDisplayMessages,
67
projectChatDisplayMessagesWithState,

0 commit comments

Comments
 (0)