@gloom-sh/terminal 0.20.22 → 0.20.23

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 (195) hide show
  1. package/package.json +1 -1
  2. package/src/account/heard-from-question.tsx +6 -4
  3. package/src/account/heard-from.ts +3 -4
  4. package/src/api-client/exchange-announcements.ts +2 -2
  5. package/src/api-client/heard-from.ts +5 -7
  6. package/src/api-client/ownership-disclosures.ts +38 -5
  7. package/src/api-client/types/ticker-data.ts +3 -1
  8. package/src/architecture/dom-cell-metrics-allowlist.json +2 -2
  9. package/src/cli/commands/market.ts +5 -3
  10. package/src/cli/commands/overview.ts +7 -9
  11. package/src/cli/listing-arg.ts +45 -18
  12. package/src/cli/pane-functions/catalog-snapshot.json +2 -2
  13. package/src/cli/pane-functions/data.ts +3 -1
  14. package/src/cli/pane-functions/freshness.ts +6 -1
  15. package/src/cli/pane-functions/function-help.ts +0 -2
  16. package/src/cli/pane-functions/market-session.ts +12 -2
  17. package/src/cli/pane-functions/screenshot-payload.ts +3 -1
  18. package/src/cli/symbol-list.ts +52 -14
  19. package/src/cli/ticker-resolution.ts +133 -38
  20. package/src/components/chart/composite/composite-chart.tsx +12 -0
  21. package/src/components/chart/composite/types.ts +18 -0
  22. package/src/components/chart/composite/use-composite-chart-keyboard.ts +38 -15
  23. package/src/components/chart-table/header.tsx +11 -5
  24. package/src/components/chart-table/selection.ts +20 -1
  25. package/src/components/data-table/view.tsx +2 -0
  26. package/src/components/feed-data-table/stack-view.tsx +85 -5
  27. package/src/components/layout/pane/header.tsx +12 -30
  28. package/src/components/ticker/badge/index.tsx +9 -4
  29. package/src/components/ticker/badge/list.tsx +3 -1
  30. package/src/components/ui/data-table/index.tsx +7 -1
  31. package/src/components/ui/data-table/muted-row.tsx +47 -0
  32. package/src/components/ui/data-table/opentui/index.tsx +42 -11
  33. package/src/components/ui/data-table/spill.ts +36 -0
  34. package/src/components/ui/data-table/types.ts +17 -1
  35. package/src/components/ui/data-table/use-column-order.ts +11 -0
  36. package/src/components/ui/icon.tsx +50 -3
  37. package/src/components/ui/list-view.tsx +2 -2
  38. package/src/components/ui/table-layout.ts +32 -0
  39. package/src/components/ui/terminal-hover-label.tsx +49 -0
  40. package/src/components/use-pinned-moment.ts +222 -13
  41. package/src/core/state/app/state.ts +11 -2
  42. package/src/core/state/app/types.ts +2 -1
  43. package/src/data/sqlite/access.ts +14 -1
  44. package/src/data/sqlite/checkpointer.ts +2 -2
  45. package/src/data/sqlite/database.ts +4 -0
  46. package/src/docs/snapshot.json +180 -26
  47. package/src/i18n/es.ts +1 -0
  48. package/src/i18n/ja.ts +1 -0
  49. package/src/i18n/ko.ts +1 -0
  50. package/src/i18n/zh-cn.ts +1 -0
  51. package/src/i18n/zh-tw.ts +1 -0
  52. package/src/market-data/market/freshness.ts +2 -2
  53. package/src/market-data/market/globex-day.ts +14 -0
  54. package/src/market-data/published-us-sessions.ts +3 -2
  55. package/src/market-data/quotes/live-valuation.ts +4 -2
  56. package/src/market-data/quotes/metadata.ts +48 -5
  57. package/src/market-data/quotes/regular-session-valuation.ts +12 -1
  58. package/src/plugins/builtin/alerts/history-pane.tsx +19 -3
  59. package/src/plugins/builtin/broker-trading/orders.tsx +4 -2
  60. package/src/plugins/builtin/chat/attachments/desktop.tsx +46 -12
  61. package/src/plugins/builtin/chat/channels.ts +5 -2
  62. package/src/plugins/builtin/chat/content/composer-runtime.ts +64 -65
  63. package/src/plugins/builtin/chat/content/footer.tsx +17 -7
  64. package/src/plugins/builtin/chat/content/index.tsx +108 -36
  65. package/src/plugins/builtin/chat/content/new-dm-dialog.tsx +21 -8
  66. package/src/plugins/builtin/chat/content/selection-runtime.ts +16 -0
  67. package/src/plugins/builtin/chat/content/shortcuts.ts +3 -0
  68. package/src/plugins/builtin/chat/content/snapshot.ts +37 -13
  69. package/src/plugins/builtin/chat/content/transcript.tsx +12 -0
  70. package/src/plugins/builtin/chat/content/types.ts +2 -0
  71. package/src/plugins/builtin/chat/controller/channels.ts +15 -15
  72. package/src/plugins/builtin/chat/controller/index.ts +140 -34
  73. package/src/plugins/builtin/chat/controller/lifecycle.ts +8 -12
  74. package/src/plugins/builtin/chat/controller/persistence.ts +32 -4
  75. package/src/plugins/builtin/chat/controller/send.ts +41 -17
  76. package/src/plugins/builtin/chat/controller/session-runtime.ts +28 -27
  77. package/src/plugins/builtin/chat/controller/state.ts +17 -8
  78. package/src/plugins/builtin/chat/controller/storage.ts +41 -4
  79. package/src/plugins/builtin/chat/controller/view.ts +6 -3
  80. package/src/plugins/builtin/chat/index.tsx +1 -1
  81. package/src/plugins/builtin/chat/layout.ts +8 -1
  82. package/src/plugins/builtin/chat/message/desktop.tsx +15 -11
  83. package/src/plugins/builtin/chat/message/header.tsx +112 -30
  84. package/src/plugins/builtin/chat/message/reactions.tsx +10 -11
  85. package/src/plugins/builtin/chat/message/render-state.ts +4 -2
  86. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  87. package/src/plugins/builtin/chat/message/types.ts +5 -0
  88. package/src/plugins/builtin/cloud-tweets/table.tsx +25 -2
  89. package/src/plugins/builtin/company-kpis/model.ts +11 -3
  90. package/src/plugins/builtin/correlation/compute.ts +6 -1
  91. package/src/plugins/builtin/custom-view/loader.ts +95 -34
  92. package/src/plugins/builtin/custom-view/pane.tsx +31 -41
  93. package/src/plugins/builtin/custom-view/table.ts +201 -0
  94. package/src/plugins/builtin/dividend-yield/client.ts +14 -17
  95. package/src/plugins/builtin/dividend-yield/headless.ts +0 -1
  96. package/src/plugins/builtin/dividend-yield/model.ts +45 -6
  97. package/src/plugins/builtin/dividend-yield/pane.tsx +70 -7
  98. package/src/plugins/builtin/dividend-yield/types.ts +2 -3
  99. package/src/plugins/builtin/dividend-yield/view.ts +22 -2
  100. package/src/plugins/builtin/econ/calendar-model.ts +135 -0
  101. package/src/plugins/builtin/econ/columns.ts +132 -0
  102. package/src/plugins/builtin/econ/index.tsx +25 -65
  103. package/src/plugins/builtin/holders/disclosures-view.tsx +9 -6
  104. package/src/plugins/builtin/holders/disclosures.ts +20 -6
  105. package/src/plugins/builtin/holders/headless.ts +2 -2
  106. package/src/plugins/builtin/ipo-calendar/model.ts +30 -1
  107. package/src/plugins/builtin/ipo-calendar/pane.tsx +7 -3
  108. package/src/plugins/builtin/kelly-sizer/headless.ts +9 -4
  109. package/src/plugins/builtin/kelly-sizer/pane.tsx +19 -9
  110. package/src/plugins/builtin/kelly-sizer/units.ts +26 -0
  111. package/src/plugins/builtin/market-halts/pane.tsx +14 -2
  112. package/src/plugins/builtin/news/wire/news/row.ts +5 -12
  113. package/src/plugins/builtin/news/wire/news/table.tsx +32 -41
  114. package/src/plugins/builtin/pe-band/headless.ts +1 -1
  115. package/src/plugins/builtin/pe-band/model.ts +41 -18
  116. package/src/plugins/builtin/pe-band/pane.tsx +6 -5
  117. package/src/plugins/builtin/perps/equity-row.tsx +4 -6
  118. package/src/plugins/builtin/perps/markets-section.tsx +19 -15
  119. package/src/plugins/builtin/perps/model.ts +10 -2
  120. package/src/plugins/builtin/portfolio-list/cli/import-positions.ts +6 -18
  121. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +1 -1
  122. package/src/plugins/builtin/portfolio-list/pane/purchase-date-fx.ts +1 -1
  123. package/src/plugins/builtin/portfolio-list/positions-import/index.tsx +1 -1
  124. package/src/plugins/builtin/portfolio-list/positions-import/lookup.ts +28 -57
  125. package/src/plugins/builtin/research/event-data.ts +3 -1
  126. package/src/plugins/builtin/research/event-model.ts +17 -15
  127. package/src/plugins/builtin/research/relative-valuation-columns.ts +19 -6
  128. package/src/plugins/builtin/research/relative-valuation-headless.ts +1 -1
  129. package/src/plugins/builtin/scanner/flow-pane.tsx +10 -0
  130. package/src/plugins/builtin/sec/exchange-filings.ts +32 -7
  131. package/src/plugins/builtin/sec/headless.ts +8 -8
  132. package/src/plugins/builtin/sec/index.tsx +69 -29
  133. package/src/plugins/builtin/shared/report-freshness.ts +4 -1
  134. package/src/plugins/builtin/ticker-detail/financials/aggregation.ts +1 -2
  135. package/src/plugins/builtin/ticker-detail/financials/exchange-table.tsx +61 -0
  136. package/src/plugins/builtin/ticker-detail/financials/model.ts +38 -4
  137. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +9 -2
  138. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +68 -39
  139. package/src/plugins/builtin/ticker-detail/headless.ts +4 -1
  140. package/src/plugins/builtin/ticker-detail/overview/model.ts +61 -15
  141. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +5 -0
  142. package/src/plugins/builtin/time-sales/model.ts +16 -9
  143. package/src/plugins/builtin/time-sales/pane.tsx +27 -24
  144. package/src/plugins/builtin/treasury-daily/client.ts +43 -9
  145. package/src/plugins/builtin/treasury-daily/pane.tsx +48 -27
  146. package/src/plugins/builtin/treasury-daily/resource.ts +33 -0
  147. package/src/portfolio/positions-import/parse.ts +14 -6
  148. package/src/portfolio/positions-import/plan.ts +3 -2
  149. package/src/react/async-resource.ts +3 -1
  150. package/src/renderers/dom/data-table/index.tsx +40 -0
  151. package/src/renderers/dom/data-table/row.tsx +39 -3
  152. package/src/renderers/dom/desktop/icons.tsx +147 -3
  153. package/src/renderers/dom/desktop/popover.tsx +2 -2
  154. package/src/renderers/dom/host/media-surface.tsx +204 -45
  155. package/src/renderers/dom/host/tabs.tsx +1 -0
  156. package/src/renderers/dom/styles.css +14 -2
  157. package/src/renderers/electrobun/bun/desktop/backend.ts +2 -0
  158. package/src/renderers/electrobun/bun/desktop/rpc-timing.ts +9 -3
  159. package/src/renderers/electrobun/shared/protocol.ts +2 -0
  160. package/src/renderers/electrobun/view/backend-rpc.ts +5 -2
  161. package/src/renderers/electrobun/view/rpc-timeout.ts +44 -3
  162. package/src/sources/gloomberb-cloud/index.ts +8 -7
  163. package/src/sources/gloomberb-cloud/normalizers.ts +7 -2
  164. package/src/sources/listing-symbols.ts +7 -1
  165. package/src/sources/provider-router/cache.ts +5 -4
  166. package/src/sources/provider-router/financials.ts +40 -18
  167. package/src/state/app/tab-cursor.ts +47 -6
  168. package/src/telemetry/stall-clocks.ts +3 -0
  169. package/src/telemetry/stall-reports.ts +12 -3
  170. package/src/telemetry/windows-process-activity.ts +41 -0
  171. package/src/telemetry/windows-time.ts +32 -0
  172. package/src/test-support/scoped-earnings.ts +24 -0
  173. package/src/tickers/terminal-codes.ts +1 -6
  174. package/src/time-series/daily-valuation.ts +13 -6
  175. package/src/time-series/filed-trailing-eps.ts +16 -3
  176. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  177. package/src/time-series/fundamentals/historical-valuation.ts +20 -0
  178. package/src/time-series/fundamentals/series.ts +13 -1
  179. package/src/time-series/valuation-currency.ts +2 -0
  180. package/src/types/financials.ts +46 -10
  181. package/src/ui/dialog-context.ts +8 -0
  182. package/src/utils/datetime-format.ts +23 -1
  183. package/src/utils/declared-dividends.ts +12 -2
  184. package/src/utils/exchange-announcements.ts +4 -1
  185. package/src/utils/exchange-notation.generated.ts +3 -1
  186. package/src/utils/exchanges.ts +2 -1
  187. package/src/utils/fundamentals.ts +1 -0
  188. package/src/utils/main-thread-stall.ts +9 -1
  189. package/src/utils/rpc-timeout-error.ts +36 -11
  190. package/src/utils/sec.ts +3 -1
  191. package/src/utils/share-multiples.ts +1 -1
  192. package/src/utils/stall-process-activity.ts +70 -0
  193. package/src/utils/statement-scope.ts +103 -0
  194. package/src/utils/trailing-eps.ts +1 -1
  195. package/src/utils/zoned-date-time.ts +1 -0
@@ -412,6 +412,7 @@ export function WebTabs({
412
412
  icon="chevron-down"
413
413
  label="All tabs"
414
414
  hasPopup="menu"
415
+ expanded={overflowMenuOpen}
415
416
  size={10}
416
417
  onPress={() => setOverflowMenuOpen((open) => !open)}
417
418
  />
@@ -261,14 +261,17 @@ button, [data-gloom-interactive="true"] { cursor: pointer; }
261
261
  }
262
262
  /* A row's hover band is painted from the chat's own state (data-hovered), not
263
263
  :hover, so it can be dropped when the list scrolls or fills under a pointer
264
- that did not move. Its actions show with it. */
264
+ that did not move. Its actions show with it, on the selected row, while
265
+ one of them has focus and while its picker is open. A tap marks the row
266
+ the way a pointer does, so a touch screen reaches them too. */
265
267
  [data-gloom-role="chat-message-reply-action"] {
266
268
  opacity: 0;
267
269
  pointer-events: none;
268
270
  }
269
271
  [data-gloom-role="chat-message"][data-hovered="true"] [data-gloom-role="chat-message-reply-action"],
270
272
  [data-gloom-role="chat-message"][data-selected="true"] [data-gloom-role="chat-message-reply-action"],
271
- [data-gloom-role="chat-message-reply-action"][data-picker-open="true"] {
273
+ [data-gloom-role="chat-message-reply-action"][data-picker-open="true"],
274
+ [data-gloom-role="chat-message-reply-action"]:focus-within {
272
275
  opacity: 1;
273
276
  pointer-events: auto;
274
277
  }
@@ -1643,6 +1646,15 @@ html[data-gloom-screenshot="true"] [data-gloom-role="chart-watermark"] {
1643
1646
  .gloom-icon-button:disabled, [data-gloom-role="pane-footer-icon"] { cursor: default; }
1644
1647
  .gloom-icon-button:not(:disabled):hover { background: var(--gloom-hover-fill); color: var(--gloom-text-bright); }
1645
1648
  .gloom-icon-button[aria-pressed="true"] { color: var(--gloom-warning); }
1649
+ /* A keyboard-focused icon's name (`focusLabel`): above the panes, under any
1650
+ popover, and never in the way of the pointer. */
1651
+ .gloom-icon-focus-label {
1652
+ position: fixed;
1653
+ z-index: 10000;
1654
+ white-space: nowrap;
1655
+ color: var(--gloom-text-bright);
1656
+ pointer-events: none;
1657
+ }
1646
1658
  .gloom-qb-view button:disabled { color: var(--gloom-text-muted); opacity: 0.55; cursor: default; }
1647
1659
  [data-gloom-role="field-grid-value"] button,
1648
1660
  [data-gloom-role="field-grid-value"] button > span { justify-content: flex-end !important; text-align: right; padding-inline: 0 !important; }
@@ -21,6 +21,7 @@ import type { RemoteControlRequest, RemoteControlResponse } from "../../../../re
21
21
  import { installCrashReporter } from "../../../../telemetry/crash-reports";
22
22
  import { createNodeCrashReporterHost } from "../../../../telemetry/crash-reports-node";
23
23
  import { createStallClocks } from "../../../../telemetry/stall-clocks";
24
+ import { readWindowsTimeoutClock } from "../../../../telemetry/windows-time";
24
25
  import { installStallReporter, parseStallEvent, recordStall } from "../../../../telemetry/stall-reports";
25
26
  import { createNodeStallReporterHost } from "../../../../telemetry/stall-reports-node";
26
27
  import { installUpdateFailureReporter, reviewLastUpdateAttempt } from "../../../../telemetry/update-failures";
@@ -574,6 +575,7 @@ export class DesktopBackend {
574
575
  rpc = BrowserView.defineRPC<ElectrobunDesktopRpcSchema>({
575
576
  handlers: {
576
577
  requests: {
578
+ "runtime.clock": readWindowsTimeoutClock,
577
579
  "backend.request": async ({ method, payload }) => {
578
580
  const request = {
579
581
  method,
@@ -1,4 +1,4 @@
1
- import { measurePerf } from "../../../../utils/perf-marks";
1
+ import { measurePerf, withoutLastStep } from "../../../../utils/perf-marks";
2
2
 
3
3
  interface RpcPacket {
4
4
  type?: unknown;
@@ -33,6 +33,12 @@ function requestName(packet: RpcPacket): string {
33
33
  return sectionPart(packet.method === "backend.request" ? params?.method : packet.method);
34
34
  }
35
35
 
36
+ function measureTurn<T>(name: string, run: () => T): T {
37
+ return name === "rpc.request.runtime.clock" || name === "rpc.respond.runtime.clock"
38
+ ? withoutLastStep(() => measurePerf(name, run))
39
+ : measurePerf(name, run);
40
+ }
41
+
36
42
  /**
37
43
  * Names every turn a window's channel takes on this process: the part of a
38
44
  * request answered before its first wait (`rpc.request.<method>`), a message
@@ -74,12 +80,12 @@ export function measureRpcTraffic(rpc: { setTransport(transport: RpcTransport):
74
80
  const { send, registerHandler } = transport;
75
81
  setTransport.call(rpc, {
76
82
  ...transport,
77
- ...(send ? { send: (packet: RpcPacket) => measurePerf(outgoing(packet), () => send.call(transport, packet)) } : {}),
83
+ ...(send ? { send: (packet: RpcPacket) => measureTurn(outgoing(packet), () => send.call(transport, packet)) } : {}),
78
84
  ...(registerHandler
79
85
  ? {
80
86
  registerHandler: (handler: (packet: RpcPacket) => unknown) => registerHandler.call(
81
87
  transport,
82
- (packet: RpcPacket) => measurePerf(incoming(packet), () => handler(packet)),
88
+ (packet: RpcPacket) => measureTurn(incoming(packet), () => handler(packet)),
83
89
  ),
84
90
  }
85
91
  : {}),
@@ -19,6 +19,7 @@ import type { PluginSeedProgress } from "../../../plugins/seed-progress";
19
19
  import type { RemoteControlRequest, RemoteControlResponse } from "../../../remote/types";
20
20
  import type { HttpProxyRequestEnvelope, HttpProxyResponseEnvelope } from "../../../utils/http-proxy-response";
21
21
  import type { StallEvent } from "../../../utils/main-thread-stall";
22
+ import type { RpcClockSample } from "../../../utils/rpc-timeout-error";
22
23
  import type { BootFrame } from "../../dom/boot-frame-page";
23
24
 
24
25
  export const ELECTROBUN_CONTEXT_MENU_ACTION = "gloom.context-menu.select";
@@ -408,6 +409,7 @@ export interface ElectrobunDesktopRpcSchema {
408
409
  params: BackendRequestPayload;
409
410
  response: unknown;
410
411
  };
412
+ "runtime.clock": { params: Record<string, never>; response: RpcClockSample | null };
411
413
  };
412
414
  messages: {
413
415
  "host.restart": DesktopRestartMessage;
@@ -16,7 +16,7 @@ import { decodeRpcResponse, decodeRpcValue, encodeRpcValue } from "../shared/rpc
16
16
  import { subscribeCapability, type CapabilitySubscriptionOptions } from "./capability-subscription";
17
17
  import { connectionHealth, DESKTOP_BRIDGE_CONNECTION_ID } from "../../../core/connection-health";
18
18
  import { createBridgeHealth, createHostRoute } from "./host-route";
19
- import { nameRpcTimeout, RPC_MAX_REQUEST_TIME_MS } from "./rpc-timeout";
19
+ import { createRpcTimeoutClockProbe, nameRpcTimeout, RPC_MAX_REQUEST_TIME_MS } from "./rpc-timeout";
20
20
  import type { RemoteControlRequest, RemoteControlResponse } from "../../../remote/types";
21
21
  import type { StallEvent } from "../../../utils/main-thread-stall";
22
22
  import { publishPluginSeedProgress } from "../../../plugins/seed-progress";
@@ -143,6 +143,9 @@ const hostRoute = createHostRoute({
143
143
  });
144
144
  // What failed for want of an answer is asked again once the bridge answers.
145
145
  const bridgeHealth = createBridgeHealth(() => connectionHealth.reportRecovery(DESKTOP_BRIDGE_CONNECTION_ID));
146
+ const timeoutClock = globalThis.navigator?.platform?.startsWith("Win")
147
+ ? createRpcTimeoutClockProbe(() => rpc.request["runtime.clock"]({}))
148
+ : undefined;
146
149
 
147
150
  export function backendRequest<T = unknown>(
148
151
  method: "capability.invoke",
@@ -159,7 +162,7 @@ export async function backendRequest(
159
162
  const encoded = encodeRpcValue(payload);
160
163
  const result = await bridgeHealth.track(async () => {
161
164
  await hostRoute.ready(method);
162
- return nameRpcTimeout(method, payload, () => rpc.request["backend.request"]({ method, payload: encoded }));
165
+ return nameRpcTimeout(method, payload, () => rpc.request["backend.request"]({ method, payload: encoded }), timeoutClock);
163
166
  });
164
167
  return decodeRpcResponse(result);
165
168
  }
@@ -1,5 +1,5 @@
1
1
  import { getCloudApiBaseUrl } from "../../../api-client/request";
2
- import { REQUEST_TIMED_OUT_MESSAGE, RpcTimeoutError } from "../../../utils/rpc-timeout-error";
2
+ import { REQUEST_TIMED_OUT_MESSAGE, RPC_CLOCK_FRESHNESS_MS, rpcAwakeTimeBound, RpcTimeoutError, type RpcClockSample } from "../../../utils/rpc-timeout-error";
3
3
  import type { DesktopBackendRequestMethod } from "../shared/protocol";
4
4
 
5
5
  /** How long the view waits for the Bun process to answer one request. */
@@ -7,6 +7,42 @@ export const RPC_MAX_REQUEST_TIME_MS = 120_000;
7
7
 
8
8
  /** What Electrobun's request timer rejects with: no method, request id or caller. */
9
9
  const ELECTROBUN_REQUEST_TIMEOUT_MESSAGE = "RPC request timed out.";
10
+ const EVIDENCE_WAIT_MS = 400;
11
+
12
+ type ClockProbe = (fresh?: boolean) => Promise<RpcClockSample | null>;
13
+
14
+ /** Share burst samples and leave at most one clock request outstanding if the host stops answering. */
15
+ export function createRpcTimeoutClockProbe(read: () => Promise<RpcClockSample | null>): ClockProbe {
16
+ let recent: { at: number; result: Promise<RpcClockSample | null> } | undefined;
17
+ let pending: Promise<RpcClockSample | null> | undefined;
18
+ return (fresh = false) => {
19
+ const now = Date.now();
20
+ if (pending) return pending;
21
+ if (!fresh && recent && now >= recent.at && now - recent.at < RPC_CLOCK_FRESHNESS_MS) return recent.result;
22
+ const result = Promise.resolve().then(read).catch(() => {
23
+ // Intentional ignore: a failed optional clock RPC provides no sleep evidence and must not fail the primary request.
24
+ return null;
25
+ }).finally(() => { pending = undefined; });
26
+ pending = result;
27
+ recent = { at: now, result };
28
+ return result;
29
+ };
30
+ }
31
+
32
+ async function awakeTimeBound(startedAt: number, timedOutAt: number, before: ReturnType<ClockProbe>, clock: ClockProbe): Promise<number | null> {
33
+ let timer: ReturnType<typeof setTimeout> | undefined;
34
+ try {
35
+ return await Promise.race([
36
+ Promise.all([before, clock(true)]).then(([start, end]) => rpcAwakeTimeBound(startedAt, timedOutAt, start, end)),
37
+ new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), EVIDENCE_WAIT_MS); }),
38
+ ]);
39
+ } catch {
40
+ // Intentional ignore: rejected clock evidence must not replace the visible timeout or suppress its crash report.
41
+ return null;
42
+ } finally {
43
+ if (timer !== undefined) clearTimeout(timer);
44
+ }
45
+ }
10
46
 
11
47
  /**
12
48
  * Runs one `backend.request` and, when Electrobun's request timer gives up on
@@ -21,24 +57,29 @@ const ELECTROBUN_REQUEST_TIMEOUT_MESSAGE = "RPC request timed out.";
21
57
  * only called external. Never the payload, rest of the path, query or headers.
22
58
  * Elapsed time is rounded to 10 s because crash reports are deduplicated per
23
59
  * session on the reported message. The error keeps its `Error` type, and
24
- * carries the elapsed time so a timer that fired long after its limit (the
25
- * machine slept) can be told from a request that really stalled.
60
+ * carries awake-time evidence, when the host can supply it, so sleep can be
61
+ * told from a request that really stalled.
26
62
  */
27
63
  export async function nameRpcTimeout<T>(
28
64
  method: DesktopBackendRequestMethod,
29
65
  payload: unknown,
30
66
  request: () => Promise<T>,
67
+ clock?: ClockProbe,
31
68
  ): Promise<T> {
32
69
  const startedAt = performance.now();
70
+ const wallStartedAt = clock ? Date.now() : 0;
71
+ const before = clock?.();
33
72
  try {
34
73
  return await request();
35
74
  } catch (error) {
36
75
  if (!(error instanceof Error) || error.message !== ELECTROBUN_REQUEST_TIMEOUT_MESSAGE) throw error;
37
76
  const elapsedMs = performance.now() - startedAt;
77
+ const wallTimedOutAt = clock ? Date.now() : 0;
38
78
  const seconds = Math.round(elapsedMs / 10_000) * 10;
39
79
  throw new RpcTimeoutError(REQUEST_TIMED_OUT_MESSAGE, {
40
80
  elapsedMs,
41
81
  limitMs: RPC_MAX_REQUEST_TIME_MS,
82
+ awakeUpperBoundMs: before && clock ? await awakeTimeBound(wallStartedAt, wallTimedOutAt, before, clock) : null,
42
83
  report: `RPC request timed out: ${describeRequest(method, payload)} after ~${seconds}s`,
43
84
  cause: error,
44
85
  });
@@ -34,7 +34,7 @@ import type { AnalystResearchData, CorporateActionsData, HolderData, OptionsChai
34
34
  import { fundCorporateActions, isIndianEtfListing } from "../../market-data/fund-actions";
35
35
  import type { PriceHistoryResult } from "../../types/price-history";
36
36
  import { parseHistorySession } from "../../market-data/history-session";
37
- import { quoteMetadataFromQuote, quoteMetadataMatchesTarget } from "../../market-data/quotes/metadata";
37
+ import { isOtcQuoteVenue, quoteMetadataFromQuote, quoteMetadataMatchesTarget } from "../../market-data/quotes/metadata";
38
38
  import type { InstrumentSearchResult } from "../../types/instrument";
39
39
  import type { TickerChanges } from "../../types/ticker-changes";
40
40
  import type { IssuerListings } from "../../types/issuer-listings";
@@ -421,13 +421,11 @@ function cloudInstrumentTarget(symbol: string, exchange?: string) {
421
421
  /**
422
422
  * Whether a quote names a listing other than the one asked for: asked for BHP
423
423
  * on Cboe Australia, Gloom Cloud has answered with BHP on NYSE, in dollars. A
424
- * price for another instrument is worse than none. A quote that names no
425
- * listing is judged by its symbol alone, as the router judges it.
424
+ * price for another instrument is worse than none. An unnamed listing is
425
+ * judged by its symbol alone unless the request specifies an OTC tier.
426
426
  */
427
427
  function pricesOtherListing(quote: Quote, target: ReturnType<typeof cloudInstrumentTarget>): boolean {
428
- const metadata = quoteMetadataFromQuote(quote);
429
- const named = !!(metadata.listingExchangeName || parsePublicTickerKey(quote.symbol).exchange);
430
- return !quoteMetadataMatchesTarget(metadata, named ? target.symbol : parsePublicTickerKey(target.symbol).symbol, named ? target.exchange : undefined);
428
+ return !quoteMetadataMatchesTarget(quoteMetadataFromQuote(quote), target.symbol, target.exchange, { allowUnnamedListing: true });
431
429
  }
432
430
 
433
431
  function otherListingMiss(ticker: string, quote: Quote) {
@@ -494,7 +492,10 @@ function matchCloudBatchItems<T extends { symbol: string; exchange?: string }, I
494
492
  }
495
493
 
496
494
  function retainRequestedQuoteSymbol(quote: Quote, ticker: string): Quote {
497
- return parsePublicTickerKey(ticker).exchange || tickerHasListingSuffix(ticker) ? { ...quote, symbol: ticker } : quote;
495
+ const requestedExchange = parsePublicTickerKey(ticker).exchange;
496
+ if (typeof quote.symbol !== "string" || isOtcQuoteVenue(requestedExchange)
497
+ || isOtcQuoteVenue(parsePublicTickerKey(quote.symbol).exchange)) return quote;
498
+ return requestedExchange || tickerHasListingSuffix(ticker) ? { ...quote, symbol: ticker } : quote;
498
499
  }
499
500
 
500
501
  function retainRequestedFinancialsSymbol(financials: TickerFinancials, ticker: string): TickerFinancials {
@@ -1,4 +1,5 @@
1
1
  import { futuresListingPriceBasis } from "../../utils/futures-generic";
2
+ import { captureScopedEarnings } from "../../utils/statement-scope";
2
3
  import type { TimeRange } from "../../time-series/range";
3
4
  import { RANGE_HISTORY_RESOLUTION } from "../../time-series/resolution";
4
5
  import type {
@@ -384,7 +385,7 @@ export function mapCloudFinancials(
384
385
  const exchange = rawQuote?.listingExchangeName ?? rawQuote?.exchangeName ?? "";
385
386
  const coin = isRoundTheClockCoin(rawQuote?.symbol, exchange);
386
387
  const derive = !isBankOrInsurerIndustry(financials.profile?.industry);
387
- return {
388
+ return captureScopedEarnings({
388
389
  quote,
389
390
  quoteMetadata: financials.quoteMetadata,
390
391
  quoteContributions: financials.quoteContributions,
@@ -393,8 +394,12 @@ export function mapCloudFinancials(
393
394
  fundamentals: mapCloudFundamentals(financials.fundamentals),
394
395
  financialCurrency: financials.financialCurrency,
395
396
  statementHistory: financials.statementHistory,
397
+ ...(financials.statementScope ? { statementScope: financials.statementScope } : {}),
398
+ ...(financials.statementReview ? { statementReview: financials.statementReview } : {}),
396
399
  annualStatements: (financials.annualStatements ?? []).map((row) => mapCloudStatement(row, derive)),
397
400
  quarterlyStatements: (financials.quarterlyStatements ?? []).map((row) => mapCloudStatement(row, derive)),
401
+ ...(financials.statementFilings !== undefined ? { periodFilings: financials.statementFilings } : {}),
402
+ ...(financials.taiwanExchangeStatements?.length ? { taiwanExchangeStatements: financials.taiwanExchangeStatements } : {}),
398
403
  ...(financials.trailingStatement
399
404
  ? { trailingStatement: { ...mapCloudStatement(financials.trailingStatement, derive), trailing: financials.trailingStatement.trailing } }
400
405
  : {}),
@@ -404,7 +409,7 @@ export function mapCloudFinancials(
404
409
  : mapPricePoint(point as unknown as CloudPricePointPayload, divisor, exchange, coin),
405
410
  ),
406
411
  ...(financials.epsEstimates ? { epsEstimates: financials.epsEstimates } : {}),
407
- };
412
+ });
408
413
  }
409
414
 
410
415
  /**
@@ -12,7 +12,7 @@ const EXCHANGE_SUFFIX_MAP: Record<string, string> = {
12
12
  IDX: ".JK",
13
13
  NSE: ".NS", BSE: ".BO",
14
14
  ASX: ".AX", NZE: ".NZ",
15
- SET: ".BK", BKK: ".BK", KLSE: ".KL", MYX: ".KL", PSE: ".PS", HOSE: ".VN", HNX: "",
15
+ SET: ".BK", BKK: ".BK", KLSE: ".KL", MYX: ".KL", PSE: ".PS", XPHS: "", HOSE: ".VN", HNX: "",
16
16
  LSE: ".L", LSEETF: ".L",
17
17
  XETRA: ".DE", XETR: ".DE", IBIS: ".DE", IBIS2: ".DE", FWB: ".F", FWB2: ".F", GETTEX: ".DE", TGATE: ".DE", SWB: ".SG",
18
18
  EURONEXT: ".AS", AEB: ".AS", AMS: ".AS", SBF: ".PA", EPA: ".PA", "ENEXT.BE": ".BR", BRU: ".BR", BVL: ".LS", LIS: ".LS",
@@ -205,6 +205,12 @@ export function hongKongListingCode(ticker: string, exchange: string): string {
205
205
  return isHongKongExchange(exchange) && /^\d+$/.test(ticker) ? ticker.padStart(4, "0") : ticker;
206
206
  }
207
207
 
208
+ /** Accept both short and zero-padded Hong Kong codes without dropping a significant fifth digit. */
209
+ export function hongKongWorkingCode(ticker: string, exchange = "HKEX"): string | null {
210
+ if (!isHongKongExchange(exchange) || !/^\d{1,5}$/.test(ticker) || !Number(ticker)) return null;
211
+ return String(Number(ticker)).padStart(4, "0");
212
+ }
213
+
208
214
  function normalizeListingTicker(ticker: string, exchange: string): string {
209
215
  return hongKongListingCode(ticker, exchange).replace(/ /g, "-");
210
216
  }
@@ -1,6 +1,7 @@
1
1
  import { apiClient } from "../../api-client";
2
2
  import { listingSuffixExchange } from "../listing-symbols";
3
3
  import type { CachedResourceRecord, ResourceStore } from "../../data/resource-store";
4
+ import { isOtcQuoteVenue } from "../../market-data/quotes/metadata";
4
5
  import type { TimeRange } from "../../time-series/range";
5
6
  import type { BrokerContractRef } from "../../types/instrument";
6
7
  import type { Quote, TickerFinancials } from "../../types/financials";
@@ -185,7 +186,7 @@ function cachedProviderFinancialsMatchTarget(value: TickerFinancials, symbol: st
185
186
  // symbol into the returned metadata or bypass quote/contribution checks.
186
187
  const metadata = value.quoteMetadata;
187
188
  const checked = metadata && metadata.symbol === undefined
188
- ? { ...value, quoteMetadata: { ...metadata, symbol } }
189
+ ? { ...value, quoteMetadata: { ...metadata, symbol: parsePublicTickerKey(symbol).symbol } }
189
190
  : value;
190
191
  return providerFinancialsMatchTarget(checked, symbol, exchange);
191
192
  }
@@ -223,9 +224,9 @@ export function listCachedResources<T>(
223
224
  const metadata = kind === "financials" ? (record.value as TickerFinancials).quoteMetadata : undefined;
224
225
  const declaredExchange = canonicalExchange(quote?.listingExchangeName || quote?.exchangeName
225
226
  || metadata?.listingExchangeName || parsePublicTickerKey(quote?.symbol ?? metadata?.symbol ?? "").exchange);
226
- // Refetch a record that declares another public listing; never relabel it
227
- // or let it outrank a fresh exact-listing response.
228
- if (requestedExchange && declaredExchange && requestedExchange !== declaredExchange) return false;
227
+ // OTC identity was checked above using the listing venue and symbol suffix
228
+ // together. Other cached listings still require the declared venue.
229
+ if (requestedExchange && declaredExchange && !isOtcQuoteVenue(requestedExchange) && requestedExchange !== declaredExchange) return false;
229
230
  // A bare lookup that names no listing cannot say which venue it priced:
230
231
  // the unqualified BA quote is Boeing's, never BAE Systems' London line.
231
232
  return !(requestedExchange && !declaredExchange && !parsePublicTickerKey(entityKey).exchange
@@ -89,6 +89,8 @@ function excludeNonCompanyFinancials(financials: TickerFinancials): TickerFinanc
89
89
  nextEarnings: undefined,
90
90
  annualStatements: [],
91
91
  quarterlyStatements: [],
92
+ periodFilings: undefined,
93
+ taiwanExchangeStatements: undefined,
92
94
  };
93
95
  }
94
96
 
@@ -225,11 +227,9 @@ export function providerQuoteMatchesTarget(quote: Quote | null | undefined, symb
225
227
  if ([quote.listingExchangeName, quote.exchangeName, quote.instrumentType]
226
228
  .some((value) => value != null && typeof value !== "string")) return false;
227
229
  if (symbol) {
228
- const metadata = quoteMetadataFromQuote(quote);
229
230
  // Older quote providers omit listing metadata. They must still return the
230
- // requested symbol; when they do name a listing it must agree as well.
231
- const hasListing = !!(metadata.listingExchangeName || parsePublicTickerKey(quote.symbol).exchange);
232
- if (!quoteMetadataMatchesTarget(metadata, hasListing ? symbol : parsePublicTickerKey(symbol).symbol, hasListing ? exchange : undefined)) return false;
231
+ // requested symbol; an explicit OTC tier also needs matching evidence.
232
+ if (!quoteMetadataMatchesTarget(quoteMetadataFromQuote(quote), symbol, exchange, { allowUnnamedListing: true })) return false;
233
233
  }
234
234
  return true;
235
235
  }
@@ -284,14 +284,16 @@ export function lastKnownProviderQuote(quote: Quote | null | undefined, exchange
284
284
  }
285
285
 
286
286
  export function providerFinancialsMatchTarget(value: TickerFinancials, symbol: string, exchange?: string): boolean {
287
+ const listing = parsePublicTickerKey(symbol);
288
+ const venue = canonicalExchange(listing.exchange || exchange || value.quote?.listingExchangeName);
289
+ if (listing.symbol === "VYLR" && (!venue || venue === "NYSE") && !value.statementScope && hasStatementRows(value)) return false;
287
290
  if (value.quote && !providerQuoteMatchesTarget(value.quote, symbol, exchange)) return false;
288
291
  if (Object.values(value.quoteContributions ?? {}).some((quote) => !providerQuoteMatchesTarget(quote, symbol, exchange))) return false;
289
292
  const metadata = value.quoteMetadata;
290
293
  if (!metadata) return true;
291
294
  if (typeof metadata.symbol !== "string" || !metadata.symbol.trim()
292
295
  || [metadata.listingExchangeName, metadata.instrumentType].some((field) => field != null && typeof field !== "string")) return false;
293
- const hasListing = !!(metadata.listingExchangeName || parsePublicTickerKey(metadata.symbol).exchange);
294
- return quoteMetadataMatchesTarget(metadata, hasListing ? symbol : parsePublicTickerKey(symbol).symbol, hasListing ? exchange : undefined);
296
+ return quoteMetadataMatchesTarget(metadata, symbol, exchange, { allowUnnamedListing: true });
295
297
  }
296
298
 
297
299
  export function dropUnusableProviderQuote(
@@ -346,21 +348,23 @@ export function hasRecentFinancialProfileAttempt(resources: ResourceStore | unde
346
348
  && attempt.value.sourceKeys.every((key, index) => key === sourceKeys[index]);
347
349
  }
348
350
 
349
- /** Company classification may only cross sources for the same explicit listing. */
350
- export function profileForSameListing(source: TickerFinancials, target: TickerFinancials, request?: { symbol: string; exchange?: string }): TickerFinancials["profile"] {
351
- if (!hasMeaningfulProfile(source)) return undefined;
351
+ function sameFinancialListing(source: TickerFinancials, target: TickerFinancials, request?: { symbol: string; exchange?: string }): boolean {
352
352
  const identity = (value: TickerFinancials) => [
353
353
  value.quote ? quoteMetadataFromQuote(value.quote) : undefined, value.quoteMetadata,
354
354
  ].find(metadata => metadata && typeof metadata.symbol === "string" && (metadata.listingExchangeName || parsePublicTickerKey(metadata.symbol).exchange));
355
355
  const actual = identity(source), requested = identity(target);
356
- if (!actual || !requested) return undefined;
356
+ if (!actual || !requested) return false;
357
357
  const symbol = request?.symbol ?? requested.symbol;
358
358
  const listing = parsePublicTickerKey(symbol).exchange || request?.exchange || requested.listingExchangeName || parsePublicTickerKey(requested.symbol).exchange;
359
359
  const actualListing = actual.listingExchangeName || parsePublicTickerKey(actual.symbol).exchange;
360
- if (typeof listing !== "string" || typeof actualListing !== "string" || !listing.trim() || !actualListing.trim()
361
- || !providerFinancialsMatchTarget(source, symbol, listing) || !providerFinancialsMatchTarget(target, symbol, listing)
362
- || !quoteMetadataMatchesTarget(requested, symbol, listing) || !quoteMetadataMatchesTarget(actual, symbol, listing)) return undefined;
363
- return source.profile;
360
+ return typeof listing === "string" && typeof actualListing === "string" && !!listing.trim() && !!actualListing.trim()
361
+ && providerFinancialsMatchTarget(source, symbol, listing) && providerFinancialsMatchTarget(target, symbol, listing)
362
+ && quoteMetadataMatchesTarget(requested, symbol, listing) && quoteMetadataMatchesTarget(actual, symbol, listing);
363
+ }
364
+
365
+ /** Company classification may only cross sources for the same explicit listing. */
366
+ export function profileForSameListing(source: TickerFinancials, target: TickerFinancials, request?: { symbol: string; exchange?: string }): TickerFinancials["profile"] {
367
+ return hasMeaningfulProfile(source) && sameFinancialListing(source, target, request) ? source.profile : undefined;
364
368
  }
365
369
 
366
370
  export function hasStatementRows(data: TickerFinancials | null | undefined): boolean {
@@ -400,13 +404,15 @@ export function hasShallowStatementHistory(data: TickerFinancials | null | undef
400
404
  }
401
405
 
402
406
  export function mergeMissingStatementArrays(primary: TickerFinancials, fallback: TickerFinancials): TickerFinancials {
407
+ const scoped = scopedResearch(primary, fallback);
403
408
  return excludeNonCompanyFinancials({
404
409
  ...primary,
405
410
  profile: mergeDefinedObject(primary.profile, profileForSameListing(fallback, primary)),
406
411
  statementHistory: fallback.statementHistory?.status === "available" ? fallback.statementHistory : primary.statementHistory ?? fallback.statementHistory,
412
+ periodFilings: primary.periodFilings ?? (fallback.periodFilings && sameFinancialListing(fallback, primary) ? fallback.periodFilings : undefined),
413
+ taiwanExchangeStatements: primary.taiwanExchangeStatements ?? fallback.taiwanExchangeStatements,
407
414
  financialCurrency: primary.financialCurrency ?? (hasStatementRows(primary) ? undefined : fallback.financialCurrency),
408
- annualStatements: mergeFinancialStatementRows(primary.annualStatements, fallback.annualStatements),
409
- quarterlyStatements: mergeFinancialStatementRows(primary.quarterlyStatements, fallback.quarterlyStatements),
415
+ ...scoped,
410
416
  });
411
417
  }
412
418
 
@@ -472,6 +478,10 @@ function mergeFundamentals(primary: Fundamentals | undefined, fallback: Fundamen
472
478
  }
473
479
  const merged = mergeDefinedObject(primary, fallback);
474
480
  if (merged) {
481
+ const cashFlow = primary?.freeCashFlow != null ? primary : fallback;
482
+ if (cashFlow?.freeCashFlow != null) {
483
+ merged.freeCashFlowCurrency = cashFlow.freeCashFlowCurrency === undefined ? cashFlow.financialCurrency ?? null : cashFlow.freeCashFlowCurrency;
484
+ } else delete merged.freeCashFlowCurrency;
475
485
  const unavailable = new Set(fallback?.unavailableFields ?? []);
476
486
  for (const field of RETRACTED_FUNDAMENTALS_FIELDS) {
477
487
  if (primary?.unavailableFields?.includes(field)) unavailable.add(field);
@@ -532,6 +542,18 @@ function mergeFundamentals(primary: Fundamentals | undefined, fallback: Fundamen
532
542
  return redactUnavailableFundamentals(merged);
533
543
  }
534
544
 
545
+ function scopedResearch(primary: TickerFinancials, fallback: TickerFinancials) {
546
+ const owned = !primary.statementScope ? (fallback.statementScope ? fallback : undefined) : !fallback.statementScope ? primary
547
+ : primary.statementScope.basis !== fallback.statementScope.basis ? (fallback.statementScope.basis === "standalone" ? fallback : primary)
548
+ : (fallback.statementReview?.reviewedThrough ?? "") > (primary.statementReview?.reviewedThrough ?? "") ? fallback : primary;
549
+ return owned ? { statementScope: owned.statementScope, statementReview: owned.statementReview, financialCurrency: owned.financialCurrency,
550
+ annualStatements: owned.annualStatements, quarterlyStatements: owned.quarterlyStatements,
551
+ trailingStatement: owned.trailingStatement, fundamentals: owned.fundamentals } : {
552
+ annualStatements: mergeFinancialStatementRows(primary.annualStatements, fallback.annualStatements),
553
+ quarterlyStatements: mergeFinancialStatementRows(primary.quarterlyStatements, fallback.quarterlyStatements),
554
+ };
555
+ }
556
+
535
557
  export function mergeFinancials(primary: TickerFinancials | null, fallback: TickerFinancials | null): TickerFinancials | null {
536
558
  if (!primary || !fallback) {
537
559
  const single = primary ?? fallback;
@@ -574,8 +596,7 @@ export function mergeFinancials(primary: TickerFinancials | null, fallback: Tick
574
596
  profile: mergeDefinedObject(primaryResearch?.profile, fallbackResearch?.profile),
575
597
  fundamentals: mergeFundamentals(primaryResearch?.fundamentals, fallbackResearch?.fundamentals),
576
598
  priceHistory: normalizePriceHistory(dominant.priceHistory.length > 0 ? dominant.priceHistory : secondary.priceHistory),
577
- annualStatements: mergeFinancialStatementRows(primary.annualStatements, fallback.annualStatements),
578
- quarterlyStatements: mergeFinancialStatementRows(primary.quarterlyStatements, fallback.quarterlyStatements),
599
+ ...scopedResearch(primary, fallback),
579
600
  });
580
601
  }
581
602
 
@@ -583,6 +604,7 @@ export function mergeFinancials(primary: TickerFinancials | null, fallback: Tick
583
604
  * must supersede the older cache that caused this provider fetch. */
584
605
  export function mergeRefreshedFinancials(cached: TickerFinancials, fresh: TickerFinancials | null): TickerFinancials {
585
606
  const merged = mergeFinancials(cached, fresh)!;
607
+ if (merged.statementScope) return fresh?.statementScope ? { ...merged, ...scopedResearch(fresh, cached) } : merged;
586
608
  const statistics = redactUnavailableFundamentals(fresh?.fundamentals);
587
609
  if (!statistics) return merged;
588
610
  const update: Fundamentals = {
@@ -14,6 +14,19 @@ interface TabCursor {
14
14
  time: number;
15
15
  /** The chart the cursor is on; it never follows its own time back. */
16
16
  sourceId: string;
17
+ /** A pinned cursor's number, new each time the pin is set or moved; see `PinnedMoment`. */
18
+ serial?: number;
19
+ }
20
+
21
+ /**
22
+ * The moment a tab's crosshair is pinned at, as a list that follows it reads
23
+ * it: `serial` is new each time the pin is set or moved, so a list mounted
24
+ * again under the same pin (a tab switch) can tell it already followed it,
25
+ * and one pinned again at the same time follows again.
26
+ */
27
+ export interface PinnedMoment {
28
+ at: number;
29
+ serial: number;
17
30
  }
18
31
 
19
32
  const cursors = new Map<string, TabCursor>();
@@ -25,6 +38,7 @@ const PINNED = "\u0000pinned";
25
38
  /** How many charts in each tab are mounted to show its pin; see `useTabCursorLink`. */
26
39
  const pinViewers = new Map<string, number>();
27
40
  const listeners = new Set<() => void>();
41
+ let pinSerial = 0;
28
42
 
29
43
  /** A time a Date can hold. A pin is never NaN, infinite or past the Date range, whatever asks for it. */
30
44
  function isMoment(time: number): boolean {
@@ -41,7 +55,7 @@ function setTabCursorTime(tabKey: string, sourceId: string | null, time: number
41
55
  cursors.delete(tabKey);
42
56
  } else {
43
57
  if (sourceId === null || (current?.sourceId === sourceId && current.time === time)) return;
44
- cursors.set(tabKey, { time, sourceId });
58
+ cursors.set(tabKey, sourceId === PINNED ? { time, sourceId, serial: ++pinSerial } : { time, sourceId });
45
59
  }
46
60
  for (const listener of listeners) listener();
47
61
  }
@@ -67,6 +81,8 @@ export interface TabCursorLink {
67
81
  pinned?(): boolean;
68
82
  /** Pins the tab's cursor at `time`, which no chart's pointer moves, or unpins it with null. */
69
83
  pin?(time: number | null): void;
84
+ /** The tab's pinned moment, the same object until the pin moves; null while nothing is pinned. */
85
+ pinnedMoment?(): PinnedMoment | null;
70
86
  }
71
87
 
72
88
  /** A layout tab is named by its id; older saved tabs have none, and go by position. */
@@ -153,6 +169,7 @@ export function useTabCursorLink(sourceId: string | null, { viewer = true }: { v
153
169
  pin: (time) => {
154
170
  if (time === null || isMoment(time)) setTabCursorTime(tabKey, PINNED, time);
155
171
  },
172
+ pinnedMoment: () => pinnedMomentOf(cursors.get(tabKey)),
156
173
  }, [sourceId, tabKey]);
157
174
  useEffect(() => {
158
175
  if (app && "subscribe" in app) watchTabs(app);
@@ -199,12 +216,36 @@ export function useTabCursorLink(sourceId: string | null, { viewer = true }: { v
199
216
  * never on a pointer move.
200
217
  */
201
218
  export function usePinnedTabTime(): number | null {
219
+ return usePinnedTabMoment()?.at ?? null;
220
+ }
221
+
222
+ /** A pinned cursor as the moment a list follows, the same object until the pin moves. */
223
+ const pinnedMoments = new WeakMap<TabCursor, PinnedMoment>();
224
+ function pinnedMomentOf(cursor: TabCursor | undefined): PinnedMoment | null {
225
+ if (cursor?.sourceId !== PINNED) return null;
226
+ let moment = pinnedMoments.get(cursor);
227
+ if (!moment) {
228
+ moment = { at: cursor.time, serial: cursor.serial ?? 0 };
229
+ pinnedMoments.set(cursor, moment);
230
+ }
231
+ return moment;
232
+ }
233
+
234
+ /** `usePinnedTabTime` with the pin's serial, for a list that follows the pin once each time it moves. */
235
+ export function usePinnedTabMoment(): PinnedMoment | null {
202
236
  const tabKey = useOptionalAppSelector<string | null>(selectTabKey, null);
203
- const pinnedTime = useCallback(() => {
204
- const cursor = tabKey === null ? undefined : cursors.get(tabKey);
205
- return cursor?.sourceId === PINNED ? cursor.time : null;
206
- }, [tabKey]);
207
- return useSyncExternalStore(subscribe, pinnedTime);
237
+ const pinned = useCallback(() => tabKey === null ? null : pinnedMomentOf(cursors.get(tabKey)), [tabKey]);
238
+ return useSyncExternalStore(subscribe, pinned);
239
+ }
240
+
241
+ /**
242
+ * Reads the pin of the layout tab the caller is in when called, not when it
243
+ * rendered: for a cleanup that runs after the caller has gone, whatever the
244
+ * caller showed of the pin then. Null outside an app.
245
+ */
246
+ export function usePinnedTabMomentReader(): () => PinnedMoment | null {
247
+ const tabKey = useOptionalAppSelector<string | null>(selectTabKey, null);
248
+ return useCallback(() => tabKey === null ? null : pinnedMomentOf(cursors.get(tabKey)), [tabKey]);
208
249
  }
209
250
 
210
251
  /** The moment the active layout tab has its crosshair pinned at, outside React: a shared link opens there. */
@@ -1,5 +1,6 @@
1
1
  import { dlopen, FFIType, ptr } from "bun:ffi";
2
2
  import type { StallClockReading } from "../utils/main-thread-stall";
3
+ import { createWindowsProcessActivity } from "./windows-process-activity";
3
4
 
4
5
  /** macOS `clock_gettime_nsec_np` clocks: awake time (stops in sleep), and this thread's CPU time. */
5
6
  const DARWIN_CLOCK_UPTIME_RAW = 8;
@@ -84,10 +85,12 @@ function platformClocks(): PlatformClocks | null {
84
85
  */
85
86
  export function createStallClocks(): () => StallClockReading {
86
87
  const platform = platformClocks();
88
+ const activity = process.platform === "win32" ? createWindowsProcessActivity() : null;
87
89
  return () => ({
88
90
  awakeMs: null,
89
91
  threadCpuMs: null,
90
92
  ...platform?.(),
91
93
  processCpuMs: processCpuMs(),
94
+ ...(activity ? { processActivity: activity() } : {}),
92
95
  });
93
96
  }