rvlib-shipkit 2.30.0 → 2.32.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 (821) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +15 -0
  3. package/package.json +1 -1
  4. package/src/advisors/acts.ts +186 -94
  5. package/src/advisors/advice.ts +227 -96
  6. package/src/advisors/advisor-view.ts +141 -68
  7. package/src/advisors/app-graph.ts +8 -2
  8. package/src/advisors/app.ts +3 -11
  9. package/src/advisors/cf-api.ts +44 -0
  10. package/src/advisors/dir-bucket.ts +70 -0
  11. package/src/advisors/edge/api.ts +32 -197
  12. package/src/advisors/edge/bucket.ts +10 -1
  13. package/src/advisors/edge/handler.ts +36 -137
  14. package/src/advisors/edge/here.ts +63 -0
  15. package/src/advisors/edge/pages.ts +90 -0
  16. package/src/advisors/edge/shell.ts +11 -8
  17. package/src/advisors/edge/sign-in.ts +209 -0
  18. package/src/advisors/edge/status.ts +41 -6
  19. package/src/advisors/edge/types.ts +42 -58
  20. package/src/advisors/expose.ts +227 -121
  21. package/src/advisors/here.ts +66 -0
  22. package/src/advisors/invite-send.ts +220 -0
  23. package/src/advisors/invite.ts +72 -0
  24. package/src/advisors/job.ts +100 -14
  25. package/src/advisors/login.ts +91 -0
  26. package/src/advisors/owner-name.ts +37 -0
  27. package/src/advisors/owner-store.ts +295 -66
  28. package/src/advisors/photos.ts +12 -52
  29. package/src/advisors/project.ts +105 -59
  30. package/src/advisors/reach.ts +89 -0
  31. package/src/advisors/rights.ts +152 -0
  32. package/src/advisors/routes.ts +340 -127
  33. package/src/advisors/scan.ts +24 -2
  34. package/src/advisors/setup-run.ts +132 -0
  35. package/src/advisors/share-trace.ts +78 -0
  36. package/src/advisors/sign-in-probe.ts +89 -0
  37. package/src/advisors/speaks.ts +29 -0
  38. package/src/advisors/sync.ts +219 -194
  39. package/src/advisors/tunnel.ts +119 -0
  40. package/src/advisors/users-listen.ts +92 -0
  41. package/src/advisors/users-router.ts +358 -0
  42. package/src/advisors/users-store.ts +81 -0
  43. package/src/agent-time/accounts-usage-disk.ts +45 -3
  44. package/src/agent-time/blocked-scan.ts +181 -0
  45. package/src/agent-time/claude-sessions.ts +63 -3
  46. package/src/agent-time/registry.ts +142 -51
  47. package/src/agent-time/store.ts +204 -141
  48. package/src/annex/born.ts +2 -9
  49. package/src/asks/ask-bar-fold.ts +2 -1
  50. package/src/asks/ask-carry.ts +14 -7
  51. package/src/asks/ask-close.ts +2 -1
  52. package/src/asks/ask-doc.ts +2 -1
  53. package/src/asks/ask-edit.ts +49 -0
  54. package/src/asks/ask-migrate.ts +3 -2
  55. package/src/asks/ask-since.ts +74 -0
  56. package/src/asks/ask-steps-fold.ts +2 -1
  57. package/src/asks/ask-store.ts +74 -32
  58. package/src/asks/ask-words-fold.ts +2 -2
  59. package/src/check.ts +3 -43
  60. package/src/checks/SK001-package-json-shape.check.ts +16 -58
  61. package/src/checks/SK003-claude-md-shape.check.ts +78 -20
  62. package/src/checks/SK004-gitignore-policy.check.ts +31 -73
  63. package/src/checks/SK008-reviewer-agent.check.ts +1 -1
  64. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  65. package/src/checks/SK013-one-way-in-policy.check.ts +3 -7
  66. package/src/checks/SK017-vscode-hub-task.check.ts +4 -4
  67. package/src/checks/SK019-tests-run-in-units.check.ts +3 -14
  68. package/src/checks/SK020-self-spawning-check.check.ts +5 -7
  69. package/src/checks/SK032-ignored-inputs.check.ts +9 -5
  70. package/src/checks/SK035-public-clean.check.ts +1 -1
  71. package/src/checks/SK036-draft-media-size.check.ts +4 -3
  72. package/src/checks/SK038-speaks-as.check.ts +6 -5
  73. package/src/checks/SK039-vscode-watch-generated.check.ts +5 -25
  74. package/src/checks/SK042-post-kinds.check.ts +5 -14
  75. package/src/checks/SK044-behind-upstream.check.ts +2 -1
  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 +73 -0
  79. package/src/checks/SK055-retired-config-keys.check.ts +45 -0
  80. package/src/cli/clip.ts +44 -0
  81. package/src/cli/cmd_Advisors.ts +278 -144
  82. package/src/cli/cmd_Annex.ts +1 -1
  83. package/src/cli/cmd_Asks.ts +126 -31
  84. package/src/cli/cmd_Assets.ts +1 -1
  85. package/src/cli/cmd_Backup.ts +25 -168
  86. package/src/cli/cmd_BackupTargets.ts +106 -0
  87. package/src/cli/cmd_Bump.ts +1 -1
  88. package/src/cli/cmd_CacheAudit.ts +1 -1
  89. package/src/cli/cmd_Calls.ts +1 -1
  90. package/src/cli/cmd_Capacity.ts +1 -1
  91. package/src/cli/cmd_Check.ts +2 -2
  92. package/src/cli/cmd_Checks.ts +2 -15
  93. package/src/cli/cmd_Ci.ts +1 -1
  94. package/src/cli/cmd_Commands.ts +1 -1
  95. package/src/cli/cmd_ConfigKeys.ts +1 -1
  96. package/src/cli/cmd_Contracts.ts +1 -1
  97. package/src/cli/cmd_CrossRepoActivity.ts +1 -6
  98. package/src/cli/cmd_Db.ts +33 -68
  99. package/src/cli/cmd_Drill.ts +1 -1
  100. package/src/cli/cmd_Drive.ts +259 -0
  101. package/src/cli/cmd_Fleet.ts +1 -1
  102. package/src/cli/cmd_FleetContext.ts +45 -0
  103. package/src/cli/cmd_FleetPush.ts +1 -1
  104. package/src/cli/cmd_FleetUpdate.ts +104 -0
  105. package/src/cli/cmd_GlobalContext.ts +1 -1
  106. package/src/cli/cmd_GlobalProcesses.ts +6 -4
  107. package/src/cli/cmd_History.ts +8 -27
  108. package/src/cli/cmd_Home.ts +8 -36
  109. package/src/cli/cmd_Hooks.ts +3 -12
  110. package/src/cli/cmd_Hq.ts +47 -90
  111. package/src/cli/cmd_Init.ts +1 -1
  112. package/src/cli/cmd_Insights.ts +1 -1
  113. package/src/cli/cmd_Keys.ts +1 -1
  114. package/src/cli/cmd_Lanes.ts +5 -4
  115. package/src/cli/cmd_Machines.ts +1 -1
  116. package/src/cli/cmd_Media.ts +6 -19
  117. package/src/cli/cmd_Messages.ts +1 -1
  118. package/src/cli/cmd_Mv.ts +1 -1
  119. package/src/cli/cmd_Needs.ts +1 -1
  120. package/src/cli/cmd_Orchestrator.ts +7 -16
  121. package/src/cli/cmd_OrchestratorRole.ts +10 -21
  122. package/src/cli/cmd_Overview.ts +1 -1
  123. package/src/cli/cmd_Pb.ts +1 -1
  124. package/src/cli/cmd_Planned.ts +1 -1
  125. package/src/cli/cmd_Rec.ts +1 -1
  126. package/src/cli/cmd_Reflect.ts +3 -3
  127. package/src/cli/cmd_Release.ts +1 -1
  128. package/src/cli/cmd_Releases.ts +58 -5
  129. package/src/cli/cmd_Review.ts +576 -483
  130. package/src/cli/cmd_Secret.ts +84 -2
  131. package/src/cli/cmd_Serve.ts +1 -1
  132. package/src/cli/cmd_Setup.ts +30 -0
  133. package/src/cli/cmd_Shot.ts +1 -1
  134. package/src/cli/cmd_Sign.ts +1 -1
  135. package/src/cli/cmd_Smoke.ts +1 -1
  136. package/src/cli/cmd_Social.ts +6 -3
  137. package/src/cli/cmd_SocialDrafts.ts +23 -16
  138. package/src/cli/cmd_Sound.ts +1 -1
  139. package/src/cli/cmd_Space.ts +4 -4
  140. package/src/cli/cmd_Start.ts +1 -1
  141. package/src/cli/cmd_Status.ts +1 -1
  142. package/src/cli/cmd_ThreadHolds.ts +1 -1
  143. package/src/cli/cmd_ThreadKinds.ts +1 -1
  144. package/src/cli/cmd_ThreadReflect.ts +3 -3
  145. package/src/cli/cmd_ThreadSyncNeeds.ts +7 -3
  146. package/src/cli/cmd_Time.ts +2 -2
  147. package/src/cli/cmd_Tmp.ts +1 -1
  148. package/src/cli/cmd_TraceAudit.ts +1 -1
  149. package/src/cli/cmd_Trailer.ts +2 -2
  150. package/src/cli/cmd_Tui.ts +1 -1
  151. package/src/cli/cmd_Urls.ts +61 -9
  152. package/src/cli/cmd_Vault.ts +1 -1
  153. package/src/cli/cmd_Veille.ts +1 -1
  154. package/src/cli/cmd_When.ts +1 -1
  155. package/src/cli/cmd_Wiki.ts +5 -2
  156. package/src/cli/cmd_Worktrees.ts +1 -1
  157. package/src/cli/family-pages.ts +1 -0
  158. package/src/cli/inbox-hook-run.ts +26 -18
  159. package/src/cli/line.ts +131 -0
  160. package/src/cli/registry-cli.ts +100 -0
  161. package/src/cli/registry-heads.ts +398 -0
  162. package/src/cli/registry.ts +381 -254
  163. package/src/cli/review-here.ts +5 -5
  164. package/src/cli.ts +47 -35
  165. package/src/collections/collection-types.ts +4 -1
  166. package/src/collections/providers.ts +6 -3
  167. package/src/collections/review.ts +6 -6
  168. package/src/context/context-line.ts +29 -0
  169. package/src/context/context-view.ts +34 -0
  170. package/src/context/project-context.ts +144 -0
  171. package/src/core/agent-allow-policy.ts +129 -0
  172. package/src/core/agent-env.ts +8 -0
  173. package/src/core/agent-spawn.ts +2 -0
  174. package/src/core/allow-rows.ts +74 -0
  175. package/src/core/capacity.ts +3 -2
  176. package/src/core/check-file-names.ts +19 -106
  177. package/src/core/es2022.ts +19 -0
  178. package/src/core/footprint.ts +39 -0
  179. package/src/core/git-bin.ts +18 -0
  180. package/src/core/git-root.ts +40 -4
  181. package/src/core/git.ts +22 -0
  182. package/src/core/hard-reset.ts +7 -1
  183. package/src/core/house-config-text.ts +47 -0
  184. package/src/core/house-layout.ts +4 -0
  185. package/src/core/identities-path.ts +67 -0
  186. package/src/core/identities-root.ts +23 -0
  187. package/src/core/instance.ts +1 -1
  188. package/src/core/jobs.ts +1 -4
  189. package/src/{scaffold → core}/jsonc-spans.ts +42 -0
  190. package/src/core/layout.ts +4 -2
  191. package/src/core/loop-watch.ts +28 -5
  192. package/src/core/machine-db.ts +34 -216
  193. package/src/core/machine-layout.ts +14 -127
  194. package/src/core/machine-name.ts +31 -0
  195. package/src/core/mask-source.ts +60 -0
  196. package/src/core/memory-watch.ts +62 -11
  197. package/src/core/motherhome.ts +8 -35
  198. package/src/core/on-loop.ts +10 -7
  199. package/src/core/one-way-in-policy.ts +0 -3
  200. package/src/core/pid-alive.ts +11 -0
  201. package/src/core/proc-path.ts +42 -0
  202. package/src/core/repo-walk.ts +0 -9
  203. package/src/core/retention.ts +3 -11
  204. package/src/core/retired-checks.ts +2 -0
  205. package/src/core/role-policy.ts +6 -7
  206. package/src/core/run-dirs.ts +2 -5
  207. package/src/core/runs.ts +5 -3
  208. package/src/core/scope.ts +44 -0
  209. package/src/core/scratch-objects.ts +1 -1
  210. package/src/core/slot-env.ts +4 -0
  211. package/src/core/slots.ts +2 -2
  212. package/src/core/spawn-timeout.ts +9 -3
  213. package/src/core/tmux-policy.ts +1 -1
  214. package/src/core/tools.ts +20 -0
  215. package/src/core/tree-watch.ts +304 -0
  216. package/src/core/when.ts +7 -45
  217. package/src/core/window-policy.ts +132 -0
  218. package/src/drives/context.ts +29 -0
  219. package/src/drives/drives-view.ts +121 -0
  220. package/src/drives/file.ts +89 -0
  221. package/src/drives/local-folder.ts +107 -0
  222. package/src/drives/login.ts +181 -0
  223. package/src/drives/named.ts +33 -0
  224. package/src/drives/rclone.ts +100 -0
  225. package/src/drives/reach.ts +73 -0
  226. package/src/drives/routes.ts +89 -0
  227. package/src/drives/shares.ts +292 -0
  228. package/src/fleet/context-fleet.ts +83 -0
  229. package/src/fleet/follow.ts +172 -0
  230. package/src/gate/builtin-checks-dir.ts +32 -0
  231. package/src/gate/discover-checks.ts +45 -58
  232. package/src/gate/gate-checks.ts +21 -131
  233. package/src/gate/pre-commit-discovery.ts +205 -24
  234. package/src/gate/run-check.ts +0 -4
  235. package/src/gate/run-fix.ts +5 -17
  236. package/src/gate/run-fixers.ts +13 -41
  237. package/src/home/advisors-tunnel-start.ts +9 -0
  238. package/src/home/app-sign.ts +2 -2
  239. package/src/home/autostart.ts +61 -17
  240. package/src/home/backup-status.ts +326 -0
  241. package/src/home/backup-verdict.ts +19 -0
  242. package/src/home/daemon-jobs.ts +206 -107
  243. package/src/home/database-words.ts +18 -2
  244. package/src/home/databases.ts +70 -39
  245. package/src/home/drives-deps.ts +54 -0
  246. package/src/home/follow-run.ts +146 -0
  247. package/src/home/global-context.ts +26 -22
  248. package/src/home/global-units.ts +3 -1
  249. package/src/home/gui-app/ShipkitGui.swift +1595 -17
  250. package/src/home/gui-app.ts +12 -16
  251. package/src/home/handoff.ts +5 -3
  252. package/src/home/handover.ts +2 -10
  253. package/src/home/home-launchd.ts +0 -6
  254. package/src/home/home-paths.ts +20 -7
  255. package/src/home/home-routes.ts +92 -29
  256. package/src/home/home-state.ts +2 -14
  257. package/src/home/inbox-shape.ts +15 -16
  258. package/src/home/inbox.ts +1 -1
  259. package/src/home/machine-host.ts +3 -17
  260. package/src/home/machine-repair.ts +102 -103
  261. package/src/home/machine-stores.ts +8 -7
  262. package/src/home/owner-switch-route.ts +33 -0
  263. package/src/home/page-build.ts +20 -4
  264. package/src/home/page-files.ts +79 -0
  265. package/src/home/pm-switch.ts +10 -0
  266. package/src/home/pm.ts +13 -1
  267. package/src/home/process-apps.ts +15 -3
  268. package/src/home/push-sources.ts +17 -5
  269. package/src/home/resume.ts +7 -19
  270. package/src/home/run-daemon.ts +63 -7
  271. package/src/home/run-pm.ts +3 -3
  272. package/src/home/secrets-context.ts +119 -0
  273. package/src/home/serve-web.ts +12 -7
  274. package/src/home/shipkit-mark.ts +26 -0
  275. package/src/home/space-page.ts +3 -2
  276. package/src/home/space-route.ts +3 -10
  277. package/src/home/supervise.ts +5 -16
  278. package/src/home/vault-page.ts +39 -18
  279. package/src/home/vault-reveal.ts +2 -1
  280. package/src/home/web-places.ts +5 -3
  281. package/src/hooks/commit-run.ts +420 -0
  282. package/src/hooks/git-hook.ts +49 -0
  283. package/src/hooks/held-calls.ts +104 -0
  284. package/src/hooks/hook-config.ts +103 -0
  285. package/src/hooks/hook-gates.ts +15 -9
  286. package/src/hooks/leak-guard.ts +16 -15
  287. package/src/hooks/one-way-in-guard.ts +12 -3
  288. package/src/hooks/pre-commit-checks.ts +64 -0
  289. package/src/hooks/root-identity.ts +15 -18
  290. package/src/hooks/run-hooks.ts +123 -301
  291. package/src/hooks/shared-file.ts +18 -15
  292. package/src/hooks/shell-writes.ts +6 -100
  293. package/src/hooks/staged.ts +245 -18
  294. package/src/hooks/write-log.ts +122 -28
  295. package/src/house/project-gutter.ts +32 -8
  296. package/src/hq/backup-targets.ts +74 -0
  297. package/src/hq/daemon-db.ts +177 -0
  298. package/src/hq/door-route.ts +5 -5
  299. package/src/hq/door.ts +16 -15
  300. package/src/hq/files-send.ts +23 -17
  301. package/src/hq/follow-fact.ts +66 -0
  302. package/src/hq/forgotten-log.ts +3 -1
  303. package/src/hq/history-check.ts +9 -0
  304. package/src/hq/history-send.ts +6 -22
  305. package/src/hq/holds-shape.ts +42 -0
  306. package/src/hq/hq-db.ts +17 -26
  307. package/src/hq/hq-holds.ts +181 -0
  308. package/src/hq/hq-local.ts +65 -47
  309. package/src/hq/hq-role.ts +150 -0
  310. package/src/hq/hq-routes.ts +15 -3
  311. package/src/hq/hq-store.ts +28 -10
  312. package/src/hq/item-direct.ts +55 -0
  313. package/src/hq/item-fill.ts +37 -0
  314. package/src/hq/kinds/index.ts +2 -1
  315. package/src/hq/kinds/item-gone.ts +18 -13
  316. package/src/hq/kinds/item-msg.ts +19 -10
  317. package/src/hq/kinds/item.ts +22 -19
  318. package/src/hq/kinds/kind.ts +9 -0
  319. package/src/hq/kinds/presence.ts +21 -3
  320. package/src/hq/kinds/prompt.ts +1 -0
  321. package/src/hq/kinds/reflection.ts +1 -0
  322. package/src/hq/kinds/report.ts +6 -2
  323. package/src/hq/kinds/thread-event.ts +105 -0
  324. package/src/hq/lead-order.ts +5 -5
  325. package/src/hq/machine-key.ts +10 -3
  326. package/src/hq/machine-notes.ts +3 -2
  327. package/src/hq/outbox.ts +2 -153
  328. package/src/hq/owner-switch.ts +61 -0
  329. package/src/hq/replica.ts +165 -18
  330. package/src/hq/report-facts.ts +26 -3
  331. package/src/hq/report.ts +26 -6
  332. package/src/hq/switch.ts +20 -60
  333. package/src/hq/terminal-hop.ts +1 -1
  334. package/src/hq/thread-events.ts +91 -0
  335. package/src/hq/thread-sync.ts +34 -65
  336. package/src/hq/threads-words.ts +21 -0
  337. package/src/http/door-forward.ts +3 -3
  338. package/src/http/hop-names.ts +3 -3
  339. package/src/http/owner-word.ts +7 -2
  340. package/src/identities/collection.ts +2 -3
  341. package/src/identities/identities.ts +43 -6
  342. package/src/identities/machine.ts +16 -0
  343. package/src/init-repo.ts +12 -1
  344. package/src/ledger/check-stats.ts +6 -5
  345. package/src/ledger/db.ts +18 -7
  346. package/src/ledger/git-scan.ts +23 -9
  347. package/src/ledger/live-runs.ts +1 -12
  348. package/src/ledger/record-kept.ts +139 -42
  349. package/src/ledger/run-log.ts +23 -3
  350. package/src/ledger/slow-tests.ts +96 -0
  351. package/src/ledger/store.ts +3 -86
  352. package/src/ledger/suite-log.ts +8 -2
  353. package/src/media-store/backup/facts.ts +29 -0
  354. package/src/media-store/backup/keys.ts +1 -8
  355. package/src/media-store/backup/manifest.ts +6 -67
  356. package/src/media-store/backup/restore.ts +11 -9
  357. package/src/media-store/backup/retention.ts +14 -2
  358. package/src/media-store/backup/run.ts +6 -267
  359. package/src/media-store/backup/snapshot.ts +2 -38
  360. package/src/media-store/backup/sources.ts +21 -213
  361. package/src/media-store/backup/ssh-target.ts +74 -0
  362. package/src/media-store/backup/target-send.ts +138 -0
  363. package/src/media-store/copy/config.ts +5 -4
  364. package/src/media-store/copy/copy.ts +11 -6
  365. package/src/media-store/copy/proof.ts +17 -10
  366. package/src/media-store/copy/snapshot.ts +29 -22
  367. package/src/media-store/copy/store.ts +2 -10
  368. package/src/media-store/copy/stream.ts +7 -2
  369. package/src/media-store/daemon.ts +8 -5
  370. package/src/media-store/db.ts +11 -5
  371. package/src/media-store/forget-one.ts +15 -4
  372. package/src/media-store/forget.ts +1 -80
  373. package/src/media-store/hq-find.ts +1 -3
  374. package/src/media-store/hq-send.ts +4 -5
  375. package/src/orchestrator/brief.md +1 -1
  376. package/src/orchestrator/guards.ts +0 -4
  377. package/src/orchestrator/lead-shape.ts +5 -4
  378. package/src/orchestrator/now.ts +1 -1
  379. package/src/orchestrator/places-look.ts +45 -17
  380. package/src/orchestrator/places-shape.ts +17 -2
  381. package/src/orchestrator/places.ts +1 -1
  382. package/src/orchestrator/presence.ts +17 -7
  383. package/src/orchestrator/role-shape.ts +12 -21
  384. package/src/orchestrator/role.ts +7 -58
  385. package/src/orchestrator/routes.ts +26 -17
  386. package/src/orchestrator/sessions-shape.ts +48 -3
  387. package/src/orchestrator/sessions.ts +5 -8
  388. package/src/orchestrator/start.ts +3 -10
  389. package/src/orchestrator/started.ts +1 -10
  390. package/src/orchestrator/talk-key.ts +20 -0
  391. package/src/orchestrator/unheard.ts +2 -2
  392. package/src/recordings/edit.ts +3 -3
  393. package/src/recordings/marks-draw.ts +17 -6
  394. package/src/recordings/marks.ts +120 -9
  395. package/src/recordings/recorder-app/Editor.swift +6 -0
  396. package/src/recordings/recorder-app/main.swift +3 -0
  397. package/src/reflections/reflection-close.ts +2 -1
  398. package/src/reflections/reflections-queue.ts +5 -9
  399. package/src/release/notes.ts +1 -1
  400. package/src/release/public-clean.ts +102 -17
  401. package/src/release/run-bump.ts +11 -0
  402. package/src/release/run-release.ts +4 -0
  403. package/src/releases/from-thread.ts +3 -3
  404. package/src/releases/model.ts +186 -36
  405. package/src/releases/store.ts +13 -3
  406. package/src/releases/validate.ts +83 -0
  407. package/src/repo-config.ts +45 -68
  408. package/src/review/answer-kinds.ts +71 -2
  409. package/src/review/blocked-guard.ts +11 -0
  410. package/src/review/blocked-object.ts +298 -0
  411. package/src/review/cell-copy.ts +27 -0
  412. package/src/review/cells.ts +317 -219
  413. package/src/review/close.ts +39 -1
  414. package/src/review/doc-save.ts +3 -2
  415. package/src/review/draft-item.ts +1 -1
  416. package/src/review/events.ts +27 -11
  417. package/src/review/expect.ts +112 -0
  418. package/src/review/file-tags.ts +9 -0
  419. package/src/review/format.ts +160 -39
  420. package/src/review/glyphs.ts +1 -0
  421. package/src/review/gone.ts +10 -86
  422. package/src/review/hand-over.ts +3 -3
  423. package/src/review/heard.ts +1 -1
  424. package/src/review/holds-sync.ts +2 -1
  425. package/src/review/inbox-hook.ts +8 -5
  426. package/src/review/inbox-read.ts +96 -22
  427. package/src/review/instruction-guards.ts +68 -1
  428. package/src/review/instructions.ts +25 -2
  429. package/src/review/item-db.ts +124 -70
  430. package/src/review/item-hq.ts +119 -0
  431. package/src/review/item-rows.ts +95 -62
  432. package/src/review/kind-catalog.ts +5 -1
  433. package/src/review/kinds.ts +25 -12
  434. package/src/review/live-post.ts +20 -6
  435. package/src/review/live-view.ts +21 -1
  436. package/src/review/media-away.ts +35 -0
  437. package/src/review/media-kind.ts +1 -1
  438. package/src/review/mentions.ts +4 -8
  439. package/src/review/model.ts +254 -98
  440. package/src/review/move.ts +131 -474
  441. package/src/review/need-threads.ts +3 -2
  442. package/src/review/notes.ts +4 -4
  443. package/src/review/object-card.ts +11 -0
  444. package/src/review/object-read.ts +32 -8
  445. package/src/review/one-block.ts +1 -1
  446. package/src/review/owner-read.ts +1 -1
  447. package/src/review/parties.ts +16 -0
  448. package/src/review/phone-push.ts +15 -13
  449. package/src/review/previews-job.ts +49 -0
  450. package/src/review/previews.ts +79 -29
  451. package/src/review/push.ts +26 -42
  452. package/src/review/recap.ts +129 -0
  453. package/src/review/referring.ts +6 -3
  454. package/src/review/reflection-object.ts +28 -14
  455. package/src/review/refs.ts +143 -0
  456. package/src/review/reply-guards.ts +71 -0
  457. package/src/review/routes.ts +133 -47
  458. package/src/review/search-index.ts +6 -10
  459. package/src/review/search-job.ts +4 -6
  460. package/src/review/search-ocr.ts +1 -1
  461. package/src/review/secret-route.ts +14 -9
  462. package/src/review/settle.ts +0 -6
  463. package/src/review/snooze.ts +5 -3
  464. package/src/review/speaker.ts +68 -0
  465. package/src/review/start-title.ts +19 -0
  466. package/src/review/store-index.ts +1 -1
  467. package/src/review/store.ts +256 -614
  468. package/src/review/supersede.ts +3 -3
  469. package/src/review/take-back.ts +1 -2
  470. package/src/review/thread-code.ts +101 -0
  471. package/src/review/{wakes.ts → thread-events.ts} +97 -8
  472. package/src/review/thread-md.ts +148 -0
  473. package/src/review/thread-query.ts +67 -0
  474. package/src/review/thread-state.ts +798 -0
  475. package/src/review/threads.ts +58 -301
  476. package/src/review/traces.ts +121 -12
  477. package/src/review/trailer-item.ts +1 -1
  478. package/src/review/unit.ts +7 -9
  479. package/src/review/verdict-items.ts +10 -8
  480. package/src/review/view-layout.ts +28 -1
  481. package/src/review/watch-feed.ts +1 -2
  482. package/src/review/watchers.ts +1 -10
  483. package/src/review/working-guards.ts +38 -0
  484. package/src/rules/untrack-generated.ts +1 -15
  485. package/src/scaffold/starter-house.ts +85 -0
  486. package/src/secrets/about-words.ts +33 -0
  487. package/src/secrets/archive.ts +2 -2
  488. package/src/secrets/audit-run.ts +53 -0
  489. package/src/secrets/audit.ts +407 -0
  490. package/src/secrets/changed-mark.ts +15 -0
  491. package/src/secrets/clip.ts +29 -0
  492. package/src/secrets/held.ts +4 -4
  493. package/src/secrets/lapse.ts +3 -2
  494. package/src/secrets/list.ts +9 -4
  495. package/src/secrets/read.ts +5 -1
  496. package/src/secrets/ref-state.ts +18 -0
  497. package/src/secrets/registry-rows.ts +18 -0
  498. package/src/secrets/secret-ref.ts +42 -0
  499. package/src/secrets/token-siblings.ts +60 -0
  500. package/src/secrets/who-reads.ts +25 -20
  501. package/src/serve/frame-part.ts +2 -1
  502. package/src/serve/hub-app/activity-view.tsx +6 -6
  503. package/src/serve/hub-app/admin-view.tsx +7 -6
  504. package/src/serve/hub-app/advisor-app.tsx +80 -17
  505. package/src/serve/hub-app/advisor-face.tsx +27 -7
  506. package/src/serve/hub-app/advisor-host.ts +113 -21
  507. package/src/serve/hub-app/advisors-model.ts +243 -0
  508. package/src/serve/hub-app/advisors-rights.tsx +66 -0
  509. package/src/serve/hub-app/advisors-st.ts +433 -36
  510. package/src/serve/hub-app/advisors-view.tsx +333 -234
  511. package/src/serve/hub-app/advisors.css +134 -21
  512. package/src/serve/hub-app/app-bridge.ts +116 -6
  513. package/src/serve/hub-app/ask-steps.tsx +6 -3
  514. package/src/serve/hub-app/asks-page.tsx +1 -1
  515. package/src/serve/hub-app/auto-text.tsx +114 -19
  516. package/src/serve/hub-app/backups-st.ts +55 -0
  517. package/src/serve/hub-app/backups-view.tsx +115 -0
  518. package/src/serve/hub-app/backups.css +33 -0
  519. package/src/serve/hub-app/card-head.tsx +1 -1
  520. package/src/serve/hub-app/check-view.tsx +7 -15
  521. package/src/serve/hub-app/col-card.tsx +4 -4
  522. package/src/serve/hub-app/col-list-page.tsx +2 -1
  523. package/src/serve/hub-app/col-tables.ts +5 -4
  524. package/src/serve/hub-app/comfy-view.tsx +1 -1
  525. package/src/serve/hub-app/commands/commands-page.tsx +2 -2
  526. package/src/serve/hub-app/controls.css +34 -2
  527. package/src/serve/hub-app/cycle-button.tsx +2 -2
  528. package/src/serve/hub-app/database-st.ts +40 -11
  529. package/src/serve/hub-app/database-view.tsx +67 -3
  530. package/src/serve/hub-app/database.css +3 -0
  531. package/src/serve/hub-app/dock-view.tsx +1 -1
  532. package/src/serve/hub-app/drives-page.tsx +309 -0
  533. package/src/serve/hub-app/drives-st.ts +486 -0
  534. package/src/serve/hub-app/drives.css +122 -0
  535. package/src/serve/hub-app/editor/doc-editor.tsx +4 -3
  536. package/src/serve/hub-app/empty-section.tsx +1 -1
  537. package/src/serve/hub-app/entry-list.tsx +1 -1
  538. package/src/serve/hub-app/floating.tsx +0 -1
  539. package/src/serve/hub-app/frame-refusal.ts +13 -0
  540. package/src/serve/hub-app/geometry-view.tsx +3 -3
  541. package/src/serve/hub-app/git-view.tsx +3 -1
  542. package/src/serve/hub-app/hash-route.ts +12 -5
  543. package/src/serve/hub-app/header-bar.tsx +2 -1
  544. package/src/serve/hub-app/home-pages.ts +40 -0
  545. package/src/serve/hub-app/home-st.ts +8 -1
  546. package/src/serve/hub-app/home-strip.tsx +22 -20
  547. package/src/serve/hub-app/home.html +2 -1
  548. package/src/serve/hub-app/hub-app.tsx +16 -3
  549. package/src/serve/hub-app/hub.css +84 -10
  550. package/src/serve/hub-app/icons.tsx +9 -1
  551. package/src/serve/hub-app/identities-view.tsx +5 -4
  552. package/src/serve/hub-app/inbox-view.tsx +11 -12
  553. package/src/serve/hub-app/index.html +2 -1
  554. package/src/serve/hub-app/insights-view.tsx +8 -8
  555. package/src/serve/hub-app/keys.ts +31 -11
  556. package/src/serve/hub-app/layout-st.ts +4 -1
  557. package/src/serve/hub-app/lightbox-zoom.css +29 -19
  558. package/src/serve/hub-app/list-filter.tsx +46 -5
  559. package/src/serve/hub-app/live-socket.ts +12 -6
  560. package/src/serve/hub-app/live-sources.ts +138 -67
  561. package/src/serve/hub-app/machine-groups.ts +87 -0
  562. package/src/serve/hub-app/machines-st.ts +100 -3
  563. package/src/serve/hub-app/machines-view.tsx +50 -3
  564. package/src/serve/hub-app/machines.css +22 -0
  565. package/src/serve/hub-app/main-panel.css +16 -10
  566. package/src/serve/hub-app/main-panel.tsx +8 -9
  567. package/src/serve/hub-app/markdown.css +12 -2
  568. package/src/serve/hub-app/md.ts +60 -18
  569. package/src/serve/hub-app/media-view.tsx +21 -12
  570. package/src/serve/hub-app/messages/messages-page.tsx +15 -6
  571. package/src/serve/hub-app/new-thread.tsx +6 -3
  572. package/src/serve/hub-app/orchestrator-line.tsx +1 -1
  573. package/src/serve/hub-app/orchestrator-places.tsx +28 -2
  574. package/src/serve/hub-app/orchestrator.css +5 -0
  575. package/src/serve/hub-app/page-keys.ts +4 -1
  576. package/src/serve/hub-app/pages-frames.tsx +2 -1
  577. package/src/serve/hub-app/palette-st.ts +285 -60
  578. package/src/serve/hub-app/palette-view.tsx +96 -18
  579. package/src/serve/hub-app/pane-boundary.tsx +3 -2
  580. package/src/serve/hub-app/panel-head.tsx +1 -1
  581. package/src/serve/hub-app/panel-repo.ts +0 -9
  582. package/src/serve/hub-app/panel-source.ts +16 -5
  583. package/src/serve/hub-app/panel-tint.ts +3 -18
  584. package/src/serve/hub-app/panel-walk.ts +1 -1
  585. package/src/serve/hub-app/pic.tsx +54 -0
  586. package/src/serve/hub-app/pick-kinds.ts +101 -0
  587. package/src/serve/hub-app/places-svc.ts +44 -10
  588. package/src/serve/hub-app/plan-view.tsx +2 -2
  589. package/src/serve/hub-app/planned-view.tsx +6 -5
  590. package/src/serve/hub-app/polled.ts +33 -8
  591. package/src/serve/hub-app/presence-st.ts +9 -1
  592. package/src/serve/hub-app/processes-view.tsx +16 -10
  593. package/src/serve/hub-app/project-bar.tsx +85 -29
  594. package/src/serve/hub-app/project-list.tsx +7 -19
  595. package/src/serve/hub-app/projects-svc.ts +50 -20
  596. package/src/serve/hub-app/rail-groups.ts +1 -0
  597. package/src/serve/hub-app/recordings-st.ts +23 -2
  598. package/src/serve/hub-app/recordings-view.tsx +94 -36
  599. package/src/serve/hub-app/ref-list-slot.ts +10 -0
  600. package/src/serve/hub-app/ref-pill.ts +58 -0
  601. package/src/serve/hub-app/reflections-page.tsx +3 -3
  602. package/src/serve/hub-app/releases/releases-page.tsx +6 -6
  603. package/src/serve/hub-app/repo-mark.tsx +29 -0
  604. package/src/serve/hub-app/repo-sections.ts +16 -9
  605. package/src/serve/hub-app/repo-st.ts +68 -16
  606. package/src/serve/hub-app/review/advisor-add.tsx +155 -0
  607. package/src/serve/hub-app/review/advisor-bar.tsx +92 -22
  608. package/src/serve/hub-app/review/advisor-invite.tsx +66 -0
  609. package/src/serve/hub-app/review/ask-proof.tsx +4 -3
  610. package/src/serve/hub-app/review/attach-view.tsx +7 -6
  611. package/src/serve/hub-app/review/box-view.ts +35 -18
  612. package/src/serve/hub-app/review/box-zoom.tsx +1 -1
  613. package/src/serve/hub-app/review/copy-button.tsx +29 -0
  614. package/src/serve/hub-app/review/diff-mode.ts +41 -0
  615. package/src/serve/hub-app/review/diff-view.tsx +92 -19
  616. package/src/serve/hub-app/review/doc-body.tsx +2 -2
  617. package/src/serve/hub-app/review/draft-body.tsx +4 -4
  618. package/src/serve/hub-app/review/group-block.tsx +8 -8
  619. package/src/serve/hub-app/review/heard-line.tsx +1 -1
  620. package/src/serve/hub-app/review/instructions-view.tsx +4 -17
  621. package/src/serve/hub-app/review/kind-states.tsx +14 -9
  622. package/src/serve/hub-app/review/kind-view.tsx +13 -19
  623. package/src/serve/hub-app/review/kit.tsx +19 -18
  624. package/src/serve/hub-app/review/lane-bar.tsx +4 -4
  625. package/src/serve/hub-app/review/lightbox.tsx +15 -11
  626. package/src/serve/hub-app/review/line-window.ts +55 -9
  627. package/src/serve/hub-app/review/live-bar-st.ts +2 -2
  628. package/src/serve/hub-app/review/live-bar.tsx +5 -2
  629. package/src/serve/hub-app/review/live-view.tsx +67 -11
  630. package/src/serve/hub-app/review/mention-st.ts +9 -38
  631. package/src/serve/hub-app/review/object-panel.tsx +58 -21
  632. package/src/serve/hub-app/review/outbox-st.ts +200 -0
  633. package/src/serve/hub-app/review/pano-view.tsx +2 -2
  634. package/src/serve/hub-app/review/phone-top.tsx +2 -1
  635. package/src/serve/hub-app/review/question-views.tsx +321 -62
  636. package/src/serve/hub-app/review/recap-bar.tsx +40 -0
  637. package/src/serve/hub-app/review/request-cell.tsx +48 -0
  638. package/src/serve/hub-app/review/review-cells.tsx +327 -112
  639. package/src/serve/hub-app/review/review-host.ts +11 -2
  640. package/src/serve/hub-app/review/review-kit.ts +38 -16
  641. package/src/serve/hub-app/review/review-list.tsx +63 -110
  642. package/src/serve/hub-app/review/review-page.tsx +6 -5
  643. package/src/serve/hub-app/review/review-st.ts +114 -70
  644. package/src/serve/hub-app/review/review-thread.tsx +378 -204
  645. package/src/serve/hub-app/review/review-views.tsx +205 -111
  646. package/src/serve/hub-app/review/secret-facts.ts +2 -1
  647. package/src/serve/hub-app/review/share-lines.tsx +40 -0
  648. package/src/serve/hub-app/review/start-st.ts +134 -0
  649. package/src/serve/hub-app/review/start-thread.tsx +104 -0
  650. package/src/serve/hub-app/review/superseded-runs.ts +24 -5
  651. package/src/serve/hub-app/review/thread-close.tsx +11 -8
  652. package/src/serve/hub-app/review/thread-control.tsx +5 -4
  653. package/src/serve/hub-app/review/thread-st.ts +591 -206
  654. package/src/serve/hub-app/review/thread-views.ts +3 -2
  655. package/src/serve/hub-app/review/tone-bar.tsx +126 -0
  656. package/src/serve/hub-app/review/tones.ts +35 -0
  657. package/src/serve/hub-app/review/trailer-body.tsx +8 -8
  658. package/src/serve/hub-app/review/trailer-page.tsx +33 -33
  659. package/src/serve/hub-app/review/trailer-st.ts +3 -2
  660. package/src/serve/hub-app/review/trailer-voices-st.ts +3 -2
  661. package/src/serve/hub-app/review/trailer-voices.tsx +10 -10
  662. package/src/serve/hub-app/review/zoom-still.tsx +60 -0
  663. package/src/serve/hub-app/review.css +320 -123
  664. package/src/serve/hub-app/row-acts.tsx +2 -0
  665. package/src/serve/hub-app/row-face.tsx +0 -1
  666. package/src/serve/hub-app/run-page.tsx +236 -0
  667. package/src/serve/hub-app/running-rows.tsx +2 -2
  668. package/src/serve/hub-app/search-view.tsx +2 -2
  669. package/src/serve/hub-app/secret-cli.tsx +32 -0
  670. package/src/serve/hub-app/secret-readable.tsx +59 -0
  671. package/src/serve/hub-app/secret-refs.ts +173 -0
  672. package/src/serve/hub-app/secrets-page.tsx +2 -2
  673. package/src/serve/hub-app/section-head.tsx +3 -1
  674. package/src/serve/hub-app/seen-rows.ts +72 -0
  675. package/src/serve/hub-app/shared-faces.tsx +32 -0
  676. package/src/serve/hub-app/side-frame-view.tsx +115 -0
  677. package/src/serve/hub-app/side-frame.ts +120 -0
  678. package/src/serve/hub-app/site/site-part.tsx +7 -7
  679. package/src/serve/hub-app/social/calendar.tsx +1 -1
  680. package/src/serve/hub-app/social/comms-page.tsx +3 -3
  681. package/src/serve/hub-app/social/copy-forms.ts +31 -0
  682. package/src/serve/hub-app/social/kit.tsx +42 -23
  683. package/src/serve/hub-app/social/post-card.tsx +5 -5
  684. package/src/serve/hub-app/social/post-page.tsx +2 -2
  685. package/src/serve/hub-app/social/social-model.ts +0 -4
  686. package/src/serve/hub-app/social/social-page.tsx +31 -12
  687. package/src/serve/hub-app/social/social-st.ts +8 -2
  688. package/src/serve/hub-app/social/stage-popup.tsx +6 -6
  689. package/src/serve/hub-app/social.css +7 -1
  690. package/src/serve/hub-app/source-acts.ts +2 -1
  691. package/src/serve/hub-app/source-page.tsx +2 -0
  692. package/src/serve/hub-app/space-view.tsx +3 -3
  693. package/src/serve/hub-app/stores/stores-page.tsx +20 -19
  694. package/src/serve/hub-app/terminal-gone.tsx +41 -0
  695. package/src/serve/hub-app/terminal-history-st.ts +3 -0
  696. package/src/serve/hub-app/terminal-list-st.ts +27 -3
  697. package/src/serve/hub-app/terminal-pages.tsx +50 -10
  698. package/src/serve/hub-app/terminal-panel.tsx +3 -3
  699. package/src/serve/hub-app/terminal-picture.ts +78 -0
  700. package/src/serve/hub-app/terminal-sources.tsx +320 -49
  701. package/src/serve/hub-app/terminal-st.ts +57 -2
  702. package/src/serve/hub-app/terminal-tab.tsx +2 -1
  703. package/src/serve/hub-app/terminal.css +5 -0
  704. package/src/serve/hub-app/test-view.tsx +2 -2
  705. package/src/serve/hub-app/tests-view.tsx +3 -3
  706. package/src/serve/hub-app/thread-row.tsx +15 -6
  707. package/src/serve/hub-app/time-charts.tsx +3 -2
  708. package/src/serve/hub-app/time-pages.tsx +3 -2
  709. package/src/serve/hub-app/time-view.tsx +6 -5
  710. package/src/serve/hub-app/timeline-chart.tsx +1 -1
  711. package/src/serve/hub-app/timeline-view.tsx +12 -4
  712. package/src/serve/hub-app/tree-build.ts +3 -7
  713. package/src/serve/hub-app/url-faces.ts +3 -4
  714. package/src/serve/hub-app/url-forms.tsx +112 -20
  715. package/src/serve/hub-app/url-needs.ts +31 -0
  716. package/src/serve/hub-app/urls-svc.ts +163 -25
  717. package/src/serve/hub-app/urls-view.tsx +76 -75
  718. package/src/serve/hub-app/urls.css +62 -5
  719. package/src/serve/hub-app/vault-view.tsx +13 -13
  720. package/src/serve/hub-app/veille/veille-page.tsx +12 -11
  721. package/src/serve/hub-app/view-layout.css +13 -1
  722. package/src/serve/hub-app/when-view.tsx +2 -2
  723. package/src/serve/hub-app/wikis-view.tsx +6 -3
  724. package/src/serve/hub-app/word-refs.ts +12 -0
  725. package/src/serve/hub-app/words.tsx +25 -8
  726. package/src/serve/hub-runtime.ts +7 -37
  727. package/src/serve/picture-types.ts +10 -0
  728. package/src/serve/project-gutter-route.ts +24 -15
  729. package/src/serve/read-thread.ts +49 -12
  730. package/src/serve/read-worker.ts +16 -1
  731. package/src/serve/record-pages.ts +46 -0
  732. package/src/serve/secret-ref-routes.ts +71 -0
  733. package/src/serve/serve-hub.ts +28 -3
  734. package/src/serve/terminal-claudes.ts +44 -7
  735. package/src/serve/terminal-guard.ts +5 -1
  736. package/src/serve/terminal-host.ts +6 -2
  737. package/src/serve/terminal-paste.ts +49 -0
  738. package/src/serve/terminal-record.ts +8 -2
  739. package/src/serve/terminal-route.ts +19 -8
  740. package/src/serve/tracked-watch.ts +14 -14
  741. package/src/setup-house.ts +333 -0
  742. package/src/shipkit-files.ts +15 -4
  743. package/src/shipkit.ts +1 -6
  744. package/src/shot/film-box.ts +1 -29
  745. package/src/social/discord-layout.ts +1 -1
  746. package/src/social/drafts.ts +1 -1
  747. package/src/social/kind-pages.ts +11 -5
  748. package/src/social/kinds.ts +6 -29
  749. package/src/social/load.ts +2 -2
  750. package/src/social/media-limit.ts +18 -8
  751. package/src/social/media-of.ts +5 -5
  752. package/src/social/post-object.ts +3 -2
  753. package/src/social/publish/discord.ts +1 -1
  754. package/src/social/release-stage.ts +1 -1
  755. package/src/social/routes.ts +6 -3
  756. package/src/social/stage.ts +2 -2
  757. package/src/start-repo.ts +5 -0
  758. package/src/stores/model.ts +4 -0
  759. package/src/stores/routes.ts +11 -3
  760. package/src/suite/judge-suites.ts +67 -51
  761. package/src/suite/red-alone.ts +105 -0
  762. package/src/suite/runner-shapes.ts +2 -2
  763. package/src/suite/suite-cli.ts +88 -34
  764. package/src/suite/test-units.ts +2 -1
  765. package/src/trailer/titles.ts +2 -2
  766. package/src/urls/added.ts +34 -15
  767. package/src/urls/fill.ts +127 -0
  768. package/src/urls/frame.ts +39 -0
  769. package/src/urls/places.ts +18 -13
  770. package/src/urls/routes.ts +30 -10
  771. package/src/urls/rows.ts +98 -23
  772. package/src/urls/totp.ts +121 -0
  773. package/src/urls/unit.ts +95 -36
  774. package/src/urls/write-routes.ts +141 -25
  775. package/src/vault/vault-config.ts +2 -2
  776. package/src/vault/vault-import.ts +2 -9
  777. package/src/vault/vault-init.ts +1 -4
  778. package/src/vault/vault-restore.ts +1 -9
  779. package/src/veille/chrome.ts +8 -18
  780. package/src/veille/identity.ts +6 -5
  781. package/src/wiki/graph-page.ts +41 -39
  782. package/src/wiki/graph-positions.ts +13 -3
  783. package/src/wiki/graph-sim.ts +77 -0
  784. package/src/wiki/run-wiki.ts +12 -1
  785. package/src/advisors/door.ts +0 -59
  786. package/src/advisors/edge/certs.ts +0 -20
  787. package/src/advisors/edge/jwt.ts +0 -76
  788. package/src/advisors/edge/worker.ts +0 -52
  789. package/src/advisors/r2.ts +0 -46
  790. package/src/checks/SK016-legacy-check-shapes.check.ts +0 -189
  791. package/src/checks/SK029-explicit-check-files.check.ts +0 -112
  792. package/src/checks/SK048-one-local-file.check.ts +0 -36
  793. package/src/cli/channel-run.ts +0 -17
  794. package/src/cli/cmd_Channel.ts +0 -43
  795. package/src/core/config-rewrite.ts +0 -111
  796. package/src/core/legacy-shapes.ts +0 -263
  797. package/src/core/migrate-layout.ts +0 -638
  798. package/src/core/port-check-cli.ts +0 -52
  799. package/src/core/port-check-file.ts +0 -295
  800. package/src/core/port-check-files.ts +0 -31
  801. package/src/gate/discover-legacy-checks.ts +0 -26
  802. package/src/home/home-move.ts +0 -527
  803. package/src/home/machine-fold.ts +0 -818
  804. package/src/media-store/backup/daemon.ts +0 -205
  805. package/src/media-store/backup/kept.ts +0 -241
  806. package/src/media-store/backup/prune.ts +0 -362
  807. package/src/media-store/backup/secret.ts +0 -88
  808. package/src/media-store/backup/thread-copy.ts +0 -343
  809. package/src/media-store/backup/watch.ts +0 -110
  810. package/src/orchestrator/channel-declare.ts +0 -58
  811. package/src/orchestrator/channel.ts +0 -226
  812. package/src/review/band.ts +0 -145
  813. package/src/review/role.ts +0 -48
  814. package/src/review/thread-fold.ts +0 -64
  815. package/src/review/wait.ts +0 -91
  816. package/src/rules/rule.ts +0 -43
  817. package/src/serve/hub-app/panel-tint.css +0 -6
  818. package/src/serve/hub-app/review/dock.tsx +0 -119
  819. package/src/serve/hub-app/review/faces.tsx +0 -18
  820. package/src/serve/hub-app/review/item-verdict.tsx +0 -111
  821. package/src/serve/hub-app/review/review-board.tsx +0 -48
@@ -17,6 +17,7 @@
17
17
  // its repo's count alone, and stays quiet: both as their page posts them
18
18
  // (`shipkit` message handler, serve/hub-app/app-bridge.ts).
19
19
  import AppKit
20
+ import CryptoKit
20
21
  import UserNotifications
21
22
  import WebKit
22
23
 
@@ -317,6 +318,50 @@ final class Web: WKWebView {
317
318
  if let action = forward.action { NSApp.sendAction(action, to: forward.target, from: sender) }
318
319
  DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.tabNext = false }
319
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")
320
365
  }
321
366
 
322
367
  /** the login chips a page's tab note names (serve/hub-app/app-bridge.ts TabChips): the url's id and its logins'
@@ -443,8 +488,14 @@ final class Pane: NSView, NSSearchFieldDelegate {
443
488
  override func layout() {
444
489
  super.layout()
445
490
  let top = isFindBarVisible ? Pane.barHeight : 0
446
- bar.frame = NSRect(x: 0, y: 0, width: bounds.width, height: Pane.barHeight)
447
- 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
+ }
448
499
  mark.frame = NSRect(x: bounds.width - 12, y: bounds.height - 12, width: 6, height: 6)
449
500
  }
450
501
 
@@ -500,6 +551,820 @@ final class Pane: NSView, NSSearchFieldDelegate {
500
551
  }
501
552
  return false
502
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)) }
596
+ }
597
+
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
+ }
603
+
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()
688
+ }
689
+
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
698
+ }
699
+
700
+ override func mouseUp(with e: NSEvent) {
701
+ guard let pane else { return }
702
+ SidePanel.keep(pane.sideSpan())
703
+ }
704
+ }
705
+
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
+ }
716
+
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()
752
+ }
753
+
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)?)
757
+
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()
774
+ }
775
+
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)
806
+ }
807
+ required init?(coder: NSCoder) { fatalError("not from a nib") }
808
+
809
+ @objc func pressed() { onAct?() }
810
+
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()
816
+ }
817
+
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)
823
+ }
824
+ }
825
+
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] = []
839
+
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
+ """
855
+
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
871
+ }
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
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
+ """
934
+
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) }
948
+ }
949
+
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
989
+ let config = WKWebViewConfiguration()
990
+ config.websiteDataStore = store
991
+ config.preferences.setValue(true, forKey: "developerExtrasEnabled")
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
+ }
503
1368
  }
504
1369
 
505
1370
  final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate, NSWindowDelegate, NSMenuItemValidation, WKScriptMessageHandler, UNUserNotificationCenterDelegate {
@@ -513,6 +1378,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
513
1378
 
514
1379
  func applicationDidFinishLaunching(_ note: Notification) {
515
1380
  if CommandLine.arguments.contains("--self-test-find") { return selfTestFind() }
1381
+ if CommandLine.arguments.contains("--self-test-paste") { return selfTestPaste() }
516
1382
  if CommandLine.arguments.contains("--self-test-mic") { return selfTestMic() }
517
1383
  if CommandLine.arguments.contains("--self-test-panels") { return selfTestPanels() }
518
1384
  if CommandLine.arguments.contains("--self-test-download") { return selfTestDownload() }
@@ -524,6 +1390,9 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
524
1390
  if CommandLine.arguments.contains("--self-test-address") { return selfTestAddress() }
525
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))) }
526
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) }
527
1396
  buildMenu()
528
1397
  watchBuild()
529
1398
  // the system asks the owner once; refused, the badge still counts and each notification says why it did not show
@@ -538,6 +1407,11 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
538
1407
  keep(home: startURL)
539
1408
  }
540
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
+ }
541
1415
  // an open event may deliver the url right after launch: wait for it
542
1416
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
543
1417
  if !self.opened {
@@ -931,6 +1805,9 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
931
1805
  if selfTesting { config.websiteDataStore = .nonPersistent() }
932
1806
  if hasBadge && bridge {
933
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))
934
1811
  // the home's badge poll keeps its pace while its window is hidden or covered; a project app's page is throttled
935
1812
  // as any background page is: its badge moves at that slower pace
936
1813
  if isShipkit, #available(macOS 14.0, *) { config.preferences.inactiveSchedulingPolicy = .none }
@@ -970,7 +1847,8 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
970
1847
  /** a window's web view, not loaded yet. `view`: what a page kept of its scrolls before it asked for a fresh view
971
1848
  * (hub-app/page-reload.ts), put back where that page reads it, before its first script */
972
1849
  func makeWeb(_ url: URL, view: String? = nil) -> Web {
973
- let config = webConfig(bridge: !tabbed || isHub(url))
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))
974
1852
  // parsed and written again: the page's words never reach the script as they came
975
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) {
976
1854
  config.userContentController.addUserScript(WKUserScript(source: "try { sessionStorage.setItem('sk-view', JSON.stringify(\(json))) } catch (e) {}", injectionTime: .atDocumentStart, forMainFrameOnly: true))
@@ -2048,6 +2926,536 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
2048
2926
  run()
2049
2927
  }
2050
2928
 
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)
2956
+ }
2957
+
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()
3129
+ }
3130
+
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() {
3140
+ buildMenu()
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)") }
3145
+ }
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)
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)
3224
+ }
3225
+ }
3226
+ }
3227
+
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)") }
3244
+ }
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
+ }
3453
+ }
3454
+ }
3455
+ }
3456
+ run()
3457
+ }
3458
+
2051
3459
  // `--self-test-find`: a window that is never shown, on a page holding a word twice,
2052
3460
  // the find bar opened, a word on the page searched, then one that is not;
2053
3461
  // what happened printed, exit 0 only when the bar shows and finds
@@ -2075,6 +3483,64 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
2075
3483
  web.loadHTMLString("<p>one needle, two needle</p>", baseURL: nil)
2076
3484
  }
2077
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
+
2078
3544
  // `--self-test-mic`: a window's own web view on a page of the machine, then on a page of another host, each
2079
3545
  // printing whether the page can reach the microphone api (`getUserMedia`); no capture is asked, so no prompt
2080
3546
  func selfTestMic() {
@@ -2225,12 +3691,93 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
2225
3691
  // « new version: relaunch » button in its title bar, and only his click quits it
2226
3692
  var stale = false
2227
3693
  func watchBuild() {
2228
- Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { _ in
2229
- guard !self.stale, let now = stampOnDisk(), let was = launchedStamp, now != was else { return }
2230
- self.stale = true
2231
- if self.windows.isEmpty { return self.relaunch(nil) }
2232
- for w in self.windows { self.offerRelaunch(w) }
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)])
2233
3779
  }
3780
+ showTabBars()
2234
3781
  }
2235
3782
 
2236
3783
  func offerRelaunch(_ w: NSWindow) {
@@ -2319,7 +3866,8 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
2319
3866
  }.resume()
2320
3867
  }
2321
3868
 
2322
- /** the board a chip copies into: the owner's, and one of the run's own in a self test, which never reaches his */
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 */
2323
3871
  lazy var board: NSPasteboard = selfTesting ? NSPasteboard(name: NSPasteboard.Name("dev.shipkit.self-test.\(ProcessInfo.processInfo.processIdentifier)")) : .general
2324
3872
  /** how long a copied value stays on the board */
2325
3873
  var clearAfter: TimeInterval = 90
@@ -2345,11 +3893,18 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
2345
3893
  if board.changeCount == at { board.clearContents() }
2346
3894
  }
2347
3895
 
2348
- // a quit before the clock: the value leaves with the app
2349
- func applicationWillTerminate(_ note: Notification) { clearCopy() }
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
+ }
2350
3902
 
2351
- /** a fresh copy of this bundle once this one has quit: the home app with no window comes back with none */
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 */
2352
3905
  @objc func relaunch(_ sender: Any?) {
3906
+ keepWindows()
3907
+ if selfTesting { relaunches += 1; return }
2353
3908
  let back = isShipkit && windows.isEmpty ? " --args --background" : ""
2354
3909
  let path = Bundle.main.bundlePath.replacingOccurrences(of: "'", with: "'\\''")
2355
3910
  let p = Process()
@@ -2403,7 +3958,8 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
2403
3958
  if out { openOutside(url) }
2404
3959
  return decisionHandler(out ? .cancel : .allow)
2405
3960
  }
2406
- guard let url = action.request.url, action.navigationType == .linkActivated || action.targetFrame == nil, leaves(url) else { return decisionHandler(.allow) }
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) }
2407
3963
  openOutside(url)
2408
3964
  decisionHandler(.cancel)
2409
3965
  }
@@ -2568,10 +4124,16 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
2568
4124
 
2569
4125
  func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
2570
4126
  guard message.frameInfo.isMainFrame, let body = message.body as? [String: Any] else { return }
2571
- // a project app hears its hub alone: a page of another site that reached a hub tab posts nothing
4127
+ // the home app and a project app hear their hub alone: a page of another site that reached a hub tab posts nothing
2572
4128
  let from = message.frameInfo.securityOrigin
2573
- if tabbed && !(from.host == startURL.host && from.port == (startURL.port ?? 0)) { return }
4129
+ if hubApp && !(from.host == startURL.host && from.port == (startURL.port ?? 0)) { return }
2574
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
+ }
2575
4137
  // the name of the tab the page asks next, and what command with t opens for the entry it shows
2576
4138
  if let name = body["tabName"] as? String, let url = (body["url"] as? String).flatMap({ URL(string: $0) }) {
2577
4139
  tabNames[tabKey(url)] = String(name.prefix(120))
@@ -2791,15 +4353,31 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
2791
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)
2792
4354
  }
2793
4355
 
2794
- // 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
2795
4359
  func webView(_ web: WKWebView, createWebViewWith config: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
2796
4360
  if let url = action.request.url {
2797
4361
  // a script's window.open comes here with no policy asked first: a project app sends it down its road too
2798
- if tabbed { asksWindow(url, from: web) } else if leaves(url) { openOutside(url) } else { open(url) }
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) }
2799
4363
  }
2800
4364
  return nil
2801
4365
  }
2802
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
+
2803
4381
  // alert, confirm and prompt: without these WebKit answers each one at once
2804
4382
  // (no panel, confirm false, prompt null), so a page's dialogs do nothing.
2805
4383
  // WebKit throws when a handler is dropped or called twice: `panel` calls