mixdog 0.9.147 → 0.9.148

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.
Files changed (255) hide show
  1. package/package.json +23 -3
  2. package/scripts/build-voice-runtime-unix.sh +101 -0
  3. package/scripts/embedding-quality-probe.mjs +96 -0
  4. package/scripts/generate-voice-runtime-manifest.mjs +300 -0
  5. package/scripts/generate-voice-runtime-manifest.test.mjs +135 -0
  6. package/scripts/native-binary-arch.mjs +30 -13
  7. package/scripts/native-binary-arch.test.mjs +40 -4
  8. package/scripts/plan-voice-runtime-release.mjs +73 -0
  9. package/scripts/prepare-native-assets.mjs +50 -9
  10. package/scripts/prune-embedding-runtime.mjs +3 -3
  11. package/scripts/sync-voice-runtime-manifest.mjs +46 -0
  12. package/scripts/verify-release-assets.mjs +106 -6
  13. package/scripts/verify-voice-runtime-release.mjs +89 -0
  14. package/scripts/voice-runtime-config.json +52 -0
  15. package/src/app.mjs +42 -5
  16. package/src/headless-exec.mjs +58 -32
  17. package/src/headless-exec.test.mjs +74 -13
  18. package/src/rules/lead/01-general.md +2 -0
  19. package/src/rules/shared/10-tool-workflow.md +7 -4
  20. package/src/rules/shared/30-exploration.md +2 -1
  21. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +28 -9
  22. package/src/runtime/agent/orchestrator/agent-trace-format.mjs +6 -1
  23. package/src/runtime/agent/orchestrator/config.mjs +53 -18
  24. package/src/runtime/agent/orchestrator/mcp/cancellation.test.mjs +139 -0
  25. package/src/runtime/agent/orchestrator/mcp/child-tree.mjs +34 -5
  26. package/src/runtime/agent/orchestrator/mcp/client.mjs +94 -10
  27. package/src/runtime/agent/orchestrator/providers/anthropic-betas.mjs +5 -0
  28. package/src/runtime/agent/orchestrator/providers/anthropic-fast-mode.mjs +98 -0
  29. package/src/runtime/agent/orchestrator/providers/anthropic-fast-mode.test.mjs +90 -0
  30. package/src/runtime/agent/orchestrator/providers/anthropic-leaked-toolcall.mjs +67 -16
  31. package/src/runtime/agent/orchestrator/providers/anthropic-messages.mjs +4 -82
  32. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-credentials.mjs +0 -5
  33. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +62 -121
  34. package/src/runtime/agent/orchestrator/providers/anthropic-server-fallback.mjs +48 -0
  35. package/src/runtime/agent/orchestrator/providers/anthropic-server-fallback.test.mjs +215 -0
  36. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +44 -48
  37. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +54 -31
  38. package/src/runtime/agent/orchestrator/providers/antigravity-oauth.mjs +56 -2
  39. package/src/runtime/agent/orchestrator/providers/cursor-auth.mjs +34 -2
  40. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +61 -1
  41. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +6 -1
  42. package/src/runtime/agent/orchestrator/providers/gemini.mjs +61 -15
  43. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +120 -1
  44. package/src/runtime/agent/orchestrator/providers/lib/env-utils.mjs +9 -0
  45. package/src/runtime/agent/orchestrator/providers/lib/stream-outcome.mjs +0 -3
  46. package/src/runtime/agent/orchestrator/providers/oauth-credential-probes.mjs +187 -84
  47. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +36 -36
  48. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +16 -6
  49. package/src/runtime/agent/orchestrator/providers/openai-compat-xai.mjs +50 -213
  50. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +135 -126
  51. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +17 -11
  52. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +20 -7
  53. package/src/runtime/agent/orchestrator/providers/openai-ws-delta.mjs +11 -0
  54. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +132 -42
  55. package/src/runtime/agent/orchestrator/providers/openai-ws-stream.mjs +2 -2
  56. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +28 -10
  57. package/src/runtime/agent/orchestrator/providers/registry.mjs +122 -95
  58. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +58 -3
  59. package/src/runtime/agent/orchestrator/providers/tool-stream-state.mjs +4 -22
  60. package/src/runtime/agent/orchestrator/session/agent-loop.mjs +7 -14
  61. package/src/runtime/agent/orchestrator/session/compact-policy.test.mjs +128 -0
  62. package/src/runtime/agent/orchestrator/session/context-compaction-policy.mjs +5 -0
  63. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +27 -48
  64. package/src/runtime/agent/orchestrator/session/loop/steering.mjs +19 -14
  65. package/src/runtime/agent/orchestrator/session/loop/stored-tool-args.mjs +9 -43
  66. package/src/runtime/agent/orchestrator/session/loop/tool-exec.mjs +5 -1
  67. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +15 -2
  68. package/src/runtime/agent/orchestrator/session/manager/pending-messages-persistence.test.mjs +325 -0
  69. package/src/runtime/agent/orchestrator/session/manager/pending-messages.mjs +599 -195
  70. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +22 -0
  71. package/src/runtime/agent/orchestrator/session/manager/session-crud.mjs +9 -2
  72. package/src/runtime/agent/orchestrator/session/manager.mjs +3 -0
  73. package/src/runtime/agent/orchestrator/session/pre-send-compact.mjs +26 -16
  74. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +23 -11
  75. package/src/runtime/agent/orchestrator/session/store-summary-reader.mjs +118 -3
  76. package/src/runtime/agent/orchestrator/session/store-summary-reader.test.mjs +332 -0
  77. package/src/runtime/agent/orchestrator/session/store.mjs +38 -1
  78. package/src/runtime/agent/orchestrator/tools/builtin/advisory-lock.mjs +27 -6
  79. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +12 -20
  80. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +291 -128
  81. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +45 -8
  82. package/src/runtime/agent/orchestrator/tools/builtin/edit-encoding-eol.test.mjs +224 -0
  83. package/src/runtime/agent/orchestrator/tools/builtin/edit-sequential-occupation.test.mjs +53 -3
  84. package/src/runtime/agent/orchestrator/tools/builtin/external-tool-adapters.mjs +255 -25
  85. package/src/runtime/agent/orchestrator/tools/builtin/find-search-budget.test.mjs +87 -0
  86. package/src/runtime/agent/orchestrator/tools/builtin/git-command-policy.mjs +1 -1
  87. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.mjs +132 -9
  88. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.test.mjs +10 -0
  89. package/src/runtime/agent/orchestrator/tools/builtin/lib/grep-pattern-fanout.mjs +29 -3
  90. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-job-records.mjs +1 -1
  91. package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +178 -29
  92. package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +4 -1
  93. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +32 -5
  94. package/src/runtime/agent/orchestrator/tools/builtin/native-search-health.test.mjs +5 -2
  95. package/src/runtime/agent/orchestrator/tools/builtin/native-search-runner.mjs +10 -1
  96. package/src/runtime/agent/orchestrator/tools/builtin/read-batch.mjs +38 -10
  97. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +12 -0
  98. package/src/runtime/agent/orchestrator/tools/builtin/read-snapshot-runtime.mjs +31 -1
  99. package/src/runtime/agent/orchestrator/tools/builtin/read-tool.mjs +11 -1
  100. package/src/runtime/agent/orchestrator/tools/builtin/read-windows.mjs +22 -4
  101. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +6 -8
  102. package/src/runtime/agent/orchestrator/tools/builtin/shell-analysis.mjs +25 -24
  103. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +152 -133
  104. package/src/runtime/agent/orchestrator/tools/builtin/task-tool.mjs +114 -42
  105. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +129 -15
  106. package/src/runtime/agent/orchestrator/tools/code-graph/loose-file-target.test.mjs +72 -0
  107. package/src/runtime/agent/orchestrator/tools/code-graph/project-root.mjs +7 -8
  108. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +4 -4
  109. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +201 -19
  110. package/src/runtime/agent/orchestrator/tools/code-graph/span.mjs +26 -3
  111. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +10 -1
  112. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-search-scope.test.mjs +55 -0
  113. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +115 -25
  114. package/src/runtime/agent/orchestrator/tools/code-graph/text-span-mask.test.mjs +268 -0
  115. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +3 -3
  116. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +296 -46
  117. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.test.mjs +104 -0
  118. package/src/runtime/agent/orchestrator/tools/lib/shell-descendants.mjs +136 -0
  119. package/src/runtime/agent/orchestrator/tools/patch/dispatch.mjs +127 -38
  120. package/src/runtime/agent/orchestrator/tools/patch/engine-contract-gate.test.mjs +661 -0
  121. package/src/runtime/agent/orchestrator/tools/patch/matcher.mjs +350 -9
  122. package/src/runtime/agent/orchestrator/tools/patch/native-server.mjs +418 -44
  123. package/src/runtime/agent/orchestrator/tools/patch/orchestrator.mjs +27 -3
  124. package/src/runtime/agent/orchestrator/tools/patch/patch-codec-eol.test.mjs +552 -0
  125. package/src/runtime/agent/orchestrator/tools/patch/v4a-convert.mjs +65 -15
  126. package/src/runtime/agent/orchestrator/tools/patch-manifest.json +11 -11
  127. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +284 -109
  128. package/src/runtime/agent/orchestrator/tools/shell-exec-output.mjs +51 -21
  129. package/src/runtime/agent/orchestrator/tools/shell-exec-policy.mjs +44 -27
  130. package/src/runtime/agent/orchestrator/tools/shell-policy.mjs +6 -1
  131. package/src/runtime/agent/orchestrator/tools/spawn-manifest.json +11 -11
  132. package/src/runtime/attachments/store.mjs +11 -3
  133. package/src/runtime/channels/data/voice-runtime-manifest.json +46 -70
  134. package/src/runtime/channels/lib/event-queue.mjs +51 -41
  135. package/src/runtime/channels/lib/scheduler.mjs +23 -28
  136. package/src/runtime/channels/lib/voice-runtime-fetcher.mjs +6 -17
  137. package/src/runtime/channels/lib/voice-runtime-fetcher.test.mjs +17 -0
  138. package/src/runtime/channels/lib/webhook.mjs +39 -20
  139. package/src/runtime/channels/lib/whisper-server.mjs +46 -1
  140. package/src/runtime/channels/lib/worker-main.mjs +3 -1
  141. package/src/runtime/media/adapters/gemini-video.mjs +20 -4
  142. package/src/runtime/media/jobs.mjs +13 -0
  143. package/src/runtime/media/renditions.mjs +7 -1
  144. package/src/runtime/media/store.mjs +42 -22
  145. package/src/runtime/memory/index.mjs +4 -9
  146. package/src/runtime/memory/lib/agent-ipc.mjs +1 -6
  147. package/src/runtime/memory/lib/archive-security.test.mjs +21 -1
  148. package/src/runtime/memory/lib/core-memory-store.mjs +28 -50
  149. package/src/runtime/memory/lib/embedding-model-config.mjs +37 -1
  150. package/src/runtime/memory/lib/embedding-model-config.test.mjs +33 -0
  151. package/src/runtime/memory/lib/embedding-provider.mjs +34 -12
  152. package/src/runtime/memory/lib/embedding-worker.mjs +37 -5
  153. package/src/runtime/memory/lib/ko-morph.mjs +46 -15
  154. package/src/runtime/memory/lib/memory-action-handlers.mjs +18 -1
  155. package/src/runtime/memory/lib/memory-cycle1.mjs +1 -18
  156. package/src/runtime/memory/lib/memory-cycle2-gate.mjs +1 -18
  157. package/src/runtime/memory/lib/memory-cycle2-mutations.mjs +98 -45
  158. package/src/runtime/memory/lib/memory-cycle2-shared.mjs +71 -0
  159. package/src/runtime/memory/lib/memory-cycle2-shared.test.mjs +78 -0
  160. package/src/runtime/memory/lib/memory-cycle2.mjs +37 -3
  161. package/src/runtime/memory/lib/memory-cycle3.mjs +1 -1
  162. package/src/runtime/memory/lib/memory-embedding-migration.test.mjs +50 -0
  163. package/src/runtime/memory/lib/memory-recall-store.mjs +9 -24
  164. package/src/runtime/memory/lib/memory.mjs +50 -12
  165. package/src/runtime/memory/lib/pg/process.mjs +1 -10
  166. package/src/runtime/memory/lib/pg/supervisor.mjs +1 -9
  167. package/src/runtime/memory/lib/query-handlers.mjs +2 -4
  168. package/src/runtime/memory/lib/session-ingest-runtime.mjs +2 -2
  169. package/src/runtime/shared/background-tasks.mjs +15 -0
  170. package/src/runtime/shared/background-tasks.test.mjs +78 -0
  171. package/src/runtime/shared/child-guardian.mjs +2 -10
  172. package/src/runtime/shared/pid-liveness.mjs +27 -0
  173. package/src/runtime/shared/runtime-root.mjs +1 -11
  174. package/src/runtime/shared/service-discovery.mjs +1 -17
  175. package/src/runtime/shared/singleton-owner.mjs +1 -11
  176. package/src/runtime/shared/staged-update.mjs +2 -12
  177. package/src/runtime/shared/tool-status.mjs +5 -1
  178. package/src/runtime/shared/tool-surface.mjs +15 -7
  179. package/src/runtime/shared/turn-snapshot-store.mjs +168 -0
  180. package/src/runtime/shared/turn-snapshot.mjs +137 -13
  181. package/src/runtime/shared/turn-worktree-snapshot.mjs +110 -18
  182. package/src/runtime/shared/webhook-session-run.mjs +16 -2
  183. package/src/runtime/web-search/lib/http-fetch.mjs +34 -4
  184. package/src/runtime/web-search/lib/state.mjs +15 -15
  185. package/src/runtime/web-search/lib/web-tools.mjs +46 -5
  186. package/src/session-runtime/context-status.mjs +4 -12
  187. package/src/session-runtime/runtime-core.mjs +20 -1
  188. package/src/standalone/agent-dispatch-broker.mjs +33 -2
  189. package/src/standalone/agent-tool/job-task-reconcile.mjs +78 -0
  190. package/src/standalone/agent-tool/notify.mjs +3 -1
  191. package/src/standalone/agent-tool/spawn-flow.mjs +48 -66
  192. package/src/standalone/agent-tool/tag-registry.mjs +116 -33
  193. package/src/standalone/agent-tool/tool-def.mjs +2 -2
  194. package/src/standalone/agent-tool/worker-index.mjs +8 -11
  195. package/src/standalone/agent-tool/worker-rows.mjs +4 -1
  196. package/src/standalone/agent-tool.mjs +20 -55
  197. package/src/standalone/agent-watchdog-registry.mjs +28 -4
  198. package/src/standalone/channel-client.mjs +47 -15
  199. package/src/standalone/channel-transport.mjs +44 -25
  200. package/src/standalone/daemon.mjs +31 -2
  201. package/src/standalone/hook-bus/config.mjs +25 -9
  202. package/src/standalone/hook-bus/handlers.mjs +16 -52
  203. package/src/standalone/hook-bus.mjs +29 -23
  204. package/src/standalone/memory-runtime-proxy.mjs +1 -16
  205. package/src/standalone/session-client.mjs +86 -23
  206. package/src/standalone/session-protocol.mjs +0 -2
  207. package/src/standalone/session-runtime-host-health.test.mjs +5 -4
  208. package/src/standalone/session-runtime-host.mjs +101 -6
  209. package/src/standalone/session-runtime-record.mjs +1 -5
  210. package/src/standalone/session-runtime-worker.mjs +52 -57
  211. package/src/standalone/session-service.mjs +4 -1
  212. package/src/standalone/session-transport.mjs +56 -25
  213. package/src/tui/App.jsx +40 -49
  214. package/src/tui/app/app-view.jsx +14 -21
  215. package/src/tui/app/core-memory-picker.mjs +29 -16
  216. package/src/tui/app/create-app-pickers.mjs +15 -36
  217. package/src/tui/app/extension-pickers.mjs +60 -49
  218. package/src/tui/app/maintenance-pickers.mjs +100 -57
  219. package/src/tui/app/message-selector.mjs +6 -5
  220. package/src/tui/app/model-picker.mjs +30 -13
  221. package/src/tui/app/onboarding-steps.mjs +21 -12
  222. package/src/tui/app/panel-epoch.mjs +56 -0
  223. package/src/tui/app/panel-epoch.test.mjs +1009 -0
  224. package/src/tui/app/panel-surface.mjs +98 -0
  225. package/src/tui/app/project-picker.mjs +30 -29
  226. package/src/tui/app/prompt-submit.mjs +192 -97
  227. package/src/tui/app/prompt-submit.test.mjs +206 -0
  228. package/src/tui/app/provider-setup-picker.mjs +74 -43
  229. package/src/tui/app/resume-picker.mjs +11 -8
  230. package/src/tui/app/route-pickers.mjs +45 -28
  231. package/src/tui/app/settings-picker.mjs +69 -18
  232. package/src/tui/app/shell-layout.mjs +1 -3
  233. package/src/tui/app/slash-commands.mjs +0 -2
  234. package/src/tui/app/slash-dispatch.mjs +4 -2
  235. package/src/tui/app/text-entry-policy.mjs +25 -0
  236. package/src/tui/app/theme-effort-pickers.mjs +11 -16
  237. package/src/tui/app/usage-context-panels.mjs +21 -25
  238. package/src/tui/app/use-global-key-input.mjs +3 -2
  239. package/src/tui/app/use-prompt-draft-flow.mjs +6 -18
  240. package/src/tui/app/use-prompt-handlers.mjs +3 -2
  241. package/src/tui/app/use-welcome-prompt-hint.mjs +17 -3
  242. package/src/tui/components/Picker.jsx +1 -1
  243. package/src/tui/components/TextEntryPanel.jsx +7 -2
  244. package/src/tui/dist/index.mjs +652 -561
  245. package/src/tui/lib/voice-setup.mjs +1 -2
  246. package/src/tui/session/agent-job-feed.mjs +73 -11
  247. package/src/tui/session/session-api-ext.mjs +5 -6
  248. package/src/tui/session/session-api.mjs +1 -0
  249. package/src/tui/session/tool-approval.mjs +15 -5
  250. package/src/tui/session/tui-steering-persist.mjs +33 -19
  251. package/src/tui/session/tui-steering-persist.test.mjs +104 -0
  252. package/src/tui/session-local.mjs +0 -22
  253. package/scripts/.tmp-coverage-report.mjs +0 -96
  254. package/src/runtime/agent/orchestrator/tools/builtin/shell-monitor.mjs +0 -57
  255. package/src/runtime/agent/orchestrator/tools/builtin/shell-monitor.test.mjs +0 -57
@@ -0,0 +1,1009 @@
1
+ // Panel-ownership (epoch) regression suite.
2
+ //
3
+ // Two resurrection paths are pinned here, both reproduced in review:
4
+ // 1. a settings chain whose ASYNC PREFLIGHT (listOutputStyles/listWorkflows)
5
+ // settles after Esc — the epoch must belong to the KEYPRESS, not to the
6
+ // ack, or the post-write refresh re-opens Settings over whatever surface
7
+ // the user is looking at now;
8
+ // 2. an object → object panel replacement — opening a different panel over
9
+ // Settings must supersede, or a deferred Settings refresh clobbers it.
10
+ // App.jsx cannot be imported here (no JSX parser in this workspace), so its
11
+ // handover rule is exercised through the shared helper it delegates to, plus a
12
+ // source-text pin on the one call site.
13
+ //
14
+ // The class rule is no longer audited by pattern matching: panel-surface.mjs
15
+ // owns the sinks, so the two structural tests at the bottom are the whole
16
+ // enforcement — the sinks are unreachable outside the owning layer, and a claim
17
+ // rejects every late-paint shape that used to defeat the analyzer.
18
+ import assert from 'node:assert/strict';
19
+ import test from 'node:test';
20
+ import { readFile, readdir } from 'node:fs/promises';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { basename, join, relative } from 'node:path';
23
+
24
+ import {
25
+ panelIdentity,
26
+ shouldSupersedePanelEpoch,
27
+ supersedePanelEpoch,
28
+ } from './panel-epoch.mjs';
29
+ import { createPanelSurface } from './panel-surface.mjs';
30
+ import { createSettingsPicker } from './settings-picker.mjs';
31
+ import { createMaintenancePickers } from './maintenance-pickers.mjs';
32
+ import { createExtensionPickers } from './extension-pickers.mjs';
33
+ import { createModelPicker } from './model-picker.mjs';
34
+ import { createOnboardingSteps } from './onboarding-steps.mjs';
35
+ import { createProviderSetupPicker } from './provider-setup-picker.mjs';
36
+ import { createRoutePickers } from './route-pickers.mjs';
37
+
38
+ function deferred() {
39
+ let resolve;
40
+ let reject;
41
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
42
+ return { promise, resolve, reject };
43
+ }
44
+
45
+ // Drain BOTH phases repeatedly: these chains hop through timers (setTimeout 0)
46
+ // as well as microtasks, and a too-short drain lets a probe pass vacuously
47
+ // because the branch under test had not run yet.
48
+ const flush = async (rounds = 12) => {
49
+ for (let i = 0; i < rounds; i += 1) {
50
+ await new Promise((resolve) => setTimeout(resolve, 0));
51
+ await new Promise((resolve) => setImmediate(resolve));
52
+ }
53
+ };
54
+
55
+ // Mirrors the ownership rule of App.jsx (src/tui/App.jsx:349-368): the live ref
56
+ // is updated synchronously and a handover bumps the epoch. The host plays the
57
+ // owning layer — it holds the raw sink and hands the panel modules a surface.
58
+ function createPanelHost() {
59
+ let live = null;
60
+ const painted = [];
61
+ const setPicker = (next) => {
62
+ const previous = live;
63
+ live = typeof next === 'function' ? next(previous) : next;
64
+ if (shouldSupersedePanelEpoch(previous, live)) supersedePanelEpoch();
65
+ painted.push(live);
66
+ };
67
+ // The context panel is a SEPARATE sink with no supersede step of its own, so
68
+ // it has to be observed to prove a dismissed context stays dismissed.
69
+ const contextPainted = [];
70
+ const surface = createPanelSurface({
71
+ setPicker,
72
+ setContextPanel: (next) => contextPainted.push(next),
73
+ setUsagePanel: () => {},
74
+ });
75
+ return { setPicker, surface, painted, contextPainted, current: () => live };
76
+ }
77
+
78
+ function createSettingsHarness({ store: storeOverrides = {}, host = null } = {}) {
79
+ const painted = [];
80
+ const notices = [];
81
+ const store = {
82
+ pushNotice: (message, tone) => notices.push([message, tone]),
83
+ getSettingsSnapshot: async () => ({}),
84
+ ...storeOverrides,
85
+ };
86
+ const noop = () => {};
87
+ const { openSettingsPicker } = createSettingsPicker({
88
+ store,
89
+ state: { model: 'gpt-5', provider: 'openai', workflow: { id: 'default' } },
90
+ surface: createPanelSurface({
91
+ setPicker: (next) => {
92
+ painted.push(next);
93
+ if (host) host.setPicker(next);
94
+ },
95
+ setUsagePanel: noop,
96
+ }),
97
+ setProviderPrompt: noop,
98
+ setSettingsPrompt: noop,
99
+ settingsHeavyCacheRef: { current: null },
100
+ settingsRequestRef: { current: 0 },
101
+ formatDuration: (ms) => `${ms}ms`,
102
+ displayModelName: () => 'gpt-5',
103
+ routeModelLabel: () => '(unset)',
104
+ workflowDisplayName: () => 'Default',
105
+ workflowSwitchNotice: () => 'workflow switched',
106
+ themeNotice: () => 'theme set',
107
+ openModelPicker: noop,
108
+ openWebSearchPicker: noop,
109
+ openAgentsPicker: noop,
110
+ openWorkflowPicker: noop,
111
+ openOutputStylePicker: noop,
112
+ openProviderSetupPicker: noop,
113
+ openThemePicker: noop,
114
+ openAutoClearPicker: noop,
115
+ openProfilePicker: noop,
116
+ openMcpPicker: noop,
117
+ openPluginsPicker: noop,
118
+ openHooksPicker: noop,
119
+ openSkillsPicker: noop,
120
+ openMemoryCorePicker: noop,
121
+ openUpdatePicker: noop,
122
+ });
123
+ return { openSettingsPicker, painted, notices };
124
+ }
125
+
126
+ const lastPanel = (painted) => painted[painted.length - 1];
127
+
128
+ test('panel handover: close and replacement supersede, rebuild and first open do not', () => {
129
+ const settings = { title: 'Settings' };
130
+ assert.equal(panelIdentity(settings), 'Settings');
131
+ assert.equal(panelIdentity({ _kind: 'mcp-servers', title: 'MCP servers · 2 connected' }), 'mcp-servers');
132
+ assert.equal(panelIdentity(null), null);
133
+
134
+ // Close: the reviewed case.
135
+ assert.equal(shouldSupersedePanelEpoch(settings, null), true);
136
+ // Replacement by a DIFFERENT panel: the gap this suite closes.
137
+ assert.equal(shouldSupersedePanelEpoch(settings, { title: 'Core memories' }), true);
138
+ assert.equal(shouldSupersedePanelEpoch({ _kind: 'hooks', title: 'Hooks' }, { _kind: 'skills', title: 'Hooks' }), true);
139
+ // Rebuild of the same surface (light refresh / toggle re-render): keeps
140
+ // ownership so its own deferred refresh still lands.
141
+ assert.equal(shouldSupersedePanelEpoch(settings, { title: 'Settings', items: [] }), false);
142
+ assert.equal(shouldSupersedePanelEpoch(settings, settings), false);
143
+ assert.equal(shouldSupersedePanelEpoch({ _kind: 'mcp-servers', title: 'MCP · 1' }, { _kind: 'mcp-servers', title: 'MCP · 2' }), false);
144
+ // Nothing owned the surface: null → null and the first open are not handovers
145
+ // (an in-flight text-entry prompt write must stay valid).
146
+ assert.equal(shouldSupersedePanelEpoch(null, null), false);
147
+ assert.equal(shouldSupersedePanelEpoch(null, settings), false);
148
+ });
149
+
150
+ test('an output-style cycle whose preflight resolves after Esc does not re-open Settings', async () => {
151
+ supersedePanelEpoch();
152
+ const listGate = deferred();
153
+ const styleWrites = [];
154
+ const harness = createSettingsHarness({
155
+ store: {
156
+ listOutputStyles: () => listGate.promise,
157
+ setOutputStyle: (id) => {
158
+ styleWrites.push(id);
159
+ return Promise.resolve({ current: { id, label: id } });
160
+ },
161
+ },
162
+ });
163
+ await harness.openSettingsPicker();
164
+ const panel = lastPanel(harness.painted);
165
+ assert.ok(panel, `settings panel never painted: ${JSON.stringify(harness.notices)}`);
166
+ assert.equal(panel.title, 'Settings');
167
+ const paintedBefore = harness.painted.length;
168
+
169
+ // Keypress: the epoch must be captured HERE, before the listOutputStyles
170
+ // round-trip below.
171
+ panel.onRight({ _action: 'output-style' });
172
+ // Esc — the user is now looking at something else.
173
+ supersedePanelEpoch();
174
+ listGate.resolve({ styles: [{ id: 'default' }, { id: 'concise' }], current: { id: 'default' } });
175
+ await flush();
176
+
177
+ // The write still runs (the user asked for it); only the paint is dropped.
178
+ assert.deepEqual(styleWrites, ['concise']);
179
+ assert.equal(harness.painted.length, paintedBefore);
180
+ });
181
+
182
+ test('a workflow cycle whose preflight resolves after Esc does not re-open Settings', async () => {
183
+ supersedePanelEpoch();
184
+ const listGate = deferred();
185
+ const workflowWrites = [];
186
+ const harness = createSettingsHarness({
187
+ store: {
188
+ listWorkflows: () => listGate.promise,
189
+ setWorkflow: (id) => {
190
+ workflowWrites.push(id);
191
+ return Promise.resolve({ id });
192
+ },
193
+ },
194
+ });
195
+ await harness.openSettingsPicker();
196
+ const panel = lastPanel(harness.painted);
197
+ const paintedBefore = harness.painted.length;
198
+
199
+ panel.onRight({ _action: 'workflow' });
200
+ supersedePanelEpoch();
201
+ listGate.resolve([{ id: 'default', active: true }, { id: 'ship' }]);
202
+ await flush();
203
+
204
+ assert.deepEqual(workflowWrites, ['ship']);
205
+ assert.equal(harness.painted.length, paintedBefore);
206
+ });
207
+
208
+ test('an undisturbed output-style cycle still refreshes Settings', async () => {
209
+ supersedePanelEpoch();
210
+ const listGate = deferred();
211
+ const harness = createSettingsHarness({
212
+ store: {
213
+ listOutputStyles: () => listGate.promise,
214
+ setOutputStyle: (id) => Promise.resolve({ current: { id, label: id } }),
215
+ },
216
+ });
217
+ await harness.openSettingsPicker();
218
+ const paintedBefore = harness.painted.length;
219
+
220
+ lastPanel(harness.painted).onRight({ _action: 'output-style' });
221
+ listGate.resolve({ styles: [{ id: 'default' }, { id: 'concise' }], current: { id: 'default' } });
222
+ await flush();
223
+
224
+ assert.ok(harness.painted.length > paintedBefore);
225
+ assert.equal(lastPanel(harness.painted).title, 'Settings');
226
+ });
227
+
228
+ test('a deferred Settings refresh cannot clobber the panel that replaced Settings', async () => {
229
+ supersedePanelEpoch();
230
+ const writeGate = deferred();
231
+ const host = createPanelHost();
232
+ const harness = createSettingsHarness({
233
+ host,
234
+ store: { setRecapEnabled: () => writeGate.promise },
235
+ });
236
+ await harness.openSettingsPicker();
237
+ assert.equal(host.current().title, 'Settings');
238
+
239
+ // Toggle a row: the refresh epoch is captured on this keypress.
240
+ lastPanel(harness.painted).onRight({ _action: 'memory-cycles' });
241
+ // The user opens a nested panel over Settings (object → object).
242
+ host.setPicker({ title: 'Core memories' });
243
+ const paintedBefore = host.painted.length;
244
+
245
+ writeGate.resolve(true);
246
+ await flush();
247
+
248
+ assert.equal(host.current().title, 'Core memories');
249
+ assert.equal(host.painted.length, paintedBefore);
250
+ });
251
+
252
+ test('a Settings rebuild keeps ownership, so its own deferred refresh still lands', async () => {
253
+ supersedePanelEpoch();
254
+ const writeGate = deferred();
255
+ const host = createPanelHost();
256
+ const harness = createSettingsHarness({
257
+ host,
258
+ store: { setRecapEnabled: () => writeGate.promise },
259
+ });
260
+ await harness.openSettingsPicker();
261
+
262
+ lastPanel(harness.painted).onRight({ _action: 'memory-cycles' });
263
+ // Same surface, rebuilt (a light refresh from another chain): not a handover.
264
+ host.setPicker({ title: 'Settings', items: [] });
265
+ const paintedBefore = host.painted.length;
266
+
267
+ writeGate.resolve(true);
268
+ await flush();
269
+
270
+ assert.ok(host.painted.length > paintedBefore);
271
+ assert.equal(host.current().title, 'Settings');
272
+ });
273
+
274
+ function createUpdateHarness(host, checkGate) {
275
+ const notices = [];
276
+ const store = {
277
+ pushNotice: (message, tone) => notices.push([message, tone]),
278
+ getUpdateSettings: async () => ({ currentVersion: '0.9.147', autoUpdate: false }),
279
+ getUpdateStatus: async () => ({ phase: 'idle' }),
280
+ checkForUpdate: () => checkGate.promise,
281
+ };
282
+ const noop = () => {};
283
+ const { openUpdatePicker } = createMaintenancePickers({
284
+ store,
285
+ theme: {},
286
+ formatDuration: (ms) => `${ms}ms`,
287
+ surface: host.surface,
288
+ setProviderPrompt: noop,
289
+ setSettingsPrompt: noop,
290
+ closeUsagePanel: noop,
291
+ });
292
+ return { openUpdatePicker, notices };
293
+ }
294
+
295
+ test('the Update panel repaints its first check across the Settings → Update handover', async () => {
296
+ supersedePanelEpoch();
297
+ const host = createPanelHost();
298
+ host.setPicker({ title: 'Settings' });
299
+ const checkGate = deferred();
300
+ const { openUpdatePicker } = createUpdateHarness(host, checkGate);
301
+
302
+ openUpdatePicker({});
303
+ await flush();
304
+ assert.equal(host.current().title, 'Update');
305
+ const paintedBefore = host.painted.length;
306
+
307
+ checkGate.resolve({ latestVersion: '0.9.148' });
308
+ await flush();
309
+
310
+ // The open transition supersedes the previous owner's deferred paints, but
311
+ // the panel's own initial check (captured after it took the surface) lands.
312
+ assert.ok(host.painted.length > paintedBefore);
313
+ assert.equal(host.current().title, 'Update');
314
+ });
315
+
316
+ test('Esc on the Update panel still kills its in-flight first check', async () => {
317
+ supersedePanelEpoch();
318
+ const host = createPanelHost();
319
+ const checkGate = deferred();
320
+ const { openUpdatePicker } = createUpdateHarness(host, checkGate);
321
+
322
+ openUpdatePicker({});
323
+ await flush();
324
+ host.setPicker(null);
325
+ const paintedBefore = host.painted.length;
326
+
327
+ checkGate.resolve({ latestVersion: '0.9.148' });
328
+ await flush();
329
+
330
+ assert.equal(host.current(), null);
331
+ assert.equal(host.painted.length, paintedBefore);
332
+ });
333
+
334
+ test('App.jsx routes every picker handover through shouldSupersedePanelEpoch', async () => {
335
+ // No JSX parser exists in this workspace, so the one line that cannot be
336
+ // executed from a test is pinned as source text.
337
+ const source = await readFile(new URL('../App.jsx', import.meta.url), 'utf8');
338
+ assert.match(source, /import \{ shouldSupersedePanelEpoch, supersedePanelEpoch \} from '\.\/app\/panel-epoch\.mjs';/);
339
+ assert.match(
340
+ source,
341
+ /if \(shouldSupersedePanelEpoch\(previousPicker, livePickerRef\.current\)\) supersedePanelEpoch\(\);/,
342
+ );
343
+ });
344
+
345
+ // ── Pending-open resurrection: the epoch must be captured at the OPEN action ──
346
+ // A panel whose first paint waits on a daemon read has nothing to protect it:
347
+ // null → panel is deliberately not a handover, so a close during the pending
348
+ // open would let it paint over the surface the user went back to.
349
+
350
+ test('Esc during the Update panel pending first read keeps it off the surface', async () => {
351
+ supersedePanelEpoch();
352
+ const host = createPanelHost();
353
+ host.setPicker({ title: 'Settings' });
354
+ const readGate = deferred();
355
+ const checkGate = deferred();
356
+ const noop = () => {};
357
+ const { openUpdatePicker } = createMaintenancePickers({
358
+ store: {
359
+ pushNotice: () => {},
360
+ getUpdateSettings: () => readGate.promise,
361
+ getUpdateStatus: async () => ({ phase: 'idle' }),
362
+ checkForUpdate: () => checkGate.promise,
363
+ },
364
+ theme: {},
365
+ formatDuration: (ms) => `${ms}ms`,
366
+ surface: host.surface,
367
+ setProviderPrompt: noop,
368
+ setSettingsPrompt: noop,
369
+ closeUsagePanel: noop,
370
+ });
371
+
372
+ openUpdatePicker({});
373
+ await flush();
374
+ // Still pending: Settings is what the user sees.
375
+ assert.equal(host.current().title, 'Settings');
376
+
377
+ // Esc closes Settings while the open is in flight.
378
+ host.setPicker(null);
379
+ const paintedBefore = host.painted.length;
380
+
381
+ readGate.resolve({ currentVersion: '0.9.147', autoUpdate: false });
382
+ await flush();
383
+ assert.equal(host.current(), null);
384
+ assert.equal(host.painted.length, paintedBefore);
385
+
386
+ // The abandoned open must not come back through its own initial check either.
387
+ checkGate.resolve({ latestVersion: '0.9.148' });
388
+ await flush();
389
+ assert.equal(host.current(), null);
390
+ assert.equal(host.painted.length, paintedBefore);
391
+ });
392
+
393
+ test('Esc during a pending Settings open leaves the surface untouched', async () => {
394
+ supersedePanelEpoch();
395
+ const host = createPanelHost();
396
+ host.setPicker({ title: 'Core memories' });
397
+ const snapshotGate = deferred();
398
+ const harness = createSettingsHarness({
399
+ host,
400
+ store: { getSettingsSnapshot: () => snapshotGate.promise },
401
+ });
402
+
403
+ const opening = harness.openSettingsPicker();
404
+ host.setPicker(null);
405
+ const paintedBefore = host.painted.length;
406
+
407
+ snapshotGate.resolve({});
408
+ await opening;
409
+ await flush();
410
+
411
+ assert.equal(host.current(), null);
412
+ assert.equal(host.painted.length, paintedBefore);
413
+ });
414
+
415
+ test('Esc during a pending Hooks open keeps the panel off the surface', async () => {
416
+ supersedePanelEpoch();
417
+ const host = createPanelHost();
418
+ host.setPicker({ title: 'Settings' });
419
+ const statusGate = deferred();
420
+ const noop = () => {};
421
+ const { openHooksPicker } = createExtensionPickers({
422
+ store: { pushNotice: () => {}, hooksStatus: () => statusGate.promise },
423
+ theme: {},
424
+ clean: (value) => value,
425
+ copyToClipboard: noop,
426
+ surface: host.surface,
427
+ getPicker: host.current,
428
+ setProviderPrompt: noop,
429
+ setSettingsPrompt: noop,
430
+ getDisabledSkills: () => new Set(),
431
+ setDisabledSkills: noop,
432
+ });
433
+
434
+ void openHooksPicker();
435
+ host.setPicker(null);
436
+ const paintedBefore = host.painted.length;
437
+
438
+ statusGate.resolve({ rules: [], events: [], recent: [] });
439
+ await flush();
440
+
441
+ assert.equal(host.current(), null);
442
+ assert.equal(host.painted.length, paintedBefore);
443
+ });
444
+
445
+ test('an uninterrupted open still paints and keeps repainting', async () => {
446
+ supersedePanelEpoch();
447
+ const host = createPanelHost();
448
+ const statusGate = deferred();
449
+ const noop = () => {};
450
+ const { openHooksPicker } = createExtensionPickers({
451
+ store: { pushNotice: () => {}, hooksStatus: () => statusGate.promise },
452
+ theme: {},
453
+ clean: (value) => value,
454
+ copyToClipboard: noop,
455
+ surface: host.surface,
456
+ getPicker: host.current,
457
+ setProviderPrompt: noop,
458
+ setSettingsPrompt: noop,
459
+ getDisabledSkills: () => new Set(),
460
+ setDisabledSkills: noop,
461
+ });
462
+
463
+ void openHooksPicker();
464
+ statusGate.resolve({ rules: [{ index: 0, tool: 'shell', action: 'ask', enabled: true }], events: [], recent: [] });
465
+ await flush();
466
+ assert.equal(host.current()._kind, 'hooks');
467
+
468
+ // A same-surface reopen (the toggle path) still paints: the guard only
469
+ // blocks opens whose surface was handed over while they were pending.
470
+ const paintedBefore = host.painted.length;
471
+ void openHooksPicker();
472
+ await flush();
473
+ assert.ok(host.painted.length > paintedBefore);
474
+ assert.equal(host.current()._kind, 'hooks');
475
+ });
476
+
477
+ // ── Late REPAINTS must prove ownership too, not just the first paint ─────────
478
+ // A panel that keeps a render closure alive (Update, Auto-clear, Model) repaints
479
+ // from later daemon reads; those reads settle after Esc just as easily as the
480
+ // opening one.
481
+
482
+ test('probe: an Update re-check settling after Esc paints nothing', async () => {
483
+ supersedePanelEpoch();
484
+ const host = createPanelHost();
485
+ let readGate = null;
486
+ let reads = 0;
487
+ const checkGate = deferred();
488
+ checkGate.resolve({});
489
+ const noop = () => {};
490
+ const { openUpdatePicker } = createMaintenancePickers({
491
+ store: {
492
+ pushNotice: () => {},
493
+ getUpdateSettings: () => { reads += 1; return readGate ? readGate.promise : Promise.resolve({ currentVersion: '0.9.147' }); },
494
+ getUpdateStatus: async () => ({ phase: 'idle' }),
495
+ checkForUpdate: () => checkGate.promise,
496
+ },
497
+ theme: {},
498
+ formatDuration: (ms) => `${ms}ms`,
499
+ surface: host.surface,
500
+ setProviderPrompt: noop,
501
+ setSettingsPrompt: noop,
502
+ closeUsagePanel: noop,
503
+ });
504
+
505
+ openUpdatePicker({});
506
+ await flush();
507
+ assert.equal(host.current().title, 'Update');
508
+
509
+ // Enter on "Latest version" → recheck(): a fresh daemon read feeds a repaint.
510
+ readGate = deferred();
511
+ host.current().onSelect('latest', { _action: 'latest' });
512
+ await flush();
513
+ host.setPicker(null);
514
+ const paintedBefore = host.painted.length;
515
+
516
+ readGate.resolve({ currentVersion: '0.9.147' });
517
+ await flush();
518
+
519
+ assert.ok(reads >= 2, 're-check must have issued its own read');
520
+ assert.equal(host.current(), null, 'afterEsc');
521
+ assert.equal(host.painted.length - paintedBefore, 0, 'latePaints');
522
+ });
523
+
524
+ test('probe: an Auto-clear read settling after Esc paints nothing', async () => {
525
+ supersedePanelEpoch();
526
+ const host = createPanelHost();
527
+ const autoClear = { enabled: true, idleMs: 3_600_000, providerDefaults: [] };
528
+ let readGate = null;
529
+ let reads = 0;
530
+ const noop = () => {};
531
+ const { openAutoClearPicker } = createMaintenancePickers({
532
+ store: {
533
+ pushNotice: () => {},
534
+ getAutoClear: () => { reads += 1; return readGate ? readGate.promise : Promise.resolve(autoClear); },
535
+ },
536
+ theme: { success: '' },
537
+ formatDuration: (ms) => `${ms}ms`,
538
+ surface: host.surface,
539
+ setProviderPrompt: noop,
540
+ setSettingsPrompt: noop,
541
+ closeUsagePanel: noop,
542
+ });
543
+
544
+ openAutoClearPicker({});
545
+ await flush();
546
+ assert.equal(host.current().title, 'Auto-clear');
547
+
548
+ // Enter on "Advanced" → renderAdvanced(): another daemon read, another paint.
549
+ readGate = deferred();
550
+ host.current().onSelect('advanced', { _action: 'advanced' });
551
+ await flush();
552
+ host.setPicker(null);
553
+ const paintedBefore = host.painted.length;
554
+
555
+ readGate.resolve(autoClear);
556
+ await flush();
557
+
558
+ assert.ok(reads >= 2, 'Advanced must have issued its own read');
559
+ assert.equal(host.current(), null, 'afterEsc');
560
+ assert.equal(host.painted.length - paintedBefore, 0, 'latePaints');
561
+ });
562
+
563
+ test('probe: a model load completing after Esc paints nothing', async () => {
564
+ supersedePanelEpoch();
565
+ const host = createPanelHost();
566
+ const loadGate = deferred();
567
+ const noop = () => {};
568
+ const { openModelPicker } = createModelPicker({
569
+ store: { pushNotice: () => {}, listProviderModels: () => loadGate.promise },
570
+ getState: () => ({ provider: 'openai', model: 'gpt-5', effort: null, fast: false }),
571
+ surface: host.surface,
572
+ setProviderPrompt: noop,
573
+ setSettingsPrompt: noop,
574
+ providerModelsCacheRef: { current: { models: [], at: 0 } },
575
+ webSearchModelsCacheRef: { current: { models: [], at: 0 } },
576
+ modelPickerRequestRef: { current: 0 },
577
+ clearModelCaches: noop,
578
+ modelSwitchNotice: () => 'switched',
579
+ // NOT stubbed away: the empty-catalog fallback really opens Providers, and
580
+ // a stub would hide an unguarded delegation.
581
+ openProviderSetupPicker: () => { host.setPicker({ title: 'Providers' }); },
582
+ });
583
+
584
+ void openModelPicker({ refreshModels: true });
585
+ await flush();
586
+ // The synchronous loading frame is on screen; Esc closes it mid-load.
587
+ assert.equal(host.current().title, 'Model');
588
+ host.setPicker(null);
589
+ const paintedBefore = host.painted.length;
590
+
591
+ loadGate.resolve([{ provider: 'openai', id: 'gpt-5', label: 'GPT-5' }]);
592
+ await flush();
593
+
594
+ assert.equal(host.current(), null, 'afterEsc');
595
+ assert.equal(host.painted.length - paintedBefore, 0, 'latePaints');
596
+ });
597
+
598
+ test('probe: onboarding Step 1 does not paint when Esc lands during its read', async () => {
599
+ supersedePanelEpoch();
600
+ const host = createPanelHost();
601
+ host.setPicker({ title: 'Settings' });
602
+ const setupGate = deferred();
603
+ const opened = [];
604
+ const noop = () => {};
605
+ const { openOnboardingAuthStep } = createOnboardingSteps({
606
+ store: { pushNotice: () => {}, getProviderSetup: () => setupGate.promise },
607
+ surface: host.surface,
608
+ setProviderPrompt: noop,
609
+ setSettingsPrompt: noop,
610
+ setOnboardingActive: noop,
611
+ onboardingRef: { current: { providerModels: [{ provider: 'openai', id: 'gpt-5' }], agents: [{ id: 'lead' }] } },
612
+ providerModelsCacheRef: { current: { models: [], at: 0 } },
613
+ onboardingPrefetchSeqRef: { current: 0 },
614
+ openProviderSetupPicker: (options) => { opened.push(options?.title); },
615
+ openThemePicker: noop,
616
+ openOutputStylePicker: noop,
617
+ });
618
+
619
+ void openOnboardingAuthStep();
620
+ await flush();
621
+ host.setPicker(null);
622
+ const paintedBefore = host.painted.length;
623
+
624
+ setupGate.resolve({ providers: [] });
625
+ await flush();
626
+
627
+ assert.deepEqual(opened, [], 'Step 1 must not open');
628
+ assert.equal(host.current(), null, 'afterEsc');
629
+ assert.equal(host.painted.length - paintedBefore, 0, 'latePaints');
630
+ });
631
+
632
+ // ── Post-await DELEGATION: handing the surface to ANOTHER panel is a paint ───
633
+ // Empty-result / error / no-op fallbacks reach a different panel without going
634
+ // through this opener's paint path, so they need the same ownership proof.
635
+
636
+ function createModelHarness(host, loadGate) {
637
+ const noop = () => {};
638
+ const opened = [];
639
+ const notices = [];
640
+ const { openModelPicker } = createModelPicker({
641
+ store: { pushNotice: (message) => notices.push(String(message)), listProviderModels: () => loadGate.promise },
642
+ getState: () => ({ provider: 'openai', model: 'gpt-5' }),
643
+ surface: host.surface,
644
+ setProviderPrompt: noop,
645
+ setSettingsPrompt: noop,
646
+ providerModelsCacheRef: { current: { models: [], at: 0 } },
647
+ webSearchModelsCacheRef: { current: { models: [], at: 0 } },
648
+ modelPickerRequestRef: { current: 0 },
649
+ clearModelCaches: noop,
650
+ modelSwitchNotice: () => 'switched',
651
+ openProviderSetupPicker: () => {
652
+ opened.push('Providers');
653
+ host.setPicker({ title: 'Providers' });
654
+ },
655
+ });
656
+ return { openModelPicker, opened, notices };
657
+ }
658
+
659
+ // Proof that the branch under test actually ran: without it a probe passes for
660
+ // the wrong reason (the chain simply had not reached the delegation yet).
661
+ const branchRan = (notices, pattern, label) => assert.ok(
662
+ notices.some((message) => pattern.test(message)),
663
+ `${label}: the branch under test did not run`,
664
+ );
665
+
666
+ test('probe: the empty-catalog fallback does not delegate to Providers after Esc', async () => {
667
+ supersedePanelEpoch();
668
+ const host = createPanelHost();
669
+ const loadGate = deferred();
670
+ const { openModelPicker, opened, notices } = createModelHarness(host, loadGate);
671
+
672
+ void openModelPicker({ refreshModels: true });
673
+ await flush();
674
+ assert.equal(host.current().title, 'Model');
675
+ host.setPicker(null);
676
+ const paintedBefore = host.painted.length;
677
+
678
+ loadGate.resolve([]); // empty catalog → Providers fallback branch
679
+ await flush();
680
+
681
+ branchRan(notices, /no provider models available/, 'empty-catalog');
682
+ assert.deepEqual(opened, [], 'Providers must not open');
683
+ assert.equal(host.current(), null, 'afterEsc');
684
+ assert.equal(host.painted.length - paintedBefore, 0, 'latePaints');
685
+ });
686
+
687
+ test('probe: an uninterrupted empty catalog still delegates to Providers', async () => {
688
+ supersedePanelEpoch();
689
+ const host = createPanelHost();
690
+ const loadGate = deferred();
691
+ const { openModelPicker, opened } = createModelHarness(host, loadGate);
692
+
693
+ void openModelPicker({ refreshModels: true });
694
+ await flush();
695
+ loadGate.resolve([]);
696
+ await flush();
697
+
698
+ assert.deepEqual(opened, ['Providers']);
699
+ assert.equal(host.current().title, 'Providers');
700
+ });
701
+
702
+ function createOnboardingHarness(host, overrides = {}) {
703
+ const noop = () => {};
704
+ const opened = [];
705
+ const notices = [];
706
+ const steps = createOnboardingSteps({
707
+ store: {
708
+ pushNotice: (message) => notices.push(String(message)),
709
+ getProviderSetup: async () => ({ providers: [] }),
710
+ listProviderModels: async () => [{ provider: 'openai', id: 'gpt-5' }],
711
+ listWebSearchModels: async () => [],
712
+ listAgents: async () => [],
713
+ ...overrides,
714
+ },
715
+ surface: host.surface,
716
+ setProviderPrompt: noop,
717
+ setSettingsPrompt: noop,
718
+ setOnboardingActive: noop,
719
+ onboardingRef: { current: {} },
720
+ providerModelsCacheRef: { current: { models: [], at: 0 } },
721
+ onboardingPrefetchSeqRef: { current: 0 },
722
+ // Step 1 is a real panel here too, so an unguarded fallback shows as a paint.
723
+ openProviderSetupPicker: (options) => {
724
+ opened.push(options?.title);
725
+ host.setPicker({ title: options?.title || 'Providers' });
726
+ },
727
+ openThemePicker: noop,
728
+ openOutputStylePicker: noop,
729
+ });
730
+ return { steps, opened, notices };
731
+ }
732
+
733
+ test('probe: Step 2 empty-model fallback does not reopen Step 1 after Esc', async () => {
734
+ supersedePanelEpoch();
735
+ const host = createPanelHost();
736
+ host.setPicker({ title: 'Settings' });
737
+ const modelsGate = deferred();
738
+ const { steps, opened, notices } = createOnboardingHarness(host, { listProviderModels: () => modelsGate.promise });
739
+
740
+ void steps.openOnboardingWorkflowStep();
741
+ await flush();
742
+ host.setPicker(null);
743
+ const paintedBefore = host.painted.length;
744
+
745
+ modelsGate.resolve([]); // empty models → Step 1 fallback branch
746
+ await flush();
747
+
748
+ branchRan(notices, /no provider models available/, 'empty-models');
749
+ assert.deepEqual(opened, [], 'Step 1 must not open');
750
+ assert.equal(host.current(), null, 'afterEsc');
751
+ assert.equal(host.painted.length - paintedBefore, 0, 'latePaints');
752
+ });
753
+
754
+ test('probe: the onboarding Web Search fallback does not jump to Step 2 after Esc', async () => {
755
+ supersedePanelEpoch();
756
+ const host = createPanelHost();
757
+ host.setPicker({ title: 'Settings' });
758
+ const webSearchGate = deferred();
759
+ const { steps, notices } = createOnboardingHarness(host, { listWebSearchModels: () => webSearchGate.promise });
760
+
761
+ void steps.openOnboardingRoleModelPicker('webSearch');
762
+ await flush();
763
+ host.setPicker(null);
764
+ const paintedBefore = host.painted.length;
765
+
766
+ webSearchGate.resolve([]); // empty list → "back to Step 2" fallback branch
767
+ await flush();
768
+
769
+ branchRan(notices, /no native web-search models available/, 'empty-web-search');
770
+ assert.equal(host.current(), null, 'afterEsc');
771
+ assert.equal(host.painted.length - paintedBefore, 0, 'latePaints');
772
+ });
773
+
774
+ // ── The class rule, now STRUCTURAL ──────────────────────────────────────────
775
+ // This used to be an AST analyzer over arbitrary JavaScript, and every review
776
+ // round defeated it in a new way (guard polarity, member/showX calls, renamed
777
+ // re-exported aliases, callbacks handed to other modules, stored callbacks,
778
+ // reassigned bindings, yield, labelled break, class fields). It is replaced by
779
+ // two facts nothing has to infer: the raw sinks do not exist outside the owning
780
+ // layer, and the only way in — a claim — validates ownership at the sink.
781
+ const OWNING_LAYER = new Set(['App.jsx', 'panel-surface.mjs']);
782
+ const RAW_SINKS = /\b(?:setPicker|setContextPanel|setUsagePanel)\b/;
783
+
784
+ // Sources only: src/tui/dist/index.mjs is a bundle of exactly these files.
785
+ const GENERATED = new Set(['dist', 'node_modules']);
786
+
787
+ async function sourceFiles(directory) {
788
+ const out = [];
789
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
790
+ const full = join(directory, entry.name);
791
+ if (entry.isDirectory()) {
792
+ if (!GENERATED.has(entry.name)) out.push(...await sourceFiles(full));
793
+ }
794
+ else if (/\.(?:mjs|jsx|js)$/.test(entry.name) && !entry.name.endsWith('.test.mjs')) out.push(full);
795
+ }
796
+ return out;
797
+ }
798
+
799
+ test('audit: the raw panel sinks are unreachable outside the owning layer', async () => {
800
+ const root = fileURLToPath(new URL('..', import.meta.url));
801
+ const offenders = [];
802
+ for (const file of await sourceFiles(root)) {
803
+ if (OWNING_LAYER.has(basename(file))) continue;
804
+ const source = await readFile(file, 'utf8');
805
+ if (RAW_SINKS.test(source)) offenders.push(relative(root, file));
806
+ }
807
+ // Nothing to alias, rename, or smuggle through a callback: outside these two
808
+ // files the sink names do not occur at all.
809
+ assert.deepEqual(offenders, []);
810
+ });
811
+
812
+ test('audit: a claim rejects every late-paint shape once the surface changed hands', async () => {
813
+ supersedePanelEpoch();
814
+ const host = createPanelHost();
815
+ host.setPicker({ title: 'Settings' });
816
+ const own = host.surface.claim();
817
+
818
+ // Every shape that defeated the analyzer, built while the claim is valid: an
819
+ // alias, a member call, a stored callback, a class field, and a callback
820
+ // handed to a foreign module that decides when to run it.
821
+ const alias = own.paint;
822
+ const holder = { paint: own.paint };
823
+ const stored = () => own.paint({ title: 'Stored' });
824
+ class LatePanel { painted = own.paint({ title: 'Field' }); }
825
+ let subscriber = null;
826
+ const foreignModule = { subscribe: (fn) => { subscriber = fn; } };
827
+ foreignModule.subscribe(() => own.paint({ title: 'Pushed' }));
828
+
829
+ // Undisturbed they all paint, so the probe below is not vacuous.
830
+ const beforeValid = host.painted.length;
831
+ alias({ title: 'Alias' });
832
+ holder.paint({ title: 'Member' });
833
+ stored();
834
+ void new LatePanel();
835
+ subscriber();
836
+ // Bound to the surface this action currently holds, exactly like the openers.
837
+ const deferredPaint = own.defer(() => own.paint({ title: 'Deferred' }));
838
+ deferredPaint();
839
+ assert.equal(host.painted.length - beforeValid, 6, 'validPaints');
840
+
841
+ // Esc: the user takes the surface back, and the async work settles after it.
842
+ host.setPicker(null);
843
+ await flush(1);
844
+ const afterEsc = host.painted.length;
845
+ alias({ title: 'Alias' });
846
+ holder.paint({ title: 'Member' });
847
+ stored();
848
+ void new LatePanel();
849
+ subscriber();
850
+ deferredPaint();
851
+ assert.equal(host.painted.length - afterEsc, 0, 'latePaints');
852
+ assert.equal(host.current(), null);
853
+ });
854
+
855
+ test('probe: a late Agent "Not used" ack does not overwrite the replacement panel', async () => {
856
+ supersedePanelEpoch();
857
+ const host = createPanelHost();
858
+ const saveGate = deferred();
859
+ const noop = () => {};
860
+ const notices = [];
861
+ const { openAgentsPicker } = createRoutePickers({
862
+ store: {
863
+ pushNotice: (message) => notices.push(String(message)),
864
+ listAgents: async () => [{ id: 'reviewer', label: 'Reviewer', description: 'reviews', route: {} }],
865
+ setAgentRoute: () => saveGate.promise,
866
+ },
867
+ state: {},
868
+ surface: host.surface,
869
+ setProviderPrompt: noop,
870
+ setSettingsPrompt: noop,
871
+ closeUsagePanel: noop,
872
+ clean: (value) => value,
873
+ routeLabel: () => 'route',
874
+ agentModelParts: () => [],
875
+ agentModelProfile: () => 'profile',
876
+ workflowSwitchNotice: () => 'switched',
877
+ openModelPicker: noop,
878
+ });
879
+
880
+ await openAgentsPicker();
881
+ await flush();
882
+ const agents = host.current();
883
+ assert.equal(agents.title, 'Agents');
884
+ agents.onSelect('reviewer', agents.items[0]);
885
+ const agentPanel = host.current();
886
+ assert.equal(agentPanel.title, 'Reviewer');
887
+
888
+ void agentPanel.onSelect('off'); // Enter on "Not used": the write starts
889
+ // Something else takes the surface before the ack lands.
890
+ host.setPicker({ title: 'Settings' });
891
+ const paintedBefore = host.painted.length;
892
+
893
+ saveGate.resolve({ disabled: true });
894
+ await flush();
895
+
896
+ branchRan(notices, /no longer used/, 'agent-off');
897
+ assert.equal(host.current().title, 'Settings', 'afterReplacement');
898
+ assert.equal(host.painted.length - paintedBefore, 0, 'latePaints');
899
+ });
900
+
901
+ test('probe: an undisturbed Agent "Not used" ack still reopens Agents', async () => {
902
+ supersedePanelEpoch();
903
+ const host = createPanelHost();
904
+ const saveGate = deferred();
905
+ const noop = () => {};
906
+ const { openAgentsPicker } = createRoutePickers({
907
+ store: {
908
+ pushNotice: () => {},
909
+ listAgents: async () => [{ id: 'reviewer', label: 'Reviewer', description: 'reviews', route: {} }],
910
+ setAgentRoute: () => saveGate.promise,
911
+ },
912
+ state: {},
913
+ surface: host.surface,
914
+ setProviderPrompt: noop,
915
+ setSettingsPrompt: noop,
916
+ closeUsagePanel: noop,
917
+ clean: (value) => value,
918
+ routeLabel: () => 'route',
919
+ agentModelParts: () => [],
920
+ agentModelProfile: () => 'profile',
921
+ workflowSwitchNotice: () => 'switched',
922
+ openModelPicker: noop,
923
+ });
924
+
925
+ await openAgentsPicker();
926
+ await flush();
927
+ host.current().onSelect('reviewer', host.current().items[0]);
928
+ void host.current().onSelect('off');
929
+
930
+ saveGate.resolve({ disabled: true });
931
+ await flush();
932
+
933
+ assert.equal(host.current().title, 'Agents', 'the undisturbed flow still repaints');
934
+ });
935
+
936
+ test('main-provider Enter still opens the provider action panel', async () => {
937
+ supersedePanelEpoch();
938
+ const host = createPanelHost();
939
+ const noop = () => {};
940
+ const { openProviderSetupPicker } = createProviderSetupPicker({
941
+ store: {
942
+ pushNotice: () => {},
943
+ getProviderSetup: async () => ({
944
+ api: [{ id: 'openai', name: 'OpenAI', authenticated: true, stored: true }],
945
+ oauth: [],
946
+ local: [],
947
+ }),
948
+ },
949
+ surface: host.surface,
950
+ setProviderPrompt: noop,
951
+ setSettingsPrompt: noop,
952
+ closeUsagePanel: noop,
953
+ oauthSubmitRef: { current: false },
954
+ clearModelCaches: noop,
955
+ });
956
+
957
+ await openProviderSetupPicker({});
958
+ await flush();
959
+ const list = host.current();
960
+ assert.equal(list.title, 'Providers');
961
+
962
+ // Enter on a provider row: in-flow navigation, so the action panel must paint.
963
+ const providerRow = list.items.find((item) => item._type === 'api-key');
964
+ list.onSelect(providerRow.value, providerRow);
965
+
966
+ assert.equal(host.current()?.title, 'Provider · OpenAI', 'afterEnter');
967
+ assert.deepEqual(
968
+ host.painted.slice(-2).map((panel) => (panel === null ? null : panel.title)),
969
+ [null, 'Provider · OpenAI'],
970
+ );
971
+ });
972
+
973
+ test('a context open still in flight cannot reopen what Esc dismissed', () => {
974
+ supersedePanelEpoch();
975
+ const host = createPanelHost();
976
+ const usage = { _kind: 'context-usage', title: 'Context Usage' };
977
+
978
+ // A flow opens the context panel and keeps its claim, the way a real
979
+ // openContextPicker() holds one across the await that fetches the numbers.
980
+ const opening = host.surface.claim();
981
+ assert.equal(opening.context(usage), true);
982
+
983
+ // Esc on the context panel: that keypress owns what it closes
984
+ // (use-global-key-input.mjs, use-prompt-handlers.mjs, slash-dispatch.mjs all
985
+ // take a fresh claim for exactly this).
986
+ assert.equal(host.surface.claim().context(null), true);
987
+
988
+ // The open settles afterwards. Before the surface superseded on a context
989
+ // clear this repainted "Context Usage" over a screen the user had dismissed.
990
+ assert.equal(opening.context(usage), false, 'late context paint was accepted');
991
+ assert.deepEqual(host.contextPainted, [usage, null]);
992
+
993
+ // The dismissal does not wedge the surface: the next user action still owns it.
994
+ const reopening = host.surface.claim();
995
+ assert.equal(reopening.context(usage), true);
996
+ assert.deepEqual(host.contextPainted, [usage, null, usage]);
997
+ });
998
+
999
+ test('clearing context mid-flow keeps the flow that cleared it', () => {
1000
+ supersedePanelEpoch();
1001
+ const host = createPanelHost();
1002
+
1003
+ // Settings pickers clear the context panel and carry on painting their own
1004
+ // surface in the same action (maintenance-pickers.mjs, theme-effort-pickers.mjs).
1005
+ const own = host.surface.claim();
1006
+ assert.equal(own.context(null), true);
1007
+ assert.equal(own.paint({ _kind: 'settings', title: 'Settings' }), true);
1008
+ assert.equal(host.current()?.title, 'Settings');
1009
+ });