@tomflow/chatloop-extension 0.3.48 → 0.3.53

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/README.md CHANGED
@@ -32,6 +32,8 @@ Run: chatloop-extension extension <command> --help
32
32
 
33
33
  **Chrome 独立运行安装路径:**先用 `npm install --prefix "$HOME/.chat-loop/extension/npm" --save-exact --ignore-scripts @tomflow/chatloop-extension@latest` 下载,再在 `chrome://extensions` 加载该目录下的 `node_modules/@tomflow/chatloop-extension/extension`。改目录会改变扩展 ID,必须通过同一个 npm 包的 `host install <id>` 更新 Native Host。详情见 [Extension 主文档](../../docs/extension.md)。
34
34
 
35
+ **原 Chat 接管候选接口**:用户在同一普通 Chat 完成两轮真实 R/P 确认后,用 `chat_loop_extension__start({projectId,mode:'adopt',confirmed:true})` 申请原地绑定;可选提供规范化的 `chatUrl` 精确限制候选范围,但不可用它代替批准证据。扩展自己核对真实网页 R→user确认→P(引用当前R)→user确认,必须唯一匹配;不新建 Chat、不写输入框、不重发消息。未匹配/多匹配/版本变化一律拒绝;当前代码的正式 Chrome E2E 尚未完成,不能以本机测试替代发布。
36
+
35
37
  `extension start` 正常只在 `status=IDLE`、用户确认后启动。上一 Session 若是 `BLOCKED`,可在用户**再次明确批准一个不同 projectId 的全新任务**时附上 `replaceBlockedSessionId`(精确 UUID)作为受控替换条件:扩展 Worker 与本机持久指针必须同时指向该 BLOCKED Session,才能允许新 Session;旧执行 Chat 保留审计,旧用户 Turn 永不自动重发。示例只用于说明 JSON 签名,不会自动调用:
36
38
 
37
39
  ```json
@@ -48,7 +50,20 @@ Clean 只清空输入框,不发送,不更改 Owner;必须指定精确标
48
50
 
49
51
  **0.3.46 Chrome pendingUrl 修复**:Worker 创建正式 Action 时,以自己刚发起的受控 Extension URL 与 Chrome 返回的数值 tabId 登记资源,不能依赖 `tabs.create` 立即返回最终 `tab.url`(它可能仅有 `pendingUrl`)。Action 自身仍需验证真实 URL、Owner、token,任何未确认发送都不得重试;代码回归覆盖过渡 tab.url 缺失但单次 Action 正常创建。
50
52
 
51
- **下一源码候选 0.3.48(未发行)**:Worker 内正式串行消息类型统一以显式路由表派发;各处理器自身的来源、一次性凭证和 Owner 身份校验保持不变。未重构或发布网页发送行为,真实已发行版仍见 CURRENT。
53
+ **npm 发行版 0.3.48**:Worker 内正式串行消息类型统一以显式路由表派发,各处理器的来源、一次性凭证和 Owner 身份校验保持不变。此版本已发布到 npm 并安装到本机原扩展目录;Chrome 是否重新载入新代码以及真实 E2E 结果须单独验证,具体以 [CURRENT](../../context/CURRENT.md) 为准。
54
+
55
+
56
+ **0.3.48 中的源码级熵减**:删除仅用于旧手动验收的 Popup 脚本、Clock Action、计数/模拟墙钟状态及其专属测试。正式 Start、Continue、Handoff 与 Observer/Owner、十分钟真实时钟、错误隔离、配额与已登记测试 Chat 的安全回收保持实现。继续/交接只能由独立 Action 单次发送,用户未发送草稿不允许清除;过往隐藏验收 URL 不再可调用。确切最新测试数量及未验证项只看 [CURRENT](../../context/CURRENT.md)。
57
+
58
+ **源码候选 0.3.49(未发布)**:扩展同 Chat 接管候选修复,不改变旧新 Chat Start/Continue/Handoff 入口;需要真实 Chrome 与云端同 Chat 审批正向验收后才能发布。
59
+
60
+
61
+ ## 原 Owner 的有界技术恢复
62
+
63
+ Worker仍是唯一发送裁决者,Native会话文件只是带身份校验的持久投影。正式Status返回当前Session/Chat及有限diagnostics(版本、失败码、消息身份、恢复预算、执行时钟),不返回发送token或任务正文;终态BLOCKED的Eye可只读检查同一个已确认Owner,不获得发送权。
64
+
65
+ 已由可信操作者核实修复的Start/adopt工具前置故障,可通过原内置 `continue.html?tabId=<原Owner精确tabId>` 申请一次恢复。必须保持Session/project/Chat/generation、两条原消息身份和执行时钟,无待确认表单;未知发送、权限拒绝和页面挑战不自动恢复。恢复预算在后续Continue中继续保留。恢复成功不是业务DONE。
52
66
 
67
+ 仅升级前的0.3.52遗留预留可能需要显式 `&repairLegacyReservation=<Native原updatedAt>`:操作者须先验证保存的旧Native源码确实不能提交BLOCKED→PENDING,且原消息和指针未变。Worker还要求旧恢复来源、旧user未变、没有现代recoveryProtocol;Native在锁内对精确updatedAt做CAS。缺任何证据均禁止使用;此参数不能解锁现代未知发送,也不是自动重试机制。禁止直接编辑active-session.json。
53
68
 
54
- **本次源码级熵减(仅候选、未发行)**:删除仅用于旧手动验收的 Popup 脚本、Clock Action、计数/模拟墙钟状态及其专属测试。正式 Start、Continue、Handoff 与 Observer/Owner、十分钟真实时钟、错误隔离、配额与已登记测试 Chat 的安全回收保持实现。继续/交接只能由独立 Action 单次发送,用户未发送草稿不允许清除;过往隐藏验收 URL 不再可调用。确切最新测试数量及未验证项只看 [CURRENT](../../context/CURRENT.md)。
69
+ Native与Chrome.storage是两个存储,按顺序提交不代表跨存储原子事务;中途崩溃且无法证明发送边界时保持UNVERIFIED/BLOCKED,先查正式回执,不重发。回滚Native/Extension前先核实当前Owner,不把旧代码强行覆盖正在执行的新协议。
package/bin/cli.mjs CHANGED
@@ -15,7 +15,7 @@ const HELP={
15
15
  'extension continue':'Usage: chatloop-extension extension continue (JSON intent on stdin)\nSubmit next-turn text or query receipt; does not send directly.',
16
16
  'extension handoff':'Usage: chatloop-extension extension handoff (JSON intent on stdin)\nRequest early handoff or query receipt; does not transfer directly.',
17
17
  'extension status':'Usage: chatloop-extension extension status\nRead-only, verified active Web Chat status.',
18
- 'extension start':'Usage: chatloop-extension extension start (JSON on stdin)\nStart exactly one confirmed task in the Mac Chrome Web Chat; refuses duplicate owner.'
18
+ 'extension start':'Usage: chatloop-extension extension start (JSON on stdin)\nStart a new task with prompt, or use mode=adopt (no prompt) to bind the only R/P-approved existing Chat without sending.'
19
19
  };
20
20
  function helpFor(args){
21
21
  if(args.length===1&&['-h','--help','help'].includes(args[0]))return HELP[''];
@@ -28,7 +28,8 @@ process.stdin.on('data',chunk=>{
28
28
  }else if(m.op==='session-read'){
29
29
  write({status:'OK',session:readSession()});
30
30
  }else if(m.op==='session-sync'){
31
- write({status:'OK',session:writeSession(m.session,m.replaceBlockedSessionId)});
31
+ write({status:'OK',session:writeSession(m.session,
32
+ m.replaceBlockedSessionId,m.resumeBlockedSessionId,m.resumeBlockedUpdatedAt??null)});
32
33
  }else throw Object.assign(Error('Unknown operation'),{code:'INVALID_OPERATION'});
33
34
  }catch(e){write({status:'FAILED',code:e.code||'NATIVE_HOST_ERROR'});}
34
35
  });
@@ -38,7 +38,9 @@ async function sendOnce(target, text) {
38
38
  || answer.closest('[data-talvt-turn-state]') || answer;
39
39
  const replyText = (answer.querySelector('.markdown')?.innerText || answer.innerText || '').trim();
40
40
  const lines = replyText.split(/\r?\n/);
41
- if (lines.at(-1)?.trim() !== "[CHAT_LOOP_STATUS:CONTINUE]"
41
+ const expectedMarker=expected.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
42
+ ? "[CHAT_LOOP_STATUS:BLOCKED]" : "[CHAT_LOOP_STATUS:CONTINUE]";
43
+ if (lines.at(-1)?.trim() !== expectedMarker
42
44
  || (replyText.match(/\[CHAT_LOOP_STATUS:(?:CONTINUE|DONE|BLOCKED)\]/g) || []).length !== 1) {
43
45
  throw Error("CONTINUE_STATUS_CHANGED");
44
46
  }
@@ -78,6 +80,18 @@ async function sendOnce(target, text) {
78
80
  await new Promise(resolve => setTimeout(resolve, 120));
79
81
  }
80
82
  if (!button || button.disabled || !visible(button)) throw Error("SEND_BUTTON_UNAVAILABLE");
83
+ // Final same-page DOM guard. The Worker checked before Action Take; a
84
+ // confirmation may appear while React settles the composer. Reuse
85
+ // Observer's existing read-only detection, no new action or state.
86
+ const gate = globalThis.ChatLoopTurnObserverV1?.poll?.();
87
+ if (gate?.contract !== "chat-loop.turn-observer.v1"
88
+ || gate.page !== expected.page
89
+ || gate.userKey !== expected.userKey
90
+ || gate.assistantKey !== expected.assistantKey
91
+ || gate.reason === "WAITING_CHAT_HYDRATION"
92
+ || typeof gate.pendingConfirmation !== "boolean")
93
+ throw Error("CONFIRMATION_OBSERVER_UNVERIFIED");
94
+ if (gate.pendingConfirmation) throw Error("CONFIRMATION_PENDING_DOM");
81
95
  if (location.pathname !== expected.page) throw Error("CHAT_PAGE_CHANGED_BEFORE_SEND");
82
96
  if (canonical(input.innerText) !== canonical(instruction)
83
97
  && canonical(input.textContent) !== canonical(instruction)) throw Error("INPUT_CHANGED_BEFORE_SEND");
@@ -170,12 +184,12 @@ async function run() {
170
184
  const raw = params.get("tabId") || "";
171
185
  let token = params.get("token") || "";
172
186
  let tabId = Number(raw);
173
- if ([...params.keys()].some(k => k !== "tabId" && k !== "token")
187
+ if ([...params.keys()].some(k => k !== "tabId" && k !== "token" && k !== "repairLegacyReservation")
174
188
  || [...params.keys()].length !== new Set(params.keys()).size)
175
189
  throw Error("ACTION_PARAMETERS_INVALID");
176
190
  if (raw && !/^[1-9][0-9]*$/.test(raw)
177
191
  || token && !/^[0-9a-f-]{36}$/.test(token)
178
- || token && !raw) throw Error("ACTION_PARAMETERS_INVALID");
192
+ || token && (!raw||params.has("repairLegacyReservation"))) throw Error("ACTION_PARAMETERS_INVALID");
179
193
  const own = await chrome.tabs.getCurrent();
180
194
  if (!own?.id || own.url !== location.href) throw Error("ACTION_TAB_UNVERIFIED");
181
195
  if (!token) {
@@ -191,6 +205,13 @@ async function run() {
191
205
  }
192
206
  const request = {token, tabId};
193
207
  const permit = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_TAKE_V1", ...request});
208
+ if (permit?.status === "DENIED" && permit.code === "PENDING_CONFIRMATION_DOM") {
209
+ // The Worker durably returned the Owner to WAITING_REPLY before denying
210
+ // this Action. No click occurred; close the now-obsolete Action tab so
211
+ // pending human choices do not accumulate background Chrome tabs.
212
+ await chrome.tabs.remove(own.id);
213
+ return;
214
+ }
194
215
  if (permit?.status !== "OK" || permit.target?.tabId !== tabId)
195
216
  throw Error(permit?.code || "ACTION_NOT_AUTHORIZED");
196
217
  show("RUNNING", "已独占一次发送许可,正在核验目标 Chat 和最新已完成 Turn。");
@@ -61,6 +61,19 @@ async function verifyOldChat(target, summary, mode = "EXPLICIT") {
61
61
  throw Error("SOURCE_GENERATION_STILL_RUNNING");
62
62
  if (handoffMode !== "ERROR" && ![...scope.querySelectorAll('button[aria-label="复制"],button[aria-label="Copy"],button[data-testid="copy-turn-action-button"]')].some(visible))
63
63
  throw Error("SOURCE_NOT_FINAL");
64
+ // Last read-only guard before the Action creates any successor Chat:
65
+ // an unanswered confirmation in the current assistant Turn wins.
66
+ if (handoffMode !== "ERROR") {
67
+ const gate = globalThis.ChatLoopTurnObserverV1?.poll?.();
68
+ if (gate?.contract !== "chat-loop.turn-observer.v1"
69
+ || gate.page !== expected.page
70
+ || gate.userKey !== expected.userKey
71
+ || gate.assistantKey !== expected.assistantKey
72
+ || gate.reason === "WAITING_CHAT_HYDRATION"
73
+ || typeof gate.pendingConfirmation !== "boolean")
74
+ throw Error("CONFIRMATION_OBSERVER_UNVERIFIED");
75
+ if (gate.pendingConfirmation) throw Error("CONFIRMATION_PENDING_DOM");
76
+ }
64
77
  // Timed handoff must not modify the original Chat. Capture a bounded
65
78
  // read-only evidence snapshot here, not through URL or Worker storage.
66
79
  if (handoffMode === "TIMED" || handoffMode === "ERROR") {
@@ -208,6 +221,12 @@ async function run() {
208
221
  }
209
222
  const request = {tabId, token};
210
223
  const permit = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_TAKE_V1", ...request});
224
+ if (permit?.status === "DENIED" && permit.code === "PENDING_CONFIRMATION_DOM") {
225
+ // A choice appeared after timed Handoff was reserved. Worker retains
226
+ // the same Owner and no new Chat was created; close this stale Action.
227
+ await chrome.tabs.remove(own.id);
228
+ return;
229
+ }
211
230
  if (permit?.status !== "OK" || permit.action !== "HANDOFF"
212
231
  || permit.target?.tabId !== request.tabId
213
232
  || (permit.handoffMode === "EXPLICIT" && typeof permit.text !== "string")
@@ -128,7 +128,42 @@ async function run(){
128
128
  taken=await chrome.runtime.sendMessage({type:'CHAT_LOOP_SESSION_START_TAKE_V1',
129
129
  requestId:id,token:prepared.token});
130
130
  if(taken?.status!=='OK'||taken.sessionId!==prepared.sessionId
131
- ||typeof taken.prompt!=='string')throw Error(taken?.code||'START_TAKE_DENIED');
131
+ ||(taken.mode==='adopt'
132
+ ? !Number.isSafeInteger(taken.tabId)||!/^\/c\/[0-9a-f-]{12,}$/i.test(taken.page||'')
133
+ && !/^\/g\/[^/]+\/c\/[0-9a-f-]{12,}$/i.test(taken.page||'')
134
+ ||typeof taken.userKey!=='string'
135
+ : typeof taken.prompt!=='string'))
136
+ throw Error(taken?.code||'START_TAKE_DENIED');
137
+ if(taken.mode==='adopt'){
138
+ const existing=await chrome.tabs.get(taken.tabId).catch(()=>null);
139
+ if(!existing || new URL(existing.url).pathname!==taken.page)
140
+ throw Error('ADOPTION_TAB_UNVERIFIED');
141
+ await observerReady(existing.id);
142
+ const evidence=await chrome.tabs.sendMessage(existing.id,
143
+ {type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
144
+ ...(taken.explicitChatId
145
+ ?{explicitChatId:taken.explicitChatId}:{})}).catch(()=>null);
146
+ if(evidence?.status!=='VERIFIED'||evidence.page!==taken.page
147
+ ||evidence.userKey!==taken.userKey)
148
+ throw Error('ADOPTION_APPROVAL_CHANGED');
149
+ const registered=await chrome.runtime.sendMessage({type:'CHAT_LOOP_RESOURCE_CHAT_V1',
150
+ action:'start',stage:'adopt',tabId:existing.id});
151
+ if(registered?.status!=='OK')throw Error(registered?.code||'ADOPTION_RESOURCE_UNVERIFIED');
152
+ // No tabs.create, no composer input, no send-button click in this branch.
153
+ committed=await chrome.runtime.sendMessage({type:'CHAT_LOOP_SESSION_START_RESULT_V1',
154
+ requestId:id,token:prepared.token,result:'ADOPTED_CONFIRMED',
155
+ newTabId:existing.id,newPage:taken.page,newUserKey:taken.userKey});
156
+ if(committed?.status!=='OK')throw Error(committed?.code||'ADOPTION_COMMIT_UNVERIFIED');
157
+ await chrome.tabs.sendMessage(existing.id,{type:'CHAT_LOOP_TURN_RESUME_V1',
158
+ page:taken.page,userKey:taken.userKey,
159
+ assistantKey:taken.priorAssistantKey||null,startedAt:Date.now()}).catch(()=>null);
160
+ const stored=await chrome.runtime.sendNativeMessage(host,{op:'complete',
161
+ id,nonce:proof.nonce,action:'start',status:'OK',payload:JSON.stringify(committed)});
162
+ if(stored?.status!=='SAVED')throw Error(stored?.code||'ADOPTION_RECEIPT_UNVERIFIED');
163
+ show('SUCCESS','已接管完成 R/P 确认的原 Chat;没有新建会话或重新发送消息。');
164
+ await chrome.tabs.remove(own.id);
165
+ return;
166
+ }
132
167
  const quota=await chrome.runtime.sendMessage({type:'CHAT_LOOP_RESOURCE_CHAT_V1',
133
168
  action:'start',stage:'preflight'});
134
169
  if(quota?.status!=='OK')throw Error(quota?.code||'RESOURCE_QUOTA_UNVERIFIED');
@@ -3,7 +3,8 @@
3
3
  importScripts("loop/core.js", "loop/resources.js");
4
4
  const RUN_KEY = "chat-loop.action.run.v1";
5
5
  const SESSION_HOST = "com.tomflow.chatloop.extension";
6
- const RUN_BUDGET_MS = 10 * 60 * 1000;
6
+ // Product window: 4h of elapsed execution time per owned Chat, never per R/P review.
7
+ const RUN_BUDGET_MS = 4 * 60 * 60 * 1000;
7
8
  const ALARM_NAME = "chat-loop.turn-watch.v1";
8
9
  const DEADLINE_ALARM_NAME = "chat-loop.handoff-deadline.v1";
9
10
  const CONTINUE_TEXT = "继续当前任务,完成本轮后只在末行写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
@@ -41,6 +42,10 @@ const pathOf = url => {
41
42
  ? path : "";
42
43
  } catch { return ""; }
43
44
  };
45
+ // ChatGPT may render the very same conversation as /c/<id> or under a
46
+ // project /g/<project>/c/<id>. Match the immutable conversation ID, never
47
+ // create a second Chat because the visible path prefix differs.
48
+ const chatIdOf = url => pathOf(url)?.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase() || null;
44
49
  const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
45
50
  const windowMsOf = run => Number.isSafeInteger(run?.windowMs) && run.windowMs > 0
46
51
  ? run.windowMs : RUN_BUDGET_MS;
@@ -92,15 +97,29 @@ async function saveRun(run) {
92
97
  next.handoffPending = true;
93
98
  next.handoffPendingAt = now;
94
99
  }
95
- await chrome.storage.local.set({[RUN_KEY]: next});
96
- if(next.sessionId){
97
- const record = sessionProjection(next);
98
- const saved = await chrome.runtime.sendNativeMessage(SESSION_HOST,
100
+ const stored=await readRun();
101
+ const recoveryCommit=next.sessionId&&next.phase==="RESERVED"
102
+ &&next.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
103
+ &&next.recoveryAttempts===1&&stored?.phase==="BLOCKED";
104
+ const syncNative=async()=>{
105
+ if(!next.sessionId)return;
106
+ const record=sessionProjection(next);
107
+ const saved=await chrome.runtime.sendNativeMessage(SESSION_HOST,
99
108
  {op:"session-sync",session:record,
100
- ...(next.replacedBlockedSessionId?{replaceBlockedSessionId:next.replacedBlockedSessionId}:{})}).catch(()=>null);
101
- if(saved?.status!=="OK"||saved.session?.sessionId!==next.sessionId)
109
+ ...(next.replacedBlockedSessionId&&!recoveryCommit&&next.phase==='STARTING'
110
+ ?{replaceBlockedSessionId:next.replacedBlockedSessionId}:{}),
111
+ ...(recoveryCommit?{resumeBlockedSessionId:next.sessionId,
112
+ ...(next.recoveryExpectedNativeAt?{resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{})}:{})}).catch(()=>null);
113
+ if(saved?.status!=="OK"||saved.session?.sessionId!==next.sessionId
114
+ ||saved.session?.phase!==next.phase)
102
115
  throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
103
- }
116
+ };
117
+ // A terminal BLOCKED session may resume only after native CAS first.
118
+ // Do not leave a Chrome RESERVED owner behind if native rejects the
119
+ // transition: that mismatch previously made all status calls unreadable.
120
+ if(recoveryCommit)await syncNative();
121
+ await chrome.storage.local.set({[RUN_KEY]:next});
122
+ if(!recoveryCommit)await syncNative();
104
123
  // The resource inventory is derived evidence; it never grants browser Owner.
105
124
  if (["DONE","BLOCKED"].includes(next.phase))
106
125
  await resources.terminal(next).catch(()=>{});
@@ -143,6 +162,14 @@ async function resourceChatGate(message,sender) {
143
162
  return quota.ok?{status:'OK',code:'RESOURCE_CHAT_PERMITTED'}
144
163
  :{status:'DENIED',code:quota.code};
145
164
  }
165
+ if(message.stage==='adopt' && run.mode==='adopt'
166
+ &&Number.isInteger(message.tabId)&&message.tabId===run.adoptTabId){
167
+ const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
168
+ if(!tab||pathOf(tab.url)!==run.adoptPage
169
+ ||!await resources.adoptChat(tab,run))
170
+ return {status:'DENIED',code:'RESOURCE_ADOPTION_UNVERIFIED'};
171
+ return {status:'OK',code:'RESOURCE_CHAT_ADOPTED'};
172
+ }
146
173
  if(message.stage!=='register' || !Number.isInteger(message.tabId))
147
174
  return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
148
175
  const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
@@ -154,6 +181,74 @@ async function resourceChatGate(message,sender) {
154
181
  return {status:'DENIED',code:'RESOURCE_CHAT_LIMIT'};
155
182
  return {status:'OK',code:'RESOURCE_CHAT_REGISTERED'};
156
183
  }
184
+ async function approvedAdoptionTarget(chatUrl=null){
185
+ const requestedId=chatUrl?chatIdOf(chatUrl):null;
186
+ let tabs=await chrome.tabs.query({url:"https://chatgpt.com/*"});
187
+ // App and desktop users keep their exact conversation ID. When Chrome
188
+ // has not opened that conversation yet, open only the supplied existing
189
+ // URL. No / new-chat page, prompt, composer write or first-send occurs.
190
+ if(requestedId){
191
+ const existing=tabs.filter(t=>chatIdOf(t.url)===requestedId);
192
+ if(existing.length>1)return {error:"ADOPTION_CHAT_DUPLICATE_TABS"};
193
+ if(existing.length===0){
194
+ let opened;
195
+ try{opened=await chrome.tabs.create({url:chatUrl,active:true});}
196
+ catch{return {error:"ADOPTION_CHAT_OPEN_FAILED"};}
197
+ if(!Number.isSafeInteger(opened?.id))
198
+ return {error:"ADOPTION_CHAT_OPEN_UNVERIFIED"};
199
+ // Content scripts have document_idle timing. A bounded wait allows
200
+ // authentication/hydration; an error or CAPTCHA is NOT approval.
201
+ let ready=false;
202
+ for(let attempt=0;attempt<60;attempt++){
203
+ const current=await chrome.tabs.get(opened.id).catch(()=>null);
204
+ if(!current)return {error:"ADOPTION_CHAT_CLOSED"};
205
+ if(current.url && chatIdOf(current.url)!==requestedId){
206
+ if(current.url!=="about:blank"&&current.url!=="chrome://newtab/")
207
+ return {error:"ADOPTION_CHAT_REDIRECTED"};
208
+ }
209
+ const proof=await chrome.tabs.sendMessage(opened.id,
210
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
211
+ explicitChatId:requestedId}).catch(()=>null);
212
+ if(proof?.contract==="chat-loop.turn-observer.v1"
213
+ &&proof.status==="VERIFIED"
214
+ &&chatIdOf('https://chatgpt.com'+proof.page)===requestedId){
215
+ ready=true;break;
216
+ }
217
+ await new Promise(resolve=>setTimeout(resolve,500));
218
+ }
219
+ if(!ready)return {error:"ADOPTION_APPROVAL_NOT_FOUND"};
220
+ tabs=await chrome.tabs.query({url:"https://chatgpt.com/*"});
221
+ }
222
+ }
223
+ const matched=[];
224
+ for(const tab of tabs) {
225
+ const page=pathOf(tab.url);
226
+ if(!page||!Number.isSafeInteger(tab.id)
227
+ ||(requestedId && chatIdOf(tab.url)!==requestedId))continue;
228
+ const proof=await chrome.tabs.sendMessage(tab.id,
229
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
230
+ ...(requestedId?{explicitChatId:requestedId}:{})}).catch(()=>null);
231
+ if(proof?.contract!=="chat-loop.turn-observer.v1"
232
+ ||proof.status!=="VERIFIED"||proof.page!==page
233
+ ||typeof proof.userKey!=="string"||!/^user:[^\s]{8,}$/.test(proof.userKey))
234
+ continue;
235
+ matched.push({tabId:tab.id,page,userKey:proof.userKey,
236
+ priorAssistantKey:proof.priorAssistantKey||null,
237
+ rVersion:proof.rVersion,pVersion:proof.pVersion});
238
+ }
239
+ if(matched.length!==1)return {error:matched.length
240
+ ?"ADOPTION_APPROVAL_AMBIGUOUS":"ADOPTION_APPROVAL_NOT_FOUND"};
241
+ const target=matched[0];
242
+ await new Promise(resolve=>setTimeout(resolve,400));
243
+ const second=await chrome.tabs.sendMessage(target.tabId,
244
+ {type:"CHAT_LOOP_APPROVAL_EVIDENCE_V1",
245
+ ...(requestedId?{explicitChatId:requestedId}:{})}).catch(()=>null);
246
+ if(second?.status!=="VERIFIED"
247
+ ||second.page!==target.page||second.userKey!==target.userKey
248
+ ||second.rVersion!==target.rVersion||second.pVersion!==target.pVersion)
249
+ return {error:"ADOPTION_APPROVAL_CHANGED"};
250
+ return {target};
251
+ }
157
252
  async function sessionStartPrepare(message,sender){
158
253
  if(!sessionPage(sender,'start',message.requestId))
159
254
  return {status:'DENIED',code:'INVALID_START_SOURCE'};
@@ -167,7 +262,13 @@ async function sessionStartPrepare(message,sender){
167
262
  if(proof?.status!=='OK'||intent?.confirmed!==true
168
263
  ||typeof intent.projectId!=='string'
169
264
  ||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.projectId)
170
- ||typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
265
+ ||(intent.chatUrl!==undefined
266
+ && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'
267
+ ||!pathOf(intent.chatUrl)
268
+ ||intent.chatUrl!=='https://chatgpt.com'+pathOf(intent.chatUrl)))
269
+ ||(intent.mode==='adopt' ? Object.hasOwn(intent,'prompt')
270
+ : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000)
271
+ ||(intent.mode!==undefined && intent.mode!=='adopt')
171
272
  ||(intent.replaceBlockedSessionId!==undefined
172
273
  && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId)))
173
274
  return {status:'DENIED',code:'START_INTENT_UNVERIFIED'};
@@ -184,8 +285,11 @@ async function sessionStartPrepare(message,sender){
184
285
  return {status:'DENIED',code:'SESSION_REPLACEMENT_MISMATCH'};
185
286
  if(disk.session&&disk.session.phase!=='DONE'&&!matchingBlocked)
186
287
  return {status:'DENIED',code:'SESSION_ALREADY_ACTIVE'};
187
- const capacity=await resources.admit(prior,{kind:'chat'});
288
+ const capacity=await resources.admit(prior,{kind:intent.mode==='adopt'?'action':'chat'});
188
289
  if(!capacity.ok)return {status:'DENIED',code:capacity.code};
290
+ const adoption=intent.mode==='adopt'
291
+ ?await approvedAdoptionTarget(intent.chatUrl||null):null;
292
+ if(adoption?.error)return {status:'DENIED',code:adoption.error};
189
293
  // The same blocked task may never be replayed implicitly: a replacement
190
294
  // requires a new project ID and leaves the old Chat intact for audit.
191
295
  const next={sessionId:crypto.randomUUID(),projectId:intent.projectId,
@@ -193,7 +297,11 @@ async function sessionStartPrepare(message,sender){
193
297
  page:'/',tabId:null,startedAt:Date.now(),
194
298
  machineRequestId:message.requestId,machineActionTabId:sender.tab.id,
195
299
  ...(matchingBlocked?{replacedBlockedSessionId:replace}:{}),
196
- startPrompt:intent.prompt};
300
+ ...(adoption?{mode:'adopt',adoptTabId:adoption.target.tabId,
301
+ adoptPage:adoption.target.page,adoptUserKey:adoption.target.userKey,
302
+ ...(intent.chatUrl?{adoptExplicitChatId:chatIdOf(intent.chatUrl)}:{}),
303
+ adoptPriorAssistantKey:adoption.target.priorAssistantKey}
304
+ :{startPrompt:intent.prompt})};
197
305
  await saveRun(next); // Reserve BEFORE any new Chrome tab or send.
198
306
  return {status:'PREPARED',token:next.token,sessionId:next.sessionId};
199
307
  }
@@ -203,14 +311,21 @@ async function sessionStartTake(message,sender){
203
311
  ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
204
312
  ||run.phase!=='STARTING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
205
313
  await saveRun({...run,phase:'PENDING'});
206
- return {status:'OK',sessionId:run.sessionId,prompt:run.startPrompt};
314
+ return {status:'OK',sessionId:run.sessionId,
315
+ ...(run.mode==='adopt'?{mode:'adopt',tabId:run.adoptTabId,
316
+ page:run.adoptPage,userKey:run.adoptUserKey,
317
+ ...(run.adoptExplicitChatId?{explicitChatId:run.adoptExplicitChatId}:{}),
318
+ priorAssistantKey:run.adoptPriorAssistantKey}
319
+ :{prompt:run.startPrompt})};
207
320
  }
208
321
  async function sessionStartResult(message,sender){
209
322
  const run=await readRun();
210
323
  if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
211
324
  ||run.machineActionTabId!==sender.tab.id||run.token!==message.token
212
325
  ||run.phase!=='PENDING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
213
- let confirmed=message.result==='SENT_CONFIRMED'
326
+ const adopted=run.mode==='adopt';
327
+ let confirmed=(adopted?message.result==='ADOPTED_CONFIRMED'
328
+ :message.result==='SENT_CONFIRMED')
214
329
  &&Number.isInteger(message.newTabId)
215
330
  &&typeof message.newPage==='string'&&pathOf('https://chatgpt.com'+message.newPage)===message.newPage
216
331
  &&typeof message.newUserKey==='string'&&/^user:[^\s]{8,}$/.test(message.newUserKey);
@@ -218,24 +333,51 @@ async function sessionStartResult(message,sender){
218
333
  const tab=await chrome.tabs.get(message.newTabId).catch(()=>null);
219
334
  confirmed=!!tab&&pathOf(tab.url)===message.newPage;
220
335
  }
336
+ if(confirmed && adopted){
337
+ confirmed=message.newTabId===run.adoptTabId
338
+ &&message.newPage===run.adoptPage
339
+ &&message.newUserKey===run.adoptUserKey;
340
+ if(confirmed){
341
+ const proof=await chrome.tabs.sendMessage(run.adoptTabId,
342
+ {type:'CHAT_LOOP_APPROVAL_EVIDENCE_V1',
343
+ ...(run.adoptExplicitChatId
344
+ ?{explicitChatId:run.adoptExplicitChatId}:{})}).catch(()=>null);
345
+ confirmed=proof?.status==='VERIFIED'&&proof.page===run.adoptPage
346
+ &&proof.userKey===run.adoptUserKey;
347
+ }
348
+ }
349
+ // Four-hour execution clock begins at confirmed enrollment, not at
350
+ // the UI approval or potentially long Start readiness/preparation.
221
351
  const next={...run,phase:confirmed?'WAITING_REPLY':'BLOCKED',
352
+ startedAt:confirmed?Date.now():run.startedAt,
222
353
  lastStartActionTabId:sender.tab.id,
223
- reason:confirmed?'':'START_SEND_UNVERIFIED',
354
+ reason:confirmed?'':adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED',
224
355
  ...(!confirmed&&['START_HOME_URL_UNVERIFIED','NEW_CHAT_NOT_READY',
225
356
  'FIRST_TURN_OBSERVER_UNAVAILABLE'].includes(message.failureCode)
226
357
  ?{lastStartFailureCode:message.failureCode}:{}),
227
358
  ...(confirmed?{tabId:message.newTabId,page:message.newPage,
228
359
  newUserKey:message.newUserKey}:{attemptedNewTabId:Number.isInteger(message.newTabId)?message.newTabId:null})};
360
+ if(confirmed){
361
+ delete next.handoffPending;
362
+ delete next.handoffPendingAt;
363
+ }
229
364
  delete next.startPrompt;
365
+ delete next.adoptTabId;
366
+ delete next.adoptPage;
367
+ delete next.adoptUserKey;
368
+ delete next.adoptExplicitChatId;
369
+ delete next.adoptPriorAssistantKey;
370
+ delete next.mode;
230
371
  delete next.machineRequestId;
231
372
  delete next.machineActionTabId;
373
+ delete next.replacedBlockedSessionId;
232
374
  await saveRun(next);
233
375
  if(confirmed)await resources.confirmChat(message.newTabId,next.sessionId||next.token,
234
376
  'https://chatgpt.com'+message.newPage).catch(()=>{});
235
377
  return confirmed?{status:'OK',sessionId:next.sessionId,
236
378
  activeChatId:sessionProjection(next).activeChatId,
237
379
  activeChatUrl:sessionProjection(next).activeChatUrl}
238
- :{status:'BLOCKED',code:'START_SEND_UNVERIFIED'};
380
+ :{status:'BLOCKED',code:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED'};
239
381
  }
240
382
  async function sessionStatus(message,sender){
241
383
  if(!sessionPage(sender,'status',message.requestId))
@@ -243,9 +385,9 @@ async function sessionStatus(message,sender){
243
385
  const run=await readRun();
244
386
  const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
245
387
  if(disk?.status!=='OK')return {status:'UNVERIFIED',code:'SESSION_STATE_UNVERIFIED'};
246
- if(run?.sessionId&&(!disk.session||run.sessionId!==disk.session.sessionId
247
- ||run.phase!==disk.session.phase
248
- ||(run.generation||0)!==disk.session.generation))
388
+ const projection=run?.sessionId?sessionProjection(run):null;
389
+ if(projection&&(!disk.session||['sessionId','projectId','phase','generation',
390
+ 'activeChatId','activeChatUrl'].some(key=>projection[key]!==disk.session[key])))
249
391
  return {status:'UNVERIFIED',code:'SESSION_FILE_MISMATCH'};
250
392
  if(!run?.sessionId&&disk.session&&disk.session.phase!=='DONE')
251
393
  return {status:'UNVERIFIED',code:'SESSION_OWNER_MISMATCH'};
@@ -259,7 +401,15 @@ async function sessionStatus(message,sender){
259
401
  if(!tab||pathOf(tab.url)!==run.page)
260
402
  return {status:'UNVERIFIED',code:'OWNER_TAB_MISSING',session:record};
261
403
  }
262
- return {status:'OK',state:run.phase==='BLOCKED'?'BLOCKED':'ACTIVE',session:record};
404
+ return {status:'OK',state:run.phase==='BLOCKED'?'BLOCKED':'ACTIVE',session:record,
405
+ diagnostics:{extensionVersion:chrome.runtime.getManifest?.().version||null,
406
+ reason:run.reason||null,action:run.action||null,
407
+ userKey:run.userKey||null,assistantKey:run.assistantKey||null,
408
+ newUserKey:run.newUserKey||null,recoveryAttempts:run.recoveryAttempts||0,
409
+ recoveryMode:run.recoveryMode||null,recoveryProtocol:run.recoveryProtocol||null,
410
+ recoverySourceAssistantKey:run.recoverySourceAssistantKey||null,
411
+ startedAt:run.startedAt||null,
412
+ deadlineAt:deadlineOf(run),lastManualFeedback:run.lastManualFeedback||null}};
263
413
  }
264
414
  async function expireStaleAction() {
265
415
  const run=await readRun();
@@ -290,6 +440,21 @@ const eligible = async (sender, page) => {
290
440
  } catch { return false; }
291
441
  };
292
442
 
443
+ // Reuse the existing Observer read channel. This checks ONLY the latest
444
+ // assistant Turn in the current owned Chat, not historical forms or composer
445
+ // fields. An unknown read is never evidence of approval.
446
+ async function currentConfirmation(tabId,page,userKey,assistantKey) {
447
+ const tab=await chrome.tabs.get(tabId).catch(()=>null);
448
+ if(pathOf(tab?.url)!==page)return null;
449
+ const proof=await chrome.tabs.sendMessage(tabId,
450
+ {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null);
451
+ if(proof?.contract!=="chat-loop.turn-observer.v1"
452
+ ||proof.page!==page||proof.userKey!==userKey
453
+ ||proof.assistantKey!==assistantKey
454
+ ||proof.reason==="WAITING_CHAT_HYDRATION"
455
+ ||typeof proof.pendingConfirmation!=="boolean")return null;
456
+ return proof.pendingConfirmation;
457
+ }
293
458
  // A transient partial UI snapshot may end with UNKNOWN even when the same
294
459
  // already-confirmed reply later settles on a valid final status. Only resample
295
460
  // the exact in-flight user/assistant turn, read-only, before failing closed.
@@ -342,8 +507,24 @@ async function onTurnBlocked(message, sender) {
342
507
  return {status: "DENIED", code: "ERROR_SOURCE_UNVERIFIED"};
343
508
  const previous = await readRun();
344
509
  if (previous?.phase !== "WAITING_REPLY" || previous.tabId !== sender.tab.id
345
- || previous.page !== message.page || previous.newUserKey !== message.userKey)
510
+ || previous.page !== message.page)
346
511
  return {status: "IGNORED", code: "NOT_OWNED_RUNNING_TURN"};
512
+ // An unanswered confirmation can be followed by a new human user Turn.
513
+ // If THAT Turn fails, stop the same Owner; never silently ignore its error
514
+ // or treat it as an automatically sent Turn eligible for Retry/Handoff.
515
+ if(message.userKey!==previous.newUserKey){
516
+ const proof=await chrome.tabs.sendMessage(previous.tabId,
517
+ {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null);
518
+ const humanFault=proof?.contract==="chat-loop.turn-observer.v1"
519
+ &&proof.page===previous.page&&proof.status==="BLOCKED"
520
+ &&proof.userKey===message.userKey
521
+ &&proof.priorAssistantKey===previous.assistantKey
522
+ &&proof.priorAssistantUserKey===previous.userKey
523
+ &&proof.directReplyAfterPriorAssistant===true;
524
+ if(!humanFault)return {status:"IGNORED",code:"NOT_OWNED_RUNNING_TURN"};
525
+ await saveRun({...previous,phase:"BLOCKED",reason:"HUMAN_RESPONSE_PAGE_ERROR"});
526
+ return {status:"BLOCKED",code:"HUMAN_RESPONSE_PAGE_ERROR"};
527
+ }
347
528
  const verify = async () => {
348
529
  const proof = await chrome.tabs.sendMessage(previous.tabId,
349
530
  {type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
@@ -530,10 +711,37 @@ async function onTurnFinished(message, sender) {
530
711
  return {status: "IGNORED", code: "ALREADY_HANDLED"};
531
712
  if (previous.phase !== "WAITING_REPLY")
532
713
  return {status: "IGNORED", code: "INVALID_PHASE"};
533
- if (message.userKey !== previous.newUserKey) {
714
+ // A clicked ChatGPT choice creates a regular NEW user Turn. Its preceding
715
+ // assistant must be the exact already-handled question from this Owner, with
716
+ // no intervening user messages. This keeps the old identity boundary
717
+ // without adding a WAITING_USER phase or a second communication channel.
718
+ const humanReply=previous.reason==="PENDING_CONFIRMATION_DOM"
719
+ && message.userKey!==previous.newUserKey
720
+ && previous.userKey && previous.assistantKey
721
+ && message.userKey!==previous.userKey
722
+ && message.priorAssistantKey===previous.assistantKey
723
+ && message.priorAssistantUserKey===previous.userKey
724
+ && message.directReplyAfterPriorAssistant===true;
725
+ if (message.userKey !== previous.newUserKey && !humanReply) {
534
726
  await saveRun({...previous, phase: "BLOCKED", reason: "REPLY_USER_MISMATCH"});
535
727
  return {status: "BLOCKED", code: "REPLY_USER_MISMATCH"};
536
728
  }
729
+ const confirmation=await currentConfirmation(tabId,message.page,
730
+ message.userKey,message.assistantKey);
731
+ if (message.pendingConfirmation===true || confirmation===true) {
732
+ // The current assistant still has an unanswered confirmation widget.
733
+ // Do not open a Continue/Handoff Action, even after its old deadline.
734
+ const held=settleModelIntent({...previous,phase:"WAITING_REPLY",
735
+ userKey:message.userKey,assistantKey:message.assistantKey,
736
+ reason:"PENDING_CONFIRMATION_DOM"},
737
+ "CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
738
+ await saveRun(held);
739
+ return {status:"IGNORED",code:"PENDING_CONFIRMATION_DOM"};
740
+ }
741
+ if (confirmation===null) {
742
+ await saveRun({...previous,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
743
+ return {status:"BLOCKED",code:"CONFIRMATION_DOM_UNVERIFIED"};
744
+ }
537
745
  let replyText = message.replyText;
538
746
  let status = globalThis.ChatLoopCoreV1.parseStatus(replyText);
539
747
  if (status === "UNKNOWN") {
@@ -544,11 +752,12 @@ async function onTurnFinished(message, sender) {
544
752
  // Keep the same clock throughout one Chat. A successful Handoff resets it.
545
753
  const initial = Number.isSafeInteger(message.startedAt) && message.startedAt > 0
546
754
  && message.startedAt <= now ? message.startedAt : now;
547
- const startedAt = previous?.phase === "WAITING_REPLY" ? previous.startedAt || now : initial;
755
+ const startedAt = previous?.phase === "WAITING_REPLY"
756
+ ? previous.startedAt || now : initial;
548
757
  const timeExpired = now >= startedAt + windowMsOf(previous);
549
758
  // Deadline intent can be persisted by the timer even while a Turn RUNS.
550
759
  // The decision below still waits for the observer's complete Turn proof.
551
- const queued = previous?.modelIntent?.page===message.page
760
+ const queued = !humanReply && previous?.modelIntent?.page===message.page
552
761
  && previous.modelIntent.userKey===message.userKey ? previous.modelIntent : null;
553
762
  // Existing DONE/BLOCKED, deadline and page-error policies still win.
554
763
  // A queued model request only changes a still-eligible CONTINUE Turn.
@@ -575,6 +784,14 @@ async function onTurnFinished(message, sender) {
575
784
  tabId, page: message.page, userKey: message.userKey,
576
785
  assistantKey: message.assistantKey, phase: "RESERVED", token,
577
786
  action: nextAction, startedAt, modelReceipts:receiptHistory(previous),
787
+ // Recovery is a lifetime budget of this Session, not of its last Turn.
788
+ ...(previous?.recoveryAttempts ? {recoveryAttempts:previous.recoveryAttempts,
789
+ ...(previous.recoveryProtocol?{recoveryProtocol:previous.recoveryProtocol}:{})} : {}),
790
+ // Preserve an explicitly configured window through every Continue and
791
+ // Handoff. Otherwise the clock silently falls back to the default
792
+ // after the first completed Turn, breaking the persisted deadline.
793
+ ...(Number.isSafeInteger(previous?.windowMs) && previous.windowMs > 0
794
+ ? {windowMs:previous.windowMs} : {}),
578
795
  ...(previous?.lastFaultProof ? {lastFaultProof:previous.lastFaultProof} : {}),
579
796
  ...((previous?.handoffPending || newlyDue) ? {
580
797
  handoffPending: true,
@@ -608,6 +825,32 @@ async function onTurnFinished(message, sender) {
608
825
  return {status: "BLOCKED", code: error.message || "ACTION_PAGE_CREATE_FAILED"};
609
826
  }
610
827
  }
828
+ // Recover ONLY an interrupted pre-send reservation from the old Worker
829
+ // implementation: Chrome said RESERVED, native still said BLOCKED, so no
830
+ // ACTION_TAKE/PENDING/DOM click could have occurred. Invalidate that token
831
+ // through the same authorized scheduler, never by editing the disk file.
832
+ async function repairUncommittedBlockedRecovery(){
833
+ const run=await readRun();
834
+ if(run?.phase!=="RESERVED"
835
+ ||run.recoveryMode!=="TOOL_PREFLIGHT_REPAIRED"
836
+ ||run.recoveryAttempts!==1 || run.recoveryProtocol || !run.sessionId
837
+ ||!Number.isInteger(run.manualActionTabId))
838
+ return run;
839
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
840
+ {op:"session-read"}).catch(()=>null);
841
+ if(disk?.status!=="OK"||disk.session?.phase!=="BLOCKED"
842
+ ||disk.session.sessionId!==run.sessionId
843
+ ||disk.session.projectId!==run.projectId
844
+ ||disk.session.generation!==(run.generation||0)
845
+ ||disk.session.activeChatId!==chatIdOf("https://chatgpt.com"+run.page))
846
+ return run;
847
+ const restored={...run,phase:"BLOCKED",reason:"BLOCKED",recoveryAttempts:0};
848
+ for(const field of ["recoveryMode","recoverySourceAssistantKey","token",
849
+ "manualActionTabId","actionPendingAt","resourceToken"])
850
+ delete restored[field];
851
+ await saveRun(restored);
852
+ return restored;
853
+ }
611
854
  async function onManualPrepare(message, sender) {
612
855
  const requested = message.action;
613
856
  if (!["CONTINUE", "HANDOFF"].includes(requested)
@@ -616,14 +859,40 @@ async function onManualPrepare(message, sender) {
616
859
  let url;
617
860
  try { url = new URL(sender.url); } catch {return {status: "DENIED", code: "INVALID_ACTION_URL"};}
618
861
  const rawTabId = url.searchParams.get("tabId");
862
+ // Explicit operator-only migration of 0.3.52's unsent recovery reservation.
863
+ // The old Native Host could NEVER commit BLOCKED -> PENDING. Operator must
864
+ // verify that installed-version provenance before supplying this disk CAS.
865
+ // Modern unknown sends are never eligible, even with the query parameter.
866
+ const legacyRaw=url.searchParams.get("repairLegacyReservation");
867
+ const legacyAt=legacyRaw!==null?Number(legacyRaw):null;
868
+ if(legacyRaw!==null&&(requested!=="CONTINUE"||!rawTabId
869
+ ||!Number.isSafeInteger(legacyAt)||legacyAt<=0
870
+ ||!String(legacyAt).match(/^[1-9][0-9]{12}$/)))
871
+ return {status:"DENIED",code:"INVALID_LEGACY_REPAIR"};
619
872
  if (url.origin !== new URL(chrome.runtime.getURL(filename)).origin
620
873
  || url.pathname !== "/" + filename || url.searchParams.has("token")
621
- || Array.from(url.searchParams.keys()).some(key => key !== "tabId")
874
+ || Array.from(url.searchParams.keys()).some(key => key !== "tabId"&&key!=="repairLegacyReservation")
875
+ || url.searchParams.size!==new Set(url.searchParams.keys()).size
622
876
  || (rawTabId !== null && (!/^[1-9][0-9]*$/.test(rawTabId)
623
877
  || message.tabId !== Number(rawTabId))))
624
878
  return {status: "DENIED", code: "INVALID_ACTION_URL"};
625
- const previous = await readRun();
626
- if (previous && (previous.sessionId&&previous.phase!=="DONE"
879
+ const previous = await repairUncommittedBlockedRecovery();
880
+ // Existing Owner may recover a *verified resolved* model-level tool blocker
881
+ // via the SAME built-in Continue Action. Never grant a new Owner or create
882
+ // a new conversation. This cannot recover unknown sends/page errors.
883
+ const legacyUnsent=Boolean(legacyAt&&previous?.sessionId
884
+ &&previous.phase==="BLOCKED"&&previous.action==="CONTINUE"
885
+ &&previous.reason==="ACTION_RESULT_TIMEOUT_UNVERIFIED"
886
+ &&previous.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
887
+ &&previous.recoveryAttempts===1&&!previous.recoveryProtocol
888
+ &&previous.newUserKey===previous.userKey
889
+ &&previous.recoverySourceAssistantKey===previous.assistantKey);
890
+ const recoveryCandidate=requested==="CONTINUE"
891
+ &&previous?.sessionId&&previous.phase==="BLOCKED"
892
+ &&Number.isInteger(previous.tabId)
893
+ &&(legacyUnsent||previous.reason==="BLOCKED"
894
+ &&(previous.recoveryAttempts||0)===0);
895
+ if (previous && (previous.sessionId&&previous.phase!=="DONE"&&!recoveryCandidate
627
896
  || !["DONE", "BLOCKED"].includes(previous.phase)))
628
897
  return {status: "DENIED", code: "LOOP_ALREADY_ACTIVE"};
629
898
  const candidates = await chrome.tabs.query({url: "https://chatgpt.com/*"});
@@ -646,11 +915,24 @@ async function onManualPrepare(message, sender) {
646
915
  || second.userKey !== first.userKey || second.assistantKey !== first.assistantKey
647
916
  || second.replyText !== first.replyText) return {status: "DENIED", code: "TURN_NOT_STABLE"};
648
917
  const modelStatus = globalThis.ChatLoopCoreV1.parseStatus(first.replyText);
649
- if (requested === "CONTINUE" && modelStatus !== "CONTINUE"
918
+ const ownedRecovery=Boolean(recoveryCandidate && modelStatus==="BLOCKED"
919
+ &&Number.isInteger(message.tabId) && message.tabId===previous.tabId
920
+ &&previous.tabId===tab.id&&previous.page===first.page
921
+ &&previous.userKey===first.userKey
922
+ &&previous.assistantKey===first.assistantKey
923
+ // Specific repaired tool capability, not generic BLOCKED, human
924
+ // approval failure, unknown browser send or context exhaustion.
925
+ &&/\b(?:adopt|Start)\b/i.test(first.replyText)
926
+ &&!first.pendingConfirmation
927
+ &&!second.pendingConfirmation);
928
+ if (recoveryCandidate && !ownedRecovery)
929
+ return {status:"DENIED",code:"BLOCKED_RECOVERY_UNVERIFIED"};
930
+ if (requested === "CONTINUE" && modelStatus !== "CONTINUE"&&!ownedRecovery
650
931
  || requested === "HANDOFF" && !["HANDOFF", "CONTINUE"].includes(modelStatus))
651
932
  return {status: "DENIED", code: "ACTION_MARKER_MISMATCH"};
652
933
  if (previous && previous.tabId === tab.id && previous.page === first.page
653
- && (previous.userKey === first.userKey || previous.assistantKey === first.assistantKey))
934
+ && (previous.userKey === first.userKey || previous.assistantKey === first.assistantKey)
935
+ &&!ownedRecovery)
654
936
  return {status: "DENIED", code: "ALREADY_HANDLED"};
655
937
  const summary = modelStatus === "HANDOFF"
656
938
  ? first.replyText.replace(/\r?\n\[CHAT_LOOP_STATUS:HANDOFF\]\s*$/, "").trim() : null;
@@ -658,10 +940,27 @@ async function onManualPrepare(message, sender) {
658
940
  || !/目标/.test(summary) || !/已完成|进度/.test(summary)
659
941
  || !/下一步|待办/.test(summary)))
660
942
  return {status: "DENIED", code: "HANDOFF_PACKET_MISSING"};
943
+ if(ownedRecovery){
944
+ const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
945
+ {op:"session-read"}).catch(()=>null);
946
+ if(disk?.status!=="OK"||disk.session?.sessionId!==previous.sessionId
947
+ ||disk.session.phase!=="BLOCKED"
948
+ ||disk.session.projectId!==previous.projectId
949
+ ||disk.session.generation!==(previous.generation||0)
950
+ ||disk.session.activeChatId!==chatIdOf(tab.url)
951
+ ||legacyAt&&(!legacyUnsent||disk.session.updatedAt!==legacyAt))
952
+ return {status:"DENIED",code:"BLOCKED_OWNER_PERSISTENCE_UNVERIFIED"};
953
+ }
661
954
  const token = crypto.randomUUID();
662
- await saveRun({tabId: tab.id, page: first.page, userKey: first.userKey,
955
+ await saveRun({...(ownedRecovery?previous:{}),
956
+ tabId: tab.id, page: first.page, userKey: first.userKey,
663
957
  assistantKey: first.assistantKey, phase: "RESERVED", token,
664
- action: requested, startedAt: Date.now(), manualActionTabId: sender.tab.id,
958
+ action: requested, startedAt:ownedRecovery?previous.startedAt:Date.now(),
959
+ manualActionTabId: sender.tab.id,
960
+ ...(ownedRecovery?{recoveryMode:"TOOL_PREFLIGHT_REPAIRED",
961
+ recoveryAttempts:1,recoveryProtocol:1,
962
+ ...(legacyUnsent?{recoveryExpectedNativeAt:legacyAt}:{}),
963
+ recoverySourceAssistantKey:first.assistantKey}:{}),
665
964
  handoffMode: requested === "HANDOFF"
666
965
  ? (modelStatus === "HANDOFF" ? "EXPLICIT" : "TIMED") : null,
667
966
  ...(summary ? {handoffText: summary} : {})});
@@ -691,6 +990,24 @@ async function onTake(message, sender) {
691
990
  await saveRun({...run, phase: "BLOCKED", reason: "CHAT_TARGET_CHANGED"});
692
991
  return {status: "DENIED", code: "CHAT_TARGET_CHANGED"};
693
992
  }
993
+ if (run.retryMode!=="NATIVE" && run.handoffMode!=="ERROR") {
994
+ const pending=await currentConfirmation(run.tabId,run.page,
995
+ run.userKey,run.assistantKey);
996
+ if(pending===true) {
997
+ // A widget appeared after the scheduler decided to Continue.
998
+ // Cancel this Action without a send; the same owner observes a fresh
999
+ // user reply through the existing Turn observer.
1000
+ const held=settleModelIntent({...run,phase:"WAITING_REPLY",
1001
+ newUserKey:run.userKey,reason:"PENDING_CONFIRMATION_DOM"},
1002
+ "CANCELLED_PENDING_USER_INPUT","PENDING_CONFIRMATION_DOM");
1003
+ await saveRun(held);
1004
+ return {status:"DENIED",code:"PENDING_CONFIRMATION_DOM"};
1005
+ }
1006
+ if(pending===null) {
1007
+ await saveRun({...run,phase:"BLOCKED",reason:"CONFIRMATION_DOM_UNVERIFIED"});
1008
+ return {status:"DENIED",code:"CONFIRMATION_DOM_UNVERIFIED"};
1009
+ }
1010
+ }
694
1011
  // Bind a model-control capability to the next *user* Turn, not to a tab or to another Chat.
695
1012
  // Acceptance fixtures retain their existing prompts; native Retry keeps its original Turn token.
696
1013
  const modelTurnToken = run.retryMode === "NATIVE"
@@ -703,7 +1020,9 @@ async function onTake(message, sender) {
703
1020
  modelTurnToken,
704
1021
  modelTurnNote: modelTurnToken ? turnToolNote(modelTurnToken) : "",
705
1022
  handoffMode: run.handoffMode || null, retryMode: run.retryMode || null,
1023
+ recoveryMode:run.recoveryMode||null,
706
1024
  target: {tabId: run.tabId, page: run.page,
1025
+ recoveryMode:run.recoveryMode||null,
707
1026
  assistantKey: run.assistantKey,
708
1027
  userKey: run.retryMode === "NATIVE" || run.handoffMode === "ERROR"
709
1028
  ? run.newUserKey : run.userKey,
@@ -713,6 +1032,8 @@ async function onTake(message, sender) {
713
1032
  pendingPlan: run.action==="HANDOFF" && run.modelIntent?.action==="CONTINUE"
714
1033
  ? {id:run.modelIntent.id,nextPrompt:run.modelIntent.nextPrompt} : null,
715
1034
  text: run.action === "HANDOFF" ? run.handoffText || null
1035
+ : run.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
1036
+ ? "【Chat Loop 受控故障恢复:唯一一次】用户已授权修复并继续原任务。此前模型因旧工具 Start/adopt 能力不足输出 BLOCKED;现在扩展已成功接管此原 Chat,当前 Session 不变。不要再次调用 Start、不要新建 Chat、不要重复 R/P 审批。首先核实原工作区真实状态、已执行副作用和当前 Tools 可调用能力,再依据原任务唯一检查点继续尚未完成的工作、测试与迭代;若仍有真实风险如实 BLOCKED,不要再次反复自恢复。本轮结束末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
716
1037
  : run.modelIntent?.action==="CONTINUE" ? (
717
1038
  "【Chat Loop 续接来源】上一轮由模型登记的 Continue 请求 " + run.modelIntent.id
718
1039
  + " 已被扩展唯一 Action 领取。\n"
@@ -820,9 +1141,22 @@ async function reconnectOpenChats() {
820
1141
  const owner = await readRun();
821
1142
  if (owner?.phase === "WAITING_REPLY" && owner.tabId === tab.id
822
1143
  && owner.page === pathOf(tab.url) && owner.newUserKey) {
1144
+ // Normal WAITING_REPLY uses its original zero-extra-read resume.
1145
+ // Only a previously seen pending confirmation needs an extra DOM
1146
+ // identity check for a human response that arrived during reload.
1147
+ const proof=owner.reason==="PENDING_CONFIRMATION_DOM"
1148
+ ? await chrome.tabs.sendMessage(tab.id,
1149
+ {type:"CHAT_LOOP_TURN_OBSERVE_V1",poll:true}).catch(()=>null)
1150
+ :null;
1151
+ const freshUser=proof?.page===owner.page
1152
+ && proof.userKey!==owner.newUserKey
1153
+ && proof.priorAssistantKey===owner.assistantKey
1154
+ && proof.priorAssistantUserKey===owner.userKey
1155
+ && proof.directReplyAfterPriorAssistant===true;
823
1156
  const res = await chrome.tabs.sendMessage(tab.id, {
824
1157
  type: "CHAT_LOOP_TURN_RESUME_V1", page: owner.page,
825
- userKey: owner.newUserKey, assistantKey: owner.assistantKey || null,
1158
+ userKey:freshUser?proof.userKey:owner.newUserKey,
1159
+ assistantKey: owner.assistantKey || null,
826
1160
  startedAt: owner.startedAt
827
1161
  }).catch(() => null);
828
1162
  if (res?.status !== "RESUMED" && res?.status !== "ALREADY_MONITORING")
@@ -859,17 +1193,31 @@ async function watchActiveTurn() {
859
1193
  // A reloaded Observer may have mistaken the in-flight user Turn for
860
1194
  // historical baseline. Its IDLE state is not proof of completion.
861
1195
  // Rebind the exact persisted owner using read-only verification.
1196
+ const freshHuman=run?.phase==="WAITING_REPLY" && run.tabId===tab.id
1197
+ && proof?.page===run.page && proof.userKey!==run.newUserKey
1198
+ && proof.priorAssistantKey===run.assistantKey
1199
+ && proof.priorAssistantUserKey===run.userKey
1200
+ && proof.directReplyAfterPriorAssistant===true;
862
1201
  if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
863
- && proof?.page === run.page && proof.userKey === run.newUserKey
1202
+ && proof?.page === run.page
1203
+ && (proof.userKey === run.newUserKey || freshHuman)
864
1204
  && (proof.status === "IDLE"
865
1205
  || proof.status === "UNKNOWN"
866
1206
  && ["ATTACHING_CHAT", "WAITING_CHAT_HYDRATION"].includes(proof.reason))) {
867
1207
  await chrome.tabs.sendMessage(tab.id, {
868
1208
  type: "CHAT_LOOP_TURN_RESUME_V1", page: run.page,
869
- userKey: run.newUserKey, assistantKey: run.assistantKey || null,
1209
+ userKey: freshHuman?proof.userKey:run.newUserKey,
1210
+ assistantKey: run.assistantKey || null,
870
1211
  startedAt: run.startedAt
871
1212
  }).catch(() => null);
872
1213
  }
1214
+ // A human response can fail after the previous question was kept in
1215
+ // WAITING_REPLY. Do not let this become an indefinite silent wait.
1216
+ if(freshHuman && proof.status==="BLOCKED") {
1217
+ void serial(()=>onTurnBlocked({page:run.page,userKey:proof.userKey,
1218
+ reason:proof.reason||"PAGE_ERROR"},
1219
+ {tab,url:tab.url}));
1220
+ }
873
1221
  // Alarm is still read-only. It may reconcile a verified page failure if
874
1222
  // the observer's original notification was lost while Worker slept.
875
1223
  if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
@@ -937,10 +1285,10 @@ async function onExtensionCliTarget(message,sender) {
937
1285
  return {status:"DENIED",code:"INVALID_EXTENSION_ACTION_SOURCE"};
938
1286
  if(message.action==="reload")return {status:"OK"};
939
1287
  const run=await readRun();
940
- // Read-only Eye may inspect the last confirmed DONE Owner while the same
1288
+ // Read-only Eye may inspect the last confirmed terminal Owner while the same
941
1289
  // Chat URL and exact tab still match. This does not reactivate the Loop,
942
1290
  // grant Continue/Handoff permission or select another Chat tab.
943
- const finishedOwned = run?.phase === "DONE"
1291
+ const finishedOwned = ["DONE","BLOCKED"].includes(run?.phase)
944
1292
  && /^user:[^\s]{8,}$/.test(run.userKey || "")
945
1293
  && /^assistant:[^\s]{8,}$/.test(run.assistantKey || "");
946
1294
  if(!(run?.phase === "WAITING_REPLY" || finishedOwned) || !Number.isInteger(run.tabId)
@@ -972,8 +1320,20 @@ chrome.runtime.onMessage.addListener((message, sender, reply) => {
972
1320
  const type=message?.type;
973
1321
  const handle=SERIAL_ROUTES.get(type);
974
1322
  if(handle){
975
- void serial(()=>handle(message,sender)).then(reply,
976
- error=>reply({status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'}));
1323
+ void serial(async()=>{
1324
+ let result;
1325
+ try{result=await handle(message,sender);}
1326
+ catch(error){result={status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'};}
1327
+ // A bounded diagnostic receipt, never permission or a second state store.
1328
+ // In particular a rejected manual recovery must be observable remotely.
1329
+ if(type==='CHAT_LOOP_ACTION_MANUAL_PREPARE_V1'){
1330
+ const current=await readRun();
1331
+ if(current)await chrome.storage.local.set({[RUN_KEY]:{...current,
1332
+ lastManualFeedback:{status:result.status,
1333
+ code:/^[A-Z0-9_]{1,100}$/.test(result.code||'')?result.code:null,at:Date.now()}}});
1334
+ }
1335
+ return result;
1336
+ }).then(reply,error=>reply({status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'}));
977
1337
  return true;
978
1338
  }
979
1339
  if (type === 'CHAT_LOOP_POPUP_CLEAN_OPEN_V1') {
@@ -66,10 +66,37 @@
66
66
  const userKey = messageId(lastUser, "user");
67
67
  const assistantKey = messageId(lastAssistant, "assistant");
68
68
  const historicAssistantKey = messageId(lastHistoricAssistant, "assistant");
69
+ // The immediately preceding assistant before a NEW user Turn is the
70
+ // only eligible confirmation anchor. Historical interactive cards do
71
+ // not block a later assistant Turn or authorize a new action.
72
+ const priorIndex = roles.findLastIndex((el, i) =>
73
+ i < userIndex && roleOf(el) === "assistant");
74
+ const priorAssistant = priorIndex >= 0 ? roles[priorIndex] : null;
75
+ const priorAssistantKey = messageId(priorAssistant, "assistant");
76
+ const priorUser = priorIndex > 0 ? roles.slice(0,priorIndex)
77
+ .filter(el=>roleOf(el)==="user").at(-1) : null;
78
+ const priorAssistantUserKey = messageId(priorUser,"user");
79
+ const directReplyAfterPriorAssistant = priorIndex>=0
80
+ && !roles.slice(priorIndex+1,userIndex).some(el=>roleOf(el)==="user");
69
81
  const scope = lastAssistant?.closest?.('[data-testid^="conversation-turn-"]')
70
82
  || lastAssistant?.closest?.('[data-talvt-turn-state]') || lastAssistant;
71
83
  const reply = lastAssistant?.querySelector?.(".markdown") || lastAssistant;
72
84
  const text = (reply?.innerText ?? reply?.textContent ?? "").trim();
85
+ // A Chat Loop confirmation is a REAL actionable choice surface in the
86
+ // latest assistant Turn, never a form elsewhere on the page. Disabled
87
+ // Submit still means pending: no user message has yet been submitted.
88
+ const controls = [...scope?.querySelectorAll?.(
89
+ '[role="radiogroup"],[role="radio"],input[type="radio"],' +
90
+ 'select,[role="combobox"],textarea,[role="textbox"],' +
91
+ 'input[type="checkbox"],[role="checkbox"]') || []];
92
+ const submit = [...scope?.querySelectorAll?.('button') || []].some(button =>
93
+ visible(button) && /(?:提交|确认|submit|confirm)/i.test(
94
+ (button.innerText || button.textContent ||
95
+ button.getAttribute?.("aria-label") || "").trim()));
96
+ const labels = (scope?.innerText || scope?.textContent || "").slice(-2000);
97
+ const pendingConfirmation = Boolean(lastAssistant && submit
98
+ && controls.some(visible)
99
+ && /(?:确认|修改|不通过|拒绝|自定义|approval|revise|reject|choice)/i.test(labels));
73
100
  const stop = [...document.querySelectorAll(
74
101
  'button[data-testid="stop-button"],button[aria-label="Stop generating"],' +
75
102
  'button[aria-label="Stop"],button[aria-label="停止生成"],' +
@@ -132,7 +159,9 @@
132
159
  const dialog = [...document.querySelectorAll(
133
160
  '[role="dialog"][aria-modal="true"],dialog[open]')].some(visible);
134
161
  const turnState = scope?.getAttribute?.("data-talvt-turn-state") || null;
135
- return {path, userKey, assistantKey, historicAssistantKey, text,
162
+ return {path, userKey, assistantKey, historicAssistantKey, priorAssistantKey,
163
+ priorAssistantUserKey, directReplyAfterPriorAssistant,
164
+ pendingConfirmation, text,
136
165
  hasUser: Boolean(lastUser), hasAssistant: Boolean(lastAssistant),
137
166
  stop, busy, toolUnknown, turnState, composerReady, copyAction,
138
167
  fatal, errorReason: securityChallenge ? "SECURITY_CHALLENGE"
@@ -143,7 +172,11 @@
143
172
  state = {contract: CONTRACT, status, reason, page: snap.path || null,
144
173
  userKey: snap.userKey || null, assistantKey: snap.assistantKey || null,
145
174
  retryAvailable: status === "BLOCKED" && snap.retryAvailable === true,
146
- eventCount: session.emittedCount, observedAt: Date.now()};
175
+ eventCount: session.emittedCount, observedAt: Date.now(),
176
+ pendingConfirmation: snap.pendingConfirmation === true,
177
+ priorAssistantKey: snap.priorAssistantKey || null,
178
+ priorAssistantUserKey:snap.priorAssistantUserKey || null,
179
+ directReplyAfterPriorAssistant:snap.directReplyAfterPriorAssistant===true};
147
180
  if (event) {
148
181
  document.dispatchEvent(new CustomEvent("CHAT_LOOP_TURN_FINISHED_V1", {
149
182
  detail: {contract: CONTRACT, page: snap.path,
@@ -155,7 +188,11 @@
155
188
  void Promise.resolve(chrome.runtime.sendMessage({
156
189
  type: "CHAT_LOOP_TURN_FINISHED_V1", page: snap.path,
157
190
  userKey: snap.userKey, assistantKey: snap.assistantKey,
158
- replyText: snap.text, startedAt: session.firstTurnAt || Date.now()
191
+ replyText: snap.text, startedAt: session.firstTurnAt || Date.now(),
192
+ pendingConfirmation: snap.pendingConfirmation === true,
193
+ priorAssistantKey: snap.priorAssistantKey || null,
194
+ priorAssistantUserKey:snap.priorAssistantUserKey || null,
195
+ directReplyAfterPriorAssistant:snap.directReplyAfterPriorAssistant===true
159
196
  })).catch(() => {});
160
197
  }
161
198
  }
@@ -416,6 +453,95 @@
416
453
  userKey: observation.userKey});
417
454
  return false;
418
455
  }
456
+ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
457
+ // Read-only, fail-closed two-stage approval proof for same-Chat adoption.
458
+ // An explicit model assertion or a copied task Context is never evidence.
459
+ const path = conversationPath();
460
+ const mains = [...document.querySelectorAll("main")].filter(visible);
461
+ const fail = reason => reply({contract: CONTRACT, status:"UNVERIFIED",reason});
462
+ if (!path || mains.length !== 1) {
463
+ fail("APPROVAL_CHAT_UNVERIFIED");return false;
464
+ }
465
+ const main=mains[0];
466
+ const legacy=[...main.querySelectorAll(
467
+ '[data-message-author-role="user"],[data-message-author-role="assistant"]')];
468
+ const nodes=legacy.length?legacy:[...main.querySelectorAll(
469
+ '[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
470
+ const role=node=>node.getAttribute("data-message-author-role")
471
+ ||node.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
472
+ const rows=nodes.map(el=>({el,role:role(el)}))
473
+ .filter(x=>["user","assistant"].includes(x.role));
474
+ const textOf=x=>(x.el.querySelector?.(".markdown")?.innerText
475
+ ||x.el.innerText||x.el.textContent||"").trim();
476
+ const confirms=(value,type)=>{
477
+ const line=value.replace(/\s+/g,"").trim();
478
+ if (!line || line.length>100) return false;
479
+ // Only an affirmative standalone user action. Do NOT accept
480
+ // "我确认方案 P1,但测试先不要做" or copied/embedded approvals.
481
+ const target=type==="R"
482
+ ? "(?:这份|当前|本版|上述)?(?:需求(?:R[1-9][0-9]*)?|R[1-9][0-9]*)"
483
+ : "(?:这份|当前|本版|上述)?(?:方案(?:与|及|和)?计划|实施计划|方案|计划|P[1-9][0-9]*)(?:P[1-9][0-9]*)?";
484
+ return new RegExp("^(?:我)?(?:已经|已)?(?:确认|同意|批准)"+target+"[。.!!]?$","i")
485
+ .test(line);
486
+ };
487
+ const lastUser=rows.findLastIndex(x=>x.role==="user");
488
+ if(lastUser<3 || rows[lastUser-1].role!=="assistant") {
489
+ fail("APPROVAL_SEQUENCE_UNVERIFIED");return false;
490
+ }
491
+ const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
492
+ if(!confirms(textOf(pUser),"P")
493
+ || !/(?:方案|计划)/.test(textOf(pAssistant))
494
+ || !/\bP[1-9][0-9]*\b/i.test(textOf(pAssistant))) {
495
+ fail("APPROVAL_PLAN_MISSING");return false;
496
+ }
497
+ const pVersion=textOf(pAssistant).match(/\bP[1-9][0-9]*\b/i)?.[0].toUpperCase();
498
+ const pUserVersion=textOf(pUser).match(/\bP[1-9][0-9]*\b/i)?.[0].toUpperCase();
499
+ if(pUserVersion && pVersion!==pUserVersion){
500
+ fail("APPROVAL_PLAN_VERSION_MISMATCH");return false;
501
+ }
502
+ const rIndex=rows.slice(0,lastUser-1).findLastIndex(x=>x.role==="user"
503
+ &&confirms(textOf(x),"R"));
504
+ if(rIndex<1 ||rows[rIndex-1].role!=="assistant"){
505
+ fail("APPROVAL_REQUIREMENTS_MISSING");return false;
506
+ }
507
+ const rAssistant=rows[rIndex-1],rUser=rows[rIndex];
508
+ if(!/(?:需求|范围|验收)/.test(textOf(rAssistant))
509
+ || !/\bR[1-9][0-9]*\b/i.test(textOf(rAssistant))) {
510
+ fail("APPROVAL_REQUIREMENTS_MISSING");return false;
511
+ }
512
+ const rVersion=textOf(rAssistant).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
513
+ const rUserVersion=textOf(rUser).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
514
+ const referencedR=textOf(pAssistant).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
515
+ if(!referencedR || referencedR!==rVersion){
516
+ fail("APPROVAL_PLAN_REQUIREMENT_MISMATCH");return false;
517
+ }
518
+ if(rUserVersion && rVersion!==rUserVersion){
519
+ fail("APPROVAL_REQUIREMENTS_VERSION_MISMATCH");return false;
520
+ }
521
+ const userKey=messageId(pUser.el,"user");
522
+ const snap=inspect();
523
+ // Normally the model calls Start during its P-confirmation Turn.
524
+ // A fresh, explicitly scoped native Start intent can also adopt AFTER
525
+ // that assistant Turn ends (e.g. MCP schema was stale in the same Chat).
526
+ // Only the exact current Chat ID, last R/P approval user identity and
527
+ // completed assistant reply qualify. A historical unscoped idle Chat
528
+ // must never become an Owner just because R/P messages are visible.
529
+ const explicitChatId=typeof message.explicitChatId==="string"
530
+ ? message.explicitChatId.toLowerCase():null;
531
+ const currentId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
532
+ const scopedIdle=Boolean(explicitChatId && explicitChatId===currentId
533
+ &&!snap.stop&&!snap.busy&&snap.assistantKey
534
+ &&snap.composerReady&&snap.copyAction&&snap.text
535
+ &&!snap.pendingConfirmation);
536
+ if(!userKey ||snap.path!==path||snap.userKey!==userKey
537
+ ||!(snap.stop||snap.busy||scopedIdle)
538
+ ||snap.fatal||snap.dialog||snap.toolUnknown){
539
+ fail("APPROVAL_LAST_TURN_UNVERIFIED");return false;
540
+ }
541
+ reply({contract:CONTRACT,status:"VERIFIED",page:path,
542
+ userKey,rVersion,pVersion,priorAssistantKey:messageId(pAssistant.el,"assistant")});
543
+ return false;
544
+ }
419
545
  if (message?.type === "CHAT_LOOP_TURN_VERIFY_V1") {
420
546
  // Explicit manual Action: only a fresh read-only completed-Turn candidate.
421
547
  // This does not emit a completion event or write anything to the page.
@@ -202,11 +202,27 @@
202
202
  await save(state);
203
203
  return true;
204
204
  }
205
+ async function adoptChat(tab,run) {
206
+ if(!Number.isInteger(tab?.id)||typeof tab.url!=="string"
207
+ || !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(tab.url)
208
+ ||!run?.sessionId||run.phase!=="PENDING"||run.adoptTabId!==tab.id)
209
+ return false;
210
+ const state=await load();
211
+ if(state.entries.some(e=>e.id===tab.id))return false; // Existing Owner, even terminal, is not silently replaced.
212
+ state.entries.push({id:tab.id,url:tab.url,kind:"chat",
213
+ sessionId:run.sessionId,firstSeenAt:Date.now(),confirmed:true,
214
+ adopted:true,testOwned:false});
215
+ state.created++;
216
+ state.peakChats=Math.max(state.peakChats,
217
+ state.entries.filter(e=>e.kind==="chat").length);
218
+ await save(state);
219
+ return true;
220
+ }
205
221
  async function confirmChat(id,sessionId,url) {
206
222
  const state=await load();
207
223
  const entry=state.entries.find(e=>e.id===id&&e.kind==='chat'
208
224
  &&e.sessionId===sessionId);
209
- if (!entry || !/^https:\/\/chatgpt\.com\/c\/[0-9a-f-]{12,}$/i.test(url)) return;
225
+ if (!entry || !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(url)) return;
210
226
  entry.url=url;entry.confirmed=true;
211
227
  await save(state);
212
228
  }
@@ -218,5 +234,5 @@
218
234
  await save(state);
219
235
  }
220
236
  globalThis.ChatLoopResourcesV1=Object.freeze({reconcile,admit,registerAction,
221
- registerChat,confirmChat,terminal,KEY,ACTION_LIMIT,CHAT_LIMIT});
237
+ registerChat,adoptChat,confirmChat,terminal,KEY,ACTION_LIMIT,CHAT_LIMIT});
222
238
  })();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.3.48",
4
+ "version": "0.3.53",
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
@@ -9,6 +9,7 @@ const ID = /^[a-f0-9]{32}$/;
9
9
  const MAX_TEXT = 8 * 1024 * 1024;
10
10
  const MAX_PNG = 24 * 1024 * 1024;
11
11
  const TTL_MS = 20 * 60 * 1000;
12
+ const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
12
13
  export const configFile = () => join(homedir(), '.chat-loop', 'extension', 'config.json');
13
14
  export const tempRoot = () => join(tmpdir(), 'chatloop-extension-' + (process.getuid?.() ?? process.env.USERNAME ?? 'user'));
14
15
  export function privateDir(path) {
@@ -26,16 +27,20 @@ export function requestDir(id) {
26
27
  function validateIntent(action, intent) {
27
28
  if(action==='start'){
28
29
  if(!intent||typeof intent!=='object'||Array.isArray(intent)
29
- ||Object.keys(intent).some(k=>!['projectId','prompt','confirmed','replaceBlockedSessionId'].includes(k))
30
+ ||Object.keys(intent).some(k=>!['projectId','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl'].includes(k))
30
31
  ||!(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.projectId||'')
31
- ||intent.confirmed!==true
32
+ ||intent.confirmed!==true || (intent.mode!==undefined && intent.mode!=='adopt')
32
33
  || (intent.replaceBlockedSessionId!==undefined
33
34
  && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId))
34
- ||typeof intent.prompt!=='string'
35
- ||!intent.prompt.trim()||intent.prompt.length>4000
36
- ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt))
35
+ ||(intent.chatUrl!==undefined
36
+ && (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'||!CHAT_URL.test(intent.chatUrl)))
37
+ ||(intent.mode==='adopt'
38
+ ? Object.hasOwn(intent,'prompt')
39
+ : typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
40
+ ||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)))
37
41
  throw Object.assign(Error('Explicit confirmed task and project required'),{code:'INVALID_START_INTENT'});
38
- return {projectId:intent.projectId,prompt:intent.prompt,confirmed:true,
42
+ return {projectId:intent.projectId,confirmed:true,
43
+ ...(intent.mode==='adopt'?{mode:'adopt',...(intent.chatUrl?{chatUrl:intent.chatUrl}:{})}:{prompt:intent.prompt}),
39
44
  ...(intent.replaceBlockedSessionId?{replaceBlockedSessionId:intent.replaceBlockedSessionId}:{})};
40
45
  }
41
46
  if(action==='clean'){
@@ -47,13 +47,28 @@ export function readSession(){
47
47
  try{return validate(JSON.parse(readFileSync(file,'utf8')));}
48
48
  catch(e){if(e.code)throw e;throw fail('SESSION_FILE_CORRUPT');}
49
49
  }
50
- export function writeSession(input,replaceBlockedSessionId=null){
50
+ export function writeSession(input,replaceBlockedSessionId=null,resumeBlockedSessionId=null,resumeBlockedUpdatedAt=null){
51
51
  const next=validate(input),file=sessionPath(),dir=dirname(file),lock=file+'.lock';
52
52
  ensurePrivate(dir);
53
53
  let fd;
54
54
  try{fd=openSync(lock,'wx',0o600);}catch{throw fail('SESSION_CONCURRENT_UPDATE');}
55
55
  try{
56
56
  const old=readSession();
57
+ if(resumeBlockedSessionId){
58
+ // A BLOCKED session is terminal except for an exact-same-owner,
59
+ // same-Chat, same-generation, one-shot recovery CAS. No new Chat,
60
+ // task, project, approval or Handoff may be smuggled into recovery.
61
+ if(replaceBlockedSessionId || !old || old.phase!=='BLOCKED'
62
+ ||resumeBlockedUpdatedAt!==null&&old.updatedAt!==resumeBlockedUpdatedAt
63
+ ||old.sessionId!==resumeBlockedSessionId
64
+ ||next.sessionId!==old.sessionId
65
+ ||next.projectId!==old.projectId
66
+ ||next.generation!==old.generation
67
+ ||next.activeChatId!==old.activeChatId
68
+ ||next.activeChatUrl!==old.activeChatUrl
69
+ ||next.phase!=='RESERVED')
70
+ throw fail('SESSION_RECOVERY_MISMATCH');
71
+ }
57
72
  if(replaceBlockedSessionId && (!old||old.sessionId!==next.sessionId
58
73
  && (old.phase!=='BLOCKED'||old.sessionId!==replaceBlockedSessionId)))
59
74
  throw fail('SESSION_REPLACEMENT_MISMATCH');
@@ -62,9 +77,12 @@ export function writeSession(input,replaceBlockedSessionId=null){
62
77
  && replaceBlockedSessionId===old.sessionId && next.projectId!==old.projectId))
63
78
  throw fail('SESSION_ALREADY_ACTIVE');
64
79
  if(old&&old.sessionId===next.sessionId){
80
+ if(next.projectId!==old.projectId)throw fail('SESSION_PROJECT_CHANGED');
65
81
  if(next.generation<old.generation)throw fail('SESSION_STALE_GENERATION');
66
82
  if(old.phase==='DONE'&&next.phase!=='DONE'||old.phase==='BLOCKED'
67
- && !['BLOCKED','DONE'].includes(next.phase))
83
+ && !['BLOCKED','DONE'].includes(next.phase)
84
+ &&!(resumeBlockedSessionId===old.sessionId
85
+ &&next.phase==='RESERVED'))
68
86
  throw fail('SESSION_TERMINAL_LOCKED');
69
87
  if(old.activeChatId!==null&&next.generation===old.generation&&
70
88
  next.activeChatId!==null&&old.activeChatId!==next.activeChatId)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.3.48",
3
+ "version": "0.3.53",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
6
6
  "bin": {