@kelceyp/chrome-control-mcp 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bun.lock ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "lockfileVersion": 1,
3
+ "workspaces": {
4
+ "": {
5
+ "name": "@kelceyp/chrome-control-mcp",
6
+ "dependencies": {
7
+ "@modelcontextprotocol/sdk": "^0.6.0",
8
+ },
9
+ },
10
+ },
11
+ "packages": {
12
+ "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@0.6.1", "", { "dependencies": { "content-type": "^1.0.5", "raw-body": "^3.0.0", "zod": "^3.23.8" } }, "sha512-OkVXMix3EIbB5Z6yife2XTrSlOnVvCLR1Kg91I4pYFEsV9RbnoyQVScXCuVhGaZHOnTZgso8lMQN1Po2TadGKQ=="],
13
+
14
+ "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
15
+
16
+ "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
17
+
18
+ "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
19
+
20
+ "http-errors": ["http-errors@2.0.0", "", { "dependencies": { "depd": "2.0.0", "inherits": "2.0.4", "setprototypeof": "1.2.0", "statuses": "2.0.1", "toidentifier": "1.0.1" } }, "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ=="],
21
+
22
+ "iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
23
+
24
+ "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
25
+
26
+ "raw-body": ["raw-body@3.0.0", "", { "dependencies": { "bytes": "3.1.2", "http-errors": "2.0.0", "iconv-lite": "0.6.3", "unpipe": "1.0.0" } }, "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g=="],
27
+
28
+ "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
29
+
30
+ "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
31
+
32
+ "statuses": ["statuses@2.0.1", "", {}, "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ=="],
33
+
34
+ "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
35
+
36
+ "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
37
+
38
+ "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
39
+ }
40
+ }
package/handover.md ADDED
@@ -0,0 +1,302 @@
1
+ # Chrome Control MCP - ChatGPT Adapter Handover
2
+
3
+ **Date:** 2025-10-25
4
+ **Status:** In progress - adapter bug fix needed
5
+ **Current Version:** 0.3.0 (published)
6
+
7
+ ---
8
+
9
+ ## Overview
10
+
11
+ This MCP server provides Chrome automation via AppleScript. It includes a specialized `gpt_chat` tool for conversing with ChatGPT programmatically.
12
+
13
+ **Problem:** The `gpt_chat` tool currently has a bug where it returns `{ok: true, text: "", ms: ~1200}` - empty text despite ChatGPT responding successfully.
14
+
15
+ ---
16
+
17
+ ## What Works
18
+
19
+ 1. ✅ **execute_javascript** - Sync JS execution
20
+ 2. ✅ **execute_javascript_async** - Async JS with polling (v0.2.0)
21
+ 3. ⚠️ **gpt_chat** - Auto-injects ChatGPT adapter, but has empty text bug (v0.3.0)
22
+
23
+ ---
24
+
25
+ ## The Bug
26
+
27
+ ### Symptoms
28
+ ```json
29
+ // gpt_chat returns:
30
+ {"ok": true, "text": "", "ms": 1244}
31
+ // ChatGPT DID respond, but text is empty
32
+ ```
33
+
34
+ ### Root Cause (Diagnosed with ChatGPT)
35
+
36
+ **Node Replacement Issue:**
37
+ 1. Adapter captures `const node = lastAssistantNode()` once
38
+ 2. During streaming, ChatGPT replaces DOM nodes (stream container → final wrapper)
39
+ 3. MutationObserver watches the **old/detached node**
40
+ 4. Detached node stops mutating → idle detected after 1.2s
41
+ 5. Reads `node.innerText` from detached node → returns ""
42
+
43
+ **Evidence:**
44
+ - Timing is exactly 1.2s (the idle threshold)
45
+ - Manual DOM queries show text IS there
46
+ - Happens consistently
47
+
48
+ ---
49
+
50
+ ## The Solution (Designed with ChatGPT)
51
+
52
+ ### Hybrid Approach: Text-Length Primary + Button Confirmation
53
+
54
+ **Why this approach:**
55
+ - Text-length polling is robust (no DOM structure assumptions)
56
+ - Longer idle period handles "Thinking..." pauses
57
+ - Button presence confirms rendering is complete
58
+ - Falls back gracefully if buttons don't appear
59
+
60
+ ### Implementation Details
61
+
62
+ **Key Parameters:**
63
+ ```javascript
64
+ idlePrimaryMs: 1200 // Normal streaming pause
65
+ idleConfirmMs: 3300 // Thinking pause threshold
66
+ finalButtonGraceMs: 2000 // Grace period for buttons
67
+ ```
68
+
69
+ **Logic Flow:**
70
+ 1. Poll text length every 100ms
71
+ 2. Track when length changes (resets idle timer)
72
+ 3. After 1.2s idle + input enabled: eligible for checking
73
+ 4. After 3.3s idle: check for turn-action buttons
74
+ 5. If buttons found: return text (confirmed complete)
75
+ 6. If no buttons after 2s grace: return text anyway (with note)
76
+
77
+ **Key Fixes:**
78
+ - Always fetch `lastAssistantNode()` fresh (no capturing)
79
+ - Look for buttons in turn container, not content node
80
+ - Proper async with `await sleep(100)` (prevents page freeze)
81
+
82
+ ---
83
+
84
+ ## Implementation Code
85
+
86
+ ChatGPT provided complete implementation in conversation. See their latest response for:
87
+
88
+ ```javascript
89
+ const waitForResponseWithBaseline = async (baseline, {
90
+ timeoutMs = 120000,
91
+ idlePrimaryMs = 1200,
92
+ idleConfirmMs = 3300,
93
+ finalButtonGraceMs = 2000
94
+ } = {}) => {
95
+ // Full implementation in ChatGPT response
96
+ // Uses text-length polling + button confirmation
97
+ // Returns: {ok, text, ms, note?}
98
+ }
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Testing Plan
104
+
105
+ ### Step 1: Test via execute_javascript_async
106
+
107
+ **Do NOT update gpt_chat tool yet.** Test manually first.
108
+
109
+ 1. **Inject v1.0.2 adapter** with hybrid approach
110
+ 2. **Send test message:** `"[CC] Test 1/5: Hybrid approach - reply HYBRID-OK-1"`
111
+ 3. **Verify result:** `{ok: true, text: "HYBRID-OK-1", ms: ...}`
112
+ 4. **Run 5 consecutive tests** to verify consistency
113
+ 5. **Check for page freezes** (previous attempts froze the page)
114
+
115
+ ### Step 2: Update gpt_chat tool
116
+
117
+ Once validated:
118
+ 1. Update embedded adapter in `server/index.js` (case 'gpt_chat')
119
+ 2. Bump `ADAPTER_VERSION` to `'1.0.2'`
120
+ 3. Update `package.json` to `0.4.0`
121
+ 4. Publish to npm
122
+ 5. Restart Claude Code
123
+ 6. Test `gpt_chat` tool directly
124
+
125
+ ---
126
+
127
+ ## ChatGPT Collaboration Context
128
+
129
+ **ChatGPT Session:** https://chatgpt.com/c/68fc1d3b-286c-8323-9488-82949cd69331
130
+ **Tab:** "Conversation setup explanation"
131
+
132
+ **Message Prefixes:**
133
+ - `[PK]` - Paul (user)
134
+ - `[CC]` - Claude Code (this agent)
135
+
136
+ **What ChatGPT Knows:**
137
+ - The complete adapter evolution (experiments, bugs, fixes)
138
+ - The node replacement issue diagnosis
139
+ - Text-length vs button detection trade-offs
140
+ - The hybrid approach design
141
+ - Implementation details and edge cases
142
+
143
+ **You can continue the conversation** by sending messages with `[CC]` prefix to ask questions or clarify implementation details.
144
+
145
+ ---
146
+
147
+ ## File Locations
148
+
149
+ ### Source Code
150
+ - **MCP Server:** `/Users/paulkelcey/Dev/gh/kelceyp-mcp-servers/chrome-control/server/index.js`
151
+ - **Package:** `/Users/paulkelcey/Dev/gh/kelceyp-mcp-servers/chrome-control/package.json`
152
+
153
+ ### Backup
154
+ - **Backup (pre-async):** `/Users/paulkelcey/Dev/gh/kelceyp-mcp-servers/chrome-control-bak/`
155
+
156
+ ### Related Files (in clibuilder project)
157
+ - **Original Adapter:** `/Users/paulkelcey/Dev/gh/kelceyp-mcp-servers/clibuilder/docs/cartridges/runbooks/chatgpt-adapter.js`
158
+ - **Handover Notes:** `/Users/paulkelcey/Dev/gh/kelceyp-mcp-servers/clibuilder/docs/cartridges/runbooks/chatgpt-collaboration-handover.md`
159
+
160
+ ---
161
+
162
+ ## Current gpt_chat Implementation (Broken)
163
+
164
+ Located in `server/index.js` starting at line ~570:
165
+
166
+ ```javascript
167
+ case 'gpt_chat': {
168
+ const { message, idle_ms = 1200, timeout_ms = 120000, tab_id } = args;
169
+
170
+ const ADAPTER_VERSION = '1.0.0';
171
+
172
+ // Embeds ChatBridge adapter
173
+ // Problem: Uses old node-capturing approach
174
+ // Line ~656: const node = lastAssistantNode();
175
+ // This node can become detached during streaming
176
+
177
+ // Needs update to v1.0.2 with hybrid approach
178
+ }
179
+ ```
180
+
181
+ ---
182
+
183
+ ## Button Detection Notes
184
+
185
+ **Initial Idea:** Poll for action buttons (Copy/Regenerate) to detect completion
186
+
187
+ **Problem Found:**
188
+ - Buttons are NOT children of `[data-message-author-role="assistant"]`
189
+ - They're in a separate toolbar within the turn container
190
+ - Need to search `[data-testid*="conversation-turn"]` → find toolbar → check buttons
191
+
192
+ **Filter Issue:**
193
+ ```javascript
194
+ // This was too aggressive:
195
+ candidates.filter(btn => !btn.closest('pre, code'))
196
+
197
+ // Excluded ALL buttons because markdown container has code blocks
198
+ ```
199
+
200
+ **ChatGPT's Fix:**
201
+ - Find the turn container first
202
+ - Find toolbar within turn: `[data-testid*="turn-actions"]` or `[role="toolbar"]`
203
+ - Check for buttons only in toolbar (naturally excludes code-copy buttons)
204
+
205
+ **Why Hybrid is Better:**
206
+ - Button detection is fragile (A/B testing, DOM changes)
207
+ - Text-length is robust
208
+ - Buttons confirm, but text-length drives the decision
209
+
210
+ ---
211
+
212
+ ## Edge Cases Handled
213
+
214
+ 1. **Thinking pauses:** 3.3s idle threshold
215
+ 2. **Toolbar A/B variants:** Falls back to text if no buttons
216
+ 3. **Code-heavy replies:** Text length jumps handled by longer idle
217
+ 4. **Images-only replies:** May need special handling (not critical for v1)
218
+ 5. **Node replacement:** Always fetch fresh node
219
+ 6. **Page freezing:** Proper async with `await sleep(100)`
220
+
221
+ ---
222
+
223
+ ## Known Issues
224
+
225
+ 1. **Page freeze** - Previous test script froze the page
226
+ - Cause: Tight polling loop without proper async
227
+ - Fix: Use `await sleep(100)` between polls
228
+
229
+ 2. **Empty text response** - Current gpt_chat bug
230
+ - Cause: Node replacement during streaming
231
+ - Fix: Implement v1.0.2 hybrid approach
232
+
233
+ 3. **AppleScript "missing value"** - Some DOM queries return this error
234
+ - Cause: AppleScript can't serialize complex objects
235
+ - Workaround: Return simple strings or use JSON.stringify carefully
236
+
237
+ ---
238
+
239
+ ## Next Steps
240
+
241
+ 1. **Read ChatGPT's latest response** in the conversation
242
+ 2. **Copy the complete `waitForResponseWithBaseline` implementation**
243
+ 3. **Create test payload** for execute_javascript_async
244
+ 4. **Run 5 tests** to verify consistency
245
+ 5. **Check for page freezes**
246
+ 6. **If successful:** Update gpt_chat tool
247
+ 7. **Publish v0.4.0**
248
+
249
+ ---
250
+
251
+ ## Collaboration Principles (from Paul)
252
+
253
+ When working on this project, follow these:
254
+ 1. **Don't be helpful** - Don't do more than asked
255
+ 2. **Be brutal with scope** - No gold plating
256
+ 3. **Measure twice, cut once** - Test before implementing
257
+ 4. **RTFM** - Research before implementing
258
+ 5. **No backwards compatibility** - Breaking changes OK
259
+ 6. **No fallbacks or defaults** - Fail fast
260
+ 7. **Shift left** - Ask questions, do designs
261
+ 8. **Don't run ahead** - Work with the user
262
+
263
+ ---
264
+
265
+ ## Questions for ChatGPT
266
+
267
+ If you need clarification:
268
+
269
+ 1. Ask about specific edge cases
270
+ 2. Request code snippets for tricky parts
271
+ 3. Confirm implementation details
272
+ 4. Discuss trade-offs
273
+
274
+ Use `[CC]` prefix in messages.
275
+
276
+ ---
277
+
278
+ ## Success Criteria
279
+
280
+ **For v1.0.2 adapter:**
281
+ - [ ] 5/5 consecutive tests return `{ok: true, text: "<response>", ms: ...}`
282
+ - [ ] No empty text responses
283
+ - [ ] No page freezes
284
+ - [ ] Latency roughly stable (within expected range)
285
+
286
+ **For gpt_chat tool:**
287
+ - [ ] Same success criteria as adapter
288
+ - [ ] Works without manual injection
289
+ - [ ] Version auto-detection works
290
+
291
+ ---
292
+
293
+ ## Version History
294
+
295
+ - **v0.1.0** - Initial chrome-control (execute_javascript only)
296
+ - **v0.2.0** - Added execute_javascript_async
297
+ - **v0.3.0** - Added gpt_chat (has empty text bug)
298
+ - **v0.4.0** - (Pending) gpt_chat with v1.0.2 hybrid adapter
299
+
300
+ ---
301
+
302
+ **End of handover**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kelceyp/chrome-control-mcp",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "MCP server for controlling Google Chrome on macOS via AppleScript with async JavaScript support",
5
5
  "main": "server/index.js",
6
6
  "type": "module",
package/server/index.js CHANGED
@@ -575,19 +575,21 @@ class ChromeControlServer {
575
575
  return { content: [{ type: 'text', text: 'Error: message (string) is required' }] };
576
576
  }
577
577
 
578
- const ADAPTER_VERSION = '1.0.0';
578
+ const ADAPTER_VERSION = '1.0.3';
579
579
 
580
- // Strict-core adapter with versioning
580
+ // v1.0.3: Hybrid completion detection (text-length polling + button confirmation)
581
+ // v1.0.3 fix: pickText uses turn container to handle sibling content layouts
581
582
  const ADAPTER_JS = `
582
583
  (() => {
583
584
  if (window.ChatBridge && window.ChatBridge.version === '${ADAPTER_VERSION}') return;
584
585
 
585
586
  const sleep = (ms) => new Promise(r => setTimeout(r, ms));
586
587
  const now = () => performance.now();
588
+ const qAll = (sel, root = document) => Array.from(root.querySelectorAll(sel));
587
589
 
588
590
  const findTextbox = () =>
589
591
  document.querySelector('[role="textbox"][contenteditable="true"]') ||
590
- [...document.querySelectorAll('[contenteditable="true"]')].at(-1) || null;
592
+ qAll('[contenteditable="true"]').at(-1) || null;
591
593
 
592
594
  const findForm = () => { const tb = findTextbox(); return tb?.closest('form') || null; };
593
595
  const findSendButton = () =>
@@ -597,11 +599,52 @@ class ChromeControlServer {
597
599
  return tb.getAttribute('aria-disabled') !== 'true' && !tb.closest('[aria-disabled="true"]');
598
600
  };
599
601
  const countUser = () =>
600
- document.querySelectorAll('[data-message-author-role="user"],[data-author-role="user"]').length;
602
+ qAll('[data-message-author-role="user"],[data-author-role="user"]').length;
601
603
  const countAssistant = () =>
602
- document.querySelectorAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').length;
604
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').length;
603
605
  const lastAssistantNode = () =>
604
- [...document.querySelectorAll('[data-message-author-role="assistant"],[data-author-role="assistant"]')].at(-1) || null;
606
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').at(-1) || null;
607
+
608
+ const pickText = (node) => {
609
+ const turn = lastAssistantTurn();
610
+ if (!turn) return '';
611
+ const c = turn.querySelector('.markdown, article, [data-testid*="content"], [data-message-content]') || turn;
612
+ const t = c.innerText ?? c.textContent ?? '';
613
+ return (t || '').trim();
614
+ };
615
+
616
+ const lastAssistantTurn = () => {
617
+ const turns = qAll('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]');
618
+ for (let i = turns.length - 1; i >= 0; i--) {
619
+ if (turns[i].querySelector('[data-message-author-role="assistant"], [data-author-role="assistant"]')) {
620
+ return turns[i];
621
+ }
622
+ }
623
+ const content = lastAssistantNode();
624
+ return (
625
+ content?.closest('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]') ||
626
+ content ||
627
+ null
628
+ );
629
+ };
630
+
631
+ const hasTurnActions = (turn) => {
632
+ if (!turn) return false;
633
+ const toolbar =
634
+ turn.querySelector('[data-testid*="turn-actions"]') ||
635
+ turn.querySelector('[role="toolbar"]') ||
636
+ null;
637
+ if (!toolbar) return false;
638
+ const btns = toolbar.querySelectorAll(
639
+ 'button[aria-label*="Regenerate"],' +
640
+ 'button[aria-label*="Copy"],' +
641
+ 'button[aria-label*="Share"],' +
642
+ 'button[aria-label*="Like"],' +
643
+ 'button[aria-label*="Dislike"],' +
644
+ '[data-testid*="thumb"]'
645
+ );
646
+ return btns.length > 0;
647
+ };
605
648
 
606
649
  const clearInput = async () => {
607
650
  const tb = findTextbox(); if (!tb) throw new Error('ChatBridge: textbox not found');
@@ -634,6 +677,10 @@ class ChromeControlServer {
634
677
  };
635
678
 
636
679
  const waitForResponseWithBaseline = async (baseline, { idleMs = 1200, timeoutMs = 120000 } = {}) => {
680
+ const idlePrimaryMs = idleMs;
681
+ const idleConfirmMs = 3300;
682
+ const finalButtonGraceMs = 2000;
683
+
637
684
  const t0 = now();
638
685
  const preUser = baseline?.user ?? countUser();
639
686
  const preAsst = baseline?.asst ?? countAssistant();
@@ -641,34 +688,57 @@ class ChromeControlServer {
641
688
  if (countUser() < preUser + 1) {
642
689
  while (now() - t0 < timeoutMs) {
643
690
  if (countUser() >= preUser + 1) break;
644
- await new Promise(r => setTimeout(r, 60));
691
+ await sleep(60);
692
+ }
693
+ if (countUser() < preUser + 1) {
694
+ return { ok: false, reason: 'userMessageNotCommitted', ms: now() - t0 };
645
695
  }
646
- if (countUser() < preUser + 1) return { ok: false, reason: 'userMessageNotCommitted', ms: now() - t0 };
647
696
  }
648
697
 
649
698
  if (countAssistant() < preAsst + 1) {
650
699
  while (now() - t0 < timeoutMs) {
651
700
  if (countAssistant() >= preAsst + 1) break;
652
- await new Promise(r => setTimeout(r, 60));
701
+ await sleep(60);
702
+ }
703
+ if (countAssistant() < preAsst + 1) {
704
+ return { ok: false, reason: 'assistantNeverStarted', ms: now() - t0 };
653
705
  }
654
- if (countAssistant() < preAsst + 1) return { ok: false, reason: 'assistantNeverStarted', ms: now() - t0 };
655
706
  }
656
707
 
657
- const node = lastAssistantNode();
708
+ let lastLen = -1;
658
709
  let lastChange = now();
659
- const obs = node ? new MutationObserver(() => { lastChange = now(); }) : null;
660
- if (node && obs) obs.observe(node, { subtree: true, childList: true, characterData: true });
710
+ let confirmStart = null;
661
711
 
662
712
  while (now() - t0 < timeoutMs) {
663
- const idle = now() - lastChange >= idleMs;
664
- if (idle && inputEnabled()) {
665
- if (obs) obs.disconnect();
666
- const text = (node?.innerText ?? node?.textContent ?? '').trim();
667
- return { ok: true, text, ms: now() - t0 };
713
+ const node = lastAssistantNode();
714
+ const txt = pickText(node);
715
+ const len = txt.length;
716
+
717
+ if (len !== lastLen) {
718
+ lastLen = len;
719
+ lastChange = now();
720
+ confirmStart = null;
721
+ }
722
+
723
+ const idle = now() - lastChange;
724
+
725
+ if (idle >= idlePrimaryMs && inputEnabled()) {
726
+ if (idle >= idleConfirmMs) {
727
+ const turn = lastAssistantTurn();
728
+ if (hasTurnActions(turn)) {
729
+ return { ok: true, text: txt, ms: now() - t0 };
730
+ }
731
+
732
+ if (confirmStart == null) confirmStart = now();
733
+ if (now() - confirmStart >= finalButtonGraceMs) {
734
+ return { ok: true, text: txt, ms: now() - t0, note: 'noButtonsConfirm' };
735
+ }
736
+ }
668
737
  }
669
- await new Promise(r => setTimeout(r, 80));
738
+
739
+ await sleep(100);
670
740
  }
671
- if (obs) obs.disconnect();
741
+
672
742
  return { ok: false, reason: 'timeout', ms: now() - t0 };
673
743
  };
674
744
 
package/test-runner.js ADDED
@@ -0,0 +1,170 @@
1
+ // Test runner that installs adapter if needed and sends test message
2
+ const testNumber = arguments[0] || 2;
3
+
4
+ // Only install if not already present or wrong version
5
+ if (!window.ChatBridge || window.ChatBridge.version !== '1.0.2' || !window.ChatBridge.sendMessage) {
6
+ const ADAPTER_VERSION = '1.0.2';
7
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
8
+ const now = () => performance.now();
9
+ const qAll = (sel, root = document) => Array.from(root.querySelectorAll(sel));
10
+
11
+ const countUser = () =>
12
+ qAll('[data-message-author-role="user"],[data-author-role="user"]').length;
13
+ const countAssistant = () =>
14
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').length;
15
+ const lastAssistantNode = () =>
16
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').at(-1) || null;
17
+ const inputEnabled = () => {
18
+ const tb =
19
+ document.querySelector('[role="textbox"][contenteditable="true"]') ||
20
+ qAll('[contenteditable="true"]').at(-1);
21
+ return !!tb && tb.getAttribute('aria-disabled') !== 'true' && !tb.closest('[aria-disabled="true"]');
22
+ };
23
+ const pickText = (node) => {
24
+ const n = node || lastAssistantNode();
25
+ if (!n) return '';
26
+ const c = n.querySelector('.markdown, article') || n;
27
+ const t = c.innerText ?? c.textContent ?? '';
28
+ return (t || '').trim();
29
+ };
30
+ const lastAssistantTurn = () => {
31
+ const turns = qAll('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]');
32
+ for (let i = turns.length - 1; i >= 0; i--) {
33
+ if (turns[i].querySelector('[data-message-author-role="assistant"], [data-author-role="assistant"]')) {
34
+ return turns[i];
35
+ }
36
+ }
37
+ const content = lastAssistantNode();
38
+ return (
39
+ content?.closest('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]') ||
40
+ content ||
41
+ null
42
+ );
43
+ };
44
+ const hasTurnActions = (turn) => {
45
+ if (!turn) return false;
46
+ const toolbar =
47
+ turn.querySelector('[data-testid*="turn-actions"]') ||
48
+ turn.querySelector('[role="toolbar"]') ||
49
+ null;
50
+ if (!toolbar) return false;
51
+ const btns = toolbar.querySelectorAll(
52
+ 'button[aria-label*="Regenerate"],' +
53
+ 'button[aria-label*="Copy"],' +
54
+ 'button[aria-label*="Share"],' +
55
+ 'button[aria-label*="Like"],' +
56
+ 'button[aria-label*="Dislike"],' +
57
+ '[data-testid*="thumb"]'
58
+ );
59
+ return btns.length > 0;
60
+ };
61
+
62
+ const waitForResponseWithBaseline = async (
63
+ baseline,
64
+ {
65
+ timeoutMs = 120000,
66
+ idlePrimaryMs = 1200,
67
+ idleConfirmMs = 3300,
68
+ finalButtonGraceMs = 2000
69
+ } = {}
70
+ ) => {
71
+ const t0 = now();
72
+ const preUser = baseline?.user ?? countUser();
73
+ const preAsst = baseline?.asst ?? countAssistant();
74
+
75
+ if (countUser() < preUser + 1) {
76
+ while (now() - t0 < timeoutMs) {
77
+ if (countUser() >= preUser + 1) break;
78
+ await sleep(60);
79
+ }
80
+ if (countUser() < preUser + 1) {
81
+ return { ok: false, reason: 'userMessageNotCommitted', ms: now() - t0 };
82
+ }
83
+ }
84
+
85
+ if (countAssistant() < preAsst + 1) {
86
+ while (now() - t0 < timeoutMs) {
87
+ if (countAssistant() >= preAsst + 1) break;
88
+ await sleep(60);
89
+ }
90
+ if (countAssistant() < preAsst + 1) {
91
+ return { ok: false, reason: 'assistantNeverStarted', ms: now() - t0 };
92
+ }
93
+ }
94
+
95
+ let lastLen = -1;
96
+ let lastChange = now();
97
+ let confirmStart = null;
98
+
99
+ while (now() - t0 < timeoutMs) {
100
+ const node = lastAssistantNode();
101
+ const txt = pickText(node);
102
+ const len = txt.length;
103
+
104
+ if (len !== lastLen) {
105
+ lastLen = len;
106
+ lastChange = now();
107
+ confirmStart = null;
108
+ }
109
+
110
+ const idle = now() - lastChange;
111
+
112
+ if (idle >= idlePrimaryMs && inputEnabled()) {
113
+ if (idle >= idleConfirmMs) {
114
+ const turn = lastAssistantTurn();
115
+ if (hasTurnActions(turn)) {
116
+ return { ok: true, text: txt, ms: now() - t0 };
117
+ }
118
+
119
+ if (confirmStart == null) confirmStart = now();
120
+ if (now() - confirmStart >= finalButtonGraceMs) {
121
+ return { ok: true, text: txt, ms: now() - t0, note: 'noButtonsConfirm' };
122
+ }
123
+ }
124
+ }
125
+
126
+ await sleep(100);
127
+ }
128
+
129
+ return { ok: false, reason: 'timeout', ms: now() - t0 };
130
+ };
131
+
132
+ const sendMessage = async (message) => {
133
+ const baseline = { user: countUser(), asst: countAssistant() };
134
+
135
+ const textbox =
136
+ document.querySelector('[role="textbox")[contenteditable="true"]') ||
137
+ qAll('[contenteditable="true"]').at(-1);
138
+
139
+ if (!textbox) {
140
+ return { ok: false, reason: 'noTextbox' };
141
+ }
142
+
143
+ textbox.focus();
144
+ textbox.innerText = message;
145
+ textbox.dispatchEvent(new Event('input', { bubbles: true }));
146
+
147
+ await sleep(100);
148
+ const sendBtn = document.querySelector('[data-testid="send-button"]') ||
149
+ qAll('button').find(b =>
150
+ b.getAttribute('aria-label')?.includes('Send') ||
151
+ b.innerText?.includes('Send')
152
+ );
153
+
154
+ if (!sendBtn) {
155
+ return { ok: false, reason: 'noSendButton' };
156
+ }
157
+
158
+ sendBtn.click();
159
+ return await waitForResponseWithBaseline(baseline);
160
+ };
161
+
162
+ // Install adapter
163
+ window.ChatBridge = {
164
+ version: ADAPTER_VERSION,
165
+ sendMessage
166
+ };
167
+ }
168
+
169
+ // Run test
170
+ return await window.ChatBridge.sendMessage(`[CC] Test ${testNumber}/5: Consistency check - reply TEST-OK-${testNumber}`);
package/test-simple.js ADDED
@@ -0,0 +1,166 @@
1
+ // First install the adapter, then send a test message
2
+ const ADAPTER_VERSION = '1.0.2';
3
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
4
+ const now = () => performance.now();
5
+ const qAll = (sel, root = document) => Array.from(root.querySelectorAll(sel));
6
+
7
+ const countUser = () =>
8
+ qAll('[data-message-author-role="user"],[data-author-role="user"]').length;
9
+ const countAssistant = () =>
10
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').length;
11
+ const lastAssistantNode = () =>
12
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').at(-1) || null;
13
+ const inputEnabled = () => {
14
+ const tb =
15
+ document.querySelector('[role="textbox"][contenteditable="true"]') ||
16
+ qAll('[contenteditable="true"]').at(-1);
17
+ return !!tb && tb.getAttribute('aria-disabled') !== 'true' && !tb.closest('[aria-disabled="true"]');
18
+ };
19
+ const pickText = (node) => {
20
+ const n = node || lastAssistantNode();
21
+ if (!n) return '';
22
+ const c = n.querySelector('.markdown, article') || n;
23
+ const t = c.innerText ?? c.textContent ?? '';
24
+ return (t || '').trim();
25
+ };
26
+ const lastAssistantTurn = () => {
27
+ const turns = qAll('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]');
28
+ for (let i = turns.length - 1; i >= 0; i--) {
29
+ if (turns[i].querySelector('[data-message-author-role="assistant"], [data-author-role="assistant"]')) {
30
+ return turns[i];
31
+ }
32
+ }
33
+ const content = lastAssistantNode();
34
+ return (
35
+ content?.closest('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]') ||
36
+ content ||
37
+ null
38
+ );
39
+ };
40
+ const hasTurnActions = (turn) => {
41
+ if (!turn) return false;
42
+ const toolbar =
43
+ turn.querySelector('[data-testid*="turn-actions"]') ||
44
+ turn.querySelector('[role="toolbar"]') ||
45
+ null;
46
+ if (!toolbar) return false;
47
+ const btns = toolbar.querySelectorAll(
48
+ 'button[aria-label*="Regenerate"],' +
49
+ 'button[aria-label*="Copy"],' +
50
+ 'button[aria-label*="Share"],' +
51
+ 'button[aria-label*="Like"],' +
52
+ 'button[aria-label*="Dislike"],' +
53
+ '[data-testid*="thumb"]'
54
+ );
55
+ return btns.length > 0;
56
+ };
57
+
58
+ const waitForResponseWithBaseline = async (
59
+ baseline,
60
+ {
61
+ timeoutMs = 120000,
62
+ idlePrimaryMs = 1200,
63
+ idleConfirmMs = 3300,
64
+ finalButtonGraceMs = 2000
65
+ } = {}
66
+ ) => {
67
+ const t0 = now();
68
+ const preUser = baseline?.user ?? countUser();
69
+ const preAsst = baseline?.asst ?? countAssistant();
70
+
71
+ if (countUser() < preUser + 1) {
72
+ while (now() - t0 < timeoutMs) {
73
+ if (countUser() >= preUser + 1) break;
74
+ await sleep(60);
75
+ }
76
+ if (countUser() < preUser + 1) {
77
+ return { ok: false, reason: 'userMessageNotCommitted', ms: now() - t0 };
78
+ }
79
+ }
80
+
81
+ if (countAssistant() < preAsst + 1) {
82
+ while (now() - t0 < timeoutMs) {
83
+ if (countAssistant() >= preAsst + 1) break;
84
+ await sleep(60);
85
+ }
86
+ if (countAssistant() < preAsst + 1) {
87
+ return { ok: false, reason: 'assistantNeverStarted', ms: now() - t0 };
88
+ }
89
+ }
90
+
91
+ let lastLen = -1;
92
+ let lastChange = now();
93
+ let confirmStart = null;
94
+
95
+ while (now() - t0 < timeoutMs) {
96
+ const node = lastAssistantNode();
97
+ const txt = pickText(node);
98
+ const len = txt.length;
99
+
100
+ if (len !== lastLen) {
101
+ lastLen = len;
102
+ lastChange = now();
103
+ confirmStart = null;
104
+ }
105
+
106
+ const idle = now() - lastChange;
107
+
108
+ if (idle >= idlePrimaryMs && inputEnabled()) {
109
+ if (idle >= idleConfirmMs) {
110
+ const turn = lastAssistantTurn();
111
+ if (hasTurnActions(turn)) {
112
+ return { ok: true, text: txt, ms: now() - t0 };
113
+ }
114
+
115
+ if (confirmStart == null) confirmStart = now();
116
+ if (now() - confirmStart >= finalButtonGraceMs) {
117
+ return { ok: true, text: txt, ms: now() - t0, note: 'noButtonsConfirm' };
118
+ }
119
+ }
120
+ }
121
+
122
+ await sleep(100);
123
+ }
124
+
125
+ return { ok: false, reason: 'timeout', ms: now() - t0 };
126
+ };
127
+
128
+ const sendMessage = async (message) => {
129
+ const baseline = { user: countUser(), asst: countAssistant() };
130
+
131
+ const textbox =
132
+ document.querySelector('[role="textbox"][contenteditable="true"]') ||
133
+ qAll('[contenteditable="true"]').at(-1);
134
+
135
+ if (!textbox) {
136
+ return { ok: false, reason: 'noTextbox' };
137
+ }
138
+
139
+ textbox.focus();
140
+ textbox.innerText = message;
141
+ textbox.dispatchEvent(new Event('input', { bubbles: true }));
142
+
143
+ await sleep(100);
144
+ const sendBtn = document.querySelector('[data-testid="send-button"]') ||
145
+ qAll('button').find(b =>
146
+ b.getAttribute('aria-label')?.includes('Send') ||
147
+ b.innerText?.includes('Send')
148
+ );
149
+
150
+ if (!sendBtn) {
151
+ return { ok: false, reason: 'noSendButton' };
152
+ }
153
+
154
+ sendBtn.click();
155
+ return await waitForResponseWithBaseline(baseline);
156
+ };
157
+
158
+ // Install adapter
159
+ if (!window.ChatBridge) {
160
+ window.ChatBridge = {};
161
+ }
162
+ window.ChatBridge.version = ADAPTER_VERSION;
163
+ window.ChatBridge.sendMessage = sendMessage;
164
+
165
+ // Send test message and return result
166
+ return await sendMessage('[CC] Test 1/5: Verify v1.0.2 adapter - reply TEST-OK-1');
@@ -0,0 +1,207 @@
1
+ // Test script for v1.0.2 ChatGPT adapter
2
+ // This injects the new hybrid approach and sends a test message
3
+
4
+ (async () => {
5
+ const ADAPTER_VERSION = '1.0.2';
6
+
7
+ // === Helper functions ===
8
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
9
+ const now = () => performance.now();
10
+ const qAll = (sel, root = document) => Array.from(root.querySelectorAll(sel));
11
+
12
+ const countUser = () =>
13
+ qAll('[data-message-author-role="user"],[data-author-role="user"]').length;
14
+
15
+ const countAssistant = () =>
16
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').length;
17
+
18
+ const lastAssistantNode = () =>
19
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').at(-1) || null;
20
+
21
+ const inputEnabled = () => {
22
+ const tb =
23
+ document.querySelector('[role="textbox"][contenteditable="true"]') ||
24
+ qAll('[contenteditable="true"]').at(-1);
25
+ return !!tb && tb.getAttribute('aria-disabled') !== 'true' && !tb.closest('[aria-disabled="true"]');
26
+ };
27
+
28
+ const pickText = (node) => {
29
+ const n = node || lastAssistantNode();
30
+ if (!n) return '';
31
+ const c = n.querySelector('.markdown, article') || n;
32
+ const t = c.innerText ?? c.textContent ?? '';
33
+ return (t || '').trim();
34
+ };
35
+
36
+ const lastAssistantTurn = () => {
37
+ const turns = qAll('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]');
38
+ for (let i = turns.length - 1; i >= 0; i--) {
39
+ if (turns[i].querySelector('[data-message-author-role="assistant"], [data-author-role="assistant"]')) {
40
+ return turns[i];
41
+ }
42
+ }
43
+ const content = lastAssistantNode();
44
+ return (
45
+ content?.closest('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]') ||
46
+ content ||
47
+ null
48
+ );
49
+ };
50
+
51
+ const hasTurnActions = (turn) => {
52
+ if (!turn) return false;
53
+ const toolbar =
54
+ turn.querySelector('[data-testid*="turn-actions"]') ||
55
+ turn.querySelector('[role="toolbar"]') ||
56
+ null;
57
+ if (!toolbar) return false;
58
+ const btns = toolbar.querySelectorAll(
59
+ 'button[aria-label*="Regenerate"],' +
60
+ 'button[aria-label*="Copy"],' +
61
+ 'button[aria-label*="Share"],' +
62
+ 'button[aria-label*="Like"],' +
63
+ 'button[aria-label*="Dislike"],' +
64
+ '[data-testid*="thumb"]'
65
+ );
66
+ return btns.length > 0;
67
+ };
68
+
69
+ // === v1.0.2 waitForResponseWithBaseline ===
70
+ const waitForResponseWithBaseline = async (
71
+ baseline,
72
+ {
73
+ timeoutMs = 120000,
74
+ idlePrimaryMs = 1200, // normal token-stop idle
75
+ idleConfirmMs = 3300, // thinking-lull idle before checking buttons
76
+ finalButtonGraceMs = 2000 // how long to keep trying buttons before accepting stable text
77
+ } = {}
78
+ ) => {
79
+ // ----- Conversation guards -----
80
+ const t0 = now();
81
+ const preUser = baseline?.user ?? countUser();
82
+ const preAsst = baseline?.asst ?? countAssistant();
83
+
84
+ // Require: user bubble committed (+1), tolerate if already present
85
+ if (countUser() < preUser + 1) {
86
+ while (now() - t0 < timeoutMs) {
87
+ if (countUser() >= preUser + 1) break;
88
+ await sleep(60);
89
+ }
90
+ if (countUser() < preUser + 1) {
91
+ return { ok: false, reason: 'userMessageNotCommitted', ms: now() - t0 };
92
+ }
93
+ }
94
+
95
+ // Require: assistant bubble appeared (+1)
96
+ if (countAssistant() < preAsst + 1) {
97
+ while (now() - t0 < timeoutMs) {
98
+ if (countAssistant() >= preAsst + 1) break;
99
+ await sleep(60);
100
+ }
101
+ if (countAssistant() < preAsst + 1) {
102
+ return { ok: false, reason: 'assistantNeverStarted', ms: now() - t0 };
103
+ }
104
+ }
105
+
106
+ // ----- Hybrid completion loop -----
107
+ let lastLen = -1;
108
+ let lastChange = now();
109
+ let confirmStart = null;
110
+
111
+ while (now() - t0 < timeoutMs) {
112
+ const node = lastAssistantNode();
113
+ const txt = pickText(node);
114
+ const len = txt.length;
115
+
116
+ if (len !== lastLen) {
117
+ lastLen = len;
118
+ lastChange = now();
119
+ confirmStart = null; // reset confirmation window on new tokens/layout changes
120
+ }
121
+
122
+ const idle = now() - lastChange;
123
+
124
+ // Primary: text-length stability
125
+ if (idle >= idlePrimaryMs && inputEnabled()) {
126
+ // After a longer lull, attempt toolbar confirmation
127
+ if (idle >= idleConfirmMs) {
128
+ const turn = lastAssistantTurn();
129
+ if (hasTurnActions(turn)) {
130
+ return { ok: true, text: txt, ms: now() - t0 };
131
+ }
132
+
133
+ // Start/continue a brief grace window for toolbar to show; then accept stable text
134
+ if (confirmStart == null) confirmStart = now();
135
+ if (now() - confirmStart >= finalButtonGraceMs) {
136
+ return { ok: true, text: txt, ms: now() - t0, note: 'noButtonsConfirm' };
137
+ }
138
+ }
139
+ // Else: keep accumulating idle time
140
+ }
141
+
142
+ await sleep(100); // poll cadence
143
+ }
144
+
145
+ return { ok: false, reason: 'timeout', ms: now() - t0 };
146
+ };
147
+
148
+ // === sendMessage function ===
149
+ const sendMessage = async (message) => {
150
+ const baseline = { user: countUser(), asst: countAssistant() };
151
+
152
+ const textbox =
153
+ document.querySelector('[role="textbox"][contenteditable="true"]') ||
154
+ qAll('[contenteditable="true"]').at(-1);
155
+
156
+ if (!textbox) {
157
+ return { ok: false, reason: 'noTextbox' };
158
+ }
159
+
160
+ // Set message
161
+ textbox.focus();
162
+ textbox.innerText = message;
163
+
164
+ // Trigger input event
165
+ textbox.dispatchEvent(new Event('input', { bubbles: true }));
166
+
167
+ // Find and click send button
168
+ await sleep(100);
169
+ const sendBtn = document.querySelector('[data-testid="send-button"]') ||
170
+ qAll('button').find(b =>
171
+ b.getAttribute('aria-label')?.includes('Send') ||
172
+ b.innerText?.includes('Send')
173
+ );
174
+
175
+ if (!sendBtn) {
176
+ return { ok: false, reason: 'noSendButton' };
177
+ }
178
+
179
+ sendBtn.click();
180
+
181
+ // Wait for response
182
+ return await waitForResponseWithBaseline(baseline);
183
+ };
184
+
185
+ // === Install adapter in window ===
186
+ if (!window.ChatBridge) {
187
+ window.ChatBridge = {};
188
+ }
189
+
190
+ window.ChatBridge.version = ADAPTER_VERSION;
191
+ window.ChatBridge.sendMessage = sendMessage;
192
+ window.ChatBridge.waitForResponseWithBaseline = waitForResponseWithBaseline;
193
+ window.ChatBridge.getBaseline = () => ({
194
+ user: countUser(),
195
+ asst: countAssistant()
196
+ });
197
+
198
+ // === Send test message ===
199
+ const testMessage = '[CC] Test 1/5: Hybrid approach - reply HYBRID-OK-1';
200
+ const result = await sendMessage(testMessage);
201
+
202
+ return {
203
+ adapterVersion: ADAPTER_VERSION,
204
+ testMessage,
205
+ result
206
+ };
207
+ })();