gloomberb 0.20.0 → 0.20.1

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 (86) hide show
  1. package/package.json +1 -1
  2. package/patches/electrobun-devkit@2.0.5.patch +268 -8
  3. package/src/api-client/crypto-markets.ts +20 -2
  4. package/src/api-client/fund-facts.ts +23 -1
  5. package/src/api-client/types/filings-and-calls.ts +6 -0
  6. package/src/app/runtime/plugin-seed.ts +119 -0
  7. package/src/app/runtime/startup.ts +45 -9
  8. package/src/app.tsx +1 -0
  9. package/src/cli/board-coins.ts +38 -5
  10. package/src/cli/commands/crypto-hints.ts +8 -1
  11. package/src/cli/commands/market.ts +29 -26
  12. package/src/cli/commands/overview.ts +13 -6
  13. package/src/cli/commands/ticker.ts +61 -14
  14. package/src/cli/company-name-hint.ts +19 -0
  15. package/src/cli/entry.ts +10 -4
  16. package/src/cli/glossary.ts +25 -0
  17. package/src/cli/helpers.ts +4 -2
  18. package/src/cli/not-a-ticker.ts +26 -1
  19. package/src/cli/pane-functions/freshness.ts +45 -29
  20. package/src/cli/pane-functions/market-session.ts +14 -5
  21. package/src/cli/restore-plugins.ts +164 -51
  22. package/src/components/chart-table/header.tsx +10 -1
  23. package/src/components/chart-table/layout.ts +14 -5
  24. package/src/components/command-bar/panel/index.tsx +13 -0
  25. package/src/components/command-bar/panel/layout.ts +7 -0
  26. package/src/components/command-bar/panel/runtime.ts +1 -0
  27. package/src/components/command-bar/panel/types.ts +2 -0
  28. package/src/i18n/es.ts +3 -0
  29. package/src/i18n/ja.ts +3 -0
  30. package/src/i18n/ko.ts +3 -0
  31. package/src/i18n/zh-cn.ts +3 -0
  32. package/src/i18n/zh-tw.ts +3 -0
  33. package/src/market-data/fund-facts.ts +7 -1
  34. package/src/market-data/market/change-basis.ts +20 -0
  35. package/src/market-data/market/format.ts +62 -2
  36. package/src/market-data/market/futures-week.ts +3 -1
  37. package/src/plugins/builtin/chart-composer/headless.ts +57 -17
  38. package/src/plugins/builtin/chart-composer/session-range.ts +82 -3
  39. package/src/plugins/builtin/correlation/compute.ts +8 -2
  40. package/src/plugins/builtin/correlation/headless.ts +10 -9
  41. package/src/plugins/builtin/correlation/history.ts +30 -0
  42. package/src/plugins/builtin/correlation/matrix/model.ts +10 -10
  43. package/src/plugins/builtin/correlation/relationship/model.ts +3 -6
  44. package/src/plugins/builtin/correlation/relationship/pane.tsx +1 -2
  45. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  46. package/src/plugins/builtin/crypto-board/defi-view.tsx +12 -1
  47. package/src/plugins/builtin/crypto-board/defi.ts +44 -7
  48. package/src/plugins/builtin/crypto-board/headless.ts +83 -12
  49. package/src/plugins/builtin/crypto-board/model.ts +30 -6
  50. package/src/plugins/builtin/crypto-board/pane.tsx +13 -2
  51. package/src/plugins/builtin/perps/headless.ts +8 -2
  52. package/src/plugins/builtin/risk-factors/index.tsx +2 -28
  53. package/src/plugins/builtin/risk-factors/lock-note.ts +58 -0
  54. package/src/plugins/builtin/risk-factors/pane.tsx +10 -3
  55. package/src/plugins/builtin/scanner/hilo-model.ts +4 -3
  56. package/src/plugins/builtin/sec/fund-facts.ts +45 -11
  57. package/src/plugins/builtin/sec/headless.ts +30 -1
  58. package/src/plugins/builtin/sec/index.tsx +26 -5
  59. package/src/plugins/builtin/shared/pro-lock-note.ts +5 -1
  60. package/src/plugins/builtin/ticker-detail/overview/model.ts +14 -6
  61. package/src/plugins/builtin/time-sales/headless.ts +23 -7
  62. package/src/plugins/builtin/time-sales/index.tsx +2 -2
  63. package/src/plugins/extracted-plugins.ts +49 -24
  64. package/src/plugins/installer.ts +220 -31
  65. package/src/plugins/running-installs.ts +34 -0
  66. package/src/plugins/seed-progress.ts +72 -0
  67. package/src/renderers/electrobun/bun/desktop/backend.ts +14 -0
  68. package/src/renderers/electrobun/bun/desktop/host-requests.ts +14 -7
  69. package/src/renderers/electrobun/bun/desktop/initialization.ts +24 -14
  70. package/src/renderers/electrobun/bun/index.ts +5 -0
  71. package/src/renderers/electrobun/bun/window/context-menu-thread.ts +84 -0
  72. package/src/renderers/electrobun/bun/window/native-call-thread.ts +224 -0
  73. package/src/renderers/electrobun/bun/window/native-timing.ts +10 -0
  74. package/src/renderers/electrobun/bun/window/script-for-webview.ts +15 -0
  75. package/src/renderers/electrobun/bun/window/webview-script-thread.ts +82 -0
  76. package/src/renderers/electrobun/shared/protocol.ts +13 -2
  77. package/src/renderers/electrobun/view/backend-rpc.ts +7 -0
  78. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +1 -1
  79. package/src/renderers/electrobun/view/main.tsx +4 -3
  80. package/src/renderers/opentui/start.tsx +3 -0
  81. package/src/telemetry/stall-reports.ts +21 -4
  82. package/src/utils/main-thread-stall.ts +21 -5
  83. package/src/utils/perf-marks.ts +88 -9
  84. package/src/utils/reported-money.ts +9 -2
  85. package/src/utils/sec.ts +34 -3
  86. package/src/plugins/seed-notice.ts +0 -20
@@ -11,6 +11,8 @@ import {
11
11
  import { saveConfig } from "../../../../data/config/store";
12
12
  import { pluginAutoUpdateEnabled } from "../../../../plugins/auto-update";
13
13
  import { startNodePluginAutoUpdates } from "../../../../plugins/auto-update-node";
14
+ import { getPluginSeedProgress, subscribePluginSeed } from "../../../../plugins/seed-progress";
15
+ import { stopInstallCommands } from "../../../../plugins/running-installs";
14
16
  import { loadDesktopBackendPlugins } from "../../../../plugins/catalog-backend";
15
17
  import { startRemoteControlServer, type RemoteControlServer } from "../../../../remote/server";
16
18
  import type { RemoteControlRequest, RemoteControlResponse } from "../../../../remote/types";
@@ -46,6 +48,7 @@ import {
46
48
  takeExternalPluginBundles,
47
49
  } from "../external-plugins";
48
50
  import { MAIN_WINDOW_RPC_KEY, paneIdFromDetachedRpcKey } from "../window/focus";
51
+ import { runContextMenusOffThread } from "../window/context-menu-thread";
49
52
  import { measureNativeWindowCalls } from "../window/native-timing";
50
53
  import { createAppWindow } from "../window/create";
51
54
  import { desktopBootFramePath, desktopBootFramePreload, readDesktopBootFrame } from "../window/boot-frame";
@@ -214,8 +217,16 @@ export class DesktopBackend {
214
217
  // before the main window opens, so it runs before the shell's own
215
218
  // handlers wait for the windows to go.
216
219
  Electrobun.events.on("before-quit", () => {
220
+ stopInstallCommands();
217
221
  if (!this.quitting) this.windowController?.flush();
218
222
  });
223
+ // The launch restores plugins that moved into their own repositories in
224
+ // this process, after the services are up; the main window brings each
225
+ // in as it lands. Its init carries where the restore was then.
226
+ subscribePluginSeed(() => {
227
+ const seed = getPluginSeedProgress();
228
+ if (seed) this.readyMainWindowRpc()?.send["plugins.seedProgress"]({ seed });
229
+ });
219
230
  this.windowController.openWindow(MAIN_WINDOW_ID);
220
231
  this.windowController.focus(MAIN_WINDOW_ID);
221
232
  }
@@ -441,6 +452,7 @@ export class DesktopBackend {
441
452
  setStallSink((event) => recordStall("app", event));
442
453
  setStallClocks(createStallClocks());
443
454
  measureNativeWindowCalls();
455
+ runContextMenusOffThread();
444
456
  startMainThreadStallMonitor();
445
457
  }
446
458
  // The native menu shows the same accelerators the keys use, so a rebind
@@ -635,6 +647,8 @@ export class DesktopBackend {
635
647
  quit(): void {
636
648
  if (this.quitting) return;
637
649
  this.quitting = true;
650
+ // Plugin installs still running in the background end with the app.
651
+ stopInstallCommands();
638
652
  // The order a quit had with one window: the other windows close, the
639
653
  // services stop while the main window can still hear from them, and
640
654
  // the main window goes last.
@@ -11,6 +11,7 @@ import { safeExternalUrl } from "../../../../utils/external-url";
11
11
  import { getContextMenuRequestId, normalizeContextMenuItems } from "../context-menu/normalize";
12
12
  import { MAIN_WINDOW_RPC_KEY } from "../window/focus";
13
13
  import { applyDesktopWindowControl } from "../window/controls";
14
+ import { measureNativeCall } from "../window/native-timing";
14
15
  import { startSystemWindowMove, startSystemWindowResize } from "../window/windows-native";
15
16
  import { saveTextFileToDownloads } from "../../../../utils/save-text-file";
16
17
  import { setAppBadge } from "./app-badge";
@@ -138,10 +139,10 @@ export async function handleDesktopHostRequest(
138
139
  throw new Error("host.openExternal requires a URL.");
139
140
  }
140
141
  const externalUrl = safeExternalUrl(request.payload.url);
141
- return externalUrl ? Utils.openExternal(externalUrl) !== false : false;
142
+ return externalUrl ? measureNativeCall("utils.open-external", () => Utils.openExternal(externalUrl)) !== false : false;
142
143
  }
143
144
  case "host.copyText":
144
- Utils.clipboardWriteText(normalizeText(request.payload.text) ?? "");
145
+ measureNativeCall("utils.clipboard-write-text", () => Utils.clipboardWriteText(normalizeText(request.payload.text) ?? ""));
145
146
  return null;
146
147
  case "host.focusWindow": {
147
148
  const windowKey = backend.rpcs.getRpcWindowKey(rpc);
@@ -151,11 +152,11 @@ export async function handleDesktopHostRequest(
151
152
  case "host.copyPngImage": {
152
153
  const pngBase64 = normalizeText(request.payload.pngBase64);
153
154
  if (!pngBase64) throw new Error("host.copyPngImage requires PNG data.");
154
- Utils.clipboardWriteImage(new Uint8Array(Buffer.from(pngBase64, "base64")));
155
+ measureNativeCall("utils.clipboard-write-image", () => Utils.clipboardWriteImage(new Uint8Array(Buffer.from(pngBase64, "base64"))));
155
156
  return null;
156
157
  }
157
158
  case "host.readText":
158
- return Utils.clipboardReadText() ?? "";
159
+ return measureNativeCall("utils.clipboard-read-text", () => Utils.clipboardReadText()) ?? "";
159
160
  case "host.saveTextFile": {
160
161
  if (typeof request.payload.name !== "string" || typeof request.payload.text !== "string") {
161
162
  throw new Error("host.saveTextFile requires a name and text.");
@@ -164,19 +165,25 @@ export async function handleDesktopHostRequest(
164
165
  }
165
166
  case "host.notify":
166
167
  playNotificationSound(normalizeText(request.payload.sound));
167
- Utils.showNotification({
168
+ measureNativeCall("utils.show-notification", () => Utils.showNotification({
168
169
  title: normalizeText(request.payload.title) ?? "Gloom",
169
170
  body: normalizeText(request.payload.body),
170
171
  subtitle: normalizeText(request.payload.subtitle),
171
172
  silent: true,
172
- });
173
+ }));
173
174
  return null;
174
175
  case "host.showContextMenu": {
175
176
  const menu = normalizeContextMenuItems(request.payload.menu);
176
177
  if (menu.length === 0) return false;
177
178
  const requestId = getContextMenuRequestId(menu);
178
179
  if (requestId) backend.trackContextMenuRequest(requestId, rpc);
179
- ContextMenu.showContextMenu(menu as never);
180
+ // On Windows the menu opens on a thread of its own (context-menu-thread.ts)
181
+ // and this returns at once. Where that thread failed, the menu holds
182
+ // this thread until it closes, the freeze the thread removes: a stall.
183
+ // Elsewhere a menu that holds the thread waits on the person.
184
+ measureNativeCall("context-menu.show", () => ContextMenu.showContextMenu(menu as never), {
185
+ waitsOnPerson: process.platform !== "win32",
186
+ });
180
187
  return true;
181
188
  }
182
189
  case "host.saveBootFrame":
@@ -3,8 +3,9 @@ import { makePrivateDirSync } from "../../../../utils/private-files";
3
3
  import { homedir, hostname } from "os";
4
4
  import { getGloomberbDirs } from "../../../../data/config/home";
5
5
  import type { AppServices } from "../../../../core/app-services";
6
- import { restoreExtractedPlugins } from "../../../../cli/restore-plugins";
7
- import { takePluginSeedNotice } from "../../../../plugins/seed-notice";
6
+ import { prepareExtractedPluginSeed } from "../../../../cli/restore-plugins";
7
+ import { getPluginSeedProgress, type PluginSeedRecord } from "../../../../plugins/seed-progress";
8
+ import { logFailure } from "../../../../utils/log-failure";
8
9
  import {
9
10
  getDataDir,
10
11
  initDataDir,
@@ -82,8 +83,9 @@ function buildInitializationPayload(
82
83
  windowKey: string | undefined,
83
84
  ): ElectrobunBackendInit {
84
85
  const mainWindow = windowTarget.windowId === MAIN_WINDOW_RPC_KEY;
85
- // The main window says once what the launch's seed could not install.
86
- const pluginSeedNotice = mainWindow ? takePluginSeedNotice() : null;
86
+ // The main window brings in the plugins the launch restores as they land,
87
+ // and says what it could not install; later changes follow as messages.
88
+ const pluginSeed = mainWindow ? getPluginSeedProgress() : null;
87
89
  // Each full window draws its own tabs; a popped-out pane's draws the main
88
90
  // window's. Numbered like every state sent, so the window's first sync is
89
91
  // merged against it.
@@ -104,7 +106,7 @@ function buildInitializationPayload(
104
106
  paneId: windowTarget.paneId,
105
107
  ...(windowTarget.windowId ? { windowId: windowTarget.windowId, windows: backend.windowInfos() } : {}),
106
108
  ...(mainWindow ? { otherWindowTabs: backend.otherWindowTabsForInit() } : {}),
107
- ...(pluginSeedNotice ? { pluginSeedNotice } : {}),
109
+ ...(pluginSeed ? { pluginSeed } : {}),
108
110
  telemetry: {
109
111
  installId: readOrCreateInstallId(config.dataDir),
110
112
  os: describeNodeOs(),
@@ -126,8 +128,12 @@ async function resolveDesktopDataDir(): Promise<string> {
126
128
  /** The launch work, in order. Injected so a test can watch the order without a data folder. */
127
129
  export interface DesktopLaunchSteps {
128
130
  readConfig(): Promise<AppConfig>;
129
- /** Installs plugins that moved into their own repositories; returns the seed record to merge. */
130
- restorePlugins(): Promise<Partial<AppConfig> | null>;
131
+ /**
132
+ * Plans the restore of plugins that moved into their own repositories:
133
+ * the record to merge into the config, and the installs to start once the
134
+ * services are up. Reads the disk only.
135
+ */
136
+ planPluginRestore(): Promise<{ record: PluginSeedRecord; start: (() => Promise<unknown>) | null } | null>;
131
137
  startServices(config: AppConfig): Promise<unknown>;
132
138
  /** Starts compiling the plugins for the view; not awaited. */
133
139
  prefetchPluginBundles(): void;
@@ -136,11 +142,11 @@ export interface DesktopLaunchSteps {
136
142
  function desktopLaunchSteps(backend: DesktopBackend): DesktopLaunchSteps {
137
143
  return {
138
144
  readConfig: async () => initDataDir(await resolveDesktopDataDir()),
139
- // Restore plugins that moved into their own repositories before the
140
- // catalog is read, the same as the terminal does at startup. Without it a
141
- // desktop-only user silently loses a feature the day it is extracted,
142
- // since nothing else installs it for them.
143
- restorePlugins: restoreExtractedPlugins,
145
+ // Restore plugins that moved into their own repositories, the same as the
146
+ // terminal does at startup. Without it a desktop-only user silently loses
147
+ // a feature the day it is extracted, since nothing else installs it for
148
+ // them.
149
+ planPluginRestore: () => prepareExtractedPluginSeed(),
144
150
  startServices: (config) => backend.startServices(config),
145
151
  prefetchPluginBundles: () => backend.prefetchExternalPluginBundles(),
146
152
  };
@@ -169,9 +175,13 @@ export function startDesktopBackend(
169
175
  if (backend.config && backend.services) return Promise.resolve();
170
176
  const launch = (async () => {
171
177
  const initialConfig = await steps.readConfig();
172
- const seed = await steps.restorePlugins();
173
- await steps.startServices(seed ? { ...initialConfig, ...seed } : initialConfig);
178
+ const seed = await steps.planPluginRestore();
179
+ await steps.startServices(seed ? { ...initialConfig, ...seed.record } : initialConfig);
174
180
  steps.prefetchPluginBundles();
181
+ // In the background: the window draws without them, and the main window
182
+ // brings each in as it lands. Never awaited by a launch, so a clone that
183
+ // hangs holds nothing up.
184
+ void seed?.start?.().catch(logFailure("plugin-seed", "Plugin restore failed"));
175
185
  })();
176
186
  launches.set(backend, launch);
177
187
  const settled = () => {
@@ -14,6 +14,7 @@ import { renameLegacyMacApp } from "./desktop/app-name";
14
14
  import { scheduleDesktopRelaunch } from "./desktop/relaunch";
15
15
  import { settleInstallerFolder } from "./desktop/installer-folder";
16
16
  import { ensureInstallRecords } from "./desktop/install-records";
17
+ import { runWebviewScriptsOffThread } from "./window/webview-script-thread";
17
18
 
18
19
  console.log = (...args) => console.error(...args);
19
20
  console.info = (...args) => console.error(...args);
@@ -31,6 +32,10 @@ setConfigStoreHost(nodeConfigStoreHost);
31
32
  // before the config, and its off switch, has been read.
32
33
  installProcessCrashListeners();
33
34
 
35
+ // Before any window opens: on Windows each message to a window is a script
36
+ // whose native call waits on the thread that runs the windows.
37
+ runWebviewScriptsOffThread();
38
+
34
39
  // A Windows install from before Electrobun 2 lives in the installer's folder.
35
40
  // Its last update put this build in Electrobun's folder, the only one
36
41
  // Electrobun 2 updates: the installer's folder is retired in the background.
@@ -0,0 +1,84 @@
1
+ import { ContextMenu } from "electrobun/bun";
2
+ import { reportCrash } from "../../../../telemetry/crash-reports";
3
+ import { debugLog } from "../../../../utils/debug-log";
4
+ import { nativeWrapperLibraryPath, startNativeCallThread, type NativeCallThread, type NativeCallThreadFailure } from "./native-call-thread";
5
+ import { measureNativeCall } from "./native-timing";
6
+
7
+ const menuLog = debugLog.createLogger("context-menu-thread");
8
+
9
+ /**
10
+ * Past this a menu's call counts as stuck: a person picks or dismisses a
11
+ * menu well within it, and Windows closes one when the app loses focus.
12
+ */
13
+ const MENU_CALL_LIMIT_MS = 60_000;
14
+ /** A menu asked for longer ago than this is not shown late. */
15
+ const REPLAY_WITHIN_MS = 5_000;
16
+ /**
17
+ * After this many stuck threads in a row, menus open on the app's thread. A
18
+ * menu that closes starts the count again: one left open past the limit,
19
+ * or open while the computer slept, is not a thread that cannot show menus.
20
+ */
21
+ const MAX_STUCK_THREADS = 3;
22
+
23
+ let installed = false;
24
+ let reported = false;
25
+
26
+ /**
27
+ * Once per process, and only once it happens: menus waiting on the app's
28
+ * thread again is the freeze this thread removes, so error tracking hears
29
+ * of it, and the menus themselves count as stalls (host-requests.ts).
30
+ */
31
+ function reportMenuThreadFailure(failure: NativeCallThreadFailure | "unavailable"): void {
32
+ if (reported) return;
33
+ reported = true;
34
+ reportCrash(
35
+ { name: "ContextMenuThread", message: `Context menus could not open off the app's thread: ${failure}` },
36
+ { kind: "plugin", plugin: "stall-monitor" },
37
+ );
38
+ }
39
+
40
+ /**
41
+ * On Windows a context menu's native call waits on the thread that runs the
42
+ * windows until the menu closes, which is as long as the person takes to
43
+ * pick from it. It goes to a thread of its own, started with the first menu.
44
+ * Where that thread cannot run, menus open on this thread as before, those
45
+ * it took and never began included; a stuck one is replaced by a new thread.
46
+ */
47
+ export function runContextMenusOffThread(platform: string = process.platform): void {
48
+ if (platform !== "win32" || installed) return;
49
+ installed = true;
50
+ /** Undefined: started with the next menu. Null: menus open on this thread. */
51
+ let thread: NativeCallThread | null | undefined;
52
+ let stuckThreads = 0;
53
+ const encoder = new TextEncoder();
54
+
55
+ const start = (): NativeCallThread | null => {
56
+ const started = startNativeCallThread(nativeWrapperLibraryPath(), "showContextMenu", {
57
+ callLimitMs: MENU_CALL_LIMIT_MS,
58
+ onCallDone: () => {
59
+ stuckThreads = 0;
60
+ },
61
+ onFailure: (failure, unstarted) => {
62
+ reportMenuThreadFailure(failure);
63
+ stuckThreads += failure === "stuck" ? 1 : 0;
64
+ thread = failure === "stuck" && stuckThreads < MAX_STUCK_THREADS ? undefined : null;
65
+ const now = performance.now();
66
+ for (const call of unstarted) {
67
+ if (now - call.takenAt <= REPLAY_WITHIN_MS) call.replay();
68
+ else menuLog.warn("A context menu asked for too long ago was not shown", { ageMs: Math.round(now - call.takenAt) });
69
+ }
70
+ },
71
+ });
72
+ if (!started) reportMenuThreadFailure("unavailable");
73
+ return started;
74
+ };
75
+
76
+ const show = (menuConfig: string, handler: number, showHere: () => void): boolean => {
77
+ if (thread === undefined) thread = start();
78
+ if (!thread) return false;
79
+ return thread.call(encoder.encode(`${menuConfig}\0`), handler, () => {
80
+ if (!show(menuConfig, handler, showHere)) measureNativeCall("context-menu.show", showHere);
81
+ });
82
+ };
83
+ ContextMenu.setContextMenuRunner(show);
84
+ }
@@ -0,0 +1,224 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { debugLog } from "../../../../utils/debug-log";
4
+
5
+ const threadLog = debugLog.createLogger("native-call-thread");
6
+
7
+ /**
8
+ * Electrobun's native library, where its SDK opens it for this process: the
9
+ * working folder, else beside the running Bun. Another thread opens the same
10
+ * one, already loaded.
11
+ */
12
+ export function nativeWrapperLibraryPath(): string {
13
+ const name = `libNativeWrapper.${process.platform === "win32" ? "dll" : process.platform === "darwin" ? "dylib" : "so"}`;
14
+ const candidates = [join(process.cwd(), name), join(dirname(process.argv0 || process.execPath), name), join(dirname(process.execPath), name)];
15
+ return candidates.find((path) => existsSync(path)) ?? candidates[0]!;
16
+ }
17
+
18
+ /**
19
+ * Runs on a thread of its own: opens the library once, then makes each call
20
+ * it is sent, one at a time and in order, saying when each starts and ends.
21
+ * The bytes stay alive in the message until the call returns.
22
+ */
23
+ const WORKER_SOURCE = `
24
+ import { dlopen, ptr } from "bun:ffi";
25
+ let call = null;
26
+ let pointerFirst = false;
27
+ self.onmessage = (event) => {
28
+ const message = event.data;
29
+ if (message.type === "open") {
30
+ try {
31
+ pointerFirst = message.pointerFirst === true;
32
+ call = dlopen(message.library, { [message.symbol]: { args: ["ptr", "ptr"], returns: "void" } }).symbols[message.symbol];
33
+ postMessage({ type: "ready" });
34
+ } catch (error) {
35
+ postMessage({ type: "failed", message: String(error && error.message || error) });
36
+ }
37
+ return;
38
+ }
39
+ if (message.type === "call") {
40
+ if (!call) return;
41
+ postMessage({ type: "started", id: message.id });
42
+ const startedAt = performance.now();
43
+ try {
44
+ if (pointerFirst) call(message.pointer || null, ptr(message.bytes));
45
+ else call(ptr(message.bytes), message.pointer || null);
46
+ postMessage({ type: "done", id: message.id, ms: performance.now() - startedAt });
47
+ } catch (error) {
48
+ postMessage({ type: "failed", id: message.id, message: String(error && error.message || error) });
49
+ }
50
+ }
51
+ };
52
+ `;
53
+
54
+ /**
55
+ * Why the thread stopped taking calls: the library would not open on it, the
56
+ * thread ended, or a call ran past `callLimitMs` and everything behind it
57
+ * would have waited for good.
58
+ */
59
+ export type NativeCallThreadFailure = "open-failed" | "ended" | "stuck";
60
+
61
+ /** A call the thread took and never began. */
62
+ export interface UnstartedNativeCall {
63
+ /** When it was taken (performance.now()). */
64
+ takenAt: number;
65
+ /** What the caller gave `call` to make it another way. */
66
+ replay(): void;
67
+ }
68
+
69
+ export interface NativeCallThreadOptions {
70
+ /** Each call that returned, and how long it took. */
71
+ onCallDone?(ms: number): void;
72
+ /**
73
+ * The thread takes no more calls. `unstarted`: those it took and never
74
+ * began, oldest first, for the caller to make another way. A call that
75
+ * began and had not returned is not among them: it may be showing.
76
+ */
77
+ onFailure?(failure: NativeCallThreadFailure, unstarted: UnstartedNativeCall[]): void;
78
+ /** A call running this long counts the thread as stuck. */
79
+ callLimitMs?: number;
80
+ /** `symbol(pointer, bytes)` rather than `symbol(bytes, pointer)`. */
81
+ pointerFirst?: boolean;
82
+ }
83
+
84
+ export interface NativeCallThread {
85
+ /**
86
+ * Queues `symbol(bytes, pointer)` (or `symbol(pointer, bytes)`) and returns at once. False when the
87
+ * thread cannot take it, and the caller makes the call itself; `replay`
88
+ * makes it another way if the thread stops before beginning it.
89
+ */
90
+ call(bytes: Uint8Array, pointer: number | null, replay: () => void): boolean;
91
+ close(): void;
92
+ }
93
+
94
+ interface WorkerMessage {
95
+ type: "ready" | "failed" | "started" | "done";
96
+ id?: number;
97
+ ms?: number;
98
+ message?: string;
99
+ }
100
+
101
+ interface OwedCall extends UnstartedNativeCall {
102
+ started: boolean;
103
+ }
104
+
105
+ /**
106
+ * A native call that waits on another thread, made from a thread of its own
107
+ * so this one keeps running. On Windows, Electrobun's native calls wait for
108
+ * the thread that runs the windows to answer them. That thread answers a
109
+ * context menu's only once the menu closes, and a script for a window (every
110
+ * message the app sends one) whenever it gets to it: made here, the app
111
+ * froze for as long as a menu was open or that thread was busy.
112
+ *
113
+ * `symbol` takes a pointer to the bytes and one pointer, in either order.
114
+ * Null where there is no Worker to run it on.
115
+ */
116
+ export function startNativeCallThread(
117
+ library: string,
118
+ symbol: string,
119
+ options: NativeCallThreadOptions = {},
120
+ ): NativeCallThread | null {
121
+ if (typeof Worker === "undefined" || typeof Blob === "undefined" || typeof URL.createObjectURL !== "function") return null;
122
+ const source = URL.createObjectURL(new Blob([WORKER_SOURCE], { type: "application/javascript" }));
123
+ let worker: Worker;
124
+ try {
125
+ worker = new Worker(source);
126
+ } catch (error) {
127
+ threadLog.warn("Could not start a thread for native calls", { error: String(error) });
128
+ URL.revokeObjectURL(source);
129
+ return null;
130
+ }
131
+ (worker as { unref?: () => void }).unref?.();
132
+ let stopped = false;
133
+ let nextId = 1;
134
+ const owed = new Map<number, OwedCall>();
135
+ let stuckTimer: ReturnType<typeof setTimeout> | null = null;
136
+
137
+ const clearStuckTimer = () => {
138
+ if (stuckTimer) clearTimeout(stuckTimer);
139
+ stuckTimer = null;
140
+ };
141
+
142
+ const stop = () => {
143
+ stopped = true;
144
+ clearStuckTimer();
145
+ try {
146
+ // A thread inside a native call ends once the call returns.
147
+ worker.terminate();
148
+ } catch {
149
+ // Intentional ignore: a thread that cannot be stopped is already gone.
150
+ }
151
+ URL.revokeObjectURL(source);
152
+ };
153
+
154
+ const fail = (failure: NativeCallThreadFailure, reason: string) => {
155
+ if (stopped) return;
156
+ const unstarted = [...owed.values()].filter((call) => !call.started).map(({ takenAt, replay }) => ({ takenAt, replay }));
157
+ threadLog.warn("The thread for native calls stopped", { failure, reason, unstarted: unstarted.length, running: owed.size - unstarted.length });
158
+ owed.clear();
159
+ stop();
160
+ options.onFailure?.(failure, unstarted);
161
+ };
162
+
163
+ worker.onmessage = (event: MessageEvent<WorkerMessage>) => {
164
+ const message = event.data;
165
+ if (message.type === "failed") {
166
+ if (message.id === undefined) {
167
+ fail("open-failed", message.message ?? "could not open the library");
168
+ return;
169
+ }
170
+ owed.delete(message.id);
171
+ clearStuckTimer();
172
+ threadLog.warn("A native call failed on its thread", { message: message.message });
173
+ return;
174
+ }
175
+ if (message.type === "started" && message.id !== undefined) {
176
+ const call = owed.get(message.id);
177
+ if (call) call.started = true;
178
+ const limitMs = options.callLimitMs;
179
+ if (limitMs !== undefined) {
180
+ clearStuckTimer();
181
+ stuckTimer = setTimeout(() => fail("stuck", `a call ran past ${limitMs} ms`), limitMs);
182
+ (stuckTimer as { unref?: () => void }).unref?.();
183
+ }
184
+ return;
185
+ }
186
+ if (message.type === "done" && message.id !== undefined) {
187
+ owed.delete(message.id);
188
+ clearStuckTimer();
189
+ options.onCallDone?.(message.ms ?? 0);
190
+ }
191
+ };
192
+ worker.onerror = (event) => {
193
+ fail("ended", event instanceof ErrorEvent ? event.message : "the thread failed");
194
+ };
195
+ worker.addEventListener("close", () => fail("ended", "the thread ended"));
196
+
197
+ try {
198
+ worker.postMessage({ type: "open", library, symbol, pointerFirst: options.pointerFirst === true });
199
+ } catch (error) {
200
+ stop();
201
+ threadLog.warn("Could not start a thread for native calls", { error: String(error) });
202
+ return null;
203
+ }
204
+
205
+ return {
206
+ call(bytes, pointer, replay) {
207
+ if (stopped) return false;
208
+ const id = nextId++;
209
+ try {
210
+ worker.postMessage({ type: "call", id, bytes, pointer });
211
+ } catch (error) {
212
+ fail("ended", error instanceof Error ? error.message : String(error));
213
+ return false;
214
+ }
215
+ owed.set(id, { takenAt: performance.now(), replay, started: false });
216
+ return true;
217
+ },
218
+ close() {
219
+ if (stopped) return;
220
+ owed.clear();
221
+ stop();
222
+ },
223
+ };
224
+ }
@@ -46,3 +46,13 @@ export function measureNativeWindowCalls(): void {
46
46
  measureCalls(BrowserWindow.prototype, "native.window", WINDOW_CALLS);
47
47
  measureCalls(BrowserView.prototype, "native.view", VIEW_CALLS);
48
48
  }
49
+
50
+ /**
51
+ * Measures one of Electrobun's other native calls (a menu, the clipboard, a
52
+ * notification) as `native.<name>`: on Windows each waits for the thread that
53
+ * runs the windows, as the window calls do. `waitsOnPerson`: the call returns
54
+ * when a person chooses (a menu), so its time is not a freeze.
55
+ */
56
+ export function measureNativeCall<T>(name: string, call: () => T, options?: { waitsOnPerson?: boolean }): T {
57
+ return measurePerf(`native.${name}`, call, undefined, { waitedOnPerson: options?.waitsOnPerson });
58
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `js`, made to run only in the page of the webview it was sent to.
3
+ *
4
+ * Off the app's thread a script reaches its webview by the webview's native
5
+ * pointer, taken when it was sent. A webview opened after that one closed
6
+ * can reuse the pointer, and the script would run there: its RPC answers
7
+ * could settle the other page's requests. The page knows its own webview id
8
+ * (Electrobun's preload sets it), and ids are never reused, so anywhere else
9
+ * the script does nothing. The scripts are Electrobun's message calls; a
10
+ * block around them changes nothing where they run.
11
+ */
12
+ export function scriptForWebview(webviewId: number, js: string): string {
13
+ if (!Number.isSafeInteger(webviewId)) throw new Error(`Not a webview id: ${webviewId}`);
14
+ return `if (window.__electrobunWebviewId === ${webviewId}) {\n${js}\n}`;
15
+ }
@@ -0,0 +1,82 @@
1
+ import { BrowserView } from "electrobun/bun";
2
+ import { reportCrash } from "../../../../telemetry/crash-reports";
3
+ import { nativeWrapperLibraryPath, startNativeCallThread, type NativeCallThread, type NativeCallThreadFailure } from "./native-call-thread";
4
+ import { scriptForWebview } from "./script-for-webview";
5
+
6
+ /**
7
+ * Past this a script's call counts as stuck: the thread that runs the
8
+ * windows takes one in milliseconds, and keeps taking them while a menu is
9
+ * open or a window is held mid-move. The app's own freeze watchdog waits
10
+ * as long.
11
+ */
12
+ const SCRIPT_CALL_LIMIT_MS = 30_000;
13
+ /** After this many stuck threads in a row, scripts run on the app's thread. */
14
+ const MAX_STUCK_THREADS = 3;
15
+
16
+ let installed = false;
17
+ let reported = false;
18
+
19
+ /**
20
+ * Once per process, and only once it happens: scripts waiting on the app's
21
+ * thread again, or piling up behind a call that does not return, is the
22
+ * freeze this thread removes, so error tracking hears of it.
23
+ */
24
+ function reportScriptThreadFailure(failure: NativeCallThreadFailure | "unavailable"): void {
25
+ if (reported) return;
26
+ reported = true;
27
+ reportCrash(
28
+ { name: "WebviewScriptThread", message: `Messages to windows could not go off the app's thread: ${failure}` },
29
+ { kind: "plugin", plugin: "stall-monitor" },
30
+ );
31
+ }
32
+
33
+ /**
34
+ * On Windows every message the app sends a window goes as a script (it has
35
+ * no socket there), and the script's native call waits until the thread
36
+ * that runs the windows takes it, so the app stood still whenever that
37
+ * thread was busy. Scripts go to a thread of their own, started with the
38
+ * first one, and run there in the order they were sent, each only in the
39
+ * page it was sent to (script-for-webview.ts).
40
+ *
41
+ * A call that does not return within the limit gives the thread up: the
42
+ * scripts behind it go to a new thread, in order, so they neither pile up
43
+ * behind it for good nor wait on this thread. After three stuck threads in
44
+ * a row, or where no thread can run, scripts run on this thread as before,
45
+ * the ones a thread took and never began first, so none is lost or
46
+ * overtaken.
47
+ */
48
+ export function runWebviewScriptsOffThread(platform: string = process.platform): void {
49
+ if (platform !== "win32" || installed) return;
50
+ installed = true;
51
+ /** Undefined: started with the next script. Null: scripts run on this thread. */
52
+ let thread: NativeCallThread | null | undefined;
53
+ let stuckThreads = 0;
54
+ const encoder = new TextEncoder();
55
+
56
+ const start = (): NativeCallThread | null => {
57
+ const started = startNativeCallThread(nativeWrapperLibraryPath(), "evaluateJavaScriptWithNoCompletion", {
58
+ pointerFirst: true,
59
+ callLimitMs: SCRIPT_CALL_LIMIT_MS,
60
+ onCallDone: () => {
61
+ stuckThreads = 0;
62
+ },
63
+ onFailure: (failure, unstarted) => {
64
+ reportScriptThreadFailure(failure);
65
+ stuckThreads += failure === "stuck" ? 1 : 0;
66
+ thread = failure === "stuck" && stuckThreads < MAX_STUCK_THREADS ? undefined : null;
67
+ for (const call of unstarted) call.replay();
68
+ },
69
+ });
70
+ if (!started) reportScriptThreadFailure("unavailable");
71
+ return started;
72
+ };
73
+
74
+ const run = (js: string, webviewId: number, webview: number, runHere: () => void): boolean => {
75
+ if (thread === undefined) thread = start();
76
+ if (!thread) return false;
77
+ return thread.call(encoder.encode(`${scriptForWebview(webviewId, js)}\0`), webview, () => {
78
+ if (!run(js, webviewId, webview, runHere)) runHere();
79
+ });
80
+ };
81
+ BrowserView.setScriptRunner(run);
82
+ }