webhelm 1.0.26 → 1.0.28
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 +38 -0
- package/package.json +1 -1
- package/runtime/chatgpt/chatgpt-probe.mjs +28 -2
- package/runtime/chatgpt/chatgpt-queue.mjs +9 -2
- package/runtime/chatgpt/lifecycle-common.mjs +1 -1
- package/runtime/extension/control-rpc.mjs +42 -2
- package/runtime/extension/manifest.json +1 -1
- package/runtime/extension/popup.html +11 -0
- package/runtime/extension/popup.mjs +53 -2
- package/runtime/extension/service-worker.mjs +3 -1
- package/runtime/extension/site-registry.mjs +50 -0
- package/runtime/extension-manager.mjs +1 -1
- package/runtime/node-daemon.mjs +20 -1
- package/runtime/platforms.mjs +1 -1
- package/runtime/site-keepalive.mjs +78 -0
package/README.md
CHANGED
|
@@ -45,6 +45,44 @@ 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
|
+
On a WebHelm-leased HTTPS page, use the Extension's **Keep Alive** toggle 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. Click its name to open/focus
|
|
53
|
+
that website in the existing managed Chrome profile and sign in again. Remove
|
|
54
|
+
clears the registration. Credentials, cookies, URL query strings, and browser
|
|
55
|
+
Session IDs are never copied into the registry. Site registration does **not**
|
|
56
|
+
keep a WebHelm Session or Tab permanently leased.
|
|
57
|
+
|
|
58
|
+
A Platform only needs a periodic heartbeat if that specific website requires
|
|
59
|
+
one. Site Actions opt in **individually**, in their Actions checkout's
|
|
60
|
+
`manifest.yaml`, for example:
|
|
61
|
+
|
|
62
|
+
```yaml
|
|
63
|
+
url_patterns:
|
|
64
|
+
- https://creator.example.com/*
|
|
65
|
+
actions:
|
|
66
|
+
heartbeat: actions/_heartbeat.mjs
|
|
67
|
+
keep_alive:
|
|
68
|
+
action: heartbeat
|
|
69
|
+
interval_minutes: 30
|
|
70
|
+
url: https://creator.example.com/
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The Platform's heartbeat Action runs with the existing `helpers` and must be
|
|
74
|
+
read-only. It returns `{status:'alive'|'login_required'|'unknown'}` after using
|
|
75
|
+
site-specific evidence; never infer login solely from HTTP success or page
|
|
76
|
+
load. WebHelm schedules only opted-in platforms, using a temporary browser
|
|
77
|
+
Session and an idle pool slot. On failure, the UI displays **Check failed**;
|
|
78
|
+
non-opted-in sites display **No heartbeat action** and can still be opened for
|
|
79
|
+
manual login. Failed/unknown checks retry no faster than five minutes. Neither
|
|
80
|
+
heartbeat nor browser persistence guarantees that the service will extend its
|
|
81
|
+
login lifetime. No automatic credential input or challenge bypass occurs.
|
|
82
|
+
|
|
83
|
+
The Platform Action implementation and its verification belong in
|
|
84
|
+
`lalalic/webhelm-actions`, not in this Runtime repository.
|
|
85
|
+
|
|
48
86
|
## Architecture and compatibility
|
|
49
87
|
|
|
50
88
|
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
|
@@ -7,8 +7,34 @@ export function targetUrl(projectId, threadId, message) {
|
|
|
7
7
|
return "https://chatgpt.com/c/" + encodeURIComponent(threadId) +
|
|
8
8
|
"?" + new URLSearchParams({ prompt: message });
|
|
9
9
|
}
|
|
10
|
-
export const PROBE_JS =
|
|
11
|
-
|
|
10
|
+
export const PROBE_JS = `(() => {
|
|
11
|
+
const visible = e => !!e && !!e.getClientRects().length && getComputedStyle(e).visibility !== 'hidden';
|
|
12
|
+
const body = (document.body?.innerText || '').toLowerCase();
|
|
13
|
+
if (body.includes('could not load this chatgpt conversation'))
|
|
14
|
+
return {state: 'BLOCKED', error: 'thread_load_failed'};
|
|
15
|
+
if (body.includes('log in to chatgpt') || body.includes('sign in to chatgpt'))
|
|
16
|
+
return {state: 'BLOCKED', error: 'authentication_required'};
|
|
17
|
+
const stop = [...document.querySelectorAll('button')].some(b => {
|
|
18
|
+
if (!visible(b)) return false;
|
|
19
|
+
const label = (b.getAttribute('aria-label') || '').trim().toLowerCase();
|
|
20
|
+
const title = (b.getAttribute('title') || '').trim().toLowerCase();
|
|
21
|
+
const testId = (b.getAttribute('data-testid') || '').trim().toLowerCase();
|
|
22
|
+
return ['stop generating', 'stop answering', 'stop response', 'stop'].includes(label) ||
|
|
23
|
+
['stop generating', 'stop answering'].includes(title) ||
|
|
24
|
+
['stop-button', 'stop-generating-button'].includes(testId);
|
|
25
|
+
});
|
|
26
|
+
if (stop) return {state: 'RUNNING', stop_visible: true};
|
|
27
|
+
const e = [...document.querySelectorAll('#prompt-textarea,[contenteditable="true"][data-lexical-editor="true"],[role="textbox"][contenteditable="true"],textarea')].find(visible);
|
|
28
|
+
const editable = e?.getAttribute?.('contenteditable') === 'true';
|
|
29
|
+
// ProseMirror uses <p> for each visual line, including empty lines.
|
|
30
|
+
// e.textContent and, in some Chrome builds, e.innerText omit those line
|
|
31
|
+
// boundaries, so a correctly prefilled multiline prompt never matches.
|
|
32
|
+
const paragraphs = editable ? [...e.children] : [];
|
|
33
|
+
const composerText = editable && paragraphs.length && paragraphs.every(p => p.tagName === 'P')
|
|
34
|
+
? paragraphs.map(p => p.textContent || '').join('\\n')
|
|
35
|
+
: editable ? (e.innerText || e.textContent || '') : (e?.value || e?.textContent || e?.innerText || '');
|
|
36
|
+
return {state: visible(e) ? 'READY' : 'NOT_READY', stop_visible: false, composer_text: composerText};
|
|
37
|
+
})()`;
|
|
12
38
|
export function classifyProbe(observedUrl, expectedUrl, state) {
|
|
13
39
|
const actual = new URL(observedUrl), expected = new URL(expectedUrl);
|
|
14
40
|
const thread = url => {
|
|
@@ -64,6 +64,10 @@ const chatgptQueuePolicy = {
|
|
|
64
64
|
claim(db, owner, now, leaseSeconds) {
|
|
65
65
|
db.prepare("UPDATE turns SET state='UNCERTAIN',lease_owner=NULL,lease_until=NULL WHERE state='SENDING' AND lease_until<=?").run(now);
|
|
66
66
|
db.prepare("UPDATE turns SET state='WAITING',lease_owner=NULL,lease_until=NULL,next_check_at=? WHERE state='CHECKING' AND lease_until<=?").run(now,now);
|
|
67
|
+
// BLOCKED is a pre-send failure. Retry after cooldown so a transient
|
|
68
|
+
// login or redirect cannot permanently starve all later turns in a thread.
|
|
69
|
+
// UNCERTAIN remains excluded: that turn might already have been sent.
|
|
70
|
+
db.prepare("UPDATE turns SET state='WAITING',lease_owner=NULL,lease_until=NULL,next_check_at=? WHERE state='BLOCKED' AND next_check_at<=?").run(now,now);
|
|
67
71
|
const row=this.one(db, `SELECT t.* FROM turns t WHERE t.state IN ('QUEUED','WAITING') AND t.next_check_at<=? AND NOT EXISTS(SELECT 1 FROM turns older WHERE older.thread_id=t.thread_id AND older.seq<t.seq AND (older.state NOT IN ('SENT','CANCELLED') OR (older.state='SENT' AND older.next_check_at>?))) ORDER BY t.seq LIMIT 1`,now,now);
|
|
68
72
|
if (!row) return null;
|
|
69
73
|
db.prepare("UPDATE turns SET state='CHECKING',lease_owner=?,lease_until=?,attempts=attempts+1 WHERE id=?").run(owner,now+leaseSeconds,row.id);
|
|
@@ -181,7 +185,7 @@ export class ChatGPTQueue extends DurableQueueCore {
|
|
|
181
185
|
target,
|
|
182
186
|
release ? null : owner,
|
|
183
187
|
release ? null : now + 120,
|
|
184
|
-
["WAITING", "SENT"].includes(target) ? now + delay : now,
|
|
188
|
+
["WAITING", "SENT", "BLOCKED"].includes(target) ? now + delay : now,
|
|
185
189
|
receipt,
|
|
186
190
|
id,
|
|
187
191
|
);
|
|
@@ -283,9 +287,12 @@ export class ChatGPTQueue extends DurableQueueCore {
|
|
|
283
287
|
return;
|
|
284
288
|
}
|
|
285
289
|
if (state === "BLOCKED") {
|
|
290
|
+
// Recheck pre-send failures with bounded exponential backoff (1m..1h).
|
|
291
|
+
const delay = Math.min(3600, 60 * (2 ** Math.min(6, Math.max(0, item.attempts - 1))));
|
|
286
292
|
this.transition(item.id, owner, "CHECKING", "BLOCKED", {
|
|
287
|
-
receipt: "page blocked",
|
|
293
|
+
receipt: "page blocked", delay,
|
|
288
294
|
});
|
|
295
|
+
this.logger({event: "page_blocked", queue_id: item.id, attempts: item.attempts, retry_in_seconds: delay});
|
|
289
296
|
return;
|
|
290
297
|
}
|
|
291
298
|
if (state !== "READY") {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { waitUntilStable } from "./readiness.mjs";
|
|
2
2
|
export const SEND_ENABLED_JS =
|
|
3
|
-
`(() => { const
|
|
3
|
+
`(() => { const buttons=[...document.querySelectorAll('button[data-testid="send-button"],button[aria-label="Send prompt"],button[aria-label="Send"],form button[type="submit"]')]; const b=buttons.find(e=>e.getClientRects().length>0); return !!b && !b.disabled && b.getAttribute('aria-disabled') !== 'true'; })()`;
|
|
4
4
|
export const CLICK_SEND_JS =
|
|
5
5
|
`(() => { const visible=e=>!!e&&!!e.getClientRects().length; const running=[...document.querySelectorAll('button')].some(b=>{ if(!visible(b))return false; const l=(b.getAttribute('aria-label')||'').trim().toLowerCase(),t=(b.getAttribute('title')||'').trim().toLowerCase(),d=(b.getAttribute('data-testid')||'').trim().toLowerCase(); return ['stop generating','stop answering','stop response','stop'].includes(l)||['stop generating','stop answering'].includes(t)||['stop-button','stop-generating-button'].includes(d); }); if(running)return false; const b=document.querySelector('button[data-testid="send-button"],button[aria-label="Send prompt"],button[aria-label="Send"],form button[type="submit"]'); if(!b||b.disabled||b.getAttribute('aria-disabled')==='true')return false; b.click(); return true; })()`;
|
|
6
6
|
export function targetUrl(
|
|
@@ -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,45 @@ 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
|
+
const tab = await chromeApi.tabs.get(session.tabId);
|
|
60
|
+
const id = siteOrigin(tab.url || '');
|
|
61
|
+
return setKeptSite(chromeApi,id,Boolean(args.enabled));
|
|
62
|
+
}
|
|
63
|
+
case "workspace.control.site.remove": {
|
|
64
|
+
const site = (await listKeptSites(chromeApi)).find(s => s.id === args.siteId);
|
|
65
|
+
if (!site) throw Error('Keep Alive site is no longer registered');
|
|
66
|
+
return setKeptSite(chromeApi,site.url,false);
|
|
67
|
+
}
|
|
68
|
+
case "workspace.control.site.open": {
|
|
69
|
+
const site = (await listKeptSites(chromeApi)).find(s => s.id === args.siteId);
|
|
70
|
+
if (!site) throw Error('Keep Alive site is no longer registered');
|
|
71
|
+
const url = siteOrigin(site.url);
|
|
72
|
+
const daemon = await control.status();
|
|
73
|
+
const leasedIds = new Set(daemon.connected ? daemon.sessions.flatMap(session =>
|
|
74
|
+
Array.isArray(session.tabIds) ? session.tabIds : [session.tabId]) : []);
|
|
75
|
+
// Never hand a human-login operation an active agent-owned leased Tab.
|
|
76
|
+
const existing = daemon.connected && (await chromeApi.tabs.query({})).find(tab => {
|
|
77
|
+
if (leasedIds.has(tab.id)) return false;
|
|
78
|
+
try { return siteOrigin(tab.url) === url; } catch { return false; }
|
|
79
|
+
});
|
|
80
|
+
if (existing) {
|
|
81
|
+
await chromeApi.tabs.update(existing.id,{active:true});
|
|
82
|
+
await chromeApi.windows.update(existing.windowId,{focused:true});
|
|
83
|
+
return {ok:true,tabId:existing.id,focused:true};
|
|
84
|
+
}
|
|
85
|
+
const opened = await chromeApi.tabs.create({url,active:true});
|
|
86
|
+
return {ok:true,tabId:opened.id,opened:true};
|
|
87
|
+
}
|
|
88
|
+
// Daemon-only control RPCs, unavailable to extension pages.
|
|
89
|
+
case "workspace.control.site.list":
|
|
90
|
+
return listKeptSites(chromeApi);
|
|
91
|
+
case "workspace.control.site.report":
|
|
92
|
+
return reportKeptSite(chromeApi,args);
|
|
53
93
|
case "workspace.control.requestStop":
|
|
54
94
|
return control.requestStop(args.action, args.sessionId, args.workspace);
|
|
55
95
|
case "workspace.control.queueCancel":
|
|
@@ -33,6 +33,15 @@
|
|
|
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-bottom:6px; font-size:11px; color:light-dark(var(--muted),#acb8c9); }
|
|
37
|
+
.keepalive-row { display:flex; align-items:center; gap:6px; padding:5px 0; }
|
|
38
|
+
.keepalive-info { flex:1; min-width:0; overflow:hidden; }
|
|
39
|
+
.keepalive-row button { width:auto; padding:4px 7px; font-size:11px; }
|
|
40
|
+
.keepalive-row .tab-title { width:100%; font-size:12px; }
|
|
41
|
+
.keepalive-status { display:block; font-size:10px; }
|
|
42
|
+
.keepalive-status[data-status="alive"] { color:#23915c; }
|
|
43
|
+
.keepalive-status[data-status="login_required"] { color:#ae3849; }
|
|
44
|
+
.session-row button.site-enabled { color:#23915c; }
|
|
36
45
|
#queue-list { border-top:1px solid light-dark(var(--border),#334155); padding-top:6px; margin-top:2px; }
|
|
37
46
|
.queue-platform { padding:5px 0; }
|
|
38
47
|
.queue-platform + .queue-platform { border-top:1px solid light-dark(var(--border),#334155); }
|
|
@@ -57,6 +66,8 @@
|
|
|
57
66
|
<header class="panel-heading">
|
|
58
67
|
<span id="daemon-status" class="daemon-state" role="status">Connecting…</span>
|
|
59
68
|
</header>
|
|
69
|
+
<strong>Keep Alive Sites</strong>
|
|
70
|
+
<div id="keepalive-list" aria-label="Keep Alive Sites">Loading…</div>
|
|
60
71
|
<div id="workspace-list" class="session-list" aria-label="Workspaces" aria-live="polite">Connecting…</div>
|
|
61
72
|
<div id="queue-list" class="session-list" aria-label="Queue" aria-live="polite">No queue entries</div>
|
|
62
73
|
<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,9 +37,45 @@ 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='Toggle Keep Alive on a leased website to add it here.';
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const labels={alive:'Logged in',login_required:'Login required',unknown:'Login unknown',
|
|
56
|
+
error:'Check failed',unsupported:'No heartbeat action',pending:'Pending check'};
|
|
57
|
+
for (const site of sites) {
|
|
58
|
+
const row=document.createElement('div'); row.className='keepalive-row';
|
|
59
|
+
const details=document.createElement('div'); details.className='keepalive-info';
|
|
60
|
+
const name=actionButton(new URL(site.url).hostname,false,async()=>{
|
|
61
|
+
try {await rpc('workspace.control.site.open',{siteId:site.id});}
|
|
62
|
+
catch(error){el('message').textContent=error.message;}
|
|
63
|
+
},'tab-title');
|
|
64
|
+
const status=document.createElement('span'); status.className='keepalive-status';
|
|
65
|
+
status.textContent=labels[site.status] || 'Pending check';
|
|
66
|
+
status.dataset.status=site.status;
|
|
67
|
+
details.append(name,status);
|
|
68
|
+
row.append(details,actionButton('Remove',false,async()=>{
|
|
69
|
+
try {await rpc('workspace.control.site.remove',{siteId:site.id});lastSignature='';refresh();}
|
|
70
|
+
catch(error){el('message').textContent=error.message;}
|
|
71
|
+
}));
|
|
72
|
+
target.append(row);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
38
76
|
function renderWorkspaces(workspaces, busy, connected) {
|
|
39
77
|
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]),
|
|
78
|
+
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]),
|
|
41
79
|
])) + ':' + busy + ':' + connected;
|
|
42
80
|
if (signature === lastSignature) return;
|
|
43
81
|
lastSignature = signature;
|
|
@@ -73,7 +111,18 @@ function renderWorkspaces(workspaces, busy, connected) {
|
|
|
73
111
|
}, 'tab-title');
|
|
74
112
|
title.title = session.tab_title || 'Untitled tab';
|
|
75
113
|
details.append(title);
|
|
76
|
-
|
|
114
|
+
const siteId=originForTab(session.tab_url);
|
|
115
|
+
sessionRow.append(details);
|
|
116
|
+
if (siteId) {
|
|
117
|
+
const enabled=currentSites.some(site=>site.id===siteId);
|
|
118
|
+
sessionRow.append(actionButton(enabled?'On':'Keep Alive',busy||!connected,async()=>{
|
|
119
|
+
try {
|
|
120
|
+
await rpc('workspace.control.site.toggle',{sessionId:session.session_id,enabled:!enabled});
|
|
121
|
+
lastSignature='';refresh();
|
|
122
|
+
} catch(error){el('message').textContent=error.message;}
|
|
123
|
+
},enabled?'site-enabled':''));
|
|
124
|
+
}
|
|
125
|
+
sessionRow.append(actionButton('Stop', busy || !connected,
|
|
77
126
|
() => showConfirmation('stop', {sessionId:session.session_id})));
|
|
78
127
|
row.append(sessionRow);
|
|
79
128
|
}
|
|
@@ -159,6 +208,8 @@ async function refresh() {
|
|
|
159
208
|
el('daemon-status').textContent = state.connected ? 'Online' : 'Offline';
|
|
160
209
|
el('daemon-status').className = `daemon-state ${state.connected ? 'online' : 'offline'}`;
|
|
161
210
|
const busy = Boolean(state.request);
|
|
211
|
+
currentSites=state.keptSites || [];
|
|
212
|
+
renderKeptSites(currentSites,busy,state.connected);
|
|
162
213
|
renderWorkspaces(state.workspaces || [], busy, state.connected);
|
|
163
214
|
renderQueue(state.queue || [], busy, state.connected);
|
|
164
215
|
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"
|
|
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
|
|
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 {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
|
-
|
|
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) {
|
package/runtime/platforms.mjs
CHANGED
|
@@ -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
|
+
}
|