@aarwitz/tapp 0.23.1 → 0.24.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.23.1",
4
+ "version": "0.24.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.23.1",
27
+ "@aarwitz/tapp@0.24.0",
28
28
  "mcp"
29
29
  ],
30
30
  "cwd": "${CLAUDE_PROJECT_DIR}"
package/browser/app.css CHANGED
@@ -573,3 +573,12 @@ dialog::backdrop { background:rgba(0,0,0,.6); }
573
573
  .actor-row:last-child { border-bottom:0; }
574
574
  .actor-row small { color:var(--muted); }
575
575
  .actor-app { padding:8px 10px 2px; font-weight:600; font-size:12px; color:var(--muted); border-top:1px solid var(--tapp-border); }
576
+
577
+ /* Journeys with status (ADR-0009 slice 3). */
578
+ .journey-row .journey-name small { color:var(--muted); font-size:11px; }
579
+ .journey-status { display:inline-block; padding:1px 7px; border-radius:999px; font-size:10px; font-weight:600; letter-spacing:.02em; }
580
+ .journey-status.passing { background:rgba(46,160,67,.18); color:#4ade80; }
581
+ .journey-status.failing { background:rgba(220,38,38,.18); color:#f87171; }
582
+ .journey-status.never { background:var(--control); color:var(--muted); }
583
+ .journey-actions { display:flex; gap:6px; }
584
+ .chat-keep .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); }
package/browser/app.js CHANGED
@@ -155,6 +155,7 @@ function applyAccessMode() {
155
155
  ? "Websites are explored in the cloud. Test accounts you give tapp are kept encrypted, used only to sign in, and never shown again. iOS, Android and folders on your own machine need tapp there: npx -y @aarwitz/tapp@latest app"
156
156
  : "Websites are audited read-only in the cloud; nothing is clicked. Sign in to go inside a site. iOS, Android and folders on your own machine need tapp there: npx -y @aarwitz/tapp@latest app";
157
157
  $("#actors-panel")?.classList.toggle("hidden", !signedIn);
158
+ $("#journeys-panel")?.classList.toggle("hidden", !signedIn);
158
159
  }
159
160
 
160
161
  // The test accounts tapp holds, by application — names and what is held, never a value.
@@ -352,17 +353,27 @@ function allRuns() {
352
353
 
353
354
  // The journeys the open repository has committed under .tapp/flows/. This is the thing a
354
355
  // person owns; the engine has listed them all along and the Studio never showed them.
356
+ // The journeys this person owns, with how the last replay went. A repository's committed flows
357
+ // come grouped by folder; kept journeys (from a run that got somewhere) are flat. Both replay
358
+ // the same way and both show the same status pill.
359
+ function journeyStatus(status) {
360
+ if (!status) return '<span class="journey-status never">never run</span>';
361
+ return `<span class="journey-status ${status.passed ? "passing" : "failing"}">${status.passed ? "passing" : "failing"} · ${esc(compactDate(status.at))}</span>`;
362
+ }
363
+
355
364
  function renderJourneys() {
356
365
  const node = $("#journeys-list");
357
366
  if (!node) return;
358
- const flows = state.project?.flows || [];
359
- setCount("#journey-count", flows.length);
360
- if (!flows.length) { node.innerHTML = '<div class="empty">No journeys yet. Prove something with a session, then save it as a Flow.</div>'; return; }
361
- // Group by folder: a real repository keeps dozens under sandbox/, weekly/, mobile/. The top
362
- // level comes first; each group opens on demand so a hundred journeys read as a map.
367
+ const journeys = state.journeys || [];
368
+ setCount("#journey-count", journeys.length);
369
+ const note = $("#journeys-note");
370
+ if (note) note.textContent = journeys.some((j) => j.source === "repo")
371
+ ? "Committed under .tapp/flows/. Each replays exactly as written — no model, no key — and is what the release gate guards."
372
+ : "Each replays exactly as written — no model, no key. Keep one from any run that got somewhere; run it any time to prove it still works.";
373
+ if (!journeys.length) { node.innerHTML = '<div class="empty">No journeys yet. Explore a site — when a run gets somewhere, tapp offers to keep it.</div>'; return; }
363
374
  const groups = new Map();
364
- for (const flow of flows) { const key = flow.group || ""; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(flow); }
365
- 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>`;
375
+ for (const journey of journeys) { const key = journey.group || ""; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(journey); }
376
+ const row = (j) => `<div class="journey-row"><span class="journey-platform ${esc(j.platform || "web")}">${esc(j.platform || "web")}</span><span class="journey-name">${esc(j.name)}<br><small>${j.steps || 0} steps · ${journeyStatus(j.status)}</small></span><span></span><span class="journey-actions"><button class="quiet" data-run-journey="${esc(j.slug)}" title="Replay this journey">▶ Run</button>${j.source === "kept" ? `<button class="quiet" data-forget-journey="${esc(j.slug)}" title="Forget this journey">Forget</button>` : ""}</span></div>`;
366
377
  node.innerHTML = [...groups.entries()].sort(([a], [b]) => (a === "" ? -1 : b === "" ? 1 : a.localeCompare(b))).map(([group, items]) =>
367
378
  group === ""
368
379
  ? items.map(row).join("")
@@ -370,18 +381,68 @@ function renderJourneys() {
370
381
  ).join("");
371
382
  }
372
383
 
373
- async function runJourney(relativePath) {
374
- const name = String(relativePath).replace(/^\.tapp\/flows\//, "").replace(/\.ya?ml$/i, "");
375
- showProduct(); activateView("overview"); renderChat();
376
- setHeading(name, "Replaying the journey exactly as committed.", { owned: true });
384
+ async function loadJourneys() {
385
+ if (!state.session || state.session.access === "anonymous") { state.journeys = []; return; }
386
+ state.journeys = (await api("/api/journeys").catch(() => ({ journeys: [] }))).journeys || [];
387
+ }
388
+
389
+ async function runJourney(slug) {
390
+ const name = String(slug).replace(/^\.tapp\/flows\//, "").replace(/\.ya?ml$/i, "");
391
+ const known = (state.journeys || []).find((j) => j.slug === name);
392
+ state.promptRun = true; state.promptPlatform = "web";
393
+ showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
394
+ document.querySelector(".device-stage")?.classList.remove("hidden");
395
+ setHeading(known?.name || name, "Replaying the journey exactly as kept.", { owned: true });
377
396
  const result = await runOperation("run-flow", { name }, { input: name });
378
397
  if (result?.kind === "self-host") { answerSelfHost(result); return; }
379
398
  if (result?.kind === "journey") {
380
399
  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` : ""}.` });
381
400
  renderChat();
401
+ await loadJourneys(); renderJourneys();
382
402
  }
383
403
  }
384
404
 
405
+ async function forgetJourney(slug) {
406
+ await api(`/api/journeys/${encodeURIComponent(slug)}`, { method:"DELETE" });
407
+ await loadJourneys(); renderJourneys();
408
+ toast("Forgot that journey.");
409
+ }
410
+
411
+ // A run that got somewhere is worth keeping: offer it in the chat, with a name to edit.
412
+ async function offerJourney(result) {
413
+ const captureId = result?.capture?.id;
414
+ if (!captureId || !(result?.actionsPerformed > 0)) return;
415
+ // Ask the server what the journey would be — its name comes from where the run went.
416
+ let preview = null;
417
+ try { preview = await api(`/api/captures/${encodeURIComponent(captureId)}/keep`, { method:"POST", body:JSON.stringify({ preview: true }) }); }
418
+ catch { return; /* a run that only looked around is not offered */ }
419
+ state.pendingKeep = { captureId, suggested: preview.name, steps: preview.steps, screens: preview.screens || [], signedIn: preview.signedIn };
420
+ renderChat();
421
+ }
422
+
423
+ function renderKeepCard() {
424
+ const keep = state.pendingKeep;
425
+ if (!keep || state.activeJob) return "";
426
+ return `<form class="chat-ask chat-keep" id="chat-keep" data-capture="${esc(keep.captureId)}">
427
+ <div class="chat-ask-head"><span class="chat-icon">🧭</span><span>This run got somewhere${keep.signedIn ? ", signed in" : ""}: <b>${esc((keep.screens || []).join(" → "))}</b> (${keep.steps} steps). Keep it as a journey? It will replay exactly this path and tell you when it stops working.</span></div>
428
+ <label class="ask-field"><span>Name</span><input name="name" type="text" value="${esc(keep.suggested)}" maxlength="120"></label>
429
+ <div class="ask-actions"><button type="submit" class="primary">Keep</button><button type="button" class="quiet" data-keep="dismiss">Not now</button></div>
430
+ </form>`;
431
+ }
432
+
433
+ async function keepJourney(form) {
434
+ const captureId = form.dataset.capture;
435
+ const name = form.elements.name.value.trim();
436
+ try {
437
+ const kept = await api(`/api/captures/${encodeURIComponent(captureId)}/keep`, { method:"POST", body:JSON.stringify({ name }) });
438
+ state.pendingKeep = null;
439
+ pushLine({ kind: "step", icon: "🧭", text: `Kept as “${kept.name}” — ${kept.steps} steps${kept.signedIn ? ", signs in as your test account" : ""}. Run it any time from Journeys.` });
440
+ renderChat();
441
+ await loadJourneys(); renderJourneys();
442
+ toast(`Kept “${kept.name}”.`);
443
+ } catch (error) { toast(error.message, true); }
444
+ }
445
+
385
446
  function renderRuns() {
386
447
  renderJourneys();
387
448
  renderActors();
@@ -446,6 +507,8 @@ function renderChat() {
446
507
  // engine waits, so leave the DOM alone until the ask is answered or withdrawn.
447
508
  const openAsk = node.querySelector("#chat-ask");
448
509
  if (openAsk && state.pendingInput && openAsk.dataset.request === String(state.pendingInput.requestId)) return;
510
+ const openKeep = node.querySelector("#chat-keep");
511
+ if (openKeep && state.pendingKeep && openKeep.dataset.capture === state.pendingKeep.captureId && !state.activeJob) return;
449
512
  const stickToBottom = node.scrollTop + node.clientHeight >= node.scrollHeight - 24;
450
513
  const lines = state.transcript.map((entry) => {
451
514
  if (entry.kind === "shots") return `<div class="chat-shots">${entry.shots.map((shot) => `<a href="${esc(shot.href)}" target="_blank" rel="noreferrer" title="${esc(shot.caption)}"><img src="${esc(shot.src)}" alt="${esc(shot.caption)}"></a>`).join("")}</div>`;
@@ -454,7 +517,7 @@ function renderChat() {
454
517
  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>`;
455
518
  if (entry.kind === "progress") return "";
456
519
  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>`;
457
- }).join("") + renderAskCard() + (state.activeJob && !state.pendingInput ? '<div class="chat-line typing"><span class="chat-icon">✨</span><span>tapp is working<i>…</i></span></div>' : "");
520
+ }).join("") + renderAskCard() + renderKeepCard() + (state.activeJob && !state.pendingInput ? '<div class="chat-line typing"><span class="chat-icon">✨</span><span>tapp is working<i>…</i></span></div>' : "");
458
521
  node.innerHTML = lines;
459
522
  if (stickToBottom) node.scrollTop = node.scrollHeight;
460
523
  const progress = [...state.transcript].reverse().find((entry) => entry.kind === "progress");
@@ -662,6 +725,7 @@ async function refresh() {
662
725
  state.audits = runs.audits || [];
663
726
  state.explores = runs.explores || [];
664
727
  state.actors = actors.apps || [];
728
+ await loadJourneys();
665
729
  renderProject();
666
730
  return;
667
731
  }
@@ -670,6 +734,7 @@ async function refresh() {
670
734
  state.live = live;
671
735
  state.audits = runs.audits || [];
672
736
  state.explores = runs.explores || [];
737
+ await loadJourneys();
673
738
  renderProject();
674
739
  }
675
740
 
@@ -774,6 +839,8 @@ async function startFromPrompt(raw) {
774
839
  }
775
840
  if (result?.kind === "self-host") { answerSelfHost(result); return; }
776
841
  state.selectedRunId = result?.capture?.id || state.selectedRunId;
842
+ state.pendingKeep = null;
843
+ await offerJourney(result);
777
844
  return;
778
845
  }
779
846
  state.promptRun = true; state.promptPlatform = "web";
@@ -844,6 +911,8 @@ document.addEventListener("submit", (event) => {
844
911
  if (ask) { event.preventDefault(); answerAsk(ask, "submit"); }
845
912
  const signin = event.target.closest("#signin-form");
846
913
  if (signin) { event.preventDefault(); requestSignInLink(signin.elements.email.value.trim()); }
914
+ const keep = event.target.closest("#chat-keep");
915
+ if (keep) { event.preventDefault(); keepJourney(keep); }
847
916
  });
848
917
  document.addEventListener("click", (event) => {
849
918
  const button = event.target.closest("#chat-ask [data-ask]");
@@ -858,6 +927,9 @@ document.addEventListener("click", (event) => {
858
927
  state.signInOpen = true; renderAccount(); showPrompt(); setTimeout(() => $("#signin-email")?.focus(), 50);
859
928
  }
860
929
  if (event.target.closest("[data-signout]")) { event.preventDefault(); signOut(); }
930
+ if (event.target.closest("[data-keep=dismiss]")) { event.preventDefault(); state.pendingKeep = null; renderChat(); }
931
+ const forgetJ = event.target.closest("[data-forget-journey]");
932
+ if (forgetJ) { event.preventDefault(); forgetJourney(forgetJ.dataset.forgetJourney).catch((error) => toast(error.message, true)); }
861
933
  const forget = event.target.closest("[data-forget-actor]");
862
934
  if (forget) { event.preventDefault(); forgetActor(forget.dataset.forgetHost, forget.dataset.forgetActor).catch((error) => toast(error.message, true)); }
863
935
  });
@@ -176,8 +176,8 @@
176
176
  <div class="section-heading compact"><div><p class="eyebrow">Test accounts</p><h2>What tapp can sign in as <i id="actor-count" class="zero">0</i></h2><p>Kept encrypted. Shown here is only the name and whether a password or a signed-in session is held — never the values. Forget one and tapp will ask again next time.</p></div></div>
177
177
  <div id="actors-list"><div class="empty">None yet. Explore a site with a sign-in and tapp will ask.</div></div>
178
178
  </section>
179
- <section class="panel section" id="journeys-panel" data-repo-only>
180
- <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>
179
+ <section class="panel section" id="journeys-panel">
180
+ <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 id="journeys-note">Each replays exactly as written — no model, no key. Keep one from any run that got somewhere; run it any time to prove it still works.</p></div></div>
181
181
  <div id="journeys-list"><div class="empty">No journeys yet.</div></div>
182
182
  </section>
183
183
  <div class="split-view">
@@ -114,3 +114,26 @@ write-only from the UI, encrypted at rest, decrypted only inside the run that si
114
114
 
115
115
  A local trial of the public mode (`--origin http://127.0.0.1:PORT`) does not pin browser egress
116
116
  to public addresses, so it can reach a site on the same machine; a real origin always does.
117
+
118
+ ## Journeys: keeping a proven run
119
+
120
+ A run that got somewhere is offered in the chat as a journey (`journeys.js`). Keeping it writes a
121
+ Flow in the runner's vocabulary — `wait_for` each screen, `tap` each control and navigation link,
122
+ `login: $TEST_EMAIL / $TEST_PASSWORD` for a sign-in, `assert_screen` on the last screen — to the
123
+ place this person owns:
124
+
125
+ | Who | Where | Replayed by |
126
+ |---|---|---|
127
+ | Operator with a repository open | `<repo>/.tapp/flows/<slug>.yml` | the Studio, `tapp run`, `tapp ci` |
128
+ | Account on a public Studio | `TAPP_HOME/accounts/journeys/<id>/<slug>.yml` | the Studio |
129
+ | Operator without a repository | `TAPP_HOME/journeys/<slug>.yml` | the Studio |
130
+
131
+ The last replay's result sits beside it in `.status/<slug>.json` and shows in the Journeys panel
132
+ as *passing · 2h ago*, *failing* or *never run*. A replay resolves `$TEST_EMAIL`/`$TEST_PASSWORD`
133
+ from the encrypted actor store for the journey's `actor` (never from the file) and, for a journey
134
+ kept from a run that started signed in, opens the browser from that actor's saved session.
135
+
136
+ Endpoints: `POST /api/captures/:id/keep` (`{ name, actor, replace, preview }` — `preview` names
137
+ the journey and lists its screens without keeping it), `GET /api/journeys`,
138
+ `DELETE /api/journeys/:slug` (kept journeys only; committed flows are the repository's),
139
+ `POST /api/operations/run-flow` (`{ name }`).
@@ -21,6 +21,7 @@ import { AccountStore } from "./account-store.js";
21
21
  import { ActorStore, hostKey } from "./actor-store.js";
22
22
  import { createMailer, signInMessage } from "./mailer.js";
23
23
  import { accessConfig, createAccessVerifier } from "./access-jwt.js";
24
+ import { journeyFromCapture, JourneyStore, slugify } from "./journeys.js";
24
25
 
25
26
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
26
27
  const assetRoot = path.join(packageRoot, "browser");
@@ -153,8 +154,11 @@ function anonymousAllows(method, pathname) {
153
154
  function accountAllows(method, pathname) {
154
155
  if (anonymousAllows(method, pathname)) return true;
155
156
  if (method === "POST" && (pathname === "/api/auth/signout" || /^\/api\/jobs\/[a-f0-9]{20}\/input$/.test(pathname))) return true;
156
- if (method === "GET" && pathname === "/api/actors") return true;
157
+ if (method === "GET" && (pathname === "/api/actors" || pathname === "/api/journeys")) return true;
157
158
  if (method === "DELETE" && /^\/api\/actors\/[A-Za-z0-9.:-]{1,253}\/[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(pathname)) return true;
159
+ // Journeys: keep a proven run, replay it, forget it (ADR-0009 slice 3).
160
+ if (method === "POST" && (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/keep$/.test(pathname) || pathname === "/api/operations/run-flow")) return true;
161
+ if (method === "DELETE" && /^\/api\/journeys\/[a-z0-9-]{1,60}$/.test(pathname)) return true;
158
162
  return false;
159
163
  }
160
164
 
@@ -787,6 +791,56 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
787
791
  json(response, 200, { ok: true });
788
792
  return;
789
793
  }
794
+ // Where this person's journeys live: the open repository's .tapp/flows/ for the operator,
795
+ // the account's own store on a public Studio, this machine's store otherwise.
796
+ const journeyStore = () => {
797
+ if (account) return JourneyStore.forAccount(account.id);
798
+ const root = registry.currentRoot();
799
+ return root ? JourneyStore.forRepository(root) : JourneyStore.forMachine();
800
+ };
801
+ const keepMatch = !anonymous && request.method === "POST" ? url.pathname.match(/^\/api\/captures\/([A-Za-z0-9._-]{1,128})\/keep$/) : null;
802
+ if (keepMatch) {
803
+ requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
804
+ if (!visibleToOwner(keepMatch[1], evidenceOwner)) { response.writeHead(404); response.end("Not found"); return; }
805
+ const captureDir = capturePath(keepMatch[1], ".");
806
+ if (!captureDir || !fs.existsSync(captureDir)) { json(response, 404, { error: "No such capture" }); return; }
807
+ const body = await readJsonBody(request);
808
+ const journey = journeyFromCapture(captureDir, { name: String(body.name || "").slice(0, 120), actor: /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(String(body.actor || "")) ? String(body.actor) : "default" });
809
+ if (!journey) { json(response, 409, { error: "That run only looked around; there is no path to keep." }); return; }
810
+ // A preview names the journey and lists where it went without keeping anything, so the
811
+ // Studio can offer it with the right name instead of a guess.
812
+ if (body.preview === true) { json(response, 200, { name: journey.flow.name, slug: slugify(journey.flow.name), steps: journey.steps, screens: journey.screens, signedIn: journey.signedIn, preview: true }); return; }
813
+ let kept;
814
+ try { kept = journeyStore().keep(journey, { replace: body.replace === true }); }
815
+ catch (error) { json(response, error.statusCode || 500, { error: error.message }); return; }
816
+ logUsage("journey.kept", { owner: (ownerKey || "operator").slice(0, 13), steps: journey.steps, signedIn: journey.signedIn });
817
+ json(response, 200, { name: journey.flow.name, slug: kept.slug, steps: journey.steps, screens: journey.screens, signedIn: journey.signedIn, path: registry.currentRoot() && !account ? path.relative(registry.currentRoot(), kept.path) : null });
818
+ return;
819
+ }
820
+ if (!anonymous && request.method === "GET" && url.pathname === "/api/journeys") {
821
+ const store = journeyStore();
822
+ const root = !account ? registry.currentRoot() : null;
823
+ let journeys;
824
+ if (root) {
825
+ // The repository's committed flows, recursively, with the last Studio replay beside each.
826
+ const { readProductProject } = await import("./product-operations.js");
827
+ const flows = readProductProject({ projectDir: root }).flows || [];
828
+ journeys = flows.map((flow) => ({ name: flow.name, slug: flow.relativePath.replace(/^\.tapp\/flows\//, "").replace(/\.(?:ya?ml|json)$/i, ""), group: flow.group || "", platform: flow.platform, steps: flow.steps, source: "repo", status: store.status(flow.relativePath.replace(/^\.tapp\/flows\//, "").replace(/\.(?:ya?ml|json)$/i, "")) }));
829
+ } else {
830
+ journeys = store.list().map((journey) => ({ ...journey, group: "" }));
831
+ }
832
+ json(response, 200, { journeys });
833
+ return;
834
+ }
835
+ const forgetJourneyMatch = !anonymous && request.method === "DELETE" ? url.pathname.match(/^\/api\/journeys\/([a-z0-9-]{1,60})$/) : null;
836
+ if (forgetJourneyMatch) {
837
+ requireMutationAuth(request, hosted ? publicOrigins : origin, csrfToken);
838
+ // Committed flows are the repository's; only kept journeys are forgotten from here.
839
+ if (!account && registry.currentRoot()) { json(response, 409, { error: "That journey is committed in the repository; remove the file there." }); return; }
840
+ journeyStore().forget(forgetJourneyMatch[1]);
841
+ json(response, 200, { ok: true });
842
+ return;
843
+ }
790
844
  if (request.method === "GET" && url.pathname === "/api/session") {
791
845
  if (account) {
792
846
  json(response, 200, {
@@ -1033,30 +1087,64 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1033
1087
  // answered with the command to run it where that is.
1034
1088
  if (operation === "run-flow") {
1035
1089
  if (anonymous) { json(response, 401, { error: "Sign in to replay a journey" }); return; }
1036
- const root = registry.currentRoot();
1037
- if (!root) throw Object.assign(new Error("Open a repository first"), { statusCode: 409 });
1090
+ const store = journeyStore();
1091
+ const root = !account ? registry.currentRoot() : null;
1038
1092
  const name = String(body.name || "").replace(/\.ya?ml$/i, "");
1039
1093
  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 });
1040
- const flowPath = path.join(root, ".tapp", "flows", `${name}.yml`);
1041
- if (!flowPath.startsWith(path.join(root, ".tapp", "flows") + path.sep) || !fs.existsSync(flowPath)) throw Object.assign(new Error(`No journey named ${name}`), { statusCode: 404 });
1094
+ // A repository journey may sit in a subfolder; a kept one is a flat slug in its store.
1095
+ const flowPath = root ? path.join(root, ".tapp", "flows", `${name}.yml`) : store.flowPath(name);
1096
+ if (!flowPath.startsWith(store.root + path.sep) || !fs.existsSync(flowPath)) throw Object.assign(new Error(`No journey named ${name}`), { statusCode: 404 });
1042
1097
  const { loadFlowFile, inferFlowPlatform } = await import("./flow-runtime.js");
1043
1098
  const flow = loadFlowFile(flowPath);
1044
1099
  const platform = inferFlowPlatform(flow);
1100
+ const shown = root ? path.relative(root, flowPath) : `${name}.yml`;
1045
1101
  if (platform !== "web") {
1046
- json(response, 200, { kind: "self-host", command: `npx -y @aarwitz/tapp@latest run ${path.relative(root, flowPath)}`,
1047
- 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)}` });
1102
+ json(response, 200, { kind: "self-host", command: `npx -y @aarwitz/tapp@latest run ${shown}`,
1103
+ 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 ${shown}` });
1048
1104
  return;
1049
1105
  }
1106
+ // A journey that signs in does so as the test account tapp was told about for that
1107
+ // site: the values come from the encrypted actor store at replay and never from the file.
1108
+ const variables = {};
1109
+ let storageStatePath = "";
1110
+ if (flow.url && (flow.actor || (flow.steps || []).some((step) => step && typeof step === "object" && "login" in step))) {
1111
+ const actors = new ActorStore(actorRootFor() ? { root: actorRootFor() } : {});
1112
+ const record = actors.read(flow.url, flow.actor || "default");
1113
+ if (record?.credentials?.email) variables.TEST_EMAIL = record.credentials.email;
1114
+ if (record?.credentials?.password) variables.TEST_PASSWORD = record.credentials.password;
1115
+ // A journey that began inside replays from the actor's saved session, like the run did.
1116
+ if (flow.actor) storageStatePath = actors.sessionFile(flow.url, flow.actor) || "";
1117
+ }
1050
1118
  const captureId = `flow-web-${Date.now().toString(36)}-${crypto.randomBytes(4).toString("hex")}`;
1051
1119
  const evidenceDir = path.join(captureRoot(), captureId);
1052
1120
  fs.mkdirSync(evidenceDir, { recursive: true });
1053
1121
  const job = startJob(operation, async (progress) => {
1054
1122
  progress({ phase: "runtime", text: `Replaying ${flow.name || name}` });
1055
1123
  const { runWebFlow } = await import("./web-flow.js");
1056
- const result = await runWebFlow({ flow, logPath: path.join(evidenceDir, "flow.log"), screenshotDir: evidenceDir, recordVideoDir: evidenceDir });
1057
- for (const line of result.lines || []) progress({ phase: "replay", text: typeof line === "string" ? line : (line.text || JSON.stringify(line)) });
1058
- return { kind: "journey", name: flow.name || name, passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, capture: { id: captureId, path: evidenceDir } };
1059
- }, null);
1124
+ let result;
1125
+ try { result = await runWebFlow({ flow, variables, storageStatePath, logPath: path.join(evidenceDir, "flow.log"), screenshotDir: evidenceDir, recordVideoDir: evidenceDir }); }
1126
+ finally { if (storageStatePath) { try { fs.rmSync(storageStatePath, { force: true }); } catch { /* temp */ } } }
1127
+ // The runner's log is marker lines; the chat wants one plain sentence per step.
1128
+ for (const line of result.lines || []) {
1129
+ const raw = typeof line === "string" ? line : (line.text || "");
1130
+ const step = raw.match(/^OCQA_FLOW_STEP:(\{.*\})$/);
1131
+ if (step) {
1132
+ try {
1133
+ const s = JSON.parse(step[1]);
1134
+ const what = s.action === "login" ? "Signed in" : s.action === "wait_for" ? `Reached ${s.target}` : s.action === "assert_screen" ? `On ${s.target}` : s.action === "tap" ? `Tapped "${s.target}"` : `${s.action} ${s.target || ""}`.trim();
1135
+ progress({ phase: "replay", text: s.status === "pass" ? `${what}` : `Step ${s.index}: ${what} — ${s.detail || "failed"}` });
1136
+ } catch { progress({ phase: "replay", text: raw }); }
1137
+ continue;
1138
+ }
1139
+ if (/^OCQA_(FLOW_RESULT|ISSUE):/.test(raw)) continue;
1140
+ if (raw) progress({ phase: "replay", text: raw });
1141
+ }
1142
+ const status = store.recordRun(root ? name : slugify(name), { passed: result.passed, captureId, executed: result.executed, total: result.total, failed: result.failed });
1143
+ if (ownerKey) setCaptureOwner(captureId, ownerKey);
1144
+ logUsage("journey.run", { owner: (ownerKey || "operator").slice(0, 13), passed: result.passed });
1145
+ return { kind: "journey", name: flow.name || name, slug: root ? name : slugify(name), passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, status, capture: { id: captureId, path: evidenceDir } };
1146
+ }, null, { lane: ownerKey || OPERATOR_LANE });
1147
+ job.ownerKey = ownerKey;
1060
1148
  json(response, 202, { job: publicJob(job, { hosted }) });
1061
1149
  return;
1062
1150
  }
@@ -0,0 +1,189 @@
1
+ // A proven run becomes a journey you own (ADR-0009 slice 3).
2
+ //
3
+ // An exploration that got somewhere — through a sign-in, across a few screens — is worth more
4
+ // than its report: replayed, it is a test of that path through the real application. This
5
+ // module turns the capture's action log (OCQA_ACTION / OCQA_STATE markers) into a Flow in the
6
+ // vocabulary the deterministic runner already speaks, keeps it where it belongs, and remembers
7
+ // how its last replay went.
8
+ //
9
+ // Where a journey lives:
10
+ // a repository → <repo>/.tapp/flows/<slug>.yml (committed, guarded by `tapp ci`)
11
+ // an account → TAPP_HOME/accounts/journeys/<id>/<slug>.yml
12
+ // a local prompt run → TAPP_HOME/journeys/<slug>.yml
13
+ // Its last result lives beside it in .status/<slug>.json. Credentials never enter a journey: a
14
+ // sign-in is `login: $TEST_EMAIL / $TEST_PASSWORD`, resolved at replay from the actor store.
15
+ import fs from "node:fs";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+
19
+ const MAX_STEPS = 40;
20
+
21
+ export function slugify(name) {
22
+ return String(name || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "journey";
23
+ }
24
+
25
+ function readMarkers(captureDir) {
26
+ let text = "";
27
+ try { text = fs.readFileSync(path.join(captureDir, "ocqa-markers.txt"), "utf8"); } catch { return []; }
28
+ const out = [];
29
+ for (const line of text.split("\n")) {
30
+ const match = line.match(/^(OCQA_ACTION|OCQA_STATE):(\{.*\})\s*$/);
31
+ if (!match) continue;
32
+ try { out.push({ kind: match[1], ...JSON.parse(match[2]) }); } catch { /* a torn line */ }
33
+ }
34
+ return out;
35
+ }
36
+
37
+ // tapp names a revisited screen "Orders (refreshed)"; the page itself still says "Orders".
38
+ const pageName = (screen) => String(screen || "").replace(/\s*\((?:refreshed|again|\d+)\)\s*$/i, "").trim();
39
+
40
+ /**
41
+ * Build a Flow from an exploration capture. Returns null when the run did nothing worth
42
+ * replaying (no action but the opening).
43
+ */
44
+ export function journeyFromCapture(captureDir, { name = "", actor = "default" } = {}) {
45
+ let provenance = null;
46
+ try { provenance = JSON.parse(fs.readFileSync(path.join(captureDir, "provenance.json"), "utf8")); } catch { /* older capture */ }
47
+ const target = String(provenance?.target || "");
48
+ if (!/^https?:\/\//i.test(target)) return null;
49
+ const markers = readMarkers(captureDir);
50
+ const steps = [];
51
+ const screens = [];
52
+ let lastWaited = "";
53
+ const waitFor = (screen) => {
54
+ const page = pageName(screen);
55
+ if (!page || page === lastWaited) return;
56
+ steps.push({ wait_for: page });
57
+ lastWaited = page;
58
+ screens.push(page);
59
+ };
60
+ let acted = false;
61
+ let signedIn = false;
62
+ for (let i = 0; i < markers.length && steps.length < MAX_STEPS; i += 1) {
63
+ const marker = markers[i];
64
+ if (marker.kind === "OCQA_STATE") { waitFor(marker.screen); continue; }
65
+ switch (marker.type) {
66
+ case "open":
67
+ // The first open is the journey's URL; a later one came through a navigation link.
68
+ if (marker.via && marker.via !== marker.target && marker.via !== "/") { steps.push({ tap: marker.via }); acted = true; }
69
+ break;
70
+ case "login":
71
+ steps.push({ login: { email: "$TEST_EMAIL", password: "$TEST_PASSWORD" } });
72
+ signedIn = true; acted = true;
73
+ break;
74
+ case "session":
75
+ // The run started inside from a saved session; the replay will too (storageState).
76
+ signedIn = true;
77
+ break;
78
+ case "tap":
79
+ if (marker.target) { steps.push({ tap: marker.target }); acted = true; }
80
+ break;
81
+ case "type":
82
+ // What was typed during exploration is not part of the path; the field is.
83
+ if (marker.target && !marker.secure) { steps.push({ type: { field: marker.target, value: String(marker.value || "") } }); acted = true; }
84
+ break;
85
+ default:
86
+ break;
87
+ }
88
+ }
89
+ if (!acted) return null;
90
+ // End on the screen the run ended on, so a replay that drifts is a failure, not a pass.
91
+ if (lastWaited) { steps.pop(); steps.push({ assert_screen: lastWaited }); }
92
+ const host = (() => { try { return new URL(target).host; } catch { return "site"; } })();
93
+ const journeyName = String(name || "").trim() || `${host} — ${screens[0] || "start"}${screens.length > 1 ? ` to ${screens[screens.length - 1]}` : ""}`;
94
+ const flow = { name: journeyName, platform: "web", url: target, ...(signedIn ? { actor } : {}), steps };
95
+ return { flow, yaml: flowToYaml(flow), steps: steps.length, screens, signedIn };
96
+ }
97
+
98
+ // The Flow vocabulary is small and flat; a dependency-free emitter keeps the hosted Studio from
99
+ // needing python for this. Strings are JSON-quoted, which YAML accepts verbatim.
100
+ const q = (value) => JSON.stringify(String(value));
101
+ export function flowToYaml(flow) {
102
+ const lines = [`name: ${q(flow.name)}`, `platform: ${flow.platform || "web"}`];
103
+ if (flow.url) lines.push(`url: ${q(flow.url)}`);
104
+ if (flow.actor) lines.push(`actor: ${q(flow.actor)}`);
105
+ lines.push("steps:");
106
+ for (const step of flow.steps || []) {
107
+ const [action, value] = Object.entries(step)[0];
108
+ if (value && typeof value === "object") {
109
+ lines.push(`- ${action}:`);
110
+ for (const [key, inner] of Object.entries(value)) lines.push(` ${key}: ${/^\$[A-Z_]+$/.test(String(inner)) ? inner : q(inner)}`);
111
+ } else {
112
+ lines.push(`- ${action}: ${q(value)}`);
113
+ }
114
+ }
115
+ return `${lines.join("\n")}\n`;
116
+ }
117
+
118
+ /** Where kept journeys and their statuses live for one owner. */
119
+ export class JourneyStore {
120
+ constructor({ root }) {
121
+ this.root = root;
122
+ }
123
+
124
+ static forAccount(accountId, env = process.env) {
125
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
126
+ if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) throw new Error("Not an account id");
127
+ return new JourneyStore({ root: path.join(home, "accounts", "journeys", accountId) });
128
+ }
129
+
130
+ static forMachine(env = process.env) {
131
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
132
+ return new JourneyStore({ root: path.join(home, "journeys") });
133
+ }
134
+
135
+ static forRepository(repoRoot) {
136
+ return new JourneyStore({ root: path.join(repoRoot, ".tapp", "flows") });
137
+ }
138
+
139
+ flowPath(slug) {
140
+ const safe = slugify(slug);
141
+ return path.join(this.root, `${safe}.yml`);
142
+ }
143
+
144
+ keep(journey, { replace = false } = {}) {
145
+ const slug = slugify(journey.flow.name);
146
+ const file = this.flowPath(slug);
147
+ if (fs.existsSync(file) && !replace) throw Object.assign(new Error(`A journey named '${journey.flow.name}' already exists. Pick another name or replace it.`), { statusCode: 409 });
148
+ fs.mkdirSync(this.root, { recursive: true, mode: 0o700 });
149
+ fs.writeFileSync(file, journey.yaml, { mode: 0o600 });
150
+ return { slug, path: file };
151
+ }
152
+
153
+ forget(slug) {
154
+ try { fs.rmSync(this.flowPath(slug), { force: true }); fs.rmSync(this.statusPath(slug), { force: true }); return true; } catch { return false; }
155
+ }
156
+
157
+ statusPath(slug) {
158
+ return path.join(this.root, ".status", `${slugify(slug)}.json`);
159
+ }
160
+
161
+ recordRun(slug, { passed, captureId = null, executed = 0, total = 0, failed = 0 }) {
162
+ const file = this.statusPath(slug);
163
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
164
+ const status = { passed: !!passed, at: new Date().toISOString(), captureId, executed, total, failed };
165
+ fs.writeFileSync(file, JSON.stringify(status), { mode: 0o600 });
166
+ return status;
167
+ }
168
+
169
+ status(slug) {
170
+ try { return JSON.parse(fs.readFileSync(this.statusPath(slug), "utf8")); } catch { return null; }
171
+ }
172
+
173
+ /** Every journey here, with its last result. Names only; never the file contents. */
174
+ list() {
175
+ let entries = [];
176
+ try { entries = fs.readdirSync(this.root, { withFileTypes: true }); } catch { return []; }
177
+ const out = [];
178
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
179
+ if (!entry.isFile() || !/\.ya?ml$/i.test(entry.name)) continue;
180
+ const slug = entry.name.replace(/\.ya?ml$/i, "");
181
+ let source = "";
182
+ try { source = fs.readFileSync(path.join(this.root, entry.name), "utf8"); } catch { continue; }
183
+ const scalar = (key) => { const m = source.match(new RegExp(`^${key}:\\s*(.+?)\\s*$`, "m")); return m ? m[1].replace(/^["']|["']$/g, "") : ""; };
184
+ const steps = (source.match(/^- [a-z_]+:/gm) || []).length;
185
+ out.push({ name: scalar("name") || slug, slug, platform: scalar("platform") || "web", url: scalar("url"), actor: scalar("actor"), steps, status: this.status(slug), source: "kept" });
186
+ }
187
+ return out;
188
+ }
189
+ }
@@ -879,7 +879,9 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
879
879
  let probeCapHit = false;
880
880
  let actions = 0;
881
881
  let screenCount = 0;
882
- if (startedSignedIn) narrate("Starting signed in from the saved session");
882
+ // A marker as well as a line, so a journey kept from this run knows it began inside and
883
+ // replays from the same saved session rather than at a sign-in it never saw.
884
+ if (startedSignedIn) emitAction({ type: "session", target: "saved session", narrative: "Starting signed in from the saved session" });
883
885
  // Which distinct on-screen states each route has produced, so one route cannot mint states
884
886
  // without limit when something on it never settles.
885
887
  const signaturesByRoute = new Map();
@@ -290,7 +290,7 @@ export function resolveGateFlowUrl(declared, gateUrl) {
290
290
  }
291
291
  }
292
292
 
293
- export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVideoDir, variables = {}, strictOrigin = false, playwright, device = "", viewport = "", urlIsFallback = false }) {
293
+ export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVideoDir, variables = {}, strictOrigin = false, playwright, device = "", viewport = "", urlIsFallback = false, storageStatePath = "" }) {
294
294
  // urlIsFallback = the caller is a gate: the Flow's own page wins, rebased onto the gate's
295
295
  // deployment (see resolveGateFlowUrl). An explicit caller url (CLI positional) still overrides.
296
296
  const declaredUrl = flow.url || (/^https?:\/\//i.test(flow.app || "") ? flow.app : "");
@@ -311,6 +311,8 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVide
311
311
  const context = await browser.newContext({
312
312
  ...contextOptions,
313
313
  ...(recordVideoDir ? { recordVideo: { dir: recordVideoDir, ...(contextOptions.viewport ? { size: contextOptions.viewport } : {}) } } : {}),
314
+ // A journey kept from a run that started signed in replays from the same saved session.
315
+ ...(storageStatePath ? { storageState: storageStatePath } : {}),
314
316
  });
315
317
  const page = await context.newPage();
316
318
  const timeout = Number(flow.timeoutMs ?? flow.timeout) || DEFAULT_TIMEOUT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aarwitz/tapp",
3
- "version": "0.23.1",
3
+ "version": "0.24.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/actor-store.test.js tests/account-store.test.js tests/access-jwt.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/account-store.test.js tests/access-jwt.test.js tests/journeys.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
  }
@@ -37,7 +37,7 @@ def to_yaml(json_str):
37
37
  # Order keys for readability. `platform` + `url` make the same repository-native
38
38
  # Flow format portable across the XCUITest, Playwright, and Android drivers.
39
39
  ordered = {}
40
- for k in ("name", "platform", "app", "url", "vars", "reset"):
40
+ for k in ("name", "platform", "app", "url", "actor", "vars", "reset"):
41
41
  if flow.get(k):
42
42
  ordered[k] = flow[k]
43
43
  ordered["steps"] = flow.get("steps", [])
@@ -54,6 +54,8 @@ def to_json(path):
54
54
  "platform": flow.get("platform", ""),
55
55
  "app": flow.get("app", ""),
56
56
  "url": flow.get("url", ""),
57
+ # Which test account a journey signs in as (ADR-0009); the Studio resolves it at replay.
58
+ "actor": str(flow.get("actor", "") or ""),
57
59
  "steps": flow.get("steps", []),
58
60
  "vars": flow.get("vars", {}),
59
61
  "reset": flow.get("reset", "launch"),