Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix: address Bugbot round 2 (stable turn ids, Request-body capture)

shukieshah874bbb3b6e96
diff --git a/browser-extension/e2e/claude.replay.spec.ts b/browser-extension/e2e/claude.replay.spec.ts
index a3cac2d3..128831db 100644
--- a/browser-extension/e2e/claude.replay.spec.ts
+++ b/browser-extension/e2e/claude.replay.spec.ts
@@ -60,6 +60,41 @@ test('captures a simple Claude turn end-to-end into normalized OTLP', async ({
expect(String(attrs['gen_ai.output.messages'])).toContain('Paris');
});
+test('captures the prompt when the page uses fetch(new Request(...))', async ({
+ context,
+ serviceWorker,
+ replay,
+ mockCollector,
+}) => {
+ replay.setCase({
+ site: 'claude',
+ name: 'simple-turn',
+ conversationId: CONV,
+ prompt: 'What is the capital of France?',
+ completionPath: COMPLETION_PATH,
+ requestStyle: 'request', // body lives on the Request object, not init.body
+ });
+ await seedSettings(serviceWorker, {
+ enabled: true,
+ retention: 'full',
+ endpoint: mockCollector.url,
+ sites: { claude_web: true, chatgpt_web: true },
+ });
+
+ const page = await context.newPage();
+ await page.goto('https://claude.ai/chat');
+ await expect(page.locator('[data-testid="assistant-message"]')).toHaveAttribute(
+ 'data-complete',
+ '1',
+ );
+
+ await expect
+ .poll(() => recordByAction(mockCollector.received, 'prompt.submitted'), { timeout: 10_000 })
+ .toBeTruthy();
+ const p = flatAttrs(recordByAction(mockCollector.received, 'prompt.submitted')!.attributes);
+ expect(p['beacon.prompt.text']).toBe('What is the capital of France?');
+});
+
test('captures a Claude tool call as a tool.invoked record', async ({
context,
serviceWorker,
diff --git a/browser-extension/e2e/helpers/sse-replay-server.ts b/browser-extension/e2e/helpers/sse-replay-server.ts
index 2f9f844c..fb016cd3 100644
--- a/browser-extension/e2e/helpers/sse-replay-server.ts
+++ b/browser-extension/e2e/helpers/sse-replay-server.ts
@@ -32,6 +32,8 @@ export interface ReplayCase {
completionPath: string;
/** optional CSP header to prove injection survives it */
csp?: string;
+ /** how the page issues the completion fetch: 'init' (default) or a Request object */
+ requestStyle?: 'init' | 'request';
}
export interface ReplayServer {
@@ -135,13 +137,17 @@ function pageHtml(c: ReplayCase): string {
</main>
<script>
(async () => {
- const res = await fetch(${JSON.stringify(completionUrl)}, {
+ const url = ${JSON.stringify(completionUrl)};
+ const init = {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ prompt: ${JSON.stringify(c.prompt)}, conversation_id: ${JSON.stringify(
c.conversationId,
)} }),
- });
+ };
+ const res = await ${
+ c.requestStyle === 'request' ? 'fetch(new Request(url, init))' : 'fetch(url, init)'
+ };
// Consume the stream like the real site does.
const reader = res.body.getReader();
const dec = new TextDecoder();
diff --git a/browser-extension/src/adapters/adapter.ts b/browser-extension/src/adapters/adapter.ts
index aa537785..c56a795e 100644
--- a/browser-extension/src/adapters/adapter.ts
+++ b/browser-extension/src/adapters/adapter.ts
@@ -20,7 +20,8 @@ export interface SiteAdapter {
matchesHost(host: string): boolean;
/** Whether this request is a chat completion worth capturing. */
matchesRequest(url: string, method: string): boolean;
- createParser(): TurnParser;
+ /** @param reqId the interceptor's per-page request id (from the InterceptEvent). */
+ createParser(reqId: number): TurnParser;
}
const registry: SiteAdapter[] = [];
diff --git a/browser-extension/src/adapters/claude.ts b/browser-extension/src/adapters/claude.ts
index 840cb1cf..dbd05e49 100644
--- a/browser-extension/src/adapters/claude.ts
+++ b/browser-extension/src/adapters/claude.ts
@@ -31,6 +31,9 @@ class ClaudeParser implements TurnParser {
private startedAt = Date.now();
private completedAt?: number;
private reqId: number;
+ /** Stable per-turn id from message_start; used for turnId so ids don't collide
+ * across service-worker restarts (which reset the reqId counter). */
+ private messageId = '';
// tool_use blocks keyed by content-block index.
private blocks = new Map<number, { type: string; tool?: ToolCall; argBuf: string }>();
@@ -83,6 +86,8 @@ class ClaudeParser implements TurnParser {
case 'message_start': {
const m = obj.message ?? {};
if (typeof m.model === 'string') this.model = m.model;
+ if (typeof m.uuid === 'string') this.messageId = m.uuid;
+ else if (typeof m.id === 'string') this.messageId = m.id;
if (typeof m.id === 'string' && !this.sessionId) this.sessionId = m.id;
if (typeof m.usage?.input_tokens === 'number') this.inputTokens = m.usage.input_tokens;
break;
@@ -135,11 +140,14 @@ class ClaudeParser implements TurnParser {
toolCalls.push({ ...entry.tool, arguments: args });
}
}
- const sessionId = this.sessionId || `claude-${this.reqId}`;
+ const sessionId = this.sessionId || `claude-${this.messageId || this.reqId}`;
+ // Prefer the stable assistant message id; fall back to the interceptor's
+ // per-page reqId only when message_start was never seen (degenerate case).
+ const turnKey = this.messageId || `r${this.reqId}`;
return {
site: 'claude_web',
sessionId,
- turnId: turnId(sessionId, this.reqId),
+ turnId: turnId(sessionId, turnKey),
requestModel: this.model,
responseModel: this.model,
promptText: this.promptText,
@@ -197,12 +205,7 @@ export const claudeAdapter: SiteAdapter = {
matchesRequest: (url, method) =>
/chat_conversations\/.+\/(completion|retry_completion)/.test(url) &&
method.toUpperCase() === 'POST',
- createParser: () => new ClaudeParser(nextReqId()),
+ createParser: (reqId) => new ClaudeParser(reqId),
};
-let reqCounter = 0;
-function nextReqId(): number {
- return ++reqCounter;
-}
-
registerAdapter(claudeAdapter);
diff --git a/browser-extension/src/background/assembler.ts b/browser-extension/src/background/assembler.ts
index 2500c798..ded16b9e 100644
--- a/browser-extension/src/background/assembler.ts
+++ b/browser-extension/src/background/assembler.ts
@@ -26,7 +26,7 @@ export class Assembler {
if (event.kind === 'request') {
const adapter = adapterForHost(host);
if (!adapter || !adapter.matchesRequest(event.url, event.method)) return null;
- const parser = adapter.createParser();
+ const parser = adapter.createParser(event.reqId);
parser.onRequest(event.url, event.method, event.body);
this.entries.set(k, { adapter, parser });
return null;
diff --git a/browser-extension/src/interceptor/interceptor.ts b/browser-extension/src/interceptor/interceptor.ts
index 83d20ee9..d870c706 100644
--- a/browser-extension/src/interceptor/interceptor.ts
+++ b/browser-extension/src/interceptor/interceptor.ts
@@ -37,13 +37,27 @@ declare global {
const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
const matched = looksLikeChatRequest(url);
+
+ // Capture the request body BEFORE fetch consumes it. Prefer a string
+ // init.body; otherwise read a clone of the Request (fetch(new Request(...))),
+ // whose body would otherwise never be seen and the prompt would be lost.
+ let body: string | null = null;
+ if (matched) {
+ if (typeof init?.body === 'string') {
+ body = init.body;
+ } else if (input instanceof Request) {
+ try {
+ body = await input.clone().text();
+ } catch {
+ body = null;
+ }
+ }
+ }
+
const response = await originalFetch(input as RequestInfo, init);
if (matched && response.body) {
const reqId = ++reqSeq;
- // Capture request body if it is a simple string (claude.ai/ChatGPT both
- // send JSON string bodies for completions).
- const body = typeof init?.body === 'string' ? init.body : null;
post({ kind: 'request', reqId, url, method, body });
// Tee the stream via a clone so the page's own reader is untouched.
diff --git a/browser-extension/src/shared/ids.ts b/browser-extension/src/shared/ids.ts
index 1befc8b0..4917ab59 100644
--- a/browser-extension/src/shared/ids.ts
+++ b/browser-extension/src/shared/ids.ts
@@ -5,8 +5,8 @@
* Derive a stable turn id from a conversation id and the request sequence.
* Deterministic so retried/duplicate deliveries can be de-duped downstream.
*/
-export function turnId(sessionId: string, reqId: number): string {
- return `${sessionId}:${reqId}`;
+export function turnId(sessionId: string, key: string | number): string {
+ return `${sessionId}:${key}`;
}
/** A per-record idempotency key for dedupe across delivery retries. */
diff --git a/browser-extension/test/unit/claude.adapter.test.ts b/browser-extension/test/unit/claude.adapter.test.ts
index f2ea1a96..ec1a4620 100644
--- a/browser-extension/test/unit/claude.adapter.test.ts
+++ b/browser-extension/test/unit/claude.adapter.test.ts
@@ -14,7 +14,7 @@ const URL = `/api/organizations/org-x/chat_conversations/${CONV}/completion`;
/** Feed a body through a fresh parser in tiny, boundary-crossing chunks. */
function run(name: string, prompt: string, chunkSize = 7): TurnParser {
- const parser = claudeAdapter.createParser();
+ const parser = claudeAdapter.createParser(1);
parser.onRequest(URL, 'POST', JSON.stringify({ prompt, conversation_id: CONV }));
const body = fixture(name);
for (let i = 0; i < body.length; i += chunkSize) parser.onChunk(body.slice(i, i + chunkSize));