webhelm 1.0.52 → 1.0.54
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 +1 -1
- package/package.json +1 -1
- package/runtime/extension/control-rpc.mjs +6 -1
- package/runtime/extension/manifest.json +1 -1
- package/runtime/extension/popup-data.mjs +13 -6
- package/runtime/extension/popup.mjs +14 -4
- package/runtime/extension/service-worker.mjs +1 -1
- package/runtime/extension/site-registry.mjs +25 -12
- package/runtime/network-observer.mjs +55 -0
- package/runtime/node-daemon.mjs +28 -6
- package/runtime/site-keepalive.mjs +25 -11
- package/scripts/chatgpt-three-mvps.mjs +4 -2
package/README.md
CHANGED
|
@@ -133,7 +133,7 @@ site-specific evidence; never infer login solely from HTTP success or page
|
|
|
133
133
|
load. WebHelm schedules only opted-in platforms, using a temporary browser
|
|
134
134
|
Session and an idle pool slot. On failure, the UI displays **Check failed**;
|
|
135
135
|
non-opted-in sites display **No heartbeat action** and can still be opened for
|
|
136
|
-
manual login.
|
|
136
|
+
manual login. Only confirmed login schedules another heartbeat. Every other result pauses checks immediately; failure reasons are diagnostic only. Pause state survives restarts; after signing in, click the resume icon in Keep Alive Sites to request a fresh check. Failed releases retry cleanup of the original Session without allocating a new Tab. Neither
|
|
137
137
|
heartbeat nor browser persistence guarantees that the service will extend its
|
|
138
138
|
login lifetime. No automatic credential input or challenge bypass occurs.
|
|
139
139
|
|
package/package.json
CHANGED
|
@@ -119,9 +119,14 @@ export function createControlRpc({control, manager, design=null, summarizeWorksp
|
|
|
119
119
|
const opened = await chromeApi.tabs.create({url,active:true});
|
|
120
120
|
return {ok:true,tabId:opened.id,opened:true};
|
|
121
121
|
}
|
|
122
|
+
case "workspace.control.site.resume": {
|
|
123
|
+
const site = (await listKeptSites(chromeApi)).find(s => s.id === args.siteId);
|
|
124
|
+
if (!site) throw Error('Keep Alive site is no longer registered');
|
|
125
|
+
return setKeptSite(chromeApi,site.url,true);
|
|
126
|
+
}
|
|
122
127
|
// Daemon-only control RPCs, unavailable to extension pages.
|
|
123
128
|
case "workspace.control.site.list":
|
|
124
|
-
return
|
|
129
|
+
return sitesWithStatus(chromeApi);
|
|
125
130
|
case "workspace.control.site.report":
|
|
126
131
|
return reportKeptSite(chromeApi,args);
|
|
127
132
|
case "workspace.control.requestStop":
|
|
@@ -17,7 +17,12 @@ function validSite(site) {
|
|
|
17
17
|
export function mergeKeptSites(persisted, statusById, reported) {
|
|
18
18
|
const sites = new Map();
|
|
19
19
|
for (const site of Array.isArray(persisted) ? persisted : []) {
|
|
20
|
-
if (validSite(site))
|
|
20
|
+
if (validSite(site)) {
|
|
21
|
+
const state=statusById?.[site.id];
|
|
22
|
+
const valid=state && (state.revision===undefined || state.revision===site.revision);
|
|
23
|
+
const failed=valid&&['failed','login_required','unknown','error','release_error'].includes(state.status);
|
|
24
|
+
sites.set(site.id, {...site,status:failed?'failed':valid?state.status:'pending',...(failed||valid&&state.paused?{paused:true}:{}),...(failed?{reason:state.reason||state.status}:{})});
|
|
25
|
+
}
|
|
21
26
|
}
|
|
22
27
|
for (const site of Array.isArray(reported) ? reported : []) {
|
|
23
28
|
if (validSite(site)) sites.set(site.id, {...sites.get(site.id), ...site});
|
|
@@ -31,7 +36,7 @@ export async function readKeptSites(chromeApi, reported) {
|
|
|
31
36
|
const stored=await chromeApi.storage.local.get(SITE_STORAGE_KEY);
|
|
32
37
|
persisted=stored[SITE_STORAGE_KEY];
|
|
33
38
|
const latest=await chromeApi.storage.session.get(SITE_STATUS_KEY);
|
|
34
|
-
statuses=latest[SITE_STATUS_KEY] || {};
|
|
39
|
+
statuses={...(latest[SITE_STATUS_KEY] || {}),...((await chromeApi.storage.local.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {})};
|
|
35
40
|
} catch { /* Keep any site entries returned by the current service worker. */ }
|
|
36
41
|
return mergeKeptSites(persisted,statuses,reported);
|
|
37
42
|
}
|
|
@@ -47,10 +52,12 @@ export async function setStoredSite(chromeApi, url, enabled) {
|
|
|
47
52
|
enabled:true,addedAt:Date.now(),revision:crypto.randomUUID()});
|
|
48
53
|
await chromeApi.storage.local.set({[SITE_STORAGE_KEY]: next.sort((a,b)=>a.id.localeCompare(b.id))});
|
|
49
54
|
if (!enabled) {
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
55
|
+
for (const storage of [chromeApi.storage.local,chromeApi.storage.session]) {
|
|
56
|
+
const storedStates=await storage.get(SITE_STATUS_KEY);
|
|
57
|
+
const states=storedStates[SITE_STATUS_KEY] || {};
|
|
58
|
+
delete states[origin];
|
|
59
|
+
await storage.set({[SITE_STATUS_KEY]:states});
|
|
60
|
+
}
|
|
54
61
|
}
|
|
55
62
|
return {id:origin,enabled:Boolean(enabled)};
|
|
56
63
|
}
|
|
@@ -95,12 +95,12 @@ function renderKeptSites(sites, busy, connected) {
|
|
|
95
95
|
target.textContent='Enable Keep Alive from a WebHelm Session.';
|
|
96
96
|
return;
|
|
97
97
|
}
|
|
98
|
-
const labels={alive:'Logged in',login_required:'Login required',unknown:'Login not confirmed',
|
|
99
|
-
error:'Heartbeat failed',unsupported:'No heartbeat action',pending:'Checking login'};
|
|
98
|
+
const labels={alive:'Logged in',failed:'Heartbeat failed',login_required:'Login required',unknown:'Login not confirmed',
|
|
99
|
+
error:'Heartbeat failed',release_error:'Tab release failed',unsupported:'No heartbeat action',pending:'Checking login'};
|
|
100
100
|
for (const site of sites) {
|
|
101
101
|
const row=document.createElement('div'); row.className='keepalive-row';
|
|
102
102
|
const loggedIn=site.status==='alive';
|
|
103
|
-
const statusText=labels[site.status] || labels.pending;
|
|
103
|
+
const statusText=(labels[site.status] || labels.pending)+(site.paused?' · Paused':'')+(site.reason&&site.reason!==site.status?' · '+(labels[site.reason]||site.reason):'');
|
|
104
104
|
const status=document.createElement('span'); status.className='keepalive-status';
|
|
105
105
|
status.dataset.status=loggedIn?'alive':'inactive';
|
|
106
106
|
status.title=statusText;
|
|
@@ -122,7 +122,17 @@ function renderKeptSites(sites, busy, connected) {
|
|
|
122
122
|
},'keepalive-remove');
|
|
123
123
|
remove.title=`Remove ${siteLabel(site.url)} from Keep Alive`;
|
|
124
124
|
remove.setAttribute('aria-label',remove.title);
|
|
125
|
-
row.append(status,name
|
|
125
|
+
row.append(status,name);
|
|
126
|
+
if (site.paused) {
|
|
127
|
+
const resume=actionButton('↻',!connected,async()=>{
|
|
128
|
+
try {await rpc('workspace.control.site.resume',{siteId:site.id});lastSiteSignature='';refresh();}
|
|
129
|
+
catch(error){el('message').textContent=error.message;}
|
|
130
|
+
},'keepalive-remove');
|
|
131
|
+
resume.title=resume.getAttribute('aria-label') || 'Resume heartbeat after signing in';
|
|
132
|
+
resume.setAttribute('aria-label',resume.title);
|
|
133
|
+
row.append(resume);
|
|
134
|
+
}
|
|
135
|
+
row.append(remove);
|
|
126
136
|
target.append(row);
|
|
127
137
|
}
|
|
128
138
|
}
|
|
@@ -108,7 +108,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
|
108
108
|
!["workspace.control.requestStop", "workspace.control.queueCancel", "workspace.control.status",
|
|
109
109
|
"workspace.control.activateTab", "workspace.control.openQueue",
|
|
110
110
|
"workspace.control.site.toggle", "workspace.control.site.open",
|
|
111
|
-
"workspace.control.site.remove", "workspace.control.design.toggle"].includes(request.method))) {
|
|
111
|
+
"workspace.control.site.remove", "workspace.control.site.resume", "workspace.control.design.toggle"].includes(request.method))) {
|
|
112
112
|
sendResponse({ok:false,error:{message:"WebHelm control actions require the toolbar popup"}});
|
|
113
113
|
return false;
|
|
114
114
|
}
|
|
@@ -34,28 +34,41 @@ export async function setKeptSite(chromeApi, url, enabled) {
|
|
|
34
34
|
sites.sort((a,b) => a.id.localeCompare(b.id));
|
|
35
35
|
await chromeApi.storage.local.set({[SITE_STORAGE_KEY]: sites});
|
|
36
36
|
if (!enabled) {
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
for (const storage of [chromeApi.storage.local,chromeApi.storage.session]) {
|
|
38
|
+
const states = (await storage.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {};
|
|
39
|
+
delete states[id];
|
|
40
|
+
await storage.set({[SITE_STATUS_KEY]: states});
|
|
41
|
+
}
|
|
40
42
|
}
|
|
41
43
|
return {id, enabled:Boolean(enabled), sites};
|
|
42
44
|
}
|
|
43
45
|
|
|
44
46
|
export async function sitesWithStatus(chromeApi) {
|
|
45
|
-
const [sites, stored] = await Promise.all([listKeptSites(chromeApi),
|
|
46
|
-
|
|
47
|
-
return sites.map(site =>
|
|
48
|
-
|
|
49
|
-
|
|
47
|
+
const [sites, stored, legacy] = await Promise.all([listKeptSites(chromeApi),
|
|
48
|
+
chromeApi.storage.local.get(SITE_STATUS_KEY),chromeApi.storage.session.get(SITE_STATUS_KEY)]);
|
|
49
|
+
return sites.map(site => {
|
|
50
|
+
const durable=stored[SITE_STATUS_KEY]?.[site.id];
|
|
51
|
+
const old=legacy[SITE_STATUS_KEY]?.[site.id];
|
|
52
|
+
const state=durable?.revision===site.revision ? durable :
|
|
53
|
+
(!durable && old && (!old.checkedAt || old.checkedAt>=site.addedAt) ? old : {});
|
|
54
|
+
const failed=['failed','login_required','unknown','error','release_error'].includes(state.status);
|
|
55
|
+
return {...site,status:failed?'failed':state.status || 'pending',
|
|
56
|
+
paused:failed || state.paused===true,
|
|
57
|
+
...(failed ? {reason:state.reason || state.status} : {}),
|
|
58
|
+
...(state.checkedAt ? {checkedAt:state.checkedAt} : {}),
|
|
59
|
+
...(state.platform ? {platform:state.platform} : {})};
|
|
60
|
+
});
|
|
50
61
|
}
|
|
51
62
|
|
|
52
63
|
export async function reportKeptSite(chromeApi, report) {
|
|
53
64
|
const registered = (await listKeptSites(chromeApi)).some(site => site.id === report?.id && site.revision === report?.revision);
|
|
54
|
-
if (!registered || !['alive','login_required','unknown','error','unsupported'].includes(report?.status))
|
|
65
|
+
if (!registered || !['alive','login_required','unknown','error','unsupported','release_error','failed'].includes(report?.status))
|
|
55
66
|
return {ignored:true};
|
|
56
|
-
const states = (await chromeApi.storage.
|
|
57
|
-
states[report.id] = {status:report.status,checkedAt:Date.now(),
|
|
67
|
+
const states = (await chromeApi.storage.local.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {};
|
|
68
|
+
states[report.id] = {revision:report.revision,status:report.status,checkedAt:Date.now(),
|
|
69
|
+
paused:report.paused===true,
|
|
70
|
+
...(['login_required','unknown','error','release_error'].includes(report.reason)?{reason:report.reason}:{}),
|
|
58
71
|
...(typeof report.platform === 'string' ? {platform:report.platform} : {})};
|
|
59
|
-
await chromeApi.storage.
|
|
72
|
+
await chromeApi.storage.local.set({[SITE_STATUS_KEY]:states});
|
|
60
73
|
return {ok:true};
|
|
61
74
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Generic, bounded, per-CDP-session response observer. No platform-specific
|
|
2
|
+
// endpoints or identifiers here. Never persist request/response bodies.
|
|
3
|
+
export function observeNetwork(browser, sessionId, {url, method='POST'}={}) {
|
|
4
|
+
if(typeof url!=='string'||!/^https:\/\//.test(url)||typeof method!=='string')
|
|
5
|
+
throw new TypeError('observe_network requires an exact HTTPS URL and HTTP method');
|
|
6
|
+
const maxBytes=256*1024, records=new Map(), removers=[];
|
|
7
|
+
let armed=false,closed=false,overflow=false;
|
|
8
|
+
const on=(name,fn)=>removers.push(browser.on(name,(p,owner)=>{
|
|
9
|
+
if(!closed&&armed&&owner===sessionId){try{fn(p)}catch{}}
|
|
10
|
+
}));
|
|
11
|
+
const append=(rec,data,initial=false)=>{
|
|
12
|
+
if(closed||typeof data!=='string'||!data)return;
|
|
13
|
+
const bytes=Buffer.from(data,'base64');
|
|
14
|
+
if(rec.bytes+bytes.length>maxBytes){rec.truncated=true;return}
|
|
15
|
+
rec.bytes+=bytes.length;
|
|
16
|
+
if(initial)rec.chunks.unshift(bytes);else rec.chunks.push(bytes);
|
|
17
|
+
};
|
|
18
|
+
on('Network.requestWillBeSent',p=>{
|
|
19
|
+
if(records.has(p.requestId)){records.get(p.requestId).ambiguous=true;return}
|
|
20
|
+
if(p.request?.url!==url||p.request?.method!==method)return;
|
|
21
|
+
if(records.size>=4){overflow=true;return}
|
|
22
|
+
const rec={requestId:p.requestId,postData:typeof p.request.postData==='string'&&p.request.postData.length<=32768?p.request.postData:null,
|
|
23
|
+
status:null,mime:null,ambiguous:false,truncated:false,bytes:0,chunks:[],body:null};
|
|
24
|
+
records.set(p.requestId,rec);
|
|
25
|
+
if(rec.postData===null&&p.request.hasPostData)void browser.send('Network.getRequestPostData',{requestId:p.requestId},sessionId).then(r=>{
|
|
26
|
+
if(!closed&&typeof r.postData==='string'&&r.postData.length<=32768)rec.postData=r.postData;
|
|
27
|
+
}).catch(()=>{});
|
|
28
|
+
});
|
|
29
|
+
on('Network.responseReceived',p=>{
|
|
30
|
+
const rec=records.get(p.requestId);if(!rec)return;
|
|
31
|
+
rec.status=p.response?.status;rec.mime=p.response?.mimeType;
|
|
32
|
+
if(p.response?.url!==url){rec.ambiguous=true;return}
|
|
33
|
+
if(rec.status<200||rec.status>=300||!/(?:event-stream|ndjson)/i.test(rec.mime||''))return;
|
|
34
|
+
void browser.send('Network.streamResourceContent',{requestId:p.requestId},sessionId).then(r=>append(rec,r.bufferedData,true)).catch(()=>{});
|
|
35
|
+
});
|
|
36
|
+
on('Network.dataReceived',p=>{const rec=records.get(p.requestId);if(rec)append(rec,p.data)});
|
|
37
|
+
on('Network.loadingFinished',p=>{
|
|
38
|
+
const rec=records.get(p.requestId);
|
|
39
|
+
if(!rec||rec.status<200||rec.status>=300||!/(?:event-stream|ndjson)/i.test(rec.mime||''))return;
|
|
40
|
+
void browser.send('Network.getResponseBody',{requestId:p.requestId},sessionId).then(r=>{
|
|
41
|
+
if(closed||typeof r.body!=='string')return;
|
|
42
|
+
const bytes=Buffer.from(r.body,r.base64Encoded?'base64':'utf8');
|
|
43
|
+
if(bytes.length<=maxBytes)rec.body=bytes.toString('utf8');
|
|
44
|
+
}).catch(()=>{});
|
|
45
|
+
});
|
|
46
|
+
return {
|
|
47
|
+
arm(){if(closed)throw Error('network observer closed');if(armed)throw Error('network observer already armed');armed=true},
|
|
48
|
+
snapshot(){
|
|
49
|
+
if(closed)return {overflow:true,requests:[]};
|
|
50
|
+
return {overflow,requests:[...records.values()].map(r=>({request_id:r.requestId,post_data:r.postData,status:r.status,mime:r.mime,
|
|
51
|
+
ambiguous:r.ambiguous,truncated:r.truncated,body:r.body??Buffer.concat(r.chunks).toString('utf8')}))};
|
|
52
|
+
},
|
|
53
|
+
close(){if(closed)return;closed=true;for(const off of removers)off();records.clear()}
|
|
54
|
+
};
|
|
55
|
+
}
|
package/runtime/node-daemon.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import vm from 'node:vm';
|
|
|
7
7
|
import crypto from 'node:crypto';
|
|
8
8
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
9
9
|
import { invokePlatformAction } from './platforms.mjs';
|
|
10
|
+
import { observeNetwork } from './network-observer.mjs';
|
|
10
11
|
import {createSiteKeepaliveScheduler} from './site-keepalive.mjs';
|
|
11
12
|
import { PlatformQueueRegistry } from './queue-registry.mjs';
|
|
12
13
|
import { idleUrlFromIdentity, sameIdleUrl, staleSession, withinDeadline, SessionDeadlineError, endedDesignSessions } from './session-lifecycle.mjs';
|
|
@@ -206,7 +207,7 @@ async function attach(s,targetId,b=null){b ||= await connectBrowser();const {ses
|
|
|
206
207
|
function sidFor(s,targetId=s.targetId){const sid=s.attachments.get(targetId);if(!sid)throw new Error(`target ${targetId} is not attached to this session`);return sid}
|
|
207
208
|
async function evaluate(s,expression,targetId=s.targetId,awaitPromise=true){if(s.poisoned || s.closing)throw Error('Session execution expired or closing');if(!s.targets.has(targetId))throw Error('cannot evaluate a target outside the active WebHelm session');const b=await connectBrowser();if(s.poisoned || s.closing)throw Error('Session execution expired or closing');const r=await b.send('Runtime.evaluate',{expression,returnByValue:true,awaitPromise,userGesture:true},sidFor(s,targetId));if(r.exceptionDetails)throw new Error(r.exceptionDetails.exception?.description||r.exceptionDetails.text);return r.result?.value}
|
|
208
209
|
async function cdp(s,method,params={},targetId=s.targetId){if(s.poisoned || s.closing)throw Error('Session execution expired or closing');if(method==='Target.createTarget')throw Error('Target.createTarget is disabled; use new_tab(url)');if(method==='Target.attachToTarget'||method==='Target.detachFromTarget')throw Error('direct target attachment changes are disabled in WebHelm sessions');if(['Target.closeTarget','Target.activateTarget'].includes(method)&&!s.targets.has(params.targetId))throw Error('cannot operate on a tab outside the active WebHelm session');return connectBrowser().then(browser=>{if(s.poisoned || s.closing)throw Error('Session execution expired or closing');if(method.startsWith('Target.')||method.startsWith('Browser.')||method.startsWith('ServiceWorker.'))return browser.send(method,params);return browser.send(method,params,sidFor(s,targetId));})}
|
|
209
|
-
function makeHelpers(s){
|
|
210
|
+
function makeHelpers(s, observers=null){
|
|
210
211
|
const h={
|
|
211
212
|
js:(expression,target_id)=>evaluate(s,expression,target_id||s.targetId),
|
|
212
213
|
cdp:(method,params={})=>cdp(s,method,params),
|
|
@@ -298,6 +299,18 @@ function makeHelpers(s){
|
|
|
298
299
|
if (!s.targets.has(tid)) throw Error('cannot activate a tab outside the active WebHelm session');
|
|
299
300
|
return cdp(s,'Target.activateTarget',{targetId:tid});
|
|
300
301
|
},
|
|
302
|
+
// Available only to Platform Actions; the runner always closes observers.
|
|
303
|
+
async observe_network(options){
|
|
304
|
+
if(!observers||observers.closed)throw Error('observe_network requires an active Platform Action');
|
|
305
|
+
const target=s.targetId, browser=await connectBrowser();
|
|
306
|
+
if(observers.closed||s.closing||s.poisoned||target!==s.targetId)throw Error('network observer target unavailable');
|
|
307
|
+
const attachment=sidFor(s,target);
|
|
308
|
+
await browser.send('Network.enable',{maxTotalBufferSize:16000000,maxResourceBufferSize:2000000,maxPostDataSize:32768},attachment);
|
|
309
|
+
if(observers.closed||s.closing||s.poisoned||target!==s.targetId)throw Error('network observer target unavailable');
|
|
310
|
+
const observer=observeNetwork(browser,attachment,options);
|
|
311
|
+
observers.items.add(observer);
|
|
312
|
+
return observer;
|
|
313
|
+
},
|
|
301
314
|
events(){const e=s.events.splice(0);return e},
|
|
302
315
|
async current_url(){return (await h.page_info()).url},
|
|
303
316
|
async title(){return (await h.page_info()).title}
|
|
@@ -306,7 +319,7 @@ function makeHelpers(s){
|
|
|
306
319
|
// A rejected async VM execution does not cancel browser operations it
|
|
307
320
|
// already started. Keep their tab ownership until those operations settle.
|
|
308
321
|
const effectHelpers=new Set(['js','cdp','goto_url','new_tab','close_tab','fill_input',
|
|
309
|
-
'click','capture_screenshot','snapshot','type_text','upload_file','switch_tab','activate_tab']);
|
|
322
|
+
'click','capture_screenshot','snapshot','type_text','upload_file','switch_tab','activate_tab','observe_network']);
|
|
310
323
|
for(const [name,helper] of Object.entries(h)){
|
|
311
324
|
if(typeof helper!=='function')continue;
|
|
312
325
|
h[name]=(...args)=>{
|
|
@@ -816,7 +829,8 @@ async function runPlatform(req) {
|
|
|
816
829
|
result=await session.mutex.run(async()=>{
|
|
817
830
|
if(session.poisoned||session.closing)throw Error('Session expired while waiting for platform action');
|
|
818
831
|
const logs=[];
|
|
819
|
-
const
|
|
832
|
+
const observers={closed:false,items:new Set()};
|
|
833
|
+
const helpers=makeHelpers(session,observers);
|
|
820
834
|
try {
|
|
821
835
|
const actionTimeoutMs=Math.max(50,Math.min(300000,Number(process.env.WEBHELM_PLATFORM_TIMEOUT_MS)||180000));
|
|
822
836
|
const value=await withinDeadline(Promise.resolve().then(()=>invokePlatformAction(platform,action,{
|
|
@@ -830,11 +844,11 @@ async function runPlatform(req) {
|
|
|
830
844
|
} catch(error) {
|
|
831
845
|
if(error instanceof SessionDeadlineError)session.poisoned=true;
|
|
832
846
|
return {ok:false,stdout:logs.join('\n').slice(-40000),stderr:'',error:`${error.name}: ${error.message}`};
|
|
833
|
-
}
|
|
847
|
+
} finally { observers.closed=true;for(const observer of observers.items)observer.close(); observers.items.clear(); }
|
|
834
848
|
});
|
|
835
849
|
} finally {
|
|
836
850
|
session.inFlight--;session.last_used_at=Date.now();
|
|
837
|
-
cleanup=auto ? await stopSession(sid).catch(e=>({release_error:e.message})) : {caller_owned_session:true};
|
|
851
|
+
cleanup=auto ? await stopSession(sid).catch(e=>({session_id:sid,release_error:e.message})) : {caller_owned_session:true};
|
|
838
852
|
}
|
|
839
853
|
result.cleanup=cleanup;
|
|
840
854
|
// Action completion/receipt semantics belong to the Platform, not this runner.
|
|
@@ -855,10 +869,18 @@ const siteKeepalive = createSiteKeepaliveScheduler({
|
|
|
855
869
|
const capacity=await workspaceCapacity();
|
|
856
870
|
return Number.isInteger(capacity.available) && capacity.available > 0;
|
|
857
871
|
},
|
|
872
|
+
recover:async sid => {
|
|
873
|
+
const session=sessions.get(sid);
|
|
874
|
+
if (!session) return true;
|
|
875
|
+
if (session.closing) return false;
|
|
876
|
+
await stopSession(sid);
|
|
877
|
+
return !sessions.has(sid);
|
|
878
|
+
},
|
|
858
879
|
run:async plan => {
|
|
859
880
|
const outcome=await runPlatform({platform:plan.platform,action:plan.action,
|
|
860
881
|
url:plan.url,auto_session:true,config:{}});
|
|
861
|
-
if (
|
|
882
|
+
if (outcome.result.cleanup?.release_error) return {status:'release_error',releaseSessionId:outcome.result.cleanup.session_id};
|
|
883
|
+
if (!outcome.result.ok) throw Error('Platform heartbeat action failed');
|
|
862
884
|
return outcome.result.value;
|
|
863
885
|
},
|
|
864
886
|
});
|
|
@@ -37,40 +37,54 @@ export function resolveSiteHeartbeat(site, names=listPlatforms, manifestFor=plat
|
|
|
37
37
|
return null;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
// Only positive login evidence permits another heartbeat. All failures pause
|
|
41
|
+
// until a new registration revision is explicitly requested.
|
|
40
42
|
export function createSiteKeepaliveScheduler({listSites, report, run, resolve=resolveSiteHeartbeat,
|
|
41
|
-
now=Date.now, canRun=async()=>true}) {
|
|
43
|
+
now=Date.now, canRun=async()=>true, recover=async()=>true}) {
|
|
42
44
|
const next = new Map();
|
|
45
|
+
const cleanup = new Map();
|
|
43
46
|
let active = false;
|
|
44
47
|
return {
|
|
45
48
|
async tick() {
|
|
46
49
|
if (active) return {busy:true};
|
|
47
50
|
active=true;
|
|
48
51
|
try {
|
|
52
|
+
// Retry only the old Session's release, never the failed Action.
|
|
53
|
+
for (const [id, pending] of cleanup) {
|
|
54
|
+
if (now() < pending.at) continue;
|
|
55
|
+
pending.at=now()+60000;
|
|
56
|
+
try { if (await recover(pending.sessionId)) cleanup.delete(id); } catch {}
|
|
57
|
+
}
|
|
49
58
|
const sites=await listSites();
|
|
50
59
|
const known=new Set(sites.map(s=>s.id));
|
|
51
60
|
for (const id of next.keys()) if (!known.has(id)) next.delete(id);
|
|
52
61
|
for (const site of sites) {
|
|
53
|
-
|
|
54
|
-
|
|
62
|
+
if (cleanup.has(site.id)) continue;
|
|
63
|
+
const previous=next.get(site.id);
|
|
64
|
+
const current=previous?.revision === site.revision ? previous : null;
|
|
65
|
+
if (site.paused || current?.paused || (current && now() < current.at)) continue;
|
|
55
66
|
let plan;
|
|
56
67
|
try {plan = resolve(site);} catch {plan=null; }
|
|
57
68
|
if (!plan) {
|
|
58
|
-
next.set(site.id,{at:
|
|
69
|
+
next.set(site.id,{at:Infinity,revision:site.revision,paused:true});
|
|
59
70
|
await report({id:site.id,revision:site.revision,status:'unsupported'});
|
|
60
71
|
continue;
|
|
61
72
|
}
|
|
62
73
|
if (!await canRun()) return {deferred:true};
|
|
63
|
-
// Set deadline before running to prevent concurrent retries during
|
|
64
|
-
// slow site actions. No automatic replay of timed-out actions.
|
|
65
74
|
next.set(site.id,{at:now()+plan.intervalMs,revision:site.revision});
|
|
66
|
-
let
|
|
75
|
+
let reason='error', releaseSessionId;
|
|
67
76
|
try {
|
|
68
77
|
const result=await run({...plan,site});
|
|
69
|
-
|
|
78
|
+
releaseSessionId=result?.releaseSessionId;
|
|
79
|
+
reason=['alive','login_required','unknown','release_error'].includes(result?.status)?result.status:'unknown';
|
|
70
80
|
} catch { /* No secret URLs, cookies, or Action traces in the popup. */ }
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
81
|
+
const status=reason==='alive'?'alive':'failed';
|
|
82
|
+
const paused=status==='failed';
|
|
83
|
+
if (reason==='release_error' && releaseSessionId)
|
|
84
|
+
cleanup.set(site.id,{sessionId:releaseSessionId,at:now()+60000});
|
|
85
|
+
next.set(site.id,{at:paused?Infinity:now()+plan.intervalMs,revision:site.revision,paused});
|
|
86
|
+
await report({id:site.id,revision:site.revision,platform:plan.platform,status,reason,paused});
|
|
87
|
+
return {id:site.id,status};
|
|
74
88
|
}
|
|
75
89
|
return {idle:true};
|
|
76
90
|
} finally {active=false;}
|
|
@@ -170,11 +170,13 @@ try {
|
|
|
170
170
|
// A queue receipt can persist before its browser Session has fully returned to idle.
|
|
171
171
|
// Allow the daemon's awaited cleanup to finish without touching unrelated Sessions.
|
|
172
172
|
for(let i=0;i<45;i++) {
|
|
173
|
-
const remaining=(await sessions()).filter(x
|
|
173
|
+
const remaining=(await sessions()).filter(x=>x.workspace==='WebHelm'&&!existing.has(x.session_id));
|
|
174
174
|
if(!remaining.length) break;
|
|
175
175
|
await sleep(1000);
|
|
176
176
|
}
|
|
177
|
-
|
|
177
|
+
// Only the shared WebHelm workspace owns these test leases. Application
|
|
178
|
+
// workspaces (e.g. WeChat) may independently start during the gate.
|
|
179
|
+
const leftovers=(await sessions()).filter(x=>x.workspace==='WebHelm'&&!existing.has(x.session_id));
|
|
178
180
|
assert.equal(leftovers.length,0,'owned Sessions not cleaned: '+JSON.stringify(leftovers));
|
|
179
181
|
evidence.pass=true;
|
|
180
182
|
record('ALL_3_MVPS_PASS',{thread_url:evidence.thread_url,real_browser:true,
|