@tomflow/chatloop-extension 0.4.15 → 0.4.20

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.
@@ -5,22 +5,44 @@ const detailNode=document.getElementById('details');
5
5
  const show=(status,detail)=>{statusNode.textContent=status;detailNode.textContent=detail;document.body.dataset.result=status==='SUCCESS'?'success':'error';};
6
6
  const pause=ms=>new Promise(r=>setTimeout(r,ms));
7
7
  const safeCode=code=>/^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'ENTRY_TEST_UNVERIFIED';
8
- async function readNewChat(id){
8
+ async function readNewChat(id,recoverTestAt=false,recoverExactDraft=''){
9
9
  const end=Date.now()+90000;
10
+ let cleaned=false;
10
11
  while(Date.now()<end){
11
12
  const tab=await chrome.tabs.get(id).catch(()=>null);
12
13
  if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
13
14
  if(tab.url==='https://chatgpt.com/'){
14
- const proof=await chrome.scripting.executeScript({target:{tabId:id},func:()=>{
15
- if(location.origin!=='https://chatgpt.com'||location.pathname!=='/')return false;
16
- const mains=[...document.querySelectorAll('main')].filter(e=>e.getClientRects().length);
17
- const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
18
- ||document.querySelector('[contenteditable="true"][data-composer-markdown]');
19
- return mains.length===1&&editor?.getClientRects().length>0
20
- &&editor.isContentEditable&&!((editor.innerText||'').trim())
21
- &&!mains[0].querySelector('[data-chatgpt-search-message-ids],[data-message-author-role]');
22
- }}).catch(()=>null);
23
- if(proof?.[0]?.result===true)return;
15
+ const proof=await chrome.scripting.executeScript({target:{tabId:id},
16
+ func:(recover,exactDraft)=>{
17
+ if(location.origin!=='https://chatgpt.com'||location.pathname!=='/')return false;
18
+ const mains=[...document.querySelectorAll('main')].filter(e=>e.getClientRects().length);
19
+ const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
20
+ ||document.querySelector('[contenteditable="true"][data-composer-markdown]');
21
+ if(mains.length!==1||!editor?.getClientRects().length||!editor.isContentEditable
22
+ ||mains[0].querySelector('[data-chatgpt-search-message-ids],[data-message-author-role]'))
23
+ return false;
24
+ const current=(editor.innerText||editor.textContent||'').trim();
25
+ if(!current)return 'READY';
26
+ const canonical=value=>String(value||'').replace(/\s+/g,'');
27
+ const exactRecovery=typeof exactDraft==='string'&&!!exactDraft
28
+ &&canonical(current)===canonical(exactDraft);
29
+ if(!recover&& !exactRecovery)return 'HAS_DRAFT';
30
+ if(recover&&current!=='@'&&!exactRecovery)return 'HAS_DRAFT';
31
+ // Only a verified leftover "@" or byte-equivalent earlier TEST_ONLY
32
+ // draft may be cleared, on the newly created empty Chat home. Never
33
+ // touch other drafts, user turns or existing Chat tabs.
34
+ editor.focus();
35
+ const selection=window.getSelection(),range=document.createRange();
36
+ range.selectNodeContents(editor);selection.removeAllRanges();selection.addRange(range);
37
+ if(!document.execCommand('delete',false))return 'RECOVERY_FAILED';
38
+ return !(editor.innerText||editor.textContent||'').trim()
39
+ ?'RECOVERED_DRAFT':'RECOVERY_FAILED';
40
+ },args:[recoverTestAt&&!cleaned,cleaned?'':recoverExactDraft]}).catch(()=>null);
41
+ const state=proof?.[0]?.result;
42
+ if(state==='READY')return;
43
+ if(state==='RECOVERED_DRAFT'){cleaned=true;continue;}
44
+ if(state==='HAS_DRAFT')throw Error('ENTRY_COMPOSER_HAS_DRAFT');
45
+ if(state==='RECOVERY_FAILED')throw Error('ENTRY_AT_RECOVERY_FAILED');
24
46
  }
25
47
  await pause(320);
26
48
  }
@@ -39,22 +61,34 @@ async function nativeMentionAndSend(id,appId,prompt){
39
61
  ||!editor||!visible(editor)||!editor.isContentEditable
40
62
  ||(editor.innerText||editor.textContent||'').trim())
41
63
  return fail('ENTRY_EDITOR_UNVERIFIED');
64
+ // Commit the natural-language task to the host editor first. Selecting
65
+ // a native App mention can rehydrate the composer and otherwise discard
66
+ // text entered immediately after the selection transaction.
42
67
  editor.focus();
68
+ if(!document.execCommand('insertText',false,prompt))return fail('ENTRY_PROMPT_INPUT_FAILED');
69
+ await wait(700);
70
+ if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
71
+ return fail('ENTRY_PROMPT_NOT_VISIBLE');
72
+ const selection=window.getSelection(),range=document.createRange();
73
+ range.selectNodeContents(editor);range.collapse(true);
74
+ selection.removeAllRanges();selection.addRange(range);
43
75
  if(!document.execCommand('insertText',false,'@'))return fail('ENTRY_AT_INPUT_FAILED');
44
76
  let choice=null,diagnostic='';
45
- const selectors=['[role="option"]','[role="menuitem"]','[cmdk-item]',
77
+ const selectors=['button[data-plugin-impression-id]','[role="option"]','[role="menuitem"]','[cmdk-item]',
46
78
  '[data-testid*="app-item"]','[data-testid*="mention-item"]'];
47
79
  for(let i=0;i<55;i++){
48
80
  if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
49
81
  const nodes=[...document.querySelectorAll(selectors.join(','))]
50
82
  .filter(visible).filter(e=>(e.innerText||'').includes('Chat Loop'));
83
+ const matching=nodes.filter(e=>e.getAttribute('data-plugin-impression-id')===appId);
84
+ if(matching.length===1){choice=matching[0];break;}
51
85
  const exact=nodes.filter(e=>{
52
86
  const t=(e.innerText||'').trim();
53
87
  return t==='Chat Loop'||t.startsWith('Chat Loop\n');
54
88
  });
55
89
  if(exact.length===1){choice=exact[0];break;}
56
90
  if(!exact.length && nodes.length===1){choice=nodes[0];break;}
57
- diagnostic=nodes.slice(0,4).map(e=>e.getAttribute('role')+':'+(e.innerText||'').slice(0,55)).join('|');
91
+ diagnostic=nodes.slice(0,4).map(e=>e.getAttribute('data-plugin-impression-id')+':'+(e.innerText||'').slice(0,55)).join('|');
58
92
  await wait(220);
59
93
  }
60
94
  if(!choice)return fail('ENTRY_NATIVE_APP_OPTION_MISSING',diagnostic);
@@ -70,14 +104,14 @@ async function nativeMentionAndSend(id,appId,prompt){
70
104
  await wait(120);
71
105
  }
72
106
  if(!native)return fail('ENTRY_NATIVE_MENTION_UNVERIFIED',editor.innerHTML);
73
- editor.focus();
74
- if(!document.execCommand('insertText',false,' '+prompt))return fail('ENTRY_PROMPT_INPUT_FAILED');
75
- for(let i=0;i<25;i++){
76
- if(canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))break;
77
- await wait(130);
107
+ // Wait for the host selection transaction to settle; never rely on
108
+ // a transient DOM text match before clicking its native send button.
109
+ for(let i=0;i<5;i++){
110
+ await wait(240);
111
+ if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED_BEFORE_SEND');
112
+ if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
113
+ return fail('ENTRY_PROMPT_LOST_ON_MENTION');
78
114
  }
79
- if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
80
- return fail('ENTRY_PROMPT_NOT_VISIBLE');
81
115
  const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
82
116
  if(!tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
83
117
  ||(e.getAttribute('data-app-mention-path')||'').includes(appId)
@@ -97,7 +131,7 @@ async function nativeMentionAndSend(id,appId,prompt){
97
131
  if(r.status!=='CLICKED_ONCE')throw Error(safeCode(r.code));
98
132
  }
99
133
  async function verifyNativeUserTurn(id,appId,prompt){
100
- const end=Date.now()+120000;let last=null,stable=0;
134
+ const end=Date.now()+120000;let last=null,stable=0,mismatch=0;
101
135
  while(Date.now()<end){
102
136
  const tab=await chrome.tabs.get(id).catch(()=>null);
103
137
  if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
@@ -106,11 +140,12 @@ async function verifyNativeUserTurn(id,appId,prompt){
106
140
  const r=await chrome.scripting.executeScript({target:{tabId:id},
107
141
  func:(appId,prompt)=>{
108
142
  if(location.origin!=='https://chatgpt.com')return null;
109
- const main=document.querySelector('main');
110
- const users=[...main.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')]
143
+ // ChatGPT can render conversation turns outside its composer <main>.
144
+ // A main-scoped read silently misses real user turns in that layout.
145
+ const users=[...document.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')]
111
146
  .filter(x=>x.getAttribute('data-chatgpt-search-unit-key')?.endsWith(':user'));
112
147
  if(!users.length){
113
- users.push(...main.querySelectorAll('[data-message-author-role="user"]'));
148
+ users.push(...document.querySelectorAll('[data-message-author-role="user"]'));
114
149
  }
115
150
  const u=users.at(-1);
116
151
  const key=u?.getAttribute('data-message-id')
@@ -128,6 +163,9 @@ async function verifyNativeUserTurn(id,appId,prompt){
128
163
  const v=r?.[0]?.result;
129
164
  if(v?.userCount>1||v?.ids?.some(x=>x!==v.ids[0]))
130
165
  throw Error('ENTRY_DUPLICATE_USER_TURN');
166
+ if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&!v.userKey){
167
+ if(++mismatch>=4)throw Error('ENTRY_USER_TURN_CONTENT_MISMATCH');
168
+ }else mismatch=0;
131
169
  if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&v.userKey){
132
170
  const k=path+'|'+v.userKey;
133
171
  stable=last===k?stable+1:1;last=k;
@@ -161,14 +199,25 @@ async function run(){
161
199
  const durable=await chrome.runtime.sendNativeMessage(HOST,{op:'session-read'});
162
200
  if(durable?.status!=='OK'||durable.session&&!['DONE'].includes(durable.session.phase))
163
201
  throw Error('ENTRY_TEST_ACTIVE_OWNER');
164
- show('RUNNING','新普通 Chat 正在加载;仅验证原生 App 入口,不进行批准或 Start。');
165
- tab=await chrome.tabs.create({url:'https://chatgpt.com/',active:true,
166
- windowId:own.windowId,openerTabId:own.id});
167
- if(!Number.isSafeInteger(tab?.id))throw Error('ENTRY_NEW_TAB_UNVERIFIED');
168
- await readNewChat(tab.id);
169
- await nativeMentionAndSend(tab.id,intent.appId,intent.prompt);
170
- clicked=true;
171
- const result=await verifyNativeUserTurn(tab.id,intent.appId,intent.prompt);
202
+ let result;
203
+ if(intent.verifyChatUrl){
204
+ // Pure receipt recovery. Never click, resend, adopt or modify an existing Chat.
205
+ show('RUNNING','只读核对已存在 Chat 的唯一原生 @ App 用户消息。');
206
+ const candidates=await chrome.tabs.query({url:intent.verifyChatUrl});
207
+ const matches=candidates.filter(t=>t.url===intent.verifyChatUrl
208
+ &&Number.isSafeInteger(t.id));
209
+ if(matches.length!==1)throw Error('ENTRY_VERIFY_TAB_UNVERIFIED');
210
+ result=await verifyNativeUserTurn(matches[0].id,intent.appId,intent.prompt);
211
+ }else{
212
+ show('RUNNING','新普通 Chat 正在加载;仅验证原生 App 入口,不进行批准或 Start。');
213
+ tab=await chrome.tabs.create({url:'https://chatgpt.com/',active:true,
214
+ windowId:own.windowId,openerTabId:own.id});
215
+ if(!Number.isSafeInteger(tab?.id))throw Error('ENTRY_NEW_TAB_UNVERIFIED');
216
+ await readNewChat(tab.id,intent.recoverTestAt===true,intent.recoverExactDraft||'');
217
+ await nativeMentionAndSend(tab.id,intent.appId,intent.prompt);
218
+ clicked=true;
219
+ result=await verifyNativeUserTurn(tab.id,intent.appId,intent.prompt);
220
+ }
172
221
  const stored=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
173
222
  nonce:proof.nonce,action:'entry_test',status:'OK',payload:JSON.stringify(result)});
174
223
  if(stored?.status!=='SAVED'||stored.id!==id)throw Error('ENTRY_TEST_NATIVE_RECEIPT_UNVERIFIED');
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.15",
4
+ "version": "0.4.20",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
package/lib/bridge.mjs CHANGED
@@ -51,13 +51,25 @@ export function requestDir(id) {
51
51
  function validateIntent(action, intent) {
52
52
  if(action==='entry_test'){
53
53
  if(!intent||typeof intent!=='object'||Array.isArray(intent)
54
- ||Object.keys(intent).some(k=>!['prompt','appId','testOnly','confirmed'].includes(k))
54
+ ||Object.keys(intent).some(k=>!['prompt','appId','testOnly','confirmed','recoverTestAt','recoverExactDraft','verifyChatUrl'].includes(k))
55
55
  ||typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
56
56
  ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)
57
57
  ||typeof intent.appId!=='string'||!/^asdk_app_[a-z0-9]{20,64}$/.test(intent.appId)
58
- ||intent.testOnly!==true||intent.confirmed!==true)
58
+ ||intent.testOnly!==true||intent.confirmed!==true
59
+ ||(intent.verifyChatUrl!==undefined&&(
60
+ typeof intent.verifyChatUrl!=='string'
61
+ ||!/^https:\/\/chatgpt\.com\/c\/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.verifyChatUrl)
62
+ ||intent.recoverTestAt!==undefined||intent.recoverExactDraft!==undefined))
63
+ ||(intent.recoverTestAt!==undefined&&intent.recoverTestAt!==true)
64
+ ||(intent.recoverExactDraft!==undefined
65
+ &&(typeof intent.recoverExactDraft!=='string'
66
+ ||!intent.recoverExactDraft.trim()
67
+ ||intent.recoverExactDraft.length>4000)))
59
68
  throw Object.assign(Error('Explicit test-only entry intent required'),{code:'INVALID_ENTRY_TEST_INTENT'});
60
- return {prompt:intent.prompt,appId:intent.appId,testOnly:true,confirmed:true};
69
+ return {prompt:intent.prompt,appId:intent.appId,testOnly:true,confirmed:true,
70
+ ...(intent.recoverTestAt?{recoverTestAt:true}:{}),
71
+ ...(intent.recoverExactDraft?{recoverExactDraft:intent.recoverExactDraft}:{}),
72
+ ...(intent.verifyChatUrl?{verifyChatUrl:intent.verifyChatUrl}:{})};
61
73
  }
62
74
  if(action==='start'){
63
75
  if(!intent||typeof intent!=='object'||Array.isArray(intent)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.15",
3
+ "version": "0.4.20",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension: reviewed formal Action pages, including TEST_ONLY native App entry",
6
6
  "bin": {