@aarwitz/tapp 0.35.6 → 0.35.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tapp",
3
3
  "description": "Give Claude hands and eyes on iOS, Android, and web apps, with exploration, replayable flows, evidence, and deterministic CI gates.",
4
- "version": "0.35.6",
4
+ "version": "0.35.7",
5
5
  "author": {
6
6
  "name": "Aaron Horowitz",
7
7
  "url": "https://github.com/aarwitz"
@@ -24,7 +24,7 @@
24
24
  "command": "npx",
25
25
  "args": [
26
26
  "-y",
27
- "@aarwitz/tapp@0.35.6",
27
+ "@aarwitz/tapp@0.35.7",
28
28
  "mcp"
29
29
  ],
30
30
  "cwd": "${CLAUDE_PROJECT_DIR}"
package/AGENTS.md CHANGED
@@ -58,7 +58,19 @@ Tapp's current action and pointer; the overlay is omitted from evidence screensh
58
58
  drive the person's existing/default browser profile.
59
59
 
60
60
  The interactive session/record loop is MCP-only (it needs a long-lived process). Flow replay is
61
- also available in the CLI. The rest of this playbook assumes the `tapp_*` MCP tools are connected. With
61
+ also available in the CLI.
62
+
63
+ To film an iOS Flow, `tapp run <flow.yml> --record take.mp4 [--hold 3s]` records the simulator and
64
+ writes `take.steps.json` beside it: every step in the video's own seconds, so a cut can be made by
65
+ step name instead of off a contact sheet. `--hold` keeps the last screen on screen for that long —
66
+ it has to be added to the file afterwards, because the simulator records changes rather than
67
+ frames and a motionless screen records nothing. Needs ffmpeg on the machine.
68
+
69
+ A one-time system alert ("Allow notifications", "You have changed the icon") belongs to iOS rather
70
+ than to the app, so a Flow's own `tap:` reaches it only by its exact button label. `alerts: allow`
71
+ or `alerts: dismiss` at the top of an iOS Flow clears whichever one appears and records which
72
+ button was pressed, which is what keeps a journey replayable when the alert shows up on some runs
73
+ and not others. The rest of this playbook assumes the `tapp_*` MCP tools are connected. With
62
74
  MCP, the no-bundle-id path is: `tapp_build {projectDir}` (auto-detects + builds +
63
75
  installs, returns the bundle id) → `tapp_explore {appBundleId}`.
64
76
 
@@ -487,6 +487,74 @@ class ExplorerTests: XCTestCase {
487
487
 
488
488
  private var backTitleHistory: [String] = []
489
489
 
490
+ /// A system alert belongs to SpringBoard, not to the app, so a Flow's `tap: OK` cannot reach it
491
+ /// and the step fails on a button the author can plainly see. A field case: changing an app's
492
+ /// theme switched its icon, iOS asked "You have changed the icon for <app>", and the flow for
493
+ /// that screen stopped after one choice.
494
+ private func systemAlertButton(labelled label: String) -> XCUIElement? {
495
+ let alert = XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts.firstMatch
496
+ guard alert.exists else { return nil }
497
+ // By label, not by subscript: `alert.buttons["Allow"]` matched "Allow Once" on an alert
498
+ // that has no "Allow" at all, so a flow asking for a button that is not there pressed a
499
+ // different one and passed.
500
+ let wanted = alertLabelKey(label)
501
+ return alert.buttons.allElementsBoundByIndex
502
+ .first { alertLabelKey($0.label) == wanted && $0.exists && $0.isHittable }
503
+ }
504
+
505
+ /// The labels an `alerts:` setting will press, and nothing else.
506
+ ///
507
+ /// Matched through `alertLabelKey`, because iOS writes "Don\u{2019}t Allow" with a typographic
508
+ /// apostrophe: a list spelled with the ASCII one matched nothing at all, the dismiss mode
509
+ /// silently did nothing, and the run still reported a pass (found by running it against Maps).
510
+ private static let alertAllowLabels = ["Allow While Using App", "Allow Once", "Allow", "OK", "Continue"]
511
+ private static let alertDismissLabels = ["Don't Allow", "Not Now", "Cancel", "Dismiss", "Later"]
512
+
513
+ /// Compare alert labels the way a person reads them: either apostrophe, any case.
514
+ private func alertLabelKey(_ label: String) -> String {
515
+ label.replacingOccurrences(of: "\u{2019}", with: "'")
516
+ .trimmingCharacters(in: .whitespacesAndNewlines)
517
+ .lowercased()
518
+ }
519
+
520
+ /// Clear a one-time system alert standing between the flow and the app (TM-497).
521
+ ///
522
+ /// Three of the eight takes on 11/7 were re-recorded because of these. Returns the button it
523
+ /// pressed, so the run records that it diverged from the script rather than quietly doing it.
524
+ ///
525
+ /// Only a recognised label, or a single-button alert. An unrecognised alert with a choice in it
526
+ /// is left alone and the step fails naming its buttons: guessing on a dialog about permissions,
527
+ /// money or deletion is worse than stopping.
528
+ private func handleSystemAlert(mode: String) -> String? {
529
+ let alert = XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts.firstMatch
530
+ guard alert.exists else { return nil }
531
+ let wanted = (mode == "dismiss" ? Self.alertDismissLabels : Self.alertAllowLabels).map(alertLabelKey)
532
+ let present = alert.buttons.allElementsBoundByIndex
533
+ for key in wanted {
534
+ if let button = present.first(where: { alertLabelKey($0.label) == key && $0.exists && $0.isHittable }) {
535
+ let label = button.label
536
+ button.tap()
537
+ waitForUIStability(timeout: 1.5)
538
+ return label
539
+ }
540
+ }
541
+ if alert.buttons.count == 1 {
542
+ let button = alert.buttons.element(boundBy: 0)
543
+ let label = button.label
544
+ button.tap()
545
+ waitForUIStability(timeout: 1.5)
546
+ return label
547
+ }
548
+ return nil
549
+ }
550
+
551
+ /// What a system alert offers, for a failure message that names the way out.
552
+ private func systemAlertButtonLabels() -> [String] {
553
+ let alert = XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts.firstMatch
554
+ guard alert.exists else { return [] }
555
+ return alert.buttons.allElementsBoundByIndex.map { $0.label }.filter { !$0.isEmpty }
556
+ }
557
+
490
558
  private func sessionTapById(_ identifier: String) -> String {
491
559
  var existedButNotHittable = false
492
560
  var existedButDisabled = false
@@ -1046,6 +1114,10 @@ class ExplorerTests: XCTestCase {
1046
1114
  // Per-flow wait default (field issue #20): a splash that prefetches for ~8s makes the
1047
1115
  // fixed 6s wait_for fail on a healthy app. Steps may still override individually.
1048
1116
  let flowDefaultTimeoutMs = (flow["timeoutMs"] as? Int) ?? (flow["timeout"] as? Int) ?? 6000
1117
+ // `alerts: allow|dismiss` (TM-497). One-time system alerts — "Allow notifications", "You
1118
+ // have changed the icon" — appear on some runs and not others and belong to SpringBoard,
1119
+ // not the app, so without this they stop the flow dead on a screen nobody scripted.
1120
+ let alertMode = ((flow["alerts"] as? String) ?? "").lowercased()
1049
1121
  // XCTest runs teardown blocks even when a step aborts unexpectedly. Keep the final
1050
1122
  // visible frame inspectable for both successful and failing replays (public issue #26).
1051
1123
  addTeardownBlock { [self] in recordFlowScreenshot(name: "flow-final") }
@@ -1088,6 +1160,16 @@ class ExplorerTests: XCTestCase {
1088
1160
  var failed = 0
1089
1161
  var executed = 0
1090
1162
  var aiIndex = 0
1163
+ // TM-497: every step says when it happened, in milliseconds from the flow's start, so a
1164
+ // recording can be cut by step name. The JavaScript runners have carried this since the
1165
+ // first half of the story; iOS has its own loop and did not, which meant the one platform
1166
+ // the demo videos are made on was the one platform whose steps had no times.
1167
+ //
1168
+ // Contiguous by construction: a step starts where the previous one ended, so its window
1169
+ // carries its own settling and waiting — the seconds an editor is looking for.
1170
+ let flowStartedAt = Date()
1171
+ print("OCQA_FLOW_CLOCK:{\"startedAtEpochMs\":\(Int(flowStartedAt.timeIntervalSince1970 * 1000))}")
1172
+ var stepStartMs = 0
1091
1173
  for (i, raw) in steps.enumerated() {
1092
1174
  let idx = i + 1
1093
1175
  executed = idx
@@ -1100,10 +1182,22 @@ class ExplorerTests: XCTestCase {
1100
1182
  let timeoutMs = (step["timeoutMs"] as? Int) ?? (step["timeout"] as? Int) ?? flowDefaultTimeoutMs
1101
1183
  var status = "pass"
1102
1184
  var detail = ""
1185
+ // Before the step, not after: an alert on screen is what makes the step fail.
1186
+ var alertNote = ""
1187
+ if alertMode == "allow" || alertMode == "dismiss", let pressed = handleSystemAlert(mode: alertMode) {
1188
+ alertNote = "a system alert was \(alertMode == "dismiss" ? "dismissed" : "allowed") first: pressed ‘\(escapeJSON(pressed))’"
1189
+ }
1103
1190
 
1104
1191
  switch action {
1105
1192
  case "tap":
1106
- let tapStatus = sessionTapById(target)
1193
+ var tapStatus = sessionTapById(target)
1194
+ // TM-686: the button really is on screen, it just belongs to SpringBoard.
1195
+ if tapStatus != "ok", let alertButton = systemAlertButton(labelled: target) {
1196
+ alertButton.tap()
1197
+ waitForUIStability(timeout: 1.5)
1198
+ tapStatus = "ok"
1199
+ detail = "‘\(escapeJSON(target))’ is a system alert's button, not the app's"
1200
+ }
1107
1201
  status = tapStatus == "ok" ? "pass" : "fail"
1108
1202
  if status == "fail" {
1109
1203
  // Name which of the three it was. "Disabled" in particular sends the
@@ -1115,6 +1209,10 @@ class ExplorerTests: XCTestCase {
1115
1209
  case "not_hittable": detail = "‘\(target)’ exists but could not be reached, even after dismissing the keyboard and scrolling"
1116
1210
  default: detail = "could not find ‘\(target)’ on this screen"
1117
1211
  }
1212
+ let alertButtons = systemAlertButtonLabels()
1213
+ if !alertButtons.isEmpty {
1214
+ detail += " — a system alert is in the way, offering \(escapeJSON(alertButtons.joined(separator: ", "))); add `alerts: allow` or `alerts: dismiss` to the flow, or tap one of them"
1215
+ }
1118
1216
  }
1119
1217
  case "type":
1120
1218
  status = sessionType(value, id: target.isEmpty ? nil : target) ? "pass" : "fail"
@@ -1181,7 +1279,13 @@ class ExplorerTests: XCTestCase {
1181
1279
  let isAssert = action.hasPrefix("assert_")
1182
1280
  let taskEvidence = taskName.isEmpty ? "" : ",\"task\":\"\(escapeJSON(taskName))\""
1183
1281
  let contractEvidence = contractName.isEmpty ? "" : ",\"contract\":\"\(escapeJSON(contractName))\""
1184
- print("OCQA_FLOW_STEP:{\"index\":\(idx),\"action\":\"\(escapeJSON(action))\",\"target\":\"\(escapeJSON(target.isEmpty ? value : target))\",\"assert\":\(isAssert),\"status\":\"\(status)\",\"detail\":\"\(escapeJSON(detail))\"\(taskEvidence)\(contractEvidence)}")
1282
+ // Kept whatever the step then did: the first version wrote it into `detail` and the
1283
+ // tap-failure branch overwrote it, so a run that handled an alert and then failed said
1284
+ // nothing about the alert at all.
1285
+ if !alertNote.isEmpty { detail = detail.isEmpty ? alertNote : "\(alertNote); \(detail)" }
1286
+ let stepEndMs = Int(Date().timeIntervalSince(flowStartedAt) * 1000)
1287
+ print("OCQA_FLOW_STEP:{\"index\":\(idx),\"action\":\"\(escapeJSON(action))\",\"target\":\"\(escapeJSON(target.isEmpty ? value : target))\",\"assert\":\(isAssert),\"status\":\"\(status)\",\"detail\":\"\(escapeJSON(detail))\",\"startMs\":\(stepStartMs),\"endMs\":\(stepEndMs)\(taskEvidence)\(contractEvidence)}")
1288
+ stepStartMs = stepEndMs
1185
1289
  if status == "fail" {
1186
1290
  failed += 1
1187
1291
  // Web and Android flows write flow-failure-N.png next to the log; iOS buried the
package/bin/tapp.js CHANGED
@@ -1488,7 +1488,7 @@ switch (command) {
1488
1488
  break;
1489
1489
  }
1490
1490
  if (!["run", "validate"].includes(verb) || !flowPath) {
1491
- console.error("usage: tapp validate --example\n tapp flow steps [--json]\n tapp run <flow.yml|glob> [...more] [--var NAME=VALUE ...] [--platform ios|android|web] [--actor NAME] [--email VALUE] [--password VALUE] [--url URL] [--app-id ID] [--apk FILE] [--serial ID]\n tapp validate <flow.yml|glob> [...more]\n Several Flows (or a glob) run in sequence and print one line per Flow; exit 1 if any failed.");
1491
+ console.error("usage: tapp validate --example\n tapp flow steps [--json]\n tapp run <flow.yml|glob> [...more] [--var NAME=VALUE ...] [--platform ios|android|web] [--actor NAME] [--email VALUE] [--password VALUE] [--url URL] [--app-id ID] [--apk FILE] [--serial ID] [--record out.mp4 [--hold 3s]]\n tapp validate <flow.yml|glob> [...more]\n Several Flows (or a glob) run in sequence and print one line per Flow; exit 1 if any failed.");
1492
1492
  process.exit(2);
1493
1493
  }
1494
1494
  // Several Flows in one command (field issue #9): the shell usually expands the glob, but a
@@ -1648,7 +1648,77 @@ switch (command) {
1648
1648
  requireMacFor("iOS Flow replay");
1649
1649
  invocation = ["bash", [path.join(packageRoot, "scripts", "run-flow.sh"), absolute, typeof flags["bundle-id"] === "string" ? flags["bundle-id"] : flow.app || ""]];
1650
1650
  }
1651
+ // --record / --hold (TM-497). tapp owns the recorder so the video and the step times come out
1652
+ // of the same run; before this the wrapper started simctl by hand and the two clocks drifted.
1653
+ const recordTo = typeof flags.record === "string" && flags.record ? path.resolve(flags.record) : "";
1654
+ let holdMs = 0;
1655
+ let recorder = null;
1656
+ if (recordTo || flags.hold !== undefined) {
1657
+ const { parseHold } = await import(path.join(packageRoot, "mcp-server", "src", "flow-recording.js"));
1658
+ try { holdMs = parseHold(flags.hold === true ? "" : flags.hold); }
1659
+ catch (error) { console.error(`❌ ${error.message}`); process.exit(2); }
1660
+ }
1661
+ if (recordTo) {
1662
+ if (platform !== "ios") { console.error(`❌ --record records an iOS simulator (this Flow is ${platform})`); process.exit(2); }
1663
+ const { prepareRecorder, recorderToolingError, startRecording } = await import(path.join(packageRoot, "mcp-server", "src", "sim-recorder.js"));
1664
+ const missing = recorderToolingError();
1665
+ if (missing) { console.error(`❌ ${missing}`); process.exit(2); }
1666
+ const ready = prepareRecorder(env.TAPP_UDID);
1667
+ if (!ready.ok) { console.error(`❌ ${ready.error}`); process.exit(2); }
1668
+ // One line, because a repair nobody is told about costs the same three re-records next time.
1669
+ for (const note of ready.repaired) console.log(` recorder: ${note}`);
1670
+ recorder = startRecording({ udid: env.TAPP_UDID, out: recordTo, holdMs });
1671
+ // The recorder marks itself on a still screen; the flow must not start before that mark, or
1672
+ // the first change in the file is the app moving and the whole clock is wrong.
1673
+ await recorder.ready();
1674
+ }
1675
+ const flowStartedAtMs = Date.now();
1651
1676
  const result = spawnSync(invocation[0], invocation[1], { stdio: "inherit", env });
1677
+ if (recorder) {
1678
+ const stopped = await recorder.stop();
1679
+ if (!stopped.ok) {
1680
+ console.error(`\n⚠️ ${stopped.error}`);
1681
+ } else {
1682
+ const { flowStartedAtEpochMs, parseFlowSteps, writeStepsSidecar } = await import(path.join(packageRoot, "mcp-server", "src", "flow-recording.js"));
1683
+ const logText = fs.existsSync(flowLog) ? fs.readFileSync(flowLog, "utf8") : "";
1684
+ const steps = parseFlowSteps(logText);
1685
+ // The runner's own start, not this process's: on iOS most of a minute passes building and
1686
+ // launching the harness while the recorder is already rolling, and using the CLI's clock
1687
+ // puts every step that far too early in the video.
1688
+ const startedAt = flowStartedAtEpochMs(logText) ?? flowStartedAtMs;
1689
+ // The recorder writes a frame when the screen CHANGES, so a flow that ends on a still
1690
+ // screen leaves the file ending before the flow does and the last steps land past its end.
1691
+ // Cloning the final frame covers that gap; the hold comes on top of it. This happens
1692
+ // before the sidecar is written so the sidecar can be told the file's real length.
1693
+ const { padTail, tailMsFor } = await import(path.join(packageRoot, "mcp-server", "src", "sim-recorder.js"));
1694
+ const { stepsInVideoTime } = await import(path.join(packageRoot, "mcp-server", "src", "flow-recording.js"));
1695
+ const placed = stepsInVideoTime(steps, { flowStartedAtMs: startedAt, recordingStartedAtMs: stopped.startedAtMs });
1696
+ const lastStepEndMs = placed.length ? placed[placed.length - 1].end * 1000 : 0;
1697
+ // TAPP_RECORD_DEBUG keeps the capture exactly as simctl wrote it, before any tail is added,
1698
+ // and prints the two clocks. This is what a report of "the step times are wrong" needs:
1699
+ // every timing bug found while building this was invisible in the finished file.
1700
+ if (process.env.TAPP_RECORD_DEBUG === "1") {
1701
+ fs.copyFileSync(recordTo, `${recordTo}.raw.mp4`);
1702
+ console.error(`[record] capture ${(stopped.durationMs / 1000).toFixed(3)}s, ${stopped.frames} frames, first frame at ${stopped.startedAtMs}, flow started at ${startedAt} (+${((startedAt - stopped.startedAtMs) / 1000).toFixed(3)}s), last step ends ${(lastStepEndMs / 1000).toFixed(3)}s`);
1703
+ console.error(`[record] capture kept unpadded at ${recordTo}.raw.mp4`);
1704
+ }
1705
+ const held = padTail(recordTo, tailMsFor({ durationMs: stopped.durationMs, lastStepEndMs, holdMs }));
1706
+ if (held.error) console.error(`⚠️ ${held.error}`);
1707
+ const finalMs = held.durationMs ?? stopped.durationMs;
1708
+ // Say how much of the finished file is a held frame rather than captured picture. The
1709
+ // recorder stops writing when the screen stops changing, so the tail is always partly a
1710
+ // clone — a few seconds on a normal run. One take ended its capture 26 seconds before the
1711
+ // flow did and the rest was a single frozen frame, and the finished file gave no sign of
1712
+ // it; anyone editing that would have found out the hard way.
1713
+ const heldMs = Math.max(0, finalMs - stopped.durationMs);
1714
+ const sidecar = writeStepsSidecar(recordTo, steps, {
1715
+ flowStartedAtMs: startedAt, recordingStartedAtMs: stopped.startedAtMs, holdMs,
1716
+ name: flow.name || "", videoDurationMs: finalMs,
1717
+ });
1718
+ console.log(`\nRecording: ${recordTo} (${(finalMs / 1000).toFixed(1)}s — ${(stopped.durationMs / 1000).toFixed(1)}s captured${heldMs > 500 ? `, ${(heldMs / 1000).toFixed(1)}s holding the last screen` : ""})`);
1719
+ console.log(`Step times: ${sidecar.path} (${sidecar.steps.length} step${sidecar.steps.length === 1 ? "" : "s"} in the video's own seconds)`);
1720
+ }
1721
+ }
1652
1722
  const evidenceWritten = fs.existsSync(evidenceDir) && fs.readdirSync(evidenceDir).length > 0;
1653
1723
  if (evidenceWritten) console.log(`\nEvidence: ${evidenceDir}`);
1654
1724
  else console.error("\n⚠️ Evidence unavailable — the platform runner did not write any artifacts for this Flow run.");
package/browser/app.css CHANGED
@@ -631,3 +631,80 @@ dialog::backdrop { background:rgba(0,0,0,.6); }
631
631
 
632
632
  /* A suggestion this Studio cannot start is dimmed, not deleted: pressing it still answers. */
633
633
  .prompt-suggestions [data-kind].elsewhere { opacity:.62; }
634
+
635
+ /* ---- Findings and Coverage (TM-794) -------------------------------------------------------
636
+ Findings reads as a short list of kinds a person can scan, each opening onto the individual
637
+ places. Coverage reads left to right, one column per step away from the screen the run
638
+ started on, the way the run actually went. */
639
+
640
+ .run-picker { min-width:240px; max-width:340px; padding:7px 10px; border:1px solid var(--line); border-radius:var(--radius); background:var(--control); color:var(--ink); font-size:11px; }
641
+
642
+ .findings-tally { display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin-bottom:14px; }
643
+ .findings-tally .button-link { margin-top:0; margin-left:auto; }
644
+ .sev-tally { border:1px solid var(--line); border-radius:999px; padding:4px 11px; font-size:11px; font-weight:600; color:var(--muted); background:var(--control); }
645
+ .sev-tally.critical,.sev-tally.high { color:var(--tapp-red); border-color:rgba(248,81,73,.45); background:var(--tapp-red-bg); }
646
+ .sev-tally.medium { color:var(--tapp-amber-soft); border-color:rgba(210,153,34,.45); background:var(--tapp-amber-bg); }
647
+
648
+ .finding-group { border:1px solid var(--line); border-radius:var(--radius); background:var(--paper); margin-bottom:8px; }
649
+ .finding-group>summary { display:flex; align-items:center; gap:10px; padding:12px 14px; cursor:pointer; list-style:none; }
650
+ .finding-group>summary::-webkit-details-marker { display:none; }
651
+ .finding-group>summary::after { content:"▾"; width:14px; text-align:center; color:var(--muted); font-size:11px; line-height:1; transition:transform .12s ease; }
652
+ .finding-group.single { display:flex; align-items:center; gap:10px; padding:12px 14px; }
653
+ .finding-group.single .group-count { color:var(--faint); }
654
+ .finding-group[open]>summary::after { transform:rotate(180deg); }
655
+ .finding-group>summary:hover { background:var(--wash); border-radius:var(--radius); }
656
+ .group-label { flex:1; font-weight:600; font-size:13px; }
657
+ .group-count { color:var(--muted); font-size:11px; font-variant-numeric:tabular-nums; }
658
+ .sev-dot { width:8px; height:8px; border-radius:50%; background:var(--faint); flex:none; }
659
+ .sev-dot.critical,.sev-dot.high { background:var(--tapp-red); }
660
+ .sev-dot.medium { background:var(--tapp-amber); }
661
+ .sev-dot.low { background:var(--tapp-text-faint); }
662
+ .finding-group .detail-list { padding:0 18px 14px 34px; }
663
+ .finding-group .detail-list li { margin-bottom:5px; }
664
+ .finding-group .detail-list b { text-transform:uppercase; font-size:9px; letter-spacing:.06em; }
665
+ .detail-list b.sev-critical,.detail-list b.sev-high { color:var(--tapp-red); }
666
+ .detail-list b.sev-medium { color:var(--tapp-amber-soft); }
667
+
668
+ .coverage-counts { display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin-bottom:16px; }
669
+ .coverage-counts span { border:1px solid var(--line); border-radius:999px; padding:5px 12px; font-size:11px; color:var(--muted); background:var(--control); }
670
+ .coverage-counts span b { color:var(--ink); font-size:13px; margin-right:4px; font-variant-numeric:tabular-nums; }
671
+ .coverage-counts .button-link { margin-top:0; margin-left:auto; }
672
+
673
+ .coverage-map { display:flex; gap:22px; align-items:flex-start; overflow-x:auto; padding-bottom:10px; }
674
+ .coverage-column { display:flex; flex-direction:column; gap:14px; flex:none; width:210px; }
675
+ .coverage-column-head { margin:0 0 2px; color:var(--faint); font-size:10px; font-weight:700; letter-spacing:.1em; text-transform:uppercase; }
676
+
677
+ .screen-card { border:1px solid var(--line); border-radius:var(--radius-lg); background:var(--paper); padding:10px; }
678
+ .screen-card.orphan { border-style:dashed; }
679
+ .screen-card strong { display:block; margin-top:9px; font-size:12px; line-height:1.3; }
680
+ .screen-card>small { display:block; margin-top:3px; color:var(--faint); font-size:10px; }
681
+ /* The card is the shape of the thing it is a picture of. A web still forced into a phone's
682
+ portrait box loses its left edge to `cover`, taking the screen's own name with it. */
683
+ .screen-shot { position:relative; aspect-ratio:3/4; border-radius:var(--radius); overflow:hidden; background:var(--wash); display:flex; align-items:center; justify-content:center; }
684
+ .coverage-map[data-platform="web"] .screen-shot,
685
+ .coverage-map[data-platform="macos"] .screen-shot { aspect-ratio:16/10; }
686
+ .coverage-map[data-platform="web"] .coverage-column,
687
+ .coverage-map[data-platform="macos"] .coverage-column { width:260px; }
688
+ .screen-shot img { width:100%; height:100%; object-fit:cover; object-position:top center; }
689
+ .screen-shot-none { color:var(--faint); font-size:10px; }
690
+ .screen-note { position:absolute; left:6px; right:6px; bottom:6px; padding:3px 6px; border-radius:4px; background:rgba(9,12,17,.82); color:var(--tapp-amber-soft); font-size:9px; text-align:center; }
691
+ .screen-exits { margin:9px 0 0; padding:0; list-style:none; display:flex; flex-direction:column; gap:4px; }
692
+ .screen-exits li { color:var(--muted); font-size:10px; line-height:1.35; }
693
+ .screen-exits li span { color:var(--faint); }
694
+ .screen-exits-none { margin:9px 0 0; color:var(--faint); font-size:10px; }
695
+ .coverage-note { margin-top:14px; font-size:11px; }
696
+
697
+ @media (max-width:860px) {
698
+ .coverage-column { width:168px; }
699
+ .run-picker { min-width:0; width:100%; max-width:none; }
700
+ }
701
+
702
+ .findings-section { margin-bottom:26px; }
703
+ .findings-section h2 { font-size:14px; margin-bottom:4px; }
704
+ .findings-section h2 i { color:var(--muted); font-style:normal; font-size:12px; font-variant-numeric:tabular-nums; }
705
+ .findings-section>.muted { font-size:11px; margin-bottom:10px; }
706
+
707
+ /* A run with no recorded transitions has no path to lay out, so its screens are a plain grid. */
708
+ .coverage-map.flat { display:grid; grid-template-columns:repeat(auto-fill,minmax(210px,1fr)); gap:16px; overflow-x:visible; }
709
+ .coverage-map.flat[data-platform="web"] { grid-template-columns:repeat(auto-fill,minmax(260px,1fr)); }
710
+ .coverage-map.flat .screen-card { width:auto; }
package/browser/app.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { customerProductContract } from "./product-contract.js";
2
- import { classifyPrompt, narrate, narrateFinding, operationIsPending, summarize } from "./view-model.js";
2
+ import { classifyPrompt, coverageGraph, groupFindings, narrate, narrateFinding, operationIsPending, severityTally, 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 || "");
@@ -141,6 +141,10 @@ function activateView(view) {
141
141
  $$('.primary-nav [data-view]').forEach((button) => button.classList.toggle("active", button.dataset.view === view));
142
142
  history.replaceState(null, "", `#${view}`);
143
143
  window.scrollTo({ top:0, behavior:"instant" });
144
+ // Findings and Coverage read whichever run is selected; render on arrival so they are never a
145
+ // stale picture of a run the person has since changed in another view.
146
+ if (view === "findings") renderFindings();
147
+ if (view === "coverage") renderCoverage();
144
148
  }
145
149
 
146
150
  // A hosted Studio has no Mac, no simulator and no access to the visitor's disk, so folders,
@@ -742,6 +746,9 @@ function renderRuns() {
742
746
  const chosen = runs.find((run) => run.id === state.selectedRunId) || runs[0];
743
747
  if (chosen) state.selectedRunId = chosen.id;
744
748
  renderRunDetail(chosen);
749
+ setCount("#findings-count", runFindings(chosen).length);
750
+ if (state.activeView === "findings") renderFindings();
751
+ if (state.activeView === "coverage") renderCoverage();
745
752
  }
746
753
 
747
754
  function detailLists(report) {
@@ -770,6 +777,214 @@ function renderRunDetail(run) {
770
777
  $("#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)}`;
771
778
  }
772
779
 
780
+ // ---- Findings and Coverage: reading a run (TM-794) ------------------------------------------
781
+ // Both views read the run the Runs view has selected, so picking a run in one picks it in all
782
+ // three. Neither computes anything about the run: Findings arranges the findings the engine
783
+ // reported, and Coverage draws the map the engine wrote beside the capture.
784
+
785
+ function selectedRun() {
786
+ const runs = allRuns();
787
+ return runs.find((run) => run.id === state.selectedRunId) || runs[0] || null;
788
+ }
789
+
790
+ // What a run reported, in the engine's own two kinds. A read-only audit keeps them apart on
791
+ // purpose: an *issue* is broken, an *observation* is something a person would notice and not
792
+ // like. Merging them would say a site is broken because its body text is faint, so the view
793
+ // keeps the separation the engine drew and groups each side on its own.
794
+ function runSections(run) {
795
+ if (!run) return [];
796
+ const page = (item) => ({ ...item, screen: item.screen || item.pages?.[0] || "" });
797
+ if (run.kind === "audit") {
798
+ return [
799
+ { id: "issues", title: "Broken", note: "Structural defects the pages were served with.", empty: "Nothing broken was observed. That says the pages are served without structural defects, not that the site works.", items: (run.audit?.issues || []).map(page) },
800
+ { id: "observations", title: "Worth a look", note: "Not broken — things a person would notice and may not like.", empty: "", items: (run.audit?.observations || []).map(page) },
801
+ ];
802
+ }
803
+ const report = run.kind === "explore" ? run.explore?.report : run.report;
804
+ return [{ id: "findings", title: "Findings", note: "", empty: "Nothing was found in the surfaces this run exercised. That is not the same as “this works”.", items: (report?.findings || []).map(page) }];
805
+ }
806
+
807
+ // Every finding a run reported, whatever kind of run it is — what the nav badge counts.
808
+ function runFindings(run) {
809
+ return runSections(run).flatMap((section) => section.items);
810
+ }
811
+
812
+ function runLabel(run) {
813
+ if (!run) return "";
814
+ if (run.kind === "audit") { try { return `Audit · ${new URL(run.audit.url).host}`; } catch { return `Audit · ${run.audit.url}`; } }
815
+ if (run.kind === "explore") return `Explore · ${run.explore.target || run.explore.platform}`;
816
+ return run.report?.headline ? String(run.report.headline).slice(0, 60) : `Release run ${run.id.slice(-8)}`;
817
+ }
818
+
819
+ // What a run drove, so its evidence can be shown in that thing's shape.
820
+ function runPlatform(run) {
821
+ if (!run) return "";
822
+ if (run.kind === "audit") return "web";
823
+ if (run.kind === "explore") return run.explore?.platform || "";
824
+ return run.report?.platform || "";
825
+ }
826
+
827
+ // The capture a run's evidence lives in. Explorations and audits are named for it; a gate run
828
+ // carries it inside its report.
829
+ function runCaptureId(run) {
830
+ if (!run) return "";
831
+ if (run.kind === "audit" || run.kind === "explore") return run.id;
832
+ return captureId(run.report);
833
+ }
834
+
835
+ function renderRunPicker(selector) {
836
+ const runs = allRuns();
837
+ const node = $(selector);
838
+ if (!node) return;
839
+ node.innerHTML = runs.map((run) => `<option value="${esc(run.id)}"${run.id === state.selectedRunId ? " selected" : ""}>${esc(runLabel(run))} · ${esc(compactDate(run.createdAt))}</option>`).join("");
840
+ node.classList.toggle("hidden", runs.length < 2);
841
+ }
842
+
843
+ function renderFindings() {
844
+ const run = selectedRun();
845
+ renderRunPicker("#findings-run");
846
+ const body = $("#findings-body");
847
+ if (!run) { body.innerHTML = '<div class="empty">No run yet. Put a URL in the prompt and tapp will go and look.</div>'; return; }
848
+ const sections = runSections(run).map((section) => ({ ...section, groups: groupFindings(section.items) }));
849
+ const total = sections.reduce((sum, section) => sum + section.items.length, 0);
850
+ const kinds = sections.reduce((sum, section) => sum + section.groups.length, 0);
851
+ $("#findings-title").textContent = runLabel(run);
852
+ $("#findings-note").textContent = total
853
+ ? `${total} in ${kinds} kind${kinds === 1 ? "" : "s"}, worst first. An observation, not a release decision.`
854
+ : "An observation, not a release decision.";
855
+ body.innerHTML = `<div class="findings-tally">${findingsTally(sections)}${evidenceLink(runCaptureId(run), "Visual report")}</div>
856
+ ${sections.filter((section) => section.groups.length || section.empty).map((section) => `
857
+ <section class="findings-section">
858
+ <h2>${esc(section.title)}${section.items.length ? ` <i>${section.items.length}</i>` : ""}</h2>
859
+ ${section.note ? `<p class="muted">${esc(section.note)}</p>` : ""}
860
+ ${section.groups.length ? section.groups.map(findingGroupHtml).join("") : `<p class="muted">${esc(section.empty)}</p>`}
861
+ </section>`).join("")}`;
862
+ }
863
+
864
+ function findingsTally(sections) {
865
+ return severityTally(sections.flatMap((section) => section.items))
866
+ .map(({ severity, count }) => `<span class="sev-tally ${esc(severity)}">${count} ${esc(severity)}</span>`).join("");
867
+ }
868
+
869
+ // Where one finding is, said once. An audit reports the pages a finding appears on, so naming
870
+ // the first of them and then counting them again reads as `on / (7 pages)`.
871
+ function findingWhere(item) {
872
+ const pages = item.pages || [];
873
+ if (pages.length > 1) return `on ${pages.length} pages`;
874
+ if (pages.length === 1) return `on ${pages[0]}`;
875
+ return item.screen ? `on ${item.screen}` : "";
876
+ }
877
+
878
+ // One kind of problem: its name in the engine's words, how many places it covers, and — once
879
+ // opened — every one of those places. A group that is already serious opens itself.
880
+ function findingGroupHtml(group) {
881
+ // A group of one is already fully written on its own row; opening it would show the same
882
+ // sentence again, so it is a row rather than something to click.
883
+ const item = group.count === 1 ? group.items[0] : null;
884
+ if (item) {
885
+ const where = findingWhere(item);
886
+ return `<div class="finding-group single">
887
+ <span class="sev-dot ${esc(group.severity)}" aria-hidden="true"></span>
888
+ <span class="group-label">${esc(group.label)}</span>
889
+ ${where ? `<span class="group-count">${esc(where)}</span>` : ""}
890
+ </div>`;
891
+ }
892
+ return `<details class="finding-group"${group.severity === "critical" || group.severity === "high" ? " open" : ""}>
893
+ <summary>
894
+ <span class="sev-dot ${esc(group.severity)}" aria-hidden="true"></span>
895
+ <span class="group-label">${esc(group.label)}</span>
896
+ <span class="group-count">${group.count}${group.screens.length > 1 ? ` · ${group.screens.length} screens` : ""}</span>
897
+ </summary>
898
+ <ul class="detail-list">${group.items.map((item) => `<li>
899
+ <b class="sev-${esc(String(item.severity || "info").toLowerCase())}">${esc(item.severity || "info")}</b> · ${esc(item.title || item.type || "Finding")}
900
+ <small>${esc(findingWhere(item))}</small>
901
+ </li>`).join("")}</ul>
902
+ </details>`;
903
+ }
904
+
905
+ function renderCoverage() {
906
+ const run = selectedRun();
907
+ renderRunPicker("#coverage-run");
908
+ const body = $("#coverage-body");
909
+ const counts = $("#coverage-counts");
910
+ if (!run) { counts.innerHTML = ""; body.innerHTML = '<div class="empty">No run yet.</div>'; return; }
911
+ const id = runCaptureId(run);
912
+ if (!id) { counts.innerHTML = ""; body.innerHTML = '<div class="empty">This run kept no capture, so there is no map to draw.</div>'; return; }
913
+ const cached = state.coverage?.[id];
914
+ if (!cached) { counts.innerHTML = ""; body.innerHTML = '<div class="empty">Reading the map this run wrote…</div>'; loadCoverage(id); return; }
915
+ if (cached.error) { counts.innerHTML = ""; body.innerHTML = `<div class="empty">${esc(cached.error)}</div>`; return; }
916
+ const graph = cached.graph;
917
+ if (!graph.screens.length) { counts.innerHTML = ""; body.innerHTML = '<div class="empty">This run recorded no screens. Older runs, and runs that never got past the first screen, have no map.</div>'; return; }
918
+
919
+ const actions = run.kind === "explore" ? run.explore?.report?.actionsPerformed : run.report?.actionsPerformed;
920
+ // A card takes the shape of the thing it is a picture of, the same rule the stage follows: a
921
+ // web page is landscape, a phone is portrait. Forced into the wrong one, `cover` crops a web
922
+ // still so hard that the screen's own name is cut off the left edge of its card.
923
+ const platform = runPlatform(run);
924
+ counts.innerHTML = `<span><b>${graph.counts.screens}</b> screens</span><span><b>${graph.counts.transitions}</b> transitions</span>${
925
+ actions ? `<span><b>${actions}</b> actions</span>` : ""}${evidenceLink(id, "Visual report")}`;
926
+
927
+ const byId = new Map(graph.screens.map((screen) => [screen.id, screen]));
928
+ // A run with no transitions has no path to draw. That is the normal and correct outcome of a
929
+ // read-only audit, which opens pages and clicks nothing — so say that, rather than labelling
930
+ // every page "no recorded way in" and reading as a fault in the run.
931
+ if (!graph.counts.transitions) {
932
+ body.innerHTML = `<p class="muted coverage-note">${run.kind === "audit"
933
+ ? "Nothing was clicked in this read-only pass, so no path between pages was recorded. These are the pages it opened."
934
+ : "This run recorded no way from one screen to another, so there is no path to draw. These are the screens it reached."}</p>
935
+ <div class="coverage-map flat" data-platform="${esc(platform)}">${graph.screens.map((screen) => screenCardHtml(screen, id)).join("")}</div>`;
936
+ return;
937
+ }
938
+ body.innerHTML = `<div class="coverage-map" data-platform="${esc(platform)}">${graph.columns.map((column, index) => {
939
+ const screens = column.map((screenId) => byId.get(screenId)).filter(Boolean);
940
+ if (!screens.length) return "";
941
+ const unreached = screens.every((screen) => !screen.reached);
942
+ return `<div class="coverage-column">
943
+ <p class="coverage-column-head">${unreached ? "No recorded way in" : index === 0 ? "Started here" : `${index} step${index === 1 ? "" : "s"} in`}</p>
944
+ ${screens.map((screen) => screenCardHtml(screen, id, { deadEnds: true })).join("")}
945
+ </div>`;
946
+ }).join("")}</div>
947
+ <p class="muted coverage-note">Only transitions the engine recorded are drawn. A screen with no recorded way in is in its own column, never implied to follow from the one beside it.</p>`;
948
+ }
949
+
950
+ // One screen: the still the run wrote, what the engine called it, and what led on from it. A
951
+ // screen with no still says so rather than borrowing another screen's picture. `deadEnds` is on
952
+ // only where it means something: in a path, a screen nothing led on from is a dead end worth
953
+ // naming; where the run recorded no transitions at all, every screen is one and saying so is noise.
954
+ function screenCardHtml(screen, captureId, { deadEnds = false } = {}) {
955
+ return `<article class="screen-card${screen.reached ? "" : " orphan"}">
956
+ <div class="screen-shot">${screen.shot
957
+ ? `<img loading="lazy" src="${esc(captureUrl(captureId, screen.shot))}" alt="${esc(screen.name)}">`
958
+ : '<span class="screen-shot-none">no picture</span>'}
959
+ ${screen.shotIsOfBaseScreen ? '<span class="screen-note" title="The stills are named for the screen, not the state, so this is that screen in a different state.">picture is of another state</span>' : ""}
960
+ </div>
961
+ <strong>${esc(screen.name)}</strong>
962
+ <small>${screen.controls} control${screen.controls === 1 ? "" : "s"}</small>
963
+ ${screen.outgoing.length
964
+ ? `<ul class="screen-exits">${screen.outgoing.map((exit) => `<li>${esc(exit.label)} <span>→ ${esc(exit.toName)}</span></li>`).join("")}</ul>`
965
+ : deadEnds ? '<p class="screen-exits-none">nothing led on from here</p>' : ""}
966
+ </article>`;
967
+ }
968
+
969
+ // The map is written beside the run, not sent with the run list, so it is fetched once per
970
+ // capture and kept. A capture from before the map was written answers 404; say so plainly.
971
+ async function loadCoverage(id) {
972
+ state.coverage ||= {};
973
+ if (state.coverage[id]) return;
974
+ state.coverage[id] = { loading: true };
975
+ try {
976
+ const [map, files] = await Promise.all([
977
+ fetch(captureUrl(id, "ui-map.json")).then((response) => response.ok ? response.json() : Promise.reject(new Error("no map"))),
978
+ api(`/api/captures/${encodeURIComponent(id)}/files`).catch(() => ({ shots: [] })),
979
+ ]);
980
+ const platform = map?.app?.platforms?.[0] || "";
981
+ state.coverage[id] = { graph: coverageGraph(map, files.shots || [], { platform }) };
982
+ } catch {
983
+ state.coverage[id] = { error: "This run wrote no map. Runs from before tapp recorded one, and runs that ended on the first screen, have nothing to draw." };
984
+ }
985
+ if (state.activeView === "coverage") renderCoverage();
986
+ }
987
+
773
988
  // ---- tapp chat: the engine's progress log, rendered as a transcript -------------------------
774
989
  function renderChat() {
775
990
  const node = $("#chat-transcript");
@@ -1179,6 +1394,11 @@ document.addEventListener("click", (event) => {
1179
1394
  }
1180
1395
  });
1181
1396
 
1397
+ document.addEventListener("change", (event) => {
1398
+ const picker = event.target.closest("#findings-run, #coverage-run");
1399
+ if (picker) { state.selectedRunId = picker.value; renderRuns(); }
1400
+ });
1401
+
1182
1402
  document.addEventListener("submit", (event) => {
1183
1403
  const audit = event.target.closest("form.audit-form");
1184
1404
  if (audit) { event.preventDefault(); auditWebsite(audit.elements.url.value).catch((error) => toast(error.message, true)); return; }