@aarwitz/tapp 0.18.2 → 0.18.3

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,5 +1,5 @@
1
1
  import { customerProductContract } from "./product-contract.js";
2
- import { operationIsPending } from "./view-model.js";
2
+ import { classifyPrompt, narrate, narrateFinding, operationIsPending, summarize } 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 || "");
@@ -11,14 +11,16 @@ function apiRoute(route) {
11
11
  }
12
12
 
13
13
  const state = {
14
- csrf: "", session: null, project: null, audits: [], activeJob: null, activeView: "overview",
14
+ csrf: "", session: null, project: null, audits: [], explores: [], activeJob: null, activeView: "overview",
15
15
  selectedTargetId: "", selectedRunId: "", live: { active:false }, transcript: [], transcriptSource: "", frameTimer: null,
16
+ chatCollapsed: false, shotScreens: new Set(), lastShotAt: 0,
16
17
  };
17
18
  const $ = (selector) => document.querySelector(selector);
18
19
  const $$ = (selector) => [...document.querySelectorAll(selector)];
19
20
  const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (character) => ({ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":"&#39;" }[character]));
20
21
  const pretty = (value) => String(value || "").replaceAll("_", " ").replaceAll("-", " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
21
22
  const compactDate = (value) => value ? new Intl.DateTimeFormat(undefined, { month:"short", day:"numeric", hour:"numeric", minute:"2-digit" }).format(new Date(value)) : "—";
23
+ const chatTime = (value) => new Intl.DateTimeFormat(undefined, { hour:"numeric", minute:"2-digit" }).format(new Date(value));
22
24
 
23
25
  function toast(message, error = false) {
24
26
  const node = $("#toast");
@@ -49,14 +51,15 @@ function captureId(report) {
49
51
  }
50
52
  return report?.capture?.id || "";
51
53
  }
52
-
54
+ const captureUrl = (id, file = "report.html") => apiRoute(`/evidence/captures/${encodeURIComponent(id)}/${file}`);
53
55
  function evidenceLink(id, label = "Open visual evidence") {
54
- return id ? `<a class="button-link" href="${esc(apiRoute(`/evidence/captures/${encodeURIComponent(id)}/report.html`))}" target="_blank" rel="noreferrer">${esc(label)}</a>` : "";
56
+ return id ? `<a class="button-link" href="${esc(captureUrl(id))}" target="_blank" rel="noreferrer">${esc(label)}</a>` : "";
55
57
  }
56
58
  function reportLink(report, label) { return evidenceLink(captureId(report), label); }
57
59
 
58
60
  function currentTarget() { return (state.project?.targets || []).find((target) => target.id === state.selectedTargetId) || null; }
59
61
  function targetStorageKey() { return `tapp:selected-target:${state.project?.repository?.id || "none"}`; }
62
+ function currentPlatform() { return state.live?.active ? state.live.platform : (currentTarget()?.platform || state.promptPlatform || ""); }
60
63
 
61
64
  function chooseDefaultTarget() {
62
65
  const targets = state.project?.targets || [];
@@ -84,9 +87,10 @@ function activateView(view) {
84
87
  window.scrollTo({ top:0, behavior:"instant" });
85
88
  }
86
89
 
87
- function showSourceOnboarding() {
90
+ function showPrompt() {
88
91
  $("#source-onboarding").classList.remove("hidden");
89
92
  $("#product-shell").classList.add("hidden");
93
+ setTimeout(() => $("#prompt-input")?.focus(), 50);
90
94
  }
91
95
 
92
96
  function showProduct() {
@@ -133,7 +137,7 @@ function renderTargets() {
133
137
  const appId = target?.runtime?.bundleId || target?.runtime?.applicationId || target?.build?.bundleId || "";
134
138
  $("#sidebar-app-row").classList.toggle("hidden", !appId);
135
139
  $("#sidebar-app-id").textContent = appId;
136
- renderDeviceChrome(target);
140
+ renderDeviceChrome();
137
141
  $("#runtime-row").classList.toggle("hidden", !targets.length);
138
142
  $("#serial-field").classList.toggle("hidden", target?.platform !== "android");
139
143
  $("#explore").disabled = !target;
@@ -147,14 +151,17 @@ function renderTargets() {
147
151
  : "Builds and starts the selected repository web application, then explores it in Chromium.";
148
152
  }
149
153
 
150
- function renderDeviceChrome(target) {
151
- const platform = state.live?.active ? state.live.platform : target?.platform;
152
- const frame = $("#device-frame");
153
- frame.className = `device-frame ${platform === "ios" ? "" : platform || ""}`.trim();
154
- $("#device-feed-label").textContent = platform === "android" ? "Live Android Feed" : platform === "web" ? "Live Browser Feed" : "Live iPhone Feed";
154
+ // The device frame takes the platform's real shape: a phone is tall, a browser is wide. The stage
155
+ // gives it every pixel it can, so the frame class drives the aspect ratio and the stage the size.
156
+ function renderDeviceChrome() {
157
+ const platform = currentPlatform();
158
+ const target = currentTarget();
159
+ $("#device-frame").className = `device-frame ${platform || "ios"}`;
160
+ $("#stage").className = `stage ${platform || "ios"}`;
161
+ $("#device-feed-label").textContent = platform === "android" ? "Android" : platform === "web" ? "Chromium" : "iPhone";
155
162
  $("#device-meta-device").textContent = platform === "ios" ? (target?.runtime?.surface || "iOS Simulator")
156
163
  : platform === "android" ? (target?.runtime?.serial || "Android emulator / device")
157
- : platform === "web" ? "Chromium" : "—";
164
+ : platform === "web" ? "Local Chromium" : "—";
158
165
  }
159
166
 
160
167
  // The device panel shows whichever real surface exists right now: an interactive session's frame,
@@ -165,8 +172,6 @@ function frameSource() {
165
172
  return "";
166
173
  }
167
174
 
168
- // One in-flight capture at a time; the next request waits for the previous image to land so a
169
- // slow simulator does not pile up frame requests.
170
175
  function refreshLiveFrame() {
171
176
  clearTimeout(state.frameTimer);
172
177
  const source = frameSource();
@@ -179,31 +184,22 @@ function refreshLiveFrame() {
179
184
  image.onerror = () => { loading.textContent = "Live frame could not be captured. The semantic controls remain available."; scheduleLiveFrame(); };
180
185
  image.src = apiRoute(`${source}?at=${Date.now()}`);
181
186
  }
182
-
183
- function scheduleLiveFrame() {
184
- clearTimeout(state.frameTimer);
185
- if (frameSource()) state.frameTimer = setTimeout(refreshLiveFrame, 1500);
186
- }
187
-
188
- function stopLiveFrames() {
189
- clearTimeout(state.frameTimer);
190
- state.frameTimer = null;
191
- }
187
+ function scheduleLiveFrame() { clearTimeout(state.frameTimer); if (frameSource()) state.frameTimer = setTimeout(refreshLiveFrame, 1500); }
188
+ function stopLiveFrames() { clearTimeout(state.frameTimer); state.frameTimer = null; }
192
189
 
193
190
  function renderLiveSession() {
194
191
  const live = state.live || { active:false };
195
192
  $("#live-session-panel").classList.toggle("hidden", !live.active);
196
193
  if (!live.active) {
197
- // Keep the last real frame on screen after a run; only show the placeholder when nothing was ever captured.
198
194
  if (!frameSource()) stopLiveFrames();
199
195
  const hasFrame = !!$("#live-frame-image").getAttribute("src");
200
196
  $("#live-frame-loading").classList.toggle("hidden", hasFrame || !frameSource());
201
197
  $("#device-placeholder").classList.toggle("hidden", hasFrame);
202
198
  if (!state.activeJob) $("#live-screen-title").textContent = hasFrame ? $("#live-screen-title").textContent : "—";
203
- renderDeviceChrome(currentTarget());
199
+ renderDeviceChrome();
204
200
  return;
205
201
  }
206
- renderDeviceChrome(currentTarget());
202
+ renderDeviceChrome();
207
203
  $("#live-screen-title").textContent = live.screenTitle || live.targetName || "Running target";
208
204
  $("#live-platform").textContent = `${pretty(live.platform)} · ${live.targetName || "live target"}`;
209
205
  $("#live-recorded-steps").textContent = `${live.recordedSteps || 0} recorded step${live.recordedSteps === 1 ? "" : "s"}`;
@@ -236,8 +232,6 @@ function renderDecision(run) {
236
232
  return;
237
233
  }
238
234
  const report = latest.report;
239
- // The decision reflects the GATE outcome (pass/fail/inconclusive), not a ship verdict — exploration
240
- // only observes (ADR-0005). Without a gate, it's an observation, not a merge decision.
241
235
  const outcome = report.gate?.outcome || (report.gate?.failed === true ? "fail" : report.inconclusive ? "inconclusive" : report.gate ? "pass" : null);
242
236
  const cssClass = { pass: "ready", fail: "blocked", inconclusive: "caution" }[outcome] || "caution";
243
237
  card.className = `decision-card ${cssClass}`;
@@ -246,23 +240,30 @@ function renderDecision(run) {
246
240
  $("#overview-evidence").innerHTML = `<div class="latest-run-line"><span class="verdict-dot ${esc(cssClass)}"></span><div><strong>${esc(report.headline || pretty(cssClass))}</strong><small>${esc(pretty(report.platform || "unknown"))} · ${compactDate(latest.createdAt)} · ${(report.contracts || []).filter((item) => item.passed).length}/${(report.contracts || []).length} contracts passed</small></div></div><p>${esc((report.gate?.reasons || ["No blocking release-gate reason reported."])[0])}</p>${reportLink(report)}`;
247
241
  }
248
242
 
249
- // Runs are two kinds with one list: gate runs on the repository (`report`) and read-only website
250
- // audits (`audit`). Both open the report page the engine wrote.
243
+ // Runs are three kinds in one list: gate runs on the repository, explorations started from the
244
+ // prompt, and read-only website audits. Each opens the report page the engine wrote.
251
245
  function allRuns() {
252
246
  const gates = (state.project?.evidence || []).map((run) => ({ ...run, kind:"gate" }));
247
+ const explores = (state.explores || []).map((run) => ({ id:run.id, createdAt:run.createdAt, kind:"explore", explore:run }));
253
248
  const audits = (state.audits || []).map((audit) => ({ id:audit.id, createdAt:audit.createdAt, kind:"audit", audit }));
254
- return [...gates, ...audits].sort((a, b) => String(b.createdAt || "").localeCompare(String(a.createdAt || "")));
249
+ return [...gates, ...explores, ...audits].sort((a, b) => String(b.createdAt || "").localeCompare(String(a.createdAt || "")));
255
250
  }
256
251
 
257
252
  function renderRuns() {
258
253
  const runs = allRuns();
259
254
  setCount("#run-count", runs.length);
260
255
  $("#runs-list").innerHTML = runs.length ? runs.map((run) => {
256
+ const selected = run.id === state.selectedRunId ? "selected" : "";
261
257
  if (run.kind === "audit") {
262
258
  const audit = run.audit;
263
259
  const issues = audit.issueCount || 0;
264
260
  const host = (() => { try { return new URL(audit.url).host; } catch { return audit.url; } })();
265
- return `<button class="run-row ${run.id === state.selectedRunId ? "selected" : ""}" data-run-id="${esc(run.id)}"><span class="run-status ${issues ? "inconclusive" : "ready"}">${issues ? "!" : "✓"}</span><span><strong>Audit · ${esc(host)}</strong><small>${compactDate(run.createdAt)} · ${audit.pagesAudited || 0} page${audit.pagesAudited === 1 ? "" : "s"} · read-only</small></span><em>${issues ? `${issues} issue${issues === 1 ? "" : "s"}` : "Nothing broken"}</em></button>`;
261
+ return `<button class="run-row ${selected}" data-run-id="${esc(run.id)}"><span class="run-status ${issues ? "inconclusive" : "ready"}">${issues ? "!" : "✓"}</span><span><strong>Audit · ${esc(host)}</strong><small>${compactDate(run.createdAt)} · ${audit.pagesAudited || 0} page${audit.pagesAudited === 1 ? "" : "s"} · read-only</small></span><em>${issues ? `${issues} issue${issues === 1 ? "" : "s"}` : "Nothing broken"}</em></button>`;
262
+ }
263
+ if (run.kind === "explore") {
264
+ const e = run.explore;
265
+ const findings = e.report?.findingCounts?.total ?? (e.report?.findings || []).length;
266
+ return `<button class="run-row ${selected}" data-run-id="${esc(run.id)}"><span class="run-status ${e.report?.inconclusive ? "inconclusive" : "completed"}">${e.report?.inconclusive ? "◐" : "✓"}</span><span><strong>Explore · ${esc(e.target || e.platform)}</strong><small>${compactDate(run.createdAt)} · ${esc(pretty(e.platform))}</small></span><em>${findings} finding${findings === 1 ? "" : "s"}</em></button>`;
266
267
  }
267
268
  const report = run.report;
268
269
  const failed = report?.gate?.failed === true;
@@ -270,65 +271,127 @@ function renderRuns() {
270
271
  : report.gate?.outcome === "fail" || failed ? "blocked"
271
272
  : report.gate?.outcome === "inconclusive" || report.inconclusive ? "inconclusive"
272
273
  : report.gate?.outcome === "pass" ? "ready" : "completed";
273
- return `<button class="run-row ${run.id === state.selectedRunId ? "selected" : ""}" data-run-id="${esc(run.id)}"><span class="run-status ${esc(status)}">${failed ? "×" : report ? "✓" : "…"}</span><span><strong>${esc(report?.headline || `Release run ${run.id.slice(-8)}`)}</strong><small>${compactDate(run.createdAt)} · ${esc(pretty(report?.platform || "unknown"))}</small></span><em>${esc(pretty(status))}</em></button>`;
274
+ return `<button class="run-row ${selected}" data-run-id="${esc(run.id)}"><span class="run-status ${esc(status)}">${failed ? "×" : report ? "✓" : "…"}</span><span><strong>${esc(report?.headline || `Release run ${run.id.slice(-8)}`)}</strong><small>${compactDate(run.createdAt)} · ${esc(pretty(report?.platform || "unknown"))}</small></span><em>${esc(pretty(status))}</em></button>`;
274
275
  }).join("") : '<div class="empty">No runs yet. Run a release check, or audit a website above.</div>';
275
- const selected = runs.find((run) => run.id === state.selectedRunId) || runs[0];
276
- if (selected) state.selectedRunId = selected.id;
277
- renderRunDetail(selected);
276
+ const chosen = runs.find((run) => run.id === state.selectedRunId) || runs[0];
277
+ if (chosen) state.selectedRunId = chosen.id;
278
+ renderRunDetail(chosen);
278
279
  }
279
280
 
280
- function renderAuditDetail(audit) {
281
- const counts = audit.findingCounts || {};
282
- const issues = audit.issues || [];
283
- $("#run-detail").innerHTML = `<div class="run-detail-head"><div><p class="eyebrow">READ-ONLY AUDIT</p><h2>${esc(audit.url)}</h2><small><code>${esc(audit.id)}</code> · ${compactDate(audit.createdAt)} · nothing was clicked</small></div>${evidenceLink(audit.id, "Visual report")}</div><div class="run-stats"><div><strong>${audit.pagesAudited || 0}</strong><small>pages</small></div><div><strong>${issues.length}</strong><small>distinct issues</small></div><div><strong>${counts.high || 0}</strong><small>high</small></div><div><strong>${counts.medium || 0}</strong><small>medium</small></div></div><h3>Issues</h3>${issues.length ? `<ul class="detail-list">${issues.slice(0, 40).map((issue) => `<li><b>${esc(issue.severity)}</b> · ${esc(issue.title)}${issue.pages?.length > 1 ? ` <small>(${issue.pages.length} pages)</small>` : ""}</li>`).join("")}</ul>` : '<p class="muted">Nothing broken was observed. This says the pages are served without structural defects, not that the site works.</p>'}<h3>Not checked</h3><ul class="detail-list boundary">${(audit.notChecked || []).slice(0, 6).map((item) => `<li>${esc(item)}</li>`).join("")}</ul>`;
281
+ function detailLists(report) {
282
+ return `<h3>What Tapp checked</h3><ul class="detail-list">${(report.checkedFor || []).slice(0, 8).map((item) => `<li>${esc(item)}</li>`).join("")}</ul><h3>Not checked</h3><ul class="detail-list boundary">${(report.notChecked || []).slice(0, 8).map((item) => `<li>${esc(item)}</li>`).join("")}</ul>`;
284
283
  }
285
284
 
286
285
  function renderRunDetail(run) {
287
- if (run?.kind === "audit") { renderAuditDetail(run.audit); return; }
288
- if (!run?.report) { $("#run-detail").innerHTML = '<div class="empty">Select a completed run to inspect its evidence.</div>'; return; }
286
+ if (!run) { $("#run-detail").innerHTML = '<div class="empty">Select a run to inspect its evidence.</div>'; return; }
287
+ if (run.kind === "audit") {
288
+ const audit = run.audit;
289
+ const counts = audit.findingCounts || {};
290
+ const issues = audit.issues || [];
291
+ $("#run-detail").innerHTML = `<div class="run-detail-head"><div><p class="eyebrow">READ-ONLY AUDIT</p><h2>${esc(audit.url)}</h2><small><code>${esc(audit.id)}</code> · ${compactDate(audit.createdAt)} · nothing was clicked</small></div>${evidenceLink(audit.id, "Visual report")}</div><div class="run-stats"><div><strong>${audit.pagesAudited || 0}</strong><small>pages</small></div><div><strong>${issues.length}</strong><small>distinct issues</small></div><div><strong>${counts.high || 0}</strong><small>high</small></div><div><strong>${counts.medium || 0}</strong><small>medium</small></div></div><h3>Issues</h3>${issues.length ? `<ul class="detail-list">${issues.slice(0, 40).map((issue) => `<li><b>${esc(issue.severity)}</b> · ${esc(issue.title)}${issue.pages?.length > 1 ? ` <small>(${issue.pages.length} pages)</small>` : ""}</li>`).join("")}</ul>` : '<p class="muted">Nothing broken was observed. This says the pages are served without structural defects, not that the site works.</p>'}${detailLists(audit)}`;
292
+ return;
293
+ }
294
+ if (run.kind === "explore") {
295
+ const e = run.explore;
296
+ const report = e.report || {};
297
+ $("#run-detail").innerHTML = `<div class="run-detail-head"><div><p class="eyebrow">${esc(report.inconclusive ? "INCONCLUSIVE" : "EXPLORATION")}</p><h2>${esc(report.headline || `Explored ${e.target || e.platform}`)}</h2><small><code>${esc(e.id)}</code> · ${compactDate(e.createdAt)} · an observation, not a release decision</small></div>${evidenceLink(e.id, "Visual report")}</div><div class="run-stats"><div><strong>${report.screensExplored || 0}</strong><small>screens</small></div><div><strong>${report.actionsPerformed || 0}</strong><small>actions</small></div><div><strong>${report.findingCounts?.total ?? (report.findings || []).length}</strong><small>findings</small></div></div><h3>Findings</h3>${(report.findings || []).length ? `<ul class="detail-list">${report.findings.slice(0, 40).map((f) => `<li><b>${esc(f.severity)}</b> · ${esc(f.title)}${f.screen ? ` <small>on ${esc(f.screen)}</small>` : ""}</li>`).join("")}</ul>` : '<p class="muted">No findings surfaced in the exercised surfaces.</p>'}${detailLists(report)}`;
298
+ return;
299
+ }
300
+ if (!run.report) { $("#run-detail").innerHTML = '<div class="empty">Select a completed run to inspect its evidence.</div>'; return; }
289
301
  const report = run.report;
290
302
  const contracts = report.contracts || [];
291
- $("#run-detail").innerHTML = `<div class="run-detail-head"><div><p class="eyebrow">${esc(report.gate?.failed ? "BLOCKED" : report.inconclusive ? "INCONCLUSIVE" : "RELEASE RUN")}</p><h2>${esc(report.headline || "Release gate completed")}</h2><small><code>${esc(run.id)}</code> · ${compactDate(run.createdAt)}</small></div>${reportLink(report, "Visual report")}</div><div class="run-stats"><div><strong>${report.screensExplored || 0}</strong><small>states</small></div><div><strong>${report.actionsPerformed || 0}</strong><small>actions</small></div><div><strong>${contracts.filter((item) => item.passed).length}/${contracts.length}</strong><small>contracts</small></div><div><strong>${report.findingCounts?.total ?? (report.findings || []).length}</strong><small>findings</small></div></div><h3>Decision rationale</h3><ul class="detail-list">${(report.gate?.reasons || ["No blocking gate reason reported."]).map((item) => `<li>${esc(item)}</li>`).join("")}</ul><h3>Deterministic contracts</h3>${contracts.length ? contracts.map((contract) => `<div class="contract-result"><span class="${contract.passed ? "pass" : "fail"}">${contract.passed ? "✓" : "×"}</span><div><strong>${esc(contract.title || contract.name || contract.path)}</strong><small>${esc(contract.detail || contract.path || "Deterministic replay")}</small></div></div>`).join("") : '<p class="muted">No committed release contracts applied to this target.</p>'}<h3>What Tapp checked</h3><ul class="detail-list">${(report.checkedFor || []).slice(0, 8).map((item) => `<li>${esc(item)}</li>`).join("")}</ul><h3>Not checked</h3><ul class="detail-list boundary">${(report.notChecked || []).slice(0, 8).map((item) => `<li>${esc(item)}</li>`).join("")}</ul>`;
303
+ $("#run-detail").innerHTML = `<div class="run-detail-head"><div><p class="eyebrow">${esc(report.gate?.failed ? "BLOCKED" : report.inconclusive ? "INCONCLUSIVE" : "RELEASE RUN")}</p><h2>${esc(report.headline || "Release gate completed")}</h2><small><code>${esc(run.id)}</code> · ${compactDate(run.createdAt)}</small></div>${reportLink(report, "Visual report")}</div><div class="run-stats"><div><strong>${report.screensExplored || 0}</strong><small>states</small></div><div><strong>${report.actionsPerformed || 0}</strong><small>actions</small></div><div><strong>${contracts.filter((item) => item.passed).length}/${contracts.length}</strong><small>contracts</small></div><div><strong>${report.findingCounts?.total ?? (report.findings || []).length}</strong><small>findings</small></div></div><h3>Decision rationale</h3><ul class="detail-list">${(report.gate?.reasons || ["No blocking gate reason reported."]).map((item) => `<li>${esc(item)}</li>`).join("")}</ul><h3>Deterministic contracts</h3>${contracts.length ? contracts.map((contract) => `<div class="contract-result"><span class="${contract.passed ? "pass" : "fail"}">${contract.passed ? "✓" : "×"}</span><div><strong>${esc(contract.title || contract.name || contract.path)}</strong><small>${esc(contract.detail || contract.path || "Deterministic replay")}</small></div></div>`).join("") : '<p class="muted">No committed release contracts applied to this target.</p>'}${detailLists(report)}`;
292
304
  }
293
305
 
294
- const chatTime = (value) => new Intl.DateTimeFormat(undefined, { hour:"numeric", minute:"2-digit" }).format(new Date(value));
295
-
306
+ // ---- tapp chat: the engine's progress log, rendered as a transcript -------------------------
296
307
  function renderChat() {
297
308
  const node = $("#chat-transcript");
298
309
  const stickToBottom = node.scrollTop + node.clientHeight >= node.scrollHeight - 24;
299
- node.innerHTML = state.transcript.map((entry) => `<div class="chat-bubble ${esc(entry.kind || "")} ${esc(entry.severity || "")}">${esc(entry.text)}<small>${chatTime(entry.at)}</small></div>`).join("")
300
- + (state.activeJob ? '<div class="chat-bubble typing">tapp is working…</div>' : "");
310
+ const lines = state.transcript.map((entry) => {
311
+ if (entry.kind === "shots") return `<div class="chat-shots">${entry.shots.map((shot) => `<a href="${esc(shot.href)}" target="_blank" rel="noreferrer" title="${esc(shot.caption)}"><img src="${esc(shot.src)}" alt="${esc(shot.caption)}"></a>`).join("")}</div>`;
312
+ if (entry.kind === "attachments") return `<div class="chat-attachments">${entry.items.map((item) => `<a href="${esc(item.href)}" target="_blank" rel="noreferrer"><span>${item.icon}</span>${esc(item.label)}</a>`).join("")}</div>`;
313
+ if (entry.kind === "summary") return `<div class="chat-summary ${esc(entry.tone)}"><span class="chat-pill">${esc(entry.pill)}</span><p>${esc(entry.text)}</p></div>`;
314
+ if (entry.kind === "finding") return `<div class="chat-line finding ${esc(entry.severity)}"><span class="chat-icon">${entry.icon}</span><span>${esc(entry.text)}</span></div>`;
315
+ if (entry.kind === "progress") return "";
316
+ return `<div class="chat-line ${esc(entry.kind || "")}"><span class="chat-icon">${entry.icon || "•"}</span><span>${esc(entry.text)}${entry.detail ? ` <em>— ${esc(entry.detail)}</em>` : ""}</span></div>`;
317
+ }).join("") + (state.activeJob ? '<div class="chat-line typing"><span class="chat-icon">✨</span><span>tapp is working<i>…</i></span></div>' : "");
318
+ node.innerHTML = lines;
301
319
  if (stickToBottom) node.scrollTop = node.scrollHeight;
320
+ const progress = [...state.transcript].reverse().find((entry) => entry.kind === "progress");
321
+ $("#chat-status").textContent = state.activeJob ? (progress ? `${progress.current}/${progress.total} actions${progress.states != null ? ` · ${progress.states} screens` : ""}` : "working…") : state.transcript.length > 1 ? "done" : "ready";
322
+ }
323
+
324
+ function setChatCollapsed(collapsed) {
325
+ state.chatCollapsed = collapsed;
326
+ $("#chat-float").classList.toggle("collapsed", collapsed);
327
+ $("#chat-toggle").setAttribute("aria-expanded", String(!collapsed));
328
+ try { localStorage.setItem("tapp:chat-collapsed", collapsed ? "1" : "0"); } catch { /* storage may be unavailable */ }
329
+ }
330
+
331
+ function pushLine(entry) { state.transcript.push({ at: new Date().toISOString(), ...entry }); }
332
+
333
+ // A screenshot the engine wrote during the run, kept as a thumbnail in the transcript. Captured
334
+ // once per screen name the engine reports, and never more often than every few seconds.
335
+ async function keepShot(screen) {
336
+ const key = screen || `t${Math.floor(Date.now() / 4000)}`;
337
+ if (state.shotScreens.has(key) || Date.now() - state.lastShotAt < 2500 || !state.activeJob) return;
338
+ state.shotScreens.add(key);
339
+ state.lastShotAt = Date.now();
340
+ try {
341
+ const response = await fetch(apiRoute(`/api/jobs/${state.activeJob}/frame?at=${Date.now()}`));
342
+ if (!response.ok) return;
343
+ const blob = await response.blob();
344
+ const src = URL.createObjectURL(blob);
345
+ const last = state.transcript.at(-1);
346
+ if (last?.kind === "shots" && last.shots.length < 3) last.shots.push({ src, href: src, caption: screen || "screen" });
347
+ else pushLine({ kind: "shots", shots: [{ src, href: src, caption: screen || "screen" }] });
348
+ renderChat();
349
+ } catch { /* a missed thumbnail is not an error */ }
302
350
  }
303
351
 
304
- // The transcript is the engine's own progress log, bubble per entry. Phase changes get the
305
- // `phase` style; everything else is narration of what actually happened.
306
352
  function syncTranscriptFromJob(name, job) {
307
- const key = job.id;
308
- if (state.transcriptSource !== key) { state.transcript = [{ at: job.createdAt, kind: "phase", text: `${pretty(name)} started` }]; state.transcriptSource = key; }
309
- const seen = state.transcript.length - 1;
353
+ if (state.transcriptSource !== job.id) {
354
+ state.transcript = [{ at: job.createdAt, kind: "phase", icon: "🚀", text: startLine(name, job) }];
355
+ state.transcriptSource = job.id;
356
+ state.shotScreens = new Set();
357
+ state.lastShotAt = 0;
358
+ }
359
+ const seen = state.transcript.filter((entry) => entry.source === "job").length;
310
360
  for (const entry of job.progress.slice(seen)) {
311
- const text = String(entry.text || "").trim().replace(/\s+/g, " ").slice(0, 220).replace(/(.{219}).+/, "$1…");
312
- if (!text) continue;
313
- const last = state.transcript.at(-1);
314
- if (last && last.text === text) continue;
315
- state.transcript.push({ at: entry.at, kind: entry.phase === "explore" || entry.phase === "runtime" ? "" : "phase", text });
361
+ const line = narrate(entry, { platform: currentPlatform() });
362
+ state.transcript.push({ ...(line || { kind: "step", icon: "•", text: "" }), at: entry.at, source: "job" });
363
+ if (line && line.kind !== "progress") {
364
+ const last = state.transcript.at(-2);
365
+ if (last && last.text === line.text && last.kind !== "shots") state.transcript.splice(-1, 1);
366
+ }
367
+ if (entry.screen) keepShot(entry.screen);
316
368
  }
317
369
  }
318
370
 
319
- function finishTranscript(name, job) {
320
- if (job.status === "failed") { state.transcript.push({ at: job.completedAt || new Date().toISOString(), kind: "failed", text: job.error?.message || `${pretty(name)} failed` }); return; }
321
- const report = job.result?.report || job.result;
322
- const findings = report?.findings || (report?.issues || []);
323
- for (const finding of findings.slice(0, 12)) {
324
- const severity = String(finding.severity || "info").toLowerCase();
325
- state.transcript.push({ at: job.completedAt || new Date().toISOString(), kind: "finding", severity, text: `${pretty(severity)} issue${finding.screen ? ` on ${finding.screen}` : ""}: ${finding.title || finding.message || finding.type}` });
371
+ function startLine(name, job) {
372
+ const input = job.input || "";
373
+ return { initialize: "Starting a release check — build, launch and explore the real app", gate: "Running the release gate", audit: `Opening ${input} read-only — nothing will be clicked`, "explore-build": `Exploring ${input} on the booted device`, open: `Opening ${input}`, "session-start": "Opening a live session", "session-act": "Acting in the live session", "session-save-flow": "Saving the journey as a Flow", "session-end": "Ending the live session" }[name] || `${pretty(name)} started`;
374
+ }
375
+
376
+ async function finishTranscript(name, job) {
377
+ state.transcript = state.transcript.filter((entry) => entry.kind !== "progress" || true);
378
+ if (job.status === "failed") { pushLine({ kind: "warning", icon: "⚠️", text: job.error?.message || `${pretty(name)} failed` }); return; }
379
+ const result = job.result || {};
380
+ // initialize carries its exploration beside the project; the gate carries a report.
381
+ const report = result.exploration || result.report || result;
382
+ for (const finding of (report.findings || result.issues || []).slice(0, 12)) pushLine(narrateFinding(finding));
383
+ const id = result.capture?.id || captureId(report);
384
+ if (id) {
385
+ try {
386
+ const files = await api(`/api/captures/${encodeURIComponent(id)}/files`);
387
+ if (files.shots?.length) pushLine({ kind: "shots", shots: files.shots.slice(0, 3).map((shot) => ({ src: captureUrl(id, shot.src), href: captureUrl(id, shot.src), caption: shot.caption })) });
388
+ const items = [];
389
+ if (files.recording) items.push({ icon: "🎬", label: files.recording, href: captureUrl(id, files.recording) });
390
+ if (files.report) items.push({ icon: "📄", label: "report.html", href: captureUrl(id, files.report) });
391
+ if (items.length) pushLine({ kind: "attachments", items });
392
+ } catch { /* the summary still renders */ }
326
393
  }
327
- const summary = report?.headline
328
- || (name === "gate" ? (job.result?.passed === false ? "Release gate blocked this revision." : "Release gate completed.")
329
- : name === "audit" ? `Audit complete — ${job.result?.pagesAudited || 0} page(s), ${job.result?.issueCount || 0} distinct issue(s), nothing clicked.`
330
- : `${pretty(name)} completed`);
331
- state.transcript.push({ at: job.completedAt || new Date().toISOString(), kind: "summary", text: summary });
394
+ pushLine({ kind: "summary", ...summarize(name, result.exploration ? { ...result, report } : result) });
332
395
  }
333
396
 
334
397
  function seedIdleTranscript() {
@@ -336,8 +399,8 @@ function seedIdleTranscript() {
336
399
  const latest = latestRun();
337
400
  const report = latest?.report;
338
401
  state.transcript = report
339
- ? [{ at: latest.createdAt, kind: "summary", text: `Last run: ${report.headline || "release run completed"} · ${report.screensExplored || 0} states · ${(report.findings || []).length} findings` }]
340
- : [{ at: new Date().toISOString(), kind: "phase", text: state.project?.state?.inspected ? "Ready. Run a release check to watch Tapp build, launch and explore the real app." : "Inspecting the project…" }];
402
+ ? [{ at: latest.createdAt, kind: "summary", ...summarize("gate", report) }]
403
+ : [{ at: new Date().toISOString(), kind: "phase", icon: "👋", text: state.project?.state?.inspected ? "Ready. Run a release check and I'll narrate what the app does while you watch it." : "Inspecting the project…" }];
341
404
  }
342
405
 
343
406
  function renderCommandState(job = null, name = "") {
@@ -361,9 +424,8 @@ function renderCommandState(job = null, name = "") {
361
424
  const target = currentTarget();
362
425
  const runner = target ? state.session?.runners?.find((item) => item.platform === target.platform) : null;
363
426
  $("#idle-badges").innerHTML = [
364
- target ? `<span><b>${esc(pretty(target.platform))}</b> · ${esc(target.name)}</span>` : "<span>No target selected</span>",
365
- runner ? `<span>${esc(runner.label)} · ${esc(pretty(runner.status))}</span>` : "",
366
- `<span>Idle · ${target ? "Ready for the next release check" : "Choose a target to run"}</span>`,
427
+ target ? `<span><b>${esc(pretty(target.platform))}</b> · ${esc(target.name)}</span>` : "",
428
+ runner ? `<span>${esc(runner.label)}</span>` : "",
367
429
  ].filter(Boolean).join("");
368
430
  }
369
431
 
@@ -371,9 +433,9 @@ function renderProject() {
371
433
  const project = state.project;
372
434
  renderRepositoryChrome();
373
435
  if (!project?.connected) {
374
- // No repository: the Studio is still a run viewer for website audits.
375
- if (state.audits.length && state.activeView === "runs") { showProduct(); renderRuns(); return; }
376
- showSourceOnboarding();
436
+ if ((state.audits.length || state.explores.length) && state.activeView === "runs") { showProduct(); renderRuns(); return; }
437
+ if (state.promptRun) { showProduct(); renderRuns(); renderDeviceChrome(); renderChat(); return; }
438
+ showPrompt();
377
439
  renderRuns();
378
440
  return;
379
441
  }
@@ -397,25 +459,30 @@ async function refreshSession() {
397
459
  const local = state.session.mode === "local";
398
460
  $("#mode-pill").textContent = local ? "Self-host · this machine" : "Cloud · outbound runner";
399
461
  $("#onboarding-mode-pill").textContent = local ? "Self-host · this machine" : "Cloud";
400
- $("#privacy-note-title").textContent = local ? "Your code stays on this machine." : "Your repository stays in your private Tapp workspace.";
462
+ $("#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.";
401
463
  }
402
464
 
403
465
  async function refresh() {
404
- [state.project, state.live, { audits: state.audits = [] }] = await Promise.all([api("/api/project"), api("/api/live-session"), api("/api/audits").catch(() => ({ audits: [] }))]);
466
+ const [project, live, runs] = await Promise.all([api("/api/project"), api("/api/live-session"), api("/api/audits").catch(() => ({ audits: [], explores: [] }))]);
467
+ state.project = project;
468
+ state.live = live;
469
+ state.audits = runs.audits || [];
470
+ state.explores = runs.explores || [];
405
471
  renderProject();
406
472
  }
407
473
 
408
- async function runOperation(name, body = {}) {
474
+ async function runOperation(name, body = {}, { input = "" } = {}) {
409
475
  if (state.activeJob) throw new Error("Another operation is still running");
410
476
  const started = await api(`/api/operations/${name}`, { method:"POST", body:JSON.stringify(body) });
477
+ if (!started.job) return started; // synchronous answers (open a path, a business name)
411
478
  state.activeJob = started.job.id;
412
479
  const drawer = $("#operation-drawer");
413
480
  drawer.classList.remove("hidden");
414
481
  $("#operation-title").textContent = name === "audit" ? "Read-only audit" : pretty(name);
415
482
  $("#operation-progress").textContent = "Starting";
416
483
  $("#operation-progress-bar").style.width = "6%";
417
- syncTranscriptFromJob(name, started.job);
418
- if ($("#product-shell").classList.contains("hidden") === false) { renderCommandState(started.job, name); renderChat(); }
484
+ syncTranscriptFromJob(name, { ...started.job, input });
485
+ if (!$("#product-shell").classList.contains("hidden")) { renderCommandState(started.job, name); renderChat(); }
419
486
  try {
420
487
  while (true) {
421
488
  await new Promise((resolve) => setTimeout(resolve, 650));
@@ -424,13 +491,13 @@ async function runOperation(name, body = {}) {
424
491
  $("#operation-progress").textContent = progress?.text || "Working…";
425
492
  const ratio = progress?.current && progress?.total ? Math.min(92, Math.round(progress.current / progress.total * 100)) : Math.min(88, 8 + job.progress.length * 4);
426
493
  $("#operation-progress-bar").style.width = `${ratio}%`;
427
- syncTranscriptFromJob(name, job);
428
- if ($("#product-shell").classList.contains("hidden") === false) { renderCommandState(job, name); renderChat(); }
494
+ syncTranscriptFromJob(name, { ...job, input });
495
+ if (!$("#product-shell").classList.contains("hidden")) { renderCommandState(job, name); renderChat(); }
429
496
  const screen = [...job.progress].reverse().find((entry) => entry.screen)?.screen;
430
497
  if (screen && !state.live?.active) $("#live-screen-title").textContent = screen;
431
498
  if (job.frame && !state.jobHasFrame) { state.jobHasFrame = true; refreshLiveFrame(); }
432
499
  if (operationIsPending(job.status)) continue;
433
- finishTranscript(name, job);
500
+ await finishTranscript(name, job);
434
501
  if (job.status === "failed") throw new Error(job.error?.message || "Operation failed");
435
502
  if (job.status !== "completed") throw new Error(`Operation ended in an unknown '${job.status}' state`);
436
503
  $("#operation-progress-bar").style.width = "100%";
@@ -438,7 +505,6 @@ async function runOperation(name, body = {}) {
438
505
  else if (name === "session-save-flow") toast(`Saved ${job.result.path} as a reviewable deterministic Flow`);
439
506
  else if (name === "gate" && job.result.passed === false) toast("The release gate blocked this revision. Tapp did not soften the result.", true);
440
507
  else if (name === "audit") toast(`Audited ${job.result.pagesAudited} page(s) — ${job.result.issueCount} distinct issue(s)`);
441
- else toast(`${pretty(name)} completed`);
442
508
  return job.result;
443
509
  }
444
510
  } finally {
@@ -448,18 +514,44 @@ async function runOperation(name, body = {}) {
448
514
  await refreshSession();
449
515
  await refresh();
450
516
  } finally {
451
- // The operation is not visually complete until the resulting snapshot/frame has rendered.
517
+ renderChat();
452
518
  drawer.classList.add("hidden");
453
519
  }
454
520
  }
455
521
  }
456
522
 
523
+ // "What should tapp test?" — route by what was typed. The server classifies again and refuses
524
+ // what the mode cannot do (a hosted Studio cannot open a path on your machine).
525
+ async function startFromPrompt(raw) {
526
+ const prompt = classifyPrompt(raw);
527
+ if (prompt.kind === "empty") return;
528
+ if (prompt.kind === "url") {
529
+ state.promptRun = true; state.promptPlatform = "web";
530
+ showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
531
+ const result = await runOperation("audit", { url: prompt.value }, { input: prompt.value });
532
+ state.selectedRunId = result?.capture?.id || state.selectedRunId;
533
+ return;
534
+ }
535
+ if (["bundle", "app", "apk"].includes(prompt.kind)) {
536
+ state.promptRun = true; state.promptPlatform = prompt.kind === "apk" ? "android" : "ios";
537
+ showProduct(); activateView("overview"); renderDeviceChrome(); renderChat();
538
+ const result = await runOperation("explore-build", { input: prompt.value }, { input: prompt.value });
539
+ state.selectedRunId = result?.capture?.id || state.selectedRunId;
540
+ return;
541
+ }
542
+ const answer = await runOperation("open", { input: prompt.value }, { input: prompt.value });
543
+ if (answer?.kind === "business") { toast(answer.message, true); return; }
544
+ await refreshSession();
545
+ await refresh();
546
+ state.selectedTargetId = "";
547
+ if (state.project?.connected && !state.project?.state?.inspected) await runOperation("initialize", { write:true });
548
+ }
549
+
457
550
  async function auditWebsite(url) {
458
551
  const trimmed = String(url || "").trim();
459
552
  if (!/^https?:\/\//i.test(trimmed)) { toast("Enter an http(s) URL to audit", true); return; }
460
- const result = await runOperation("audit", { url: trimmed });
553
+ const result = await runOperation("audit", { url: trimmed }, { input: trimmed });
461
554
  state.selectedRunId = result?.capture?.id || state.selectedRunId;
462
- showProduct();
463
555
  activateView("runs");
464
556
  renderRuns();
465
557
  }
@@ -476,29 +568,29 @@ document.addEventListener("click", (event) => {
476
568
  }
477
569
  const runButton = event.target.closest("[data-run-id]");
478
570
  if (runButton) { state.selectedRunId = runButton.dataset.runId; renderRuns(); }
571
+ const suggestion = event.target.closest("[data-prompt]");
572
+ if (suggestion) { const input = $("#prompt-input"); input.value = suggestion.dataset.prompt; input.focus(); input.select(); }
479
573
  const liveControl = event.target.closest("[data-live-control]");
480
574
  if (liveControl) {
481
575
  const target = liveControl.dataset.liveTarget;
482
576
  $("#live-action-target").value = target;
483
- if (liveControl.dataset.liveInput === "true") {
484
- $("#live-action-text").focus();
485
- } else {
486
- runOperation("session-act", { action:"tap", id:target }).catch((error) => toast(error.message, true));
487
- }
577
+ if (liveControl.dataset.liveInput === "true") $("#live-action-text").focus();
578
+ else runOperation("session-act", { action:"tap", id:target }).catch((error) => toast(error.message, true));
488
579
  }
489
580
  });
490
581
 
491
582
  document.addEventListener("submit", (event) => {
492
- const form = event.target.closest("form.audit-form");
493
- if (!form) return;
494
- event.preventDefault();
495
- auditWebsite(form.elements.url.value).catch((error) => toast(error.message, true));
583
+ const audit = event.target.closest("form.audit-form");
584
+ if (audit) { event.preventDefault(); auditWebsite(audit.elements.url.value).catch((error) => toast(error.message, true)); return; }
585
+ const prompt = event.target.closest("#prompt-form");
586
+ if (prompt) { event.preventDefault(); startFromPrompt(prompt.elements.input.value).catch((error) => toast(error.message, true)); }
496
587
  });
497
588
 
498
- $$("[data-brand-home]").forEach((button) => button.addEventListener("click", () => state.project?.connected ? (showProduct(), activateView("overview")) : showSourceOnboarding()));
589
+ $$("[data-brand-home]").forEach((button) => button.addEventListener("click", () => state.project?.connected ? (showProduct(), activateView("overview")) : showPrompt()));
499
590
  $("#command-run").addEventListener("click", () => runOperation("initialize", operationPayload({ explore:true })).catch((error) => toast(error.message, true)));
500
591
  $("#refresh-project").addEventListener("click", () => refresh().catch((error) => toast(error.message, true)));
501
- $("#change-source").addEventListener("click", showSourceOnboarding);
592
+ $("#change-source").addEventListener("click", showPrompt);
593
+ $("#chat-toggle").addEventListener("click", () => setChatCollapsed(!state.chatCollapsed));
502
594
  $("#repository-switcher").addEventListener("change", async (event) => {
503
595
  try { await api("/api/repositories/select", { method:"POST", body:JSON.stringify({ id:event.target.value }) }); state.selectedTargetId = ""; await refreshSession(); await refresh(); } catch (error) { toast(error.message, true); }
504
596
  });
@@ -514,9 +606,8 @@ $("#live-swipe").addEventListener("click", () => runOperation("session-act", { a
514
606
  $("#run-gate").addEventListener("click", () => runOperation("gate", operationPayload()).catch((error) => toast(error.message, true)));
515
607
 
516
608
  try {
609
+ try { setChatCollapsed(localStorage.getItem("tapp:chat-collapsed") === "1"); } catch { /* storage may be unavailable */ }
517
610
  await refreshSession();
518
611
  await refresh();
519
- // A repository supplied by `tapp app /path` is inspected immediately, then stops for an
520
- // explicit target choice when detection is ambiguous.
521
612
  if (state.project?.connected && !state.project?.state?.inspected) await runOperation("initialize", { write:true });
522
613
  } catch (error) { toast(error.message, true); }