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
@@ -6,6 +6,7 @@ import { debugLog } from "../utils/debug-log";
6
6
  import { getPluginsDir } from "./loader";
7
7
  import { encodeBuiltinDisabledPluginIds } from "./ownership";
8
8
  import { pluginDirectoryNames } from "./plugin-names";
9
+ import { samePluginSeedFailure, type PluginSeedNotice } from "./seed-progress";
9
10
 
10
11
  const log = debugLog.createLogger("plugin-seed");
11
12
 
@@ -37,6 +38,12 @@ export const EXTRACTED_PLUGINS = [
37
38
 
38
39
  type ExtractedPlugin = (typeof EXTRACTED_PLUGINS)[number];
39
40
 
41
+ /** Where an install landed: its folder, and the sibling plugins it brought along. */
42
+ interface SeedInstall {
43
+ directory: string;
44
+ peers?: string[];
45
+ }
46
+
40
47
  export interface SeedResult {
41
48
  installed: string[];
42
49
  failed: string[];
@@ -49,17 +56,18 @@ export interface SeedResult {
49
56
  * was renamed sits in a directory under the old one. Missing that install would
50
57
  * clone a second copy, and the loader refuses the duplicate id.
51
58
  */
52
- function isInstalled(directory: string, pluginsDir: string): boolean {
53
- return pluginDirectoryNames(directory).some((name) => existsSync(join(pluginsDir, name)));
59
+ function installedDirectory(directory: string, pluginsDir: string): string | null {
60
+ return pluginDirectoryNames(directory).find((name) => existsSync(join(pluginsDir, name))) ?? null;
54
61
  }
55
62
 
56
63
  /**
57
64
  * The plugins left to install, each neither recorded as seeded, installed
58
65
  * already, nor switched off before the move, and the ids to record as seeded
59
66
  * without installing them. After a launch's seed, `pending` is what it could
60
- * not install.
67
+ * not install. Reads only the config and the plugins folder, so a launch can
68
+ * know before its first frame what it will install after.
61
69
  */
62
- function classifyExtractedPlugins(config: AppConfig, pluginsDir: string): { pending: ExtractedPlugin[]; settled: string[] } {
70
+ export function classifyExtractedPlugins(config: AppConfig, pluginsDir: string = getPluginsDir()): { pending: ExtractedPlugin[]; settled: string[] } {
63
71
  const alreadySeeded = new Set(config.seededPlugins ?? []);
64
72
  // A previous owner that is now a group of built-ins counts as off only while
65
73
  // all of them are, which is when its id is saved.
@@ -74,7 +82,7 @@ function classifyExtractedPlugins(config: AppConfig, pluginsDir: string): { pend
74
82
  // Present already (installed by hand, or seeded before this record
75
83
  // existed), or turned off before the move, which restoring it would
76
84
  // override: recorded so we stop looking.
77
- if (isInstalled(entry.directory, pluginsDir)
85
+ if (installedDirectory(entry.directory, pluginsDir)
78
86
  || disabled.has(entry.id) || ("previousOwnerIds" in entry && entry.previousOwnerIds.some((id) => disabled.has(id)))) {
79
87
  settled.push(entry.id);
80
88
  continue;
@@ -85,30 +93,57 @@ function classifyExtractedPlugins(config: AppConfig, pluginsDir: string): { pend
85
93
  }
86
94
 
87
95
  /**
88
- * Installs any extracted plugin the user has not seen yet.
96
+ * Installs any extracted plugin the user has not seen yet, one at a time, and
97
+ * reports each as it settles (`onSettled`, with where it landed when it did).
98
+ * `plan` is what a launch worked out before its first frame, so each plugin it
99
+ * said it would install is reported, even one another Gloom installed since.
89
100
  *
90
101
  * Best effort by design: a failure is logged and retried on the next launch
91
102
  * rather than recorded, because the common cause is being offline at startup and
92
- * marking it seeded would silently drop the plugin forever.
103
+ * marking it seeded would silently drop the plugin forever. A plugin that is
104
+ * there by the time its turn comes (a sibling's install brought it along, or
105
+ * another Gloom running beside this one installed it) counts as installed.
93
106
  */
94
107
  export async function seedExtractedPlugins(
95
108
  config: AppConfig,
96
- installPlugin: (ref: string) => Promise<unknown>,
109
+ installPlugin: (ref: string) => Promise<SeedInstall | void>,
97
110
  pluginsDir: string = getPluginsDir(),
111
+ onSettled?: (id: string, installed: SeedInstall | null) => void,
112
+ plan: { pending: readonly ExtractedPlugin[]; settled: readonly string[] } = classifyExtractedPlugins(config, pluginsDir),
98
113
  ): Promise<SeedResult> {
99
- const { pending, settled } = classifyExtractedPlugins(config, pluginsDir);
114
+ const { pending, settled } = plan;
100
115
  const result: SeedResult = { installed: [], failed: [], seeded: [...config.seededPlugins ?? [], ...settled] };
116
+ // A report that fails never changes what happened to the install it reports.
117
+ const report = (id: string, installed: SeedInstall | null) => {
118
+ try {
119
+ onSettled?.(id, installed);
120
+ } catch (error) {
121
+ log.error(`Could not report ${id}: ${error instanceof Error ? error.message : String(error)}`);
122
+ }
123
+ };
101
124
 
102
125
  for (const entry of pending) {
103
- try {
104
- log.info(`Restoring ${entry.id} from ${entry.repo}`);
105
- await installPlugin(entry.repo);
126
+ let installed: SeedInstall | null = null;
127
+ const present = installedDirectory(entry.directory, pluginsDir);
128
+ if (present) {
129
+ installed = { directory: present };
130
+ } else {
131
+ try {
132
+ log.info(`Restoring ${entry.id} from ${entry.repo}`);
133
+ installed = await installPlugin(entry.repo) ?? { directory: entry.directory };
134
+ } catch (error) {
135
+ const raced = installedDirectory(entry.directory, pluginsDir);
136
+ if (raced) installed = { directory: raced };
137
+ else log.error(`Could not restore ${entry.id}: ${error instanceof Error ? error.message : String(error)}`);
138
+ }
139
+ }
140
+ if (installed) {
106
141
  result.installed.push(entry.id);
107
142
  result.seeded.push(entry.id);
108
- } catch (error) {
109
- log.error(`Could not restore ${entry.id}: ${error}`);
143
+ } else {
110
144
  result.failed.push(entry.id);
111
145
  }
146
+ report(entry.id, installed);
112
147
  }
113
148
 
114
149
  return result;
@@ -134,16 +169,6 @@ export function pluginSeedFailure(failedIds: readonly string[], gitMissing: bool
134
169
  return failedIds.length > 0 ? { plugins: [...new Set(failedIds)].sort(), gitMissing } : undefined;
135
170
  }
136
171
 
137
- /** Whether two recorded seed failures are the same: the same plugins, for the same reason. */
138
- export function samePluginSeedFailure(a: PluginSeedFailure | undefined, b: PluginSeedFailure | undefined): boolean {
139
- return a?.gitMissing === b?.gitMissing && (a?.plugins ?? []).join() === (b?.plugins ?? []).join();
140
- }
141
-
142
- export interface PluginSeedNotice {
143
- body: string;
144
- type: "error" | "info";
145
- }
146
-
147
172
  /**
148
173
  * The one notice a launch shows when its seed left official plugins
149
174
  * uninstalled. A missing git, the usual cause on Windows, is an error said at
@@ -1,11 +1,11 @@
1
1
  import { logFailure } from "../utils/log-failure";
2
2
  import { basename, join, resolve } from "path";
3
- import { existsSync, lstatSync, mkdirSync, readdirSync, rmSync, symlinkSync } from "fs";
3
+ import { existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, symlinkSync } from "fs";
4
4
  import { execFile as execFileCallback, execFileSync, spawn } from "child_process";
5
5
  import { promisify } from "util";
6
6
  import { findAbsorbedPlugin, type AbsorbedPlugin } from "./absorbed";
7
7
  import type { PluginPin } from "./marketplace/store";
8
- import { bunCommand, recordDependencyInstall } from "./dependencies";
8
+ import { bunCommand, missingPluginDependencies, recordDependencyInstall } from "./dependencies";
9
9
  import { linkHostPackages, missingPeerPlugins } from "./host-link";
10
10
  import { importSiblingsFromTheirFolders } from "./peer-imports";
11
11
  import {
@@ -19,6 +19,7 @@ import {
19
19
  import { pluginDirectoryNames } from "./plugin-names";
20
20
  import { gitInstallAdvice } from "./extracted-plugins";
21
21
  import { pluginFromModule } from "./plugin-export";
22
+ import { INSTALL_TIMED_OUT, trackInstallCommand } from "./running-installs";
22
23
  import type { GloomPlugin } from "../types/plugin";
23
24
  import { cliStyles } from "../utils/cli-output";
24
25
  import { compareSemver, requiredGloomberb } from "../utils/semver";
@@ -103,6 +104,19 @@ export interface PluginInstallOptions {
103
104
  */
104
105
  quiet?: boolean;
105
106
  pin?: PluginPin;
107
+ /**
108
+ * How long each git command, and the dependency install, may run before it
109
+ * is stopped and the install fails with the code `INSTALL_TIMED_OUT`. No
110
+ * limit when absent.
111
+ */
112
+ timeouts?: { gitMs: number; dependenciesMs: number };
113
+ /**
114
+ * Fail, leaving nothing installed, when the plugin's dependencies do not
115
+ * all install, rather than keep a checkout that only loads once the loader
116
+ * fetches them. For an install nobody is watching, which the next launch
117
+ * retries.
118
+ */
119
+ requireDependencies?: boolean;
106
120
  }
107
121
 
108
122
  export interface PluginDirectoryInfo {
@@ -115,7 +129,7 @@ export interface PluginDirectoryInfo {
115
129
  }
116
130
 
117
131
  class GitError extends Error {
118
- constructor(message: string, readonly stderr: string) {
132
+ constructor(message: string, readonly stderr: string, readonly timedOut = false) {
119
133
  super(stderr.trim() ? `${message}: ${stderr.trim().split("\n").pop()}` : message);
120
134
  this.name = "GitError";
121
135
  }
@@ -125,6 +139,16 @@ interface RunResult {
125
139
  code: number | null;
126
140
  stdout: string;
127
141
  stderr: string;
142
+ /** Stopped at its time limit. */
143
+ timedOut?: boolean;
144
+ }
145
+
146
+ /** How long a command stopped at its time limit has to exit before it is killed. */
147
+ const KILL_GRACE_MS = 2_000;
148
+
149
+
150
+ function seconds(ms: number): string {
151
+ return `${Math.round(ms / 1000)} s`;
128
152
  }
129
153
 
130
154
  /** Resolves git before a command changes into a plugin checkout. */
@@ -134,11 +158,30 @@ function gitExecutable(): string {
134
158
  return executable;
135
159
  }
136
160
 
161
+ /** Ends a Windows process and every process it started; `fallback` when taskkill cannot run. */
162
+ function stopWindowsTree(pid: number, fallback: () => void): void {
163
+ const killer = spawn("taskkill", ["/T", "/F", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
164
+ killer.once("error", () => {
165
+ try {
166
+ fallback();
167
+ } catch {
168
+ // Intentional ignore: it exited between the check and the signal.
169
+ }
170
+ });
171
+ killer.unref();
172
+ }
173
+
137
174
  /**
138
175
  * Runs a command without blocking the event loop: a fetch or `bun install`
139
176
  * takes seconds, and the terminal UI and the desktop's Bun process keep
140
177
  * serving the app while a plugin updates in the background. Rejects only
141
178
  * when the command cannot be started at all.
179
+ *
180
+ * With `timeoutMs`, a command still running then is stopped and the result
181
+ * says so at once: a clone whose connection stalls would otherwise hold its
182
+ * install for good. The helpers git starts for the transfer are stopped with
183
+ * it: off Windows it runs in a process group of its own, and on Windows
184
+ * `taskkill /T` ends its process tree, where a signal reaches only git.
142
185
  */
143
186
  function run(
144
187
  command: string,
@@ -146,15 +189,56 @@ function run(
146
189
  cwd: string,
147
190
  output: { stdout: "pipe" | "inherit"; stderr: "pipe" | "inherit" },
148
191
  env?: NodeJS.ProcessEnv,
192
+ timeoutMs?: number,
149
193
  ): Promise<RunResult> {
150
194
  return new Promise((resolveRun, reject) => {
151
- const child = spawn(command === "git" ? gitExecutable() : command, args, { cwd, env, stdio: ["ignore", output.stdout, output.stderr] });
195
+ const group = timeoutMs !== undefined && process.platform !== "win32";
196
+ const child = spawn(command === "git" ? gitExecutable() : command, args, {
197
+ cwd,
198
+ env,
199
+ stdio: ["ignore", output.stdout, output.stderr],
200
+ ...(group ? { detached: true } : {}),
201
+ });
152
202
  let stdout = "";
153
203
  let stderr = "";
204
+ let settled = false;
205
+ const stop = (signal: NodeJS.Signals) => {
206
+ try {
207
+ if (group && child.pid) process.kill(-child.pid, signal);
208
+ else if (timeoutMs !== undefined && process.platform === "win32" && child.pid) stopWindowsTree(child.pid, () => child.kill(signal));
209
+ else child.kill(signal);
210
+ } catch {
211
+ // Intentional ignore: it exited between the check and the signal.
212
+ }
213
+ };
214
+ // An install with a limit is one nobody waits on: quitting stops it.
215
+ const forget = timeoutMs === undefined ? null : trackInstallCommand(() => stop("SIGKILL"));
216
+ child.once("exit", () => forget?.());
217
+ const timer = timeoutMs === undefined ? null : setTimeout(() => {
218
+ if (settled) return;
219
+ settled = true;
220
+ stop("SIGTERM");
221
+ // A command that ignores the request is not left running.
222
+ setTimeout(() => stop("SIGKILL"), KILL_GRACE_MS).unref?.();
223
+ child.stdout?.destroy();
224
+ child.stderr?.destroy();
225
+ resolveRun({ code: null, stdout, stderr, timedOut: true });
226
+ }, timeoutMs);
154
227
  child.stdout?.setEncoding("utf-8").on("data", (chunk: string) => { stdout += chunk; });
155
228
  child.stderr?.setEncoding("utf-8").on("data", (chunk: string) => { stderr += chunk; });
156
- child.once("error", reject);
157
- child.once("close", (code) => resolveRun({ code, stdout, stderr }));
229
+ child.once("error", (error) => {
230
+ if (timer) clearTimeout(timer);
231
+ forget?.();
232
+ if (settled) return;
233
+ settled = true;
234
+ reject(error);
235
+ });
236
+ child.once("close", (code) => {
237
+ if (timer) clearTimeout(timer);
238
+ if (settled) return;
239
+ settled = true;
240
+ resolveRun({ code, stdout, stderr });
241
+ });
158
242
  });
159
243
  }
160
244
 
@@ -181,18 +265,19 @@ function gitMissingMessage(platform: string = process.platform): string {
181
265
  * the detached-HEAD advice a pinned checkout prints are chatter, and a failure
182
266
  * says what went wrong in its error, from git's last line.
183
267
  */
184
- async function git(args: string[], cwd: string, quiet: boolean, failure: string): Promise<string> {
268
+ async function git(args: string[], cwd: string, quiet: boolean, failure: string, timeoutMs?: number): Promise<string> {
185
269
  // Quiet means the app owns the screen, or there is no terminal at all: a
186
270
  // repository that wants credentials fails instead of prompting on it.
187
271
  const env = quiet ? { ...process.env, GIT_TERMINAL_PROMPT: "0" } : undefined;
188
272
  let result: RunResult;
189
273
  try {
190
- result = await run("git", ["-c", "advice.detachedHead=false", ...args], cwd, { stdout: "pipe", stderr: "pipe" }, env);
274
+ result = await run("git", ["-c", "advice.detachedHead=false", ...args], cwd, { stdout: "pipe", stderr: "pipe" }, env, timeoutMs);
191
275
  } catch (error) {
192
276
  // git could not start: almost always because it is not installed.
193
277
  const missing = (error as NodeJS.ErrnoException | null)?.code === "ENOENT";
194
278
  throw new GitError(failure, missing ? gitMissingMessage() : String(error));
195
279
  }
280
+ if (result.timedOut) throw new GitError(failure, `no answer within ${seconds(timeoutMs!)}`, true);
196
281
  if (result.code !== 0) throw new GitError(failure, result.stderr);
197
282
  return result.stdout.trim();
198
283
  }
@@ -212,13 +297,13 @@ function pinMatches(commit: string | null, expected: string | undefined): boolea
212
297
  * is what the ref names and the pinned commit (when known) only verifies it;
213
298
  * with a commit alone, that commit is fetched directly.
214
299
  */
215
- async function fetchPin(targetDir: string, pin: PluginPin, quiet: boolean): Promise<string> {
300
+ async function fetchPin(targetDir: string, pin: PluginPin, quiet: boolean, timeoutMs?: number): Promise<string> {
216
301
  const wanted = pin.ref ?? pin.commit;
217
302
  if (!wanted) throw new Error("The registry pin names no ref or commit.");
218
303
  if (pin.ref) validatePinRef(pin.ref);
219
304
  if (pin.commit && !COMMIT_PATTERN.test(pin.commit)) throw new Error(`Invalid commit in registry pin: ${pin.commit}`);
220
- await git(["fetch", "--depth", "1", "origin", "--", wanted], targetDir, quiet, `Could not fetch ${wanted}`);
221
- const commit = await git(["rev-parse", "FETCH_HEAD^{commit}"], targetDir, quiet, `Could not read ${wanted}`);
305
+ await git(["fetch", "--depth", "1", "origin", "--", wanted], targetDir, quiet, `Could not fetch ${wanted}`, timeoutMs);
306
+ const commit = await git(["rev-parse", "FETCH_HEAD^{commit}"], targetDir, quiet, `Could not read ${wanted}`, timeoutMs);
222
307
  if (!pinMatches(commit, pin.commit)) {
223
308
  throw new Error(`${pin.ref ?? "The pinned ref"} now points at ${commit.slice(0, 7)}, the registry reviewed ${pin.commit!.slice(0, 7)}.`);
224
309
  }
@@ -226,8 +311,8 @@ async function fetchPin(targetDir: string, pin: PluginPin, quiet: boolean): Prom
226
311
  }
227
312
 
228
313
  /** Leaves HEAD detached at one exact commit, which is the state `update` expects to find. */
229
- async function checkoutCommit(targetDir: string, commit: string, quiet: boolean): Promise<void> {
230
- await git(["checkout", "--detach", "--force", commit], targetDir, quiet, `Could not check out ${commit.slice(0, 7)}`);
314
+ async function checkoutCommit(targetDir: string, commit: string, quiet: boolean, timeoutMs?: number): Promise<void> {
315
+ await git(["checkout", "--detach", "--force", commit], targetDir, quiet, `Could not check out ${commit.slice(0, 7)}`, timeoutMs);
231
316
  }
232
317
 
233
318
 
@@ -282,14 +367,19 @@ export async function describeOlderCommit(dir: string, installed: string, candid
282
367
  }
283
368
 
284
369
  /** Brings `targetDir` to the pinned commit. */
285
- async function checkoutPin(targetDir: string, pin: PluginPin, quiet: boolean): Promise<void> {
370
+ async function checkoutPin(targetDir: string, pin: PluginPin, quiet: boolean, timeoutMs?: number): Promise<void> {
286
371
  if (!pin.ref && !pin.commit) return;
287
- await checkoutCommit(targetDir, await fetchPin(targetDir, pin, quiet), quiet);
372
+ await checkoutCommit(targetDir, await fetchPin(targetDir, pin, quiet, timeoutMs), quiet, timeoutMs);
288
373
  }
289
374
 
290
- async function installDependencies(targetDir: string, quiet: boolean): Promise<void> {
375
+ /**
376
+ * Runs `bun install` in `targetDir` and links the host. `recordAs` is the
377
+ * folder the plugin is installed under, when `targetDir` is where it is
378
+ * being put together. Null when there was nothing to install or no bun.
379
+ */
380
+ async function installDependencies(targetDir: string, quiet: boolean, timeoutMs?: number, recordAs: string = targetDir): Promise<RunResult | null> {
291
381
  const pkgPath = join(targetDir, "package.json");
292
- if (!existsSync(pkgPath)) return;
382
+ if (!existsSync(pkgPath)) return null;
293
383
  if (!quiet) console.log(cliStyles.muted("Installing plugin dependencies..."));
294
384
  // --production: plugin repos depend on `gloomberb` as a devDependency so
295
385
  // their own CI can typecheck against the real API. At runtime the host is
@@ -298,7 +388,7 @@ async function installDependencies(targetDir: string, quiet: boolean): Promise<v
298
388
  const output = quiet ? "pipe" : "inherit";
299
389
  const bun = bunCommand();
300
390
  const result = bun
301
- ? await recordDependencyInstall(targetDir, () => run(bun.command, ["install", "--production"], targetDir, { stdout: output, stderr: output }, bun.env)
391
+ ? await recordDependencyInstall(recordAs, () => run(bun.command, ["install", "--production"], targetDir, { stdout: output, stderr: output }, bun.env, timeoutMs)
302
392
  .catch(logFailure("plugin-installer", "Plugin dependency installation failed", null)))
303
393
  : null;
304
394
  if (result?.code !== 0 && !quiet) console.error(cliStyles.warning("Warning: failed to install plugin dependencies."));
@@ -309,6 +399,7 @@ async function installDependencies(targetDir: string, quiet: boolean): Promise<v
309
399
  console.error(cliStyles.warning(`Warning: could not link the Gloom runtime (${link.error}).`));
310
400
  console.error(cliStyles.muted("The plugin's \"gloomberb/*\" imports will not resolve."));
311
401
  }
402
+ return result;
312
403
  }
313
404
 
314
405
  async function readPluginExport(targetDir: string): Promise<Pick<GloomPlugin, "id" | "name" | "version"> | null> {
@@ -351,37 +442,67 @@ export async function installPlugin(ref: string, options: PluginInstallOptions =
351
442
  ensurePluginsDir();
352
443
  const targetDir = join(PLUGINS_DIR, name);
353
444
 
354
- if (existsSync(targetDir)) {
355
- fail(`Plugin "${name}" already exists.`, `Use "gloom update ${name}" to refresh it.`);
356
- }
445
+ const alreadyInstalled = () => fail(`Plugin "${name}" already exists.`, `Use "gloom update ${name}" to refresh it.`);
446
+ if (existsSync(targetDir)) alreadyInstalled();
357
447
 
358
448
  say(cliStyles.accent(`Installing ${name}`));
359
449
  say(cliStyles.muted(url));
360
450
 
451
+ // Put together beside the plugins, under a dot name the loader and the
452
+ // seeder pass over, and moved into place only once complete: an install
453
+ // stopped half way (the app quit, a limit hit) never leaves a folder that
454
+ // passes for the plugin.
455
+ removeAbandonedInstalls();
456
+ const stagingDir = join(PLUGINS_DIR, `${STAGING_PREFIX}${name}-${process.pid}-${++stagingCount}`);
457
+ const timeoutMs = options.timeouts?.gitMs;
361
458
  const pin = options.pin ?? {};
362
459
  try {
363
460
  const cloneArgs = ["clone", "--depth", "1"];
364
461
  if (pin.ref) cloneArgs.push(`--branch=${validatePinRef(pin.ref)}`);
365
- cloneArgs.push("--", url, targetDir);
366
- await git(cloneArgs, PLUGINS_DIR, quiet, `Failed to clone ${url}`);
462
+ cloneArgs.push("--", url, stagingDir);
463
+ await git(cloneArgs, PLUGINS_DIR, quiet, `Failed to clone ${url}`, timeoutMs);
367
464
  if (pin.ref) {
368
- const commit = readPluginCommit(targetDir);
465
+ const commit = readPluginCommit(stagingDir);
369
466
  if (!pinMatches(commit, pin.commit)) {
370
467
  throw new Error(`${pin.ref} now points at ${commit?.slice(0, 7) ?? "?"}, the registry reviewed ${pin.commit!.slice(0, 7)}.`);
371
468
  }
372
469
  } else if (pin.commit) {
373
- await checkoutPin(targetDir, pin, quiet);
470
+ await checkoutPin(stagingDir, pin, quiet, timeoutMs);
374
471
  }
375
472
  // A fork under another name says what it is in its gloom.json.
376
- refuseAbsorbed(findAbsorbedCheckout(targetDir));
473
+ refuseAbsorbed(findAbsorbedCheckout(stagingDir));
474
+
475
+ if (pin.ref || pin.commit) say(cliStyles.muted(`Pinned to ${pin.ref ?? pin.commit}`));
476
+
477
+ const dependenciesMs = options.timeouts?.dependenciesMs;
478
+ const dependencies = await installDependencies(stagingDir, quiet, dependenciesMs, targetDir);
479
+ if (dependencies?.timedOut) {
480
+ throw Object.assign(new Error(`Installing ${name}'s dependencies took longer than ${seconds(dependenciesMs!)}.`), { timedOut: true });
481
+ }
482
+ if (options.requireDependencies) {
483
+ const missing = missingPluginDependencies(stagingDir);
484
+ if (missing.length > 0) throw new Error(`${name}'s dependencies did not install: ${missing.join(", ")}.`);
485
+ }
377
486
  } catch (error) {
378
- rmSync(targetDir, { recursive: true, force: true });
379
- fail(error instanceof Error ? error.message : String(error));
487
+ removeStaging(stagingDir);
488
+ const timedOut = (error as { timedOut?: unknown } | null)?.timedOut === true;
489
+ fail(error instanceof Error ? error.message : String(error), undefined, timedOut ? INSTALL_TIMED_OUT : undefined);
380
490
  }
381
491
 
382
- if (pin.ref || pin.commit) say(cliStyles.muted(`Pinned to ${pin.ref ?? pin.commit}`));
383
-
384
- await installDependencies(targetDir, quiet);
492
+ let moved = false;
493
+ try {
494
+ moved = await moveIntoPlace(stagingDir, targetDir);
495
+ } catch (error) {
496
+ removeStaging(stagingDir);
497
+ fail(error instanceof Error ? error.message : String(error));
498
+ }
499
+ if (!moved) {
500
+ removeStaging(stagingDir);
501
+ // Another install of it finished first: the app beside this one, or a second click.
502
+ alreadyInstalled();
503
+ }
504
+ // The links were made from where it was put together.
505
+ linkHostPackages(targetDir);
385
506
 
386
507
  const missing = missingPeerPlugins(targetDir);
387
508
  if (missing.length > 0) {
@@ -391,6 +512,74 @@ export async function installPlugin(ref: string, options: PluginInstallOptions =
391
512
  return validateInstall(targetDir, name, quiet);
392
513
  }
393
514
 
515
+ /** Where an install is put together: `.installing-<name>-<pid>-<n>` in the plugins folder. */
516
+ const STAGING_PREFIX = ".installing-";
517
+ const STAGING_NAME = /^\.installing-.+-(\d+)-\d+$/;
518
+ let stagingCount = 0;
519
+
520
+ function processRunning(pid: number): boolean {
521
+ try {
522
+ process.kill(pid, 0);
523
+ return true;
524
+ } catch (error) {
525
+ // EPERM: it runs, as another user.
526
+ return (error as NodeJS.ErrnoException | null)?.code === "EPERM";
527
+ }
528
+ }
529
+
530
+ /**
531
+ * Removes an install's staging folder. A folder that will not go (a git
532
+ * helper that outlived its stop still holds it on Windows, a read-only file)
533
+ * never replaces the reason the install failed: it carries a name the loader
534
+ * passes over, and a later install clears it once its process has ended.
535
+ */
536
+ function removeStaging(stagingDir: string): void {
537
+ try {
538
+ rmSync(stagingDir, { recursive: true, force: true });
539
+ } catch (error) {
540
+ logFailure("plugin-installer", "Could not remove an unfinished plugin install")(error);
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Drops what installs left behind when their process ended mid-way. Best
546
+ * effort: one that cannot be removed stays, and never stops this install.
547
+ */
548
+ function removeAbandonedInstalls(): void {
549
+ let entries: string[];
550
+ try {
551
+ entries = readdirSync(PLUGINS_DIR);
552
+ } catch (error) {
553
+ logFailure("plugin-installer", "Could not list the plugins folder for unfinished installs")(error);
554
+ return;
555
+ }
556
+ for (const entry of entries) {
557
+ const pid = Number(STAGING_NAME.exec(entry)?.[1]);
558
+ if (!pid || pid === process.pid || processRunning(pid)) continue;
559
+ removeStaging(join(PLUGINS_DIR, entry));
560
+ }
561
+ }
562
+
563
+ /**
564
+ * Renames the finished install into place. False when the folder is taken.
565
+ * Windows refuses a rename while a scanner still holds a file just written,
566
+ * so a refusal there is tried again for a moment.
567
+ */
568
+ async function moveIntoPlace(stagingDir: string, targetDir: string): Promise<boolean> {
569
+ for (let attempt = 0; ; attempt += 1) {
570
+ if (existsSync(targetDir)) return false;
571
+ try {
572
+ renameSync(stagingDir, targetDir);
573
+ return true;
574
+ } catch (error) {
575
+ const code = (error as NodeJS.ErrnoException | null)?.code;
576
+ if (existsSync(targetDir)) return false;
577
+ if (attempt >= 10 || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES")) throw error;
578
+ await Bun.sleep(200);
579
+ }
580
+ }
581
+ }
582
+
394
583
  /** Reads the export of a checkout that was just installed, and says what it is. */
395
584
  async function validateInstall(targetDir: string, name: string, quiet: boolean): Promise<PluginDirectoryInfo> {
396
585
  const say = (message: string) => {
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The commands of installs nobody waits on (a launch's restore of plugins
3
+ * that moved out of Gloom), which quitting the app stops rather than leave a
4
+ * download running after it. Kept apart from the installer, so the app's way
5
+ * out reaches them without loading it. A process exit stops them as well,
6
+ * but the app cannot count on that event, so it calls this on its way out.
7
+ */
8
+ /** The code of an install that failed because a step ran past its time limit: the network did not answer. */
9
+ export const INSTALL_TIMED_OUT = "install_timed_out";
10
+
11
+ const running = new Set<() => void>();
12
+ let stopsOnExit = false;
13
+ /** Set on the way out: a command started after that, as the next install begins, stops at once. */
14
+ let stopped = false;
15
+
16
+ export function trackInstallCommand(stop: () => void): () => void {
17
+ if (stopped) {
18
+ stop();
19
+ return () => {};
20
+ }
21
+ if (!stopsOnExit) {
22
+ stopsOnExit = true;
23
+ process.once("exit", stopInstallCommands);
24
+ }
25
+ running.add(stop);
26
+ return () => { running.delete(stop); };
27
+ }
28
+
29
+ /** Stops every one still running, and any started from now on. */
30
+ export function stopInstallCommands(): void {
31
+ stopped = true;
32
+ for (const stop of [...running]) stop();
33
+ running.clear();
34
+ }
@@ -0,0 +1,72 @@
1
+ import type { AppConfig, PluginSeedFailure } from "../types/config";
2
+ import { logFailure } from "../utils/log-failure";
3
+
4
+ /**
5
+ * The plugins this launch is installing because they moved out of Gloom into
6
+ * their own repositories (extracted-plugins.ts), as the app sees them.
7
+ *
8
+ * The installs run after the first frame, in the process that can run git and
9
+ * bun: the terminal's own, or the desktop's Bun process, which passes each
10
+ * change to its main window. The app brings every plugin into the session as
11
+ * it lands, then records the outcome in its config and says what could not be
12
+ * installed. Until then the panes they add stay in the layout, hidden like
13
+ * any pane whose plugin is not there, and appear in place once it is.
14
+ */
15
+
16
+ export interface PluginSeedNotice {
17
+ body: string;
18
+ type: "error" | "info";
19
+ }
20
+
21
+ export type PluginSeedRecord = Pick<AppConfig, "seededPlugins" | "pluginSeedFailure">;
22
+
23
+ export interface PluginSeedEntry {
24
+ id: string;
25
+ name: string;
26
+ state: "installing" | "installed" | "failed";
27
+ /** Its folder once installed, and the sibling plugins it brought along. */
28
+ directory?: string;
29
+ peers?: string[];
30
+ }
31
+
32
+ export interface PluginSeedProgress {
33
+ /** Grows with every change, so a snapshot that arrives late is ignored. */
34
+ seq: number;
35
+ plugins: PluginSeedEntry[];
36
+ /** Set once every install is over: what the config records, and what to tell the user. */
37
+ outcome?: { record: PluginSeedRecord; notice: PluginSeedNotice | null };
38
+ }
39
+
40
+ /** Whether two recorded seed failures are the same: the same plugins, for the same reason. */
41
+ export function samePluginSeedFailure(a: PluginSeedFailure | undefined, b: PluginSeedFailure | undefined): boolean {
42
+ return a?.gitMissing === b?.gitMissing && (a?.plugins ?? []).join() === (b?.plugins ?? []).join();
43
+ }
44
+
45
+ let progress: PluginSeedProgress | null = null;
46
+ const listeners = new Set<() => void>();
47
+
48
+ /**
49
+ * Adopts a snapshot unless an equal or newer one is already here. A listener
50
+ * that throws (the desktop's send to a window that is closing) is logged and
51
+ * the others still hear: the install it reports has happened either way.
52
+ */
53
+ export function publishPluginSeedProgress(next: PluginSeedProgress): void {
54
+ if (progress && next.seq <= progress.seq) return;
55
+ progress = next;
56
+ for (const listener of [...listeners]) {
57
+ try {
58
+ listener();
59
+ } catch (error) {
60
+ logFailure("plugin-seed", "A plugin restore progress listener failed")(error);
61
+ }
62
+ }
63
+ }
64
+
65
+ export function getPluginSeedProgress(): PluginSeedProgress | null {
66
+ return progress;
67
+ }
68
+
69
+ export function subscribePluginSeed(listener: () => void): () => void {
70
+ listeners.add(listener);
71
+ return () => { listeners.delete(listener); };
72
+ }