gitspace 0.2.0-rc.20 → 0.2.0-rc.21

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 (474) hide show
  1. package/package.json +11 -6
  2. package/.claude/settings.local.json +0 -10
  3. package/.gitspace/bundle.json +0 -50
  4. package/.gitspace/events.json +0 -11
  5. package/.gitspace/processes.json +0 -23
  6. package/.gitspace/scripts/select/01-status.sh +0 -39
  7. package/.gitspace/scripts/setup/01-install-deps.sh +0 -12
  8. package/.gitspace/scripts/setup/02-typecheck.sh +0 -16
  9. package/AGENTS.md +0 -469
  10. package/CLAUDE.md +0 -1
  11. package/bun.lock +0 -794
  12. package/docs/CONNECTION.md +0 -623
  13. package/docs/GATEWAY-WORKER.md +0 -319
  14. package/docs/GETTING-STARTED.md +0 -448
  15. package/docs/GITSPACE-PLATFORM.md +0 -1819
  16. package/docs/INFRASTRUCTURE.md +0 -1347
  17. package/docs/PROTOCOL.md +0 -619
  18. package/docs/QUICKSTART.md +0 -183
  19. package/docs/RELAY.md +0 -327
  20. package/docs/REMOTE-DESIGN.md +0 -554
  21. package/docs/ROADMAP.md +0 -564
  22. package/docs/SITE_DOCS_FIGMA_MAKE.md +0 -1176
  23. package/docs/STACK-DESIGN.md +0 -588
  24. package/docs/UNIFIED_ARCHITECTURE.md +0 -138
  25. package/experiments/pty-benchmark.ts +0 -148
  26. package/experiments/pty-latency.ts +0 -100
  27. package/experiments/router/client.ts +0 -199
  28. package/experiments/router/protocol.ts +0 -74
  29. package/experiments/router/router.ts +0 -217
  30. package/experiments/router/session.ts +0 -180
  31. package/experiments/router/test.ts +0 -133
  32. package/experiments/socket-bandwidth.ts +0 -77
  33. package/homebrew/gitspace.rb +0 -45
  34. package/landing-page/ATTRIBUTIONS.md +0 -3
  35. package/landing-page/README.md +0 -11
  36. package/landing-page/bun.lock +0 -801
  37. package/landing-page/guidelines/Guidelines.md +0 -61
  38. package/landing-page/index.html +0 -37
  39. package/landing-page/package.json +0 -90
  40. package/landing-page/postcss.config.mjs +0 -15
  41. package/landing-page/public/_redirects +0 -1
  42. package/landing-page/public/favicon.png +0 -0
  43. package/landing-page/src/app/App.tsx +0 -53
  44. package/landing-page/src/app/components/figma/ImageWithFallback.tsx +0 -27
  45. package/landing-page/src/app/components/ui/accordion.tsx +0 -66
  46. package/landing-page/src/app/components/ui/alert-dialog.tsx +0 -157
  47. package/landing-page/src/app/components/ui/alert.tsx +0 -66
  48. package/landing-page/src/app/components/ui/aspect-ratio.tsx +0 -11
  49. package/landing-page/src/app/components/ui/avatar.tsx +0 -53
  50. package/landing-page/src/app/components/ui/badge.tsx +0 -46
  51. package/landing-page/src/app/components/ui/breadcrumb.tsx +0 -109
  52. package/landing-page/src/app/components/ui/button.tsx +0 -57
  53. package/landing-page/src/app/components/ui/calendar.tsx +0 -75
  54. package/landing-page/src/app/components/ui/card.tsx +0 -92
  55. package/landing-page/src/app/components/ui/carousel.tsx +0 -241
  56. package/landing-page/src/app/components/ui/chart.tsx +0 -353
  57. package/landing-page/src/app/components/ui/checkbox.tsx +0 -32
  58. package/landing-page/src/app/components/ui/collapsible.tsx +0 -33
  59. package/landing-page/src/app/components/ui/command.tsx +0 -177
  60. package/landing-page/src/app/components/ui/context-menu.tsx +0 -252
  61. package/landing-page/src/app/components/ui/dialog.tsx +0 -135
  62. package/landing-page/src/app/components/ui/drawer.tsx +0 -132
  63. package/landing-page/src/app/components/ui/dropdown-menu.tsx +0 -257
  64. package/landing-page/src/app/components/ui/form.tsx +0 -168
  65. package/landing-page/src/app/components/ui/hover-card.tsx +0 -44
  66. package/landing-page/src/app/components/ui/input-otp.tsx +0 -77
  67. package/landing-page/src/app/components/ui/input.tsx +0 -21
  68. package/landing-page/src/app/components/ui/label.tsx +0 -24
  69. package/landing-page/src/app/components/ui/menubar.tsx +0 -276
  70. package/landing-page/src/app/components/ui/navigation-menu.tsx +0 -168
  71. package/landing-page/src/app/components/ui/pagination.tsx +0 -127
  72. package/landing-page/src/app/components/ui/popover.tsx +0 -48
  73. package/landing-page/src/app/components/ui/progress.tsx +0 -31
  74. package/landing-page/src/app/components/ui/radio-group.tsx +0 -45
  75. package/landing-page/src/app/components/ui/resizable.tsx +0 -56
  76. package/landing-page/src/app/components/ui/scroll-area.tsx +0 -58
  77. package/landing-page/src/app/components/ui/select.tsx +0 -189
  78. package/landing-page/src/app/components/ui/separator.tsx +0 -28
  79. package/landing-page/src/app/components/ui/sheet.tsx +0 -139
  80. package/landing-page/src/app/components/ui/sidebar.tsx +0 -726
  81. package/landing-page/src/app/components/ui/skeleton.tsx +0 -13
  82. package/landing-page/src/app/components/ui/slider.tsx +0 -63
  83. package/landing-page/src/app/components/ui/sonner.tsx +0 -25
  84. package/landing-page/src/app/components/ui/switch.tsx +0 -31
  85. package/landing-page/src/app/components/ui/table.tsx +0 -116
  86. package/landing-page/src/app/components/ui/tabs.tsx +0 -66
  87. package/landing-page/src/app/components/ui/textarea.tsx +0 -18
  88. package/landing-page/src/app/components/ui/toggle-group.tsx +0 -73
  89. package/landing-page/src/app/components/ui/toggle.tsx +0 -47
  90. package/landing-page/src/app/components/ui/tooltip.tsx +0 -61
  91. package/landing-page/src/app/components/ui/use-mobile.ts +0 -21
  92. package/landing-page/src/app/components/ui/utils.ts +0 -6
  93. package/landing-page/src/components/docs/DocsContent.tsx +0 -801
  94. package/landing-page/src/components/docs/DocsSidebar.tsx +0 -90
  95. package/landing-page/src/components/landing/CTA.tsx +0 -59
  96. package/landing-page/src/components/landing/Comparison.tsx +0 -84
  97. package/landing-page/src/components/landing/FaultyTerminal.tsx +0 -424
  98. package/landing-page/src/components/landing/Features.tsx +0 -201
  99. package/landing-page/src/components/landing/Hero.tsx +0 -142
  100. package/landing-page/src/components/landing/Pricing.tsx +0 -140
  101. package/landing-page/src/components/landing/Roadmap.tsx +0 -86
  102. package/landing-page/src/components/landing/Security.tsx +0 -81
  103. package/landing-page/src/components/landing/TerminalWindow.tsx +0 -27
  104. package/landing-page/src/components/landing/UseCases.tsx +0 -55
  105. package/landing-page/src/components/landing/Workflow.tsx +0 -101
  106. package/landing-page/src/components/layout/DashboardNavbar.tsx +0 -37
  107. package/landing-page/src/components/layout/Footer.tsx +0 -55
  108. package/landing-page/src/components/layout/LandingNavbar.tsx +0 -82
  109. package/landing-page/src/components/ui/badge.tsx +0 -39
  110. package/landing-page/src/components/ui/breadcrumb.tsx +0 -115
  111. package/landing-page/src/components/ui/button.tsx +0 -57
  112. package/landing-page/src/components/ui/card.tsx +0 -79
  113. package/landing-page/src/components/ui/mock-terminal.tsx +0 -68
  114. package/landing-page/src/components/ui/separator.tsx +0 -28
  115. package/landing-page/src/lib/utils.ts +0 -6
  116. package/landing-page/src/main.tsx +0 -10
  117. package/landing-page/src/pages/Dashboard.tsx +0 -133
  118. package/landing-page/src/pages/DocsPage.tsx +0 -79
  119. package/landing-page/src/pages/LandingPage.tsx +0 -31
  120. package/landing-page/src/pages/TerminalView.tsx +0 -106
  121. package/landing-page/src/styles/fonts.css +0 -0
  122. package/landing-page/src/styles/index.css +0 -3
  123. package/landing-page/src/styles/tailwind.css +0 -4
  124. package/landing-page/src/styles/theme.css +0 -181
  125. package/landing-page/vite.config.ts +0 -19
  126. package/scripts/GHOSTTY_TAB_BUG.md +0 -106
  127. package/scripts/build.ts +0 -298
  128. package/scripts/migrate-secrets.ts +0 -77
  129. package/scripts/release.ts +0 -140
  130. package/scripts/sample-events.ts +0 -263
  131. package/scripts/test-tabs-minimal.ts +0 -68
  132. package/scripts/test-tabs-workaround.ts +0 -95
  133. package/scripts/test-tabs.ts +0 -171
  134. package/src/__tests__/test-utils.ts +0 -298
  135. package/src/app/input/__tests__/sessionCommands.test.ts +0 -40
  136. package/src/app/input/sessionCommands.ts +0 -94
  137. package/src/app/session/__tests__/useAttachController.test.ts +0 -229
  138. package/src/app/session/createSessionBackend.bun.ts +0 -76
  139. package/src/app/session/createSessionBackend.web.ts +0 -104
  140. package/src/app/session/types.ts +0 -16
  141. package/src/app/session/useAttachController.ts +0 -220
  142. package/src/app/session/useProcessActions.ts +0 -201
  143. package/src/app/session/useSessionClient.ts +0 -35
  144. package/src/app/session/useWorkspaceDeleteFlow.ts +0 -170
  145. package/src/app.tui.tsx +0 -2929
  146. package/src/app.web.tsx +0 -1454
  147. package/src/commands/__tests__/connect-key.test.ts +0 -10
  148. package/src/commands/__tests__/events.test.ts +0 -201
  149. package/src/commands/__tests__/notifications.test.ts +0 -349
  150. package/src/commands/__tests__/process.test.ts +0 -251
  151. package/src/commands/__tests__/serve-messages.test.ts +0 -190
  152. package/src/commands/__tests__/serve-process-hosting.test.ts +0 -63
  153. package/src/commands/access.ts +0 -298
  154. package/src/commands/add.ts +0 -455
  155. package/src/commands/auth.ts +0 -369
  156. package/src/commands/bundle.ts +0 -232
  157. package/src/commands/config.ts +0 -242
  158. package/src/commands/connect-key.ts +0 -1
  159. package/src/commands/connect.ts +0 -576
  160. package/src/commands/directory.ts +0 -16
  161. package/src/commands/events.ts +0 -157
  162. package/src/commands/host.ts +0 -566
  163. package/src/commands/identity.ts +0 -184
  164. package/src/commands/linear.ts +0 -717
  165. package/src/commands/list.ts +0 -181
  166. package/src/commands/migrate.ts +0 -52
  167. package/src/commands/notifications.ts +0 -351
  168. package/src/commands/process.ts +0 -104
  169. package/src/commands/relay.ts +0 -315
  170. package/src/commands/remove.ts +0 -279
  171. package/src/commands/review.ts +0 -787
  172. package/src/commands/serve.ts +0 -1946
  173. package/src/commands/share.ts +0 -451
  174. package/src/commands/status.ts +0 -125
  175. package/src/commands/switch.ts +0 -361
  176. package/src/commands/tmux.ts +0 -317
  177. package/src/components/DPad.web.tsx +0 -343
  178. package/src/components/DiffViewer.web.tsx +0 -1192
  179. package/src/components/Events.tsx +0 -137
  180. package/src/components/Events.tui.tsx +0 -129
  181. package/src/components/Events.web.tsx +0 -386
  182. package/src/components/FloatingControls.web.tsx +0 -112
  183. package/src/components/FloatingJogWheel.web.tsx +0 -240
  184. package/src/components/Flow.tsx +0 -458
  185. package/src/components/Flow.tui.tsx +0 -343
  186. package/src/components/Flow.web.tsx +0 -442
  187. package/src/components/Inbox.tsx +0 -448
  188. package/src/components/Inbox.tui.tsx +0 -262
  189. package/src/components/Inbox.web.tsx +0 -329
  190. package/src/components/MachineList.tsx +0 -187
  191. package/src/components/MachineList.tui.tsx +0 -161
  192. package/src/components/MachineList.web.tsx +0 -210
  193. package/src/components/NumPad.web.tsx +0 -270
  194. package/src/components/ProjectList.tsx +0 -175
  195. package/src/components/ProjectList.tui.tsx +0 -109
  196. package/src/components/ProjectList.web.tsx +0 -143
  197. package/src/components/ProjectOnboardingStep.ts +0 -23
  198. package/src/components/ProjectOnboardingStep.tui.tsx +0 -88
  199. package/src/components/ProjectOnboardingStep.web.tsx +0 -59
  200. package/src/components/RemoteMachineScreen.tui.tsx +0 -690
  201. package/src/components/ScriptTerminal.tui.tsx +0 -160
  202. package/src/components/ScriptTerminal.web.tsx +0 -89
  203. package/src/components/SessionTerminal.tui.tsx +0 -406
  204. package/src/components/SessionTerminal.web.tsx +0 -467
  205. package/src/components/SpacesBrowser.tsx +0 -540
  206. package/src/components/SpacesBrowser.tui.tsx +0 -258
  207. package/src/components/SpacesBrowser.web.tsx +0 -332
  208. package/src/components/TerminalControls.web.tsx +0 -464
  209. package/src/components/ThreadPanel.web.tsx +0 -798
  210. package/src/components/__tests__/SpacesBrowser.test.ts +0 -541
  211. package/src/components/__tests__/SpacesBrowser.tui.test.tsx +0 -249
  212. package/src/components/__tests__/script-terminal-buffer.tui.test.ts +0 -72
  213. package/src/components/index.ts +0 -105
  214. package/src/components/review-decision-colors.ts +0 -11
  215. package/src/components/script-terminal-buffer.tui.ts +0 -37
  216. package/src/components/session-terminal-page-navigation.ts +0 -48
  217. package/src/components/terminal-bracketed-paste.tui.test.ts +0 -43
  218. package/src/components/terminal-bracketed-paste.tui.ts +0 -46
  219. package/src/core/__tests__/access.test.ts +0 -240
  220. package/src/core/__tests__/bundle-refresh.test.ts +0 -567
  221. package/src/core/__tests__/bundle.test.ts +0 -209
  222. package/src/core/__tests__/github-review.test.ts +0 -781
  223. package/src/core/__tests__/project-lifecycle.test.ts +0 -137
  224. package/src/core/__tests__/workspace-lifecycle.test.ts +0 -159
  225. package/src/core/__tests__/workspace.test.ts +0 -149
  226. package/src/core/access.ts +0 -277
  227. package/src/core/bundle-refresh.ts +0 -1064
  228. package/src/core/bundle.ts +0 -326
  229. package/src/core/config.ts +0 -405
  230. package/src/core/git.ts +0 -768
  231. package/src/core/github-review.ts +0 -761
  232. package/src/core/github.ts +0 -151
  233. package/src/core/identity.ts +0 -631
  234. package/src/core/linear.ts +0 -403
  235. package/src/core/preferences-service.ts +0 -17
  236. package/src/core/project-catalog.ts +0 -52
  237. package/src/core/project-lifecycle.ts +0 -163
  238. package/src/core/review-executor.ts +0 -316
  239. package/src/core/review.ts +0 -407
  240. package/src/core/secret-runtime.ts +0 -167
  241. package/src/core/shell.ts +0 -117
  242. package/src/core/trusted-relays.ts +0 -315
  243. package/src/core/workspace-lifecycle.ts +0 -216
  244. package/src/core/workspace.ts +0 -363
  245. package/src/hooks/__tests__/useLocalSession.tui.test.ts +0 -557
  246. package/src/hooks/index.ts +0 -8
  247. package/src/hooks/index.tui.ts +0 -32
  248. package/src/hooks/useDaemonStatus.tui.ts +0 -174
  249. package/src/hooks/useLocalSession.tui.ts +0 -395
  250. package/src/hooks/useRelayConnection.web.ts +0 -54
  251. package/src/hooks/useRemoteMachines.tui.ts +0 -166
  252. package/src/hooks/useRemoteTerminal.tui.ts +0 -22
  253. package/src/hooks/useReview.web.ts +0 -248
  254. package/src/hooks/useTerminal.web.ts +0 -36
  255. package/src/hooks/useUserActivity.ts +0 -61
  256. package/src/hooks/useVisualViewport.web.ts +0 -104
  257. package/src/index.ts +0 -1376
  258. package/src/lib/events/__tests__/collector-filter.test.ts +0 -105
  259. package/src/lib/events/__tests__/store-query.test.ts +0 -103
  260. package/src/lib/events/collector.ts +0 -494
  261. package/src/lib/events/filters.ts +0 -26
  262. package/src/lib/events/index.ts +0 -11
  263. package/src/lib/events/indexer.ts +0 -14
  264. package/src/lib/events/paths.ts +0 -69
  265. package/src/lib/events/reader.ts +0 -212
  266. package/src/lib/events/store.ts +0 -141
  267. package/src/lib/invite.web.ts +0 -58
  268. package/src/lib/preferences-service.web.ts +0 -41
  269. package/src/lib/processes/__tests__/config.test.ts +0 -83
  270. package/src/lib/processes/__tests__/names.test.ts +0 -125
  271. package/src/lib/processes/__tests__/schema.test.ts +0 -208
  272. package/src/lib/processes/__tests__/watchdog.test.ts +0 -210
  273. package/src/lib/processes/autostart.ts +0 -16
  274. package/src/lib/processes/config.ts +0 -187
  275. package/src/lib/processes/control.ts +0 -53
  276. package/src/lib/processes/editor.ts +0 -32
  277. package/src/lib/processes/events-config.ts +0 -37
  278. package/src/lib/processes/index.ts +0 -14
  279. package/src/lib/processes/instances.ts +0 -20
  280. package/src/lib/processes/manager.ts +0 -131
  281. package/src/lib/processes/names.ts +0 -71
  282. package/src/lib/processes/registry.ts +0 -26
  283. package/src/lib/processes/runner.ts +0 -211
  284. package/src/lib/processes/scheduler.ts +0 -17
  285. package/src/lib/processes/schema.ts +0 -74
  286. package/src/lib/processes/session-list.ts +0 -15
  287. package/src/lib/processes/state.ts +0 -82
  288. package/src/lib/processes/watchdog.test.ts +0 -79
  289. package/src/lib/processes/watchdog.ts +0 -106
  290. package/src/lib/remote-session/__tests__/protocol.test.ts +0 -291
  291. package/src/lib/remote-session/index.ts +0 -7
  292. package/src/lib/remote-session/protocol.ts +0 -443
  293. package/src/lib/remote-session/session-handler.ts +0 -1298
  294. package/src/lib/remote-session/workspace-scanner.ts +0 -161
  295. package/src/lib/sonner.web.ts +0 -1
  296. package/src/lib/storage/identity-store.web.ts +0 -94
  297. package/src/lib/tmux-lite/README.md +0 -81
  298. package/src/lib/tmux-lite/cli.ts +0 -855
  299. package/src/lib/tmux-lite/crypto/__tests__/helpers/handshake-runner.ts +0 -349
  300. package/src/lib/tmux-lite/crypto/__tests__/helpers/mock-relay.ts +0 -291
  301. package/src/lib/tmux-lite/crypto/__tests__/helpers/test-identities.ts +0 -142
  302. package/src/lib/tmux-lite/crypto/__tests__/integration/authorization.integration.test.ts +0 -339
  303. package/src/lib/tmux-lite/crypto/__tests__/integration/e2e-communication.integration.test.ts +0 -477
  304. package/src/lib/tmux-lite/crypto/__tests__/integration/error-handling.integration.test.ts +0 -499
  305. package/src/lib/tmux-lite/crypto/__tests__/integration/handshake.integration.test.ts +0 -371
  306. package/src/lib/tmux-lite/crypto/__tests__/integration/security.integration.test.ts +0 -573
  307. package/src/lib/tmux-lite/crypto/access-control.test.ts +0 -512
  308. package/src/lib/tmux-lite/crypto/access-control.ts +0 -320
  309. package/src/lib/tmux-lite/crypto/frames.test.ts +0 -262
  310. package/src/lib/tmux-lite/crypto/frames.ts +0 -141
  311. package/src/lib/tmux-lite/crypto/handshake.ts +0 -894
  312. package/src/lib/tmux-lite/crypto/identity.test.ts +0 -220
  313. package/src/lib/tmux-lite/crypto/identity.ts +0 -286
  314. package/src/lib/tmux-lite/crypto/index.ts +0 -51
  315. package/src/lib/tmux-lite/crypto/invites.test.ts +0 -381
  316. package/src/lib/tmux-lite/crypto/invites.ts +0 -215
  317. package/src/lib/tmux-lite/crypto/keyexchange.ts +0 -435
  318. package/src/lib/tmux-lite/crypto/keys.test.ts +0 -58
  319. package/src/lib/tmux-lite/crypto/keys.ts +0 -47
  320. package/src/lib/tmux-lite/crypto/secretbox.test.ts +0 -169
  321. package/src/lib/tmux-lite/crypto/secretbox.ts +0 -124
  322. package/src/lib/tmux-lite/handshake-handler.ts +0 -451
  323. package/src/lib/tmux-lite/process-run.integration.test.ts +0 -266
  324. package/src/lib/tmux-lite/protocol.test.ts +0 -307
  325. package/src/lib/tmux-lite/protocol.ts +0 -291
  326. package/src/lib/tmux-lite/relay-client.ts +0 -506
  327. package/src/lib/tmux-lite/server-lifecycle.test.ts +0 -212
  328. package/src/lib/tmux-lite/server.ts +0 -1412
  329. package/src/lib/tmux-lite/shell-integration.sh +0 -37
  330. package/src/lib/tmux-lite/terminal-queries.test.ts +0 -54
  331. package/src/lib/tmux-lite/terminal-queries.ts +0 -49
  332. package/src/notifications/__tests__/useNotifications.test.ts +0 -739
  333. package/src/notifications/index.ts +0 -32
  334. package/src/notifications/policy.test.ts +0 -424
  335. package/src/notifications/policy.ts +0 -139
  336. package/src/notifications/types.ts +0 -82
  337. package/src/notifications/useNotifications.ts +0 -350
  338. package/src/pages/ReviewPage.web.tsx +0 -511
  339. package/src/preferences/index.ts +0 -1
  340. package/src/preferences/types.ts +0 -9
  341. package/src/relay/__tests__/e2e-flow.test.ts +0 -1284
  342. package/src/relay/__tests__/helpers/auth.ts +0 -354
  343. package/src/relay/__tests__/helpers/ports.ts +0 -51
  344. package/src/relay/__tests__/protocol-validation.test.ts +0 -265
  345. package/src/relay/authorization.ts +0 -303
  346. package/src/relay/embedded-assets.generated.d.ts +0 -15
  347. package/src/relay/identity.ts +0 -352
  348. package/src/relay/index.ts +0 -57
  349. package/src/relay/pipes.test.ts +0 -427
  350. package/src/relay/pipes.ts +0 -195
  351. package/src/relay/protocol.ts +0 -804
  352. package/src/relay/registries.test.ts +0 -437
  353. package/src/relay/registries.ts +0 -593
  354. package/src/relay/server.test.ts +0 -1323
  355. package/src/relay/server.ts +0 -1128
  356. package/src/relay/signing.ts +0 -238
  357. package/src/relay/types.ts +0 -69
  358. package/src/relay-client/__tests__/machine-directory-client.test.ts +0 -152
  359. package/src/relay-client/__tests__/useMachineDirectory.test.ts +0 -172
  360. package/src/relay-client/adapters/browser.ts +0 -27
  361. package/src/relay-client/adapters/node.ts +0 -29
  362. package/src/relay-client/index.ts +0 -33
  363. package/src/relay-client/machine-directory-client.ts +0 -244
  364. package/src/relay-client/useMachineDirectory.ts +0 -175
  365. package/src/serve/client-session-manager.ts +0 -635
  366. package/src/serve/daemon.ts +0 -497
  367. package/src/serve/pty-session.ts +0 -236
  368. package/src/serve/types.ts +0 -174
  369. package/src/session/__tests__/backend-manager.test.ts +0 -101
  370. package/src/session/__tests__/local-session-backend.test.ts +0 -1129
  371. package/src/session/__tests__/reducer.test.ts +0 -80
  372. package/src/session/__tests__/remote-session-backend.test.ts +0 -995
  373. package/src/session/__tests__/session-name.test.ts +0 -35
  374. package/src/session/__tests__/useBundleRefreshAttachFlow.test.ts +0 -431
  375. package/src/session/__tests__/useRemoteSessionClient.test.ts +0 -424
  376. package/src/session/__tests__/workspace-shell-hooks.integration.test.ts +0 -268
  377. package/src/session/__tests__/workspace-shell-hooks.test.ts +0 -24
  378. package/src/session/adapters/browser-remote.ts +0 -101
  379. package/src/session/adapters/node-remote.ts +0 -135
  380. package/src/session/backend-key.ts +0 -5
  381. package/src/session/backend-manager.ts +0 -80
  382. package/src/session/backend.ts +0 -93
  383. package/src/session/backends/local-session-backend.ts +0 -1119
  384. package/src/session/backends/remote-session-backend.ts +0 -1378
  385. package/src/session/crypto/__tests__/web-terminal.test.ts +0 -1158
  386. package/src/session/crypto/frames.web.ts +0 -205
  387. package/src/session/crypto/handshake.web.ts +0 -396
  388. package/src/session/crypto/identity.web.ts +0 -133
  389. package/src/session/crypto/keyexchange.web.ts +0 -246
  390. package/src/session/crypto/relay-signing.web.ts +0 -53
  391. package/src/session/events.ts +0 -38
  392. package/src/session/index.ts +0 -116
  393. package/src/session/reducer.ts +0 -274
  394. package/src/session/selectors.ts +0 -28
  395. package/src/session/session-name.ts +0 -50
  396. package/src/session/types.ts +0 -101
  397. package/src/session/useBundleRefreshAttachFlow.ts +0 -608
  398. package/src/session/useRemoteSessionClient.ts +0 -424
  399. package/src/session/useSessionEngine.ts +0 -432
  400. package/src/session/workspace-shell-hooks.ts +0 -35
  401. package/src/tui/__tests__/input-text.test.ts +0 -24
  402. package/src/tui/__tests__/local-terminal-sync.test.ts +0 -82
  403. package/src/tui/__tests__/session-terminal-page-navigation.test.ts +0 -94
  404. package/src/tui/app.tsx +0 -2
  405. package/src/tui/index.ts +0 -18
  406. package/src/tui/input-text.ts +0 -38
  407. package/src/tui/local-terminal-sync.ts +0 -41
  408. package/src/types/bundle-refresh.ts +0 -42
  409. package/src/types/bundle.ts +0 -130
  410. package/src/types/config.ts +0 -287
  411. package/src/types/errors.ts +0 -292
  412. package/src/types/events.ts +0 -91
  413. package/src/types/identity.ts +0 -284
  414. package/src/types/processes.ts +0 -45
  415. package/src/types/review.ts +0 -349
  416. package/src/types/script-phase.ts +0 -3
  417. package/src/types/workspace-fuzzy.ts +0 -49
  418. package/src/types/workspace.ts +0 -151
  419. package/src/utils/__tests__/onboarding.test.ts +0 -358
  420. package/src/utils/__tests__/run-scripts.test.ts +0 -535
  421. package/src/utils/__tests__/run-workspace-scripts.test.ts +0 -406
  422. package/src/utils/__tests__/workspace-setup.integration.test.ts +0 -633
  423. package/src/utils/__tests__/workspace-state.test.ts +0 -78
  424. package/src/utils/bun-socket-writer.ts +0 -80
  425. package/src/utils/clipboard.ts +0 -53
  426. package/src/utils/deps.test.ts +0 -31
  427. package/src/utils/deps.ts +0 -145
  428. package/src/utils/device.web.ts +0 -163
  429. package/src/utils/fuzzy-match.ts +0 -125
  430. package/src/utils/hostnames.ts +0 -43
  431. package/src/utils/hunk-header.ts +0 -17
  432. package/src/utils/id.ts +0 -9
  433. package/src/utils/logger.ts +0 -127
  434. package/src/utils/markdown.ts +0 -254
  435. package/src/utils/normalize-env-key.ts +0 -13
  436. package/src/utils/onboarding.ts +0 -279
  437. package/src/utils/prompts.ts +0 -176
  438. package/src/utils/run-commands.ts +0 -112
  439. package/src/utils/run-scripts.ts +0 -337
  440. package/src/utils/run-workspace-scripts.ts +0 -355
  441. package/src/utils/sanitize.test.ts +0 -149
  442. package/src/utils/sanitize.ts +0 -162
  443. package/src/utils/secrets.ts +0 -836
  444. package/src/utils/shell-escape.ts +0 -40
  445. package/src/utils/utf8.ts +0 -79
  446. package/src/utils/workspace-id.ts +0 -55
  447. package/src/utils/workspace-state.ts +0 -427
  448. package/src/version.generated.d.ts +0 -2
  449. package/todo-security.md +0 -92
  450. package/tsconfig.json +0 -29
  451. package/web/README.md +0 -73
  452. package/web/bun.lock +0 -675
  453. package/web/eslint.config.js +0 -23
  454. package/web/index.css +0 -249
  455. package/web/index.html +0 -16
  456. package/web/main.tsx +0 -10
  457. package/web/package.json +0 -39
  458. package/web/public/vite.svg +0 -1
  459. package/web/tsconfig.app.json +0 -35
  460. package/web/tsconfig.json +0 -7
  461. package/web/tsconfig.node.json +0 -26
  462. package/web/vite.config.ts +0 -39
  463. package/worker/bun.lock +0 -237
  464. package/worker/package.json +0 -22
  465. package/worker/schema.sql +0 -96
  466. package/worker/src/handlers/auth.ts +0 -451
  467. package/worker/src/handlers/subdomains.ts +0 -376
  468. package/worker/src/handlers/user.ts +0 -98
  469. package/worker/src/index.ts +0 -70
  470. package/worker/src/middleware/auth.ts +0 -152
  471. package/worker/src/services/cloudflare.ts +0 -609
  472. package/worker/src/types.ts +0 -96
  473. package/worker/tsconfig.json +0 -15
  474. package/worker/wrangler.toml +0 -26
@@ -1,1412 +0,0 @@
1
- #!/usr/bin/env bun
2
- // @ts-nocheck - Uses Bun-specific APIs (Bun.Terminal, etc.)
3
- /**
4
- * tmux-lite server - manages all sessions in a single process
5
- * Uses xterm-headless for proper terminal state tracking
6
- */
7
-
8
- import { existsSync, mkdirSync, unlinkSync, writeFileSync } from "fs";
9
- import { dirname } from "path";
10
- import { Terminal as XTerminal } from "@xterm/headless";
11
- import { SerializeAddon } from "@xterm/addon-serialize";
12
- import { createBufferedSocketWriter } from "../../utils/bun-socket-writer";
13
- import { installDsrCprResponder } from "./terminal-queries";
14
- import { getNotificationConfig, type NotificationConfig } from "../../core/config.js";
15
- import { DEFAULT_NOTIFICATION_CONFIG } from "../../types/config.js";
16
- import {
17
- getRouterSocket,
18
- getSessionSocketPath,
19
- getPidFile,
20
- PROTOCOL_VERSION,
21
- PACKAGE_VERSION,
22
- type Command,
23
- type Response,
24
- type Session,
25
- type SessionCtrl,
26
- type InboxItem,
27
- type SessionCreateHooks,
28
- encodeRouterMessage,
29
- decodeRouterMessages,
30
- encodePTY,
31
- encodeControl,
32
- parseFrames,
33
- decodeControl,
34
- FrameType,
35
- MAX_FRAME_SIZE,
36
- } from "./protocol";
37
-
38
- // Chunk size for large PTY data (leave room for frame header overhead)
39
- // Using 512KB to be well under the 1MB limit
40
- const PTY_CHUNK_SIZE = 512 * 1024;
41
-
42
- // Max scrollback lines to include in serialized state during attach
43
- // This is a limit - if less scrollback exists, we'll send what's available
44
- const SERIALIZE_SCROLLBACK_LINES = 10_000;
45
-
46
- const rawArgs = process.argv.slice(2);
47
- if (rawArgs.includes("--test")) {
48
- process.env.TMUX_LITE_SOCKET = "/tmp/tmux-lite-test.sock";
49
- process.env.TMUX_LITE_SESSION_DIR = "/tmp/tmux-lite-test";
50
- process.env.TMUX_LITE_PID_FILE = "/tmp/tmux-lite-test.pid";
51
- }
52
-
53
- const ROUTER_SOCKET = getRouterSocket();
54
- const PID_FILE = getPidFile();
55
- const SERVER_START_TIME = Date.now();
56
-
57
- // Load notification config (with fallback to defaults)
58
- let notificationConfig: NotificationConfig;
59
- try {
60
- notificationConfig = getNotificationConfig();
61
- } catch {
62
- // If config can't be loaded (e.g., gitspace not initialized), use defaults
63
- notificationConfig = { ...DEFAULT_NOTIFICATION_CONFIG };
64
- }
65
-
66
- /**
67
- * Check if a notification type is enabled
68
- */
69
- function isNotificationTypeEnabled(type: InboxItem['type']): boolean {
70
- if (!notificationConfig.enabled) return false;
71
-
72
- switch (type) {
73
- case 'exit':
74
- return notificationConfig.types.exit;
75
- case 'idle':
76
- return notificationConfig.types.idle;
77
- case 'bell':
78
- return notificationConfig.types.bell;
79
- case 'title':
80
- return notificationConfig.types.title;
81
- case 'osc':
82
- return notificationConfig.types.osc;
83
- default:
84
- return notificationConfig.types.osc;
85
- }
86
- }
87
-
88
- // Clean up old socket
89
- try { unlinkSync(ROUTER_SOCKET); } catch {}
90
-
91
- // Write PID file
92
- writeFileSync(PID_FILE, String(process.pid));
93
-
94
- interface SessionData {
95
- info: Session;
96
- ptyTerminal: Bun.Terminal;
97
- xterm: XTerminal;
98
- serialize: SerializeAddon;
99
- proc: Bun.Subprocess;
100
- client: any;
101
- clientWriter: any;
102
- ctrlBuffer: Buffer;
103
- pendingWrites: number; // Track pending xterm writes
104
- attaching: boolean;
105
- attachBuffer: Buffer[];
106
- attachPending: boolean;
107
- attachTimer: any;
108
- processTitle: string; // Title set by running process (via OSC 0)
109
- lastInteraction: number; // Timestamp of last user input
110
- lastDetached: number; // Timestamp of last detach (for grace period)
111
- lastAttached: number; // Timestamp of last attach (for grace period)
112
- }
113
-
114
- const sessions = new Map<string, SessionData>();
115
- const inbox: InboxItem[] = [];
116
-
117
- function writeToClient(session: SessionData, data: Buffer): void {
118
- if (!session.client) return;
119
- if (session.clientWriter) {
120
- session.clientWriter.write(data);
121
- return;
122
- }
123
- session.client.write(data);
124
- }
125
-
126
- function flushClient(session: SessionData): void {
127
- if (session.clientWriter) session.clientWriter.flush();
128
- }
129
-
130
- // ============================================================================
131
- // Socket State Management
132
- // ============================================================================
133
-
134
- /**
135
- * Type-safe socket state manager using WeakMap.
136
- * This avoids mutating socket objects with `as any` casts.
137
- */
138
- interface RouterSocketState {
139
- buffer: Buffer;
140
- writer: any;
141
- }
142
-
143
- const routerSocketStates = new WeakMap<object, RouterSocketState>();
144
-
145
- function getRouterSocketState(socket: object): RouterSocketState {
146
- let state = routerSocketStates.get(socket);
147
- if (!state) {
148
- state = { buffer: Buffer.alloc(0), writer: null };
149
- routerSocketStates.set(socket, state);
150
- }
151
- return state;
152
- }
153
-
154
- function clearRouterSocketState(socket: object): void {
155
- routerSocketStates.delete(socket);
156
- }
157
-
158
- // How long after last interaction before we consider the user "inactive"
159
- const INTERACTION_TIMEOUT_MS = 30000; // 30 seconds
160
- // Grace period after attach/detach - don't notify immediately
161
- const ATTACH_GRACE_MS = 5000; // 5 seconds after attach
162
- const DETACH_GRACE_MS = 5000; // 5 seconds after detach
163
-
164
- // ============================================================================
165
- // OSC Pattern Registry
166
- // ============================================================================
167
-
168
- /**
169
- * Registry of OSC (Operating System Command) patterns for terminal notifications.
170
- * Each pattern matches specific escape sequences and extracts relevant data.
171
- */
172
- interface OscPattern {
173
- name: string;
174
- pattern: RegExp;
175
- /** Extract notification data from a match. Returns null to skip notification. */
176
- extract: (match: RegExpMatchArray, context: OscMatchContext) => OscNotificationData | null;
177
- }
178
-
179
- interface OscMatchContext {
180
- sessionId: string;
181
- sessionName: string;
182
- processTitle: string;
183
- xterm: XTerminal;
184
- now: number;
185
- }
186
-
187
- interface OscNotificationData {
188
- type: InboxItem['type'];
189
- context: string;
190
- exitCode?: number;
191
- }
192
-
193
- const OSC_PATTERNS: OscPattern[] = [
194
- {
195
- // Custom exit code: ESC ] 777 ; exit : <code> BEL
196
- name: 'exit',
197
- pattern: /\x1b\]777;exit:(-?\d+)\x07/g,
198
- extract: (match, ctx) => ({
199
- type: 'exit',
200
- exitCode: parseInt(match[1], 10),
201
- context: getCurrentLine(ctx.xterm) || `Exit code: ${match[1]}`,
202
- }),
203
- },
204
- {
205
- // iTerm2/Growl notification: ESC ] 9 ; message BEL
206
- name: 'osc9',
207
- pattern: /\x1b\]9;([^\x07]*)\x07/g,
208
- extract: (match) => match[1] ? { type: 'osc', context: match[1] } : null,
209
- },
210
- {
211
- // Kitty notification: ESC ] 99 ; i=id:d=0; body BEL (simplified)
212
- name: 'osc99',
213
- pattern: /\x1b\]99;[^;]*;([^\x07]*)\x07/g,
214
- extract: (match) => match[1] ? { type: 'osc', context: match[1] } : null,
215
- },
216
- {
217
- // rxvt notification: ESC ] 777 ; notify ; title ; body BEL
218
- name: 'osc777notify',
219
- pattern: /\x1b\]777;notify;([^;]*);([^\x07]*)\x07/g,
220
- extract: (match) => ({
221
- type: 'osc',
222
- context: match[2] || match[1] || 'Notification',
223
- }),
224
- },
225
- ];
226
-
227
- // Semantic shell integration patterns (OSC 133) - handled separately due to state tracking
228
- const OSC_133_DONE_PATTERN = /\x1b\]133;D(?:;(\d+))?\x07/g;
229
- const OSC_133_CMD_START = /\x1b\]133;C\x07/g;
230
-
231
- /**
232
- * Process OSC patterns in terminal output and create inbox notifications.
233
- */
234
- function processOscPatterns(
235
- str: string,
236
- ctx: OscMatchContext,
237
- addNotification: (data: OscNotificationData) => void
238
- ): void {
239
- for (const { name, pattern, extract } of OSC_PATTERNS) {
240
- // Reset lastIndex for global patterns
241
- pattern.lastIndex = 0;
242
- const matches = [...str.matchAll(pattern)];
243
- for (const match of matches) {
244
- const data = extract(match, ctx);
245
- if (data) {
246
- addNotification(data);
247
- console.log(`[${ctx.sessionName}] ${name} notification: ${data.context.substring(0, 50)}`);
248
- }
249
- }
250
- }
251
- }
252
-
253
- // ============================================================================
254
- // Inbox Notification Helpers
255
- // ============================================================================
256
-
257
- /**
258
- * Creates an inbox item with common fields populated.
259
- */
260
- function createInboxNotification(
261
- sessionId: string,
262
- sessionName: string,
263
- type: InboxItem['type'],
264
- context: string,
265
- processTitle?: string,
266
- exitCode?: number
267
- ): Omit<InboxItem, 'id' | 'read'> {
268
- return {
269
- sessionId,
270
- sessionName,
271
- type,
272
- timestamp: Date.now(),
273
- context,
274
- processTitle,
275
- exitCode,
276
- };
277
- }
278
-
279
- // Check if user is actively using the session or recently attached/detached
280
- // Returns true if we should SUPPRESS notifications
281
- function isActivelyUsing(session: SessionData | undefined): boolean {
282
- if (!session) return false;
283
-
284
- const now = Date.now();
285
-
286
- // If recently detached, still suppress notifications (grace period)
287
- if (session.lastDetached > 0) {
288
- const timeSinceDetach = now - session.lastDetached;
289
- if (timeSinceDetach < DETACH_GRACE_MS) {
290
- return true; // Suppress - just detached
291
- }
292
- }
293
-
294
- // If not attached, don't suppress (unless in grace period above)
295
- if (!session.info.attached) return false;
296
-
297
- // If recently attached, suppress notifications (startup grace period)
298
- if (session.lastAttached > 0) {
299
- const timeSinceAttach = now - session.lastAttached;
300
- if (timeSinceAttach < ATTACH_GRACE_MS) {
301
- return true; // Suppress - just attached
302
- }
303
- }
304
-
305
- // If attached but never interacted AND past the attach grace period, don't suppress
306
- if (session.lastInteraction === 0) return false;
307
-
308
- // If attached and recently interacted, suppress
309
- const timeSinceInteraction = now - session.lastInteraction;
310
- return timeSinceInteraction < INTERACTION_TIMEOUT_MS;
311
- }
312
-
313
- let sessionCounter = 0;
314
- let inboxCounter = 0;
315
-
316
- function genId(): string {
317
- return String(sessionCounter++);
318
- }
319
-
320
- function genInboxId(): string {
321
- return String(inboxCounter++);
322
- }
323
-
324
- function addInboxItem(item: Omit<InboxItem, 'id' | 'read'>): void {
325
- // Check if this notification type is enabled in config
326
- if (!isNotificationTypeEnabled(item.type)) {
327
- return;
328
- }
329
-
330
- inbox.push({
331
- ...item,
332
- id: genInboxId(),
333
- read: false,
334
- });
335
- console.log(`[inbox] ${item.type}: ${item.sessionName} - ${item.context.substring(0, 50)}`);
336
-
337
- // Update titles for all attached sessions to show new inbox count
338
- broadcastTitleUpdate();
339
- }
340
-
341
- /**
342
- * Prune inbox items for a destroyed session.
343
- * This removes all notifications associated with a session when it exits,
344
- * keeping the inbox clean and ensuring the count only reflects active sessions.
345
- */
346
- function pruneInboxForSession(sessionId: string): void {
347
- // Find and remove all inbox items for this session
348
- let i = inbox.length;
349
- while (i--) {
350
- if (inbox[i].sessionId === sessionId) {
351
- inbox.splice(i, 1);
352
- }
353
- }
354
- console.log(`[inbox] Pruned notifications for session ${sessionId}`);
355
- }
356
-
357
- function getLastLines(xterm: XTerminal, count: number): string {
358
- const buffer = xterm.buffer.active;
359
- const lines: string[] = [];
360
- const startRow = Math.max(0, buffer.cursorY - count + 1);
361
-
362
- for (let i = startRow; i <= buffer.cursorY; i++) {
363
- const line = buffer.getLine(i)?.translateToString(true);
364
- if (line) lines.push(line);
365
- }
366
-
367
- return lines.join('\n').trim();
368
- }
369
-
370
- function getCurrentLine(xterm: XTerminal): string {
371
- const buffer = xterm.buffer.active;
372
- return buffer.getLine(buffer.cursorY)?.translateToString(true)?.trim() || '';
373
- }
374
-
375
- /**
376
- * Get count of unread inbox items, bounded by active sessions.
377
- * Returns the number of unique active sessions that have unread notifications,
378
- * not the total number of unread items. This prevents the count from growing
379
- * unboundedly (e.g., to 3000) and instead caps it at one per active session.
380
- */
381
- function getUnreadInboxCount(): number {
382
- // Get unique session IDs that have unread items AND are still active
383
- const activeSessionsWithUnread = new Set<string>();
384
-
385
- for (const item of inbox) {
386
- if (!item.read && sessions.has(item.sessionId)) {
387
- activeSessionsWithUnread.add(item.sessionId);
388
- }
389
- }
390
-
391
- return activeSessionsWithUnread.size;
392
- }
393
-
394
- function buildTitle(sessionName: string, processTitle?: string): string {
395
- const unread = getUnreadInboxCount();
396
- let title = `tl: ${sessionName}`;
397
-
398
- if (processTitle) {
399
- title += ` | ${processTitle}`;
400
- }
401
-
402
- if (unread > 0) {
403
- title += ` (${unread} 🔔)`;
404
- }
405
-
406
- return title;
407
- }
408
-
409
- function sendTitle(session: SessionData, sessionName: string, processTitle?: string): void {
410
- if (!session.client) return;
411
- const title = buildTitle(sessionName, processTitle);
412
- // OSC 0 sets both icon and window title - must be framed!
413
- writeToClient(session, encodePTY(Buffer.from(`\x1b]0;${title}\x07`)));
414
- }
415
-
416
- function broadcastTitleUpdate(): void {
417
- // Update title for all attached sessions
418
- for (const [id, session] of sessions) {
419
- if (session.client) {
420
- sendTitle(session, session.info.name, session.processTitle);
421
- }
422
- }
423
- }
424
-
425
- // RIS (Reset to Initial State) - the nuclear option that resets everything
426
- const TERM_RESET = Buffer.from("\x1bc");
427
-
428
- // ============================================================================
429
- // Session Helper Functions
430
- // ============================================================================
431
-
432
- /**
433
- * Configuration for idle detection in a session.
434
- */
435
- interface IdleDetectionState {
436
- lastOutputTime: number;
437
- outputSinceIdle: number;
438
- idleTimer: ReturnType<typeof setTimeout> | null;
439
- }
440
-
441
- const IDLE_THRESHOLD_MS = 10000; // 10 seconds of quiet after output
442
- const MIN_OUTPUT_FOR_IDLE = 500; // Need at least 500 bytes of output to consider "activity"
443
-
444
- /**
445
- * Creates the idle detection check function for a session.
446
- */
447
- function createIdleChecker(
448
- id: string,
449
- sessionName: string,
450
- xterm: XTerminal,
451
- idleState: IdleDetectionState,
452
- getProcessTitle: () => string
453
- ): () => void {
454
- return () => {
455
- const session = sessions.get(id);
456
- // Only notify if: not actively using, had significant output, and now idle
457
- if (!isActivelyUsing(session) && idleState.outputSinceIdle >= MIN_OUTPUT_FOR_IDLE) {
458
- const context = getLastLines(xterm, 3) || '(idle)';
459
- addInboxItem(createInboxNotification(
460
- id,
461
- sessionName,
462
- 'idle',
463
- context,
464
- session?.processTitle || getProcessTitle()
465
- ));
466
- console.log(`[${sessionName}] idle notification after ${idleState.outputSinceIdle} bytes output`);
467
- }
468
- idleState.outputSinceIdle = 0;
469
- };
470
- }
471
-
472
- /**
473
- * Sets up xterm event handlers for bell and title change notifications.
474
- */
475
- function setupXtermEventHandlers(
476
- id: string,
477
- sessionName: string,
478
- xterm: XTerminal
479
- ): { getProcessTitle: () => string; setProcessTitle: (title: string) => void } {
480
- let processTitle = '';
481
- let lastBellTime = 0;
482
- let lastTitleNotification = 0;
483
-
484
- // Track bells for inbox notifications (with debounce)
485
- xterm.onBell(() => {
486
- const session = sessions.get(id);
487
- // Don't notify if user is actively using the session
488
- if (isActivelyUsing(session)) return;
489
-
490
- const now = Date.now();
491
- // Debounce: ignore bells within 500ms of each other
492
- if (now - lastBellTime < 500) return;
493
- lastBellTime = now;
494
-
495
- // Get last few lines for context (not just current line)
496
- const context = getLastLines(xterm, 3) || getCurrentLine(xterm) || '(bell)';
497
- addInboxItem(createInboxNotification(
498
- id,
499
- sessionName,
500
- 'bell',
501
- context,
502
- session?.processTitle
503
- ));
504
- });
505
-
506
- // Track title changes from running processes
507
- xterm.onTitleChange((title) => {
508
- console.log(`[${sessionName}] title changed: "${title}"`);
509
- const previousTitle = processTitle;
510
- processTitle = title;
511
- const session = sessions.get(id);
512
- if (session) {
513
- session.processTitle = title;
514
- // Update client's terminal title if attached
515
- if (session.client) {
516
- sendTitle(session.client, sessionName, title);
517
- }
518
-
519
- // Create inbox notification for ANY title change when not actively using
520
- // This helps track when background processes change state
521
- const now = Date.now();
522
- if (!isActivelyUsing(session) && title && title !== previousTitle) {
523
- // Debounce: don't notify more than once per 3 seconds
524
- if (now - lastTitleNotification > 3000) {
525
- lastTitleNotification = now;
526
- addInboxItem(createInboxNotification(
527
- id,
528
- sessionName,
529
- 'title',
530
- title,
531
- title
532
- ));
533
- console.log(`[${sessionName}] title change: ${previousTitle} -> ${title}`);
534
- }
535
- }
536
- }
537
- });
538
-
539
- return {
540
- getProcessTitle: () => processTitle,
541
- setProcessTitle: (title: string) => { processTitle = title; },
542
- };
543
- }
544
-
545
- /**
546
- * State for tracking OSC 133 shell integration commands.
547
- */
548
- interface Osc133State {
549
- commandRunning: boolean;
550
- commandStartTime: number; // Timestamp when command started (for duration filter)
551
- }
552
-
553
- /**
554
- * Creates the PTY data handler that processes terminal output.
555
- */
556
- function createPtyDataHandler(
557
- id: string,
558
- sessionName: string,
559
- xterm: XTerminal,
560
- idleState: IdleDetectionState,
561
- osc133State: Osc133State,
562
- checkIdle: () => void,
563
- getProcessTitle: () => string
564
- ): (term: Bun.Terminal, data: Buffer) => void {
565
- return (term, data) => {
566
- // Track output for idle detection
567
- idleState.lastOutputTime = Date.now();
568
- idleState.outputSinceIdle += data.length;
569
-
570
- // Reset idle timer
571
- if (idleState.idleTimer) clearTimeout(idleState.idleTimer);
572
- idleState.idleTimer = setTimeout(checkIdle, IDLE_THRESHOLD_MS);
573
-
574
- const session = sessions.get(id);
575
- if (!session) return;
576
-
577
- const str = data.toString();
578
- const now = Date.now();
579
-
580
- // Only create inbox notifications if user is not actively using the session
581
- const activelyUsing = session.attaching || isActivelyUsing(session);
582
- const currentProcessTitle = session.processTitle || getProcessTitle();
583
-
584
- // Process OSC patterns for notifications (only if not actively using)
585
- if (!activelyUsing) {
586
- const oscContext: OscMatchContext = {
587
- sessionId: id,
588
- sessionName,
589
- processTitle: currentProcessTitle,
590
- xterm,
591
- now,
592
- };
593
-
594
- processOscPatterns(str, oscContext, (notifData) => {
595
- addInboxItem(createInboxNotification(
596
- id,
597
- sessionName,
598
- notifData.type,
599
- notifData.context,
600
- currentProcessTitle,
601
- notifData.exitCode
602
- ));
603
- });
604
- }
605
-
606
- // Check for semantic shell integration (OSC 133)
607
- // Command start
608
- if (OSC_133_CMD_START.test(str)) {
609
- osc133State.commandRunning = true;
610
- osc133State.commandStartTime = now;
611
- OSC_133_CMD_START.lastIndex = 0; // Reset regex state
612
- }
613
-
614
- // Command done - only notify if not actively using and command was running
615
- OSC_133_DONE_PATTERN.lastIndex = 0;
616
- const osc133DoneMatches = [...str.matchAll(OSC_133_DONE_PATTERN)];
617
- for (const match of osc133DoneMatches) {
618
- const exitCode = match[1] ? parseInt(match[1], 10) : 0;
619
- const commandDuration = osc133State.commandStartTime > 0
620
- ? now - osc133State.commandStartTime
621
- : 0;
622
-
623
- // Only notify for background sessions if:
624
- // - Non-zero exit (always notify on errors)
625
- // - OR command duration >= minCommandDurationMs
626
- const shouldNotify = !activelyUsing && (
627
- exitCode !== 0 ||
628
- (osc133State.commandRunning && commandDuration >= notificationConfig.minCommandDurationMs)
629
- );
630
-
631
- if (shouldNotify) {
632
- const context = getLastLines(xterm, 2) || `Command finished (exit ${exitCode})`;
633
- addInboxItem(createInboxNotification(
634
- id,
635
- sessionName,
636
- exitCode !== 0 ? 'exit' : 'osc',
637
- context,
638
- currentProcessTitle,
639
- exitCode !== 0 ? exitCode : undefined
640
- ));
641
- console.log(`[${sessionName}] OSC 133 command done: exit ${exitCode}, duration ${commandDuration}ms`);
642
- }
643
- osc133State.commandRunning = false;
644
- osc133State.commandStartTime = 0;
645
- }
646
-
647
- // Pass original data through unchanged to preserve all escape sequences
648
- // Our custom OSC 777 exit sequences are harmless - terminals ignore unknown OSC
649
- // Converting to string and back was corrupting cursor movement/screen control sequences
650
-
651
- if (session.attaching) {
652
- session.attachBuffer.push(Buffer.from(data));
653
- return;
654
- }
655
-
656
- // Feed data to xterm-headless for state tracking
657
- session.pendingWrites++;
658
- xterm.write(data, () => {
659
- session.pendingWrites--;
660
- });
661
-
662
- // Send to client (buffered - avoid framed protocol desync on backpressure)
663
- writeToClient(session, encodePTY(data));
664
- };
665
- }
666
-
667
- /**
668
- * Handles process exit and cleanup for a session.
669
- */
670
- function handleProcessExit(
671
- id: string,
672
- sessionName: string,
673
- xterm: XTerminal,
674
- socketPath: string,
675
- disposeDsr: () => void,
676
- getProcessTitle: () => string
677
- ): (code: number) => void {
678
- return (code) => {
679
- const session = sessions.get(id);
680
-
681
- // Clean up parser hooks
682
- try { disposeDsr(); } catch {}
683
-
684
- // Prune old inbox items for this session so inbox stays bounded to active sessions.
685
- // Do this before adding the final exit notification so the user still sees the exit event.
686
- pruneInboxForSession(id);
687
-
688
- // Capture last lines for inbox before disposing xterm
689
- const context = getLastLines(xterm, 3);
690
- addInboxItem(createInboxNotification(
691
- id,
692
- sessionName,
693
- 'exit',
694
- context || `Session ended (exit ${code})`,
695
- session?.processTitle || getProcessTitle(),
696
- code
697
- ));
698
-
699
- // Update session info with exit code
700
- if (session) {
701
- session.info.exitCode = code;
702
- }
703
-
704
- if (session?.client) {
705
- writeToClient(session, encodeControl({ type: "exited", code }));
706
- session.client.end();
707
- }
708
-
709
- xterm.dispose();
710
- try { unlinkSync(socketPath); } catch {}
711
- sessions.delete(id);
712
- console.log(`[${sessionName}] exited (${code})`);
713
- };
714
- }
715
-
716
- /**
717
- * Sends cursor visibility and style state to the client.
718
- */
719
- function sendCursorState(session: SessionData): void {
720
- // Access xterm internal API for cursor hidden state
721
- // Note: _core is not part of the public API but is stable
722
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
723
- const xtermInternal = session.xterm as { _core?: { coreService?: { isCursorHidden?: boolean } } };
724
- const isCursorHidden = xtermInternal._core?.coreService?.isCursorHidden;
725
- if (typeof isCursorHidden === "boolean") {
726
- writeToClient(session, encodePTY(Buffer.from(isCursorHidden ? "\x1b[?25l" : "\x1b[?25h")));
727
- }
728
-
729
- const cursorStyle = session.xterm.options.cursorStyle;
730
- const cursorBlink = session.xterm.options.cursorBlink;
731
- let cursorStyleParam: number | null = null;
732
- if (cursorStyle === "block") {
733
- cursorStyleParam = cursorBlink ? 2 : 1;
734
- } else if (cursorStyle === "underline") {
735
- cursorStyleParam = cursorBlink ? 4 : 3;
736
- } else if (cursorStyle === "bar") {
737
- cursorStyleParam = cursorBlink ? 6 : 5;
738
- }
739
- if (cursorStyleParam !== null) {
740
- writeToClient(session, encodePTY(Buffer.from(`\x1b[${cursorStyleParam} q`)));
741
- }
742
- }
743
-
744
- /**
745
- * Clears the attach timer for a session.
746
- */
747
- function clearAttachTimer(session: SessionData): void {
748
- if (session.attachTimer) {
749
- clearTimeout(session.attachTimer);
750
- session.attachTimer = null;
751
- }
752
- }
753
-
754
- /**
755
- * Sends serialized terminal state to client during attach.
756
- */
757
- function sendSerializedState(session: SessionData, sessionName: string): void {
758
- // Debug mode: skip xterm serialization to test if it's the issue
759
- const skipSerialize = process.env.TMUX_LITE_SKIP_SERIALIZE === '1';
760
-
761
- try {
762
- // Send reset first to clear any bad modes
763
- console.log(`[${sessionName}] sending TERM_RESET`);
764
- writeToClient(session, encodePTY(TERM_RESET));
765
- writeToClient(session, encodePTY(Buffer.from("\x1b[2J\x1b[H"))); // clear + home
766
-
767
- if (!skipSerialize) {
768
- // Get serialized terminal state (including modes) for consistent redraws
769
- // Limit scrollback to prevent oversized payloads
770
- const serialized = session.serialize.serialize({
771
- scrollback: SERIALIZE_SCROLLBACK_LINES,
772
- });
773
- const serializedBytes = Buffer.from(serialized);
774
-
775
- // Log size for debugging
776
- const sizeKB = Math.round(serializedBytes.length / 1024);
777
- if (serializedBytes.length > PTY_CHUNK_SIZE) {
778
- console.log(`[${sessionName}] serialized ${serializedBytes.length} bytes (${sizeKB}KB) - will send in chunks`);
779
- } else {
780
- console.log(`[${sessionName}] serialized ${serializedBytes.length} bytes (${sizeKB}KB)`);
781
- }
782
-
783
- // Send in chunks if too large for a single frame
784
- if (serializedBytes.length > PTY_CHUNK_SIZE) {
785
- let offset = 0;
786
- let chunkNum = 0;
787
- while (offset < serializedBytes.length) {
788
- const chunkEnd = Math.min(offset + PTY_CHUNK_SIZE, serializedBytes.length);
789
- const chunk = serializedBytes.subarray(offset, chunkEnd);
790
- writeToClient(session, encodePTY(chunk));
791
- chunkNum++;
792
- offset = chunkEnd;
793
- }
794
- console.log(`[${sessionName}] attached (restored ${serializedBytes.length} bytes in ${chunkNum} chunks)`);
795
- } else {
796
- writeToClient(session, encodePTY(serializedBytes));
797
- console.log(`[${sessionName}] attached (restored ${serializedBytes.length} bytes)`);
798
- }
799
- } else {
800
- console.log(`[${sessionName}] attached (serialization skipped for debugging)`);
801
- }
802
- } catch (e) {
803
- console.log(`[${sessionName}] serialize error:`, e);
804
- // Fallback: just send a reset
805
- writeToClient(session, encodePTY(TERM_RESET));
806
- writeToClient(session, encodePTY(Buffer.from("\x1b[2J\x1b[H")));
807
- }
808
- }
809
-
810
- /**
811
- * Creates the startAttach function that handles the attach process.
812
- */
813
- function createStartAttach(sessionName: string): (session: SessionData) => void {
814
- return (session: SessionData) => {
815
- if (!session.attachPending || !session.client) return;
816
- session.attachPending = false;
817
- clearAttachTimer(session);
818
-
819
- // Wait for any pending xterm writes to complete
820
- const sendState = () => {
821
- if (session.pendingWrites > 0) {
822
- setTimeout(sendState, 10);
823
- return;
824
- }
825
-
826
- sendSerializedState(session, sessionName);
827
- sendCursorState(session);
828
-
829
- writeToClient(session, encodeControl({ type: "attach-ready", cols: session.xterm.cols, rows: session.xterm.rows }));
830
-
831
- const drainAttachBuffer = () => {
832
- const buffered = session.attachBuffer;
833
- session.attachBuffer = [];
834
- for (const chunk of buffered) {
835
- session.pendingWrites++;
836
- session.xterm.write(chunk, () => {
837
- session.pendingWrites--;
838
- });
839
- writeToClient(session, encodePTY(chunk));
840
- }
841
- };
842
-
843
- const attachStart = Date.now();
844
- const finalizeAttach = () => {
845
- if (session.attachBuffer.length > 0) {
846
- drainAttachBuffer();
847
- }
848
-
849
- if ((session.pendingWrites > 0 || session.attachBuffer.length > 0) &&
850
- Date.now() - attachStart < 200) {
851
- setTimeout(finalizeAttach, 10);
852
- return;
853
- }
854
-
855
- session.attaching = false;
856
-
857
- writeToClient(session, encodeControl({ type: "attached" }));
858
-
859
- // Set terminal title
860
- sendTitle(session, sessionName, session.processTitle);
861
- };
862
-
863
- finalizeAttach();
864
- };
865
-
866
- sendState();
867
- };
868
- }
869
-
870
- /**
871
- * Creates socket handlers for a session.
872
- */
873
- function createSessionSocketHandlers(
874
- id: string,
875
- sessionName: string,
876
- proc: Bun.Subprocess,
877
- startAttach: (session: SessionData) => void
878
- ): {
879
- open: (socket: any) => void;
880
- data: (socket: any, data: Buffer) => void;
881
- drain: (socket: any) => void;
882
- close: (socket: any) => void;
883
- } {
884
- return {
885
- open(socket) {
886
- const session = sessions.get(id);
887
- if (!session) return socket.end();
888
-
889
- // Kick existing client
890
- if (session.client) {
891
- writeToClient(session, encodeControl({ type: "kicked" }));
892
- session.client.end();
893
- }
894
-
895
- session.attaching = true;
896
- session.attachPending = true;
897
- session.attachBuffer = [];
898
- session.client = socket;
899
- session.clientWriter = createBufferedSocketWriter(socket);
900
- session.info.attached = true;
901
- session.lastAttached = Date.now(); // Record attach time for grace period
902
- session.ctrlBuffer = Buffer.alloc(0);
903
- clearAttachTimer(session);
904
- // Fallback timeout - client should send attach-init immediately, but just in case
905
- session.attachTimer = setTimeout(() => {
906
- if (session.attachPending) {
907
- console.log(`[${sessionName}] WARN: attach-init not received after 5s, starting attach anyway`);
908
- startAttach(session);
909
- }
910
- }, 5000);
911
- },
912
-
913
- data(socket, data) {
914
- const session = sessions.get(id);
915
- if (!session) return;
916
-
917
- const applyResize = (cols: number, rows: number) => {
918
- try {
919
- session.ptyTerminal.resize(cols, rows);
920
- session.xterm.resize(cols, rows);
921
- // Send SIGWINCH to process group so children (vim, etc.) get it
922
- try {
923
- process.kill(-proc.pid, "SIGWINCH");
924
- } catch {
925
- try {
926
- process.kill(proc.pid, "SIGWINCH");
927
- } catch {}
928
- }
929
- } catch {}
930
- };
931
-
932
- let buf = Buffer.from(data);
933
-
934
- // Prepend any buffered data
935
- if (session.ctrlBuffer.length > 0) {
936
- buf = Buffer.concat([session.ctrlBuffer, buf]);
937
- }
938
-
939
- // Parse frames using the new framed protocol
940
- let frames;
941
- let remaining;
942
- try {
943
- const result = parseFrames(buf);
944
- frames = result.frames;
945
- remaining = result.remaining;
946
- } catch (err) {
947
- // Protocol error - likely desync or corrupted data
948
- const msg = err instanceof Error ? err.message : 'Frame parse error';
949
- console.error(`[${sessionName}] Frame parse error: ${msg}`);
950
- // Close the client connection on protocol error
951
- socket.end();
952
- return;
953
- }
954
- // Copy remaining bytes - subarray references can become invalid when Bun reuses buffers
955
- session.ctrlBuffer = Buffer.from(remaining);
956
-
957
- for (const frame of frames) {
958
- if (frame.type === FrameType.CONTROL) {
959
- const ctrl = decodeControl(frame.payload) as SessionCtrl;
960
- if (ctrl.type === "resize" || ctrl.type === "attach-init") {
961
- applyResize(ctrl.cols, ctrl.rows);
962
- if (session.attaching && session.attachPending) {
963
- startAttach(session);
964
- }
965
- } else if (ctrl.type === "detach") {
966
- // Send reset before detaching to clean up client terminal
967
- writeToClient(session, encodePTY(TERM_RESET));
968
- session.client = null;
969
- session.clientWriter = null;
970
- session.info.attached = false;
971
- session.attaching = false;
972
- session.attachPending = false;
973
- clearAttachTimer(session);
974
- session.attachBuffer = [];
975
- session.lastDetached = Date.now(); // Record detach time for grace period
976
- socket.end();
977
- console.log(`[${sessionName}] detached`);
978
- }
979
- } else if (frame.type === FrameType.PTY) {
980
- // Raw PTY input - write to terminal
981
- session.ptyTerminal.write(frame.payload);
982
- // Track last interaction time
983
- session.lastInteraction = Date.now();
984
- }
985
- }
986
- },
987
-
988
- drain(socket) {
989
- const session = sessions.get(id);
990
- if (session && session.client === socket) {
991
- flushClient(session);
992
- }
993
- },
994
-
995
- close(socket) {
996
- const session = sessions.get(id);
997
- if (session && session.client === socket) {
998
- session.client = null;
999
- session.clientWriter = null;
1000
- session.info.attached = false;
1001
- session.attaching = false;
1002
- session.attachPending = false;
1003
- clearAttachTimer(session);
1004
- session.attachBuffer = [];
1005
- console.log(`[${sessionName}] disconnected`);
1006
- }
1007
- }
1008
- };
1009
- }
1010
-
1011
- /**
1012
- * Builds the shell environment with integration hooks.
1013
- */
1014
- function buildShellEnvironment(
1015
- id: string,
1016
- shell: string,
1017
- hooks?: SessionCreateHooks
1018
- ): Record<string, string> {
1019
- // Shell integration: report non-zero exit codes via OSC 777
1020
- // This creates inbox notifications for failed commands
1021
- const exitReporter = '__tl_report() { local e=$?; [[ $e -ne 0 ]] && printf "\\033]777;exit:%d\\007" "$e"; return $e; }';
1022
-
1023
- const shellEnv: Record<string, string> = {
1024
- ...process.env as Record<string, string>,
1025
- TMUX_LITE: id,
1026
- ...(hooks?.env ?? {}),
1027
- };
1028
-
1029
- const shellName = shell.split('/').pop() ?? '';
1030
-
1031
- // Add PROMPT_COMMAND only for bash-compatible shells.
1032
- if (shellName === 'bash' || shellName === 'rbash') {
1033
- const existingPrompt = process.env.PROMPT_COMMAND || '';
1034
- shellEnv.PROMPT_COMMAND = `${exitReporter}; __tl_report${existingPrompt ? '; ' + existingPrompt : ''}`;
1035
- }
1036
-
1037
- return shellEnv;
1038
- }
1039
-
1040
- function getShellInitScript(shell: string, hooks?: SessionCreateHooks): string | null {
1041
- const shellInit = hooks?.shellInit;
1042
- if (!shellInit) return null;
1043
-
1044
- const shellName = shell.split('/').pop() ?? '';
1045
- const scriptParts: string[] = [];
1046
-
1047
- if (shellInit.all) {
1048
- scriptParts.push(shellInit.all);
1049
- }
1050
-
1051
- const isBashShell = shellName === 'bash' || shellName === 'rbash';
1052
- const isZshShell = shellName === 'zsh';
1053
- const isShShell = shellName === 'sh' || shellName === 'dash';
1054
-
1055
- if (isBashShell && shellInit.bash) {
1056
- scriptParts.push(shellInit.bash);
1057
- } else if (isZshShell && shellInit.zsh) {
1058
- scriptParts.push(shellInit.zsh);
1059
- } else if (isShShell && shellInit.sh) {
1060
- scriptParts.push(shellInit.sh);
1061
- }
1062
-
1063
- if (scriptParts.length === 0) {
1064
- return null;
1065
- }
1066
-
1067
- return `${scriptParts.join('\n')}\n`;
1068
- }
1069
-
1070
- // ============================================================================
1071
- // Main Session Creation
1072
- // ============================================================================
1073
-
1074
- function createSession(
1075
- name: string | undefined,
1076
- cwd: string,
1077
- options?: {
1078
- hooks?: SessionCreateHooks;
1079
- command?: string;
1080
- args?: string[];
1081
- env?: Record<string, string>;
1082
- }
1083
- ): Session {
1084
- const id = genId();
1085
- const sessionName = name || `session-${id}`;
1086
- const socketPath = getSessionSocketPath(id);
1087
- const socketDir = dirname(socketPath);
1088
- if (!existsSync(socketDir)) {
1089
- mkdirSync(socketDir, { recursive: true });
1090
- }
1091
-
1092
- const cols = process.stdout.columns || 80;
1093
- const rows = process.stdout.rows || 24;
1094
-
1095
- // Create xterm-headless for proper terminal state tracking
1096
- const xterm = new XTerminal({
1097
- cols,
1098
- rows,
1099
- // Keep stored scrollback bounded; match ghostty-web default (10k).
1100
- // Note: attach serialization is additionally capped by SERIALIZE_SCROLLBACK_LINES.
1101
- scrollback: 10_000,
1102
- allowProposedApi: true,
1103
- });
1104
-
1105
- const serialize = new SerializeAddon();
1106
- xterm.loadAddon(serialize);
1107
-
1108
- // Set up xterm event handlers for notifications (bell, title changes)
1109
- const { getProcessTitle } = setupXtermEventHandlers(id, sessionName, xterm);
1110
-
1111
- // Initialize idle detection state
1112
- const idleState: IdleDetectionState = {
1113
- lastOutputTime: 0,
1114
- outputSinceIdle: 0,
1115
- idleTimer: null,
1116
- };
1117
-
1118
- // Initialize OSC 133 state for shell integration
1119
- const osc133State: Osc133State = {
1120
- commandRunning: false,
1121
- commandStartTime: 0,
1122
- };
1123
-
1124
- // Create the idle checker function
1125
- const checkIdle = createIdleChecker(id, sessionName, xterm, idleState, getProcessTitle);
1126
-
1127
- // Create PTY terminal with data handler
1128
- const ptyDataHandler = createPtyDataHandler(
1129
- id,
1130
- sessionName,
1131
- xterm,
1132
- idleState,
1133
- osc133State,
1134
- checkIdle,
1135
- getProcessTitle
1136
- );
1137
-
1138
- const ptyTerminal = new Bun.Terminal({
1139
- cols,
1140
- rows,
1141
- data: ptyDataHandler,
1142
- });
1143
-
1144
- // Terminal query support (server-side): respond to DSR (CSI 6 n) with CPR.
1145
- const disposeDsr = installDsrCprResponder(xterm, (data) => {
1146
- try { ptyTerminal.write(data); } catch {}
1147
- });
1148
-
1149
- // Spawn shell process (or custom command if provided)
1150
- const shell = process.env.SHELL || "/bin/bash";
1151
- const hooks = options?.hooks;
1152
- const shellEnv = buildShellEnvironment(id, shell, hooks);
1153
-
1154
- const spawnCmd = options?.command
1155
- ? [options.command, ...(options.args ?? [])]
1156
- : [shell];
1157
- const spawnEnv = options?.env
1158
- ? { ...shellEnv, ...options.env }
1159
- : shellEnv;
1160
-
1161
- const proc = Bun.spawn(spawnCmd, {
1162
- terminal: ptyTerminal,
1163
- cwd,
1164
- env: spawnEnv,
1165
- });
1166
-
1167
- const shellInitScript = getShellInitScript(shell, hooks);
1168
- if (shellInitScript) {
1169
- try {
1170
- ptyTerminal.write(shellInitScript);
1171
- } catch (error) {
1172
- const message = error instanceof Error ? error.message : String(error);
1173
- console.warn(`[${sessionName}] failed to apply shell init hook: ${message}`);
1174
- }
1175
- }
1176
-
1177
- // Handle process exit
1178
- proc.exited.then(handleProcessExit(id, sessionName, xterm, socketPath, disposeDsr, getProcessTitle));
1179
-
1180
- // Create session info
1181
- const info: Session = {
1182
- id,
1183
- name: sessionName,
1184
- socketPath,
1185
- pid: proc.pid,
1186
- attached: false,
1187
- cwd,
1188
- createdAt: Date.now(),
1189
- };
1190
-
1191
- // Create attach handler
1192
- const startAttach = createStartAttach(sessionName);
1193
-
1194
- // Create and bind socket handlers
1195
- const socketHandlers = createSessionSocketHandlers(id, sessionName, proc, startAttach);
1196
-
1197
- // Create session socket
1198
- Bun.listen({
1199
- unix: socketPath,
1200
- socket: socketHandlers,
1201
- });
1202
-
1203
- // Store session data
1204
- sessions.set(id, {
1205
- info,
1206
- ptyTerminal,
1207
- xterm,
1208
- serialize,
1209
- proc,
1210
- client: null,
1211
- clientWriter: null,
1212
- ctrlBuffer: Buffer.alloc(0),
1213
- pendingWrites: 0,
1214
- attaching: false,
1215
- attachBuffer: [],
1216
- attachPending: false,
1217
- attachTimer: null,
1218
- processTitle: '',
1219
- lastInteraction: 0, // No interaction yet
1220
- lastDetached: 0, // Never detached yet
1221
- lastAttached: 0, // Never attached yet (will be set on first attach)
1222
- });
1223
-
1224
- console.log(`[${sessionName}] created (pid ${proc.pid})`);
1225
- return info;
1226
- }
1227
-
1228
- // Router server
1229
- Bun.listen({
1230
- unix: ROUTER_SOCKET,
1231
- socket: {
1232
- open(socket) {
1233
- const socketState = getRouterSocketState(socket);
1234
- socketState.writer = createBufferedSocketWriter(socket as any);
1235
- },
1236
- data(socket, data) {
1237
- const socketState = getRouterSocketState(socket);
1238
- const combined = Buffer.concat([socketState.buffer, Buffer.from(data)]);
1239
- let decoded;
1240
-
1241
- try {
1242
- decoded = decodeRouterMessages(combined);
1243
- } catch (err) {
1244
- const message = err instanceof Error ? err.message : "Invalid request";
1245
- if (socketState.writer) socketState.writer.write(encodeRouterMessage({ type: "error", message }));
1246
- else socket.write(encodeRouterMessage({ type: "error", message }));
1247
- socketState.buffer = Buffer.alloc(0);
1248
- return;
1249
- }
1250
-
1251
- socketState.buffer = decoded.remaining;
1252
-
1253
- for (const message of decoded.messages) {
1254
- const cmd = message as Command;
1255
- let res: Response;
1256
-
1257
- // Helper to get session info with current processTitle
1258
- const getSessionInfo = (s: SessionData): Session => ({
1259
- ...s.info,
1260
- processTitle: s.processTitle || undefined,
1261
- });
1262
-
1263
- switch (cmd.type) {
1264
- case "list":
1265
- res = {
1266
- type: "sessions",
1267
- sessions: Array.from(sessions.values()).map(getSessionInfo)
1268
- };
1269
- break;
1270
-
1271
- case "new":
1272
- try {
1273
- const session = createSession(cmd.name, cmd.cwd, {
1274
- hooks: cmd.hooks,
1275
- command: cmd.command,
1276
- args: cmd.args,
1277
- env: cmd.env,
1278
- });
1279
- res = { type: "session", session };
1280
- } catch (e) {
1281
- const errMsg = e instanceof Error ? e.message : String(e);
1282
- console.error(`[server] createSession failed: ${errMsg}`);
1283
- res = { type: "error", message: `Failed to create session: ${errMsg}` };
1284
- }
1285
- break;
1286
-
1287
- case "attach": {
1288
- const s = sessions.get(cmd.id);
1289
- if (!s) {
1290
- res = { type: "error", message: `Session ${cmd.id} not found` };
1291
- } else if (s.info.attached && !cmd.force) {
1292
- res = { type: "already-attached", session: getSessionInfo(s) };
1293
- } else {
1294
- res = { type: "session", session: getSessionInfo(s) };
1295
- }
1296
- break;
1297
- }
1298
-
1299
- case "kill": {
1300
- const s = sessions.get(cmd.id);
1301
- if (!s) {
1302
- res = { type: "error", message: `Session ${cmd.id} not found` };
1303
- } else {
1304
- // Use SIGKILL to forcefully terminate - SIGTERM is often ignored by shells
1305
- s.proc.kill(9);
1306
- res = { type: "ok" };
1307
- }
1308
- break;
1309
- }
1310
-
1311
- case "kill-server":
1312
- console.log("Shutting down...");
1313
- for (const [id, s] of sessions) {
1314
- s.xterm.dispose();
1315
- s.proc.kill(9); // Use SIGKILL - shells ignore SIGTERM
1316
- }
1317
- // Clean up PID file
1318
- try { unlinkSync(PID_FILE); } catch {}
1319
- res = { type: "ok" };
1320
- if (socketState.writer) socketState.writer.write(encodeRouterMessage(res));
1321
- else socket.write(encodeRouterMessage(res));
1322
- // Clean up socket file after sending response, before exit
1323
- setTimeout(() => {
1324
- try { unlinkSync(ROUTER_SOCKET); } catch {}
1325
- process.exit(0);
1326
- }, 100);
1327
- return;
1328
-
1329
- case "inbox":
1330
- res = { type: "inbox", items: [...inbox] };
1331
- break;
1332
-
1333
- case "inbox-clear":
1334
- if (cmd.id) {
1335
- const idx = inbox.findIndex(i => i.id === cmd.id);
1336
- if (idx !== -1) inbox.splice(idx, 1);
1337
- } else {
1338
- inbox.length = 0;
1339
- }
1340
- broadcastTitleUpdate();
1341
- res = { type: "ok" };
1342
- break;
1343
-
1344
- case "inbox-read": {
1345
- const item = inbox.find(i => i.id === cmd.id);
1346
- if (item) item.read = true;
1347
- broadcastTitleUpdate();
1348
- res = { type: "ok" };
1349
- break;
1350
- }
1351
-
1352
- case "version":
1353
- res = {
1354
- type: "version",
1355
- version: PACKAGE_VERSION,
1356
- protocol: PROTOCOL_VERSION,
1357
- };
1358
- break;
1359
-
1360
- case "status": {
1361
- const sessionList = Array.from(sessions.values());
1362
- const attachedCount = sessionList.filter(s => s.info.attached).length;
1363
- res = {
1364
- type: "status",
1365
- version: PACKAGE_VERSION,
1366
- protocol: PROTOCOL_VERSION,
1367
- pid: process.pid,
1368
- uptime: Math.floor((Date.now() - SERVER_START_TIME) / 1000),
1369
- sessions: sessionList.length,
1370
- attached: attachedCount,
1371
- };
1372
- break;
1373
- }
1374
-
1375
- default:
1376
- res = { type: "error", message: "Unknown command" };
1377
- }
1378
-
1379
- if (socketState.writer) socketState.writer.write(encodeRouterMessage(res));
1380
- else socket.write(encodeRouterMessage(res));
1381
- }
1382
- },
1383
- drain(socket) {
1384
- const socketState = getRouterSocketState(socket);
1385
- socketState.writer?.flush?.();
1386
- },
1387
- close(socket) {
1388
- clearRouterSocketState(socket);
1389
- }
1390
- }
1391
- });
1392
-
1393
- // Handle unexpected termination - kill all session processes
1394
- function cleanupAndExit(signal: string) {
1395
- console.log(`\nReceived ${signal}, cleaning up sessions...`);
1396
- for (const [id, s] of sessions) {
1397
- try {
1398
- s.xterm.dispose();
1399
- s.proc.kill(9);
1400
- } catch {}
1401
- }
1402
- // Clean up PID file
1403
- try { unlinkSync(PID_FILE); } catch {}
1404
- process.exit(0);
1405
- }
1406
-
1407
- process.on('SIGTERM', () => cleanupAndExit('SIGTERM'));
1408
- process.on('SIGINT', () => cleanupAndExit('SIGINT'));
1409
- process.on('SIGHUP', () => cleanupAndExit('SIGHUP'));
1410
-
1411
- console.log("tmux-lite server running (xterm-headless)");
1412
- console.log(`Socket: ${ROUTER_SOCKET}\n`);