gloomberb 0.19.3 → 0.19.4

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 (104) hide show
  1. package/package.json +2 -2
  2. package/src/api-client/errors.ts +8 -0
  3. package/src/api-client/index.ts +18 -0
  4. package/src/api-client/request.ts +295 -42
  5. package/src/api-client/socket.ts +95 -0
  6. package/src/app/keybindings/actions.ts +1 -1
  7. package/src/app/pane-runtime/index.tsx +1 -1
  8. package/src/app/pane-runtime/ticker-inspector-runtime.ts +1 -1
  9. package/src/app/pane-runtime/ticker-open-runtime.ts +1 -1
  10. package/src/app/pane-runtime/ticker-open-target.ts +12 -2
  11. package/src/cli/desktop-pane-shot-api-policy.ts +10 -2
  12. package/src/cli/desktop-pane-shot.ts +2 -1
  13. package/src/components/command-bar/action-runtime.ts +2 -0
  14. package/src/components/command-bar/commands/direct/runtime.ts +3 -3
  15. package/src/components/command-bar/helpers.ts +2 -0
  16. package/src/components/command-bar/list/model.ts +9 -0
  17. package/src/components/command-bar/pane-actions.ts +46 -35
  18. package/src/components/command-bar/pane-templates/workflow.ts +6 -0
  19. package/src/components/command-bar/panel/index.tsx +30 -3
  20. package/src/components/command-bar/panel/types.ts +7 -0
  21. package/src/components/command-bar/routes/root/results.ts +4 -4
  22. package/src/components/command-bar/routes/root/selection.ts +3 -2
  23. package/src/components/command-bar/routes/ticker-search/actions.ts +21 -16
  24. package/src/components/command-bar/routing/launch-request.ts +3 -2
  25. package/src/components/command-bar/routing/list-state.ts +4 -1
  26. package/src/components/command-bar/surface/index.tsx +15 -1
  27. package/src/components/layout/floating-pane.tsx +10 -0
  28. package/src/components/layout/pane/frame.tsx +6 -0
  29. package/src/components/layout/pane/header.tsx +244 -42
  30. package/src/components/layout/pane/index.tsx +20 -2
  31. package/src/components/layout/shell/active-drag.ts +128 -27
  32. package/src/components/layout/shell/drag/index.ts +99 -96
  33. package/src/components/layout/shell/drag/live.ts +3 -17
  34. package/src/components/layout/shell/drag/magnets.ts +198 -0
  35. package/src/components/layout/shell/drag/overlays.tsx +77 -75
  36. package/src/components/layout/shell/drag/runtime.ts +12 -7
  37. package/src/components/layout/shell/index.tsx +66 -32
  38. package/src/components/layout/shell/native/pointer-runtime.ts +7 -2
  39. package/src/components/layout/shell/native/surfaces.ts +1 -9
  40. package/src/components/layout/shell/native/window-state.ts +21 -25
  41. package/src/components/layout/shell/pane/layers.tsx +153 -24
  42. package/src/components/layout/shell/shortcuts.ts +4 -1
  43. package/src/components/layout/shell/terminal-pointer-runtime.ts +24 -1
  44. package/src/components/layout/shell/window-mode/overlays.tsx +14 -6
  45. package/src/components/layout/status-bar.tsx +75 -6
  46. package/src/core/app-runtime.ts +4 -1
  47. package/src/core/connection-health.ts +76 -1
  48. package/src/core/state/app/command-bar-launch.ts +12 -0
  49. package/src/core/state/app/layout.ts +4 -3
  50. package/src/core/state/app/types.ts +4 -1
  51. package/src/data/config/layout.ts +2 -2
  52. package/src/data/config/store/fold-panes.ts +6 -1
  53. package/src/i18n/es.ts +8 -1
  54. package/src/i18n/ja.ts +8 -1
  55. package/src/i18n/ko.ts +8 -1
  56. package/src/i18n/zh-cn.ts +8 -1
  57. package/src/i18n/zh-tw.ts +8 -1
  58. package/src/layout/pane-follow.ts +3 -2
  59. package/src/layout/pane-layout-move.ts +2 -1
  60. package/src/layout/pane-manager/dock-stack.ts +38 -0
  61. package/src/layout/pane-manager/dock-tree.ts +76 -15
  62. package/src/layout/pane-manager/docking.ts +48 -6
  63. package/src/layout/pane-manager/floating-actions.ts +12 -3
  64. package/src/layout/pane-manager/floating-placement.ts +189 -0
  65. package/src/layout/pane-manager/floating.ts +23 -4
  66. package/src/layout/pane-manager/gridlock.ts +16 -4
  67. package/src/layout/pane-manager/hidden-panes.ts +30 -1
  68. package/src/layout/pane-manager/index.ts +2 -0
  69. package/src/layout/pane-manager/layout-state.ts +17 -0
  70. package/src/layout/pane-manager/types.ts +4 -1
  71. package/src/layout/ticker-retarget.ts +88 -0
  72. package/src/layout-marketplace/cloud.ts +9 -1
  73. package/src/market-data/connection-follow.ts +68 -0
  74. package/src/market-data/coordinator/entries.ts +15 -3
  75. package/src/market-data/coordinator/financials.ts +20 -7
  76. package/src/market-data/coordinator/index.ts +217 -4
  77. package/src/market-data/coordinator/quotes.ts +10 -0
  78. package/src/market-data/hooks.tsx +31 -0
  79. package/src/news/aggregator.ts +12 -1
  80. package/src/plugins/builtin/buildout/company/pane.tsx +2 -1
  81. package/src/plugins/builtin/buildout/model/index.ts +6 -0
  82. package/src/plugins/builtin/buildout/pane/index.tsx +2 -1
  83. package/src/plugins/builtin/chart-composer/index.tsx +13 -0
  84. package/src/plugins/builtin/chat/controller/index.ts +10 -3
  85. package/src/plugins/builtin/chat/controller/session-runtime.ts +9 -2
  86. package/src/plugins/builtin/chat/status-widget.tsx +3 -1
  87. package/src/plugins/builtin/help/index.tsx +1 -1
  88. package/src/plugins/builtin/sectors/client.ts +18 -8
  89. package/src/plugins/builtin/sectors/index.tsx +19 -5
  90. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -1
  91. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +25 -2
  92. package/src/react/async-resource.ts +12 -0
  93. package/src/remote/controller.ts +3 -1
  94. package/src/renderers/browser/app-services.ts +8 -1
  95. package/src/renderers/browser/cloud-transport.ts +6 -1
  96. package/src/renderers/cloudflare/worker.ts +24 -2
  97. package/src/renderers/dom/styles.css +32 -0
  98. package/src/shares/portable-layout.ts +99 -2
  99. package/src/sources/provider-router/index.ts +2 -2
  100. package/src/sources/provider-router/sources.ts +26 -1
  101. package/src/sync/core-contributors.ts +18 -4
  102. package/src/time-series/resolve.ts +12 -0
  103. package/src/types/config.ts +17 -1
  104. package/src/types/plugin.ts +6 -0
@@ -1,4 +1,5 @@
1
1
  import { logFailure } from "../../utils/log-failure";
2
+ import { createConcurrencyLimiter } from "../../utils/concurrency";
2
3
  import type { CachedAssetArgs, CachedAssetMethod, CachedAssetValue, DataProvider, SecFilingDocument, SecFilingItem } from "../../types/data-provider";
3
4
  import type { CorporateActionsData, OptionsChain, PricePoint, Quote, TickerFinancials } from "../../types/financials";
4
5
  import { fetchHistoryResult, type HistoryResultRequest } from "../../sources/history-result";
@@ -55,6 +56,7 @@ import {
55
56
  classifyError,
56
57
  createAttempt,
57
58
  errorEntry,
59
+ hasFailedLoad,
58
60
  hasFreshEntryData,
59
61
  hasFreshReadyEntry,
60
62
  readyChartEntry,
@@ -112,6 +114,33 @@ const STREAM_QUOTE_BASELINE_LIMIT = 256;
112
114
  * cap if this ceiling turns out to be too generous for it.
113
115
  */
114
116
  const RETAINED_ENTRIES_PER_STORE = 64;
117
+ /**
118
+ * Past this many remembered reloads, those for keys no pane watches are
119
+ * dropped. A session browses hundreds of symbols; only what is on screen is
120
+ * asked again after an outage.
121
+ */
122
+ const REMEMBERED_RELOADS_PRUNE_AT = 512;
123
+ const outageReloadFailed = logFailure("market-data.coordinator.index", "Loading again after an outage failed");
124
+ /**
125
+ * The least time between two sweeps of what an outage failed
126
+ * (`reloadAfterOutage`): a link that keeps dropping and coming back is asked
127
+ * again once in this window, at its end, not at every flip.
128
+ */
129
+ const OUTAGE_RELOAD_MIN_INTERVAL_MS = 10_000;
130
+ /**
131
+ * How many loads a sweep after an outage runs at once, beside the one batch
132
+ * for quotes and the one for snapshots: a layout of charts and tables must
133
+ * not send its whole backlog in the same instant.
134
+ */
135
+ const OUTAGE_RELOAD_CONCURRENCY = 4;
136
+
137
+ /** How a key a load wrote is asked again after an outage (`reloadAfterOutage`). */
138
+ interface RememberedReload {
139
+ entry: () => QueryEntry<unknown>;
140
+ reload: () => Promise<unknown>;
141
+ /** A quote or snapshot, asked again with the others of its kind in one batch request. */
142
+ batch?: { kind: "quote" | "snapshot"; instrument: InstrumentRef };
143
+ }
115
144
 
116
145
  // A store hands out a fresh idle entry for every key it has never seen, so
117
146
  // two idle reads of the same key must count as the same entry.
@@ -133,6 +162,30 @@ export class MarketDataCoordinator {
133
162
  private destroyed = false;
134
163
  private readonly cachedQueries = new Map<string, { query: CachedQueryHandle<unknown>; dispose: () => void }>();
135
164
  private readonly streamQuoteBaselines = new Map<string, { baseline: TickerFinancials | null; readAt: number }>();
165
+ /**
166
+ * How to ask again for each key a load wrote, so what an outage failed is
167
+ * asked again for the panes still showing it once the data service answers
168
+ * (`reloadAfterOutage`).
169
+ */
170
+ private readonly reloads = new Map<string, RememberedReload>();
171
+ private reloadsPruneAt = REMEMBERED_RELOADS_PRUNE_AT;
172
+ /** When the last sweep after an outage ran, and the one waiting out OUTAGE_RELOAD_MIN_INTERVAL_MS. */
173
+ private lastOutageSweepAt = Number.NEGATIVE_INFINITY;
174
+ private outageSweepTimer: ReturnType<typeof setTimeout> | null = null;
175
+ /** Loads in flight at a sweep that then failed, asked again together. */
176
+ private outageRetries: RememberedReload[] = [];
177
+ private outageRetryTimer: ReturnType<typeof setTimeout> | null = null;
178
+ private readonly outageReloadGate = createConcurrencyLimiter(OUTAGE_RELOAD_CONCURRENCY);
179
+ /** When the data service last answered again after an outage: a failure before it no longer holds a load back. */
180
+ private failuresBefore = 0;
181
+ /**
182
+ * Since when the quote stream has been down, while it is down
183
+ * (`setQuoteStreamDown`): a streamed quote nothing refreshed since reads as
184
+ * stale. Null while the stream runs.
185
+ */
186
+ private quoteStreamDownSince: number | null = null;
187
+ /** Quote entries as read while the stream is down, so each keeps one identity for its readers. */
188
+ private interruptedQuoteEntries = new WeakMap<QueryEntry<Quote>, QueryEntry<Quote>>();
136
189
 
137
190
  private readonly retained: QueryStoreRetention = {
138
191
  maxRetainedEntries: RETAINED_ENTRIES_PER_STORE,
@@ -232,7 +285,39 @@ export class MarketDataCoordinator {
232
285
  }
233
286
 
234
287
  getQuoteEntry(instrument: InstrumentRef): QueryEntry<Quote> {
235
- return this.quoteStore.get(buildQuoteKey(instrument));
288
+ const key = buildQuoteKey(instrument);
289
+ const entry = this.quoteStore.get(key);
290
+ if (!this.isInterruptedQuote(key, entry, [entry])) return entry;
291
+ let interrupted = this.interruptedQuoteEntries.get(entry);
292
+ if (!interrupted) {
293
+ const quote = resolveEntryData(entry)!;
294
+ const stale = { ...quote, stale: true as const };
295
+ interrupted = { ...entry, data: stale, lastGoodData: entry.lastGoodData === quote ? stale : entry.lastGoodData };
296
+ this.interruptedQuoteEntries.set(entry, interrupted);
297
+ }
298
+ return interrupted;
299
+ }
300
+
301
+ /**
302
+ * The quote stream went down at `since`, or runs again (null). While it is
303
+ * down, a quote a pane streams that nothing refreshed since reads as stale,
304
+ * so a price that stopped moving says so instead of passing for live. The
305
+ * held quote itself is kept: the next tick, or a refresh, replaces it.
306
+ */
307
+ setQuoteStreamDown(since: number | null): void {
308
+ if (this.destroyed || this.quoteStreamDownSince === since) return;
309
+ this.quoteStreamDownSince = since;
310
+ this.interruptedQuoteEntries = new WeakMap();
311
+ for (const key of this.quoteSubscriptionManager.streamingKeys()) this.events.bump(key);
312
+ }
313
+
314
+ /** A streamed quote shown from entries none of which was written since the stream went down. */
315
+ private isInterruptedQuote(key: string, quoteEntry: QueryEntry<Quote>, entries: ReadonlyArray<QueryEntry<unknown>>): boolean {
316
+ const since = this.quoteStreamDownSince;
317
+ if (since == null) return false;
318
+ const quote = resolveEntryData(quoteEntry);
319
+ return !!quote && quote.stale !== true && this.quoteSubscriptionManager.isStreaming(key)
320
+ && entries.every((entry) => (entry.fetchedAt ?? 0) <= since);
236
321
  }
237
322
 
238
323
  getSnapshotEntry(instrument: InstrumentRef): QueryEntry<TickerFinancials> {
@@ -277,25 +362,34 @@ export class MarketDataCoordinator {
277
362
  snapshotEntry: QueryEntry<TickerFinancials>;
278
363
  quoteEntry: QueryEntry<Quote>;
279
364
  chartEntry: QueryEntry<PricePoint[]>;
365
+ streamDownSince: number | null;
280
366
  financials: TickerFinancials | null;
281
367
  }>();
282
368
 
283
369
  getTickerFinancialsSync(instrument: InstrumentRef): TickerFinancials | null {
284
370
  const key = buildSnapshotKey(instrument);
371
+ const quoteKey = buildQuoteKey(instrument);
285
372
  const snapshotEntry = this.getSnapshotEntry(instrument);
286
- const quoteEntry = this.getQuoteEntry(instrument);
373
+ // The quote as stored: it is resolved against the snapshot's first, and marked stale after.
374
+ const quoteEntry = this.quoteStore.get(quoteKey);
287
375
  const chartEntry = this.getChartEntry(createBaselineChartRequest(instrument));
376
+ const streamDownSince = this.quoteStreamDownSince;
288
377
  const cached = this.financialsSnapshotCache.get(key);
289
378
  if (
290
379
  cached
291
380
  && sameQueryEntry(cached.snapshotEntry, snapshotEntry)
292
381
  && sameQueryEntry(cached.quoteEntry, quoteEntry)
293
382
  && sameQueryEntry(cached.chartEntry, chartEntry)
383
+ && cached.streamDownSince === streamDownSince
294
384
  ) {
295
385
  return cached.financials;
296
386
  }
297
- const financials = buildTickerFinancialsSnapshot(snapshotEntry, quoteEntry, chartEntry);
298
- this.financialsSnapshotCache.set(key, { snapshotEntry, quoteEntry, chartEntry, financials });
387
+ let financials = buildTickerFinancialsSnapshot(snapshotEntry, quoteEntry, chartEntry);
388
+ // Marked after the quote is resolved: a stale streamed quote must not hand the price back to an older snapshot's.
389
+ if (financials?.quote && financials.quote.stale !== true && this.isInterruptedQuote(quoteKey, quoteEntry, [quoteEntry, snapshotEntry])) {
390
+ financials = { ...financials, quote: { ...financials.quote, stale: true } };
391
+ }
392
+ this.financialsSnapshotCache.set(key, { snapshotEntry, quoteEntry, chartEntry, streamDownSince, financials });
299
393
  return financials;
300
394
  }
301
395
 
@@ -359,6 +453,102 @@ export class MarketDataCoordinator {
359
453
  }
360
454
  }
361
455
 
456
+ /** Remembers how to ask again for `key` (`reloadAfterOutage`). */
457
+ private rememberReload<T>(key: string, store: QueryStore<T>, reload: () => Promise<unknown>, batch?: RememberedReload["batch"]): void {
458
+ this.reloads.set(key, { entry: () => store.get(key), reload, batch });
459
+ if (this.reloads.size <= this.reloadsPruneAt) return;
460
+ for (const remembered of this.reloads.keys()) {
461
+ if (!this.events.hasKeyListeners(remembered)) this.reloads.delete(remembered);
462
+ }
463
+ this.reloadsPruneAt = Math.max(REMEMBERED_RELOADS_PRUNE_AT, this.reloads.size * 2);
464
+ }
465
+
466
+ /**
467
+ * The data service answers again after an outage. A failure from before now
468
+ * no longer holds a load back, and what a pane still shows that failed is
469
+ * asked again (`sweepAfterOutage`), at most once per
470
+ * OUTAGE_RELOAD_MIN_INTERVAL_MS: a recovery inside that window is swept at
471
+ * its end.
472
+ */
473
+ reloadAfterOutage(): void {
474
+ if (this.destroyed) return;
475
+ this.failuresBefore = Date.now();
476
+ if (this.outageSweepTimer) return;
477
+ const waitMs = this.lastOutageSweepAt + OUTAGE_RELOAD_MIN_INTERVAL_MS - Date.now();
478
+ if (waitMs <= 0) {
479
+ this.sweepAfterOutage();
480
+ return;
481
+ }
482
+ const timer = setTimeout(() => {
483
+ this.outageSweepTimer = null;
484
+ this.sweepAfterOutage();
485
+ }, waitMs);
486
+ (timer as { unref?: () => void }).unref?.();
487
+ this.outageSweepTimer = timer;
488
+ }
489
+
490
+ /**
491
+ * Asks again for what a pane still shows that failed, and for what waits on
492
+ * a request sent into the outage, should that request fail. Keys no pane
493
+ * watches are left until something asks.
494
+ */
495
+ private sweepAfterOutage(): void {
496
+ if (this.destroyed) return;
497
+ this.lastOutageSweepAt = Date.now();
498
+ const failed: RememberedReload[] = [];
499
+ for (const [key, remembered] of [...this.reloads]) {
500
+ if (!this.events.hasKeyListeners(key)) {
501
+ this.reloads.delete(key);
502
+ continue;
503
+ }
504
+ const current = remembered.entry();
505
+ if (current.phase === "loading" || current.phase === "refreshing") {
506
+ // Joins the request in flight; a failure it ends in was the outage's.
507
+ void remembered.reload().then(() => {
508
+ if (hasFailedLoad(remembered.entry())) this.retryAfterOutage(remembered);
509
+ }).catch(outageReloadFailed);
510
+ } else if (hasFailedLoad(current)) {
511
+ failed.push(remembered);
512
+ }
513
+ }
514
+ void this.reloadTogether(failed);
515
+ }
516
+
517
+ /** A load in flight at a sweep failed: asked again with the others that fail with it (one deadline, one dropped connection). */
518
+ private retryAfterOutage(remembered: RememberedReload): void {
519
+ if (this.destroyed) return;
520
+ this.outageRetries.push(remembered);
521
+ if (this.outageRetryTimer) return;
522
+ this.outageRetryTimer = setTimeout(() => {
523
+ this.outageRetryTimer = null;
524
+ const retries = this.outageRetries;
525
+ this.outageRetries = [];
526
+ void this.reloadTogether(retries);
527
+ }, 0);
528
+ }
529
+
530
+ /**
531
+ * Asks again for keys an outage failed: the quotes in one batch request,
532
+ * the snapshots in another, and the rest OUTAGE_RELOAD_CONCURRENCY at a
533
+ * time, rather than one request per symbol all at once.
534
+ */
535
+ private async reloadTogether(remembered: readonly RememberedReload[]): Promise<void> {
536
+ const quotes: InstrumentRef[] = [];
537
+ const snapshots: InstrumentRef[] = [];
538
+ const rest: Array<() => Promise<unknown>> = [];
539
+ for (const { batch, reload } of remembered) {
540
+ if (batch?.kind === "quote") quotes.push(batch.instrument);
541
+ else if (batch?.kind === "snapshot") snapshots.push(batch.instrument);
542
+ else rest.push(reload);
543
+ }
544
+ const runs: Array<() => Promise<unknown>> = [...rest];
545
+ if (quotes.length > 0) runs.unshift(() => this.loadQuotesBatch(quotes));
546
+ if (snapshots.length > 0) runs.unshift(() => this.loadSnapshotsBatch(snapshots));
547
+ await Promise.all(runs.map((run) => this.outageReloadGate(async () => {
548
+ if (!this.destroyed) await run();
549
+ }).catch(outageReloadFailed)));
550
+ }
551
+
362
552
  private runSingleFlight<T>(key: string, task: () => Promise<T>): Promise<T> {
363
553
  const existing = this.inFlight.get(key);
364
554
  if (existing) {
@@ -375,12 +565,14 @@ export class MarketDataCoordinator {
375
565
  instrument: InstrumentRef,
376
566
  options: { forceRefresh?: boolean } = {},
377
567
  ): Promise<QueryEntry<TickerFinancials>> {
568
+ this.rememberReload(buildSnapshotKey(instrument), this.snapshotStore, () => this.loadSnapshot(instrument), { kind: "snapshot", instrument });
378
569
  return loadFinancialsSnapshotEntry({
379
570
  dataProvider: this.dataProvider,
380
571
  instrument,
381
572
  options,
382
573
  runSingleFlight: (key, task) => this.runSingleFlight(key, task),
383
574
  stores: this.financialCacheStores,
575
+ failuresBefore: this.failuresBefore,
384
576
  });
385
577
  }
386
578
 
@@ -388,12 +580,16 @@ export class MarketDataCoordinator {
388
580
  instruments: InstrumentRef[],
389
581
  options: { forceRefresh?: boolean } = {},
390
582
  ): Promise<QueryEntry<TickerFinancials>[]> {
583
+ for (const instrument of instruments) {
584
+ this.rememberReload(buildSnapshotKey(instrument), this.snapshotStore, () => this.loadSnapshot(instrument), { kind: "snapshot", instrument });
585
+ }
391
586
  return loadFinancialsSnapshotBatch({
392
587
  dataProvider: this.dataProvider,
393
588
  instruments,
394
589
  options,
395
590
  runSingleFlight: (key, task) => this.runSingleFlight(key, task),
396
591
  stores: this.financialCacheStores,
592
+ failuresBefore: this.failuresBefore,
397
593
  });
398
594
  }
399
595
 
@@ -401,6 +597,7 @@ export class MarketDataCoordinator {
401
597
  instrument: InstrumentRef,
402
598
  options: { forceRefresh?: boolean } = {},
403
599
  ): Promise<QueryEntry<Quote>> {
600
+ this.rememberReload(buildQuoteKey(instrument), this.quoteStore, () => this.loadQuote(instrument), { kind: "quote", instrument });
404
601
  return loadQuoteEntry({
405
602
  dataProvider: this.dataProvider,
406
603
  instrument,
@@ -415,6 +612,9 @@ export class MarketDataCoordinator {
415
612
  instruments: InstrumentRef[],
416
613
  options: { forceRefresh?: boolean } = {},
417
614
  ): Promise<QueryEntry<Quote>[]> {
615
+ for (const instrument of instruments) {
616
+ this.rememberReload(buildQuoteKey(instrument), this.quoteStore, () => this.loadQuote(instrument), { kind: "quote", instrument });
617
+ }
418
618
  return loadQuoteBatchEntries({
419
619
  dataProvider: this.dataProvider,
420
620
  instruments,
@@ -431,6 +631,7 @@ export class MarketDataCoordinator {
431
631
  ): Promise<QueryEntry<PricePoint[]>> {
432
632
  const key = buildChartKey(request);
433
633
  this.chartRequests.set(key, request);
634
+ this.rememberReload(key, this.chartStore, () => this.loadChart(request));
434
635
  const current = this.chartStore.get(key);
435
636
  const currentData = normalizeFreshChartData(resolveEntryData(current), request, current.history, current.fetchedAt);
436
637
  if (!options.forceRefresh && currentData.length > 0 && hasFreshEntryData(current, CHART_CACHE_TTL_MS)) {
@@ -491,6 +692,7 @@ export class MarketDataCoordinator {
491
692
  options: { forceRefresh?: boolean; batch?: boolean } = {},
492
693
  ): Promise<QueryEntry<OptionsChain>> {
493
694
  const key = buildOptionsKey(request);
695
+ this.rememberReload(key, this.optionsStore, () => this.loadOptions(request, { batch: options.batch }));
494
696
  const loadingKey = options.forceRefresh ? `${key}|refresh` : key;
495
697
  const existing = this.optionsLoads.get(loadingKey);
496
698
  if (existing) return existing;
@@ -535,6 +737,7 @@ export class MarketDataCoordinator {
535
737
  }
536
738
 
537
739
  async loadSecFilings(request: SecFilingsRequest, options: { forceRefresh?: boolean } = {}): Promise<QueryEntry<SecFilingItem[]>> {
740
+ this.rememberReload(buildSecFilingsKey(request), this.secFilingsStore, () => this.loadSecFilings(request));
538
741
  return this.loadCachedQuery("getSecFilings", [request.instrument.symbol, request.count ?? 50, request.instrument.exchange, toMarketDataContext(request.instrument)], buildSecFilingsKey(request), this.secFilingsStore, options.forceRefresh, (value) => value.length === 0) ?? loadSecFilingsEntry({
539
742
  forceRefresh: options.forceRefresh,
540
743
  dataProvider: this.dataProvider,
@@ -545,6 +748,7 @@ export class MarketDataCoordinator {
545
748
  }
546
749
 
547
750
  async loadSecFilingContent(filing: SecFilingItem, options: { forceRefresh?: boolean } = {}): Promise<QueryEntry<string | null>> {
751
+ this.rememberReload(buildSecContentKey(filing.accessionNumber), this.secContentStore, () => this.loadSecFilingContent(filing));
548
752
  return this.loadCachedQuery("getSecFilingContent", [filing], buildSecContentKey(filing.accessionNumber), this.secContentStore, options.forceRefresh) ?? loadSecFilingContentEntry({
549
753
  forceRefresh: options.forceRefresh,
550
754
  dataProvider: this.dataProvider,
@@ -555,6 +759,7 @@ export class MarketDataCoordinator {
555
759
  }
556
760
 
557
761
  async loadSecFilingDocuments(filing: SecFilingItem, options: { forceRefresh?: boolean } = {}): Promise<QueryEntry<SecFilingDocument[]>> {
762
+ this.rememberReload(buildSecDocumentsKey(filing.accessionNumber), this.secDocumentsStore, () => this.loadSecFilingDocuments(filing));
558
763
  return this.loadCachedQuery("getSecFilingDocuments", [filing], buildSecDocumentsKey(filing.accessionNumber), this.secDocumentsStore, options.forceRefresh, (value) => value.length === 0) ?? loadSecFilingDocumentsEntry({
559
764
  forceRefresh: options.forceRefresh,
560
765
  dataProvider: this.dataProvider,
@@ -565,6 +770,7 @@ export class MarketDataCoordinator {
565
770
  }
566
771
 
567
772
  async loadArticleSummary(url: string): Promise<QueryEntry<string | null>> {
773
+ this.rememberReload(buildArticleSummaryKey(url), this.articleSummaryStore, () => this.loadArticleSummary(url));
568
774
  return this.loadCachedQuery("getArticleSummary", [url], buildArticleSummaryKey(url), this.articleSummaryStore) ?? loadArticleSummaryEntry({
569
775
  dataProvider: this.dataProvider,
570
776
  url,
@@ -574,6 +780,7 @@ export class MarketDataCoordinator {
574
780
  }
575
781
 
576
782
  async loadFxRate(currency: string, options: { forceRefresh?: boolean } = {}): Promise<QueryEntry<number>> {
783
+ this.rememberReload(buildFxKey(currency), this.fxStore, () => this.loadFxRate(currency));
577
784
  return this.loadCachedQuery("getExchangeRate", [currency], buildFxKey(currency), this.fxStore, options.forceRefresh) ?? loadFxRateEntry({
578
785
  dataProvider: this.dataProvider,
579
786
  currency,
@@ -647,6 +854,12 @@ export class MarketDataCoordinator {
647
854
  for (const { dispose } of this.cachedQueries.values()) dispose();
648
855
  this.cachedQueries.clear();
649
856
  this.streamQuoteBaselines.clear();
857
+ this.reloads.clear();
858
+ if (this.outageSweepTimer) clearTimeout(this.outageSweepTimer);
859
+ if (this.outageRetryTimer) clearTimeout(this.outageRetryTimer);
860
+ this.outageSweepTimer = null;
861
+ this.outageRetryTimer = null;
862
+ this.outageRetries = [];
650
863
  for (const timer of this.fxLegTimers.values()) clearTimeout(timer);
651
864
  this.fxLegTimers.clear();
652
865
  }
@@ -247,6 +247,16 @@ export class QuoteSubscriptionManager {
247
247
  return dispose;
248
248
  }
249
249
 
250
+ /** Whether a pane streams this quote key now. */
251
+ isStreaming(key: string): boolean {
252
+ return (this.quoteSubscriptions.get(key)?.targets.size ?? 0) > 0;
253
+ }
254
+
255
+ /** The quote keys panes stream now. */
256
+ streamingKeys(): string[] {
257
+ return [...this.quoteSubscriptions].filter(([, entry]) => entry.targets.size > 0).map(([key]) => key);
258
+ }
259
+
250
260
  private createNoopSubscription(): QuoteSubscriptionHandle {
251
261
  const dispose = (() => {}) as QuoteSubscriptionHandle;
252
262
  dispose.update = () => {};
@@ -121,6 +121,37 @@ export function useTickerFinancials(symbol: string | null | undefined, ticker: T
121
121
  return financials;
122
122
  }
123
123
 
124
+ /** Where a ticker's snapshot load stands, for a pane with nothing of it to show yet. */
125
+ export interface TickerSnapshotState {
126
+ /** Asked for, or about to be, with no answer yet. */
127
+ loading: boolean;
128
+ /** Why the last load came back with nothing, or null. */
129
+ error: string | null;
130
+ /** Asks again now, past a recent failure. */
131
+ retry: () => Promise<void>;
132
+ }
133
+
134
+ /** The snapshot load behind `useTickerFinancials`, as its entry stands. */
135
+ export function useTickerSnapshotState(symbol: string | null | undefined, ticker: TickerRecord | null | undefined): TickerSnapshotState {
136
+ const instrument = useTickerInstrument(symbol, ticker);
137
+ const instrumentKey = instrument ? instrumentIdentityKey(instrument) : null;
138
+ const keys = useMemo(() => (instrument ? [buildSnapshotKey(instrument)] : []), [instrumentKey]);
139
+ useCoordinatorKeysVersion(keys);
140
+ const coordinator = getSharedMarketDataCoordinator();
141
+ const entry = coordinator && instrument ? coordinator.getSnapshotEntry(instrument) : null;
142
+ const retry = useCallback(async () => {
143
+ const coordinator = getSharedMarketDataCoordinator();
144
+ if (coordinator && instrument) await coordinator.loadSnapshot(instrument, { forceRefresh: true });
145
+ }, [instrumentKey]);
146
+ const failed = !!entry && (entry.phase === "error" || entry.phase === "ready") && entry.error != null;
147
+ return {
148
+ // Idle is a load the hook is about to start.
149
+ loading: !!entry && (entry.phase === "idle" || entry.phase === "loading" || entry.phase === "refreshing"),
150
+ error: failed ? entry.error!.message : null,
151
+ retry,
152
+ };
153
+ }
154
+
124
155
  function buildTickerFinancialsKeys(tickers: TickerRecord[], options: TickerInstrumentOptions = {}): string[] {
125
156
  const keys: string[] = [];
126
157
  for (const ticker of tickers) {
@@ -1,7 +1,7 @@
1
1
  import type { CompanyFrom } from "../types/company-from";
2
2
  import { logFailure } from "../utils/log-failure";
3
3
  import type { NewsCapability } from "../capabilities";
4
- import type { ConnectionHealthRegistry } from "../core/connection-health";
4
+ import { GLOOM_CLOUD_HTTP_CONNECTION_ID, type ConnectionHealthRegistry } from "../core/connection-health";
5
5
  import type { NewsAccess, NewsArticle, NewsQuery, NewsQueryState } from "./types";
6
6
  import { isAppVisible, subscribeAppVisibility } from "../state/app/activity";
7
7
  import {
@@ -113,6 +113,7 @@ export class NewsService {
113
113
  private readonly visibility: NonNullable<NewsServiceOptions["visibility"]>;
114
114
  private lastPollAt = 0;
115
115
  private unsubscribeVisibility: (() => void) | null = null;
116
+ private unsubscribeRecovery: (() => void) | null = null;
116
117
  private readonly session?: NewsSessionSignal;
117
118
  private sessionKey: string | null = null;
118
119
  /** Bumped when the session changes; a read from an older generation is dropped. */
@@ -164,6 +165,14 @@ export class NewsService {
164
165
  this.sessionKey = this.session.key();
165
166
  this.unsubscribeSession = this.session.subscribe(() => this.handleSessionChange());
166
167
  }
168
+ // A list that failed while the data service was unreachable is read again once it answers, not at the next poll.
169
+ this.unsubscribeRecovery = this.connectionHealth?.subscribeRecovery((sourceId) => {
170
+ if (sourceId !== GLOOM_CLOUD_HTTP_CONNECTION_ID || !this.polling) return;
171
+ for (const entry of this.queries.values()) {
172
+ // A list missing some of its sources is read again too, keeping what it shows meanwhile.
173
+ if (entry.refs > 0 && entry.state.error != null) void this.refreshQuery(entry.query, entry.state.phase === "error");
174
+ }
175
+ }) ?? null;
167
176
  this.scheduleNextPoll();
168
177
  }
169
178
 
@@ -173,6 +182,8 @@ export class NewsService {
173
182
  this.unsubscribeVisibility = null;
174
183
  this.unsubscribeSession?.();
175
184
  this.unsubscribeSession = null;
185
+ this.unsubscribeRecovery?.();
186
+ this.unsubscribeRecovery = null;
176
187
  this.clearPollTimer();
177
188
  }
178
189
 
@@ -31,6 +31,7 @@ import { BuildoutDetail } from "../detail";
31
31
  import { BUILDOUT_COMPANY_PANE_ID } from "./id";
32
32
  import { metricNumber, moneyText, text, tickerSearchText, tickerSymbol } from "../format";
33
33
  import type { BuildoutColumn, BuildoutRow, BuildoutUpdate } from "../model/types";
34
+ import { NOT_IN_SCREENSHOTS } from "../model";
34
35
  import { rowKey } from "../table-model";
35
36
  import { CompanyFlow, CompanyFlowList, FLOW_MIN_WIDTH } from "./flow";
36
37
  import {
@@ -210,7 +211,7 @@ export function BuildoutCompanyPane({ focused, width, height }: PaneProps) {
210
211
  }
211
212
  if (!company) {
212
213
  if (missing) return frame(<EmptyState title={`${symbol} is not in TheBuildout.`} />);
213
- if (profile.error) return frame(<PaneStatusBody error={String(profile.error)} subject="TheBuildout" retry={{ onRetry: () => void profile.load(true) }} />);
214
+ if (profile.error) return frame(<PaneStatusBody error={String(profile.error)} subject="TheBuildout" retry={String(profile.error) === NOT_IN_SCREENSHOTS ? undefined : { onRetry: () => void profile.load(true) }} />);
214
215
  return frame(<PaneStatusBody loading subject="TheBuildout" />);
215
216
  }
216
217
 
@@ -1,4 +1,5 @@
1
1
  import { apiClient } from "../../../../api-client";
2
+ import { isShotRequestRefused } from "../../../../api-client/errors";
2
3
  import { createTtlCache } from "../../../../data/ttl-cache";
3
4
  import { httpFetch } from "../../../../utils/http-transport";
4
5
  import { logFailure } from "../../../../utils/log-failure";
@@ -138,6 +139,9 @@ export interface BuildoutReader {
138
139
  token: string | null;
139
140
  }
140
141
 
142
+ /** What a pane shows in a screenshot of an account with the plan, whose token the capture never holds. */
143
+ export const NOT_IN_SCREENSHOTS = "Not available in screenshots.";
144
+
141
145
  const NO_GRANT: BuildoutGrant = { token: null, expiresAtMs: null };
142
146
  /** A token is asked for again this long before it lapses. */
143
147
  const TOKEN_RENEW_EARLY_MS = 60_000;
@@ -186,6 +190,8 @@ export async function getBuildoutReader({ fresh = false }: { fresh?: boolean } =
186
190
  const grant = await grants.load(user.id, () => issueGrant(restored !== null), { force: fresh });
187
191
  return { account: user.id, token: grant.token };
188
192
  } catch (error) {
193
+ // A capture's proxy never mints a plan's token: access is not unknown, the capture cannot carry it.
194
+ if (isShotRequestRefused(error)) throw new Error(NOT_IN_SCREENSHOTS);
189
195
  logFailure("buildout.model", "Check access failed")(error);
190
196
  throw new Error("Access check failed. Access is unknown.");
191
197
  }
@@ -34,6 +34,7 @@ import type {
34
34
  import {
35
35
  BUILDOUT_NAME,
36
36
  LOAD_MORE_THRESHOLD,
37
+ NOT_IN_SCREENSHOTS,
37
38
  buildoutApi,
38
39
  } from "../model";
39
40
  import { renderBuildoutCell } from "../cells";
@@ -447,7 +448,7 @@ export function BuildoutPane({ focused, width, height }: PaneProps) {
447
448
  <Box flexDirection="column" width={width} height={height} overflow="hidden">
448
449
  {tabStrip && <Box height={1}>{tabStrip}</Box>}
449
450
  {state.status === "loading" ? <PaneStatusBody loading subject={BUILDOUT_NAME} />
450
- : <PaneStatusBody error={state.message} subject={BUILDOUT_NAME} retry={{ onRetry: refresh }} />}
451
+ : <PaneStatusBody error={state.message} subject={BUILDOUT_NAME} retry={state.message === NOT_IN_SCREENSHOTS ? undefined : { onRetry: refresh }} />}
451
452
  </Box>
452
453
  );
453
454
  }
@@ -41,6 +41,7 @@ import {
41
41
  buildValuationChartPreset,
42
42
  } from "./presets";
43
43
  import { buildChartComposerPaneSettingsDef } from "./settings";
44
+ import { rebindResearchChartSpec } from "./chart-spec-edit";
44
45
  import type { PluginModule } from "../plugin-module";
45
46
  import {
46
47
  LIVE_STREAMING_QUICK_SETTING,
@@ -499,6 +500,17 @@ function chartShowsOneSecurity(pane: PaneInstanceConfig): boolean {
499
500
  return symbols.size === 1;
500
501
  }
501
502
 
503
+ /**
504
+ * Ticker search moves a chart of one security to another ticker: its series of that ticker move
505
+ * and keep their fields, as the research tab's chart does when its ticker changes.
506
+ */
507
+ function retargetChartTicker(pane: PaneInstanceConfig, symbol: string, previous: string | null): PaneInstanceConfig {
508
+ const spec = parseChartSpec(pane.settings?.[CHART_SPEC_SETTING_KEY]);
509
+ if (!spec) return pane;
510
+ const rebound = rebindResearchChartSpec(spec, previous, symbol);
511
+ return rebound === spec ? pane : { ...pane, settings: { ...pane.settings, [CHART_SPEC_SETTING_KEY]: rebound } };
512
+ }
513
+
502
514
  export const chartComposerModule: PluginModule = {
503
515
  // Every ticker field, asking for the ticker when charted.
504
516
  series: listFieldSeries(),
@@ -509,6 +521,7 @@ export const chartComposerModule: PluginModule = {
509
521
  component: ChartComposerPane,
510
522
  defaultPosition: "right",
511
523
  tickerFollower: chartShowsOneSecurity,
524
+ retargetTicker: retargetChartTicker,
512
525
  defaultMode: "floating",
513
526
  defaultFloatingSize: { width: 100, height: 32 },
514
527
  portableShare: { prepare: prepareChartPaneForShare },
@@ -353,12 +353,18 @@ export class ChatController {
353
353
  }
354
354
 
355
355
  /** Single-flight: every open chat pane calls this on mount. */
356
- async refreshSession(): Promise<void> {
356
+ /**
357
+ * Reads the signed-in user again. `reuseCheckWithinMs` accepts a session
358
+ * check the app made that recently instead: the web app checks its session
359
+ * before the first paint, and the status bar opening right after has
360
+ * nothing new to learn from a second request.
361
+ */
362
+ async refreshSession(options: { reuseCheckWithinMs?: number } = {}): Promise<void> {
357
363
  if (this.sessionRefreshPromise) return this.sessionRefreshPromise;
358
364
  this.realtime.stopSessionRetry();
359
365
  const generation = this.sessionRefreshGeneration;
360
366
  const isCurrent = () => generation === this.sessionRefreshGeneration;
361
- const request = this.runSessionRefresh(isCurrent)
367
+ const request = this.runSessionRefresh(isCurrent, options.reuseCheckWithinMs)
362
368
  .catch((error) => {
363
369
  if (isCurrent()) this.realtime.scheduleSessionRetry();
364
370
  throw error;
@@ -379,9 +385,10 @@ export class ChatController {
379
385
  this.sessionRefreshPromise = null;
380
386
  }
381
387
 
382
- private async runSessionRefresh(isCurrent: () => boolean): Promise<void> {
388
+ private async runSessionRefresh(isCurrent: () => boolean, reuseCheckWithinMs?: number): Promise<void> {
383
389
  return refreshChatControllerSession({
384
390
  isCurrent,
391
+ reuseCheckWithinMs,
385
392
  applySignedOut: () => this.applySignedOutSession(),
386
393
  channelStates: this.storage.channelStates,
387
394
  emit: () => this.emit(),
@@ -49,7 +49,10 @@ export function hydrateChatControllerSession({
49
49
  const storedSession = storage.readSessionState();
50
50
  const restoredUser = apiClient.getCurrentUser() ?? storedSession?.user ?? null;
51
51
  session.sessionToken = storedSession?.sessionToken ?? null;
52
- apiClient.setSessionToken(session.sessionToken);
52
+ // Installing the credential already in place would discard its session
53
+ // check: the web app, which signs in with a cookie and stores no token,
54
+ // asked the server for its session a second time on every open.
55
+ if (apiClient.getSessionToken() !== session.sessionToken) apiClient.setSessionToken(session.sessionToken);
53
56
  // WebSocket tokens are short-lived connection credentials. Reusing a persisted
54
57
  // one can trap reconnects on an expired token even while the session cookie is valid.
55
58
  apiClient.setWebSocketToken(null);
@@ -88,6 +91,8 @@ export function applySignedOutChatControllerSession({
88
91
 
89
92
  interface RefreshChatControllerSessionOptions {
90
93
  isCurrent: () => boolean;
94
+ /** Use a session check the app made within this many milliseconds instead of asking again. */
95
+ reuseCheckWithinMs?: number;
91
96
  applySignedOut: () => void;
92
97
  channelStates: Map<string, ChannelRuntimeState>;
93
98
  emit: () => void;
@@ -106,6 +111,7 @@ interface RefreshChatControllerSessionOptions {
106
111
 
107
112
  export async function refreshChatControllerSession({
108
113
  isCurrent,
114
+ reuseCheckWithinMs,
109
115
  applySignedOut,
110
116
  channelStates,
111
117
  emit,
@@ -122,7 +128,8 @@ export async function refreshChatControllerSession({
122
128
  syncVerificationPolling,
123
129
  }: RefreshChatControllerSessionOptions): Promise<void> {
124
130
  const cachedToken = session.sessionToken;
125
- const apiSession = await apiClient.getSession(isCurrent);
131
+ const recent = reuseCheckWithinMs === undefined ? undefined : apiClient.recentSession(reuseCheckWithinMs);
132
+ const apiSession = recent ? recent.user : await apiClient.getSession(isCurrent);
126
133
  if (!isCurrent()) return;
127
134
  if (!apiSession) {
128
135
  const persistedToken = apiClient.getSessionToken();
@@ -34,6 +34,8 @@ const CHIP_NAME_COLUMNS = 12;
34
34
  /** The message on arrival never takes more columns than this, and does not show in fewer than the least. */
35
35
  const PREVIEW_MOST_COLUMNS = 48;
36
36
  const PREVIEW_LEAST_COLUMNS = 12;
37
+ /** A session the app checked this recently (the web app does before its first paint) is not asked for again on mount. */
38
+ const RECENT_SESSION_CHECK_MS = 30_000;
37
39
 
38
40
  /** Who the chip names: the sender of the newest message for you, and whether it came in a DM or group chat. */
39
41
  interface ChipWho {
@@ -183,7 +185,7 @@ export function ChatStatusWidget({ controller = chatController }: ChatStatusWidg
183
185
  setUsername(nextSnapshot.user?.username ?? null);
184
186
  setHasSavedSession(nextSnapshot.hasSavedSession);
185
187
  });
186
- void controller.refreshSession().catch(() => {});
188
+ void controller.refreshSession({ reuseCheckWithinMs: RECENT_SESSION_CHECK_MS }).catch(() => {});
187
189
  return unsubscribe;
188
190
  }, [controller]);
189
191