@clipy/cli 0.8.0 → 0.8.2
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 +90 -13
- package/dist/index.js +355 -121
- package/dist/skill.js +66 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -146,6 +146,19 @@ to headless web capture on `record` and `session start`; they're rejected on
|
|
|
146
146
|
(repeatable).
|
|
147
147
|
- `--init-script <file>` — run a JS file in every page before its own scripts (e.g. to
|
|
148
148
|
stub a feature flag or inject a token).
|
|
149
|
+
- `--user-data-dir <dir>` — launch a **persistent** Chromium profile from `dir` instead
|
|
150
|
+
of an ephemeral context (`launchPersistentContext`), so the recording carries that
|
|
151
|
+
profile's whole logged-in identity. Web only; **mutually exclusive with
|
|
152
|
+
`--storage-state`** (a profile already carries its own storage). `--cookie` /
|
|
153
|
+
`--local-storage` / `--init-script` still compose. Chrome locks a profile while it's
|
|
154
|
+
open, so Clipy refuses a dir that has a `SingletonLock`/`SingletonSocket`. Two ways to
|
|
155
|
+
point it at a real logged-in profile:
|
|
156
|
+
- **Quit Chrome, then point at the real profile dir.** No copy needed and you record
|
|
157
|
+
with full identity — but the recorder writes to that profile, so quit Chrome first
|
|
158
|
+
(that's what clears the `Singleton*` locks) and expect it to have your live session.
|
|
159
|
+
- **Copy the profile out and strip the locks** (`cp -R "<profile>" ./clipy-profile &&
|
|
160
|
+
rm -f ./clipy-profile/Singleton*`) for isolation from your live browser, at the cost
|
|
161
|
+
of duplicating a (large) profile dir. The profile owner's call.
|
|
149
162
|
|
|
150
163
|
```bash
|
|
151
164
|
# Reuse a saved Playwright login
|
|
@@ -155,8 +168,30 @@ clipy record --url https://app.example.com/dashboard --for 20 \
|
|
|
155
168
|
# Or seed a token directly
|
|
156
169
|
clipy record --url https://app.example.com/dashboard \
|
|
157
170
|
--local-storage "authToken=eyJ…" --cookie "sid=abc; Domain=app.example.com; Secure"
|
|
171
|
+
|
|
172
|
+
# Or record a persistent logged-in profile
|
|
173
|
+
clipy record --url https://app.example.com/dashboard --for 20 \
|
|
174
|
+
--user-data-dir ./clipy-profile
|
|
158
175
|
```
|
|
159
176
|
|
|
177
|
+
#### The auth boundary
|
|
178
|
+
|
|
179
|
+
`--storage-state` seeds only the cookies and `localStorage` the **file contains** — it
|
|
180
|
+
can't conjure a whole browser identity, so an app that also needs cross-origin or
|
|
181
|
+
auth-host cookies (SSO, a separate API domain) can still bounce to `/login`. Three
|
|
182
|
+
reliable ways to get a real logged-in recording:
|
|
183
|
+
|
|
184
|
+
1. **Produce the state file with a real interactive login** (it captures cross-domain
|
|
185
|
+
cookies a hand-built file misses):
|
|
186
|
+
```bash
|
|
187
|
+
npx playwright open --save-storage=auth.json https://login.example.com
|
|
188
|
+
# sign in, close the window, then:
|
|
189
|
+
clipy record --url https://app.example.com/dashboard --storage-state auth.json
|
|
190
|
+
```
|
|
191
|
+
2. **`--user-data-dir <dedicated-profile>`** — a persistent profile you logged into once.
|
|
192
|
+
3. **`--source mac-screen --window "Chrome"`** — record your real, already-logged-in
|
|
193
|
+
Chrome window through the Mac app; there's no headless auth to reproduce at all.
|
|
194
|
+
|
|
160
195
|
## Session mode — you work, Clipy records
|
|
161
196
|
|
|
162
197
|
For recordings where an agent (or you) drives the app live, don't script the capture:
|
|
@@ -208,12 +243,28 @@ resolves Playwright from **its own** directory — if `require("playwright")` ca
|
|
|
208
243
|
run the script with `NODE_PATH=$(clipy playwright-path) node driver.js`.
|
|
209
244
|
|
|
210
245
|
**In-page marks (zero spawn latency).** While `--expose-cdp` is on, the daemon also exposes
|
|
211
|
-
`window.__clipyMark("text")` and `window.__clipyChapter("label")` in the recorded
|
|
212
|
-
Calling them from your driver
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
246
|
+
`window.__clipyMark("text", opts?)` and `window.__clipyChapter("label")` in the recorded
|
|
247
|
+
page. Calling them from your driver emits a mark/chapter *without* spawning a `clipy mark`
|
|
248
|
+
process, so it lands exactly when your code runs, and it runs **daemon-side with the page in
|
|
249
|
+
hand**. `__clipyMark`'s second argument takes the same assertions as the CLI flags —
|
|
250
|
+
evaluated and annotated ✓/✗ identically:
|
|
251
|
+
|
|
252
|
+
```js
|
|
253
|
+
await page.evaluate(() => window.__clipyMark("clicked Export"));
|
|
254
|
+
await page.evaluate(() =>
|
|
255
|
+
window.__clipyMark("status is Active", {
|
|
256
|
+
assertSelector: ".status-badge",
|
|
257
|
+
assertText: "Active", // needs assertSelector — otherwise the call rejects
|
|
258
|
+
assertUrl: "**/redemptions", // optional
|
|
259
|
+
failMode: "abort", // optional; "warn" is the default
|
|
260
|
+
}),
|
|
261
|
+
);
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
It returns the annotated `{ tMs, text, assert }`; `failMode: "abort"` discards the session
|
|
265
|
+
just like the flag. These marks land in the same transcript and count toward the same
|
|
266
|
+
200-mark cap. Note: while CDP is exposed the page's **own** scripts can call these too —
|
|
267
|
+
the same trust boundary as `--expose-cdp` itself (any local process can already drive the
|
|
217
268
|
browser), so only enable it when you intend to drive the session.
|
|
218
269
|
|
|
219
270
|
`session start` also accepts the same auth flags as `record`
|
|
@@ -256,8 +307,21 @@ freely — all provided checks must pass.
|
|
|
256
307
|
`--fail-mode` decides what a failed assertion does: `warn` (default) records the `✗` and
|
|
257
308
|
keeps recording; **`abort` discards the whole session** — nothing is uploaded and the CLI
|
|
258
309
|
exits non-zero, so a driver that asserts its way to a broken state doesn't ship a misleading
|
|
259
|
-
clip. If any
|
|
260
|
-
note is prepended at 0 ms, so the transcript and the `.md` context
|
|
310
|
+
clip. If any assertion was attempted, a leading `[verification] N assertion(s): P passed,
|
|
311
|
+
F failed[, K unverified]` note is prepended at 0 ms, so the transcript and the `.md` context
|
|
312
|
+
open with the scorecard.
|
|
313
|
+
|
|
314
|
+
**A mark is never dropped, and a late verdict never rewrites it.** If the daemon can't be
|
|
315
|
+
reached to evaluate an assertion — its event loop briefly starved during a heavy dev-server
|
|
316
|
+
recompile, say — `clipy mark` doesn't fail and lose the note. It records the narration
|
|
317
|
+
anyway, tags it `[ASSERT ⚠ could not evaluate — <reason>]`, prints a loud `⚠`, and exits 0.
|
|
318
|
+
An unverified claim is flagged as unverified (the `K` in the tally), never silently promoted
|
|
319
|
+
to a `✓`. That ⚠ is the **mark of record**: if the daemon was only slow (not gone) and
|
|
320
|
+
evaluates the same claim a moment later, that verdict judged a *later* page state, so it does
|
|
321
|
+
**not** overwrite the ⚠. It's recorded as a separate, honestly-timestamped
|
|
322
|
+
`[late check of "…" — evaluated Ns after the claim: …]` note at the moment it actually ran,
|
|
323
|
+
and it counts toward neither passed, failed, nor unverified. (Plain, non-asserted marks that
|
|
324
|
+
the daemon later processes are simply deduped — they appear exactly once.)
|
|
261
325
|
|
|
262
326
|
Assertions evaluate against a real page, so they need a **web** session (they're rejected on
|
|
263
327
|
`--source mac-screen`, which records the real screen with no page to probe).
|
|
@@ -288,11 +352,16 @@ clipy session run --url http://localhost:3000 --expose-cdp -- node driver.js
|
|
|
288
352
|
|
|
289
353
|
It starts the session, runs everything after `--` with inherited stdio, and then: **exit 0
|
|
290
354
|
→ `session stop`** (upload + share link); **any non-zero exit or a signal → `session abort`**
|
|
291
|
-
(discard) and the child's exit code is propagated. The command runs with `CLIPY_SESSION=1
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
355
|
+
(discard) and the child's exit code is propagated. The command runs with `CLIPY_SESSION=1`,
|
|
356
|
+
`CLIPY_SESSION_FILE=<path>`, and (when `--expose-cdp`) `CLIPY_CDP_URL=<cdpHttpUrl>` in its
|
|
357
|
+
environment. `Ctrl-C` is forwarded to the child, then the session is discarded. All the
|
|
358
|
+
`session start` flags (`--url`, `--title`, `--max`, `--type`, `--expose-cdp`, auth flags)
|
|
359
|
+
apply before the `--`.
|
|
360
|
+
|
|
361
|
+
`clipy mark` / `clipy chapter` resolve the session from `CLIPY_SESSION_FILE` first and the
|
|
362
|
+
current directory second — so a driver you launch with `session run` can shell out
|
|
363
|
+
`clipy mark …` from **any working directory** and still hit the right session, instead of
|
|
364
|
+
failing with "no recording session in this workspace".
|
|
296
365
|
|
|
297
366
|
### Backdating a mark
|
|
298
367
|
|
|
@@ -304,6 +373,14 @@ clipy mark "the toast appeared" --ago 2 # 2 seconds before now
|
|
|
304
373
|
clipy mark "page finished loading" --at 4 # at an absolute 4s on the recording clock
|
|
305
374
|
```
|
|
306
375
|
|
|
376
|
+
Backdating an **asserted** mark is a subtlety: the mark lands at the backdated time, but the
|
|
377
|
+
assertion still judges the **live** page (the daemon can't rewind). When the verdict was
|
|
378
|
+
observed more than 2 s from the backdated position, the mark stays where you put it and the
|
|
379
|
+
text gains `(assertion observed Ns after this backdated mark — the verdict describes the page
|
|
380
|
+
at observation time)`, with a signed `assert.driftSec` in `--json` — so a ✓/✗ is never read
|
|
381
|
+
as describing the earlier moment. Live-clock asserted marks and backdated plain marks are
|
|
382
|
+
unaffected.
|
|
383
|
+
|
|
307
384
|
## Record the real screen — a window, a display (Mac)
|
|
308
385
|
|
|
309
386
|
`--source mac-screen` on `record` / `session start` records through the **running Clipy
|
package/dist/index.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* override the stored key. Read-only unless the key carries the "ingest" scope.
|
|
14
14
|
*/
|
|
15
15
|
import { parseArgs } from "node:util";
|
|
16
|
-
import { appendFileSync, closeSync, createWriteStream, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
|
|
16
|
+
import { appendFileSync, closeSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
|
|
17
17
|
import { homedir, tmpdir } from "node:os";
|
|
18
18
|
import { dirname, join, resolve } from "node:path";
|
|
19
19
|
import { createInterface } from "node:readline";
|
|
@@ -132,6 +132,13 @@ function writeConfig(cfg) {
|
|
|
132
132
|
}
|
|
133
133
|
}
|
|
134
134
|
const FETCH_TIMEOUT_MS = 20_000;
|
|
135
|
+
// Timeout for a `clipy mark`/`chapter` control call to the session daemon.
|
|
136
|
+
// Generous (the daemon's event loop can stall during a heavy client recompile —
|
|
137
|
+
// two observed drops took ~5.6s/5.9s), env-overridable so tests don't wait it out.
|
|
138
|
+
const CONTROL_TIMEOUT_MS = (() => {
|
|
139
|
+
const n = Number(process.env.CLIPY_CONTROL_TIMEOUT_MS);
|
|
140
|
+
return Number.isFinite(n) && n > 0 ? n : 15_000;
|
|
141
|
+
})();
|
|
135
142
|
function requireKey(ctx) {
|
|
136
143
|
if (ctx.apiKey)
|
|
137
144
|
return ctx.apiKey;
|
|
@@ -314,6 +321,9 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
|
|
|
314
321
|
--cookie "n=v[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]" (repeatable)
|
|
315
322
|
--local-storage "k=v" Seed a localStorage pair for the target origin (repeatable)
|
|
316
323
|
--init-script <f> Run a JS file before every page load
|
|
324
|
+
--user-data-dir <d> Launch a persistent Chromium profile dir (its whole
|
|
325
|
+
logged-in identity). Excl. with --storage-state; use a
|
|
326
|
+
copy, never a live/locked Chrome profile
|
|
317
327
|
|
|
318
328
|
${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
|
|
319
329
|
${c.dim("--source mac-screen on record/session records the REAL screen via the")}
|
|
@@ -1748,6 +1758,53 @@ async function applyAuthCapture(context, auth, targetUrl) {
|
|
|
1748
1758
|
if (auth.initScriptPath)
|
|
1749
1759
|
await context.addInitScript({ path: auth.initScriptPath });
|
|
1750
1760
|
}
|
|
1761
|
+
/** Validate a --user-data-dir before launch. It must exist and must NOT look
|
|
1762
|
+
* like a profile a live Chrome is holding open — Chrome locks its profile with
|
|
1763
|
+
* Singleton{Lock,Socket} entries, and pointing Playwright at a locked profile
|
|
1764
|
+
* either fails or forces a flaky copy. The docs boundary: never the live default
|
|
1765
|
+
* profile; use a copy or a dedicated logged-in profile dir. die(2) on any miss. */
|
|
1766
|
+
function validateUserDataDir(dir) {
|
|
1767
|
+
let st;
|
|
1768
|
+
try {
|
|
1769
|
+
st = statSync(dir);
|
|
1770
|
+
}
|
|
1771
|
+
catch {
|
|
1772
|
+
die(`--user-data-dir not found: ${dir} (create it, or use a copy of a logged-in profile)`, 2);
|
|
1773
|
+
}
|
|
1774
|
+
if (!st.isDirectory())
|
|
1775
|
+
die(`--user-data-dir is not a directory: ${dir}`, 2);
|
|
1776
|
+
for (const lock of ["SingletonLock", "SingletonSocket"]) {
|
|
1777
|
+
if (existsSync(join(dir, lock))) {
|
|
1778
|
+
die(`--user-data-dir looks like a live/locked Chrome profile (${lock} present): ${dir}\n` +
|
|
1779
|
+
`Never point Clipy at a running Chrome's profile — Chrome locks it while open. Close that Chrome, or use a COPY / a dedicated logged-in profile dir.`, 2);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
/** Launch a recording context. With userDataDir: a PERSISTENT context bound to
|
|
1784
|
+
* that dir (launchPersistentContext — it IS the context, there's no separate
|
|
1785
|
+
* browser; recordVideo/init-scripts/cookies still apply). Without: an ephemeral
|
|
1786
|
+
* browser + newContext (storageState only applies here). Either way the caller
|
|
1787
|
+
* gets {context, browser} — browser is null in persistent mode, and closing the
|
|
1788
|
+
* context tears down that browser. */
|
|
1789
|
+
async function launchRecordingContext(chromium, opts) {
|
|
1790
|
+
const recordVideo = { dir: opts.recordVideoDir, size: opts.viewport };
|
|
1791
|
+
if (opts.userDataDir) {
|
|
1792
|
+
const context = await chromium.launchPersistentContext(opts.userDataDir, {
|
|
1793
|
+
headless: true,
|
|
1794
|
+
viewport: opts.viewport,
|
|
1795
|
+
recordVideo,
|
|
1796
|
+
args: opts.args,
|
|
1797
|
+
});
|
|
1798
|
+
return { context, browser: null };
|
|
1799
|
+
}
|
|
1800
|
+
const browser = await chromium.launch({ headless: true, args: opts.args });
|
|
1801
|
+
const context = await browser.newContext({
|
|
1802
|
+
viewport: opts.viewport,
|
|
1803
|
+
recordVideo,
|
|
1804
|
+
...(opts.storageStatePath ? { storageState: opts.storageStatePath } : {}),
|
|
1805
|
+
});
|
|
1806
|
+
return { context, browser };
|
|
1807
|
+
}
|
|
1751
1808
|
async function cmdRecord(ctx, opts) {
|
|
1752
1809
|
// Validate the target URL up front — a headless browser will happily hang on
|
|
1753
1810
|
// a typo'd or non-http(s) URL otherwise.
|
|
@@ -1762,6 +1819,8 @@ async function cmdRecord(ctx, opts) {
|
|
|
1762
1819
|
die(`--url must be http(s), got ${target.protocol}`, 2);
|
|
1763
1820
|
}
|
|
1764
1821
|
validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/browser
|
|
1822
|
+
if (opts.userDataDir)
|
|
1823
|
+
validateUserDataDir(opts.userDataDir);
|
|
1765
1824
|
requireKey(ctx); // fail fast before we spin up a browser
|
|
1766
1825
|
const chromium = await loadChromium();
|
|
1767
1826
|
const tmpDir = join(tmpdir(), `clipy-record-${randomUUID()}`);
|
|
@@ -1796,24 +1855,24 @@ async function cmdRecord(ctx, opts) {
|
|
|
1796
1855
|
try {
|
|
1797
1856
|
// --- Capture -----------------------------------------------------------
|
|
1798
1857
|
let videoPath;
|
|
1799
|
-
log(`${c.dim("launching headless chromium…")}`);
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1858
|
+
log(`${c.dim(opts.userDataDir ? "launching chromium (persistent profile)…" : "launching headless chromium…")}`);
|
|
1859
|
+
// Cloud sandboxes / CI containers run as root where Chromium's own sandbox
|
|
1860
|
+
// can't initialize; this is a user-driven capture of a URL they chose, so the
|
|
1861
|
+
// browser sandbox isn't a trust boundary here. --user-data-dir ⇒ a persistent
|
|
1862
|
+
// context (its own browser); else an ephemeral browser + context.
|
|
1863
|
+
const { context, browser } = await launchRecordingContext(chromium, {
|
|
1864
|
+
userDataDir: opts.userDataDir,
|
|
1865
|
+
viewport: frame,
|
|
1866
|
+
recordVideoDir: tmpDir,
|
|
1805
1867
|
args: ["--no-sandbox", "--disable-dev-shm-usage"],
|
|
1868
|
+
storageStatePath: opts.auth.storageStatePath,
|
|
1806
1869
|
});
|
|
1807
1870
|
try {
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
// Playwright takes the storageState file path directly (cookies + origins).
|
|
1812
|
-
...(opts.auth.storageStatePath ? { storageState: opts.auth.storageStatePath } : {}),
|
|
1813
|
-
});
|
|
1814
|
-
// Seed cookies/localStorage/init-script before the first navigation.
|
|
1871
|
+
// Seed cookies/localStorage/init-script before the first navigation. These
|
|
1872
|
+
// compose with a persistent profile too; --storage-state does not (rejected
|
|
1873
|
+
// together at parse time).
|
|
1815
1874
|
await applyAuthCapture(context, opts.auth, target.href);
|
|
1816
|
-
const page = await context.newPage();
|
|
1875
|
+
const page = context.pages()[0] ?? (await context.newPage());
|
|
1817
1876
|
// captureStart is set AFTER the first meaningful paint (below), so notes
|
|
1818
1877
|
// and pass marks aren't anchored to the blank t=0 a compiling app shows.
|
|
1819
1878
|
let captureStart = 0;
|
|
@@ -1870,7 +1929,12 @@ async function cmdRecord(ctx, opts) {
|
|
|
1870
1929
|
videoPath = await video.path();
|
|
1871
1930
|
}
|
|
1872
1931
|
finally {
|
|
1873
|
-
|
|
1932
|
+
// Persistent mode has no separate browser — closing the context (above, or
|
|
1933
|
+
// here on an early throw) tears down its Chromium.
|
|
1934
|
+
if (browser)
|
|
1935
|
+
await browser.close().catch(() => { });
|
|
1936
|
+
else
|
|
1937
|
+
await context.close().catch(() => { });
|
|
1874
1938
|
}
|
|
1875
1939
|
// --- Upload ------------------------------------------------------------
|
|
1876
1940
|
const notes = [...autoNotes, ...resolveNarrationNotes(opts.notes, passStartsMs)].sort((a, b) => a.startMs - b.startMs);
|
|
@@ -1932,6 +1996,14 @@ function sessionFilePath(cwd) {
|
|
|
1932
1996
|
const digest = createHash("sha1").update(cwd).digest("hex").slice(0, 16);
|
|
1933
1997
|
return join(sessionDir(), `session-${digest}.json`);
|
|
1934
1998
|
}
|
|
1999
|
+
/** Which session file the mark/chapter/stop/abort/status verbs operate on.
|
|
2000
|
+
* CLIPY_SESSION_FILE (exported by `session run` to its child) wins, so a driver
|
|
2001
|
+
* invoked from a different cwd than the session still finds it; the cwd hash is
|
|
2002
|
+
* the fallback for a plain interactive session. */
|
|
2003
|
+
function sessionFileToUse() {
|
|
2004
|
+
const fromEnv = process.env.CLIPY_SESSION_FILE?.trim();
|
|
2005
|
+
return fromEnv || sessionFilePath(process.cwd());
|
|
2006
|
+
}
|
|
1935
2007
|
function readSessionState(file) {
|
|
1936
2008
|
try {
|
|
1937
2009
|
return JSON.parse(readFileSync(file, "utf8"));
|
|
@@ -2234,6 +2306,8 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
2234
2306
|
die(`--url must be http(s), got ${target.protocol}`, 2);
|
|
2235
2307
|
}
|
|
2236
2308
|
validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/daemonizing
|
|
2309
|
+
if (opts.userDataDir)
|
|
2310
|
+
validateUserDataDir(opts.userDataDir);
|
|
2237
2311
|
const key = requireKey(ctx);
|
|
2238
2312
|
await loadChromium(); // fail fast with install instructions before daemonizing
|
|
2239
2313
|
const file = sessionFilePath(process.cwd());
|
|
@@ -2264,6 +2338,7 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
2264
2338
|
initScriptPath: opts.auth.initScriptPath,
|
|
2265
2339
|
cookieSpecs: opts.auth.cookieSpecs.length ? opts.auth.cookieSpecs : undefined,
|
|
2266
2340
|
localStorageSpecs: opts.auth.localStorageSpecs.length ? opts.auth.localStorageSpecs : undefined,
|
|
2341
|
+
userDataDir: opts.userDataDir,
|
|
2267
2342
|
state: "starting",
|
|
2268
2343
|
marksPath: join(dir, `marks-${id}.jsonl`),
|
|
2269
2344
|
controlPath: join(dir, `control-${id}.json`),
|
|
@@ -2329,7 +2404,7 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
2329
2404
|
`${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
|
|
2330
2405
|
}
|
|
2331
2406
|
function requireSession() {
|
|
2332
|
-
const file =
|
|
2407
|
+
const file = sessionFileToUse();
|
|
2333
2408
|
const state = readSessionState(file);
|
|
2334
2409
|
if (!state) {
|
|
2335
2410
|
die(`no recording session in this workspace. Start one with \`clipy session start --url <app>\`.`);
|
|
@@ -2392,24 +2467,41 @@ async function cmdMark(text, json, opts) {
|
|
|
2392
2467
|
? Math.max(0, Math.round(opts.atSec * 1000))
|
|
2393
2468
|
: Math.max(0, Date.now() - state.recordStartEpochMs - Math.round((opts.agoSec ?? 0) * 1000))
|
|
2394
2469
|
: undefined;
|
|
2470
|
+
// A client-generated id rides both the HTTP call and any file fallback so the
|
|
2471
|
+
// daemon can drop a file duplicate of an HTTP mark it already processed (the
|
|
2472
|
+
// client timed out, the daemon didn't).
|
|
2473
|
+
const markId = randomUUID();
|
|
2474
|
+
const cleanText = text.trim();
|
|
2475
|
+
const localTMs = atMs != null ? atMs : Math.max(0, Date.now() - state.recordStartEpochMs);
|
|
2395
2476
|
if (state.controlPort && state.controlToken) {
|
|
2396
2477
|
let res;
|
|
2397
2478
|
try {
|
|
2398
2479
|
res = await postToControl(state, "/mark", {
|
|
2399
|
-
|
|
2480
|
+
id: markId,
|
|
2481
|
+
text: cleanText,
|
|
2400
2482
|
...(atMs != null ? { atMs } : {}),
|
|
2401
2483
|
...(hasAssert ? { assert: opts.assert } : {}),
|
|
2402
|
-
},
|
|
2484
|
+
}, CONTROL_TIMEOUT_MS);
|
|
2403
2485
|
}
|
|
2404
2486
|
catch (e) {
|
|
2405
|
-
|
|
2406
|
-
//
|
|
2487
|
+
const reason = String(e.message).slice(0, 120);
|
|
2488
|
+
// NEVER drop a mark. If the daemon didn't answer, record the narration to
|
|
2489
|
+
// the file regardless. For an ASSERTED mark we couldn't verify the claim,
|
|
2490
|
+
// so tag it honestly ⚠ UNVERIFIED (never a silent pass) — the daemon counts
|
|
2491
|
+
// {unverified:true} file marks into the tally's third bucket.
|
|
2407
2492
|
if (hasAssert) {
|
|
2408
|
-
|
|
2493
|
+
const annotated = `${cleanText} [ASSERT ⚠ could not evaluate — ${reason}]`;
|
|
2494
|
+
appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: annotated, unverified: true })}\n`, { mode: 0o600 });
|
|
2495
|
+
if (json) {
|
|
2496
|
+
printJson({ tMs: localTMs, text: annotated, assert: { unverified: true, reason } });
|
|
2497
|
+
}
|
|
2498
|
+
else {
|
|
2499
|
+
process.stderr.write(`${c.yellow("⚠")} mark recorded, assertion UNVERIFIED (${reason}) @ ${(localTMs / 1000).toFixed(1)}s — ${annotated}\n`);
|
|
2500
|
+
}
|
|
2501
|
+
return;
|
|
2409
2502
|
}
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
printMarkResult({ tMs, text: text.trim() }, json);
|
|
2503
|
+
appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: cleanText })}\n`, { mode: 0o600 });
|
|
2504
|
+
printMarkResult({ tMs: localTMs, text: cleanText }, json);
|
|
2413
2505
|
return;
|
|
2414
2506
|
}
|
|
2415
2507
|
if (res.aborted) {
|
|
@@ -2425,9 +2517,8 @@ async function cmdMark(text, json, opts) {
|
|
|
2425
2517
|
if (hasAssert) {
|
|
2426
2518
|
die("this session has no control endpoint (started by an older clipy) — stop it and run `clipy session start` again to use assertion marks");
|
|
2427
2519
|
}
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
printMarkResult({ tMs, text: text.trim() }, json);
|
|
2520
|
+
appendFileSync(state.marksPath, `${JSON.stringify({ id: markId, tMs: localTMs, text: cleanText })}\n`, { mode: 0o600 });
|
|
2521
|
+
printMarkResult({ tMs: localTMs, text: cleanText }, json);
|
|
2431
2522
|
}
|
|
2432
2523
|
/** `clipy chapter "<label>"` — a chapter is a specially-formatted mark
|
|
2433
2524
|
* (=== CHAPTER: <label> ===) that splits one recording into BEFORE/AFTER
|
|
@@ -2457,9 +2548,12 @@ async function cmdChapter(label, json) {
|
|
|
2457
2548
|
if (state.state !== "recording" || !state.recordStartEpochMs) {
|
|
2458
2549
|
die(`session is ${state.state} — chapters can only be added while recording`);
|
|
2459
2550
|
}
|
|
2551
|
+
// Client id for HTTP↔file dedup, same as marks (a timed-out chapter that the
|
|
2552
|
+
// daemon still processed shouldn't double up).
|
|
2553
|
+
const chapterId = randomUUID();
|
|
2460
2554
|
if (state.controlPort && state.controlToken) {
|
|
2461
2555
|
try {
|
|
2462
|
-
const res = await postToControl(state, "/chapter", { label },
|
|
2556
|
+
const res = await postToControl(state, "/chapter", { id: chapterId, label }, CONTROL_TIMEOUT_MS);
|
|
2463
2557
|
if (json) {
|
|
2464
2558
|
printJson({ tMs: Number(res.tMs ?? 0), label, text: chapterText });
|
|
2465
2559
|
}
|
|
@@ -2473,7 +2567,7 @@ async function cmdChapter(label, json) {
|
|
|
2473
2567
|
}
|
|
2474
2568
|
}
|
|
2475
2569
|
const tMs = Math.max(0, Date.now() - state.recordStartEpochMs);
|
|
2476
|
-
appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: chapterText })}\n`, { mode: 0o600 });
|
|
2570
|
+
appendFileSync(state.marksPath, `${JSON.stringify({ id: chapterId, tMs, text: chapterText })}\n`, { mode: 0o600 });
|
|
2477
2571
|
if (json) {
|
|
2478
2572
|
printJson({ tMs, label, text: chapterText });
|
|
2479
2573
|
}
|
|
@@ -2648,7 +2742,7 @@ async function cmdSessionAbort(json) {
|
|
|
2648
2742
|
process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
|
|
2649
2743
|
}
|
|
2650
2744
|
async function cmdSessionStatus(json) {
|
|
2651
|
-
const file =
|
|
2745
|
+
const file = sessionFileToUse();
|
|
2652
2746
|
const state = readSessionState(file);
|
|
2653
2747
|
if (!state) {
|
|
2654
2748
|
if (json)
|
|
@@ -2736,8 +2830,11 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
|
|
|
2736
2830
|
stdio: "inherit",
|
|
2737
2831
|
env: {
|
|
2738
2832
|
...process.env,
|
|
2739
|
-
// Signals to the child that it's being recorded, and where to drive.
|
|
2833
|
+
// Signals to the child that it's being recorded, and where to drive. The
|
|
2834
|
+
// session file is exported explicitly so `clipy mark`/`chapter` resolve it
|
|
2835
|
+
// even from a different cwd than this session's (the reporter's driver did).
|
|
2740
2836
|
CLIPY_SESSION: "1",
|
|
2837
|
+
CLIPY_SESSION_FILE: file,
|
|
2741
2838
|
...(cdpHttpUrl ? { CLIPY_CDP_URL: cdpHttpUrl } : {}),
|
|
2742
2839
|
},
|
|
2743
2840
|
});
|
|
@@ -2834,25 +2931,21 @@ async function runSessionDaemon(file) {
|
|
|
2834
2931
|
return;
|
|
2835
2932
|
autoMarks.push({ startMs: Math.max(0, Date.now() - recordStart), text });
|
|
2836
2933
|
};
|
|
2837
|
-
// Marks that arrive over the control endpoint (`clipy mark`/`chapter`) or the
|
|
2838
|
-
// in-page __clipyMark/__clipyChapter bindings. Kept in memory (like autoMarks)
|
|
2839
|
-
// and merged at stop. A hard 200 cap here is the server limit; storeDaemonMark
|
|
2840
|
-
// refuses past it so `clipy mark` gets an error rather than a silent drop.
|
|
2841
2934
|
const daemonMarks = [];
|
|
2842
|
-
const storeDaemonMark = (
|
|
2935
|
+
const storeDaemonMark = (m) => {
|
|
2843
2936
|
if (daemonMarks.length >= 200)
|
|
2844
2937
|
return false;
|
|
2845
|
-
daemonMarks.push(
|
|
2938
|
+
daemonMarks.push(m);
|
|
2846
2939
|
return true;
|
|
2847
2940
|
};
|
|
2848
|
-
// Assertion tallies → the leading [verification] note at stop.
|
|
2849
|
-
let assertRan = 0;
|
|
2850
|
-
let assertPassed = 0;
|
|
2851
|
-
let assertFailed = 0;
|
|
2852
2941
|
// A failed --fail-mode=abort assertion sets this; the main loop discards.
|
|
2853
2942
|
let controlSignal = null;
|
|
2854
2943
|
mkdirSync(state.tmpDir, { recursive: true });
|
|
2855
2944
|
let browser = null;
|
|
2945
|
+
// Persistent (--user-data-dir) contexts have no separate browser, so track the
|
|
2946
|
+
// context too for the finally cleanup (an exception before stop must not leak
|
|
2947
|
+
// the Chromium).
|
|
2948
|
+
let ctxToClose = null;
|
|
2856
2949
|
let controlServer = null;
|
|
2857
2950
|
try {
|
|
2858
2951
|
const chromium = await loadChromium();
|
|
@@ -2866,52 +2959,33 @@ async function runSessionDaemon(file) {
|
|
|
2866
2959
|
if (state.exposeCdp && !wantCdp)
|
|
2867
2960
|
log("CDP disabled by CLIPY_DISABLE_CDP=1 — not opening a debugging port");
|
|
2868
2961
|
const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
|
|
2869
|
-
browser
|
|
2870
|
-
|
|
2962
|
+
// --user-data-dir ⇒ a persistent context (its own browser); else an ephemeral
|
|
2963
|
+
// browser + context. The CDP debugging port (if any) rides the launch args.
|
|
2964
|
+
const { context, browser: launchedBrowser } = await launchRecordingContext(chromium, {
|
|
2965
|
+
userDataDir: state.userDataDir,
|
|
2966
|
+
viewport: { width: state.width, height: state.height },
|
|
2967
|
+
recordVideoDir: state.tmpDir,
|
|
2871
2968
|
args: [
|
|
2872
2969
|
"--no-sandbox",
|
|
2873
2970
|
"--disable-dev-shm-usage",
|
|
2874
2971
|
...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
|
|
2875
2972
|
],
|
|
2973
|
+
storageStatePath: state.storageStatePath,
|
|
2876
2974
|
});
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
recordVideo: { dir: state.tmpDir, size: { width: state.width, height: state.height } },
|
|
2880
|
-
// Playwright takes the storageState file path directly (cookies + origins).
|
|
2881
|
-
...(state.storageStatePath ? { storageState: state.storageStatePath } : {}),
|
|
2882
|
-
});
|
|
2975
|
+
browser = launchedBrowser;
|
|
2976
|
+
ctxToClose = context;
|
|
2883
2977
|
// Seed cookies/localStorage/init-script before the first navigation — re-parse
|
|
2884
2978
|
// the raw specs the parent CLI already validated. A bad spec here is caught by
|
|
2885
|
-
// the outer try/catch and fails the session cleanly.
|
|
2979
|
+
// the outer try/catch and fails the session cleanly. (--storage-state was
|
|
2980
|
+
// applied at launch; it and --user-data-dir are mutually exclusive.)
|
|
2886
2981
|
await applyAuthCapture(context, {
|
|
2887
2982
|
storageStatePath: state.storageStatePath,
|
|
2888
2983
|
initScriptPath: state.initScriptPath,
|
|
2889
2984
|
cookieSpecs: state.cookieSpecs ?? [],
|
|
2890
2985
|
localStorageSpecs: state.localStorageSpecs ?? [],
|
|
2891
2986
|
}, state.url);
|
|
2892
|
-
//
|
|
2893
|
-
|
|
2894
|
-
// window.__clipyMark("…")) emits a mark with ZERO spawn latency (no `clipy
|
|
2895
|
-
// mark` process). Same 200-cap store as the HTTP path. NOTE: while CDP is
|
|
2896
|
-
// exposed, the page's own scripts can call these too — that's within the
|
|
2897
|
-
// existing --expose-cdp trust model (any local process can already drive the
|
|
2898
|
-
// browser), and it's documented in the README's --expose-cdp section.
|
|
2899
|
-
if (wantCdp) {
|
|
2900
|
-
const inPageMark = (label) => {
|
|
2901
|
-
if (recordStart === 0)
|
|
2902
|
-
return;
|
|
2903
|
-
const text = label.trim();
|
|
2904
|
-
if (text)
|
|
2905
|
-
storeDaemonMark({ startMs: Math.max(0, Date.now() - recordStart), text });
|
|
2906
|
-
};
|
|
2907
|
-
await context
|
|
2908
|
-
.exposeBinding("__clipyMark", (_src, ...args) => inPageMark(String(args[0] ?? "")))
|
|
2909
|
-
.catch((e) => log(`__clipyMark binding failed: ${e.message}`));
|
|
2910
|
-
await context
|
|
2911
|
-
.exposeBinding("__clipyChapter", (_src, ...args) => inPageMark(`=== CHAPTER: ${String(args[0] ?? "").trim()} ===`))
|
|
2912
|
-
.catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
|
|
2913
|
-
}
|
|
2914
|
-
const page = await context.newPage();
|
|
2987
|
+
// Persistent contexts open with a default page; ephemeral ones start empty.
|
|
2988
|
+
const page = context.pages()[0] ?? (await context.newPage());
|
|
2915
2989
|
// Best-effort: publish the CDP URL so `session start`/`status` can hand it
|
|
2916
2990
|
// to the agent. The recording works fine even if discovery fails.
|
|
2917
2991
|
let cdpUrl;
|
|
@@ -2947,42 +3021,55 @@ async function runSessionDaemon(file) {
|
|
|
2947
3021
|
// ignore
|
|
2948
3022
|
}
|
|
2949
3023
|
}));
|
|
2950
|
-
//
|
|
2951
|
-
//
|
|
2952
|
-
//
|
|
2953
|
-
//
|
|
2954
|
-
const
|
|
2955
|
-
|
|
2956
|
-
/** POST /mark → tMs (atMs override or live clock), optional assertion run
|
|
2957
|
-
* against the page, stored (annotated) mark, and the response the CLI shows. */
|
|
2958
|
-
const handleMark = async (body) => {
|
|
2959
|
-
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
3024
|
+
// The ONE place a mark is recorded, shared by the HTTP control endpoint and
|
|
3025
|
+
// the in-page __clipyMark binding, so both evaluate assertions against the
|
|
3026
|
+
// live page identically. Records the (annotated) mark and returns the
|
|
3027
|
+
// CLI/driver-facing response.
|
|
3028
|
+
const applyMark = async (m) => {
|
|
3029
|
+
const text = m.text.trim();
|
|
2960
3030
|
if (!text)
|
|
2961
3031
|
throw new Error("mark text is required");
|
|
2962
|
-
const tMs = typeof
|
|
2963
|
-
? Math.max(0, Math.round(
|
|
3032
|
+
const tMs = typeof m.atMs === "number" && Number.isFinite(m.atMs)
|
|
3033
|
+
? Math.max(0, Math.round(m.atMs))
|
|
2964
3034
|
: Math.max(0, Date.now() - recordStart);
|
|
3035
|
+
const evalAtMs = Math.max(0, Date.now() - recordStart);
|
|
2965
3036
|
let annotated = text;
|
|
2966
3037
|
let assertOut;
|
|
3038
|
+
let assertOutcome;
|
|
2967
3039
|
let aborted = false;
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
//
|
|
2971
|
-
//
|
|
2972
|
-
const ev = await evaluateAssertion(page,
|
|
2973
|
-
assertRan++;
|
|
2974
|
-
if (ev.passed)
|
|
2975
|
-
assertPassed++;
|
|
2976
|
-
else
|
|
2977
|
-
assertFailed++;
|
|
3040
|
+
if (m.assert && typeof m.assert === "object") {
|
|
3041
|
+
// evaluateAssertion throws if the page is unresponsive — the HTTP path
|
|
3042
|
+
// turns that into a 5xx (the CLI then records a ⚠ UNVERIFIED file mark),
|
|
3043
|
+
// and the in-page path rejects to the driver.
|
|
3044
|
+
const ev = await evaluateAssertion(page, m.assert);
|
|
2978
3045
|
annotated = ev.passed
|
|
2979
3046
|
? `${text} [assert ✓ ${ev.observed}]`
|
|
2980
3047
|
: `${text} [ASSERT ✗ expected ${ev.expected}; observed ${ev.observed}]`;
|
|
2981
3048
|
assertOut = { passed: ev.passed, observed: ev.observed };
|
|
2982
|
-
|
|
3049
|
+
assertOutcome = { passed: ev.passed, expected: ev.expected, observed: ev.observed };
|
|
3050
|
+
if (!ev.passed && m.assert.failMode === "abort")
|
|
2983
3051
|
aborted = true;
|
|
3052
|
+
// Backdated assertion divergence: a --at/--ago mark is stamped in the past
|
|
3053
|
+
// but the assertion judged the LIVE page. If the verdict was observed more
|
|
3054
|
+
// than 2s from the backdated position, keep the mark where the agent put it
|
|
3055
|
+
// but say so in the text (and expose a signed drift), so the ✓/✗ isn't read
|
|
3056
|
+
// as describing the page at the backdated moment. Live-clock asserted marks
|
|
3057
|
+
// (no atMs) and backdated PLAIN marks get nothing.
|
|
3058
|
+
if (m.atMs != null) {
|
|
3059
|
+
const driftMs = evalAtMs - tMs; // + = observed AFTER the backdated stamp
|
|
3060
|
+
if (Math.abs(driftMs) > 2000) {
|
|
3061
|
+
const n = Math.round(Math.abs(driftMs) / 1000);
|
|
3062
|
+
const dir = driftMs >= 0 ? "after" : "before";
|
|
3063
|
+
annotated += ` (assertion observed ${n}s ${dir} this backdated mark — the verdict describes the page at observation time)`;
|
|
3064
|
+
assertOut.driftSec = Math.round(driftMs / 1000); // signed, for --json
|
|
3065
|
+
}
|
|
3066
|
+
}
|
|
2984
3067
|
}
|
|
2985
|
-
|
|
3068
|
+
// Store the provisional mark of record at the claim time. The merge decides
|
|
3069
|
+
// whether it stays the record (no client timeout) or becomes a late check
|
|
3070
|
+
// (the client already wrote a ⚠ mark of record for this id). P/F is counted
|
|
3071
|
+
// at merge from assertOutcome, so a late eval never lands in the tally.
|
|
3072
|
+
if (!storeDaemonMark({ startMs: tMs, text: annotated, id: m.id, evalAtMs, claim: text, assertOutcome })) {
|
|
2986
3073
|
throw new Error("mark limit reached (200 marks per recording)");
|
|
2987
3074
|
}
|
|
2988
3075
|
if (aborted)
|
|
@@ -2994,13 +3081,84 @@ async function runSessionDaemon(file) {
|
|
|
2994
3081
|
...(aborted ? { aborted: true } : {}),
|
|
2995
3082
|
};
|
|
2996
3083
|
};
|
|
2997
|
-
|
|
3084
|
+
// In-page mark/chapter bindings — only under --expose-cdp, alongside the
|
|
3085
|
+
// debugging port a driver already uses. window.__clipyMark(text, opts?) with
|
|
3086
|
+
// opts {assertSelector, assertText, assertUrl, failMode} runs the SAME
|
|
3087
|
+
// daemon-side assertion + annotation as the CLI flags, at ZERO spawn cost.
|
|
3088
|
+
// NOTE: while CDP is exposed the page's own scripts can call these too —
|
|
3089
|
+
// within the existing --expose-cdp trust model (documented in the README).
|
|
3090
|
+
// The bindings are exposed under *Impl names and re-declared with explicit
|
|
3091
|
+
// arity below, so an agent probing window.__clipyMark.length sees 2 (not the
|
|
3092
|
+
// 0 an exposeBinding wrapper reports).
|
|
3093
|
+
if (wantCdp) {
|
|
3094
|
+
await context
|
|
3095
|
+
.exposeBinding("__clipyMarkImpl", async (_src, ...args) => {
|
|
3096
|
+
if (recordStart === 0)
|
|
3097
|
+
return { skipped: true };
|
|
3098
|
+
const o = (args[1] ?? {});
|
|
3099
|
+
let assert;
|
|
3100
|
+
if (o.assertSelector || o.assertText || o.assertUrl) {
|
|
3101
|
+
// Thrown here ⇒ the page's `await window.__clipyMark(...)` rejects, so
|
|
3102
|
+
// the driver sees the misuse (mirrors the CLI's die(2)).
|
|
3103
|
+
if (o.assertText != null && !o.assertSelector) {
|
|
3104
|
+
throw new Error("__clipyMark: assertText requires assertSelector");
|
|
3105
|
+
}
|
|
3106
|
+
assert = {
|
|
3107
|
+
selector: o.assertSelector,
|
|
3108
|
+
expectText: o.assertText,
|
|
3109
|
+
urlGlob: o.assertUrl,
|
|
3110
|
+
failMode: o.failMode === "abort" ? "abort" : "warn",
|
|
3111
|
+
};
|
|
3112
|
+
}
|
|
3113
|
+
return await applyMark({ text: String(args[0] ?? ""), assert });
|
|
3114
|
+
})
|
|
3115
|
+
.catch((e) => log(`__clipyMark binding failed: ${e.message}`));
|
|
3116
|
+
await context
|
|
3117
|
+
.exposeBinding("__clipyChapterImpl", (_src, ...args) => {
|
|
3118
|
+
if (recordStart === 0)
|
|
3119
|
+
return;
|
|
3120
|
+
const label = String(args[0] ?? "").trim();
|
|
3121
|
+
if (label) {
|
|
3122
|
+
storeDaemonMark({ startMs: Math.max(0, Date.now() - recordStart), text: `=== CHAPTER: ${label} ===` });
|
|
3123
|
+
}
|
|
3124
|
+
})
|
|
3125
|
+
.catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
|
|
3126
|
+
// Declared-arity wrappers so window.__clipyMark.length === 2 / __clipyChapter
|
|
3127
|
+
// === 1 (they resolve the *Impl bindings lazily, at call time).
|
|
3128
|
+
await context
|
|
3129
|
+
.addInitScript({
|
|
3130
|
+
content: "window.__clipyMark = (text, opts) => window.__clipyMarkImpl(text, opts);\n" +
|
|
3131
|
+
"window.__clipyChapter = (label) => window.__clipyChapterImpl(label);",
|
|
3132
|
+
})
|
|
3133
|
+
.catch((e) => log(`in-page binding wrappers failed: ${e.message}`));
|
|
3134
|
+
}
|
|
3135
|
+
// Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
|
|
3136
|
+
// which owns the live page — evaluates assertions and stamps marks on its
|
|
3137
|
+
// own clock. 127.0.0.1 only, bearer-token auth (random UUID). If it can't
|
|
3138
|
+
// bind, the recording still runs and marks fall back to the marks file.
|
|
3139
|
+
const controlToken = randomUUID();
|
|
3140
|
+
let controlPort = 0;
|
|
3141
|
+
/** POST /mark → applyMark (shared with the in-page binding): stamp, optional
|
|
3142
|
+
* assertion against the live page, store, and return the CLI-facing shape.
|
|
3143
|
+
* The client id rides through so a timed-out-but-processed mark is deduped. */
|
|
3144
|
+
const handleMark = (body) => applyMark({
|
|
3145
|
+
text: typeof body.text === "string" ? body.text : "",
|
|
3146
|
+
atMs: typeof body.atMs === "number" ? body.atMs : undefined,
|
|
3147
|
+
assert: body.assert,
|
|
3148
|
+
id: typeof body.id === "string" ? body.id : undefined,
|
|
3149
|
+
});
|
|
3150
|
+
/** POST /chapter → a === CHAPTER === mark at the live clock. Carries its
|
|
3151
|
+
* client id so a timed-out-but-processed chapter dedups against the file. */
|
|
2998
3152
|
const handleChapter = (body) => {
|
|
2999
3153
|
const label = typeof body.label === "string" ? body.label.trim() : "";
|
|
3000
3154
|
if (!label)
|
|
3001
3155
|
throw new Error("chapter label is required");
|
|
3002
3156
|
const tMs = Math.max(0, Date.now() - recordStart);
|
|
3003
|
-
if (!storeDaemonMark({
|
|
3157
|
+
if (!storeDaemonMark({
|
|
3158
|
+
startMs: tMs,
|
|
3159
|
+
text: `=== CHAPTER: ${label} ===`,
|
|
3160
|
+
id: typeof body.id === "string" ? body.id : undefined,
|
|
3161
|
+
})) {
|
|
3004
3162
|
throw new Error("mark limit reached (200 marks per recording)");
|
|
3005
3163
|
}
|
|
3006
3164
|
return { tMs };
|
|
@@ -3157,35 +3315,89 @@ async function runSessionDaemon(file) {
|
|
|
3157
3315
|
if (!video)
|
|
3158
3316
|
throw new Error("browser did not produce a video (recordVideo unavailable)");
|
|
3159
3317
|
const videoPath = await video.path();
|
|
3160
|
-
|
|
3318
|
+
// Persistent mode: context.close() (above) already tore down Chromium; there
|
|
3319
|
+
// is no separate browser to close.
|
|
3320
|
+
if (browser)
|
|
3321
|
+
await browser.close().catch(() => { });
|
|
3161
3322
|
browser = null;
|
|
3162
|
-
// Merge marks
|
|
3163
|
-
//
|
|
3164
|
-
//
|
|
3165
|
-
//
|
|
3323
|
+
// Merge marks. The FILE is the mark of record: `clipy mark` writes there when
|
|
3324
|
+
// its control call fails, and a timed-out ASSERTION is recorded ⚠-unverified.
|
|
3325
|
+
// That ⚠ is authoritative — if the daemon later evaluated the same mark, that
|
|
3326
|
+
// late verdict must NOT overwrite the ⚠ (it judged a LATER page state), so we
|
|
3327
|
+
// keep the ⚠ and re-stamp the late evaluation as a self-describing "late check"
|
|
3328
|
+
// at its own time. K counts the ⚠; the late check counts toward neither P/F/K.
|
|
3166
3329
|
const fileMarks = [];
|
|
3330
|
+
const unverifiedClaimById = new Map(); // id → claim time (ms)
|
|
3331
|
+
const abandonedIds = new Set(); // any id the client wrote to the file
|
|
3332
|
+
let assertUnverified = 0; // K
|
|
3167
3333
|
try {
|
|
3168
3334
|
for (const line of readFileSync(state.marksPath, "utf8").split("\n")) {
|
|
3169
3335
|
if (!line.trim())
|
|
3170
3336
|
continue;
|
|
3171
3337
|
const m = JSON.parse(line);
|
|
3172
|
-
if (typeof m.tMs
|
|
3173
|
-
|
|
3338
|
+
if (typeof m.tMs !== "number" || typeof m.text !== "string" || !m.text.trim())
|
|
3339
|
+
continue;
|
|
3340
|
+
const startMs = Math.max(0, Math.round(m.tMs));
|
|
3341
|
+
fileMarks.push({ startMs, text: m.text.trim() }); // the mark of record, verbatim
|
|
3342
|
+
if (m.id) {
|
|
3343
|
+
abandonedIds.add(m.id);
|
|
3344
|
+
if (m.unverified) {
|
|
3345
|
+
unverifiedClaimById.set(m.id, startMs);
|
|
3346
|
+
assertUnverified++;
|
|
3347
|
+
}
|
|
3174
3348
|
}
|
|
3175
3349
|
}
|
|
3176
3350
|
}
|
|
3177
3351
|
catch {
|
|
3178
3352
|
// no marks file — fine
|
|
3179
3353
|
}
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
|
|
3184
|
-
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3354
|
+
// Resolve the daemon marks against the file marks of record.
|
|
3355
|
+
const resolvedDaemon = [];
|
|
3356
|
+
let assertPassed = 0;
|
|
3357
|
+
let assertFailed = 0;
|
|
3358
|
+
for (const dm of daemonMarks) {
|
|
3359
|
+
if (dm.id && unverifiedClaimById.has(dm.id)) {
|
|
3360
|
+
// The client already recorded a ⚠ mark of record for this assertion; this
|
|
3361
|
+
// daemon copy is a LATE evaluation. Emit it as a separate, honestly-timed
|
|
3362
|
+
// "late check" annotation (not counted in P/F/K).
|
|
3363
|
+
const claimMs = unverifiedClaimById.get(dm.id);
|
|
3364
|
+
const evalAt = Math.max(0, dm.evalAtMs ?? dm.startMs);
|
|
3365
|
+
const afterSec = Math.max(0, Math.round((evalAt - claimMs) / 1000));
|
|
3366
|
+
const oc = dm.assertOutcome;
|
|
3367
|
+
const verdict = oc
|
|
3368
|
+
? oc.passed
|
|
3369
|
+
? `✓ ${oc.observed}`
|
|
3370
|
+
: `✗ expected ${oc.expected}; observed ${oc.observed}`
|
|
3371
|
+
: "(no result)";
|
|
3372
|
+
resolvedDaemon.push({
|
|
3373
|
+
startMs: evalAt,
|
|
3374
|
+
text: `[late check of "${dm.claim ?? ""}" — evaluated ${afterSec}s after the claim: ${verdict}]`,
|
|
3375
|
+
});
|
|
3376
|
+
continue;
|
|
3377
|
+
}
|
|
3378
|
+
if (dm.id && abandonedIds.has(dm.id)) {
|
|
3379
|
+
// A plain mark/chapter the client already wrote to the file — dedup, the
|
|
3380
|
+
// file copy is the mark of record. (Exactly once.)
|
|
3381
|
+
continue;
|
|
3382
|
+
}
|
|
3383
|
+
resolvedDaemon.push({ startMs: dm.startMs, text: dm.text });
|
|
3384
|
+
if (dm.assertOutcome) {
|
|
3385
|
+
if (dm.assertOutcome.passed)
|
|
3386
|
+
assertPassed++;
|
|
3387
|
+
else
|
|
3388
|
+
assertFailed++;
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3391
|
+
let notes = [...fileMarks, ...resolvedDaemon, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
|
|
3392
|
+
// If any ORIGINAL assertion was attempted (evaluated pass/fail, or recorded
|
|
3393
|
+
// ⚠-unverified), prepend a 0ms verification summary so it LEADS the transcript
|
|
3394
|
+
// (a stable sort keeps it ahead of other 0ms marks). The K clause is omitted
|
|
3395
|
+
// when K=0 so existing renderings don't churn. Late checks don't count.
|
|
3396
|
+
const assertN = assertPassed + assertFailed + assertUnverified;
|
|
3397
|
+
if (assertN > 0) {
|
|
3398
|
+
const tally = `${assertN} assertion(s): ${assertPassed} passed, ${assertFailed} failed` +
|
|
3399
|
+
(assertUnverified > 0 ? `, ${assertUnverified} unverified` : "");
|
|
3400
|
+
notes.unshift({ startMs: 0, text: `[verification] ${tally}` });
|
|
3189
3401
|
notes.sort((a, b) => a.startMs - b.startMs);
|
|
3190
3402
|
}
|
|
3191
3403
|
// Server limit: cap the merged set at 200 marks (the verification note sorts
|
|
@@ -3231,6 +3443,11 @@ async function runSessionDaemon(file) {
|
|
|
3231
3443
|
finally {
|
|
3232
3444
|
if (controlServer)
|
|
3233
3445
|
controlServer.close();
|
|
3446
|
+
// Persistent (--user-data-dir) contexts have no separate browser, so an
|
|
3447
|
+
// exception before the stop/abort path must close the context to avoid
|
|
3448
|
+
// leaking Chromium. Both closes are no-ops if the object is already closed.
|
|
3449
|
+
if (ctxToClose)
|
|
3450
|
+
await ctxToClose.close().catch(() => { });
|
|
3234
3451
|
if (browser)
|
|
3235
3452
|
await browser.close().catch(() => { });
|
|
3236
3453
|
}
|
|
@@ -3324,7 +3541,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
|
|
|
3324
3541
|
// command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
|
|
3325
3542
|
// contract changes.
|
|
3326
3543
|
// ---------------------------------------------------------------------------
|
|
3327
|
-
const GUIDE_SCHEMA_VERSION =
|
|
3544
|
+
const GUIDE_SCHEMA_VERSION = 7;
|
|
3328
3545
|
function cmdGuide(json) {
|
|
3329
3546
|
if (!json) {
|
|
3330
3547
|
process.stdout.write(HELP);
|
|
@@ -3352,6 +3569,7 @@ function cmdGuide(json) {
|
|
|
3352
3569
|
{ name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; write commands need the 'ingest' scope" },
|
|
3353
3570
|
{ name: "CLIPY_API_URL", description: "API base URL override (default https://clipy.online)" },
|
|
3354
3571
|
{ name: "CLIPY_DISABLE_CDP", description: "set to 1 to force session --expose-cdp off (a hard kill switch that wins over the flag)" },
|
|
3572
|
+
{ name: "CLIPY_SESSION_FILE", description: "path to a session state file that mark/chapter/session stop|abort|status resolve FIRST (before the cwd hash). `session run` exports it to the child so a driver can mark from any cwd." },
|
|
3355
3573
|
{ name: "NO_COLOR", description: "disable ANSI color" },
|
|
3356
3574
|
],
|
|
3357
3575
|
exitCodes: [
|
|
@@ -3374,8 +3592,8 @@ function cmdGuide(json) {
|
|
|
3374
3592
|
cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
|
|
3375
3593
|
cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
|
|
3376
3594
|
cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
|
|
3377
|
-
cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load
|
|
3378
|
-
cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen] [--window w] [--display d] [--expose-cdp] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). --window/--display (with --source mac-screen) record one window/display. --expose-cdp (web sessions) opens a CDP endpoint (cdpUrl/cdpHttpUrl in the state file + session start/status output) so your own tools can drive the page while it records; OFF by default (any local process could attach), and CLIPY_DISABLE_CDP=1 forces it off. `session run [start flags] -- <command…>` starts a session, runs the command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code — the crash-safe wrapper so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp", "--storage-state", "--cookie", "--local-storage", "--init-script", "--json"]),
|
|
3595
|
+
cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch a persistent Chromium profile with its whole logged-in identity; web only, mutually exclusive with --storage-state, refused if the dir looks like a live/locked Chrome profile via a SingletonLock/Socket). Auth boundary: --storage-state only seeds what the file contains; for cross-origin auth produce it with `npx playwright open --save-storage=auth.json <login-host>`, or use --user-data-dir, or --source mac-screen --window Chrome. With --source mac-screen: records the real screen via the Clipy Mac app (--type not yet applied on mac; auth flags rejected — the screen is already logged in); --window '<title|app|id>' or --display <id> target one window/display (ids from clipy sources). --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--user-data-dir", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
|
|
3596
|
+
cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen] [--window w] [--display d] [--expose-cdp] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). --window/--display (with --source mac-screen) record one window/display. --expose-cdp (web sessions) opens a CDP endpoint (cdpUrl/cdpHttpUrl in the state file + session start/status output) so your own tools can drive the page while it records; OFF by default (any local process could attach), and CLIPY_DISABLE_CDP=1 forces it off. `session run [start flags] -- <command…>` starts a session, runs the command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code — the crash-safe wrapper so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--user-data-dir/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp", "--storage-state", "--user-data-dir", "--cookie", "--local-storage", "--init-script", "--json"]),
|
|
3379
3597
|
cmdDoc("mark", "clipy mark \"<text>\" [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>] [--json]", "Drop a live-timestamped note into the active session. ASSERTION MARKS make the note evidence instead of a claim: --assert-selector checks a CSS selector matches (its trimmed textContent is recorded as 'observed'); --assert-text requires that element's text to contain a substring (needs --assert-selector); --assert-url matches the page URL against a glob (** = any, * = any non-slash, no * = substring). The daemon evaluates against its live page and annotates the mark: pass ⇒ '<text> [assert ✓ <observed>]', fail ⇒ '<text> [ASSERT ✗ expected …; observed …]' — a false claim cannot read as fact. --fail-mode warn (default) records the ✗; --fail-mode abort DISCARDS the whole session on a failed assertion (no upload) and the CLI exits non-zero. If any assertions ran, a leading 0ms '[verification] N assertion(s): P passed, F failed' note is prepended. --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now (mutually exclusive). Assertions/backdating need a web session (rejected on --source mac-screen). Up to 200 marks per recording.", ["--assert-selector", "--assert-text", "--assert-url", "--fail-mode", "--at", "--ago", "--json"]),
|
|
3380
3598
|
cmdDoc("chapter", "clipy chapter \"<label>\" [--json]", "Mark a BEFORE/AFTER section boundary in the active recording (stored as '=== CHAPTER: <label> ==='). The PR-review shape: demo the base branch, run `clipy chapter \"AFTER — fix applied\"`, swap branches + restart the dev server, demo the fix — one video carrying both states. Works on web + --source mac-screen sessions.", ["--json"]),
|
|
3381
3599
|
cmdDoc("doctor", "clipy doctor [--json]", "One-shot health check: API key + whoami round-trip, Mac agent bridge (exists/parses/pid/appVersion>=" + MIN_BRIDGE_APP_VERSION + "), Playwright resolvability (and the resolved path/node_modules dir), and install mode (npx/global/local) — each a pass/warn/fail with a fix hint; exits non-zero if any check fails", ["--json"]),
|
|
@@ -3393,9 +3611,10 @@ function cmdGuide(json) {
|
|
|
3393
3611
|
"--note is absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text'); pass-scoped notes anchor to the real start of a --viewports pass, so they don't drift when load time shifts the pass boundaries. A malformed pass note (e.g. 'pass2 text' with no colon) is a usage error, not silently demoted.",
|
|
3394
3612
|
"--type declares what a recording IS (bug_report/feature_request/product_demo/walkthrough_tutorial/feedback_review/discussion_talk/other, plus short aliases) so the AI summary doesn't misread a demo as a bug report. Applied on web today; --source mac-screen support is pending a Clipy app update.",
|
|
3395
3613
|
"Assertion marks are the differentiator: assert what you claim. `clipy mark \"X\" --assert-selector '.status' --assert-text Active` records X only alongside the live-page truth — the daemon runs the check against its Playwright page and annotates the mark ✓/✗ with what it actually observed, so a false claim cannot pass as fact in the transcript. --fail-mode abort turns a failed assertion into a discarded session (nothing uploaded, non-zero exit). Assertions need a web session and the daemon's control endpoint (started by clipy 0.6+); they are rejected on --source mac-screen.",
|
|
3614
|
+
"A mark is NEVER dropped, and a late verdict never rewrites it. If the daemon can't be reached to evaluate an assertion (its event loop briefly starved during a dev-server recompile), `clipy mark` records the narration anyway tagged '[ASSERT ⚠ could not evaluate — <reason>]', prints a loud ⚠, and exits 0 — an unverified claim is flagged, never promoted to a ✓. The tally's third bucket counts these: '[verification] N assertion(s): P passed, F failed, K unverified' (the ', K unverified' clause is omitted when K=0). That ⚠ is the MARK OF RECORD: if the daemon was only slow and evaluates the same claim later, that verdict judged a LATER page state, so it does NOT overwrite the ⚠ — it's recorded as a separate '[late check of \"…\" — evaluated Ns after the claim: …]' note at its own time and counts toward none of P/F/K. Plain non-asserted marks the daemon later processes are just deduped (exactly once).",
|
|
3396
3615
|
"clipy chapter \"<label>\" splits one recording into BEFORE/AFTER sections for PR-review-style demos: record the base branch, `clipy chapter \"AFTER — fix applied\"`, swap branches + restart, record the fix. One video carries both states.",
|
|
3397
3616
|
"clipy session run [start flags] -- <command…> is the crash-safe wrapper: it starts a session, runs your driver command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp), and guarantees cleanup — exit 0 uploads, any non-zero exit or signal discards and propagates the code. Use it so a crashing driver never records dead air to the max ceiling.",
|
|
3398
|
-
"clipy mark --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now — a `clipy mark` spawn lands ~100-300ms late, so backdate to align a mark with the state it describes. When driving over --expose-cdp, call window.__clipyMark(
|
|
3617
|
+
"clipy mark --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now — a `clipy mark` spawn lands ~100-300ms late, so backdate to align a mark with the state it describes. Backdating an ASSERTED mark: it lands at the backdated time but the assertion judges the LIVE page, so if the verdict was observed >2s from the backdated position the text gains '(assertion observed Ns after this backdated mark — the verdict describes the page at observation time)' and --json carries a signed assert.driftSec; live-clock asserted marks and backdated plain marks are unaffected. When driving over --expose-cdp, call window.__clipyMark(text, opts?) / window.__clipyChapter(label) IN-PAGE (page.evaluate) to emit marks/chapters with zero spawn latency, evaluated daemon-side with the page in hand. __clipyMark's opts {assertSelector, assertText, assertUrl, failMode} run the SAME assertions as the CLI flags (assertText requires assertSelector or the call rejects; failMode 'abort' discards the session); it returns the annotated {tMs, text, assert}. While CDP is exposed the page's own scripts can call these too (within the existing --expose-cdp trust model).",
|
|
3399
3618
|
"session --expose-cdp (web, opt-in) publishes a CDP endpoint (cdpHttpUrl) in `session start`/`session status` output and the 0600 session state file; connect with playwright.connectOverCDP() to drive the recorded page. Off by default (any local process could attach); CLIPY_DISABLE_CDP=1 forces it off.",
|
|
3400
3619
|
"Driving an --expose-cdp session: connect with playwright.connectOverCDP(cdpHttpUrl); the recorded page is browser.contexts()[0].pages()[0] (a fresh context/page you open is NOT captured); page.viewportSize() is null over a CDP attach; resize with a CDP session's Emulation.setDeviceMetricsOverride, not setViewportSize. Your own driver script resolves Playwright from its own cwd — run it as NODE_PATH=$(clipy playwright-path) node driver.js if require('playwright') can't find it.",
|
|
3401
3620
|
"Auth for headless web capture (record + session start): --storage-state <playwright storageState JSON> is passed straight to Playwright's newContext; --cookie / --local-storage / --init-script are applied to the context BEFORE the first navigation, so a logged-in SPA's route guard sees the state on first paint (seeding it after navigating loses that race). --cookie without a Domain is url-scoped to the target; with a Domain it is domain-scoped. --local-storage pairs are origin-guarded to the target. All four are web-only and are rejected on --source mac-screen, which records the real, already-signed-in screen. The storage-state file may hold live credentials; the CLI never prints its contents and the session state file that carries these specs is chmod 0600.",
|
|
@@ -3507,6 +3726,7 @@ async function main() {
|
|
|
3507
3726
|
ago: { type: "string" },
|
|
3508
3727
|
"expose-cdp": { type: "boolean", default: false },
|
|
3509
3728
|
"storage-state": { type: "string" },
|
|
3729
|
+
"user-data-dir": { type: "string" },
|
|
3510
3730
|
"init-script": { type: "string" },
|
|
3511
3731
|
cookie: { type: "string", multiple: true },
|
|
3512
3732
|
"local-storage": { type: "string", multiple: true },
|
|
@@ -3546,6 +3766,7 @@ async function main() {
|
|
|
3546
3766
|
// screen). Resolve the file paths to absolute so the detached daemon — spawned
|
|
3547
3767
|
// without an explicit cwd — reads the same files the parent validated.
|
|
3548
3768
|
const authFlagsPresent = Boolean(values["storage-state"] ||
|
|
3769
|
+
values["user-data-dir"] ||
|
|
3549
3770
|
values["init-script"] ||
|
|
3550
3771
|
values.cookie?.length ||
|
|
3551
3772
|
values["local-storage"]?.length);
|
|
@@ -3555,7 +3776,18 @@ async function main() {
|
|
|
3555
3776
|
cookieSpecs: values.cookie ?? [],
|
|
3556
3777
|
localStorageSpecs: values["local-storage"] ?? [],
|
|
3557
3778
|
});
|
|
3558
|
-
|
|
3779
|
+
// --user-data-dir launches a persistent profile context (web only). Resolved to
|
|
3780
|
+
// absolute so the detached daemon (no explicit cwd) opens the same dir. It's
|
|
3781
|
+
// mutually exclusive with --storage-state — die(2) when both are set.
|
|
3782
|
+
const userDataDir = () => {
|
|
3783
|
+
if (!values["user-data-dir"])
|
|
3784
|
+
return undefined;
|
|
3785
|
+
if (values["storage-state"]) {
|
|
3786
|
+
die("--user-data-dir and --storage-state are mutually exclusive — a persistent profile already carries its own storage; pick one", 2);
|
|
3787
|
+
}
|
|
3788
|
+
return resolve(String(values["user-data-dir"]));
|
|
3789
|
+
};
|
|
3790
|
+
const macAuthGuard = "auth state (--storage-state/--user-data-dir/--cookie/--local-storage/--init-script) applies to headless web capture — --source mac-screen records the real, already-logged-in screen";
|
|
3559
3791
|
switch (command) {
|
|
3560
3792
|
case "login":
|
|
3561
3793
|
await cmdLogin(ctx, {
|
|
@@ -3744,6 +3976,7 @@ async function main() {
|
|
|
3744
3976
|
wait: Boolean(values.wait),
|
|
3745
3977
|
json,
|
|
3746
3978
|
auth: authCapture(),
|
|
3979
|
+
userDataDir: userDataDir(),
|
|
3747
3980
|
});
|
|
3748
3981
|
return;
|
|
3749
3982
|
}
|
|
@@ -3784,6 +4017,7 @@ async function main() {
|
|
|
3784
4017
|
source: source,
|
|
3785
4018
|
exposeCdp: Boolean(values["expose-cdp"]),
|
|
3786
4019
|
auth: authCapture(),
|
|
4020
|
+
userDataDir: userDataDir(),
|
|
3787
4021
|
};
|
|
3788
4022
|
};
|
|
3789
4023
|
if (sub === "start") {
|
package/dist/skill.js
CHANGED
|
@@ -15,7 +15,7 @@ description: Read and create Clipy screen recordings. Use when the user shares a
|
|
|
15
15
|
|
|
16
16
|
# Clipy — recordings you can read AND make
|
|
17
17
|
|
|
18
|
-
Written for @clipy/cli + @clipy/mcp 0.8.
|
|
18
|
+
Written for @clipy/cli + @clipy/mcp 0.8.2 (the two versions move in lockstep). If
|
|
19
19
|
\`clipy --version\` reports older, upgrade first: \`npm i -g @clipy/cli@latest\`.
|
|
20
20
|
|
|
21
21
|
Clipy (clipy.online) is the screen recorder built to be agent-readable. Every
|
|
@@ -103,6 +103,25 @@ work on both \`record\` and \`session start\` (web only; rejected on --source ma
|
|
|
103
103
|
repeatable; without a Domain it's url-scoped to the target.
|
|
104
104
|
- \`--local-storage "key=value"\` — repeatable; origin-guarded to the target.
|
|
105
105
|
- \`--init-script <file>\` — a JS file run before every page's own scripts.
|
|
106
|
+
- \`--user-data-dir <dir>\` — launch a PERSISTENT Chromium profile from \`dir\`
|
|
107
|
+
(its whole logged-in identity, not just injected storage). Web only; mutually
|
|
108
|
+
exclusive with --storage-state; --cookie/--local-storage/--init-script still
|
|
109
|
+
compose. Point it at a COPY or a dedicated profile — never your live Chrome's
|
|
110
|
+
default profile (Chrome locks it; Clipy refuses a dir with a SingletonLock).
|
|
111
|
+
|
|
112
|
+
### The auth boundary (read this if a login won't stick)
|
|
113
|
+
|
|
114
|
+
\`--storage-state\` seeds ONLY the cookies + localStorage the file CONTAINS — it
|
|
115
|
+
cannot conjure a whole browser identity, so an app that also needs cross-origin
|
|
116
|
+
or auth-host cookies (SSO, a separate API domain) can still bounce to /login.
|
|
117
|
+
Three reliable ways to record a real logged-in app:
|
|
118
|
+
1. Produce the state file with a REAL interactive login (it captures cross-domain
|
|
119
|
+
cookies): \`npx playwright open --save-storage=auth.json https://<login-host>\`,
|
|
120
|
+
sign in, close — then \`--storage-state auth.json\`.
|
|
121
|
+
2. \`--user-data-dir <dedicated-profile>\` — a persistent profile you logged into
|
|
122
|
+
once (copy it out of your real Chrome, or make a throwaway profile).
|
|
123
|
+
3. \`--source mac-screen --window "Chrome"\` — record your REAL logged-in Chrome
|
|
124
|
+
window (Mac app), no headless auth to reproduce at all.
|
|
106
125
|
|
|
107
126
|
## Session mode — you drive the app, Clipy records
|
|
108
127
|
|
|
@@ -152,10 +171,20 @@ A pass annotates the mark \`… [assert ✓ <observed>]\`; a fail annotates it
|
|
|
152
171
|
assertion, it can never read as fact. \`--fail-mode warn\` (default) records the ✗
|
|
153
172
|
and keeps going; \`--fail-mode abort\` DISCARDS the whole session (nothing uploaded,
|
|
154
173
|
non-zero exit) so you never ship a clip that asserted its way into a broken state.
|
|
155
|
-
If any
|
|
156
|
-
note opens the transcript.
|
|
157
|
-
|
|
158
|
-
|
|
174
|
+
If any assertion was attempted, a leading \`[verification] N assertion(s): P passed,
|
|
175
|
+
F failed[, K unverified]\` note opens the transcript.
|
|
176
|
+
|
|
177
|
+
A mark is NEVER dropped: if the recording daemon can't be reached to evaluate an
|
|
178
|
+
assertion (e.g. its event loop is briefly starved during a dev-server recompile),
|
|
179
|
+
\`clipy mark\` still records the narration, tags it \`[ASSERT ⚠ could not evaluate —
|
|
180
|
+
<reason>]\`, prints a loud ⚠, and exits 0 — an unverified claim is flagged as
|
|
181
|
+
unverified (the K bucket), never passed off as a ✓. That ⚠ is the MARK OF RECORD:
|
|
182
|
+
if the daemon was only slow and evaluates the same claim a moment later, that late
|
|
183
|
+
verdict does NOT overwrite the ⚠ (it judged a later page state) — it's recorded as a
|
|
184
|
+
separate \`[late check of "…" — evaluated Ns after the claim: …]\` note at its own
|
|
185
|
+
time, and it counts toward neither passed/failed/unverified. Assertions need a WEB
|
|
186
|
+
session (rejected on --source mac-screen — there's no page to probe). Prefer
|
|
187
|
+
asserting the specific claims a reviewer cares about over narrating them unverified.
|
|
159
188
|
|
|
160
189
|
### Before/after in one recording (clipy chapter)
|
|
161
190
|
|
|
@@ -178,9 +207,13 @@ If your driver script crashes, a plain \`session start\` keeps recording dead ai
|
|
|
178
207
|
|
|
179
208
|
It starts the session, runs everything after \`--\` with inherited stdio, then: exit
|
|
180
209
|
0 → \`session stop\` (upload); any non-zero exit or signal → \`session abort\` (discard)
|
|
181
|
-
with the child's exit code propagated. The command runs with \`CLIPY_SESSION=1
|
|
182
|
-
|
|
183
|
-
before the \`--\`.
|
|
210
|
+
with the child's exit code propagated. The command runs with \`CLIPY_SESSION=1\`,
|
|
211
|
+
\`CLIPY_SESSION_FILE=<path>\`, and (when --expose-cdp) \`CLIPY_CDP_URL=<cdpHttpUrl>\`.
|
|
212
|
+
All session-start flags apply before the \`--\`.
|
|
213
|
+
|
|
214
|
+
\`clipy mark\`/\`chapter\` find the session from \`CLIPY_SESSION_FILE\` first, then the
|
|
215
|
+
current directory — so a driver you \`session run\` can shell out \`clipy mark\` from
|
|
216
|
+
ANY cwd and still hit the right session (no "no recording session" surprise).
|
|
184
217
|
|
|
185
218
|
### Mark timing (backdating + in-page marks)
|
|
186
219
|
|
|
@@ -190,12 +223,36 @@ the state it describes. Backdate onto the recording clock:
|
|
|
190
223
|
clipy mark "toast appeared" --ago 2 # 2s before now
|
|
191
224
|
clipy mark "page loaded" --at 4 # absolute 4s on the recording clock
|
|
192
225
|
|
|
226
|
+
Backdating an ASSERTED mark: the mark lands at the backdated time, but the assertion
|
|
227
|
+
judges the LIVE page (the daemon can't rewind). If the verdict was observed >2s from
|
|
228
|
+
the backdated position, the mark stays put and its text gains \`(assertion observed Ns
|
|
229
|
+
after this backdated mark — the verdict describes the page at observation time)\` plus a
|
|
230
|
+
signed \`assert.driftSec\` in --json — so a ✓/✗ isn't misread as describing the earlier
|
|
231
|
+
moment. So: assert on the LIVE clock, and reserve --at/--ago for narration you're
|
|
232
|
+
backdating without a claim (or accept the disclaimer).
|
|
233
|
+
|
|
193
234
|
When you drive over --expose-cdp, emit marks IN-PAGE with zero spawn latency by
|
|
194
|
-
calling the bindings the daemon exposes
|
|
235
|
+
calling the bindings the daemon exposes (they run daemon-side with the page in
|
|
236
|
+
hand — no \`clipy mark\` process, no shell-out latency):
|
|
195
237
|
|
|
196
238
|
await page.evaluate(() => window.__clipyMark("clicked Export"));
|
|
197
239
|
await page.evaluate(() => window.__clipyChapter("AFTER — fix applied"));
|
|
198
240
|
|
|
241
|
+
\`__clipyMark\` takes the SAME assertions as the CLI, via a second options arg —
|
|
242
|
+
evaluated daemon-side, annotated ✓/✗ identically:
|
|
243
|
+
|
|
244
|
+
await page.evaluate(() =>
|
|
245
|
+
window.__clipyMark("status is Active", {
|
|
246
|
+
assertSelector: ".status-badge", assertText: "Active", // assertText needs assertSelector
|
|
247
|
+
assertUrl: "**/redemptions", // optional
|
|
248
|
+
failMode: "abort", // optional; "warn" default
|
|
249
|
+
}),
|
|
250
|
+
);
|
|
251
|
+
|
|
252
|
+
It returns the annotated result (\`{ tMs, text, assert }\`); \`assertText\` without
|
|
253
|
+
\`assertSelector\` REJECTS so your driver sees the misuse, and \`failMode: "abort"\`
|
|
254
|
+
discards the session just like the CLI flag.
|
|
255
|
+
|
|
199
256
|
(While CDP is exposed the page's own scripts can call these too — same trust model as
|
|
200
257
|
--expose-cdp itself.) \`clipy playwright-path\` prints the node_modules dir to resolve
|
|
201
258
|
Playwright for your driver: \`NODE_PATH=$(clipy playwright-path) node driver.js\`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clipy/cli",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.2",
|
|
4
4
|
"description": "Command-line interface for Clipy — list, search, and read your screen recordings' transcripts, AI summaries, and key moments from the terminal.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|