webhelm 1.0.54 → 1.0.55

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webhelm",
3
- "version": "1.0.54",
3
+ "version": "1.0.55",
4
4
  "description": "Agent browser automation in a visible managed Chrome with persistent JavaScript sessions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,6 +18,7 @@
18
18
  ],
19
19
  "scripts": {
20
20
  "test": "node --test test/node/*.test.mjs test/workspace-manager.test.mjs test/skill/*.test.mjs",
21
+ "test:demo-media": "node --test test/e2e/demo-media.test.mjs",
21
22
  "test:package": "npm pack --dry-run --json",
22
23
  "test:e2e:extension": "node test/e2e/extension-control.e2e.mjs",
23
24
  "test:e2e:chatgpt-mvps": "node scripts/chatgpt-three-mvps.mjs"
@@ -155,6 +155,32 @@ A Session stopped or garbage-collected independently also auto-unsplits.
155
155
 
156
156
  Example:
157
157
  webhelm design stop SESSION_ID`,
158
+ demo: `webhelm demo — record an iPhoneHelm-compatible browser demo
159
+
160
+ Usage:
161
+ webhelm demo SESSION_ID COMMAND [OPTIONS]
162
+
163
+ Commands:
164
+ step --title TITLE Add a numbered step
165
+ spotlight (--ref REF|--label TEXT) [--text TEXT]
166
+ annotate (--ref REF|--label TEXT) --text TEXT
167
+ cursor|highlight (--ref REF|--label TEXT)
168
+ caption|say --text TEXT
169
+ clear|pause|resume|status
170
+ wait --ms 0..30000
171
+ start_recording --output-dir DIR [--fps 1..30]
172
+ stop_recording --output-dir DIR --markcut PATH [--render|--no-render] [--no-voice]
173
+
174
+ Start uses daemon-owned live CDP screencast frames before Demo events and errors
175
+ when actual video is unavailable. stop writes capture.mp4, timeline.json and
176
+ Markcut's video.md, events.json, assets/screen.mp4 and rendered video.mp4 by
177
+ default. --no-render skips the final composition. Target DOM is never decorated
178
+ or input-intercepted.
179
+
180
+ Examples:
181
+ webhelm demo SESSION_ID start_recording --output-dir /tmp/webhelm-demo --fps 15
182
+ webhelm demo SESSION_ID step --title "Open preferences"
183
+ webhelm demo SESSION_ID stop_recording --output-dir /tmp/webhelm-demo --markcut $(command -v markcut)`,
158
184
  session: `webhelm session — manage persistent JavaScript browser Sessions
159
185
 
160
186
  Usage:
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' || group === 'design') && (!command || command === 'help'))) {
77
+ ((group === 'session' || group === 'platform' || group === 'design' || group === 'demo') && (!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));
@@ -177,6 +177,37 @@ async function main(args = process.argv.slice(2)) {
177
177
  return;
178
178
  }
179
179
  }
180
+ if (group === 'demo') {
181
+ const sessionId = command;
182
+ const demoCommand = args[2];
183
+ const valueOptions={step:['--title'],spotlight:['--ref','--label','--text'],annotate:['--ref','--label','--text'],
184
+ caption:['--text'],say:['--text'],cursor:['--ref','--label'],highlight:['--ref','--label'],wait:['--ms'],
185
+ clear:[],pause:[],resume:[],status:[],start_recording:['--output-dir','--fps'],
186
+ stop_recording:['--output-dir','--markcut']};
187
+ const allowed=valueOptions[demoCommand];
188
+ if(!allowed)throw Error(`unknown Demo command: ${String(demoCommand||'')}`);
189
+ const booleanOptions=demoCommand==='stop_recording'?['--render','--no-render','--no-voice']:[];
190
+ for(let index=3;index<args.length;index++){
191
+ const option=args[index];
192
+ if(allowed.includes(option)){
193
+ const value=args[++index];
194
+ if(!value||value.startsWith('--'))throw Error(`${option} requires a value`);
195
+ }else if(!booleanOptions.includes(option))throw Error(`unsupported ${demoCommand} option: ${option}`);
196
+ }
197
+ if(has(args,'--render')&&has(args,'--no-render'))throw Error('Choose --render or --no-render, not both');
198
+ await requireCliSession(sessionId);
199
+ const option = name => arg(args, name);
200
+ return emit(await request({
201
+ op:'demo', session_id:sessionId, command:demoCommand,
202
+ arguments:{
203
+ title:option('--title'), text:option('--text'), ref:option('--ref'),
204
+ label:option('--label'), ms:option('--ms') === undefined ? undefined : Number(option('--ms')),
205
+ },
206
+ output_dir:option('--output-dir'), markcut:option('--markcut'),
207
+ render:has(args,'--render') || !has(args,'--no-render'), voice:!has(args,'--no-voice'),
208
+ fps:option('--fps') === undefined ? undefined : Number(option('--fps')),
209
+ }));
210
+ }
180
211
  if (group === 'platform') {
181
212
  rejectWorkspaceOverride(args);
182
213
  if (command === 'sync') return emit(await syncActions());
@@ -0,0 +1,344 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+
6
+ const MAX_CAPTURE_BYTES = 256 * 1024 * 1024;
7
+ const MAX_FRAME_BYTES = 16 * 1024 * 1024;
8
+
9
+ function run(command, args, timeoutMs = 30000) {
10
+ return new Promise((resolve, reject) => {
11
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
12
+ let stdout = '', stderr = '';
13
+ const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs);
14
+ child.stdout.on('data', data => { if (stdout.length < 1_000_000) stdout += data.toString().slice(0, 1_000_000 - stdout.length); });
15
+ child.stderr.on('data', data => { if (stderr.length < 8_000) stderr += data.toString().slice(0, 8_000 - stderr.length); });
16
+ child.on('error', error => {
17
+ clearTimeout(timer);
18
+ const guidance=command==='markcut'?' (install Markcut or pass --markcut /absolute/path/to/markcut)':command==='say'?' (macOS say is needed for narration)':'';
19
+ reject(new Error(`${command} is unavailable${guidance}: ${error.message}`));
20
+ });
21
+ child.on('close', code => {
22
+ clearTimeout(timer);
23
+ if (code === 0) resolve(stdout);
24
+ else reject(new Error(`${command} exited ${code}: ${stderr.slice(-1000)}`));
25
+ });
26
+ });
27
+ }
28
+
29
+ async function probeMedia(file) {
30
+ const json = JSON.parse(await run('ffprobe', ['-v', 'error', '-show_streams', '-show_format', '-of', 'json', file]));
31
+ const video = json.streams?.find(stream => stream.codec_type === 'video');
32
+ const audio = json.streams?.find(stream => stream.codec_type === 'audio');
33
+ const duration = Number(json.format?.duration || video?.duration || 0);
34
+ if (video?.codec_name !== 'h264') throw new Error(`Capture did not produce an H.264 video stream: ${file}`);
35
+ if (duration <= 0) throw new Error(`Capture has no positive duration: ${file}`);
36
+ const [numerator, denominator] = String(video.avg_frame_rate || '1/1').split('/').map(Number);
37
+ const fps = denominator ? numerator / denominator : numerator;
38
+ if (!Number.isFinite(fps) || fps <= 0 || fps > 60) throw new Error(`Capture has invalid frame-rate metadata: ${fps}`);
39
+ return { width: video.width, height: video.height, fps, duration, has_audio: !!audio, pixel_format: video.pix_fmt };
40
+ }
41
+
42
+ export async function requireMediaCommands() {
43
+ for (const command of ['ffmpeg', 'ffprobe']) {
44
+ try { await run(command, ['-version'], 5000); }
45
+ catch(error) { throw new Error(`Demo capture dependency unavailable: install ${command} (${error.message})`); }
46
+ }
47
+ }
48
+
49
+ function quoteDrawText(value) {
50
+ return String(value).replace(/\\/g, '\\\\').replace(/:/g, '\\:').replace(/'/g, "\\'")
51
+ .replace(/%/g, '\\%').replace(/,/g, '\\,').replace(/;/g, '\\;').replace(/\n/g, '\\n');
52
+ }
53
+
54
+ function annotationFilters(timeline) {
55
+ const filters = [];
56
+ let cursor = null;
57
+ const points = timeline.screen_points || {};
58
+ const scaleX = points.width > 0 ? timeline.width / points.width : 1;
59
+ const scaleY = points.height > 0 ? timeline.height / points.height : 1;
60
+ const startAt = event => ((event.relative_ms || 0) + Number(timeline.video_time_offset_ms || 0)) / 1000;
61
+ const clearedAt = index => {
62
+ const event = timeline.events[index];
63
+ for (let i = index + 1; i < timeline.events.length; i++) {
64
+ const next = timeline.events[i];
65
+ if (next.command === 'clear') return startAt(next);
66
+ if (['step'].includes(event.command) && next.command === 'step') return startAt(next);
67
+ if (['caption', 'say'].includes(event.command) && ['caption', 'say'].includes(next.command)) return startAt(next);
68
+ if (['spotlight', 'annotate', 'highlight'].includes(event.command) && ['spotlight', 'annotate', 'highlight'].includes(next.command)) return startAt(next);
69
+ if (event.command === 'cursor' && next.command === 'cursor') return startAt(next);
70
+ }
71
+ return Number(timeline.duration || 0);
72
+ };
73
+ const enabled = (event, index, fallbackEnd) => {
74
+ const start = startAt(event);
75
+ const end = Math.max(start + 0.001, Math.min(fallbackEnd, clearedAt(index)));
76
+ return `enable='between(t,${start.toFixed(3)},${end.toFixed(3)})'`;
77
+ };
78
+ const frame = value => ({
79
+ x: Math.max(0, Math.round((value.x || 0) * scaleX)),
80
+ y: Math.max(0, Math.round((value.y || 0) * scaleY)),
81
+ width: Math.max(1, Math.round((value.width || 0) * scaleX)),
82
+ height: Math.max(1, Math.round((value.height || 0) * scaleY)),
83
+ });
84
+ const drawText = (value, x, y, size) =>
85
+ `drawtext=text='${quoteDrawText(value)}':fontcolor=white:box=1:boxcolor=black@0.72:boxborderw=12:fontsize=${size}:x=${x}:y=${y}`;
86
+ for (const [index, event] of timeline.events.entries()) {
87
+ if (event.command === 'step') {
88
+ filters.push(`${drawText(`${event.number}. ${event.title}`, 'w-text_w-32', 28, 28)}:${enabled(event, index, timeline.duration)}`);
89
+ } else if (event.command === 'caption' || event.command === 'say') {
90
+ filters.push(`${drawText(event.text, 36, Math.max(0, timeline.height - 82), 24)}:${enabled(event, index, timeline.duration)}`);
91
+ } else if (['spotlight', 'annotate', 'highlight'].includes(event.command) && event.frame) {
92
+ const target = frame(event.frame);
93
+ const end = event.command === 'highlight' ? startAt(event) + 0.65 : timeline.duration;
94
+ if (event.command === 'spotlight') {
95
+ const right = Math.max(0, timeline.width - target.x - target.width);
96
+ const bottom = Math.max(0, timeline.height - target.y - target.height);
97
+ const dim=`color=black@0.48:t=fill:${enabled(event, index, end)}`;
98
+ if(target.y>0)filters.push(`drawbox=x=0:y=0:w=${timeline.width}:h=${target.y}:${dim}`);
99
+ if(bottom>0)filters.push(`drawbox=x=${target.x}:y=${target.y + target.height}:w=${target.width}:h=${bottom}:${dim}`);
100
+ if(target.x>0)filters.push(`drawbox=x=0:y=${target.y}:w=${target.x}:h=${target.height}:${dim}`);
101
+ if(right>0)filters.push(`drawbox=x=${target.x + target.width}:y=${target.y}:w=${right}:h=${target.height}:${dim}`);
102
+ }
103
+ const color = event.command === 'spotlight' ? 'red@0.95' : 'yellow@0.95';
104
+ filters.push(`drawbox=x=${target.x}:y=${target.y}:w=${target.width}:h=${target.height}:color=${color}:t=5:${enabled(event, index, end)}`);
105
+ if (event.command === 'annotate' && event.text) {
106
+ const y = Math.max(4, target.y - 42);
107
+ filters.push(`${drawText(event.text, target.x, y, 20)}:${enabled(event, index, end)}`);
108
+ }
109
+ } else if (event.command === 'cursor' && event.frame) {
110
+ const target = frame(event.frame);
111
+ const to = { x: target.x + Math.round(target.width / 2), y: target.y + Math.round(target.height / 2) };
112
+ const from = cursor || { x: (points.width || 0) * scaleX / 2, y: (points.height || 0) * scaleY * 0.82 };
113
+ const start=startAt(event);
114
+ const progress=`((t-${start.toFixed(3)})/0.48)`;
115
+ const x=`(${from.x}-9)+(${to.x}-${from.x})*${progress}`;
116
+ const y=`(${from.y}-9)+(${to.y}-${from.y})*${progress}`;
117
+ filters.push(`drawbox=x='${x}':y='${y}':w=18:h=18:color=lime@0.95:t=fill:${enabled(event, index, start + 0.48)}`);
118
+ cursor = to;
119
+ }
120
+ }
121
+ return filters.join(',');
122
+ }
123
+
124
+ async function probeAudio(file) {
125
+ const json = JSON.parse(await run('ffprobe', ['-v', 'error', '-show_streams', '-show_format', '-of', 'json', file]));
126
+ return Number(json.format?.duration || json.streams?.find(stream => stream.codec_type === 'audio')?.duration || 0);
127
+ }
128
+
129
+ async function synthesizeVoice(text, file, durationLimit, voice) {
130
+ try { await run('say', ['-v', voice, '-o', `${file}.aiff`, text], 15000); }
131
+ catch(error) { throw new Error(`Narration synthesis unavailable; install or configure macOS say (${error.message})`); }
132
+ try {
133
+ await run('ffmpeg', ['-nostdin', '-hide_banner', '-loglevel', 'error', '-y', '-i', `${file}.aiff`, '-t', durationLimit.toFixed(3), '-c:a', 'aac', '-b:a', '128k', file], 20000);
134
+ const ok=(await fs.stat(file)).size > 0;
135
+ if(ok)await fs.chmod(file,0o600);
136
+ return ok;
137
+ } finally { await fs.unlink(`${file}.aiff`).catch(() => {}); }
138
+ }
139
+
140
+ export async function exportMarkcut(captureFile, timeline, outputDir, options = {}) {
141
+ const markcut = options.markcut;
142
+ if (!markcut) throw new Error('Markcut CLI is unavailable; capture is retained but video.md requires --markcut');
143
+ const meta = await probeMedia(captureFile);
144
+ const output = path.resolve(outputDir, 'markcut');
145
+ const outputStat=await fs.lstat(output).catch(error=>error.code==='ENOENT'?null:Promise.reject(error));
146
+ if(outputStat?.isSymbolicLink())throw new Error(`Markcut output directory must not be a symbolic link: ${output}`);
147
+ if(outputStat&&!outputStat.isDirectory())throw new Error(`Markcut output path is not a directory: ${output}`);
148
+ const prior = outputStat ? await fs.readdir(output) : [];
149
+ if (prior.length) throw new Error(`Markcut output already exists: ${output}`);
150
+ await fs.mkdir(path.join(output, 'assets'), { recursive: true, mode: 0o700 });
151
+ const screen=path.join(output,'assets','screen.mp4');
152
+ await fs.copyFile(captureFile, screen);
153
+ await fs.chmod(screen,0o600);
154
+ const lines = ['# video', 'title:"WebHelm Demo"', `width:${meta.width} height:${meta.height} fps:${meta.fps} layout:series`, '', '## Demo', 'layout:parallel', `- video src:assets/screen.mp4 duration:${meta.duration.toFixed(3)} volume:0`];
155
+ const offset = Number(timeline.video_time_offset_ms || 0);
156
+ const sayEvents = (timeline.events || []).filter(event => event.command === 'say');
157
+ const generatedSpeech=[];
158
+ for (const [index, event] of (timeline.events || []).entries()) {
159
+ if(event.command!=='say')continue;
160
+ const start = ((event.relative_ms || 0) + offset) / 1000;
161
+ if (start < 0 || start >= meta.duration) throw new Error(`Say event ${index} is outside captured video`);
162
+ if (options.voice === false) {
163
+ generatedSpeech.push({ event_index:index, start_seconds:start, pending_text:event.text });
164
+ continue;
165
+ }
166
+ const file = path.join(output, 'assets', `voice-${String(index).padStart(3, '0')}.m4a`);
167
+ const voice = /[\u3400-\u9fff]/.test(event.text) ? 'Tingting' : 'Samantha';
168
+ const ok = await synthesizeVoice(event.text, file, meta.duration - start, voice);
169
+ if (!ok) throw new Error(`Could not synthesize narration for event ${index}`);
170
+ const spoken = Math.min(await probeAudio(file), meta.duration - start);
171
+ if (spoken <= 0) throw new Error(`Synthesized narration for event ${index} has no positive duration`);
172
+ lines.push(`- audio src:assets/${path.basename(file)} start:${start.toFixed(3)} duration:${spoken.toFixed(3)} volume:1`);
173
+ generatedSpeech.push({ event_index:index, start_seconds:start, file:path.basename(file) });
174
+ }
175
+ const videoMd = path.join(output, 'video.md');
176
+ await fs.writeFile(videoMd, `${lines.join('\n')}\n`, { mode: 0o600 });
177
+ const manifest={protocol:timeline.protocol,recording:timeline,video:meta,generated_speech:generatedSpeech,
178
+ overlay:'already composited by WebHelm FFmpeg into screen.mp4',
179
+ unspoken_say_events:generatedSpeech.some(item=>Object.hasOwn(item,'pending_text'))};
180
+ await fs.writeFile(path.join(output, 'events.json'), JSON.stringify(manifest, null, 2), { mode: 0o600 });
181
+ await run(markcut, ['verify', videoMd], 60000);
182
+ if (options.render) {
183
+ const rendered = path.join(output, 'video.mp4');
184
+ await run(markcut, ['render', videoMd, '--output', rendered], 300000);
185
+ await fs.chmod(rendered,0o600);
186
+ const renderMeta = await probeMedia(rendered);
187
+ if (sayEvents.length && options.voice !== false && !renderMeta.has_audio) throw new Error('Markcut render has no narration audio stream');
188
+ }
189
+ return { video_md: videoMd, verified: true, rendered: !!options.render };
190
+ }
191
+
192
+ export class DemoCapture {
193
+ constructor(transport, outputDirectory, fps = 15) {
194
+ this.transport = transport;
195
+ this.outputDirectory = outputDirectory;
196
+ this.fps = fps;
197
+ this.active = false;
198
+ this.owner = randomUUID();
199
+ this.latestFrame = null;
200
+ this.incomingBytes = 0;
201
+ }
202
+
203
+ async start() {
204
+ if (this.active) throw new Error('Demo capture already active');
205
+ this.active = true;
206
+ this.startedWall = Date.now();
207
+ this.startedMono = performance.now();
208
+ this.sourceFile = path.join(this.outputDirectory, '.webhelm-capture-source.mp4');
209
+ this.ownerFile = path.join(this.outputDirectory, '.webhelm-demo-owner');
210
+ await fs.writeFile(this.ownerFile, this.owner, { flag: 'wx', mode: 0o600 });
211
+ const args = ['-nostdin', '-hide_banner', '-loglevel', 'error', '-y', '-f', 'image2pipe', '-framerate', String(this.fps), '-vcodec', 'mjpeg', '-i', 'pipe:0', '-an', '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p', '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '22', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-fs', String(MAX_CAPTURE_BYTES), this.sourceFile];
212
+ this.child = spawn('ffmpeg', args, { stdio: ['pipe', 'ignore', 'pipe'] });
213
+ this.child.stderr.on('data', data => { this.stderr = `${this.stderr || ''}${data}`.slice(-1000); });
214
+ this.child.on('error', error => { this.captureError ||= new Error(`FFmpeg capture failed: ${error.message}`); });
215
+ this.child.on('close', code => {
216
+ this.childClosed = true;
217
+ this.childExitCode = code;
218
+ if (this.active && code !== 0) this.captureError ||= new Error(`Live FFmpeg capture exited ${code}: ${this.stderr || ''}`);
219
+ });
220
+ let firstFrame;
221
+ const gotFirst = new Promise((resolve, reject) => { firstFrame = { resolve, reject }; });
222
+ try {
223
+ await this.transport.startCapture(frame => {
224
+ if (!this.active || this.captureError) return;
225
+ const data = Buffer.from(frame.data, 'base64');
226
+ if (!data.length || data.length > MAX_FRAME_BYTES) {
227
+ this.captureError = new Error('Actual browser frame is empty or exceeds the 16 MiB frame limit');
228
+ return;
229
+ }
230
+ this.incomingBytes += data.length;
231
+ if (this.incomingBytes > MAX_CAPTURE_BYTES) {
232
+ this.captureError = new Error(`Capture exceeded the ${MAX_CAPTURE_BYTES / 1024 / 1024} MiB bounded evidence limit`);
233
+ return;
234
+ }
235
+ this.latestFrame = data;
236
+ firstFrame.resolve();
237
+ });
238
+ let firstTimer;
239
+ try {
240
+ await Promise.race([gotFirst, new Promise((_, reject) => { firstTimer = setTimeout(() => reject(new Error(`No CDP screencast frame received within 5 seconds (${JSON.stringify(this.transport.captureDiagnostics || {})})`)), 5000); })]);
241
+ } finally { clearTimeout(firstTimer); }
242
+ this.nextTickAt = performance.now();
243
+ const interval = 1000 / this.fps;
244
+ const tick = () => {
245
+ if (!this.active) return;
246
+ if (this.captureError) return;
247
+ if (this.child?.stdin.destroyed || this.childClosed) {
248
+ this.captureError ||= new Error('FFmpeg live capture input closed unexpectedly');
249
+ return;
250
+ }
251
+ if (this.latestFrame && !this.waitingForDrain) {
252
+ this.waitingForDrain = !this.child.stdin.write(this.latestFrame);
253
+ if (this.waitingForDrain) this.child.stdin.once('drain', () => { this.waitingForDrain = false; });
254
+ }
255
+ this.nextTickAt += interval;
256
+ this.timer = setTimeout(tick, Math.max(0, this.nextTickAt - performance.now()));
257
+ this.timer.unref?.();
258
+ };
259
+ tick();
260
+ } catch(error) {
261
+ this.captureError = error;
262
+ await this.dispose();
263
+ throw error;
264
+ }
265
+ }
266
+
267
+ async finishProcess() {
268
+ if (!this.child) return;
269
+ if (!this.childClosed) {
270
+ this.child.stdin.end();
271
+ let timer;
272
+ try {
273
+ await Promise.race([
274
+ new Promise(resolve => this.child.once('close', resolve)),
275
+ new Promise((_, reject) => { timer = setTimeout(() => { this.child.kill('SIGKILL'); reject(new Error('FFmpeg capture did not stop within 10 seconds')); }, 10000); }),
276
+ ]);
277
+ } finally { clearTimeout(timer); }
278
+ }
279
+ if (this.childExitCode !== 0) throw new Error(`FFmpeg capture exited ${this.childExitCode}: ${this.stderr || ''}`);
280
+ if (this.captureError) throw this.captureError;
281
+ }
282
+
283
+ async stop({ destination, timeline, markcut, render, voice }) {
284
+ if (!this.active) throw new Error('Demo capture not started');
285
+ this.active = false;
286
+ clearTimeout(this.timer);
287
+ try {
288
+ await this.transport.stopCapture?.();
289
+ const captureDuration = (performance.now() - this.startedMono) / 1000;
290
+ await this.finishProcess();
291
+ const sourceMeta = await probeMedia(this.sourceFile);
292
+ if (captureDuration < 0.2 || sourceMeta.duration <= 0) throw new Error('Captured browser video duration is too short');
293
+ timeline.capture_origin_unix_ms = this.startedWall;
294
+ timeline.video_time_offset_ms = timeline.recording_started_at_unix_ms - this.startedWall;
295
+ timeline.duration = sourceMeta.duration;
296
+ timeline.width = sourceMeta.width;
297
+ timeline.height = sourceMeta.height;
298
+ const filters = annotationFilters(timeline);
299
+ const captureFile = path.join(destination, 'capture.mp4');
300
+ const requiredEnd = Math.max(0, ...(timeline.events || []).map(event => {
301
+ const start = ((event.relative_ms || 0) + Number(timeline.video_time_offset_ms || 0)) / 1000;
302
+ return start + (event.command === 'highlight' ? 0.65 : event.command === 'cursor' ? 0.48 : 0);
303
+ }));
304
+ const pad = Math.max(0, requiredEnd + 0.1 - sourceMeta.duration);
305
+ const tail = pad ? `tpad=stop_mode=clone:stop_duration=${pad.toFixed(3)},` : '';
306
+ const vf = ['-vf', `${filters ? `${filters},` : ''}${tail}scale=trunc(iw/2)*2:trunc(ih/2)*2:in_range=pc:out_range=tv,format=yuv420p`];
307
+ await run('ffmpeg', ['-nostdin', '-hide_banner', '-loglevel', 'error', '-y', '-i', this.sourceFile, ...vf, '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '22', '-fs', String(MAX_CAPTURE_BYTES), '-pix_fmt', 'yuv420p', '-movflags', '+faststart', captureFile], 120000);
308
+ await fs.chmod(captureFile, 0o600);
309
+ await fs.unlink(this.sourceFile).catch(() => {});
310
+ const finalMeta = await probeMedia(captureFile);
311
+ timeline.duration = finalMeta.duration;
312
+ timeline.achieved_fps = finalMeta.fps;
313
+ await fs.writeFile(path.join(destination, 'timeline.json'), JSON.stringify(timeline, null, 2), { mode: 0o600 });
314
+ const exportResult = await exportMarkcut(captureFile, timeline, destination, { markcut, render, voice });
315
+ await fs.unlink(this.ownerFile).catch(() => {});
316
+ this.succeeded = true;
317
+ return { capture_mp4: captureFile, capture_return_code: 0, ...exportResult };
318
+ } catch(error) {
319
+ await this.cleanOutput();
320
+ throw error;
321
+ }
322
+ }
323
+
324
+ async cleanOutput() {
325
+ const owner = await fs.readFile(this.ownerFile, 'utf8').catch(() => '');
326
+ if (owner !== this.owner) return;
327
+ for (const name of ['.webhelm-capture-source.mp4', '.webhelm-demo-owner', 'capture.mp4', 'timeline.json', 'markcut']) {
328
+ await fs.rm(path.join(this.outputDirectory, name), { recursive: name === 'markcut', force: true }).catch(() => {});
329
+ }
330
+ }
331
+
332
+ async dispose() {
333
+ this.active = false;
334
+ clearTimeout(this.timer);
335
+ try { await this.transport.stopCapture?.(); } catch {}
336
+ if (this.child && !this.childClosed) {
337
+ this.child.kill('SIGKILL');
338
+ await new Promise(resolve => this.child.once('close', resolve));
339
+ }
340
+ if (this.succeeded) await fs.unlink(this.ownerFile).catch(() => {});
341
+ else await this.cleanOutput();
342
+ this.latestFrame = null;
343
+ }
344
+ }
@@ -0,0 +1,298 @@
1
+ export const DEMO_PROTOCOL = 'webhelm.demo/1';
2
+ const TEXT_LIMIT = 1500;
3
+ const WAIT_LIMIT = 30000;
4
+ const EVENT_LIMIT = 5000;
5
+ const HIGHLIGHT_MS = 650;
6
+ const CURSOR_MS = 480;
7
+ const MAX_RECORDING_MS = 300000;
8
+
9
+ const DEMO_COMMANDS = new Set([
10
+ 'step', 'spotlight', 'annotate', 'caption', 'say', 'cursor', 'highlight',
11
+ 'clear', 'pause', 'resume', 'wait', 'start_recording', 'stop_recording',
12
+ 'status',
13
+ ]);
14
+ const TARGET_COMMANDS = new Set(['spotlight', 'annotate', 'cursor', 'highlight']);
15
+ const TEXT_COMMANDS = new Set(['caption', 'say', 'annotate']);
16
+ const PAUSE_ALLOWED = new Set(['resume', 'clear', 'stop_recording']);
17
+
18
+ function text(value) {
19
+ return typeof value === 'string' ? value : '';
20
+ }
21
+
22
+ function integer(value) {
23
+ return typeof value === 'number' && Number.isSafeInteger(value) ? value : null;
24
+ }
25
+
26
+ function jsString(value) {
27
+ return JSON.stringify(String(value));
28
+ }
29
+
30
+ function commandError(message) {
31
+ const error = new Error(message);
32
+ error.demoCommand = true;
33
+ return error;
34
+ }
35
+
36
+ function viewportValue(width, height) {
37
+ return { width: integer(width), height: integer(height) };
38
+ }
39
+
40
+ export class DemoEngine {
41
+ constructor(session, transport) {
42
+ this.sessionId = session.session_id;
43
+ this.transport = transport;
44
+ this.targetId = session.targetId;
45
+ this.state = null;
46
+ }
47
+
48
+ requireActive() {
49
+ if (!this.sessionId) throw commandError('Demo requires an active WebHelm Session');
50
+ }
51
+
52
+ ensureOverlay() {
53
+ if (!this.state) {
54
+ this.state = {
55
+ sessionId: this.sessionId,
56
+ targetId: this.targetId,
57
+ recording: false,
58
+ paused: false,
59
+ startedAt: 0,
60
+ stepNumber: 0,
61
+ events: [],
62
+ completed: null,
63
+ overlay: {
64
+ screen_width: this.transport.viewport.width,
65
+ screen_height: this.transport.viewport.height,
66
+ },
67
+ viewport: { ...this.transport.viewport },
68
+ };
69
+ } else if (!this.state.overlay?.screen_width) {
70
+ this.state.overlay = {
71
+ screen_width: this.state.viewport.width || this.transport.viewport.width,
72
+ screen_height: this.state.viewport.height || this.transport.viewport.height,
73
+ };
74
+ }
75
+ return this.state;
76
+ }
77
+
78
+ requireRecording() {
79
+ if (!this.state?.recording) throw commandError('Demo recording not started');
80
+ }
81
+
82
+ newEvent(command, extra = {}) {
83
+ const at = Date.now();
84
+ const relative = this.state?.startedMono ? Math.round(performance.now() - this.state.startedMono) : 0;
85
+ return { command, at_unix_ms: at, relative_ms: relative, ...extra };
86
+ }
87
+
88
+ result(event) {
89
+ return {
90
+ command: event.command,
91
+ event_count: this.state?.events.length || 0,
92
+ at_unix_ms: event.at_unix_ms,
93
+ relative_ms: event.relative_ms,
94
+ overlay_mode: 'webhelm_capture_only',
95
+ };
96
+ }
97
+
98
+ status() {
99
+ return {
100
+ protocol: DEMO_PROTOCOL,
101
+ recording: !!this.state?.recording,
102
+ paused: !!this.state?.paused,
103
+ overlay_active: !!(this.state && Object.keys(this.state.overlay).length > 2),
104
+ recording_started_at_unix_ms: this.state?.startedAt || 0,
105
+ screen_points: { ...(this.state?.viewport || this.transport.viewport || { width: 0, height: 0 }) },
106
+ events: this.state?.events || [],
107
+ completed_recording: this.state?.completed || null,
108
+ };
109
+ }
110
+
111
+ startRecording() {
112
+ this.requireActive();
113
+ if (this.state?.recording) throw commandError('Demo recording already active; stop it before starting again');
114
+ const startedAt = Date.now();
115
+ this.state = {
116
+ sessionId: this.sessionId, targetId: this.targetId, recording: true,
117
+ paused: false, startedAt, startedMono: performance.now(), stepNumber: 0, events: [], overlay: {
118
+ screen_width: this.transport.viewport.width,
119
+ screen_height: this.transport.viewport.height,
120
+ }, viewport: { ...this.transport.viewport },
121
+ capture_deadline_mono: performance.now() + MAX_RECORDING_MS,
122
+ };
123
+ return {
124
+ protocol: DEMO_PROTOCOL,
125
+ recording_started_at_unix_ms: startedAt,
126
+ video_recorded: false,
127
+ events_recorded: true,
128
+ };
129
+ }
130
+
131
+ stopRecording() {
132
+ this.requireRecording();
133
+ const endedAt = Date.now();
134
+ const completed = {
135
+ protocol: DEMO_PROTOCOL,
136
+ recording_started_at_unix_ms: this.state.startedAt,
137
+ recording_ended_at_unix_ms: endedAt,
138
+ video_recorded: false,
139
+ events: this.state.events,
140
+ screen_points: { ...this.state.viewport },
141
+ };
142
+ this.state.completed = completed;
143
+ this.state.recording = false;
144
+ this.state.paused = false;
145
+ this.state.events = [];
146
+ return completed;
147
+ }
148
+
149
+ async resolveTarget(command, args) {
150
+ const ref = text(args.ref);
151
+ const label = text(args.label);
152
+ if (!ref && !label) throw commandError('Demo target requires ref or accessible label');
153
+ if (ref && label) throw commandError('Supply ref or accessible label, not both');
154
+ if (ref.length > 200) throw commandError('Demo ref exceeds 200 characters');
155
+ if (label.length > TEXT_LIMIT) throw commandError('Demo accessible label exceeds 1500 characters');
156
+ if (label && !label.trim()) throw commandError('Demo accessible label must be nonempty');
157
+ if (ref && (!this.transport.snapshotGeneration || this.transport.snapshotTargetId !== this.targetId ||
158
+ !ref.startsWith(`d${this.sessionId}-${this.transport.snapshotGeneration}-`))) {
159
+ throw commandError('Invalid or stale element ref: take a fresh snapshot in the active tab');
160
+ }
161
+ const script = `(() => {
162
+ const wanted=${jsString(ref)};
163
+ const label=${jsString(label)};
164
+ let roots=[];
165
+ const visible=node=>{const r=node.getBoundingClientRect();if(r.width<=0||r.height<=0||r.right<=0||r.bottom<=0||r.left>=innerWidth||r.top>=innerHeight)return false;for(let p=node;p;p=p.parentElement){const s=getComputedStyle(p);if(s.visibility==='hidden'||s.visibility==='collapse'||s.display==='none'||s.opacity==='0'||p.hasAttribute('hidden')||p.hasAttribute('inert')||p.getAttribute('aria-hidden')==='true')return false}return true};
166
+ if(wanted)roots=Array.from(document.querySelectorAll('[data-ref]')).filter(node=>node.getAttribute('data-ref')===wanted&&visible(node));
167
+ else {
168
+ const matches=Array.from(document.querySelectorAll('button,a,input,textarea,select,[role],[tabindex]')).filter(node=>{
169
+ const labelledBy=node.getAttribute('aria-labelledby');
170
+ const labelled=labelledBy?labelledBy.trim().split(/\\s+/).map(id=>document.getElementById(id)?.innerText||'').join(' '):'';
171
+ const accessible=node.getAttribute('aria-label')||labelled||node.getAttribute('title')||node.getAttribute('alt')||node.value||node.labels?.[0]?.innerText||node.innerText||node.textContent||'';
172
+ return visible(node)&&accessible.trim().toLowerCase().includes(label.trim().toLowerCase());
173
+ });
174
+ roots=matches;
175
+ }
176
+ if(roots.length!==1)return {error:roots.length?'ambiguous':'missing'};
177
+ const node=roots[0];
178
+ const rect=node.getBoundingClientRect();
179
+ const style=getComputedStyle(node);
180
+ if(!visible(node))return {error:'invisible'};
181
+ return {frame:{x:rect.x,y:rect.y,width:rect.width,height:rect.height},label:node.getAttribute('aria-label')||node.textContent||''};
182
+ })()`;
183
+ const found = await this.transport.evaluate(script, this.targetId);
184
+ if (found?.error === 'missing') {
185
+ throw commandError(ref ? 'Invalid or stale element ref: take a fresh pilot snapshot' : 'Demo target not found; supply a current ref or accessible label');
186
+ }
187
+ if (found?.error === 'ambiguous') throw commandError('Ambiguous accessible label');
188
+ if (!found?.frame || !(found.frame.width > 0) || !(found.frame.height > 0)) {
189
+ throw commandError('Demo target is invisible or has zero area');
190
+ }
191
+ return found.frame;
192
+ }
193
+
194
+ async execute(command, args = {}) {
195
+ this.requireActive();
196
+ if (!DEMO_COMMANDS.has(command)) throw commandError('Invalid agent.demo command');
197
+ const state = this.ensureOverlay();
198
+ if (command === 'status') return this.status();
199
+ if (command === 'start_recording') return this.startRecording();
200
+ if (command === 'stop_recording') return this.stopRecording();
201
+ if (this.state?.paused && !PAUSE_ALLOWED.has(command)) {
202
+ throw commandError('Demo paused: call resume before adding events');
203
+ }
204
+ if (this.state?.recording && performance.now() >= this.state.capture_deadline_mono) {
205
+ throw commandError(`Demo recording reached ${MAX_RECORDING_MS / 1000} seconds; stop it before starting a new recording`);
206
+ }
207
+
208
+ const allowed = {
209
+ step:['title'], spotlight:['ref','label','text'], annotate:['ref','label','text'],
210
+ caption:['text'], say:['text'], cursor:['ref','label'], highlight:['ref','label'],
211
+ clear:[], pause:[], resume:[], wait:['ms'], status:[], start_recording:[], stop_recording:[],
212
+ }[command];
213
+ const unexpected=Object.keys(args).filter(key=>args[key]!==undefined&&!allowed.includes(key));
214
+ if(unexpected.length)throw commandError(`${command} does not accept argument: ${unexpected[0]}`);
215
+ if(TARGET_COMMANDS.has(command)){
216
+ for(const key of ['ref','label'])if(args[key]!==undefined&&typeof args[key]!=='string')throw commandError(`Demo ${key} must be a string`);
217
+ }
218
+ if(this.state.recording&&this.state.events.length>=EVENT_LIMIT)throw commandError(`Demo event limit reached (${EVENT_LIMIT})`);
219
+
220
+ const event = this.newEvent(command);
221
+ if (TARGET_COMMANDS.has(command)) {
222
+ if (text(args.ref)) event.ref = text(args.ref);
223
+ if (text(args.label)) event.label = text(args.label);
224
+ }
225
+ if (command === 'step') {
226
+ const title = text(args.title);
227
+ if (!title || title.length > TEXT_LIMIT) throw commandError('step requires title (1..1500 characters)');
228
+ event.title = title;
229
+ event.number = ++this.state.stepNumber;
230
+ }
231
+ if (TEXT_COMMANDS.has(command)) {
232
+ const value = text(args.text);
233
+ if (!value || value.length > TEXT_LIMIT) throw commandError('Demo command requires nonempty text (1..1500 characters)');
234
+ event.text = value;
235
+ }
236
+ if (command==='spotlight'&&args.text!==undefined&&typeof args.text!=='string') {
237
+ throw commandError('spotlight text must be a string');
238
+ }
239
+ if (text(args.text).length > TEXT_LIMIT) {
240
+ throw commandError('Demo command requires text at most 1500 characters');
241
+ }
242
+ if (command !== 'annotate' && text(args.text)) event.text = text(args.text);
243
+ if (TARGET_COMMANDS.has(command)) event.frame = await this.resolveTarget(command, args);
244
+ if (command === 'wait') {
245
+ const ms = integer(args.ms);
246
+ if (ms === null || ms < 0 || ms > WAIT_LIMIT) throw commandError('wait requires ms 0..30000');
247
+ event.ms = ms;
248
+ }
249
+
250
+ const overlay = state.overlay;
251
+ if (command === 'step') {
252
+ overlay.step = event.title;
253
+ overlay.step_number = event.number;
254
+ } else if (command === 'caption' || command === 'say') {
255
+ overlay.caption = event.text;
256
+ } else if (['spotlight', 'annotate', 'highlight'].includes(command)) {
257
+ overlay.frame = event.frame;
258
+ overlay.spotlight = command === 'spotlight';
259
+ overlay.tooltip = command === 'annotate' ? event.text : undefined;
260
+ overlay.expires_at_ms = command === 'highlight' ? event.at_unix_ms + HIGHLIGHT_MS : undefined;
261
+ } else if (command === 'cursor') {
262
+ const previous = overlay.cursor || {
263
+ x: this.state.viewport.width / 2,
264
+ y: this.state.viewport.height * 0.82,
265
+ };
266
+ overlay.cursor_from = previous;
267
+ overlay.cursor = {
268
+ x: event.frame.x + event.frame.width / 2,
269
+ y: event.frame.y + event.frame.height / 2,
270
+ };
271
+ overlay.cursor_started_at_ms = event.at_unix_ms;
272
+ overlay.cursor_duration_ms = CURSOR_MS;
273
+ overlay.expires_at_ms = undefined;
274
+ } else if (command === 'clear') {
275
+ state.overlay = {
276
+ screen_width: state.viewport.width,
277
+ screen_height: state.viewport.height,
278
+ };
279
+ }
280
+ if (command === 'pause') this.state.paused = true;
281
+ if (command === 'resume' || command === 'clear') this.state.paused = false;
282
+ if (state.recording) state.events.push(event);
283
+ if (command === 'wait' && event.ms > 0) {
284
+ await new Promise(resolve => setTimeout(resolve, event.ms));
285
+ event.wait_completed_at_unix_ms = Date.now();
286
+ event.wait_completed_relative_ms = Math.round(performance.now() - this.state.startedMono);
287
+ }
288
+ return this.result(event);
289
+ }
290
+
291
+ dispose() {
292
+ try {
293
+ this.transport?.close?.();
294
+ } finally {
295
+ this.state = null;
296
+ }
297
+ }
298
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "WebHelm",
4
- "version": "1.0.54",
4
+ "version": "1.0.55",
5
5
  "description": "Own named Chrome tab-group workspaces and lazy reusable tab pools for browser agents.",
6
6
  "permissions": [
7
7
  "storage",
@@ -16,6 +16,8 @@ import { ensureManagedChrome } from './chrome.mjs';
16
16
  import { ensureExtensionLoaded } from './extension-manager.mjs';
17
17
  import { createManagedChromeGuard } from './managed-chrome-guard.mjs';
18
18
  import { PROFILE_DIR, RUNTIME_DIR, assertProfileConsistency } from './config-paths.mjs';
19
+ import { DemoCapture, requireMediaCommands } from './demo-capture.mjs';
20
+ import { DemoEngine } from './demo-engine.mjs';
19
21
 
20
22
  const ROOT = path.dirname(fileURLToPath(import.meta.url));
21
23
  const PACKAGE_VERSION=JSON.parse(fs.readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
@@ -268,7 +270,7 @@ function makeHelpers(s, observers=null){
268
270
  async fill_input(selector,text){if(!await h.wait_for_element(selector))throw Error(`element not found: ${selector}`);return evaluate(s,`(()=>{const e=document.querySelector(${JSON.stringify(selector)});const set=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),'value')?.set;if(set)set.call(e,${JSON.stringify(String(text))});else e.textContent=${JSON.stringify(String(text))};e.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertText',data:${JSON.stringify(String(text))}}));e.dispatchEvent(new Event('change',{bubbles:true}));return true})()`)},
269
271
  async click(selector){if(!await h.wait_for_element(selector))throw Error(`element not found: ${selector}`);return evaluate(s,`(()=>{const e=document.querySelector(${JSON.stringify(selector)});e.click();return true})()`)},
270
272
  async capture_screenshot(pathname){const b=await connectBrowser();if(s.poisoned || s.closing)throw Error('Session execution expired or closing');const data=await b.send('Page.captureScreenshot',{format:'png'},sidFor(s));if(s.poisoned || s.closing)throw Error('Session execution expired or closing');if(pathname)fs.writeFileSync(pathname,Buffer.from(data.data,'base64'));return data.data},
271
- async snapshot(interactive_only=false){const result=await evaluate(s,`(()=>{let n=0;const xs=[...document.querySelectorAll('button,a,input,textarea,select,[role],[tabindex]')].filter(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width&&r.height&&s.visibility!=='hidden'&&s.display!=='none'});return xs.map(e=>{const id='e'+(++n);e.setAttribute('data-ref',id);const role=e.getAttribute('role')||({BUTTON:'button',A:'link',INPUT:'textbox',TEXTAREA:'textbox',SELECT:'combobox'}[e.tagName]||e.tagName.toLowerCase());const name=e.getAttribute('aria-label')||e.innerText||e.value||e.placeholder||'';return '- '+role+' '+JSON.stringify(name.trim().slice(0,100))+' [ref='+id+']'}).join('\\n')})()`);return result||''},
273
+ async snapshot(interactive_only=false){const generation=++s.snapshotGeneration;s.snapshotTargetId=s.targetId;const sessionId=JSON.stringify(s.session_id);const result=await evaluate(s,`(()=>{let n=0;const generation=${JSON.stringify(generation)},sessionId=${sessionId};const xs=[...document.querySelectorAll('button,a,input,textarea,select,[role],[tabindex]')].filter(e=>{const r=e.getBoundingClientRect(),s=getComputedStyle(e);return r.width&&r.height&&s.visibility!=='hidden'&&s.display!=='none'});return xs.map(e=>{const id='d'+sessionId+'-'+generation+'-e'+(++n);e.setAttribute('data-ref',id);const role=e.getAttribute('role')||({BUTTON:'button',A:'link',INPUT:'textbox',TEXTAREA:'textbox',SELECT:'combobox'}[e.tagName]||e.tagName.toLowerCase());const name=e.getAttribute('aria-label')||e.innerText||e.value||e.placeholder||'';return '- '+role+' '+JSON.stringify(name.trim().slice(0,100))+' [ref='+id+']'}).join('\\n')})()`);return result||''},
272
274
  async workspace_status(){return extensionCall(s,'workspace.status',{name:s.workspace})},
273
275
  async workspace_capacity(){const r=await h.workspace_status();const idle=Array.isArray(r.idleTabIds)?r.idleTabIds.length:null,leased=Array.isArray(r.leasedTabIds)?r.leasedTabIds.length:null;return {name:r.name,poolSize:r.poolSize??null,maxCapacity:r.maxCapacity??r.poolSize??null,physicalTabs:r.physicalTabs??(idle!==null&&leased!==null?idle+leased:null),idle,leased,available:Number.isInteger(r.maxCapacity??r.poolSize)&&leased!==null?Math.max(0,(r.maxCapacity??r.poolSize)-leased):null}} ,
274
276
  async workspace_list(){return extensionCall(s,'workspace.list')},
@@ -335,6 +337,161 @@ function makeHelpers(s, observers=null){
335
337
  Object.defineProperty(h,'targetId',{get:()=>s.targetId});
336
338
  return h;
337
339
  }
340
+
341
+ function demoTransport(s) {
342
+ return {
343
+ get viewport() { return s.demoViewport || { width: 0, height: 0 }; },
344
+ get snapshotGeneration() { return s.snapshotGeneration || 0; },
345
+ get snapshotTargetId() { return s.snapshotTargetId; },
346
+ get captureDiagnostics() { return { events:s.demoCaptureEventCount||0, lastOwner:s.demoCaptureLastOwner||null }; },
347
+ async evaluate(expression, targetId) { return evaluate(s, expression, targetId || s.targetId); },
348
+ async inspectViewport() {
349
+ const viewport = await evaluate(s, '({width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio})', s.targetId);
350
+ if (!Number.isInteger(viewport?.width) || viewport.width <= 0 ||
351
+ !Number.isInteger(viewport?.height) || viewport.height <= 0) {
352
+ throw Error('Demo viewport is unavailable');
353
+ }
354
+ s.demoViewport = viewport;
355
+ return viewport;
356
+ },
357
+ async startCapture(onFrame) {
358
+ const browser = await connectBrowser();
359
+ const sessionId = sidFor(s, s.targetId);
360
+ await browser.send('Target.activateTarget', { targetId: s.targetId });
361
+ await browser.send('Page.bringToFront', {}, sessionId);
362
+ const disposer = browser.on('Page.screencastFrame', (params, owner) => {
363
+ s.demoCaptureEventCount=(s.demoCaptureEventCount||0)+1;
364
+ s.demoCaptureLastOwner=owner||null;
365
+ if (owner !== sessionId) return;
366
+ onFrame({ data: params.data, width: params.metadata?.deviceWidth, height: params.metadata?.deviceHeight });
367
+ browser.send('Page.screencastFrameAck', { sessionId: params.sessionId }, sessionId).catch(() => {});
368
+ });
369
+ s.demoCaptureDisposer = disposer;
370
+ try {
371
+ await browser.send('Page.startScreencast', {
372
+ format: 'jpeg', everyNthFrame: 1, maxWidth: 1280, maxHeight: 720,
373
+ }, sessionId);
374
+ // Request a compositor paint so the live screencast emits its first frame; only screencast events are encoded.
375
+ await browser.send('Page.captureScreenshot', { format: 'jpeg', quality: 80 }, sessionId);
376
+ } catch(error) {
377
+ s.demoCaptureDisposer = null;
378
+ disposer();
379
+ throw error;
380
+ }
381
+ },
382
+ async stopCapture() {
383
+ const disposer = s.demoCaptureDisposer;
384
+ s.demoCaptureDisposer = null;
385
+ disposer?.();
386
+ const browser = await connectBrowser();
387
+ await browser.send('Page.stopScreencast', {}, sidFor(s, s.targetId)).catch(() => {});
388
+ },
389
+ };
390
+ }
391
+
392
+ function activeDemoEngine(s) {
393
+ const engine = s.demoEngine;
394
+ if (!engine) throw Error('Demo Engine is not initialized for this Session');
395
+ return engine;
396
+ }
397
+
398
+ function integerOption(value, name, minimum, maximum) {
399
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
400
+ throw Error(`${name} requires an integer ${minimum}..${maximum}`);
401
+ }
402
+ return value;
403
+ }
404
+
405
+ function requiredPathOption(value, name) {
406
+ if (typeof value !== 'string' || !value.trim()) throw Error(`${name} requires a nonempty path`);
407
+ return path.resolve(value);
408
+ }
409
+
410
+ async function demoRequest(req) {
411
+ const s = sessions.get(req.session_id);
412
+ if (!s || s.closing || s.poisoned) throw Error(`unknown session_id: ${req.session_id} (missing or closing)`);
413
+ if (s.workspace !== 'WebHelm') throw Error('Demo Engine supports WebHelm CLI-owned Sessions only');
414
+ s.inFlight++;
415
+ try {
416
+ return await s.mutex.run(async() => {
417
+ if (s.closing || s.poisoned) throw Error('session closing or expired');
418
+ s.last_used_at = Date.now();
419
+ const demoCommand = String(req.command || '');
420
+ if (String(req.command || '') === 'start_recording') {
421
+ requiredPathOption(req.output_dir, 'start_recording output_dir');
422
+ integerOption(req.fps === undefined ? 15 : req.fps, 'fps', 1, 30);
423
+ await requireMediaCommands();
424
+ }
425
+ if (demoCommand === 'start_recording') {
426
+ const outputDir = requiredPathOption(req.output_dir, 'start_recording output_dir');
427
+ let outputStats=null;
428
+ try { outputStats=fs.lstatSync(outputDir); }
429
+ catch(error) { if(error.code!=='ENOENT')throw error; }
430
+ if (outputStats?.isSymbolicLink()) throw Error('Capture output directory must not be a symbolic link');
431
+ if (!outputStats) fs.mkdirSync(outputDir, { recursive: true, mode: 0o700 });
432
+ else if (!outputStats.isDirectory()) throw Error(`Capture output path is not a directory: ${outputDir}`);
433
+ else if (fs.readdirSync(outputDir).length) throw Error(`Capture output already exists: ${outputDir}`);
434
+ fs.chmodSync(outputDir, 0o700);
435
+ }
436
+ if (demoCommand === 'stop_recording') {
437
+ const outputDir = requiredPathOption(req.output_dir, 'stop_recording output_dir');
438
+ if (outputDir !== s.demoOutputDir) throw Error('stop_recording output_dir must match start_recording output_dir');
439
+ if (!s.demoCapture) throw Error('Demo capture unavailable; recording cannot honestly produce video');
440
+ requiredPathOption(req.markcut, 'markcut');
441
+ }
442
+ if (!s.demoEngine) {
443
+ const transport = demoTransport(s);
444
+ s.demoViewport = await transport.inspectViewport();
445
+ s.demoEngine = new DemoEngine(s, transport);
446
+ }
447
+ const engine = activeDemoEngine(s);
448
+ if (engine.state?.recording && s.targetId !== engine.targetId) {
449
+ throw Error('Demo recording owns the tab active at start; stop it before switching tabs');
450
+ }
451
+ engine.targetId = s.targetId;
452
+ const previousEngine = activeDemoEngine(s);
453
+ const result = req.command === 'start_recording' ? null : await previousEngine.execute(demoCommand, req.arguments || {});
454
+ if (req.command === 'start_recording') {
455
+ const outputDir = requiredPathOption(req.output_dir, 'start_recording output_dir');
456
+ const capture = new DemoCapture(engine.transport, outputDir, integerOption(req.fps === undefined ? 15 : req.fps, 'fps', 1, 30));
457
+ try {
458
+ await capture.start();
459
+ const started = await engine.execute(demoCommand, req.arguments || {});
460
+ s.demoCapture = capture;
461
+ s.demoOutputDir = outputDir;
462
+ started.capture_started = true;
463
+ return started;
464
+ } catch(error) {
465
+ previousEngine.dispose();
466
+ await capture.dispose().catch(() => {});
467
+ throw error;
468
+ }
469
+ }
470
+ if (req.command === 'stop_recording') {
471
+ const outputDir = requiredPathOption(req.output_dir, 'stop_recording output_dir');
472
+ const capture = s.demoCapture;
473
+ try {
474
+ const exported = await capture.stop({
475
+ destination: outputDir,
476
+ timeline: result,
477
+ markcut: req.markcut,
478
+ render: req.render === true,
479
+ voice: req.voice !== false,
480
+ fps: integerOption(req.fps === undefined ? 15 : req.fps, 'fps', 1, 30),
481
+ markcut: requiredPathOption(req.markcut, 'markcut'),
482
+ });
483
+ result.video_recorded = true;
484
+ result.export = exported;
485
+ } finally {
486
+ await capture.dispose();
487
+ s.demoCapture = null;
488
+ s.demoOutputDir = null;
489
+ }
490
+ }
491
+ return result;
492
+ });
493
+ } finally { s.inFlight--; s.last_used_at = Date.now(); }
494
+ }
338
495
  const EXTENSION_ID='kkkpgmhpoeceojalkpfdidffdfnlgdog';
339
496
  const EXTENSION_PREFIX=`chrome-extension://${EXTENSION_ID}/`;
340
497
  let debuggerSession=null;
@@ -434,7 +591,7 @@ async function createSession(req={}) {
434
591
  const s={session_id:sid, workspace:req.workspace||await defaultWorkspaceName(), targetId:null,
435
592
  rootTargetId:null, workspaceSupported:false,targets:new Set(), attachments:new Map(), eventDisposers:new Map(),
436
593
  leasedTabs:new Map(), idleUrls:new Map(), mutex:new Mutex(), events:[], namespace:null,context:null,
437
- inFlight:0, pendingEffects:0, closing:false, poisoned:false, last_used_at:Date.now()};
594
+ inFlight:0, pendingEffects:0, closing:false, poisoned:false, last_used_at:Date.now(), snapshotGeneration:0, snapshotTargetId:null};
438
595
  let targetId,lease;
439
596
  try {
440
597
  if(await extensionSupported()) {
@@ -608,6 +765,13 @@ async function closeSessionOwned(s){
608
765
  const returnedTabs=s.leasedTabs.size;
609
766
  const closedChildTabs=s.targets.size - returnedTabs;
610
767
  await s.mutex.run(async()=>{
768
+ try {
769
+ await s.demoCapture?.dispose();
770
+ s.demoCaptureDisposer?.();
771
+ s.demoEngine?.dispose();
772
+ } finally {
773
+ s.demoCapture=null;s.demoCaptureDisposer=null;s.demoEngine=null;s.demoOutputDir=null;
774
+ }
611
775
  const browser=await connectBrowser();
612
776
  // Return managed tabs to their original Extension pool; keep their CDP targets.
613
777
  for(const tid of [...s.targets]){
@@ -747,7 +911,7 @@ function visibleSessions() {
747
911
  }));
748
912
  }
749
913
  async function pollExtensionControl() {
750
- if (controlPollActive || shuttingDown) return;
914
+ if (controlPollActive || shuttingDown || process.env.WEBHELM_NO_PROFILE_EXTENSION_PROBE === '1') return;
751
915
  controlPollActive = true;
752
916
  try {
753
917
  // Extension records are authoritative only on successful contact. A
@@ -898,7 +1062,7 @@ export async function handle(req){
898
1062
  setTimeout(()=>process.kill(process.pid,'SIGTERM'),150).unref();
899
1063
  return {ok:true,stopping:true,pid:process.pid};
900
1064
  }
901
- 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}`)}}
1065
+ 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'demo':return demoRequest(req);case'platform-run':return runPlatform(req);default:throw Error(`unknown op: ${req.op}`)}}
902
1066
  export function serve(conn) {
903
1067
  let buffer = '', dispatched = false;
904
1068
  conn.on('error',()=>{ /* A disconnected client must not crash the daemon. */ });