gloomberb 0.9.2 → 0.9.3

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 (111) hide show
  1. package/README.md +23 -2
  2. package/bin/gloomberb +1 -1
  3. package/package.json +1 -1
  4. package/src/app.tsx +10 -7
  5. package/src/capabilities/registry.ts +1 -0
  6. package/src/capabilities/types.ts +23 -0
  7. package/src/cli/commands/api.ts +119 -0
  8. package/src/cli/commands/automation.ts +173 -0
  9. package/src/cli/commands/command-utils.ts +53 -0
  10. package/src/cli/commands/market.ts +527 -0
  11. package/src/cli/commands/overview.ts +222 -0
  12. package/src/cli/commands/search.ts +39 -0
  13. package/src/cli/commands/system.ts +553 -0
  14. package/src/cli/commands/ticker.ts +104 -12
  15. package/src/cli/context.ts +35 -2
  16. package/src/cli/entry.ts +51 -0
  17. package/src/cli/errors.ts +56 -5
  18. package/src/cli/index.ts +73 -11
  19. package/src/cli/options.test.ts +38 -0
  20. package/src/cli/options.ts +95 -0
  21. package/src/cli/pane-functions/index.ts +10 -1
  22. package/src/cli/registry.test.ts +40 -0
  23. package/src/cli/registry.ts +46 -5
  24. package/src/cli/result.test.ts +82 -0
  25. package/src/cli/result.ts +149 -0
  26. package/src/cli/types.ts +11 -0
  27. package/src/cli.test.ts +11 -11
  28. package/src/components/chart/comparison-stock-chart/interactions.ts +7 -1
  29. package/src/components/chart/comparison-stock-chart/legend.tsx +4 -0
  30. package/src/components/chart/comparison-stock-chart/render-data.ts +37 -8
  31. package/src/components/chart/comparison-stock-chart/selection-runtime.ts +19 -2
  32. package/src/components/chart/comparison-stock-chart/sources.ts +8 -4
  33. package/src/components/chart/comparison-stock-chart/toolbar.tsx +13 -3
  34. package/src/components/chart/comparison-stock-chart/view.tsx +12 -2
  35. package/src/components/chart/core/pane-settings.test.ts +27 -0
  36. package/src/components/chart/core/pane-settings.ts +60 -1
  37. package/src/components/chart/core/pointer.ts +2 -0
  38. package/src/components/chart/stock-chart/resolved/runtime.ts +1 -1
  39. package/src/components/chart/stock-chart/settings.ts +7 -3
  40. package/src/components/chart/stock-chart/viewport/runtime.ts +5 -5
  41. package/src/components/command-bar/pane-templates/workflow-route.ts +10 -0
  42. package/src/components/command-bar/surface/pane.test.tsx +76 -0
  43. package/src/components/data-table/view.tsx +13 -2
  44. package/src/components/feed-data-table/stack-view.tsx +9 -1
  45. package/src/components/index.ts +1 -1
  46. package/src/components/input-search-bar.test.tsx +103 -0
  47. package/src/components/input-search-bar.tsx +16 -0
  48. package/src/components/layout/shell/active-drag.ts +5 -1
  49. package/src/components/layout/shell/drag/runtime.ts +21 -3
  50. package/src/components/layout/shell/fullscreen.ts +10 -0
  51. package/src/components/layout/shell/index.test.tsx +395 -2
  52. package/src/components/layout/shell/index.tsx +128 -2
  53. package/src/components/layout/shell/native/pointer-runtime.ts +10 -4
  54. package/src/components/layout/shell/pane/layers.tsx +26 -14
  55. package/src/components/layout/shell/pane/management-shortcuts.ts +19 -0
  56. package/src/components/layout/shell/shortcuts.ts +4 -0
  57. package/src/components/layout/shell/terminal-pointer-runtime.ts +29 -19
  58. package/src/components/layout/shell/window-mode/index.ts +11 -3
  59. package/src/components/layout/shell/window-mode/overlays.tsx +8 -1
  60. package/src/components/layout/status-bar.test.tsx +105 -0
  61. package/src/components/layout/status-bar.tsx +32 -6
  62. package/src/components/layout/transient-layout.tsx +57 -0
  63. package/src/components/layout/window-edit/mode.test.ts +76 -5
  64. package/src/components/layout/window-edit/mode.ts +47 -2
  65. package/src/components/layout/window-edit/presentation.ts +2 -1
  66. package/src/components/price-performance.tsx +9 -1
  67. package/src/core/app-services.ts +7 -4
  68. package/src/data/config/store/index.ts +1 -2
  69. package/src/plugins/builtin/cloud-tweets/pane.tsx +2 -0
  70. package/src/plugins/builtin/cloud-tweets/search-bar.tsx +3 -0
  71. package/src/plugins/builtin/cloud-tweets/table.tsx +14 -2
  72. package/src/plugins/builtin/comparison-chart/index.test.tsx +130 -6
  73. package/src/plugins/builtin/news/wire/read-state.ts +9 -32
  74. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +23 -0
  75. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +19 -2
  76. package/src/plugins/builtin/portfolio-list/pane/index.tsx +1 -1
  77. package/src/plugins/builtin/portfolio-list/quick-add/index.tsx +2 -7
  78. package/src/plugins/builtin/shared/read-state.ts +43 -0
  79. package/src/plugins/builtin/substack/article-detail.test.tsx +10 -0
  80. package/src/plugins/builtin/substack/article-detail.tsx +39 -15
  81. package/src/plugins/builtin/substack/article-stack.tsx +6 -2
  82. package/src/plugins/builtin/substack/feed-tabs.tsx +12 -9
  83. package/src/plugins/builtin/substack/pane.tsx +8 -3
  84. package/src/plugins/builtin/substack/read-state.ts +55 -0
  85. package/src/plugins/builtin/thirteenf/pane.test.tsx +26 -0
  86. package/src/plugins/builtin/thirteenf/pane.tsx +12 -1
  87. package/src/plugins/pane-manager/docking.ts +9 -2
  88. package/src/plugins/pane-manager/queries.ts +8 -2
  89. package/src/plugins/prediction-markets/controller/index.ts +2 -0
  90. package/src/plugins/prediction-markets/controller/keyboard.ts +34 -5
  91. package/src/plugins/prediction-markets/pane.test.tsx +32 -0
  92. package/src/plugins/prediction-markets/pane.tsx +21 -1
  93. package/src/plugins/prediction-markets/test-helpers.tsx +1 -0
  94. package/src/renderers/electrobun/bun/application-menu/click.test.ts +9 -0
  95. package/src/renderers/electrobun/bun/application-menu/click.ts +1 -0
  96. package/src/renderers/electrobun/bun/application-menu/index.test.ts +9 -0
  97. package/src/renderers/electrobun/bun/application-menu/index.ts +3 -2
  98. package/src/renderers/electrobun/bun/index.ts +13 -0
  99. package/src/renderers/electrobun/bun/window/focus.test.ts +35 -0
  100. package/src/renderers/electrobun/bun/window/focus.ts +5 -0
  101. package/src/renderers/electrobun/view/app-services.ts +6 -4
  102. package/src/renderers/electrobun/view/host/ascii-text.ts +50 -0
  103. package/src/renderers/electrobun/view/host/text.test.ts +22 -0
  104. package/src/renderers/electrobun/view/host/text.tsx +24 -20
  105. package/src/renderers/electrobun/view/ui-host.tsx +1 -1
  106. package/src/renderers/opentui/start.tsx +13 -5
  107. package/src/state/app/input-capture.ts +12 -0
  108. package/src/types/plugin.ts +28 -0
  109. package/src/utils/cli-output.ts +6 -0
  110. package/src/utils/search-focus-navigation.ts +24 -0
  111. package/src/version.ts +1 -1
@@ -1,9 +1,17 @@
1
1
  import type { AppConfig } from "../types/config";
2
- import type { CliCommandContext, CliCommandDef, CliDispatchResult, GloomPlugin } from "../types/plugin";
2
+ import type {
3
+ CliCommandContext,
4
+ CliCommandDef,
5
+ CliDispatchResult,
6
+ GloomPlugin,
7
+ PluginCliCommandDescriptor,
8
+ } from "../types/plugin";
3
9
  import type { LoadedExternalPlugin } from "../plugins/loader";
4
10
  import { getPluginCatalog } from "../plugins/catalog";
5
- import { initConfigData, initMarketData } from "./context";
11
+ import { initCliServices, initConfigData, initMarketData } from "./context";
6
12
  import { closeAndFail, fail } from "./errors";
13
+ import { DEFAULT_CLI_OPTIONS, type CliGlobalOptions } from "./options";
14
+ import { printCliResult } from "./result";
7
15
  import {
8
16
  cliStyles,
9
17
  colorBySign,
@@ -26,6 +34,8 @@ export interface CliCommandRegistry {
26
34
  lookup: ReadonlyMap<string, RegisteredCliCommand>;
27
35
  config: AppConfig | null;
28
36
  plugins: GloomPlugin[];
37
+ externalPlugins: LoadedExternalPlugin[];
38
+ descriptors: Array<{ pluginId: string; descriptor: PluginCliCommandDescriptor }>;
29
39
  }
30
40
 
31
41
  interface BuildCliCommandRegistryOptions {
@@ -61,6 +71,19 @@ function getCommandUsageLabel(command: CliCommandDef): string {
61
71
  return command.help?.usage?.[0] ?? command.name;
62
72
  }
63
73
 
74
+ function descriptorToCommand(descriptor: PluginCliCommandDescriptor): CliCommandDef | null {
75
+ if (!descriptor.execute) return null;
76
+ return {
77
+ name: descriptor.name,
78
+ aliases: descriptor.aliases,
79
+ description: descriptor.summary,
80
+ help: descriptor.examples?.length
81
+ ? { usage: descriptor.examples }
82
+ : undefined,
83
+ execute: descriptor.execute,
84
+ };
85
+ }
86
+
64
87
  function renderHelpSections(registry: CliCommandRegistry): string[] {
65
88
  const lines: string[] = [];
66
89
 
@@ -149,6 +172,7 @@ export function buildCliCommandRegistry({
149
172
  }
150
173
 
151
174
  const loadablePlugins: GloomPlugin[] = [];
175
+ const descriptors: Array<{ pluginId: string; descriptor: PluginCliCommandDescriptor }> = [];
152
176
  for (const entry of catalog) {
153
177
  if (entry.error) {
154
178
  registryLog.warn(`Skipping external plugin "${entry.plugin.id}" for CLI registration.`, {
@@ -161,6 +185,11 @@ export function buildCliCommandRegistry({
161
185
  for (const command of entry.plugin.cliCommands ?? []) {
162
186
  registerCommand(command, entry.plugin.id, "plugin");
163
187
  }
188
+ for (const descriptor of entry.plugin.cli?.commands ?? []) {
189
+ descriptors.push({ pluginId: entry.plugin.id, descriptor });
190
+ const command = descriptorToCommand(descriptor);
191
+ if (command) registerCommand(command, entry.plugin.id, "plugin");
192
+ }
164
193
  }
165
194
 
166
195
  const commands = allCommands.filter((entry) => (
@@ -180,14 +209,25 @@ export function buildCliCommandRegistry({
180
209
  lookup,
181
210
  config,
182
211
  plugins: loadablePlugins,
212
+ externalPlugins,
213
+ descriptors,
183
214
  };
184
215
  }
185
216
 
186
- export function createCliCommandContext(ownerId: string, plugins: GloomPlugin[]): CliCommandContext {
217
+ export function createCliCommandContext(
218
+ ownerId: string,
219
+ registryOrPlugins: Pick<CliCommandRegistry, "plugins" | "externalPlugins"> | GloomPlugin[],
220
+ cliOptions: CliGlobalOptions = DEFAULT_CLI_OPTIONS,
221
+ ): CliCommandContext {
222
+ const registry = Array.isArray(registryOrPlugins)
223
+ ? { plugins: registryOrPlugins, externalPlugins: [] }
224
+ : registryOrPlugins;
187
225
  return {
188
226
  initConfigData,
189
- initMarketData: () => initMarketData({ plugins }),
190
- plugins,
227
+ initMarketData: () => initMarketData({ plugins: registry.plugins }),
228
+ initServices: () => initCliServices({ externalPlugins: registry.externalPlugins }),
229
+ cliOptions,
230
+ plugins: registry.plugins,
191
231
  fail,
192
232
  closeAndFail,
193
233
  output: {
@@ -197,6 +237,7 @@ export function createCliCommandContext(ownerId: string, plugins: GloomPlugin[])
197
237
  renderStat,
198
238
  renderTable,
199
239
  },
240
+ printResult: (result, options) => printCliResult(result, cliOptions, options),
200
241
  log: debugLog.createLogger(ownerId === "core" ? "cli" : ownerId),
201
242
  };
202
243
  }
@@ -0,0 +1,82 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { serializeCliError, serializeCliResult } from "./result";
3
+ import type { CliGlobalOptions } from "./options";
4
+
5
+ const baseOptions: CliGlobalOptions = {
6
+ format: "text",
7
+ quiet: false,
8
+ color: null,
9
+ refresh: false,
10
+ dryRun: false,
11
+ yes: false,
12
+ };
13
+
14
+ describe("serializeCliResult", () => {
15
+ test("renders limited JSON result envelopes", () => {
16
+ const output = serializeCliResult(
17
+ { data: [{ symbol: "AAPL" }, { symbol: "MSFT" }] },
18
+ { ...baseOptions, format: "json", limit: 1 },
19
+ );
20
+ expect(JSON.parse(output)).toEqual({
21
+ ok: true,
22
+ data: [{ symbol: "AAPL" }],
23
+ });
24
+ });
25
+
26
+ test("includes display column metadata in JSON envelopes", () => {
27
+ const output = serializeCliResult(
28
+ { data: [{ quote: { symbol: "AAPL", price: 123 } }] },
29
+ { ...baseOptions, format: "json" },
30
+ {
31
+ rows: (data) => data.map((row) => row.quote),
32
+ columns: [
33
+ { key: "symbol", header: "Symbol" },
34
+ { key: "price", header: "Last", align: "right" },
35
+ ],
36
+ },
37
+ );
38
+ expect(JSON.parse(output)).toEqual({
39
+ ok: true,
40
+ data: [{ quote: { symbol: "AAPL", price: 123 } }],
41
+ columns: [
42
+ { key: "symbol", header: "Symbol" },
43
+ { key: "price", header: "Last", align: "right" },
44
+ ],
45
+ });
46
+ });
47
+
48
+ test("renders CSV with provided column order", () => {
49
+ const output = serializeCliResult(
50
+ { data: [{ symbol: "AAPL", name: "Apple, Inc." }] },
51
+ { ...baseOptions, format: "csv" },
52
+ {
53
+ columns: [
54
+ { key: "symbol", header: "Symbol" },
55
+ { key: "name", header: "Name" },
56
+ ],
57
+ },
58
+ );
59
+ expect(output).toBe('Symbol,Name\nAAPL,"Apple, Inc."');
60
+ });
61
+
62
+ test("renders NDJSON rows", () => {
63
+ const output = serializeCliResult(
64
+ { data: [{ symbol: "AAPL" }, { symbol: "MSFT" }] },
65
+ { ...baseOptions, format: "ndjson" },
66
+ );
67
+ expect(output).toBe('{"symbol":"AAPL"}\n{"symbol":"MSFT"}');
68
+ });
69
+ });
70
+
71
+ describe("serializeCliError", () => {
72
+ test("renders stable structured errors for JSON", () => {
73
+ const output = serializeCliError(
74
+ { code: "auth_required", message: "Sign in first.", retryable: true },
75
+ { ...baseOptions, format: "json" },
76
+ );
77
+ expect(JSON.parse(output)).toEqual({
78
+ ok: false,
79
+ error: { code: "auth_required", message: "Sign in first.", retryable: true },
80
+ });
81
+ });
82
+ });
@@ -0,0 +1,149 @@
1
+ import type { CliGlobalOptions } from "./options";
2
+ import { renderTable, type CliTableColumn } from "../utils/cli-output";
3
+
4
+ export interface CliResult<T = unknown> {
5
+ data: T;
6
+ metadata?: Record<string, unknown>;
7
+ warnings?: string[];
8
+ }
9
+
10
+ export interface CliErrorObject {
11
+ code: string;
12
+ message: string;
13
+ details?: unknown;
14
+ retryable?: boolean;
15
+ }
16
+
17
+ export interface CliResultColumn<Row = Record<string, unknown>> extends CliTableColumn {
18
+ key: string;
19
+ value?: (row: Row) => unknown;
20
+ }
21
+
22
+ export interface CliResultRenderOptions<T = unknown, Row = Record<string, unknown>> {
23
+ text?: (data: T) => string;
24
+ columns?: CliResultColumn<Row>[];
25
+ rows?: (data: T) => Row[];
26
+ }
27
+
28
+ interface CliResultJsonEnvelope<T> extends CliResult<T> {
29
+ ok: true;
30
+ columns?: Array<Pick<CliResultColumn, "key" | "header" | "align" | "width">>;
31
+ }
32
+
33
+ function applyLimit<T>(data: T, limit?: number): T {
34
+ if (!Array.isArray(data) || limit == null) return data;
35
+ return data.slice(0, limit) as T;
36
+ }
37
+
38
+ function asRows<T, Row>(data: T, limit?: number, rows?: (data: T) => Row[]): Row[] {
39
+ const resolvedRows = rows ? rows(data) : (Array.isArray(data) ? data : [data]) as Row[];
40
+ return limit == null ? resolvedRows : resolvedRows.slice(0, limit);
41
+ }
42
+
43
+ function normalizeCell(value: unknown): string {
44
+ if (value == null) return "";
45
+ if (value instanceof Date) return value.toISOString();
46
+ if (typeof value === "object") return JSON.stringify(value);
47
+ return String(value);
48
+ }
49
+
50
+ function inferColumns(rows: Record<string, unknown>[]): CliResultColumn<Record<string, unknown>>[] {
51
+ const keys = new Set<string>();
52
+ for (const row of rows) {
53
+ if (row && typeof row === "object" && !Array.isArray(row)) {
54
+ for (const key of Object.keys(row)) keys.add(key);
55
+ }
56
+ }
57
+ return [...keys].map((key) => ({ key, header: key }));
58
+ }
59
+
60
+ function csvEscape(value: string): string {
61
+ if (!/[",\n\r]/.test(value)) return value;
62
+ return `"${value.replace(/"/g, '""')}"`;
63
+ }
64
+
65
+ function serializeColumns<Row>(columns?: CliResultColumn<Row>[]) {
66
+ return columns?.map((column) => ({
67
+ key: column.key,
68
+ header: column.header,
69
+ ...(column.align ? { align: column.align } : {}),
70
+ ...(column.width ? { width: column.width } : {}),
71
+ }));
72
+ }
73
+
74
+ function renderCsv<Row extends Record<string, unknown>>(
75
+ rows: Row[],
76
+ columns?: CliResultColumn<Row>[],
77
+ ): string {
78
+ const resolvedColumns = columns && columns.length > 0
79
+ ? columns
80
+ : inferColumns(rows as Record<string, unknown>[]) as CliResultColumn<Row>[];
81
+ const header = resolvedColumns.map((column) => csvEscape(column.header)).join(",");
82
+ const body = rows.map((row) => resolvedColumns
83
+ .map((column) => csvEscape(normalizeCell(column.value ? column.value(row) : row[column.key])))
84
+ .join(","));
85
+ return [header, ...body].join("\n");
86
+ }
87
+
88
+ function renderTextTable<Row extends Record<string, unknown>>(
89
+ rows: Row[],
90
+ columns?: CliResultColumn<Row>[],
91
+ ): string {
92
+ const resolvedColumns = columns && columns.length > 0
93
+ ? columns
94
+ : inferColumns(rows as Record<string, unknown>[]) as CliResultColumn<Row>[];
95
+ return renderTable(
96
+ resolvedColumns.map((column) => ({
97
+ header: column.header,
98
+ align: column.align,
99
+ width: column.width,
100
+ })),
101
+ rows.map((row) => resolvedColumns.map((column) => normalizeCell(column.value ? column.value(row) : row[column.key]))),
102
+ );
103
+ }
104
+
105
+ export function serializeCliResult<T, Row extends Record<string, unknown> = Record<string, unknown>>(
106
+ result: CliResult<T>,
107
+ options: CliGlobalOptions,
108
+ renderOptions: CliResultRenderOptions<T, Row> = {},
109
+ ): string {
110
+ if (options.format === "json") {
111
+ const columns = serializeColumns(renderOptions.columns);
112
+ const envelope: CliResultJsonEnvelope<T> = {
113
+ ok: true,
114
+ ...result,
115
+ data: applyLimit(result.data, options.limit),
116
+ ...(columns?.length ? { columns } : {}),
117
+ };
118
+ return JSON.stringify(envelope, null, 2);
119
+ }
120
+
121
+ const rows = asRows(result.data, options.limit, renderOptions.rows);
122
+ if (options.format === "ndjson") {
123
+ return rows.map((row) => JSON.stringify(row)).join("\n");
124
+ }
125
+ if (options.format === "csv") {
126
+ return renderCsv(rows as Row[], renderOptions.columns);
127
+ }
128
+ if (renderOptions.text) {
129
+ return renderOptions.text(result.data);
130
+ }
131
+ return renderTextTable(rows as Row[], renderOptions.columns);
132
+ }
133
+
134
+ export function printCliResult<T, Row extends Record<string, unknown> = Record<string, unknown>>(
135
+ result: CliResult<T>,
136
+ options: CliGlobalOptions,
137
+ renderOptions: CliResultRenderOptions<T, Row> = {},
138
+ ): void {
139
+ if (options.quiet && options.format === "text") return;
140
+ const output = serializeCliResult(result, options, renderOptions);
141
+ if (output) console.log(output);
142
+ }
143
+
144
+ export function serializeCliError(error: CliErrorObject, options: CliGlobalOptions): string {
145
+ if (options.format === "json" || options.format === "ndjson") {
146
+ return JSON.stringify({ ok: false, error }, null, options.format === "json" ? 2 : 0);
147
+ }
148
+ return error.details == null ? error.message : `${error.message}\n${String(error.details)}`;
149
+ }
package/src/cli/types.ts CHANGED
@@ -2,6 +2,7 @@ import type { AppConfig } from "../types/config";
2
2
  import { AppPersistence } from "../data/app-persistence";
3
3
  import { TickerRepository } from "../data/ticker-repository";
4
4
  import { AssetDataRouter } from "../sources/provider-router";
5
+ import type { AppServices } from "../core/app-services";
5
6
 
6
7
  export type ConfigContext = {
7
8
  config: AppConfig;
@@ -13,3 +14,13 @@ export type ConfigContext = {
13
14
  export type MarketContext = ConfigContext & {
14
15
  dataProvider: AssetDataRouter;
15
16
  };
17
+
18
+ export type CliServicesContext = {
19
+ config: AppConfig;
20
+ dataDir: string;
21
+ services: AppServices;
22
+ dataProvider: AssetDataRouter;
23
+ persistence: AppPersistence;
24
+ store: TickerRepository;
25
+ destroy(): void;
26
+ };
package/src/cli.test.ts CHANGED
@@ -22,6 +22,7 @@ const originalHome = process.env.HOME;
22
22
 
23
23
  afterEach(async () => {
24
24
  process.env.HOME = originalHome;
25
+ process.exitCode = 0;
25
26
  await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
26
27
  });
27
28
 
@@ -96,12 +97,12 @@ async function captureConsole<T>(fn: () => Promise<T> | T): Promise<{ result: T;
96
97
  }
97
98
  }
98
99
 
99
- async function captureConsoleFailure(fn: () => Promise<unknown> | unknown): Promise<{ stdout: string; stderr: string; error: unknown }> {
100
+ async function captureConsoleFailure(fn: () => Promise<unknown> | unknown): Promise<{ stdout: string; stderr: string; exitCode: string | number | undefined }> {
100
101
  const logs: string[] = [];
101
102
  const errors: string[] = [];
102
103
  const originalLog = console.log;
103
104
  const originalError = console.error;
104
- const originalExit = process.exit;
105
+ const originalExitCode = process.exitCode;
105
106
 
106
107
  console.log = (...args: unknown[]) => {
107
108
  logs.push(args.map(String).join(" "));
@@ -109,23 +110,22 @@ async function captureConsoleFailure(fn: () => Promise<unknown> | unknown): Prom
109
110
  console.error = (...args: unknown[]) => {
110
111
  errors.push(args.map(String).join(" "));
111
112
  };
112
- process.exit = ((code?: number) => {
113
- throw new Error(`process.exit:${code ?? 0}`);
114
- }) as typeof process.exit;
113
+ process.exitCode = undefined;
115
114
 
116
115
  try {
117
116
  await fn();
118
- throw new Error("Expected command to fail.");
119
- } catch (error) {
117
+ if (process.exitCode == null || process.exitCode === 0) {
118
+ throw new Error("Expected command to fail.");
119
+ }
120
120
  return {
121
121
  stdout: logs.join("\n"),
122
122
  stderr: errors.join("\n"),
123
- error,
123
+ exitCode: process.exitCode,
124
124
  };
125
125
  } finally {
126
126
  console.log = originalLog;
127
127
  console.error = originalError;
128
- process.exit = originalExit;
128
+ process.exitCode = originalExitCode ?? 0;
129
129
  }
130
130
  }
131
131
 
@@ -226,7 +226,7 @@ describe("CLI portfolio commands", () => {
226
226
  });
227
227
 
228
228
  const result = await captureConsoleFailure(() => runCli(["portfolio", "create", "Research"]));
229
- expect(String(result.error)).toContain("process.exit:1");
229
+ expect(result.exitCode).toBe(1);
230
230
  expect(result.stderr).toContain('Portfolio "Research" already exists.');
231
231
  });
232
232
 
@@ -370,7 +370,7 @@ describe("CLI portfolio commands", () => {
370
370
  });
371
371
 
372
372
  const result = await captureConsoleFailure(() => runCli(["portfolio", "add", "IBKR Account", "NVDA"]));
373
- expect(String(result.error)).toContain("process.exit:1");
373
+ expect(result.exitCode).toBe(1);
374
374
  expect(result.stderr).toContain('Portfolio "IBKR Account" is broker-managed and cannot be modified manually.');
375
375
  });
376
376
  });
@@ -28,6 +28,7 @@ import {
28
28
  resolveCursorMotionKind,
29
29
  type ChartMouseEvent,
30
30
  type DisplayCursorState,
31
+ type MouseInteractionEvent,
31
32
  } from "../core/pointer";
32
33
  import type {
33
34
  ComparisonChartSeries,
@@ -48,6 +49,7 @@ interface UseComparisonChartPointerInteractionsOptions {
48
49
  chartWidth: number;
49
50
  commitSelectionCursor: (next: { cursorX: number | null; cursorY: number | null }) => void;
50
51
  expandBufferRange: (action: PendingExpansionAction) => boolean;
52
+ focusPaneForMouseInteraction: (event: MouseInteractionEvent | null | undefined) => void;
51
53
  mouseCrosshairDisabledRef: MutableRefObject<boolean>;
52
54
  plotRef: RefObject<BoxRenderable | null>;
53
55
  pointCount: number;
@@ -65,6 +67,7 @@ export function useComparisonChartPointerInteractions({
65
67
  chartWidth,
66
68
  commitSelectionCursor,
67
69
  expandBufferRange,
70
+ focusPaneForMouseInteraction,
68
71
  mouseCrosshairDisabledRef,
69
72
  plotRef,
70
73
  pointCount,
@@ -113,13 +116,14 @@ export function useComparisonChartPointerInteractions({
113
116
 
114
117
  const handlePlotDown = useCallback((event: ChartMouseEvent) => {
115
118
  consumeChartMouseEvent(event);
119
+ focusPaneForMouseInteraction(null);
116
120
  mouseCrosshairDisabledRef.current = false;
117
121
  if (!syncPointerCursor(event)) return;
118
122
  dragRef.current = {
119
123
  startGlobalX: getGlobalMouseX(event, renderer),
120
124
  startWindow: visibleDateWindow,
121
125
  };
122
- }, [mouseCrosshairDisabledRef, renderer, syncPointerCursor, visibleDateWindow]);
126
+ }, [focusPaneForMouseInteraction, mouseCrosshairDisabledRef, renderer, syncPointerCursor, visibleDateWindow]);
123
127
 
124
128
  const handlePlotDrag = useCallback((event: ChartMouseEvent) => {
125
129
  consumeChartMouseEvent(event);
@@ -147,6 +151,7 @@ export function useComparisonChartPointerInteractions({
147
151
 
148
152
  const handlePlotScroll = useCallback((event: ChartMouseEvent) => {
149
153
  consumeChartMouseEvent(event);
154
+ focusPaneForMouseInteraction(null);
150
155
  const direction = event.scroll?.direction;
151
156
  if (!direction) return;
152
157
  const scrollPan = consumeScrollPanMovement(
@@ -179,6 +184,7 @@ export function useComparisonChartPointerInteractions({
179
184
  chartWidth,
180
185
  dateBounds,
181
186
  expandBufferRange,
187
+ focusPaneForMouseInteraction,
182
188
  scrollPanCellRemainderRef,
183
189
  series,
184
190
  seriesDates,
@@ -1,11 +1,13 @@
1
1
  import type { ComparisonChartProjection } from "../comparison/data";
2
2
  import { PriceReturnTable, type PriceReturnTableRow } from "../../price-performance";
3
3
  import type { PriceReturnField } from "../../../market-data/performance";
4
+ import type { MouseInteractionEvent } from "../core/pointer";
4
5
 
5
6
  interface ComparisonChartLegendProps {
6
7
  legendActiveIndex: number | null;
7
8
  legendItemWidth: number;
8
9
  legendRows: number;
10
+ onFocusInteraction: (event: MouseInteractionEvent | null | undefined) => void;
9
11
  onOpenSymbol: (symbol: string) => void;
10
12
  onSelectSymbol: (symbol: string) => void;
11
13
  performanceBySymbol: ReadonlyMap<string, PriceReturnField[]>;
@@ -36,6 +38,7 @@ export function ComparisonChartLegend({
36
38
  legendActiveIndex,
37
39
  legendItemWidth,
38
40
  legendRows,
41
+ onFocusInteraction,
39
42
  onOpenSymbol,
40
43
  onSelectSymbol,
41
44
  performanceBySymbol,
@@ -61,6 +64,7 @@ export function ComparisonChartLegend({
61
64
  return (
62
65
  <PriceReturnTable
63
66
  height={legendRows}
67
+ onFocusInteraction={onFocusInteraction}
64
68
  onOpenSymbol={onOpenSymbol}
65
69
  onSelectSymbol={onSelectSymbol}
66
70
  rows={rows}
@@ -3,7 +3,8 @@ import {
3
3
  DEFAULT_LIVE_CHART_REFRESH_INTERVAL_MS,
4
4
  useChartQueries,
5
5
  } from "../../../market-data/hooks";
6
- import { buildChartKey } from "../../../market-data/selectors";
6
+ import type { ChartRequest, InstrumentRef } from "../../../market-data/request-types";
7
+ import { buildChartKey, resolveEntryData } from "../../../market-data/selectors";
7
8
  import { getSharedMarketData } from "../../../plugins/registry";
8
9
  import { blendHex, colors, getComparisonSeriesColor } from "../../../theme/colors";
9
10
  import type { BrokerContractRef } from "../../../types/instrument";
@@ -24,6 +25,8 @@ import type {
24
25
  ComparisonChartViewState,
25
26
  } from "../core/types";
26
27
 
28
+ const COMPARISON_PERFORMANCE_RANGE = "5Y" as const;
29
+
27
30
  export interface ComparisonChartSymbolSource {
28
31
  symbol: string;
29
32
  currency: string | undefined;
@@ -40,6 +43,16 @@ interface UseComparisonChartRenderDataOptions {
40
43
  viewState: ComparisonChartViewState;
41
44
  }
42
45
 
46
+ function instrumentFromSymbolSource(source: ComparisonChartSymbolSource): InstrumentRef {
47
+ return {
48
+ symbol: source.symbol,
49
+ exchange: source.exchange,
50
+ brokerId: source.brokerId,
51
+ brokerInstanceId: source.brokerInstanceId,
52
+ instrument: source.instrument,
53
+ };
54
+ }
55
+
43
56
  export function useComparisonChartRenderData({
44
57
  symbolSources,
45
58
  viewState,
@@ -143,21 +156,25 @@ export function useComparisonChartRenderData({
143
156
  );
144
157
  const chartRequests = useMemo(() => (
145
158
  symbolSources.map((source) => ({
146
- instrument: {
147
- symbol: source.symbol,
148
- exchange: source.exchange,
149
- brokerId: source.brokerId,
150
- brokerInstanceId: source.brokerInstanceId,
151
- instrument: source.instrument,
152
- },
159
+ instrument: instrumentFromSymbolSource(source),
153
160
  bufferRange: viewState.bufferRange,
154
161
  granularity: effectiveResolution === "auto" ? "range" as const : "resolution" as const,
155
162
  resolution: effectiveResolution === "auto" ? undefined : effectiveResolution,
156
163
  }))
157
164
  ), [effectiveResolution, symbolSources, viewState.bufferRange]);
165
+ const performanceRequests = useMemo<ChartRequest[]>(() => (
166
+ symbolSources.map((source) => ({
167
+ instrument: instrumentFromSymbolSource(source),
168
+ bufferRange: COMPARISON_PERFORMANCE_RANGE,
169
+ granularity: "range",
170
+ }))
171
+ ), [symbolSources]);
158
172
  const chartEntries = useChartQueries(chartRequests, {
159
173
  refreshIntervalMs: DEFAULT_LIVE_CHART_REFRESH_INTERVAL_MS,
160
174
  });
175
+ const performanceEntries = useChartQueries(performanceRequests, {
176
+ refreshIntervalMs: DEFAULT_LIVE_CHART_REFRESH_INTERVAL_MS,
177
+ });
161
178
  const entryStates = useMemo(() => chartRequests.map((request) => (
162
179
  resolveChartBodyState(chartEntries.get(buildChartKey(request)), (value) => Array.isArray(value) && value.length > 0, "No chart data yet.")
163
180
  )), [chartEntries, chartRequests]);
@@ -182,6 +199,17 @@ export function useComparisonChartRenderData({
182
199
  points,
183
200
  };
184
201
  }), [chartEntries, chartRequests, symbolSources]);
202
+ const performanceHistoryBySymbol = useMemo(() => {
203
+ const bySymbol = new Map<string, PricePoint[]>();
204
+ symbolSources.forEach((source, index) => {
205
+ const request = performanceRequests[index];
206
+ const history = request ? resolveEntryData(performanceEntries.get(buildChartKey(request))) : null;
207
+ if (history?.length) {
208
+ bySymbol.set(source.symbol, history);
209
+ }
210
+ });
211
+ return bySymbol;
212
+ }, [performanceEntries, performanceRequests, symbolSources]);
185
213
 
186
214
  return {
187
215
  availableManualResolutions,
@@ -192,6 +220,7 @@ export function useComparisonChartRenderData({
192
220
  isUpdating,
193
221
  resolutionChips,
194
222
  selectionSupportMap,
223
+ performanceHistoryBySymbol,
195
224
  series,
196
225
  supportMap,
197
226
  };
@@ -1,6 +1,7 @@
1
- import { useEffect, useRef, type Dispatch, type MutableRefObject, type SetStateAction } from "react";
1
+ import { useCallback, useEffect, useRef, type Dispatch, type MutableRefObject, type SetStateAction } from "react";
2
2
  import type { BoxRenderable, NativeRendererHost } from "../../../ui";
3
- import { buildDisplayCursorState } from "../core/pointer";
3
+ import { useAppDispatch, usePaneInstanceId } from "../../../state/app/context";
4
+ import { buildDisplayCursorState, type MouseInteractionEvent } from "../core/pointer";
4
5
  import type { ComparisonChartViewState } from "../core/types";
5
6
  import { useChartDisplayCursor, useChartDisplayCursorLayoutRemap } from "../display-cursor";
6
7
  import { clamp } from "./helpers";
@@ -10,6 +11,7 @@ interface UseComparisonChartSelectionRuntimeOptions {
10
11
  chartWidth: number;
11
12
  cursorX: number | null;
12
13
  cursorY: number | null;
14
+ focused: boolean;
13
15
  renderer: NativeRendererHost;
14
16
  setViewState: Dispatch<SetStateAction<ComparisonChartViewState>>;
15
17
  symbols: string[];
@@ -20,6 +22,7 @@ export function useComparisonChartSelectionRuntime({
20
22
  chartWidth,
21
23
  cursorX: viewCursorX,
22
24
  cursorY: viewCursorY,
25
+ focused,
23
26
  renderer,
24
27
  setViewState,
25
28
  symbols,
@@ -28,6 +31,7 @@ export function useComparisonChartSelectionRuntime({
28
31
  displayCursor: ReturnType<typeof useChartDisplayCursor>["displayCursor"];
29
32
  displayCursorX: number | null;
30
33
  displayCursorY: number | null;
34
+ focusPaneForMouseInteraction: (event: MouseInteractionEvent | null | undefined) => void;
31
35
  mouseCrosshairDisabledRef: MutableRefObject<boolean>;
32
36
  plotRef: MutableRefObject<BoxRenderable | null>;
33
37
  scrollPanCellRemainderRef: MutableRefObject<number>;
@@ -35,6 +39,8 @@ export function useComparisonChartSelectionRuntime({
35
39
  setSelectedSymbol: (symbol: string) => void;
36
40
  updateDisplayCursorTarget: ReturnType<typeof useChartDisplayCursor>["updateDisplayCursorTarget"];
37
41
  } {
42
+ const dispatch = useAppDispatch();
43
+ const paneId = usePaneInstanceId();
38
44
  const plotRef = useRef<BoxRenderable | null>(null);
39
45
  const mouseCrosshairDisabledRef = useRef(false);
40
46
  const scrollPanCellRemainderRef = useRef(0);
@@ -52,6 +58,16 @@ export function useComparisonChartSelectionRuntime({
52
58
  const displayCursorX = displayCursor.cellX !== null ? clamp(displayCursor.cellX, 0, chartWidth - 1) : null;
53
59
  const displayCursorY = displayCursor.cellY !== null ? clamp(displayCursor.cellY, 0, chartHeight - 1) : null;
54
60
 
61
+ const focusPaneForMouseInteraction = useCallback((
62
+ event: MouseInteractionEvent | null | undefined,
63
+ ) => {
64
+ event?.stopPropagation?.();
65
+ event?.preventDefault?.();
66
+ if (!focused) {
67
+ dispatch({ type: "FOCUS_PANE", paneId });
68
+ }
69
+ }, [dispatch, focused, paneId]);
70
+
55
71
  const setSelectedSymbol = (symbol: string) => {
56
72
  setViewState((current) => (
57
73
  current.selectedSymbol === symbol
@@ -101,6 +117,7 @@ export function useComparisonChartSelectionRuntime({
101
117
  displayCursor,
102
118
  displayCursorX,
103
119
  displayCursorY,
120
+ focusPaneForMouseInteraction,
104
121
  mouseCrosshairDisabledRef,
105
122
  plotRef,
106
123
  scrollPanCellRemainderRef,