@gloom-sh/terminal 0.20.5 → 0.20.7

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 (185) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/package.json +2 -1
  4. package/src/api-client/data.ts +10 -2
  5. package/src/api-client/fund-facts.ts +20 -4
  6. package/src/api-client/hk-tenders.ts +59 -0
  7. package/src/api-client/index.ts +1 -0
  8. package/src/api-client/socket.ts +4 -4
  9. package/src/api-client/types/econ.ts +20 -2
  10. package/src/app.tsx +18 -13
  11. package/src/architecture/floating-promise-allowlist.json +313 -0
  12. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  13. package/src/cli/commands/market.ts +197 -57
  14. package/src/cli/commands/news-search.ts +22 -7
  15. package/src/cli/commands/overview.ts +12 -6
  16. package/src/cli/commands/search.ts +19 -3
  17. package/src/cli/commands/ticker.ts +3 -1
  18. package/src/cli/desktop-pane-shot.ts +61 -0
  19. package/src/cli/early-command.ts +2 -0
  20. package/src/cli/errors.ts +10 -1
  21. package/src/cli/fx-forward.ts +76 -12
  22. package/src/cli/fx-pair.ts +1 -1
  23. package/src/cli/fx-quote-rate.ts +23 -0
  24. package/src/cli/help.ts +1 -0
  25. package/src/cli/index-roots.ts +5 -4
  26. package/src/cli/index.ts +40 -3
  27. package/src/cli/known-gaps.ts +11 -8
  28. package/src/cli/listing-arg.ts +6 -4
  29. package/src/cli/options.ts +52 -3
  30. package/src/cli/output-file.ts +5 -3
  31. package/src/cli/pane-functions/catalog.ts +15 -0
  32. package/src/cli/pane-functions/dom.ts +4 -4
  33. package/src/cli/pane-functions/freshness.ts +38 -5
  34. package/src/cli/pane-functions/function-help.ts +4 -4
  35. package/src/cli/pane-functions/headless.ts +9 -4
  36. package/src/cli/pane-functions/index.ts +6 -4
  37. package/src/cli/pane-functions/resolver.ts +2 -2
  38. package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
  39. package/src/cli/quote-answer.ts +57 -1
  40. package/src/cli/result.ts +38 -2
  41. package/src/cli/spreadsheet-hint.ts +7 -3
  42. package/src/cli/treasury-yields.ts +5 -3
  43. package/src/components/chart/composite/legend.tsx +40 -2
  44. package/src/components/command-bar/workflow/tickers.ts +2 -2
  45. package/src/components/data-table/view.tsx +9 -2
  46. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  47. package/src/components/ui/data-table/opentui/model.ts +8 -6
  48. package/src/components/ui/data-table/types.ts +6 -1
  49. package/src/components/ui/table-layout.ts +38 -1
  50. package/src/docs/snapshot.json +58 -19
  51. package/src/i18n/es.ts +2 -0
  52. package/src/i18n/ja.ts +2 -0
  53. package/src/i18n/ko.ts +2 -0
  54. package/src/i18n/zh-cn.ts +2 -0
  55. package/src/i18n/zh-tw.ts +2 -0
  56. package/src/market-data/market/change-basis.ts +57 -12
  57. package/src/market-data/market/dated-previous-close.ts +184 -10
  58. package/src/market-data/market/freshness.ts +18 -6
  59. package/src/market-data/market/status.ts +9 -1
  60. package/src/market-data/published-nse-sessions.ts +16 -1
  61. package/src/market-data/quotes/contributions.ts +2 -0
  62. package/src/market-data/quotes/freshness.ts +15 -0
  63. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  64. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  65. package/src/plugins/builtin/alerts/cli.ts +22 -9
  66. package/src/plugins/builtin/alerts/headless.ts +1 -1
  67. package/src/plugins/builtin/alerts/index.tsx +5 -1
  68. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  69. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  70. package/src/plugins/builtin/backtest/headless.ts +1 -1
  71. package/src/plugins/builtin/cds/model.ts +0 -6
  72. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  73. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  74. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  75. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  76. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  77. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  78. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  79. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  80. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  81. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  82. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  83. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  84. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  85. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  86. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  87. package/src/plugins/builtin/econ/calendar-model.ts +41 -7
  88. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  89. package/src/plugins/builtin/econ/index.tsx +41 -8
  90. package/src/plugins/builtin/econ/types.ts +3 -0
  91. package/src/plugins/builtin/fixed-income/index.tsx +2 -0
  92. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  93. package/src/plugins/builtin/help/keybindings-editor.tsx +6 -2
  94. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  95. package/src/plugins/builtin/holders/headless.ts +5 -4
  96. package/src/plugins/builtin/holders/pane.tsx +7 -3
  97. package/src/plugins/builtin/holders/report-header.ts +23 -0
  98. package/src/plugins/builtin/members/client.ts +1 -1
  99. package/src/plugins/builtin/members/headless.ts +2 -0
  100. package/src/plugins/builtin/members/model.ts +10 -8
  101. package/src/plugins/builtin/members/pane.tsx +4 -1
  102. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
  103. package/src/plugins/builtin/portfolio-list/cli/render.ts +86 -26
  104. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  105. package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
  106. package/src/plugins/builtin/portfolio-list/income.ts +46 -22
  107. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  108. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
  109. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  110. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  111. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  112. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  113. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  114. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  115. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  116. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  117. package/src/plugins/builtin/sec/fund-facts.ts +25 -5
  118. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  119. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  120. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  121. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  122. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  123. package/src/plugins/builtin/ticker-detail/financials/model.ts +6 -2
  124. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +1 -1
  125. package/src/plugins/builtin/ticker-detail/headless.ts +6 -4
  126. package/src/plugins/builtin/treasury-auctions/cache.ts +36 -2
  127. package/src/plugins/builtin/treasury-auctions/headless.ts +42 -4
  128. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  129. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  130. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  131. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -1
  132. package/src/plugins/builtin/treasury-auctions/model.ts +16 -8
  133. package/src/plugins/builtin/treasury-auctions/pane.tsx +45 -21
  134. package/src/portfolio/collection-name.ts +22 -0
  135. package/src/portfolio/column-values.ts +3 -0
  136. package/src/portfolio/valuation-basis.ts +23 -1
  137. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  138. package/src/renderers/dom/data-table/index.tsx +27 -9
  139. package/src/renderers/dom/data-table/row.tsx +2 -0
  140. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  141. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  142. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  143. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  144. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  145. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  146. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  147. package/src/sources/provider-router/cache.ts +3 -1
  148. package/src/state/hooks/quote-streaming.ts +14 -6
  149. package/src/sync/controller.ts +17 -2
  150. package/src/sync/other-window-tabs.ts +32 -1
  151. package/src/sync/react.ts +4 -4
  152. package/src/tickers/instrument-kind.ts +22 -1
  153. package/src/tickers/search/index.ts +5 -0
  154. package/src/tickers/terminal-codes.ts +17 -5
  155. package/src/time-series/bar-spacing.ts +33 -0
  156. package/src/time-series/base-series.ts +21 -3
  157. package/src/time-series/chart-bounds.ts +31 -0
  158. package/src/time-series/field-catalog.ts +17 -0
  159. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  160. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  161. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  162. package/src/time-series/fundamentals/period-points.ts +104 -0
  163. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  164. package/src/time-series/fundamentals/series.ts +164 -0
  165. package/src/time-series/fundamentals/source-statements.ts +177 -0
  166. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  167. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  168. package/src/time-series/fundamentals/statement.ts +114 -0
  169. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  170. package/src/time-series/fundamentals.ts +18 -1275
  171. package/src/time-series/ice-credit.ts +32 -6
  172. package/src/time-series/resolve.ts +9 -5
  173. package/src/time-series/session-bar.ts +78 -9
  174. package/src/time-series/studies/formula.ts +53 -10
  175. package/src/time-series/studies/pair.ts +18 -7
  176. package/src/time-series/studies/units.ts +49 -2
  177. package/src/time-series/types.ts +12 -0
  178. package/src/types/desktop-window.ts +2 -0
  179. package/src/types/financials.ts +15 -0
  180. package/src/types/headless.ts +8 -0
  181. package/src/utils/cli-output.ts +6 -3
  182. package/src/utils/debug-log.ts +29 -0
  183. package/src/utils/ebitda.ts +128 -0
  184. package/src/utils/format.ts +1 -1
  185. package/src/utils/shell-word.ts +13 -0
@@ -64,7 +64,9 @@ export function getPortfolioValuationDisplay(
64
64
  * When the price a position is valued at on `basis` is from: the quote's time
65
65
  * for a print, the session's close for a regular close
66
66
  * (regularSessionValuationTime), and a future's settlement session at the
67
- * close. Null without a dated quote or settlement.
67
+ * close. A nominal price, nothing having traded, is dated by the session it is
68
+ * the venue's price for (Quote.nominalPrice), on either basis: its last trade
69
+ * is older and at another price. Null without a dated quote or settlement.
68
70
  */
69
71
  export function getPortfolioValuationTime(
70
72
  quote: Quote | null | undefined,
@@ -77,10 +79,30 @@ export function getPortfolioValuationTime(
77
79
  return Number.isFinite(day) ? { time: day, dateOnly: true } : null;
78
80
  }
79
81
  if (!quote) return null;
82
+ const nominal = nominalPriceDay(quote);
83
+ if (nominal) return nominal;
80
84
  if (valuesAtClose(metrics, basis)) return regularSessionValuationTime(quote);
81
85
  return Number.isFinite(quote.lastUpdated) && quote.lastUpdated > 0 ? { time: quote.lastUpdated, dateOnly: false } : null;
82
86
  }
83
87
 
88
+ /**
89
+ * Whether a position is valued at its venue's nominal price on `basis`: a
90
+ * quote nothing traded at (Quote.nominalPrice), never a future at its
91
+ * settlement.
92
+ */
93
+ export function valuesAtNominalPrice(
94
+ quote: Quote | null | undefined,
95
+ metrics: Pick<PortfolioPositionMetrics, "isFuture"> | null | undefined,
96
+ basis: PortfolioValuationBasis = "latest-print",
97
+ ): boolean {
98
+ return !!quote?.nominalPrice && !valuesAtSettlement(metrics ?? null, basis);
99
+ }
100
+
101
+ function nominalPriceDay(quote: Quote): ReportTime | null {
102
+ const day = quote.nominalPrice ? Date.parse(`${quote.nominalPrice.session}T00:00:00Z`) : Number.NaN;
103
+ return Number.isFinite(day) ? { time: day, dateOnly: true } : null;
104
+ }
105
+
84
106
  /** A valuation time as exports write it: an ISO instant in UTC, or an ISO date. */
85
107
  export function valuationTimeIso(time: ReportTime | null): string | null {
86
108
  if (!time) return null;
@@ -1,9 +1,11 @@
1
1
  import { useLayoutEffect, useRef, useState } from "react";
2
2
 
3
3
  /** Fit partially covered cells into their remaining area, retaining text ellipses. */
4
- export function useFrozenColumnInsets(enabled: boolean, scrollLeft: number, viewportWidth: number, columns: unknown, gap: number) {
4
+ export function useFrozenColumnInsets(frozen: boolean, scrollLeft: number, viewportWidth: number, columns: unknown, gap: number) {
5
5
  const ref = useRef<HTMLDivElement>(null);
6
6
  const [insets, setInsets] = useState<number[]>([]);
7
+ // Unscrolled, no column is under the frozen one and every inset is 0: a resize measures nothing.
8
+ const enabled = frozen && scrollLeft > 0;
7
9
  useLayoutEffect(() => {
8
10
  const cells = ref.current?.children;
9
11
  if (!enabled || !cells?.length) {
@@ -11,6 +11,7 @@ import {
11
11
  type ReactNode,
12
12
  type RefObject,
13
13
  } from "react";
14
+ import { flushSync } from "react-dom";
14
15
  import { EmptyState } from "../../../components/ui/status";
15
16
  import { usePaneInstance } from "../../../state/app/context";
16
17
  import { useRegisterPaneScrollBox } from "../../../state/pane-scroll-registry";
@@ -26,6 +27,7 @@ import {
26
27
  buildTableGridTemplateColumns,
27
28
  getTableWidth,
28
29
  hasMeaningfulTableHorizontalOverflow,
30
+ tableFreezesFirstColumn,
29
31
  } from "../../../components/ui/table-layout";
30
32
  import { WEB_CELL_HEIGHT, WEB_CELL_WIDTH } from "../../../theme/font-scale";
31
33
  import { isLiveResizing, onLiveResizeEnd } from "../../../ui/live-resize";
@@ -113,7 +115,7 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
113
115
  horizontalPadding = 1,
114
116
  fillAvailableWidth = true,
115
117
  showHorizontalScrollbar = true,
116
- freezeFirstColumn = false,
118
+ freezeFirstColumn: freezeFirstColumnProp,
117
119
  scrollToIndex,
118
120
  scrollToIndexAlign = "nearest",
119
121
  scrollToIndexVersion = 0,
@@ -202,6 +204,17 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
202
204
  const bodyAfterHeight = bodyAfter ? WEB_CELL_HEIGHT * 6 : 0;
203
205
  const horizontalScrollEnabled = showHorizontalScrollbar
204
206
  && hasMeaningfulTableHorizontalOverflow(tableWidth, viewportWidth, columnGap);
207
+ const freezeFirstColumn = tableFreezesFirstColumn({
208
+ freezeFirstColumn: freezeFirstColumnProp, columns, columnGap, horizontalPadding, viewportWidth,
209
+ overflows: horizontalScrollEnabled,
210
+ });
211
+ // A table that pins by default pins once scrolled: unscrolled nothing is under
212
+ // its first column, so a pane dragged or resized at rest draws no sticky cells.
213
+ const pinned = freezeFirstColumn && (freezeFirstColumnProp === true || frozenScrollLeft > 0);
214
+ // Pinned from a scroll that came before it, it starts where the body is.
215
+ useLayoutEffect(() => {
216
+ if (freezeFirstColumn) setFrozenScrollLeft(bodyElementRef.current?.scrollLeft ?? 0);
217
+ }, [freezeFirstColumn]);
205
218
  const scrollContentWidth = horizontalScrollEnabled
206
219
  || !fillAvailableWidth
207
220
  ? Math.max(1, tableWidth * WEB_CELL_WIDTH)
@@ -325,7 +338,7 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
325
338
  const [frozenEdgePx, setFrozenEdgePx] = useState(0);
326
339
  useLayoutEffect(() => {
327
340
  const body = bodyElementRef.current;
328
- const frozenCell = freezeFirstColumn && overflowEdges.start
341
+ const frozenCell = pinned && overflowEdges.start
329
342
  ? body?.querySelector<HTMLElement>('[data-gloom-role="data-table-header-cell"]')
330
343
  : null;
331
344
  // The gap after it is the next column's margin, as laid out.
@@ -336,7 +349,7 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
336
349
  : 0;
337
350
  // Set only on a change: a state update from a layout effect costs the render a second commit.
338
351
  if (next !== frozenEdgePx) setFrozenEdgePx(next);
339
- }, [columnGap, columns, freezeFirstColumn, frozenEdgePx, overflowEdges.start, viewportWidth]);
352
+ }, [columnGap, columns, pinned, frozenEdgePx, overflowEdges.start, viewportWidth]);
340
353
 
341
354
  const rootStyle: CSSProperties = {
342
355
  position: "relative",
@@ -390,7 +403,12 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
390
403
  }}
391
404
  onScroll={(event) => {
392
405
  markScrollbarActive();
393
- if (freezeFirstColumn) setFrozenScrollLeft(event.currentTarget.scrollLeft);
406
+ if (freezeFirstColumn) {
407
+ const left = event.currentTarget.scrollLeft;
408
+ // Pinning on the first scroll away draws before that frame shows the column leaving.
409
+ if (!pinned && left > 0) flushSync(() => setFrozenScrollLeft(left));
410
+ else setFrozenScrollLeft(left);
411
+ }
394
412
  const controlledOffset = controlledScrollOffsetRef.current;
395
413
  controlledScrollOffsetRef.current = null;
396
414
  if (controlledOffset
@@ -418,9 +436,9 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
418
436
  >
419
437
  <WebDataTableHeader
420
438
  columns={columns}
421
- freezeFirstColumn={freezeFirstColumn}
439
+ freezeFirstColumn={pinned}
422
440
  scrollLeft={frozenScrollLeft}
423
- viewportWidth={freezeFirstColumn ? viewportWidth : 0}
441
+ viewportWidth={pinned && frozenScrollLeft > 0 ? viewportWidth : 0}
424
442
  columnGap={columnGap}
425
443
  horizontalPadding={horizontalPadding}
426
444
  focusPane={focusPane}
@@ -453,11 +471,11 @@ export function WebDataTable<T, C extends DataTableColumn = DataTableColumn>({
453
471
  item={item}
454
472
  itemKey={itemKey}
455
473
  columns={columns}
456
- freezeFirstColumn={freezeFirstColumn}
474
+ freezeFirstColumn={pinned}
457
475
  scrollLeft={frozenScrollLeft}
458
- // Only a frozen first column places itself by it: every
476
+ // Only a frozen first column scrolled past places itself by it: every
459
477
  // other row stays memoized when the viewport changes width.
460
- viewportWidth={freezeFirstColumn ? viewportWidth : 0}
478
+ viewportWidth={pinned && frozenScrollLeft > 0 ? viewportWidth : 0}
461
479
  columnGap={columnGap}
462
480
  horizontalPadding={horizontalPadding}
463
481
  focusPane={focusPane}
@@ -297,6 +297,8 @@ function WebDataTableRowInner<
297
297
  sectionHeader.attributes ?? TextAttributes.BOLD,
298
298
  ),
299
299
  gridColumn: "1 / -1",
300
+ // Beside a pinned first column the heading stays in view too, not cut to its last letters.
301
+ ...(freezeFirstColumn ? { position: "sticky", left: inlinePaddingPx(horizontalPadding), justifySelf: "start" } : {}),
300
302
  overflow: "hidden",
301
303
  textOverflow: "ellipsis",
302
304
  display: "flex",
@@ -1,7 +1,6 @@
1
1
  import Electrobun, { ApplicationMenu, BrowserView, Screen, Utils, type BrowserWindow } from "electrobun/bun";
2
2
  import { homedir } from "os";
3
3
  import { createAppServices, type AppServices } from "../../../../core/app-services";
4
- import { syncConfigActiveLayoutState, type PaneRuntimeState } from "../../../../core/state/app/state";
5
4
  import {
6
5
  APP_SESSION_ID,
7
6
  APP_SESSION_SCHEMA_VERSION,
@@ -77,6 +76,13 @@ import { scheduleDesktopRelaunch } from "./relaunch";
77
76
  import { createDesktopRpcRegistry } from "./rpc-registry";
78
77
  import { measureRpcTraffic } from "./rpc-timing";
79
78
  import { DesktopStateBroadcaster } from "./state-broadcaster";
79
+ import {
80
+ commitDesktopSnapshot,
81
+ commitDesktopSnapshotInBackground,
82
+ syncActiveLayout,
83
+ type DesktopSnapshotCommitHost,
84
+ type DesktopSnapshotCommitOptions,
85
+ } from "./snapshot-commit";
80
86
  import { createDesktopWorkspace, type DesktopWorkspace } from "./workspace";
81
87
  import { handleDesktopWorkspaceRequest } from "./workspace/requests";
82
88
 
@@ -105,14 +111,6 @@ function isGloomberbDeepLink(rawUrl: string): boolean {
105
111
  }
106
112
  }
107
113
 
108
- function syncActiveLayout(
109
- config: AppConfig,
110
- paneState: Record<string, PaneRuntimeState> = config.layouts[config.activeLayoutIndex]?.paneState ?? {},
111
- focusedPaneId: string | null = config.layouts[config.activeLayoutIndex]?.focusedPaneId ?? null,
112
- ): AppConfig {
113
- return syncConfigActiveLayoutState(config, paneState, focusedPaneId);
114
- }
115
-
116
114
  /**
117
115
  * Everything the desktop Bun process holds for its windows: the config and
118
116
  * services they share, the workspace that owns popped-out panes, the native
@@ -391,7 +389,7 @@ export class DesktopBackend {
391
389
  if (this.quitting) return;
392
390
  const workspace = this.workspace;
393
391
  if (!workspace || !workspace.windowIds().includes(windowId)) return;
394
- void this.commitDesktopSnapshot(workspace.closeWindow(windowId));
392
+ this.commitDesktopSnapshotInBackground(workspace.closeWindow(windowId));
395
393
  }
396
394
 
397
395
  /** What a closed full window held: its streams, its channel. */
@@ -512,22 +510,27 @@ export class DesktopBackend {
512
510
  this.services = null;
513
511
  }
514
512
 
515
- async commitDesktopSnapshot(
513
+ private readonly snapshotCommits: DesktopSnapshotCommitHost = {
514
+ setConfig: (config) => this.setConfig(config),
515
+ replaceConfig: (config, options) => { this.requireWorkspace().replaceConfig(config, options); },
516
+ currentSnapshot: () => this.requireWorkspace().getSnapshot(),
517
+ saveConfig: (config) => saveConfig(config),
518
+ reconcileWindows: () => this.reconcileWindows(),
519
+ broadcastState: (snapshot) => this.stateBroadcaster.sendDesktopState(snapshot),
520
+ sendWindowList: () => this.sendWindowList(),
521
+ reportSaveFailure: () => { this.readyMainWindowRpc()?.send["desktop.saveFailed"]({}); },
522
+ };
523
+
524
+ commitDesktopSnapshot(
516
525
  snapshot: DesktopSharedStateSnapshot,
517
- options: { persistConfig?: boolean; reconcileWindows?: boolean } = {},
526
+ options: DesktopSnapshotCommitOptions = {},
518
527
  ): Promise<DesktopSharedStateSnapshot> {
519
- const nextConfig = syncActiveLayout(snapshot.config, snapshot.paneState, snapshot.focusedPaneId);
520
- this.setConfig(nextConfig);
521
- this.requireWorkspace().replaceConfig(nextConfig, { layoutChanged: snapshot.layoutChanged });
522
- if (options.persistConfig !== false) {
523
- await saveConfig(nextConfig);
524
- }
525
- if (options.reconcileWindows !== false) {
526
- this.reconcileWindows();
527
- }
528
- this.stateBroadcaster.sendDesktopState(this.requireWorkspace().getSnapshot());
529
- this.sendWindowList();
530
- return this.requireWorkspace().getSnapshot();
528
+ return commitDesktopSnapshot(this.snapshotCommits, snapshot, options);
529
+ }
530
+
531
+ /** For a change no request waits on: a failure is logged and the main window says so. */
532
+ commitDesktopSnapshotInBackground(snapshot: DesktopSharedStateSnapshot, options: DesktopSnapshotCommitOptions = {}): void {
533
+ commitDesktopSnapshotInBackground(this.snapshotCommits, snapshot, options);
531
534
  }
532
535
 
533
536
  /** Stops what a closed window was streaming or subscribed to. */
@@ -80,7 +80,7 @@ export class DesktopDetachedWindowManager {
80
80
  const workspace = this.backend.workspace;
81
81
  const config = this.backend.config;
82
82
  if (!workspace || !config || !isPaneDetached(config.layout, instanceId)) return;
83
- void this.backend.commitDesktopSnapshot(workspace.closeDetachedPane(instanceId));
83
+ this.backend.commitDesktopSnapshotInBackground(workspace.closeDetachedPane(instanceId));
84
84
  }
85
85
 
86
86
  /**
@@ -264,7 +264,7 @@ export class DesktopDetachedWindowManager {
264
264
  const nextConfig = this.backend.config;
265
265
  const nextWorkspace = this.backend.workspace;
266
266
  if (!nextConfig || !nextWorkspace || !isPaneDetached(nextConfig.layout, instanceId)) return;
267
- void this.backend.commitDesktopSnapshot(
267
+ this.backend.commitDesktopSnapshotInBackground(
268
268
  this.backend.requireWorkspace().updateDetachedFrame(instanceId, frame),
269
269
  { reconcileWindows: false },
270
270
  );
@@ -302,7 +302,7 @@ export class DesktopDetachedWindowManager {
302
302
  || this.backend.stateBroadcaster.currentDockPreview.edge !== edge
303
303
  ) return;
304
304
  this.backend.stateBroadcaster.clearDockPreview(instanceId);
305
- void this.backend.commitDesktopSnapshot(this.backend.requireWorkspace().dockDetachedPane(instanceId, edge));
305
+ this.backend.commitDesktopSnapshotInBackground(this.backend.requireWorkspace().dockDetachedPane(instanceId, edge));
306
306
  }, 120));
307
307
  }
308
308
 
@@ -0,0 +1,77 @@
1
+ import { syncConfigActiveLayoutState, type PaneRuntimeState } from "../../../../core/state/app/state";
2
+ import type { AppConfig } from "../../../../types/config";
3
+ import type { DesktopSharedStateSnapshot } from "../../../../types/desktop-window";
4
+ import { logFailure } from "../../../../utils/log-failure";
5
+
6
+ export function syncActiveLayout(
7
+ config: AppConfig,
8
+ paneState: Record<string, PaneRuntimeState> = config.layouts[config.activeLayoutIndex]?.paneState ?? {},
9
+ focusedPaneId: string | null = config.layouts[config.activeLayoutIndex]?.focusedPaneId ?? null,
10
+ ): AppConfig {
11
+ return syncConfigActiveLayoutState(config, paneState, focusedPaneId);
12
+ }
13
+
14
+ /** What a desktop state change touches in the backend. */
15
+ export interface DesktopSnapshotCommitHost {
16
+ setConfig(config: AppConfig): void;
17
+ replaceConfig(config: AppConfig, options: { layoutChanged?: boolean }): void;
18
+ currentSnapshot(): DesktopSharedStateSnapshot;
19
+ saveConfig(config: AppConfig): Promise<void>;
20
+ reconcileWindows(): void;
21
+ broadcastState(snapshot: DesktopSharedStateSnapshot): void;
22
+ sendWindowList(): void;
23
+ /** Tells the person a change nobody waited on was not saved. */
24
+ reportSaveFailure(): void;
25
+ }
26
+
27
+ export interface DesktopSnapshotCommitOptions {
28
+ persistConfig?: boolean;
29
+ reconcileWindows?: boolean;
30
+ }
31
+
32
+ /**
33
+ * Makes a state change the backend's, saves its config and shows it in every
34
+ * window. The windows follow even when the save fails: the backend holds the
35
+ * change already, and a window left on the old state would send it back. The
36
+ * failed save rejects after that.
37
+ */
38
+ export async function commitDesktopSnapshot(
39
+ host: DesktopSnapshotCommitHost,
40
+ snapshot: DesktopSharedStateSnapshot,
41
+ options: DesktopSnapshotCommitOptions = {},
42
+ ): Promise<DesktopSharedStateSnapshot> {
43
+ const nextConfig = syncActiveLayout(snapshot.config, snapshot.paneState, snapshot.focusedPaneId);
44
+ host.setConfig(nextConfig);
45
+ host.replaceConfig(nextConfig, { layoutChanged: snapshot.layoutChanged });
46
+ let saveFailure: { error: unknown } | null = null;
47
+ if (options.persistConfig !== false) {
48
+ try {
49
+ await host.saveConfig(nextConfig);
50
+ } catch (error) {
51
+ saveFailure = { error };
52
+ }
53
+ }
54
+ if (options.reconcileWindows !== false) {
55
+ host.reconcileWindows();
56
+ }
57
+ host.broadcastState(host.currentSnapshot());
58
+ host.sendWindowList();
59
+ if (saveFailure) throw saveFailure.error;
60
+ return host.currentSnapshot();
61
+ }
62
+
63
+ /**
64
+ * A change no request waits on: a window or popped-out pane closed, a pane
65
+ * docked or moved by dragging. A failure is logged, and the main window says
66
+ * the change was not saved.
67
+ */
68
+ export function commitDesktopSnapshotInBackground(
69
+ host: DesktopSnapshotCommitHost,
70
+ snapshot: DesktopSharedStateSnapshot,
71
+ options: DesktopSnapshotCommitOptions = {},
72
+ ): void {
73
+ commitDesktopSnapshot(host, snapshot, options).catch((error: unknown) => {
74
+ logFailure("desktop-backend", "Saving a window change failed")(error);
75
+ host.reportSaveFailure();
76
+ });
77
+ }
@@ -377,6 +377,9 @@ interface DesktopWindowVisibilityMessage {
377
377
  visible: boolean;
378
378
  }
379
379
 
380
+ /** A window change no request waited on (a window closed, a pane docked) could not be saved; to the main window. */
381
+ type DesktopSaveFailedMessage = Record<string, never>;
382
+
380
383
  /** Plugin folders the Bun process updated in the background, for the main window to bring into its session. */
381
384
  interface PluginsUpdatedMessage {
382
385
  directories: string[];
@@ -423,6 +426,7 @@ export interface ElectrobunDesktopRpcSchema {
423
426
  "desktop.otherWindowTabs": DesktopOtherWindowTabsMessage;
424
427
  "desktop.focusPane": DesktopFocusPaneMessage;
425
428
  "desktop.windowVisibility": DesktopWindowVisibilityMessage;
429
+ "desktop.saveFailed": DesktopSaveFailedMessage;
426
430
  "plugins.updated": PluginsUpdatedMessage;
427
431
  "plugins.seedProgress": PluginSeedProgressMessage;
428
432
  "update.progress": UpdateProgressMessage;
@@ -101,6 +101,9 @@ const rpc = Electroview.defineRPC<ElectrobunDesktopRpcSchema>({
101
101
  "desktop.windowVisibility": (message) => {
102
102
  emit("desktop.windowVisibility", { visible: message?.visible !== false });
103
103
  },
104
+ "desktop.saveFailed": () => {
105
+ emit("desktop.saveFailed", {});
106
+ },
104
107
  "update.progress": (message) => {
105
108
  emit("update.progress", { progress: decodeRpcValue(message.progress) });
106
109
  },
@@ -124,5 +124,8 @@ export function createDesktopWindowBridge(kind: "main" | "detached", paneId?: st
124
124
  listener(message.preview);
125
125
  });
126
126
  },
127
+ subscribeSaveFailures: kind === "main"
128
+ ? (listener: () => void) => onBackendMessage("desktop.saveFailed", () => listener())
129
+ : undefined,
127
130
  };
128
131
  }
@@ -29,6 +29,7 @@ import { parseOptionTicker } from "../../utils/options";
29
29
  import { reconcileQuoteDayRange } from "../../market-data/quotes/day-range";
30
30
  import { redactUnavailableFundamentals } from "../../utils/fundamentals";
31
31
  import { readWithdrawnObservations } from "../../utils/statement-gaps";
32
+ import { isBankOrInsurerIndustry, withStatementEbitda } from "../../utils/ebitda";
32
33
  import { parseListingDelisting } from "../../market-data/quotes/delisting";
33
34
  import { readIntradayBar, readStaleReason } from "../../market-data/quotes/intraday-bar";
34
35
  import { readSessionSplit } from "../../market-data/quotes/session-split";
@@ -313,11 +314,13 @@ function mapCloudNextEarnings(value: NextEarnings | undefined): NextEarnings | u
313
314
 
314
315
  /**
315
316
  * A served statement row with withdrawn values read as declared gaps, without
316
- * the per-issuer provenance the service can still attach.
317
+ * the per-issuer provenance the service can still attach, and its EBITDA
318
+ * operating income plus D&A whatever the service sent: derived where the row
319
+ * reports no operating income, except for a bank or an insurer (`derive`).
317
320
  */
318
- function mapCloudStatement(row: FinancialStatement): FinancialStatement {
321
+ function mapCloudStatement(row: FinancialStatement, derive: boolean): FinancialStatement {
319
322
  const { earningsResult: _earnings, operatingResult: _operating, operatingResultAggregation: _aggregation, ...statement } = row;
320
- return readWithdrawnObservations(statement);
323
+ return withStatementEbitda(readWithdrawnObservations(statement), derive);
321
324
  }
322
325
 
323
326
  export function mapCloudFinancials(
@@ -329,6 +332,7 @@ export function mapCloudFinancials(
329
332
  const divisor = rawQuote ? resolveCurrencyUnit(rawQuote.currency).divisor : 1;
330
333
  const exchange = rawQuote?.listingExchangeName ?? rawQuote?.exchangeName ?? "";
331
334
  const coin = isRoundTheClockCoin(rawQuote?.symbol, exchange);
335
+ const derive = !isBankOrInsurerIndustry(financials.profile?.industry);
332
336
  return {
333
337
  quote,
334
338
  quoteMetadata: financials.quoteMetadata,
@@ -338,8 +342,8 @@ export function mapCloudFinancials(
338
342
  fundamentals: mapCloudFundamentals(financials.fundamentals),
339
343
  financialCurrency: financials.financialCurrency,
340
344
  statementHistory: financials.statementHistory,
341
- annualStatements: (financials.annualStatements ?? []).map(mapCloudStatement),
342
- quarterlyStatements: (financials.quarterlyStatements ?? []).map(mapCloudStatement),
345
+ annualStatements: (financials.annualStatements ?? []).map((row) => mapCloudStatement(row, derive)),
346
+ quarterlyStatements: (financials.quarterlyStatements ?? []).map((row) => mapCloudStatement(row, derive)),
343
347
  priceHistory: (financials.priceHistory ?? []).map((point) =>
344
348
  point.date instanceof Date
345
349
  ? point
@@ -13,7 +13,9 @@ const MARKET_NAMESPACE = "market";
13
13
  const HOT_READ_TOUCH_MS = 10 * 60_000;
14
14
  // A record written under another version is a miss: bump these instead of
15
15
  // repairing older records on read.
16
- export const FINANCIALS_SCHEMA_VERSION = 13;
16
+ // 14: EBITDA is operating income plus D&A (utils/ebitda.ts), whatever an older record holds.
17
+ // 15: a row without operating income derives it for EBITDA (utils/ebitda.ts), a bank's or an insurer's excepted.
18
+ export const FINANCIALS_SCHEMA_VERSION = 15;
17
19
  export const QUOTE_SCHEMA_VERSION = 3;
18
20
  export const MARKET_METADATA_SCHEMA_VERSION = 2;
19
21
  // Refresh persisted provider metadata through the managed backend on upgrade.
@@ -3,7 +3,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
3
3
  import { useAppVisible, usePaneInView } from "../app/activity";
4
4
  import type { QuoteSubscriptionTarget } from "../../types/data-provider";
5
5
  import type { Quote } from "../../types/financials";
6
- import { debugLog } from "../../utils/debug-log";
6
+ import { debugLog, previewList, type ListPreview } from "../../utils/debug-log";
7
7
  import { normalizeSymbol } from "../../utils/exchanges";
8
8
  import { getSharedMarketDataCoordinator, type MarketDataCoordinator } from "../../market-data/coordinator";
9
9
  import { useQuoteEntries } from "../../market-data/hooks";
@@ -80,6 +80,8 @@ type UpdateableQuoteSubscription = (() => void) & {
80
80
  interface ActiveQuoteSubscription {
81
81
  identityKey: string;
82
82
  subscriptionKey: string;
83
+ /** The subscription's targets as the log names them. */
84
+ preview: ListPreview<string>;
83
85
  count: number;
84
86
  dispose: UpdateableQuoteSubscription;
85
87
  }
@@ -110,7 +112,7 @@ export function useQuoteStreaming(
110
112
  // Keyed on the array, not its contents: callers memoize their targets, and a
111
113
  // portfolio re-renders on every data frame, where re-keying and sorting a
112
114
  // thousand targets cost a few milliseconds each time.
113
- const { coordinatorTargets, identityKey, subscriptionKey } = useMemo(() => {
115
+ const { coordinatorTargets, identityKey, subscriptionKey, preview } = useMemo(() => {
114
116
  const normalizedEntries = new Map<string, QuoteSubscriptionTarget>();
115
117
  for (const target of targets) {
116
118
  const resolved = normalizeQuoteStreamSubscriptionTarget(target);
@@ -127,16 +129,20 @@ export function useQuoteStreaming(
127
129
  .sort()
128
130
  .join("\u001f"),
129
131
  subscriptionKey: sortedEntries.map(([key]) => key).join("|"),
132
+ // The log names the first few targets, not the hundreds a long list subscribes.
133
+ preview: previewList(sortedEntries, ([key]) => key),
130
134
  };
131
135
  }, [paneInView, targets]);
132
136
  const latestSubscriptionRef = useRef({
133
137
  identityKey,
134
138
  subscriptionKey,
139
+ preview,
135
140
  targets: coordinatorTargets,
136
141
  });
137
142
  latestSubscriptionRef.current = {
138
143
  identityKey,
139
144
  subscriptionKey,
145
+ preview,
140
146
  targets: coordinatorTargets,
141
147
  };
142
148
  const activeSubscriptionRef = useRef<ActiveQuoteSubscription | null>(null);
@@ -147,7 +153,7 @@ export function useQuoteStreaming(
147
153
  if (latest.targets.length > 0) {
148
154
  quoteStreamLog.info("skipping subscription", {
149
155
  reason: enabled ? "inactive" : "disabled",
150
- targets: latest.subscriptionKey,
156
+ targets: latest.preview,
151
157
  });
152
158
  }
153
159
  return;
@@ -156,11 +162,12 @@ export function useQuoteStreaming(
156
162
  quoteStreamLog.info("subscribe", {
157
163
  providerId: "market-data",
158
164
  count: latest.targets.length,
159
- targets: latest.subscriptionKey,
165
+ targets: latest.preview,
160
166
  });
161
167
  const active: ActiveQuoteSubscription = {
162
168
  identityKey: latest.identityKey,
163
169
  subscriptionKey: latest.subscriptionKey,
170
+ preview: latest.preview,
164
171
  count: latest.targets.length,
165
172
  dispose: coordinator.subscribeQuotes(latest.targets) as UpdateableQuoteSubscription,
166
173
  };
@@ -172,7 +179,7 @@ export function useQuoteStreaming(
172
179
  quoteStreamLog.info("unsubscribe", {
173
180
  providerId: "market-data",
174
181
  count: active.count,
175
- targets: active.subscriptionKey,
182
+ targets: active.preview,
176
183
  });
177
184
  active.dispose();
178
185
  };
@@ -193,7 +200,7 @@ export function useQuoteStreaming(
193
200
  quoteStreamLog.info("update subscription", {
194
201
  providerId: "market-data",
195
202
  count: latest.targets.length,
196
- targets: latest.subscriptionKey,
203
+ targets: latest.preview,
197
204
  });
198
205
  if (typeof active.dispose.update === "function") {
199
206
  active.dispose.update(latest.targets);
@@ -203,6 +210,7 @@ export function useQuoteStreaming(
203
210
  previousDispose();
204
211
  }
205
212
  active.subscriptionKey = latest.subscriptionKey;
213
+ active.preview = latest.preview;
206
214
  active.count = latest.targets.length;
207
215
  }, [appActive, coordinator, enabled, identityKey, subscriptionKey]);
208
216
  }
@@ -52,6 +52,7 @@ const OBSERVE_DEBOUNCE_MS = 250;
52
52
  const MAX_CONFLICT_RETRIES = 3;
53
53
  const SYNC_HISTORY_UNREADABLE = "This device's sync history could not be read, so sync is paused and local data is kept.";
54
54
  const SYNC_HISTORY_UNSAVED = "This device's sync history could not be saved, so sync is paused until it can be.";
55
+ const SYNC_COLLECT_FAILED = "This device's changes could not be gathered, so they were not synced.";
55
56
 
56
57
  /** Merge history storage refused to write; kept here to write again, and read instead of the older stored copy. */
57
58
  interface UnsavedHistory {
@@ -244,10 +245,15 @@ export class CloudSyncController {
244
245
  if (this.pushTimer) clearTimeout(this.pushTimer);
245
246
  this.pushTimer = setTimeout(() => {
246
247
  this.pushTimer = null;
247
- void this.requestSync({ reason });
248
+ this.startSync({ reason });
248
249
  }, PUSH_DEBOUNCE_MS);
249
250
  }
250
251
 
252
+ /** A sync nobody waits on. Its failures end in the status; anything that escapes is logged. */
253
+ startSync(options: { reason?: string; force?: boolean } = {}): void {
254
+ this.requestSync(options).catch(logFailure("sync.controller", "Sync failed"));
255
+ }
256
+
251
257
  async requestSync(options: { reason?: string; force?: boolean } = {}): Promise<void> {
252
258
  if (this.inFlight) {
253
259
  this.syncQueued = true;
@@ -308,7 +314,16 @@ export class CloudSyncController {
308
314
  const pulled = await this.runPull(runtime, transport, generation, sessionIdentity);
309
315
  if (!pulled || !this.isCurrent(runtime, transport, generation, sessionIdentity)) return;
310
316
 
311
- const snapshot = await this.assembleSnapshot(runtime, generation, sessionIdentity);
317
+ let snapshot: SyncSnapshot | null;
318
+ try {
319
+ snapshot = await this.assembleSnapshot(runtime, generation, sessionIdentity);
320
+ } catch (error) {
321
+ // Nothing is pushed: the pull's "synced" no longer holds for this device's changes.
322
+ logFailure("sync.controller", "Collect sync contributor data failed")(error);
323
+ if (!this.isCurrent(runtime, transport, generation, sessionIdentity)) return;
324
+ this.setStatus({ phase: "error", transportId: transport.id, error: SYNC_COLLECT_FAILED });
325
+ return;
326
+ }
312
327
  if (!snapshot || !this.isCurrent(runtime, transport, generation, sessionIdentity)) return;
313
328
  const signature = snapshotContentSignature(snapshot);
314
329
  if (!options.force && signature === this.lastSignature) return;
@@ -1,6 +1,9 @@
1
- import type { AppState } from "../core/state/app/state";
1
+ import type { Dispatch } from "react";
2
+ import type { AppAction, AppState } from "../core/state/app/state";
3
+ import { saveConfigImmediately } from "../state/config-save-scheduler";
2
4
  import type { AppConfig } from "../types/config";
3
5
  import type { OtherWindowTab } from "../types/desktop-window";
6
+ import { logFailure } from "../utils/log-failure";
4
7
 
5
8
  /**
6
9
  * Cloud sync runs in the desktop app's main window, whose state holds only
@@ -60,3 +63,31 @@ export function withoutOtherWindowTabs(config: AppConfig, others: readonly Other
60
63
  const layout = byActive >= 0 ? config.layout : shown.layout;
61
64
  return { ...config, layouts, activeLayoutIndex, layout };
62
65
  }
66
+
67
+ /**
68
+ * The dispatch a config sync applies through in the main window. A config that
69
+ * changes another window's tab is saved whole at once, and nothing else would
70
+ * write that change: a failed save is logged and `onSaveFailure` tells the
71
+ * person.
72
+ */
73
+ export function createSyncConfigDispatch({ dispatch, otherWindowTabs, currentConfig, onSaveFailure }: {
74
+ dispatch: Dispatch<AppAction>;
75
+ otherWindowTabs: () => readonly OtherWindowTab[];
76
+ currentConfig: () => AppConfig;
77
+ onSaveFailure: () => void;
78
+ }): Dispatch<AppAction> {
79
+ return (action) => {
80
+ if (action.type !== "SET_CONFIG") {
81
+ dispatch(action);
82
+ return;
83
+ }
84
+ const others = otherWindowTabs();
85
+ if (changesOtherWindowTabs(action.config, others)) {
86
+ saveConfigImmediately(action.config).catch((error: unknown) => {
87
+ logFailure("sync.other-window-tabs", "Saving tabs synced to other windows failed")(error);
88
+ onSaveFailure();
89
+ });
90
+ }
91
+ dispatch({ ...action, config: withoutOtherWindowTabs(action.config, others, currentConfig()) });
92
+ };
93
+ }