@aarwitz/tapp 0.21.2 → 0.22.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.21.2",
4
+ "version": "0.22.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.21.2",
27
+ "@aarwitz/tapp@0.22.0",
28
28
  "mcp"
29
29
  ],
30
30
  "cwd": "${CLAUDE_PROJECT_DIR}"
package/bin/tapp.js CHANGED
@@ -134,6 +134,32 @@ function parseVerbArgs(argv) {
134
134
  // Is this target a finished run rather than something to launch? A capture is a directory with
135
135
  // the markers a run writes, addressed by id, by path, or as "latest". Deliberately narrow: a
136
136
  // bundle id, a URL, a repo dir and an .apk must all still mean what they meant before.
137
+ // Ask on the terminal. Hidden input turns echo off (raw mode) so a password is never shown or
138
+ // left in a scrollback; a plain field uses the ordinary readline path.
139
+ async function promptOnTerminal(question, { hidden = false } = {}) {
140
+ const { createInterface } = await import("node:readline");
141
+ if (!hidden) {
142
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
143
+ return new Promise((resolve) => rl.question(question, (answer) => { rl.close(); resolve(String(answer || "").trim()); }));
144
+ }
145
+ process.stderr.write(question);
146
+ return new Promise((resolve) => {
147
+ const chars = [];
148
+ const stdin = process.stdin;
149
+ const wasRaw = stdin.isRaw;
150
+ stdin.setRawMode(true); stdin.resume(); stdin.setEncoding("utf8");
151
+ const onData = (ch) => {
152
+ for (const c of ch) {
153
+ if (c === "\r" || c === "\n") { stdin.setRawMode(!!wasRaw); stdin.pause(); stdin.removeListener("data", onData); process.stderr.write("\n"); resolve(chars.join("")); return; }
154
+ if (c === "\u0003") { stdin.setRawMode(!!wasRaw); process.stderr.write("\n"); process.exit(130); }
155
+ if (c === "\u007f" || c === "\b") { chars.pop(); continue; }
156
+ chars.push(c);
157
+ }
158
+ };
159
+ stdin.on("data", onData);
160
+ });
161
+ }
162
+
137
163
  function looksLikeCapture(value) {
138
164
  const raw = String(value || "").trim();
139
165
  if (!raw || raw.startsWith("-") || /^https?:\/\//i.test(raw)) return false;
@@ -365,7 +391,7 @@ async function resolveTargetOrExit(engine, input, { inspect = false } = {}) {
365
391
  function safeCommandUsage(verb) {
366
392
  const usage = {
367
393
  workflows: "tapp plan workflows [repo] [--save FILE --confirm] [--workflow ID] [--json]",
368
- 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]",
394
+ explore: "tapp explore [target] [--platform ios|android|web] [--actions N] [--timeout SEC] [--email VALUE] [--password VALUE] [--baseline FILE] [--json FILE]\n Web: --interactive stops at a sign-in and asks on this terminal (--remember keeps it, encrypted, for next time); --actor NAME starts from that actor's saved session\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]",
369
395
  focus: "tapp explore --goal \"SCREEN OR CONTROL\" [target] [--platform ios|android|web] [--project-dir REPO] [--target NAME|PATH] [--map FILE] [--out FILE]",
370
396
  init: "tapp init [repo] [--explore] [--refresh] [--platform PLATFORM] [--target NAME] [--url URL] [--watch] [--dry-run]",
371
397
  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]",
@@ -911,6 +937,31 @@ switch (command) {
911
937
  const progressMetric = platform === "web" ? "pages reached" : platform === "ios" ? "structural states observed" : "screens reached";
912
938
  const onProgress = (p) =>
913
939
  writeProgress(`🔍 Exploring… ${p.action}/${p.max || flags.actions || 60} actions · ${p.states} ${progressMetric}`);
940
+ // --interactive: when the run meets a sign-in it has no credentials for, it stops and asks
941
+ // here, on this terminal, the same way the desktop app asks in its chat. The answer goes to
942
+ // the engine through a 0600 file it polls; --remember keeps it in the encrypted actor store
943
+ // so the next run starts signed in. Nothing typed is echoed or logged.
944
+ const interactive = flags.interactive === true && process.stdin.isTTY;
945
+ if (flags.interactive === true && !process.stdin.isTTY) console.error("ℹ️ --interactive needs a terminal to ask on; running without it.");
946
+ const inputResponsePath = interactive ? path.join(os.tmpdir(), `tapp-input-${process.pid}-${Date.now().toString(36)}.json`) : "";
947
+ const actorName = typeof flags.actor === "string" && flags.actor ? flags.actor : (interactive ? "default" : "");
948
+ const askOnTerminal = async (request) => {
949
+ writeProgress("");
950
+ process.stderr.write(`\n🔐 tapp found a sign-in on "${request.screen}". Go in? (press Enter on an empty field to skip)\n`);
951
+ const values = {};
952
+ for (const field of request.fields || []) {
953
+ values[field.key] = await promptOnTerminal(` ${field.label}${field.placeholder ? ` (${field.placeholder})` : ""}: `, { hidden: !!field.secure });
954
+ }
955
+ const filled = Object.values(values).some((v) => v);
956
+ const action = filled ? "submit" : "skip";
957
+ fs.writeFileSync(inputResponsePath, JSON.stringify({ requestId: request.requestId, action, values: filled ? values : {} }), { mode: 0o600 });
958
+ if (action === "submit" && flags.remember === true) {
959
+ const { ActorStore } = await import(path.join(packageRoot, "mcp-server", "src", "actor-store.js"));
960
+ new ActorStore().write(target, actorName || "default", { credentials: { email: values.email || "", password: values.password || "" } });
961
+ process.stderr.write(` remembered for ${new URL(target).host} as actor "${actorName || "default"}"\n`);
962
+ }
963
+ };
964
+ const onProgressWithAsk = (p) => { if (p.awaitInput && interactive) { askOnTerminal(p.awaitInput).catch(() => {}); return; } onProgress(p); };
914
965
  const r = platform === "web"
915
966
  ? await engine.runQaWeb({
916
967
  url: target,
@@ -923,7 +974,10 @@ switch (command) {
923
974
  device: typeof flags.device === "string" ? flags.device : "",
924
975
  viewport: typeof flags.viewport === "string" ? flags.viewport : "",
925
976
  surface: "cli",
926
- onProgress,
977
+ onProgress: onProgressWithAsk,
978
+ interactive,
979
+ inputResponsePath,
980
+ actor: actorName,
927
981
  })
928
982
  : platform === "android"
929
983
  ? await engine.runQaAndroid({
package/browser/app.css CHANGED
@@ -529,3 +529,27 @@ dialog::backdrop { background:rgba(0,0,0,.6); }
529
529
 
530
530
  @media (max-width: 900px) { .stage { height:auto; min-height:0; } .device-stage { height:auto; } .device-frame { height:62vh; } .device-frame.web { height:auto; } .chat-float { position:static; width:100%; max-height:none; margin:12px; width:calc(100% - 24px); } }
531
531
  @media (prefers-reduced-motion: reduce) { .hero-page, .hero-cursor, .hero-log li { animation:none !important; opacity:1 !important; transform:none !important; } .hero-page-1, .hero-page-2 { display:none; } .chat-line.typing i { animation:none; } }
532
+
533
+
534
+ /* ---- The ask: a sign-in the engine stopped at, answered in the chat --------------------------- */
535
+ .chat-ask { margin-top:6px; padding:12px; border-radius:var(--tapp-radius-lg); background:rgba(15,26,34,.85); border:1px solid var(--tapp-accent, #4f6cf7); display:grid; gap:8px; }
536
+ .chat-ask-head { display:grid; grid-template-columns:22px 1fr; gap:8px; align-items:start; font-size:13px; line-height:1.45; color:var(--tapp-text); }
537
+ .chat-ask .ask-field { display:grid; gap:4px; font-size:12px; color:var(--tapp-text-soft); }
538
+ .chat-ask .ask-field input { font:inherit; font-size:13px; padding:8px 10px; border-radius:8px; border:1px solid var(--tapp-border); background:rgba(0,0,0,.25); color:var(--tapp-text); }
539
+ .chat-ask .ask-remember { display:flex; gap:8px; align-items:center; font-size:12px; color:var(--tapp-text-soft); }
540
+ .chat-ask .ask-actions { display:flex; gap:8px; flex-wrap:wrap; }
541
+ .chat-ask .ask-actions button { font:inherit; font-size:12px; padding:7px 12px; border-radius:8px; cursor:pointer; }
542
+
543
+ /* ---- Journeys: the list a person owns ------------------------------------------------------- */
544
+ .journey-row { display:grid; grid-template-columns:auto 1fr auto auto; gap:10px; align-items:center; padding:8px 10px; border-bottom:1px solid var(--tapp-border); font-size:13px; }
545
+ .journey-row:last-child { border-bottom:0; }
546
+ .journey-platform { font-size:10px; letter-spacing:.08em; text-transform:uppercase; padding:2px 7px; border-radius:999px; background:rgba(79,108,247,.14); color:var(--tapp-accent, #4f6cf7); }
547
+ .journey-platform.ios { background:rgba(74,194,107,.14); color:var(--tapp-green, #4ac26b); }
548
+ .journey-platform.android { background:rgba(227,179,65,.14); color:var(--tapp-amber, #e3b341); }
549
+ .journey-name { color:var(--tapp-text); font-weight:600; }
550
+ .journey-steps { color:var(--tapp-text-soft); font-size:12px; }
551
+
552
+ .journey-group { border-top:1px solid var(--tapp-border); }
553
+ .journey-group > summary { cursor:pointer; list-style:none; display:flex; justify-content:space-between; align-items:center; padding:9px 10px; font-size:12px; letter-spacing:.06em; text-transform:uppercase; color:var(--tapp-text-soft); }
554
+ .journey-group > summary::-webkit-details-marker { display:none; }
555
+ .journey-group[open] > summary { color:var(--tapp-text); }
package/browser/app.js CHANGED
@@ -12,7 +12,7 @@ function apiRoute(route) {
12
12
 
13
13
  const state = {
14
14
  csrf: "", session: null, project: null, audits: [], explores: [], activeJob: null, activeView: "overview",
15
- selectedTargetId: "", selectedRunId: "", live: { active:false }, transcript: [], transcriptSource: "", frameTimer: null,
15
+ selectedTargetId: "", selectedRunId: "", live: { active:false }, transcript: [], transcriptSource: "", frameTimer: null, pendingInput: null,
16
16
  chatCollapsed: false, shotScreens: new Set(), lastShotAt: 0,
17
17
  };
18
18
  const $ = (selector) => document.querySelector(selector);
@@ -288,7 +288,40 @@ function allRuns() {
288
288
  return [...gates, ...explores, ...audits].sort((a, b) => String(b.createdAt || "").localeCompare(String(a.createdAt || "")));
289
289
  }
290
290
 
291
+ // The journeys the open repository has committed under .tapp/flows/. This is the thing a
292
+ // person owns; the engine has listed them all along and the Studio never showed them.
293
+ function renderJourneys() {
294
+ const node = $("#journeys-list");
295
+ if (!node) return;
296
+ const flows = state.project?.flows || [];
297
+ setCount("#journey-count", flows.length);
298
+ if (!flows.length) { node.innerHTML = '<div class="empty">No journeys yet. Prove something with a session, then save it as a Flow.</div>'; return; }
299
+ // Group by folder: a real repository keeps dozens under sandbox/, weekly/, mobile/. The top
300
+ // level comes first; each group opens on demand so a hundred journeys read as a map.
301
+ const groups = new Map();
302
+ for (const flow of flows) { const key = flow.group || ""; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(flow); }
303
+ const row = (flow) => `<div class="journey-row"><span class="journey-platform ${esc(flow.platform || "web")}">${esc(flow.platform || "web")}</span><span class="journey-name">${esc(flow.name)}</span><span class="journey-steps">${flow.steps || 0} steps</span><button class="quiet" data-run-journey="${esc(flow.relativePath || flow.name)}" title="Replay this journey">▶ Run</button></div>`;
304
+ node.innerHTML = [...groups.entries()].sort(([a], [b]) => (a === "" ? -1 : b === "" ? 1 : a.localeCompare(b))).map(([group, items]) =>
305
+ group === ""
306
+ ? items.map(row).join("")
307
+ : `<details class="journey-group"${items.length <= 8 ? " open" : ""}><summary><span class="journey-group-name">${esc(group)}/</span><span class="journey-steps">${items.length}</span></summary>${items.map(row).join("")}</details>`
308
+ ).join("");
309
+ }
310
+
311
+ async function runJourney(relativePath) {
312
+ const name = String(relativePath).replace(/^\.tapp\/flows\//, "").replace(/\.ya?ml$/i, "");
313
+ showProduct(); activateView("overview"); renderChat();
314
+ setHeading(name, "Replaying the journey exactly as committed.", { owned: true });
315
+ const result = await runOperation("run-flow", { name }, { input: name });
316
+ if (result?.kind === "self-host") { answerSelfHost(result); return; }
317
+ if (result?.kind === "journey") {
318
+ pushLine({ kind: "summary", tone: result.passed ? "ready" : "blocked", pill: result.passed ? "Passed" : "Failed", text: `${result.name}: ${result.executed}/${result.total} steps${result.failed ? `, ${result.failed} failed` : ""}.` });
319
+ renderChat();
320
+ }
321
+ }
322
+
291
323
  function renderRuns() {
324
+ renderJourneys();
292
325
  const runs = allRuns();
293
326
  setCount("#run-count", runs.length);
294
327
  $("#runs-list").innerHTML = runs.length ? runs.map((run) => {
@@ -353,13 +386,45 @@ function renderChat() {
353
386
  if (entry.kind === "finding") return `<div class="chat-line finding ${esc(entry.severity)}"><span class="chat-icon">${entry.icon}</span><span>${esc(entry.text)}</span></div>`;
354
387
  if (entry.kind === "progress") return "";
355
388
  return `<div class="chat-line ${esc(entry.kind || "")}"><span class="chat-icon">${entry.icon || "•"}</span><span>${esc(entry.text)}${entry.detail ? ` <em>— ${esc(entry.detail)}</em>` : ""}</span></div>`;
356
- }).join("") + (state.activeJob ? '<div class="chat-line typing"><span class="chat-icon">✨</span><span>tapp is working<i>…</i></span></div>' : "");
389
+ }).join("") + renderAskCard() + (state.activeJob && !state.pendingInput ? '<div class="chat-line typing"><span class="chat-icon">✨</span><span>tapp is working<i>…</i></span></div>' : "");
357
390
  node.innerHTML = lines;
358
391
  if (stickToBottom) node.scrollTop = node.scrollHeight;
359
392
  const progress = [...state.transcript].reverse().find((entry) => entry.kind === "progress");
360
393
  $("#chat-status").textContent = state.activeJob ? (progress ? `${progress.current}/${progress.total} actions${progress.states != null ? ` · ${progress.states} screens` : ""}` : "working…") : state.transcript.length > 1 ? "done" : "ready";
361
394
  }
362
395
 
396
+ // The desktop app's prompt, in the chat: Submit, Use defaults, Skip, Don't ask again. Secure
397
+ // fields are password inputs; nothing typed here is echoed into the transcript, and "remember"
398
+ // keeps it in the encrypted actor store so the next run starts signed in.
399
+ function renderAskCard() {
400
+ const ask = state.pendingInput;
401
+ if (!ask) return "";
402
+ const fields = (ask.fields || []).map((f) => `<label class="ask-field"><span>${esc(f.label || f.key)}</span><input name="${esc(f.key)}" type="${f.secure ? "password" : "text"}" placeholder="${esc(f.placeholder || "")}" value="${esc(f.default || "")}" autocomplete="${f.secure ? "current-password" : "username"}"></label>`).join("");
403
+ return `<form class="chat-ask" id="chat-ask" data-request="${esc(ask.requestId)}" data-job="${esc(ask.jobId)}">
404
+ <div class="chat-ask-head"><span class="chat-icon">🔐</span><span>tapp found a sign-in on <b>${esc(ask.screen || "this screen")}</b>. Go in?</span></div>
405
+ ${fields}
406
+ <label class="ask-remember"><input type="checkbox" name="remember" checked> Remember for this site, so next time starts signed in</label>
407
+ <div class="ask-actions">
408
+ <button type="submit" class="primary" data-ask="submit">Submit</button>
409
+ <button type="button" class="quiet" data-ask="skip">Skip</button>
410
+ <button type="button" class="quiet" data-ask="dont_ask">Don't ask again</button>
411
+ </div>
412
+ </form>`;
413
+ }
414
+
415
+ async function answerAsk(form, action) {
416
+ const jobId = form.dataset.job;
417
+ const values = {};
418
+ if (action === "submit") for (const input of form.querySelectorAll("input[name]:not([type=checkbox])")) values[input.name] = input.value;
419
+ const remember = !!form.querySelector("input[name=remember]")?.checked;
420
+ try {
421
+ await api(`/api/jobs/${encodeURIComponent(jobId)}/input`, { method: "POST", body: JSON.stringify({ action, values, remember: action === "submit" && remember }) });
422
+ state.pendingInput = null;
423
+ pushLine({ kind: "step", icon: action === "submit" ? "🔐" : "⏭️", text: action === "submit" ? "Signing in with what you gave me" : action === "dont_ask" ? "Won't ask again this run" : "Skipped the sign-in" });
424
+ renderChat();
425
+ } catch (error) { toast(error.message, true); }
426
+ }
427
+
363
428
  function setChatCollapsed(collapsed) {
364
429
  state.chatCollapsed = collapsed;
365
430
  $("#chat-float").classList.toggle("collapsed", collapsed);
@@ -493,9 +558,9 @@ function renderProject() {
493
558
  return;
494
559
  }
495
560
  showProduct();
496
- $("#app-name").textContent = project.application?.name || "Unnamed product";
561
+ if (!state.headingOwnedByRun) $("#app-name").textContent = project.application?.name || "Unnamed product";
497
562
  const platforms = project.application?.platforms?.map(pretty).join(" · ") || "Targets not inspected";
498
- $("#app-summary").textContent = `${platforms} · ${project.capabilities?.length || 0} known capabilities`;
563
+ if (!state.headingOwnedByRun) $("#app-summary").textContent = `${platforms} · ${project.capabilities?.length || 0} known capabilities`;
499
564
  renderTargets();
500
565
  renderRequirements();
501
566
  renderDecision();
@@ -557,6 +622,10 @@ async function runOperation(name, body = {}, { input = "" } = {}) {
557
622
  const ratio = progress?.current && progress?.total ? Math.min(92, Math.round(progress.current / progress.total * 100)) : Math.min(88, 8 + job.progress.length * 4);
558
623
  $("#operation-progress-bar").style.width = `${ratio}%`;
559
624
  syncTranscriptFromJob(name, { ...job, input });
625
+ // The engine has stopped at a sign-in and is waiting on a person. Show the ask in the chat
626
+ // until it is answered or the engine moves on.
627
+ if (job.input && state.pendingInput?.requestId !== job.input.requestId) { state.pendingInput = { ...job.input, jobId: job.id }; }
628
+ if (!job.input && state.pendingInput) state.pendingInput = null;
560
629
  if (!$("#product-shell").classList.contains("hidden")) { renderCommandState(job, name); renderChat(); }
561
630
  const screen = [...job.progress].reverse().find((entry) => entry.screen)?.screen;
562
631
  if (screen && !state.live?.active) $("#live-screen-title").textContent = screen;
@@ -616,6 +685,18 @@ async function startFromPrompt(raw) {
616
685
  const prompt = classifyPrompt(raw);
617
686
  if (prompt.kind === "empty") return;
618
687
  if (prompt.kind === "url") {
688
+ // On your own machine a website is explored for real — it can stop at a sign-in and ask
689
+ // you. A public Studio only ever reads.
690
+ if (state.session?.mode === "local") {
691
+ state.promptRun = true; state.promptPlatform = "web";
692
+ showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
693
+ document.querySelector(".device-stage")?.classList.remove("hidden");
694
+ setHeading("Exploring", "Going inside. If there is a sign-in, I will ask.", { owned: true });
695
+ const result = await runOperation("explore", { url: prompt.value }, { input: prompt.value });
696
+ if (result?.kind === "self-host") { answerSelfHost(result); return; }
697
+ state.selectedRunId = result?.capture?.id || state.selectedRunId;
698
+ return;
699
+ }
619
700
  state.promptRun = true; state.promptPlatform = "web";
620
701
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
621
702
  document.querySelector(".device-stage")?.classList.remove("hidden");
@@ -680,6 +761,14 @@ document.addEventListener("submit", (event) => {
680
761
  if (audit) { event.preventDefault(); auditWebsite(audit.elements.url.value).catch((error) => toast(error.message, true)); return; }
681
762
  const prompt = event.target.closest("#prompt-form");
682
763
  if (prompt) { event.preventDefault(); startFromPrompt(prompt.elements.input.value).catch((error) => toast(error.message, true)); }
764
+ const ask = event.target.closest("#chat-ask");
765
+ if (ask) { event.preventDefault(); answerAsk(ask, "submit"); }
766
+ });
767
+ document.addEventListener("click", (event) => {
768
+ const button = event.target.closest("#chat-ask [data-ask]");
769
+ if (button && button.type === "button") { event.preventDefault(); answerAsk(button.closest("#chat-ask"), button.dataset.ask); }
770
+ const play = event.target.closest("[data-run-journey]");
771
+ if (play) { event.preventDefault(); runJourney(play.dataset.runJourney).catch((error) => toast(error.message, true)); }
683
772
  });
684
773
 
685
774
  $$("[data-brand-home]").forEach((button) => button.addEventListener("click", () => state.project?.connected ? (showProduct(), activateView("overview")) : showPrompt()));
@@ -160,6 +160,10 @@
160
160
  <button class="primary" type="submit" id="audit-start">Audit read-only</button>
161
161
  </form>
162
162
  </section>
163
+ <section class="panel section" id="journeys-panel">
164
+ <div class="section-heading compact"><div><p class="eyebrow">Journeys</p><h2>What this app has proven <i id="journey-count" class="zero">0</i></h2><p>Committed under <code>.tapp/flows/</code>. Each replays exactly as written — no model, no key — and is what the release gate guards.</p></div></div>
165
+ <div id="journeys-list"><div class="empty">No journeys yet.</div></div>
166
+ </section>
163
167
  <div class="split-view">
164
168
  <section class="panel list-panel" id="runs-list"><div class="empty">No runs yet.</div></section>
165
169
  <section class="panel detail-panel" id="run-detail"><div class="empty">Select a run to inspect its evidence.</div></section>
@@ -0,0 +1,149 @@
1
+ // Where tapp keeps what it has been told about an application's test accounts, and the signed-in
2
+ // sessions it has built with them.
3
+ //
4
+ // The point of the store is that a login happens once. The first time tapp meets a sign-in it
5
+ // asks (see the OCQA_AWAIT_INPUT protocol in web-explorer.js); after a successful sign-in the
6
+ // browser's storageState — cookies and local storage, which is what "being signed in" is — is kept
7
+ // here, so the next run starts inside the application. A login that needs a code from a phone or
8
+ // an email link therefore only ever has to be done by a person once.
9
+ //
10
+ // Everything here is encrypted at rest. The key is generated once into TAPP_HOME/actors/.key
11
+ // (0600). Each record is AES-256-GCM with the host and actor name as additional authenticated
12
+ // data, so a record copied between applications or actors does not decrypt — the same shape the
13
+ // hosted product's service-access store uses. Nothing in this module ever logs a value.
14
+ //
15
+ // Layout: TAPP_HOME/actors/<host>/<actor>.json
16
+ import crypto from "node:crypto";
17
+ import fs from "node:fs";
18
+ import os from "node:os";
19
+ import path from "node:path";
20
+
21
+ const KEY_FILE = ".key";
22
+ const CIPHER = "aes-256-gcm";
23
+ const INFO = "tapp-actor-store-v1";
24
+
25
+ export function actorStoreRoot(env = process.env) {
26
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
27
+ return path.join(home, "actors");
28
+ }
29
+
30
+ // A host is the application; everything about it keys off the origin's host, never the full URL.
31
+ export function hostKey(target) {
32
+ try { return new URL(String(target)).host.toLowerCase(); } catch { return String(target || "").trim().toLowerCase(); }
33
+ }
34
+
35
+ const ACTOR = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
36
+ export function normalizeActorName(name) {
37
+ const value = String(name || "default").trim();
38
+ if (!ACTOR.test(value)) throw new Error(`Actor name '${value}' must be letters, digits, _ or - (max 64)`);
39
+ return value;
40
+ }
41
+
42
+ function loadKey(root) {
43
+ const keyPath = path.join(root, KEY_FILE);
44
+ try {
45
+ const raw = fs.readFileSync(keyPath);
46
+ if (raw.length === 32) return raw;
47
+ } catch { /* first use */ }
48
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
49
+ const key = crypto.randomBytes(32);
50
+ fs.writeFileSync(keyPath, key, { mode: 0o600 });
51
+ return key;
52
+ }
53
+
54
+ function derive(root, host, actor) {
55
+ return Buffer.from(crypto.hkdfSync("sha256", loadKey(root), `${host}/${actor}`, INFO, 32));
56
+ }
57
+
58
+ function seal(key, aad, value) {
59
+ const iv = crypto.randomBytes(12);
60
+ const cipher = crypto.createCipheriv(CIPHER, key, iv);
61
+ cipher.setAAD(Buffer.from(aad));
62
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final()]);
63
+ return { v: 1, iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), data: ciphertext.toString("base64") };
64
+ }
65
+
66
+ function unseal(key, aad, sealed) {
67
+ const decipher = crypto.createDecipheriv(CIPHER, key, Buffer.from(sealed.iv, "base64"));
68
+ decipher.setAAD(Buffer.from(aad));
69
+ decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
70
+ return JSON.parse(Buffer.concat([decipher.update(Buffer.from(sealed.data, "base64")), decipher.final()]).toString("utf8"));
71
+ }
72
+
73
+ function recordPath(root, host, actor) {
74
+ return path.join(root, host.replace(/[^a-z0-9.:-]/gi, "_"), `${actor}.json`);
75
+ }
76
+
77
+ /**
78
+ * The store for one application. `credentials` are what a person typed; `session` is the
79
+ * browser's storageState after a sign-in worked. Either may be absent.
80
+ */
81
+ export class ActorStore {
82
+ constructor({ root = actorStoreRoot() } = {}) {
83
+ this.root = root;
84
+ }
85
+
86
+ read(target, actorName = "default") {
87
+ const host = hostKey(target);
88
+ const actor = normalizeActorName(actorName);
89
+ const file = recordPath(this.root, host, actor);
90
+ let sealed;
91
+ try { sealed = JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
92
+ try {
93
+ const record = unseal(derive(this.root, host, actor), `${host}/${actor}`, sealed);
94
+ return { host, actor, ...record };
95
+ } catch {
96
+ // A record that does not authenticate is treated as absent, never as partially trusted.
97
+ return null;
98
+ }
99
+ }
100
+
101
+ write(target, actorName, record) {
102
+ const host = hostKey(target);
103
+ const actor = normalizeActorName(actorName);
104
+ const prior = this.read(target, actor) || {};
105
+ const next = {
106
+ credentials: record.credentials ?? prior.credentials ?? null,
107
+ session: record.session ?? prior.session ?? null,
108
+ updatedAt: new Date().toISOString(),
109
+ sessionSavedAt: record.session ? new Date().toISOString() : (prior.sessionSavedAt ?? null),
110
+ };
111
+ const file = recordPath(this.root, host, actor);
112
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
113
+ const sealed = seal(derive(this.root, host, actor), `${host}/${actor}`, next);
114
+ const tmp = `${file}.${process.pid}.tmp`;
115
+ fs.writeFileSync(tmp, JSON.stringify(sealed), { mode: 0o600 });
116
+ fs.renameSync(tmp, file);
117
+ return { host, actor, sessionSavedAt: next.sessionSavedAt };
118
+ }
119
+
120
+ forget(target, actorName = "default") {
121
+ const host = hostKey(target);
122
+ const actor = normalizeActorName(actorName);
123
+ try { fs.rmSync(recordPath(this.root, host, actor), { force: true }); return true; } catch { return false; }
124
+ }
125
+
126
+ // Names only — this is what a UI may show. Never the records.
127
+ list(target) {
128
+ const host = hostKey(target);
129
+ const dir = path.dirname(recordPath(this.root, host, "x"));
130
+ let names = [];
131
+ try { names = fs.readdirSync(dir).filter((n) => n.endsWith(".json")).map((n) => n.slice(0, -5)); } catch { return []; }
132
+ return names.map((actor) => {
133
+ const record = this.read(target, actor);
134
+ return { actor, hasCredentials: !!record?.credentials, hasSession: !!record?.session, sessionSavedAt: record?.sessionSavedAt || null };
135
+ });
136
+ }
137
+
138
+ // Playwright wants storageState as a file path or an object; a path keeps the object out of
139
+ // argument lists and logs. The file is 0600 and removed by the caller after the context opens.
140
+ sessionFile(target, actorName = "default") {
141
+ const record = this.read(target, actorName);
142
+ if (!record?.session) return null;
143
+ const dir = path.join(os.tmpdir(), "tapp-sessions");
144
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
145
+ const file = path.join(dir, `${crypto.randomBytes(8).toString("hex")}.json`);
146
+ fs.writeFileSync(file, JSON.stringify(record.session), { mode: 0o600 });
147
+ return file;
148
+ }
149
+ }
@@ -131,7 +131,9 @@ function anonymousAllows(method, pathname) {
131
131
  // A visitor may start a read-only audit, and may *ask* about the other kinds of target so the
132
132
  // Studio can say where they actually run. A bare 401 reads as "broken" to someone who typed a
133
133
  // repo into the landing page, which is how five of its six examples used to dead-end.
134
- return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build"].includes(pathname);
134
+ // `explore` is listed so a visitor receives the honest "run this on your own machine" answer
135
+ // from the handler, rather than a bare 401 that reads as broken.
136
+ return method === "POST" && ["/api/operations/audit", "/api/operations/open", "/api/operations/explore-build", "/api/operations/explore"].includes(pathname);
135
137
  }
136
138
 
137
139
  // One visitor may start a bounded number of audits per hour. Each audit drives a real browser
@@ -217,6 +219,19 @@ function listBuildExplores(limit = 50) {
217
219
  return runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, limit);
218
220
  }
219
221
 
222
+ // Mark a capture as prompt-started so the Studio lists it in Runs without a repository. The
223
+ // report summary beside it is what the list row and detail read; the capture stays the evidence.
224
+ function markPromptStarted(structured) {
225
+ try {
226
+ const captureDir = structured?.capture?.path;
227
+ if (!captureDir) return;
228
+ const provenancePath = path.join(captureDir, "provenance.json");
229
+ const provenance = JSON.parse(fs.readFileSync(provenancePath, "utf8"));
230
+ fs.writeFileSync(provenancePath, JSON.stringify({ ...provenance, origin: "studio-prompt" }, null, 2));
231
+ fs.writeFileSync(path.join(captureDir, "report.json"), JSON.stringify({ headline: structured.headline, inconclusive: structured.inconclusive, screensExplored: structured.screensExplored, actionsPerformed: structured.actionsPerformed, findingCounts: structured.findingCounts, findings: structured.findings, checkedFor: structured.checkedFor, notChecked: structured.notChecked, platform: structured.platform, target: structured.target }, null, 2));
232
+ } catch { /* listing is a convenience; the capture is the evidence */ }
233
+ }
234
+
220
235
  function openBrowser(url) {
221
236
  const invocation = process.platform === "darwin" ? ["open", [url]]
222
237
  : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
@@ -231,6 +246,8 @@ function publicJob(job, { hosted = false } = {}) {
231
246
  createdAt: job.createdAt, completedAt: job.completedAt || null, progress: job.progress.slice(-80), frame: !!job.latestFrame || !!job.liveSimulator, platform: job.platform || null,
232
247
  result: hosted ? hostedPayload(job.result) : job.result || null,
233
248
  error: job.error || null,
249
+ // Fields only (labels, which are secure); what the person typed never travels back out.
250
+ input: job.input ? { requestId: job.input.requestId, screen: job.input.screen, fields: job.input.fields, askedAt: job.input.askedAt } : null,
234
251
  };
235
252
  }
236
253
 
@@ -509,6 +526,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
509
526
  // The engine names the screenshot it just wrote; the Studio device panel polls it as the
510
527
  // exploration feed. Only engine-supplied paths ever land here, never client input.
511
528
  if (normalized.screenshot && path.isAbsolute(normalized.screenshot)) job.latestFrame = normalized.screenshot;
529
+ // A pause-and-ask from the engine (OCQA_AWAIT_INPUT): keep the request on the job so the
530
+ // Studio can render it, and clear it once the engine says it was resolved.
531
+ if (normalized.awaitInput && typeof normalized.awaitInput === "object") job.input = { ...normalized.awaitInput, askedAt: new Date().toISOString() };
532
+ if (normalized.inputResolved) job.input = null;
512
533
  };
513
534
  jobs.set(job.id, job);
514
535
  Promise.resolve().then(() => work(progress)).then((result) => {
@@ -692,6 +713,29 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
692
713
  json(response, 200, publicJob(job, { hosted }));
693
714
  return;
694
715
  }
716
+ // Answering an ask. Only the operator may: an anonymous visitor is never asked (see the
717
+ // explore operation below), and this is the one place typed credentials pass through the
718
+ // server — straight to the engine's response file (0600), optionally into the encrypted
719
+ // actor store, and nowhere else. They are not logged and not kept on the job.
720
+ const jobInputMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/input$/);
721
+ if (request.method === "POST" && jobInputMatch) {
722
+ if (anonymous) { response.writeHead(401); response.end("Sign in to answer a run"); return; }
723
+ requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
724
+ const job = jobs.get(jobInputMatch[1]);
725
+ if (!job || !job.input || !job.inputResponsePath) { json(response, 409, { error: "This run is not waiting for anything" }); return; }
726
+ const body = await readJsonBody(request);
727
+ const action = ["submit", "defaults", "skip", "dont_ask"].includes(body.action) ? body.action : "skip";
728
+ const values = action === "submit" && body.values && typeof body.values === "object"
729
+ ? Object.fromEntries(Object.entries(body.values).filter(([k, v]) => typeof k === "string" && typeof v === "string").map(([k, v]) => [k.slice(0, 64), v.slice(0, 512)]))
730
+ : {};
731
+ fs.writeFileSync(job.inputResponsePath, JSON.stringify({ requestId: job.input.requestId, action, values }), { mode: 0o600 });
732
+ if (action === "submit" && body.remember === true && job.actorTarget) {
733
+ const { ActorStore } = await import("./actor-store.js");
734
+ new ActorStore().write(job.actorTarget, job.actorName || "default", { credentials: { email: values.email || "", password: values.password || "" } });
735
+ }
736
+ json(response, 200, { ok: true, action });
737
+ return;
738
+ }
695
739
  const jobFrameMatch = url.pathname.match(/^\/api\/jobs\/([a-f0-9]{20})\/frame$/);
696
740
  if (request.method === "GET" && jobFrameMatch && anonymous && jobs.get(jobFrameMatch[1])?.visitorId !== visitorId) { response.writeHead(404); response.end("Not found"); return; }
697
741
  if (request.method === "GET" && jobFrameMatch) {
@@ -809,22 +853,76 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
809
853
  }
810
854
  if (result?.error) throw Object.assign(new Error(result.error), { details: result.details || {} });
811
855
  const structured = result.structured;
812
- // Mark the capture as prompt-started so the Studio lists it without a repository.
813
- try {
814
- const captureDir = structured?.capture?.path;
815
- if (captureDir) {
816
- const provenancePath = path.join(captureDir, "provenance.json");
817
- const provenance = JSON.parse(fs.readFileSync(provenancePath, "utf8"));
818
- fs.writeFileSync(provenancePath, JSON.stringify({ ...provenance, origin: "studio-prompt" }, null, 2));
819
- fs.writeFileSync(path.join(captureDir, "report.json"), JSON.stringify({ headline: structured.headline, inconclusive: structured.inconclusive, screensExplored: structured.screensExplored, actionsPerformed: structured.actionsPerformed, findingCounts: structured.findingCounts, findings: structured.findings, checkedFor: structured.checkedFor, notChecked: structured.notChecked, platform: structured.platform, target: structured.target }, null, 2));
820
- }
821
- } catch { /* listing is a convenience; the capture is the evidence */ }
856
+ markPromptStarted(structured);
822
857
  return structured;
823
858
  }, null);
824
859
  json(response, 202, { job: publicJob(job, { hosted }) });
825
860
  return;
826
861
  }
827
862
  // A website audit needs no repository: it is read-only against a URL and writes a capture.
863
+ // Going inside a website: a full exploration that can stop at a sign-in and ask. Operator
864
+ // only — a public Studio asking a stranger for their login to another site is
865
+ // phishing-shaped, so a visitor is told to run this on their own machine instead.
866
+ if (operation === "explore") {
867
+ if (anonymous) {
868
+ json(response, 200, { kind: "self-host", command: "npx -y @aarwitz/tapp@latest app",
869
+ message: "Going inside a site means signing in, and that is something to do on your own machine. Start the Studio there: npx -y @aarwitz/tapp@latest app" });
870
+ return;
871
+ }
872
+ let target;
873
+ try { target = new URL(String(body.url || "")); } catch { throw Object.assign(new Error("Explore needs a valid http(s) URL"), { statusCode: 400 }); }
874
+ if (!/^https?:$/.test(target.protocol)) throw Object.assign(new Error("Explore needs a valid http(s) URL"), { statusCode: 400 });
875
+ const actorName = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(String(body.actor || "")) ? String(body.actor) : "default";
876
+ const responsePath = path.join(os.tmpdir(), `tapp-input-${crypto.randomBytes(8).toString("hex")}.json`);
877
+ const job = startJob(operation, async (progress) => {
878
+ const engine = await import("./index.js");
879
+ const result = await engine.runQaWeb({
880
+ url: target.href, maxActions: Number(body.maxActions) || 40, timeout: Number(body.timeout) || 600,
881
+ interactive: true, inputResponsePath: responsePath, inputWaitSec: 180, actor: actorName,
882
+ onProgress: (entry) => progress({ phase: entry.awaitInput ? "ask" : "explore", text: entry.narrative || `${entry.action || 0}/${entry.max || 0} actions · ${entry.states || 0} screens`, ...(entry.action ? { current: entry.action, total: entry.max } : {}), ...(entry.screen ? { screen: entry.screen } : {}), ...(entry.screenshot ? { screenshot: entry.screenshot } : {}), ...(entry.awaitInput ? { awaitInput: entry.awaitInput } : {}), ...(entry.inputResolved ? { inputResolved: entry.inputResolved } : {}) }),
883
+ });
884
+ if (result?.error) throw Object.assign(new Error(result.error), { details: result.details || {} });
885
+ markPromptStarted(result.structured);
886
+ return result.structured;
887
+ }, null);
888
+ job.inputResponsePath = responsePath;
889
+ job.actorTarget = target.href;
890
+ job.actorName = actorName;
891
+ json(response, 202, { job: publicJob(job, { hosted }) });
892
+ return;
893
+ }
894
+ // Replay a committed journey from the open project's .tapp/flows/. Web journeys run here
895
+ // with a recording; an iOS or Android journey needs the simulator or device, so it is
896
+ // answered with the command to run it where that is.
897
+ if (operation === "run-flow") {
898
+ if (anonymous) { json(response, 401, { error: "Sign in to replay a journey" }); return; }
899
+ const root = registry.currentRoot();
900
+ if (!root) throw Object.assign(new Error("Open a repository first"), { statusCode: 409 });
901
+ const name = String(body.name || "").replace(/\.ya?ml$/i, "");
902
+ if (!/^[A-Za-z0-9][A-Za-z0-9._\/-]{0,120}$/.test(name) || name.includes("..")) throw Object.assign(new Error("That is not a journey name"), { statusCode: 400 });
903
+ const flowPath = path.join(root, ".tapp", "flows", `${name}.yml`);
904
+ if (!flowPath.startsWith(path.join(root, ".tapp", "flows") + path.sep) || !fs.existsSync(flowPath)) throw Object.assign(new Error(`No journey named ${name}`), { statusCode: 404 });
905
+ const { loadFlowFile, inferFlowPlatform } = await import("./flow-runtime.js");
906
+ const flow = loadFlowFile(flowPath);
907
+ const platform = inferFlowPlatform(flow);
908
+ if (platform !== "web") {
909
+ json(response, 200, { kind: "self-host", command: `npx -y @aarwitz/tapp@latest run ${path.relative(root, flowPath)}`,
910
+ message: `${flow.name || name} runs on ${platform === "android" ? "an Android device or emulator" : "an iOS simulator"}, which the Studio does not have. Run it where that is: npx -y @aarwitz/tapp@latest run ${path.relative(root, flowPath)}` });
911
+ return;
912
+ }
913
+ const captureId = `flow-web-${Date.now().toString(36)}-${crypto.randomBytes(4).toString("hex")}`;
914
+ const evidenceDir = path.join(captureRoot(), captureId);
915
+ fs.mkdirSync(evidenceDir, { recursive: true });
916
+ const job = startJob(operation, async (progress) => {
917
+ progress({ phase: "runtime", text: `Replaying ${flow.name || name}` });
918
+ const { runWebFlow } = await import("./web-flow.js");
919
+ const result = await runWebFlow({ flow, logPath: path.join(evidenceDir, "flow.log"), screenshotDir: evidenceDir, recordVideoDir: evidenceDir });
920
+ for (const line of result.lines || []) progress({ phase: "replay", text: typeof line === "string" ? line : (line.text || JSON.stringify(line)) });
921
+ return { kind: "journey", name: flow.name || name, passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, capture: { id: captureId, path: evidenceDir } };
922
+ }, null);
923
+ json(response, 202, { job: publicJob(job, { hosted }) });
924
+ return;
925
+ }
828
926
  if (operation === "audit") {
829
927
  let target;
830
928
  try { target = new URL(String(body.url || "")); } catch { throw Object.assign(new Error("Audit needs a valid http(s) URL"), { statusCode: 400 }); }
@@ -1975,7 +1975,7 @@ export function formatScreen(screenTitle, elements, { full = false } = {}) {
1975
1975
  // `tapp` CLI verbs in bin/tapp.js — same pattern as report.js. Keep orchestration HERE so
1976
1976
  // the surfaces can't drift.)
1977
1977
 
1978
- export async function runQaWeb({ url, maxActions, timeout, testEmail, testPassword, baselineFindings, seedRoutes = [], seedTargets = [], watch = false, surface = "mcp", onProgress = () => {}, device = "", viewport = "" }) {
1978
+ export async function runQaWeb({ url, maxActions, timeout, testEmail, testPassword, baselineFindings, seedRoutes = [], seedTargets = [], watch = false, surface = "mcp", onProgress = () => {}, device = "", viewport = "", interactive = false, inputResponsePath = "", inputWaitSec = 120, actor = "" }) {
1979
1979
  const { storagePreflight } = await import("./environment-preflight.js");
1980
1980
  const storage = storagePreflight(capturesDir);
1981
1981
  if (!storage.ok) return { error: storage.message, details: { environment: "storage", storage } };
@@ -1984,6 +1984,23 @@ export async function runQaWeb({ url, maxActions, timeout, testEmail, testPasswo
1984
1984
  const id = "web-" + new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14).replace(/^(\d{8})/, "$1-");
1985
1985
  const outDir = path.join(capturesDir, id);
1986
1986
  const provenance = writeCaptureProvenance(outDir, { kind: "explore", platform: "web", target: url.trim(), projectDir: workspaceRoot });
1987
+ // A named actor is an identity tapp remembers for this application: credentials it was told
1988
+ // once, and the signed-in session it built with them. With one, the run starts inside the
1989
+ // application; without one, and with a person to ask, it asks at the door.
1990
+ let store = null;
1991
+ let storageStatePath = "";
1992
+ let actorName = isNonEmptyString(actor) ? actor.trim() : "";
1993
+ let storedEmail = "";
1994
+ let storedPassword = "";
1995
+ if (actorName || interactive) {
1996
+ const { ActorStore } = await import("./actor-store.js");
1997
+ store = new ActorStore();
1998
+ actorName = actorName || "default";
1999
+ const record = store.read(url.trim(), actorName);
2000
+ storageStatePath = store.sessionFile(url.trim(), actorName) || "";
2001
+ storedEmail = record?.credentials?.email || "";
2002
+ storedPassword = record?.credentials?.password || "";
2003
+ }
1987
2004
  let webResult;
1988
2005
  try {
1989
2006
  const { exploreWeb } = await import("./web-explorer.js");
@@ -1992,8 +2009,13 @@ export async function runQaWeb({ url, maxActions, timeout, testEmail, testPasswo
1992
2009
  maxActions: actions,
1993
2010
  timeoutSec,
1994
2011
  outDir,
1995
- testEmail: isNonEmptyString(testEmail) ? testEmail.trim() : "",
1996
- testPassword: isNonEmptyString(testPassword) ? testPassword.trim() : "",
2012
+ testEmail: isNonEmptyString(testEmail) ? testEmail.trim() : storedEmail,
2013
+ testPassword: isNonEmptyString(testPassword) ? testPassword.trim() : storedPassword,
2014
+ interactive: interactive === true,
2015
+ inputResponsePath: isNonEmptyString(inputResponsePath) ? inputResponsePath.trim() : "",
2016
+ inputWaitSec: Math.max(10, Math.min(900, asInteger(inputWaitSec, 120))),
2017
+ storageStatePath,
2018
+ onSessionSaved: store ? (session) => { store.write(url.trim(), actorName, { session }); } : null,
1997
2019
  seedRoutes,
1998
2020
  seedTargets,
1999
2021
  watch: watch === true,
@@ -182,12 +182,19 @@ function listProductRuns(root) {
182
182
  }
183
183
 
184
184
  function listRepositoryFlows(root) {
185
+ // Every committed journey, including the ones in subfolders — a real repository keeps dozens
186
+ // under sandbox/, mobile/, weekly/, and a flat listing hid all of them. YAML steps are counted
187
+ // from the list items under `steps:`; before, only JSON flows ever had a step count.
185
188
  const directory = path.join(root, projectArtifactDirectory(root), "flows");
186
189
  if (!fs.existsSync(directory)) return [];
187
- return fs.readdirSync(directory, { withFileTypes:true })
188
- .filter((entry) => entry.isFile() && /\.(?:ya?ml|json)$/i.test(entry.name))
189
- .map((entry) => {
190
- const file = path.join(directory, entry.name);
190
+ const out = [];
191
+ const walk = (dir, group) => {
192
+ let entries = [];
193
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
194
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
195
+ const file = path.join(dir, entry.name);
196
+ if (entry.isDirectory()) { walk(file, group ? `${group}/${entry.name}` : entry.name); continue; }
197
+ if (!entry.isFile() || !/\.(?:ya?ml|json)$/i.test(entry.name)) continue;
191
198
  const relativePath = path.relative(root, file).replaceAll(path.sep, "/");
192
199
  let name = entry.name.replace(/\.(?:ya?ml|json)$/i, "");
193
200
  let platform = "ios";
@@ -205,14 +212,22 @@ function listRepositoryFlows(root) {
205
212
  return match ? match[1].replace(/^["']|["']$/g, "") : "";
206
213
  };
207
214
  name = scalar("name") || name;
208
- platform = (scalar("platform") || (/^url:\s*https?:\/\//im.test(source) ? "web" : "ios")).toLowerCase();
209
- const block = source.split(/^steps:\s*$/m)[1] || "";
210
- steps = (block.match(/^\s{2}-\s/gm) || []).length;
215
+ const declared = scalar("platform").toLowerCase();
216
+ platform = declared || (/^https?:\/\//i.test(scalar("url") || scalar("app")) ? "web" : "ios");
217
+ const stepsAt = source.search(/^steps:\s*$/m);
218
+ if (stepsAt >= 0) {
219
+ const tail = source.slice(stepsAt);
220
+ const stop = tail.slice(7).search(/^[A-Za-z_][\w-]*:\s*/m);
221
+ const block = stop >= 0 ? tail.slice(0, 7 + stop) : tail;
222
+ steps = (block.match(/^\s*-\s/gm) || []).length;
223
+ }
211
224
  }
212
- } catch { /* Artifact remains inspectable; deterministic replay reports invalid syntax. */ }
213
- return { id:`flow_${crypto.createHash("sha256").update(relativePath).digest("hex").slice(0, 16)}`, name, path:relativePath, platform, steps, sha256:crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"), status:"committed" };
214
- })
215
- .sort((left, right) => left.path.localeCompare(right.path));
225
+ } catch { /* an unreadable flow is still listed by file name */ }
226
+ out.push({ name, relativePath, platform, steps, group });
227
+ }
228
+ };
229
+ walk(directory, "");
230
+ return out;
216
231
  }
217
232
 
218
233
  export function readProductProject({ projectDir, outDir = ".tapp" } = {}) {
@@ -775,7 +775,7 @@ export function normalizeWebSeedTargets(seedTargets = [], limit = 5) {
775
775
  return result;
776
776
  }
777
777
 
778
- export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDir, testEmail = "", testPassword = "", seedRoutes = [], seedTargets = [], watch = false, onProgress, device = "", viewport = "" }) {
778
+ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDir, testEmail = "", testPassword = "", seedRoutes = [], seedTargets = [], watch = false, onProgress, device = "", viewport = "", interactive = false, inputResponsePath = "", inputWaitSec = 120, storageStatePath = "", onSessionSaved = null }) {
779
779
  const start = new URL(url);
780
780
  if (!/^https?:$/.test(start.protocol)) throw new Error("url must be http(s)");
781
781
  fs.mkdirSync(outDir, { recursive: true });
@@ -807,7 +807,17 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
807
807
  // searching the whole recording. Record where the capture begins relative to the marker
808
808
  // timebase; every STATE below carries the same `t`, so a frame is a seek.
809
809
  const recordingStartedMs = Date.now() - startedAtMs;
810
- const context = await browser.newContext({ ...captureProfile, recordVideo: { dir: outDir, size: captureProfile.viewport } });
810
+ // A stored session means the run starts inside the application instead of at its door. The
811
+ // file is a temp copy written by the actor store; remove it as soon as the context has it.
812
+ const storageState = storageStatePath && fs.existsSync(storageStatePath) ? storageStatePath : undefined;
813
+ const context = await browser.newContext({ ...captureProfile, ...(storageState ? { storageState } : {}), recordVideo: { dir: outDir, size: captureProfile.viewport } });
814
+ const startedSignedIn = !!storageState;
815
+ if (storageState) { try { fs.rmSync(storageState, { force: true }); } catch { /* best effort */ } }
816
+ // After a sign-in works, hand the session back so it can be kept for next time.
817
+ const keepSession = async (why) => {
818
+ if (!onSessionSaved) return;
819
+ try { await onSessionSaved(await context.storageState(), why); } catch { /* keeping the session is never allowed to fail the run */ }
820
+ };
811
821
  emit("RECORDING", { file: "exploration.webm", startsAtMs: recordingStartedMs, fps: 25 });
812
822
  await installWebListenerTracking(context);
813
823
  if (watch) await installWebWatchUi(context);
@@ -869,6 +879,7 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
869
879
  let probeCapHit = false;
870
880
  let actions = 0;
871
881
  let screenCount = 0;
882
+ if (startedSignedIn) narrate("Starting signed in from the saved session");
872
883
  // Which distinct on-screen states each route has produced, so one route cannot mint states
873
884
  // without limit when something on it never settles.
874
885
  const signaturesByRoute = new Map();
@@ -1057,10 +1068,52 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
1057
1068
 
1058
1069
  // Login preamble parity with iOS: if creds were given and a password field is present,
1059
1070
  // fill + submit once, and flag auth_failed if we clearly bounced.
1071
+ // The same protocol the iOS harness and the desktop app speak: emit OCQA_AWAIT_INPUT with the
1072
+ // fields, poll the response path, honour only a response for this request, and say how it was
1073
+ // resolved. Secure fields never carry a default over stdout. A host that never answers turns
1074
+ // interactivity off for the rest of the run rather than freezing it.
1075
+ let interactiveEnabled = interactive && !!inputResponsePath;
1076
+ async function askForInput(screen, fields) {
1077
+ if (!interactiveEnabled) return null;
1078
+ const requestId = `in-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1079
+ const request = { requestId, screen, fields: fields.map((f) => ({ key: f.key, label: f.label, secure: !!f.secure, placeholder: f.placeholder || "", default: f.secure ? "" : (f.default || "") })) };
1080
+ emit("AWAIT_INPUT", request);
1081
+ narrate(`Waiting for ${fields.map((f) => f.label).join(" and ")}`, { screen, awaitInput: request });
1082
+ const started = Date.now();
1083
+ let resolved = { action: "timeout", values: {} };
1084
+ try { fs.rmSync(inputResponsePath, { force: true }); } catch {}
1085
+ while (Date.now() - started < inputWaitSec * 1000) {
1086
+ await page.waitForTimeout(500);
1087
+ let reply;
1088
+ try { reply = JSON.parse(fs.readFileSync(inputResponsePath, "utf8")); } catch { continue; }
1089
+ if (reply?.requestId !== requestId) { try { fs.rmSync(inputResponsePath, { force: true }); } catch {} continue; }
1090
+ resolved = { action: String(reply.action || "defaults"), values: reply.action === "submit" && reply.values && typeof reply.values === "object" ? reply.values : {} };
1091
+ try { fs.rmSync(inputResponsePath, { force: true }); } catch {}
1092
+ break;
1093
+ }
1094
+ if (resolved.action === "timeout") interactiveEnabled = false;
1095
+ if (resolved.action === "dont_ask") interactiveEnabled = false;
1096
+ emit("INPUT_RESOLVED", { requestId, action: resolved.action });
1097
+ narrate(resolved.action === "submit" ? "Received the sign-in details" : `Sign-in request ${resolved.action === "timeout" ? "went unanswered" : resolved.action.replace("_", " ")}`, { screen, inputResolved: { requestId, action: resolved.action } });
1098
+ return resolved;
1099
+ }
1100
+
1060
1101
  async function tryLogin(screen) {
1061
- if (loginTried || !testPassword) return null;
1102
+ if (loginTried) return null;
1062
1103
  const pw = page.locator("input[type=password]").first();
1063
1104
  if (!(await pw.isVisible().catch(() => false))) return null;
1105
+ if (!testPassword) {
1106
+ // No credentials. Ask, if someone is there to answer; otherwise this is where the run ends
1107
+ // its view of the application, and the report says so.
1108
+ const answer = await askForInput(screen, [
1109
+ { key: "email", label: "Email", placeholder: "you@example.com" },
1110
+ { key: "password", label: "Password", secure: true },
1111
+ ]);
1112
+ if (!answer || answer.action !== "submit") return null;
1113
+ testEmail = String(answer.values.email || testEmail || "");
1114
+ testPassword = String(answer.values.password || "");
1115
+ if (!testPassword) return null;
1116
+ }
1064
1117
  loginTried = true;
1065
1118
  const emailSel = "input[type=email], input[name*=mail i], input[name*=user i], input[id*=mail i], input[id*=user i]";
1066
1119
  if (testEmail) {
@@ -1095,6 +1148,7 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
1095
1148
  "login form"
1096
1149
  );
1097
1150
  } else {
1151
+ await keepSession("signed-in");
1098
1152
  // SPAs commonly replace the login view without changing URL. Capture the
1099
1153
  // authenticated state immediately so coverage does not remain stuck at 1.
1100
1154
  return await observe();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aarwitz/tapp",
3
- "version": "0.21.2",
3
+ "version": "0.22.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/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/job-lanes.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/actor-store.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/job-lanes.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
  }