gloomberb 0.20.0 → 0.20.2

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 (481) hide show
  1. package/README.md +16 -26
  2. package/README.zh-CN.md +21 -65
  3. package/package.json +1 -1
  4. package/patches/electrobun-devkit@2.0.5.patch +268 -8
  5. package/src/account/auth-model.ts +20 -1
  6. package/src/account/upgrade-dialog.tsx +8 -4
  7. package/src/api-client/askg.ts +7 -1
  8. package/src/api-client/auth.ts +27 -0
  9. package/src/api-client/catalysts.ts +2 -0
  10. package/src/api-client/company-kpis.ts +2 -1
  11. package/src/api-client/cot.ts +14 -2
  12. package/src/api-client/crypto-markets.ts +20 -2
  13. package/src/api-client/data.ts +3 -2
  14. package/src/api-client/earnings.ts +46 -3
  15. package/src/api-client/fund-facts.ts +23 -1
  16. package/src/api-client/futures-curve.ts +17 -0
  17. package/src/api-client/index.ts +4 -1
  18. package/src/api-client/one-tap-reasons.ts +42 -0
  19. package/src/api-client/perps.ts +2 -1
  20. package/src/api-client/request.ts +3 -1
  21. package/src/api-client/research-activity.ts +16 -3
  22. package/src/api-client/types/filings-and-calls.ts +9 -0
  23. package/src/api-client/types/search.ts +3 -0
  24. package/src/app/keybindings/chord.ts +153 -9
  25. package/src/app/keybindings/index.ts +1 -1
  26. package/src/app/keybindings/labels.ts +49 -6
  27. package/src/app/runtime/desktop-deeplink.ts +73 -8
  28. package/src/app/runtime/plugin-seed.ts +119 -0
  29. package/src/app/runtime/startup.ts +45 -9
  30. package/src/app.tsx +8 -1
  31. package/src/architecture/core-builtin-allowlist.json +1 -2
  32. package/src/architecture/pane-tabs-allowlist.json +2 -1
  33. package/src/architecture/shortcut-labels-allowlist.json +11 -0
  34. package/src/architecture/ui-literals-allowlist.json +8 -8
  35. package/src/brokers/broker-portfolio-sync.ts +1 -1
  36. package/src/cli/bank-section.ts +26 -12
  37. package/src/cli/board-coins.ts +38 -5
  38. package/src/cli/commands/crypto-hints.ts +8 -1
  39. package/src/cli/commands/market.ts +294 -100
  40. package/src/cli/commands/overview.ts +13 -6
  41. package/src/cli/commands/ticker.ts +73 -21
  42. package/src/cli/company-name-hint.ts +19 -0
  43. package/src/cli/desktop-pane-shot-browser.ts +47 -31
  44. package/src/cli/desktop-pane-shot.ts +15 -0
  45. package/src/cli/entry.ts +15 -4
  46. package/src/cli/export-source.ts +7 -1
  47. package/src/cli/freshness.ts +0 -16
  48. package/src/cli/fx-pair.ts +64 -12
  49. package/src/cli/fx-quote-rate.ts +144 -0
  50. package/src/cli/glossary.ts +30 -0
  51. package/src/cli/helpers.ts +4 -2
  52. package/src/cli/history-back-adjust.ts +122 -0
  53. package/src/cli/history-rows.ts +114 -10
  54. package/src/cli/index.ts +4 -1
  55. package/src/cli/known-gaps.ts +45 -3
  56. package/src/cli/listing-arg.ts +48 -4
  57. package/src/cli/name-entries.ts +25 -5
  58. package/src/cli/not-a-ticker.ts +26 -1
  59. package/src/cli/pane-functions/catalog.ts +12 -2
  60. package/src/cli/pane-functions/dom.ts +4 -2
  61. package/src/cli/pane-functions/freshness.ts +45 -29
  62. package/src/cli/pane-functions/headless.ts +8 -5
  63. package/src/cli/pane-functions/index.ts +3 -0
  64. package/src/cli/pane-functions/market-session.ts +14 -5
  65. package/src/cli/pane-functions/resolver.ts +4 -1
  66. package/src/cli/pane-functions/screenshot-assessment.ts +15 -3
  67. package/src/cli/pane-functions/screenshot-payload.ts +130 -66
  68. package/src/cli/pane-functions/screenshot-render.ts +14 -2
  69. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  70. package/src/cli/restore-plugins.ts +164 -51
  71. package/src/cli/symbol-rows.ts +22 -2
  72. package/src/cli/ticker-resolution.ts +74 -17
  73. package/src/components/chart/composite/axis-overlays.tsx +13 -3
  74. package/src/components/chart/composite/composite-chart.tsx +8 -1
  75. package/src/components/chart/composite/format.ts +16 -1
  76. package/src/components/chart/composite/legend.tsx +4 -3
  77. package/src/components/chart/composite/panel-labels.ts +2 -1
  78. package/src/components/chart/composite/panel-surface.tsx +33 -4
  79. package/src/components/chart/composite/time-scale.ts +1 -1
  80. package/src/components/chart/composite/toolbar.tsx +8 -4
  81. package/src/components/chart/composite/types.ts +17 -1
  82. package/src/components/chart/composite/use-composite-chart-keyboard.ts +15 -5
  83. package/src/components/chart/composite/use-composite-viewport.ts +31 -8
  84. package/src/components/chart/static/scatter-chart-surface.tsx +25 -9
  85. package/src/components/chart-table/axis.ts +11 -0
  86. package/src/components/chart-table/header.tsx +10 -1
  87. package/src/components/chart-table/layout.ts +14 -5
  88. package/src/components/command-bar/assist/inventory.ts +3 -2
  89. package/src/components/command-bar/commands/collection-list.ts +3 -2
  90. package/src/components/command-bar/panel/index.tsx +13 -0
  91. package/src/components/command-bar/panel/layout.ts +15 -1
  92. package/src/components/command-bar/panel/prompt-width.ts +34 -0
  93. package/src/components/command-bar/panel/runtime.ts +1 -0
  94. package/src/components/command-bar/panel/state.ts +4 -0
  95. package/src/components/command-bar/panel/types.ts +2 -0
  96. package/src/components/command-bar/routes/root/search-providers.ts +3 -2
  97. package/src/components/command-bar/routes/root/search-report.ts +2 -2
  98. package/src/components/command-bar/workflow/ticker-listing-picker.ts +1 -0
  99. package/src/components/company-logo.tsx +2 -2
  100. package/src/components/data-table/view.tsx +11 -2
  101. package/src/components/feed-data-table/stack-view.tsx +20 -6
  102. package/src/components/feedback-dialog.tsx +3 -1
  103. package/src/components/form-modal/field-row.tsx +1 -1
  104. package/src/components/form-modal/routes.ts +1 -0
  105. package/src/components/index.ts +1 -1
  106. package/src/components/layout/header.tsx +12 -3
  107. package/src/components/layout/market-summary.ts +2 -1
  108. package/src/components/layout/pane/footer/index.tsx +9 -5
  109. package/src/components/layout/pane/footer/model.ts +26 -10
  110. package/src/components/layout/pane/footer/registration.tsx +60 -1
  111. package/src/components/layout/pane/header-tabs.tsx +17 -3
  112. package/src/components/layout/pane/header.tsx +5 -2
  113. package/src/components/layout/pane/pane-tabs.tsx +57 -3
  114. package/src/components/layout/shell/active-drag.ts +38 -30
  115. package/src/components/layout/shell/drag/index.ts +51 -21
  116. package/src/components/layout/shell/menu.ts +3 -5
  117. package/src/components/layout/shell/pane/actions.ts +4 -1
  118. package/src/components/layout/shell/pane/ask.ts +5 -2
  119. package/src/components/layout/status-bar.tsx +59 -54
  120. package/src/components/markdown-text.tsx +35 -10
  121. package/src/components/onboarding/first-run-workspace.ts +25 -23
  122. package/src/components/onboarding/onboarding-keyboard.ts +6 -1
  123. package/src/components/onboarding/onboarding-wizard.tsx +12 -2
  124. package/src/components/onboarding/portfolio-step/positions-panel.tsx +3 -3
  125. package/src/components/onboarding/use-onboarding-broker-form.ts +2 -1
  126. package/src/components/onboarding/use-onboarding-progress.ts +11 -4
  127. package/src/components/onboarding/use-onboarding-upgrade.ts +3 -2
  128. package/src/components/onboarding/wizard-positions.ts +8 -1
  129. package/src/components/pane-notice-seen.ts +125 -0
  130. package/src/components/pane-settings-dialog/field-dialogs.tsx +2 -1
  131. package/src/components/pane-settings-dialog.tsx +7 -6
  132. package/src/components/sign-in-code-panel.tsx +3 -2
  133. package/src/components/speedometer-gauge/terminal.tsx +30 -9
  134. package/src/components/ticker/list-table-view.tsx +39 -3
  135. package/src/components/ui/confirm-dialog.tsx +2 -1
  136. package/src/components/ui/data-table/index.tsx +4 -2
  137. package/src/components/ui/data-table/opentui/index.tsx +15 -5
  138. package/src/components/ui/data-table/types.ts +8 -0
  139. package/src/components/ui/external-link.tsx +4 -1
  140. package/src/components/ui/field-grid.tsx +1 -1
  141. package/src/components/ui/index.ts +2 -0
  142. package/src/components/ui/inline-quick-add.tsx +5 -0
  143. package/src/components/ui/multi-select/dialog.tsx +10 -9
  144. package/src/components/ui/pane-link-chip.tsx +354 -0
  145. package/src/components/ui/query-bar.tsx +22 -13
  146. package/src/components/ui/ratio-bar.tsx +24 -1
  147. package/src/components/ui/select-button.tsx +2 -1
  148. package/src/components/ui/shortcut-hint.tsx +6 -3
  149. package/src/components/ui/table-layout.ts +81 -0
  150. package/src/components/ui/tabs.tsx +45 -6
  151. package/src/components/use-pane-notice-footer.tsx +12 -4
  152. package/src/core/app-service-ports.ts +1 -1
  153. package/src/data/plugin-state-store.ts +44 -8
  154. package/src/docs/snapshot.json +53 -32
  155. package/src/i18n/es.ts +28 -6
  156. package/src/i18n/ja.ts +28 -5
  157. package/src/i18n/ko.ts +28 -5
  158. package/src/i18n/zh-cn.ts +28 -5
  159. package/src/i18n/zh-tw.ts +28 -5
  160. package/src/layout/pane-manager/gridlock-inference.ts +2 -1
  161. package/src/layout/pane-manager/gridlock.ts +47 -2
  162. package/src/layout-marketplace/api.ts +1 -0
  163. package/src/layout-marketplace/gallery.tsx +4 -3
  164. package/src/layout-marketplace/linked.ts +6 -4
  165. package/src/layout-marketplace/model.ts +3 -2
  166. package/src/market-data/fund-facts.ts +7 -1
  167. package/src/market-data/futures-contract.ts +77 -31
  168. package/src/market-data/fx-closes.ts +5 -2
  169. package/src/market-data/hooks.tsx +23 -0
  170. package/src/market-data/market/change-basis.ts +92 -14
  171. package/src/market-data/market/format.ts +81 -13
  172. package/src/market-data/market/futures-week.ts +3 -1
  173. package/src/market-data/market/globex-day.ts +73 -0
  174. package/src/market-data/market/index-level.ts +10 -1
  175. package/src/market-data/quotes/intraday-bar.ts +1 -1
  176. package/src/market-data/quotes/session-split.ts +28 -0
  177. package/src/plugins/builtin/account-management/pane.tsx +1 -1
  178. package/src/plugins/builtin/analytics/account-returns.ts +1 -1
  179. package/src/plugins/builtin/analytics/index.tsx +10 -3
  180. package/src/plugins/builtin/analytics/pane-model.ts +1 -1
  181. package/src/plugins/builtin/analytics/risk-client.ts +4 -1
  182. package/src/plugins/builtin/analytics/risk-episodes.ts +422 -0
  183. package/src/plugins/builtin/analytics/risk-fx.ts +1 -1
  184. package/src/plugins/builtin/analytics/risk-headless.ts +28 -10
  185. package/src/plugins/builtin/analytics/risk-math.ts +1 -1
  186. package/src/plugins/builtin/analytics/risk-model.ts +115 -26
  187. package/src/plugins/builtin/analytics/risk-pane.tsx +201 -23
  188. package/src/plugins/builtin/analytics/sharpe-cadence.ts +1 -1
  189. package/src/plugins/builtin/backtest/format.ts +14 -0
  190. package/src/plugins/builtin/backtest/pane.tsx +3 -3
  191. package/src/plugins/builtin/backtest/report.ts +5 -3
  192. package/src/plugins/builtin/broker-manager/add-request.ts +10 -1
  193. package/src/plugins/builtin/broker-trading/pane.tsx +20 -2
  194. package/src/plugins/builtin/buildout/company/flow.tsx +5 -5
  195. package/src/plugins/builtin/buildout/company/model.ts +14 -2
  196. package/src/plugins/builtin/catalysts/detail.tsx +2 -2
  197. package/src/plugins/builtin/catalysts/model.ts +7 -2
  198. package/src/plugins/builtin/catalysts/pane.tsx +2 -2
  199. package/src/plugins/builtin/chart-composer/headless.ts +57 -17
  200. package/src/plugins/builtin/chart-composer/session-range.ts +82 -3
  201. package/src/plugins/builtin/chat/message/pane-chip.tsx +36 -208
  202. package/src/plugins/builtin/cloud/askg/answer-follow-ups.tsx +61 -0
  203. package/src/plugins/builtin/cloud/askg/answer-sources.tsx +102 -0
  204. package/src/plugins/builtin/cloud/askg/controller.ts +7 -1
  205. package/src/plugins/builtin/cloud/askg/host.ts +57 -0
  206. package/src/plugins/builtin/cloud/askg/model.ts +45 -5
  207. package/src/plugins/builtin/cloud/askg/pane.tsx +304 -25
  208. package/src/plugins/builtin/cloud/askg/protocol.ts +26 -1
  209. package/src/plugins/builtin/cloud/askg/sources.ts +466 -0
  210. package/src/plugins/builtin/cloud/one-tap/controller.ts +309 -0
  211. package/src/plugins/builtin/cloud/one-tap/google-identity.ts +142 -0
  212. package/src/plugins/builtin/cloud/one-tap/one-tap-prompt.tsx +101 -0
  213. package/src/plugins/builtin/cloud/plugin.tsx +7 -1
  214. package/src/plugins/builtin/company-kpis/client.ts +4 -3
  215. package/src/plugins/builtin/company-kpis/model.ts +34 -3
  216. package/src/plugins/builtin/correlation/compute.ts +8 -2
  217. package/src/plugins/builtin/correlation/headless.ts +10 -9
  218. package/src/plugins/builtin/correlation/history.ts +30 -0
  219. package/src/plugins/builtin/correlation/index.tsx +39 -167
  220. package/src/plugins/builtin/correlation/matrix/grid.tsx +285 -0
  221. package/src/plugins/builtin/correlation/matrix/model.ts +10 -10
  222. package/src/plugins/builtin/correlation/relationship/model.ts +3 -6
  223. package/src/plugins/builtin/correlation/relationship/pane.tsx +7 -9
  224. package/src/plugins/builtin/correlation/relationship/view-model.ts +14 -5
  225. package/src/plugins/builtin/cot/client.ts +8 -3
  226. package/src/plugins/builtin/cot/headless.ts +65 -12
  227. package/src/plugins/builtin/cot/pane.tsx +11 -5
  228. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  229. package/src/plugins/builtin/crypto-board/defi-view.tsx +12 -1
  230. package/src/plugins/builtin/crypto-board/defi.ts +44 -7
  231. package/src/plugins/builtin/crypto-board/headless.ts +83 -12
  232. package/src/plugins/builtin/crypto-board/model.ts +30 -6
  233. package/src/plugins/builtin/crypto-board/pane.tsx +13 -2
  234. package/src/plugins/builtin/earnings/client.ts +40 -6
  235. package/src/plugins/builtin/earnings/fiscal-quarter.ts +54 -0
  236. package/src/plugins/builtin/earnings/headless.ts +47 -11
  237. package/src/plugins/builtin/earnings/history-model.ts +136 -24
  238. package/src/plugins/builtin/earnings/history-table.ts +42 -10
  239. package/src/plugins/builtin/earnings/history.tsx +23 -8
  240. package/src/plugins/builtin/earnings-ripple/client.ts +5 -2
  241. package/src/plugins/builtin/earnings-ripple/headless.ts +8 -3
  242. package/src/plugins/builtin/earnings-ripple/model.ts +21 -0
  243. package/src/plugins/builtin/earnings-ripple/pane.tsx +2 -3
  244. package/src/plugins/builtin/econ/index.tsx +5 -4
  245. package/src/plugins/builtin/econ-statistics/stats.ts +13 -5
  246. package/src/plugins/builtin/equity-screener/headless.ts +2 -1
  247. package/src/plugins/builtin/filing-events/feed.ts +56 -18
  248. package/src/plugins/builtin/filing-events/pane.tsx +8 -2
  249. package/src/plugins/builtin/futures/index.tsx +32 -10
  250. package/src/plugins/builtin/futures/model.ts +93 -6
  251. package/src/plugins/builtin/futures/returns.ts +29 -7
  252. package/src/plugins/builtin/futures/table.tsx +59 -17
  253. package/src/plugins/builtin/futures/use-front-returns.ts +32 -6
  254. package/src/plugins/builtin/futures-curve/client.ts +12 -2
  255. package/src/plugins/builtin/futures-curve/headless.ts +58 -17
  256. package/src/plugins/builtin/futures-curve/model.ts +111 -15
  257. package/src/plugins/builtin/futures-curve/pane.tsx +11 -6
  258. package/src/plugins/builtin/fx-matrix/amount.ts +132 -0
  259. package/src/plugins/builtin/fx-matrix/headless.ts +53 -13
  260. package/src/plugins/builtin/fx-matrix/index.tsx +205 -42
  261. package/src/plugins/builtin/fx-matrix/pairs.ts +10 -8
  262. package/src/plugins/builtin/fx-matrix/settings.ts +22 -1
  263. package/src/plugins/builtin/help/index.tsx +68 -61
  264. package/src/plugins/builtin/holders/format.ts +7 -2
  265. package/src/plugins/builtin/holders/pane.tsx +11 -3
  266. package/src/plugins/builtin/holders/report-header.ts +5 -4
  267. package/src/plugins/builtin/holders/report-rows.ts +4 -1
  268. package/src/plugins/builtin/holders/treemap.tsx +5 -3
  269. package/src/plugins/builtin/insider/signals-model.ts +4 -5
  270. package/src/plugins/builtin/ipo-calendar/headless.ts +18 -7
  271. package/src/plugins/builtin/ipo-calendar/listing-ipo.ts +3 -1
  272. package/src/plugins/builtin/ipo-calendar/model.ts +28 -8
  273. package/src/plugins/builtin/ipo-calendar/pane.tsx +2 -1
  274. package/src/plugins/builtin/kelly-sizer/headless.ts +4 -0
  275. package/src/plugins/builtin/perps/headless.ts +81 -19
  276. package/src/plugins/builtin/perps/index.tsx +3 -1
  277. package/src/plugins/builtin/perps/model.ts +1 -1
  278. package/src/plugins/builtin/perps/pane.tsx +2 -0
  279. package/src/plugins/builtin/portfolio-list/cell-version.ts +1 -0
  280. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +20 -1
  281. package/src/plugins/builtin/portfolio-list/cli/import-positions.ts +260 -0
  282. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +154 -0
  283. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +64 -22
  284. package/src/plugins/builtin/portfolio-list/cli/render.ts +18 -7
  285. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -3
  286. package/src/plugins/builtin/portfolio-list/grid.tsx +56 -12
  287. package/src/plugins/builtin/portfolio-list/headless.ts +128 -0
  288. package/src/plugins/builtin/portfolio-list/pane/index.tsx +42 -4
  289. package/src/plugins/builtin/portfolio-list/pane/period-pnl.ts +124 -0
  290. package/src/plugins/builtin/portfolio-list/period-pnl.ts +179 -0
  291. package/src/plugins/builtin/portfolio-list/positions-import/dialog.tsx +445 -0
  292. package/src/plugins/builtin/portfolio-list/positions-import/index.tsx +255 -0
  293. package/src/plugins/builtin/portfolio-list/positions-import/lookup.ts +78 -0
  294. package/src/plugins/builtin/portfolio-list/positions-import/read-file.ts +32 -0
  295. package/src/plugins/builtin/portfolio-list/quick-add/index.tsx +186 -50
  296. package/src/plugins/builtin/portfolio-list/quick-add/resolution.ts +118 -4
  297. package/src/plugins/builtin/portfolio-list/settings.ts +25 -0
  298. package/src/plugins/builtin/portfolio-list/summary/index.tsx +16 -1
  299. package/src/plugins/builtin/portfolio-list/summary/totals.ts +7 -5
  300. package/src/plugins/builtin/portfolio-list/table.tsx +105 -6
  301. package/src/plugins/builtin/power/headless.ts +47 -9
  302. package/src/plugins/builtin/research/relative-valuation-model.ts +8 -3
  303. package/src/plugins/builtin/research-search/article.ts +12 -2
  304. package/src/plugins/builtin/research-search/data.ts +5 -2
  305. package/src/plugins/builtin/research-search/document-view.tsx +1 -1
  306. package/src/plugins/builtin/research-search/model.ts +47 -3
  307. package/src/plugins/builtin/research-search/pane.tsx +3 -2
  308. package/src/plugins/builtin/reverse-dcf/model.ts +7 -4
  309. package/src/plugins/builtin/risk-factors/headless.ts +3 -2
  310. package/src/plugins/builtin/risk-factors/index.tsx +2 -28
  311. package/src/plugins/builtin/risk-factors/lock-note.ts +58 -0
  312. package/src/plugins/builtin/risk-factors/pane.tsx +14 -5
  313. package/src/plugins/builtin/scanner/flow-model.ts +17 -13
  314. package/src/plugins/builtin/scanner/flow-pane.tsx +8 -9
  315. package/src/plugins/builtin/scanner/flow-session.ts +2 -9
  316. package/src/plugins/builtin/scanner/hilo-model.ts +4 -3
  317. package/src/plugins/builtin/sec/filing-display.tsx +0 -5
  318. package/src/plugins/builtin/sec/forms.ts +19 -0
  319. package/src/plugins/builtin/sec/fund-facts.ts +45 -11
  320. package/src/plugins/builtin/sec/headless.ts +37 -12
  321. package/src/plugins/builtin/sec/index.tsx +37 -8
  322. package/src/plugins/builtin/shared/earnings-calendar.ts +6 -3
  323. package/src/plugins/builtin/shared/earnings-report.ts +1 -1
  324. package/src/plugins/builtin/shared/fx-rate-freshness.ts +0 -35
  325. package/src/plugins/builtin/shared/pro-lock-note.ts +5 -1
  326. package/src/plugins/builtin/shared/use-quote-board.ts +42 -27
  327. package/src/plugins/builtin/supply-chain/graph-model.ts +7 -1
  328. package/src/plugins/builtin/supply-chain/headless.ts +20 -10
  329. package/src/plugins/builtin/supply-chain/model.ts +117 -20
  330. package/src/plugins/builtin/supply-chain/pane.tsx +22 -15
  331. package/src/plugins/builtin/supply-chain/row-evidence.tsx +1 -1
  332. package/src/plugins/builtin/ticker-detail/data-panes/returns-chart-model.ts +69 -0
  333. package/src/plugins/builtin/ticker-detail/data-panes/returns-chart.tsx +118 -0
  334. package/src/plugins/builtin/ticker-detail/data-panes/returns-model.ts +1 -1
  335. package/src/plugins/builtin/ticker-detail/data-panes/returns-pane.tsx +103 -40
  336. package/src/plugins/builtin/ticker-detail/headless-schema.ts +10 -1
  337. package/src/plugins/builtin/ticker-detail/headless.ts +8 -1
  338. package/src/plugins/builtin/ticker-detail/overview/components.tsx +2 -1
  339. package/src/plugins/builtin/ticker-detail/overview/model.ts +18 -8
  340. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +11 -8
  341. package/src/plugins/builtin/ticker-detail/pane.tsx +95 -20
  342. package/src/plugins/builtin/ticker-detail/research-groups.ts +89 -0
  343. package/src/plugins/builtin/ticker-detail/settings.ts +4 -3
  344. package/src/plugins/builtin/time-sales/headless.ts +23 -7
  345. package/src/plugins/builtin/time-sales/index.tsx +2 -2
  346. package/src/plugins/builtin/volatility/charts.tsx +2 -2
  347. package/src/plugins/extracted-plugins.ts +49 -24
  348. package/src/plugins/host-resolver.ts +3 -2
  349. package/src/plugins/installer.ts +220 -31
  350. package/src/plugins/running-installs.ts +34 -0
  351. package/src/plugins/seed-progress.ts +72 -0
  352. package/src/portfolio/column-values.ts +42 -8
  353. package/src/portfolio/futures-positions.ts +10 -2
  354. package/src/portfolio/mutations.ts +4 -3
  355. package/src/portfolio/period-pnl.ts +119 -0
  356. package/src/portfolio/positions-import/describe.ts +89 -0
  357. package/src/portfolio/positions-import/parse.ts +682 -0
  358. package/src/portfolio/positions-import/plan.ts +295 -0
  359. package/src/{plugins/builtin/analytics/metrics.ts → portfolio/return-metrics.ts} +24 -11
  360. package/src/public/__snapshots__/public-api.test.ts.snap +1 -0
  361. package/src/react/jsx-dev-fallback.ts +62 -0
  362. package/src/renderers/browser/cloud-transport.ts +1 -1
  363. package/src/renderers/browser/config-host.ts +3 -1
  364. package/src/renderers/browser/deeplink-bridge.ts +8 -1
  365. package/src/renderers/browser/http-proxy-transport.ts +9 -2
  366. package/src/renderers/browser/main.tsx +2 -1
  367. package/src/renderers/browser/research-entry.ts +12 -0
  368. package/src/renderers/cloudflare/http-proxy.ts +8 -2
  369. package/src/renderers/cloudflare/proxy-session.ts +1 -0
  370. package/src/renderers/cloudflare/worker.ts +12 -3
  371. package/src/renderers/dom/desktop/audio-player.tsx +2 -2
  372. package/src/renderers/dom/desktop/controls.tsx +1 -1
  373. package/src/renderers/dom/desktop/dialog-actions.tsx +10 -24
  374. package/src/renderers/dom/desktop/icons.tsx +4 -2
  375. package/src/renderers/dom/desktop/query-bar.tsx +23 -19
  376. package/src/renderers/dom/dom-host-providers.tsx +7 -2
  377. package/src/renderers/dom/host/box.tsx +2 -2
  378. package/src/renderers/dom/host/input.tsx +13 -0
  379. package/src/renderers/dom/key-event.ts +1 -0
  380. package/src/renderers/dom/styles.css +3 -0
  381. package/src/renderers/electrobun/bun/context-menu/click.ts +1 -0
  382. package/src/renderers/electrobun/bun/desktop/backend.ts +15 -0
  383. package/src/renderers/electrobun/bun/desktop/capability-bridge.ts +5 -4
  384. package/src/renderers/electrobun/bun/desktop/host-requests.ts +19 -11
  385. package/src/renderers/electrobun/bun/desktop/http-fetch.ts +1 -0
  386. package/src/renderers/electrobun/bun/desktop/http-stream.ts +1 -1
  387. package/src/renderers/electrobun/bun/desktop/initialization.ts +27 -15
  388. package/src/renderers/electrobun/bun/desktop/install-records.ts +4 -1
  389. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +5 -2
  390. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +3 -1
  391. package/src/renderers/electrobun/bun/desktop/screen-setup-file.ts +9 -4
  392. package/src/renderers/electrobun/bun/desktop/update.ts +27 -13
  393. package/src/renderers/electrobun/bun/desktop/windows-script.ts +6 -2
  394. package/src/renderers/electrobun/bun/index.ts +5 -0
  395. package/src/renderers/electrobun/bun/window/attention.ts +1 -0
  396. package/src/renderers/electrobun/bun/window/boot-frame.ts +1 -0
  397. package/src/renderers/electrobun/bun/window/context-menu-thread.ts +84 -0
  398. package/src/renderers/electrobun/bun/window/create.ts +1 -0
  399. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +13 -8
  400. package/src/renderers/electrobun/bun/window/native-call-thread.ts +224 -0
  401. package/src/renderers/electrobun/bun/window/native-min-size.ts +1 -1
  402. package/src/renderers/electrobun/bun/window/native-timing.ts +10 -0
  403. package/src/renderers/electrobun/bun/window/remembered-frame.ts +1 -0
  404. package/src/renderers/electrobun/bun/window/script-for-webview.ts +15 -0
  405. package/src/renderers/electrobun/bun/window/webview-script-thread.ts +82 -0
  406. package/src/renderers/electrobun/bun/window/windows-native.ts +3 -1
  407. package/src/renderers/electrobun/bun/window/windows-quit.ts +3 -1
  408. package/src/renderers/electrobun/shared/protocol.ts +13 -2
  409. package/src/renderers/electrobun/view/app-badge-host.ts +2 -1
  410. package/src/renderers/electrobun/view/backend-rpc.ts +7 -0
  411. package/src/renderers/electrobun/view/capability-subscription.ts +2 -1
  412. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +7 -10
  413. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +1 -1
  414. package/src/renderers/electrobun/view/cli-pane-shot-mutations.ts +36 -0
  415. package/src/renderers/electrobun/view/http-fetch.ts +2 -1
  416. package/src/renderers/electrobun/view/main.tsx +13 -7
  417. package/src/renderers/electrobun/view/remote/capability-invoker.ts +6 -3
  418. package/src/renderers/electrobun/view/remote/persistence.ts +63 -27
  419. package/src/renderers/electrobun/view/rpc-timeout.ts +1 -0
  420. package/src/renderers/electrobun/view/ui-host.tsx +3 -2
  421. package/src/renderers/electrobun/view/window-fullscreen.ts +3 -1
  422. package/src/renderers/opentui/browser-open.ts +2 -1
  423. package/src/renderers/opentui/dialog-host.tsx +1 -1
  424. package/src/renderers/opentui/interaction-performance.ts +3 -1
  425. package/src/renderers/opentui/start.tsx +5 -1
  426. package/src/renderers/opentui/terminal-media.ts +11 -6
  427. package/src/renderers/opentui/ui-host.tsx +5 -8
  428. package/src/shares/open.ts +22 -1
  429. package/src/shares/pane.ts +2 -1
  430. package/src/sources/gloomberb-cloud/normalizers.ts +3 -0
  431. package/src/sync/analytics-payload.ts +194 -0
  432. package/src/sync/baseline.ts +19 -9
  433. package/src/sync/broker-identity.ts +171 -0
  434. package/src/sync/broker-instances.ts +137 -0
  435. package/src/sync/collections-contributor.ts +173 -0
  436. package/src/sync/config-contributor.ts +100 -0
  437. package/src/sync/config-merge.ts +229 -0
  438. package/src/sync/controller.ts +139 -28
  439. package/src/sync/core-contributors.ts +8 -1583
  440. package/src/sync/history-memo.ts +32 -0
  441. package/src/sync/layout-merge.ts +259 -0
  442. package/src/sync/sanitize.ts +114 -0
  443. package/src/sync/ticker-merge.ts +208 -0
  444. package/src/sync/ticker-payload.ts +81 -0
  445. package/src/sync/types.ts +15 -1
  446. package/src/telemetry/attention-setting.ts +1 -1
  447. package/src/telemetry/stall-reports.ts +21 -4
  448. package/src/telemetry/usage-counts.ts +16 -0
  449. package/src/test-support/preload.ts +5 -0
  450. package/src/theme/color-utils.ts +10 -0
  451. package/src/theme/font-scale.ts +34 -3
  452. package/src/theme/series-colors.ts +44 -0
  453. package/src/theme/themes.ts +2 -1
  454. package/src/tickers/batched-lookups.ts +263 -6
  455. package/src/tickers/company-name-listing.ts +44 -2
  456. package/src/tickers/company-name.ts +7 -2
  457. package/src/tickers/search/upsert.ts +16 -1
  458. package/src/time-series/base-series.ts +18 -4
  459. package/src/time-series/studies/indicators.ts +3 -1
  460. package/src/time-series/studies/resolve.ts +1 -1
  461. package/src/time-series/types.ts +6 -0
  462. package/src/types/financials.ts +18 -0
  463. package/src/types/headless.ts +11 -0
  464. package/src/ui/host.tsx +26 -3
  465. package/src/ui/index.tsx +1 -0
  466. package/src/utils/concurrency.ts +6 -0
  467. package/src/utils/currency-pair.ts +56 -4
  468. package/src/utils/datetime-format.ts +11 -0
  469. package/src/utils/decimal-comma.ts +9 -6
  470. package/src/utils/exchanges.ts +32 -0
  471. package/src/utils/fundamentals.ts +41 -0
  472. package/src/utils/main-thread-stall.ts +21 -5
  473. package/src/utils/markdown.ts +4 -2
  474. package/src/utils/pasted-lines.ts +14 -0
  475. package/src/utils/perf-marks.ts +88 -9
  476. package/src/utils/price-window.ts +2 -1
  477. package/src/utils/reported-money.ts +9 -2
  478. package/src/utils/sec-filings.ts +17 -0
  479. package/src/utils/sec.ts +37 -25
  480. package/src/utils/shortcut-labels.ts +6 -30
  481. package/src/plugins/seed-notice.ts +0 -20
@@ -1,1587 +1,12 @@
1
- import { saveConfigImmediately, scheduleConfigSave } from "../state/config-save-scheduler";
2
- import { persistTickerCleanup } from "../state/ticker-cleanup";
3
- import { hasPendingTickerWrites } from "../data/ticker-writes";
4
- import { normalizeStoredBaseCurrency } from "../utils/base-currency";
5
- import { debugLog } from "../utils/debug-log";
6
- import { fnv1aHex, stableStringify } from "../utils/hash";
7
- import type { AppConfig, BrokerInstanceConfig, SavedLayout } from "../types/config";
8
- import type { PricePoint, TickerFinancials } from "../types/financials";
9
- import type { Portfolio, TickerMetadata, TickerPosition, TickerRecord, Watchlist } from "../types/ticker";
10
- import type { BrokerAccount } from "../types/trading";
11
- import { hydrateTickerMetadata } from "../tickers/metadata";
12
1
  import type { SyncContributor } from "./types";
13
- import { convertCurrency } from "../utils/format";
14
- import { fxRateCurrencies } from "../utils/currency-units";
15
- import { getSharedMarketDataCoordinator, resolveEntryValue } from "../market-data/coordinator";
16
- import {
17
- computeDatedBeta,
18
- resolveDatedReturns,
19
- computeWeightedPortfolioReturns,
20
- syntheticAccountUnsupportedReason,
21
- syntheticPositionUnsupportedReason,
22
- type DatedReturn,
23
- type ReturnHistoryResult,
24
- type WeightedReturnSeries,
25
- } from "../plugins/builtin/analytics/metrics";
26
- import {
27
- getSyncedProfileAnalytics,
28
- setSyncedProfileAnalytics,
29
- } from "./profile-analytics";
30
- import {
31
- addLegacyBuiltinDisabledPluginAliases,
32
- addLegacyBuiltinPluginOwnerAliases,
33
- decodeBuiltinDisabledPluginIds,
34
- encodeBuiltinDisabledPluginIds,
35
- normalizeBuiltinPluginStateMap,
36
- } from "../plugins/ownership";
37
- import { isFiniteNumber, isRecord, recordOrNull } from "../utils/guards";
38
- import { getBrokerInstance } from "../utils/broker-instances";
39
- import { withoutMissingWatchlists } from "../portfolio/mutations";
40
- import { mergeSuffixedListings, moveTargetWeights } from "../portfolio/suffixed-listings";
41
- import { positionContractMultiplier } from "../portfolio/position-metrics";
42
- import { reportTelemetryConfig } from "../telemetry/live-config";
43
- import {
44
- clearLeftoverBrokerHoldings,
45
- knownBrokerHoldings,
46
- type KnownBrokerHoldings,
47
- } from "../brokers/broker-portfolio-sync";
48
- import {
49
- isLocalOnlyInstance,
50
- isLocalOnlyPortfolio,
51
- localOnlyScope,
52
- publicConfig,
53
- publicMarketData,
54
- publicTickers,
55
- withLocalOnlyEntries,
56
- type LocalOnlyScope,
57
- } from "./local-only";
58
-
59
- /**
60
- * What a saved layout mirrors from the live session rather than from the
61
- * workspace the user arranged. None of it crosses the network: it is the view
62
- * this device is looking at right now, not a layout two devices should agree
63
- * on. Syncing it made every poll hand each client the other's open detail,
64
- * cursor and scroll position, and each apply pushed the view straight back.
65
- */
66
- const SESSION_SAVED_LAYOUT_KEYS = ["paneState", "focusedPaneId", "activePanel"] as const;
67
-
68
- /** Together these are the workspace: the tabs, the one showing, and its arrangement. */
69
- const LAYOUT_SYNC_KEYS = ["layout", "layouts", "activeLayoutIndex"] as const;
70
-
71
- const SENSITIVE_KEY_PATTERN = /(token|secret|password|credential|private|api[_-]?key|access[_-]?key|refresh[_-]?key|session|cookie|dataDir|path|directory|localPath)/i;
72
-
73
- const log = debugLog.createLogger("sync");
74
-
75
- function sanitizeUnknown(value: unknown): unknown {
76
- if (Array.isArray(value)) {
77
- return value.map(sanitizeUnknown).filter((entry) => entry !== undefined);
78
- }
79
- if (!isRecord(value)) return value;
80
-
81
- const output: Record<string, unknown> = {};
82
- for (const [key, child] of Object.entries(value)) {
83
- if (SENSITIVE_KEY_PATTERN.test(key)) continue;
84
- const sanitized = sanitizeUnknown(child);
85
- if (sanitized !== undefined) output[key] = sanitized;
86
- }
87
- return output;
88
- }
89
-
90
- /**
91
- * Puts back what `sanitizeUnknown` keeps off the wire. A pulled config never
92
- * carries a token, password, key or local path, so taking it as-is deleted
93
- * them on this device: any plugin setting changed elsewhere (an alert, a
94
- * price level) wiped every plugin's saved credentials, and the user had to
95
- * paste them again. Those values belong to this device, so they always win.
96
- */
97
- function withLocalSensitiveValues(
98
- pulled: Record<string, unknown>,
99
- local: Record<string, unknown>,
100
- ): Record<string, unknown> {
101
- const output: Record<string, unknown> = { ...pulled };
102
- for (const [key, localChild] of Object.entries(local)) {
103
- if (SENSITIVE_KEY_PATTERN.test(key)) {
104
- output[key] = localChild;
105
- } else if (isRecord(output[key]) && isRecord(localChild)) {
106
- output[key] = withLocalSensitiveValues(output[key] as Record<string, unknown>, localChild);
107
- }
108
- }
109
- return output;
110
- }
111
-
112
- function withLocalPluginSecrets(
113
- pulled: AppConfig["pluginConfig"],
114
- local: AppConfig["pluginConfig"],
115
- ): AppConfig["pluginConfig"] {
116
- const next = { ...pulled };
117
- for (const [pluginId, localState] of Object.entries(local)) {
118
- if (!isRecord(localState)) continue;
119
- // A plugin the other device has no settings for still keeps its secrets here.
120
- const merged = withLocalSensitiveValues(next[pluginId] ?? {}, localState);
121
- if (pluginId in next || Object.keys(merged).length > 0) next[pluginId] = merged;
122
- }
123
- return next;
124
- }
125
-
126
- function sanitizePortfolio(portfolio: Portfolio): Portfolio {
127
- return {
128
- id: portfolio.id,
129
- name: portfolio.name,
130
- description: portfolio.description,
131
- currency: portfolio.currency,
132
- ...(portfolio.fixedCurrency ? { fixedCurrency: true } : {}),
133
- brokerId: portfolio.brokerId,
134
- lastSyncedAt: portfolio.lastSyncedAt,
135
- // Cash and targets are the user's own entries: a pulled portfolio without
136
- // them would erase them on this device.
137
- ...(portfolio.cash ? { cash: { ...portfolio.cash } } : {}),
138
- ...(portfolio.targetWeights ? { targetWeights: { ...portfolio.targetWeights } } : {}),
139
- ...(portfolio.importedFrom ? {
140
- importedFrom: {
141
- ...portfolio.importedFrom,
142
- ...(portfolio.importedFrom.weights ? { weights: { ...portfolio.importedFrom.weights } } : {}),
143
- },
144
- } : {}),
145
- };
146
- }
147
-
148
- function brokerAccountIdFromPortfolioId(portfolioId: string): string | undefined {
149
- const [kind, instanceId, ...accountParts] = portfolioId.split(":");
150
- if (kind !== "broker" || !instanceId) return undefined;
151
- const accountId = accountParts.join(":").trim();
152
- return accountId && accountId !== "default" ? accountId : undefined;
153
- }
154
-
155
- function brokerPortfolioKey(brokerId: string | undefined, accountId: string | undefined): string | undefined {
156
- if (!brokerId || !accountId) return undefined;
157
- return [brokerId, accountId].join("\u0000");
158
- }
159
-
160
- function portfolioSyncTimestamp(portfolio: Portfolio): number {
161
- return typeof portfolio.lastSyncedAt === "number" && Number.isFinite(portfolio.lastSyncedAt)
162
- ? portfolio.lastSyncedAt
163
- : 0;
164
- }
165
-
166
- function latestBrokerSyncByType(portfolios: Portfolio[], linkedOnly: boolean): Map<string, number> {
167
- const latest = new Map<string, number>();
168
- for (const portfolio of portfolios) {
169
- if (!portfolio.brokerId || (linkedOnly && !portfolio.brokerInstanceId)) continue;
170
- const timestamp = portfolioSyncTimestamp(portfolio);
171
- latest.set(portfolio.brokerId, Math.max(latest.get(portfolio.brokerId) ?? 0, timestamp));
172
- }
173
- return latest;
174
- }
175
-
176
- /**
177
- * Broker identity is deliberately excluded from cloud payloads, but it is
178
- * still local state that must survive applying a sanitized portfolio back to
179
- * this device. Match by the stable portfolio ID first, then by the account
180
- * suffix in that stable ID. A newer local broker snapshot also wins over old
181
- * unlinked records left in a cloud snapshot from before a reset.
182
- */
183
- function mergeLocalBrokerPortfolioIdentity(
184
- localPortfolios: Portfolio[],
185
- syncedPortfolios: Portfolio[],
186
- ): Portfolio[] {
187
- const localById = new Map(localPortfolios.map((portfolio) => [portfolio.id, portfolio] as const));
188
- const localByBrokerAccount = new Map<string, Portfolio[]>();
189
- for (const portfolio of localPortfolios) {
190
- if (!portfolio.brokerInstanceId) continue;
191
- const key = brokerPortfolioKey(portfolio.brokerId, portfolio.brokerAccountId);
192
- if (!key) continue;
193
- const entries = localByBrokerAccount.get(key) ?? [];
194
- entries.push(portfolio);
195
- localByBrokerAccount.set(key, entries);
196
- }
197
-
198
- const exactIncomingIds = new Set(
199
- syncedPortfolios
200
- .map((portfolio) => portfolio.id)
201
- .filter((portfolioId) => localById.has(portfolioId)),
202
- );
203
- const localLatestByBroker = latestBrokerSyncByType(localPortfolios, true);
204
- const syncedLatestByBroker = latestBrokerSyncByType(syncedPortfolios, false);
205
- const merged: Portfolio[] = [];
206
- const seenIds = new Set<string>();
207
-
208
- for (const portfolio of syncedPortfolios) {
209
- const localByStableId = localById.get(portfolio.id);
210
- const accountId = brokerAccountIdFromPortfolioId(portfolio.id);
211
- const accountCandidates = localByBrokerAccount.get(brokerPortfolioKey(portfolio.brokerId, accountId) ?? "");
212
- const local = localByStableId?.brokerInstanceId && localByStableId.brokerId === portfolio.brokerId
213
- ? localByStableId
214
- : accountCandidates?.length === 1
215
- ? accountCandidates[0]
216
- : undefined;
217
-
218
- if (local) {
219
- // Prefer an exact stable-ID entry when an older duplicate appears first
220
- // in the remote array.
221
- if (portfolio.id !== local.id && exactIncomingIds.has(local.id)) continue;
222
- if (seenIds.has(local.id)) continue;
223
-
224
- const localIsNewer = portfolioSyncTimestamp(local) > portfolioSyncTimestamp(portfolio);
225
- merged.push(localIsNewer
226
- ? local
227
- : {
228
- ...portfolio,
229
- id: local.id,
230
- brokerInstanceId: local.brokerInstanceId,
231
- brokerAccountId: local.brokerAccountId,
232
- });
233
- seenIds.add(local.id);
234
- continue;
235
- }
236
-
237
- const localLatest = portfolio.brokerId ? localLatestByBroker.get(portfolio.brokerId) : undefined;
238
- if (localLatest !== undefined && localLatest > portfolioSyncTimestamp(portfolio)) continue;
239
- merged.push(portfolio);
240
- seenIds.add(portfolio.id);
241
- }
242
-
243
- // If the newer local broker snapshot is absent from the cloud array
244
- // altogether, keep it instead of treating the older array as authoritative.
245
- for (const portfolio of localPortfolios) {
246
- if (!portfolio.brokerInstanceId || seenIds.has(portfolio.id)) continue;
247
- const localLatest = portfolio.brokerId ? localLatestByBroker.get(portfolio.brokerId) : undefined;
248
- const syncedLatest = portfolio.brokerId ? syncedLatestByBroker.get(portfolio.brokerId) ?? 0 : 0;
249
- if (localLatest !== undefined && localLatest > syncedLatest) {
250
- merged.push(portfolio);
251
- seenIds.add(portfolio.id);
252
- }
253
- }
254
-
255
- return merged;
256
- }
257
-
258
- function sanitizeWatchlist(watchlist: Watchlist): Watchlist {
259
- return {
260
- id: watchlist.id,
261
- name: watchlist.name,
262
- description: watchlist.description,
263
- };
264
- }
265
-
266
- function sanitizeBrokerInstance(instance: BrokerInstanceConfig): Omit<BrokerInstanceConfig, "config"> {
267
- return {
268
- id: instance.id,
269
- brokerType: instance.brokerType,
270
- label: instance.label,
271
- connectionMode: instance.connectionMode,
272
- enabled: instance.enabled,
273
- lastSyncedAt: instance.lastSyncedAt,
274
- };
275
- }
276
-
277
- function sanitizePosition(position: TickerPosition): TickerPosition {
278
- return {
279
- portfolio: position.portfolio,
280
- shares: position.shares,
281
- avgCost: position.avgCost,
282
- currency: position.currency,
283
- dateAcquired: position.dateAcquired,
284
- ...(position.costFxRate != null && position.costFxCurrency ? { costFxRate: position.costFxRate, costFxCurrency: position.costFxCurrency } : {}),
285
- broker: position.broker,
286
- side: position.side,
287
- marketValue: position.marketValue,
288
- unrealizedPnl: position.unrealizedPnl,
289
- multiplier: position.multiplier,
290
- markPrice: position.markPrice,
291
- };
292
- }
293
-
294
- function brokerPositionKey(position: Pick<TickerPosition, "portfolio" | "broker" | "side">): string {
295
- return [position.portfolio, position.broker, position.side ?? ""].join("\u0000");
296
- }
297
-
298
- /** Keep broker position identity local while applying public cloud fields. */
299
- function mergeLocalBrokerPositionIdentity(
300
- localPositions: TickerPosition[],
301
- syncedPositions: TickerPosition[],
302
- ): TickerPosition[] {
303
- const localByKey = new Map<string, TickerPosition[]>();
304
- for (const position of localPositions) {
305
- if (!position.brokerInstanceId) continue;
306
- const key = brokerPositionKey(position);
307
- const entries = localByKey.get(key) ?? [];
308
- entries.push(position);
309
- localByKey.set(key, entries);
310
- }
311
-
312
- return syncedPositions.map((position) => {
313
- const entries = localByKey.get(brokerPositionKey(position));
314
- const local = entries?.shift();
315
- if (!local) return position;
316
-
317
- return {
318
- ...position,
319
- brokerInstanceId: local.brokerInstanceId,
320
- brokerAccountId: local.brokerAccountId,
321
- brokerContractId: local.brokerContractId,
322
- };
323
- });
324
- }
325
-
326
- function pricePointTime(point: { date: Date | string | number }): number {
327
- const value = point.date;
328
- if (value instanceof Date) return value.getTime();
329
- return new Date(value).getTime();
330
- }
331
-
332
- /** The bars a week's move can start from, oldest first. */
333
- const datedCloses = historyMemo((history) => history
334
- .filter((point) => Number.isFinite(point.close) && point.close > 0 && Number.isFinite(pricePointTime(point)))
335
- .sort((left, right) => pricePointTime(left) - pricePointTime(right)));
336
-
337
- function weeklyQuoteMove(financials: TickerFinancials | null | undefined) {
338
- const quote = financials?.quote;
339
- if (!quote || !Number.isFinite(quote.price) || quote.price <= 0) return undefined;
340
- const history = datedCloses(financials?.priceHistory);
341
- if (history.length === 0) return undefined;
342
- const latestTime = Number.isFinite(quote.lastUpdated)
343
- ? quote.lastUpdated
344
- : pricePointTime(history[history.length - 1]!);
345
- const cutoff = latestTime - 7 * 24 * 60 * 60 * 1000;
346
- const reference = history.find((point) => pricePointTime(point) >= cutoff) ?? history[Math.max(0, history.length - 7)];
347
- if (!reference || !Number.isFinite(reference.close) || reference.close <= 0) return undefined;
348
- const weekChange = quote.price - reference.close;
349
- return {
350
- weekReferencePrice: reference.close,
351
- weekChange,
352
- weekChangePercent: (weekChange / reference.close) * 100,
353
- };
354
- }
355
-
356
- function sanitizeQuote(financials: TickerFinancials | null | undefined) {
357
- const quote = financials?.quote;
358
- if (!quote) return undefined;
359
- const week = weeklyQuoteMove(financials);
360
- return {
361
- price: Number.isFinite(quote.price) ? quote.price : undefined,
362
- currency: quote.currency,
363
- changePercent: Number.isFinite(quote.changePercent) ? quote.changePercent : undefined,
364
- previousClose: Number.isFinite(quote.previousClose) ? quote.previousClose : undefined,
365
- weekReferencePrice: week?.weekReferencePrice,
366
- weekChange: week?.weekChange,
367
- weekChangePercent: week?.weekChangePercent,
368
- lastUpdated: quote.lastUpdated,
369
- };
370
- }
371
-
372
- function sanitizeTickerMetadata(metadata: TickerMetadata, financials?: TickerFinancials | null): Omit<TickerMetadata, "broker_contracts"> & { quote?: ReturnType<typeof sanitizeQuote> } {
373
- return {
374
- ticker: metadata.ticker,
375
- exchange: metadata.exchange,
376
- currency: metadata.currency,
377
- name: metadata.name,
378
- sector: metadata.sector,
379
- industry: metadata.industry,
380
- assetCategory: metadata.assetCategory,
381
- isin: metadata.isin,
382
- cusip: metadata.cusip,
383
- portfolios: [...metadata.portfolios],
384
- watchlists: [...metadata.watchlists],
385
- positions: metadata.positions.map(sanitizePosition),
386
- custom: (sanitizeUnknown(metadata.custom) as Record<string, unknown>) ?? {},
387
- tags: [...metadata.tags],
388
- // What a listing's row took from a suffixed key's row, so a device that merges it later never counts a lot twice.
389
- ...metadata.mergedLots ? { mergedLots: metadata.mergedLots } : {},
390
- quote: sanitizeQuote(financials),
391
- };
392
- }
393
-
394
- function collectLayoutPayload(config: Pick<AppConfig, typeof LAYOUT_SYNC_KEYS[number]>) {
395
- return sanitizeUnknown({
396
- layout: config.layout,
397
- layouts: config.layouts.map(withoutSessionLayoutState),
398
- activeLayoutIndex: config.activeLayoutIndex,
399
- }) as Record<string, unknown>;
400
- }
401
-
402
- function collectCoreConfigPayload(config: AppConfig) {
403
- return sanitizeUnknown({
404
- configVersion: config.configVersion,
405
- baseCurrency: config.baseCurrency,
406
- refreshIntervalMinutes: config.refreshIntervalMinutes,
407
- portfolios: config.portfolios.map(sanitizePortfolio),
408
- watchlists: config.watchlists.map(sanitizeWatchlist),
409
- ...collectLayoutPayload(config),
410
- brokerInstances: config.brokerInstances.map(sanitizeBrokerInstance),
411
- // This build merges profiles one by one before it pushes, so a profile
412
- // missing from its list was removed, not one it never pulled.
413
- brokerInstancesMergedById: true,
414
- disabledPlugins: addLegacyBuiltinDisabledPluginAliases(encodeBuiltinDisabledPluginIds(config.disabledPlugins)),
415
- disabledSources: config.disabledSources,
416
- pluginConfig: addLegacyBuiltinPluginOwnerAliases(config.pluginConfig),
417
- theme: config.theme,
418
- chartPreferences: config.chartPreferences,
419
- valueFlashingEnabled: config.valueFlashingEnabled,
420
- recentTickers: config.recentTickers,
421
- recentCommands: config.recentCommands,
422
- // Completion is monotonic in synced state. A device only advertises the
423
- // completed state, while resumable progress and incomplete state stay local.
424
- onboardingComplete: config.onboardingComplete === true ? true : undefined,
425
- // Only whether Attention Counts is off: see mergedAttentionTelemetry.
426
- attentionOff: config.telemetry?.attention === false,
427
- });
428
- }
429
-
430
- /**
431
- * Attention Counts off belongs to the signed-in account, not to one device:
432
- * an off made on another device turns it off here, and an explicit on made
433
- * there afterwards turns it back on. The default never overrides either. An
434
- * edit made here since the last sync wins, like any setting. No synced copy,
435
- * or one from before `attentionOff` existed, reads as not off: a device's
436
- * first sync takes an off already on the account, and keeps its own off
437
- * instead of taking an on.
438
- */
439
- function mergedAttentionTelemetry(
440
- config: AppConfig,
441
- baselineConfig: AppConfig,
442
- payload: Record<string, unknown>,
443
- lastSynced: Record<string, unknown> | null,
444
- ): AppConfig["telemetry"] {
445
- // A copy pushed by an older build says nothing either way.
446
- if (typeof payload.attentionOff !== "boolean") return config.telemetry;
447
- const localOff = config.telemetry?.attention === false;
448
- if (payload.attentionOff === localOff) return config.telemetry;
449
- const editedHere = localOff !== (baselineConfig.telemetry?.attention === false)
450
- || localOff !== (lastSynced?.attentionOff === true);
451
- if (editedHere) return config.telemetry;
452
- return { ...config.telemetry, attention: !payload.attentionOff };
453
- }
454
-
455
- function positionValueBase(
456
- ticker: TickerRecord,
457
- position: TickerPosition,
458
- financials: TickerFinancials | null | undefined,
459
- baseCurrency: string,
460
- exchangeRates: Map<string, number>,
461
- ): number | null {
462
- const quoteCurrency = financials?.quote?.currency || position.currency || baseCurrency;
463
- const positionCurrency = position.currency || quoteCurrency;
464
- if (typeof position.marketValue === "number" && Number.isFinite(position.marketValue)) {
465
- return convertCurrency(Math.abs(position.marketValue), positionCurrency, baseCurrency, exchangeRates);
466
- }
467
- const hasMarkPrice = typeof position.markPrice === "number" && Number.isFinite(position.markPrice);
468
- const hasQuotePrice = typeof financials?.quote?.price === "number" && Number.isFinite(financials.quote.price);
469
- const price = hasMarkPrice ? position.markPrice : hasQuotePrice ? financials!.quote!.price : position.avgCost;
470
- // The multiplier the portfolio values the lot by: a future of unknown size has no value, never one at 1x.
471
- const multiplier = positionContractMultiplier(ticker, position);
472
- if (!Number.isFinite(position.shares) || typeof price !== "number" || !Number.isFinite(price) || multiplier === null) return null;
473
- return convertCurrency(
474
- Math.abs(position.shares * price * multiplier),
475
- hasQuotePrice && !hasMarkPrice ? quoteCurrency : positionCurrency,
476
- baseCurrency,
477
- exchangeRates,
478
- );
479
- }
480
-
481
- function pricePointTimeOrNull(point: PricePoint): number | null {
482
- const value = point.date;
483
- if (value == null) return null;
484
- const time = value instanceof Date ? value.getTime() : new Date(value).getTime();
485
- return Number.isFinite(time) ? time : null;
486
- }
487
-
488
- function recentPriceHistory(history: PricePoint[], days: number): PricePoint[] {
489
- let latestTime = 0;
490
- for (const point of history) {
491
- const time = pricePointTimeOrNull(point);
492
- if (time != null && time > latestTime) latestTime = time;
493
- }
494
- if (latestTime <= 0) return [];
495
- const cutoff = latestTime - days * 24 * 60 * 60 * 1000;
496
- return history.filter((point) => {
497
- const time = pricePointTimeOrNull(point);
498
- return time != null && time >= cutoff;
499
- });
500
- }
501
-
502
- /**
503
- * Work derived from a bar history, kept with the history. Every sync values
504
- * every portfolio and quotes every filed ticker (each 15 s poll, and after
505
- * each workspace change), and redoing that work from each holding's bars
506
- * blocked the view for a quarter of a second on a few hundred holdings.
507
- * Bars change when a history loads again, which replaces the
508
- * array; a last bar extended or revised in place, or one appended, is caught
509
- * by its length, time and close.
510
- */
511
- function historyMemo<T>(derive: (history: PricePoint[]) => T): (history: PricePoint[] | undefined) => T {
512
- const kept = new WeakMap<PricePoint[], { length: number; lastTime: number | null; lastClose: number | undefined; value: T }>();
513
- const empty = derive([]);
514
- return (history) => {
515
- if (!history || history.length === 0) return empty;
516
- const last = history[history.length - 1]!;
517
- const lastTime = pricePointTimeOrNull(last);
518
- const cached = kept.get(history);
519
- if (cached && cached.length === history.length && cached.lastTime === lastTime && cached.lastClose === last.close) return cached.value;
520
- const value = derive(history);
521
- kept.set(history, { length: history.length, lastTime, lastClose: last.close, value });
522
- return value;
523
- };
524
- }
525
-
526
- /** A holding's daily returns over its last year of bars. */
527
- const lastYearReturns = historyMemo((history): ReturnHistoryResult => resolveDatedReturns(recentPriceHistory(history, 366)));
528
-
529
- /** The holdings' beta to SPY at today's weights, worked out only when no preview supplies one. */
530
- function holdingsBeta(series: WeightedReturnSeries[], spyReturns: DatedReturn[]): number | null {
531
- if (series.length === 0 || spyReturns.length === 0) return null;
532
- const returns = computeWeightedPortfolioReturns(series);
533
- return returns.length > 0 ? computeDatedBeta(returns, spyReturns) : null;
534
- }
535
-
536
- function collectAnalyticsByPortfolio(
537
- config: AppConfig,
538
- tickers: Map<string, TickerRecord>,
539
- financials: Map<string, TickerFinancials>,
540
- exchangeRates: Map<string, number>,
541
- brokerAccounts: Record<string, BrokerAccount[]>,
542
- ) {
543
- const output: Record<string, Record<string, unknown>> = {};
544
- const spySample = lastYearReturns(financials.get("SPY")?.priceHistory);
545
- const spyReturns = spySample.returns;
546
- for (const portfolio of config.portfolios) {
547
- const account = portfolio.brokerInstanceId && portfolio.brokerAccountId
548
- ? brokerAccounts[portfolio.brokerInstanceId]?.find((entry) => entry.accountId === portfolio.brokerAccountId)
549
- : undefined;
550
- let unsupported = !!syntheticAccountUnsupportedReason(account);
551
- let invalidHistory = false;
552
- const datedReturnSeries: WeightedReturnSeries[] = [];
553
- for (const ticker of tickers.values()) {
554
- const tickerFinancials = financials.get(ticker.metadata.ticker);
555
- const portfolioPositions = ticker.metadata.positions.filter((position) => position.portfolio === portfolio.id);
556
- if (portfolioPositions.length === 0) continue;
557
- unsupported ||= !!syntheticPositionUnsupportedReason(
558
- ticker, tickerFinancials?.quote?.currency || ticker.metadata.currency || config.baseCurrency, portfolio.id,
559
- );
560
- for (const position of portfolioPositions) {
561
- if (position.shares === 0) continue;
562
- const value = positionValueBase(ticker, position, tickerFinancials, config.baseCurrency, exchangeRates);
563
- if (value == null || !Number.isFinite(value)) {
564
- unsupported = true;
565
- continue;
566
- }
567
- const sample = lastYearReturns(tickerFinancials?.priceHistory);
568
- invalidHistory ||= sample.integrity != null;
569
- const returns = sample.returns;
570
- if (returns.length >= 10) datedReturnSeries.push({ weight: value, returns });
571
- else unsupported = true;
572
- }
573
- }
574
- const previewAnalytics = getSyncedProfileAnalytics(portfolio.id);
575
- // The broker's own returns do not depend on the holdings' price histories.
576
- const accountBasis = previewAnalytics?.basis === "account";
577
- // A weighted history of today's holdings is not the investor's actual
578
- // one-year account return. Only preserve an explicitly supplied preview.
579
- const oneYearReturn = invalidHistory && !accountBasis ? null : previewAnalytics?.oneYearReturn ?? null;
580
- const spyBeta = (invalidHistory && !accountBasis) || spySample.integrity ? null : previewAnalytics?.spyBeta
581
- ?? holdingsBeta(unsupported ? [] : datedReturnSeries, spyReturns);
582
- output[portfolio.id] = {
583
- oneYearReturn,
584
- spyBeta,
585
- basis: oneYearReturn == null && spyBeta == null ? null : previewAnalytics?.basis ?? "holdings",
586
- };
587
- }
588
- return output;
589
- }
590
-
591
- function collectAccountsByPortfolio(
592
- config: AppConfig,
593
- brokerAccounts: Record<string, BrokerAccount[]>,
594
- ) {
595
- const output: Record<string, Record<string, string | number>> = {};
596
- for (const portfolio of config.portfolios) {
597
- if (!portfolio.brokerInstanceId || !portfolio.brokerAccountId) continue;
598
- const account = brokerAccounts[portfolio.brokerInstanceId]?.find(
599
- (entry) => entry.accountId === portfolio.brokerAccountId,
600
- );
601
- if (!account || !Number.isFinite(account.netLiquidation)) continue;
602
- output[portfolio.id] = {
603
- currency: account.currency ?? portfolio.currency ?? config.baseCurrency,
604
- netLiquidation: account.netLiquidation!,
605
- ...(Number.isFinite(account.dailyPnl) ? { dailyPnl: account.dailyPnl! } : {}),
606
- ...(Number.isFinite(account.unrealizedPnl) ? { unrealizedPnl: account.unrealizedPnl! } : {}),
607
- ...(Number.isFinite(account.updatedAt) ? { updatedAt: account.updatedAt! } : {}),
608
- };
609
- }
610
- return output;
611
- }
612
-
613
- type SanitizedTickerMetadata = ReturnType<typeof sanitizeTickerMetadata>;
614
-
615
- /** Only tickers the user actually filed somewhere are worth syncing. */
616
- function isSyncableTicker(metadata: Pick<SanitizedTickerMetadata, "portfolios" | "watchlists" | "positions">): boolean {
617
- return metadata.portfolios.length > 0
618
- || metadata.watchlists.length > 0
619
- || metadata.positions.length > 0;
620
- }
621
-
622
- /**
623
- * USD-per-unit rates for the base currency and every currency a holding is
624
- * valued in, read from the same FX store the portfolio panes use. A currency
625
- * without a usable rate stays missing, so its holdings count as unsupported.
626
- */
627
- async function loadHoldingExchangeRates(
628
- config: AppConfig,
629
- tickers: Map<string, TickerRecord>,
630
- financials: Map<string, TickerFinancials>,
631
- ): Promise<Map<string, number>> {
632
- const rates = new Map([["USD", 1]]);
633
- const coordinator = getSharedMarketDataCoordinator();
634
- if (!coordinator) return rates;
635
- const held: Array<string | undefined> = [config.baseCurrency];
636
- for (const ticker of tickers.values()) {
637
- if (ticker.metadata.positions.length === 0) continue;
638
- held.push(financials.get(ticker.metadata.ticker)?.quote?.currency);
639
- for (const position of ticker.metadata.positions) held.push(position.currency);
640
- }
641
- // With a minor unit's major currency, as the panes load them (GBX and ILA have no rate of their own).
642
- const currencies = fxRateCurrencies(held).filter((currency) => currency !== "USD");
643
- await Promise.all(currencies.map(async (currency) => {
644
- // A failed FX load must not hold back the rest of the push.
645
- await coordinator.loadFxRate(currency).catch(() => {});
646
- const rate = resolveEntryValue(coordinator.getFxEntry(currency));
647
- if (rate != null) rates.set(currency, rate);
648
- }));
649
- return rates;
650
- }
651
-
652
- function collectCoreCollectionsPayload(
653
- config: AppConfig,
654
- tickers: Map<string, TickerRecord>,
655
- financials: Map<string, TickerFinancials>,
656
- exchangeRates: Map<string, number>,
657
- brokerAccounts: Record<string, BrokerAccount[]>,
658
- /** The financials whose quotes may be uploaded: without those a source that keeps its market data local supplied. */
659
- quoted: Map<string, TickerFinancials> = financials,
660
- ) {
661
- const records = [...tickers.values()]
662
- .map((ticker) => sanitizeTickerMetadata(ticker.metadata, quoted.get(ticker.metadata.ticker)))
663
- .filter(isSyncableTicker);
664
-
665
- // Only the USD anchor goes on the wire, as before: readers of the snapshot
666
- // use any rate found here instead of fetching a current one, and a rate
667
- // loaded for this push would age with it.
668
- return {
669
- baseCurrency: config.baseCurrency,
670
- exchangeRates: { USD: 1 },
671
- portfolios: config.portfolios.map(sanitizePortfolio),
672
- watchlists: config.watchlists.map(sanitizeWatchlist),
673
- analyticsByPortfolio: collectAnalyticsByPortfolio(config, tickers, financials, exchangeRates, brokerAccounts),
674
- accountsByPortfolio: collectAccountsByPortfolio(config, brokerAccounts),
675
- tickers: records,
676
- };
677
- }
678
-
679
- function hydrateProfileAnalytics(payload: Record<string, unknown>): void {
680
- if (!isRecord(payload.analyticsByPortfolio)) return;
681
- for (const [portfolioId, analytics] of Object.entries(payload.analyticsByPortfolio)) {
682
- if (!isRecord(analytics)) continue;
683
- setSyncedProfileAnalytics(portfolioId, {
684
- oneYearReturn: typeof analytics.oneYearReturn === "number" ? analytics.oneYearReturn : null,
685
- spyBeta: typeof analytics.spyBeta === "number" ? analytics.spyBeta : null,
686
- basis: analytics.basis === "account" || analytics.basis === "holdings" ? analytics.basis : null,
687
- });
688
- }
689
- }
690
-
691
- function valuesEqual(left: unknown, right: unknown): boolean {
692
- return stableStringify(left) === stableStringify(right);
693
- }
694
-
695
- function isPluginStateMap(value: unknown): value is Record<string, Record<string, unknown>> {
696
- return isRecord(value) && Object.values(value).every(isRecord);
697
- }
698
-
699
- function withoutSessionLayoutState(savedLayout: SavedLayout): SavedLayout {
700
- if (!isRecord(savedLayout)) return savedLayout;
701
- if (!SESSION_SAVED_LAYOUT_KEYS.some((key) => key in savedLayout)) return savedLayout;
702
- const { paneState: _paneState, focusedPaneId: _focusedPaneId, activePanel: _activePanel, ...rest } = savedLayout;
703
- return rest;
704
- }
705
-
706
- /**
707
- * A pulled layout list describes the workspace; the session state stays with
708
- * this device. Entries are matched by name first so a renamed or reordered
709
- * list still hands each layout back its own pane state.
710
- */
711
- function withLocalSessionLayoutState(
712
- pulled: SavedLayout[],
713
- local: SavedLayout[],
714
- ): SavedLayout[] {
715
- const localByName = new Map(local.map((savedLayout) => [savedLayout?.name, savedLayout]));
716
- return pulled.map((savedLayout, index) => {
717
- if (!isRecord(savedLayout)) return savedLayout;
718
- const stripped = withoutSessionLayoutState(savedLayout);
719
- const source = localByName.get(savedLayout.name) ?? local[index];
720
- if (!source) return stripped;
721
- return {
722
- ...stripped,
723
- paneState: source.paneState,
724
- focusedPaneId: source.focusedPaneId,
725
- };
726
- });
727
- }
728
-
729
- /** A dock tree with no stack's shown tab: like stacking order, it follows whichever pane was focused last. */
730
- function withoutShownTabs(node: unknown): unknown {
731
- if (!isRecord(node) || node.kind !== "split") return node;
732
- const { tabs, ...rest } = node;
733
- return {
734
- ...rest,
735
- first: withoutShownTabs(node.first),
736
- second: withoutShownTabs(node.second),
737
- ...(tabs === undefined ? {} : { tabs: true }),
738
- };
739
- }
740
-
741
- /**
742
- * A layout as the user arranged it. Stacking order and the tab a stack shows
743
- * follow whichever pane was focused last, and a pane in its own desktop window
744
- * is one a terminal draws inline as a floating pane, so none of them tells two
745
- * copies apart.
746
- */
747
- function arrangedLayout(layout: unknown): unknown {
748
- if (!isRecord(layout)) return layout;
749
- const windows = [
750
- ...(Array.isArray(layout.floating) ? layout.floating : []),
751
- ...(Array.isArray(layout.detached) ? layout.detached : []),
752
- ].map((entry) => {
753
- if (!isRecord(entry)) return entry;
754
- const { zIndex: _zIndex, ...rest } = entry;
755
- return rest;
756
- });
757
- const instanceId = (entry: unknown) => (isRecord(entry) ? String(entry.instanceId) : "");
758
- windows.sort((left, right) => instanceId(left).localeCompare(instanceId(right)));
759
- return { ...layout, dockRoot: withoutShownTabs(layout.dockRoot), floating: windows, detached: [] };
760
- }
761
-
762
- // Pulled and last synced payloads are compared on every sync and never change.
763
- const layoutIntents = new WeakMap<object, string | null>();
764
-
765
- /**
766
- * A key for the workspace a payload describes, equal for two copies that only
767
- * differ in what reflects one device, so a real edit can be told from them.
768
- * Null when the payload holds no complete workspace.
769
- */
770
- function layoutIntent(payload: unknown): string | null {
771
- if (!isRecord(payload) || !Array.isArray(payload.layouts)) return null;
772
- if (!LAYOUT_SYNC_KEYS.every((key) => key in payload)) return null;
773
- const cached = layoutIntents.get(payload);
774
- if (cached !== undefined) return cached;
775
- const intent = stableStringify(sanitizeUnknown({
776
- layout: arrangedLayout(payload.layout),
777
- layouts: payload.layouts.map((entry) => (
778
- isRecord(entry)
779
- ? { ...withoutSessionLayoutState(entry as unknown as SavedLayout), layout: arrangedLayout(entry.layout) }
780
- : entry
781
- )),
782
- activeLayoutIndex: payload.activeLayoutIndex,
783
- }));
784
- const key = `${fnv1aHex(intent)}:${intent.length}`;
785
- layoutIntents.set(payload, key);
786
- return key;
787
- }
788
-
789
- /** The workspace keys of a payload, with the time its layout was last edited when it says. */
790
- function pickLayoutPayload(payload: Record<string, unknown>): Record<string, unknown> {
791
- const picked = Object.fromEntries([...LAYOUT_SYNC_KEYS, "layoutEditedAt"].flatMap((key) => (
792
- key in payload ? [[key, payload[key]]] : []
793
- )));
794
- // An older build still sent the view it was looking at with each layout.
795
- if (Array.isArray(picked.layouts)) {
796
- picked.layouts = picked.layouts.map((entry) => (isRecord(entry) ? withoutSessionLayoutState(entry as unknown as SavedLayout) : entry));
797
- }
798
- return picked;
799
- }
800
-
801
- /**
802
- * What this device remembers about its workspace between syncs: when it last
803
- * edited it (null when that happened while the app was closed, so the time is
804
- * unknown), or, when it took the workspace from the cloud, that copy as synced.
805
- */
806
- interface LayoutMemo {
807
- intent: string;
808
- editedAt: number | null;
809
- synced?: Record<string, unknown>;
810
- }
811
-
812
- function readLayoutMemo(value: unknown): LayoutMemo | null {
813
- if (!isRecord(value) || typeof value.intent !== "string") return null;
814
- return {
815
- intent: value.intent,
816
- editedAt: typeof value.editedAt === "number" && Number.isFinite(value.editedAt) ? value.editedAt : null,
817
- ...(isRecord(value.synced) ? { synced: value.synced } : {}),
818
- };
819
- }
820
-
821
- /**
822
- * When a pulled workspace was last edited. A copy from a build that did not
823
- * date edits counts as edited when it was pushed, which is never earlier.
824
- */
825
- function pulledLayoutEditedAt(payload: Record<string, unknown>, pushedAt: string | undefined): number {
826
- if (typeof payload.layoutEditedAt === "number" && Number.isFinite(payload.layoutEditedAt)) return payload.layoutEditedAt;
827
- const pushed = pushedAt ? Date.parse(pushedAt) : Number.NaN;
828
- return Number.isFinite(pushed) ? pushed : Number.POSITIVE_INFINITY;
829
- }
830
-
831
- /**
832
- * Whether a pulled workspace replaces this device's, three ways: against the
833
- * copy this device last synced, the one it had when the pull started, and the
834
- * pulled one. Only a real edit here keeps the local copy; the pane state,
835
- * focus and window stacking that change on every launch never do.
836
- */
837
- function shouldAdoptPulledLayout({
838
- local,
839
- atPullStart,
840
- lastSynced,
841
- pulled,
842
- memo,
843
- pulledEditedAt,
844
- }: {
845
- local: string | null;
846
- atPullStart: string | null;
847
- lastSynced: string | null;
848
- pulled: string | null;
849
- memo: LayoutMemo | null;
850
- pulledEditedAt: number;
851
- }): boolean {
852
- if (pulled === null || pulled === local) return false;
853
- // Edited while the pull was in flight: newer than anything it carries.
854
- if (local !== atPullStart) return false;
855
- const takenFromCloud = !!memo?.synced && memo.intent === local;
856
- const editedHere = lastSynced !== null && local !== lastSynced && !takenFromCloud;
857
- if (!editedHere) return true;
858
- // The cloud still holds what this device last synced: only this side changed.
859
- if (pulled === lastSynced) return false;
860
- // Both sides changed since: the later edit wins, and an undated local one loses.
861
- const localEditedAt = memo?.intent === local ? memo.editedAt : null;
862
- return localEditedAt === null || localEditedAt <= pulledEditedAt;
863
- }
864
-
865
- /**
866
- * The workspace as the cloud already has it unless this device really edited
867
- * it, so what only reflects this device never replaces another device's copy,
868
- * and a real edit goes out dated.
869
- */
870
- function withLayoutProvenance(
871
- payload: Record<string, unknown>,
872
- lastSyncedPayload: unknown,
873
- memoValue: unknown,
874
- ): Record<string, unknown> {
875
- const local = layoutIntent(payload);
876
- if (local === null) return payload;
877
- const memo = readLayoutMemo(memoValue);
878
- if (memo?.synced && memo.intent === local) return { ...payload, ...memo.synced };
879
- if (isRecord(lastSyncedPayload) && layoutIntent(lastSyncedPayload) === local) {
880
- return { ...payload, ...pickLayoutPayload(lastSyncedPayload) };
881
- }
882
- return {
883
- ...payload,
884
- layoutEditedAt: memo?.intent === local && memo.editedAt !== null ? memo.editedAt : Date.now(),
885
- };
886
- }
887
-
888
- /**
889
- * Dates a workspace edit when it happens, online or not, so a later conflict
890
- * with another device's edit goes to the newer one.
891
- */
892
- function noteLayoutEdit(config: AppConfig, lastSyncedPayload: unknown, memoValue: unknown, launch: boolean): LayoutMemo | null {
893
- const lastSynced = layoutIntent(lastSyncedPayload);
894
- if (lastSynced === null) return null;
895
- const local = layoutIntent(collectLayoutPayload(config));
896
- if (local === null || local === lastSynced) return null;
897
- if (readLayoutMemo(memoValue)?.intent === local) return null;
898
- // Seen at launch, it was made while the app was closed or just before it
899
- // quit; when is unknown, so it gives way to a dated edit elsewhere.
900
- return { intent: local, editedAt: launch ? null : Date.now() };
901
- }
902
-
903
- /**
904
- * Once this device holds the cloud's workspace, by taking it or because the
905
- * two already matched, it remembers that copy as synced, keyed by how it
906
- * looks here once applied. The next push then sends the cloud's own copy back
907
- * rather than this device's rendering of it.
908
- */
909
- function rememberCloudLayout(
910
- payload: Record<string, unknown>,
911
- pushedAt: string | undefined,
912
- applied: AppConfig,
913
- memo: { get(): unknown; set(value: unknown): void },
914
- adopted: boolean,
915
- ): void {
916
- const local = layoutIntent(collectLayoutPayload(applied));
917
- if (local === null || (!adopted && local !== layoutIntent(payload))) return;
918
- const current = readLayoutMemo(memo.get());
919
- if (!adopted && current?.synced && current.intent === local) return;
920
- const editedAt = pulledLayoutEditedAt(payload, pushedAt);
921
- memo.set({
922
- intent: local,
923
- editedAt: Number.isFinite(editedAt) ? editedAt : null,
924
- synced: pickLayoutPayload(payload),
925
- } satisfies LayoutMemo);
926
- }
927
-
928
- interface LayoutMergeContext {
929
- memo?: unknown;
930
- /** When the pulled copy was pushed, for one from a build that did not date layout edits. */
931
- pushedAt?: string;
932
- }
933
-
934
- /** A pulled config without profiles and portfolios that are local-only here (an older build may have pushed them). */
935
- function publicConfigPayload(payload: Record<string, unknown>, scope: LocalOnlyScope): Record<string, unknown> {
936
- const without = (entries: unknown, isLocal: (entry: Record<string, unknown>) => boolean) => (
937
- Array.isArray(entries) ? entries.filter((entry) => !isRecord(entry) || !isLocal(entry)) : entries
938
- );
939
- return {
940
- ...payload,
941
- ...("brokerInstances" in payload ? { brokerInstances: without(payload.brokerInstances, (entry) => isLocalOnlyInstance({ id: String(entry.id) }, scope)) } : {}),
942
- ...("portfolios" in payload ? { portfolios: without(payload.portfolios, (entry) => isLocalOnlyPortfolio(entry as unknown as Portfolio, scope)) } : {}),
943
- };
944
- }
945
-
946
- function mergeConfigPayload(
947
- config: AppConfig,
948
- payload: unknown,
949
- baselineConfig: AppConfig = config,
950
- lastSyncedPayload?: unknown,
951
- layoutContext: LayoutMergeContext = {},
952
- scope: LocalOnlyScope | null = null,
953
- ): AppConfig | null {
954
- if (!isRecord(payload)) return null;
955
- if (scope) {
956
- // Merged as if the local-only profiles and portfolios were not here, then put back as they were.
957
- const local = publicConfig(config, scope);
958
- const merged = mergeConfigPayload(local, publicConfigPayload(payload, scope), baselineConfig === config ? local : publicConfig(baselineConfig, scope),
959
- lastSyncedPayload, layoutContext);
960
- return merged && {
961
- ...merged,
962
- brokerInstances: withLocalOnlyEntries(merged.brokerInstances, config.brokerInstances, (instance) => isLocalOnlyInstance(instance, scope)),
963
- portfolios: withLocalOnlyEntries(merged.portfolios, config.portfolios, (portfolio) => isLocalOnlyPortfolio(portfolio, scope)),
964
- };
965
- }
966
- const next: AppConfig = { ...config };
967
- // Two guards, both needed. baselineConfig catches edits made while this pull
968
- // was in flight; lastSyncedPayload catches edits made while the app was not
969
- // running at all (CLI writes, offline edits), which otherwise look pristine.
970
- const lastSynced = isRecord(lastSyncedPayload) ? lastSyncedPayload : null;
971
- const localPayload = collectCoreConfigPayload(config) as Record<string, unknown>;
972
- const matchesLastSynced = (key: string) => (
973
- !lastSynced || valuesEqual(localPayload[key], lastSynced[key])
974
- );
975
- const canApply = <K extends keyof AppConfig>(key: K) => (
976
- valuesEqual(config[key], baselineConfig[key]) && matchesLastSynced(key as string)
977
- );
978
- const assign = <K extends keyof AppConfig>(key: K) => {
979
- if (key in payload && canApply(key)) {
980
- next[key] = payload[key as string] as AppConfig[K];
981
- }
982
- };
983
-
984
- assign("baseCurrency");
985
- // A device on an older version may still send a name or sign (Canadian dollar, CA$): it applies as its code, as a saved one loads.
986
- if (typeof next.baseCurrency === "string" && next.baseCurrency.trim()) next.baseCurrency = normalizeStoredBaseCurrency(next.baseCurrency);
987
- assign("refreshIntervalMinutes");
988
- if ("portfolios" in payload && canApply("portfolios")) {
989
- const syncedPortfolios = payload.portfolios;
990
- next.portfolios = Array.isArray(syncedPortfolios)
991
- ? mergeLocalBrokerPortfolioIdentity(config.portfolios, syncedPortfolios as Portfolio[])
992
- : syncedPortfolios as AppConfig["portfolios"];
993
- }
994
- assign("watchlists");
995
- assign("disabledSources");
996
- assign("theme");
997
- assign("chartPreferences");
998
- assign("valueFlashingEnabled");
999
- assign("recentTickers");
1000
- assign("recentCommands");
1001
- const telemetry = mergedAttentionTelemetry(config, baselineConfig, payload, lastSynced);
1002
- if (telemetry !== config.telemetry) next.telemetry = telemetry;
1003
- // Sync can complete onboarding on another device, but never reopen it.
1004
- // Resumable progress remains local until this installation completes it.
1005
- if (
1006
- !config.onboardingProgress
1007
- && config.onboardingComplete !== true
1008
- && payload.onboardingComplete === true
1009
- && canApply("onboardingComplete")
1010
- ) {
1011
- next.onboardingComplete = true;
1012
- }
1013
-
1014
- if (
1015
- canApply("disabledPlugins")
1016
- && Array.isArray(payload.disabledPlugins)
1017
- && payload.disabledPlugins.every((pluginId) => typeof pluginId === "string")
1018
- ) {
1019
- next.disabledPlugins = decodeBuiltinDisabledPluginIds(payload.disabledPlugins);
1020
- }
1021
- if (canApply("pluginConfig") && isPluginStateMap(payload.pluginConfig)) {
1022
- next.pluginConfig = withLocalPluginSecrets(
1023
- normalizeBuiltinPluginStateMap(payload.pluginConfig),
1024
- config.pluginConfig,
1025
- );
1026
- }
1027
-
1028
- // Compared by content, not identity: the active layout mirrors pane state,
1029
- // so a cursor settling at launch replaced it mid-pull, the pulled workspace
1030
- // was refused, and the push that followed wrote this device's older one
1031
- // over it on every other device.
1032
- const localIntent = layoutIntent(localPayload);
1033
- const adoptLayout = shouldAdoptPulledLayout({
1034
- local: localIntent,
1035
- atPullStart: baselineConfig === config ? localIntent : layoutIntent(collectLayoutPayload(baselineConfig)),
1036
- lastSynced: layoutIntent(lastSynced),
1037
- pulled: layoutIntent(payload),
1038
- memo: readLayoutMemo(layoutContext.memo),
1039
- pulledEditedAt: pulledLayoutEditedAt(payload, layoutContext.pushedAt),
1040
- });
1041
- if (adoptLayout) {
1042
- next.layout = payload.layout as unknown as AppConfig["layout"];
1043
- next.layouts = withLocalSessionLayoutState(payload.layouts as AppConfig["layouts"], config.layouts);
1044
- next.activeLayoutIndex = payload.activeLayoutIndex as number;
1045
- }
1046
-
1047
- if (Array.isArray(payload.brokerInstances)) {
1048
- const syncedIds = Array.isArray(lastSynced?.brokerInstances) ? idsOf(lastSynced.brokerInstances) : null;
1049
- next.brokerInstances = mergeBrokerInstances(
1050
- config.brokerInstances,
1051
- payload.brokerInstances as Array<Partial<BrokerInstanceConfig>>,
1052
- canApply("brokerInstances"),
1053
- syncedIds,
1054
- payload.brokerInstancesMergedById === true,
1055
- );
1056
- if (syncedIds) next.portfolios = withoutRemovedBrokerPortfolios(config, next, syncedIds, payload.portfolios);
1057
- }
1058
- return next;
1059
- }
1060
-
1061
- /** The entries of a pulled list that carry an id. */
1062
- function idEntries(entries: unknown): Array<{ id: string }> {
1063
- return Array.isArray(entries)
1064
- ? entries.flatMap((entry) => (isRecord(entry) && typeof entry.id === "string" ? [{ id: entry.id }] : []))
1065
- : [];
1066
- }
1067
-
1068
- function idsOf(entries: unknown[]): Set<string> {
1069
- return new Set(entries.flatMap((entry) => (isRecord(entry) && typeof entry.id === "string" ? [entry.id] : [])));
1070
- }
1071
-
1072
- /**
1073
- * Takes the pulled profiles when this device has not changed its own since it
1074
- * last synced. When it has (a broker sync alone moves `lastSyncedAt`), it keeps
1075
- * its own, but profile by profile against the ids it last synced: one removed
1076
- * on another device goes, one removed here stays gone, and one added elsewhere
1077
- * arrives. Keeping the whole list instead pushed a profile removed elsewhere
1078
- * back to every device.
1079
- *
1080
- * An older build that changed its own profiles pushes its whole list, without
1081
- * a profile added here since it last pulled, so only a list merged the same
1082
- * way (`removalsCount`) can remove one: the profile's settings never sync and
1083
- * would be lost for good.
1084
- */
1085
- function mergeBrokerInstances(
1086
- local: BrokerInstanceConfig[],
1087
- incoming: Array<Partial<BrokerInstanceConfig>>,
1088
- localUnchanged: boolean,
1089
- syncedIds: ReadonlySet<string> | null,
1090
- removalsCount: boolean,
1091
- ): BrokerInstanceConfig[] {
1092
- const localById = new Map(local.map((instance) => [instance.id, instance]));
1093
- const fromIncoming = (instance: Partial<BrokerInstanceConfig>): BrokerInstanceConfig => {
1094
- const current = instance.id ? localById.get(instance.id) : undefined;
1095
- return {
1096
- id: instance.id ?? current?.id ?? crypto.randomUUID(),
1097
- brokerType: instance.brokerType ?? current?.brokerType ?? "",
1098
- label: instance.label ?? current?.label ?? "",
1099
- connectionMode: instance.connectionMode ?? current?.connectionMode,
1100
- enabled: instance.enabled ?? current?.enabled,
1101
- lastSyncedAt: instance.lastSyncedAt ?? current?.lastSyncedAt,
1102
- config: current?.config ?? {},
1103
- };
1104
- };
1105
- if (localUnchanged) return incoming.map(fromIncoming);
1106
- if (!syncedIds) return local;
1107
-
1108
- const incomingIds = idsOf(incoming);
1109
- const kept = removalsCount
1110
- ? local.filter((instance) => incomingIds.has(instance.id) || !syncedIds.has(instance.id))
1111
- : local;
1112
- const added = incoming.filter((instance) => (
1113
- typeof instance.id === "string" && !localById.has(instance.id) && !syncedIds.has(instance.id)
1114
- ));
1115
- return kept.length === local.length && added.length === 0 ? local : [...kept, ...added.map(fromIncoming)];
1116
- }
1117
-
1118
- /**
1119
- * A broker portfolio goes with a profile the pull removed, unless the pulled
1120
- * portfolios still list it: another device handed it to a profile it kept.
1121
- * Only a profile this device had synced counts as removed elsewhere.
1122
- */
1123
- function withoutRemovedBrokerPortfolios(
1124
- config: AppConfig,
1125
- next: AppConfig,
1126
- syncedIds: ReadonlySet<string>,
1127
- pulledPortfolios: unknown,
1128
- ): Portfolio[] {
1129
- const remaining = new Set(next.brokerInstances.map((instance) => instance.id));
1130
- const removed = new Set(config.brokerInstances.flatMap((instance) => (
1131
- syncedIds.has(instance.id) && !remaining.has(instance.id) ? [instance.id] : []
1132
- )));
1133
- if (removed.size === 0) return next.portfolios;
1134
- const pulledIds = Array.isArray(pulledPortfolios) ? idsOf(pulledPortfolios) : new Set<string>();
1135
- const portfolios = next.portfolios.filter((portfolio) => (
1136
- !portfolio.brokerInstanceId || !removed.has(portfolio.brokerInstanceId) || pulledIds.has(portfolio.id)
1137
- ));
1138
- return portfolios.length === next.portfolios.length ? next.portfolios : portfolios;
1139
- }
1140
-
1141
- interface RemovedBrokerHoldings {
1142
- instanceIds: ReadonlySet<string>;
1143
- portfolioIds: ReadonlySet<string>;
1144
- }
1145
-
1146
- /** The profiles a pull removed, and the portfolios that went with them. */
1147
- function removedBrokerHoldings(before: AppConfig, after: AppConfig): RemovedBrokerHoldings | null {
1148
- const remaining = new Set(after.brokerInstances.map((instance) => instance.id));
1149
- const instanceIds = new Set(before.brokerInstances.flatMap((instance) => (
1150
- remaining.has(instance.id) ? [] : [instance.id]
1151
- )));
1152
- if (instanceIds.size === 0) return null;
1153
- const keptPortfolios = new Set(after.portfolios.map((portfolio) => portfolio.id));
1154
- const portfolioIds = new Set(before.portfolios.flatMap((portfolio) => (
1155
- portfolio.brokerInstanceId && instanceIds.has(portfolio.brokerInstanceId) && !keptPortfolios.has(portfolio.id)
1156
- ? [portfolio.id]
1157
- : []
1158
- )));
1159
- return { instanceIds, portfolioIds };
1160
- }
1161
-
1162
- /**
1163
- * The ticker as the removal on the other device left it: without the removed
1164
- * profiles' positions and contracts, or its place in their portfolios. Null
1165
- * when nothing is left to keep, as that removal deleted it; the same record
1166
- * when the removal did not touch it.
1167
- */
1168
- function withoutRemovedBrokerHoldings(ticker: TickerRecord, removed: RemovedBrokerHoldings): TickerRecord | null {
1169
- const { metadata } = ticker;
1170
- const positions = metadata.positions.filter((position) => (
1171
- !(position.brokerInstanceId && removed.instanceIds.has(position.brokerInstanceId))
1172
- && !removed.portfolioIds.has(position.portfolio)
1173
- ));
1174
- const portfolios = metadata.portfolios.filter((portfolioId) => !removed.portfolioIds.has(portfolioId));
1175
- const contracts = (metadata.broker_contracts ?? []).filter((contract) => (
1176
- !(contract.brokerInstanceId && removed.instanceIds.has(contract.brokerInstanceId))
1177
- ));
1178
- if (
1179
- positions.length === metadata.positions.length
1180
- && portfolios.length === metadata.portfolios.length
1181
- && contracts.length === (metadata.broker_contracts ?? []).length
1182
- ) {
1183
- return ticker;
1184
- }
1185
- const empty = positions.length === 0
1186
- && portfolios.length === 0
1187
- && contracts.length === 0
1188
- && metadata.watchlists.length === 0
1189
- && metadata.tags.length === 0
1190
- && Object.keys(metadata.custom).length === 0;
1191
- if (empty) return null;
1192
- return { ...ticker, metadata: { ...metadata, positions, portfolios, broker_contracts: contracts } };
1193
- }
1194
-
1195
- function lastSyncedTickersById(baselinePayload: unknown): Map<string, Record<string, unknown>> | null {
1196
- if (!isRecord(baselinePayload) || !Array.isArray(baselinePayload.tickers)) return null;
1197
- const byId = new Map<string, Record<string, unknown>>();
1198
- for (const entry of baselinePayload.tickers) {
1199
- if (isRecord(entry) && typeof entry.ticker === "string") byId.set(entry.ticker, entry);
1200
- }
1201
- return byId;
1202
- }
1203
-
1204
- /**
1205
- * Compared as stored. What this device last synced is read back from storage
1206
- * at launch without the fields that were undefined, so set against a copy
1207
- * collected fresh as is, every ticker read as edited here: a device started
1208
- * after a while away kept all its old rows and pushed them over newer ones.
1209
- */
1210
- function sameAsStored(left: unknown, right: unknown): boolean {
1211
- const stored = (value: unknown) => (value === undefined ? null : JSON.parse(JSON.stringify(value)));
1212
- return stableStringify(stored(left)) === stableStringify(stored(right));
1213
- }
1214
-
1215
- /**
1216
- * A ticker's own fields. Quotes churn on every refresh, and which portfolios
1217
- * hold it, and how much, merges portfolio by portfolio.
1218
- */
1219
- function tickerOwnFields(metadata: Record<string, unknown>): Record<string, unknown> {
1220
- const { quote: _quote, positions: _positions, portfolios: _portfolios, ...rest } = metadata;
1221
- return rest;
1222
- }
1223
-
1224
- /** One portfolio's part of a ticker: whether it lists the ticker, and the positions it holds in it. */
1225
- function holdingIn(positions: readonly TickerPosition[], links: readonly unknown[], portfolioId: string) {
1226
- return {
1227
- linked: links.includes(portfolioId),
1228
- positions: positions.filter((position) => position.portfolio === portfolioId).map(sanitizePosition),
1229
- };
1230
- }
1231
-
1232
- /** Without a shared baseline, keep both devices' manual lots, matching identical copies one for one. */
1233
- function mergeUntrackedManualPositions(local: TickerPosition[], pulled: TickerPosition[]): TickerPosition[] {
1234
- const unmatched = new Map<string, number>();
1235
- for (const position of local) {
1236
- const key = JSON.stringify(sanitizePosition(position));
1237
- unmatched.set(key, (unmatched.get(key) ?? 0) + 1);
1238
- }
1239
- const merged = [...local];
1240
- for (const position of pulled) {
1241
- const key = JSON.stringify(sanitizePosition(position));
1242
- const count = unmatched.get(key) ?? 0;
1243
- if (count > 0) unmatched.set(key, count - 1);
1244
- else merged.push(position);
1245
- }
1246
- return merged;
1247
- }
1248
-
1249
- interface PulledTickersMerge {
1250
- lastSyncedTickers: Map<string, Record<string, unknown>> | null;
1251
- /** This device's live broker portfolios, each with the side holding its latest broker sync. */
1252
- brokerPortfolios: ReadonlyMap<string, "local" | "pulled">;
1253
- known: KnownBrokerHoldings;
1254
- /** Connections kept on this device: their portfolios' holdings here outlast any pull. */
1255
- localOnly: LocalOnlyScope | null;
1256
- }
1257
-
1258
- /**
1259
- * Which side holds the latest sync of each live broker portfolio. Its
1260
- * positions are what the broker last reported, so only a later sync replaces
1261
- * them: a pushed copy older than this device's (from a device that was away,
1262
- * or an older build) never takes away positions this device's broker reported
1263
- * since, whatever other portfolios hold on the same ticker.
1264
- */
1265
- function latestBrokerPortfolioSyncs(
1266
- atPullStart: AppConfig,
1267
- live: AppConfig,
1268
- pulledPortfolios: unknown,
1269
- ): Map<string, "local" | "pulled"> {
1270
- const pulledSyncedAt = new Map<string, number>();
1271
- for (const portfolio of Array.isArray(pulledPortfolios) ? pulledPortfolios : []) {
1272
- if (isRecord(portfolio) && typeof portfolio.id === "string" && isFiniteNumber(portfolio.lastSyncedAt)) {
1273
- pulledSyncedAt.set(portfolio.id, portfolio.lastSyncedAt);
1274
- }
1275
- }
1276
- const sides = new Map<string, "local" | "pulled">();
1277
- for (const portfolio of live.portfolios) {
1278
- if (!getBrokerInstance(live.brokerInstances, portfolio.brokerInstanceId)) continue;
1279
- const localSyncedAt = atPullStart.portfolios.find((entry) => entry.id === portfolio.id)?.lastSyncedAt;
1280
- // Never synced here: its positions merge like a manual portfolio's.
1281
- if (!isFiniteNumber(localSyncedAt)) continue;
1282
- const pulled = pulledSyncedAt.get(portfolio.id);
1283
- // Later than this device's copy, and than a sync here that ended while the pull was out.
1284
- const pulledIsLater = pulled !== undefined
1285
- && pulled > localSyncedAt
1286
- && pulled >= (isFiniteNumber(portfolio.lastSyncedAt) ? portfolio.lastSyncedAt : 0);
1287
- sides.set(portfolio.id, pulledIsLater ? "pulled" : "local");
1288
- }
1289
- return sides;
1290
- }
1291
-
1292
- /**
1293
- * A pulled ticker merged with this device's, portfolio by portfolio: this
1294
- * device's part in a portfolio stays when it changed it since it last synced,
1295
- * a live broker portfolio goes to the side with its latest sync, and the rest
1296
- * comes from the pull. Broker contracts never sync and stay local.
1297
- */
1298
- function mergePulledTicker(
1299
- current: TickerRecord | undefined,
1300
- pulled: Record<string, unknown>,
1301
- merge: PulledTickersMerge,
1302
- ): TickerRecord {
1303
- const local = current?.metadata;
1304
- const baseline = merge.lastSyncedTickers?.get(String(pulled.ticker));
1305
- // Nothing to compare with (no copy here, or this device never synced): the pull is taken.
1306
- const comparable = !!local && !!merge.lastSyncedTickers;
1307
- // No copy last synced means this device never uploaded the ticker: filed
1308
- // locally it is unsynced work, unfiled it is not something sync tracks.
1309
- const ownFieldsEdited = comparable && (baseline
1310
- ? !sameAsStored(tickerOwnFields(sanitizeTickerMetadata(local)), tickerOwnFields(baseline))
1311
- : isSyncableTicker(sanitizeTickerMetadata(local)));
1312
-
1313
- const localPositions = local?.positions ?? [];
1314
- const localLinks = local?.portfolios ?? [];
1315
- const pulledPositions = Array.isArray(pulled.positions)
1316
- ? mergeLocalBrokerPositionIdentity(localPositions, pulled.positions as TickerPosition[])
1317
- : localPositions;
1318
- const pulledLinks = Array.isArray(pulled.portfolios)
1319
- ? pulled.portfolios.filter((portfolioId): portfolioId is string => typeof portfolioId === "string")
1320
- : localLinks;
1321
- const baselinePositions = Array.isArray(baseline?.positions) ? baseline.positions as TickerPosition[] : [];
1322
- const baselineLinks = Array.isArray(baseline?.portfolios) ? baseline.portfolios : [];
1323
-
1324
- const portfolioIds = [...new Set([
1325
- ...localLinks, ...localPositions.map((position) => position.portfolio),
1326
- ...pulledLinks, ...pulledPositions.map((position) => position.portfolio),
1327
- ])];
1328
- const positions: TickerPosition[] = [];
1329
- const portfolios: string[] = [];
1330
- for (const portfolioId of portfolioIds) {
1331
- const brokerSide = merge.brokerPortfolios.get(portfolioId);
1332
- const takePulled = merge.localOnly?.portfolioIds.has(portfolioId) ? false : brokerSide
1333
- ? brokerSide === "pulled"
1334
- : !comparable || sameAsStored(
1335
- holdingIn(localPositions, localLinks, portfolioId),
1336
- holdingIn(baselinePositions, baselineLinks, portfolioId),
1337
- );
1338
- const [sidePositions, sideLinks] = takePulled ? [pulledPositions, pulledLinks] : [localPositions, localLinks];
1339
- if (brokerSide && !merge.localOnly?.portfolioIds.has(portfolioId)) {
1340
- // A broker's timestamp governs imported holdings, never hand-entered
1341
- // lots. Those use the same edit comparison as a manual portfolio.
1342
- const manualIn = (entries: readonly TickerPosition[]) => entries.filter((position) => (
1343
- position.portfolio === portfolioId && position.broker === "manual"
1344
- ));
1345
- const localManual = manualIn(localPositions);
1346
- const manualEdited = comparable && !sameAsStored(
1347
- localManual.map(sanitizePosition), manualIn(baselinePositions).map(sanitizePosition),
1348
- );
1349
- const pulledManual = manualIn(pulledPositions);
1350
- const manual = !comparable ? mergeUntrackedManualPositions(localManual, pulledManual)
1351
- : manualEdited ? localManual : pulledManual;
1352
- positions.push(...sidePositions.filter((position) => position.portfolio === portfolioId && position.broker !== "manual"), ...manual);
1353
- if (sideLinks.includes(portfolioId) || manual.length > 0) portfolios.push(portfolioId);
1354
- } else {
1355
- positions.push(...sidePositions.filter((position) => position.portfolio === portfolioId));
1356
- if (sideLinks.includes(portfolioId)) portfolios.push(portfolioId);
1357
- }
1358
- }
1359
-
1360
- const record: TickerRecord = {
1361
- metadata: hydrateTickerMetadata({
1362
- ...(ownFieldsEdited ? local : { ...local, ...pulled }),
1363
- positions,
1364
- portfolios,
1365
- broker_contracts: local?.broker_contracts ?? [],
1366
- }),
1367
- };
1368
- return clearLeftoverBrokerHoldings(record, merge.known) ?? record;
1369
- }
1370
-
1371
- /**
1372
- * A ticker the pull did not carry: without what removed broker profiles left,
1373
- * and without positions in a broker portfolio whose later sync elsewhere no
1374
- * longer reports the ticker. Null when nothing changes.
1375
- */
1376
- function withoutUnpulledHoldings(ticker: TickerRecord, merge: PulledTickersMerge): TickerRecord | null {
1377
- const sold = (portfolioId: string) => merge.brokerPortfolios.get(portfolioId) === "pulled";
1378
- const { metadata } = ticker;
1379
- const positions = metadata.positions.filter((position) => position.broker === "manual" || !sold(position.portfolio));
1380
- const held = new Set(positions.map((position) => position.portfolio));
1381
- const portfolios = metadata.portfolios.filter((portfolioId) => held.has(portfolioId) || !sold(portfolioId));
1382
- const kept = positions.length === metadata.positions.length && portfolios.length === metadata.portfolios.length
1383
- ? ticker
1384
- : { ...ticker, metadata: { ...metadata, positions, portfolios } };
1385
- const cleaned = clearLeftoverBrokerHoldings(kept, merge.known) ?? kept;
1386
- return cleaned === ticker ? null : cleaned;
1387
- }
1388
-
1389
- const CORE_CONFIG_CONTRIBUTOR_ID = "core.config";
1390
-
1391
- export const coreConfigSyncContributor: SyncContributor = {
1392
- id: CORE_CONFIG_CONTRIBUTOR_ID,
1393
- schemaVersion: 1,
1394
- collect: ({ state, baselinePayload, memo }) => withLayoutProvenance(
1395
- collectCoreConfigPayload(publicConfig(state.config, localOnlyScope(state.config))) as Record<string, unknown>,
1396
- baselinePayload,
1397
- memo?.get(),
1398
- ),
1399
- observe: ({ state, baselinePayload, memo, launch }) => {
1400
- const edit = noteLayoutEdit(state.config, baselinePayload, memo.get(), launch);
1401
- if (edit) memo.set(edit);
1402
- },
1403
- apply: async (payload, { snapshot, baselinePayload, baselineState, state, getState, isCurrent, dispatch, tickerRepository, memo }) => {
1404
- const pushedAt = snapshot?.contributors[CORE_CONFIG_CONTRIBUTOR_ID]?.updatedAt;
1405
- const merge = (config: AppConfig) => mergeConfigPayload(config, payload, baselineState.config, baselinePayload, {
1406
- memo: memo?.get(),
1407
- pushedAt,
1408
- }, localOnlyScope(config));
1409
- let nextConfig = merge(state.config);
1410
- if (!nextConfig) return;
1411
- const removed = removedBrokerHoldings(state.config, nextConfig);
1412
- if (removed) {
1413
- // Keep the profile until row and config writes succeed, so a failed
1414
- // cleanup remains visible to the next attempt.
1415
- const cleanTickers = () => persistTickerCleanup({
1416
- tickerRepository,
1417
- getTickers: () => getState().tickers,
1418
- transform: (ticker) => withoutRemovedBrokerHoldings(ticker, removed),
1419
- publish: (symbol, ticker) => {
1420
- const tickers = new Map(getState().tickers);
1421
- if (ticker) tickers.set(symbol, ticker);
1422
- else tickers.delete(symbol);
1423
- dispatch({ type: "SET_TICKERS", tickers });
1424
- },
1425
- isCurrent,
1426
- });
1427
- let savedRemoval = false;
1428
- for (;;) {
1429
- const cleaned = await cleanTickers().catch(async (error: unknown) => {
1430
- // Restore the profile if a late row fails after config was saved,
1431
- // so retry can also recover after restarting the app.
1432
- if (savedRemoval) await saveConfigImmediately(getState().config);
1433
- throw error;
1434
- });
1435
- if (!cleaned || !isCurrent()) return;
1436
- if (hasPendingTickerWrites(tickerRepository) || getState().tickers !== cleaned) continue;
1437
- const source = getState().config;
1438
- const merged = merge(source);
1439
- if (!merged) return;
1440
- // Preserve unrelated edits while retaining the removal already applied
1441
- // to rows, including pulls from builds that merged whole profile lists.
1442
- nextConfig = {
1443
- ...merged,
1444
- brokerInstances: merged.brokerInstances.filter((instance) => !removed.instanceIds.has(instance.id)),
1445
- portfolios: merged.portfolios.filter((portfolio) => !removed.portfolioIds.has(portfolio.id)),
1446
- };
1447
- await saveConfigImmediately(nextConfig);
1448
- savedRemoval = true;
1449
- if (!isCurrent()) return;
1450
- if (getState().config !== source || getState().tickers !== cleaned
1451
- || hasPendingTickerWrites(tickerRepository)) continue;
1452
- break;
1453
- }
1454
- }
1455
- const configChanged = !valuesEqual(nextConfig, getState().config);
1456
- if (configChanged) {
1457
- // Adopting another device's workspace rearranges the screen under the
1458
- // user, so it is worth a line in the log when a report says "my panes
1459
- // moved on their own".
1460
- if (nextConfig.layout !== state.config.layout) {
1461
- log.info("config.layout.adopted", {
1462
- panes: nextConfig.layout.instances.length,
1463
- activeLayoutIndex: nextConfig.activeLayoutIndex,
1464
- });
1465
- }
1466
- // An Attention Counts off from another device drops unsent counts before React commits.
1467
- if (nextConfig.telemetry !== getState().config.telemetry) reportTelemetryConfig(nextConfig.telemetry);
1468
- dispatch({ type: "SET_CONFIG", config: nextConfig });
1469
- if (!removed) scheduleConfigSave(nextConfig);
1470
- }
1471
- if (memo && isRecord(payload)) rememberCloudLayout(payload, pushedAt, getState().config, memo, nextConfig.layouts !== state.config.layouts);
1472
- },
1473
- };
1474
-
1475
- export const coreCollectionsSyncContributor: SyncContributor = {
1476
- id: "core.collections",
1477
- schemaVersion: 1,
1478
- collect: async ({ state, isLocalMarketData }) => {
1479
- // Connections the user keeps on this device stay here, with their portfolios, account values and
1480
- // positions; so do the quotes and bars of a source that keeps its market data local.
1481
- const scope = localOnlyScope(state.config);
1482
- const config = publicConfig(state.config, scope);
1483
- const tickers = publicTickers(state.tickers, scope);
1484
- return collectCoreCollectionsPayload(
1485
- config,
1486
- tickers,
1487
- state.financials,
1488
- await loadHoldingExchangeRates(config, tickers, state.financials),
1489
- state.brokerAccounts,
1490
- publicMarketData(state.financials, isLocalMarketData),
1491
- );
1492
- },
1493
- apply: async (payload, { snapshot, baselinePayload, baselineState, getState, isCurrent, dispatch, tickerRepository }) => {
1494
- if (!isRecord(payload)) return;
1495
- const scope = localOnlyScope(getState().config);
1496
- hydrateProfileAnalytics(payload);
1497
- if (!isCurrent()) return;
1498
- // The config contributor applies first, so this is the config this pull left.
1499
- const state = getState();
1500
- const pulledConfig = recordOrNull(snapshot?.contributors[CORE_CONFIG_CONTRIBUTOR_ID]?.payload);
1501
- const pulledPortfolios = Array.isArray(payload.portfolios) ? payload.portfolios : pulledConfig?.portfolios;
1502
- // A copy without its ticker list says nothing of what any portfolio holds:
1503
- // a later sync stamp there must not take this device's broker positions.
1504
- const pulledTickers = Array.isArray(payload.tickers) ? payload.tickers : null;
1505
- const merge: PulledTickersMerge = {
1506
- lastSyncedTickers: lastSyncedTickersById(baselinePayload),
1507
- brokerPortfolios: pulledTickers
1508
- ? latestBrokerPortfolioSyncs(baselineState.config, state.config, pulledPortfolios)
1509
- : new Map(),
1510
- // A broker portfolio the pull still lists may only exist on another device: it stays.
1511
- known: knownBrokerHoldings(state.config, {
1512
- portfolios: [pulledPortfolios, pulledConfig?.portfolios].flatMap(idEntries),
1513
- brokerInstances: idEntries(pulledConfig?.brokerInstances),
1514
- }),
1515
- localOnly: scope,
1516
- };
1517
- // Tickers here and pulled ones drop the ids of any watchlist that is gone
1518
- // (removed elsewhere, or deleted by an older build that left its id on the
1519
- // tickers), so this device never pushes them back.
1520
- const watchlistIds = new Set(state.config.watchlists.map((watchlist) => watchlist.id));
1521
-
1522
- // Merged and handed to the app in one go, with no wait in between, so a
1523
- // broker sync committing meanwhile is not overwritten with an older row.
1524
- const nextTickers = new Map(state.tickers);
1525
- const changed: TickerRecord[] = [];
1526
- const pulledSymbols = new Set<string>();
1527
- for (const rawTicker of pulledTickers ?? []) {
1528
- if (!isRecord(rawTicker) || typeof rawTicker.ticker !== "string") continue;
1529
- pulledSymbols.add(rawTicker.ticker);
1530
- const current = state.tickers.get(rawTicker.ticker);
1531
- const record = withoutMissingWatchlists(mergePulledTicker(current, rawTicker, merge), watchlistIds);
1532
- if (current ? sameAsStored(record.metadata, hydrateTickerMetadata({ ...current.metadata })) : !isSyncableTicker(record.metadata)) continue;
1533
- nextTickers.set(record.metadata.ticker, record);
1534
- changed.push(record);
1535
- }
1536
- for (const ticker of state.tickers.values()) {
1537
- if (pulledSymbols.has(ticker.metadata.ticker)) continue;
1538
- const kept = withoutUnpulledHoldings(ticker, merge) ?? ticker;
1539
- const next = withoutMissingWatchlists(kept, watchlistIds);
1540
- if (next === ticker) continue;
1541
- nextTickers.set(next.metadata.ticker, next);
1542
- changed.push(next);
1543
- }
1544
- const suffixed = mergePulledSuffixedListings(nextTickers, changed, state.config);
1545
- if (changed.length === 0 && !suffixed.config) return;
1546
- if (suffixed.config) dispatch({ type: "SET_CONFIG", config: suffixed.config });
1547
- if (changed.length > 0) dispatch({ type: "SET_TICKERS", tickers: nextTickers });
1548
- // The moved targets first, so a stop before the rows strands none on an emptied key.
1549
- if (suffixed.config) await saveConfigImmediately(suffixed.config);
1550
- // Written one at a time, so an edit or a broker sync can replace a row
1551
- // before its turn. That copy is newer and its writer saves it; this one
1552
- // written over it would come back at launch as an edit and be pushed.
1553
- for (const record of changed) {
1554
- if (getState().tickers.get(record.metadata.ticker) !== record) continue;
1555
- await tickerRepository.saveTicker(record);
1556
- }
1557
- },
1558
- };
1559
-
1560
- /**
1561
- * An older build still files lots under a vendor's suffixed key (GARAN.IS)
1562
- * and pushes them: pulled, they merge into the listing's row here as at
1563
- * launch (`mergeSuffixedListings`), each lot once, so they never count in
1564
- * both rows or go back out under the old key. The merged rows replace their
1565
- * entries in `tickers` and `changed`; the config comes back with targets
1566
- * moved, or null when none moved.
1567
- */
1568
- function mergePulledSuffixedListings(
1569
- tickers: Map<string, TickerRecord>,
1570
- changed: TickerRecord[],
1571
- config: AppConfig,
1572
- ): { config: AppConfig | null } {
1573
- const merged = mergeSuffixedListings([...tickers.values()]);
1574
- if (!merged) return { config: null };
1575
- for (const row of merged.saves) {
1576
- tickers.set(row.metadata.ticker, row);
1577
- const at = changed.findIndex((record) => record.metadata.ticker === row.metadata.ticker);
1578
- if (at >= 0) changed[at] = row;
1579
- else changed.push(row);
1580
- }
1581
- for (const kept of merged.keptCustom) log.info("sync.suffixed-listing.custom-kept", kept);
1582
- const next = moveTargetWeights(config, merged.moved);
1583
- return { config: next === config ? null : next };
1584
- }
2
+ import { collectCoreCollectionsPayload, coreCollectionsSyncContributor } from "./collections-contributor";
3
+ import { coreConfigSyncContributor } from "./config-contributor";
4
+ import { collectCoreConfigPayload, mergeConfigPayload } from "./config-merge";
5
+ import { layoutIntent } from "./layout-merge";
6
+ import { sanitizeUnknown } from "./sanitize";
7
+
8
+ export { coreCollectionsSyncContributor } from "./collections-contributor";
9
+ export { coreConfigSyncContributor } from "./config-contributor";
1585
10
 
1586
11
  export function createCoreSyncContributors(): SyncContributor[] {
1587
12
  return [coreConfigSyncContributor, coreCollectionsSyncContributor];