@aarwitz/tapp 0.35.8 → 0.35.10

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,23 @@ 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
+ // A connect link pasted into a tab that is already open changes only the fragment, which is
41
+ // not a page load: take the pair the same way, then load the page properly.
42
+ window.addEventListener("hashchange", () => {
43
+ const pasted = parseConnectFragment(location.hash);
44
+ if (pasted) { saveConnection(pasted); location.replace(location.pathname + location.search); }
45
+ });
46
+ }
18
47
  const $ = (selector) => document.querySelector(selector);
19
48
  const $$ = (selector) => [...document.querySelectorAll(selector)];
20
49
  const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (character) => ({ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":"&#39;" }[character]));
@@ -32,7 +61,8 @@ function toast(message, error = false) {
32
61
 
33
62
  async function api(route, options = {}) {
34
63
  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 || {}) };
64
+ const connected = state.connection && state.connection.origin !== location.origin;
65
+ const headers = { ...(options.body !== undefined ? { "content-type":"application/json" } : {}), ...(mutation ? { "x-tapp-csrf":state.csrf } : {}), ...(connected ? { authorization: `Bearer ${state.connection.token}` } : {}), ...(options.headers || {}) };
36
66
  const response = await fetch(apiRoute(route), { ...options, headers });
37
67
  const data = await response.json().catch(() => ({}));
38
68
  if (response.status === 401 && LOGIN_URL) {
@@ -51,7 +81,14 @@ function captureId(report) {
51
81
  }
52
82
  return report?.capture?.id || "";
53
83
  }
54
- const captureUrl = (id, file = "report.html") => apiRoute(`/evidence/captures/${encodeURIComponent(id)}/${file}`);
84
+ // An image or a report the page shows cannot carry a header, so when this page is driving a
85
+ // runtime on the person's machine the launch secret rides on the query instead (ADR-0011 §4).
86
+ const assetUrl = (route) => {
87
+ const base = apiRoute(route);
88
+ if (!state.connection) return base;
89
+ return `${base}${base.includes("?") ? "&" : "?"}token=${encodeURIComponent(state.connection.token)}`;
90
+ };
91
+ const captureUrl = (id, file = "report.html") => assetUrl(`/evidence/captures/${encodeURIComponent(id)}/${file}`);
55
92
  function evidenceLink(id, label = "Open visual evidence") {
56
93
  return id ? `<a class="button-link" href="${esc(captureUrl(id))}" target="_blank" rel="noreferrer">${esc(label)}</a>` : "";
57
94
  }
@@ -167,11 +204,18 @@ function renderAccount() {
167
204
  const session = state.session || {};
168
205
  const isPublic = session.access === "anonymous" || session.access === "account";
169
206
  for (const slot of document.querySelectorAll("#account-slot, #account-slot-side")) {
207
+ if (state.connection) {
208
+ slot.classList.remove("hidden");
209
+ slot.innerHTML = `<span class="account-email" title="${esc(state.connection.origin)}">your machine</span><button type="button" data-disconnect-machine>Disconnect</button>`;
210
+ continue;
211
+ }
170
212
  slot.classList.toggle("hidden", !isPublic);
171
213
  if (!isPublic) continue;
214
+ // A visitor is not offered a sign-in button up front: the cloud is coming soon, and the way
215
+ // in for an account that already exists sits on that card (ADR-0011 §3).
172
216
  slot.innerHTML = session.access === "account"
173
217
  ? `<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>`;
218
+ : "";
175
219
  }
176
220
  $("#signin-card")?.classList.toggle("hidden", session.access !== "anonymous" || !state.signInOpen);
177
221
  renderSignInOptions();
@@ -221,6 +265,7 @@ function applyAccessMode() {
221
265
  renderPlatformStrip();
222
266
  renderPlatforms();
223
267
  renderStudioLink();
268
+ renderSetup();
224
269
  if (session.access !== "anonymous" && session.access !== "account") return;
225
270
  const signedIn = session.access === "account";
226
271
  const accepts = new Set(session.accepts || ["url"]);
@@ -236,8 +281,11 @@ function applyAccessMode() {
236
281
  button.closest("li")?.classList.toggle("hidden", !usable);
237
282
  }
238
283
  $("#selfhost-card")?.classList.remove("hidden");
284
+ $("#cloud-card")?.classList.toggle("hidden", signedIn);
285
+ const lead = $("#selfhost-lead");
286
+ if (lead && state.connectionLost) lead.innerHTML = `<strong>This page could not reach your machine at ${esc(state.connectionLost.origin)}</strong> (${esc(state.connectionLost.reason)}). If Chrome asked to access devices on your local network, allow it and run the command again. Otherwise open the Studio directly on your machine — the same thing, served from there: <a href="${esc(state.connectionLost.launch)}">${esc(state.connectionLost.origin)}</a>.`;
239
287
  const input = $("#prompt-input");
240
- if (input) input.placeholder = accepts.has("path") ? input.placeholder : "A website URL — https://…";
288
+ if (input && !accepts.has("path")) input.placeholder = "A business name or website URL…";
241
289
  // Everything that only means something against a source repository: a target to build, a
242
290
  // runner, a release gate, a decision. A hosted visitor auditing a URL has none of them, and
243
291
  // showing the empty frames makes a working run look like a broken one.
@@ -546,7 +594,7 @@ function refreshLiveFrame() {
546
594
  if (!image.naturalWidth) loading.classList.remove("hidden");
547
595
  image.onload = () => { loading.classList.add("hidden"); scheduleLiveFrame(); };
548
596
  image.onerror = () => { loading.textContent = "Live frame could not be captured. The semantic controls remain available."; scheduleLiveFrame(); };
549
- image.src = apiRoute(`${source}?at=${Date.now()}`);
597
+ image.src = assetUrl(`${source}?at=${Date.now()}`);
550
598
  }
551
599
  function scheduleLiveFrame() { clearTimeout(state.frameTimer); if (frameSource()) state.frameTimer = setTimeout(refreshLiveFrame, 1500); }
552
600
  function stopLiveFrames() { clearTimeout(state.frameTimer); state.frameTimer = null; }
@@ -644,13 +692,96 @@ function renderStudioLink() {
644
692
  const link = state.session?.studioLink;
645
693
  body.innerHTML = link
646
694
  ? `<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>
695
+ : linkFormMarkup();
696
+ }
697
+
698
+ function linkFormMarkup() {
699
+ return `<form class="link-form" data-link-form autocomplete="off">
700
+ <input name="origin" type="url" value="https://app.runtapp.com" aria-label="Studio URL" spellcheck="false">
701
+ <input name="token" type="password" placeholder="tapp_… — a token from your Studio, under “Your coding agent”" aria-label="Token" autocomplete="off" required>
702
+ <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
703
  </form>`;
652
704
  }
653
705
 
706
+ // ——— Setting this machine up (ADR-0012) ——————————————————————————————————————————————————
707
+ // The journey's first screen on a local Studio: the runtime, the agent on your own plan, what
708
+ // each target needs with the exact fix, and the account. Collapses to one line once ready.
709
+ async function loadSetup() {
710
+ if (state.session?.mode !== "local") { state.setup = null; return; }
711
+ state.setup = await api("/api/setup").catch(() => null);
712
+ if (state.setup) state.engines = { engines: state.setup.engines, selected: state.setup.selected };
713
+ }
714
+
715
+ function setupEngine() {
716
+ return (state.setup?.engines || []).find((engine) => engine.id === state.setup?.selected) || null;
717
+ }
718
+
719
+ function renderSetup() {
720
+ const card = $("#setup-card");
721
+ if (!card) return;
722
+ const local = state.session?.mode === "local";
723
+ card.classList.toggle("hidden", !local);
724
+ if (!local) return;
725
+ const steps = $("#setup-steps");
726
+ const setup = state.setup;
727
+ if (!setup) { steps.innerHTML = '<li class="empty">Checking this machine…</li>'; return; }
728
+ const engine = setupEngine();
729
+ const agentOk = !!(engine?.usable && engine?.drives);
730
+ const readyTargets = (setup.targets || []).filter((t) => t.ready).map((t) => t.label);
731
+ let stored = null;
732
+ try { stored = localStorage.getItem("tapp.setupCollapsed"); } catch { /* fine */ }
733
+ const collapsed = state.setupCollapsed ?? (stored !== null ? stored === "1" : agentOk && readyTargets.length > 1);
734
+ card.classList.toggle("collapsed", collapsed);
735
+ $("#setup-toggle").textContent = collapsed ? "Show" : "Hide";
736
+ $("#setup-title").textContent = agentOk ? "This machine is ready" : "Set up tapp here";
737
+ 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`;
738
+ $("#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"}`;
739
+
740
+ const mark = (ok, warn = false) => ok ? "✓" : warn ? "⚠️" : "○";
741
+ 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>`;
742
+ const r = setup.runtime || {};
743
+ 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.")}` : "";
744
+ 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>`;
745
+
746
+ const claude = (setup.engines || []).find((e) => e.id === "claude");
747
+ const codex = (setup.engines || []).find((e) => e.id === "codex");
748
+ 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("");
749
+ const codexSignIn = codex && codex.state !== "missing" && codex.billing !== "plan"
750
+ ? (setup.deviceAuth
751
+ ? `<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>`
752
+ : `<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>`)
753
+ : "";
754
+ const apiKey = setup.apiKey?.set
755
+ ? `<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>`
756
+ : `<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>`;
757
+ 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>`;
758
+
759
+ 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>`;
760
+
761
+ 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>`;
762
+ steps.innerHTML = runtime + agent + targets + account;
763
+ }
764
+
765
+ async function refreshSetup() {
766
+ await loadSetup();
767
+ renderSetup();
768
+ renderEngines();
769
+ renderChatPrompt();
770
+ }
771
+
772
+ // While a Codex device sign-in is open, look every few seconds for it to finish.
773
+ function watchDeviceAuth() {
774
+ if (state.deviceAuthPoll) return;
775
+ state.deviceAuthPoll = setInterval(async () => {
776
+ await refreshSetup();
777
+ const codex = (state.setup?.engines || []).find((e) => e.id === "codex");
778
+ if (!state.setup?.deviceAuth || codex?.billing === "plan") {
779
+ clearInterval(state.deviceAuthPoll); state.deviceAuthPoll = null;
780
+ if (codex?.billing === "plan") toast("Codex is signed in with your ChatGPT plan.");
781
+ }
782
+ }, 3000);
783
+ }
784
+
654
785
  function renderJourneys() {
655
786
  const node = $("#journeys-list");
656
787
  if (!node) return;
@@ -1039,6 +1170,7 @@ function renderChat() {
1039
1170
  }).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
1171
  node.innerHTML = lines;
1041
1172
  if (stickToBottom) node.scrollTop = node.scrollHeight;
1173
+ renderChatPrompt();
1042
1174
  const progress = [...state.transcript].reverse().find((entry) => entry.kind === "progress");
1043
1175
  $("#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
1176
  }
@@ -1084,6 +1216,54 @@ function setChatCollapsed(collapsed) {
1084
1216
 
1085
1217
  function pushLine(entry) { state.transcript.push({ at: new Date().toISOString(), ...entry }); }
1086
1218
 
1219
+ // ——— Your agent (ADR-0012) ———————————————————————————————————————————————————————————————————
1220
+ // The chat can ask the person's own coding agent — found on this machine, signed in to their own
1221
+ // plan — to drive tapp. Local only; nothing on a hosted Studio can reach a laptop.
1222
+ function selectedEngine() {
1223
+ const engines = state.engines?.engines || [];
1224
+ return engines.find((engine) => engine.id === state.engines?.selected) || null;
1225
+ }
1226
+
1227
+ function renderChatPrompt() {
1228
+ const form = $("#chat-prompt");
1229
+ if (!form) return;
1230
+ const engine = selectedEngine();
1231
+ const local = state.session?.mode === "local";
1232
+ form.classList.toggle("hidden", !(local && engine?.usable && engine?.drives));
1233
+ const input = $("#chat-prompt-input");
1234
+ const send = $("#chat-prompt-send");
1235
+ const stop = $("#chat-prompt-stop");
1236
+ const busy = !!state.activeJob;
1237
+ if (input) input.disabled = busy;
1238
+ if (send) send.disabled = busy;
1239
+ if (stop) stop.classList.toggle("hidden", !(busy && state.activeOperation === "agent"));
1240
+ }
1241
+
1242
+ async function loadEngines() {
1243
+ if (state.session?.mode !== "local") { state.engines = null; return; }
1244
+ state.engines = await api("/api/engines").catch(() => null);
1245
+ }
1246
+
1247
+ function renderEngines() {
1248
+ const panel = $("#engines-panel");
1249
+ const node = $("#engines-list");
1250
+ if (!panel || !node) return;
1251
+ const local = state.session?.mode === "local";
1252
+ panel.classList.toggle("hidden", !local);
1253
+ if (!local) return;
1254
+ const data = state.engines;
1255
+ if (!data) { node.innerHTML = '<div class="empty">Checking this machine…</div>'; return; }
1256
+ const pill = (engine) => engine.state === "ok" ? `<span class="journey-status passing">signed in</span>`
1257
+ : engine.state === "warning" ? `<span class="journey-status warning">${esc(engine.billing === "api-key" ? "API key" : "not signed in")}</span>`
1258
+ : `<span class="journey-status never">not installed</span>`;
1259
+ node.innerHTML = data.engines.map((engine) => `<div class="engine-row">
1260
+ <span>${pill(engine)}</span>
1261
+ <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>
1262
+ <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>
1263
+ </div>`).join("");
1264
+ renderChatPrompt();
1265
+ }
1266
+
1087
1267
  // A screenshot the engine wrote during the run, kept as a thumbnail in the transcript. Captured
1088
1268
  // once per screen name the engine reports, and never more often than every few seconds.
1089
1269
  async function keepShot(screen) {
@@ -1105,15 +1285,22 @@ async function keepShot(screen) {
1105
1285
 
1106
1286
  function syncTranscriptFromJob(name, job) {
1107
1287
  if (state.transcriptSource !== job.id) {
1108
- state.transcript = [{ at: job.createdAt, kind: "phase", icon: "🚀", text: startLine(name, job) }];
1288
+ // A run starts a fresh transcript. A chat turn with the agent is a conversation: the person's
1289
+ // words go in as a line of their own, and an earlier turn in the same thread stays on screen.
1290
+ const first = name === "agent"
1291
+ ? { at: job.createdAt, kind: "you", icon: "🧑", text: job.input || "" }
1292
+ : { at: job.createdAt, kind: "phase", icon: "🚀", text: startLine(name, job) };
1293
+ if (name === "agent" && state.transcriptKind === "agent") state.transcript.push(first);
1294
+ else state.transcript = [first];
1295
+ state.transcriptKind = name === "agent" ? "agent" : "run";
1109
1296
  state.transcriptSource = job.id;
1110
1297
  state.shotScreens = new Set();
1111
1298
  state.lastShotAt = 0;
1112
1299
  }
1113
- const seen = state.transcript.filter((entry) => entry.source === "job").length;
1300
+ const seen = state.transcript.filter((entry) => entry.source === job.id).length;
1114
1301
  for (const entry of job.progress.slice(seen)) {
1115
1302
  const line = narrate(entry, { platform: currentPlatform() });
1116
- state.transcript.push({ ...(line || { kind: "step", icon: "•", text: "" }), at: entry.at, source: "job" });
1303
+ state.transcript.push({ ...(line || { kind: "step", icon: "•", text: "" }), at: entry.at, source: job.id });
1117
1304
  if (line && line.kind !== "progress") {
1118
1305
  const last = state.transcript.at(-2);
1119
1306
  if (last && last.text === line.text && last.kind !== "shots") state.transcript.splice(-1, 1);
@@ -1223,13 +1410,31 @@ function renderProject() {
1223
1410
  }
1224
1411
 
1225
1412
  async function refreshSession() {
1226
- state.session = await api("/api/session");
1413
+ if (state.connection) {
1414
+ // Chrome asks the person before a page may reach their local network, and the fetch waits
1415
+ // on their answer; give that long, then stop waiting rather than show a blank page.
1416
+ const waited = new Promise((_, reject) => setTimeout(() => reject(new Error("this page was not allowed to reach your machine")), 25_000));
1417
+ try { state.session = await Promise.race([api("/api/session"), waited]); }
1418
+ catch (error) {
1419
+ // The machine stopped answering (the runtime was closed, Chrome refused, or this browser
1420
+ // will not reach loopback). Say so on the hosted page, with the way round it, and carry on
1421
+ // as a visitor; the saved connection is dropped so a reload does not loop on the failure.
1422
+ state.connectionLost = { origin: state.connection.origin, launch: `${state.connection.origin}/?token=${encodeURIComponent(state.connection.token)}`, reason: error.message };
1423
+ state.connection = null;
1424
+ saveConnection(null);
1425
+ state.session = await api("/api/session");
1426
+ }
1427
+ } else state.session = await api("/api/session");
1428
+ $("#connecting-note")?.classList.add("hidden");
1227
1429
  state.csrf = state.session.csrfToken;
1228
1430
  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";
1431
+ $("#mode-pill").textContent = local ? (state.connection ? "Connected · your machine" : "Self-host · this machine") : "Cloud · outbound runner";
1432
+ $("#onboarding-mode-pill").textContent = local ? (state.connection ? "Connected · your machine" : "Self-host · this machine") : "Cloud";
1231
1433
  $("#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
1434
  applyAccessMode();
1435
+ // The setup answer takes a few seconds the first time (doctor asks xcodebuild and adb), so it
1436
+ // follows the session rather than holding it up.
1437
+ if (local) refreshSetup().catch(() => {});
1233
1438
  }
1234
1439
 
1235
1440
  async function refresh() {
@@ -1255,8 +1460,9 @@ async function refresh() {
1255
1460
  state.live = live;
1256
1461
  state.audits = runs.audits || [];
1257
1462
  state.explores = runs.explores || [];
1258
- await loadJourneys();
1463
+ await Promise.all([loadJourneys(), loadEngines()]);
1259
1464
  renderProject();
1465
+ renderEngines();
1260
1466
  }
1261
1467
 
1262
1468
  async function runOperation(name, body = {}, { input = "" } = {}) {
@@ -1264,9 +1470,10 @@ async function runOperation(name, body = {}, { input = "" } = {}) {
1264
1470
  const started = await api(`/api/operations/${name}`, { method:"POST", body:JSON.stringify(body) });
1265
1471
  if (!started.job) return started; // synchronous answers (open a path, a business name)
1266
1472
  state.activeJob = started.job.id;
1473
+ state.activeOperation = name;
1267
1474
  const drawer = $("#operation-drawer");
1268
1475
  drawer.classList.remove("hidden");
1269
- $("#operation-title").textContent = name === "audit" ? "Read-only audit" : pretty(name);
1476
+ $("#operation-title").textContent = name === "audit" ? "Read-only audit" : name === "agent" ? "Your agent is on it" : pretty(name);
1270
1477
  $("#operation-progress").textContent = "Starting";
1271
1478
  $("#operation-progress-bar").style.width = "6%";
1272
1479
  syncTranscriptFromJob(name, { ...started.job, input });
@@ -1302,6 +1509,7 @@ async function runOperation(name, body = {}, { input = "" } = {}) {
1302
1509
  } finally {
1303
1510
  if (state.jobHasFrame) { state.jobHasFrame = false; await new Promise((resolve) => setTimeout(resolve, 200)); stopLiveFrames(); }
1304
1511
  state.activeJob = null;
1512
+ state.activeOperation = "";
1305
1513
  try {
1306
1514
  await refreshSession();
1307
1515
  await refresh();
@@ -1339,13 +1547,39 @@ function answerSelfHost(answer) {
1339
1547
  toast(answer.message, true);
1340
1548
  }
1341
1549
 
1342
- async function startFromPrompt(raw) {
1550
+ let businessRequest = 0;
1551
+ function clearBusinessResults() {
1552
+ businessRequest++;
1553
+ const panel = $("#business-results");
1554
+ panel.replaceChildren();
1555
+ panel.classList.add("hidden");
1556
+ $("#business-hint").classList.toggle("hidden", classifyPrompt($("#prompt-input").value).kind !== "business");
1557
+ }
1558
+ $("#prompt-input").addEventListener("input", clearBusinessResults);
1559
+
1560
+ async function searchBusiness(name) {
1561
+ const request = ++businessRequest;
1562
+ const panel = $("#business-results");
1563
+ panel.textContent = "Searching the App Store…";
1564
+ panel.classList.remove("hidden");
1565
+ const result = await api("/api/operations/open", { method: "POST", body: JSON.stringify({ input: name, searchAppStore: true }) }).catch(() => ({
1566
+ message: "Search could not finish. Enter a website or try again.", matches: [],
1567
+ }));
1568
+ if (request !== businessRequest) return;
1569
+ panel.innerHTML = `<p>${esc(result.message)}</p>` + (result.matches || []).map(app =>
1570
+ `<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>`
1571
+ ).join("");
1572
+ }
1573
+
1574
+ async function startFromPrompt(raw, { readOnly = false } = {}) {
1343
1575
  const prompt = classifyPrompt(raw);
1344
1576
  if (prompt.kind === "empty") return;
1577
+ if (prompt.kind === "business") return searchBusiness(prompt.value);
1578
+ clearBusinessResults();
1345
1579
  if (prompt.kind === "url") {
1346
1580
  // On your own machine, or signed in to a public Studio, a website is explored for real — it
1347
1581
  // can stop at a sign-in and ask you. A visitor only ever reads.
1348
- if (state.session?.mode === "local" || state.session?.access === "account") {
1582
+ if (!readOnly && (state.session?.mode === "local" || state.session?.access === "account")) {
1349
1583
  state.promptRun = true; state.promptPlatform = "web";
1350
1584
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
1351
1585
  document.querySelector(".device-stage")?.classList.remove("hidden");
@@ -1368,7 +1602,7 @@ async function startFromPrompt(raw) {
1368
1602
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
1369
1603
  document.querySelector(".device-stage")?.classList.remove("hidden");
1370
1604
  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 });
1605
+ setHeading("Website audit", "Read-only. Nothing on the page is clicked.", { owned: true });
1372
1606
  const result = await runOperation("audit", { url: prompt.value }, { input: prompt.value });
1373
1607
  state.selectedRunId = result?.capture?.id || state.selectedRunId;
1374
1608
  return;
@@ -1384,7 +1618,6 @@ async function startFromPrompt(raw) {
1384
1618
  showProduct(); activateView("overview"); renderChat();
1385
1619
  const answer = await runOperation("open", { input: prompt.value }, { input: prompt.value });
1386
1620
  if (answer?.kind === "self-host") { answerSelfHost(answer); return; }
1387
- if (answer?.kind === "business") { answerSelfHost({ message: answer.message }); return; }
1388
1621
  await refreshSession();
1389
1622
  await refresh();
1390
1623
  state.selectedTargetId = "";
@@ -1401,6 +1634,12 @@ async function auditWebsite(url) {
1401
1634
  }
1402
1635
 
1403
1636
  document.addEventListener("click", (event) => {
1637
+ const site = event.target.closest("[data-business-site]");
1638
+ if (site) {
1639
+ $("#prompt-input").value = site.dataset.businessSite;
1640
+ startFromPrompt(site.dataset.businessSite, { readOnly: true }).catch(error => toast(error.message, true));
1641
+ return;
1642
+ }
1404
1643
  const viewButton = event.target.closest("[data-view]");
1405
1644
  if (viewButton && $("#product-shell").contains(viewButton)) activateView(viewButton.dataset.view);
1406
1645
  // "What tapp can drive" is reachable from the first screen, before there is any project.
@@ -1418,9 +1657,40 @@ document.addEventListener("click", (event) => {
1418
1657
  if (runButton) { state.selectedRunId = runButton.dataset.runId; renderRuns(); }
1419
1658
  const suggestion = event.target.closest("[data-prompt]");
1420
1659
  if (suggestion) { const input = $("#prompt-input"); input.value = suggestion.dataset.prompt; input.focus(); input.select(); }
1660
+ if (event.target.closest("[data-disconnect-machine]")) {
1661
+ saveConnection(null); state.connection = null; location.replace(location.pathname);
1662
+ }
1663
+ if (event.target.closest("#chat-prompt-stop")) {
1664
+ 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));
1665
+ }
1666
+ const engineButton = event.target.closest("[data-engine-select]");
1667
+ if (engineButton) {
1668
+ api("/api/engines", { method:"POST", body: JSON.stringify({ engine: engineButton.dataset.engineSelect }) })
1669
+ .then(async (data) => { state.engines = data; renderEngines(); toast(`${selectedEngine()?.label || "That agent"} drives the chat now.`); await refreshSetup(); })
1670
+ .catch((error) => toast(error.message, true));
1671
+ }
1421
1672
  if (event.target.closest("[data-unlink-studio]")) {
1422
1673
  api("/api/studio-link", { method:"DELETE" }).then(async () => { toast("Disconnected."); await refreshSession(); }).catch((error) => toast(error.message, true));
1423
1674
  }
1675
+ if (event.target.closest("#setup-refresh")) refreshSetup().then(() => toast("Checked again.")).catch((error) => toast(error.message, true));
1676
+ if (event.target.closest("#setup-toggle")) {
1677
+ state.setupCollapsed = !$("#setup-card").classList.contains("collapsed");
1678
+ try { localStorage.setItem("tapp.setupCollapsed", state.setupCollapsed ? "1" : "0"); } catch { /* fine */ }
1679
+ renderSetup();
1680
+ }
1681
+ if (event.target.closest("[data-apikey-forget]")) {
1682
+ api("/api/engines/api-key", { method:"DELETE" }).then(async () => { toast("Key forgotten."); await refreshSetup(); }).catch((error) => toast(error.message, true));
1683
+ }
1684
+ if (event.target.closest("[data-codex-signin]")) {
1685
+ api("/api/engines/codex/sign-in", { method:"POST", body:"{}" }).then(async (data) => {
1686
+ if (data.alreadySignedIn) { toast("Codex is already signed in."); return; }
1687
+ await refreshSetup();
1688
+ watchDeviceAuth();
1689
+ }).catch((error) => toast(error.message, true));
1690
+ }
1691
+ if (event.target.closest("[data-codex-cancel]")) {
1692
+ api("/api/engines/codex/sign-in", { method:"DELETE" }).then(refreshSetup).catch((error) => toast(error.message, true));
1693
+ }
1424
1694
  const planButton = event.target.closest("[data-plan-account]");
1425
1695
  if (planButton) {
1426
1696
  const { planAccount, planKind, planDays } = planButton.dataset;
@@ -1442,13 +1712,47 @@ document.addEventListener("click", (event) => {
1442
1712
  });
1443
1713
 
1444
1714
  document.addEventListener("submit", async (event) => {
1445
- const form = event.target.closest("#link-form");
1715
+ const ask = event.target.closest("#chat-prompt");
1716
+ if (ask) {
1717
+ event.preventDefault();
1718
+ const input = $("#chat-prompt-input");
1719
+ const prompt = String(input?.value || "").trim();
1720
+ if (!prompt || state.activeJob) return;
1721
+ input.value = "";
1722
+ setChatCollapsed(false);
1723
+ runOperation("agent", { prompt, thread: "studio" }, { input: prompt }).catch((error) => toast(error.message, true));
1724
+ return;
1725
+ }
1726
+ const cloudForm = event.target.closest("#cloud-interest");
1727
+ if (cloudForm) {
1728
+ event.preventDefault();
1729
+ try {
1730
+ await api("/api/cloud/interest", { method:"POST", body: JSON.stringify({ email: cloudForm.elements.email?.value || "" }) });
1731
+ cloudForm.classList.add("hidden");
1732
+ const sent = $("#cloud-sent"); if (sent) { sent.textContent = "Noted — we will write when the cloud opens."; sent.classList.remove("hidden"); }
1733
+ } catch (error) { toast(error.message, true); }
1734
+ return;
1735
+ }
1736
+ const keyForm = event.target.closest("#setup-apikey");
1737
+ if (keyForm) {
1738
+ event.preventDefault();
1739
+ const button = keyForm.querySelector("button");
1740
+ if (button) button.disabled = true;
1741
+ try {
1742
+ await api("/api/engines/api-key", { method:"POST", body: JSON.stringify({ key: keyForm.elements.key?.value || "" }) });
1743
+ toast("Key saved on this machine. It bills per use.");
1744
+ await refreshSetup();
1745
+ } catch (error) { toast(error.message, true); }
1746
+ finally { if (button) button.disabled = false; }
1747
+ return;
1748
+ }
1749
+ const form = event.target.closest("form[data-link-form]");
1446
1750
  if (!form) return;
1447
1751
  event.preventDefault();
1448
- const button = $("#link-connect");
1752
+ const button = form.querySelector("button[type=submit]");
1449
1753
  if (button) button.disabled = true;
1450
1754
  try {
1451
- await api("/api/studio-link", { method:"POST", body: JSON.stringify({ origin: $("#link-origin")?.value || "", token: $("#link-token")?.value || "" }) });
1755
+ await api("/api/studio-link", { method:"POST", body: JSON.stringify({ origin: form.elements.origin?.value || "", token: form.elements.token?.value || "" }) });
1452
1756
  toast("Connected. Journeys run here will report to your account.");
1453
1757
  await refreshSession();
1454
1758
  } catch (error) { toast(error.message, true); }
@@ -1551,6 +1855,14 @@ function handoffTarget() {
1551
1855
 
1552
1856
  try {
1553
1857
  try { setChatCollapsed(localStorage.getItem("tapp:chat-collapsed") === "1"); } catch { /* storage may be unavailable */ }
1858
+ if (state.connection) {
1859
+ // Say what is happening before the machine answers: a blank page while Chrome asks for
1860
+ // permission reads as broken.
1861
+ showPrompt();
1862
+ $("#onboarding-mode-pill").textContent = "Connecting · your machine";
1863
+ const note = $("#connecting-note");
1864
+ if (note) { note.textContent = `Connecting to your machine at ${state.connection.origin}… If Chrome asks whether this site may access devices on your local network, allow it — that is your own machine.`; note.classList.remove("hidden"); }
1865
+ }
1554
1866
  await refreshSession();
1555
1867
  await refresh();
1556
1868
  if (state.project?.connected && !state.project?.state?.inspected) await runOperation("initialize", { write:true });
@@ -1570,6 +1882,7 @@ try {
1570
1882
  if (handoff) {
1571
1883
  const input = $("#prompt-input");
1572
1884
  if (input) input.value = handoff;
1573
- await startFromPrompt(handoff);
1885
+ if (classifyPrompt(handoff).kind === "business") { showPrompt(); clearBusinessResults(); }
1886
+ else await startFromPrompt(handoff);
1574
1887
  }
1575
1888
  } catch (error) { toast(error.message, true); }