@gloom-sh/terminal 0.20.18 → 0.20.19

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 (204) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/cot.ts +5 -6
  3. package/src/api-client/data.ts +11 -1
  4. package/src/api-client/index.ts +1 -0
  5. package/src/api-client/request.ts +162 -40
  6. package/src/api-client/types/news.ts +45 -0
  7. package/src/api-client/types/world-venues.ts +9 -0
  8. package/src/app.tsx +4 -2
  9. package/src/architecture/floating-promise-allowlist.json +1 -1
  10. package/src/cli/commands/market.ts +53 -17
  11. package/src/cli/commands/ticker.ts +13 -6
  12. package/src/cli/context.ts +8 -0
  13. package/src/cli/desktop-pane-shot-browser.ts +3 -1
  14. package/src/cli/desktop-pane-shot-view.ts +0 -1
  15. package/src/cli/desktop-pane-shot.ts +204 -43
  16. package/src/cli/errors.ts +3 -9
  17. package/src/cli/exit-codes.ts +1 -1
  18. package/src/cli/glossary.ts +1 -1
  19. package/src/cli/help.ts +1 -1
  20. package/src/cli/history-rows.ts +2 -2
  21. package/src/cli/index.ts +1 -1
  22. package/src/cli/listing-arg.ts +87 -23
  23. package/src/cli/pane-functions/catalog-snapshot.json +17 -6
  24. package/src/cli/pane-functions/dom.ts +30 -2
  25. package/src/cli/pane-functions/freshness.ts +23 -4
  26. package/src/cli/pane-functions/function-help.ts +3 -3
  27. package/src/cli/pane-functions/headless.ts +9 -1
  28. package/src/cli/pane-functions/index.ts +77 -10
  29. package/src/cli/pane-functions/report-notices.ts +10 -0
  30. package/src/cli/pane-functions/resolver.ts +3 -2
  31. package/src/cli/pane-functions/screenshot-assessment.ts +10 -5
  32. package/src/cli/pane-functions/screenshot-data-evidence.ts +7 -15
  33. package/src/cli/pane-functions/screenshot-payload.ts +24 -10
  34. package/src/cli/pane-functions/screenshot-render.ts +21 -8
  35. package/src/cli/pane-functions/screenshot-types.ts +9 -0
  36. package/src/cli/quote-answer.ts +1 -1
  37. package/src/cli/result.ts +17 -0
  38. package/src/cli/scroll-truncation.ts +7 -2
  39. package/src/cli/ticker-resolution.ts +1 -1
  40. package/src/cli/unreachable.ts +21 -0
  41. package/src/components/chart/composite/drawing-store.ts +11 -7
  42. package/src/components/chart/composite/format.ts +1 -0
  43. package/src/components/chart/composite/legend.tsx +5 -2
  44. package/src/components/chart/composite/panel-surface/plot-gestures.ts +9 -2
  45. package/src/components/chart/composite/panel-surface.tsx +1 -1
  46. package/src/components/chart/composite/tools.ts +164 -39
  47. package/src/components/chart-table/header.tsx +2 -2
  48. package/src/components/chart-table/layout.ts +5 -6
  49. package/src/components/command-bar/routes/root/runtime.ts +11 -3
  50. package/src/components/command-bar/routes/ticker-search/results.ts +5 -0
  51. package/src/components/command-bar/selection-runtime.ts +29 -5
  52. package/src/components/command-bar/surface/index.tsx +4 -1
  53. package/src/components/command-bar/workflow/alert.ts +13 -5
  54. package/src/components/layout/pane/footer/model.ts +10 -2
  55. package/src/components/layout/pane/status-footer.ts +24 -0
  56. package/src/components/price-performance.tsx +26 -8
  57. package/src/components/reader/article-reader.tsx +12 -5
  58. package/src/components/ui/data-table/opentui/index.tsx +7 -0
  59. package/src/components/ui/table-layout.ts +32 -1
  60. package/src/market-data/ah-pair.ts +19 -0
  61. package/src/market-data/coordinator/entries.ts +6 -4
  62. package/src/market-data/coordinator/index.ts +14 -3
  63. package/src/market-data/futures-board.ts +36 -29
  64. package/src/market-data/futures-contract.ts +37 -1
  65. package/src/market-data/market/change-basis.ts +9 -0
  66. package/src/market-data/market/status.ts +40 -4
  67. package/src/market-data/performance.ts +127 -32
  68. package/src/market-data/quotes/time.ts +5 -2
  69. package/src/news/types.ts +28 -0
  70. package/src/notifications/app-badge.ts +2 -3
  71. package/src/notifications/app-notifier.ts +5 -0
  72. package/src/plugins/builtin/alerts/cli.ts +65 -18
  73. package/src/plugins/builtin/alerts/command.ts +39 -9
  74. package/src/plugins/builtin/alerts/event-rows.ts +9 -3
  75. package/src/plugins/builtin/alerts/events-pane.tsx +16 -10
  76. package/src/plugins/builtin/alerts/headless.ts +12 -6
  77. package/src/plugins/builtin/alerts/index.tsx +60 -8
  78. package/src/plugins/builtin/alerts/option-contract.ts +197 -0
  79. package/src/plugins/builtin/alerts/price.ts +30 -5
  80. package/src/plugins/builtin/alerts/pro-rules.ts +62 -0
  81. package/src/plugins/builtin/alerts/research-builder.ts +5 -10
  82. package/src/plugins/builtin/analytics/account-returns.ts +1 -1
  83. package/src/plugins/builtin/analytics/pane-model.ts +2 -2
  84. package/src/plugins/builtin/analytics/risk-client.ts +1 -1
  85. package/src/plugins/builtin/buildout/company/pane.tsx +4 -14
  86. package/src/plugins/builtin/catalysts/model.ts +2 -1
  87. package/src/plugins/builtin/chart-composer/chart-spec.ts +5 -0
  88. package/src/plugins/builtin/chart-composer/cli-options.ts +5 -3
  89. package/src/plugins/builtin/chart-composer/headless-schema.ts +14 -10
  90. package/src/plugins/builtin/chart-composer/headless.ts +2 -0
  91. package/src/plugins/builtin/chart-composer/index.tsx +17 -5
  92. package/src/plugins/builtin/chart-composer/pane.tsx +14 -4
  93. package/src/plugins/builtin/chart-composer/viewport-labels.ts +2 -17
  94. package/src/plugins/builtin/chat/controller/notifications.ts +1 -0
  95. package/src/plugins/builtin/chat/index.tsx +0 -1
  96. package/src/plugins/builtin/commodities-energy/index.tsx +1 -1
  97. package/src/plugins/builtin/company-kpis/headless.ts +1 -1
  98. package/src/plugins/builtin/company-kpis/model.ts +21 -9
  99. package/src/plugins/builtin/congress-trades/model.ts +9 -5
  100. package/src/plugins/builtin/cot/client.ts +2 -3
  101. package/src/plugins/builtin/cot/headless.ts +16 -16
  102. package/src/plugins/builtin/cot/index.tsx +6 -6
  103. package/src/plugins/builtin/cot/model.ts +25 -5
  104. package/src/plugins/builtin/cot/pane.tsx +11 -6
  105. package/src/plugins/builtin/cot/series.ts +11 -8
  106. package/src/plugins/builtin/cpi/model.ts +15 -4
  107. package/src/plugins/builtin/cpi/pane.tsx +29 -7
  108. package/src/plugins/builtin/doe/model.ts +30 -0
  109. package/src/plugins/builtin/doe/pane.tsx +8 -2
  110. package/src/plugins/builtin/earnings/board-table.ts +9 -4
  111. package/src/plugins/builtin/earnings/headless.ts +10 -3
  112. package/src/plugins/builtin/earnings/history-table.ts +4 -2
  113. package/src/plugins/builtin/earnings-calls/calendar.tsx +4 -3
  114. package/src/plugins/builtin/earnings-ripple/pane.tsx +2 -2
  115. package/src/plugins/builtin/econ/index.tsx +4 -2
  116. package/src/plugins/builtin/futures/model.ts +14 -1
  117. package/src/plugins/builtin/futures/series.ts +1 -8
  118. package/src/plugins/builtin/fx-matrix/index.tsx +2 -2
  119. package/src/plugins/builtin/insider/detail.tsx +36 -7
  120. package/src/plugins/builtin/insider/filing-stories.ts +110 -0
  121. package/src/plugins/builtin/insider/headless.ts +37 -2
  122. package/src/plugins/builtin/insider/index.tsx +79 -10
  123. package/src/plugins/builtin/insider/model.ts +43 -5
  124. package/src/plugins/builtin/ipo-calendar/client.ts +11 -1
  125. package/src/plugins/builtin/ipo-calendar/model.ts +3 -7
  126. package/src/plugins/builtin/jobs/headless.ts +2 -1
  127. package/src/plugins/builtin/jobs/model.ts +6 -0
  128. package/src/plugins/builtin/jobs/pane.tsx +8 -3
  129. package/src/plugins/builtin/news/wire/news/detail-view.tsx +118 -10
  130. package/src/plugins/builtin/news/wire/news/story-evidence.ts +178 -0
  131. package/src/plugins/builtin/options/analytics.ts +1 -1
  132. package/src/plugins/builtin/options/view.tsx +18 -11
  133. package/src/plugins/builtin/options-positioning/model.ts +11 -0
  134. package/src/plugins/builtin/options-positioning/pane.tsx +22 -1
  135. package/src/plugins/builtin/options-scenario/client.ts +49 -8
  136. package/src/plugins/builtin/options-scenario/headless.ts +7 -3
  137. package/src/plugins/builtin/options-scenario/model.ts +33 -2
  138. package/src/plugins/builtin/options-scenario/pane.tsx +3 -4
  139. package/src/plugins/builtin/perps/cascade.ts +4 -3
  140. package/src/plugins/builtin/perps/markets-section.tsx +5 -2
  141. package/src/plugins/builtin/perps/model.ts +4 -3
  142. package/src/plugins/builtin/portfolio-list/table.tsx +3 -2
  143. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -14
  144. package/src/plugins/builtin/research/event-model.ts +12 -6
  145. package/src/plugins/builtin/research-search/index.tsx +3 -1
  146. package/src/plugins/builtin/scanner/denied.tsx +16 -4
  147. package/src/plugins/builtin/scanner/flow-pane.tsx +1 -1
  148. package/src/plugins/builtin/scanner/hilo-pane.tsx +1 -1
  149. package/src/plugins/builtin/sec/filing-display.tsx +14 -2
  150. package/src/plugins/builtin/sec/headless.ts +42 -4
  151. package/src/plugins/builtin/sec/index.tsx +21 -1
  152. package/src/plugins/builtin/sectors/sector-model.ts +1 -1
  153. package/src/plugins/builtin/shared/earnings-report.ts +32 -3
  154. package/src/plugins/builtin/shared/options-pro-copy.ts +34 -0
  155. package/src/plugins/builtin/shared/statement-currency.ts +23 -0
  156. package/src/plugins/builtin/shared/ticker-surface.ts +1 -1
  157. package/src/plugins/builtin/supply-chain/pane.tsx +4 -3
  158. package/src/plugins/builtin/themes/headless.ts +4 -4
  159. package/src/plugins/builtin/themes/model.ts +11 -8
  160. package/src/plugins/builtin/themes/pane.tsx +2 -2
  161. package/src/plugins/builtin/ticker-detail/financials/model.ts +22 -32
  162. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +7 -9
  163. package/src/plugins/builtin/ticker-detail/headless-schema.ts +2 -0
  164. package/src/plugins/builtin/ticker-detail/headless.ts +28 -12
  165. package/src/plugins/builtin/ticker-detail/overview/board-lot.ts +21 -0
  166. package/src/plugins/builtin/ticker-detail/overview/model.ts +11 -1
  167. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -0
  168. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +61 -13
  169. package/src/plugins/builtin/volatility/pane.tsx +3 -3
  170. package/src/plugins/builtin/world-venue-map/headless.ts +4 -2
  171. package/src/plugins/builtin/world-venue-map/model.ts +6 -1
  172. package/src/plugins/builtin/world-venue-map/venue-header.tsx +5 -3
  173. package/src/plugins/catalog-browser.ts +10 -1
  174. package/src/renderers/browser/activity.ts +16 -0
  175. package/src/renderers/browser/app-badge-host.ts +14 -0
  176. package/src/renderers/browser/main.tsx +5 -0
  177. package/src/renderers/browser/notifications.ts +103 -0
  178. package/src/renderers/browser/ui-host.tsx +4 -0
  179. package/src/renderers/dom/data-table/index.tsx +27 -4
  180. package/src/renderers/electrobun/view/http-fetch.ts +3 -2
  181. package/src/sources/gloomberb-cloud/index.ts +8 -6
  182. package/src/sources/gloomberb-cloud/news.ts +35 -0
  183. package/src/sources/provider-errors.ts +34 -7
  184. package/src/sources/provider-router/history.ts +32 -6
  185. package/src/time-series/base-series.ts +39 -6
  186. package/src/time-series/chart-seed.ts +2 -2
  187. package/src/time-series/history-quality.ts +4 -1
  188. package/src/time-series/hooks.ts +2 -0
  189. package/src/time-series/price-comparison.ts +17 -23
  190. package/src/time-series/reporting.ts +1 -1
  191. package/src/time-series/resolution.ts +13 -0
  192. package/src/time-series/resolve-context.ts +6 -0
  193. package/src/time-series/resolve.ts +39 -2
  194. package/src/time-series/types.ts +2 -1
  195. package/src/types/financials.ts +9 -1
  196. package/src/types/headless.ts +1 -0
  197. package/src/types/issuer-listings.ts +2 -0
  198. package/src/types/plugin-notifications.ts +3 -0
  199. package/src/types/price-history.ts +6 -4
  200. package/src/ui/host.tsx +2 -0
  201. package/src/utils/exchange-announcements.ts +7 -2
  202. package/src/utils/fundamentals.ts +40 -0
  203. package/src/utils/network-failure.ts +2 -0
  204. package/src/utils/price-history-integrity.ts +9 -1
@@ -0,0 +1,21 @@
1
+ import { useCallback } from "react";
2
+ import { useAsyncResource } from "../../../../react/async-resource";
3
+ import { listingBoardLot, statesBoardLot } from "../../../../market-data/ah-pair";
4
+ import { useAssetData } from "../../../runtime";
5
+
6
+ /**
7
+ * The shares one lot of an HKEX or SGX listing trades in, from its company's
8
+ * listings as Gloom Cloud holds them (`getIssuerListings`, the read an A+H
9
+ * line's DES already makes); null for a listing elsewhere, while it loads, or
10
+ * when none is stated.
11
+ */
12
+ export function useListingBoardLot(symbol: string | null | undefined, exchange: string | null | undefined): number | null {
13
+ const dataProvider = useAssetData();
14
+ const reads = statesBoardLot(symbol, exchange) && !!dataProvider?.getIssuerListings;
15
+ const loader = useCallback(
16
+ () => dataProvider!.getIssuerListings!(symbol!, exchange ?? undefined),
17
+ [dataProvider, exchange, symbol],
18
+ );
19
+ const issuer = useAsyncResource(reads ? loader : null);
20
+ return reads && symbol ? listingBoardLot(issuer.data, symbol, exchange) : null;
21
+ }
@@ -160,6 +160,7 @@ export function buildOverviewStats({
160
160
  depositaryPair = null,
161
161
  ahPair = null,
162
162
  cedearRatio = null,
163
+ boardLot = null,
163
164
  today,
164
165
  dividend,
165
166
  bond = null,
@@ -187,6 +188,8 @@ export function buildOverviewStats({
187
188
  ahPair?: { other: string; side: "h" | "a"; premiumPercent: number | null; linked: boolean } | null;
188
189
  /** A Buenos Aires CEDEAR's ratio in its company's shares, as Gloom Cloud serves it. */
189
190
  cedearRatio?: CedearRatio | null;
191
+ /** The shares one lot of the listing trades in, as its exchange states it (an HKEX or SGX line). */
192
+ boardLot?: number | null;
190
193
  /** The listing's calendar day, YYYY-MM-DD; dates before it are left out. */
191
194
  today?: string;
192
195
  /** The history the dividend yield reads (useOverviewDividend): a trailing one is measured from its cash, a forward one stops with it; without it the yield stands. */
@@ -253,6 +256,10 @@ export function buildOverviewStats({
253
256
  if (finite(fundamentals?.floatShares) && fundamentals.floatShares > 0) {
254
257
  stats.push({ label: "Float", value: formatCompact(fundamentals.floatShares), ...counted(fundamentals.floatSharesAsOf) });
255
258
  }
259
+ // The shares one lot trades in, which an order on the venue is sized by.
260
+ if (boardLot != null && Number.isSafeInteger(boardLot) && boardLot > 0) {
261
+ stats.push({ label: "Board Lot", value: boardLot.toLocaleString("en-US"), detail: ["shares", "sh"] });
262
+ }
256
263
  // A receipt says how many shares it holds and a home line which receipt holds it, both opening ADR vs Home.
257
264
  if (depositaryPair) {
258
265
  const { pair, receiptSide } = depositaryPair;
@@ -336,7 +343,10 @@ export function buildOverviewStats({
336
343
  });
337
344
  }
338
345
  if (fundamentals?.revenue != null) {
339
- stats.push({ label: "Revenue", ...money(fundamentals.revenue) });
346
+ // Which twelve months the revenue, net income and margin are, as Financials' TTM column names them.
347
+ const end = fundamentals.trailingPeriodEnd;
348
+ const revenue = money(fundamentals.revenue);
349
+ stats.push({ label: "Revenue", ...revenue, ...(end && ISO_DATE.test(end) && !revenue.detail ? { detail: [`TTM to ${end}`, `to ${end}`] } : {}) });
340
350
  }
341
351
  if (fundamentals?.netIncome != null) {
342
352
  stats.push({ label: "Net Income", ...money(fundamentals.netIncome) });
@@ -19,6 +19,7 @@ import { useOpenResearchTab } from "../research-tab-navigation";
19
19
  import type { OverviewFunctionLink } from "./types";
20
20
  import { useOverviewDividend } from "./dividend";
21
21
  import { useAhPair } from "../adr-pair/ah";
22
+ import { useListingBoardLot } from "./board-lot";
22
23
  import { useTickerSnapshotState } from "../../../../market-data/hooks";
23
24
  import { taxRatesFromSettings } from "../../../../market-data/tax-equivalent";
24
25
  import { PaneLinkMenu } from "../../../../components";
@@ -41,6 +42,8 @@ export function OverviewResearchTab({ width, height, focused }: TickerResearchTa
41
42
  const dividend = useOverviewDividend(ticker?.metadata.ticker ?? null, ticker?.metadata.exchange ?? "", financials?.fundamentals);
42
43
  // An A+H company's other line and the premium between them, beside the ADR row.
43
44
  const ah = useAhPair(ticker?.metadata.ticker ?? null, ticker?.metadata.exchange || financials?.quote?.listingExchangeName, financials?.quote);
45
+ // A Hong Kong or Singapore line's board lot, the shares one lot trades in.
46
+ const boardLot = useListingBoardLot(ticker?.metadata.ticker ?? null, ticker?.metadata.exchange || financials?.quote?.listingExchangeName);
44
47
  // A pane locked to one tab has nowhere to go.
45
48
  const lockedToOneTab = getTickerResearchPaneSettings(paneInstance?.settings).hideTabs;
46
49
  // The chart's scale, once set from the pane menu, holds for every ticker the pane shows.
@@ -67,6 +70,7 @@ export function OverviewResearchTab({ width, height, focused }: TickerResearchTa
67
70
  onOpenFunction={openFunction}
68
71
  dividend={dividend}
69
72
  ah={ah}
73
+ boardLot={boardLot}
70
74
  snapshot={snapshot}
71
75
  tax={taxRatesFromSettings(paneInstance?.settings)}
72
76
  chartScale={parseOverviewChartScaleChoice(chartScale)}
@@ -12,19 +12,26 @@ import { CompanyLogo, resolveCompanyLogoSrc } from "../../../components/company-
12
12
  import { bodyLineInk, FigureText, figureLineInk, useFigureCells } from "../../../components/ui/figure";
13
13
  import { PriceReturnStrip } from "../../../components/price-performance";
14
14
  import { t } from "../../../i18n";
15
- import { useFxRateObservations, useTickerChangeNote, type TickerSnapshotState } from "../../../market-data/hooks";
15
+ import { useChartQueries, useFxRateObservations, useResolvedEntryValue, useTickerChangeNote, type TickerSnapshotState } from "../../../market-data/hooks";
16
16
  import { formatMarketPriceWithCurrency, formatSignedMarketPrice, liveQuoteFormatOptions } from "../../../market-data/market/format";
17
17
  import { priceSeriesUnit } from "../../../market-data/market/index-level";
18
18
  import {
19
19
  exchangeShortName,
20
+ extendedPrintTime,
20
21
  extendedSessionLineLabel,
21
22
  getExtendedSessionDisplay,
22
23
  getRegularSessionDisplay,
24
+ headlineCloseDate,
23
25
  quoteSessionColor,
24
26
  quoteSessionLabel,
25
27
  } from "../../../market-data/market/status";
26
- import { appendQuoteToPriceReturnHistory, buildPriceReturnFields } from "../../../market-data/performance";
27
- import { changeBasisLabel, changeBasisNote, futuresQuoteFromSettle, quoteChangeBasis, quoteSettleText } from "../../../market-data/market/change-basis";
28
+ import { buildPriceReturnFields, headlinePriceReturnEnd, priceReturnDailyWindow, priceReturnIntegrityNotice } from "../../../market-data/performance";
29
+ import type { ChartRequest } from "../../../market-data/request-types";
30
+ import { buildChartKey } from "../../../market-data/selectors";
31
+ import { changeBasisLabel, changeBasisNote, closeDayLabel, futuresQuoteFromSettle, quoteChangeBasis, quoteSettleText } from "../../../market-data/market/change-basis";
32
+ import { asOfClock } from "../../../market-data/quotes/time";
33
+ import { useRemoteUiNode } from "../../../remote/semantic-tree";
34
+ import { quoteObservation } from "../shared/report-freshness";
28
35
  import {
29
36
  fitFuturesContractLines, futuresContractLines, isFuturesInstrument, futuresPricePer, usdPerMmbtu, usdPerMmbtuText,
30
37
  type FuturesContractLine,
@@ -39,7 +46,8 @@ import { Box, ScrollBox, Text, useUiCapabilities } from "../../../ui";
39
46
  import { publicTickerKey, resolveExchangeTimeZone } from "../../../utils/exchanges";
40
47
  import { convertCurrency, displayWidth, formatPercentRaw, truncateToDisplayWidth } from "../../../utils/format";
41
48
  import {
42
- appTtmRate, enterpriseValueGapIsLarge, enterpriseValueReconciliationNote, trailingEpsFiscalYear, ttmAtAppRate, ttmConversionNote, withFinancialEnterpriseValue,
49
+ appTtmRate, baseCurrencyFiguresNote, enterpriseValueGapIsLarge, enterpriseValueReconciliationNote, trailingEpsFiscalYear, ttmAtAppRate,
50
+ ttmConversionNote, withFinancialEnterpriseValue,
43
51
  } from "../../../utils/fundamentals";
44
52
  import { servedRatesNotMeaningful } from "../../../utils/served-rates";
45
53
  import { atRegularSessionPrice } from "../../../market-data/quotes/regular-session-valuation";
@@ -122,6 +130,8 @@ interface OverviewTabProps {
122
130
  dividend?: OverviewDividendState;
123
131
  /** An A+H company's other line and how the two prices compare (useAhPair); none for any other listing. */
124
132
  ah?: AhPairState | null;
133
+ /** The shares one lot of an HKEX or SGX line trades in (useListingBoardLot); none elsewhere. */
134
+ boardLot?: number | null;
125
135
  /** Where the ticker's snapshot load stands (useTickerSnapshotState), for the state shown before anything of it is in. */
126
136
  snapshot?: TickerSnapshotState;
127
137
  /** The rates `fn DES --tax-rate` set (taxRatesFromSettings): a fund's tax-equivalent yield and muni/Treasury ratio follow its facts. */
@@ -162,7 +172,7 @@ export function OverviewTab(props: OverviewTabProps) {
162
172
  const FUND_FACTS_LINK: OverviewFunctionLink = { name: "Fund Facts", templateId: "sec-etf-pane" };
163
173
 
164
174
  function ResolvedOverviewTab({
165
- width, height, focused = false, ticker, financials, onOpenChart, onOpenFunction, perpetuals, news, dividend, ah = null, tax = null,
175
+ width, height, focused = false, ticker, financials, onOpenChart, onOpenFunction, perpetuals, news, dividend, ah = null, boardLot = null, tax = null,
166
176
  chartScale: chartScaleChoice = "auto", onChartScaleChange,
167
177
  }: OverviewTabProps & { ticker: TickerRecord }) {
168
178
  const trade = useResearchTrading();
@@ -180,6 +190,13 @@ function ResolvedOverviewTab({
180
190
 
181
191
  const quote = financials?.quote;
182
192
  const quoteDelayMinutes = useDelayedMarkMinutes(quote);
193
+ // `fn DES` and a capture are dated by the quote the header shows, as `quote` dates it: its last print,
194
+ // its delay and its session, the time it was read after them.
195
+ useRemoteUiNode(quote ? {
196
+ role: "report-freshness",
197
+ label: "Quote freshness",
198
+ getMetadata: () => ({ observations: [quoteObservation(quote, Date.now())] }),
199
+ } : null);
183
200
  const fundamentals = financials?.fundamentals;
184
201
  const capitalization = liveMarketCapitalization(quote, fundamentals);
185
202
  const profile = financials?.profile;
@@ -255,6 +272,16 @@ function ResolvedOverviewTab({
255
272
  const unknownHistoryBasis = hasUnknownBondHistoryBasis(quote, ticker.metadata.assetCategory, financials?.quoteMetadata?.instrumentType);
256
273
  const historyQuote = unknownHistoryBasis ? undefined : quote;
257
274
  const chartHistory = appendLiveQuotePoint(financials?.priceHistory ?? [], historyQuote);
275
+ // Five years of daily closes, which the Price Return strip measures each horizon on: the chart's bars are weekly.
276
+ const returnInstrument = useMemo(() => instrumentFromTicker(ticker), [ticker]);
277
+ const returnWindowDay = new Date().toISOString().slice(0, 10);
278
+ const dailyReturnsRequest = useMemo<ChartRequest | null>(() => {
279
+ if (!returnInstrument || unknownHistoryBasis) return null;
280
+ const { start, end } = priceReturnDailyWindow(Date.parse(`${returnWindowDay}T12:00:00Z`));
281
+ return { instrument: returnInstrument, bufferRange: "5Y", granularity: "detail", barSize: "1d", startDate: start, endDate: end };
282
+ }, [returnInstrument, returnWindowDay, unknownHistoryBasis]);
283
+ const dailyReturnEntries = useChartQueries(dailyReturnsRequest ? [dailyReturnsRequest] : []);
284
+ const dailyReturnBars = useResolvedEntryValue(dailyReturnsRequest ? dailyReturnEntries.get(buildChartKey(dailyReturnsRequest)) ?? null : null);
258
285
  const chartDelta = (chartHistory.at(-1)?.close ?? 0) - (chartHistory[0]?.close ?? 0);
259
286
  const chartTimeZone = resolveExchangeTimeZone(
260
287
  ticker.metadata.exchange || quote?.listingExchangeName || quote?.exchangeName,
@@ -269,6 +296,15 @@ function ResolvedOverviewTab({
269
296
  panelId: "price",
270
297
  timeBasis: chartTimeZone ? { kind: "market", timeZone: chartTimeZone } : undefined,
271
298
  });
299
+ // Each horizon runs from the daily close on its start date to the headline's close, as CMP and `history` measure
300
+ // it; the chart's weekly bars stand in until the daily ones are in. Bars and the quote are dated on the listing's clock.
301
+ const returnVenue = ticker.metadata.exchange || quote?.listingExchangeName || quote?.exchangeName || undefined;
302
+ const performanceFields = buildPriceReturnFields(
303
+ dailyReturnBars?.length ? dailyReturnBars : financials?.priceHistory ?? [],
304
+ returnVenue,
305
+ undefined,
306
+ historyQuote ? headlinePriceReturnEnd(historyQuote, returnVenue) : null,
307
+ );
272
308
  // Years of history from a few dollars to hundreds read on a log axis, the Chart tab's own, so the early ones do not lie flat.
273
309
  const autoChartScale = autoOverviewChartScale(priceSeries.points, { rate: isYieldIndexSymbol(ticker.metadata.ticker) });
274
310
  const chartScale = resolveOverviewChartScale(chartScaleChoice, autoChartScale);
@@ -291,8 +327,11 @@ function ResolvedOverviewTab({
291
327
  // A converted TTM block names what it was converted from, at the pane's rate and its time.
292
328
  const ttmNote = [shownFundamentals?.revenue, shownFundamentals?.netIncome, shownFundamentals?.freeCashFlow].some((value) => value != null)
293
329
  ? ttmConversionNote(shownFundamentals) : undefined;
330
+ // A cap shown in the base currency too (7.80T ARS, 5.03B USD) says at what rate, and when it was read.
331
+ const capRateNote = capitalization ? baseCurrencyFiguresNote(capitalization.currency, baseCurrency, fxObservations) : undefined;
294
332
  // FB lists a fund now, and Meta trades as META: said for someone who typed FB meaning the company, as `quote FB` says it.
295
333
  const changeNote = useTickerChangeNote(ticker.metadata.ticker, ticker, quote);
334
+ const returnIntegrityNotice = priceReturnIntegrityNotice(performanceFields);
296
335
  usePaneNoticeFooter({
297
336
  registrationId: "overview-notices",
298
337
  notices: [
@@ -300,10 +339,13 @@ function ResolvedOverviewTab({
300
339
  ...(!quote && financials ? [t("Current quote unavailable. Other research data is still available.")] : []),
301
340
  ...(runwayOfferingNote ? [runwayOfferingNote] : []),
302
341
  ...(runway?.trailingGap === "short-history" ? [`Runway TTM: ${SHORT_RUNWAY_HISTORY}.`] : []),
303
- ...(priceSeries.warning ? [priceSeries.warning] : []),
342
+ // A bar with contradictory prices is said only where it leaves a shown return blank: on a chart of years one
343
+ // bar's gap is a hairline that changes no figure, and a return reads only the bars at its ends.
344
+ ...(returnIntegrityNotice ? [returnIntegrityNotice] : []),
304
345
  ...(hiddenOnLog > 0 ? [logScaleHiddenWarning(priceSeries.label, hiddenOnLog)] : []),
305
346
  ...(enterpriseValueNote ? [enterpriseValueNote] : []),
306
347
  ...(ttmNote ? [ttmNote] : []),
348
+ ...(capRateNote ? [capRateNote] : []),
307
349
  ...(capitalization?.provenance.kind === "fundamentals" && !capitalization.live
308
350
  ? [`Market cap: ${describeFundamentalMarketCap(capitalization.provenance)}.`] : []),
309
351
  ],
@@ -329,7 +371,13 @@ function ResolvedOverviewTab({
329
371
  const quoteChangeText = sessionQuote && !delisted ? formatSignedMarketPrice(sessionQuote.change, moneyOptions) : "";
330
372
  const quotePercentText = sessionQuote && !delisted ? `(${formatPercentRaw(sessionQuote.changePercent)})` : "";
331
373
  const changeBasis = delisted ? null : quoteChangeBasis(movedQuote, { terms: contractTerms });
332
- const changeBasisText = changeBasis ? changeBasisLabel(changeBasis) : "";
374
+ // Once the session is over the headline is its close, dated apart from the extended print below it:
375
+ // "Tue 17 Nov close · vs Mon 16 Nov close". A future's settle is dated on its own line.
376
+ const closeDate = contractTerms ? null : headlineCloseDate(movedQuote);
377
+ const changeBasisText = [
378
+ closeDate ? closeDayLabel(closeDate) : "",
379
+ changeBasis ? changeBasisLabel(changeBasis) : "",
380
+ ].filter(Boolean).join(" \u00b7 ");
333
381
  // The days the venue was closed since that close, under the move: "HKEX closed Mon 19 Oct, holiday".
334
382
  const changeBasisNoteText = changeBasisNote(changeBasis);
335
383
  // The pane title already names the ticker, so the line leads with the company and drops a name that only repeats it.
@@ -379,7 +427,11 @@ function ResolvedOverviewTab({
379
427
  : "";
380
428
  // The extended session's line keeps its label and price whole on a narrow pane: the move gives
381
429
  // way to its percent, then goes, rather than wrapping a figure across two lines ("(+0." / "08%)").
382
- const extendedLabelText = extendedQuote ? `${extendedSessionLineLabel(extendedQuote, t)}:` : "";
430
+ // The extended print says when it was observed (After-Hours 00:10 UTC), as the close above says its day.
431
+ const extendedTime = extendedQuote ? extendedPrintTime(quote) : null;
432
+ const extendedLabelText = extendedQuote
433
+ ? `${extendedSessionLineLabel(extendedQuote, t)}${extendedTime != null ? ` ${asOfClock(Math.min(extendedTime, Date.now()))}` : ""}:`
434
+ : "";
383
435
  const extendedPriceText = extendedQuote ? formatMarketPriceWithCurrency(extendedQuote.price, quote?.currency, moneyOptions) : "";
384
436
  const extendedMoveText = extendedQuote
385
437
  ? [
@@ -450,6 +502,7 @@ function ResolvedOverviewTab({
450
502
  depositaryReceipt: sharesOutstandingInReceipts(quote, fundamentals, description),
451
503
  depositaryPair: depositaryPair ? { pair: depositaryPair, receiptSide: isReceiptSide(financials) } : null,
452
504
  cedearRatio: listingCedearRatio(financials),
505
+ boardLot,
453
506
  // Report and ex-dividend dates are the listing's calendar days.
454
507
  today: zonedDateKey(Date.now(), chartTimeZone ?? "America/New_York"),
455
508
  dividend,
@@ -466,11 +519,6 @@ function ResolvedOverviewTab({
466
519
  profile,
467
520
  isin: ticker.metadata.isin,
468
521
  });
469
- // Bars and the quote are dated on the listing's clock.
470
- const performanceFields = buildPriceReturnFields(
471
- appendQuoteToPriceReturnHistory(financials?.priceHistory ?? [], historyQuote),
472
- ticker.metadata.exchange || quote?.listingExchangeName || quote?.exchangeName || undefined,
473
- );
474
522
  const hasPerformance = performanceFields.some((field) => field.value != null || field.unavailableReason);
475
523
  const positionRows = buildPositionRows({
476
524
  ticker,
@@ -4,7 +4,7 @@ import { ChartTableHeader, CurveSurface, curveGhostColors, DataTableView, format
4
4
  import { curveStrip, curveSurfaceMinRows } from "../../../components/chart/curve";
5
5
  import { savedCopyFooterInfo } from "../../../components/layout/pane/footer";
6
6
  import { STALE_SEGMENT } from "../../../components/layout/pane/status-footer";
7
- import { dropColumnsToFit } from "../../../components/ui/table-layout";
7
+ import { dropColumnsToFit, hiddenTableColumnRows } from "../../../components/ui/table-layout";
8
8
  import { useAsyncResource } from "../../../react/async-resource";
9
9
  import { usePaneRefreshKey } from "../../../components/data-table/table-pane";
10
10
  import { usePaneSettingValue, usePluginPaneState } from "../../../public/react";
@@ -184,8 +184,9 @@ export function VolatilityPane({ focused, width, height }: PaneProps) {
184
184
  ], hints: [{ id: "view", key: "v", label: "iew", onPress: cycleTab }] }), [resource.loading, result?.stale, result?.savedAt, data, asOf, observationTime, observationBasis, cycleTab]);
185
185
  const { strip: tabStrip, rows: tabRows } = usePaneTabs({ tabs: TABS, activeValue: tab, onSelect: setTab, focused, dense: true });
186
186
  const contentHeight = Math.max(5, height - tabRows);
187
+ const boardColumns = useMemo(() => dropColumnsToFit(BOARD_COLUMNS, width - 1, BOARD_DROP_ORDER), [width]);
187
188
  // The board needs only its rows; the selected index history takes the rest.
188
- const boardHeight = Math.max(5, Math.min(rows.length + 2, Math.floor(contentHeight * 0.62)));
189
+ const boardHeight = Math.max(5, Math.min(rows.length + 2 + hiddenTableColumnRows(boardColumns, rows.length), Math.floor(contentHeight * 0.62)));
189
190
  const curve = data?.curve;
190
191
  // The week- and month-back curves come from the histories the board already loaded.
191
192
  const lookbacks = useMemo(() => data ? volatilityCurveLookbacks(data) : [], [data]);
@@ -208,7 +209,6 @@ export function VolatilityPane({ focused, width, height }: PaneProps) {
208
209
  { id: "spread", label: "Spread", value: `${number(curve.slope, true)} pts` },
209
210
  ] : [];
210
211
  const ready = !!data && (data.board.some((row) => row.value != null) || data.fred.metrics.some((metric) => metric.value != null));
211
- const boardColumns = useMemo(() => dropColumnsToFit(BOARD_COLUMNS, width - 1, BOARD_DROP_ORDER), [width]);
212
212
  return <Box width={width} height={height} flexDirection="column" overflow="hidden">
213
213
  {tabStrip}
214
214
  <PaneStatusBody subject="volatility" loading={resource.loading && !ready} error={!ready ? resource.error ?? result?.errors[0] ?? null : null} empty={!resource.loading && !ready}>
@@ -9,7 +9,7 @@ import type { HeadlessPaneColumn, HeadlessPaneContext, HeadlessPaneDefinition, H
9
9
  import { formatUtcDayTime } from "../../../utils/utc-time";
10
10
  import { REFERENCE_DATA } from "../shared/report-freshness";
11
11
  import { columnValue, formatGeoValue, isChangeColumn, layerCoverageNote, parseLayerTokens, parseMapPreset, plainGeoValue, resolveActiveLayers, tickerLinkKey } from "./layers";
12
- import { filterWorldVenues, formatVenueLocalTime } from "./model";
12
+ import { filterWorldVenues, formatVenueLocalTime, venueSession } from "./model";
13
13
  import { REPORT_FILTER, REPORT_ROWS } from "../shared/headless-options";
14
14
  import { mapHomeArea, mapPlaceBbox, nearestPlaces, resolveMapPlace, type MapStart } from "./place";
15
15
 
@@ -46,7 +46,8 @@ const VENUE_COLUMNS: HeadlessPaneColumn[] = [
46
46
  { key: "name", header: "Venue" },
47
47
  { key: "city", header: "City" },
48
48
  { key: "country", header: "Country" },
49
- { key: "open", header: "Open", format: (value) => (value ? "open" : "closed") },
49
+ // The state by the exchange's calendar: a holiday, or a US venue's pre-market and after-hours around its core session.
50
+ { key: "session", header: "Session" },
50
51
  { key: "localTime", header: "Local" },
51
52
  ];
52
53
 
@@ -61,6 +62,7 @@ async function venueRows(context: HeadlessPaneContext, query: string, start: Map
61
62
  name: venue.title,
62
63
  city: venue.city,
63
64
  country: venue.country,
65
+ session: venueSession(venue),
64
66
  open: venue.isOpen,
65
67
  localTime: formatVenueLocalTime(venue.timezone, now),
66
68
  lon: venue.longitude,
@@ -1,4 +1,4 @@
1
- import type { CloudWorldVenuePayload } from "../../../api-client";
1
+ import type { CloudWorldVenuePayload, WorldVenueSession } from "../../../api-client";
2
2
  import { clamp } from "../../../utils/math";
3
3
 
4
4
  export interface WorldMapPoint {
@@ -300,6 +300,11 @@ export function formatVenueLocalTime(timezone: string, now: number): string {
300
300
  return formatter.format(now);
301
301
  }
302
302
 
303
+ /** The venue's state as the service read it from the exchange's calendar, or from its core session where it says none. */
304
+ export function venueSession(venue: Pick<CloudWorldVenuePayload, "isOpen" | "session">): WorldVenueSession {
305
+ return venue.session ?? (venue.isOpen ? "open" : "closed");
306
+ }
307
+
303
308
  export function venueRemainingSeconds(
304
309
  venue: CloudWorldVenuePayload,
305
310
  checkedAt: number,
@@ -2,7 +2,7 @@ import type { CloudWorldVenuePayload } from "../../../api-client";
2
2
  import { colors } from "../../../theme/colors";
3
3
  import { CountryFlagLead } from "../../../components/ui/country-flag";
4
4
  import { Box, Text, TextAttributes, useUiCapabilities } from "../../../ui";
5
- import { formatVenueCountdown, formatVenueLocalTime, venueRemainingSeconds } from "./model";
5
+ import { formatVenueCountdown, formatVenueLocalTime, venueRemainingSeconds, venueSession } from "./model";
6
6
 
7
7
  export function SelectedVenueHeader({
8
8
  venue,
@@ -18,7 +18,9 @@ export function SelectedVenueHeader({
18
18
  const desktop = useUiCapabilities().nativePaneChrome === true;
19
19
  if (!venue) return <Box height={2} />;
20
20
  const remaining = formatVenueCountdown(venueRemainingSeconds(venue, checkedAt, now));
21
- const state = venue.isOpen ? "OPEN" : "CLOSED";
21
+ // A holiday, or a US venue's pre-market and after-hours, says so: "closed" alone read as nothing trading.
22
+ const session = venueSession(venue);
23
+ const state = session.toUpperCase();
22
24
  const transition = remaining ? `${venue.isOpen ? "closes" : "opens"} ${remaining}` : "";
23
25
  const place = (
24
26
  <Text fg={colors.textMuted}>
@@ -29,7 +31,7 @@ export function SelectedVenueHeader({
29
31
  <Box flexDirection="column" height={2} width={width} paddingX={1}>
30
32
  <Box flexDirection="row" justifyContent="space-between" width="100%">
31
33
  <Text fg={colors.textBright} attributes={TextAttributes.BOLD}>{venue.mic}</Text>
32
- <Text fg={venue.isOpen ? colors.positive : colors.textDim}>{state}</Text>
34
+ <Text fg={venue.isOpen ? colors.positive : session === "pre-market" || session === "after-hours" ? colors.warning : colors.textDim}>{state}</Text>
33
35
  </Box>
34
36
  {desktop ? (
35
37
  // The desktop and the web lead the venue's place with its country's flag.
@@ -44,6 +44,7 @@ import { clinicalTrialsPlugin } from "./builtin/clinical-trials";
44
44
  import { commentLettersPlugin } from "./builtin/comment-letters";
45
45
  import { openFdaPlugin } from "./builtin/openfda";
46
46
  import { gloomberbCloudPlugin } from "./builtin/cloud";
47
+ import { browserChatSettings } from "../renderers/browser/notifications";
47
48
  import { changelogModule } from "./builtin/changelog";
48
49
  import { roadmapModule } from "./builtin/roadmap";
49
50
  import { chartComposerModule } from "./builtin/chart-composer";
@@ -298,7 +299,15 @@ const browserEarningsPlugin = composeBuiltinPlugin({
298
299
  * browser-safe public API are absent rather than registered behind stubs.
299
300
  */
300
301
  export const browserBuiltinPlugins: readonly GloomPlugin[] = [
301
- gloomberbCloudPlugin,
302
+ {
303
+ ...gloomberbCloudPlugin,
304
+ panes: gloomberbCloudPlugin.panes?.map((pane) => pane.id === "chat"
305
+ ? Object.create(Object.getPrototypeOf(pane), {
306
+ ...Object.getOwnPropertyDescriptors(pane),
307
+ settings: { value: browserChatSettings, enumerable: true },
308
+ })
309
+ : pane),
310
+ },
302
311
  browserPortfolioPlugin,
303
312
  browserTickerCorePlugin,
304
313
  browserOptionsVolatilityPlugin,
@@ -0,0 +1,16 @@
1
+ export function isBrowserAppActive(): boolean {
2
+ return !document.hidden && document.hasFocus();
3
+ }
4
+
5
+ export function subscribeBrowserAppActivity(listener: (active: boolean) => void): () => void {
6
+ const update = () => listener(isBrowserAppActive());
7
+ window.addEventListener("focus", update);
8
+ window.addEventListener("blur", update);
9
+ document.addEventListener("visibilitychange", update);
10
+ update();
11
+ return () => {
12
+ window.removeEventListener("focus", update);
13
+ window.removeEventListener("blur", update);
14
+ document.removeEventListener("visibilitychange", update);
15
+ };
16
+ }
@@ -0,0 +1,14 @@
1
+ import { installAppBadgeHost } from "../../notifications/app-badge";
2
+
3
+ export function installBrowserAppBadgeHost(doc: Pick<Document, "title"> = document): () => void {
4
+ const title = doc.title;
5
+ const uninstall = installAppBadgeHost({
6
+ setBadge(label) {
7
+ doc.title = label ? `(${label}) ${title}` : title;
8
+ },
9
+ });
10
+ return () => {
11
+ uninstall();
12
+ doc.title = title;
13
+ };
14
+ }
@@ -20,6 +20,9 @@ import {
20
20
  import { loadWebBundledPlugins } from "./bundled-plugins";
21
21
  import { BROWSER_DATA_DIR, hasSavedBrowserConfig, installBrowserConfigStore } from "./config-host";
22
22
  import { browserRendererHost, browserUiHost } from "./ui-host";
23
+ import { installBrowserAppBadgeHost } from "./app-badge-host";
24
+ import { isBrowserAppActive } from "./activity";
25
+ import { setAppActive } from "../../state/app/activity";
23
26
  import { createBrowserDeepLinkBridge } from "./deeplink-bridge";
24
27
  import { initializeBrowserResearchActivity, recordResearchActivity } from "../../api-client/research-activity";
25
28
  import { flushPendingPersistence } from "../../state/persist-scheduler";
@@ -101,6 +104,8 @@ async function boot(): Promise<void> {
101
104
  applyLanguageFromConfig(config);
102
105
  const externalPlugins = await bundledPlugins;
103
106
  const deepLinkBridge = createBrowserDeepLinkBridge();
107
+ installBrowserAppBadgeHost();
108
+ setAppActive(isBrowserAppActive());
104
109
  root.render(
105
110
  <DomErrorBoundary label="Browser renderer crashed" fallback={(error) => (
106
111
  <div className="gloom-fatal">
@@ -0,0 +1,103 @@
1
+ import type { AppNotificationRequest, PaneSettingsDef } from "../../types/plugin";
2
+ import { logFailure } from "../../utils/log-failure";
3
+ import { isBrowserAppActive } from "./activity";
4
+
5
+ const PREFERENCE_KEY = "gloomberb:browser-notifications";
6
+
7
+ interface NotificationApi {
8
+ new(title: string, options: NotificationOptions): Pick<Notification, "onclick" | "close">;
9
+ readonly permission: NotificationPermission;
10
+ requestPermission(): Promise<NotificationPermission>;
11
+ }
12
+
13
+ interface BrowserNotificationOptions {
14
+ getApi?: () => NotificationApi | undefined;
15
+ getStorage?: () => Pick<Storage, "getItem" | "setItem" | "removeItem">;
16
+ isActive?: () => boolean;
17
+ focus?: () => void;
18
+ }
19
+
20
+ export function createBrowserNotifications({
21
+ getApi = () => typeof globalThis.Notification?.requestPermission === "function" ? globalThis.Notification : undefined,
22
+ getStorage = () => window.localStorage,
23
+ isActive = isBrowserAppActive,
24
+ focus = () => window.focus(),
25
+ }: BrowserNotificationOptions = {}) {
26
+ function isEnabled(): boolean {
27
+ try {
28
+ return getApi()?.permission === "granted" && getStorage().getItem(PREFERENCE_KEY) === "1";
29
+ } catch (error) {
30
+ logFailure("browser-notifications", "Could not read the browser notification preference")(error);
31
+ return false;
32
+ }
33
+ }
34
+
35
+ async function setEnabled(enabled: boolean): Promise<"changed" | "denied" | "dismissed" | "unavailable"> {
36
+ try {
37
+ const storage = getStorage();
38
+ if (!enabled) {
39
+ storage.removeItem(PREFERENCE_KEY);
40
+ return "changed";
41
+ }
42
+ const api = getApi();
43
+ if (!api) return "unavailable";
44
+ const permission = api.permission === "default" ? await api.requestPermission() : api.permission;
45
+ if (permission === "denied") return "denied";
46
+ if (permission !== "granted") return "dismissed";
47
+ storage.setItem(PREFERENCE_KEY, "1");
48
+ return "changed";
49
+ } catch (error) {
50
+ logFailure("browser-notifications", "Could not change the browser notification preference")(error);
51
+ return "unavailable";
52
+ }
53
+ }
54
+
55
+ function notify(request: AppNotificationRequest): boolean {
56
+ const api = getApi();
57
+ if (!api || isActive() || !isEnabled() || !request.body.trim()) return false;
58
+ try {
59
+ const banner = new api(request.title?.trim() || "Gloom", {
60
+ body: [request.subtitle, request.body].filter(Boolean).join("\n"),
61
+ tag: request.refId,
62
+ silent: true,
63
+ });
64
+ banner.onclick = () => {
65
+ focus();
66
+ banner.close();
67
+ request.action?.onClick();
68
+ };
69
+ return true;
70
+ } catch (error) {
71
+ logFailure("browser-notifications", "Could not show a browser notification")(error);
72
+ return false;
73
+ }
74
+ }
75
+
76
+ return { isSupported: () => !!getApi(), isEnabled, setEnabled, notify };
77
+ }
78
+
79
+ export const browserNotifications = createBrowserNotifications();
80
+
81
+ export function browserChatSettings(): PaneSettingsDef {
82
+ if (!browserNotifications.isSupported()) return { fields: [] };
83
+ const enabled = browserNotifications.isEnabled();
84
+ return {
85
+ fields: [{
86
+ key: "browserNotifications",
87
+ type: "action",
88
+ actionId: "browser.notifications",
89
+ label: "Browser notifications",
90
+ description: "Alerts when this tab is in the background.",
91
+ actionLabel: enabled ? "Turn off" : "Turn on",
92
+ async action({ setRowNote, notify }) {
93
+ const result = await browserNotifications.setEnabled(!browserNotifications.isEnabled());
94
+ if (result === "changed") return;
95
+ const status = result === "denied" ? "Blocked" : result === "dismissed" ? "Not enabled" : "Unavailable";
96
+ const text = result === "denied" ? "Allow notifications in your browser’s site settings." : undefined;
97
+ if (!setRowNote?.({ status, text, tone: "warning" })) {
98
+ notify({ title: "Browser notifications", body: text ?? status });
99
+ }
100
+ },
101
+ }],
102
+ };
103
+ }
@@ -2,6 +2,8 @@
2
2
  import type { RendererHost, UiHost } from "../../ui/host";
3
3
  import { safeExternalUrl } from "../../utils/external-url";
4
4
  import { createDomUiHost } from "../dom/dom-ui-host";
5
+ import { subscribeBrowserAppActivity } from "./activity";
6
+ import { browserNotifications } from "./notifications";
5
7
 
6
8
  export const browserUiHost: UiHost = createDomUiHost("browser", {
7
9
  nativePaneChrome: true,
@@ -16,6 +18,8 @@ export const browserRendererHost: RendererHost = {
16
18
  requestExit() {},
17
19
  canExit: false,
18
20
  notify() {},
21
+ notifyInBackground: browserNotifications.notify,
22
+ subscribeAppActivity: subscribeBrowserAppActivity,
19
23
  async openExternal(rawUrl) {
20
24
  const url = safeExternalUrl(rawUrl);
21
25
  if (!url) return;