@gloom-sh/terminal 0.20.5 → 0.20.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) 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/hk-tenders.ts +59 -0
  6. package/src/api-client/index.ts +1 -0
  7. package/src/api-client/types/econ.ts +20 -2
  8. package/src/app.tsx +18 -13
  9. package/src/architecture/floating-promise-allowlist.json +313 -0
  10. package/src/cli/commands/market.ts +164 -40
  11. package/src/cli/commands/news-search.ts +22 -7
  12. package/src/cli/commands/overview.ts +12 -6
  13. package/src/cli/commands/ticker.ts +3 -1
  14. package/src/cli/early-command.ts +2 -0
  15. package/src/cli/errors.ts +10 -1
  16. package/src/cli/fx-forward.ts +76 -12
  17. package/src/cli/fx-pair.ts +1 -1
  18. package/src/cli/fx-quote-rate.ts +23 -0
  19. package/src/cli/help.ts +1 -0
  20. package/src/cli/index-roots.ts +5 -4
  21. package/src/cli/index.ts +40 -3
  22. package/src/cli/known-gaps.ts +11 -8
  23. package/src/cli/listing-arg.ts +6 -4
  24. package/src/cli/options.ts +52 -3
  25. package/src/cli/output-file.ts +5 -3
  26. package/src/cli/pane-functions/catalog.ts +15 -0
  27. package/src/cli/pane-functions/function-help.ts +4 -4
  28. package/src/cli/pane-functions/headless.ts +9 -4
  29. package/src/cli/pane-functions/index.ts +6 -4
  30. package/src/cli/pane-functions/resolver.ts +2 -2
  31. package/src/cli/result.ts +21 -2
  32. package/src/cli/spreadsheet-hint.ts +7 -3
  33. package/src/cli/treasury-yields.ts +5 -3
  34. package/src/components/chart/composite/legend.tsx +40 -2
  35. package/src/components/command-bar/workflow/tickers.ts +2 -2
  36. package/src/components/data-table/view.tsx +9 -2
  37. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  38. package/src/components/ui/data-table/opentui/model.ts +8 -6
  39. package/src/components/ui/data-table/types.ts +6 -1
  40. package/src/components/ui/table-layout.ts +38 -1
  41. package/src/docs/snapshot.json +3 -3
  42. package/src/market-data/market/change-basis.ts +9 -5
  43. package/src/market-data/market/dated-previous-close.ts +57 -6
  44. package/src/market-data/quotes/contributions.ts +2 -0
  45. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  46. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  47. package/src/plugins/builtin/backtest/headless.ts +1 -1
  48. package/src/plugins/builtin/cds/model.ts +0 -6
  49. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  50. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  51. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  52. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  53. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  54. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  55. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  56. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  57. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  58. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  59. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  60. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  61. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  62. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  63. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  64. package/src/plugins/builtin/econ/calendar-model.ts +41 -7
  65. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  66. package/src/plugins/builtin/econ/index.tsx +41 -8
  67. package/src/plugins/builtin/econ/types.ts +3 -0
  68. package/src/plugins/builtin/fixed-income/index.tsx +2 -0
  69. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  70. package/src/plugins/builtin/help/keybindings-editor.tsx +6 -2
  71. package/src/plugins/builtin/portfolio-list/cli/render.ts +20 -3
  72. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  73. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  74. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  75. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  76. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  77. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  78. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  79. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  80. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  81. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  82. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  83. package/src/plugins/builtin/ticker-detail/financials/model.ts +6 -2
  84. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +1 -1
  85. package/src/plugins/builtin/ticker-detail/headless.ts +6 -4
  86. package/src/plugins/builtin/treasury-auctions/cache.ts +36 -2
  87. package/src/plugins/builtin/treasury-auctions/headless.ts +42 -4
  88. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  89. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  90. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  91. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -1
  92. package/src/plugins/builtin/treasury-auctions/model.ts +16 -8
  93. package/src/plugins/builtin/treasury-auctions/pane.tsx +45 -21
  94. package/src/portfolio/collection-name.ts +22 -0
  95. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  96. package/src/renderers/dom/data-table/index.tsx +27 -9
  97. package/src/renderers/dom/data-table/row.tsx +2 -0
  98. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  99. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  100. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  101. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  102. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  103. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  104. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  105. package/src/sources/provider-router/cache.ts +3 -1
  106. package/src/sync/controller.ts +17 -2
  107. package/src/sync/other-window-tabs.ts +32 -1
  108. package/src/sync/react.ts +4 -4
  109. package/src/time-series/bar-spacing.ts +33 -0
  110. package/src/time-series/base-series.ts +21 -3
  111. package/src/time-series/chart-bounds.ts +31 -0
  112. package/src/time-series/field-catalog.ts +17 -0
  113. package/src/time-series/fundamentals.ts +143 -11
  114. package/src/time-series/ice-credit.ts +32 -6
  115. package/src/time-series/resolve.ts +9 -5
  116. package/src/time-series/session-bar.ts +78 -9
  117. package/src/time-series/studies/formula.ts +53 -10
  118. package/src/time-series/studies/pair.ts +18 -7
  119. package/src/time-series/studies/units.ts +49 -2
  120. package/src/time-series/types.ts +12 -0
  121. package/src/types/desktop-window.ts +2 -0
  122. package/src/types/financials.ts +6 -0
  123. package/src/types/headless.ts +8 -0
  124. package/src/utils/cli-output.ts +6 -3
  125. package/src/utils/ebitda.ts +128 -0
  126. package/src/utils/format.ts +1 -1
  127. package/src/utils/shell-word.ts +13 -0
@@ -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.
@@ -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
+ }
package/src/sync/react.ts CHANGED
@@ -54,14 +54,14 @@ export function useCloudSyncRuntime({
54
54
 
55
55
  useEffect(() => {
56
56
  if (!initialized) return;
57
- void cloudSyncController.requestSync({ reason: "startup" });
57
+ cloudSyncController.startSync({ reason: "startup" });
58
58
  }, [initialized, pluginRegistry]);
59
59
 
60
60
  useEffect(() => {
61
61
  if (!initialized || !appActive) return;
62
- void cloudSyncController.requestSync({ reason: "foreground" });
62
+ cloudSyncController.startSync({ reason: "foreground" });
63
63
  const timer = setInterval(() => {
64
- void cloudSyncController.requestSync({ reason: "poll" });
64
+ cloudSyncController.startSync({ reason: "poll" });
65
65
  }, CLOUD_SYNC_POLL_MS);
66
66
  return () => clearInterval(timer);
67
67
  }, [appActive, initialized]);
@@ -70,7 +70,7 @@ export function useCloudSyncRuntime({
70
70
  if (!initialized) return;
71
71
  // Email verification makes the Cloud transport available. Force the first
72
72
  // sync so a workspace completed before verification is uploaded promptly.
73
- void cloudSyncController.requestSync({ reason: "session-verified", force: true });
73
+ cloudSyncController.startSync({ reason: "session-verified", force: true });
74
74
  }, (accountId) => cloudSyncController.resetAccount(accountId),
75
75
  () => cloudSyncController.retireSession()), [initialized]);
76
76
 
@@ -17,3 +17,36 @@ export function barSizeFromGap(gapMs: number): "1d" | "1wk" | "1mo" {
17
17
  const days = gapMs / DAY_MS;
18
18
  return days >= 25 ? "1mo" : days >= 6 ? "1wk" : "1d";
19
19
  }
20
+
21
+ const BAR_SIZE_ORDER = { "1d": 0, "1wk": 1, "1mo": 2 } as const;
22
+
23
+ /** Whether bars are each the start of a week, all on one weekday, or of a month, in its first week. */
24
+ function startPeriods(times: readonly number[], size: "1wk" | "1mo"): boolean {
25
+ const dates = times.filter(Number.isFinite).map((time) => new Date(time));
26
+ return size === "1wk" ? new Set(dates.map((date) => date.getUTCDay())).size === 1 : dates.every((date) => date.getUTCDate() <= 7);
27
+ }
28
+
29
+ /** Fewer bars than this cannot say they are coarser than asked: three Mondays of a thin listing are no weekly bars. */
30
+ const MIN_COARSER_BARS = 4;
31
+
32
+ type DailyOrLonger = "1d" | "1wk" | "1mo";
33
+
34
+ /**
35
+ * The size of bars asked for as `requested`: the request, not the spacing,
36
+ * unless the source stated the size it served (`stated`). A thinly traded
37
+ * listing's daily bars sit a week or two apart (B95 on SGX traded on 13 Oct,
38
+ * 22 Oct and 6 Nov), which the spacing reads as weekly. Bars the source
39
+ * served finer than asked show it in their spacing; coarser ones only when
40
+ * there are at least four and each starts its period, as weekly and monthly
41
+ * bars do.
42
+ */
43
+ export function requestedBarSize(times: readonly number[], requested: DailyOrLonger, stated?: string | null): DailyOrLonger {
44
+ if (stated === "1d" || stated === "1wk" || stated === "1mo") return stated;
45
+ const gap = medianBarGap(times);
46
+ if (gap == null) return requested;
47
+ const read = barSizeFromGap(gap);
48
+ if (BAR_SIZE_ORDER[read] < BAR_SIZE_ORDER[requested]) return read;
49
+ const bars = new Set(times.filter(Number.isFinite)).size;
50
+ return BAR_SIZE_ORDER[read] > BAR_SIZE_ORDER[requested] && bars >= MIN_COARSER_BARS && startPeriods(times, read as "1wk" | "1mo")
51
+ ? read : requested;
52
+ }
@@ -7,9 +7,12 @@ import { CHART_RESOLUTION_STEP_MS, type ManualChartResolution } from "./resoluti
7
7
  import type { Quote, QuoteMetadata, TickerFinancials } from "../types/financials";
8
8
  import type { FredSeriesLoadResult } from "../sources/gloomberb-cloud/fred-series";
9
9
  import { extractFredSeries } from "./economic";
10
+ import { isIceSpreadSeries } from "./ice-credit";
11
+ import { BASIS_POINT_UNIT, BP_PER_PERCENT } from "./studies/units";
10
12
  import { getTimeSeriesField, isMarketFieldId } from "./field-catalog";
11
13
  import {
12
14
  unreportedStatementPeriod,
15
+ valuationNotMeaningful,
13
16
  dailyValuationFallbackPeriod,
14
17
  valuationCurrencyWarning,
15
18
  valuationPriceIssues,
@@ -122,6 +125,7 @@ export function baseSecuritySeries(
122
125
  const points = extractSecuritySeries(financials, spec.source);
123
126
  const valuationFallback = dailyValuationFallbackPeriod(financials, spec.source);
124
127
  const unreportedPeriod = points.length === 0 ? unreportedStatementPeriod(financials, spec.source) : null;
128
+ const notMeaningful = valuationNotMeaningful(financials, spec.source);
125
129
  const symbol = instrumentLabel(spec.source);
126
130
  const statementCurrency = field.id.startsWith("fundamental.") && field.unit.startsWith("currency")
127
131
  ? reportingCurrencySeries(points, financials.financialCurrency) : null;
@@ -220,11 +224,13 @@ export function baseSecuritySeries(
220
224
  ...(volumeBasis ? { volumeBasis } : {}),
221
225
  ...(priceIssues.length ? { valuationPriceIssues: priceIssues } : {}),
222
226
  warning: [valuationFallback ? "Release dates unavailable; showing reported periods." : undefined,
227
+ notMeaningful ? `N/M: ${notMeaningful.reason} (period to ${notMeaningful.asOf}).` : undefined,
223
228
  field.id === "market.volume" && !volumeUnit && !volumeBasis && points.some((point) => Number.isFinite(point.value) && point.value !== 0)
224
229
  ? "Volume unit unknown." : statementCurrency?.warning ?? valuationCurrencyWarning(financials, spec.source)].filter(Boolean).join(" ") || undefined,
225
230
  nativeFrequency: marketField ? marketSeriesFrequency(spec.source, marketResolution)
226
231
  : valuationFallback ?? (spec.source.period && spec.source.period !== "auto" ? spec.source.period : field.nativeFrequency),
227
232
  ...(unreportedPeriod ? { unreportedPeriod } : {}),
233
+ ...(notMeaningful ? { notMeaningful } : {}),
228
234
  ...(marketField ? { historyResolution: marketResolution } : {}),
229
235
  timestampMode: spec.source.timestampMode,
230
236
  dataShape: field.dataShape,
@@ -278,12 +284,18 @@ export function baseEconomicSeries(
278
284
  const catalogUnit = fredCatalogUnit(units);
279
285
  // "Percent Change from Year Ago" and "Percent per Annum" are percent too.
280
286
  const isPercent = units.toLowerCase().includes("percent");
287
+ // An ICE option-adjusted spread reads in bp, as CRD and `fred` print it and CDX quotes, not FRED's percentage points.
288
+ const basisPoints = isPercent && /^percent$/i.test(units) && isIceSpreadSeries(spec.source.seriesId);
289
+ const points = extractFredSeries(data.observations, { providerId: "fred", timestampMode: "period-end" });
281
290
  return {
282
291
  id: spec.id,
283
292
  label: spec.label?.trim() || data.info?.title?.trim() || spec.source.seriesId,
293
+ expression: `FRED:${spec.source.seriesId}`,
284
294
  color: spec.color ?? SERIES_COLORS[index % SERIES_COLORS.length]!,
285
- unit: isPercent ? "%" : catalogUnit,
286
- unitGroup: isPercent ? "percent" : `economic:${catalogUnit.toLowerCase()}`,
295
+ ...(basisPoints ? BASIS_POINT_UNIT : {
296
+ unit: isPercent ? "%" : catalogUnit,
297
+ unitGroup: isPercent ? "percent" : `economic:${catalogUnit.toLowerCase()}`,
298
+ }),
287
299
  nativeFrequency: "auto",
288
300
  timestampMode: "period-end",
289
301
  dataShape: "scalar",
@@ -292,7 +304,10 @@ export function baseEconomicSeries(
292
304
  axis: spec.axis === "right" ? "right" : "left",
293
305
  panelId: spec.panelId,
294
306
  interpolation: spec.interpolation,
295
- points: extractFredSeries(data.observations, { providerId: "fred", timestampMode: "period-end" }),
307
+ // Rounded off the float's last digits: 0.93 × 100 is 93, not 93.00000000000001.
308
+ points: basisPoints
309
+ ? points.map((point) => typeof point.value === "number" ? { ...point, value: Number((point.value * BP_PER_PERCENT).toPrecision(12)) } : point)
310
+ : points,
296
311
  warning: "FRED vintage dates are unavailable; observations use period dates.",
297
312
  };
298
313
  }
@@ -312,6 +327,9 @@ export function baseCapabilitySeries(
312
327
  ...loaded,
313
328
  id: spec.id,
314
329
  label: spec.label?.trim() || loaded.label || (spec.source.kind === "capability" ? spec.source.seriesId : spec.id),
330
+ // A geographic series writes as GEO:, which only the chart composer spells; it keeps its label.
331
+ ...(spec.source.kind === "capability" && spec.source.capabilityId !== "geo-series"
332
+ ? { expression: `CAP:${spec.source.capabilityId}:${spec.source.seriesId}` } : {}),
315
333
  color: spec.color ?? loaded.color ?? SERIES_COLORS[index % SERIES_COLORS.length]!,
316
334
  style: spec.style,
317
335
  transform: spec.transform,