@gloom-sh/terminal 0.19.6 → 0.20.0

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 (137) hide show
  1. package/LICENSE +0 -4
  2. package/package.json +6 -5
  3. package/patches/electrobun-devkit@2.0.5.patch +148 -0
  4. package/src/api-client/bond-trades.ts +59 -0
  5. package/src/api-client/data.ts +21 -0
  6. package/src/api-client/index.ts +2 -0
  7. package/src/api-client/types/account.ts +86 -0
  8. package/src/api-client/types/assist.ts +32 -0
  9. package/src/api-client/types/auth.ts +63 -0
  10. package/src/api-client/types/billing.ts +54 -0
  11. package/src/api-client/types/chat.ts +180 -0
  12. package/src/api-client/types/congress.ts +107 -0
  13. package/src/api-client/types/credit.ts +110 -0
  14. package/src/api-client/types/econ.ts +158 -0
  15. package/src/api-client/types/equity-diagnostic.ts +73 -0
  16. package/src/api-client/types/filings-and-calls.ts +350 -0
  17. package/src/api-client/types/index.ts +25 -0
  18. package/src/api-client/types/jobs.ts +147 -0
  19. package/src/api-client/types/market.ts +122 -0
  20. package/src/api-client/types/news.ts +91 -0
  21. package/src/api-client/types/notes-and-theses.ts +172 -0
  22. package/src/api-client/types/quotes.ts +28 -0
  23. package/src/api-client/types/scanners.ts +125 -0
  24. package/src/api-client/types/screener.ts +65 -0
  25. package/src/api-client/types/search.ts +107 -0
  26. package/src/api-client/types/sync.ts +14 -0
  27. package/src/api-client/types/team-collections.ts +43 -0
  28. package/src/api-client/types/team-views.ts +32 -0
  29. package/src/api-client/types/teams.ts +135 -0
  30. package/src/api-client/types/ticker-data.ts +57 -0
  31. package/src/api-client/types/tweets.ts +59 -0
  32. package/src/api-client/types/world-venues.ts +23 -0
  33. package/src/app/runtime/desktop-deeplink.ts +41 -6
  34. package/src/app/star-prompt/status-line.tsx +1 -1
  35. package/src/app.tsx +1 -7
  36. package/src/architecture/ui-tokens-allowlist.json +0 -8
  37. package/src/cli/commands/ticker.ts +17 -4
  38. package/src/cli/desktop-pane-shot-browser.ts +69 -3
  39. package/src/cli/pane-functions/catalog.ts +3 -1
  40. package/src/components/chart/composite/use-composite-chart-keyboard.ts +11 -2
  41. package/src/components/data-table/export.ts +4 -1
  42. package/src/components/layout/detached-pane-shell.tsx +10 -37
  43. package/src/components/layout/double-escape-close.ts +90 -0
  44. package/src/components/layout/header.tsx +3 -2
  45. package/src/components/layout/market-summary.ts +6 -3
  46. package/src/components/layout/pane/footer/index.tsx +2 -6
  47. package/src/components/layout/pane/footer/model.ts +6 -12
  48. package/src/components/layout/shell/active-drag.ts +53 -11
  49. package/src/components/layout/shell/drag/magnets.ts +128 -19
  50. package/src/components/layout/shell/pane/actions.ts +6 -2
  51. package/src/components/layout/shell/pane/management-shortcuts.ts +13 -51
  52. package/src/components/layout/status-bar.tsx +4 -78
  53. package/src/components/layout/status-widget-space.ts +5 -5
  54. package/src/components/onboarding/portfolio-step/positions-panel.tsx +1 -1
  55. package/src/components/ui/data-table/index.tsx +5 -1
  56. package/src/components/ui/data-table/render-cell.ts +19 -0
  57. package/src/components/ui/delayed-mark.tsx +59 -7
  58. package/src/components/ui/icon.tsx +1 -8
  59. package/src/components/ui/menu.tsx +6 -1
  60. package/src/i18n/es.ts +3 -3
  61. package/src/i18n/ja.ts +3 -3
  62. package/src/i18n/ko.ts +3 -3
  63. package/src/i18n/zh-cn.ts +3 -3
  64. package/src/i18n/zh-tw.ts +3 -3
  65. package/src/plugins/builtin/chat/content/composer.tsx +21 -27
  66. package/src/plugins/builtin/chat/content/index.tsx +31 -3
  67. package/src/plugins/builtin/chat/content/shortcuts.ts +4 -2
  68. package/src/plugins/builtin/chat/content/snapshot.ts +0 -3
  69. package/src/plugins/builtin/cloud/auth-actions.tsx +51 -23
  70. package/src/plugins/builtin/cloud/trial-offer-status-widget.tsx +3 -3
  71. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +32 -25
  72. package/src/plugins/builtin/congress-trades/model.ts +2 -1
  73. package/src/plugins/builtin/congress-trades/pane.tsx +3 -0
  74. package/src/plugins/builtin/custom-view/index.tsx +1 -1
  75. package/src/plugins/builtin/custom-view/loader.ts +85 -8
  76. package/src/plugins/builtin/custom-view/view-spec.ts +28 -0
  77. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +13 -4
  78. package/src/plugins/builtin/equity-screener/headless.ts +33 -1
  79. package/src/plugins/builtin/equity-screener/model.ts +58 -15
  80. package/src/plugins/builtin/equity-screener/pane.tsx +36 -6
  81. package/src/plugins/builtin/executives/format.ts +5 -4
  82. package/src/plugins/builtin/executives/pane.tsx +1 -1
  83. package/src/plugins/builtin/help/index.tsx +55 -1
  84. package/src/plugins/builtin/insider/model.ts +30 -2
  85. package/src/plugins/builtin/jobs/model.ts +2 -2
  86. package/src/plugins/builtin/mna/model.ts +2 -2
  87. package/src/plugins/builtin/notes/files.ts +2 -0
  88. package/src/plugins/builtin/notes/owner.tsx +20 -1
  89. package/src/plugins/builtin/notes/quick-notes-pane.tsx +22 -4
  90. package/src/plugins/builtin/notes/store.ts +6 -1
  91. package/src/plugins/builtin/portfolio-list/header.tsx +1 -1
  92. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -25
  93. package/src/plugins/builtin/series-inventory.ts +1 -0
  94. package/src/plugins/builtin/shared/earnings-report.ts +7 -2
  95. package/src/plugins/builtin/shared/use-quote-board.ts +85 -46
  96. package/src/plugins/builtin/short-interest/headless.ts +1 -1
  97. package/src/plugins/builtin/short-interest/model.ts +15 -6
  98. package/src/plugins/builtin/short-interest/types.ts +2 -0
  99. package/src/plugins/builtin/thirteenf/overlap-pane.tsx +3 -0
  100. package/src/plugins/builtin/thirteenf/pane.tsx +3 -0
  101. package/src/plugins/builtin/ticker-detail/overview/model.ts +5 -3
  102. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +4 -4
  103. package/src/plugins/builtin/trace-bonds/detail.tsx +198 -0
  104. package/src/plugins/builtin/trace-bonds/headless.ts +62 -4
  105. package/src/plugins/builtin/trace-bonds/history.ts +155 -0
  106. package/src/plugins/builtin/trace-bonds/pane.tsx +64 -5
  107. package/src/plugins/installer.ts +16 -3
  108. package/src/plugins/plugin-names.ts +11 -2
  109. package/src/remote/controller.ts +9 -2
  110. package/src/remote/schema.ts +2 -1
  111. package/src/renderers/cloudflare/http-proxy.ts +67 -8
  112. package/src/renderers/cloudflare/proxy-session.ts +1 -1
  113. package/src/renderers/cloudflare/worker.ts +29 -2
  114. package/src/renderers/dom/desktop/icons.tsx +0 -2
  115. package/src/renderers/dom/styles.css +0 -3
  116. package/src/renderers/electrobun/bun/desktop/install-records.ts +59 -0
  117. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +208 -592
  118. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +14 -0
  119. package/src/renderers/electrobun/bun/desktop/update.ts +1 -1
  120. package/src/renderers/electrobun/bun/index.ts +19 -13
  121. package/src/renderers/electrobun/bun/window/create.ts +23 -3
  122. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +4 -4
  123. package/src/renderers/electrobun/bun/window/events.ts +4 -4
  124. package/src/renderers/electrobun/bun/window/frame.ts +2 -1
  125. package/src/renderers/electrobun/bun/window/native-min-size.ts +322 -0
  126. package/src/renderers/electrobun/view/backend-rpc.ts +1 -1
  127. package/src/sources/gloomberb-cloud/index.ts +5 -7
  128. package/src/sources/provider-router/batches.ts +18 -3
  129. package/src/sources/provider-router/financials.ts +18 -4
  130. package/src/types/data-provider.ts +14 -0
  131. package/src/types/financials.ts +15 -3
  132. package/src/types/headless.ts +2 -0
  133. package/src/utils/double-escape-close.ts +38 -16
  134. package/src/utils/format.ts +23 -3
  135. package/src/utils/price-earnings.ts +18 -0
  136. package/patches/electrobun@1.18.1.patch +0 -633
  137. package/src/api-client/types.ts +0 -2441
@@ -24,6 +24,8 @@ function loadObjc() {
24
24
  const runtime = dlopen(LIBOBJC, {
25
25
  objc_getClass: { args: [FFIType.ptr], returns: ID },
26
26
  sel_registerName: { args: [FFIType.ptr], returns: FFIType.ptr },
27
+ objc_autoreleasePoolPush: { args: [], returns: FFIType.ptr },
28
+ objc_autoreleasePoolPop: { args: [FFIType.ptr], returns: FFIType.void },
27
29
  }).symbols;
28
30
  const msgSend = <const Args extends FFIType[], Returns extends FFIType>(args: Args, returns: Returns) =>
29
31
  dlopen(LIBOBJC, { objc_msgSend: { args: [ID, FFIType.ptr, ...args], returns } }).symbols.objc_msgSend;
@@ -31,11 +33,23 @@ function loadObjc() {
31
33
  return {
32
34
  getClass: (name: string) => runtime.objc_getClass(cString(name)),
33
35
  selector: (name: string) => runtime.sel_registerName(cString(name)),
36
+ /** Runs `run` in an autorelease pool of its own, for the objects class methods return: Bun's thread may have none. */
37
+ withAutoreleasePool: <T>(run: () => T): T => {
38
+ const pool = runtime.objc_autoreleasePoolPush();
39
+ try {
40
+ return run();
41
+ } finally {
42
+ runtime.objc_autoreleasePoolPop(pool);
43
+ }
44
+ },
34
45
  send: msgSend([], ID),
35
46
  sendVoid: msgSend([], FFIType.void),
36
47
  sendObject: msgSend([ID], ID),
37
48
  sendCString: msgSend([FFIType.ptr], ID),
38
49
  sendBytes: msgSend([FFIType.ptr, FFIType.u64], ID),
50
+ /** A message taking an NSSize or NSPoint: two doubles, passed as two on arm64 and x86-64 alike. */
51
+ sendDoubles: msgSend([FFIType.f64, FFIType.f64], ID),
52
+ sendObjects: msgSend([ID, ID], ID),
39
53
  sendOnMainThread: msgSend([FFIType.ptr, ID, FFIType.bool], FFIType.void),
40
54
  };
41
55
  }
@@ -40,7 +40,7 @@ type ElectrobunUpdater = typeof Electrobun.Updater;
40
40
  /**
41
41
  * The part of Electrobun's updater this flow uses. Tests pass a fake, because
42
42
  * the real module cannot be loaded or exercised outside the packaged app.
43
- * `setUpdateSource` is this app's patch (patches/electrobun@*.patch).
43
+ * `setUpdateSource` is this app's patch (patches/electrobun-devkit@*.patch).
44
44
  */
45
45
  export type ElectrobunUpdaterApi = Pick<
46
46
  ElectrobunUpdater,
@@ -1,4 +1,4 @@
1
- import Electrobun, { ApplicationMenu, Utils } from "electrobun/bun";
1
+ import Electrobun, { ApplicationMenu, Updater, Utils } from "electrobun/bun";
2
2
  import { homedir } from "os";
3
3
  import { debugLog } from "../../../utils/debug-log";
4
4
  import { setConfigStoreHost } from "../../../data/config/store";
@@ -13,6 +13,7 @@ import { installProcessCrashListeners } from "../../../telemetry/crash-reports-n
13
13
  import { renameLegacyMacApp } from "./desktop/app-name";
14
14
  import { scheduleDesktopRelaunch } from "./desktop/relaunch";
15
15
  import { settleInstallerFolder } from "./desktop/installer-folder";
16
+ import { ensureInstallRecords } from "./desktop/install-records";
16
17
 
17
18
  console.log = (...args) => console.error(...args);
18
19
  console.info = (...args) => console.error(...args);
@@ -30,24 +31,17 @@ setConfigStoreHost(nodeConfigStoreHost);
30
31
  // before the config, and its off switch, has been read.
31
32
  installProcessCrashListeners();
32
33
 
33
- // An install the Windows installer made lives in the installer's folder,
34
- // where its shortcuts, the gloom command and its uninstall entry lead.
35
- // Electrobun's updater installs an update into a folder of its own and opens
36
- // it from there: this build moves into the installer's folder and opens again
37
- // from it before any window shows.
38
- const installerFolderMove = await settleInstallerFolder({
34
+ // A Windows install from before Electrobun 2 lives in the installer's folder.
35
+ // Its last update put this build in Electrobun's folder, the only one
36
+ // Electrobun 2 updates: the installer's folder is retired in the background.
37
+ void settleInstallerFolder({
39
38
  platform: process.platform,
40
39
  execPath: process.execPath,
41
40
  homeDir: homedir(),
42
41
  localAppData: process.env.LOCALAPPDATA,
43
42
  }).catch((error: unknown) => {
44
- console.error("[desktop] could not move the app into the installer's folder", error instanceof Error ? error.message : String(error));
45
- return null;
43
+ console.error("[desktop] could not retire the installer's folder", error instanceof Error ? error.message : String(error));
46
44
  });
47
- if (installerFolderMove?.kind === "relaunching") {
48
- Utils.quit();
49
- await new Promise<never>(() => {});
50
- }
51
45
 
52
46
  // An install from before the rename runs from Gloomberb.app, where its updater
53
47
  // put this build. It takes the new name and opens again from there before any
@@ -70,6 +64,18 @@ if (appRename?.kind === "renamed") {
70
64
  console.error(`[desktop] kept the app's old name: ${appRename.reason}`);
71
65
  }
72
66
 
67
+ // A Mac app that has not updated yet has no folder for Electrobun's install
68
+ // records, which its launcher otherwise fails to write at every start. The
69
+ // records name the bundle the app runs from, so they are written once it has
70
+ // its new name: a Gloomberb.app being renamed above opens again as Gloom.app
71
+ // and writes them from there.
72
+ void ensureInstallRecords({
73
+ platform: process.platform,
74
+ execPath: process.execPath,
75
+ channel: () => Updater.localInfo.channel(),
76
+ channelRoot: () => Updater.appDataFolder(),
77
+ });
78
+
73
79
  function readOpenUrlEvent(event: unknown): string | null {
74
80
  const data = event && typeof event === "object" ? (event as { data?: unknown }).data : null;
75
81
  if (!data || typeof data !== "object") return null;
@@ -1,4 +1,6 @@
1
1
  import { BrowserWindow } from "electrobun/bun";
2
+ import { readFileSync } from "fs";
3
+ import { resolve } from "path";
2
4
  import { measurePerf } from "../../../../utils/perf-marks";
3
5
  import { trackWindowAttention } from "./attention";
4
6
  import {
@@ -10,6 +12,7 @@ import {
10
12
  type WindowResizeEvent,
11
13
  } from "./events";
12
14
  import type { WindowFrame, WindowMinimumSize } from "./frame";
15
+ import { applyNativeMinimumSize } from "./native-min-size";
13
16
  import { applyWindowsCustomChrome } from "./windows-custom-chrome";
14
17
  import { applyWindowsWindowIcon } from "./windows-icons";
15
18
  import { fitPageToClientArea } from "./windows-native";
@@ -33,10 +36,24 @@ function desktopTitleBarStyle(): DesktopTitleBarStyle {
33
36
  return process.platform === "linux" ? "hidden" : "hiddenInset";
34
37
  }
35
38
 
39
+ let chromiumShipped: boolean | undefined;
40
+
41
+ /** Whether this build ships Chromium (Resources/build.json); a build that does not say is taken to. */
42
+ function shipsChromium(): boolean {
43
+ if (chromiumShipped !== undefined) return chromiumShipped;
44
+ try {
45
+ const build = JSON.parse(readFileSync(resolve("../Resources/build.json"), "utf8")) as { availableRenderers?: unknown };
46
+ chromiumShipped = !Array.isArray(build.availableRenderers) || build.availableRenderers.includes("cef");
47
+ } catch {
48
+ chromiumShipped = true;
49
+ }
50
+ return chromiumShipped;
51
+ }
52
+
36
53
  function desktopWindowRenderer(): DesktopWindowRenderer {
37
54
  if (process.platform === "win32") {
38
55
  const hostArchitecture = process.env.PROCESSOR_ARCHITEW6432 ?? process.env.PROCESSOR_ARCHITECTURE;
39
- return hostArchitecture?.toLowerCase() === "arm64" ? "native" : "cef";
56
+ return hostArchitecture?.toLowerCase() === "arm64" || !shipsChromium() ? "native" : "cef";
40
57
  }
41
58
  return "native";
42
59
  }
@@ -82,7 +99,8 @@ interface AppWindowOptions {
82
99
 
83
100
  /**
84
101
  * Opens a window on the app view with this platform's chrome and icon, keeps
85
- * its cached frame current as it moves, and holds it to `minSize` on resize.
102
+ * its cached frame current as it moves, and holds it to `minSize`: the system
103
+ * does while it is resized, and a resize that still ends under it is undone.
86
104
  */
87
105
  export function createAppWindow({ title, frame, rpc, minSize, onFrameChange, preload }: AppWindowOptions): BrowserWindow {
88
106
  // Opening a window waits on the native layer, the webview's creation included.
@@ -100,11 +118,13 @@ export function createAppWindow({ title, frame, rpc, minSize, onFrameChange, pre
100
118
  }));
101
119
  applyWindowsWindowIcon(title);
102
120
  applyWindowsCustomChrome(title);
121
+ applyNativeMinimumSize(window, minSize);
103
122
  if (process.platform === "win32") {
104
123
  loadAgainWhenTakenForCtrlClick(window);
105
124
  // The page exists once it has loaded; until then there is nothing to fit.
106
125
  window.webview.on("dom-ready", () => {
107
- fitPageToClientArea(window.ptr);
126
+ const handle = window.ptr;
127
+ if (handle) fitPageToClientArea(handle);
108
128
  });
109
129
  }
110
130
  updateWindowFrameCache(window, frame, minSize);
@@ -10,9 +10,9 @@ import { getWindowFrame, updateWindowFrameCache } from "./events";
10
10
  import type { FocusableElectrobunWindow } from "./focus";
11
11
 
12
12
  /**
13
- * Electrobun 1.18 has no event for displays coming and going, nor for a window
14
- * being minimized: both are read on a timer, this often while there is more
15
- * than one window...
13
+ * Electrobun (2.0.5, as 1.18) has no event for displays coming and going, nor
14
+ * for a window being minimized: both are read on a timer, this often while
15
+ * there is more than one window...
16
16
  */
17
17
  const POLL_MS = 3_000;
18
18
  /**
@@ -90,7 +90,7 @@ function read(call: () => boolean): boolean {
90
90
  }
91
91
  }
92
92
 
93
- /** The desktop window host on Electrobun 1.18: windows, their frames and events, and the displays. */
93
+ /** The desktop window host on Electrobun: windows, their frames and events, and the displays. */
94
94
  export class ElectrobunWindowHost implements DesktopWindowHost {
95
95
  readonly canPlaceWindows: boolean;
96
96
  /** Windows has no way into full screen with Electrobun's frameless windows. */
@@ -52,10 +52,10 @@ type FramedWindow = Pick<BrowserWindow, "frame" | "getFrame" | "isMinimized" | "
52
52
 
53
53
  /**
54
54
  * Electrobun's Windows events do not carry the window's frame: a resize
55
- * reports the client area's size at 0,0, a move the client area's corner as
56
- * unsigned 16-bit values, and both come while the window is minimized. There
57
- * the frame is read from the window itself, and a minimized window keeps the
58
- * frame it had.
55
+ * reports the client area's size rather than the window's (2.0.5; 1.18 put it
56
+ * at 0,0 too, and a move gave the client area's corner as unsigned 16-bit
57
+ * values), and both come while the window is minimized. There the frame is
58
+ * read from the window itself, and a minimized window keeps the frame it had.
59
59
  */
60
60
  export function applyNativeWindowFrame(window: FramedWindow, minimumSize?: WindowMinimumSize): WindowFrame | null {
61
61
  if (window.isMinimized()) return null;
@@ -12,7 +12,8 @@ export interface WindowMinimumSize {
12
12
 
13
13
  export const DEFAULT_WINDOW_FRAME: WindowFrame = { x: 64, y: 48, width: 1440, height: 920 };
14
14
  const DEFAULT_WINDOWS_WINDOW_FRAME: WindowFrame = { x: 32, y: 32, width: 960, height: 680 };
15
- // Emergency fallback until Electrobun exposes stable native minimum-size handling:
15
+ // Held by the system while a window is resized (native-min-size.ts), and by
16
+ // the resize handlers where that does not apply: Electrobun has no minimum size,
16
17
  // https://github.com/blackboardsh/electrobun/issues/188
17
18
  export const MAIN_WINDOW_MIN_SIZE: WindowMinimumSize = { width: 640, height: 400 };
18
19
  export const DETACHED_WINDOW_MIN_SIZE: WindowMinimumSize = { width: 360, height: 240 };
@@ -0,0 +1,322 @@
1
+ import { cc, dlopen, FFIType, type Pointer } from "bun:ffi";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "fs";
3
+ import { tmpdir } from "os";
4
+ import { join } from "path";
5
+ import { logFailure } from "../../../../utils/log-failure";
6
+ import { cString, objcOrNull } from "../desktop/macos-objc";
7
+ import type { WindowMinimumSize } from "./frame";
8
+
9
+ /**
10
+ * Electrobun has no minimum window size (2.0.5 neither), so the app shrank
11
+ * under it at every resize and jumped back once the resize event came. Here
12
+ * each system holds the window to it while it is being resized:
13
+ *
14
+ * - macOS: `NSWindow.contentMinSize`.
15
+ * - Windows: the window's `WM_GETMINMAXINFO` answer, by a window procedure
16
+ * placed before Electrobun's that raises its minimum tracking size to this
17
+ * one, at the window's DPI.
18
+ * - Linux: GTK's geometry hints, which the window manager reads.
19
+ *
20
+ * The app's code runs on a thread of its own, not the one the windows belong
21
+ * to, so each change is handed to that thread: AppKit's
22
+ * `performSelectorOnMainThread:`, GLib's main loop. A Windows window procedure
23
+ * runs on the window's thread and has to answer there and then, which is why
24
+ * Windows and Linux use a few lines of C compiled at runtime (Bun's `cc`).
25
+ *
26
+ * The snap back in events.ts stays as the fallback for a system where this
27
+ * does not apply.
28
+ */
29
+
30
+ /** The C the Windows window procedure is made of. Pointer-sized integers are `long long`: `long` is 32-bit there. */
31
+ const WINDOWS_SOURCE = String.raw`
32
+ typedef long long sptr;
33
+ typedef unsigned long long uptr;
34
+ typedef void *HWND;
35
+ typedef sptr (*WNDPROC)(HWND, unsigned int, uptr, sptr);
36
+ typedef struct { int x; int y; } Pt;
37
+ typedef struct { Pt reserved; Pt max_size; Pt max_position; Pt min_track; Pt max_track; } MinMaxInfo;
38
+
39
+ #define WM_GETMINMAXINFO 0x0024
40
+ #define WM_NCDESTROY 0x0082
41
+ #define GWLP_WNDPROC (-4)
42
+ #define SLOTS 64
43
+
44
+ typedef struct { HWND volatile hwnd; WNDPROC volatile previous; int volatile width; int volatile height; } Slot;
45
+
46
+ static Slot slots[SLOTS];
47
+ static sptr (*call_window_proc)(WNDPROC, HWND, unsigned int, uptr, sptr);
48
+ static sptr (*get_window_long_ptr)(HWND, int);
49
+ static sptr (*set_window_long_ptr)(HWND, int, sptr);
50
+ static sptr (*def_window_proc)(HWND, unsigned int, uptr, sptr);
51
+ static unsigned int (*get_dpi_for_window)(HWND);
52
+
53
+ static Slot *slot_of(HWND hwnd) {
54
+ for (int i = 0; i < SLOTS; i++) if (slots[i].hwnd == hwnd) return &slots[i];
55
+ return 0;
56
+ }
57
+
58
+ static sptr min_size_proc(HWND hwnd, unsigned int message, uptr wparam, sptr lparam) {
59
+ Slot *slot = slot_of(hwnd);
60
+ WNDPROC previous = slot ? slot->previous : 0;
61
+ if (!previous) return def_window_proc(hwnd, message, wparam, lparam);
62
+ if (message == WM_NCDESTROY) {
63
+ set_window_long_ptr(hwnd, GWLP_WNDPROC, (sptr)previous);
64
+ slot->hwnd = 0;
65
+ return call_window_proc(previous, hwnd, message, wparam, lparam);
66
+ }
67
+ sptr result = call_window_proc(previous, hwnd, message, wparam, lparam);
68
+ if (message == WM_GETMINMAXINFO && lparam) {
69
+ MinMaxInfo *info = (MinMaxInfo *)lparam;
70
+ int dpi = get_dpi_for_window ? (int)get_dpi_for_window(hwnd) : 0;
71
+ if (dpi <= 0) dpi = 96;
72
+ int width = (slot->width * dpi + 48) / 96;
73
+ int height = (slot->height * dpi + 48) / 96;
74
+ if (info->min_track.x < width) info->min_track.x = width;
75
+ if (info->min_track.y < height) info->min_track.y = height;
76
+ }
77
+ return result;
78
+ }
79
+
80
+ int gloom_min_size_init(void *call, void *get_long, void *set_long, void *def, void *dpi) {
81
+ call_window_proc = (sptr (*)(WNDPROC, HWND, unsigned int, uptr, sptr))call;
82
+ get_window_long_ptr = (sptr (*)(HWND, int))get_long;
83
+ set_window_long_ptr = (sptr (*)(HWND, int, sptr))set_long;
84
+ def_window_proc = (sptr (*)(HWND, unsigned int, uptr, sptr))def;
85
+ get_dpi_for_window = (unsigned int (*)(HWND))dpi;
86
+ return call && get_long && set_long && def;
87
+ }
88
+
89
+ /* 1 when the window had a minimum already and now has this one, 2 when it is newly held to it, 0 when it cannot be. */
90
+ int gloom_min_size_set(HWND hwnd, int width, int height) {
91
+ Slot *slot = slot_of(hwnd);
92
+ if (slot) {
93
+ slot->width = width;
94
+ slot->height = height;
95
+ return 1;
96
+ }
97
+ for (int i = 0; i < SLOTS && !slot; i++) if (!slots[i].hwnd) slot = &slots[i];
98
+ if (!slot) return 0;
99
+ sptr current = get_window_long_ptr(hwnd, GWLP_WNDPROC);
100
+ if (!current) return 0;
101
+ slot->width = width;
102
+ slot->height = height;
103
+ slot->previous = (WNDPROC)current;
104
+ /* Taken only once the procedure it hands on to is in place. */
105
+ slot->hwnd = hwnd;
106
+ sptr replaced = set_window_long_ptr(hwnd, GWLP_WNDPROC, (sptr)min_size_proc);
107
+ if (!replaced) {
108
+ slot->hwnd = 0;
109
+ return 0;
110
+ }
111
+ if (replaced != current) slot->previous = (WNDPROC)replaced;
112
+ return 2;
113
+ }
114
+ `;
115
+
116
+ /** The C that hands a GTK window's minimum size to GLib's main loop. */
117
+ const LINUX_SOURCE = String.raw`
118
+ typedef struct {
119
+ int min_width; int min_height; int max_width; int max_height;
120
+ int base_width; int base_height; int width_inc; int height_inc;
121
+ double min_aspect; double max_aspect; int win_gravity;
122
+ } Geometry;
123
+
124
+ #define GDK_HINT_MIN_SIZE 2
125
+ #define SLOTS 64
126
+
127
+ typedef struct { void *volatile window; Geometry geometry; } Request;
128
+
129
+ static Request requests[SLOTS];
130
+ static unsigned int next_request;
131
+ static unsigned int (*idle_add)(int (*)(void *), void *);
132
+ static void (*set_geometry_hints)(void *, void *, Geometry *, int);
133
+ static void *(*object_ref)(void *);
134
+ static void (*object_unref)(void *);
135
+
136
+ static int apply(void *data) {
137
+ Request *request = (Request *)data;
138
+ void *window = request->window;
139
+ if (window) {
140
+ set_geometry_hints(window, 0, &request->geometry, GDK_HINT_MIN_SIZE);
141
+ request->window = 0;
142
+ object_unref(window);
143
+ }
144
+ return 0;
145
+ }
146
+
147
+ int gloom_min_size_init(void *idle, void *hints, void *ref, void *unref) {
148
+ idle_add = (unsigned int (*)(int (*)(void *), void *))idle;
149
+ set_geometry_hints = (void (*)(void *, void *, Geometry *, int))hints;
150
+ object_ref = (void *(*)(void *))ref;
151
+ object_unref = (void (*)(void *))unref;
152
+ return idle && hints && ref && unref;
153
+ }
154
+
155
+ int gloom_min_size_set(void *window, int width, int height) {
156
+ Request *request = &requests[next_request++ % SLOTS];
157
+ if (request->window) return 0;
158
+ request->geometry.min_width = width;
159
+ request->geometry.min_height = height;
160
+ request->window = object_ref(window);
161
+ idle_add(apply, request);
162
+ return 2;
163
+ }
164
+ `;
165
+
166
+ const MIN_SIZE_SYMBOLS = {
167
+ gloom_min_size_set: { args: [FFIType.ptr, FFIType.i32, FFIType.i32], returns: FFIType.i32 },
168
+ } as const;
169
+
170
+ type MinSizeSetter = (window: Pointer, width: number, height: number) => number;
171
+
172
+ /** The compiled helper for this system, once; `null` when it could not be made. */
173
+ let compiledSetter: MinSizeSetter | null | undefined;
174
+ /** The compiled code, kept for good: a window procedure in it runs for as long as its window does. */
175
+ const compiledLibraries: unknown[] = [];
176
+
177
+ /**
178
+ * Hands `compile` a file holding `source`, in a folder this process just made
179
+ * for it alone (owner only, under a random name), never a shared name another
180
+ * user could have written first. `cc` reads the file only while it compiles,
181
+ * so the folder goes right after.
182
+ */
183
+ function fromPrivateSource<T>(source: string, compile: (path: string) => T): T {
184
+ const folder = mkdtempSync(join(tmpdir(), "gloom-native-min-size-"));
185
+ try {
186
+ const path = join(folder, "min-size.c");
187
+ writeFileSync(path, source, { flag: "wx", mode: 0o600 });
188
+ return compile(path);
189
+ } finally {
190
+ rmSync(folder, { recursive: true, force: true });
191
+ }
192
+ }
193
+
194
+ function windowsSetter(): MinSizeSetter | null {
195
+ const kernel32 = dlopen("kernel32.dll", {
196
+ GetModuleHandleW: { args: [FFIType.ptr], returns: FFIType.ptr },
197
+ GetProcAddress: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
198
+ }).symbols;
199
+ const user32 = kernel32.GetModuleHandleW(Buffer.from("user32.dll\0", "utf16le"));
200
+ if (!user32) return null;
201
+ const proc = (name: string) => kernel32.GetProcAddress(user32, cString(name));
202
+ const library = fromPrivateSource(WINDOWS_SOURCE, (source) => cc({
203
+ source,
204
+ symbols: {
205
+ ...MIN_SIZE_SYMBOLS,
206
+ gloom_min_size_init: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },
207
+ },
208
+ }));
209
+ const ready = library.symbols.gloom_min_size_init(
210
+ proc("CallWindowProcW"),
211
+ proc("GetWindowLongPtrW"),
212
+ proc("SetWindowLongPtrW"),
213
+ proc("DefWindowProcW"),
214
+ proc("GetDpiForWindow"),
215
+ );
216
+ if (!ready) return null;
217
+ compiledLibraries.push(library);
218
+ return library.symbols.gloom_min_size_set;
219
+ }
220
+
221
+ /** The address of `name` in the already loaded library `file`, or null. */
222
+ function linuxSymbol(file: string, name: string): Pointer | null {
223
+ for (const libc of ["libc.so.6", "libdl.so.2"]) {
224
+ try {
225
+ const dl = dlopen(libc, {
226
+ dlopen: { args: [FFIType.ptr, FFIType.i32], returns: FFIType.ptr },
227
+ dlsym: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
228
+ }).symbols;
229
+ // RTLD_LAZY | RTLD_NOLOAD: the library GTK's windows already use, never a second one.
230
+ const handle = dl.dlopen(cString(file), 0x1 | 0x4);
231
+ return handle ? dl.dlsym(handle, cString(name)) : null;
232
+ } catch {
233
+ // No dlopen in this libc: glibc before 2.34 keeps it in libdl.
234
+ }
235
+ }
236
+ return null;
237
+ }
238
+
239
+ function linuxSetter(): MinSizeSetter | null {
240
+ const idleAdd = linuxSymbol("libglib-2.0.so.0", "g_idle_add");
241
+ const geometryHints = linuxSymbol("libgtk-3.so.0", "gtk_window_set_geometry_hints");
242
+ const ref = linuxSymbol("libgobject-2.0.so.0", "g_object_ref");
243
+ const unref = linuxSymbol("libgobject-2.0.so.0", "g_object_unref");
244
+ if (!idleAdd || !geometryHints || !ref || !unref) return null;
245
+ const library = fromPrivateSource(LINUX_SOURCE, (source) => cc({
246
+ source,
247
+ symbols: {
248
+ ...MIN_SIZE_SYMBOLS,
249
+ gloom_min_size_init: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },
250
+ },
251
+ }));
252
+ if (!library.symbols.gloom_min_size_init(idleAdd, geometryHints, ref, unref)) return null;
253
+ compiledLibraries.push(library);
254
+ return library.symbols.gloom_min_size_set;
255
+ }
256
+
257
+ function compiledMinSizeSetter(platform: NodeJS.Platform): MinSizeSetter | null {
258
+ if (compiledSetter !== undefined) return compiledSetter;
259
+ try {
260
+ compiledSetter = platform === "win32" ? windowsSetter() : platform === "linux" ? linuxSetter() : null;
261
+ } catch (error) {
262
+ logFailure("desktop-window", "Could not make the native minimum window size")(error);
263
+ compiledSetter = null;
264
+ }
265
+ return compiledSetter;
266
+ }
267
+
268
+ /** Sets an NSWindow's `contentMinSize` on the main thread, through key-value coding, which takes the size boxed. */
269
+ function setMacosContentMinSize(window: Pointer, size: WindowMinimumSize): boolean {
270
+ const objc = objcOrNull();
271
+ if (!objc) return false;
272
+ return objc.withAutoreleasePool(() => {
273
+ const value = objc.sendDoubles(objc.getClass("NSValue"), objc.selector("valueWithSize:"), size.width, size.height);
274
+ const key = objc.sendCString(objc.getClass("NSString"), objc.selector("stringWithUTF8String:"), cString("contentMinSize"));
275
+ const values = objc.sendObjects(objc.getClass("NSDictionary"), objc.selector("dictionaryWithObject:forKey:"), value, key);
276
+ if (!values) return false;
277
+ // Retained by the call until it has run on the main thread.
278
+ objc.sendOnMainThread(
279
+ BigInt(window),
280
+ objc.selector("performSelectorOnMainThread:withObject:waitUntilDone:"),
281
+ objc.selector("setValuesForKeysWithDictionary:"),
282
+ values,
283
+ false,
284
+ );
285
+ return true;
286
+ });
287
+ }
288
+
289
+ /** Holds the native window `ptr` to `size` (in the window frame's points) while it is resized. Resolves whether it took. */
290
+ function setNativeMinimumSize(ptr: Pointer, size: WindowMinimumSize, platform: NodeJS.Platform = process.platform): boolean {
291
+ const width = Math.ceil(size.width);
292
+ const height = Math.ceil(size.height);
293
+ try {
294
+ if (platform === "darwin") return setMacosContentMinSize(ptr, { width, height });
295
+ const set = compiledMinSizeSetter(platform);
296
+ return set ? set(ptr, width, height) > 0 : false;
297
+ } catch (error) {
298
+ logFailure("desktop-window", "Could not set the native minimum window size")(error);
299
+ return false;
300
+ }
301
+ }
302
+
303
+ const HANDLE_ATTEMPTS = 20;
304
+ const HANDLE_RETRY_MS = 100;
305
+
306
+ /**
307
+ * `setNativeMinimumSize` for a window just opened, once its native window
308
+ * exists: Electrobun may make it after the constructor returns.
309
+ */
310
+ export function applyNativeMinimumSize(window: { ptr: Pointer | null }, size: WindowMinimumSize): void {
311
+ let attempts = 0;
312
+ const attempt = () => {
313
+ const handle = window.ptr;
314
+ if (handle) {
315
+ setNativeMinimumSize(handle, size);
316
+ return;
317
+ }
318
+ attempts += 1;
319
+ if (attempts < HANDLE_ATTEMPTS) setTimeout(attempt, HANDLE_RETRY_MS);
320
+ };
321
+ attempt();
322
+ }
@@ -129,7 +129,7 @@ const BRIDGE_READY_LIMIT_MS = 5_000;
129
129
  async function waitForBridgeReady(): Promise<void> {
130
130
  const start = Date.now();
131
131
  while (Date.now() - start < BRIDGE_READY_LIMIT_MS) {
132
- if (electroview.bunSocket?.readyState === WebSocket.OPEN) {
132
+ if (electroview.hostSocket?.readyState === WebSocket.OPEN) {
133
133
  return;
134
134
  }
135
135
  await new Promise((resolve) => setTimeout(resolve, 25));
@@ -618,13 +618,11 @@ export class GloomberbCloudProvider implements AssetDataProvider {
618
618
  const { matched, missing } = matchCloudBatchItems(submitted, payload.items);
619
619
  return [...rejected, ...matched.map(({ target, item }) => {
620
620
  // A successful batch can contain an expired cache fallback for only
621
- // one listing. Match the single-quote freshness boundary and let the
622
- // normal router retry that item without discarding its healthy peers.
623
- // A listing that no longer trades has only that last quote: kept, flagged stale.
624
- const delisted = !!parseListingDelisting(item.data?.delisting);
625
- if (item.stale === true && !delisted) {
626
- return { target, quote: null, error: createProviderMiss(`Cloud quotes are stale for ${target.symbol}`) };
627
- }
621
+ // one listing: the last price the service has, flagged stale as the
622
+ // single-quote route flags it. No freshness check passes it, so the
623
+ // router asks for that listing alone and keeps this price only when
624
+ // that read brings none. A listing that no longer trades has only
625
+ // that last quote too.
628
626
  if ((item.status === "success" || item.status === "partial") && item.data) {
629
627
  const answered = mapQuote(item.data);
630
628
  if (pricesOtherListing(answered, cloudInstrumentTarget(target.symbol, target.exchange))) {
@@ -21,6 +21,7 @@ import {
21
21
  hasRecentFinancialProfileAttempt,
22
22
  hasDetailedStatementRows,
23
23
  isProviderQuoteUsableForCurrentSession,
24
+ lastKnownProviderQuote,
24
25
  providerFinancialsMatchTarget,
25
26
  quoteWithFreshnessExchange,
26
27
  type CachedFinancialsSelection,
@@ -58,6 +59,8 @@ export class ProviderRouterBatchRoutes {
58
59
  const providerOptions = { forceRefresh: options.forceRefresh };
59
60
  const forceRefresh = options.forceRefresh === true;
60
61
  const results = new Array<QuoteBatchResult | null>(targets.length).fill(null);
62
+ // A dated price the batch answered that is not current: shown, flagged stale, when asking alone brings none.
63
+ const lastKnown = new Array<Quote | null>(targets.length).fill(null);
61
64
  const misses: Array<{ index: number; target: QuoteSubscriptionTarget }> = [];
62
65
 
63
66
  targets.forEach((target, index) => {
@@ -104,8 +107,12 @@ export class ProviderRouterBatchRoutes {
104
107
  return logFailure("sources.provider-router.batches", "Loading batch quotes failed", [] as QuoteBatchResult[])(error);
105
108
  });
106
109
  for (const item of batchResults) {
107
- if (!isProviderQuoteUsableForCurrentSession(item.quote, item.target.exchange, item.target.symbol, { recentAnswer: true })) continue;
108
110
  const key = this.quoteBatchKey(item.target);
111
+ if (!isProviderQuoteUsableForCurrentSession(item.quote, item.target.exchange, item.target.symbol, { recentAnswer: true })) {
112
+ const fallback = lastKnownProviderQuote(item.quote, item.target.exchange, item.target.symbol);
113
+ if (fallback) for (const entry of providerIndexes.get(key) ?? []) lastKnown[entry.index] = fallback;
114
+ continue;
115
+ }
109
116
  const sourceKey = this.deps.providerSourceKey(batchProvider);
110
117
  for (const entry of providerIndexes.get(key) ?? []) {
111
118
  const entityKey = this.deps.getEntityKey(entry.target.symbol, entry.target.context?.instrument);
@@ -119,16 +126,24 @@ export class ProviderRouterBatchRoutes {
119
126
  // The batch never reached the data service: a copy saved a moment ago is still a saved copy, not the
120
127
  // service's answer, so each is asked for as a refresh, which fails at once and says it answers from that copy.
121
128
  const unreached = isNetworkFailure(batchFailure) ? new Set(providerMisses.map(({ index }) => index)) : null;
129
+ const followUp = (index: number): "default" | "refresh" => (forceRefresh || unreached?.has(index) ? "refresh" : "default");
130
+ if (options.deferFollowUps) {
131
+ for (const { index, target } of misses) {
132
+ results[index] ??= { target, quote: lastKnown[index] ?? null, followUp: followUp(index) };
133
+ }
134
+ }
122
135
  await Promise.all(misses.map(async ({ index, target }) => {
123
136
  if (results[index]) return;
124
137
  try {
125
138
  const quote = await this.deps.getQuote(target.symbol, target.exchange, {
126
139
  ...target.context,
127
- cacheMode: forceRefresh || unreached?.has(index) ? "refresh" : "default",
140
+ cacheMode: followUp(index),
128
141
  });
129
142
  results[index] = { target, quote };
130
143
  } catch (error) {
131
- results[index] = { target, quote: null, error };
144
+ // Asked alone it brought nothing: the batch's dated price, flagged stale, rather than none, as the quote route answers.
145
+ const fallback = lastKnown[index];
146
+ results[index] = fallback ? { target, quote: fallback } : { target, quote: null, error };
132
147
  }
133
148
  }));
134
149