gentle-pi 4.7.0 → 4.8.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 (365) hide show
  1. package/README.md +55 -44
  2. package/assets/agents/gentle-ai-explore.md +3 -3
  3. package/assets/agents/gentle-ai-verify.md +20 -6
  4. package/assets/agents/gentle-ai-worker.md +6 -6
  5. package/assets/agents/jd-judge-a.md +1 -3
  6. package/assets/agents/jd-judge-b.md +1 -3
  7. package/assets/agents/review-readability.md +1 -5
  8. package/assets/agents/review-reliability.md +1 -5
  9. package/assets/agents/review-resilience.md +1 -5
  10. package/assets/agents/review-risk.md +1 -5
  11. package/assets/design-canvas/canvas-api.js +45 -0
  12. package/assets/design-canvas/canvas-boards.js +456 -0
  13. package/assets/design-canvas/canvas-boot.js +217 -0
  14. package/assets/design-canvas/canvas-checks.js +491 -0
  15. package/assets/design-canvas/canvas-comments.js +315 -0
  16. package/assets/design-canvas/canvas-compare.js +159 -0
  17. package/assets/design-canvas/canvas-events.js +75 -0
  18. package/assets/design-canvas/canvas-export.js +393 -0
  19. package/assets/design-canvas/canvas-focus.js +203 -0
  20. package/assets/design-canvas/canvas-handoffs.js +150 -0
  21. package/assets/design-canvas/canvas-i18n-es.js +392 -0
  22. package/assets/design-canvas/canvas-i18n.js +108 -0
  23. package/assets/design-canvas/canvas-layout.js +526 -0
  24. package/assets/design-canvas/canvas-menu.js +213 -0
  25. package/assets/design-canvas/canvas-messages.js +86 -0
  26. package/assets/design-canvas/canvas-minimap.js +163 -0
  27. package/assets/design-canvas/canvas-parts.js +401 -0
  28. package/assets/design-canvas/canvas-popover.js +234 -0
  29. package/assets/design-canvas/canvas-rail.js +348 -0
  30. package/assets/design-canvas/canvas-sizes.js +524 -0
  31. package/assets/design-canvas/canvas-store.js +164 -0
  32. package/assets/design-canvas/canvas-tokens.js +674 -0
  33. package/assets/design-canvas/canvas-ui.js +24 -0
  34. package/assets/design-canvas/canvas-view.js +184 -0
  35. package/assets/design-canvas/canvas.css +746 -15
  36. package/assets/design-canvas/canvas.js +2 -1506
  37. package/assets/design-canvas/index.html +117 -36
  38. package/assets/design-canvas/inspector.js +546 -16
  39. package/assets/install-wizard/wizard.js +5 -1
  40. package/assets/migrations/agent-body-history.json +24 -0
  41. package/assets/orchestrator-delegation-reference.md +8 -14
  42. package/assets/orchestrator-delegation.md +4 -4
  43. package/assets/orchestrator-full-delegation-card.md +4 -5
  44. package/assets/orchestrator-full-delegation.md +8 -8
  45. package/assets/orchestrator-memory.md +2 -2
  46. package/assets/orchestrator-prompts.md +1 -1
  47. package/assets/orchestrator-quota-recovery.md +5 -0
  48. package/assets/orchestrator-skills.md +13 -12
  49. package/assets/orchestrator-tracking.md +10 -14
  50. package/assets/orchestrator-verification.md +10 -8
  51. package/assets/orchestrator-writer.md +4 -4
  52. package/assets/orchestrator.md +18 -22
  53. package/bin/gentle-shell.mjs +128 -9
  54. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  55. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
  56. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
  60. package/docs/assets/brand/sponsor-banner.svg +60 -0
  61. package/docs/bundled-install.md +14 -6
  62. package/docs/delegated-verification.md +18 -2
  63. package/docs/desktop-rpc.md +1253 -0
  64. package/docs/gentle-agents-activity.md +26 -0
  65. package/docs/gentle-shell.md +39 -16
  66. package/docs/install-wizard.md +30 -21
  67. package/docs/odd-preparation-continuity.md +24 -0
  68. package/docs/permission-modes.md +9 -1
  69. package/docs/prompt-budget.md +12 -0
  70. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  71. package/docs/readme-reference.md +76 -24
  72. package/docs/review-coordinator.md +29 -9
  73. package/docs/review-delivery-preflight.md +22 -0
  74. package/docs/work-continuity.md +11 -1
  75. package/extensions/ask-user-question.ts +2 -2
  76. package/extensions/child-context.ts +21 -7
  77. package/extensions/gentle-agents.ts +234 -33
  78. package/extensions/gentle-ai.ts +576 -135
  79. package/extensions/gentle-design.ts +69 -3
  80. package/extensions/gentle-desktop-rpc.ts +143 -0
  81. package/extensions/gentle-guide.ts +3 -0
  82. package/extensions/gentle-shell.ts +105 -52
  83. package/extensions/gentle-todo.ts +48 -25
  84. package/extensions/skill-registry.ts +248 -223
  85. package/lib/agent-assets.ts +30 -6
  86. package/lib/agent-tool-overlay.ts +117 -0
  87. package/lib/agents-config.ts +47 -6
  88. package/lib/agents-message-delivery.ts +17 -0
  89. package/lib/agents-messaging.ts +8 -2
  90. package/lib/agents-protocol.ts +15 -0
  91. package/lib/agents-report-cap.ts +115 -0
  92. package/lib/agents-runner.ts +91 -6
  93. package/lib/agents-session-transport.ts +17 -1
  94. package/lib/background-jobs-tools.ts +9 -4
  95. package/lib/bounded-writer-admission.ts +184 -31
  96. package/lib/child-context-files.ts +21 -6
  97. package/lib/codemode-renderer.ts +1 -0
  98. package/lib/delivery-conflict-markers.ts +349 -0
  99. package/lib/design-canvas-assets.ts +36 -0
  100. package/lib/design-canvas-server.ts +241 -23
  101. package/lib/design-comments.ts +94 -4
  102. package/lib/design-handoffs.ts +2 -1
  103. package/lib/design-layout.ts +125 -0
  104. package/lib/design-parts.ts +281 -0
  105. package/lib/design-system-tokens.ts +111 -0
  106. package/lib/desktop-agents-service.ts +294 -0
  107. package/lib/desktop-design-service.ts +233 -0
  108. package/lib/desktop-jobs-service.ts +263 -0
  109. package/lib/desktop-rpc-agents.ts +294 -0
  110. package/lib/desktop-rpc-config.ts +731 -0
  111. package/lib/desktop-rpc-design.ts +138 -0
  112. package/lib/desktop-rpc-jobs.ts +181 -0
  113. package/lib/desktop-rpc-permissions.ts +177 -0
  114. package/lib/desktop-rpc-profiles.ts +196 -0
  115. package/lib/desktop-rpc-usage.ts +229 -0
  116. package/lib/desktop-rpc.ts +225 -0
  117. package/lib/desktop-usage-service.ts +310 -0
  118. package/lib/destructive-command-guard.ts +188 -13
  119. package/lib/gentle-ai-renderer.ts +13 -1
  120. package/lib/gentle-design.ts +201 -14
  121. package/lib/gentle-shell-bundled.ts +100 -9
  122. package/lib/hidden-tools.ts +35 -0
  123. package/lib/inprocess-reviewer.ts +96 -12
  124. package/lib/model-fallback-policy.ts +9 -0
  125. package/lib/model-routing-authority.ts +9 -0
  126. package/lib/nan-provider.ts +42 -28
  127. package/lib/native-review-cli.ts +79 -4
  128. package/lib/orchestrator-discovery.ts +39 -2
  129. package/lib/reply-language-anchor.ts +27 -2
  130. package/lib/request-context-placement.ts +53 -0
  131. package/lib/review-candidate-view.ts +11 -1
  132. package/lib/review-continuation-registry.ts +17 -0
  133. package/lib/review-coordinator.ts +252 -8
  134. package/lib/review-delivery-preflight.ts +85 -0
  135. package/lib/review-host-relay.ts +5 -1
  136. package/lib/review-integration-v2.ts +56 -3
  137. package/lib/reviewer-stream.ts +87 -0
  138. package/lib/shell-prompt.ts +16 -3
  139. package/lib/shell-usage.ts +10 -0
  140. package/lib/vim-editor-adapter.ts +9 -2
  141. package/lib/writer-batch-admission.ts +55 -0
  142. package/lib/yolo-session-policy.ts +6 -1
  143. package/package.json +2 -2
  144. package/prompts/skill-creation.md +1 -10
  145. package/runtime/design-canvas-assets.mjs +37 -0
  146. package/runtime/gentle-shell-bundled.mjs +100 -9
  147. package/runtime/native-review-cli.mjs +79 -4
  148. package/runtime/review-integration-v2.mjs +56 -3
  149. package/scripts/bootstrap.cmd +2 -2
  150. package/scripts/bootstrap.sh +41 -4
  151. package/scripts/build-full-delegation-card.mjs +4 -0
  152. package/scripts/build-runtime-modules.mjs +1 -0
  153. package/scripts/gentle-ai-installer.mjs +10 -10
  154. package/scripts/gentle-ai-proxy.mjs +1 -1
  155. package/scripts/installer-downloads.mjs +34 -8
  156. package/scripts/installer-preflight.mjs +28 -17
  157. package/scripts/installer-probes.mjs +25 -5
  158. package/scripts/installer-server.mjs +38 -9
  159. package/scripts/installer-windows.mjs +2 -2
  160. package/scripts/pi-update.mjs +166 -27
  161. package/scripts/prepare-verifier.mjs +107 -0
  162. package/scripts/update-agent-body-history.mjs +55 -8
  163. package/scripts/verify-package-files.mjs +40 -19
  164. package/skills/branch-pr/SKILL.md +16 -16
  165. package/skills/comment-writer/SKILL.md +1 -1
  166. package/skills/design/SKILL.md +6 -6
  167. package/skills/gentle-ai/SKILL.md +5 -5
  168. package/skills/judgment-day/SKILL.md +2 -2
  169. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  170. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  171. package/skills/skill-improver/SKILL.md +2 -2
  172. package/skills/skill-registry/SKILL.md +11 -13
  173. package/skills/tui-design/SKILL.md +1 -1
  174. package/skills/work-unit-commits/SKILL.md +5 -5
  175. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  176. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  177. package/tests/agent-tool-overlay.test.ts +89 -0
  178. package/tests/agents-config.test.ts +10 -1
  179. package/tests/agents-message-delivery.test.ts +36 -0
  180. package/tests/agents-queries.test.ts +144 -4
  181. package/tests/agents-report-cap.test.ts +126 -0
  182. package/tests/agents-runner.test.ts +37 -1
  183. package/tests/agents-session-transport.test.ts +34 -0
  184. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  185. package/tests/append-system-prompt-route.test.ts +10 -2
  186. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  187. package/tests/artifact-language.test.ts +1 -1
  188. package/tests/ask-user-question.test.ts +2 -1
  189. package/tests/audit-leftovers-contract.test.ts +51 -0
  190. package/tests/bounded-stop-contract.test.ts +9 -1
  191. package/tests/branch-pr-skill.test.ts +10 -1
  192. package/tests/bundled-install.test.ts +1 -1
  193. package/tests/child-context-files.test.ts +64 -8
  194. package/tests/child-skills-catalog.test.ts +56 -0
  195. package/tests/codemode-rendering.test.ts +4 -1
  196. package/tests/delegate-for-reason-contract.test.ts +30 -8
  197. package/tests/delivery-conflict-markers.test.ts +348 -0
  198. package/tests/design-canvas-all-sizes.test.ts +631 -0
  199. package/tests/design-canvas-allowlist.test.ts +32 -0
  200. package/tests/design-canvas-assets.test.ts +11 -878
  201. package/tests/design-canvas-boards.test.ts +77 -0
  202. package/tests/design-canvas-checks.test.ts +655 -0
  203. package/tests/design-canvas-compare.test.ts +79 -0
  204. package/tests/design-canvas-events.test.ts +59 -0
  205. package/tests/design-canvas-export.test.ts +1168 -0
  206. package/tests/design-canvas-focus.test.ts +113 -0
  207. package/tests/design-canvas-handoffs.test.ts +59 -0
  208. package/tests/design-canvas-i18n-review.test.ts +513 -0
  209. package/tests/design-canvas-i18n-views.test.ts +259 -0
  210. package/tests/design-canvas-i18n.test.ts +526 -0
  211. package/tests/design-canvas-inspector.test.ts +937 -0
  212. package/tests/design-canvas-layout.test.ts +1222 -0
  213. package/tests/design-canvas-minimap.test.ts +413 -0
  214. package/tests/design-canvas-modules.test.ts +90 -0
  215. package/tests/design-canvas-parts.test.ts +721 -0
  216. package/tests/design-canvas-rail.test.ts +799 -0
  217. package/tests/design-canvas-server.test.ts +855 -17
  218. package/tests/design-canvas-sizes.test.ts +548 -0
  219. package/tests/design-canvas-store.test.ts +180 -0
  220. package/tests/design-canvas-tokens.test.ts +965 -0
  221. package/tests/design-canvas-view.test.ts +299 -0
  222. package/tests/design-comments.test.ts +201 -1
  223. package/tests/design-handoffs.test.ts +20 -0
  224. package/tests/design-layout.test.ts +100 -0
  225. package/tests/design-parts.test.ts +260 -0
  226. package/tests/design-system-tokens.test.ts +215 -0
  227. package/tests/desktop-rpc-agents.test.ts +893 -0
  228. package/tests/desktop-rpc-config.test.ts +1452 -0
  229. package/tests/desktop-rpc-design.test.ts +662 -0
  230. package/tests/desktop-rpc-jobs.test.ts +796 -0
  231. package/tests/desktop-rpc-permissions.test.ts +311 -0
  232. package/tests/desktop-rpc-profiles.test.ts +140 -0
  233. package/tests/desktop-rpc-safety.test.ts +119 -0
  234. package/tests/desktop-rpc-usage.test.ts +697 -0
  235. package/tests/desktop-rpc.test.ts +252 -0
  236. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  237. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  238. package/tests/engram-safety.test.ts +111 -0
  239. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  240. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  241. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
  242. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  243. package/tests/full-delegation-closure.test.ts +29 -0
  244. package/tests/gentle-agents.test.ts +329 -4
  245. package/tests/gentle-ai-binary.test.ts +1 -1
  246. package/tests/gentle-ai-child-guards.test.ts +1 -0
  247. package/tests/gentle-ai-installer.test.ts +52 -51
  248. package/tests/gentle-ai-renderer.test.ts +36 -2
  249. package/tests/gentle-ai.test.ts +121 -6
  250. package/tests/gentle-design.test.ts +365 -1
  251. package/tests/gentle-shell-bundled.test.ts +91 -5
  252. package/tests/gentle-shell-launcher.test.ts +1 -1
  253. package/tests/gentle-shell.test.ts +118 -87
  254. package/tests/gentle-todo.test.ts +32 -9
  255. package/tests/hidden-tools.test.ts +188 -0
  256. package/tests/independent-recovery-delivery.test.ts +19 -5
  257. package/tests/inprocess-reviewer.test.ts +73 -0
  258. package/tests/install-wizard.test.ts +27 -1
  259. package/tests/installer-downloads.test.ts +30 -1
  260. package/tests/installer-posix-bootstrap.test.ts +114 -13
  261. package/tests/installer-preflight.test.ts +49 -1
  262. package/tests/installer-probes.test.ts +146 -0
  263. package/tests/installer-server.test.ts +203 -4
  264. package/tests/installer-windows-bootstrap.test.ts +19 -1
  265. package/tests/judgment-day-severity-admission.test.ts +46 -0
  266. package/tests/lazy-module-contradictions-contract.test.ts +158 -0
  267. package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
  268. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  269. package/tests/model-fallback-policy.test.ts +26 -7
  270. package/tests/nan-provider-runtime.test.ts +17 -3
  271. package/tests/nan-provider.test.ts +111 -56
  272. package/tests/native-review-capability-contract.test.ts +11 -1
  273. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  274. package/tests/native-review-parity.test.ts +24 -5
  275. package/tests/native-review-refusal-identity.test.ts +25 -0
  276. package/tests/no-self-pause-contract.test.ts +11 -3
  277. package/tests/odd-integration.test.ts +11 -3
  278. package/tests/odd-routing-contract.test.ts +80 -28
  279. package/tests/orchestrator-budget.test.ts +30 -5
  280. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  281. package/tests/orchestrator-delegation-mode.test.ts +2 -1
  282. package/tests/orchestrator-discovery.test.ts +28 -0
  283. package/tests/orchestrator-prompt-budget.test.ts +11 -2
  284. package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
  285. package/tests/orchestrator-rdd-ownership.test.ts +2 -1
  286. package/tests/orchestrator-work-search.test.ts +4 -2
  287. package/tests/package-files.test.ts +25 -1
  288. package/tests/package-manifest.test.ts +11 -10
  289. package/tests/parallel-reason-contract.test.ts +6 -3
  290. package/tests/permission-allowlist.test.ts +200 -30
  291. package/tests/persona-neutral-voseo.test.ts +4 -4
  292. package/tests/persona-reply-language.test.ts +1 -1
  293. package/tests/persona-single-channel.test.ts +13 -5
  294. package/tests/pi-update-launcher.test.ts +17 -7
  295. package/tests/pi-update-source.test.ts +113 -6
  296. package/tests/pi-update.test.ts +294 -19
  297. package/tests/pnpm-workspace-policy.test.ts +47 -0
  298. package/tests/primary-context-files.test.ts +233 -0
  299. package/tests/primary-context-three-files.test.ts +174 -0
  300. package/tests/provider-defect-handoff.test.ts +9 -2
  301. package/tests/rdd-aware-verification-contract.test.ts +1 -1
  302. package/tests/rdd-status-line.test.ts +94 -1
  303. package/tests/reply-language-anchor-placement.test.ts +184 -0
  304. package/tests/reply-language-anchor.test.ts +17 -1
  305. package/tests/request-context-append-only.test.ts +218 -0
  306. package/tests/request-context-placement.test.ts +148 -0
  307. package/tests/review-agent-end-preflight.test.ts +79 -1
  308. package/tests/review-candidate-view.test.ts +65 -0
  309. package/tests/review-continuation-registry.test.ts +31 -0
  310. package/tests/review-contract-prompt.test.ts +1 -1
  311. package/tests/review-controller.test.ts +2 -1
  312. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  313. package/tests/review-coordinator-findings.test.ts +206 -0
  314. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  315. package/tests/review-coordinator.test.ts +271 -4
  316. package/tests/review-delivery-preflight.test.ts +462 -0
  317. package/tests/review-due-compaction.test.ts +31 -0
  318. package/tests/review-due-public-boundary.test.ts +26 -0
  319. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  320. package/tests/review-json-arguments.test.ts +41 -2
  321. package/tests/review-ledger-contract.test.ts +19 -40
  322. package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
  323. package/tests/review-one-call-findings.test.ts +131 -0
  324. package/tests/review-one-call-followups.test.ts +308 -0
  325. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  326. package/tests/review-one-call.test.ts +452 -0
  327. package/tests/review-relay-transport-agent.test.ts +28 -1
  328. package/tests/review-reviewer-evidence.test.ts +41 -1
  329. package/tests/review-risk-assessment.test.ts +52 -5
  330. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  331. package/tests/review-session-standing-permission-controller.test.ts +32 -2
  332. package/tests/review-tool-prose-budget.test.ts +1 -0
  333. package/tests/reviewer-stream.test.ts +149 -0
  334. package/tests/session-profile-extension.test.ts +2 -2
  335. package/tests/shell-prompt.test.ts +17 -0
  336. package/tests/shell-usage.test.ts +59 -10
  337. package/tests/skill-contradictions-contract.test.ts +122 -0
  338. package/tests/skill-registry-watcher.test.ts +216 -2
  339. package/tests/skill-registry.test.ts +929 -306
  340. package/tests/support/design-canvas-dom.ts +369 -0
  341. package/tests/support/review-coordinator-runtime.ts +212 -17
  342. package/tests/task-size-routing-contract.test.ts +42 -11
  343. package/tests/test-strength-contract.test.ts +2 -1
  344. package/tests/todo-request-append-only.test.ts +214 -0
  345. package/tests/tool-batching-contract.test.ts +3 -1
  346. package/tests/update-agent-body-history.test.ts +138 -0
  347. package/tests/verification-tiers-contract.test.ts +229 -0
  348. package/tests/verifier-preparation.test.ts +229 -0
  349. package/tests/verify-agent-contract.test.ts +20 -2
  350. package/tests/verify-first-launch-contract.test.ts +87 -11
  351. package/tests/vim-editor-adapter.test.ts +2 -2
  352. package/tests/work-continuity-contract.test.ts +54 -11
  353. package/tests/writer-admission-messages.test.ts +232 -0
  354. package/tests/writer-batch-admission.test.ts +66 -0
  355. package/tests/writer-edit-surface-scope.test.ts +52 -20
  356. package/tests/writer-feature-document-admission.test.ts +184 -0
  357. package/tests/yolo-mode.test.ts +39 -0
  358. package/skills/_shared/review-ledger-contract.md +0 -106
  359. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
  360. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
  361. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
  362. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  363. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
  364. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
  365. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -0,0 +1,401 @@
1
+ // Partial implementations (design/<slug>/parts.json): one element of an artboard
2
+ // handed to the session on its own, without choosing a direction. The comment
3
+ // popover's Implement only this sends the picked element with the field as an
4
+ // optional note; "Partial implementations · N", at the bottom of the panel, lists
5
+ // the design's parts live with the state in words, the time, the excerpt, the
6
+ // agent's note, Show (that artboard in focus with the element highlighted in every
7
+ // frame of it) and, while the agent has not taken a part up, Remove behind an
8
+ // inline confirm. Which part has its confirm open and which Removes and sends are
9
+ // in flight are this module's own view state, kept across re-renders; the parts themselves
10
+ // change only through store.setParts.
11
+
12
+ const TEXT = Object.freeze({
13
+ title: (count) => `Partial implementations · ${count}`,
14
+ states: { sent: "Sent", queued: "Queued", in_progress: "In progress", implemented: "Implemented ✓" },
15
+ times: {
16
+ sent: (time, today) => `Sent ${today ? "at" : "on"} ${time}`,
17
+ queued: (time, today) => `Queued ${today ? "at" : "on"} ${time}`,
18
+ in_progress: (time) => `In progress since ${time}`,
19
+ implemented: (time, today) => `Implemented ${today ? "at" : "on"} ${time}`,
20
+ },
21
+ quoted: (value) => `“${value}”`,
22
+ show: "Show",
23
+ showLabel: (number, file) => `Show part ${number} in ${file}`,
24
+ remove: "Remove",
25
+ removeLabel: (number, file) => `Remove part ${number} in ${file}`,
26
+ question: "Remove this part? The agent can no longer report on it.",
27
+ confirmLabel: (number) => `Confirm removing part ${number}`,
28
+ cancel: "Cancel",
29
+ partTitle: "Build only this element in the project; the field is an optional note",
30
+ partOffline: "The canvas is not connected to a Pi session; open it with /gentle:design open",
31
+ noteTooLong: (max) => `The note can have at most ${max} characters.`,
32
+ sending: "Sending…",
33
+ sentShort: "Sent to the session",
34
+ sent: (title) => `Sent: the session is building only this part of ${title} now.`,
35
+ queued: (title) => `Queued: the session will build only this part of ${title} after its current task.`,
36
+ notSent: (why) => `Not sent: ${why}`,
37
+ sendErrors: {
38
+ "implement-part-unavailable": "the canvas is not connected to a Pi session; open it with /gentle:design open.",
39
+ "invalid-file": "that artboard is no longer in the design.",
40
+ "invalid-selector": "this element's selector cannot be sent.",
41
+ "invalid-excerpt": "this element's text cannot be sent.",
42
+ "invalid-note": "the note can have at most 2000 characters.",
43
+ "not-found": "the design is gone.",
44
+ "too-many-parts": "this design already has 100 parts; remove one first.",
45
+ "parts-too-large": "parts.json is full; remove a part first.",
46
+ "invalid-parts": "parts.json cannot be read; fix it or delete it.",
47
+ },
48
+ deliveryFailed: (reason) => (reason ? `the session did not take it (${reason}).` : "the session did not take it."),
49
+ removed: "Part removed. The agent can no longer report on it.",
50
+ notRemoved: (why) => `Not removed: ${why}`,
51
+ removeErrors: {
52
+ "part-not-sent": "the agent already took this part up.",
53
+ "not-found": "this part is gone; its delivery failed or it was removed already.",
54
+ "invalid-parts": "parts.json cannot be read; fix it or delete it.",
55
+ "invalid-part": "this part's id is not valid.",
56
+ },
57
+ notShown: "Not shown: the artboard of this part is no longer in the design.",
58
+ unreadable: (slug, message) => `parts.json for ${slug} cannot be read: ${message}`,
59
+ });
60
+
61
+ const NOTE_LIMIT = 2000;
62
+ const STATUSES = ["sent", "in_progress", "implemented"];
63
+ const CLOSE_MS = 1200;
64
+
65
+ export function init(ctx) {
66
+ const { win, doc, els, store, api, ui, actions } = ctx;
67
+ const { state } = store;
68
+ const { getJson, postJson, delivery } = api;
69
+ const { setStatus, showToast } = ui;
70
+ const T = ctx.i18n.text("parts", TEXT);
71
+ // The part whose Remove confirm is open, and the Removes in flight ("<slug>/<id>").
72
+ let confirming = null;
73
+ const removing = new Set();
74
+ // The latest loadParts: parts.json is written more than once per send, so an older reply landing last changes nothing.
75
+ // A part listed by Implement only this or dropped by Remove counts as newer too; when that drops a read in flight,
76
+ // which may carry other parts' updates, a fresh read follows.
77
+ let partLoads = 0;
78
+ let reading = 0;
79
+ // The parts a parts.json read listed or a Remove dropped ("<slug>/<id>"): the server already reported on them, so
80
+ // an Implement only this reply that lands later never lists them again, even when the list no longer has them.
81
+ const reported = new Set();
82
+ // The elements whose Implement only this is in flight ("<slug>/<file>/<selector>"), across popovers.
83
+ const sending = new Set();
84
+ const sendKey = (pick) => JSON.stringify([pick.board.slug, pick.board.artboard.file, pick.selector]);
85
+ // Why Implement only this is disabled, under the popover's buttons, where the keyboard and screen readers reach it too.
86
+ const partNote = doc.createElement("p");
87
+ partNote.id = "gd-popover-part-note";
88
+ partNote.className = "gd-popover-note";
89
+ partNote.textContent = T.partOffline;
90
+ partNote.hidden = true;
91
+ els.form.append(partNote);
92
+
93
+ const partsPath = (slug) => `api/designs/${encodeURIComponent(slug)}/parts`;
94
+ // A request that never reached the server has no error code, only its reason.
95
+ const failed = (error) => ({ ok: false, status: 0, body: { reason: error.message } });
96
+
97
+ function isPart(part) {
98
+ return Boolean(part && typeof part === "object" && typeof part.id === "string" && typeof part.file === "string" && typeof part.selector === "string" && STATUSES.includes(part.status));
99
+ }
100
+
101
+ /** The parts of the design shown; another design's parts never show. */
102
+ function shownParts() {
103
+ return state.parts.slug !== null && state.parts.slug === state.slug ? state.parts.parts : [];
104
+ }
105
+
106
+ function kindOf(part) {
107
+ if (part.status === "sent") return part.queued === true ? "queued" : "sent";
108
+ return part.status;
109
+ }
110
+
111
+ // By design and file: while a design switch waits for its design.json, the boards installed are the old design's.
112
+ const boardOf = (part, slug) => state.boards.find((board) => board.slug === slug && board.artboard.file === part.file) ?? null;
113
+ const removeKey = (slug, part) => `${slug}/${part.id}`;
114
+ const twoDigits = (value) => String(value).padStart(2, "0");
115
+
116
+ /** "09:30" today, "Oct 26, 09:30" this year, "Mar 4 2020, 09:05" before (in Spanish "26 oct, 09:30"); null when unreadable. */
117
+ function timeOf(value) {
118
+ const date = typeof value === "string" ? new Date(value) : null;
119
+ if (!date || Number.isNaN(date.getTime())) return null;
120
+ const now = new Date();
121
+ const clock = `${twoDigits(date.getHours())}:${twoDigits(date.getMinutes())}`;
122
+ if (date.toDateString() === now.toDateString()) return { time: clock, today: true };
123
+ const day = date.toLocaleDateString(state.language === "es" ? "es-ES" : "en-US", { month: "short", day: "numeric" });
124
+ return { time: `${date.getFullYear() === now.getFullYear() ? day : `${day} ${date.getFullYear()}`}, ${clock}`, today: false };
125
+ }
126
+
127
+ function chip(className, value) {
128
+ const element = doc.createElement("span");
129
+ element.className = className;
130
+ element.textContent = value;
131
+ return element;
132
+ }
133
+
134
+ function button(className, label, onClick) {
135
+ const element = doc.createElement("button");
136
+ element.type = "button";
137
+ element.className = className;
138
+ element.textContent = label;
139
+ element.addEventListener("click", onClick);
140
+ return element;
141
+ }
142
+
143
+ function renderPart(part, index, slug) {
144
+ const number = index + 1;
145
+ const kind = kindOf(part);
146
+ const board = boardOf(part, slug);
147
+ const item = doc.createElement("li");
148
+ item.className = "gd-part";
149
+ item.dataset.id = part.id;
150
+ item.dataset.status = kind;
151
+ const head = doc.createElement("div");
152
+ head.className = "gd-part-head";
153
+ head.append(chip("gd-part-title", board ? board.artboard.title : part.file), chip("gd-part-state", T.states[kind]));
154
+ item.append(head);
155
+ if (typeof part.excerpt === "string" && part.excerpt) item.append(chip("gd-part-excerpt", T.quoted(part.excerpt)));
156
+ const when = timeOf(kind === "implemented" ? part.implementedAt : kind === "in_progress" ? part.startedAt : part.sentAt);
157
+ if (when) item.append(chip("gd-part-time", T.times[kind](when.time, when.today)));
158
+ if (typeof part.note === "string" && part.note) item.append(chip("gd-part-note", T.quoted(part.note)));
159
+ const controls = doc.createElement("div");
160
+ controls.className = "gd-part-actions";
161
+ const show = button("gd-part-show", T.show, () => showPart(part));
162
+ show.setAttribute("aria-label", T.showLabel(number, part.file));
163
+ show.dataset.control = "show";
164
+ show.disabled = !board;
165
+ controls.append(show);
166
+ if (kind === "sent" || kind === "queued") controls.append(...removeControl(part, number, slug));
167
+ item.append(controls);
168
+ return item;
169
+ }
170
+
171
+ /** Remove and its inline confirm (like Implement this): the agent can no longer report on a removed part. */
172
+ function removeControl(part, number, slug) {
173
+ const key = removeKey(slug, part);
174
+ const inFlight = removing.has(key);
175
+ const start = button("gd-part-remove", T.remove, () => {
176
+ confirming = key;
177
+ start.hidden = true;
178
+ confirm.hidden = false;
179
+ yes.focus();
180
+ });
181
+ start.setAttribute("aria-label", T.removeLabel(number, part.file));
182
+ start.dataset.control = "remove";
183
+ start.disabled = inFlight;
184
+ const confirm = doc.createElement("div");
185
+ confirm.className = "gd-part-confirm";
186
+ confirm.setAttribute("role", "group");
187
+ confirm.setAttribute("aria-label", T.confirmLabel(number));
188
+ // Cancel and Esc wait for a Remove in flight: Remove (start) is disabled until it answers.
189
+ const close = () => {
190
+ if (removing.has(key)) return;
191
+ confirming = null;
192
+ confirm.hidden = true;
193
+ start.hidden = false;
194
+ start.focus();
195
+ };
196
+ const yes = button("gd-part-confirm-yes gd-primary", T.remove, () => removePart(slug, part));
197
+ yes.dataset.control = "yes";
198
+ // In flight it stays focusable, so the redraw keeps keyboard focus on it; removePart ignores the click.
199
+ if (inFlight) yes.setAttribute("aria-disabled", "true");
200
+ const no = button("gd-part-confirm-no", T.cancel, close);
201
+ no.dataset.control = "no";
202
+ no.disabled = inFlight;
203
+ confirm.addEventListener("keydown", (event) => {
204
+ if (event.key !== "Escape") return;
205
+ event.preventDefault();
206
+ event.stopPropagation();
207
+ close();
208
+ });
209
+ confirm.append(chip("gd-part-question", T.question), yes, no);
210
+ const open = confirming === key;
211
+ confirm.hidden = !open;
212
+ start.hidden = open;
213
+ return [start, confirm];
214
+ }
215
+
216
+ /** The list from the store; keyboard focus on a part's control stays on it across a re-render. */
217
+ function renderParts() {
218
+ const parts = shownParts();
219
+ const slug = state.parts.slug;
220
+ if (confirming && !parts.some((part) => removeKey(slug, part) === confirming && ["sent", "queued"].includes(kindOf(part)))) confirming = null;
221
+ const active = els.partsList.contains(doc.activeElement) ? doc.activeElement : null;
222
+ const focusItem = active?.closest(".gd-part");
223
+ const focus = focusItem ? { id: focusItem.dataset.id, control: active.dataset.control, index: Array.from(els.partsList.children).indexOf(focusItem) } : null;
224
+ const rendered = parts.map((part, index) => renderPart(part, index, slug));
225
+ els.partsList.replaceChildren(...rendered);
226
+ els.parts.hidden = parts.length === 0;
227
+ els.partsTitle.textContent = T.title(parts.length);
228
+ if (focus) restoreFocus(rendered, focus);
229
+ }
230
+
231
+ /** The same control of the same part, else a usable one of the part now at its place, else the panel's toggle. */
232
+ function restoreFocus(rendered, focus) {
233
+ const usable = (element) => !element.hidden && !element.disabled && !element.parentElement.hidden;
234
+ const buttonsIn = (root) => Array.from(root.children).flatMap((child) => (child.localName === "button" ? [child] : buttonsIn(child)));
235
+ const pickIn = (item) => {
236
+ const buttons = buttonsIn(item).filter(usable);
237
+ return buttons.find((element) => element.dataset.control === focus.control) ?? buttons[0];
238
+ };
239
+ const same = rendered.find((item) => item.dataset.id === focus.id);
240
+ const near = rendered[Math.min(Math.max(focus.index, 0), rendered.length - 1)];
241
+ const target = same ? pickIn(same) : near ? pickIn(near) : null;
242
+ (target ?? els.panelToggle).focus();
243
+ }
244
+
245
+ function setParts(slug, parts) {
246
+ store.setParts({ slug, parts });
247
+ renderParts();
248
+ }
249
+
250
+ /** Drops the parts of the design shown before (canvas-boards.js showDesign). */
251
+ function clearParts() {
252
+ setParts(state.slug, []);
253
+ }
254
+
255
+ async function loadParts() {
256
+ const slug = state.slug;
257
+ if (!slug) return;
258
+ const load = ++partLoads;
259
+ let data = null;
260
+ let failure = null;
261
+ reading += 1;
262
+ try {
263
+ data = await getJson(partsPath(slug));
264
+ } catch (error) {
265
+ failure = error;
266
+ } finally {
267
+ reading -= 1;
268
+ }
269
+ if (load !== partLoads || slug !== state.slug) return;
270
+ // A failed read keeps the parts shown.
271
+ if (failure) return setStatus(T.unreadable(slug, failure.message), true);
272
+ const parts = data && Array.isArray(data.parts) ? data.parts.filter(isPart) : [];
273
+ for (const part of parts) reported.add(removeKey(slug, part));
274
+ setParts(slug, parts);
275
+ }
276
+
277
+ /** A part the server just accepted, before its parts.json change event arrives; never into another design's list. */
278
+ function noteParts(slug, part) {
279
+ if (slug !== state.slug || reported.has(removeKey(slug, part))) return;
280
+ const current = state.parts.slug === slug ? state.parts.parts : [];
281
+ if (current.some((entry) => entry.id === part.id)) return;
282
+ partLoads += 1;
283
+ setParts(slug, [...current, part]);
284
+ if (reading > 0) void loadParts();
285
+ }
286
+
287
+ /** Show: the part's artboard in focus, its element highlighted in every frame; the board is looked up now. */
288
+ function showPart(part) {
289
+ const board = state.parts.slug === state.slug ? boardOf(part, state.slug) : null;
290
+ if (!board) {
291
+ setStatus(T.notShown, true);
292
+ renderParts();
293
+ return;
294
+ }
295
+ actions.exitCompare(false);
296
+ actions.enterFocus(board);
297
+ for (const surface of actions.surfacesOf(board)) surface.frame.contentWindow?.postMessage({ type: "gd:highlight", selector: part.selector }, "*");
298
+ }
299
+
300
+ async function removePart(slug, part) {
301
+ const key = removeKey(slug, part);
302
+ if (removing.has(key)) return;
303
+ removing.add(key);
304
+ renderParts();
305
+ const reply = await postJson(`${partsPath(slug)}/remove`, { id: part.id }).catch(failed);
306
+ removing.delete(key);
307
+ if (confirming === key) confirming = null;
308
+ const current = slug === state.slug && state.parts.slug === slug;
309
+ if (reply.ok) {
310
+ reported.add(key);
311
+ setStatus(T.removed, false);
312
+ showToast(T.removed, false);
313
+ if (!current) return;
314
+ partLoads += 1;
315
+ setParts(slug, state.parts.parts.filter((entry) => entry.id !== part.id));
316
+ if (reading > 0) await loadParts();
317
+ return;
318
+ }
319
+ const code = typeof reply.body.error === "string" ? reply.body.error : "";
320
+ const text = T.notRemoved(T.removeErrors[code] ?? (reply.body.reason || code || `HTTP ${reply.status}`));
321
+ setStatus(text, true);
322
+ showToast(text, true);
323
+ if (!current) return;
324
+ // The agent took it up meanwhile (409), or a failed delivery took it back (404): show what parts.json holds now.
325
+ if (code === "part-not-sent" || code === "not-found") await loadParts();
326
+ else renderParts();
327
+ }
328
+
329
+ /** A new language: the list (focus kept, as on any re-render), the note and Implement only this's tooltip (not its state). */
330
+ function relabel() {
331
+ partNote.textContent = T.partOffline;
332
+ els.partAdd.title = delivery.part ? T.partTitle : T.partOffline;
333
+ renderParts();
334
+ }
335
+
336
+ /** Implement only this on the open popover: enabled only when the page config says the server can deliver a part and that element is not in flight. */
337
+ function renderPartButton() {
338
+ const offline = !delivery.part;
339
+ els.partAdd.disabled = offline || Boolean(state.pick && sending.has(sendKey(state.pick)));
340
+ els.partAdd.title = offline ? T.partOffline : T.partTitle;
341
+ // Worded where it is shown: the language may have been set after init (a stored choice).
342
+ partNote.textContent = T.partOffline;
343
+ partNote.hidden = !offline;
344
+ if (offline) els.partAdd.setAttribute("aria-describedby", partNote.id);
345
+ else els.partAdd.removeAttribute("aria-describedby");
346
+ }
347
+
348
+ function sendFailure(reply) {
349
+ const code = typeof reply.body.error === "string" ? reply.body.error : "";
350
+ const reason = typeof reply.body.reason === "string" ? reply.body.reason : "";
351
+ const why = code === "delivery-failed" ? T.deliveryFailed(reason) : T.sendErrors[code] ?? (reason || code || `HTTP ${reply.status}`);
352
+ return { text: T.notSent(why), code };
353
+ }
354
+
355
+ function popoverMessage(text, isError, detail = "") {
356
+ els.message.setAttribute("data-gd-message-owner", "parts");
357
+ els.message.textContent = text;
358
+ els.message.title = detail;
359
+ els.message.classList.toggle("gd-error", isError);
360
+ }
361
+
362
+ els.partAdd.addEventListener("click", async () => {
363
+ const pick = state.pick;
364
+ if (!pick || !delivery.part || els.partAdd.disabled) return;
365
+ const key = sendKey(pick);
366
+ if (sending.has(key)) return;
367
+ const note = els.text.value.replace(/\r\n?/g, "\n").trim();
368
+ if (note.length > NOTE_LIMIT) return popoverMessage(T.noteTooLong(NOTE_LIMIT), true);
369
+ sending.add(key);
370
+ els.partAdd.disabled = true;
371
+ popoverMessage(T.sending, false);
372
+ const board = pick.board;
373
+ const slug = board.slug;
374
+ const reply = await postJson(`api/designs/${encodeURIComponent(slug)}/implement-part`, { file: board.artboard.file, selector: pick.selector, excerpt: pick.excerpt, ...(note ? { note } : {}) }).catch(failed);
375
+ sending.delete(key);
376
+ const open = state.pick === pick;
377
+ // The same element picked again while this was in flight can be sent now.
378
+ if (!open && state.pick && sendKey(state.pick) === key) renderPartButton();
379
+ if (!reply.ok) {
380
+ const failure = sendFailure(reply);
381
+ if (!open) return setStatus(failure.text, true);
382
+ els.partAdd.disabled = !delivery.part;
383
+ popoverMessage(failure.text, true, failure.code);
384
+ return;
385
+ }
386
+ // Sent: it stays disabled until the popover closes, so a second click sends no duplicate; a new pick enables it.
387
+ const queued = reply.body.queued === true;
388
+ if (typeof reply.body.id === "string") {
389
+ noteParts(slug, { id: reply.body.id, file: board.artboard.file, selector: pick.selector, excerpt: pick.excerpt, status: "sent", queued, sentAt: new Date().toISOString(), startedAt: null, implementedAt: null, ...(note ? { instruction: note } : {}) });
390
+ }
391
+ const done = queued ? T.queued(board.artboard.title) : T.sent(board.artboard.title);
392
+ setStatus(done, false);
393
+ showToast(done, false);
394
+ if (!open) return;
395
+ els.text.value = "";
396
+ popoverMessage(T.sentShort, false);
397
+ store.setPopover({ closeTimer: win.setTimeout(actions.closePopover, CLOSE_MS) });
398
+ });
399
+
400
+ return { relabel, loadParts, clearParts, renderParts, renderPartButton };
401
+ }
@@ -0,0 +1,234 @@
1
+ // The comment popover: the pick it opens on, the screenshot attach (file, paste,
2
+ // drop), Esc and Shift+Esc in the canvas, and the submit that saves or sends the
3
+ // comment. Its Implement only this button belongs to canvas-parts.js.
4
+
5
+ // Every string the comment box shows, in English; canvas-i18n-es.js has the Spanish (its static labels are index.html's).
6
+ // The comment the person writes is sent as written.
7
+ const TEXT = Object.freeze({
8
+ shotType: "Attach a PNG, JPEG, WebP or GIF image.",
9
+ shotSize: "The screenshot must be at most 5 MB.",
10
+ shotRead: "The screenshot could not be read.",
11
+ limits: (max) => `Write a comment of 1 to ${max} characters.`,
12
+ sending: "Sending…",
13
+ savedOnly: "Saved, but not sent to the session",
14
+ saved: "Saved; use Send all to send it",
15
+ sent: "Sent to the session",
16
+ notSent: (reason) => `Not sent: ${reason}`,
17
+ });
18
+
19
+ const LIMITS = { selector: 500, excerpt: 300, comment: 2000, screenshotBytes: 5 * 1024 * 1024 };
20
+ const SCREENSHOT_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
21
+
22
+ export function init(ctx) {
23
+ const { win, doc, els, store, api, ui, actions } = ctx;
24
+ const { state } = store;
25
+ const { base, isFiniteNumber } = api;
26
+ const { setStatus } = ui;
27
+ const T = ctx.i18n.text("popover", TEXT);
28
+
29
+ function readPick(data) {
30
+ if (typeof data.selector !== "string") return null;
31
+ const selector = data.selector.trim();
32
+ if (!selector || selector.length > LIMITS.selector) return null;
33
+ const excerpt = typeof data.excerpt === "string" ? data.excerpt.slice(0, LIMITS.excerpt) : "";
34
+ const rect = data.rect && typeof data.rect === "object" ? data.rect : {};
35
+ const box = ["x", "y", "width", "height"].every((key) => isFiniteNumber(rect[key])) ? rect : { x: 0, y: 0, width: 0, height: 0 };
36
+ return { selector, excerpt, rect: { x: box.x, y: box.y, width: box.width, height: box.height } };
37
+ }
38
+
39
+ /**
40
+ * The pick of `surface`, a board's frame or one of its All sizes frames (canvas-sizes.js), with the size it was
41
+ * made at (viewport, null at the artboard's own size); the popover opens beside the element in that frame.
42
+ */
43
+ function openPopover(surface, pick) {
44
+ // The comment box takes the token inspector's place.
45
+ actions.hideInspector();
46
+ win.clearTimeout(state.closeTimer);
47
+ const board = actions.ownerOf(surface);
48
+ // A pick in another frame replaces the open one: that frame's highlight goes, as on a close.
49
+ const previous = state.pick && state.pick.surface;
50
+ if (previous && previous !== surface) previous.frame.contentWindow?.postMessage({ type: "gd:clear" }, "*");
51
+ store.setPopover({ pick: { board, surface, viewport: actions.viewportOf(surface), ...pick } });
52
+ els.target.textContent = `${board.artboard.file} · ${pick.selector}`;
53
+ showMessage("", false);
54
+ els.send.disabled = false;
55
+ actions.renderPartButton();
56
+ els.popover.hidden = false;
57
+ // The frame may be scaled (All sizes) or resized (a single size).
58
+ const frameRect = surface.frame.getBoundingClientRect();
59
+ const scale = frameRect.width / surface.viewWidth || 1;
60
+ const width = els.popover.offsetWidth;
61
+ const height = els.popover.offsetHeight;
62
+ let left = frameRect.left + pick.rect.x * scale;
63
+ let top = frameRect.top + (pick.rect.y + pick.rect.height) * scale + 8;
64
+ if (top + height > win.innerHeight - 12) top = frameRect.top + pick.rect.y * scale - height - 8;
65
+ left = Math.min(Math.max(12, left), win.innerWidth - width - 12);
66
+ top = Math.min(Math.max(12, top), win.innerHeight - height - 12);
67
+ els.popover.style.left = `${left}px`;
68
+ els.popover.style.top = `${top}px`;
69
+ els.text.focus();
70
+ }
71
+
72
+ function clearShot() {
73
+ store.setPopover({ shot: null, shotToken: state.shotToken + 1 });
74
+ els.shotInput.value = "";
75
+ els.shotImage.removeAttribute("src");
76
+ els.shotPreview.hidden = true;
77
+ els.shotAttach.hidden = false;
78
+ }
79
+
80
+ /** The popover's message line; a refusal's raw code in its tooltip (canvas-parts.js) goes with the message it explained. */
81
+ // Set when the message is the canvas's own wording, given as a function so a language switch words it again.
82
+ let worded = null;
83
+ function showMessage(text, isError) {
84
+ worded = typeof text === "function" ? text : null;
85
+ els.message.setAttribute("data-gd-message-owner", "comment");
86
+ els.message.textContent = worded ? worded() : text;
87
+ els.message.title = "";
88
+ els.message.classList.toggle("gd-error", isError);
89
+ }
90
+
91
+ function shotError(message) {
92
+ showMessage(message, true);
93
+ }
94
+
95
+ /** Reads one image file into the popover; a later attach or a clear discards a read still running. */
96
+ function attachShot(file) {
97
+ if (!file || els.popover.hidden) return;
98
+ if (!SCREENSHOT_TYPES.includes(file.type)) return shotError(T.shotType);
99
+ if (file.size === 0 || file.size > LIMITS.screenshotBytes) return shotError(T.shotSize);
100
+ store.setPopover({ shotToken: state.shotToken + 1 });
101
+ const token = state.shotToken;
102
+ const reader = new win.FileReader();
103
+ reader.addEventListener("load", () => {
104
+ if (token !== state.shotToken || typeof reader.result !== "string") return;
105
+ const url = reader.result;
106
+ store.setPopover({ shot: { mimeType: file.type, data: url.slice(url.indexOf(",") + 1) } });
107
+ els.shotImage.src = url;
108
+ els.shotPreview.hidden = false;
109
+ els.shotAttach.hidden = true;
110
+ showMessage("", false);
111
+ });
112
+ reader.addEventListener("error", () => { if (token === state.shotToken) shotError(T.shotRead); });
113
+ reader.readAsDataURL(file);
114
+ }
115
+
116
+ function imageFile(list) {
117
+ return Array.from(list || []).find((file) => file.type.startsWith("image/")) || (list && list[0]) || null;
118
+ }
119
+
120
+ els.shotAttach.addEventListener("click", () => els.shotInput.click());
121
+ els.shotInput.addEventListener("change", () => attachShot(els.shotInput.files && els.shotInput.files[0]));
122
+ els.shotRemove.addEventListener("click", () => {
123
+ clearShot();
124
+ els.shotAttach.focus();
125
+ });
126
+ els.popover.addEventListener("paste", (event) => {
127
+ const items = Array.from(event.clipboardData ? event.clipboardData.items : []);
128
+ const item = items.find((entry) => entry.kind === "file" && entry.type.startsWith("image/"));
129
+ if (!item) return;
130
+ event.preventDefault();
131
+ attachShot(item.getAsFile());
132
+ });
133
+ els.popover.addEventListener("dragover", (event) => {
134
+ if (!event.dataTransfer || !Array.from(event.dataTransfer.types).includes("Files")) return;
135
+ event.preventDefault();
136
+ event.dataTransfer.dropEffect = "copy";
137
+ els.popover.classList.add("gd-dropping");
138
+ });
139
+ els.popover.addEventListener("dragleave", (event) => {
140
+ if (!els.popover.contains(event.relatedTarget)) els.popover.classList.remove("gd-dropping");
141
+ });
142
+ els.popover.addEventListener("drop", (event) => {
143
+ els.popover.classList.remove("gd-dropping");
144
+ if (!event.dataTransfer || event.dataTransfer.files.length === 0) return;
145
+ event.preventDefault();
146
+ attachShot(imageFile(event.dataTransfer.files));
147
+ });
148
+
149
+ function closePopover() {
150
+ // Before the early return: every path that closes the box (focus mode ending, another size, Comment mode off,
151
+ // a pan or a zoom) also ends the token inspector's panel, open or not.
152
+ actions.hideInspector();
153
+ if (els.popover.hidden) return;
154
+ win.clearTimeout(state.closeTimer);
155
+ // The frame that was picked clears its outline.
156
+ const surface = state.pick && state.pick.surface;
157
+ store.setPopover({ pick: null });
158
+ clearShot();
159
+ els.popover.hidden = true;
160
+ surface?.frame.contentWindow?.postMessage({ type: "gd:clear" }, "*");
161
+ if (els.popover.contains(doc.activeElement) || doc.activeElement === doc.body) returnFocus(surface);
162
+ }
163
+
164
+ /** Back to the size frame that was picked while it still shows, else the focused artboard, else Comment. */
165
+ function returnFocus(surface) {
166
+ const sizeFrame = Boolean(state.focus && surface && surface !== state.focus && actions.surfacesOf(state.focus).includes(surface));
167
+ (sizeFrame ? surface.frame : state.focus ? state.focus.frame : els.comment).focus();
168
+ }
169
+
170
+ els.cancel.addEventListener("click", closePopover);
171
+ els.popover.addEventListener("keydown", (event) => {
172
+ if (event.key === "Escape") {
173
+ event.preventDefault();
174
+ closePopover();
175
+ }
176
+ });
177
+ doc.addEventListener("keydown", (event) => {
178
+ if (event.defaultPrevented || event.key !== "Escape") return;
179
+ if (event.shiftKey) {
180
+ if (state.compare) {
181
+ event.preventDefault();
182
+ actions.exitCompare(true);
183
+ return;
184
+ }
185
+ if (!state.focus) return;
186
+ event.preventDefault();
187
+ actions.exitFocus();
188
+ } else if (state.commenting && els.popover.hidden && event.target === doc.body) actions.setCommenting(false);
189
+ });
190
+
191
+ els.form.addEventListener("submit", async (event) => {
192
+ event.preventDefault();
193
+ const pick = state.pick;
194
+ if (!pick) return;
195
+ const comment = els.text.value.trim();
196
+ if (!comment || comment.length > LIMITS.comment) return showMessage(() => T.limits(LIMITS.comment), true);
197
+ els.send.disabled = true;
198
+ showMessage(() => T.sending, false);
199
+ const shot = state.shot;
200
+ try {
201
+ const response = await win.fetch(`${base}api/comments`, {
202
+ method: "POST",
203
+ headers: { "Content-Type": "application/json" },
204
+ cache: "no-store",
205
+ body: JSON.stringify({ slug: pick.board.slug, file: pick.board.artboard.file, selector: pick.selector, excerpt: pick.excerpt, comment, mode: state.mode, ...(shot ? { screenshot: shot } : {}), ...(pick.viewport ? { viewport: pick.viewport } : {}) }),
206
+ });
207
+ let reply = {};
208
+ try { reply = await response.json(); } catch { /* keep the status */ }
209
+ // Delivery can fail after the comment was saved; it then waits for "Send all".
210
+ const savedOnly = response.status === 500 && reply.saved === true;
211
+ if (response.status !== 202 && response.status !== 201 && !savedOnly) throw new Error(reply.reason || reply.error || `HTTP ${response.status}`);
212
+ actions.loadComments();
213
+ if (state.pick !== pick) return;
214
+ els.text.value = "";
215
+ if (state.shot === shot) clearShot();
216
+ const done = () => (savedOnly ? T.savedOnly : response.status === 201 ? T.saved : T.sent);
217
+ showMessage(() => done(), savedOnly);
218
+ setStatus(done(), savedOnly);
219
+ store.setPopover({ closeTimer: win.setTimeout(closePopover, savedOnly ? 2500 : 1200) });
220
+ } catch (error) {
221
+ if (state.pick !== pick) return;
222
+ els.send.disabled = false;
223
+ showMessage(() => T.notSent(error.message), true);
224
+ }
225
+ });
226
+
227
+ /** A new language: the message on screen, when it is the canvas's own wording (the rest of the box is keyed markup). */
228
+ function relabel() {
229
+ if (!worded || els.message.getAttribute("data-gd-message-owner") !== "comment") return;
230
+ els.message.textContent = worded();
231
+ }
232
+
233
+ return { relabel, readPick, openPopover, closePopover };
234
+ }