@gloom-sh/terminal 0.20.4 → 0.20.6

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 (316) hide show
  1. package/README.md +3 -1
  2. package/README.zh-CN.md +1 -1
  3. package/bin/gloom +9 -0
  4. package/bin/without-bun.cjs +98 -0
  5. package/package.json +4 -1
  6. package/src/api-client/data.ts +148 -37
  7. package/src/api-client/hk-tenders.ts +59 -0
  8. package/src/api-client/index.ts +1 -0
  9. package/src/api-client/types/econ.ts +30 -0
  10. package/src/api-client/yield-curves.ts +1 -1
  11. package/src/app/global-shortcuts.ts +4 -1
  12. package/src/app/keybindings/actions.ts +6 -0
  13. package/src/app/keybindings/config.ts +2 -1
  14. package/src/app/keybindings/index.ts +1 -0
  15. package/src/app/keybindings/labels.ts +6 -1
  16. package/src/app/keybindings/resolve.ts +23 -4
  17. package/src/app/keybindings/terminal-keys.ts +35 -0
  18. package/src/app/pane-runtime/index.tsx +2 -2
  19. package/src/app/pane-runtime/ticker-open-runtime.ts +68 -40
  20. package/src/app.tsx +18 -13
  21. package/src/architecture/floating-promise-allowlist.json +313 -0
  22. package/src/architecture/ui-literals-allowlist.json +1 -1
  23. package/src/capabilities/chart-series.ts +27 -1
  24. package/src/cli/commands/keybindings.ts +5 -5
  25. package/src/cli/commands/market.ts +238 -57
  26. package/src/cli/commands/news-search.ts +81 -14
  27. package/src/cli/commands/overview.ts +27 -6
  28. package/src/cli/commands/remote.ts +16 -17
  29. package/src/cli/commands/system.ts +1 -1
  30. package/src/cli/commands/ticker.ts +3 -1
  31. package/src/cli/early-command.ts +2 -0
  32. package/src/cli/errors.ts +10 -1
  33. package/src/cli/fx-forward.ts +89 -7
  34. package/src/cli/fx-pair.ts +1 -1
  35. package/src/cli/fx-quote-rate.ts +23 -0
  36. package/src/cli/glossary.ts +19 -5
  37. package/src/cli/help.ts +1 -0
  38. package/src/cli/history-rows.ts +5 -3
  39. package/src/cli/index-roots.ts +5 -4
  40. package/src/cli/index.ts +40 -3
  41. package/src/cli/known-gaps.ts +38 -9
  42. package/src/cli/listing-arg.ts +17 -5
  43. package/src/cli/name-entries.ts +5 -1
  44. package/src/cli/not-a-ticker.ts +4 -0
  45. package/src/cli/options.ts +52 -3
  46. package/src/cli/output-file.ts +5 -3
  47. package/src/cli/pane-functions/catalog.ts +15 -0
  48. package/src/cli/pane-functions/function-help.ts +4 -4
  49. package/src/cli/pane-functions/headless.ts +9 -4
  50. package/src/cli/pane-functions/index.ts +6 -4
  51. package/src/cli/pane-functions/resolver.ts +2 -2
  52. package/src/cli/result.ts +21 -2
  53. package/src/cli/spreadsheet-hint.ts +7 -3
  54. package/src/cli/treasury-yields.ts +5 -3
  55. package/src/components/chart/composite/legend.tsx +40 -2
  56. package/src/components/command-bar/pane-settings.ts +2 -2
  57. package/src/components/command-bar/routes/root/results.ts +6 -2
  58. package/src/components/command-bar/workflow/tickers.ts +2 -2
  59. package/src/components/data-table/view.tsx +9 -2
  60. package/src/components/input-search-bar.tsx +9 -2
  61. package/src/components/layout/pane/header.tsx +2 -0
  62. package/src/components/layout/shell/pane/capture.ts +4 -1
  63. package/src/components/layout/status-bar.tsx +6 -1
  64. package/src/components/onboarding/first-run-workspace.ts +44 -2
  65. package/src/components/onboarding/onboarding-frame.tsx +11 -2
  66. package/src/components/onboarding/onboarding-keyboard.ts +16 -0
  67. package/src/components/onboarding/onboarding-wizard.tsx +8 -8
  68. package/src/components/onboarding/portfolio-step/positions-panel.tsx +62 -1
  69. package/src/components/onboarding/use-onboarding-progress.ts +12 -4
  70. package/src/components/pane-settings-dialog/desktop.tsx +2 -2
  71. package/src/components/pane-settings-dialog/tui.tsx +2 -2
  72. package/src/components/pane-settings-dialog/value.ts +6 -0
  73. package/src/components/pane-settings-dialog.tsx +3 -3
  74. package/src/components/reader/detail-reader.tsx +4 -0
  75. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  76. package/src/components/ui/data-table/opentui/model.ts +8 -6
  77. package/src/components/ui/data-table/types.ts +6 -1
  78. package/src/components/ui/index.ts +1 -1
  79. package/src/components/ui/page-stack-view.tsx +3 -0
  80. package/src/components/ui/pane-link-chip.tsx +269 -54
  81. package/src/components/ui/query-bar.tsx +2 -1
  82. package/src/components/ui/table-layout.ts +38 -1
  83. package/src/components/ui/tabs.tsx +97 -19
  84. package/src/core/state/app/layout-reducer.ts +7 -0
  85. package/src/core/state/app/layout.ts +44 -7
  86. package/src/core/state/app/state.ts +1 -1
  87. package/src/core/state/app/types.ts +22 -2
  88. package/src/docs/snapshot.json +30 -13
  89. package/src/market-data/depositary-pair.ts +5 -3
  90. package/src/market-data/market/change-basis.ts +9 -5
  91. package/src/market-data/market/dated-previous-close.ts +147 -17
  92. package/src/market-data/market/status.ts +17 -1
  93. package/src/market-data/quotes/contributions.ts +2 -0
  94. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  95. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  96. package/src/plugins/builtin/analytics/risk-client.ts +10 -4
  97. package/src/plugins/builtin/analytics/risk-episodes.ts +5 -4
  98. package/src/plugins/builtin/analytics/risk-headless.ts +4 -2
  99. package/src/plugins/builtin/analytics/risk-sectors.ts +91 -0
  100. package/src/plugins/builtin/awards/index.tsx +1 -1
  101. package/src/plugins/builtin/backtest/headless.ts +1 -1
  102. package/src/plugins/builtin/buildout/index.tsx +1 -0
  103. package/src/plugins/builtin/catalysts/index.tsx +2 -2
  104. package/src/plugins/builtin/cds/headless.ts +4 -0
  105. package/src/plugins/builtin/cds/model.ts +0 -6
  106. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  107. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  108. package/src/plugins/builtin/chart-composer/headless.ts +4 -2
  109. package/src/plugins/builtin/chart-composer/index.tsx +1 -0
  110. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  111. package/src/plugins/builtin/chat/content/composer.tsx +5 -4
  112. package/src/plugins/builtin/chat/content/index.tsx +12 -2
  113. package/src/plugins/builtin/chat/content/layout-metrics.ts +3 -3
  114. package/src/plugins/builtin/chat/content/open-targets.ts +3 -3
  115. package/src/plugins/builtin/chat/layout.ts +5 -2
  116. package/src/plugins/builtin/chat/message/pane-chip.tsx +61 -40
  117. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  118. package/src/plugins/builtin/chat/pane-links/previews.ts +51 -5
  119. package/src/plugins/builtin/chat/pane-links/share-card.ts +36 -0
  120. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  121. package/src/plugins/builtin/cloud/askg/tool-display.ts +1 -0
  122. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +5 -3
  123. package/src/plugins/builtin/commodity-balances/index.tsx +1 -0
  124. package/src/plugins/builtin/company-attention/index.tsx +1 -1
  125. package/src/plugins/builtin/company-kpis/headless.ts +3 -1
  126. package/src/plugins/builtin/company-kpis/index.tsx +2 -2
  127. package/src/plugins/builtin/cot/index.tsx +1 -1
  128. package/src/plugins/builtin/cpi/index.tsx +1 -1
  129. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  130. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  131. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  132. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  133. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  134. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  135. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  136. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  137. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  138. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  139. package/src/plugins/builtin/crypto-board/index.tsx +1 -0
  140. package/src/plugins/builtin/dividend-yield/index.tsx +1 -0
  141. package/src/plugins/builtin/doe/index.tsx +1 -1
  142. package/src/plugins/builtin/earnings-calls/headless.ts +5 -1
  143. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  144. package/src/plugins/builtin/econ/calendar-model.ts +115 -8
  145. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  146. package/src/plugins/builtin/econ/fred-catalog.ts +3 -1
  147. package/src/plugins/builtin/econ/index.tsx +42 -8
  148. package/src/plugins/builtin/econ/types.ts +3 -0
  149. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  150. package/src/plugins/builtin/econ-statistics/pane.tsx +6 -0
  151. package/src/plugins/builtin/estimate-revisions/index.tsx +1 -0
  152. package/src/plugins/builtin/executives/index.tsx +1 -0
  153. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  154. package/src/plugins/builtin/fixed-income/index.tsx +3 -0
  155. package/src/plugins/builtin/futures-curve/headless.ts +3 -3
  156. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  157. package/src/plugins/builtin/futures-curve/model.ts +18 -0
  158. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  159. package/src/plugins/builtin/gpu/index.tsx +1 -1
  160. package/src/plugins/builtin/help/functions-table.tsx +1 -1
  161. package/src/plugins/builtin/help/index.tsx +11 -1
  162. package/src/plugins/builtin/help/keybindings-editor.tsx +7 -3
  163. package/src/plugins/builtin/holders/index.tsx +1 -0
  164. package/src/plugins/builtin/holders/report-header.ts +2 -2
  165. package/src/plugins/builtin/insider/index.tsx +1 -0
  166. package/src/plugins/builtin/iv-history/index.tsx +1 -1
  167. package/src/plugins/builtin/jobs/index.tsx +1 -0
  168. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  169. package/src/plugins/builtin/macro-day/index.tsx +1 -1
  170. package/src/plugins/builtin/macro-day/model.ts +19 -3
  171. package/src/plugins/builtin/macro-day/pane.tsx +14 -9
  172. package/src/plugins/builtin/macro-day/releases.ts +25 -7
  173. package/src/plugins/builtin/market-valuation/index.tsx +1 -0
  174. package/src/plugins/builtin/market-valuation/pane.tsx +8 -0
  175. package/src/plugins/builtin/members/index.tsx +1 -1
  176. package/src/plugins/builtin/mna/index.tsx +1 -0
  177. package/src/plugins/builtin/news/index.tsx +1 -0
  178. package/src/plugins/builtin/news/wire/index.tsx +5 -1
  179. package/src/plugins/builtin/news/wire/news/detail-view.tsx +4 -0
  180. package/src/plugins/builtin/news/wire/news/list-search.ts +5 -2
  181. package/src/plugins/builtin/options/index.tsx +1 -0
  182. package/src/plugins/builtin/options-positioning/index.tsx +1 -0
  183. package/src/plugins/builtin/pe-band/index.tsx +1 -1
  184. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +25 -0
  185. package/src/plugins/builtin/portfolio-list/cli/render.ts +20 -3
  186. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  187. package/src/plugins/builtin/portfolio-list/headless.ts +15 -6
  188. package/src/plugins/builtin/power/index.tsx +1 -1
  189. package/src/plugins/builtin/realized-vol/index.tsx +1 -1
  190. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  191. package/src/plugins/builtin/research/headless.ts +10 -4
  192. package/src/plugins/builtin/research/index.tsx +4 -0
  193. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  194. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  195. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  196. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  197. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  198. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  199. package/src/plugins/builtin/research-search/index.tsx +1 -0
  200. package/src/plugins/builtin/research-search/pane.tsx +8 -0
  201. package/src/plugins/builtin/revenue-breakdown/index.tsx +1 -0
  202. package/src/plugins/builtin/reverse-dcf/index.tsx +1 -1
  203. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  204. package/src/plugins/builtin/scanner/headless.ts +52 -13
  205. package/src/plugins/builtin/seasonality/index.tsx +1 -1
  206. package/src/plugins/builtin/sec/index.tsx +1 -0
  207. package/src/plugins/builtin/series-inventory.ts +1 -1
  208. package/src/plugins/builtin/shared/scanner-capture.ts +11 -3
  209. package/src/plugins/builtin/shared/series-list-detail.tsx +5 -0
  210. package/src/plugins/builtin/short-interest/index.tsx +1 -0
  211. package/src/plugins/builtin/social-mentions/index.tsx +1 -1
  212. package/src/plugins/builtin/supply-chain/index.tsx +1 -0
  213. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  214. package/src/plugins/builtin/thirteenf/data.ts +43 -10
  215. package/src/plugins/builtin/thirteenf/headless.ts +55 -11
  216. package/src/plugins/builtin/thirteenf/model.ts +25 -9
  217. package/src/plugins/builtin/thirteenf/report-notes.ts +27 -6
  218. package/src/plugins/builtin/thirteenf/types.ts +2 -0
  219. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +1 -1
  220. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  221. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  222. package/src/plugins/builtin/ticker-detail/financials/model.ts +18 -2
  223. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +3 -3
  224. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +6 -6
  225. package/src/plugins/builtin/ticker-detail/headless.ts +24 -17
  226. package/src/plugins/builtin/ticker-detail/index.tsx +4 -0
  227. package/src/plugins/builtin/ticker-detail/overview/model.ts +6 -4
  228. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +6 -4
  229. package/src/plugins/builtin/time-sales/client.ts +9 -11
  230. package/src/plugins/builtin/time-sales/index.tsx +1 -1
  231. package/src/plugins/builtin/treasury-auctions/after.ts +267 -0
  232. package/src/plugins/builtin/treasury-auctions/cache.ts +54 -5
  233. package/src/plugins/builtin/treasury-auctions/client.ts +33 -2
  234. package/src/plugins/builtin/treasury-auctions/headless.ts +150 -22
  235. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  236. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  237. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  238. package/src/plugins/builtin/treasury-auctions/index.tsx +27 -4
  239. package/src/plugins/builtin/treasury-auctions/model.ts +264 -28
  240. package/src/plugins/builtin/treasury-auctions/pane.tsx +176 -41
  241. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +5 -2
  242. package/src/plugins/builtin/treasury-auctions/types.ts +7 -1
  243. package/src/plugins/builtin/vol-surface/index.tsx +1 -1
  244. package/src/plugins/builtin/world-venue-map/index.ts +1 -0
  245. package/src/plugins/builtin/yield-curve/curves.ts +10 -4
  246. package/src/plugins/builtin/yield-curve/headless.ts +6 -2
  247. package/src/plugins/builtin/yield-curve/index.tsx +3 -3
  248. package/src/plugins/builtin/yield-curve/series.ts +10 -0
  249. package/src/plugins/builtin/yield-curve/world.ts +3 -1
  250. package/src/portfolio/collection-name.ts +22 -0
  251. package/src/portfolio/column-values.ts +2 -1
  252. package/src/public/__snapshots__/public-api.test.ts.snap +4 -0
  253. package/src/public/remote.ts +7 -1
  254. package/src/remote/client.ts +191 -11
  255. package/src/remote/controller-utils.ts +13 -1
  256. package/src/remote/controller.ts +88 -26
  257. package/src/remote/endpoint.ts +24 -0
  258. package/src/remote/form.ts +59 -4
  259. package/src/remote/resources.ts +44 -18
  260. package/src/remote/schema.ts +21 -9
  261. package/src/remote/secrets.ts +12 -0
  262. package/src/remote/semantic-tree.tsx +14 -2
  263. package/src/remote/server.ts +2 -1
  264. package/src/remote/surface.tsx +192 -0
  265. package/src/remote/types.ts +5 -0
  266. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  267. package/src/renderers/dom/data-table/index.tsx +27 -9
  268. package/src/renderers/dom/data-table/row.tsx +2 -0
  269. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  270. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  271. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  272. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  273. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  274. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  275. package/src/renderers/opentui/host.tsx +6 -0
  276. package/src/series/standalone.ts +2 -2
  277. package/src/shares/api.ts +21 -4
  278. package/src/shares/item.ts +73 -0
  279. package/src/shares/pane-item.ts +205 -0
  280. package/src/shares/pane.ts +4 -0
  281. package/src/shares/payload.ts +9 -5
  282. package/src/sources/gloomberb-cloud/news.ts +2 -0
  283. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  284. package/src/sources/provider-router/cache.ts +3 -1
  285. package/src/sync/controller.ts +17 -2
  286. package/src/sync/other-window-tabs.ts +32 -1
  287. package/src/sync/react.ts +4 -4
  288. package/src/tickers/renamed-listings.ts +105 -0
  289. package/src/tickers/search/index.ts +103 -16
  290. package/src/time-series/bar-spacing.ts +33 -0
  291. package/src/time-series/base-series.ts +21 -3
  292. package/src/time-series/chart-bounds.ts +31 -0
  293. package/src/time-series/field-catalog.ts +17 -0
  294. package/src/time-series/fundamentals.ts +143 -11
  295. package/src/time-series/ice-credit.ts +32 -6
  296. package/src/time-series/resolve.ts +11 -7
  297. package/src/time-series/session-bar.ts +78 -9
  298. package/src/time-series/studies/formula.ts +53 -10
  299. package/src/time-series/studies/pair.ts +18 -7
  300. package/src/time-series/studies/units.ts +49 -2
  301. package/src/time-series/types.ts +12 -0
  302. package/src/types/desktop-window.ts +2 -0
  303. package/src/types/financials.ts +7 -0
  304. package/src/types/headless.ts +8 -0
  305. package/src/types/plugin-pane-settings.ts +2 -0
  306. package/src/types/plugin-panes.ts +22 -0
  307. package/src/utils/central-banks.ts +86 -1
  308. package/src/utils/cli-output.ts +6 -3
  309. package/src/utils/datetime-format.ts +12 -3
  310. package/src/utils/depositary-receipt.ts +28 -3
  311. package/src/utils/ebitda.ts +128 -0
  312. package/src/utils/format.ts +1 -1
  313. package/src/utils/fundamentals.ts +14 -0
  314. package/src/utils/max-drawdown.ts +97 -16
  315. package/src/utils/shell-word.ts +13 -0
  316. package/src/utils/untrusted-text.ts +29 -0
@@ -774,7 +774,8 @@ export function getColumnValue(
774
774
  // An export writes the date with it, as ISO: 16:49 alone says nothing of which day.
775
775
  const iso = new Date(time.time).toISOString();
776
776
  return {
777
- text: time.dateOnly ? formatShortDate(time.time, MONTH_DAY) : formatFeedTime(time.time, ctx.now, "—", { utc: true }),
777
+ // Every row names its day: a bare 00:47 beside Fri 21:00 reads as the same evening.
778
+ text: time.dateOnly ? formatShortDate(time.time, MONTH_DAY) : formatFeedTime(time.time, ctx.now, "—", { utc: true, dayToday: true }),
778
779
  value: time.dateOnly ? iso.slice(0, 10) : iso,
779
780
  };
780
781
  }
@@ -309,6 +309,10 @@ exports[`the runtime exports of every public subpath are the reviewed ones 1`] =
309
309
  "useViewport",
310
310
  ],
311
311
  "./remote": [
312
+ "RemoteAppAmbiguousError",
313
+ "RemoteAppError",
314
+ "RemoteAppNotRunningError",
315
+ "RemoteAppUnreachableError",
312
316
  "sendRemoteControlRequest",
313
317
  ],
314
318
  "./test-support": [
@@ -13,7 +13,13 @@
13
13
  * compile, which is the correct answer for a browser context.
14
14
  */
15
15
 
16
- export { sendRemoteControlRequest } from "../remote/client";
16
+ export {
17
+ RemoteAppAmbiguousError,
18
+ RemoteAppError,
19
+ RemoteAppNotRunningError,
20
+ RemoteAppUnreachableError,
21
+ sendRemoteControlRequest,
22
+ } from "../remote/client";
17
23
  export type { SendRemoteControlRequestOptions } from "../remote/client";
18
24
  export type {
19
25
  RemoteAppKind,
@@ -1,24 +1,204 @@
1
- import type { RemoteAppKind, RemoteControlRequest, RemoteControlResponse } from "./types";
2
- import { readRemoteEndpoint } from "./endpoint";
1
+ import type { RemoteAppKind, RemoteControlRequest, RemoteControlResponse, RemoteEndpoint } from "./types";
2
+ import { currentPidNamespace, inNestedPidNamespace, readRemoteEndpoint, removeRemoteEndpointFiles } from "./endpoint";
3
+ import { isNetworkFailure } from "../utils/network-failure";
3
4
 
4
5
  export interface SendRemoteControlRequestOptions {
5
6
  dataDir: string;
6
7
  appKind?: RemoteAppKind;
7
8
  }
8
9
 
10
+ const APP_NAMES: Record<RemoteAppKind, string> = { tui: "terminal", desktop: "desktop" };
11
+ /** How long the app's health answer may take before it counts as unreachable; a busy app still answers well within it. */
12
+ const HEALTH_TIMEOUT_MS = 5_000;
13
+
14
+ /** Why no app took the request, with what to do about it in `details`. `code` is what `--json` reports. */
15
+ export class RemoteAppError extends Error {
16
+ readonly code: string;
17
+ readonly details: string;
18
+
19
+ constructor(code: string, message: string, details: string) {
20
+ super(message);
21
+ this.name = "RemoteAppError";
22
+ this.code = code;
23
+ this.details = details;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * No app of this profile runs: none was started, or the one that wrote the
29
+ * endpoint file has exited without a clean quit (its terminal closed, it was
30
+ * killed). Says how to start one.
31
+ */
32
+ export class RemoteAppNotRunningError extends RemoteAppError {
33
+ constructor(appKind?: RemoteAppKind, otherKind?: RemoteAppKind) {
34
+ super(
35
+ "app_not_running",
36
+ appKind ? `The Gloom ${APP_NAMES[appKind]} app is not running.` : "No Gloom app is running.",
37
+ otherKind
38
+ ? `The ${APP_NAMES[otherKind]} app is: pass --app ${otherKind}, or leave --app out.`
39
+ : appKind === "desktop"
40
+ ? "Open the Gloom desktop app, then try again."
41
+ : appKind === "tui"
42
+ ? "Start it with `gloom` in another terminal, then try again."
43
+ : "Start one with `gloom` in another terminal or open the desktop app, then try again.",
44
+ );
45
+ this.name = "RemoteAppNotRunningError";
46
+ }
47
+ }
48
+
49
+ /** Both apps run and neither is the one last started: the caller names which. */
50
+ export class RemoteAppAmbiguousError extends RemoteAppError {
51
+ constructor() {
52
+ super("app_ambiguous", "The Gloom terminal and desktop apps are both running.", "Pass --app tui or --app desktop.");
53
+ this.name = "RemoteAppAmbiguousError";
54
+ }
55
+ }
56
+
57
+ /**
58
+ * An endpoint file names an app this process cannot reach, and nothing proves
59
+ * the app gone: a sandbox that blocks localhost or hides other processes looks
60
+ * the same from inside as an app that quit. The file is kept.
61
+ */
62
+ export class RemoteAppUnreachableError extends RemoteAppError {
63
+ constructor(endpoint: RemoteEndpoint, foreign: boolean) {
64
+ const address = `127.0.0.1:${endpoint.port}, where its endpoint file says it listens`;
65
+ super(
66
+ "app_unreachable",
67
+ `The Gloom ${APP_NAMES[endpoint.appKind] ?? "app"} app could not be reached.`,
68
+ `${foreign ? `What answers at ${address}, is not Gloom.` : `Nothing answered at ${address}.`} `
69
+ + "If this command runs in a sandbox, let it reach 127.0.0.1 or run it outside the sandbox. "
70
+ + "If Gloom has quit, start it again: the new app replaces the file.",
71
+ );
72
+ this.name = "RemoteAppUnreachableError";
73
+ }
74
+ }
75
+
76
+ /** Whether an endpoint's app is there: true, false, or null when this process cannot tell. */
77
+ function processAlive(endpoint: RemoteEndpoint): boolean | null {
78
+ // A process id is only meaningful in the namespace that issued it.
79
+ const own = currentPidNamespace();
80
+ const comparable = endpoint.pidNamespace !== undefined
81
+ ? endpoint.pidNamespace === own
82
+ // A file from an app that did not name its namespace: doubt the ids only inside a sandbox's or container's own.
83
+ : !inNestedPidNamespace();
84
+ if (!comparable || !Number.isInteger(endpoint.pid) || endpoint.pid <= 0) return null;
85
+ try {
86
+ process.kill(endpoint.pid, 0);
87
+ return true;
88
+ } catch (error) {
89
+ const code = (error as NodeJS.ErrnoException).code;
90
+ // One owned by another user, or that a sandbox will not let this process signal, still runs.
91
+ return code === "ESRCH" ? false : code === "EPERM" ? true : null;
92
+ }
93
+ }
94
+
95
+ function connectionRefused(error: unknown): boolean {
96
+ const codes = [error, (error as { cause?: unknown } | null)?.cause]
97
+ .map((entry) => (entry as { code?: unknown } | null | undefined)?.code);
98
+ return codes.includes("ConnectionRefused") || codes.includes("ECONNREFUSED");
99
+ }
100
+
101
+ /** Gloom answered; the port refused; the connection failed some other way (a sandbox, a timeout); something else answered. */
102
+ type Health = "gloom" | "refused" | "failed" | "foreign";
103
+
104
+ /** Asks the endpoint's port, without the token, whether a Gloom app answers there. */
105
+ async function probeHealth(endpoint: RemoteEndpoint): Promise<Health> {
106
+ try {
107
+ const response = await fetch(`http://127.0.0.1:${endpoint.port}/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) });
108
+ const body = await response.json().catch(() => {
109
+ // Intentional ignore: an answer that is not JSON is not Gloom's, which the null below says.
110
+ return null;
111
+ }) as { ok?: unknown } | null;
112
+ return response.ok && body?.ok === true ? "gloom" : "foreign";
113
+ } catch (error) {
114
+ return connectionRefused(error) ? "refused" : "failed";
115
+ }
116
+ }
117
+
118
+ type EndpointState =
119
+ | { kind: "running"; endpoint: RemoteEndpoint }
120
+ | { kind: "unreachable"; endpoint: RemoteEndpoint; foreign: boolean }
121
+ | { kind: "gone" };
122
+
123
+ /** Reads the endpoint files and probes each app once, however many files name it. */
124
+ function endpointReader(dataDir: string) {
125
+ const states = new Map<string, Promise<EndpointState>>();
126
+
127
+ const classify = async (endpoint: RemoteEndpoint): Promise<EndpointState> => {
128
+ const health = await probeHealth(endpoint);
129
+ if (health === "gloom") return { kind: "running", endpoint };
130
+ // Only proof on both counts removes the file: the app's process is gone, and its port refuses.
131
+ if (health === "refused" && processAlive(endpoint) === false) {
132
+ await removeRemoteEndpointFiles(dataDir, endpoint).catch(() => { /* Intentional ignore: a file another process removed or replaced first is not ours to clean. */ });
133
+ return { kind: "gone" };
134
+ }
135
+ return { kind: "unreachable", endpoint, foreign: health === "foreign" };
136
+ };
137
+
138
+ return async (appKind?: RemoteAppKind): Promise<EndpointState> => {
139
+ let endpoint: RemoteEndpoint;
140
+ try {
141
+ endpoint = await readRemoteEndpoint(dataDir, appKind);
142
+ } catch {
143
+ // Intentional ignore: a file that is absent, or cut short by an app that died writing it, names no app to reach.
144
+ return { kind: "gone" };
145
+ }
146
+ const key = `${endpoint.pid}:${endpoint.port}:${endpoint.token}`;
147
+ let state = states.get(key);
148
+ if (!state) states.set(key, state = classify(endpoint));
149
+ return state;
150
+ };
151
+ }
152
+
153
+ function unreachable(state: Extract<EndpointState, { kind: "unreachable" }>): RemoteAppUnreachableError {
154
+ return new RemoteAppUnreachableError(state.endpoint, state.foreign);
155
+ }
156
+
157
+ /**
158
+ * The running app to send to: the one asked for, else the one started last
159
+ * (`remote-control.json`), else the only one of the two still running. An
160
+ * endpoint file is removed only when its process is gone and its port refuses.
161
+ */
162
+ export async function resolveRemoteEndpoint(dataDir: string, appKind?: RemoteAppKind): Promise<RemoteEndpoint> {
163
+ const read = endpointReader(dataDir);
164
+ if (appKind) {
165
+ const state = await read(appKind);
166
+ if (state.kind === "running") return state.endpoint;
167
+ if (state.kind === "unreachable") throw unreachable(state);
168
+ const other: RemoteAppKind = appKind === "tui" ? "desktop" : "tui";
169
+ throw new RemoteAppNotRunningError(appKind, (await read(other)).kind === "running" ? other : undefined);
170
+ }
171
+ const latest = await read();
172
+ if (latest.kind === "running") return latest.endpoint;
173
+ const states = await Promise.all([read("tui"), read("desktop")]);
174
+ const running = states.filter((state) => state.kind === "running");
175
+ if (running.length > 1) throw new RemoteAppAmbiguousError();
176
+ if (running[0]) return running[0].endpoint;
177
+ const blocked = [latest, ...states].find((state) => state.kind === "unreachable");
178
+ if (blocked) throw unreachable(blocked);
179
+ throw new RemoteAppNotRunningError();
180
+ }
181
+
9
182
  export async function sendRemoteControlRequest(
10
183
  request: RemoteControlRequest,
11
184
  options: SendRemoteControlRequestOptions,
12
185
  ): Promise<RemoteControlResponse> {
13
- const endpoint = await readRemoteEndpoint(options.dataDir, options.appKind);
14
- const response = await fetch(`http://127.0.0.1:${endpoint.port}/rpc`, {
15
- method: "POST",
16
- headers: {
17
- authorization: `Bearer ${endpoint.token}`,
18
- "content-type": "application/json",
19
- },
20
- body: JSON.stringify(request),
21
- });
186
+ const endpoint = await resolveRemoteEndpoint(options.dataDir, options.appKind);
187
+ let response: Response;
188
+ try {
189
+ response = await fetch(`http://127.0.0.1:${endpoint.port}/rpc`, {
190
+ method: "POST",
191
+ headers: {
192
+ authorization: `Bearer ${endpoint.token}`,
193
+ "content-type": "application/json",
194
+ },
195
+ body: JSON.stringify(request),
196
+ });
197
+ } catch (error) {
198
+ // It answered its health check a moment ago; the next call finds out whether it quit.
199
+ if (!isNetworkFailure(error)) throw error;
200
+ throw new RemoteAppUnreachableError(endpoint, false);
201
+ }
22
202
  const payload = await response.json() as RemoteControlResponse;
23
203
  if (!response.ok && payload.ok !== false) {
24
204
  return {
@@ -77,11 +77,23 @@ function panePlacement(layout: LayoutConfig, instanceId: string): "docked" | "fl
77
77
  }
78
78
 
79
79
  export function paneSnapshot(state: AppState, pane: PaneInstanceConfig) {
80
+ return {
81
+ ...paneSummary(state, pane),
82
+ runtimeState: state.paneState[pane.instanceId] ?? {},
83
+ };
84
+ }
85
+
86
+ /**
87
+ * A pane as the snapshot and every call's answer list it: where it is and
88
+ * whether it has focus, without its runtime state, which can hold everything
89
+ * it loaded (a news pane's stories). app://panes and app://pane-state/{paneId}
90
+ * carry that.
91
+ */
92
+ export function paneSummary(state: AppState, pane: PaneInstanceConfig) {
80
93
  return {
81
94
  ...pane,
82
95
  placement: panePlacement(state.config.layout, pane.instanceId),
83
96
  focused: state.focusedPaneId === pane.instanceId,
84
- runtimeState: state.paneState[pane.instanceId] ?? {},
85
97
  };
86
98
  }
87
99
 
@@ -37,6 +37,7 @@ import type {
37
37
  } from "./types";
38
38
  import type { RemoteUiRegistry } from "./semantic-tree";
39
39
  import { commandBarResultsFromNodes, isCommandBarInputNode } from "./command-bar";
40
+ import { commandBarBlockedBy, coveredByWarning, formNodes, formSnapshot, noDialogToClose } from "./form";
40
41
  import { findCommandBarResult, findMatchingUiNode } from "./matching";
41
42
  import { REMOTE_AGENT_HELP, REMOTE_OPERATIONS, remoteControlSchema } from "./schema";
42
43
  import {
@@ -100,6 +101,26 @@ interface AppRemoteControllerOptions {
100
101
  const PLANNED_OPERATIONS = new Set(["watchlist.add", "watchlist.remove"]);
101
102
  /** Reads change nothing, so their answer carries no layout or command-bar state. */
102
103
  const READ_OPERATIONS = new Set(REMOTE_OPERATIONS.filter((entry) => entry.sideEffectLevel === "none").map((entry) => entry.id));
104
+ /**
105
+ * Calls that act on the dialog on top, or on nothing drawn behind it: made
106
+ * while a form or the setup covers the app, they are not reported as hidden.
107
+ * `ui.invoke` and `ui.invokeMatching` are, when the node they pressed is in a pane.
108
+ */
109
+ const NOT_BEHIND_A_DIALOG = new Set([
110
+ "app.closeDialog",
111
+ "app.closeCommandBar",
112
+ "app.notify",
113
+ // What the pane settings dialog edits, and how an agent edits it while it is open.
114
+ "pane.setSetting",
115
+ "pane.setState",
116
+ "capability.invoke",
117
+ "watchlist.add",
118
+ "watchlist.remove",
119
+ // Another window: nothing in this one covers it.
120
+ "desktop.popOutPane",
121
+ "desktop.focusDetachedPane",
122
+ "desktop.closeDetachedPane",
123
+ ]);
103
124
 
104
125
  // A command with a wizard closes the bar and opens its form, so every call says whether one is open.
105
126
  const DEFAULT_MUTATION_INCLUDE: RemoteStateInclude[] = ["app", "layout", "panes", "commandBar", "form"];
@@ -269,11 +290,17 @@ export function createAppRemoteController({
269
290
  }
270
291
  };
271
292
 
293
+ /** The open form, confirm or setup, as `app://form` reads it. */
294
+ const currentForm = () => formSnapshot(formNodes(uiRegistry), isDialogOpen());
295
+
272
296
  const openCommandBar = async (input: Record<string, unknown>): Promise<unknown> => {
273
297
  const mode = optionalString(input, "mode") ?? "command";
274
298
  const query = optionalString(input, "query") ?? "";
275
299
  // The bar would open over the dialog without its keys.
276
300
  if (isDialogOpen()) throw new Error("A dialog is open. Close it first with app.closeDialog.");
301
+ // The setup holds the keys a person would open the bar with, and the bar would open behind it.
302
+ const blocked = commandBarBlockedBy(currentForm());
303
+ if (blocked) throw new Error(blocked);
277
304
  if (getState().commandBarOpen) {
278
305
  dispatch({ type: "SET_COMMAND_BAR", open: false });
279
306
  await afterMutation();
@@ -438,7 +465,7 @@ export function createAppRemoteController({
438
465
  dispatch({ type: "SET_COMMAND_BAR", open: false });
439
466
  return getAfterMutationSummary();
440
467
  case "app.closeDialog":
441
- if (!closeTopmostDialog()) throw new Error("No dialog is open.");
468
+ if (!closeTopmostDialog()) throw new Error(noDialogToClose(currentForm()));
442
469
  return getAfterMutationSummary();
443
470
  case "app.setCommandBarQuery":
444
471
  await setVisibleCommandBarQuery(stringInput(input, "query"));
@@ -663,6 +690,32 @@ export function createAppRemoteController({
663
690
  }
664
691
  };
665
692
 
693
+ /**
694
+ * Whether a call is made on the app behind an open form or setup rather than
695
+ * on the form itself: a UI node is behind it when it is drawn in a pane.
696
+ */
697
+ const actsBehindDialog = (operation: string, rawInput: unknown): boolean => {
698
+ if (READ_OPERATIONS.has(operation) || NOT_BEHIND_A_DIALOG.has(operation)) return false;
699
+ if (operation !== "ui.invoke" && operation !== "ui.invokeMatching") return true;
700
+ const input = asRecord(rawInput);
701
+ const nodes = uiRegistry?.snapshot() ?? [];
702
+ const node = operation === "ui.invoke"
703
+ ? nodes.find((entry) => entry.id === input.nodeId)
704
+ : findMatchingUiNode(nodes, input);
705
+ return !!node?.paneId;
706
+ };
707
+
708
+ /**
709
+ * Runs a change, and says so when a form or the setup covered the app before
710
+ * and after it: the change happened behind it, where the person cannot see it.
711
+ */
712
+ const withCoverWarning = async (behind: boolean, run: () => Promise<RemoteControlResponse>): Promise<RemoteControlResponse> => {
713
+ const before = behind ? coveredByWarning(currentForm()) : null;
714
+ const response = await run();
715
+ if (!before || !response.ok || !coveredByWarning(currentForm())) return response;
716
+ return { ...response, warnings: [...response.warnings ?? [], before] };
717
+ };
718
+
666
719
  /** `context` comes from in-process callers only; the local endpoint never passes one. */
667
720
  const handle = async (request: RemoteControlRequest, context: RemoteCallContext = {}): Promise<RemoteControlResponse> => {
668
721
  try {
@@ -678,27 +731,31 @@ export function createAppRemoteController({
678
731
  case "data":
679
732
  return ok(await queryMarketData(request));
680
733
  case "call": {
681
- const data = await call(request.operation, request.input, request.dryRun, context);
682
- const defaults = request.dryRun || READ_OPERATIONS.has(request.operation) ? [] : DEFAULT_MUTATION_INCLUDE;
683
- return ok(data, undefined, buildIncludedState(request.include, defaults));
684
- }
685
- case "patch": {
686
- const target = patchTarget(request.resource);
687
- const currentRev = revisionFor(target.value);
688
- if (request.expectRev && request.expectRev !== currentRev) {
689
- throw new Error(`Revision mismatch for ${request.resource}: expected ${request.expectRev}, got ${currentRev}.`);
690
- }
691
- const nextValue = applyJsonPatch(target.value, request.patch as RemoteJsonPatchOperation[]);
692
- if (!request.dryRun) {
693
- await target.apply(nextValue);
694
- await afterMutation();
695
- }
696
- return ok(
697
- nextValue,
698
- revisionFor(nextValue),
699
- buildIncludedState(request.include, request.dryRun ? [] : DEFAULT_MUTATION_INCLUDE),
700
- );
734
+ const behind = !request.dryRun && actsBehindDialog(request.operation, request.input);
735
+ return await withCoverWarning(behind, async () => {
736
+ const data = await call(request.operation, request.input, request.dryRun, context);
737
+ const defaults = request.dryRun || READ_OPERATIONS.has(request.operation) ? [] : DEFAULT_MUTATION_INCLUDE;
738
+ return ok(data, undefined, buildIncludedState(request.include, defaults));
739
+ });
701
740
  }
741
+ case "patch":
742
+ return await withCoverWarning(!request.dryRun, async () => {
743
+ const target = patchTarget(request.resource);
744
+ const currentRev = revisionFor(target.value);
745
+ if (request.expectRev && request.expectRev !== currentRev) {
746
+ throw new Error(`Revision mismatch for ${request.resource}: expected ${request.expectRev}, got ${currentRev}.`);
747
+ }
748
+ const nextValue = applyJsonPatch(target.value, request.patch as RemoteJsonPatchOperation[]);
749
+ if (!request.dryRun) {
750
+ await target.apply(nextValue);
751
+ await afterMutation();
752
+ }
753
+ return ok(
754
+ nextValue,
755
+ revisionFor(nextValue),
756
+ buildIncludedState(request.include, request.dryRun ? [] : DEFAULT_MUTATION_INCLUDE),
757
+ );
758
+ });
702
759
  case "batch": {
703
760
  const responses = [];
704
761
  const haltOnError = request.haltOnError !== false;
@@ -718,11 +775,16 @@ export function createAppRemoteController({
718
775
  }
719
776
  }
720
777
  if (request.settle === "afterBatch") await afterMutation();
721
- return ok({
722
- ok: responses.every((response) => response.ok),
723
- haltedAt,
724
- responses,
725
- }, undefined, buildIncludedState(request.include, request.dryRun ? [] : DEFAULT_MUTATION_INCLUDE));
778
+ // Each step's warnings, once each, where a client prints the batch's own.
779
+ const warnings = [...new Set(responses.flatMap((response) => response.ok ? response.warnings ?? [] : []))];
780
+ return {
781
+ ...ok({
782
+ ok: responses.every((response) => response.ok),
783
+ haltedAt,
784
+ responses,
785
+ }, undefined, buildIncludedState(request.include, request.dryRun ? [] : DEFAULT_MUTATION_INCLUDE)),
786
+ ...(warnings.length > 0 ? { warnings } : {}),
787
+ };
726
788
  }
727
789
  default:
728
790
  throw new Error(`Unknown remote request type: ${(request as { type?: unknown }).type}`);
@@ -1,3 +1,4 @@
1
+ import { readFileSync, readlinkSync } from "fs";
1
2
  import { readFile, rename, rm } from "fs/promises";
2
3
  import { dirname, join } from "path";
3
4
  import { makePrivateDir, writePrivateFile } from "../utils/private-files";
@@ -9,6 +10,29 @@ export function remoteEndpointPath(dataDir: string, appKind?: RemoteAppKind): st
9
10
  return join(dataDir, appKind ? `remote-control.${appKind}.json` : DEFAULT_ENDPOINT_FILE);
10
11
  }
11
12
 
13
+ /** This process's process-id namespace on Linux (`pid:[4026531836]`); undefined elsewhere, where there are none. */
14
+ export function currentPidNamespace(): string | undefined {
15
+ if (process.platform !== "linux") return undefined;
16
+ try {
17
+ return readlinkSync("/proc/self/ns/pid");
18
+ } catch {
19
+ // Intentional ignore: without /proc the namespace is unknown, and the caller treats it as such.
20
+ return undefined;
21
+ }
22
+ }
23
+
24
+ /** Whether this process runs in a process-id namespace nested in another, as a sandbox's or a container's. */
25
+ export function inNestedPidNamespace(): boolean {
26
+ if (process.platform !== "linux") return false;
27
+ try {
28
+ const line = /^NSpid:\s*(.+)$/m.exec(readFileSync("/proc/self/status", "utf-8"))?.[1];
29
+ return !!line && line.trim().split(/\s+/).length > 1;
30
+ } catch {
31
+ // Intentional ignore: without /proc nothing says this process is nested, so its process ids are taken as they are.
32
+ return false;
33
+ }
34
+ }
35
+
12
36
  export async function readRemoteEndpoint(dataDir: string, appKind?: RemoteAppKind): Promise<RemoteEndpoint> {
13
37
  const raw = await readFile(remoteEndpointPath(dataDir, appKind), "utf-8");
14
38
  return JSON.parse(raw) as RemoteEndpoint;
@@ -1,11 +1,14 @@
1
+ import type { RemoteUiRegistry } from "./semantic-tree";
1
2
  import type { RemoteUiNodeSnapshot } from "./types";
2
3
 
3
4
  /**
4
5
  * The open form or confirm, read from the node the form modal registers: its
5
6
  * kind, title, fields with their values and options, error, pending state and
6
- * submit label, and the node that cancels or sends it. `covered` when another
7
- * dialog (a listing picker, a sign-in) sits over it. `{ open: false }` when
8
- * none is open, with `otherDialogOpen` while a dialog that is not a form (pane
7
+ * submit label, and the node that cancels or sends it. A full-window card
8
+ * such as the first-run setup reads the same way, as kind "setup" with its
9
+ * step and buttons (remote/surface.tsx). `covered` when another dialog (a
10
+ * listing picker, a sign-in) sits over it. `{ open: false }` when none is
11
+ * open, with `otherDialogOpen` while a dialog that is not a form (pane
9
12
  * settings) is.
10
13
  */
11
14
  export function formSnapshot(nodes: RemoteUiNodeSnapshot[], dialogOpen: boolean) {
@@ -15,6 +18,58 @@ export function formSnapshot(nodes: RemoteUiNodeSnapshot[], dialogOpen: boolean)
15
18
  return { open: true, nodeId: node.id, actions: node.actions, ...form, ...(covered === true ? { covered } : {}) };
16
19
  }
17
20
 
21
+ /** The nodes `formSnapshot` reads, without projecting the rest of the tree where the registry can. */
22
+ export function formNodes(registry: Pick<RemoteUiRegistry, "snapshot" | "snapshotRole"> | null | undefined): RemoteUiNodeSnapshot[] {
23
+ if (!registry) return [];
24
+ return registry.snapshotRole?.("form") ?? registry.snapshot();
25
+ }
26
+
27
+ /** The form on top: the last one opened that nothing covers, else the last one. */
18
28
  export function findFormNode(nodes: RemoteUiNodeSnapshot[]): RemoteUiNodeSnapshot | undefined {
19
- return nodes.filter((entry) => entry.role === "form" && entry.metadata?.scope === "form").at(-1);
29
+ const forms = nodes.filter((entry) => entry.role === "form" && entry.metadata?.scope === "form");
30
+ return forms.filter((entry) => entry.metadata?.covered !== true).at(-1) ?? forms.at(-1);
31
+ }
32
+
33
+ type FormState = Record<string, unknown>;
34
+
35
+ function isSetup(form: FormState): boolean {
36
+ return form.open === true && form.kind === "setup";
37
+ }
38
+
39
+ /** The open form by what it is and its title: `the setup dialog "What do you hold?"`. */
40
+ function formName(form: FormState): string {
41
+ const title = typeof form.title === "string" && form.title ? ` "${form.title}"` : "";
42
+ return isSetup(form) ? `the setup dialog${title}` : `the form${title}`;
43
+ }
44
+
45
+ function capitalized(text: string): string {
46
+ return text.charAt(0).toUpperCase() + text.slice(1);
47
+ }
48
+
49
+ /** What a call made while `form` is open did not reach: the app behind it. */
50
+ export function coveredByWarning(form: FormState): string | null {
51
+ if (form.open !== true) {
52
+ return form.otherDialogOpen === true
53
+ ? "A dialog is open over the app, so this change is behind it until the dialog closes (app.closeDialog)."
54
+ : null;
55
+ }
56
+ return isSetup(form)
57
+ ? `${capitalized(formName(form))} covers the app, so this change is behind it until setup is finished or skipped. app://form lists its fields and buttons.`
58
+ : `${capitalized(formName(form))} is open over the app, so this change is behind it until the form is sent or cancelled (app://form).`;
59
+ }
60
+
61
+ /** Why the command bar does not open while `form` is open, or null when nothing is. */
62
+ export function commandBarBlockedBy(form: FormState): string | null {
63
+ if (form.open !== true) return null;
64
+ return `${capitalized(formName(form))} covers the app, and the command bar would open behind it. `
65
+ + `${isSetup(form) ? "Finish or skip setup first" : "Send or cancel it first"}: app://form lists its fields and buttons.`;
66
+ }
67
+
68
+ /** Why app.closeDialog closed nothing: no dialog is open, and the setup is closed through its own buttons. */
69
+ export function noDialogToClose(form: FormState): string {
70
+ if (!isSetup(form)) return "No dialog is open.";
71
+ const skip = Array.isArray(form.actions) && form.actions.includes("cancel");
72
+ return skip
73
+ ? `No dialog is open over ${formName(form)}. Skip setup with ui.invokeMatching { role: 'form', action: 'cancel' }, or finish it with its buttons (app://form).`
74
+ : `No dialog is open over ${formName(form)}, and this step cannot skip the whole setup. Press its buttons (app://form lists them); Skip leaves a step without filling it.`;
20
75
  }