Skip to content

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

feat: ChatGPT adapter (delta_encoding v1) + reused test harness

shukieshahad551ed22802
diff --git a/browser-extension/.gitignore b/browser-extension/.gitignore
index fb5ae353..8facc606 100644
--- a/browser-extension/.gitignore
+++ b/browser-extension/.gitignore
@@ -12,5 +12,6 @@ blob-report/
fixtures/**/*.page.html
fixtures/**/*.meta.json
fixtures/**/real-*.sse
+fixtures/**/diag-*.sse
*.log
.DS_Store
diff --git a/browser-extension/README.md b/browser-extension/README.md
index 0793c8af..214ea0f8 100644
--- a/browser-extension/README.md
+++ b/browser-extension/README.md
@@ -58,7 +58,7 @@ Make sure the beacon endpoint agent is running (it provides the `127.0.0.1:4318`
| Path | Purpose |
|---|---|
| `src/shared/` | Site-agnostic core. `normalize.ts` (pure `ChatTurn → OTLP`), `otlp.ts`, `vocab.ts`, `types.ts`, `ids.ts`. |
-| `src/adapters/` | The only site-specific code. `claude.ts` (done), `chatgpt.ts` (next). `sse.ts` shared SSE framing. |
+| `src/adapters/` | The only site-specific code. `claude.ts` + `chatgpt.ts` (both done). `sse.ts` shared SSE framing. |
| `src/interceptor/` | MAIN-world `fetch`/stream tee. |
| `src/content/` | ISOLATED-world relay + (future) DOM fallback. |
| `src/background/` | Service worker: `assembler.ts`, `delivery.ts` (durable queue + backoff), `settings.ts`, `sw.ts`. |
@@ -87,8 +87,8 @@ Beacon collector (prompt → response → tool calls → `runtime.jsonl` → S3
- ✅ Claude capture end-to-end + autonomous replay e2e
- ✅ Resilience: multi-tab correlation + aborted/partial stream (e2e)
- ✅ Content-script context-invalidation guard (survives extension reloads)
-- ⬜ ChatGPT adapter
-- ⬜ DOM-fallback capture, XHR transport
+- ✅ ChatGPT capture (`delta_encoding: v1` parser) + autonomous replay e2e
+- ⬜ ChatGPT stream-handoff/resume case (see limitations); DOM-fallback capture, XHR transport
- ⬜ Real-collector integration test + live-smoke/fixture-recorder as CI layers
### Known limitations (V0 — intentionally deferred)
@@ -105,6 +105,12 @@ Beacon collector (prompt → response → tool calls → `runtime.jsonl` → S3
service worker for streaming would need additional interception (deferred).
- **Single capture path.** No DOM-scraping fallback yet; if a site changes its SSE wire format, the
adapter needs updating (the live-smoke drift alarm is designed to catch this).
+- **ChatGPT stream-handoff turns.** ChatGPT streams the answer as `delta_encoding: v1` SSE, usually
+ *inline* on the `POST /backend-api/f/conversation` response (which we tee). Occasionally it instead
+ returns a `stream_handoff` and streams the tokens on a **resume-SSE endpoint** — those turns are
+ currently missed. That resume stream is also SSE-over-fetch (no WebSocket needed for tokens; the
+ `wss://ws.chatgpt.com` socket only carries control messages), so teeing the resume GET is a
+ follow-up, not a rearchitecture. ChatGPT web (like Claude web) doesn't stream token usage.
- **Telemetry integrity on the injected page.** The MAIN-world interceptor and any other page script
share the same JS world, so the ISOLATED content script cannot cryptographically distinguish the
extension's own `postMessage` events from forged ones. A malicious script already running on
diff --git a/browser-extension/e2e/chatgpt.replay.spec.ts b/browser-extension/e2e/chatgpt.replay.spec.ts
new file mode 100644
index 00000000..f92a7a80
--- /dev/null
+++ b/browser-extension/e2e/chatgpt.replay.spec.ts
@@ -0,0 +1,59 @@
+import { test, expect, seedSettings } from './fixtures.js';
+import { flatAttrs, recordByAction, resourceAttrs } from './helpers/otlp-assertions.js';
+
+// conversation id embedded in the fixture's resume_conversation_token
+const CONV = '6a73b75a-18d8-83ea-bbcf-984208806963';
+const COMPLETION_PATH = '/backend-api/f/conversation';
+
+test.beforeEach(async ({ mockCollector }) => {
+ mockCollector.reset();
+});
+
+test('captures a simple ChatGPT turn end-to-end into normalized OTLP', async ({
+ context,
+ serviceWorker,
+ replay,
+ mockCollector,
+}) => {
+ replay.setCase({
+ site: 'chatgpt',
+ name: 'simple-turn',
+ conversationId: CONV,
+ prompt: 'good evening',
+ completionPath: COMPLETION_PATH,
+ });
+ 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://chatgpt.com/');
+ await expect(page.locator('[data-testid="assistant-message"]')).toHaveAttribute(
+ 'data-complete',
+ '1',
+ );
+
+ await expect.poll(() => mockCollector.received.length, { timeout: 10_000 }).toBeGreaterThan(0);
+
+ const res = resourceAttrs(mockCollector.received[0]);
+ expect(res['beacon.harness.name']).toBe('chatgpt_web');
+ expect(res['gen_ai.provider.name']).toBe('openai');
+
+ // Prompt lands on its own prompt.submitted record with the conv id from the stream.
+ const promptRec = recordByAction(mockCollector.received, 'prompt.submitted');
+ expect(promptRec, 'a prompt.submitted record should have been delivered').toBeTruthy();
+ const promptAttrs = flatAttrs(promptRec!.attributes);
+ expect(promptAttrs['beacon.prompt.text']).toBe('good evening');
+ expect(promptAttrs['beacon.session.id']).toBe(CONV);
+
+ // Response lands on the agent.response.completed record.
+ const rec = recordByAction(mockCollector.received, 'agent.response.completed');
+ expect(rec, 'a completed-response record should have been delivered').toBeTruthy();
+ const attrs = flatAttrs(rec!.attributes);
+ expect(attrs['gen_ai.conversation.id']).toBe(CONV);
+ expect(attrs['gen_ai.response.model']).toBe('gpt-5-6-thinking');
+ expect(String(attrs['gen_ai.output.messages'])).toContain('Good evening');
+});
diff --git a/browser-extension/e2e/helpers/sse-replay-server.ts b/browser-extension/e2e/helpers/sse-replay-server.ts
index fb016cd3..f59b9547 100644
--- a/browser-extension/e2e/helpers/sse-replay-server.ts
+++ b/browser-extension/e2e/helpers/sse-replay-server.ts
@@ -51,16 +51,16 @@ export async function startReplayServer(): Promise<ReplayServer> {
const server = https.createServer({ key, cert }, (req, res) => {
const url = new URL(req.url ?? '/', 'https://claude.ai');
- // The completion endpoint: stream the recorded SSE for that conversation.
- if (req.method === 'POST' && url.pathname.includes('/chat_conversations/')) {
- const convId = url.pathname.match(/chat_conversations\/([^/]+)\//)?.[1] ?? '';
- const c = cases.get(convId);
- if (!c) {
- res.writeHead(404).end('no case for conversation');
- return;
+ // The completion endpoint: match the POST path against a registered case's
+ // completion path (site-agnostic — Claude embeds the conv id in the path;
+ // ChatGPT posts to a fixed /backend-api/f/conversation).
+ if (req.method === 'POST') {
+ for (const c of cases.values()) {
+ if (url.pathname === c.completionPath.replace('{conv}', c.conversationId)) {
+ streamFixture(res, c);
+ return;
+ }
}
- streamFixture(res, c);
- return;
}
// Anything else → the chat page for the requested (or default) conversation.
@@ -125,6 +125,19 @@ function chunkify(body: string): string[] {
/** Minimal page that mirrors a chat message list and fires the completion fetch. */
function pageHtml(c: ReplayCase): string {
const completionUrl = c.completionPath.replace('{conv}', c.conversationId);
+ // Per-site request body: ChatGPT posts messages[].content.parts (conv id comes
+ // back in the stream); Claude posts {prompt, conversation_id}.
+ const bodyStr =
+ c.site === 'chatgpt'
+ ? JSON.stringify({
+ action: 'next',
+ conversation_id: null,
+ model: 'gpt-5-6-thinking',
+ messages: [
+ { author: { role: 'user' }, content: { content_type: 'text', parts: [c.prompt] } },
+ ],
+ })
+ : JSON.stringify({ prompt: c.prompt, conversation_id: c.conversationId });
return `<!doctype html>
<html>
<head><meta charset="utf-8" /><title>${c.site} (replay)</title></head>
@@ -141,9 +154,7 @@ function pageHtml(c: ReplayCase): string {
const init = {
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ prompt: ${JSON.stringify(c.prompt)}, conversation_id: ${JSON.stringify(
- c.conversationId,
- )} }),
+ body: ${JSON.stringify(bodyStr)},
};
const res = await ${
c.requestStyle === 'request' ? 'fetch(new Request(url, init))' : 'fetch(url, init)'
diff --git a/browser-extension/fixtures/chatgpt/simple-turn.sse b/browser-extension/fixtures/chatgpt/simple-turn.sse
new file mode 100644
index 00000000..a2bbe4dd
--- /dev/null
+++ b/browser-extension/fixtures/chatgpt/simple-turn.sse
@@ -0,0 +1,24 @@
+event: delta_encoding
+data: "v1"
+
+data: {"type": "resume_conversation_token", "kind": "topic", "token": "REDACTED", "conversation_id": "6a73b75a-18d8-83ea-bbcf-984208806963"}
+
+event: delta
+data: {"p": "", "o": "add", "v": {"message": {"id": "seed-system", "author": {"role": "system", "name": null, "metadata": {}}, "content": {"content_type": "text", "parts": [""]}, "status": "finished_successfully", "recipient": "all", "metadata": {}}}}
+
+event: delta
+data: {"v": {"message": {"id": "asst-0001", "author": {"role": "assistant", "name": null, "metadata": {}}, "content": {"content_type": "text", "parts": [""]}, "status": "in_progress", "recipient": "all", "metadata": {"model_slug": "gpt-5-6-thinking"}}}}
+
+event: delta
+data: {"p": "/message/content/parts/0", "o": "append", "v": "Good evening"}
+
+event: delta
+data: {"v": "! Hello to you as well."}
+
+event: delta
+data: {"o": "patch", "p": "", "v": [{"p": "/message/content/parts/0", "o": "append", "v": " Hope your day is going well."}, {"p": "/message/status", "o": "replace", "v": "finished_successfully"}, {"p": "/message/end_turn", "o": "replace", "v": true}, {"p": "/message/metadata", "o": "append", "v": {"search_result_groups": []}}]}
+
+data: {"type": "message_stream_complete", "conversation_id": "6a73b75a-18d8-83ea-bbcf-984208806963"}
+
+data: [DONE]
+
diff --git a/browser-extension/src/adapters/adapter.ts b/browser-extension/src/adapters/adapter.ts
index c56a795e..1f8a663d 100644
--- a/browser-extension/src/adapters/adapter.ts
+++ b/browser-extension/src/adapters/adapter.ts
@@ -37,7 +37,9 @@ export function adapterForHost(host: string): SiteAdapter | undefined {
/** Permissive request predicate for the MAIN-world interceptor (which is
* site-agnostic). The SW's adapter makes the authoritative decision. */
export function looksLikeChatRequest(url: string): boolean {
- return /(\/backend-api\/conversation|\/backend-anon\/conversation|chat_conversations\/.+\/(completion|retry_completion)|\/completion\b)/.test(
+ // Over-matches on purpose (the SW's adapter.matchesRequest makes the precise
+ // call); must include ChatGPT's /f/conversation variant so it gets teed.
+ return /(\/backend-(api|anon)\/(f\/)?conversation|chat_conversations\/.+\/(completion|retry_completion)|\/completion\b)/.test(
url,
);
}
diff --git a/browser-extension/src/adapters/chatgpt.ts b/browser-extension/src/adapters/chatgpt.ts
new file mode 100644
index 00000000..6ab546f5
--- /dev/null
+++ b/browser-extension/src/adapters/chatgpt.ts
@@ -0,0 +1,256 @@
+// ChatGPT (chatgpt.com / chat.openai.com) adapter.
+//
+// ChatGPT streams the assistant turn as Server-Sent Events over `fetch` from
+// POST /backend-api/f/conversation, using OpenAI's `delta_encoding: v1` format:
+// event: delta_encoding data: "v1"
+// data: {"type":"resume_conversation_token", "conversation_id":"..."}
+// event: delta data: {"p":"","o":"add","v":{"message":{...}}} ← seed a message
+// event: delta data: {"v":{"message":{...}}} ← bare: inherits o/p (add @ "")
+// event: delta data: {"p":"/message/content/parts/0","o":"append","v":"tok"}
+// event: delta data: {"v":"more"} ← bare: inherits append @ path
+// event: delta data: {"o":"patch","p":"","v":[{op},{op},...]} ← batched ops
+// data: {"type":"message_stream_complete", ...}
+// data: [DONE]
+//
+// A frame carrying only `v` inherits the previous frame's `o` (op) and `p`
+// (path). We maintain a single "root" object and apply add/append/replace/patch
+// to it, tracking the visible assistant message (author.role === 'assistant',
+// recipient 'all') and accumulating its content/parts text.
+//
+// NOTE: ChatGPT sometimes hands the stream off to a resume endpoint instead of
+// streaming inline on this POST (a `stream_handoff` event). That resume stream
+// is also SSE-over-fetch; capturing it is a documented follow-up.
+
+import type { ChatTurn, Msg, ToolCall } from '../shared/types.js';
+import { registerAdapter, type SiteAdapter, type TurnParser } from './adapter.js';
+import { SSEParser, type SSEEvent } from './sse.js';
+import { turnId } from '../shared/ids.js';
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+class ChatGptParser implements TurnParser {
+ private sse = new SSEParser();
+ private reqId: number;
+ private sessionId = '';
+ private requestModel?: string;
+ private promptText = '';
+ private inputMessages: Msg[] = [];
+ private startedAt = Date.now();
+ private completedAt?: number;
+
+ // delta_encoding v1 cursor + document state
+ private lastOp = '';
+ private lastPath = '';
+ private root: any = null;
+ /** Reference to the visible assistant message object (mutated in place by ops). */
+ private assistantMsg: any = null;
+
+ constructor(reqId: number) {
+ this.reqId = reqId;
+ }
+
+ onRequest(_url: string, _method: string, body: string | null): void {
+ if (!body) return;
+ try {
+ const parsed = JSON.parse(body);
+ if (typeof parsed?.conversation_id === 'string') this.sessionId = parsed.conversation_id;
+ if (typeof parsed?.model === 'string') this.requestModel = parsed.model;
+ const { text, messages } = extractPrompt(parsed);
+ this.promptText = text;
+ this.inputMessages = messages;
+ } catch {
+ /* non-JSON body — prompt stays empty */
+ }
+ }
+
+ onChunk(chunk: string): void {
+ for (const evt of this.sse.push(chunk)) this.handle(evt);
+ }
+
+ onDone(): void {
+ for (const evt of this.sse.flush()) this.handle(evt);
+ }
+
+ private handle(evt: SSEEvent): void {
+ const data = evt.data;
+ if (!data) return;
+ if (data === '[DONE]') {
+ this.completedAt ??= Date.now();
+ return;
+ }
+ if (evt.event === 'delta_encoding') return; // just declares "v1"
+
+ let obj: any;
+ try {
+ obj = JSON.parse(data);
+ } catch {
+ return;
+ }
+ if (obj == null || typeof obj !== 'object') return;
+
+ // Typed control events carry a `type` and are not delta ops.
+ if (typeof obj.type === 'string' && !('v' in obj && (('o' in obj) || ('p' in obj)))) {
+ switch (obj.type) {
+ case 'resume_conversation_token':
+ if (!this.sessionId && typeof obj.conversation_id === 'string')
+ this.sessionId = obj.conversation_id;
+ break;
+ case 'message_stream_complete':
+ this.completedAt ??= Date.now();
+ break;
+ // input_message / message_marker / title_generation / *_metadata → ignore
+ }
+ return;
+ }
+
+ // Delta op: resolve op/path with bare-value inheritance.
+ if ('o' in obj) this.lastOp = obj.o;
+ if ('p' in obj) this.lastPath = obj.p;
+ this.apply(this.lastOp, this.lastPath, obj.v);
+ }
+
+ private apply(op: string, path: string, v: any): void {
+ switch (op) {
+ case 'add':
+ if (path === '' || path === '/') {
+ this.root = v;
+ this.trackAssistant();
+ } else {
+ setAt(this.root, path, v);
+ }
+ break;
+ case 'append':
+ appendAt(this.root, path, v);
+ break;
+ case 'replace':
+ setAt(this.root, path, v);
+ break;
+ case 'patch':
+ if (Array.isArray(v)) for (const s of v) this.apply(s.o, s.p ?? '', s.v);
+ break;
+ }
+ }
+
+ /** After an add at root, record the visible assistant message reference. */
+ private trackAssistant(): void {
+ const m = this.root?.message;
+ if (!m || m.author?.role !== 'assistant') return;
+ if (m.recipient != null && m.recipient !== 'all') return; // tool/aside message
+ if (!m.content || !Array.isArray(m.content.parts)) m.content = { parts: [''] };
+ this.assistantMsg = m; // subsequent ops mutate this in place
+ }
+
+ getTurn(): ChatTurn | null {
+ const m = this.assistantMsg;
+ const responseText = m?.content?.parts?.filter((p: any) => typeof p === 'string').join('') ?? '';
+ if (!responseText && !this.promptText) return null;
+
+ const responseModel = m?.metadata?.model_slug ?? this.requestModel;
+ const messageId: string = m?.id ?? '';
+ const sessionId = this.sessionId || `chatgpt-unknown-${this.reqId}`;
+ const turnKey = messageId || `r${this.reqId}`;
+
+ return {
+ site: 'chatgpt_web',
+ sessionId,
+ turnId: turnId(sessionId, turnKey),
+ requestModel: this.requestModel,
+ responseModel,
+ promptText: this.promptText,
+ inputMessages: this.inputMessages,
+ outputMessages: [{ role: 'assistant', text: responseText }],
+ responseText,
+ toolCalls: extractToolCalls(m, messageId),
+ usage: {}, // ChatGPT web does not stream token usage
+ startedAt: this.startedAt,
+ completedAt: this.completedAt,
+ captureMode: 'sse',
+ };
+ }
+}
+
+/** Best-effort web-search/tool capture from the assistant message metadata. */
+function extractToolCalls(m: any, messageId: string): ToolCall[] {
+ const groups = m?.metadata?.search_result_groups;
+ if (Array.isArray(groups) && groups.length > 0) {
+ return [{ id: `${messageId}:search`, name: 'web_search', arguments: { search_result_groups: groups } }];
+ }
+ return [];
+}
+
+/** Navigate to the parent of `path` and return [container, key]. */
+function locate(root: any, path: string): [any, string | number] | null {
+ const segs = path.split('/').filter(Boolean);
+ if (segs.length === 0) return null;
+ let obj = root;
+ for (let i = 0; i < segs.length - 1; i++) {
+ if (obj == null) return null;
+ const k = segs[i];
+ obj = Array.isArray(obj) ? obj[Number(k)] : obj[k];
+ }
+ if (obj == null) return null;
+ const last = segs[segs.length - 1];
+ return [obj, Array.isArray(obj) ? Number(last) : last];
+}
+
+function appendAt(root: any, path: string, v: any): void {
+ const loc = locate(root, path);
+ if (!loc) return;
+ const [obj, key] = loc;
+ const cur = (obj as any)[key];
+ if (typeof v === 'string') {
+ (obj as any)[key] = (typeof cur === 'string' ? cur : '') + v;
+ } else if (v && typeof v === 'object' && !Array.isArray(v) && cur && typeof cur === 'object') {
+ (obj as any)[key] = { ...cur, ...v }; // merge (e.g. metadata) — preserves model_slug
+ } else {
+ (obj as any)[key] = v;
+ }
+}
+
+function setAt(root: any, path: string, v: any): void {
+ const loc = locate(root, path);
+ if (!loc) return;
+ const [obj, key] = loc;
+ (obj as any)[key] = v;
+}
+
+function extractPrompt(body: any): { text: string; messages: Msg[] } {
+ const messages: Msg[] = [];
+ let text = '';
+ for (const m of Array.isArray(body?.messages) ? body.messages : []) {
+ const role = normalizeRole(m?.author?.role ?? m?.role);
+ const t = coerceParts(m?.content);
+ messages.push({ role, text: t });
+ if (role === 'user') text = t;
+ }
+ return { text, messages };
+}
+
+function coerceParts(content: any): string {
+ if (typeof content === 'string') return content;
+ const parts = content?.parts;
+ if (Array.isArray(parts)) {
+ return parts.map((p: any) => (typeof p === 'string' ? p : typeof p?.text === 'string' ? p.text : '')).join('');
+ }
+ return '';
+}
+
+function normalizeRole(role: unknown): Msg['role'] {
+ return role === 'assistant' || role === 'system' || role === 'tool' ? role : 'user';
+}
+
+export const chatgptAdapter: SiteAdapter = {
+ name: 'chatgpt_web',
+ matchesHost: (host) =>
+ host === 'chatgpt.com' ||
+ host.endsWith('.chatgpt.com') ||
+ host === 'chat.openai.com' ||
+ host.endsWith('.chat.openai.com'),
+ // The message-send endpoint is a POST to /backend-(api|anon)/(f/)?conversation
+ // exactly — NOT sub-resources like /conversation/init or /conversation/{id}.
+ matchesRequest: (url, method) =>
+ /\/backend-(api|anon)\/(f\/)?conversation(?:\?|$)/.test(url) && method.toUpperCase() === 'POST',
+ createParser: (reqId) => new ChatGptParser(reqId),
+};
+
+registerAdapter(chatgptAdapter);
diff --git a/browser-extension/src/background/sw.ts b/browser-extension/src/background/sw.ts
index d5aac3a9..3945ba54 100644
--- a/browser-extension/src/background/sw.ts
+++ b/browser-extension/src/background/sw.ts
@@ -2,6 +2,7 @@
// completed turns to the durable delivery queue.
import '../adapters/claude.js'; // registers the Claude adapter (side effect)
+import '../adapters/chatgpt.js'; // registers the ChatGPT adapter (side effect)
import type { ChatTurn, RelayMessage, Settings } from '../shared/types.js';
import { getSettings, saveSettings, siteEnabled } from './settings.js';
import { Assembler } from './assembler.js';
diff --git a/browser-extension/test/unit/chatgpt.adapter.test.ts b/browser-extension/test/unit/chatgpt.adapter.test.ts
new file mode 100644
index 00000000..f2d33079
--- /dev/null
+++ b/browser-extension/test/unit/chatgpt.adapter.test.ts
@@ -0,0 +1,72 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { chatgptAdapter } from '../../src/adapters/chatgpt.js';
+import type { TurnParser } from '../../src/adapters/adapter.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const fixture = (name: string) =>
+ readFileSync(path.join(__dirname, '..', '..', 'fixtures', 'chatgpt', `${name}.sse`), 'utf8');
+
+const CONV = '6a73b75a-18d8-83ea-bbcf-984208806963';
+
+/** ChatGPT request body shape (messages[].content.parts). */
+function reqBody(prompt: string, conversationId: string | null): string {
+ return JSON.stringify({
+ action: 'next',
+ conversation_id: conversationId,
+ model: 'gpt-5-6-thinking',
+ messages: [
+ { id: 'u1', author: { role: 'user' }, content: { content_type: 'text', parts: [prompt] } },
+ ],
+ });
+}
+
+function run(name: string, prompt: string, conversationId: string | null, chunkSize = 7): TurnParser {
+ const parser = chatgptAdapter.createParser(1);
+ parser.onRequest('https://chatgpt.com/backend-api/f/conversation', 'POST', reqBody(prompt, conversationId));
+ const body = fixture(name);
+ for (let i = 0; i < body.length; i += chunkSize) parser.onChunk(body.slice(i, i + chunkSize));
+ parser.onDone();
+ return parser;
+}
+
+describe('chatgpt adapter — simple turn (delta_encoding v1)', () => {
+ const turn = run('simple-turn', 'good evening', null)!.getTurn()!;
+
+ it('reconstructs the response across add/append/bare/patch ops', () => {
+ expect(turn.responseText).toBe('Good evening! Hello to you as well. Hope your day is going well.');
+ });
+ it('captures the prompt from the request body', () => {
+ expect(turn.promptText).toBe('good evening');
+ });
+ it('takes the conversation id from the stream (not the message id)', () => {
+ expect(turn.sessionId).toBe(CONV);
+ });
+ it('captures the response model from metadata.model_slug', () => {
+ expect(turn.responseModel).toBe('gpt-5-6-thinking');
+ });
+ it('selects the assistant message id for the turn key', () => {
+ expect(turn.turnId).toBe(`${CONV}:asst-0001`);
+ });
+ it('marks the turn completed and has no tool calls (empty search groups)', () => {
+ expect(turn.completedAt).toBeTypeOf('number');
+ expect(turn.toolCalls).toHaveLength(0);
+ });
+});
+
+describe('chatgpt adapter — chunk-size invariance', () => {
+ it('produces the same response text regardless of chunk boundaries', () => {
+ const texts = [1, 3, 13, 100, 9999].map((n) => run('simple-turn', 'x', null, n).getTurn()!.responseText);
+ for (const t of texts)
+ expect(t).toBe('Good evening! Hello to you as well. Hope your day is going well.');
+ });
+});
+
+describe('chatgpt adapter — existing conversation', () => {
+ it('uses the request-body conversation_id when present', () => {
+ const turn = run('simple-turn', 'hi', 'body-conv-123')!.getTurn()!;
+ expect(turn.sessionId).toBe('body-conv-123');
+ });
+});
diff --git a/browser-extension/tools/record-fixtures.ts b/browser-extension/tools/record-fixtures.ts
index 86bc6e59..c215d60d 100644
--- a/browser-extension/tools/record-fixtures.ts
+++ b/browser-extension/tools/record-fixtures.ts
@@ -32,7 +32,10 @@ const SITES: Record<string, SiteConfig> = {
},
chatgpt: {
startUrl: 'https://chatgpt.com/',
- isCompletion: (u) => /\/backend-api\/(conversation|f\/conversation)\b/.test(u),
+ // The message-send endpoint is a POST to /backend-api/conversation (or the
+ // /f/conversation variant), NOT sub-resources like /conversation/init,
+ // /conversation/{id}, or /conversation/gen_title — hence the end/query anchor.
+ isCompletion: (u) => /\/backend-(api|anon)\/(f\/)?conversation(?:\?|$)/.test(u),
},
};
@@ -76,7 +79,7 @@ async function main() {
const pending = new Map<string, { url: string; postData?: string }>();
client.on('Network.requestWillBeSent', (e: any) => {
- if (cfg.isCompletion(e.request.url)) {
+ if ((e.request.method || '').toUpperCase() === 'POST' && cfg.isCompletion(e.request.url)) {
pending.set(e.requestId, { url: e.request.url, postData: e.request.postData });
}
});