@aarwitz/tapp 0.35.7 → 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
  }
@@ -153,15 +184,32 @@ function activateView(view) {
153
184
  // On a public Studio a person is a visitor until they sign in, and an account after. Both slots
154
185
  // (prompt screen and sidebar) show the same thing. A local Studio has neither: the one person at
155
186
  // the keyboard is the operator.
187
+ // What the cloud will do for this account, in a word: the trial's days left, that it ended, or
188
+ // that there is nothing to count (ADR-0011 §3). Never shown to the deployment's owner.
189
+ function planPill(plan) {
190
+ if (!plan || plan.kind === "owner") return "";
191
+ if (plan.kind === "paid") return `<span class="journey-status passing" title="On a plan">plan</span>`;
192
+ if (plan.kind === "lapsed") return `<span class="journey-status failing" title="Cloud runs are for accounts on a plan — write to hello@runtapp.com">trial ended</span>`;
193
+ const days = plan.daysLeft ?? 0;
194
+ return `<span class="journey-status ${days <= 3 ? "failing" : "never"}" title="Free trial until ${esc(String(plan.endsAt || "").slice(0, 10))}">trial · ${esc(String(days))} day${days === 1 ? "" : "s"} left</span>`;
195
+ }
196
+
156
197
  function renderAccount() {
157
198
  const session = state.session || {};
158
199
  const isPublic = session.access === "anonymous" || session.access === "account";
159
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
+ }
160
206
  slot.classList.toggle("hidden", !isPublic);
161
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).
162
210
  slot.innerHTML = session.access === "account"
163
- ? `<span class="account-email" title="${esc(session.email || "")}">${esc(session.email || "")}</span><button type="button" data-signout>Sign out</button>`
164
- : `<button type="button" class="primary" data-signin>Sign in</button>`;
211
+ ? `<span class="account-email" title="${esc(session.email || "")}">${esc(session.email || "")}</span>${planPill(session.plan)}<button type="button" data-signout>Sign out</button>`
212
+ : "";
165
213
  }
166
214
  $("#signin-card")?.classList.toggle("hidden", session.access !== "anonymous" || !state.signInOpen);
167
215
  renderSignInOptions();
@@ -210,21 +258,28 @@ function applyAccessMode() {
210
258
  // one where most of it says "ready".
211
259
  renderPlatformStrip();
212
260
  renderPlatforms();
261
+ renderStudioLink();
262
+ renderSetup();
213
263
  if (session.access !== "anonymous" && session.access !== "account") return;
214
264
  const signedIn = session.access === "account";
215
265
  const accepts = new Set(session.accepts || ["url"]);
216
- // A target this Studio cannot START is still a thing tapp does. It used to be deleted from
217
- // the screen, which is how a cross-platform product came to look like a website checker: the
218
- // hosted Studio erased every mention of iOS, Android and folders. Keep them, mark them, and
219
- // let the answer be "here is where that runs" (ADR-0010).
266
+ // A target this Studio cannot START is still a thing tapp does — on the person's own machine.
267
+ // It used to be deleted from the screen, which is how a cross-platform product came to look
268
+ // like a website checker; then dimmed but offered (ADR-0010), so a stranger learned what the
269
+ // page could not do by trying it. Now the self-host card names it, with the command, before
270
+ // anyone types it (ADR-0011): an example nobody can start here is not offered as something to
271
+ // type here. Typing one anyway still gets the "here is where that runs" answer.
220
272
  for (const button of document.querySelectorAll("[data-kind]")) {
221
273
  const kind = button.dataset.kind;
222
274
  const usable = kind === "url" ? accepts.has("url") : accepts.has(kind);
223
- button.closest("li")?.classList.remove("hidden");
224
- button.classList.toggle("elsewhere", !usable);
275
+ button.closest("li")?.classList.toggle("hidden", !usable);
225
276
  }
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.`;
226
281
  const input = $("#prompt-input");
227
- if (input) input.placeholder = accepts.has("path") ? input.placeholder : "A website URL — or an .app, .apk or repo to be told where it runs…";
282
+ if (input && !accepts.has("path")) input.placeholder = "A business name or website URL…";
228
283
  // Everything that only means something against a source repository: a target to build, a
229
284
  // runner, a release gate, a decision. A hosted visitor auditing a URL has none of them, and
230
285
  // showing the empty frames makes a working run look like a broken one.
@@ -237,8 +292,8 @@ function applyAccessMode() {
237
292
  if (!state.headingOwnedByRun) setHeading("tapp", signedIn ? "Give it a website. If there is a sign-in, I will ask you for a test account and remember it." : "Give it a public website and it will audit the pages read-only.");
238
293
  const note = $("#privacy-note-detail");
239
294
  if (note) note.textContent = signedIn
240
- ? "Websites are explored in the cloud. Test accounts you give tapp are kept encrypted, used only to sign in, and never shown again. iOS, Android and folders on your own machine run the same Studio there: npx -y @aarwitz/tapp@latest app"
241
- : "Websites are audited read-only in the cloud; nothing is clicked. Sign in to go inside a site. iOS, Android and folders on your own machine run the same Studio there: npx -y @aarwitz/tapp@latest app";
295
+ ? "Public websites are explored in the cloud. Test accounts you give tapp are kept encrypted, used only to sign in, and never shown again."
296
+ : "Public websites are audited read-only in the cloud; nothing is clicked. Sign in to go inside a site from here.";
242
297
  $("#actors-panel")?.classList.toggle("hidden", !signedIn);
243
298
  $("#journeys-panel")?.classList.toggle("hidden", !signedIn);
244
299
  $("#agent-panel")?.classList.toggle("hidden", !signedIn);
@@ -346,7 +401,7 @@ function renderAdmin() {
346
401
 
347
402
  <section class="panel section">
348
403
  <div class="section-heading compact"><div><p class="eyebrow">Accounts</p><h2>People with a tapp account <i class="zero">${data.accounts.length}</i></h2><p>Test accounts are counted, never shown — tapp cannot show them.</p></div></div>
349
- ${data.accounts.length ? data.accounts.map((account) => `<div class="actor-row"><span><strong>${esc(account.email)}</strong>${owner(account.email) ? ' <small class="journey-status passing">owner</small>' : ""}<br><small>joined ${esc(compactDate(account.createdAt))}${account.lastSeenAt ? ` · last seen ${esc(compactDate(account.lastSeenAt))}` : ""}</small></span><span><small>${account.journeys} journey${account.journeys === 1 ? "" : "s"}${account.failing ? ` · <b class="journey-status failing">${account.failing} failing</b>` : ""}${account.neverRun ? ` · ${account.neverRun} never run` : ""}</small></span><span><small>${account.testAccounts} test account${account.testAccounts === 1 ? "" : "s"} · ${account.tokens} token${account.tokens === 1 ? "" : "s"}</small></span></div>`).join("") : '<div class="empty">Nobody has signed in yet.</div>'}
404
+ ${data.accounts.length ? data.accounts.map((account) => `<div class="actor-row"><span><strong>${esc(account.email)}</strong>${owner(account.email) ? ' <small class="journey-status passing">owner</small>' : ` ${planPill(account.plan)}`}<br><small>joined ${esc(compactDate(account.createdAt))}${account.lastSeenAt ? ` · last seen ${esc(compactDate(account.lastSeenAt))}` : ""}</small></span><span><small>${account.journeys} journey${account.journeys === 1 ? "" : "s"}${account.failing ? ` · <b class="journey-status failing">${account.failing} failing</b>` : ""}${account.neverRun ? ` · ${account.neverRun} never run` : ""}<br>${account.testAccounts} test account${account.testAccounts === 1 ? "" : "s"} · ${account.tokens} token${account.tokens === 1 ? "" : "s"}</small></span><span class="journey-actions">${owner(account.email) ? "" : `<button class="quiet" type="button" data-plan-account="${esc(account.id)}" data-plan-kind="trial" data-plan-days="30">+30 days</button>${account.plan?.kind === "paid" ? "" : `<button class="quiet" type="button" data-plan-account="${esc(account.id)}" data-plan-kind="paid">Mark paid</button>`}`}</span></div>`).join("") : '<div class="empty">Nobody has signed in yet.</div>'}
350
405
  </section>
351
406
 
352
407
  <section class="panel section">
@@ -533,7 +588,7 @@ function refreshLiveFrame() {
533
588
  if (!image.naturalWidth) loading.classList.remove("hidden");
534
589
  image.onload = () => { loading.classList.add("hidden"); scheduleLiveFrame(); };
535
590
  image.onerror = () => { loading.textContent = "Live frame could not be captured. The semantic controls remain available."; scheduleLiveFrame(); };
536
- image.src = apiRoute(`${source}?at=${Date.now()}`);
591
+ image.src = assetUrl(`${source}?at=${Date.now()}`);
537
592
  }
538
593
  function scheduleLiveFrame() { clearTimeout(state.frameTimer); if (frameSource()) state.frameTimer = setTimeout(refreshLiveFrame, 1500); }
539
594
  function stopLiveFrames() { clearTimeout(state.frameTimer); state.frameTimer = null; }
@@ -620,6 +675,107 @@ function journeyStatus(status) {
620
675
  return `<span class="journey-status ${status.passed ? "passing" : "failing"}">${status.passed ? "passing" : "failing"} · ${esc(compactDate(status.at))}</span>`;
621
676
  }
622
677
 
678
+ // The link from this machine to an account on a hosted Studio (ADR-0011 §4). Local only.
679
+ function renderStudioLink() {
680
+ const panel = $("#link-panel");
681
+ const body = $("#link-body");
682
+ if (!panel || !body) return;
683
+ const local = state.session?.mode === "local";
684
+ panel.classList.toggle("hidden", !local);
685
+ if (!local) return;
686
+ const link = state.session?.studioLink;
687
+ body.innerHTML = link
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>`
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>
697
+ </form>`;
698
+ }
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
+
623
779
  function renderJourneys() {
624
780
  const node = $("#journeys-list");
625
781
  if (!node) return;
@@ -634,7 +790,9 @@ function renderJourneys() {
634
790
  if (!journeys.length) { node.innerHTML = '<div class="empty">No journeys yet. Explore a site — when a run gets somewhere, tapp offers to keep it.</div>'; return; }
635
791
  const groups = new Map();
636
792
  for (const journey of journeys) { const key = journey.group || ""; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(journey); }
637
- const row = (j) => `<div class="journey-row"><span class="journey-platform ${esc(j.platform || "web")}">${esc(j.platform || "web")}</span><span class="journey-name">${esc(j.name)}<br><small>${j.steps || 0} steps · ${journeyStatus(j.status)}</small></span><span></span><span class="journey-actions"><button class="quiet" data-run-journey="${esc(j.slug)}" title="Replay this journey">▶ Run</button>${j.source === "kept" ? `<button class="quiet" data-forget-journey="${esc(j.slug)}" title="Forget this journey">Forget</button>` : ""}</span></div>`;
793
+ // A reported journey ran on the owner's own machine: it is listed with where, and cannot be
794
+ // run from here — the cloud has no flow for it, only the result (ADR-0011 §4).
795
+ const row = (j) => `<div class="journey-row"><span class="journey-platform ${esc(j.platform || "web")}">${esc(j.platform || "web")}</span><span class="journey-name">${esc(j.name)}<br><small>${j.steps || 0} steps · ${journeyStatus(j.status)}${j.source === "reported" ? ` · runs on ${esc(j.machine || "your machine")}` : ""}</small></span><span></span><span class="journey-actions">${j.source === "reported" ? "" : `<button class="quiet" data-run-journey="${esc(j.slug)}" title="Replay this journey">▶ Run</button>`}${j.source === "kept" || j.source === "reported" ? `<button class="quiet" data-forget-journey="${esc(j.slug)}" title="Forget this journey">Forget</button>` : ""}</span></div>`;
638
796
  node.innerHTML = [...groups.entries()].sort(([a], [b]) => (a === "" ? -1 : b === "" ? 1 : a.localeCompare(b))).map(([group, items]) =>
639
797
  group === ""
640
798
  ? items.map(row).join("")
@@ -1006,6 +1164,7 @@ function renderChat() {
1006
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>' : "");
1007
1165
  node.innerHTML = lines;
1008
1166
  if (stickToBottom) node.scrollTop = node.scrollHeight;
1167
+ renderChatPrompt();
1009
1168
  const progress = [...state.transcript].reverse().find((entry) => entry.kind === "progress");
1010
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";
1011
1170
  }
@@ -1051,6 +1210,54 @@ function setChatCollapsed(collapsed) {
1051
1210
 
1052
1211
  function pushLine(entry) { state.transcript.push({ at: new Date().toISOString(), ...entry }); }
1053
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
+
1054
1261
  // A screenshot the engine wrote during the run, kept as a thumbnail in the transcript. Captured
1055
1262
  // once per screen name the engine reports, and never more often than every few seconds.
1056
1263
  async function keepShot(screen) {
@@ -1072,15 +1279,22 @@ async function keepShot(screen) {
1072
1279
 
1073
1280
  function syncTranscriptFromJob(name, job) {
1074
1281
  if (state.transcriptSource !== job.id) {
1075
- 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";
1076
1290
  state.transcriptSource = job.id;
1077
1291
  state.shotScreens = new Set();
1078
1292
  state.lastShotAt = 0;
1079
1293
  }
1080
- const seen = state.transcript.filter((entry) => entry.source === "job").length;
1294
+ const seen = state.transcript.filter((entry) => entry.source === job.id).length;
1081
1295
  for (const entry of job.progress.slice(seen)) {
1082
1296
  const line = narrate(entry, { platform: currentPlatform() });
1083
- 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 });
1084
1298
  if (line && line.kind !== "progress") {
1085
1299
  const last = state.transcript.at(-2);
1086
1300
  if (last && last.text === line.text && last.kind !== "shots") state.transcript.splice(-1, 1);
@@ -1190,13 +1404,27 @@ function renderProject() {
1190
1404
  }
1191
1405
 
1192
1406
  async function refreshSession() {
1193
- 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");
1194
1419
  state.csrf = state.session.csrfToken;
1195
1420
  const local = state.session.mode === "local";
1196
- $("#mode-pill").textContent = local ? "Self-host · this machine" : "Cloud · outbound runner";
1197
- $("#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";
1198
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.";
1199
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(() => {});
1200
1428
  }
1201
1429
 
1202
1430
  async function refresh() {
@@ -1222,8 +1450,9 @@ async function refresh() {
1222
1450
  state.live = live;
1223
1451
  state.audits = runs.audits || [];
1224
1452
  state.explores = runs.explores || [];
1225
- await loadJourneys();
1453
+ await Promise.all([loadJourneys(), loadEngines()]);
1226
1454
  renderProject();
1455
+ renderEngines();
1227
1456
  }
1228
1457
 
1229
1458
  async function runOperation(name, body = {}, { input = "" } = {}) {
@@ -1231,9 +1460,10 @@ async function runOperation(name, body = {}, { input = "" } = {}) {
1231
1460
  const started = await api(`/api/operations/${name}`, { method:"POST", body:JSON.stringify(body) });
1232
1461
  if (!started.job) return started; // synchronous answers (open a path, a business name)
1233
1462
  state.activeJob = started.job.id;
1463
+ state.activeOperation = name;
1234
1464
  const drawer = $("#operation-drawer");
1235
1465
  drawer.classList.remove("hidden");
1236
- $("#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);
1237
1467
  $("#operation-progress").textContent = "Starting";
1238
1468
  $("#operation-progress-bar").style.width = "6%";
1239
1469
  syncTranscriptFromJob(name, { ...started.job, input });
@@ -1269,6 +1499,7 @@ async function runOperation(name, body = {}, { input = "" } = {}) {
1269
1499
  } finally {
1270
1500
  if (state.jobHasFrame) { state.jobHasFrame = false; await new Promise((resolve) => setTimeout(resolve, 200)); stopLiveFrames(); }
1271
1501
  state.activeJob = null;
1502
+ state.activeOperation = "";
1272
1503
  try {
1273
1504
  await refreshSession();
1274
1505
  await refresh();
@@ -1295,7 +1526,7 @@ function setHeading(title, summary, { owned = false } = {}) {
1295
1526
  // simulator build, a repository that needs a toolchain. The engine answers with where they do
1296
1527
  // run; show that answer where it stays put, not in a toast that disappears in six seconds.
1297
1528
  function answerSelfHost(answer) {
1298
- setHeading("Run this on your machine", "The cloud Studio audits websites; this target needs your toolchain.", { owned: true });
1529
+ setHeading("Run this on your machine", "The cloud Studio runs public websites; this target runs on your own machine, with the same Studio.", { owned: true });
1299
1530
  document.querySelector(".summary-panel")?.classList.add("hidden");
1300
1531
  document.querySelector(".device-stage")?.classList.add("hidden");
1301
1532
  state.transcript = [];
@@ -1306,13 +1537,39 @@ function answerSelfHost(answer) {
1306
1537
  toast(answer.message, true);
1307
1538
  }
1308
1539
 
1309
- 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 } = {}) {
1310
1565
  const prompt = classifyPrompt(raw);
1311
1566
  if (prompt.kind === "empty") return;
1567
+ if (prompt.kind === "business") return searchBusiness(prompt.value);
1568
+ clearBusinessResults();
1312
1569
  if (prompt.kind === "url") {
1313
1570
  // On your own machine, or signed in to a public Studio, a website is explored for real — it
1314
1571
  // can stop at a sign-in and ask you. A visitor only ever reads.
1315
- if (state.session?.mode === "local" || state.session?.access === "account") {
1572
+ if (!readOnly && (state.session?.mode === "local" || state.session?.access === "account")) {
1316
1573
  state.promptRun = true; state.promptPlatform = "web";
1317
1574
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
1318
1575
  document.querySelector(".device-stage")?.classList.remove("hidden");
@@ -1335,7 +1592,7 @@ async function startFromPrompt(raw) {
1335
1592
  showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
1336
1593
  document.querySelector(".device-stage")?.classList.remove("hidden");
1337
1594
  if (state.session?.access !== "anonymous") document.querySelector(".summary-panel")?.classList.remove("hidden");
1338
- 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 });
1339
1596
  const result = await runOperation("audit", { url: prompt.value }, { input: prompt.value });
1340
1597
  state.selectedRunId = result?.capture?.id || state.selectedRunId;
1341
1598
  return;
@@ -1351,7 +1608,6 @@ async function startFromPrompt(raw) {
1351
1608
  showProduct(); activateView("overview"); renderChat();
1352
1609
  const answer = await runOperation("open", { input: prompt.value }, { input: prompt.value });
1353
1610
  if (answer?.kind === "self-host") { answerSelfHost(answer); return; }
1354
- if (answer?.kind === "business") { answerSelfHost({ message: answer.message }); return; }
1355
1611
  await refreshSession();
1356
1612
  await refresh();
1357
1613
  state.selectedTargetId = "";
@@ -1368,6 +1624,12 @@ async function auditWebsite(url) {
1368
1624
  }
1369
1625
 
1370
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
+ }
1371
1633
  const viewButton = event.target.closest("[data-view]");
1372
1634
  if (viewButton && $("#product-shell").contains(viewButton)) activateView(viewButton.dataset.view);
1373
1635
  // "What tapp can drive" is reachable from the first screen, before there is any project.
@@ -1385,6 +1647,51 @@ document.addEventListener("click", (event) => {
1385
1647
  if (runButton) { state.selectedRunId = runButton.dataset.runId; renderRuns(); }
1386
1648
  const suggestion = event.target.closest("[data-prompt]");
1387
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
+ }
1662
+ if (event.target.closest("[data-unlink-studio]")) {
1663
+ api("/api/studio-link", { method:"DELETE" }).then(async () => { toast("Disconnected."); await refreshSession(); }).catch((error) => toast(error.message, true));
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
+ }
1684
+ const planButton = event.target.closest("[data-plan-account]");
1685
+ if (planButton) {
1686
+ const { planAccount, planKind, planDays } = planButton.dataset;
1687
+ api("/api/admin/plan", { method:"POST", body: JSON.stringify({ accountId: planAccount, kind: planKind, days: planDays ? Number(planDays) : undefined }) })
1688
+ .then(async () => { toast(planKind === "paid" ? "Marked paid." : `Trial set to ${planDays} days from today.`); await loadAdmin(); renderAdmin(); })
1689
+ .catch((error) => toast(error.message, true));
1690
+ }
1691
+ if (event.target.closest("#selfhost-copy")) {
1692
+ const text = $("#selfhost-command")?.textContent || "";
1693
+ navigator.clipboard?.writeText(text).then(() => toast("Copied. Run it in a terminal on your machine."), () => toast("Select the command and copy it.", true));
1694
+ }
1388
1695
  const liveControl = event.target.closest("[data-live-control]");
1389
1696
  if (liveControl) {
1390
1697
  const target = liveControl.dataset.liveTarget;
@@ -1394,6 +1701,54 @@ document.addEventListener("click", (event) => {
1394
1701
  }
1395
1702
  });
1396
1703
 
1704
+ document.addEventListener("submit", async (event) => {
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]");
1740
+ if (!form) return;
1741
+ event.preventDefault();
1742
+ const button = form.querySelector("button[type=submit]");
1743
+ if (button) button.disabled = true;
1744
+ try {
1745
+ await api("/api/studio-link", { method:"POST", body: JSON.stringify({ origin: form.elements.origin?.value || "", token: form.elements.token?.value || "" }) });
1746
+ toast("Connected. Journeys run here will report to your account.");
1747
+ await refreshSession();
1748
+ } catch (error) { toast(error.message, true); }
1749
+ finally { if (button) button.disabled = false; }
1750
+ });
1751
+
1397
1752
  document.addEventListener("change", (event) => {
1398
1753
  const picker = event.target.closest("#findings-run, #coverage-run");
1399
1754
  if (picker) { state.selectedRunId = picker.value; renderRuns(); }
@@ -1509,6 +1864,7 @@ try {
1509
1864
  if (handoff) {
1510
1865
  const input = $("#prompt-input");
1511
1866
  if (input) input.value = handoff;
1512
- await startFromPrompt(handoff);
1867
+ if (classifyPrompt(handoff).kind === "business") { showPrompt(); clearBusinessResults(); }
1868
+ else await startFromPrompt(handoff);
1513
1869
  }
1514
1870
  } catch (error) { toast(error.message, true); }