@clipy/cli 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -570,7 +570,7 @@ By default it captures the primary display. Target one window instead:
570
570
  ```bash
571
571
  clipy sources # list displays + windows with ids
572
572
  clipy session start --source mac-screen --window "Chrome" --title "Fix walkthrough"
573
- # … the agent drives Chrome while Clipy records its initial screen area …
573
+ # … the agent drives Chrome while Clipy records that window by itself …
574
574
  clipy mark "reproduced the bug"
575
575
  clipy mark "fix applied — retesting"
576
576
  clipy session stop # uploads, prints the share link
@@ -616,8 +616,58 @@ of a different tab: worse than no evidence, because the tally vouches for the wr
616
616
  **Clipy will never bring a window or tab to the front for you.** It can't know which
617
617
  tab/page/simulator you mean, and on `--source mac-screen` it may not be recording a browser
618
618
  at all — focusing the right surface is the caller's job. Do it before `session start`, then
619
- confirm with the reported title. (The title and recorded screen area are fixed at start time;
620
- moving the window does not move the recording, and anything entering that area is filmed.)
619
+ confirm with the reported title. (The title is fixed at start time. When the start JSON reports
620
+ `windowCapture: "window"`, a `--window` recording is that window's own pixels: it follows the
621
+ window if it moves and windows on top of it are not filmed, so it need not stay in front, but
622
+ it must show the right tab. `"area"`, from a Clipy app too old to record a window by itself or
623
+ from ffmpeg older than 5.1 on Linux, films whatever is on top of it, so keep it in front.)
624
+
625
+ ## Record the real screen on Linux: a window, a display, or a private screen
626
+
627
+ `--source screen` works on Linux without any Clipy app: the CLI records the X
628
+ display itself with ffmpeg (`x11grab`). The same flag means the Mac app on macOS,
629
+ so an agent can use one spelling everywhere.
630
+
631
+ ```bash
632
+ clipy doctor # the "screen" rows say what this machine can do
633
+ clipy sources --json # displays + windows on $DISPLAY
634
+ clipy session start --source screen --window 2097155 --title "Fix walkthrough"
635
+ clipy mark "reproduced the bug" --observed "Save stays disabled" --verdict fail
636
+ clipy session stop
637
+ ```
638
+
639
+ - **A window** (`--window <id|title|app>`) is that window's own pixels. Under a
640
+ compositor (GNOME, KDE, picom, xcompmgr) a window that is covered still records
641
+ in full and nothing on top of it appears, so the user can keep working. Without a
642
+ compositor the covered part is black. The picture follows the window when it
643
+ moves; a resize starts a new segment that is fitted into the first frame, and a
644
+ closed window ends the take and uploads it. Each of these lands as an `[auto]`
645
+ mark. Listing windows needs `xwininfo` and `xprop` (`sudo apt install x11-utils`);
646
+ capturing by id needs FFmpeg 5.1+, and older builds record the window's area of
647
+ the screen instead (with a warning).
648
+ - **A display** (`--display <id>`, default the first monitor) is that monitor of
649
+ the X screen.
650
+ - **A private screen** (`--virtual-display`, sized by `--width`/`--height`) starts
651
+ an Xvfb display only the agent draws on: the user's screen, cursor and keyboard
652
+ are never involved, which also makes it the way to record GUI work on a server,
653
+ container or CI. `session run` hands the command `DISPLAY`:
654
+
655
+ ```bash
656
+ clipy session run --source screen --virtual-display --width 1600 --height 900 -- \
657
+ sh -c 'chromium --app=http://localhost:3000 & sleep 2; ./drive-the-ui.sh'
658
+ ```
659
+
660
+ It needs `Xvfb` (`sudo apt install xvfb`); with `picom` or `xcompmgr` installed,
661
+ Clipy also starts a compositor on it so covered windows record in full.
662
+ - `--x-display :N` records any other X display, for example one your harness
663
+ already runs.
664
+
665
+ Linux screen recordings are silent; narrate with `clipy mark`. Wayland sessions
666
+ only let an app read the real screen through the desktop's own consent dialog, so
667
+ `--source screen` refuses the real screen there and points at `--virtual-display`
668
+ or `--x-display`. On Windows there is no real-screen path for agents yet: use
669
+ `--source chrome-for-clipy` for a browser tab, `--url` for a headless page, or
670
+ `clipy proof` with your own tool's video or screenshots.
621
671
 
622
672
  ## Scripting
623
673
 
@@ -0,0 +1,277 @@
1
+ /**
2
+ * A minimal Chrome DevTools Protocol client for Chrome for Clipy.
3
+ *
4
+ * Playwright's connectOverCDP attaches to EVERY target in the browser before
5
+ * it returns, so one stuck tab (a hung renderer, an embedded view, another
6
+ * extension's page) blocks it indefinitely. Chrome for Clipy is long-lived and
7
+ * full of the person's own tabs, so the extension path talks to the browser
8
+ * endpoint directly and attaches only to the tabs it creates.
9
+ *
10
+ * Uses the global WebSocket where Node has one (22+) and otherwise a small
11
+ * RFC 6455 client over node:http, so the CLI keeps its Node 18 floor and its
12
+ * zero runtime dependencies.
13
+ */
14
+ import { request } from "node:http";
15
+ import { randomBytes } from "node:crypto";
16
+ function openWithGlobalWebSocket(url, onMessage, onClose, signal) {
17
+ const WS = globalThis.WebSocket;
18
+ const ws = new WS(url);
19
+ signal.addEventListener("abort", () => ws.close(), { once: true });
20
+ return new Promise((resolve, reject) => {
21
+ ws.onopen = () => resolve({ send: (t) => ws.send(t), close: () => ws.close() });
22
+ ws.onerror = () => reject(new Error(`could not open ${url}`));
23
+ ws.onmessage = (e) => onMessage(String(e.data));
24
+ ws.onclose = () => onClose("socket closed");
25
+ });
26
+ }
27
+ /** Client side of RFC 6455: masked text frames out; text, continuation,
28
+ * ping and close frames in. Enough for CDP, which sends JSON text frames. */
29
+ function openWithHttpUpgrade(url, onMessage, onClose, signal) {
30
+ const target = new URL(url);
31
+ return new Promise((resolve, reject) => {
32
+ // A stalled handshake must not keep the process alive after its timeout.
33
+ signal.addEventListener("abort", () => req.destroy(), { once: true });
34
+ const req = request({
35
+ host: target.hostname,
36
+ port: target.port,
37
+ path: target.pathname + target.search,
38
+ headers: {
39
+ Connection: "Upgrade",
40
+ Upgrade: "websocket",
41
+ "Sec-WebSocket-Version": "13",
42
+ "Sec-WebSocket-Key": randomBytes(16).toString("base64"),
43
+ },
44
+ });
45
+ req.on("error", reject);
46
+ req.on("response", (res) => reject(new Error(`websocket upgrade refused (${res.statusCode})`)));
47
+ req.on("upgrade", (_res, socket, head) => {
48
+ if (signal.aborted) {
49
+ socket.destroy();
50
+ return;
51
+ }
52
+ let buffer = head.length ? Buffer.from(head) : Buffer.alloc(0);
53
+ let fragments = [];
54
+ const writeFrame = (opcode, payload) => {
55
+ const mask = randomBytes(4);
56
+ const len = payload.length;
57
+ const header = len < 126
58
+ ? Buffer.from([0x80 | opcode, 0x80 | len])
59
+ : len < 65536
60
+ ? Buffer.from([0x80 | opcode, 0x80 | 126, len >> 8, len & 0xff])
61
+ : (() => {
62
+ const h = Buffer.alloc(10);
63
+ h[0] = 0x80 | opcode;
64
+ h[1] = 0x80 | 127;
65
+ h.writeBigUInt64BE(BigInt(len), 2);
66
+ return h;
67
+ })();
68
+ const masked = Buffer.alloc(len);
69
+ for (let i = 0; i < len; i++)
70
+ masked[i] = payload[i] ^ mask[i % 4];
71
+ socket.write(Buffer.concat([header, mask, masked]));
72
+ };
73
+ socket.on("data", (chunk) => {
74
+ buffer = Buffer.concat([buffer, chunk]);
75
+ for (;;) {
76
+ if (buffer.length < 2)
77
+ return;
78
+ const fin = (buffer[0] & 0x80) !== 0;
79
+ const opcode = buffer[0] & 0x0f;
80
+ let len = buffer[1] & 0x7f;
81
+ let offset = 2;
82
+ if (len === 126) {
83
+ if (buffer.length < 4)
84
+ return;
85
+ len = buffer.readUInt16BE(2);
86
+ offset = 4;
87
+ }
88
+ else if (len === 127) {
89
+ if (buffer.length < 10)
90
+ return;
91
+ len = Number(buffer.readBigUInt64BE(2));
92
+ offset = 10;
93
+ }
94
+ if (buffer.length < offset + len)
95
+ return;
96
+ const payload = buffer.subarray(offset, offset + len);
97
+ buffer = buffer.subarray(offset + len);
98
+ if (opcode === 0x8) {
99
+ socket.end();
100
+ return;
101
+ }
102
+ if (opcode === 0x9) {
103
+ writeFrame(0xa, Buffer.from(payload));
104
+ continue;
105
+ }
106
+ if (opcode === 0x1 || opcode === 0x0) {
107
+ fragments.push(Buffer.from(payload));
108
+ if (fin) {
109
+ onMessage(Buffer.concat(fragments).toString("utf8"));
110
+ fragments = [];
111
+ }
112
+ }
113
+ }
114
+ });
115
+ socket.on("close", () => onClose("socket closed"));
116
+ socket.on("error", () => onClose("socket error"));
117
+ resolve({
118
+ send: (text) => writeFrame(0x1, Buffer.from(text, "utf8")),
119
+ close: () => {
120
+ try {
121
+ writeFrame(0x8, Buffer.alloc(0));
122
+ }
123
+ catch {
124
+ // already gone
125
+ }
126
+ socket.end();
127
+ },
128
+ });
129
+ });
130
+ req.end();
131
+ });
132
+ }
133
+ export class CdpConnection {
134
+ transport;
135
+ nextId = 1;
136
+ pending = new Map();
137
+ closedReason = null;
138
+ constructor(transport) {
139
+ this.transport = transport;
140
+ }
141
+ static async connect(port, timeoutMs = 10_000) {
142
+ const version = (await (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(timeoutMs) })).json());
143
+ if (!version.webSocketDebuggerUrl)
144
+ throw new Error("Chrome for Clipy did not report a debugger endpoint");
145
+ const conn = new CdpConnection(null);
146
+ const onMessage = (text) => conn.dispatch(text);
147
+ const onClose = (reason) => conn.failAll(reason);
148
+ const open = typeof globalThis.WebSocket === "function"
149
+ ? openWithGlobalWebSocket
150
+ : openWithHttpUpgrade;
151
+ const abort = new AbortController();
152
+ try {
153
+ conn.transport = await withTimeout(open(version.webSocketDebuggerUrl, onMessage, onClose, abort.signal), timeoutMs, "connecting to Chrome for Clipy");
154
+ }
155
+ catch (error) {
156
+ abort.abort();
157
+ throw error;
158
+ }
159
+ return conn;
160
+ }
161
+ dispatch(text) {
162
+ let msg;
163
+ try {
164
+ msg = JSON.parse(text);
165
+ }
166
+ catch {
167
+ return;
168
+ }
169
+ if (typeof msg.id !== "number")
170
+ return;
171
+ const waiter = this.pending.get(msg.id);
172
+ if (!waiter)
173
+ return;
174
+ this.pending.delete(msg.id);
175
+ if (msg.error)
176
+ waiter.reject(new Error(msg.error.message ?? "CDP error"));
177
+ else
178
+ waiter.resolve(msg.result ?? {});
179
+ }
180
+ failAll(reason) {
181
+ this.closedReason = reason;
182
+ for (const waiter of this.pending.values())
183
+ waiter.reject(new Error(`Chrome for Clipy connection lost (${reason})`));
184
+ this.pending.clear();
185
+ }
186
+ send(method, params = {}, sessionId, timeoutMs = 30_000) {
187
+ if (this.closedReason || !this.transport) {
188
+ return Promise.reject(new Error(`Chrome for Clipy connection lost (${this.closedReason ?? "not open"})`));
189
+ }
190
+ const id = this.nextId++;
191
+ const result = new Promise((resolve, reject) => {
192
+ this.pending.set(id, { resolve: resolve, reject });
193
+ });
194
+ this.transport.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
195
+ return withTimeout(result, timeoutMs, method).finally(() => this.pending.delete(id));
196
+ }
197
+ close() {
198
+ this.transport?.close();
199
+ this.failAll("closed");
200
+ }
201
+ }
202
+ function withTimeout(promise, ms, what) {
203
+ let timer;
204
+ return Promise.race([
205
+ promise,
206
+ new Promise((_, reject) => {
207
+ timer = setTimeout(() => reject(new Error(`${what} timed out after ${Math.round(ms / 1000)}s`)), ms);
208
+ }),
209
+ ]).finally(() => clearTimeout(timer));
210
+ }
211
+ /** A tab this client created and attached to, and only that tab. */
212
+ export class CdpTab {
213
+ conn;
214
+ targetId;
215
+ sessionId;
216
+ constructor(conn, targetId, sessionId) {
217
+ this.conn = conn;
218
+ this.targetId = targetId;
219
+ this.sessionId = sessionId;
220
+ }
221
+ /** Opens `url` as a background tab (never activated) and attaches to it. */
222
+ static async openBackground(conn, url) {
223
+ const { targetId } = await conn.send("Target.createTarget", { url, background: true });
224
+ try {
225
+ const { sessionId } = await conn.send("Target.attachToTarget", { targetId, flatten: true });
226
+ return new CdpTab(conn, targetId, sessionId);
227
+ }
228
+ catch (error) {
229
+ await conn.send("Target.closeTarget", { targetId }).catch(() => { });
230
+ throw error;
231
+ }
232
+ }
233
+ /** Evaluates an expression in the page, awaiting a returned promise. A
234
+ * navigation can swap the document mid-call; that is retried, not failed. */
235
+ async evaluate(expression, timeoutMs = 30_000) {
236
+ for (let attempt = 1;; attempt++) {
237
+ try {
238
+ return await this.evaluateOnce(expression, timeoutMs);
239
+ }
240
+ catch (error) {
241
+ const message = error instanceof Error ? error.message : String(error);
242
+ if (attempt >= 4 || !/context was destroyed|Cannot find context|Inspected target navigated/i.test(message))
243
+ throw error;
244
+ await new Promise((r) => setTimeout(r, 250 * attempt));
245
+ }
246
+ }
247
+ }
248
+ async evaluateOnce(expression, timeoutMs) {
249
+ const res = await this.conn.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }, this.sessionId, timeoutMs);
250
+ if (res.exceptionDetails) {
251
+ throw new Error(res.exceptionDetails.exception?.description ?? res.exceptionDetails.text ?? "evaluation failed");
252
+ }
253
+ return res.result?.value;
254
+ }
255
+ /** Polls until `expression` is truthy; false if it never became so in time. */
256
+ async waitFor(expression, timeoutMs, intervalMs = 200) {
257
+ const deadline = Date.now() + timeoutMs;
258
+ for (;;) {
259
+ try {
260
+ if (await this.evaluate(`Boolean(${expression})`, 5_000))
261
+ return true;
262
+ }
263
+ catch {
264
+ // the document may be mid-navigation; keep polling
265
+ }
266
+ if (Date.now() >= deadline)
267
+ return false;
268
+ await new Promise((r) => setTimeout(r, intervalMs));
269
+ }
270
+ }
271
+ url() {
272
+ return this.evaluate("location.href", 5_000);
273
+ }
274
+ async close() {
275
+ await this.conn.send("Target.closeTarget", { targetId: this.targetId }, undefined, 5_000).catch(() => { });
276
+ }
277
+ }