@gloom-sh/terminal 0.20.14 → 0.20.16

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 (144) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/index.ts +54 -0
  3. package/src/api-client/install-experiments.ts +8 -7
  4. package/src/api-client/paths.ts +2 -1
  5. package/src/api-client/product-waitlist.ts +63 -0
  6. package/src/api-client/request.ts +4 -2
  7. package/src/api-client/types/billing.ts +45 -0
  8. package/src/api-client/yearly-plan.ts +132 -0
  9. package/src/app/global-shortcuts.ts +5 -3
  10. package/src/app/pane-runtime/index.tsx +2 -2
  11. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  12. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  13. package/src/app/since-last-visit/keys.ts +26 -0
  14. package/src/app/since-last-visit/model.ts +266 -0
  15. package/src/app/since-last-visit/strip.tsx +193 -0
  16. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  17. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  18. package/src/app.tsx +15 -0
  19. package/src/cli/commands/market.ts +8 -4
  20. package/src/cli/commands/system.ts +29 -1
  21. package/src/cli/commands/ticker.ts +12 -5
  22. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  23. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  24. package/src/cli/desktop-pane-shot-view.ts +3 -7
  25. package/src/cli/desktop-pane-shot.ts +26 -28
  26. package/src/cli/help.ts +1 -0
  27. package/src/cli/history-rows.ts +24 -0
  28. package/src/cli/index.ts +4 -0
  29. package/src/cli/options.ts +29 -1
  30. package/src/cli/pane-functions/catalog.ts +41 -4
  31. package/src/cli/pane-functions/function-help.ts +1 -1
  32. package/src/cli/pane-functions/headless.ts +63 -1
  33. package/src/cli/pane-functions/index.ts +2 -2
  34. package/src/cli/pane-functions/resolver.ts +43 -0
  35. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  36. package/src/cli/report-tables.ts +20 -5
  37. package/src/cli/shot-temp-dir.ts +30 -0
  38. package/src/cli/suffixed-listing-rows.ts +11 -0
  39. package/src/components/chart/composite/composite-chart.tsx +3 -3
  40. package/src/components/command-bar/commands/direct/index.ts +31 -8
  41. package/src/components/command-bar/commands/registry.ts +7 -0
  42. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  43. package/src/components/command-bar/routes/root/results.ts +16 -0
  44. package/src/components/company-logo.tsx +10 -3
  45. package/src/components/data-table/sections.ts +6 -1
  46. package/src/components/layout/pane/title.ts +6 -2
  47. package/src/components/layout/shell/index.tsx +5 -1
  48. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  49. package/src/components/ticker/badge/format.ts +12 -3
  50. package/src/components/ticker/badge/index.tsx +9 -3
  51. package/src/components/ticker/list-table-view.tsx +119 -17
  52. package/src/components/ui/data-table/display-columns.ts +16 -0
  53. package/src/components/ui/data-table/index.tsx +40 -9
  54. package/src/components/ui/data-table/types.ts +14 -0
  55. package/src/core/state/app/layout-reducer.ts +3 -1
  56. package/src/core/state/app/layout.ts +2 -2
  57. package/src/data/config/layout.ts +14 -0
  58. package/src/data/config/store/normalize.ts +11 -1
  59. package/src/i18n/es.ts +38 -0
  60. package/src/i18n/ja.ts +38 -0
  61. package/src/i18n/ko.ts +38 -0
  62. package/src/i18n/zh-cn.ts +38 -0
  63. package/src/i18n/zh-tw.ts +38 -0
  64. package/src/layout/pane-follow.ts +141 -4
  65. package/src/layout/pane-layout-move.ts +10 -7
  66. package/src/layout/ticker-navigation.ts +13 -19
  67. package/src/layout/ticker-retarget.ts +3 -2
  68. package/src/market-data/market/index-level.ts +19 -0
  69. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  70. package/src/plugins/builtin/account-management/model.ts +2 -0
  71. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  72. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  73. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  74. package/src/plugins/builtin/awards/pane.tsx +6 -8
  75. package/src/plugins/builtin/changelog/index.tsx +6 -44
  76. package/src/plugins/builtin/changelog/versions.ts +17 -68
  77. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  78. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  79. package/src/plugins/builtin/cpi/pane.tsx +1 -1
  80. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  81. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  82. package/src/plugins/builtin/earnings/board.tsx +36 -16
  83. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  84. package/src/plugins/builtin/earnings/history-table.ts +1 -1
  85. package/src/plugins/builtin/earnings/index.tsx +1 -1
  86. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  87. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  88. package/src/plugins/builtin/exposure/index.tsx +1 -1
  89. package/src/plugins/builtin/macro-day/model.ts +6 -4
  90. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  91. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  92. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  93. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  94. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  95. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  96. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  97. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +176 -17
  98. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  99. package/src/plugins/builtin/portfolio-list/pane/index.tsx +90 -15
  100. package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
  101. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  102. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  103. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  104. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  105. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  106. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  107. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  108. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  109. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  110. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  111. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  112. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  113. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  114. package/src/plugins/builtin/ticker-detail/headless.ts +254 -34
  115. package/src/plugins/builtin/ticker-detail/overview/model.ts +7 -3
  116. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  117. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  118. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  119. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  120. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  121. package/src/portfolio/column-values.ts +20 -8
  122. package/src/portfolio/suffixed-listings.ts +3 -1
  123. package/src/portfolio/watchlist-groups.ts +212 -0
  124. package/src/react/ticker-source.ts +3 -1
  125. package/src/renderers/dom/styles.css +7 -0
  126. package/src/state/app/bootstrap.ts +11 -0
  127. package/src/state/app/context/index.tsx +6 -0
  128. package/src/sync/collections-contributor.ts +5 -2
  129. package/src/sync/config-merge.ts +10 -2
  130. package/src/sync/sanitize.ts +28 -0
  131. package/src/telemetry/usage-counts.ts +17 -0
  132. package/src/time-series/chart-seed.ts +1 -1
  133. package/src/time-series/financial-period-coverage.ts +4 -12
  134. package/src/time-series/parsed-history-cache.ts +1 -1
  135. package/src/time-series/resolve.ts +1 -1
  136. package/src/time-series/use-chart-resolution.ts +6 -1
  137. package/src/types/config.ts +32 -0
  138. package/src/types/headless.ts +5 -0
  139. package/src/types/plugin-context.ts +5 -0
  140. package/src/types/ticker.ts +14 -0
  141. package/src/ui/ascii-font.ts +1 -4
  142. package/src/utils/async-deadline.ts +2 -2
  143. package/src/utils/csv.ts +44 -5
  144. package/src/utils/futures-generic.ts +3 -0
@@ -0,0 +1,289 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
+ import { apiClient } from "../../api-client";
3
+ import type { AppPluginStateStorePort } from "../../core/app-service-ports";
4
+ import { t } from "../../i18n";
5
+ import type { MarketDataCoordinator } from "../../market-data/coordinator";
6
+ import type { InstrumentRef } from "../../market-data/request-types";
7
+ import { buildQuoteKey, resolveEntryData } from "../../market-data/selectors";
8
+ import { useAppActive, useAppVisible } from "../../state/app/activity";
9
+ import { useAppDispatch, useAppGetState, useAppSelector } from "../../state/app/context";
10
+ import { scheduleConfigSave } from "../../state/config-save-scheduler";
11
+ import { useInlineTickerOpener } from "../../state/hooks/inline-tickers";
12
+ import { recordFunctionOpen, recordFunctionShown } from "../../telemetry/usage-counts";
13
+ import type { AppNotificationRequest } from "../../types/plugin";
14
+ import { logFailure } from "../../utils/log-failure";
15
+ import {
16
+ MIN_AWAY_MS,
17
+ observeQuote,
18
+ recapSince,
19
+ trackedListings,
20
+ visitScope,
21
+ type TrackedListing,
22
+ type VisitMove,
23
+ type VisitObservation,
24
+ type VisitRecap,
25
+ } from "./model";
26
+ import { createVisitBaselineStore, VisitTracker } from "./visit-tracker";
27
+
28
+ /** How long the return waits for its quotes before it compares what it has. */
29
+ const COMPARE_WAIT_MS = 10_000;
30
+ /** Quotes ticking in batches are read once they settle, not on every tick. */
31
+ const SWEEP_DELAY_MS = 2_000;
32
+
33
+ /**
34
+ * Usage counts, by the strip's own names: never which tickers. Showing is not
35
+ * the user opening anything, so it counts as on screen at launch (`restored`);
36
+ * opening a move and turning the strip off are opens.
37
+ */
38
+ const SHOWN_FUNCTION = "LASTVISIT";
39
+ const OPENED_FUNCTION = "LASTVISIT-OPEN";
40
+ const OFF_FUNCTION = "LASTVISIT-OFF";
41
+
42
+ const SINCE_LAST_VISIT_OFF_MESSAGE = "Since Last Visit is off. Turn it on again from the command bar: Since Last Visit.";
43
+
44
+ /** Who is signed in, as the visit is kept for: the API client unless a test says otherwise. */
45
+ export interface VisitAccountSource {
46
+ subscribe(listener: () => void): () => void;
47
+ currentId(): string | null;
48
+ }
49
+
50
+ const apiAccount: VisitAccountSource = {
51
+ subscribe: (listener) => apiClient.subscribeCurrentUser(listener),
52
+ currentId: () => apiClient.getCurrentUser()?.id ?? null,
53
+ };
54
+
55
+ export interface SinceLastVisitMove {
56
+ move: VisitMove;
57
+ instrument: InstrumentRef;
58
+ }
59
+
60
+ export interface SinceLastVisit {
61
+ /** The last visit and what moved since, while the strip has something to show; null otherwise. */
62
+ recap: { seenAt: number; moves: SinceLastVisitMove[] } | null;
63
+ /** Hides the strip for this session. */
64
+ hide(): void;
65
+ /** Turns the strip off on this machine, with a toast that can undo it. */
66
+ turnOff(): void;
67
+ /** Opens a moved ticker's research. */
68
+ open(move: VisitMove): void;
69
+ /** The strip is on screen: counted once per session. */
70
+ noteShown(): void;
71
+ }
72
+
73
+ interface UseSinceLastVisitOptions {
74
+ /** This window shows the strip: the main window, with no setup or sign-in in front of the workspace. */
75
+ active: boolean;
76
+ marketData: Pick<MarketDataCoordinator, "getQuoteEntry" | "loadQuotesBatch" | "subscribeKeys">;
77
+ pluginState: Pick<AppPluginStateStorePort, "get" | "set" | "delete" | "keys">;
78
+ /** Settles once every plugin has registered: the signed-in account is known by then. */
79
+ pluginsReady?: Promise<unknown>;
80
+ notify(request: AppNotificationRequest): void;
81
+ account?: VisitAccountSource;
82
+ }
83
+
84
+ function usePromiseSettled(promise: Promise<unknown> | undefined): boolean {
85
+ const [settled, setSettled] = useState(!promise);
86
+ useEffect(() => {
87
+ if (!promise) {
88
+ setSettled(true);
89
+ return;
90
+ }
91
+ let live = true;
92
+ const done = () => {
93
+ if (live) setSettled(true);
94
+ };
95
+ promise.then(done, done);
96
+ return () => {
97
+ live = false;
98
+ };
99
+ }, [promise]);
100
+ return settled;
101
+ }
102
+
103
+ function currentObservations(
104
+ listings: readonly TrackedListing[],
105
+ marketData: Pick<MarketDataCoordinator, "getQuoteEntry">,
106
+ now: number,
107
+ ): Map<string, VisitObservation> {
108
+ const current = new Map<string, VisitObservation>();
109
+ for (const listing of listings) {
110
+ const observation = observeQuote(listing.symbol, resolveEntryData(marketData.getQuoteEntry(listing.instrument)), now);
111
+ if (observation) current.set(listing.key, observation);
112
+ }
113
+ return current;
114
+ }
115
+
116
+ /**
117
+ * The returning-user strip's session: which account's last visit to read,
118
+ * the one comparison of each account's return with it, and the prices this
119
+ * visit keeps for the next one. See `./model.ts` for what counts as a move
120
+ * and `./visit-tracker.ts` for when the visit is written.
121
+ */
122
+ export function useSinceLastVisit({
123
+ active,
124
+ marketData,
125
+ pluginState,
126
+ pluginsReady,
127
+ notify,
128
+ account = apiAccount,
129
+ }: UseSinceLastVisitOptions): SinceLastVisit {
130
+ const dispatch = useAppDispatch();
131
+ const getState = useAppGetState();
132
+ const enabled = useAppSelector((state) => state.config.sinceLastVisit !== false);
133
+ const initialized = useAppSelector((state) => state.initialized);
134
+ const portfolios = useAppSelector((state) => state.config.portfolios);
135
+ const watchlists = useAppSelector((state) => state.config.watchlists);
136
+ const tickers = useAppSelector((state) => state.tickers);
137
+ const allTracked = useMemo(() => trackedListings({ portfolios, watchlists }, tickers), [portfolios, tickers, watchlists]);
138
+ const trackedKey = allTracked.map((listing) => listing.key).join("\n");
139
+ // A ticker refresh replaces the map without changing which listings are tracked.
140
+ const tracked = useMemo(() => allTracked, [trackedKey]);
141
+ const trackedRef = useRef(tracked);
142
+ trackedRef.current = tracked;
143
+
144
+ const pluginsSettled = usePromiseSettled(pluginsReady);
145
+ const scope = useSyncExternalStore(account.subscribe, () => visitScope(account.currentId()), () => visitScope(account.currentId()));
146
+ const visible = useAppVisible();
147
+ const focused = useAppActive();
148
+ // In the app and looking at it: a hidden window, or a terminal in the
149
+ // background, keeps ticking prices nobody saw.
150
+ const present = visible && focused;
151
+ const running = enabled && active && initialized && pluginsSettled;
152
+
153
+ const store = useMemo(() => createVisitBaselineStore(pluginState), [pluginState]);
154
+ const tracker = useMemo(() => new VisitTracker(store), [store]);
155
+ useEffect(() => () => tracker.stop(), [tracker]);
156
+
157
+ /** Each account's return is compared once per session; a re-enable or a flip back reuses it. */
158
+ const compared = useRef(new Map<string, VisitRecap | null>());
159
+ const [shown, setShown] = useState<{ scope: string; recap: VisitRecap } | null>(null);
160
+ const [hidden, setHidden] = useState(false);
161
+ const countedShown = useRef(false);
162
+
163
+ // Off forgets every stored visit; on again starts a new one.
164
+ useEffect(() => {
165
+ if (!enabled) tracker.forget();
166
+ }, [enabled, tracker]);
167
+
168
+ useEffect(() => {
169
+ tracker.setPresent(running && present);
170
+ }, [present, running, tracker]);
171
+
172
+ // The return: the last visit read once for this account, compared with the
173
+ // quotes this session loads for it, before this visit may be written over it.
174
+ useEffect(() => {
175
+ if (!running) return;
176
+ const baseline = tracker.begin(scope);
177
+ if (compared.current.has(scope)) {
178
+ tracker.allowSaving();
179
+ return;
180
+ }
181
+ const listings = trackedRef.current;
182
+ const due = !!baseline && Date.now() - baseline.seenAt >= MIN_AWAY_MS
183
+ && listings.some((listing) => !!baseline.observations[listing.key]);
184
+ if (!due) {
185
+ compared.current.set(scope, null);
186
+ tracker.allowSaving();
187
+ return;
188
+ }
189
+ let done = false;
190
+ const settle = () => {
191
+ if (done) return;
192
+ done = true;
193
+ clearTimeout(timer);
194
+ const now = Date.now();
195
+ const recap = recapSince(baseline, trackedRef.current, currentObservations(trackedRef.current, marketData, now), now);
196
+ compared.current.set(scope, recap);
197
+ if (recap) setShown({ scope, recap });
198
+ tracker.allowSaving();
199
+ };
200
+ const timer = setTimeout(settle, COMPARE_WAIT_MS);
201
+ marketData.loadQuotesBatch(listings.map((listing) => listing.instrument)).then(settle, (error: unknown) => {
202
+ logFailure("since-last-visit", "Loading the return's quotes failed")(error);
203
+ settle();
204
+ });
205
+ return () => {
206
+ // A result that lands after this (another account, turned off, gone) is not this return's.
207
+ if (done) return;
208
+ done = true;
209
+ clearTimeout(timer);
210
+ };
211
+ }, [marketData, running, scope, tracker]);
212
+
213
+ // This visit's prices: whatever quotes the app has for the tracked listings,
214
+ // read when they change while the user is in the app.
215
+ useEffect(() => {
216
+ if (!running) return;
217
+ tracker.begin(scope);
218
+ tracker.retain(new Set(tracked.map((listing) => listing.key)));
219
+ let timer: ReturnType<typeof setTimeout> | null = null;
220
+ const sweep = () => {
221
+ timer = null;
222
+ for (const [key, observation] of currentObservations(tracked, marketData, Date.now())) tracker.observe(key, observation);
223
+ };
224
+ sweep();
225
+ const unsubscribe = marketData.subscribeKeys(tracked.map((listing) => buildQuoteKey(listing.instrument)), () => {
226
+ timer ??= setTimeout(sweep, SWEEP_DELAY_MS);
227
+ });
228
+ return () => {
229
+ unsubscribe();
230
+ if (timer == null) return;
231
+ clearTimeout(timer);
232
+ sweep();
233
+ };
234
+ }, [marketData, present, running, scope, tracked, tracker]);
235
+
236
+ const recap = useMemo(() => {
237
+ // Not over setup or the sign-in gate, which can open in front of a strip already shown.
238
+ if (!enabled || !active || hidden || !shown || shown.scope !== scope) return null;
239
+ const instruments = new Map(tracked.map((listing) => [listing.key, listing.instrument] as const));
240
+ // A ticker taken out of the collections leaves the strip with it.
241
+ const moves = shown.recap.moves.flatMap((move) => {
242
+ const instrument = instruments.get(move.key);
243
+ return instrument ? [{ move, instrument }] : [];
244
+ });
245
+ return moves.length > 0 ? { seenAt: shown.recap.seenAt, moves } : null;
246
+ }, [active, enabled, hidden, scope, shown, tracked]);
247
+
248
+ const setEnabled = useCallback((on: boolean) => {
249
+ const current = getState().config;
250
+ if ((current.sinceLastVisit !== false) === on) return;
251
+ const { sinceLastVisit: _previous, ...rest } = current;
252
+ dispatch({ type: "SET_CONFIG", config: on ? rest : { ...rest, sinceLastVisit: false } });
253
+ // Assembled when the write fires, recent tickers included, as the app's own saves are.
254
+ scheduleConfigSave(() => {
255
+ const state = getState();
256
+ return { ...state.config, recentTickers: state.recentTickers };
257
+ });
258
+ }, [dispatch, getState]);
259
+
260
+ const hide = useCallback(() => {
261
+ setHidden(true);
262
+ // Seen: a restart now compares with this visit, not the one before.
263
+ tracker.flush();
264
+ }, [tracker]);
265
+
266
+ const turnOff = useCallback(() => {
267
+ setEnabled(false);
268
+ recordFunctionOpen({ shortcut: OFF_FUNCTION, externalPluginId: null });
269
+ notify({
270
+ body: t(SINCE_LAST_VISIT_OFF_MESSAGE),
271
+ type: "info",
272
+ action: { label: t("Undo"), onClick: () => setEnabled(true) },
273
+ });
274
+ }, [notify, setEnabled]);
275
+
276
+ const openTicker = useInlineTickerOpener();
277
+ const open = useCallback((move: VisitMove) => {
278
+ recordFunctionOpen({ shortcut: OPENED_FUNCTION, externalPluginId: null });
279
+ openTicker(move.symbol);
280
+ }, [openTicker]);
281
+
282
+ const noteShown = useCallback(() => {
283
+ if (countedShown.current) return;
284
+ countedShown.current = true;
285
+ recordFunctionShown({ shortcut: SHOWN_FUNCTION, externalPluginId: null });
286
+ }, []);
287
+
288
+ return useMemo(() => ({ recap, hide, turnOff, open, noteShown }), [hide, noteShown, open, recap, turnOff]);
289
+ }
@@ -0,0 +1,191 @@
1
+ import type { AppPluginStateStorePort } from "../../core/app-service-ports";
2
+ import { createPersistScheduler, type PersistScheduler } from "../../state/persist-scheduler";
3
+ import { fnv1aHex } from "../../utils/hash";
4
+ import { logFailure } from "../../utils/log-failure";
5
+ import { readVisitBaseline, type VisitBaseline, type VisitObservation } from "./model";
6
+
7
+ /**
8
+ * The last visit's prices live in the app's local state store (SQLite in the
9
+ * terminal and the desktop app, browser storage on the web), one row per
10
+ * account, never in config.json, cloud sync or anything sent anywhere.
11
+ */
12
+ const STATE_OWNER = "core.since-last-visit";
13
+ const KEY_PREFIX = "visit:";
14
+ /** Accounts whose last visit this device keeps; the one seen longest ago goes first. */
15
+ export const MAX_KEPT_SCOPES = 3;
16
+ /** How long a visit's newest prices wait before they are written, at most. */
17
+ const VISIT_SAVE_DELAY_MS = 5 * 60_000;
18
+
19
+ export interface VisitBaselineStore {
20
+ load(scope: string): VisitBaseline | null;
21
+ save(baseline: VisitBaseline): void;
22
+ clear(): void;
23
+ }
24
+
25
+ type VisitStateStore = Pick<AppPluginStateStorePort, "get" | "set" | "delete" | "keys">;
26
+
27
+ function storeKey(scope: string): string {
28
+ return `${KEY_PREFIX}${fnv1aHex(scope)}`;
29
+ }
30
+
31
+ export function createVisitBaselineStore(pluginState: VisitStateStore): VisitBaselineStore {
32
+ const seenAtOf = (key: string): number => {
33
+ const value = pluginState.get<{ seenAt?: unknown }>(STATE_OWNER, key)?.value;
34
+ return typeof value?.seenAt === "number" ? value.seenAt : 0;
35
+ };
36
+ return {
37
+ load(scope) {
38
+ try {
39
+ // The row names its account; one that hashed to the same key is not this one's.
40
+ return readVisitBaseline(pluginState.get(STATE_OWNER, storeKey(scope))?.value, scope);
41
+ } catch (error) {
42
+ logFailure("since-last-visit", "Loading the last visit failed")(error);
43
+ return null;
44
+ }
45
+ },
46
+ save(baseline) {
47
+ try {
48
+ const key = storeKey(baseline.scope);
49
+ pluginState.set(STATE_OWNER, key, baseline);
50
+ const others = pluginState.keys(STATE_OWNER).filter((entry) => entry.startsWith(KEY_PREFIX) && entry !== key);
51
+ if (others.length < MAX_KEPT_SCOPES) return;
52
+ const oldestFirst = others.map((entry) => ({ entry, seenAt: seenAtOf(entry) })).sort((a, b) => a.seenAt - b.seenAt);
53
+ for (const { entry } of oldestFirst.slice(0, others.length - (MAX_KEPT_SCOPES - 1))) {
54
+ pluginState.delete(STATE_OWNER, entry);
55
+ }
56
+ } catch (error) {
57
+ logFailure("since-last-visit", "Saving the visit failed")(error);
58
+ }
59
+ },
60
+ clear() {
61
+ try {
62
+ for (const key of pluginState.keys(STATE_OWNER)) pluginState.delete(STATE_OWNER, key);
63
+ } catch (error) {
64
+ logFailure("since-last-visit", "Forgetting the last visits failed")(error);
65
+ }
66
+ },
67
+ };
68
+ }
69
+
70
+ /**
71
+ * One visit's prices for one account, from the moment it starts until it is
72
+ * written for the next one. A price is kept only while the user is in the
73
+ * app (`setPresent`): ticks that land while it is hidden or in the
74
+ * background were never seen. The stored baseline is the only copy of the
75
+ * last visit, so nothing is written over it until the return compared
76
+ * against it (`allowSaving`); after that the visit is written at most every
77
+ * `saveDelayMs`, when the user leaves, and when the app quits.
78
+ */
79
+ export class VisitTracker {
80
+ private scope: string | null = null;
81
+ private previous: VisitBaseline | null = null;
82
+ private readonly visit = new Map<string, VisitObservation>();
83
+ private present = false;
84
+ private lastPresentAt: number | null = null;
85
+ private saving = false;
86
+ private pending = false;
87
+ private readonly saver: PersistScheduler<null>;
88
+ private readonly now: () => number;
89
+
90
+ constructor(
91
+ private readonly store: VisitBaselineStore,
92
+ { saveDelayMs = VISIT_SAVE_DELAY_MS, now = Date.now }: { saveDelayMs?: number; now?: () => number } = {},
93
+ ) {
94
+ this.now = now;
95
+ this.saver = createPersistScheduler<null>({
96
+ delayMs: saveDelayMs,
97
+ save: () => this.write(),
98
+ onError: logFailure("since-last-visit", "Saving the visit failed"),
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Starts the visit for an account (`visitScope`), writing the one under way
104
+ * for another account first. Returns the last visit stored for it, read
105
+ * once when the account's visit starts: the baseline the return compares with.
106
+ */
107
+ begin(scope: string): VisitBaseline | null {
108
+ if (scope === this.scope) return this.previous;
109
+ this.flush();
110
+ this.scope = scope;
111
+ this.visit.clear();
112
+ this.saving = false;
113
+ this.previous = this.store.load(scope);
114
+ this.lastPresentAt = this.present ? this.now() : null;
115
+ return this.previous;
116
+ }
117
+
118
+ /** Whether the user is in the app; leaving writes the visit. */
119
+ setPresent(present: boolean): void {
120
+ if (present === this.present) return;
121
+ this.lastPresentAt = this.now();
122
+ this.present = present;
123
+ if (!present) this.flush();
124
+ }
125
+
126
+ /** A price the user has on hand now, for a listing (`instrumentIdentityKey`). */
127
+ observe(key: string, observation: VisitObservation): void {
128
+ if (!this.scope || !this.present) return;
129
+ this.visit.set(key, observation);
130
+ this.lastPresentAt = this.now();
131
+ this.schedule();
132
+ }
133
+
134
+ /** Drops the prices of listings no longer in the user's collections, so the next visit never names them. */
135
+ retain(keys: ReadonlySet<string>): void {
136
+ let changed = false;
137
+ for (const key of this.visit.keys()) {
138
+ if (keys.has(key)) continue;
139
+ this.visit.delete(key);
140
+ changed = true;
141
+ }
142
+ if (changed) this.schedule();
143
+ }
144
+
145
+ /** The return has been compared with the last visit (or had none to compare with): this one may now replace it. */
146
+ allowSaving(): void {
147
+ if (this.saving) return;
148
+ this.saving = true;
149
+ this.schedule();
150
+ }
151
+
152
+ /** Writes the visit now, when it may be written. */
153
+ flush(): void {
154
+ this.saver.cancel();
155
+ this.write();
156
+ }
157
+
158
+ /** Writes what there is and stops: the app is going away. */
159
+ stop(): void {
160
+ this.setPresent(false);
161
+ this.flush();
162
+ }
163
+
164
+ /**
165
+ * Turned off: nothing pending is written, the visit is dropped and every
166
+ * stored one is deleted. The next `begin` starts over.
167
+ */
168
+ forget(): void {
169
+ this.saver.cancel();
170
+ this.pending = false;
171
+ this.visit.clear();
172
+ this.saving = false;
173
+ this.scope = null;
174
+ this.previous = null;
175
+ this.store.clear();
176
+ }
177
+
178
+ private schedule(): void {
179
+ if (!this.saving || !this.scope || this.visit.size === 0 || this.pending) return;
180
+ this.pending = true;
181
+ this.saver.schedule(null);
182
+ }
183
+
184
+ private write(): void {
185
+ this.pending = false;
186
+ if (!this.saving || !this.scope || this.visit.size === 0) return;
187
+ const seenAt = this.present ? this.now() : this.lastPresentAt;
188
+ if (seenAt == null) return;
189
+ this.store.save({ scope: this.scope, seenAt, observations: Object.fromEntries(this.visit) });
190
+ }
191
+ }
package/src/app.tsx CHANGED
@@ -77,6 +77,8 @@ import { isPaneShareHandoff } from "./shares/location";
77
77
  import { apiClient } from "./api-client";
78
78
  import { reportTelemetryConfig } from "./telemetry/live-config";
79
79
  import { AttentionCountsNotice } from "./app/attention-notice";
80
+ import { useSinceLastVisit } from "./app/since-last-visit/use-since-last-visit";
81
+ import { SinceLastVisitStrip } from "./app/since-last-visit/strip";
80
82
  import { recordFunctionOpen } from "./telemetry/usage-counts";
81
83
  import { logFailure } from "./utils/log-failure";
82
84
 
@@ -486,6 +488,17 @@ function AppInner({
486
488
  }
487
489
  }, [focusedTickerSymbol]);
488
490
 
491
+ // What moved in the user's tickers since their last visit: the main window
492
+ // only, never over setup or the sign-in gate, never in presentation mode.
493
+ const sinceLastVisit = useSinceLastVisit({
494
+ active: !appWideWorkElsewhere && !onboardingActive && !signInGateActive,
495
+ marketData,
496
+ pluginState: pluginRegistry.persistence.pluginState,
497
+ pluginsReady,
498
+ notify: notifyRequest,
499
+ });
500
+ const showSinceLastVisit = !!sinceLastVisit.recap && state.config.presentationMode !== true;
501
+
489
502
  const chrome = useAppChromeShown();
490
503
  const keybindingHost = useUiHost().kind === "opentui" ? "terminal" : "desktop";
491
504
  const keybindings = useResolvedKeybindings(state.config.keybindings, keybindingHost);
@@ -547,6 +560,7 @@ function AppInner({
547
560
  onRestartForUpdate={updatesEnabled && !isDetachedWindow ? restartToApplyUpdate : undefined}
548
561
  />
549
562
  )}
563
+ {showSinceLastVisit ? <SinceLastVisitStrip strip={sinceLastVisit} /> : null}
550
564
  <TransientLayoutProvider>
551
565
  <Shell
552
566
  pluginRegistry={pluginRegistry}
@@ -555,6 +569,7 @@ function AppInner({
555
569
  desktopWindowBridge={desktopWindowBridge}
556
570
  desktopDockPreview={desktopDockPreview}
557
571
  commandBarNativeOccluder={commandBarNativeOccluder}
572
+ topBandRows={showSinceLastVisit ? 1 : 0}
558
573
  />
559
574
  <StatusBar />
560
575
  </TransientLayoutProvider>
@@ -177,6 +177,7 @@ import {
177
177
  historyPriceDecimals,
178
178
  historyRolls,
179
179
  historyRows,
180
+ historyTextVolumes,
180
181
  historyUnit,
181
182
  quotedPriceDivisor,
182
183
  withDailyRebuiltBars,
@@ -2334,8 +2335,9 @@ function historyTextColumns(intraday: boolean, price: (value: unknown, row: Reco
2334
2335
  * market's shows it beside the venue, never as its volume, and a bar without
2335
2336
  * volume in a history that reports it prints as missing, never as 0 or blank.
2336
2337
  */
2337
- function historyVolumeCell(missingVolume: (row: Record<string, unknown>) => string) {
2338
- return (value: unknown, row: Record<string, unknown>) => formatCountCell(value)
2338
+ function historyVolumeCell(missingVolume: (row: Record<string, unknown>) => string, shown?: (row: Record<string, unknown>) => number | undefined) {
2339
+ // The newest bars' exact counts print at the step of the rest of the column (historyTextVolumes).
2340
+ return (value: unknown, row: Record<string, unknown>) => formatCountCell(shown?.(row) ?? value)
2339
2341
  || (typeof row.venueVolume === "number"
2340
2342
  ? cliStyles.muted(`${formatCountCell(row.venueVolume)} ${typeof row.volumeVenue === "string" ? row.volumeVenue : ""}`.trim())
2341
2343
  : missingVolume(row));
@@ -2451,8 +2453,9 @@ async function runHistory(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
2451
2453
  const price = historyPrice(history.decimals);
2452
2454
  // A bar without volume in a history that reports it prints as missing.
2453
2455
  const missingVolume = historyReportsVolume(data) ? MISSING_VOLUME_TEXT : "";
2456
+ const textVolumes = historyTextVolumes(data, intraday);
2454
2457
  const textColumns = historyTextColumns(intraday, price).map((column) => column.key !== "volume" ? column
2455
- : { ...column, format: historyVolumeCell(() => missingVolume) });
2458
+ : { ...column, format: historyVolumeCell(() => missingVolume, (row) => textVolumes.get(String(row.date))) });
2456
2459
  // The largest fall from a close to a later one in the bars shown, said under the heading: within one contract
2457
2460
  // of a continuous future, never from one month's close to another's across a roll.
2458
2461
  // A yield (^TNX) falls and rises by its level, in bp, and its largest rise is said too.
@@ -2858,11 +2861,12 @@ async function runHistoryList(
2858
2861
  }
2859
2862
  const decimals = (row: Record<string, unknown>) => bySymbol.get(String(row.symbol))?.decimals ?? 2;
2860
2863
  const intraday = served.some((history) => history.intraday);
2864
+ const textVolumes = new Map(served.map((history) => [history.listing.key, historyTextVolumes(history.data, history.intraday)] as const));
2861
2865
  const textColumns = historyTextColumns(intraday, (value, row) => historyPrice(decimals(row))(value)).map((column) => column.key !== "volume" ? column
2862
2866
  : { ...column, format: historyVolumeCell((row) => {
2863
2867
  const history = bySymbol.get(String(row.symbol));
2864
2868
  return history && row.date && historyReportsVolume(history.data) ? MISSING_VOLUME_TEXT : "";
2865
- }) });
2869
+ }, (row) => textVolumes.get(String(row.symbol))?.get(String(row.date))) });
2866
2870
  ctx.printResult({
2867
2871
  data: rows,
2868
2872
  metadata: {
@@ -6,6 +6,8 @@ import { layoutWindowCounts } from "../../layout/pane-manager/transient";
6
6
  import { builtinPluginGroupMembers } from "../../plugins/ownership";
7
7
  import type { AppConfig, TelemetryConfig } from "../../types/config";
8
8
  import { canonicalTimeZone } from "../../utils/utc-time";
9
+ import type { CsvDecimal } from "../../utils/csv";
10
+ import { parseCsvDecimal } from "../options";
9
11
  import { readBaseCurrency } from "../../utils/base-currency";
10
12
  import { NIGHTLY_CHANNEL_SUMMARY, parseUpdateChannel, withUpdateChannel } from "../../updater/channel";
11
13
  import type { CliCommandDef } from "../../types/plugin";
@@ -40,6 +42,8 @@ const TIMEZONE_CONFIG_KEY = "timezone";
40
42
  const NO_TIMEZONE = "none";
41
43
  /** Stable releases, or nightly builds as well. */
42
44
  const UPDATE_CHANNEL_CONFIG_KEY = "updates.channel";
45
+ /** The decimal mark CSV exports write: a dot, or a comma with `;` between cells. */
46
+ const CSV_DECIMAL_CONFIG_KEY = "csvDecimal";
43
47
  const EDITABLE_CONFIG_KEYS = [
44
48
  "baseCurrency",
45
49
  "refreshIntervalMinutes",
@@ -49,6 +53,7 @@ const EDITABLE_CONFIG_KEYS = [
49
53
  STAR_PROMPT_CONFIG_KEY,
50
54
  TIMEZONE_CONFIG_KEY,
51
55
  UPDATE_CHANNEL_CONFIG_KEY,
56
+ CSV_DECIMAL_CONFIG_KEY,
52
57
  ];
53
58
 
54
59
  function isTelemetryConfigKey(key: string): key is TelemetryConfigKey {
@@ -120,6 +125,16 @@ function describeConfigValue(value: unknown): string {
120
125
  return String(value);
121
126
  }
122
127
 
128
+ /** The config with CSV exports' decimal mark: a comma is saved, the dot is the default and leaves nothing. */
129
+ function withCsvDecimal(config: AppConfig, decimal: CsvDecimal): AppConfig {
130
+ const { csvDecimal: _previous, ...rest } = config;
131
+ return decimal === "comma" ? { ...rest, csvDecimal: "comma" } : rest;
132
+ }
133
+
134
+ function describeCsvDecimal(value: unknown): string {
135
+ return value === "comma" ? "comma: CSV numbers as 17,2, cells split by ;" : "dot: CSV numbers as 17.2, cells split by ,";
136
+ }
137
+
123
138
  function withTimezone(config: AppConfig, timezone: string | null): AppConfig {
124
139
  const { timezone: _previous, ...rest } = config;
125
140
  return timezone ? { ...rest, timezone } : rest;
@@ -253,6 +268,7 @@ export function createSystemCliCommands(): CliCommandDef[] {
253
268
  "config set starPrompt.enabled false",
254
269
  "config set timezone <Region/City>|none",
255
270
  "config set updates.channel stable|nightly",
271
+ "config set csvDecimal comma|dot",
256
272
  "config get keybindings",
257
273
  "config set keybindings.actions.<action> <keys>|null|default",
258
274
  "config set keybindings.commands.<keys> <command>|null",
@@ -265,6 +281,11 @@ export function createSystemCliCommands(): CliCommandDef[] {
265
281
  lines: [
266
282
  "Times print in UTC. timezone takes an IANA zone name such as Asia/Tokyo or America/New_York, and CLI text and function reports then show your local time beside every UTC time. Trading days keep their market's date. none goes back to UTC alone. JSON and CSV keep the raw values.",
267
283
  ],
284
+ }, {
285
+ title: "CSV numbers",
286
+ lines: [
287
+ "CSV exports write numbers with a decimal point, cells split by commas. csvDecimal comma writes 17,2 with cells split by ; for a spreadsheet in a decimal-comma locale (German, French), every CSV the CLI and the app export; --decimal comma or --decimal dot decides for one command. Text and JSON keep the dot, and dates stay ISO.",
288
+ ],
268
289
  }, {
269
290
  title: "Themes",
270
291
  lines: [
@@ -328,6 +349,7 @@ export function createSystemCliCommands(): CliCommandDef[] {
328
349
  [STAR_PROMPT_CONFIG_KEY]: context.config.starPrompt?.enabled !== false,
329
350
  [TIMEZONE_CONFIG_KEY]: context.config.timezone ?? null,
330
351
  [UPDATE_CHANNEL_CONFIG_KEY]: context.config.updates?.channel ?? "stable",
352
+ [CSV_DECIMAL_CONFIG_KEY]: context.config.csvDecimal ?? "dot",
331
353
  };
332
354
 
333
355
  if (action === "list") {
@@ -338,6 +360,7 @@ export function createSystemCliCommands(): CliCommandDef[] {
338
360
  ...(key === KEYBINDINGS_CONFIG_KEY ? { format: summarizeKeybindings } : {}),
339
361
  ...(key === "theme" ? { format: (value: unknown) => describeThemeId(String(value)) } : {}),
340
362
  ...(key === TIMEZONE_CONFIG_KEY ? { format: describeTimezone } : {}),
363
+ ...(key === CSV_DECIMAL_CONFIG_KEY ? { format: describeCsvDecimal } : {}),
341
364
  ...(key === "baseCurrency" ? { format: describeBaseCurrency } : {}),
342
365
  ...(key === "telemetry.attention" ? { format: describeAttentionSetting } : {}),
343
366
  })),
@@ -359,6 +382,7 @@ export function createSystemCliCommands(): CliCommandDef[] {
359
382
  ctx.printResult({ data: { key, value: safeConfig[key] } }, {
360
383
  text: (data) => key === KEYBINDINGS_CONFIG_KEY ? renderKeybindings(data.value)
361
384
  : key === TIMEZONE_CONFIG_KEY ? describeTimezone(data.value)
385
+ : key === CSV_DECIMAL_CONFIG_KEY ? describeCsvDecimal(data.value)
362
386
  : key === "baseCurrency" ? describeBaseCurrency(data.value)
363
387
  : key === "telemetry.attention" ? describeAttentionSetting(data.value) : describeConfigValue(data.value),
364
388
  });
@@ -404,6 +428,8 @@ export function createSystemCliCommands(): CliCommandDef[] {
404
428
  ? parseTimezoneSetting(value)
405
429
  : key === UPDATE_CHANNEL_CONFIG_KEY
406
430
  ? parseUpdateChannel(value)
431
+ : key === CSV_DECIMAL_CONFIG_KEY
432
+ ? parseCsvDecimal(value, `config set ${CSV_DECIMAL_CONFIG_KEY}`)
407
433
  : key === "refreshIntervalMinutes"
408
434
  ? Number(value)
409
435
  : isBooleanConfigKey(key)
@@ -417,7 +443,9 @@ export function createSystemCliCommands(): CliCommandDef[] {
417
443
  ? withTimezone(context.config, parsedValue as string | null)
418
444
  : key === UPDATE_CHANNEL_CONFIG_KEY
419
445
  ? withUpdateChannel(context.config, parsedValue as "stable" | "nightly")
420
- : { ...context.config, [key]: parsedValue };
446
+ : key === CSV_DECIMAL_CONFIG_KEY
447
+ ? withCsvDecimal(context.config, parsedValue as CsvDecimal)
448
+ : { ...context.config, [key]: parsedValue };
421
449
  if (!ctx.cliOptions.dryRun) await saveConfig(nextConfig);
422
450
  ctx.printResult({
423
451
  data: {