@aarwitz/tapp 0.30.1 → 0.32.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.30.1",
4
+ "version": "0.32.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.30.1",
27
+ "@aarwitz/tapp@0.32.0",
28
28
  "mcp"
29
29
  ],
30
30
  "cwd": "${CLAUDE_PROJECT_DIR}"
package/browser/app.js CHANGED
@@ -174,6 +174,7 @@ function applyAccessMode() {
174
174
  $("#actors-panel")?.classList.toggle("hidden", !signedIn);
175
175
  $("#journeys-panel")?.classList.toggle("hidden", !signedIn);
176
176
  $("#agent-panel")?.classList.toggle("hidden", !signedIn);
177
+ $("#alerts-panel")?.classList.toggle("hidden", !signedIn);
177
178
  $("#admin-nav")?.classList.toggle("hidden", !state.session?.admin);
178
179
  }
179
180
 
@@ -227,25 +228,102 @@ function renderAdmin() {
227
228
  }), { journeys: 0, failing: 0 });
228
229
  const stat = (value, label, tone = "") => `<div class="${esc(tone)}"><strong>${esc(String(value))}</strong><small>${esc(label)}</small></div>`;
229
230
  const owner = (email) => (data.admins || []).includes(String(email).toLowerCase());
231
+ const activity = data.activity || { today: {}, week: {}, recent: [], people: [] };
232
+ const count = (bucket, ...names) => names.reduce((sum, name) => sum + (bucket[name] || 0), 0);
233
+
234
+ // The log says what happened; these are the few verbs worth counting.
235
+ const period = (bucket) => [
236
+ stat(count(bucket, "signin.done"), "sign-ins"),
237
+ stat(count(bucket, "audit.start"), "audits"),
238
+ stat(count(bucket, "explore.start"), "explorations"),
239
+ stat(count(bucket, "journey.kept"), "journeys kept"),
240
+ stat(count(bucket, "journey.run", "journey.checked"), "journey runs"),
241
+ stat(count(bucket, "visitor.new"), "new visitors"),
242
+ ].join("");
243
+
244
+ const whatHappened = (entry) => {
245
+ const host = entry.host ? ` · ${esc(entry.host)}` : "";
246
+ const map = {
247
+ "visitor.new": "arrived", "signin.done": `signed in${entry.provider ? ` with ${esc(entry.provider)}` : ""}`,
248
+ "signin.link": "asked for a sign-in link", "signin.oauth.refused": `sign-in refused (${esc(entry.reason || "")})`,
249
+ "signin.access.refused": "sign-in refused", "audit.start": "started a read-only audit", "audit.done": "finished an audit",
250
+ "explore.start": "went inside a site", "journey.kept": "kept a journey", "journey.run": "ran a journey",
251
+ "journey.checked": "daily check", "journey.imported": "added a journey", "token.issued": "created an agent token",
252
+ "refused": `refused: ${esc(entry.reason || "")}`, "scanned": "automated probes refused", "rollup": "hourly rollup",
253
+ };
254
+ const what = map[entry.event] || esc(entry.event);
255
+ const extra = entry.event === "audit.done" ? ` — ${esc(String(entry.findings ?? "?"))} finding(s) over ${esc(String(entry.pagesAudited ?? "?"))} page(s)`
256
+ : entry.event === "journey.run" || entry.event === "journey.checked" ? ` — ${entry.passed ? "passed" : "FAILED"}` : "";
257
+ return `${what}${host}${extra}`;
258
+ };
259
+
230
260
  node.innerHTML = `
231
261
  <section class="panel section">
232
- <div class="section-heading compact"><div><p class="eyebrow">Right now</p><h2>How tapp is being used</h2><p>Since this release started. A visitor is counted only when they ask for something the Studio offers — scanners are not people.</p></div></div>
233
- <div class="run-stats">
234
- ${stat(data.accounts.length, "accounts")}
235
- ${stat(totals.journeys, "journeys")}
236
- ${stat(totals.failing, "failing", totals.failing ? "bad" : "")}
237
- ${stat(data.usage.distinctVisitors, "visitors")}
238
- ${stat(data.usage.audits, "audits")}
239
- ${stat(data.runs.captures, "runs kept")}
240
- </div>
241
- <p class="muted">Release <code>${esc(data.release)}</code> · up since ${esc(compactDate(data.startedAt))} · sign-in via <b>${esc(data.signInProvider)}</b> · kept journeys re-checked every ${esc(String(data.journeyCheckHours))}h · ${esc(String(data.usage.refusals))} refused requests, mostly automated probes.</p>
262
+ <div class="section-heading compact"><div><p class="eyebrow">Last 24 hours</p><h2>What happened today</h2></div></div>
263
+ <div class="run-stats">${period(activity.today)}</div>
264
+ <div class="section-heading compact" style="margin-top:14px"><div><p class="eyebrow">Last 7 days</p><h2>And this week</h2></div></div>
265
+ <div class="run-stats">${period(activity.week)}</div>
266
+ <p class="muted">Release <code>${esc(data.release)}</code> · up since ${esc(compactDate(data.startedAt))} · sign-in via <b>${esc(data.signInProvider)}</b> · kept journeys re-checked every ${esc(String(data.journeyCheckHours))}h · ${esc(String(data.totalRuns))} runs on disk · ${esc(String(activity.logged))} logged events${activity.since ? ` since ${esc(compactDate(activity.since))}` : ""}.</p>
242
267
  </section>
268
+
243
269
  <section class="panel section">
244
- <div class="section-heading compact"><div><p class="eyebrow">People</p><h2>Accounts <i class="zero">${data.accounts.length}</i></h2><p>What each person has set up. Test accounts are counted, never shown — tapp cannot show them.</p></div></div>
270
+ <div class="section-heading compact"><div><p class="eyebrow">People</p><h2>Who has been here <i class="zero">${activity.people.length}</i></h2><p>Signed-in accounts, and anonymous visitors by the first eight characters of their cookie — enough to tell two people apart, not enough to be a handle. No IP addresses are kept.</p></div></div>
271
+ ${activity.people.length ? activity.people.map((p) => `<div class="actor-row"><span><strong>${p.kind === "account" ? "account" : "visitor"} ${esc(p.id.split(":")[1])}</strong><br><small>first seen ${esc(compactDate(p.first))} · last ${esc(compactDate(p.last))}</small></span><span><small>${esc(Object.entries(p.events).map(([k, v]) => `${k.replace(/\./g, " ")} ×${v}`).join(" · ").slice(0, 90) || "—")}</small></span><span><small>${esc(p.hosts.join(", ") || "—")}</small></span></div>`).join("") : '<div class="empty">Nobody yet. Activity is recorded from the release that introduced this log.</div>'}
272
+ </section>
273
+
274
+ <section class="panel section">
275
+ <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>
245
276
  ${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>'}
277
+ </section>
278
+
279
+ <section class="panel section">
280
+ <div class="section-heading compact"><div><p class="eyebrow">Runs</p><h2>Every run still on disk <i class="zero">${data.totalRuns}</i></h2><p>Newest first. Evidence belongs to whoever started the run; this is the ledger, not their screenshots.</p></div></div>
281
+ ${(data.recentRuns || []).length ? (data.recentRuns).map((run) => `<div class="actor-row"><span><strong>${esc(run.kind)}</strong> · ${esc(run.target || "—")}<br><small><code>${esc(run.id)}</code></small></span><span><small>${run.at ? esc(compactDate(run.at)) : "—"}</small></span><span><small>${esc(String(run.owner).slice(0, 20))}</small></span></div>`).join("") : '<div class="empty">No runs yet.</div>'}
282
+ </section>
283
+
284
+ <section class="panel section">
285
+ <div class="section-heading compact"><div><p class="eyebrow">Log</p><h2>Recent activity</h2><p>The last ${(activity.recent || []).length} things that happened, newest first.</p></div></div>
286
+ ${(activity.recent || []).length ? `<ul class="detail-list">${activity.recent.map((entry) => `<li><small>${esc(compactDate(entry.at))}</small> · ${entry.account ? `account ${esc(entry.account)}` : entry.visitor ? `visitor ${esc(entry.visitor)}` : "—"} · ${whatHappened(entry)}</li>`).join("")}</ul>` : '<div class="empty">Nothing logged yet on this release.</div>'}
246
287
  </section>`;
247
288
  }
248
289
 
290
+ // Being told, rather than having to look. The URL is write-only: once set, the Studio shows
291
+ // which host it points at and when it last delivered, never the URL — anyone holding it can post
292
+ // into that channel.
293
+ async function loadAlerts() {
294
+ if (state.session?.access !== "account") { state.alerts = null; return; }
295
+ state.alerts = await api("/api/alerts").catch(() => null);
296
+ }
297
+
298
+ function renderAlerts() {
299
+ const node = $("#alerts-body");
300
+ if (!node) return;
301
+ const alerts = state.alerts;
302
+ const delivery = alerts?.lastDelivery;
303
+ const last = delivery
304
+ ? `<p class="muted">Last post: ${esc(compactDate(delivery.at))} · ${esc(delivery.journey || "")} · ${delivery.delivered ? "delivered" : `not delivered — ${esc(delivery.reason || "")}`}</p>`
305
+ : "";
306
+ node.innerHTML = alerts?.configured
307
+ ? `<div class="actor-row"><span><strong>Posting to ${esc(alerts.host)}</strong><br><small>set ${esc(compactDate(alerts.updatedAt))}</small></span><span></span><span class="journey-actions"><button class="quiet" type="button" data-alert-test>Send a test</button><button class="quiet" type="button" data-alert-clear>Stop</button></span></div>${last}`
308
+ : `<form id="alerts-form" class="signin-row"><input id="alert-webhook" type="url" placeholder="https://hooks.slack.com/services/…" required><button class="primary" type="submit">Save</button></form><p class="muted">tapp posts a test message when you save, so you know it works before anything breaks.</p>${last}`;
309
+ }
310
+
311
+ async function saveAlerts(webhook) {
312
+ try {
313
+ state.alerts = await api("/api/alerts", { method: "POST", body: JSON.stringify({ webhook }) });
314
+ renderAlerts();
315
+ toast(webhook ? "Saved — check the channel for the test message." : "Stopped posting.");
316
+ } catch (error) { toast(error.message, true); }
317
+ }
318
+
319
+ async function testAlerts() {
320
+ try {
321
+ state.alerts = await api("/api/alerts/test", { method: "POST", body: "{}" });
322
+ renderAlerts();
323
+ toast("Posted. Check the channel.");
324
+ } catch (error) { toast(error.message, true); }
325
+ }
326
+
249
327
  async function loadTokens() {
250
328
  if (state.session?.access !== "account") { state.tokens = []; return; }
251
329
  state.tokens = (await api("/api/tokens").catch(() => ({ tokens: [] }))).tokens || [];
@@ -565,6 +643,7 @@ function renderObservations(audit) {
565
643
 
566
644
  function renderRuns() {
567
645
  renderAdmin();
646
+ renderAlerts();
568
647
  renderJourneys();
569
648
  renderActors();
570
649
  renderTokens();
@@ -849,7 +928,7 @@ async function refresh() {
849
928
  state.audits = runs.audits || [];
850
929
  state.explores = runs.explores || [];
851
930
  state.actors = actors.apps || [];
852
- await Promise.all([loadJourneys(), loadTokens(), loadAdmin()]);
931
+ await Promise.all([loadJourneys(), loadTokens(), loadAdmin(), loadAlerts()]);
853
932
  renderAdmin();
854
933
  renderProject();
855
934
  return;
@@ -1034,6 +1113,8 @@ document.addEventListener("submit", (event) => {
1034
1113
  if (prompt) { event.preventDefault(); startFromPrompt(prompt.elements.input.value).catch((error) => toast(error.message, true)); }
1035
1114
  const ask = event.target.closest("#chat-ask");
1036
1115
  if (ask) { event.preventDefault(); answerAsk(ask, "submit"); }
1116
+ const alertsForm = event.target.closest("#alerts-form");
1117
+ if (alertsForm) { event.preventDefault(); saveAlerts(alertsForm.elements.webhook?.value || $("#alert-webhook")?.value || ""); }
1037
1118
  const signin = event.target.closest("#signin-form");
1038
1119
  if (signin) { event.preventDefault(); requestSignInLink(signin.elements.email.value.trim()); }
1039
1120
  const keep = event.target.closest("#chat-keep");
@@ -1056,6 +1137,8 @@ document.addEventListener("click", (event) => {
1056
1137
  const forgetJ = event.target.closest("[data-forget-journey]");
1057
1138
  if (forgetJ) { event.preventDefault(); forgetJourney(forgetJ.dataset.forgetJourney).catch((error) => toast(error.message, true)); }
1058
1139
  if (event.target.closest("[data-open-owned]")) { event.preventDefault(); showProduct(); activateView("runs"); renderRuns(); }
1140
+ if (event.target.closest("[data-alert-test]")) { event.preventDefault(); testAlerts(); }
1141
+ if (event.target.closest("[data-alert-clear]")) { event.preventDefault(); saveAlerts(""); }
1059
1142
  if (event.target.closest("#create-token")) { event.preventDefault(); createToken(); }
1060
1143
  const revoke = event.target.closest("[data-revoke-token]");
1061
1144
  if (revoke) { event.preventDefault(); revokeToken(revoke.dataset.revokeToken).catch((error) => toast(error.message, true)); }
@@ -183,6 +183,10 @@
183
183
  <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>
184
184
  <div id="actors-list"><div class="empty">None yet. Explore a site with a sign-in and tapp will ask.</div></div>
185
185
  </section>
186
+ <section class="panel section hidden" id="alerts-panel">
187
+ <div class="section-heading compact"><div><p class="eyebrow">When something breaks</p><h2>Tell me, don't make me look</h2><p>Paste a Slack or Discord webhook (anything that accepts a POST works). tapp posts when a journey <b>stops working</b>, and again when it <b>works again</b> — never on every check.</p></div></div>
188
+ <div id="alerts-body"></div>
189
+ </section>
186
190
  <section class="panel section hidden" id="agent-panel">
187
191
  <div class="section-heading compact">
188
192
  <div><p class="eyebrow">Your coding agent</p><h2>Let your agent check these journeys <i id="token-count" class="zero">0</i></h2><p>A token lets your coding agent ask “is everything still passing?” and replay a journey — as you, without a browser. It is shown once and can be revoked at any time.</p></div>
@@ -181,3 +181,22 @@ committed Flows (subfolders and all) or this machine's kept journeys. The MCP to
181
181
  two abilities on the existing tools — `tapp_report { journeys: true }` and
182
182
  `tapp_run { journey }` — never new tools (ADR-0007). Both are implemented by
183
183
  `mcp-server/src/studio-client.js`.
184
+
185
+ ## Alerts
186
+
187
+ A kept journey that goes red is only news if someone hears about it. `alerts.js` posts to a
188
+ webhook the owner pastes in (`POST /api/alerts`, `GET` returns a summary, `POST /api/alerts/test`
189
+ sends one on demand) — Slack and Discord both accept the body, which carries `text` and `content`
190
+ plus the journey, state and step counts.
191
+
192
+ Rules that keep it worth reading:
193
+
194
+ - **Only on a change.** `alertForChange` compares the previous result with the new one; a journey
195
+ that has been failing for a week does not produce a message every day, and a first run produces
196
+ none at all because nothing has changed yet.
197
+ - **Proved before promised.** Saving a webhook posts a message to it; if that fails the webhook is
198
+ not saved and the error says why.
199
+ - **Write-only.** The stored URL never leaves the store: the summary gives the host and the last
200
+ delivery. Anyone holding the URL can post into that channel.
201
+ - **Public https only.** The post comes from the server, so a webhook on localhost or a private
202
+ range is refused, the same rule the egress proxy enforces for exploration.
@@ -0,0 +1,97 @@
1
+ // Telling someone their journey stopped working, without tapp sending email.
2
+ //
3
+ // A monitoring product that only shows you a failure when you happen to open the page is not one.
4
+ // tapp has no mail provider by design (see ADR-0009 slice 2b), so the way out is a webhook: the
5
+ // owner pastes a URL — Slack and Discord both give you one, and so does anything else that can
6
+ // receive a POST — and tapp posts to it when a journey changes state.
7
+ //
8
+ // Only on a CHANGE. A journey that has been failing for a week does not deserve a message every
9
+ // day; what is news is "this used to pass and now it does not", and "it is working again".
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+
13
+ export const ALERT_EVENTS = Object.freeze(["broke", "recovered"]);
14
+
15
+ /** Did this result change anything worth telling someone about? */
16
+ export function alertForChange({ previous, current }) {
17
+ if (!current) return null;
18
+ // A journey's first run is not news: nothing has changed yet, it has only started.
19
+ if (!previous) return null;
20
+ if (previous.passed === current.passed) return null;
21
+ return current.passed ? "recovered" : "broke";
22
+ }
23
+
24
+ /** What the message says. Plain words, and never a credential — a journey holds none. */
25
+ export function alertMessage({ kind, journey, status, origin = "" }) {
26
+ const where = origin ? `${origin.replace(/\/$/, "")}/#runs` : "";
27
+ if (kind === "broke") {
28
+ const detail = status.total ? ` It got ${status.executed} of ${status.total} steps in.` : "";
29
+ return {
30
+ text: `❌ “${journey}” stopped working.${detail}${where ? ` Evidence: ${where}` : ""}`,
31
+ journey, state: "failing", at: status.at, executed: status.executed, total: status.total,
32
+ };
33
+ }
34
+ return {
35
+ text: `✅ “${journey}” is working again.${where ? ` ${where}` : ""}`,
36
+ journey, state: "passing", at: status.at, executed: status.executed, total: status.total,
37
+ };
38
+ }
39
+
40
+ /**
41
+ * Post one message. Slack and Discord both accept a JSON body with `text`/`content`, so send
42
+ * both keys and let the receiver pick; anything else gets the whole thing as JSON anyway.
43
+ */
44
+ export async function deliverAlert({ webhook, message, fetchImpl = fetch, timeoutMs = 8000 }) {
45
+ if (!webhook) return { delivered: false, reason: "no webhook configured" };
46
+ let url;
47
+ try { url = new URL(webhook); } catch { return { delivered: false, reason: "that is not a URL" }; }
48
+ if (url.protocol !== "https:") return { delivered: false, reason: "a webhook must be https" };
49
+ // The Studio posts this from the server, so the same rule as every other outbound call applies:
50
+ // public addresses only. A webhook pointing at localhost would reach this machine's own services.
51
+ if (/^(localhost|127\.|0\.|10\.|192\.168\.|169\.254\.|\[?::1)/i.test(url.hostname) || /\.local$/i.test(url.hostname)) {
52
+ return { delivered: false, reason: "a webhook must be a public address" };
53
+ }
54
+ const controller = new AbortController();
55
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
56
+ try {
57
+ const response = await fetchImpl(url.href, {
58
+ method: "POST",
59
+ headers: { "content-type": "application/json" },
60
+ body: JSON.stringify({ text: message.text, content: message.text, ...message }),
61
+ signal: controller.signal,
62
+ });
63
+ return response.ok ? { delivered: true, status: response.status } : { delivered: false, reason: `the webhook answered ${response.status}` };
64
+ } catch (error) {
65
+ return { delivered: false, reason: String(error?.name === "AbortError" ? "the webhook did not answer in time" : error.message || error).slice(0, 120) };
66
+ } finally { clearTimeout(timer); }
67
+ }
68
+
69
+ /** Where an account's alert settings live: beside its journeys, 0600, no secret but its own URL. */
70
+ export class AlertStore {
71
+ constructor({ file }) { this.file = file; }
72
+
73
+ static forAccount(accountsRoot, accountId) {
74
+ if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) throw new Error("Not an account id");
75
+ return new AlertStore({ file: path.join(accountsRoot, "alerts", `${accountId}.json`) });
76
+ }
77
+
78
+ read() {
79
+ try { return JSON.parse(fs.readFileSync(this.file, "utf8")); } catch { return { webhook: "", updatedAt: null, lastDelivery: null }; }
80
+ }
81
+
82
+ write(settings) {
83
+ const next = { ...this.read(), ...settings, updatedAt: new Date().toISOString() };
84
+ fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
85
+ fs.writeFileSync(this.file, JSON.stringify(next), { mode: 0o600 });
86
+ return next;
87
+ }
88
+
89
+ /** The URL is a secret of sorts — anyone holding it can post into that channel. Show its shape. */
90
+ summary() {
91
+ const settings = this.read();
92
+ if (!settings.webhook) return { configured: false, host: null, updatedAt: null, lastDelivery: settings.lastDelivery || null };
93
+ let host = "a webhook";
94
+ try { host = new URL(settings.webhook).host; } catch { /* keep the generic word */ }
95
+ return { configured: true, host, updatedAt: settings.updatedAt || null, lastDelivery: settings.lastDelivery || null };
96
+ }
97
+ }
@@ -23,6 +23,7 @@ import { createMailer, signInMessage } from "./mailer.js";
23
23
  import { accessConfig, createAccessVerifier } from "./access-jwt.js";
24
24
  import { oauthProviders, oauthAuthorizeUrl, oauthEmailFromCode, isOauthProvider } from "./oauth.js";
25
25
  import { journeyFromCapture, JourneyStore, slugify } from "./journeys.js";
26
+ import { AlertStore, alertForChange, alertMessage, deliverAlert } from "./alerts.js";
26
27
 
27
28
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
28
29
  const assetRoot = path.join(packageRoot, "browser");
@@ -158,7 +159,9 @@ function anonymousAllows(method, pathname) {
158
159
  function accountAllows(method, pathname) {
159
160
  if (anonymousAllows(method, pathname)) return true;
160
161
  if (method === "POST" && (pathname === "/api/auth/signout" || /^\/api\/jobs\/[a-f0-9]{20}\/input$/.test(pathname))) return true;
161
- if (method === "GET" && (pathname === "/api/actors" || pathname === "/api/journeys" || pathname === "/api/tokens" || pathname === "/api/admin/overview")) return true;
162
+ if (method === "GET" && (pathname === "/api/actors" || pathname === "/api/journeys" || pathname === "/api/tokens" || pathname === "/api/admin/overview" || pathname === "/api/alerts")) return true;
163
+ // Where to be told that a journey stopped working.
164
+ if (method === "POST" && (pathname === "/api/alerts" || pathname === "/api/alerts/test")) return true;
162
165
  // Personal access tokens: the owner's coding agent acting as them (ADR-0009 slice 4).
163
166
  if (method === "POST" && pathname === "/api/tokens") return true;
164
167
  if (method === "DELETE" && /^\/api\/tokens\/[a-f0-9]{12}$/.test(pathname)) return true;
@@ -281,7 +284,7 @@ export function journeySignInPlan(flow = {}) {
281
284
 
282
285
  // Replay one web journey and record how it went. Shared by the Studio's Run button and the
283
286
  // daily check, so both leave the same status and the same evidence behind.
284
- async function replayJourney({ store, slug, flow, actorRoot = "", ownerKey = null, progress = () => {} }) {
287
+ async function replayJourney({ store, slug, flow, actorRoot = "", ownerKey = null, progress = () => {}, alerts = null, origin = "" }) {
285
288
  // A journey that signs in does so as the test account tapp was told about for that site: the
286
289
  // values come from the encrypted actor store at replay and never from the file.
287
290
  const variables = {};
@@ -329,8 +332,19 @@ async function replayJourney({ store, slug, flow, actorRoot = "", ownerKey = nul
329
332
  if (/^OCQA_(FLOW_RESULT|ISSUE):/.test(raw)) continue;
330
333
  if (raw) progress({ phase: "replay", text: raw });
331
334
  }
335
+ // Read the old result before writing the new one: the news is the change, not the state.
336
+ const previous = store.status(slug);
332
337
  const status = store.recordRun(slug, { passed: result.passed, captureId, executed: result.executed, total: result.total, failed: result.failed });
333
- return { kind: "journey", name: flow.name || slug, slug, passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, status, capture: { id: captureId, path: evidenceDir } };
338
+ const change = alertForChange({ previous, current: status });
339
+ let alert = null;
340
+ if (change && alerts) {
341
+ const settings = alerts.read();
342
+ if (settings.webhook) {
343
+ alert = await deliverAlert({ webhook: settings.webhook, message: alertMessage({ kind: change, journey: flow.name || slug, status, origin }) });
344
+ alerts.write({ lastDelivery: { at: new Date().toISOString(), journey: flow.name || slug, change, ...alert } });
345
+ }
346
+ }
347
+ return { kind: "journey", name: flow.name || slug, slug, passed: result.passed, executed: result.executed, total: result.total, failed: result.failed, status, change, ...(alert ? { alert } : {}), capture: { id: captureId, path: evidenceDir } };
334
348
  }
335
349
 
336
350
  // "Make sure this always works": kept journeys on a public Studio are replayed on a schedule,
@@ -618,11 +632,29 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
618
632
  // durable handle for one. Off unless the Studio is public; a local Studio logging its owner's
619
633
  // own use is noise.
620
634
  const usage = { visitors: new Set(), audits: 0, refusals: 0, startedAt: new Date().toISOString() };
635
+ // The same line goes to stdout (systemd keeps it) and to a file the Studio can read back, so
636
+ // the owner's page can answer "what has been happening?" after a restart — the in-memory
637
+ // counters start again at zero every deploy, which made them nearly useless for that question.
638
+ // Same discipline either way: no IP address, no full URL, no credential, and only the first
639
+ // eight characters of a visitor id — enough to tell two people apart in a day, not a handle.
640
+ const usageLogPath = path.join(process.env.TAPP_HOME || path.join(os.homedir(), ".tapp"), "usage.jsonl");
641
+ const USAGE_LOG_MAX_BYTES = 2_000_000;
621
642
  const logUsage = (event, fields = {}) => {
622
643
  if (!publicAccess) return;
644
+ const line = JSON.stringify({ at: new Date().toISOString(), event, ...fields });
645
+ try { console.log(`tapp-usage ${line}`); } catch { /* logging must never break a run */ }
623
646
  try {
624
- console.log(`tapp-usage ${JSON.stringify({ at: new Date().toISOString(), event, ...fields })}`);
625
- } catch { /* logging must never break a run */ }
647
+ fs.appendFileSync(usageLogPath, `${line}\n`, { mode: 0o600 });
648
+ // Keep the tail rather than growing without limit; this is a record of activity, not an archive.
649
+ if (fs.statSync(usageLogPath).size > USAGE_LOG_MAX_BYTES) {
650
+ const kept = fs.readFileSync(usageLogPath, "utf8").split("\n").filter(Boolean).slice(-4000);
651
+ fs.writeFileSync(usageLogPath, `${kept.join("\n")}\n`, { mode: 0o600 });
652
+ }
653
+ } catch { /* a full disk must not fail a run either */ }
654
+ };
655
+ const readUsageLog = (limit = 4000) => {
656
+ try { return fs.readFileSync(usageLogPath, "utf8").split("\n").filter(Boolean).slice(-limit).map((line) => { try { return JSON.parse(line); } catch { return null; } }).filter(Boolean); }
657
+ catch { return []; }
626
658
  };
627
659
  // Where a visitor pointed us, without what they may have put in the query string.
628
660
  const safeHost = (value) => { try { return new URL(value).host; } catch { return "unparsed"; } };
@@ -701,7 +733,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
701
733
  try { const { loadFlowFile } = await import("./flow-runtime.js"); flow = loadFlowFile(flowPath); } catch { continue; }
702
734
  let job;
703
735
  try {
704
- job = startJob("check-journey", (progress) => replayJourney({ store, slug: journey.slug, flow, actorRoot: accounts.actorRoot(accountId), ownerKey, progress }), null, { lane: ownerKey });
736
+ job = startJob("check-journey", (progress) => replayJourney({ store, slug: journey.slug, flow, actorRoot: accounts.actorRoot(accountId), ownerKey, progress, alerts: AlertStore.forAccount(accounts.root, accountId), origin: publicOrigins[0] || "" }), null, { lane: ownerKey });
705
737
  } catch { continue; /* the owner is busy; next tick */ }
706
738
  job.ownerKey = ownerKey;
707
739
  // One at a time per owner: wait for this check before starting the next.
@@ -1107,6 +1139,42 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1107
1139
  }
1108
1140
  } catch { /* none yet */ }
1109
1141
  const owners = listAccounts();
1142
+
1143
+ // What has actually happened here, from the durable log. The in-memory counters only
1144
+ // cover the current process; this survives a deploy.
1145
+ const events = readUsageLog();
1146
+ const since = (hours) => Date.now() - hours * 3600_000;
1147
+ const within = (hours) => events.filter((e) => Date.parse(e.at) >= since(hours));
1148
+ const tally = (list) => list.reduce((counts, e) => ({ ...counts, [e.event]: (counts[e.event] || 0) + 1 }), {});
1149
+
1150
+ // "Three visitors" is not an answer. Who were they, when, and what did they do?
1151
+ const people = new Map();
1152
+ for (const entry of events) {
1153
+ const id = entry.account ? `account:${entry.account}` : entry.visitor ? `visitor:${entry.visitor}` : null;
1154
+ if (!id) continue;
1155
+ const seen = people.get(id) || { id, kind: entry.account ? "account" : "visitor", first: entry.at, last: entry.at, events: {}, hosts: [] };
1156
+ seen.last = entry.at;
1157
+ if (entry.at < seen.first) seen.first = entry.at;
1158
+ seen.events[entry.event] = (seen.events[entry.event] || 0) + 1;
1159
+ if (entry.host && !seen.hosts.includes(entry.host) && seen.hosts.length < 8) seen.hosts.push(entry.host);
1160
+ people.set(id, seen);
1161
+ }
1162
+
1163
+ // Every run still on disk, which predates the log and outlives it.
1164
+ const runs = [];
1165
+ try {
1166
+ for (const name of fs.readdirSync(captureRoot())) {
1167
+ const dir = path.join(captureRoot(), name);
1168
+ const provenance = readCaptureProvenance(dir);
1169
+ if (!provenance) continue;
1170
+ let target = provenance.target || "";
1171
+ try { target = new URL(target).host; } catch { /* a bundle id or a path */ }
1172
+ runs.push({ id: name, kind: provenance.kind || (name.startsWith("web-audit-") ? "audit" : name.startsWith("flow-") ? "journey" : "explore"),
1173
+ target: String(target).slice(0, 60), at: provenance.createdAt || null, owner: captureOwner(name) || "operator" });
1174
+ }
1175
+ } catch { /* none yet */ }
1176
+ runs.sort((a, b) => String(b.at || "").localeCompare(String(a.at || "")));
1177
+
1110
1178
  json(response, 200, {
1111
1179
  release: process.env.TAPP_RELEASE || "dev",
1112
1180
  startedAt: serverStartedAt,
@@ -1116,9 +1184,47 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1116
1184
  accounts: owners,
1117
1185
  journeyCheckHours: Math.max(1, Number(process.env.TAPP_JOURNEY_CHECK_HOURS) || 24),
1118
1186
  admins: [...adminEmails],
1187
+ activity: {
1188
+ logged: events.length,
1189
+ since: events[0]?.at || null,
1190
+ today: tally(within(24)),
1191
+ week: tally(within(24 * 7)),
1192
+ recent: events.slice(-60).reverse(),
1193
+ people: [...people.values()].sort((a, b) => String(b.last).localeCompare(String(a.last))).slice(0, 50),
1194
+ },
1195
+ recentRuns: runs.slice(0, 40),
1196
+ totalRuns: runs.length,
1119
1197
  });
1120
1198
  return;
1121
1199
  }
1200
+ // Where to be told when something breaks. The URL is write-only here: the summary says
1201
+ // which host it points at and when it last delivered, never the URL itself, because anyone
1202
+ // holding it can post into that channel.
1203
+ if (account && url.pathname === "/api/alerts") {
1204
+ const alerts = AlertStore.forAccount(accounts.root, account.id);
1205
+ if (request.method === "GET") { json(response, 200, alerts.summary()); return; }
1206
+ guardMutation(request);
1207
+ const body = await readJsonBody(request);
1208
+ const webhook = String(body.webhook || "").trim();
1209
+ if (webhook) {
1210
+ const probe = await deliverAlert({ webhook, message: alertMessage({ kind: "recovered", journey: "tapp alerts", status: { at: new Date().toISOString(), executed: 0, total: 0 }, origin: publicOrigins[0] || "" }) });
1211
+ if (!probe.delivered) { json(response, 400, { error: `tapp could not post there — ${probe.reason}.` }); return; }
1212
+ }
1213
+ alerts.write({ webhook });
1214
+ logUsage("alerts.set", { account: account.id.slice(0, 8), configured: !!webhook });
1215
+ json(response, 200, alerts.summary());
1216
+ return;
1217
+ }
1218
+ if (account && url.pathname === "/api/alerts/test" && request.method === "POST") {
1219
+ guardMutation(request);
1220
+ const alerts = AlertStore.forAccount(accounts.root, account.id);
1221
+ const settings = alerts.read();
1222
+ if (!settings.webhook) { json(response, 400, { error: "There is nowhere to send it yet." }); return; }
1223
+ const sent = await deliverAlert({ webhook: settings.webhook, message: alertMessage({ kind: "broke", journey: "a test from tapp", status: { at: new Date().toISOString(), executed: 3, total: 7 }, origin: publicOrigins[0] || "" }) });
1224
+ alerts.write({ lastDelivery: { at: new Date().toISOString(), journey: "a test from tapp", change: "test", ...sent } });
1225
+ json(response, sent.delivered ? 200 : 400, sent.delivered ? alerts.summary() : { error: `tapp could not post there — ${sent.reason}.` });
1226
+ return;
1227
+ }
1122
1228
  if (account && url.pathname === "/api/tokens" && request.method === "GET") {
1123
1229
  json(response, 200, { tokens: accounts.listTokens(account.id) });
1124
1230
  return;
@@ -1404,7 +1510,7 @@ export async function startBrowserProduct({ projectDir, port = 0, launch = false
1404
1510
  }
1405
1511
  const slug = root ? name : slugify(name);
1406
1512
  const job = startJob(operation, async (progress) => {
1407
- const result = await replayJourney({ store, slug, flow, actorRoot: actorRootFor() || "", ownerKey, progress });
1513
+ const result = await replayJourney({ store, slug, flow, actorRoot: actorRootFor() || "", ownerKey, progress, alerts: account ? AlertStore.forAccount(accounts.root, account.id) : null, origin: publicOrigins[0] || "" });
1408
1514
  logUsage("journey.run", { owner: (ownerKey || "operator").slice(0, 13), passed: result.passed });
1409
1515
  return result;
1410
1516
  }, null, { lane: ownerKey || OPERATOR_LANE });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aarwitz/tapp",
3
- "version": "0.30.1",
3
+ "version": "0.32.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-overlay.test.js tests/web-audit.test.js tests/page-observations.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/oauth.test.js tests/studio-client.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",
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-overlay.test.js tests/web-audit.test.js tests/page-observations.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/account-store.test.js tests/alerts.test.js tests/access-jwt.test.js tests/oauth.test.js tests/studio-client.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
  }