@aarwitz/tapp 0.18.4 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tapp",
3
3
  "description": "Give Claude hands and eyes on iOS, Android, and web apps, with exploration, replayable flows, evidence, and deterministic CI gates.",
4
- "version": "0.18.4",
4
+ "version": "0.19.0",
5
5
  "author": {
6
6
  "name": "Aaron Horowitz",
7
7
  "url": "https://github.com/aarwitz"
@@ -24,7 +24,7 @@
24
24
  "command": "npx",
25
25
  "args": [
26
26
  "-y",
27
- "@aarwitz/tapp@0.18.4",
27
+ "@aarwitz/tapp@0.19.0",
28
28
  "mcp"
29
29
  ],
30
30
  "cwd": "${CLAUDE_PROJECT_DIR}"
package/AGENTS.md CHANGED
@@ -17,6 +17,9 @@ npx -y @aarwitz/tapp@latest explore --goal "SCREEN OR CONTROL" [target] # source
17
17
  npx -y @aarwitz/tapp@latest explore https://your-app.example --watch # web: visibly follow the same exploration
18
18
  npx -y @aarwitz/tapp@latest explore --read-only https://example.com --pages 5 # never clicks: production or a site you do not own
19
19
  npx -y @aarwitz/tapp@latest look [target] # launch + screen summary + screenshot saved to a file (≈ tapp_look)
20
+ npx -y @aarwitz/tapp@latest look latest # a finished run: its screens, each with its moment in the recording
21
+ npx -y @aarwitz/tapp@latest look latest --at 6 # one screen's frame, seeked (not scanned) out of the video
22
+ npx -y @aarwitz/tapp@latest look latest --frames # contact sheets — many frames per image, to scan a run cheaply
20
23
  npx -y @aarwitz/tapp@latest look [target] --tree # + the accessibility tree, --json for every element
21
24
  npx -y @aarwitz/tapp@latest look # no target on iOS: the booted sim as it is → file path
22
25
  npx -y @aarwitz/tapp@latest explore app.apk --platform android --app-id com.acme.app
@@ -70,6 +73,8 @@ installs, returns the bundle id) → `tapp_explore {appBundleId}`.
70
73
  | "Is this live site / production / a prospect's site broken?" | `tapp_explore {readOnly:true}` (CLI `tapp explore --read-only <url> --pages N`) — read-only: dead controls, broken images/links/assets, failed requests, JS errors, mixed content, overflow; writes a capture with evidence | `tapp_explore` (it clicks, types and submits) |
71
74
  | "Make this flow a repeatable test" | drive it in a session, then `tapp_session {action:"save_flow"}`; replay with `tapp_run` | re-driving it by hand every time |
72
75
  | "What's on screen right now?" | `tapp_look` | relaunching the app |
76
+ | "What happened during that run?" / "show me the frame where X" | `tapp_look {capture:"latest", at:"<n\|screen>"}` | re-running the app to reproduce something already recorded |
77
+ | "Scan a recording for something odd" | `tapp_look {capture:"latest", frames:true}` (contact sheets) | pulling frames one at a time, or sampling a handful and calling it a look |
73
78
 
74
79
  ## Session driving (the Playwright loop)
75
80
 
package/bin/tapp.js CHANGED
@@ -131,6 +131,17 @@ function parseVerbArgs(argv) {
131
131
  // ADR-0007: twelve public verbs, one engine. The resolver maps the public surface onto the
132
132
  // internal case labels below (which keep their original argument shapes), and keeps every older
133
133
  // verb working as a hidden alias that names its new form once on stderr.
134
+ // Is this target a finished run rather than something to launch? A capture is a directory with
135
+ // the markers a run writes, addressed by id, by path, or as "latest". Deliberately narrow: a
136
+ // bundle id, a URL, a repo dir and an .apk must all still mean what they meant before.
137
+ function looksLikeCapture(value) {
138
+ const raw = String(value || "").trim();
139
+ if (!raw || raw.startsWith("-") || /^https?:\/\//i.test(raw)) return false;
140
+ if (raw === "latest") return true;
141
+ const marked = (dir) => { try { return fs.existsSync(path.join(dir, "ocqa-markers.txt")); } catch { return false; } };
142
+ return marked(path.resolve(raw)) || marked(path.join(tappHome, "captures", raw));
143
+ }
144
+
134
145
  function artifactKind(file) {
135
146
  if (!file) return "flow";
136
147
  if (/\.ts$/.test(file)) return "contract";
@@ -156,10 +167,16 @@ function resolveCommand(command, rest) {
156
167
  if (goal >= 0 && rest[goal + 1] !== undefined) return { command: "focus", rest: [rest[goal + 1], ...rest.slice(0, goal), ...rest.slice(goal + 2)] };
157
168
  return { command, rest };
158
169
  }
159
- case "look":
170
+ case "look": {
171
+ // A capture is a target like any other (`report [capture]` already takes one), so looking
172
+ // at a finished run is the same verb as looking at a running app — only the screen is
173
+ // recorded rather than live. See the 2026-10-21 amendment to ADR-0007.
174
+ const subject = rest.find((a) => !a.startsWith("--"));
175
+ if (looksLikeCapture(subject) || has("--frames") || has("--at")) return { command: "frames", rest };
160
176
  if (has("--sim")) return { command: "shot", rest: without("--sim") };
161
177
  if (has("--tree")) return { command: "tree", rest: without("--tree") };
162
178
  return { command: "open", rest };
179
+ }
163
180
  case "run":
164
181
  return { command: artifactKind(rest.find((a) => !a.startsWith("--"))), rest: ["run", ...rest] };
165
182
  case "validate": {
@@ -343,7 +360,7 @@ function safeCommandUsage(verb) {
343
360
  explore: "tapp explore [target] [--platform ios|android|web] [--actions N] [--timeout SEC] [--email VALUE] [--password VALUE] [--baseline FILE] [--json FILE]\n --read-only <url>...: never clicks (dead controls, broken links/assets, failed requests, JS exceptions, mixed content, overflow) [--pages N] [--urls FILE] [--json [FILE]]\n --goal \"SCREEN OR CONTROL\": source-locate a screen/control and take the shortest observed route [--project-dir REPO] [--target NAME|PATH] [--map FILE] [--out FILE]\n Web: [--watch] opens Tapp's controlled browser and shows its actions; [--device \"iPhone 13\"] [--viewport 390x844] render at a device profile or explicit size\n iOS: [--device \"iPhone 16\"|UDID] chooses the simulator (required when more than one is booted; TAPP_UDID is the default)\n iOS launch configuration: [--launch-arg VALUE ...] [--launch-env '{\"KEY\":\"VALUE\"}']\n Android: [--app-id ID] [--apk FILE] [--serial ID] [--keep-data]",
344
361
  focus: "tapp explore --goal \"SCREEN OR CONTROL\" [target] [--platform ios|android|web] [--project-dir REPO] [--target NAME|PATH] [--map FILE] [--out FILE]",
345
362
  init: "tapp init [repo] [--explore] [--refresh] [--platform PLATFORM] [--target NAME] [--url URL] [--watch] [--dry-run]",
346
- open: "tapp look [target] [--platform ios|android|web] [--out FILE] [--tap TEXT] [--wait-for TEXT]\n --tree: accessibility tree of the current screen (--json for every element)\n --sim: screenshot the booted simulator only (never builds or installs)\n iOS: [--device \"iPhone 16\"|UDID] chooses the simulator (required when more than one is booted)\n Web: [--device \"iPhone 13\"] [--viewport 390x844] [--full-page]",
363
+ open: "tapp look [target] [--platform ios|android|web] [--out FILE] [--tap TEXT] [--wait-for TEXT]\n --tree: accessibility tree of the current screen (--json for every element)\n <capture>|latest: the screens of a finished run — [--at N|\"screen\"] one frame, [--frames] contact sheets for scanning, [--json] the index\n --sim: screenshot the booted simulator only (never builds or installs)\n iOS: [--device \"iPhone 16\"|UDID] chooses the simulator (required when more than one is booted)\n Web: [--device \"iPhone 13\"] [--viewport 390x844] [--full-page]",
347
364
  tree: "tapp look --tree [target] [--platform ios|android|web] [--json] [--tap TEXT] [--wait-for TEXT]\n iOS: inspects an installed app; never builds or installs.\n Web: [--device \"iPhone 13\"] [--viewport 390x844]",
348
365
  shot: "tapp look --sim [--out FILE]",
349
366
  apps: "tapp apps",
@@ -2082,11 +2099,37 @@ switch (command) {
2082
2099
  }
2083
2100
  const port = flags.port === undefined ? 0 : Number(flags.port);
2084
2101
  if (!Number.isInteger(port) || port < 0 || port > 65535) { console.error("❌ --port must be 0..65535"); process.exit(2); }
2102
+ // --public serves the Studio to anyone who can reach it: no account, a read-only website
2103
+ // audit each, evidence scoped per visitor, and every browser connection forced through the
2104
+ // public-egress proxy. Repositories, live sessions and the gate stay unavailable, because
2105
+ // there is no way to offer them safely to an anonymous visitor on a shared machine.
2106
+ const publicAccess = flags.public === true;
2107
+ const publicOrigin = typeof flags.origin === "string" ? flags.origin : "";
2108
+ // https for anything real; plain http on loopback so the public mode can be dry-run locally
2109
+ // before a tunnel or TLS terminator is in front of it.
2110
+ const localOrigin = /^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d{1,5})?$/.test(publicOrigin);
2111
+ if (publicAccess && !localOrigin && !/^https:\/\/[^\s/]+$/.test(publicOrigin)) {
2112
+ console.error("❌ --public needs --origin https://your.domain (or an http://127.0.0.1:PORT origin to try it locally)");
2113
+ process.exit(2);
2114
+ }
2115
+ if (publicAccess && flags.port === undefined) { console.error("❌ --public needs an explicit --port"); process.exit(2); }
2085
2116
  const { startBrowserProduct } = await import(path.join(packageRoot, "mcp-server", "src", "browser-product.js"));
2086
- const product = await startBrowserProduct({ projectDir, port, launch: flags.open !== false && flags["no-open"] !== true });
2087
- console.log(`Tapp · ${product.root || "choose a local folder or GitHub repository in the browser"}`);
2088
- console.log(`Open: ${product.launchUrl}`);
2089
- console.log("Local-only session; press Ctrl-C to stop.");
2117
+ const product = await startBrowserProduct({
2118
+ projectDir, port,
2119
+ launch: !publicAccess && flags.open !== false && flags["no-open"] !== true,
2120
+ ...(publicAccess ? { publicAccess: true, publicOrigin } : {}),
2121
+ });
2122
+ if (publicAccess) {
2123
+ console.log(`Tapp · public Studio for ${publicOrigin}`);
2124
+ console.log(`Listening on ${product.origin} — put a TLS terminator or tunnel in front of it.`);
2125
+ console.log("Anonymous visitors may audit a public website read-only. Repositories, live");
2126
+ console.log("sessions and the release gate require an authenticated local session.");
2127
+ console.log("Browser egress is pinned to public addresses; private ranges are refused.");
2128
+ } else {
2129
+ console.log(`Tapp · ${product.root || "choose a local folder or GitHub repository in the browser"}`);
2130
+ console.log(`Open: ${product.launchUrl}`);
2131
+ console.log("Local-only session; press Ctrl-C to stop.");
2132
+ }
2090
2133
  const shutdown = async () => { try { await product.close(); } finally { process.exit(0); } };
2091
2134
  process.once("SIGINT", shutdown);
2092
2135
  process.once("SIGTERM", shutdown);
@@ -2094,6 +2137,67 @@ switch (command) {
2094
2137
  break;
2095
2138
  }
2096
2139
 
2140
+ // `tapp look <capture>` — the screens of a finished run. Same verb as looking at a live app;
2141
+ // the screen is recorded rather than in front of us (ADR-0007, amended 2026-10-21).
2142
+ case "frames": {
2143
+ const { flags, positionals } = parseVerbArgs(rest);
2144
+ const { resolveCapture, captureIndex, selectState, extractFrame, contactSheets, writePlayableCopy } =
2145
+ await import(path.join(packageRoot, "mcp-server", "src", "capture-frames.js"));
2146
+
2147
+ const dir = resolveCapture(positionals[0] || "latest");
2148
+ if (!dir) { console.error(`❌ No capture found for ${positionals[0] || "latest"}`); process.exit(2); }
2149
+ const index = captureIndex(dir);
2150
+
2151
+ if (flags.json !== undefined) {
2152
+ const out = typeof flags.json === "string" ? flags.json : "";
2153
+ const payload = JSON.stringify(index, null, 2);
2154
+ if (out) { fs.writeFileSync(out, payload); console.log(`Wrote ${out}`); } else console.log(payload);
2155
+ break;
2156
+ }
2157
+
2158
+ console.log(`📼 ${index.capture} — ${index.states.length} screen(s), ${index.actions} action(s), ${index.findings} finding(s)`);
2159
+ if (index.recording) {
2160
+ console.log(` recording: ${index.recording.file}${index.recording.indexed ? "" : " (no frame index — re-run to seek by screen)"}`);
2161
+ const playable = await writePlayableCopy(index.recording.path).catch(() => null);
2162
+ if (playable) console.log(` playable: ${path.basename(playable)}`);
2163
+ } else {
2164
+ console.log(" recording: none — screenshots only");
2165
+ }
2166
+
2167
+ if (flags.at !== undefined) {
2168
+ const state = selectState(index, flags.at);
2169
+ if (!state) { console.error(`❌ No screen matching '${flags.at}'. Screens: ${index.states.map((x) => `${x.index}:${x.screen}`).join(", ")}`); process.exit(2); }
2170
+ const out = typeof flags.out === "string" ? flags.out : path.join(dir, `frame_${state.index}.png`);
2171
+ const got = await extractFrame(index, state, out);
2172
+ if (!got) { console.error("❌ No frame or screenshot exists for that screen"); process.exit(1); }
2173
+ console.log(`\n${state.index}. ${state.screen}${state.url ? ` ${state.url}` : ""}`);
2174
+ console.log(` ${got.from === "recording" ? `frame at ${(got.atMs / 1000).toFixed(1)}s` : "screenshot"} → ${got.file}`);
2175
+ if (state.findings.length) for (const f of state.findings) console.log(` • ${f.severity} ${f.title}`);
2176
+ break;
2177
+ }
2178
+
2179
+ if (flags.frames) {
2180
+ const out = typeof flags.frames === "string" ? flags.frames : path.join(dir, "frames");
2181
+ const sheets = await contactSheets(index, out);
2182
+ if (!sheets.length) { console.error("❌ Nothing to tile — the run recorded no video and no screenshots"); process.exit(1); }
2183
+ console.log(`\n${sheets.length} contact sheet(s) — many frames per image, for scanning:`);
2184
+ for (const sheet of sheets) console.log(` ${sheet}`);
2185
+ break;
2186
+ }
2187
+
2188
+ // Default: the screens, with where each one is in the recording.
2189
+ console.log("");
2190
+ for (const state of index.states) {
2191
+ const when = state.videoAtMs != null ? `${(state.videoAtMs / 1000).toFixed(1)}s` : state.t != null ? `${(state.t / 1000).toFixed(1)}s` : "—";
2192
+ console.log(`${String(state.index).padStart(2)}. ${when.padStart(7)} ${state.screen}${state.url ? ` ${state.url}` : ""}`);
2193
+ if (state.screenshot) console.log(` ${state.screenshot}`);
2194
+ for (const f of state.findings) console.log(` • ${f.severity} ${f.title}`);
2195
+ }
2196
+ console.log(`\nOne screen: tapp look ${index.capture} --at <n|"screen">`);
2197
+ console.log(`Scan them: tapp look ${index.capture} --frames`);
2198
+ break;
2199
+ }
2200
+
2097
2201
  case "report": {
2098
2202
  // Regenerate + open the HTML evidence page for a capture (default: the latest).
2099
2203
  const capturesDir = path.join(tappHome, "captures");
@@ -2201,6 +2305,9 @@ Observe — look at the real app (no Tapp account or server required):
2201
2305
  straight to a named screen · web: --watch · --platform ios|android|web · --actions N)
2202
2306
  tapp look [target] One screen: summary + screenshot (--tree adds the accessibility tree,
2203
2307
  --sim screenshots the booted simulator · web: --tap TEXT · --wait-for TEXT)
2308
+ A capture id, a capture path, or 'latest' reads a finished run instead:
2309
+ its screens with the moment each was reached (--at N|"screen" pulls one
2310
+ frame · --frames tiles many frames per image for scanning · --json)
2204
2311
 
2205
2312
  Replay — deterministic, keyless:
2206
2313
  tapp run FILE Replay a committed Flow, Task, release contract, or Scenario
package/browser/app.js CHANGED
@@ -88,6 +88,29 @@ function activateView(view) {
88
88
  window.scrollTo({ top:0, behavior:"instant" });
89
89
  }
90
90
 
91
+ // A hosted Studio has no Mac, no simulator and no access to the visitor's disk, so folders,
92
+ // bundle ids and builds cannot work there however the prompt is worded. Offer only what this
93
+ // deployment can actually do, and say where the rest runs, rather than failing after the ask.
94
+ function applyAccessMode() {
95
+ const session = state.session || {};
96
+ if (session.access !== "anonymous") return;
97
+ const accepts = new Set(session.accepts || ["url"]);
98
+ for (const button of document.querySelectorAll("[data-kind]")) {
99
+ const kind = button.dataset.kind;
100
+ const usable = kind === "url" ? accepts.has("url") : accepts.has(kind);
101
+ button.closest("li")?.classList.toggle("hidden", !usable);
102
+ }
103
+ const input = $("#prompt-input");
104
+ if (input) input.placeholder = "A website URL…";
105
+ // Everything that only means something against a source repository: a target to build, a
106
+ // runner, a release gate, a decision. A hosted visitor auditing a URL has none of them, and
107
+ // showing the empty frames makes a working run look like a broken one.
108
+ for (const node of document.querySelectorAll("[data-repo-only]")) node.classList.add("hidden");
109
+ setHeading("tapp", "Give it a public website and it will audit the pages read-only.");
110
+ const note = $("#privacy-note-detail");
111
+ if (note) note.textContent = "Websites are audited read-only in the cloud; nothing is clicked. iOS, Android and folders on your own machine need tapp there: npx -y @aarwitz/tapp@latest app";
112
+ }
113
+
91
114
  function showPrompt() {
92
115
  $("#source-onboarding").classList.remove("hidden");
93
116
  $("#product-shell").classList.add("hidden");
@@ -472,9 +495,21 @@ async function refreshSession() {
472
495
  $("#mode-pill").textContent = local ? "Self-host · this machine" : "Cloud · outbound runner";
473
496
  $("#onboarding-mode-pill").textContent = local ? "Self-host · this machine" : "Cloud";
474
497
  $("#privacy-note-detail").textContent = local ? "Everything runs on this machine. Exploration, replay and merge decisions are deterministic and need no API key." : "Your repository stays in your private Tapp workspace.";
498
+ applyAccessMode();
475
499
  }
476
500
 
477
501
  async function refresh() {
502
+ // A public visitor has no project and no live session, and asking for them would only earn a
503
+ // 401 on every poll.
504
+ if (state.session?.access === "anonymous") {
505
+ const runs = await api("/api/audits").catch(() => ({ audits: [], explores: [] }));
506
+ state.project = { connected:false };
507
+ state.live = { active:false };
508
+ state.audits = runs.audits || [];
509
+ state.explores = runs.explores || [];
510
+ renderProject();
511
+ return;
512
+ }
478
513
  const [project, live, runs] = await Promise.all([api("/api/project"), api("/api/live-session"), api("/api/audits").catch(() => ({ audits: [], explores: [] }))]);
479
514
  state.project = project;
480
515
  state.live = live;
@@ -534,12 +569,37 @@ async function runOperation(name, body = {}, { input = "" } = {}) {
534
569
 
535
570
  // "What should tapp test?" — route by what was typed. The server classifies again and refuses
536
571
  // what the mode cannot do (a hosted Studio cannot open a path on your machine).
572
+ function setHeading(title, summary) {
573
+ const heading = $("#app-name");
574
+ if (heading) heading.textContent = title;
575
+ const note = $("#app-summary");
576
+ if (note) note.textContent = summary;
577
+ }
578
+
579
+ // Some targets simply cannot run where this Studio is running — a folder on someone's disk, a
580
+ // simulator build, a repository that needs a toolchain. The engine answers with where they do
581
+ // run; show that answer where it stays put, not in a toast that disappears in six seconds.
582
+ function answerSelfHost(answer) {
583
+ setHeading("Run this on your machine", "The cloud Studio audits websites; this target needs your toolchain.");
584
+ document.querySelector(".summary-panel")?.classList.add("hidden");
585
+ document.querySelector(".device-stage")?.classList.add("hidden");
586
+ state.transcript = [];
587
+ pushLine({ kind: "step", icon: "🖥️", text: answer.message });
588
+ if (answer.command) pushLine({ kind: "step", icon: "⌨️", text: answer.command });
589
+ renderChat();
590
+ setChatCollapsed(false);
591
+ toast(answer.message, true);
592
+ }
593
+
537
594
  async function startFromPrompt(raw) {
538
595
  const prompt = classifyPrompt(raw);
539
596
  if (prompt.kind === "empty") return;
540
597
  if (prompt.kind === "url") {
541
598
  state.promptRun = true; state.promptPlatform = "web";
542
599
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
600
+ document.querySelector(".device-stage")?.classList.remove("hidden");
601
+ document.querySelector(".summary-panel")?.classList.remove("hidden");
602
+ if (state.session?.access === "anonymous") setHeading("Website audit", "Read-only. Nothing on the page is clicked.");
543
603
  const result = await runOperation("audit", { url: prompt.value }, { input: prompt.value });
544
604
  state.selectedRunId = result?.capture?.id || state.selectedRunId;
545
605
  return;
@@ -548,11 +608,14 @@ async function startFromPrompt(raw) {
548
608
  state.promptRun = true; state.promptPlatform = prompt.kind === "apk" ? "android" : "ios";
549
609
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
550
610
  const result = await runOperation("explore-build", { input: prompt.value }, { input: prompt.value });
611
+ if (result?.kind === "self-host") { answerSelfHost(result); return; }
551
612
  state.selectedRunId = result?.capture?.id || state.selectedRunId;
552
613
  return;
553
614
  }
615
+ showProduct(); activateView("overview"); renderChat();
554
616
  const answer = await runOperation("open", { input: prompt.value }, { input: prompt.value });
555
- if (answer?.kind === "business") { toast(answer.message, true); return; }
617
+ if (answer?.kind === "self-host") { answerSelfHost(answer); return; }
618
+ if (answer?.kind === "business") { answerSelfHost({ message: answer.message }); return; }
556
619
  await refreshSession();
557
620
  await refresh();
558
621
  state.selectedTargetId = "";
@@ -617,9 +680,29 @@ $("#live-back").addEventListener("click", () => runOperation("session-act", { ac
617
680
  $("#live-swipe").addEventListener("click", () => runOperation("session-act", { action:"swipe", direction:"up" }).catch((error) => toast(error.message, true)));
618
681
  $("#run-gate").addEventListener("click", () => runOperation("gate", operationPayload()).catch((error) => toast(error.message, true)));
619
682
 
683
+ // runtapp.com's hero is the same prompt as this screen, so it hands the target over as
684
+ // ?target=... Prefill it and start the run, so arriving here does not mean retyping what was
685
+ // already typed on the landing page. The URL is cleaned up either way so a refresh does not
686
+ // silently re-run it.
687
+ function handoffTarget() {
688
+ let target = "";
689
+ try { target = new URLSearchParams(window.location.search).get("target") || ""; } catch { return ""; }
690
+ target = target.trim().slice(0, 512);
691
+ if (!target) return "";
692
+ try { window.history.replaceState({}, "", window.location.pathname); } catch { /* history may be unavailable */ }
693
+ return target;
694
+ }
695
+
620
696
  try {
621
697
  try { setChatCollapsed(localStorage.getItem("tapp:chat-collapsed") === "1"); } catch { /* storage may be unavailable */ }
622
698
  await refreshSession();
623
699
  await refresh();
624
700
  if (state.project?.connected && !state.project?.state?.inspected) await runOperation("initialize", { write:true });
701
+
702
+ const handoff = handoffTarget();
703
+ if (handoff) {
704
+ const input = $("#prompt-input");
705
+ if (input) input.value = handoff;
706
+ await startFromPrompt(handoff);
707
+ }
625
708
  } catch (error) { toast(error.message, true); }
@@ -56,10 +56,10 @@
56
56
  <button class="primary prompt-go" type="submit" id="prompt-start" aria-label="Start">→</button>
57
57
  </form>
58
58
  <ul class="prompt-suggestions" aria-label="Examples">
59
- <li><button type="button" data-prompt="https://example.com"><span>⌁</span><b>https://example.com</b><small>audit a website read-only — safe on production, nothing is clicked</small></button></li>
60
- <li><button type="button" data-prompt="~/code/my-app"><span>⌘</span><b>~/code/my-app</b><small>open a repo folder on this Mac — detects iOS, Android and web targets, builds locally</small></button></li>
61
- <li><button type="button" data-prompt="owner/repo"><span>🐙</span><b>owner/repo</b><small>clone from GitHub into an isolated workspace, then the same</small></button></li>
62
- <li><button type="button" data-prompt="com.company.app"><span>📱</span><b>com.company.app</b><small>explore a build already on the booted simulator (or give a .app / .apk)</small></button></li>
59
+ <li><button type="button" data-kind="url" data-prompt="https://example.com"><span>⌁</span><b>https://example.com</b><small>audit a website read-only — safe on production, nothing is clicked</small></button></li>
60
+ <li><button type="button" data-kind="path" data-prompt="~/code/my-app"><span>⌘</span><b>~/code/my-app</b><small>open a repo folder on this Mac — detects iOS, Android and web targets, builds locally</small></button></li>
61
+ <li><button type="button" data-kind="github" data-prompt="owner/repo"><span>🐙</span><b>owner/repo</b><small>clone from GitHub into an isolated workspace, then the same</small></button></li>
62
+ <li><button type="button" data-kind="build" data-prompt="com.company.app"><span>📱</span><b>com.company.app</b><small>explore a build already on the booted simulator (or give a .app / .apk)</small></button></li>
63
63
  </ul>
64
64
  <p class="prompt-note" id="privacy-note-detail">Everything runs on this machine. Exploration, replay and merge decisions are deterministic and need no API key.</p>
65
65
  <span class="sr-only" id="privacy-note-title">Your code stays on this machine.</span>
@@ -80,9 +80,9 @@
80
80
  <div class="sidebar-project">
81
81
  <p class="eyebrow">Project</p>
82
82
  <div class="row"><span><svg><use href="#i-folder"/></svg></span><span><strong id="sidebar-project-name">Product</strong></span></div>
83
- <div class="row"><span><svg><use href="#i-branch"/></svg></span><span id="sidebar-project-source">Repository</span></div>
84
- <div class="row"><span><svg><use href="#i-target"/></svg></span><span id="sidebar-target">Select a target</span></div>
85
- <div class="row"><span><svg><use href="#i-server"/></svg></span><span id="sidebar-runner">Runner not checked</span></div>
83
+ <div class="row" data-repo-only><span><svg><use href="#i-branch"/></svg></span><span id="sidebar-project-source">Repository</span></div>
84
+ <div class="row" data-repo-only><span><svg><use href="#i-target"/></svg></span><span id="sidebar-target">Select a target</span></div>
85
+ <div class="row" data-repo-only><span><svg><use href="#i-server"/></svg></span><span id="sidebar-runner">Runner not checked</span></div>
86
86
  <div class="row hidden" id="sidebar-app-row"><span><svg><use href="#i-app"/></svg></span><span><code id="sidebar-app-id"></code></span></div>
87
87
  <span class="mode-pill" id="mode-pill">Self-host · this machine</span>
88
88
  </div>
@@ -99,7 +99,7 @@
99
99
  <div class="command-actions">
100
100
  <span class="phase-pill hidden" id="phase-pill"><span class="spinner"></span><span id="phase-pill-text">Working…</span></span>
101
101
  <div class="idle-badges" id="idle-badges"></div>
102
- <button class="primary" id="command-run">Run release check</button>
102
+ <button class="primary" id="command-run" data-repo-only>Run release check</button>
103
103
  </div>
104
104
  </div>
105
105
  <div class="run-progress hidden" id="run-progress"><span class="progress-track"><span id="run-progress-bar"></span></span><span id="run-progress-text">Starting…</span></div>
@@ -127,7 +127,7 @@
127
127
  </aside>
128
128
  </section>
129
129
 
130
- <section class="panel section" id="target-stage">
130
+ <section class="panel section" id="target-stage" data-repo-only>
131
131
  <div class="section-heading"><div><p class="eyebrow">Build & run</p><h2>Choose the product target</h2><p>Tapp detected these targets from source. With more than one, you choose; nothing builds until you do.</p></div><span class="status-chip" id="target-status">No target selected</span></div>
132
132
  <div class="target-choice-callout hidden" id="target-choice-callout"><span>1</span><div><strong>Choose what Tapp should test</strong><small>Nothing will build until you select a target. Tapp never guesses when a repository contains multiple applications.</small></div></div>
133
133
  <div id="targets" class="target-grid"><div class="empty">Inspecting the repository for iOS, Android and web targets…</div></div>
@@ -147,12 +147,12 @@
147
147
  </section>
148
148
 
149
149
  <section class="overview-grid">
150
- <article class="panel summary-panel"><div class="section-heading compact"><div><p class="eyebrow">Latest evidence</p><h2>What the last run proved</h2></div><button class="quiet" data-view="runs">All runs</button></div><div class="decision-card neutral" id="decision-card"><span class="decision-label">CURRENT DECISION</span><strong id="decision-title">Not evaluated</strong><span id="decision-detail">Run a conclusive release gate to establish evidence.</span></div><div id="overview-evidence"><div class="empty">No run yet.</div></div></article>
150
+ <article class="panel summary-panel"><div data-repo-only-marker></div><div class="section-heading compact"><div><p class="eyebrow">Latest evidence</p><h2>What the last run proved</h2></div><button class="quiet" data-view="runs">All runs</button></div><div class="decision-card neutral" id="decision-card" data-repo-only><span class="decision-label">CURRENT DECISION</span><strong id="decision-title">Not evaluated</strong><span id="decision-detail">Run a conclusive release gate to establish evidence.</span></div><div id="overview-evidence"><div class="empty">No run yet.</div></div></article>
151
151
  </section>
152
152
  </section>
153
153
 
154
154
  <section class="workspace-view" data-view-panel="runs">
155
- <div class="view-heading simple"><div><p class="eyebrow">Runs</p><h1>Every run, with its evidence</h1><p>Release checks, explorations and read-only website audits. Each opens the report page the engine wrote.</p></div><button class="primary" id="run-gate">Run release gate</button></div>
155
+ <div class="view-heading simple"><div><p class="eyebrow">Runs</p><h1>Every run, with its evidence</h1><p>Release checks, explorations and read-only website audits. Each opens the report page the engine wrote.</p></div><button class="primary" id="run-gate" data-repo-only>Run release gate</button></div>
156
156
  <section class="panel section audit-panel">
157
157
  <div class="section-heading compact"><div><p class="eyebrow">Website</p><h2>Audit a website — read-only</h2><p>Up to six pages, nothing clicked. Safe on production or a site you do not own; no release verdict without source.</p></div></div>
158
158
  <form class="audit-form" id="runs-audit-form">
@@ -110,15 +110,72 @@ function capturePath(captureId, relative = "report.html") {
110
110
  return candidate === root || candidate.startsWith(root + path.sep) ? candidate : null;
111
111
  }
112
112
 
113
+ // Captures live in one flat directory shared by every run on this machine. A public Studio has
114
+ // many visitors in it, so an anonymous visitor's capture is stamped with their visitor id and
115
+ // only ever listed or served back to them. An unstamped capture belongs to the operator.
116
+ const VISITOR_MARKER = ".visitor";
117
+ const VISITOR_COOKIE = "tapp_visitor";
118
+
119
+ // What a signed-out visitor on a public Studio may reach. Everything absent from this list is
120
+ // refused, so a new route is private until someone deliberately opens it.
121
+ function anonymousAllows(method, pathname) {
122
+ if (method === "GET") {
123
+ if (pathname === "/" || pathname === "/api/version" || pathname === "/api/session" || pathname === "/api/audits") return true;
124
+ if (pathname.startsWith("/assets/")) return true;
125
+ if (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/files$/.test(pathname)) return true;
126
+ if (/^\/evidence\/captures\//.test(pathname)) return true;
127
+ if (/^\/api\/jobs\/[a-f0-9]{20}(\/frame)?$/.test(pathname)) return true;
128
+ return false;
129
+ }
130
+ // A visitor may start a read-only audit, and may *ask* about the other kinds of target so the
131
+ // Studio can say where they actually run. A bare 401 reads as "broken" to someone who typed a
132
+ // repo into the landing page, which is how five of its six examples used to dead-end.
133
+ return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build"].includes(pathname);
134
+ }
135
+
136
+ // One visitor may start a bounded number of audits per hour. Each audit drives a real browser
137
+ // over as many as 20 pages, so this is about the machine, not about abuse alone.
138
+ const AUDIT_LIMIT_PER_HOUR = 10;
139
+ const auditHistory = new Map();
140
+ function auditRateLimit(visitorId, method, pathname) {
141
+ if (method !== "POST" || pathname !== "/api/operations/audit") return 0;
142
+ const now = Date.now();
143
+ const hour = 60 * 60 * 1000;
144
+ const recent = (auditHistory.get(visitorId) || []).filter((at) => now - at < hour);
145
+ if (auditHistory.size > 5000) auditHistory.clear();
146
+ if (recent.length >= AUDIT_LIMIT_PER_HOUR) return Math.ceil((hour - (now - recent[0])) / 1000);
147
+ recent.push(now);
148
+ auditHistory.set(visitorId, recent);
149
+ return 0;
150
+ }
151
+
152
+ function captureOwner(captureId) {
153
+ const marker = capturePath(captureId, VISITOR_MARKER);
154
+ if (!marker) return null;
155
+ try { return fs.readFileSync(marker, "utf8").trim() || null; } catch { return null; }
156
+ }
157
+
158
+ function setCaptureOwner(captureId, visitorId) {
159
+ const marker = capturePath(captureId, VISITOR_MARKER);
160
+ if (!marker || !visitorId) return;
161
+ try { fs.writeFileSync(marker, `${visitorId}\n`, { mode: 0o600 }); } catch { /* evidence is still written */ }
162
+ }
163
+
164
+ // `owner` null means the operator, who sees every capture; a visitor id sees only their own.
165
+ function visibleToOwner(captureId, owner) {
166
+ return owner === null || captureOwner(captureId) === owner;
167
+ }
168
+
113
169
  // Read-only website audits live in the captures directory like every other run; the Studio
114
170
  // lists the ones with a summary file. Newest first, bounded.
115
- function listAudits(limit = 50) {
171
+ function listAudits(limit = 50, owner = null) {
116
172
  const root = captureRoot();
117
173
  let names;
118
174
  try { names = fs.readdirSync(root); } catch { return []; }
119
175
  const audits = [];
120
176
  for (const name of names) {
121
177
  if (!name.startsWith("web-audit-")) continue;
178
+ if (!visibleToOwner(name, owner)) continue;
122
179
  const summaryPath = path.join(root, name, "audit.json");
123
180
  let summary;
124
181
  try { summary = JSON.parse(fs.readFileSync(summaryPath, "utf8")); } catch { continue; }
@@ -311,7 +368,23 @@ function readFormBody(request) {
311
368
  });
312
369
  }
313
370
 
314
- function serveLoginPage(response, { failed = false } = {}) {
371
+ const escapeHtml = (value) => String(value)
372
+ .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
373
+ .replace(/"/g, "&quot;").replace(/'/g, "&#39;");
374
+
375
+ // A path the sign-in flow may return to. Only a local path is ever accepted: anything with a
376
+ // scheme or authority (including the "//evil.com" protocol-relative form) would make /login an
377
+ // open redirect, so it is rejected rather than sanitized.
378
+ function safeReturnPath(raw) {
379
+ const value = String(raw || "");
380
+ if (!value.startsWith("/") || value.startsWith("//") || value.includes("\\")) return "";
381
+ if (value.startsWith("/login")) return "";
382
+ // "/" is where sign-in lands anyway; carrying it adds a querystring that says nothing.
383
+ if (value === "/") return "";
384
+ return value.slice(0, 2048);
385
+ }
386
+
387
+ function serveLoginPage(response, { failed = false, next = "" } = {}) {
315
388
  const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
316
389
  <title>tapp — sign in</title><style>
317
390
  body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0c1210;color:#e8efe9;font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
@@ -329,6 +402,7 @@ function serveLoginPage(response, { failed = false } = {}) {
329
402
  <h1>tapp<span>.</span></h1><p class="tag">ship with proof.</p>
330
403
  ${failed ? '<p class="err" role="alert">That username or password did not match.</p>' : ""}
331
404
  <form method="post" action="/api/auth">
405
+ ${next ? `<input type="hidden" name="next" value="${escapeHtml(next)}">` : ""}
332
406
  <label>Username<input name="username" autocomplete="username" placeholder="username" required></label>
333
407
  <label>Password<input name="password" type="password" autocomplete="current-password" placeholder="password" required></label>
334
408
  <button type="submit">Launch Tapp →</button>
@@ -339,12 +413,38 @@ function serveLoginPage(response, { failed = false } = {}) {
339
413
  response.end(html);
340
414
  }
341
415
 
342
- export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null } = {}) {
343
- const hosted = !!trustedProxyToken || !!directLogin;
416
+ export async function startBrowserProduct({ projectDir, port = 0, launch = false, workspaceRoot, githubProvider, publicOrigin = "", trustedProxyToken = "", directLogin = null, publicEgressOnly = null, publicAccess = false } = {}) {
417
+ const hosted = !!trustedProxyToken || !!directLogin || !!publicAccess;
344
418
  // publicOrigin accepts a comma-separated allowlist; the first entry is canonical.
345
419
  const publicOrigins = String(publicOrigin || "").split(",").map((value) => value.trim().replace(/\/$/, "")).filter(Boolean);
346
420
  if (hosted && !publicOrigins.length) throw new Error("Hosted browser mode requires an explicit publicOrigin");
347
421
  const loginFailures = { count: 0, windowStartedAt: 0 };
422
+ // A hosted Studio audits whatever URL a visitor types, from a machine that can also see its
423
+ // own loopback services and private network. Route the browser through the egress proxy, which
424
+ // resolves and pins every connection — redirects and subresources included — and refuses
425
+ // anything that is not a public address. TAPP_ENFORCE_PUBLIC_EGRESS makes a missing proxy fail
426
+ // the run rather than silently reaching the private network. On by default whenever hosted:
427
+ // forgetting to opt in is exactly the mistake that matters here.
428
+ const enforcePublicEgress = publicEgressOnly === null ? hosted : !!publicEgressOnly;
429
+ // The engine reads the proxy off process.env, so enabling it mutates process-wide state. Keep
430
+ // what was there and put it back on close: a local Studio started later in the same process
431
+ // would otherwise inherit a proxy that no longer exists and fail every run.
432
+ let egressProxy = null;
433
+ const previousEgressEnv = {
434
+ server: process.env.TAPP_BROWSER_PROXY_SERVER,
435
+ enforce: process.env.TAPP_ENFORCE_PUBLIC_EGRESS,
436
+ };
437
+ const restoreEgressEnv = () => {
438
+ for (const [key, value] of [["TAPP_BROWSER_PROXY_SERVER", previousEgressEnv.server], ["TAPP_ENFORCE_PUBLIC_EGRESS", previousEgressEnv.enforce]]) {
439
+ if (value === undefined) delete process.env[key]; else process.env[key] = value;
440
+ }
441
+ };
442
+ if (enforcePublicEgress) {
443
+ const { startPublicBrowserProxy } = await import("./public-network.js");
444
+ egressProxy = await startPublicBrowserProxy();
445
+ process.env.TAPP_BROWSER_PROXY_SERVER = egressProxy.url;
446
+ process.env.TAPP_ENFORCE_PUBLIC_EGRESS = "1";
447
+ }
348
448
  const registry = new BrowserWorkspaceRegistry({ initialProjectDir: projectDir, workspaceRoot, githubProvider });
349
449
  const serverStartedAt = new Date().toISOString();
350
450
  const sessionToken = crypto.randomBytes(32).toString("base64url");
@@ -409,8 +509,31 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
409
509
  }
410
510
  const proxyAuthenticated = !!trustedProxyToken && sameSecret(request.headers["x-tapp-proxy-token"], trustedProxyToken);
411
511
  const authenticated = proxyAuthenticated || sameSecret(cookies(request)[SESSION_COOKIE], sessionToken);
512
+
513
+ // A public Studio lets anyone in without an account, but an anonymous visitor gets a far
514
+ // smaller surface than the operator: audit a public website, and read back only the
515
+ // evidence from their own audits. Repositories, live sessions, the gate and this
516
+ // machine's project all stay behind authentication.
517
+ let visitorId = null;
518
+ let anonymous = false;
519
+ if (publicAccess && !authenticated) {
520
+ anonymous = true;
521
+ visitorId = String(cookies(request)[VISITOR_COOKIE] || "");
522
+ if (!/^[a-f0-9]{32}$/.test(visitorId)) {
523
+ visitorId = crypto.randomBytes(16).toString("hex");
524
+ response.setHeader("set-cookie", `${VISITOR_COOKIE}=${visitorId}; HttpOnly; SameSite=Lax; Secure; Path=/; Max-Age=2592000`);
525
+ }
526
+ if (!anonymousAllows(request.method, url.pathname)) {
527
+ json(response, 401, { error: "Sign in to use this. A public visitor can audit a website read-only; repositories, live sessions and the release gate need an account." });
528
+ return;
529
+ }
530
+ const limited = auditRateLimit(visitorId, request.method, url.pathname);
531
+ if (limited) { response.writeHead(429, { "content-type": "application/json; charset=utf-8", "retry-after": String(limited) }); response.end(JSON.stringify({ error: `Too many audits from here. Try again in ${Math.ceil(limited / 60)} minute(s).` })); return; }
532
+ }
533
+ // The operator sees every capture; a visitor sees only captures stamped with their id.
534
+ const evidenceOwner = anonymous ? visitorId : null;
412
535
  if (!authenticated && directLogin) {
413
- if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed") }); return; }
536
+ if (request.method === "GET" && url.pathname === "/login") { serveLoginPage(response, { failed: url.searchParams.has("failed"), next: safeReturnPath(url.searchParams.get("next")) }); return; }
414
537
  if (request.method === "POST" && url.pathname === "/api/auth") {
415
538
  const now = Date.now();
416
539
  if (now - loginFailures.windowStartedAt > 10 * 60_000) { loginFailures.windowStartedAt = now; loginFailures.count = 0; }
@@ -431,20 +554,32 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
431
554
  if (!valid) {
432
555
  loginFailures.count += 1;
433
556
  await new Promise((resolve) => setTimeout(resolve, 400));
434
- response.writeHead(303, { location: "/login?failed=1" });
557
+ const retry = safeReturnPath(form.get("next"));
558
+ response.writeHead(303, { location: retry ? `/login?failed=1&next=${encodeURIComponent(retry)}` : "/login?failed=1" });
435
559
  response.end();
436
560
  return;
437
561
  }
438
- response.writeHead(303, { location: "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Secure; Path=/` });
562
+ response.writeHead(303, { location: safeReturnPath(form.get("next")) || "/", "set-cookie": `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}; HttpOnly; SameSite=Strict; Secure; Path=/` });
563
+ response.end();
564
+ return;
565
+ }
566
+ if (request.method === "GET" && !url.pathname.startsWith("/api/")) {
567
+ // Carry the destination through sign-in; landing on an empty Studio loses whatever
568
+ // the visitor asked for (the landing page sends ?target=... here).
569
+ const want = safeReturnPath(`${url.pathname}${url.search}`);
570
+ response.writeHead(302, { location: want ? `/login?next=${encodeURIComponent(want)}` : "/login" });
439
571
  response.end();
440
572
  return;
441
573
  }
442
- if (request.method === "GET" && !url.pathname.startsWith("/api/")) { response.writeHead(302, { location: "/login" }); response.end(); return; }
443
574
  }
444
- if (!authenticated) { response.writeHead(401, { "content-type": "text/plain; charset=utf-8" }); response.end(directLogin ? "Sign in at /login to continue." : "Open Tapp from the authenticated launch URL printed by the CLI."); return; }
575
+ if (!authenticated && !anonymous) { response.writeHead(401, { "content-type": "text/plain; charset=utf-8" }); response.end(directLogin ? "Sign in at /login to continue." : "Open Tapp from the authenticated launch URL printed by the CLI."); return; }
445
576
 
446
577
  if (request.method === "GET" && url.pathname === "/") {
447
- serveBrowserIndex(response, hosted ? (proxyAuthenticated ? { apiBase:"/api/tapp", loginUrl:"/solutions/tapp" } : { apiBase:"", loginUrl:"/login" }) : {});
578
+ // Without a sign-in page there is nowhere to bounce an anonymous visitor to, and a
579
+ // loginUrl would send them in a loop on their first privileged 401.
580
+ serveBrowserIndex(response, hosted
581
+ ? (proxyAuthenticated ? { apiBase:"/api/tapp", loginUrl:"/solutions/tapp" } : { apiBase:"", loginUrl: directLogin ? "/login" : "" })
582
+ : {});
448
583
  return;
449
584
  }
450
585
  if (request.method === "GET" && url.pathname.startsWith("/assets/")) {
@@ -454,13 +589,27 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
454
589
  return;
455
590
  }
456
591
  if (request.method === "GET" && url.pathname === "/api/session") {
592
+ if (anonymous) {
593
+ json(response, 200, {
594
+ csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
595
+ contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
596
+ access: "anonymous",
597
+ // The prompt screen offers folders, bundle ids and builds. None of them can work in
598
+ // a hosted Studio — there is no Mac, no simulator and no access to the visitor's
599
+ // disk — so say so here rather than letting the UI offer them.
600
+ accepts: ["url"],
601
+ selfHostOnly: ["path", "github", "bundle", "app", "apk"],
602
+ });
603
+ return;
604
+ }
457
605
  json(response, 200, { csrfToken, mode: hosted ? "managed" : "local", product: "Tapp", root: hosted ? null : registry.currentRoot(), repository: hosted ? hostedRepository(registry.current()) : registry.current(), repositories: hosted ? registry.list().map(hostedRepository) : registry.list(), contract: customerProductContract, supportedPlatforms: customerProductContract.targetPlatforms, runners: runnerSummary({ hosted }) });
458
606
  return;
459
607
  }
460
608
  if (request.method === "GET" && url.pathname === "/api/repositories") { json(response, 200, hosted ? { current:hostedRepository(registry.current()), repositories:registry.list().map(hostedRepository) } : { current: registry.current(), repositories: registry.list() }); return; }
461
- if (request.method === "GET" && url.pathname === "/api/audits") { json(response, 200, { audits: hosted ? hostedPayload(listAudits()) : listAudits(), explores: hosted ? hostedPayload(listBuildExplores()) : listBuildExplores() }); return; }
609
+ if (request.method === "GET" && url.pathname === "/api/audits") { const audits = listAudits(50, evidenceOwner); const explores = anonymous ? [] : listBuildExplores(); json(response, 200, { audits: hosted ? hostedPayload(audits) : audits, explores: hosted ? hostedPayload(explores) : explores }); return; }
462
610
  const filesMatch = url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/files$/);
463
611
  if (request.method === "GET" && filesMatch) {
612
+ if (!visibleToOwner(filesMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
464
613
  const files = captureFiles(filesMatch[1]);
465
614
  if (!files) { json(response, 404, { error: "No such capture" }); return; }
466
615
  json(response, 200, files);
@@ -482,11 +631,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
482
631
  const jobMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})$/);
483
632
  if (request.method === "GET" && jobMatch) {
484
633
  const job = jobs.get(jobMatch[1]);
634
+ if (job && anonymous && job.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
485
635
  if (!job) { json(response, 404, { error: "No such operation" }); return; }
486
636
  json(response, 200, publicJob(job, { hosted }));
487
637
  return;
488
638
  }
489
639
  const jobFrameMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/frame$/);
640
+ if (request.method === "GET" && jobFrameMatch && anonymous && jobs.get(jobFrameMatch[1])?.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
490
641
  if (request.method === "GET" && jobFrameMatch) {
491
642
  const job = jobs.get(jobFrameMatch[1]);
492
643
  if (job && !job.latestFrame && job.liveSimulator && job.status === "running") {
@@ -508,6 +659,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
508
659
  }
509
660
  const captureMatch = url.pathname.match(/^\/evidence\/captures\/([A-Za-z0-9._-]{1,128})(?:\/(.*))?$/);
510
661
  if (request.method === "GET" && captureMatch) {
662
+ if (!visibleToOwner(captureMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
511
663
  const file = capturePath(captureMatch[1], captureMatch[2] || "report.html");
512
664
  if (!file) { response.writeHead(404); response.end("Not found"); return; }
513
665
  serveFile(response, file);
@@ -535,6 +687,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
535
687
  const prompt = classifyPrompt(body.input);
536
688
  if (liveSession?.active) throw Object.assign(new Error("End the active live session before opening another project"), { statusCode: 409 });
537
689
  if (prompt.kind === "path") {
690
+ if (anonymous) {
691
+ json(response, 200, { kind: "self-host", target: prompt.value, command: `npx -y @aarwitz/tapp@latest app ${prompt.value}`,
692
+ message: `A folder on your machine is not visible from the cloud. Open it with the Studio there: npx -y @aarwitz/tapp@latest app ${prompt.value}` });
693
+ return;
694
+ }
538
695
  if (hosted) throw Object.assign(new Error("A hosted Studio cannot open a path on your machine; run `tapp app /path/to/repo` locally"), { statusCode: 400 });
539
696
  const resolved = prompt.value.startsWith("~") ? path.join(os.homedir(), prompt.value.slice(1)) : path.resolve(prompt.value);
540
697
  if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) throw Object.assign(new Error(`No folder at ${resolved}`), { statusCode: 400 });
@@ -543,6 +700,11 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
543
700
  return;
544
701
  }
545
702
  if (prompt.kind === "github") {
703
+ if (anonymous) {
704
+ json(response, 200, { kind: "self-host", target: prompt.value, command: "npx -y @aarwitz/tapp@latest app",
705
+ message: `Cloning and building ${prompt.value} needs a machine with your toolchain on it. Run the Studio there and paste the same thing: npx -y @aarwitz/tapp@latest app` });
706
+ return;
707
+ }
546
708
  const job = startJob(operation, async (progress) => ({ kind: "repository", repository: await registry.cloneGithub(prompt.value, progress) }), null);
547
709
  json(response, 202, { job: publicJob(job, { hosted }) });
548
710
  return;
@@ -555,6 +717,13 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
555
717
  return;
556
718
  }
557
719
  if (operation === "explore-build") {
720
+ if (anonymous) {
721
+ const asked = classifyPrompt(body.input);
722
+ const where = asked.kind === "apk" ? "an Android device or emulator" : "a Mac with an iOS simulator";
723
+ json(response, 200, { kind: "self-host", target: asked.value, command: "npx -y @aarwitz/tapp@latest app",
724
+ message: `Running ${asked.value || "a build"} needs ${where}, which the cloud does not have. Start the Studio on that machine: npx -y @aarwitz/tapp@latest app` });
725
+ return;
726
+ }
558
727
  if (hosted) throw Object.assign(new Error("Builds are explored on the machine that has the simulator; run the Studio locally"), { statusCode: 400 });
559
728
  const prompt = classifyPrompt(body.input);
560
729
  if (!["bundle", "app", "apk"].includes(prompt.kind)) throw Object.assign(new Error("Give a bundle id (com.company.app), a simulator .app, or an .apk"), { statusCode: 400 });
@@ -601,15 +770,27 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
601
770
  try { target = new URL(String(body.url || "")); } catch { throw Object.assign(new Error("Audit needs a valid http(s) URL"), { statusCode: 400 }); }
602
771
  if (!/^https?:$/.test(target.protocol)) throw Object.assign(new Error("Audit needs a valid http(s) URL"), { statusCode: 400 });
603
772
  const pages = Math.max(1, Math.min(20, Number(body.pages) || 6));
773
+ // Mint the capture id here so the evidence can be stamped as this visitor's before the
774
+ // run writes anything; a capture that appeared first and was claimed afterwards would be
775
+ // briefly readable by everyone.
776
+ const auditCapture = `web-audit-${Date.now().toString(36)}-${crypto.randomBytes(6).toString("hex")}`;
777
+ if (visitorId) {
778
+ try { fs.mkdirSync(path.join(captureRoot(), auditCapture), { recursive: true }); } catch { /* the run reports its own failure */ }
779
+ setCaptureOwner(auditCapture, visitorId);
780
+ }
604
781
  const job = startJob(operation, async (progress) => {
605
782
  const { auditWebSite } = await import("./web-audit.js");
606
783
  progress({ phase: "runtime", text: `Opening ${target.href} read-only (up to ${pages} pages, nothing will be clicked)` });
607
784
  const summary = await auditWebSite({
608
- url: target.href, pages, delayMs: 750, capturesDir: captureRoot(),
609
- onPage: (page, n) => progress({ phase: "explore", text: `Audited ${page.url} — ${page.findings.length} finding(s)`, current: n, total: pages }),
785
+ url: target.href, pages, delayMs: 750, capturesDir: captureRoot(), captureId: auditCapture,
786
+ // Hand the page's screenshot to the progress channel: the Studio's device stage polls
787
+ // the job's latest frame, and without this an audit watches an empty panel for its
788
+ // whole run while the real screenshots sit in the capture.
789
+ onPage: (page, n) => progress({ phase: "explore", text: `Audited ${page.url} — ${page.findings.length} finding(s)`, current: n, total: pages, ...(page.screenshot ? { screenshot: page.screenshot } : {}) }),
610
790
  });
611
791
  return hosted ? hostedPayload(summary) : summary;
612
792
  }, null);
793
+ job.visitorId = visitorId;
613
794
  json(response, 202, { job: publicJob(job, { hosted }) });
614
795
  return;
615
796
  }
@@ -750,6 +931,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
750
931
  if (liveManagedRuntime) await engine.stopManagedWebTarget(liveManagedRuntime).catch(() => {});
751
932
  }
752
933
  await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
934
+ if (egressProxy) { await egressProxy.close().catch(() => {}); restoreEgressEnv(); }
753
935
  registry.close();
754
936
  },
755
937
  };
@@ -0,0 +1,189 @@
1
+ // Reading a finished run back: the states it observed, and the frame of the recording that
2
+ // shows each one.
3
+ //
4
+ // The engine already knows every state transition — it emits them as OCQA_STATE while the run
5
+ // happens. So this does not analyse the video to work out what changed; it reads the index the
6
+ // run wrote and seeks. A state's frame costs one seek, not a scan of several hundred frames.
7
+ //
8
+ // Everything here is read-only and works on a capture directory alone.
9
+ import fs from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { execFile } from "node:child_process";
13
+ import { promisify } from "node:util";
14
+
15
+ const run = promisify(execFile);
16
+
17
+ const VIDEO_NAMES = ["exploration.webm", "replay.webm", "exploration.mp4", "replay.mp4", "exploration.mov"];
18
+
19
+ export function captureRoot() {
20
+ return path.join(process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), "captures");
21
+ }
22
+
23
+ // A capture is addressable by id, by path, or by "latest".
24
+ export function resolveCapture(target = "") {
25
+ const value = String(target || "").trim();
26
+ const root = captureRoot();
27
+ if (!value || value === "latest") {
28
+ let entries = [];
29
+ try { entries = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()); } catch { return null; }
30
+ const newest = entries
31
+ .map((e) => ({ dir: path.join(root, e.name), at: fs.statSync(path.join(root, e.name)).mtimeMs }))
32
+ .sort((a, b) => b.at - a.at)[0];
33
+ return newest ? newest.dir : null;
34
+ }
35
+ const direct = path.resolve(value);
36
+ if (fs.existsSync(path.join(direct, "ocqa-markers.txt"))) return direct;
37
+ const byId = path.join(root, value);
38
+ if (fs.existsSync(path.join(byId, "ocqa-markers.txt"))) return byId;
39
+ return null;
40
+ }
41
+
42
+ function readMarkers(dir) {
43
+ let text = "";
44
+ try { text = fs.readFileSync(path.join(dir, "ocqa-markers.txt"), "utf8"); } catch { return []; }
45
+ const markers = [];
46
+ for (const line of text.split("\n")) {
47
+ const match = /^OCQA_([A-Z_]+):(.*)$/.exec(line.trim());
48
+ if (!match) continue;
49
+ try { markers.push({ kind: match[1], payload: JSON.parse(match[2]) }); } catch { /* a truncated final line */ }
50
+ }
51
+ return markers;
52
+ }
53
+
54
+ export function findRecording(dir) {
55
+ for (const name of VIDEO_NAMES) {
56
+ const candidate = path.join(dir, name);
57
+ if (fs.existsSync(candidate)) return candidate;
58
+ }
59
+ return null;
60
+ }
61
+
62
+ // The screenshot a run already wrote for a state, when it named one. Older captures name it in
63
+ // the STATE marker; the rest are matched positionally by the state_N_ prefix the engine uses.
64
+ function screenshotFor(dir, state, index) {
65
+ if (state.screenshot && fs.existsSync(path.join(dir, state.screenshot))) return state.screenshot;
66
+ let names = [];
67
+ try { names = fs.readdirSync(dir); } catch { return null; }
68
+ const prefix = `state_${index + 1}_`;
69
+ return names.find((name) => name.startsWith(prefix)) || null;
70
+ }
71
+
72
+ /**
73
+ * What a finished run can show: one entry per observed state, with the time it was reached and
74
+ * the evidence that exists for it. `t` is milliseconds on the run's own clock; `videoAtMs` is
75
+ * the same instant expressed against the recording, when the run recorded one.
76
+ */
77
+ export function captureIndex(dir) {
78
+ const markers = readMarkers(dir);
79
+ const context = markers.find((m) => m.kind === "CONTEXT")?.payload || {};
80
+ const recording = markers.find((m) => m.kind === "RECORDING")?.payload || null;
81
+ const video = findRecording(dir);
82
+ const issues = markers.filter((m) => m.kind === "ISSUE").map((m) => m.payload);
83
+ const actions = markers.filter((m) => m.kind === "ACTION").map((m) => m.payload);
84
+
85
+ const states = markers.filter((m) => m.kind === "STATE").map((m, index) => {
86
+ const state = m.payload;
87
+ const t = Number.isFinite(state.t) ? state.t : null;
88
+ return {
89
+ index: index + 1,
90
+ screen: state.screen || `state ${index + 1}`,
91
+ url: state.url || "",
92
+ t,
93
+ // A recording starts a moment after the run's clock does; subtract that offset so the
94
+ // seek lands on the frame that actually shows this state.
95
+ videoAtMs: t != null && recording ? Math.max(0, t - (recording.startsAtMs || 0)) : null,
96
+ screenshot: screenshotFor(dir, state, index),
97
+ elements: state.elements ?? null,
98
+ role: state.role || "",
99
+ controls: Array.isArray(state.controls) ? state.controls : [],
100
+ inputs: Array.isArray(state.inputs) ? state.inputs : [],
101
+ findings: issues.filter((issue) => issue.screen === state.screen).map((issue) => ({
102
+ type: issue.type, severity: issue.severity, title: issue.title,
103
+ t: Number.isFinite(issue.t) ? issue.t : null,
104
+ })),
105
+ };
106
+ });
107
+
108
+ return {
109
+ capture: path.basename(dir),
110
+ dir,
111
+ context,
112
+ recording: video ? { file: path.basename(video), path: video, startsAtMs: recording?.startsAtMs ?? null, indexed: !!recording } : null,
113
+ states,
114
+ actions: actions.length,
115
+ findings: issues.length,
116
+ };
117
+ }
118
+
119
+ export function selectState(index, at) {
120
+ const value = String(at ?? "").trim();
121
+ if (!value) return null;
122
+ if (/^\d+$/.test(value)) return index.states.find((s) => s.index === Number(value)) || null;
123
+ const needle = value.toLowerCase();
124
+ return index.states.find((s) => s.screen.toLowerCase() === needle)
125
+ || index.states.find((s) => s.screen.toLowerCase().includes(needle))
126
+ || null;
127
+ }
128
+
129
+ async function ffmpeg(args) {
130
+ try {
131
+ await run("ffmpeg", args, { timeout: 120000, maxBuffer: 8 * 1024 * 1024 });
132
+ return true;
133
+ } catch (error) {
134
+ if (error?.code === "ENOENT") throw Object.assign(new Error("ffmpeg is required to read frames out of a recording"), { code: "NO_FFMPEG" });
135
+ throw error;
136
+ }
137
+ }
138
+
139
+ // One frame, by seeking to a known instant. Falls back to the state's screenshot when the run
140
+ // has no recording, because the answer to "what did this screen look like" is the same.
141
+ export async function extractFrame(index, state, outFile) {
142
+ if (state?.videoAtMs != null && index.recording) {
143
+ await ffmpeg(["-y", "-loglevel", "error", "-ss", (state.videoAtMs / 1000).toFixed(3), "-i", index.recording.path, "-frames:v", "1", outFile]);
144
+ if (fs.existsSync(outFile)) return { file: outFile, from: "recording", atMs: state.videoAtMs };
145
+ }
146
+ if (state?.screenshot) {
147
+ const source = path.join(index.dir, state.screenshot);
148
+ if (fs.existsSync(source)) { fs.copyFileSync(source, outFile); return { file: outFile, from: "screenshot", atMs: state.t }; }
149
+ }
150
+ return null;
151
+ }
152
+
153
+ /**
154
+ * Contact sheets: many frames in one image, so a run can be scanned at a glance instead of one
155
+ * costly frame at a time. Sampled across the recording when there is one; otherwise the
156
+ * screenshots the run already wrote are tiled.
157
+ */
158
+ export async function contactSheets(index, outDir, { columns = 5, rows = 5, fps = 2, width = 320 } = {}) {
159
+ fs.mkdirSync(outDir, { recursive: true });
160
+ const pattern = path.join(outDir, "frames_%02d.png");
161
+ if (index.recording) {
162
+ await ffmpeg(["-y", "-loglevel", "error", "-i", index.recording.path,
163
+ "-vf", `fps=${fps},scale=${width}:-1,tile=${columns}x${rows}`, pattern]);
164
+ } else {
165
+ const shots = index.states.map((s) => s.screenshot).filter(Boolean);
166
+ if (!shots.length) return [];
167
+ const list = path.join(outDir, "shots.txt");
168
+ fs.writeFileSync(list, shots.map((name) => `file '${path.join(index.dir, name).replace(/'/g, "'\\''")}'`).join("\n"));
169
+ await ffmpeg(["-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", list,
170
+ "-vf", `scale=${width}:-1,tile=${columns}x${rows}`, pattern]);
171
+ fs.rmSync(list, { force: true });
172
+ }
173
+ return fs.readdirSync(outDir).filter((n) => /^frames_\d+\.png$/.test(n)).sort().map((n) => path.join(outDir, n));
174
+ }
175
+
176
+ // A recording Playwright wrote as VP9 webm cannot be opened by QuickTime or Preview. Write an
177
+ // H.264 sibling so the evidence is playable without anyone converting it first.
178
+ export async function writePlayableCopy(videoPath) {
179
+ const target = videoPath.replace(/\.webm$/i, ".mp4");
180
+ if (!/\.webm$/i.test(videoPath) || fs.existsSync(target)) return fs.existsSync(target) ? target : null;
181
+ try {
182
+ await ffmpeg(["-y", "-loglevel", "error", "-i", videoPath, "-c:v", "libx264", "-preset", "veryfast",
183
+ "-crf", "23", "-pix_fmt", "yuv420p", "-movflags", "+faststart", target]);
184
+ return fs.existsSync(target) ? target : null;
185
+ } catch (error) {
186
+ if (error?.code === "NO_FFMPEG") return null;
187
+ throw error;
188
+ }
189
+ }
@@ -2741,7 +2741,9 @@ export const TOOLS = [
2741
2741
  "The fast way (seconds) to SEE the app: with appBundleId/androidAppId it launches the installed app fresh and returns a screenshot " +
2742
2742
  "plus the accessibility tree of the screen it lands on; with no target it photographs whatever is on the booted simulator right now " +
2743
2743
  "(tree:true returns the accessibility tree instead). No exploration, no findings. Use appLaunchArgs/appLaunchEnv for a login bypass " +
2744
- "or backend override. For a screen reached by signing in or several taps, use tapp_session.",
2744
+ "or backend override. For a screen reached by signing in or several taps, use tapp_session. " +
2745
+ "Pass `capture` (an id, a path, or \"latest\") to read a finished run instead of a live app: its screens with the moment each " +
2746
+ "was reached, `at` for one screen's frame, `frames:true` for contact sheets that make a recording cheap to scan.",
2745
2747
  inputSchema: {
2746
2748
  type: "object",
2747
2749
  properties: {
@@ -2752,6 +2754,9 @@ export const TOOLS = [
2752
2754
  appLaunchArgs: { type: "array", items: { type: "string" }, description: "Launch args, e.g. [\"--uitesting\"]" },
2753
2755
  appLaunchEnv: { type: "object", additionalProperties: { type: "string" }, description: "Launch env, e.g. {\"UI_TEST_BACKEND\": \"staging\"}" },
2754
2756
  maxWidth: { type: "integer", minimum: 200, maximum: 1400, default: 700, description: "Max screenshot width in px" },
2757
+ capture: { type: "string", description: "Read a FINISHED run instead of a live app: a capture id, a capture directory, or \"latest\". Returns the screens it observed with the moment each was reached." },
2758
+ at: { type: "string", description: "With capture: pull the frame for one screen, by index (\"3\") or screen name (\"Checkout\")" },
2759
+ frames: { type: "boolean", default: false, description: "With capture: contact sheets — many frames per image, for scanning a recording cheaply instead of one frame at a time" },
2755
2760
  },
2756
2761
  },
2757
2762
  },
@@ -3048,6 +3053,67 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }))
3048
3053
  // The in-flight MCP request (progress tokens); routed and legacy calls share it.
3049
3054
  let currentRequest = null;
3050
3055
 
3056
+ // Reading a finished run: the same question `tapp_look` always answered ("what was on screen"),
3057
+ // asked of a recording instead of a live app. The engine indexed the states while the run
3058
+ // happened, so a screen's frame is a seek rather than a scan of the whole video.
3059
+ async function lookAtCapture(args = {}) {
3060
+ const frames = await import("./capture-frames.js");
3061
+ const dir = frames.resolveCapture(args.capture);
3062
+ if (!dir) return errorResult(`No capture found for '${args.capture}'`, { hint: "Pass a capture id, a capture directory, or \"latest\"." });
3063
+ const index = frames.captureIndex(dir);
3064
+
3065
+ if (isNonEmptyString(args.at)) {
3066
+ const state = frames.selectState(index, args.at);
3067
+ if (!state) {
3068
+ return errorResult(`No screen matching '${args.at}' in ${index.capture}`, { screens: index.states.map((s) => ({ index: s.index, screen: s.screen })) });
3069
+ }
3070
+ const out = path.join(dir, `frame_${state.index}.png`);
3071
+ const got = await frames.extractFrame(index, state, out).catch((error) => ({ error }));
3072
+ if (!got || got.error) return errorResult(`No frame or screenshot for screen ${state.index}`, { detail: got?.error?.message });
3073
+ const summary = `📼 ${index.capture} · screen ${state.index}/${index.states.length}: ${state.screen}${state.url ? ` (${state.url})` : ""}` +
3074
+ `\n${got.from === "recording" ? `frame at ${(got.atMs / 1000).toFixed(1)}s of ${index.recording.file}` : "screenshot written during the run"}` +
3075
+ (state.findings.length ? `\nfindings here: ${state.findings.map((f) => `${f.severity} ${f.title}`).join("; ")}` : "");
3076
+ return {
3077
+ content: [
3078
+ { type: "text", text: summary },
3079
+ { type: "image", data: fs.readFileSync(out).toString("base64"), mimeType: "image/png" },
3080
+ ],
3081
+ structuredContent: { capture: index.capture, state },
3082
+ };
3083
+ }
3084
+
3085
+ if (args.frames === true) {
3086
+ const sheets = await frames.contactSheets(index, path.join(dir, "frames")).catch((error) => ({ error }));
3087
+ if (!sheets || sheets.error || !sheets.length) {
3088
+ return errorResult("Could not build contact sheets", { detail: sheets?.error?.message || "the run recorded no video and no screenshots" });
3089
+ }
3090
+ return {
3091
+ content: [
3092
+ { type: "text", text: `📼 ${index.capture} · ${sheets.length} contact sheet(s), many frames per image.` +
3093
+ `\nSheets: ${sheets.map((sheet) => path.basename(sheet)).join(", ")} in ${path.join(dir, "frames")}` +
3094
+ `\nShowing the first; read the rest from disk, or ask for one screen with at:"<n|screen>".` },
3095
+ { type: "image", data: fs.readFileSync(sheets[0]).toString("base64"), mimeType: "image/png" },
3096
+ ],
3097
+ structuredContent: { capture: index.capture, sheets },
3098
+ };
3099
+ }
3100
+
3101
+ const screens = index.states.map((state) => `${String(state.index).padStart(2)}. ${state.videoAtMs != null ? `${(state.videoAtMs / 1000).toFixed(1)}s` : "—"} ${state.screen}${state.url ? ` ${state.url}` : ""}`).join("\n");
3102
+ return {
3103
+ content: [{ type: "text", text: `📼 ${index.capture} — ${index.states.length} screen(s), ${index.actions} action(s), ${index.findings} finding(s)\n${index.recording ? `recording: ${index.recording.file}${index.recording.indexed ? "" : " (no frame index)"}` : "recording: none"}\n\n${screens}` }],
3104
+ structuredContent: {
3105
+ capture: index.capture,
3106
+ recording: index.recording ? { file: index.recording.file, indexed: index.recording.indexed } : null,
3107
+ screens: index.states.map((s) => ({ index: s.index, screen: s.screen, url: s.url, atMs: s.videoAtMs ?? s.t, screenshot: s.screenshot, findings: s.findings })),
3108
+ actions: index.actions,
3109
+ findings: index.findings,
3110
+ next: index.recording?.indexed
3111
+ ? 'Ask for one screen with at:"<n|screen>", or frames:true to scan the recording.'
3112
+ : 'This run predates frame indexing, so screens have no video timestamp; at:"<n>" falls back to the screenshot.',
3113
+ },
3114
+ };
3115
+ }
3116
+
3051
3117
  async function handleTool(name, args = {}) {
3052
3118
  const request = currentRequest || { params: { name, arguments: args, _meta: {} } };
3053
3119
 
@@ -3951,6 +4017,8 @@ async function handleTool(name, args = {}) {
3951
4017
  url: isNonEmptyString(args.url) ? args.url.trim() : undefined,
3952
4018
  logPath: flowLog,
3953
4019
  screenshotDir: evidenceDir,
4020
+ // Opt-in, matching scripts/run-web-flow.js rather than inventing a second convention.
4021
+ ...(process.env.TAPP_FLOW_RECORD_VIDEO === "1" ? { recordVideoDir: evidenceDir } : {}),
3954
4022
  device: isNonEmptyString(args.device) ? args.device.trim() : "",
3955
4023
  viewport: isNonEmptyString(args.viewport) ? args.viewport.trim() : "",
3956
4024
  });
@@ -4510,9 +4578,12 @@ export async function routePublicTool(name, args = {}) {
4510
4578
  if (readOnly === true) return handleTool("tapp_audit", rest);
4511
4579
  if (isNonEmptyString(goal)) return handleTool("tapp_focus", { query: goal, projectDir: rest.projectDir, platform: rest.platform, mapPath: rest.mapPath, authToken: rest.authToken });
4512
4580
  return handleTool("tapp_explore", rest);
4513
- case "tapp_look":
4581
+ case "tapp_look": {
4582
+ // A capture is a target like any other; the screen is recorded rather than live.
4583
+ if (isNonEmptyString(rest.capture)) return lookAtCapture(rest);
4514
4584
  if (isNonEmptyString(rest.appBundleId) || isNonEmptyString(rest.androidAppId)) return handleTool("tapp_open_app", rest);
4515
4585
  return handleTool(tree === true ? "tapp_ui_tree" : "tapp_screenshot", rest);
4586
+ }
4516
4587
  case "tapp_run": {
4517
4588
  if (rest.flow || isNonEmptyString(rest.flowPath)) return handleTool("tapp_flow_run", rest);
4518
4589
  if (rest.scenario || isNonEmptyString(rest.scenarioPath)) return handleTool("tapp_scenario_run", rest);
@@ -257,10 +257,14 @@ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, captur
257
257
  const screen = target.pathname + target.search;
258
258
  for (const f of findings) { f.screen = screen; if (!f.url) f.url = page.url(); }
259
259
 
260
+ // Where this page's screenshot landed, so a live viewer can show the page being audited
261
+ // instead of an empty panel. Absolute, because that is what the progress channel forwards.
262
+ let statePath = "";
260
263
  if (capture) {
261
264
  capture.states += 1;
262
265
  const stateName = `state_${capture.states}_${slug(target.pathname === "/" ? (controls.title || "home") : target.pathname)}.png`;
263
- await page.screenshot({ path: path.join(capture.dir, stateName), fullPage: true }).catch(() => page.screenshot({ path: path.join(capture.dir, stateName) }).catch(() => {}));
266
+ statePath = path.join(capture.dir, stateName);
267
+ await page.screenshot({ path: statePath, fullPage: true }).catch(() => page.screenshot({ path: statePath }).catch(() => {}));
264
268
  capture.emit("STATE", { screen, url: page.url(), elements: controls.controlCount, role: "page", controls: controls.dead.map((d) => d.label).filter(Boolean).slice(0, 40), inputs: [], settled: true, screenshot: stateName });
265
269
  for (const f of findings) {
266
270
  if (f.selector) {
@@ -285,6 +289,7 @@ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, captur
285
289
  // Why the wiring-dependent checks were skipped on this page, if they were.
286
290
  ...(controls.wiringUnverifiable ? { wiringUnverifiable: controls.wiringUnverifiable } : {}),
287
291
  findings,
292
+ ...(statePath ? { screenshot: statePath } : {}),
288
293
  links: allowedLinks,
289
294
  };
290
295
  } finally {
@@ -686,7 +686,12 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
686
686
  emit("CONTEXT", { ...(String(device || "").trim() ? { device: String(device).trim() } : {}), viewport: captureProfile.viewport, deviceScaleFactor: captureProfile.deviceScaleFactor ?? 1 });
687
687
  // Playwright records natively (no ffmpeg transcode needed, unlike simctl's .mov output) —
688
688
  // written to a Playwright-chosen filename in outDir, finalized only on context.close().
689
+ // The video and the markers have to share a clock, or a state's frame cannot be found without
690
+ // searching the whole recording. Record where the capture begins relative to the marker
691
+ // timebase; every STATE below carries the same `t`, so a frame is a seek.
692
+ const recordingStartedMs = Date.now() - startedAtMs;
689
693
  const context = await browser.newContext({ ...captureProfile, recordVideo: { dir: outDir, size: captureProfile.viewport } });
694
+ emit("RECORDING", { file: "exploration.webm", startsAtMs: recordingStartedMs, fps: 25 });
690
695
  await installWebListenerTracking(context);
691
696
  if (watch) await installWebWatchUi(context);
692
697
  const page = await context.newPage();
@@ -700,7 +705,7 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
700
705
  // current page; the post-crawl outbound audit passes the link's source page explicitly so
701
706
  // a bad footer link is never attributed to whatever page happened to be visited last.
702
707
  const pageUrl = sourceUrl || page.url();
703
- emit("ISSUE", { type, severity, title, screen, ...(target ? { target } : {}), ...(pageUrl && pageUrl !== "about:blank" ? { url: pageUrl } : {}), ...(evidence ? { evidence } : {}) });
708
+ emit("ISSUE", { t: Date.now() - startedAtMs, type, severity, title, screen, ...(target ? { target } : {}), ...(pageUrl && pageUrl !== "about:blank" ? { url: pageUrl } : {}), ...(evidence ? { evidence } : {}) });
704
709
  };
705
710
 
706
711
  // Async defect listeners: attribute to whatever screen is current when they fire.
@@ -856,7 +861,7 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
856
861
  const screen = webScreenTitle(info, key);
857
862
  const evidenceKey = `${key}::${screen}`;
858
863
  currentScreen = screen;
859
- emit("STATE", { screen, url: key, elements: info.controlCount, role: webScreenRole(screen, info.inputs), controls: info.controls, inputs: info.inputs, settled: !info.busy });
864
+ emit("STATE", { t: Date.now() - startedAtMs, screen, url: key, elements: info.controlCount, role: webScreenRole(screen, info.inputs), controls: info.controls, inputs: info.inputs, settled: !info.busy });
860
865
  const completedNavigation = pendingNavigation;
861
866
  const transitionFrom = webTransitionOrigin(completedNavigation, lastScreen);
862
867
  const transitionAction = completedNavigation?.action || lastActionTarget;
@@ -354,9 +354,19 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVide
354
354
  }
355
355
  } finally {
356
356
  await requestPhase(teardown);
357
+ // Playwright only finalizes a recording when its context closes, and names the file by an
358
+ // internal id. Capture the handle first, then give it the name the evidence page expects —
359
+ // the same convention exploration already uses.
360
+ const video = recordVideoDir && typeof page.video === "function" ? page.video() : null;
357
361
  // Test doubles for playwright may not model a context; a real one always closes.
358
362
  if (typeof context.close === "function") await context.close().catch(() => {});
359
363
  await browser.close().catch(() => {});
364
+ if (video) {
365
+ try {
366
+ const produced = await video.path();
367
+ if (produced && fs.existsSync(produced)) fs.renameSync(produced, path.join(recordVideoDir, "replay.webm"));
368
+ } catch { /* the replay result matters more than its recording */ }
369
+ }
360
370
  }
361
371
  return log.finish({ url: startUrl });
362
372
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aarwitz/tapp",
3
- "version": "0.18.4",
3
+ "version": "0.19.0",
4
4
  "mcpName": "io.github.aarwitz/tapp",
5
5
  "description": "Let coding agents verify UI changes on real iOS, Android, and web surfaces, then enforce reviewed proof in deterministic CI.",
6
6
  "license": "MIT",
@@ -96,7 +96,7 @@
96
96
  "mobile"
97
97
  ],
98
98
  "scripts": {
99
- "test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-audit.test.js tests/capture-provenance.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/android-flow.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
99
+ "test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-audit.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/android-flow.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
100
100
  "test:browser-journey": "node --test tests/browser-journey.test.js",
101
101
  "test:browser-native": "TAPP_RUN_NATIVE_BROWSER=1 node --test tests/browser-native-journey.test.js"
102
102
  }
@@ -14,6 +14,7 @@ screen or journey works from source inspection alone.
14
14
  |---|---|
15
15
  | See or screenshot one screen | `look` / `tapp_look` |
16
16
  | Inspect controls on the current screen | `look --tree` / `tapp_look {tree:true}` |
17
+ | See what a finished run saw | `look <capture>` / `tapp_look {capture}` — add `at` for one screen's frame, `frames:true` to scan |
17
18
  | Reach a named screen/control | `explore --goal` / `tapp_explore {goal}` (source + observed UI Map fast path) |
18
19
  | Drive a specific journey | `tapp_session` start → act → end |
19
20
  | Find bugs autonomously (owned app/environment; it clicks) | `explore` / `tapp_explore` |
@@ -18,6 +18,9 @@ npx -y @aarwitz/tapp@latest explore --read-only https://example.com --pages 5 --
18
18
  # several URLs or --urls FILE batch sites · --device "iPhone 13" audits the mobile rendering · --json FILE writes the result · exit 1 = defects found
19
19
  npx -y @aarwitz/tapp@latest look [target] # one screen: summary + screenshot file
20
20
  npx -y @aarwitz/tapp@latest look [target] --tree --json # + the accessibility tree (every element with --json)
21
+ npx -y @aarwitz/tapp@latest look latest # a finished run: its screens and when each was reached
22
+ npx -y @aarwitz/tapp@latest look latest --at 6 # that screen's frame, seeked out of the recording
23
+ npx -y @aarwitz/tapp@latest look latest --frames # contact sheets: ~25 frames per image, for scanning
21
24
  npx -y @aarwitz/tapp@latest report latest
22
25
  npx -y @aarwitz/tapp@latest doctor # toolchain check · --install prebuilds the iOS harness (~2 min, once)
23
26
  npx -y @aarwitz/tapp@latest feedback "short title" --body "what happened" --type bug|idea|question # draft; add --submit to file (public)
@@ -56,6 +59,10 @@ npx -y @aarwitz/tapp@latest look https://example.com --tap "Not now" --wait-for
56
59
  - `tapp_look`: the current real surface — screen summary plus inline screenshot; `tree:true` adds
57
60
  the accessibility tree (`full:true` for the complete raw element list when the default
58
61
  ≤160-element projection might omit the text you are checking for).
62
+ Also reads a **finished run**: `capture:"<id>|<path>|latest"` returns the screens it observed
63
+ with the moment each was reached, `at:"<n>|<screen>"` pulls that screen's frame out of the
64
+ recording, `frames:true` returns contact sheets (many frames per image) for scanning a run
65
+ cheaply. Prefer `at:` over `frames:` when you know which screen you want — it is one seek.
59
66
  - `tapp_session`: one persistent journey. `action:"start"` → `tap|type|swipe|back|wait|tree|login`
60
67
  → `action:"end"`. `action:"save_flow"` keeps the driven journey as a Flow; `action:"draft_flow"`
61
68
  proposes one from a goal (an untrusted draft until replayed). Sessions begin from a **cold**