gloomberb 0.2.0 → 0.3.2

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 (311) hide show
  1. package/README.md +20 -19
  2. package/bin/gloomberb +3 -0
  3. package/package.json +5 -4
  4. package/patches/@opentui%2Fcore@0.1.90.patch +356 -0
  5. package/src/app.tsx +1365 -0
  6. package/src/brokers/sync-broker-instance.test.ts +100 -0
  7. package/src/brokers/sync-broker-instance.ts +341 -0
  8. package/src/cli/commands/plugins.ts +173 -0
  9. package/src/cli/commands/portfolio.ts +210 -0
  10. package/src/cli/commands/search.ts +120 -0
  11. package/src/cli/commands/ticker.ts +375 -0
  12. package/src/cli/commands/watchlist.ts +210 -0
  13. package/src/cli/context.ts +62 -0
  14. package/src/cli/errors.ts +13 -0
  15. package/src/cli/helpers.ts +85 -0
  16. package/src/cli/index.ts +143 -0
  17. package/src/cli/ticker-resolution.ts +39 -0
  18. package/src/cli/types.ts +15 -0
  19. package/src/cli.test.ts +361 -0
  20. package/src/components/chart/chart-data.ts +239 -0
  21. package/src/components/chart/chart-renderer.ts +1199 -0
  22. package/src/components/chart/chart-types.ts +82 -0
  23. package/src/components/chart/chart-viewport.ts +21 -0
  24. package/src/components/chart/chart.test.ts +439 -0
  25. package/src/components/chart/comparison-chart-data.test.ts +109 -0
  26. package/src/components/chart/comparison-chart-data.ts +316 -0
  27. package/src/components/chart/comparison-chart-renderer.test.ts +84 -0
  28. package/src/components/chart/comparison-chart-renderer.ts +354 -0
  29. package/src/components/chart/comparison-stock-chart.tsx +1486 -0
  30. package/src/components/chart/cursor-motion.ts +48 -0
  31. package/src/components/chart/native/chart-rasterizer.ts +732 -0
  32. package/src/components/chart/native/kitty-adapter.ts +12 -0
  33. package/src/components/chart/native/kitty-manager.ts +142 -0
  34. package/src/components/chart/native/kitty-protocol.ts +110 -0
  35. package/src/components/chart/native/kitty-support.ts +71 -0
  36. package/src/components/chart/native/kitty.test.ts +620 -0
  37. package/src/components/chart/native/renderer-selection.ts +24 -0
  38. package/src/components/chart/native/surface-manager.ts +225 -0
  39. package/src/components/chart/native/surface-sync.ts +34 -0
  40. package/src/components/chart/stock-chart-renderer-switch.test.tsx +165 -0
  41. package/src/components/chart/stock-chart.test.ts +107 -0
  42. package/src/components/chart/stock-chart.tsx +1556 -0
  43. package/src/components/command-bar/__snapshots__/command-bar.test.tsx.snap +137 -0
  44. package/src/components/command-bar/command-bar.test.tsx +1546 -0
  45. package/src/components/command-bar/command-bar.tsx +4841 -0
  46. package/src/components/command-bar/command-registry.ts +269 -0
  47. package/src/components/command-bar/helpers.test.ts +224 -0
  48. package/src/components/command-bar/helpers.ts +371 -0
  49. package/src/components/command-bar/root-shortcuts.ts +158 -0
  50. package/src/components/command-bar/view-model.test.ts +152 -0
  51. package/src/components/command-bar/view-model.ts +185 -0
  52. package/src/components/command-bar/workflow-ops.test.ts +70 -0
  53. package/src/components/command-bar/workflow-ops.ts +433 -0
  54. package/src/components/command-bar/workflow-types.ts +127 -0
  55. package/src/components/detail-feed-view.test.tsx +105 -0
  56. package/src/components/detail-feed-view.tsx +295 -0
  57. package/src/components/index.ts +32 -0
  58. package/src/components/layout/floating-pane.tsx +49 -0
  59. package/src/components/layout/header.tsx +151 -0
  60. package/src/components/layout/pane-header.tsx +44 -0
  61. package/src/components/layout/pane.tsx +49 -0
  62. package/src/components/layout/pixel-mouse-mode.test.ts +122 -0
  63. package/src/components/layout/pixel-mouse.test.ts +40 -0
  64. package/src/components/layout/shell.test.tsx +651 -0
  65. package/src/components/layout/shell.tsx +1200 -0
  66. package/src/components/layout/status-bar.test.tsx +173 -0
  67. package/src/components/layout/status-bar.tsx +138 -0
  68. package/src/components/markdown-editor.tsx +134 -0
  69. package/src/components/markdown-text.tsx +218 -0
  70. package/src/components/onboarding/onboarding-wizard.test.tsx +184 -0
  71. package/src/components/onboarding/onboarding-wizard.tsx +1365 -0
  72. package/src/components/pane-settings-dialog.tsx +468 -0
  73. package/src/components/pane-template-wizard.test.tsx +52 -0
  74. package/src/components/pane-template-wizard.tsx +199 -0
  75. package/src/components/price-selector-dialog.tsx +195 -0
  76. package/src/components/spinner.tsx +2 -0
  77. package/src/components/tab-bar.tsx +17 -0
  78. package/src/components/ticker-badge-text.test.tsx +160 -0
  79. package/src/components/ticker-badge-text.tsx +58 -0
  80. package/src/components/ticker-badge.tsx +88 -0
  81. package/src/components/ticker-list-table.tsx +188 -0
  82. package/src/components/toggle-list.tsx +74 -0
  83. package/src/components/ui/button.tsx +77 -0
  84. package/src/components/ui/data-table.tsx +210 -0
  85. package/src/components/ui/external-link.tsx +22 -0
  86. package/src/components/ui/fields.tsx +187 -0
  87. package/src/components/ui/frame.tsx +73 -0
  88. package/src/components/ui/index.ts +53 -0
  89. package/src/components/ui/list-view.tsx +166 -0
  90. package/src/components/ui/loading.tsx +70 -0
  91. package/src/components/ui/status.tsx +83 -0
  92. package/src/components/ui/tabs.tsx +47 -0
  93. package/src/components/ui/toggle.tsx +164 -0
  94. package/src/components/ui/ui.test.tsx +134 -0
  95. package/src/data/app-persistence.ts +25 -0
  96. package/src/data/config-store.test.ts +347 -0
  97. package/src/data/config-store.ts +507 -0
  98. package/src/data/plugin-state-store.ts +102 -0
  99. package/src/data/resource-store.ts +323 -0
  100. package/src/data/session-store.ts +52 -0
  101. package/src/data/sqlite-cache.test.ts +103 -0
  102. package/src/data/sqlite-database.ts +62 -0
  103. package/src/data/sqlite-json.ts +19 -0
  104. package/src/data/ticker-repository.ts +45 -0
  105. package/src/data/ticker-store.ts +46 -0
  106. package/src/index.tsx +67 -0
  107. package/src/market-data/coordinator.test.ts +369 -0
  108. package/src/market-data/coordinator.ts +580 -0
  109. package/src/market-data/hooks.tsx +234 -0
  110. package/src/market-data/query-store.ts +28 -0
  111. package/src/market-data/request-types.test.ts +64 -0
  112. package/src/market-data/request-types.ts +70 -0
  113. package/src/market-data/result-types.ts +56 -0
  114. package/src/market-data/selectors.ts +166 -0
  115. package/src/market-data/trace.ts +7 -0
  116. package/src/pane-settings.test.ts +55 -0
  117. package/src/pane-settings.ts +73 -0
  118. package/src/plugins/builtin/ai/ask-ai-detail-tab.tsx +350 -0
  119. package/src/plugins/builtin/ai/gloomberb-cli.ts +70 -0
  120. package/src/plugins/builtin/ai/index.test.tsx +139 -0
  121. package/src/plugins/builtin/ai/index.tsx +86 -0
  122. package/src/plugins/builtin/ai/providers.ts +99 -0
  123. package/src/plugins/builtin/ai/runner.ts +82 -0
  124. package/src/plugins/builtin/ai/screener-contract.test.ts +117 -0
  125. package/src/plugins/builtin/ai/screener-contract.ts +174 -0
  126. package/src/plugins/builtin/ai/screener-pane.test.tsx +365 -0
  127. package/src/plugins/builtin/ai/screener-pane.tsx +1161 -0
  128. package/src/plugins/builtin/ai/settings.ts +79 -0
  129. package/src/plugins/builtin/ai/ticker-context.ts +64 -0
  130. package/src/plugins/builtin/ai/utils.ts +71 -0
  131. package/src/plugins/builtin/ask-ai.test.tsx +258 -0
  132. package/src/plugins/builtin/ask-ai.tsx +9 -0
  133. package/src/plugins/builtin/chat-controller.test.ts +217 -0
  134. package/src/plugins/builtin/chat-controller.ts +340 -0
  135. package/src/plugins/builtin/chat.test.tsx +451 -0
  136. package/src/plugins/builtin/chat.tsx +620 -0
  137. package/src/plugins/builtin/comparison-chart.test.tsx +277 -0
  138. package/src/plugins/builtin/comparison-chart.tsx +169 -0
  139. package/src/plugins/builtin/data-providers.ts +16 -0
  140. package/src/plugins/builtin/debug.tsx +351 -0
  141. package/src/plugins/builtin/help.test.tsx +110 -0
  142. package/src/plugins/builtin/help.tsx +281 -0
  143. package/src/plugins/builtin/layout-manager.tsx +264 -0
  144. package/src/plugins/builtin/manual-entry.tsx +25 -0
  145. package/src/plugins/builtin/news.tsx +143 -0
  146. package/src/plugins/builtin/notes-files.ts +58 -0
  147. package/src/plugins/builtin/notes.tsx +396 -0
  148. package/src/plugins/builtin/options-availability.test.tsx +179 -0
  149. package/src/plugins/builtin/options-availability.ts +158 -0
  150. package/src/plugins/builtin/options.tsx +364 -0
  151. package/src/plugins/builtin/portfolio-list/header.tsx +227 -0
  152. package/src/plugins/builtin/portfolio-list/index.tsx +99 -0
  153. package/src/plugins/builtin/portfolio-list/metrics.ts +460 -0
  154. package/src/plugins/builtin/portfolio-list/pane.tsx +533 -0
  155. package/src/plugins/builtin/portfolio-list/settings.ts +270 -0
  156. package/src/plugins/builtin/portfolio-list/summary.tsx +270 -0
  157. package/src/plugins/builtin/portfolio-list/table.tsx +64 -0
  158. package/src/plugins/builtin/portfolio-list.test.ts +74 -0
  159. package/src/plugins/builtin/portfolio-list.test.tsx +1164 -0
  160. package/src/plugins/builtin/portfolio-metrics.test.ts +224 -0
  161. package/src/plugins/builtin/quote-monitor.test.tsx +114 -0
  162. package/src/plugins/builtin/sec.tsx +250 -0
  163. package/src/plugins/builtin/ticker-detail/chart-tab.tsx +43 -0
  164. package/src/plugins/builtin/ticker-detail/financials-tab.tsx +390 -0
  165. package/src/plugins/builtin/ticker-detail/index.tsx +80 -0
  166. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +242 -0
  167. package/src/plugins/builtin/ticker-detail/pane.tsx +183 -0
  168. package/src/plugins/builtin/ticker-detail/quote-monitor.tsx +83 -0
  169. package/src/plugins/builtin/ticker-detail/settings.ts +132 -0
  170. package/src/plugins/builtin/ticker-detail-chart-tab-switch.test.tsx +193 -0
  171. package/src/plugins/builtin/ticker-detail.test.tsx +578 -0
  172. package/src/plugins/builtin/yahoo.ts +18 -0
  173. package/src/plugins/event-bus.ts +37 -0
  174. package/src/plugins/ibkr/__snapshots__/trade-tab.test.tsx.snap +35 -0
  175. package/src/plugins/ibkr/account-cache.test.ts +101 -0
  176. package/src/plugins/ibkr/account-cache.ts +137 -0
  177. package/src/plugins/ibkr/broker-adapter.ts +168 -0
  178. package/src/plugins/ibkr/config.test.ts +68 -0
  179. package/src/plugins/ibkr/config.ts +262 -0
  180. package/src/plugins/ibkr/dialogs.tsx +83 -0
  181. package/src/plugins/ibkr/flex.test.ts +107 -0
  182. package/src/plugins/ibkr/flex.ts +267 -0
  183. package/src/plugins/ibkr/fundamental-parser.ts +149 -0
  184. package/src/plugins/ibkr/gateway-helpers.ts +28 -0
  185. package/src/plugins/ibkr/gateway-selection.ts +51 -0
  186. package/src/plugins/ibkr/gateway-service.test.ts +450 -0
  187. package/src/plugins/ibkr/gateway-service.ts +2228 -0
  188. package/src/plugins/ibkr/index.test.tsx +183 -0
  189. package/src/plugins/ibkr/index.tsx +153 -0
  190. package/src/plugins/ibkr/instance-selection.test.ts +121 -0
  191. package/src/plugins/ibkr/instance-selection.ts +36 -0
  192. package/src/plugins/ibkr/price-normalization.test.ts +38 -0
  193. package/src/plugins/ibkr/price-normalization.ts +59 -0
  194. package/src/plugins/ibkr/trade-badge.tsx +27 -0
  195. package/src/plugins/ibkr/trade-tab.test.tsx +225 -0
  196. package/src/plugins/ibkr/trade-tab.tsx +1050 -0
  197. package/src/plugins/ibkr/trade-utils.test.ts +175 -0
  198. package/src/plugins/ibkr/trade-utils.ts +149 -0
  199. package/src/plugins/ibkr/trading-pane.tsx +438 -0
  200. package/src/plugins/ibkr/trading-state.test.ts +109 -0
  201. package/src/plugins/ibkr/trading-state.ts +339 -0
  202. package/src/plugins/loader.ts +71 -0
  203. package/src/plugins/pane-manager.test.ts +103 -0
  204. package/src/plugins/pane-manager.ts +974 -0
  205. package/src/plugins/plugin-persistence.ts +85 -0
  206. package/src/plugins/plugin-runtime.test.tsx +185 -0
  207. package/src/plugins/plugin-runtime.tsx +175 -0
  208. package/src/plugins/prediction-markets/cache.ts +114 -0
  209. package/src/plugins/prediction-markets/categories.ts +223 -0
  210. package/src/plugins/prediction-markets/chart.tsx +512 -0
  211. package/src/plugins/prediction-markets/columns.ts +133 -0
  212. package/src/plugins/prediction-markets/controller-data.ts +614 -0
  213. package/src/plugins/prediction-markets/controller.ts +725 -0
  214. package/src/plugins/prediction-markets/detail/book.tsx +118 -0
  215. package/src/plugins/prediction-markets/detail/outcomes.tsx +102 -0
  216. package/src/plugins/prediction-markets/detail/overview.tsx +73 -0
  217. package/src/plugins/prediction-markets/detail/pane.tsx +308 -0
  218. package/src/plugins/prediction-markets/detail/rules.tsx +16 -0
  219. package/src/plugins/prediction-markets/detail/shared.tsx +29 -0
  220. package/src/plugins/prediction-markets/detail/trades.tsx +30 -0
  221. package/src/plugins/prediction-markets/detail.test.tsx +47 -0
  222. package/src/plugins/prediction-markets/index.tsx +102 -0
  223. package/src/plugins/prediction-markets/keyboard.ts +64 -0
  224. package/src/plugins/prediction-markets/launch.test.ts +126 -0
  225. package/src/plugins/prediction-markets/launch.ts +240 -0
  226. package/src/plugins/prediction-markets/metrics.ts +311 -0
  227. package/src/plugins/prediction-markets/navigation.ts +90 -0
  228. package/src/plugins/prediction-markets/outcome-order.ts +19 -0
  229. package/src/plugins/prediction-markets/pane.test.tsx +425 -0
  230. package/src/plugins/prediction-markets/pane.tsx +294 -0
  231. package/src/plugins/prediction-markets/plugin.test.tsx +570 -0
  232. package/src/plugins/prediction-markets/rows.ts +229 -0
  233. package/src/plugins/prediction-markets/services/fetch.ts +97 -0
  234. package/src/plugins/prediction-markets/services/kalshi-adapter.ts +555 -0
  235. package/src/plugins/prediction-markets/services/polymarket-adapter.ts +660 -0
  236. package/src/plugins/prediction-markets/services/polymarket-ws.ts +108 -0
  237. package/src/plugins/prediction-markets/settings.ts +164 -0
  238. package/src/plugins/prediction-markets/status.ts +24 -0
  239. package/src/plugins/prediction-markets/table.tsx +84 -0
  240. package/src/plugins/prediction-markets/test-helpers.tsx +636 -0
  241. package/src/plugins/prediction-markets/types.ts +186 -0
  242. package/src/plugins/registry.ts +633 -0
  243. package/src/sources/exchange-rates.ts +18 -0
  244. package/src/sources/gloomberb-cloud.test.ts +199 -0
  245. package/src/sources/gloomberb-cloud.ts +326 -0
  246. package/src/sources/provider-errors.ts +19 -0
  247. package/src/sources/provider-router.test.ts +1476 -0
  248. package/src/sources/provider-router.ts +1405 -0
  249. package/src/sources/sec-edgar.test.ts +286 -0
  250. package/src/sources/sec-edgar.ts +526 -0
  251. package/src/sources/yahoo-finance.test.ts +14 -0
  252. package/src/sources/yahoo-finance.ts +1017 -0
  253. package/src/state/app-activity.test.ts +41 -0
  254. package/src/state/app-activity.ts +106 -0
  255. package/src/state/app-bootstrap.test.ts +471 -0
  256. package/src/state/app-bootstrap.ts +308 -0
  257. package/src/state/app-context.test.ts +406 -0
  258. package/src/state/app-context.test.tsx +162 -0
  259. package/src/state/app-context.tsx +981 -0
  260. package/src/state/selectors.ts +67 -0
  261. package/src/state/session-persistence.test.ts +128 -0
  262. package/src/state/session-persistence.ts +161 -0
  263. package/src/state/ticker-refresh-queue.test.ts +46 -0
  264. package/src/state/ticker-refresh-queue.ts +40 -0
  265. package/src/state/use-inline-tickers.ts +174 -0
  266. package/src/state/use-quote-streaming.test.ts +37 -0
  267. package/src/state/use-quote-streaming.test.tsx +70 -0
  268. package/src/state/use-quote-streaming.ts +80 -0
  269. package/src/state/use-session-snapshot.ts +84 -0
  270. package/src/test-support/data-provider.ts +22 -0
  271. package/src/theme/color-utils.ts +67 -0
  272. package/src/theme/colors.ts +128 -0
  273. package/src/theme/themes.test.ts +45 -0
  274. package/src/theme/themes.ts +491 -0
  275. package/src/types/broker.ts +105 -0
  276. package/src/types/config.ts +444 -0
  277. package/src/types/data-provider.ts +81 -0
  278. package/src/types/financials.ts +142 -0
  279. package/src/types/instrument.ts +29 -0
  280. package/src/types/persistence.ts +21 -0
  281. package/src/types/plugin.ts +354 -0
  282. package/src/types/ticker.ts +58 -0
  283. package/src/types/trading.ts +85 -0
  284. package/src/updater.test.ts +282 -0
  285. package/src/updater.ts +303 -0
  286. package/src/utils/api-client.ts +666 -0
  287. package/src/utils/ascii-chart.ts +172 -0
  288. package/src/utils/broker-instances.ts +47 -0
  289. package/src/utils/cli-output.ts +83 -0
  290. package/src/utils/currency-units.test.ts +49 -0
  291. package/src/utils/currency-units.ts +82 -0
  292. package/src/utils/debug-log.ts +133 -0
  293. package/src/utils/exchange-rate-map.ts +8 -0
  294. package/src/utils/format.ts +158 -0
  295. package/src/utils/fuzzy-search.ts +34 -0
  296. package/src/utils/market-status.ts +95 -0
  297. package/src/utils/options.ts +86 -0
  298. package/src/utils/price-history.ts +39 -0
  299. package/src/utils/quote-time.test.ts +22 -0
  300. package/src/utils/quote-time.ts +50 -0
  301. package/src/utils/sec.test.ts +55 -0
  302. package/src/utils/sec.ts +45 -0
  303. package/src/utils/ticker-list.test.ts +22 -0
  304. package/src/utils/ticker-list.ts +35 -0
  305. package/src/utils/ticker-metadata.ts +51 -0
  306. package/src/utils/ticker-search.test.ts +227 -0
  307. package/src/utils/ticker-search.ts +764 -0
  308. package/src/utils/ticker-tokenizer.test.ts +48 -0
  309. package/src/utils/ticker-tokenizer.ts +72 -0
  310. package/src/version.ts +1 -0
  311. package/install.mjs +0 -68
@@ -0,0 +1,340 @@
1
+ import type { PluginPersistence, PluginResumeState } from "../../types/plugin";
2
+ import { apiClient, type ChatMessage, type PersistedAuthUser } from "../../utils/api-client";
3
+
4
+ const SESSION_STATE_KEY = "session";
5
+ const CHANNEL_STATE_KEY = "channel:everyone";
6
+ const TRANSCRIPT_KIND = "channel-transcript";
7
+ const TRANSCRIPT_SOURCE = "server";
8
+ const MAX_CACHED_MESSAGES = 50;
9
+ const SESSION_SCHEMA_VERSION = 1;
10
+ const CHANNEL_SCHEMA_VERSION = 1;
11
+ const TRANSCRIPT_SCHEMA_VERSION = 1;
12
+ const TRANSCRIPT_CACHE_POLICY = {
13
+ staleMs: 30 * 24 * 60 * 60_000,
14
+ expireMs: 90 * 24 * 60 * 60_000,
15
+ };
16
+ const VERIFICATION_POLL_MS = 5_000;
17
+
18
+ interface PersistedSessionState {
19
+ sessionToken: string | null;
20
+ websocketToken?: string | null;
21
+ user: PersistedAuthUser | null;
22
+ }
23
+
24
+ interface PersistedChannelState {
25
+ draft: string;
26
+ replyToId: string | null;
27
+ lastCursor: string | null;
28
+ }
29
+
30
+ interface PersistedTranscript {
31
+ messages: ChatMessage[];
32
+ }
33
+
34
+ export interface ChatControllerSnapshot {
35
+ loading: boolean;
36
+ hasSavedSession: boolean;
37
+ user: { id: string; username: string; emailVerified: boolean } | null;
38
+ messages: ChatMessage[];
39
+ draft: string;
40
+ replyToId: string | null;
41
+ }
42
+
43
+ type ChatConnection = { send: (content: string, replyToId?: string) => void; close: () => void };
44
+
45
+ export class ChatController {
46
+ private persistence: PluginPersistence | null = null;
47
+ private resume: PluginResumeState | null = null;
48
+ private appActive = true;
49
+ private hydrated = false;
50
+ private sessionChecked = false;
51
+ private user: { id: string; username: string; emailVerified: boolean } | null = null;
52
+ private messages: ChatMessage[] = [];
53
+ private draft = "";
54
+ private replyToId: string | null = null;
55
+ private lastCursor: string | null = null;
56
+ private wsConnection: ChatConnection | null = null;
57
+ private wsConnected = false;
58
+ private verificationPollTimer: ReturnType<typeof setInterval> | null = null;
59
+ private listeners = new Set<(snapshot: ChatControllerSnapshot) => void>();
60
+
61
+ attachPersistence(persistence: PluginPersistence, resume?: PluginResumeState): void {
62
+ this.persistence = persistence;
63
+ this.resume = resume ?? this.resume;
64
+ this.hydrate();
65
+ }
66
+
67
+ hydrate(): void {
68
+ if (this.hydrated || !this.persistence) return;
69
+ this.hydrated = true;
70
+
71
+ const session = this.resume?.getState<PersistedSessionState>(SESSION_STATE_KEY, {
72
+ schemaVersion: SESSION_SCHEMA_VERSION,
73
+ }) ?? this.persistence.getState<PersistedSessionState>(SESSION_STATE_KEY, {
74
+ schemaVersion: SESSION_SCHEMA_VERSION,
75
+ });
76
+ apiClient.setSessionToken(session?.sessionToken ?? null);
77
+ apiClient.setWebSocketToken(session?.websocketToken ?? null);
78
+ apiClient.restoreCachedUser(session?.user ?? null);
79
+ this.user = session?.user
80
+ ? {
81
+ id: session.user.id,
82
+ username: session.user.username ?? session.user.name ?? "account",
83
+ emailVerified: session.user.emailVerified === true,
84
+ }
85
+ : null;
86
+ this.sessionChecked = true;
87
+
88
+ const channel = this.resume?.getState<PersistedChannelState>(CHANNEL_STATE_KEY, {
89
+ schemaVersion: CHANNEL_SCHEMA_VERSION,
90
+ }) ?? this.persistence.getState<PersistedChannelState>(CHANNEL_STATE_KEY, {
91
+ schemaVersion: CHANNEL_SCHEMA_VERSION,
92
+ });
93
+ this.draft = channel?.draft ?? "";
94
+ this.replyToId = channel?.replyToId ?? null;
95
+ this.lastCursor = channel?.lastCursor ?? null;
96
+
97
+ const transcript = this.persistence.getResource<PersistedTranscript>(TRANSCRIPT_KIND, "everyone", {
98
+ sourceKey: TRANSCRIPT_SOURCE,
99
+ schemaVersion: TRANSCRIPT_SCHEMA_VERSION,
100
+ allowExpired: true,
101
+ });
102
+ this.messages = transcript?.value.messages ?? [];
103
+ this.syncVerificationPolling();
104
+ }
105
+
106
+ subscribe(listener: (snapshot: ChatControllerSnapshot) => void): () => void {
107
+ this.listeners.add(listener);
108
+ listener(this.getSnapshot());
109
+ return () => {
110
+ this.listeners.delete(listener);
111
+ };
112
+ }
113
+
114
+ getSnapshot(): ChatControllerSnapshot {
115
+ return {
116
+ loading: !this.sessionChecked,
117
+ hasSavedSession: !!apiClient.getSessionToken(),
118
+ user: this.user,
119
+ messages: [...this.messages],
120
+ draft: this.draft,
121
+ replyToId: this.replyToId,
122
+ };
123
+ }
124
+
125
+ async refreshSession(): Promise<void> {
126
+ const token = apiClient.getSessionToken();
127
+ if (!token) {
128
+ this.stopVerificationPolling();
129
+ this.user = null;
130
+ this.sessionChecked = true;
131
+ this.persistSession();
132
+ this.emit();
133
+ return;
134
+ }
135
+
136
+ const session = await apiClient.getSession();
137
+ const nextUser = session
138
+ ? { id: session.id, username: session.username ?? session.name, emailVerified: !!session.emailVerified }
139
+ : null;
140
+ this.user = nextUser;
141
+ this.sessionChecked = true;
142
+ this.persistSession();
143
+ this.emit();
144
+
145
+ if (nextUser?.emailVerified) {
146
+ this.stopVerificationPolling();
147
+ this.ensureConnection();
148
+ return;
149
+ }
150
+
151
+ this.syncVerificationPolling();
152
+ this.wsConnection?.close();
153
+ this.wsConnection = null;
154
+ this.wsConnected = false;
155
+ if (!nextUser) {
156
+ this.stopVerificationPolling();
157
+ this.reset(true);
158
+ }
159
+ }
160
+
161
+ setDraft(draft: string): void {
162
+ this.draft = draft;
163
+ this.persistChannelState();
164
+ this.emit();
165
+ }
166
+
167
+ setReplyToId(replyToId: string | null): void {
168
+ this.replyToId = replyToId;
169
+ this.persistChannelState();
170
+ this.emit();
171
+ }
172
+
173
+ clearSession(): void {
174
+ this.stopVerificationPolling();
175
+ this.wsConnection?.close();
176
+ this.wsConnection = null;
177
+ this.wsConnected = false;
178
+ this.user = null;
179
+ this.sessionChecked = false;
180
+ this.emit();
181
+ }
182
+
183
+ setAppActive(appActive: boolean): void {
184
+ if (this.appActive === appActive) return;
185
+ this.appActive = appActive;
186
+ if (!appActive) {
187
+ this.stopVerificationPolling();
188
+ return;
189
+ }
190
+ this.syncVerificationPolling();
191
+ }
192
+
193
+ reset(clearSession = false): void {
194
+ this.stopVerificationPolling();
195
+ this.wsConnection?.close();
196
+ this.wsConnection = null;
197
+ this.wsConnected = false;
198
+ this.messages = [];
199
+ this.draft = "";
200
+ this.replyToId = null;
201
+ this.lastCursor = null;
202
+ if (clearSession) {
203
+ this.user = null;
204
+ apiClient.setSessionToken(null);
205
+ this.persistence?.deleteState(SESSION_STATE_KEY);
206
+ } else {
207
+ this.persistSession();
208
+ }
209
+ this.persistence?.deleteResource(TRANSCRIPT_KIND, "everyone", { sourceKey: TRANSCRIPT_SOURCE });
210
+ this.persistChannelState();
211
+ this.emit();
212
+ }
213
+
214
+ send(content: string, replyToId?: string): void {
215
+ this.wsConnection?.send(content, replyToId);
216
+ this.setDraft("");
217
+ this.setReplyToId(null);
218
+ }
219
+
220
+ ensureConnection(): void {
221
+ if (this.wsConnected || !this.user?.emailVerified || !apiClient.getSessionToken()) return;
222
+ this.wsConnected = true;
223
+
224
+ apiClient.getMessages("everyone", {
225
+ limit: MAX_CACHED_MESSAGES,
226
+ after: this.lastCursor ?? undefined,
227
+ }).then((messages) => {
228
+ if (messages.length > 0) {
229
+ this.mergeMessages(messages);
230
+ return;
231
+ }
232
+ this.persistChannelState();
233
+ }).catch(async () => {
234
+ try {
235
+ const messages = await apiClient.getMessages("everyone", { limit: MAX_CACHED_MESSAGES });
236
+ this.mergeMessages(messages);
237
+ } catch {
238
+ // keep local transcript
239
+ }
240
+ });
241
+
242
+ this.wsConnection = apiClient.connectChannel(
243
+ "everyone",
244
+ (message) => {
245
+ if (this.messages.some((entry) => entry.id === message.id)) return;
246
+ this.mergeMessages([message]);
247
+ },
248
+ () => {
249
+ this.wsConnected = false;
250
+ },
251
+ );
252
+ }
253
+
254
+ private emit(): void {
255
+ const snapshot = this.getSnapshot();
256
+ for (const listener of this.listeners) {
257
+ try {
258
+ listener(snapshot);
259
+ } catch {
260
+ // ignore subscriber errors
261
+ }
262
+ }
263
+ }
264
+
265
+ private syncVerificationPolling(): void {
266
+ if (!this.appActive || !apiClient.getSessionToken() || !this.user || this.user.emailVerified) {
267
+ this.stopVerificationPolling();
268
+ return;
269
+ }
270
+ if (this.verificationPollTimer) return;
271
+ this.verificationPollTimer = setInterval(() => {
272
+ void this.refreshSession().catch(() => {});
273
+ }, VERIFICATION_POLL_MS);
274
+ }
275
+
276
+ private stopVerificationPolling(): void {
277
+ if (!this.verificationPollTimer) return;
278
+ clearInterval(this.verificationPollTimer);
279
+ this.verificationPollTimer = null;
280
+ }
281
+
282
+ private mergeMessages(messages: ChatMessage[]): void {
283
+ const merged = new Map<string, ChatMessage>();
284
+ for (const message of this.messages) merged.set(message.id, message);
285
+ for (const message of messages) merged.set(message.id, message);
286
+ this.messages = [...merged.values()]
287
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
288
+ .slice(-MAX_CACHED_MESSAGES);
289
+ this.lastCursor = this.messages[this.messages.length - 1]?.createdAt ?? this.lastCursor;
290
+ this.persistTranscript();
291
+ this.emit();
292
+ }
293
+
294
+ private persistSession(): void {
295
+ const value = {
296
+ sessionToken: apiClient.getSessionToken(),
297
+ websocketToken: apiClient.getWebSocketToken(),
298
+ user: this.user,
299
+ } satisfies PersistedSessionState;
300
+ this.resume?.setState(SESSION_STATE_KEY, value, {
301
+ schemaVersion: SESSION_SCHEMA_VERSION,
302
+ });
303
+ this.persistence?.setState(SESSION_STATE_KEY, value, {
304
+ schemaVersion: SESSION_SCHEMA_VERSION,
305
+ });
306
+ }
307
+
308
+ private persistChannelState(): void {
309
+ const value = {
310
+ draft: this.draft,
311
+ replyToId: this.replyToId,
312
+ lastCursor: this.lastCursor,
313
+ } satisfies PersistedChannelState;
314
+ this.resume?.setState(CHANNEL_STATE_KEY, value, {
315
+ schemaVersion: CHANNEL_SCHEMA_VERSION,
316
+ });
317
+ this.persistence?.setState(CHANNEL_STATE_KEY, value, {
318
+ schemaVersion: CHANNEL_SCHEMA_VERSION,
319
+ });
320
+ }
321
+
322
+ private persistTranscript(): void {
323
+ if (this.messages.length === 0) {
324
+ this.persistence?.deleteResource(TRANSCRIPT_KIND, "everyone", { sourceKey: TRANSCRIPT_SOURCE });
325
+ this.persistChannelState();
326
+ return;
327
+ }
328
+
329
+ this.persistence?.setResource(TRANSCRIPT_KIND, "everyone", {
330
+ messages: this.messages,
331
+ } satisfies PersistedTranscript, {
332
+ sourceKey: TRANSCRIPT_SOURCE,
333
+ schemaVersion: TRANSCRIPT_SCHEMA_VERSION,
334
+ cachePolicy: TRANSCRIPT_CACHE_POLICY,
335
+ });
336
+ this.persistChannelState();
337
+ }
338
+ }
339
+
340
+ export const chatController = new ChatController();