-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.mjs
More file actions
225 lines (203 loc) · 8.37 KB
/
config.mjs
File metadata and controls
225 lines (203 loc) · 8.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/**
* Video Recording Configuration — Generic Template
*
* Copy this file into scripts/video_recording/ and customise:
* - BASE_URL: your app's local dev server URL
* - Add project-specific setup helpers (e.g. loginUser, createTestData, cleanup)
*
* Sound files are resolved from the skill folder (.agents/skills/video-recording/)
* via SKILL_DIR — no copies of the MP3s are needed in the project.
*/
export const BASE_URL = 'http://localhost:3000'; // ← change per project
export const VIDEO_DIR = './videos';
// Firefox passes browser-version checks that headless Chromium can fail.
export { firefox as browser } from 'playwright';
// Viewport presets
export const DEVICES = {
mobile: { viewport: { width: 390, height: 844 } },
tablet: { viewport: { width: 768, height: 1024 } },
desktop: { viewport: { width: 1280, height: 720 } },
};
// ---------------------------------------------------------------------------
// Timing helpers
// ---------------------------------------------------------------------------
export async function pause(ms = 1000) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// ---------------------------------------------------------------------------
// Audio tracker
//
// Usage:
// const tracker = createClickTracker();
// tracker.trackClick('button-label');
// tracker.trackTypingStart('field-label');
// tracker.trackTypingEnd();
// await saveAndAddSound(videoPath, tracker); // in finally block
// ---------------------------------------------------------------------------
export function createClickTracker() {
const clicks = [];
const typingEvents = [];
const startTime = Date.now();
const elapsed = () => (Date.now() - startTime) / 1000;
return {
trackClick: (label = '') => {
const time = elapsed();
clicks.push({ time, label });
console.log(` 🔊 Click tracked at ${time.toFixed(2)}s${label ? ` (${label})` : ''}`);
},
trackTypingStart: (label = '') => {
const time = elapsed();
typingEvents.push({ type: 'start', time, label });
console.log(` ⌨️ Typing started at ${time.toFixed(2)}s${label ? ` (${label})` : ''}`);
},
trackTypingEnd: () => {
const time = elapsed();
typingEvents.push({ type: 'end', time });
console.log(` ⌨️ Typing ended at ${time.toFixed(2)}s`);
},
getClicks: () => clicks,
getTypingEvents: () => typingEvents,
saveClickData: async (videoPath) => {
const { writeFile } = await import('fs/promises');
const clickDataPath = videoPath.replace(/\.webm$/, '.clicks.json');
await writeFile(clickDataPath, JSON.stringify({
clicks: clicks.map(c => ({ time: c.time, label: c.label })),
typingEvents,
clickCount: clicks.length,
typingCount: typingEvents.filter(e => e.type === 'start').length,
totalDuration: elapsed(),
}, null, 2));
console.log(` 🔊 Audio data saved: ${clickDataPath}`);
return clickDataPath;
},
};
}
// ---------------------------------------------------------------------------
// Cursor overlay
// ---------------------------------------------------------------------------
/**
* Inject a visible arrow cursor that follows Playwright's mouse position.
* Uses addInitScript so it survives navigations automatically.
*/
export async function injectCursor(page) {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="24" viewBox="0 0 20 24"><path d="M 2 2 L 2 20 L 7 15 L 10 22 L 13 21 L 10 14 L 16 14 Z" fill="white" stroke="black" stroke-width="1.5" stroke-linejoin="round"/></svg>`;
const dataUrl = `data:image/svg+xml,${encodeURIComponent(svg)}`;
await page.addInitScript((url) => {
function setup() {
if (document.getElementById('pw-cursor')) return;
const el = document.createElement('div');
el.id = 'pw-cursor';
el.style.cssText = [
'position:fixed', 'top:0', 'left:0', 'width:20px', 'height:24px',
'pointer-events:none', 'z-index:2147483647',
`background-image:url("${url}")`, 'background-size:contain',
'background-repeat:no-repeat', 'display:block',
].join(';');
document.body.appendChild(el);
document.addEventListener('mousemove', e => {
el.style.left = e.clientX + 'px';
el.style.top = e.clientY + 'px';
});
}
document.readyState === 'loading'
? document.addEventListener('DOMContentLoaded', setup)
: setup();
}, dataUrl);
}
// ---------------------------------------------------------------------------
// Natural interactions
// ---------------------------------------------------------------------------
/**
* Move the mouse smoothly to the centre of a locator's bounding box.
*/
export async function moveToElement(page, locator, steps = 12) {
const box = await locator.boundingBox();
if (!box) return;
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps });
}
/**
* Move cursor to element, then click and record the event.
*/
export async function naturalClick(page, locator, clickTracker, label = '') {
await locator.scrollIntoViewIfNeeded();
await moveToElement(page, locator);
await pause(150);
clickTracker.trackClick(label);
await locator.click();
}
/**
* Move cursor to field, focus it, then type character-by-character with
* randomised delays (40–110 ms) to look like a fast human typist.
* Never use locator.fill() in flow scripts — it looks like paste.
*/
export async function naturalFill(page, locator, text, clickTracker, label = '') {
await locator.scrollIntoViewIfNeeded();
await moveToElement(page, locator);
await pause(100);
await locator.click();
await pause(120);
clickTracker.trackTypingStart(label);
for (const char of text) {
await locator.pressSequentially(char, { delay: 0 });
await pause(40 + Math.random() * 70);
}
await pause(150);
clickTracker.trackTypingEnd();
}
// ---------------------------------------------------------------------------
// Audio post-processing
// ---------------------------------------------------------------------------
/**
* Save click/typing timestamps and run add_click_sounds.mjs via ffmpeg.
* Call in the finally block of each flow script after renaming the video.
*
* Requires: ffmpeg installed. Sound files are read from the skill folder.
*/
export async function saveAndAddSound(videoPath, clickTracker) {
const { exec } = await import('child_process');
const { promisify } = await import('util');
const { access } = await import('fs/promises');
const execAsync = promisify(exec);
const path = await import('path');
const { fileURLToPath } = await import('url');
await clickTracker.saveClickData(videoPath);
const scriptDir = path.default.dirname(fileURLToPath(import.meta.url));
// Sound files live in the skill folder regardless of where this script is copied.
const skillDir = path.default.join(scriptDir, '..', '..', '.agents', 'skills', 'video-recording');
const clickSound = path.default.join(skillDir, 'computer-mouse-click-352734.mp3');
try {
await access(clickSound);
} catch {
console.log(' ⚠ Sound files not found in skill folder – skipping audio.');
return;
}
const soundScript = path.default.join(scriptDir, 'add_click_sounds.mjs');
try {
const { stdout, stderr } = await execAsync(
`node "${soundScript}" "${videoPath}"`,
{ maxBuffer: 50 * 1024 * 1024 }
);
if (stdout) console.log(stdout.trim());
if (stderr) console.log(stderr.trim());
} catch (err) {
console.error(' ⚠ Sound post-processing failed:', err.message.split('\n')[0]);
}
}
// ---------------------------------------------------------------------------
// Project-specific helpers (add below when scaffolding)
// ---------------------------------------------------------------------------
//
// Example — login via a test helper endpoint:
//
// export async function loginUser(page, email, role = 'user') {
// const res = await page.request.post(`${BASE_URL}/test/login`, { data: { email, role } });
// const data = await res.json();
// if (!data.success) throw new Error(`Login failed: ${JSON.stringify(data)}`);
// await page.goto(data.login_url);
// await page.waitForLoadState('networkidle');
// return data;
// }
//
// export async function cleanup(page) {
// await page.request.delete(`${BASE_URL}/test/cleanup`).catch(() => {});
// }