rvlib-shipkit 2.29.0 → 2.31.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 (904) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/README.md +15 -0
  3. package/package.json +2 -1
  4. package/src/advisors/acts.ts +174 -83
  5. package/src/advisors/advice.ts +201 -24
  6. package/src/advisors/advisor-view.ts +60 -12
  7. package/src/advisors/app-graph.ts +8 -2
  8. package/src/advisors/cf-api.ts +44 -0
  9. package/src/advisors/copy-truth.ts +49 -0
  10. package/src/advisors/dir-bucket.ts +69 -0
  11. package/src/advisors/door-child.ts +112 -0
  12. package/src/advisors/door-probe.ts +88 -0
  13. package/src/advisors/door-serve.ts +52 -0
  14. package/src/advisors/door.ts +82 -23
  15. package/src/advisors/edge/api.ts +14 -7
  16. package/src/advisors/edge/bucket.ts +10 -1
  17. package/src/advisors/edge/handler.ts +85 -44
  18. package/src/advisors/edge/here.ts +63 -0
  19. package/src/advisors/edge/pages.ts +87 -0
  20. package/src/advisors/edge/shell.ts +5 -3
  21. package/src/advisors/edge/sign-in.ts +144 -0
  22. package/src/advisors/edge/status.ts +28 -6
  23. package/src/advisors/edge/types.ts +25 -17
  24. package/src/advisors/expose.ts +226 -116
  25. package/src/advisors/here.ts +66 -0
  26. package/src/advisors/invite-send.ts +176 -0
  27. package/src/advisors/invite.ts +49 -0
  28. package/src/advisors/job.ts +89 -11
  29. package/src/advisors/login.ts +66 -0
  30. package/src/advisors/owner-name.ts +37 -0
  31. package/src/advisors/owner-store.ts +267 -62
  32. package/src/advisors/photos.ts +10 -50
  33. package/src/advisors/project.ts +92 -48
  34. package/src/advisors/rights.ts +152 -0
  35. package/src/advisors/routes.ts +342 -83
  36. package/src/advisors/scan.ts +39 -2
  37. package/src/advisors/setup-run.ts +132 -0
  38. package/src/advisors/share-trace.ts +78 -0
  39. package/src/advisors/sync.ts +197 -82
  40. package/src/advisors/tunnel.ts +118 -0
  41. package/src/advisors/users-router.ts +186 -0
  42. package/src/agent-time/accounts-usage-disk.ts +45 -3
  43. package/src/agent-time/accounts-usage.ts +8 -0
  44. package/src/agent-time/claude-sessions.ts +92 -0
  45. package/src/agent-time/hooks.ts +1 -1
  46. package/src/agent-time/live.ts +5 -2
  47. package/src/agent-time/registry.ts +287 -106
  48. package/src/agent-time/store.ts +199 -34
  49. package/src/annex/born.ts +2 -9
  50. package/src/asks/ask-carry.ts +14 -7
  51. package/src/asks/ask-doc.ts +2 -2
  52. package/src/asks/ask-edit.ts +49 -0
  53. package/src/asks/ask-since.ts +74 -0
  54. package/src/asks/ask-store.ts +91 -35
  55. package/src/asks/ask-words-fold.ts +2 -2
  56. package/src/check.ts +9 -1
  57. package/src/checks/SK001-package-json-shape.check.ts +13 -3
  58. package/src/checks/SK003-claude-md-shape.check.ts +78 -19
  59. package/src/checks/SK004-gitignore-policy.check.ts +15 -6
  60. package/src/checks/SK008-reviewer-agent.check.ts +5 -8
  61. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  62. package/src/checks/SK013-one-way-in-policy.check.ts +1 -0
  63. package/src/checks/SK017-vscode-hub-task.check.ts +1 -0
  64. package/src/checks/SK024-identity-colors.check.ts +1 -1
  65. package/src/checks/SK027-agent-wiki-links.check.ts +2 -1
  66. package/src/checks/SK032-ignored-inputs.check.ts +9 -5
  67. package/src/checks/SK033-global-contribution.check.ts +1 -0
  68. package/src/checks/SK034-commit-gates-armed.check.ts +1 -0
  69. package/src/checks/SK036-draft-media-size.check.ts +4 -3
  70. package/src/checks/SK038-speaks-as.check.ts +6 -5
  71. package/src/checks/SK039-vscode-watch-generated.check.ts +6 -25
  72. package/src/checks/SK044-behind-upstream.check.ts +2 -1
  73. package/src/checks/SK049-thread-answers-hook.check.ts +9 -5
  74. package/src/checks/SK050-retired-commands.check.ts +1 -0
  75. package/src/checks/SK051-no-formatter.check.ts +1 -0
  76. package/src/checks/SK052-url-old-words.check.ts +56 -0
  77. package/src/checks/SK053-tools.check.ts +46 -0
  78. package/src/checks/SK054-agent-allow-list.check.ts +142 -0
  79. package/src/cli/clip.ts +44 -0
  80. package/src/cli/cmd_Advisors.ts +322 -133
  81. package/src/cli/cmd_Annex.ts +1 -1
  82. package/src/cli/cmd_Asks.ts +125 -23
  83. package/src/cli/cmd_Assets.ts +1 -1
  84. package/src/cli/cmd_Backup.ts +29 -66
  85. package/src/cli/cmd_BackupTargets.ts +106 -0
  86. package/src/cli/cmd_Bump.ts +1 -1
  87. package/src/cli/cmd_CacheAudit.ts +2 -2
  88. package/src/cli/cmd_Calls.ts +1 -1
  89. package/src/cli/cmd_Capacity.ts +1 -1
  90. package/src/cli/cmd_Check.ts +2 -2
  91. package/src/cli/cmd_Checks.ts +2 -1
  92. package/src/cli/cmd_Ci.ts +1 -1
  93. package/src/cli/cmd_Commands.ts +1 -1
  94. package/src/cli/cmd_ConfigKeys.ts +1 -1
  95. package/src/cli/cmd_Contracts.ts +1 -1
  96. package/src/cli/cmd_CrossRepoActivity.ts +1 -6
  97. package/src/cli/cmd_Db.ts +47 -3
  98. package/src/cli/cmd_Drill.ts +1 -1
  99. package/src/cli/cmd_Drive.ts +259 -0
  100. package/src/cli/cmd_Fleet.ts +1 -1
  101. package/src/cli/cmd_FleetContext.ts +45 -0
  102. package/src/cli/cmd_FleetPush.ts +1 -1
  103. package/src/cli/cmd_FleetUpdate.ts +104 -0
  104. package/src/cli/cmd_GlobalContext.ts +1 -1
  105. package/src/cli/cmd_GlobalProcesses.ts +7 -4
  106. package/src/cli/cmd_History.ts +8 -27
  107. package/src/cli/cmd_Home.ts +16 -9
  108. package/src/cli/cmd_Hooks.ts +4 -13
  109. package/src/cli/cmd_Hq.ts +80 -63
  110. package/src/cli/cmd_Init.ts +1 -1
  111. package/src/cli/cmd_Insights.ts +1 -1
  112. package/src/cli/cmd_Keys.ts +1 -1
  113. package/src/cli/cmd_Lanes.ts +20 -7
  114. package/src/cli/cmd_Machines.ts +1 -1
  115. package/src/cli/cmd_Media.ts +14 -22
  116. package/src/cli/cmd_Messages.ts +1 -1
  117. package/src/cli/cmd_Mv.ts +1 -1
  118. package/src/cli/cmd_Needs.ts +1 -1
  119. package/src/cli/cmd_Orchestrator.ts +245 -85
  120. package/src/cli/cmd_OrchestratorRole.ts +152 -0
  121. package/src/cli/cmd_Overview.ts +1 -1
  122. package/src/cli/cmd_Pb.ts +1 -1
  123. package/src/cli/cmd_Planned.ts +1 -1
  124. package/src/cli/cmd_Rec.ts +1 -1
  125. package/src/cli/cmd_Reflect.ts +3 -3
  126. package/src/cli/cmd_Release.ts +1 -1
  127. package/src/cli/cmd_Releases.ts +1 -1
  128. package/src/cli/cmd_Review.ts +430 -339
  129. package/src/cli/cmd_Secret.ts +128 -16
  130. package/src/cli/cmd_Serve.ts +1 -1
  131. package/src/cli/cmd_Setup.ts +30 -0
  132. package/src/cli/cmd_Shot.ts +3 -5
  133. package/src/cli/cmd_Sign.ts +1 -1
  134. package/src/cli/cmd_Smoke.ts +1 -1
  135. package/src/cli/cmd_Social.ts +6 -3
  136. package/src/cli/cmd_SocialDrafts.ts +20 -6
  137. package/src/cli/cmd_Sound.ts +2 -1
  138. package/src/cli/cmd_Space.ts +4 -4
  139. package/src/cli/cmd_Start.ts +1 -1
  140. package/src/cli/cmd_Status.ts +1 -1
  141. package/src/cli/cmd_ThreadHolds.ts +1 -1
  142. package/src/cli/cmd_ThreadKinds.ts +1 -1
  143. package/src/cli/cmd_ThreadReflect.ts +3 -3
  144. package/src/cli/cmd_ThreadSyncNeeds.ts +1 -1
  145. package/src/cli/cmd_Time.ts +1 -1
  146. package/src/cli/cmd_Tmp.ts +1 -1
  147. package/src/cli/cmd_TraceAudit.ts +1 -1
  148. package/src/cli/cmd_Trailer.ts +1 -1
  149. package/src/cli/cmd_Tui.ts +1 -1
  150. package/src/cli/cmd_Urls.ts +61 -9
  151. package/src/cli/cmd_Vault.ts +1 -1
  152. package/src/cli/cmd_Veille.ts +1 -1
  153. package/src/cli/cmd_When.ts +1 -1
  154. package/src/cli/cmd_Wiki.ts +5 -2
  155. package/src/cli/cmd_Worktrees.ts +1 -1
  156. package/src/cli/family-pages.ts +1 -0
  157. package/src/cli/inbox-hook-run.ts +135 -0
  158. package/src/cli/line.ts +131 -0
  159. package/src/cli/registry-cli.ts +100 -0
  160. package/src/cli/registry-heads.ts +448 -0
  161. package/src/cli/registry.ts +385 -250
  162. package/src/cli/review-here.ts +136 -0
  163. package/src/cli.ts +65 -22
  164. package/src/collections/actions.ts +5 -4
  165. package/src/collections/checks.ts +5 -0
  166. package/src/collections/collection-types.ts +7 -3
  167. package/src/collections/pings.ts +4 -1
  168. package/src/collections/providers.ts +10 -5
  169. package/src/collections/review.ts +3 -4
  170. package/src/collections/tests.ts +7 -4
  171. package/src/context/context-line.ts +29 -0
  172. package/src/context/context-view.ts +34 -0
  173. package/src/context/project-context.ts +144 -0
  174. package/src/core/agent-allow-policy.ts +99 -0
  175. package/src/core/agent-spawn.ts +2 -0
  176. package/src/core/app-icon-frame.ts +62 -0
  177. package/src/core/app-icon.ts +179 -17
  178. package/src/core/archived.ts +10 -7
  179. package/src/core/capacity.ts +3 -2
  180. package/src/core/check-ctx.ts +38 -4
  181. package/src/core/check-pass.ts +7 -0
  182. package/src/core/daemon-port.ts +10 -0
  183. package/src/core/es2022.ts +19 -0
  184. package/src/core/footprint.ts +35 -0
  185. package/src/core/foreign.ts +87 -0
  186. package/src/core/git-bin.ts +18 -0
  187. package/src/core/git-root.ts +40 -4
  188. package/src/core/git.ts +22 -0
  189. package/src/core/gui-color.ts +75 -0
  190. package/src/core/hard-reset.ts +7 -1
  191. package/src/core/house-config-text.ts +47 -0
  192. package/src/core/house-layout.ts +4 -0
  193. package/src/core/hub-theme.ts +1 -3
  194. package/src/core/identities-path.ts +67 -0
  195. package/src/core/identities-root.ts +26 -0
  196. package/src/core/instance.ts +1 -1
  197. package/src/core/jobs.ts +1 -4
  198. package/src/core/layout.ts +6 -0
  199. package/src/core/loop-watch.ts +28 -5
  200. package/src/core/machine-commit.ts +9 -1
  201. package/src/core/machine-db.ts +1 -8
  202. package/src/core/machine-name.ts +31 -0
  203. package/src/core/memory-watch.ts +56 -8
  204. package/src/core/on-loop.ts +10 -7
  205. package/src/core/one-lib.ts +2 -1
  206. package/src/core/one-way-in-policy.ts +17 -12
  207. package/src/core/owner-word-policy.ts +123 -0
  208. package/src/core/panel-shades.ts +140 -0
  209. package/src/core/pid-alive.ts +11 -0
  210. package/src/core/proc-path.ts +42 -0
  211. package/src/core/repo-gui-color.ts +16 -0
  212. package/src/core/retention.ts +2 -2
  213. package/src/core/role-policy.ts +16 -0
  214. package/src/core/run-dirs.ts +2 -5
  215. package/src/core/runs.ts +5 -3
  216. package/src/core/scope.ts +50 -3
  217. package/src/core/scratch-objects.ts +1 -1
  218. package/src/core/slot-env.ts +4 -0
  219. package/src/core/slots.ts +2 -2
  220. package/src/core/spawn-timeout.ts +9 -3
  221. package/src/core/tmux-policy.ts +264 -0
  222. package/src/core/tools.ts +20 -0
  223. package/src/core/tree-watch.ts +304 -0
  224. package/src/core/unit-icon.ts +43 -0
  225. package/src/core/window-policy.ts +132 -0
  226. package/src/drives/context.ts +29 -0
  227. package/src/drives/drives-view.ts +121 -0
  228. package/src/drives/file.ts +89 -0
  229. package/src/drives/local-folder.ts +107 -0
  230. package/src/drives/login.ts +181 -0
  231. package/src/drives/named.ts +33 -0
  232. package/src/drives/rclone.ts +100 -0
  233. package/src/drives/reach.ts +73 -0
  234. package/src/drives/routes.ts +89 -0
  235. package/src/drives/shares.ts +292 -0
  236. package/src/fleet/context-fleet.ts +83 -0
  237. package/src/fleet/follow.ts +172 -0
  238. package/src/fleet/push-fleet.ts +2 -0
  239. package/src/fleet/scan-fleet.ts +3 -0
  240. package/src/gate/builtin-checks-dir.ts +32 -0
  241. package/src/gate/cache-audit.ts +7 -1
  242. package/src/gate/discover-checks.ts +9 -32
  243. package/src/gate/gate-checks.ts +14 -9
  244. package/src/gate/pre-commit-discovery.ts +214 -24
  245. package/src/gate/run-fix.ts +30 -5
  246. package/src/gate/run-fixers.ts +16 -3
  247. package/src/home/activity-shape.ts +2 -0
  248. package/src/home/activity.ts +2 -1
  249. package/src/home/advisors-tunnel-start.ts +9 -0
  250. package/src/home/autostart.ts +61 -17
  251. package/src/home/backup-status.ts +366 -0
  252. package/src/home/backup-verdict.ts +19 -0
  253. package/src/home/daemon-guard.ts +20 -2
  254. package/src/home/daemon-jobs.ts +203 -52
  255. package/src/home/database-words.ts +19 -2
  256. package/src/home/databases.ts +72 -25
  257. package/src/home/drives-deps.ts +54 -0
  258. package/src/home/follow-run.ts +146 -0
  259. package/src/home/global-context.ts +26 -22
  260. package/src/home/global-units.ts +3 -1
  261. package/src/home/gui-app/ShipkitGui.swift +3732 -286
  262. package/src/home/gui-app/icon.svg +8 -0
  263. package/src/home/gui-app.ts +93 -33
  264. package/src/home/handoff.ts +5 -3
  265. package/src/home/handover.ts +2 -10
  266. package/src/home/home-paths.ts +16 -7
  267. package/src/home/home-routes.ts +152 -38
  268. package/src/home/home-start.ts +27 -3
  269. package/src/home/inbox-shape.ts +9 -5
  270. package/src/home/log-follow.ts +117 -0
  271. package/src/home/machine-fold.ts +3 -11
  272. package/src/home/machine-host.ts +3 -17
  273. package/src/home/machine-stores.ts +8 -7
  274. package/src/home/open-app.ts +9 -3
  275. package/src/home/owner-switch-route.ts +33 -0
  276. package/src/home/page-build.ts +25 -5
  277. package/src/home/page-files.ts +79 -0
  278. package/src/home/page-held.ts +1 -1
  279. package/src/home/pm-config.ts +0 -8
  280. package/src/home/pm-switch.ts +10 -0
  281. package/src/home/pm.ts +74 -5
  282. package/src/home/process-apps.ts +82 -23
  283. package/src/home/process-rows.ts +16 -1
  284. package/src/home/push-sources.ts +31 -14
  285. package/src/home/resources.ts +16 -7
  286. package/src/home/resume.ts +8 -6
  287. package/src/home/run-daemon.ts +73 -7
  288. package/src/home/run-pm.ts +4 -4
  289. package/src/home/secrets-context.ts +119 -0
  290. package/src/home/serve-daemon.ts +13 -4
  291. package/src/home/serve-web.ts +152 -23
  292. package/src/home/shipkit-mark.ts +26 -0
  293. package/src/home/space-page.ts +4 -4
  294. package/src/home/space-route.ts +5 -12
  295. package/src/home/supervise.ts +4 -10
  296. package/src/home/vault-page.ts +41 -19
  297. package/src/home/vault-reveal.ts +2 -1
  298. package/src/home/web-places.ts +241 -0
  299. package/src/home/widgets.ts +16 -2
  300. package/src/hooks/commit-message.ts +11 -9
  301. package/src/hooks/commit-run.ts +420 -0
  302. package/src/hooks/git-hook.ts +49 -0
  303. package/src/hooks/held-calls.ts +104 -0
  304. package/src/hooks/hook-config.ts +104 -0
  305. package/src/hooks/hook-gates.ts +15 -9
  306. package/src/hooks/leak-guard.ts +15 -14
  307. package/src/hooks/one-way-in-guard.ts +156 -70
  308. package/src/hooks/pre-commit-checks.ts +64 -0
  309. package/src/hooks/root-identity.ts +15 -18
  310. package/src/hooks/run-hooks.ts +130 -293
  311. package/src/hooks/shared-file.ts +277 -84
  312. package/src/hooks/shell-writes.ts +526 -0
  313. package/src/hooks/staged.ts +245 -18
  314. package/src/hooks/write-log.ts +243 -0
  315. package/src/house/project-gutter.ts +32 -8
  316. package/src/hq/backup-targets.ts +74 -0
  317. package/src/hq/daemon-db.ts +177 -0
  318. package/src/hq/door-route.ts +68 -12
  319. package/src/hq/door.ts +71 -24
  320. package/src/hq/files-send.ts +23 -17
  321. package/src/hq/follow-fact.ts +66 -0
  322. package/src/hq/forgotten-log.ts +3 -1
  323. package/src/hq/history-check.ts +9 -0
  324. package/src/hq/history-send.ts +9 -23
  325. package/src/hq/holds-shape.ts +42 -0
  326. package/src/hq/hq-db.ts +25 -28
  327. package/src/hq/hq-holds.ts +181 -0
  328. package/src/hq/hq-local.ts +87 -49
  329. package/src/hq/hq-role.ts +150 -0
  330. package/src/hq/hq-routes.ts +18 -4
  331. package/src/hq/hq-store.ts +52 -13
  332. package/src/hq/item-direct.ts +57 -0
  333. package/src/hq/item-shapes.ts +54 -0
  334. package/src/hq/kinds/index.ts +3 -1
  335. package/src/hq/kinds/item-gone.ts +20 -12
  336. package/src/hq/kinds/item-msg.ts +21 -6
  337. package/src/hq/kinds/item.ts +22 -13
  338. package/src/hq/kinds/items-read.ts +4 -0
  339. package/src/hq/kinds/kind.ts +18 -4
  340. package/src/hq/kinds/presence-rule.ts +56 -0
  341. package/src/hq/kinds/presence.ts +228 -0
  342. package/src/hq/kinds/prompt.ts +1 -0
  343. package/src/hq/kinds/reflection.ts +1 -0
  344. package/src/hq/kinds/report.ts +13 -5
  345. package/src/hq/kinds/thread-event.ts +105 -0
  346. package/src/hq/lead-order.ts +68 -0
  347. package/src/hq/machine-key.ts +10 -3
  348. package/src/hq/machine-notes.ts +3 -2
  349. package/src/hq/outbox.ts +9 -153
  350. package/src/hq/owner-switch.ts +61 -0
  351. package/src/hq/replica.ts +168 -23
  352. package/src/hq/report-facts.ts +39 -9
  353. package/src/hq/report.ts +71 -2
  354. package/src/hq/shapes-words.ts +31 -0
  355. package/src/hq/switch.ts +29 -59
  356. package/src/hq/terminal-hop.ts +64 -0
  357. package/src/hq/thread-events.ts +91 -0
  358. package/src/hq/thread-sync.ts +39 -51
  359. package/src/http/door-forward.ts +13 -15
  360. package/src/http/door-names.ts +9 -0
  361. package/src/http/hop-caller.ts +23 -0
  362. package/src/http/hop-names.ts +14 -0
  363. package/src/http/loopback-serve.ts +28 -6
  364. package/src/http/owner-word.ts +133 -0
  365. package/src/http/same-origin.ts +12 -0
  366. package/src/{serve → http}/secret-gate.ts +3 -3
  367. package/src/identities/collection.ts +2 -3
  368. package/src/identities/identities.ts +43 -6
  369. package/src/init-repo.ts +12 -0
  370. package/src/ledger/db.ts +19 -6
  371. package/src/ledger/git-scan.ts +23 -9
  372. package/src/ledger/live-runs.ts +1 -12
  373. package/src/ledger/record-kept.ts +40 -12
  374. package/src/ledger/run-log.ts +25 -0
  375. package/src/media-store/backup/daemon.ts +37 -22
  376. package/src/media-store/backup/facts.ts +63 -0
  377. package/src/media-store/backup/prune.ts +2 -5
  378. package/src/media-store/backup/restore.ts +15 -4
  379. package/src/media-store/backup/retention.ts +2 -2
  380. package/src/media-store/backup/sources.ts +33 -68
  381. package/src/media-store/backup/ssh-space.ts +202 -0
  382. package/src/media-store/backup/ssh-target.ts +74 -0
  383. package/src/media-store/backup/target-send.ts +162 -0
  384. package/src/media-store/backup/watch.ts +26 -19
  385. package/src/media-store/copy/config.ts +15 -13
  386. package/src/media-store/copy/copy.ts +11 -6
  387. package/src/media-store/copy/proof.ts +17 -10
  388. package/src/media-store/copy/snapshot.ts +29 -22
  389. package/src/media-store/copy/store.ts +2 -10
  390. package/src/media-store/copy/stream.ts +7 -2
  391. package/src/media-store/daemon.ts +13 -7
  392. package/src/media-store/db.ts +6 -1
  393. package/src/media-store/forget-one.ts +14 -3
  394. package/src/media-store/hq-find.ts +1 -3
  395. package/src/media-store/hq-send.ts +4 -5
  396. package/src/media-store/put.ts +3 -0
  397. package/src/media-store/space.ts +14 -16
  398. package/src/media-store/upload.ts +4 -0
  399. package/src/messages/collection.ts +2 -2
  400. package/src/messages/model.ts +6 -1
  401. package/src/messages/routes.ts +3 -0
  402. package/src/orchestrator/brief.md +8 -6
  403. package/src/orchestrator/guards.ts +9 -3
  404. package/src/orchestrator/host.ts +35 -0
  405. package/src/orchestrator/lead-shape.ts +87 -0
  406. package/src/orchestrator/now.ts +88 -0
  407. package/src/orchestrator/phone.ts +4 -1
  408. package/src/orchestrator/places-file.ts +38 -0
  409. package/src/orchestrator/places-look.ts +208 -0
  410. package/src/orchestrator/places-shape.ts +166 -0
  411. package/src/orchestrator/places.ts +50 -0
  412. package/src/orchestrator/presence-shape.ts +13 -2
  413. package/src/orchestrator/presence.ts +41 -20
  414. package/src/orchestrator/push.ts +5 -10
  415. package/src/orchestrator/role-shape.ts +261 -0
  416. package/src/orchestrator/role.ts +191 -0
  417. package/src/orchestrator/routes.ts +155 -41
  418. package/src/orchestrator/sessions-shape.ts +123 -0
  419. package/src/orchestrator/sessions.ts +83 -0
  420. package/src/orchestrator/share.ts +71 -0
  421. package/src/orchestrator/start-notice.ts +61 -0
  422. package/src/orchestrator/start.ts +130 -0
  423. package/src/orchestrator/started.ts +55 -0
  424. package/src/orchestrator/stuck.ts +196 -0
  425. package/src/orchestrator/talk-key.ts +21 -0
  426. package/src/orchestrator/unheard.ts +18 -7
  427. package/src/pages/frame-client.ts +44 -6
  428. package/src/problems/failure-words.ts +80 -0
  429. package/src/recordings/recorder-app/Editor.swift +6 -0
  430. package/src/recordings/recorder-app/main.swift +3 -0
  431. package/src/reflections/reflection-close.ts +2 -1
  432. package/src/reflections/reflections-queue.ts +9 -6
  433. package/src/release/public-clean.ts +40 -15
  434. package/src/release/run-bump.ts +26 -5
  435. package/src/release/run-release.ts +34 -14
  436. package/src/repo-config.ts +54 -14
  437. package/src/review/answer-kinds.ts +15 -3
  438. package/src/review/aside-at.ts +19 -0
  439. package/src/review/band.ts +53 -16
  440. package/src/review/cell-copy.ts +27 -0
  441. package/src/review/cells.ts +246 -35
  442. package/src/review/doc-save.ts +1 -1
  443. package/src/review/events.ts +24 -4
  444. package/src/review/expect.ts +128 -0
  445. package/src/review/file-tags.ts +9 -0
  446. package/src/review/folders.ts +216 -0
  447. package/src/review/format.ts +113 -25
  448. package/src/review/gone.ts +10 -86
  449. package/src/review/hook-ask.ts +58 -0
  450. package/src/review/inbox-hook.ts +17 -6
  451. package/src/review/inbox-read.ts +99 -18
  452. package/src/review/instruction-guards.ts +192 -0
  453. package/src/review/instructions.ts +38 -2
  454. package/src/review/item-db.ts +157 -23
  455. package/src/review/item-hq.ts +119 -0
  456. package/src/review/item-rows.ts +96 -52
  457. package/src/review/kind-catalog.ts +2 -0
  458. package/src/review/kinds.ts +7 -4
  459. package/src/review/live-post.ts +20 -6
  460. package/src/review/live-view.ts +18 -1
  461. package/src/review/media-away.ts +35 -0
  462. package/src/review/mentions.ts +9 -10
  463. package/src/review/model.ts +126 -13
  464. package/src/review/notes.ts +4 -4
  465. package/src/review/object-read.ts +26 -7
  466. package/src/review/parties.ts +104 -19
  467. package/src/review/phone-push.ts +11 -10
  468. package/src/review/previews-job.ts +49 -0
  469. package/src/review/previews.ts +50 -28
  470. package/src/review/push.ts +56 -55
  471. package/src/review/referring.ts +2 -2
  472. package/src/review/reflection-object.ts +24 -11
  473. package/src/review/refs.ts +143 -0
  474. package/src/review/reply-guards.ts +71 -0
  475. package/src/review/routes.ts +99 -35
  476. package/src/review/search-index.ts +6 -10
  477. package/src/review/search-job.ts +4 -6
  478. package/src/review/search-ocr.ts +1 -1
  479. package/src/review/secret-route.ts +18 -14
  480. package/src/review/snooze.ts +1 -16
  481. package/src/review/store-index.ts +1 -1
  482. package/src/review/store-parties.ts +4 -2
  483. package/src/review/store.ts +171 -556
  484. package/src/review/supersede.ts +3 -3
  485. package/src/review/take-back.ts +1 -1
  486. package/src/review/thread-code.ts +101 -0
  487. package/src/review/thread-md.ts +127 -0
  488. package/src/review/thread-query.ts +67 -0
  489. package/src/review/threads.ts +104 -18
  490. package/src/review/traces.ts +17 -5
  491. package/src/review/unit.ts +3 -2
  492. package/src/review/verdict-items.ts +4 -4
  493. package/src/review/view-layout.ts +11 -1
  494. package/src/review/wait.ts +2 -2
  495. package/src/review/wakes.ts +7 -3
  496. package/src/review/watchers.ts +26 -14
  497. package/src/review/working-guards.ts +39 -0
  498. package/src/scaffold/jsonc-spans.ts +42 -0
  499. package/src/scaffold/starter-house.ts +85 -0
  500. package/src/secrets/about-words.ts +33 -0
  501. package/src/secrets/archive.ts +2 -2
  502. package/src/secrets/audit-run.ts +53 -0
  503. package/src/secrets/audit.ts +407 -0
  504. package/src/secrets/changed-mark.ts +15 -0
  505. package/src/secrets/clip.ts +29 -0
  506. package/src/secrets/held.ts +4 -4
  507. package/src/secrets/key-pair.ts +14 -0
  508. package/src/secrets/lapse.ts +3 -3
  509. package/src/secrets/list.ts +9 -4
  510. package/src/secrets/manager.ts +5 -1
  511. package/src/secrets/name-template.ts +83 -0
  512. package/src/secrets/name.ts +3 -0
  513. package/src/secrets/read.ts +15 -7
  514. package/src/secrets/ref-state.ts +18 -0
  515. package/src/secrets/registry-rows.ts +18 -0
  516. package/src/secrets/secret-ref.ts +42 -0
  517. package/src/secrets/secrets-view.ts +299 -0
  518. package/src/secrets/token-siblings.ts +60 -0
  519. package/src/secrets/who-reads.ts +27 -21
  520. package/src/serve/frame-part.ts +50 -0
  521. package/src/serve/hook-thread.ts +37 -0
  522. package/src/serve/hook-work.ts +92 -0
  523. package/src/serve/hook-worker.ts +57 -0
  524. package/src/serve/hub-app/accounts-line.tsx +33 -45
  525. package/src/serve/hub-app/activity-st.ts +6 -5
  526. package/src/serve/hub-app/activity-view.tsx +16 -15
  527. package/src/serve/hub-app/admin-view.tsx +7 -6
  528. package/src/serve/hub-app/advice-box.tsx +6 -5
  529. package/src/serve/hub-app/advisor-app.tsx +78 -13
  530. package/src/serve/hub-app/advisor-face.tsx +22 -7
  531. package/src/serve/hub-app/advisor-host.ts +102 -10
  532. package/src/serve/hub-app/advisor.html +1 -0
  533. package/src/serve/hub-app/advisors-model.ts +234 -0
  534. package/src/serve/hub-app/advisors-rights.tsx +66 -0
  535. package/src/serve/hub-app/advisors-st.ts +430 -34
  536. package/src/serve/hub-app/advisors-view.tsx +334 -195
  537. package/src/serve/hub-app/advisors.css +135 -18
  538. package/src/serve/hub-app/app-bridge.ts +124 -8
  539. package/src/serve/hub-app/ask-steps.tsx +6 -3
  540. package/src/serve/hub-app/asked-page.ts +24 -0
  541. package/src/serve/hub-app/asks-page.tsx +10 -6
  542. package/src/serve/hub-app/auto-text.tsx +50 -8
  543. package/src/serve/hub-app/backups-st.ts +55 -0
  544. package/src/serve/hub-app/backups-view.tsx +115 -0
  545. package/src/serve/hub-app/backups.css +33 -0
  546. package/src/serve/hub-app/card-head.tsx +3 -2
  547. package/src/serve/hub-app/check-view.tsx +16 -15
  548. package/src/serve/hub-app/checks-svc.ts +96 -32
  549. package/src/serve/hub-app/clock-svc.ts +24 -8
  550. package/src/serve/hub-app/code-copy.ts +1 -1
  551. package/src/serve/hub-app/col-card.tsx +6 -5
  552. package/src/serve/hub-app/col-list-page.tsx +14 -7
  553. package/src/serve/hub-app/col-list-st.ts +12 -2
  554. package/src/serve/hub-app/col-tables-view.tsx +8 -44
  555. package/src/serve/hub-app/col-tables.ts +5 -18
  556. package/src/serve/hub-app/cols-svc.ts +6 -12
  557. package/src/serve/hub-app/columns.ts +94 -0
  558. package/src/serve/hub-app/comfy-view.tsx +9 -8
  559. package/src/serve/hub-app/commands/commands-page.tsx +6 -5
  560. package/src/serve/hub-app/commands/commands-st.ts +2 -2
  561. package/src/serve/hub-app/controls.css +91 -24
  562. package/src/serve/hub-app/cycle-button.tsx +3 -2
  563. package/src/serve/hub-app/database-st.ts +41 -12
  564. package/src/serve/hub-app/database-view.tsx +71 -4
  565. package/src/serve/hub-app/database.css +3 -0
  566. package/src/serve/hub-app/deaf.tsx +27 -0
  567. package/src/serve/hub-app/dock-st.ts +21 -16
  568. package/src/serve/hub-app/dock-view.tsx +20 -13
  569. package/src/serve/hub-app/drives-page.tsx +309 -0
  570. package/src/serve/hub-app/drives-st.ts +486 -0
  571. package/src/serve/hub-app/drives.css +122 -0
  572. package/src/serve/hub-app/editor/doc-editor.tsx +4 -3
  573. package/src/serve/hub-app/empty-section.tsx +30 -0
  574. package/src/serve/hub-app/entry-bar.css +1 -1
  575. package/src/serve/hub-app/entry-bar.tsx +11 -6
  576. package/src/serve/hub-app/entry-list.css +32 -0
  577. package/src/serve/hub-app/entry-list.tsx +123 -0
  578. package/src/serve/hub-app/entry-pick.ts +1 -1
  579. package/src/serve/hub-app/entry-sections.ts +140 -0
  580. package/src/serve/hub-app/event-stream-reader.ts +56 -0
  581. package/src/serve/hub-app/floating.tsx +68 -15
  582. package/src/serve/hub-app/frame-refusal.ts +13 -0
  583. package/src/serve/hub-app/geometry-view.tsx +4 -3
  584. package/src/serve/hub-app/git-view.tsx +3 -2
  585. package/src/serve/hub-app/hash-route.ts +25 -6
  586. package/src/serve/hub-app/header-bar.tsx +54 -36
  587. package/src/serve/hub-app/home-pages.ts +40 -0
  588. package/src/serve/hub-app/home-st.ts +138 -14
  589. package/src/serve/hub-app/home-strip.css +24 -13
  590. package/src/serve/hub-app/home-strip.tsx +151 -84
  591. package/src/serve/hub-app/home.html +6 -0
  592. package/src/serve/hub-app/hub-app.tsx +108 -103
  593. package/src/serve/hub-app/hub.css +133 -99
  594. package/src/serve/hub-app/icons.tsx +24 -0
  595. package/src/serve/hub-app/identities-st.ts +19 -54
  596. package/src/serve/hub-app/identities-view.tsx +29 -27
  597. package/src/serve/hub-app/identity-address.ts +2 -2
  598. package/src/serve/hub-app/in-sight.ts +10 -0
  599. package/src/serve/hub-app/inbox-st.ts +20 -2
  600. package/src/serve/hub-app/inbox-view.tsx +26 -19
  601. package/src/serve/hub-app/inbox.css +1 -0
  602. package/src/serve/hub-app/index.html +6 -0
  603. package/src/serve/hub-app/insights-view.tsx +11 -10
  604. package/src/serve/hub-app/instructions.css +4 -1
  605. package/src/serve/hub-app/kept-cols.tsx +83 -20
  606. package/src/serve/hub-app/kept-width.tsx +76 -0
  607. package/src/serve/hub-app/keys.ts +143 -45
  608. package/src/serve/hub-app/layout-st.ts +113 -100
  609. package/src/serve/hub-app/lightbox-zoom.css +46 -0
  610. package/src/serve/hub-app/list-filter.tsx +58 -8
  611. package/src/serve/hub-app/list-head.tsx +29 -0
  612. package/src/serve/hub-app/list-row.ts +8 -0
  613. package/src/serve/hub-app/list-walk.ts +26 -105
  614. package/src/serve/hub-app/live-socket.ts +280 -0
  615. package/src/serve/hub-app/live-sources.ts +260 -0
  616. package/src/serve/hub-app/live-svc.ts +2 -2
  617. package/src/serve/hub-app/machine-groups.ts +87 -0
  618. package/src/serve/hub-app/machine-st.ts +75 -14
  619. package/src/serve/hub-app/machines-st.ts +100 -3
  620. package/src/serve/hub-app/machines-view.tsx +50 -3
  621. package/src/serve/hub-app/machines.css +22 -0
  622. package/src/serve/hub-app/main-panel.css +217 -0
  623. package/src/serve/hub-app/main-panel.tsx +257 -0
  624. package/src/serve/hub-app/markdown.css +12 -2
  625. package/src/serve/hub-app/md.ts +64 -22
  626. package/src/serve/hub-app/media-svc.ts +5 -5
  627. package/src/serve/hub-app/media-view.tsx +32 -22
  628. package/src/serve/hub-app/messages/messages-page.tsx +22 -12
  629. package/src/serve/hub-app/messages/messages-st.ts +5 -2
  630. package/src/serve/hub-app/new-thread-st.ts +170 -0
  631. package/src/serve/hub-app/new-thread.tsx +136 -107
  632. package/src/serve/hub-app/orchestrator-line.tsx +115 -45
  633. package/src/serve/hub-app/orchestrator-places.tsx +112 -0
  634. package/src/serve/hub-app/orchestrator.css +62 -5
  635. package/src/serve/hub-app/page-keys.ts +109 -67
  636. package/src/serve/hub-app/page-reload.ts +46 -6
  637. package/src/serve/hub-app/pages-frames.tsx +42 -4
  638. package/src/serve/hub-app/pages-svc.ts +3 -1
  639. package/src/serve/hub-app/palette-st.ts +450 -70
  640. package/src/serve/hub-app/palette-view.tsx +123 -21
  641. package/src/serve/hub-app/pane-boundary.tsx +3 -2
  642. package/src/serve/hub-app/panel-head-action.tsx +39 -0
  643. package/src/serve/hub-app/panel-head.tsx +70 -0
  644. package/src/serve/hub-app/panel-repo.ts +42 -0
  645. package/src/serve/hub-app/panel-source.ts +206 -0
  646. package/src/serve/hub-app/panel-tint.ts +8 -0
  647. package/src/serve/hub-app/panel-walk.ts +107 -0
  648. package/src/serve/hub-app/pic.tsx +37 -0
  649. package/src/serve/hub-app/pick-kinds.ts +101 -0
  650. package/src/serve/hub-app/pill-row.tsx +2 -1
  651. package/src/serve/hub-app/place-path.ts +4 -0
  652. package/src/serve/hub-app/places-svc.ts +109 -0
  653. package/src/serve/hub-app/plan-view.tsx +4 -3
  654. package/src/serve/hub-app/planned-view.tsx +6 -5
  655. package/src/serve/hub-app/polled.ts +25 -4
  656. package/src/serve/hub-app/presence-st.ts +74 -32
  657. package/src/serve/hub-app/processes-view.tsx +18 -12
  658. package/src/serve/hub-app/project-bar.tsx +172 -0
  659. package/src/serve/hub-app/project-list.css +20 -173
  660. package/src/serve/hub-app/project-list.tsx +27 -307
  661. package/src/serve/hub-app/projects-svc.ts +102 -45
  662. package/src/serve/hub-app/push-sign.tsx +2 -1
  663. package/src/serve/hub-app/push-svc.ts +86 -69
  664. package/src/serve/hub-app/quiet-st.ts +5 -3
  665. package/src/serve/hub-app/rail-groups.ts +145 -0
  666. package/src/serve/hub-app/reader-chips.tsx +2 -1
  667. package/src/serve/hub-app/recordings-st.ts +2 -1
  668. package/src/serve/hub-app/recordings-view.tsx +42 -70
  669. package/src/serve/hub-app/recordings.css +0 -2
  670. package/src/serve/hub-app/ref-list-slot.ts +10 -0
  671. package/src/serve/hub-app/ref-pill.ts +58 -0
  672. package/src/serve/hub-app/reflections-page.tsx +12 -8
  673. package/src/serve/hub-app/releases/releases-page.tsx +11 -10
  674. package/src/serve/hub-app/repo-mark.tsx +29 -0
  675. package/src/serve/hub-app/repo-sections.ts +137 -41
  676. package/src/serve/hub-app/repo-st.ts +116 -42
  677. package/src/serve/hub-app/review/advisor-add.tsx +155 -0
  678. package/src/serve/hub-app/review/advisor-bar.tsx +93 -22
  679. package/src/serve/hub-app/review/advisor-invite.tsx +66 -0
  680. package/src/serve/hub-app/review/ask-proof.tsx +80 -0
  681. package/src/serve/hub-app/review/attach-view.tsx +16 -14
  682. package/src/serve/hub-app/review/box-view.ts +496 -0
  683. package/src/serve/hub-app/review/box-zoom.tsx +70 -0
  684. package/src/serve/hub-app/review/copy-button.tsx +29 -0
  685. package/src/serve/hub-app/review/diff-mode.ts +41 -0
  686. package/src/serve/hub-app/review/diff-view.tsx +95 -21
  687. package/src/serve/hub-app/review/doc-body.tsx +4 -3
  688. package/src/serve/hub-app/review/dock.tsx +54 -25
  689. package/src/serve/hub-app/review/draft-body.tsx +6 -5
  690. package/src/serve/hub-app/review/faces.tsx +0 -8
  691. package/src/serve/hub-app/review/group-block.tsx +11 -10
  692. package/src/serve/hub-app/review/heard-line.tsx +4 -3
  693. package/src/serve/hub-app/review/instructions-view.tsx +6 -11
  694. package/src/serve/hub-app/review/item-verdict.tsx +41 -40
  695. package/src/serve/hub-app/review/kind-states.tsx +5 -4
  696. package/src/serve/hub-app/review/kind-view.tsx +13 -19
  697. package/src/serve/hub-app/review/kit.tsx +37 -9
  698. package/src/serve/hub-app/review/lane-bar.tsx +30 -28
  699. package/src/serve/hub-app/review/lightbox.tsx +6 -4
  700. package/src/serve/hub-app/review/line-window.ts +51 -8
  701. package/src/serve/hub-app/review/live-bar.tsx +11 -7
  702. package/src/serve/hub-app/review/live-view.tsx +14 -13
  703. package/src/serve/hub-app/review/mention-st.ts +9 -38
  704. package/src/serve/hub-app/review/object-card.tsx +2 -1
  705. package/src/serve/hub-app/review/object-panel.tsx +49 -23
  706. package/src/serve/hub-app/review/outbox-st.ts +200 -0
  707. package/src/serve/hub-app/review/pano-view.tsx +4 -3
  708. package/src/serve/hub-app/review/phone-top.tsx +2 -1
  709. package/src/serve/hub-app/review/question-views.tsx +176 -43
  710. package/src/serve/hub-app/review/review-cells.tsx +215 -57
  711. package/src/serve/hub-app/review/review-host.ts +13 -1
  712. package/src/serve/hub-app/review/review-kit.ts +28 -10
  713. package/src/serve/hub-app/review/review-list.tsx +136 -129
  714. package/src/serve/hub-app/review/review-page.tsx +8 -7
  715. package/src/serve/hub-app/review/review-st.ts +138 -28
  716. package/src/serve/hub-app/review/review-thread.tsx +444 -228
  717. package/src/serve/hub-app/review/review-views.tsx +248 -235
  718. package/src/serve/hub-app/review/secret-facts.ts +2 -1
  719. package/src/serve/hub-app/review/share-lines.tsx +40 -0
  720. package/src/serve/hub-app/review/space3d.tsx +17 -9
  721. package/src/serve/hub-app/review/start-st.ts +137 -0
  722. package/src/serve/hub-app/review/start-thread.tsx +104 -0
  723. package/src/serve/hub-app/review/superseded-runs.ts +20 -2
  724. package/src/serve/hub-app/review/thread-close.tsx +24 -32
  725. package/src/serve/hub-app/review/thread-control.tsx +5 -4
  726. package/src/serve/hub-app/review/thread-st.ts +293 -65
  727. package/src/serve/hub-app/review/thread-views.ts +3 -2
  728. package/src/serve/hub-app/review/trailer-body.tsx +7 -6
  729. package/src/serve/hub-app/review/trailer-page.tsx +46 -44
  730. package/src/serve/hub-app/review/trailer-st.ts +3 -2
  731. package/src/serve/hub-app/review/trailer-timeline.tsx +10 -9
  732. package/src/serve/hub-app/review/trailer-voices.tsx +31 -30
  733. package/src/serve/hub-app/review/zoom-still.tsx +60 -0
  734. package/src/serve/hub-app/review.css +319 -79
  735. package/src/serve/hub-app/row-acts.tsx +128 -0
  736. package/src/serve/hub-app/row-face.tsx +28 -0
  737. package/src/serve/hub-app/run-page.tsx +236 -0
  738. package/src/serve/hub-app/running-rows.tsx +142 -0
  739. package/src/serve/hub-app/running-st.ts +110 -0
  740. package/src/serve/hub-app/search-view.tsx +4 -3
  741. package/src/serve/hub-app/secret-cli.tsx +32 -0
  742. package/src/serve/hub-app/secret-readable.tsx +59 -0
  743. package/src/serve/hub-app/secret-refs.ts +173 -0
  744. package/src/serve/hub-app/secrets-page.tsx +290 -0
  745. package/src/serve/hub-app/secrets-st.ts +181 -0
  746. package/src/serve/hub-app/secrets.css +65 -0
  747. package/src/serve/hub-app/section-head.tsx +5 -2
  748. package/src/serve/hub-app/seen-rows.ts +72 -0
  749. package/src/serve/hub-app/session-chips.tsx +55 -0
  750. package/src/serve/hub-app/shared-faces.tsx +32 -0
  751. package/src/serve/hub-app/shell.ts +56 -0
  752. package/src/serve/hub-app/side-frame-view.tsx +115 -0
  753. package/src/serve/hub-app/side-frame.ts +120 -0
  754. package/src/serve/hub-app/site/site-part.tsx +12 -11
  755. package/src/serve/hub-app/site/site-st.ts +0 -6
  756. package/src/serve/hub-app/site.css +0 -1
  757. package/src/serve/hub-app/social/calendar.tsx +8 -7
  758. package/src/serve/hub-app/social/comms-page.tsx +32 -29
  759. package/src/serve/hub-app/social/copy-forms.ts +31 -0
  760. package/src/serve/hub-app/social/group-editor.tsx +2 -1
  761. package/src/serve/hub-app/social/kit.tsx +48 -28
  762. package/src/serve/hub-app/social/next-release.tsx +3 -2
  763. package/src/serve/hub-app/social/post-card.tsx +26 -25
  764. package/src/serve/hub-app/social/post-page.tsx +4 -3
  765. package/src/serve/hub-app/social/problems.tsx +3 -2
  766. package/src/serve/hub-app/social/social-page.tsx +58 -37
  767. package/src/serve/hub-app/social/social-st.ts +12 -4
  768. package/src/serve/hub-app/social/stage-popup.tsx +15 -14
  769. package/src/serve/hub-app/social.css +14 -6
  770. package/src/serve/hub-app/source-acts.ts +79 -0
  771. package/src/serve/hub-app/source-page.tsx +19 -0
  772. package/src/serve/hub-app/space-view.tsx +8 -7
  773. package/src/serve/hub-app/stores/stores-page.tsx +32 -29
  774. package/src/serve/hub-app/stores/stores-st.ts +1 -1
  775. package/src/serve/hub-app/stores.css +1 -1
  776. package/src/serve/hub-app/terminal-gone.tsx +41 -0
  777. package/src/serve/hub-app/terminal-history-st.ts +115 -0
  778. package/src/serve/hub-app/terminal-keys.ts +79 -0
  779. package/src/serve/hub-app/terminal-lib.ts +110 -0
  780. package/src/serve/hub-app/terminal-links.ts +55 -0
  781. package/src/serve/hub-app/terminal-list-st.ts +328 -0
  782. package/src/serve/hub-app/terminal-log-st.ts +242 -0
  783. package/src/serve/hub-app/terminal-out.ts +135 -0
  784. package/src/serve/hub-app/terminal-pages.tsx +155 -0
  785. package/src/serve/hub-app/terminal-panel.tsx +62 -11
  786. package/src/serve/hub-app/terminal-picture.ts +78 -0
  787. package/src/serve/hub-app/terminal-sources.tsx +605 -0
  788. package/src/serve/hub-app/terminal-st.ts +503 -168
  789. package/src/serve/hub-app/terminal-stream.ts +233 -0
  790. package/src/serve/hub-app/terminal-tab.tsx +65 -0
  791. package/src/serve/hub-app/terminal-widths.ts +30 -0
  792. package/src/serve/hub-app/terminal.css +55 -4
  793. package/src/serve/hub-app/test-view.tsx +7 -5
  794. package/src/serve/hub-app/tests-view.tsx +19 -18
  795. package/src/serve/hub-app/theme-st.ts +5 -0
  796. package/src/serve/hub-app/thread-row.tsx +49 -31
  797. package/src/serve/hub-app/time-ago.tsx +3 -2
  798. package/src/serve/hub-app/time-charts.tsx +3 -2
  799. package/src/serve/hub-app/time-pages.tsx +3 -2
  800. package/src/serve/hub-app/time-view.tsx +8 -6
  801. package/src/serve/hub-app/time.css +1 -1
  802. package/src/serve/hub-app/timeline-chart.tsx +5 -4
  803. package/src/serve/hub-app/timeline-view.tsx +22 -13
  804. package/src/serve/hub-app/tips.ts +247 -0
  805. package/src/serve/hub-app/tree-build.ts +40 -8
  806. package/src/serve/hub-app/tree-svc.ts +167 -134
  807. package/src/serve/hub-app/unit-icons.ts +26 -0
  808. package/src/serve/hub-app/url-address.ts +154 -0
  809. package/src/serve/hub-app/url-faces.ts +87 -0
  810. package/src/serve/hub-app/url-forms.tsx +275 -0
  811. package/src/serve/hub-app/url-needs.ts +31 -0
  812. package/src/serve/hub-app/urls-svc.ts +321 -21
  813. package/src/serve/hub-app/urls-view.tsx +114 -78
  814. package/src/serve/hub-app/urls.css +85 -2
  815. package/src/serve/hub-app/vault-view.tsx +18 -17
  816. package/src/serve/hub-app/veille/veille-page.tsx +42 -40
  817. package/src/serve/hub-app/veille/veille-st.ts +6 -3
  818. package/src/serve/hub-app/view-layout.css +5 -3
  819. package/src/serve/hub-app/when-view.tsx +6 -5
  820. package/src/serve/hub-app/wikis-view.tsx +7 -6
  821. package/src/serve/hub-app/word-refs.ts +12 -0
  822. package/src/serve/hub-app/words.tsx +30 -6
  823. package/src/serve/hub-runtime.ts +3 -2
  824. package/src/serve/orchestrator-host.ts +58 -0
  825. package/src/serve/page-live.ts +147 -0
  826. package/src/serve/picture-types.ts +10 -0
  827. package/src/serve/project-gutter-route.ts +81 -15
  828. package/src/serve/read-thread.ts +31 -12
  829. package/src/serve/read-worker.ts +14 -2
  830. package/src/serve/runs-stamp.ts +33 -0
  831. package/src/serve/secret-ref-routes.ts +71 -0
  832. package/src/serve/secrets-read.ts +156 -0
  833. package/src/serve/serve-hub.ts +97 -23
  834. package/src/serve/terminal-claudes.ts +222 -0
  835. package/src/serve/terminal-guard.ts +15 -6
  836. package/src/serve/terminal-host.ts +521 -0
  837. package/src/serve/terminal-paste.ts +49 -0
  838. package/src/serve/terminal-record.ts +110 -0
  839. package/src/serve/terminal-route.ts +479 -103
  840. package/src/serve/terminal-shells.ts +3 -0
  841. package/src/serve/terminal-watch.ts +102 -0
  842. package/src/serve/tracked-watch.ts +13 -11
  843. package/src/setup-house.ts +333 -0
  844. package/src/shipkit-files.ts +23 -7
  845. package/src/shot/client.ts +4 -9
  846. package/src/shot/film-box.ts +1 -9
  847. package/src/shot/shooter.ts +2 -4
  848. package/src/shot/shot-ask.ts +2 -7
  849. package/src/shot/shot-theme.ts +6 -17
  850. package/src/social/discord-layout.ts +1 -1
  851. package/src/social/kind-pages.ts +11 -5
  852. package/src/social/media-limit.ts +18 -8
  853. package/src/social/media-of.ts +5 -5
  854. package/src/social/publish/discord.ts +1 -1
  855. package/src/social/routes.ts +8 -5
  856. package/src/social/writes.ts +3 -0
  857. package/src/start-repo.ts +5 -0
  858. package/src/suite/judge-suites.ts +9 -51
  859. package/src/suite/red-alone.ts +69 -0
  860. package/src/suite/suite-cli.ts +27 -26
  861. package/src/suite/test-units.ts +6 -2
  862. package/src/trailer/sound/eleven.ts +1 -0
  863. package/src/trailer/titles.ts +2 -2
  864. package/src/urls/added.ts +130 -0
  865. package/src/urls/fill.ts +127 -0
  866. package/src/urls/frame.ts +39 -0
  867. package/src/urls/icons.ts +294 -0
  868. package/src/urls/places.ts +145 -0
  869. package/src/urls/routes.ts +43 -13
  870. package/src/urls/rows.ts +133 -25
  871. package/src/urls/totp.ts +121 -0
  872. package/src/urls/unit.ts +123 -10
  873. package/src/urls/write-routes.ts +323 -0
  874. package/src/vault/vault-destroy.ts +2 -1
  875. package/src/vault/vault-import.ts +6 -20
  876. package/src/vault/vault-init.ts +2 -1
  877. package/src/vault/vault-restore.ts +4 -11
  878. package/src/veille/chrome.ts +7 -2
  879. package/src/veille/identity.ts +12 -5
  880. package/src/view3d/cam.ts +30 -46
  881. package/src/view3d/lib.ts +20 -2
  882. package/src/view3d/viewer.ts +62 -88
  883. package/src/wiki/agent-paths.ts +2 -1
  884. package/src/wiki/graph-page.ts +27 -37
  885. package/src/wiki/graph-positions.ts +13 -3
  886. package/src/wiki/graph-sim.ts +77 -0
  887. package/src/wiki/run-wiki.ts +12 -1
  888. package/src/advisors/edge/certs.ts +0 -20
  889. package/src/advisors/edge/jwt.ts +0 -76
  890. package/src/advisors/edge/worker.ts +0 -52
  891. package/src/advisors/r2.ts +0 -48
  892. package/src/media-store/backup/thread-copy.ts +0 -339
  893. package/src/orchestrator/deliver.ts +0 -81
  894. package/src/orchestrator/drill.ts +0 -129
  895. package/src/orchestrator/keeper.ts +0 -332
  896. package/src/orchestrator/pm.ts +0 -20
  897. package/src/orchestrator/state.ts +0 -92
  898. package/src/orchestrator/switch.ts +0 -86
  899. package/src/orchestrator/tmux.ts +0 -82
  900. package/src/review/move.ts +0 -492
  901. package/src/serve/hub-app/rail-fly.tsx +0 -95
  902. package/src/serve/hub-app/side-lists.ts +0 -72
  903. package/src/serve/hub-app/sidebar.tsx +0 -62
  904. package/src/serve/hub-app/tree-row.tsx +0 -125
@@ -1,22 +1,109 @@
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
20
+ import CryptoKit
12
21
  import UserNotifications
13
22
  import WebKit
14
23
 
15
24
  let info = Bundle.main.infoDictionary ?? [:]
16
25
  let appName = (info["CFBundleName"] as? String) ?? "shipkit"
17
26
  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"
27
+ /** 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 */
28
+ let mode = (info["ShipkitMode"] as? String) ?? (Bundle.main.bundleIdentifier == "dev.shipkit.gui" ? "home" : "process")
29
+ /** the shipkit app itself: the house's badge and the notifications */
30
+ let isShipkit = mode == "home"
31
+ /** a project app's repo: its badge counts that repo's threads alone */
32
+ let projectRepo: String? = mode == "project" ? info["ShipkitRepo"] as? String : nil
33
+ /** the apps that wear a badge: the home's stays running with no window to keep it live, a project app's lives with
34
+ * its windows (closing the last one quits it: one hub page alive per app open, never a hidden one) */
35
+ let hasBadge = isShipkit || projectRepo != nil
36
+ /** a project app: one window, every page a native tab of it */
37
+ let tabbed = projectRepo != nil
38
+ /** a self test runs (`--self-test-…`): nothing it loads is kept on disk, and no window, sheet or alert of it ever
39
+ * reaches a screen. No flag brings a visible self test back: its windows are real and never ordered in */
40
+ let selfTesting = CommandLine.arguments.contains { $0.hasPrefix("--self-test") }
41
+
42
+ /** the windows the window server has on a screen: this process's, and every process's (the control: the menu bar and
43
+ * the Dock are always there, so a count of none means the server answered nothing) */
44
+ func windowsOnScreen() -> (own: Int, all: Int) {
45
+ let pid = ProcessInfo.processInfo.processIdentifier
46
+ let all = (CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]]) ?? []
47
+ return (all.filter { ($0[kCGWindowOwnerPID as String] as? Int32) == pid }.count, all.count)
48
+ }
49
+ /** the most windows a self test had on a screen at once, as the window server counted them through its run */
50
+ var seenOnScreen = 0
51
+
52
+ /** 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
53
+ * no list to count in */
54
+ func finish(_ code: Int32) -> Never {
55
+ let now = windowsOnScreen()
56
+ seenOnScreen = max(seenOnScreen, now.own)
57
+ print("windows-on-screen=\(seenOnScreen) of \(now.all > 0 ? "some" : "none") the window server lists")
58
+ if seenOnScreen > 0 { print("refused: a self test put a window on the screen") }
59
+ if now.all == 0 { print("refused: the window server listed no window at all, so the count proves nothing") }
60
+ exit(seenOnScreen > 0 || now.all == 0 ? 1 : code)
61
+ }
62
+
63
+ /** a self test asked for a window on the screen: said once, and nothing shows */
64
+ var refusedScreen = false
65
+ func refuseScreen() {
66
+ if refusedScreen { return }
67
+ refusedScreen = true
68
+ FileHandle.standardError.write("shipkit: a self test shows no window: an order to the screen was refused\n".data(using: .utf8)!)
69
+ }
70
+
71
+ /** the repo a page of the hub belongs to (`/r/<repo>/…`), nil for any other page */
72
+ func repoOf(_ url: URL) -> String? {
73
+ let parts = url.path.split(separator: "/", omittingEmptySubsequences: true)
74
+ return parts.count >= 2 && parts[0] == "r" ? String(parts[1]).removingPercentEncoding : nil
75
+ }
76
+
77
+ /** the build a bundle carries (home/gui-app.ts writes it): the running copy compares it with its bundle's on disk */
78
+ func stampOnDisk() -> String? { try? String(contentsOfFile: Bundle.main.bundlePath + "/Contents/Resources/stamp", encoding: .utf8) }
79
+ let launchedStamp = stampOnDisk()
80
+
81
+ /** a #rrggbb as a colour, nil for anything else */
82
+ func colorOf(_ hex: String?) -> NSColor? {
83
+ guard let hex, hex.count == 7, hex.hasPrefix("#"), let n = Int(hex.dropFirst(), radix: 16) else { return nil }
84
+ return NSColor(srgbRed: CGFloat((n >> 16) & 255) / 255, green: CGFloat((n >> 8) & 255) / 255, blue: CGFloat(n & 255) / 255, alpha: 1)
85
+ }
86
+ /** the repo's window colour and the text that reads on it (home/gui-app.ts writes both); none: the system's chrome */
87
+ let tint = colorOf(info["ShipkitTint"] as? String)
88
+ let tintText = colorOf(info["ShipkitTintText"] as? String)
89
+
90
+ /** 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
91
+ * the colour, and the appearance follows the text that reads on it (light text: the dark appearance) */
92
+ func paint(_ win: NSWindow, _ color: NSColor?, text: NSColor?) {
93
+ guard let color else { return }
94
+ win.titlebarAppearsTransparent = true
95
+ win.backgroundColor = color
96
+ let light = (text?.usingColorSpace(.sRGB)?.brightnessComponent ?? 1) > 0.5
97
+ win.appearance = NSAppearance(named: light ? .darkAqua : .aqua)
98
+ }
99
+
100
+ /** 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
101
+ * post carries no count */
102
+ func badgeCount(_ body: [String: Any], repo: String?) -> Int? {
103
+ guard let total = body["waiting"] as? Int else { return nil }
104
+ guard let repo else { return total }
105
+ return ((body["repos"] as? [String: Any])?[repo] as? Int) ?? 0
106
+ }
20
107
 
21
108
  /** a thread that started waiting, as the page posts it */
22
109
  struct WaitingThread {
@@ -55,6 +142,123 @@ func stays(_ url: URL) -> Bool {
55
142
  url.host == "127.0.0.1" || url.host == "localhost" || url.host == startURL.host
56
143
  }
57
144
 
145
+ /** a page of the hub itself: the start url's host and port */
146
+ func isHub(_ url: URL) -> Bool { url.host == startURL.host && url.port == startURL.port }
147
+
148
+ /** the site a host belongs to: the machine for every loopback name, the last two labels of a dotted name
149
+ * (app.example.com and auth.example.com are one site, so a sign in on the second stays in the tab), else the host.
150
+ * No public suffix list: two sites under a two label suffix (co.uk) read as one, and such a link stays in the tab */
151
+ func siteOf(_ url: URL?) -> String? {
152
+ guard let host = url?.host?.lowercased() else { return nil }
153
+ if host == "127.0.0.1" || host == "localhost" || host.hasSuffix(".localhost") { return "this machine" }
154
+ let labels = host.split(separator: ".")
155
+ if labels.count < 3 || labels.allSatisfy({ Int($0) != nil }) { return host }
156
+ return labels.suffix(2).joined(separator: ".")
157
+ }
158
+
159
+ /** scheme, host and port: a url the project declares covers every page of its origin */
160
+ func originOf(_ url: URL) -> String { "\(url.scheme?.lowercased() ?? "")://\(url.host?.lowercased() ?? ""):\(url.port ?? (url.scheme?.lowercased() == "https" ? 443 : 80))" }
161
+
162
+ /** what a tab is found by: its address with no closing slash. A page of the hub keeps its fragment, the entry it
163
+ * shows (`#page:src:terminals:<id>`): two entries are two tabs. Any other page loses it */
164
+ func tabKey(_ url: URL) -> String {
165
+ var c = URLComponents(url: url, resolvingAgainstBaseURL: true)
166
+ if !isHub(url) || c?.fragment?.isEmpty == true { c?.fragment = nil }
167
+ let s = c?.string ?? url.absoluteString
168
+ return s.hasSuffix("/") ? String(s.dropLast()) : s
169
+ }
170
+
171
+ /** 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 */
172
+ let hubApp = isShipkit || tabbed
173
+
174
+ /** an origin as a page's script reads it (`location.origin`): no port where it is the scheme's own */
175
+ func pageOrigin(_ url: URL) -> String {
176
+ let scheme = url.scheme?.lowercased() ?? "http"
177
+ let port = url.port.flatMap { $0 == (scheme == "https" ? 443 : 80) ? nil : ":\($0)" } ?? ""
178
+ return "\(scheme)://\(url.host?.lowercased() ?? "")\(port)"
179
+ }
180
+
181
+ /** a string as a script's literal */
182
+ func jsString(_ s: String) -> String {
183
+ guard let data = try? JSONSerialization.data(withJSONObject: [s]), let json = String(data: data, encoding: .utf8) else { return "\"\"" }
184
+ return String(json.dropFirst().dropLast())
185
+ }
186
+
187
+ /** what a framed site says of its address to the hub page that frames it (serve/hub-app/url-address.ts hears it), so
188
+ * 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
189
+ * origin, so this one does nothing by itself: one listener, in a frame right under the top page. It wakes only when
190
+ * the page of `hub`, its parent, asks, and the page posts its ask to the origin of the url it declared and to no
191
+ * other, so a frame of any other origin never hears it. Awake it reads `location.href`, nothing else of the page,
192
+ * and posts it to `hub` alone: at the ask, on a fragment move, a history move and a router's push */
193
+ func reporterScript(hub: String) -> String {
194
+ """
195
+ (() => {
196
+ if (window === top || parent !== top) return
197
+ const HUB = \(jsString(hub))
198
+ let on = false
199
+ const say = () => { try { parent.postMessage({ skAddress: location.href }, HUB) } catch (e) {} }
200
+ addEventListener('message', (e) => {
201
+ if (e.source !== parent || e.origin !== HUB || e.data == null || e.data.skAddressAsk !== true) return
202
+ if (!on) {
203
+ on = true
204
+ for (const t of ['hashchange', 'popstate']) addEventListener(t, say)
205
+ for (const k of ['pushState', 'replaceState']) {
206
+ const f = history[k]
207
+ history[k] = function () { const r = f.apply(this, arguments); say(); return r }
208
+ }
209
+ }
210
+ say()
211
+ })
212
+ })()
213
+ """
214
+ }
215
+
216
+ /** the tab command with a digit selects among `count`, as a browser: 1 to 8 that tab, 9 the last; nil: there is none */
217
+ func tabIndex(digit: Int, count: Int) -> Int? {
218
+ if count < 1 { return nil }
219
+ if digit == 9 { return count - 1 }
220
+ return digit >= 1 && digit <= count ? digit - 1 : nil
221
+ }
222
+
223
+ /** 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
224
+ * app's page keeps them */
225
+ func tabDigits(_ mode: String) -> [Int] { mode == "project" ? Array(1...9) : [] }
226
+
227
+ /** where a main frame's navigation goes in a project app */
228
+ enum Road: Equatable {
229
+ /** in the page that asked */
230
+ case here
231
+ /** a tab of this window: the one open on it, else a new one */
232
+ case tab
233
+ /** a tab when the project declares the url (its `sk urls` rows, its global processes among them), else outside */
234
+ case declared
235
+ /** the default browser, or the app of the url's scheme */
236
+ case outside
237
+ /** another repo's own app */
238
+ case app(String)
239
+ }
240
+
241
+ /** `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
242
+ * a new window (target=_blank, window.open); `click`: a link clicked. The hub's pages never turn into another site:
243
+ * the machine's other servers and the project's urls become tabs, any other site leaves. A tab of another site keeps
244
+ * its site (the one it was opened on, the one it shows), and a link out of it leaves */
245
+ func road(to url: URL, from: URL?, home: URL?, new: Bool, click: Bool, repo: String?) -> Road {
246
+ switch url.scheme?.lowercased() {
247
+ case "http", "https": break
248
+ case nil, "about", "data", "blob", "javascript", "file": return .here
249
+ default: return click || new ? .outside : .here
250
+ }
251
+ if isHub(url) {
252
+ if let own = repo, let other = repoOf(url), other != own { return .app(other) }
253
+ return new ? .tab : .here
254
+ }
255
+ guard let from else { return .here }
256
+ if isHub(from) { return siteOf(url) == "this machine" ? .tab : .declared }
257
+ let site = siteOf(url)
258
+ if site == siteOf(from) || site == siteOf(home) { return new ? .tab : .here }
259
+ return click || new ? .outside : .here
260
+ }
261
+
58
262
  /** 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
263
  * another host, a mail address, any other app's scheme; the page's own data, blob and about urls stay */
60
264
  func leaves(_ url: URL) -> Bool {
@@ -71,14 +275,133 @@ func leaves(_ url: URL) -> Bool {
71
275
  // a window whose unhandled key makes no system beep: a key nobody took (the page, the menus) ends in the window's
72
276
  // noResponder, which beeps; the pane marks it in a corner instead
73
277
  final class QuietWindow: NSWindow {
278
+ // every window of the app is this one, so a self test's never reaches a screen: each order in is refused
279
+ override func order(_ place: NSWindow.OrderingMode, relativeTo other: Int) { if selfTesting && place != .out { return refuseScreen() }; super.order(place, relativeTo: other) }
280
+ override func makeKeyAndOrderFront(_ sender: Any?) { if selfTesting { return refuseScreen() }; super.makeKeyAndOrderFront(sender) }
281
+ override func orderFront(_ sender: Any?) { if selfTesting { return refuseScreen() }; super.orderFront(sender) }
282
+ override func orderFrontRegardless() { if selfTesting { return refuseScreen() }; super.orderFrontRegardless() }
283
+
284
+ // AppKit's performClose presses the window's red button, which closes every tab of a project app: a close asked
285
+ // of one tab this way (the tab bar's « close other tabs », a script) is that tab's alone
286
+ override func performClose(_ sender: Any?) {
287
+ if tabbed, let d = delegate as? Delegate { return d.closeTab(of: self) }
288
+ super.performClose(sender)
289
+ }
290
+
74
291
  override func noResponder(for eventSelector: Selector) {
75
292
  if eventSelector == #selector(NSResponder.keyDown(with:)), let pane = contentView as? Pane { return pane.blink() }
76
293
  super.noResponder(for: eventSelector)
77
294
  }
78
295
  }
79
296
 
297
+ /** 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
298
+ * this window, whatever its site: the one road by which a page of another site gets a tab here */
299
+ final class Web: WKWebView {
300
+ static let linkItem = "WKMenuItemIdentifierOpenLinkInNewWindow"
301
+ /** the next new window this page asks is a tab here; the menu's item sets it for its own ask alone */
302
+ var tabNext = false
303
+ private var forward: (target: AnyObject?, action: Selector?) = (nil, nil)
304
+
305
+ override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {
306
+ super.willOpenMenu(menu, with: event)
307
+ guard tabbed else { return }
308
+ for item in menu.items where item.identifier?.rawValue == Web.linkItem {
309
+ item.title = "Open in a Tab Here"
310
+ forward = (item.target, item.action)
311
+ item.target = self
312
+ item.action = #selector(openLinkInTab(_:))
313
+ }
314
+ }
315
+
316
+ @objc func openLinkInTab(_ sender: NSMenuItem) {
317
+ tabNext = true
318
+ if let action = forward.action { NSApp.sendAction(action, to: forward.target, from: sender) }
319
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.tabNext = false }
320
+ }
321
+
322
+ /** command V with a picture alone on the board: the page's focused node gets a paste that carries it as a file (a hub
323
+ * terminal sends it to the machine of its terminal, hub-app/terminal-picture.ts), whatever WebKit's own paste
324
+ * carries of a picture; any other board, and a page that does not take it, get WebKit's own paste */
325
+ @objc func paste(_ sender: Any?) {
326
+ guard let board = (NSApp.delegate as? Delegate)?.board, let pic = pictureOn(board) else { return webKitPaste(sender) }
327
+ hand(pic) { took in if !took { self.webKitPaste(sender) } }
328
+ }
329
+
330
+ /** WebKit's own paste, the method this one stands in front of (WKWebView declares no paste to Swift) */
331
+ private func webKitPaste(_ sender: Any?) {
332
+ typealias Paste = @convention(c) (AnyObject, Selector, AnyObject?) -> Void
333
+ let sel = #selector(NSText.paste(_:))
334
+ guard let imp = class_getMethodImplementation(WKWebView.self, sel) else { return }
335
+ unsafeBitCast(imp, to: Paste.self)(self, sel, sender as AnyObject?)
336
+ }
337
+
338
+ /** a picture handed to the page as a paste on its focused node; `took`: the page kept it (it prevented the default) */
339
+ func hand(_ pic: BoardPicture, took: @escaping (Bool) -> Void) {
340
+ let js = "const b = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)); const dt = new DataTransfer(); dt.items.add(new File([b], name, { type })); return !(document.activeElement ?? document.body).dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true, composed: true }))"
341
+ callAsyncJavaScript(js, arguments: ["b64": pic.data.base64EncodedString(), "type": pic.type, "name": pic.name], in: nil, in: .page) { r in
342
+ if case .success(let v) = r { took((v as? Bool) == true) } else { took(false) }
343
+ }
344
+ }
345
+ }
346
+
347
+ /** a picture on the board, as a page's paste carries it */
348
+ struct BoardPicture { let data: Data; let type: String; let name: String }
349
+ /** the pictures a page takes from a paste, by a file's extension (serve/picture-types.ts names the same four) */
350
+ let pictureTypes = ["png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "webp": "image/webp", "gif": "image/gif"]
351
+
352
+ /** the picture alone on a board: a file of a picture by its bytes, a png as it is, any other image (a screen shot's
353
+ * tiff) as a png. nil where the board holds words of their own (a sheet's cells come with a picture of them), a file
354
+ * that is no picture (the Finder adds its icon), or no picture */
355
+ func pictureOn(_ board: NSPasteboard) -> BoardPicture? {
356
+ let file = (board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL])?.first
357
+ if let words = board.string(forType: .string), !words.isEmpty, words != file?.lastPathComponent, words != file?.path, words != file?.absoluteString { return nil }
358
+ if let f = file {
359
+ guard let type = pictureTypes[f.pathExtension.lowercased()], let data = try? Data(contentsOf: f), data.count <= 16 << 20 else { return nil }
360
+ return BoardPicture(data: data, type: type, name: f.lastPathComponent)
361
+ }
362
+ if let png = board.data(forType: .png) { return BoardPicture(data: png, type: "image/png", name: "image.png") }
363
+ guard let tiff = board.data(forType: .tiff), let rep = NSBitmapImageRep(data: tiff), let png = rep.representation(using: .png, properties: [:]) else { return nil }
364
+ return BoardPicture(data: png, type: "image/png", name: "image.png")
365
+ }
366
+
367
+ /** the login chips a page's tab note names (serve/hub-app/app-bridge.ts TabChips): the url's id and its logins'
368
+ * labels by position, at most 8; nil when it names none */
369
+ func chipsOf(_ body: [String: Any]) -> (urlId: String, logins: [String])? {
370
+ guard let id = body["urlId"] as? String, !id.isEmpty, id.count <= 120, let logins = body["logins"] as? [String], !logins.isEmpty else { return nil }
371
+ return (id, logins.prefix(8).map { String($0.prefix(60)) })
372
+ }
373
+
374
+ /** 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
375
+ * copy route takes. Its title is a word, never a value */
376
+ final class ChipButton: NSButton {
377
+ var urlId = "", login = 0, label = "", field = ""
378
+ private var back: DispatchWorkItem?
379
+
380
+ /** `what` on the chip for `s` seconds, `why` its tip meanwhile, then its own field and tip again */
381
+ func say(_ what: String, why: String? = nil, for s: Double = 1.6) {
382
+ back?.cancel()
383
+ title = what
384
+ toolTip = why ?? "copy the \(field) of \(label)"
385
+ let w = DispatchWorkItem { [weak self] in
386
+ guard let self else { return }
387
+ self.title = self.field
388
+ self.toolTip = "copy the \(self.field) of \(self.label)"
389
+ }
390
+ back = w
391
+ DispatchQueue.main.asyncAfter(deadline: .now() + s, execute: w)
392
+ }
393
+ }
394
+
80
395
  final class Pane: NSView, NSSearchFieldDelegate {
81
- let web: WKWebView
396
+ private(set) var web: WKWebView
397
+ /** the address the window was opened on: a project app finds a tab by it */
398
+ var opened: URL?
399
+ /** a project app's hub, its tab 1: its own close is refused, and it closes last */
400
+ var pinned = false
401
+ /** 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
402
+ * not the name the project gave it. It stays as he walks the site */
403
+ var name: String? { didSet { retitle() } }
404
+ private var titleWatch: NSKeyValueObservation?
82
405
  let bar = NSStackView()
83
406
  let field = NSSearchField()
84
407
  let status = NSTextField(labelWithString: "")
@@ -115,6 +438,31 @@ final class Pane: NSView, NSSearchFieldDelegate {
115
438
  mark.layer?.cornerRadius = 3
116
439
  mark.alphaValue = 0
117
440
  addSubview(mark)
441
+ // the page's title names the window and its tab, so cmd-tab, the window menu and the tab bar tell pages apart;
442
+ // a page that renames itself with no load (the hub's router) renames them too
443
+ watchTitle()
444
+ }
445
+
446
+ private func watchTitle() {
447
+ titleWatch = web.observe(\.title, options: [.new]) { [weak self] _, _ in self?.retitle() }
448
+ }
449
+
450
+ /** the window's and the tab's title: the name it was opened under, else its page's; a page with none leaves it */
451
+ func retitle() {
452
+ if let name { window?.title = name } else if let t = web.title, !t.isEmpty { window?.title = t }
453
+ }
454
+
455
+ /** another web view in this one's place: the window, its tab, its pin and its find bar stay, the keys follow */
456
+ func swap(to new: WKWebView) {
457
+ let old = web
458
+ let keyed = (window?.firstResponder as? NSView)?.isDescendant(of: old) == true
459
+ addSubview(new, positioned: .below, relativeTo: bar)
460
+ old.removeFromSuperview()
461
+ web = new
462
+ watchTitle()
463
+ retitle()
464
+ needsLayout = true
465
+ if keyed { window?.makeFirstResponder(new) }
118
466
  }
119
467
 
120
468
  func blink() {
@@ -140,8 +488,14 @@ final class Pane: NSView, NSSearchFieldDelegate {
140
488
  override func layout() {
141
489
  super.layout()
142
490
  let top = isFindBarVisible ? Pane.barHeight : 0
143
- bar.frame = NSRect(x: 0, y: 0, width: bounds.width, height: Pane.barHeight)
144
- web.frame = NSRect(x: 0, y: top, width: bounds.width, height: max(0, bounds.height - top))
491
+ let span = side == nil ? 0 : sideSpan()
492
+ let left = bounds.width - span
493
+ bar.frame = NSRect(x: 0, y: 0, width: left, height: Pane.barHeight)
494
+ web.frame = NSRect(x: 0, y: top, width: left, height: max(0, bounds.height - top))
495
+ if let side {
496
+ side.frame = NSRect(x: left, y: 0, width: span, height: bounds.height)
497
+ divider.frame = NSRect(x: left - SideDivider.grip / 2, y: 0, width: SideDivider.grip, height: bounds.height)
498
+ }
145
499
  mark.frame = NSRect(x: bounds.width - 12, y: bounds.height - 12, width: 6, height: 6)
146
500
  }
147
501
 
@@ -197,263 +551,2920 @@ final class Pane: NSView, NSSearchFieldDelegate {
197
551
  }
198
552
  return false
199
553
  }
554
+
555
+ /** the side panel on the right of the page, once a page of the hub opened one (`openSide`) */
556
+ private(set) var side: SidePanel?
557
+ let divider = SideDivider()
558
+ /** this window's side panel width: the one it opened at, then the last one dragged */
559
+ var sideWidth = SidePanel.width
560
+
561
+ /** a url in this window's side panel, signed in as `identity` (its own store; none: the page's): the panel made on
562
+ * the first ask, shown again on the next one of the same identity, made again for another identity */
563
+ func openSide(_ url: URL, identity: SideIdentity? = nil) {
564
+ if let s = side, s.identity?.id != identity?.id { closeSide() }
565
+ if side == nil {
566
+ let s = SidePanel(store: identity.map { identityStore($0.id) } ?? web.configuration.websiteDataStore, identity: identity)
567
+ s.onClose = { [weak self] in self?.closeSide() }
568
+ s.page = web
569
+ divider.pane = self
570
+ sideWidth = SidePanel.width
571
+ addSubview(s)
572
+ addSubview(divider)
573
+ // the dot of a key nobody took stays on top, in the window's corner
574
+ addSubview(mark)
575
+ side = s
576
+ }
577
+ side?.show(url)
578
+ needsLayout = true
579
+ }
580
+
581
+ /** the side panel leaves with its web view and its process; the page takes the keys back when the panel had them */
582
+ func closeSide() {
583
+ guard let s = side else { return }
584
+ let keyed = (window?.firstResponder as? NSView)?.isDescendant(of: s) == true
585
+ s.web.stopLoading()
586
+ s.web.configuration.userContentController.removeAllScriptMessageHandlers()
587
+ s.removeFromSuperview()
588
+ divider.removeFromSuperview()
589
+ side = nil
590
+ needsLayout = true
591
+ if keyed { window?.makeFirstResponder(web) }
592
+ }
593
+
594
+ /** the panel's width as the window allows it: never under its own least, and the page keeps its least */
595
+ func sideSpan() -> CGFloat { min(max(sideWidth, SidePanel.minWidth), max(SidePanel.minWidth, bounds.width - SidePanel.pageMin)) }
200
596
  }
201
597
 
202
- final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate, NSWindowDelegate, NSMenuItemValidation, WKScriptMessageHandler, UNUserNotificationCenterDelegate {
203
- var windows: [NSWindow] = []
204
- var opened = false
598
+ /** what a page of the hub may open in the side panel: a web page, http or https with a host; nil for anything else */
599
+ func sideURL(_ s: String) -> URL? {
600
+ guard s.count <= 4096, let u = URL(string: s), let scheme = u.scheme?.lowercased(), scheme == "http" || scheme == "https", u.host?.isEmpty == false else { return nil }
601
+ return u
602
+ }
205
603
 
206
- // a click on a notification can launch the app: its delegate is set before launch ends
207
- func applicationWillFinishLaunching(_ note: Notification) {
208
- if isShipkit && !CommandLine.arguments.contains(where: { $0.hasPrefix("--self-test") }) { UNUserNotificationCenter.current().delegate = self }
604
+ /** the identity a hub page's repo speaks as, as the side panel signs in (app-bridge.ts SideIdentity): its id keys its
605
+ * store, its name heads the panel. Only a bridged hub page names one; a site in the panel has no bridge to name any */
606
+ struct SideIdentity: Codable, Equatable {
607
+ let id: String
608
+ let name: String
609
+ }
610
+
611
+ /** a page's `identity`, nil for none or for anything that is not an identity id (lowercase letters, digits, dashes) */
612
+ func sideIdentity(_ v: Any?) -> SideIdentity? {
613
+ guard let d = v as? [String: Any], let id = d["id"] as? String, (1...64).contains(id.count), id.allSatisfy({ ("a"..."z").contains($0) || ("0"..."9").contains($0) || $0 == "-" }) else { return nil }
614
+ let name = ((d["name"] as? String) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
615
+ return SideIdentity(id: id, name: name.isEmpty ? id : String(name.prefix(80)))
616
+ }
617
+
618
+ /** an identity's store id: a uuid of its id's hash, in the shape of a version 5 one, the same in every run and app */
619
+ func identityStoreId(_ id: String) -> UUID {
620
+ var b = Array(SHA256.hash(data: Data("shipkit identity store \(id)".utf8)).prefix(16))
621
+ b[6] = (b[6] & 0x0f) | 0x50
622
+ b[8] = (b[8] & 0x3f) | 0x80
623
+ return UUID(uuid: (b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]))
624
+ }
625
+
626
+ /** what a restart brings back of a tab (Delegate.keptTab) */
627
+ struct KeptTab: Codable, Equatable {
628
+ var url: String
629
+ var pinned = false
630
+ var name: String?
631
+ var chips: KeptChips?
632
+ var side: String?
633
+ var sideWidth: Double?
634
+ var sideIdentity: SideIdentity?
635
+ }
636
+ /** a url tab's login chips: its id and each login's label, never a value */
637
+ struct KeptChips: Codable, Equatable {
638
+ var urlId: String
639
+ var logins: [String]
640
+ }
641
+ /** a window: its frame, its tabs in their order, the one shown */
642
+ struct KeptWindow: Codable, Equatable {
643
+ var frame: String
644
+ var tabs: [KeptTab]
645
+ var shown: Int
646
+ }
647
+ /** every window of the app, the one in front last */
648
+ struct KeptSession: Codable, Equatable {
649
+ var windows: [KeptWindow]
650
+ }
651
+
652
+ /** each identity's sign in store, one a run: on macOS 14 and later WebKit's persistent store of its id (kept across
653
+ * restarts, apart from the app's own and from every other identity's); before 14 and in a self test, a store of its
654
+ * own that keeps nothing on disk (signed out at quit, still apart) */
655
+ var identityStores: [String: WKWebsiteDataStore] = [:]
656
+ func identityStore(_ id: String) -> WKWebsiteDataStore {
657
+ if let s = identityStores[id] { return s }
658
+ var store = WKWebsiteDataStore.nonPersistent()
659
+ if !selfTesting, #available(macOS 14.0, *) { store = WKWebsiteDataStore(forIdentifier: identityStoreId(id)) }
660
+ identityStores[id] = store
661
+ return store
662
+ }
663
+
664
+ /** what an address typed in the side panel loads: a url as typed, a bare host (a dot in it) over https, the machine's
665
+ * own names over http; nil for words, which the panel never searches */
666
+ func typedURL(_ s: String) -> URL? {
667
+ let t = s.trimmingCharacters(in: .whitespacesAndNewlines)
668
+ if t.isEmpty || t.contains(" ") { return nil }
669
+ if let u = sideURL(t) { return u }
670
+ let host = String(t.split(separator: "/").first?.split(separator: ":").first ?? "").lowercased()
671
+ let local = host == "localhost" || host == "127.0.0.1" || host.hasSuffix(".localhost")
672
+ guard local || (host.contains(".") && !host.hasPrefix(".") && !host.hasSuffix(".")) else { return nil }
673
+ return sideURL((local ? "http://" : "https://") + t)
674
+ }
675
+
676
+ /** the line between a window's page and its side panel: a drag sizes the panel, the width kept for the next one */
677
+ final class SideDivider: NSView {
678
+ /** the width a drag can start in, centred on the line */
679
+ static let grip: CGFloat = 7
680
+ weak var pane: Pane?
681
+
682
+ override var isFlipped: Bool { true }
683
+
684
+ // a mid grey, never the appearance's separator: a window painted dark sits beside pages of either colour
685
+ override func draw(_ dirty: NSRect) {
686
+ NSColor(white: 0.5, alpha: 0.5).setFill()
687
+ NSRect(x: floor(bounds.midX), y: 0, width: 1, height: bounds.height).fill()
209
688
  }
210
689
 
211
- func applicationDidFinishLaunching(_ note: Notification) {
212
- if CommandLine.arguments.contains("--self-test-find") { return selfTestFind() }
213
- if CommandLine.arguments.contains("--self-test-mic") { return selfTestMic() }
214
- if CommandLine.arguments.contains("--self-test-panels") { return selfTestPanels() }
215
- if CommandLine.arguments.contains("--self-test-download") { return selfTestDownload() }
216
- if CommandLine.arguments.contains("--self-test-badge") { return selfTestBadge() }
217
- if CommandLine.arguments.contains("--self-test-quiet-key") { return selfTestQuietKey() }
218
- if CommandLine.arguments.contains("--self-test-tabs") { return selfTestTabs() }
219
- if CommandLine.arguments.contains("--self-test-links") { return selfTestLinks() }
220
- buildMenu()
221
- // the system asks the owner once; refused, the badge still counts and each notification says why it did not show
222
- if isShipkit {
223
- UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { ok, err in
224
- if !ok { NSLog("shipkit: notifications are off for this app (System Settings, Notifications, shipkit)\(err.map { ": \($0.localizedDescription)" } ?? "")") }
225
- }
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
- }
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
239
- }
240
- // an open event may deliver the url right after launch: wait for it
241
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
242
- if !self.opened {
243
- let arg = CommandLine.arguments.dropFirst().first { $0.hasPrefix("http") }
244
- self.open(arg.flatMap { URL(string: $0) } ?? startURL)
245
- }
246
- }
690
+ override func resetCursorRects() { addCursorRect(bounds, cursor: .resizeLeftRight) }
691
+ override func mouseDown(with e: NSEvent) {}
692
+
693
+ override func mouseDragged(with e: NSEvent) {
694
+ guard let pane else { return }
695
+ pane.sideWidth = pane.bounds.width - pane.convert(e.locationInWindow, from: nil).x
696
+ pane.sideWidth = pane.sideSpan()
697
+ pane.needsLayout = true
247
698
  }
248
699
 
249
- func application(_ app: NSApplication, open urls: [URL]) {
250
- for u in urls { open(u) }
700
+ override func mouseUp(with e: NSEvent) {
701
+ guard let pane else { return }
702
+ SidePanel.keep(pane.sideSpan())
251
703
  }
704
+ }
252
705
 
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 }
706
+ /** the side panel's bar: the window's own background, a line under it */
707
+ final class SideBar: NSView {
708
+ override var isFlipped: Bool { true }
709
+ override func draw(_ dirty: NSRect) {
710
+ NSColor.windowBackgroundColor.setFill()
711
+ bounds.fill()
712
+ NSColor.separatorColor.setFill()
713
+ NSRect(x: 0, y: bounds.height - 1, width: bounds.width, height: 1).fill()
714
+ }
715
+ }
255
716
 
256
- func applicationShouldHandleReopen(_ app: NSApplication, hasVisibleWindows: Bool) -> Bool {
257
- if !hasVisibleWindows { open(startURL) }
258
- return true
717
+ /** one login a house url declares on the panel's origin, as the home lists it (urls/fill.ts LoginMatch): no value.
718
+ * `code`: it holds an authenticator setup, so a one-time-code field takes its code */
719
+ struct PanelLogin {
720
+ let repo: String, id: String, login: Int, label: String, account: String?, code: Bool, who: String?
721
+ var title: String { account.map { "\(label) (\($0))" } ?? label }
722
+ }
723
+
724
+ /** an origin as WebKit names a frame's: `location.origin`, the scheme's own port left out */
725
+ func frameOrigin(_ f: WKFrameInfo) -> String {
726
+ let o = f.securityOrigin
727
+ let scheme = o.protocol.lowercased()
728
+ let port = o.port == 0 || o.port == (scheme == "https" ? 443 : 80) ? "" : ":\(o.port)"
729
+ return "\(scheme)://\(o.host.lowercased())\(port)"
730
+ }
731
+
732
+ /** the home's login routes (urls/fill.ts), for a program of this Mac (the app is the one that asks), never a page: its requests carry no page's marks, which the home
733
+ * refuses. A value goes from the answer into the panel's fill and nowhere else: nothing here keeps or logs one */
734
+ enum PanelLogins {
735
+ static let session = URLSession(configuration: .ephemeral)
736
+
737
+ /** the logins of `origin`, none when the home does not answer */
738
+ static func list(_ origin: String, done: @escaping ([PanelLogin]) -> Void) {
739
+ var c = URLComponents(url: URL(string: "/api/home/logins", relativeTo: startURL)!.absoluteURL, resolvingAgainstBaseURL: false)
740
+ c?.queryItems = [URLQueryItem(name: "origin", value: origin)]
741
+ guard let url = c?.url else { return done([]) }
742
+ var req = URLRequest(url: url)
743
+ req.timeoutInterval = 5
744
+ session.dataTask(with: req) { data, res, _ in
745
+ let rows = (res as? HTTPURLResponse)?.statusCode == 200 ? ((data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any])?["logins"] as? [[String: Any]]) ?? [] : []
746
+ let logins = rows.compactMap { r -> PanelLogin? in
747
+ guard let repo = r["repo"] as? String, let id = r["id"] as? String, let login = r["login"] as? Int, let label = r["label"] as? String else { return nil }
748
+ return PanelLogin(repo: repo, id: id, login: login, label: String(label.prefix(60)), account: r["account"] as? String, code: r["code"] as? Bool ?? false, who: r["who"] as? String)
749
+ }
750
+ DispatchQueue.main.async { done(logins) }
751
+ }.resume()
259
752
  }
260
753
 
261
- func keyPane() -> Pane? { NSApp.keyWindow?.contentView as? Pane }
754
+ /** what a fill gets: the account, the password, and the code of a login that holds one with the seconds until it
755
+ * is valid (urls/totp.ts CodeNow) */
756
+ typealias Values = (account: String?, password: String, code: (value: String, wait: Double)?)
262
757
 
263
- @objc func newWindow(_ sender: Any?) {
264
- open(keyPane()?.web.url ?? startURL)
758
+ /** one login's account, password and code for `origin`, or the home's words of refusal */
759
+ static func values(_ l: PanelLogin, _ origin: String, done: @escaping (Result<Values, Refused>) -> Void) {
760
+ var req = URLRequest(url: URL(string: "/api/home/logins/fill", relativeTo: startURL)!.absoluteURL)
761
+ req.httpMethod = "POST"
762
+ req.timeoutInterval = 8
763
+ req.setValue("application/json", forHTTPHeaderField: "content-type")
764
+ req.httpBody = try? JSONSerialization.data(withJSONObject: ["origin": origin, "repo": l.repo, "id": l.id, "login": l.login])
765
+ session.dataTask(with: req) { data, res, err in
766
+ let code = (res as? HTTPURLResponse)?.statusCode ?? 0
767
+ let b = code == 200 ? data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any] : nil
768
+ // a refusal's words are the home's, which never hold a value; the answer of a fill is never read as words
769
+ let otp = (b?["code"] as? [String: Any]).flatMap { c in (c["value"] as? String).map { (value: $0, wait: (c["wait"] as? NSNumber)?.doubleValue ?? 0) } }
770
+ let out: Result<Values, Refused> = (b?["password"] as? String).map { .success((b?["account"] as? String, $0, otp)) }
771
+ ?? .failure(Refused(why: code == 200 ? "the home's answer held no password" : err?.localizedDescription ?? data.flatMap { String(data: $0, encoding: .utf8) }.map { String($0.prefix(240)) } ?? "the home answered \(code)"))
772
+ DispatchQueue.main.async { done(out) }
773
+ }.resume()
265
774
  }
266
775
 
267
- /// the tab after or before the one a window shows, round to the first; one tab alone stays
268
- func stepTab(of w: NSWindow?, by: Int) {
269
- guard let g = w?.tabGroup, let shown = g.selectedWindow, let i = g.windows.firstIndex(of: shown), g.windows.count > 1 else { return }
270
- let to = g.windows[(i + by + g.windows.count) % g.windows.count]
271
- g.selectedWindow = to
272
- to.makeKeyAndOrderFront(nil)
776
+ struct Refused: Error { let why: String }
777
+ }
778
+
779
+ /** hears the panel's own world (SidePanel.fillWorld) and nothing else: weak, so the web view's controller never keeps
780
+ * the panel alive */
781
+ final class FillHear: NSObject, WKScriptMessageHandler {
782
+ weak var panel: SidePanel?
783
+ init(_ p: SidePanel) { panel = p }
784
+ func userContentController(_ c: WKUserContentController, didReceive m: WKScriptMessage) { panel?.heard(m) }
785
+ }
786
+
787
+ /** a line under the panel's bar: what a fill did, why a passkey cannot be given here, with its one act */
788
+ final class SideStrip: NSView {
789
+ static let height: CGFloat = 30
790
+ let label = NSTextField(labelWithString: "")
791
+ let act = NSButton(title: "", target: nil, action: nil)
792
+ var onAct: (() -> Void)?
793
+ override var isFlipped: Bool { true }
794
+
795
+ override init(frame: NSRect) {
796
+ super.init(frame: frame)
797
+ label.font = .systemFont(ofSize: NSFont.smallSystemFontSize)
798
+ label.textColor = .secondaryLabelColor
799
+ label.lineBreakMode = .byTruncatingTail
800
+ act.bezelStyle = .recessed
801
+ act.controlSize = .small
802
+ act.target = self
803
+ act.action = #selector(pressed)
804
+ addSubview(label)
805
+ addSubview(act)
273
806
  }
807
+ required init?(coder: NSCoder) { fatalError("not from a nib") }
274
808
 
275
- @objc func nextTab(_ sender: Any?) { stepTab(of: NSApp.keyWindow ?? NSApp.mainWindow, by: 1) }
276
- @objc func previousTab(_ sender: Any?) { stepTab(of: NSApp.keyWindow ?? NSApp.mainWindow, by: -1) }
809
+ @objc func pressed() { onAct?() }
277
810
 
278
- @objc func reload(_ sender: Any?) {
279
- keyPane()?.web.reload()
811
+ override func draw(_ dirty: NSRect) {
812
+ NSColor.controlBackgroundColor.setFill()
813
+ bounds.fill()
814
+ NSColor.separatorColor.setFill()
815
+ NSRect(x: 0, y: bounds.height - 1, width: bounds.width, height: 1).fill()
280
816
  }
281
817
 
282
- // the zoom is one value for every window of the app, kept across restarts
283
- var zoom: CGFloat {
284
- get { let z = UserDefaults.standard.double(forKey: "pageZoom"); return z > 0 ? CGFloat(z) : 1 }
285
- set {
286
- let z = min(3, max(0.3, newValue))
287
- UserDefaults.standard.set(Double(z), forKey: "pageZoom")
288
- for w in windows { (w.contentView as? Pane)?.web.pageZoom = z }
289
- }
818
+ override func layout() {
819
+ super.layout()
820
+ let w = act.isHidden ? 0 : min(act.fittingSize.width, bounds.width / 2)
821
+ act.frame = NSRect(x: bounds.width - w - 8, y: (bounds.height - 22) / 2, width: w, height: 22)
822
+ label.frame = NSRect(x: 10, y: (bounds.height - 16) / 2, width: max(0, bounds.width - w - 26), height: 16)
290
823
  }
824
+ }
291
825
 
292
- @objc func zoomIn(_ sender: Any?) { zoom = zoom * 1.1 }
293
- @objc func zoomOut(_ sender: Any?) { zoom = zoom / 1.1 }
294
- @objc func zoomReset(_ sender: Any?) { zoom = 1 }
826
+ /** a site beside the hub's page, as a browser's side panel: its own web view, under a bar with back, forward, reload,
827
+ * its address, open in the browser and close. A page of the hub opens it (serve/hub-app/app-bridge.ts `openLink`).
828
+ * It never gets the page's bridge, so a site it shows posts nothing to the app, and every site stays in it: a link,
829
+ * a redirect, a window.open. Its cookies are the app's own store, the one of its tabs: a sign in made here stays.
830
+ * A page on the origin of a house url with a login gets it filled (wiki tools/shipkit/urls.md, A login filled in the
831
+ * side panel): the app asks the home for the value and puts it in that frame alone, from a world of its own that no
832
+ * script of the page reaches. A passkey the page asks, which WebKit gives a signed browser only, offers the
833
+ * identity's Chrome instead */
834
+ final class SidePanel: NSView, WKNavigationDelegate, WKUIDelegate, NSTextFieldDelegate {
835
+ /** the panel's own world: a page's scripts never see its handler, its fill or its watch */
836
+ static let fillWorld = WKContentWorld.world(name: "shipkit-fill")
837
+ /** a self test's stand ins, put before the panel's own scripts in each panel it makes */
838
+ static var testScripts: [WKUserScript] = []
295
839
 
296
- @objc func showFind(_ sender: Any?) { keyPane()?.showFind() }
297
- @objc func hideFind(_ sender: Any?) { keyPane()?.hideFind() }
298
- @objc func findNext(_ sender: Any?) { keyPane()?.findNext() }
299
- @objc func findPrevious(_ sender: Any?) { keyPane()?.findPrevious() }
840
+ /** the field of an authenticator code among a frame's shown inputs: the one marked `one-time-code`, else, with no
841
+ * password field shown (the step after the password), a lone text input that looks like one: 6 to 8 characters,
842
+ * numeric, or named so. A JS function's source, shared by the watch and the fill */
843
+ static let codeField = """
844
+ (inputs) => {
845
+ const otc = inputs.find((i) => /one-time-code/.test(i.autocomplete || ''))
846
+ if (otc) return otc
847
+ if (inputs.some((i) => i.type === 'password')) return null
848
+ const lone = inputs.filter((i) => i.type === 'text' || i.type === 'tel' || i.type === 'number')
849
+ if (lone.length !== 1) return null
850
+ const i = lone[0]
851
+ const hint = [i.name, i.id, i.placeholder, i.getAttribute('aria-label') || ''].join(' ')
852
+ return (i.maxLength >= 6 && i.maxLength <= 8) || i.inputMode === 'numeric' || /otp|totp|2fa|mfa|code|token|verif|authenticat/i.test(hint) ? i : null
853
+ }
854
+ """
300
855
 
301
- // no public api opens the inspector: `_inspector` then `show` is the
302
- // WebKit call the context menu's Inspect Element makes. Where it is gone,
303
- // say where the inspector still is
304
- @objc func devTools(_ sender: Any?) {
305
- guard let web = keyPane()?.web else { return }
306
- let get = NSSelectorFromString("_inspector"), show = NSSelectorFromString("show")
307
- if web.responds(to: get), let inspector = web.perform(get)?.takeUnretainedValue() as? NSObject, inspector.responds(to: show) {
308
- inspector.perform(show)
309
- return
856
+ /** in the panel's world, every frame: tells the app a frame holds a sign in field and a frame holds the field of an
857
+ * authenticator code (each once, when it shows, however late), and passes on a passkey the page's own world saw
858
+ * fail. The page is looked at a few times a second at most while it changes */
859
+ static let formWatch = """
860
+ (() => {
861
+ const post = (m) => { try { webkit.messageHandlers.skFill.postMessage(m) } catch (e) {} }
862
+ document.addEventListener('shipkit-passkey', (e) => post({ passkey: String(e.detail || 'failed').slice(0, 60) }))
863
+ const field = 'input[type=password], input[type=email], input[autocomplete~=username]'
864
+ const codeField = \(SidePanel.codeField)
865
+ const shown = (el) => !el.disabled && !el.readOnly && el.getClientRects().length > 0
866
+ let told = false, toldCode = false, queued = false
867
+ const look = () => {
868
+ if (!told && document.querySelector(field)) { told = true; post({ form: true }) }
869
+ if (!toldCode && codeField(Array.from(document.querySelectorAll('input')).filter(shown))) { toldCode = true; post({ code: true }) }
870
+ return told && toldCode
310
871
  }
311
- let alert = NSAlert()
312
- alert.messageText = "This WebKit has no way to open the inspector from a menu"
313
- alert.informativeText = "Right click the page and pick Inspect Element."
314
- alert.runModal()
872
+ const start = () => {
873
+ if (look()) return
874
+ const o = new MutationObserver(() => {
875
+ if (queued) return
876
+ queued = true
877
+ setTimeout(() => { queued = false; if (look()) o.disconnect() }, 150)
878
+ })
879
+ o.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['type', 'style', 'class', 'hidden'] })
880
+ }
881
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else start()
882
+ })()
883
+ """
884
+
885
+ /** in the page's own world, every frame: a WebAuthn request that fails is said as an event of the document, which
886
+ * the panel's world hears. It holds nothing: a page that sends the event itself only gets the Chrome offer */
887
+ static let passkeyWatch = """
888
+ (() => {
889
+ const c = navigator.credentials
890
+ if (c == null) return
891
+ const tell = (e) => document.dispatchEvent(new CustomEvent('shipkit-passkey', { detail: String((e && e.name) || 'failed') }))
892
+ for (const k of ['get', 'create']) {
893
+ const f = c[k]
894
+ if (typeof f !== 'function') continue
895
+ c[k] = function (o) { const p = f.call(this, o); if (o && o.publicKey) p.catch(tell); return p }
896
+ }
897
+ })()
898
+ """
899
+
900
+ /** the fill, in the panel's world of one frame, with its values as arguments (never in the source): the account
901
+ * into the field that names one before the password, the password into the first one shown, a code into the field
902
+ * of an authenticator code (codeField); an empty value fills nothing. It checks the frame
903
+ * is still `origin`, so a frame that moved on gets nothing. A fill on its own (`auto`) takes a field he can see
904
+ * only: some size, no opacity of 0 on it or above it, inside the viewport; any other waits for the key. Its answer:
905
+ * the fields filled, never a value */
906
+ static let fillScript = """
907
+ if (location.origin !== origin) return 'moved'
908
+ const shown = (el) => !el.disabled && !el.readOnly && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden'
909
+ const seen = (el) => {
910
+ const r = el.getBoundingClientRect()
911
+ for (let e = el; e != null; e = e.parentElement) if (Number(getComputedStyle(e).opacity) === 0) return false
912
+ return r.width > 0 && r.height > 0 && r.bottom > 0 && r.right > 0 && r.top < innerHeight && r.left < innerWidth
315
913
  }
914
+ const all = Array.from(document.querySelectorAll('input')).filter((i) => shown(i) && (!auto || seen(i)))
915
+ const otc = code !== '' ? (\(SidePanel.codeField))(all) : null
916
+ const pass = all.find((i) => i.type === 'password') || null
917
+ const texty = (i) => i.type === 'text' || i.type === 'email' || i.type === 'tel'
918
+ const marked = (i) => /username|email/.test(i.autocomplete || '') || i.type === 'email'
919
+ const named = (i) => /user|login|mail|account|ident|compte/i.test([i.name, i.id, i.autocomplete, i.placeholder].join(' '))
920
+ const before = (pass ? all.slice(0, all.indexOf(pass)).filter(texty) : all.filter(texty)).filter((i) => i !== otc)
921
+ const user = before.find(marked) || before.filter(named).pop() || (pass ? before.pop() : null) || null
922
+ const put = (el, v) => {
923
+ el.focus()
924
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, v)
925
+ el.dispatchEvent(new Event('input', { bubbles: true }))
926
+ el.dispatchEvent(new Event('change', { bubbles: true }))
927
+ }
928
+ const did = []
929
+ if (user && account !== '') { put(user, account); did.push('account') }
930
+ if (pass && password !== '') { put(pass, password); did.push('password') }
931
+ if (otc) { put(otc, code); did.push('code') }
932
+ return did.join(', ')
933
+ """
316
934
 
317
- func validateMenuItem(_ item: NSMenuItem) -> Bool {
318
- if item.action == #selector(hideFind(_:)) { return keyPane()?.isFindBarVisible == true }
319
- if item.action == #selector(findNext(_:)) || item.action == #selector(findPrevious(_:)) { return keyPane()?.field.stringValue.isEmpty == false }
320
- if item.action == #selector(showFind(_:)) { return keyPane() != nil }
321
- if item.action == #selector(devTools(_:)) || item.action == #selector(reload(_:)) { return keyPane() != nil }
322
- return true
935
+ static let barHeight: CGFloat = 34
936
+ static let minWidth: CGFloat = 300
937
+ /** what the page beside the panel keeps at least */
938
+ static let pageMin: CGFloat = 360
939
+ static let widthKey = "ShipkitSidePanelWidth"
940
+ /** the width a new panel opens at: the last one dragged, kept in the app's defaults (a self test reads and writes none) */
941
+ static var width: CGFloat = {
942
+ let w = selfTesting ? 0 : UserDefaults.standard.double(forKey: SidePanel.widthKey)
943
+ return w >= Double(SidePanel.minWidth) ? CGFloat(w) : 560
944
+ }()
945
+ static func keep(_ w: CGFloat) {
946
+ width = w
947
+ if !selfTesting { UserDefaults.standard.set(Double(w), forKey: SidePanel.widthKey) }
323
948
  }
324
949
 
325
- func webConfig() -> WKWebViewConfiguration {
950
+ let web: WKWebView
951
+ let bar = SideBar()
952
+ let address = NSTextField()
953
+ /** whose sign ins the panel holds: the identity its page named, nil for the page's own store */
954
+ let identity: SideIdentity?
955
+ /** the head's words for it, left of the address */
956
+ let who = NSTextField(labelWithString: "")
957
+ /** why the last page asked did not open, over the web view until the next page commits */
958
+ let fault = NSTextField(wrappingLabelWithString: "")
959
+ private(set) var buttons: [String: NSButton] = [:]
960
+ /** the address last asked: reload and « open in the browser » take it when no page committed */
961
+ private(set) var asked: URL?
962
+ var onClose: (() -> Void)?
963
+ private var watches: [NSKeyValueObservation] = []
964
+ /** the hub's page beside the panel: the identity's Chrome is opened through it, a word as the owner */
965
+ weak var page: WKWebView?
966
+ /** the logins of the page's origin, as the home listed them, and the origin they are of */
967
+ private(set) var logins: [PanelLogin] = []
968
+ private(set) var loginsOf: String?
969
+ /** several logins: he picks the one to fill */
970
+ let chooser = NSPopUpButton(frame: .zero, pullsDown: false)
971
+ let strip = SideStrip()
972
+ /** the frame of the page's origin that said it holds a sign in field, the one a fill goes to */
973
+ private(set) var formFrame: WKFrameInfo?
974
+ /** a frame of another origin that said so, which is never filled (a self test reads it) */
975
+ private(set) var foreignFrame: WKFrameInfo?
976
+ /** this page got its one fill on its own */
977
+ private var autoDone = false
978
+ /** the frame of the page's origin that said it holds the field of an authenticator code */
979
+ private(set) var codeFrame: WKFrameInfo?
980
+ /** this page got its one code on its own */
981
+ private var codeDone = false
982
+ /** the login filled last on this origin: the code step after its password takes its code */
983
+ private var lastFilled: PanelLogin?
984
+ /** the last thing the panel said of a fill (a self test reads it) */
985
+ private(set) var said = ""
986
+
987
+ init(store: WKWebsiteDataStore, identity: SideIdentity? = nil) {
988
+ self.identity = identity
326
989
  let config = WKWebViewConfiguration()
990
+ config.websiteDataStore = store
327
991
  config.preferences.setValue(true, forKey: "developerExtrasEnabled")
328
- if isShipkit {
329
- 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 }
992
+ let scripts = config.userContentController
993
+ for s in SidePanel.testScripts { scripts.addUserScript(s) }
994
+ scripts.addUserScript(WKUserScript(source: SidePanel.passkeyWatch, injectionTime: .atDocumentStart, forMainFrameOnly: false))
995
+ scripts.addUserScript(WKUserScript(source: SidePanel.formWatch, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: SidePanel.fillWorld))
996
+ web = WKWebView(frame: .zero, configuration: config)
997
+ super.init(frame: .zero)
998
+ scripts.add(FillHear(self), contentWorld: SidePanel.fillWorld, name: "skFill")
999
+ if #available(macOS 13.3, *) { web.isInspectable = true }
1000
+ web.navigationDelegate = self
1001
+ web.uiDelegate = self
1002
+ web.allowsBackForwardNavigationGestures = true
1003
+ web.allowsMagnification = true
1004
+ addSubview(web)
1005
+ addSubview(bar)
1006
+ address.controlSize = .small
1007
+ address.font = .systemFont(ofSize: NSFont.smallSystemFontSize)
1008
+ address.isBezeled = true
1009
+ address.bezelStyle = .roundedBezel
1010
+ address.lineBreakMode = .byTruncatingMiddle
1011
+ address.cell?.usesSingleLineMode = true
1012
+ address.placeholderString = "address"
1013
+ address.delegate = self
1014
+ for (key, symbol, tipText, action) in [
1015
+ ("back", "chevron.left", "back", #selector(goBack)),
1016
+ ("forward", "chevron.right", "forward", #selector(goForward)),
1017
+ ("reload", "arrow.clockwise", "reload", #selector(reloadPage)),
1018
+ ("outside", "safari", "open in the browser", #selector(openOutside)),
1019
+ ("close", "xmark", "close the side panel", #selector(closePanel)),
1020
+ ("fill", "key.fill", "fill the sign in form", #selector(fillPressed)),
1021
+ ] {
1022
+ let b = NSButton(image: NSImage(systemSymbolName: symbol, accessibilityDescription: tipText) ?? NSImage(), target: self, action: action)
1023
+ b.isBordered = false
1024
+ b.imageScaling = .scaleProportionallyDown
1025
+ b.contentTintColor = .secondaryLabelColor
1026
+ b.toolTip = tipText
1027
+ buttons[key] = b
1028
+ bar.addSubview(b)
1029
+ }
1030
+ bar.addSubview(address)
1031
+ who.font = .systemFont(ofSize: NSFont.smallSystemFontSize)
1032
+ who.textColor = .secondaryLabelColor
1033
+ who.lineBreakMode = .byTruncatingTail
1034
+ who.stringValue = identity.map { "as \($0.name)" } ?? "shared sign ins"
1035
+ who.toolTip = identity.map { "this panel signs in as \($0.name): its own cookies, which no other identity's sites see" } ?? "no identity named: the app's own sign ins"
1036
+ bar.addSubview(who)
1037
+ buttons["fill"]?.isHidden = true
1038
+ chooser.controlSize = .small
1039
+ chooser.font = .systemFont(ofSize: NSFont.smallSystemFontSize)
1040
+ chooser.target = self
1041
+ chooser.action = #selector(chosen)
1042
+ chooser.toolTip = "the login to fill"
1043
+ chooser.isHidden = true
1044
+ bar.addSubview(chooser)
1045
+ strip.isHidden = true
1046
+ addSubview(strip)
1047
+ fault.textColor = .secondaryLabelColor
1048
+ fault.alignment = .center
1049
+ fault.isHidden = true
1050
+ addSubview(fault)
1051
+ watches = [
1052
+ web.observe(\.url, options: [.initial, .new]) { [weak self] _, _ in self?.sayAddress() },
1053
+ web.observe(\.canGoBack, options: [.initial, .new]) { [weak self] w, _ in self?.buttons["back"]?.isEnabled = w.canGoBack },
1054
+ web.observe(\.canGoForward, options: [.initial, .new]) { [weak self] w, _ in self?.buttons["forward"]?.isEnabled = w.canGoForward },
1055
+ ]
1056
+ }
1057
+
1058
+ required init?(coder: NSCoder) { fatalError("not from a nib") }
1059
+
1060
+ override var isFlipped: Bool { true }
1061
+
1062
+ override func layout() {
1063
+ super.layout()
1064
+ let h = SidePanel.barHeight
1065
+ bar.frame = NSRect(x: 0, y: 0, width: bounds.width, height: h)
1066
+ let s = strip.isHidden ? 0 : SideStrip.height
1067
+ strip.frame = NSRect(x: 0, y: h, width: bounds.width, height: s)
1068
+ web.frame = NSRect(x: 0, y: h + s, width: bounds.width, height: max(0, bounds.height - h - s))
1069
+ fault.frame = NSRect(x: 24, y: h + s + 40, width: max(0, bounds.width - 48), height: 80)
1070
+ let size: CGFloat = 24, pad: CGFloat = 6, y = (h - size) / 2
1071
+ var x = pad
1072
+ for k in ["back", "forward", "reload"] {
1073
+ buttons[k]?.frame = NSRect(x: x, y: y, width: size, height: size)
1074
+ x += size + 2
1075
+ }
1076
+ var right = bounds.width - pad
1077
+ for k in ["close", "outside", "fill"] where buttons[k]?.isHidden == false {
1078
+ right -= size
1079
+ buttons[k]?.frame = NSRect(x: right, y: y, width: size, height: size)
1080
+ right -= 2
1081
+ }
1082
+ if !chooser.isHidden {
1083
+ let w = min(160, max(80, (right - x) / 3))
1084
+ right -= w
1085
+ chooser.frame = NSRect(x: right, y: (h - 22) / 2, width: w, height: 22)
1086
+ right -= 2
1087
+ }
1088
+ let label = min(140, ceil(who.intrinsicContentSize.width))
1089
+ who.frame = NSRect(x: x + 4, y: (h - who.intrinsicContentSize.height) / 2, width: label, height: who.intrinsicContentSize.height)
1090
+ x += label + 4
1091
+ address.frame = NSRect(x: x + 4, y: (h - 22) / 2, width: max(40, right - x - 8), height: 22)
1092
+ }
1093
+
1094
+ /** `url` in the panel; the page it shows already is left as he walked it */
1095
+ func show(_ url: URL) {
1096
+ asked = url
1097
+ fault.isHidden = true
1098
+ if web.url?.absoluteString == url.absoluteString { return }
1099
+ web.load(URLRequest(url: url))
1100
+ address.stringValue = url.absoluteString
1101
+ }
1102
+
1103
+ /** the address field says where the page is, unless he is typing in it */
1104
+ func sayAddress() {
1105
+ if address.currentEditor() != nil { return }
1106
+ address.stringValue = (web.url ?? asked)?.absoluteString ?? ""
1107
+ }
1108
+
1109
+ @objc func goBack() { web.goBack() }
1110
+ @objc func goForward() { web.goForward() }
1111
+ @objc func reloadPage() {
1112
+ if web.url == nil, let asked { web.load(URLRequest(url: asked)) } else { web.reload() }
1113
+ }
1114
+ @objc func openOutside() {
1115
+ guard let url = web.url ?? asked else { return }
1116
+ (NSApp.delegate as? Delegate)?.openOutside(url)
1117
+ }
1118
+ @objc func closePanel() { onClose?() }
1119
+
1120
+ // return in the address loads what he typed, esc puts back where the page is
1121
+ func control(_ control: NSControl, textView: NSTextView, doCommandBy sel: Selector) -> Bool {
1122
+ if sel == #selector(NSResponder.insertNewline(_:)) {
1123
+ if let url = typedURL(address.stringValue) {
1124
+ show(url)
1125
+ window?.makeFirstResponder(web)
1126
+ } else {
1127
+ say("Not an address: \(address.stringValue)")
1128
+ }
1129
+ return true
1130
+ }
1131
+ if sel == #selector(NSResponder.cancelOperation(_:)) {
1132
+ window?.makeFirstResponder(web)
1133
+ sayAddress()
1134
+ return true
1135
+ }
1136
+ return false
1137
+ }
1138
+
1139
+ func say(_ why: String) {
1140
+ fault.stringValue = why
1141
+ fault.isHidden = false
1142
+ }
1143
+
1144
+ // every web page stays in the panel; a mail address or another app's scheme leaves for its app, a file never opens
1145
+ func webView(_ web: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
1146
+ if action.shouldPerformDownload { return decisionHandler(.download) }
1147
+ switch action.request.url?.scheme?.lowercased() {
1148
+ case nil, "http", "https", "about", "data", "blob", "javascript": decisionHandler(.allow)
1149
+ case "file": decisionHandler(.cancel)
1150
+ default:
1151
+ if let url = action.request.url { (NSApp.delegate as? Delegate)?.openOutside(url) }
1152
+ decisionHandler(.cancel)
1153
+ }
1154
+ }
1155
+
1156
+ func webView(_ web: WKWebView, decidePolicyFor response: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
1157
+ let attachment = ((response.response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Disposition") ?? "").lowercased().hasPrefix("attachment")
1158
+ decisionHandler(attachment || !response.canShowMIMEType ? .download : .allow)
1159
+ }
1160
+
1161
+ // a download lands where the app's do: ~/Downloads, under a free name
1162
+ func webView(_ web: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) { download.delegate = NSApp.delegate as? Delegate }
1163
+ func webView(_ web: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) { download.delegate = NSApp.delegate as? Delegate }
1164
+
1165
+ func webView(_ web: WKWebView, didCommit nav: WKNavigation!) {
1166
+ fault.isHidden = true
1167
+ pageChanged()
1168
+ }
1169
+
1170
+ // MARK: a login filled in
1171
+
1172
+ /** a new page in the panel: its frames are new, and another origin has other logins, asked of the home */
1173
+ func pageChanged() {
1174
+ formFrame = nil
1175
+ foreignFrame = nil
1176
+ codeFrame = nil
1177
+ autoDone = false
1178
+ codeDone = false
1179
+ said = ""
1180
+ hideStrip()
1181
+ let origin = web.url.flatMap { $0.scheme == "http" || $0.scheme == "https" ? pageOrigin($0) : nil }
1182
+ if origin == loginsOf { return }
1183
+ loginsOf = origin
1184
+ lastFilled = nil
1185
+ showLogins([])
1186
+ guard let origin else { return }
1187
+ PanelLogins.list(origin) { [weak self] list in
1188
+ guard let self, self.loginsOf == origin else { return }
1189
+ self.showLogins(list)
1190
+ self.autoFill()
1191
+ }
1192
+ }
1193
+
1194
+ /** the bar wears what the page's origin can take: the fill button once one login is there, the chooser for several */
1195
+ func showLogins(_ list: [PanelLogin]) {
1196
+ logins = list
1197
+ chooser.removeAllItems()
1198
+ chooser.addItems(withTitles: list.map(\.title))
1199
+ chooser.isHidden = list.count < 2
1200
+ buttons["fill"]?.isHidden = list.isEmpty
1201
+ buttons["fill"]?.toolTip = list.count == 1 ? "fill the sign in form with \(list[0].title)" : "fill the sign in form with the login chosen beside"
1202
+ needsLayout = true
1203
+ }
1204
+
1205
+ /** a message of the panel's own world: a frame with a sign in field, or a passkey the page saw fail */
1206
+ func heard(_ m: WKScriptMessage) {
1207
+ guard let body = m.body as? [String: Any], m.webView === web else { return }
1208
+ if let why = body["passkey"] as? String { return passkeyFailed(why) }
1209
+ let code = body["code"] as? Bool == true
1210
+ guard body["form"] as? Bool == true || code else { return }
1211
+ // a frame is filled only when it is the page's own origin: a frame of another site inside it never is
1212
+ guard let top = web.url.map(pageOrigin), frameOrigin(m.frameInfo) == top else {
1213
+ foreignFrame = m.frameInfo
1214
+ return
1215
+ }
1216
+ if code {
1217
+ codeFrame = m.frameInfo
1218
+ return autoCode()
1219
+ }
1220
+ formFrame = m.frameInfo
1221
+ autoFill()
1222
+ }
1223
+
1224
+ /** the page's one code on its own: the field of a code shown, for the login filled last on this origin, else the
1225
+ * one login of the origin that holds a code */
1226
+ func autoCode() {
1227
+ guard !codeDone, codeFrame != nil else { return }
1228
+ let withCode = logins.filter(\.code)
1229
+ guard let l = lastFilled.flatMap({ f in withCode.first { $0.repo == f.repo && $0.id == f.id && $0.login == f.login } }) ?? (withCode.count == 1 ? withCode[0] : nil) else { return }
1230
+ codeDone = true
1231
+ fill(l, auto: true, codeOnly: true)
1232
+ }
1233
+
1234
+ /** the page's one fill on its own: one login for its origin and a form shown; with several he picks */
1235
+ func autoFill() {
1236
+ guard !autoDone, formFrame != nil, !logins.isEmpty else { return }
1237
+ autoDone = true
1238
+ if logins.count == 1 { return fill(logins[0], auto: true) }
1239
+ tell("\(logins.count) logins for \(loginsOf ?? "this page"): pick one in the bar to fill it")
1240
+ }
1241
+
1242
+ @objc func fillPressed() {
1243
+ guard !logins.isEmpty else { return }
1244
+ fill(logins[logins.count == 1 ? 0 : max(0, chooser.indexOfSelectedItem)])
1245
+ }
1246
+
1247
+ @objc func chosen() { fillPressed() }
1248
+
1249
+ /** `l` into the form of the page: only while the page is the origin the home listed it for, into a frame of that
1250
+ * origin, never another. The values go from the home's answer to the frame's fill and are kept nowhere.
1251
+ * `codeOnly`: the step after the password, its code alone. A code given near its period's end waits until it is
1252
+ * valid, said in the line */
1253
+ func fill(_ l: PanelLogin, auto: Bool = false, codeOnly: Bool = false) {
1254
+ guard let origin = loginsOf, web.url.map(pageOrigin) == origin, logins.contains(where: { $0.repo == l.repo && $0.id == l.id && $0.login == l.login }) else {
1255
+ return tell("not filled: \(l.label) is a login of another origin than \(web.url.map(pageOrigin) ?? "this page")")
1256
+ }
1257
+ let frame = codeOnly ? codeFrame : formFrame ?? codeFrame
1258
+ if let frame, frameOrigin(frame) != origin { return tell("not filled: the form is of another origin than \(origin)") }
1259
+ tell("filling \(l.label)…")
1260
+ lastFilled = l
1261
+ PanelLogins.values(l, origin) { [weak self] r in
1262
+ guard let self else { return }
1263
+ switch r {
1264
+ case .failure(let e): self.tell("not filled: \(e.why)")
1265
+ case .success(let v):
1266
+ guard self.web.url.map(pageOrigin) == origin else { return self.tell("not filled: the page left \(origin)") }
1267
+ let put = { (account: String, password: String, code: String) in
1268
+ self.web.callAsyncJavaScript(SidePanel.fillScript, arguments: ["origin": origin, "account": account, "password": password, "code": code, "auto": auto], in: frame, in: SidePanel.fillWorld) { [weak self] res in
1269
+ let did = (try? res.get()) as? String ?? ""
1270
+ self?.tell(did == "moved" ? "not filled: the page left \(origin)" : did.isEmpty ? (auto ? "no sign in field in sight: press the key to fill it" : "no sign in field on this page: press the key once it shows") : "filled \(l.label): \(did)")
1271
+ }
1272
+ }
1273
+ guard let code = v.code, code.wait > 0 else {
1274
+ return put(codeOnly ? "" : v.account ?? "", codeOnly ? "" : v.password, v.code?.value ?? "")
1275
+ }
1276
+ // the code of this period ends in a moment: the fields now, the next code once it is valid
1277
+ if !codeOnly { put(v.account ?? "", v.password, "") }
1278
+ self.tell("the code of \(l.label) in \(Int(code.wait.rounded(.up))) s")
1279
+ DispatchQueue.main.asyncAfter(deadline: .now() + code.wait) { [weak self] in
1280
+ guard let self, self.web.url.map(pageOrigin) == origin else { return }
1281
+ put("", "", code.value)
1282
+ }
1283
+ }
1284
+ }
1285
+ }
1286
+
1287
+ /** one line under the bar; a fill's goes after a while, a passkey's stays with its page */
1288
+ func tell(_ words: String, act: String? = nil, then: (() -> Void)? = nil) {
1289
+ said = words
1290
+ strip.label.stringValue = words
1291
+ strip.label.toolTip = words
1292
+ strip.act.title = act ?? ""
1293
+ strip.act.isHidden = act == nil
1294
+ strip.onAct = then
1295
+ strip.isHidden = false
1296
+ strip.needsLayout = true
1297
+ needsLayout = true
1298
+ if act == nil {
1299
+ DispatchQueue.main.asyncAfter(deadline: .now() + 6) { [weak self] in
1300
+ if self?.said == words { self?.hideStrip() }
1301
+ }
1302
+ }
1303
+ }
1304
+
1305
+ func hideStrip() {
1306
+ if strip.isHidden { return }
1307
+ strip.isHidden = true
1308
+ needsLayout = true
1309
+ }
1310
+
1311
+ /** the page asked a passkey and WebKit gave none: this app is no signed browser, so it never can. The identity's
1312
+ * Chrome (its passkeys, its Touch ID) opens the page he is on, through the hub's page; else the browser */
1313
+ func passkeyFailed(_ why: String) {
1314
+ let l = logins.first { $0.who != nil }
1315
+ let line = "This page asked a passkey (\(why)): macOS gives passkeys to a signed browser, never to this panel"
1316
+ guard let l, let who = l.who, let at = web.url else {
1317
+ return tell(line, act: "open in the browser") { [weak self] in self?.openOutside() }
1318
+ }
1319
+ tell(line, act: "open in \(who)'s Chrome") { [weak self] in self?.openChrome(l, at: at) }
1320
+ }
1321
+
1322
+ /** the page he is on in the identity's Chrome, as the url row's « Chrome » does: the hub's page asks it */
1323
+ func openChrome(_ l: PanelLogin, at: URL) {
1324
+ var c = URLComponents(url: at, resolvingAgainstBaseURL: false)
1325
+ c?.scheme = nil
1326
+ c?.host = nil
1327
+ c?.port = nil
1328
+ let path = c?.string.flatMap { $0.isEmpty ? nil : $0 } ?? "/"
1329
+ guard let page else { return tell("no hub page beside the panel: open it in the browser") }
1330
+ page.callAsyncJavaScript("const h = window.shipkitApp; if (h == null || typeof h.openChrome !== 'function') return 'this hub page opens no Chrome: reload it'; return await h.openChrome(repo, id, at)", arguments: ["repo": l.repo, "id": l.id, "at": path], in: nil, in: .page) { [weak self] r in
1331
+ let words = (try? r.get()) as? String ?? "the hub page did not answer"
1332
+ self?.tell(words)
1333
+ }
1334
+ }
1335
+
1336
+ // a page that does not open says why in the panel, never a blank pane
1337
+ func webView(_ web: WKWebView, didFailProvisionalNavigation nav: WKNavigation!, withError error: Error) { failed(error) }
1338
+ func webView(_ web: WKWebView, didFail nav: WKNavigation!, withError error: Error) { failed(error) }
1339
+
1340
+ func failed(_ error: Error) {
1341
+ let e = error as NSError
1342
+ // a load he replaced by another, and a response turned into a download, are no failure
1343
+ if e.code == NSURLErrorCancelled || (e.domain == "WebKitErrorDomain" && e.code == 102) { return }
1344
+ say("This page did not open: \(e.localizedDescription)\n\((e.userInfo[NSURLErrorFailingURLStringErrorKey] as? String) ?? asked?.absoluteString ?? "")")
1345
+ }
1346
+
1347
+ // window.open and target=_blank: the page in the panel itself
1348
+ func webView(_ web: WKWebView, createWebViewWith config: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
1349
+ web.load(action.request)
1350
+ return nil
1351
+ }
1352
+
1353
+ // alert, confirm and prompt: the app's own sheets
1354
+ func webView(_ web: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
1355
+ guard let d = NSApp.delegate as? Delegate else { return completionHandler() }
1356
+ d.webView(web, runJavaScriptAlertPanelWithMessage: message, initiatedByFrame: frame, completionHandler: completionHandler)
1357
+ }
1358
+
1359
+ func webView(_ web: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
1360
+ guard let d = NSApp.delegate as? Delegate else { return completionHandler(false) }
1361
+ d.webView(web, runJavaScriptConfirmPanelWithMessage: message, initiatedByFrame: frame, completionHandler: completionHandler)
1362
+ }
1363
+
1364
+ func webView(_ web: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
1365
+ guard let d = NSApp.delegate as? Delegate else { return completionHandler(nil) }
1366
+ d.webView(web, runJavaScriptTextInputPanelWithPrompt: prompt, defaultText: defaultText, initiatedByFrame: frame, completionHandler: completionHandler)
1367
+ }
1368
+ }
1369
+
1370
+ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate, NSWindowDelegate, NSMenuItemValidation, WKScriptMessageHandler, UNUserNotificationCenterDelegate {
1371
+ var windows: [NSWindow] = []
1372
+ var opened = false
1373
+
1374
+ // a click on a notification can launch the app: its delegate is set before launch ends
1375
+ func applicationWillFinishLaunching(_ note: Notification) {
1376
+ if isShipkit && !CommandLine.arguments.contains(where: { $0.hasPrefix("--self-test") }) { UNUserNotificationCenter.current().delegate = self }
1377
+ }
1378
+
1379
+ func applicationDidFinishLaunching(_ note: Notification) {
1380
+ if CommandLine.arguments.contains("--self-test-find") { return selfTestFind() }
1381
+ if CommandLine.arguments.contains("--self-test-paste") { return selfTestPaste() }
1382
+ if CommandLine.arguments.contains("--self-test-mic") { return selfTestMic() }
1383
+ if CommandLine.arguments.contains("--self-test-panels") { return selfTestPanels() }
1384
+ if CommandLine.arguments.contains("--self-test-download") { return selfTestDownload() }
1385
+ if CommandLine.arguments.contains("--self-test-badge") { return selfTestBadge() }
1386
+ if CommandLine.arguments.contains("--self-test-reload") { return selfTestReload() }
1387
+ if CommandLine.arguments.contains("--self-test-tabs") { return selfTestTabs() }
1388
+ if let i = CommandLine.arguments.firstIndex(of: "--self-test-windows") { return selfTestWindows(to: i + 1 < CommandLine.arguments.count ? CommandLine.arguments[i + 1] : nil) }
1389
+ if CommandLine.arguments.contains("--self-test-links") { return selfTestLinks() }
1390
+ if CommandLine.arguments.contains("--self-test-address") { return selfTestAddress() }
1391
+ 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))) }
1392
+ if let i = CommandLine.arguments.firstIndex(of: "--self-test-chips") { return selfTestChips(to: i + 1 < CommandLine.arguments.count ? CommandLine.arguments[i + 1] : nil) }
1393
+ if let i = CommandLine.arguments.firstIndex(of: "--self-test-side") { return selfTestSide(to: i + 1 < CommandLine.arguments.count ? CommandLine.arguments[i + 1] : nil) }
1394
+ if CommandLine.arguments.contains("--self-test-restart") { return selfTestRestart() }
1395
+ if let i = CommandLine.arguments.firstIndex(of: "--self-test-fill") { return selfTestFill(to: i + 1 < CommandLine.arguments.count ? CommandLine.arguments[i + 1] : nil) }
1396
+ buildMenu()
1397
+ watchBuild()
1398
+ // the system asks the owner once; refused, the badge still counts and each notification says why it did not show
1399
+ if isShipkit {
1400
+ UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { ok, err in
1401
+ if !ok { NSLog("shipkit: notifications are off for this app (System Settings, Notifications, shipkit)\(err.map { ": \($0.localizedDescription)" } ?? "")") }
1402
+ }
1403
+ }
1404
+ // `--background`: running with no window from the start, the badge live, as after the last window closed
1405
+ if isShipkit && CommandLine.arguments.contains("--background") {
1406
+ opened = true
1407
+ keep(home: startURL)
1408
+ }
1409
+ watchKeys()
1410
+ // the windows a relaunch kept come back; a launch with none to show keeps them for the next one
1411
+ if !CommandLine.arguments.contains("--background"), let kept = takeKept(), !kept.windows.isEmpty {
1412
+ opened = true
1413
+ restore(kept)
1414
+ }
1415
+ // an open event may deliver the url right after launch: wait for it
1416
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
1417
+ if !self.opened {
1418
+ let arg = CommandLine.arguments.dropFirst().first { $0.hasPrefix("http") }
1419
+ self.open(arg.flatMap { URL(string: $0) } ?? startURL)
1420
+ }
1421
+ }
1422
+ }
1423
+
1424
+ func application(_ app: NSApplication, open urls: [URL]) {
1425
+ for u in urls { open(u) }
1426
+ }
1427
+
1428
+ // the home app stays running with no window, as a mail or chat app does, so its badge stays live; Quit ends it
1429
+ func applicationShouldTerminateAfterLastWindowClosed(_ app: NSApplication) -> Bool { !isShipkit && !selfTesting }
1430
+
1431
+ func applicationShouldHandleReopen(_ app: NSApplication, hasVisibleWindows: Bool) -> Bool {
1432
+ if !hasVisibleWindows { open(startURL) }
1433
+ return true
1434
+ }
1435
+
1436
+ func keyPane() -> Pane? { NSApp.keyWindow?.contentView as? Pane }
1437
+
1438
+ /** the digit row's physical keys, 1 to 9: an AZERTY keyboard types `&` to `ç` on them, and the tab is the same */
1439
+ static let digitKeys: [UInt16: Int] = [18: 1, 19: 2, 20: 3, 21: 4, 23: 5, 22: 6, 26: 7, 28: 8, 25: 9]
1440
+
1441
+ /** the keys the app takes before the page: esc closes the find bar of the key window; command and shift with the
1442
+ * two keys right of P (their physical keys), or command with page up or page down, step the window's tabs; in a
1443
+ * project app command with a key of the digit row (its physical key) selects that tab, command with t opens the
1444
+ * 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
1445
+ * command with n asks the new thread popup, a key no page of the hub reads. Every other key reaches the page first, a
1446
+ * terminal's among them (control keys, option, esc, shift with return, command with c, v or k), and a menu
1447
+ * takes one only when the page left it. True: taken */
1448
+ func takes(_ e: NSEvent) -> Bool {
1449
+ let mods = e.modifierFlags.intersection([.command, .shift, .option, .control])
1450
+ if e.keyCode == 53, let pane = keyPane(), pane.isFindBarVisible {
1451
+ pane.hideFind()
1452
+ return true
1453
+ }
1454
+ 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
1455
+ if step != 0 {
1456
+ stepTab(of: NSApp.keyWindow ?? NSApp.mainWindow ?? windows.first, by: step)
1457
+ return true
1458
+ }
1459
+ if mods == [.command], let n = Delegate.digitKeys[e.keyCode], tabDigits(mode).contains(n) {
1460
+ selectTab(digit: n)
1461
+ return true
1462
+ }
1463
+ if tabbed, let c = e.charactersIgnoringModifiers?.lowercased(), mods == [.command] && (c == "t" || c == "w") || mods == [.command, .shift] && c == "w" {
1464
+ if c == "t" { entryTab(nil) } else if mods.contains(.shift) { closeEveryTab(nil) } else { closeTab(nil) }
1465
+ return true
1466
+ }
1467
+ if hubApp, mods == [.command], e.charactersIgnoringModifiers?.lowercased() == "n" {
1468
+ newThread(nil)
1469
+ return true
1470
+ }
1471
+ if hubApp, mods == [.command, .shift], e.charactersIgnoringModifiers?.lowercased() == "n" {
1472
+ if tabbed { projectWindow(nil) } else { newWindow(nil) }
1473
+ return true
1474
+ }
1475
+ return false
1476
+ }
1477
+
1478
+ func watchKeys() {
1479
+ NSEvent.addLocalMonitorForEvents(matching: .keyDown) { e in self.takes(e) ? nil : e }
1480
+ }
1481
+
1482
+ // one more window on the page shown; in a project app one more tab on it
1483
+ @objc func newWindow(_ sender: Any?) {
1484
+ open(keyPane()?.web.url ?? startURL, again: true)
1485
+ }
1486
+
1487
+ /** shift command n, a project app's: one more window of the project, its own and never a tab of the one in front,
1488
+ * its first tab the hub's start page, not pinned: the window that holds the pinned hub stays the project's */
1489
+ @objc func projectWindow(_ sender: Any?) {
1490
+ guard !windows.isEmpty else { return open(startURL) }
1491
+ let w = makeWindow(startURL, alone: true)
1492
+ // macOS puts a window of preferred tabbing, as it first comes on a screen, into a window of its identifier
1493
+ w.tabbingMode = .disallowed
1494
+ show(w)
1495
+ w.tabbingMode = .preferred
1496
+ settleTabs()
1497
+ }
1498
+
1499
+ /** 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,
1500
+ * its entry included, since a hub page walks from entry to entry; the hub's own tab walks them all and is never
1501
+ * one of them. Any other page is found by the address it was opened on, or shows */
1502
+ func tab(on url: URL) -> NSWindow? {
1503
+ let key = tabKey(url)
1504
+ return windows.first { w in
1505
+ guard let pane = w.contentView as? Pane, !pane.pinned else { return false }
1506
+ if isHub(url) { return (pane.web.url ?? pane.opened).map(tabKey) == key }
1507
+ return pane.opened.map(tabKey) == key || pane.web.url.map(tabKey) == key
1508
+ }
1509
+ }
1510
+
1511
+ /** a project app's hub tab, the one pinned */
1512
+ var hubTab: NSWindow? { windows.first(where: isPinned) }
1513
+
1514
+ /** the app's window in front: the key one when it is a window of pages (a panel or a sheet is none) */
1515
+ var frontWindow: NSWindow? { NSApp.keyWindow.flatMap { k in windows.first { $0 === k } } }
1516
+
1517
+ /** the tabs of a window in their order: the key window's, else the project window's */
1518
+ func tabs(of w: NSWindow?) -> [NSWindow] {
1519
+ guard let w = w ?? windows.first else { return [] }
1520
+ return w.tabGroup?.windows ?? [w]
1521
+ }
1522
+
1523
+ /** the one place a window reaches the screen, in front. A self test never shows one */
1524
+ func onScreen(_ w: NSWindow) {
1525
+ if selfTesting { return }
1526
+ if w.isMiniaturized { w.deminiaturize(nil) }
1527
+ w.makeKeyAndOrderFront(nil)
1528
+ NSApp.activate(ignoringOtherApps: true)
1529
+ }
1530
+
1531
+ /** a window, or a project app's tab, in front */
1532
+ func show(_ w: NSWindow) {
1533
+ w.tabGroup?.selectedWindow = w
1534
+ onScreen(w)
1535
+ }
1536
+
1537
+ /** the one place an alert reaches the screen: a sheet on `win`, a modal with none; `done` hears its button. A
1538
+ * self test shows none: `onPanel` answers it, and with nobody to answer it is said on stderr and cancelled */
1539
+ func present(_ alert: NSAlert, on win: NSWindow? = nil, done: ((NSApplication.ModalResponse) -> Void)? = nil) {
1540
+ if selfTesting {
1541
+ // laid out as it would show, so its buttons and its field are the ones the owner would get
1542
+ alert.layout()
1543
+ if let onPanel { return onPanel(alert) { done?($0) } }
1544
+ FileHandle.standardError.write("shipkit: an alert a self test does not show: \(alert.messageText): \(alert.informativeText)\n".data(using: .utf8)!)
1545
+ done?(.cancel)
1546
+ return
1547
+ }
1548
+ if let win { alert.beginSheetModal(for: win) { done?($0) } } else {
1549
+ let r = alert.runModal()
1550
+ done?(r)
1551
+ }
1552
+ }
1553
+
1554
+ /** command with t: the entry the hub's tab shows (its address: a terminal, a Claude session, a process, a url,
1555
+ * 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
1556
+ * on that entry is shown, never a second one */
1557
+ @objc func entryTab(_ sender: Any?) {
1558
+ guard let pane = hubTab?.contentView as? Pane else { return }
1559
+ // an entry whose tab is no page of the hub's shell (a url's site, a terminal alone): what its page said
1560
+ if let e = entries[ObjectIdentifier(pane.web)] {
1561
+ if let name = e.name { tabNames[tabKey(e.url)] = name }
1562
+ return asksWindow(e.url, from: pane.web)
1563
+ }
1564
+ openTab(pane.web.url ?? startURL)
1565
+ }
1566
+
1567
+ /** a page of a project app asks a new window on an address (window.open, target=_blank with no policy asked,
1568
+ * command with t on an entry that names one): it goes down its road, a tab of the hub's own else */
1569
+ func asksWindow(_ url: URL, from web: WKWebView) {
1570
+ if !reroutes(url, from: web, new: true, click: false) { open(url, again: true) }
1571
+ }
1572
+
1573
+ /** the name a hub page gave the tab it asks next, by that tab's address (serve/hub-app/panel-repo.ts openTab) */
1574
+ var tabNames: [String: String] = [:]
1575
+ /** the login chips the same note names for that tab, a url's (wearChips) */
1576
+ var tabChips: [String: (urlId: String, logins: [String])] = [:]
1577
+ /** what command with t opens for the entry a hub page shows, by its web view, where that is not the page
1578
+ * itself (serve/hub-app/panel-source.ts, tab) */
1579
+ var entries: [ObjectIdentifier: (url: URL, name: String?)] = [:]
1580
+
1581
+ /** the tab a hub page named and opened before on this site: a url's row asked again shows its tab, where he
1582
+ * left it, never a second one */
1583
+ func tab(named url: URL) -> NSWindow? {
1584
+ guard !isHub(url), let name = tabNames[tabKey(url)] else { return nil }
1585
+ return windows.first { w in
1586
+ guard let pane = w.contentView as? Pane, pane.name == name else { return false }
1587
+ return (pane.web.url ?? pane.opened).map(originOf) == originOf(url)
1588
+ }
1589
+ }
1590
+
1591
+ // 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
1592
+ // is taken and nothing beeps
1593
+ @objc func selectTab(_ sender: NSMenuItem) { selectTab(digit: sender.tag) }
1594
+
1595
+ func selectTab(digit: Int) {
1596
+ let all = tabs(of: NSApp.keyWindow)
1597
+ if let i = tabIndex(digit: digit, count: all.count) { show(all[i]) }
1598
+ }
1599
+
1600
+ func isPinned(_ w: NSWindow?) -> Bool { (w?.contentView as? Pane)?.pinned == true }
1601
+
1602
+ /** the window whose red button was pressed, else the one in front, closes whole. The window that holds the hub's
1603
+ * tab is the project's: every window of the app closes with it, the hub's tab last, and the app quits. A window
1604
+ * of tabs pulled out of it closes alone */
1605
+ @objc func closeEveryTab(_ sender: Any?) {
1606
+ let from = tabs(of: (sender as? NSView)?.window ?? frontWindow)
1607
+ let all = from.contains(where: isPinned) ? windows : from
1608
+ for w in all.filter({ !isPinned($0) }) + all.filter(isPinned) { w.close() }
1609
+ }
1610
+
1611
+ // a project app has three closes, each on a road of its own, so none is told from another by where a click
1612
+ // landed: the window's red button sends `closeEveryTab` (makeWindow gives it that action), command with w and
1613
+ // `performClose` go through `closeTab`, and the tab bar's own close button is all that reaches `windowShouldClose`
1614
+
1615
+ // command with w closes the tab shown, and that tab alone; on the hub's tab, the one pinned, it is refused with the
1616
+ // pane's dot: the menu's Close Window, Quit and the window's red button close the project's window, nothing else does
1617
+ @objc func closeTab(_ sender: Any?) { closeTab(of: NSApp.keyWindow ?? windows.first?.tabGroup?.selectedWindow) }
1618
+
1619
+ func closeTab(of w: NSWindow?) {
1620
+ guard let w else { return }
1621
+ if isPinned(w) { (w.contentView as? Pane)?.blink() } else { w.close() }
1622
+ }
1623
+
1624
+ /** a tab's own close button in a project app: it closes that tab alone, whatever is left; the hub's, the one tab
1625
+ * the badge and the project's pages live in, is refused with the pane's dot. Any other app: the window closes */
1626
+ func windowShouldClose(_ sender: NSWindow) -> Bool {
1627
+ guard tabbed, isPinned(sender) else { return true }
1628
+ (sender.contentView as? Pane)?.blink()
1629
+ return false
1630
+ }
1631
+
1632
+ /** the tab bars this run asked for: a second look asks none again */
1633
+ var barsAsked = 0
1634
+ /** the windows whose bar stayed hidden once asked: never asked twice, so no look repeats */
1635
+ var barRefused = Set<ObjectIdentifier>()
1636
+ var settling = false
1637
+
1638
+ /** every window of a project app shows its tab bar, with one tab too. macOS hides the bar of a window whose group
1639
+ * holds one tab, and a window with no bar has no tab to drag into another window and takes none: two windows of
1640
+ * one tab each could never be one again. The bar is asked only where it is hidden */
1641
+ func showTabBars() {
1642
+ guard tabbed else { return }
1643
+ var seen: [NSWindowTabGroup] = []
1644
+ for w in windows {
1645
+ guard let g = w.tabGroup, !seen.contains(where: { $0 === g }) else { continue }
1646
+ seen.append(g)
1647
+ let shown = g.selectedWindow ?? w
1648
+ if g.isTabBarVisible || barRefused.contains(ObjectIdentifier(shown)) { continue }
1649
+ shown.toggleTabBar(nil)
1650
+ barsAsked += 1
1651
+ if !g.isTabBarVisible { barRefused.insert(ObjectIdentifier(shown)) }
1652
+ }
1653
+ }
1654
+
1655
+ /** the same look once the event that asked it is over (a tab dragged out or in still moves while its window
1656
+ * becomes key): one look a turn of the run loop, however many events asked */
1657
+ func settleTabs() {
1658
+ guard tabbed, !settling else { return }
1659
+ settling = true
1660
+ DispatchQueue.main.async {
1661
+ self.settling = false
1662
+ self.showTabBars()
1663
+ }
1664
+ }
1665
+
1666
+ func windowDidBecomeKey(_ note: Notification) { settleTabs() }
1667
+ func windowDidResignKey(_ note: Notification) { settleTabs() }
1668
+ func windowDidBecomeMain(_ note: Notification) { settleTabs() }
1669
+
1670
+ /** the tab shown leaves its window for one of its own, a step down and right of it, its tab bar shown: he drags
1671
+ * it back among the tabs, or merges */
1672
+ @objc func tabToNewWindow(_ sender: Any?) { split(frontWindow ?? windows.first?.tabGroup?.selectedWindow) }
1673
+
1674
+ func split(_ w: NSWindow?) {
1675
+ guard tabbed, let w, let g = w.tabGroup, g.windows.count > 1 else { return }
1676
+ let from = w.frame
1677
+ g.removeWindow(w)
1678
+ w.setFrameTopLeftPoint(NSPoint(x: from.minX + 28, y: from.maxY - 28))
1679
+ showTabBars()
1680
+ show(w)
1681
+ }
1682
+
1683
+ /** every window of the project back into one */
1684
+ @objc func mergeWindows(_ sender: Any?) { merge(shown: frontWindow) }
1685
+
1686
+ /** the hub's window takes the tabs of every other window after its own, each window's in their order, and the
1687
+ * hub's tab is first whatever place a drag gave it; `shown`, the tab he was on, stays the one shown */
1688
+ func merge(shown: NSWindow? = nil) {
1689
+ guard tabbed, let hub = hubTab ?? windows.first else { return }
1690
+ var kept = tabs(of: hub)
1691
+ for w in windows where !kept.contains(where: { $0 === w }) {
1692
+ for t in tabs(of: w) {
1693
+ kept.last?.addTabbedWindow(t, ordered: .above)
1694
+ kept.append(t)
1695
+ }
1696
+ }
1697
+ if isPinned(hub), let g = hub.tabGroup, g.windows.count > 1, g.windows.first !== hub {
1698
+ g.removeWindow(hub)
1699
+ g.insertWindow(hub, at: 0)
1700
+ }
1701
+ showTabBars()
1702
+ show(shown ?? hub)
1703
+ }
1704
+
1705
+ /** the windows of the app, each a group of tabs */
1706
+ var windowCount: Int { Set(windows.map { w in ObjectIdentifier(w.tabGroup?.windows.first ?? w) }).count }
1707
+
1708
+ /** command with n: the hub page in front opens its new thread popup (serve/hub-app/app-bridge.ts, newThread). A
1709
+ * tab with none to open (another site, a terminal alone) hands the ask to the hub's tab, which comes forward;
1710
+ * with no window the home opens one first */
1711
+ @objc func newThread(_ sender: Any?) {
1712
+ var panes: [Pane] = []
1713
+ for p in [keyPane(), hubTab?.contentView as? Pane, windows.first?.contentView as? Pane] {
1714
+ if let p, !panes.contains(where: { $0 === p }) { panes.append(p) }
1715
+ }
1716
+ if panes.isEmpty {
1717
+ open(startURL)
1718
+ if let p = windows.last?.contentView as? Pane { panes = [p] }
1719
+ }
1720
+ askNewThread(panes, tries: 12)
1721
+ }
1722
+
1723
+ /** each pane in turn until a hub page says it opened the popup; a page still loading has no hook yet, so the
1724
+ * round is asked again `tries` times, then the first pane marks the key as not taken */
1725
+ func askNewThread(_ panes: [Pane], tries: Int, at i: Int = 0) {
1726
+ guard i < panes.count else {
1727
+ if tries > 0 { DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { self.askNewThread(panes, tries: tries - 1) } } else { panes.first?.blink() }
1728
+ return
1729
+ }
1730
+ let pane = panes[i]
1731
+ guard pane.window != nil, pane.web.url.map(isHub) == true else { return askNewThread(panes, tries: tries, at: i + 1) }
1732
+ pane.web.callAsyncJavaScript("return !!(window.shipkitApp && shipkitApp.newThread && shipkitApp.newThread())", arguments: [:], in: nil, in: .page) { r in
1733
+ if case .success(let v) = r, (v as? Bool) == true {
1734
+ if let w = pane.window { self.show(w) }
1735
+ return
1736
+ }
1737
+ self.askNewThread(panes, tries: tries, at: i + 1)
1738
+ }
1739
+ }
1740
+
1741
+ /// the tab after or before the one a window shows, round to the first; one tab alone stays
1742
+ func stepTab(of w: NSWindow?, by: Int) {
1743
+ guard let g = w?.tabGroup, let shown = g.selectedWindow, let i = g.windows.firstIndex(of: shown), g.windows.count > 1 else { return }
1744
+ let to = g.windows[(i + by + g.windows.count) % g.windows.count]
1745
+ g.selectedWindow = to
1746
+ onScreen(to)
1747
+ }
1748
+
1749
+ @objc func nextTab(_ sender: Any?) { stepTab(of: NSApp.keyWindow ?? NSApp.mainWindow, by: 1) }
1750
+ @objc func previousTab(_ sender: Any?) { stepTab(of: NSApp.keyWindow ?? NSApp.mainWindow, by: -1) }
1751
+
1752
+ @objc func reload(_ sender: Any?) {
1753
+ keyPane()?.web.reload()
1754
+ }
1755
+
1756
+ // the zoom is one value for every window of the app, kept across restarts
1757
+ var zoom: CGFloat {
1758
+ get { let z = UserDefaults.standard.double(forKey: "pageZoom"); return z > 0 ? CGFloat(z) : 1 }
1759
+ set {
1760
+ let z = min(3, max(0.3, newValue))
1761
+ UserDefaults.standard.set(Double(z), forKey: "pageZoom")
1762
+ for w in windows { (w.contentView as? Pane)?.web.pageZoom = z }
1763
+ }
1764
+ }
1765
+
1766
+ @objc func zoomIn(_ sender: Any?) { zoom = zoom * 1.1 }
1767
+ @objc func zoomOut(_ sender: Any?) { zoom = zoom / 1.1 }
1768
+ @objc func zoomReset(_ sender: Any?) { zoom = 1 }
1769
+
1770
+ @objc func showFind(_ sender: Any?) { keyPane()?.showFind() }
1771
+ @objc func hideFind(_ sender: Any?) { keyPane()?.hideFind() }
1772
+ @objc func findNext(_ sender: Any?) { keyPane()?.findNext() }
1773
+ @objc func findPrevious(_ sender: Any?) { keyPane()?.findPrevious() }
1774
+
1775
+ // no public api opens the inspector: `_inspector` then `show` is the
1776
+ // WebKit call the context menu's Inspect Element makes. Where it is gone,
1777
+ // say where the inspector still is
1778
+ @objc func devTools(_ sender: Any?) {
1779
+ guard let web = keyPane()?.web else { return }
1780
+ let get = NSSelectorFromString("_inspector"), show = NSSelectorFromString("show")
1781
+ if web.responds(to: get), let inspector = web.perform(get)?.takeUnretainedValue() as? NSObject, inspector.responds(to: show) {
1782
+ inspector.perform(show)
1783
+ return
1784
+ }
1785
+ let alert = NSAlert()
1786
+ alert.messageText = "This WebKit has no way to open the inspector from a menu"
1787
+ alert.informativeText = "Right click the page and pick Inspect Element."
1788
+ present(alert)
1789
+ }
1790
+
1791
+ func validateMenuItem(_ item: NSMenuItem) -> Bool {
1792
+ if item.action == #selector(hideFind(_:)) { return keyPane()?.isFindBarVisible == true }
1793
+ if item.action == #selector(findNext(_:)) || item.action == #selector(findPrevious(_:)) { return keyPane()?.field.stringValue.isEmpty == false }
1794
+ if item.action == #selector(showFind(_:)) { return keyPane() != nil }
1795
+ if item.action == #selector(mergeWindows(_:)) { return windowCount > 1 }
1796
+ if item.action == #selector(tabToNewWindow(_:)) { return tabs(of: frontWindow).count > 1 }
1797
+ if item.action == #selector(devTools(_:)) || item.action == #selector(reload(_:)) { return keyPane() != nil }
1798
+ return true
1799
+ }
1800
+
1801
+ /** `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 */
1802
+ func webConfig(bridge: Bool = true) -> WKWebViewConfiguration {
1803
+ let config = WKWebViewConfiguration()
1804
+ config.preferences.setValue(true, forKey: "developerExtrasEnabled")
1805
+ if selfTesting { config.websiteDataStore = .nonPersistent() }
1806
+ if hasBadge && bridge {
1807
+ config.userContentController.add(self, name: "shipkit")
1808
+ // the page may ask a url in its window's side panel: an app built before this says nothing, and the page
1809
+ // keeps its links as a browser's (app-bridge.ts appSide)
1810
+ config.userContentController.addUserScript(WKUserScript(source: "window.__skSidePanel = true", injectionTime: .atDocumentStart, forMainFrameOnly: true))
1811
+ // the home's badge poll keeps its pace while its window is hidden or covered; a project app's page is throttled
1812
+ // as any background page is: its badge moves at that slower pace
1813
+ if isShipkit, #available(macOS 14.0, *) { config.preferences.inactiveSchedulingPolicy = .none }
1814
+ }
1815
+ return config
1816
+ }
1817
+
1818
+ /** the page of the home the app keeps loaded while no window is open: it alone keeps the badge and the
1819
+ * notifications live, and leaves once a window's page posts again */
1820
+ var keeper: WKWebView?
1821
+
1822
+ func keep(home: URL) {
1823
+ let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 1400, height: 900), configuration: webConfig())
1824
+ web.navigationDelegate = self
1825
+ web.load(URLRequest(url: home))
1826
+ keeper = web
1827
+ }
1828
+
1829
+ /** an address asked from outside a page: the launch, the Dock, `open -a`. A project app starts with ONE tab, its
1830
+ * hub, pinned, and its start address is that tab; any other address is a tab beside it. `again`: one more page
1831
+ * on an address already shown */
1832
+ func open(_ url: URL, again: Bool = false) {
1833
+ opened = true
1834
+ guard tabbed else { return show(makeWindow(url)) }
1835
+ if windows.isEmpty { _ = makeWindow(startURL, pinned: true) }
1836
+ if !again, tabKey(url) == tabKey(startURL), let hub = hubTab { return show(hub) }
1837
+ openTab(url, again: again)
1838
+ }
1839
+
1840
+ /** a page as a tab beside the hub's: the tab already open on that address is shown, never loaded twice, else one
1841
+ * more after the last */
1842
+ func openTab(_ url: URL, again: Bool = false) {
1843
+ if !again, let w = tab(on: url) ?? tab(named: url) { return show(w) }
1844
+ show(makeWindow(url))
1845
+ }
1846
+
1847
+ /** a window's web view, not loaded yet. `view`: what a page kept of its scrolls before it asked for a fresh view
1848
+ * (hub-app/page-reload.ts), put back where that page reads it, before its first script */
1849
+ func makeWeb(_ url: URL, view: String? = nil) -> Web {
1850
+ // a tab of another site, in a project app or the home app, gets no bridge: only the hub's pages post to the app
1851
+ let config = webConfig(bridge: !hubApp || isHub(url))
1852
+ // parsed and written again: the page's words never reach the script as they came
1853
+ 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) {
1854
+ config.userContentController.addUserScript(WKUserScript(source: "try { sessionStorage.setItem('sk-view', JSON.stringify(\(json))) } catch (e) {}", injectionTime: .atDocumentStart, forMainFrameOnly: true))
1855
+ }
1856
+ // a hub page's frames say their address once the page asks (reporterScript)
1857
+ if hubApp && isHub(url) { config.userContentController.addUserScript(WKUserScript(source: reporterScript(hub: pageOrigin(startURL)), injectionTime: .atDocumentStart, forMainFrameOnly: false)) }
1858
+ let web = Web(frame: .zero, configuration: config)
1859
+ if #available(macOS 13.3, *) { web.isInspectable = true }
1860
+ web.navigationDelegate = self
1861
+ web.uiDelegate = self
1862
+ web.allowsBackForwardNavigationGestures = true
1863
+ web.allowsMagnification = true
1864
+ web.pageZoom = zoom
1865
+ return web
1866
+ }
1867
+
1868
+ /** the pages loading in a fresh web view, by that view, each with the view it replaces */
1869
+ var arriving: [ObjectIdentifier: (new: WKWebView, old: WKWebView)] = [:]
1870
+ /** the longest a fresh view loads before it takes its place anyway */
1871
+ static let arriveWait = 2.5
1872
+ /** how a fresh view loads its page: a self test hands it one with no server */
1873
+ var loadFresh: (WKWebView, URL) -> Void = { $0.load(URLRequest(url: $1)) }
1874
+
1875
+ /** a hub page asks to be loaded again (a new build). WebKit keeps a page reloaded in place alive whole, one page a
1876
+ * reload, so the page loads in a fresh web view and the old one leaves with its process. The old page stays on the
1877
+ * screen and takes the keys until the fresh one loaded: a terminal tab loses no key */
1878
+ func reload(_ old: WKWebView, to url: URL, view: String?) {
1879
+ guard isHub(url), !arriving.values.contains(where: { $0.old === old }) else { return }
1880
+ // the page reloads in place by itself when nothing says this: an app built before this request
1881
+ old.evaluateJavaScript("window.__skAppReloads = true") { _, _ in }
1882
+ if old === keeper { return keep(home: url) }
1883
+ guard old.superview is Pane else { return }
1884
+ let new = makeWeb(url, view: view)
1885
+ new.frame = old.frame
1886
+ new.pageZoom = old.pageZoom
1887
+ new.magnification = old.magnification
1888
+ arriving[ObjectIdentifier(new)] = (new, old)
1889
+ loadFresh(new, url)
1890
+ DispatchQueue.main.asyncAfter(deadline: .now() + Delegate.arriveWait) { [weak self, weak new] in if let new { self?.arrive(new) } }
1891
+ }
1892
+
1893
+ /** the fresh view takes its place: the old one is dropped, its count with it. A window closed meanwhile drops both */
1894
+ func arrive(_ new: WKWebView) {
1895
+ guard let pair = arriving.removeValue(forKey: ObjectIdentifier(new)), let pane = pair.old.superview as? Pane else { return }
1896
+ pane.swap(to: new)
1897
+ pair.old.navigationDelegate = nil
1898
+ pair.old.uiDelegate = nil
1899
+ pair.old.stopLoading()
1900
+ // the tab's count goes to the fresh view until its page posts its own: the badge never blinks for a build
1901
+ let n = counts.removeValue(forKey: ObjectIdentifier(pair.old))
1902
+ if let n, counts[ObjectIdentifier(new)] == nil { counts[ObjectIdentifier(new)] = n }
1903
+ drawBadge()
1904
+ }
1905
+
1906
+ // `--self-test-reload`, in a project app: its hub tab's page asks for a fresh web view, as hub-app/page-reload.ts
1907
+ // does for a new build. exit 0 only when the tab's pane holds another web view on the fresh page, that page read
1908
+ // the view the old one kept, the tab kept its place, its pin and its window, the count went to the fresh view, the
1909
+ // old view is gone from memory (its process ends with it), and an address that is no hub's was not obeyed
1910
+ func selfTestReload() {
1911
+ DispatchQueue.main.asyncAfter(deadline: .now() + 20) { print("timeout"); finish(1) }
1912
+ 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) }
1913
+ let hub = makeWindow(startURL, pinned: true)
1914
+ _ = makeWindow(startURL.appendingPathComponent("other"))
1915
+ guard let pane = hub.contentView as? Pane else { finish(1) }
1916
+ pane.web.loadHTMLString("<title>old</title><p>old</p>", baseURL: startURL)
1917
+ weak var old = pane.web
1918
+ let oldId = ObjectIdentifier(pane.web)
1919
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
1920
+ self.counts[oldId] = 2
1921
+ let before = self.tabs(of: nil).map { ObjectIdentifier($0) }
1922
+ self.reload(pane.web, to: URL(string: "https://example.com/")!, view: nil)
1923
+ print("foreign=\(self.arriving.isEmpty ? "refused" : "obeyed")")
1924
+ 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
1925
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
1926
+ pane.web.evaluateJavaScript("document.title + '|' + document.body.dataset.view") { v, _ in
1927
+ print("swapped=\(ObjectIdentifier(pane.web) != oldId) page=\(v ?? "nil") title=\(hub.title)")
1928
+ print("tab-kept=\(before == self.tabs(of: nil).map { ObjectIdentifier($0) }) pinned=\(pane.pinned) windows=\(self.windows.count)")
1929
+ print("count=\(self.counts[ObjectIdentifier(pane.web)] ?? -1) old-count=\(self.counts[oldId] ?? -1)")
1930
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
1931
+ print("old-view=\(old == nil ? "gone" : "held")")
1932
+ finish(0)
1933
+ }
1934
+ }
1935
+ }
1936
+ }
1937
+ }
1938
+ }
1939
+
1940
+ /** the fresh view cannot load (the server restarts): the old page reloads in place, as it did before */
1941
+ func webView(_ web: WKWebView, didFailProvisionalNavigation nav: WKNavigation!, withError error: Error) {
1942
+ guard let pair = arriving.removeValue(forKey: ObjectIdentifier(web)) else { return }
1943
+ pair.old.reload()
1944
+ }
1945
+
1946
+ /** 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
1947
+ * a step down and right of the one in front */
1948
+ func makeWindow(_ url: URL, pinned: Bool = false, alone: Bool = false) -> NSWindow {
1949
+ let web = makeWeb(url)
1950
+ let frame = NSRect(x: 0, y: 0, width: 1400, height: 900)
1951
+ let win = QuietWindow(contentRect: frame, styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
1952
+ let pane = Pane(web: web)
1953
+ pane.opened = url
1954
+ pane.pinned = pinned
1955
+ win.contentView = pane
1956
+ win.title = appName
1957
+ pane.name = isHub(url) ? nil : tabNames[tabKey(url)]
1958
+ if tabbed, !isHub(url), let chips = tabChips[tabKey(url)] { wearChips(win, chips) }
1959
+ win.delegate = self
1960
+ win.isReleasedWhenClosed = false
1961
+ if !selfTesting { win.setFrameAutosaveName("shipkit-window") }
1962
+ paint(win, tint, text: tintText)
1963
+ offerRelaunch(win)
1964
+ if tabbed {
1965
+ win.tabbingMode = .preferred
1966
+ win.tabbingIdentifier = "project"
1967
+ // the red button closes the window whole through an action of its own, so it never reaches windowShouldClose
1968
+ if let red = win.standardWindowButton(.closeButton) {
1969
+ red.target = self
1970
+ red.action = #selector(closeEveryTab(_:))
1971
+ }
1972
+ if alone, let from = frontWindow ?? hubTab {
1973
+ win.setFrameTopLeftPoint(NSPoint(x: from.frame.minX + 28, y: from.frame.maxY - 28))
1974
+ } else if !alone, let last = tabs(of: frontWindow).last { last.addTabbedWindow(win, ordered: .above) } else { win.center() }
1975
+ } else if let last = windows.last { win.setFrameTopLeftPoint(NSPoint(x: last.frame.minX + 28, y: last.frame.maxY - 28)) } else { win.center() }
1976
+ windows.append(win)
1977
+ // before it is ever shown: a project's window is born with its tab bar
1978
+ showTabBars()
1979
+ web.load(URLRequest(url: url))
1980
+ win.makeFirstResponder(web)
1981
+ return win
1982
+ }
1983
+
1984
+ var onLoad: ((WKWebView) -> Void)?
1985
+
1986
+ // `--self-test-tabs`: two windows that are never shown as two tabs of one window, the first selected; command with page down, then
1987
+ // 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
1988
+ // asked which item takes the key, and the step that item makes is run on the tab shown, as it runs on the key
1989
+ // window. exit 0 only when each key has its item and the tab moved to the second and back, and, the app being no
1990
+ // project's, command with a digit has no item and is left to the page. A project app runs `selfTestProjectTabs`
1991
+ func selfTestTabs() {
1992
+ if tabbed { return selfTestProjectTabs() }
1993
+ buildMenu()
1994
+ let make = { () -> NSWindow in
1995
+ let w = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
1996
+ w.contentView = Pane(web: WKWebView(frame: .zero, configuration: WKWebViewConfiguration()))
1997
+ w.tabbingMode = .preferred
1998
+ return w
1999
+ }
2000
+ let a = make(), b = make()
2001
+ windows.append(contentsOf: [a, b])
2002
+ a.addTabbedWindow(b, ordered: .above)
2003
+ a.tabGroup?.selectedWindow = a
2004
+ let shown = { () -> Int in a.tabGroup?.selectedWindow === b ? 2 : a.tabGroup?.selectedWindow === a ? 1 : 0 }
2005
+ // the item of the menus that takes command with this key, and whether the menu took the real event
2006
+ let press = { (key: Int, code: UInt16) -> String in
2007
+ let chars = String(UnicodeScalar(key)!)
2008
+ let item = NSApp.windowsMenu?.items.first { $0.keyEquivalent == chars && $0.keyEquivalentModifierMask == [.command] }
2009
+ guard let item, let e = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [.command, .function], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: a.windowNumber, context: nil, characters: chars, charactersIgnoringModifiers: chars, isARepeat: false, keyCode: code) else { return "no item" }
2010
+ let took = NSApp.mainMenu?.performKeyEquivalent(with: e) ?? false
2011
+ self.stepTab(of: a.tabGroup?.selectedWindow, by: item.action == #selector(self.nextTab(_:)) ? 1 : item.action == #selector(self.previousTab(_:)) ? -1 : 0)
2012
+ return "\(item.title), menu took the key: \(took)"
2013
+ }
2014
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
2015
+ let start = shown()
2016
+ let down = press(NSPageDownFunctionKey, 121)
2017
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
2018
+ let afterDown = shown()
2019
+ let up = press(NSPageUpFunctionKey, 116)
2020
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
2021
+ let afterUp = shown()
2022
+ print("tabs=\(a.tabGroup?.windows.count ?? 0) start=\(start)")
2023
+ print("page-down=\(down) shown=\(afterDown)")
2024
+ print("page-up=\(up) shown=\(afterUp)")
2025
+ let digits = (NSApp.windowsMenu?.items ?? []).filter { $0.action == #selector(self.selectTab(_:)) }.map(\.keyEquivalent).joined()
2026
+ let taken = self.key("&", 18, [.command]).map(self.takes) ?? true
2027
+ print("mode=\(mode) digits=\(digits.isEmpty ? "none" : digits) digit-taken=\(taken)")
2028
+ 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)
2029
+ }
2030
+ }
2031
+ }
2032
+ }
2033
+
2034
+ /** a key down as the keyboard sends it: its characters, its physical key, its modifiers; `plain`: what the key
2035
+ * types with no modifier, where control or option changed it */
2036
+ func key(_ chars: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags, plain: String? = nil) -> NSEvent? {
2037
+ 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)
2038
+ }
2039
+
2040
+ // `--self-test-tabs` in a project app (the bundle's ShipkitMode): its real window, never shown, on the hub the
2041
+ // test serves at the bundle's start url (tests/gui-app-live.test.ts: the hub's page, whose address moves from
2042
+ // 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
2043
+ // terminal route, a second site of the machine under `localhost`). Each link is clicked as a real mouse event,
2044
+ // each key sent as its key event (the digit row as an AZERTY keyboard types it), the red button pressed as the
2045
+ // mouse presses it, the road out recorded instead of taken. One line a fact, ` expected …` under one that is
2046
+ // wrong; exit 0 only when every line is as the owner would see it
2047
+ func selfTestProjectTabs() {
2048
+ buildMenu()
2049
+ var out: [String] = []
2050
+ openOutside = { out.append($0.absoluteString) }
2051
+ var ok = true
2052
+ func say(_ name: String, _ got: String, _ want: String) {
2053
+ print("\(name)=\(got)")
2054
+ if got != want { ok = false; print(" expected \(want)") }
2055
+ }
2056
+ DispatchQueue.main.asyncAfter(deadline: .now() + 90) { print("timeout"); finish(1) }
2057
+ /** runs `then` once `cond` holds, or after 8 s: the line that follows says what did not happen */
2058
+ func until(_ cond: @escaping () -> Bool, _ then: @escaping () -> Void) {
2059
+ let start = Date()
2060
+ func poll() {
2061
+ if cond() || Date().timeIntervalSince(start) > 8 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: then) }
2062
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
2063
+ }
2064
+ poll()
2065
+ }
2066
+ func all() -> [NSWindow] { tabs(of: nil) }
2067
+ func pane(_ i: Int) -> Pane? { i < all().count ? all()[i].contentView as? Pane : nil }
2068
+ func selected() -> NSWindow? { self.windows.first?.tabGroup?.selectedWindow ?? (all().count == 1 ? all().first : nil) }
2069
+ func shown() -> Int { all().firstIndex { $0 === selected() }.map { $0 + 1 } ?? 0 }
2070
+ func loaded(_ i: Int) -> Bool { pane(i).map { !$0.web.isLoading && $0.web.title?.isEmpty == false } ?? false }
2071
+ func titles() -> String { all().map(\.title).joined(separator: "|") }
2072
+ /** a press and a release of the mouse on a view of the window, which is never shown */
2073
+ func mouse(_ type: NSEvent.EventType, _ at: NSPoint, _ win: NSWindow) -> NSEvent? {
2074
+ 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)
2075
+ }
2076
+ func click(_ i: Int, _ id: String) {
2077
+ guard let web = pane(i)?.web, let win = web.window else { return }
2078
+ show(win)
2079
+ web.evaluateJavaScript("(() => { const r = document.getElementById('\(id)').getBoundingClientRect(); return [r.left + 4, r.top + r.height / 2] })()") { v, _ in
2080
+ guard let xy = v as? [Double], xy.count == 2 else { return print("no link \(id)") }
2081
+ let at = web.convert(NSPoint(x: xy[0], y: web.isFlipped ? xy[1] : web.bounds.height - xy[1]), to: nil)
2082
+ if let e = mouse(.leftMouseDown, at, win) { web.mouseDown(with: e) }
2083
+ if let e = mouse(.leftMouseUp, at, win) { web.mouseUp(with: e) }
2084
+ }
2085
+ }
2086
+ /** the window's red button pressed as the mouse presses it, at its middle: a button follows the mouse in a
2087
+ * loop of its own from the press on, so the release waits in the queue, where that loop reads it */
2088
+ func pressRed(_ w: NSWindow) -> String {
2089
+ guard let red = w.standardWindowButton(.closeButton) else { return "no red button" }
2090
+ let at = red.convert(NSPoint(x: red.bounds.midX, y: red.bounds.midY), to: nil)
2091
+ guard let down = mouse(.leftMouseDown, at, w), let up = mouse(.leftMouseUp, at, w) else { return "no event" }
2092
+ NSApp.postEvent(up, atStart: false)
2093
+ red.mouseDown(with: down)
2094
+ return "pressed"
2095
+ }
2096
+ /** the close button of the nth tab, as the tab bar sends its click on: the button itself shows only under the
2097
+ * mouse, which a window that is never shown never has. AppKit's own names, so one that is gone is said */
2098
+ func tabClose(_ i: Int) -> String {
2099
+ guard let frame = selected()?.contentView?.superview else { return "no frame" }
2100
+ frame.layoutSubtreeIfNeeded()
2101
+ func find(_ v: NSView, _ name: String) -> [NSView] { v.className == name ? [v] : v.subviews.flatMap { find($0, name) } }
2102
+ guard let bar = find(frame, "NSTabBar").first else { return "no tab bar" }
2103
+ let buttons = find(bar, "NSTabButton").sorted { bar.convert($0.bounds, from: $0).minX < bar.convert($1.bounds, from: $1).minX }
2104
+ let close = NSSelectorFromString("closeTabButton:")
2105
+ guard i < buttons.count, bar.responds(to: close) else { return "no close of tab \(i + 1) among \(buttons.count)" }
2106
+ _ = bar.perform(close, with: buttons[i])
2107
+ return "its button"
2108
+ }
2109
+ /** command with the nth key of the digit row, as an AZERTY keyboard types it */
2110
+ func digit(_ n: Int) -> Bool {
2111
+ let azerty = ["&", "é", "\"", "'", "(", "§", "è", "!", "ç"]
2112
+ guard let code = Delegate.digitKeys.first(where: { $0.value == n })?.key, let e = key(azerty[n - 1], code, [.command]) else { return false }
2113
+ return takes(e)
2114
+ }
2115
+ func cmdT() -> Bool { self.key("t", 17, [.command]).map(self.takes) ?? false }
2116
+ /** one key as the app hands it on: the app's own keys first, then the window's views (the page), then the
2117
+ * menus, then a plain key down. Says who took it */
2118
+ func press(_ w: NSWindow, _ chars: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags, plain: String?) -> String {
2119
+ guard let e = key(chars, code, flags, plain: plain) else { return "no event" }
2120
+ if takes(e) { return "app" }
2121
+ if !flags.intersection([.command, .control]).isEmpty {
2122
+ if w.performKeyEquivalent(with: e) { return "page" }
2123
+ if NSApp.mainMenu?.performKeyEquivalent(with: e) == true { return "menu" }
2124
+ }
2125
+ w.sendEvent(e)
2126
+ return "page"
2127
+ }
2128
+ let local = "http://localhost:\(startURL.port ?? 80)"
2129
+ let hubAt = startURL.absoluteString
2130
+ let entry = { (id: String) in URL(string: "\(hubAt)#page:src:\(id)")! }
2131
+ 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") }
2132
+ /** the hub's tab is still a page of the hub, whatever entry it shows */
2133
+ func hubStays() -> Bool { pane(0)?.web.url.map { isHub($0) && $0.path == startURL.path } ?? false }
2134
+ /** the hub's tab goes to an entry in place, as a click on a row of its main panel does */
2135
+ func go(_ id: String, _ then: @escaping () -> Void) {
2136
+ pane(0)?.web.evaluateJavaScript("location.hash = 'page:src:\(id)'; 0") { _, _ in }
2137
+ until({ pane(0)?.web.url?.fragment == "page:src:\(id)" }, then)
2138
+ }
2139
+ var steps: [(@escaping () -> Void) -> Void] = []
2140
+ func run() {
2141
+ if steps.isEmpty { return }
2142
+ let s = steps.removeFirst()
2143
+ s { run() }
2144
+ }
2145
+
2146
+ // the launch: one tab, the hub, pinned and shown
2147
+ open(startURL)
2148
+ steps.append { next in
2149
+ until({ loaded(0) }) {
2150
+ 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")
2151
+ let items = { (m: NSMenu?, a: Selector) in (m?.items ?? []).filter { $0.action == a }.map(\.keyEquivalent).joined() }
2152
+ let file = NSApp.mainMenu?.items[1].submenu
2153
+ 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")
2154
+ next()
2155
+ }
2156
+ }
2157
+ // the hub goes to a terminal's entry in place, then command with t: that entry in a tab of its own, on its
2158
+ // shell already, and the hub's tab stays where it was
2159
+ steps.append { next in
2160
+ go("terminals:t1") {
2161
+ let at = pane(0)?.web.url?.fragment ?? "none"
2162
+ let took = cmdT()
2163
+ until({ all().count == 2 && all()[1].title == "meadow terminal" }) {
2164
+ 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")
2165
+ next()
2166
+ }
2167
+ }
2168
+ }
2169
+ // the same entry again: command with t shows its tab, and so does the entry's own row asking a new window
2170
+ // (the main panel's ⌘ click, middle click and hover button all call window.open); never a second tab
2171
+ steps.append { next in
2172
+ let first = digit(1)
2173
+ let back = shown()
2174
+ _ = cmdT()
2175
+ let again = "tabs=\(all().count) shown=\(shown())"
2176
+ click(0, "term")
2177
+ until({ shown() == 2 }) {
2178
+ 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")
2179
+ next()
2180
+ }
2181
+ }
2182
+ // a url the project declares, on another host: the hub is asked for the list, the link opens as tab 3
2183
+ steps.append { next in
2184
+ click(0, "prod")
2185
+ until({ all().count == 3 }) {
2186
+ say("declared-url", "tabs=\(addresses()) shown=\(shown()) out=\(out.count)", "tabs=hub hub#terminals:t1 https://app.meadow.invalid/admin shown=3 out=0")
2187
+ next()
2188
+ }
2189
+ }
2190
+ // the same link again: its tab is selected, no second one
2191
+ steps.append { next in
2192
+ let first = digit(1)
2193
+ let back = shown()
2194
+ click(0, "prod")
2195
+ until({ shown() == 3 }) {
2196
+ say("declared-again", "cmd-1=\(first) shown=\(back) then tabs=\(all().count) shown=\(shown())", "cmd-1=true shown=1 then tabs=3 shown=3")
2197
+ next()
2198
+ }
2199
+ }
2200
+ // any other site still leaves for the default browser
2201
+ steps.append { next in
2202
+ click(0, "other")
2203
+ until({ out.count == 1 }) {
2204
+ say("other-site", "tabs=\(all().count) out=\(out.joined(separator: ","))", "tabs=3 out=https://elsewhere.invalid/x")
2205
+ next()
2206
+ }
2207
+ }
2208
+ // another server of this machine, a plain link: a tab, and the hub stays on itself
2209
+ steps.append { next in
2210
+ click(0, "dev")
2211
+ until({ all().count == 4 && loaded(3) }) {
2212
+ 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")
2213
+ next()
2214
+ }
2215
+ }
2216
+ // in that tab a link of its own site stays, a link to another site leaves
2217
+ steps.append { next in
2218
+ click(3, "next")
2219
+ until({ pane(3)?.web.url?.path == "/app/next" && loaded(3) }) {
2220
+ click(3, "away")
2221
+ until({ out.count == 2 }) {
2222
+ 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")
2223
+ next()
2224
+ }
2225
+ }
2226
+ }
2227
+ // 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
2228
+ steps.append { next in
2229
+ var seen: [String] = []
2230
+ for n in [2, 9, 5, 1] { seen.append("\(digit(n) ? "" : "!")\(shown())") }
2231
+ for code in [UInt16(30), 30, 33] { seen.append("\(self.key(code == 30 ? "}" : "{", code, [.command, .shift]).map(self.takes) == true ? "" : "!")\(shown())") }
2232
+ say("tab-keys", seen.joined(separator: " "), "2 4 4 1 2 3 2")
2233
+ next()
2234
+ }
2235
+ // in a terminal's tab the app keeps its tab keys, and every key a terminal needs reaches the page (which
2236
+ // takes each key down it gets, as a terminal does, and lists them)
2237
+ steps.append { next in
2238
+ guard let w = all().count > 1 ? all()[1] : nil, let web = pane(1)?.web else { return next() }
2239
+ self.show(w)
2240
+ w.makeFirstResponder(web)
2241
+ let keys: [(String, String, UInt16, NSEvent.ModifierFlags, String?)] = [
2242
+ ("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),
2243
+ ("shift+return", "\r", 36, [.shift], nil), ("cmd+c", "c", 8, [.command], nil), ("cmd+v", "v", 9, [.command], nil), ("cmd+k", "k", 40, [.command], nil),
2244
+ ("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),
2245
+ ]
2246
+ var who: [String] = []
2247
+ func send(_ i: Int) {
2248
+ if i == keys.count {
2249
+ return web.evaluateJavaScript("document.body.dataset.keys || ''") { got, _ in
2250
+ 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")
2251
+ 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")
2252
+ next()
2253
+ }
2254
+ }
2255
+ // each key goes to the terminal's tab, whatever tab the one before it showed
2256
+ self.show(w)
2257
+ who.append("\(keys[i].0):\(press(w, keys[i].1, keys[i].2, keys[i].3, plain: keys[i].4))")
2258
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { send(i + 1) }
2259
+ }
2260
+ send(0)
2261
+ }
2262
+ // an entry's tab closes as any tab does, by command with w: the window, the hub and the app stay. Command
2263
+ // with t opens the hub's entry again, after the last tab
2264
+ steps.append { next in
2265
+ let before = all().count
2266
+ self.closeTab(of: all()[1])
2267
+ until({ all().count == before - 1 || self.windows.isEmpty }) {
2268
+ let left = "tabs=\(all().count) windows=\(self.windows.count) hub=\(all().first.map { self.isPinned($0) } ?? false)"
2269
+ _ = cmdT()
2270
+ until({ all().count == before }) {
2271
+ let at = self.tab(on: entry("terminals:t1")).flatMap { all().firstIndex(of: $0) }.map { $0 + 1 } ?? 0
2272
+ 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")
2273
+ next()
2274
+ }
2275
+ }
2276
+ }
2277
+ // the hub tab's own close button, with other tabs open: refused with the pane's dot
2278
+ steps.append { next in
2279
+ _ = digit(1)
2280
+ let road = tabClose(0)
2281
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
2282
+ 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")
2283
+ next()
2284
+ }
2285
+ }
2286
+ // a tab he closes is gone with its page: the process that drew it ends (its pid read from WebKit, here alone)
2287
+ steps.append { next in
2288
+ let pid = (pane(2)?.web.value(forKey: "_webProcessIdentifier") as? Int32) ?? 0
2289
+ autoreleasepool { self.closeTab(of: all()[2]) }
2290
+ // an app in use drains its pool at each event; a self test gets none, so it sends itself one
2291
+ until({
2292
+ 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) }
2293
+ return pid > 0 && kill(pid, 0) != 0
2294
+ }) {
2295
+ 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")
2296
+ next()
2297
+ }
2298
+ }
2299
+ // the context menu's item, then what it asks: a page of any site as a tab here; without it the same ask leaves
2300
+ steps.append { next in
2301
+ guard let web = pane(0)?.web as? Web, let e = self.key("x", 7, []) else { return next() }
2302
+ let menu = NSMenu()
2303
+ let item = menu.addItem(withTitle: "Open Link in New Window", action: nil, keyEquivalent: "")
2304
+ item.identifier = NSUserInterfaceItemIdentifier(Web.linkItem)
2305
+ let other = menu.addItem(withTitle: "Copy Link", action: nil, keyEquivalent: "")
2306
+ web.willOpenMenu(menu, with: e)
2307
+ web.tabNext = true
2308
+ web.evaluateJavaScript("window.open('https://unrelated.invalid/z'); 0") { _, _ in }
2309
+ until({ all().count == 4 }) {
2310
+ web.evaluateJavaScript("window.open('https://unrelated.invalid/z'); 0") { _, _ in }
2311
+ until({ out.count == 3 }) {
2312
+ 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")
2313
+ next()
2314
+ }
2315
+ }
2316
+ }
2317
+ // the badge's bridge: the hub's page has it and its count shows, a tab of another site has none
2318
+ steps.append { next in
2319
+ self.open(URL(string: "\(local)/app")!)
2320
+ until({ all().count == 5 && loaded(4) }) {
2321
+ let probe = "typeof (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.shipkit)"
2322
+ pane(4)?.web.evaluateJavaScript(probe) { tab, _ in
2323
+ pane(0)?.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage({waiting: 5, keys: [], repos: {meadow: 2, atelier: 3}}); \(probe)") { hub, _ in
2324
+ until({ NSApp.dockTile.badgeLabel != nil }) {
2325
+ say("bridge", "hub=\(hub as? String ?? "error") tab=\(tab as? String ?? "error") badge=\(NSApp.dockTile.badgeLabel ?? "none")", "hub=object tab=undefined badge=2")
2326
+ next()
2327
+ }
2328
+ }
2329
+ }
2330
+ }
2331
+ }
2332
+ // a page of another repo: that repo's app is asked of the hub, and this window stays as it is
2333
+ steps.append { next in
2334
+ click(0, "repo")
2335
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
2336
+ say("other-repo", "tabs=\(all().count) hub-stays=\(hubStays())", "tabs=5 hub-stays=true")
2337
+ next()
2338
+ }
2339
+ }
2340
+ // 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
2341
+ // by its page; the start address asked from outside (the Dock, `open -a`) is the hub's tab, never one more
2342
+ steps.append { next in
2343
+ go("urls:u1") {
2344
+ let took = cmdT()
2345
+ until({ all().count == 6 && loaded(5) }) {
2346
+ let opened = "taken=\(took) tabs=\(all().count) shown=\(shown()) tab=\(addresses().split(separator: " ").last ?? "") title=\(all().last?.title ?? "")"
2347
+ self.open(startURL)
2348
+ 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")
2349
+ next()
2350
+ }
2351
+ }
2352
+ }
2353
+ // 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
2354
+ // stays on its entry and wears none; control: the tab of this machine opened with no login wears none. Then it closes
2355
+ steps.append { next in
2356
+ let hop = "http://gate--meadow.localhost:\(startURL.port ?? 80)/"
2357
+ pane(0)?.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage({ tabName: 'gate', url: '\(hop)', urlId: 'gate', logins: ['admin'] }); window.open('\(hop)'); ''") { _, _ in }
2358
+ until({ all().count == 7 && loaded(6) }) {
2359
+ let words = { (i: Int) -> String in
2360
+ let b = self.chipButtons(of: i < all().count ? all()[i] : nil)
2361
+ return b.isEmpty ? "none" : b.map { "\($0.label):\($0.title)" }.joined(separator: ",")
2362
+ }
2363
+ 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")
2364
+ if all().count > 6 { self.closeTab(of: all()[6]) }
2365
+ until({ all().count == 6 }, next)
2366
+ }
2367
+ }
2368
+ steps.append { next in
2369
+ let u = { (s: String) in URL(string: s)! }
2370
+ let hubPage = u(hubAt), app = u("https://app.example.com/a")
2371
+ let rules: [(String, Bool)] = [
2372
+ ("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),
2373
+ ("a link to another site leaves", road(to: u("https://other.org/"), from: app, home: app, new: false, click: true, repo: "meadow") == .outside),
2374
+ ("a redirect to another site stays", road(to: u("https://other.org/"), from: app, home: app, new: false, click: false, repo: "meadow") == .here),
2375
+ ("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),
2376
+ ("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),
2377
+ ("the hub's link to another site asks the list", road(to: app, from: hubPage, home: hubPage, new: false, click: true, repo: "meadow") == .declared),
2378
+ ("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),
2379
+ ("the hub's own page stays", road(to: u("\(hubAt)#page:urls"), from: hubPage, home: hubPage, new: false, click: true, repo: "meadow") == .here),
2380
+ ("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),
2381
+ ("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")),
2382
+ ("a mail address leaves", road(to: u("mailto:owner@example.com"), from: hubPage, home: hubPage, new: false, click: true, repo: "meadow") == .outside),
2383
+ ("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/"))),
2384
+ ("two entries of the hub are two tabs", tabKey(entry("terminals:t1")) != tabKey(entry("terminals:t2")) && tabKey(entry("urls:u1")) != tabKey(hubPage)),
2385
+ ("an empty entry is the hub's start address", tabKey(u("\(hubAt)#")) == tabKey(hubPage)),
2386
+ ("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)),
2387
+ ("command 9 is the last tab", tabIndex(digit: 9, count: 3) == 2 && tabIndex(digit: 4, count: 3) == nil && tabIndex(digit: 1, count: 0) == nil),
2388
+ ("the digits are a project app's alone", tabDigits("project") == Array(1...9) && tabDigits("home").isEmpty && tabDigits("process").isEmpty),
2389
+ ]
2390
+ let wrong = rules.filter { !$0.1 }.map(\.0).joined(separator: "; ")
2391
+ say("rules", wrong.isEmpty ? "ok" : wrong, "ok")
2392
+ next()
2393
+ }
2394
+ // a tab's own close button closes that tab alone, and so does a close asked of it by AppKit (performClose,
2395
+ // which presses the red button in any other app): the window, the hub and every other tab stay
2396
+ steps.append { next in
2397
+ guard let last = all().last else { return next() }
2398
+ self.show(last)
2399
+ let road = tabClose(all().count - 1)
2400
+ until({ all().count == 5 }) {
2401
+ let button = "by=\(road) tabs=\(all().count) windows=\(self.windows.count)"
2402
+ all().last?.performClose(nil)
2403
+ until({ all().count == 4 }) {
2404
+ 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")
2405
+ next()
2406
+ }
2407
+ }
2408
+ }
2409
+ // the hub alone, every other tab closed: the window is still there. Command with w and the hub tab's own
2410
+ // close close nothing. Then one tab beside the hub, shown, and the window's red button pressed as the mouse
2411
+ // presses it: the window closes whole, every tab, and the app quits with it
2412
+ steps.append { _ in
2413
+ for w in all().filter({ !self.isPinned($0) }) { self.closeTab(of: w) }
2414
+ until({ all().count == 1 || self.windows.isEmpty }) {
2415
+ let left = self.windows.count
2416
+ if let hub = all().first { self.closeTab(of: hub) }
2417
+ let kept = self.windows.count
2418
+ let closes = all().first.map { self.windowShouldClose($0) } ?? true
2419
+ _ = cmdT()
2420
+ until({ all().count == 2 && shown() == 2 }) {
2421
+ let open = "tabs=\(all().count) shown=\(shown())"
2422
+ let red = selected().map(pressRed) ?? "no tab shown"
2423
+ until({ self.windows.isEmpty }) {
2424
+ 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")
2425
+ finish(ok ? 0 : 1)
2426
+ }
2427
+ }
2428
+ }
2429
+ }
2430
+ run()
2431
+ }
2432
+
2433
+ // `--self-test-address`, in a project app: its real window, never shown, on a stand in for the hub's page that
2434
+ // the test serves at the bundle's start url (tests/gui-app-live.test.ts). That page runs the hub's own
2435
+ // serve/hub-app/url-address.ts on three frames of two sites of other origins, neither of which says anything of
2436
+ // itself: `site`, watched from its start; `stale`, watched from an address its site answers 404 for; `other`, a
2437
+ // frame the page never asks. It keeps what the watch tells it (`__heard`) and every address message it got
2438
+ // (`__said`, `__keys`). Each frame is moved as its site's own links and router would. Then the page's notes:
2439
+ // the name of a tab it asks, what command with t opens, a tab that asks to leave. One line a fact,
2440
+ // ` expected …` under one that is wrong; exit 0 only when every line is as the owner would see it
2441
+ func selfTestAddress() {
2442
+ buildMenu()
2443
+ var out: [String] = []
2444
+ openOutside = { out.append($0.absoluteString) }
2445
+ var ok = true
2446
+ func say(_ name: String, _ got: String, _ want: String) {
2447
+ print("\(name)=\(got)")
2448
+ if got != want { ok = false; print(" expected \(want)") }
2449
+ }
2450
+ DispatchQueue.main.asyncAfter(deadline: .now() + 80) { print("timeout"); finish(1) }
2451
+ func all() -> [NSWindow] { tabs(of: nil) }
2452
+ func pane(_ i: Int) -> Pane? { i < all().count ? all()[i].contentView as? Pane : nil }
2453
+ func shown() -> Int { all().firstIndex { $0 === (self.windows.first?.tabGroup?.selectedWindow ?? all().first) }.map { $0 + 1 } ?? 0 }
2454
+ func loaded(_ i: Int) -> Bool { pane(i).map { !$0.web.isLoading && $0.web.title?.isEmpty == false } ?? false }
2455
+ func at(_ i: Int) -> String { pane(i)?.web.url?.absoluteString ?? "none" }
2456
+ /** runs `then` once `cond` holds, or after 8 s: the line that follows says what did not happen */
2457
+ func until(_ cond: @escaping () -> Bool, _ then: @escaping () -> Void) {
2458
+ let start = Date()
2459
+ func poll() {
2460
+ if cond() || Date().timeIntervalSince(start) > 8 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: then) }
2461
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
2462
+ }
2463
+ poll()
2464
+ }
2465
+ /** what a script says in a tab's page, as words */
2466
+ func js(_ i: Int, _ src: String, _ done: @escaping (String) -> Void) {
2467
+ guard let web = pane(i)?.web else { return done("no tab") }
2468
+ web.evaluateJavaScript(src) { v, err in done((v as? String) ?? err.map { "error: \($0.localizedDescription)" } ?? "") }
2469
+ }
2470
+ /** `then` with the hub page's words once `cond` holds of them, or after 8 s with what they were */
2471
+ func wait(_ src: String, _ cond: @escaping (String) -> Bool, _ then: @escaping (String) -> Void) {
2472
+ let start = Date()
2473
+ func poll() {
2474
+ js(0, src) { v in
2475
+ if cond(v) || Date().timeIntervalSince(start) > 8 { return then(v) }
2476
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
2477
+ }
2478
+ }
2479
+ poll()
2480
+ }
2481
+ func cmdT() -> Bool { self.key("t", 17, [.command]).map(self.takes) ?? false }
2482
+ let heard = "(window.__heard || []).join('|')"
2483
+ /** what the watch of one frame told the page, in order */
2484
+ func of(_ h: String, _ frame: String) -> String { h.split(separator: "|").filter { $0.hasPrefix("\(frame): ") }.joined(separator: "|") }
2485
+ /** 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 */
2486
+ func move(_ frame: String, _ how: String) -> String { "document.getElementById('\(frame)').contentWindow.postMessage({ go: \(how) }, '*'); ''" }
2487
+ func post(_ note: String) -> String { "webkit.messageHandlers.shipkit.postMessage(\(note)); ''" }
2488
+ var site = "", other = ""
2489
+ var steps: [(@escaping () -> Void) -> Void] = []
2490
+ func run() {
2491
+ if steps.isEmpty { finish(ok ? 0 : 1) }
2492
+ let s = steps.removeFirst()
2493
+ s { run() }
2494
+ }
2495
+
2496
+ open(startURL)
2497
+ // each watched frame is asked at its load and answers: the one at its start keeps nothing, the one sent to
2498
+ // an address its site answers 404 for is sent back, on the app's word of that answer
2499
+ steps.append { next in
2500
+ wait(heard, { of($0, "site") == "site: drop" && of($0, "stale").hasSuffix("drop") }) { h in
2501
+ js(0, "new URL(document.getElementById('site').src).origin + ' ' + new URL(document.getElementById('other').src).origin") { o in
2502
+ let two = o.split(separator: " ").map(String.init)
2503
+ site = two.first ?? ""
2504
+ other = two.last ?? ""
2505
+ say("start", "\(of(h, "site")) \(of(h, "stale")) tabs=\(all().count)", "site: drop stale: back|stale: drop tabs=1")
2506
+ next()
2507
+ }
2508
+ }
2509
+ }
2510
+ // he walks inside the site: a link, the router's push, a fragment. The frame says each
2511
+ steps.append { next in
2512
+ js(0, move("site", "{ href: '/plain/games/lumen' }")) { _ in
2513
+ wait(heard, { of($0, "site").hasSuffix("/plain/games/lumen") }) { _ in
2514
+ js(0, move("site", "{ push: '/plain/games/lumen/sheet-1?zoom=2' }")) { _ in
2515
+ wait(heard, { of($0, "site").hasSuffix("zoom=2") }) { _ in
2516
+ js(0, move("site", "{ hash: 'tile-3' }")) { _ in
2517
+ wait(heard, { of($0, "site").hasSuffix("#tile-3") }) { h in
2518
+ 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")
2519
+ next()
2520
+ }
2521
+ }
2522
+ }
2523
+ }
2524
+ }
2525
+ }
2526
+ }
2527
+ // an address the site answers an error for is dropped
2528
+ steps.append { next in
2529
+ js(0, move("site", "{ href: '/plain/gone' }")) { _ in
2530
+ wait(heard, { of($0, "site").hasSuffix("#tile-3|site: drop") }) { h in
2531
+ say("error", of(h, "site").split(separator: "|").last.map(String.init) ?? "nothing", "site: drop")
2532
+ next()
2533
+ }
2534
+ }
2535
+ }
2536
+ // the frame the page never asks moves too, and says nothing: every address the page got came from the
2537
+ // origin it asked, and held the address alone
2538
+ steps.append { next in
2539
+ js(0, move("other", "{ href: '/plain/games/lumen' }")) { _ in
2540
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
2541
+ js(0, move("other", "{ push: '/plain/games/lumen/sheet-1' }")) { _ in
2542
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
2543
+ js(0, "[...new Set(window.__said)].join(' ') + ' keys=' + [...new Set(window.__keys)].join(',')") { v in
2544
+ say("said", v.replacingOccurrences(of: site, with: "site").replacingOccurrences(of: other, with: "other"), "site keys=skAddress")
2545
+ next()
2546
+ }
2547
+ }
2548
+ }
2549
+ }
2550
+ }
2551
+ }
2552
+ // a url's row in a new tab: the page says the tab's name, then asks the window. The site alone, named
2553
+ steps.append { next in
2554
+ let u = "\(site)/plain/games/lumen"
2555
+ js(0, post("{ tabName: 'board games', url: '\(u)' }") + "; window.open('\(u)'); ''") { _ in
2556
+ until({ all().count == 2 && loaded(1) }) {
2557
+ 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")
2558
+ next()
2559
+ }
2560
+ }
2561
+ }
2562
+ // the same row asked again, from further inside the site: its tab is shown where he left it, no second one.
2563
+ // Control: a tab of the same site asked with no name is a tab of its own, named by its page
2564
+ steps.append { next in
2565
+ if let hub = all().first { self.show(hub) }
2566
+ let u = "\(site)/plain/games/lumen/sheet-1"
2567
+ js(0, post("{ tabName: 'board games', url: '\(u)' }") + "; window.open('\(u)'); ''") { _ in
2568
+ until({ shown() == 2 }) {
2569
+ let again = "tabs=\(all().count) shown=\(shown()) at=\(at(1).replacingOccurrences(of: site, with: "site"))"
2570
+ js(0, "window.open('\(site)/coop/'); ''") { _ in
2571
+ until({ all().count == 3 && loaded(2) }) {
2572
+ 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")
2573
+ next()
2574
+ }
2575
+ }
2576
+ }
2577
+ }
2578
+ }
2579
+ // command with t on an entry whose page named a tab: that address, down the road of a window the page
2580
+ // would ask, under its name; again shows that tab
2581
+ steps.append { next in
2582
+ if let hub = all().first { self.show(hub) }
2583
+ js(0, post("{ entryTab: { url: '\(other)/plain/', name: 'print shop' } }")) { _ in
2584
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
2585
+ let took = cmdT()
2586
+ until({ all().count == 4 && loaded(3) }) {
2587
+ let first = "taken=\(took) tabs=\(all().count) shown=\(shown()) at=\(at(3).replacingOccurrences(of: other, with: "other")) title=\(all().last?.title ?? "")"
2588
+ if let hub = all().first { self.show(hub) }
2589
+ _ = cmdT()
2590
+ until({ shown() == 4 }) {
2591
+ 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")
2592
+ next()
2593
+ }
2594
+ }
2595
+ }
2596
+ }
2597
+ }
2598
+ // an entry whose page names none: command with t opens the hub's entry, as before. A hub page in another
2599
+ // tab that names one changes nothing of what command with t opens: the hub's own tab alone says it
2600
+ steps.append { next in
2601
+ if let hub = all().first { self.show(hub) }
2602
+ js(0, post("{ entryTab: null }") + "; location.hash = 'page:src:urls:u1'; ''") { _ in
2603
+ until({ pane(0)?.web.url?.fragment == "page:src:urls:u1" }) {
2604
+ _ = cmdT()
2605
+ until({ all().count == 5 && loaded(4) }) {
2606
+ let entry = "tabs=\(all().count) shown=\(shown()) at=\(at(4).replacingOccurrences(of: startURL.absoluteString, with: "hub"))"
2607
+ js(4, post("{ entryTab: { url: '\(site)/plain/elsewhere', name: 'not the hub tab' } }")) { _ in
2608
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
2609
+ if let hub = all().first { self.show(hub) }
2610
+ _ = cmdT()
2611
+ until({ shown() == 5 }) {
2612
+ 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")
2613
+ next()
2614
+ }
2615
+ }
2616
+ }
2617
+ }
2618
+ }
2619
+ }
2620
+ }
2621
+ // a hub page that asks to leave closes its own tab; the hub's own tab is refused with the pane's dot
2622
+ steps.append { next in
2623
+ js(4, post("{ closeTab: true }")) { _ in
2624
+ until({ all().count == 4 }) {
2625
+ let closed = all().count
2626
+ js(0, post("{ closeTab: true }")) { _ in
2627
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
2628
+ 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")
2629
+ next()
2630
+ }
2631
+ }
2632
+ }
2633
+ }
2634
+ }
2635
+ run()
2636
+ }
2637
+
2638
+ // `--self-test-windows [png]`, in a project app: its real windows, never shown, with no server (each page a
2639
+ // string at the address it stands for). The hub alone shows its tab bar; a tab moved to a window of its own
2640
+ // leaves two windows, each with its bar, the state a drag between them needs; a second look asks no bar again;
2641
+ // the Window menu merges them back, the hub's tab first whatever place it had; command with n asks the hub page
2642
+ // 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
2643
+ // window pulled out closes that window alone; shift command n makes a window of its own on the hub's page, apart
2644
+ // from the project's, and its red button closes it alone. `png`: the window pulled out and the one it left, each frame drawn
2645
+ // whole (`<png>` and `<png>` with `-hub` before its extension). One line a fact, ` expected …` under one that
2646
+ // 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
2647
+ func selfTestWindows(to png: String?) {
2648
+ guard tabbed else { print("not a project app"); finish(1) }
2649
+ buildMenu()
2650
+ var ok = true
2651
+ func say(_ name: String, _ got: String, _ want: String) {
2652
+ print("\(name)=\(got)")
2653
+ if got != want { ok = false; print(" expected \(want)") }
2654
+ }
2655
+ DispatchQueue.main.asyncAfter(deadline: .now() + 40) { print("timeout"); finish(1) }
2656
+ var names: [ObjectIdentifier: String] = [:]
2657
+ /** a tab on a page that counts each ask of the new thread popup and answers `opens` */
2658
+ func tab(_ name: String, at url: URL, pinned: Bool = false, opens: Bool = true) -> NSWindow {
2659
+ let w = makeWindow(url, pinned: pinned)
2660
+ names[ObjectIdentifier(w)] = name
2661
+ (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)
2662
+ return w
2663
+ }
2664
+ /** each window as its tabs in their order, with whether its tab bar shows */
2665
+ func state() -> String {
2666
+ var seen: [NSWindow] = []
2667
+ var out: [String] = []
2668
+ for w in windows where !seen.contains(where: { $0 === w }) {
2669
+ let g = tabs(of: w)
2670
+ seen.append(contentsOf: g)
2671
+ out.append(g.map { names[ObjectIdentifier($0)] ?? "?" }.joined(separator: "+") + (w.tabGroup?.isTabBarVisible == true ? " [bar]" : " [no bar]"))
2672
+ }
2673
+ return out.joined(separator: " | ")
2674
+ }
2675
+ func shown(_ w: NSWindow) -> String { (w.tabGroup?.selectedWindow ?? w).flatMap { names[ObjectIdentifier($0)] } ?? "?" }
2676
+ func draw(_ w: NSWindow, to out: String) -> Bool {
2677
+ w.setContentSize(NSSize(width: 720, height: 200))
2678
+ w.displayIfNeeded()
2679
+ guard let frame = w.contentView?.superview, let rep = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { return false }
2680
+ frame.cacheDisplay(in: frame.bounds, to: rep)
2681
+ return (try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))) != nil
2682
+ }
2683
+ func asked(_ w: NSWindow, _ done: @escaping (String) -> Void) {
2684
+ guard let web = (w.contentView as? Pane)?.web else { return done("no page") }
2685
+ web.evaluateJavaScript("document.body.dataset.asked || '0'") { v, _ in done((v as? String) ?? "error") }
2686
+ }
2687
+ func later(_ s: Double, _ then: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + s, execute: then) }
2688
+
2689
+ let hub = tab("hub", at: startURL, pinned: true)
2690
+ say("one-tab", state(), "hub [bar]")
2691
+ let term = tab("terminal", at: URL(string: "?shell=terminal", relativeTo: startURL)!.absoluteURL, opens: false)
2692
+ let site = tab("site", at: URL(string: "http://site.invalid/app")!)
2693
+ say("three-tabs", state(), "hub+terminal+site [bar]")
2694
+ split(site)
2695
+ say("tab-moved-out", "\(state()) windows=\(windowCount)", "hub+terminal [bar] | site [bar] windows=2")
2696
+ split(term)
2697
+ say("each-alone", "\(state()) windows=\(windowCount)", "hub [bar] | terminal [bar] | site [bar] windows=3")
2698
+ let before = barsAsked
2699
+ for _ in 0..<5 {
2700
+ showTabBars()
2701
+ settleTabs()
2702
+ }
2703
+ later(1.2) {
2704
+ print("bars-asked=\(before)")
2705
+ 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]")
2706
+ let menu = NSApp.windowsMenu?.items ?? []
2707
+ let count = { (t: String) in menu.filter { $0.title == t }.count }
2708
+ let on = { (a: Selector) -> String in menu.first { $0.action == a }.map { self.validateMenuItem($0) ? "on" : "off" } ?? "none" }
2709
+ 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")
2710
+ let file = NSApp.mainMenu?.items[1].submenu?.items ?? []
2711
+ 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")
2712
+ if let png {
2713
+ let wrote = draw(term, to: png) && draw(hub, to: png.replacingOccurrences(of: ".png", with: "-hub.png"))
2714
+ say("drawn", "\(wrote)", "true")
2715
+ }
2716
+ // the hub's tab second in a window, as after a tab dropped before it; then every window back into one
2717
+ site.addTabbedWindow(hub, ordered: .above)
2718
+ say("hub-second", state(), "site+hub [bar] | terminal [bar]")
2719
+ self.merge(shown: term)
2720
+ 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")
2721
+ // command with n, no window being key: the hub's tab is asked, and comes forward
2722
+ let took = self.key("n", 45, [.command]).map(self.takes) ?? false
2723
+ later(1) {
2724
+ let first = shown(hub)
2725
+ // then as from the terminal's tab in front: its page opens none, the site's is never asked, the hub's opens it
2726
+ term.tabGroup?.selectedWindow = term
2727
+ self.askNewThread([term, site, hub].compactMap { $0.contentView as? Pane }, tries: 0)
2728
+ later(1) {
2729
+ asked(hub) { h in asked(term) { t in asked(site) { s in
2730
+ 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")
2731
+ // two tabs pulled out into one window, and its red button: that window alone closes
2732
+ self.split(term)
2733
+ self.split(site)
2734
+ term.addTabbedWindow(site, ordered: .above)
2735
+ let apart = state()
2736
+ self.closeEveryTab(term.standardWindowButton(.closeButton))
2737
+ later(0.6) {
2738
+ 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")
2739
+ // shift command n, no window being key: a window of its own, apart from the project's, on the hub
2740
+ let tookWindow = self.key("N", 45, [.command, .shift]).map(self.takes) ?? false
2741
+ guard let made = self.windows.last, made !== hub, let pane = made.contentView as? Pane else {
2742
+ say("new-window", "none", "a window")
2743
+ finish(1)
2744
+ }
2745
+ names[ObjectIdentifier(made)] = "hub-page"
2746
+ later(0.6) {
2747
+ let first = self.tabs(of: made).first.flatMap { names[ObjectIdentifier($0)] } ?? "?"
2748
+ let onHub = pane.opened.map(tabKey) == tabKey(startURL)
2749
+ 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")
2750
+ self.closeEveryTab(made.standardWindowButton(.closeButton))
2751
+ later(0.6) {
2752
+ say("red-button-of-the-new-window", "\(state()) windows=\(self.windows.count)", "hub [bar] windows=1")
2753
+ finish(ok ? 0 : 1)
2754
+ }
2755
+ }
2756
+ }
2757
+ } } }
2758
+ }
2759
+ }
2760
+ }
2761
+ }
2762
+
2763
+ // `--self-test-chrome <png> [tab title…]`: a window of tabs that is never shown (two, or one a title given) as a window of
2764
+ // this app opens, painted with the bundle's colour; its frame drawn whole (title bar, tab bar, page) into the png.
2765
+ // Prints the colour and the appearance; exit 0 only when a bundle with a colour has its window painted with it,
2766
+ // and one without keeps the system's
2767
+ func selfTestChrome(to out: String, titles: [String] = []) {
2768
+ let make = { (title: String) -> NSWindow in
2769
+ 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)
2770
+ let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
2771
+ web.loadHTMLString("<body style='margin:0;font:15px -apple-system;background:#f6f6f6;color:#333;padding:18px'>\(appName)</body>", baseURL: nil)
2772
+ w.contentView = Pane(web: web)
2773
+ w.title = title
2774
+ w.tabbingMode = .preferred
2775
+ paint(w, tint, text: tintText)
2776
+ return w
2777
+ }
2778
+ let all = (titles.isEmpty ? [appName, "urls"] : titles).map(make)
2779
+ let a = all[0]
2780
+ windows.append(contentsOf: all)
2781
+ for (i, w) in all.enumerated().dropFirst() { all[i - 1].addTabbedWindow(w, ordered: .above) }
2782
+ a.tabGroup?.selectedWindow = a
2783
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
2784
+ guard let frame = a.contentView?.superview, let rep = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { print("no frame"); finish(1) }
2785
+ frame.cacheDisplay(in: frame.bounds, to: rep)
2786
+ let wrote = (try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))) != nil
2787
+ let painted = a.backgroundColor == tint && a.titlebarAppearsTransparent
2788
+ 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)")
2789
+ finish(wrote && (tint == nil ? !a.titlebarAppearsTransparent : painted) ? 0 : 1)
2790
+ }
2791
+ }
2792
+
2793
+ // `--self-test-chips [png]`, in a project app: its real window, never shown, on a stand in for the hub that the
2794
+ // test serves at the bundle's start url (tests/gui-app-live.test.ts), its copy route answering made up values
2795
+ // (SHIPKIT_TEST_CHIPS: login 0's account and password, compared here and never printed). The hub's page names a
2796
+ // 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
2797
+ // 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
2798
+ // clock, unless another copy came since or the app quits first; a refusal says so on the chip and leaves the
2799
+ // board. `png`: that tab's frame drawn with no login (`-before` before its extension) and with its chips. One line
2800
+ // a fact, ` expected …` under one that is wrong; exit 0 only when every line is as the owner would see it
2801
+ func selfTestChips(to png: String?) {
2802
+ guard tabbed else { print("not a project app"); finish(1) }
2803
+ buildMenu()
2804
+ clearAfter = 0.8
2805
+ let want = (ProcessInfo.processInfo.environment["SHIPKIT_TEST_CHIPS"] ?? "").split(separator: "|").map(String.init)
2806
+ var ok = true
2807
+ func say(_ name: String, _ got: String, _ want: String) {
2808
+ print("\(name)=\(got)")
2809
+ if got != want { ok = false; print(" expected \(want)") }
2810
+ }
2811
+ DispatchQueue.main.asyncAfter(deadline: .now() + 45) { print("timeout"); finish(1) }
2812
+ func until(_ cond: @escaping () -> Bool, _ then: @escaping () -> Void) {
2813
+ let start = Date()
2814
+ func poll() {
2815
+ if cond() || Date().timeIntervalSince(start) > 8 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: then) }
2816
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
2817
+ }
2818
+ poll()
2819
+ }
2820
+ func later(_ s: Double, _ then: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + s, execute: then) }
2821
+ func all() -> [NSWindow] { tabs(of: nil) }
2822
+ func pane(_ i: Int) -> Pane? { i < all().count ? all()[i].contentView as? Pane : nil }
2823
+ func loaded(_ i: Int) -> Bool { pane(i).map { !$0.web.isLoading && $0.web.title?.isEmpty == false } ?? false }
2824
+ func shown() -> Int { all().firstIndex { $0 === (self.windows.first?.tabGroup?.selectedWindow ?? all().first) }.map { $0 + 1 } ?? 0 }
2825
+ /** a tab's chips as words: each login's label, then its fields */
2826
+ func chips(_ i: Int) -> String {
2827
+ let b = chipButtons(of: i < all().count ? all()[i] : nil)
2828
+ if b.isEmpty { return "none" }
2829
+ var seen: [String] = []
2830
+ 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: ",")) }
2831
+ return seen.joined(separator: " ")
2832
+ }
2833
+ func chip(_ login: Int, _ field: String) -> ChipButton? { chipButtons(of: all().count > 1 ? all()[1] : nil).first { $0.login == login && $0.field == field } }
2834
+ /** what the board holds, said as how it compares: never the value */
2835
+ func held() -> String {
2836
+ guard let s = self.board.string(forType: .string) else { return "empty" }
2837
+ if let i = want.firstIndex(of: s) { return i == 0 ? "the account" : "the password" }
2838
+ return s == "his own copy" ? s : "another value"
2839
+ }
2840
+ func draw(_ w: NSWindow, to out: String) -> Bool {
2841
+ w.setContentSize(NSSize(width: 1100, height: 120))
2842
+ w.displayIfNeeded()
2843
+ guard let frame = w.contentView?.superview, let rep = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { return false }
2844
+ frame.cacheDisplay(in: frame.bounds, to: rep)
2845
+ return (try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))) != nil
2846
+ }
2847
+ let hop = "http://admin--meadow.localhost:\(startURL.port ?? 80)/admin"
2848
+ func ask(_ note: String) { pane(0)?.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage(\(note)); window.open('\(hop)'); ''") { _, _ in } }
2849
+ let tab = "{ tabName: 'admin panel', url: '\(hop)'"
2850
+ var steps: [(@escaping () -> Void) -> Void] = []
2851
+ func run() {
2852
+ if steps.isEmpty {
2853
+ self.board.releaseGlobally()
2854
+ finish(ok ? 0 : 1)
2855
+ }
2856
+ let s = steps.removeFirst()
2857
+ s { run() }
2858
+ }
2859
+
2860
+ open(startURL)
2861
+ // the hub's page names the tab of a url with no login: a tab named, no chip; then it leaves
2862
+ steps.append { next in
2863
+ until({ loaded(0) }) {
2864
+ ask(tab + " }")
2865
+ until({ all().count == 2 && loaded(1) }) {
2866
+ let drew = png.map { draw(all()[1], to: $0.replacingOccurrences(of: ".png", with: "-before.png")) } ?? true
2867
+ say("no-login", "tabs=\(all().count) title=\(all()[1].title) chips=\(chips(1)) drawn=\(drew)", "tabs=2 title=admin panel chips=none drawn=true")
2868
+ self.closeTab(of: all()[1])
2869
+ until({ all().count == 1 }, next)
2870
+ }
2871
+ }
2872
+ }
2873
+ // 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
2874
+ steps.append { next in
2875
+ ask(tab + ", urlId: 'admin', logins: ['admin', 'viewer'] }")
2876
+ until({ all().count == 2 && loaded(1) }) {
2877
+ let at = pane(1)?.web.url?.absoluteString.replacingOccurrences(of: ":\(startURL.port ?? 80)", with: ":PORT") ?? "none"
2878
+ let drew = png.map { draw(all()[1], to: $0) } ?? true
2879
+ 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")
2880
+ next()
2881
+ }
2882
+ }
2883
+ // a press of admin's password: on the run's own board, concealed, the chip says so; gone at the clock
2884
+ steps.append { next in
2885
+ chip(0, "password")?.performClick(nil)
2886
+ until({ self.board.string(forType: .string) != nil }) {
2887
+ let types = (self.board.types ?? []).map(\.rawValue)
2888
+ 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")
2889
+ later(self.clearAfter + 0.4) {
2890
+ say("at-the-clock", "holds=\(held())", "holds=empty")
2891
+ next()
2892
+ }
2893
+ }
2894
+ }
2895
+ // a press of admin's account, then his own copy before the clock: the clock leaves his copy alone
2896
+ steps.append { next in
2897
+ chip(0, "account")?.performClick(nil)
2898
+ until({ self.board.string(forType: .string) != nil }) {
2899
+ let got = held()
2900
+ self.board.clearContents()
2901
+ self.board.setString("his own copy", forType: .string)
2902
+ later(self.clearAfter + 0.4) {
2903
+ say("his-copy", "copied=\(got) then at-the-clock holds=\(held())", "copied=the account then at-the-clock holds=his own copy")
2904
+ next()
2905
+ }
2906
+ }
2907
+ }
2908
+ // a field the hub refuses: the chip says it and its tip the hub's words; the board is left as it was
2909
+ steps.append { next in
2910
+ chip(1, "password")?.performClick(nil)
2911
+ until({ chip(1, "password")?.title == "not copied" }) {
2912
+ 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")
2913
+ next()
2914
+ }
332
2915
  }
333
- return config
2916
+ // a copy, then the app quits before the clock: the value leaves with it
2917
+ steps.append { next in
2918
+ chip(0, "password")?.performClick(nil)
2919
+ until({ held() == "the password" }) {
2920
+ let got = held()
2921
+ self.applicationWillTerminate(Notification(name: NSApplication.willTerminateNotification))
2922
+ say("quit", "copied=\(got) then holds=\(held())", "copied=the password then holds=empty")
2923
+ next()
2924
+ }
2925
+ }
2926
+ run()
334
2927
  }
335
2928
 
336
- /** the page of the home the app keeps loaded while no window is open: it alone keeps the badge and the
337
- * notifications live, and leaves once a window's page posts again */
338
- var keeper: WKWebView?
339
-
340
- func keep(home: URL) {
341
- let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 1400, height: 900), configuration: webConfig())
342
- web.navigationDelegate = self
343
- web.load(URLRequest(url: home))
344
- keeper = web
2929
+ /** a window's frame drawn whole into a png: its chrome as AppKit draws it, each web view of its pane as WebKit
2930
+ * snapshots it, put where it sits */
2931
+ func drawWhole(_ w: NSWindow, to out: String, done: @escaping (Bool) -> Void) {
2932
+ w.displayIfNeeded()
2933
+ guard let frame = w.contentView?.superview, let pane = w.contentView as? Pane, let rep = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { return done(false) }
2934
+ frame.cacheDisplay(in: frame.bounds, to: rep)
2935
+ let webs = [pane.web] + (pane.side.map { [$0.web] } ?? [])
2936
+ var shots: [(WKWebView, NSImage)] = []
2937
+ func next(_ i: Int) {
2938
+ if i == webs.count {
2939
+ NSGraphicsContext.saveGraphicsState()
2940
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
2941
+ for (web, img) in shots { img.draw(in: web.convert(web.bounds, to: frame)) }
2942
+ // the divider sits over both web views, as on the screen
2943
+ if pane.side != nil, let line = pane.divider.bitmapImageRepForCachingDisplay(in: pane.divider.bounds) {
2944
+ pane.divider.cacheDisplay(in: pane.divider.bounds, to: line)
2945
+ line.draw(in: pane.divider.convert(pane.divider.bounds, to: frame), from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
2946
+ }
2947
+ NSGraphicsContext.restoreGraphicsState()
2948
+ return done((try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: out))) != nil)
2949
+ }
2950
+ webs[i].takeSnapshot(with: nil) { img, _ in
2951
+ if let img { shots.append((webs[i], img)) }
2952
+ next(i + 1)
2953
+ }
2954
+ }
2955
+ next(0)
345
2956
  }
346
2957
 
347
- func open(_ url: URL) {
348
- opened = true
349
- let web = WKWebView(frame: .zero, configuration: webConfig())
350
- if #available(macOS 13.3, *) { web.isInspectable = true }
351
- web.navigationDelegate = self
352
- web.uiDelegate = self
353
- web.allowsBackForwardNavigationGestures = true
354
- web.allowsMagnification = true
355
- web.pageZoom = zoom
356
- let frame = NSRect(x: 0, y: 0, width: 1400, height: 900)
357
- let win = QuietWindow(contentRect: frame, styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
358
- win.contentView = Pane(web: web)
359
- win.title = appName
360
- win.delegate = self
361
- 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() }
364
- windows.append(win)
365
- web.load(URLRequest(url: url))
366
- win.makeKeyAndOrderFront(nil)
367
- win.makeFirstResponder(web)
368
- NSApp.activate(ignoringOtherApps: true)
2958
+ // `--self-test-side [png]`, in a project app: its real window, never shown, on a stand in for the hub that the test
2959
+ // serves at the bundle's start url (tests/gui-app-live.test.ts), with a site of another origin beside it. The hub's
2960
+ // page posts a url as a thread's link does (app-bridge.ts openLink): the side panel opens on it beside the page, on
2961
+ // the app's own store, with no bridge of its own; a link, back, forward and a window.open stay in it; an address
2962
+ // that is no web page is refused; the divider sizes it, clamped, and the width is the next panel's; its close button
2963
+ // gives the page its width back. `png`: the window drawn whole with the panel open. One line a fact, ` expected …`
2964
+ // under one that is wrong; exit 0 only when every line is as the owner would see it
2965
+ func selfTestSide(to png: String?) {
2966
+ guard tabbed else { print("not a project app"); finish(1) }
2967
+ buildMenu()
2968
+ var ok = true
2969
+ func say(_ name: String, _ got: String, _ want: String) {
2970
+ print("\(name)=\(got)")
2971
+ if got != want { ok = false; print(" expected \(want)") }
2972
+ }
2973
+ DispatchQueue.main.asyncAfter(deadline: .now() + 45) { print("timeout"); finish(1) }
2974
+ func until(_ cond: @escaping () -> Bool, _ then: @escaping () -> Void) {
2975
+ let start = Date()
2976
+ func poll() {
2977
+ if cond() || Date().timeIntervalSince(start) > 8 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: then) }
2978
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
2979
+ }
2980
+ poll()
2981
+ }
2982
+ func js(_ web: WKWebView?, _ src: String, _ done: @escaping (String) -> Void) {
2983
+ guard let web else { return done("no page") }
2984
+ web.evaluateJavaScript(src) { v, e in done(v.map { "\($0)" } ?? "error \(e?.localizedDescription ?? "")") }
2985
+ }
2986
+ let port = startURL.port ?? 80
2987
+ let site = "http://localhost:\(port)/site"
2988
+ open(startURL)
2989
+ guard let hub = hubTab, let pane = hub.contentView as? Pane else { print("no hub tab"); finish(1) }
2990
+ hub.setContentSize(NSSize(width: 1400, height: 820))
2991
+ let ask = { (url: String) in pane.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage({ sidePanel: \(jsString(url)) }); ''") { _, _ in } }
2992
+ func title() -> String { pane.side?.web.title ?? "none" }
2993
+ func widths() -> String {
2994
+ pane.layoutSubtreeIfNeeded()
2995
+ return "page=\(Int(pane.web.frame.width)) side=\(Int(pane.side?.frame.width ?? 0))"
2996
+ }
2997
+ func drag(to x: CGFloat, up: Bool) {
2998
+ let at = pane.convert(NSPoint(x: x, y: 200), to: nil)
2999
+ for type in up ? [NSEvent.EventType.leftMouseDown, .leftMouseDragged, .leftMouseUp] : [.leftMouseDown, .leftMouseDragged] {
3000
+ guard let e = NSEvent.mouseEvent(with: type, location: at, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: hub.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1) else { continue }
3001
+ switch type {
3002
+ case .leftMouseDown: pane.divider.mouseDown(with: e)
3003
+ case .leftMouseDragged: pane.divider.mouseDragged(with: e)
3004
+ default: pane.divider.mouseUp(with: e)
3005
+ }
3006
+ }
3007
+ }
3008
+ var steps: [(@escaping () -> Void) -> Void] = []
3009
+ func run() {
3010
+ if steps.isEmpty { finish(ok ? 0 : 1) }
3011
+ let s = steps.removeFirst()
3012
+ s { run() }
3013
+ }
3014
+ // the hub's page wears the mark, and asks a site of another origin: the panel opens on it, beside the page
3015
+ steps.append { next in
3016
+ until({ !pane.web.isLoading && pane.web.title == "meadow hub" }) {
3017
+ js(pane.web, "String(window.__skSidePanel === true)") { marked in
3018
+ say("hub-marked", marked, "true")
3019
+ ask(site)
3020
+ until({ title() == "site" }) {
3021
+ let s = pane.side
3022
+ say("opened", "title=\(title()) at=\(s?.web.url?.absoluteString ?? "none") address=\(s?.address.stringValue ?? "none") tabs=\(self.tabs(of: nil).count) \(widths())", "title=site at=\(site) address=\(site) tabs=1 page=840 side=560")
3023
+ next()
3024
+ }
3025
+ }
3026
+ }
3027
+ }
3028
+ // the panel shows any site, so it never gets the bridge (a site never names an identity); asked with none, it
3029
+ // signs in with the page's store, and its head says so
3030
+ steps.append { next in
3031
+ js(pane.side?.web, "typeof (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.shipkit) + ' ' + typeof window.__skSidePanel") { v in
3032
+ say("panel-bridge", v, "undefined undefined")
3033
+ say("store", "page's=\(pane.side?.web.configuration.websiteDataStore === pane.web.configuration.websiteDataStore) head=\(pane.side?.who.stringValue ?? "none")", "page's=true head=shared sign ins")
3034
+ next()
3035
+ }
3036
+ }
3037
+ // a page that names its repo's identity: the panel signs in with that identity's own store, never the page's;
3038
+ // the same identity asked again keeps its panel and its store; another identity gets a panel on a store of its
3039
+ // own, its head naming it; an id that is no identity's is read as none
3040
+ steps.append { next in
3041
+ let askAs = { (url: String, id: String, name: String) in pane.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage({ sidePanel: \(jsString(url)), identity: { id: \(jsString(id)), name: \(jsString(name)) } }); ''") { _, _ in } }
3042
+ askAs(site, "north", "North Studio")
3043
+ until({ pane.side?.identity?.id == "north" && title() == "site" }) {
3044
+ let a = pane.side
3045
+ let aStore = a?.web.configuration.websiteDataStore
3046
+ let aHead = a?.who.stringValue ?? "none"
3047
+ askAs(site + "/two", "north", "North Studio")
3048
+ until({ title() == "two" }) {
3049
+ let again = pane.side === a && pane.side?.web.configuration.websiteDataStore === aStore
3050
+ askAs(site, "south", "south")
3051
+ until({ pane.side?.identity?.id == "south" && title() == "site" }) {
3052
+ let b = pane.side?.web.configuration.websiteDataStore
3053
+ let north = aStore === identityStore("north") && aStore !== pane.web.configuration.websiteDataStore
3054
+ let south = b === identityStore("south") && b !== aStore && b !== pane.web.configuration.websiteDataStore
3055
+ say("identities", "north=\(north) head=\(aHead) again=\(again) south=\(south) head=\(pane.side?.who.stringValue ?? "none")", "north=true head=as North Studio again=true south=true head=as south")
3056
+ say("odd-id", "\(sideIdentity(["id": "Bad Id!", "name": "x"]).map { $0.id } ?? "none") \(sideIdentity(["id": "south"])?.name ?? "none")", "none south")
3057
+ print("store-id-north=\(identityStoreId("north").uuidString.lowercased())")
3058
+ print("store-id-south=\(identityStoreId("south").uuidString.lowercased())")
3059
+ next()
3060
+ }
3061
+ }
3062
+ }
3063
+ }
3064
+ // a link of the site, then back and forward, then a window.open: each in the panel, no tab, no browser
3065
+ steps.append { next in
3066
+ var out: [String] = []
3067
+ self.openOutside = { out.append($0.absoluteString) }
3068
+ js(pane.side?.web, "document.getElementById('two').click(); ''") { _ in
3069
+ until({ title() == "two" }) {
3070
+ let back = pane.side?.buttons["back"]?.isEnabled == true
3071
+ pane.side?.buttons["back"]?.performClick(nil)
3072
+ until({ title() == "site" }) {
3073
+ let forward = pane.side?.buttons["forward"]?.isEnabled == true
3074
+ pane.side?.buttons["forward"]?.performClick(nil)
3075
+ until({ title() == "two" }) {
3076
+ js(pane.side?.web, "window.open('/site/three'); ''") { _ in
3077
+ until({ title() == "three" }) {
3078
+ say("walked", "link=two back=\(back) forward=\(forward) open=\(title()) tabs=\(self.tabs(of: nil).count) outside=\(out.count)", "link=two back=true forward=true open=three tabs=1 outside=0")
3079
+ next()
3080
+ }
3081
+ }
3082
+ }
3083
+ }
3084
+ }
3085
+ }
3086
+ }
3087
+ // an address that is no web page is refused, and the panel stays where it is
3088
+ steps.append { next in
3089
+ ask("file:///etc/hosts")
3090
+ ask("javascript:alert(1)")
3091
+ ask("about:blank")
3092
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
3093
+ say("refused", "title=\(title()) at=\(pane.side?.web.url?.path ?? "none")", "title=three at=/site/three")
3094
+ next()
3095
+ }
3096
+ }
3097
+ // the divider: a drag sizes the panel, clamped so the page keeps its least, and its width is the next panel's
3098
+ steps.append { next in
3099
+ drag(to: 700, up: false)
3100
+ let dragged = widths()
3101
+ drag(to: 100, up: false)
3102
+ let clamped = widths()
3103
+ drag(to: 860, up: true)
3104
+ say("dragged", "\(dragged) then \(clamped) then \(widths()) kept=\(Int(SidePanel.width))", "page=700 side=700 then page=360 side=1040 then page=860 side=540 kept=540")
3105
+ next()
3106
+ }
3107
+ // the window drawn whole, the panel open on the site's first page
3108
+ steps.append { next in
3109
+ ask(site)
3110
+ until({ title() == "site" }) {
3111
+ guard let png else { return next() }
3112
+ self.drawWhole(hub, to: png) { wrote in
3113
+ say("drawn", "\(wrote)", "true")
3114
+ next()
3115
+ }
3116
+ }
3117
+ }
3118
+ // its close button: the panel leaves, the page takes the window's width; the next one opens at the width kept
3119
+ steps.append { next in
3120
+ pane.side?.buttons["close"]?.performClick(nil)
3121
+ let closed = "side=\(pane.side == nil ? "none" : "open") \(widths())"
3122
+ ask(site)
3123
+ until({ title() == "site" }) {
3124
+ say("closed", "\(closed) then reopened \(widths())", "side=none page=1400 side=0 then reopened page=860 side=540")
3125
+ next()
3126
+ }
3127
+ }
3128
+ run()
369
3129
  }
370
3130
 
371
- var onLoad: ((WKWebView) -> Void)?
372
-
373
- // `--self-test-tabs`: two offscreen windows as two tabs of one window, the first shown; command with page down, then
374
- // 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
- // 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
377
- func selfTestTabs() {
3131
+ // `--self-test-restart`, in a project app or the home's: its real windows, never shown, on a stand in for the hub
3132
+ // that the test serves at the bundle's start url (tests/gui-app-live.test.ts). Two windows of tabs (a project app:
3133
+ // the pinned hub, a named url tab with its login chips, a tab with its side panel open as an identity at a width of
3134
+ // its own; then a window of its own with two tabs), each at a frame of its own, a tab other than the first shown.
3135
+ // The same build on disk offers nothing; another build offers « new version: relaunch » on every window; its
3136
+ // click keeps the windows (in memory, never the defaults) and starts nothing. Every window closes, the names and
3137
+ // chips the hub gave are forgotten, then the kept windows come back. One line a fact, ` expected …` under one that
3138
+ // is wrong; exit 0 only when the windows that came back are the ones that left, and the kept ones are read once
3139
+ func selfTestRestart() {
378
3140
  buildMenu()
379
- let make = { () -> NSWindow in
380
- let w = QuietWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
381
- w.contentView = Pane(web: WKWebView(frame: .zero, configuration: WKWebViewConfiguration()))
382
- w.tabbingMode = .preferred
383
- return w
384
- }
385
- let a = make(), b = make()
386
- windows.append(contentsOf: [a, b])
387
- a.orderFrontRegardless()
388
- a.addTabbedWindow(b, ordered: .above)
389
- a.tabGroup?.selectedWindow = a
390
- let shown = { () -> Int in a.tabGroup?.selectedWindow === b ? 2 : a.tabGroup?.selectedWindow === a ? 1 : 0 }
391
- // the item of the menus that takes command with this key, and whether the menu took the real event
392
- let press = { (key: Int, code: UInt16) -> String in
393
- let chars = String(UnicodeScalar(key)!)
394
- let item = NSApp.windowsMenu?.items.first { $0.keyEquivalent == chars && $0.keyEquivalentModifierMask == [.command] }
395
- guard let item, let e = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [.command, .function], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: a.windowNumber, context: nil, characters: chars, charactersIgnoringModifiers: chars, isARepeat: false, keyCode: code) else { return "no item" }
396
- let took = NSApp.mainMenu?.performKeyEquivalent(with: e) ?? false
397
- self.stepTab(of: a.tabGroup?.selectedWindow, by: item.action == #selector(self.nextTab(_:)) ? 1 : item.action == #selector(self.previousTab(_:)) ? -1 : 0)
398
- return "\(item.title), menu took the key: \(took)"
3141
+ var ok = true
3142
+ func say(_ name: String, _ got: String, _ want: String) {
3143
+ print("\(name)=\(got)")
3144
+ if got != want { ok = false; print(" expected \(want)") }
399
3145
  }
400
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
401
- let start = shown()
402
- let down = press(NSPageDownFunctionKey, 121)
403
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
404
- let afterDown = shown()
405
- let up = press(NSPageUpFunctionKey, 116)
406
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
407
- let afterUp = shown()
408
- print("tabs=\(a.tabGroup?.windows.count ?? 0) start=\(start)")
409
- print("page-down=\(down) shown=\(afterDown)")
410
- 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)
3146
+ DispatchQueue.main.asyncAfter(deadline: .now() + 40) { print("timeout"); finish(1) }
3147
+ func settled(_ then: @escaping () -> Void) {
3148
+ let start = Date()
3149
+ func poll() {
3150
+ let loading = self.windows.contains { w in
3151
+ guard let p = w.contentView as? Pane else { return false }
3152
+ return p.web.isLoading || p.web.url == nil || p.side?.web.isLoading == true || (p.side != nil && p.side?.web.url == nil)
412
3153
  }
3154
+ if !loading || Date().timeIntervalSince(start) > 10 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: then) }
3155
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
3156
+ }
3157
+ poll()
3158
+ }
3159
+ let port = startURL.port ?? 80
3160
+ let other = "http://localhost:\(port)"
3161
+ let hub = "http://127.0.0.1:\(port)"
3162
+ let frameA = NSRect(x: 120, y: 140, width: 1300, height: 820)
3163
+ let frameB = NSRect(x: 260, y: 200, width: 1000, height: 700)
3164
+ if tabbed {
3165
+ open(startURL)
3166
+ guard let first = hubTab else { print("no hub tab"); finish(1) }
3167
+ first.setFrame(frameA, display: false)
3168
+ // the note a hub page posts before it asks a url's tab: its name and its login chips
3169
+ let admin = URL(string: "\(other)/admin")!
3170
+ tabNames[tabKey(admin)] = "admin panel"
3171
+ tabChips[tabKey(admin)] = ("admin", ["owner", "viewer"])
3172
+ openTab(admin)
3173
+ openTab(URL(string: "\(hub)/r/meadow/docs")!)
3174
+ guard let docs = tabs(of: first).last, let pane = docs.contentView as? Pane else { print("no docs tab"); finish(1) }
3175
+ pane.openSide(URL(string: "\(other)/site")!, identity: SideIdentity(id: "south", name: "south"))
3176
+ pane.sideWidth = 610
3177
+ first.tabGroup?.selectedWindow = tabs(of: first)[1]
3178
+ projectWindow(nil)
3179
+ guard let second = windows.last else { print("no second window"); finish(1) }
3180
+ second.setFrame(frameB, display: false)
3181
+ let more = makeWindow(URL(string: "\(hub)/r/meadow/more")!, alone: true)
3182
+ second.addTabbedWindow(more, ordered: .above)
3183
+ second.tabGroup?.selectedWindow = more
3184
+ } else {
3185
+ let a = makeWindow(URL(string: "\(hub)/one")!)
3186
+ a.setFrame(frameA, display: false)
3187
+ (a.contentView as? Pane)?.openSide(URL(string: "\(other)/site")!, identity: SideIdentity(id: "north", name: "North Studio"))
3188
+ (a.contentView as? Pane)?.sideWidth = 610
3189
+ makeWindow(URL(string: "\(hub)/two")!).setFrame(frameB, display: false)
3190
+ }
3191
+ func summary(_ k: KeptSession) -> String {
3192
+ k.windows.map { w in
3193
+ let tabs = w.tabs.map { t in [t.url.replacingOccurrences(of: ":\(port)", with: ":PORT"), t.pinned ? "pinned" : nil, t.name, t.chips.map { "chips=\($0.urlId):\($0.logins.joined(separator: ","))" }, t.side.map { "side=\($0.replacingOccurrences(of: ":\(port)", with: ":PORT"))" }, t.sideWidth.map { "width=\(Int($0))" }, t.sideIdentity.map { "as=\($0.id)" }].compactMap { $0 }.joined(separator: " ") }
3194
+ let r = NSRectFromString(w.frame).integral
3195
+ return "[\(Int(r.minX)),\(Int(r.minY)) \(Int(r.width))x\(Int(r.height)) shown=\(w.shown) \(tabs.joined(separator: " | "))]"
3196
+ }.joined(separator: " ")
3197
+ }
3198
+ settled {
3199
+ let before = summary(self.keptWindows())
3200
+ print("before=\(before)")
3201
+ let count = self.windows.count
3202
+ let offered = { self.windows.filter { $0.titlebarAccessoryViewControllers.contains { $0.identifier?.rawValue == "relaunch" } } }
3203
+ self.checkBuild(disk: "abc", was: "abc")
3204
+ say("same-build", "stale=\(self.stale) offered=\(offered().count)", "stale=false offered=0")
3205
+ self.checkBuild(disk: "def", was: "abc")
3206
+ let buttons = offered().compactMap { w in w.titlebarAccessoryViewControllers.first { $0.identifier?.rawValue == "relaunch" }?.view.subviews.first as? NSButton }
3207
+ say("new-build", "stale=\(self.stale) offered=\(offered().count) of \(count) words=\(Set(buttons.map { $0.title }).sorted().joined(separator: ","))", "stale=true offered=\(count) of \(count) words=new version: relaunch")
3208
+ buttons.first?.performClick(nil)
3209
+ say("clicked", "relaunches=\(self.relaunches) kept=\(self.keptInMemory != nil) defaults=\(UserDefaults.standard.data(forKey: Delegate.keptKey) != nil)", "relaunches=1 kept=true defaults=false")
3210
+ for w in self.windows { w.close() }
3211
+ self.tabNames = [:]
3212
+ self.tabChips = [:]
3213
+ identityStores = [:]
3214
+ say("closed", "windows=\(self.windows.count)", "windows=0")
3215
+ guard let kept = self.takeKept() else { print("nothing kept"); finish(1) }
3216
+ self.restore(kept)
3217
+ settled {
3218
+ let after = summary(self.keptWindows())
3219
+ say("restored", after, before)
3220
+ let side = self.windows.compactMap { ($0.contentView as? Pane)?.side }.first
3221
+ say("side", "head=\(side?.who.stringValue ?? "none") store=\(side.map { $0.web.configuration.websiteDataStore === identityStore($0.identity?.id ?? "") } ?? false)", tabbed ? "head=as south store=true" : "head=as North Studio store=true")
3222
+ say("read-once", "again=\(self.takeKept() == nil ? "none" : "kept")", "again=none")
3223
+ finish(ok ? 0 : 1)
413
3224
  }
414
3225
  }
415
3226
  }
416
3227
 
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) }
3228
+ // `--self-test-fill [png]`, in a project app: its real window, never shown, on a stand in for the hub that the test
3229
+ // serves at the bundle's start url (tests/gui-app-live.test.ts), with the home's real login routes (urls/fill.ts)
3230
+ // over made up logins (SHIPKIT_TEST_FILL: two accounts and their passwords; a password is compared, never printed) and sign in
3231
+ // pages of three origins. The side panel fills the one login of an origin on its own, into that frame alone (a
3232
+ // frame of another origin inside it stays empty), a form that shows late too and again at its key; a page of
3233
+ // another origin gets nothing, even asked; two logins wear a chooser and fill the one picked; the hub's page and
3234
+ // the page's own scripts reach no value; a passkey that fails offers the identity's Chrome, opened through the hub's
3235
+ // page. WebKit's own word on a platform authenticator is printed. `png`: the window drawn whole on a filled form.
3236
+ // One line a fact, ` expected …` under one that is wrong; exit 0 only when every line is as the owner would see it
3237
+ func selfTestFill(to png: String?) {
3238
+ guard tabbed else { print("not a project app"); finish(1) }
3239
+ buildMenu()
3240
+ var ok = true
3241
+ func say(_ name: String, _ got: String, _ want: String) {
3242
+ print("\(name)=\(got)")
3243
+ if got != want { ok = false; print(" expected \(want)") }
430
3244
  }
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)
3245
+ let made = (ProcessInfo.processInfo.environment["SHIPKIT_TEST_FILL"] ?? "").split(separator: "|").map(String.init)
3246
+ guard made.count == 4 else { print("SHIPKIT_TEST_FILL holds no four made up values"); finish(1) }
3247
+ /** a field's value said as how it compares to the made up ones: never the value */
3248
+ func word(_ v: String) -> String {
3249
+ if v.isEmpty { return "empty" }
3250
+ guard let i = made.firstIndex(of: v) else { return "another value" }
3251
+ return ["the account", "the password", "the second account", "the second password"][i]
3252
+ }
3253
+ // a stand in for what WebKit does to a page that asks a passkey in an app that is no signed browser, so no
3254
+ // passkey prompt of the system is ever asked here
3255
+ SidePanel.testScripts = [WKUserScript(source: "navigator.credentials.get = () => Promise.reject(new DOMException('stand in', 'NotAllowedError'))", injectionTime: .atDocumentStart, forMainFrameOnly: false)]
3256
+ DispatchQueue.main.asyncAfter(deadline: .now() + 50) { print("timeout"); finish(1) }
3257
+ func until(_ cond: @escaping () -> Bool, _ then: @escaping () -> Void) {
3258
+ let start = Date()
3259
+ func poll() {
3260
+ if cond() || Date().timeIntervalSince(start) > 8 { return DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: then) }
3261
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: poll)
3262
+ }
3263
+ poll()
3264
+ }
3265
+ func js(_ web: WKWebView?, _ src: String, in frame: WKFrameInfo? = nil, _ done: @escaping (String) -> Void) {
3266
+ guard let web else { return done("no page") }
3267
+ web.callAsyncJavaScript(src, arguments: [:], in: frame, in: .page) { r in
3268
+ switch r {
3269
+ case .success(let v): done("\(v)")
3270
+ case .failure(let e): done("error \(e.localizedDescription)")
3271
+ }
3272
+ }
3273
+ }
3274
+ /** the sign in fields of a frame, as words */
3275
+ func fields(_ web: WKWebView?, in frame: WKFrameInfo? = nil, _ done: @escaping (String) -> Void) {
3276
+ js(web, "const u = document.getElementById('user'); const p = document.getElementById('pass'); return JSON.stringify([u ? u.value : '', p ? p.value : ''])", in: frame) { v in
3277
+ let pair = (try? JSONSerialization.jsonObject(with: Data(v.utf8))) as? [String] ?? ["?", "?"]
3278
+ done("account=\(word(pair[0])) password=\(word(pair[1]))")
3279
+ }
3280
+ }
3281
+ let port = startURL.port ?? 80
3282
+ let login = "http://login.localhost:\(port)", other = "http://other.localhost:\(port)", two = "http://two.localhost:\(port)"
3283
+ open(startURL)
3284
+ guard let hub = hubTab, let pane = hub.contentView as? Pane else { print("no hub tab"); finish(1) }
3285
+ hub.setContentSize(NSSize(width: 1400, height: 820))
3286
+ let ask = { (url: String) in pane.web.evaluateJavaScript("webkit.messageHandlers.shipkit.postMessage({ sidePanel: \(jsString(url)) }); ''") { _, _ in } }
3287
+ func side() -> SidePanel? { pane.side }
3288
+ func title() -> String { side()?.web.title ?? "none" }
3289
+ var steps: [(@escaping () -> Void) -> Void] = []
3290
+ func run() {
3291
+ if steps.isEmpty { finish(ok ? 0 : 1) }
3292
+ let s = steps.removeFirst()
3293
+ s { run() }
3294
+ }
3295
+ // a sign in page of an origin with one login: filled on its own, account and password, and a frame of
3296
+ // another origin inside it stays empty; the bar wears the key, no chooser
3297
+ steps.append { next in
3298
+ until({ !pane.web.isLoading && pane.web.title == "meadow hub" }) {
3299
+ ask("\(login)/signin")
3300
+ until({ title() == "sign in" && side()?.said.hasPrefix("filled") == true }) {
3301
+ let s = side()
3302
+ say("bar", "key=\(s?.buttons["fill"]?.isHidden == false ? "shown" : "hidden") chooser=\(s?.chooser.isHidden == false ? "shown" : "hidden") logins=\(s?.logins.map(\.title).joined(separator: ",") ?? "none")", "key=shown chooser=hidden logins=owner (\(made[0]))")
3303
+ say("said", s?.said ?? "none", "filled owner: account, password")
3304
+ fields(s?.web) { main in
3305
+ say("filled", main, "account=the account password=the password")
3306
+ until({ s?.foreignFrame != nil }) {
3307
+ fields(s?.web, in: s?.foreignFrame) { inner in
3308
+ say("frame-of-another-origin", "seen=\(s?.foreignFrame != nil) \(inner)", "seen=true account=empty password=empty")
3309
+ next()
3310
+ }
3311
+ }
3312
+ }
3313
+ }
3314
+ }
3315
+ }
3316
+ // the page's own scripts see no handler of the panel, nor its world's fill
3317
+ steps.append { next in
3318
+ js(side()?.web, "return typeof (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.skFill) + ' ' + typeof (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.shipkit)") { v in
3319
+ say("page-world", v, "undefined undefined")
3320
+ next()
3321
+ }
3322
+ }
3323
+ // the hub's page asks the home for the value itself: refused, and nothing of it is on the hub's page
3324
+ steps.append { next in
3325
+ js(pane.web, "const r = await fetch('/api/home/logins/fill', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ origin: \(jsString(login)), repo: 'meadow', id: 'signin', login: 0 }) }); return r.status + ' ' + (await r.text())") { v in
3326
+ let status = String(v.prefix(3))
3327
+ js(pane.web, "return document.documentElement.outerHTML + JSON.stringify(Object.keys(window))") { html in
3328
+ say("hub-asks", "status=\(status) value=\(made.contains { v.contains($0) } ? "held" : "absent") hub-page=\(made.contains { html.contains($0) } ? "held" : "absent")", "status=403 value=absent hub-page=absent")
3329
+ next()
3330
+ }
3331
+ }
3332
+ }
3333
+ // the key fills again a form he emptied
3334
+ steps.append { next in
3335
+ js(side()?.web, "document.getElementById('user').value = ''; document.getElementById('pass').value = ''; return ''") { _ in
3336
+ side()?.buttons["fill"]?.performClick(nil)
3337
+ until({ side()?.said.hasPrefix("filled") == true }) {
3338
+ fields(side()?.web) { v in
3339
+ say("key", v, "account=the account password=the password")
3340
+ next()
3341
+ }
3342
+ }
3343
+ }
3344
+ }
3345
+ // a sign in form that shows a while after the page: filled once it shows
3346
+ steps.append { next in
3347
+ ask("\(login)/late")
3348
+ until({ title() == "late" && side()?.said.hasPrefix("filled") == true }) {
3349
+ fields(side()?.web) { v in
3350
+ say("late", v, "account=the account password=the password")
3351
+ next()
3352
+ }
3353
+ }
3354
+ }
3355
+ // the step after the password, on the same origin: the field of an authenticator code (marked one-time-code, or a
3356
+ // lone field named so) gets the code of the login filled, its digits said as a shape, never printed; a lone
3357
+ // field that is no code's stays empty
3358
+ func codeStep(_ path: String, _ name: String, want: String) {
3359
+ steps.append { next in
3360
+ ask("\(login)/\(path)")
3361
+ until({ title() == path && (side()?.said.hasPrefix("filled") == true || path == "search") }) {
3362
+ DispatchQueue.main.asyncAfter(deadline: .now() + (path == "search" ? 0.8 : 0)) {
3363
+ js(side()?.web, "return document.getElementById('otc').value") { v in
3364
+ let shape = v.range(of: "^[0-9]{6}$", options: .regularExpression) != nil ? "six digits" : v.isEmpty ? "empty" : "another value"
3365
+ say(name, "said=\(side()?.said ?? "none") field=\(shape)", want)
3366
+ next()
3367
+ }
3368
+ }
3369
+ }
3370
+ }
3371
+ }
3372
+ codeStep("code", "code", want: "said=filled owner: code field=six digits")
3373
+ codeStep("lone", "lone-code", want: "said=filled owner: code field=six digits")
3374
+ codeStep("search", "not-a-code", want: "said= field=empty")
3375
+ // a form he cannot see (opacity 0): nothing filled on its own, said; his key fills it
3376
+ steps.append { next in
3377
+ ask("\(login)/hidden")
3378
+ until({ title() == "hidden" && side()?.said.hasPrefix("no sign in field in sight") == true }) {
3379
+ fields(side()?.web) { before in
3380
+ let line = side()?.said ?? "none"
3381
+ side()?.buttons["fill"]?.performClick(nil)
3382
+ until({ side()?.said.hasPrefix("filled") == true }) {
3383
+ fields(side()?.web) { after in
3384
+ say("unseen", "\(before) said=\(line) then key \(after)", "account=empty password=empty said=no sign in field in sight: press the key to fill it then key account=the account password=the password")
3385
+ next()
3386
+ }
3387
+ }
3388
+ }
3389
+ }
3390
+ }
3391
+ // a page of another origin: no login, nothing filled; the first origin's login asked into it is refused
3392
+ steps.append { next in
3393
+ let owner = side()?.logins.first
3394
+ ask("\(other)/signin")
3395
+ until({ title() == "sign in" && side()?.loginsOf == other && side()?.formFrame != nil }) {
3396
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
3397
+ let s = side()
3398
+ if let owner { s?.fill(owner) }
3399
+ fields(s?.web) { v in
3400
+ say("other-origin", "logins=\(s?.logins.count ?? -1) key=\(s?.buttons["fill"]?.isHidden == false ? "shown" : "hidden") \(v) asked=\(s?.said ?? "none")", "logins=0 key=hidden account=empty password=empty asked=not filled: owner is a login of another origin than \(other)")
3401
+ next()
3402
+ }
3403
+ }
3404
+ }
3405
+ }
3406
+ // two logins: a chooser, nothing filled on its own; the one picked is filled
3407
+ steps.append { next in
3408
+ ask("\(two)/signin")
3409
+ until({ title() == "sign in" && side()?.logins.count == 2 && side()?.formFrame != nil }) {
3410
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
3411
+ let s = side()
3412
+ fields(s?.web) { before in
3413
+ let chooser = "chooser=\(s?.chooser.isHidden == false ? "shown" : "hidden") items=\(s?.chooser.itemTitles.joined(separator: ",") ?? "none")"
3414
+ s?.chooser.selectItem(at: 1)
3415
+ s?.chooser.sendAction(s?.chooser.action, to: s?.chooser.target)
3416
+ until({ s?.said.hasPrefix("filled") == true }) {
3417
+ fields(s?.web) { after in
3418
+ say("two", "\(chooser) before \(before) then picked \(after) said=\(s?.said ?? "none")", "chooser=shown items=first (\(made[0])),second (\(made[2])) before account=empty password=empty then picked account=the second account password=the second password said=filled second: account, password")
3419
+ next()
3420
+ }
3421
+ }
3422
+ }
3423
+ }
3424
+ }
3425
+ }
3426
+ // the window drawn whole on the filled form
3427
+ steps.append { next in
3428
+ ask("\(login)/signin")
3429
+ until({ title() == "sign in" && side()?.loginsOf == login && side()?.said.hasPrefix("filled") == true }) {
3430
+ guard let png else { return next() }
3431
+ self.drawWhole(hub, to: png) { wrote in
3432
+ say("drawn", "\(wrote)", "true")
3433
+ next()
3434
+ }
3435
+ }
3436
+ }
3437
+ // a passkey the page asks fails: one line, and the identity's Chrome at the page he is on, through the hub's
3438
+ // page; WebKit's own word on a platform authenticator for this app
3439
+ steps.append { next in
3440
+ ask("\(login)/passkey")
3441
+ until({ title() == "passkey" && side()?.strip.act.isHidden == false }) {
3442
+ let s = side()
3443
+ say("passkey", "line=\(s?.strip.label.stringValue ?? "none") act=\(s?.strip.act.isHidden == false ? s?.strip.act.title ?? "" : "none")", "line=This page asked a passkey (NotAllowedError): macOS gives passkeys to a signed browser, never to this panel act=open in studio's Chrome")
3444
+ s?.strip.act.performClick(nil)
3445
+ until({ s?.said == "opened in Chrome" }) {
3446
+ js(pane.web, "return String(window.__chrome)") { asked in
3447
+ say("chrome", "hub-asked=\(asked) said=\(s?.said ?? "none")", "hub-asked=meadow signin /passkey said=opened in Chrome")
3448
+ js(s?.web, "return [typeof PublicKeyCredential, await (window.PublicKeyCredential ? PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable().then(String, (e) => 'error ' + e.name) : 'none')].join(' ')") { v in
3449
+ print("platform-authenticator=\(v)")
3450
+ next()
3451
+ }
3452
+ }
441
3453
  }
442
3454
  }
443
3455
  }
444
- web.loadHTMLString("<p>keys</p><script>addEventListener('keydown', (e) => { if (e.key === 'k') e.preventDefault() })</script>", baseURL: nil)
3456
+ run()
445
3457
  }
446
3458
 
447
- // `--self-test-find`: an offscreen window on a page holding a word twice,
3459
+ // `--self-test-find`: a window that is never shown, on a page holding a word twice,
448
3460
  // the find bar opened, a word on the page searched, then one that is not;
449
3461
  // what happened printed, exit 0 only when the bar shows and finds
450
3462
  func selfTestFind() {
451
3463
  let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
452
3464
  web.navigationDelegate = self
453
3465
  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)
3466
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
455
3467
  win.contentView = pane
456
- win.orderFrontRegardless()
457
3468
  windows.append(win)
458
3469
  onLoad = { _ in
459
3470
  pane.showFind()
@@ -465,20 +3476,78 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
465
3476
  print("found=\(found)")
466
3477
  print("absent-found=\(absent)")
467
3478
  print("status=\(pane.status.stringValue)")
468
- exit(pane.isFindBarVisible && found && !absent ? 0 : 1)
3479
+ finish(pane.isFindBarVisible && found && !absent ? 0 : 1)
469
3480
  }
470
3481
  }
471
3482
  }
472
3483
  web.loadHTMLString("<p>one needle, two needle</p>", baseURL: nil)
473
3484
  }
474
3485
 
3486
+ // `--self-test-paste`: command V with a picture on a board of the run's own (never his clipboard), into a page in a
3487
+ // window that is never shown: a png, a screen shot's tiff and a file of a picture each reach the page's paste as a
3488
+ // file, the png and the file with their bytes; a board of words with a picture of them and a file that is no picture
3489
+ // are no picture (WebKit's own paste, which reads his clipboard, is never run here). One line a case
3490
+ func selfTestPaste() {
3491
+ let web = Web(frame: NSRect(x: 0, y: 0, width: 400, height: 300), configuration: webConfig(bridge: false))
3492
+ web.navigationDelegate = self
3493
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false)
3494
+ win.contentView = web
3495
+ windows.append(win)
3496
+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 3, pixelsHigh: 2, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
3497
+ let png = rep.representation(using: .png, properties: [:])!
3498
+ let file = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("shipkit-self-test-paste-\(ProcessInfo.processInfo.processIdentifier).png")
3499
+ let other = file.deletingPathExtension().appendingPathExtension("pdf")
3500
+ try? png.write(to: file)
3501
+ try? Data("%PDF-1.4".utf8).write(to: other)
3502
+ let b = board
3503
+ var ok = true
3504
+ func say(_ name: String, _ got: String, _ want: String) {
3505
+ print("\(name)=\(got == want ? "ok" : "got \(got), want \(want)")")
3506
+ if got != want { ok = false }
3507
+ }
3508
+ /** the board filled by `fill`, command V, then the last paste the page heard: its file's type, name and bytes */
3509
+ func pasted(_ fill: () -> Void, _ done: @escaping (String) -> Void) {
3510
+ b.clearContents()
3511
+ fill()
3512
+ web.paste(nil)
3513
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { web.evaluateJavaScript("window.got.at(-1) ?? 'nothing'") { v, _ in done(v as? String ?? "nothing") } }
3514
+ }
3515
+ let page = "<textarea id=t></textarea><script>window.got = []; document.addEventListener('paste', (e) => { e.preventDefault(); const f = e.clipboardData?.files?.[0]; if (!f) return window.got.push('no file'); f.arrayBuffer().then((a) => { let s = ''; for (const x of new Uint8Array(a)) s += String.fromCharCode(x); window.got.push(f.type + ' ' + f.name + ' ' + btoa(s)) }) }, true)</script>"
3516
+ onLoad = { _ in
3517
+ web.evaluateJavaScript("document.getElementById('t').focus()") { _, _ in
3518
+ pasted({ b.setData(png, forType: .png) }) { got in
3519
+ say("png", got, "image/png image.png \(png.base64EncodedString())")
3520
+ pasted({ b.setData(rep.tiffRepresentation!, forType: .tiff) }) { got in
3521
+ say("tiff-as-png", got.hasPrefix("image/png image.png iVBORw0KGgo") ? "a png" : got, "a png")
3522
+ pasted({ b.writeObjects([file as NSURL]) }) { got in
3523
+ say("file", got, "image/png \(file.lastPathComponent) \(png.base64EncodedString())")
3524
+ b.clearContents()
3525
+ b.setString("a\tb", forType: .string)
3526
+ b.setData(png, forType: .png)
3527
+ say("words-with-a-picture", pictureOn(b) == nil ? "words" : "a picture", "words")
3528
+ b.clearContents()
3529
+ b.writeObjects([other as NSURL])
3530
+ b.setData(rep.tiffRepresentation!, forType: .tiff)
3531
+ say("file-no-picture", pictureOn(b) == nil ? "none" : "a picture", "none")
3532
+ b.releaseGlobally()
3533
+ try? FileManager.default.removeItem(at: file)
3534
+ try? FileManager.default.removeItem(at: other)
3535
+ finish(ok ? 0 : 1)
3536
+ }
3537
+ }
3538
+ }
3539
+ }
3540
+ }
3541
+ web.loadHTMLString(page, baseURL: URL(string: "http://127.0.0.1:9/"))
3542
+ }
3543
+
475
3544
  // `--self-test-mic`: a window's own web view on a page of the machine, then on a page of another host, each
476
3545
  // printing whether the page can reach the microphone api (`getUserMedia`); no capture is asked, so no prompt
477
3546
  func selfTestMic() {
478
3547
  let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 400, height: 300), configuration: webConfig())
479
3548
  web.navigationDelegate = self
480
3549
  web.uiDelegate = self
481
- windows.append(NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false))
3550
+ windows.append(QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false))
482
3551
  windows.last?.contentView = web
483
3552
  let probe = "typeof (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)"
484
3553
  onLoad = { _ in
@@ -487,7 +3556,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
487
3556
  self.onLoad = { _ in
488
3557
  web.evaluateJavaScript(probe) { other, _ in
489
3558
  print("other=\(other as? String ?? "error")")
490
- exit((local as? String) == "function" ? 0 : 1)
3559
+ finish((local as? String) == "function" ? 0 : 1)
491
3560
  }
492
3561
  }
493
3562
  web.loadHTMLString("<p>other</p>", baseURL: URL(string: "http://example.invalid/"))
@@ -498,41 +3567,37 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
498
3567
  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
3568
  }
500
3569
 
501
- /** hears every js panel once it shows: the self test answers it */
502
- var onPanel: ((NSAlert) -> Void)?
3570
+ /** a self test's answer to an alert, which it never shows: the button it gives is the one `present` reports */
3571
+ var onPanel: ((NSAlert, @escaping (NSApplication.ModalResponse) -> Void) -> Void)?
503
3572
 
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
3573
+ // `--self-test-panels`: a page in a window that is never shown calls prompt, confirm and alert. No panel reaches
3574
+ // the screen: each one is built as the owner would get it and handed to the test, which answers OK after typing
3575
+ // over the prompt's text, then again answers Cancel. What the page got printed, exit 0 only when every answer
3576
+ // reached it. Return is checked as OK being the panel's default button, esc as the key of Cancel
510
3577
  func selfTestPanels() {
511
3578
  let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
512
3579
  web.navigationDelegate = self
513
3580
  web.uiDelegate = self
514
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
3581
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
515
3582
  win.contentView = Pane(web: web)
516
- win.orderFrontRegardless()
517
3583
  windows.append(win)
518
3584
  var accept = true
519
3585
  var panels = 0
520
3586
  var returnIsOK = true
521
3587
  var escHeard = true
522
- onPanel = { alert in
3588
+ onPanel = { alert, answer in
523
3589
  panels += 1
524
3590
  DispatchQueue.main.async {
525
3591
  if alert.window.defaultButtonCell !== alert.buttons[0].cell { returnIsOK = false }
526
3592
  if accept {
527
3593
  // typing replaces the default text only when it is selected in an active editor
528
3594
  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)
3595
+ return answer(.alertFirstButtonReturn)
530
3596
  }
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)
3597
+ if alert.buttons.count == 1 { return answer(.alertFirstButtonReturn) }
3598
+ // esc is the key of Cancel, the second button: its answer is the one given
3599
+ if alert.buttons[1].keyEquivalent != "\u{1b}" { escHeard = false }
3600
+ answer(.alertSecondButtonReturn)
536
3601
  }
537
3602
  }
538
3603
  let js = "JSON.stringify([prompt('name', 'x'), confirm('ok?'), (alert('hi'), 'alerted')])"
@@ -546,7 +3611,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
546
3611
  print("esc-heard=\(escHeard)")
547
3612
  print("ok=\(ok)")
548
3613
  print("cancel=\(cancel)")
549
- exit(panels == 6 && returnIsOK && escHeard && ok == "[\"typed\",true,\"alerted\"]" && cancel == "[null,false,\"alerted\"]" ? 0 : 1)
3614
+ finish(panels == 6 && returnIsOK && escHeard && ok == "[\"typed\",true,\"alerted\"]" && cancel == "[null,false,\"alerted\"]" ? 0 : 1)
550
3615
  }
551
3616
  }
552
3617
  }
@@ -556,6 +3621,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
556
3621
  func windowWillClose(_ note: Notification) {
557
3622
  let pane = (note.object as? NSWindow)?.contentView as? Pane
558
3623
  windows.removeAll { $0 === note.object as? NSWindow }
3624
+ settleTabs()
559
3625
  guard let pane else { return }
560
3626
  // the last window leaves the home loaded with no window, on the home that window was on; its count holds
561
3627
  // until that page posts its own
@@ -566,41 +3632,352 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
566
3632
  dropCount(pane.web)
567
3633
  }
568
3634
 
569
- // the page title names the window, so cmd-tab and the window menu tell pages apart
3635
+ // a page with no title leaves the app's name on its window (Pane watches the title of one that has)
570
3636
  func webView(_ web: WKWebView, didFinish nav: WKNavigation!) {
3637
+ arrive(web)
571
3638
  onLoad?(web)
572
- web.window?.title = (web.title?.isEmpty == false) ? web.title! : appName
3639
+ if web.title?.isEmpty != false { web.window?.title = (web.superview as? Pane)?.name ?? appName }
3640
+ }
3641
+
3642
+ /** the project's own urls as its hub lists them (`sk urls`: its declared urls, its global processes among them),
3643
+ * any host: a link of the hub to one opens as a tab, where any other site leaves for the default browser */
3644
+ var declared: [URL] = []
3645
+ /** asks the hub for the list; the self test answers in its place */
3646
+ lazy var fetchDeclared: (@escaping ([URL]?) -> Void) -> Void = { done in
3647
+ guard let repo = projectRepo?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), let api = URL(string: "/r/\(repo)/api/urls.json", relativeTo: startURL) else { return done(nil) }
3648
+ var req = URLRequest(url: api)
3649
+ req.timeoutInterval = 3
3650
+ URLSession.shared.dataTask(with: req) { data, _, err in
3651
+ let rows = data.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }?["urls"] as? [[String: Any]]
3652
+ 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))") }
3653
+ DispatchQueue.main.async { done(rows?.compactMap { ($0["url"] as? String).flatMap { URL(string: $0) } }) }
3654
+ }.resume()
3655
+ }
3656
+
3657
+ func isDeclared(_ url: URL) -> Bool { declared.contains { originOf($0) == originOf(url) } }
3658
+
3659
+ /** a url of another site asked from the hub: a tab when the project declares it, read again from the hub when
3660
+ * the list kept does not hold it (a url declared since), else the road out */
3661
+ func openDeclared(_ url: URL) {
3662
+ if isDeclared(url) { return open(url) }
3663
+ fetchDeclared { list in
3664
+ if let list { self.declared = list }
3665
+ if self.isDeclared(url) { self.open(url) } else { self.openOutside(url) }
3666
+ }
3667
+ }
3668
+
3669
+ /** another repo's own app, through the home (`/api/projects/open-app`): built when missing, a running one brought
3670
+ * forward; a refusal says so in a panel */
3671
+ func openProjectApp(_ repo: String) {
3672
+ guard let api = URL(string: "/api/projects/open-app", relativeTo: startURL) else { return }
3673
+ var req = URLRequest(url: api)
3674
+ req.httpMethod = "POST"
3675
+ req.setValue("application/json", forHTTPHeaderField: "content-type")
3676
+ req.httpBody = try? JSONSerialization.data(withJSONObject: ["name": repo])
3677
+ URLSession.shared.dataTask(with: req) { data, res, err in
3678
+ let code = (res as? HTTPURLResponse)?.statusCode ?? 0
3679
+ if code == 200 { return }
3680
+ let why = err?.localizedDescription ?? data.flatMap { String(data: $0, encoding: .utf8) } ?? "status \(code)"
3681
+ DispatchQueue.main.async {
3682
+ let alert = NSAlert()
3683
+ alert.messageText = "The app of \(repo) did not open"
3684
+ alert.informativeText = why
3685
+ self.present(alert)
3686
+ }
3687
+ }.resume()
3688
+ }
3689
+
3690
+ // a rebuilt bundle reaches a running copy: with no window it relaunches by itself; with windows, each one shows a
3691
+ // « new version: relaunch » button in its title bar, and only his click quits it
3692
+ var stale = false
3693
+ func watchBuild() {
3694
+ Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { _ in self.checkBuild() }
3695
+ }
3696
+
3697
+ /** the build on disk against the one this copy started with: once they differ, the copy is stale for good */
3698
+ func checkBuild(disk: String? = stampOnDisk(), was: String? = launchedStamp) {
3699
+ guard !stale, let now = disk, let was, now != was else { return }
3700
+ stale = true
3701
+ if windows.isEmpty { return relaunch(nil) }
3702
+ for w in windows { offerRelaunch(w) }
3703
+ }
3704
+
3705
+ // MARK: the windows a restart brings back
3706
+
3707
+ /** where the windows wait for the next launch: the app's defaults; a self test's memory, never the defaults */
3708
+ static let keptKey = "ShipkitKeptWindows"
3709
+ var keptInMemory: Data?
3710
+ /** the relaunches a self test asked: it keeps the windows and starts nothing */
3711
+ var relaunches = 0
3712
+
3713
+ /** what a tab is to a restart: its address as it is now (a terminal's too), its pin, the name and the login chips
3714
+ * a hub page gave it (words, never a value), its side panel's address, width and identity */
3715
+ func keptTab(_ pane: Pane) -> KeptTab {
3716
+ let url = pane.web.url ?? pane.opened ?? startURL
3717
+ let chips = tabChips[tabKey(pane.opened ?? url)]
3718
+ let side = pane.side.flatMap { $0.web.url ?? $0.asked }
3719
+ return KeptTab(url: url.absoluteString, pinned: pane.pinned, name: pane.name, chips: chips.map { KeptChips(urlId: $0.urlId, logins: $0.logins) }, side: side?.absoluteString, sideWidth: side == nil ? nil : Double(pane.sideWidth), sideIdentity: side == nil ? nil : pane.side?.identity)
3720
+ }
3721
+
3722
+ /** every window of the app, each its frame, its tabs in their order and the one shown; the one in front last */
3723
+ func keptWindows() -> KeptSession {
3724
+ var groups: [[NSWindow]] = []
3725
+ for w in windows where w.contentView is Pane && !groups.contains(where: { $0.contains { $0 === w } }) {
3726
+ groups.append(tabs(of: w).filter { t in t.contentView is Pane && windows.contains { $0 === t } })
3727
+ }
3728
+ if let front = frontWindow ?? NSApp.mainWindow, let i = groups.firstIndex(where: { $0.contains { $0 === front } }) { groups.append(groups.remove(at: i)) }
3729
+ return KeptSession(windows: groups.compactMap { g in
3730
+ guard let first = g.first else { return nil }
3731
+ let shown = first.tabGroup?.selectedWindow ?? first
3732
+ return KeptWindow(frame: NSStringFromRect(first.frame), tabs: g.map { keptTab($0.contentView as! Pane) }, shown: g.firstIndex { $0 === shown } ?? 0)
3733
+ })
3734
+ }
3735
+
3736
+ /** the windows kept for the next launch, when there are any */
3737
+ func keepWindows() {
3738
+ let s = keptWindows()
3739
+ guard !s.windows.isEmpty, let data = try? JSONEncoder().encode(s) else { return }
3740
+ if selfTesting { keptInMemory = data } else { UserDefaults.standard.set(data, forKey: Delegate.keptKey) }
3741
+ }
3742
+
3743
+ /** the windows a restart kept, read once: a later launch never brings them back again */
3744
+ func takeKept() -> KeptSession? {
3745
+ let data = selfTesting ? keptInMemory : UserDefaults.standard.data(forKey: Delegate.keptKey)
3746
+ if selfTesting { keptInMemory = nil } else { UserDefaults.standard.removeObject(forKey: Delegate.keptKey) }
3747
+ return data.flatMap { try? JSONDecoder().decode(KeptSession.self, from: $0) }
3748
+ }
3749
+
3750
+ /** the kept windows made again: each at its frame when a screen still shows it, its tabs in their order with the
3751
+ * one shown, each side panel open on its page at its width, signed in as its identity. A window after the first
3752
+ * comes on the screen alone before its tabs join it, as shift command n's does: macOS would make it a tab of the
3753
+ * first. The window that was in front comes last, in front */
3754
+ func restore(_ s: KeptSession) {
3755
+ for kw in s.windows {
3756
+ var group: [NSWindow] = []
3757
+ for t in kw.tabs {
3758
+ guard let url = sideURL(t.url) else { continue }
3759
+ if let name = t.name { tabNames[tabKey(url)] = name }
3760
+ if let c = t.chips { tabChips[tabKey(url)] = (c.urlId, c.logins) }
3761
+ let w = makeWindow(url, pinned: tabbed && t.pinned && hubTab == nil, alone: true)
3762
+ if let side = t.side.flatMap(sideURL), let pane = w.contentView as? Pane {
3763
+ pane.openSide(side, identity: t.sideIdentity)
3764
+ if let width = t.sideWidth { pane.sideWidth = CGFloat(width) }
3765
+ }
3766
+ if let last = group.last { last.addTabbedWindow(w, ordered: .above) } else {
3767
+ let r = NSRectFromString(kw.frame)
3768
+ if r.width >= 200, r.height >= 150, NSScreen.screens.contains(where: { $0.visibleFrame.intersects(r) }) { w.setFrame(r, display: false) }
3769
+ if tabbed && windowCount > 1 {
3770
+ w.tabbingMode = .disallowed
3771
+ onScreen(w)
3772
+ w.tabbingMode = .preferred
3773
+ } else { onScreen(w) }
3774
+ }
3775
+ group.append(w)
3776
+ }
3777
+ guard !group.isEmpty else { continue }
3778
+ show(group[min(max(kw.shown, 0), group.count - 1)])
3779
+ }
3780
+ showTabBars()
3781
+ }
3782
+
3783
+ func offerRelaunch(_ w: NSWindow) {
3784
+ guard stale, !w.titlebarAccessoryViewControllers.contains(where: { $0.identifier?.rawValue == "relaunch" }) else { return }
3785
+ let button = NSButton(title: "new version: relaunch", target: self, action: #selector(relaunch(_:)))
3786
+ button.bezelStyle = .recessed
3787
+ button.controlSize = .small
3788
+ button.sizeToFit()
3789
+ let holder = NSView(frame: NSRect(x: 0, y: 0, width: button.frame.width + 12, height: 28))
3790
+ button.frame.origin = NSPoint(x: 6, y: (28 - button.frame.height) / 2)
3791
+ holder.addSubview(button)
3792
+ let c = NSTitlebarAccessoryViewController()
3793
+ c.identifier = NSUserInterfaceItemIdentifier("relaunch")
3794
+ c.view = holder
3795
+ c.layoutAttribute = .trailing
3796
+ w.addTitlebarAccessoryViewController(c)
3797
+ }
3798
+
3799
+ /** 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
3800
+ * one chip a field. A press copies that field (copyChip). Words only: no value is drawn or kept */
3801
+ func wearChips(_ w: NSWindow, _ chips: (urlId: String, logins: [String])) {
3802
+ let row = NSStackView()
3803
+ row.orientation = .horizontal
3804
+ row.spacing = 4
3805
+ row.edgeInsets = NSEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
3806
+ for (i, label) in chips.logins.enumerated() {
3807
+ let name = NSTextField(labelWithString: label)
3808
+ name.font = .systemFont(ofSize: NSFont.smallSystemFontSize)
3809
+ name.textColor = .secondaryLabelColor
3810
+ if let last = row.arrangedSubviews.last { row.setCustomSpacing(12, after: last) }
3811
+ row.addArrangedSubview(name)
3812
+ for field in ["account", "password"] {
3813
+ let b = ChipButton(title: field, target: self, action: #selector(copyChip(_:)))
3814
+ b.urlId = chips.urlId
3815
+ b.login = i
3816
+ b.label = label
3817
+ b.field = field
3818
+ b.toolTip = "copy the \(field) of \(label)"
3819
+ b.bezelStyle = .recessed
3820
+ b.controlSize = .small
3821
+ b.image = NSImage(systemSymbolName: "doc.on.doc", accessibilityDescription: "copy")
3822
+ b.imagePosition = .imageLeading
3823
+ row.addArrangedSubview(b)
3824
+ }
3825
+ }
3826
+ row.frame = NSRect(x: 0, y: 0, width: row.fittingSize.width, height: 28)
3827
+ let c = NSTitlebarAccessoryViewController()
3828
+ c.identifier = NSUserInterfaceItemIdentifier("logins")
3829
+ c.view = row
3830
+ c.layoutAttribute = .trailing
3831
+ w.addTitlebarAccessoryViewController(c)
3832
+ }
3833
+
3834
+ /** the chips a tab wears, in their order */
3835
+ func chipButtons(of w: NSWindow?) -> [ChipButton] {
3836
+ guard let c = w?.titlebarAccessoryViewControllers.first(where: { $0.identifier?.rawValue == "logins" }) else { return [] }
3837
+ return (c.view as? NSStackView)?.arrangedSubviews.compactMap { $0 as? ChipButton } ?? []
3838
+ }
3839
+
3840
+ /** the hub's answers to a chip: nothing of them is kept on disk */
3841
+ lazy var quiet = URLSession(configuration: .ephemeral)
3842
+
3843
+ /** a chip's press: the hub's copy route answers the field (any program of this Mac reaches it, the hub guards it),
3844
+ * and the value goes from the answer to the board, nowhere else. A refusal says the hub's words on the chip */
3845
+ @objc func copyChip(_ b: ChipButton) {
3846
+ guard let repo = projectRepo?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), let api = URL(string: "/r/\(repo)/api/urls/copy", relativeTo: startURL) else { return }
3847
+ var req = URLRequest(url: api)
3848
+ req.httpMethod = "POST"
3849
+ req.timeoutInterval = 5
3850
+ req.setValue("application/json", forHTTPHeaderField: "content-type")
3851
+ req.httpBody = try? JSONSerialization.data(withJSONObject: ["id": b.urlId, "login": b.login, "field": b.field])
3852
+ b.say("copying…", for: 6)
3853
+ quiet.dataTask(with: req) { data, res, err in
3854
+ let code = (res as? HTTPURLResponse)?.statusCode ?? 0
3855
+ let value = code == 200 ? (data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any])?["value"] as? String : nil
3856
+ // a refusal's words are the hub's, which never hold a value; the answer of a copy is never read as words
3857
+ 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)"
3858
+ DispatchQueue.main.async {
3859
+ if let value {
3860
+ self.conceal(value)
3861
+ return b.say("copied")
3862
+ }
3863
+ NSLog("shipkit: the \(b.field) of \(b.label) (\(b.urlId)) was not copied: \(why)")
3864
+ b.say("not copied", why: why, for: 5)
3865
+ }
3866
+ }.resume()
3867
+ }
3868
+
3869
+ /** the board a chip copies into and command V's picture is read from (Web.paste): the owner's, and one of the run's
3870
+ * own in a self test, which never reaches his */
3871
+ lazy var board: NSPasteboard = selfTesting ? NSPasteboard(name: NSPasteboard.Name("dev.shipkit.self-test.\(ProcessInfo.processInfo.processIdentifier)")) : .general
3872
+ /** how long a copied value stays on the board */
3873
+ var clearAfter: TimeInterval = 90
3874
+ /** the board's count right after the last copy: while it matches, the board holds that value */
3875
+ var copiedAt: Int?
3876
+ /** the mark a clipboard manager skips (nspasteboard.org): a password never lands in its history */
3877
+ static let concealed = NSPasteboard.PasteboardType("org.nspasteboard.ConcealedType")
3878
+
3879
+ func conceal(_ value: String) {
3880
+ board.clearContents()
3881
+ board.declareTypes([.string, Delegate.concealed], owner: nil)
3882
+ board.setString(value, forType: .string)
3883
+ board.setString("", forType: Delegate.concealed)
3884
+ let mark = board.changeCount
3885
+ copiedAt = mark
3886
+ DispatchQueue.main.asyncAfter(deadline: .now() + clearAfter) { [weak self] in self?.clearCopy(mark) }
3887
+ }
3888
+
3889
+ /** the value copied at `mark` (none: the last one) leaves the board, unless anything was copied since */
3890
+ func clearCopy(_ mark: Int? = nil) {
3891
+ guard let at = copiedAt, mark == nil || mark == at else { return }
3892
+ copiedAt = nil
3893
+ if board.changeCount == at { board.clearContents() }
3894
+ }
3895
+
3896
+ // a quit before the clock: the value leaves with the app. A plain quit keeps the windows for the next launch only
3897
+ // where the system says so (Desktop & Dock, « Close windows when quitting an application » off); a relaunch always
3898
+ func applicationWillTerminate(_ note: Notification) {
3899
+ clearCopy()
3900
+ if !selfTesting && UserDefaults.standard.bool(forKey: "NSQuitAlwaysKeepsWindows") { keepWindows() }
3901
+ }
3902
+
3903
+ /** a fresh copy of this bundle once this one has quit, its windows and tabs back as they are (keepWindows): the
3904
+ * home app with no window comes back with none. A self test keeps the windows and starts nothing */
3905
+ @objc func relaunch(_ sender: Any?) {
3906
+ keepWindows()
3907
+ if selfTesting { relaunches += 1; return }
3908
+ let back = isShipkit && windows.isEmpty ? " --args --background" : ""
3909
+ let path = Bundle.main.bundlePath.replacingOccurrences(of: "'", with: "'\\''")
3910
+ let p = Process()
3911
+ p.executableURL = URL(fileURLWithPath: "/bin/sh")
3912
+ p.arguments = ["-c", "while kill -0 \(ProcessInfo.processInfo.processIdentifier) 2>/dev/null; do sleep 0.2; done; open '\(path)'\(back)"]
3913
+ try? p.run()
3914
+ NSApp.terminate(nil)
573
3915
  }
574
3916
 
575
3917
  /** 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
3918
+ lazy var openOutside: (URL) -> Void = { url in
577
3919
  NSWorkspace.shared.open(url, configuration: NSWorkspace.OpenConfiguration()) { _, err in
578
3920
  guard let err else { return }
579
3921
  DispatchQueue.main.async {
580
3922
  let alert = NSAlert()
581
3923
  alert.messageText = "This link could not open outside the app"
582
3924
  alert.informativeText = "\(url.absoluteString)\n\n\(err.localizedDescription)"
583
- alert.runModal()
3925
+ self.present(alert)
584
3926
  }
585
3927
  }
586
3928
  }
587
3929
 
3930
+ /** a project app sends a main frame's move down its road: a tab, the default browser, another repo's app. False:
3931
+ * it stays in the page that asked. The context menu's « open in a tab here » makes its own ask a tab, whatever
3932
+ * the site */
3933
+ func reroutes(_ url: URL, from web: WKWebView, new: Bool, click: Bool) -> Bool {
3934
+ let menu = new && (web as? Web)?.tabNext == true
3935
+ if menu { (web as? Web)?.tabNext = false }
3936
+ switch menu ? Road.tab : road(to: url, from: web.url, home: (web.superview as? Pane)?.opened, new: new, click: click, repo: projectRepo) {
3937
+ case .here: return false
3938
+ case .tab: openTab(url, again: menu)
3939
+ case .declared: openDeclared(url)
3940
+ case .outside: openOutside(url)
3941
+ case .app(let other): openProjectApp(other)
3942
+ }
3943
+ return true
3944
+ }
3945
+
588
3946
  // a link clicked, or a new window asked (target=_blank, window.open): the app's own host stays in the app, any
589
3947
  // other site or app leaves for the default browser (`leaves`)
590
3948
  func webView(_ web: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
591
3949
  // a link marked download saves the file, as a browser does, instead of showing it in the window
592
3950
  if action.shouldPerformDownload { return decisionHandler(.download) }
593
- guard let url = action.request.url, action.navigationType == .linkActivated || action.targetFrame == nil, leaves(url) else { return decisionHandler(.allow) }
3951
+ // a project app: each main frame's move takes its road
3952
+ if tabbed, let url = action.request.url, action.targetFrame?.isMainFrame ?? true {
3953
+ return decisionHandler(reroutes(url, from: web, new: action.targetFrame == nil, click: action.navigationType == .linkActivated) ? .cancel : .allow)
3954
+ }
3955
+ // a frame of a project app's page moves inside its own site; a link clicked in it to another site leaves
3956
+ if tabbed, let url = action.request.url, action.targetFrame != nil {
3957
+ let out = action.navigationType == .linkActivated && road(to: url, from: action.sourceFrame.request.url, home: nil, new: false, click: true, repo: nil) == .outside
3958
+ if out { openOutside(url) }
3959
+ return decisionHandler(out ? .cancel : .allow)
3960
+ }
3961
+ // a tab of the home app on a site (tabBeside) keeps that site's own links
3962
+ guard let url = action.request.url, action.navigationType == .linkActivated || action.targetFrame == nil, leaves(url), !(isShipkit && siteOf(url) == siteOf(web.url)) else { return decisionHandler(.allow) }
594
3963
  openOutside(url)
595
3964
  decisionHandler(.cancel)
596
3965
  }
597
3966
 
598
3967
  // a response the window cannot show (an archive, an attachment) is saved too
599
3968
  func webView(_ web: WKWebView, decidePolicyFor response: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
3969
+ 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
3970
  let attachment = ((response.response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Disposition") ?? "").lowercased().hasPrefix("attachment")
601
3971
  decisionHandler(attachment || !response.canShowMIMEType ? .download : .allow)
602
3972
  }
603
3973
 
3974
+ /** a frame of a hub page got an error for an address: the page hears that address and its status, nothing else,
3975
+ * so a url's page drops an address its site no longer answers (serve/hub-app/url-address.ts, FRAME_ANSWER) */
3976
+ func frameAnswered(_ web: WKWebView, _ url: URL, _ status: Int) {
3977
+ guard let data = try? JSONSerialization.data(withJSONObject: ["url": url.absoluteString, "status": status]), let json = String(data: data, encoding: .utf8) else { return }
3978
+ web.evaluateJavaScript("dispatchEvent(new CustomEvent('sk-frame-answer', { detail: \(json) })); 0") { _, _ in }
3979
+ }
3980
+
604
3981
  func webView(_ web: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) { download.delegate = self }
605
3982
  func webView(_ web: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) { download.delegate = self }
606
3983
 
@@ -647,20 +4024,19 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
647
4024
  let alert = NSAlert()
648
4025
  alert.messageText = "Download failed"
649
4026
  alert.informativeText = "\(dest?.lastPathComponent ?? "the file"): \(error.localizedDescription)"
650
- alert.runModal()
4027
+ present(alert)
651
4028
  }
652
4029
 
653
- // `--self-test-download`: an offscreen page clicks a link marked download, twice, into SHIPKIT_GUI_DOWNLOADS; what
4030
+ // `--self-test-download`: a page in a window that is never shown clicks a link marked download, twice, into SHIPKIT_GUI_DOWNLOADS; what
654
4031
  // landed printed, exit 0 only when both files hold the bytes under a free name and the page stayed on itself
655
4032
  func selfTestDownload() {
656
4033
  let web = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
657
4034
  web.navigationDelegate = self
658
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
4035
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
659
4036
  win.contentView = Pane(web: web)
660
- win.orderFrontRegardless()
661
4037
  windows.append(win)
662
4038
  var saved: [String] = []
663
- DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); exit(1) }
4039
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); finish(1) }
664
4040
  let click = "document.getElementById('a').click(); 'clicked'"
665
4041
  onDownloaded = { url in
666
4042
  let text = url.flatMap { try? String(contentsOf: $0, encoding: .utf8) } ?? "none"
@@ -669,7 +4045,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
669
4045
  web.evaluateJavaScript("document.body.dataset.page") { page, _ in
670
4046
  print("saved=\(saved.joined(separator: ","))")
671
4047
  print("page=\((page as? String) ?? "gone")")
672
- exit(saved == ["hello.txt:hello", "hello (2).txt:hello"] && (page as? String) == "here" ? 0 : 1)
4048
+ finish(saved == ["hello.txt:hello", "hello (2).txt:hello"] && (page as? String) == "here" ? 0 : 1)
673
4049
  }
674
4050
  }
675
4051
  var started = false
@@ -681,7 +4057,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
681
4057
  web.loadHTMLString("<body data-page=here><a id=a href='data:text/plain,hello' download='hello.txt'>save</a></body>", baseURL: nil)
682
4058
  }
683
4059
 
684
- // `--self-test-links`: an offscreen page of the machine with a link of each kind, each clicked as a real mouse
4060
+ // `--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
4061
  // event, then a window.open with no click under it; the road out recorded instead of taken. What left and where
686
4062
  // the page is printed, exit 0 only when every link to another site or app left, the machine's own link stayed in
687
4063
  // the page and no window opened
@@ -691,11 +4067,10 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
691
4067
  let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 600, height: 400), configuration: webConfig())
692
4068
  web.navigationDelegate = self
693
4069
  web.uiDelegate = self
694
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
4070
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
695
4071
  win.contentView = web
696
- win.orderFrontRegardless()
697
4072
  windows.append(win)
698
- DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); exit(1) }
4073
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); finish(1) }
699
4074
  let ids = ["blank", "plain", "mail", "home"]
700
4075
  let expected = ["https://dash.cloudflare.com/?to=/:account/r2/api-tokens", "https://example.com/plain", "mailto:owner@example.com", "https://example.com/later"]
701
4076
  func click(_ k: Int) {
@@ -707,12 +4082,12 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
707
4082
  print("page=\((page as? String) ?? "gone")")
708
4083
  print("windows=\(self.windows.count)")
709
4084
  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)
4085
+ 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
4086
  }
712
4087
  }
713
4088
  }
714
4089
  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) }
4090
+ guard let xy = v as? [Double], xy.count == 2 else { print("no link \(ids[k])"); finish(1) }
716
4091
  let at = web.convert(NSPoint(x: xy[0], y: web.isFlipped ? xy[1] : web.bounds.height - xy[1]), to: nil)
717
4092
  for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] {
718
4093
  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 +4117,39 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
742
4117
  var burst: [WaitingThread] = []
743
4118
  /** each web view's last count: a page that leaves the home, or a closed window, drops out of the badge */
744
4119
  var counts: [ObjectIdentifier: Int] = [:]
4120
+ /** the repo the badge counts, the bundle's (the self test sets one) */
4121
+ var badgeRepo = projectRepo
745
4122
  /** hears every notification instead of the system: the self test reads it */
746
4123
  var deliver: ((Note) -> Void)?
747
4124
 
748
4125
  func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
749
4126
  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 {
4127
+ // the home app and a project app hear their hub alone: a page of another site that reached a hub tab posts nothing
4128
+ let from = message.frameInfo.securityOrigin
4129
+ if hubApp && !(from.host == startURL.host && from.port == (startURL.port ?? 0)) { return }
4130
+ 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) }
4131
+ // a link of a thread: the url beside the page, in its window's side panel; a page with no window (the home kept
4132
+ // loaded with none) has no panel to show it in
4133
+ if let href = body["sidePanel"] as? String {
4134
+ guard let url = sideURL(href), let pane = message.webView?.superview as? Pane else { return }
4135
+ return pane.openSide(url, identity: sideIdentity(body["identity"]))
4136
+ }
4137
+ // the name of the tab the page asks next, and what command with t opens for the entry it shows
4138
+ if let name = body["tabName"] as? String, let url = (body["url"] as? String).flatMap({ URL(string: $0) }) {
4139
+ tabNames[tabKey(url)] = String(name.prefix(120))
4140
+ tabChips[tabKey(url)] = chipsOf(body)
4141
+ return
4142
+ }
4143
+ if let e = body["entryTab"], let web = message.webView {
4144
+ let d = e as? [String: Any]
4145
+ let live = Set(windows.compactMap { ($0.contentView as? Pane)?.web }.map(ObjectIdentifier.init) + arriving.keys)
4146
+ entries = entries.filter { live.contains($0.key) }
4147
+ entries[ObjectIdentifier(web)] = (d?["url"] as? String).flatMap { URL(string: $0) }.map { (url: $0, name: d?["name"] as? String) }
4148
+ return
4149
+ }
4150
+ // a page that has nothing left to show asks to leave (a terminal alone whose terminal ended): its tab, never the hub's
4151
+ if body["closeTab"] as? Bool == true { return closeTab(of: message.webView?.window) }
4152
+ if let n = badgeCount(body, repo: badgeRepo), let web = message.webView {
751
4153
  // a window's page posts again: the page kept with no window leaves
752
4154
  if let k = keeper, k !== web {
753
4155
  keeper = nil
@@ -759,6 +4161,8 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
759
4161
  drawBadge()
760
4162
  if let keys = body["keys"] as? [String] { takeBack(waiting: Set(keys)) }
761
4163
  }
4164
+ // a project app notifies nothing: the home app's banners already name every thread
4165
+ guard badgeRepo == nil else { return }
762
4166
  if let seed = body["seed"] as? [[String: Any]] {
763
4167
  let threads = seed.compactMap(threadOf)
764
4168
  if !seeded {
@@ -848,9 +4252,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
848
4252
  if let url = fallbackOf(info) { open(url) }
849
4253
  return
850
4254
  }
851
- if win.isMiniaturized { win.deminiaturize(nil) }
852
- win.makeKeyAndOrderFront(nil)
853
- NSApp.activate(ignoringOtherApps: true)
4255
+ onScreen(win)
854
4256
  openIn(pane.web, info)
855
4257
  }
856
4258
 
@@ -875,21 +4277,20 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
875
4277
  }
876
4278
  }
877
4279
 
878
- // `--self-test-badge`: an offscreen page posts as the hub does: the seed and a count, threads (one twice), the seed
4280
+ // `--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
4281
  // of a reload, a burst of five, the count back to zero, then a notification's click opens a thread through the
880
4282
  // page's hook; the badge, the planned
881
4283
  // 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
4284
+ // reaches the system's notification center
883
4285
  func selfTestBadge() {
884
4286
  let config = WKWebViewConfiguration()
885
4287
  config.userContentController.add(self, name: "shipkit")
886
4288
  let web = WKWebView(frame: .zero, configuration: config)
887
4289
  web.navigationDelegate = self
888
- let win = NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
4290
+ let win = QuietWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
889
4291
  win.contentView = Pane(web: web)
890
- win.orderFrontRegardless()
891
4292
  windows.append(win)
892
- DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); exit(1) }
4293
+ DispatchQueue.main.asyncAfter(deadline: .now() + 15) { print("timeout"); finish(1) }
893
4294
  var notes: [String] = []
894
4295
  deliver = { n in
895
4296
  switch n {
@@ -920,19 +4321,28 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
920
4321
  let many = notes
921
4322
  post("p({waiting: 0})") {
922
4323
  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)
4324
+ // a project app of repo b: the same post shows b's count, and a thread arriving notifies nothing
4325
+ self.badgeRepo = "b"
4326
+ let heard = notes.count
4327
+ post("p({waiting: 3, keys: [], repos: {a: 2, b: 1}}); " + thread("e", "1")) {
4328
+ let project = NSApp.dockTile.badgeLabel ?? "none"
4329
+ let quiet = notes.count == heard
4330
+ self.badgeRepo = nil
4331
+ // a click on the notification of thread b/1: the page's hook opens it in place
4332
+ self.openIn(web, ["repo": "b", "id": "1", "url": "http://127.0.0.1:9/"]) { ok in
4333
+ web.evaluateJavaScript("document.body.dataset.opened") { opened, _ in
4334
+ let o = (opened as? String) ?? "none"
4335
+ // the banners taken back once a/1 and c/5 alone still wait: b/1's, and one left by an older build
4336
+ 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"])
4337
+ print("badge-two=\(two)")
4338
+ print("few=\(few.joined(separator: ","))")
4339
+ print("burst=\(many.joined(separator: ","))")
4340
+ print("badge-zero=\(zero)")
4341
+ print("badge-project=\(project) quiet=\(quiet)")
4342
+ print("click-opened=\(ok ? o : "fallback")")
4343
+ print("stale=\(stale.joined(separator: ","))")
4344
+ 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)
4345
+ }
936
4346
  }
937
4347
  }
938
4348
  }
@@ -943,14 +4353,31 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
943
4353
  web.loadHTMLString("<body><script>window.shipkitApp = { openThread: (r, i) => { document.body.dataset.opened = r + '/' + i }, openInbox: () => { document.body.dataset.opened = 'inbox' } }</script><p>badge</p></body>", baseURL: nil)
944
4354
  }
945
4355
 
946
- // window.open and target=_blank: one more window of this app for its own pages, the default browser for the rest
4356
+ // window.open and target=_blank: a project app's road; in the home app a tab of the asking hub page's window for
4357
+ // the machine's own pages and a url the hub named (its « in a tab here »), the default browser for the rest; any
4358
+ // other app one more window for its own pages
947
4359
  func webView(_ web: WKWebView, createWebViewWith config: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
948
4360
  if let url = action.request.url {
949
- if leaves(url) { openOutside(url) } else { open(url) }
4361
+ // a script's window.open comes here with no policy asked first: a project app sends it down its road too
4362
+ if tabbed { asksWindow(url, from: web) } else if homeTabs(url, from: web.url) { tabBeside(url, of: web) } else if leaves(url) { openOutside(url) } else { open(url) }
950
4363
  }
951
4364
  return nil
952
4365
  }
953
4366
 
4367
+ /** the home app: a window a hub page asks is a tab of that page's window when it stays here or the hub named it */
4368
+ func homeTabs(_ url: URL, from: URL?) -> Bool {
4369
+ isShipkit && from.map(isHub) == true && (!leaves(url) || tabNames[tabKey(url)] != nil)
4370
+ }
4371
+
4372
+ /** a page as a native tab of `web`'s window, after its last tab; a site's tab already open is shown, never a
4373
+ * second one (a hub page may ask its own address again: one more tab on it) */
4374
+ func tabBeside(_ url: URL, of web: WKWebView) {
4375
+ if !isHub(url), let w = tab(on: url) ?? tab(named: url) { return show(w) }
4376
+ let w = makeWindow(url)
4377
+ if let host = web.window, windows.contains(where: { $0 === host }) { (host.tabGroup?.windows.last ?? host).addTabbedWindow(w, ordered: .above) }
4378
+ show(w)
4379
+ }
4380
+
954
4381
  // alert, confirm and prompt: without these WebKit answers each one at once
955
4382
  // (no panel, confirm false, prompt null), so a page's dialogs do nothing.
956
4383
  // WebKit throws when a handler is dropped or called twice: `panel` calls
@@ -975,14 +4402,9 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
975
4402
  alert.accessoryView = field
976
4403
  alert.window.initialFirstResponder = field
977
4404
  }
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)
4405
+ present(alert, on: web.window) { done($0 == .alertFirstButtonReturn) }
4406
+ // on a sheet, first responder selects the whole default text, so typing replaces it
4407
+ if let field, web.window != nil { alert.window.makeFirstResponder(field) }
986
4408
  }
987
4409
 
988
4410
  func webView(_ web: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
@@ -1016,9 +4438,19 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
1016
4438
  let fileItem = NSMenuItem()
1017
4439
  main.addItem(fileItem)
1018
4440
  let file = NSMenu(title: "File")
1019
- file.addItem(withTitle: "New Window", action: #selector(newWindow(_:)), keyEquivalent: "n")
4441
+ // command with t, a project app's: the entry the hub shows in a tab of its own. Command with n: the new thread
4442
+ // 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
4443
+ // on shift, a project's a window of its own on the hub
4444
+ if tabbed { file.addItem(withTitle: "New Tab", action: #selector(entryTab(_:)), keyEquivalent: "t") }
4445
+ if hubApp { file.addItem(withTitle: "New Thread", action: #selector(newThread(_:)), keyEquivalent: "n") }
4446
+ if tabbed {
4447
+ file.addItem(withTitle: "New Window", action: #selector(projectWindow(_:)), keyEquivalent: "N")
4448
+ item(file, "Duplicate Tab", #selector(newWindow(_:)), "", [])
4449
+ } else if hubApp { file.addItem(withTitle: "New Window", action: #selector(newWindow(_:)), keyEquivalent: "N") }
4450
+ else { file.addItem(withTitle: "New Window", action: #selector(newWindow(_:)), keyEquivalent: "n") }
1020
4451
  file.addItem(withTitle: "Reload", action: #selector(reload(_:)), keyEquivalent: "r")
1021
- file.addItem(withTitle: "Close Window", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
4452
+ file.addItem(withTitle: tabbed ? "Close Tab" : "Close Window", action: tabbed ? #selector(closeTab(_:)) : #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
4453
+ if tabbed { file.addItem(withTitle: "Close Window", action: #selector(closeEveryTab(_:)), keyEquivalent: "W") }
1022
4454
  fileItem.submenu = file
1023
4455
  let editItem = NSMenuItem()
1024
4456
  main.addItem(editItem)
@@ -1062,6 +4494,18 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
1062
4494
  previous.keyEquivalentModifierMask = [.command]
1063
4495
  let next = win.addItem(withTitle: "Show Next Tab", action: #selector(nextTab(_:)), keyEquivalent: String(UnicodeScalar(NSPageDownFunctionKey)!))
1064
4496
  next.keyEquivalentModifierMask = [.command]
4497
+ // a project app's windows by their standard words: the tab shown into a window of its own, every window back
4498
+ // into one. Their actions are the app's own, so the hub's tab ends first
4499
+ if tabbed {
4500
+ item(win, "Move Tab to New Window", #selector(tabToNewWindow(_:)), "", [])
4501
+ item(win, "Merge All Windows", #selector(mergeWindows(_:)), "", [])
4502
+ }
4503
+ // a project app's tabs by number: the items show the keys, `takes` reads them from the physical digit row
4504
+ let digits = tabDigits(mode)
4505
+ if !digits.isEmpty { win.addItem(.separator()) }
4506
+ for n in digits {
4507
+ item(win, n == 1 ? "Show the Hub" : n == 9 ? "Show the Last Tab" : "Show Tab \(n)", #selector(selectTab(_:)), String(n), tag: n)
4508
+ }
1065
4509
  winItem.submenu = win
1066
4510
  NSApp.windowsMenu = win
1067
4511
  NSApp.mainMenu = main
@@ -1071,5 +4515,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
1071
4515
  let app = NSApplication.shared
1072
4516
  let delegate = Delegate()
1073
4517
  app.delegate = delegate
1074
- app.setActivationPolicy(.regular)
4518
+ // a self test is no app of the Dock and takes no focus; the window server is asked through its whole run
4519
+ app.setActivationPolicy(selfTesting ? .prohibited : .regular)
4520
+ if selfTesting { Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { _ in seenOnScreen = max(seenOnScreen, windowsOnScreen().own) } }
1075
4521
  app.run()