@aarwitz/tapp 0.35.7 → 0.35.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/browser/app.js CHANGED
@@ -153,6 +153,16 @@ function activateView(view) {
153
153
  // On a public Studio a person is a visitor until they sign in, and an account after. Both slots
154
154
  // (prompt screen and sidebar) show the same thing. A local Studio has neither: the one person at
155
155
  // the keyboard is the operator.
156
+ // What the cloud will do for this account, in a word: the trial's days left, that it ended, or
157
+ // that there is nothing to count (ADR-0011 §3). Never shown to the deployment's owner.
158
+ function planPill(plan) {
159
+ if (!plan || plan.kind === "owner") return "";
160
+ if (plan.kind === "paid") return `<span class="journey-status passing" title="On a plan">plan</span>`;
161
+ if (plan.kind === "lapsed") return `<span class="journey-status failing" title="Cloud runs are for accounts on a plan — write to hello@runtapp.com">trial ended</span>`;
162
+ const days = plan.daysLeft ?? 0;
163
+ return `<span class="journey-status ${days <= 3 ? "failing" : "never"}" title="Free trial until ${esc(String(plan.endsAt || "").slice(0, 10))}">trial · ${esc(String(days))} day${days === 1 ? "" : "s"} left</span>`;
164
+ }
165
+
156
166
  function renderAccount() {
157
167
  const session = state.session || {};
158
168
  const isPublic = session.access === "anonymous" || session.access === "account";
@@ -160,7 +170,7 @@ function renderAccount() {
160
170
  slot.classList.toggle("hidden", !isPublic);
161
171
  if (!isPublic) continue;
162
172
  slot.innerHTML = session.access === "account"
163
- ? `<span class="account-email" title="${esc(session.email || "")}">${esc(session.email || "")}</span><button type="button" data-signout>Sign out</button>`
173
+ ? `<span class="account-email" title="${esc(session.email || "")}">${esc(session.email || "")}</span>${planPill(session.plan)}<button type="button" data-signout>Sign out</button>`
164
174
  : `<button type="button" class="primary" data-signin>Sign in</button>`;
165
175
  }
166
176
  $("#signin-card")?.classList.toggle("hidden", session.access !== "anonymous" || !state.signInOpen);
@@ -210,21 +220,24 @@ function applyAccessMode() {
210
220
  // one where most of it says "ready".
211
221
  renderPlatformStrip();
212
222
  renderPlatforms();
223
+ renderStudioLink();
213
224
  if (session.access !== "anonymous" && session.access !== "account") return;
214
225
  const signedIn = session.access === "account";
215
226
  const accepts = new Set(session.accepts || ["url"]);
216
- // A target this Studio cannot START is still a thing tapp does. It used to be deleted from
217
- // the screen, which is how a cross-platform product came to look like a website checker: the
218
- // hosted Studio erased every mention of iOS, Android and folders. Keep them, mark them, and
219
- // let the answer be "here is where that runs" (ADR-0010).
227
+ // A target this Studio cannot START is still a thing tapp does — on the person's own machine.
228
+ // It used to be deleted from the screen, which is how a cross-platform product came to look
229
+ // like a website checker; then dimmed but offered (ADR-0010), so a stranger learned what the
230
+ // page could not do by trying it. Now the self-host card names it, with the command, before
231
+ // anyone types it (ADR-0011): an example nobody can start here is not offered as something to
232
+ // type here. Typing one anyway still gets the "here is where that runs" answer.
220
233
  for (const button of document.querySelectorAll("[data-kind]")) {
221
234
  const kind = button.dataset.kind;
222
235
  const usable = kind === "url" ? accepts.has("url") : accepts.has(kind);
223
- button.closest("li")?.classList.remove("hidden");
224
- button.classList.toggle("elsewhere", !usable);
236
+ button.closest("li")?.classList.toggle("hidden", !usable);
225
237
  }
238
+ $("#selfhost-card")?.classList.remove("hidden");
226
239
  const input = $("#prompt-input");
227
- if (input) input.placeholder = accepts.has("path") ? input.placeholder : "A website URL — or an .app, .apk or repo to be told where it runs…";
240
+ if (input) input.placeholder = accepts.has("path") ? input.placeholder : "A website URL — https://…";
228
241
  // Everything that only means something against a source repository: a target to build, a
229
242
  // runner, a release gate, a decision. A hosted visitor auditing a URL has none of them, and
230
243
  // showing the empty frames makes a working run look like a broken one.
@@ -237,8 +250,8 @@ function applyAccessMode() {
237
250
  if (!state.headingOwnedByRun) setHeading("tapp", signedIn ? "Give it a website. If there is a sign-in, I will ask you for a test account and remember it." : "Give it a public website and it will audit the pages read-only.");
238
251
  const note = $("#privacy-note-detail");
239
252
  if (note) note.textContent = signedIn
240
- ? "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 run the same Studio there: npx -y @aarwitz/tapp@latest app"
241
- : "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 run the same Studio there: npx -y @aarwitz/tapp@latest app";
253
+ ? "Public websites are explored in the cloud. Test accounts you give tapp are kept encrypted, used only to sign in, and never shown again."
254
+ : "Public websites are audited read-only in the cloud; nothing is clicked. Sign in to go inside a site from here.";
242
255
  $("#actors-panel")?.classList.toggle("hidden", !signedIn);
243
256
  $("#journeys-panel")?.classList.toggle("hidden", !signedIn);
244
257
  $("#agent-panel")?.classList.toggle("hidden", !signedIn);
@@ -346,7 +359,7 @@ function renderAdmin() {
346
359
 
347
360
  <section class="panel section">
348
361
  <div class="section-heading compact"><div><p class="eyebrow">Accounts</p><h2>People with a tapp account <i class="zero">${data.accounts.length}</i></h2><p>Test accounts are counted, never shown — tapp cannot show them.</p></div></div>
349
- ${data.accounts.length ? data.accounts.map((account) => `<div class="actor-row"><span><strong>${esc(account.email)}</strong>${owner(account.email) ? ' <small class="journey-status passing">owner</small>' : ""}<br><small>joined ${esc(compactDate(account.createdAt))}${account.lastSeenAt ? ` · last seen ${esc(compactDate(account.lastSeenAt))}` : ""}</small></span><span><small>${account.journeys} journey${account.journeys === 1 ? "" : "s"}${account.failing ? ` · <b class="journey-status failing">${account.failing} failing</b>` : ""}${account.neverRun ? ` · ${account.neverRun} never run` : ""}</small></span><span><small>${account.testAccounts} test account${account.testAccounts === 1 ? "" : "s"} · ${account.tokens} token${account.tokens === 1 ? "" : "s"}</small></span></div>`).join("") : '<div class="empty">Nobody has signed in yet.</div>'}
362
+ ${data.accounts.length ? data.accounts.map((account) => `<div class="actor-row"><span><strong>${esc(account.email)}</strong>${owner(account.email) ? ' <small class="journey-status passing">owner</small>' : ` ${planPill(account.plan)}`}<br><small>joined ${esc(compactDate(account.createdAt))}${account.lastSeenAt ? ` · last seen ${esc(compactDate(account.lastSeenAt))}` : ""}</small></span><span><small>${account.journeys} journey${account.journeys === 1 ? "" : "s"}${account.failing ? ` · <b class="journey-status failing">${account.failing} failing</b>` : ""}${account.neverRun ? ` · ${account.neverRun} never run` : ""}<br>${account.testAccounts} test account${account.testAccounts === 1 ? "" : "s"} · ${account.tokens} token${account.tokens === 1 ? "" : "s"}</small></span><span class="journey-actions">${owner(account.email) ? "" : `<button class="quiet" type="button" data-plan-account="${esc(account.id)}" data-plan-kind="trial" data-plan-days="30">+30 days</button>${account.plan?.kind === "paid" ? "" : `<button class="quiet" type="button" data-plan-account="${esc(account.id)}" data-plan-kind="paid">Mark paid</button>`}`}</span></div>`).join("") : '<div class="empty">Nobody has signed in yet.</div>'}
350
363
  </section>
351
364
 
352
365
  <section class="panel section">
@@ -620,6 +633,24 @@ function journeyStatus(status) {
620
633
  return `<span class="journey-status ${status.passed ? "passing" : "failing"}">${status.passed ? "passing" : "failing"} · ${esc(compactDate(status.at))}</span>`;
621
634
  }
622
635
 
636
+ // The link from this machine to an account on a hosted Studio (ADR-0011 §4). Local only.
637
+ function renderStudioLink() {
638
+ const panel = $("#link-panel");
639
+ const body = $("#link-body");
640
+ if (!panel || !body) return;
641
+ const local = state.session?.mode === "local";
642
+ panel.classList.toggle("hidden", !local);
643
+ if (!local) return;
644
+ const link = state.session?.studioLink;
645
+ body.innerHTML = link
646
+ ? `<div class="link-state"><span class="journey-status passing">connected</span><span>${esc(link.email || "")} · <small>${esc(link.origin)}</small></span><button class="quiet" type="button" data-unlink-studio>Disconnect</button></div>`
647
+ : `<form class="link-form" id="link-form" autocomplete="off">
648
+ <input id="link-origin" name="origin" type="url" value="https://app.runtapp.com" aria-label="Studio URL" spellcheck="false">
649
+ <input id="link-token" name="token" type="password" placeholder="tapp_… — a token from your Studio, under “Your coding agent”" aria-label="Token" autocomplete="off" required>
650
+ <div class="ask-actions"><button class="primary" type="submit" id="link-connect">Connect</button><small>The token is kept on this machine only, readable by you.</small></div>
651
+ </form>`;
652
+ }
653
+
623
654
  function renderJourneys() {
624
655
  const node = $("#journeys-list");
625
656
  if (!node) return;
@@ -634,7 +665,9 @@ function renderJourneys() {
634
665
  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; }
635
666
  const groups = new Map();
636
667
  for (const journey of journeys) { const key = journey.group || ""; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(journey); }
637
- 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>`;
668
+ // A reported journey ran on the owner's own machine: it is listed with where, and cannot be
669
+ // run from here — the cloud has no flow for it, only the result (ADR-0011 §4).
670
+ 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)}${j.source === "reported" ? ` · runs on ${esc(j.machine || "your machine")}` : ""}</small></span><span></span><span class="journey-actions">${j.source === "reported" ? "" : `<button class="quiet" data-run-journey="${esc(j.slug)}" title="Replay this journey">▶ Run</button>`}${j.source === "kept" || j.source === "reported" ? `<button class="quiet" data-forget-journey="${esc(j.slug)}" title="Forget this journey">Forget</button>` : ""}</span></div>`;
638
671
  node.innerHTML = [...groups.entries()].sort(([a], [b]) => (a === "" ? -1 : b === "" ? 1 : a.localeCompare(b))).map(([group, items]) =>
639
672
  group === ""
640
673
  ? items.map(row).join("")
@@ -1295,7 +1328,7 @@ function setHeading(title, summary, { owned = false } = {}) {
1295
1328
  // simulator build, a repository that needs a toolchain. The engine answers with where they do
1296
1329
  // run; show that answer where it stays put, not in a toast that disappears in six seconds.
1297
1330
  function answerSelfHost(answer) {
1298
- setHeading("Run this on your machine", "The cloud Studio audits websites; this target needs your toolchain.", { owned: true });
1331
+ setHeading("Run this on your machine", "The cloud Studio runs public websites; this target runs on your own machine, with the same Studio.", { owned: true });
1299
1332
  document.querySelector(".summary-panel")?.classList.add("hidden");
1300
1333
  document.querySelector(".device-stage")?.classList.add("hidden");
1301
1334
  state.transcript = [];
@@ -1385,6 +1418,20 @@ document.addEventListener("click", (event) => {
1385
1418
  if (runButton) { state.selectedRunId = runButton.dataset.runId; renderRuns(); }
1386
1419
  const suggestion = event.target.closest("[data-prompt]");
1387
1420
  if (suggestion) { const input = $("#prompt-input"); input.value = suggestion.dataset.prompt; input.focus(); input.select(); }
1421
+ if (event.target.closest("[data-unlink-studio]")) {
1422
+ api("/api/studio-link", { method:"DELETE" }).then(async () => { toast("Disconnected."); await refreshSession(); }).catch((error) => toast(error.message, true));
1423
+ }
1424
+ const planButton = event.target.closest("[data-plan-account]");
1425
+ if (planButton) {
1426
+ const { planAccount, planKind, planDays } = planButton.dataset;
1427
+ api("/api/admin/plan", { method:"POST", body: JSON.stringify({ accountId: planAccount, kind: planKind, days: planDays ? Number(planDays) : undefined }) })
1428
+ .then(async () => { toast(planKind === "paid" ? "Marked paid." : `Trial set to ${planDays} days from today.`); await loadAdmin(); renderAdmin(); })
1429
+ .catch((error) => toast(error.message, true));
1430
+ }
1431
+ if (event.target.closest("#selfhost-copy")) {
1432
+ const text = $("#selfhost-command")?.textContent || "";
1433
+ navigator.clipboard?.writeText(text).then(() => toast("Copied. Run it in a terminal on your machine."), () => toast("Select the command and copy it.", true));
1434
+ }
1388
1435
  const liveControl = event.target.closest("[data-live-control]");
1389
1436
  if (liveControl) {
1390
1437
  const target = liveControl.dataset.liveTarget;
@@ -1394,6 +1441,20 @@ document.addEventListener("click", (event) => {
1394
1441
  }
1395
1442
  });
1396
1443
 
1444
+ document.addEventListener("submit", async (event) => {
1445
+ const form = event.target.closest("#link-form");
1446
+ if (!form) return;
1447
+ event.preventDefault();
1448
+ const button = $("#link-connect");
1449
+ if (button) button.disabled = true;
1450
+ try {
1451
+ await api("/api/studio-link", { method:"POST", body: JSON.stringify({ origin: $("#link-origin")?.value || "", token: $("#link-token")?.value || "" }) });
1452
+ toast("Connected. Journeys run here will report to your account.");
1453
+ await refreshSession();
1454
+ } catch (error) { toast(error.message, true); }
1455
+ finally { if (button) button.disabled = false; }
1456
+ });
1457
+
1397
1458
  document.addEventListener("change", (event) => {
1398
1459
  const picker = event.target.closest("#findings-run, #coverage-run");
1399
1460
  if (picker) { state.selectedRunId = picker.value; renderRuns(); }
@@ -65,10 +65,18 @@
65
65
  <li><button type="button" data-kind="github" data-prompt="owner/repo"><span>🐙</span><b>owner/repo</b><small>clone from GitHub into an isolated workspace, then the same</small></button></li>
66
66
  <li><button type="button" data-kind="build" data-prompt="com.company.app"><span>📱</span><b>com.company.app</b><small>explore a build already on the booted simulator (or give a .app / .apk)</small></button></li>
67
67
  </ul>
68
+ <!-- The front door (ADR-0011): on a hosted Studio, everything a website is not runs on the
69
+ person's own machine, and the page says so — with the command — before anyone types
70
+ one. Hidden on a local Studio, which is that machine. -->
71
+ <section class="selfhost-card hidden" id="selfhost-card">
72
+ <p class="selfhost-lead"><strong>Everything else runs on your own machine.</strong> Your repositories, iOS and Android builds, macOS apps, staging and localhost — the same Studio, on your Mac or PC, and nothing leaves it.</p>
73
+ <div class="selfhost-row"><code id="selfhost-command">npx -y @aarwitz/tapp@latest app</code><button class="quiet" type="button" id="selfhost-copy">Copy</button></div>
74
+ <small>Needs Node.js 20 or newer. It opens this same Studio in your browser, on your machine — no account needed.</small>
75
+ </section>
68
76
  <!-- Signing in to a public Studio: an email address and a link, nothing else. Hidden on a
69
77
  local Studio, where the one person at the keyboard is the operator already. -->
70
78
  <section class="signin-card hidden" id="signin-card" aria-live="polite">
71
- <p class="signin-lead"><strong>Sign in to go inside a site.</strong> tapp can stop at a sign-in and ask you for a test account, then remember it — for that it needs to know it is you.</p>
79
+ <p class="signin-lead"><strong>Sign in to go inside a site from here.</strong> tapp can stop at a sign-in and ask you for a test account, then remember it — for that it needs to know it is you. The cloud is free for 14 days, no card; your own machine is never gated.</p>
72
80
  <div id="signin-providers"></div>
73
81
  <form id="signin-form" autocomplete="email">
74
82
  <div class="signin-row"><input id="signin-email" name="email" type="email" placeholder="you@company.com" required><button class="primary" type="submit" id="signin-send">Email me a link</button></div>
@@ -219,6 +227,14 @@
219
227
  </div>
220
228
  <div id="token-list"><div class="empty">No tokens yet.</div></div>
221
229
  </section>
230
+ <!-- Results flow up, the browser never reaches down (ADR-0011 §4): a self-hosted Studio
231
+ reports journeys run here to an account on app.runtapp.com. Local only. -->
232
+ <section class="panel section hidden" id="link-panel">
233
+ <div class="section-heading compact">
234
+ <div><p class="eyebrow">Your tapp account</p><h2>Report what runs here to your account</h2><p id="link-note">Journeys you run on this machine — including against staging and localhost — show up on your account with how their last run went. Nothing else leaves this machine: not the journey, not a credential, not a screenshot.</p></div>
235
+ </div>
236
+ <div id="link-body"></div>
237
+ </section>
222
238
  <section class="panel section" id="journeys-panel">
223
239
  <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>
224
240
  <div id="journeys-list"><div class="empty">No journeys yet.</div></div>
@@ -1,8 +1,9 @@
1
1
  # Browser Studio
2
2
 
3
- Status: current product contract as of 2026-11-15 (ADR-0006, owner decision, amended twice:
4
- 2026-10-19, and TM-794 on 2026-11-15 bringing Findings and Coverage back). Supersedes
5
- the "desktop-parity Command Center" framing of 2026-10-14.
3
+ Status: current product contract as of 2026-11-20 (ADR-0006, owner decision, amended three
4
+ times: 2026-10-19; TM-794 on 2026-11-15 bringing Findings and Coverage back; and ADR-0011 on
5
+ 2026-11-20 making the hosted first page the front door). Supersedes the "desktop-parity Command
6
+ Center" framing of 2026-10-14.
6
7
 
7
8
  The Studio in `browser/` is the one browser surface. It is a **run viewer**: point Tapp at a
8
9
  repository target or a website, watch the run live, open its evidence. It never scores or judges
@@ -39,6 +40,13 @@ looping animation of a device being driven (launch, tap, tap, screenshot, ✓).
39
40
  The server classifies the input again (`classifyPrompt` in `browser/view-model.js` is shared) and
40
41
  refuses what the mode cannot do: a hosted Studio cannot open a path or a build on your machine.
41
42
 
43
+ **On a hosted Studio the page is the front door (ADR-0011).** The box takes a public website. A
44
+ self-host card under it names everything else — repositories, iOS and Android builds, macOS apps,
45
+ staging and localhost — with the command that opens this same Studio on the person's machine, and
46
+ the examples the deployment cannot start are not offered. Typing one anyway still gets the
47
+ structured `self-host` answer in the chat (ADR-0010). The platform chips are the same in both
48
+ modes; on a laptop most of them say "ready".
49
+
42
50
  ## What is on the page
43
51
 
44
52
  | View | What it shows | Operations |
@@ -101,6 +109,31 @@ an allowlist in `browser-product.js` (`anonymousAllows`, `accountAllows`):
101
109
  | Evidence | Captures stamped with their visitor cookie | Captures stamped `acct:<id>` | All captures on the machine |
102
110
  | Test accounts | None — a visitor is never asked | Encrypted, per account: `TAPP_HOME/accounts/actors/<id>/` | `TAPP_HOME/actors/` |
103
111
 
112
+ **The cloud beyond the visitor audit is for an account on a plan or in its free trial (ADR-0011
113
+ §3).** A new account starts a 14-day trial (`plan` on the account record; `account-store.js`
114
+ `entitlement`); an account from before plans existed gets its trial from the day it is next seen.
115
+ Starting a cloud run — `POST /api/operations/explore`, `/api/operations/run-flow`,
116
+ `/api/journeys`, `/api/captures/<id>/keep` — answers **402** with the reason once the trial has
117
+ lapsed, and the daily checks skip that account's journeys; reading what the account owns stays
118
+ open, so it can still see and forget its journeys, test accounts and tokens. The deployment's
119
+ owner (`TAPP_ADMIN_EMAILS`) is never gated and marks an account paid or extends its trial from the
120
+ Admin view (`POST /api/admin/plan`). There is no payment step yet: "paid" is the owner's word.
121
+ Nothing a local Studio does needs an account.
122
+
123
+ **A self-hosted Studio can report to an account (ADR-0011 §4).** Results flow up; the browser
124
+ never reaches down. Under *Your tapp account* on a local Studio, the owner pastes a token created
125
+ on the hosted one (under *Your coding agent*); the local Studio checks it against that Studio,
126
+ records whose it is, and keeps it in `TAPP_HOME/studio-link.json` (0600, this user only). From
127
+ then on every journey run on this machine — including against staging and localhost — posts its
128
+ name, platform, step count, machine name and result to `POST /api/journeys/report`; the journey
129
+ itself, credentials and screenshots never leave. The account's Journeys list shows it with "runs
130
+ on <machine>", no Run button (the cloud has no flow for it), and Forget; a pass↔fail change between
131
+ reports delivers the same alert a cloud check's would; the daily checks never pick it up. A Studio
132
+ that cannot be reached is said in the chat and never fails the run. `tapp run` on this machine
133
+ reports the same way — so an iOS or Android journey run from a terminal shows on the account too —
134
+ using the machine's link, or `TAPP_STUDIO` + `TAPP_TOKEN` when set; `--no-report` keeps one run to
135
+ itself.
136
+
104
137
  **Signing in** is `POST /api/auth/link` with an email, then `GET /auth/<token>` from the email.
105
138
  There is no password. Links work once and expire in 15 minutes; sessions last 90 days; only the
106
139
  SHA-256 of either token is on disk (`account-store.js`). One address may ask for five links per
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // Layout: TAPP_HOME/accounts/
12
12
  // by-email/<sha256(email)> → account id
13
- // accounts/<id>.json { id, email, createdAt, lastSeenAt }
13
+ // accounts/<id>.json { id, email, createdAt, lastSeenAt, plan }
14
14
  // links/<sha256(token)>.json { email, expiresAt } (removed on use)
15
15
  // sessions/<sha256(token)>.json { accountId, createdAt, expiresAt }
16
16
  // tokens/<sha256(token)>.json { id, accountId, label, createdAt, lastUsedAt }
@@ -25,6 +25,10 @@ import path from "node:path";
25
25
  export const TOKEN_PREFIX = "tapp_";
26
26
  export const LINK_TTL_MS = 15 * 60 * 1000;
27
27
  export const SESSION_TTL_MS = 90 * 24 * 60 * 60 * 1000;
28
+ // The cloud beyond the visitor audit is for an account on a plan or in its free trial
29
+ // (ADR-0011 §3). A trial is a date, nothing more: no card, no counter of runs.
30
+ export const TRIAL_DAYS = 14;
31
+ export const TRIAL_MS = TRIAL_DAYS * 24 * 60 * 60 * 1000;
28
32
  // One address may ask for this many links in a ten-minute window; more is someone else's mailbox
29
33
  // being flooded through us.
30
34
  const LINKS_PER_WINDOW = 5;
@@ -171,6 +175,46 @@ export class AccountStore {
171
175
  return false;
172
176
  }
173
177
 
178
+ /** The account record by id, or null. */
179
+ getAccount(accountId) {
180
+ if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) return null;
181
+ return readJson(this.#file("accounts", accountId));
182
+ }
183
+
184
+ /**
185
+ * Whether this account may start a cloud run, and why. `paid` has no end; `trial` has one and
186
+ * is allowed until it; `lapsed` is a trial whose date has passed. An account from before plans
187
+ * existed has none on record — it is given a trial from the day it is next seen, not from the
188
+ * day it joined, so a change in the rules never locks out someone who was already here.
189
+ */
190
+ entitlement(accountOrId) {
191
+ const account = typeof accountOrId === "string" ? this.getAccount(accountOrId) : accountOrId;
192
+ if (!account) return { kind: "lapsed", allowed: false, endsAt: null, daysLeft: 0 };
193
+ if (!account.plan || typeof account.plan !== "object") {
194
+ account.plan = { kind: "trial", endsAt: new Date(this.now() + TRIAL_MS).toISOString() };
195
+ writeJson(this.#file("accounts", account.id), account);
196
+ }
197
+ if (account.plan.kind === "paid") return { kind: "paid", allowed: true, endsAt: null, daysLeft: null };
198
+ const endsAt = Date.parse(account.plan.endsAt);
199
+ const left = Number.isFinite(endsAt) ? endsAt - this.now() : -1;
200
+ if (left <= 0) return { kind: "lapsed", allowed: false, endsAt: account.plan.endsAt || null, daysLeft: 0 };
201
+ return { kind: "trial", allowed: true, endsAt: account.plan.endsAt, daysLeft: Math.ceil(left / 86_400_000) };
202
+ }
203
+
204
+ /** The owner of the deployment decides: mark an account paid, or give it a trial of so many days from now. */
205
+ setPlan(accountId, { kind, days } = {}) {
206
+ const account = this.getAccount(accountId);
207
+ if (!account) throw Object.assign(new Error("No such account"), { statusCode: 404 });
208
+ if (kind === "paid") account.plan = { kind: "paid" };
209
+ else if (kind === "trial") {
210
+ const length = Number(days);
211
+ if (!Number.isInteger(length) || length < 1 || length > 365) throw Object.assign(new Error("A trial is 1 to 365 days"), { statusCode: 400 });
212
+ account.plan = { kind: "trial", endsAt: new Date(this.now() + length * 86_400_000).toISOString() };
213
+ } else throw Object.assign(new Error("A plan is 'paid' or 'trial'"), { statusCode: 400 });
214
+ writeJson(this.#file("accounts", account.id), account);
215
+ return this.entitlement(account);
216
+ }
217
+
174
218
  /** Where this account's encrypted test accounts live. */
175
219
  actorRoot(accountId) {
176
220
  if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) throw new Error("Not an account id");
@@ -186,7 +230,7 @@ export class AccountStore {
186
230
  if (existing) return existing;
187
231
  }
188
232
  id = crypto.randomBytes(12).toString("hex");
189
- const account = { id, email, createdAt: new Date(this.now()).toISOString(), lastSeenAt: new Date(this.now()).toISOString() };
233
+ const account = { id, email, createdAt: new Date(this.now()).toISOString(), lastSeenAt: new Date(this.now()).toISOString(), plan: { kind: "trial", endsAt: new Date(this.now() + TRIAL_MS).toISOString() } };
190
234
  writeJson(this.#file("accounts", id), account);
191
235
  fs.mkdirSync(path.dirname(indexFile), { recursive: true, mode: 0o700 });
192
236
  fs.writeFileSync(indexFile, `${id}\n`, { mode: 0o600 });
@@ -107,6 +107,11 @@ export async function runAndroidFlow({ flow, appId, apkPath, serial, logPath, sc
107
107
  await d.swipe(target || "up");
108
108
  } else if (action === "back") {
109
109
  await d.back();
110
+ } else if (action === "open_url") {
111
+ // A journey starting from an email link ("tap the sign-in link in your receipt") opens it
112
+ // the way Android itself would hand it to the app — a VIEW intent, not a shell workaround.
113
+ const r = await d.adb(["shell", "am", "start", "-a", "android.intent.action.VIEW", "-d", target]);
114
+ if (r.code !== 0 || /Error:/i.test(r.stdout || "")) throw new Error(`could not open ‘${target}’: ${(r.stdout || r.stderr || "").trim() || "no app handled this link"}`);
110
115
  } else if (action === "wait_for") {
111
116
  const waited = await d.waitFor(target, timeout);
112
117
  if (!waited) throw new Error(`‘${target}’ never appeared within ${timeout}ms`);
@@ -170,14 +170,32 @@ function accountAllows(method, pathname) {
170
170
  if (method === "POST" && (pathname === "/api/alerts" || pathname === "/api/alerts/test")) return true;
171
171
  // Personal access tokens: the owner's coding agent acting as them (ADR-0009 slice 4).
172
172
  if (method === "POST" && pathname === "/api/tokens") return true;
173
+ // The deployment's owner marks an account paid or extends its trial; the handler checks who.
174
+ if (method === "POST" && pathname === "/api/admin/plan") return true;
173
175
  if (method === "DELETE" && /^\/api\/tokens\/[a-f0-9]{12}$/.test(pathname)) return true;
174
176
  if (method === "DELETE" && /^\/api\/actors\/[A-Za-z0-9.:-]{1,253}\/[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(pathname)) return true;
175
177
  // Journeys: keep a proven run, replay it, forget it (ADR-0009 slice 3).
176
178
  if (method === "POST" && (/^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/keep$/.test(pathname) || pathname === "/api/operations/run-flow" || pathname === "/api/journeys")) return true;
179
+ // A journey run on the owner's own machine reports how it went (ADR-0011 §4).
180
+ if (method === "POST" && pathname === "/api/journeys/report") return true;
177
181
  if (method === "DELETE" && /^\/api\/journeys\/[a-z0-9-]{1,60}$/.test(pathname)) return true;
178
182
  return false;
179
183
  }
180
184
 
185
+ // Starting a cloud run — going inside a site, keeping or replaying a journey, importing one —
186
+ // is what a plan or a free trial buys (ADR-0011 §3). Reading what you own is not gated, so a
187
+ // lapsed trial can still see its journeys, test accounts and tokens, and forget them.
188
+ function cloudRunRoute(method, pathname) {
189
+ if (method !== "POST") return false;
190
+ return pathname === "/api/operations/explore" || pathname === "/api/operations/run-flow" || pathname === "/api/journeys"
191
+ || /^\/api\/captures\/[A-Za-z0-9._-]{1,128}\/keep$/.test(pathname);
192
+ }
193
+
194
+ function trialEndedMessage(plan) {
195
+ const when = plan?.endsAt ? ` on ${String(plan.endsAt).slice(0, 10)}` : "";
196
+ return `Your free trial ended${when}. Cloud runs — going inside a site, kept journeys and daily checks — are for accounts on a plan. Write to hello@runtapp.com, or run everything on your own machine, where nothing is gated: npx -y @aarwitz/tapp@latest app`;
197
+ }
198
+
181
199
  // One visitor may start a bounded number of audits per hour. Each audit drives a real browser
182
200
  // over as many as 20 pages, so this is about the machine, not about abuse alone.
183
201
  const AUDIT_LIMIT_PER_HOUR = 10;
@@ -358,7 +376,32 @@ async function replayJourney({ store, slug, flow, actorRoot = "", ownerKey = nul
358
376
  // due when its last result is older than the interval (TAPP_JOURNEY_CHECK_HOURS, default 24);
359
377
  // a restart therefore does not re-run everything, and a busy lane simply waits for the next tick.
360
378
  export function dueJourneys(journeys, { intervalMs, now = Date.now() }) {
361
- return journeys.filter((j) => (j.platform || "web") === "web" && (!j.status || now - Date.parse(j.status.at || 0) >= intervalMs));
379
+ // A reported journey runs on somebody's own machine; the cloud has no flow to replay.
380
+ return journeys.filter((j) => j.source !== "reported" && (j.platform || "web") === "web" && (!j.status || now - Date.parse(j.status.at || 0) >= intervalMs));
381
+ }
382
+
383
+ // ADR-0011 §4: results flow up, the browser never reaches down. A self-hosted Studio can be
384
+ // linked to an account on a hosted one with a token the owner created there; from then on a
385
+ // journey run here reports its name and result to that account. The link lives beside the
386
+ // machine's other state, readable by this user only. Never on a hosted Studio: its account IS
387
+ // the account.
388
+ function studioLinkPath() {
389
+ return path.join(process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), "studio-link.json");
390
+ }
391
+ function readStudioLink() {
392
+ try {
393
+ const link = JSON.parse(fs.readFileSync(studioLinkPath(), "utf8"));
394
+ return link && typeof link.origin === "string" && typeof link.token === "string" ? link : null;
395
+ } catch { return null; }
396
+ }
397
+ function writeStudioLink(link) {
398
+ const file = studioLinkPath();
399
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
400
+ fs.writeFileSync(file, JSON.stringify(link), { mode: 0o600 });
401
+ }
402
+ function studioLinkSummary() {
403
+ const link = readStudioLink();
404
+ return link ? { origin: link.origin, email: link.email || "", linkedAt: link.linkedAt || null } : null;
362
405
  }
363
406
 
364
407
  function openBrowser(url) {
@@ -733,6 +776,10 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
733
776
  for (const accountId of owners) {
734
777
  const store = JourneyStore.forAccount(accountId);
735
778
  const ownerKey = `acct:${accountId}`;
779
+ // A daily check is a cloud run: a lapsed trial's journeys keep their last result and are
780
+ // not re-run until the account is on a plan again (ADR-0011 §3).
781
+ const record = accounts.getAccount(accountId);
782
+ if (record && !isAdmin(record) && !accounts.entitlement(record).allowed) continue;
736
783
  for (const journey of dueJourneys(store.list(), { intervalMs: checkIntervalMs })) {
737
784
  const flowPath = store.flowPath(journey.slug);
738
785
  let flow;
@@ -804,6 +851,16 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
804
851
  json(response, 401, { error: "That part of the Studio runs on your own machine: npx -y @aarwitz/tapp@latest app" });
805
852
  return;
806
853
  }
854
+ // The cloud beyond the visitor audit is for an account on a plan or in its free trial
855
+ // (ADR-0011 §3). The deployment's owner is never gated on their own machine.
856
+ if (account && !isAdmin(account) && cloudRunRoute(request.method, url.pathname)) {
857
+ const plan = accounts.entitlement(account);
858
+ if (!plan.allowed) {
859
+ logUsage("refused", { account: account.id.slice(0, 8), reason: "trial-ended", method: request.method, path: url.pathname, status: 402 });
860
+ json(response, 402, { error: trialEndedMessage(plan), plan });
861
+ return;
862
+ }
863
+ }
807
864
  if (publicAccess && !authenticated && !account) {
808
865
  anonymous = true;
809
866
  visitorId = String(cookies(request)[VISITOR_COOKIE] || "");
@@ -1037,6 +1094,57 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1037
1094
  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 });
1038
1095
  return;
1039
1096
  }
1097
+ // A journey that ran on the owner's own machine says how it went (ADR-0011 §4). The name
1098
+ // and the result are kept under the account; nothing else is accepted, and a change
1099
+ // between runs is announced the way a cloud check's would be.
1100
+ if (account && request.method === "POST" && url.pathname === "/api/journeys/report") {
1101
+ guardMutation(request);
1102
+ const body = await readJsonBody(request);
1103
+ const name = String(body.name || "").replace(/[\u0000-\u001f]/g, "").trim().slice(0, 120);
1104
+ if (!name) throw Object.assign(new Error("A report names the journey"), { statusCode: 400 });
1105
+ const platform = ["web", "ios", "android", "macos"].includes(body.platform) ? body.platform : "web";
1106
+ const machine = String(body.machine || "").replace(/[\u0000-\u001f]/g, "").trim().slice(0, 64);
1107
+ const count = (value) => Math.max(0, Math.min(10_000, Number.isFinite(Number(value)) ? Math.trunc(Number(value)) : 0));
1108
+ const at = Number.isFinite(Date.parse(body.at)) ? new Date(Date.parse(body.at)).toISOString() : null;
1109
+ const store = JourneyStore.forAccount(account.id);
1110
+ const previous = store.reported(slugify(name))?.status || null;
1111
+ const record = store.report({ name, platform, url: String(body.url || "").slice(0, 2048), steps: count(body.steps), machine, passed: body.passed === true, executed: count(body.executed), total: count(body.total), failed: count(body.failed), at });
1112
+ const change = alertForChange({ previous, current: record.status });
1113
+ if (change) {
1114
+ const alerts = AlertStore.forAccount(accounts.root, account.id);
1115
+ const settings = alerts.read();
1116
+ if (settings.webhook) {
1117
+ const alert = await deliverAlert({ webhook: settings.webhook, message: alertMessage({ kind: change, journey: `${name}${machine ? ` (on ${machine})` : ""}`, status: record.status, origin: publicOrigins[0] || "" }) });
1118
+ alerts.write({ lastDelivery: { at: new Date().toISOString(), journey: name, change, ...alert } });
1119
+ }
1120
+ }
1121
+ logUsage("journey.reported", { account: account.id.slice(0, 8), passed: record.status.passed, platform, change: change || null });
1122
+ json(response, 200, { ok: true, slug: record.slug, status: record.status, change: change || null });
1123
+ return;
1124
+ }
1125
+ // Linking this machine to an account on a hosted Studio (ADR-0011 §4). Operator only, and
1126
+ // only on a self-hosted Studio: a hosted one has nothing to link to but itself.
1127
+ if (!hosted && authenticated && url.pathname === "/api/studio-link") {
1128
+ if (request.method === "GET") { json(response, 200, { link: studioLinkSummary() }); return; }
1129
+ guardMutation(request);
1130
+ if (request.method === "DELETE") { try { fs.rmSync(studioLinkPath(), { force: true }); } catch { /* gone */ } json(response, 200, { ok: true, link: null }); return; }
1131
+ if (request.method === "POST") {
1132
+ const body = await readJsonBody(request);
1133
+ const { studioConfig, verifyStudioToken } = await import("./studio-client.js");
1134
+ let config;
1135
+ try { config = studioConfig({ studio: String(body.origin || "https://app.runtapp.com"), token: String(body.token || "") }, {}); }
1136
+ catch (error) { json(response, 400, { error: error.message }); return; }
1137
+ if (!config) { json(response, 400, { error: "A Studio URL is needed" }); return; }
1138
+ let who;
1139
+ try { who = await verifyStudioToken(config); }
1140
+ catch (error) { json(response, 400, { error: error.message }); return; }
1141
+ const link = { origin: config.origin, token: config.token, email: who.email, linkedAt: new Date().toISOString() };
1142
+ writeStudioLink(link);
1143
+ logUsage("studio.linked", { origin: config.origin });
1144
+ json(response, 200, { ok: true, link: studioLinkSummary() });
1145
+ return;
1146
+ }
1147
+ }
1040
1148
  if (!anonymous && request.method === "GET" && url.pathname === "/api/journeys") {
1041
1149
  const store = journeyStore();
1042
1150
  const root = !account ? registry.currentRoot() : null;
@@ -1109,6 +1217,17 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1109
1217
  // What the owner of this deployment can see: how it is being used, who has an account, and
1110
1218
  // which journeys are failing. Never a credential — they are encrypted and never decrypted
1111
1219
  // for display — and never anyone's evidence.
1220
+ // The owner decides who is on a plan: mark an account paid, or give it a trial of so many
1221
+ // days from today. Anyone else asking gets 403, not a hint of who has an account.
1222
+ if (account && request.method === "POST" && url.pathname === "/api/admin/plan") {
1223
+ if (!isAdmin(account)) { json(response, 403, { error: "Only the owner of this deployment can do that" }); return; }
1224
+ guardMutation(request);
1225
+ const body = await readJsonBody(request);
1226
+ const plan = accounts.setPlan(String(body.accountId || ""), { kind: String(body.kind || ""), days: body.days });
1227
+ logUsage("plan.set", { account: String(body.accountId || "").slice(0, 8), kind: plan.kind, by: account.id.slice(0, 8) });
1228
+ json(response, 200, { ok: true, plan });
1229
+ return;
1230
+ }
1112
1231
  if (account && isAdmin(account) && request.method === "GET" && url.pathname === "/api/admin/overview") {
1113
1232
  const accountsRoot = accounts.root;
1114
1233
  const listAccounts = () => {
@@ -1127,7 +1246,8 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1127
1246
  }
1128
1247
  } catch { /* none yet */ }
1129
1248
  return {
1130
- email: record.email, createdAt: record.createdAt, lastSeenAt: record.lastSeenAt || null,
1249
+ id: record.id, email: record.email, createdAt: record.createdAt, lastSeenAt: record.lastSeenAt || null,
1250
+ plan: isAdmin(record) ? { kind: "owner", allowed: true, endsAt: null, daysLeft: null } : accounts.entitlement(record),
1131
1251
  journeys: journeys.length,
1132
1252
  failing: journeys.filter((j) => j.status && !j.status.passed).length,
1133
1253
  neverRun: journeys.filter((j) => !j.status).length,
@@ -1291,6 +1411,8 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1291
1411
  csrfToken, mode: "public", product: "Tapp", root: null, repository: null, repositories: [],
1292
1412
  contract: customerProductContract, supportedPlatforms: ["web"], runners: [],
1293
1413
  access: "account", email: account.email, signInProvider, signInOptions, viaToken, admin: isAdmin(account),
1414
+ // What the cloud will do for this account, and until when (ADR-0011 §3).
1415
+ plan: isAdmin(account) ? { kind: "owner", allowed: true, endsAt: null, daysLeft: null } : accounts.entitlement(account),
1294
1416
  accepts: ["url"],
1295
1417
  selfHostOnly: ["path", "github", "bundle", "app", "apk"],
1296
1418
  // What tapp drives, and what THIS machine can start. The Studio shows all of it:
@@ -1316,7 +1438,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1316
1438
  });
1317
1439
  return;
1318
1440
  }
1319
- json(response, 200, { csrfToken, mode: hosted ? "managed" : "local", product: "Tapp", root: hosted ? null : registry.currentRoot(), repository: hosted ? hostedRepository(registry.current()) : registry.current(), repositories: hosted ? registry.list().map(hostedRepository) : registry.list(), contract: customerProductContract, supportedPlatforms: customerProductContract.targetPlatforms, runners: runnerSummary({ hosted }), platforms: platformStates({ hosted }) });
1441
+ json(response, 200, { csrfToken, mode: hosted ? "managed" : "local", product: "Tapp", root: hosted ? null : registry.currentRoot(), repository: hosted ? hostedRepository(registry.current()) : registry.current(), repositories: hosted ? registry.list().map(hostedRepository) : registry.list(), contract: customerProductContract, supportedPlatforms: customerProductContract.targetPlatforms, runners: runnerSummary({ hosted }), platforms: platformStates({ hosted }), studioLink: hosted ? null : studioLinkSummary() });
1320
1442
  return;
1321
1443
  }
1322
1444
  if (request.method === "GET" && url.pathname === "/api/repositories") { json(response, 200, hosted ? { current:hostedRepository(registry.current()), repositories:registry.list().map(hostedRepository) } : { current: registry.current(), repositories: registry.list() }); return; }
@@ -1572,6 +1694,17 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1572
1694
  const job = startJob(operation, async (progress) => {
1573
1695
  const result = await replayJourney({ store, slug, flow, actorRoot: actorRootFor() || "", ownerKey, progress, alerts: account ? AlertStore.forAccount(accounts.root, account.id) : null, origin: publicOrigins[0] || "" });
1574
1696
  logUsage("journey.run", { owner: (ownerKey || "operator").slice(0, 13), passed: result.passed });
1697
+ // A run on this machine reports to the linked account: the name and how it went,
1698
+ // never the journey, a credential or a screenshot (ADR-0011 §4). Best effort — a
1699
+ // Studio that cannot be reached is said in the chat and never fails the run.
1700
+ const link = !hosted && !account ? readStudioLink() : null;
1701
+ if (link) {
1702
+ try {
1703
+ const { reportStudioJourney } = await import("./studio-client.js");
1704
+ await reportStudioJourney({ origin: link.origin, token: link.token }, { name: flow.name || slug, platform, url: flow.url || "", steps: (flow.steps || []).length, machine: os.hostname(), passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, at: result.status?.at || null });
1705
+ progress({ phase: "replay", text: `Reported to ${link.origin} as ${link.email || "your account"}` });
1706
+ } catch (error) { progress({ phase: "replay", text: `Could not report to ${link.origin}: ${error.message}` }); }
1707
+ }
1575
1708
  return result;
1576
1709
  }, null, { lane: ownerKey || OPERATOR_LANE });
1577
1710
  job.ownerKey = ownerKey;
@@ -49,6 +49,7 @@ export const FLOW_ACTIONS = Object.freeze([
49
49
  { action: "drag", target: "{from, by: [dx, dy]} or {from, to}", passes: "the control was dragged in steps, so listeners watching movement fire; web only — typing into a range input sets its value without the handle moving. This says the gesture was made, not that the page reacted: assert after it" },
50
50
  { action: "screenshot", target: "a name for the picture", passes: "a viewport-sized picture was saved beside the run's evidence; web only" },
51
51
  { action: "back", target: "(none)", passes: "the platform back navigation was performed" },
52
+ { action: "open_url", target: "a URL or deep link (myapp://claim?t=$TOKEN; $NAME substitutes like any other step)", passes: "the link was opened and the app under test came to the front (iOS/Android); on web, the page navigated there. Not supported on macOS" },
52
53
  { action: "wait", target: "milliseconds (fixed pause; prefer wait_for)", passes: "always" },
53
54
  { action: "wait_for", target: "label / text (+ per-step timeoutMs/timeout; flow-level timeoutMs sets the default)", passes: "the element appeared before the timeout" },
54
55
  { action: "assert_screen", target: "the detected SCREEN TITLE (navigation bar / heading), not arbitrary text", passes: "the current screen's title equals the target" },
@@ -103,7 +104,7 @@ export function validateFlowSteps(flow, platform = inferFlowPlatform(flow)) {
103
104
  if (step.action === "tap" && /^\s*-?\d+(\.\d+)?\s*,\s*-?\d+(\.\d+)?\s*$/.test(step.target)) {
104
105
  errors.push(`step ${n}: tap target '${step.target.trim()}' is a coordinate; Flow taps are label-only on ${platform} (use tapp_session_act tap {x,y} to learn the label, then record it)`);
105
106
  }
106
- if (["tap", "wait_for", "assert_screen", "assert_exists", "assert_absent"].includes(step.action) && !step.target.trim()) {
107
+ if (["tap", "wait_for", "assert_screen", "assert_exists", "assert_absent", "open_url"].includes(step.action) && !step.target.trim()) {
107
108
  errors.push(`step ${n}: ${step.action} needs a target`);
108
109
  }
109
110
  if (step.action === "type" && (!step.target.trim() || !("value" in (step.params || {})))) {