khal-os 1.260324.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 (408) hide show
  1. package/.env.example +23 -0
  2. package/.genie/mailbox/cli-sent.jsonl +3 -0
  3. package/.genie/mailbox/ds1-wave2-engineer-1.json +15 -0
  4. package/.genie/mailbox/ds1-wave2-engineer-2.json +15 -0
  5. package/.genie/mailbox/ds1-wave2-engineer-3.json +15 -0
  6. package/.genie/state/os-observability.json +39 -0
  7. package/.genie/state/tmux-control-mode-terminal.json +28 -0
  8. package/.genie/wishes/genieos-one-theme/WISH.md +417 -0
  9. package/.genie/wishes/workos-prod-rbac/WISH.md +345 -0
  10. package/.github/workflows/ci.yml +39 -0
  11. package/.github/workflows/release.yml +78 -0
  12. package/.github/workflows/version.yml +122 -0
  13. package/.husky/pre-commit +1 -0
  14. package/.pnpm-approve-builds.json +1 -0
  15. package/CLAUDE.md +117 -0
  16. package/LICENSE +21 -0
  17. package/README.md +38 -0
  18. package/biome.json +124 -0
  19. package/bun.lock +1249 -0
  20. package/docs/workos-setup.md +116 -0
  21. package/ecosystem.config.cjs +26 -0
  22. package/instrumentation.ts +8 -0
  23. package/knip.json +35 -0
  24. package/nats.conf +7 -0
  25. package/next.config.ts +25 -0
  26. package/package.json +78 -0
  27. package/packages/dev3000-app/components.ts +12 -0
  28. package/packages/dev3000-app/manifest.ts +19 -0
  29. package/packages/dev3000-app/package.json +23 -0
  30. package/packages/dev3000-app/views/dev3000/Dev3000App.tsx +758 -0
  31. package/packages/dev3000-app/views/dev3000/ErrorsPanel.tsx +160 -0
  32. package/packages/dev3000-app/views/dev3000/dev3000-context.tsx +21 -0
  33. package/packages/dev3000-app/views/dev3000/index.ts +4 -0
  34. package/packages/dev3000-app/views/dev3000/schema.ts +55 -0
  35. package/packages/dev3000-app/views/dev3000/service/index.ts +358 -0
  36. package/packages/dev3000-app/views/dev3000/service/runtime +1 -0
  37. package/packages/dev3000-app/views/dev3000/subjects.ts +9 -0
  38. package/packages/dev3000-app/views/dev3000/types.ts +77 -0
  39. package/packages/files-app/components.ts +12 -0
  40. package/packages/files-app/manifest.ts +19 -0
  41. package/packages/files-app/package.json +23 -0
  42. package/packages/files-app/views/files/ContextMenu.tsx +151 -0
  43. package/packages/files-app/views/files/DeleteConfirmDialog.tsx +39 -0
  44. package/packages/files-app/views/files/FileItem.tsx +128 -0
  45. package/packages/files-app/views/files/FilesApp.tsx +509 -0
  46. package/packages/files-app/views/files/FilesListView.tsx +201 -0
  47. package/packages/files-app/views/files/FilesToolbar.tsx +117 -0
  48. package/packages/files-app/views/files/GridView.tsx +90 -0
  49. package/packages/files-app/views/files/InlineInput.tsx +131 -0
  50. package/packages/files-app/views/files/UploadOverlay.tsx +61 -0
  51. package/packages/files-app/views/files/schema.ts +49 -0
  52. package/packages/files-app/views/files/service/index.ts +184 -0
  53. package/packages/files-app/views/files/service/runtime +1 -0
  54. package/packages/files-app/views/files/use-files.ts +201 -0
  55. package/packages/files-app/views/files/use-upload.ts +105 -0
  56. package/packages/genie-app/components.ts +12 -0
  57. package/packages/genie-app/lib/subjects.ts +87 -0
  58. package/packages/genie-app/manifest.ts +19 -0
  59. package/packages/genie-app/package.json +29 -0
  60. package/packages/genie-app/views/genie/service/agent-lifecycle.ts +136 -0
  61. package/packages/genie-app/views/genie/service/cli.ts +114 -0
  62. package/packages/genie-app/views/genie/service/comms.ts +141 -0
  63. package/packages/genie-app/views/genie/service/directory.ts +167 -0
  64. package/packages/genie-app/views/genie/service/index.ts +219 -0
  65. package/packages/genie-app/views/genie/service/system.ts +123 -0
  66. package/packages/genie-app/views/genie/service/teams.ts +191 -0
  67. package/packages/genie-app/views/genie/service/terminal-proxy.ts +184 -0
  68. package/packages/genie-app/views/genie/service/tmux-control.ts +318 -0
  69. package/packages/genie-app/views/genie/service/wishes.ts +270 -0
  70. package/packages/genie-app/views/genie/ui/GenieApp.tsx +5 -0
  71. package/packages/genie-app/views/genie/ui/PaneCard.tsx +307 -0
  72. package/packages/genie-app/views/genie/ui/Sidebar.tsx +212 -0
  73. package/packages/genie-app/views/genie/ui/TabBar.tsx +70 -0
  74. package/packages/genie-app/views/genie/ui/WorkspaceCanvas.tsx +343 -0
  75. package/packages/genie-app/views/genie/ui/XTermPane.tsx +306 -0
  76. package/packages/genie-app/views/genie/ui/hooks/useNatsAction.ts +54 -0
  77. package/packages/genie-app/views/genie/ui/hooks/useNatsRequest.ts +68 -0
  78. package/packages/genie-app/views/genie/ui/panels/AgentsPanel.tsx +399 -0
  79. package/packages/genie-app/views/genie/ui/panels/ChatPanel.tsx +351 -0
  80. package/packages/genie-app/views/genie/ui/panels/SystemPanel.tsx +195 -0
  81. package/packages/genie-app/views/genie/ui/panels/TeamsPanel.tsx +560 -0
  82. package/packages/genie-app/views/genie/ui/panels/WishesPanel.tsx +424 -0
  83. package/packages/nats-viewer-app/components.ts +12 -0
  84. package/packages/nats-viewer-app/manifest.ts +18 -0
  85. package/packages/nats-viewer-app/package.json +14 -0
  86. package/packages/nats-viewer-app/views/nats-viewer/ActiveSubs.tsx +34 -0
  87. package/packages/nats-viewer-app/views/nats-viewer/MessageLog.tsx +247 -0
  88. package/packages/nats-viewer-app/views/nats-viewer/NatsViewer.tsx +209 -0
  89. package/packages/nats-viewer-app/views/nats-viewer/PublishPanel.tsx +111 -0
  90. package/packages/nats-viewer-app/views/nats-viewer/RequestPanel.tsx +165 -0
  91. package/packages/nats-viewer-app/views/nats-viewer/Sidebar.tsx +59 -0
  92. package/packages/nats-viewer-app/views/nats-viewer/SubjectCatalog.tsx +63 -0
  93. package/packages/nats-viewer-app/views/nats-viewer/SubscribeInput.tsx +59 -0
  94. package/packages/nats-viewer-app/views/nats-viewer/index.ts +5 -0
  95. package/packages/nats-viewer-app/views/nats-viewer/nats-viewer-context.tsx +31 -0
  96. package/packages/nats-viewer-app/views/nats-viewer/types.ts +7 -0
  97. package/packages/nats-viewer-app/views/nats-viewer/use-message-buffer.ts +55 -0
  98. package/packages/os-cli/package.json +18 -0
  99. package/packages/os-cli/src/commands/events.ts +176 -0
  100. package/packages/os-cli/src/commands/logs.ts +96 -0
  101. package/packages/os-cli/src/commands/status.ts +53 -0
  102. package/packages/os-cli/src/commands/traces.ts +115 -0
  103. package/packages/os-cli/src/index.ts +15 -0
  104. package/packages/os-cli/src/lib/formatter.ts +123 -0
  105. package/packages/os-cli/src/lib/nats.ts +16 -0
  106. package/packages/os-cli/src/lib/trace-tree.ts +144 -0
  107. package/packages/os-cli/tsconfig.json +12 -0
  108. package/packages/os-sdk/package.json +27 -0
  109. package/packages/os-sdk/src/api/handler.ts +67 -0
  110. package/packages/os-sdk/src/config.ts +68 -0
  111. package/packages/os-sdk/src/db/factory.test.ts +42 -0
  112. package/packages/os-sdk/src/db/factory.ts +72 -0
  113. package/packages/os-sdk/src/db/migrate.ts +140 -0
  114. package/packages/os-sdk/src/db/provision.ts +44 -0
  115. package/packages/os-sdk/src/index.ts +36 -0
  116. package/packages/os-sdk/src/service/console-intercept.ts +60 -0
  117. package/packages/os-sdk/src/service/logger.ts +88 -0
  118. package/packages/os-sdk/src/service/o11y-streams.ts +88 -0
  119. package/packages/os-sdk/src/service/runtime.ts +259 -0
  120. package/packages/os-sdk/src/service/trace.ts +71 -0
  121. package/packages/os-sdk/tsconfig.json +16 -0
  122. package/packages/os-ui/package.json +13 -0
  123. package/packages/os-ui/src/index.ts +29 -0
  124. package/packages/os-ui/src/server.ts +4 -0
  125. package/packages/os-ui/tsconfig.json +19 -0
  126. package/packages/settings-app/components.ts +12 -0
  127. package/packages/settings-app/manifest.ts +18 -0
  128. package/packages/settings-app/package.json +14 -0
  129. package/packages/settings-app/views/settings/Settings.tsx +492 -0
  130. package/packages/terminal-app/components.ts +12 -0
  131. package/packages/terminal-app/manifest.ts +20 -0
  132. package/packages/terminal-app/package.json +23 -0
  133. package/packages/terminal-app/views/terminal/schema.ts +82 -0
  134. package/packages/terminal-app/views/terminal/service/index.ts +133 -0
  135. package/packages/terminal-app/views/terminal/service/runtime +1 -0
  136. package/packages/terminal-app/views/terminal/service/session.ts +290 -0
  137. package/packages/terminal-app/views/terminal/service/shell-hooks/bashrc-hook.sh +21 -0
  138. package/packages/terminal-app/views/terminal/types.ts +26 -0
  139. package/packages/terminal-app/views/terminal/ui/MultiTerminalApp.tsx +615 -0
  140. package/packages/terminal-app/views/terminal/ui/SplitDragHandle.tsx +91 -0
  141. package/packages/terminal-app/views/terminal/ui/SplitPaneRenderer.tsx +112 -0
  142. package/packages/terminal-app/views/terminal/ui/TerminalPane.tsx +478 -0
  143. package/packages/terminal-app/views/terminal/ui/TerminalTabBar.tsx +131 -0
  144. package/pnpm-workspace.yaml +9 -0
  145. package/postcss.config.mjs +7 -0
  146. package/public/file.svg +1 -0
  147. package/public/globe.svg +1 -0
  148. package/public/icons/code-server.svg +6 -0
  149. package/public/icons/default.svg +5 -0
  150. package/public/icons/dusk/1password.svg +1 -0
  151. package/public/icons/dusk/activity_monitor.svg +1 -0
  152. package/public/icons/dusk/app_store.svg +1 -0
  153. package/public/icons/dusk/atom.svg +1 -0
  154. package/public/icons/dusk/brave.svg +1 -0
  155. package/public/icons/dusk/calculator.svg +1 -0
  156. package/public/icons/dusk/calendar.svg +1 -0
  157. package/public/icons/dusk/chrome.svg +1 -0
  158. package/public/icons/dusk/chrome2.svg +1 -0
  159. package/public/icons/dusk/dashboard.svg +13 -0
  160. package/public/icons/dusk/discord.svg +1 -0
  161. package/public/icons/dusk/dropbox.svg +1 -0
  162. package/public/icons/dusk/electron.svg +1 -0
  163. package/public/icons/dusk/figma.svg +1 -0
  164. package/public/icons/dusk/finder.svg +1 -0
  165. package/public/icons/dusk/finder2.svg +1 -0
  166. package/public/icons/dusk/finder3.svg +1 -0
  167. package/public/icons/dusk/firefox.svg +1 -0
  168. package/public/icons/dusk/framer.svg +1 -0
  169. package/public/icons/dusk/gimp.svg +1 -0
  170. package/public/icons/dusk/github_desktop.svg +1 -0
  171. package/public/icons/dusk/hyper.svg +1 -0
  172. package/public/icons/dusk/hyper3.svg +1 -0
  173. package/public/icons/dusk/intellij.svg +1 -0
  174. package/public/icons/dusk/iterm2.svg +1 -0
  175. package/public/icons/dusk/itunes.svg +1 -0
  176. package/public/icons/dusk/mail.svg +1 -0
  177. package/public/icons/dusk/messenger.svg +1 -0
  178. package/public/icons/dusk/mongodb.svg +1 -0
  179. package/public/icons/dusk/notes.svg +1 -0
  180. package/public/icons/dusk/notion.svg +1 -0
  181. package/public/icons/dusk/obs.svg +1 -0
  182. package/public/icons/dusk/pages.svg +1 -0
  183. package/public/icons/dusk/photos.svg +1 -0
  184. package/public/icons/dusk/postman.svg +1 -0
  185. package/public/icons/dusk/preview.svg +1 -0
  186. package/public/icons/dusk/reminders.svg +1 -0
  187. package/public/icons/dusk/safari.svg +1 -0
  188. package/public/icons/dusk/sequel_pro.svg +1 -0
  189. package/public/icons/dusk/sketch.svg +1 -0
  190. package/public/icons/dusk/skype.svg +1 -0
  191. package/public/icons/dusk/slack.svg +1 -0
  192. package/public/icons/dusk/slack2.svg +1 -0
  193. package/public/icons/dusk/spotify.svg +1 -0
  194. package/public/icons/dusk/steam.svg +1 -0
  195. package/public/icons/dusk/system_preferences.svg +1 -0
  196. package/public/icons/dusk/tableplus.svg +1 -0
  197. package/public/icons/dusk/teams.svg +1 -0
  198. package/public/icons/dusk/telegram.svg +1 -0
  199. package/public/icons/dusk/terminal.svg +1 -0
  200. package/public/icons/dusk/todoist.svg +1 -0
  201. package/public/icons/dusk/trash.svg +1 -0
  202. package/public/icons/dusk/trello.svg +1 -0
  203. package/public/icons/dusk/vivaldi.svg +1 -0
  204. package/public/icons/dusk/vlc.svg +1 -0
  205. package/public/icons/dusk/vscode.svg +1 -0
  206. package/public/icons/dusk/whatsapp.svg +1 -0
  207. package/public/icons/dusk/xeyes.svg +1 -0
  208. package/public/icons/dusk/zoom.svg +1 -0
  209. package/public/icons/files.svg +5 -0
  210. package/public/icons/pwa/icon-192.png +0 -0
  211. package/public/icons/pwa/icon-512.png +0 -0
  212. package/public/icons/settings.svg +14 -0
  213. package/public/icons/terminal.svg +5 -0
  214. package/public/icons/text-editor.svg +7 -0
  215. package/public/manifest.json +38 -0
  216. package/public/next.svg +1 -0
  217. package/public/sw.js +41 -0
  218. package/public/vercel.svg +1 -0
  219. package/public/wallpapers/default.svg +10 -0
  220. package/public/window.svg +1 -0
  221. package/scripts/generate-pwa-icons.mjs +33 -0
  222. package/scripts/install-nats.sh +37 -0
  223. package/sentry.client.config.ts +21 -0
  224. package/sentry.edge.config.ts +12 -0
  225. package/sentry.server.config.ts +12 -0
  226. package/src/app/api/files/download/route.ts +81 -0
  227. package/src/app/api/files/download-zip/route.ts +102 -0
  228. package/src/app/api/files/upload/route.ts +58 -0
  229. package/src/app/api/webhooks/workos/route.ts +98 -0
  230. package/src/app/auth/callback/route.ts +16 -0
  231. package/src/app/auth/logout/route.ts +15 -0
  232. package/src/app/desktop/desktop-shell.tsx +110 -0
  233. package/src/app/desktop/layout.tsx +8 -0
  234. package/src/app/desktop/page.tsx +24 -0
  235. package/src/app/favicon.ico +0 -0
  236. package/src/app/globals.css +7 -0
  237. package/src/app/layout.tsx +64 -0
  238. package/src/app/offline/page.tsx +83 -0
  239. package/src/app/page.tsx +5 -0
  240. package/src/app/standalone/[appId]/page.tsx +28 -0
  241. package/src/app/standalone/layout.tsx +10 -0
  242. package/src/components/app-icon.tsx +55 -0
  243. package/src/components/apps/_echo/schema.ts +14 -0
  244. package/src/components/apps/_echo/service/index.ts +42 -0
  245. package/src/components/apps/app-manifest.ts +97 -0
  246. package/src/components/apps/app-registry.ts +55 -0
  247. package/src/components/apps/dev3000/Dev3000App.tsx +224 -0
  248. package/src/components/apps/dev3000/ErrorsPanel.tsx +160 -0
  249. package/src/components/apps/dev3000/Sidebar.tsx +41 -0
  250. package/src/components/apps/dev3000/TimelineLog.tsx +173 -0
  251. package/src/components/apps/dev3000/dev3000-context.tsx +29 -0
  252. package/src/components/apps/dev3000/index.ts +4 -0
  253. package/src/components/apps/dev3000/schema.ts +48 -0
  254. package/src/components/apps/dev3000/service/index.ts +520 -0
  255. package/src/components/apps/dev3000/service/runtime +1 -0
  256. package/src/components/apps/dev3000/types.ts +15 -0
  257. package/src/components/apps/dev3000/use-message-buffer.ts +46 -0
  258. package/src/components/apps/files/ContextMenu.tsx +151 -0
  259. package/src/components/apps/files/DeleteConfirmDialog.tsx +78 -0
  260. package/src/components/apps/files/FileItem.tsx +128 -0
  261. package/src/components/apps/files/FilesApp.tsx +509 -0
  262. package/src/components/apps/files/FilesListView.tsx +201 -0
  263. package/src/components/apps/files/FilesToolbar.tsx +117 -0
  264. package/src/components/apps/files/GridView.tsx +90 -0
  265. package/src/components/apps/files/InlineInput.tsx +131 -0
  266. package/src/components/apps/files/UploadOverlay.tsx +61 -0
  267. package/src/components/apps/files/schema.ts +49 -0
  268. package/src/components/apps/files/service/index.ts +227 -0
  269. package/src/components/apps/files/service/runtime +1 -0
  270. package/src/components/apps/files/use-files.ts +201 -0
  271. package/src/components/apps/files/use-upload.ts +105 -0
  272. package/src/components/apps/nats-viewer/ActiveSubs.tsx +34 -0
  273. package/src/components/apps/nats-viewer/MessageLog.tsx +247 -0
  274. package/src/components/apps/nats-viewer/NatsViewer.tsx +209 -0
  275. package/src/components/apps/nats-viewer/PublishPanel.tsx +113 -0
  276. package/src/components/apps/nats-viewer/RequestPanel.tsx +167 -0
  277. package/src/components/apps/nats-viewer/Sidebar.tsx +62 -0
  278. package/src/components/apps/nats-viewer/SubjectCatalog.tsx +64 -0
  279. package/src/components/apps/nats-viewer/SubscribeInput.tsx +59 -0
  280. package/src/components/apps/nats-viewer/index.ts +5 -0
  281. package/src/components/apps/nats-viewer/nats-viewer-context.tsx +31 -0
  282. package/src/components/apps/nats-viewer/types.ts +7 -0
  283. package/src/components/apps/nats-viewer/use-message-buffer.ts +55 -0
  284. package/src/components/apps/settings/Settings.tsx +492 -0
  285. package/src/components/apps/terminal/schema.ts +82 -0
  286. package/src/components/apps/terminal/service/index.ts +189 -0
  287. package/src/components/apps/terminal/service/runtime +1 -0
  288. package/src/components/apps/terminal/service/session.ts +296 -0
  289. package/src/components/apps/terminal/service/shell-hooks/bashrc-hook.sh +21 -0
  290. package/src/components/apps/terminal/types.ts +26 -0
  291. package/src/components/apps/terminal/ui/MultiTerminalApp.tsx +617 -0
  292. package/src/components/apps/terminal/ui/SplitDragHandle.tsx +91 -0
  293. package/src/components/apps/terminal/ui/SplitPaneRenderer.tsx +112 -0
  294. package/src/components/apps/terminal/ui/TerminalPane.tsx +476 -0
  295. package/src/components/apps/terminal/ui/TerminalTabBar.tsx +131 -0
  296. package/src/components/desktop/AnimatedBackground.tsx +69 -0
  297. package/src/components/desktop/Desktop.tsx +79 -0
  298. package/src/components/desktop/DesktopBackground.tsx +16 -0
  299. package/src/components/desktop/DesktopIcon.tsx +49 -0
  300. package/src/components/desktop/ShortcutViewer.tsx +136 -0
  301. package/src/components/desktop/WindowRenderer.tsx +34 -0
  302. package/src/components/desktop/WindowSwitcher.tsx +42 -0
  303. package/src/components/notifications/NotificationCenter.tsx +153 -0
  304. package/src/components/notifications/NotificationToasts.tsx +66 -0
  305. package/src/components/notifications/OrphanSessionToast.tsx +293 -0
  306. package/src/components/os-primitives/collapsible-sidebar.tsx +226 -0
  307. package/src/components/os-primitives/dialog.tsx +76 -0
  308. package/src/components/os-primitives/empty-state.tsx +43 -0
  309. package/src/components/os-primitives/index.ts +21 -0
  310. package/src/components/os-primitives/list-view.tsx +155 -0
  311. package/src/components/os-primitives/property-panel.tsx +108 -0
  312. package/src/components/os-primitives/section-header.tsx +19 -0
  313. package/src/components/os-primitives/sidebar-nav.tsx +110 -0
  314. package/src/components/os-primitives/split-pane.tsx +146 -0
  315. package/src/components/os-primitives/status-badge.tsx +10 -0
  316. package/src/components/os-primitives/status-bar.tsx +100 -0
  317. package/src/components/os-primitives/toolbar.tsx +152 -0
  318. package/src/components/taskbar/AppLauncher.tsx +114 -0
  319. package/src/components/taskbar/RunningApps.tsx +71 -0
  320. package/src/components/taskbar/SystemTray.tsx +134 -0
  321. package/src/components/taskbar/Taskbar.tsx +45 -0
  322. package/src/components/taskbar/UserMenu.tsx +138 -0
  323. package/src/components/taskbar/WorkspaceSwitcher.tsx +9 -0
  324. package/src/components/ui/ContextMenu.tsx +130 -0
  325. package/src/components/ui/badge.tsx +39 -0
  326. package/src/components/ui/button.tsx +102 -0
  327. package/src/components/ui/command.tsx +165 -0
  328. package/src/components/ui/dropdown-menu.tsx +233 -0
  329. package/src/components/ui/input.tsx +48 -0
  330. package/src/components/ui/note.tsx +55 -0
  331. package/src/components/ui/separator.tsx +25 -0
  332. package/src/components/ui/spinner.tsx +42 -0
  333. package/src/components/ui/switch.tsx +36 -0
  334. package/src/components/ui/theme-provider.tsx +24 -0
  335. package/src/components/ui/theme-switcher.tsx +51 -0
  336. package/src/components/ui/tooltip.tsx +62 -0
  337. package/src/components/window/MobileWindowStack.tsx +218 -0
  338. package/src/components/window/SnapPreview.tsx +37 -0
  339. package/src/components/window/StandaloneFrame.tsx +170 -0
  340. package/src/components/window/Window.tsx +423 -0
  341. package/src/components/window/WindowContent.tsx +14 -0
  342. package/src/components/window/WindowControlsOverlay.tsx +89 -0
  343. package/src/components/window/WindowFrame.tsx +124 -0
  344. package/src/lib/auth/index.ts +27 -0
  345. package/src/lib/auth/roles.ts +50 -0
  346. package/src/lib/auth/types.ts +32 -0
  347. package/src/lib/auth/use-auth.ts +53 -0
  348. package/src/lib/auth/webhook-handler.ts +87 -0
  349. package/src/lib/auth/workos.ts +67 -0
  350. package/src/lib/constants.ts +1 -0
  351. package/src/lib/desktop/dedup.ts +57 -0
  352. package/src/lib/desktop/schema.ts +55 -0
  353. package/src/lib/files/filename-validation.ts +41 -0
  354. package/src/lib/files/safe-path.ts +49 -0
  355. package/src/lib/hooks/use-desktop-nats.ts +438 -0
  356. package/src/lib/hooks/use-is-mobile.ts +23 -0
  357. package/src/lib/hooks/use-launch-app.ts +79 -0
  358. package/src/lib/hooks/use-nats-notifications.ts +84 -0
  359. package/src/lib/hooks/use-nats.ts +60 -0
  360. package/src/lib/hooks/use-visual-viewport.ts +72 -0
  361. package/src/lib/icons/resolve-window-icon.ts +10 -0
  362. package/src/lib/keyboard/defaults.ts +146 -0
  363. package/src/lib/keyboard/types.ts +52 -0
  364. package/src/lib/keyboard/use-global-keybinds.ts +231 -0
  365. package/src/lib/nats-client.ts +255 -0
  366. package/src/lib/nats.ts +35 -0
  367. package/src/lib/notifications/schema.ts +12 -0
  368. package/src/lib/service-loader.ts +171 -0
  369. package/src/lib/subjects.ts +64 -0
  370. package/src/lib/utils.ts +6 -0
  371. package/src/lib/ws-bridge.ts +288 -0
  372. package/src/lib/ws-protocol.ts +53 -0
  373. package/src/lib/ws-server.ts +167 -0
  374. package/src/middleware.ts +57 -0
  375. package/src/stores/desktop-store.ts +112 -0
  376. package/src/stores/keybind-store.ts +66 -0
  377. package/src/stores/notification-store.ts +271 -0
  378. package/src/stores/theme-store.ts +25 -0
  379. package/src/stores/window-store.ts +294 -0
  380. package/src/theme/animations.css +68 -0
  381. package/src/theme/base.css +123 -0
  382. package/src/theme/controls.css +35 -0
  383. package/src/theme/design-tokens.css +276 -0
  384. package/src/theme/index.css +23 -0
  385. package/src/theme/menus.css +45 -0
  386. package/src/theme/status.css +41 -0
  387. package/src/theme/surfaces.css +94 -0
  388. package/src/theme/tailwind-map.css +138 -0
  389. package/src/theme/taskbar.css +25 -0
  390. package/src/theme/terminal.css +55 -0
  391. package/src/theme/typography.css +26 -0
  392. package/src/theme/utilities.css +156 -0
  393. package/src/theme/window.css +103 -0
  394. package/src/types/desktop-entry.ts +12 -0
  395. package/src/types/use-descendants.d.ts +13 -0
  396. package/src/types/window.ts +28 -0
  397. package/src/types.d.ts +9 -0
  398. package/tauri/Cargo.lock +5464 -0
  399. package/tauri/Cargo.toml +19 -0
  400. package/tauri/build.rs +3 -0
  401. package/tauri/capabilities/default.json +36 -0
  402. package/tauri/icons/128x128.png +0 -0
  403. package/tauri/icons/128x128@2x.png +0 -0
  404. package/tauri/icons/32x32.png +0 -0
  405. package/tauri/icons/icon.png +0 -0
  406. package/tauri/src/main.rs +396 -0
  407. package/tauri/tauri.conf.json +23 -0
  408. package/tsconfig.json +43 -0
@@ -0,0 +1,520 @@
1
+ import { existsSync, readdirSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { connect } from '@nats-io/transport-node';
5
+ import type { D3kCmdRequest, D3kCmdResponse } from '../schema';
6
+ import type { D3kLevel, D3kSource } from '../types';
7
+
8
+ const startTime = Date.now();
9
+ const D3K_BASE = join(homedir(), '.d3k');
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Binary resolution — find d3k and Chrome at runtime
13
+ // ---------------------------------------------------------------------------
14
+
15
+ function findBin(name: string, candidates: string[]): string {
16
+ for (const c of candidates) {
17
+ if (existsSync(c)) return c;
18
+ }
19
+ return name; // fallback to PATH
20
+ }
21
+
22
+ function findChromeBin(): string {
23
+ // Check puppeteer cache first
24
+ const puppeteerBase = join(homedir(), '.cache', 'puppeteer', 'chrome');
25
+ if (existsSync(puppeteerBase)) {
26
+ const versions = readdirSync(puppeteerBase).sort().reverse();
27
+ for (const v of versions) {
28
+ const bin = join(puppeteerBase, v, 'chrome-linux64', 'chrome');
29
+ if (existsSync(bin)) return bin;
30
+ }
31
+ }
32
+ return ''; // let d3k find it
33
+ }
34
+
35
+ const D3K_BIN =
36
+ process.env.D3K_BIN || findBin('d3k', [join(homedir(), '.npm-global', 'bin', 'd3k'), '/usr/local/bin/d3k']);
37
+ const CHROME_BIN = process.env.CHROME_BIN || findChromeBin();
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // d3k log file discovery — find the active session's log
41
+ // ---------------------------------------------------------------------------
42
+
43
+ function findD3kProjectDir(): string | null {
44
+ if (!existsSync(D3K_BASE)) return null;
45
+ const dirs = readdirSync(D3K_BASE).filter((d) => {
46
+ const full = join(D3K_BASE, d);
47
+ return statSync(full).isDirectory() && existsSync(join(full, 'logs'));
48
+ });
49
+ if (dirs.length === 0) return null;
50
+ // Pick the most recently modified project dir
51
+ dirs.sort((a, b) => {
52
+ const sa = statSync(join(D3K_BASE, a)).mtimeMs;
53
+ const sb = statSync(join(D3K_BASE, b)).mtimeMs;
54
+ return sb - sa;
55
+ });
56
+ return join(D3K_BASE, dirs[0]);
57
+ }
58
+
59
+ function findLatestLogFile(projectDir: string): string | null {
60
+ const logsDir = join(projectDir, 'logs');
61
+ if (!existsSync(logsDir)) return null;
62
+ const files = readdirSync(logsDir)
63
+ .filter((f) => f.endsWith('.log'))
64
+ .sort()
65
+ .reverse();
66
+ return files.length > 0 ? join(logsDir, files[0]) : null;
67
+ }
68
+
69
+ // Also check the d3k.log (cleared each session, always written to)
70
+ function getD3kMainLog(projectDir: string): string | null {
71
+ const p = join(projectDir, 'd3k.log');
72
+ return existsSync(p) ? p : null;
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // d3k log line parser — format: "[HH:mm:ss.SSS] [SOURCE] message"
77
+ // SOURCE can be SERVER or BROWSER, with optional sub-tags like [NETWORK], [ERROR], etc.
78
+ // ---------------------------------------------------------------------------
79
+
80
+ const D3K_LINE_RE = /^\[(\d{2}:\d{2}:\d{2}\.\d{3})\]\s+\[(\w+)]\s+(.*)$/;
81
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: stripping ANSI escape sequences
82
+ const ANSI_RE = /\x1b\[[0-9;]*m/g;
83
+
84
+ interface ParsedLogLine {
85
+ source: D3kSource;
86
+ level: D3kLevel;
87
+ message: string;
88
+ tag?: string;
89
+ rawTimestamp: string;
90
+ }
91
+
92
+ function classifySource(source: string, message: string): { source: D3kSource; tag?: string } {
93
+ const upper = source.toUpperCase();
94
+ if (upper === 'SERVER') return { source: 'SERVER' };
95
+ if (upper === 'BROWSER') {
96
+ // Extract sub-tag: [NETWORK], [ERROR], [NAVIGATION], [DOM], [SCREENSHOT], etc.
97
+ const tagMatch = message.match(/^\[(\w+(?:\.\w+)?)]/);
98
+ if (tagMatch) {
99
+ const tag = tagMatch[1].toUpperCase();
100
+ if (tag === 'NETWORK' || tag.startsWith('NETWORK')) return { source: 'NETWORK', tag };
101
+ return { source: 'BROWSER', tag };
102
+ }
103
+ return { source: 'BROWSER' };
104
+ }
105
+ return { source: 'UNKNOWN' };
106
+ }
107
+
108
+ function classifyLevel(message: string, tag?: string): D3kLevel {
109
+ if (tag === 'ERROR' || tag === 'RUNTIME.ERROR') return 'error';
110
+ if (tag === 'WARNING' || tag === 'CONSOLE WARNING') return 'warn';
111
+ if (tag === 'DEBUG') return 'debug';
112
+ const lower = message.toLowerCase();
113
+ if (lower.includes('error') || lower.includes('failed') || lower.includes('exception')) return 'error';
114
+ if (lower.includes('warn') || lower.includes('⚠')) return 'warn';
115
+ return 'info';
116
+ }
117
+
118
+ function parseLine(line: string): ParsedLogLine | null {
119
+ // Strip ANSI escape codes before parsing
120
+ const clean = line.replace(ANSI_RE, '');
121
+ const match = clean.match(D3K_LINE_RE);
122
+ if (!match) return null;
123
+ const [, rawTimestamp, rawSource, rawMessage] = match;
124
+ const { source, tag } = classifySource(rawSource, rawMessage);
125
+ const level = classifyLevel(rawMessage, tag);
126
+ return { source, level, message: rawMessage, tag, rawTimestamp };
127
+ }
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // File tail watcher
131
+ // ---------------------------------------------------------------------------
132
+
133
+ async function readNewLines(filePath: string, start: number, onLine: (parsed: ParsedLogLine) => void): Promise<void> {
134
+ const { createReadStream } = await import('node:fs');
135
+ const { createInterface } = await import('node:readline');
136
+ const stream = createReadStream(filePath, { start, encoding: 'utf8' });
137
+ const rl = createInterface({ input: stream });
138
+ for await (const line of rl) {
139
+ const trimmed = line.trim();
140
+ if (!trimmed) continue;
141
+ const parsed = parseLine(trimmed);
142
+ if (parsed) onLine(parsed);
143
+ }
144
+ }
145
+
146
+ async function tailFile(filePath: string, onLine: (parsed: ParsedLogLine) => void, signal: AbortSignal): Promise<void> {
147
+ const { watch } = await import('node:fs/promises');
148
+ let offset = existsSync(filePath) ? statSync(filePath).size : 0;
149
+
150
+ try {
151
+ const watcher = watch(filePath, { signal });
152
+ for await (const _event of watcher) {
153
+ if (signal.aborted) break;
154
+ const stat = statSync(filePath);
155
+ if (stat.size > offset) {
156
+ await readNewLines(filePath, offset, onLine);
157
+ offset = stat.size;
158
+ } else if (stat.size < offset) {
159
+ offset = 0;
160
+ }
161
+ }
162
+ } catch (err: unknown) {
163
+ if (signal.aborted) return;
164
+ console.error('[d3k-service] tail watcher error:', err);
165
+ }
166
+ }
167
+
168
+ // ---------------------------------------------------------------------------
169
+ // Watch for new log files (d3k creates a new one each session)
170
+ // ---------------------------------------------------------------------------
171
+
172
+ async function watchForLogFiles(
173
+ projectDir: string,
174
+ onNewFile: (filePath: string) => void,
175
+ signal: AbortSignal
176
+ ): Promise<void> {
177
+ const { watch } = await import('node:fs/promises');
178
+ const logsDir = join(projectDir, 'logs');
179
+ const seen = new Set<string>();
180
+
181
+ // Track existing files
182
+ if (existsSync(logsDir)) {
183
+ for (const f of readdirSync(logsDir)) {
184
+ seen.add(f);
185
+ }
186
+ }
187
+
188
+ try {
189
+ const watcher = watch(logsDir, { signal });
190
+ for await (const event of watcher) {
191
+ if (signal.aborted) break;
192
+ if (event.filename && event.filename.endsWith('.log') && !seen.has(event.filename)) {
193
+ seen.add(event.filename);
194
+ const fullPath = join(logsDir, event.filename);
195
+ if (existsSync(fullPath)) {
196
+ onNewFile(fullPath);
197
+ }
198
+ }
199
+ }
200
+ } catch (err: unknown) {
201
+ if (signal.aborted) return;
202
+ console.error('[d3k-service] log dir watcher error:', err);
203
+ }
204
+ }
205
+
206
+ // ---------------------------------------------------------------------------
207
+ // d3k process management
208
+ // ---------------------------------------------------------------------------
209
+
210
+ interface D3kManager {
211
+ get process(): import('node:child_process').ChildProcess | null;
212
+ get running(): boolean;
213
+ stop(): void;
214
+ }
215
+
216
+ function createD3kManager(signal: AbortSignal): D3kManager {
217
+ let child: import('node:child_process').ChildProcess | null = null;
218
+ let stopped = false;
219
+ const RESTART_DELAY = 5_000;
220
+
221
+ const doSpawn = async () => {
222
+ if (stopped || signal.aborted) return;
223
+
224
+ const { spawn } = await import('node:child_process');
225
+ const args = [
226
+ '--headless',
227
+ ...(CHROME_BIN ? ['--browser', CHROME_BIN] : []),
228
+ '--no-agent',
229
+ '--no-tui',
230
+ '--command',
231
+ 'bun dev',
232
+ '--port',
233
+ '8888',
234
+ ];
235
+
236
+ console.log(`[d3k-service] spawning: ${D3K_BIN} ${args.join(' ')}`);
237
+
238
+ child = spawn(D3K_BIN, args, {
239
+ cwd: process.cwd(),
240
+ env: { ...process.env, FORCE_COLOR: '0', VERCEL_SANDBOX: '1' },
241
+ stdio: ['ignore', 'pipe', 'pipe'],
242
+ });
243
+
244
+ child.stdout?.on('data', (chunk: Buffer) => {
245
+ for (const line of chunk.toString().split('\n').filter(Boolean)) {
246
+ console.log(`[d3k] ${line}`);
247
+ }
248
+ });
249
+
250
+ child.stderr?.on('data', (chunk: Buffer) => {
251
+ for (const line of chunk.toString().split('\n').filter(Boolean)) {
252
+ console.error(`[d3k:err] ${line}`);
253
+ }
254
+ });
255
+
256
+ child.on('close', (code) => {
257
+ console.log(`[d3k-service] d3k exited with code ${code}`);
258
+ child = null;
259
+ if (!stopped && !signal.aborted) {
260
+ console.log(`[d3k-service] restarting d3k in ${RESTART_DELAY / 1000}s...`);
261
+ setTimeout(() => doSpawn(), RESTART_DELAY);
262
+ }
263
+ });
264
+ };
265
+
266
+ // Kill d3k when service shuts down
267
+ signal.addEventListener('abort', () => {
268
+ stopped = true;
269
+ if (child && !child.killed) child.kill('SIGTERM');
270
+ });
271
+
272
+ doSpawn();
273
+
274
+ return {
275
+ get process() {
276
+ return child;
277
+ },
278
+ get running() {
279
+ return child !== null && !child.killed;
280
+ },
281
+ stop() {
282
+ stopped = true;
283
+ if (child && !child.killed) child.kill('SIGTERM');
284
+ },
285
+ };
286
+ }
287
+
288
+ // ---------------------------------------------------------------------------
289
+ // Command execution
290
+ // ---------------------------------------------------------------------------
291
+
292
+ async function runD3kCommand(command: string, args: string[] = []): Promise<D3kCmdResponse> {
293
+ const { spawn } = await import('node:child_process');
294
+ const CMD_TIMEOUT = 15_000;
295
+
296
+ return new Promise((resolve) => {
297
+ let resolved = false;
298
+ const done = (result: D3kCmdResponse) => {
299
+ if (resolved) return;
300
+ resolved = true;
301
+ clearTimeout(timer);
302
+ resolve(result);
303
+ };
304
+
305
+ const child = spawn(D3K_BIN, [command, '--json', ...args], {
306
+ cwd: process.cwd(),
307
+ env: { ...process.env, FORCE_COLOR: '0' },
308
+ });
309
+
310
+ const timer = setTimeout(() => {
311
+ child.kill('SIGTERM');
312
+ done({ ok: false, error: `command timed out after ${CMD_TIMEOUT / 1000}s` });
313
+ }, CMD_TIMEOUT);
314
+
315
+ let stdout = '';
316
+ let stderr = '';
317
+
318
+ child.stdout?.on('data', (chunk: Buffer) => {
319
+ stdout += chunk.toString();
320
+ });
321
+ child.stderr?.on('data', (chunk: Buffer) => {
322
+ stderr += chunk.toString();
323
+ });
324
+
325
+ child.on('close', (code) => {
326
+ if (code === 0) {
327
+ done({ ok: true, output: stdout.trim() || undefined });
328
+ } else {
329
+ done({ ok: false, error: stderr.trim() || `exit code ${code}`, output: stdout.trim() || undefined });
330
+ }
331
+ });
332
+
333
+ child.on('error', (err) => {
334
+ done({ ok: false, error: err.message });
335
+ });
336
+ });
337
+ }
338
+
339
+ // ---------------------------------------------------------------------------
340
+ // Main
341
+ // ---------------------------------------------------------------------------
342
+
343
+ async function main() {
344
+ const nc = await connect({
345
+ servers: process.env.NATS_URL || 'nats://localhost:4222',
346
+ });
347
+
348
+ console.log('[d3k-service] connected to NATS');
349
+
350
+ let lineCount = 0;
351
+ const abortController = new AbortController();
352
+ const REPLAY_CAPACITY = 500;
353
+
354
+ const knownOrgIds = new Set<string>();
355
+ const replayBuffer: string[] = [];
356
+ let currentTailAbort: AbortController | null = null;
357
+
358
+ function extractOrgId(subject: string): string {
359
+ return subject.split('.')[1];
360
+ }
361
+
362
+ function makePayload(parsed: ParsedLogLine): string {
363
+ return JSON.stringify({
364
+ id: crypto.randomUUID(),
365
+ timestamp: Date.now(),
366
+ source: parsed.source,
367
+ level: parsed.level,
368
+ message: parsed.message,
369
+ tag: parsed.tag,
370
+ });
371
+ }
372
+
373
+ const publishEntry = (parsed: ParsedLogLine) => {
374
+ lineCount++;
375
+ const payload = makePayload(parsed);
376
+ replayBuffer.push(payload);
377
+ if (replayBuffer.length > REPLAY_CAPACITY) {
378
+ replayBuffer.splice(0, replayBuffer.length - REPLAY_CAPACITY);
379
+ }
380
+ for (const orgId of knownOrgIds) {
381
+ nc.publish(`khal.${orgId}.d3k.log`, payload);
382
+ }
383
+ };
384
+
385
+ // --- Spawn d3k process (with auto-restart) ---
386
+ const d3k = createD3kManager(abortController.signal);
387
+
388
+ // --- Wait for d3k to create its log, then tail it ---
389
+ const startTailing = async () => {
390
+ // Wait a bit for d3k to start and create its project dir + log
391
+ const waitForProjectDir = async (): Promise<string | null> => {
392
+ for (let i = 0; i < 30; i++) {
393
+ const dir = findD3kProjectDir();
394
+ if (dir) return dir;
395
+ await new Promise((r) => setTimeout(r, 1000));
396
+ if (abortController.signal.aborted) return null;
397
+ }
398
+ return null;
399
+ };
400
+
401
+ const projectDir = await waitForProjectDir();
402
+ if (!projectDir) {
403
+ console.error('[d3k-service] could not find d3k project dir after 30s');
404
+ return;
405
+ }
406
+ console.log(`[d3k-service] found d3k project: ${projectDir}`);
407
+
408
+ // Chain abort: when main controller aborts, also abort the current tail
409
+ abortController.signal.addEventListener('abort', () => {
410
+ if (currentTailAbort && !currentTailAbort.signal.aborted) currentTailAbort.abort();
411
+ });
412
+
413
+ // Tail the current latest log file
414
+ const tailLatest = async (logFile: string) => {
415
+ // Abort previous tail if any
416
+ if (currentTailAbort) currentTailAbort.abort();
417
+ currentTailAbort = new AbortController();
418
+
419
+ console.log(`[d3k-service] tailing ${logFile}`);
420
+ await readNewLines(logFile, 0, publishEntry);
421
+ await tailFile(logFile, publishEntry, currentTailAbort.signal);
422
+ };
423
+
424
+ // Start with current latest log
425
+ const initialLog = findLatestLogFile(projectDir) || getD3kMainLog(projectDir);
426
+ if (initialLog) {
427
+ tailLatest(initialLog).catch((err) => console.error('[d3k-service] tail error:', err));
428
+ } else {
429
+ console.log('[d3k-service] no log file yet, waiting...');
430
+ }
431
+
432
+ // Watch for new log files (d3k creates new ones on restart)
433
+ watchForLogFiles(
434
+ projectDir,
435
+ (newFile) => {
436
+ console.log(`[d3k-service] new log file detected: ${newFile}`);
437
+ tailLatest(newFile).catch((err) => console.error('[d3k-service] tail error:', err));
438
+ },
439
+ abortController.signal
440
+ ).catch((err) => console.error('[d3k-service] log dir watch error:', err));
441
+ };
442
+
443
+ startTailing();
444
+
445
+ // --- khal.*.d3k.cmd (request-reply) ---
446
+ const cmdSub = nc.subscribe('khal.*.d3k.cmd');
447
+ (async () => {
448
+ for await (const msg of cmdSub) {
449
+ try {
450
+ knownOrgIds.add(extractOrgId(msg.subject));
451
+ let request: D3kCmdRequest = { command: 'logs' };
452
+ if (msg.data.length > 0) {
453
+ request = msg.json<D3kCmdRequest>();
454
+ }
455
+ console.log(`[d3k-service] cmd: ${request.command} ${(request.args || []).join(' ')}`);
456
+ const result = await runD3kCommand(request.command, request.args);
457
+ msg.respond(JSON.stringify(result));
458
+ } catch (err) {
459
+ console.error('[d3k-service] cmd error:', err);
460
+ msg.respond(JSON.stringify({ ok: false, error: (err as Error).message }));
461
+ }
462
+ }
463
+ })();
464
+
465
+ // --- khal.*.d3k.status (request-reply) ---
466
+ const statusSub = nc.subscribe('khal.*.d3k.status');
467
+ (async () => {
468
+ for await (const msg of statusSub) {
469
+ try {
470
+ const orgId = extractOrgId(msg.subject);
471
+ const isNew = !knownOrgIds.has(orgId);
472
+ knownOrgIds.add(orgId);
473
+
474
+ const entries: unknown[] = [];
475
+ for (const p of replayBuffer) {
476
+ try {
477
+ entries.push(JSON.parse(p));
478
+ } catch {
479
+ // skip corrupted buffer entries
480
+ }
481
+ }
482
+ console.log(
483
+ `[d3k-service] ${isNew ? 'registered' : 'status for'} orgId: ${orgId} (${entries.length} buffered)`
484
+ );
485
+ msg.respond(
486
+ JSON.stringify({
487
+ d3kRunning: d3k.running,
488
+ lineCount,
489
+ version: '0.0.167',
490
+ uptime: (Date.now() - startTime) / 1000,
491
+ entries,
492
+ })
493
+ );
494
+ } catch (err) {
495
+ console.error('[d3k-service] status error:', err);
496
+ msg.respond(JSON.stringify({ error: (err as Error).message }));
497
+ }
498
+ }
499
+ })();
500
+
501
+ // --- Graceful shutdown ---
502
+ const shutdown = async () => {
503
+ console.log('[d3k-service] shutting down...');
504
+ abortController.abort();
505
+ cmdSub.unsubscribe();
506
+ statusSub.unsubscribe();
507
+ await nc.close();
508
+ process.exit(0);
509
+ };
510
+
511
+ process.on('SIGINT', shutdown);
512
+ process.on('SIGTERM', shutdown);
513
+
514
+ await nc.closed();
515
+ }
516
+
517
+ main().catch((err) => {
518
+ console.error('[d3k-service] fatal:', err);
519
+ process.exit(1);
520
+ });
@@ -0,0 +1,15 @@
1
+ export type D3kSource = 'SERVER' | 'BROWSER' | 'D3K' | 'NETWORK' | 'UNKNOWN';
2
+
3
+ export type D3kLevel = 'info' | 'warn' | 'error' | 'debug';
4
+
5
+ export interface D3kLogEntry {
6
+ id: string;
7
+ timestamp: number;
8
+ source: D3kSource;
9
+ level: D3kLevel;
10
+ message: string;
11
+ /** Sub-tag from d3k log, e.g. NAVIGATION, SCREENSHOT, ERROR, NETWORK */
12
+ tag?: string;
13
+ }
14
+
15
+ export type D3kTab = 'timeline' | 'errors';
@@ -0,0 +1,46 @@
1
+ import { useCallback, useReducer } from 'react';
2
+ import type { D3kLogEntry } from './types';
3
+
4
+ const DEFAULT_CAPACITY = 1000;
5
+
6
+ type Action = { type: 'push'; entry: D3kLogEntry } | { type: 'clear' } | { type: 'set-capacity'; capacity: number };
7
+
8
+ interface State {
9
+ entries: D3kLogEntry[];
10
+ capacity: number;
11
+ }
12
+
13
+ function reducer(state: State, action: Action): State {
14
+ switch (action.type) {
15
+ case 'push': {
16
+ const next = [...state.entries, action.entry];
17
+ if (next.length > state.capacity) {
18
+ return { ...state, entries: next.slice(next.length - state.capacity) };
19
+ }
20
+ return { ...state, entries: next };
21
+ }
22
+ case 'clear':
23
+ return { ...state, entries: [] };
24
+ case 'set-capacity': {
25
+ const entries =
26
+ state.entries.length > action.capacity
27
+ ? state.entries.slice(state.entries.length - action.capacity)
28
+ : state.entries;
29
+ return { capacity: action.capacity, entries };
30
+ }
31
+ }
32
+ }
33
+
34
+ export function useMessageBuffer(capacity = DEFAULT_CAPACITY) {
35
+ const [state, dispatch] = useReducer(reducer, { entries: [], capacity });
36
+
37
+ const push = useCallback((entry: D3kLogEntry) => {
38
+ dispatch({ type: 'push', entry });
39
+ }, []);
40
+
41
+ const clear = useCallback(() => {
42
+ dispatch({ type: 'clear' });
43
+ }, []);
44
+
45
+ return { entries: state.entries, push, clear };
46
+ }