Skip to content

Commit b2278f6

Browse files
committed
fix(cache): stabilize synthetic tool-result timestamps
1 parent 1d19abb commit b2278f6

6 files changed

Lines changed: 57 additions & 11 deletions

‎src/agents/session-file-repair.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -653,11 +653,12 @@ describe("repairSessionFileIfNeeded", () => {
653653
it("inserts missing code-mode tool results before replay repair has to synthesize them", async () => {
654654
const { file } = await createTempSessionPath();
655655
const { header, message } = buildSessionHeaderAndMessage();
656+
const sourceEntryTimestamp = "2026-06-15T14:16:00.000Z";
656657
const toolCallAssistant = {
657658
type: "message",
658659
id: "msg-asst-process",
659660
parentId: "msg-1",
660-
timestamp: new Date().toISOString(),
661+
timestamp: sourceEntryTimestamp,
661662
message: {
662663
role: "assistant",
663664
provider: "openai",
@@ -707,6 +708,7 @@ describe("repairSessionFileIfNeeded", () => {
707708
expect(inserted.message.toolCallId).toBe("call_process|fc_1");
708709
expect(inserted.message.toolName).toBe("process");
709710
expect(inserted.message.isError).toBe(true);
711+
expect(inserted.message.timestamp).toBe(Date.parse(sourceEntryTimestamp));
710712
expect(inserted.message.content[0].text).toBe("aborted");
711713
expect(JSON.parse(lines[4])).toEqual(deliveryMirror);
712714
});

‎src/agents/session-file-repair.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,10 +322,12 @@ function makeSyntheticToolResultEntry(params: {
322322
toolCallId: string;
323323
toolName?: string;
324324
}): SessionMessageEntry {
325+
const parentMessageTimestamp = readSessionEntrySourceTimestamp(params.parent);
325326
const message = makeMissingToolResult({
326327
toolCallId: params.toolCallId,
327328
toolName: params.toolName,
328329
text: "aborted",
330+
sourceTimestamp: parentMessageTimestamp,
329331
});
330332
return {
331333
type: "message",
@@ -336,6 +338,17 @@ function makeSyntheticToolResultEntry(params: {
336338
};
337339
}
338340

341+
function readSessionEntrySourceTimestamp(entry: SessionMessageEntry): number | undefined {
342+
if (typeof entry.message.timestamp === "number" && Number.isFinite(entry.message.timestamp)) {
343+
return entry.message.timestamp;
344+
}
345+
if (typeof entry.timestamp === "string") {
346+
const timestamp = Date.parse(entry.timestamp);
347+
return Number.isFinite(timestamp) ? timestamp : undefined;
348+
}
349+
return undefined;
350+
}
351+
339352
function insertMissingCodeModeToolResults(entries: unknown[]): {
340353
entries: unknown[];
341354
insertedToolResults: number;

‎src/agents/session-tool-result-guard.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ import { makeMissingToolResult, sanitizeToolCallInputs } from "./session-transcr
3737
import type { SessionManager } from "./sessions/index.js";
3838
import { extractToolCallsFromAssistant, extractToolResultId } from "./tool-call-id.js";
3939

40+
function readFiniteTimestamp(value: unknown): number | undefined {
41+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
42+
}
43+
4044
/**
4145
* Truncate oversized text content blocks in a tool result message.
4246
* Returns the original message if under the limit, or a new message with
@@ -705,16 +709,17 @@ export function installSessionToolResultGuard(
705709
return;
706710
}
707711
if (allowSyntheticToolResults) {
708-
for (const [id, name] of pendingState.entries()) {
712+
for (const [id, entry] of pendingState.entries()) {
709713
const synthetic = makeMissingToolResult({
710714
toolCallId: id,
711-
toolName: name,
715+
toolName: entry.name,
712716
text: missingToolResultText,
717+
sourceTimestamp: entry.timestamp,
713718
});
714719
const flushed = applyBeforeWriteHook(
715720
persistToolResult(persistMessage(synthetic), {
716721
toolCallId: id,
717-
toolName: name,
722+
toolName: entry.name,
718723
isSynthetic: true,
719724
}),
720725
);
@@ -858,7 +863,17 @@ export function installSessionToolResultGuard(
858863
}
859864

860865
if (toolCalls.length > 0) {
861-
pendingState.trackToolCalls(toolCalls);
866+
const assistantTimestamp = readFiniteTimestamp(
867+
(finalMessage as { timestamp?: unknown }).timestamp,
868+
);
869+
pendingState.trackToolCalls(
870+
toolCalls.map((call) => {
871+
if (assistantTimestamp === undefined) {
872+
return call;
873+
}
874+
return { id: call.id, name: call.name, timestamp: assistantTimestamp };
875+
}),
876+
);
862877
}
863878
if (isUserAgentMessage(finalMessage)) {
864879
void opts?.onUserMessagePersisted?.(finalMessage);

‎src/agents/session-tool-result-state.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
* The state object decides when dropped or reordered messages need synthetic
44
* tool results flushed.
55
*/
6-
type PendingToolCall = { id: string; name?: string };
6+
type PendingToolCall = { id: string; name?: string; timestamp?: number };
7+
type PendingToolCallEntry = { name?: string; timestamp?: number };
78

89
type PendingToolCallState = {
910
size: () => number;
10-
entries: () => IterableIterator<[string, string | undefined]>;
11+
entries: () => IterableIterator<[string, PendingToolCallEntry]>;
1112
getToolName: (id: string) => string | undefined;
1213
delete: (id: string) => void;
1314
clear: () => void;
@@ -20,12 +21,12 @@ type PendingToolCallState = {
2021

2122
/** Tracks pending tool calls so sanitized transcript repair can flush in order. */
2223
export function createPendingToolCallState(): PendingToolCallState {
23-
const pending = new Map<string, string | undefined>();
24+
const pending = new Map<string, PendingToolCallEntry>();
2425

2526
return {
2627
size: () => pending.size,
2728
entries: () => pending.entries(),
28-
getToolName: (id: string) => pending.get(id),
29+
getToolName: (id: string) => pending.get(id)?.name,
2930
delete: (id: string) => {
3031
pending.delete(id);
3132
},
@@ -34,7 +35,10 @@ export function createPendingToolCallState(): PendingToolCallState {
3435
},
3536
trackToolCalls: (calls: PendingToolCall[]) => {
3637
for (const call of calls) {
37-
pending.set(call.id, call.name);
38+
pending.set(call.id, {
39+
...(call.name !== undefined ? { name: call.name } : {}),
40+
...(call.timestamp !== undefined ? { timestamp: call.timestamp } : {}),
41+
});
3842
}
3943
},
4044
getPendingIds: () => Array.from(pending.keys()),

‎src/agents/session-transcript-repair.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ describe("sanitizeToolUseResultPairing", () => {
9191
{
9292
role: "assistant",
9393
content: [{ type: "toolCall", id: "call_1", name: "read", arguments: {} }],
94+
timestamp: 12345,
9495
},
9596
{ role: "user", content: "user message that should come after tool use" },
9697
]);
@@ -102,6 +103,11 @@ describe("sanitizeToolUseResultPairing", () => {
102103
expect(result.added).toHaveLength(1);
103104
expect(result.messages.map((m) => m.role)).toEqual(["assistant", "toolResult", "user"]);
104105
expect(result.added[0]?.content).toEqual([{ type: "text", text: "aborted" }]);
106+
const repeated = repairToolUseResultPairing(input, {
107+
missingToolResultText: "aborted",
108+
});
109+
expect(result.added[0]?.timestamp).toBe(12345);
110+
expect(repeated.added[0]?.timestamp).toBe(result.added[0]?.timestamp);
105111
});
106112

107113
it("keeps matched parallel tool results and synthesizes only missing siblings", () => {

‎src/agents/session-transcript-repair.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,10 @@ const DEFAULT_MISSING_TOOL_RESULT_TEXT =
151151
"[openclaw] missing tool result in session history; inserted synthetic error result for transcript repair.";
152152
const SYNTHETIC_MISSING_TOOL_RESULT_DETAIL_KEY = "openclawSyntheticMissingToolResult";
153153

154+
function readFiniteTimestamp(value: unknown): number | undefined {
155+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
156+
}
157+
154158
function makeMissingToolResult(params: {
155159
toolCallId: string;
156160
toolName?: string;
@@ -160,6 +164,7 @@ function makeMissingToolResult(params: {
160164
// sends this repaired history to real models. Other providers keep the older,
161165
// explicit OpenClaw diagnostic text unless the caller opts in.
162166
text?: string;
167+
sourceTimestamp?: unknown;
163168
}): Extract<AgentMessage, { role: "toolResult" }> {
164169
return {
165170
role: "toolResult",
@@ -173,7 +178,7 @@ function makeMissingToolResult(params: {
173178
],
174179
details: { [SYNTHETIC_MISSING_TOOL_RESULT_DETAIL_KEY]: true },
175180
isError: true,
176-
timestamp: Date.now(),
181+
timestamp: readFiniteTimestamp(params.sourceTimestamp) ?? 0,
177182
} as Extract<AgentMessage, { role: "toolResult" }>;
178183
}
179184

@@ -715,6 +720,7 @@ export function repairToolUseResultPairing(
715720
toolCallId: call.id,
716721
toolName: call.name,
717722
text: options?.missingToolResultText,
723+
sourceTimestamp: readFiniteTimestamp((msg as { timestamp?: unknown }).timestamp),
718724
});
719725
added.push(missing);
720726
changed = true;

0 commit comments

Comments
 (0)