@aarwitz/tapp 0.35.8 → 0.35.9

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
@@ -1,9 +1,24 @@
1
1
  import { customerProductContract } from "./product-contract.js";
2
- import { classifyPrompt, coverageGraph, groupFindings, narrate, narrateFinding, operationIsPending, severityTally, summarize } from "./view-model.js";
2
+ import { classifyPrompt, coverageGraph, groupFindings, narrate, narrateFinding, operationIsPending, severityTally, summarize, parseConnectFragment } from "./view-model.js";
3
3
 
4
4
  const API_BASE = String(document.querySelector('meta[name="tapp-api-base"]')?.content || "").replace(/\/$/, "");
5
5
  const LOGIN_URL = String(document.querySelector('meta[name="tapp-login-url"]')?.content || "");
6
+ // app.runtapp.com driving the runtime on this person's machine (ADR-0011 §4, join B). The
7
+ // runtime opened this page with its address and launch secret in the URL fragment; the page
8
+ // keeps them in this browser only and talks to that address with the secret as a bearer.
9
+ function loadConnection() {
10
+ try {
11
+ const saved = JSON.parse(localStorage.getItem("tapp.connect") || "null");
12
+ return saved && /^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d{1,5})?$/.test(saved.origin) && /^[A-Za-z0-9_-]{20,}$/.test(saved.token || "") ? saved : null;
13
+ } catch { return null; }
14
+ }
15
+ function saveConnection(connection) {
16
+ try { if (connection) localStorage.setItem("tapp.connect", JSON.stringify(connection)); else localStorage.removeItem("tapp.connect"); } catch { /* fine */ }
17
+ }
18
+
6
19
  function apiRoute(route) {
20
+ // A page that is not itself that runtime talks to it; the runtime's own page never loops back.
21
+ if (state.connection && state.connection.origin !== location.origin) return `${state.connection.origin}${route}`;
7
22
  if (!API_BASE) return route;
8
23
  if (route === "/api" || route.startsWith("/api/")) return `${API_BASE}${route.slice(4)}`;
9
24
  if (route === "/evidence" || route.startsWith("/evidence/")) return `${API_BASE}${route}`;
@@ -12,9 +27,17 @@ function apiRoute(route) {
12
27
 
13
28
  const state = {
14
29
  csrf: "", session: null, project: null, audits: [], explores: [], activeJob: null, activeView: "overview",
15
- selectedTargetId: "", selectedRunId: "", live: { active:false }, transcript: [], transcriptSource: "", frameTimer: null, pendingInput: null,
30
+ selectedTargetId: "", selectedRunId: "", live: { active:false }, transcript: [], transcriptSource: "", transcriptKind: "", activeOperation: "", engines: null, setup: null, setupCollapsed: null, deviceAuthPoll: null, connection: null, connectionLost: null, frameTimer: null, pendingInput: null,
16
31
  chatCollapsed: false, shotScreens: new Set(), lastShotAt: 0,
17
32
  };
33
+ {
34
+ // The runtime hands this page its address and secret in the fragment; keep them here, and take
35
+ // them off the address bar so a copied link carries no secret.
36
+ const fromHash = parseConnectFragment(location.hash);
37
+ if (fromHash) { saveConnection(fromHash); history.replaceState(null, "", location.pathname + location.search); }
38
+ state.connection = loadConnection();
39
+ if (state.connection && state.connection.origin === location.origin) state.connection = null;
40
+ }
18
41
  const $ = (selector) => document.querySelector(selector);
19
42
  const $$ = (selector) => [...document.querySelectorAll(selector)];
20
43
  const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (character) => ({ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":"&#39;" }[character]));
@@ -32,7 +55,8 @@ function toast(message, error = false) {
32
55
 
33
56
  async function api(route, options = {}) {
34
57
  const mutation = options.method && options.method !== "GET";
35
- const headers = { ...(options.body !== undefined ? { "content-type":"application/json" } : {}), ...(mutation ? { "x-tapp-csrf":state.csrf } : {}), ...(options.headers || {}) };
58
+ const connected = state.connection && state.connection.origin !== location.origin;
59
+ const headers = { ...(options.body !== undefined ? { "content-type":"application/json" } : {}), ...(mutation ? { "x-tapp-csrf":state.csrf } : {}), ...(connected ? { authorization: `Bearer ${state.connection.token}` } : {}), ...(options.headers || {}) };
36
60
  const response = await fetch(apiRoute(route), { ...options, headers });
37
61
  const data = await response.json().catch(() => ({}));
38
62
  if (response.status === 401 && LOGIN_URL) {
@@ -51,7 +75,14 @@ function captureId(report) {
51
75
  }
52
76
  return report?.capture?.id || "";
53
77
  }
54
- const captureUrl = (id, file = "report.html") => apiRoute(`/evidence/captures/${encodeURIComponent(id)}/${file}`);
78
+ // An image or a report the page shows cannot carry a header, so when this page is driving a
79
+ // runtime on the person's machine the launch secret rides on the query instead (ADR-0011 §4).
80
+ const assetUrl = (route) => {
81
+ const base = apiRoute(route);
82
+ if (!state.connection) return base;
83
+ return `${base}${base.includes("?") ? "&" : "?"}token=${encodeURIComponent(state.connection.token)}`;
84
+ };
85
+ const captureUrl = (id, file = "report.html") => assetUrl(`/evidence/captures/${encodeURIComponent(id)}/${file}`);
55
86
  function evidenceLink(id, label = "Open visual evidence") {
56
87
  return id ? `<a class="button-link" href="${esc(captureUrl(id))}" target="_blank" rel="noreferrer">${esc(label)}</a>` : "";
57
88
  }
@@ -167,11 +198,18 @@ function renderAccount() {
167
198
  const session = state.session || {};
168
199
  const isPublic = session.access === "anonymous" || session.access === "account";
169
200
  for (const slot of document.querySelectorAll("#account-slot, #account-slot-side")) {
201
+ if (state.connection) {
202
+ slot.classList.remove("hidden");
203
+ slot.innerHTML = `<span class="account-email" title="${esc(state.connection.origin)}">your machine</span><button type="button" data-disconnect-machine>Disconnect</button>`;
204
+ continue;
205
+ }
170
206
  slot.classList.toggle("hidden", !isPublic);
171
207
  if (!isPublic) continue;
208
+ // A visitor is not offered a sign-in button up front: the cloud is coming soon, and the way
209
+ // in for an account that already exists sits on that card (ADR-0011 §3).
172
210
  slot.innerHTML = session.access === "account"
173
211
  ? `<span class="account-email" title="${esc(session.email || "")}">${esc(session.email || "")}</span>${planPill(session.plan)}<button type="button" data-signout>Sign out</button>`
174
- : `<button type="button" class="primary" data-signin>Sign in</button>`;
212
+ : "";
175
213
  }
176
214
  $("#signin-card")?.classList.toggle("hidden", session.access !== "anonymous" || !state.signInOpen);
177
215
  renderSignInOptions();
@@ -221,6 +259,7 @@ function applyAccessMode() {
221
259
  renderPlatformStrip();
222
260
  renderPlatforms();
223
261
  renderStudioLink();
262
+ renderSetup();
224
263
  if (session.access !== "anonymous" && session.access !== "account") return;
225
264
  const signedIn = session.access === "account";
226
265
  const accepts = new Set(session.accepts || ["url"]);
@@ -236,8 +275,11 @@ function applyAccessMode() {
236
275
  button.closest("li")?.classList.toggle("hidden", !usable);
237
276
  }
238
277
  $("#selfhost-card")?.classList.remove("hidden");
278
+ $("#cloud-card")?.classList.toggle("hidden", signedIn);
279
+ const lead = $("#selfhost-lead");
280
+ if (lead && state.connectionLost) lead.innerHTML = `<strong>Your machine stopped answering at ${esc(state.connectionLost.origin)}.</strong> Start the runtime again and this page connects to it; or open the address the command prints if this browser will not reach your machine.`;
239
281
  const input = $("#prompt-input");
240
- if (input) input.placeholder = accepts.has("path") ? input.placeholder : "A website URL — https://…";
282
+ if (input && !accepts.has("path")) input.placeholder = "A business name or website URL…";
241
283
  // Everything that only means something against a source repository: a target to build, a
242
284
  // runner, a release gate, a decision. A hosted visitor auditing a URL has none of them, and
243
285
  // showing the empty frames makes a working run look like a broken one.
@@ -546,7 +588,7 @@ function refreshLiveFrame() {
546
588
  if (!image.naturalWidth) loading.classList.remove("hidden");
547
589
  image.onload = () => { loading.classList.add("hidden"); scheduleLiveFrame(); };
548
590
  image.onerror = () => { loading.textContent = "Live frame could not be captured. The semantic controls remain available."; scheduleLiveFrame(); };
549
- image.src = apiRoute(`${source}?at=${Date.now()}`);
591
+ image.src = assetUrl(`${source}?at=${Date.now()}`);
550
592
  }
551
593
  function scheduleLiveFrame() { clearTimeout(state.frameTimer); if (frameSource()) state.frameTimer = setTimeout(refreshLiveFrame, 1500); }
552
594
  function stopLiveFrames() { clearTimeout(state.frameTimer); state.frameTimer = null; }
@@ -644,13 +686,96 @@ function renderStudioLink() {
644
686
  const link = state.session?.studioLink;
645
687
  body.innerHTML = link
646
688
  ? `<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>
689
+ : linkFormMarkup();
690
+ }
691
+
692
+ function linkFormMarkup() {
693
+ return `<form class="link-form" data-link-form autocomplete="off">
694
+ <input name="origin" type="url" value="https://app.runtapp.com" aria-label="Studio URL" spellcheck="false">
695
+ <input name="token" type="password" placeholder="tapp_… — a token from your Studio, under “Your coding agent”" aria-label="Token" autocomplete="off" required>
696
+ <div class="ask-actions"><button class="primary" type="submit">Connect</button><small>The token is kept on this machine only, readable by you.</small></div>
651
697
  </form>`;
652
698
  }
653
699
 
700
+ // ——— Setting this machine up (ADR-0012) ——————————————————————————————————————————————————
701
+ // The journey's first screen on a local Studio: the runtime, the agent on your own plan, what
702
+ // each target needs with the exact fix, and the account. Collapses to one line once ready.
703
+ async function loadSetup() {
704
+ if (state.session?.mode !== "local") { state.setup = null; return; }
705
+ state.setup = await api("/api/setup").catch(() => null);
706
+ if (state.setup) state.engines = { engines: state.setup.engines, selected: state.setup.selected };
707
+ }
708
+
709
+ function setupEngine() {
710
+ return (state.setup?.engines || []).find((engine) => engine.id === state.setup?.selected) || null;
711
+ }
712
+
713
+ function renderSetup() {
714
+ const card = $("#setup-card");
715
+ if (!card) return;
716
+ const local = state.session?.mode === "local";
717
+ card.classList.toggle("hidden", !local);
718
+ if (!local) return;
719
+ const steps = $("#setup-steps");
720
+ const setup = state.setup;
721
+ if (!setup) { steps.innerHTML = '<li class="empty">Checking this machine…</li>'; return; }
722
+ const engine = setupEngine();
723
+ const agentOk = !!(engine?.usable && engine?.drives);
724
+ const readyTargets = (setup.targets || []).filter((t) => t.ready).map((t) => t.label);
725
+ let stored = null;
726
+ try { stored = localStorage.getItem("tapp.setupCollapsed"); } catch { /* fine */ }
727
+ const collapsed = state.setupCollapsed ?? (stored !== null ? stored === "1" : agentOk && readyTargets.length > 1);
728
+ card.classList.toggle("collapsed", collapsed);
729
+ $("#setup-toggle").textContent = collapsed ? "Show" : "Hide";
730
+ $("#setup-title").textContent = agentOk ? "This machine is ready" : "Set up tapp here";
731
+ const agentWord = !engine ? "no agent signed in" : engine.usable ? `${engine.label}${engine.billing === "plan" ? ` on your ${engine.account?.plan ? engine.account.plan[0].toUpperCase() + engine.account.plan.slice(1) : engine.plan} plan` : engine.billing === "api-key" ? " on an API key" : ""}` : `${engine.label} not signed in`;
732
+ $("#setup-sub").textContent = `${agentWord} · ${readyTargets.length ? `${readyTargets.join(", ")} ready` : "no target ready yet"} · ${setup.link ? `reports to ${setup.link.email || setup.link.origin}` : "not linked to an account"}`;
733
+
734
+ const mark = (ok, warn = false) => ok ? "✓" : warn ? "⚠️" : "○";
735
+ const pill = (e) => e.state === "ok" ? `<span class="journey-status passing">signed in</span>` : e.state === "warning" ? `<span class="journey-status warning">${esc(e.billing === "api-key" ? "API key" : "not signed in")}</span>` : `<span class="journey-status never">not installed</span>`;
736
+ const r = setup.runtime || {};
737
+ const runtimeIssue = r.pyyaml === false ? " Flow replay needs PyYAML: <code>python3 -m pip install pyyaml</code>." : r.disk?.level === "blocked" ? ` ${esc(r.disk.message || "Disk is full.")}` : "";
738
+ const runtime = `<li class="setup-step"><i>${mark(!runtimeIssue, true)}</i><div><h3>Runtime</h3><p>tapp v${esc(r.version || "")} · Node ${esc(r.node || "")}${r.python ? ` · ${esc(r.python)}` : ""}.${runtimeIssue}</p></div></li>`;
739
+
740
+ const claude = (setup.engines || []).find((e) => e.id === "claude");
741
+ const codex = (setup.engines || []).find((e) => e.id === "codex");
742
+ const engineRows = (setup.engines || []).map((e) => `<li class="engine-line"><span>${pill(e)}</span><span><strong>${esc(e.label)}</strong>${e.id === setup.selected && e.usable ? ' <small class="journey-status passing" style="display:inline">drives the chat</small>' : ""}<small>${esc(e.detail)}${e.fix ? ` ${esc(e.fix)}` : ""}${e.usable && !e.drives ? " Driving the chat from here comes next." : ""}</small>${e.usable && e.drives && e.id !== setup.selected ? `<button class="quiet" type="button" data-engine-select="${esc(e.id)}" style="margin-top:4px">Use</button>` : ""}</span></li>`).join("");
743
+ const codexSignIn = codex && codex.state !== "missing" && codex.billing !== "plan"
744
+ ? (setup.deviceAuth
745
+ ? `<div class="button-row"><span>1. Open <a href="${esc(setup.deviceAuth.url)}" target="_blank" rel="noreferrer">${esc(setup.deviceAuth.url)}</a> &nbsp; 2. Enter <code>${esc(setup.deviceAuth.code)}</code> — waiting for you to finish…</span><button class="quiet" type="button" data-codex-cancel>Cancel</button></div>`
746
+ : `<div class="button-row"><button class="quiet" type="button" data-codex-signin>Sign in with ChatGPT</button><small>You get a link and a code to finish on any device.</small></div>`)
747
+ : "";
748
+ const apiKey = setup.apiKey?.set
749
+ ? `<div class="button-row"><span>API key on file ${esc(setup.apiKey.hint)} — bills per use.</span><button class="quiet" type="button" data-apikey-forget>Forget</button></div>`
750
+ : `<form id="setup-apikey" autocomplete="off"><input name="key" type="password" placeholder="Or paste an Anthropic API key (sk-ant-…) — bills per use" aria-label="Anthropic API key" autocomplete="off" required><button class="quiet" type="submit">Save key</button></form>`;
751
+ const agent = `<li class="setup-step"><i>${mark(agentOk, !!claude && claude.state !== "missing")}</i><div><h3>Your agent</h3><p>tapp signs you in to nothing and holds no token: it drives the coding agent you already signed in to, on your own plan.</p><ul>${engineRows}</ul>${codexSignIn}${apiKey}</div></li>`;
752
+
753
+ const targets = `<li class="setup-step"><i>${mark(readyTargets.length > 1, readyTargets.length === 1)}</i><div><h3>What you'll test</h3><p>What this machine has for each kind of app, and the one thing to install when something is missing.</p><ul>${(setup.targets || []).map((t) => `<li><span>${mark(t.ready)}</span><span><strong>${esc(t.label)}</strong>${t.items.map((i) => `<small>${i.ok ? "✓" : "○"} ${esc(i.text)}${i.fix ? ` — ${esc(i.fix)}` : ""}</small>`).join("")}</span></li>`).join("")}</ul></div></li>`;
754
+
755
+ const account = `<li class="setup-step"><i>${mark(!!setup.link)}</i><div><h3>Your account <small>optional</small></h3><p>${setup.link ? `Journeys run here report to <strong>${esc(setup.link.email || setup.link.origin)}</strong>. <button class="quiet" type="button" data-unlink-studio>Disconnect</button>` : "Link this machine to your account on app.runtapp.com and journeys run here show up there with how they went. Nothing else leaves this machine."}</p>${setup.link ? "" : linkFormMarkup()}</div></li>`;
756
+ steps.innerHTML = runtime + agent + targets + account;
757
+ }
758
+
759
+ async function refreshSetup() {
760
+ await loadSetup();
761
+ renderSetup();
762
+ renderEngines();
763
+ renderChatPrompt();
764
+ }
765
+
766
+ // While a Codex device sign-in is open, look every few seconds for it to finish.
767
+ function watchDeviceAuth() {
768
+ if (state.deviceAuthPoll) return;
769
+ state.deviceAuthPoll = setInterval(async () => {
770
+ await refreshSetup();
771
+ const codex = (state.setup?.engines || []).find((e) => e.id === "codex");
772
+ if (!state.setup?.deviceAuth || codex?.billing === "plan") {
773
+ clearInterval(state.deviceAuthPoll); state.deviceAuthPoll = null;
774
+ if (codex?.billing === "plan") toast("Codex is signed in with your ChatGPT plan.");
775
+ }
776
+ }, 3000);
777
+ }
778
+
654
779
  function renderJourneys() {
655
780
  const node = $("#journeys-list");
656
781
  if (!node) return;
@@ -1039,6 +1164,7 @@ function renderChat() {
1039
1164
  }).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>' : "");
1040
1165
  node.innerHTML = lines;
1041
1166
  if (stickToBottom) node.scrollTop = node.scrollHeight;
1167
+ renderChatPrompt();
1042
1168
  const progress = [...state.transcript].reverse().find((entry) => entry.kind === "progress");
1043
1169
  $("#chat-status").textContent = state.activeJob ? (progress ? `${progress.current}/${progress.total} actions${progress.states != null ? ` · ${progress.states} screens` : ""}` : "working…") : state.transcript.length > 1 ? "done" : "ready";
1044
1170
  }
@@ -1084,6 +1210,54 @@ function setChatCollapsed(collapsed) {
1084
1210
 
1085
1211
  function pushLine(entry) { state.transcript.push({ at: new Date().toISOString(), ...entry }); }
1086
1212
 
1213
+ // ——— Your agent (ADR-0012) ———————————————————————————————————————————————————————————————————
1214
+ // The chat can ask the person's own coding agent — found on this machine, signed in to their own
1215
+ // plan — to drive tapp. Local only; nothing on a hosted Studio can reach a laptop.
1216
+ function selectedEngine() {
1217
+ const engines = state.engines?.engines || [];
1218
+ return engines.find((engine) => engine.id === state.engines?.selected) || null;
1219
+ }
1220
+
1221
+ function renderChatPrompt() {
1222
+ const form = $("#chat-prompt");
1223
+ if (!form) return;
1224
+ const engine = selectedEngine();
1225
+ const local = state.session?.mode === "local";
1226
+ form.classList.toggle("hidden", !(local && engine?.usable && engine?.drives));
1227
+ const input = $("#chat-prompt-input");
1228
+ const send = $("#chat-prompt-send");
1229
+ const stop = $("#chat-prompt-stop");
1230
+ const busy = !!state.activeJob;
1231
+ if (input) input.disabled = busy;
1232
+ if (send) send.disabled = busy;
1233
+ if (stop) stop.classList.toggle("hidden", !(busy && state.activeOperation === "agent"));
1234
+ }
1235
+
1236
+ async function loadEngines() {
1237
+ if (state.session?.mode !== "local") { state.engines = null; return; }
1238
+ state.engines = await api("/api/engines").catch(() => null);
1239
+ }
1240
+
1241
+ function renderEngines() {
1242
+ const panel = $("#engines-panel");
1243
+ const node = $("#engines-list");
1244
+ if (!panel || !node) return;
1245
+ const local = state.session?.mode === "local";
1246
+ panel.classList.toggle("hidden", !local);
1247
+ if (!local) return;
1248
+ const data = state.engines;
1249
+ if (!data) { node.innerHTML = '<div class="empty">Checking this machine…</div>'; return; }
1250
+ const pill = (engine) => engine.state === "ok" ? `<span class="journey-status passing">signed in</span>`
1251
+ : engine.state === "warning" ? `<span class="journey-status warning">${esc(engine.billing === "api-key" ? "API key" : "not signed in")}</span>`
1252
+ : `<span class="journey-status never">not installed</span>`;
1253
+ node.innerHTML = data.engines.map((engine) => `<div class="engine-row">
1254
+ <span>${pill(engine)}</span>
1255
+ <span><strong>${esc(engine.label)}</strong>${engine.id === data.selected ? ' <small class="journey-status passing" style="display:inline">drives the chat</small>' : ""}<small>${esc(engine.detail)}${engine.fix ? ` ${esc(engine.fix)}` : ""}${engine.usable && !engine.drives ? " Driving the chat from here comes next; Claude Code drives it today." : ""}</small></span>
1256
+ <span class="journey-actions">${engine.usable && engine.drives && engine.id !== data.selected ? `<button class="quiet" type="button" data-engine-select="${esc(engine.id)}">Use</button>` : ""}</span>
1257
+ </div>`).join("");
1258
+ renderChatPrompt();
1259
+ }
1260
+
1087
1261
  // A screenshot the engine wrote during the run, kept as a thumbnail in the transcript. Captured
1088
1262
  // once per screen name the engine reports, and never more often than every few seconds.
1089
1263
  async function keepShot(screen) {
@@ -1105,15 +1279,22 @@ async function keepShot(screen) {
1105
1279
 
1106
1280
  function syncTranscriptFromJob(name, job) {
1107
1281
  if (state.transcriptSource !== job.id) {
1108
- state.transcript = [{ at: job.createdAt, kind: "phase", icon: "🚀", text: startLine(name, job) }];
1282
+ // A run starts a fresh transcript. A chat turn with the agent is a conversation: the person's
1283
+ // words go in as a line of their own, and an earlier turn in the same thread stays on screen.
1284
+ const first = name === "agent"
1285
+ ? { at: job.createdAt, kind: "you", icon: "🧑", text: job.input || "" }
1286
+ : { at: job.createdAt, kind: "phase", icon: "🚀", text: startLine(name, job) };
1287
+ if (name === "agent" && state.transcriptKind === "agent") state.transcript.push(first);
1288
+ else state.transcript = [first];
1289
+ state.transcriptKind = name === "agent" ? "agent" : "run";
1109
1290
  state.transcriptSource = job.id;
1110
1291
  state.shotScreens = new Set();
1111
1292
  state.lastShotAt = 0;
1112
1293
  }
1113
- const seen = state.transcript.filter((entry) => entry.source === "job").length;
1294
+ const seen = state.transcript.filter((entry) => entry.source === job.id).length;
1114
1295
  for (const entry of job.progress.slice(seen)) {
1115
1296
  const line = narrate(entry, { platform: currentPlatform() });
1116
- state.transcript.push({ ...(line || { kind: "step", icon: "•", text: "" }), at: entry.at, source: "job" });
1297
+ state.transcript.push({ ...(line || { kind: "step", icon: "•", text: "" }), at: entry.at, source: job.id });
1117
1298
  if (line && line.kind !== "progress") {
1118
1299
  const last = state.transcript.at(-2);
1119
1300
  if (last && last.text === line.text && last.kind !== "shots") state.transcript.splice(-1, 1);
@@ -1223,13 +1404,27 @@ function renderProject() {
1223
1404
  }
1224
1405
 
1225
1406
  async function refreshSession() {
1226
- state.session = await api("/api/session");
1407
+ if (state.connection) {
1408
+ try { state.session = await api("/api/session"); }
1409
+ catch (error) {
1410
+ // The machine stopped answering (the runtime was closed, or this browser will not reach
1411
+ // loopback). Say so on the hosted page and carry on as a visitor; the saved connection is
1412
+ // dropped so a reload does not loop on the same failure.
1413
+ state.connectionLost = { origin: state.connection.origin, reason: error.message };
1414
+ state.connection = null;
1415
+ saveConnection(null);
1416
+ state.session = await api("/api/session");
1417
+ }
1418
+ } else state.session = await api("/api/session");
1227
1419
  state.csrf = state.session.csrfToken;
1228
1420
  const local = state.session.mode === "local";
1229
- $("#mode-pill").textContent = local ? "Self-host · this machine" : "Cloud · outbound runner";
1230
- $("#onboarding-mode-pill").textContent = local ? "Self-host · this machine" : "Cloud";
1421
+ $("#mode-pill").textContent = local ? (state.connection ? "Connected · your machine" : "Self-host · this machine") : "Cloud · outbound runner";
1422
+ $("#onboarding-mode-pill").textContent = local ? (state.connection ? "Connected · your machine" : "Self-host · this machine") : "Cloud";
1231
1423
  $("#privacy-note-detail").textContent = local ? "Everything runs on this machine. Exploration, replay and merge decisions are deterministic and need no API key." : "Your repository stays in your private Tapp workspace.";
1232
1424
  applyAccessMode();
1425
+ // The setup answer takes a few seconds the first time (doctor asks xcodebuild and adb), so it
1426
+ // follows the session rather than holding it up.
1427
+ if (local) refreshSetup().catch(() => {});
1233
1428
  }
1234
1429
 
1235
1430
  async function refresh() {
@@ -1255,8 +1450,9 @@ async function refresh() {
1255
1450
  state.live = live;
1256
1451
  state.audits = runs.audits || [];
1257
1452
  state.explores = runs.explores || [];
1258
- await loadJourneys();
1453
+ await Promise.all([loadJourneys(), loadEngines()]);
1259
1454
  renderProject();
1455
+ renderEngines();
1260
1456
  }
1261
1457
 
1262
1458
  async function runOperation(name, body = {}, { input = "" } = {}) {
@@ -1264,9 +1460,10 @@ async function runOperation(name, body = {}, { input = "" } = {}) {
1264
1460
  const started = await api(`/api/operations/${name}`, { method:"POST", body:JSON.stringify(body) });
1265
1461
  if (!started.job) return started; // synchronous answers (open a path, a business name)
1266
1462
  state.activeJob = started.job.id;
1463
+ state.activeOperation = name;
1267
1464
  const drawer = $("#operation-drawer");
1268
1465
  drawer.classList.remove("hidden");
1269
- $("#operation-title").textContent = name === "audit" ? "Read-only audit" : pretty(name);
1466
+ $("#operation-title").textContent = name === "audit" ? "Read-only audit" : name === "agent" ? "Your agent is on it" : pretty(name);
1270
1467
  $("#operation-progress").textContent = "Starting";
1271
1468
  $("#operation-progress-bar").style.width = "6%";
1272
1469
  syncTranscriptFromJob(name, { ...started.job, input });
@@ -1302,6 +1499,7 @@ async function runOperation(name, body = {}, { input = "" } = {}) {
1302
1499
  } finally {
1303
1500
  if (state.jobHasFrame) { state.jobHasFrame = false; await new Promise((resolve) => setTimeout(resolve, 200)); stopLiveFrames(); }
1304
1501
  state.activeJob = null;
1502
+ state.activeOperation = "";
1305
1503
  try {
1306
1504
  await refreshSession();
1307
1505
  await refresh();
@@ -1339,13 +1537,39 @@ function answerSelfHost(answer) {
1339
1537
  toast(answer.message, true);
1340
1538
  }
1341
1539
 
1342
- async function startFromPrompt(raw) {
1540
+ let businessRequest = 0;
1541
+ function clearBusinessResults() {
1542
+ businessRequest++;
1543
+ const panel = $("#business-results");
1544
+ panel.replaceChildren();
1545
+ panel.classList.add("hidden");
1546
+ $("#business-hint").classList.toggle("hidden", classifyPrompt($("#prompt-input").value).kind !== "business");
1547
+ }
1548
+ $("#prompt-input").addEventListener("input", clearBusinessResults);
1549
+
1550
+ async function searchBusiness(name) {
1551
+ const request = ++businessRequest;
1552
+ const panel = $("#business-results");
1553
+ panel.textContent = "Searching the App Store…";
1554
+ panel.classList.remove("hidden");
1555
+ const result = await api("/api/operations/open", { method: "POST", body: JSON.stringify({ input: name, searchAppStore: true }) }).catch(() => ({
1556
+ message: "Search could not finish. Enter a website or try again.", matches: [],
1557
+ }));
1558
+ if (request !== businessRequest) return;
1559
+ panel.innerHTML = `<p>${esc(result.message)}</p>` + (result.matches || []).map(app =>
1560
+ `<div class="business-match"><strong>${esc(app.name)}<small>${esc(app.publisher)}</small></strong><a href="${esc(app.listing)}" target="_blank" rel="noreferrer">App Store listing</a>${app.website ? `<button type="button" class="secondary" data-business-site="${esc(app.website)}">Audit ${esc(new URL(app.website).host)}</button>` : "<small>Publisher has no website listed.</small>"}</div>`
1561
+ ).join("");
1562
+ }
1563
+
1564
+ async function startFromPrompt(raw, { readOnly = false } = {}) {
1343
1565
  const prompt = classifyPrompt(raw);
1344
1566
  if (prompt.kind === "empty") return;
1567
+ if (prompt.kind === "business") return searchBusiness(prompt.value);
1568
+ clearBusinessResults();
1345
1569
  if (prompt.kind === "url") {
1346
1570
  // On your own machine, or signed in to a public Studio, a website is explored for real — it
1347
1571
  // can stop at a sign-in and ask you. A visitor only ever reads.
1348
- if (state.session?.mode === "local" || state.session?.access === "account") {
1572
+ if (!readOnly && (state.session?.mode === "local" || state.session?.access === "account")) {
1349
1573
  state.promptRun = true; state.promptPlatform = "web";
1350
1574
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
1351
1575
  document.querySelector(".device-stage")?.classList.remove("hidden");
@@ -1368,7 +1592,7 @@ async function startFromPrompt(raw) {
1368
1592
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
1369
1593
  document.querySelector(".device-stage")?.classList.remove("hidden");
1370
1594
  if (state.session?.access !== "anonymous") document.querySelector(".summary-panel")?.classList.remove("hidden");
1371
- if (state.session?.access === "anonymous") setHeading("Website audit", "Read-only. Nothing on the page is clicked.", { owned: true });
1595
+ setHeading("Website audit", "Read-only. Nothing on the page is clicked.", { owned: true });
1372
1596
  const result = await runOperation("audit", { url: prompt.value }, { input: prompt.value });
1373
1597
  state.selectedRunId = result?.capture?.id || state.selectedRunId;
1374
1598
  return;
@@ -1384,7 +1608,6 @@ async function startFromPrompt(raw) {
1384
1608
  showProduct(); activateView("overview"); renderChat();
1385
1609
  const answer = await runOperation("open", { input: prompt.value }, { input: prompt.value });
1386
1610
  if (answer?.kind === "self-host") { answerSelfHost(answer); return; }
1387
- if (answer?.kind === "business") { answerSelfHost({ message: answer.message }); return; }
1388
1611
  await refreshSession();
1389
1612
  await refresh();
1390
1613
  state.selectedTargetId = "";
@@ -1401,6 +1624,12 @@ async function auditWebsite(url) {
1401
1624
  }
1402
1625
 
1403
1626
  document.addEventListener("click", (event) => {
1627
+ const site = event.target.closest("[data-business-site]");
1628
+ if (site) {
1629
+ $("#prompt-input").value = site.dataset.businessSite;
1630
+ startFromPrompt(site.dataset.businessSite, { readOnly: true }).catch(error => toast(error.message, true));
1631
+ return;
1632
+ }
1404
1633
  const viewButton = event.target.closest("[data-view]");
1405
1634
  if (viewButton && $("#product-shell").contains(viewButton)) activateView(viewButton.dataset.view);
1406
1635
  // "What tapp can drive" is reachable from the first screen, before there is any project.
@@ -1418,9 +1647,40 @@ document.addEventListener("click", (event) => {
1418
1647
  if (runButton) { state.selectedRunId = runButton.dataset.runId; renderRuns(); }
1419
1648
  const suggestion = event.target.closest("[data-prompt]");
1420
1649
  if (suggestion) { const input = $("#prompt-input"); input.value = suggestion.dataset.prompt; input.focus(); input.select(); }
1650
+ if (event.target.closest("[data-disconnect-machine]")) {
1651
+ saveConnection(null); state.connection = null; location.replace(location.pathname);
1652
+ }
1653
+ if (event.target.closest("#chat-prompt-stop")) {
1654
+ api("/api/operations/agent-stop", { method:"POST", body:"{}" }).then((r) => toast(r.stopped ? "Stopping the agent after this step." : "Nothing was running.")).catch((error) => toast(error.message, true));
1655
+ }
1656
+ const engineButton = event.target.closest("[data-engine-select]");
1657
+ if (engineButton) {
1658
+ api("/api/engines", { method:"POST", body: JSON.stringify({ engine: engineButton.dataset.engineSelect }) })
1659
+ .then(async (data) => { state.engines = data; renderEngines(); toast(`${selectedEngine()?.label || "That agent"} drives the chat now.`); await refreshSetup(); })
1660
+ .catch((error) => toast(error.message, true));
1661
+ }
1421
1662
  if (event.target.closest("[data-unlink-studio]")) {
1422
1663
  api("/api/studio-link", { method:"DELETE" }).then(async () => { toast("Disconnected."); await refreshSession(); }).catch((error) => toast(error.message, true));
1423
1664
  }
1665
+ if (event.target.closest("#setup-refresh")) refreshSetup().then(() => toast("Checked again.")).catch((error) => toast(error.message, true));
1666
+ if (event.target.closest("#setup-toggle")) {
1667
+ state.setupCollapsed = !$("#setup-card").classList.contains("collapsed");
1668
+ try { localStorage.setItem("tapp.setupCollapsed", state.setupCollapsed ? "1" : "0"); } catch { /* fine */ }
1669
+ renderSetup();
1670
+ }
1671
+ if (event.target.closest("[data-apikey-forget]")) {
1672
+ api("/api/engines/api-key", { method:"DELETE" }).then(async () => { toast("Key forgotten."); await refreshSetup(); }).catch((error) => toast(error.message, true));
1673
+ }
1674
+ if (event.target.closest("[data-codex-signin]")) {
1675
+ api("/api/engines/codex/sign-in", { method:"POST", body:"{}" }).then(async (data) => {
1676
+ if (data.alreadySignedIn) { toast("Codex is already signed in."); return; }
1677
+ await refreshSetup();
1678
+ watchDeviceAuth();
1679
+ }).catch((error) => toast(error.message, true));
1680
+ }
1681
+ if (event.target.closest("[data-codex-cancel]")) {
1682
+ api("/api/engines/codex/sign-in", { method:"DELETE" }).then(refreshSetup).catch((error) => toast(error.message, true));
1683
+ }
1424
1684
  const planButton = event.target.closest("[data-plan-account]");
1425
1685
  if (planButton) {
1426
1686
  const { planAccount, planKind, planDays } = planButton.dataset;
@@ -1442,13 +1702,47 @@ document.addEventListener("click", (event) => {
1442
1702
  });
1443
1703
 
1444
1704
  document.addEventListener("submit", async (event) => {
1445
- const form = event.target.closest("#link-form");
1705
+ const ask = event.target.closest("#chat-prompt");
1706
+ if (ask) {
1707
+ event.preventDefault();
1708
+ const input = $("#chat-prompt-input");
1709
+ const prompt = String(input?.value || "").trim();
1710
+ if (!prompt || state.activeJob) return;
1711
+ input.value = "";
1712
+ setChatCollapsed(false);
1713
+ runOperation("agent", { prompt, thread: "studio" }, { input: prompt }).catch((error) => toast(error.message, true));
1714
+ return;
1715
+ }
1716
+ const cloudForm = event.target.closest("#cloud-interest");
1717
+ if (cloudForm) {
1718
+ event.preventDefault();
1719
+ try {
1720
+ await api("/api/cloud/interest", { method:"POST", body: JSON.stringify({ email: cloudForm.elements.email?.value || "" }) });
1721
+ cloudForm.classList.add("hidden");
1722
+ const sent = $("#cloud-sent"); if (sent) { sent.textContent = "Noted — we will write when the cloud opens."; sent.classList.remove("hidden"); }
1723
+ } catch (error) { toast(error.message, true); }
1724
+ return;
1725
+ }
1726
+ const keyForm = event.target.closest("#setup-apikey");
1727
+ if (keyForm) {
1728
+ event.preventDefault();
1729
+ const button = keyForm.querySelector("button");
1730
+ if (button) button.disabled = true;
1731
+ try {
1732
+ await api("/api/engines/api-key", { method:"POST", body: JSON.stringify({ key: keyForm.elements.key?.value || "" }) });
1733
+ toast("Key saved on this machine. It bills per use.");
1734
+ await refreshSetup();
1735
+ } catch (error) { toast(error.message, true); }
1736
+ finally { if (button) button.disabled = false; }
1737
+ return;
1738
+ }
1739
+ const form = event.target.closest("form[data-link-form]");
1446
1740
  if (!form) return;
1447
1741
  event.preventDefault();
1448
- const button = $("#link-connect");
1742
+ const button = form.querySelector("button[type=submit]");
1449
1743
  if (button) button.disabled = true;
1450
1744
  try {
1451
- await api("/api/studio-link", { method:"POST", body: JSON.stringify({ origin: $("#link-origin")?.value || "", token: $("#link-token")?.value || "" }) });
1745
+ await api("/api/studio-link", { method:"POST", body: JSON.stringify({ origin: form.elements.origin?.value || "", token: form.elements.token?.value || "" }) });
1452
1746
  toast("Connected. Journeys run here will report to your account.");
1453
1747
  await refreshSession();
1454
1748
  } catch (error) { toast(error.message, true); }
@@ -1570,6 +1864,7 @@ try {
1570
1864
  if (handoff) {
1571
1865
  const input = $("#prompt-input");
1572
1866
  if (input) input.value = handoff;
1573
- await startFromPrompt(handoff);
1867
+ if (classifyPrompt(handoff).kind === "business") { showPrompt(); clearBusinessResults(); }
1868
+ else await startFromPrompt(handoff);
1574
1869
  }
1575
1870
  } catch (error) { toast(error.message, true); }
@@ -52,12 +52,24 @@
52
52
  </div>
53
53
  </section>
54
54
 
55
+ <!-- Setting this machine up (ADR-0012's journey): the runtime, the agent on your own plan,
56
+ what each target needs with the exact fix, and the account. Local only; collapses to one
57
+ line once this machine is ready. -->
58
+ <section class="setup-card hidden" id="setup-card" aria-live="polite">
59
+ <div class="setup-head">
60
+ <div><p class="eyebrow">This machine</p><h2 id="setup-title">Set up tapp here</h2><p id="setup-sub">Everything runs on this machine. Four things to check, once.</p></div>
61
+ <div class="button-row"><button class="quiet" type="button" id="setup-toggle">Hide</button><button class="quiet" type="button" id="setup-refresh">Check again</button></div>
62
+ </div>
63
+ <ol class="setup-steps" id="setup-steps"><li class="empty">Checking this machine…</li></ol>
64
+ </section>
55
65
  <section class="prompt-block">
56
66
  <h1>What should tapp test?</h1>
57
67
  <form class="prompt-form" id="prompt-form" autocomplete="off">
58
68
  <label class="prompt-field"><span class="sr-only">Website, repository, folder, or build</span><input id="prompt-input" name="input" placeholder="A website URL, a GitHub repo, a folder on this Mac, a bundle id, an .app or .apk…" spellcheck="false" required></label>
59
69
  <button class="primary prompt-go" type="submit" id="prompt-start" aria-label="Start">→</button>
60
70
  </form>
71
+ <small id="business-hint" class="prompt-note hidden">Search this name in Apple’s US App Store, or enter the website directly.</small>
72
+ <section id="business-results" class="hidden" aria-live="polite" aria-label="Matching apps"></section>
61
73
  <div class="platform-strip" id="platform-strip" hidden></div>
62
74
  <ul class="prompt-suggestions" aria-label="Examples">
63
75
  <li><button type="button" data-kind="url" data-prompt="https://example.com"><span>⌁</span><b>https://example.com</b><small>audit a website read-only — safe on production, nothing is clicked</small></button></li>
@@ -69,9 +81,16 @@
69
81
  person's own machine, and the page says so — with the command — before anyone types
70
82
  one. Hidden on a local Studio, which is that machine. -->
71
83
  <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>
84
+ <p class="selfhost-lead" id="selfhost-lead"><strong>Everything else runs on your own machine — connect it.</strong> Run this once in a terminal: it opens this page connected to your Mac or PC, and everything — your repositories, iOS and Android builds, macOS apps, staging and localhost — runs there. Nothing leaves it.</p>
85
+ <div class="selfhost-row"><code id="selfhost-command">npx -y @aarwitz/tapp@latest app --connect</code><button class="quiet" type="button" id="selfhost-copy">Copy</button></div>
86
+ <small id="selfhost-note">Needs Node.js 20 or newer. No account needed. If your browser refuses to reach your machine, the same Studio opens at the address the command prints.</small>
87
+ </section>
88
+ <!-- The cloud — tapp running it for you — is coming, not sold (ADR-0011 §3). An address to
89
+ tell, and a way in for an account that already exists. -->
90
+ <section class="selfhost-card hidden" id="cloud-card">
91
+ <p class="selfhost-lead"><strong>Cloud — tapp runs it for you — coming soon.</strong> Leave an address and we will tell you when it opens. <button type="button" class="linklike" data-signin>Have an account? Sign in</button></p>
92
+ <form class="selfhost-row" id="cloud-interest" autocomplete="email"><input name="email" type="email" placeholder="you@company.com" aria-label="Email" required><button class="quiet" type="submit">Tell me</button></form>
93
+ <p class="cloud-sent hidden" id="cloud-sent"></p>
75
94
  </section>
76
95
  <!-- Signing in to a public Studio: an email address and a link, nothing else. Hidden on a
77
96
  local Studio, where the one person at the keyboard is the operator already. -->
@@ -153,6 +172,13 @@
153
172
  <span class="chat-caret" aria-hidden="true">▾</span>
154
173
  </button>
155
174
  <div class="chat-transcript" id="chat-transcript"></div>
175
+ <!-- The person's own agent, driving tapp from here (ADR-0012). Local only, and only when
176
+ an engine on this machine is signed in. -->
177
+ <form class="chat-prompt hidden" id="chat-prompt" autocomplete="off">
178
+ <input id="chat-prompt-input" name="prompt" placeholder="Ask tapp to test something…" aria-label="Ask tapp" maxlength="4000" required>
179
+ <button class="primary" type="submit" id="chat-prompt-send">Send</button>
180
+ <button class="quiet hidden" type="button" id="chat-prompt-stop">Stop</button>
181
+ </form>
156
182
  </aside>
157
183
  </section>
158
184
 
@@ -235,6 +261,13 @@
235
261
  </div>
236
262
  <div id="link-body"></div>
237
263
  </section>
264
+ <!-- Which agent drives tapp from the chat, on whose plan (ADR-0012). Local only. -->
265
+ <section class="panel section hidden" id="engines-panel">
266
+ <div class="section-heading compact">
267
+ <div><p class="eyebrow">Your agent</p><h2>Who drives tapp from the chat</h2><p>tapp signs you in to nothing and holds no token: it finds the coding agent you already signed in to on this machine and drives it on your own plan. In the chat it gets tapp's tools and reading the project — never a shell, never an edit.</p></div>
268
+ </div>
269
+ <div id="engines-list"><div class="empty">Checking this machine…</div></div>
270
+ </section>
238
271
  <section class="panel section" id="journeys-panel">
239
272
  <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>
240
273
  <div id="journeys-list"><div class="empty">No journeys yet.</div></div>