webhelm 1.0.54 → 1.0.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/package.json +2 -1
- package/runtime/cli-help.mjs +31 -4
- package/runtime/cli.mjs +32 -1
- package/runtime/demo-capture.mjs +344 -0
- package/runtime/demo-engine.mjs +298 -0
- package/runtime/extension/manifest.json +1 -1
- package/runtime/node-daemon.mjs +273 -36
- package/runtime/user-helpers.mjs +72 -0
- package/runtime/network-observer.mjs +0 -55
package/README.md
CHANGED
|
@@ -36,6 +36,15 @@ npx --yes webhelm@latest session stop SESSION_ID
|
|
|
36
36
|
Use `npx skills add lalalic/webhelm --skill webhelm` to install agent guidance.
|
|
37
37
|
The Extension is bundled with the npm Runtime and staged by WebHelm Daemon at `~/.local/webhelm/extension`. The Skill lives **in this repo** at `skills/webhelm/SKILL.md`. No Chrome Web Store publication or manual Extension installation is required.
|
|
38
38
|
|
|
39
|
+
### Browser helpers and local extensions
|
|
40
|
+
|
|
41
|
+
Use semantic built-in browser helpers for navigation, input, tab allocation,
|
|
42
|
+
file selection, frame evaluation and page initialization. Raw CDP is internal
|
|
43
|
+
to the Runtime. Reviewed local user helper modules can provide additional
|
|
44
|
+
diagnostics through a Runtime-enforced, current-tab broker. See
|
|
45
|
+
[Browser helper development](docs/browser-helpers.md) for the API, migration
|
|
46
|
+
table, policy boundary and test requirements.
|
|
47
|
+
|
|
39
48
|
### Automatic npm Runtime upgrades (macOS)
|
|
40
49
|
|
|
41
50
|
`webhelm setup` installs two independent LaunchAgents: the offline Chrome health
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webhelm",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.56",
|
|
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"
|
package/runtime/cli-help.mjs
CHANGED
|
@@ -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:
|
|
@@ -219,11 +245,12 @@ Options:
|
|
|
219
245
|
|
|
220
246
|
The JavaScript context persists across exec calls. Browser helpers are async:
|
|
221
247
|
snapshot, page_info, goto_url, wait_for_load, wait_for_element,
|
|
222
|
-
fill_input, click, js,
|
|
223
|
-
switch_tab, close_tab, upload_file, type_text,
|
|
224
|
-
wait.
|
|
248
|
+
fill_input, click, js, new_tab, current_tab, list_tabs,
|
|
249
|
+
switch_tab, activate_tab, close_tab, upload_file, type_text, press_key,
|
|
250
|
+
add_init_script, list_frames, js_in_frame, capture_screenshot, events, wait.
|
|
225
251
|
Read 'snapshot()' before using element references and refresh after navigation.
|
|
226
|
-
|
|
252
|
+
Raw CDP is private; use the semantic helpers. Reviewed local helper modules
|
|
253
|
+
can be installed in ~/.local/webhelm/helpers/ (see Skill and developer docs).
|
|
227
254
|
Output: JSON with execution status and captured result/stdout.
|
|
228
255
|
|
|
229
256
|
Example:
|
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
|
+
}
|