Skip to content

Commit 3c2667c

Browse files
authored
fix(gateway): fill older chat pages without duplicate transcript storage (#128810)
* fix(gateway): page visible chat history without duplicate storage * chore: keep release changelog owned by release automation
1 parent 614e084 commit 3c2667c

75 files changed

Lines changed: 980 additions & 8396 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2882,7 +2882,7 @@ src/gateway/chat-attachments.ts 4
28822882
src/gateway/chat-display-projection.canvas.ts 14
28832883
src/gateway/chat-display-projection.core.ts 6
28842884
src/gateway/chat-display-projection.helpers.ts 10
2885-
src/gateway/chat-display-projection.history.ts 2
2885+
src/gateway/chat-display-projection.history.ts 1
28862886
src/gateway/chat-display-projection.sanitize.ts 16
28872887
src/gateway/chat-sanitize.ts 3
28882888
src/gateway/chat-tool-titles.ts 2
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
9c5037d4a08541485a0fb4b6901872ba258832b5e120bcd2cb230df7348c18d8 sqlite-session-transcript-schema-baseline.sql
1+
fecbb8adccfa0be0b452f646d3bee8d5a17faeb2c2d8a2300fb75ef173c709cd sqlite-session-transcript-schema-baseline.sql

‎docs/web/webchat.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ Status: the macOS/iOS SwiftUI chat UI talks directly to the Gateway WebSocket. N
2323
## How it works
2424

2525
- The UI connects to the Gateway WebSocket and uses the `chat.history`, `chat.send`, `chat.inject`, and `chat.message.get` RPC methods.
26-
- `chat.history` is bounded for stability: Gateway may truncate long text fields, omit heavy metadata, and replace oversized entries with `[chat.history omitted: message too large]`. API clients can send a per-request `maxChars` to override the default limit for one call.
26+
- `chat.history` is bounded for stability: Gateway may truncate long text fields, omit heavy metadata, and replace oversized entries with `[chat.history omitted: message too large]`. History pages skip hidden and tool-only transcript entries while filling the requested visible-message window from the existing indexed transcript. API clients can send a per-request `maxChars` to override the default limit for one call.
2727
- When a visible assistant message was truncated in `chat.history`, **Show more** fetches the full display-normalized entry inline through `chat.message.get`, without increasing the default history payload. **Show less** restores the truncated preview and reuses the fetched content on the next expansion. `chat.message.get` uses the same transcript branch and display rules as `chat.history`, but targets one entry by `messageId` and returns an honest unavailable reason when the full content can no longer be returned.
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).

‎scripts/lib/sqlite-session-schema-baseline.ts‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,6 @@ const TARGET_TABLES = new Set([
3838
"transcript_event_identities",
3939
"session_transcript_index_state",
4040
"session_transcript_active_events",
41-
"session_transcript_display_state",
42-
"session_transcript_display_rows",
43-
"session_transcript_display_row_sources",
44-
"session_transcript_display_canvas",
45-
"session_transcript_display_carry",
4641
"session_transcript_archives",
4742
]);
4843

‎src/agents/harness/context-engine-turn-attempt.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ describe("accepted context-engine turn finalization", () => {
355355
if (siblingIdentity?.seq === undefined) {
356356
throw new Error("expected sibling transcript identity");
357357
}
358-
// Model a published malformed projection that assigns a later active position
358+
// Model a stale/concurrent projection that assigns a later active position
359359
// to a sibling. Position order alone must not make it an accepted descendant.
360360
database.db
361361
.prepare(
@@ -369,9 +369,9 @@ describe("accepted context-engine turn finalization", () => {
369369
);
370370
database.db
371371
.prepare(
372-
"UPDATE session_transcript_index_state SET indexed_seq = ?, needs_rebuild = 0, source_generation = ? WHERE session_id = ?",
372+
"UPDATE session_transcript_index_state SET indexed_seq = ?, needs_rebuild = 0 WHERE session_id = ?",
373373
)
374-
.run(siblingIdentity.seq, terminal.anchor.generation, target.sessionId);
374+
.run(siblingIdentity.seq, target.sessionId);
375375
const siblingAnchor = readActiveTranscriptEntryAnchor({
376376
...target,
377377
entryId: sibling.messageId,

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

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ describe("SQLite active transcript event projection", () => {
646646
touchSessionEntry: false,
647647
});
648648
await persistSessionTranscriptTurn(secondScope, {
649-
messages: Array.from({ length: 1_000 }, (_, index) => ({
649+
messages: Array.from({ length: 5_000 }, (_, index) => ({
650650
eventId: `slow-${index}`,
651651
parentId: index === 0 ? null : `slow-${index - 1}`,
652652
message: { role: "toolResult", content: "slow" },
@@ -800,13 +800,7 @@ describe("SQLite active transcript event projection", () => {
800800

801801
it("skips the preparation worker when the projection is already current", async () => {
802802
await persistSessionTranscriptTurn(scope, {
803-
messages: [
804-
{
805-
eventId: "seed",
806-
maintainDisplayProjection: true,
807-
message: { role: "user", content: "seed" },
808-
},
809-
],
803+
messages: [{ eventId: "seed", message: { role: "user", content: "seed" } }],
810804
touchSessionEntry: false,
811805
});
812806
queuedSessionWrite.mockClear();
@@ -959,15 +953,11 @@ describe("SQLite active transcript event projection", () => {
959953
`
960954
INSERT INTO session_transcript_index_state
961955
(session_id, indexed_seq, leaf_event_id, needs_rebuild,
962-
active_event_count, active_message_count, source_generation, updated_at)
963-
VALUES (
964-
?, 100000, 'm100000', 0, 100000, 100000,
965-
(SELECT generation FROM transcript_rewrite_watermarks WHERE session_id = ?),
966-
100000
967-
)
956+
active_event_count, active_message_count, updated_at)
957+
VALUES (?, 100000, 'm100000', 0, 100000, 100000, 100000)
968958
`,
969959
)
970-
.run(scope.sessionId, scope.sessionId);
960+
.run(scope.sessionId);
971961
database.db.exec("COMMIT;");
972962
} catch (error) {
973963
database.db.exec("ROLLBACK;");

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

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import {
55
openOpenClawAgentDatabase,
66
type OpenClawAgentDatabase,
77
} from "../../state/openclaw-agent-db.js";
8-
import { ensureOpenClawAgentTranscriptProjectionSourceColumns } from "../../state/openclaw-agent-transcript-projection-source-schema.js";
98
import type { SessionTranscriptReadScope } from "./session-accessor.sqlite-contract.js";
109
import {
1110
resolveSqliteTranscriptReadScope,
@@ -14,7 +13,6 @@ import {
1413
import type { SessionTranscriptProjectionState } from "./session-transcript-index.js";
1514
import { SessionTranscriptProjectionUnavailableError } from "./session-transcript-projection-error.js";
1615
import { startSessionTranscriptIndexReconcile } from "./session-transcript-reconcile.js";
17-
import { EMPTY_SESSION_TRANSCRIPT_SOURCE_INDEXED_SEQ } from "./session-transcript-source-generation.js";
1816

1917
type ActiveTranscriptDatabase = Pick<
2018
OpenClawAgentKyselyDatabase,
@@ -34,10 +32,9 @@ export type CurrentTranscriptProjection = {
3432
const EMPTY_PROJECTION_STATE: SessionTranscriptProjectionState = {
3533
activeEventCount: 0,
3634
activeMessageCount: 0,
37-
indexedSeq: EMPTY_SESSION_TRANSCRIPT_SOURCE_INDEXED_SEQ,
35+
indexedSeq: -1,
3836
leafEventId: null,
3937
needsRebuild: false,
40-
sourceGeneration: null,
4138
};
4239

4340
export function getActiveTranscriptKysely(database: OpenClawAgentDatabase) {
@@ -48,22 +45,18 @@ function readProjectionSnapshot(
4845
database: OpenClawAgentDatabase,
4946
sessionId: string,
5047
): { latestSeq: number; state?: SessionTranscriptProjectionState } | undefined {
51-
ensureOpenClawAgentTranscriptProjectionSourceColumns(database.db);
5248
const row = executeSqliteQueryTakeFirstSync(
5349
database.db,
5450
getActiveTranscriptKysely(database)
5551
.selectFrom("transcript_events as latest")
5652
.leftJoin("session_transcript_index_state as state", "state.session_id", "latest.session_id")
57-
.leftJoin("transcript_rewrite_watermarks as source", "source.session_id", "latest.session_id")
5853
.select([
5954
"latest.seq as latest_seq",
6055
"state.active_event_count",
6156
"state.active_message_count",
6257
"state.indexed_seq",
6358
"state.leaf_event_id",
6459
"state.needs_rebuild",
65-
"state.source_generation",
66-
"source.generation",
6760
])
6861
.where("latest.session_id", "=", sessionId)
6962
.orderBy("latest.seq", "desc")
@@ -82,8 +75,6 @@ function readProjectionSnapshot(
8275
indexedSeq: row.indexed_seq,
8376
leafEventId: row.leaf_event_id,
8477
needsRebuild: row.needs_rebuild !== 0,
85-
sourceGeneration:
86-
row.source_generation === row.generation ? row.source_generation : null,
8778
},
8879
}
8980
: {}),
@@ -110,8 +101,7 @@ export function withCurrentProjectionSnapshot<T>(
110101
if (
111102
snapshot.state &&
112103
!snapshot.state.needsRebuild &&
113-
snapshot.state.indexedSeq === snapshot.latestSeq &&
114-
snapshot.state.sourceGeneration !== null
104+
snapshot.state.indexedSeq === snapshot.latestSeq
115105
) {
116106
return {
117107
kind: "value" as const,

‎src/config/sessions/session-accessor.sqlite-archive.worker.test.ts‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ import {
3030
import { touchTranscriptMutationInTransaction } from "./session-accessor.sqlite-transcript-state.js";
3131
import { replaceTranscriptEvents } from "./session-accessor.sqlite-transcript-write.js";
3232
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
33-
import { waitForSessionTranscriptIndexReconcile } from "./session-transcript-reconcile.js";
3433

3534
type TestTranscriptEvent = {
3635
id: string;
@@ -46,14 +45,7 @@ describe("SQLite transcript archive worker", () => {
4645
storePath = path.join(tempDir, "agents", "main", "sessions", "sessions.json");
4746
});
4847

49-
afterEach(async () => {
50-
const target = resolveSqliteTargetFromSessionStorePath(storePath);
51-
if (target.path) {
52-
await waitForSessionTranscriptIndexReconcile({
53-
agentId: target.agentId ?? "main",
54-
path: target.path,
55-
});
56-
}
48+
afterEach(() => {
5749
closeOpenClawAgentDatabasesForTest();
5850
fs.rmSync(tempDir, { recursive: true, force: true });
5951
});

‎src/config/sessions/session-accessor.sqlite-canonical-repair.ts‎

Lines changed: 22 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,12 @@ import {
2323
} from "./session-accessor.sqlite-scope.js";
2424
import { bindSessionWindowEntryProjection } from "./session-accessor.sqlite-session-row.js";
2525
import { parseSessionEntryJson } from "./session-accessor.sqlite-status.js";
26+
import { ensureTranscriptGenerationInTransaction } from "./session-accessor.sqlite-transcript-state.js";
2627
import { canonicalSessionKeyMigrationRequiredError } from "./session-canonical-key.js";
27-
import { invalidateExistingSessionTranscriptDisplayInTransaction } from "./session-transcript-display.js";
2828
import {
2929
deleteSessionTranscriptIndexInTransaction,
3030
reconcileSessionTranscriptIndexInTransaction,
3131
} from "./session-transcript-index.js";
32-
import {
33-
startSessionTranscriptDisplayReconcile,
34-
startSessionTranscriptIndexReconcile,
35-
} from "./session-transcript-reconcile.js";
36-
import {
37-
ensureSessionTranscriptSourceGenerationInTransaction,
38-
readSessionTranscriptSourceGenerationInTransaction,
39-
replaceSessionTranscriptSourceGenerationInTransaction,
40-
} from "./session-transcript-source-generation.js";
4132
import { normalizeStoreSessionKey } from "./store-entry.js";
4233
import type { SessionEntry } from "./types.js";
4334

@@ -171,15 +162,16 @@ export async function ensureSqliteTranscriptGenerationsForCanonicalRepair(
171162
),
172163
]);
173164
const db = getSessionKysely(database.db);
174-
const windowSessionIds = executeSqliteQuerySync(
165+
const eventSessionIds = executeSqliteQuerySync(
175166
database.db,
176167
db
177-
.selectFrom("session_windows")
168+
.selectFrom("transcript_events")
178169
.select("session_id")
179-
.where("session_id", "in", sessionIds),
170+
.where("session_id", "in", sessionIds)
171+
.groupBy("session_id"),
180172
).rows;
181-
for (const row of windowSessionIds) {
182-
ensureSessionTranscriptSourceGenerationInTransaction(database, row.session_id);
173+
for (const row of eventSessionIds) {
174+
ensureTranscriptGenerationInTransaction(database, row.session_id);
183175
}
184176
}, toDatabaseOptions(group.resolved));
185177
});
@@ -477,22 +469,9 @@ function copySqliteSessionOwnedStateForRepair(params: {
477469
if (!replaced) {
478470
continue;
479471
}
480-
// Every transcript projection follows the selected canonical source, including replacements
481-
// whose final sequence is unchanged or lower than the destination it supersedes.
482-
const displayProjectionInvalidated = invalidateExistingSessionTranscriptDisplayInTransaction(
483-
params.destination.db,
484-
sessionId,
485-
);
472+
// Search and active-event tables are derived from transcript_events; force their canonical rebuild.
486473
deleteSessionTranscriptIndexInTransaction(params.destination.db, sessionId);
487474
reconcileSessionTranscriptIndexInTransaction(params.destination.db, sessionId);
488-
const startReconcile = displayProjectionInvalidated
489-
? startSessionTranscriptDisplayReconcile
490-
: startSessionTranscriptIndexReconcile;
491-
startReconcile({
492-
agentId: params.destination.agentId,
493-
path: params.destination.path,
494-
preferredSessionId: sessionId,
495-
});
496475
publishSessionEntryCacheInvalidation(params.destination);
497476
}
498477
// Membership is authorization state and follows the selected winner. Boards,
@@ -532,10 +511,13 @@ function copySqliteSessionGenerationRows(params: {
532511
.selectAll()
533512
.where("session_id", "=", params.sessionId),
534513
).rows;
535-
const sourceGeneration = readSessionTranscriptSourceGenerationInTransaction(
514+
const rewriteWatermarks = executeSqliteQuerySync(
536515
params.source.db,
537-
params.sessionId,
538-
);
516+
sourceDb
517+
.selectFrom("transcript_rewrite_watermarks")
518+
.selectAll()
519+
.where("session_id", "=", params.sessionId),
520+
).rows;
539521
const trajectoryEvents = executeSqliteQuerySync(
540522
params.source.db,
541523
sourceDb
@@ -554,18 +536,16 @@ function copySqliteSessionGenerationRows(params: {
554536
!params.sourceWindowPresent &&
555537
transcriptEvents.length === 0 &&
556538
transcriptIdentities.length === 0 &&
557-
sourceGeneration === undefined &&
539+
rewriteWatermarks.length === 0 &&
558540
trajectoryEvents.length === 0 &&
559541
parentStreamEvents.length === 0
560542
) {
561543
return false;
562544
}
563-
if (params.sourceWindowPresent && !sourceGeneration) {
564-
throw new Error(`Canonical transcript source ${params.sessionId} has no generation`);
565-
}
566545
for (const table of [
567546
"transcript_event_identities",
568547
"transcript_events",
548+
"transcript_rewrite_watermarks",
569549
"trajectory_runtime_events",
570550
"acp_parent_stream_events",
571551
] as const) {
@@ -586,7 +566,12 @@ function copySqliteSessionGenerationRows(params: {
586566
destinationDb.insertInto("transcript_event_identities").values(row),
587567
);
588568
}
589-
replaceSessionTranscriptSourceGenerationInTransaction(params.destination, params.sessionId);
569+
for (const row of rewriteWatermarks) {
570+
executeSqliteQuerySync(
571+
params.destination.db,
572+
destinationDb.insertInto("transcript_rewrite_watermarks").values(row),
573+
);
574+
}
590575
for (const row of trajectoryEvents) {
591576
executeSqliteQuerySync(
592577
params.destination.db,

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,6 @@ export type TranscriptMessageAppendOptions<TMessage> = {
131131
message: TMessage;
132132
now?: number;
133133
eventId?: string;
134-
maintainDisplayProjection?: boolean;
135134
parentId?: string | null;
136135
prepareMessageAfterIdempotencyCheck?: (message: TMessage) => TMessage | undefined;
137136
useRawWhenLinear?: boolean;

0 commit comments

Comments
 (0)