webhelm 1.0.41 → 1.0.43

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
@@ -33,7 +33,38 @@ npx --yes webhelm@latest session stop SESSION_ID
33
33
  # Long-running worker managers: session heartbeat SESSION_ID every 60 seconds
34
34
  ```
35
35
 
36
- Use `npx skills add lalalic/webhelm --skill webhelm` to install agent guidance. The Extension is bundled with the npm Runtime and staged by WebHelm Daemon at `~/.local/webhelm/extension`. The Skill lives **in this repo** at `skills/webhelm/SKILL.md`. No Chrome Web Store publication or manual Extension installation is required.
36
+ Use `npx skills add lalalic/webhelm --skill webhelm` to install agent guidance.
37
+ The Extension is bundled with the npm Runtime and staged by WebHelm Daemon at `~/.local/webhelm/extension`. The Skill lives **in this repo** at `skills/webhelm/SKILL.md`. No Chrome Web Store publication or manual Extension installation is required.
38
+
39
+ ### Automatic npm Runtime upgrades (macOS)
40
+
41
+ `webhelm setup` installs two independent LaunchAgents: the offline Chrome health
42
+ check (`com.lalalic.webhelm.keepalive`, every 30 seconds) and the npm Runtime
43
+ updater (`com.lalalic.webhelm.runtime-update`, every hour and at login).
44
+ The updater checks the npm registry and downloads new releases to a temporary
45
+ location without running npm lifecycle scripts. It validates that Runtime and
46
+ Extension versions match, stages an immutable copy under
47
+ `~/.local/share/webhelm/runtime-VERSION`, and uses the stable
48
+ `~/.local/share/webhelm/runtime-current` symlink for subsequent launches.
49
+ The scheduled job does not depend on the npx cache. For immediate checking use
50
+ `webhelm upgrade`; for a read-only daemon check use `webhelm status`.
51
+
52
+ **No active Session is interrupted.** Before cutover, the daemon atomically
53
+ checks that no Sessions, pending leases, IPC operations or queue workers are
54
+ running, then pauses new browser work. New queued ChatGPT turns remain durable
55
+ and are accepted during the short cutover. The updater switches the stable
56
+ Runtime pointer, waits for the idle daemon to stop gracefully, starts the
57
+ new daemon against the existing Chrome/profile/queue, and verifies its version.
58
+ A busy daemon returns `deferred` and retries on the next scheduled run. A failed
59
+ installation reverts the pointer and resumes the old queue. Unavailable npm or
60
+ unrecognized old daemon upgrade protocols fail closed rather than killing a
61
+ Session. The update log is at `~/.config/webhelm/runtime/auto-update.log`.
62
+
63
+ Neo Master uses `WEBHELM_SOURCE_MODE=1` and runs its linked Git checkout, not
64
+ a published npm package. Automatic npm updates are deliberately disabled
65
+ there; updating a development checkout is a separate, reviewed Git operation.
66
+ Existing npm installations need to run `webhelm setup` once after receiving
67
+ this release to register the updater LaunchAgent.
37
68
 
38
69
  ## WebHelm Chrome Extension control panel
39
70
 
@@ -41,7 +72,7 @@ The daemon-managed Chrome Extension is installed from the npm Runtime and does n
41
72
 
42
73
  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.
43
74
 
44
- 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. Do not manually remove active managed tabs.
75
+ 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.
45
76
 
46
77
  For a real browser integration check on macOS, run `node test/e2e/extension-control.e2e.mjs`; it creates a temporary isolated Chrome profile and daemon and does not touch the current production Sessions.
47
78
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webhelm",
3
- "version": "1.0.41",
3
+ "version": "1.0.43",
4
4
  "description": "Agent browser automation in a visible managed Chrome with persistent JavaScript sessions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,157 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import {execFileSync} from 'node:child_process';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {request} from './node-daemon.mjs';
7
+ import {activateRuntime,currentRuntimePath,installLoginGuard,installRuntimeUpdate,stageRuntimeForLoginGuard} from './login-guard.mjs';
8
+
9
+ const REGISTRY='https://registry.npmjs.org';
10
+ const SOURCE=fileURLToPath(new URL('../',import.meta.url));
11
+ const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
12
+
13
+ export function compareVersions(a,b) {
14
+ const parts=v=>{
15
+ if(typeof v!=='string'||!/^\d+\.\d+\.\d+$/.test(v))throw Error(`Invalid Runtime version: ${v}`);
16
+ return v.split('.').map(Number);
17
+ };
18
+ const x=parts(a),y=parts(b);
19
+ for(let i=0;i<3;i++)if(x[i]!==y[i])return Math.sign(x[i]-y[i]);
20
+ return 0;
21
+ }
22
+
23
+ export function npmLatest() {
24
+ const value=execFileSync('npm',['view','webhelm','version','--json',`--registry=${REGISTRY}`,'--fetch-retries=0','--fetch-timeout=8000'],
25
+ {encoding:'utf8',timeout:15000,stdio:['ignore','pipe','pipe']});
26
+ const version=JSON.parse(value);
27
+ compareVersions(version,version);
28
+ return version;
29
+ }
30
+
31
+ // npm installs into an isolated temporary prefix; lifecycle scripts never run.
32
+ // The existing offline staging contract (Runtime + yaml) remains unchanged.
33
+ export function downloadRuntime(version,{home=os.homedir()}={}) {
34
+ compareVersions(version,version);
35
+ const cached=path.join(home,'.local/share/webhelm',`runtime-${version}`);
36
+ try {
37
+ const pkg=JSON.parse(fs.readFileSync(path.join(cached,'package.json'),'utf8'));
38
+ const ext=JSON.parse(fs.readFileSync(path.join(cached,'runtime/extension/manifest.json'),'utf8'));
39
+ if(pkg.name==='webhelm' && pkg.version===version && ext.version===version &&
40
+ fs.existsSync(path.join(cached,'node_modules/yaml/package.json')) &&
41
+ fs.existsSync(path.join(cached,'runtime/auto-update.mjs')))
42
+ return {path:cached,version,updated:false};
43
+ }catch{}
44
+ const temp=fs.mkdtempSync(path.join(os.tmpdir(),'webhelm-npm-upgrade-'));
45
+ try {
46
+ execFileSync('npm',['install','--prefix',temp,'--no-save','--omit=dev','--ignore-scripts',
47
+ '--no-audit','--no-fund','--package-lock=false','--fetch-retries=0',
48
+ `--registry=${REGISTRY}`,`webhelm@${version}`],
49
+ {timeout:120000,stdio:['ignore','pipe','pipe']});
50
+ const source=path.join(temp,'node_modules/webhelm');
51
+ const manifest=JSON.parse(fs.readFileSync(path.join(source,'package.json'),'utf8'));
52
+ const extension=JSON.parse(fs.readFileSync(path.join(source,'runtime/extension/manifest.json'),'utf8'));
53
+ if(manifest.name!=='webhelm'||manifest.version!==version||extension.version!==version)
54
+ throw Error('npm Runtime/Extension version verification failed');
55
+ if(Object.keys(manifest.dependencies||{}).some(name=>name!=='yaml'))
56
+ throw Error('Runtime dependencies changed; offline staging requires a review');
57
+ return stageRuntimeForLoginGuard({home,source,yamlSource:path.join(temp,'node_modules/yaml')});
58
+ }finally{fs.rmSync(temp,{recursive:true,force:true});}
59
+ }
60
+
61
+ function acquireLock(home) {
62
+ const runtime=path.join(home,'.config/webhelm/runtime');
63
+ fs.mkdirSync(runtime,{recursive:true,mode:0o700});
64
+ const lock=path.join(runtime,'auto-upgrade.lock');
65
+ for(let i=0;i<2;i++){
66
+ try {
67
+ const fd=fs.openSync(lock,'wx',0o600);
68
+ fs.writeFileSync(fd,String(process.pid));fs.closeSync(fd);
69
+ return ()=>{if(fs.existsSync(lock)&&fs.readFileSync(lock,'utf8')===String(process.pid))fs.unlinkSync(lock);};
70
+ }catch(error){
71
+ if(error.code!=='EEXIST')throw error;
72
+ const owner=Number(fs.readFileSync(lock,'utf8'));
73
+ if(owner>0){try{process.kill(owner,0);return null;}catch(e){if(e.code==='EPERM')return null;}}
74
+ fs.unlinkSync(lock);
75
+ }
76
+ }
77
+ return null;
78
+ }
79
+
80
+ // Inject ports for isolated tests. Production never imports npm code or
81
+ // touches another Chrome profile to decide whether to upgrade.
82
+ export async function upgradeRuntime({home=os.homedir(),source=SOURCE,nodePath=process.execPath,
83
+ latest=npmLatest,download=downloadRuntime,ipc=req=>request(req,false),
84
+ installGuard=installLoginGuard,installPoller=installRuntimeUpdate,
85
+ activate=activateRuntime,verify=null,apply=true}={}) {
86
+ if(process.env.WEBHELM_SOURCE_MODE==='1')return {status:'source_checkout',upgraded:false};
87
+ const unlock=acquireLock(home);
88
+ if(!unlock)return {status:'already_running',upgraded:false};
89
+ let prepared=false,prior=null,switched=false,committed=false;
90
+ try {
91
+ const local=JSON.parse(fs.readFileSync(path.join(source,'package.json'),'utf8')).version;
92
+ const published=await latest();
93
+ const target=compareVersions(published,local)>0?published:local;
94
+ let daemon=null;
95
+ try{daemon=await ipc({op:'ping'});}catch{}
96
+ if(daemon?.version && compareVersions(daemon.version,target)>0)
97
+ return {status:'daemon_newer',upgraded:false,daemon_version:daemon.version,latest:published};
98
+ const current=currentRuntimePath(home);
99
+ const currentTarget=fs.existsSync(current)?fs.realpathSync(current):null;
100
+ const upToDate=daemon?.version===target && currentTarget &&
101
+ fs.existsSync(path.join(currentTarget,'package.json')) &&
102
+ JSON.parse(fs.readFileSync(path.join(currentTarget,'package.json'),'utf8')).version===target;
103
+ if(upToDate)return {status:'current',upgraded:false,version:target};
104
+ // Stage before requesting the daemon to drain; download may take time.
105
+ const staged=compareVersions(target,local)>0
106
+ ? await download(target,{home}) : stageRuntimeForLoginGuard({home,source});
107
+ if(daemon && compareVersions(daemon.version,target)<0){
108
+ let gate;
109
+ try{gate=await ipc({op:'upgrade-prepare'});}
110
+ catch(error){return {status:'deferred',upgraded:false,reason:'daemon_upgrade_protocol_unavailable',detail:error.message,latest:target};}
111
+ if(!gate?.ready)return {status:'deferred',upgraded:false,reason:gate?.reason||'daemon_busy',latest:target,session_count:gate?.session_count};
112
+ prepared=true;
113
+ }
114
+ prior=currentTarget;
115
+ activate(staged.path,{home});switched=true;
116
+ const cliPath=path.join(current,'bin/webhelm.mjs');
117
+ const guard=installGuard({home,cliPath,nodePath,apply});
118
+ const poller=installPoller({home,cliPath,nodePath,apply});
119
+ if(['staged_not_loaded','skipped'].includes(guard.status)||
120
+ ['staged_not_loaded','skipped'].includes(poller.status))throw Error('Runtime LaunchAgent activation failed');
121
+ if(prepared){
122
+ const result=await ipc({op:'upgrade-commit'});
123
+ if(!result?.stopping)throw Error('Daemon did not accept Runtime cutover');
124
+ prepared=false;committed=true;
125
+ // SIGTERM completes the daemon's lock/socket cleanup. Never kill Chrome.
126
+ for(let i=0;i<100;i++){
127
+ try{const ping=await ipc({op:'ping'});if(ping?.pid!==daemon.pid)break;}
128
+ catch{break;}
129
+ await sleep(100);
130
+ }
131
+ }
132
+ const run=verify||(()=>{
133
+ const result=execFileSync(nodePath,[cliPath,'status'],{encoding:'utf8',timeout:30000,stdio:['ignore','pipe','pipe']});
134
+ return JSON.parse(result.trim().split('\n').at(-1));
135
+ });
136
+ const state=await run();
137
+ if(state.version!==target)throw Error(`Cutover verification failed: ${state.version} !== ${target}`);
138
+ return {status:'upgraded',upgraded:true,from:daemon?.version||null,to:target,
139
+ daemon_pid:state.daemon?.pid||null,guard:guard.status,auto_update:poller.status};
140
+ }catch(error){
141
+ // Never point new clients at an old Runtime after a committed daemon
142
+ // cutover: the new daemon may already be serving requests.
143
+ if(switched && !committed){
144
+ try{
145
+ if(prior)activate(prior,{home});
146
+ else fs.unlinkSync(currentRuntimePath(home));
147
+ const cliPath=prior?path.join(currentRuntimePath(home),'bin/webhelm.mjs'):path.join(source,'bin/webhelm.mjs');
148
+ installGuard({home,cliPath,nodePath,apply});
149
+ installPoller({home,cliPath,nodePath,apply});
150
+ }catch(rollbackError){error.message+=`; rollback failed: ${rollbackError.message}`;}
151
+ }
152
+ throw error;
153
+ }finally{
154
+ if(prepared)await ipc({op:'upgrade-release'}).catch(()=>{});
155
+ unlock();
156
+ }
157
+ }
@@ -13,6 +13,7 @@ Commands:
13
13
  webhelm setup Set up managed Chrome and local Actions
14
14
  webhelm status Report browser and daemon status (JSON)
15
15
  webhelm ensure Check and recover managed Chrome health
16
+ webhelm upgrade Check npm and safely upgrade the Runtime
16
17
  webhelm capacity Report available browser capacity (JSON)
17
18
  webhelm session start [--url URL] Start a persistent browser Session
18
19
  webhelm session list List CLI-owned Sessions
@@ -55,6 +56,7 @@ Output: JSON with status, Actions checkout path, daemon and browser details.
55
56
 
56
57
  Example:
57
58
  webhelm setup`,
59
+ upgrade: `webhelm upgrade — update the npm Runtime when safely idle\n\nUsage:\n webhelm upgrade\n\nChecks npm once. Stages newer Runtime without executing install scripts.\nCutover waits until all Sessions and in-flight queue workers are idle;\notherwise reports deferred and retries on the next hourly LaunchAgent run.\nNever updates a source-mode checkout or restarts managed Chrome.\n\nOutput: JSON current, upgraded, deferred, or source_checkout.`,
58
60
  status: `webhelm status — inspect managed browser and daemon
59
61
 
60
62
  Usage:
package/runtime/cli.mjs CHANGED
@@ -7,7 +7,8 @@ import { randomUUID } from 'node:crypto';
7
7
  import { ensureDaemon, request, SOCKET } from './node-daemon.mjs';
8
8
  import { PLATFORMS, listPlatforms, platformProfile, actionPath, validateConfig } from './platforms.mjs';
9
9
  import { ACTIONS_DIR, ensureActions, syncActions, publishActions } from './actions-repo.mjs';
10
- import { installLoginGuard, stageRuntimeForLoginGuard } from './login-guard.mjs';
10
+ import { activateRuntime, currentRuntimePath, installLoginGuard, installRuntimeUpdate, stageRuntimeForLoginGuard } from './login-guard.mjs';
11
+ import { upgradeRuntime } from './auto-update.mjs';
11
12
  import { cliHelp } from './cli-help.mjs';
12
13
 
13
14
  const ROOT = path.dirname(fileURLToPath(import.meta.url));
@@ -108,12 +109,15 @@ async function main(args = process.argv.slice(2)) {
108
109
  const repo=await ensureActions();
109
110
  const chrome=await ensureDaemon();
110
111
  const sourceMode=process.env.WEBHELM_SOURCE_MODE==='1';
112
+ if(!sourceMode)activateRuntime(stageRuntimeForLoginGuard().path);
111
113
  const cliPath=sourceMode
112
114
  ? fileURLToPath(new URL('../bin/webhelm.mjs',import.meta.url))
113
- : path.join(stageRuntimeForLoginGuard().path,'bin/webhelm.mjs');
115
+ : path.join(currentRuntimePath(),'bin/webhelm.mjs');
114
116
  const login_guard=installLoginGuard({cliPath,nodePath:process.execPath,sourceMode});
115
- return emit({status:'ready',...repo,daemon_pid:chrome.pid,managed_chrome:chrome.managed_chrome,login_guard});
117
+ const auto_update=installRuntimeUpdate({cliPath,nodePath:process.execPath,sourceMode});
118
+ return emit({status:'ready',...repo,daemon_pid:chrome.pid,managed_chrome:chrome.managed_chrome,login_guard,auto_update});
116
119
  }
120
+ if (group === 'upgrade') return emit(await upgradeRuntime());
117
121
  if (group === 'ensure') {
118
122
  try { return emit(await request({op:'guard-check'})); }
119
123
  catch(error) {
@@ -130,7 +134,12 @@ async function main(args = process.argv.slice(2)) {
130
134
  }
131
135
  if (group === 'status') {
132
136
  const daemon = await ensureDaemon();
133
- return emit({version:daemon.version, platform_dir:PLATFORMS, root:ROOT,
137
+ const link=currentRuntimePath();
138
+ let installed_version=null;
139
+ try{installed_version=JSON.parse(fs.readFileSync(path.join(link,'package.json'),'utf8')).version;}catch{}
140
+ const auto_update_installed=fs.existsSync(path.join(os.homedir(),'Library/LaunchAgents/com.lalalic.webhelm.runtime-update.plist'));
141
+ return emit({version:daemon.version, installed_version, auto_update_installed,
142
+ source_mode:process.env.WEBHELM_SOURCE_MODE==='1',platform_dir:PLATFORMS, root:ROOT,
134
143
  cli:fileURLToPath(import.meta.url),
135
144
  admin_helper:process.env.WEBHELM_ADMIN_HELPER || (fs.existsSync(path.join(os.homedir(),'.agents/skills/webhelm/scripts/admin.mjs')) ? path.join(os.homedir(),'.agents/skills/webhelm/scripts/admin.mjs') : path.join(ROOT,'admin.mjs')),
136
145
  managed_chrome:daemon.managed_chrome, chrome_guard:daemon.chrome_guard,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "WebHelm",
4
- "version": "1.0.41",
4
+ "version": "1.0.43",
5
5
  "description": "Own named Chrome tab-group workspaces and lazy reusable tab pools for browser agents.",
6
6
  "permissions": [
7
7
  "storage",
@@ -479,24 +479,58 @@ export class WorkspaceManager {
479
479
  return await this.inheritWorkspaceForCreatedTab(tab);
480
480
  }
481
481
 
482
+ // A group membership or an old "marker" URL is not a free lease. The
483
+ // actual extension idle page must be visible, with no navigation pending.
484
+ isIdleWorkspaceTab(name, tab) {
485
+ const meta = this.parseManagedUrl(this.tabUrl(tab));
486
+ return meta?.workspace === name && meta.role === "idle" &&
487
+ !this.inFlightTabIds.has(tab.id) && !tab.pendingUrl &&
488
+ tab.status !== "loading";
489
+ }
490
+
482
491
  classify(name, tabs) {
483
- const idle = [];
484
- const leased = [];
492
+ const idle = [], leased = [];
485
493
  for (const tab of tabs) {
486
- const meta = this.parseManagedUrl(tab.url || "");
487
- if (meta?.workspace === name && ["idle", "marker"].includes(meta.role)) idle.push(tab);
488
- else leased.push(tab);
494
+ (this.isIdleWorkspaceTab(name, tab) ? idle : leased).push(tab);
489
495
  }
490
496
  return { idle, leased };
491
497
  }
492
498
 
499
+ async occupiedSessionTabIds(excludedTabIds = []) {
500
+ const ids = new Set(excludedTabIds.map(Number).filter(Number.isInteger));
501
+ // The daemon supplies the current leases with each allocation RPC; its
502
+ // live Session table is authoritative even if Chrome still shows idle.
503
+ // Include the extension control snapshot as an additional safety fence.
504
+ const sessions = await this.getDaemonSessions();
505
+ if (Array.isArray(sessions)) {
506
+ for (const session of sessions) {
507
+ for (const id of [session.tabId, ...(session.tabIds || [])]) {
508
+ if (Number.isInteger(Number(id)) && id !== null) ids.add(Number(id));
509
+ }
510
+ }
511
+ }
512
+ return ids;
513
+ }
514
+
515
+ async waitForIdentityTab(tabId, workspace, timeoutMs = 3000) {
516
+ const deadline = Date.now() + timeoutMs;
517
+ for (;;) {
518
+ const tab = await this.chrome.tabs.get(tabId);
519
+ const meta = this.parseManagedUrl(this.tabUrl(tab));
520
+ if (meta?.workspace === workspace && meta.role === "lease" &&
521
+ meta.tabId === String(tabId) && !tab.pendingUrl) return tab;
522
+ if (Date.now() >= deadline)
523
+ throw new Error(`Timed out waiting for workspace ${workspace} lease identity ${tabId}`);
524
+ await new Promise(resolve => setTimeout(resolve, 25));
525
+ }
526
+ }
527
+
493
528
  async waitForIdleTab(tabId, workspace, timeoutMs = 3000) {
494
529
  const deadline = Date.now() + timeoutMs;
495
530
  for (;;) {
496
531
  const tabs = await this.chrome.tabs.query({});
497
532
  const tab = tabs.find((candidate) => candidate.id === tabId);
498
- const meta = this.parseManagedUrl(tab?.url || "");
499
- if (tab && meta?.workspace === workspace && meta.role === "idle") return tab;
533
+ if (tab && this.isIdleWorkspaceTab(workspace, tab)) return tab;
500
534
  if (Date.now() >= deadline) {
501
535
  throw new Error(`Timed out waiting for workspace ${workspace} idle tab ${tabId}`);
502
536
  }
@@ -673,7 +707,7 @@ export class WorkspaceManager {
673
707
  return await this.ensureWorkspace(normalizedName, wanted);
674
708
  }
675
709
 
676
- async acquireIdentity(name) {
710
+ async acquireIdentity(name, excludedTabIds = []) {
677
711
  const normalizedName = normalizeWorkspaceName(name);
678
712
  return await this.workspaceLock(normalizedName).run(async () => {
679
713
  // Leasing may allocate a Tab inside an existing Workspace, but must never
@@ -687,11 +721,15 @@ export class WorkspaceManager {
687
721
  await this.recoverOrphanedLeases(normalizedName);
688
722
  const tabs = await this.groupTabs(ready.groupId);
689
723
  const { idle, leased } = this.classify(normalizedName, tabs);
690
- if (!idle.length && leased.length >= ready.poolSize) {
724
+ const occupied = await this.occupiedSessionTabIds(excludedTabIds);
725
+ const free = idle.filter(tab => !occupied.has(tab.id));
726
+ // A Session-owned tab that temporarily displays role=idle still occupies
727
+ // pool capacity and must never be recycled into a second Session.
728
+ if (!free.length && leased.length + (idle.length - free.length) >= ready.poolSize) {
691
729
  throw new Error(`Workspace ${normalizedName} pool is exhausted at size ${ready.poolSize}`);
692
730
  }
693
731
 
694
- let tab = idle[0];
732
+ let tab = free[0];
695
733
  if (!tab) {
696
734
  tab = await this.chrome.tabs.create({
697
735
  url: this.idleUrl(normalizedName),
@@ -707,9 +745,13 @@ export class WorkspaceManager {
707
745
  const identityTitle = this.identityTitle(tab.id);
708
746
  const identityUrl = this.identityUrl(normalizedName, tab.id);
709
747
  let updated;
710
- try { updated = await this.chrome.tabs.update(tab.id, { url: identityUrl, active: false }); }
711
- finally { this.inFlightTabIds.delete(tab.id); }
712
- await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: true });
748
+ try {
749
+ await this.chrome.tabs.update(tab.id, { url: identityUrl, active: false });
750
+ // Do not release the allocation fence while Chrome still exposes the
751
+ // old idle URL. An overlapping allocation must not see this tab as free.
752
+ updated = await this.waitForIdentityTab(tab.id, normalizedName);
753
+ await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: true });
754
+ } finally { this.inFlightTabIds.delete(tab.id); }
713
755
  return {
714
756
  workspace: normalizedName,
715
757
  groupId: ready.groupId,
@@ -722,7 +764,7 @@ export class WorkspaceManager {
722
764
  });
723
765
  }
724
766
 
725
- async acquire(name, url) {
767
+ async acquire(name, url, excludedTabIds = []) {
726
768
  const normalizedName = normalizeWorkspaceName(name);
727
769
  const parsed = new URL(String(url || ""));
728
770
  if (!["http:", "https:", "chrome-extension:"].includes(parsed.protocol)) {
@@ -741,11 +783,15 @@ export class WorkspaceManager {
741
783
  await this.recoverOrphanedLeases(normalizedName);
742
784
  const tabs = await this.groupTabs(ready.groupId);
743
785
  const { idle, leased } = this.classify(normalizedName, tabs);
744
- if (!idle.length && leased.length >= ready.poolSize) {
786
+ const occupied = await this.occupiedSessionTabIds(excludedTabIds);
787
+ const free = idle.filter(tab => !occupied.has(tab.id));
788
+ // A Session-owned tab that temporarily displays role=idle still occupies
789
+ // pool capacity and must never be recycled into a second Session.
790
+ if (!free.length && leased.length + (idle.length - free.length) >= ready.poolSize) {
745
791
  throw new Error(`Workspace ${normalizedName} pool is exhausted at size ${ready.poolSize}`);
746
792
  }
747
793
 
748
- let tab = idle[0];
794
+ let tab = free[0];
749
795
  if (!tab) {
750
796
  tab = await this.chrome.tabs.create({
751
797
  url: this.idleUrl(normalizedName),
@@ -758,20 +804,24 @@ export class WorkspaceManager {
758
804
  tab = await this.waitForIdleTab(tab.id, normalizedName);
759
805
  }
760
806
  this.markOwned(tab.id);
761
- const updated = await this.chrome.tabs.update(tab.id, { url: parsed.href, active: false });
762
- await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: true });
763
- return {
764
- workspace: normalizedName,
765
- groupId: ready.groupId,
766
- tabId: updated.id,
767
- url: updated.url || parsed.href,
768
- active: Boolean(updated.active),
769
- };
807
+ this.inFlightTabIds.add(tab.id);
808
+ try {
809
+ const updated = await this.chrome.tabs.update(tab.id, { url: parsed.href, active: false });
810
+ await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: true });
811
+ return {
812
+ workspace: normalizedName,
813
+ groupId: ready.groupId,
814
+ tabId: updated.id,
815
+ url: updated.url || parsed.href,
816
+ active: Boolean(updated.active),
817
+ };
818
+ } finally { this.inFlightTabIds.delete(tab.id); }
770
819
  });
771
820
  }
772
821
 
773
822
  async release(name, tabId) {
774
823
  const normalizedName = normalizeWorkspaceName(name);
824
+ return this.workspaceLock(normalizedName).run(async () => {
775
825
  const ready = await this.ensureWorkspace(normalizedName);
776
826
  const wanted = Number(tabId);
777
827
  const tabs = await this.groupTabs(ready.groupId);
@@ -804,6 +854,7 @@ export class WorkspaceManager {
804
854
  }
805
855
  await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: true });
806
856
  return { workspace: normalizedName, tabId: wanted, released: true };
857
+ });
807
858
  }
808
859
 
809
860
  async releaseAll() {
@@ -861,8 +912,8 @@ export class WorkspaceManager {
861
912
  if (method === "workspace.status") return await this.status(args.name);
862
913
  if (method === "workspace.list") return await this.list();
863
914
  if (method === "workspace.migrateDefault") return await this.migrateDefaultWorkspace(Number(args.activeLegacySessions || 0));
864
- if (method === "workspace.acquire") return await this.acquire(args.name, args.url);
865
- if (method === "workspace.acquireIdentity") return await this.acquireIdentity(args.name);
915
+ if (method === "workspace.acquire") return await this.acquire(args.name, args.url, args.excludedTabIds || []);
916
+ if (method === "workspace.acquireIdentity") return await this.acquireIdentity(args.name, args.excludedTabIds || []);
866
917
  if (method === "workspace.release") return await this.release(args.name, args.tabId);
867
918
  if (method === "workspace.releaseAll") return await this.releaseAll();
868
919
  if (method === "workspace.resize") return await this.resize(args.name, args.poolSize);
@@ -5,6 +5,7 @@ import {execFileSync} from 'node:child_process';
5
5
  import {fileURLToPath} from 'node:url';
6
6
 
7
7
  const LABEL='com.lalalic.webhelm.keepalive';
8
+ const UPDATE_LABEL='com.lalalic.webhelm.runtime-update';
8
9
  // launchd must never depend on npm's removable npx cache, or on the Skill
9
10
  // launcher being present. Stage an immutable, package-backed runtime locally.
10
11
  export function stageRuntimeForLoginGuard({home=os.homedir(),source=fileURLToPath(new URL('../',import.meta.url)),yamlSource=null}={}){
@@ -79,3 +80,63 @@ export function installLoginGuard({home=os.homedir(), platform=process.platform,
79
80
  }catch(e){return {status:'staged_not_loaded',path:dest,label:LABEL,reason:e.message};}
80
81
  }
81
82
  }
83
+
84
+ // The npm poller is separate from the offline, 30-second Chrome health guard.
85
+ // It is pinned to a staged Runtime and never relies on a removable npx cache.
86
+ export function runtimeUpdateDefinition(home=os.homedir(),{cliPath,nodePath}={}) {
87
+ const cli=cliPath||path.join(home,'.local/bin/webhelm');
88
+ const node=nodePath||process.execPath;
89
+ const environment=[path.join(home,'.local/bin'),path.join(home,'.local/opt/node22/bin'),
90
+ '/opt/homebrew/bin','/usr/local/bin','/usr/bin','/bin'].join(':');
91
+ const log=path.join(home,'.config/webhelm/runtime/auto-update.log');
92
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${UPDATE_LABEL}</string>\n<key>ProgramArguments</key><array><string>${escapeXml(node)}</string><string>${escapeXml(cli)}</string><string>upgrade</string></array>\n<key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(environment)}</string><key>HOME</key><string>${escapeXml(home)}</string></dict>\n<key>RunAtLoad</key><true/>\n<key>StartInterval</key><integer>3600</integer>\n<key>StandardOutPath</key><string>${escapeXml(log)}</string>\n<key>StandardErrorPath</key><string>${escapeXml(log)}</string>\n</dict></plist>\n`;
93
+ }
94
+
95
+ export function installRuntimeUpdate({home=os.homedir(),platform=process.platform,apply=true,cliPath,nodePath,sourceMode=false}={}) {
96
+ if(sourceMode)return {status:'disabled',reason:'source_checkout',label:UPDATE_LABEL};
97
+ if(platform!=='darwin')return {status:'unsupported',label:UPDATE_LABEL};
98
+ const cli=cliPath||path.join(home,'.local/bin/webhelm');
99
+ if(!fs.existsSync(cli))return {status:'skipped',reason:'WebHelm runtime launcher missing',label:UPDATE_LABEL};
100
+ const dest=path.join(home,'Library/LaunchAgents',`${UPDATE_LABEL}.plist`);
101
+ const content=runtimeUpdateDefinition(home,{cliPath:cli,nodePath});
102
+ fs.mkdirSync(path.dirname(dest),{recursive:true});
103
+ fs.mkdirSync(path.join(home,'.config/webhelm/runtime'),{recursive:true,mode:0o700});
104
+ if(fs.existsSync(dest)&&!fs.readFileSync(dest,'utf8').includes(`<string>${UPDATE_LABEL}</string>`))
105
+ throw Error(`Refusing to replace unrelated LaunchAgent: ${dest}`);
106
+ const updated=!fs.existsSync(dest)||fs.readFileSync(dest,'utf8')!==content;
107
+ if(updated){const tmp=dest+`.${process.pid}.tmp`;fs.writeFileSync(tmp,content,{mode:0o600});fs.renameSync(tmp,dest);}
108
+ if(!apply)return {status:'staged',path:dest,updated,label:UPDATE_LABEL};
109
+ const service=`gui/${process.getuid()}/${UPDATE_LABEL}`;
110
+ try {
111
+ execFileSync('launchctl',['print',service],{timeout:5000,stdio:'ignore'});
112
+ if(updated){
113
+ execFileSync('launchctl',['bootout',service],{timeout:5000,stdio:'ignore'});
114
+ execFileSync('launchctl',['bootstrap',`gui/${process.getuid()}`,dest],{timeout:5000,stdio:'ignore'});
115
+ }
116
+ return {status:'active',path:dest,updated,label:UPDATE_LABEL};
117
+ }catch{
118
+ try{execFileSync('launchctl',['bootstrap',`gui/${process.getuid()}`,dest],{timeout:5000,stdio:'ignore'});
119
+ return {status:'active',path:dest,updated,label:UPDATE_LABEL};}
120
+ catch(error){return {status:'staged_not_loaded',path:dest,label:UPDATE_LABEL,reason:error.message};}
121
+ }
122
+ }
123
+
124
+ export function currentRuntimePath(home=os.homedir()) {
125
+ return path.join(home,'.local/share/webhelm/runtime-current');
126
+ }
127
+
128
+ // Atomic pointer swap: version directories remain immutable, so a running
129
+ // daemon or CLI can finish on its original files while future invocations
130
+ // start from the new version. Never replace a user-owned directory.
131
+ export function activateRuntime(stagedPath,{home=os.homedir()}={}) {
132
+ const current=currentRuntimePath(home);
133
+ if(!fs.existsSync(path.join(stagedPath,'bin/webhelm.mjs')))throw Error('Missing staged WebHelm Runtime CLI');
134
+ if(fs.existsSync(current)&&!fs.lstatSync(current).isSymbolicLink())
135
+ throw Error(`Refusing to replace unmanaged Runtime directory: ${current}`);
136
+ if(fs.existsSync(current)&&fs.realpathSync(current)===fs.realpathSync(stagedPath))return {path:current,updated:false};
137
+ fs.mkdirSync(path.dirname(current),{recursive:true,mode:0o700});
138
+ const temp=`${current}.${process.pid}.${Date.now()}.tmp`;
139
+ fs.symlinkSync(stagedPath,temp,'dir');
140
+ try{fs.renameSync(temp,current);}finally{if(fs.existsSync(temp))fs.unlinkSync(temp);}
141
+ return {path:current,updated:true};
142
+ }
@@ -26,9 +26,39 @@ const SOCKET = process.env.WEBHELM_SOCKET || path.join(RUNTIME, 'session-node.so
26
26
  const LOCK = process.env.WEBHELM_LOCK || path.join(RUNTIME, 'session-node.lock');
27
27
  const sessions = new Map();
28
28
  const targets = new Map();
29
+ // Pending Session creation is not yet in `sessions`, but its tab must already
30
+ // be reserved before the workspace lease mutex is released.
31
+ const pendingLeaseTabIds = new Set();
32
+ function ownedLeaseTabIds() {
33
+ return [...new Set([...pendingLeaseTabIds,
34
+ ...[...sessions.values()].flatMap(session => [...session.leasedTabs.values()])])];
35
+ }
29
36
  const pending = new Map();
30
37
  let socket, nextId = 1, browserWs, connected = false, reconnecting = false, shuttingDown = false;
31
38
  let chatgptQueue, managedChrome;
39
+ let upgradePending=false, upgradeTimeout=null, activeRequests=0, pendingSessionStarts=0;
40
+ function releaseUpgrade() {
41
+ clearTimeout(upgradeTimeout); upgradeTimeout=null;
42
+ if(!upgradePending)return;
43
+ upgradePending=false;
44
+ if(chatgptQueue && process.env.WEBHELM_CHATGPT_QUEUE_PAUSED!=='1'){
45
+ chatgptQueue.started=false;
46
+ chatgptQueue.start();
47
+ }
48
+ }
49
+ async function prepareUpgrade() {
50
+ if(upgradePending)return {ok:true,deferred:true,reason:'already_preparing'};
51
+ // The test and gate run within one event-loop turn, before any awaited work.
52
+ if(activeRequests!==1 || sessions.size || pendingSessionStarts || pendingLeaseTabIds.size ||
53
+ controlPollActive || getChatGPTQueue().active.size)
54
+ return {ok:true,deferred:true,reason:'daemon_busy',session_count:sessions.size};
55
+ upgradePending=true;
56
+ await chatgptQueue.stopScheduler(); // No active worker may cross this gate.
57
+ upgradeTimeout=setTimeout(releaseUpgrade,60000);
58
+ upgradeTimeout.unref?.();
59
+ return {ok:true,ready:true,pid:process.pid,version:PACKAGE_VERSION};
60
+ }
61
+
32
62
  let connectingBrowser=null;
33
63
  const delay = ms => new Promise(r => setTimeout(r, ms));
34
64
 
@@ -56,7 +86,9 @@ function leaseMutex(workspace) {
56
86
  async function acquireIdentityLease(session) {
57
87
  return leaseMutex(session.workspace).run(async()=>{
58
88
  await reconcileWorkspaceSessions(session.workspace);
59
- const lease=await extensionCall(session,'workspace.acquireIdentity',{name:session.workspace});
89
+ const lease=await extensionCall(session,'workspace.acquireIdentity',{
90
+ name:session.workspace,excludedTabIds:ownedLeaseTabIds(),
91
+ });
60
92
  const targetId=await targetForUrl(lease.identityUrl);
61
93
  if(!targetId){
62
94
  await extensionCall(session,'workspace.release',{name:session.workspace,tabId:lease.tabId}).catch(()=>{});
@@ -67,6 +99,7 @@ async function acquireIdentityLease(session) {
67
99
  throw Error('Workspace extension returned a target already owned by another Session');
68
100
  }
69
101
  lease.idleUrl ||= idleUrlFromIdentity(lease.identityUrl);
102
+ pendingLeaseTabIds.add(lease.tabId);
70
103
  return {lease,targetId};
71
104
  });
72
105
  }
@@ -188,9 +221,14 @@ function makeHelpers(s){
188
221
  let targetId,lease;
189
222
  if(s.workspaceSupported){
190
223
  ({lease,targetId}=await acquireIdentityLease(s));
191
- if(s.poisoned || s.closing){await extensionCall(s,'workspace.release',{name:s.workspace,tabId:lease.tabId});throw Error('Session execution expired');}
224
+ if(s.poisoned || s.closing){
225
+ try{await extensionCall(s,'workspace.release',{name:s.workspace,tabId:lease.tabId});}
226
+ finally{pendingLeaseTabIds.delete(lease.tabId);}
227
+ throw Error('Session execution expired');
228
+ }
192
229
  s.leasedTabs.set(targetId,lease.tabId);
193
230
  s.idleUrls.set(targetId,lease.idleUrl);
231
+ pendingLeaseTabIds.delete(lease.tabId);
194
232
  }else ({targetId}=await browser.send('Target.createTarget',{url:'about:blank'}));
195
233
  await attach(s,targetId);
196
234
  s.targetId=targetId;
@@ -378,6 +416,9 @@ async function extensionCallSerialized(_session,method,args={}) {
378
416
 
379
417
  function jsonSafe(value){try{JSON.stringify(value);return {value}}catch{return {value_repr:String(value)}}}
380
418
  async function createSession(req={}) {
419
+ if(upgradePending)throw Error('WebHelm Runtime is upgrading; retry Session start');
420
+ pendingSessionStarts++;
421
+ try {
381
422
  const browser=await connectBrowser();
382
423
  const sid=crypto.randomBytes(8).toString('hex');
383
424
  const s={session_id:sid, workspace:req.workspace||await defaultWorkspaceName(), targetId:null,
@@ -404,15 +445,18 @@ async function createSession(req={}) {
404
445
  s.namespace={...h,helpers:h,session_id:sid};
405
446
  s.context=vm.createContext(s.namespace);
406
447
  sessions.set(sid,s);
448
+ if(lease)pendingLeaseTabIds.delete(lease.tabId);
407
449
  return {session_id:sid,workspace:s.workspace,target_id:targetId,
408
450
  url:req.url||'about:blank',workspace_supported:!!lease};
409
451
  }catch(error){
410
452
  if(lease){
411
453
  try{await extensionCall(s,'workspace.release',{name:s.workspace,tabId:lease.tabId});}
412
454
  catch{if(targetId)await browser.send('Target.closeTarget',{targetId}).catch(()=>{});}
455
+ finally{pendingLeaseTabIds.delete(lease.tabId);}
413
456
  }else if(targetId)await browser.send('Target.closeTarget',{targetId}).catch(()=>{});
414
457
  throw error;
415
458
  }
459
+ } finally { pendingSessionStarts--; }
416
460
  }
417
461
 
418
462
  async function targetForUrl(url){for(let i=0;i<100;i++){const {targetInfos=[]}=await connectBrowser().then(b=>b.send('Target.getTargets'));const match=targetInfos.find(t=>t.type==='page'&&t.url===url);if(match)return match.targetId;await delay(50)}return null}
@@ -509,15 +553,12 @@ async function closeSessionOwned(s){
509
553
  }
510
554
 
511
555
  async function reconcileWorkspaceSessions(workspace){
512
- const browser=await connectBrowser();
513
556
  for(const s of [...sessions.values()]){
514
557
  if(s.workspace!==workspace||s.closing||s.inFlight>0||s.pendingEffects>0)continue;
515
- let alreadyIdle=false;
516
- for(const [tid,idleUrl] of s.idleUrls){
517
- try {if(sameIdleUrl(await targetUrl(browser,tid),idleUrl)){alreadyIdle=true;break;}}
518
- catch {alreadyIdle=true;break;} // Lost target means this Session is no longer valid.
519
- }
520
- if(!alreadyIdle&&!staleSession(s))continue;
558
+ // A fresh Session may still be on the WebHelm idle page during a Chrome
559
+ // navigation; the URL is NOT proof its target has been released. Never
560
+ // collect a fresh Session (even when its CDP target looks idle/missing).
561
+ if(!staleSession(s))continue;
521
562
  try {await closeSessionOwned(s);}
522
563
  catch(error){console.error(JSON.stringify({component:'session-gc',session_id:s.session_id,error:String(error)}));}
523
564
  }
@@ -726,7 +767,7 @@ const siteKeepalive = createSiteKeepaliveScheduler({
726
767
  listSites:() => extensionCall(null,'workspace.control.site.list'),
727
768
  report:result => extensionCall(null,'workspace.control.site.report',result),
728
769
  canRun:async() => {
729
- if (shuttingDown) return false; // Low priority: use idle browser capacity only.
770
+ if (shuttingDown || upgradePending) return false; // Low priority: use idle browser capacity only.
730
771
  const capacity=await workspaceCapacity();
731
772
  return Number.isInteger(capacity.available) && capacity.available > 0;
732
773
  },
@@ -738,7 +779,20 @@ const siteKeepalive = createSiteKeepaliveScheduler({
738
779
  },
739
780
  });
740
781
 
741
- 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-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}`)}}
782
+ export async function handle(req){
783
+ if(upgradePending && !['ping','upgrade-release','upgrade-commit',
784
+ 'chatgpt-new-turn-enqueue','queue-list','queue-cancel'].includes(req.op))
785
+ throw Error('WebHelm Runtime upgrade in progress; retry request');
786
+ switch(req.op){
787
+ case'upgrade-prepare':return prepareUpgrade();
788
+ case'upgrade-release':releaseUpgrade();return {ok:true,released:true};
789
+ case'upgrade-commit':{
790
+ if(!upgradePending)throw Error('Runtime upgrade has not been prepared');
791
+ clearTimeout(upgradeTimeout);upgradeTimeout=null;
792
+ setTimeout(()=>process.kill(process.pid,'SIGTERM'),150).unref();
793
+ return {ok:true,stopping:true,pid:process.pid};
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}`)}}
742
796
  export function serve(conn) {
743
797
  let buffer = '', dispatched = false;
744
798
  conn.on('error',()=>{ /* A disconnected client must not crash the daemon. */ });
@@ -755,12 +809,13 @@ export function serve(conn) {
755
809
  if (newline < 0 || dispatched) return;
756
810
  dispatched=true;
757
811
  const raw = buffer.slice(0, newline);
812
+ activeRequests++;
758
813
  try {
759
814
  const reply = await handle(JSON.parse(raw));
760
815
  if(!conn.destroyed)conn.end(JSON.stringify(reply) + '\n');
761
816
  } catch (error) {
762
817
  if(!conn.destroyed)conn.end(JSON.stringify({ error: `${error.name}: ${error.message}` }) + '\n');
763
- }
818
+ } finally { activeRequests--; }
764
819
  });
765
820
  }
766
821