@gloom-sh/terminal 0.19.3 → 0.19.5

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 (226) hide show
  1. package/package.json +4 -2
  2. package/src/api-client/errors.ts +8 -0
  3. package/src/api-client/index.ts +18 -0
  4. package/src/api-client/request.ts +295 -42
  5. package/src/api-client/socket.ts +95 -0
  6. package/src/app/keybindings/actions.ts +1 -1
  7. package/src/app/pane-runtime/index.tsx +1 -1
  8. package/src/app/pane-runtime/ticker-inspector-runtime.ts +1 -1
  9. package/src/app/pane-runtime/ticker-open-runtime.ts +1 -1
  10. package/src/app/pane-runtime/ticker-open-target.ts +12 -2
  11. package/src/cli/commands/command-utils.ts +4 -0
  12. package/src/cli/commands/market.ts +119 -27
  13. package/src/cli/commands/search.ts +1 -1
  14. package/src/cli/commands/ticker.ts +10 -6
  15. package/src/cli/currency-name-hint.ts +60 -0
  16. package/src/cli/desktop-pane-shot-api-policy.ts +10 -2
  17. package/src/cli/desktop-pane-shot.ts +2 -1
  18. package/src/cli/history-rows.ts +18 -1
  19. package/src/cli/known-gaps.ts +17 -2
  20. package/src/cli/not-a-ticker.ts +5 -3
  21. package/src/cli/pane-functions/catalog.ts +9 -1
  22. package/src/cli/pane-functions/headless.ts +7 -3
  23. package/src/cli/pane-functions/market-session.ts +6 -7
  24. package/src/cli/series-search.ts +4 -5
  25. package/src/components/chart/composite/panel-bitmap.ts +28 -2
  26. package/src/components/chart/composite/time-axis.ts +17 -2
  27. package/src/components/command-bar/action-runtime.ts +2 -0
  28. package/src/components/command-bar/commands/direct/runtime.ts +3 -3
  29. package/src/components/command-bar/helpers.ts +2 -0
  30. package/src/components/command-bar/list/model.ts +9 -0
  31. package/src/components/command-bar/pane-actions.ts +46 -35
  32. package/src/components/command-bar/pane-templates/workflow.ts +6 -0
  33. package/src/components/command-bar/panel/index.tsx +30 -3
  34. package/src/components/command-bar/panel/types.ts +7 -0
  35. package/src/components/command-bar/routes/root/results.ts +4 -4
  36. package/src/components/command-bar/routes/root/selection.ts +3 -2
  37. package/src/components/command-bar/routes/ticker-search/actions.ts +21 -16
  38. package/src/components/command-bar/routing/launch-request.ts +3 -2
  39. package/src/components/command-bar/routing/list-state.ts +4 -1
  40. package/src/components/command-bar/surface/index.tsx +15 -1
  41. package/src/components/layout/floating-pane.tsx +10 -0
  42. package/src/components/layout/pane/frame.tsx +6 -0
  43. package/src/components/layout/pane/header.tsx +244 -42
  44. package/src/components/layout/pane/index.tsx +20 -2
  45. package/src/components/layout/shell/active-drag.ts +160 -28
  46. package/src/components/layout/shell/drag/index.ts +99 -96
  47. package/src/components/layout/shell/drag/live.ts +3 -17
  48. package/src/components/layout/shell/drag/magnets.ts +304 -0
  49. package/src/components/layout/shell/drag/overlays.tsx +77 -75
  50. package/src/components/layout/shell/drag/runtime.ts +12 -7
  51. package/src/components/layout/shell/index.tsx +66 -32
  52. package/src/components/layout/shell/native/pointer-runtime.ts +7 -2
  53. package/src/components/layout/shell/native/surfaces.ts +1 -9
  54. package/src/components/layout/shell/native/window-state.ts +21 -25
  55. package/src/components/layout/shell/pane/layers.tsx +153 -24
  56. package/src/components/layout/shell/shortcuts.ts +4 -1
  57. package/src/components/layout/shell/terminal-pointer-runtime.ts +24 -1
  58. package/src/components/layout/shell/window-mode/overlays.tsx +14 -6
  59. package/src/components/layout/status-bar.tsx +75 -6
  60. package/src/components/layout/window-controls.tsx +96 -35
  61. package/src/components/layout/window-fullscreen.ts +20 -0
  62. package/src/components/quote-flash.ts +36 -32
  63. package/src/core/app-runtime.ts +4 -1
  64. package/src/core/connection-health.ts +76 -1
  65. package/src/core/state/app/command-bar-launch.ts +12 -0
  66. package/src/core/state/app/layout.ts +4 -3
  67. package/src/core/state/app/types.ts +4 -1
  68. package/src/data/config/layout.ts +2 -2
  69. package/src/data/config/store/fold-panes.ts +6 -1
  70. package/src/i18n/es.ts +8 -1
  71. package/src/i18n/ja.ts +8 -1
  72. package/src/i18n/ko.ts +8 -1
  73. package/src/i18n/zh-cn.ts +8 -1
  74. package/src/i18n/zh-tw.ts +8 -1
  75. package/src/layout/pane-follow.ts +3 -2
  76. package/src/layout/pane-layout-move.ts +2 -1
  77. package/src/layout/pane-manager/dock-stack.ts +38 -0
  78. package/src/layout/pane-manager/dock-tree.ts +76 -15
  79. package/src/layout/pane-manager/docking.ts +48 -6
  80. package/src/layout/pane-manager/floating-actions.ts +12 -3
  81. package/src/layout/pane-manager/floating-placement.ts +189 -0
  82. package/src/layout/pane-manager/floating.ts +23 -4
  83. package/src/layout/pane-manager/gridlock.ts +16 -4
  84. package/src/layout/pane-manager/hidden-panes.ts +30 -1
  85. package/src/layout/pane-manager/index.ts +2 -0
  86. package/src/layout/pane-manager/layout-state.ts +17 -0
  87. package/src/layout/pane-manager/types.ts +4 -1
  88. package/src/layout/ticker-retarget.ts +88 -0
  89. package/src/layout-marketplace/cloud.ts +9 -1
  90. package/src/market-data/connection-follow.ts +68 -0
  91. package/src/market-data/coordinator/entries.ts +15 -3
  92. package/src/market-data/coordinator/events.ts +17 -1
  93. package/src/market-data/coordinator/financials.ts +20 -7
  94. package/src/market-data/coordinator/index.ts +217 -4
  95. package/src/market-data/coordinator/quotes.ts +10 -0
  96. package/src/market-data/frame-scheduler.ts +47 -10
  97. package/src/market-data/frame-wake.ts +74 -0
  98. package/src/market-data/futures-board.ts +7 -6
  99. package/src/market-data/hooks.tsx +43 -3
  100. package/src/market-data/performance.ts +78 -9
  101. package/src/market-data/request-types.ts +6 -3
  102. package/src/news/aggregator.ts +12 -1
  103. package/src/plugins/builtin/alerts/cli.ts +2 -1
  104. package/src/plugins/builtin/analytics/risk-evidence.ts +1 -0
  105. package/src/plugins/builtin/attention/evidence.ts +1 -1
  106. package/src/plugins/builtin/awards/client.ts +1 -1
  107. package/src/plugins/builtin/awards/evidence.ts +1 -1
  108. package/src/plugins/builtin/awards/pane.tsx +2 -1
  109. package/src/plugins/builtin/bond-calculator/math.ts +1 -1
  110. package/src/plugins/builtin/broker-manager/footer.ts +3 -2
  111. package/src/plugins/builtin/broker-manager/index.tsx +2 -1
  112. package/src/plugins/builtin/broker-manager/keyboard.ts +2 -1
  113. package/src/plugins/builtin/buildout/company/pane.tsx +2 -1
  114. package/src/plugins/builtin/buildout/model/index.ts +6 -0
  115. package/src/plugins/builtin/buildout/pane/index.tsx +2 -1
  116. package/src/plugins/builtin/catalysts/evidence.ts +1 -1
  117. package/src/plugins/builtin/catalysts/pane.tsx +2 -1
  118. package/src/plugins/builtin/chart-composer/headless.ts +40 -1
  119. package/src/plugins/builtin/chart-composer/index.tsx +13 -0
  120. package/src/plugins/builtin/chat/controller/index.ts +10 -3
  121. package/src/plugins/builtin/chat/controller/session-runtime.ts +9 -2
  122. package/src/plugins/builtin/chat/status-widget.tsx +3 -1
  123. package/src/plugins/builtin/cloud-tweets/table.tsx +3 -2
  124. package/src/plugins/builtin/comment-letters/client.ts +2 -1
  125. package/src/plugins/builtin/company-kpis/client.ts +1 -1
  126. package/src/plugins/builtin/company-kpis/pane.tsx +2 -1
  127. package/src/plugins/builtin/company-kpis/screenshot-evidence.ts +3 -2
  128. package/src/plugins/builtin/cot/headless.ts +9 -3
  129. package/src/plugins/builtin/cot/model.ts +44 -3
  130. package/src/plugins/builtin/credit-documents/client.ts +1 -1
  131. package/src/plugins/builtin/credit-documents/evidence.ts +1 -1
  132. package/src/plugins/builtin/credit-documents/pane.tsx +2 -1
  133. package/src/plugins/builtin/earnings-calls/pane.tsx +1 -1
  134. package/src/plugins/builtin/earnings-ripple/index.tsx +6 -1
  135. package/src/plugins/builtin/econ/calendar-model.ts +2 -0
  136. package/src/plugins/builtin/econ/fred-catalog.ts +5 -5
  137. package/src/plugins/builtin/econ/print-watch.ts +3 -1
  138. package/src/plugins/builtin/futures/series.ts +16 -1
  139. package/src/plugins/builtin/fx-matrix/headless.ts +4 -2
  140. package/src/plugins/builtin/fx-matrix/index.tsx +37 -3
  141. package/src/plugins/builtin/fx-matrix/pairs.ts +15 -0
  142. package/src/plugins/builtin/gpu/headless.ts +2 -1
  143. package/src/plugins/builtin/help/function-card.tsx +2 -1
  144. package/src/plugins/builtin/help/index.tsx +3 -2
  145. package/src/plugins/builtin/insider/display.ts +45 -6
  146. package/src/plugins/builtin/ipo-calendar/model.ts +2 -0
  147. package/src/plugins/builtin/iv-history/client.ts +2 -1
  148. package/src/plugins/builtin/iv-history/headless.ts +2 -1
  149. package/src/plugins/builtin/jobs/pages.ts +4 -4
  150. package/src/plugins/builtin/kelly-sizer/headless.ts +2 -1
  151. package/src/plugins/builtin/market-heatmap/index.tsx +2 -1
  152. package/src/plugins/builtin/members/client.ts +1 -1
  153. package/src/plugins/builtin/mna/distress/client.ts +1 -0
  154. package/src/plugins/builtin/mna/pane.tsx +4 -1
  155. package/src/plugins/builtin/options/market-reference.ts +1 -1
  156. package/src/plugins/builtin/options/open-interest-as-of.ts +3 -1
  157. package/src/plugins/builtin/options/view.tsx +2 -1
  158. package/src/plugins/builtin/options-calculator/evidence.ts +1 -1
  159. package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +1 -1
  160. package/src/plugins/builtin/options-scenario/csp-screen.ts +8 -4
  161. package/src/plugins/builtin/options-scenario/csp.ts +28 -9
  162. package/src/plugins/builtin/options-scenario/evidence.ts +5 -4
  163. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  164. package/src/plugins/builtin/perps/client.ts +1 -1
  165. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
  166. package/src/plugins/builtin/portfolio-list/pane/index.tsx +7 -3
  167. package/src/plugins/builtin/portfolio-list/use-throttled-memo.ts +10 -19
  168. package/src/plugins/builtin/research/analyst-model.ts +1 -0
  169. package/src/plugins/builtin/research/equity-diagnostic-pane.tsx +2 -1
  170. package/src/plugins/builtin/research/index.tsx +1 -0
  171. package/src/plugins/builtin/research/relative-valuation-currency.ts +1 -1
  172. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -1
  173. package/src/plugins/builtin/research-search/command-bar-search.ts +3 -1
  174. package/src/plugins/builtin/research-search/snippet.ts +1 -0
  175. package/src/plugins/builtin/revenue-breakdown/client.ts +3 -2
  176. package/src/plugins/builtin/seasonality/headless.ts +2 -1
  177. package/src/plugins/builtin/sec/command-bar-search.ts +3 -2
  178. package/src/plugins/builtin/sec/index.tsx +7 -4
  179. package/src/plugins/builtin/sec/row-summaries.ts +28 -12
  180. package/src/plugins/builtin/sectors/client.ts +18 -8
  181. package/src/plugins/builtin/sectors/index.tsx +19 -5
  182. package/src/plugins/builtin/short-interest/watch-client.ts +2 -1
  183. package/src/plugins/builtin/social-mentions/client.ts +2 -1
  184. package/src/plugins/builtin/supply-chain/client.ts +1 -1
  185. package/src/plugins/builtin/supply-chain/evidence.ts +1 -1
  186. package/src/plugins/builtin/supply-chain/graph-pane.tsx +2 -1
  187. package/src/plugins/builtin/supply-chain/pane.tsx +2 -1
  188. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +1 -1
  189. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +24 -4
  190. package/src/plugins/builtin/ticker-detail/adr-pair/tab.tsx +1 -1
  191. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -1
  192. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +25 -2
  193. package/src/plugins/builtin/time-sales/client.ts +1 -0
  194. package/src/plugins/builtin/vol-surface/client.ts +2 -1
  195. package/src/plugins/builtin/yield-curve/headless.ts +3 -1
  196. package/src/portfolio/column-values.ts +76 -10
  197. package/src/react/async-resource.ts +12 -0
  198. package/src/remote/controller.ts +3 -1
  199. package/src/renderers/browser/app-services.ts +8 -1
  200. package/src/renderers/browser/cloud-transport.ts +6 -1
  201. package/src/renderers/cloudflare/worker.ts +24 -2
  202. package/src/renderers/dom/host/box.tsx +204 -176
  203. package/src/renderers/dom/host/style.ts +49 -20
  204. package/src/renderers/dom/host/text.tsx +3 -2
  205. package/src/renderers/dom/styles.css +32 -0
  206. package/src/renderers/electrobun/bun/desktop/backend.ts +2 -0
  207. package/src/renderers/electrobun/bun/desktop/host-requests.ts +25 -1
  208. package/src/renderers/electrobun/bun/desktop/relaunch.ts +9 -1
  209. package/src/renderers/electrobun/bun/desktop/windows-script.ts +9 -6
  210. package/src/renderers/electrobun/bun/window/windows-native.ts +26 -1
  211. package/src/renderers/electrobun/shared/protocol.ts +6 -0
  212. package/src/renderers/electrobun/view/ui-host.tsx +7 -0
  213. package/src/renderers/electrobun/view/window-fullscreen.ts +10 -3
  214. package/src/shares/portable-layout.ts +99 -2
  215. package/src/sources/provider-router/index.ts +9 -3
  216. package/src/sources/provider-router/sources.ts +26 -1
  217. package/src/sync/core-contributors.ts +18 -4
  218. package/src/time-series/price-units.ts +11 -0
  219. package/src/time-series/resolve.ts +12 -0
  220. package/src/types/config.ts +17 -1
  221. package/src/types/plugin.ts +6 -0
  222. package/src/ui/host.tsx +2 -0
  223. package/src/utils/currency-names.ts +20 -0
  224. package/src/utils/currency-pair.ts +6 -0
  225. package/src/utils/exchange-rate-snapshot.ts +20 -2
  226. package/src/utils/fx-market-hours.ts +43 -0
@@ -142,12 +142,13 @@ export const FUTURES_CONTRACTS: FuturesContract[] = [
142
142
  { symbol: "LE=F", code: "LE", name: "Live Cattle", sector: "livestock", venue: "CME", tick: 0.025, unit: "US cents / lb" },
143
143
  { symbol: "HE=F", code: "HE", name: "Lean Hogs", sector: "livestock", venue: "CME", tick: 0.025, unit: "US cents / lb" },
144
144
 
145
- { symbol: "6E=F", code: "6E", name: "Euro FX", sector: "currencies", venue: "CME", tick: 0.00005, bareCode: true },
146
- { symbol: "6J=F", code: "6J", name: "Japanese Yen", sector: "currencies", venue: "CME", tick: 0.0000005, bareCode: true },
147
- { symbol: "6B=F", code: "6B", name: "British Pound", sector: "currencies", venue: "CME", tick: 0.0001, bareCode: true },
148
- { symbol: "6A=F", code: "6A", name: "Australian Dollar", sector: "currencies", venue: "CME", tick: 0.00005, bareCode: true },
149
- { symbol: "6C=F", code: "6C", name: "Canadian Dollar", sector: "currencies", venue: "CME", tick: 0.00005, bareCode: true },
150
- { symbol: "6S=F", code: "6S", name: "Swiss Franc", sector: "currencies", venue: "CME", tick: 0.00005, bareCode: true },
145
+ // Quoted in US dollars per unit of the foreign currency, as the server's terms state for most of them.
146
+ { symbol: "6E=F", code: "6E", name: "Euro FX", sector: "currencies", venue: "CME", tick: 0.00005, unit: "USD / EUR", bareCode: true },
147
+ { symbol: "6J=F", code: "6J", name: "Japanese Yen", sector: "currencies", venue: "CME", tick: 0.0000005, unit: "USD / JPY", bareCode: true },
148
+ { symbol: "6B=F", code: "6B", name: "British Pound", sector: "currencies", venue: "CME", tick: 0.0001, unit: "USD / GBP", bareCode: true },
149
+ { symbol: "6A=F", code: "6A", name: "Australian Dollar", sector: "currencies", venue: "CME", tick: 0.00005, unit: "USD / AUD", bareCode: true },
150
+ { symbol: "6C=F", code: "6C", name: "Canadian Dollar", sector: "currencies", venue: "CME", tick: 0.00005, unit: "USD / CAD", bareCode: true },
151
+ { symbol: "6S=F", code: "6S", name: "Swiss Franc", sector: "currencies", venue: "CME", tick: 0.00005, unit: "USD / CHF", bareCode: true },
151
152
  ];
152
153
 
153
154
  export const FUTURES_SECTOR_LABELS: Record<FuturesSector, string> = {
@@ -121,6 +121,37 @@ export function useTickerFinancials(symbol: string | null | undefined, ticker: T
121
121
  return financials;
122
122
  }
123
123
 
124
+ /** Where a ticker's snapshot load stands, for a pane with nothing of it to show yet. */
125
+ export interface TickerSnapshotState {
126
+ /** Asked for, or about to be, with no answer yet. */
127
+ loading: boolean;
128
+ /** Why the last load came back with nothing, or null. */
129
+ error: string | null;
130
+ /** Asks again now, past a recent failure. */
131
+ retry: () => Promise<void>;
132
+ }
133
+
134
+ /** The snapshot load behind `useTickerFinancials`, as its entry stands. */
135
+ export function useTickerSnapshotState(symbol: string | null | undefined, ticker: TickerRecord | null | undefined): TickerSnapshotState {
136
+ const instrument = useTickerInstrument(symbol, ticker);
137
+ const instrumentKey = instrument ? instrumentIdentityKey(instrument) : null;
138
+ const keys = useMemo(() => (instrument ? [buildSnapshotKey(instrument)] : []), [instrumentKey]);
139
+ useCoordinatorKeysVersion(keys);
140
+ const coordinator = getSharedMarketDataCoordinator();
141
+ const entry = coordinator && instrument ? coordinator.getSnapshotEntry(instrument) : null;
142
+ const retry = useCallback(async () => {
143
+ const coordinator = getSharedMarketDataCoordinator();
144
+ if (coordinator && instrument) await coordinator.loadSnapshot(instrument, { forceRefresh: true });
145
+ }, [instrumentKey]);
146
+ const failed = !!entry && (entry.phase === "error" || entry.phase === "ready") && entry.error != null;
147
+ return {
148
+ // Idle is a load the hook is about to start.
149
+ loading: !!entry && (entry.phase === "idle" || entry.phase === "loading" || entry.phase === "refreshing"),
150
+ error: failed ? entry.error!.message : null,
151
+ retry,
152
+ };
153
+ }
154
+
124
155
  function buildTickerFinancialsKeys(tickers: TickerRecord[], options: TickerInstrumentOptions = {}): string[] {
125
156
  const keys: string[] = [];
126
157
  for (const ticker of tickers) {
@@ -188,6 +219,8 @@ interface PatchedMapSlot<K, V> {
188
219
  interface PatchedMapState<K, V> {
189
220
  signature: string;
190
221
  coordinator: SharedCoordinator | null;
222
+ /** The subscribed keys' summed version when the slots were last read. */
223
+ aggregateVersion: number;
191
224
  slots: Array<PatchedMapSlot<K, V>>;
192
225
  versions: number[];
193
226
  backing: Map<K, V>;
@@ -224,18 +257,22 @@ function usePatchedMap<K, V>(
224
257
  versions.push(slotVersion(slot, versionOf, aggregateVersion));
225
258
  }
226
259
  const view = new RetainedMapView(backing);
227
- state = { signature, coordinator, slots, versions, backing, view };
260
+ state = { signature, coordinator, slots, versions, backing, view, aggregateVersion };
228
261
  stateRef.current = state;
229
262
  return view;
230
263
  }
231
264
 
265
+ // Key versions only grow, so an unchanged sum means no slot moved: a render
266
+ // for any other reason skips reading every slot's versions. Both are kept
267
+ // only once read, so a read that throws is tried again on the next render.
268
+ if (aggregateVersion === state.aggregateVersion) return state.view;
232
269
  let changed = false;
233
270
  for (let index = 0; index < state.slots.length; index += 1) {
234
271
  const slot = state.slots[index]!;
235
272
  const version = slotVersion(slot, versionOf, aggregateVersion);
236
273
  if (version === state.versions[index]) continue;
237
- state.versions[index] = version;
238
274
  const value = slot.read();
275
+ state.versions[index] = version;
239
276
  if (value == null) {
240
277
  if (state.backing.delete(slot.key)) changed = true;
241
278
  } else if (state.backing.get(slot.key) !== value) {
@@ -243,6 +280,7 @@ function usePatchedMap<K, V>(
243
280
  changed = true;
244
281
  }
245
282
  }
283
+ state.aggregateVersion = aggregateVersion;
246
284
  if (!changed) return state.view;
247
285
  const view = new RetainedMapView(state.backing);
248
286
  state.view = view;
@@ -260,7 +298,9 @@ export function useTickerFinancialsMap(
260
298
  ): Map<string, TickerFinancials> {
261
299
  const coordinator = getSharedMarketDataCoordinator();
262
300
  const optionsKey = options.portfolioId ?? "";
263
- const tickerKey = buildTickerFinancialsMapKey(tickers, options);
301
+ // Per list, not per render: a quote tick re-renders the pane but leaves its
302
+ // rows (immutable records, replaced when they change) and portfolio alone.
303
+ const tickerKey = useMemo(() => buildTickerFinancialsMapKey(tickers, options), [optionsKey, tickers]);
264
304
  const subscriptionKeys = useMemo(() => buildTickerFinancialsKeys(tickers, options), [optionsKey, tickerKey]);
265
305
  const keysVersion = useCoordinatorKeysVersion(subscriptionKeys);
266
306
 
@@ -31,22 +31,76 @@ function coercePointDate(value: Date | string | number): Date | null {
31
31
  return Number.isFinite(date.getTime()) ? date : null;
32
32
  }
33
33
 
34
- function normalizePriceReturnHistory(points: readonly PricePoint[]): PricePoint[] {
34
+ interface NormalizedHistory {
35
+ /** The input's length and ends when it was read, so an array grown in place is read again. */
36
+ length: number;
37
+ first: PricePoint | undefined;
38
+ last: PricePoint | undefined;
39
+ history: readonly PricePoint[];
40
+ }
41
+
42
+ /**
43
+ * The normalized copy of each history read before. A ticker's bars stay the
44
+ * same array while its quote ticks, and every tick asks again with the quote
45
+ * appended, so the bars are sorted and copied once rather than per tick.
46
+ */
47
+ const normalizedCopies = new WeakMap<readonly PricePoint[], NormalizedHistory>();
48
+ /** Arrays built here already normalized (a copy, or one with the quote appended): read as they are. */
49
+ const normalizedArrays = new WeakSet<readonly PricePoint[]>();
50
+
51
+ function normalizePriceReturnHistory(points: readonly PricePoint[]): readonly PricePoint[] {
52
+ if (normalizedArrays.has(points)) return points;
53
+ const cached = normalizedCopies.get(points);
54
+ if (cached && cached.length === points.length && cached.first === points[0] && cached.last === points.at(-1)) return cached.history;
35
55
  const byTimestamp = new Map<number, PricePoint>();
36
56
  for (const point of points) {
37
57
  const date = coercePointDate(point.date as Date | string | number);
38
58
  if (!date || (!Number.isFinite(point.close) && !pricePointIntegrity(point))) continue;
39
59
  byTimestamp.set(date.getTime(), { ...point, date });
40
60
  }
41
- return [...byTimestamp.entries()]
61
+ const history = [...byTimestamp.entries()]
42
62
  .sort((left, right) => left[0] - right[0])
43
63
  .map(([, point]) => point);
64
+ normalizedArrays.add(history);
65
+ normalizedCopies.set(points, { length: points.length, first: points[0], last: points.at(-1), history });
66
+ return history;
67
+ }
68
+
69
+ /** Each normalized bar's session day by venue (barSessionDay), kept with the bar: the zone lookup is the slow part. */
70
+ const sessionDaysByVenue = new Map<string, WeakMap<PricePoint, string>>();
71
+ /** Whether each normalized bar's OHLC contradicts itself (pricePointIntegrity). */
72
+ const inconsistentPoints = new WeakMap<PricePoint, boolean>();
73
+
74
+ function sessionDays(history: readonly PricePoint[], venue: string | undefined): string[] {
75
+ const venueKey = venue ?? "";
76
+ let days = sessionDaysByVenue.get(venueKey);
77
+ if (!days) {
78
+ days = new WeakMap();
79
+ sessionDaysByVenue.set(venueKey, days);
80
+ }
81
+ return history.map((point) => {
82
+ let day = days.get(point);
83
+ if (day === undefined) {
84
+ day = barSessionDay(point.date.getTime(), venue);
85
+ days.set(point, day);
86
+ }
87
+ return day;
88
+ });
89
+ }
90
+
91
+ function isInconsistent(point: PricePoint): boolean {
92
+ let inconsistent = inconsistentPoints.get(point);
93
+ if (inconsistent === undefined) {
94
+ inconsistent = !!pricePointIntegrity(point);
95
+ inconsistentPoints.set(point, inconsistent);
96
+ }
97
+ return inconsistent;
44
98
  }
45
99
 
46
100
  export function appendQuoteToPriceReturnHistory(
47
101
  points: readonly PricePoint[],
48
102
  quote: Pick<Quote, "price" | "lastUpdated"> | null | undefined,
49
- ): PricePoint[] {
103
+ ): readonly PricePoint[] {
50
104
  const history = normalizePriceReturnHistory(points);
51
105
  if (!quote || !Number.isFinite(quote.price) || !Number.isFinite(quote.lastUpdated)) {
52
106
  return history;
@@ -58,13 +112,15 @@ export function appendQuoteToPriceReturnHistory(
58
112
  const latestHistoryTime = history.at(-1)?.date.getTime() ?? Number.NEGATIVE_INFINITY;
59
113
  if (quoteDate.getTime() <= latestHistoryTime) return history;
60
114
 
61
- return [
115
+ const withQuote = [
62
116
  ...history,
63
117
  {
64
118
  date: quoteDate,
65
119
  close: quote.price,
66
120
  },
67
121
  ];
122
+ normalizedArrays.add(withQuote);
123
+ return withQuote;
68
124
  }
69
125
 
70
126
  /** The calendar date a horizon ending on `day` is measured back to (periodBaseDay). */
@@ -89,23 +145,33 @@ function priceReturnForHorizon(
89
145
  venue: string | undefined,
90
146
  ): Pick<PriceReturnField, "value" | "unavailableReason"> {
91
147
  const history = normalizePriceReturnHistory(points);
148
+ return priceReturnFromHistory(history, sessionDays(history, venue), horizon);
149
+ }
150
+
151
+ /** `history` normalized, `days` its bars' session days. */
152
+ function priceReturnFromHistory(
153
+ history: readonly PricePoint[],
154
+ days: readonly string[],
155
+ horizon: PriceReturnHorizon,
156
+ ): Pick<PriceReturnField, "value" | "unavailableReason"> {
92
157
  if (history.length < 2) return {
93
158
  value: null,
94
- ...(history.some(pricePointIntegrity) ? { unavailableReason: "inconsistent-ohlc" as const } : {}),
159
+ ...(history.some(isInconsistent) ? { unavailableReason: "inconsistent-ohlc" as const } : {}),
95
160
  };
96
161
 
97
162
  const latest = history.at(-1)!;
98
163
  // The close on or before the same date a horizon earlier, as every period return is measured. No gap
99
164
  // limit: the overview's history can be sparse, and its base is whatever close it holds on or before then.
100
165
  // Each bar and the quote by its session day: a JPX bar stamped 00:00 JST, or a quote after a New York close, is not the UTC date's.
101
- const days = history.map((point) => barSessionDay(point.date.getTime(), venue));
102
166
  const baseDay = horizonBaseDay(days.at(-1)!, horizon);
103
167
  const baseIndex = periodBaseIndex(days, baseDay, Number.POSITIVE_INFINITY);
104
168
  const baseline = baseIndex < 0 ? null : history[baseIndex]!;
105
169
  const cutoff = new Date(`${baseDay}T00:00:00Z`);
106
170
 
107
- if (history.some((point) => point.date >= (baseline?.date ?? cutoff) && pricePointIntegrity(point))) {
108
- return { value: null, unavailableReason: "inconsistent-ohlc" };
171
+ // The bars from the baseline (or the cutoff) on: the history is in time order, one bar a timestamp.
172
+ const since = (baseline?.date ?? cutoff).getTime();
173
+ for (let index = history.length - 1; index >= 0 && history[index]!.date.getTime() >= since; index -= 1) {
174
+ if (isInconsistent(history[index]!)) return { value: null, unavailableReason: "inconsistent-ohlc" };
109
175
  }
110
176
  if (!baseline || !Number.isFinite(baseline.close) || baseline.close === 0) return { value: null };
111
177
  if (!Number.isFinite(latest.close)) return { value: null };
@@ -117,9 +183,12 @@ export function buildPriceReturnFields(
117
183
  venue?: string,
118
184
  horizons: readonly PriceReturnHorizon[] = PRICE_RETURN_HORIZONS,
119
185
  ): PriceReturnField[] {
186
+ // Normalized and dated once for every horizon.
187
+ const history = normalizePriceReturnHistory(points);
188
+ const days = sessionDays(history, venue);
120
189
  return horizons.map((horizon) => ({
121
190
  id: horizon.id,
122
191
  label: horizon.label,
123
- ...priceReturnForHorizon(points, horizon, venue),
192
+ ...priceReturnFromHistory(history, days, horizon),
124
193
  }));
125
194
  }
@@ -46,10 +46,11 @@ function brokerContractForTicker(
46
46
  const contracts = ticker?.metadata.broker_contracts ?? [];
47
47
  const portfolioId = options.portfolioId;
48
48
  if (portfolioId) {
49
- const positions = ticker?.metadata.positions.filter((position) => position.portfolio === portfolioId && position.shares !== 0) ?? [];
50
- const selected = new Map<string, BrokerContractRef>();
49
+ // Rows ask on every render of a list: nothing is allocated for a portfolio's lots until one names a contract.
50
+ let selected: Map<string, BrokerContractRef> | null = null;
51
51
  let hasPublicPosition = false;
52
- for (const position of positions) {
52
+ for (const position of ticker?.metadata.positions ?? []) {
53
+ if (position.portfolio !== portfolioId || position.shares === 0) continue;
53
54
  const hasExplicitId = position.brokerContractId != null;
54
55
  const hasExplicitIdentity = position.brokerContractIdentity != null;
55
56
  const hasLegacyScope = position.broker !== "manual" && !!position.broker && !!position.brokerInstanceId;
@@ -68,11 +69,13 @@ function brokerContractForTicker(
68
69
  hasPublicPosition = true;
69
70
  continue;
70
71
  }
72
+ selected ??= new Map();
71
73
  for (const contract of matches) {
72
74
  const key = scopedBrokerContractIdentityKey(contract);
73
75
  selected.set(key, contract);
74
76
  }
75
77
  }
78
+ if (!selected) return null;
76
79
  // One ticker quote must identify every selected lot. Never choose by array order.
77
80
  if (selected.size > 1 || (selected.size > 0 && hasPublicPosition)) return undefined;
78
81
  return selected.values().next().value ?? null;
@@ -1,7 +1,7 @@
1
1
  import type { CompanyFrom } from "../types/company-from";
2
2
  import { logFailure } from "../utils/log-failure";
3
3
  import type { NewsCapability } from "../capabilities";
4
- import type { ConnectionHealthRegistry } from "../core/connection-health";
4
+ import { GLOOM_CLOUD_HTTP_CONNECTION_ID, type ConnectionHealthRegistry } from "../core/connection-health";
5
5
  import type { NewsAccess, NewsArticle, NewsQuery, NewsQueryState } from "./types";
6
6
  import { isAppVisible, subscribeAppVisibility } from "../state/app/activity";
7
7
  import {
@@ -113,6 +113,7 @@ export class NewsService {
113
113
  private readonly visibility: NonNullable<NewsServiceOptions["visibility"]>;
114
114
  private lastPollAt = 0;
115
115
  private unsubscribeVisibility: (() => void) | null = null;
116
+ private unsubscribeRecovery: (() => void) | null = null;
116
117
  private readonly session?: NewsSessionSignal;
117
118
  private sessionKey: string | null = null;
118
119
  /** Bumped when the session changes; a read from an older generation is dropped. */
@@ -164,6 +165,14 @@ export class NewsService {
164
165
  this.sessionKey = this.session.key();
165
166
  this.unsubscribeSession = this.session.subscribe(() => this.handleSessionChange());
166
167
  }
168
+ // A list that failed while the data service was unreachable is read again once it answers, not at the next poll.
169
+ this.unsubscribeRecovery = this.connectionHealth?.subscribeRecovery((sourceId) => {
170
+ if (sourceId !== GLOOM_CLOUD_HTTP_CONNECTION_ID || !this.polling) return;
171
+ for (const entry of this.queries.values()) {
172
+ // A list missing some of its sources is read again too, keeping what it shows meanwhile.
173
+ if (entry.refs > 0 && entry.state.error != null) void this.refreshQuery(entry.query, entry.state.phase === "error");
174
+ }
175
+ }) ?? null;
167
176
  this.scheduleNextPoll();
168
177
  }
169
178
 
@@ -173,6 +182,8 @@ export class NewsService {
173
182
  this.unsubscribeVisibility = null;
174
183
  this.unsubscribeSession?.();
175
184
  this.unsubscribeSession = null;
185
+ this.unsubscribeRecovery?.();
186
+ this.unsubscribeRecovery = null;
176
187
  this.clearPollTimer();
177
188
  }
178
189
 
@@ -1110,7 +1110,8 @@ export const alertsCliCommand: CliCommandDef = {
1110
1110
  });
1111
1111
  return;
1112
1112
  }
1113
- if (action === "delete" || action === "rm") {
1113
+ // `remove`, as the command's own description says it does, and `rm` delete as `delete` does.
1114
+ if (action === "delete" || action === "remove" || action === "rm") {
1114
1115
  const id = requireArg(args[1], "Usage: gloom alerts delete <id>", ctx);
1115
1116
  const level = alerts.find((alert) => alert.id === id) ?? null;
1116
1117
  const rule = level ? null : events.rules.find((entry) => entry.id === id) ?? null;
@@ -480,6 +480,7 @@ export function brokerPerformanceEvidence(
480
480
  performance: { flowTiming: "end-of-day", externalFlowsComplete: true, observations },
481
481
  }), now);
482
482
  } catch {
483
+ // Intentional ignore: account history that fails evidence validation does not qualify as evidence.
483
484
  return null;
484
485
  }
485
486
  }
@@ -19,7 +19,7 @@ export const attentionScreenshotEvidence: PaneScreenshotEvidenceHook<AttentionEv
19
19
  if (!isRecord(value) || value.kind !== "attention" || value.version !== 1 || value.complete !== true
20
20
  || !isRecord(value.payload) || attentionTab(value.tab) !== value.tab || typeof value.selectedSymbol !== "string"
21
21
  || !Number.isInteger(value.plottedValueCount) || Number(value.plottedValueCount) < 0) return null;
22
- try { validateAttention(value.payload as unknown as AttentionPayload); return value as unknown as AttentionEvidence; } catch { return null; }
22
+ try { validateAttention(value.payload as unknown as AttentionPayload); return value as unknown as AttentionEvidence; } catch { /* Intentional ignore: invalid captured observations are rejected as evidence by returning null. */ return null; }
23
23
  },
24
24
  mismatches(evidence, { resolved }) {
25
25
  return [evidence.payload.window !== attentionWindow(resolved.options.window) ? "Attention window does not match" : null,
@@ -14,7 +14,7 @@ const optionalText = (value: unknown) => value == null || text(value);
14
14
  const amount = (value: unknown) => value == null || text(value) && /^-?\d+(?:\.\d+)?$/.test(value) && Number.isFinite(Number(value));
15
15
  const date = (value: unknown) => text(value) && /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
16
16
  const instant = (value: unknown) => text(value) && Number.isFinite(Date.parse(value));
17
- const url = (value: unknown) => { try { return text(value) && ["https:", "http:"].includes(new URL(value).protocol); } catch { return false; } };
17
+ const url = (value: unknown) => { try { return text(value) && ["https:", "http:"].includes(new URL(value).protocol); } catch { /* Intentional ignore: malformed URLs fail this web link field validator. */ return false; } };
18
18
  const confidence = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
19
19
  const count = (value: unknown) => Number.isSafeInteger(value) && Number(value) >= 0;
20
20
  const currency = (value: unknown) => text(value) && /^[A-Z]{3}$/.test(value);
@@ -24,7 +24,7 @@ export const awardsScreenshotEvidence: PaneScreenshotEvidenceHook<AwardsEvidence
24
24
  read(value) {
25
25
  if (!isRecord(value) || value.kind !== "government-awards" || value.version !== 1 || value.complete !== true || !Number.isSafeInteger(value.plottedValueCount)
26
26
  || Number(value.plottedValueCount) < 0 || awardTab(value.tab) !== value.tab || !isRecord(value.payload)) return null;
27
- try { validateAwards(value.payload as unknown as AwardsPayload); return value as unknown as AwardsEvidence; } catch { return null; }
27
+ try { validateAwards(value.payload as unknown as AwardsPayload); return value as unknown as AwardsEvidence; } catch { /* Intentional ignore: invalid captured observations are rejected as evidence by returning null. */ return null; }
28
28
  },
29
29
  mismatches(evidence, { resolved, payload }) {
30
30
  const snapshot = payload.config.layout.instances.find((entry) => entry.instanceId === payload.paneId)?.settings?.awardsSnapshot;
@@ -26,6 +26,7 @@ import { AWARDS_UNAVAILABLE, fetchAwards, loadAward, loadAwards, validateAwards
26
26
  import { useAwardsEvidence } from "./evidence";
27
27
  import { AWARD_TABS, aggregateId, awardHistorySeries, awardPercent, awardPeriod, awardScope, awardsCoverageNotes, awardsPreviewNote, awardTab, awardTypeLabel, futureAwardDatesNote, money,
28
28
  rankedAggregates } from "./model";
29
+ import { logFailure } from "../../../utils/log-failure";
29
30
 
30
31
  type Item = { kind: "award"; row: AwardRow } | { kind: "aggregate"; row: AwardAggregate } | { kind: "leader"; row: AwardCompanyLeader } | { kind: "locked"; id: string }
31
32
  | { kind: "section"; id: string; label: string; count: number } | { kind: "note"; id: string; text: string };
@@ -116,7 +117,7 @@ function AwardsView({ width, height, focused, symbol }: PaneProps & { symbol: st
116
117
  const [selectedId, setSelected] = usePluginPaneState<string | null>(`awards:selection:${tab}`, null);
117
118
  const search = useQueryBarSearch(), tickerSearch = useQueryBarSearch();
118
119
  const [snapshotSetting] = usePaneSettingValue<AwardsPayload | null>("awardsSnapshot", null);
119
- const snapshot = useMemo(() => { try { return snapshotSetting ? validateAwards(snapshotSetting) : null; } catch { return null; } }, [snapshotSetting]);
120
+ const snapshot = useMemo(() => { try { return snapshotSetting ? validateAwards(snapshotSetting) : null; } catch (error) { return logFailure("awards.pane", "Validate awards snapshot failed", null)(error); } }, [snapshotSetting]);
120
121
  const filter = useMemo<AwardFilter>(() => ({ ticker: ticker.trim().toUpperCase() || undefined, query: query.trim() || undefined,
121
122
  jurisdiction: jurisdiction || undefined, currency: currency || undefined, source: source || undefined, awardType, agency: agency || undefined, sector: sector || undefined, parentId: parentId || undefined,
122
123
  from: parentId ? undefined : range === "all" ? from || undefined : new Date(Date.now() - Number(range) * 86_400_000).toISOString().slice(0, 10), to: parentId ? undefined : to || undefined, limit: 100,
@@ -157,7 +157,7 @@ export function treasurySpread(terms: BondTerms, yieldPercent: number, curve: re
157
157
  const before = points.findLast((point) => point.maturityYears <= maturityYears);
158
158
  const after = points.find((point) => point.maturityYears >= maturityYears);
159
159
  if (!before || !after || !before.asOf || before.asOf !== after.asOf) return null;
160
- try { parseDate(before.asOf); } catch { return null; }
160
+ try { parseDate(before.asOf); } catch { /* Intentional ignore: a benchmark curve with an unreadable date gives no spread. */ return null; }
161
161
  const weight = before === after ? 0 : (maturityYears - before.maturityYears) / (after.maturityYears - before.maturityYears);
162
162
  const benchmarkPercent = before.yieldPercent! + weight * (after.yieldPercent! - before.yieldPercent!);
163
163
  return { benchmarkPercent, spreadBps: (yieldPercent - benchmarkPercent) * 100, asOf: before.asOf, maturityYears };
@@ -2,6 +2,7 @@ import { useMemo, useRef } from "react";
2
2
  import { usePaneFooter, type PaneFooterSegment, type PaneHint } from "../../../components";
3
3
  import { enableBrokerHint } from "../shared/broker-reconnect";
4
4
  import type { BrokerManagerMessage } from "./pane-actions";
5
+ import { logFailure } from "../../../utils/log-failure";
5
6
 
6
7
  interface BrokerManagerFooterActions {
7
8
  connectSelected: () => Promise<void>;
@@ -58,8 +59,8 @@ export function useBrokerManagerFooter({
58
59
  hints.push({ id: "edit", key: "e", label: "dit", onPress: () => actionsRef.current.startEdit() });
59
60
  if (disabledSelected === null) {
60
61
  hints.push(
61
- { id: "connect", key: "c", label: "onnect", onPress: () => actionsRef.current.connectSelected().catch(() => {}) },
62
- { id: "sync", key: "s", label: "ync", onPress: () => actionsRef.current.syncSelected().catch(() => {}) },
62
+ { id: "connect", key: "c", label: "onnect", onPress: () => actionsRef.current.connectSelected().catch(logFailure("broker-manager.footer", "Connect selected broker profile failed")) },
63
+ { id: "sync", key: "s", label: "ync", onPress: () => actionsRef.current.syncSelected().catch(logFailure("broker-manager.footer", "Sync selected broker profile failed")) },
63
64
  );
64
65
  }
65
66
  }
@@ -43,6 +43,7 @@ import {
43
43
  renderBrokerCell,
44
44
  type BrokerColumn,
45
45
  } from "./table";
46
+ import { logFailure } from "../../../utils/log-failure";
46
47
 
47
48
  export function BrokersPane({ focused, width, height }: PaneProps) {
48
49
  const language = useAppLanguage();
@@ -275,7 +276,7 @@ export function BrokersPane({ focused, width, height }: PaneProps) {
275
276
  }, []);
276
277
 
277
278
  const saveCurrentEdit = useCallback(() => {
278
- saveEdit().catch(() => {});
279
+ saveEdit().catch(logFailure("broker-manager", "Save broker profile edit failed"));
279
280
  }, [saveEdit]);
280
281
 
281
282
  // The detail insets one cell each side like the table cells.
@@ -1,6 +1,7 @@
1
1
  import { useShortcut, type KeyEventLike } from "../../../react/input";
2
2
  import { isPlainKey } from "../../../utils/keyboard";
3
3
  import type { BrokerEditKey } from "./detail";
4
+ import { logFailure } from "../../../utils/log-failure";
4
5
 
5
6
  /**
6
7
  * The edit form's keys beside its field ring (the detail's useFieldRing walks
@@ -48,7 +49,7 @@ export function useBrokerManagerKeyboard({
48
49
  }
49
50
  if (isPlainKey(event, "enter", "return")) {
50
51
  consume(event);
51
- saveEdit().catch(() => {});
52
+ saveEdit().catch(logFailure("broker-manager.keyboard", "Save broker form failed"));
52
53
  return;
53
54
  }
54
55
  if (onSelectRow && isPlainKey(event, "left", "h", "right", "l", "space")) {
@@ -31,6 +31,7 @@ import { BuildoutDetail } from "../detail";
31
31
  import { BUILDOUT_COMPANY_PANE_ID } from "./id";
32
32
  import { metricNumber, moneyText, text, tickerSearchText, tickerSymbol } from "../format";
33
33
  import type { BuildoutColumn, BuildoutRow, BuildoutUpdate } from "../model/types";
34
+ import { NOT_IN_SCREENSHOTS } from "../model";
34
35
  import { rowKey } from "../table-model";
35
36
  import { CompanyFlow, CompanyFlowList, FLOW_MIN_WIDTH } from "./flow";
36
37
  import {
@@ -210,7 +211,7 @@ export function BuildoutCompanyPane({ focused, width, height }: PaneProps) {
210
211
  }
211
212
  if (!company) {
212
213
  if (missing) return frame(<EmptyState title={`${symbol} is not in TheBuildout.`} />);
213
- if (profile.error) return frame(<PaneStatusBody error={String(profile.error)} subject="TheBuildout" retry={{ onRetry: () => void profile.load(true) }} />);
214
+ if (profile.error) return frame(<PaneStatusBody error={String(profile.error)} subject="TheBuildout" retry={String(profile.error) === NOT_IN_SCREENSHOTS ? undefined : { onRetry: () => void profile.load(true) }} />);
214
215
  return frame(<PaneStatusBody loading subject="TheBuildout" />);
215
216
  }
216
217
 
@@ -1,4 +1,5 @@
1
1
  import { apiClient } from "../../../../api-client";
2
+ import { isShotRequestRefused } from "../../../../api-client/errors";
2
3
  import { createTtlCache } from "../../../../data/ttl-cache";
3
4
  import { httpFetch } from "../../../../utils/http-transport";
4
5
  import { logFailure } from "../../../../utils/log-failure";
@@ -138,6 +139,9 @@ export interface BuildoutReader {
138
139
  token: string | null;
139
140
  }
140
141
 
142
+ /** What a pane shows in a screenshot of an account with the plan, whose token the capture never holds. */
143
+ export const NOT_IN_SCREENSHOTS = "Not available in screenshots.";
144
+
141
145
  const NO_GRANT: BuildoutGrant = { token: null, expiresAtMs: null };
142
146
  /** A token is asked for again this long before it lapses. */
143
147
  const TOKEN_RENEW_EARLY_MS = 60_000;
@@ -186,6 +190,8 @@ export async function getBuildoutReader({ fresh = false }: { fresh?: boolean } =
186
190
  const grant = await grants.load(user.id, () => issueGrant(restored !== null), { force: fresh });
187
191
  return { account: user.id, token: grant.token };
188
192
  } catch (error) {
193
+ // A capture's proxy never mints a plan's token: access is not unknown, the capture cannot carry it.
194
+ if (isShotRequestRefused(error)) throw new Error(NOT_IN_SCREENSHOTS);
189
195
  logFailure("buildout.model", "Check access failed")(error);
190
196
  throw new Error("Access check failed. Access is unknown.");
191
197
  }
@@ -34,6 +34,7 @@ import type {
34
34
  import {
35
35
  BUILDOUT_NAME,
36
36
  LOAD_MORE_THRESHOLD,
37
+ NOT_IN_SCREENSHOTS,
37
38
  buildoutApi,
38
39
  } from "../model";
39
40
  import { renderBuildoutCell } from "../cells";
@@ -447,7 +448,7 @@ export function BuildoutPane({ focused, width, height }: PaneProps) {
447
448
  <Box flexDirection="column" width={width} height={height} overflow="hidden">
448
449
  {tabStrip && <Box height={1}>{tabStrip}</Box>}
449
450
  {state.status === "loading" ? <PaneStatusBody loading subject={BUILDOUT_NAME} />
450
- : <PaneStatusBody error={state.message} subject={BUILDOUT_NAME} retry={{ onRetry: refresh }} />}
451
+ : <PaneStatusBody error={state.message} subject={BUILDOUT_NAME} retry={state.message === NOT_IN_SCREENSHOTS ? undefined : { onRetry: refresh }} />}
451
452
  </Box>
452
453
  );
453
454
  }
@@ -32,7 +32,7 @@ function screenshotEvidence(paneId: string): PaneScreenshotEvidenceHook<Catalyst
32
32
  const payload = validateCatalysts(value.payload as unknown as CatalystResponse);
33
33
  if (value.rowIds.some((id) => !payload.events.some((event) => event.id === id)) || value.plottedValueCount !== value.rowIds.length) return null;
34
34
  return value as unknown as CatalystEvidence;
35
- } catch { return null; }
35
+ } catch { /* Intentional ignore: invalid captured observations are rejected as evidence by returning null. */ return null; }
36
36
  },
37
37
  mismatches(evidence, { resolved, payload }) {
38
38
  const snapshot = payload.config.layout.instances.find((pane) => pane.instanceId === payload.paneId)?.settings?.catalystSnapshot;
@@ -18,6 +18,7 @@ import { CLOUD_PLAN_KEY, useCloudUpgradeAction } from "../shared/cloud-upgrade";
18
18
  import { useOpenDescription } from "../shared/open-description";
19
19
  import { Blurred, LockedOverlay, UpgradeLabel } from "../shared/locked-rows";
20
20
  import { listingCell, toneColor } from "../shared/research-cells";
21
+ import { logFailure } from "../../../utils/log-failure";
21
22
  import { isCloudSessionRequired, useResearchCloudSession } from "../shared/research-cloud-session";
22
23
  import { loadCatalystDetail, loadCatalysts, validateCatalysts } from "./client";
23
24
  import { CatalystEventDetail } from "./detail";
@@ -65,7 +66,7 @@ export function CatalystView({ width, height, focused, symbol, litigation = fals
65
66
  const [selectedId, setSelectedId] = usePluginPaneState<string | null>("catalyst:selected", null);
66
67
  const [searchActive, setSearchActive] = useState(false);
67
68
  const [dateFieldActive, setDateFieldActive] = useState<string | null>(null);
68
- const snapshot = useMemo(() => { try { return snapshotSetting ? validateCatalysts(snapshotSetting) : null; } catch { return null; } }, [snapshotSetting]);
69
+ const snapshot = useMemo(() => { try { return snapshotSetting ? validateCatalysts(snapshotSetting) : null; } catch (error) { return logFailure("catalysts.pane", "Validate catalysts snapshot failed", null)(error); } }, [snapshotSetting]);
69
70
  const query = useMemo(() => catalystQuery({ ...filters, tab }, symbol ?? undefined, litigation), [filters, tab, symbol, litigation]);
70
71
  const loader = useCallback(async ({ offset, signal, force }: PageRequest) => {
71
72
  const result = snapshot ? { payload: snapshot, stale: false, refreshError: null } : await loadCatalysts({ ...query, limit: 100, offset }, accessKey, force, signal);
@@ -37,7 +37,7 @@ import { futuresSessionOpenMinute } from "../../../market-data/market/trading-se
37
37
  import { isAlwaysOpenExchange, isRegularSessionTime } from "../../../market-data/market/freshness";
38
38
  import { isRoundTheClockCoin } from "../../../utils/crypto-pair";
39
39
  import { isCurrencyPairListing } from "../../../utils/fx-market-hours";
40
- import { cleanFloat32Price } from "../../../cli/history-rows";
40
+ import { cleanFloat32Price, historyPriceDecimals } from "../../../cli/history-rows";
41
41
  import { parseChartSpec } from "./chart-spec";
42
42
  import { paneSchemas } from "./headless-schema";
43
43
  import { barHistoryFreshness, DAILY_CLOSES, REPORTED_DATA } from "../shared/report-freshness";
@@ -533,6 +533,43 @@ function tradedBars(series: HeadlessSeries): HeadlessSeries {
533
533
  };
534
534
  }
535
535
 
536
+ /** The significant digits an exported bar price keeps however few decimals its series needs, as `formatSignificant` shows a small value. */
537
+ const PRICE_SIGNIFICANT_FLOOR = 4;
538
+
539
+ /**
540
+ * A chart's bars at the series' own precision: each price the decimal the
541
+ * feed's float stands for (113.045, not 113.044998), then all of them to the
542
+ * decimals nine in ten need (historyPriceDecimals), so a bar from a finer
543
+ * source reads as the rest do: USDJPY=X's 154.19901 among three-decimal bars
544
+ * is 154.199. A price those decimals would leave with fewer than four
545
+ * significant digits keeps four, so a reverse-split penny stock adjusted up to
546
+ * 50,000 still writes its 0.00421875 as 0.004219, never 0. A `value` that is
547
+ * no close (a transform) keeps its digits.
548
+ */
549
+ function barsAtSeriesPrecision(series: HeadlessSeries): HeadlessSeries {
550
+ if (!series.points.some((point) => point.close != null)) return series;
551
+ const valueIsClose = series.points.every((point) => point.value == null || point.value === point.close);
552
+ const clean = (price: number | null | undefined) => price == null || !Number.isFinite(price) ? price : cleanFloat32Price(price);
553
+ const decimals = historyPriceDecimals(series.points.map((point) => ({
554
+ open: clean(point.open) ?? null, high: clean(point.high) ?? null, low: clean(point.low) ?? null, close: clean(point.close) ?? null,
555
+ })));
556
+ const round = (price: number | null | undefined) => {
557
+ const cleaned = clean(price);
558
+ if (cleaned == null || !Number.isFinite(cleaned) || cleaned === 0) return cleaned;
559
+ const floorDecimals = PRICE_SIGNIFICANT_FLOOR - 1 - Math.floor(Math.log10(Math.abs(cleaned)));
560
+ return floorDecimals > decimals ? Number(cleaned.toPrecision(PRICE_SIGNIFICANT_FLOOR)) : Number(cleaned.toFixed(decimals));
561
+ };
562
+ return {
563
+ ...series,
564
+ points: series.points.map((point) => {
565
+ const bar = { ...point };
566
+ for (const field of ["open", "high", "low", "close"] as const) if (point[field] !== undefined) bar[field] = round(point[field]);
567
+ if (point.value != null && valueIsClose) bar.value = bar.close;
568
+ return bar;
569
+ }),
570
+ };
571
+ }
572
+
536
573
  /** What a chart series was asked as: a listing as typed (`USDZAR=X`, `SAN:EPA`), a FRED series by its ID. */
537
574
  function askedSymbol(source: ChartSeriesSource): string {
538
575
  switch (source.kind) {
@@ -830,6 +867,8 @@ export function chartHeadless(template: keyof typeof paneSchemas): HeadlessPaneD
830
867
  const interval = servedInterval(series as HeadlessSeries & Pick<ResolvedSeries, "historyResolution" | "barSize" | "nativeFrequency">);
831
868
  return { ...series, ...(symbol ? { symbol } : {}), ...(interval ? { interval } : {}) };
832
869
  });
870
+ // GIP keeps each intraday print as traded (a sub-penny 86.3775); a chart's bars read at the series' precision.
871
+ if (template !== "graph-intraday-price-pane") model.series = model.series.map(barsAtSeriesPrecision);
833
872
  if (template === "graph-intraday-price-pane") {
834
873
  model.series = model.series.map(tradedBars);
835
874
  const regular = regularSessionNotice(intradayHistories.map((window) => ({ ...window, exchange: listingExchange(window.symbol, window.exchange) })));