@gloom-sh/terminal 0.20.9 → 0.20.11

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 (212) hide show
  1. package/package.json +1 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
  3. package/src/api-client/auth.ts +6 -0
  4. package/src/api-client/data.ts +1 -0
  5. package/src/api-client/earnings.ts +15 -0
  6. package/src/api-client/index.ts +14 -3
  7. package/src/api-client/socket-connection.ts +355 -0
  8. package/src/api-client/socket-features.ts +75 -0
  9. package/src/api-client/socket-frames.ts +161 -0
  10. package/src/api-client/socket-listeners.ts +207 -0
  11. package/src/api-client/socket-quotes.ts +332 -0
  12. package/src/api-client/socket.ts +150 -983
  13. package/src/api-client/types/account.ts +10 -0
  14. package/src/api-client/types/billing.ts +10 -0
  15. package/src/api-client/types/econ.ts +19 -7
  16. package/src/api-client/types/market.ts +7 -0
  17. package/src/api-client/types/screener.ts +2 -0
  18. package/src/brokers/signed-in/adapter.ts +19 -5
  19. package/src/brokers/signed-in/client.ts +13 -1
  20. package/src/brokers/signed-in/sign-in-dialog.tsx +33 -9
  21. package/src/cli/commands/market.ts +18 -8
  22. package/src/cli/commands/overview.ts +26 -7
  23. package/src/cli/commands/ticker.ts +40 -15
  24. package/src/cli/desktop-pane-shot.ts +39 -0
  25. package/src/cli/errors.ts +20 -3
  26. package/src/cli/fx-pair.ts +11 -2
  27. package/src/cli/history-rows.ts +34 -3
  28. package/src/cli/index.ts +1 -1
  29. package/src/cli/listing-arg.ts +51 -13
  30. package/src/cli/pane-functions/headless.ts +4 -2
  31. package/src/cli/pane-functions/index.ts +1 -0
  32. package/src/cli/pane-functions/resolver.ts +2 -1
  33. package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
  34. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  35. package/src/components/chart/composite/chart-layout.ts +7 -4
  36. package/src/components/chart/composite/composite-chart.tsx +6 -16
  37. package/src/components/chart/composite/toolbar.tsx +258 -82
  38. package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
  39. package/src/components/chart/native/kitty/manager.ts +2 -0
  40. package/src/components/chart/native/surface/manager.ts +211 -11
  41. package/src/components/command-bar/list/model.ts +13 -0
  42. package/src/components/command-bar/panel/index.tsx +2 -13
  43. package/src/components/command-bar/panel/layout.ts +1 -7
  44. package/src/components/command-bar/panel/runtime.ts +0 -1
  45. package/src/components/command-bar/panel/types.ts +0 -2
  46. package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
  47. package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
  48. package/src/components/command-bar/surface/index.tsx +10 -5
  49. package/src/components/command-bar/workflow/alert.ts +21 -7
  50. package/src/components/data-table/column-menu.tsx +89 -0
  51. package/src/components/data-table/sort-menu.tsx +9 -2
  52. package/src/components/data-table/table-pane.ts +3 -1
  53. package/src/components/data-table/view.tsx +33 -6
  54. package/src/components/form-modal/content.tsx +10 -0
  55. package/src/components/index.ts +1 -1
  56. package/src/components/layout/pane/footer/index.tsx +25 -11
  57. package/src/components/layout/pane/footer/model.ts +88 -21
  58. package/src/components/layout/pane/sidebar.tsx +125 -15
  59. package/src/components/layout/shell/active-drag.ts +18 -13
  60. package/src/components/layout/shell/drag/magnets.ts +34 -18
  61. package/src/components/metric-treemap/heat-surface.tsx +2 -1
  62. package/src/components/metric-treemap/index.tsx +3 -2
  63. package/src/components/ticker/list-table-view.tsx +5 -0
  64. package/src/components/ui/confirm-dialog.tsx +253 -7
  65. package/src/components/ui/data-table/column-order.ts +180 -0
  66. package/src/components/ui/data-table/index.tsx +13 -2
  67. package/src/components/ui/data-table/opentui/index.tsx +267 -23
  68. package/src/components/ui/data-table/opentui/model.ts +43 -4
  69. package/src/components/ui/data-table/types.ts +56 -0
  70. package/src/components/ui/data-table/use-column-order.ts +135 -0
  71. package/src/components/ui/index.ts +1 -1
  72. package/src/components/ui/list-view.tsx +4 -3
  73. package/src/components/ui/status.tsx +9 -6
  74. package/src/components/ui/table-layout.ts +120 -0
  75. package/src/docs/snapshot.json +39 -2
  76. package/src/i18n/es.ts +14 -0
  77. package/src/i18n/ja.ts +14 -0
  78. package/src/i18n/ko.ts +14 -0
  79. package/src/i18n/zh-cn.ts +14 -0
  80. package/src/i18n/zh-tw.ts +14 -0
  81. package/src/market-data/coordinator/index.ts +4 -3
  82. package/src/market-data/coordinator/quotes.ts +12 -4
  83. package/src/market-data/fx-closes.ts +14 -2
  84. package/src/market-data/market/change-basis.ts +35 -1
  85. package/src/market-data/market/status.ts +37 -0
  86. package/src/market-data/performance.ts +4 -1
  87. package/src/market-data/quotes/freshness.ts +12 -0
  88. package/src/market-data/quotes/live-valuation.ts +26 -3
  89. package/src/market-data/quotes/regular-session-valuation.ts +1 -1
  90. package/src/market-data/realized-volatility.ts +3 -0
  91. package/src/market-data/us-bond-market.ts +115 -0
  92. package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
  93. package/src/plugins/builtin/account-management/keyboard.ts +3 -0
  94. package/src/plugins/builtin/account-management/model.ts +1 -0
  95. package/src/plugins/builtin/account-management/pane.tsx +51 -5
  96. package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
  97. package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
  98. package/src/plugins/builtin/broker-manager/index.tsx +6 -6
  99. package/src/plugins/builtin/broker-manager/model.ts +15 -6
  100. package/src/plugins/builtin/broker-manager/pane-actions.tsx +11 -4
  101. package/src/plugins/builtin/broker-manager/sign-in-end.ts +50 -19
  102. package/src/plugins/builtin/broker-manager/table.ts +10 -4
  103. package/src/plugins/builtin/chat/sidebar.tsx +33 -16
  104. package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
  105. package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
  106. package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
  107. package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
  108. package/src/plugins/builtin/correlation/compute.ts +4 -3
  109. package/src/plugins/builtin/earnings/board-model.ts +33 -0
  110. package/src/plugins/builtin/earnings/board-table.ts +50 -11
  111. package/src/plugins/builtin/earnings/board.tsx +29 -13
  112. package/src/plugins/builtin/earnings/calendar.tsx +15 -3
  113. package/src/plugins/builtin/earnings/client.ts +4 -1
  114. package/src/plugins/builtin/earnings/headless.ts +27 -14
  115. package/src/plugins/builtin/econ/calendar-source.ts +3 -0
  116. package/src/plugins/builtin/equity-screener/live.ts +74 -18
  117. package/src/plugins/builtin/equity-screener/model.ts +19 -4
  118. package/src/plugins/builtin/equity-screener/pane.tsx +19 -14
  119. package/src/plugins/builtin/equity-screener/refresh-anchor.ts +45 -0
  120. package/src/plugins/builtin/equity-screener/results.ts +22 -2
  121. package/src/plugins/builtin/equity-screener/screen-check.ts +9 -3
  122. package/src/plugins/builtin/futures/index.tsx +15 -1
  123. package/src/plugins/builtin/futures/table.tsx +1 -1
  124. package/src/plugins/builtin/fx-matrix/index.tsx +2 -0
  125. package/src/plugins/builtin/help/index.tsx +1 -1
  126. package/src/plugins/builtin/holders/pane.tsx +30 -20
  127. package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
  128. package/src/plugins/builtin/iv-history/events.ts +5 -0
  129. package/src/plugins/builtin/iv-history/headless.ts +19 -12
  130. package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
  131. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  132. package/src/plugins/builtin/macro-day/model.ts +17 -4
  133. package/src/plugins/builtin/macro-day/releases.ts +36 -15
  134. package/src/plugins/builtin/market-halts/model.ts +3 -2
  135. package/src/plugins/builtin/market-movers/headless.ts +2 -1
  136. package/src/plugins/builtin/market-movers/index.tsx +3 -2
  137. package/src/plugins/builtin/market-movers/model.ts +75 -22
  138. package/src/plugins/builtin/market-movers/screener.ts +2 -1
  139. package/src/plugins/builtin/market-movers/table.ts +7 -5
  140. package/src/plugins/builtin/options/view.tsx +2 -0
  141. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  142. package/src/plugins/builtin/pe-band/model.ts +4 -0
  143. package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
  144. package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
  145. package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
  146. package/src/plugins/builtin/portfolio-list/pane/index.tsx +15 -1
  147. package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
  148. package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
  149. package/src/plugins/builtin/portfolio-list/table.tsx +18 -1
  150. package/src/plugins/builtin/rate-path/pane.tsx +2 -0
  151. package/src/plugins/builtin/research/analyst-headless.ts +9 -1
  152. package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
  153. package/src/plugins/builtin/research/client.ts +25 -1
  154. package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
  155. package/src/plugins/builtin/research/event-model.ts +3 -13
  156. package/src/plugins/builtin/research/event-sources.ts +3 -1
  157. package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
  158. package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
  159. package/src/plugins/builtin/seasonality/pane.tsx +2 -1
  160. package/src/plugins/builtin/short-interest/headless.ts +2 -0
  161. package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
  162. package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
  163. package/src/plugins/builtin/thirteenf/pane.tsx +2 -0
  164. package/src/plugins/builtin/ticker-detail/financials/model.ts +28 -6
  165. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +26 -9
  166. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +58 -35
  167. package/src/plugins/builtin/vol-surface/heat-grid.tsx +2 -1
  168. package/src/plugins/builtin/vol-surface/pane.tsx +2 -1
  169. package/src/plugins/builtin/world-indices/index.tsx +5 -1
  170. package/src/plugins/builtin/yield-curve/headless.ts +5 -1
  171. package/src/plugins/builtin/yield-curve/index.tsx +7 -1
  172. package/src/portfolio/column-values.ts +47 -14
  173. package/src/portfolio/return-metrics.ts +4 -2
  174. package/src/renderers/dom/data-table/column-drag.ts +147 -0
  175. package/src/renderers/dom/data-table/index.tsx +22 -0
  176. package/src/renderers/dom/data-table/row.tsx +27 -5
  177. package/src/renderers/dom/host/image-surface.tsx +19 -9
  178. package/src/renderers/dom/host/input.tsx +4 -0
  179. package/src/renderers/dom/styles.css +22 -0
  180. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
  181. package/src/renderers/opentui/chart-surface.tsx +1 -0
  182. package/src/renderers/opentui/frame-hits.ts +33 -0
  183. package/src/renderers/opentui/host.tsx +2 -0
  184. package/src/renderers/opentui/native-surface.ts +14 -21
  185. package/src/renderers/opentui/test-utils.tsx +3 -0
  186. package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
  187. package/src/sources/provider-errors.ts +12 -0
  188. package/src/sources/provider-router/index.ts +12 -4
  189. package/src/state/app/context/index.tsx +22 -0
  190. package/src/state/pane-session.ts +145 -0
  191. package/src/test-support/app-store.ts +24 -1
  192. package/src/tickers/search/home-listing.ts +44 -1
  193. package/src/tickers/search/index.ts +5 -2
  194. package/src/tickers/search/ranking.ts +7 -7
  195. package/src/tickers/us-listing.ts +11 -5
  196. package/src/time-series/base-series.ts +7 -1
  197. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  198. package/src/time-series/fundamentals/series.ts +6 -0
  199. package/src/time-series/live-quotes.ts +3 -9
  200. package/src/time-series/resolve.ts +1 -0
  201. package/src/types/financials.ts +20 -0
  202. package/src/types/headless.ts +9 -0
  203. package/src/ui/host.tsx +20 -0
  204. package/src/ui/pointer-drag.ts +11 -2
  205. package/src/utils/exchanges.ts +13 -8
  206. package/src/utils/fundamentals.ts +14 -3
  207. package/src/utils/price-earnings.ts +17 -10
  208. package/src/utils/price-history-integrity.ts +15 -0
  209. package/src/utils/reason-codes.ts +79 -0
  210. package/src/utils/share-multiples.cases.json +1667 -0
  211. package/src/utils/share-multiples.ts +384 -0
  212. package/src/utils/untrusted-text.ts +11 -0
@@ -0,0 +1,94 @@
1
+ import { apiClient } from "../../../../api-client";
2
+ import type { RemoteControlHandler } from "../../../../remote/app-host";
3
+ import type { AppState } from "../../../../state/app/context";
4
+ import type { AppConfig } from "../../../../types/config";
5
+ import { getCurrentPluginTarget } from "../../../current-target";
6
+ import { ASKGSessionController, type ASKGControllerManifest } from "./controller";
7
+ import { createASKGRendererToolExecutor, loadASKGClientManifest } from "./host";
8
+ import { attachedPaneContext, type ASKGAttachedPane } from "./pane-attachment";
9
+ import { ASKGUndoManager } from "./undo";
10
+ import { buildASKGUserData } from "./user-data";
11
+
12
+ const CLIENT_VERSION = "1";
13
+
14
+ function clientKind(): "tui" | "desktop" | "web" {
15
+ const target = getCurrentPluginTarget();
16
+ return target === "web" || target === "desktop" ? target : "tui";
17
+ }
18
+
19
+ /** What the pane that is mounted now gives the session; the pane writes it on every render. */
20
+ export interface ASKGPaneBindings {
21
+ config: AppConfig;
22
+ remoteHandler: RemoteControlHandler | null;
23
+ getAppState: () => AppState;
24
+ /** The ticker open beside the pane and the pane's own id, read when a question is sent. */
25
+ context: { symbol: string | null; paneId: string };
26
+ }
27
+
28
+ /**
29
+ * The conversation an Ask Gloom pane is in: the transcript on screen and the
30
+ * answer still coming in. It belongs to the pane, not to one drawing of it, so
31
+ * docking, floating or stacking the pane picks it up where it was instead of
32
+ * mounting an empty conversation and fetching the last one back.
33
+ */
34
+ export interface ASKGPaneSession {
35
+ controller: ASKGSessionController;
36
+ bindings: ASKGPaneBindings;
37
+ /** The pane the conversation on screen is about, read whenever a question goes. */
38
+ attached: { current: ASKGAttachedPane | null };
39
+ /** Whether this pane has already looked for the conversation it showed before. */
40
+ restored: boolean;
41
+ }
42
+
43
+ export function createASKGPaneSession(initial: ASKGPaneBindings): ASKGPaneSession {
44
+ const bindings = { ...initial };
45
+ const attached: ASKGPaneSession["attached"] = { current: null };
46
+ // Each call and each undo gets a fresh executor, so the tokens live here:
47
+ // an executor's own manager would forget them as soon as its call returned.
48
+ const undoManager = new ASKGUndoManager((request) => {
49
+ const handler = bindings.remoteHandler;
50
+ if (!handler) return Promise.reject(new Error("This window cannot undo tool calls."));
51
+ return handler(request);
52
+ });
53
+ const controller = new ASKGSessionController({
54
+ transport: apiClient.askg,
55
+ loadManifest: () => loadASKGClientManifest(),
56
+ getExecutor: (manifest: ASKGControllerManifest) => {
57
+ const handler = bindings.remoteHandler;
58
+ if (!handler) return null;
59
+ return createASKGRendererToolExecutor({
60
+ config: bindings.config,
61
+ remoteHandler: handler,
62
+ manifest: {
63
+ tools: manifest.tools,
64
+ manifestHash: manifest.manifestHash,
65
+ skipped: [],
66
+ },
67
+ undoManager,
68
+ });
69
+ },
70
+ client: { kind: clientKind(), version: CLIENT_VERSION },
71
+ getContext: () => {
72
+ const state = bindings.getAppState();
73
+ const userData = buildASKGUserData({
74
+ config: state.config,
75
+ brokerAccounts: state.brokerAccounts,
76
+ tickers: state.tickers.values(),
77
+ });
78
+ const pane = attached.current;
79
+ // An attached pane is what the question is about: its function, its
80
+ // symbol and, once that may go, what it shows.
81
+ if (pane) return { ...attachedPaneContext(pane), ...(userData ? { userData } : {}) };
82
+ return {
83
+ ...(bindings.context.symbol ? { symbol: bindings.context.symbol } : {}),
84
+ paneId: bindings.context.paneId,
85
+ ...(userData ? { userData } : {}),
86
+ };
87
+ },
88
+ });
89
+ return { controller, bindings, attached, restored: false };
90
+ }
91
+
92
+ export function disposeASKGPaneSession(session: ASKGPaneSession): void {
93
+ session.controller.dispose();
94
+ }
@@ -1,5 +1,4 @@
1
1
  import { CLOUD_PLAN_KEY } from "../../shared/cloud-upgrade";
2
- import { getCurrentPluginTarget } from "../../../current-target";
3
2
  import {
4
3
  useCallback,
5
4
  useEffect,
@@ -44,6 +43,7 @@ import {
44
43
  useAppSelector,
45
44
  usePaneAppConfig,
46
45
  } from "../../../../state/app/context";
46
+ import { usePaneSession, usePaneSessionState } from "../../../../state/pane-session";
47
47
  import { useInlineTickers } from "../../../../state/hooks/inline-tickers";
48
48
  import { useRemoteControlHandler } from "../../../../remote/app-host";
49
49
  import { RemoteUiScope } from "../../../../remote/semantic-tree";
@@ -62,14 +62,12 @@ import { usePlanAccess } from "../../../../api-client/plan-access";
62
62
  import { SignInWall } from "../auth-actions";
63
63
  import { afterLayout, revealInScrollBox } from "../../../../components/ui/reveal-in-scroll-box";
64
64
  import { describePortfolioTab } from "../../analytics/portfolio-selection";
65
- import { ASKGSessionController, type ASKGControllerManifest } from "./controller";
66
65
  import {
67
- createASKGRendererToolExecutor,
68
66
  buildASKGSourceShare,
69
67
  type ASKGSourceShare,
70
- loadASKGClientManifest,
71
68
  resolveToolPaneTarget,
72
69
  } from "./host";
70
+ import { createASKGPaneSession, disposeASKGPaneSession } from "./pane-session";
73
71
  import { getSharedRegistry } from "../../../registry";
74
72
  import {
75
73
  answerReadNothing,
@@ -102,7 +100,6 @@ import type { AskGloomPaneAttachment } from "../../../../ask-gloom/pane-request"
102
100
  import { moveComposerCursorToOffset } from "../../chat/content/composer-cursor";
103
101
  import {
104
102
  ASKG_PANE_QUESTION,
105
- attachedPaneContext,
106
103
  attachPane,
107
104
  type ASKGAttachedPane,
108
105
  } from "./pane-attachment";
@@ -112,9 +109,7 @@ import {
112
109
  attachedPaneBlockHeight,
113
110
  LEAVE_OUT_PANE_KEY,
114
111
  } from "./attached-pane";
115
- import { buildASKGUserData } from "./user-data";
116
112
  import { ASKGConversationSidebar } from "./sidebar";
117
- import { ASKGUndoManager } from "./undo";
118
113
  import {
119
114
  activeTurn,
120
115
  canRateTurn,
@@ -146,7 +141,6 @@ import { logFailure } from "../../../../utils/log-failure";
146
141
 
147
142
  export const ASKG_PANE_ID = "askg";
148
143
 
149
- const CLIENT_VERSION = "1";
150
144
  const MIN_DETAIL_HEIGHT = 8;
151
145
  /** The composer grows with the question up to this many lines, then scrolls. */
152
146
  const MAX_COMPOSER_LINES = 6;
@@ -155,11 +149,6 @@ const LOW_QUOTA = 20;
155
149
  /** What unlocks Ask Gloom: a free account with a verified email; a paid plan only changes the model. */
156
150
  const ASKG_WALL_HINT = "Free with a verified Gloom account.";
157
151
 
158
- function clientKind(): "tui" | "desktop" | "web" {
159
- const target = getCurrentPluginTarget();
160
- return target === "web" || target === "desktop" ? target : "tui";
161
- }
162
-
163
152
  function tierLabel(row: ASKGToolRow): string | null {
164
153
  if (row.writeTier === "read") return null;
165
154
  if (row.writeTier === "ui-write") return "layout";
@@ -611,72 +600,37 @@ export function ASKGPane({ paneId, focused, width, height }: PaneProps) {
611
600
  const dialog = useDialog();
612
601
  const rendererHost = useRendererHost();
613
602
 
614
- const configRef = useRef(config);
615
- configRef.current = config;
616
- const remoteHandlerRef = useRef(remoteHandler);
617
- remoteHandlerRef.current = remoteHandler;
618
- const contextRef = useRef({ symbol: activeSymbol, paneId });
619
- contextRef.current = { symbol: activeSymbol, paneId };
620
603
  // Read when a question is sent, so portfolio and ticker changes do not re-render the pane.
621
604
  const getAppState = useAppGetState();
622
- const getAppStateRef = useRef(getAppState);
623
- getAppStateRef.current = getAppState;
605
+
606
+ // The conversation belongs to the pane, not to this drawing of it: docking
607
+ // or floating the pane mounts it again, and it picks the conversation up
608
+ // where it was (see `usePaneSession`).
609
+ const session = usePaneSession(
610
+ "askg:conversation",
611
+ () => createASKGPaneSession({
612
+ config,
613
+ remoteHandler,
614
+ getAppState,
615
+ context: { symbol: activeSymbol, paneId },
616
+ }),
617
+ disposeASKGPaneSession,
618
+ paneId,
619
+ );
620
+ const { controller } = session;
621
+ session.bindings.config = config;
622
+ session.bindings.remoteHandler = remoteHandler;
623
+ session.bindings.getAppState = getAppState;
624
+ session.bindings.context = { symbol: activeSymbol, paneId };
624
625
 
625
626
  // The pane the conversation on screen is about, read whenever a question
626
627
  // goes so every turn of it carries the pane.
627
- const [attached, setAttachedState] = useState<ASKGAttachedPane | null>(null);
628
- const attachedRef = useRef<ASKGAttachedPane | null>(null);
628
+ const [attached, setAttachedState] = usePaneSessionState<ASKGAttachedPane | null>("askg:attached", null, paneId);
629
+ const attachedRef = session.attached;
629
630
  const setAttached = useCallback((next: ASKGAttachedPane | null) => {
630
631
  attachedRef.current = next;
631
632
  setAttachedState(next);
632
- }, []);
633
-
634
- // Each call and each undo gets a fresh executor, so the tokens live here:
635
- // an executor's own manager would forget them as soon as its call returned.
636
- const undoManager = useMemo(() => new ASKGUndoManager((request) => {
637
- const handler = remoteHandlerRef.current;
638
- if (!handler) return Promise.reject(new Error("This window cannot undo tool calls."));
639
- return handler(request);
640
- }), []);
641
-
642
- const controller = useMemo(() => new ASKGSessionController({
643
- transport: apiClient.askg,
644
- loadManifest: () => loadASKGClientManifest(),
645
- getExecutor: (manifest: ASKGControllerManifest) => {
646
- const handler = remoteHandlerRef.current;
647
- if (!handler) return null;
648
- return createASKGRendererToolExecutor({
649
- config: configRef.current,
650
- remoteHandler: handler,
651
- manifest: {
652
- tools: manifest.tools,
653
- manifestHash: manifest.manifestHash,
654
- skipped: [],
655
- },
656
- undoManager,
657
- });
658
- },
659
- client: { kind: clientKind(), version: CLIENT_VERSION },
660
- getContext: () => {
661
- const state = getAppStateRef.current();
662
- const userData = buildASKGUserData({
663
- config: state.config,
664
- brokerAccounts: state.brokerAccounts,
665
- tickers: state.tickers.values(),
666
- });
667
- const pane = attachedRef.current;
668
- // An attached pane is what the question is about: its function, its
669
- // symbol and, once that may go, what it shows.
670
- if (pane) return { ...attachedPaneContext(pane), ...(userData ? { userData } : {}) };
671
- return {
672
- ...(contextRef.current.symbol ? { symbol: contextRef.current.symbol } : {}),
673
- paneId: contextRef.current.paneId,
674
- ...(userData ? { userData } : {}),
675
- };
676
- },
677
- }), [undoManager]);
678
-
679
- useEffect(() => () => controller.dispose(), [controller]);
633
+ }, [attachedRef, setAttachedState]);
680
634
 
681
635
  const state: ASKGConversationState = useSyncExternalStore(
682
636
  useCallback((listener) => controller.subscribe(listener), [controller]),
@@ -684,14 +638,16 @@ export function ASKGPane({ paneId, focused, width, height }: PaneProps) {
684
638
  useCallback(() => controller.getState(), [controller]),
685
639
  );
686
640
 
687
- const [inputValue, setInputValue] = useState("");
641
+ // What is in the composer and which row of the conversation the keyboard is
642
+ // on go with the conversation, so a dock change leaves them where they were.
643
+ const [inputValue, setInputValue] = usePaneSessionState("askg:draft", "", paneId);
688
644
  const [inputFocused, setInputFocused] = useState(false);
689
645
  // A tool row or a turn's folded calls; j/k walk them.
690
- const [selectedId, setSelectedId] = useState<string | null>(null);
691
- const [expandedToolCallId, setExpandedToolCallId] = useState<string | null>(null);
692
- const [openGroups, setOpenGroups] = useState<ReadonlySet<string>>(() => new Set());
646
+ const [selectedId, setSelectedId] = usePaneSessionState<string | null>("askg:selected", null, paneId);
647
+ const [expandedToolCallId, setExpandedToolCallId] = usePaneSessionState<string | null>("askg:expanded", null, paneId);
648
+ const [openGroups, setOpenGroups] = usePaneSessionState<ReadonlySet<string>>("askg:open-groups", () => new Set(), paneId);
693
649
  // The answer whose thumbs down shows its reasons and the send action.
694
- const [feedbackFollowUpTurnId, setFeedbackFollowUpTurnId] = useState<string | null>(null);
650
+ const [feedbackFollowUpTurnId, setFeedbackFollowUpTurnId] = usePaneSessionState<string | null>("askg:feedback-follow-up", null, paneId);
695
651
  // The example question the keyboard is on while the pane is empty.
696
652
  const [exampleIndex, setExampleIndex] = useState<number | null>(null);
697
653
  const inputRef = useRef<TextareaRenderable | null>(null);
@@ -793,7 +749,7 @@ export function ASKGPane({ paneId, focused, width, height }: PaneProps) {
793
749
  }, [state]);
794
750
 
795
751
  const profileExamples = useMemo(() => {
796
- const appState = getAppStateRef.current();
752
+ const appState = getAppState();
797
753
  return askgExampleQuestions({
798
754
  config: appState.config,
799
755
  tickers: appState.tickers.values(),
@@ -1019,10 +975,11 @@ export function ASKGPane({ paneId, focused, width, height }: PaneProps) {
1019
975
  // Closing the pane is two Escs away, so the conversation it showed comes
1020
976
  // back with the next one this session opens. A question typed with the
1021
977
  // command that opened it starts a new one instead.
1022
- const restoredRef = useRef(false);
1023
978
  useEffect(() => {
1024
- if (restoredRef.current || !planAccess.emailVerified) return;
1025
- restoredRef.current = true;
979
+ // Once per pane: a pane that comes back from a dock change has its
980
+ // conversation already, and one that was started empty stays empty.
981
+ if (session.restored || !planAccess.emailVerified) return;
982
+ session.restored = true;
1026
983
  const remembered = askgConversationListStore.rememberedOpen();
1027
984
  if (!remembered || queuedQuestionRef.current || queuedPaneRef.current || controller.getState().turns.length > 0) return;
1028
985
  void apiClient.askg.loadConversation(remembered).then((conversation) => {
@@ -1031,7 +988,7 @@ export function ASKGPane({ paneId, focused, width, height }: PaneProps) {
1031
988
  if (!conversation || current.turns.length > 0 || current.conversationId || attachedRef.current || queuedPaneRef.current) return;
1032
989
  controller.openConversation(conversation);
1033
990
  }).catch(logFailure("cloud.askg.pane", "Restore the last open conversation failed"));
1034
- }, [controller, planAccess.emailVerified]);
991
+ }, [attachedRef, controller, planAccess.emailVerified, session]);
1035
992
 
1036
993
  useEffect(() => {
1037
994
  if (state.conversationId) askgConversationListStore.rememberOpen(state.conversationId);
@@ -1162,7 +1119,7 @@ export function ASKGPane({ paneId, focused, width, height }: PaneProps) {
1162
1119
  if (target.kind !== "pane") return;
1163
1120
  const failed = (reason: string) => notify({ body: `Could not open ${formatSourceCommand(target.command)}: ${reason}`, type: "error" });
1164
1121
  try {
1165
- const share = await buildASKGSourceShare(target.command, configRef.current);
1122
+ const share = await buildASKGSourceShare(target.command, session.bindings.config);
1166
1123
  openSharedPane(share.data, () => failed("panes cannot open from here."));
1167
1124
  } catch (error) {
1168
1125
  failed(error instanceof Error ? error.message : String(error));
@@ -1350,7 +1307,7 @@ export function ASKGPane({ paneId, focused, width, height }: PaneProps) {
1350
1307
  if (source.target.kind !== "pane") continue;
1351
1308
  const key = formatSourceCommand(source.target.command);
1352
1309
  if (links.has(key) || pending.some((entry) => entry.key === key)) continue;
1353
- const share = await buildASKGSourceShare(source.target.command, configRef.current).catch((error: unknown) => {
1310
+ const share = await buildASKGSourceShare(source.target.command, session.bindings.config).catch((error: unknown) => {
1354
1311
  logFailure("cloud.askg.pane", "An answer source could not be shared")(error);
1355
1312
  return null;
1356
1313
  });
@@ -386,6 +386,8 @@ export function ToolResultDetail({
386
386
  rootWidth={width}
387
387
  rootHeight={Math.max(3, height - headerHeight)}
388
388
  columns={columns}
389
+ // A tool's answer, read once: its columns are the tool's, not a layout to keep with the pane.
390
+ columnReorder={false}
389
391
  items={table.rows}
390
392
  sortColumnId={null}
391
393
  sortDirection="asc"
@@ -263,7 +263,12 @@ export function CongressTradesPane({ focused, width, height, tickerFilter }: Pan
263
263
 
264
264
  const openTicker = useInlineTickerOpener();
265
265
 
266
+ // The rows come in after the pane mounts, every time it mounts (docking or
267
+ // floating it mounts it again), so no rows yet says nothing about which row
268
+ // was selected. Only a loaded table with no such row moves the selection.
269
+ const rowsLoaded = !!payload && status === "loaded";
266
270
  useEffect(() => {
271
+ if (!rowsLoaded) return;
267
272
  if (tradeRows.length === 0) {
268
273
  if (selectedTradeId !== null) setSelectedTradeId(null);
269
274
  return;
@@ -271,9 +276,10 @@ export function CongressTradesPane({ focused, width, height, tickerFilter }: Pan
271
276
  if (!selectedTrade || !selectedTradeId) {
272
277
  setSelectedTradeId(tradeRows[0]!.id);
273
278
  }
274
- }, [selectedTrade, selectedTradeId, setSelectedTradeId, tradeRows]);
279
+ }, [rowsLoaded, selectedTrade, selectedTradeId, setSelectedTradeId, tradeRows]);
275
280
 
276
281
  useEffect(() => {
282
+ if (!rowsLoaded) return;
277
283
  if (memberRows.length === 0) {
278
284
  if (selectedMemberId !== null) setSelectedMemberId(null);
279
285
  return;
@@ -281,7 +287,7 @@ export function CongressTradesPane({ focused, width, height, tickerFilter }: Pan
281
287
  if (!selectedMember || !selectedMemberId) {
282
288
  setSelectedMemberId(memberRows[0]!.id);
283
289
  }
284
- }, [memberRows, selectedMember, selectedMemberId, setSelectedMemberId]);
290
+ }, [memberRows, rowsLoaded, selectedMember, selectedMemberId, setSelectedMemberId]);
285
291
 
286
292
  useEffect(() => {
287
293
  if (!payload || status !== "loaded") return;
@@ -1,6 +1,6 @@
1
1
  import type { PricePoint } from "../../../types/financials";
2
2
  import { getPricePointTimestamp } from "../../../utils/price-history";
3
- import { pricePointIntegrity } from "../../../utils/price-history-integrity";
3
+ import { pricePointCloseCopied, pricePointIntegrity } from "../../../utils/price-history-integrity";
4
4
 
5
5
  export interface CorrelationResult {
6
6
  correlation: number | null;
@@ -26,13 +26,14 @@ export type ChangeBasis = "return" | "difference";
26
26
  * Keep the final valid close for each UTC trading date, in chronological order.
27
27
  * A bar whose prices contradict each other (a high under its open) is left out,
28
28
  * as `history` leaves it blank: the series has a gap there, and the next return
29
- * runs from the close before it, as across a holiday.
29
+ * runs from the close before it, as across a holiday. So is a pair's close its
30
+ * source copied from the open, which nothing rebuilt (flag close copied).
30
31
  */
31
32
  export function dailyCloses(points: readonly PricePoint[]): DailyClose[] {
32
33
  const byDate = new Map<string, number>();
33
34
  for (const point of [...points].sort(comparePricePointsByDate)) {
34
35
  const dateKey = toDateKey(point);
35
- if (!dateKey || !Number.isFinite(point.close) || point.close <= 0 || pricePointIntegrity(point)) continue;
36
+ if (!dateKey || !Number.isFinite(point.close) || point.close <= 0 || pricePointIntegrity(point) || pricePointCloseCopied(point)) continue;
36
37
  byDate.set(dateKey, point.close);
37
38
  }
38
39
  return [...byDate].map(([dateKey, close]) => ({ dateKey, close }));
@@ -6,6 +6,9 @@ import type { EarningsDateStatus, EarningsEpsBasis, Quote } from "../../../types
6
6
  import type { TickerRecord } from "../../../types/ticker";
7
7
  import { earningsDateStatus, earningsEpsBasis, isProvisionalActual } from "../shared/earnings-report";
8
8
  import { calendarReport } from "../shared/earnings-calendar";
9
+ import { listingSuffixCandidate } from "../../../sources/listing-symbols";
10
+ import { isUsListingExchange } from "../../../utils/exchanges";
11
+ import { sameHistoryListing } from "./client";
9
12
  import { shortDate, surprise, weekday } from "./format";
10
13
 
11
14
  /** A held name is in a portfolio; a watched one only in watchlists. */
@@ -36,6 +39,14 @@ export interface BoardReport {
36
39
  impliedMove: number | null;
37
40
  averageMove: number | null;
38
41
  owned: Ownership | null;
42
+ /** ISO currency of the EPS and sales figures; null when the report has none. The market cap is always dollars. */
43
+ currency?: string | null;
44
+ /**
45
+ * A listing abroad's lines on its markets, the one shown first; on a US line
46
+ * the board shows instead of its listing abroad (BABA, the day 9988:HKEX
47
+ * reports too), that listing's. Absent for other US listings.
48
+ */
49
+ listings?: readonly string[];
39
50
  }
40
51
 
41
52
  export type BoardRow =
@@ -145,9 +156,30 @@ export function boardReport(report: EarningsCalendarReport, owned: ReadonlyMap<s
145
156
  impliedMove: report.implied?.move ?? null,
146
157
  averageMove: report.averageReports >= MIN_AVERAGE_REPORTS ? report.averageMove : null,
147
158
  owned: owned.get(report.symbol) ?? null,
159
+ // The board's US reports are in dollars; a listing abroad's say their own.
160
+ currency: report.currency ?? "USD",
161
+ ...report.listings?.length ? { listings: report.listings } : {},
148
162
  };
149
163
  }
150
164
 
165
+ /** A listing as the board keys it: 0700.HK, as typed where its quote could not be read, is 0700:HKEX. */
166
+ export function boardKey(symbol: string): string {
167
+ const suffixed = listingSuffixCandidate(symbol);
168
+ return (suffixed ? `${suffixed.symbol}:${suffixed.exchange}` : symbol).toUpperCase();
169
+ }
170
+
171
+ /**
172
+ * Whether a board row is the listing named: its own line, or another of its
173
+ * company's (0939:HKEX for 601939:SSE, 9988:HKEX for BABA the day both report).
174
+ */
175
+ export function boardRowOf(entry: Pick<BoardReport, "symbol" | "listings">, named: string): boolean {
176
+ const symbol = boardKey(named);
177
+ const [bare = symbol, venue] = symbol.split(":");
178
+ // A US ticker is a US row's bare symbol, never a listing abroad's.
179
+ if (!venue || isUsListingExchange(venue)) return !entry.symbol.includes(":") && entry.symbol.toUpperCase() === bare;
180
+ return [entry.symbol, ...entry.listings ?? []].some((line) => sameHistoryListing(line, symbol));
181
+ }
182
+
151
183
  /**
152
184
  * A company the stored calendar does not carry (a listing abroad, a date past
153
185
  * its horizon) from the per-ticker calendar, read as every earnings surface
@@ -182,6 +214,7 @@ export function fallbackReport(event: EarningsEvent, owned: ReadonlyMap<string,
182
214
  impliedMove: null,
183
215
  averageMove: null,
184
216
  owned: owned.get(event.symbol) ?? null,
217
+ currency: epsEstimate != null || dollars("revenueEstimate") != null ? "USD" : null,
185
218
  };
186
219
  }
187
220
 
@@ -1,6 +1,6 @@
1
1
  import type { DataTableCell, DataTableColumn } from "../../../components";
2
2
  import { withCompanyLogo } from "../../../components/company-logo";
3
- import { TABLE_COLUMN_GAP, tableColumnWidth } from "../../../components/ui/table-layout";
3
+ import { TABLE_COLUMN_GAP, tableColumnLeadGap, tableColumnWidth } from "../../../components/ui/table-layout";
4
4
  import { colors } from "../../../theme/colors";
5
5
  import { TextAttributes } from "../../../ui";
6
6
  import { epsBasisShort, showsEpsBasis } from "../shared/earnings-report";
@@ -8,27 +8,33 @@ import type { BoardReport, BoardRow, BoardSort } from "./board-model";
8
8
  import { epsText, impliedText, moneyText, moveSize, signedPercent, TIMING_LABEL, weekday } from "./format";
9
9
 
10
10
  type BoardColumnId =
11
- | "owned" | "symbol" | "name" | "when" | "status" | "cap" | "epsEstimate" | "analysts" | "epsActual" | "basis"
11
+ | "owned" | "symbol" | "name" | "when" | "status" | "cap" | "ccy" | "epsEstimate" | "analysts" | "epsActual" | "basis"
12
12
  | "epsSurprise" | "revenueEstimate" | "implied" | "move" | "average";
13
13
 
14
14
  export type BoardColumn = DataTableColumn & { id: BoardColumnId };
15
15
 
16
16
  const NAME_MIN_WIDTH = 12;
17
+ /** TICKER fits a US ticker; a listing abroad's key is longer (0700:HKEX, 601939:SSE, 000333:SZSE). */
18
+ const SYMBOL_WIDTH = 6;
19
+ const SYMBOL_MAX_WIDTH = 11;
17
20
 
18
21
  const ALL_COLUMNS: BoardColumn[] = [
19
22
  { id: "owned", label: "", width: 1, align: "left" },
20
- { id: "symbol", label: "TICKER", width: 6, align: "left" },
23
+ { id: "symbol", label: "TICKER", width: SYMBOL_WIDTH, align: "left" },
21
24
  { id: "name", label: "NAME", width: NAME_MIN_WIDTH, align: "left" },
22
25
  { id: "when", label: "WHEN", width: 7, align: "left" },
23
26
  { id: "status", label: "STATUS", width: 9, align: "left" },
24
27
  { id: "implied", label: "IMPLIED", width: 7, align: "right" },
25
- { id: "move", label: "MOVE", width: 7, align: "right" },
28
+ // The move, the actual EPS and its surprise come with the report: an upcoming one has none.
29
+ { id: "move", label: "MOVE", width: 7, align: "right", mayBeBlank: true },
26
30
  { id: "average", label: "AVG MOVE", width: 8, align: "right" },
31
+ // The currency of the EPS and sales figures, on a board with a listing abroad's (CNY for Tencent).
32
+ { id: "ccy", label: "CCY", width: 3, align: "left" },
27
33
  { id: "epsEstimate", label: "EPS EST", width: 7, align: "right" },
28
34
  { id: "analysts", label: "ESTS", width: 4, align: "right" },
29
- { id: "epsActual", label: "EPS ACT", width: 7, align: "right" },
35
+ { id: "epsActual", label: "EPS ACT", width: 7, align: "right", mayBeBlank: true },
30
36
  { id: "basis", label: "BASIS", width: 5, align: "left" },
31
- { id: "epsSurprise", label: "EPS SURP", width: 8, align: "right" },
37
+ { id: "epsSurprise", label: "EPS SURP", width: 8, align: "right", mayBeBlank: true },
32
38
  { id: "revenueEstimate", label: "SALES EST", width: 9, align: "right" },
33
39
  { id: "cap", label: "MKT CAP", width: 8, align: "right" },
34
40
  ];
@@ -36,8 +42,9 @@ const ALL_COLUMNS: BoardColumn[] = [
36
42
  /**
37
43
  * Dropped first when narrow, the report's labels before its figures; the
38
44
  * implied move, the move on the report and their average stay beside the name.
45
+ * CCY goes only with the last figure it is the currency of.
39
46
  */
40
- const DROP_ORDER: BoardColumnId[] = ["basis", "analysts", "epsSurprise", "status", "epsActual", "cap", "revenueEstimate", "epsEstimate", "owned"];
47
+ const DROP_ORDER: BoardColumnId[] = ["basis", "analysts", "epsSurprise", "status", "epsActual", "cap", "revenueEstimate", "epsEstimate", "ccy", "owned"];
41
48
 
42
49
  /**
43
50
  * With an actual on the board the report is the news: EPS ACT, then EPS SURP,
@@ -46,9 +53,12 @@ const DROP_ORDER: BoardColumnId[] = ["basis", "analysts", "epsSurprise", "status
46
53
  * goes. Without one, those two columns would be empty, so DROP_ORDER holds.
47
54
  */
48
55
  const REPORTED_DROP_ORDER: BoardColumnId[] = [
49
- "basis", "analysts", "status", "average", "cap", "revenueEstimate", "epsSurprise", "epsActual", "epsEstimate", "owned",
56
+ "basis", "analysts", "status", "average", "cap", "revenueEstimate", "epsSurprise", "epsActual", "epsEstimate", "ccy", "owned",
50
57
  ];
51
58
 
59
+ /** The columns in the report's currency, which CCY names. */
60
+ const CURRENCY_FIGURES: BoardColumnId[] = ["epsEstimate", "epsActual", "revenueEstimate"];
61
+
52
62
  /** Header clicks sort these; the rest keep the ranking. */
53
63
  export const SORTABLE: Partial<Record<BoardColumnId, BoardSort["column"]>> = {
54
64
  symbol: "symbol", cap: "cap", implied: "implied", average: "average",
@@ -59,14 +69,41 @@ export function boardHasActuals(rows: readonly BoardRow[]): boolean {
59
69
  return rows.some((row) => row.kind === "report" && row.report.epsActual != null);
60
70
  }
61
71
 
62
- export function boardColumns(width: number, { actuals = false }: { actuals?: boolean } = {}): BoardColumn[] {
72
+ /**
73
+ * Whether a report on the board is in another currency than dollars (a
74
+ * listing abroad's): the board then shows CCY, and says its market cap is in
75
+ * dollars (boardColumns). A board of US reports looks as it always has.
76
+ */
77
+ export function boardHasCurrencies(rows: readonly BoardRow[]): boolean {
78
+ return rows.some((row) => row.kind === "report" && row.report.currency != null && row.report.currency !== "USD");
79
+ }
80
+
81
+ /** TICKER's width for the board's symbols: a US ticker's, or wide enough for the longest listing abroad's key. */
82
+ export function boardSymbolWidth(rows: readonly BoardRow[]): number {
83
+ const longest = Math.max(0, ...rows.map((row) => (row.kind === "report" ? row.report.symbol.length : 0)));
84
+ return Math.min(SYMBOL_MAX_WIDTH, Math.max(SYMBOL_WIDTH, longest));
85
+ }
86
+
87
+ export function boardColumns(
88
+ width: number,
89
+ { actuals = false, currencies = false, symbolWidth = SYMBOL_WIDTH }: { actuals?: boolean; currencies?: boolean; symbolWidth?: number } = {},
90
+ ): BoardColumn[] {
91
+ // Every column but the name, with the space a left-aligned column keeps from a right-aligned one before it (CCY after
92
+ // AVG MOVE, BASIS after EPS ACT), so the last column is never cut at the pane's edge.
63
93
  const fixed = (list: BoardColumn[]) =>
64
- list.reduce((sum, column) => sum + (column.id === "name" ? 0 : tableColumnWidth(column)) + TABLE_COLUMN_GAP, 2);
65
- let columns = ALL_COLUMNS;
94
+ list.reduce((sum, column, index) =>
95
+ sum + tableColumnLeadGap(list, index, TABLE_COLUMN_GAP) + (column.id === "name" ? 0 : tableColumnWidth(column)) + TABLE_COLUMN_GAP, 2);
96
+ // Beside figures in yuan or Hong Kong dollars, the cap says it is in dollars.
97
+ let columns = (currencies ? ALL_COLUMNS : ALL_COLUMNS.filter((column) => column.id !== "ccy")).map((column) =>
98
+ column.id === "cap" && currencies ? { ...column, label: "MKT CAP $", width: 9 }
99
+ : column.id === "symbol" ? { ...column, width: symbolWidth }
100
+ : column);
66
101
  for (const id of actuals ? REPORTED_DROP_ORDER : DROP_ORDER) {
67
102
  if (fixed(columns) + NAME_MIN_WIDTH <= width) break;
68
103
  columns = columns.filter((column) => column.id !== id);
69
104
  }
105
+ // CCY is the currency of the figures beside it; with none left it goes too.
106
+ if (!columns.some((column) => CURRENCY_FIGURES.includes(column.id))) columns = columns.filter((column) => column.id !== "ccy");
70
107
  // The name takes what the other columns leave.
71
108
  const nameWidth = Math.max(NAME_MIN_WIDTH, width - fixed(columns));
72
109
  return columns.map((column) => (column.id === "name" ? { ...column, width: nameWidth } : column));
@@ -120,6 +157,8 @@ export function renderBoardCell(row: BoardRow, column: BoardColumn, context: Boa
120
157
  return { text: report.dateStatus ?? "--", color: report.dateStatus === "projected" ? colors.textMuted : dim };
121
158
  case "cap":
122
159
  return { text: moneyText(report.marketCap), color: dim };
160
+ case "ccy":
161
+ return { text: report.currency ?? "--", color: dim };
123
162
  case "epsEstimate":
124
163
  return { text: epsText(report.epsEstimate), color: dim };
125
164
  case "analysts":