Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): stop secret redaction from breaking tool call ids (#108456)

Vojta Bartoš3a09733d9200
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.test.ts
index 9fed45496050..62f9d564fc9e 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.test.ts
@@ -36,6 +36,19 @@ function toolEntry(
return entry(sessionUpdate, { _meta: { claudeCode: meta } });
}
+const REJECTED_TOOL_IDS = [
+ "toolu_01AbCdEfGh[REDACTED]",
+ "toolu_01AbCdEfGh.REDACTED.",
+];
+
+function expectRepairedToolIds(callIds: unknown[], resultIds: unknown[]): void {
+ for (const id of callIds) {
+ expect(id).toMatch(/^[a-zA-Z0-9_-]+$/);
+ }
+ expect(new Set(callIds).size).toBe(callIds.length);
+ expect(resultIds).toEqual(callIds);
+}
+
describe("getSessionJsonlPath", () => {
it("constructs path from sessionId and cwd", () => {
const original = process.env.CLAUDE_CONFIG_DIR;
@@ -744,6 +757,32 @@ describe("conversationTurnsToJsonlEntries", () => {
);
});
+ it("repairs tool ids the API rejects, and keeps each call paired with its result", () => {
+ const lines = conversationTurnsToJsonlEntries(
+ [
+ {
+ role: "assistant",
+ content: [],
+ toolCalls: REJECTED_TOOL_IDS.map((toolCallId) => ({
+ toolCallId,
+ toolName: "Bash",
+ input: {},
+ result: "ok",
+ })),
+ },
+ ],
+ config,
+ );
+
+ const blocks = parseConversationEntries(lines).map(
+ (line) => line.message.content[0],
+ );
+ expectRepairedToolIds(
+ blocks.slice(0, 2).map((block) => block.id),
+ blocks.slice(2).map((block) => block.tool_use_id),
+ );
+ });
+
it("falls back to space for empty user content", () => {
const lines = conversationTurnsToJsonlEntries(
[{ role: "user", content: [] }],
@@ -1413,6 +1452,36 @@ describe("sanitizeSessionJsonl", () => {
]);
});
+ it("repairs tool ids the API rejects, and keeps each call paired with its result", async () => {
+ const file = await writeJsonl([
+ ...REJECTED_TOOL_IDS.map((id) => ({
+ type: "assistant",
+ message: {
+ role: "assistant",
+ content: [{ type: "tool_use", id, name: "Bash", input: {} }],
+ },
+ })),
+ ...REJECTED_TOOL_IDS.map((id) => ({
+ type: "user",
+ message: {
+ role: "user",
+ content: [{ type: "tool_result", tool_use_id: id, content: "ok" }],
+ },
+ })),
+ ]);
+
+ expect(await sanitizeSessionJsonl(file)).toBe(true);
+
+ const blocks = (await readJsonl(file)).map(
+ (line) =>
+ (line.message as { content: Record<string, unknown>[] }).content[0],
+ );
+ expectRepairedToolIds(
+ blocks.slice(0, 2).map((block) => block.id),
+ blocks.slice(2).map((block) => block.tool_use_id),
+ );
+ });
+
it("sanitizes empty blocks in user lines too", async () => {
const file = await writeJsonl([
{
diff --git a/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.ts b/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.ts
index 735eb6b8a55a..4733c54180e3 100644
--- a/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/session/jsonl-hydration.ts
@@ -90,6 +90,22 @@ function stripMcpResultMeta(value: unknown): unknown {
return value;
}
+const API_TOOL_ID = /^[a-zA-Z0-9_-]+$/;
+
+// Secret redaction can rewrite part of a stored id. The repair depends on the id alone, so
+// a tool_use and its tool_result keep the same id when each is repaired on its own line.
+// The digest keeps apart two ids that differ only in the characters the API rejects.
+function toApiToolId(id: string): string {
+ if (API_TOOL_ID.test(id)) return id;
+ const digest = createHash("sha256").update(id).digest("hex").slice(0, 8);
+ return `${id.replace(/[^a-zA-Z0-9_-]/g, "_")}_${digest}`;
+}
+
+const TOOL_ID_KEY: Record<string, string | undefined> = {
+ tool_use: "id",
+ tool_result: "tool_use_id",
+};
+
function isEmptyRecord(value: unknown): boolean {
return (
typeof value === "object" &&
@@ -472,7 +488,7 @@ export function conversationTurnsToJsonlEntries(
for (const tc of turn.toolCalls) {
allBlocks.push({
type: "tool_use",
- id: tc.toolCallId,
+ id: toApiToolId(tc.toolCallId),
name: tc.toolName,
// undefined would be dropped on stringify; the API requires input
input: tc.input ?? {},
@@ -550,7 +566,7 @@ export function conversationTurnsToJsonlEntries(
content: [
{
type: "tool_result",
- tool_use_id: tc.toolCallId,
+ tool_use_id: toApiToolId(tc.toolCallId),
content: resultText,
},
],
@@ -592,10 +608,11 @@ function recordSanitized(
}
// Heals a persisted transcript that would otherwise 400 on every resume:
-// empty content blocks, missing tool_use.input, and images the API can't
-// process (unsupported type or over the per-image byte limit). The image case
-// is why a session that once read/attached a bad image keeps re-triggering the
-// same error on nearly every subsequent turn until the block is neutralized.
+// empty content blocks, missing tool_use.input, tool ids the API rejects, and
+// images the API can't process (unsupported type or over the per-image byte
+// limit). The image case is why a session that once read/attached a bad image
+// keeps re-triggering the same error on nearly every subsequent turn until the
+// block is neutralized.
export async function sanitizeSessionJsonl(
jsonlPath: string,
): Promise<boolean> {
@@ -638,6 +655,13 @@ export async function sanitizeSessionJsonl(
block.input = {};
lineChanged = true;
}
+ const idKey =
+ typeof block?.type === "string" ? TOOL_ID_KEY[block.type] : undefined;
+ const id = block && idKey ? block[idKey] : undefined;
+ if (block && idKey && typeof id === "string" && toApiToolId(id) !== id) {
+ block[idKey] = toApiToolId(id);
+ lineChanged = true;
+ }
}
const imageResult = neutralizeUnprocessableImages(message.content);
if (imageResult.changed) {
diff --git a/products/desktop/packages/agent/src/utils/redact-secrets.test.ts b/products/desktop/packages/agent/src/utils/redact-secrets.test.ts
index 1360897b7088..b3b279563a5f 100644
--- a/products/desktop/packages/agent/src/utils/redact-secrets.test.ts
+++ b/products/desktop/packages/agent/src/utils/redact-secrets.test.ts
@@ -89,6 +89,14 @@ describe("redactSecrets", () => {
expect(redactSecrets(`Bearer ${jwt}. ok`)).toBe("Bearer [REDACTED]. ok");
});
+ it("keeps a tool call id that contains the JWT prefix", () => {
+ const update = {
+ sessionUpdate: "tool_call",
+ toolCallId: "toolu_01AbCdEfGheyJ4mQ7xZp2Wv9Ls",
+ };
+ expect(redactSecrets(update)).toEqual(update);
+ });
+
it.each(headerCases)("redacts a %s", (_shape, server, expected) => {
expect(
redactSecrets({
diff --git a/products/desktop/packages/agent/src/utils/redact-secrets.ts b/products/desktop/packages/agent/src/utils/redact-secrets.ts
index d204c402d5a7..e2b3c7b55b20 100644
--- a/products/desktop/packages/agent/src/utils/redact-secrets.ts
+++ b/products/desktop/packages/agent/src/utils/redact-secrets.ts
@@ -29,7 +29,9 @@ function trailingDots(match: string): string {
}
const TOKEN = new RegExp(
- TOKEN_RULES.map((rule) => tokenSource(rule, "+")).join("|"),
+ TOKEN_RULES.map((rule) => rule.shape?.source ?? tokenSource(rule, "+")).join(
+ "|",
+ ),
"g",
);
diff --git a/products/desktop/packages/agent/src/utils/secret-rules.ts b/products/desktop/packages/agent/src/utils/secret-rules.ts
index c056af09f391..a87063ee667f 100644
--- a/products/desktop/packages/agent/src/utils/secret-rules.ts
+++ b/products/desktop/packages/agent/src/utils/secret-rules.ts
@@ -2,6 +2,9 @@ export interface TokenRule {
label: string;
prefix: string;
body: RegExp;
+ // Replaces prefix and body for a complete string. Streamed chunks keep the prefix,
+ // because a chunk can end before the part of the token that the shape requires.
+ shape?: RegExp;
}
const URL_SAFE_BODY = /[A-Za-z0-9_-]/;
@@ -42,6 +45,9 @@ export const TOKEN_RULES: TokenRule[] = [
label: "jwt",
prefix: "eyJ",
body: /[A-Za-z0-9_.-]/,
+ // The prefix also occurs inside random identifiers such as a tool call id. A dot
+ // does not, and a JWT always has one after its header.
+ shape: /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-][A-Za-z0-9_.-]*/,
},
];