@gloom-sh/terminal 0.20.11 → 0.20.12

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 (242) hide show
  1. package/package.json +2 -1
  2. package/src/api-client/awards.ts +16 -0
  3. package/src/api-client/central-bank-rates.ts +5 -0
  4. package/src/api-client/data.ts +55 -2
  5. package/src/api-client/index.ts +18 -1
  6. package/src/api-client/request.ts +86 -3
  7. package/src/api-client/socket-connection.ts +12 -1
  8. package/src/api-client/socket.ts +21 -3
  9. package/src/api-client/supply-chain-graph.ts +4 -2
  10. package/src/api-client/supply-chain.ts +8 -0
  11. package/src/api-client/types/econ.ts +10 -7
  12. package/src/api-client/types/filings-and-calls.ts +8 -0
  13. package/src/app/global-shortcuts.ts +2 -1
  14. package/src/app/keybindings/actions.ts +19 -0
  15. package/src/app/pane-runtime/index.tsx +18 -3
  16. package/src/app/pane-runtime/layout-placement.ts +63 -0
  17. package/src/app/pane-runtime/ticker-open-runtime.ts +10 -2
  18. package/src/capabilities/chart-series.ts +4 -1
  19. package/src/cli/board-coins.ts +10 -1
  20. package/src/cli/commands/crypto-hints.ts +3 -2
  21. package/src/cli/commands/fred-series.ts +0 -54
  22. package/src/cli/commands/market.ts +209 -31
  23. package/src/cli/commands/overview.ts +47 -14
  24. package/src/cli/commands/search.ts +37 -8
  25. package/src/cli/commands/ticker.ts +15 -4
  26. package/src/cli/desktop-pane-shot.ts +27 -2
  27. package/src/cli/fx-quote-rate.ts +1 -1
  28. package/src/cli/glossary.ts +14 -5
  29. package/src/cli/history-catalog-series.ts +85 -0
  30. package/src/cli/index.ts +1 -1
  31. package/src/cli/list-progress.ts +45 -0
  32. package/src/cli/listing-arg.ts +71 -7
  33. package/src/cli/name-entries.ts +8 -4
  34. package/src/cli/not-a-ticker.ts +2 -2
  35. package/src/cli/pane-functions/freshness.ts +50 -3
  36. package/src/cli/pane-functions/index.ts +7 -4
  37. package/src/cli/pane-functions/market-session.ts +66 -14
  38. package/src/cli/pane-functions/options.ts +5 -0
  39. package/src/cli/pane-functions/resolver.ts +9 -2
  40. package/src/cli/pane-functions/screenshot-assessment.ts +28 -3
  41. package/src/cli/pane-functions/screenshot-types.ts +6 -0
  42. package/src/cli/quote-answer.ts +49 -10
  43. package/src/cli/quote-list-reads.ts +87 -0
  44. package/src/cli/report-tables.ts +70 -13
  45. package/src/cli/result.ts +24 -2
  46. package/src/cli/symbol-list.ts +31 -4
  47. package/src/cli/terminal-code-hints.ts +83 -0
  48. package/src/cli/ticker-resolution.ts +2 -1
  49. package/src/cli/treasury-yields.ts +5 -0
  50. package/src/components/command-bar/action-runtime.ts +2 -0
  51. package/src/components/command-bar/routing/launch-request.ts +2 -1
  52. package/src/components/command-bar/routing/navigation-state.ts +4 -2
  53. package/src/components/command-bar/workflow/types.ts +6 -0
  54. package/src/components/layout/detached-pane-shell.tsx +3 -0
  55. package/src/components/layout/double-escape-close.ts +34 -3
  56. package/src/components/layout/floating-pane.tsx +10 -4
  57. package/src/components/layout/pane/cycle-order.ts +66 -2
  58. package/src/components/layout/pane/header.tsx +140 -31
  59. package/src/components/layout/pane/sidebar.tsx +13 -5
  60. package/src/components/layout/pane/status-footer.ts +3 -1
  61. package/src/components/layout/shell/drag/runtime.ts +5 -0
  62. package/src/components/layout/shell/index.tsx +25 -0
  63. package/src/components/layout/shell/menu.ts +9 -0
  64. package/src/components/layout/shell/pane/actions.ts +36 -0
  65. package/src/components/layout/shell/pane/management-shortcuts.ts +27 -3
  66. package/src/components/layout/shell/pane-occlusion.ts +40 -0
  67. package/src/components/layout/shell/shortcuts.ts +17 -1
  68. package/src/components/layout/shell/terminal-pointer-runtime.ts +39 -6
  69. package/src/components/layout/shell/window-mode/index.ts +5 -16
  70. package/src/components/layout/shell/window-mode/overlays.tsx +3 -1
  71. package/src/components/market-board/index.tsx +14 -5
  72. package/src/components/metric-treemap/index.tsx +3 -1
  73. package/src/components/ui/button.tsx +48 -4
  74. package/src/components/ui/data-table/opentui/index.tsx +24 -9
  75. package/src/components/ui/data-table/types.ts +7 -0
  76. package/src/components/ui/inline-quick-add.tsx +19 -3
  77. package/src/components/ui/list-view.tsx +11 -5
  78. package/src/components/ui/query-bar.tsx +16 -1
  79. package/src/components/ui/selection-fill.ts +39 -0
  80. package/src/core/state/app/layout-reducer.ts +2 -1
  81. package/src/core/state/app/pane-choices.ts +68 -0
  82. package/src/core/state/app/state.ts +14 -6
  83. package/src/core/state/app/types.ts +8 -0
  84. package/src/layout/pane-manager/dock-tree.ts +19 -0
  85. package/src/layout/pane-manager/index.ts +3 -0
  86. package/src/market-data/market/freshness.ts +33 -0
  87. package/src/market-data/market/status.ts +5 -1
  88. package/src/market-data/quotes/contributions.ts +10 -0
  89. package/src/market-data/quotes/freshness.ts +19 -0
  90. package/src/market-data/quotes/live-valuation.ts +31 -4
  91. package/src/market-data/quotes/resolution.ts +4 -0
  92. package/src/market-data/quotes/time.ts +0 -14
  93. package/src/plugins/builtin/account-management/index.tsx +1 -0
  94. package/src/plugins/builtin/awards/detail.tsx +12 -4
  95. package/src/plugins/builtin/awards/headless.ts +29 -8
  96. package/src/plugins/builtin/awards/model.ts +36 -2
  97. package/src/plugins/builtin/awards/pane.tsx +7 -4
  98. package/src/plugins/builtin/broker-manager/index.tsx +1 -0
  99. package/src/plugins/builtin/broker-trading/index.tsx +1 -1
  100. package/src/plugins/builtin/central-bank-rates/headless.ts +6 -6
  101. package/src/plugins/builtin/central-bank-rates/index.tsx +1 -1
  102. package/src/plugins/builtin/central-bank-rates/model.ts +21 -3
  103. package/src/plugins/builtin/central-bank-rates/pane.tsx +15 -5
  104. package/src/plugins/builtin/chart-composer/headless.ts +5 -1
  105. package/src/plugins/builtin/chart-composer/pane.tsx +1 -0
  106. package/src/plugins/builtin/chat/content/handle-prompt.tsx +4 -0
  107. package/src/plugins/builtin/chat/controller/realtime.ts +17 -1
  108. package/src/plugins/builtin/chat/message/terminal.tsx +4 -1
  109. package/src/plugins/builtin/chat/sidebar.tsx +3 -4
  110. package/src/plugins/builtin/cloud/askg/pane.tsx +4 -0
  111. package/src/plugins/builtin/cloud/plugin.tsx +1 -0
  112. package/src/plugins/builtin/cloud/team/module.tsx +1 -0
  113. package/src/plugins/builtin/cloud/thesis/detail.tsx +9 -4
  114. package/src/plugins/builtin/commodity-balances/pane.tsx +13 -5
  115. package/src/plugins/builtin/company-kpis/model.ts +3 -3
  116. package/src/plugins/builtin/connections/index.ts +1 -0
  117. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +9 -5
  118. package/src/plugins/builtin/credit-boards/client.ts +5 -0
  119. package/src/plugins/builtin/credit-boards/headless.ts +1 -6
  120. package/src/plugins/builtin/credit-boards/model.ts +0 -6
  121. package/src/plugins/builtin/credit-boards/series.ts +19 -8
  122. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +9 -5
  123. package/src/plugins/builtin/crypto-etf-flows/headless.ts +23 -13
  124. package/src/plugins/builtin/crypto-etf-flows/pane.tsx +8 -3
  125. package/src/plugins/builtin/debt-maturities/headless.ts +16 -7
  126. package/src/plugins/builtin/debt-maturities/model.ts +9 -15
  127. package/src/plugins/builtin/debt-maturities/pane.tsx +9 -10
  128. package/src/plugins/builtin/earnings/board-model.ts +33 -4
  129. package/src/plugins/builtin/earnings/board.tsx +15 -3
  130. package/src/plugins/builtin/earnings/calendar.tsx +10 -6
  131. package/src/plugins/builtin/earnings/client.ts +0 -9
  132. package/src/plugins/builtin/earnings/headless.ts +10 -7
  133. package/src/plugins/builtin/earnings/history.tsx +21 -14
  134. package/src/plugins/builtin/earnings-calls/data.ts +24 -4
  135. package/src/plugins/builtin/earnings-calls/format.ts +23 -5
  136. package/src/plugins/builtin/earnings-calls/headless.ts +23 -3
  137. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  138. package/src/plugins/builtin/earnings-calls/model.ts +11 -1
  139. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -5
  140. package/src/plugins/builtin/econ/calendar-model.ts +27 -0
  141. package/src/plugins/builtin/econ/fred-catalog.ts +3 -0
  142. package/src/plugins/builtin/econ/index.tsx +9 -2
  143. package/src/plugins/builtin/econ-statistics/headless.ts +3 -1
  144. package/src/plugins/builtin/econ-statistics/index.tsx +1 -1
  145. package/src/plugins/builtin/fear-greed/headless.ts +16 -13
  146. package/src/plugins/builtin/fear-greed/pane.tsx +12 -4
  147. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  148. package/src/plugins/builtin/fx-matrix/index.tsx +30 -19
  149. package/src/plugins/builtin/insider/table.tsx +10 -7
  150. package/src/plugins/builtin/insider/tickers.tsx +1 -1
  151. package/src/plugins/builtin/iv-history/headless.ts +9 -8
  152. package/src/plugins/builtin/jobs/index.tsx +1 -0
  153. package/src/plugins/builtin/macro-day/headless.ts +3 -3
  154. package/src/plugins/builtin/macro-day/model.ts +1 -1
  155. package/src/plugins/builtin/macro-day/releases.ts +25 -16
  156. package/src/plugins/builtin/market-movers/index.tsx +20 -8
  157. package/src/plugins/builtin/market-movers/model.ts +5 -0
  158. package/src/plugins/builtin/market-movers/session-body.tsx +2 -1
  159. package/src/plugins/builtin/money-markets/headless.ts +12 -2
  160. package/src/plugins/builtin/money-markets/pane.tsx +10 -1
  161. package/src/plugins/builtin/options/view.tsx +1 -0
  162. package/src/plugins/builtin/options-positioning/pane.tsx +1 -1
  163. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -31
  164. package/src/plugins/builtin/portfolio-list/pane/index.tsx +6 -1
  165. package/src/plugins/builtin/portfolio-list/quick-add/index.tsx +22 -8
  166. package/src/plugins/builtin/portfolio-list/summary/index.tsx +6 -8
  167. package/src/plugins/builtin/portfolio-list/table.tsx +10 -1
  168. package/src/plugins/builtin/realized-vol/headless.ts +28 -2
  169. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  170. package/src/plugins/builtin/shared/source-footer.ts +70 -0
  171. package/src/plugins/builtin/short-interest/publications-pane.tsx +5 -1
  172. package/src/plugins/builtin/short-volume/pane.tsx +5 -1
  173. package/src/plugins/builtin/social-mentions/outliers.tsx +10 -1
  174. package/src/plugins/builtin/social-mentions/pane.tsx +7 -0
  175. package/src/plugins/builtin/supply-chain/client.ts +3 -1
  176. package/src/plugins/builtin/supply-chain/flow.tsx +25 -8
  177. package/src/plugins/builtin/supply-chain/graph-client.ts +1 -1
  178. package/src/plugins/builtin/supply-chain/graph-evidence.ts +1 -1
  179. package/src/plugins/builtin/supply-chain/graph-model.ts +12 -1
  180. package/src/plugins/builtin/supply-chain/graph-pane.tsx +9 -8
  181. package/src/plugins/builtin/supply-chain/graph.tsx +12 -6
  182. package/src/plugins/builtin/supply-chain/headless.ts +13 -7
  183. package/src/plugins/builtin/supply-chain/model.ts +68 -11
  184. package/src/plugins/builtin/supply-chain/pane.tsx +9 -6
  185. package/src/plugins/builtin/supply-chain/row-evidence.tsx +5 -5
  186. package/src/plugins/builtin/ticker-detail/overview/components.tsx +14 -1
  187. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +2 -0
  188. package/src/plugins/builtin/ticker-detail/pane.tsx +48 -24
  189. package/src/plugins/builtin/ticker-detail/quote-footer.ts +5 -0
  190. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +6 -3
  191. package/src/plugins/builtin/treasury-auctions/after.ts +50 -23
  192. package/src/plugins/builtin/treasury-auctions/cache.ts +23 -5
  193. package/src/plugins/builtin/treasury-auctions/headless.ts +226 -37
  194. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +11 -5
  195. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +27 -25
  196. package/src/plugins/builtin/treasury-auctions/hk.ts +60 -8
  197. package/src/plugins/builtin/treasury-auctions/index.tsx +3 -0
  198. package/src/plugins/builtin/treasury-auctions/keys.ts +27 -0
  199. package/src/plugins/builtin/treasury-auctions/like.ts +137 -0
  200. package/src/plugins/builtin/treasury-auctions/model.ts +100 -22
  201. package/src/plugins/builtin/treasury-auctions/pane.tsx +39 -11
  202. package/src/plugins/builtin/vol-surface/heat-grid.tsx +4 -2
  203. package/src/plugins/builtin/vol-surface/pane.tsx +5 -2
  204. package/src/plugins/runtime/index.tsx +1 -0
  205. package/src/plugins/runtime/state.ts +20 -0
  206. package/src/portfolio/column-values.ts +8 -2
  207. package/src/public/__snapshots__/public-api.test.ts.snap +5 -0
  208. package/src/public/react.ts +7 -0
  209. package/src/react/auto-refresh.ts +29 -0
  210. package/src/renderers/browser/deeplink-bridge.ts +24 -3
  211. package/src/renderers/dom/desktop/query-bar.tsx +229 -60
  212. package/src/renderers/dom/host/overflow-fade-px.ts +2 -0
  213. package/src/renderers/dom/host/overflow-fade.ts +1 -2
  214. package/src/renderers/dom/styles.css +25 -5
  215. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +2 -1
  216. package/src/series/types.ts +2 -0
  217. package/src/sources/gloomberb-cloud/fred-attribution.ts +86 -0
  218. package/src/sources/gloomberb-cloud/index.ts +25 -1
  219. package/src/sources/gloomberb-cloud/normalizers.ts +22 -3
  220. package/src/sources/provider-errors.ts +64 -1
  221. package/src/sources/provider-router/batches.ts +19 -0
  222. package/src/sources/provider-router/index.ts +7 -1
  223. package/src/state/app/context/index.tsx +24 -1
  224. package/src/state/pane-unsent-work.ts +47 -0
  225. package/src/test-support/shell-pane-keys.tsx +5 -0
  226. package/src/test-support/telemetry-guard.ts +83 -0
  227. package/src/test-support/test-env.ts +12 -0
  228. package/src/theme/colors.ts +17 -1
  229. package/src/theme/ui-tokens.ts +50 -1
  230. package/src/tickers/listing-venues.ts +11 -1
  231. package/src/tickers/search/japanese-names.json +1 -0
  232. package/src/tickers/search/japanese-names.ts +152 -0
  233. package/src/tickers/terminal-codes.ts +55 -6
  234. package/src/time-series/base-series.ts +3 -0
  235. package/src/types/data-provider.ts +6 -0
  236. package/src/types/financials.ts +11 -0
  237. package/src/types/plugin-contributions.ts +7 -0
  238. package/src/types/plugin-panes.ts +7 -0
  239. package/src/ui/host.tsx +6 -0
  240. package/src/utils/double-escape-close.ts +42 -0
  241. package/src/utils/fx-status.ts +30 -7
  242. package/src/utils/network-failure.ts +23 -0
@@ -0,0 +1,87 @@
1
+ import type { QuoteBatchResult, QuoteSubscriptionTarget } from "../types/data-provider";
2
+ import { isRateLimited, isTransientServiceFailure } from "../sources/provider-errors";
3
+
4
+ /**
5
+ * Waits before each new ask for a list's rows that failed for a reason that
6
+ * says nothing of the symbol. Two: a busy moment passes within them, and a
7
+ * list still refused after them is done within ten seconds, each row saying why.
8
+ */
9
+ const QUOTE_RETRY_WAITS_MS: readonly number[] = [2_000, 6_000];
10
+
11
+ /** Lists longer than this say how far they have got while they are slow. */
12
+ export const QUOTE_PROGRESS_MIN_SYMBOLS = 50;
13
+
14
+ /**
15
+ * Whether a row's failure says nothing of its symbol, so asked again in a
16
+ * moment it may be quoted: a source failed rather than answered (`transient`,
17
+ * which the router sets for a timeout or a refusal behind its bare "No quote
18
+ * provider available"), or the data service could not be reached, did not
19
+ * answer or was busy. A source's own reason (Not a ticker, a delisting) is an
20
+ * answer and is kept, and so is the request limit: asked again is more of
21
+ * what it refused, so its row says when to try.
22
+ */
23
+ function isTransientQuoteFailure({ error, transient }: Pick<QuoteBatchResult, "error" | "transient">): boolean {
24
+ return error != null && !isRateLimited(error) && (transient === true || isTransientServiceFailure(error));
25
+ }
26
+
27
+ /**
28
+ * A list is asked for this many symbols at a time, a few asks in flight, so it
29
+ * says how far it has got as each ask comes back: the service takes up to a
30
+ * hundred from a signed-out caller.
31
+ */
32
+ const QUOTE_LIST_CHUNK = 100;
33
+ const QUOTE_LIST_CHUNKS_IN_FLIGHT = 3;
34
+
35
+ /**
36
+ * A list's quotes, its rows that failed for a reason that says nothing of the
37
+ * symbol (`isTransientQuoteFailure`) asked for again after each wait, so a
38
+ * busy moment never marks a listing that trades as having no quote. A row
39
+ * still failing after the last wait keeps the latest reason it was given.
40
+ * Rows come back in the order of `targets`, each the target it was asked as.
41
+ * `onSettled` is told of each row once it is final, as the ask it came in
42
+ * returns: answered, refused for its own reason, or failing after the last
43
+ * wait.
44
+ */
45
+ export async function quotesWithRetries(
46
+ targets: QuoteSubscriptionTarget[],
47
+ ask: (targets: QuoteSubscriptionTarget[]) => Promise<QuoteBatchResult[]>,
48
+ {
49
+ waitsMs = QUOTE_RETRY_WAITS_MS,
50
+ chunkSize = QUOTE_LIST_CHUNK,
51
+ onRetry,
52
+ onSettled,
53
+ }: {
54
+ waitsMs?: readonly number[];
55
+ chunkSize?: number;
56
+ /** Told before each new ask, with how many rows and how long it waits first. */
57
+ onRetry?: (count: number, waitMs: number) => void;
58
+ /** Told of an ask's rows that are final, each with its place in `targets`. */
59
+ onSettled?: (settled: Array<{ result: QuoteBatchResult; index: number }>) => void;
60
+ } = {},
61
+ ): Promise<QuoteBatchResult[]> {
62
+ const results: QuoteBatchResult[] = [];
63
+ const transient = (result: QuoteBatchResult) => !result.quote && isTransientQuoteFailure(result);
64
+ const askInChunks = async (asked: number[], last: boolean): Promise<void> => {
65
+ const chunks: number[][] = [];
66
+ for (let at = 0; at < asked.length; at += chunkSize) chunks.push(asked.slice(at, at + chunkSize));
67
+ let next = 0;
68
+ await Promise.all(Array.from({ length: Math.min(QUOTE_LIST_CHUNKS_IN_FLIGHT, chunks.length) }, async () => {
69
+ while (next < chunks.length) {
70
+ const chunk = chunks[next++]!;
71
+ const answered = await ask(chunk.map((index) => targets[index]!));
72
+ const rows = chunk.flatMap((index, at) => answered[at] ? [{ result: answered[at]!, index }] : []);
73
+ for (const { result, index } of rows) results[index] = result;
74
+ onSettled?.(last ? rows : rows.filter(({ result }) => !transient(result)));
75
+ }
76
+ }));
77
+ };
78
+ await askInChunks(targets.map((_target, index) => index), waitsMs.length === 0);
79
+ for (const [attempt, waitMs] of waitsMs.entries()) {
80
+ const failed = targets.flatMap((_target, index) => results[index] && transient(results[index]!) ? [index] : []);
81
+ if (failed.length === 0) break;
82
+ onRetry?.(failed.length, waitMs);
83
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
84
+ await askInChunks(failed, attempt === waitsMs.length - 1);
85
+ }
86
+ return results.filter(Boolean);
87
+ }
@@ -97,7 +97,8 @@ type Cell =
97
97
  /** `unit`: what the column draws a number of this row in, so a missing figure still names its unit. */
98
98
  | { kind: "blank"; unit?: string }
99
99
  | { kind: "text"; text: string; time?: boolean }
100
- | { kind: "number"; value: number; unit: string }
100
+ /** `drawn`: the value and the number the text drew for it, whose scale the whole column decides (`columnScale`). */
101
+ | { kind: "number"; value: number; unit: string; drawn?: { value: number; display: DisplayNumber } }
101
102
  /** Text that may read as a number, once the whole column is known. */
102
103
  | { kind: "textual"; text: string };
103
104
 
@@ -192,16 +193,50 @@ function readDisplay(value: string): DisplayNumber | typeof BLANK_DISPLAY | null
192
193
  * with its sign turned (a short position as a negative amount) exports it as
193
194
  * drawn, every digit, not the rounded figure read back.
194
195
  */
195
- function valueAsDrawn(value: number, drawn: DisplayNumber): number | null {
196
- const target = Number(drawn.number);
197
- const tolerance = drawn.step * (1 + 1e-9) + Number.EPSILON;
198
- for (const sign of [1, -1]) {
199
- for (const scale of DISPLAY_SCALES) {
200
- const scaled = sign * value * scale;
201
- if (Math.abs(scaled - target) <= tolerance) return exportNumber(scaled);
202
- }
196
+ function valueAsDrawn(value: number, drawn: DisplayNumber, scales: readonly number[] = SIGNED_SCALES): number | null {
197
+ const scale = scales.find((entry) => fitsDrawn(value, drawn, entry));
198
+ return scale === undefined ? null : exportNumber(value * scale);
199
+ }
200
+
201
+ /** Each display scale, then each with the sign turned, in the order a value is read by. */
202
+ const SIGNED_SCALES = [...DISPLAY_SCALES, ...DISPLAY_SCALES.map((scale) => -scale)];
203
+
204
+ /** Whether a value times a signed scale is the number drawn, to its last digit. */
205
+ function fitsDrawn(value: number, drawn: DisplayNumber, scale: number): boolean {
206
+ return Math.abs(value * scale - Number(drawn.number)) <= drawn.step * (1 + 1e-9) + Number.EPSILON;
207
+ }
208
+
209
+ /**
210
+ * The one scale a column's values are drawn at, decided from all of them,
211
+ * one row's column too: a value near zero fits several (a spread of 0.0013
212
+ * drawn "+0.1" is within a step of itself as of 100 times itself), and read
213
+ * alone it would export at another scale than the rows beside it (0.0013
214
+ * beside 0.8586). Of the scales most values fit, the one whose values come
215
+ * closest to the figures drawn, in steps; the earlier in `SIGNED_SCALES` on a
216
+ * tie. A figure drawn as 0 says nothing of the scale (0.04 drawn "0" is
217
+ * nearer still at a hundredth of itself), so it is left out of the distance.
218
+ * Null for a column with no value drawn as a number.
219
+ */
220
+ function columnScale(cells: readonly Cell[]): number | null {
221
+ const drawn = cells.flatMap((cell) => cell.kind === "number" && cell.drawn ? [cell.drawn] : []);
222
+ let best: { scale: number; fits: number; miss: number } | null = null;
223
+ for (const scale of SIGNED_SCALES) {
224
+ const fitting = drawn.filter((entry) => fitsDrawn(entry.value, entry.display, scale));
225
+ if (fitting.length === 0) continue;
226
+ const scaled = fitting.filter(({ display }) => Number(display.number) !== 0);
227
+ const miss = scaled.reduce((total, { value, display }) => total + Math.abs(value * scale - Number(display.number)) / display.step, 0) / Math.max(1, scaled.length);
228
+ if (!best || fitting.length > best.fits || (fitting.length === best.fits && miss < best.miss - 1e-9)) best = { scale, fits: fitting.length, miss };
203
229
  }
204
- return null;
230
+ return best?.scale ?? null;
231
+ }
232
+
233
+ /** The column's cells, each value drawn as a number exported at the column's one scale where it fits it. */
234
+ function atColumnScale(cells: Cell[]): Cell[] {
235
+ const scale = columnScale(cells);
236
+ if (scale == null) return cells;
237
+ return cells.map((cell) => cell.kind === "number" && cell.drawn && fitsDrawn(cell.drawn.value, cell.drawn.display, scale)
238
+ ? { ...cell, value: exportNumber(cell.drawn.value * scale) }
239
+ : cell);
205
240
  }
206
241
 
207
242
  function timeCell(instant: number, dateOnly: boolean, shown: string | null, raw?: string): Cell {
@@ -220,13 +255,13 @@ function numberCell(value: number, shown: string | null, key: string | undefined
220
255
  if (drawn === BLANK_DISPLAY) return BLANK;
221
256
  // "3M" drawn from 3 is a tenor or a code, not three million.
222
257
  if (drawn && BARE_SCALED.test(shown) && value === Number(shown.replace(/[kKMBT]$/, ""))) return text(shown);
223
- if (drawn) return { kind: "number", value: valueAsDrawn(value, drawn) ?? Number(drawn.number), unit: drawn.unit };
258
+ if (drawn) return { kind: "number", value: valueAsDrawn(value, drawn) ?? Number(drawn.number), unit: drawn.unit, drawn: { value, display: drawn } };
224
259
  // A time drawn as a date or a clock.
225
260
  if (isEpochMilliseconds(value)) return timeCell(value, false, shown);
226
261
  const [first, ...rest] = shown.split(/\s+/);
227
262
  const lead = rest.length > 0 && CHANGE_NOTE.test(rest.join(" ")) ? readDisplay(first!) : null;
228
263
  const scaled = lead && lead !== BLANK_DISPLAY ? valueAsDrawn(value, lead) : null;
229
- if (lead && lead !== BLANK_DISPLAY && scaled != null) return { kind: "number", value: scaled, unit: lead.unit };
264
+ if (lead && lead !== BLANK_DISPLAY && scaled != null) return { kind: "number", value: scaled, unit: lead.unit, drawn: { value, display: lead } };
230
265
  return text(shown);
231
266
  }
232
267
 
@@ -288,7 +323,8 @@ function exportCell(raw: unknown, display: string | null, key?: string): Cell {
288
323
  * becomes a number only beside other figures, never in a column of tenors
289
324
  * ("3M, 6M, 1Y"). Identifier columns keep their text.
290
325
  */
291
- function resolveColumn(header: string, cells: Cell[], parseText: boolean): ResolvedColumn {
326
+ function resolveColumn(header: string, column: Cell[], parseText: boolean): ResolvedColumn {
327
+ const cells = atColumnScale(column);
292
328
  const textual = cells.flatMap((cell) => cell.kind === "textual" ? [cell] : []);
293
329
  const read = parseText ? textual.map((cell) => readDisplay(cell.text)) : [];
294
330
  const numeric = read.filter((entry): entry is DisplayNumber => entry != null && entry !== BLANK_DISPLAY);
@@ -623,6 +659,27 @@ function sectionByTitle(tables: readonly CliReportTable[], wanted: string): CliR
623
659
  return starting[0];
624
660
  }
625
661
 
662
+ /**
663
+ * The report with a row for each listing a list left out (a pair with no options of its own, a listing abroad where
664
+ * the data covers US listings only), added to its first table that has a Symbol and a status column: the symbol, its
665
+ * reason in status, the figures empty, so every symbol asked for has a row, as `fn` help says a missing figure's
666
+ * reason goes in status. A report with no such table is as it was.
667
+ */
668
+ export function withRefusedRows(report: CliReportTables, refused: ReadonlyArray<{ symbol: string; reason: string }> | undefined): CliReportTables {
669
+ if (!refused?.length) return report;
670
+ const at = report.tables.findIndex((table) => table.columns.some((column) => column.toLowerCase() === "symbol")
671
+ && table.columns.some((column) => column === "status" || column === "value_status"));
672
+ if (at < 0) return report;
673
+ const table = report.tables[at]!;
674
+ const symbolAt = table.columns.findIndex((column) => column.toLowerCase() === "symbol");
675
+ const statusAt = table.columns.findIndex((column) => column === "status" || column === "value_status");
676
+ const rows = refused.map(({ symbol, reason }) => table.columns.map((_column, index) => index === symbolAt ? symbol : index === statusAt ? reason : ""));
677
+ const rowIdentities = [...table.rowIdentities ?? table.rows.map(() => undefined), ...refused.map(({ symbol }) => ({ symbolOrSeries: symbol, asOf: null }))];
678
+ const tables = [...report.tables];
679
+ tables[at] = { ...table, rows: [...table.rows, ...rows], rowIdentities };
680
+ return { ...report, tables };
681
+ }
682
+
626
683
  /**
627
684
  * `--section`: one table, by its title or the start of it (any case), or its
628
685
  * 1-based position. Without a selector the report keeps every table.
package/src/cli/result.ts CHANGED
@@ -676,6 +676,25 @@ export function exitLeavingReadsBehind(): void {
676
676
  }, LEFT_BEHIND_EXIT_MS).unref();
677
677
  }
678
678
 
679
+ /** A result whose rows' "Not a ticker: US10Y." cells carry the hint `hinted` gives the sentence. */
680
+ function withHintedCells<T>(result: CliResult<T>, hinted: (text: string) => string): CliResult<T> {
681
+ if (!Array.isArray(result.data)) return result;
682
+ let changed = false;
683
+ const data = result.data.map((row: unknown) => {
684
+ if (!row || typeof row !== "object" || Array.isArray(row)) return row;
685
+ let next = row as Record<string, unknown>;
686
+ for (const [key, value] of Object.entries(row)) {
687
+ if (typeof value !== "string" || !value.includes("Not a ticker: ")) continue;
688
+ const hint = hinted(value);
689
+ if (hint === value) continue;
690
+ next = { ...next, [key]: hint };
691
+ changed = true;
692
+ }
693
+ return next;
694
+ });
695
+ return changed ? { ...result, data: data as T } : result;
696
+ }
697
+
679
698
  export function printCliResult<T, Row extends Record<string, unknown> = Record<string, unknown>>(
680
699
  result: CliResult<T>,
681
700
  options: CliGlobalOptions,
@@ -686,11 +705,14 @@ export function printCliResult<T, Row extends Record<string, unknown> = Record<s
686
705
  if (options.quiet && options.format === "text") return;
687
706
  // JSON keeps the router's own words; everything else is for a person, so a "Not a ticker" gets its hint.
688
707
  const hinted = (text: string) => options.format === "json" ? text : withSearchHints(text, args, isFredSeries);
708
+ // A CSV's status cell is where its row says why, so it gets the hint the warning line has: a cell ends in a comma,
709
+ // which the text's sentence search does not take for the sentence's end.
710
+ const cells = options.format === "csv" ? withHintedCells(result, hinted) : result;
689
711
  // An export `--output` names is drawn for the file (no colour), and held for the command's end to write.
690
712
  const toFile = options.output !== undefined && options.format !== "text";
691
713
  const serialized = hinted(toFile
692
- ? renderForFile(() => serializeCliResult(result, options, renderOptions))
693
- : serializeCliResult(result, options, renderOptions));
714
+ ? renderForFile(() => serializeCliResult(cells, options, renderOptions))
715
+ : serializeCliResult(cells, options, renderOptions));
694
716
  // A CSV's closing source and note lines go to stderr with the warnings: in the file they are rows of junk to a spreadsheet.
695
717
  const { csv, footer } = options.format === "csv" ? splitCsvFooter(serialized) : { csv: serialized, footer: [] };
696
718
  const output = csv;
@@ -1,9 +1,9 @@
1
1
  import { readFile } from "fs/promises";
2
2
  import { fstatSync } from "fs";
3
- import { splitSymbolArgLines, splitSymbolWords, stripStrayEdges, uniqueSymbols } from "./symbol-args";
3
+ import { splitSymbolArgLines, splitSymbolWords, stripStrayEdges, symbolInputKey, uniqueSymbols } from "./symbol-args";
4
4
  import { foldTypedText } from "../utils/typed-text";
5
5
  import { hasDecimalCommas, isFigure, isJunkCell, isNumberCell, isSheetErrorCell, protectFigureCommas, restoreFigureCommas } from "./symbol-cells";
6
- import { endsInLegalForm, readTerminalListingCode, unknownBloombergMarket } from "../tickers/terminal-codes";
6
+ import { endsInLegalForm, readTerminalListingCode, unknownBloombergMarket, unreadBloombergCode } from "../tickers/terminal-codes";
7
7
 
8
8
  /** Header cells that name a spreadsheet's symbol column, compared without case, spaces or punctuation. */
9
9
  const SYMBOL_HEADERS = new Set(["symbol", "symbols", "ticker", "tickers", "code", "stockcode", "securitycode", "instrument"]);
@@ -153,7 +153,7 @@ function looksLikeSymbol(cell: string): boolean {
153
153
  */
154
154
  function isTerminalCodeCell(cell: string): boolean {
155
155
  return /\s/.test(cell.trim()) && !endsInLegalForm(cell)
156
- && (readTerminalListingCode(cell) != null || unknownBloombergMarket(cell) != null);
156
+ && (readTerminalListingCode(cell) != null || unknownBloombergMarket(cell) != null || unreadBloombergCode(cell) != null);
157
157
  }
158
158
 
159
159
  /** A numeric exchange code as a grid holds one (`2007`, `0700`, `600519`): Hong Kong, Tokyo, Shanghai. Shorter is a quantity. */
@@ -420,6 +420,8 @@ export interface SymbolListSource {
420
420
  * words, each a symbol.
421
421
  */
422
422
  readEntries?: (entries: string[]) => Promise<string[]>;
423
+ /** Given, gets each line of the file and standard input as typed (`TypedForm`), for a command whose rows name them. */
424
+ typedForms?: TypedForm[];
423
425
  }
424
426
 
425
427
  export class SymbolListError extends Error {
@@ -456,6 +458,7 @@ export async function readSymbolList(source: SymbolListSource): Promise<{ symbol
456
458
  const strays = new Set<string>(stripStrayEdges(typedArgs.join(" ")).notes);
457
459
  const ignored: string[] = [];
458
460
  const headers: string[] = [];
461
+ const typedForms = source.typedForms ?? [];
459
462
  const addCells = async ({ symbols, ignored: beside, entries: whole, header }: SymbolText) => {
460
463
  if (header) headers.push(`Skipped the first row as a header: ${listCells(header)}.`);
461
464
  const cells = symbols.map((cell) => {
@@ -476,13 +479,37 @@ export async function readSymbolList(source: SymbolListSource): Promise<{ symbol
476
479
  const code = (error as NodeJS.ErrnoException).code;
477
480
  throw new SymbolListError(code === "ENOENT" ? `No file at ${source.file}.` : `Could not read ${source.file}: ${error instanceof Error ? error.message : String(error)}`);
478
481
  }
482
+ typedForms.push(...typedLines(text));
479
483
  await addCells(parseSymbolText(foldTypedText(text)));
480
484
  }
481
485
  if (wantsStdin || (typed.length === 0 && source.file == null && (source.stdinPiped ?? stdinIsPiped()))) {
482
- await addCells(parseSymbolText(foldTypedText(await readStdin())));
486
+ const text = await readStdin();
487
+ typedForms.push(...typedLines(text));
488
+ await addCells(parseSymbolText(foldTypedText(text)));
483
489
  }
484
490
  // A number where a symbol goes (a line of prices, a typed 1.899) is left out with those typed beside a symbol.
485
491
  const numbers = [...figures, ...collected.filter(isNumberCell)];
486
492
  const notes = [ignoredCellsNote(ignored), ignoredNumbersNote(numbers)].filter((note): note is string => !!note);
487
493
  return { ...uniqueSymbols(collected.filter((symbol) => !isNumberCell(symbol))), notes: [...headers, ...strays, ...notes] };
488
494
  }
495
+
496
+ /** A line of a list as typed, before full-width letters and case were folded, and the entry it reads as. */
497
+ export interface TypedForm {
498
+ typed: string;
499
+ /** The entry the line reads as, its repeats' key (`symbolInputKey`): `USDJPY` and `usdjpy` are both `USDJPY`'s. */
500
+ key: string;
501
+ }
502
+
503
+ /**
504
+ * Each line of a list's text that is one entry, as typed and in order, an exact repeat too, with the key of the entry
505
+ * it reads as: so a command can give every line its row and say which line of a sheet each row is, where several
506
+ * were read as one entry.
507
+ */
508
+ function typedLines(text: string): TypedForm[] {
509
+ return text.split(/\r?\n/).flatMap((line) => {
510
+ const typed = line.trim();
511
+ const key = symbolInputKey(stripStrayEdges(foldTypedText(typed)).text);
512
+ if (!typed || !key) return [];
513
+ return [{ typed, key }];
514
+ });
515
+ }
@@ -0,0 +1,83 @@
1
+ import type { UnreadBloombergCode } from "../tickers/terminal-codes";
2
+ import { isCurrencyCode } from "../utils/currency-pair";
3
+ import { METAL_FRONT_MONTH, METAL_NAMES } from "./fx-quote-rate";
4
+ import { treasuryYieldHint, treasuryYieldTenor } from "./treasury-yields";
5
+
6
+ /**
7
+ * The government yield curves the catalog charts (`CAP:bond-yield:<curve>-<tenor>`), by the
8
+ * currency Bloomberg's generic bond codes name (GTJPY10Y) or the root of its benchmark index
9
+ * (GJGB10, GDBR10, GUKG10, GCAN10YR), with the country the line names.
10
+ */
11
+ const YIELD_CURVES: ReadonlyArray<{ curve: string; country: string; currencies: readonly string[]; index: RegExp }> = [
12
+ { curve: "jp", country: "Japan's", currencies: ["JPY"], index: /^GJGB(\d{1,2})$/ },
13
+ { curve: "de", country: "Germany's", currencies: ["DEM", "EUR"], index: /^GDBR(\d{1,2})$/ },
14
+ { curve: "gb", country: "the UK's", currencies: ["GBP"], index: /^GUKG(\d{1,2})$/ },
15
+ { curve: "ca", country: "Canada's", currencies: ["CAD"], index: /^GCAN(\d{1,2})YR$/ },
16
+ { curve: "mx", country: "Mexico's", currencies: ["MXN"], index: /^GMXN(\d{1,2})YR$/ },
17
+ { curve: "br", country: "Brazil's", currencies: ["BRL"], index: /^GEBR(\d{1,2})Y$/ },
18
+ ];
19
+
20
+ /** Bloomberg's generic government bond code: GT, the currency, the tenor in years (GTJPY10Y, GTUSD2Y, GTDEM10YR). */
21
+ const GENERIC_BOND = /^GT([A-Z]{3})(\d{1,2})YR?$/;
22
+
23
+ /** The yield a Bloomberg bond code or benchmark index names, as the catalog series that charts it; null for any other. */
24
+ function yieldLine(code: string): string | null {
25
+ const bond = GENERIC_BOND.exec(code);
26
+ const [currency, years] = bond ? [bond[1]!, bond[2]!] : [null, null];
27
+ if (currency === "USD") {
28
+ const tenor = treasuryYieldTenor(`${Number(years)}y`);
29
+ return tenor ? treasuryYieldHint(tenor) : null;
30
+ }
31
+ for (const { curve, country, currencies, index } of YIELD_CURVES) {
32
+ const tenor = currency && currencies.includes(currency) ? years : index.exec(code)?.[1];
33
+ if (tenor) return `${country} ${Number(tenor)}-year government yield: gloom fn G CAP:bond-yield:${curve}-${Number(tenor)}y.`;
34
+ }
35
+ return null;
36
+ }
37
+
38
+ /** "Spot gold is not quoted; GC=F is the front-month future.", for XAU, XAUUSD and XAUJPY. */
39
+ function metalLine(code: string): string | null {
40
+ const metal = Object.keys(METAL_FRONT_MONTH).find((symbol) => code === symbol || (code.startsWith(symbol) && /^[A-Z]{3}$/.test(code.slice(3))));
41
+ return metal ? `Spot ${METAL_NAMES[metal]!.toLowerCase()} is not quoted; ${METAL_FRONT_MONTH[metal]} is the front-month future.` : null;
42
+ }
43
+
44
+ /** The pair a currency code starts with (USDJPY of `USDJPY BGN`, `USDJPYV1M`), or null. */
45
+ function pairOf(code: string): { base: string; quote: string } | null {
46
+ const pair = /^([A-Z]{3})([A-Z]{3})/.exec(code);
47
+ if (!pair || pair[1] === pair[2] || !isCurrencyCode(pair[1]!) || !isCurrencyCode(pair[2]!)) return null;
48
+ return { base: pair[1]!, quote: pair[2]! };
49
+ }
50
+
51
+ /**
52
+ * Why a line written as a Bloomberg code that names nothing here
53
+ * (`unreadBloombergCode`) is not quoted, and what has it instead: a
54
+ * government bond's yield series, the Treasury yield an index is, the future
55
+ * spot gold is priced from, a pair's spot rate beside its forwards and vols.
56
+ * Starts with the line as typed, so a list's note names it once.
57
+ */
58
+ export function unreadBloombergCodeMessage(read: UnreadBloombergCode): string {
59
+ const { typed, code, yellowKey } = read;
60
+ const root = code.split(" ")[0]!;
61
+ if (yellowKey === "Govt" || yellowKey === "Index") {
62
+ const tenor = /^USGG/.test(root) ? treasuryYieldTenor(root) : null;
63
+ if (tenor) return `${typed} is Bloomberg's US ${tenor.label} Treasury yield, which has no quote here. ${treasuryYieldHint(tenor)}`;
64
+ const line = yieldLine(root);
65
+ if (yellowKey === "Govt") {
66
+ return `${typed} is Bloomberg's code for a government bond, which is not quoted here. ${line
67
+ ?? "Government yields: gloom catalog \"10Y government bond\"; US Treasuries: gloom fred DGS10."}`;
68
+ }
69
+ if (line) return `${typed} is Bloomberg's benchmark yield index, which has no quote here. ${line}`;
70
+ return `${typed} is a Bloomberg index code no symbol here is read from. Try gloom search ${root}.`;
71
+ }
72
+ if (yellowKey === "Curncy") {
73
+ const metal = metalLine(root);
74
+ if (metal) return `${typed}: ${metal}`;
75
+ const pair = pairOf(root);
76
+ if (pair) {
77
+ return `${typed} is not quoted here: Bloomberg's ${pair.base}/${pair.quote} forwards, option volatilities, risk reversals and pricing sources `
78
+ + `are not carried. ${pair.base}/${pair.quote} spot: gloom quote ${pair.base}${pair.quote}=X.`;
79
+ }
80
+ return `${typed} is a Bloomberg currency code no symbol here is read from. Try gloom search ${root}.`;
81
+ }
82
+ return `${typed} is a Bloomberg commodity code no future here is rooted at. Try gloom search ${root.replace(/\d+$/, "")}.`;
83
+ }
@@ -61,6 +61,7 @@ import { NotASymbolError, notASymbolError } from "./symbol-cells";
61
61
  import { kindFromListingSyntax } from "../tickers/instrument-kind";
62
62
  import { classifyInstrumentKind, normalizeTickerSymbol } from "../tickers/search/ranking";
63
63
  import { companyNameQueries, findFormerIssuerOfName, isCompanyNameInput, settledTerminalCode } from "../tickers/company-name-listing";
64
+ import { unreadBloombergCode } from "../tickers/terminal-codes";
64
65
 
65
66
  /** The saved ticker for a symbol (`SAN:EPA`, or `SAN` with `--exchange EPA`), saving it from search first if needed. */
66
67
  export async function resolveTickerForCli(
@@ -615,7 +616,7 @@ function listLookupPlan(input: string, exchange: string | undefined): ListLookup
615
616
  if (notASymbolError(input)) return { searches: [], changes: null };
616
617
  // A terminal's code abroad (`VOD LN`) is its listing as written: it asks only for its quote.
617
618
  const code = settledTerminalCode(input);
618
- if (code) return { searches: [], changes: null };
619
+ if (code || unreadBloombergCode(input)) return { searches: [], changes: null };
619
620
  // A company's name searches what its reading searched (`readNameEntries`), answered by the same batch.
620
621
  if (isCompanyNameInput(input)) return { searches: companyNameQueries(input), changes: null };
621
622
  try {
@@ -67,6 +67,11 @@ export function treasuryYieldTenor(text: string): TreasuryYieldTenor | null {
67
67
  return named || (!/\s/.test(typed) && YEAR_UNITS.has(unit)) ? tenor : null;
68
68
  }
69
69
 
70
+ /** FRED's Treasury yield series typed where a ticker goes (DGS10): no ticker search finds them. */
71
+ export function isTreasuryFredSeries(id: string): boolean {
72
+ return [...TENORS.values()].some((tenor) => tenor.fred === id);
73
+ }
74
+
70
75
  /** The commands with the yield: its Cboe index when there is one, its FRED series, the curve. */
71
76
  function yieldCommands(tenor: TreasuryYieldTenor): Array<readonly [command: string, gives: string]> {
72
77
  return [
@@ -104,6 +104,7 @@ export function useCommandBarActionRuntime({
104
104
  screen: "ticker-search" | "layout",
105
105
  initialQuery = "",
106
106
  payload?: Record<string, unknown>,
107
+ options?: { launched?: boolean },
107
108
  ) => {
108
109
  if (screen === "ticker-search" && initialQuery.trim()) {
109
110
  skipTickerSearchDebounceRef.current = true;
@@ -115,6 +116,7 @@ export function useCommandBarActionRuntime({
115
116
  selectedIdx: 0,
116
117
  hoveredIdx: null,
117
118
  payload,
119
+ ...(options?.launched ? { launched: true } : {}),
118
120
  });
119
121
  }, [pushRoute, skipTickerSearchDebounceRef]);
120
122
 
@@ -9,6 +9,7 @@ interface UseCommandBarLaunchRequestOptions {
9
9
  screen: "ticker-search" | "layout",
10
10
  initialQuery?: string,
11
11
  payload?: TickerSearchPayload,
12
+ options?: { launched?: boolean },
12
13
  ) => void;
13
14
  }
14
15
 
@@ -30,7 +31,7 @@ export function useCommandBarLaunchRequest({
30
31
  processedLaunchSequenceRef.current = launch.sequence;
31
32
 
32
33
  if (launch.kind === "ticker-search") {
33
- openModeRoute("ticker-search", launch.query ?? "", launch.payload);
34
+ openModeRoute("ticker-search", launch.query ?? "", launch.payload, { launched: true });
34
35
  }
35
36
  // Submitting text needs the selection runtime, which the surface wires up
36
37
  // after this hook; it watches for run-query itself.
@@ -161,13 +161,15 @@ export function useCommandBarNavigationState({
161
161
  setRouteStack((current) => current.slice(0, -1));
162
162
  }, [closeAll, currentRoute, routeStack.length, setRootQuery]);
163
163
 
164
+ // Esc: one screen back, or out of the bar from the root or from a screen
165
+ // the bar opened on (`launched`).
164
166
  const dismissCommandBar = useCallback(() => {
165
- if (currentRoute) {
167
+ if (currentRoute && !(routeStack.length === 1 && currentRoute.launched)) {
166
168
  popRoute();
167
169
  return;
168
170
  }
169
171
  closeAll();
170
- }, [closeAll, currentRoute, popRoute]);
172
+ }, [closeAll, currentRoute, popRoute, routeStack.length]);
171
173
 
172
174
  return {
173
175
  closeAll,
@@ -35,6 +35,12 @@ export type CommandBarFieldValue = string | boolean | string[];
35
35
 
36
36
  interface CommandBarRouteBase {
37
37
  restoreMain?: CommandBarMainSnapshot;
38
+ /**
39
+ * The bar opened on this screen from outside it (the ticker search key, a
40
+ * click in the header): Esc closes the bar, back where the user was,
41
+ * instead of showing the root screen they never saw.
42
+ */
43
+ launched?: boolean;
38
44
  }
39
45
 
40
46
  interface CommandBarModeRoute extends CommandBarRouteBase {
@@ -41,6 +41,7 @@ import { paneMenuButtonAnchor, ShellActionMenuOverlay, type ActionMenuState } fr
41
41
  import { getPaneFooter } from "./pane/footer";
42
42
  import { requestPaneDocs } from "../../docs/requests";
43
43
  import { DOCS_PANE_TEMPLATE_ID } from "../../docs/content";
44
+ import { paneHoldsUnsentWork } from "../../state/pane-unsent-work";
44
45
 
45
46
  interface DetachedPaneShellProps {
46
47
  pluginRegistry: PluginRegistry;
@@ -130,6 +131,8 @@ export function DetachedPaneShell({ pluginRegistry, desktopWindowBridge }: Detac
130
131
  overlayOpen: dialogOpen || menuState !== null,
131
132
  editing: inputCaptured,
132
133
  close: () => {
134
+ // A draft not sent or an answer coming in keeps the window: the Esc goes on to the pane.
135
+ if (paneHoldsUnsentWork(desktopWindowBridge.paneId)) return false;
133
136
  if (!locked) fireAndForget(desktopWindowBridge.closeDetachedPane?.(desktopWindowBridge.paneId), "desktop.closeDetachedPane");
134
137
  return true;
135
138
  },
@@ -4,9 +4,12 @@ import {
4
4
  armDoubleEscapeClose,
5
5
  createDoubleEscapeCloseState,
6
6
  isEscapeKeptFromClosing,
7
+ isHeldEscapePress,
7
8
  offerEscapeTowardClose,
8
9
  resetDoubleEscapeClose,
10
+ swallowEscapeAfterSingleClose,
9
11
  takeDoubleEscapeClose,
12
+ takeSingleEscapeClose,
10
13
  } from "../../utils/double-escape-close";
11
14
 
12
15
  function isEscapeKey(event: KeyEventLike): boolean {
@@ -24,11 +27,19 @@ interface DoubleEscapeCloseOptions {
24
27
  dragging?: () => boolean;
25
28
  /** Closes the target; false when nothing was closed and the Esc goes on to the pane. */
26
29
  close(): boolean;
30
+ /**
31
+ * Closes the target on one Esc that nothing in it took, where one Esc is
32
+ * enough (a floating window); false where it is not, and the Esc goes on.
33
+ */
34
+ closeOnSingle?: () => boolean;
27
35
  }
28
36
 
29
37
  /**
30
38
  * Esc Esc closes the focused pane, even one that could still go back: every
31
- * Esc is the first half of a pair, whatever the pane did with it. Kept out:
39
+ * Esc is the first half of a pair, whatever the pane did with it. Where one
40
+ * Esc is enough (`closeOnSingle`, a floating window), an Esc nothing took
41
+ * closes it, and the Esc after it at a double press's pace closes nothing
42
+ * more. Kept out:
32
43
  *
33
44
  * - an Esc in a text field, or while the pane is editing, unless the pane
34
45
  * counts it because nothing typed is left behind (an empty composer);
@@ -43,10 +54,12 @@ interface DoubleEscapeCloseOptions {
43
54
  * A surface that takes Esc in a scoped `before` handler (onboarding, a form,
44
55
  * key capture) runs ahead of the arming and so never counts.
45
56
  */
46
- export function useDoubleEscapeClose({ targetId, overlayOpen, editing, dragging, close }: DoubleEscapeCloseOptions): void {
57
+ export function useDoubleEscapeClose({ targetId, overlayOpen, editing, dragging, close, closeOnSingle }: DoubleEscapeCloseOptions): void {
47
58
  const stateRef = useRef(createDoubleEscapeCloseState());
48
59
  const live = useRef({ targetId, overlayOpen });
49
60
  live.current = { targetId, overlayOpen };
61
+ /** Esc presses that came as a held key's, judged before they armed anything. */
62
+ const heldRef = useRef(new WeakSet<object>());
50
63
 
51
64
  useEffect(() => {
52
65
  if (overlayOpen) resetDoubleEscapeClose(stateRef.current);
@@ -60,6 +73,7 @@ export function useDoubleEscapeClose({ targetId, overlayOpen, editing, dragging,
60
73
  return;
61
74
  }
62
75
  const at = Date.now();
76
+ if (isHeldEscapePress(state, at, event.repeat)) heldRef.current.add(event);
63
77
  offerEscapeTowardClose(event, {
64
78
  count: () => {
65
79
  if (!live.current.overlayOpen) armDoubleEscapeClose(state, live.current.targetId, at, event.repeat);
@@ -72,12 +86,29 @@ export function useDoubleEscapeClose({ targetId, overlayOpen, editing, dragging,
72
86
  // with more to go back through still closes. Not in a text field.
73
87
  useShortcut((event) => {
74
88
  if (!isEscapeKey(event) || overlayOpen || editing || dragging?.()) return;
75
- if (takeDoubleEscapeClose(stateRef.current, targetId, Date.now(), event.repeat) && close()) {
89
+ const now = Date.now();
90
+ if (swallowEscapeAfterSingleClose(stateRef.current, now, event.repeat)) {
91
+ event.preventDefault();
92
+ event.stopPropagation();
93
+ return;
94
+ }
95
+ if (takeDoubleEscapeClose(stateRef.current, targetId, now, event.repeat) && close()) {
76
96
  event.preventDefault();
77
97
  event.stopPropagation();
78
98
  }
79
99
  }, { phase: "capture" });
80
100
 
101
+ // One Esc that nothing took (the window had nothing to back out of, no menu
102
+ // to close) closes a floating window, as it does a dialog or Help.
103
+ useShortcut((event) => {
104
+ if (!closeOnSingle || !isEscapeKey(event) || overlayOpen || editing || dragging?.()) return;
105
+ if (isEscapeKeptFromClosing(event) || heldRef.current.has(event)) return;
106
+ if (!closeOnSingle()) return;
107
+ takeSingleEscapeClose(stateRef.current, Date.now());
108
+ event.preventDefault();
109
+ event.stopPropagation();
110
+ }, { phase: "idle" });
111
+
81
112
  // The first: after the scoped surfaces that own their Esc (onboarding, a
82
113
  // form, key capture), so theirs never counts, and before the pane.
83
114
  useShortcut((event) => {