rvlib-shipkit 2.29.0 → 2.30.0

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 (512) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/package.json +2 -1
  3. package/src/advisors/app-graph.ts +1 -1
  4. package/src/advisors/expose.ts +5 -1
  5. package/src/advisors/r2.ts +7 -9
  6. package/src/advisors/routes.ts +29 -2
  7. package/src/advisors/scan.ts +11 -0
  8. package/src/agent-time/accounts-usage.ts +8 -0
  9. package/src/agent-time/claude-sessions.ts +32 -0
  10. package/src/agent-time/hooks.ts +1 -1
  11. package/src/agent-time/live.ts +5 -2
  12. package/src/agent-time/registry.ts +186 -89
  13. package/src/agent-time/store.ts +6 -4
  14. package/src/asks/ask-doc.ts +2 -2
  15. package/src/asks/ask-store.ts +22 -7
  16. package/src/check.ts +9 -1
  17. package/src/checks/SK001-package-json-shape.check.ts +1 -0
  18. package/src/checks/SK003-claude-md-shape.check.ts +1 -0
  19. package/src/checks/SK004-gitignore-policy.check.ts +12 -6
  20. package/src/checks/SK008-reviewer-agent.check.ts +4 -7
  21. package/src/checks/SK013-one-way-in-policy.check.ts +1 -0
  22. package/src/checks/SK017-vscode-hub-task.check.ts +1 -0
  23. package/src/checks/SK024-identity-colors.check.ts +1 -1
  24. package/src/checks/SK027-agent-wiki-links.check.ts +2 -1
  25. package/src/checks/SK033-global-contribution.check.ts +1 -0
  26. package/src/checks/SK034-commit-gates-armed.check.ts +1 -0
  27. package/src/checks/SK039-vscode-watch-generated.check.ts +1 -0
  28. package/src/checks/SK049-thread-answers-hook.check.ts +9 -5
  29. package/src/checks/SK050-retired-commands.check.ts +1 -0
  30. package/src/checks/SK051-no-formatter.check.ts +1 -0
  31. package/src/cli/channel-run.ts +17 -0
  32. package/src/cli/cmd_Advisors.ts +28 -7
  33. package/src/cli/cmd_Asks.ts +2 -2
  34. package/src/cli/cmd_Backup.ts +5 -1
  35. package/src/cli/cmd_CacheAudit.ts +1 -1
  36. package/src/cli/cmd_Channel.ts +43 -0
  37. package/src/cli/cmd_GlobalProcesses.ts +1 -0
  38. package/src/cli/cmd_Home.ts +12 -5
  39. package/src/cli/cmd_Hooks.ts +1 -1
  40. package/src/cli/cmd_Hq.ts +43 -0
  41. package/src/cli/cmd_Lanes.ts +15 -3
  42. package/src/cli/cmd_Media.ts +8 -3
  43. package/src/cli/cmd_Orchestrator.ts +253 -84
  44. package/src/cli/cmd_OrchestratorRole.ts +163 -0
  45. package/src/cli/cmd_Review.ts +142 -165
  46. package/src/cli/cmd_Secret.ts +44 -14
  47. package/src/cli/cmd_Shot.ts +2 -4
  48. package/src/cli/cmd_Sound.ts +1 -0
  49. package/src/cli/cmd_Urls.ts +3 -3
  50. package/src/cli/inbox-hook-run.ts +109 -0
  51. package/src/cli/registry.ts +6 -2
  52. package/src/cli/review-here.ts +136 -0
  53. package/src/cli.ts +45 -14
  54. package/src/collections/actions.ts +5 -4
  55. package/src/collections/checks.ts +5 -0
  56. package/src/collections/collection-types.ts +4 -3
  57. package/src/collections/pings.ts +4 -1
  58. package/src/collections/providers.ts +6 -4
  59. package/src/collections/tests.ts +7 -4
  60. package/src/core/app-icon-frame.ts +62 -0
  61. package/src/core/app-icon.ts +179 -17
  62. package/src/core/archived.ts +10 -7
  63. package/src/core/check-ctx.ts +38 -4
  64. package/src/core/check-pass.ts +7 -0
  65. package/src/core/foreign.ts +87 -0
  66. package/src/core/gui-color.ts +75 -0
  67. package/src/core/hub-theme.ts +1 -3
  68. package/src/core/layout.ts +3 -0
  69. package/src/core/machine-commit.ts +9 -1
  70. package/src/core/one-lib.ts +2 -1
  71. package/src/core/one-way-in-policy.ts +17 -12
  72. package/src/core/owner-word-policy.ts +123 -0
  73. package/src/core/panel-shades.ts +140 -0
  74. package/src/core/repo-gui-color.ts +16 -0
  75. package/src/core/role-policy.ts +17 -0
  76. package/src/core/scope.ts +6 -3
  77. package/src/core/tmux-policy.ts +264 -0
  78. package/src/core/unit-icon.ts +43 -0
  79. package/src/fleet/push-fleet.ts +2 -0
  80. package/src/fleet/scan-fleet.ts +3 -0
  81. package/src/gate/cache-audit.ts +7 -1
  82. package/src/gate/gate-checks.ts +14 -9
  83. package/src/gate/run-fix.ts +30 -5
  84. package/src/gate/run-fixers.ts +8 -3
  85. package/src/home/activity-shape.ts +2 -0
  86. package/src/home/activity.ts +2 -1
  87. package/src/home/daemon-guard.ts +20 -2
  88. package/src/home/daemon-jobs.ts +26 -18
  89. package/src/home/gui-app/ShipkitGui.swift +2012 -144
  90. package/src/home/gui-app/icon.svg +8 -0
  91. package/src/home/gui-app.ts +94 -30
  92. package/src/home/home-routes.ts +53 -9
  93. package/src/home/home-start.ts +27 -3
  94. package/src/home/inbox-shape.ts +7 -3
  95. package/src/home/log-follow.ts +117 -0
  96. package/src/home/machine-fold.ts +1 -1
  97. package/src/home/open-app.ts +9 -3
  98. package/src/home/page-build.ts +5 -1
  99. package/src/home/page-held.ts +1 -1
  100. package/src/home/pm-config.ts +0 -8
  101. package/src/home/pm.ts +62 -5
  102. package/src/home/process-apps.ts +70 -23
  103. package/src/home/process-rows.ts +16 -1
  104. package/src/home/push-sources.ts +18 -13
  105. package/src/home/resources.ts +16 -7
  106. package/src/home/run-daemon.ts +4 -1
  107. package/src/home/run-pm.ts +1 -1
  108. package/src/home/serve-daemon.ts +13 -4
  109. package/src/home/serve-web.ts +141 -17
  110. package/src/home/space-page.ts +3 -3
  111. package/src/home/space-route.ts +2 -2
  112. package/src/home/supervise.ts +2 -1
  113. package/src/home/vault-page.ts +2 -1
  114. package/src/home/web-places.ts +239 -0
  115. package/src/home/widgets.ts +16 -2
  116. package/src/hooks/commit-message.ts +11 -9
  117. package/src/hooks/one-way-in-guard.ts +145 -68
  118. package/src/hooks/run-hooks.ts +15 -5
  119. package/src/hooks/shared-file.ts +273 -83
  120. package/src/hooks/shell-writes.ts +620 -0
  121. package/src/hooks/write-log.ts +149 -0
  122. package/src/hq/door-route.ts +63 -7
  123. package/src/hq/door.ts +45 -12
  124. package/src/hq/history-send.ts +3 -1
  125. package/src/hq/hq-db.ts +10 -3
  126. package/src/hq/hq-local.ts +24 -5
  127. package/src/hq/hq-routes.ts +3 -1
  128. package/src/hq/hq-store.ts +9 -3
  129. package/src/hq/kinds/index.ts +2 -1
  130. package/src/hq/kinds/kind.ts +9 -4
  131. package/src/hq/kinds/presence-rule.ts +56 -0
  132. package/src/hq/kinds/presence.ts +210 -0
  133. package/src/hq/kinds/report.ts +8 -5
  134. package/src/hq/lead-order.ts +68 -0
  135. package/src/hq/outbox.ts +7 -0
  136. package/src/hq/replica.ts +5 -7
  137. package/src/hq/report-facts.ts +14 -7
  138. package/src/hq/report.ts +47 -2
  139. package/src/hq/switch.ts +1 -0
  140. package/src/hq/terminal-hop.ts +64 -0
  141. package/src/hq/thread-sync.ts +13 -6
  142. package/src/http/door-forward.ts +10 -12
  143. package/src/http/door-names.ts +9 -0
  144. package/src/http/hop-caller.ts +23 -0
  145. package/src/http/hop-names.ts +14 -0
  146. package/src/http/loopback-serve.ts +28 -6
  147. package/src/http/owner-word.ts +128 -0
  148. package/src/http/same-origin.ts +12 -0
  149. package/src/{serve → http}/secret-gate.ts +3 -3
  150. package/src/ledger/run-log.ts +25 -1
  151. package/src/media-store/backup/sources.ts +53 -6
  152. package/src/media-store/backup/thread-copy.ts +9 -5
  153. package/src/media-store/copy/config.ts +10 -9
  154. package/src/media-store/daemon.ts +5 -2
  155. package/src/media-store/put.ts +3 -0
  156. package/src/media-store/space.ts +14 -16
  157. package/src/media-store/upload.ts +4 -0
  158. package/src/messages/collection.ts +2 -2
  159. package/src/messages/model.ts +6 -1
  160. package/src/messages/routes.ts +3 -0
  161. package/src/orchestrator/brief.md +8 -6
  162. package/src/orchestrator/channel-declare.ts +58 -0
  163. package/src/orchestrator/channel.ts +226 -0
  164. package/src/orchestrator/guards.ts +12 -3
  165. package/src/orchestrator/host.ts +35 -0
  166. package/src/orchestrator/lead-shape.ts +86 -0
  167. package/src/orchestrator/now.ts +88 -0
  168. package/src/orchestrator/phone.ts +4 -1
  169. package/src/orchestrator/places-file.ts +38 -0
  170. package/src/orchestrator/places-look.ts +180 -0
  171. package/src/orchestrator/places-shape.ts +151 -0
  172. package/src/orchestrator/places.ts +50 -0
  173. package/src/orchestrator/presence-shape.ts +13 -2
  174. package/src/orchestrator/presence.ts +26 -15
  175. package/src/orchestrator/push.ts +5 -10
  176. package/src/orchestrator/role-shape.ts +270 -0
  177. package/src/orchestrator/role.ts +242 -0
  178. package/src/orchestrator/routes.ts +136 -31
  179. package/src/orchestrator/sessions-shape.ts +78 -0
  180. package/src/orchestrator/sessions.ts +86 -0
  181. package/src/orchestrator/share.ts +71 -0
  182. package/src/orchestrator/start-notice.ts +61 -0
  183. package/src/orchestrator/start.ts +137 -0
  184. package/src/orchestrator/started.ts +55 -0
  185. package/src/orchestrator/stuck.ts +196 -0
  186. package/src/orchestrator/unheard.ts +18 -7
  187. package/src/pages/frame-client.ts +44 -6
  188. package/src/problems/failure-words.ts +80 -0
  189. package/src/release/run-bump.ts +26 -5
  190. package/src/release/run-release.ts +34 -14
  191. package/src/repo-config.ts +37 -9
  192. package/src/review/aside-at.ts +19 -0
  193. package/src/review/band.ts +3 -3
  194. package/src/review/doc-save.ts +1 -1
  195. package/src/review/inbox-hook.ts +12 -4
  196. package/src/review/inbox-read.ts +20 -7
  197. package/src/review/instruction-guards.ts +137 -0
  198. package/src/review/instructions.ts +14 -2
  199. package/src/review/item-db.ts +52 -2
  200. package/src/review/mentions.ts +6 -4
  201. package/src/review/model.ts +3 -2
  202. package/src/review/parties.ts +88 -19
  203. package/src/review/push.ts +32 -15
  204. package/src/review/routes.ts +12 -4
  205. package/src/review/secret-route.ts +5 -5
  206. package/src/review/snooze.ts +1 -16
  207. package/src/review/store-parties.ts +4 -2
  208. package/src/review/take-back.ts +2 -1
  209. package/src/review/threads.ts +13 -2
  210. package/src/review/unit.ts +3 -2
  211. package/src/review/view-layout.ts +8 -1
  212. package/src/review/watchers.ts +25 -4
  213. package/src/secrets/key-pair.ts +14 -0
  214. package/src/secrets/lapse.ts +3 -3
  215. package/src/secrets/manager.ts +5 -1
  216. package/src/secrets/name-template.ts +83 -0
  217. package/src/secrets/name.ts +3 -0
  218. package/src/secrets/read.ts +10 -6
  219. package/src/secrets/secrets-view.ts +299 -0
  220. package/src/secrets/who-reads.ts +2 -1
  221. package/src/serve/frame-part.ts +49 -0
  222. package/src/serve/hub-app/accounts-line.tsx +33 -45
  223. package/src/serve/hub-app/activity-st.ts +6 -5
  224. package/src/serve/hub-app/activity-view.tsx +10 -9
  225. package/src/serve/hub-app/advice-box.tsx +6 -5
  226. package/src/serve/hub-app/advisor-app.tsx +2 -0
  227. package/src/serve/hub-app/advisor-face.tsx +3 -2
  228. package/src/serve/hub-app/advisor.html +1 -0
  229. package/src/serve/hub-app/advisors-view.tsx +52 -10
  230. package/src/serve/hub-app/advisors.css +4 -0
  231. package/src/serve/hub-app/app-bridge.ts +31 -5
  232. package/src/serve/hub-app/asked-page.ts +24 -0
  233. package/src/serve/hub-app/asks-page.tsx +10 -6
  234. package/src/serve/hub-app/auto-text.tsx +7 -5
  235. package/src/serve/hub-app/card-head.tsx +3 -2
  236. package/src/serve/hub-app/check-view.tsx +10 -9
  237. package/src/serve/hub-app/checks-svc.ts +96 -32
  238. package/src/serve/hub-app/clock-svc.ts +24 -8
  239. package/src/serve/hub-app/code-copy.ts +1 -1
  240. package/src/serve/hub-app/col-card.tsx +2 -1
  241. package/src/serve/hub-app/col-list-page.tsx +12 -6
  242. package/src/serve/hub-app/col-list-st.ts +12 -2
  243. package/src/serve/hub-app/col-tables-view.tsx +8 -44
  244. package/src/serve/hub-app/col-tables.ts +0 -14
  245. package/src/serve/hub-app/cols-svc.ts +6 -12
  246. package/src/serve/hub-app/columns.ts +94 -0
  247. package/src/serve/hub-app/comfy-view.tsx +8 -7
  248. package/src/serve/hub-app/commands/commands-page.tsx +4 -3
  249. package/src/serve/hub-app/commands/commands-st.ts +2 -2
  250. package/src/serve/hub-app/controls.css +69 -23
  251. package/src/serve/hub-app/cycle-button.tsx +2 -1
  252. package/src/serve/hub-app/database-st.ts +1 -1
  253. package/src/serve/hub-app/database-view.tsx +4 -2
  254. package/src/serve/hub-app/deaf.tsx +27 -0
  255. package/src/serve/hub-app/dock-st.ts +21 -16
  256. package/src/serve/hub-app/dock-view.tsx +19 -12
  257. package/src/serve/hub-app/empty-section.tsx +30 -0
  258. package/src/serve/hub-app/entry-bar.css +1 -1
  259. package/src/serve/hub-app/entry-bar.tsx +11 -6
  260. package/src/serve/hub-app/entry-list.css +32 -0
  261. package/src/serve/hub-app/entry-list.tsx +123 -0
  262. package/src/serve/hub-app/entry-pick.ts +1 -1
  263. package/src/serve/hub-app/entry-sections.ts +140 -0
  264. package/src/serve/hub-app/event-stream-reader.ts +56 -0
  265. package/src/serve/hub-app/floating.tsx +68 -14
  266. package/src/serve/hub-app/geometry-view.tsx +3 -2
  267. package/src/serve/hub-app/git-view.tsx +3 -2
  268. package/src/serve/hub-app/hash-route.ts +14 -2
  269. package/src/serve/hub-app/header-bar.tsx +53 -36
  270. package/src/serve/hub-app/home-st.ts +131 -14
  271. package/src/serve/hub-app/home-strip.css +24 -13
  272. package/src/serve/hub-app/home-strip.tsx +131 -66
  273. package/src/serve/hub-app/home.html +5 -0
  274. package/src/serve/hub-app/hub-app.tsx +94 -102
  275. package/src/serve/hub-app/hub.css +61 -94
  276. package/src/serve/hub-app/icons.tsx +16 -0
  277. package/src/serve/hub-app/identities-st.ts +19 -54
  278. package/src/serve/hub-app/identities-view.tsx +25 -24
  279. package/src/serve/hub-app/identity-address.ts +2 -2
  280. package/src/serve/hub-app/in-sight.ts +10 -0
  281. package/src/serve/hub-app/inbox-st.ts +20 -2
  282. package/src/serve/hub-app/inbox-view.tsx +16 -9
  283. package/src/serve/hub-app/inbox.css +1 -0
  284. package/src/serve/hub-app/index.html +5 -0
  285. package/src/serve/hub-app/insights-view.tsx +6 -5
  286. package/src/serve/hub-app/instructions.css +4 -1
  287. package/src/serve/hub-app/kept-cols.tsx +83 -20
  288. package/src/serve/hub-app/kept-width.tsx +76 -0
  289. package/src/serve/hub-app/keys.ts +116 -38
  290. package/src/serve/hub-app/layout-st.ts +109 -99
  291. package/src/serve/hub-app/lightbox-zoom.css +36 -0
  292. package/src/serve/hub-app/list-filter.tsx +15 -6
  293. package/src/serve/hub-app/list-head.tsx +29 -0
  294. package/src/serve/hub-app/list-row.ts +8 -0
  295. package/src/serve/hub-app/list-walk.ts +26 -105
  296. package/src/serve/hub-app/live-socket.ts +274 -0
  297. package/src/serve/hub-app/live-sources.ts +189 -0
  298. package/src/serve/hub-app/live-svc.ts +2 -2
  299. package/src/serve/hub-app/machine-st.ts +75 -14
  300. package/src/serve/hub-app/main-panel.css +211 -0
  301. package/src/serve/hub-app/main-panel.tsx +259 -0
  302. package/src/serve/hub-app/md.ts +4 -4
  303. package/src/serve/hub-app/media-svc.ts +5 -5
  304. package/src/serve/hub-app/media-view.tsx +13 -12
  305. package/src/serve/hub-app/messages/messages-page.tsx +8 -7
  306. package/src/serve/hub-app/messages/messages-st.ts +5 -2
  307. package/src/serve/hub-app/new-thread-st.ts +170 -0
  308. package/src/serve/hub-app/new-thread.tsx +133 -107
  309. package/src/serve/hub-app/orchestrator-line.tsx +115 -45
  310. package/src/serve/hub-app/orchestrator-places.tsx +86 -0
  311. package/src/serve/hub-app/orchestrator.css +57 -5
  312. package/src/serve/hub-app/page-keys.ts +107 -68
  313. package/src/serve/hub-app/page-reload.ts +46 -6
  314. package/src/serve/hub-app/pages-frames.tsx +40 -3
  315. package/src/serve/hub-app/pages-svc.ts +3 -1
  316. package/src/serve/hub-app/palette-st.ts +198 -43
  317. package/src/serve/hub-app/palette-view.tsx +32 -8
  318. package/src/serve/hub-app/panel-head-action.tsx +39 -0
  319. package/src/serve/hub-app/panel-head.tsx +70 -0
  320. package/src/serve/hub-app/panel-repo.ts +42 -0
  321. package/src/serve/hub-app/panel-source.ts +195 -0
  322. package/src/serve/hub-app/panel-tint.css +6 -0
  323. package/src/serve/hub-app/panel-tint.ts +23 -0
  324. package/src/serve/hub-app/panel-walk.ts +107 -0
  325. package/src/serve/hub-app/pill-row.tsx +2 -1
  326. package/src/serve/hub-app/place-path.ts +4 -0
  327. package/src/serve/hub-app/places-svc.ts +75 -0
  328. package/src/serve/hub-app/plan-view.tsx +3 -2
  329. package/src/serve/hub-app/polled.ts +11 -1
  330. package/src/serve/hub-app/presence-st.ts +66 -32
  331. package/src/serve/hub-app/processes-view.tsx +2 -2
  332. package/src/serve/hub-app/project-bar.tsx +116 -0
  333. package/src/serve/hub-app/project-list.css +20 -173
  334. package/src/serve/hub-app/project-list.tsx +30 -298
  335. package/src/serve/hub-app/projects-svc.ts +59 -32
  336. package/src/serve/hub-app/push-sign.tsx +2 -1
  337. package/src/serve/hub-app/push-svc.ts +86 -69
  338. package/src/serve/hub-app/quiet-st.ts +5 -3
  339. package/src/serve/hub-app/rail-groups.ts +144 -0
  340. package/src/serve/hub-app/reader-chips.tsx +2 -1
  341. package/src/serve/hub-app/recordings-st.ts +2 -1
  342. package/src/serve/hub-app/recordings-view.tsx +19 -47
  343. package/src/serve/hub-app/recordings.css +0 -2
  344. package/src/serve/hub-app/reflections-page.tsx +10 -6
  345. package/src/serve/hub-app/releases/releases-page.tsx +6 -5
  346. package/src/serve/hub-app/repo-sections.ts +127 -38
  347. package/src/serve/hub-app/repo-st.ts +57 -36
  348. package/src/serve/hub-app/review/advisor-bar.tsx +3 -2
  349. package/src/serve/hub-app/review/ask-proof.tsx +79 -0
  350. package/src/serve/hub-app/review/attach-view.tsx +11 -10
  351. package/src/serve/hub-app/review/box-view.ts +479 -0
  352. package/src/serve/hub-app/review/box-zoom.tsx +70 -0
  353. package/src/serve/hub-app/review/diff-view.tsx +3 -2
  354. package/src/serve/hub-app/review/doc-body.tsx +2 -1
  355. package/src/serve/hub-app/review/dock.tsx +3 -2
  356. package/src/serve/hub-app/review/draft-body.tsx +4 -3
  357. package/src/serve/hub-app/review/faces.tsx +0 -8
  358. package/src/serve/hub-app/review/group-block.tsx +8 -7
  359. package/src/serve/hub-app/review/heard-line.tsx +4 -3
  360. package/src/serve/hub-app/review/instructions-view.tsx +3 -2
  361. package/src/serve/hub-app/review/item-verdict.tsx +40 -40
  362. package/src/serve/hub-app/review/kind-states.tsx +5 -4
  363. package/src/serve/hub-app/review/kit.tsx +24 -4
  364. package/src/serve/hub-app/review/lane-bar.tsx +30 -28
  365. package/src/serve/hub-app/review/lightbox.tsx +6 -4
  366. package/src/serve/hub-app/review/live-bar.tsx +7 -6
  367. package/src/serve/hub-app/review/live-view.tsx +6 -5
  368. package/src/serve/hub-app/review/object-card.tsx +2 -1
  369. package/src/serve/hub-app/review/object-panel.tsx +11 -10
  370. package/src/serve/hub-app/review/pano-view.tsx +3 -2
  371. package/src/serve/hub-app/review/question-views.tsx +6 -5
  372. package/src/serve/hub-app/review/review-cells.tsx +21 -20
  373. package/src/serve/hub-app/review/review-host.ts +3 -0
  374. package/src/serve/hub-app/review/review-kit.ts +7 -5
  375. package/src/serve/hub-app/review/review-list.tsx +98 -52
  376. package/src/serve/hub-app/review/review-page.tsx +3 -3
  377. package/src/serve/hub-app/review/review-st.ts +70 -14
  378. package/src/serve/hub-app/review/review-thread.tsx +234 -138
  379. package/src/serve/hub-app/review/review-views.tsx +166 -191
  380. package/src/serve/hub-app/review/space3d.tsx +17 -9
  381. package/src/serve/hub-app/review/thread-close.tsx +24 -32
  382. package/src/serve/hub-app/review/thread-st.ts +39 -25
  383. package/src/serve/hub-app/review/trailer-body.tsx +5 -4
  384. package/src/serve/hub-app/review/trailer-page.tsx +18 -16
  385. package/src/serve/hub-app/review/trailer-st.ts +3 -2
  386. package/src/serve/hub-app/review/trailer-timeline.tsx +10 -9
  387. package/src/serve/hub-app/review/trailer-voices.tsx +29 -28
  388. package/src/serve/hub-app/review.css +159 -42
  389. package/src/serve/hub-app/row-acts.tsx +126 -0
  390. package/src/serve/hub-app/row-face.tsx +29 -0
  391. package/src/serve/hub-app/running-rows.tsx +142 -0
  392. package/src/serve/hub-app/running-st.ts +110 -0
  393. package/src/serve/hub-app/search-view.tsx +3 -2
  394. package/src/serve/hub-app/secrets-page.tsx +290 -0
  395. package/src/serve/hub-app/secrets-st.ts +181 -0
  396. package/src/serve/hub-app/secrets.css +65 -0
  397. package/src/serve/hub-app/section-head.tsx +3 -2
  398. package/src/serve/hub-app/session-chips.tsx +55 -0
  399. package/src/serve/hub-app/shell.ts +56 -0
  400. package/src/serve/hub-app/site/site-part.tsx +6 -5
  401. package/src/serve/hub-app/site/site-st.ts +0 -6
  402. package/src/serve/hub-app/site.css +0 -1
  403. package/src/serve/hub-app/social/calendar.tsx +7 -6
  404. package/src/serve/hub-app/social/comms-page.tsx +29 -26
  405. package/src/serve/hub-app/social/group-editor.tsx +2 -1
  406. package/src/serve/hub-app/social/kit.tsx +12 -11
  407. package/src/serve/hub-app/social/next-release.tsx +3 -2
  408. package/src/serve/hub-app/social/post-card.tsx +21 -20
  409. package/src/serve/hub-app/social/post-page.tsx +2 -1
  410. package/src/serve/hub-app/social/problems.tsx +3 -2
  411. package/src/serve/hub-app/social/social-page.tsx +29 -27
  412. package/src/serve/hub-app/social/social-st.ts +4 -2
  413. package/src/serve/hub-app/social/stage-popup.tsx +11 -10
  414. package/src/serve/hub-app/social.css +7 -5
  415. package/src/serve/hub-app/source-acts.ts +79 -0
  416. package/src/serve/hub-app/source-page.tsx +17 -0
  417. package/src/serve/hub-app/space-view.tsx +5 -4
  418. package/src/serve/hub-app/stores/stores-page.tsx +21 -19
  419. package/src/serve/hub-app/stores/stores-st.ts +1 -1
  420. package/src/serve/hub-app/stores.css +1 -1
  421. package/src/serve/hub-app/terminal-history-st.ts +112 -0
  422. package/src/serve/hub-app/terminal-keys.ts +79 -0
  423. package/src/serve/hub-app/terminal-lib.ts +110 -0
  424. package/src/serve/hub-app/terminal-links.ts +55 -0
  425. package/src/serve/hub-app/terminal-list-st.ts +304 -0
  426. package/src/serve/hub-app/terminal-log-st.ts +242 -0
  427. package/src/serve/hub-app/terminal-out.ts +135 -0
  428. package/src/serve/hub-app/terminal-pages.tsx +115 -0
  429. package/src/serve/hub-app/terminal-panel.tsx +60 -9
  430. package/src/serve/hub-app/terminal-sources.tsx +335 -0
  431. package/src/serve/hub-app/terminal-st.ts +447 -167
  432. package/src/serve/hub-app/terminal-stream.ts +233 -0
  433. package/src/serve/hub-app/terminal-tab.tsx +64 -0
  434. package/src/serve/hub-app/terminal-widths.ts +30 -0
  435. package/src/serve/hub-app/terminal.css +50 -4
  436. package/src/serve/hub-app/test-view.tsx +5 -3
  437. package/src/serve/hub-app/tests-view.tsx +16 -15
  438. package/src/serve/hub-app/theme-st.ts +5 -0
  439. package/src/serve/hub-app/thread-row.tsx +39 -31
  440. package/src/serve/hub-app/time-ago.tsx +3 -2
  441. package/src/serve/hub-app/time-view.tsx +2 -1
  442. package/src/serve/hub-app/time.css +1 -1
  443. package/src/serve/hub-app/timeline-chart.tsx +5 -4
  444. package/src/serve/hub-app/timeline-view.tsx +10 -9
  445. package/src/serve/hub-app/tips.ts +247 -0
  446. package/src/serve/hub-app/tree-build.ts +40 -8
  447. package/src/serve/hub-app/tree-svc.ts +167 -134
  448. package/src/serve/hub-app/unit-icons.ts +26 -0
  449. package/src/serve/hub-app/url-address.ts +154 -0
  450. package/src/serve/hub-app/url-faces.ts +88 -0
  451. package/src/serve/hub-app/url-forms.tsx +183 -0
  452. package/src/serve/hub-app/urls-svc.ts +167 -5
  453. package/src/serve/hub-app/urls-view.tsx +56 -20
  454. package/src/serve/hub-app/urls.css +26 -0
  455. package/src/serve/hub-app/vault-view.tsx +5 -4
  456. package/src/serve/hub-app/veille/veille-page.tsx +34 -33
  457. package/src/serve/hub-app/veille/veille-st.ts +6 -3
  458. package/src/serve/hub-app/view-layout.css +3 -3
  459. package/src/serve/hub-app/when-view.tsx +5 -4
  460. package/src/serve/hub-app/wikis-view.tsx +6 -5
  461. package/src/serve/hub-app/words.tsx +9 -2
  462. package/src/serve/hub-runtime.ts +3 -2
  463. package/src/serve/orchestrator-host.ts +58 -0
  464. package/src/serve/page-live.ts +147 -0
  465. package/src/serve/project-gutter-route.ts +63 -2
  466. package/src/serve/read-worker.ts +7 -2
  467. package/src/serve/runs-stamp.ts +33 -0
  468. package/src/serve/secrets-read.ts +156 -0
  469. package/src/serve/serve-hub.ts +71 -22
  470. package/src/serve/terminal-claudes.ts +185 -0
  471. package/src/serve/terminal-guard.ts +10 -5
  472. package/src/serve/terminal-host.ts +517 -0
  473. package/src/serve/terminal-record.ts +104 -0
  474. package/src/serve/terminal-route.ts +466 -103
  475. package/src/serve/terminal-shells.ts +3 -0
  476. package/src/serve/terminal-watch.ts +102 -0
  477. package/src/shipkit-files.ts +9 -4
  478. package/src/shot/client.ts +4 -9
  479. package/src/shot/shooter.ts +2 -4
  480. package/src/shot/shot-ask.ts +2 -7
  481. package/src/shot/shot-theme.ts +6 -17
  482. package/src/social/routes.ts +2 -2
  483. package/src/social/writes.ts +3 -0
  484. package/src/suite/test-units.ts +6 -2
  485. package/src/trailer/sound/eleven.ts +1 -0
  486. package/src/urls/added.ts +111 -0
  487. package/src/urls/icons.ts +294 -0
  488. package/src/urls/places.ts +139 -0
  489. package/src/urls/routes.ts +17 -7
  490. package/src/urls/rows.ts +48 -15
  491. package/src/urls/unit.ts +57 -3
  492. package/src/urls/write-routes.ts +207 -0
  493. package/src/vault/vault-destroy.ts +2 -1
  494. package/src/vault/vault-import.ts +4 -11
  495. package/src/vault/vault-restore.ts +3 -2
  496. package/src/veille/chrome.ts +18 -3
  497. package/src/veille/identity.ts +6 -0
  498. package/src/view3d/cam.ts +30 -46
  499. package/src/view3d/lib.ts +20 -2
  500. package/src/view3d/viewer.ts +62 -88
  501. package/src/wiki/agent-paths.ts +2 -1
  502. package/src/orchestrator/deliver.ts +0 -81
  503. package/src/orchestrator/drill.ts +0 -129
  504. package/src/orchestrator/keeper.ts +0 -332
  505. package/src/orchestrator/pm.ts +0 -20
  506. package/src/orchestrator/state.ts +0 -92
  507. package/src/orchestrator/switch.ts +0 -86
  508. package/src/orchestrator/tmux.ts +0 -82
  509. package/src/serve/hub-app/rail-fly.tsx +0 -95
  510. package/src/serve/hub-app/side-lists.ts +0 -72
  511. package/src/serve/hub-app/sidebar.tsx +0 -62
  512. package/src/serve/hub-app/tree-row.tsx +0 -125
@@ -1,13 +1,21 @@
1
1
  // one web app window on macOS: its own app, so the dock and cmd-tab show its
2
- // own icon, never a second browser. The same source is the shipkit window and
3
- // every per-process app (home/gui-app.ts builds both with swiftc, no Xcode
4
- // project): the bundle's Info.plist names the app (CFBundleName) and the url
5
- // a bare launch opens (ShipkitStartURL). One WKWebView per window; every
6
- // `open -a <app> <url>` opens one more window, cmd-n too. A link to another
7
- // site opens in the default browser, and a download lands in ~/Downloads.
8
- // The shipkit app alone wears the Dock badge of the threads waiting for
9
- // the owner and notifies each new one, as its page posts them (`shipkit`
10
- // message handler, serve/hub-app/app-bridge.ts).
2
+ // own icon, never a second browser. The same source is the shipkit window,
3
+ // every per-project app and every per-process app (home/gui-app.ts builds them
4
+ // with swiftc, no Xcode project): the bundle's Info.plist names the app
5
+ // (CFBundleName), the url a bare launch opens (ShipkitStartURL), its mode
6
+ // (ShipkitMode: home, project, process) and a project's repo (ShipkitRepo).
7
+ // One WKWebView per window; every `open -a <app> <url>` opens one more window,
8
+ // cmd-n too in a process's app. A project app is ONE window of native tabs instead: tab 1 its hub,
9
+ // pinned and alone at launch, then each entry of the hub he opens beside it (cmd-t,
10
+ // a new window a page asks) and each url opened from the hub (`road` says where a
11
+ // link goes). Its tab bar shows with one tab too, so a tab pulled out into a window
12
+ // of its own drags back, and the Window menu merges every window into one. In the
13
+ // home's app and a project's, cmd-n asks the hub's page for its new thread popup.
14
+ // A link to another site opens in the default browser, and a
15
+ // download lands in ~/Downloads. The home app wears the Dock badge of the
16
+ // threads waiting for the owner and notifies each new one; a project app wears
17
+ // its repo's count alone, and stays quiet: both as their page posts them
18
+ // (`shipkit` message handler, serve/hub-app/app-bridge.ts).
11
19
  import AppKit
12
20
  import UserNotifications
13
21
  import WebKit
@@ -15,8 +23,86 @@ import WebKit
15
23
  let info = Bundle.main.infoDictionary ?? [:]
16
24
  let appName = (info["CFBundleName"] as? String) ?? "shipkit"
17
25
  let startURL = URL(string: (info["ShipkitStartURL"] as? String) ?? "") ?? URL(string: "http://127.0.0.1:4799/")!
18
- /** the shipkit app itself (home/gui-app.ts BUNDLE_ID), never a process app */
19
- let isShipkit = Bundle.main.bundleIdentifier == "dev.shipkit.gui"
26
+ /** what this app is; a bundle built before the key: the shipkit app by its id (home/gui-app.ts BUNDLE_ID), else a process's */
27
+ let mode = (info["ShipkitMode"] as? String) ?? (Bundle.main.bundleIdentifier == "dev.shipkit.gui" ? "home" : "process")
28
+ /** the shipkit app itself: the house's badge and the notifications */
29
+ let isShipkit = mode == "home"
30
+ /** a project app's repo: its badge counts that repo's threads alone */
31
+ let projectRepo: String? = mode == "project" ? info["ShipkitRepo"] as? String : nil
32
+ /** the apps that wear a badge: the home's stays running with no window to keep it live, a project app's lives with
33
+ * its windows (closing the last one quits it: one hub page alive per app open, never a hidden one) */
34
+ let hasBadge = isShipkit || projectRepo != nil
35
+ /** a project app: one window, every page a native tab of it */
36
+ let tabbed = projectRepo != nil
37
+ /** a self test runs (`--self-test-…`): nothing it loads is kept on disk, and no window, sheet or alert of it ever
38
+ * reaches a screen. No flag brings a visible self test back: its windows are real and never ordered in */
39
+ let selfTesting = CommandLine.arguments.contains { $0.hasPrefix("--self-test") }
40
+
41
+ /** the windows the window server has on a screen: this process's, and every process's (the control: the menu bar and
42
+ * the Dock are always there, so a count of none means the server answered nothing) */
43
+ func windowsOnScreen() -> (own: Int, all: Int) {
44
+ let pid = ProcessInfo.processInfo.processIdentifier
45
+ let all = (CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]]) ?? []
46
+ return (all.filter { ($0[kCGWindowOwnerPID as String] as? Int32) == pid }.count, all.count)
47
+ }
48
+ /** the most windows a self test had on a screen at once, as the window server counted them through its run */
49
+ var seenOnScreen = 0
50
+
51
+ /** the end of a self test: its code, and never 0 once the window server saw one window of it on a screen, or gave
52
+ * no list to count in */
53
+ func finish(_ code: Int32) -> Never {
54
+ let now = windowsOnScreen()
55
+ seenOnScreen = max(seenOnScreen, now.own)
56
+ print("windows-on-screen=\(seenOnScreen) of \(now.all > 0 ? "some" : "none") the window server lists")
57
+ if seenOnScreen > 0 { print("refused: a self test put a window on the screen") }
58
+ if now.all == 0 { print("refused: the window server listed no window at all, so the count proves nothing") }
59
+ exit(seenOnScreen > 0 || now.all == 0 ? 1 : code)
60
+ }
61
+
62
+ /** a self test asked for a window on the screen: said once, and nothing shows */
63
+ var refusedScreen = false
64
+ func refuseScreen() {
65
+ if refusedScreen { return }
66
+ refusedScreen = true
67
+ FileHandle.standardError.write("shipkit: a self test shows no window: an order to the screen was refused\n".data(using: .utf8)!)
68
+ }
69
+
70
+ /** the repo a page of the hub belongs to (`/r/<repo>/…`), nil for any other page */
71
+ func repoOf(_ url: URL) -> String? {
72
+ let parts = url.path.split(separator: "/", omittingEmptySubsequences: true)
73
+ return parts.count >= 2 && parts[0] == "r" ? String(parts[1]).removingPercentEncoding : nil
74
+ }
75
+
76
+ /** the build a bundle carries (home/gui-app.ts writes it): the running copy compares it with its bundle's on disk */
77
+ func stampOnDisk() -> String? { try? String(contentsOfFile: Bundle.main.bundlePath + "/Contents/Resources/stamp", encoding: .utf8) }
78
+ let launchedStamp = stampOnDisk()
79
+
80
+ /** a #rrggbb as a colour, nil for anything else */
81
+ func colorOf(_ hex: String?) -> NSColor? {
82
+ guard let hex, hex.count == 7, hex.hasPrefix("#"), let n = Int(hex.dropFirst(), radix: 16) else { return nil }
83
+ return NSColor(srgbRed: CGFloat((n >> 16) & 255) / 255, green: CGFloat((n >> 8) & 255) / 255, blue: CGFloat(n & 255) / 255, alpha: 1)
84
+ }
85
+ /** the repo's window colour and the text that reads on it (home/gui-app.ts writes both); none: the system's chrome */
86
+ let tint = colorOf(info["ShipkitTint"] as? String)
87
+ let tintText = colorOf(info["ShipkitTintText"] as? String)
88
+
89
+ /** a window's chrome in the repo's colour, as Peacock tints a VSCode window: the title bar and the tab bar under it take
90
+ * the colour, and the appearance follows the text that reads on it (light text: the dark appearance) */
91
+ func paint(_ win: NSWindow, _ color: NSColor?, text: NSColor?) {
92
+ guard let color else { return }
93
+ win.titlebarAppearsTransparent = true
94
+ win.backgroundColor = color
95
+ let light = (text?.usingColorSpace(.sRGB)?.brightnessComponent ?? 1) > 0.5
96
+ win.appearance = NSAppearance(named: light ? .darkAqua : .aqua)
97
+ }
98
+
99
+ /** the count a page's post puts on the badge: the house's, or one repo's (0 when the page names none); nil when the
100
+ * post carries no count */
101
+ func badgeCount(_ body: [String: Any], repo: String?) -> Int? {
102
+ guard let total = body["waiting"] as? Int else { return nil }
103
+ guard let repo else { return total }
104
+ return ((body["repos"] as? [String: Any])?[repo] as? Int) ?? 0
105
+ }
20
106
 
21
107
  /** a thread that started waiting, as the page posts it */
22
108
  struct WaitingThread {
@@ -55,6 +141,123 @@ func stays(_ url: URL) -> Bool {
55
141
  url.host == "127.0.0.1" || url.host == "localhost" || url.host == startURL.host
56
142
  }
57
143
 
144
+ /** a page of the hub itself: the start url's host and port */
145
+ func isHub(_ url: URL) -> Bool { url.host == startURL.host && url.port == startURL.port }
146
+
147
+ /** the site a host belongs to: the machine for every loopback name, the last two labels of a dotted name
148
+ * (app.example.com and auth.example.com are one site, so a sign in on the second stays in the tab), else the host.
149
+ * No public suffix list: two sites under a two label suffix (co.uk) read as one, and such a link stays in the tab */
150
+ func siteOf(_ url: URL?) -> String? {
151
+ guard let host = url?.host?.lowercased() else { return nil }
152
+ if host == "127.0.0.1" || host == "localhost" || host.hasSuffix(".localhost") { return "this machine" }
153
+ let labels = host.split(separator: ".")
154
+ if labels.count < 3 || labels.allSatisfy({ Int($0) != nil }) { return host }
155
+ return labels.suffix(2).joined(separator: ".")
156
+ }
157
+
158
+ /** scheme, host and port: a url the project declares covers every page of its origin */
159
+ func originOf(_ url: URL) -> String { "\(url.scheme?.lowercased() ?? "")://\(url.host?.lowercased() ?? ""):\(url.port ?? (url.scheme?.lowercased() == "https" ? 443 : 80))" }
160
+
161
+ /** what a tab is found by: its address with no closing slash. A page of the hub keeps its fragment, the entry it
162
+ * shows (`#page:src:terminals:<id>`): two entries are two tabs. Any other page loses it */
163
+ func tabKey(_ url: URL) -> String {
164
+ var c = URLComponents(url: url, resolvingAgainstBaseURL: true)
165
+ if !isHub(url) || c?.fragment?.isEmpty == true { c?.fragment = nil }
166
+ let s = c?.string ?? url.absoluteString
167
+ return s.hasSuffix("/") ? String(s.dropLast()) : s
168
+ }
169
+
170
+ /** an app whose pages are the hub's: the home's and a project's. A process's app shows a site of its own */
171
+ let hubApp = isShipkit || tabbed
172
+
173
+ /** an origin as a page's script reads it (`location.origin`): no port where it is the scheme's own */
174
+ func pageOrigin(_ url: URL) -> String {
175
+ let scheme = url.scheme?.lowercased() ?? "http"
176
+ let port = url.port.flatMap { $0 == (scheme == "https" ? 443 : 80) ? nil : ":\($0)" } ?? ""
177
+ return "\(scheme)://\(url.host?.lowercased() ?? "")\(port)"
178
+ }
179
+
180
+ /** a string as a script's literal */
181
+ func jsString(_ s: String) -> String {
182
+ guard let data = try? JSONSerialization.data(withJSONObject: [s]), let json = String(data: data, encoding: .utf8) else { return "\"\"" }
183
+ return String(json.dropFirst().dropLast())
184
+ }
185
+
186
+ /** what a framed site says of its address to the hub page that frames it (serve/hub-app/url-address.ts hears it), so
187
+ * a url's page comes back where he was. WebKit puts a user script in every frame of a web view, with no choice of
188
+ * origin, so this one does nothing by itself: one listener, in a frame right under the top page. It wakes only when
189
+ * the page of `hub`, its parent, asks, and the page posts its ask to the origin of the url it declared and to no
190
+ * other, so a frame of any other origin never hears it. Awake it reads `location.href`, nothing else of the page,
191
+ * and posts it to `hub` alone: at the ask, on a fragment move, a history move and a router's push */
192
+ func reporterScript(hub: String) -> String {
193
+ """
194
+ (() => {
195
+ if (window === top || parent !== top) return
196
+ const HUB = \(jsString(hub))
197
+ let on = false
198
+ const say = () => { try { parent.postMessage({ skAddress: location.href }, HUB) } catch (e) {} }
199
+ addEventListener('message', (e) => {
200
+ if (e.source !== parent || e.origin !== HUB || e.data == null || e.data.skAddressAsk !== true) return
201
+ if (!on) {
202
+ on = true
203
+ for (const t of ['hashchange', 'popstate']) addEventListener(t, say)
204
+ for (const k of ['pushState', 'replaceState']) {
205
+ const f = history[k]
206
+ history[k] = function () { const r = f.apply(this, arguments); say(); return r }
207
+ }
208
+ }
209
+ say()
210
+ })
211
+ })()
212
+ """
213
+ }
214
+
215
+ /** the tab command with a digit selects among `count`, as a browser: 1 to 8 that tab, 9 the last; nil: there is none */
216
+ func tabIndex(digit: Int, count: Int) -> Int? {
217
+ if count < 1 { return nil }
218
+ if digit == 9 { return count - 1 }
219
+ return digit >= 1 && digit <= count ? digit - 1 : nil
220
+ }
221
+
222
+ /** command with 1 to 9 as menu keys: a project app's tabs alone. The home's pages take them as repo n, and a process
223
+ * app's page keeps them */
224
+ func tabDigits(_ mode: String) -> [Int] { mode == "project" ? Array(1...9) : [] }
225
+
226
+ /** where a main frame's navigation goes in a project app */
227
+ enum Road: Equatable {
228
+ /** in the page that asked */
229
+ case here
230
+ /** a tab of this window: the one open on it, else a new one */
231
+ case tab
232
+ /** a tab when the project declares the url (its `sk urls` rows, its global processes among them), else outside */
233
+ case declared
234
+ /** the default browser, or the app of the url's scheme */
235
+ case outside
236
+ /** another repo's own app */
237
+ case app(String)
238
+ }
239
+
240
+ /** `from`: the page that asks (a tab's first load asks from its own address, or from none); `home`: the address the tab was opened on; `new`: it asks
241
+ * a new window (target=_blank, window.open); `click`: a link clicked. The hub's pages never turn into another site:
242
+ * the machine's other servers and the project's urls become tabs, any other site leaves. A tab of another site keeps
243
+ * its site (the one it was opened on, the one it shows), and a link out of it leaves */
244
+ func road(to url: URL, from: URL?, home: URL?, new: Bool, click: Bool, repo: String?) -> Road {
245
+ switch url.scheme?.lowercased() {
246
+ case "http", "https": break
247
+ case nil, "about", "data", "blob", "javascript", "file": return .here
248
+ default: return click || new ? .outside : .here
249
+ }
250
+ if isHub(url) {
251
+ if let own = repo, let other = repoOf(url), other != own { return .app(other) }
252
+ return new ? .tab : .here
253
+ }
254
+ guard let from else { return .here }
255
+ if isHub(from) { return siteOf(url) == "this machine" ? .tab : .declared }
256
+ let site = siteOf(url)
257
+ if site == siteOf(from) || site == siteOf(home) { return new ? .tab : .here }
258
+ return click || new ? .outside : .here
259
+ }
260
+
58
261
  /** a url a link or window.open leads to that leaves the app for the default browser or its own app: a web page of
59
262
  * another host, a mail address, any other app's scheme; the page's own data, blob and about urls stay */
60
263
  func leaves(_ url: URL) -> Bool {
@@ -71,14 +274,89 @@ func leaves(_ url: URL) -> Bool {
71
274
  // a window whose unhandled key makes no system beep: a key nobody took (the page, the menus) ends in the window's
72
275
  // noResponder, which beeps; the pane marks it in a corner instead
73
276
  final class QuietWindow: NSWindow {
277
+ // every window of the app is this one, so a self test's never reaches a screen: each order in is refused
278
+ override func order(_ place: NSWindow.OrderingMode, relativeTo other: Int) { if selfTesting && place != .out { return refuseScreen() }; super.order(place, relativeTo: other) }
279
+ override func makeKeyAndOrderFront(_ sender: Any?) { if selfTesting { return refuseScreen() }; super.makeKeyAndOrderFront(sender) }
280
+ override func orderFront(_ sender: Any?) { if selfTesting { return refuseScreen() }; super.orderFront(sender) }
281
+ override func orderFrontRegardless() { if selfTesting { return refuseScreen() }; super.orderFrontRegardless() }
282
+
283
+ // AppKit's performClose presses the window's red button, which closes every tab of a project app: a close asked
284
+ // of one tab this way (the tab bar's « close other tabs », a script) is that tab's alone
285
+ override func performClose(_ sender: Any?) {
286
+ if tabbed, let d = delegate as? Delegate { return d.closeTab(of: self) }
287
+ super.performClose(sender)
288
+ }
289
+
74
290
  override func noResponder(for eventSelector: Selector) {
75
291
  if eventSelector == #selector(NSResponder.keyDown(with:)), let pane = contentView as? Pane { return pane.blink() }
76
292
  super.noResponder(for: eventSelector)
77
293
  }
78
294
  }
79
295
 
296
+ /** a window's web view. In a project app the context menu's « open link in new window » opens the link as a tab of
297
+ * this window, whatever its site: the one road by which a page of another site gets a tab here */
298
+ final class Web: WKWebView {
299
+ static let linkItem = "WKMenuItemIdentifierOpenLinkInNewWindow"
300
+ /** the next new window this page asks is a tab here; the menu's item sets it for its own ask alone */
301
+ var tabNext = false
302
+ private var forward: (target: AnyObject?, action: Selector?) = (nil, nil)
303
+
304
+ override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {
305
+ super.willOpenMenu(menu, with: event)
306
+ guard tabbed else { return }
307
+ for item in menu.items where item.identifier?.rawValue == Web.linkItem {
308
+ item.title = "Open in a Tab Here"
309
+ forward = (item.target, item.action)
310
+ item.target = self
311
+ item.action = #selector(openLinkInTab(_:))
312
+ }
313
+ }
314
+
315
+ @objc func openLinkInTab(_ sender: NSMenuItem) {
316
+ tabNext = true
317
+ if let action = forward.action { NSApp.sendAction(action, to: forward.target, from: sender) }
318
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.tabNext = false }
319
+ }
320
+ }
321
+
322
+ /** the login chips a page's tab note names (serve/hub-app/app-bridge.ts TabChips): the url's id and its logins'
323
+ * labels by position, at most 8; nil when it names none */
324
+ func chipsOf(_ body: [String: Any]) -> (urlId: String, logins: [String])? {
325
+ guard let id = body["urlId"] as? String, !id.isEmpty, id.count <= 120, let logins = body["logins"] as? [String], !logins.isEmpty else { return nil }
326
+ return (id, logins.prefix(8).map { String($0.prefix(60)) })
327
+ }
328
+
329
+ /** one chip of a url's tab title bar: a field of a login, by the url's id and the login's position, which the hub's
330
+ * copy route takes. Its title is a word, never a value */
331
+ final class ChipButton: NSButton {
332
+ var urlId = "", login = 0, label = "", field = ""
333
+ private var back: DispatchWorkItem?
334
+
335
+ /** `what` on the chip for `s` seconds, `why` its tip meanwhile, then its own field and tip again */
336
+ func say(_ what: String, why: String? = nil, for s: Double = 1.6) {
337
+ back?.cancel()
338
+ title = what
339
+ toolTip = why ?? "copy the \(field) of \(label)"
340
+ let w = DispatchWorkItem { [weak self] in
341
+ guard let self else { return }
342
+ self.title = self.field
343
+ self.toolTip = "copy the \(self.field) of \(self.label)"
344
+ }
345
+ back = w
346
+ DispatchQueue.main.asyncAfter(deadline: .now() + s, execute: w)
347
+ }
348
+ }
349
+
80
350
  final class Pane: NSView, NSSearchFieldDelegate {
81
- let web: WKWebView
351
+ private(set) var web: WKWebView
352
+ /** the address the window was opened on: a project app finds a tab by it */
353
+ var opened: URL?
354
+ /** a project app's hub, its tab 1: its own close is refused, and it closes last */
355
+ var pinned = false
356
+ /** the name the tab was opened under, when a page of the hub gave one: a url's, where the site's own title is
357
+ * not the name the project gave it. It stays as he walks the site */
358
+ var name: String? { didSet { retitle() } }
359
+ private var titleWatch: NSKeyValueObservation?
82
360
  let bar = NSStackView()
83
361
  let field = NSSearchField()
84
362
  let status = NSTextField(labelWithString: "")
@@ -115,6 +393,31 @@ final class Pane: NSView, NSSearchFieldDelegate {
115
393
  mark.layer?.cornerRadius = 3
116
394
  mark.alphaValue = 0
117
395
  addSubview(mark)
396
+ // the page's title names the window and its tab, so cmd-tab, the window menu and the tab bar tell pages apart;
397
+ // a page that renames itself with no load (the hub's router) renames them too
398
+ watchTitle()
399
+ }
400
+
401
+ private func watchTitle() {
402
+ titleWatch = web.observe(\.title, options: [.new]) { [weak self] _, _ in self?.retitle() }
403
+ }
404
+
405
+ /** the window's and the tab's title: the name it was opened under, else its page's; a page with none leaves it */
406
+ func retitle() {
407
+ if let name { window?.title = name } else if let t = web.title, !t.isEmpty { window?.title = t }
408
+ }
409
+
410
+ /** another web view in this one's place: the window, its tab, its pin and its find bar stay, the keys follow */
411
+ func swap(to new: WKWebView) {
412
+ let old = web
413
+ let keyed = (window?.firstResponder as? NSView)?.isDescendant(of: old) == true
414
+ addSubview(new, positioned: .below, relativeTo: bar)
415
+ old.removeFromSuperview()
416
+ web = new
417
+ watchTitle()
418
+ retitle()
419
+ needsLayout = true
420
+ if keyed { window?.makeFirstResponder(new) }
118
421
  }
119
422
 
120
423
  func blink() {
@@ -214,29 +517,27 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
214
517
  if CommandLine.arguments.contains("--self-test-panels") { return selfTestPanels() }
215
518
  if CommandLine.arguments.contains("--self-test-download") { return selfTestDownload() }
216
519
  if CommandLine.arguments.contains("--self-test-badge") { return selfTestBadge() }
217
- if CommandLine.arguments.contains("--self-test-quiet-key") { return selfTestQuietKey() }
520
+ if CommandLine.arguments.contains("--self-test-reload") { return selfTestReload() }
218
521
  if CommandLine.arguments.contains("--self-test-tabs") { return selfTestTabs() }
522
+ if let i = CommandLine.arguments.firstIndex(of: "--self-test-windows") { return selfTestWindows(to: i + 1 < CommandLine.arguments.count ? CommandLine.arguments[i + 1] : nil) }
219
523
  if CommandLine.arguments.contains("--self-test-links") { return selfTestLinks() }
524
+ if CommandLine.arguments.contains("--self-test-address") { return selfTestAddress() }
525
+ if let i = CommandLine.arguments.firstIndex(of: "--self-test-chrome"), i + 1 < CommandLine.arguments.count { return selfTestChrome(to: CommandLine.arguments[i + 1], titles: Array(CommandLine.arguments.dropFirst(i + 2))) }
526
+ if let i = CommandLine.arguments.firstIndex(of: "--self-test-chips") { return selfTestChips(to: i + 1 < CommandLine.arguments.count ? CommandLine.arguments[i + 1] : nil) }
220
527
  buildMenu()
528
+ watchBuild()
221
529
  // the system asks the owner once; refused, the badge still counts and each notification says why it did not show
222
530
  if isShipkit {
223
531
  UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { ok, err in
224
532
  if !ok { NSLog("shipkit: notifications are off for this app (System Settings, Notifications, shipkit)\(err.map { ": \($0.localizedDescription)" } ?? "")") }
225
533
  }
226
- // `--background`: running with no window from the start, the badge live, as after the last window closed
227
- if CommandLine.arguments.contains("--background") {
228
- opened = true
229
- keep(home: startURL)
230
- }
231
534
  }
232
- // esc closes the find bar of the key window, and reaches the page otherwise
233
- NSEvent.addLocalMonitorForEvents(matching: .keyDown) { e in
234
- if e.keyCode == 53, let pane = self.keyPane(), pane.isFindBarVisible {
235
- pane.hideFind()
236
- return nil
237
- }
238
- return e
535
+ // `--background`: running with no window from the start, the badge live, as after the last window closed
536
+ if isShipkit && CommandLine.arguments.contains("--background") {
537
+ opened = true
538
+ keep(home: startURL)
239
539
  }
540
+ watchKeys()
240
541
  // an open event may deliver the url right after launch: wait for it
241
542
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
242
543
  if !self.opened {
@@ -250,8 +551,8 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
250
551
  for u in urls { open(u) }
251
552
  }
252
553
 
253
- // the shipkit app stays running with no window, as a mail or chat app does, so its badge stays live; Quit ends it
254
- func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool { !isShipkit }
554
+ // the home app stays running with no window, as a mail or chat app does, so its badge stays live; Quit ends it
555
+ func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool { !isShipkit && !selfTesting }
255
556
 
256
557
  func applicationShouldHandleReopen(_ app: NSApplication, hasVisibleWindows: Bool) -> Bool {
257
558
  if !hasVisibleWindows { open(startURL) }
@@ -260,8 +561,307 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
260
561
 
261
562
  func keyPane() -> Pane? { NSApp.keyWindow?.contentView as? Pane }
262
563
 
564
+ /** the digit row's physical keys, 1 to 9: an AZERTY keyboard types `&` to `ç` on them, and the tab is the same */
565
+ static let digitKeys: [UInt16: Int] = [18: 1, 19: 2, 20: 3, 21: 4, 23: 5, 22: 6, 26: 7, 28: 8, 25: 9]
566
+
567
+ /** the keys the app takes before the page: esc closes the find bar of the key window; command and shift with the
568
+ * two keys right of P (their physical keys), or command with page up or page down, step the window's tabs; in a
569
+ * project app command with a key of the digit row (its physical key) selects that tab, command with t opens the
570
+ * hub's entry in a tab, command with w closes the tab, and with shift the window; in an app of the hub's pages
571
+ * command with n asks the new thread popup, a key no page of the hub reads. Every other key reaches the page first, a
572
+ * terminal's among them (control keys, option, esc, shift with return, command with c, v or k), and a menu
573
+ * takes one only when the page left it. True: taken */
574
+ func takes(_ e: NSEvent) -> Bool {
575
+ let mods = e.modifierFlags.intersection([.command, .shift, .option, .control])
576
+ if e.keyCode == 53, let pane = keyPane(), pane.isFindBarVisible {
577
+ pane.hideFind()
578
+ return true
579
+ }
580
+ let step = mods == [.command, .shift] ? (e.keyCode == 30 ? 1 : e.keyCode == 33 ? -1 : 0) : mods == [.command] ? (e.keyCode == 121 ? 1 : e.keyCode == 116 ? -1 : 0) : 0
581
+ if step != 0 {
582
+ stepTab(of: NSApp.keyWindow ?? NSApp.mainWindow ?? windows.first, by: step)
583
+ return true
584
+ }
585
+ if mods == [.command], let n = Delegate.digitKeys[e.keyCode], tabDigits(mode).contains(n) {
586
+ selectTab(digit: n)
587
+ return true
588
+ }
589
+ if tabbed, let c = e.charactersIgnoringModifiers?.lowercased(), mods == [.command] && (c == "t" || c == "w") || mods == [.command, .shift] && c == "w" {
590
+ if c == "t" { entryTab(nil) } else if mods.contains(.shift) { closeEveryTab(nil) } else { closeTab(nil) }
591
+ return true
592
+ }
593
+ if hubApp, mods == [.command], e.charactersIgnoringModifiers?.lowercased() == "n" {
594
+ newThread(nil)
595
+ return true
596
+ }
597
+ if hubApp, mods == [.command, .shift], e.charactersIgnoringModifiers?.lowercased() == "n" {
598
+ if tabbed { projectWindow(nil) } else { newWindow(nil) }
599
+ return true
600
+ }
601
+ return false
602
+ }
603
+
604
+ func watchKeys() {
605
+ NSEvent.addLocalMonitorForEvents(matching: .keyDown) { e in self.takes(e) ? nil : e }
606
+ }
607
+
608
+ // one more window on the page shown; in a project app one more tab on it
263
609
  @objc func newWindow(_ sender: Any?) {
264
- open(keyPane()?.web.url ?? startURL)
610
+ open(keyPane()?.web.url ?? startURL, again: true)
611
+ }
612
+
613
+ /** shift command n, a project app's: one more window of the project, its own and never a tab of the one in front,
614
+ * its first tab the hub's start page, not pinned: the window that holds the pinned hub stays the project's */
615
+ @objc func projectWindow(_ sender: Any?) {
616
+ guard !windows.isEmpty else { return open(startURL) }
617
+ let w = makeWindow(startURL, alone: true)
618
+ // macOS puts a window of preferred tabbing, as it first comes on a screen, into a window of its identifier
619
+ w.tabbingMode = .disallowed
620
+ show(w)
621
+ w.tabbingMode = .preferred
622
+ settleTabs()
623
+ }
624
+
625
+ /** the tab beside the hub's that is open on this address. A page of the hub is found by the address it shows now,
626
+ * its entry included, since a hub page walks from entry to entry; the hub's own tab walks them all and is never
627
+ * one of them. Any other page is found by the address it was opened on, or shows */
628
+ func tab(on url: URL) -> NSWindow? {
629
+ let key = tabKey(url)
630
+ return windows.first { w in
631
+ guard let pane = w.contentView as? Pane, !pane.pinned else { return false }
632
+ if isHub(url) { return (pane.web.url ?? pane.opened).map(tabKey) == key }
633
+ return pane.opened.map(tabKey) == key || pane.web.url.map(tabKey) == key
634
+ }
635
+ }
636
+
637
+ /** a project app's hub tab, the one pinned */
638
+ var hubTab: NSWindow? { windows.first(where: isPinned) }
639
+
640
+ /** the app's window in front: the key one when it is a window of pages (a panel or a sheet is none) */
641
+ var frontWindow: NSWindow? { NSApp.keyWindow.flatMap { k in windows.first { $0 === k } } }
642
+
643
+ /** the tabs of a window in their order: the key window's, else the project window's */
644
+ func tabs(of w: NSWindow?) -> [NSWindow] {
645
+ guard let w = w ?? windows.first else { return [] }
646
+ return w.tabGroup?.windows ?? [w]
647
+ }
648
+
649
+ /** the one place a window reaches the screen, in front. A self test never shows one */
650
+ func onScreen(_ w: NSWindow) {
651
+ if selfTesting { return }
652
+ if w.isMiniaturized { w.deminiaturize(nil) }
653
+ w.makeKeyAndOrderFront(nil)
654
+ NSApp.activate(ignoringOtherApps: true)
655
+ }
656
+
657
+ /** a window, or a project app's tab, in front */
658
+ func show(_ w: NSWindow) {
659
+ w.tabGroup?.selectedWindow = w
660
+ onScreen(w)
661
+ }
662
+
663
+ /** the one place an alert reaches the screen: a sheet on `win`, a modal with none; `done` hears its button. A
664
+ * self test shows none: `onPanel` answers it, and with nobody to answer it is said on stderr and cancelled */
665
+ func present(_ alert: NSAlert, on win: NSWindow? = nil, done: ((NSApplication.ModalResponse) -> Void)? = nil) {
666
+ if selfTesting {
667
+ // laid out as it would show, so its buttons and its field are the ones the owner would get
668
+ alert.layout()
669
+ if let onPanel { return onPanel(alert) { done?($0) } }
670
+ FileHandle.standardError.write("shipkit: an alert a self test does not show: \(alert.messageText): \(alert.informativeText)\n".data(using: .utf8)!)
671
+ done?(.cancel)
672
+ return
673
+ }
674
+ if let win { alert.beginSheetModal(for: win) { done?($0) } } else {
675
+ let r = alert.runModal()
676
+ done?(r)
677
+ }
678
+ }
679
+
680
+ /** command with t: the entry the hub's tab shows (its address: a terminal, a Claude session, a process, a url,
681
+ * any page of the main panel) in a tab of its own, so the hub walks on and the entry stays; the tab already open
682
+ * on that entry is shown, never a second one */
683
+ @objc func entryTab(_ sender: Any?) {
684
+ guard let pane = hubTab?.contentView as? Pane else { return }
685
+ // an entry whose tab is no page of the hub's shell (a url's site, a terminal alone): what its page said
686
+ if let e = entries[ObjectIdentifier(pane.web)] {
687
+ if let name = e.name { tabNames[tabKey(e.url)] = name }
688
+ return asksWindow(e.url, from: pane.web)
689
+ }
690
+ openTab(pane.web.url ?? startURL)
691
+ }
692
+
693
+ /** a page of a project app asks a new window on an address (window.open, target=_blank with no policy asked,
694
+ * command with t on an entry that names one): it goes down its road, a tab of the hub's own else */
695
+ func asksWindow(_ url: URL, from web: WKWebView) {
696
+ if !reroutes(url, from: web, new: true, click: false) { open(url, again: true) }
697
+ }
698
+
699
+ /** the name a hub page gave the tab it asks next, by that tab's address (serve/hub-app/panel-repo.ts openTab) */
700
+ var tabNames: [String: String] = [:]
701
+ /** the login chips the same note names for that tab, a url's (wearChips) */
702
+ var tabChips: [String: (urlId: String, logins: [String])] = [:]
703
+ /** what command with t opens for the entry a hub page shows, by its web view, where that is not the page
704
+ * itself (serve/hub-app/panel-source.ts, tab) */
705
+ var entries: [ObjectIdentifier: (url: URL, name: String?)] = [:]
706
+
707
+ /** the tab a hub page named and opened before on this site: a url's row asked again shows its tab, where he
708
+ * left it, never a second one */
709
+ func tab(named url: URL) -> NSWindow? {
710
+ guard !isHub(url), let name = tabNames[tabKey(url)] else { return nil }
711
+ return windows.first { w in
712
+ guard let pane = w.contentView as? Pane, pane.name == name else { return false }
713
+ return (pane.web.url ?? pane.opened).map(originOf) == originOf(url)
714
+ }
715
+ }
716
+
717
+ // command with a digit, as a browser: 1 to 8 that tab, 9 the last. The item is always on, so a digit with no tab
718
+ // is taken and nothing beeps
719
+ @objc func selectTab(_ sender: NSMenuItem) { selectTab(digit: sender.tag) }
720
+
721
+ func selectTab(digit: Int) {
722
+ let all = tabs(of: NSApp.keyWindow)
723
+ if let i = tabIndex(digit: digit, count: all.count) { show(all[i]) }
724
+ }
725
+
726
+ func isPinned(_ w: NSWindow?) -> Bool { (w?.contentView as? Pane)?.pinned == true }
727
+
728
+ /** the window whose red button was pressed, else the one in front, closes whole. The window that holds the hub's
729
+ * tab is the project's: every window of the app closes with it, the hub's tab last, and the app quits. A window
730
+ * of tabs pulled out of it closes alone */
731
+ @objc func closeEveryTab(_ sender: Any?) {
732
+ let from = tabs(of: (sender as? NSView)?.window ?? frontWindow)
733
+ let all = from.contains(where: isPinned) ? windows : from
734
+ for w in all.filter({ !isPinned($0) }) + all.filter(isPinned) { w.close() }
735
+ }
736
+
737
+ // a project app has three closes, each on a road of its own, so none is told from another by where a click
738
+ // landed: the window's red button sends `closeEveryTab` (makeWindow gives it that action), command with w and
739
+ // `performClose` go through `closeTab`, and the tab bar's own close button is all that reaches `windowShouldClose`
740
+
741
+ // command with w closes the tab shown, and that tab alone; on the hub's tab, the one pinned, it is refused with the
742
+ // pane's dot: the menu's Close Window, Quit and the window's red button close the project's window, nothing else does
743
+ @objc func closeTab(_ sender: Any?) { closeTab(of: NSApp.keyWindow ?? windows.first?.tabGroup?.selectedWindow) }
744
+
745
+ func closeTab(of w: NSWindow?) {
746
+ guard let w else { return }
747
+ if isPinned(w) { (w.contentView as? Pane)?.blink() } else { w.close() }
748
+ }
749
+
750
+ /** a tab's own close button in a project app: it closes that tab alone, whatever is left; the hub's, the one tab
751
+ * the badge and the project's pages live in, is refused with the pane's dot. Any other app: the window closes */
752
+ func windowShouldClose(_ sender: NSWindow) -> Bool {
753
+ guard tabbed, isPinned(sender) else { return true }
754
+ (sender.contentView as? Pane)?.blink()
755
+ return false
756
+ }
757
+
758
+ /** the tab bars this run asked for: a second look asks none again */
759
+ var barsAsked = 0
760
+ /** the windows whose bar stayed hidden once asked: never asked twice, so no look repeats */
761
+ var barRefused = Set<ObjectIdentifier>()
762
+ var settling = false
763
+
764
+ /** every window of a project app shows its tab bar, with one tab too. macOS hides the bar of a window whose group
765
+ * holds one tab, and a window with no bar has no tab to drag into another window and takes none: two windows of
766
+ * one tab each could never be one again. The bar is asked only where it is hidden */
767
+ func showTabBars() {
768
+ guard tabbed else { return }
769
+ var seen: [NSWindowTabGroup] = []
770
+ for w in windows {
771
+ guard let g = w.tabGroup, !seen.contains(where: { $0 === g }) else { continue }
772
+ seen.append(g)
773
+ let shown = g.selectedWindow ?? w
774
+ if g.isTabBarVisible || barRefused.contains(ObjectIdentifier(shown)) { continue }
775
+ shown.toggleTabBar(nil)
776
+ barsAsked += 1
777
+ if !g.isTabBarVisible { barRefused.insert(ObjectIdentifier(shown)) }
778
+ }
779
+ }
780
+
781
+ /** the same look once the event that asked it is over (a tab dragged out or in still moves while its window
782
+ * becomes key): one look a turn of the run loop, however many events asked */
783
+ func settleTabs() {
784
+ guard tabbed, !settling else { return }
785
+ settling = true
786
+ DispatchQueue.main.async {
787
+ self.settling = false
788
+ self.showTabBars()
789
+ }
790
+ }
791
+
792
+ func windowDidBecomeKey(_ note: Notification) { settleTabs() }
793
+ func windowDidResignKey(_ note: Notification) { settleTabs() }
794
+ func windowDidBecomeMain(_ note: Notification) { settleTabs() }
795
+
796
+ /** the tab shown leaves its window for one of its own, a step down and right of it, its tab bar shown: he drags
797
+ * it back among the tabs, or merges */
798
+ @objc func tabToNewWindow(_ sender: Any?) { split(frontWindow ?? windows.first?.tabGroup?.selectedWindow) }
799
+
800
+ func split(_ w: NSWindow?) {
801
+ guard tabbed, let w, let g = w.tabGroup, g.windows.count > 1 else { return }
802
+ let from = w.frame
803
+ g.removeWindow(w)
804
+ w.setFrameTopLeftPoint(NSPoint(x: from.minX + 28, y: from.maxY - 28))
805
+ showTabBars()
806
+ show(w)
807
+ }
808
+
809
+ /** every window of the project back into one */
810
+ @objc func mergeWindows(_ sender: Any?) { merge(shown: frontWindow) }
811
+
812
+ /** the hub's window takes the tabs of every other window after its own, each window's in their order, and the
813
+ * hub's tab is first whatever place a drag gave it; `shown`, the tab he was on, stays the one shown */
814
+ func merge(shown: NSWindow? = nil) {
815
+ guard tabbed, let hub = hubTab ?? windows.first else { return }
816
+ var kept = tabs(of: hub)
817
+ for w in windows where !kept.contains(where: { $0 === w }) {
818
+ for t in tabs(of: w) {
819
+ kept.last?.addTabbedWindow(t, ordered: .above)
820
+ kept.append(t)
821
+ }
822
+ }
823
+ if isPinned(hub), let g = hub.tabGroup, g.windows.count > 1, g.windows.first !== hub {
824
+ g.removeWindow(hub)
825
+ g.insertWindow(hub, at: 0)
826
+ }
827
+ showTabBars()
828
+ show(shown ?? hub)
829
+ }
830
+
831
+ /** the windows of the app, each a group of tabs */
832
+ var windowCount: Int { Set(windows.map { w in ObjectIdentifier(w.tabGroup?.windows.first ?? w) }).count }
833
+
834
+ /** command with n: the hub page in front opens its new thread popup (serve/hub-app/app-bridge.ts, newThread). A
835
+ * tab with none to open (another site, a terminal alone) hands the ask to the hub's tab, which comes forward;
836
+ * with no window the home opens one first */
837
+ @objc func newThread(_ sender: Any?) {
838
+ var panes: [Pane] = []
839
+ for p in [keyPane(), hubTab?.contentView as? Pane, windows.first?.contentView as? Pane] {
840
+ if let p, !panes.contains(where: { $0 === p }) { panes.append(p) }
841
+ }
842
+ if panes.isEmpty {
843
+ open(startURL)
844
+ if let p = windows.last?.contentView as? Pane { panes = [p] }
845
+ }
846
+ askNewThread(panes, tries: 12)
847
+ }
848
+
849
+ /** each pane in turn until a hub page says it opened the popup; a page still loading has no hook yet, so the
850
+ * round is asked again `tries` times, then the first pane marks the key as not taken */
851
+ func askNewThread(_ panes: [Pane], tries: Int, at i: Int = 0) {
852
+ guard i < panes.count else {
853
+ if tries > 0 { DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { self.askNewThread(panes, tries: tries - 1) } } else { panes.first?.blink() }
854
+ return
855
+ }
856
+ let pane = panes[i]
857
+ guard pane.window != nil, pane.web.url.map(isHub) == true else { return askNewThread(panes, tries: tries, at: i + 1) }
858
+ pane.web.callAsyncJavaScript("return !!(window.shipkitApp && shipkitApp.newThread && shipkitApp.newThread())", arguments: [:], in: nil, in: .page) { r in
859
+ if case .success(let v) = r, (v as? Bool) == true {
860
+ if let w = pane.window { self.show(w) }
861
+ return
862
+ }
863
+ self.askNewThread(panes, tries: tries, at: i + 1)
864
+ }
265
865
  }
266
866
 
267
867
  /// the tab after or before the one a window shows, round to the first; one tab alone stays
@@ -269,7 +869,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
269
869
  guard let g = w?.tabGroup, let shown = g.selectedWindow, let i = g.windows.firstIndex(of: shown), g.windows.count > 1 else { return }
270
870
  let to = g.windows[(i + by + g.windows.count) % g.windows.count]
271
871
  g.selectedWindow = to
272
- to.makeKeyAndOrderFront(nil)
872
+ onScreen(to)
273
873
  }
274
874
 
275
875
  @objc func nextTab(_ sender: Any?) { stepTab(of: NSApp.keyWindow ?? NSApp.mainWindow, by: 1) }
@@ -311,24 +911,29 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
311
911
  let alert = NSAlert()
312
912
  alert.messageText = "This WebKit has no way to open the inspector from a menu"
313
913
  alert.informativeText = "Right click the page and pick Inspect Element."
314
- alert.runModal()
914
+ present(alert)
315
915
  }
316
916
 
317
917
  func validateMenuItem(_ item: NSMenuItem) -> Bool {
318
918
  if item.action == #selector(hideFind(_:)) { return keyPane()?.isFindBarVisible == true }
319
919
  if item.action == #selector(findNext(_:)) || item.action == #selector(findPrevious(_:)) { return keyPane()?.field.stringValue.isEmpty == false }
320
920
  if item.action == #selector(showFind(_:)) { return keyPane() != nil }
921
+ if item.action == #selector(mergeWindows(_:)) { return windowCount > 1 }
922
+ if item.action == #selector(tabToNewWindow(_:)) { return tabs(of: frontWindow).count > 1 }
321
923
  if item.action == #selector(devTools(_:)) || item.action == #selector(reload(_:)) { return keyPane() != nil }
322
924
  return true
323
925
  }
324
926
 
325
- func webConfig() -> WKWebViewConfiguration {
927
+ /** `bridge`: the page may post the badge; a project app gives it to its hub's pages alone, never to a tab of another site */
928
+ func webConfig(bridge: Bool = true) -> WKWebViewConfiguration {
326
929
  let config = WKWebViewConfiguration()
327
930
  config.preferences.setValue(true, forKey: "developerExtrasEnabled")
328
- if isShipkit {
931
+ if selfTesting { config.websiteDataStore = .nonPersistent() }
932
+ if hasBadge && bridge {
329
933
  config.userContentController.add(self, name: "shipkit")
330
- // the badge's poll keeps its pace while the window is hidden or covered
331
- if #available(macOS 14.0, *) { config.preferences.inactiveSchedulingPolicy = .none }
934
+ // the home's badge poll keeps its pace while its window is hidden or covered; a project app's page is throttled
935
+ // as any background page is: its badge moves at that slower pace
936
+ if isShipkit, #available(macOS 14.0, *) { config.preferences.inactiveSchedulingPolicy = .none }
332
937
  }
333
938
  return config
334
939
  }
@@ -344,47 +949,178 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
344
949
  keeper = web
345
950
  }
346
951
 
347
- func open(_ url: URL) {
952
+ /** an address asked from outside a page: the launch, the Dock, `open -a`. A project app starts with ONE tab, its
953
+ * hub, pinned, and its start address is that tab; any other address is a tab beside it. `again`: one more page
954
+ * on an address already shown */
955
+ func open(_ url: URL, again: Bool = false) {
348
956
  opened = true
349
- let web = WKWebView(frame: .zero, configuration: webConfig())
957
+ guard tabbed else { return show(makeWindow(url)) }
958
+ if windows.isEmpty { _ = makeWindow(startURL, pinned: true) }
959
+ if !again, tabKey(url) == tabKey(startURL), let hub = hubTab { return show(hub) }
960
+ openTab(url, again: again)
961
+ }
962
+
963
+ /** a page as a tab beside the hub's: the tab already open on that address is shown, never loaded twice, else one
964
+ * more after the last */
965
+ func openTab(_ url: URL, again: Bool = false) {
966
+ if !again, let w = tab(on: url) ?? tab(named: url) { return show(w) }
967
+ show(makeWindow(url))
968
+ }
969
+
970
+ /** a window's web view, not loaded yet. `view`: what a page kept of its scrolls before it asked for a fresh view
971
+ * (hub-app/page-reload.ts), put back where that page reads it, before its first script */
972
+ func makeWeb(_ url: URL, view: String? = nil) -> Web {
973
+ let config = webConfig(bridge: !tabbed || isHub(url))
974
+ // parsed and written again: the page's words never reach the script as they came
975
+ if let view, let obj = try? JSONSerialization.jsonObject(with: Data(view.utf8)), let clean = try? JSONSerialization.data(withJSONObject: obj), let json = String(data: clean, encoding: .utf8) {
976
+ config.userContentController.addUserScript(WKUserScript(source: "try { sessionStorage.setItem('sk-view', JSON.stringify(\(json))) } catch (e) {}", injectionTime: .atDocumentStart, forMainFrameOnly: true))
977
+ }
978
+ // a hub page's frames say their address once the page asks (reporterScript)
979
+ if hubApp && isHub(url) { config.userContentController.addUserScript(WKUserScript(source: reporterScript(hub: pageOrigin(startURL)), injectionTime: .atDocumentStart, forMainFrameOnly: false)) }
980
+ let web = Web(frame: .zero, configuration: config)
350
981
  if #available(macOS 13.3, *) { web.isInspectable = true }
351
982
  web.navigationDelegate = self
352
983
  web.uiDelegate = self
353
984
  web.allowsBackForwardNavigationGestures = true
354
985
  web.allowsMagnification = true
355
986
  web.pageZoom = zoom
987
+ return web
988
+ }
989
+
990
+ /** the pages loading in a fresh web view, by that view, each with the view it replaces */
991
+ var arriving: [ObjectIdentifier: (new: WKWebView, old: WKWebView)] = [:]
992
+ /** the longest a fresh view loads before it takes its place anyway */
993
+ static let arriveWait = 2.5
994
+ /** how a fresh view loads its page: a self test hands it one with no server */
995
+ var loadFresh: (WKWebView, URL) -> Void = { $0.load(URLRequest(url: $1)) }
996
+
997
+ /** a hub page asks to be loaded again (a new build). WebKit keeps a page reloaded in place alive whole, one page a
998
+ * reload, so the page loads in a fresh web view and the old one leaves with its process. The old page stays on the
999
+ * screen and takes the keys until the fresh one loaded: a terminal tab loses no key */
1000
+ func reload(_ old: WKWebView, to url: URL, view: String?) {
1001
+ guard isHub(url), !arriving.values.contains(where: { $0.old === old }) else { return }
1002
+ // the page reloads in place by itself when nothing says this: an app built before this request
1003
+ old.evaluateJavaScript("window.__skAppReloads = true") { _, _ in }
1004
+ if old === keeper { return keep(home: url) }
1005
+ guard old.superview is Pane else { return }
1006
+ let new = makeWeb(url, view: view)
1007
+ new.frame = old.frame
1008
+ new.pageZoom = old.pageZoom
1009
+ new.magnification = old.magnification
1010
+ arriving[ObjectIdentifier(new)] = (new, old)
1011
+ loadFresh(new, url)
1012
+ DispatchQueue.main.asyncAfter(deadline: .now() + Delegate.arriveWait) { [weak self, weak new] in if let new { self?.arrive(new) } }
1013
+ }
1014
+
1015
+ /** the fresh view takes its place: the old one is dropped, its count with it. A window closed meanwhile drops both */
1016
+ func arrive(_ new: WKWebView) {
1017
+ guard let pair = arriving.removeValue(forKey: ObjectIdentifier(new)), let pane = pair.old.superview as? Pane else { return }
1018
+ pane.swap(to: new)
1019
+ pair.old.navigationDelegate = nil
1020
+ pair.old.uiDelegate = nil
1021
+ pair.old.stopLoading()
1022
+ // the tab's count goes to the fresh view until its page posts its own: the badge never blinks for a build
1023
+ let n = counts.removeValue(forKey: ObjectIdentifier(pair.old))
1024
+ if let n, counts[ObjectIdentifier(new)] == nil { counts[ObjectIdentifier(new)] = n }
1025
+ drawBadge()
1026
+ }
1027
+
1028
+ // `--self-test-reload`, in a project app: its hub tab's page asks for a fresh web view, as hub-app/page-reload.ts
1029
+ // does for a new build. exit 0 only when the tab's pane holds another web view on the fresh page, that page read
1030
+ // the view the old one kept, the tab kept its place, its pin and its window, the count went to the fresh view, the
1031
+ // old view is gone from memory (its process ends with it), and an address that is no hub's was not obeyed
1032
+ func selfTestReload() {
1033
+ DispatchQueue.main.asyncAfter(deadline: .now() + 20) { print("timeout"); finish(1) }
1034
+ loadFresh = { web, url in web.loadHTMLString("<title>fresh</title><body><script>const v = JSON.parse(sessionStorage.getItem('sk-view') || '{}'); document.body.dataset.view = (v.scrolls ? v.scrolls[0].top : 'none') + ':' + v.at</script></body>", baseURL: url) }
1035
+ let hub = makeWindow(startURL, pinned: true)
1036
+ _ = makeWindow(startURL.appendingPathComponent("other"))
1037
+ guard let pane = hub.contentView as? Pane else { finish(1) }
1038
+ pane.web.loadHTMLString("<title>old</title><p>old</p>", baseURL: startURL)
1039
+ weak var old = pane.web
1040
+ let oldId = ObjectIdentifier(pane.web)
1041
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
1042
+ self.counts[oldId] = 2
1043
+ let before = self.tabs(of: nil).map { ObjectIdentifier($0) }
1044
+ self.reload(pane.web, to: URL(string: "https://example.com/")!, view: nil)
1045
+ print("foreign=\(self.arriving.isEmpty ? "refused" : "obeyed")")
1046
+ pane.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage({ reload: location.href, view: JSON.stringify({ href: location.href, at: 7, scrolls: [{ path: [0], top: 12, bottom: 0 }] }) }); 0") { _, _ in
1047
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
1048
+ pane.web.evaluateJavaScript("document.title + '|' + document.body.dataset.view") { v, _ in
1049
+ print("swapped=\(ObjectIdentifier(pane.web) != oldId) page=\(v ?? "nil") title=\(hub.title)")
1050
+ print("tab-kept=\(before == self.tabs(of: nil).map { ObjectIdentifier($0) }) pinned=\(pane.pinned) windows=\(self.windows.count)")
1051
+ print("count=\(self.counts[ObjectIdentifier(pane.web)] ?? -1) old-count=\(self.counts[oldId] ?? -1)")
1052
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
1053
+ print("old-view=\(old == nil ? "gone" : "held")")
1054
+ finish(0)
1055
+ }
1056
+ }
1057
+ }
1058
+ }
1059
+ }
1060
+ }
1061
+
1062
+ /** the fresh view cannot load (the server restarts): the old page reloads in place, as it did before */
1063
+ func webView(_ web: WKWebView, didFailProvisionalNavigation nav: WKNavigation!, withError error: Error) {
1064
+ guard let pair = arriving.removeValue(forKey: ObjectIdentifier(web)) else { return }
1065
+ pair.old.reload()
1066
+ }
1067
+
1068
+ /** one more window on a page, not shown yet; in a project app a tab after the last one, `alone` a window of its own
1069
+ * a step down and right of the one in front */
1070
+ func makeWindow(_ url: URL, pinned: Bool = false, alone: Bool = false) -> NSWindow {
1071
+ let web = makeWeb(url)
356
1072
  let frame = NSRect(x: 0, y: 0, width: 1400, height: 900)
357
1073
  let win = QuietWindow(contentRect: frame, styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
358
- win.contentView = Pane(web: web)
1074
+ let pane = Pane(web: web)
1075
+ pane.opened = url
1076
+ pane.pinned = pinned
1077
+ win.contentView = pane
359
1078
  win.title = appName
1079
+ pane.name = isHub(url) ? nil : tabNames[tabKey(url)]
1080
+ if tabbed, !isHub(url), let chips = tabChips[tabKey(url)] { wearChips(win, chips) }
360
1081
  win.delegate = self
361
1082
  win.isReleasedWhenClosed = false
362
- win.setFrameAutosaveName("shipkit-window")
363
- if let last = windows.last { win.setFrameTopLeftPoint(NSPoint(x: last.frame.minX + 28, y: last.frame.maxY - 28)) } else { win.center() }
1083
+ if !selfTesting { win.setFrameAutosaveName("shipkit-window") }
1084
+ paint(win, tint, text: tintText)
1085
+ offerRelaunch(win)
1086
+ if tabbed {
1087
+ win.tabbingMode = .preferred
1088
+ win.tabbingIdentifier = "project"
1089
+ // the red button closes the window whole through an action of its own, so it never reaches windowShouldClose
1090
+ if let red = win.standardWindowButton(.closeButton) {
1091
+ red.target = self
1092
+ red.action = #selector(closeEveryTab(_:))
1093
+ }
1094
+ if alone, let from = frontWindow ?? hubTab {
1095
+ win.setFrameTopLeftPoint(NSPoint(x: from.frame.minX + 28, y: from.frame.maxY - 28))
1096
+ } else if !alone, let last = tabs(of: frontWindow).last { last.addTabbedWindow(win, ordered: .above) } else { win.center() }
1097
+ } else if let last = windows.last { win.setFrameTopLeftPoint(NSPoint(x: last.frame.minX + 28, y: last.frame.maxY - 28)) } else { win.center() }
364
1098
  windows.append(win)
1099
+ // before it is ever shown: a project's window is born with its tab bar
1100
+ showTabBars()
365
1101
  web.load(URLRequest(url: url))
366
- win.makeKeyAndOrderFront(nil)
367
1102
  win.makeFirstResponder(web)
368
- NSApp.activate(ignoringOtherApps: true)
1103
+ return win
369
1104
  }
370
1105
 
371
1106
  var onLoad: ((WKWebView) -> Void)?
372
1107
 
373
- // `--self-test-tabs`: two offscreen windows as two tabs of one window, the first shown; command with page down, then
1108
+ // `--self-test-tabs`: two windows that are never shown as two tabs of one window, the first selected; command with page down, then
374
1109
  // with page up, as real key events. A self test is never the active app, so no window of it is key: the menu is
375
1110
  // asked which item takes the key, and the step that item makes is run on the tab shown, as it runs on the key
376
- // window. exit 0 only when each key has its item and the tab moved to the second and back
1111
+ // window. exit 0 only when each key has its item and the tab moved to the second and back, and, the app being no
1112
+ // project's, command with a digit has no item and is left to the page. A project app runs `selfTestProjectTabs`
377
1113
  func selfTestTabs() {
1114
+ if tabbed { return selfTestProjectTabs() }
378
1115
  buildMenu()
379
1116
  let make = { () -> NSWindow in
380
- let w = QuietWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
1117
+ let w = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
381
1118
  w.contentView = Pane(web: WKWebView(frame: .zero, configuration: WKWebViewConfiguration()))
382
1119
  w.tabbingMode = .preferred
383
1120
  return w
384
1121
  }
385
1122
  let a = make(), b = make()
386
1123
  windows.append(contentsOf: [a, b])
387
- a.orderFrontRegardless()
388
1124
  a.addTabbedWindow(b, ordered: .above)
389
1125
  a.tabGroup?.selectedWindow = a
390
1126
  let shown = { () -> Int in a.tabGroup?.selectedWindow === b ? 2 : a.tabGroup?.selectedWindow === a ? 1 : 0 }
@@ -408,52 +1144,919 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
408
1144
  print("tabs=\(a.tabGroup?.windows.count ?? 0) start=\(start)")
409
1145
  print("page-down=\(down) shown=\(afterDown)")
410
1146
  print("page-up=\(up) shown=\(afterUp)")
411
- exit(start == 1 && down == "Show Next Tab, menu took the key: true" && afterDown == 2 && up == "Show Previous Tab, menu took the key: true" && afterUp == 1 ? 0 : 1)
1147
+ let digits = (NSApp.windowsMenu?.items ?? []).filter { $0.action == #selector(self.selectTab(_:)) }.map(\.keyEquivalent).joined()
1148
+ let taken = self.key("&", 18, [.command]).map(self.takes) ?? true
1149
+ print("mode=\(mode) digits=\(digits.isEmpty ? "none" : digits) digit-taken=\(taken)")
1150
+ finish(start == 1 && down == "Show Next Tab, menu took the key: true" && afterDown == 2 && up == "Show Previous Tab, menu took the key: true" && afterUp == 1 && digits.isEmpty && !taken ? 0 : 1)
412
1151
  }
413
1152
  }
414
1153
  }
415
1154
  }
416
1155
 
417
- // `--self-test-quiet-key`: an offscreen window on a page that takes the letter k and nothing else; shift and the up
418
- // arrow, then k, sent as real key events. what the pane marked printed, exit 0 only when the key nobody took was
419
- // marked once (it would have been the system beep) and the key the page took was not
420
- func selfTestQuietKey() {
421
- let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
422
- web.navigationDelegate = self
423
- let pane = Pane(web: web)
424
- let win = QuietWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
425
- win.contentView = pane
426
- win.orderFrontRegardless()
427
- windows.append(win)
428
- let key = { (chars: String, code: UInt16, flags: NSEvent.ModifierFlags) in
429
- if let e = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: win.windowNumber, context: nil, characters: chars, charactersIgnoringModifiers: chars, isARepeat: false, keyCode: code) { win.sendEvent(e) }
1156
+ /** a key down as the keyboard sends it: its characters, its physical key, its modifiers; `plain`: what the key
1157
+ * types with no modifier, where control or option changed it */
1158
+ func key(_ chars: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags, plain: String? = nil) -> NSEvent? {
1159
+ NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: windows.first?.windowNumber ?? 0, context: nil, characters: chars, charactersIgnoringModifiers: plain ?? chars, isARepeat: false, keyCode: code)
1160
+ }
1161
+
1162
+ // `--self-test-tabs` in a project app (the bundle's ShipkitMode): its real window, never shown, on the hub the
1163
+ // test serves at the bundle's start url (tests/gui-app-live.test.ts: the hub's page, whose address moves from
1164
+ // entry to entry as the main panel's does, its links, the project's url list, a terminal's page on the hub's real
1165
+ // terminal route, a second site of the machine under `localhost`). Each link is clicked as a real mouse event,
1166
+ // each key sent as its key event (the digit row as an AZERTY keyboard types it), the red button pressed as the
1167
+ // mouse presses it, the road out recorded instead of taken. One line a fact, ` expected …` under one that is
1168
+ // wrong; exit 0 only when every line is as the owner would see it
1169
+ func selfTestProjectTabs() {
1170
+ buildMenu()
1171
+ var out: [String] = []
1172
+ openOutside = { out.append($0.absoluteString) }
1173
+ var ok = true
1174
+ func say(_ name: String, _ got: String, _ want: String) {
1175
+ print("\(name)=\(got)")
1176
+ if got != want { ok = false; print(" expected \(want)") }
430
1177
  }
431
- onLoad = { _ in
432
- win.makeFirstResponder(web)
433
- key(String(UnicodeScalar(NSUpArrowFunctionKey)!), 126, [.shift, .function, .numericPad])
434
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
435
- let untaken = pane.blinks
436
- key("k", 40, [])
437
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
438
- print("untaken-key-marked=\(untaken)")
439
- print("taken-key-marked=\(pane.blinks - untaken)")
440
- exit(untaken == 1 && pane.blinks == 1 ? 0 : 1)
1178
+ DispatchQueue.main.asyncAfter(deadline: .now() + 90) { print("timeout"); finish(1) }
1179
+ /** runs `then` once `cond` holds, or after 8 s: the line that follows says what did not happen */
1180
+ func until(_ cond: @escaping () -> Bool, _ then: @escaping () -> Void) {
1181
+ let start = Date()
1182
+ func poll() {
1183
+ if cond() || Date().timeIntervalSince(start) > 8 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: then) }
1184
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
1185
+ }
1186
+ poll()
1187
+ }
1188
+ func all() -> [NSWindow] { tabs(of: nil) }
1189
+ func pane(_ i: Int) -> Pane? { i < all().count ? all()[i].contentView as? Pane : nil }
1190
+ func selected() -> NSWindow? { self.windows.first?.tabGroup?.selectedWindow ?? (all().count == 1 ? all().first : nil) }
1191
+ func shown() -> Int { all().firstIndex { $0 === selected() }.map { $0 + 1 } ?? 0 }
1192
+ func loaded(_ i: Int) -> Bool { pane(i).map { !$0.web.isLoading && $0.web.title?.isEmpty == false } ?? false }
1193
+ func titles() -> String { all().map(\.title).joined(separator: "|") }
1194
+ /** a press and a release of the mouse on a view of the window, which is never shown */
1195
+ func mouse(_ type: NSEvent.EventType, _ at: NSPoint, _ win: NSWindow) -> NSEvent? {
1196
+ NSEvent.mouseEvent(with: type, location: at, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: win.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: type == .leftMouseDown ? 1 : 0)
1197
+ }
1198
+ func click(_ i: Int, _ id: String) {
1199
+ guard let web = pane(i)?.web, let win = web.window else { return }
1200
+ show(win)
1201
+ web.evaluateJavaScript("(() => { const r = document.getElementById('\(id)').getBoundingClientRect(); return [r.left + 4, r.top + r.height / 2] })()") { v, _ in
1202
+ guard let xy = v as? [Double], xy.count == 2 else { return print("no link \(id)") }
1203
+ let at = web.convert(NSPoint(x: xy[0], y: web.isFlipped ? xy[1] : web.bounds.height - xy[1]), to: nil)
1204
+ if let e = mouse(.leftMouseDown, at, win) { web.mouseDown(with: e) }
1205
+ if let e = mouse(.leftMouseUp, at, win) { web.mouseUp(with: e) }
1206
+ }
1207
+ }
1208
+ /** the window's red button pressed as the mouse presses it, at its middle: a button follows the mouse in a
1209
+ * loop of its own from the press on, so the release waits in the queue, where that loop reads it */
1210
+ func pressRed(_ w: NSWindow) -> String {
1211
+ guard let red = w.standardWindowButton(.closeButton) else { return "no red button" }
1212
+ let at = red.convert(NSPoint(x: red.bounds.midX, y: red.bounds.midY), to: nil)
1213
+ guard let down = mouse(.leftMouseDown, at, w), let up = mouse(.leftMouseUp, at, w) else { return "no event" }
1214
+ NSApp.postEvent(up, atStart: false)
1215
+ red.mouseDown(with: down)
1216
+ return "pressed"
1217
+ }
1218
+ /** the close button of the nth tab, as the tab bar sends its click on: the button itself shows only under the
1219
+ * mouse, which a window that is never shown never has. AppKit's own names, so one that is gone is said */
1220
+ func tabClose(_ i: Int) -> String {
1221
+ guard let frame = selected()?.contentView?.superview else { return "no frame" }
1222
+ frame.layoutSubtreeIfNeeded()
1223
+ func find(_ v: NSView, _ name: String) -> [NSView] { v.className == name ? [v] : v.subviews.flatMap { find($0, name) } }
1224
+ guard let bar = find(frame, "NSTabBar").first else { return "no tab bar" }
1225
+ let buttons = find(bar, "NSTabButton").sorted { bar.convert($0.bounds, from: $0).minX < bar.convert($1.bounds, from: $1).minX }
1226
+ let close = NSSelectorFromString("closeTabButton:")
1227
+ guard i < buttons.count, bar.responds(to: close) else { return "no close of tab \(i + 1) among \(buttons.count)" }
1228
+ _ = bar.perform(close, with: buttons[i])
1229
+ return "its button"
1230
+ }
1231
+ /** command with the nth key of the digit row, as an AZERTY keyboard types it */
1232
+ func digit(_ n: Int) -> Bool {
1233
+ let azerty = ["&", "é", "\"", "'", "(", "§", "è", "!", "ç"]
1234
+ guard let code = Delegate.digitKeys.first(where: { $0.value == n })?.key, let e = key(azerty[n - 1], code, [.command]) else { return false }
1235
+ return takes(e)
1236
+ }
1237
+ func cmdT() -> Bool { self.key("t", 17, [.command]).map(self.takes) ?? false }
1238
+ /** one key as the app hands it on: the app's own keys first, then the window's views (the page), then the
1239
+ * menus, then a plain key down. Says who took it */
1240
+ func press(_ w: NSWindow, _ chars: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags, plain: String?) -> String {
1241
+ guard let e = key(chars, code, flags, plain: plain) else { return "no event" }
1242
+ if takes(e) { return "app" }
1243
+ if !flags.intersection([.command, .control]).isEmpty {
1244
+ if w.performKeyEquivalent(with: e) { return "page" }
1245
+ if NSApp.mainMenu?.performKeyEquivalent(with: e) == true { return "menu" }
1246
+ }
1247
+ w.sendEvent(e)
1248
+ return "page"
1249
+ }
1250
+ let local = "http://localhost:\(startURL.port ?? 80)"
1251
+ let hubAt = startURL.absoluteString
1252
+ let entry = { (id: String) in URL(string: "\(hubAt)#page:src:\(id)")! }
1253
+ func addresses() -> String { all().map { ($0.contentView as? Pane)?.opened?.absoluteString ?? "?" }.joined(separator: " ").replacingOccurrences(of: "\(hubAt)#page:src:", with: "hub#").replacingOccurrences(of: hubAt, with: "hub") }
1254
+ /** the hub's tab is still a page of the hub, whatever entry it shows */
1255
+ func hubStays() -> Bool { pane(0)?.web.url.map { isHub($0) && $0.path == startURL.path } ?? false }
1256
+ /** the hub's tab goes to an entry in place, as a click on a row of its main panel does */
1257
+ func go(_ id: String, _ then: @escaping () -> Void) {
1258
+ pane(0)?.web.evaluateJavaScript("location.hash = 'page:src:\(id)'; 0") { _, _ in }
1259
+ until({ pane(0)?.web.url?.fragment == "page:src:\(id)" }, then)
1260
+ }
1261
+ var steps: [(@escaping () -> Void) -> Void] = []
1262
+ func run() {
1263
+ if steps.isEmpty { return }
1264
+ let s = steps.removeFirst()
1265
+ s { run() }
1266
+ }
1267
+
1268
+ // the launch: one tab, the hub, pinned and shown
1269
+ open(startURL)
1270
+ steps.append { next in
1271
+ until({ loaded(0) }) {
1272
+ say("start", "tabs=\(addresses()) windows=\(self.windows.count) pinned=\(all().map { self.isPinned($0) ? "yes" : "no" }.joined(separator: ",")) shown=\(shown()) titles=\(titles())", "tabs=hub windows=1 pinned=yes shown=1 titles=meadow hub")
1273
+ let items = { (m: NSMenu?, a: Selector) in (m?.items ?? []).filter { $0.action == a }.map(\.keyEquivalent).joined() }
1274
+ let file = NSApp.mainMenu?.items[1].submenu
1275
+ say("menu", "digits=\(items(NSApp.windowsMenu, #selector(self.selectTab(_:)))) entry=\(items(file, #selector(self.entryTab(_:)))) close-tab=\(items(file, #selector(self.closeTab(_:)))) close-window=\(items(file, #selector(self.closeEveryTab(_:))))", "digits=123456789 entry=t close-tab=w close-window=W")
1276
+ next()
1277
+ }
1278
+ }
1279
+ // the hub goes to a terminal's entry in place, then command with t: that entry in a tab of its own, on its
1280
+ // shell already, and the hub's tab stays where it was
1281
+ steps.append { next in
1282
+ go("terminals:t1") {
1283
+ let at = pane(0)?.web.url?.fragment ?? "none"
1284
+ let took = cmdT()
1285
+ until({ all().count == 2 && all()[1].title == "meadow terminal" }) {
1286
+ say("cmd-t", "hub-at=#\(at) taken=\(took) tabs=\(addresses()) shown=\(shown()) titles=\(titles())", "hub-at=#page:src:terminals:t1 taken=true tabs=hub hub#terminals:t1 shown=2 titles=meadow t1|meadow terminal")
1287
+ next()
1288
+ }
1289
+ }
1290
+ }
1291
+ // the same entry again: command with t shows its tab, and so does the entry's own row asking a new window
1292
+ // (the main panel's ⌘ click, middle click and hover button all call window.open); never a second tab
1293
+ steps.append { next in
1294
+ let first = digit(1)
1295
+ let back = shown()
1296
+ _ = cmdT()
1297
+ let again = "tabs=\(all().count) shown=\(shown())"
1298
+ click(0, "term")
1299
+ until({ shown() == 2 }) {
1300
+ say("same-entry", "cmd-1=\(first) shown=\(back) then cmd-t \(again) then its-row tabs=\(all().count) shown=\(shown())", "cmd-1=true shown=1 then cmd-t tabs=2 shown=2 then its-row tabs=2 shown=2")
1301
+ next()
1302
+ }
1303
+ }
1304
+ // a url the project declares, on another host: the hub is asked for the list, the link opens as tab 3
1305
+ steps.append { next in
1306
+ click(0, "prod")
1307
+ until({ all().count == 3 }) {
1308
+ say("declared-url", "tabs=\(addresses()) shown=\(shown()) out=\(out.count)", "tabs=hub hub#terminals:t1 https://app.meadow.invalid/admin shown=3 out=0")
1309
+ next()
1310
+ }
1311
+ }
1312
+ // the same link again: its tab is selected, no second one
1313
+ steps.append { next in
1314
+ let first = digit(1)
1315
+ let back = shown()
1316
+ click(0, "prod")
1317
+ until({ shown() == 3 }) {
1318
+ say("declared-again", "cmd-1=\(first) shown=\(back) then tabs=\(all().count) shown=\(shown())", "cmd-1=true shown=1 then tabs=3 shown=3")
1319
+ next()
1320
+ }
1321
+ }
1322
+ // any other site still leaves for the default browser
1323
+ steps.append { next in
1324
+ click(0, "other")
1325
+ until({ out.count == 1 }) {
1326
+ say("other-site", "tabs=\(all().count) out=\(out.joined(separator: ","))", "tabs=3 out=https://elsewhere.invalid/x")
1327
+ next()
1328
+ }
1329
+ }
1330
+ // another server of this machine, a plain link: a tab, and the hub stays on itself
1331
+ steps.append { next in
1332
+ click(0, "dev")
1333
+ until({ all().count == 4 && loaded(3) }) {
1334
+ say("this-machine", "tabs=\(all().count) shown=\(shown()) tab=\(pane(3)?.web.url?.absoluteString ?? "") title=\(all().last?.title ?? "") hub-stays=\(hubStays())", "tabs=4 shown=4 tab=\(local)/app title=dev app hub-stays=true")
1335
+ next()
1336
+ }
1337
+ }
1338
+ // in that tab a link of its own site stays, a link to another site leaves
1339
+ steps.append { next in
1340
+ click(3, "next")
1341
+ until({ pane(3)?.web.url?.path == "/app/next" && loaded(3) }) {
1342
+ click(3, "away")
1343
+ until({ out.count == 2 }) {
1344
+ say("in-a-tab", "tabs=\(all().count) tab=\(pane(3)?.web.url?.absoluteString ?? "") out=\(out.last ?? "")", "tabs=4 tab=\(local)/app/next out=https://elsewhere.invalid/y")
1345
+ next()
1346
+ }
1347
+ }
1348
+ }
1349
+ // the digit row: 2 that tab, 9 the last, 5 taken with no tab under it, 1 the hub; then the two keys right of P
1350
+ steps.append { next in
1351
+ var seen: [String] = []
1352
+ for n in [2, 9, 5, 1] { seen.append("\(digit(n) ? "" : "!")\(shown())") }
1353
+ for code in [UInt16(30), 30, 33] { seen.append("\(self.key(code == 30 ? "}" : "{", code, [.command, .shift]).map(self.takes) == true ? "" : "!")\(shown())") }
1354
+ say("tab-keys", seen.joined(separator: " "), "2 4 4 1 2 3 2")
1355
+ next()
1356
+ }
1357
+ // in a terminal's tab the app keeps its tab keys, and every key a terminal needs reaches the page (which
1358
+ // takes each key down it gets, as a terminal does, and lists them)
1359
+ steps.append { next in
1360
+ guard let w = all().count > 1 ? all()[1] : nil, let web = pane(1)?.web else { return next() }
1361
+ self.show(w)
1362
+ w.makeFirstResponder(web)
1363
+ let keys: [(String, String, UInt16, NSEvent.ModifierFlags, String?)] = [
1364
+ ("ctrl+c", "\u{3}", 8, [.control], "c"), ("ctrl+l", "\u{c}", 37, [.control], "l"), ("ctrl+r", "\u{12}", 15, [.control], "r"), ("alt+b", "∫", 11, [.option], "b"), ("esc", "\u{1b}", 53, [], nil),
1365
+ ("shift+return", "\r", 36, [.shift], nil), ("cmd+c", "c", 8, [.command], nil), ("cmd+v", "v", 9, [.command], nil), ("cmd+k", "k", 40, [.command], nil),
1366
+ ("cmd+t", "t", 17, [.command], nil), ("cmd+3", "\"", 20, [.command], nil), ("cmd+shift+]", "}", 30, [.command, .shift], nil), ("cmd+pagedown", String(UnicodeScalar(NSPageDownFunctionKey)!), 121, [.command, .function], nil),
1367
+ ]
1368
+ var who: [String] = []
1369
+ func send(_ i: Int) {
1370
+ if i == keys.count {
1371
+ return web.evaluateJavaScript("document.body.dataset.keys || ''") { got, _ in
1372
+ say("terminal-keys", who.joined(separator: " "), "ctrl+c:page ctrl+l:page ctrl+r:page alt+b:page esc:page shift+return:page cmd+c:page cmd+v:page cmd+k:page cmd+t:app cmd+3:app cmd+shift+]:app cmd+pagedown:app")
1373
+ say("terminal-page-got", "\((got as? String) ?? "error") tabs=\(all().count)", "ctrl+c ctrl+l ctrl+r alt+b Escape shift+Enter meta+c meta+v meta+k tabs=4")
1374
+ next()
1375
+ }
1376
+ }
1377
+ // each key goes to the terminal's tab, whatever tab the one before it showed
1378
+ self.show(w)
1379
+ who.append("\(keys[i].0):\(press(w, keys[i].1, keys[i].2, keys[i].3, plain: keys[i].4))")
1380
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { send(i + 1) }
1381
+ }
1382
+ send(0)
1383
+ }
1384
+ // an entry's tab closes as any tab does, by command with w: the window, the hub and the app stay. Command
1385
+ // with t opens the hub's entry again, after the last tab
1386
+ steps.append { next in
1387
+ let before = all().count
1388
+ self.closeTab(of: all()[1])
1389
+ until({ all().count == before - 1 || self.windows.isEmpty }) {
1390
+ let left = "tabs=\(all().count) windows=\(self.windows.count) hub=\(all().first.map { self.isPinned($0) } ?? false)"
1391
+ _ = cmdT()
1392
+ until({ all().count == before }) {
1393
+ let at = self.tab(on: entry("terminals:t1")).flatMap { all().firstIndex(of: $0) }.map { $0 + 1 } ?? 0
1394
+ say("entry-closes", "\(left) then cmd-t tabs=\(addresses()) entry-at=\(at) shown=\(shown())", "tabs=3 windows=3 hub=true then cmd-t tabs=hub https://app.meadow.invalid/admin \(local)/app hub#terminals:t1 entry-at=4 shown=4")
1395
+ next()
1396
+ }
1397
+ }
1398
+ }
1399
+ // the hub tab's own close button, with other tabs open: refused with the pane's dot
1400
+ steps.append { next in
1401
+ _ = digit(1)
1402
+ let road = tabClose(0)
1403
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
1404
+ say("hub-close", "by=\(road) marked=\(pane(0)?.blinks ?? 0) tabs=\(all().count) hub=\(all().first.map { self.isPinned($0) } ?? false)", "by=its button marked=1 tabs=4 hub=true")
1405
+ next()
1406
+ }
1407
+ }
1408
+ // a tab he closes is gone with its page: the process that drew it ends (its pid read from WebKit, here alone)
1409
+ steps.append { next in
1410
+ let pid = (pane(2)?.web.value(forKey: "_webProcessIdentifier") as? Int32) ?? 0
1411
+ autoreleasepool { self.closeTab(of: all()[2]) }
1412
+ // an app in use drains its pool at each event; a self test gets none, so it sends itself one
1413
+ until({
1414
+ if let e = NSEvent.otherEvent(with: .applicationDefined, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, subtype: 0, data1: 0, data2: 0) { NSApp.postEvent(e, atStart: false) }
1415
+ return pid > 0 && kill(pid, 0) != 0
1416
+ }) {
1417
+ say("closed-tab", "tabs=\(addresses()) its-process-ended=\(pid > 0 && kill(pid, 0) != 0)", "tabs=hub https://app.meadow.invalid/admin hub#terminals:t1 its-process-ended=true")
1418
+ next()
1419
+ }
1420
+ }
1421
+ // the context menu's item, then what it asks: a page of any site as a tab here; without it the same ask leaves
1422
+ steps.append { next in
1423
+ guard let web = pane(0)?.web as? Web, let e = self.key("x", 7, []) else { return next() }
1424
+ let menu = NSMenu()
1425
+ let item = menu.addItem(withTitle: "Open Link in New Window", action: nil, keyEquivalent: "")
1426
+ item.identifier = NSUserInterfaceItemIdentifier(Web.linkItem)
1427
+ let other = menu.addItem(withTitle: "Copy Link", action: nil, keyEquivalent: "")
1428
+ web.willOpenMenu(menu, with: e)
1429
+ web.tabNext = true
1430
+ web.evaluateJavaScript("window.open('https://unrelated.invalid/z'); 0") { _, _ in }
1431
+ until({ all().count == 4 }) {
1432
+ web.evaluateJavaScript("window.open('https://unrelated.invalid/z'); 0") { _, _ in }
1433
+ until({ out.count == 3 }) {
1434
+ say("open-in-a-tab-here", "item=\(item.title) other=\(other.title) tabs=\(all().count) tab=\(pane(3)?.opened?.absoluteString ?? "") without=\(out.last ?? "")", "item=Open in a Tab Here other=Copy Link tabs=4 tab=https://unrelated.invalid/z without=https://unrelated.invalid/z")
1435
+ next()
1436
+ }
1437
+ }
1438
+ }
1439
+ // the badge's bridge: the hub's page has it and its count shows, a tab of another site has none
1440
+ steps.append { next in
1441
+ self.open(URL(string: "\(local)/app")!)
1442
+ until({ all().count == 5 && loaded(4) }) {
1443
+ let probe = "typeof (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.shipkit)"
1444
+ pane(4)?.web.evaluateJavaScript(probe) { tab, _ in
1445
+ pane(0)?.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage({waiting: 5, keys: [], repos: {meadow: 2, atelier: 3}}); \(probe)") { hub, _ in
1446
+ until({ NSApp.dockTile.badgeLabel != nil }) {
1447
+ say("bridge", "hub=\(hub as? String ?? "error") tab=\(tab as? String ?? "error") badge=\(NSApp.dockTile.badgeLabel ?? "none")", "hub=object tab=undefined badge=2")
1448
+ next()
1449
+ }
1450
+ }
1451
+ }
1452
+ }
1453
+ }
1454
+ // a page of another repo: that repo's app is asked of the hub, and this window stays as it is
1455
+ steps.append { next in
1456
+ click(0, "repo")
1457
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
1458
+ say("other-repo", "tabs=\(all().count) hub-stays=\(hubStays())", "tabs=5 hub-stays=true")
1459
+ next()
1460
+ }
1461
+ }
1462
+ // the hub goes to a url's entry, then command with t: a second entry of the hub is a tab of its own, named
1463
+ // by its page; the start address asked from outside (the Dock, `open -a`) is the hub's tab, never one more
1464
+ steps.append { next in
1465
+ go("urls:u1") {
1466
+ let took = cmdT()
1467
+ until({ all().count == 6 && loaded(5) }) {
1468
+ let opened = "taken=\(took) tabs=\(all().count) shown=\(shown()) tab=\(addresses().split(separator: " ").last ?? "") title=\(all().last?.title ?? "")"
1469
+ self.open(startURL)
1470
+ say("second-entry", "\(opened) then the start address tabs=\(all().count) shown=\(shown())", "taken=true tabs=6 shown=6 tab=hub#urls:u1 title=meadow u1 then the start address tabs=6 shown=1")
1471
+ next()
1472
+ }
1473
+ }
1474
+ }
1475
+ // the url's entry asks its tab, as its row does, at the home's hop with its logins: the tab wears them, the hub
1476
+ // stays on its entry and wears none; control: the tab of this machine opened with no login wears none. Then it closes
1477
+ steps.append { next in
1478
+ let hop = "http://gate--meadow.localhost:\(startURL.port ?? 80)/"
1479
+ pane(0)?.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage({ tabName: 'gate', url: '\(hop)', urlId: 'gate', logins: ['admin'] }); window.open('\(hop)'); ''") { _, _ in }
1480
+ until({ all().count == 7 && loaded(6) }) {
1481
+ let words = { (i: Int) -> String in
1482
+ let b = self.chipButtons(of: i < all().count ? all()[i] : nil)
1483
+ return b.isEmpty ? "none" : b.map { "\($0.label):\($0.title)" }.joined(separator: ",")
1484
+ }
1485
+ say("url-chips", "tabs=\(all().count) shown=\(shown()) tab=\(pane(6)?.web.url?.host ?? "none") title=\(all().count > 6 ? all()[6].title : "none") chips=\(words(6)) hub-at=#\(pane(0)?.web.url?.fragment ?? "") hub-chips=\(words(0)) dev-chips=\(words(4))", "tabs=7 shown=7 tab=gate--meadow.localhost title=gate chips=admin:account,admin:password hub-at=#page:src:urls:u1 hub-chips=none dev-chips=none")
1486
+ if all().count > 6 { self.closeTab(of: all()[6]) }
1487
+ until({ all().count == 6 }, next)
1488
+ }
1489
+ }
1490
+ steps.append { next in
1491
+ let u = { (s: String) in URL(string: s)! }
1492
+ let hubPage = u(hubAt), app = u("https://app.example.com/a")
1493
+ let rules: [(String, Bool)] = [
1494
+ ("a sign in on a sibling host stays", road(to: u("https://auth.example.com/login"), from: app, home: app, new: false, click: true, repo: "meadow") == .here),
1495
+ ("a link to another site leaves", road(to: u("https://other.org/"), from: app, home: app, new: false, click: true, repo: "meadow") == .outside),
1496
+ ("a redirect to another site stays", road(to: u("https://other.org/"), from: app, home: app, new: false, click: false, repo: "meadow") == .here),
1497
+ ("a new window of the tab's site is a tab", road(to: u("https://app.example.com/b"), from: app, home: app, new: true, click: true, repo: "meadow") == .tab),
1498
+ ("a tab's first load stays", road(to: app, from: nil, home: app, new: false, click: false, repo: "meadow") == .here && road(to: app, from: app, home: app, new: false, click: false, repo: "meadow") == .here),
1499
+ ("the hub's link to another site asks the list", road(to: app, from: hubPage, home: hubPage, new: false, click: true, repo: "meadow") == .declared),
1500
+ ("the hub's link to a name under localhost is a tab", road(to: u("http://web--meadow.localhost:\(startURL.port ?? 80)/"), from: hubPage, home: hubPage, new: true, click: true, repo: "meadow") == .tab),
1501
+ ("the hub's own page stays", road(to: u("\(hubAt)#page:urls"), from: hubPage, home: hubPage, new: false, click: true, repo: "meadow") == .here),
1502
+ ("an entry of the hub asked as a new window is a tab", road(to: entry("claude:c1"), from: entry("urls:u1"), home: hubPage, new: true, click: false, repo: "meadow") == .tab),
1503
+ ("another repo's page is its app", road(to: URL(string: "/r/atelier/", relativeTo: hubPage)!.absoluteURL, from: hubPage, home: hubPage, new: false, click: true, repo: "meadow") == .app("atelier")),
1504
+ ("a mail address leaves", road(to: u("mailto:owner@example.com"), from: hubPage, home: hubPage, new: false, click: true, repo: "meadow") == .outside),
1505
+ ("an address is its own site", siteOf(u("http://10.0.0.7:8080/")) == "10.0.0.7" && siteOf(u("http://127.0.0.1:1/")) == siteOf(u("http://x.localhost/"))),
1506
+ ("two entries of the hub are two tabs", tabKey(entry("terminals:t1")) != tabKey(entry("terminals:t2")) && tabKey(entry("urls:u1")) != tabKey(hubPage)),
1507
+ ("an empty entry is the hub's start address", tabKey(u("\(hubAt)#")) == tabKey(hubPage)),
1508
+ ("a page of another site is one tab whatever its fragment", tabKey(u("https://app.example.com/a#one")) == tabKey(app) && tabKey(u("https://app.example.com/a/")) == tabKey(app)),
1509
+ ("command 9 is the last tab", tabIndex(digit: 9, count: 3) == 2 && tabIndex(digit: 4, count: 3) == nil && tabIndex(digit: 1, count: 0) == nil),
1510
+ ("the digits are a project app's alone", tabDigits("project") == Array(1...9) && tabDigits("home").isEmpty && tabDigits("process").isEmpty),
1511
+ ]
1512
+ let wrong = rules.filter { !$0.1 }.map(\.0).joined(separator: "; ")
1513
+ say("rules", wrong.isEmpty ? "ok" : wrong, "ok")
1514
+ next()
1515
+ }
1516
+ // a tab's own close button closes that tab alone, and so does a close asked of it by AppKit (performClose,
1517
+ // which presses the red button in any other app): the window, the hub and every other tab stay
1518
+ steps.append { next in
1519
+ guard let last = all().last else { return next() }
1520
+ self.show(last)
1521
+ let road = tabClose(all().count - 1)
1522
+ until({ all().count == 5 }) {
1523
+ let button = "by=\(road) tabs=\(all().count) windows=\(self.windows.count)"
1524
+ all().last?.performClose(nil)
1525
+ until({ all().count == 4 }) {
1526
+ say("tab-closes", "\(button) then perform-close tabs=\(all().count) windows=\(self.windows.count) hub=\(all().first.map { self.isPinned($0) } ?? false)", "by=its button tabs=5 windows=5 then perform-close tabs=4 windows=4 hub=true")
1527
+ next()
1528
+ }
1529
+ }
1530
+ }
1531
+ // the hub alone, every other tab closed: the window is still there. Command with w and the hub tab's own
1532
+ // close close nothing. Then one tab beside the hub, shown, and the window's red button pressed as the mouse
1533
+ // presses it: the window closes whole, every tab, and the app quits with it
1534
+ steps.append { _ in
1535
+ for w in all().filter({ !self.isPinned($0) }) { self.closeTab(of: w) }
1536
+ until({ all().count == 1 || self.windows.isEmpty }) {
1537
+ let left = self.windows.count
1538
+ if let hub = all().first { self.closeTab(of: hub) }
1539
+ let kept = self.windows.count
1540
+ let closes = all().first.map { self.windowShouldClose($0) } ?? true
1541
+ _ = cmdT()
1542
+ until({ all().count == 2 && shown() == 2 }) {
1543
+ let open = "tabs=\(all().count) shown=\(shown())"
1544
+ let red = selected().map(pressRed) ?? "no tab shown"
1545
+ until({ self.windows.isEmpty }) {
1546
+ say("close-window", "hub-left=\(left) after-cmd-w=\(kept) its-button-closes=\(closes) then cmd-t \(open) then red-button \(red) tabs=\(self.windows.count)", "hub-left=1 after-cmd-w=1 its-button-closes=false then cmd-t tabs=2 shown=2 then red-button pressed tabs=0")
1547
+ finish(ok ? 0 : 1)
1548
+ }
1549
+ }
1550
+ }
1551
+ }
1552
+ run()
1553
+ }
1554
+
1555
+ // `--self-test-address`, in a project app: its real window, never shown, on a stand in for the hub's page that
1556
+ // the test serves at the bundle's start url (tests/gui-app-live.test.ts). That page runs the hub's own
1557
+ // serve/hub-app/url-address.ts on three frames of two sites of other origins, neither of which says anything of
1558
+ // itself: `site`, watched from its start; `stale`, watched from an address its site answers 404 for; `other`, a
1559
+ // frame the page never asks. It keeps what the watch tells it (`__heard`) and every address message it got
1560
+ // (`__said`, `__keys`). Each frame is moved as its site's own links and router would. Then the page's notes:
1561
+ // the name of a tab it asks, what command with t opens, a tab that asks to leave. One line a fact,
1562
+ // ` expected …` under one that is wrong; exit 0 only when every line is as the owner would see it
1563
+ func selfTestAddress() {
1564
+ buildMenu()
1565
+ var out: [String] = []
1566
+ openOutside = { out.append($0.absoluteString) }
1567
+ var ok = true
1568
+ func say(_ name: String, _ got: String, _ want: String) {
1569
+ print("\(name)=\(got)")
1570
+ if got != want { ok = false; print(" expected \(want)") }
1571
+ }
1572
+ DispatchQueue.main.asyncAfter(deadline: .now() + 80) { print("timeout"); finish(1) }
1573
+ func all() -> [NSWindow] { tabs(of: nil) }
1574
+ func pane(_ i: Int) -> Pane? { i < all().count ? all()[i].contentView as? Pane : nil }
1575
+ func shown() -> Int { all().firstIndex { $0 === (self.windows.first?.tabGroup?.selectedWindow ?? all().first) }.map { $0 + 1 } ?? 0 }
1576
+ func loaded(_ i: Int) -> Bool { pane(i).map { !$0.web.isLoading && $0.web.title?.isEmpty == false } ?? false }
1577
+ func at(_ i: Int) -> String { pane(i)?.web.url?.absoluteString ?? "none" }
1578
+ /** runs `then` once `cond` holds, or after 8 s: the line that follows says what did not happen */
1579
+ func until(_ cond: @escaping () -> Bool, _ then: @escaping () -> Void) {
1580
+ let start = Date()
1581
+ func poll() {
1582
+ if cond() || Date().timeIntervalSince(start) > 8 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: then) }
1583
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
1584
+ }
1585
+ poll()
1586
+ }
1587
+ /** what a script says in a tab's page, as words */
1588
+ func js(_ i: Int, _ src: String, _ done: @escaping (String) -> Void) {
1589
+ guard let web = pane(i)?.web else { return done("no tab") }
1590
+ web.evaluateJavaScript(src) { v, err in done((v as? String) ?? err.map { "error: \($0.localizedDescription)" } ?? "") }
1591
+ }
1592
+ /** `then` with the hub page's words once `cond` holds of them, or after 8 s with what they were */
1593
+ func wait(_ src: String, _ cond: @escaping (String) -> Bool, _ then: @escaping (String) -> Void) {
1594
+ let start = Date()
1595
+ func poll() {
1596
+ js(0, src) { v in
1597
+ if cond(v) || Date().timeIntervalSince(start) > 8 { return then(v) }
1598
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
1599
+ }
1600
+ }
1601
+ poll()
1602
+ }
1603
+ func cmdT() -> Bool { self.key("t", 17, [.command]).map(self.takes) ?? false }
1604
+ let heard = "(window.__heard || []).join('|')"
1605
+ /** what the watch of one frame told the page, in order */
1606
+ func of(_ h: String, _ frame: String) -> String { h.split(separator: "|").filter { $0.hasPrefix("\(frame): ") }.joined(separator: "|") }
1607
+ /** a frame's page moves as its site's own link or router would: the hub's page has no part in where it goes */
1608
+ func move(_ frame: String, _ how: String) -> String { "document.getElementById('\(frame)').contentWindow.postMessage({ go: \(how) }, '*'); ''" }
1609
+ func post(_ note: String) -> String { "webkit.messageHandlers.shipkit.postMessage(\(note)); ''" }
1610
+ var site = "", other = ""
1611
+ var steps: [(@escaping () -> Void) -> Void] = []
1612
+ func run() {
1613
+ if steps.isEmpty { finish(ok ? 0 : 1) }
1614
+ let s = steps.removeFirst()
1615
+ s { run() }
1616
+ }
1617
+
1618
+ open(startURL)
1619
+ // each watched frame is asked at its load and answers: the one at its start keeps nothing, the one sent to
1620
+ // an address its site answers 404 for is sent back, on the app's word of that answer
1621
+ steps.append { next in
1622
+ wait(heard, { of($0, "site") == "site: drop" && of($0, "stale").hasSuffix("drop") }) { h in
1623
+ js(0, "new URL(document.getElementById('site').src).origin + ' ' + new URL(document.getElementById('other').src).origin") { o in
1624
+ let two = o.split(separator: " ").map(String.init)
1625
+ site = two.first ?? ""
1626
+ other = two.last ?? ""
1627
+ say("start", "\(of(h, "site")) \(of(h, "stale")) tabs=\(all().count)", "site: drop stale: back|stale: drop tabs=1")
1628
+ next()
1629
+ }
1630
+ }
1631
+ }
1632
+ // he walks inside the site: a link, the router's push, a fragment. The frame says each
1633
+ steps.append { next in
1634
+ js(0, move("site", "{ href: '/plain/games/lumen' }")) { _ in
1635
+ wait(heard, { of($0, "site").hasSuffix("/plain/games/lumen") }) { _ in
1636
+ js(0, move("site", "{ push: '/plain/games/lumen/sheet-1?zoom=2' }")) { _ in
1637
+ wait(heard, { of($0, "site").hasSuffix("zoom=2") }) { _ in
1638
+ js(0, move("site", "{ hash: 'tile-3' }")) { _ in
1639
+ wait(heard, { of($0, "site").hasSuffix("#tile-3") }) { h in
1640
+ say("walk", of(h, "site"), "site: drop|site: keep /plain/games/lumen|site: keep /plain/games/lumen/sheet-1?zoom=2|site: keep /plain/games/lumen/sheet-1?zoom=2#tile-3")
1641
+ next()
1642
+ }
1643
+ }
1644
+ }
1645
+ }
1646
+ }
1647
+ }
1648
+ }
1649
+ // an address the site answers an error for is dropped
1650
+ steps.append { next in
1651
+ js(0, move("site", "{ href: '/plain/gone' }")) { _ in
1652
+ wait(heard, { of($0, "site").hasSuffix("#tile-3|site: drop") }) { h in
1653
+ say("error", of(h, "site").split(separator: "|").last.map(String.init) ?? "nothing", "site: drop")
1654
+ next()
1655
+ }
1656
+ }
1657
+ }
1658
+ // the frame the page never asks moves too, and says nothing: every address the page got came from the
1659
+ // origin it asked, and held the address alone
1660
+ steps.append { next in
1661
+ js(0, move("other", "{ href: '/plain/games/lumen' }")) { _ in
1662
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
1663
+ js(0, move("other", "{ push: '/plain/games/lumen/sheet-1' }")) { _ in
1664
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
1665
+ js(0, "[...new Set(window.__said)].join(' ') + ' keys=' + [...new Set(window.__keys)].join(',')") { v in
1666
+ say("said", v.replacingOccurrences(of: site, with: "site").replacingOccurrences(of: other, with: "other"), "site keys=skAddress")
1667
+ next()
1668
+ }
1669
+ }
1670
+ }
1671
+ }
1672
+ }
1673
+ }
1674
+ // a url's row in a new tab: the page says the tab's name, then asks the window. The site alone, named
1675
+ steps.append { next in
1676
+ let u = "\(site)/plain/games/lumen"
1677
+ js(0, post("{ tabName: 'board games', url: '\(u)' }") + "; window.open('\(u)'); ''") { _ in
1678
+ until({ all().count == 2 && loaded(1) }) {
1679
+ say("url-tab", "tabs=\(all().count) shown=\(shown()) at=\(at(1).replacingOccurrences(of: site, with: "site")) title=\(all().last?.title ?? "") out=\(out.count)", "tabs=2 shown=2 at=site/plain/games/lumen title=board games out=0")
1680
+ next()
1681
+ }
1682
+ }
1683
+ }
1684
+ // the same row asked again, from further inside the site: its tab is shown where he left it, no second one.
1685
+ // Control: a tab of the same site asked with no name is a tab of its own, named by its page
1686
+ steps.append { next in
1687
+ if let hub = all().first { self.show(hub) }
1688
+ let u = "\(site)/plain/games/lumen/sheet-1"
1689
+ js(0, post("{ tabName: 'board games', url: '\(u)' }") + "; window.open('\(u)'); ''") { _ in
1690
+ until({ shown() == 2 }) {
1691
+ let again = "tabs=\(all().count) shown=\(shown()) at=\(at(1).replacingOccurrences(of: site, with: "site"))"
1692
+ js(0, "window.open('\(site)/coop/'); ''") { _ in
1693
+ until({ all().count == 3 && loaded(2) }) {
1694
+ say("url-tab-again", "\(again) then no-name tabs=\(all().count) title=\(all().last?.title ?? "")", "tabs=2 shown=2 at=site/plain/games/lumen then no-name tabs=3 title=the site that says its address")
1695
+ next()
1696
+ }
1697
+ }
1698
+ }
1699
+ }
1700
+ }
1701
+ // command with t on an entry whose page named a tab: that address, down the road of a window the page
1702
+ // would ask, under its name; again shows that tab
1703
+ steps.append { next in
1704
+ if let hub = all().first { self.show(hub) }
1705
+ js(0, post("{ entryTab: { url: '\(other)/plain/', name: 'print shop' } }")) { _ in
1706
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
1707
+ let took = cmdT()
1708
+ until({ all().count == 4 && loaded(3) }) {
1709
+ let first = "taken=\(took) tabs=\(all().count) shown=\(shown()) at=\(at(3).replacingOccurrences(of: other, with: "other")) title=\(all().last?.title ?? "")"
1710
+ if let hub = all().first { self.show(hub) }
1711
+ _ = cmdT()
1712
+ until({ shown() == 4 }) {
1713
+ say("cmd-t-named", "\(first) then again tabs=\(all().count) shown=\(shown())", "taken=true tabs=4 shown=4 at=other/plain/ title=print shop then again tabs=4 shown=4")
1714
+ next()
1715
+ }
1716
+ }
1717
+ }
1718
+ }
1719
+ }
1720
+ // an entry whose page names none: command with t opens the hub's entry, as before. A hub page in another
1721
+ // tab that names one changes nothing of what command with t opens: the hub's own tab alone says it
1722
+ steps.append { next in
1723
+ if let hub = all().first { self.show(hub) }
1724
+ js(0, post("{ entryTab: null }") + "; location.hash = 'page:src:urls:u1'; ''") { _ in
1725
+ until({ pane(0)?.web.url?.fragment == "page:src:urls:u1" }) {
1726
+ _ = cmdT()
1727
+ until({ all().count == 5 && loaded(4) }) {
1728
+ let entry = "tabs=\(all().count) shown=\(shown()) at=\(at(4).replacingOccurrences(of: startURL.absoluteString, with: "hub"))"
1729
+ js(4, post("{ entryTab: { url: '\(site)/plain/elsewhere', name: 'not the hub tab' } }")) { _ in
1730
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
1731
+ if let hub = all().first { self.show(hub) }
1732
+ _ = cmdT()
1733
+ until({ shown() == 5 }) {
1734
+ say("cmd-t-entry", "\(entry) then another-tab-names-one tabs=\(all().count) shown=\(shown())", "tabs=5 shown=5 at=hub#page:src:urls:u1 then another-tab-names-one tabs=5 shown=5")
1735
+ next()
1736
+ }
1737
+ }
1738
+ }
1739
+ }
1740
+ }
1741
+ }
1742
+ }
1743
+ // a hub page that asks to leave closes its own tab; the hub's own tab is refused with the pane's dot
1744
+ steps.append { next in
1745
+ js(4, post("{ closeTab: true }")) { _ in
1746
+ until({ all().count == 4 }) {
1747
+ let closed = all().count
1748
+ js(0, post("{ closeTab: true }")) { _ in
1749
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
1750
+ say("close-tab", "tabs=\(closed) then the-hub tabs=\(all().count) marked=\(pane(0)?.blinks ?? 0) pinned=\(all().first.map { self.isPinned($0) } ?? false)", "tabs=4 then the-hub tabs=4 marked=1 pinned=true")
1751
+ next()
1752
+ }
1753
+ }
1754
+ }
1755
+ }
1756
+ }
1757
+ run()
1758
+ }
1759
+
1760
+ // `--self-test-windows [png]`, in a project app: its real windows, never shown, with no server (each page a
1761
+ // string at the address it stands for). The hub alone shows its tab bar; a tab moved to a window of its own
1762
+ // leaves two windows, each with its bar, the state a drag between them needs; a second look asks no bar again;
1763
+ // the Window menu merges them back, the hub's tab first whatever place it had; command with n asks the hub page
1764
+ // for its new thread popup, and a page with none to open hands the ask to the hub's tab; the red button of a
1765
+ // window pulled out closes that window alone; shift command n makes a window of its own on the hub's page, apart
1766
+ // from the project's, and its red button closes it alone. `png`: the window pulled out and the one it left, each frame drawn
1767
+ // whole (`<png>` and `<png>` with `-hub` before its extension). One line a fact, ` expected …` under one that
1768
+ // is wrong; exit 0 only when every line is as the owner would see it. A drag of a tab is the mouse's: not here
1769
+ func selfTestWindows(to png: String?) {
1770
+ guard tabbed else { print("not a project app"); finish(1) }
1771
+ buildMenu()
1772
+ var ok = true
1773
+ func say(_ name: String, _ got: String, _ want: String) {
1774
+ print("\(name)=\(got)")
1775
+ if got != want { ok = false; print(" expected \(want)") }
1776
+ }
1777
+ DispatchQueue.main.asyncAfter(deadline: .now() + 40) { print("timeout"); finish(1) }
1778
+ var names: [ObjectIdentifier: String] = [:]
1779
+ /** a tab on a page that counts each ask of the new thread popup and answers `opens` */
1780
+ func tab(_ name: String, at url: URL, pinned: Bool = false, opens: Bool = true) -> NSWindow {
1781
+ let w = makeWindow(url, pinned: pinned)
1782
+ names[ObjectIdentifier(w)] = name
1783
+ (w.contentView as? Pane)?.web.loadHTMLString("<title>\(name)</title><body style='margin:0;font:15px -apple-system;background:#f6f6f6;color:#333;padding:18px'><script>window.shipkitApp = { newThread: () => { document.body.dataset.asked = String(Number(document.body.dataset.asked || 0) + 1); return \(opens) } }</script>\(appName): \(name)</body>", baseURL: url)
1784
+ return w
1785
+ }
1786
+ /** each window as its tabs in their order, with whether its tab bar shows */
1787
+ func state() -> String {
1788
+ var seen: [NSWindow] = []
1789
+ var out: [String] = []
1790
+ for w in windows where !seen.contains(where: { $0 === w }) {
1791
+ let g = tabs(of: w)
1792
+ seen.append(contentsOf: g)
1793
+ out.append(g.map { names[ObjectIdentifier($0)] ?? "?" }.joined(separator: "+") + (w.tabGroup?.isTabBarVisible == true ? " [bar]" : " [no bar]"))
1794
+ }
1795
+ return out.joined(separator: " | ")
1796
+ }
1797
+ func shown(_ w: NSWindow) -> String { (w.tabGroup?.selectedWindow ?? w).flatMap { names[ObjectIdentifier($0)] } ?? "?" }
1798
+ func draw(_ w: NSWindow, to out: String) -> Bool {
1799
+ w.setContentSize(NSSize(width: 720, height: 200))
1800
+ w.displayIfNeeded()
1801
+ guard let frame = w.contentView?.superview, let rep = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { return false }
1802
+ frame.cacheDisplay(in: frame.bounds, to: rep)
1803
+ return (try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))) != nil
1804
+ }
1805
+ func asked(_ w: NSWindow, _ done: @escaping (String) -> Void) {
1806
+ guard let web = (w.contentView as? Pane)?.web else { return done("no page") }
1807
+ web.evaluateJavaScript("document.body.dataset.asked || '0'") { v, _ in done((v as? String) ?? "error") }
1808
+ }
1809
+ func later(_ s: Double, _ then: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + s, execute: then) }
1810
+
1811
+ let hub = tab("hub", at: startURL, pinned: true)
1812
+ say("one-tab", state(), "hub [bar]")
1813
+ let term = tab("terminal", at: URL(string: "?shell=terminal", relativeTo: startURL)!.absoluteURL, opens: false)
1814
+ let site = tab("site", at: URL(string: "http://site.invalid/app")!)
1815
+ say("three-tabs", state(), "hub+terminal+site [bar]")
1816
+ split(site)
1817
+ say("tab-moved-out", "\(state()) windows=\(windowCount)", "hub+terminal [bar] | site [bar] windows=2")
1818
+ split(term)
1819
+ say("each-alone", "\(state()) windows=\(windowCount)", "hub [bar] | terminal [bar] | site [bar] windows=3")
1820
+ let before = barsAsked
1821
+ for _ in 0..<5 {
1822
+ showTabBars()
1823
+ settleTabs()
1824
+ }
1825
+ later(1.2) {
1826
+ print("bars-asked=\(before)")
1827
+ say("second-look", "bars-asked-again=\(self.barsAsked - before) refused=\(self.barRefused.count) \(state())", "bars-asked-again=0 refused=0 hub [bar] | terminal [bar] | site [bar]")
1828
+ let menu = NSApp.windowsMenu?.items ?? []
1829
+ let count = { (t: String) in menu.filter { $0.title == t }.count }
1830
+ let on = { (a: Selector) -> String in menu.first { $0.action == a }.map { self.validateMenuItem($0) ? "on" : "off" } ?? "none" }
1831
+ say("window-menu", "move=\(count("Move Tab to New Window")) merge=\(count("Merge All Windows")) merge-now=\(on(#selector(self.mergeWindows(_:)))) move-now=\(on(#selector(self.tabToNewWindow(_:))))", "move=1 merge=1 merge-now=on move-now=off")
1832
+ let file = NSApp.mainMenu?.items[1].submenu?.items ?? []
1833
+ say("file-menu", file.filter { !$0.keyEquivalent.isEmpty }.map { "\($0.title):\($0.keyEquivalent)" }.joined(separator: " "), "New Tab:t New Thread:n New Window:N Reload:r Close Tab:w Close Window:W")
1834
+ if let png {
1835
+ let wrote = draw(term, to: png) && draw(hub, to: png.replacingOccurrences(of: ".png", with: "-hub.png"))
1836
+ say("drawn", "\(wrote)", "true")
1837
+ }
1838
+ // the hub's tab second in a window, as after a tab dropped before it; then every window back into one
1839
+ site.addTabbedWindow(hub, ordered: .above)
1840
+ say("hub-second", state(), "site+hub [bar] | terminal [bar]")
1841
+ self.merge(shown: term)
1842
+ say("merged", "\(state()) windows=\(self.windowCount) shown=\(shown(hub)) merge-now=\(on(#selector(self.mergeWindows(_:)))) move-now=\(on(#selector(self.tabToNewWindow(_:))))", "hub+site+terminal [bar] windows=1 shown=terminal merge-now=off move-now=on")
1843
+ // command with n, no window being key: the hub's tab is asked, and comes forward
1844
+ let took = self.key("n", 45, [.command]).map(self.takes) ?? false
1845
+ later(1) {
1846
+ let first = shown(hub)
1847
+ // then as from the terminal's tab in front: its page opens none, the site's is never asked, the hub's opens it
1848
+ term.tabGroup?.selectedWindow = term
1849
+ self.askNewThread([term, site, hub].compactMap { $0.contentView as? Pane }, tries: 0)
1850
+ later(1) {
1851
+ asked(hub) { h in asked(term) { t in asked(site) { s in
1852
+ say("new-thread", "key-taken=\(took) shown=\(first) then from-the-terminal hub=\(h) terminal=\(t) site=\(s) shown=\(shown(hub))", "key-taken=true shown=hub then from-the-terminal hub=2 terminal=1 site=0 shown=hub")
1853
+ // two tabs pulled out into one window, and its red button: that window alone closes
1854
+ self.split(term)
1855
+ self.split(site)
1856
+ term.addTabbedWindow(site, ordered: .above)
1857
+ let apart = state()
1858
+ self.closeEveryTab(term.standardWindowButton(.closeButton))
1859
+ later(0.6) {
1860
+ say("red-button-of-the-window-pulled-out", "\(apart) then \(state()) windows=\(self.windows.count)", "hub [bar] | terminal+site [bar] then hub [bar] windows=1")
1861
+ // shift command n, no window being key: a window of its own, apart from the project's, on the hub
1862
+ let tookWindow = self.key("N", 45, [.command, .shift]).map(self.takes) ?? false
1863
+ guard let made = self.windows.last, made !== hub, let pane = made.contentView as? Pane else {
1864
+ say("new-window", "none", "a window")
1865
+ finish(1)
1866
+ }
1867
+ names[ObjectIdentifier(made)] = "hub-page"
1868
+ later(0.6) {
1869
+ let first = self.tabs(of: made).first.flatMap { names[ObjectIdentifier($0)] } ?? "?"
1870
+ let onHub = pane.opened.map(tabKey) == tabKey(startURL)
1871
+ say("new-window", "key-taken=\(tookWindow) \(state()) windows=\(self.windowCount) apart=\(made.tabGroup !== hub.tabGroup) first=\(first) on-hub=\(onHub) pinned=\(pane.pinned) hub-tab=\(self.hubTab === hub)", "key-taken=true hub [bar] | hub-page [bar] windows=2 apart=true first=hub-page on-hub=true pinned=false hub-tab=true")
1872
+ self.closeEveryTab(made.standardWindowButton(.closeButton))
1873
+ later(0.6) {
1874
+ say("red-button-of-the-new-window", "\(state()) windows=\(self.windows.count)", "hub [bar] windows=1")
1875
+ finish(ok ? 0 : 1)
1876
+ }
1877
+ }
1878
+ }
1879
+ } } }
441
1880
  }
442
1881
  }
443
1882
  }
444
- web.loadHTMLString("<p>keys</p><script>addEventListener('keydown', (e) => { if (e.key === 'k') e.preventDefault() })</script>", baseURL: nil)
445
1883
  }
446
1884
 
447
- // `--self-test-find`: an offscreen window on a page holding a word twice,
1885
+ // `--self-test-chrome <png> [tab title…]`: a window of tabs that is never shown (two, or one a title given) as a window of
1886
+ // this app opens, painted with the bundle's colour; its frame drawn whole (title bar, tab bar, page) into the png.
1887
+ // Prints the colour and the appearance; exit 0 only when a bundle with a colour has its window painted with it,
1888
+ // and one without keeps the system's
1889
+ func selfTestChrome(to out: String, titles: [String] = []) {
1890
+ let make = { (title: String) -> NSWindow in
1891
+ let w = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: titles.count > 2 ? 980 : 720, height: 260), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
1892
+ let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
1893
+ web.loadHTMLString("<body style='margin:0;font:15px -apple-system;background:#f6f6f6;color:#333;padding:18px'>\(appName)</body>", baseURL: nil)
1894
+ w.contentView = Pane(web: web)
1895
+ w.title = title
1896
+ w.tabbingMode = .preferred
1897
+ paint(w, tint, text: tintText)
1898
+ return w
1899
+ }
1900
+ let all = (titles.isEmpty ? [appName, "urls"] : titles).map(make)
1901
+ let a = all[0]
1902
+ windows.append(contentsOf: all)
1903
+ for (i, w) in all.enumerated().dropFirst() { all[i - 1].addTabbedWindow(w, ordered: .above) }
1904
+ a.tabGroup?.selectedWindow = a
1905
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
1906
+ guard let frame = a.contentView?.superview, let rep = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { print("no frame"); finish(1) }
1907
+ frame.cacheDisplay(in: frame.bounds, to: rep)
1908
+ let wrote = (try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))) != nil
1909
+ let painted = a.backgroundColor == tint && a.titlebarAppearsTransparent
1910
+ print("tint=\(info["ShipkitTint"] as? String ?? "none") text=\(info["ShipkitTintText"] as? String ?? "none") appearance=\(a.appearance?.name.rawValue ?? "system") tabs=\(a.tabGroup?.windows.count ?? 0) wrote=\(wrote)")
1911
+ finish(wrote && (tint == nil ? !a.titlebarAppearsTransparent : painted) ? 0 : 1)
1912
+ }
1913
+ }
1914
+
1915
+ // `--self-test-chips [png]`, in a project app: its real window, never shown, on a stand in for the hub that the
1916
+ // test serves at the bundle's start url (tests/gui-app-live.test.ts), its copy route answering made up values
1917
+ // (SHIPKIT_TEST_CHIPS: login 0's account and password, compared here and never printed). The hub's page names a
1918
+ // url's tab and asks it at a hop's address, first with no login (as a url with none), then with two. Each chip is
1919
+ // pressed by its own click. A copy lands on a board of the run's own, marked concealed, and leaves it at the test's
1920
+ // clock, unless another copy came since or the app quits first; a refusal says so on the chip and leaves the
1921
+ // board. `png`: that tab's frame drawn with no login (`-before` before its extension) and with its chips. One line
1922
+ // a fact, ` expected …` under one that is wrong; exit 0 only when every line is as the owner would see it
1923
+ func selfTestChips(to png: String?) {
1924
+ guard tabbed else { print("not a project app"); finish(1) }
1925
+ buildMenu()
1926
+ clearAfter = 0.8
1927
+ let want = (ProcessInfo.processInfo.environment["SHIPKIT_TEST_CHIPS"] ?? "").split(separator: "|").map(String.init)
1928
+ var ok = true
1929
+ func say(_ name: String, _ got: String, _ want: String) {
1930
+ print("\(name)=\(got)")
1931
+ if got != want { ok = false; print(" expected \(want)") }
1932
+ }
1933
+ DispatchQueue.main.asyncAfter(deadline: .now() + 45) { print("timeout"); finish(1) }
1934
+ func until(_ cond: @escaping () -> Bool, _ then: @escaping () -> Void) {
1935
+ let start = Date()
1936
+ func poll() {
1937
+ if cond() || Date().timeIntervalSince(start) > 8 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: then) }
1938
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
1939
+ }
1940
+ poll()
1941
+ }
1942
+ func later(_ s: Double, _ then: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + s, execute: then) }
1943
+ func all() -> [NSWindow] { tabs(of: nil) }
1944
+ func pane(_ i: Int) -> Pane? { i < all().count ? all()[i].contentView as? Pane : nil }
1945
+ func loaded(_ i: Int) -> Bool { pane(i).map { !$0.web.isLoading && $0.web.title?.isEmpty == false } ?? false }
1946
+ func shown() -> Int { all().firstIndex { $0 === (self.windows.first?.tabGroup?.selectedWindow ?? all().first) }.map { $0 + 1 } ?? 0 }
1947
+ /** a tab's chips as words: each login's label, then its fields */
1948
+ func chips(_ i: Int) -> String {
1949
+ let b = chipButtons(of: i < all().count ? all()[i] : nil)
1950
+ if b.isEmpty { return "none" }
1951
+ var seen: [String] = []
1952
+ for login in Set(b.map(\.login)).sorted() { seen.append("\(b.first { $0.login == login }!.label):" + b.filter { $0.login == login }.map(\.title).joined(separator: ",")) }
1953
+ return seen.joined(separator: " ")
1954
+ }
1955
+ func chip(_ login: Int, _ field: String) -> ChipButton? { chipButtons(of: all().count > 1 ? all()[1] : nil).first { $0.login == login && $0.field == field } }
1956
+ /** what the board holds, said as how it compares: never the value */
1957
+ func held() -> String {
1958
+ guard let s = self.board.string(forType: .string) else { return "empty" }
1959
+ if let i = want.firstIndex(of: s) { return i == 0 ? "the account" : "the password" }
1960
+ return s == "his own copy" ? s : "another value"
1961
+ }
1962
+ func draw(_ w: NSWindow, to out: String) -> Bool {
1963
+ w.setContentSize(NSSize(width: 1100, height: 120))
1964
+ w.displayIfNeeded()
1965
+ guard let frame = w.contentView?.superview, let rep = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { return false }
1966
+ frame.cacheDisplay(in: frame.bounds, to: rep)
1967
+ return (try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))) != nil
1968
+ }
1969
+ let hop = "http://admin--meadow.localhost:\(startURL.port ?? 80)/admin"
1970
+ func ask(_ note: String) { pane(0)?.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage(\(note)); window.open('\(hop)'); ''") { _, _ in } }
1971
+ let tab = "{ tabName: 'admin panel', url: '\(hop)'"
1972
+ var steps: [(@escaping () -> Void) -> Void] = []
1973
+ func run() {
1974
+ if steps.isEmpty {
1975
+ self.board.releaseGlobally()
1976
+ finish(ok ? 0 : 1)
1977
+ }
1978
+ let s = steps.removeFirst()
1979
+ s { run() }
1980
+ }
1981
+
1982
+ open(startURL)
1983
+ // the hub's page names the tab of a url with no login: a tab named, no chip; then it leaves
1984
+ steps.append { next in
1985
+ until({ loaded(0) }) {
1986
+ ask(tab + " }")
1987
+ until({ all().count == 2 && loaded(1) }) {
1988
+ let drew = png.map { draw(all()[1], to: $0.replacingOccurrences(of: ".png", with: "-before.png")) } ?? true
1989
+ say("no-login", "tabs=\(all().count) title=\(all()[1].title) chips=\(chips(1)) drawn=\(drew)", "tabs=2 title=admin panel chips=none drawn=true")
1990
+ self.closeTab(of: all()[1])
1991
+ until({ all().count == 1 }, next)
1992
+ }
1993
+ }
1994
+ }
1995
+ // the same url with two logins: its tab, at the hop's address, wears a chip a field a login; the hub's has none
1996
+ steps.append { next in
1997
+ ask(tab + ", urlId: 'admin', logins: ['admin', 'viewer'] }")
1998
+ until({ all().count == 2 && loaded(1) }) {
1999
+ let at = pane(1)?.web.url?.absoluteString.replacingOccurrences(of: ":\(startURL.port ?? 80)", with: ":PORT") ?? "none"
2000
+ let drew = png.map { draw(all()[1], to: $0) } ?? true
2001
+ say("tab", "tabs=\(all().count) shown=\(shown()) at=\(at) title=\(all()[1].title) chips=\(chips(1)) hub-chips=\(chips(0)) drawn=\(drew)", "tabs=2 shown=2 at=http://admin--meadow.localhost:PORT/admin title=admin panel chips=admin:account,password viewer:account,password hub-chips=none drawn=true")
2002
+ next()
2003
+ }
2004
+ }
2005
+ // a press of admin's password: on the run's own board, concealed, the chip says so; gone at the clock
2006
+ steps.append { next in
2007
+ chip(0, "password")?.performClick(nil)
2008
+ until({ self.board.string(forType: .string) != nil }) {
2009
+ let types = (self.board.types ?? []).map(\.rawValue)
2010
+ say("password", "board=\(self.board.name.rawValue.hasPrefix("dev.shipkit.self-test.") ? "private" : "not the run's") holds=\(held()) concealed=\(types.contains(Delegate.concealed.rawValue)) chip=\(chip(0, "password")?.title ?? "none")", "board=private holds=the password concealed=true chip=copied")
2011
+ later(self.clearAfter + 0.4) {
2012
+ say("at-the-clock", "holds=\(held())", "holds=empty")
2013
+ next()
2014
+ }
2015
+ }
2016
+ }
2017
+ // a press of admin's account, then his own copy before the clock: the clock leaves his copy alone
2018
+ steps.append { next in
2019
+ chip(0, "account")?.performClick(nil)
2020
+ until({ self.board.string(forType: .string) != nil }) {
2021
+ let got = held()
2022
+ self.board.clearContents()
2023
+ self.board.setString("his own copy", forType: .string)
2024
+ later(self.clearAfter + 0.4) {
2025
+ say("his-copy", "copied=\(got) then at-the-clock holds=\(held())", "copied=the account then at-the-clock holds=his own copy")
2026
+ next()
2027
+ }
2028
+ }
2029
+ }
2030
+ // a field the hub refuses: the chip says it and its tip the hub's words; the board is left as it was
2031
+ steps.append { next in
2032
+ chip(1, "password")?.performClick(nil)
2033
+ until({ chip(1, "password")?.title == "not copied" }) {
2034
+ say("refused", "chip=\(chip(1, "password")?.title ?? "none") tip=\(chip(1, "password")?.toolTip ?? "none") holds=\(held())", "chip=not copied tip=no password for viewer in this test hub holds=his own copy")
2035
+ next()
2036
+ }
2037
+ }
2038
+ // a copy, then the app quits before the clock: the value leaves with it
2039
+ steps.append { next in
2040
+ chip(0, "password")?.performClick(nil)
2041
+ until({ held() == "the password" }) {
2042
+ let got = held()
2043
+ self.applicationWillTerminate(Notification(name: NSApplication.willTerminateNotification))
2044
+ say("quit", "copied=\(got) then holds=\(held())", "copied=the password then holds=empty")
2045
+ next()
2046
+ }
2047
+ }
2048
+ run()
2049
+ }
2050
+
2051
+ // `--self-test-find`: a window that is never shown, on a page holding a word twice,
448
2052
  // the find bar opened, a word on the page searched, then one that is not;
449
2053
  // what happened printed, exit 0 only when the bar shows and finds
450
2054
  func selfTestFind() {
451
2055
  let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
452
2056
  web.navigationDelegate = self
453
2057
  let pane = Pane(web: web)
454
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
2058
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
455
2059
  win.contentView = pane
456
- win.orderFrontRegardless()
457
2060
  windows.append(win)
458
2061
  onLoad = { _ in
459
2062
  pane.showFind()
@@ -465,7 +2068,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
465
2068
  print("found=\(found)")
466
2069
  print("absent-found=\(absent)")
467
2070
  print("status=\(pane.status.stringValue)")
468
- exit(pane.isFindBarVisible && found && !absent ? 0 : 1)
2071
+ finish(pane.isFindBarVisible && found && !absent ? 0 : 1)
469
2072
  }
470
2073
  }
471
2074
  }
@@ -478,7 +2081,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
478
2081
  let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 400, height: 300), configuration: webConfig())
479
2082
  web.navigationDelegate = self
480
2083
  web.uiDelegate = self
481
- windows.append(NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false))
2084
+ windows.append(QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false))
482
2085
  windows.last?.contentView = web
483
2086
  let probe = "typeof (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)"
484
2087
  onLoad = { _ in
@@ -487,7 +2090,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
487
2090
  self.onLoad = { _ in
488
2091
  web.evaluateJavaScript(probe) { other, _ in
489
2092
  print("other=\(other as? String ?? "error")")
490
- exit((local as? String) == "function" ? 0 : 1)
2093
+ finish((local as? String) == "function" ? 0 : 1)
491
2094
  }
492
2095
  }
493
2096
  web.loadHTMLString("<p>other</p>", baseURL: URL(string: "http://example.invalid/"))
@@ -498,41 +2101,37 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
498
2101
  if let url = served { web.load(URLRequest(url: url)) } else { web.loadHTMLString("<p>local</p>", baseURL: URL(string: "http://127.0.0.1:9/")) }
499
2102
  }
500
2103
 
501
- /** hears every js panel once it shows: the self test answers it */
502
- var onPanel: ((NSAlert) -> Void)?
2104
+ /** a self test's answer to an alert, which it never shows: the button it gives is the one `present` reports */
2105
+ var onPanel: ((NSAlert, @escaping (NSApplication.ModalResponse) -> Void) -> Void)?
503
2106
 
504
- // `--self-test-panels`: a page in an offscreen window calls prompt, confirm
505
- // and alert, answered OK after typing over the prompt's text, then again,
506
- // answered with esc. What the page got printed, exit 0 only when every
507
- // answer reached it. Return is checked as OK being the sheet's default
508
- // button: a synthetic return reaches it only in a key window, and the test
509
- // must not take the focus
2107
+ // `--self-test-panels`: a page in a window that is never shown calls prompt, confirm and alert. No panel reaches
2108
+ // the screen: each one is built as the owner would get it and handed to the test, which answers OK after typing
2109
+ // over the prompt's text, then again answers Cancel. What the page got printed, exit 0 only when every answer
2110
+ // reached it. Return is checked as OK being the panel's default button, esc as the key of Cancel
510
2111
  func selfTestPanels() {
511
2112
  let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
512
2113
  web.navigationDelegate = self
513
2114
  web.uiDelegate = self
514
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
2115
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
515
2116
  win.contentView = Pane(web: web)
516
- win.orderFrontRegardless()
517
2117
  windows.append(win)
518
2118
  var accept = true
519
2119
  var panels = 0
520
2120
  var returnIsOK = true
521
2121
  var escHeard = true
522
- onPanel = { alert in
2122
+ onPanel = { alert, answer in
523
2123
  panels += 1
524
2124
  DispatchQueue.main.async {
525
2125
  if alert.window.defaultButtonCell !== alert.buttons[0].cell { returnIsOK = false }
526
2126
  if accept {
527
2127
  // typing replaces the default text only when it is selected in an active editor
528
2128
  if let field = alert.accessoryView as? NSTextField { (field.currentEditor() as? NSTextView)?.insertText("typed", replacementRange: NSRange(location: NSNotFound, length: 0)) }
529
- return alert.buttons[0].performClick(nil)
2129
+ return answer(.alertFirstButtonReturn)
530
2130
  }
531
- if alert.buttons.count == 1 { return alert.buttons[0].performClick(nil) }
532
- let esc = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: alert.window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53)
533
- if let esc, alert.window.performKeyEquivalent(with: esc) { return }
534
- escHeard = false
535
- alert.buttons[1].performClick(nil)
2131
+ if alert.buttons.count == 1 { return answer(.alertFirstButtonReturn) }
2132
+ // esc is the key of Cancel, the second button: its answer is the one given
2133
+ if alert.buttons[1].keyEquivalent != "\u{1b}" { escHeard = false }
2134
+ answer(.alertSecondButtonReturn)
536
2135
  }
537
2136
  }
538
2137
  let js = "JSON.stringify([prompt('name', 'x'), confirm('ok?'), (alert('hi'), 'alerted')])"
@@ -546,7 +2145,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
546
2145
  print("esc-heard=\(escHeard)")
547
2146
  print("ok=\(ok)")
548
2147
  print("cancel=\(cancel)")
549
- exit(panels == 6 && returnIsOK && escHeard && ok == "[\"typed\",true,\"alerted\"]" && cancel == "[null,false,\"alerted\"]" ? 0 : 1)
2148
+ finish(panels == 6 && returnIsOK && escHeard && ok == "[\"typed\",true,\"alerted\"]" && cancel == "[null,false,\"alerted\"]" ? 0 : 1)
550
2149
  }
551
2150
  }
552
2151
  }
@@ -556,6 +2155,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
556
2155
  func windowWillClose(_ note: Notification) {
557
2156
  let pane = (note.object as? NSWindow)?.contentView as? Pane
558
2157
  windows.removeAll { $0 === note.object as? NSWindow }
2158
+ settleTabs()
559
2159
  guard let pane else { return }
560
2160
  // the last window leaves the home loaded with no window, on the home that window was on; its count holds
561
2161
  // until that page posts its own
@@ -566,30 +2166,243 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
566
2166
  dropCount(pane.web)
567
2167
  }
568
2168
 
569
- // the page title names the window, so cmd-tab and the window menu tell pages apart
2169
+ // a page with no title leaves the app's name on its window (Pane watches the title of one that has)
570
2170
  func webView(_ web: WKWebView, didFinish nav: WKNavigation!) {
2171
+ arrive(web)
571
2172
  onLoad?(web)
572
- web.window?.title = (web.title?.isEmpty == false) ? web.title! : appName
2173
+ if web.title?.isEmpty != false { web.window?.title = (web.superview as? Pane)?.name ?? appName }
2174
+ }
2175
+
2176
+ /** the project's own urls as its hub lists them (`sk urls`: its declared urls, its global processes among them),
2177
+ * any host: a link of the hub to one opens as a tab, where any other site leaves for the default browser */
2178
+ var declared: [URL] = []
2179
+ /** asks the hub for the list; the self test answers in its place */
2180
+ lazy var fetchDeclared: (@escaping ([URL]?) -> Void) -> Void = { done in
2181
+ guard let repo = projectRepo?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), let api = URL(string: "/r/\(repo)/api/urls.json", relativeTo: startURL) else { return done(nil) }
2182
+ var req = URLRequest(url: api)
2183
+ req.timeoutInterval = 3
2184
+ URLSession.shared.dataTask(with: req) { data, _, err in
2185
+ let rows = data.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }?["urls"] as? [[String: Any]]
2186
+ if rows == nil { NSLog("shipkit: the project's urls did not load, so a link to one leaves for the browser: \(err?.localizedDescription ?? "not the list") (\(api.absoluteString))") }
2187
+ DispatchQueue.main.async { done(rows?.compactMap { ($0["url"] as? String).flatMap { URL(string: $0) } }) }
2188
+ }.resume()
2189
+ }
2190
+
2191
+ func isDeclared(_ url: URL) -> Bool { declared.contains { originOf($0) == originOf(url) } }
2192
+
2193
+ /** a url of another site asked from the hub: a tab when the project declares it, read again from the hub when
2194
+ * the list kept does not hold it (a url declared since), else the road out */
2195
+ func openDeclared(_ url: URL) {
2196
+ if isDeclared(url) { return open(url) }
2197
+ fetchDeclared { list in
2198
+ if let list { self.declared = list }
2199
+ if self.isDeclared(url) { self.open(url) } else { self.openOutside(url) }
2200
+ }
2201
+ }
2202
+
2203
+ /** another repo's own app, through the home (`/api/projects/open-app`): built when missing, a running one brought
2204
+ * forward; a refusal says so in a panel */
2205
+ func openProjectApp(_ repo: String) {
2206
+ guard let api = URL(string: "/api/projects/open-app", relativeTo: startURL) else { return }
2207
+ var req = URLRequest(url: api)
2208
+ req.httpMethod = "POST"
2209
+ req.setValue("application/json", forHTTPHeaderField: "content-type")
2210
+ req.httpBody = try? JSONSerialization.data(withJSONObject: ["name": repo])
2211
+ URLSession.shared.dataTask(with: req) { data, res, err in
2212
+ let code = (res as? HTTPURLResponse)?.statusCode ?? 0
2213
+ if code == 200 { return }
2214
+ let why = err?.localizedDescription ?? data.flatMap { String(data: $0, encoding: .utf8) } ?? "status \(code)"
2215
+ DispatchQueue.main.async {
2216
+ let alert = NSAlert()
2217
+ alert.messageText = "The app of \(repo) did not open"
2218
+ alert.informativeText = why
2219
+ self.present(alert)
2220
+ }
2221
+ }.resume()
2222
+ }
2223
+
2224
+ // a rebuilt bundle reaches a running copy: with no window it relaunches by itself; with windows, each one shows a
2225
+ // « new version: relaunch » button in its title bar, and only his click quits it
2226
+ var stale = false
2227
+ func watchBuild() {
2228
+ Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { _ in
2229
+ guard !self.stale, let now = stampOnDisk(), let was = launchedStamp, now != was else { return }
2230
+ self.stale = true
2231
+ if self.windows.isEmpty { return self.relaunch(nil) }
2232
+ for w in self.windows { self.offerRelaunch(w) }
2233
+ }
2234
+ }
2235
+
2236
+ func offerRelaunch(_ w: NSWindow) {
2237
+ guard stale, !w.titlebarAccessoryViewControllers.contains(where: { $0.identifier?.rawValue == "relaunch" }) else { return }
2238
+ let button = NSButton(title: "new version: relaunch", target: self, action: #selector(relaunch(_:)))
2239
+ button.bezelStyle = .recessed
2240
+ button.controlSize = .small
2241
+ button.sizeToFit()
2242
+ let holder = NSView(frame: NSRect(x: 0, y: 0, width: button.frame.width + 12, height: 28))
2243
+ button.frame.origin = NSPoint(x: 6, y: (28 - button.frame.height) / 2)
2244
+ holder.addSubview(button)
2245
+ let c = NSTitlebarAccessoryViewController()
2246
+ c.identifier = NSUserInterfaceItemIdentifier("relaunch")
2247
+ c.view = holder
2248
+ c.layoutAttribute = .trailing
2249
+ w.addTitlebarAccessoryViewController(c)
2250
+ }
2251
+
2252
+ /** a url's tab wears its logins in its title bar, as the hub's page does above a frame: each login's label, then
2253
+ * one chip a field. A press copies that field (copyChip). Words only: no value is drawn or kept */
2254
+ func wearChips(_ w: NSWindow, _ chips: (urlId: String, logins: [String])) {
2255
+ let row = NSStackView()
2256
+ row.orientation = .horizontal
2257
+ row.spacing = 4
2258
+ row.edgeInsets = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
2259
+ for (i, label) in chips.logins.enumerated() {
2260
+ let name = NSTextField(labelWithString: label)
2261
+ name.font = .systemFont(ofSize: NSFont.smallSystemFontSize)
2262
+ name.textColor = .secondaryLabelColor
2263
+ if let last = row.arrangedSubviews.last { row.setCustomSpacing(12, after: last) }
2264
+ row.addArrangedSubview(name)
2265
+ for field in ["account", "password"] {
2266
+ let b = ChipButton(title: field, target: self, action: #selector(copyChip(_:)))
2267
+ b.urlId = chips.urlId
2268
+ b.login = i
2269
+ b.label = label
2270
+ b.field = field
2271
+ b.toolTip = "copy the \(field) of \(label)"
2272
+ b.bezelStyle = .recessed
2273
+ b.controlSize = .small
2274
+ b.image = NSImage(systemSymbolName: "doc.on.doc", accessibilityDescription: "copy")
2275
+ b.imagePosition = .imageLeading
2276
+ row.addArrangedSubview(b)
2277
+ }
2278
+ }
2279
+ row.frame = NSRect(x: 0, y: 0, width: row.fittingSize.width, height: 28)
2280
+ let c = NSTitlebarAccessoryViewController()
2281
+ c.identifier = NSUserInterfaceItemIdentifier("logins")
2282
+ c.view = row
2283
+ c.layoutAttribute = .trailing
2284
+ w.addTitlebarAccessoryViewController(c)
2285
+ }
2286
+
2287
+ /** the chips a tab wears, in their order */
2288
+ func chipButtons(of w: NSWindow?) -> [ChipButton] {
2289
+ guard let c = w?.titlebarAccessoryViewControllers.first(where: { $0.identifier?.rawValue == "logins" }) else { return [] }
2290
+ return (c.view as? NSStackView)?.arrangedSubviews.compactMap { $0 as? ChipButton } ?? []
2291
+ }
2292
+
2293
+ /** the hub's answers to a chip: nothing of them is kept on disk */
2294
+ lazy var quiet = URLSession(configuration: .ephemeral)
2295
+
2296
+ /** a chip's press: the hub's copy route answers the field (any program of this Mac reaches it, the hub guards it),
2297
+ * and the value goes from the answer to the board, nowhere else. A refusal says the hub's words on the chip */
2298
+ @objc func copyChip(_ b: ChipButton) {
2299
+ guard let repo = projectRepo?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), let api = URL(string: "/r/\(repo)/api/urls/copy", relativeTo: startURL) else { return }
2300
+ var req = URLRequest(url: api)
2301
+ req.httpMethod = "POST"
2302
+ req.timeoutInterval = 5
2303
+ req.setValue("application/json", forHTTPHeaderField: "content-type")
2304
+ req.httpBody = try? JSONSerialization.data(withJSONObject: ["id": b.urlId, "login": b.login, "field": b.field])
2305
+ b.say("copying…", for: 6)
2306
+ quiet.dataTask(with: req) { data, res, err in
2307
+ let code = (res as? HTTPURLResponse)?.statusCode ?? 0
2308
+ let value = code == 200 ? (data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any])?["value"] as? String : nil
2309
+ // a refusal's words are the hub's, which never hold a value; the answer of a copy is never read as words
2310
+ let why = value != nil ? "" : code == 200 ? "the hub's answer held no value" : err?.localizedDescription ?? data.flatMap { String(data: $0, encoding: .utf8) }.map { String($0.prefix(200)) } ?? "the hub answered \(code)"
2311
+ DispatchQueue.main.async {
2312
+ if let value {
2313
+ self.conceal(value)
2314
+ return b.say("copied")
2315
+ }
2316
+ NSLog("shipkit: the \(b.field) of \(b.label) (\(b.urlId)) was not copied: \(why)")
2317
+ b.say("not copied", why: why, for: 5)
2318
+ }
2319
+ }.resume()
2320
+ }
2321
+
2322
+ /** the board a chip copies into: the owner's, and one of the run's own in a self test, which never reaches his */
2323
+ lazy var board: NSPasteboard = selfTesting ? NSPasteboard(name: NSPasteboard.Name("dev.shipkit.self-test.\(ProcessInfo.processInfo.processIdentifier)")) : .general
2324
+ /** how long a copied value stays on the board */
2325
+ var clearAfter: TimeInterval = 90
2326
+ /** the board's count right after the last copy: while it matches, the board holds that value */
2327
+ var copiedAt: Int?
2328
+ /** the mark a clipboard manager skips (nspasteboard.org): a password never lands in its history */
2329
+ static let concealed = NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")
2330
+
2331
+ func conceal(_ value: String) {
2332
+ board.clearContents()
2333
+ board.declareTypes([.string, Delegate.concealed], owner: nil)
2334
+ board.setString(value, forType: .string)
2335
+ board.setString("", forType: Delegate.concealed)
2336
+ let mark = board.changeCount
2337
+ copiedAt = mark
2338
+ DispatchQueue.main.asyncAfter(deadline: .now() + clearAfter) { [weak self] in self?.clearCopy(mark) }
2339
+ }
2340
+
2341
+ /** the value copied at `mark` (none: the last one) leaves the board, unless anything was copied since */
2342
+ func clearCopy(_ mark: Int? = nil) {
2343
+ guard let at = copiedAt, mark == nil || mark == at else { return }
2344
+ copiedAt = nil
2345
+ if board.changeCount == at { board.clearContents() }
2346
+ }
2347
+
2348
+ // a quit before the clock: the value leaves with the app
2349
+ func applicationWillTerminate(_ note: Notification) { clearCopy() }
2350
+
2351
+ /** a fresh copy of this bundle once this one has quit: the home app with no window comes back with none */
2352
+ @objc func relaunch(_ sender: Any?) {
2353
+ let back = isShipkit && windows.isEmpty ? " --args --background" : ""
2354
+ let path = Bundle.main.bundlePath.replacingOccurrences(of: "'", with: "'\\''")
2355
+ let p = Process()
2356
+ p.executableURL = URL(fileURLWithPath: "/bin/sh")
2357
+ p.arguments = ["-c", "while kill -0 \(ProcessInfo.processInfo.processIdentifier) 2>/dev/null; do sleep 0.2; done; open '\(path)'\(back)"]
2358
+ try? p.run()
2359
+ NSApp.terminate(nil)
573
2360
  }
574
2361
 
575
2362
  /** the one road out of the app: the default browser, or the app of the url's scheme; a refusal says so */
576
- var openOutside: (URL) -> Void = { url in
2363
+ lazy var openOutside: (URL) -> Void = { url in
577
2364
  NSWorkspace.shared.open(url, configuration: NSWorkspace.OpenConfiguration()) { _, err in
578
2365
  guard let err else { return }
579
2366
  DispatchQueue.main.async {
580
2367
  let alert = NSAlert()
581
2368
  alert.messageText = "This link could not open outside the app"
582
2369
  alert.informativeText = "\(url.absoluteString)\n\n\(err.localizedDescription)"
583
- alert.runModal()
2370
+ self.present(alert)
584
2371
  }
585
2372
  }
586
2373
  }
587
2374
 
2375
+ /** a project app sends a main frame's move down its road: a tab, the default browser, another repo's app. False:
2376
+ * it stays in the page that asked. The context menu's « open in a tab here » makes its own ask a tab, whatever
2377
+ * the site */
2378
+ func reroutes(_ url: URL, from web: WKWebView, new: Bool, click: Bool) -> Bool {
2379
+ let menu = new && (web as? Web)?.tabNext == true
2380
+ if menu { (web as? Web)?.tabNext = false }
2381
+ switch menu ? Road.tab : road(to: url, from: web.url, home: (web.superview as? Pane)?.opened, new: new, click: click, repo: projectRepo) {
2382
+ case .here: return false
2383
+ case .tab: openTab(url, again: menu)
2384
+ case .declared: openDeclared(url)
2385
+ case .outside: openOutside(url)
2386
+ case .app(let other): openProjectApp(other)
2387
+ }
2388
+ return true
2389
+ }
2390
+
588
2391
  // a link clicked, or a new window asked (target=_blank, window.open): the app's own host stays in the app, any
589
2392
  // other site or app leaves for the default browser (`leaves`)
590
2393
  func webView(_ web: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
591
2394
  // a link marked download saves the file, as a browser does, instead of showing it in the window
592
2395
  if action.shouldPerformDownload { return decisionHandler(.download) }
2396
+ // a project app: each main frame's move takes its road
2397
+ if tabbed, let url = action.request.url, action.targetFrame?.isMainFrame ?? true {
2398
+ return decisionHandler(reroutes(url, from: web, new: action.targetFrame == nil, click: action.navigationType == .linkActivated) ? .cancel : .allow)
2399
+ }
2400
+ // a frame of a project app's page moves inside its own site; a link clicked in it to another site leaves
2401
+ if tabbed, let url = action.request.url, action.targetFrame != nil {
2402
+ let out = action.navigationType == .linkActivated && road(to: url, from: action.sourceFrame.request.url, home: nil, new: false, click: true, repo: nil) == .outside
2403
+ if out { openOutside(url) }
2404
+ return decisionHandler(out ? .cancel : .allow)
2405
+ }
593
2406
  guard let url = action.request.url, action.navigationType == .linkActivated || action.targetFrame == nil, leaves(url) else { return decisionHandler(.allow) }
594
2407
  openOutside(url)
595
2408
  decisionHandler(.cancel)
@@ -597,10 +2410,18 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
597
2410
 
598
2411
  // a response the window cannot show (an archive, an attachment) is saved too
599
2412
  func webView(_ web: WKWebView, decidePolicyFor response: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
2413
+ if !response.isForMainFrame, hubApp, web.url.map(isHub) == true, let http = response.response as? HTTPURLResponse, http.statusCode >= 400, let url = http.url { frameAnswered(web, url, http.statusCode) }
600
2414
  let attachment = ((response.response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Disposition") ?? "").lowercased().hasPrefix("attachment")
601
2415
  decisionHandler(attachment || !response.canShowMIMEType ? .download : .allow)
602
2416
  }
603
2417
 
2418
+ /** a frame of a hub page got an error for an address: the page hears that address and its status, nothing else,
2419
+ * so a url's page drops an address its site no longer answers (serve/hub-app/url-address.ts, FRAME_ANSWER) */
2420
+ func frameAnswered(_ web: WKWebView, _ url: URL, _ status: Int) {
2421
+ guard let data = try? JSONSerialization.data(withJSONObject: ["url": url.absoluteString, "status": status]), let json = String(data: data, encoding: .utf8) else { return }
2422
+ web.evaluateJavaScript("dispatchEvent(new CustomEvent('sk-frame-answer', { detail: \(json) })); 0") { _, _ in }
2423
+ }
2424
+
604
2425
  func webView(_ web: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) { download.delegate = self }
605
2426
  func webView(_ web: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) { download.delegate = self }
606
2427
 
@@ -647,20 +2468,19 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
647
2468
  let alert = NSAlert()
648
2469
  alert.messageText = "Download failed"
649
2470
  alert.informativeText = "\(dest?.lastPathComponent ?? "the file"): \(error.localizedDescription)"
650
- alert.runModal()
2471
+ present(alert)
651
2472
  }
652
2473
 
653
- // `--self-test-download`: an offscreen page clicks a link marked download, twice, into SHIPKIT_GUI_DOWNLOADS; what
2474
+ // `--self-test-download`: a page in a window that is never shown clicks a link marked download, twice, into SHIPKIT_GUI_DOWNLOADS; what
654
2475
  // landed printed, exit 0 only when both files hold the bytes under a free name and the page stayed on itself
655
2476
  func selfTestDownload() {
656
2477
  let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
657
2478
  web.navigationDelegate = self
658
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
2479
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
659
2480
  win.contentView = Pane(web: web)
660
- win.orderFrontRegardless()
661
2481
  windows.append(win)
662
2482
  var saved: [String] = []
663
- DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); exit(1) }
2483
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); finish(1) }
664
2484
  let click = "document.getElementById('a').click(); 'clicked'"
665
2485
  onDownloaded = { url in
666
2486
  let text = url.flatMap { try? String(contentsOf: $0, encoding: .utf8) } ?? "none"
@@ -669,7 +2489,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
669
2489
  web.evaluateJavaScript("document.body.dataset.page") { page, _ in
670
2490
  print("saved=\(saved.joined(separator: ","))")
671
2491
  print("page=\((page as? String) ?? "gone")")
672
- exit(saved == ["hello.txt:hello", "hello (2).txt:hello"] && (page as? String) == "here" ? 0 : 1)
2492
+ finish(saved == ["hello.txt:hello", "hello (2).txt:hello"] && (page as? String) == "here" ? 0 : 1)
673
2493
  }
674
2494
  }
675
2495
  var started = false
@@ -681,7 +2501,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
681
2501
  web.loadHTMLString("<body data-page=here><a id=a href='data:text/plain,hello' download='hello.txt'>save</a></body>", baseURL: nil)
682
2502
  }
683
2503
 
684
- // `--self-test-links`: an offscreen page of the machine with a link of each kind, each clicked as a real mouse
2504
+ // `--self-test-links`: a page of the machine, in a window that is never shown, with a link of each kind, each clicked as a real mouse
685
2505
  // event, then a window.open with no click under it; the road out recorded instead of taken. What left and where
686
2506
  // the page is printed, exit 0 only when every link to another site or app left, the machine's own link stayed in
687
2507
  // the page and no window opened
@@ -691,11 +2511,10 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
691
2511
  let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 600, height: 400), configuration: webConfig())
692
2512
  web.navigationDelegate = self
693
2513
  web.uiDelegate = self
694
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
2514
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
695
2515
  win.contentView = web
696
- win.orderFrontRegardless()
697
2516
  windows.append(win)
698
- DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); exit(1) }
2517
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); finish(1) }
699
2518
  let ids = ["blank", "plain", "mail", "home"]
700
2519
  let expected = ["https://dash.cloudflare.com/?to=/:account/r2/api-tokens", "https://example.com/plain", "mailto:owner@example.com", "https://example.com/later"]
701
2520
  func click(_ k: Int) {
@@ -707,12 +2526,12 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
707
2526
  print("page=\((page as? String) ?? "gone")")
708
2527
  print("windows=\(self.windows.count)")
709
2528
  let p = (page as? String) ?? ""
710
- exit(out == expected && p.hasPrefix("http://127.0.0.1:9/") && p.hasSuffix(" clicked=,blank,plain,mail,home") && self.windows.count == 1 ? 0 : 1)
2529
+ finish(out == expected && p.hasPrefix("http://127.0.0.1:9/") && p.hasSuffix(" clicked=,blank,plain,mail,home") && self.windows.count == 1 ? 0 : 1)
711
2530
  }
712
2531
  }
713
2532
  }
714
2533
  web.evaluateJavaScript("(() => { const r = document.getElementById('\(ids[k])').getBoundingClientRect(); return [r.left + 4, r.top + r.height / 2] })()") { v, _ in
715
- guard let xy = v as? [Double], xy.count == 2 else { print("no link \(ids[k])"); exit(1) }
2534
+ guard let xy = v as? [Double], xy.count == 2 else { print("no link \(ids[k])"); finish(1) }
716
2535
  let at = web.convert(NSPoint(x: xy[0], y: web.isFlipped ? xy[1] : web.bounds.height - xy[1]), to: nil)
717
2536
  for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] {
718
2537
  guard let e = NSEvent.mouseEvent(with: type, location: at, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: win.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1) else { continue }
@@ -742,12 +2561,33 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
742
2561
  var burst: [WaitingThread] = []
743
2562
  /** each web view's last count: a page that leaves the home, or a closed window, drops out of the badge */
744
2563
  var counts: [ObjectIdentifier: Int] = [:]
2564
+ /** the repo the badge counts, the bundle's (the self test sets one) */
2565
+ var badgeRepo = projectRepo
745
2566
  /** hears every notification instead of the system: the self test reads it */
746
2567
  var deliver: ((Note) -> Void)?
747
2568
 
748
2569
  func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
749
2570
  guard message.frameInfo.isMainFrame, let body = message.body as? [String: Any] else { return }
750
- if let n = body["waiting"] as? Int, let web = message.webView {
2571
+ // a project app hears its hub alone: a page of another site that reached a hub tab posts nothing
2572
+ let from = message.frameInfo.securityOrigin
2573
+ if tabbed && !(from.host == startURL.host && from.port == (startURL.port ?? 0)) { return }
2574
+ if let href = body["reload"] as? String, let url = URL(string: href), let web = message.webView { return reload(web, to: url, view: body["view"] as? String) }
2575
+ // the name of the tab the page asks next, and what command with t opens for the entry it shows
2576
+ if let name = body["tabName"] as? String, let url = (body["url"] as? String).flatMap({ URL(string: $0) }) {
2577
+ tabNames[tabKey(url)] = String(name.prefix(120))
2578
+ tabChips[tabKey(url)] = chipsOf(body)
2579
+ return
2580
+ }
2581
+ if let e = body["entryTab"], let web = message.webView {
2582
+ let d = e as? [String: Any]
2583
+ let live = Set(windows.compactMap { ($0.contentView as? Pane)?.web }.map(ObjectIdentifier.init) + arriving.keys)
2584
+ entries = entries.filter { live.contains($0.key) }
2585
+ entries[ObjectIdentifier(web)] = (d?["url"] as? String).flatMap { URL(string: $0) }.map { (url: $0, name: d?["name"] as? String) }
2586
+ return
2587
+ }
2588
+ // a page that has nothing left to show asks to leave (a terminal alone whose terminal ended): its tab, never the hub's
2589
+ if body["closeTab"] as? Bool == true { return closeTab(of: message.webView?.window) }
2590
+ if let n = badgeCount(body, repo: badgeRepo), let web = message.webView {
751
2591
  // a window's page posts again: the page kept with no window leaves
752
2592
  if let k = keeper, k !== web {
753
2593
  keeper = nil
@@ -759,6 +2599,8 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
759
2599
  drawBadge()
760
2600
  if let keys = body["keys"] as? [String] { takeBack(waiting: Set(keys)) }
761
2601
  }
2602
+ // a project app notifies nothing: the home app's banners already name every thread
2603
+ guard badgeRepo == nil else { return }
762
2604
  if let seed = body["seed"] as? [[String: Any]] {
763
2605
  let threads = seed.compactMap(threadOf)
764
2606
  if !seeded {
@@ -848,9 +2690,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
848
2690
  if let url = fallbackOf(info) { open(url) }
849
2691
  return
850
2692
  }
851
- if win.isMiniaturized { win.deminiaturize(nil) }
852
- win.makeKeyAndOrderFront(nil)
853
- NSApp.activate(ignoringOtherApps: true)
2693
+ onScreen(win)
854
2694
  openIn(pane.web, info)
855
2695
  }
856
2696
 
@@ -875,21 +2715,20 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
875
2715
  }
876
2716
  }
877
2717
 
878
- // `--self-test-badge`: an offscreen page posts as the hub does: the seed and a count, threads (one twice), the seed
2718
+ // `--self-test-badge`: a page in a window that is never shown posts as the hub does: the seed and a count, threads (one twice), the seed
879
2719
  // of a reload, a burst of five, the count back to zero, then a notification's click opens a thread through the
880
2720
  // page's hook; the badge, the planned
881
2721
  // notifications and the thread opened printed, exit 0 only when each one is as the owner would see it. Nothing
882
- // reaches the system's notification center, and the test never takes the focus
2722
+ // reaches the system's notification center
883
2723
  func selfTestBadge() {
884
2724
  let config = WKWebViewConfiguration()
885
2725
  config.userContentController.add(self, name: "shipkit")
886
2726
  let web = WKWebView(frame: .zero, configuration: config)
887
2727
  web.navigationDelegate = self
888
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
2728
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
889
2729
  win.contentView = Pane(web: web)
890
- win.orderFrontRegardless()
891
2730
  windows.append(win)
892
- DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); exit(1) }
2731
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); finish(1) }
893
2732
  var notes: [String] = []
894
2733
  deliver = { n in
895
2734
  switch n {
@@ -920,19 +2759,28 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
920
2759
  let many = notes
921
2760
  post("p({waiting: 0})") {
922
2761
  let zero = NSApp.dockTile.badgeLabel ?? "none"
923
- // a click on the notification of thread b/1: the page's hook opens it in place
924
- self.openIn(web, ["repo": "b", "id": "1", "url": "http://127.0.0.1:9/"]) { ok in
925
- web.evaluateJavaScript("document.body.dataset.opened") { opened, _ in
926
- let o = (opened as? String) ?? "none"
927
- // the banners taken back once a/1 and c/5 alone still wait: b/1's, and one left by an older build
928
- let stale = staleOf([("a/1", ["a/1"]), ("b/1", ["b/1"]), ("more:c/4,c/5", ["c/4", "c/5"]), ("F09E-0F96", ["F09E-0F96"])], waiting: ["a/1", "c/5"])
929
- print("badge-two=\(two)")
930
- print("few=\(few.joined(separator: ","))")
931
- print("burst=\(many.joined(separator: ","))")
932
- print("badge-zero=\(zero)")
933
- print("click-opened=\(ok ? o : "fallback")")
934
- print("stale=\(stale.joined(separator: ","))")
935
- exit(two == "2" && few == ["a/1:t1@a/1", "b/1:t1@b/1", "d/1:t1@d/1"] && many == ["c/1:t1@c/1", "c/2:t2@c/2", "c/3:t3@c/3", "more:2:http://127.0.0.1:9/inbox@more:c/4,c/5"] && zero == "none" && ok && o == "b/1" && stale == ["b/1", "F09E-0F96"] ? 0 : 1)
2762
+ // a project app of repo b: the same post shows b's count, and a thread arriving notifies nothing
2763
+ self.badgeRepo = "b"
2764
+ let heard = notes.count
2765
+ post("p({waiting: 3, keys: [], repos: {a: 2, b: 1}}); " + thread("e", "1")) {
2766
+ let project = NSApp.dockTile.badgeLabel ?? "none"
2767
+ let quiet = notes.count == heard
2768
+ self.badgeRepo = nil
2769
+ // a click on the notification of thread b/1: the page's hook opens it in place
2770
+ self.openIn(web, ["repo": "b", "id": "1", "url": "http://127.0.0.1:9/"]) { ok in
2771
+ web.evaluateJavaScript("document.body.dataset.opened") { opened, _ in
2772
+ let o = (opened as? String) ?? "none"
2773
+ // the banners taken back once a/1 and c/5 alone still wait: b/1's, and one left by an older build
2774
+ let stale = staleOf([("a/1", ["a/1"]), ("b/1", ["b/1"]), ("more:c/4,c/5", ["c/4", "c/5"]), ("F09E-0F96", ["F09E-0F96"])], waiting: ["a/1", "c/5"])
2775
+ print("badge-two=\(two)")
2776
+ print("few=\(few.joined(separator: ","))")
2777
+ print("burst=\(many.joined(separator: ","))")
2778
+ print("badge-zero=\(zero)")
2779
+ print("badge-project=\(project) quiet=\(quiet)")
2780
+ print("click-opened=\(ok ? o : "fallback")")
2781
+ print("stale=\(stale.joined(separator: ","))")
2782
+ finish(two == "2" && few == ["a/1:t1@a/1", "b/1:t1@b/1", "d/1:t1@d/1"] && many == ["c/1:t1@c/1", "c/2:t2@c/2", "c/3:t3@c/3", "more:2:http://127.0.0.1:9/inbox@more:c/4,c/5"] && zero == "none" && project == "1" && quiet && ok && o == "b/1" && stale == ["b/1", "F09E-0F96"] ? 0 : 1)
2783
+ }
936
2784
  }
937
2785
  }
938
2786
  }
@@ -946,7 +2794,8 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
946
2794
  // window.open and target=_blank: one more window of this app for its own pages, the default browser for the rest
947
2795
  func webView(_ web: WKWebView, createWebViewWith config: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
948
2796
  if let url = action.request.url {
949
- if leaves(url) { openOutside(url) } else { open(url) }
2797
+ // a script's window.open comes here with no policy asked first: a project app sends it down its road too
2798
+ if tabbed { asksWindow(url, from: web) } else if leaves(url) { openOutside(url) } else { open(url) }
950
2799
  }
951
2800
  return nil
952
2801
  }
@@ -975,14 +2824,9 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
975
2824
  alert.accessoryView = field
976
2825
  alert.window.initialFirstResponder = field
977
2826
  }
978
- guard let win = web.window else {
979
- onPanel?(alert)
980
- return done(alert.runModal() == .alertFirstButtonReturn)
981
- }
982
- alert.beginSheetModal(for: win) { r in done(r == .alertFirstButtonReturn) }
983
- // first responder selects the whole default text, so typing replaces it
984
- if let field { alert.window.makeFirstResponder(field) }
985
- onPanel?(alert)
2827
+ present(alert, on: web.window) { done($0 == .alertFirstButtonReturn) }
2828
+ // on a sheet, first responder selects the whole default text, so typing replaces it
2829
+ if let field, web.window != nil { alert.window.makeFirstResponder(field) }
986
2830
  }
987
2831
 
988
2832
  func webView(_ web: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
@@ -1016,9 +2860,19 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
1016
2860
  let fileItem = NSMenuItem()
1017
2861
  main.addItem(fileItem)
1018
2862
  let file = NSMenu(title: "File")
1019
- file.addItem(withTitle: "New Window", action: #selector(newWindow(_:)), keyEquivalent: "n")
2863
+ // command with t, a project app's: the entry the hub shows in a tab of its own. Command with n: the new thread
2864
+ // popup in an app of the hub's pages, one more window in a process's; an app of the hub's pages has its new window
2865
+ // on shift, a project's a window of its own on the hub
2866
+ if tabbed { file.addItem(withTitle: "New Tab", action: #selector(entryTab(_:)), keyEquivalent: "t") }
2867
+ if hubApp { file.addItem(withTitle: "New Thread", action: #selector(newThread(_:)), keyEquivalent: "n") }
2868
+ if tabbed {
2869
+ file.addItem(withTitle: "New Window", action: #selector(projectWindow(_:)), keyEquivalent: "N")
2870
+ item(file, "Duplicate Tab", #selector(newWindow(_:)), "", [])
2871
+ } else if hubApp { file.addItem(withTitle: "New Window", action: #selector(newWindow(_:)), keyEquivalent: "N") }
2872
+ else { file.addItem(withTitle: "New Window", action: #selector(newWindow(_:)), keyEquivalent: "n") }
1020
2873
  file.addItem(withTitle: "Reload", action: #selector(reload(_:)), keyEquivalent: "r")
1021
- file.addItem(withTitle: "Close Window", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
2874
+ file.addItem(withTitle: tabbed ? "Close Tab" : "Close Window", action: tabbed ? #selector(closeTab(_:)) : #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
2875
+ if tabbed { file.addItem(withTitle: "Close Window", action: #selector(closeEveryTab(_:)), keyEquivalent: "W") }
1022
2876
  fileItem.submenu = file
1023
2877
  let editItem = NSMenuItem()
1024
2878
  main.addItem(editItem)
@@ -1062,6 +2916,18 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
1062
2916
  previous.keyEquivalentModifierMask = [.command]
1063
2917
  let next = win.addItem(withTitle: "Show Next Tab", action: #selector(nextTab(_:)), keyEquivalent: String(UnicodeScalar(NSPageDownFunctionKey)!))
1064
2918
  next.keyEquivalentModifierMask = [.command]
2919
+ // a project app's windows by their standard words: the tab shown into a window of its own, every window back
2920
+ // into one. Their actions are the app's own, so the hub's tab ends first
2921
+ if tabbed {
2922
+ item(win, "Move Tab to New Window", #selector(tabToNewWindow(_:)), "", [])
2923
+ item(win, "Merge All Windows", #selector(mergeWindows(_:)), "", [])
2924
+ }
2925
+ // a project app's tabs by number: the items show the keys, `takes` reads them from the physical digit row
2926
+ let digits = tabDigits(mode)
2927
+ if !digits.isEmpty { win.addItem(.separator()) }
2928
+ for n in digits {
2929
+ item(win, n == 1 ? "Show the Hub" : n == 9 ? "Show the Last Tab" : "Show Tab \(n)", #selector(selectTab(_:)), String(n), tag: n)
2930
+ }
1065
2931
  winItem.submenu = win
1066
2932
  NSApp.windowsMenu = win
1067
2933
  NSApp.mainMenu = main
@@ -1071,5 +2937,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
1071
2937
  let app = NSApplication.shared
1072
2938
  let delegate = Delegate()
1073
2939
  app.delegate = delegate
1074
- app.setActivationPolicy(.regular)
2940
+ // a self test is no app of the Dock and takes no focus; the window server is asked through its whole run
2941
+ app.setActivationPolicy(selfTesting ? .prohibited : .regular)
2942
+ if selfTesting { Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { _ in seenOnScreen = max(seenOnScreen, windowsOnScreen().own) } }
1075
2943
  app.run()