webhelm 1.0.48 → 1.0.49

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
@@ -1,6 +1,6 @@
1
1
  # WebHelm
2
2
 
3
- [WebHelm](https://github.com/lalalic/webhelm) is a Node.js CLI and agent Skill for a visible, managed Chrome instance. One Runtime daemon controls CDP, persistent JavaScript browser Sessions, Chrome Tab Groups, and durable ChatGPT FIFO delivery.
3
+ [WebHelm](https://github.com/lalalic/webhelm) is a Node.js CLI and agent Skill for a visible, managed Chrome instance. One Runtime daemon controls CDP, persistent JavaScript browser Sessions, Chrome Tab Groups, and durable Platform-registered FIFO queues.
4
4
 
5
5
  ## Two repositories, independent releases
6
6
 
@@ -54,7 +54,7 @@ The scheduled job does not depend on the npx cache. For immediate checking use
54
54
 
55
55
  **No active Session is interrupted.** Before cutover, the daemon atomically
56
56
  checks that no Sessions, pending leases, IPC operations or queue workers are
57
- running, then pauses new browser work. New queued ChatGPT turns remain durable
57
+ running, then pauses new browser work. New queued Platform actions remain durable
58
58
  and are accepted during the short cutover. The updater switches the stable
59
59
  Runtime pointer, waits for the idle daemon to stop gracefully, starts the
60
60
  new daemon against the existing Chrome/profile/queue, and verifies its version.
@@ -83,13 +83,13 @@ the actual `message`. If the combined text exceeds 2,000 characters, WebHelm
83
83
  uploads the exact original `message` as `prompt.md` and keeps the optional
84
84
  context in the visible composer before `Read prompt.md...`. Omitting the
85
85
  option preserves the old short composer and attachment behavior. Durable
86
- queued `newTurn` persists the context and checks it for idempotency.
86
+ queued `newTurn` queue Policy persists the context and checks it for idempotency.
87
87
 
88
88
  ## WebHelm Chrome Extension control panel
89
89
 
90
90
  The daemon-managed Chrome Extension is installed from the npm Runtime and does not require the Chrome Web Store. Click the WebHelm toolbar icon to see daemon connectivity, each configured workspace's available capacity and current Session count. The toolbar badge shows the number of **active daemon Sessions** across all workspaces (including `0` when idle). `!` means the daemon heartbeat is stale and `?` means the Session count is unknown. The popup separately shows pool availability and idle tabs.
91
91
 
92
- The compact popup shows daemon connectivity and per-workspace capacity and Session counts, with confirmation before stopping a Session or clearing Sessions in one workspace. The popup does not include a global stop-all action. These actions are executed by the same Node daemon as the CLI, over the existing CDP-backed Extension RPC. No shell access or HTTP listener is granted to the Extension. The persistent ChatGPT queue is not deleted, and queued work may create new Sessions afterward.
92
+ The compact popup shows daemon connectivity and per-workspace capacity and Session counts, with confirmation before stopping a Session or clearing Sessions in one workspace. The popup does not include a global stop-all action. These actions are executed by the same Node daemon as the CLI, over the existing CDP-backed Extension RPC. No shell access or HTTP listener is granted to the Extension. Persistent Platform queues are not deleted, and queued work may create new Sessions afterward.
93
93
 
94
94
  New installations use the default Chrome tab group `WebHelm` and the idle page `helm.html`. Idle URLs use only `workspace` and `role=idle`; Lease URLs use Chrome's actual `tabId` for initial CDP target discovery. There is no separate slot identity. Every newly created WebHelm-managed tab group (default and custom) is placed at the far left of its Chrome window, immediately after pinned tabs. Existing groups retain their user-chosen position during restoration, legacy migration and Session allocation. Chrome-saved tab group shortcuts in the bookmarks bar are separate from active groups and cannot safely be deduplicated through the Extension API. Legacy `Harness` default groups migrate only when their tabs are idle. Custom workspace names are unchanged; the old `workspace.html` path and lease titles remain readable until their Sessions finish. Closing an allocated Session returns its managed tabs to the idle page, retaining physical Chrome targets, while unleased popup children are closed. **A new lease only selects an actual `role=idle` extension tab with no pending navigation, excluding every tab owned by a live or pending daemon Session.** A briefly idle-looking URL is never sufficient to reclaim an active Session; stale Sessions are recovered only after the inactivity timeout. Do not manually remove active managed tabs.
95
95
 
@@ -142,7 +142,7 @@ The Platform Action implementation and its verification belong in
142
142
 
143
143
  ## Architecture and compatibility
144
144
 
145
- The Runtime stores the Chrome profile under `~/.local/webhelm/chrome` and the persistent FIFO queue and IPC socket under `~/.config/webhelm/runtime/`. The runtime refuses to start against a conflicting Chrome profile rather than silently replacing an existing login. 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.
145
+ The Runtime stores the Chrome profile under `~/.local/webhelm/chrome` and the persistent FIFO queues and IPC socket under `~/.config/webhelm/runtime/`. The runtime refuses to start against a conflicting Chrome profile rather than silently replacing an existing login. 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.
146
146
 
147
147
  NeoY and Relay can continue using `webhelm` session commands, `result.stdout` JSON receipts, and `admin_helper` returned by `status`. An `admin_helper` inside the installed Skill is a stable connector to the same Node IPC socket. `webhelm capacity` replaces the legacy Python capacity probe.
148
148
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webhelm",
3
- "version": "1.0.48",
3
+ "version": "1.0.49",
4
4
  "description": "Agent browser automation in a visible managed Chrome with persistent JavaScript sessions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -250,7 +250,7 @@ Example:
250
250
  Usage:
251
251
  webhelm platform run PLATFORM ACTION --session-id SESSION_ID [--config FILE] [--url URL]
252
252
  webhelm platform run PLATFORM ACTION --auto-session [--config FILE] [--url URL]
253
- webhelm platform run chatgpt new-turn [--config FILE] [--mode async|sync] [--session-id ID]
253
+ webhelm platform run PLATFORM QUEUED_ACTION [--config FILE]
254
254
 
255
255
  Arguments:
256
256
  PLATFORM Site name from 'webhelm platform list'
@@ -261,18 +261,18 @@ Options:
261
261
  --auto-session Create and release a Session for one self-contained Action
262
262
  --config FILE Read a JSON object of Action-specific inputs (default: {})
263
263
  --url URL Optional initial URL for a browser Action
264
- --mode MODE Only for chatgpt/new-turn: async (default) or sync
265
264
  -h, --help Show help without executing an Action
266
265
 
267
- --session-id and --auto-session cannot be combined. For chatgpt/new-turn,
268
- async mode uses no Session option; sync mode requires --session-id.
266
+ --session-id and --auto-session cannot be combined. A Platform Policy in
267
+ queues/*.mjs makes a no-Session invocation asynchronous and durable; providing
268
+ --session-id runs the declared Action directly. No mode flag or config field.
269
269
  Inspect 'platform profile' and 'platform source' for Action-specific inputs.
270
270
  Output: JSON Action result. An accepted submission may require later verification.
271
271
 
272
272
  Examples:
273
273
  webhelm platform run z new-turn --session-id SESSION_ID --config ./turn.json
274
274
  webhelm platform run chatgpt new-turn --config ./turn.json
275
- webhelm platform run chatgpt new-turn --mode sync --session-id SESSION_ID --config ./turn.json`,
275
+ webhelm platform run chatgpt new-turn --session-id SESSION_ID --config ./turn.json`,
276
276
  'platform sync': `webhelm platform sync — update installed site Actions
277
277
 
278
278
  Usage:
package/runtime/cli.mjs CHANGED
@@ -5,7 +5,7 @@ import os from 'node:os';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { ensureDaemon, request, SOCKET } from './node-daemon.mjs';
8
- import { PLATFORMS, listPlatforms, platformProfile, actionPath, validateConfig } from './platforms.mjs';
8
+ import { PLATFORMS, listPlatforms, platformProfile, actionPath, validateConfig, queueForAction } from './platforms.mjs';
9
9
  import { ACTIONS_DIR, ensureActions, syncActions, publishActions } from './actions-repo.mjs';
10
10
  import { activateRuntime, currentRuntimePath, installLoginGuard, installRuntimeUpdate, migrateLegacyRuntimeCli, stageRuntimeForLoginGuard } from './login-guard.mjs';
11
11
  import { upgradeRuntime } from './auto-update.mjs';
@@ -29,52 +29,29 @@ function loadConfig(args) {
29
29
  return cfg;
30
30
  }
31
31
 
32
- function validateMode(platform, action, args, config) {
33
- const isNewTurn = platform === 'chatgpt' && action === 'new-turn';
34
- const override = arg(args, '--mode');
35
- if (!isNewTurn && override !== undefined) throw Error('--mode is supported only for chatgpt/new-turn');
36
- if (!isNewTurn) return null;
37
- if ('sync' in config) throw Error('legacy sync is not supported; use mode: async or sync');
38
- if (override !== undefined && 'mode' in config && override !== config.mode) throw Error('--mode conflicts with the new-turn config mode');
39
- const mode = override ?? config.mode ?? 'async';
40
- if (typeof mode !== 'string' || !['async', 'sync'].includes(mode)) throw Error('mode must be exactly async or sync');
41
- if (mode === 'sync' && config.mergeable !== undefined && config.mergeable !== false) {
42
- throw Error('mergeable is only supported in async mode');
43
- }
44
- return mode;
45
- }
46
-
47
32
  async function runPlatform(args) {
48
- const platform = args[2], action = args[3]?.replaceAll('_', '-');
33
+ const platform = args[2], action = args[3];
49
34
  if (!platform || !action) throw Error('platform run requires PLATFORM ACTION');
50
35
  await ensureActions();
51
36
  actionPath(platform, action);
52
37
  const config = loadConfig(args);
53
- const mode = validateMode(platform, action, args, config);
38
+ if (arg(args,'--mode') !== undefined) throw Error('--mode has been removed; use --session-id for direct execution or omit for a registered Queue');
54
39
  const sid = arg(args, '--session-id');
55
40
  if (sid) await requireCliSession(sid);
56
41
  const auto = has(args, '--auto-session');
57
42
  validateConfig(platform, action, config);
58
43
  if (sid && auto) throw Error('--session-id and --auto-session are mutually exclusive');
59
- if (platform === 'chatgpt' && action === 'new-turn' && mode === 'async') {
60
- if (sid || auto) throw Error('async new-turn cannot use browser session options');
61
- if (!config.thread_id || (!config.message && !config.file?.length)) throw Error('thread_id and message or file required');
62
- if (config.file !== undefined && (!Array.isArray(config.file) || config.file.length > 4 || config.file.some(f => typeof f !== 'string' || !path.isAbsolute(f) || !fs.existsSync(f)))) throw Error('file must contain at most 4 existing absolute paths');
63
- if (typeof config.mergeable !== 'undefined' && typeof config.mergeable !== 'boolean') throw Error('mergeable must be a boolean');
64
- const receipt = await request({op:'chatgpt-new-turn-enqueue', config: {...config, idempotency_key: config.idempotency_key || randomUUID(), mode}});
65
- if (!receipt.ok || !receipt.queue_id || receipt.thread_id !== String(config.thread_id)) throw Error('ChatGPT queue returned an invalid acceptance receipt');
66
- const project = config.project_id || null;
67
- const prefix = project ? `/g/${encodeURIComponent(project)}` : '';
68
- return {
69
- platform, action, session_mode: 'durable_queue', self_heal_capable: false,
70
- result: {ok:true, status:'submitted', mode:'new-turn', project_id:project,
71
- thread_id:String(config.thread_id), thread_url:`https://chatgpt.com${prefix}/c/${encodeURIComponent(config.thread_id)}`,
72
- verified_by:'durable-queue', user_message_id:null, queue_id: receipt.queue_id, state:receipt.state},
73
- };
44
+ const registeredQueue=await queueForAction(platform,action);
45
+ if (registeredQueue && !sid && !auto) {
46
+ const receipt=await request({op:'queue-enqueue',platform,queue:registeredQueue,
47
+ config:{...config,idempotency_key:config.idempotency_key||randomUUID(),mergeable:config.mergeable??false}});
48
+ if (!receipt.ok || !receipt.queue_id) throw Error('queue returned an invalid acceptance receipt');
49
+ return {platform,action,session_mode:'durable_queue',self_heal_capable:false,
50
+ result:{ok:true,status:'queued',queue_id:receipt.queue_id,
51
+ group:receipt.group,state:receipt.state,queue:registeredQueue}};
74
52
  }
75
- if (mode === 'sync' && (!sid || auto)) throw Error('sync new-turn requires a caller-owned --session-id');
76
53
  if (!sid && !auto) throw Error('platform run requires --session-id; use --auto-session only for one-shot actions');
77
- return request({op:'platform-run', platform, action, config: {...config, ...(mode ? {mode} : {})},
54
+ return request({op:'platform-run', platform, action, config,
78
55
  session_id:sid, auto_session:auto, url:arg(args, '--url'), workspace:CLI_WORKSPACE});
79
56
  }
80
57
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "WebHelm",
4
- "version": "1.0.48",
4
+ "version": "1.0.49",
5
5
  "description": "Own named Chrome tab-group workspaces and lazy reusable tab pools for browser agents.",
6
6
  "permissions": [
7
7
  "storage",
@@ -55,10 +55,10 @@ export async function setStoredSite(chromeApi, url, enabled) {
55
55
  return {id:origin,enabled:Boolean(enabled)};
56
56
  }
57
57
 
58
- const priority = {UNCERTAIN:0,BLOCKED:1,SENDING:2,CHECKING:2,WAITING:3,QUEUED:4};
58
+ const priority = {FAILED:0,SENDING:1,CHECKING:1,WAITING:2,QUEUED:3};
59
59
  function threadKey(item) {
60
- // Old queue adapters might not identify threads; don't merge unrelated IDs.
61
- return `${item.platform||'Queue'}\u0000${item.thread_id||item.id}`;
60
+ // Queue groups are provided by registered Platform Policies.
61
+ return `${item.platform||'Queue'}\u0000${item.group||item.id}`;
62
62
  }
63
63
 
64
64
  export function compactQueue(items, {expanded=false,maxHeads=8}={}) {
@@ -75,10 +75,9 @@ export function compactQueue(items, {expanded=false,maxHeads=8}={}) {
75
75
  const visible=expanded ? heads.flatMap(x=>x.items) : heads.slice(0,Math.max(1,maxHeads)).map(x=>x.head);
76
76
  const headFor=new Map(heads.flatMap(x=>x.items.map(item=>[item.id,x.head])));
77
77
  const behind=new Map(heads.map(x=>[x.head.id,x.count-1]));
78
- const uncertain=all.filter(x=>x.state==='UNCERTAIN').length;
79
- const blocked=all.filter(x=>x.state==='BLOCKED').length;
78
+ const failed=all.filter(x=>x.state==='FAILED').length;
80
79
  return {visible,total:all.length,threads:threads.size,behind,headFor,
81
- hidden:all.length-visible.length,uncertain,blocked};
80
+ hidden:all.length-visible.length,failed};
82
81
  }
83
82
 
84
83
  // Statuses describe what the user can do, not internal retry counters.
@@ -87,19 +86,17 @@ export function queueStatusText(item,{head=item,remaining=0}={}) {
87
86
  const state=String(item.state||'QUEUED').toUpperCase();
88
87
  const following=head.id!==item.id;
89
88
  let message;
90
- if(following && ['UNCERTAIN','BLOCKED'].includes(head.state))
91
- message=head.state==='UNCERTAIN' ? 'Waiting — previous send unconfirmed' : 'Waiting — previous message blocked';
89
+ if(following && head.state==='FAILED') message='Queued to send — previous attempt failed';
92
90
  else if(following) message='Waiting behind earlier message';
93
91
  else message=({
94
- UNCERTAIN:'Send unconfirmed — open thread to check',
95
- BLOCKED:'Blocked — needs attention',
92
+ FAILED:'Action failed — not retried',
96
93
  SENDING:'Sending',
97
94
  CHECKING:'Checking delivery',
98
95
  WAITING:'Waiting to send',
99
96
  QUEUED:'Queued to send',
100
97
  })[state]||state.toLowerCase();
101
98
  if(!following && remaining>0)
102
- message+=' · '+remaining+' later message'+(remaining===1?'':'s')+' waiting';
99
+ message+=' · '+remaining+' later message'+(remaining===1?'':'s')+(state==='FAILED'?' queued':' waiting');
103
100
  return message;
104
101
  }
105
102
 
@@ -52,7 +52,7 @@
52
52
  .queue-row { display:flex; align-items:center; gap:5px; padding:2px 0 2px 9px; }
53
53
  .queue-info { min-width:0; flex:1; display:flex; gap:4px; align-items:baseline; overflow:hidden; }
54
54
  .queue-meta { flex-shrink:0; white-space:nowrap; color:light-dark(var(--muted),#acb8c9); font-size:9px; }
55
- .queue-unconfirmed .queue-title { color:light-dark(var(--warning),#f7a4ad); }
55
+ .queue-failed .queue-title { color:light-dark(var(--warning),#f7a4ad); }
56
56
  .queue-row button.queue-remove { flex:0 0 20px; width:20px; height:20px; padding:0; border:0; background:transparent; color:light-dark(var(--muted),#acb8c9); font-size:16px; font-weight:400; line-height:18px; }
57
57
  button.tab-title { flex:1; min-width:0; width:100%; padding:0; border:0; border-radius:2px; background:transparent; color:inherit; text-align:left; font-size:12px; font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; cursor:pointer; }
58
58
  .queue-title { flex:1; min-width:0; font-size:10px; font-weight:400; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
@@ -158,7 +158,7 @@ function renderWorkspaces(workspaces, busy, connected) {
158
158
 
159
159
  function renderQueue(items, busy, connected) {
160
160
  const signature=JSON.stringify({
161
- items:items.map(item=>[item.id,item.platform,item.thread_id,item.title,item.url,item.state,item.attempts,item.created_at]),
161
+ items:items.map(item=>[item.id,item.platform,item.group,item.title,item.url,item.state,item.attempts,item.created_at]),
162
162
  busy,connected,
163
163
  });
164
164
  if(signature===lastQueueSignature)return;
@@ -168,7 +168,7 @@ function renderQueue(items, busy, connected) {
168
168
  const grouped=new Map();
169
169
  for(const item of items) {
170
170
  const platform=String(item.platform||'Queue');
171
- const threadId=String(item.thread_id||item.id);
171
+ const threadId=String(item.group||item.id);
172
172
  if(!grouped.has(platform))grouped.set(platform,new Map());
173
173
  const threads=grouped.get(platform);
174
174
  if(!threads.has(threadId))threads.set(threadId,[]);
@@ -228,7 +228,6 @@ function renderQueue(items, busy, connected) {
228
228
  const meta=document.createElement('span');meta.className='queue-meta';
229
229
  const remove=actionButton('×',false,async()=>{
230
230
  try{
231
- if(row.dataset.state==='UNCERTAIN' && !confirm('This send is unconfirmed. It may already have reached ChatGPT. Removing it may unblock later messages. Remove?'))return;
232
231
  const result=await rpc('workspace.control.queueCancel',{queueId:item.id});
233
232
  if(!result.id)throw Error('Missing queue request ID');
234
233
  el('message').textContent='Waiting for WebHelm daemon…';
@@ -239,15 +238,16 @@ function renderQueue(items, busy, connected) {
239
238
  }
240
239
  const title=row.querySelector('.queue-title');
241
240
  title.textContent=item.title||platform+' message';
242
- title.title=(item.title||platform+' message')+(item.state==='UNCERTAIN'?' — Send not confirmed; check thread before removing.':'');
241
+ title.title=(item.title||platform+' message')+
242
+ (item.state==='FAILED'?' — Action failed; no automatic retry.':'');
243
243
  row.dataset.queueId=item.id;
244
244
  row.dataset.state=item.state;
245
- row.classList.toggle('queue-unconfirmed',item.state==='UNCERTAIN');
245
+ row.classList.toggle('queue-failed',item.state==='FAILED');
246
246
  const elapsed=formatQueueElapsed(item.created_at,queueOpenedAtSeconds);
247
247
  const attempts=Math.max(0,Number(item.attempts)||0);
248
- row.querySelector('.queue-meta').textContent='('+(elapsed??'–')+'/'+attempts+')';
248
+ row.querySelector('.queue-meta').textContent=(item.state==='FAILED'?'FAILED ':'')+'('+(elapsed??'–')+'/'+attempts+')';
249
249
  const remove=row.querySelector('.queue-remove');
250
- const cancellable=['QUEUED','WAITING','BLOCKED','UNCERTAIN'].includes(item.state);
250
+ const cancellable=['QUEUED','WAITING'].includes(item.state);
251
251
  remove.disabled=!cancellable||busy||!connected;
252
252
  remove.title=cancellable?'Remove '+title.textContent+' from queue':'Cannot remove a running or completed submission';
253
253
  remove.setAttribute('aria-label',remove.title);
@@ -8,7 +8,7 @@ import crypto from 'node:crypto';
8
8
  import { fileURLToPath, pathToFileURL } from 'node:url';
9
9
  import { invokePlatformAction } from './platforms.mjs';
10
10
  import {createSiteKeepaliveScheduler} from './site-keepalive.mjs';
11
- import { ChatGPTQueue } from './chatgpt/chatgpt-queue.mjs';
11
+ import { PlatformQueueRegistry } from './queue-registry.mjs';
12
12
  import { idleUrlFromIdentity, sameIdleUrl, staleSession, withinDeadline, SessionDeadlineError } from './session-lifecycle.mjs';
13
13
  import { stopMatchingSessions } from './session-control.mjs';
14
14
  import { ensureManagedChrome } from './chrome.mjs';
@@ -35,25 +35,22 @@ function ownedLeaseTabIds() {
35
35
  }
36
36
  const pending = new Map();
37
37
  let socket, nextId = 1, browserWs, connected = false, reconnecting = false, shuttingDown = false;
38
- let chatgptQueue, managedChrome;
38
+ let queueRegistry, queueRegistryInit, managedChrome;
39
39
  let upgradePending=false, upgradeTimeout=null, activeRequests=0, pendingSessionStarts=0;
40
40
  function releaseUpgrade() {
41
41
  clearTimeout(upgradeTimeout); upgradeTimeout=null;
42
42
  if(!upgradePending)return;
43
43
  upgradePending=false;
44
- if(chatgptQueue && process.env.WEBHELM_CHATGPT_QUEUE_PAUSED!=='1'){
45
- chatgptQueue.started=false;
46
- chatgptQueue.start();
47
- }
44
+ if(queueRegistry && process.env.WEBHELM_QUEUE_PAUSED!=='1')queueRegistry.setPaused(false);
48
45
  }
49
46
  async function prepareUpgrade() {
50
47
  if(upgradePending)return {ok:true,deferred:true,reason:'already_preparing'};
51
48
  // The test and gate run within one event-loop turn, before any awaited work.
52
49
  if(activeRequests!==1 || sessions.size || pendingSessionStarts || pendingLeaseTabIds.size ||
53
- controlPollActive || getChatGPTQueue().active.size)
50
+ controlPollActive || (queueRegistry?.activeCount()||0))
54
51
  return {ok:true,deferred:true,reason:'daemon_busy',session_count:sessions.size};
55
52
  upgradePending=true;
56
- await chatgptQueue.stopScheduler(); // No active worker may cross this gate.
53
+ if(queueRegistry)await queueRegistry.stopScheduler(); // No worker may cross this gate.
57
54
  upgradeTimeout=setTimeout(releaseUpgrade,60000);
58
55
  upgradeTimeout.unref?.();
59
56
  return {ok:true,ready:true,pid:process.pid,version:PACKAGE_VERSION};
@@ -620,19 +617,22 @@ async function workspaceOp(req) {
620
617
  return extensionCall(null,'workspace.delete',{name:req.name,force:Boolean(req.force)});
621
618
  throw Error(`unknown workspace operation: ${req.op}`);
622
619
  }
623
- function getChatGPTQueue() {
624
- if (chatgptQueue) return chatgptQueue;
625
- chatgptQueue = new ChatGPTQueue({
626
- persistenceRoot: RUNTIME,
627
- startSession: ({url}) => createSession({url}),
628
- execSession: (session_id, code) => execute({session_id, code}),
629
- stopSession,
630
- logger: entry => console.error(JSON.stringify({component:'chatgpt-queue',...entry})),
631
- });
632
- // Keep the durable queue intact during a cutover smoke check. A paused
633
- // daemon accepts queue writes but never starts its dispatcher.
634
- if(process.env.WEBHELM_CHATGPT_QUEUE_PAUSED!=='1')chatgptQueue.start();
635
- return chatgptQueue;
620
+ async function getQueueRegistry() {
621
+ if(queueRegistry) return queueRegistry;
622
+ if(!queueRegistryInit){
623
+ const instance=new PlatformQueueRegistry({
624
+ persistenceRoot:RUNTIME,
625
+ startSession:({url,workspace})=>createSession({url,workspace}),
626
+ stopSession,
627
+ runAction:runPlatform,
628
+ paused:process.env.WEBHELM_QUEUE_PAUSED==='1',
629
+ logger:entry=>console.error(JSON.stringify({component:'queue-registry',...entry})),
630
+ });
631
+ queueRegistryInit=instance.start().then(()=>{queueRegistry=instance;return instance;}).catch(error=>{
632
+ queueRegistryInit=null;throw error;
633
+ });
634
+ }
635
+ return queueRegistryInit;
636
636
  }
637
637
 
638
638
  async function workspaceCapacity(req={}) {
@@ -668,13 +668,13 @@ async function pollExtensionControl() {
668
668
  if (controlPollActive || shuttingDown) return;
669
669
  controlPollActive = true;
670
670
  try {
671
- const pendingAction = await extensionCall(null,'workspace.control.poll',{sessions:visibleSessions(),queue:getChatGPTQueue().list().items});
671
+ const pendingAction = await extensionCall(null,'workspace.control.poll',{sessions:visibleSessions(),queue:(await getQueueRegistry()).list().items});
672
672
  if (!pendingAction) return;
673
673
  const {id,action,sessionId} = pendingAction;
674
674
  // Keep the status panel fresh while a lengthy Session stop waits for
675
675
  // browser navigation or an in-flight task.
676
676
  const controlHeartbeat=setInterval(()=>{
677
- extensionCall(null,'workspace.control.heartbeat',{sessions:visibleSessions(),queue:getChatGPTQueue().list().items})
677
+ extensionCall(null,'workspace.control.heartbeat',{sessions:visibleSessions(),queue:queueRegistry?.list().items||[]})
678
678
  .catch(error=>console.warn(`WebHelm control heartbeat: ${error.message}`));
679
679
  },3000);
680
680
  let response;
@@ -686,7 +686,7 @@ async function pollExtensionControl() {
686
686
  } else if (action === 'stop') {
687
687
  response = {ok:true,stopped:await stopSession(sessionId)};
688
688
  } else if (action === 'queue-cancel') {
689
- response = getChatGPTQueue().cancel(pendingAction.queueId);
689
+ response = (await getQueueRegistry()).cancel(pendingAction.queueId);
690
690
  } else {
691
691
  throw Error('Unknown extension control action');
692
692
  }
@@ -696,7 +696,7 @@ async function pollExtensionControl() {
696
696
  clearInterval(controlHeartbeat);
697
697
  }
698
698
  await extensionCall(null,'workspace.control.complete',{id,response});
699
- await extensionCall(null,'workspace.control.poll',{sessions:visibleSessions(),queue:getChatGPTQueue().list().items});
699
+ await extensionCall(null,'workspace.control.poll',{sessions:visibleSessions(),queue:queueRegistry?.list().items||[]});
700
700
  } catch(error) {
701
701
  console.warn(`WebHelm extension control sync failed: ${error.message}`);
702
702
  } finally {
@@ -753,10 +753,10 @@ async function runPlatform(req) {
753
753
  cleanup=auto ? await stopSession(sid).catch(e=>({release_error:e.message})) : {caller_owned_session:true};
754
754
  }
755
755
  result.cleanup=cleanup;
756
- if (platform==='chatgpt' && action==='new-turn' && config.mode==='sync' && result.ok) {
757
- if (result.value?.status!=='submitted' || result.value?.thread_id!==String(config.thread_id) || !result.value?.verified_by) {
758
- result={ok:false,error:'synchronous ChatGPT new-turn did not return a verified submission receipt',cleanup};
759
- } else Object.assign(result,result.value);
756
+ // Action completion/receipt semantics belong to the Platform, not this runner.
757
+ if (result.ok && result.value && typeof result.value==='object' && !Array.isArray(result.value)) {
758
+ const {ok,cleanup,...fields}=result.value;
759
+ Object.assign(result,fields);
760
760
  }
761
761
  return {platform,action,workspace_supported:started.workspace_supported??null,
762
762
  session_mode:auto?'auto_session_no_self_heal':'caller_owned_self_heal_capable',
@@ -781,7 +781,7 @@ const siteKeepalive = createSiteKeepaliveScheduler({
781
781
 
782
782
  export async function handle(req){
783
783
  if(upgradePending && !['ping','upgrade-release','upgrade-commit',
784
- 'chatgpt-new-turn-enqueue','queue-list','queue-cancel'].includes(req.op))
784
+ 'queue-enqueue','queue-list','queue-cancel'].includes(req.op))
785
785
  throw Error('WebHelm Runtime upgrade in progress; retry request');
786
786
  switch(req.op){
787
787
  case'upgrade-prepare':return prepareUpgrade();
@@ -792,7 +792,7 @@ export async function handle(req){
792
792
  setTimeout(()=>process.kill(process.pid,'SIGTERM'),150).unref();
793
793
  return {ok:true,stopping:true,pid:process.pid};
794
794
  }
795
- 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-configure':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}`)}}
795
+ case'ping':return {ok:true,pid:process.pid,version:PACKAGE_VERSION,queue_paused:process.env.WEBHELM_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-configure':case'workspace-resize':case'workspace-delete':return workspaceOp(req);case'queue-enqueue':return (await getQueueRegistry()).enqueue(req);case'queue-list':return (await getQueueRegistry()).list();case'queue-cancel':return (await getQueueRegistry()).cancel(req.queue_id);case'platform-run':return runPlatform(req);default:throw Error(`unknown op: ${req.op}`)}}
796
796
  export function serve(conn) {
797
797
  let buffer = '', dispatched = false;
798
798
  conn.on('error',()=>{ /* A disconnected client must not crash the daemon. */ });
@@ -819,12 +819,12 @@ export function serve(conn) {
819
819
  });
820
820
  }
821
821
 
822
- 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();
822
+ 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();await getQueueRegistry();
823
823
  const controlTimer=setInterval(()=>pollExtensionControl(),3000);
824
824
  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));
825
825
  pollExtensionControl().catch(()=>{});
826
826
  siteKeepalive.tick().catch(()=>{});
827
- 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)}
827
+ const cleanup=async()=>{if(shuttingDown)return;shuttingDown=true;clearInterval(controlTimer);clearInterval(siteTimer);managedChromeGuard.stop();if(queueRegistry)await queueRegistry.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)}
828
828
  // IPC duration is independent of the daemon's JS/Action execution timeout.
829
829
  // A wedged daemon can no longer strand CLI processes indefinitely.
830
830
  export function ipcTimeoutMs(op) {