@tomflow/chatloop-extension 0.3.47 → 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 +23 -7
- package/bin/cli.mjs +2 -2
- package/bin/native-host.mjs +3 -6
- package/extension/actions/clean.js +4 -10
- package/extension/actions/common.js +24 -1
- package/extension/actions/continue.js +33 -66
- package/extension/actions/dom.js +2 -25
- package/extension/actions/handoff.js +30 -50
- package/extension/actions/start.js +36 -1
- package/extension/actions/text.js +2 -25
- package/extension/background.js +429 -479
- package/extension/loop/core.js +3 -16
- package/extension/loop/observer.js +129 -3
- package/extension/loop/resources.js +25 -15
- package/extension/manifest.json +1 -1
- package/extension/popup.html +0 -1
- package/extension/popup.js +1 -1
- package/lib/bridge.mjs +12 -16
- package/lib/session-file.mjs +21 -3
- package/package.json +1 -1
- package/extension/acceptance.js +0 -641
- package/extension/actions/clock.js +0 -29
- package/extension/clock.html +0 -4
- package/lib/mcp-tools.json +0 -26
package/extension/background.js
CHANGED
|
@@ -3,37 +3,12 @@
|
|
|
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
|
-
|
|
7
|
-
const RUN_BUDGET_MS =
|
|
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;
|
|
8
8
|
const ALARM_NAME = "chat-loop.turn-watch.v1";
|
|
9
|
-
// One-shot deadline on the same MV3 alarm facility; never sends a Chat message.
|
|
10
9
|
const DEADLINE_ALARM_NAME = "chat-loop.handoff-deadline.v1";
|
|
11
|
-
const COUNT_ALARM_NAME = "chat-loop.count-wait.v1";
|
|
12
|
-
const COUNT_INTERVAL_MS = 60000;
|
|
13
10
|
const CONTINUE_TEXT = "继续当前任务,完成本轮后只在末行写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
|
|
14
|
-
// The model cannot authenticate its originating Chat through MCP alone.
|
|
15
|
-
// This per-Turn capability is sent only to the newly confirmed loop-owned Chat.
|
|
16
|
-
// It is never a browser-send authorization; it only permits staging one intent.
|
|
17
11
|
const turnToolNote = token => "\n\n【Chat Loop 本轮工具凭证】只有本轮需要自定下一轮内容或提前交接时,才能调用 chat_loop_extension__continue / chat_loop_extension__handoff;参数 turnToken 填写 " + token + "。工具只登记意图,不等待本轮结束,不直接发送;请照常在本轮结束时输出 CONTINUE、DONE 或 BLOCKED 标记。不要在助手正文重复该凭证。";
|
|
18
|
-
// Explicit acceptance setup only, dispatched by the same formal Continue page.
|
|
19
|
-
// Fixed harmless prompt; no arbitrary text or external write interface.
|
|
20
|
-
const ACTION_TEST_TEXT = "这是 Chat Loop 短轮回归专用测试,不调用工具、不改文件。每次仅回复一句短话,最后一行单独输出一个协议状态标记。\n第1条消息:OK1,然后末行 [CHAT_LOOP_STATUS:CONTINUE]。\n第2条消息:OK2,然后末行 [CHAT_LOOP_STATUS:CONTINUE]。\n第3条消息:OK3,然后末行 [CHAT_LOOP_STATUS:DONE]。\n不主动交接,也不追加解释。校验串:LOOP-V037-FAST-3C1H。";
|
|
21
|
-
const ACTION_TIMED_TEST_TEXT = "这是 Chat Loop 的长回复与一小时边界隔离测试,不能使用工具,不访问其他聊天,不改文件。请认真完成以下技术文字任务:用至少十八个独立自然段,以不同角度解释长任务的状态管理、异步任务完成检测、最终回执、一次性发送、跨会话交接、故障隔离与日志证据。段落各包含具体推理或例子,持续生成直到全部十八段完成。即使你看到与“时间到期”有关的叙述,也不要主动停止、跳过段落或交接。在全部正文结束后,最后一行只能输出 [CHAT_LOOP_STATUS:CONTINUE];不能提前写出这个标记。当前 Chat 不再收到新的用户消息。\n\n如果你是在新 Chat 收到了包含【原始任务用户消息】【最近轮次证据】的定时交接,请忽略上述长文要求,只回复“定时交接接收完成”,并在最后一行输出 [CHAT_LOOP_STATUS:DONE]。\n\n本测试仅用于验证真正完成一个回复之后才触发交接,模型生成需要多久并没有固定值。校验串 LOOP-V037-FAST-3C1H / MODE-TIMED-1H。";
|
|
22
|
-
const ACTION_WALL_TEST_TEXT = "这是 Chat Loop 的墙钟边界隔离测试,不调用工具、不改文件。原 Chat 每轮计算当前算式,第一行只写得数,末行单独写 [CHAT_LOOP_STATUS:CONTINUE]。第一题:1+1=?后续题目由 Continue 提供。新 Chat 若收到【原始任务用户消息】和【最近轮次证据】,只回复“已接班”,末行写 [CHAT_LOOP_STATUS:DONE]。交接仅由扩展按时钟决定。校验串 LOOP-V037-FAST-3C1H / MODE-WALL-10M / WALL-CLOCK-TEST。";
|
|
23
|
-
// The arithmetic progression belongs ONLY to the controlled 10m acceptance
|
|
24
|
-
// Chat. Each confirmed continuation asks a different, easily checked problem.
|
|
25
|
-
// No prompt variation is a substitute for respecting website security checks.
|
|
26
|
-
const wallArithmeticText = step => {
|
|
27
|
-
const left = Math.ceil(step / 2);
|
|
28
|
-
const right = step === 2 ? 3 : step;
|
|
29
|
-
return `第${step}题:${left}+${right}=?只写得数,末行写 [CHAT_LOOP_STATUS:CONTINUE]。`;
|
|
30
|
-
};
|
|
31
|
-
const COUNT_SETUP_TEXT = "这是 Chat Loop 的计数隔离验收,不调用工具、不改文件。初始整数86,本轮加1后输出87。以后每收到一条Continue才加1。每轮只能输出两行:第一行是整数;第二行是状态,整数小于100输出 [CHAT_LOOP_STATUS:CONTINUE],等于100才输出 [CHAT_LOOP_STATUS:DONE]。新Chat从交接包的最后已确认数值继续加1,交接本身不得DONE。十分钟交接由扩展执行,60秒发送间隔由扩展控制。校验串 LOOP-V037-FAST-3C1H / MODE-WALL-10M / COUNT-86-100 / WALL-CLOCK-TEST。";
|
|
32
|
-
const countText = n => `上一轮确认数字是${n}。本轮只加1,第一行只输出${n + 1};第二行数字未到100写 [CHAT_LOOP_STATUS:CONTINUE],达到100才写 [CHAT_LOOP_STATUS:DONE]。`;
|
|
33
|
-
const readCount = reply => {
|
|
34
|
-
const m = String(reply).trim().match(/(?:^|\n)\s*(\d{2,3})\s*\r?\n\s*\[CHAT_LOOP_STATUS:(?:CONTINUE|DONE)\]$/);
|
|
35
|
-
return m ? Number(m[1]) : null;
|
|
36
|
-
};
|
|
37
12
|
let queue = Promise.resolve();
|
|
38
13
|
const serial = fn => {
|
|
39
14
|
const work = queue.then(fn);
|
|
@@ -67,14 +42,16 @@ const pathOf = url => {
|
|
|
67
42
|
? path : "";
|
|
68
43
|
} catch { return ""; }
|
|
69
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;
|
|
70
49
|
const readRun = async () => (await chrome.storage.local.get(RUN_KEY))[RUN_KEY] || null;
|
|
71
50
|
const windowMsOf = run => Number.isSafeInteger(run?.windowMs) && run.windowMs > 0
|
|
72
|
-
? run.windowMs :
|
|
73
|
-
? 20 * 60 * 1000 : RUN_BUDGET_MS;
|
|
51
|
+
? run.windowMs : RUN_BUDGET_MS;
|
|
74
52
|
const deadlineOf = run => Number.isSafeInteger(run?.startedAt) && run.startedAt > 0
|
|
75
53
|
? run.startedAt + windowMsOf(run) : null;
|
|
76
|
-
const clockActive = run => run && ["RESERVED", "PENDING", "WAITING_REPLY"
|
|
77
|
-
&& !run.testSetup && !run.wallTestHours;
|
|
54
|
+
const clockActive = run => run && ["RESERVED", "PENDING", "WAITING_REPLY"].includes(run.phase);
|
|
78
55
|
// Durable, bounded metadata for model intent receipts. The prompt text remains only
|
|
79
56
|
// in the active run while its Action is pending; history never stores the prompt.
|
|
80
57
|
const MODEL_RECEIPT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
@@ -120,15 +97,29 @@ async function saveRun(run) {
|
|
|
120
97
|
next.handoffPending = true;
|
|
121
98
|
next.handoffPendingAt = now;
|
|
122
99
|
}
|
|
123
|
-
await
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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,
|
|
127
108
|
{op:"session-sync",session:record,
|
|
128
|
-
...(next.replacedBlockedSessionId
|
|
129
|
-
|
|
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)
|
|
130
115
|
throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
|
|
131
|
-
}
|
|
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();
|
|
132
123
|
// The resource inventory is derived evidence; it never grants browser Owner.
|
|
133
124
|
if (["DONE","BLOCKED"].includes(next.phase))
|
|
134
125
|
await resources.terminal(next).catch(()=>{});
|
|
@@ -139,9 +130,6 @@ async function saveRun(run) {
|
|
|
139
130
|
} else {
|
|
140
131
|
await chrome.alarms?.clear?.(DEADLINE_ALARM_NAME);
|
|
141
132
|
}
|
|
142
|
-
if (next.phase === "WAITING_INTERVAL" && next.countMode && !next.handoffPending)
|
|
143
|
-
await chrome.alarms?.create?.(COUNT_ALARM_NAME, {when: next.countReleaseAt});
|
|
144
|
-
else await chrome.alarms?.clear?.(COUNT_ALARM_NAME);
|
|
145
133
|
} catch { /* The existing periodic alarm is a conservative backup. */ }
|
|
146
134
|
}
|
|
147
135
|
// Browser Owner remains the only send authority. Native Host mirrors a minimal
|
|
@@ -174,6 +162,14 @@ async function resourceChatGate(message,sender) {
|
|
|
174
162
|
return quota.ok?{status:'OK',code:'RESOURCE_CHAT_PERMITTED'}
|
|
175
163
|
:{status:'DENIED',code:quota.code};
|
|
176
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
|
+
}
|
|
177
173
|
if(message.stage!=='register' || !Number.isInteger(message.tabId))
|
|
178
174
|
return {status:'DENIED',code:'RESOURCE_REGISTER_INVALID'};
|
|
179
175
|
const tab=await chrome.tabs.get(message.tabId).catch(()=>null);
|
|
@@ -185,6 +181,74 @@ async function resourceChatGate(message,sender) {
|
|
|
185
181
|
return {status:'DENIED',code:'RESOURCE_CHAT_LIMIT'};
|
|
186
182
|
return {status:'OK',code:'RESOURCE_CHAT_REGISTERED'};
|
|
187
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"&¤t.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
|
+
}
|
|
188
252
|
async function sessionStartPrepare(message,sender){
|
|
189
253
|
if(!sessionPage(sender,'start',message.requestId))
|
|
190
254
|
return {status:'DENIED',code:'INVALID_START_SOURCE'};
|
|
@@ -198,7 +262,13 @@ async function sessionStartPrepare(message,sender){
|
|
|
198
262
|
if(proof?.status!=='OK'||intent?.confirmed!==true
|
|
199
263
|
||typeof intent.projectId!=='string'
|
|
200
264
|
||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(intent.projectId)
|
|
201
|
-
||
|
|
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')
|
|
202
272
|
||(intent.replaceBlockedSessionId!==undefined
|
|
203
273
|
&& !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId)))
|
|
204
274
|
return {status:'DENIED',code:'START_INTENT_UNVERIFIED'};
|
|
@@ -215,8 +285,11 @@ async function sessionStartPrepare(message,sender){
|
|
|
215
285
|
return {status:'DENIED',code:'SESSION_REPLACEMENT_MISMATCH'};
|
|
216
286
|
if(disk.session&&disk.session.phase!=='DONE'&&!matchingBlocked)
|
|
217
287
|
return {status:'DENIED',code:'SESSION_ALREADY_ACTIVE'};
|
|
218
|
-
const capacity=await resources.admit(prior,{kind:'chat'});
|
|
288
|
+
const capacity=await resources.admit(prior,{kind:intent.mode==='adopt'?'action':'chat'});
|
|
219
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};
|
|
220
293
|
// The same blocked task may never be replayed implicitly: a replacement
|
|
221
294
|
// requires a new project ID and leaves the old Chat intact for audit.
|
|
222
295
|
const next={sessionId:crypto.randomUUID(),projectId:intent.projectId,
|
|
@@ -224,7 +297,11 @@ async function sessionStartPrepare(message,sender){
|
|
|
224
297
|
page:'/',tabId:null,startedAt:Date.now(),
|
|
225
298
|
machineRequestId:message.requestId,machineActionTabId:sender.tab.id,
|
|
226
299
|
...(matchingBlocked?{replacedBlockedSessionId:replace}:{}),
|
|
227
|
-
|
|
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})};
|
|
228
305
|
await saveRun(next); // Reserve BEFORE any new Chrome tab or send.
|
|
229
306
|
return {status:'PREPARED',token:next.token,sessionId:next.sessionId};
|
|
230
307
|
}
|
|
@@ -234,14 +311,21 @@ async function sessionStartTake(message,sender){
|
|
|
234
311
|
||run.machineActionTabId!==sender.tab.id||run.token!==message.token
|
|
235
312
|
||run.phase!=='STARTING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
|
|
236
313
|
await saveRun({...run,phase:'PENDING'});
|
|
237
|
-
return {status:'OK',sessionId:run.sessionId,
|
|
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})};
|
|
238
320
|
}
|
|
239
321
|
async function sessionStartResult(message,sender){
|
|
240
322
|
const run=await readRun();
|
|
241
323
|
if(!sessionPage(sender,'start',message.requestId)||run?.machineRequestId!==message.requestId
|
|
242
324
|
||run.machineActionTabId!==sender.tab.id||run.token!==message.token
|
|
243
325
|
||run.phase!=='PENDING')return {status:'DENIED',code:'START_OWNER_CHANGED'};
|
|
244
|
-
|
|
326
|
+
const adopted=run.mode==='adopt';
|
|
327
|
+
let confirmed=(adopted?message.result==='ADOPTED_CONFIRMED'
|
|
328
|
+
:message.result==='SENT_CONFIRMED')
|
|
245
329
|
&&Number.isInteger(message.newTabId)
|
|
246
330
|
&&typeof message.newPage==='string'&&pathOf('https://chatgpt.com'+message.newPage)===message.newPage
|
|
247
331
|
&&typeof message.newUserKey==='string'&&/^user:[^\s]{8,}$/.test(message.newUserKey);
|
|
@@ -249,24 +333,51 @@ async function sessionStartResult(message,sender){
|
|
|
249
333
|
const tab=await chrome.tabs.get(message.newTabId).catch(()=>null);
|
|
250
334
|
confirmed=!!tab&&pathOf(tab.url)===message.newPage;
|
|
251
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.
|
|
252
351
|
const next={...run,phase:confirmed?'WAITING_REPLY':'BLOCKED',
|
|
352
|
+
startedAt:confirmed?Date.now():run.startedAt,
|
|
253
353
|
lastStartActionTabId:sender.tab.id,
|
|
254
|
-
reason:confirmed?'':'START_SEND_UNVERIFIED',
|
|
354
|
+
reason:confirmed?'':adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED',
|
|
255
355
|
...(!confirmed&&['START_HOME_URL_UNVERIFIED','NEW_CHAT_NOT_READY',
|
|
256
356
|
'FIRST_TURN_OBSERVER_UNAVAILABLE'].includes(message.failureCode)
|
|
257
357
|
?{lastStartFailureCode:message.failureCode}:{}),
|
|
258
358
|
...(confirmed?{tabId:message.newTabId,page:message.newPage,
|
|
259
359
|
newUserKey:message.newUserKey}:{attemptedNewTabId:Number.isInteger(message.newTabId)?message.newTabId:null})};
|
|
360
|
+
if(confirmed){
|
|
361
|
+
delete next.handoffPending;
|
|
362
|
+
delete next.handoffPendingAt;
|
|
363
|
+
}
|
|
260
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;
|
|
261
371
|
delete next.machineRequestId;
|
|
262
372
|
delete next.machineActionTabId;
|
|
373
|
+
delete next.replacedBlockedSessionId;
|
|
263
374
|
await saveRun(next);
|
|
264
375
|
if(confirmed)await resources.confirmChat(message.newTabId,next.sessionId||next.token,
|
|
265
376
|
'https://chatgpt.com'+message.newPage).catch(()=>{});
|
|
266
377
|
return confirmed?{status:'OK',sessionId:next.sessionId,
|
|
267
378
|
activeChatId:sessionProjection(next).activeChatId,
|
|
268
379
|
activeChatUrl:sessionProjection(next).activeChatUrl}
|
|
269
|
-
:{status:'BLOCKED',code:'START_SEND_UNVERIFIED'};
|
|
380
|
+
:{status:'BLOCKED',code:adopted?'ADOPTION_UNVERIFIED':'START_SEND_UNVERIFIED'};
|
|
270
381
|
}
|
|
271
382
|
async function sessionStatus(message,sender){
|
|
272
383
|
if(!sessionPage(sender,'status',message.requestId))
|
|
@@ -274,9 +385,9 @@ async function sessionStatus(message,sender){
|
|
|
274
385
|
const run=await readRun();
|
|
275
386
|
const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
|
|
276
387
|
if(disk?.status!=='OK')return {status:'UNVERIFIED',code:'SESSION_STATE_UNVERIFIED'};
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
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])))
|
|
280
391
|
return {status:'UNVERIFIED',code:'SESSION_FILE_MISMATCH'};
|
|
281
392
|
if(!run?.sessionId&&disk.session&&disk.session.phase!=='DONE')
|
|
282
393
|
return {status:'UNVERIFIED',code:'SESSION_OWNER_MISMATCH'};
|
|
@@ -290,7 +401,15 @@ async function sessionStatus(message,sender){
|
|
|
290
401
|
if(!tab||pathOf(tab.url)!==run.page)
|
|
291
402
|
return {status:'UNVERIFIED',code:'OWNER_TAB_MISSING',session:record};
|
|
292
403
|
}
|
|
293
|
-
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}};
|
|
294
413
|
}
|
|
295
414
|
async function expireStaleAction() {
|
|
296
415
|
const run=await readRun();
|
|
@@ -321,6 +440,21 @@ const eligible = async (sender, page) => {
|
|
|
321
440
|
} catch { return false; }
|
|
322
441
|
};
|
|
323
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
|
+
}
|
|
324
458
|
// A transient partial UI snapshot may end with UNKNOWN even when the same
|
|
325
459
|
// already-confirmed reply later settles on a valid final status. Only resample
|
|
326
460
|
// the exact in-flight user/assistant turn, read-only, before failing closed.
|
|
@@ -373,8 +507,24 @@ async function onTurnBlocked(message, sender) {
|
|
|
373
507
|
return {status: "DENIED", code: "ERROR_SOURCE_UNVERIFIED"};
|
|
374
508
|
const previous = await readRun();
|
|
375
509
|
if (previous?.phase !== "WAITING_REPLY" || previous.tabId !== sender.tab.id
|
|
376
|
-
|| previous.page !== message.page
|
|
510
|
+
|| previous.page !== message.page)
|
|
377
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
|
+
}
|
|
378
528
|
const verify = async () => {
|
|
379
529
|
const proof = await chrome.tabs.sendMessage(previous.tabId,
|
|
380
530
|
{type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
|
|
@@ -492,8 +642,7 @@ async function onModelIntent(message,sender) {
|
|
|
492
642
|
||/[\x00-\x1f]/.test(intent.reason)))
|
|
493
643
|
return {status:'DENIED',code:'INVALID_MODEL_INTENT'};
|
|
494
644
|
const run=await readRun();
|
|
495
|
-
if(!run||run.phase!=='WAITING_REPLY'||run.
|
|
496
|
-
||run.timedTest||run.wallTestHours||run.modelTurnToken!==intent.turnToken)
|
|
645
|
+
if(!run||run.phase!=='WAITING_REPLY'||run.modelTurnToken!==intent.turnToken)
|
|
497
646
|
return {status:'DENIED',code:'MODEL_INTENT_OWNER_NOT_RUNNING'};
|
|
498
647
|
if(run.modelIntent)
|
|
499
648
|
return {status:'DENIED',code:'MODEL_INTENT_ALREADY_QUEUED'};
|
|
@@ -551,8 +700,6 @@ async function onTurnFinished(message, sender) {
|
|
|
551
700
|
// A Chat is owned only after an extension Action has explicitly reserved
|
|
552
701
|
// and confirmed its user Turn. A status marker on an arbitrary Chat never
|
|
553
702
|
// starts or reactivates a loop, including after DONE/BLOCKED.
|
|
554
|
-
if (previous?.testSetup && previous.tabId === tabId)
|
|
555
|
-
return {status: "IGNORED", code: "TEST_SETUP_UNVERIFIED"};
|
|
556
703
|
if (!previous || ["DONE", "BLOCKED"].includes(previous.phase))
|
|
557
704
|
return {status: "IGNORED", code: "NO_ACTIVE_OWNER"};
|
|
558
705
|
if (previous.tabId !== tabId || previous.page !== message.page)
|
|
@@ -564,46 +711,53 @@ async function onTurnFinished(message, sender) {
|
|
|
564
711
|
return {status: "IGNORED", code: "ALREADY_HANDLED"};
|
|
565
712
|
if (previous.phase !== "WAITING_REPLY")
|
|
566
713
|
return {status: "IGNORED", code: "INVALID_PHASE"};
|
|
567
|
-
|
|
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) {
|
|
568
726
|
await saveRun({...previous, phase: "BLOCKED", reason: "REPLY_USER_MISMATCH"});
|
|
569
727
|
return {status: "BLOCKED", code: "REPLY_USER_MISMATCH"};
|
|
570
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
|
+
}
|
|
571
745
|
let replyText = message.replyText;
|
|
572
746
|
let status = globalThis.ChatLoopCoreV1.parseStatus(replyText);
|
|
573
747
|
if (status === "UNKNOWN") {
|
|
574
748
|
const recovery = await recheckUnknownTurn(message, previous, tabId);
|
|
575
749
|
if (recovery) {status = recovery.status; replyText = recovery.replyText;}
|
|
576
750
|
}
|
|
577
|
-
// Dedicated acceptance Chats only: retain the exact unrecognized reply to
|
|
578
|
-
// diagnose real UI text wrappers. Never persist private user Chat text.
|
|
579
|
-
let parseEvidence = null;
|
|
580
|
-
if (status === "UNKNOWN") {
|
|
581
|
-
const owned = (await chrome.storage.local.get("chat-loop.acceptance.owned.v1"))[
|
|
582
|
-
"chat-loop.acceptance.owned.v1"];
|
|
583
|
-
if (Array.isArray(owned) && owned.some(item => item.id === tabId || item.id === previous?.sourceTabId)) {
|
|
584
|
-
parseEvidence = {replyText: message.replyText.slice(0, 2500),
|
|
585
|
-
length: message.replyText.length, capturedAt: Date.now()};
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
const countMode = previous?.countMode === true;
|
|
589
|
-
let verifiedCount = null;
|
|
590
|
-
if (countMode && (status === "CONTINUE" || status === "DONE")) {
|
|
591
|
-
verifiedCount = readCount(replyText);
|
|
592
|
-
if (verifiedCount !== previous.countValue + 1
|
|
593
|
-
|| status !== (verifiedCount === 100 ? "DONE" : "CONTINUE")) {
|
|
594
|
-
await saveRun({...previous, phase: "BLOCKED", reason: "COUNT_STEP_UNVERIFIED"});
|
|
595
|
-
return {status: "BLOCKED", code: "COUNT_STEP_UNVERIFIED"};
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
751
|
const now = Date.now();
|
|
599
752
|
// Keep the same clock throughout one Chat. A successful Handoff resets it.
|
|
600
753
|
const initial = Number.isSafeInteger(message.startedAt) && message.startedAt > 0
|
|
601
754
|
&& message.startedAt <= now ? message.startedAt : now;
|
|
602
|
-
const startedAt = previous?.phase === "WAITING_REPLY"
|
|
755
|
+
const startedAt = previous?.phase === "WAITING_REPLY"
|
|
756
|
+
? previous.startedAt || now : initial;
|
|
603
757
|
const timeExpired = now >= startedAt + windowMsOf(previous);
|
|
604
758
|
// Deadline intent can be persisted by the timer even while a Turn RUNS.
|
|
605
759
|
// The decision below still waits for the observer's complete Turn proof.
|
|
606
|
-
const queued = previous?.modelIntent?.page===message.page
|
|
760
|
+
const queued = !humanReply && previous?.modelIntent?.page===message.page
|
|
607
761
|
&& previous.modelIntent.userKey===message.userKey ? previous.modelIntent : null;
|
|
608
762
|
// Existing DONE/BLOCKED, deadline and page-error policies still win.
|
|
609
763
|
// A queued model request only changes a still-eligible CONTINUE Turn.
|
|
@@ -615,35 +769,11 @@ async function onTurnFinished(message, sender) {
|
|
|
615
769
|
if (previous?.phase === "WAITING_REPLY" && previous.tabId === tabId) {
|
|
616
770
|
await saveRun({...previous, phase: status === "DONE" ? "DONE" : "BLOCKED",
|
|
617
771
|
reason: status, userKey: message.userKey, assistantKey: message.assistantKey,
|
|
618
|
-
|
|
619
|
-
...(parseEvidence ? {parseEvidence} : {})});
|
|
772
|
+
});
|
|
620
773
|
}
|
|
621
774
|
return {status: "IGNORED", code: nextAction === "UNSUPPORTED_MODEL_HANDOFF"
|
|
622
775
|
? "MODEL_HANDOFF_DISABLED" : status};
|
|
623
776
|
}
|
|
624
|
-
// Historical 1h/2h endurance fixtures explicitly park the Chat to avoid
|
|
625
|
-
// huge message counts; the real 10m acceptance MUST use the normal running
|
|
626
|
-
// loop: each finished CONTINUE immediately dispatches Continue, without a hold.
|
|
627
|
-
if (previous?.wallTestHours
|
|
628
|
-
&& status === "CONTINUE" && !timeExpired
|
|
629
|
-
&& !previous.wallReleasedAt && previous.phase === "WAITING_REPLY") {
|
|
630
|
-
const releaseAt = startedAt + (previous.wallTestMinutes === 10
|
|
631
|
-
? RUN_BUDGET_MS : previous.wallTestHours * HOUR_MS);
|
|
632
|
-
await saveRun({...previous, phase: "WALL_CLOCK_HOLD", reason: "ACCEPTANCE_WALL_WAIT",
|
|
633
|
-
userKey: message.userKey, assistantKey: message.assistantKey,
|
|
634
|
-
wallHoldAt: now, wallReleaseAt: releaseAt});
|
|
635
|
-
return {status: "WAITING_DEADLINE", releaseAt};
|
|
636
|
-
}
|
|
637
|
-
// Count acceptance: completion is recorded now, but the next Continue is
|
|
638
|
-
// not authorized until 60 real seconds after the previous confirmed send.
|
|
639
|
-
if (countMode && nextAction === "CONTINUE" && !timeExpired
|
|
640
|
-
&& now < previous.countLastSendAt + COUNT_INTERVAL_MS) {
|
|
641
|
-
const countReleaseAt = previous.countLastSendAt + COUNT_INTERVAL_MS;
|
|
642
|
-
await saveRun({...previous, phase: "WAITING_INTERVAL", reason: "COUNT_INTERVAL",
|
|
643
|
-
userKey: message.userKey, assistantKey: message.assistantKey,
|
|
644
|
-
countValue: verifiedCount, countReleaseAt});
|
|
645
|
-
return {status: "WAITING_INTERVAL", countReleaseAt};
|
|
646
|
-
}
|
|
647
777
|
// Recheck at the last new-authorization boundary, even if a periodic or
|
|
648
778
|
// one-shot alarm was delayed while the Worker handled completion evidence.
|
|
649
779
|
const newlyDue = Date.now() >= startedAt + windowMsOf(previous);
|
|
@@ -654,35 +784,20 @@ async function onTurnFinished(message, sender) {
|
|
|
654
784
|
tabId, page: message.page, userKey: message.userKey,
|
|
655
785
|
assistantKey: message.assistantKey, phase: "RESERVED", token,
|
|
656
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} : {}),
|
|
657
795
|
...(previous?.lastFaultProof ? {lastFaultProof:previous.lastFaultProof} : {}),
|
|
658
|
-
...(countMode ? {countMode:true, countValue:verifiedCount,
|
|
659
|
-
countLastSendAt:previous.countLastSendAt,
|
|
660
|
-
countHandoffs:previous.countHandoffs || 0} : {}),
|
|
661
796
|
...((previous?.handoffPending || newlyDue) ? {
|
|
662
797
|
handoffPending: true,
|
|
663
798
|
handoffPendingAt: previous?.handoffPendingAt || Date.now()} : {}),
|
|
664
799
|
// A completed Turn is a successful recovery and clears the consecutive error-Handoff guard.
|
|
665
800
|
errorHandoffCount: 0,
|
|
666
|
-
// Carry only dedicated acceptance evidence across the finished Turn. The
|
|
667
|
-
// evidence proves the deadline was crossed while Observer was RUNNING.
|
|
668
|
-
...(previous?.timedTest && previous?.clockAdvancedAt ? {
|
|
669
|
-
timedTest: true, clockAdvancedAt: previous.clockAdvancedAt,
|
|
670
|
-
clockAdvanceMinutes: previous.clockAdvanceMinutes,
|
|
671
|
-
clockRunningProof: previous.clockRunningProof} : {}),
|
|
672
|
-
// Keep the 10m continuous-flow test identity only for audit evidence;
|
|
673
|
-
// unlike historical hour-long endurance it never delays the next Continue.
|
|
674
|
-
...(previous?.timedTest && previous?.wallTestMinutes === 10 ? {
|
|
675
|
-
timedTest: true, wallTestMinutes: 10,
|
|
676
|
-
testTurnIndex: (previous.testTurnIndex || 1) + 1} : {}),
|
|
677
|
-
// Preserve historical wall-clock hold receipt across its subsequent Turn.
|
|
678
|
-
...(previous?.timedTest && previous?.wallReleasedAt ? {
|
|
679
|
-
timedTest: true, wallTestHours: previous.wallTestHours,
|
|
680
|
-
wallHoldAt: previous.wallHoldAt, wallReleaseAt: previous.wallReleaseAt,
|
|
681
|
-
wallReleasedAt: previous.wallReleasedAt,
|
|
682
|
-
...([10, 20].includes(previous.wallTestMinutes) ? {
|
|
683
|
-
wallTestMinutes: previous.wallTestMinutes,
|
|
684
|
-
...(previous.wallTestMinutes === 20 ? {wallAdjustedAt: previous.wallAdjustedAt,
|
|
685
|
-
wallOriginalReleaseAt: previous.wallOriginalReleaseAt} : {})} : {})} : {}),
|
|
686
801
|
// A timed Handoff uses an Action-local read-only snapshot. Do not keep
|
|
687
802
|
// the entire conversation in storage or embed it in the Action URL.
|
|
688
803
|
handoffMode: nextAction === "HANDOFF" ? "TIMED" : null,
|
|
@@ -710,42 +825,32 @@ async function onTurnFinished(message, sender) {
|
|
|
710
825
|
return {status: "BLOCKED", code: error.message || "ACTION_PAGE_CREATE_FAILED"};
|
|
711
826
|
}
|
|
712
827
|
}
|
|
713
|
-
//
|
|
714
|
-
//
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
const
|
|
719
|
-
if
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
return;
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
||
|
|
729
|
-
||
|
|
730
|
-
|
|
731
|
-
return;
|
|
732
|
-
}
|
|
733
|
-
const
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
try {
|
|
739
|
-
await createBoundedAction({url:chrome.runtime.getURL(action === "HANDOFF"
|
|
740
|
-
? "handoff.html" : "continue.html") + "?tabId=" + old.tabId
|
|
741
|
-
+ "&token=" + encodeURIComponent(run.token), active:false, windowId:tab.windowId});
|
|
742
|
-
} catch {
|
|
743
|
-
await saveRun({...run,phase:"BLOCKED",reason:"COUNT_ACTION_OPEN_FAILED"});
|
|
744
|
-
}
|
|
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;
|
|
745
853
|
}
|
|
746
|
-
// Opening a formal Action page manually is a supported test/debug entry.
|
|
747
|
-
// No token in URL: the Worker verifies a single explicit target and reserves
|
|
748
|
-
// this exact Action tab. It never sends or creates the new Chat itself.
|
|
749
854
|
async function onManualPrepare(message, sender) {
|
|
750
855
|
const requested = message.action;
|
|
751
856
|
if (!["CONTINUE", "HANDOFF"].includes(requested)
|
|
@@ -754,14 +859,40 @@ async function onManualPrepare(message, sender) {
|
|
|
754
859
|
let url;
|
|
755
860
|
try { url = new URL(sender.url); } catch {return {status: "DENIED", code: "INVALID_ACTION_URL"};}
|
|
756
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"};
|
|
757
872
|
if (url.origin !== new URL(chrome.runtime.getURL(filename)).origin
|
|
758
873
|
|| url.pathname !== "/" + filename || url.searchParams.has("token")
|
|
759
|
-
|| 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
|
|
760
876
|
|| (rawTabId !== null && (!/^[1-9][0-9]*$/.test(rawTabId)
|
|
761
877
|
|| message.tabId !== Number(rawTabId))))
|
|
762
878
|
return {status: "DENIED", code: "INVALID_ACTION_URL"};
|
|
763
|
-
const previous = await
|
|
764
|
-
|
|
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
|
|
765
896
|
|| !["DONE", "BLOCKED"].includes(previous.phase)))
|
|
766
897
|
return {status: "DENIED", code: "LOOP_ALREADY_ACTIVE"};
|
|
767
898
|
const candidates = await chrome.tabs.query({url: "https://chatgpt.com/*"});
|
|
@@ -784,11 +915,24 @@ async function onManualPrepare(message, sender) {
|
|
|
784
915
|
|| second.userKey !== first.userKey || second.assistantKey !== first.assistantKey
|
|
785
916
|
|| second.replyText !== first.replyText) return {status: "DENIED", code: "TURN_NOT_STABLE"};
|
|
786
917
|
const modelStatus = globalThis.ChatLoopCoreV1.parseStatus(first.replyText);
|
|
787
|
-
|
|
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
|
|
788
931
|
|| requested === "HANDOFF" && !["HANDOFF", "CONTINUE"].includes(modelStatus))
|
|
789
932
|
return {status: "DENIED", code: "ACTION_MARKER_MISMATCH"};
|
|
790
933
|
if (previous && previous.tabId === tab.id && previous.page === first.page
|
|
791
|
-
&& (previous.userKey === first.userKey || previous.assistantKey === first.assistantKey)
|
|
934
|
+
&& (previous.userKey === first.userKey || previous.assistantKey === first.assistantKey)
|
|
935
|
+
&&!ownedRecovery)
|
|
792
936
|
return {status: "DENIED", code: "ALREADY_HANDLED"};
|
|
793
937
|
const summary = modelStatus === "HANDOFF"
|
|
794
938
|
? first.replyText.replace(/\r?\n\[CHAT_LOOP_STATUS:HANDOFF\]\s*$/, "").trim() : null;
|
|
@@ -796,199 +940,32 @@ async function onManualPrepare(message, sender) {
|
|
|
796
940
|
|| !/目标/.test(summary) || !/已完成|进度/.test(summary)
|
|
797
941
|
|| !/下一步|待办/.test(summary)))
|
|
798
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
|
+
}
|
|
799
954
|
const token = crypto.randomUUID();
|
|
800
|
-
await saveRun({
|
|
955
|
+
await saveRun({...(ownedRecovery?previous:{}),
|
|
956
|
+
tabId: tab.id, page: first.page, userKey: first.userKey,
|
|
801
957
|
assistantKey: first.assistantKey, phase: "RESERVED", token,
|
|
802
|
-
action: requested, startedAt:
|
|
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}:{}),
|
|
803
964
|
handoffMode: requested === "HANDOFF"
|
|
804
965
|
? (modelStatus === "HANDOFF" ? "EXPLICIT" : "TIMED") : null,
|
|
805
966
|
...(summary ? {handoffText: summary} : {})});
|
|
806
967
|
return {status: "PREPARED", token, tabId: tab.id};
|
|
807
968
|
}
|
|
808
|
-
// This is a test preparation permit, not a successful Continue regression.
|
|
809
|
-
// Both readiness probes are read-only; PENDING must be durable before any edit.
|
|
810
|
-
async function onTestPrepare(message, sender) {
|
|
811
|
-
const tabId = message.tabId;
|
|
812
|
-
if (!Number.isInteger(tabId) || !Number.isInteger(sender.tab?.id)
|
|
813
|
-
|| ![chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1",
|
|
814
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&discardDraft=1",
|
|
815
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&timed=1",
|
|
816
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&discardDraft=1&timed=1",
|
|
817
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&timed=1&wall=1",
|
|
818
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&discardDraft=1&timed=1&wall=1",
|
|
819
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&timed=1&wall=2",
|
|
820
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&discardDraft=1&timed=1&wall=2",
|
|
821
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&timed=1&wall=10m",
|
|
822
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&discardDraft=1&timed=1&wall=10m",
|
|
823
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&timed=1&wall=10m&count=86",
|
|
824
|
-
chrome.runtime.getURL("continue.html") + "?tabId=" + tabId + "&setup=1&discardDraft=1&timed=1&wall=10m&count=86"].includes(sender.url))
|
|
825
|
-
return {status: "DENIED", code: "INVALID_TEST_ACTION"};
|
|
826
|
-
const previous = await readRun();
|
|
827
|
-
if (previous && (previous.sessionId&&previous.phase!=="DONE"
|
|
828
|
-
|| !["DONE", "BLOCKED"].includes(previous.phase)))
|
|
829
|
-
return {status: "DENIED", code: "LOOP_ALREADY_ACTIVE"};
|
|
830
|
-
if (previous?.tabId === tabId)
|
|
831
|
-
return {status: "DENIED", code: "TEST_TARGET_ALREADY_USED"};
|
|
832
|
-
const tab = await chrome.tabs.get(tabId).catch(() => null);
|
|
833
|
-
if (tab?.url !== "https://chatgpt.com/")
|
|
834
|
-
return {status: "DENIED", code: "TEST_TARGET_NOT_BLANK"};
|
|
835
|
-
const params = new URL(sender.url).searchParams;
|
|
836
|
-
const discardDraft = params.get("discardDraft") === "1";
|
|
837
|
-
const timedTest = params.get("timed") === "1";
|
|
838
|
-
const wall = params.get("wall");
|
|
839
|
-
const wallTestHours = wall && wall !== "10m" ? Number(wall) : null;
|
|
840
|
-
const wallTestMinutes = wall === "10m" ? 10 : null;
|
|
841
|
-
const countMode = params.get("count") === "86";
|
|
842
|
-
if (params.has("count") && (!countMode || !timedTest || wallTestMinutes !== 10))
|
|
843
|
-
return {status:"DENIED",code:"COUNT_TEST_INVALID"};
|
|
844
|
-
if (wall !== null && (!timedTest || !(wallTestMinutes === 10 || [1, 2].includes(wallTestHours))))
|
|
845
|
-
return {status: "DENIED", code: "INVALID_WALL_TEST"};
|
|
846
|
-
if (timedTest) {
|
|
847
|
-
const registry = (await chrome.storage.local.get("chat-loop.acceptance.owned.v1"))[
|
|
848
|
-
"chat-loop.acceptance.owned.v1"];
|
|
849
|
-
if (!Array.isArray(registry) || !registry.some(item => item.id === tabId))
|
|
850
|
-
return {status: "DENIED", code: "TIMED_TEST_OWNERSHIP_REQUIRED"};
|
|
851
|
-
}
|
|
852
|
-
const probe = async () => {
|
|
853
|
-
const [read] = await chrome.scripting.executeScript({target: {tabId}, func: allowDiscard => {
|
|
854
|
-
const visible = node => Boolean(node?.getClientRects?.().length);
|
|
855
|
-
const mains = [...document.querySelectorAll("main")].filter(visible);
|
|
856
|
-
const input = document.querySelector('[contenteditable="true"][data-composer-markdown]')
|
|
857
|
-
|| document.querySelector('#prompt-textarea[contenteditable="true"]');
|
|
858
|
-
const draft = (input?.innerText || input?.textContent || "").trim();
|
|
859
|
-
const knownTestDraft = (draft.includes("LOOP-V037-FAST-3C1H") || (draft.startsWith("你正在接手上一 Chat 未完成的任务。旧 Chat 的网页历史仍可核实")
|
|
860
|
-
&& draft.includes("【交接参考:只读网页片段,可能截断】")
|
|
861
|
-
&& draft.includes("【原始任务用户消息】")
|
|
862
|
-
&& draft.includes("【最近轮次证据】")
|
|
863
|
-
&& draft.endsWith("是否跨 Chat 由扩展决定,不要主动要求 Handoff。")
|
|
864
|
-
&& draft.length >= 450 && draft.length <= 8192)) && (
|
|
865
|
-
(draft.startsWith("这是 Chat Loop 短轮回归专用测试") && draft.length <= 800)
|
|
866
|
-
|| (draft.startsWith("你正在接手上一 Chat 尚未完成的同一个任务")
|
|
867
|
-
&& draft.length <= 8192 && (draft.length <= 2000
|
|
868
|
-
|| (draft.includes("【原始任务用户消息】") && draft.includes("【最近轮次证据】"))))
|
|
869
|
-
|| (draft.startsWith("你正在接手上一 Chat 未完成的任务。旧 Chat 的网页历史仍可核实")
|
|
870
|
-
&& draft.includes("【原始任务用户消息】") && draft.includes("【最近轮次证据】")
|
|
871
|
-
&& draft.endsWith("是否跨 Chat 由扩展决定,不要主动要求 Handoff。")
|
|
872
|
-
&& draft.length >= 450 && draft.length <= 8192)
|
|
873
|
-
|| (draft.startsWith("这是 Chat Loop 的计数隔离验收")
|
|
874
|
-
&& draft.includes("COUNT-86-100") && draft.endsWith("WALL-CLOCK-TEST。"))
|
|
875
|
-
|| ((draft.startsWith("这是 Chat Loop 的长回复与一小时边界隔离测试")
|
|
876
|
-
|| draft.startsWith("这是 Chat Loop 的墙钟边界隔离测试"))
|
|
877
|
-
&& (draft.includes("MODE-TIMED-1H") || draft.includes("MODE-WALL-10M"))));
|
|
878
|
-
return location.href === "https://chatgpt.com/" && mains.length === 1
|
|
879
|
-
&& !mains[0].querySelector('[data-chatgpt-search-message-ids],[data-message-author-role]')
|
|
880
|
-
&& visible(input) && (!draft || (allowDiscard && knownTestDraft))
|
|
881
|
-
&& ![...document.querySelectorAll('button[data-testid="stop-button"]')].some(visible);
|
|
882
|
-
}, args: [discardDraft]});
|
|
883
|
-
return read?.result === true;
|
|
884
|
-
};
|
|
885
|
-
if (!await probe()) return {status: "DENIED", code: "TEST_TARGET_NOT_EMPTY"};
|
|
886
|
-
await new Promise(resolve => setTimeout(resolve, 2300));
|
|
887
|
-
if (!await probe()) return {status: "DENIED", code: "TEST_TARGET_NOT_STABLE"};
|
|
888
|
-
const token = crypto.randomUUID();
|
|
889
|
-
await saveRun({tabId, page: "/", userKey: null, assistantKey: null,
|
|
890
|
-
phase: "RESERVED", token, action: "CONTINUE", testSetup: true, discardDraft,
|
|
891
|
-
...(timedTest ? {timedTest: true} : {}),
|
|
892
|
-
...(wallTestHours ? {wallTestHours} : {}),
|
|
893
|
-
...(wallTestMinutes ? {wallTestMinutes} : {}),
|
|
894
|
-
...(countMode ? {countMode:true, countValue:86, countHandoffs:0} : {}),
|
|
895
|
-
// The first Turn starts with a real clock, including acceptance tests.
|
|
896
|
-
// A dedicated test Action may advance it later only while Observer RUNNING.
|
|
897
|
-
startedAt: Date.now(),
|
|
898
|
-
manualActionTabId: sender.tab.id});
|
|
899
|
-
return {status: "PREPARED", token, tabId};
|
|
900
|
-
}
|
|
901
|
-
async function onAcceptanceShortenWallHold(message, sender) {
|
|
902
|
-
// User-requested shortening of an existing *owned acceptance* wait.
|
|
903
|
-
// The real elapsed time must already exceed 20 min; never backdate time.
|
|
904
|
-
const tabId = message.tabId, now = Date.now();
|
|
905
|
-
if (!Number.isSafeInteger(tabId) || tabId <= 0
|
|
906
|
-
|| message.minutes !== 20 || !Number.isSafeInteger(sender.tab?.id)
|
|
907
|
-
|| sender.url !== chrome.runtime.getURL("clock.html")
|
|
908
|
-
+ "?tabId=" + tabId + "&minutes=20")
|
|
909
|
-
return {status: "DENIED", code: "SHORTEN_SOURCE_INVALID"};
|
|
910
|
-
const run = await readRun();
|
|
911
|
-
if (run?.phase !== "WALL_CLOCK_HOLD" || run.tabId !== tabId
|
|
912
|
-
|| run.timedTest !== true || run.wallTestHours !== 2
|
|
913
|
-
|| run.wallAdjustedAt || !run.userKey || !run.assistantKey
|
|
914
|
-
|| !Number.isSafeInteger(run.startedAt)
|
|
915
|
-
|| now < run.startedAt + 20 * 60 * 1000)
|
|
916
|
-
return {status: "DENIED", code: "SHORTEN_NOT_ELIGIBLE"};
|
|
917
|
-
const owned = (await chrome.storage.local.get("chat-loop.acceptance.owned.v1"))[
|
|
918
|
-
"chat-loop.acceptance.owned.v1"];
|
|
919
|
-
if (!Array.isArray(owned) || !owned.some(item => item.id === tabId))
|
|
920
|
-
return {status: "DENIED", code: "SHORTEN_NOT_OWNED"};
|
|
921
|
-
const tab = await chrome.tabs.get(tabId).catch(() => null);
|
|
922
|
-
if (!tab || pathOf(tab.url) !== run.page)
|
|
923
|
-
return {status: "DENIED", code: "SHORTEN_TARGET_CHANGED"};
|
|
924
|
-
const verify = async () => {
|
|
925
|
-
const proof = await chrome.tabs.sendMessage(tabId,
|
|
926
|
-
{type: "CHAT_LOOP_TURN_VERIFY_V1"}).catch(() => null);
|
|
927
|
-
return proof?.contract === "chat-loop.turn-observer.v1"
|
|
928
|
-
&& proof.status === "READY" && proof.page === run.page
|
|
929
|
-
&& proof.userKey === run.userKey
|
|
930
|
-
&& proof.assistantKey === run.assistantKey
|
|
931
|
-
&& globalThis.ChatLoopCoreV1.parseStatus(proof.replyText) === "CONTINUE";
|
|
932
|
-
};
|
|
933
|
-
if (!await verify()) return {status: "DENIED", code: "SHORTEN_NOT_STABLE"};
|
|
934
|
-
await new Promise(resolve => setTimeout(resolve, 2300));
|
|
935
|
-
if (!await verify()) return {status: "DENIED", code: "SHORTEN_IDENTITY_CHANGED"};
|
|
936
|
-
const latest = await readRun();
|
|
937
|
-
if (latest?.phase !== "WALL_CLOCK_HOLD" || latest.tabId !== run.tabId
|
|
938
|
-
|| latest.wallHoldAt !== run.wallHoldAt || latest.userKey !== run.userKey)
|
|
939
|
-
return {status: "DENIED", code: "SHORTEN_OWNER_CHANGED"};
|
|
940
|
-
const changed = {...latest,
|
|
941
|
-
wallOriginalReleaseAt: latest.wallReleaseAt,
|
|
942
|
-
wallReleaseAt: latest.startedAt + 20 * 60 * 1000,
|
|
943
|
-
wallTestMinutes: 20, wallAdjustedAt: Date.now()};
|
|
944
|
-
await saveRun(changed);
|
|
945
|
-
return {status: "SHORTENED_AFTER_REAL_20MIN", tabId,
|
|
946
|
-
startedAt: changed.startedAt, releaseAt: changed.wallReleaseAt,
|
|
947
|
-
adjustedAt: changed.wallAdjustedAt};
|
|
948
|
-
}
|
|
949
|
-
async function onAcceptanceClockAdvance(message, sender) {
|
|
950
|
-
if (message?.minutes === 20) return onAcceptanceShortenWallHold(message, sender);
|
|
951
|
-
// Test-only clock mutation. All production time comparisons remain unchanged.
|
|
952
|
-
// This must happen DURING the assistant Turn, never before the first Turn.
|
|
953
|
-
const tabId = message.tabId, minutes = message.minutes;
|
|
954
|
-
if (!Number.isSafeInteger(tabId) || tabId <= 0
|
|
955
|
-
|| !Number.isSafeInteger(minutes) || minutes < 60 || minutes > 180
|
|
956
|
-
|| sender.url !== chrome.runtime.getURL("clock.html")
|
|
957
|
-
+ "?tabId=" + tabId + "&minutes=" + minutes
|
|
958
|
-
|| !Number.isSafeInteger(sender.tab?.id))
|
|
959
|
-
return {status: "DENIED", code: "CLOCK_ACTION_SOURCE_INVALID"};
|
|
960
|
-
const run = await readRun();
|
|
961
|
-
if (run?.phase !== "WAITING_REPLY" || run?.action !== "CONTINUE"
|
|
962
|
-
|| run?.tabId !== tabId || run?.timedTest !== true
|
|
963
|
-
|| run?.clockAdvancedAt || !run.newUserKey || !run.page
|
|
964
|
-
|| run.testSetup) return {status: "DENIED", code: "CLOCK_TEST_NOT_WAITING"};
|
|
965
|
-
const owned = (await chrome.storage.local.get("chat-loop.acceptance.owned.v1"))[
|
|
966
|
-
"chat-loop.acceptance.owned.v1"];
|
|
967
|
-
if (!Array.isArray(owned) || !owned.some(item => item.id === tabId))
|
|
968
|
-
return {status: "DENIED", code: "CLOCK_TEST_NOT_OWNED"};
|
|
969
|
-
const live = await chrome.tabs.get(tabId).catch(() => null);
|
|
970
|
-
if (!live || pathOf(live.url) !== run.page)
|
|
971
|
-
return {status: "DENIED", code: "CLOCK_TARGET_CHANGED"};
|
|
972
|
-
const sample = async () => chrome.tabs.sendMessage(tabId,
|
|
973
|
-
{type: "CHAT_LOOP_TURN_OBSERVE_V1", poll: true}).catch(() => null);
|
|
974
|
-
const isRunning = x => x?.contract === "chat-loop.turn-observer.v1"
|
|
975
|
-
&& x.status === "RUNNING" && x.page === run.page
|
|
976
|
-
&& x.userKey === run.newUserKey;
|
|
977
|
-
const first = await sample();
|
|
978
|
-
if (!isRunning(first)) return {status: "DENIED", code: "CLOCK_TURN_NOT_RUNNING"};
|
|
979
|
-
await new Promise(resolve => setTimeout(resolve, 300));
|
|
980
|
-
const second = await sample();
|
|
981
|
-
if (!isRunning(second)) return {status: "DENIED", code: "CLOCK_TURN_NOT_STABLE_RUNNING"};
|
|
982
|
-
const now = Date.now();
|
|
983
|
-
// Advance by a test-chosen elapsed duration, not by a hard-coded 61 minutes.
|
|
984
|
-
// No scheduler event or writing action is dispatched at this moment.
|
|
985
|
-
await saveRun({...run, startedAt: now - minutes * 60000,
|
|
986
|
-
clockAdvancedAt: now, clockAdvanceMinutes: minutes,
|
|
987
|
-
clockRunningProof: {first: first.reason, second: second.reason,
|
|
988
|
-
userKey: run.newUserKey, observedAt: second.observedAt}});
|
|
989
|
-
return {status: "ADVANCED_WHILE_RUNNING", minutes, tabId,
|
|
990
|
-
firstReason: first.reason, secondReason: second.reason};
|
|
991
|
-
}
|
|
992
969
|
const isAction = (sender, message, run) => {
|
|
993
970
|
if (!Number.isInteger(sender.tab?.id) || typeof sender.url !== "string") return false;
|
|
994
971
|
try {
|
|
@@ -1006,21 +983,35 @@ const isAction = (sender, message, run) => {
|
|
|
1006
983
|
async function onTake(message, sender) {
|
|
1007
984
|
const run = await readRun();
|
|
1008
985
|
if (!isAction(sender, message, run)) return {status: "DENIED", code: "ACTION_SOURCE_INVALID"};
|
|
1009
|
-
if (run?.countMode && run.action === "CONTINUE" && !run.testSetup
|
|
1010
|
-
&& Date.now() < run.countLastSendAt + COUNT_INTERVAL_MS)
|
|
1011
|
-
return {status:"DENIED",code:"COUNT_INTERVAL_NOT_DUE"};
|
|
1012
986
|
if (run?.phase !== "RESERVED" || run.token !== message.token
|
|
1013
987
|
|| run.tabId !== message.tabId) return {status: "DENIED", code: "ACTION_NOT_RESERVED"};
|
|
1014
988
|
const tab = await chrome.tabs.get(run.tabId).catch(() => null);
|
|
1015
|
-
if (!tab ||
|
|
989
|
+
if (!tab || pathOf(tab.url) !== run.page) {
|
|
1016
990
|
await saveRun({...run, phase: "BLOCKED", reason: "CHAT_TARGET_CHANGED"});
|
|
1017
991
|
return {status: "DENIED", code: "CHAT_TARGET_CHANGED"};
|
|
1018
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
|
+
}
|
|
1019
1011
|
// Bind a model-control capability to the next *user* Turn, not to a tab or to another Chat.
|
|
1020
1012
|
// Acceptance fixtures retain their existing prompts; native Retry keeps its original Turn token.
|
|
1021
|
-
const modelTurnToken = run.retryMode === "NATIVE"
|
|
1022
|
-
|
|
1023
|
-
? null : crypto.randomUUID();
|
|
1013
|
+
const modelTurnToken = run.retryMode === "NATIVE"
|
|
1014
|
+
? run.modelTurnToken || null : crypto.randomUUID();
|
|
1024
1015
|
const pending={...run, phase: "PENDING", modelTurnToken};
|
|
1025
1016
|
await saveRun(run.modelIntent ? updateModelReceipt(pending,run.modelIntent.id,{
|
|
1026
1017
|
status:run.action==="HANDOFF"&&run.modelIntent.action==="CONTINUE"
|
|
@@ -1029,21 +1020,20 @@ async function onTake(message, sender) {
|
|
|
1029
1020
|
modelTurnToken,
|
|
1030
1021
|
modelTurnNote: modelTurnToken ? turnToolNote(modelTurnToken) : "",
|
|
1031
1022
|
handoffMode: run.handoffMode || null, retryMode: run.retryMode || null,
|
|
1032
|
-
|
|
1033
|
-
countValue: run.countMode ? run.countValue : null,
|
|
1023
|
+
recoveryMode:run.recoveryMode||null,
|
|
1034
1024
|
target: {tabId: run.tabId, page: run.page,
|
|
1025
|
+
recoveryMode:run.recoveryMode||null,
|
|
1035
1026
|
assistantKey: run.assistantKey,
|
|
1036
1027
|
userKey: run.retryMode === "NATIVE" || run.handoffMode === "ERROR"
|
|
1037
1028
|
? run.newUserKey : run.userKey,
|
|
1038
|
-
|
|
1029
|
+
},
|
|
1039
1030
|
modelIntent: run.action==="HANDOFF" && run.modelIntent?.action==="HANDOFF"
|
|
1040
1031
|
? {id:run.modelIntent.id,reason:run.modelIntent.reason||""} : null,
|
|
1041
1032
|
pendingPlan: run.action==="HANDOFF" && run.modelIntent?.action==="CONTINUE"
|
|
1042
1033
|
? {id:run.modelIntent.id,nextPrompt:run.modelIntent.nextPrompt} : null,
|
|
1043
|
-
text: run.
|
|
1044
|
-
: run.
|
|
1045
|
-
|
|
1046
|
-
: run.action === "HANDOFF" ? run.handoffText || null
|
|
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]。"
|
|
1047
1037
|
: run.modelIntent?.action==="CONTINUE" ? (
|
|
1048
1038
|
"【Chat Loop 续接来源】上一轮由模型登记的 Continue 请求 " + run.modelIntent.id
|
|
1049
1039
|
+ " 已被扩展唯一 Action 领取。\n"
|
|
@@ -1051,9 +1041,7 @@ async function onTake(message, sender) {
|
|
|
1051
1041
|
+ run.modelIntent.nextPrompt + "\n\n"
|
|
1052
1042
|
+ "执行前核对当前项目状态、既有用户授权和已完成副作用,不重做不明操作。"
|
|
1053
1043
|
+ "本轮完成后,末行只输出一个状态标记:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。")
|
|
1054
|
-
:
|
|
1055
|
-
: run.timedTest && run.wallTestMinutes === 10
|
|
1056
|
-
? wallArithmeticText(run.testTurnIndex || 2) : CONTINUE_TEXT};
|
|
1044
|
+
: CONTINUE_TEXT};
|
|
1057
1045
|
if (modelTurnToken && typeof permit.text === "string")
|
|
1058
1046
|
permit.text += permit.modelTurnNote;
|
|
1059
1047
|
return permit;
|
|
@@ -1111,31 +1099,16 @@ async function onResult(message, sender) {
|
|
|
1111
1099
|
// its first Retry/Error Handoff using the OLD Chat's assistant ID.
|
|
1112
1100
|
userKey: null, assistantKey: null, startedAt: Date.now(),
|
|
1113
1101
|
errorHandoffCount: run.handoffMode === "ERROR" ? (run.errorHandoffCount || 0) + 1 : 0,
|
|
1114
|
-
|
|
1115
|
-
countHandoffs:(run.countHandoffs || 0) + 1,
|
|
1116
|
-
countLastSendAt:Date.now()} : {})};
|
|
1102
|
+
};
|
|
1117
1103
|
delete next.handoffText;
|
|
1118
1104
|
delete next.errorReason;
|
|
1119
1105
|
delete next.handoffPending;
|
|
1120
1106
|
delete next.handoffPendingAt;
|
|
1121
1107
|
delete next.deadlineAt;
|
|
1122
1108
|
}
|
|
1123
|
-
} else if (confirmed && run.testSetup) {
|
|
1124
|
-
const tab = await chrome.tabs.get(run.tabId).catch(() => null);
|
|
1125
|
-
confirmed = Boolean(tab && pathOf(tab.url) && pathOf(tab.url) === message.newPage);
|
|
1126
|
-
if (confirmed) {
|
|
1127
|
-
next = {...run, page: message.newPage, phase: "WAITING_REPLY", reason: "",
|
|
1128
|
-
newUserKey: message.newUserKey,
|
|
1129
|
-
...(run.wallTestMinutes === 10 ? {testTurnIndex: 1} : {}),
|
|
1130
|
-
...(run.countMode ? {countLastSendAt:Date.now()} : {}),
|
|
1131
|
-
...(run.wallTestHours ? {startedAt: Date.now()} : {})};
|
|
1132
|
-
delete next.testSetup;
|
|
1133
|
-
delete next.discardDraft;
|
|
1134
|
-
}
|
|
1135
1109
|
} else if (confirmed) {
|
|
1136
1110
|
next = {...run, phase: "WAITING_REPLY", reason: "",
|
|
1137
|
-
newUserKey: message.newUserKey
|
|
1138
|
-
...(run.countMode ? {countLastSendAt:Date.now()} : {})};
|
|
1111
|
+
newUserKey: message.newUserKey};
|
|
1139
1112
|
}
|
|
1140
1113
|
// A model prompt is one-shot. Keep only a short receipt, not the prompt
|
|
1141
1114
|
// body, after the Action has reached a confirmed or blocked terminal state.
|
|
@@ -1168,9 +1141,22 @@ async function reconnectOpenChats() {
|
|
|
1168
1141
|
const owner = await readRun();
|
|
1169
1142
|
if (owner?.phase === "WAITING_REPLY" && owner.tabId === tab.id
|
|
1170
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;
|
|
1171
1156
|
const res = await chrome.tabs.sendMessage(tab.id, {
|
|
1172
1157
|
type: "CHAT_LOOP_TURN_RESUME_V1", page: owner.page,
|
|
1173
|
-
userKey:
|
|
1158
|
+
userKey:freshUser?proof.userKey:owner.newUserKey,
|
|
1159
|
+
assistantKey: owner.assistantKey || null,
|
|
1174
1160
|
startedAt: owner.startedAt
|
|
1175
1161
|
}).catch(() => null);
|
|
1176
1162
|
if (res?.status !== "RESUMED" && res?.status !== "ALREADY_MONITORING")
|
|
@@ -1179,54 +1165,6 @@ async function reconnectOpenChats() {
|
|
|
1179
1165
|
} catch (error) {console.warn("Chat Loop observer reconnect unavailable:", error?.message);}
|
|
1180
1166
|
}
|
|
1181
1167
|
}
|
|
1182
|
-
async function releaseWallClockHold(run) {
|
|
1183
|
-
const liveRun = await readRun();
|
|
1184
|
-
if (liveRun?.phase !== "WALL_CLOCK_HOLD" || liveRun.tabId !== run?.tabId
|
|
1185
|
-
|| liveRun.wallHoldAt !== run?.wallHoldAt
|
|
1186
|
-
|| liveRun.userKey !== run?.userKey) return {status: "IGNORED", code: "HOLD_ALREADY_CHANGED"};
|
|
1187
|
-
if (run?.phase !== "WALL_CLOCK_HOLD" || !([1, 2].includes(run.wallTestHours)
|
|
1188
|
-
|| run.wallTestMinutes === 10)
|
|
1189
|
-
|| !run.timedTest || !Number.isSafeInteger(run.wallReleaseAt)
|
|
1190
|
-
|| Date.now() < run.wallReleaseAt) return {status: "NOT_DUE"};
|
|
1191
|
-
const owned = (await chrome.storage.local.get("chat-loop.acceptance.owned.v1"))[
|
|
1192
|
-
"chat-loop.acceptance.owned.v1"];
|
|
1193
|
-
if (!Array.isArray(owned) || !owned.some(t => t.id === run.tabId))
|
|
1194
|
-
return {status: "DENIED", code: "NOT_TEST_OWNED"};
|
|
1195
|
-
const tab = await chrome.tabs.get(run.tabId).catch(() => null);
|
|
1196
|
-
if (!tab || pathOf(tab.url) !== run.page) {
|
|
1197
|
-
await saveRun({...run, phase: "BLOCKED", reason: "WALL_CHAT_CHANGED"});
|
|
1198
|
-
return {status: "BLOCKED", code: "WALL_CHAT_CHANGED"};
|
|
1199
|
-
}
|
|
1200
|
-
const verify = async () => {
|
|
1201
|
-
const p = await chrome.tabs.sendMessage(run.tabId,
|
|
1202
|
-
{type: "CHAT_LOOP_TURN_VERIFY_V1"}).catch(() => null);
|
|
1203
|
-
return p?.contract === "chat-loop.turn-observer.v1" && p.status === "READY"
|
|
1204
|
-
&& p.page === run.page && p.userKey === run.userKey
|
|
1205
|
-
&& p.assistantKey === run.assistantKey
|
|
1206
|
-
&& globalThis.ChatLoopCoreV1.parseStatus(p.replyText) === "CONTINUE";
|
|
1207
|
-
};
|
|
1208
|
-
if (!await verify()) return {status: "UNVERIFIED", code: "WALL_TURN_NOT_STABLE"};
|
|
1209
|
-
await new Promise(resolve => setTimeout(resolve, 2300));
|
|
1210
|
-
if (!await verify()) return {status: "UNVERIFIED", code: "WALL_TURN_CHANGED"};
|
|
1211
|
-
const latest = await readRun();
|
|
1212
|
-
if (latest?.phase !== "WALL_CLOCK_HOLD" || latest.tabId !== run.tabId
|
|
1213
|
-
|| latest.userKey !== run.userKey || latest.wallHoldAt !== run.wallHoldAt)
|
|
1214
|
-
return {status: "IGNORED", code: "HOLD_CHANGED_DURING_VERIFICATION"};
|
|
1215
|
-
const token = crypto.randomUUID();
|
|
1216
|
-
const next = {...run, phase: "RESERVED", action: "CONTINUE", token,
|
|
1217
|
-
wallReleasedAt: Date.now(), reason: ""};
|
|
1218
|
-
await saveRun(next); // reserve once, then Action page exclusively sends
|
|
1219
|
-
try {
|
|
1220
|
-
const action = await createBoundedAction({
|
|
1221
|
-
url: chrome.runtime.getURL("continue.html") + "?tabId=" + run.tabId
|
|
1222
|
-
+ "&token=" + encodeURIComponent(token), active: false, windowId: tab.windowId
|
|
1223
|
-
});
|
|
1224
|
-
return {status: "QUEUED", actionTabId: action.id};
|
|
1225
|
-
} catch {
|
|
1226
|
-
await saveRun({...next, phase: "BLOCKED", reason: "WALL_ACTION_CREATE_FAILED"});
|
|
1227
|
-
return {status: "BLOCKED", code: "WALL_ACTION_CREATE_FAILED"};
|
|
1228
|
-
}
|
|
1229
|
-
}
|
|
1230
1168
|
// MV3 background service workers can suspend, and hidden-page setInterval
|
|
1231
1169
|
// may be throttled. An alarm asks the Observer to sample, never acts directly.
|
|
1232
1170
|
async function ensureAlarm() {
|
|
@@ -1243,14 +1181,6 @@ async function watchActiveTurn() {
|
|
|
1243
1181
|
await serial(async()=>{await expireStaleModelIntent();await prepareHandoffIfDue();});
|
|
1244
1182
|
const run = await readRun();
|
|
1245
1183
|
// While an Action is pending, never dispatch competing operations.
|
|
1246
|
-
if (run?.phase === "WALL_CLOCK_HOLD") {
|
|
1247
|
-
void serial(() => releaseWallClockHold(run));
|
|
1248
|
-
return;
|
|
1249
|
-
}
|
|
1250
|
-
if (run?.phase === "WAITING_INTERVAL") {
|
|
1251
|
-
void serial(releaseCountInterval);
|
|
1252
|
-
return;
|
|
1253
|
-
}
|
|
1254
1184
|
if (run && ["RESERVED", "PENDING"].includes(run.phase)) return;
|
|
1255
1185
|
const tabs = run?.phase === "WAITING_REPLY"
|
|
1256
1186
|
? [await chrome.tabs.get(run.tabId).catch(() => null)]
|
|
@@ -1263,17 +1193,31 @@ async function watchActiveTurn() {
|
|
|
1263
1193
|
// A reloaded Observer may have mistaken the in-flight user Turn for
|
|
1264
1194
|
// historical baseline. Its IDLE state is not proof of completion.
|
|
1265
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;
|
|
1266
1201
|
if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
|
|
1267
|
-
&& proof?.page === run.page
|
|
1202
|
+
&& proof?.page === run.page
|
|
1203
|
+
&& (proof.userKey === run.newUserKey || freshHuman)
|
|
1268
1204
|
&& (proof.status === "IDLE"
|
|
1269
1205
|
|| proof.status === "UNKNOWN"
|
|
1270
1206
|
&& ["ATTACHING_CHAT", "WAITING_CHAT_HYDRATION"].includes(proof.reason))) {
|
|
1271
1207
|
await chrome.tabs.sendMessage(tab.id, {
|
|
1272
1208
|
type: "CHAT_LOOP_TURN_RESUME_V1", page: run.page,
|
|
1273
|
-
userKey:
|
|
1209
|
+
userKey: freshHuman?proof.userKey:run.newUserKey,
|
|
1210
|
+
assistantKey: run.assistantKey || null,
|
|
1274
1211
|
startedAt: run.startedAt
|
|
1275
1212
|
}).catch(() => null);
|
|
1276
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
|
+
}
|
|
1277
1221
|
// Alarm is still read-only. It may reconcile a verified page failure if
|
|
1278
1222
|
// the observer's original notification was lost while Worker slept.
|
|
1279
1223
|
if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
|
|
@@ -1289,8 +1233,7 @@ async function watchActiveTurn() {
|
|
|
1289
1233
|
chrome.alarms?.onAlarm?.addListener(alarm => {
|
|
1290
1234
|
if (alarm?.name === ALARM_NAME) void watchActiveTurn();
|
|
1291
1235
|
if (alarm?.name === DEADLINE_ALARM_NAME)
|
|
1292
|
-
void serial(
|
|
1293
|
-
if (alarm?.name === COUNT_ALARM_NAME) void serial(releaseCountInterval);
|
|
1236
|
+
void serial(prepareHandoffIfDue);
|
|
1294
1237
|
});
|
|
1295
1238
|
chrome.runtime.onInstalled?.addListener(() => {
|
|
1296
1239
|
void ensureAlarm();
|
|
@@ -1342,10 +1285,10 @@ async function onExtensionCliTarget(message,sender) {
|
|
|
1342
1285
|
return {status:"DENIED",code:"INVALID_EXTENSION_ACTION_SOURCE"};
|
|
1343
1286
|
if(message.action==="reload")return {status:"OK"};
|
|
1344
1287
|
const run=await readRun();
|
|
1345
|
-
// Read-only Eye may inspect the last confirmed
|
|
1288
|
+
// Read-only Eye may inspect the last confirmed terminal Owner while the same
|
|
1346
1289
|
// Chat URL and exact tab still match. This does not reactivate the Loop,
|
|
1347
1290
|
// grant Continue/Handoff permission or select another Chat tab.
|
|
1348
|
-
const finishedOwned = run?.phase
|
|
1291
|
+
const finishedOwned = ["DONE","BLOCKED"].includes(run?.phase)
|
|
1349
1292
|
&& /^user:[^\s]{8,}$/.test(run.userKey || "")
|
|
1350
1293
|
&& /^assistant:[^\s]{8,}$/.test(run.assistantKey || "");
|
|
1351
1294
|
if(!(run?.phase === "WAITING_REPLY" || finishedOwned) || !Number.isInteger(run.tabId)
|
|
@@ -1356,34 +1299,41 @@ async function onExtensionCliTarget(message,sender) {
|
|
|
1356
1299
|
return {status:"DENIED",code:"OWNER_CHANGED"};
|
|
1357
1300
|
return {status:"OK",tabId:run.tabId,page:run.page};
|
|
1358
1301
|
}
|
|
1302
|
+
// One explicit router for authenticated, serialized state changes.
|
|
1303
|
+
// The registered handler still verifies source, token, Owner and Turn identity.
|
|
1304
|
+
const SERIAL_ROUTES=new Map([
|
|
1305
|
+
['CHAT_LOOP_TURN_FINISHED_V1',onTurnFinished],
|
|
1306
|
+
['CHAT_LOOP_TURN_BLOCKED_V1',onTurnBlocked],
|
|
1307
|
+
['CHAT_LOOP_ACTION_TAKE_V1',onTake],
|
|
1308
|
+
['CHAT_LOOP_ACTION_RESULT_V1',onResult],
|
|
1309
|
+
['CHAT_LOOP_ACTION_MANUAL_PREPARE_V1',onManualPrepare],
|
|
1310
|
+
['CHAT_LOOP_MODEL_INTENT_V1',onModelIntent],
|
|
1311
|
+
['CHAT_LOOP_MODEL_INTENT_STATUS_V1',onModelIntentStatus],
|
|
1312
|
+
['CHAT_LOOP_SESSION_START_PREPARE_V1',sessionStartPrepare],
|
|
1313
|
+
['CHAT_LOOP_SESSION_START_TAKE_V1',sessionStartTake],
|
|
1314
|
+
['CHAT_LOOP_SESSION_START_RESULT_V1',sessionStartResult],
|
|
1315
|
+
['CHAT_LOOP_SESSION_STATUS_V1',sessionStatus],
|
|
1316
|
+
['CHAT_LOOP_RESOURCE_CHAT_V1',resourceChatGate]
|
|
1317
|
+
|
|
1318
|
+
]);
|
|
1359
1319
|
chrome.runtime.onMessage.addListener((message, sender, reply) => {
|
|
1360
|
-
const type
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
? onModelIntent(message, sender) : type === "CHAT_LOOP_MODEL_INTENT_STATUS_V1"
|
|
1378
|
-
? onModelIntentStatus(message,sender) : type === "CHAT_LOOP_TURN_FINISHED_V1"
|
|
1379
|
-
? onTurnFinished(message, sender) : type === "CHAT_LOOP_TURN_BLOCKED_V1"
|
|
1380
|
-
? onTurnBlocked(message, sender) : type === "CHAT_LOOP_ACTION_TAKE_V1"
|
|
1381
|
-
? onTake(message, sender) : type === "CHAT_LOOP_ACTION_MANUAL_PREPARE_V1"
|
|
1382
|
-
? onManualPrepare(message, sender) : type === "CHAT_LOOP_ACTION_TEST_PREPARE_V1"
|
|
1383
|
-
? onTestPrepare(message, sender)
|
|
1384
|
-
: type === "CHAT_LOOP_ACCEPTANCE_CLOCK_ADVANCE_V1"
|
|
1385
|
-
? onAcceptanceClockAdvance(message, sender) : onResult(message, sender));
|
|
1386
|
-
void work.then(reply, error => reply({status: "BLOCKED", code: error.message || "SCHEDULER_ERROR"}));
|
|
1320
|
+
const type=message?.type;
|
|
1321
|
+
const handle=SERIAL_ROUTES.get(type);
|
|
1322
|
+
if(handle){
|
|
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'}));
|
|
1387
1337
|
return true;
|
|
1388
1338
|
}
|
|
1389
1339
|
if (type === 'CHAT_LOOP_POPUP_CLEAN_OPEN_V1') {
|