webhelm 1.0.51 → 1.0.53

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
@@ -133,7 +133,7 @@ site-specific evidence; never infer login solely from HTTP success or page
133
133
  load. WebHelm schedules only opted-in platforms, using a temporary browser
134
134
  Session and an idle pool slot. On failure, the UI displays **Check failed**;
135
135
  non-opted-in sites display **No heartbeat action** and can still be opened for
136
- manual login. Failed/unknown checks retry no faster than five minutes. Neither
136
+ manual login. Only confirmed login schedules another heartbeat. Every other result pauses checks immediately; failure reasons are diagnostic only. Pause state survives restarts; after signing in, click the resume icon in Keep Alive Sites to request a fresh check. Failed releases retry cleanup of the original Session without allocating a new Tab. Neither
137
137
  heartbeat nor browser persistence guarantees that the service will extend its
138
138
  login lifetime. No automatic credential input or challenge bypass occurs.
139
139
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webhelm",
3
- "version": "1.0.51",
3
+ "version": "1.0.53",
4
4
  "description": "Agent browser automation in a visible managed Chrome with persistent JavaScript sessions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,6 +20,10 @@ Commands:
20
20
  webhelm session exec ID [--code-file F] Run JavaScript in a Session
21
21
  webhelm session heartbeat ID Keep a Session alive during idle waits
22
22
  webhelm session stop ID|--all Stop a Session or explicitly stop all CLI Sessions
23
+ webhelm design start --url URL Open reference site with native ChatGPT Split View
24
+ webhelm design attach ID Split an existing CLI Session
25
+ webhelm design status Show active Design Mode Sessions
26
+ webhelm design stop ID Unsplit; stop only Design-created Sessions
23
27
  webhelm platform list List installed website integrations
24
28
  webhelm platform profile NAME Inspect a site's supported fields
25
29
  webhelm platform source NAME ACTION Read the source of an installed Action
@@ -88,6 +92,69 @@ Output: JSON capacity information.
88
92
 
89
93
  Example:
90
94
  webhelm capacity`,
95
+ design: `webhelm design — share one native site with the active ChatGPT thread
96
+
97
+ Usage:
98
+ webhelm design <start|attach|status|stop> [options]
99
+
100
+ Start creates one managed WebHelm Session and pairs it with an existing
101
+ ChatGPT thread Tab in Chrome Split View; attach reuses an existing Session.
102
+ The Extension automatically tracks and protects the companion ChatGPT tab.
103
+ Sessions in Design Mode are heartbeat-renewed by the daemon.
104
+ Stopping Design Mode restores the original ChatGPT tab layout; a Session
105
+ created with design start is also stopped.
106
+
107
+ Examples:
108
+ webhelm design start --url https://mobbin.com/
109
+ webhelm design attach SESSION_ID
110
+ webhelm design status
111
+ webhelm design stop SESSION_ID`,
112
+ 'design start': `webhelm design start — open the selected design reference site and split with ChatGPT
113
+
114
+ Usage:
115
+ webhelm design start --url HTTPS_URL
116
+
117
+ The native reference URL is selected by the Agent using
118
+ skills/webhelm/references/design-mode.md. Requires an existing ChatGPT
119
+ conversation tab in WebHelm managed Chrome (Chrome 155+).
120
+ No screenshot, iframe aggregator, or duplicate ChatGPT tab is created.
121
+ If no suitable thread exists, the new Session is rolled back.
122
+
123
+ Example:
124
+ webhelm design start --url https://www.motionlex.online/`,
125
+ 'design attach': `webhelm design attach — enable Design Mode on an existing Session
126
+
127
+ Usage:
128
+ webhelm design attach SESSION_ID
129
+
130
+ Preserves Session identity and existing site state; opens native Split View.
131
+ Repeated calls are idempotent.
132
+
133
+ Example:
134
+ webhelm design attach SESSION_ID`,
135
+ 'design status': `webhelm design status — list shared Design Mode Sessions
136
+
137
+ Usage:
138
+ webhelm design status
139
+
140
+ Returns JSON with current session_id, original site URL (when known),
141
+ ownership, and heartbeat time. No browser navigation or Session creation.
142
+
143
+ Example:
144
+ webhelm design status`,
145
+ 'design stop': `webhelm design stop — end native Split View
146
+
147
+ Usage:
148
+ webhelm design stop SESSION_ID
149
+
150
+ Restores the companion ChatGPT Tab to its original window/group/index.
151
+ Only Sessions created with design start are also stopped; attached Sessions
152
+ return to ordinary Session lifecycle. Extension icon exit or manual Chrome
153
+ Unsplit applies the same ownership rule on the next daemon poll.
154
+ A Session stopped or garbage-collected independently also auto-unsplits.
155
+
156
+ Example:
157
+ webhelm design stop SESSION_ID`,
91
158
  session: `webhelm session — manage persistent JavaScript browser Sessions
92
159
 
93
160
  Usage:
@@ -305,7 +372,7 @@ Example:
305
372
  export const helpTopics = Object.freeze(Object.keys(sections).filter(Boolean));
306
373
  export function cliHelp(topics=[]) {
307
374
  const parts = topics.filter(Boolean);
308
- const key = parts.length>1 && ['session','platform'].includes(parts[0])
375
+ const key = parts.length>1 && ['session','platform','design'].includes(parts[0])
309
376
  ? parts.slice(0,2).join(' ') : (parts[0] || '');
310
377
  if (!Object.hasOwn(sections,key)) throw Error(`unknown help topic: ${parts.join(' ')}`);
311
378
  return sections[key];
package/runtime/cli.mjs CHANGED
@@ -74,7 +74,7 @@ async function requireCliSession(sessionId) {
74
74
  async function main(args = process.argv.slice(2)) {
75
75
  const [group, command] = args;
76
76
  if (!group || ['--help', '-h', 'help'].includes(group) || has(args, '--help') || has(args, '-h') ||
77
- ((group === 'session' || group === 'platform') && (!command || command === 'help'))) {
77
+ ((group === 'session' || group === 'platform' || group === 'design') && (!command || command === 'help'))) {
78
78
  const topics = group === 'help'
79
79
  ? args.slice(1).filter(item => !['--help', '-h'].includes(item))
80
80
  : ['--help', '-h'].includes(group) ? [] : args.filter(item => !['--help', '-h', 'help'].includes(item));
@@ -134,6 +134,23 @@ async function main(args = process.argv.slice(2)) {
134
134
  // reload an older daemon's Extension while its Sessions are still active.
135
135
  return emit(await request(payload));
136
136
  }
137
+ if (group === 'design') {
138
+ if (command === 'status') return emit(await request({op:'design-status'}));
139
+ if (command === 'start') {
140
+ const url=arg(args,'--url');
141
+ if (!url) throw Error('design start requires --url URL; select a native reference site');
142
+ return emit(await request({op:'design-start',url}));
143
+ }
144
+ if (command === 'attach') {
145
+ await requireCliSession(args[2]);
146
+ return emit(await request({op:'design-attach',session_id:args[2]}));
147
+ }
148
+ if (command === 'stop') {
149
+ await requireCliSession(args[2]);
150
+ return emit(await request({op:'design-stop',session_id:args[2]}));
151
+ }
152
+ throw Error('unknown design command: '+String(command||''));
153
+ }
137
154
  if (group === 'session') {
138
155
  if (command === 'start') return emit(await request({op:'start', workspace:CLI_WORKSPACE, url:arg(args,'--url')}));
139
156
  if (command === 'list') {
@@ -1,3 +1,5 @@
1
+ import {showSessionTab} from './workspace-summary.mjs';
2
+ import {activeChatThread} from './design-mode.mjs';
1
3
  import {siteOrigin, sitePage, setKeptSite, listKeptSites, sitesWithStatus, reportKeptSite} from "./site-registry.mjs";
2
4
  function validTabId(tabId) { return Number.isSafeInteger(tabId) && tabId > 0; }
3
5
  function validateQueueUrl(url) {
@@ -6,26 +8,55 @@ function validateQueueUrl(url) {
6
8
  return parsed.href;
7
9
  }
8
10
 
9
- export function createControlRpc({control, manager, summarizeWorkspaces, scheduleBadge, chromeApi=globalThis.chrome ?? control.chrome}) {
11
+ export function createControlRpc({control, manager, design=null, summarizeWorkspaces, scheduleBadge, chromeApi=globalThis.chrome ?? control.chrome}) {
10
12
  return async function controlRpc(method, args = {}) {
11
13
  switch (method) {
12
14
  case "workspace.control.status": {
15
+ if (design) await design.reconcile();
13
16
  const state = await control.status();
14
17
  const summary = summarizeWorkspaces((await manager.list()).workspaces, state.sessions);
15
18
  const workspaces = await Promise.all(summary.workspaces.map(async workspace => ({
16
19
  ...workspace,
17
- sessions: await Promise.all(workspace.sessions.map(async session => {
20
+ sessions: (await Promise.all(workspace.sessions.map(async session => {
18
21
  if (!validTabId(session.tabId)) return session;
19
22
  try {
20
23
  const tab = await chromeApi.tabs.get(session.tabId);
21
- return {...session, tab_title: tab.title || 'Untitled tab', tab_url:tab.url || ''};
24
+ return {...session, tab_title: tab.title || 'Untitled tab', tab_url:tab.url || '', designActive:design?.hasSession(session.session_id) || false};
22
25
  } catch { return {...session, tabId:null}; }
23
- })),
26
+ }))).filter(session => !validTabId(session.tabId) ||
27
+ showSessionTab(session.tab_url, chromeApi.runtime?.getURL?.('helm.html'))),
24
28
  })));
25
- return {...state,...summary,
29
+ const activeChat = await activeChatThread(chromeApi).catch(()=>null);
30
+ return {...state,...summary,canEnableDesign:Boolean(activeChat),
26
31
  workspaces:workspaces.filter(workspace => workspace.showInMenu !== false),
27
32
  keptSites:chromeApi.storage?.local ? await sitesWithStatus(chromeApi) : []};
28
33
  }
34
+ case "workspace.control.design.toggle": {
35
+ if (!design) throw Error("Design Mode unavailable");
36
+ return design.toggle(args.sessionId);
37
+ }
38
+ case "workspace.control.design.enable": {
39
+ if (!design) throw Error("Design Mode unavailable");
40
+ return design.enableSession(args.sessionId);
41
+ }
42
+ case "workspace.control.design.disable": {
43
+ if (!design) throw Error("Design Mode unavailable");
44
+ return design.closeSession(args.sessionId);
45
+ }
46
+ case "workspace.control.design.sessions": {
47
+ if (!design) return [];
48
+ await design.reconcile();
49
+ return design.activeSessionIds();
50
+ }
51
+ case "workspace.control.design.records": {
52
+ if (!design) return [];
53
+ await design.reconcile();
54
+ return design.allSessionIds();
55
+ }
56
+ case "workspace.control.design.closeSession": {
57
+ if (!design) return {active:false};
58
+ return design.closeSession(args.sessionId);
59
+ }
29
60
  case "workspace.control.activateTab": {
30
61
  const state = await control.status();
31
62
  if (!state.connected) throw Error('WebHelm daemon is not responding');
@@ -88,9 +119,14 @@ export function createControlRpc({control, manager, summarizeWorkspaces, schedul
88
119
  const opened = await chromeApi.tabs.create({url,active:true});
89
120
  return {ok:true,tabId:opened.id,opened:true};
90
121
  }
122
+ case "workspace.control.site.resume": {
123
+ const site = (await listKeptSites(chromeApi)).find(s => s.id === args.siteId);
124
+ if (!site) throw Error('Keep Alive site is no longer registered');
125
+ return setKeptSite(chromeApi,site.url,true);
126
+ }
91
127
  // Daemon-only control RPCs, unavailable to extension pages.
92
128
  case "workspace.control.site.list":
93
- return listKeptSites(chromeApi);
129
+ return sitesWithStatus(chromeApi);
94
130
  case "workspace.control.site.report":
95
131
  return reportKeptSite(chromeApi,args);
96
132
  case "workspace.control.requestStop":
@@ -0,0 +1,279 @@
1
+ // Optional, user-initiated Chrome Split View pairing for an existing WebHelm
2
+ // Session and the user's existing ChatGPT thread tab. Never adopt the chat tab
3
+ // as an agent Session, navigate it or close it.
4
+ const KEY = 'webhelm.design-mode.v1';
5
+
6
+ export function isChatThread(url) {
7
+ try {
8
+ const u = new URL(url);
9
+ return ['chatgpt.com', 'chat.openai.com'].includes(u.hostname) &&
10
+ /^\/(?:g\/[^/]+\/)?c\/[a-z0-9-]+\/?$/i.test(u.pathname);
11
+ } catch { return false; }
12
+ }
13
+
14
+ function validId(id) { return Number.isSafeInteger(id) && id >= 0; }
15
+ function isMissingTab(error) { return /No tab with id|Invalid tab ID|No window with id/i.test(String(error?.message || error)); }
16
+
17
+ // Only pair the user's currently active ChatGPT conversation, never guess
18
+ // among background or recently visited threads.
19
+ export async function activeChatThread(chromeApi) {
20
+ const window = await chromeApi.windows.getLastFocused({windowTypes:['normal']});
21
+ if (!window || !validId(window.id)) return null;
22
+ const tabs = await chromeApi.tabs.query({windowId:window.id,active:true});
23
+ return tabs.find(tab => isChatThread(tab.url)) || null;
24
+ }
25
+
26
+
27
+ export class DesignMode {
28
+ constructor(chromeApi, manager, control) {
29
+ this.chrome = chromeApi;
30
+ this.manager = manager;
31
+ this.control = control;
32
+ this.records = new Map();
33
+ this.serial = Promise.resolve();
34
+ this.ready = this.load();
35
+ }
36
+
37
+ async load() {
38
+ // storage.session is cleared when Chrome reloads an unpacked Extension.
39
+ // The original tab location must survive Extension reloads and updates.
40
+ const persisted = (await this.chrome.storage.local.get(KEY))[KEY];
41
+ const legacy = persisted === undefined
42
+ ? (await this.chrome.storage.session.get(KEY))[KEY] : undefined;
43
+ const saved = persisted ?? legacy ?? {};
44
+ for (const [id, value] of Object.entries(saved)) {
45
+ if (!value || !validId(value.chatTabId) || !validId(value.agentTabId)) continue;
46
+ this.records.set(id, value);
47
+ this.manager.designCompanionTabIds.add(value.chatTabId);
48
+ if (validId(value.groupId)) this.manager.designActiveGroupIds.add(value.groupId);
49
+ }
50
+ if (legacy !== undefined) await this.save();
51
+ }
52
+
53
+ async save() {
54
+ await this.chrome.storage.local.set({[KEY]:Object.fromEntries(this.records)});
55
+ }
56
+
57
+ hasSession(sessionId) { return this.records.has(sessionId); }
58
+ activeSessionIds() { return [...this.records].filter(([,r]) => r.state === 'active').map(([id]) => id); }
59
+ allSessionIds() { return [...this.records.keys()]; }
60
+
61
+ serialize(fn) {
62
+ const result = this.serial.then(fn);
63
+ this.serial = result.catch(() => {});
64
+ return result;
65
+ }
66
+
67
+ async toggle(sessionId) {
68
+ await this.ready;
69
+ return this.serialize(async () => {
70
+ await this.reconcileState();
71
+ return this.records.has(sessionId) ? this.disable(sessionId) : this.enable(sessionId);
72
+ });
73
+ }
74
+
75
+ async enableSession(sessionId) {
76
+ await this.ready;
77
+ return this.serialize(async () => {
78
+ await this.reconcileState();
79
+ const record=this.records.get(sessionId);
80
+ if(record) {
81
+ if(record.state!=='active') throw Error('Design Mode restore is pending; cannot enable');
82
+ return {active:true,sessionId,alreadyActive:true};
83
+ }
84
+ return this.enable(sessionId);
85
+ });
86
+ }
87
+
88
+ async enable(sessionId) {
89
+ if (typeof this.chrome.tabs.createSplit !== 'function' || typeof this.chrome.tabs.unsplit !== 'function')
90
+ throw Error('Design Mode requires Chrome 155+ Split View APIs');
91
+ const daemon = await this.control.status();
92
+ if (!daemon.connected) throw Error('WebHelm daemon is offline');
93
+ const session = daemon.sessions.find(s => s.session_id === sessionId);
94
+ if (!session || !validId(session.tabId)) throw Error('Session tab not found');
95
+ const agent = await this.chrome.tabs.get(session.tabId);
96
+ if (!validId(agent.groupId) || !validId(agent.windowId))
97
+ throw Error('Agent Session has no managed Chrome tab group');
98
+ if (validId(agent.splitViewId) && agent.splitViewId !== -1)
99
+ throw Error('Agent tab is already in a Split View');
100
+ if (agent.pinned) throw Error('Pinned Session tabs are not supported');
101
+
102
+ const chat = await activeChatThread(this.chrome);
103
+ if (!chat) throw Error('Activate a ChatGPT conversation tab before enabling Design Mode');
104
+ const leased = new Set(daemon.sessions.flatMap(s => Array.isArray(s.tabIds) ? s.tabIds : [s.tabId]));
105
+ if (leased.has(chat.id) || [...this.records.values()].some(r => r.chatTabId === chat.id) ||
106
+ (validId(chat.splitViewId) && chat.splitViewId !== -1) || chat.pinned)
107
+ throw Error('Active ChatGPT tab is already owned, split or pinned');
108
+ const allTabs = await this.chrome.tabs.query({});
109
+ const group = chat.groupId >= 0
110
+ ? await this.chrome.tabGroups.get(chat.groupId).catch(() => null) : null;
111
+ const agentGroup = await this.chrome.tabGroups.get(agent.groupId);
112
+ const original = {
113
+ windowId:chat.windowId, index:chat.index, groupId:chat.groupId,
114
+ group:group ? {title:group.title, color:group.color, collapsed:group.collapsed} : null,
115
+ };
116
+ const record = {
117
+ sessionId, agentTabId:agent.id, chatTabId:chat.id, groupId:agent.groupId,
118
+ agentGroupCollapsed:agentGroup.collapsed, original, state:'preparing',
119
+ splitViewId:null, placeholderTabId:null,
120
+ };
121
+ this.records.set(sessionId,record);
122
+ this.manager.designCompanionTabIds.add(chat.id);
123
+ this.manager.designActiveGroupIds.add(agent.groupId);
124
+ await this.save();
125
+ try {
126
+ if (chat.windowId !== agent.windowId) {
127
+ const windowTabs = allTabs.filter(t => t.windowId === chat.windowId);
128
+ // Keep the original window alive so restoring this exact tab remains possible.
129
+ if (windowTabs.length === 1) {
130
+ const placeholder = await this.chrome.tabs.create({
131
+ windowId: chat.windowId, url:'about:blank', active:false,
132
+ });
133
+ record.placeholderTabId = placeholder.id;
134
+ await this.save();
135
+ }
136
+ await this.chrome.tabs.move(chat.id,{windowId:agent.windowId,index:agent.index+1});
137
+ }
138
+ await this.chrome.tabs.group({groupId:agent.groupId,tabIds:[chat.id]});
139
+ const currentAgent = await this.chrome.tabs.get(agent.id);
140
+ await this.chrome.tabs.move(chat.id,{index:currentAgent.index+1});
141
+ const left = await this.chrome.tabs.get(agent.id);
142
+ const right = await this.chrome.tabs.get(chat.id);
143
+ if (left.windowId !== right.windowId || left.groupId !== right.groupId ||
144
+ right.index !== left.index+1)
145
+ throw Error('Chrome could not place ChatGPT adjacent to the Session tab');
146
+ await this.chrome.tabGroups.update(agent.groupId,{collapsed:false});
147
+ record.splitViewId = await this.chrome.tabs.createSplit([agent.id,chat.id]);
148
+ record.state='active';
149
+ await this.save();
150
+ await this.chrome.tabs.update(chat.id,{active:true});
151
+ await this.chrome.windows.update(agent.windowId,{focused:true});
152
+ return {active:true,sessionId,agentTabId:agent.id,chatTabId:chat.id,splitViewId:record.splitViewId};
153
+ } catch (error) {
154
+ try { await this.disable(sessionId); }
155
+ catch (recovery) { throw Error(error.message + '; restore failed: ' + recovery.message); }
156
+ throw error;
157
+ }
158
+ }
159
+
160
+ async restoreChat(record) {
161
+ const id=record.chatTabId, original=record.original;
162
+ let chat;
163
+ try { chat=await this.chrome.tabs.get(id); }
164
+ catch(error) { if (isMissingTab(error)) return; throw error; }
165
+
166
+ if (validId(chat.splitViewId) && chat.splitViewId !== -1) {
167
+ await this.chrome.tabs.unsplit(chat.splitViewId);
168
+ } else if (validId(record.splitViewId)) {
169
+ await this.chrome.tabs.unsplit(record.splitViewId).catch(()=>{});
170
+ }
171
+ chat=await this.chrome.tabs.get(id);
172
+ // Orphan splits created before persistence was fixed have no known prior
173
+ // window/group/index. Never guess or move the user's ChatGPT tab.
174
+ if (!original) {
175
+ if (chat.groupId === record.groupId) await this.chrome.tabs.ungroup([id]);
176
+ return;
177
+ }
178
+ if (chat.groupId >= 0) await this.chrome.tabs.ungroup([id]);
179
+ if (validId(original.windowId)) {
180
+ const windowExists = await this.chrome.windows.get(original.windowId).then(()=>true,()=>false);
181
+ if (windowExists) await this.chrome.tabs.move(id,{
182
+ windowId:original.windowId,index:Math.max(0,original.index),
183
+ });
184
+ }
185
+ if (original.groupId >= 0 && original.group) {
186
+ const oldGroup = await this.chrome.tabGroups.get(original.groupId).catch(()=>null);
187
+ const groupId = oldGroup
188
+ ? await this.chrome.tabs.group({groupId:oldGroup.id,tabIds:[id]})
189
+ : await this.chrome.tabs.group({tabIds:[id]});
190
+ if (!oldGroup) await this.chrome.tabGroups.update(groupId,original.group);
191
+ await this.chrome.tabs.move(id,{index:Math.max(0,original.index)});
192
+ }
193
+ if (validId(record.placeholderTabId)) {
194
+ await this.chrome.tabs.remove(record.placeholderTabId).catch(()=>{});
195
+ }
196
+ }
197
+
198
+ async disable(sessionId) {
199
+ const record=this.records.get(sessionId);
200
+ if (!record) return {active:false,sessionId};
201
+ try {
202
+ await this.restoreChat(record);
203
+ } catch (error) {
204
+ // Keep the recovery record and companion protection for the next attempt.
205
+ record.state='restore-failed';
206
+ await this.save();
207
+ throw error;
208
+ }
209
+ this.records.delete(sessionId);
210
+ this.manager.designCompanionTabIds.delete(record.chatTabId);
211
+ if (![...this.records.values()].some(r => r.groupId === record.groupId))
212
+ this.manager.designActiveGroupIds.delete(record.groupId);
213
+ await this.save();
214
+ if (validId(record.groupId) && !this.manager.designActiveGroupIds.has(record.groupId)) {
215
+ await this.chrome.tabGroups.update(record.groupId,
216
+ {collapsed:Boolean(record.agentGroupCollapsed)}).catch(()=>{});
217
+ }
218
+ return {active:false,sessionId,chatTabId:record.chatTabId,restored:true};
219
+ }
220
+
221
+ async closeSession(sessionId) {
222
+ await this.ready;
223
+ return this.serialize(()=>this.disable(sessionId));
224
+ }
225
+
226
+ async reconcileState() {
227
+ const daemon=await this.control.status();
228
+ if (!daemon.connected) return;
229
+ const live=new Set(daemon.sessions.map(s=>s.session_id));
230
+ for (const id of [...this.records.keys()]) {
231
+ if (!live.has(id)) await this.disable(id).catch(()=>{});
232
+ }
233
+ const tabs=await this.chrome.tabs.query({});
234
+ const byId=new Map(tabs.map(tab=>[tab.id,tab]));
235
+ // Chrome may unsplit a pair outside WebHelm. Restore its original layout
236
+ // and stop renewing that Session rather than showing a stale Exit button.
237
+ for (const [id, record] of [...this.records]) {
238
+ const agent=byId.get(record.agentTabId), chat=byId.get(record.chatTabId);
239
+ const together=agent && chat && validId(agent.splitViewId) &&
240
+ agent.splitViewId!==-1 && agent.splitViewId===chat.splitViewId;
241
+ if (live.has(id) && record.state==='active' && !together)
242
+ await this.disable(id).catch(()=>{});
243
+ else if (live.has(id) && together && record.state==='preparing') {
244
+ record.state='active';
245
+ record.splitViewId=agent.splitViewId;
246
+ await this.save();
247
+ }
248
+ }
249
+ // Older Extension versions stored only ephemeral state. Adopt an intact,
250
+ // already-split pair only when a *live* WebHelm Session owns one pane and
251
+ // the other is an actual ChatGPT thread in the same window and group.
252
+ for (const session of daemon.sessions) {
253
+ if (this.records.has(session.session_id)) continue;
254
+ const agent=byId.get(session.tabId);
255
+ if (!agent || !validId(agent.groupId) || agent.groupId<0 ||
256
+ !validId(agent.splitViewId) || agent.splitViewId===-1) continue;
257
+ const candidates=tabs.filter(tab=>tab.id!==agent.id &&
258
+ tab.windowId===agent.windowId && tab.groupId===agent.groupId &&
259
+ tab.splitViewId===agent.splitViewId && isChatThread(tab.url) &&
260
+ !this.manager.designCompanionTabIds.has(tab.id));
261
+ if (candidates.length!==1) continue;
262
+ const chat=candidates[0];
263
+ this.records.set(session.session_id,{
264
+ sessionId:session.session_id,agentTabId:agent.id,chatTabId:chat.id,
265
+ groupId:agent.groupId,agentGroupCollapsed:false,original:null,
266
+ state:'active',splitViewId:agent.splitViewId,placeholderTabId:null,
267
+ adopted:true,
268
+ });
269
+ this.manager.designCompanionTabIds.add(chat.id);
270
+ this.manager.designActiveGroupIds.add(agent.groupId);
271
+ await this.save();
272
+ }
273
+ }
274
+
275
+ async reconcile() {
276
+ await this.ready;
277
+ return this.serialize(()=>this.reconcileState());
278
+ }
279
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "WebHelm",
4
- "version": "1.0.51",
4
+ "version": "1.0.53",
5
5
  "description": "Own named Chrome tab-group workspaces and lazy reusable tab pools for browser agents.",
6
6
  "permissions": [
7
7
  "storage",
@@ -17,7 +17,12 @@ function validSite(site) {
17
17
  export function mergeKeptSites(persisted, statusById, reported) {
18
18
  const sites = new Map();
19
19
  for (const site of Array.isArray(persisted) ? persisted : []) {
20
- if (validSite(site)) sites.set(site.id, {...site, status:statusById?.[site.id]?.status || 'pending'});
20
+ if (validSite(site)) {
21
+ const state=statusById?.[site.id];
22
+ const valid=state && (state.revision===undefined || state.revision===site.revision);
23
+ const failed=valid&&['failed','login_required','unknown','error','release_error'].includes(state.status);
24
+ sites.set(site.id, {...site,status:failed?'failed':valid?state.status:'pending',...(failed||valid&&state.paused?{paused:true}:{}),...(failed?{reason:state.reason||state.status}:{})});
25
+ }
21
26
  }
22
27
  for (const site of Array.isArray(reported) ? reported : []) {
23
28
  if (validSite(site)) sites.set(site.id, {...sites.get(site.id), ...site});
@@ -31,7 +36,7 @@ export async function readKeptSites(chromeApi, reported) {
31
36
  const stored=await chromeApi.storage.local.get(SITE_STORAGE_KEY);
32
37
  persisted=stored[SITE_STORAGE_KEY];
33
38
  const latest=await chromeApi.storage.session.get(SITE_STATUS_KEY);
34
- statuses=latest[SITE_STATUS_KEY] || {};
39
+ statuses={...(latest[SITE_STATUS_KEY] || {}),...((await chromeApi.storage.local.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {})};
35
40
  } catch { /* Keep any site entries returned by the current service worker. */ }
36
41
  return mergeKeptSites(persisted,statuses,reported);
37
42
  }
@@ -47,10 +52,12 @@ export async function setStoredSite(chromeApi, url, enabled) {
47
52
  enabled:true,addedAt:Date.now(),revision:crypto.randomUUID()});
48
53
  await chromeApi.storage.local.set({[SITE_STORAGE_KEY]: next.sort((a,b)=>a.id.localeCompare(b.id))});
49
54
  if (!enabled) {
50
- const storedStates=await chromeApi.storage.session.get(SITE_STATUS_KEY);
51
- const states=storedStates[SITE_STATUS_KEY] || {};
52
- delete states[origin];
53
- await chromeApi.storage.session.set({[SITE_STATUS_KEY]:states});
55
+ for (const storage of [chromeApi.storage.local,chromeApi.storage.session]) {
56
+ const storedStates=await storage.get(SITE_STATUS_KEY);
57
+ const states=storedStates[SITE_STATUS_KEY] || {};
58
+ delete states[origin];
59
+ await storage.set({[SITE_STATUS_KEY]:states});
60
+ }
54
61
  }
55
62
  return {id:origin,enabled:Boolean(enabled)};
56
63
  }
@@ -42,6 +42,10 @@
42
42
  .keepalive-row .keepalive-name.is-logged-in { color:#23915c; }
43
43
  .keepalive-row .keepalive-remove { flex:0 0 19px; width:19px; padding:1px; border:0; background:transparent; color:light-dark(var(--muted),#acb8c9); font-size:16px; font-weight:400; line-height:18px; }
44
44
  .session-row button.site-enabled { color:#23915c; }
45
+ .session-row button.icon-button { display:inline-flex; flex:0 0 27px; align-items:center; justify-content:center; padding:5px; height:27px; width:27px; }
46
+ .session-row button.icon-button svg { display:block; }
47
+ .session-row button.icon-button:hover { background:light-dark(#edf2ff,#304465); }
48
+ .session-row button.design-active { color:#23915c; border-color:#23915c; }
45
49
  #queue-list { border-top:1px solid light-dark(var(--border),#334155); margin-top:6px; padding-top:4px; max-height:240px; }
46
50
  .queue-platform { padding:3px 0; }
47
51
  .queue-platform + .queue-platform { border-top:1px solid light-dark(var(--border),#334155); }
@@ -9,6 +9,7 @@ let lastSiteSignature = '';
9
9
  let currentSites = [];
10
10
  let refreshRunning = false;
11
11
  let canControlSites = false;
12
+ let canEnableDesign = false;
12
13
  let currentQueue = [];
13
14
  let queueBusy = false;
14
15
  let queueConnected = false;
@@ -45,6 +46,35 @@ function actionButton(label, disabled, onClick, className = '') {
45
46
  return button;
46
47
  }
47
48
 
49
+ function iconButton(kind, disabled, onClick, title, active = false) {
50
+ const activeClass = active ? (kind === 'keepalive' ? ' site-enabled' : ' design-active') : '';
51
+ const button = actionButton('', disabled, onClick, 'icon-button' + activeClass);
52
+ button.title=title;
53
+ button.setAttribute('aria-label',title);
54
+ const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');
55
+ svg.setAttribute('viewBox','0 0 24 24');
56
+ svg.setAttribute('width','16');
57
+ svg.setAttribute('height','16');
58
+ svg.setAttribute('fill','none');
59
+ svg.setAttribute('stroke','currentColor');
60
+ svg.setAttribute('stroke-width','1.8');
61
+ svg.setAttribute('stroke-linecap','round');
62
+ svg.setAttribute('stroke-linejoin','round');
63
+ svg.setAttribute('aria-hidden','true');
64
+ const paths=kind==='split'
65
+ ? ['M12 3v18','M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z']
66
+ : kind==='keepalive'
67
+ ? ['M22 12h-4l-3 9L9 3l-3 9H2']
68
+ : ['M6 6h12v12H6z','M9 9l6 6','M15 9l-6 6'];
69
+ for(const d of paths){
70
+ const path=document.createElementNS('http://www.w3.org/2000/svg','path');
71
+ path.setAttribute('d',d);
72
+ svg.append(path);
73
+ }
74
+ button.append(svg);
75
+ return button;
76
+ }
77
+
48
78
  function originForTab(url) {
49
79
  try { const site=new URL(url); return site.protocol === 'https:' ? site.origin : null; }
50
80
  catch { return null; }
@@ -65,12 +95,12 @@ function renderKeptSites(sites, busy, connected) {
65
95
  target.textContent='Enable Keep Alive from a WebHelm Session.';
66
96
  return;
67
97
  }
68
- const labels={alive:'Logged in',login_required:'Login required',unknown:'Login not confirmed',
69
- error:'Heartbeat failed',unsupported:'No heartbeat action',pending:'Checking login'};
98
+ const labels={alive:'Logged in',failed:'Heartbeat failed',login_required:'Login required',unknown:'Login not confirmed',
99
+ error:'Heartbeat failed',release_error:'Tab release failed',unsupported:'No heartbeat action',pending:'Checking login'};
70
100
  for (const site of sites) {
71
101
  const row=document.createElement('div'); row.className='keepalive-row';
72
102
  const loggedIn=site.status==='alive';
73
- const statusText=labels[site.status] || labels.pending;
103
+ const statusText=(labels[site.status] || labels.pending)+(site.paused?' · Paused':'')+(site.reason&&site.reason!==site.status?' · '+(labels[site.reason]||site.reason):'');
74
104
  const status=document.createElement('span'); status.className='keepalive-status';
75
105
  status.dataset.status=loggedIn?'alive':'inactive';
76
106
  status.title=statusText;
@@ -92,15 +122,25 @@ function renderKeptSites(sites, busy, connected) {
92
122
  },'keepalive-remove');
93
123
  remove.title=`Remove ${siteLabel(site.url)} from Keep Alive`;
94
124
  remove.setAttribute('aria-label',remove.title);
95
- row.append(status,name,remove);
125
+ row.append(status,name);
126
+ if (site.paused) {
127
+ const resume=actionButton('↻',!connected,async()=>{
128
+ try {await rpc('workspace.control.site.resume',{siteId:site.id});lastSiteSignature='';refresh();}
129
+ catch(error){el('message').textContent=error.message;}
130
+ },'keepalive-remove');
131
+ resume.title=resume.getAttribute('aria-label') || 'Resume heartbeat after signing in';
132
+ resume.setAttribute('aria-label',resume.title);
133
+ row.append(resume);
134
+ }
135
+ row.append(remove);
96
136
  target.append(row);
97
137
  }
98
138
  }
99
139
 
100
140
  function renderWorkspaces(workspaces, busy, connected) {
101
141
  const signature = JSON.stringify(workspaces.map(w => [
102
- 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]),
103
- ])) + ':' + JSON.stringify(currentSites.map(site=>site.id)) + ':' + canControlSites + ':' + busy + ':' + connected;
142
+ 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,s.designActive]),
143
+ ])) + ':' + JSON.stringify(currentSites.map(site=>site.id)) + ':' + canControlSites + ':' + canEnableDesign + ':' + busy + ':' + connected;
104
144
  if (signature === lastSignature) return;
105
145
  lastSignature = signature;
106
146
  const target = el('workspace-list');
@@ -139,17 +179,32 @@ function renderWorkspaces(workspaces, busy, connected) {
139
179
  sessionRow.append(details);
140
180
  if (workspace.name === 'WebHelm' && siteId) {
141
181
  const enabled=currentSites.some(site=>site.id===siteId);
142
- const toggle=actionButton(enabled?'On':'Keep Alive',busy||!connected||!canControlSites,async()=>{
182
+ const toggle=iconButton('keepalive',busy||!connected||!canControlSites,async()=>{
143
183
  try {
144
184
  await rpc('workspace.control.site.toggle',{sessionId:session.session_id,enabled:!enabled});
145
185
  lastSignature='';refresh();
146
186
  } catch(error){el('message').textContent=error.message;}
147
- },enabled?'site-enabled':'');
148
- if(!canControlSites) toggle.title='Update the running WebHelm daemon to manage Keep Alive sites';
187
+ },!canControlSites
188
+ ? 'Update the running WebHelm daemon to manage Keep Alive sites'
189
+ : enabled ? 'Disable Keep Alive for this site' : 'Enable Keep Alive for this site',enabled);
149
190
  sessionRow.append(toggle);
150
191
  }
151
- sessionRow.append(actionButton('Stop', busy || !connected,
152
- () => showConfirmation('stop', {sessionId:session.session_id})));
192
+ if (session.tabId && (session.designActive || canEnableDesign)) {
193
+ const designButton=iconButton('split',
194
+ busy || !connected,async()=>{
195
+ try {
196
+ await rpc('workspace.control.design.toggle',{sessionId:session.session_id});
197
+ lastSignature='';
198
+ refresh();
199
+ } catch(error){el('message').textContent=error.message;}
200
+ },session.designActive
201
+ ? 'Exit Design Mode: restore ChatGPT tab'
202
+ : 'Design Mode: split Session with active ChatGPT thread',session.designActive);
203
+ sessionRow.append(designButton);
204
+ }
205
+ sessionRow.append(iconButton('stop', busy || !connected,
206
+ () => showConfirmation('stop', {sessionId:session.session_id}),
207
+ 'Stop Session'));
153
208
  row.append(sessionRow);
154
209
  }
155
210
  target.append(row);
@@ -264,6 +319,7 @@ async function refresh() {
264
319
  el('daemon-status').className = `daemon-state ${state.connected ? 'online' : 'offline'}`;
265
320
  const busy = Boolean(state.request);
266
321
  canControlSites=Array.isArray(state.keptSites);
322
+ canEnableDesign=Boolean(state.canEnableDesign);
267
323
  currentSites=await readKeptSites(chrome,state.keptSites);
268
324
  renderKeptSites(currentSites,busy,state.connected);
269
325
  renderWorkspaces(await readMenuWorkspaces(chrome,state.workspaces || []),busy,state.connected);
@@ -3,9 +3,11 @@ import { ControlChannel } from "./control-channel.mjs";
3
3
  import { summarizeWorkspaces } from "./workspace-summary.mjs";
4
4
  import { sessionBadge } from "./session-badge.mjs";
5
5
  import { createControlRpc } from "./control-rpc.mjs";
6
+ import { DesignMode } from "./design-mode.mjs";
6
7
 
7
8
  const manager = new WorkspaceManager(chrome);
8
9
  const control = new ControlChannel(chrome);
10
+ const design = new DesignMode(chrome, manager, control);
9
11
  manager.setOwnershipProvider(async () => {
10
12
  const state = await control.status();
11
13
  return state.connected ? state.sessions : null;
@@ -37,6 +39,7 @@ async function scheduleBadgeAlarm() {
37
39
  }
38
40
  chrome.alarms.onAlarm.addListener(alarm => {
39
41
  if (alarm.name === BADGE_ALARM) scheduleBadge();
42
+ if (alarm.name === ORPHAN_ALARM) design.reconcile().catch(error => console.warn("Design Mode recovery:",error));
40
43
  if (alarm.name === ORPHAN_ALARM) manager.recoverConfiguredOrphans().catch(error => {
41
44
  console.warn("WebHelm orphan lease recovery failed", error);
42
45
  });
@@ -49,7 +52,7 @@ async function removeLegacyContextMenu() {
49
52
  catch { /* already absent */ }
50
53
  }
51
54
 
52
- manager.restoreConfiguredWorkspaces()
55
+ design.reconcile().then(() => manager.restoreConfiguredWorkspaces())
53
56
  .then(scheduleBadge)
54
57
  .catch(error => console.warn("WebHelm failed to restore configured workspaces", error));
55
58
  removeLegacyContextMenu().catch(() => {});
@@ -62,10 +65,11 @@ chrome.runtime.onStartup.addListener(() => {
62
65
  scheduleBadge();
63
66
  });
64
67
 
65
- const controlRpc = createControlRpc({control, manager, summarizeWorkspaces, scheduleBadge});
68
+ const controlRpc = createControlRpc({control, manager, design, summarizeWorkspaces, scheduleBadge});
66
69
 
67
70
  globalThis.browserWorkspaceManagerRpc = async (request) => {
68
71
  try {
72
+ await design.ready;
69
73
  const method = String(request?.method || "");
70
74
  const result = method.startsWith("workspace.control.")
71
75
  ? await controlRpc(method, request.args || {})
@@ -104,7 +108,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
104
108
  !["workspace.control.requestStop", "workspace.control.queueCancel", "workspace.control.status",
105
109
  "workspace.control.activateTab", "workspace.control.openQueue",
106
110
  "workspace.control.site.toggle", "workspace.control.site.open",
107
- "workspace.control.site.remove"].includes(request.method))) {
111
+ "workspace.control.site.remove", "workspace.control.site.resume", "workspace.control.design.toggle"].includes(request.method))) {
108
112
  sendResponse({ok:false,error:{message:"WebHelm control actions require the toolbar popup"}});
109
113
  return false;
110
114
  }
@@ -34,28 +34,41 @@ export async function setKeptSite(chromeApi, url, enabled) {
34
34
  sites.sort((a,b) => a.id.localeCompare(b.id));
35
35
  await chromeApi.storage.local.set({[SITE_STORAGE_KEY]: sites});
36
36
  if (!enabled) {
37
- const states = (await chromeApi.storage.session.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {};
38
- delete states[id];
39
- await chromeApi.storage.session.set({[SITE_STATUS_KEY]: states});
37
+ for (const storage of [chromeApi.storage.local,chromeApi.storage.session]) {
38
+ const states = (await storage.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {};
39
+ delete states[id];
40
+ await storage.set({[SITE_STATUS_KEY]: states});
41
+ }
40
42
  }
41
43
  return {id, enabled:Boolean(enabled), sites};
42
44
  }
43
45
 
44
46
  export async function sitesWithStatus(chromeApi) {
45
- const [sites, stored] = await Promise.all([listKeptSites(chromeApi),chromeApi.storage.session.get(SITE_STATUS_KEY)]);
46
- const states = stored[SITE_STATUS_KEY] || {};
47
- return sites.map(site => ({...site, status:states[site.id]?.status || 'pending',
48
- ...(states[site.id]?.checkedAt ? {checkedAt:states[site.id].checkedAt} : {}),
49
- ...(states[site.id]?.platform ? {platform:states[site.id].platform} : {})}));
47
+ const [sites, stored, legacy] = await Promise.all([listKeptSites(chromeApi),
48
+ chromeApi.storage.local.get(SITE_STATUS_KEY),chromeApi.storage.session.get(SITE_STATUS_KEY)]);
49
+ return sites.map(site => {
50
+ const durable=stored[SITE_STATUS_KEY]?.[site.id];
51
+ const old=legacy[SITE_STATUS_KEY]?.[site.id];
52
+ const state=durable?.revision===site.revision ? durable :
53
+ (!durable && old && (!old.checkedAt || old.checkedAt>=site.addedAt) ? old : {});
54
+ const failed=['failed','login_required','unknown','error','release_error'].includes(state.status);
55
+ return {...site,status:failed?'failed':state.status || 'pending',
56
+ paused:failed || state.paused===true,
57
+ ...(failed ? {reason:state.reason || state.status} : {}),
58
+ ...(state.checkedAt ? {checkedAt:state.checkedAt} : {}),
59
+ ...(state.platform ? {platform:state.platform} : {})};
60
+ });
50
61
  }
51
62
 
52
63
  export async function reportKeptSite(chromeApi, report) {
53
64
  const registered = (await listKeptSites(chromeApi)).some(site => site.id === report?.id && site.revision === report?.revision);
54
- if (!registered || !['alive','login_required','unknown','error','unsupported'].includes(report?.status))
65
+ if (!registered || !['alive','login_required','unknown','error','unsupported','release_error','failed'].includes(report?.status))
55
66
  return {ignored:true};
56
- const states = (await chromeApi.storage.session.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {};
57
- states[report.id] = {status:report.status,checkedAt:Date.now(),
67
+ const states = (await chromeApi.storage.local.get(SITE_STATUS_KEY))[SITE_STATUS_KEY] || {};
68
+ states[report.id] = {revision:report.revision,status:report.status,checkedAt:Date.now(),
69
+ paused:report.paused===true,
70
+ ...(['login_required','unknown','error','release_error'].includes(report.reason)?{reason:report.reason}:{}),
58
71
  ...(typeof report.platform === 'string' ? {platform:report.platform} : {})};
59
- await chromeApi.storage.session.set({[SITE_STATUS_KEY]:states});
72
+ await chromeApi.storage.local.set({[SITE_STATUS_KEY]:states});
60
73
  return {ok:true};
61
74
  }
@@ -48,6 +48,10 @@ export class WorkspaceManager {
48
48
  this.inFlightTabIds = new Set();
49
49
  this.recentExtensionManagementByWindow = new Map();
50
50
  this.ownedTabIds = new Set();
51
+ // Companion tabs in Design Mode share the group only for Chrome Split View.
52
+ // They are never pooled, adopted, reclaimed or counted as capacity.
53
+ this.designCompanionTabIds = new Set();
54
+ this.designActiveGroupIds = new Set();
51
55
  }
52
56
 
53
57
  setOwnershipProvider(provider) {
@@ -86,6 +90,7 @@ export class WorkspaceManager {
86
90
  .map(Number).filter(Number.isInteger));
87
91
  const tabs = await this.groupTabs(group.id);
88
92
  const candidates = tabs.filter(tab => {
93
+ if (this.designCompanionTabIds.has(tab.id)) return false;
89
94
  const url = this.tabUrl(tab);
90
95
  const meta = this.parseManagedUrl(url);
91
96
  return url === 'about:blank' ||
@@ -114,7 +119,7 @@ export class WorkspaceManager {
114
119
  const current = await this.chrome.tabs.get(candidate.id).catch(() => null);
115
120
  const currentUrl = this.tabUrl(current);
116
121
  const currentMeta = this.parseManagedUrl(currentUrl);
117
- const stillCandidate = current?.groupId === group.id && (currentUrl === 'about:blank' ||
122
+ const stillCandidate = !this.designCompanionTabIds.has(candidate.id) && current?.groupId === group.id && (currentUrl === 'about:blank' ||
118
123
  (currentMeta?.workspace === normalizedName && currentMeta.role === 'lease' && currentMeta.tabId === String(current.id)));
119
124
  const latestSessions = await this.getDaemonSessions();
120
125
  if (!Array.isArray(latestSessions)) continue;
@@ -337,7 +342,7 @@ export class WorkspaceManager {
337
342
  await this.chrome.tabs.group({ groupId, tabIds: [tabId] });
338
343
 
339
344
  const tabs = await this.groupTabs(groupId);
340
- if (tabs.length > entry.poolSize) {
345
+ if (this.poolTabCount(tabs) > entry.poolSize) {
341
346
  const { idle } = this.classify(group.title, tabs);
342
347
  const removable = idle.find((candidate) => candidate.id !== tabId);
343
348
  if (removable) await this.chrome.tabs.remove(removable.id);
@@ -345,7 +350,7 @@ export class WorkspaceManager {
345
350
 
346
351
  await this.chrome.tabGroups.update(groupId, {
347
352
  title: group.title,
348
- collapsed: true,
353
+ collapsed: !this.designActiveGroupIds.has(group.id),
349
354
  });
350
355
 
351
356
  return {
@@ -420,6 +425,7 @@ export class WorkspaceManager {
420
425
  }
421
426
 
422
427
  if (!inherited) {
428
+ if (this.designCompanionTabIds.has(tabId)) return { tabId, companion: true };
423
429
  if (this.isOwnedTab(tab)) return {
424
430
  tabId,
425
431
  owned: true,
@@ -450,7 +456,7 @@ export class WorkspaceManager {
450
456
  await this.chrome.tabs.group({ groupId: group.id, tabIds: [tabId] });
451
457
 
452
458
  const tabs = await this.groupTabs(group.id);
453
- if (tabs.length > entry.poolSize) {
459
+ if (this.poolTabCount(tabs) > entry.poolSize) {
454
460
  const { idle } = this.classify(group.title, tabs);
455
461
  const removable = idle.find((candidate) => candidate.id !== tabId);
456
462
  if (removable) await this.chrome.tabs.remove(removable.id);
@@ -458,7 +464,7 @@ export class WorkspaceManager {
458
464
 
459
465
  await this.chrome.tabGroups.update(group.id, {
460
466
  title: group.title,
461
- collapsed: true,
467
+ collapsed: !this.designActiveGroupIds.has(group.id),
462
468
  });
463
469
 
464
470
  const result = {
@@ -488,9 +494,12 @@ export class WorkspaceManager {
488
494
  tab.status !== "loading";
489
495
  }
490
496
 
497
+ poolTabCount(tabs) { return tabs.filter(tab => !this.designCompanionTabIds.has(tab.id)).length; }
498
+
491
499
  classify(name, tabs) {
492
500
  const idle = [], leased = [];
493
501
  for (const tab of tabs) {
502
+ if (this.designCompanionTabIds.has(tab.id)) continue;
494
503
  (this.isIdleWorkspaceTab(name, tab) ? idle : leased).push(tab);
495
504
  }
496
505
  return { idle, leased };
@@ -547,7 +556,7 @@ export class WorkspaceManager {
547
556
  })];
548
557
  for (const tab of created) this.markOwned(tab.id);
549
558
  const groupId = await this.chrome.tabs.group({ tabIds: created.map((tab) => tab.id) });
550
- await this.chrome.tabGroups.update(groupId, { title: name, collapsed: true });
559
+ await this.chrome.tabGroups.update(groupId, { title: name, collapsed: !this.designActiveGroupIds.has(groupId) });
551
560
  await this.positionNewGroupLeftmost(groupId);
552
561
  for (const tab of created) await this.waitForIdleTab(tab.id, name);
553
562
  return await this.status(name);
@@ -569,7 +578,7 @@ export class WorkspaceManager {
569
578
  const group = await this.workspaceGroup(normalizedName);
570
579
  if (!group) return await this.createGroup(normalizedName, wanted);
571
580
 
572
- await this.chrome.tabGroups.update(group.id, { title: normalizedName, collapsed: true });
581
+ await this.chrome.tabGroups.update(group.id, { title: normalizedName, collapsed: !this.designActiveGroupIds.has(group.id) });
573
582
  await this.reconcilePool(normalizedName, group.id, wanted);
574
583
  return await this.status(normalizedName);
575
584
  }
@@ -580,12 +589,12 @@ export class WorkspaceManager {
580
589
 
581
590
  // poolSize is a maximum concurrent capacity, not a target tab count.
582
591
  // Only remove surplus idle tabs when shrinking; never refill a lazy pool.
583
- if (tabs.length > poolSize && idle.length) {
584
- const removable = Math.min(idle.length, tabs.length - poolSize);
592
+ if (this.poolTabCount(tabs) > poolSize && idle.length) {
593
+ const removable = Math.min(idle.length, this.poolTabCount(tabs) - poolSize);
585
594
  await this.chrome.tabs.remove(idle.slice(0, removable).map((tab) => tab.id));
586
595
  }
587
596
 
588
- await this.chrome.tabGroups.update(groupId, { title: name, collapsed: true });
597
+ await this.chrome.tabGroups.update(groupId, { title: name, collapsed: !this.designActiveGroupIds.has(groupId) });
589
598
  }
590
599
 
591
600
  async status(name) {
@@ -613,13 +622,13 @@ export class WorkspaceManager {
613
622
  poolSize: entry.poolSize,
614
623
  showInMenu: entry.showInMenu !== false,
615
624
  maxCapacity: entry.poolSize,
616
- physicalTabs: tabs.length,
625
+ physicalTabs: this.poolTabCount(tabs),
617
626
  idle: idle.length,
618
627
  leased: leased.length,
619
- tabIds: tabs.map((tab) => tab.id),
628
+ tabIds: tabs.filter(tab => !this.designCompanionTabIds.has(tab.id)).map((tab) => tab.id),
620
629
  idleTabIds: idle.map((tab) => tab.id),
621
630
  leasedTabIds: leased.map((tab) => tab.id),
622
- tabs: tabs.map((tab) => ({
631
+ tabs: tabs.filter(tab => !this.designCompanionTabIds.has(tab.id)).map((tab) => ({
623
632
  tabId: tab.id,
624
633
  groupId: tab.groupId,
625
634
  title: tab.title || "",
@@ -750,7 +759,7 @@ export class WorkspaceManager {
750
759
  // Do not release the allocation fence while Chrome still exposes the
751
760
  // old idle URL. An overlapping allocation must not see this tab as free.
752
761
  updated = await this.waitForIdentityTab(tab.id, normalizedName);
753
- await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: true });
762
+ await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: !this.designActiveGroupIds.has(ready.groupId) });
754
763
  } finally { this.inFlightTabIds.delete(tab.id); }
755
764
  return {
756
765
  workspace: normalizedName,
@@ -807,7 +816,7 @@ export class WorkspaceManager {
807
816
  this.inFlightTabIds.add(tab.id);
808
817
  try {
809
818
  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 });
819
+ await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: !this.designActiveGroupIds.has(ready.groupId) });
811
820
  return {
812
821
  workspace: normalizedName,
813
822
  groupId: ready.groupId,
@@ -829,7 +838,7 @@ export class WorkspaceManager {
829
838
  throw new Error(`Tab ${wanted} is not owned by workspace ${normalizedName}`);
830
839
  }
831
840
 
832
- if (tabs.length > ready.poolSize) {
841
+ if (this.poolTabCount(tabs) > ready.poolSize) {
833
842
  await this.chrome.tabs.remove(wanted);
834
843
  } else {
835
844
  try {
@@ -852,7 +861,7 @@ export class WorkspaceManager {
852
861
  await this.chrome.tabs.remove(wanted);
853
862
  }
854
863
  }
855
- await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: true });
864
+ await this.chrome.tabGroups.update(ready.groupId, { title: normalizedName, collapsed: !this.designActiveGroupIds.has(ready.groupId) });
856
865
  return { workspace: normalizedName, tabId: wanted, released: true };
857
866
  });
858
867
  }
@@ -898,7 +907,7 @@ export class WorkspaceManager {
898
907
  }
899
908
 
900
909
  const tabs = await this.groupTabs(state.groupId);
901
- if (tabs.length) await this.chrome.tabs.remove(tabs.map((tab) => tab.id));
910
+ if (tabs.length) await this.chrome.tabs.remove(tabs.filter(tab => !this.designCompanionTabIds.has(tab.id)).map((tab) => tab.id));
902
911
  await this.removeConfig(normalizedName);
903
912
  return { name: normalizedName, deleted: true };
904
913
  }
@@ -1,3 +1,17 @@
1
+ // A managed idle/lease marker or an Extension management page is not a
2
+ // user-facing browser Session. Keep the daemon-owned Session record unchanged;
3
+ // this filters only the toolbar's presentation.
4
+ export function showSessionTab(url, extensionUrl) {
5
+ try {
6
+ const page = new URL(url);
7
+ if (page.protocol === 'about:' && page.pathname === 'blank') return false;
8
+ const ownOrigin = extensionUrl ? new URL(extensionUrl).origin : null;
9
+ if (ownOrigin && page.origin === ownOrigin &&
10
+ ['/helm.html', '/workspace.html', '/popup.html'].includes(page.pathname)) return false;
11
+ return true;
12
+ } catch { return false; }
13
+ }
14
+
1
15
  export function summarizeWorkspaces(workspaces, sessions = []) {
2
16
  if (!Array.isArray(workspaces)) throw new Error('Workspace list is invalid');
3
17
  const configured = workspaces.map(workspace => ({
@@ -13,7 +13,7 @@ export const EXTENSION_HOME=path.resolve(process.env.WEBHELM_EXTENSION_HOME ||
13
13
  (SOURCE_MODE ? SOURCE : path.join(LOCAL_ROOT,'extension')));
14
14
  const FILES=[
15
15
  'manifest.json','service-worker.mjs','workspace-manager.mjs','workspace.html','helm.html','workspace-page.mjs',
16
- 'control-channel.mjs','control-rpc.mjs','site-registry.mjs','popup-data.mjs','workspace-summary.mjs','session-badge.mjs','popup.html','popup.mjs',
16
+ 'control-channel.mjs','control-rpc.mjs','design-mode.mjs','site-registry.mjs','popup-data.mjs','workspace-summary.mjs','session-badge.mjs','popup.html','popup.mjs',
17
17
  ...[16,32,48,128].map(size => `icons/webhelm-${size}.png`),
18
18
  ];
19
19
 
@@ -9,7 +9,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
9
9
  import { invokePlatformAction } from './platforms.mjs';
10
10
  import {createSiteKeepaliveScheduler} from './site-keepalive.mjs';
11
11
  import { PlatformQueueRegistry } from './queue-registry.mjs';
12
- import { idleUrlFromIdentity, sameIdleUrl, staleSession, withinDeadline, SessionDeadlineError } from './session-lifecycle.mjs';
12
+ import { idleUrlFromIdentity, sameIdleUrl, staleSession, withinDeadline, SessionDeadlineError, endedDesignSessions } from './session-lifecycle.mjs';
13
13
  import { stopMatchingSessions } from './session-control.mjs';
14
14
  import { ensureManagedChrome } from './chrome.mjs';
15
15
  import { ensureExtensionLoaded } from './extension-manager.mjs';
@@ -456,6 +456,68 @@ async function createSession(req={}) {
456
456
  } finally { pendingSessionStarts--; }
457
457
  }
458
458
 
459
+ // Agent-driven Design Mode uses the same Extension Split View operation as
460
+ // the per-Session popup button. The daemon owns the Session and sends an
461
+ // authoritative ownership snapshot before asking Chrome to split.
462
+ async function enableDesignMode(s) {
463
+ await extensionCall(null,'workspace.control.heartbeat',{
464
+ sessions:visibleSessions(),queue:queueRegistry?.list().items||[],
465
+ });
466
+ const split=await extensionCall(null,'workspace.control.design.enable',{sessionId:s.session_id});
467
+ s.designWasEnabled=true;
468
+ return split;
469
+ }
470
+
471
+ function requireCliDesignSession(id) {
472
+ const s=sessions.get(id);
473
+ if(!s || s.workspace!=='WebHelm' || s.closing || s.poisoned)
474
+ throw Error('No active WebHelm Session: '+id);
475
+ return s;
476
+ }
477
+
478
+ async function startDesignMode(req) {
479
+ const raw=String(req.url||'');
480
+ let url;
481
+ try { url=new URL(raw); } catch { throw Error('Design Mode requires a valid site URL'); }
482
+ if(url.protocol!=='https:' && !(url.protocol==='http:' &&
483
+ ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))
484
+ throw Error('Design Mode requires HTTPS (or local HTTP)');
485
+ const started=await createSession({workspace:'WebHelm',url:url.href});
486
+ const s=requireCliDesignSession(started.session_id);
487
+ s.designOwned=true;
488
+ s.designUrl=url.href;
489
+ try {
490
+ const split=await enableDesignMode(s);
491
+ return {...started,design_mode:true,split,site:url.href};
492
+ } catch(error) {
493
+ try { await stopSession(s.session_id); }
494
+ catch(cleanup) { throw Error(error.message+'; Session rollback failed: '+cleanup.message); }
495
+ throw error;
496
+ }
497
+ }
498
+
499
+ async function attachDesignMode(id) {
500
+ const s=requireCliDesignSession(id);
501
+ const split=await enableDesignMode(s);
502
+ return {session_id:id,design_mode:true,attached:true,split};
503
+ }
504
+
505
+ async function stopDesignMode(id) {
506
+ const s=requireCliDesignSession(id);
507
+ const split=await extensionCall(null,'workspace.control.design.disable',{sessionId:id});
508
+ if(!s.designOwned) return {session_id:id,design_mode:false,session_stopped:false,split};
509
+ const stopped=await stopSession(id);
510
+ return {session_id:id,design_mode:false,session_stopped:true,split,stopped};
511
+ }
512
+
513
+ async function designStatus() {
514
+ const ids=await extensionCall(null,'workspace.control.design.sessions');
515
+ const active=new Set(Array.isArray(ids)?ids:[]);
516
+ return {sessions:[...sessions.values()].filter(s=>s.workspace==='WebHelm'&&active.has(s.session_id))
517
+ .map(s=>({session_id:s.session_id,url:s.designUrl||null,created_by_design:!!s.designOwned,
518
+ last_used_at:s.last_used_at}))};
519
+ }
520
+
459
521
  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}
460
522
  async function extensionSupported() {
461
523
  const browser=await connectBrowser();
@@ -523,6 +585,13 @@ async function closeSessionOwned(s){
523
585
  s.poisoned=true; // Revoke delayed helpers after terminal close.
524
586
  let release_error=null;
525
587
  try {
588
+ // User's companion thread must leave the managed group before Session
589
+ // release returns this tab to the pool. Old extensions may lack the RPC.
590
+ if (s.workspaceSupported) {
591
+ const activeDesignIds=await extensionCall(null,'workspace.control.design.records');
592
+ if (Array.isArray(activeDesignIds) && activeDesignIds.includes(s.session_id))
593
+ await extensionCall(null,'workspace.control.design.closeSession',{sessionId:s.session_id});
594
+ }
526
595
  const returnedTabs=s.leasedTabs.size;
527
596
  const closedChildTabs=s.targets.size - returnedTabs;
528
597
  await s.mutex.run(async()=>{
@@ -668,6 +737,21 @@ async function pollExtensionControl() {
668
737
  if (controlPollActive || shuttingDown) return;
669
738
  controlPollActive = true;
670
739
  try {
740
+ // Extension records are authoritative only on successful contact. A
741
+ // temporary RPC failure must never close user-owned browser sessions.
742
+ const designSessionIds=await extensionCall(null,'workspace.control.design.sessions').catch(error=>{
743
+ console.warn(`WebHelm Design Mode status unavailable: ${error.message}`);
744
+ return null;
745
+ });
746
+ if (Array.isArray(designSessionIds)) {
747
+ for (const id of designSessionIds) {
748
+ try { heartbeatSession(id); } catch { /* Session already ended */ }
749
+ }
750
+ for (const s of endedDesignSessions(sessions.values(),designSessionIds)) {
751
+ try { await stopSession(s.session_id); }
752
+ catch(error){console.warn(`WebHelm Design Mode release failed for ${s.session_id}: ${error.message}`);}
753
+ }
754
+ }
671
755
  const pendingAction = await extensionCall(null,'workspace.control.poll',{sessions:visibleSessions(),queue:(await getQueueRegistry()).list().items});
672
756
  if (!pendingAction) return;
673
757
  const {id,action,sessionId} = pendingAction;
@@ -750,7 +834,7 @@ async function runPlatform(req) {
750
834
  });
751
835
  } finally {
752
836
  session.inFlight--;session.last_used_at=Date.now();
753
- cleanup=auto ? await stopSession(sid).catch(e=>({release_error:e.message})) : {caller_owned_session:true};
837
+ cleanup=auto ? await stopSession(sid).catch(e=>({session_id:sid,release_error:e.message})) : {caller_owned_session:true};
754
838
  }
755
839
  result.cleanup=cleanup;
756
840
  // Action completion/receipt semantics belong to the Platform, not this runner.
@@ -771,10 +855,18 @@ const siteKeepalive = createSiteKeepaliveScheduler({
771
855
  const capacity=await workspaceCapacity();
772
856
  return Number.isInteger(capacity.available) && capacity.available > 0;
773
857
  },
858
+ recover:async sid => {
859
+ const session=sessions.get(sid);
860
+ if (!session) return true;
861
+ if (session.closing) return false;
862
+ await stopSession(sid);
863
+ return !sessions.has(sid);
864
+ },
774
865
  run:async plan => {
775
866
  const outcome=await runPlatform({platform:plan.platform,action:plan.action,
776
867
  url:plan.url,auto_session:true,config:{}});
777
- if (!outcome.result.ok || outcome.result.cleanup?.release_error) throw Error('Platform heartbeat action failed or session not released');
868
+ if (outcome.result.cleanup?.release_error) return {status:'release_error',releaseSessionId:outcome.result.cleanup.session_id};
869
+ if (!outcome.result.ok) throw Error('Platform heartbeat action failed');
778
870
  return outcome.result.value;
779
871
  },
780
872
  });
@@ -792,7 +884,7 @@ export async function handle(req){
792
884
  setTimeout(()=>process.kill(process.pid,'SIGTERM'),150).unref();
793
885
  return {ok:true,stopping:true,pid:process.pid};
794
886
  }
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}`)}}
887
+ 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'design-start':return startDesignMode(req);case'design-attach':return attachDesignMode(req.session_id);case'design-stop':return stopDesignMode(req.session_id);case'design-status':return designStatus();case'platform-run':return runPlatform(req);default:throw Error(`unknown op: ${req.op}`)}}
796
888
  export function serve(conn) {
797
889
  let buffer = '', dispatched = false;
798
890
  conn.on('error',()=>{ /* A disconnected client must not crash the daemon. */ });
@@ -48,3 +48,13 @@ export function sameIdleUrl(actual, expected) {
48
48
  return url.protocol === 'chrome-extension:' && url.href === idle.href;
49
49
  } catch { return false; }
50
50
  }
51
+
52
+ // A Design-created Session belongs to the split. Once the pair disappears,
53
+ // return its tab to the pool; a Session merely attached to Design Mode survives.
54
+ // Null means the Extension could not be reached, not that its splits ended.
55
+ export function endedDesignSessions(sessions, activeIds) {
56
+ if (!Array.isArray(activeIds)) return [];
57
+ const active=new Set(activeIds);
58
+ return [...sessions].filter(s => s.designOwned && s.designWasEnabled &&
59
+ !s.closing && !s.poisoned && !active.has(s.session_id));
60
+ }
@@ -37,40 +37,54 @@ export function resolveSiteHeartbeat(site, names=listPlatforms, manifestFor=plat
37
37
  return null;
38
38
  }
39
39
 
40
+ // Only positive login evidence permits another heartbeat. All failures pause
41
+ // until a new registration revision is explicitly requested.
40
42
  export function createSiteKeepaliveScheduler({listSites, report, run, resolve=resolveSiteHeartbeat,
41
- now=Date.now, canRun=async()=>true}) {
43
+ now=Date.now, canRun=async()=>true, recover=async()=>true}) {
42
44
  const next = new Map();
45
+ const cleanup = new Map();
43
46
  let active = false;
44
47
  return {
45
48
  async tick() {
46
49
  if (active) return {busy:true};
47
50
  active=true;
48
51
  try {
52
+ // Retry only the old Session's release, never the failed Action.
53
+ for (const [id, pending] of cleanup) {
54
+ if (now() < pending.at) continue;
55
+ pending.at=now()+60000;
56
+ try { if (await recover(pending.sessionId)) cleanup.delete(id); } catch {}
57
+ }
49
58
  const sites=await listSites();
50
59
  const known=new Set(sites.map(s=>s.id));
51
60
  for (const id of next.keys()) if (!known.has(id)) next.delete(id);
52
61
  for (const site of sites) {
53
- const nextCheck=next.get(site.id);
54
- if (nextCheck && nextCheck.revision === site.revision && now() < nextCheck.at) continue;
62
+ if (cleanup.has(site.id)) continue;
63
+ const previous=next.get(site.id);
64
+ const current=previous?.revision === site.revision ? previous : null;
65
+ if (site.paused || current?.paused || (current && now() < current.at)) continue;
55
66
  let plan;
56
67
  try {plan = resolve(site);} catch {plan=null; }
57
68
  if (!plan) {
58
- next.set(site.id,{at:now()+5*60000,revision:site.revision});
69
+ next.set(site.id,{at:Infinity,revision:site.revision,paused:true});
59
70
  await report({id:site.id,revision:site.revision,status:'unsupported'});
60
71
  continue;
61
72
  }
62
73
  if (!await canRun()) return {deferred:true};
63
- // Set deadline before running to prevent concurrent retries during
64
- // slow site actions. No automatic replay of timed-out actions.
65
74
  next.set(site.id,{at:now()+plan.intervalMs,revision:site.revision});
66
- let status='error';
75
+ let reason='error', releaseSessionId;
67
76
  try {
68
77
  const result=await run({...plan,site});
69
- status=['alive','login_required','unknown'].includes(result?.status)?result.status:'unknown';
78
+ releaseSessionId=result?.releaseSessionId;
79
+ reason=['alive','login_required','unknown','release_error'].includes(result?.status)?result.status:'unknown';
70
80
  } catch { /* No secret URLs, cookies, or Action traces in the popup. */ }
71
- if (status !== 'alive') next.set(site.id,{at:now()+Math.min(plan.intervalMs,5*60000),revision:site.revision});
72
- await report({id:site.id,revision:site.revision,platform:plan.platform,status});
73
- return {id:site.id,status}; // At most one site check per scheduler tick.
81
+ const status=reason==='alive'?'alive':'failed';
82
+ const paused=status==='failed';
83
+ if (reason==='release_error' && releaseSessionId)
84
+ cleanup.set(site.id,{sessionId:releaseSessionId,at:now()+60000});
85
+ next.set(site.id,{at:paused?Infinity:now()+plan.intervalMs,revision:site.revision,paused});
86
+ await report({id:site.id,revision:site.revision,platform:plan.platform,status,reason,paused});
87
+ return {id:site.id,status};
74
88
  }
75
89
  return {idle:true};
76
90
  } finally {active=false;}
@@ -170,11 +170,13 @@ try {
170
170
  // A queue receipt can persist before its browser Session has fully returned to idle.
171
171
  // Allow the daemon's awaited cleanup to finish without touching unrelated Sessions.
172
172
  for(let i=0;i<45;i++) {
173
- const remaining=(await sessions()).filter(x=>!existing.has(x.session_id));
173
+ const remaining=(await sessions()).filter(x=>x.workspace==='WebHelm'&&!existing.has(x.session_id));
174
174
  if(!remaining.length) break;
175
175
  await sleep(1000);
176
176
  }
177
- const leftovers=(await sessions()).filter(x=>!existing.has(x.session_id));
177
+ // Only the shared WebHelm workspace owns these test leases. Application
178
+ // workspaces (e.g. WeChat) may independently start during the gate.
179
+ const leftovers=(await sessions()).filter(x=>x.workspace==='WebHelm'&&!existing.has(x.session_id));
178
180
  assert.equal(leftovers.length,0,'owned Sessions not cleaned: '+JSON.stringify(leftovers));
179
181
  evidence.pass=true;
180
182
  record('ALL_3_MVPS_PASS',{thread_url:evidence.thread_url,real_browser:true,