@clipy/cli 0.8.0 → 0.8.1

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
@@ -146,6 +146,13 @@ 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. Point it at a **copy** or a
154
+ dedicated profile — never your live Chrome's default profile: Chrome locks a profile
155
+ while it's open, so Clipy refuses a dir that has a `SingletonLock`/`SingletonSocket`.
149
156
 
150
157
  ```bash
151
158
  # Reuse a saved Playwright login
@@ -155,8 +162,30 @@ clipy record --url https://app.example.com/dashboard --for 20 \
155
162
  # Or seed a token directly
156
163
  clipy record --url https://app.example.com/dashboard \
157
164
  --local-storage "authToken=eyJ…" --cookie "sid=abc; Domain=app.example.com; Secure"
165
+
166
+ # Or record a persistent logged-in profile
167
+ clipy record --url https://app.example.com/dashboard --for 20 \
168
+ --user-data-dir ./clipy-profile
158
169
  ```
159
170
 
171
+ #### The auth boundary
172
+
173
+ `--storage-state` seeds only the cookies and `localStorage` the **file contains** — it
174
+ can't conjure a whole browser identity, so an app that also needs cross-origin or
175
+ auth-host cookies (SSO, a separate API domain) can still bounce to `/login`. Three
176
+ reliable ways to get a real logged-in recording:
177
+
178
+ 1. **Produce the state file with a real interactive login** (it captures cross-domain
179
+ cookies a hand-built file misses):
180
+ ```bash
181
+ npx playwright open --save-storage=auth.json https://login.example.com
182
+ # sign in, close the window, then:
183
+ clipy record --url https://app.example.com/dashboard --storage-state auth.json
184
+ ```
185
+ 2. **`--user-data-dir <dedicated-profile>`** — a persistent profile you logged into once.
186
+ 3. **`--source mac-screen --window "Chrome"`** — record your real, already-logged-in
187
+ Chrome window through the Mac app; there's no headless auth to reproduce at all.
188
+
160
189
  ## Session mode — you work, Clipy records
161
190
 
162
191
  For recordings where an agent (or you) drives the app live, don't script the capture:
@@ -208,12 +237,28 @@ resolves Playwright from **its own** directory — if `require("playwright")` ca
208
237
  run the script with `NODE_PATH=$(clipy playwright-path) node driver.js`.
209
238
 
210
239
  **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 page.
212
- Calling them from your driver (`page.evaluate(() => window.__clipyMark("clicked Export"))`)
213
- emits a mark or chapter *without* spawning a `clipy mark` process, so it lands exactly when
214
- your code runs. These marks land in the same transcript and count toward the same 200-mark
215
- cap. Note: while CDP is exposed the page's **own** scripts can call these too — that's the
216
- same trust boundary as `--expose-cdp` itself (any local process can already drive the
240
+ `window.__clipyMark("text", opts?)` and `window.__clipyChapter("label")` in the recorded
241
+ page. Calling them from your driver emits a mark/chapter *without* spawning a `clipy mark`
242
+ process, so it lands exactly when your code runs, and it runs **daemon-side with the page in
243
+ hand**. `__clipyMark`'s second argument takes the same assertions as the CLI flags —
244
+ evaluated and annotated ✓/✗ identically:
245
+
246
+ ```js
247
+ await page.evaluate(() => window.__clipyMark("clicked Export"));
248
+ await page.evaluate(() =>
249
+ window.__clipyMark("status is Active", {
250
+ assertSelector: ".status-badge",
251
+ assertText: "Active", // needs assertSelector — otherwise the call rejects
252
+ assertUrl: "**/redemptions", // optional
253
+ failMode: "abort", // optional; "warn" is the default
254
+ }),
255
+ );
256
+ ```
257
+
258
+ It returns the annotated `{ tMs, text, assert }`; `failMode: "abort"` discards the session
259
+ just like the flag. These marks land in the same transcript and count toward the same
260
+ 200-mark cap. Note: while CDP is exposed the page's **own** scripts can call these too —
261
+ the same trust boundary as `--expose-cdp` itself (any local process can already drive the
217
262
  browser), so only enable it when you intend to drive the session.
218
263
 
219
264
  `session start` also accepts the same auth flags as `record`
@@ -256,8 +301,18 @@ freely — all provided checks must pass.
256
301
  `--fail-mode` decides what a failed assertion does: `warn` (default) records the `✗` and
257
302
  keeps recording; **`abort` discards the whole session** — nothing is uploaded and the CLI
258
303
  exits non-zero, so a driver that asserts its way to a broken state doesn't ship a misleading
259
- clip. If any assertions ran, a leading `[verification] N assertion(s): P passed, F failed`
260
- note is prepended at 0 ms, so the transcript and the `.md` context open with the scorecard.
304
+ clip. If any assertion was attempted, a leading `[verification] N assertion(s): P passed,
305
+ F failed[, K unverified]` note is prepended at 0 ms, so the transcript and the `.md` context
306
+ open with the scorecard.
307
+
308
+ **A mark is never dropped.** If the daemon can't be reached to evaluate an assertion — its
309
+ event loop briefly starved during a heavy dev-server recompile, say — `clipy mark` doesn't
310
+ fail and lose the note. It records the narration anyway, tags it
311
+ `[ASSERT ⚠ could not evaluate — <reason>]`, prints a loud `⚠`, and exits 0. An unverified
312
+ claim is flagged as unverified (the `K` in the tally), never silently promoted to a `✓`. If
313
+ the daemon was only slow (not gone) and processes the same mark a moment later, a
314
+ client-generated id dedups the two so the evaluated copy wins and the mark appears exactly
315
+ once.
261
316
 
262
317
  Assertions evaluate against a real page, so they need a **web** session (they're rejected on
263
318
  `--source mac-screen`, which records the real screen with no page to probe).
@@ -288,11 +343,16 @@ clipy session run --url http://localhost:3000 --expose-cdp -- node driver.js
288
343
 
289
344
  It starts the session, runs everything after `--` with inherited stdio, and then: **exit 0
290
345
  → `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
- in its environment (and `CLIPY_CDP_URL=<cdpHttpUrl>` when `--expose-cdp` is set, so the
293
- driver knows where to attach). `Ctrl-C` is forwarded to the child, then the session is
294
- discarded. All the `session start` flags (`--url`, `--title`, `--max`, `--type`,
295
- `--expose-cdp`, auth flags) apply before the `--`.
346
+ (discard) and the child's exit code is propagated. The command runs with `CLIPY_SESSION=1`,
347
+ `CLIPY_SESSION_FILE=<path>`, and (when `--expose-cdp`) `CLIPY_CDP_URL=<cdpHttpUrl>` in its
348
+ environment. `Ctrl-C` is forwarded to the child, then the session is discarded. All the
349
+ `session start` flags (`--url`, `--title`, `--max`, `--type`, `--expose-cdp`, auth flags)
350
+ apply before the `--`.
351
+
352
+ `clipy mark` / `clipy chapter` resolve the session from `CLIPY_SESSION_FILE` first and the
353
+ current directory second — so a driver you launch with `session run` can shell out
354
+ `clipy mark …` from **any working directory** and still hit the right session, instead of
355
+ failing with "no recording session in this workspace".
296
356
 
297
357
  ### Backdating a mark
298
358
 
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
- const browser = await chromium.launch({
1801
- headless: true,
1802
- // Cloud sandboxes / CI containers run as root where Chromium's own
1803
- // sandbox can't initialize; this is a user-driven capture of a URL they
1804
- // chose, so the browser sandbox isn't a trust boundary here.
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
- const context = await browser.newContext({
1809
- viewport: { width: frame.width, height: frame.height },
1810
- recordVideo: { dir: tmpDir, size: frame },
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
- await browser.close().catch(() => { });
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 = sessionFilePath(process.cwd());
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
- text: text.trim(),
2480
+ id: markId,
2481
+ text: cleanText,
2400
2482
  ...(atMs != null ? { atMs } : {}),
2401
2483
  ...(hasAssert ? { assert: opts.assert } : {}),
2402
- }, 5000);
2484
+ }, CONTROL_TIMEOUT_MS);
2403
2485
  }
2404
2486
  catch (e) {
2405
- // Assertions REQUIRE the live page — there's no honest file fallback for a
2406
- // verification the daemon couldn't run. Plain marks fall back to the file.
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
- die(`the session daemon isn't answering — assertions need the live page (${e.message})`);
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
- const tMs = atMs != null ? atMs : Math.max(0, Date.now() - state.recordStartEpochMs);
2411
- appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`, { mode: 0o600 });
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
- const tMs = atMs != null ? atMs : Math.max(0, Date.now() - state.recordStartEpochMs);
2429
- appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`, { mode: 0o600 });
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 }, 5000);
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 = sessionFilePath(process.cwd());
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
  });
@@ -2851,8 +2948,16 @@ async function runSessionDaemon(file) {
2851
2948
  let assertFailed = 0;
2852
2949
  // A failed --fail-mode=abort assertion sets this; the main loop discards.
2853
2950
  let controlSignal = null;
2951
+ // Client-generated ids of marks/chapters we processed over HTTP — so at merge
2952
+ // we can drop a file duplicate the client wrote after its call timed out but
2953
+ // the daemon actually completed it.
2954
+ const processedMarkIds = new Set();
2854
2955
  mkdirSync(state.tmpDir, { recursive: true });
2855
2956
  let browser = null;
2957
+ // Persistent (--user-data-dir) contexts have no separate browser, so track the
2958
+ // context too for the finally cleanup (an exception before stop must not leak
2959
+ // the Chromium).
2960
+ let ctxToClose = null;
2856
2961
  let controlServer = null;
2857
2962
  try {
2858
2963
  const chromium = await loadChromium();
@@ -2866,52 +2971,33 @@ async function runSessionDaemon(file) {
2866
2971
  if (state.exposeCdp && !wantCdp)
2867
2972
  log("CDP disabled by CLIPY_DISABLE_CDP=1 — not opening a debugging port");
2868
2973
  const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
2869
- browser = await chromium.launch({
2870
- headless: true,
2974
+ // --user-data-dir ⇒ a persistent context (its own browser); else an ephemeral
2975
+ // browser + context. The CDP debugging port (if any) rides the launch args.
2976
+ const { context, browser: launchedBrowser } = await launchRecordingContext(chromium, {
2977
+ userDataDir: state.userDataDir,
2978
+ viewport: { width: state.width, height: state.height },
2979
+ recordVideoDir: state.tmpDir,
2871
2980
  args: [
2872
2981
  "--no-sandbox",
2873
2982
  "--disable-dev-shm-usage",
2874
2983
  ...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
2875
2984
  ],
2985
+ storageStatePath: state.storageStatePath,
2876
2986
  });
2877
- const context = await browser.newContext({
2878
- viewport: { width: state.width, height: state.height },
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
- });
2987
+ browser = launchedBrowser;
2988
+ ctxToClose = context;
2883
2989
  // Seed cookies/localStorage/init-script before the first navigation — re-parse
2884
2990
  // 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.
2991
+ // the outer try/catch and fails the session cleanly. (--storage-state was
2992
+ // applied at launch; it and --user-data-dir are mutually exclusive.)
2886
2993
  await applyAuthCapture(context, {
2887
2994
  storageStatePath: state.storageStatePath,
2888
2995
  initScriptPath: state.initScriptPath,
2889
2996
  cookieSpecs: state.cookieSpecs ?? [],
2890
2997
  localStorageSpecs: state.localStorageSpecs ?? [],
2891
2998
  }, state.url);
2892
- // In-page mark/chapter bindings — only under --expose-cdp, and only alongside
2893
- // the debugging port a driver already uses. A page.evaluate(() =>
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();
2999
+ // Persistent contexts open with a default page; ephemeral ones start empty.
3000
+ const page = context.pages()[0] ?? (await context.newPage());
2915
3001
  // Best-effort: publish the CDP URL so `session start`/`status` can hand it
2916
3002
  // to the agent. The recording works fine even if discovery fails.
2917
3003
  let cdpUrl;
@@ -2947,29 +3033,25 @@ async function runSessionDaemon(file) {
2947
3033
  // ignore
2948
3034
  }
2949
3035
  }));
2950
- // Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
2951
- // which owns the live page — evaluates assertions and stamps marks on its
2952
- // own clock. 127.0.0.1 only, bearer-token auth (random UUID). If it can't
2953
- // bind, the recording still runs and marks fall back to the marks file.
2954
- const controlToken = randomUUID();
2955
- let controlPort = 0;
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() : "";
3036
+ // The ONE place a mark is recorded, shared by the HTTP control endpoint and
3037
+ // the in-page __clipyMark binding, so both evaluate assertions against the
3038
+ // live page identically. Records the (annotated) mark and returns the
3039
+ // CLI/driver-facing response.
3040
+ const applyMark = async (m) => {
3041
+ const text = m.text.trim();
2960
3042
  if (!text)
2961
3043
  throw new Error("mark text is required");
2962
- const tMs = typeof body.atMs === "number" && Number.isFinite(body.atMs)
2963
- ? Math.max(0, Math.round(body.atMs))
3044
+ const tMs = typeof m.atMs === "number" && Number.isFinite(m.atMs)
3045
+ ? Math.max(0, Math.round(m.atMs))
2964
3046
  : Math.max(0, Date.now() - recordStart);
2965
3047
  let annotated = text;
2966
3048
  let assertOut;
2967
3049
  let aborted = false;
2968
- const assertSpec = body.assert;
2969
- if (assertSpec && typeof assertSpec === "object") {
2970
- // evaluateAssertion throws if the page is unresponsive — surfaced as a
2971
- // 5xx so the CLI die()s rather than recording an unverified claim.
2972
- const ev = await evaluateAssertion(page, assertSpec);
3050
+ if (m.assert && typeof m.assert === "object") {
3051
+ // evaluateAssertion throws if the page is unresponsive — the HTTP path
3052
+ // turns that into a 5xx (the CLI then records a ⚠ UNVERIFIED file mark),
3053
+ // and the in-page path rejects to the driver.
3054
+ const ev = await evaluateAssertion(page, m.assert);
2973
3055
  assertRan++;
2974
3056
  if (ev.passed)
2975
3057
  assertPassed++;
@@ -2979,12 +3061,14 @@ async function runSessionDaemon(file) {
2979
3061
  ? `${text} [assert ✓ ${ev.observed}]`
2980
3062
  : `${text} [ASSERT ✗ expected ${ev.expected}; observed ${ev.observed}]`;
2981
3063
  assertOut = { passed: ev.passed, observed: ev.observed };
2982
- if (!ev.passed && assertSpec.failMode === "abort")
3064
+ if (!ev.passed && m.assert.failMode === "abort")
2983
3065
  aborted = true;
2984
3066
  }
2985
3067
  if (!storeDaemonMark({ startMs: tMs, text: annotated })) {
2986
3068
  throw new Error("mark limit reached (200 marks per recording)");
2987
3069
  }
3070
+ if (m.id)
3071
+ processedMarkIds.add(m.id);
2988
3072
  if (aborted)
2989
3073
  controlSignal = "abort";
2990
3074
  return {
@@ -2994,7 +3078,62 @@ async function runSessionDaemon(file) {
2994
3078
  ...(aborted ? { aborted: true } : {}),
2995
3079
  };
2996
3080
  };
2997
- /** POST /chapter → a =={ CHAPTER }== mark at the live clock. */
3081
+ // In-page mark/chapter bindings — only under --expose-cdp, alongside the
3082
+ // debugging port a driver already uses. window.__clipyMark(text, opts?) with
3083
+ // opts {assertSelector, assertText, assertUrl, failMode} runs the SAME
3084
+ // daemon-side assertion + annotation as the CLI flags, at ZERO spawn cost.
3085
+ // NOTE: while CDP is exposed the page's own scripts can call these too —
3086
+ // within the existing --expose-cdp trust model (documented in the README).
3087
+ if (wantCdp) {
3088
+ await context
3089
+ .exposeBinding("__clipyMark", async (_src, ...args) => {
3090
+ if (recordStart === 0)
3091
+ return { skipped: true };
3092
+ const o = (args[1] ?? {});
3093
+ let assert;
3094
+ if (o.assertSelector || o.assertText || o.assertUrl) {
3095
+ // Thrown here ⇒ the page's `await window.__clipyMark(...)` rejects, so
3096
+ // the driver sees the misuse (mirrors the CLI's die(2)).
3097
+ if (o.assertText != null && !o.assertSelector) {
3098
+ throw new Error("__clipyMark: assertText requires assertSelector");
3099
+ }
3100
+ assert = {
3101
+ selector: o.assertSelector,
3102
+ expectText: o.assertText,
3103
+ urlGlob: o.assertUrl,
3104
+ failMode: o.failMode === "abort" ? "abort" : "warn",
3105
+ };
3106
+ }
3107
+ return await applyMark({ text: String(args[0] ?? ""), assert });
3108
+ })
3109
+ .catch((e) => log(`__clipyMark binding failed: ${e.message}`));
3110
+ await context
3111
+ .exposeBinding("__clipyChapter", (_src, ...args) => {
3112
+ if (recordStart === 0)
3113
+ return;
3114
+ const label = String(args[0] ?? "").trim();
3115
+ if (label) {
3116
+ storeDaemonMark({ startMs: Math.max(0, Date.now() - recordStart), text: `=== CHAPTER: ${label} ===` });
3117
+ }
3118
+ })
3119
+ .catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
3120
+ }
3121
+ // Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
3122
+ // which owns the live page — evaluates assertions and stamps marks on its
3123
+ // own clock. 127.0.0.1 only, bearer-token auth (random UUID). If it can't
3124
+ // bind, the recording still runs and marks fall back to the marks file.
3125
+ const controlToken = randomUUID();
3126
+ let controlPort = 0;
3127
+ /** POST /mark → applyMark (shared with the in-page binding): stamp, optional
3128
+ * assertion against the live page, store, and return the CLI-facing shape.
3129
+ * The client id rides through so a timed-out-but-processed mark is deduped. */
3130
+ const handleMark = (body) => applyMark({
3131
+ text: typeof body.text === "string" ? body.text : "",
3132
+ atMs: typeof body.atMs === "number" ? body.atMs : undefined,
3133
+ assert: body.assert,
3134
+ id: typeof body.id === "string" ? body.id : undefined,
3135
+ });
3136
+ /** POST /chapter → a === CHAPTER === mark at the live clock. */
2998
3137
  const handleChapter = (body) => {
2999
3138
  const label = typeof body.label === "string" ? body.label.trim() : "";
3000
3139
  if (!label)
@@ -3003,6 +3142,8 @@ async function runSessionDaemon(file) {
3003
3142
  if (!storeDaemonMark({ startMs: tMs, text: `=== CHAPTER: ${label} ===` })) {
3004
3143
  throw new Error("mark limit reached (200 marks per recording)");
3005
3144
  }
3145
+ if (typeof body.id === "string" && body.id)
3146
+ processedMarkIds.add(body.id);
3006
3147
  return { tMs };
3007
3148
  };
3008
3149
  const BODY_CAP = 1_000_000;
@@ -3157,35 +3298,47 @@ async function runSessionDaemon(file) {
3157
3298
  if (!video)
3158
3299
  throw new Error("browser did not produce a video (recordVideo unavailable)");
3159
3300
  const videoPath = await video.path();
3160
- await browser.close().catch(() => { });
3301
+ // Persistent mode: context.close() (above) already tore down Chromium; there
3302
+ // is no separate browser to close.
3303
+ if (browser)
3304
+ await browser.close().catch(() => { });
3161
3305
  browser = null;
3162
3306
  // Merge marks from three sources: the file (fallback path, written by
3163
3307
  // `clipy mark` when the control endpoint was unreachable), the daemon-side
3164
3308
  // marks (control endpoint + in-page bindings, already assertion-annotated),
3165
3309
  // and the [auto] instrumentation marks.
3166
3310
  const fileMarks = [];
3311
+ let assertUnverified = 0;
3167
3312
  try {
3168
3313
  for (const line of readFileSync(state.marksPath, "utf8").split("\n")) {
3169
3314
  if (!line.trim())
3170
3315
  continue;
3171
3316
  const m = JSON.parse(line);
3172
- if (typeof m.tMs === "number" && typeof m.text === "string" && m.text.trim()) {
3173
- fileMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
3174
- }
3317
+ if (typeof m.tMs !== "number" || typeof m.text !== "string" || !m.text.trim())
3318
+ continue;
3319
+ // Dedup: the daemon already processed this mark over HTTP (the client's
3320
+ // control call timed out, but the daemon completed it) — keep the daemon's
3321
+ // evaluated copy, drop this file duplicate.
3322
+ if (m.id && processedMarkIds.has(m.id))
3323
+ continue;
3324
+ fileMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
3325
+ if (m.unverified)
3326
+ assertUnverified++; // ⚠ marks the CLI recorded but couldn't verify
3175
3327
  }
3176
3328
  }
3177
3329
  catch {
3178
3330
  // no marks file — fine
3179
3331
  }
3180
3332
  let notes = [...fileMarks, ...daemonMarks, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
3181
- // If any assertions ran, prepend a 0ms verification summary so it LEADS the
3182
- // transcript and the .md context (a stable sort keeps it ahead of other 0ms
3183
- // marks). This is the "recordings are evidence" headline.
3184
- if (assertRan > 0) {
3185
- notes.unshift({
3186
- startMs: 0,
3187
- text: `[verification] ${assertRan} assertion(s): ${assertPassed} passed, ${assertFailed} failed`,
3188
- });
3333
+ // If any assertion was ATTEMPTED (evaluated pass/fail OR recorded ⚠-unverified),
3334
+ // prepend a 0ms verification summary so it LEADS the transcript (a stable sort
3335
+ // keeps it ahead of other 0ms marks). The K-unverified clause is omitted when
3336
+ // K=0 so existing renderings don't churn.
3337
+ const assertN = assertPassed + assertFailed + assertUnverified;
3338
+ if (assertN > 0) {
3339
+ const tally = `${assertN} assertion(s): ${assertPassed} passed, ${assertFailed} failed` +
3340
+ (assertUnverified > 0 ? `, ${assertUnverified} unverified` : "");
3341
+ notes.unshift({ startMs: 0, text: `[verification] ${tally}` });
3189
3342
  notes.sort((a, b) => a.startMs - b.startMs);
3190
3343
  }
3191
3344
  // Server limit: cap the merged set at 200 marks (the verification note sorts
@@ -3231,6 +3384,11 @@ async function runSessionDaemon(file) {
3231
3384
  finally {
3232
3385
  if (controlServer)
3233
3386
  controlServer.close();
3387
+ // Persistent (--user-data-dir) contexts have no separate browser, so an
3388
+ // exception before the stop/abort path must close the context to avoid
3389
+ // leaking Chromium. Both closes are no-ops if the object is already closed.
3390
+ if (ctxToClose)
3391
+ await ctxToClose.close().catch(() => { });
3234
3392
  if (browser)
3235
3393
  await browser.close().catch(() => { });
3236
3394
  }
@@ -3324,7 +3482,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
3324
3482
  // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
3325
3483
  // contract changes.
3326
3484
  // ---------------------------------------------------------------------------
3327
- const GUIDE_SCHEMA_VERSION = 5;
3485
+ const GUIDE_SCHEMA_VERSION = 6;
3328
3486
  function cmdGuide(json) {
3329
3487
  if (!json) {
3330
3488
  process.stdout.write(HELP);
@@ -3352,6 +3510,7 @@ function cmdGuide(json) {
3352
3510
  { name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; write commands need the 'ingest' scope" },
3353
3511
  { name: "CLIPY_API_URL", description: "API base URL override (default https://clipy.online)" },
3354
3512
  { name: "CLIPY_DISABLE_CDP", description: "set to 1 to force session --expose-cdp off (a hard kill switch that wins over the flag)" },
3513
+ { 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
3514
  { name: "NO_COLOR", description: "disable ANSI color" },
3356
3515
  ],
3357
3516
  exitCodes: [
@@ -3374,8 +3533,8 @@ function cmdGuide(json) {
3374
3533
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
3375
3534
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
3376
3535
  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>. 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", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
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"]),
3536
+ 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"]),
3537
+ 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
3538
  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
3539
  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
3540
  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 +3552,10 @@ function cmdGuide(json) {
3393
3552
  "--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
3553
  "--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
3554
  "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.",
3555
+ "A mark is NEVER dropped. 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). Every mark carries a client id so a slow-but-not-gone daemon that later processes the same mark dedups the two — the evaluated copy wins and the mark appears exactly once.",
3396
3556
  "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
3557
  "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(\"text\") / window.__clipyChapter(\"label\") IN-PAGE (page.evaluate) to emit marks/chapters with zero spawn latency; while CDP is exposed the page's own scripts can call these too (within the existing --expose-cdp trust model).",
3558
+ "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(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
3559
  "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
3560
  "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
3561
  "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 +3667,7 @@ async function main() {
3507
3667
  ago: { type: "string" },
3508
3668
  "expose-cdp": { type: "boolean", default: false },
3509
3669
  "storage-state": { type: "string" },
3670
+ "user-data-dir": { type: "string" },
3510
3671
  "init-script": { type: "string" },
3511
3672
  cookie: { type: "string", multiple: true },
3512
3673
  "local-storage": { type: "string", multiple: true },
@@ -3546,6 +3707,7 @@ async function main() {
3546
3707
  // screen). Resolve the file paths to absolute so the detached daemon — spawned
3547
3708
  // without an explicit cwd — reads the same files the parent validated.
3548
3709
  const authFlagsPresent = Boolean(values["storage-state"] ||
3710
+ values["user-data-dir"] ||
3549
3711
  values["init-script"] ||
3550
3712
  values.cookie?.length ||
3551
3713
  values["local-storage"]?.length);
@@ -3555,7 +3717,18 @@ async function main() {
3555
3717
  cookieSpecs: values.cookie ?? [],
3556
3718
  localStorageSpecs: values["local-storage"] ?? [],
3557
3719
  });
3558
- const macAuthGuard = "auth state applies to headless web capture — --source mac-screen records the real, already-logged-in screen";
3720
+ // --user-data-dir launches a persistent profile context (web only). Resolved to
3721
+ // absolute so the detached daemon (no explicit cwd) opens the same dir. It's
3722
+ // mutually exclusive with --storage-state — die(2) when both are set.
3723
+ const userDataDir = () => {
3724
+ if (!values["user-data-dir"])
3725
+ return undefined;
3726
+ if (values["storage-state"]) {
3727
+ die("--user-data-dir and --storage-state are mutually exclusive — a persistent profile already carries its own storage; pick one", 2);
3728
+ }
3729
+ return resolve(String(values["user-data-dir"]));
3730
+ };
3731
+ 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
3732
  switch (command) {
3560
3733
  case "login":
3561
3734
  await cmdLogin(ctx, {
@@ -3744,6 +3917,7 @@ async function main() {
3744
3917
  wait: Boolean(values.wait),
3745
3918
  json,
3746
3919
  auth: authCapture(),
3920
+ userDataDir: userDataDir(),
3747
3921
  });
3748
3922
  return;
3749
3923
  }
@@ -3784,6 +3958,7 @@ async function main() {
3784
3958
  source: source,
3785
3959
  exposeCdp: Boolean(values["expose-cdp"]),
3786
3960
  auth: authCapture(),
3961
+ userDataDir: userDataDir(),
3787
3962
  };
3788
3963
  };
3789
3964
  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.0 (the two versions move in lockstep). If
18
+ Written for @clipy/cli + @clipy/mcp 0.8.1 (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,16 @@ 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 assertions ran, a leading \`[verification] N assertion(s): P passed, F failed\`
156
- note opens the transcript. Assertions need a WEB session (rejected on --source
157
- mac-screen — there's no page to probe). Prefer asserting the specific claims a
158
- reviewer cares about over narrating them unverified.
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 ✓. Assertions need a WEB session
182
+ (rejected on --source mac-screen — there's no page to probe). Prefer asserting the
183
+ specific claims a reviewer cares about over narrating them unverified.
159
184
 
160
185
  ### Before/after in one recording (clipy chapter)
161
186
 
@@ -178,9 +203,13 @@ If your driver script crashes, a plain \`session start\` keeps recording dead ai
178
203
 
179
204
  It starts the session, runs everything after \`--\` with inherited stdio, then: exit
180
205
  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\` set
182
- (and \`CLIPY_CDP_URL=<cdpHttpUrl>\` when --expose-cdp). All session-start flags apply
183
- before the \`--\`.
206
+ with the child's exit code propagated. The command runs with \`CLIPY_SESSION=1\`,
207
+ \`CLIPY_SESSION_FILE=<path>\`, and (when --expose-cdp) \`CLIPY_CDP_URL=<cdpHttpUrl>\`.
208
+ All session-start flags apply before the \`--\`.
209
+
210
+ \`clipy mark\`/\`chapter\` find the session from \`CLIPY_SESSION_FILE\` first, then the
211
+ current directory — so a driver you \`session run\` can shell out \`clipy mark\` from
212
+ ANY cwd and still hit the right session (no "no recording session" surprise).
184
213
 
185
214
  ### Mark timing (backdating + in-page marks)
186
215
 
@@ -191,11 +220,27 @@ the state it describes. Backdate onto the recording clock:
191
220
  clipy mark "page loaded" --at 4 # absolute 4s on the recording clock
192
221
 
193
222
  When you drive over --expose-cdp, emit marks IN-PAGE with zero spawn latency by
194
- calling the bindings the daemon exposes:
223
+ calling the bindings the daemon exposes (they run daemon-side with the page in
224
+ hand — no \`clipy mark\` process, no shell-out latency):
195
225
 
196
226
  await page.evaluate(() => window.__clipyMark("clicked Export"));
197
227
  await page.evaluate(() => window.__clipyChapter("AFTER — fix applied"));
198
228
 
229
+ \`__clipyMark\` takes the SAME assertions as the CLI, via a second options arg —
230
+ evaluated daemon-side, annotated ✓/✗ identically:
231
+
232
+ await page.evaluate(() =>
233
+ window.__clipyMark("status is Active", {
234
+ assertSelector: ".status-badge", assertText: "Active", // assertText needs assertSelector
235
+ assertUrl: "**/redemptions", // optional
236
+ failMode: "abort", // optional; "warn" default
237
+ }),
238
+ );
239
+
240
+ It returns the annotated result (\`{ tMs, text, assert }\`); \`assertText\` without
241
+ \`assertSelector\` REJECTS so your driver sees the misuse, and \`failMode: "abort"\`
242
+ discards the session just like the CLI flag.
243
+
199
244
  (While CDP is exposed the page's own scripts can call these too — same trust model as
200
245
  --expose-cdp itself.) \`clipy playwright-path\` prints the node_modules dir to resolve
201
246
  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.0",
3
+ "version": "0.8.1",
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",