webhelm 1.0.50 → 1.0.52
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/package.json +1 -1
- package/runtime/cli-help.mjs +68 -1
- package/runtime/cli.mjs +18 -1
- package/runtime/extension/control-channel.mjs +3 -2
- package/runtime/extension/control-rpc.mjs +36 -5
- package/runtime/extension/design-mode.mjs +279 -0
- package/runtime/extension/manifest.json +1 -1
- package/runtime/extension/popup-data.mjs +5 -9
- package/runtime/extension/popup.html +4 -0
- package/runtime/extension/popup.mjs +58 -16
- package/runtime/extension/service-worker.mjs +7 -3
- package/runtime/extension/workspace-manager.mjs +27 -18
- package/runtime/extension/workspace-summary.mjs +14 -0
- package/runtime/extension-manager.mjs +1 -1
- package/runtime/node-daemon.mjs +86 -2
- package/runtime/platform-delivery-queue.mjs +38 -28
- package/runtime/queue-registry.mjs +2 -1
- package/runtime/session-lifecycle.mjs +10 -0
- package/scripts/chatgpt-three-mvps.mjs +7 -2
package/package.json
CHANGED
package/runtime/cli-help.mjs
CHANGED
|
@@ -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') {
|
|
@@ -82,11 +82,12 @@ export class ControlChannel {
|
|
|
82
82
|
return this.serialize(async () => {
|
|
83
83
|
if (typeof queueId !== 'string' || !queueId) throw new Error('Queue item is required');
|
|
84
84
|
const state = this.normalize(await this.read());
|
|
85
|
+
// The popup can lag the daemon. A vanished item is always a no-op.
|
|
86
|
+
if (!(state.queue || []).some(item => item.id === queueId))
|
|
87
|
+
return {ok:true,skipped:true};
|
|
85
88
|
if (state.request) throw new Error('Another WebHelm operation is already running');
|
|
86
89
|
if (!Number.isFinite(state.daemon?.seenAt) || this.now() - state.daemon.seenAt >= FRESH_MS)
|
|
87
90
|
throw new Error('WebHelm daemon is not responding');
|
|
88
|
-
if (!(state.queue || []).some(item => item.id === queueId && ['QUEUED','WAITING','BLOCKED','UNCERTAIN'].includes(item.state)))
|
|
89
|
-
throw new Error('Queue item is no longer cancellable');
|
|
90
91
|
const request = {id:this.makeId(), action:'queue-cancel', queueId, state:'pending', createdAt:this.now()};
|
|
91
92
|
await this.save({...state, request, lastResult:null});
|
|
92
93
|
return {id:request.id,state:'pending'};
|
|
@@ -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
|
-
|
|
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');
|
|
@@ -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
|
+
}
|
|
@@ -55,14 +55,14 @@ export async function setStoredSite(chromeApi, url, enabled) {
|
|
|
55
55
|
return {id:origin,enabled:Boolean(enabled)};
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
const priority = {
|
|
58
|
+
const priority = {SENDING:0,CHECKING:0,QUEUED:1};
|
|
59
59
|
function threadKey(item) {
|
|
60
60
|
// Queue groups are provided by registered Platform Policies.
|
|
61
61
|
return `${item.platform||'Queue'}\u0000${item.group||item.id}`;
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
export function compactQueue(items, {expanded=false,maxHeads=8}={}) {
|
|
65
|
-
const all=Array.isArray(items) ? items : [];
|
|
65
|
+
const all=Array.isArray(items) ? items.filter(item=>['QUEUED','CHECKING','SENDING'].includes(item.state)) : [];
|
|
66
66
|
const threads=new Map();
|
|
67
67
|
for (const [index,item] of all.entries()) {
|
|
68
68
|
const key=threadKey(item);
|
|
@@ -75,9 +75,8 @@ export function compactQueue(items, {expanded=false,maxHeads=8}={}) {
|
|
|
75
75
|
const visible=expanded ? heads.flatMap(x=>x.items) : heads.slice(0,Math.max(1,maxHeads)).map(x=>x.head);
|
|
76
76
|
const headFor=new Map(heads.flatMap(x=>x.items.map(item=>[item.id,x.head])));
|
|
77
77
|
const behind=new Map(heads.map(x=>[x.head.id,x.count-1]));
|
|
78
|
-
const failed=all.filter(x=>x.state==='FAILED').length;
|
|
79
78
|
return {visible,total:all.length,threads:threads.size,behind,headFor,
|
|
80
|
-
hidden:all.length-visible.length
|
|
79
|
+
hidden:all.length-visible.length};
|
|
81
80
|
}
|
|
82
81
|
|
|
83
82
|
// Statuses describe what the user can do, not internal retry counters.
|
|
@@ -86,17 +85,14 @@ export function queueStatusText(item,{head=item,remaining=0}={}) {
|
|
|
86
85
|
const state=String(item.state||'QUEUED').toUpperCase();
|
|
87
86
|
const following=head.id!==item.id;
|
|
88
87
|
let message;
|
|
89
|
-
if(following
|
|
90
|
-
else if(following) message='Waiting behind earlier message';
|
|
88
|
+
if(following) message='Waiting behind earlier message';
|
|
91
89
|
else message=({
|
|
92
|
-
FAILED:'Action failed — not retried',
|
|
93
90
|
SENDING:'Sending',
|
|
94
91
|
CHECKING:'Checking delivery',
|
|
95
|
-
WAITING:'Waiting to send',
|
|
96
92
|
QUEUED:'Queued to send',
|
|
97
93
|
})[state]||state.toLowerCase();
|
|
98
94
|
if(!following && remaining>0)
|
|
99
|
-
message+=' · '+remaining+' later message'+(remaining===1?'':'s')+
|
|
95
|
+
message+=' · '+remaining+' later message'+(remaining===1?'':'s')+' waiting';
|
|
100
96
|
return message;
|
|
101
97
|
}
|
|
102
98
|
|
|
@@ -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; }
|
|
@@ -99,8 +129,8 @@ function renderKeptSites(sites, busy, connected) {
|
|
|
99
129
|
|
|
100
130
|
function renderWorkspaces(workspaces, busy, connected) {
|
|
101
131
|
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;
|
|
132
|
+
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]),
|
|
133
|
+
])) + ':' + JSON.stringify(currentSites.map(site=>site.id)) + ':' + canControlSites + ':' + canEnableDesign + ':' + busy + ':' + connected;
|
|
104
134
|
if (signature === lastSignature) return;
|
|
105
135
|
lastSignature = signature;
|
|
106
136
|
const target = el('workspace-list');
|
|
@@ -139,17 +169,32 @@ function renderWorkspaces(workspaces, busy, connected) {
|
|
|
139
169
|
sessionRow.append(details);
|
|
140
170
|
if (workspace.name === 'WebHelm' && siteId) {
|
|
141
171
|
const enabled=currentSites.some(site=>site.id===siteId);
|
|
142
|
-
const toggle=
|
|
172
|
+
const toggle=iconButton('keepalive',busy||!connected||!canControlSites,async()=>{
|
|
143
173
|
try {
|
|
144
174
|
await rpc('workspace.control.site.toggle',{sessionId:session.session_id,enabled:!enabled});
|
|
145
175
|
lastSignature='';refresh();
|
|
146
176
|
} catch(error){el('message').textContent=error.message;}
|
|
147
|
-
}
|
|
148
|
-
|
|
177
|
+
},!canControlSites
|
|
178
|
+
? 'Update the running WebHelm daemon to manage Keep Alive sites'
|
|
179
|
+
: enabled ? 'Disable Keep Alive for this site' : 'Enable Keep Alive for this site',enabled);
|
|
149
180
|
sessionRow.append(toggle);
|
|
150
181
|
}
|
|
151
|
-
|
|
152
|
-
|
|
182
|
+
if (session.tabId && (session.designActive || canEnableDesign)) {
|
|
183
|
+
const designButton=iconButton('split',
|
|
184
|
+
busy || !connected,async()=>{
|
|
185
|
+
try {
|
|
186
|
+
await rpc('workspace.control.design.toggle',{sessionId:session.session_id});
|
|
187
|
+
lastSignature='';
|
|
188
|
+
refresh();
|
|
189
|
+
} catch(error){el('message').textContent=error.message;}
|
|
190
|
+
},session.designActive
|
|
191
|
+
? 'Exit Design Mode: restore ChatGPT tab'
|
|
192
|
+
: 'Design Mode: split Session with active ChatGPT thread',session.designActive);
|
|
193
|
+
sessionRow.append(designButton);
|
|
194
|
+
}
|
|
195
|
+
sessionRow.append(iconButton('stop', busy || !connected,
|
|
196
|
+
() => showConfirmation('stop', {sessionId:session.session_id}),
|
|
197
|
+
'Stop Session'));
|
|
153
198
|
row.append(sessionRow);
|
|
154
199
|
}
|
|
155
200
|
target.append(row);
|
|
@@ -229,8 +274,7 @@ function renderQueue(items, busy, connected) {
|
|
|
229
274
|
const remove=actionButton('×',false,async()=>{
|
|
230
275
|
try{
|
|
231
276
|
const result=await rpc('workspace.control.queueCancel',{queueId:item.id});
|
|
232
|
-
if(
|
|
233
|
-
el('message').textContent='Waiting for WebHelm daemon…';
|
|
277
|
+
if(result.id)el('message').textContent='Waiting for WebHelm daemon…';
|
|
234
278
|
}catch(error){el('message').textContent=error.message;}
|
|
235
279
|
refresh();
|
|
236
280
|
},'queue-remove');
|
|
@@ -238,18 +282,15 @@ function renderQueue(items, busy, connected) {
|
|
|
238
282
|
}
|
|
239
283
|
const title=row.querySelector('.queue-title');
|
|
240
284
|
title.textContent=item.title||platform+' message';
|
|
241
|
-
title.title=
|
|
242
|
-
(item.state==='FAILED'?' — Action failed; no automatic retry.':'');
|
|
285
|
+
title.title=item.title||platform+' message';
|
|
243
286
|
row.dataset.queueId=item.id;
|
|
244
287
|
row.dataset.state=item.state;
|
|
245
|
-
row.classList.toggle('queue-failed',item.state==='FAILED');
|
|
246
288
|
const elapsed=formatQueueElapsed(item.created_at,queueOpenedAtSeconds);
|
|
247
289
|
const attempts=Math.max(0,Number(item.attempts)||0);
|
|
248
|
-
row.querySelector('.queue-meta').textContent=
|
|
290
|
+
row.querySelector('.queue-meta').textContent='('+(elapsed??'–')+'/'+attempts+')';
|
|
249
291
|
const remove=row.querySelector('.queue-remove');
|
|
250
|
-
|
|
251
|
-
remove.
|
|
252
|
-
remove.title=cancellable?'Remove '+title.textContent+' from queue':'Cannot remove a running or completed submission';
|
|
292
|
+
remove.disabled=busy||!connected;
|
|
293
|
+
remove.title='Cancel '+title.textContent+' (best effort before sending)';
|
|
253
294
|
remove.setAttribute('aria-label',remove.title);
|
|
254
295
|
if(row.parentElement!==rows)rows.append(row);
|
|
255
296
|
}
|
|
@@ -268,6 +309,7 @@ async function refresh() {
|
|
|
268
309
|
el('daemon-status').className = `daemon-state ${state.connected ? 'online' : 'offline'}`;
|
|
269
310
|
const busy = Boolean(state.request);
|
|
270
311
|
canControlSites=Array.isArray(state.keptSites);
|
|
312
|
+
canEnableDesign=Boolean(state.canEnableDesign);
|
|
271
313
|
currentSites=await readKeptSites(chrome,state.keptSites);
|
|
272
314
|
renderKeptSites(currentSites,busy,state.connected);
|
|
273
315
|
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.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
|
}
|
|
@@ -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
|
|
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:
|
|
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
|
|
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:
|
|
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:
|
|
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:
|
|
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
|
|
584
|
-
const removable = Math.min(idle.length, tabs
|
|
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:
|
|
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
|
|
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:
|
|
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:
|
|
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
|
|
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:
|
|
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
|
|
package/runtime/node-daemon.mjs
CHANGED
|
@@ -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;
|
|
@@ -792,7 +876,7 @@ export async function handle(req){
|
|
|
792
876
|
setTimeout(()=>process.kill(process.pid,'SIGTERM'),150).unref();
|
|
793
877
|
return {ok:true,stopping:true,pid:process.pid};
|
|
794
878
|
}
|
|
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}`)}}
|
|
879
|
+
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
880
|
export function serve(conn) {
|
|
797
881
|
let buffer = '', dispatched = false;
|
|
798
882
|
conn.on('error',()=>{ /* A disconnected client must not crash the daemon. */ });
|
|
@@ -55,7 +55,7 @@ const dbPolicy = {
|
|
|
55
55
|
}
|
|
56
56
|
const meta = display(this.definition, config);
|
|
57
57
|
const tail = db.prepare('SELECT * FROM items WHERE group_key=? ORDER BY seq DESC LIMIT 1').get(meta.group);
|
|
58
|
-
if (tail && config.mergeable === true &&
|
|
58
|
+
if (tail && config.mergeable === true && tail.state === 'QUEUED' &&
|
|
59
59
|
tail.lease_owner === null && typeof this.definition.merge === 'function') {
|
|
60
60
|
const previous = JSON.parse(tail.payload_json);
|
|
61
61
|
if (previous.mergeable === true) {
|
|
@@ -81,26 +81,32 @@ const dbPolicy = {
|
|
|
81
81
|
return {ok:true,status:'queued',queue_id:id,state:'QUEUED',group:meta.group};
|
|
82
82
|
},
|
|
83
83
|
claim(db, owner, now, leaseSeconds) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
84
|
+
const retries=this.definition.retries??1;
|
|
85
|
+
// Expired sending leases have already counted as an attempt. Never exceed the policy budget.
|
|
86
|
+
db.prepare(`UPDATE items SET state=CASE WHEN attempts<=? THEN 'QUEUED' ELSE 'FAILED' END,
|
|
87
|
+
lease_owner=NULL,lease_until=NULL,next_check_at=?,receipt=COALESCE(receipt,'send_interrupted')
|
|
88
|
+
WHERE state='SENDING' AND lease_until<=?`).run(retries,now+(this.definition.intervalMs??10000)/1000,now);
|
|
89
|
+
// Expired read-only checks count as failures but cannot have clicked Send.
|
|
90
|
+
db.prepare(`UPDATE items SET state=CASE WHEN attempts<? THEN 'QUEUED' ELSE 'FAILED' END,
|
|
91
|
+
attempts=attempts+1,lease_owner=NULL,lease_until=NULL,next_check_at=?,receipt='validate_interrupted'
|
|
92
|
+
WHERE state='CHECKING' AND lease_until<=?`).run(retries,now+(this.definition.intervalMs??10000)/1000,now);
|
|
93
|
+
const row = db.prepare(`SELECT item.* FROM items item WHERE item.state='QUEUED' AND item.next_check_at<=?
|
|
87
94
|
AND NOT EXISTS (SELECT 1 FROM items older WHERE older.group_key=item.group_key AND older.seq<item.seq
|
|
88
95
|
AND (older.state NOT IN ('SENT','FAILED','CANCELLED') OR (older.state='SENT' AND older.next_check_at>?)))
|
|
89
96
|
ORDER BY item.seq LIMIT 1`).get(now,now);
|
|
90
97
|
if (!row) return null;
|
|
91
|
-
db.prepare("UPDATE items SET state='CHECKING',lease_owner=?,lease_until
|
|
98
|
+
db.prepare("UPDATE items SET state='CHECKING',lease_owner=?,lease_until=? WHERE id=?")
|
|
92
99
|
.run(owner,now+leaseSeconds,row.id);
|
|
93
100
|
return db.prepare('SELECT * FROM items WHERE id=?').get(row.id);
|
|
94
101
|
},
|
|
95
102
|
cancel(db, id) {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
return {ok:true,queue_id:id,state:'CANCELLED'};
|
|
103
|
+
// Best effort: a read-only CHECKING action can be cancelled before it sends.
|
|
104
|
+
// An already SENDING action must finish; the caller sees a silent no-op.
|
|
105
|
+
const result=db.prepare("UPDATE items SET state='CANCELLED',lease_owner=NULL,lease_until=NULL WHERE id=? AND state IN ('QUEUED','CHECKING')").run(id);
|
|
106
|
+
return {ok:true,queue_id:id,...(result.changes ? {state:'CANCELLED'} : {skipped:true})};
|
|
101
107
|
},
|
|
102
108
|
list(db) {
|
|
103
|
-
const items = db.prepare("SELECT * FROM items WHERE state
|
|
109
|
+
const items = db.prepare("SELECT * FROM items WHERE state IN ('QUEUED','CHECKING','SENDING') ORDER BY seq").all();
|
|
104
110
|
return {ok:true,items:items.map(row => ({id:row.id,queue_id:row.id,group:row.group_key,
|
|
105
111
|
state:row.state,attempts:row.attempts,created_at:row.created_at,
|
|
106
112
|
receipt:row.receipt,title:row.title,url:row.url}))};
|
|
@@ -123,6 +129,8 @@ export class PlatformDeliveryQueue extends DurableQueueCore {
|
|
|
123
129
|
attempts INTEGER NOT NULL DEFAULT 0, receipt TEXT);
|
|
124
130
|
CREATE INDEX IF NOT EXISTS queue_group_fifo ON items(group_key,seq);
|
|
125
131
|
CREATE TABLE IF NOT EXISTS request_keys(idem_key TEXT PRIMARY KEY,queue_id TEXT NOT NULL,payload_hash TEXT NOT NULL);`);
|
|
132
|
+
// Discard obsolete WAITING entries; never silently replay stale sends.
|
|
133
|
+
db.exec("UPDATE items SET state='CANCELLED' WHERE state='WAITING'");
|
|
126
134
|
const adapter=Object.create(dbPolicy);
|
|
127
135
|
super(db,adapter,now,{concurrency:concurrency??definition.concurrency??1,intervalMs:intervalMs??definition.intervalMs??10000});
|
|
128
136
|
adapter.definition=definition;
|
|
@@ -170,15 +178,15 @@ export class PlatformDeliveryQueue extends DurableQueueCore {
|
|
|
170
178
|
})};
|
|
171
179
|
}
|
|
172
180
|
has(id) { return Boolean(this.db.prepare('SELECT 1 FROM items WHERE id=?').get(id)); }
|
|
173
|
-
transition(id,owner,from,to,{delay=0,receipt=null}={}) {
|
|
181
|
+
transition(id,owner,from,to,{delay=0,receipt=null,incrementAttempt=false}={}) {
|
|
174
182
|
const now=this.now();
|
|
175
183
|
return this._transaction(()=>{
|
|
176
184
|
const row=this.db.prepare('SELECT state,lease_owner,lease_until FROM items WHERE id=?').get(id);
|
|
177
185
|
if (!row || row.state!==from || row.lease_owner!==owner || row.lease_until<=now) throw Error('stale queue lease');
|
|
178
|
-
this.db.prepare('UPDATE items SET state=?,lease_owner=?,lease_until=?,next_check_at=?,receipt
|
|
179
|
-
.run(to,['SENT','FAILED','
|
|
180
|
-
['SENT','FAILED','
|
|
181
|
-
now+delay,receipt,id);
|
|
186
|
+
this.db.prepare('UPDATE items SET state=?,lease_owner=?,lease_until=?,next_check_at=?,receipt=?,attempts=attempts+? WHERE id=?')
|
|
187
|
+
.run(to,['SENT','FAILED','QUEUED'].includes(to)?null:owner,
|
|
188
|
+
['SENT','FAILED','QUEUED'].includes(to)?null:now+this.leaseSeconds,
|
|
189
|
+
now+delay,receipt,incrementAttempt?1:0,id);
|
|
182
190
|
});
|
|
183
191
|
}
|
|
184
192
|
process(item) { return this._process(item); }
|
|
@@ -201,23 +209,17 @@ export class PlatformDeliveryQueue extends DurableQueueCore {
|
|
|
201
209
|
sid=started.session_id??started.sessionId;
|
|
202
210
|
if (!sid) throw Error('queue Session creation did not return session_id');
|
|
203
211
|
const checked=await this.runAction({platform:this.platform,action:definition.validate,config,session_id:sid});
|
|
204
|
-
if (checked?.result?.ok !== true)
|
|
205
|
-
// A failed read-only gate must not silently drop its FIFO head.
|
|
206
|
-
this.transition(item.id,item.lease_owner,'CHECKING','WAITING',{
|
|
207
|
-
delay:this.intervalMs/1000,receipt:'validate_error',
|
|
208
|
-
});
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
212
|
+
if (checked?.result?.ok !== true) throw Error('validate_failed');
|
|
211
213
|
const value=checked.result.value;
|
|
212
214
|
const ready=checked?.result?.ok === true && (value === true || value?.ready === true || value?.status === 'ready');
|
|
213
215
|
if (!ready) {
|
|
214
|
-
this.transition(item.id,item.lease_owner,'CHECKING','
|
|
216
|
+
this.transition(item.id,item.lease_owner,'CHECKING','QUEUED',{
|
|
215
217
|
delay:this.intervalMs/1000,
|
|
216
218
|
receipt:'not_ready',
|
|
217
219
|
});
|
|
218
220
|
return;
|
|
219
221
|
}
|
|
220
|
-
this.transition(item.id,item.lease_owner,'CHECKING','SENDING');
|
|
222
|
+
this.transition(item.id,item.lease_owner,'CHECKING','SENDING',{incrementAttempt:true});
|
|
221
223
|
const outcome=await this.runAction({platform:this.platform,action:definition.action,
|
|
222
224
|
config:typeof definition.execute==='function'?definition.execute(config):config,session_id:sid});
|
|
223
225
|
if (outcome?.result?.ok!==true ||
|
|
@@ -229,9 +231,17 @@ export class PlatformDeliveryQueue extends DurableQueueCore {
|
|
|
229
231
|
} catch(error) {
|
|
230
232
|
const diagnostic='Error;fingerprint='+createHash('sha256').update(String(error)).digest('hex').slice(0,16);
|
|
231
233
|
try {
|
|
232
|
-
const row=this.db.prepare('SELECT state FROM items WHERE id=?').get(item.id);
|
|
233
|
-
|
|
234
|
-
|
|
234
|
+
const row=this.db.prepare('SELECT state,attempts FROM items WHERE id=?').get(item.id);
|
|
235
|
+
const retries=definition.retries??1;
|
|
236
|
+
if (row?.state==='SENDING') {
|
|
237
|
+
const retry=row.attempts<=retries;
|
|
238
|
+
this.transition(item.id,item.lease_owner,'SENDING',retry?'QUEUED':'FAILED',{
|
|
239
|
+
delay:retry?this.intervalMs/1000:0,receipt:diagnostic});
|
|
240
|
+
} else if (row?.state==='CHECKING') {
|
|
241
|
+
const retry=row.attempts<retries;
|
|
242
|
+
this.transition(item.id,item.lease_owner,'CHECKING',retry?'QUEUED':'FAILED',{
|
|
243
|
+
delay:retry?this.intervalMs/1000:0,receipt:diagnostic,incrementAttempt:true});
|
|
244
|
+
}
|
|
235
245
|
} catch(transitionError) { this.onDispatchError(transitionError); }
|
|
236
246
|
} finally {
|
|
237
247
|
clearInterval(heartbeat);
|
|
@@ -43,6 +43,7 @@ function validPolicy(definition, platform, root) {
|
|
|
43
43
|
}
|
|
44
44
|
if (definition.concurrency!==undefined && (!Number.isInteger(definition.concurrency) || definition.concurrency<1 || definition.concurrency>32)) throw TypeError('concurrency must be 1..32');
|
|
45
45
|
if (definition.intervalMs!==undefined && (!Number.isInteger(definition.intervalMs) || definition.intervalMs<100 || definition.intervalMs>3600000)) throw TypeError('intervalMs must be 100..3600000');
|
|
46
|
+
if (definition.retries!==undefined && (!Number.isInteger(definition.retries) || definition.retries<0 || definition.retries>100)) throw TypeError('retries must be 0..100');
|
|
46
47
|
}
|
|
47
48
|
|
|
48
49
|
export class PlatformQueueRegistry {
|
|
@@ -147,7 +148,7 @@ export class PlatformQueueRegistry {
|
|
|
147
148
|
list() { return {ok:true,items:[...this.records.values()].flatMap(({instance})=>instance.list().items)}; }
|
|
148
149
|
cancel(id) {
|
|
149
150
|
for (const {instance} of this.records.values()) if (instance.has(id)) return instance.cancel(id);
|
|
150
|
-
return {ok:
|
|
151
|
+
return {ok:true,queue_id:id,skipped:true};
|
|
151
152
|
}
|
|
152
153
|
activeCount() { return [...this.records.values()].reduce((sum,{instance})=>sum+instance.active.size,0); }
|
|
153
154
|
async stopScheduler() { this.paused=true;await Promise.all([...this.records.values()].map(({instance})=>instance.stopScheduler())); }
|
|
@@ -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
|
+
}
|
|
@@ -60,6 +60,10 @@ try {
|
|
|
60
60
|
assert.ok(sid,'failed to create owned real Chrome Session');
|
|
61
61
|
evidence.session_ids.push(sid);
|
|
62
62
|
record('session_started',{session_id:sid});
|
|
63
|
+
// Session creation schedules initial navigation; wait for it to settle before
|
|
64
|
+
// the new-thread Action navigates with its own ?prompt= URL.
|
|
65
|
+
const initialLoad=await ipc('exec',{session_id:sid,code:'await wait_for_load();'});
|
|
66
|
+
assert.equal(initialLoad?.ok,true,'new-thread browser Session did not finish initial load');
|
|
63
67
|
async function runDirect(action,config,session_id=sid) {
|
|
64
68
|
const value=await ipc('platform-run',{platform:'chatgpt',action,config,session_id,workspace:'WebHelm'});
|
|
65
69
|
const result=value?.result;
|
|
@@ -163,8 +167,9 @@ try {
|
|
|
163
167
|
states:[a.state,b.state],receipts:[a.receipt,b.receipt],
|
|
164
168
|
ordered_seq:[a.seq,b.seq],isolated_harness:isolatedManual};
|
|
165
169
|
record('MVP3_PASS',evidence.mvp3);
|
|
166
|
-
//
|
|
167
|
-
|
|
170
|
+
// A queue receipt can persist before its browser Session has fully returned to idle.
|
|
171
|
+
// Allow the daemon's awaited cleanup to finish without touching unrelated Sessions.
|
|
172
|
+
for(let i=0;i<45;i++) {
|
|
168
173
|
const remaining=(await sessions()).filter(x=>!existing.has(x.session_id));
|
|
169
174
|
if(!remaining.length) break;
|
|
170
175
|
await sleep(1000);
|