webhelm 1.0.27 → 1.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,6 +45,47 @@ For a real browser integration check on macOS, run `node test/e2e/extension-cont
45
45
 
46
46
  The Actions checkout is `~/.local/webhelm`, with site modules at `~/.local/webhelm/platforms`. Setup clones if absent, then reuses that checkout without discarding local modifications. Run `platform sync` for new commits. For a verified local Action fix, `platform publish --message "..."` tests, commits and pushes only the action changes to the separate repo.
47
47
 
48
+ ## Optional site Keep Alive (Extension)
49
+
50
+ Only a Session in the **WebHelm** Workspace can use the Extension's **Keep Alive** toggle on an HTTPS page to
51
+ register that website's **origin**. The website stays in the popup's Keep Alive
52
+ Sites list even after the original Session ends. Custom/other Workspace
53
+ Sessions have no Keep Alive toggle. A green dot and website name mean that
54
+ the Platform last confirmed login; gray means not confirmed or not logged in
55
+ (hover to see the exact status). Click a website to open/focus it in the
56
+ existing managed Chrome profile and sign in again. The × control
57
+ clears the registration. Credentials, cookies, URL query strings, and browser
58
+ Session IDs are never copied into the registry. Site registration does **not**
59
+ keep a WebHelm Session or Tab permanently leased.
60
+
61
+ A Platform only needs a periodic heartbeat if that specific website requires
62
+ one. Site Actions opt in **individually**, in their Actions checkout's
63
+ `manifest.yaml`, for example:
64
+
65
+ ```yaml
66
+ url_patterns:
67
+ - https://creator.example.com/*
68
+ actions:
69
+ heartbeat: actions/_heartbeat.mjs
70
+ keep_alive:
71
+ action: heartbeat
72
+ interval_minutes: 30
73
+ url: https://creator.example.com/
74
+ ```
75
+
76
+ The Platform's heartbeat Action runs with the existing `helpers` and must be
77
+ read-only. It returns `{status:'alive'|'login_required'|'unknown'}` after using
78
+ site-specific evidence; never infer login solely from HTTP success or page
79
+ load. WebHelm schedules only opted-in platforms, using a temporary browser
80
+ Session and an idle pool slot. On failure, the UI displays **Check failed**;
81
+ non-opted-in sites display **No heartbeat action** and can still be opened for
82
+ manual login. Failed/unknown checks retry no faster than five minutes. Neither
83
+ heartbeat nor browser persistence guarantees that the service will extend its
84
+ login lifetime. No automatic credential input or challenge bypass occurs.
85
+
86
+ The Platform Action implementation and its verification belong in
87
+ `lalalic/webhelm-actions`, not in this Runtime repository.
88
+
48
89
  ## Architecture and compatibility
49
90
 
50
91
  The Runtime stores its managed Chrome profile, persistent FIFO queue, and IPC socket under `~/.config/webhelm/`. Run `webhelm migrate` with the legacy daemon and Chrome stopped to migrate existing `~/.config/browser-workspace/` data without dropping logins or queued turns. The command leaves a compatibility symlink for legacy maintenance scripts. Session idle GC runs on Node before new Session allocation (5 minutes without operations or explicit heartbeat); no background sweep is started. A timed-out Session refuses subsequent exec, platform Actions and heartbeat, while already-issued browser effects retain tab ownership until settled. A stop that times out while queued cannot execute a late release, and a stop already physically releasing keeps its Session closing until the release finishes. Managed tabs are navigated back to their Extension idle URL instead of closing CDP targets; the Extension does not use `tab.lastAccessed` GC. An async Session execution has a finite deadline: if it expires, its helper capabilities are revoked and the poisoned Session is collected on the next Tab request (or immediately by an explicit stop). Session stop also has a bounded drain/release deadline and cannot leave a permanent closing flag. Client IPC requests have an independent absolute timeout and return an error if the daemon does not respond. These safeguards do not introduce periodic background GC. Only one daemon is permitted to own the queue. A CLI package update does not kill a running daemon or close another agent's tabs; upgrade daemons when idle.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webhelm",
3
- "version": "1.0.27",
3
+ "version": "1.0.29",
4
4
  "description": "Agent browser automation in a visible managed Chrome with persistent JavaScript sessions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,3 +1,4 @@
1
+ import {siteOrigin, setKeptSite, listKeptSites, sitesWithStatus, reportKeptSite} from "./site-registry.mjs";
1
2
  function validTabId(tabId) { return Number.isSafeInteger(tabId) && tabId > 0; }
2
3
  function validateQueueUrl(url) {
3
4
  const parsed = new URL(url);
@@ -17,11 +18,11 @@ export function createControlRpc({control, manager, summarizeWorkspaces, schedul
17
18
  if (!validTabId(session.tabId)) return session;
18
19
  try {
19
20
  const tab = await chromeApi.tabs.get(session.tabId);
20
- return {...session, tab_title: tab.title || 'Untitled tab'};
21
+ return {...session, tab_title: tab.title || 'Untitled tab', tab_url:tab.url || ''};
21
22
  } catch { return {...session, tabId:null}; }
22
23
  })),
23
24
  })));
24
- return {...state,...summary,workspaces};
25
+ return {...state,...summary,workspaces,keptSites:chromeApi.storage?.local ? await sitesWithStatus(chromeApi) : []};
25
26
  }
26
27
  case "workspace.control.activateTab": {
27
28
  const state = await control.status();
@@ -50,6 +51,47 @@ export function createControlRpc({control, manager, summarizeWorkspaces, schedul
50
51
  const opened = await chromeApi.tabs.create({url, active:true});
51
52
  return {ok:true,tabId:opened.id,opened:true};
52
53
  }
54
+ case "workspace.control.site.toggle": {
55
+ const state = await control.status();
56
+ if (!state.connected) throw Error('WebHelm daemon is not responding');
57
+ const session = state.sessions.find(s => s.session_id === args.sessionId);
58
+ if (!session || !validTabId(session.tabId)) throw Error('Session tab is no longer leased');
59
+ if (session.workspace !== 'WebHelm')
60
+ throw Error('Keep Alive can be enabled only from a WebHelm Session');
61
+ const tab = await chromeApi.tabs.get(session.tabId);
62
+ const id = siteOrigin(tab.url || '');
63
+ return setKeptSite(chromeApi,id,Boolean(args.enabled));
64
+ }
65
+ case "workspace.control.site.remove": {
66
+ const site = (await listKeptSites(chromeApi)).find(s => s.id === args.siteId);
67
+ if (!site) throw Error('Keep Alive site is no longer registered');
68
+ return setKeptSite(chromeApi,site.url,false);
69
+ }
70
+ case "workspace.control.site.open": {
71
+ const site = (await listKeptSites(chromeApi)).find(s => s.id === args.siteId);
72
+ if (!site) throw Error('Keep Alive site is no longer registered');
73
+ const url = siteOrigin(site.url);
74
+ const daemon = await control.status();
75
+ const leasedIds = new Set(daemon.connected ? daemon.sessions.flatMap(session =>
76
+ Array.isArray(session.tabIds) ? session.tabIds : [session.tabId]) : []);
77
+ // Never hand a human-login operation an active agent-owned leased Tab.
78
+ const existing = daemon.connected && (await chromeApi.tabs.query({})).find(tab => {
79
+ if (leasedIds.has(tab.id)) return false;
80
+ try { return siteOrigin(tab.url) === url; } catch { return false; }
81
+ });
82
+ if (existing) {
83
+ await chromeApi.tabs.update(existing.id,{active:true});
84
+ await chromeApi.windows.update(existing.windowId,{focused:true});
85
+ return {ok:true,tabId:existing.id,focused:true};
86
+ }
87
+ const opened = await chromeApi.tabs.create({url,active:true});
88
+ return {ok:true,tabId:opened.id,opened:true};
89
+ }
90
+ // Daemon-only control RPCs, unavailable to extension pages.
91
+ case "workspace.control.site.list":
92
+ return listKeptSites(chromeApi);
93
+ case "workspace.control.site.report":
94
+ return reportKeptSite(chromeApi,args);
53
95
  case "workspace.control.requestStop":
54
96
  return control.requestStop(args.action, args.sessionId, args.workspace);
55
97
  case "workspace.control.queueCancel":
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "WebHelm",
4
- "version": "0.4.10",
4
+ "version": "0.4.12",
5
5
  "description": "Own named Chrome tab-group workspaces and lazy reusable tab pools for browser agents.",
6
6
  "permissions": [
7
7
  "storage",
@@ -33,6 +33,14 @@
33
33
  .session-info strong { display:block; font-size:12px; }
34
34
  .session-info span { display:block; color:light-dark(var(--muted),#acb8c9); font-size:11px; }
35
35
  .session-row button { width:auto; padding:5px 9px; font-size:11px; }
36
+ #keepalive-list { max-height:160px; overflow-y:auto; border-bottom:1px solid light-dark(var(--border),#334155); padding:3px 0 5px; font-size:11px; color:light-dark(var(--muted),#acb8c9); }
37
+ .keepalive-row { display:flex; align-items:center; gap:7px; min-height:25px; padding:2px 0; }
38
+ .keepalive-status { flex:0 0 7px; width:7px; height:7px; border-radius:50%; background:light-dark(#8893a1,#8995a5); }
39
+ .keepalive-status[data-status="alive"] { background:#23915c; }
40
+ .keepalive-row .keepalive-name { flex:1; min-width:0; color:light-dark(var(--muted),#acb8c9); font-size:11px; font-weight:500; }
41
+ .keepalive-row .keepalive-name.is-logged-in { color:#23915c; }
42
+ .keepalive-row .keepalive-remove { flex:0 0 19px; width:19px; padding:1px; border:0; background:transparent; color:light-dark(var(--muted),#acb8c9); font-size:16px; font-weight:400; line-height:18px; }
43
+ .session-row button.site-enabled { color:#23915c; }
36
44
  #queue-list { border-top:1px solid light-dark(var(--border),#334155); padding-top:6px; margin-top:2px; }
37
45
  .queue-platform { padding:5px 0; }
38
46
  .queue-platform + .queue-platform { border-top:1px solid light-dark(var(--border),#334155); }
@@ -57,6 +65,8 @@
57
65
  <header class="panel-heading">
58
66
  <span id="daemon-status" class="daemon-state" role="status">Connecting…</span>
59
67
  </header>
68
+ <strong>Keep Alive Sites</strong>
69
+ <div id="keepalive-list" aria-label="Keep Alive Sites">Loading…</div>
60
70
  <div id="workspace-list" class="session-list" aria-label="Workspaces" aria-live="polite">Connecting…</div>
61
71
  <div id="queue-list" class="session-list" aria-label="Queue" aria-live="polite">No queue entries</div>
62
72
  <section id="confirmation" hidden aria-label="Confirm clear sessions">
@@ -3,6 +3,8 @@ let confirming = false;
3
3
  let chosen = null;
4
4
  let lastSignature = '';
5
5
  let lastQueueSignature = '';
6
+ let lastSiteSignature = '';
7
+ let currentSites = [];
6
8
  let refreshRunning = false;
7
9
  const queueRows = new Map();
8
10
  const queueGroups = new Map();
@@ -35,10 +37,52 @@ function actionButton(label, disabled, onClick, className = '') {
35
37
  return button;
36
38
  }
37
39
 
40
+ function originForTab(url) {
41
+ try { const site=new URL(url); return site.protocol === 'https:' ? site.origin : null; }
42
+ catch { return null; }
43
+ }
44
+
45
+ function renderKeptSites(sites, busy, connected) {
46
+ const signature = JSON.stringify(sites) + `:${busy}:${connected}`;
47
+ if (signature === lastSiteSignature) return;
48
+ lastSiteSignature = signature;
49
+ const target = el('keepalive-list');
50
+ target.replaceChildren();
51
+ if (!sites.length) {
52
+ target.textContent='Enable Keep Alive from a WebHelm Session.';
53
+ return;
54
+ }
55
+ const labels={alive:'Logged in',login_required:'Login required',unknown:'Login not confirmed',
56
+ error:'Heartbeat failed',unsupported:'No heartbeat action',pending:'Checking login'};
57
+ for (const site of sites) {
58
+ const row=document.createElement('div'); row.className='keepalive-row';
59
+ const loggedIn=site.status==='alive';
60
+ const statusText=labels[site.status] || labels.pending;
61
+ const status=document.createElement('span'); status.className='keepalive-status';
62
+ status.dataset.status=loggedIn?'alive':'inactive';
63
+ status.title=statusText;
64
+ status.setAttribute('aria-hidden','true');
65
+ const name=actionButton(new URL(site.url).hostname,false,async()=>{
66
+ try {await rpc('workspace.control.site.open',{siteId:site.id});}
67
+ catch(error){el('message').textContent=error.message;}
68
+ },`tab-title keepalive-name ${loggedIn?'is-logged-in':''}`);
69
+ name.title=`${statusText} · Click to open site`;
70
+ name.setAttribute('aria-label',`${new URL(site.url).hostname}: ${statusText}. Open site`);
71
+ const remove=actionButton('×',false,async()=>{
72
+ try {await rpc('workspace.control.site.remove',{siteId:site.id});lastSignature='';refresh();}
73
+ catch(error){el('message').textContent=error.message;}
74
+ },'keepalive-remove');
75
+ remove.title=`Remove ${new URL(site.url).hostname} from Keep Alive`;
76
+ remove.setAttribute('aria-label',remove.title);
77
+ row.append(status,name,remove);
78
+ target.append(row);
79
+ }
80
+ }
81
+
38
82
  function renderWorkspaces(workspaces, busy, connected) {
39
83
  const signature = JSON.stringify(workspaces.map(w => [
40
- w.name,w.initialized,w.available,w.poolSize,w.idleTabs,w.leasedTabs,w.sessions.map(s => [s.session_id,s.tab_title,s.tabId]),
41
- ])) + ':' + busy + ':' + connected;
84
+ w.name,w.initialized,w.available,w.poolSize,w.idleTabs,w.leasedTabs,w.sessions.map(s => [s.session_id,s.tab_title,s.tabId,s.tab_url]),
85
+ ])) + ':' + JSON.stringify(currentSites.map(site=>site.id)) + ':' + busy + ':' + connected;
42
86
  if (signature === lastSignature) return;
43
87
  lastSignature = signature;
44
88
  const target = el('workspace-list');
@@ -73,7 +117,18 @@ function renderWorkspaces(workspaces, busy, connected) {
73
117
  }, 'tab-title');
74
118
  title.title = session.tab_title || 'Untitled tab';
75
119
  details.append(title);
76
- sessionRow.append(details, actionButton('Stop', busy || !connected,
120
+ const siteId=originForTab(session.tab_url);
121
+ sessionRow.append(details);
122
+ if (workspace.name === 'WebHelm' && siteId) {
123
+ const enabled=currentSites.some(site=>site.id===siteId);
124
+ sessionRow.append(actionButton(enabled?'On':'Keep Alive',busy||!connected,async()=>{
125
+ try {
126
+ await rpc('workspace.control.site.toggle',{sessionId:session.session_id,enabled:!enabled});
127
+ lastSignature='';refresh();
128
+ } catch(error){el('message').textContent=error.message;}
129
+ },enabled?'site-enabled':''));
130
+ }
131
+ sessionRow.append(actionButton('Stop', busy || !connected,
77
132
  () => showConfirmation('stop', {sessionId:session.session_id})));
78
133
  row.append(sessionRow);
79
134
  }
@@ -159,6 +214,8 @@ async function refresh() {
159
214
  el('daemon-status').textContent = state.connected ? 'Online' : 'Offline';
160
215
  el('daemon-status').className = `daemon-state ${state.connected ? 'online' : 'offline'}`;
161
216
  const busy = Boolean(state.request);
217
+ currentSites=state.keptSites || [];
218
+ renderKeptSites(currentSites,busy,state.connected);
162
219
  renderWorkspaces(state.workspaces || [], busy, state.connected);
163
220
  renderQueue(state.queue || [], busy, state.connected);
164
221
  el('confirm').disabled = !state.connected || busy;
@@ -102,7 +102,9 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
102
102
  if (request?.method?.startsWith("workspace.control.") &&
103
103
  (sender?.url !== chrome.runtime.getURL("popup.html") ||
104
104
  !["workspace.control.requestStop", "workspace.control.queueCancel", "workspace.control.status",
105
- "workspace.control.activateTab", "workspace.control.openQueue"].includes(request.method))) {
105
+ "workspace.control.activateTab", "workspace.control.openQueue",
106
+ "workspace.control.site.toggle", "workspace.control.site.open",
107
+ "workspace.control.site.remove"].includes(request.method))) {
106
108
  sendResponse({ok:false,error:{message:"WebHelm control actions require the toolbar popup"}});
107
109
  return false;
108
110
  }
@@ -0,0 +1,50 @@
1
+ // Site keep-alive configuration lives in the managed Chrome profile, not a
2
+ // leased WebHelm Session. No cookies, credentials, or page contents are stored.
3
+ export const SITE_STORAGE_KEY = 'webhelm.keepalive.sites.v1';
4
+ export const SITE_STATUS_KEY = 'webhelm.keepalive.status.v1';
5
+
6
+ export function siteOrigin(rawUrl) {
7
+ const parsed = new URL(rawUrl);
8
+ if (parsed.protocol !== 'https:' || !parsed.hostname || parsed.username || parsed.password)
9
+ throw Error('Keep Alive requires a normal HTTPS website');
10
+ return parsed.origin;
11
+ }
12
+
13
+ export async function listKeptSites(chromeApi) {
14
+ const record = (await chromeApi.storage.local.get(SITE_STORAGE_KEY))[SITE_STORAGE_KEY];
15
+ return Array.isArray(record) ? record.filter(site => site && typeof site.id === 'string' &&
16
+ typeof site.url === 'string' && site.id === site.url && site.enabled === true) : [];
17
+ }
18
+
19
+ export async function setKeptSite(chromeApi, url, enabled) {
20
+ const id = siteOrigin(url);
21
+ const sites = (await listKeptSites(chromeApi)).filter(site => site.id !== id);
22
+ if (enabled) sites.push({id, url:id, enabled:true, addedAt:Date.now(), revision:crypto.randomUUID()});
23
+ sites.sort((a,b) => a.id.localeCompare(b.id));
24
+ await chromeApi.storage.local.set({[SITE_STORAGE_KEY]: sites});
25
+ if (!enabled) {
26
+ const states = (await chromeApi.storage.session.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {};
27
+ delete states[id];
28
+ await chromeApi.storage.session.set({[SITE_STATUS_KEY]: states});
29
+ }
30
+ return {id, enabled:Boolean(enabled), sites};
31
+ }
32
+
33
+ export async function sitesWithStatus(chromeApi) {
34
+ const [sites, stored] = await Promise.all([listKeptSites(chromeApi),chromeApi.storage.session.get(SITE_STATUS_KEY)]);
35
+ const states = stored[SITE_STATUS_KEY] || {};
36
+ return sites.map(site => ({...site, status:states[site.id]?.status || 'pending',
37
+ ...(states[site.id]?.checkedAt ? {checkedAt:states[site.id].checkedAt} : {}),
38
+ ...(states[site.id]?.platform ? {platform:states[site.id].platform} : {})}));
39
+ }
40
+
41
+ export async function reportKeptSite(chromeApi, report) {
42
+ const registered = (await listKeptSites(chromeApi)).some(site => site.id === report?.id && site.revision === report?.revision);
43
+ if (!registered || !['alive','login_required','unknown','error','unsupported'].includes(report?.status))
44
+ return {ignored:true};
45
+ const states = (await chromeApi.storage.session.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {};
46
+ states[report.id] = {status:report.status,checkedAt:Date.now(),
47
+ ...(typeof report.platform === 'string' ? {platform:report.platform} : {})};
48
+ await chromeApi.storage.session.set({[SITE_STATUS_KEY]:states});
49
+ return {ok:true};
50
+ }
@@ -12,7 +12,7 @@ export const EXTENSION_HOME=path.resolve(process.env.WEBHELM_EXTENSION_HOME ||
12
12
  (SOURCE_MODE ? SOURCE : path.join(LOCAL_ROOT,'extension')));
13
13
  const FILES=[
14
14
  'manifest.json','service-worker.mjs','workspace-manager.mjs','workspace.html','helm.html','workspace-page.mjs',
15
- 'control-channel.mjs','control-rpc.mjs','workspace-summary.mjs','session-badge.mjs','popup.html','popup.mjs',
15
+ 'control-channel.mjs','control-rpc.mjs','site-registry.mjs','workspace-summary.mjs','session-badge.mjs','popup.html','popup.mjs',
16
16
  ...[16,32,48,128].map(size => `icons/webhelm-${size}.png`),
17
17
  ];
18
18
 
@@ -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 {createSiteKeepaliveScheduler} from './site-keepalive.mjs';
10
11
  import { ChatGPTQueue } from './chatgpt/chatgpt-queue.mjs';
11
12
  import { idleUrlFromIdentity, sameIdleUrl, staleSession, withinDeadline, SessionDeadlineError } from './session-lifecycle.mjs';
12
13
  import { stopMatchingSessions } from './session-control.mjs';
@@ -718,6 +719,22 @@ async function runPlatform(req) {
718
719
  self_heal_capable:!auto,result};
719
720
  }
720
721
 
722
+ const siteKeepalive = createSiteKeepaliveScheduler({
723
+ listSites:() => extensionCall(null,'workspace.control.site.list'),
724
+ report:result => extensionCall(null,'workspace.control.site.report',result),
725
+ canRun:async() => {
726
+ if (shuttingDown) return false; // Low priority: use idle browser capacity only.
727
+ const capacity=await workspaceCapacity();
728
+ return Number.isInteger(capacity.available) && capacity.available > 0;
729
+ },
730
+ run:async plan => {
731
+ const outcome=await runPlatform({platform:plan.platform,action:plan.action,
732
+ url:plan.url,auto_session:true,config:{}});
733
+ if (!outcome.result.ok || outcome.result.cleanup?.release_error) throw Error('Platform heartbeat action failed or session not released');
734
+ return outcome.result.value;
735
+ },
736
+ });
737
+
721
738
  export async function handle(req){switch(req.op){case'ping':return {ok:true,pid:process.pid,version:PACKAGE_VERSION,queue_paused:process.env.WEBHELM_CHATGPT_QUEUE_PAUSED==='1',session_count:sessions.size,managed_chrome:managedChrome||{profile_dir:PROFILE_DIR, endpoint:process.env.WEBHELM_CDP_URL||'http://127.0.0.1:9222',reused:true},chrome_guard:managedChromeGuard.status()};case'guard-check':{let status=await managedChromeGuard.tick();for(let retry=0;retry<6 && status.status!=='healthy' && !status.skipped;retry++){await delay(800);status=await managedChromeGuard.tick();}if(status.status!=='healthy' && !status.skipped)throw Error(`WebHelm Chrome health degraded: ${status.error||status.status}`);return {ok:true,chrome_guard:status};}case'heartbeat':return heartbeatSession(req.session_id);case'list':return {session_count:sessions.size,sessions:[...sessions.values()].map(s=>({session_id:s.session_id,workspace:s.workspace,target_id:s.targetId,last_used_at:s.last_used_at}))};case'start':return createSession(req);case'exec':return execute(req);case'stop':return stopSession(req.session_id);case'stop-all':return stopAllSessions();case'stop-workspace':{if(typeof req.workspace!=='string'||!req.workspace.trim())throw Error('workspace required');return stopWorkspaceSessions(req.workspace)}case'capacity':return workspaceCapacity(req);case'workspace-create':case'workspace-resize':case'workspace-delete':return workspaceOp(req);case'chatgpt-new-turn-enqueue':return getChatGPTQueue().enqueue(req.config);case'queue-list':return getChatGPTQueue().list();case'queue-cancel':return getChatGPTQueue().cancel(req.queue_id);case'platform-run':return runPlatform(req);default:throw Error(`unknown op: ${req.op}`)}}
722
739
  export function serve(conn) {
723
740
  let buffer = '', dispatched = false;
@@ -746,8 +763,10 @@ export function serve(conn) {
746
763
 
747
764
  async function main(){fs.mkdirSync(RUNTIME,{recursive:true,mode:0o700});let lockfd;try{lockfd=fs.openSync(LOCK,'wx',0o600);fs.writeFileSync(lockfd,String(process.pid))}catch{throw Error(`Node pilot lock exists: ${LOCK}`)}if(fs.existsSync(SOCKET)){try{const c=net.createConnection(SOCKET);await new Promise((res,rej)=>{c.once('connect',res);c.once('error',rej)});c.destroy();fs.closeSync(lockfd);fs.unlinkSync(LOCK);throw Error(`Node daemon socket already active: ${SOCKET}`)}catch(e){if(e.message.includes('already active'))throw e;fs.unlinkSync(SOCKET)}}socket=net.createServer(serve);await new Promise((res,rej)=>socket.listen(SOCKET,res).once('error',rej));fs.chmodSync(SOCKET,0o600);connectBrowser().catch(()=>{});managedChromeGuard.start();getChatGPTQueue();
748
765
  const controlTimer=setInterval(()=>pollExtensionControl(),3000);
766
+ const siteTimer=setInterval(()=>siteKeepalive.tick().catch(e=>console.warn(`WebHelm site keep-alive: ${e.message}`)),Math.max(1000,Number(process.env.WEBHELM_SITE_HEARTBEAT_POLL_MS)||30000));
749
767
  pollExtensionControl().catch(()=>{});
750
- const cleanup=async()=>{if(shuttingDown)return;shuttingDown=true;clearInterval(controlTimer);managedChromeGuard.stop();if(chatgptQueue)await chatgptQueue.shutdown().catch(()=>{});await handle({op:'stop-all'}).catch(()=>{});socket?.close();try{if(fs.existsSync(SOCKET))fs.unlinkSync(SOCKET)}catch{}try{fs.closeSync(lockfd);fs.unlinkSync(LOCK)}catch{}process.exit(0)};process.on('SIGTERM',cleanup);process.on('SIGINT',cleanup)}
768
+ siteKeepalive.tick().catch(()=>{});
769
+ const cleanup=async()=>{if(shuttingDown)return;shuttingDown=true;clearInterval(controlTimer);clearInterval(siteTimer);managedChromeGuard.stop();if(chatgptQueue)await chatgptQueue.shutdown().catch(()=>{});await handle({op:'stop-all'}).catch(()=>{});socket?.close();try{if(fs.existsSync(SOCKET))fs.unlinkSync(SOCKET)}catch{}try{fs.closeSync(lockfd);fs.unlinkSync(LOCK)}catch{}process.exit(0)};process.on('SIGTERM',cleanup);process.on('SIGINT',cleanup)}
751
770
  // IPC duration is independent of the daemon's JS/Action execution timeout.
752
771
  // A wedged daemon can no longer strand CLI processes indefinitely.
753
772
  export function ipcTimeoutMs(op) {
@@ -32,7 +32,7 @@ export function platformManifest(platform) {
32
32
 
33
33
  export function platformProfile(platform) {
34
34
  const manifest = platformManifest(platform);
35
- const fields = ['platform', 'display_name', 'aliases', 'implementation_status', 'media', 'fields', 'capabilities', 'content_mapping', 'notes'];
35
+ const fields = ['platform', 'display_name', 'aliases', 'implementation_status', 'media', 'fields', 'capabilities', 'content_mapping', 'keep_alive', 'notes'];
36
36
  return Object.fromEntries(fields.filter(k => k in manifest).map(k => [k, manifest[k]]));
37
37
  }
38
38
 
@@ -0,0 +1,78 @@
1
+ import {listPlatforms, platformManifest, actionPath} from './platforms.mjs';
2
+
3
+ const MAX_INTERVAL_MINUTES = 24 * 60;
4
+ const MIN_INTERVAL_MINUTES = 5;
5
+
6
+ function matchingOrigin(pattern, origin) {
7
+ try { return new URL(String(pattern).replaceAll('*','webhelm-wildcard')).origin === origin; }
8
+ catch { return false; }
9
+ }
10
+
11
+ // A platform opts in through a manifest keep_alive declaration. There is NO
12
+ // generic web request or URL ping: only its own read-only Action can decide
13
+ // whether a login is alive, expired, or unknown.
14
+ export function resolveSiteHeartbeat(site, names=listPlatforms, manifestFor=platformManifest, actionFor=actionPath) {
15
+ let origin;
16
+ try {
17
+ const url = new URL(site?.url);
18
+ if (!site?.enabled || url.protocol !== 'https:' || url.origin !== site.id || url.href !== `${url.origin}/`) return null;
19
+ origin = url.origin;
20
+ } catch { return null; }
21
+ for (const platform of names()) {
22
+ const manifest = manifestFor(platform);
23
+ const conf = manifest.keep_alive;
24
+ if (!conf || conf.enabled === false || !Array.isArray(manifest.url_patterns) ||
25
+ !manifest.url_patterns.some(pattern => matchingOrigin(pattern,origin))) continue;
26
+ const action = conf.action || 'heartbeat';
27
+ actionFor(platform,action); // Ensure only declared local Actions execute.
28
+ const minutes = Number(conf.interval_minutes ?? 30);
29
+ if (!Number.isFinite(minutes) || minutes < MIN_INTERVAL_MINUTES || minutes > MAX_INTERVAL_MINUTES)
30
+ throw Error(`Invalid keep_alive interval for ${platform}`);
31
+ const target = new URL(conf.url || site.url);
32
+ if (target.protocol !== 'https:' || target.origin !== origin || target.username || target.password ||
33
+ target.search || target.hash) throw Error(`Invalid keep_alive URL for ${platform}`);
34
+ return {platform,action,url:target.href,intervalMs:minutes*60000};
35
+ }
36
+ return null;
37
+ }
38
+
39
+ export function createSiteKeepaliveScheduler({listSites, report, run, resolve=resolveSiteHeartbeat,
40
+ now=Date.now, canRun=async()=>true}) {
41
+ const next = new Map();
42
+ let active = false;
43
+ return {
44
+ async tick() {
45
+ if (active) return {busy:true};
46
+ active=true;
47
+ try {
48
+ const sites=await listSites();
49
+ const known=new Set(sites.map(s=>s.id));
50
+ for (const id of next.keys()) if (!known.has(id)) next.delete(id);
51
+ for (const site of sites) {
52
+ const nextCheck=next.get(site.id);
53
+ if (nextCheck && nextCheck.revision === site.revision && now() < nextCheck.at) continue;
54
+ let plan;
55
+ try {plan = resolve(site);} catch {plan=null; }
56
+ if (!plan) {
57
+ next.set(site.id,{at:now()+5*60000,revision:site.revision});
58
+ await report({id:site.id,revision:site.revision,status:'unsupported'});
59
+ continue;
60
+ }
61
+ if (!await canRun()) return {deferred:true};
62
+ // Set deadline before running to prevent concurrent retries during
63
+ // slow site actions. No automatic replay of timed-out actions.
64
+ next.set(site.id,{at:now()+plan.intervalMs,revision:site.revision});
65
+ let status='error';
66
+ try {
67
+ const result=await run({...plan,site});
68
+ status=['alive','login_required','unknown'].includes(result?.status)?result.status:'unknown';
69
+ } catch { /* No secret URLs, cookies, or Action traces in the popup. */ }
70
+ if (status !== 'alive') next.set(site.id,{at:now()+Math.min(plan.intervalMs,5*60000),revision:site.revision});
71
+ await report({id:site.id,revision:site.revision,platform:plan.platform,status});
72
+ return {id:site.id,status}; // At most one site check per scheduler tick.
73
+ }
74
+ return {idle:true};
75
+ } finally {active=false;}
76
+ },
77
+ };
78
+ }