History

Merge origin/main into t3code/context-window-meter

Julius Marminge committed 7 months ago

Commit 58f45db2 parents 4bf483d f59ee36475 files · +57982 −13942Browse files

Unified · Split

475 files
  1. .devcontainer/devcontainer.json +22 −0
  2. .docs/remote-architecture.md +302 −0
  3. .github/workflows/ci.yml +3 −1
  4. .github/workflows/release.yml +5 −0
  5. .gitignore +1 −0
  6. .oxfmtrc.json +2 −1
  7. .plans/18-server-auth-model.md +823 −0
  8. CLAUDE.md +1 −1
  9. KEYBINDINGS.md +2 −0
  10. README.md +2 −0
  11. REMOTE.md +63 −44
  12. apps/desktop/package.json +1 −1
  13. apps/desktop/scripts/dev-electron.mjs +13 −6
  14. apps/desktop/scripts/electron-launcher.mjs +1 −1
  15. apps/desktop/src/backendPort.test.ts +109 −0
  16. apps/desktop/src/backendPort.ts +83 −0
  17. apps/desktop/src/backendReadiness.test.ts +83 −0
  18. apps/desktop/src/backendReadiness.ts +103 −0
  19. apps/desktop/src/clientPersistence.test.ts +234 −0
  20. apps/desktop/src/clientPersistence.ts +216 −0
  21. apps/desktop/src/desktopSettings.test.ts +64 −0
  22. apps/desktop/src/desktopSettings.ts +51 −0
  23. apps/desktop/src/main.ts +477 −43
  24. apps/desktop/src/preload.ts +29 −4
  25. apps/desktop/src/serverExposure.test.ts +139 −0
  26. apps/desktop/src/serverExposure.ts +80 −0
  27. apps/desktop/src/updateState.test.ts +29 −0
  28. apps/desktop/src/updateState.ts +4 −0
  29. apps/marketing/src/pages/download.astro +5 −4
  30. apps/server/integration/OrchestrationEngineHarness.integration.ts +23 −4
  31. apps/server/integration/TestProviderAdapter.integration.ts +3 −3
  32. apps/server/integration/fixtures/providerRuntime.ts +2 −2
  33. apps/server/integration/orchestrationEngine.integration.test.ts +18 −19
  34. apps/server/integration/providerService.integration.test.ts +29 −41
  35. apps/server/package.json +1 −1
  36. apps/server/scripts/cli.ts +25 −3
  37. apps/server/src/auth/Layers/AuthControlPlane.test.ts +111 −0
  38. apps/server/src/auth/Layers/AuthControlPlane.ts +176 −0
  39. apps/server/src/auth/Layers/BootstrapCredentialService.test.ts +151 −0
  40. apps/server/src/auth/Layers/BootstrapCredentialService.ts +296 −0
  41. apps/server/src/auth/Layers/ServerAuth.test.ts +182 −0
  42. apps/server/src/auth/Layers/ServerAuth.ts +395 −0
  43. apps/server/src/auth/Layers/ServerAuthPolicy.test.ts +114 −0
  44. apps/server/src/auth/Layers/ServerAuthPolicy.ts +44 −0
  45. apps/server/src/auth/Layers/ServerSecretStore.test.ts +263 −0
  46. apps/server/src/auth/Layers/ServerSecretStore.ts +148 −0
  47. apps/server/src/auth/Layers/SessionCredentialService.test.ts +191 −0
  48. apps/server/src/auth/Layers/SessionCredentialService.ts +500 −0
  49. apps/server/src/auth/Services/AuthControlPlane.ts +69 −0
  50. apps/server/src/auth/Services/BootstrapCredentialService.ts +57 −0
  51. apps/server/src/auth/Services/ServerAuth.ts +84 −0
  52. apps/server/src/auth/Services/ServerAuthPolicy.ts +11 −0
  53. apps/server/src/auth/Services/ServerSecretStore.ts +21 −0
  54. apps/server/src/auth/Services/SessionCredentialService.ts +87 −0
  55. apps/server/src/auth/http.ts +254 −0
  56. apps/server/src/auth/utils.test.ts +26 −0
  57. apps/server/src/auth/utils.ts +132 −0
  58. apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts +4 −4
  59. apps/server/src/checkpointing/Layers/CheckpointStore.test.ts +3 −3
  60. apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts +2 −2
  61. apps/server/src/checkpointing/Services/CheckpointStore.ts +3 −3
  62. apps/server/src/checkpointing/Utils.ts +1 −1
  63. apps/server/src/cli-config.test.ts +223 −13
  64. apps/server/src/cli.test.ts +326 −7
  65. apps/server/src/cli.ts +916 −76
  66. apps/server/src/cliAuthFormat.test.ts +88 −0
  67. apps/server/src/cliAuthFormat.ts +190 −0
  68. apps/server/src/codexAppServerManager.test.ts +5 −5
  69. apps/server/src/codexAppServerManager.ts +34 −28
  70. apps/server/src/config.ts +36 −4
  71. apps/server/src/environment/Layers/ServerEnvironment.test.ts +125 −0
  72. apps/server/src/environment/Layers/ServerEnvironment.ts +92 −0
  73. apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts +150 −0
  74. apps/server/src/environment/Layers/ServerEnvironmentLabel.ts +106 −0
  75. apps/server/src/environment/Services/ServerEnvironment.ts +12 −0
  76. apps/server/src/git/Layers/GitCore.test.ts +183 −63
  77. apps/server/src/git/Layers/GitCore.ts +158 −42
  78. apps/server/src/git/Layers/GitHubCli.test.ts +99 −0
  79. apps/server/src/git/Layers/GitHubCli.ts +40 −80
  80. apps/server/src/git/Layers/GitManager.test.ts +316 −5
  81. apps/server/src/git/Layers/GitManager.ts +155 −118
  82. apps/server/src/git/Layers/GitStatusBroadcaster.test.ts +312 −0
  83. apps/server/src/git/Layers/GitStatusBroadcaster.ts +311 −0
  84. apps/server/src/git/Layers/RoutingTextGeneration.ts +3 −3
  85. apps/server/src/git/Services/GitCore.ts +14 −7
  86. apps/server/src/git/Services/GitHubCli.ts +2 −2
  87. apps/server/src/git/Services/GitManager.ts +33 −2
  88. apps/server/src/git/Services/GitStatusBroadcaster.ts +27 −0
  89. apps/server/src/git/Services/TextGeneration.ts +2 −2
  90. apps/server/src/git/githubPullRequests.ts +128 −0
  91. apps/server/src/http.test.ts +27 −0
  92. apps/server/src/http.ts +123 −9
  93. apps/server/src/keybindings.test.ts +18 −1
  94. apps/server/src/keybindings.ts +5 −4
  95. apps/server/src/observability/Attributes.test.ts +46 −0
  96. apps/server/src/observability/Attributes.ts +128 −0
  97. apps/server/src/observability/Layers/Observability.ts +84 −0
  98. apps/server/src/observability/LocalFileTracer.test.ts +117 −0
  99. apps/server/src/observability/LocalFileTracer.ts +107 −0
  100. apps/server/src/observability/Metrics.test.ts +111 −0
  101. apps/server/src/observability/Metrics.ts +160 −0
  102. apps/server/src/observability/RpcInstrumentation.test.ts +161 −0
  103. apps/server/src/observability/RpcInstrumentation.ts +89 −0
  104. apps/server/src/observability/Services/BrowserTraceCollector.ts +13 −0
  105. apps/server/src/observability/TraceRecord.ts +287 −0
  106. apps/server/src/observability/TraceSink.test.ts +152 −0
  107. apps/server/src/observability/TraceSink.ts +68 −0
  108. apps/server/src/open.test.ts +105 −1
  109. apps/server/src/open.ts +86 −17
  110. apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +164 −119
  111. apps/server/src/orchestration/Layers/CheckpointReactor.ts +142 −115
  112. apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +163 −58
  113. apps/server/src/orchestration/Layers/OrchestrationEngine.ts +168 −95
  114. apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +304 −302
  115. apps/server/src/orchestration/Layers/ProjectionPipeline.ts +1 −1
  116. apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +18 −13
  117. apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +279 −259
  118. apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +143 −152
  119. apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +105 −90
  120. apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +45 −49
  121. apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +51 −50
  122. apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts +20 −2
  123. apps/server/src/orchestration/Services/CheckpointReactor.ts +4 −5
  124. apps/server/src/orchestration/Services/OrchestrationEngine.ts +3 −3
  125. apps/server/src/orchestration/Services/OrchestrationReactor.ts +2 −2
  126. apps/server/src/orchestration/Services/ProjectionPipeline.ts +2 −2
  127. apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +2 −2
  128. apps/server/src/orchestration/Services/ProviderCommandReactor.ts +2 −2
  129. apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts +2 −2
  130. apps/server/src/orchestration/Services/RuntimeReceiptBus.ts +21 −6
  131. apps/server/src/orchestration/commandInvariants.test.ts +24 −26
  132. apps/server/src/orchestration/decider.projectScripts.test.ts +34 −34
  133. apps/server/src/orchestration/http.ts +93 −0
  134. apps/server/src/orchestration/projector.test.ts +4 −4
  135. apps/server/src/orchestration/runtimeLayer.ts +27 −0
  136. apps/server/src/persistence/Errors.ts +2 −0
  137. apps/server/src/persistence/Layers/AuthPairingLinks.ts +209 −0
  138. apps/server/src/persistence/Layers/AuthSessions.ts +279 −0
  139. apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts +8 −8
  140. apps/server/src/persistence/Layers/ProjectionRepositories.test.ts +5 −5
  141. apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts +4 −4
  142. apps/server/src/persistence/Layers/Sqlite.ts +11 −1
  143. apps/server/src/persistence/Migrations.ts +6 −0
  144. apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts +42 −0
  145. apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts +62 −0
  146. apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts +17 −0
  147. apps/server/src/persistence/NodeSqliteClient.ts +10 −10
  148. apps/server/src/persistence/Services/AuthPairingLinks.ts +76 −0
  149. apps/server/src/persistence/Services/AuthSessions.ts +93 −0
  150. apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts +2 −2
  151. apps/server/src/persistence/Services/OrchestrationEventStore.ts +3 −3
  152. apps/server/src/persistence/Services/ProjectionCheckpoints.ts +2 −2
  153. apps/server/src/persistence/Services/ProjectionPendingApprovals.ts +2 −2
  154. apps/server/src/persistence/Services/ProjectionProjects.ts +2 −2
  155. apps/server/src/persistence/Services/ProjectionState.ts +2 −2
  156. apps/server/src/persistence/Services/ProjectionThreadActivities.ts +2 −2
  157. apps/server/src/persistence/Services/ProjectionThreadMessages.ts +2 −2
  158. apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts +2 −2
  159. apps/server/src/persistence/Services/ProjectionThreadSessions.ts +2 −2
  160. apps/server/src/persistence/Services/ProjectionThreads.ts +2 −2
  161. apps/server/src/persistence/Services/ProjectionTurns.ts +2 −2
  162. apps/server/src/persistence/Services/ProviderSessionRuntime.ts +2 −2
  163. apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts +166 −0
  164. apps/server/src/project/Layers/ProjectSetupScriptRunner.ts +75 −0
  165. apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts +193 −0
  166. apps/server/src/project/Layers/RepositoryIdentityResolver.ts +149 −0
  167. apps/server/src/project/Services/ProjectFaviconResolver.ts +2 −2
  168. apps/server/src/project/Services/ProjectSetupScriptRunner.ts +37 −0
  169. apps/server/src/project/Services/RepositoryIdentityResolver.ts +12 −0
  170. apps/server/src/provider/Layers/ClaudeAdapter.test.ts +72 −69
  171. apps/server/src/provider/Layers/ClaudeAdapter.ts +25 −20
  172. apps/server/src/provider/Layers/ClaudeProvider.ts +119 −65
  173. apps/server/src/provider/Layers/CodexAdapter.test.ts +10 −15
  174. apps/server/src/provider/Layers/CodexAdapter.ts +18 −21
  175. apps/server/src/provider/Layers/CodexProvider.ts +61 −18
  176. apps/server/src/provider/Layers/EventNdjsonLogger.test.ts +46 −3
  177. apps/server/src/provider/Layers/EventNdjsonLogger.ts +65 −27
  178. apps/server/src/provider/Layers/ProviderRegistry.test.ts +130 −1
  179. apps/server/src/provider/Layers/ProviderService.test.ts +135 −8
  180. apps/server/src/provider/Layers/ProviderService.ts +325 −171
  181. apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts +5 −5
  182. apps/server/src/provider/Services/ClaudeAdapter.ts +3 −3
  183. apps/server/src/provider/Services/ClaudeProvider.ts +2 −2
  184. apps/server/src/provider/Services/CodexAdapter.ts +3 −3
  185. apps/server/src/provider/Services/CodexProvider.ts +2 −2
  186. apps/server/src/provider/Services/ProviderAdapterRegistry.ts +2 −2
  187. apps/server/src/provider/Services/ProviderRegistry.ts +2 −2
  188. apps/server/src/provider/Services/ProviderService.ts +3 −3
  189. apps/server/src/provider/Services/ProviderSessionDirectory.ts +2 −2
  190. apps/server/src/provider/codexAppServer.ts +95 −8
  191. apps/server/src/provider/providerSnapshot.ts +10 −3
  192. apps/server/src/server.test.ts +2827 −574
  193. apps/server/src/server.ts +97 −42
  194. apps/server/src/serverLifecycleEvents.test.ts +10 −0
  195. apps/server/src/serverLifecycleEvents.ts +2 −2
  196. apps/server/src/serverLogger.ts +1 −4
  197. apps/server/src/serverRuntimeStartup.test.ts +9 −0
  198. apps/server/src/serverRuntimeStartup.ts +134 −64
  199. apps/server/src/serverRuntimeState.ts +77 −0
  200. apps/server/src/serverSettings.test.ts +26 −0
  201. apps/server/src/serverSettings.ts +2 −2
  202. apps/server/src/startupAccess.test.ts +79 −0
  203. apps/server/src/startupAccess.ts +148 −0
  204. apps/server/src/telemetry/Layers/AnalyticsService.ts +13 −11
  205. apps/server/src/telemetry/Services/AnalyticsService.ts +2 −2
  206. apps/server/src/terminal/Layers/Manager.test.ts +79 −0
  207. apps/server/src/terminal/Layers/Manager.ts +100 −67
  208. apps/server/src/terminal/Services/Manager.ts +3 −2
  209. apps/server/src/terminal/Services/PTY.ts +2 −2
  210. apps/server/src/workspace/Layers/WorkspaceEntries.test.ts +12 −0
  211. apps/server/src/workspace/Layers/WorkspaceEntries.ts +49 −129
  212. apps/server/src/workspace/Services/WorkspaceEntries.ts +2 −2
  213. apps/server/src/workspace/Services/WorkspaceFileSystem.ts +2 −2
  214. apps/server/src/workspace/Services/WorkspacePaths.ts +2 −2
  215. apps/server/src/ws.ts +900 −273
  216. apps/web/index.html +83 −2
  217. apps/web/package.json +2 −1
  218. apps/web/src/authBootstrap.test.ts +501 −0
  219. apps/web/src/clientPersistenceStorage.test.ts +80 −0
  220. apps/web/src/clientPersistenceStorage.ts +194 −0
  221. apps/web/src/commandPaletteStore.ts +13 −0
  222. apps/web/src/components/BranchToolbar.logic.test.ts +82 −1
  223. apps/web/src/components/BranchToolbar.logic.ts +50 −4
  224. apps/web/src/components/BranchToolbar.tsx +68 −133
  225. apps/web/src/components/BranchToolbarBranchSelector.tsx +164 −79
  226. apps/web/src/components/BranchToolbarEnvModeSelector.tsx +97 −0
  227. apps/web/src/components/BranchToolbarEnvironmentSelector.tsx +88 −0
  228. apps/web/src/components/ChatMarkdown.browser.tsx +79 −0
  229. apps/web/src/components/ChatMarkdown.tsx +13 −5
  230. apps/web/src/components/ChatView.browser.tsx +1913 −197
  231. apps/web/src/components/ChatView.logic.test.ts +236 −121
  232. apps/web/src/components/ChatView.logic.ts +48 −9
  233. apps/web/src/components/ChatView.tsx +1083 −2073
  234. apps/web/src/components/CommandPalette.logic.test.ts +166 −0
  235. apps/web/src/components/CommandPalette.logic.ts +262 −0
  236. apps/web/src/components/CommandPalette.tsx +458 −0
  237. apps/web/src/components/CommandPaletteResults.tsx +103 −0
  238. apps/web/src/components/ComposerPromptEditor.tsx +566 −13
  239. apps/web/src/components/DiffPanel.tsx +28 −16
  240. apps/web/src/components/GitActionsControl.browser.tsx +294 −70
  241. apps/web/src/components/GitActionsControl.tsx +138 −38
  242. apps/web/src/components/Icons.tsx +222 −0
  243. apps/web/src/components/KeybindingsToast.browser.tsx +141 −24
  244. apps/web/src/components/NoActiveThreadState.tsx +41 −0
  245. apps/web/src/components/PlanSidebar.tsx +6 −3
  246. apps/web/src/components/ProjectFavicon.tsx +14 −7
  247. apps/web/src/components/PullRequestThreadDialog.tsx +11 −3
  248. apps/web/src/components/Sidebar.logic.test.ts +97 −230
  249. apps/web/src/components/Sidebar.logic.ts +10 −62
  250. apps/web/src/components/Sidebar.tsx +2438 −1411
  251. apps/web/src/components/SplashScreen.tsx +9 −0
  252. apps/web/src/components/ThreadTerminalDrawer.browser.tsx +318 −0
  253. apps/web/src/components/ThreadTerminalDrawer.tsx +83 −31
  254. apps/web/src/components/WebSocketConnectionSurface.logic.test.ts +113 −0
  255. apps/web/src/components/WebSocketConnectionSurface.tsx +390 −0
  256. apps/web/src/components/auth/PairingRouteSurface.tsx +195 −0
  257. apps/web/src/components/chat/ChangedFilesTree.test.tsx +2 −2
  258. apps/web/src/components/chat/ChatComposer.tsx +1990 −0
  259. apps/web/src/components/chat/ChatHeader.tsx +14 −1
  260. apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx +37 −29
  261. apps/web/src/components/chat/CompactComposerControlsMenu.tsx +3 −2
  262. apps/web/src/components/chat/ComposerCommandMenu.tsx +161 −27
  263. apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx +1 −1
  264. apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +39 −32
  265. apps/web/src/components/chat/ComposerPrimaryActions.test.ts +93 −0
  266. apps/web/src/components/chat/ComposerPrimaryActions.tsx +8 −3
  267. apps/web/src/components/chat/ExpandedImageDialog.tsx +120 −0
  268. apps/web/src/components/chat/MessageCopyButton.tsx +74 −12
  269. apps/web/src/components/chat/MessagesTimeline.logic.test.ts +123 −1
  270. apps/web/src/components/chat/MessagesTimeline.logic.ts +47 −0
  271. apps/web/src/components/chat/MessagesTimeline.test.tsx +10 −2
  272. apps/web/src/components/chat/MessagesTimeline.tsx +109 −41
  273. apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx +41 −7
  274. apps/web/src/components/chat/OpenInPicker.tsx +21 −6
  275. apps/web/src/components/chat/ProposedPlanCard.tsx +5 −2
  276. apps/web/src/components/chat/ProviderModelPicker.browser.tsx +6 −0
  277. apps/web/src/components/chat/TraitsPicker.browser.tsx +35 −25
  278. apps/web/src/components/chat/TraitsPicker.tsx +12 −5
  279. apps/web/src/components/chat/composerMenuHighlight.test.ts +51 −0
  280. apps/web/src/components/chat/composerMenuHighlight.ts +20 −0
  281. apps/web/src/components/chat/composerProviderRegistry.test.tsx +33 −1
  282. apps/web/src/components/chat/composerProviderRegistry.tsx +93 −53
  283. apps/web/src/components/chat/composerSlashCommandSearch.test.ts +68 −0
  284. apps/web/src/components/chat/composerSlashCommandSearch.ts +83 −0
  285. apps/web/src/components/composerFooterLayout.test.ts +0 −99
  286. apps/web/src/components/composerFooterLayout.ts +0 −45
  287. apps/web/src/components/composerInlineChip.ts +3 −0
  288. apps/web/src/components/settings/ConnectionsSettings.tsx +1432 −0
  289. apps/web/src/components/settings/SettingsPanels.browser.tsx +694 −0
  290. apps/web/src/components/settings/SettingsPanels.tsx +133 −157
  291. apps/web/src/components/settings/SettingsSidebarNav.tsx +9 −5
  292. apps/web/src/components/settings/settingsLayout.tsx +122 −0
  293. apps/web/src/components/timelineHeight.test.ts +17 −4
  294. apps/web/src/components/timelineHeight.ts +28 −4
  295. apps/web/src/components/ui/command.tsx +6 −3
  296. apps/web/src/components/ui/qr-code.test.tsx +27 −0
  297. apps/web/src/components/ui/qr-code.tsx +81 −0
  298. apps/web/src/components/ui/toast.logic.test.ts +52 −1
  299. apps/web/src/components/ui/toast.logic.ts +27 −0
  300. apps/web/src/components/ui/toast.tsx +48 −32
  301. apps/web/src/composer-editor-mentions.test.ts +88 −1
  302. apps/web/src/composer-editor-mentions.ts +185 −27
  303. apps/web/src/composer-logic.test.ts +53 −0
  304. apps/web/src/composer-logic.ts +50 −14
  305. apps/web/src/composerDraftStore.test.ts +360 −202
  306. apps/web/src/composerDraftStore.ts +1635 −960
  307. apps/web/src/composerHandleContext.ts +10 −0
  308. apps/web/src/diffRouteSearch.ts +1 −1
  309. apps/web/src/editorPreferences.ts +2 −2
  310. apps/web/src/environmentApi.ts +68 −0
  311. apps/web/src/environmentGrouping.test.ts +453 −0
  312. apps/web/src/environments/primary/auth.ts +359 −0
  313. apps/web/src/environments/primary/bootstrap.test.ts +170 −0
  314. apps/web/src/environments/primary/context.ts +120 −0
  315. apps/web/src/environments/primary/index.ts +35 −0
  316. apps/web/src/environments/primary/target.ts +158 −0
  317. apps/web/src/environments/remote/api.test.ts +235 −0
  318. apps/web/src/environments/remote/api.ts +143 −0
  319. apps/web/src/environments/remote/target.ts +86 −0
  320. apps/web/src/environments/runtime/catalog.test.ts +141 −0
  321. apps/web/src/environments/runtime/catalog.ts +341 −0
  322. apps/web/src/environments/runtime/connection.test.ts +347 −0
  323. apps/web/src/environments/runtime/connection.ts +334 −0
  324. apps/web/src/environments/runtime/index.ts +29 −0
  325. apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts +105 −0
  326. apps/web/src/environments/runtime/service.test.ts +41 −0
  327. apps/web/src/environments/runtime/service.ts +720 −0
  328. apps/web/src/historyBootstrap.test.ts +1 −1
  329. apps/web/src/hooks/useHandleNewThread.ts +106 −52
  330. apps/web/src/hooks/useSettings.test.ts +0 −16
  331. apps/web/src/hooks/useSettings.ts +100 −176
  332. apps/web/src/hooks/useTheme.ts +78 −5
  333. apps/web/src/hooks/useThreadActions.ts +131 −66
  334. apps/web/src/index.css +9 −6
  335. apps/web/src/keybindings.test.ts +26 −0
  336. apps/web/src/lib/chatThreadActions.test.ts +107 −0
  337. apps/web/src/lib/chatThreadActions.ts +98 −0
  338. apps/web/src/lib/contextWindow.test.ts +2 −2
  339. apps/web/src/lib/gitReactQuery.test.ts +30 −42
  340. apps/web/src/lib/gitReactQuery.ts +128 −103
  341. apps/web/src/lib/gitStatusState.test.ts +326 −0
  342. apps/web/src/lib/gitStatusState.ts +287 −0
  343. apps/web/src/lib/projectReactQuery.ts +17 −8
  344. apps/web/src/lib/providerReactQuery.test.ts +12 −5
  345. apps/web/src/lib/providerReactQuery.ts +11 −4
  346. apps/web/src/lib/terminalContext.test.ts +1 −1
  347. apps/web/src/lib/terminalStateCleanup.test.ts +43 −10
  348. apps/web/src/lib/terminalStateCleanup.ts +17 −9
  349. apps/web/src/lib/threadSort.test.ts +187 −0
  350. apps/web/src/lib/threadSort.ts +73 −0
  351. apps/web/src/lib/utils.test.ts +1 −2
  352. apps/web/src/lib/utils.ts +6 −42
  353. apps/web/src/localApi.test.ts +618 −0
  354. apps/web/src/localApi.ts +154 −0
  355. apps/web/src/logicalProject.ts +19 −0
  356. apps/web/src/markdown-links.test.ts +15 −1
  357. apps/web/src/markdown-links.ts +18 −7
  358. apps/web/src/nativeApi.ts +0 −31
  359. apps/web/src/observability/clientTracing.ts +144 −0
  360. apps/web/src/orchestrationEventEffects.test.ts +39 −13
  361. apps/web/src/orchestrationEventEffects.ts +22 −4
  362. apps/web/src/orchestrationRecovery.test.ts +177 −4
  363. apps/web/src/orchestrationRecovery.ts +77 −7
  364. apps/web/src/pairingUrl.ts +33 −0
  365. apps/web/src/pendingUserInput.test.ts +113 −55
  366. apps/web/src/pendingUserInput.ts +64 −16
  367. apps/web/src/projectScripts.test.ts +5 −3
  368. apps/web/src/projectScripts.ts +1 −37
  369. apps/web/src/providerSkillPresentation.test.ts +57 −0
  370. apps/web/src/providerSkillPresentation.ts +52 −0
  371. apps/web/src/providerSkillSearch.test.ts +59 −0
  372. apps/web/src/providerSkillSearch.ts +105 −0
  373. apps/web/src/pullRequestReference.test.ts +2 −2
  374. apps/web/src/pullRequestReference.ts +1 −1
  375. apps/web/src/routeTree.gen.ts +81 −17
  376. apps/web/src/routes/__root.tsx +101 −310
  377. apps/web/src/routes/_chat.$environmentId.$threadId.tsx +84 −31
  378. apps/web/src/routes/_chat.draft.$draftId.tsx +86 −0
  379. apps/web/src/routes/_chat.index.tsx +2 −26
  380. apps/web/src/routes/_chat.tsx +49 −25
  381. apps/web/src/routes/pair.tsx +47 −0
  382. apps/web/src/routes/settings.connections.tsx +7 −0
  383. apps/web/src/routes/settings.tsx +13 −1
  384. apps/web/src/rpc/client.test.ts +0 −231
  385. apps/web/src/rpc/client.ts +0 −33
  386. apps/web/src/rpc/protocol.ts +163 −13
  387. apps/web/src/rpc/requestLatencyState.test.ts +65 −0
  388. apps/web/src/rpc/requestLatencyState.ts +133 −0
  389. apps/web/src/rpc/serverState.test.ts +38 −6
  390. apps/web/src/rpc/serverState.ts +6 −1
  391. apps/web/src/rpc/transportError.test.ts +24 −0
  392. apps/web/src/rpc/transportError.ts +23 −0
  393. apps/web/src/rpc/wsConnectionState.test.ts +75 −0
  394. apps/web/src/rpc/wsConnectionState.ts +199 −0
  395. apps/web/src/rpc/wsRpcClient.test.ts +104 −0
  396. apps/web/src/rpc/wsRpcClient.ts +66 −31
  397. apps/web/src/rpc/wsTransport.test.ts +946 −0
  398. apps/web/src/rpc/wsTransport.ts +281 −0
  399. apps/web/src/session-logic.test.ts +141 −128
  400. apps/web/src/session-logic.ts +188 −47
  401. apps/web/src/store.test.ts +623 −204
  402. apps/web/src/store.ts +919 −364
  403. apps/web/src/storeSelectors.ts +69 −18
  404. apps/web/src/terminal-links.test.ts +104 −0
  405. apps/web/src/terminal-links.ts +111 −0
  406. apps/web/src/terminalActivity.test.ts +1 −0
  407. apps/web/src/terminalStateStore.test.ts +211 −59
  408. apps/web/src/terminalStateStore.ts +281 −99
  409. apps/web/src/threadDerivation.ts +152 −0
  410. apps/web/src/threadRoutes.test.ts +67 −0
  411. apps/web/src/threadRoutes.ts +59 −0
  412. apps/web/src/threadSelectionStore.test.ts +59 −59
  413. apps/web/src/threadSelectionStore.ts +51 −53
  414. apps/web/src/timestampFormat.test.ts +86 −2
  415. apps/web/src/timestampFormat.ts +87 −0
  416. apps/web/src/types.ts +28 −0
  417. apps/web/src/uiStateStore.test.ts +185 −29
  418. apps/web/src/uiStateStore.ts +197 −49
  419. apps/web/src/vite-env.d.ts +2 −2
  420. apps/web/src/worktreeCleanup.test.ts +15 −12
  421. apps/web/src/wsNativeApi.test.ts +0 −352
  422. apps/web/src/wsNativeApi.ts +0 −107
  423. apps/web/src/wsTransport.test.ts +0 −443
  424. apps/web/src/wsTransport.ts +0 −131
  425. apps/web/test/authHttpHandlers.ts +41 −0
  426. apps/web/test/wsRpcHarness.ts +10 −2
  427. apps/web/vite.config.ts +48 −2
  428. apps/web/vitest.browser.config.ts +8 −0
  429. bun.lock +40 −17
  430. docs/observability.md +519 −0
  431. package.json +14 −6
  432. packages/client-runtime/package.json +25 −0
  433. packages/client-runtime/src/index.ts +2 −0
  434. packages/client-runtime/src/knownEnvironment.test.ts +92 −0
  435. packages/client-runtime/src/knownEnvironment.ts +53 −0
  436. packages/client-runtime/src/scoped.ts +64 −0
  437. packages/client-runtime/tsconfig.json +4 −0
  438. packages/contracts/package.json +1 −1
  439. packages/contracts/src/auth.ts +266 −0
  440. packages/contracts/src/baseSchemas.ts +7 −2
  441. packages/contracts/src/editor.ts +21 −10
  442. packages/contracts/src/environment.ts +77 −0
  443. packages/contracts/src/git.ts +51 −2
  444. packages/contracts/src/index.ts +2 −0
  445. packages/contracts/src/ipc.ts +107 −26
  446. packages/contracts/src/keybindings.test.ts +6 −0
  447. packages/contracts/src/keybindings.ts +1 −0
  448. packages/contracts/src/model.ts +1 −0
  449. packages/contracts/src/orchestration.test.ts +41 −0
  450. packages/contracts/src/orchestration.ts +81 −16
  451. packages/contracts/src/rpc.ts +27 −4
  452. packages/contracts/src/server.test.ts +26 −0
  453. packages/contracts/src/server.ts +45 −1
  454. packages/contracts/src/settings.ts +38 −21
  455. packages/contracts/src/terminal.test.ts +26 −0
  456. packages/contracts/src/terminal.ts +5 −2
  457. packages/contracts/src/userInput.ts +2 −2
  458. packages/shared/package.json +16 −0
  459. packages/shared/src/Net.ts +2 −2
  460. packages/shared/src/git.test.ts +114 −0
  461. packages/shared/src/git.ts +188 −1
  462. packages/shared/src/model.test.ts +1 −0
  463. packages/shared/src/projectScripts.ts +37 −0
  464. packages/shared/src/qrCode.ts +984 −0
  465. packages/shared/src/searchRanking.test.ts +95 −0
  466. packages/shared/src/searchRanking.ts +192 −0
  467. packages/shared/src/serverSettings.test.ts +53 −0
  468. packages/shared/src/serverSettings.ts +40 −0
  469. scripts/build-desktop-artifact.test.ts +45 −0
  470. scripts/build-desktop-artifact.ts +30 −10
  471. scripts/dev-runner.test.ts +73 −24
  472. scripts/dev-runner.ts +33 −66
  473. scripts/lib/resolve-catalog.ts +3 −3
  474. scripts/release-smoke.ts +1 −0
  475. turbo.json +12 −2
.devcontainer/devcontainer.json+22−0
@@ -0,0 +1,22 @@
1{
2 "name": "T3 Code Dev",
3 "image": "debian:bookworm",
4 "features": {
5 "ghcr.io/devcontainers-extra/features/bun:1": {},
6 "ghcr.io/devcontainers/features/node:1": {
7 "version": "24",
8 "nodeGypDependencies": true
9 },
10 "ghcr.io/devcontainers/features/python:1": {
11 "version": "3.12"
12 }
13 },
14 "postCreateCommand": {
15 "bun-install": "bun install --backend=copyfile --frozen-lockfile"
16 },
17 "customizations": {
18 "vscode": {
19 "extensions": ["oxc.oxc-vscode"]
20 }
21 }
22}
.docs/remote-architecture.md+302−0
@@ -0,0 +1,302 @@
1# Remote Architecture
2
3This document describes the target architecture for first-class remote environments in T3 Code.
4
5It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
6
7## Goals
8
9- Treat remote environments as first-class product primitives, not special cases.
10- Support multiple ways to reach the same environment.
11- Keep the T3 server as the execution boundary.
12- Let desktop, mobile, and web all share the same conceptual model.
13- Avoid introducing a local control plane unless product pressure proves it is necessary.
14
15## Non-goals
16
17- Replacing the existing WebSocket server boundary with a custom transport protocol.
18- Making SSH the only remote story.
19- Syncing provider auth across machines.
20- Shipping every access method in the first iteration.
21
22## High-level architecture
23
24T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
25
26Remote support should preserve that boundary.
27
28```text
29┌──────────────────────────────────────────────┐
30│ Client (desktop / mobile / web) │
31│ │
32│ - known environments │
33│ - connection manager │
34│ - environment-aware routing │
35└───────────────┬──────────────────────────────┘
36 │
37 │ resolves one access endpoint
38 │
39┌───────────────▼──────────────────────────────┐
40│ Access method │
41│ │
42│ - direct ws / wss │
43│ - tunneled ws / wss │
44│ - desktop-managed ssh bootstrap + forward │
45└───────────────┬──────────────────────────────┘
46 │
47 │ connects to one T3 server
48 │
49┌───────────────▼──────────────────────────────┐
50│ Execution environment = one T3 server │
51│ │
52│ - environment identity │
53│ - provider state │
54│ - projects / threads / terminals │
55│ - git / filesystem / process runtime │
56└──────────────────────────────────────────────┘
57```
58
59The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
60
61## Domain model
62
63### ExecutionEnvironment
64
65An `ExecutionEnvironment` is one running T3 server instance.
66
67It is the unit that owns:
68
69- provider availability and auth state
70- model availability
71- projects and threads
72- terminal processes
73- filesystem access
74- git operations
75- server settings
76
77It is identified by a stable `environmentId`.
78
79This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
80
81### KnownEnvironment
82
83A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
84
85It is not server-authored. It is local to a device or client profile.
86
87Examples:
88
89- a saved LAN URL
90- a saved public `wss://` endpoint
91- a desktop-managed SSH host entry
92- a saved tunneled environment
93
94A known environment may or may not know the target `environmentId` before first successful connect.
95
96### AccessEndpoint
97
98An `AccessEndpoint` is one concrete way to reach a known environment.
99
100This is the key abstraction that keeps SSH from taking over the model.
101
102A single environment may have many endpoints:
103
104- `wss://t3.example.com`
105- `ws://10.0.0.25:3773`
106- a tunneled relay URL
107- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
108
109The environment stays the same. Only the access path changes.
110
111### RepositoryIdentity
112
113`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
114
115It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
116
117### Workspace / Project
118
119The current `Project` model remains environment-local.
120
121That means:
122
123- a local clone and a remote clone are different projects
124- they may share a `RepositoryIdentity`
125- threads still bind to one project in one environment
126
127## Access methods
128
129Access methods answer one question:
130
131How does the client speak WebSocket to a T3 server?
132
133They do not answer:
134
135- how the server got started
136- who manages the server process
137- whether the environment is local or remote
138
139### 1. Direct WebSocket access
140
141Examples:
142
143- `ws://10.0.0.15:3773`
144- `wss://t3.example.com`
145
146This is the base model and should be the first-class default.
147
148Benefits:
149
150- works for desktop, mobile, and web
151- no client-specific process management required
152- best fit for hosted or self-managed remote T3 deployments
153
154### 2. Tunneled WebSocket access
155
156Examples:
157
158- public relay URLs
159- private network relay URLs
160- local tunnel products such as pipenet
161
162This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
163
164For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
165
166This is especially useful when:
167
168- the host is behind NAT
169- inbound ports are unavailable
170- mobile must reach a desktop-hosted environment
171- a machine should be reachable without exposing raw LAN or public ports
172
173### 3. Desktop-managed SSH access
174
175SSH is an access and launch helper, not a separate environment type.
176
177The desktop main process can use SSH to:
178
179- reach a machine
180- probe it
181- launch or reuse a remote T3 server
182- establish a local port forward
183
184After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
185
186This keeps the renderer transport model consistent with every other access method.
187
188## Launch methods
189
190Launch methods answer a different question:
191
192How does a T3 server come to exist on the target machine?
193
194Launch and access should stay separate in the design.
195
196### 1. Pre-existing server
197
198The simplest launch method is no launch at all.
199
200The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
201
202This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
203
204### 2. Desktop-managed remote launch over SSH
205
206This is the main place where Zed is a useful reference.
207
208Useful ideas to borrow from Zed:
209
210- remote probing
211- platform detection
212- session directories with pid/log metadata
213- reconnect-friendly launcher behavior
214- desktop-owned connection UX
215
216What should be different in T3:
217
218- no custom stdio/socket proxy protocol between renderer and remote runtime
219- no attempt to make the remote runtime look like an editor transport
220- keep the final client-to-server connection as WebSocket
221
222The recommended T3 flow is:
223
2241. Desktop connects over SSH.
2252. Desktop probes the remote machine and verifies T3 availability.
2263. Desktop launches or reuses a remote T3 server.
2274. Desktop establishes local port forwarding.
2285. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
229
230### 3. Client-managed local publish
231
232This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
233
234This is useful for:
235
236- exposing a desktop-hosted environment to mobile
237- temporary remote access without changing router or firewall settings
238
239This is still a launch concern, not a new environment kind.
240
241## Why access and launch must stay separate
242
243These concerns are easy to conflate, but separating them prevents architectural drift.
244
245Examples:
246
247- A manually hosted T3 server might be reached through direct `wss`.
248- The same server might also be reachable through a tunnel.
249- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
250- A local desktop server might be published through a tunnel for mobile.
251
252In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
253
254Only the launch and access paths differ.
255
256## Security model
257
258Remote support must assume that some environments will be reachable over untrusted networks.
259
260That means:
261
262- remote-capable environments should require explicit authentication
263- tunnel exposure should not rely on obscurity
264- client-saved endpoints should carry enough auth metadata to reconnect safely
265
266T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
267
268For publicly reachable environments, authenticated access should be treated as required.
269
270## Relationship to Zed
271
272Zed is a useful reference implementation for managed remote launch and reconnect behavior.
273
274The relevant lessons are:
275
276- remote bootstrap should be explicit
277- reconnect should be first-class
278- connection UX belongs in the client shell
279- runtime ownership should stay clearly on the remote host
280
281The important mismatch is transport shape.
282
283Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
284
285T3 should not copy that part.
286
287T3 already has the right runtime boundary:
288
289- one T3 server per environment
290- ordinary HTTP/WebSocket between client and environment
291
292So T3 should borrow Zed's launch discipline, not its transport protocol.
293
294## Recommended rollout
295
2961. First-class known environments and access endpoints.
2972. Direct `ws` / `wss` remote environments.
2983. Authenticated tunnel-backed environments.
2994. Desktop-managed SSH launch and forwarding.
3005. Multi-environment UI improvements after the base runtime path is proven.
301
302This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
.github/workflows/ci.yml+3−1
@@ -10,6 +10,7 @@ jobs: · 9 unmodified lines
10 quality:10 quality:
11 name: Format, Lint, Typecheck, Test, Browser Test, Build11 name: Format, Lint, Typecheck, Test, Browser Test, Build
12 runs-on: blacksmith-4vcpu-ubuntu-240412 runs-on: blacksmith-4vcpu-ubuntu-2404
13 timeout-minutes: 10
13 steps:14 steps:
14 - name: Checkout15 - name: Checkout
15 uses: actions/checkout@v616 uses: actions/checkout@v6
@@ -71,11 +72,12 @@ jobs: · 55 unmodified lines
71 - name: Verify preload bundle output72 - name: Verify preload bundle output
72 run: |73 run: |
73 test -f apps/desktop/dist-electron/preload.js74 test -f apps/desktop/dist-electron/preload.js
74 grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js75 grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
75 76
76 release_smoke:77 release_smoke:
77 name: Release Smoke78 name: Release Smoke
78 runs-on: ubuntu-24.0479 runs-on: ubuntu-24.04
80 timeout-minutes: 10
79 steps:81 steps:
80 - name: Checkout82 - name: Checkout
81 uses: actions/checkout@v683 uses: actions/checkout@v6
.github/workflows/release.yml+5−0
@@ -19,6 +19,7 @@ jobs: · 18 unmodified lines
19 preflight:19 preflight:
20 name: Preflight20 name: Preflight
21 runs-on: ubuntu-24.0421 runs-on: ubuntu-24.04
22 timeout-minutes: 10
22 outputs:23 outputs:
23 version: ${{ steps.release_meta.outputs.version }}24 version: ${{ steps.release_meta.outputs.version }}
24 tag: ${{ steps.release_meta.outputs.tag }}25 tag: ${{ steps.release_meta.outputs.tag }}
@@ -81,6 +82,7 @@ jobs: · 56 unmodified lines
81 name: Build ${{ matrix.label }}82 name: Build ${{ matrix.label }}
82 needs: preflight83 needs: preflight
83 runs-on: ${{ matrix.runner }}84 runs-on: ${{ matrix.runner }}
85 timeout-minutes: 30
84 strategy:86 strategy:
85 fail-fast: false87 fail-fast: false
86 matrix:88 matrix:
@@ -227,6 +229,7 @@ jobs: · 140 unmodified lines
227 name: Publish CLI to npm229 name: Publish CLI to npm
228 needs: [preflight, build]230 needs: [preflight, build]
229 runs-on: ubuntu-24.04231 runs-on: ubuntu-24.04
232 timeout-minutes: 10
230 steps:233 steps:
231 - name: Checkout234 - name: Checkout
232 uses: actions/checkout@v6235 uses: actions/checkout@v6
@@ -260,6 +263,7 @@ jobs: · 27 unmodified lines
260 name: Publish GitHub Release263 name: Publish GitHub Release
261 needs: [preflight, build, publish_cli]264 needs: [preflight, build, publish_cli]
262 runs-on: ubuntu-24.04265 runs-on: ubuntu-24.04
266 timeout-minutes: 10
263 steps:267 steps:
264 - name: Checkout268 - name: Checkout
265 uses: actions/checkout@v6269 uses: actions/checkout@v6
@@ -307,6 +311,7 @@ jobs: · 41 unmodified lines
307 name: Finalize release311 name: Finalize release
308 needs: [preflight, release]312 needs: [preflight, release]
309 runs-on: ubuntu-24.04313 runs-on: ubuntu-24.04
314 timeout-minutes: 10
310 steps:315 steps:
311 - id: app_token316 - id: app_token
312 name: Mint release app token317 name: Mint release app token
.gitignore+1−0
@@ -21,3 +21,4 @@ apps/web/src/components/__screenshots__ · 20 unmodified lines
21.vitest-*21.vitest-*
22__screenshots__/22__screenshots__/
23.tanstack23.tanstack
24squashfs-root/
.oxfmtrc.json+2−1
@@ -9,7 +9,8 @@ · 8 unmodified lines
9 "bun.lock",9 "bun.lock",
10 "*.tsbuildinfo",10 "*.tsbuildinfo",
11 "**/routeTree.gen.ts",11 "**/routeTree.gen.ts",
12 "apps/web/public/mockServiceWorker.js"12 "apps/web/public/mockServiceWorker.js",
13 "apps/web/src/lib/vendor/qrcodegen.ts"
13 ],14 ],
14 "sortPackageJson": {}15 "sortPackageJson": {}
15}16}
.plans/18-server-auth-model.md+823−0
@@ -0,0 +1,823 @@
1# Server Auth Model Plan
2
3## Purpose
4
5Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
6
7This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
8
9This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
10
11## Primary goals
12
13- Make auth server-wide, not WebSocket-only.
14- Make insecure exposure hard to do accidentally.
15- Preserve zero-login local desktop UX for desktop-managed environments.
16- Support browser-native pairing and session auth.
17- Leave room for native/mobile credentials later without rewriting the server boundary.
18- Keep auth separate from transport and launch method.
19
20## Non-goals
21
22- Full multi-user authorization and RBAC.
23- OAuth / SSO / enterprise identity.
24- Passkeys or biometric UX in v1.
25- Syncing auth state across environments.
26- Designing the full remote environment product in this document.
27
28## Core decisions
29
30### 1. Auth is a server concern
31
32Every privileged surface of the T3 server must go through the same auth policy engine:
33
34- HTTP routes
35- WebSocket upgrades
36- RPC methods reached through WebSocket
37
38The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
39
40### 2. Pairing and session are different things
41
42The system should distinguish:
43
44- bootstrap credentials
45- session credentials
46
47Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
48
49Session credentials are the durable credentials used after pairing.
50
51Bootstrap should never become the long-lived request credential.
52
53### 3. Auth and transport are separate
54
55Auth must not be defined by how the client reached the server.
56
57Examples:
58
59- local desktop-managed server
60- LAN `ws://`
61- public `wss://`
62- tunneled `wss://`
63- SSH-forwarded `ws://127.0.0.1:<port>`
64
65All of these should feed into the same auth model.
66
67### 4. Exposure level changes defaults
68
69The more exposed an environment is, the narrower the safe default should be.
70
71Safe default expectations:
72
73- local desktop-managed: auto-pair allowed
74- loopback browser access: explicit bootstrap allowed
75- non-loopback bind: auth required
76- tunnel/public endpoint: auth required, explicit enablement required
77
78### 5. Browser and native clients may use different session credentials
79
80The auth model should support more than one session credential type even if only one ships first.
81
82Examples:
83
84- browser session cookie
85- native bearer/device token
86
87This should be represented in the model now, even if browser cookies are the first implementation.
88
89## Target auth domain
90
91### Route classes
92
93Every route or transport entrypoint should be classified as one of:
94
951. `public`
962. `bootstrap`
973. `authenticated`
98
99#### `public`
100
101Unauthenticated by definition.
102
103Should be extremely small. Examples:
104
105- static shell needed to render the pairing/login UI
106- favicon/assets required for the pairing screen
107- a minimal server health/version endpoint if needed
108
109#### `bootstrap`
110
111Used only to exchange a bootstrap credential for a session.
112
113Examples:
114
115- Initial bootstrap envelope over file descriptor at startup
116- `POST /api/auth/bootstrap`
117- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
118
119#### `authenticated`
120
121Everything that reveals machine state or mutates it.
122
123Examples:
124
125- WebSocket upgrade
126- orchestration snapshot and events
127- terminal open/write/close
128- project search and file writes
129- git routes
130- attachments
131- project favicon lookup
132- server settings
133
134The default stance should be: if it touches the machine, it is authenticated.
135
136## Credential model
137
138### Bootstrap credentials
139
140Initial credential types to model:
141
142- `desktop-bootstrap`
143- `one-time-token`
144
145Possible future credential types:
146
147- `device-code`
148- `passkey-assertion`
149- `external-identity`
150
151#### `desktop-bootstrap`
152
153Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
154
155Properties:
156
157- launcher-provided
158- short-lived
159- one-time or bounded-use
160- never shown to the user as a reusable password
161
162#### `one-time-token`
163
164Used for explicit browser/mobile pairing flows.
165
166Properties:
167
168- short TTL
169- one-time use
170- safe to embed in a pairing URL fragment
171- exchanged for a session credential
172
173### Session credentials
174
175Initial credential types to model:
176
177- `browser-session-cookie`
178- `bearer-session-token`
179
180#### `browser-session-cookie`
181
182Primary browser credential.
183
184Properties:
185
186- signed
187- `HttpOnly`
188- bounded lifetime
189- revocable by server key rotation or session invalidation
190
191#### `bearer-session-token`
192
193Reserved for native/mobile or non-browser clients.
194
195Properties:
196
197- opaque token, not a bootstrap secret
198- long enough lifetime to survive reconnects
199- stored in secure client storage when available
200
201## Auth policy model
202
203Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
204
205### Policy examples
206
207#### `DesktopManagedLocalPolicy`
208
209Default for desktop-managed local server.
210
211Allowed bootstrap methods:
212
213- `desktop-bootstrap`
214
215Allowed session methods:
216
217- `browser-session-cookie`
218
219Disabled by default:
220
221- `one-time-token`
222- `bearer-session-token`
223- password login
224- public pairing
225
226#### `LoopbackBrowserPolicy`
227
228Used for browser access on localhost without desktop-managed bootstrap.
229
230Allowed bootstrap methods:
231
232- `one-time-token`
233
234Allowed session methods:
235
236- `browser-session-cookie`
237
238#### `RemoteReachablePolicy`
239
240Used when binding non-loopback or using an explicit remote/tunnel workflow.
241
242Allowed bootstrap methods:
243
244- `one-time-token`
245- possibly `desktop-bootstrap` when a desktop shell is brokering access
246
247Allowed session methods:
248
249- `browser-session-cookie`
250- `bearer-session-token`
251
252#### `UnsafeNoAuthPolicy`
253
254Should exist only as an explicit escape hatch.
255
256Requirements:
257
258- explicit opt-in flag
259- loud startup warnings
260- never defaulted automatically
261
262## Effect-native service model
263
264### `ServerAuth`
265
266The main auth facade used by HTTP routes and WebSocket upgrade handling.
267
268Responsibilities:
269
270- classify requests
271- authenticate requests
272- authorize bootstrap attempts
273- create sessions from bootstrap credentials
274- enforce policy by environment mode
275
276Sketch:
277
278```ts
279export interface ServerAuthShape {
280 readonly getCapabilities: Effect.Effect<AuthCapabilities>;
281 readonly authenticateHttpRequest: (
282 request: HttpServerRequest.HttpServerRequest,
283 routeClass: RouteAuthClass,
284 ) => Effect.Effect<AuthContext, AuthError>;
285 readonly authenticateWebSocketUpgrade: (
286 request: HttpServerRequest.HttpServerRequest,
287 ) => Effect.Effect<AuthContext, AuthError>;
288 readonly exchangeBootstrapCredential: (
289 input: BootstrapExchangeInput,
290 ) => Effect.Effect<SessionGrant, AuthError>;
291}
292
293export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
294 "t3/ServerAuth",
295) {}
296```
297
298### `BootstrapCredentialService`
299
300Owns issuance, storage, validation, and consumption of bootstrap credentials.
301
302Responsibilities:
303
304- issue desktop bootstrap grants
305- issue one-time pairing tokens
306- validate TTL and single-use semantics
307- consume bootstrap grants atomically
308
309Sketch:
310
311```ts
312export interface BootstrapCredentialServiceShape {
313 readonly issueDesktopBootstrap: (
314 input: IssueDesktopBootstrapInput,
315 ) => Effect.Effect<BootstrapCredential>;
316 readonly issueOneTimeToken: (
317 input: IssueOneTimeTokenInput,
318 ) => Effect.Effect<BootstrapCredential>;
319 readonly consume: (
320 presented: PresentedBootstrapCredential,
321 ) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
322}
323```
324
325### `SessionCredentialService`
326
327Owns creation and validation of authenticated sessions.
328
329Responsibilities:
330
331- mint cookie sessions
332- mint bearer sessions
333- validate active session credentials
334- revoke sessions if needed later
335
336Sketch:
337
338```ts
339export interface SessionCredentialServiceShape {
340 readonly createBrowserSession: (
341 input: CreateSessionFromBootstrapInput,
342 ) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
343 readonly createBearerSession: (
344 input: CreateSessionFromBootstrapInput,
345 ) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
346 readonly authenticateCookie: (
347 request: HttpServerRequest.HttpServerRequest,
348 ) => Effect.Effect<AuthContext, SessionCredentialError>;
349 readonly authenticateBearer: (
350 request: HttpServerRequest.HttpServerRequest,
351 ) => Effect.Effect<AuthContext, SessionCredentialError>;
352}
353```
354
355### `ServerAuthPolicy`
356
357Pure policy/config service that decides which credential types are allowed.
358
359Responsibilities:
360
361- map runtime mode and bind/exposure settings to allowed auth methods
362- answer whether a route can be public
363- answer whether remote exposure requires auth
364
365This should stay mostly pure and cheap to test.
366
367### `ServerSecretStore`
368
369Owns long-lived server signing keys and secrets.
370
371Responsibilities:
372
373- get or create signing key
374- rotate signing key
375- abstract secure OS-backed storage vs filesystem fallback
376
377Important:
378
379- prefer platform secure storage when available
380- support hardened filesystem fallback for headless/server-only environments
381
382### `BrowserSessionCookieCodec`
383
384Focused utility service for cookie encode/decode/signing behavior.
385
386This should not own policy. It should only own the cookie format.
387
388### `AuthRouteGuards`
389
390Thin helper layer used by routes to enforce auth consistently.
391
392Responsibilities:
393
394- require auth for HTTP route handlers
395- classify route auth mode
396- convert auth failures into `401` / `403`
397
398This prevents every route from re-implementing the same pattern.
399
400Integrates with `HttpRouter.middleware` to enforce auth consistently.
401
402## Suggested layer graph
403
404```text
405ServerSecretStore
406 ├─> BootstrapCredentialService
407 ├─> BrowserSessionCookieCodec
408 └─> SessionCredentialService
409
410ServerAuthPolicy
411 ├─> BootstrapCredentialService
412 ├─> SessionCredentialService
413 └─> ServerAuth
414
415ServerAuth
416 └─> AuthRouteGuards
417```
418
419Layer naming should follow existing repo style:
420
421- `ServerSecretStoreLive`
422- `BootstrapCredentialServiceLive`
423- `SessionCredentialServiceLive`
424- `ServerAuthPolicyLive`
425- `ServerAuthLive`
426- `AuthRouteGuardsLive`
427
428## High-level implementation examples
429
430### Example: WebSocket upgrade auth
431
432Current state:
433
434- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
435
436Target shape:
437
438```ts
439const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
440 Effect.gen(function* () {
441 const request = yield* HttpServerRequest.HttpServerRequest;
442 const serverAuth = yield* ServerAuth;
443 yield* serverAuth.authenticateWebSocketUpgrade(request);
444 return yield* httpApp;
445 }),
446);
447```
448
449Then the `/ws` route becomes:
450
451```ts
452export const websocketRpcRouteLayer = HttpRouter.add(
453 "GET",
454 "/ws",
455 rpcWebSocketHttpEffect.pipe(
456 websocketUpgradeAuth,
457 Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
458 ),
459);
460```
461
462This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
463
464### Example: authenticated HTTP route
465
466For routes like attachments or project favicon:
467
468```ts
469const authenticatedRoute = (routeClass: RouteAuthClass) =>
470 HttpMiddleware.make((httpApp) =>
471 Effect.gen(function* () {
472 const request = yield* HttpServerRequest.HttpServerRequest;
473 const serverAuth = yield* ServerAuth;
474 yield* serverAuth.authenticateHttpRequest(request, routeClass);
475 return yield* httpApp;
476 }),
477 );
478```
479
480Then:
481
482```ts
483export const attachmentsRouteLayer = HttpRouter.add(
484 "GET",
485 `${ATTACHMENTS_ROUTE_PREFIX}/*`,
486 serveAttachment.pipe(
487 authenticatedRoute(RouteAuthClass.Authenticated),
488 Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
489 ),
490);
491```
492
493### Example: desktop bootstrap exchange
494
495The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
496
497That grant is then exchanged for a browser cookie session when the renderer loads.
498
499Sketch:
500
501```ts
502const pairDesktopRenderer = Effect.gen(function* () {
503 const bootstrapService = yield* BootstrapCredentialService;
504 const credential = yield* bootstrapService.issueDesktopBootstrap({
505 audience: "desktop-renderer",
506 ttlMs: 30_000,
507 });
508 return credential;
509});
510```
511
512The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
513
514### Example: one-time pairing URL
515
516For browser-driven pairing:
517
518```ts
519const createPairingToken = Effect.gen(function* () {
520 const bootstrapService = yield* BootstrapCredentialService;
521 return yield* bootstrapService.issueOneTimeToken({
522 ttlMs: 5 * 60_000,
523 audience: "browser",
524 });
525});
526```
527
528The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
529
530## Sequence diagrams
531
532These flows are meant to anchor the auth model in concrete user journeys.
533
534The important invariant across all of them is:
535
536- access method is not the auth method
537- launch method is not the auth method
538- bootstrap credential is not the session credential
539
540### Normal desktop user
541
542This is the default desktop-managed local flow.
543
544The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
545
546```text
547Participants:
548 DesktopMain = Electron main
549 SecretStore = secure local secret backend
550 T3Server = local backend child process
551 Frontend = desktop renderer
552
553DesktopMain -> SecretStore : getOrCreate("server-signing-key")
554SecretStore --> DesktopMain : signing key available
555
556DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
557DesktopMain -> T3Server : send desktop bootstrap envelope
558note over T3Server : policy = DesktopManagedLocalPolicy
559note over T3Server : allowed pairing = desktop-bootstrap only
560
561Frontend -> DesktopMain : request local bootstrap grant
562DesktopMain --> Frontend : short-lived desktop bootstrap grant
563
564Frontend -> T3Server : POST /api/auth/bootstrap
565T3Server -> T3Server : validate desktop bootstrap grant
566T3Server -> T3Server : create browser session
567T3Server --> Frontend : Set-Cookie: session=...
568
569Frontend -> T3Server : GET /ws + authenticated cookie
570T3Server -> T3Server : validate cookie session
571T3Server --> Frontend : websocket accepted
572```
573
574### `npx t3` user
575
576This is the standalone local server flow.
577
578There is no trusted desktop shell here, so pairing should be explicit.
579
580```text
581Participants:
582 UserShell = npx t3 launcher
583 T3Server = standalone local server
584 Browser = browser tab
585
586UserShell -> T3Server : start server
587T3Server -> T3Server : getOrCreate("server-signing-key")
588note over T3Server : policy = LoopbackBrowserPolicy
589
590UserShell -> T3Server : issue one-time pairing token
591T3Server --> UserShell : pairing URL or pairing token
592
593UserShell --> Browser : open /pair?token=...
594
595Browser -> T3Server : GET /pair?token=...
596T3Server -> T3Server : validate one-time token
597T3Server -> T3Server : create browser session
598T3Server --> Browser : Set-Cookie: session=...
599T3Server --> Browser : redirect to app
600
601Browser -> T3Server : GET /ws + authenticated cookie
602T3Server --> Browser : websocket accepted
603```
604
605### Phone user with tunneled host
606
607This is the explicit remote access flow for a browser on another device.
608
609The tunnel only provides reachability. It must not imply trust.
610
611Recommended UX:
612
613- desktop shows a QR code
614- desktop also shows a copyable pairing URL
615- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
616
617```text
618Participants:
619 DesktopUser = user at the host machine
620 DesktopMain = desktop app
621 Tunnel = tunnel provider
622 T3Server = T3 server
623 PhoneBrowser = mobile browser
624
625DesktopUser -> DesktopMain : enable remote access via tunnel
626DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
627DesktopMain -> Tunnel : publish local T3 endpoint
628Tunnel --> DesktopMain : public https/wss URL
629
630DesktopMain -> T3Server : issue one-time pairing token
631T3Server --> DesktopMain : pairing token
632DesktopMain -> DesktopUser : show QR code / shareable URL
633
634DesktopUser -> PhoneBrowser : scan QR / open URL
635PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
636Tunnel -> T3Server : forward request
637T3Server -> T3Server : validate one-time token
638T3Server -> T3Server : create mobile browser session
639T3Server --> PhoneBrowser : Set-Cookie: session=...
640T3Server --> PhoneBrowser : redirect to app
641
642PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
643Tunnel -> T3Server : forward websocket upgrade
644T3Server --> PhoneBrowser : websocket accepted
645```
646
647### Phone user with private network
648
649This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
650
651The auth flow should stay the same.
652
653```text
654Participants:
655 DesktopUser = user at the host machine
656 T3Server = T3 server
657 PrivateNet = tailscale / private LAN
658 PhoneBrowser = mobile browser
659
660DesktopUser -> T3Server : enable private-network access
661T3Server -> T3Server : switch policy to RemoteReachablePolicy
662DesktopUser -> T3Server : issue one-time pairing token
663T3Server --> DesktopUser : pairing URL / QR
664
665DesktopUser -> PhoneBrowser : open private-network URL
666PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
667PrivateNet -> T3Server : route request
668T3Server -> T3Server : validate one-time token
669T3Server -> T3Server : create mobile browser session
670T3Server --> PhoneBrowser : Set-Cookie: session=...
671T3Server --> PhoneBrowser : redirect to app
672
673PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
674PrivateNet -> T3Server : websocket upgrade
675T3Server --> PhoneBrowser : websocket accepted
676```
677
678### Desktop user adding new SSH hosts
679
680SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
681
682The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
683
684```text
685Participants:
686 DesktopUser = local desktop user
687 DesktopMain = desktop app
688 SSH = ssh transport/session
689 RemoteHost = remote machine
690 RemoteT3 = remote T3 server
691 Frontend = desktop renderer
692
693DesktopUser -> DesktopMain : add SSH host
694DesktopMain -> SSH : connect to remote host
695SSH -> RemoteHost : probe environment / verify t3 availability
696DesktopMain -> SSH : run remote launch command
697SSH -> RemoteHost : t3 remote launch --json
698RemoteHost -> RemoteT3 : start or reuse server
699RemoteT3 --> RemoteHost : port + environment metadata
700RemoteHost --> SSH : launch result JSON
701SSH --> DesktopMain : remote server details
702
703DesktopMain -> SSH : establish local port forward
704SSH --> DesktopMain : localhost:FORWARDED_PORT ready
705
706note over RemoteT3 : policy = RemoteReachablePolicy
707note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
708
709Frontend -> DesktopMain : request bootstrap for selected environment
710DesktopMain --> Frontend : short-lived bootstrap grant
711
712Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
713RemoteT3 -> RemoteT3 : validate bootstrap grant
714RemoteT3 -> RemoteT3 : create browser session
715RemoteT3 --> Frontend : Set-Cookie: session=...
716
717Frontend -> RemoteT3 : GET /ws + authenticated cookie
718RemoteT3 --> Frontend : websocket accepted
719```
720
721## Storage decisions
722
723### Server secrets
724
725Use a `ServerSecretStore` abstraction.
726
727Preferred order (use a layer for each, resolve on startup):
728
7291. OS secure storage if available
7302. hardened filesystem fallback if not
731
732The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
733
734### Client credentials
735
736Client-side credential persistence should prefer secure storage when available:
737
738- desktop: OS keychain / secure store
739- mobile: platform secure storage
740- browser: cookie session for browser auth
741
742This concern should stay in the client shell/runtime layer, not the server auth layer.
743
744## What to build now
745
746These are the parts worth building before remote environments ship:
747
7481. `ServerAuth` service boundary.
7492. route classification and route guards.
7503. `ServerSecretStore` abstraction.
7514. bootstrap vs session credential split.
7525. browser session cookie codec as one session method.
7536. explicit auth capabilities/config surfaced in contracts.
754
755Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
756
757## What to add as part of first remote-capable auth
758
7591. Browser pairing flow using one-time bootstrap token and cookie session.
7602. Desktop-managed auto-bootstrap for the local desktop-managed environment.
7613. Auth-required defaults for any non-loopback or explicitly published server.
7624. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
763
764## What to defer
765
766- passkeys / WebAuthn
767- iCloud Keychain / Face ID-specific UX
768- multi-user permissions
769- collaboration roles
770- OAuth / SSO
771- polished session management UI
772- complex device approval flows
773
774These can all sit on top of the same bootstrap/session/service split.
775
776## Relationship to future remote environments
777
778Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
779
780Keep the design focused on:
781
782- one T3 server
783- one auth policy
784- multiple credential types
785- multiple future access methods
786
787That keeps the server auth model stable even as access methods expand later.
788
789## Recommended implementation order
790
791### Phase 1
792
793- Introduce route auth classes.
794- Add `ServerAuth` and `AuthRouteGuards`.
795- Move existing `authToken` check behind `ServerAuth`.
796- Require auth for all privileged HTTP routes as well as WebSocket.
797
798### Phase 2
799
800- Add `ServerSecretStore` service with platform-specific layer implementations.
801 - `layerOSXKeychain`, `layer
802- Add bootstrap/session split.
803- Add browser session cookie support.
804- Add one-time bootstrap exchange endpoint.
805
806### Phase 3
807
808- Add desktop bootstrap flow on top of the same services.
809- Make desktop-managed local environments default to bootstrap-only pairing.
810- Surface auth capabilities in shared contracts and renderer bootstrap.
811
812### Phase 4
813
814- Add non-browser bearer session support if mobile/native needs it.
815- Add richer policy modes for remote-reachable environments.
816
817## Acceptance criteria
818
819- No privileged HTTP or WebSocket path bypasses auth policy.
820- Local desktop-managed flows still avoid a visible login screen.
821- Non-loopback or published environments require explicit authenticated pairing by default.
822- Bootstrap and session credentials are distinct in code and in behavior.
823- Auth logic is centralized in Effect services/layers rather than route-local branching.
CLAUDE.md+1−1
@@ -1 +1 @@
1AGENTS.md1AGENTS.md
KEYBINDINGS.md+2−0
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`]( · 22 unmodified lines
23 { "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },23 { "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
24 { "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },24 { "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
25 { "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },25 { "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
26 { "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
26 { "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },27 { "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
27 { "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },28 { "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
28 { "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },29 { "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
@@ -50,6 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged · 21 unmodified lines
50- `terminal.split`: split terminal (in focused terminal context by default)51- `terminal.split`: split terminal (in focused terminal context by default)
51- `terminal.new`: create new terminal (in focused terminal context by default)52- `terminal.new`: create new terminal (in focused terminal context by default)
52- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)53- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
54- `commandPalette.toggle`: open or close the global command palette
53- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state55- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
54- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))56- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
55- `editor.openFavorite`: open current project/worktree in the last-used editor57- `editor.openFavorite`: open current project/worktree in the last-used editor
README.md+2−0
@@ -45,6 +45,8 @@ We are very very early in this project. Expect bugs. · 44 unmodified lines
45 45
46We are not accepting contributions yet.46We are not accepting contributions yet.
47 47
48Observability guide: [docs/observability.md](./docs/observability.md)
49
48## If you REALLY want to contribute still.... read this first50## If you REALLY want to contribute still.... read this first
49 51
50Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.52Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
REMOTE.md+63−44
@@ -1,68 +1,87 @@
1# Remote Access Setup1# Remote Access
2 2
3Use this when you want to open T3 Code from another device (phone, tablet, another laptop).3Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
4 4
5## CLI ↔ Env option map5## Recommended Setup
6 6
7The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:7Use a trusted private network that meshes your devices together, such as a tailnet.
8 8
9| CLI flag | Env var | Notes |9That gives you:
10| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
11| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
12| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
13| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
14| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
15| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
16| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
17| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
18| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
19 10
20> TIP: Use the `--help` flag to see all available options and their descriptions.11- a stable address to connect to
12- transport security at the network layer
13- less exposure than opening the server to the public internet
21 14
22## Security First15## Enabling Network Access
23 16
24- Always set `--auth-token` before exposing the server outside localhost.17There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
25 - When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
26 With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
27- Treat the token like a password.
28- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
29 18
30## 1) Build + run server for remote access19### Option 1: Desktop App
31 20
32Remote access should use the built web app (not local Vite redirect mode).21If you are already running the desktop app and want to make it reachable from other devices:
22
231. Open **Settings** → **Connections**.
242. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
253. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
264. Use **Create Link** to generate a pairing link you can share with another device.
27
28### Option 2: Headless Server (CLI)
29
30Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
31
32Run the server with `t3 serve`.
33 33
34```bash34```bash
35bun run build35npx t3 serve --host "$(tailscale ip -4)"
36TOKEN="$(openssl rand -hex 24)"
37bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
38```36```
39 37
40Then open on your phone:38`t3 serve` starts the server without opening a browser and prints:
41 39
42`http://<your-machine-ip>:3773`40- a connection string
41- a pairing token
42- a pairing URL
43- a QR code for the pairing URL
43 44
44Example:45From there, connect from another device in either of these ways:
45 46
46`http://192.168.1.42:3773`47- scan the QR code on your phone
48- in the desktop app, enter the full pairing URL
49- in the desktop app, enter the host and token separately
47 50
48Notes:51Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
49 52
50- `--host 0.0.0.0` listens on all IPv4 interfaces.53> Note
51- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.54> The GUIs do not currently support adding projects on remote environments.
52- Ensure your OS firewall allows inbound TCP on the selected port.55> For now, use `t3 project ...` on the server machine instead.
56> Full GUI support for remote project management is coming soon.
53 57
54## 2) Tailnet / Tailscale access58## How Pairing Works
55 59
56If you use Tailscale, you can bind directly to your Tailnet address.60The remote device does not need a long-lived secret up front.
57 61
58```bash62Instead:
59TAILNET_IP="$(tailscale ip -4)"63
60TOKEN="$(openssl rand -hex 24)"641. `t3 serve` issues a one-time owner pairing token.
61bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser652. The remote device exchanges that token with the server.
62```663. The server creates an authenticated session for that device.
67
68After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
69
70## Managing Access Later
71
72Use `t3 auth` to manage access after the initial pairing flow.
73
74Typical uses:
75
76- issue additional pairing credentials
77- inspect active sessions
78- revoke old pairing links or sessions
63 79
64Open from any device in your tailnet:80Use `t3 auth --help` and the nested subcommand help pages for the full reference.
65 81
66`http://<tailnet-ip>:3773`82## Security Notes
67 83
68You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.84- Treat pairing URLs and pairing tokens like passwords.
85- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
86- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
87- Use `t3 auth` to revoke credentials or sessions you no longer trust.
apps/desktop/package.json+1−1
@@ -1,6 +1,6 @@
1{1{
2 "name": "@t3tools/desktop",2 "name": "@t3tools/desktop",
3 "version": "0.0.15",3 "version": "0.0.17",
4 "private": true,4 "private": true,
5 "main": "dist-electron/main.js",5 "main": "dist-electron/main.js",
6 "scripts": {6 "scripts": {
apps/desktop/scripts/dev-electron.mjs+13−6
@@ -5,8 +5,17 @@ import { join } from "node:path"; · 4 unmodified lines
5import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";5import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
6import { waitForResources } from "./wait-for-resources.mjs";6import { waitForResources } from "./wait-for-resources.mjs";
7 7
8const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);8const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
9const devServerUrl = `http://localhost:${port}`;9if (!devServerUrl) {
10 throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
11}
12
13const devServer = new URL(devServerUrl);
14const port = Number.parseInt(devServer.port, 10);
15if (!Number.isInteger(port) || port <= 0) {
16 throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
17}
18
10const requiredFiles = [19const requiredFiles = [
11 "dist-electron/main.js",20 "dist-electron/main.js",
12 "dist-electron/preload.js",21 "dist-electron/preload.js",
@@ -23,6 +32,7 @@ const childTreeGracePeriodMs = 1_200; · 10 unmodified lines
23await waitForResources({32await waitForResources({
24 baseDir: desktopDir,33 baseDir: desktopDir,
25 files: requiredFiles,34 files: requiredFiles,
35 tcpHost: devServer.hostname,
26 tcpPort: port,36 tcpPort: port,
27});37});
28 38
@@ -62,10 +72,7 @@ function startApp() { · 33 unmodified lines
62 [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],72 [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
63 {73 {
64 cwd: desktopDir,74 cwd: desktopDir,
65 env: {75 env: childEnv,
66 ...childEnv,
67 VITE_DEV_SERVER_URL: devServerUrl,
68 },
69 stdio: "inherit",76 stdio: "inherit",
70 },77 },
71 );78 );
apps/desktop/scripts/electron-launcher.mjs+1−1
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url"; · 17 unmodified lines
18 18
19const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);19const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
20const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";20const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
21const APP_BUNDLE_ID = "com.t3tools.t3code";21const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
22const LAUNCHER_VERSION = 1;22const LAUNCHER_VERSION = 1;
23 23
24const __dirname = dirname(fileURLToPath(import.meta.url));24const __dirname = dirname(fileURLToPath(import.meta.url));
apps/desktop/src/backendPort.test.ts+109−0
@@ -0,0 +1,109 @@
1import { describe, expect, it, vi } from "vitest";
2
3import { resolveDesktopBackendPort } from "./backendPort";
4
5describe("resolveDesktopBackendPort", () => {
6 it("returns the starting port when it is available", async () => {
7 const canListenOnHost = vi.fn(async (port: number) => port === 3773);
8
9 await expect(
10 resolveDesktopBackendPort({
11 host: "127.0.0.1",
12 startPort: 3773,
13 canListenOnHost,
14 }),
15 ).resolves.toBe(3773);
16
17 expect(canListenOnHost).toHaveBeenCalledTimes(1);
18 expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
19 });
20
21 it("increments sequentially until it finds an available port", async () => {
22 const canListenOnHost = vi.fn(async (port: number) => port === 3775);
23
24 await expect(
25 resolveDesktopBackendPort({
26 host: "127.0.0.1",
27 startPort: 3773,
28 canListenOnHost,
29 }),
30 ).resolves.toBe(3775);
31
32 expect(canListenOnHost.mock.calls).toEqual([
33 [3773, "127.0.0.1"],
34 [3774, "127.0.0.1"],
35 [3775, "127.0.0.1"],
36 ]);
37 });
38
39 it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
40 const canListenOnHost = vi.fn(async (port: number, host: string) => {
41 if (port === 3773 && host === "127.0.0.1") return true;
42 if (port === 3773 && host === "0.0.0.0") return false;
43 return port === 3774;
44 });
45
46 await expect(
47 resolveDesktopBackendPort({
48 host: "127.0.0.1",
49 requiredHosts: ["0.0.0.0"],
50 startPort: 3773,
51 canListenOnHost,
52 }),
53 ).resolves.toBe(3774);
54
55 expect(canListenOnHost.mock.calls).toEqual([
56 [3773, "127.0.0.1"],
57 [3773, "0.0.0.0"],
58 [3774, "127.0.0.1"],
59 [3774, "0.0.0.0"],
60 ]);
61 });
62
63 it("checks overlapping hosts sequentially to avoid self-interference", async () => {
64 let inFlightCount = 0;
65 const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
66 inFlightCount += 1;
67 const overlapped = inFlightCount > 1;
68 await Promise.resolve();
69 inFlightCount -= 1;
70 return !overlapped;
71 });
72
73 await expect(
74 resolveDesktopBackendPort({
75 host: "127.0.0.1",
76 requiredHosts: ["0.0.0.0", "::"],
77 startPort: 3773,
78 maxPort: 3773,
79 canListenOnHost,
80 }),
81 ).resolves.toBe(3773);
82
83 expect(canListenOnHost.mock.calls).toEqual([
84 [3773, "127.0.0.1"],
85 [3773, "0.0.0.0"],
86 [3773, "::"],
87 ]);
88 });
89
90 it("fails when the scan range is exhausted", async () => {
91 const canListenOnHost = vi.fn(async () => false);
92
93 await expect(
94 resolveDesktopBackendPort({
95 host: "127.0.0.1",
96 startPort: 65534,
97 maxPort: 65535,
98 canListenOnHost,
99 }),
100 ).rejects.toThrow(
101 "No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
102 );
103
104 expect(canListenOnHost.mock.calls).toEqual([
105 [65534, "127.0.0.1"],
106 [65535, "127.0.0.1"],
107 ]);
108 });
109});
apps/desktop/src/backendPort.ts+83−0
@@ -0,0 +1,83 @@
1import * as Effect from "effect/Effect";
2import { NetService } from "@t3tools/shared/Net";
3
4export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
5const MAX_TCP_PORT = 65_535;
6
7export interface ResolveDesktopBackendPortOptions {
8 readonly host: string;
9 readonly startPort?: number;
10 readonly maxPort?: number;
11 readonly requiredHosts?: ReadonlyArray<string>;
12 readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
13}
14
15const defaultCanListenOnHost = async (port: number, host: string): Promise<boolean> =>
16 Effect.service(NetService).pipe(
17 Effect.flatMap((net) => net.canListenOnHost(port, host)),
18 Effect.provide(NetService.layer),
19 Effect.runPromise,
20 );
21
22const isValidPort = (port: number): boolean =>
23 Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
24
25const normalizeHosts = (
26 host: string,
27 requiredHosts: ReadonlyArray<string>,
28): ReadonlyArray<string> =>
29 Array.from(
30 new Set(
31 [host, ...requiredHosts]
32 .map((candidate) => candidate.trim())
33 .filter((candidate) => candidate.length > 0),
34 ),
35 );
36
37async function canListenOnAllHosts(
38 port: number,
39 hosts: ReadonlyArray<string>,
40 canListenOnHost: (port: number, host: string) => Promise<boolean>,
41): Promise<boolean> {
42 for (const candidateHost of hosts) {
43 if (!(await canListenOnHost(port, candidateHost))) {
44 return false;
45 }
46 }
47
48 return true;
49}
50
51export async function resolveDesktopBackendPort({
52 host,
53 startPort = DEFAULT_DESKTOP_BACKEND_PORT,
54 maxPort = MAX_TCP_PORT,
55 requiredHosts = [],
56 canListenOnHost = defaultCanListenOnHost,
57}: ResolveDesktopBackendPortOptions): Promise<number> {
58 if (!isValidPort(startPort)) {
59 throw new Error(`Invalid desktop backend start port: ${startPort}`);
60 }
61
62 if (!isValidPort(maxPort)) {
63 throw new Error(`Invalid desktop backend max port: ${maxPort}`);
64 }
65
66 if (maxPort < startPort) {
67 throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
68 }
69
70 const hostsToCheck = normalizeHosts(host, requiredHosts);
71
72 // Keep desktop startup predictable across app restarts by probing upward from
73 // the same preferred port instead of picking a fresh ephemeral port.
74 for (let port = startPort; port <= maxPort; port += 1) {
75 if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
76 return port;
77 }
78 }
79
80 throw new Error(
81 `No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
82 );
83}
apps/desktop/src/backendReadiness.test.ts+83−0
@@ -0,0 +1,83 @@
1import { describe, expect, it, vi } from "vitest";
2
3import {
4 BackendReadinessAbortedError,
5 isBackendReadinessAborted,
6 waitForHttpReady,
7} from "./backendReadiness";
8
9describe("waitForHttpReady", () => {
10 it("returns once the backend reports a successful session endpoint", async () => {
11 const fetchImpl = vi
12 .fn<typeof fetch>()
13 .mockResolvedValueOnce(new Response(null, { status: 503 }))
14 .mockResolvedValueOnce(new Response(null, { status: 200 }));
15
16 await waitForHttpReady("http://127.0.0.1:3773", {
17 fetchImpl,
18 timeoutMs: 1_000,
19 intervalMs: 0,
20 });
21
22 expect(fetchImpl).toHaveBeenCalledTimes(2);
23 });
24
25 it("retries after a readiness request stalls past the per-request timeout", async () => {
26 const fetchImpl = vi
27 .fn<typeof fetch>()
28 .mockImplementationOnce(
29 (_input, init) =>
30 new Promise((_resolve, reject) => {
31 init?.signal?.addEventListener(
32 "abort",
33 () => {
34 reject(new Error("request timed out"));
35 },
36 { once: true },
37 );
38 }) as ReturnType<typeof fetch>,
39 )
40 .mockResolvedValueOnce(new Response(null, { status: 200 }));
41
42 await waitForHttpReady("http://127.0.0.1:3773", {
43 fetchImpl,
44 timeoutMs: 100,
45 intervalMs: 0,
46 requestTimeoutMs: 1,
47 });
48
49 expect(fetchImpl).toHaveBeenCalledTimes(2);
50 });
51
52 it("aborts an in-flight readiness wait", async () => {
53 const controller = new AbortController();
54 const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
55 () =>
56 new Promise((_resolve, reject) => {
57 controller.signal.addEventListener(
58 "abort",
59 () => {
60 reject(new BackendReadinessAbortedError());
61 },
62 { once: true },
63 );
64 }) as ReturnType<typeof fetch>,
65 );
66
67 const waitPromise = waitForHttpReady("http://127.0.0.1:3773", {
68 fetchImpl,
69 timeoutMs: 1_000,
70 intervalMs: 0,
71 signal: controller.signal,
72 });
73
74 controller.abort();
75
76 await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError);
77 });
78
79 it("recognizes aborted readiness errors", () => {
80 expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
81 expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
82 });
83});
apps/desktop/src/backendReadiness.ts+103−0
@@ -0,0 +1,103 @@
1export interface WaitForHttpReadyOptions {
2 readonly timeoutMs?: number;
3 readonly intervalMs?: number;
4 readonly requestTimeoutMs?: number;
5 readonly fetchImpl?: typeof fetch;
6 readonly signal?: AbortSignal;
7}
8
9const DEFAULT_TIMEOUT_MS = 10_000;
10const DEFAULT_INTERVAL_MS = 100;
11const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
12
13export class BackendReadinessAbortedError extends Error {
14 constructor() {
15 super("Backend readiness wait was aborted.");
16 this.name = "BackendReadinessAbortedError";
17 }
18}
19
20function delay(ms: number, signal: AbortSignal | undefined): Promise<void> {
21 return new Promise<void>((resolve, reject) => {
22 const timer = setTimeout(() => {
23 cleanup();
24 resolve();
25 }, ms);
26
27 const onAbort = () => {
28 cleanup();
29 reject(new BackendReadinessAbortedError());
30 };
31
32 const cleanup = () => {
33 clearTimeout(timer);
34 signal?.removeEventListener("abort", onAbort);
35 };
36
37 if (signal?.aborted) {
38 cleanup();
39 reject(new BackendReadinessAbortedError());
40 return;
41 }
42
43 signal?.addEventListener("abort", onAbort, { once: true });
44 });
45}
46
47export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError {
48 return error instanceof BackendReadinessAbortedError;
49}
50
51export async function waitForHttpReady(
52 baseUrl: string,
53 options?: WaitForHttpReadyOptions,
54): Promise<void> {
55 const fetchImpl = options?.fetchImpl ?? fetch;
56 const signal = options?.signal;
57 const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
58 const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
59 const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
60 const deadline = Date.now() + timeoutMs;
61
62 for (;;) {
63 if (signal?.aborted) {
64 throw new BackendReadinessAbortedError();
65 }
66
67 const requestController = new AbortController();
68 const requestTimeout = setTimeout(() => {
69 requestController.abort();
70 }, requestTimeoutMs);
71 const abortRequest = () => {
72 requestController.abort();
73 };
74 signal?.addEventListener("abort", abortRequest, { once: true });
75
76 try {
77 const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
78 redirect: "manual",
79 signal: requestController.signal,
80 });
81 if (response.ok) {
82 return;
83 }
84 } catch (error) {
85 if (isBackendReadinessAborted(error)) {
86 throw error;
87 }
88 if (signal?.aborted) {
89 throw new BackendReadinessAbortedError();
90 }
91 // Retry until the backend becomes reachable or the deadline expires.
92 } finally {
93 clearTimeout(requestTimeout);
94 signal?.removeEventListener("abort", abortRequest);
95 }
96
97 if (Date.now() >= deadline) {
98 throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`);
99 }
100
101 await delay(intervalMs, signal);
102 }
103}
apps/desktop/src/clientPersistence.test.ts+234−0
@@ -0,0 +1,234 @@
1import * as fs from "node:fs";
2import * as os from "node:os";
3import * as path from "node:path";
4
5import {
6 EnvironmentId,
7 type ClientSettings,
8 type PersistedSavedEnvironmentRecord,
9} from "@t3tools/contracts";
10import { afterEach, describe, expect, it } from "vitest";
11
12import {
13 readClientSettings,
14 readSavedEnvironmentRegistry,
15 readSavedEnvironmentSecret,
16 removeSavedEnvironmentSecret,
17 writeClientSettings,
18 writeSavedEnvironmentRegistry,
19 writeSavedEnvironmentSecret,
20 type DesktopSecretStorage,
21} from "./clientPersistence";
22
23const tempDirectories: string[] = [];
24
25afterEach(() => {
26 for (const directory of tempDirectories.splice(0)) {
27 fs.rmSync(directory, { recursive: true, force: true });
28 }
29});
30
31function makeTempPath(fileName: string): string {
32 const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
33 tempDirectories.push(directory);
34 return path.join(directory, fileName);
35}
36
37function makeSecretStorage(available: boolean): DesktopSecretStorage {
38 return {
39 isEncryptionAvailable: () => available,
40 encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
41 decryptString: (value) => {
42 const decoded = value.toString("utf8");
43 if (!decoded.startsWith("enc:")) {
44 throw new Error("invalid secret");
45 }
46 return decoded.slice("enc:".length);
47 },
48 };
49}
50
51const clientSettings: ClientSettings = {
52 confirmThreadArchive: true,
53 confirmThreadDelete: false,
54 diffWordWrap: true,
55 sidebarProjectSortOrder: "manual",
56 sidebarThreadSortOrder: "created_at",
57 timestampFormat: "24-hour",
58};
59
60const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
61 environmentId: EnvironmentId.make("environment-1"),
62 label: "Remote environment",
63 httpBaseUrl: "https://remote.example.com/",
64 wsBaseUrl: "wss://remote.example.com/",
65 createdAt: "2026-04-09T00:00:00.000Z",
66 lastConnectedAt: "2026-04-09T01:00:00.000Z",
67};
68
69describe("clientPersistence", () => {
70 it("persists and reloads client settings", () => {
71 const settingsPath = makeTempPath("client-settings.json");
72
73 writeClientSettings(settingsPath, clientSettings);
74
75 expect(readClientSettings(settingsPath)).toEqual(clientSettings);
76 });
77
78 it("persists and reloads saved environment metadata", () => {
79 const registryPath = makeTempPath("saved-environments.json");
80
81 writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
82
83 expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
84 });
85
86 it("persists encrypted saved environment secrets when encryption is available", () => {
87 const registryPath = makeTempPath("saved-environments.json");
88 const secretStorage = makeSecretStorage(true);
89
90 writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
91
92 expect(
93 writeSavedEnvironmentSecret({
94 registryPath,
95 environmentId: savedRegistryRecord.environmentId,
96 secret: "bearer-token",
97 secretStorage,
98 }),
99 ).toBe(true);
100
101 expect(
102 readSavedEnvironmentSecret({
103 registryPath,
104 environmentId: savedRegistryRecord.environmentId,
105 secretStorage,
106 }),
107 ).toBe("bearer-token");
108
109 expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
110 records: [
111 {
112 ...savedRegistryRecord,
113 encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
114 },
115 ],
116 });
117 });
118
119 it("preserves existing secrets when encryption is unavailable", () => {
120 const registryPath = makeTempPath("saved-environments.json");
121 const availableSecretStorage = makeSecretStorage(true);
122
123 writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
124
125 writeSavedEnvironmentSecret({
126 registryPath,
127 environmentId: savedRegistryRecord.environmentId,
128 secret: "bearer-token",
129 secretStorage: availableSecretStorage,
130 });
131
132 expect(
133 writeSavedEnvironmentSecret({
134 registryPath,
135 environmentId: savedRegistryRecord.environmentId,
136 secret: "next-token",
137 secretStorage: makeSecretStorage(false),
138 }),
139 ).toBe(false);
140
141 expect(
142 readSavedEnvironmentSecret({
143 registryPath,
144 environmentId: savedRegistryRecord.environmentId,
145 secretStorage: availableSecretStorage,
146 }),
147 ).toBe("bearer-token");
148 });
149
150 it("removes saved environment secrets", () => {
151 const registryPath = makeTempPath("saved-environments.json");
152 const secretStorage = makeSecretStorage(true);
153
154 writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
155
156 writeSavedEnvironmentSecret({
157 registryPath,
158 environmentId: savedRegistryRecord.environmentId,
159 secret: "bearer-token",
160 secretStorage,
161 });
162
163 removeSavedEnvironmentSecret({
164 registryPath,
165 environmentId: savedRegistryRecord.environmentId,
166 });
167
168 expect(
169 readSavedEnvironmentSecret({
170 registryPath,
171 environmentId: savedRegistryRecord.environmentId,
172 secretStorage,
173 }),
174 ).toBeNull();
175 });
176
177 it("treats malformed secrets documents as empty", () => {
178 const registryPath = makeTempPath("saved-environments.json");
179 fs.writeFileSync(registryPath, "{}\n", "utf8");
180
181 expect(
182 readSavedEnvironmentSecret({
183 registryPath,
184 environmentId: savedRegistryRecord.environmentId,
185 secretStorage: makeSecretStorage(true),
186 }),
187 ).toBeNull();
188
189 expect(() =>
190 removeSavedEnvironmentSecret({
191 registryPath,
192 environmentId: savedRegistryRecord.environmentId,
193 }),
194 ).not.toThrow();
195 });
196
197 it("returns false when writing a secret without metadata", () => {
198 const registryPath = makeTempPath("saved-environments.json");
199
200 expect(
201 writeSavedEnvironmentSecret({
202 registryPath,
203 environmentId: savedRegistryRecord.environmentId,
204 secret: "bearer-token",
205 secretStorage: makeSecretStorage(true),
206 }),
207 ).toBe(false);
208 });
209
210 it("preserves encrypted secrets when metadata is rewritten", () => {
211 const registryPath = makeTempPath("saved-environments.json");
212 const secretStorage = makeSecretStorage(true);
213
214 writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
215
216 writeSavedEnvironmentSecret({
217 registryPath,
218 environmentId: savedRegistryRecord.environmentId,
219 secret: "bearer-token",
220 secretStorage,
221 });
222
223 writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
224
225 expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
226 expect(
227 readSavedEnvironmentSecret({
228 registryPath,
229 environmentId: savedRegistryRecord.environmentId,
230 secretStorage,
231 }),
232 ).toBe("bearer-token");
233 });
234});
apps/desktop/src/clientPersistence.ts+216−0
@@ -0,0 +1,216 @@
1import * as FS from "node:fs";
2import * as Path from "node:path";
3
4import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
5import { Predicate } from "effect";
6
7interface ClientSettingsDocument {
8 readonly settings: ClientSettings;
9}
10
11interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
12 readonly encryptedBearerToken?: string;
13}
14
15interface SavedEnvironmentRegistryDocument {
16 readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
17}
18
19export interface DesktopSecretStorage {
20 readonly isEncryptionAvailable: () => boolean;
21 readonly encryptString: (value: string) => Buffer;
22 readonly decryptString: (value: Buffer) => string;
23}
24
25function readJsonFile<T>(filePath: string): T | null {
26 try {
27 if (!FS.existsSync(filePath)) {
28 return null;
29 }
30 return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
31 } catch {
32 return null;
33 }
34}
35
36function writeJsonFile(filePath: string, value: unknown): void {
37 const directory = Path.dirname(filePath);
38 const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
39 FS.mkdirSync(directory, { recursive: true });
40 FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
41 FS.renameSync(tempPath, filePath);
42}
43
44function isPersistedSavedEnvironmentStorageRecord(
45 value: unknown,
46): value is PersistedSavedEnvironmentStorageRecord {
47 return (
48 Predicate.isObject(value) &&
49 typeof value.environmentId === "string" &&
50 typeof value.label === "string" &&
51 typeof value.httpBaseUrl === "string" &&
52 typeof value.wsBaseUrl === "string" &&
53 typeof value.createdAt === "string" &&
54 (value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
55 (value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
56 );
57}
58
59function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
60 const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
61 if (!Predicate.isObject(parsed)) {
62 return { records: [] };
63 }
64
65 return {
66 records: Array.isArray(parsed.records)
67 ? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
68 : [],
69 };
70}
71
72function toPersistedSavedEnvironmentRecord(
73 record: PersistedSavedEnvironmentStorageRecord,
74): PersistedSavedEnvironmentRecord {
75 return {
76 environmentId: record.environmentId,
77 label: record.label,
78 httpBaseUrl: record.httpBaseUrl,
79 wsBaseUrl: record.wsBaseUrl,
80 createdAt: record.createdAt,
81 lastConnectedAt: record.lastConnectedAt,
82 };
83}
84
85export function readClientSettings(settingsPath: string): ClientSettings | null {
86 return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
87}
88
89export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
90 writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
91}
92
93export function readSavedEnvironmentRegistry(
94 registryPath: string,
95): readonly PersistedSavedEnvironmentRecord[] {
96 return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
97 toPersistedSavedEnvironmentRecord(record),
98 );
99}
100
101export function writeSavedEnvironmentRegistry(
102 registryPath: string,
103 records: readonly PersistedSavedEnvironmentRecord[],
104): void {
105 const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
106 const encryptedBearerTokenById = new Map(
107 currentDocument.records.flatMap((record) =>
108 record.encryptedBearerToken
109 ? [[record.environmentId, record.encryptedBearerToken] as const]
110 : [],
111 ),
112 );
113 writeJsonFile(registryPath, {
114 records: records.map((record) => {
115 const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
116 return encryptedBearerToken
117 ? {
118 environmentId: record.environmentId,
119 label: record.label,
120 httpBaseUrl: record.httpBaseUrl,
121 wsBaseUrl: record.wsBaseUrl,
122 createdAt: record.createdAt,
123 lastConnectedAt: record.lastConnectedAt,
124 encryptedBearerToken,
125 }
126 : record;
127 }),
128 } satisfies SavedEnvironmentRegistryDocument);
129}
130
131export function readSavedEnvironmentSecret(input: {
132 readonly registryPath: string;
133 readonly environmentId: string;
134 readonly secretStorage: DesktopSecretStorage;
135}): string | null {
136 const document = readSavedEnvironmentRegistryDocument(input.registryPath);
137 const encoded = document.records.find(
138 (record) => record.environmentId === input.environmentId,
139 )?.encryptedBearerToken;
140 if (!encoded) {
141 return null;
142 }
143
144 if (!input.secretStorage.isEncryptionAvailable()) {
145 return null;
146 }
147
148 try {
149 return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
150 } catch {
151 return null;
152 }
153}
154
155export function writeSavedEnvironmentSecret(input: {
156 readonly registryPath: string;
157 readonly environmentId: string;
158 readonly secret: string;
159 readonly secretStorage: DesktopSecretStorage;
160}): boolean {
161 const document = readSavedEnvironmentRegistryDocument(input.registryPath);
162
163 if (!input.secretStorage.isEncryptionAvailable()) {
164 return false;
165 }
166
167 let found = false;
168
169 writeJsonFile(input.registryPath, {
170 records: document.records.map((record) => {
171 if (record.environmentId !== input.environmentId) {
172 return record;
173 }
174
175 found = true;
176 const encryptedBearerToken = input.secretStorage
177 .encryptString(input.secret)
178 .toString("base64");
179 return {
180 environmentId: record.environmentId,
181 label: record.label,
182 httpBaseUrl: record.httpBaseUrl,
183 wsBaseUrl: record.wsBaseUrl,
184 createdAt: record.createdAt,
185 lastConnectedAt: record.lastConnectedAt,
186 encryptedBearerToken,
187 } satisfies PersistedSavedEnvironmentStorageRecord;
188 }),
189 } satisfies SavedEnvironmentRegistryDocument);
190 return found;
191}
192
193export function removeSavedEnvironmentSecret(input: {
194 readonly registryPath: string;
195 readonly environmentId: string;
196}): void {
197 const document = readSavedEnvironmentRegistryDocument(input.registryPath);
198 if (
199 !document.records.some(
200 (record) =>
201 record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
202 )
203 ) {
204 return;
205 }
206
207 writeJsonFile(input.registryPath, {
208 records: document.records.map((record) => {
209 if (record.environmentId !== input.environmentId) {
210 return record;
211 }
212
213 return toPersistedSavedEnvironmentRecord(record);
214 }),
215 } satisfies SavedEnvironmentRegistryDocument);
216}
apps/desktop/src/desktopSettings.test.ts+64−0
@@ -0,0 +1,64 @@
1import * as fs from "node:fs";
2import * as os from "node:os";
3import * as path from "node:path";
4
5import { afterEach, describe, expect, it } from "vitest";
6
7import {
8 DEFAULT_DESKTOP_SETTINGS,
9 readDesktopSettings,
10 setDesktopServerExposurePreference,
11 writeDesktopSettings,
12} from "./desktopSettings";
13
14const tempDirectories: string[] = [];
15
16afterEach(() => {
17 for (const directory of tempDirectories.splice(0)) {
18 fs.rmSync(directory, { recursive: true, force: true });
19 }
20});
21
22function makeSettingsPath() {
23 const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-"));
24 tempDirectories.push(directory);
25 return path.join(directory, "desktop-settings.json");
26}
27
28describe("desktopSettings", () => {
29 it("returns defaults when no settings file exists", () => {
30 expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
31 });
32
33 it("persists and reloads the configured server exposure mode", () => {
34 const settingsPath = makeSettingsPath();
35
36 writeDesktopSettings(settingsPath, {
37 serverExposureMode: "network-accessible",
38 });
39
40 expect(readDesktopSettings(settingsPath)).toEqual({
41 serverExposureMode: "network-accessible",
42 });
43 });
44
45 it("preserves the requested network-accessible preference across temporary fallback", () => {
46 expect(
47 setDesktopServerExposurePreference(
48 {
49 serverExposureMode: "local-only",
50 },
51 "network-accessible",
52 ),
53 ).toEqual({
54 serverExposureMode: "network-accessible",
55 });
56 });
57
58 it("falls back to defaults when the settings file is malformed", () => {
59 const settingsPath = makeSettingsPath();
60 fs.writeFileSync(settingsPath, "{not-json", "utf8");
61
62 expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
63 });
64});
apps/desktop/src/desktopSettings.ts+51−0
@@ -0,0 +1,51 @@
1import * as FS from "node:fs";
2import * as Path from "node:path";
3import type { DesktopServerExposureMode } from "@t3tools/contracts";
4
5export interface DesktopSettings {
6 readonly serverExposureMode: DesktopServerExposureMode;
7}
8
9export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
10 serverExposureMode: "local-only",
11};
12
13export function setDesktopServerExposurePreference(
14 settings: DesktopSettings,
15 requestedMode: DesktopServerExposureMode,
16): DesktopSettings {
17 return settings.serverExposureMode === requestedMode
18 ? settings
19 : {
20 ...settings,
21 serverExposureMode: requestedMode,
22 };
23}
24
25export function readDesktopSettings(settingsPath: string): DesktopSettings {
26 try {
27 if (!FS.existsSync(settingsPath)) {
28 return DEFAULT_DESKTOP_SETTINGS;
29 }
30
31 const raw = FS.readFileSync(settingsPath, "utf8");
32 const parsed = JSON.parse(raw) as {
33 readonly serverExposureMode?: unknown;
34 };
35
36 return {
37 serverExposureMode:
38 parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
39 };
40 } catch {
41 return DEFAULT_DESKTOP_SETTINGS;
42 }
43}
44
45export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void {
46 const directory = Path.dirname(settingsPath);
47 const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
48 FS.mkdirSync(directory, { recursive: true });
49 FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
50 FS.renameSync(tempPath, settingsPath);
51}
apps/desktop/src/main.ts+477−43
@@ -7,18 +7,23 @@ import * as Path from "node:path"; · 6 unmodified lines
7import {7import {
8 app,8 app,
9 BrowserWindow,9 BrowserWindow,
10 clipboard,
10 dialog,11 dialog,
11 ipcMain,12 ipcMain,
12 Menu,13 Menu,
13 nativeImage,14 nativeImage,
14 nativeTheme,15 nativeTheme,
15 protocol,16 protocol,
17 safeStorage,
16 shell,18 shell,
17} from "electron";19} from "electron";
18import type { MenuItemConstructorOptions } from "electron";20import type { MenuItemConstructorOptions } from "electron";
19import * as Effect from "effect/Effect";
20import type {21import type {
22 ClientSettings,
21 DesktopTheme,23 DesktopTheme,
24 DesktopServerExposureMode,
25 DesktopServerExposureState,
26 PersistedSavedEnvironmentRecord,
22 DesktopUpdateActionResult,27 DesktopUpdateActionResult,
23 DesktopUpdateCheckResult,28 DesktopUpdateCheckResult,
24 DesktopUpdateState,29 DesktopUpdateState,
@@ -26,9 +31,27 @@ import type { · 1 unmodified line
26import { autoUpdater } from "electron-updater";31import { autoUpdater } from "electron-updater";
27 32
28import type { ContextMenuItem } from "@t3tools/contracts";33import type { ContextMenuItem } from "@t3tools/contracts";
29import { NetService } from "@t3tools/shared/Net";
30import { RotatingFileSink } from "@t3tools/shared/logging";34import { RotatingFileSink } from "@t3tools/shared/logging";
35import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
36import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
37import {
38 DEFAULT_DESKTOP_SETTINGS,
39 readDesktopSettings,
40 setDesktopServerExposurePreference,
41 writeDesktopSettings,
42} from "./desktopSettings";
43import {
44 readClientSettings,
45 readSavedEnvironmentRegistry,
46 readSavedEnvironmentSecret,
47 removeSavedEnvironmentSecret,
48 writeClientSettings,
49 writeSavedEnvironmentRegistry,
50 writeSavedEnvironmentSecret,
51} from "./clientPersistence";
52import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
31import { showDesktopConfirmDialog } from "./confirmDialog";53import { showDesktopConfirmDialog } from "./confirmDialog";
54import { resolveDesktopServerExposure } from "./serverExposure";
32import { syncShellEnvironment } from "./syncShellEnvironment";55import { syncShellEnvironment } from "./syncShellEnvironment";
33import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";56import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
34import {57import {
@@ -58,14 +81,26 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; · 23 unmodified lines
58const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";81const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
59const UPDATE_INSTALL_CHANNEL = "desktop:update-install";82const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
60const UPDATE_CHECK_CHANNEL = "desktop:update-check";83const UPDATE_CHECK_CHANNEL = "desktop:update-check";
61const GET_WS_URL_CHANNEL = "desktop:get-ws-url";84const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
85const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
86const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
87const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
88const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
89const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
90const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
91const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
92const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
93const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
62const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");94const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
63const STATE_DIR = Path.join(BASE_DIR, "userdata");95const STATE_DIR = Path.join(BASE_DIR, "userdata");
96const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
97const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
98const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
64const DESKTOP_SCHEME = "t3";99const DESKTOP_SCHEME = "t3";
65const ROOT_DIR = Path.resolve(__dirname, "../../..");100const ROOT_DIR = Path.resolve(__dirname, "../../..");
66const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);101const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
67const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";102const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
68const APP_USER_MODEL_ID = "com.t3tools.t3code";103const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
69const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";104const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
70const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";105const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
71const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";106const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
@@ -76,10 +111,13 @@ const LOG_DIR = Path.join(STATE_DIR, "logs"); · 4 unmodified lines
76const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;111const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
77const LOG_FILE_MAX_FILES = 10;112const LOG_FILE_MAX_FILES = 10;
78const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");113const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
114const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
79const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;115const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
80const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;116const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
81const DESKTOP_UPDATE_CHANNEL = "latest";117const DESKTOP_UPDATE_CHANNEL = "latest";
82const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;118const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
119const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
120const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
83 121
84type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];122type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
85type LinuxDesktopNamedApp = Electron.App & {123type LinuxDesktopNamedApp = Electron.App & {
@@ -89,8 +127,13 @@ type LinuxDesktopNamedApp = Electron.App & { · 3 unmodified lines
89let mainWindow: BrowserWindow | null = null;127let mainWindow: BrowserWindow | null = null;
90let backendProcess: ChildProcess.ChildProcess | null = null;128let backendProcess: ChildProcess.ChildProcess | null = null;
91let backendPort = 0;129let backendPort = 0;
92let backendAuthToken = "";130let backendBindHost = DESKTOP_LOOPBACK_HOST;
131let backendBootstrapToken = "";
132let backendHttpUrl = "";
93let backendWsUrl = "";133let backendWsUrl = "";
134let backendEndpointUrl: string | null = null;
135let backendAdvertisedHost: string | null = null;
136let backendReadinessAbortController: AbortController | null = null;
94let restartAttempt = 0;137let restartAttempt = 0;
95let restartTimer: ReturnType<typeof setTimeout> | null = null;138let restartTimer: ReturnType<typeof setTimeout> | null = null;
96let isQuitting = false;139let isQuitting = false;
@@ -99,8 +142,12 @@ let aboutCommitHashCache: string | null | undefined; · 2 unmodified lines
99let desktopLogSink: RotatingFileSink | null = null;142let desktopLogSink: RotatingFileSink | null = null;
100let backendLogSink: RotatingFileSink | null = null;143let backendLogSink: RotatingFileSink | null = null;
101let restoreStdIoCapture: (() => void) | null = null;144let restoreStdIoCapture: (() => void) | null = null;
145let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
146let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
147let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
102 148
103let destructiveMenuIconCache: Electron.NativeImage | null | undefined;149let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
150const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
104const desktopRuntimeInfo = resolveDesktopRuntimeInfo({151const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
105 platform: process.platform,152 platform: process.platform,
106 processArch: process.arch,153 processArch: process.arch,
@@ -121,17 +168,143 @@ function sanitizeLogValue(value: string): string { · 14 unmodified lines
121 return value.replace(/\s+/g, " ").trim();168 return value.replace(/\s+/g, " ").trim();
122}169}
123 170
171function readPersistedBackendObservabilitySettings(): {
172 readonly otlpTracesUrl: string | undefined;
173 readonly otlpMetricsUrl: string | undefined;
174} {
175 try {
176 if (!FS.existsSync(SERVER_SETTINGS_PATH)) {
177 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
178 }
179 return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8"));
180 } catch (error) {
181 console.warn("[desktop] failed to read persisted backend observability settings", error);
182 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
183 }
184}
185
186function resolveConfiguredDesktopBackendPort(rawPort: string | undefined): number | undefined {
187 if (!rawPort) {
188 return undefined;
189 }
190
191 const parsedPort = Number.parseInt(rawPort, 10);
192 if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65_535) {
193 return undefined;
194 }
195
196 return parsedPort;
197}
198
199function resolveDesktopDevServerUrl(): string {
200 const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
201 if (!devServerUrl) {
202 throw new Error("VITE_DEV_SERVER_URL is required in desktop development.");
203 }
204
205 return devServerUrl;
206}
207
124function backendChildEnv(): NodeJS.ProcessEnv {208function backendChildEnv(): NodeJS.ProcessEnv {
125 const env = { ...process.env };209 const env = { ...process.env };
126 delete env.T3CODE_PORT;210 delete env.T3CODE_PORT;
127 delete env.T3CODE_AUTH_TOKEN;
128 delete env.T3CODE_MODE;211 delete env.T3CODE_MODE;
129 delete env.T3CODE_NO_BROWSER;212 delete env.T3CODE_NO_BROWSER;
130 delete env.T3CODE_HOST;213 delete env.T3CODE_HOST;
131 delete env.T3CODE_DESKTOP_WS_URL;214 delete env.T3CODE_DESKTOP_WS_URL;
215 delete env.T3CODE_DESKTOP_LAN_ACCESS;
216 delete env.T3CODE_DESKTOP_LAN_HOST;
132 return env;217 return env;
133}218}
134 219
220function getDesktopServerExposureState(): DesktopServerExposureState {
221 return {
222 mode: desktopServerExposureMode,
223 endpointUrl: backendEndpointUrl,
224 advertisedHost: backendAdvertisedHost,
225 };
226}
227
228function getDesktopSecretStorage() {
229 return {
230 isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
231 encryptString: (value: string) => safeStorage.encryptString(value),
232 decryptString: (value: Buffer) => safeStorage.decryptString(value),
233 } as const;
234}
235
236function resolveAdvertisedHostOverride(): string | undefined {
237 const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim();
238 return override && override.length > 0 ? override : undefined;
239}
240
241async function applyDesktopServerExposureMode(
242 mode: DesktopServerExposureMode,
243 options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean },
244): Promise<DesktopServerExposureState> {
245 const advertisedHostOverride = resolveAdvertisedHostOverride();
246 const requestedMode = mode;
247 let exposure = resolveDesktopServerExposure({
248 mode,
249 port: backendPort,
250 networkInterfaces: OS.networkInterfaces(),
251 ...(advertisedHostOverride ? { advertisedHostOverride } : {}),
252 });
253
254 if (requestedMode === "network-accessible" && exposure.endpointUrl === null) {
255 if (options?.rejectIfUnavailable) {
256 throw new Error("No reachable network address is available for this desktop right now.");
257 }
258 exposure = resolveDesktopServerExposure({
259 mode: "local-only",
260 port: backendPort,
261 networkInterfaces: OS.networkInterfaces(),
262 ...(advertisedHostOverride ? { advertisedHostOverride } : {}),
263 });
264 }
265
266 desktopServerExposureMode = exposure.mode;
267 desktopSettings = setDesktopServerExposurePreference(desktopSettings, requestedMode);
268 backendBindHost = exposure.bindHost;
269 backendHttpUrl = exposure.localHttpUrl;
270 backendWsUrl = exposure.localWsUrl;
271 backendEndpointUrl = exposure.endpointUrl;
272 backendAdvertisedHost = exposure.advertisedHost;
273
274 if (options?.persist) {
275 writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
276 }
277
278 return getDesktopServerExposureState();
279}
280
281function relaunchDesktopApp(reason: string): void {
282 writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`);
283 setImmediate(() => {
284 isQuitting = true;
285 clearUpdatePollTimer();
286 cancelBackendReadinessWait();
287 void stopBackendAndWaitForExit()
288 .catch((error) => {
289 writeDesktopLogHeader(
290 `desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`,
291 );
292 })
293 .finally(() => {
294 restoreStdIoCapture?.();
295 if (isDevelopment) {
296 app.exit(75);
297 return;
298 }
299 app.relaunch({
300 execPath: process.execPath,
301 args: process.argv.slice(1),
302 });
303 app.exit(0);
304 });
305 });
306}
307
135function writeDesktopLogHeader(message: string): void {308function writeDesktopLogHeader(message: string): void {
136 if (!desktopLogSink) return;309 if (!desktopLogSink) return;
137 desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);310 desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
@@ -179,6 +352,27 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null { · 41 unmodified lines
179 return null;352 return null;
180}353}
181 354
355async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
356 cancelBackendReadinessWait();
357 const controller = new AbortController();
358 backendReadinessAbortController = controller;
359
360 try {
361 await waitForHttpReady(baseUrl, {
362 signal: controller.signal,
363 });
364 } finally {
365 if (backendReadinessAbortController === controller) {
366 backendReadinessAbortController = null;
367 }
368 }
369}
370
371function cancelBackendReadinessWait(): void {
372 backendReadinessAbortController?.abort();
373 backendReadinessAbortController = null;
374}
375
182function writeDesktopStreamChunk(376function writeDesktopStreamChunk(
183 streamName: "stdout" | "stderr",377 streamName: "stdout" | "stderr",
184 chunk: unknown,378 chunk: unknown,
@@ -523,10 +717,7 @@ function dispatchMenuAction(action: string): void { · 338 unmodified lines
523 const send = () => {717 const send = () => {
524 if (targetWindow.isDestroyed()) return;718 if (targetWindow.isDestroyed()) return;
525 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);719 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
526 if (!targetWindow.isVisible()) {720 revealWindow(targetWindow);
527 targetWindow.show();
528 }
529 targetWindow.focus();
530 };721 };
531 722
532 if (targetWindow.webContents.isLoadingMainFrame()) {723 if (targetWindow.webContents.isLoadingMainFrame()) {
@@ -538,12 +729,15 @@ function dispatchMenuAction(action: string): void { · 5 unmodified lines
538}729}
539 730
540function handleCheckForUpdatesMenuClick(): void {731function handleCheckForUpdatesMenuClick(): void {
732 const hasUpdateFeedConfig =
733 readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
541 const disabledReason = getAutoUpdateDisabledReason({734 const disabledReason = getAutoUpdateDisabledReason({
542 isDevelopment,735 isDevelopment,
543 isPackaged: app.isPackaged,736 isPackaged: app.isPackaged,
544 platform: process.platform,737 platform: process.platform,
545 appImage: process.env.APPIMAGE,738 appImage: process.env.APPIMAGE,
546 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",739 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
740 hasUpdateFeedConfig,
547 });741 });
548 if (disabledReason) {742 if (disabledReason) {
549 console.info("[desktop-updater] Manual update check requested, but updates are disabled.");743 console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
@@ -747,6 +941,26 @@ function clearUpdatePollTimer(): void { · 197 unmodified lines
747 }941 }
748}942}
749 943
944function revealWindow(window: BrowserWindow): void {
945 if (window.isDestroyed()) {
946 return;
947 }
948
949 if (window.isMinimized()) {
950 window.restore();
951 }
952
953 if (!window.isVisible()) {
954 window.show();
955 }
956
957 if (process.platform === "darwin") {
958 app.focus({ steal: true });
959 }
960
961 window.focus();
962}
963
750function emitUpdateState(): void {964function emitUpdateState(): void {
751 for (const window of BrowserWindow.getAllWindows()) {965 for (const window of BrowserWindow.getAllWindows()) {
752 if (window.isDestroyed()) continue;966 if (window.isDestroyed()) continue;
@@ -760,6 +974,8 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void { · 7 unmodified lines
760}974}
761 975
762function shouldEnableAutoUpdates(): boolean {976function shouldEnableAutoUpdates(): boolean {
977 const hasUpdateFeedConfig =
978 readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
763 return (979 return (
764 getAutoUpdateDisabledReason({980 getAutoUpdateDisabledReason({
765 isDevelopment,981 isDevelopment,
@@ -767,6 +983,7 @@ function shouldEnableAutoUpdates(): boolean { · 1 unmodified line
767 platform: process.platform,983 platform: process.platform,
768 appImage: process.env.APPIMAGE,984 appImage: process.env.APPIMAGE,
769 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",985 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
986 hasUpdateFeedConfig,
770 }) === null987 }) === null
771 );988 );
772}989}
@@ -850,17 +1067,6 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed · 77 unmodified lines
850}1067}
851 1068
852function configureAutoUpdater(): void {1069function configureAutoUpdater(): void {
853 const enabled = shouldEnableAutoUpdates();
854 setUpdateState({
855 ...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
856 enabled,
857 status: enabled ? "idle" : "disabled",
858 });
859 if (!enabled) {
860 return;
861 }
862 updaterConfigured = true;
863
864 const githubToken =1070 const githubToken =
865 process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";1071 process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
866 if (githubToken) {1072 if (githubToken) {
@@ -885,6 +1091,17 @@ function configureAutoUpdater(): void { · 18 unmodified lines
885 });1091 });
886 }1092 }
887 1093
1094 const enabled = shouldEnableAutoUpdates();
1095 setUpdateState({
1096 ...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
1097 enabled,
1098 status: enabled ? "idle" : "disabled",
1099 });
1100 if (!enabled) {
1101 return;
1102 }
1103 updaterConfigured = true;
1104
888 autoUpdater.autoDownload = false;1105 autoUpdater.autoDownload = false;
889 autoUpdater.autoInstallOnAppQuit = false;1106 autoUpdater.autoInstallOnAppQuit = false;
890 // Keep alpha branding, but force all installs onto the stable update track.1107 // Keep alpha branding, but force all installs onto the stable update track.
@@ -988,6 +1205,7 @@ function scheduleBackendRestart(reason: string): void { · 97 unmodified lines
988function startBackend(): void {1205function startBackend(): void {
989 if (isQuitting || backendProcess) return;1206 if (isQuitting || backendProcess) return;
990 1207
1208 backendObservabilitySettings = readPersistedBackendObservabilitySettings();
991 const backendEntry = resolveBackendEntry();1209 const backendEntry = resolveBackendEntry();
992 if (!FS.existsSync(backendEntry)) {1210 if (!FS.existsSync(backendEntry)) {
993 scheduleBackendRestart(`missing server entry at ${backendEntry}`);1211 scheduleBackendRestart(`missing server entry at ${backendEntry}`);
@@ -1015,7 +1233,14 @@ function startBackend(): void { · 21 unmodified lines
1015 noBrowser: true,1233 noBrowser: true,
1016 port: backendPort,1234 port: backendPort,
1017 t3Home: BASE_DIR,1235 t3Home: BASE_DIR,
1018 authToken: backendAuthToken,1236 host: backendBindHost,
1237 desktopBootstrapToken: backendBootstrapToken,
1238 ...(backendObservabilitySettings.otlpTracesUrl
1239 ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
1240 : {}),
1241 ...(backendObservabilitySettings.otlpMetricsUrl
1242 ? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
1243 : {}),
1019 })}\n`,1244 })}\n`,
1020 );1245 );
1021 bootstrapStream.end();1246 bootstrapStream.end();
@@ -1042,27 +1267,33 @@ function startBackend(): void { · 20 unmodified lines
1042 });1267 });
1043 1268
1044 child.on("error", (error) => {1269 child.on("error", (error) => {
1270 const wasExpected = expectedBackendExitChildren.has(child);
1045 if (backendProcess === child) {1271 if (backendProcess === child) {
1046 backendProcess = null;1272 backendProcess = null;
1047 }1273 }
1048 closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);1274 closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
1275 if (wasExpected) {
1276 return;
1277 }
1049 scheduleBackendRestart(error.message);1278 scheduleBackendRestart(error.message);
1050 });1279 });
1051 1280
1052 child.on("exit", (code, signal) => {1281 child.on("exit", (code, signal) => {
1282 const wasExpected = expectedBackendExitChildren.has(child);
1053 if (backendProcess === child) {1283 if (backendProcess === child) {
1054 backendProcess = null;1284 backendProcess = null;
1055 }1285 }
1056 closeBackendSession(1286 closeBackendSession(
1057 `pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,1287 `pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
1058 );1288 );
1059 if (isQuitting) return;1289 if (isQuitting || wasExpected) return;
1060 const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;1290 const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
1061 scheduleBackendRestart(reason);1291 scheduleBackendRestart(reason);
1062 });1292 });
1063}1293}
1064 1294
1065function stopBackend(): void {1295function stopBackend(): void {
1296 cancelBackendReadinessWait();
1066 if (restartTimer) {1297 if (restartTimer) {
1067 clearTimeout(restartTimer);1298 clearTimeout(restartTimer);
1068 restartTimer = null;1299 restartTimer = null;
@@ -1073,6 +1304,7 @@ function stopBackend(): void { · 4 unmodified lines
1073 if (!child) return;1304 if (!child) return;
1074 1305
1075 if (child.exitCode === null && child.signalCode === null) {1306 if (child.exitCode === null && child.signalCode === null) {
1307 expectedBackendExitChildren.add(child);
1076 child.kill("SIGTERM");1308 child.kill("SIGTERM");
1077 setTimeout(() => {1309 setTimeout(() => {
1078 if (child.exitCode === null && child.signalCode === null) {1310 if (child.exitCode === null && child.signalCode === null) {
@@ -1083,6 +1315,7 @@ function stopBackend(): void { · 4 unmodified lines
1083}1315}
1084 1316
1085async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {1317async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
1318 cancelBackendReadinessWait();
1086 if (restartTimer) {1319 if (restartTimer) {
1087 clearTimeout(restartTimer);1320 clearTimeout(restartTimer);
1088 restartTimer = null;1321 restartTimer = null;
@@ -1093,6 +1326,7 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> { · 4 unmodified lines
1093 if (!child) return;1326 if (!child) return;
1094 const backendChild = child;1327 const backendChild = child;
1095 if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;1328 if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
1329 expectedBackendExitChildren.add(backendChild);
1096 1330
1097 await new Promise<void>((resolve) => {1331 await new Promise<void>((resolve) => {
1098 let settled = false;1332 let settled = false;
@@ -1134,9 +1368,116 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> { · 35 unmodified lines
1134}1368}
1135 1369
1136function registerIpcHandlers(): void {1370function registerIpcHandlers(): void {
1137 ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);1371 ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
1138 ipcMain.on(GET_WS_URL_CHANNEL, (event) => {1372 ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
1139 event.returnValue = backendWsUrl;1373 event.returnValue = {
1374 label: "Local environment",
1375 httpBaseUrl: backendHttpUrl || null,
1376 wsBaseUrl: backendWsUrl || null,
1377 bootstrapToken: backendBootstrapToken || undefined,
1378 } as const;
1379 });
1380
1381 ipcMain.removeHandler(GET_CLIENT_SETTINGS_CHANNEL);
1382 ipcMain.handle(GET_CLIENT_SETTINGS_CHANNEL, async () => readClientSettings(CLIENT_SETTINGS_PATH));
1383
1384 ipcMain.removeHandler(SET_CLIENT_SETTINGS_CHANNEL);
1385 ipcMain.handle(SET_CLIENT_SETTINGS_CHANNEL, async (_event, rawSettings: unknown) => {
1386 if (typeof rawSettings !== "object" || rawSettings === null) {
1387 throw new Error("Invalid client settings payload.");
1388 }
1389
1390 writeClientSettings(CLIENT_SETTINGS_PATH, rawSettings as ClientSettings);
1391 });
1392
1393 ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
1394 ipcMain.handle(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async () =>
1395 readSavedEnvironmentRegistry(SAVED_ENVIRONMENT_REGISTRY_PATH),
1396 );
1397
1398 ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
1399 ipcMain.handle(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async (_event, rawRecords: unknown) => {
1400 if (!Array.isArray(rawRecords)) {
1401 throw new Error("Invalid saved environment registry payload.");
1402 }
1403
1404 writeSavedEnvironmentRegistry(
1405 SAVED_ENVIRONMENT_REGISTRY_PATH,
1406 rawRecords as readonly PersistedSavedEnvironmentRecord[],
1407 );
1408 });
1409
1410 ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
1411 ipcMain.handle(
1412 GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
1413 async (_event, rawEnvironmentId: unknown) => {
1414 if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
1415 return null;
1416 }
1417
1418 return readSavedEnvironmentSecret({
1419 registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
1420 environmentId: rawEnvironmentId,
1421 secretStorage: getDesktopSecretStorage(),
1422 });
1423 },
1424 );
1425
1426 ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
1427 ipcMain.handle(
1428 SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
1429 async (_event, rawEnvironmentId: unknown, rawSecret: unknown) => {
1430 if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
1431 throw new Error("Invalid saved environment id.");
1432 }
1433 if (typeof rawSecret !== "string" || rawSecret.trim().length === 0) {
1434 throw new Error("Invalid saved environment secret.");
1435 }
1436
1437 return writeSavedEnvironmentSecret({
1438 registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
1439 environmentId: rawEnvironmentId,
1440 secret: rawSecret,
1441 secretStorage: getDesktopSecretStorage(),
1442 });
1443 },
1444 );
1445
1446 ipcMain.removeHandler(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL);
1447 ipcMain.handle(
1448 REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
1449 async (_event, rawEnvironmentId: unknown) => {
1450 if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
1451 return;
1452 }
1453
1454 removeSavedEnvironmentSecret({
1455 registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
1456 environmentId: rawEnvironmentId,
1457 });
1458 },
1459 );
1460
1461 ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
1462 ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
1463
1464 ipcMain.removeHandler(SET_SERVER_EXPOSURE_MODE_CHANNEL);
1465 ipcMain.handle(SET_SERVER_EXPOSURE_MODE_CHANNEL, async (_event, rawMode: unknown) => {
1466 if (rawMode !== "local-only" && rawMode !== "network-accessible") {
1467 throw new Error("Invalid desktop server exposure input.");
1468 }
1469
1470 const nextMode = rawMode as DesktopServerExposureMode;
1471 if (nextMode === desktopServerExposureMode) {
1472 return getDesktopServerExposureState();
1473 }
1474
1475 const nextState = await applyDesktopServerExposureMode(nextMode, {
1476 persist: true,
1477 rejectIfUnavailable: true,
1478 });
1479 relaunchDesktopApp(`serverExposureMode=${nextMode}`);
1480 return nextState;
1140 });1481 });
1141 1482
1142 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);1483 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
@@ -1304,14 +1645,19 @@ function getIconOption(): { icon: string } | Record<string, never> { · 161 unmodified lines
1304 return iconPath ? { icon: iconPath } : {};1645 return iconPath ? { icon: iconPath } : {};
1305}1646}
1306 1647
1648function getInitialWindowBackgroundColor(): string {
1649 return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
1650}
1651
1307function createWindow(): BrowserWindow {1652function createWindow(): BrowserWindow {
1308 const window = new BrowserWindow({1653 const window = new BrowserWindow({
1309 width: 1100,1654 width: 1100,
1310 height: 780,1655 height: 780,
1311 minWidth: 840,1656 minWidth: 840,
1312 minHeight: 620,1657 minHeight: 620,
1313 show: false,1658 show: isDevelopment,
1314 autoHideMenuBar: true,1659 autoHideMenuBar: true,
1660 backgroundColor: getInitialWindowBackgroundColor(),
1315 ...getIconOption(),1661 ...getIconOption(),
1316 title: APP_DISPLAY_NAME,1662 title: APP_DISPLAY_NAME,
1317 titleBarStyle: "hiddenInset",1663 titleBarStyle: "hiddenInset",
@@ -1342,6 +1688,22 @@ function createWindow(): BrowserWindow { · 24 unmodified lines
1342 menuTemplate.push({ type: "separator" });1688 menuTemplate.push({ type: "separator" });
1343 }1689 }
1344 1690
1691 const externalUrl = getSafeExternalUrl(params.linkURL);
1692 if (externalUrl) {
1693 menuTemplate.push(
1694 { label: "Copy Link", click: () => clipboard.writeText(params.linkURL) },
1695 { type: "separator" },
1696 );
1697 }
1698
1699 if (params.mediaType === "image") {
1700 menuTemplate.push({
1701 label: "Copy Image",
1702 click: () => window.webContents.copyImageAt(params.x, params.y),
1703 });
1704 menuTemplate.push({ type: "separator" });
1705 }
1706
1345 menuTemplate.push(1707 menuTemplate.push(
1346 { role: "cut", enabled: params.editFlags.canCut },1708 { role: "cut", enabled: params.editFlags.canCut },
1347 { role: "copy", enabled: params.editFlags.canCopy },1709 { role: "copy", enabled: params.editFlags.canCopy },
@@ -1368,15 +1730,20 @@ function createWindow(): BrowserWindow { · 20 unmodified lines
1368 window.setTitle(APP_DISPLAY_NAME);1730 window.setTitle(APP_DISPLAY_NAME);
1369 emitUpdateState();1731 emitUpdateState();
1370 });1732 });
1371 window.once("ready-to-show", () => {1733 if (!isDevelopment) {
1372 window.show();1734 window.once("ready-to-show", () => {
1373 });1735 revealWindow(window);
1736 });
1737 }
1374 1738
1375 if (isDevelopment) {1739 if (isDevelopment) {
1376 void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);1740 void window.loadURL(resolveDesktopDevServerUrl());
1377 window.webContents.openDevTools({ mode: "detach" });1741 window.webContents.openDevTools({ mode: "detach" });
1742 setImmediate(() => {
1743 revealWindow(window);
1744 });
1378 } else {1745 } else {
1379 void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);1746 void window.loadURL(resolveDesktopWindowUrl());
1380 }1747 }
1381 1748
1382 window.on("closed", () => {1749 window.on("closed", () => {
@@ -1388,6 +1755,14 @@ function createWindow(): BrowserWindow { · 5 unmodified lines
1388 return window;1755 return window;
1389}1756}
1390 1757
1758function resolveDesktopWindowUrl(): string {
1759 if (backendHttpUrl) {
1760 return backendHttpUrl;
1761 }
1762
1763 return `${DESKTOP_SCHEME}://app`;
1764}
1765
1391// Override Electron's userData path before the `ready` event so that1766// Override Electron's userData path before the `ready` event so that
1392// Chromium session data uses a filesystem-friendly directory name.1767// Chromium session data uses a filesystem-friendly directory name.
1393// Must be called synchronously at the top level — before `app.whenReady()`.1768// Must be called synchronously at the top level — before `app.whenReady()`.
@@ -1397,21 +1772,72 @@ configureAppIdentity(); · 3 unmodified lines
1397 1772
1398async function bootstrap(): Promise<void> {1773async function bootstrap(): Promise<void> {
1399 writeDesktopLogHeader("bootstrap start");1774 writeDesktopLogHeader("bootstrap start");
1400 backendPort = await Effect.service(NetService).pipe(1775 const configuredBackendPort = resolveConfiguredDesktopBackendPort(process.env.T3CODE_PORT);
1401 Effect.flatMap((net) => net.reserveLoopbackPort()),1776 if (isDevelopment && configuredBackendPort === undefined) {
1402 Effect.provide(NetService.layer),1777 throw new Error("T3CODE_PORT is required in desktop development.");
1403 Effect.runPromise,1778 }
1779
1780 backendPort =
1781 configuredBackendPort ??
1782 (await resolveDesktopBackendPort({
1783 host: DESKTOP_LOOPBACK_HOST,
1784 startPort: DEFAULT_DESKTOP_BACKEND_PORT,
1785 requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
1786 }));
1787 writeDesktopLogHeader(
1788 configuredBackendPort === undefined
1789 ? `selected backend port via sequential scan startPort=${DEFAULT_DESKTOP_BACKEND_PORT} port=${backendPort}`
1790 : `using configured backend port port=${backendPort}`,
1404 );1791 );
1405 writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);1792 backendBootstrapToken = Crypto.randomBytes(24).toString("hex");
1406 backendAuthToken = Crypto.randomBytes(24).toString("hex");1793 if (desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode) {
1407 const baseUrl = `ws://127.0.0.1:${backendPort}`;1794 writeDesktopLogHeader(
1408 backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;1795 `bootstrap restoring persisted server exposure mode mode=${desktopSettings.serverExposureMode}`,
1409 writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);1796 );
1797 }
1798 const serverExposureState = await applyDesktopServerExposureMode(
1799 desktopSettings.serverExposureMode,
1800 {
1801 persist: desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
1802 },
1803 );
1804 writeDesktopLogHeader(`bootstrap resolved backend endpoint baseUrl=${backendHttpUrl}`);
1805 if (serverExposureState.endpointUrl) {
1806 writeDesktopLogHeader(
1807 `bootstrap enabled network access endpointUrl=${serverExposureState.endpointUrl}`,
1808 );
1809 } else if (desktopSettings.serverExposureMode === "network-accessible") {
1810 writeDesktopLogHeader(
1811 "bootstrap fell back to local-only because no advertised network host was available",
1812 );
1813 }
1410 1814
1411 registerIpcHandlers();1815 registerIpcHandlers();
1412 writeDesktopLogHeader("bootstrap ipc handlers registered");1816 writeDesktopLogHeader("bootstrap ipc handlers registered");
1413 startBackend();1817 startBackend();
1414 writeDesktopLogHeader("bootstrap backend start requested");1818 writeDesktopLogHeader("bootstrap backend start requested");
1819
1820 if (isDevelopment) {
1821 mainWindow = createWindow();
1822 writeDesktopLogHeader("bootstrap main window created");
1823 void waitForBackendHttpReady(backendHttpUrl)
1824 .then(() => {
1825 writeDesktopLogHeader("bootstrap backend ready");
1826 })
1827 .catch((error) => {
1828 if (isBackendReadinessAborted(error)) {
1829 return;
1830 }
1831 writeDesktopLogHeader(
1832 `bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
1833 );
1834 console.warn("[desktop] backend readiness check timed out during dev bootstrap", error);
1835 });
1836 return;
1837 }
1838
1839 await waitForBackendHttpReady(backendHttpUrl);
1840 writeDesktopLogHeader("bootstrap backend ready");
1415 mainWindow = createWindow();1841 mainWindow = createWindow();
1416 writeDesktopLogHeader("bootstrap main window created");1842 writeDesktopLogHeader("bootstrap main window created");
1417}1843}
@@ -1421,6 +1847,7 @@ app.on("before-quit", () => { · 3 unmodified lines
1421 updateInstallInFlight = false;1847 updateInstallInFlight = false;
1422 writeDesktopLogHeader("before-quit received");1848 writeDesktopLogHeader("before-quit received");
1423 clearUpdatePollTimer();1849 clearUpdatePollTimer();
1850 cancelBackendReadinessWait();
1424 stopBackend();1851 stopBackend();
1425 restoreStdIoCapture?.();1852 restoreStdIoCapture?.();
1426});1853});
@@ -1434,13 +1861,19 @@ app · 7 unmodified lines
1434 registerDesktopProtocol();1861 registerDesktopProtocol();
1435 configureAutoUpdater();1862 configureAutoUpdater();
1436 void bootstrap().catch((error) => {1863 void bootstrap().catch((error) => {
1864 if (isBackendReadinessAborted(error) && isQuitting) {
1865 return;
1866 }
1437 handleFatalStartupError("bootstrap", error);1867 handleFatalStartupError("bootstrap", error);
1438 });1868 });
1439 1869
1440 app.on("activate", () => {1870 app.on("activate", () => {
1441 if (BrowserWindow.getAllWindows().length === 0) {1871 const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0];
1442 mainWindow = createWindow();1872 if (existingWindow) {
1873 revealWindow(existingWindow);
1874 return;
1443 }1875 }
1876 mainWindow = createWindow();
1444 });1877 });
1445 })1878 })
1446 .catch((error) => {1879 .catch((error) => {
@@ -1459,6 +1892,7 @@ if (process.platform !== "win32") { · 12 unmodified lines
1459 isQuitting = true;1892 isQuitting = true;
1460 writeDesktopLogHeader("SIGINT received");1893 writeDesktopLogHeader("SIGINT received");
1461 clearUpdatePollTimer();1894 clearUpdatePollTimer();
1895 cancelBackendReadinessWait();
1462 stopBackend();1896 stopBackend();
1463 restoreStdIoCapture?.();1897 restoreStdIoCapture?.();
1464 app.quit();1898 app.quit();
apps/desktop/src/preload.ts+29−4
@@ -12,13 +12,38 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; · 11 unmodified lines
12const UPDATE_CHECK_CHANNEL = "desktop:update-check";12const UPDATE_CHECK_CHANNEL = "desktop:update-check";
13const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";13const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
14const UPDATE_INSTALL_CHANNEL = "desktop:update-install";14const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
15const GET_WS_URL_CHANNEL = "desktop:get-ws-url";15const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
16const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
17const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
18const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
19const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
20const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
21const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
22const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
23const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
24const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
16 25
17contextBridge.exposeInMainWorld("desktopBridge", {26contextBridge.exposeInMainWorld("desktopBridge", {
18 getWsUrl: () => {27 getLocalEnvironmentBootstrap: () => {
19 const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);28 const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
20 return typeof result === "string" ? result : null;29 if (typeof result !== "object" || result === null) {
30 return null;
31 }
32 return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
21 },33 },
34 getClientSettings: () => ipcRenderer.invoke(GET_CLIENT_SETTINGS_CHANNEL),
35 setClientSettings: (settings) => ipcRenderer.invoke(SET_CLIENT_SETTINGS_CHANNEL, settings),
36 getSavedEnvironmentRegistry: () => ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
37 setSavedEnvironmentRegistry: (records) =>
38 ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
39 getSavedEnvironmentSecret: (environmentId) =>
40 ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
41 setSavedEnvironmentSecret: (environmentId, secret) =>
42 ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
43 removeSavedEnvironmentSecret: (environmentId) =>
44 ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
45 getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
46 setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
22 pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),47 pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
23 confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),48 confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
24 setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),49 setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
apps/desktop/src/serverExposure.test.ts+139−0
@@ -0,0 +1,139 @@
1import { describe, expect, it } from "vitest";
2
3import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
4
5describe("resolveLanAdvertisedHost", () => {
6 it("prefers an explicit host override", () => {
7 expect(
8 resolveLanAdvertisedHost(
9 {
10 en0: [
11 {
12 address: "192.168.1.44",
13 family: "IPv4",
14 internal: false,
15 netmask: "255.255.255.0",
16 cidr: "192.168.1.44/24",
17 mac: "00:00:00:00:00:00",
18 },
19 ],
20 },
21 "10.0.0.9",
22 ),
23 ).toBe("10.0.0.9");
24 });
25
26 it("returns the first usable non-internal IPv4 address", () => {
27 expect(
28 resolveLanAdvertisedHost(
29 {
30 lo0: [
31 {
32 address: "127.0.0.1",
33 family: "IPv4",
34 internal: true,
35 netmask: "255.0.0.0",
36 cidr: "127.0.0.1/8",
37 mac: "00:00:00:00:00:00",
38 },
39 ],
40 en0: [
41 {
42 address: "192.168.1.44",
43 family: "IPv4",
44 internal: false,
45 netmask: "255.255.255.0",
46 cidr: "192.168.1.44/24",
47 mac: "00:00:00:00:00:00",
48 },
49 ],
50 },
51 undefined,
52 ),
53 ).toBe("192.168.1.44");
54 });
55
56 it("returns null when no usable network address is available", () => {
57 expect(
58 resolveLanAdvertisedHost(
59 {
60 lo0: [
61 {
62 address: "127.0.0.1",
63 family: "IPv4",
64 internal: true,
65 netmask: "255.0.0.0",
66 cidr: "127.0.0.1/8",
67 mac: "00:00:00:00:00:00",
68 },
69 ],
70 },
71 undefined,
72 ),
73 ).toBeNull();
74 });
75});
76
77describe("resolveDesktopServerExposure", () => {
78 it("keeps the desktop server loopback-only when local-only mode is selected", () => {
79 expect(
80 resolveDesktopServerExposure({
81 mode: "local-only",
82 port: 3773,
83 networkInterfaces: {},
84 }),
85 ).toEqual({
86 mode: "local-only",
87 bindHost: "127.0.0.1",
88 localHttpUrl: "http://127.0.0.1:3773",
89 localWsUrl: "ws://127.0.0.1:3773",
90 endpointUrl: null,
91 advertisedHost: null,
92 });
93 });
94
95 it("binds to all interfaces in network-accessible mode", () => {
96 expect(
97 resolveDesktopServerExposure({
98 mode: "network-accessible",
99 port: 3773,
100 networkInterfaces: {
101 en0: [
102 {
103 address: "192.168.1.44",
104 family: "IPv4",
105 internal: false,
106 netmask: "255.255.255.0",
107 cidr: "192.168.1.44/24",
108 mac: "00:00:00:00:00:00",
109 },
110 ],
111 },
112 }),
113 ).toEqual({
114 mode: "network-accessible",
115 bindHost: "0.0.0.0",
116 localHttpUrl: "http://127.0.0.1:3773",
117 localWsUrl: "ws://127.0.0.1:3773",
118 endpointUrl: "http://192.168.1.44:3773",
119 advertisedHost: "192.168.1.44",
120 });
121 });
122
123 it("stays network-accessible even when no LAN address is currently detectable", () => {
124 expect(
125 resolveDesktopServerExposure({
126 mode: "network-accessible",
127 port: 3773,
128 networkInterfaces: {},
129 }),
130 ).toEqual({
131 mode: "network-accessible",
132 bindHost: "0.0.0.0",
133 localHttpUrl: "http://127.0.0.1:3773",
134 localWsUrl: "ws://127.0.0.1:3773",
135 endpointUrl: null,
136 advertisedHost: null,
137 });
138 });
139});
apps/desktop/src/serverExposure.ts+80−0
@@ -0,0 +1,80 @@
1import type { NetworkInterfaceInfo } from "node:os";
2import type { DesktopServerExposureMode } from "@t3tools/contracts";
3
4const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
5const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
6
7export interface DesktopServerExposure {
8 readonly mode: DesktopServerExposureMode;
9 readonly bindHost: string;
10 readonly localHttpUrl: string;
11 readonly localWsUrl: string;
12 readonly endpointUrl: string | null;
13 readonly advertisedHost: string | null;
14}
15
16const normalizeOptionalHost = (value: string | undefined): string | undefined => {
17 const normalized = value?.trim();
18 return normalized && normalized.length > 0 ? normalized : undefined;
19};
20
21const isUsableLanIpv4Address = (address: string): boolean =>
22 !address.startsWith("127.") && !address.startsWith("169.254.");
23
24export function resolveLanAdvertisedHost(
25 networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
26 explicitHost: string | undefined,
27): string | null {
28 const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
29 if (normalizedExplicitHost) {
30 return normalizedExplicitHost;
31 }
32
33 for (const interfaceAddresses of Object.values(networkInterfaces)) {
34 if (!interfaceAddresses) continue;
35
36 for (const address of interfaceAddresses) {
37 if (address.internal) continue;
38 if (address.family !== "IPv4") continue;
39 if (!isUsableLanIpv4Address(address.address)) continue;
40 return address.address;
41 }
42 }
43
44 return null;
45}
46
47export function resolveDesktopServerExposure(input: {
48 readonly mode: DesktopServerExposureMode;
49 readonly port: number;
50 readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
51 readonly advertisedHostOverride?: string;
52}): DesktopServerExposure {
53 const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
54 const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
55
56 if (input.mode === "local-only") {
57 return {
58 mode: input.mode,
59 bindHost: DESKTOP_LOOPBACK_HOST,
60 localHttpUrl,
61 localWsUrl,
62 endpointUrl: null,
63 advertisedHost: null,
64 };
65 }
66
67 const advertisedHost = resolveLanAdvertisedHost(
68 input.networkInterfaces,
69 input.advertisedHostOverride,
70 );
71
72 return {
73 mode: input.mode,
74 bindHost: DESKTOP_LAN_BIND_HOST,
75 localHttpUrl,
76 localWsUrl,
77 endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
78 advertisedHost,
79 };
80}
apps/desktop/src/updateState.test.ts+29−0
@@ -71,10 +71,37 @@ describe("getAutoUpdateDisabledReason", () => { · 70 unmodified lines
71 platform: "darwin",71 platform: "darwin",
72 appImage: undefined,72 appImage: undefined,
73 disabledByEnv: false,73 disabledByEnv: false,
74 hasUpdateFeedConfig: true,
74 }),75 }),
75 ).toContain("packaged production builds");76 ).toContain("packaged production builds");
76 });77 });
77 78
79 it("reports packaged local builds without an update feed as disabled", () => {
80 expect(
81 getAutoUpdateDisabledReason({
82 isDevelopment: false,
83 isPackaged: true,
84 platform: "darwin",
85 appImage: undefined,
86 disabledByEnv: false,
87 hasUpdateFeedConfig: false,
88 }),
89 ).toContain("no update feed");
90 });
91
92 it("allows packaged builds with an update feed", () => {
93 expect(
94 getAutoUpdateDisabledReason({
95 isDevelopment: false,
96 isPackaged: true,
97 platform: "darwin",
98 appImage: undefined,
99 disabledByEnv: false,
100 hasUpdateFeedConfig: true,
101 }),
102 ).toBeNull();
103 });
104
78 it("reports env-disabled auto updates", () => {105 it("reports env-disabled auto updates", () => {
79 expect(106 expect(
80 getAutoUpdateDisabledReason({107 getAutoUpdateDisabledReason({
@@ -83,6 +110,7 @@ describe("getAutoUpdateDisabledReason", () => { · 2 unmodified lines
83 platform: "darwin",110 platform: "darwin",
84 appImage: undefined,111 appImage: undefined,
85 disabledByEnv: true,112 disabledByEnv: true,
113 hasUpdateFeedConfig: true,
86 }),114 }),
87 ).toContain("T3CODE_DISABLE_AUTO_UPDATE");115 ).toContain("T3CODE_DISABLE_AUTO_UPDATE");
88 });116 });
@@ -95,6 +123,7 @@ describe("getAutoUpdateDisabledReason", () => { · 6 unmodified lines
95 platform: "linux",123 platform: "linux",
96 appImage: undefined,124 appImage: undefined,
97 disabledByEnv: false,125 disabledByEnv: false,
126 hasUpdateFeedConfig: true,
98 }),127 }),
99 ).toContain("AppImage");128 ).toContain("AppImage");
100 });129 });
apps/desktop/src/updateState.ts+4−0
@@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: { · 33 unmodified lines
34 platform: NodeJS.Platform;34 platform: NodeJS.Platform;
35 appImage?: string | undefined;35 appImage?: string | undefined;
36 disabledByEnv: boolean;36 disabledByEnv: boolean;
37 hasUpdateFeedConfig: boolean;
37}): string | null {38}): string | null {
39 if (!args.hasUpdateFeedConfig) {
40 return "Automatic updates are not available because no update feed is configured.";
41 }
38 if (args.isDevelopment || !args.isPackaged) {42 if (args.isDevelopment || !args.isPackaged) {
39 return "Automatic updates are only available in packaged production builds.";43 return "Automatic updates are only available in packaged production builds.";
40 }44 }
apps/marketing/src/pages/download.astro+5−4
@@ -1,5 +1,6 @@
1---1---
2import Layout from "../layouts/Layout.astro";2import Layout from "../layouts/Layout.astro";
3import { RELEASES_URL } from "../lib/releases";
3---4---
4 5
5<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">6<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
@@ -17,11 +18,11 @@ import Layout from "../layouts/Layout.astro"; · 11 unmodified lines
17 <h2 class="platform-name">macOS</h2>18 <h2 class="platform-name">macOS</h2>
18 </div>19 </div>
19 <div class="download-cards">20 <div class="download-cards">
20 <a class="download-card" data-asset="arm64.dmg" href="#">21 <a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
21 <span class="card-arch">Apple Silicon (arm64)</span>22 <span class="card-arch">Apple Silicon (arm64)</span>
22 <span class="card-format">.dmg</span>23 <span class="card-format">.dmg</span>
23 </a>24 </a>
24 <a class="download-card" data-asset="x64.dmg" href="#">25 <a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
25 <span class="card-arch">Intel (x64)</span>26 <span class="card-arch">Intel (x64)</span>
26 <span class="card-format">.dmg</span>27 <span class="card-format">.dmg</span>
27 </a>28 </a>
@@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro"; · 7 unmodified lines
35 <h2 class="platform-name">Windows</h2>36 <h2 class="platform-name">Windows</h2>
36 </div>37 </div>
37 <div class="download-cards">38 <div class="download-cards">
38 <a class="download-card" data-asset="x64.exe" href="#">39 <a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
39 <span class="card-arch">Windows 10, 11</span>40 <span class="card-arch">Windows 10, 11</span>
40 <span class="card-format">.exe</span>41 <span class="card-format">.exe</span>
41 </a>42 </a>
@@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro"; · 7 unmodified lines
49 <h2 class="platform-name">Linux</h2>50 <h2 class="platform-name">Linux</h2>
50 </div>51 </div>
51 <div class="download-cards">52 <div class="download-cards">
52 <a class="download-card" data-asset="x86_64.AppImage" href="#">53 <a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
53 <span class="card-arch">x86_64</span>54 <span class="card-arch">x86_64</span>
54 <span class="card-format">AppImage</span>55 <span class="card-format">AppImage</span>
55 </a>56 </a>
apps/server/integration/OrchestrationEngineHarness.integration.ts+23−4
@@ -26,6 +26,7 @@ import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore · 25 unmodified lines
26import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";26import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
27import { GitCoreLive } from "../src/git/Layers/GitCore.ts";27import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
28import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";28import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
29import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
29import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";30import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
30import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";31import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
31import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";32import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
@@ -46,10 +47,11 @@ import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts"; · 14 unmodified lines
46import { ProviderService } from "../src/provider/Services/ProviderService.ts";47import { ProviderService } from "../src/provider/Services/ProviderService.ts";
47import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";48import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
48import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";49import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
50import { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.ts";
49import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";51import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
50import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";52import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
51import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";53import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
52import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";54import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
53import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";55import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
54import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";56import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
55import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";57import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
@@ -299,7 +301,7 @@ export const makeOrchestrationIntegrationHarness = ( · 243 unmodified lines
299 ProjectionTurnRepositoryLive,301 ProjectionTurnRepositoryLive,
300 checkpointStoreLayer,302 checkpointStoreLayer,
301 providerLayer,303 providerLayer,
302 RuntimeReceiptBusLive,304 RuntimeReceiptBusTest,
303 );305 );
304 const serverSettingsLayer = ServerSettingsService.layerTest();306 const serverSettingsLayer = ServerSettingsService.layerTest();
305 const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(307 const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
@@ -322,6 +324,22 @@ export const makeOrchestrationIntegrationHarness = ( · 16 unmodified lines
322 );324 );
323 const checkpointReactorLayer = CheckpointReactorLive.pipe(325 const checkpointReactorLayer = CheckpointReactorLive.pipe(
324 Layer.provideMerge(runtimeServicesLayer),326 Layer.provideMerge(runtimeServicesLayer),
327 Layer.provideMerge(
328 Layer.succeed(GitStatusBroadcaster, {
329 getStatus: () => Effect.die("getStatus should not be called in this test"),
330 refreshLocalStatus: () =>
331 Effect.succeed({
332 isRepo: true,
333 hasOriginRemote: false,
334 isDefaultBranch: true,
335 branch: "main",
336 hasWorkingTreeChanges: false,
337 workingTree: { files: [], insertions: 0, deletions: 0 },
338 }),
339 refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
340 streamStatus: () => Stream.empty,
341 }),
342 ),
325 Layer.provideMerge(343 Layer.provideMerge(
326 WorkspaceEntriesLive.pipe(344 WorkspaceEntriesLive.pipe(
327 Layer.provide(WorkspacePathsLive),345 Layer.provide(WorkspacePathsLive),
@@ -340,6 +358,7 @@ export const makeOrchestrationIntegrationHarness = ( · 12 unmodified lines
340 Layer.provideMerge(runtimeServicesLayer),358 Layer.provideMerge(runtimeServicesLayer),
341 Layer.provideMerge(orchestrationReactorLayer),359 Layer.provideMerge(orchestrationReactorLayer),
342 Layer.provide(persistenceLayer),360 Layer.provide(persistenceLayer),
361 Layer.provideMerge(RepositoryIdentityResolverLive),
343 Layer.provideMerge(ServerSettingsService.layerTest()),362 Layer.provideMerge(ServerSettingsService.layerTest()),
344 Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),363 Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
345 Layer.provideMerge(NodeServices.layer),364 Layer.provideMerge(NodeServices.layer),
@@ -378,7 +397,7 @@ export const makeOrchestrationIntegrationHarness = ( · 32 unmodified lines
378 runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),397 runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
379 ).pipe(Effect.orDie);398 ).pipe(Effect.orDie);
380 const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);399 const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
381 yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>400 yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
382 Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),401 Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
383 ).pipe(Effect.forkIn(scope));402 ).pipe(Effect.forkIn(scope));
384 yield* Effect.sleep(10);403 yield* Effect.sleep(10);
@@ -421,7 +440,7 @@ export const makeOrchestrationIntegrationHarness = ( · 36 unmodified lines
421 ) =>440 ) =>
422 waitFor(441 waitFor(
423 pendingApprovalRepository442 pendingApprovalRepository
424 .getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })443 .getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
425 .pipe(444 .pipe(
426 Effect.map((row) =>445 Effect.map((row) =>
427 Option.match(row, {446 Option.match(row, {
apps/server/integration/TestProviderAdapter.integration.ts+3−3
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter · 288 unmodified lines
289 289
290 state.turnCount += 1;290 state.turnCount += 1;
291 const turnCount = state.turnCount;291 const turnCount = state.turnCount;
292 const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);292 const turnId = TurnId.make(`turn-${turnCount}`);
293 293
294 const response = state.queuedResponses.shift();294 const response = state.queuedResponses.shift();
295 if (!response) {295 if (!response) {
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter · 11 unmodified lines
307 ...(fixtureEvent as Record<string, unknown>),307 ...(fixtureEvent as Record<string, unknown>),
308 eventId: randomUUID(),308 eventId: randomUUID(),
309 provider,309 provider,
310 sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),310 sessionId: RuntimeSessionId.make(String(input.threadId)),
311 createdAt: nowIso(),311 createdAt: nowIso(),
312 };312 };
313 rawEvent.threadId = state.snapshot.threadId;313 rawEvent.threadId = state.snapshot.threadId;
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter · 49 unmodified lines
363 if (deferredTurnCompletedEvents.length === 0) {363 if (deferredTurnCompletedEvents.length === 0) {
364 yield* emit({364 yield* emit({
365 type: "turn.completed",365 type: "turn.completed",
366 eventId: EventId.makeUnsafe(randomUUID()),366 eventId: EventId.make(randomUUID()),
367 provider,367 provider,
368 createdAt: nowIso(),368 createdAt: nowIso(),
369 threadId: state.snapshot.threadId,369 threadId: state.snapshot.threadId,
apps/server/integration/fixtures/providerRuntime.ts+2−2
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const; · 4 unmodified lines
5const SESSION_ID = "fixture-session";5const SESSION_ID = "fixture-session";
6const THREAD_ID = "fixture-thread";6const THREAD_ID = "fixture-thread";
7const TURN_ID = "fixture-turn";7const TURN_ID = "fixture-turn";
8const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");8const REQUEST_ID = RuntimeRequestId.make("req-1");
9 9
10function baseEvent(10function baseEvent(
11 eventId: string,11 eventId: string,
12 createdAt: string,12 createdAt: string,
13): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {13): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
14 return {14 return {
15 eventId: EventId.makeUnsafe(eventId),15 eventId: EventId.make(eventId),
16 provider: PROVIDER,16 provider: PROVIDER,
17 sessionId: SESSION_ID,17 sessionId: SESSION_ID,
18 createdAt,18 createdAt,
apps/server/integration/orchestrationEngine.integration.test.ts+18−19
@@ -30,14 +30,13 @@ import type { · 29 unmodified lines
30} from "../src/orchestration/Services/RuntimeReceiptBus.ts";30} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
31import * as NodeServices from "@effect/platform-node/NodeServices";31import * as NodeServices from "@effect/platform-node/NodeServices";
32 32
33const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);33const asMessageId = (value: string): MessageId => MessageId.make(value);
34const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);34const asProjectId = (value: string): ProjectId => ProjectId.make(value);
35const asEventId = (value: string): EventId => EventId.makeUnsafe(value);35const asEventId = (value: string): EventId => EventId.make(value);
36const asApprovalRequestId = (value: string): ApprovalRequestId =>36const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
37 ApprovalRequestId.makeUnsafe(value);
38 37
39const PROJECT_ID = asProjectId("project-1");38const PROJECT_ID = asProjectId("project-1");
40const THREAD_ID = ThreadId.makeUnsafe("thread-1");39const THREAD_ID = ThreadId.make("thread-1");
41const FIXTURE_TURN_ID = "fixture-turn";40const FIXTURE_TURN_ID = "fixture-turn";
42const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");41const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
43type IntegrationProvider = ProviderKind;42type IntegrationProvider = ProviderKind;
@@ -112,7 +111,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => · 68 unmodified lines
112 111
113 yield* harness.engine.dispatch({112 yield* harness.engine.dispatch({
114 type: "project.create",113 type: "project.create",
115 commandId: CommandId.makeUnsafe("cmd-project-create"),114 commandId: CommandId.make("cmd-project-create"),
116 projectId: PROJECT_ID,115 projectId: PROJECT_ID,
117 title: "Integration Project",116 title: "Integration Project",
118 workspaceRoot: harness.workspaceDir,117 workspaceRoot: harness.workspaceDir,
@@ -125,7 +124,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => · 6 unmodified lines
125 124
126 yield* harness.engine.dispatch({125 yield* harness.engine.dispatch({
127 type: "thread.create",126 type: "thread.create",
128 commandId: CommandId.makeUnsafe("cmd-thread-create"),127 commandId: CommandId.make("cmd-thread-create"),
129 threadId: THREAD_ID,128 threadId: THREAD_ID,
130 projectId: PROJECT_ID,129 projectId: PROJECT_ID,
131 title: "Integration Thread",130 title: "Integration Thread",
@@ -150,7 +149,7 @@ const startTurn = (input: { · 18 unmodified lines
150}) =>149}) =>
151 input.harness.engine.dispatch({150 input.harness.engine.dispatch({
152 type: "thread.turn.start",151 type: "thread.turn.start",
153 commandId: CommandId.makeUnsafe(input.commandId),152 commandId: CommandId.make(input.commandId),
154 threadId: THREAD_ID,153 threadId: THREAD_ID,
155 message: {154 message: {
156 messageId: asMessageId(input.messageId),155 messageId: asMessageId(input.messageId),
@@ -261,7 +260,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( · 104 unmodified lines
261 260
262 yield* harness.engine.dispatch({261 yield* harness.engine.dispatch({
263 type: "project.create",262 type: "project.create",
264 commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),263 commandId: CommandId.make("cmd-project-create-real-codex"),
265 projectId: PROJECT_ID,264 projectId: PROJECT_ID,
266 title: "Integration Project",265 title: "Integration Project",
267 workspaceRoot: harness.workspaceDir,266 workspaceRoot: harness.workspaceDir,
@@ -274,7 +273,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( · 6 unmodified lines
274 273
275 yield* harness.engine.dispatch({274 yield* harness.engine.dispatch({
276 type: "thread.create",275 type: "thread.create",
277 commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),276 commandId: CommandId.make("cmd-thread-create-real-codex"),
278 threadId: THREAD_ID,277 threadId: THREAD_ID,
279 projectId: PROJECT_ID,278 projectId: PROJECT_ID,
280 title: "Integration Thread",279 title: "Integration Thread",
@@ -291,7 +290,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( · 10 unmodified lines
291 290
292 yield* harness.engine.dispatch({291 yield* harness.engine.dispatch({
293 type: "thread.turn.start",292 type: "thread.turn.start",
294 commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),293 commandId: CommandId.make("cmd-turn-start-real-codex-1"),
295 threadId: THREAD_ID,294 threadId: THREAD_ID,
296 message: {295 message: {
297 messageId: asMessageId("msg-real-codex-1"),296 messageId: asMessageId("msg-real-codex-1"),
@@ -318,7 +317,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( · 20 unmodified lines
318 317
319 yield* harness.engine.dispatch({318 yield* harness.engine.dispatch({
320 type: "thread.turn.start",319 type: "thread.turn.start",
321 commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),320 commandId: CommandId.make("cmd-turn-start-real-codex-2"),
322 threadId: THREAD_ID,321 threadId: THREAD_ID,
323 message: {322 message: {
324 messageId: asMessageId("msg-real-codex-2"),323 messageId: asMessageId("msg-real-codex-2"),
@@ -583,7 +582,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons · 258 unmodified lines
583 582
584 yield* harness.engine.dispatch({583 yield* harness.engine.dispatch({
585 type: "thread.approval.respond",584 type: "thread.approval.respond",
586 commandId: CommandId.makeUnsafe("cmd-approval-respond"),585 commandId: CommandId.make("cmd-approval-respond"),
587 threadId: THREAD_ID,586 threadId: THREAD_ID,
588 requestId: APPROVAL_REQUEST_ID,587 requestId: APPROVAL_REQUEST_ID,
589 decision: "accept",588 decision: "accept",
@@ -815,7 +814,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git · 225 unmodified lines
815 814
816 yield* harness.engine.dispatch({815 yield* harness.engine.dispatch({
817 type: "thread.checkpoint.revert",816 type: "thread.checkpoint.revert",
818 commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),817 commandId: CommandId.make("cmd-checkpoint-revert"),
819 threadId: THREAD_ID,818 threadId: THREAD_ID,
820 turnCount: 1,819 turnCount: 1,
821 createdAt: nowIso(),820 createdAt: nowIso(),
@@ -875,7 +874,7 @@ it.live( · 53 unmodified lines
875 874
876 yield* harness.engine.dispatch({875 yield* harness.engine.dispatch({
877 type: "thread.checkpoint.revert",876 type: "thread.checkpoint.revert",
878 commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),877 commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
879 threadId: THREAD_ID,878 threadId: THREAD_ID,
880 turnCount: 0,879 turnCount: 0,
881 createdAt: nowIso(),880 createdAt: nowIso(),
@@ -1119,7 +1118,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () => · 237 unmodified lines
1119 1118
1120 yield* harness.engine.dispatch({1119 yield* harness.engine.dispatch({
1121 type: "thread.approval.respond",1120 type: "thread.approval.respond",
1122 commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),1121 commandId: CommandId.make("cmd-claude-approval-respond"),
1123 threadId: THREAD_ID,1122 threadId: THREAD_ID,
1124 requestId: APPROVAL_REQUEST_ID,1123 requestId: APPROVAL_REQUEST_ID,
1125 decision: "accept",1124 decision: "accept",
@@ -1192,7 +1191,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () => · 66 unmodified lines
1192 1191
1193 yield* harness.engine.dispatch({1192 yield* harness.engine.dispatch({
1194 type: "thread.turn.interrupt",1193 type: "thread.turn.interrupt",
1195 commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),1194 commandId: CommandId.make("cmd-turn-interrupt-claude"),
1196 threadId: THREAD_ID,1195 threadId: THREAD_ID,
1197 createdAt: nowIso(),1196 createdAt: nowIso(),
1198 });1197 });
@@ -1309,7 +1308,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state", · 110 unmodified lines
1309 1308
1310 yield* harness.engine.dispatch({1309 yield* harness.engine.dispatch({
1311 type: "thread.checkpoint.revert",1310 type: "thread.checkpoint.revert",
1312 commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),1311 commandId: CommandId.make("cmd-checkpoint-revert-claude"),
1313 threadId: THREAD_ID,1312 threadId: THREAD_ID,
1314 turnCount: 1,1313 turnCount: 1,
1315 createdAt: nowIso(),1314 createdAt: nowIso(),
apps/server/integration/providerService.integration.test.ts+29−41
@@ -86,6 +86,7 @@ const collectEventsDuring = <A, E, R>( · 85 unmodified lines
86 Effect.forkScoped,86 Effect.forkScoped,
87 );87 );
88 88
89 yield* Effect.sleep("50 millis");
89 yield* action;90 yield* action;
90 91
91 return yield* Effect.forEach(92 return yield* Effect.forEach(
@@ -104,7 +105,6 @@ const runTurn = (input: { · 12 unmodified lines
104}) =>105}) =>
105 Effect.gen(function* () {106 Effect.gen(function* () {
106 yield* input.harness.queueTurnResponse(input.threadId, input.response);107 yield* input.harness.queueTurnResponse(input.threadId, input.response);
107
108 return yield* collectEventsDuring(108 return yield* collectEventsDuring(
109 input.provider.streamEvents,109 input.provider.streamEvents,
110 input.response.events.length,110 input.response.events.length,
@@ -116,21 +116,18 @@ const runTurn = (input: { · 5 unmodified lines
116 );116 );
117 });117 });
118 118
119it.effect("replays typed runtime fixture events", () =>119it.live("replays typed runtime fixture events", () =>
120 Effect.gen(function* () {120 Effect.gen(function* () {
121 const fixture = yield* makeIntegrationFixture;121 const fixture = yield* makeIntegrationFixture;
122 122
123 yield* Effect.gen(function* () {123 yield* Effect.gen(function* () {
124 const provider = yield* ProviderService;124 const provider = yield* ProviderService;
125 const session = yield* provider.startSession(125 const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
126 ThreadId.makeUnsafe("thread-integration-typed"),126 threadId: ThreadId.make("thread-integration-typed"),
127 {127 provider: "codex",
128 threadId: ThreadId.makeUnsafe("thread-integration-typed"),128 cwd: fixture.cwd,
129 provider: "codex",129 runtimeMode: "full-access",
130 cwd: fixture.cwd,130 });
131 runtimeMode: "full-access",
132 },
133 );
134 assert.equal((session.threadId ?? "").length > 0, true);131 assert.equal((session.threadId ?? "").length > 0, true);
135 132
136 const observedEvents = yield* runTurn({133 const observedEvents = yield* runTurn({
@@ -149,7 +146,7 @@ it.effect("replays typed runtime fixture events", () => · 12 unmodified lines
149 }).pipe(Effect.provide(NodeServices.layer)),146 }).pipe(Effect.provide(NodeServices.layer)),
150);147);
151 148
152it.effect("replays file-changing fixture turn events", () =>149it.live("replays file-changing fixture turn events", () =>
153 Effect.gen(function* () {150 Effect.gen(function* () {
154 const fixture = yield* makeIntegrationFixture;151 const fixture = yield* makeIntegrationFixture;
155 const { join } = yield* Path.Path;152 const { join } = yield* Path.Path;
@@ -157,15 +154,12 @@ it.effect("replays file-changing fixture turn events", () => · 1 unmodified line
157 154
158 yield* Effect.gen(function* () {155 yield* Effect.gen(function* () {
159 const provider = yield* ProviderService;156 const provider = yield* ProviderService;
160 const session = yield* provider.startSession(157 const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
161 ThreadId.makeUnsafe("thread-integration-tools"),158 threadId: ThreadId.make("thread-integration-tools"),
162 {159 provider: "codex",
163 threadId: ThreadId.makeUnsafe("thread-integration-tools"),160 cwd: fixture.cwd,
164 provider: "codex",161 runtimeMode: "full-access",
165 cwd: fixture.cwd,162 });
166 runtimeMode: "full-access",
167 },
168 );
169 assert.equal((session.threadId ?? "").length > 0, true);163 assert.equal((session.threadId ?? "").length > 0, true);
170 164
171 const observedEvents = yield* runTurn({165 const observedEvents = yield* runTurn({
@@ -188,7 +182,7 @@ it.effect("replays file-changing fixture turn events", () => · 16 unmodified lines
188 }).pipe(Effect.provide(NodeServices.layer)),182 }).pipe(Effect.provide(NodeServices.layer)),
189);183);
190 184
191it.effect("runs multi-turn tool/approval flow", () =>185it.live("runs multi-turn tool/approval flow", () =>
192 Effect.gen(function* () {186 Effect.gen(function* () {
193 const fixture = yield* makeIntegrationFixture;187 const fixture = yield* makeIntegrationFixture;
194 const { join } = yield* Path.Path;188 const { join } = yield* Path.Path;
@@ -196,15 +190,12 @@ it.effect("runs multi-turn tool/approval flow", () => · 1 unmodified line
196 190
197 yield* Effect.gen(function* () {191 yield* Effect.gen(function* () {
198 const provider = yield* ProviderService;192 const provider = yield* ProviderService;
199 const session = yield* provider.startSession(193 const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
200 ThreadId.makeUnsafe("thread-integration-multi"),194 threadId: ThreadId.make("thread-integration-multi"),
201 {195 provider: "codex",
202 threadId: ThreadId.makeUnsafe("thread-integration-multi"),196 cwd: fixture.cwd,
203 provider: "codex",197 runtimeMode: "full-access",
204 cwd: fixture.cwd,198 });
205 runtimeMode: "full-access",
206 },
207 );
208 assert.equal((session.threadId ?? "").length > 0, true);199 assert.equal((session.threadId ?? "").length > 0, true);
209 200
210 const firstTurnEvents = yield* runTurn({201 const firstTurnEvents = yield* runTurn({
@@ -242,7 +233,7 @@ it.effect("runs multi-turn tool/approval flow", () => · 31 unmodified lines
242 }).pipe(Effect.provide(NodeServices.layer)),233 }).pipe(Effect.provide(NodeServices.layer)),
243);234);
244 235
245it.effect("rolls back provider conversation state only", () =>236it.live("rolls back provider conversation state only", () =>
246 Effect.gen(function* () {237 Effect.gen(function* () {
247 const fixture = yield* makeIntegrationFixture;238 const fixture = yield* makeIntegrationFixture;
248 const { join } = yield* Path.Path;239 const { join } = yield* Path.Path;
@@ -250,15 +241,12 @@ it.effect("rolls back provider conversation state only", () => · 1 unmodified line
250 241
251 yield* Effect.gen(function* () {242 yield* Effect.gen(function* () {
252 const provider = yield* ProviderService;243 const provider = yield* ProviderService;
253 const session = yield* provider.startSession(244 const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
254 ThreadId.makeUnsafe("thread-integration-rollback"),245 threadId: ThreadId.make("thread-integration-rollback"),
255 {246 provider: "codex",
256 threadId: ThreadId.makeUnsafe("thread-integration-rollback"),247 cwd: fixture.cwd,
257 provider: "codex",248 runtimeMode: "full-access",
258 cwd: fixture.cwd,249 });
259 runtimeMode: "full-access",
260 },
261 );
262 assert.equal((session.threadId ?? "").length > 0, true);250 assert.equal((session.threadId ?? "").length > 0, true);
263 251
264 yield* runTurn({252 yield* runTurn({
apps/server/package.json+1−1
@@ -1,6 +1,6 @@
1{1{
2 "name": "t3",2 "name": "t3",
3 "version": "0.0.15",3 "version": "0.0.17",
4 "license": "MIT",4 "license": "MIT",
5 "repository": {5 "repository": {
6 "type": "git",6 "type": "git",
apps/server/scripts/cli.ts+25−3
@@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog · 13 unmodified lines
14import rootPackageJson from "../../../package.json" with { type: "json" };14import rootPackageJson from "../../../package.json" with { type: "json" };
15import serverPackageJson from "../package.json" with { type: "json" };15import serverPackageJson from "../package.json" with { type: "json" };
16 16
17interface PackageJson {
18 name: string;
19 repository: {
20 type: string;
21 url: string;
22 directory: string;
23 };
24 bin: Record<string, string>;
25 type: string;
26 version: string;
27 engines: Record<string, string>;
28 files: string[];
29 dependencies: Record<string, string>;
30 overrides: Record<string, string>;
31}
32
17class CliError extends Data.TaggedError("CliError")<{33class CliError extends Data.TaggedError("CliError")<{
18 readonly message: string;34 readonly message: string;
19 readonly cause?: unknown;35 readonly cause?: unknown;
@@ -177,7 +193,7 @@ const publishCmd = Command.make( · 157 unmodified lines
177 const backupPath = `${packageJsonPath}.bak`;193 const backupPath = `${packageJsonPath}.bak`;
178 194
179 // Assert build assets exist195 // Assert build assets exist
180 for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {196 for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
181 const abs = path.join(serverDir, relPath);197 const abs = path.join(serverDir, relPath);
182 if (!(yield* fs.exists(abs))) {198 if (!(yield* fs.exists(abs))) {
183 return yield* new CliError({199 return yield* new CliError({
@@ -192,7 +208,7 @@ const publishCmd = Command.make( · 8 unmodified lines
192 // Resolve catalog dependencies before any file mutations. If this throws,208 // Resolve catalog dependencies before any file mutations. If this throws,
193 // acquire fails and no release hook runs, so filesystem must still be untouched.209 // acquire fails and no release hook runs, so filesystem must still be untouched.
194 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);210 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
195 const pkg = {211 const pkg: PackageJson = {
196 name: serverPackageJson.name,212 name: serverPackageJson.name,
197 repository: serverPackageJson.repository,213 repository: serverPackageJson.repository,
198 bin: serverPackageJson.bin,214 bin: serverPackageJson.bin,
@@ -200,7 +216,8 @@ const publishCmd = Command.make( · 1 unmodified line
200 version,216 version,
201 engines: serverPackageJson.engines,217 engines: serverPackageJson.engines,
202 files: serverPackageJson.files,218 files: serverPackageJson.files,
203 dependencies: serverPackageJson.dependencies as Record<string, unknown>,219 dependencies: serverPackageJson.dependencies,
220 overrides: rootPackageJson.overrides,
204 };221 };
205 222
206 pkg.dependencies = resolveCatalogDependencies(223 pkg.dependencies = resolveCatalogDependencies(
@@ -208,6 +225,11 @@ const publishCmd = Command.make( · 1 unmodified line
208 rootPackageJson.workspaces.catalog,225 rootPackageJson.workspaces.catalog,
209 "apps/server dependencies",226 "apps/server dependencies",
210 );227 );
228 pkg.overrides = resolveCatalogDependencies(
229 pkg.overrides,
230 rootPackageJson.workspaces.catalog,
231 "root overrides",
232 );
211 233
212 const original = yield* fs.readFileString(packageJsonPath);234 const original = yield* fs.readFileString(packageJsonPath);
213 yield* fs.writeFileString(backupPath, original);235 yield* fs.writeFileString(backupPath, original);
apps/server/src/auth/Layers/AuthControlPlane.test.ts+111−0
@@ -0,0 +1,111 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { Effect, Layer } from "effect";
4
5import { ServerConfigShape } from "../../config.ts";
6import { ServerConfig } from "../../config.ts";
7import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
8import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
9import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
10import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
11import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
12import { makeAuthControlPlane } from "./AuthControlPlane.ts";
13import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
14
15const makeServerConfigLayer = (
16 overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
17) =>
18 Layer.effect(
19 ServerConfig,
20 Effect.gen(function* () {
21 const config = yield* ServerConfig;
22 return {
23 ...config,
24 ...overrides,
25 } satisfies ServerConfigShape;
26 }),
27 ).pipe(
28 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),
29 );
30
31const makeAuthControlPlaneLayer = (
32 overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
33) =>
34 Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe(
35 Layer.provideMerge(BootstrapCredentialServiceLive),
36 Layer.provideMerge(SessionCredentialServiceLive),
37 Layer.provideMerge(ServerSecretStoreLive),
38 Layer.provideMerge(SqlitePersistenceMemory),
39 Layer.provide(makeServerConfigLayer(overrides)),
40 );
41
42it.layer(NodeServices.layer)("AuthControlPlane", (it) => {
43 it.effect("creates, lists, and revokes client pairing links", () =>
44 Effect.gen(function* () {
45 const authControlPlane = yield* AuthControlPlane;
46
47 const created = yield* authControlPlane.createPairingLink({
48 role: "client",
49 subject: "one-time-token",
50 label: "CI phone",
51 });
52 const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
53 const revoked = yield* authControlPlane.revokePairingLink(created.id);
54 const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
55
56 expect(created.role).toBe("client");
57 expect(created.credential.length).toBeGreaterThan(0);
58 expect(listedBeforeRevoke).toHaveLength(1);
59 expect(listedBeforeRevoke[0]?.id).toBe(created.id);
60 expect(listedBeforeRevoke[0]?.label).toBe("CI phone");
61 expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);
62 expect(revoked).toBe(true);
63 expect(listedAfterRevoke).toHaveLength(0);
64 }).pipe(Effect.provide(makeAuthControlPlaneLayer())),
65 );
66
67 it.effect("issues bearer sessions and lists them without exposing raw tokens", () =>
68 Effect.gen(function* () {
69 const authControlPlane = yield* AuthControlPlane;
70 const sessionCredentials = yield* SessionCredentialService;
71
72 const issued = yield* authControlPlane.issueSession({
73 label: "deploy-bot",
74 });
75 const verified = yield* sessionCredentials.verify(issued.token);
76 const listedBeforeRevoke = yield* authControlPlane.listSessions();
77 const revoked = yield* authControlPlane.revokeSession(issued.sessionId);
78 const listedAfterRevoke = yield* authControlPlane.listSessions();
79
80 expect(issued.method).toBe("bearer-session-token");
81 expect(issued.role).toBe("owner");
82 expect(issued.client.deviceType).toBe("bot");
83 expect(issued.client.label).toBe("deploy-bot");
84 expect(verified.sessionId).toBe(issued.sessionId);
85 expect(verified.role).toBe("owner");
86 expect(verified.method).toBe("bearer-session-token");
87 expect(listedBeforeRevoke).toHaveLength(1);
88 expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);
89 expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);
90 expect(revoked).toBe(true);
91 expect(listedAfterRevoke).toHaveLength(0);
92 }).pipe(Effect.provide(makeAuthControlPlaneLayer())),
93 );
94
95 it.effect("surfaces lastConnectedAt through the listed session view", () =>
96 Effect.gen(function* () {
97 const authControlPlane = yield* AuthControlPlane;
98 const sessionCredentials = yield* SessionCredentialService;
99
100 const issued = yield* authControlPlane.issueSession({
101 label: "remote-ipad",
102 });
103 const beforeConnect = yield* authControlPlane.listSessions();
104 yield* sessionCredentials.markConnected(issued.sessionId);
105 const afterConnect = yield* authControlPlane.listSessions();
106
107 expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
108 expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();
109 }).pipe(Effect.provide(makeAuthControlPlaneLayer())),
110 );
111});
apps/server/src/auth/Layers/AuthControlPlane.ts+176−0
@@ -0,0 +1,176 @@
1import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
2import { DateTime, Effect, Layer } from "effect";
3
4import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
5import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
6import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
7import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
8import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
9import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
10import {
11 AuthControlPlane,
12 AuthControlPlaneError,
13 AuthControlPlaneShape,
14 DEFAULT_SESSION_SUBJECT,
15 IssuedBearerSession,
16 IssuedPairingLink,
17} from "../Services/AuthControlPlane.ts";
18
19const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
20 if (left.role !== right.role) {
21 return left.role === "owner" ? -1 : 1;
22 }
23 if (left.connected !== right.connected) {
24 return left.connected ? -1 : 1;
25 }
26 return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
27};
28
29const toAuthControlPlaneError =
30 (message: string) =>
31 (cause: unknown): AuthControlPlaneError =>
32 new AuthControlPlaneError({
33 message,
34 cause,
35 });
36
37export const makeAuthControlPlane = Effect.gen(function* () {
38 const bootstrapCredentials = yield* BootstrapCredentialService;
39 const sessions = yield* SessionCredentialService;
40
41 const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>
42 Effect.gen(function* () {
43 const createdAt = yield* DateTime.now;
44 const issued = yield* bootstrapCredentials.issueOneTimeToken({
45 role: input?.role ?? "client",
46 subject: input?.subject ?? "one-time-token",
47 ...(input?.ttl ? { ttl: input.ttl } : {}),
48 ...(input?.label ? { label: input.label } : {}),
49 });
50 return {
51 id: issued.id,
52 credential: issued.credential,
53 role: input?.role ?? "client",
54 subject: input?.subject ?? "one-time-token",
55 ...(issued.label ? { label: issued.label } : {}),
56 createdAt: DateTime.toUtc(createdAt),
57 expiresAt: DateTime.toUtc(issued.expiresAt),
58 } satisfies IssuedPairingLink;
59 }).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));
60
61 const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
62 bootstrapCredentials.listActive().pipe(
63 Effect.map((pairingLinks) =>
64 pairingLinks
65 .filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
66 .filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
67 .map((pairingLink) =>
68 pairingLink.label
69 ? ({
70 id: pairingLink.id,
71 credential: pairingLink.credential,
72 role: pairingLink.role,
73 subject: pairingLink.subject,
74 label: pairingLink.label,
75 createdAt: pairingLink.createdAt,
76 expiresAt: pairingLink.expiresAt,
77 } satisfies AuthPairingLink)
78 : ({
79 id: pairingLink.id,
80 credential: pairingLink.credential,
81 role: pairingLink.role,
82 subject: pairingLink.subject,
83 createdAt: pairingLink.createdAt,
84 expiresAt: pairingLink.expiresAt,
85 } satisfies AuthPairingLink),
86 )
87 .toSorted(
88 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
89 ),
90 ),
91 Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
92 );
93
94 const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>
95 bootstrapCredentials
96 .revoke(id)
97 .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));
98
99 const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>
100 sessions
101 .issue({
102 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
103 method: "bearer-session-token",
104 role: input?.role ?? "owner",
105 client: {
106 ...(input?.label ? { label: input.label } : {}),
107 deviceType: "bot",
108 },
109 ...(input?.ttl ? { ttl: input.ttl } : {}),
110 })
111 .pipe(
112 Effect.flatMap((issued) => {
113 if (issued.method !== "bearer-session-token") {
114 return Effect.fail(
115 new AuthControlPlaneError({
116 message: "CLI session issuance produced an unexpected session method.",
117 }),
118 );
119 }
120
121 return Effect.succeed({
122 sessionId: issued.sessionId,
123 token: issued.token,
124 method: "bearer-session-token" as const,
125 role: issued.role,
126 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
127 client: issued.client,
128 expiresAt: DateTime.toUtc(issued.expiresAt),
129 } satisfies IssuedBearerSession);
130 }),
131 Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),
132 );
133
134 const listSessions: AuthControlPlaneShape["listSessions"] = () =>
135 sessions.listActive().pipe(
136 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
137 Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),
138 );
139
140 const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>
141 sessions
142 .revoke(sessionId)
143 .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));
144
145 const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (
146 sessionId,
147 ) =>
148 sessions
149 .revokeAllExcept(sessionId)
150 .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));
151
152 return {
153 createPairingLink,
154 listPairingLinks,
155 revokePairingLink,
156 issueSession,
157 listSessions,
158 revokeSession,
159 revokeOtherSessionsExcept,
160 } satisfies AuthControlPlaneShape;
161});
162
163export const AuthCoreLive = Layer.mergeAll(
164 BootstrapCredentialServiceLive,
165 SessionCredentialServiceLive,
166);
167
168export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
169
170export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
171
172export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
173
174export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
175 Layer.provideMerge(AuthRuntimeLive),
176);
apps/server/src/auth/Layers/BootstrapCredentialService.test.ts+151−0
@@ -0,0 +1,151 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { Duration, Effect, Layer } from "effect";
4import { TestClock } from "effect/testing";
5
6import type { ServerConfigShape } from "../../config.ts";
7import { ServerConfig } from "../../config.ts";
8import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
9import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
10import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
11
12const makeServerConfigLayer = (
13 overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
14) =>
15 Layer.effect(
16 ServerConfig,
17 Effect.gen(function* () {
18 const config = yield* ServerConfig;
19 return {
20 ...config,
21 ...overrides,
22 } satisfies ServerConfigShape;
23 }),
24 ).pipe(
25 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
26 );
27
28const makeBootstrapCredentialLayer = (
29 overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
30) =>
31 BootstrapCredentialServiceLive.pipe(
32 Layer.provide(SqlitePersistenceMemory),
33 Layer.provide(makeServerConfigLayer(overrides)),
34 );
35
36it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {
37 it.effect("issues pairing tokens in a short manual-entry format", () =>
38 Effect.gen(function* () {
39 const bootstrapCredentials = yield* BootstrapCredentialService;
40 const issued = yield* bootstrapCredentials.issueOneTimeToken();
41
42 expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);
43 }).pipe(Effect.provide(makeBootstrapCredentialLayer())),
44 );
45
46 it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
47 Effect.gen(function* () {
48 const bootstrapCredentials = yield* BootstrapCredentialService;
49 const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
50 const first = yield* bootstrapCredentials.consume(issued.credential);
51 const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
52
53 expect(first.method).toBe("one-time-token");
54 expect(first.role).toBe("client");
55 expect(first.subject).toBe("one-time-token");
56 expect(first.label).toBe("Julius iPhone");
57 expect(issued.label).toBe("Julius iPhone");
58 expect(second._tag).toBe("BootstrapCredentialError");
59 expect(second.message).toContain("Unknown bootstrap credential");
60 }).pipe(Effect.provide(makeBootstrapCredentialLayer())),
61 );
62
63 it.effect("atomically consumes a one-time token when multiple requests race", () =>
64 Effect.gen(function* () {
65 const bootstrapCredentials = yield* BootstrapCredentialService;
66 const token = yield* bootstrapCredentials.issueOneTimeToken();
67 const results = yield* Effect.all(
68 Array.from({ length: 8 }, () =>
69 Effect.result(bootstrapCredentials.consume(token.credential)),
70 ),
71 {
72 concurrency: "unbounded",
73 },
74 );
75
76 const successes = results.filter((result) => result._tag === "Success");
77 const failures = results.filter((result) => result._tag === "Failure");
78
79 expect(successes).toHaveLength(1);
80 expect(failures).toHaveLength(7);
81 for (const failure of failures) {
82 expect(failure.failure._tag).toBe("BootstrapCredentialError");
83 expect(failure.failure.message).toContain("Unknown bootstrap credential");
84 }
85 }).pipe(Effect.provide(makeBootstrapCredentialLayer())),
86 );
87
88 it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
89 Effect.gen(function* () {
90 const bootstrapCredentials = yield* BootstrapCredentialService;
91 const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
92 const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
93
94 expect(first.method).toBe("desktop-bootstrap");
95 expect(first.role).toBe("owner");
96 expect(first.subject).toBe("desktop-bootstrap");
97 expect(second._tag).toBe("BootstrapCredentialError");
98 expect(second.status).toBe(401);
99 }).pipe(
100 Effect.provide(
101 makeBootstrapCredentialLayer({
102 desktopBootstrapToken: "desktop-bootstrap-token",
103 }),
104 ),
105 ),
106 );
107
108 it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
109 Effect.gen(function* () {
110 const bootstrapCredentials = yield* BootstrapCredentialService;
111
112 yield* TestClock.adjust(Duration.minutes(6));
113 const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
114
115 expect(expired._tag).toBe("BootstrapCredentialError");
116 expect(expired.status).toBe(401);
117 expect(expired.message).toContain("Bootstrap credential expired");
118 }).pipe(
119 Effect.provide(
120 Layer.merge(
121 makeBootstrapCredentialLayer({
122 desktopBootstrapToken: "desktop-bootstrap-token",
123 }),
124 TestClock.layer(),
125 ),
126 ),
127 ),
128 );
129
130 it.effect("lists and revokes active pairing links", () =>
131 Effect.gen(function* () {
132 const bootstrapCredentials = yield* BootstrapCredentialService;
133 const first = yield* bootstrapCredentials.issueOneTimeToken();
134 const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" });
135
136 const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
137 expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
138 expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
139
140 const revoked = yield* bootstrapCredentials.revoke(first.id);
141 const activeAfterRevoke = yield* bootstrapCredentials.listActive();
142 const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
143
144 expect(revoked).toBe(true);
145 expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
146 expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
147 expect(revokedConsume.message).toContain("no longer available");
148 expect(revokedConsume.status).toBe(401);
149 }).pipe(Effect.provide(makeBootstrapCredentialLayer())),
150 );
151});
apps/server/src/auth/Layers/BootstrapCredentialService.ts+296−0
@@ -0,0 +1,296 @@
1import type { AuthPairingLink } from "@t3tools/contracts";
2import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
3import { Option } from "effect";
4
5import { ServerConfig } from "../../config.ts";
6import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
7import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
8import {
9 BootstrapCredentialError,
10 BootstrapCredentialService,
11 type BootstrapCredentialChange,
12 type BootstrapCredentialServiceShape,
13 type BootstrapGrant,
14 type IssuedBootstrapCredential,
15} from "../Services/BootstrapCredentialService.ts";
16
17interface StoredBootstrapGrant extends BootstrapGrant {
18 readonly remainingUses: number | "unbounded";
19}
20
21type ConsumeResult =
22 | {
23 readonly _tag: "error";
24 readonly reason: "not-found" | "expired";
25 readonly error: BootstrapCredentialError;
26 }
27 | {
28 readonly _tag: "success";
29 readonly grant: BootstrapGrant;
30 };
31
32const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
33const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
34const PAIRING_TOKEN_LENGTH = 12;
35
36const generatePairingToken = (): string => {
37 const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
38
39 return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
40};
41
42export const makeBootstrapCredentialService = Effect.gen(function* () {
43 const config = yield* ServerConfig;
44 const pairingLinks = yield* AuthPairingLinkRepository;
45 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
46 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
47
48 const invalidBootstrapCredentialError = (message: string) =>
49 new BootstrapCredentialError({
50 message,
51 status: 401,
52 });
53
54 const internalBootstrapCredentialError = (message: string, cause: unknown) =>
55 new BootstrapCredentialError({
56 message,
57 status: 500,
58 cause,
59 });
60
61 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
62 Ref.update(seededGrantsRef, (current) => {
63 const next = new Map(current);
64 next.set(credential, grant);
65 return next;
66 });
67
68 const emitUpsert = (pairingLink: AuthPairingLink) =>
69 PubSub.publish(changesPubSub, {
70 type: "pairingLinkUpserted",
71 pairingLink,
72 }).pipe(Effect.asVoid);
73
74 const emitRemoved = (id: string) =>
75 PubSub.publish(changesPubSub, {
76 type: "pairingLinkRemoved",
77 id,
78 }).pipe(Effect.asVoid);
79
80 if (config.desktopBootstrapToken) {
81 const now = yield* DateTime.now;
82 yield* seedGrant(config.desktopBootstrapToken, {
83 method: "desktop-bootstrap",
84 role: "owner",
85 subject: "desktop-bootstrap",
86 expiresAt: DateTime.add(now, {
87 milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
88 }),
89 remainingUses: 1,
90 });
91 }
92
93 const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
94 internalBootstrapCredentialError(message, cause);
95
96 const listActive: BootstrapCredentialServiceShape["listActive"] = () =>
97 Effect.gen(function* () {
98 const now = yield* DateTime.now;
99 const rows = yield* pairingLinks.listActive({ now });
100
101 return rows.map((row) =>
102 row.label
103 ? ({
104 id: row.id,
105 credential: row.credential,
106 role: row.role,
107 subject: row.subject,
108 label: row.label,
109 createdAt: row.createdAt,
110 expiresAt: row.expiresAt,
111 } satisfies AuthPairingLink)
112 : ({
113 id: row.id,
114 credential: row.credential,
115 role: row.role,
116 subject: row.subject,
117 createdAt: row.createdAt,
118 expiresAt: row.expiresAt,
119 } satisfies AuthPairingLink),
120 );
121 }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));
122
123 const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>
124 Effect.gen(function* () {
125 const revokedAt = yield* DateTime.now;
126 const revoked = yield* pairingLinks.revoke({
127 id,
128 revokedAt,
129 });
130 if (revoked) {
131 yield* emitRemoved(id);
132 }
133 return revoked;
134 }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));
135
136 const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
137 Effect.gen(function* () {
138 const id = crypto.randomUUID();
139 const credential = generatePairingToken();
140 const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
141 const now = yield* DateTime.now;
142 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
143 const issued: IssuedBootstrapCredential = {
144 id,
145 credential,
146 ...(input?.label ? { label: input.label } : {}),
147 expiresAt,
148 };
149 yield* pairingLinks.create({
150 id,
151 credential,
152 method: "one-time-token",
153 role: input?.role ?? "client",
154 subject: input?.subject ?? "one-time-token",
155 label: input?.label ?? null,
156 createdAt: now,
157 expiresAt: expiresAt,
158 });
159 yield* emitUpsert({
160 id,
161 credential,
162 role: input?.role ?? "client",
163 subject: input?.subject ?? "one-time-token",
164 ...(input?.label ? { label: input.label } : {}),
165 createdAt: now,
166 expiresAt,
167 });
168 return issued;
169 }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));
170
171 const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>
172 Effect.gen(function* () {
173 const now = yield* DateTime.now;
174 const seededResult: ConsumeResult = yield* Ref.modify(
175 seededGrantsRef,
176 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
177 const grant = current.get(credential);
178 if (!grant) {
179 return [
180 {
181 _tag: "error",
182 reason: "not-found",
183 error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
184 },
185 current,
186 ];
187 }
188
189 const next = new Map(current);
190 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
191 next.delete(credential);
192 return [
193 {
194 _tag: "error",
195 reason: "expired",
196 error: invalidBootstrapCredentialError("Bootstrap credential expired."),
197 },
198 next,
199 ];
200 }
201
202 const remainingUses = grant.remainingUses;
203 if (typeof remainingUses === "number") {
204 if (remainingUses <= 1) {
205 next.delete(credential);
206 } else {
207 next.set(credential, {
208 ...grant,
209 remainingUses: remainingUses - 1,
210 });
211 }
212 }
213
214 return [
215 {
216 _tag: "success",
217 grant: {
218 method: grant.method,
219 role: grant.role,
220 subject: grant.subject,
221 ...(grant.label ? { label: grant.label } : {}),
222 expiresAt: grant.expiresAt,
223 } satisfies BootstrapGrant,
224 },
225 next,
226 ];
227 },
228 );
229
230 if (seededResult._tag === "success") {
231 return seededResult.grant;
232 }
233 if (seededResult.reason !== "not-found") {
234 return yield* seededResult.error;
235 }
236
237 const consumed = yield* pairingLinks.consumeAvailable({
238 credential,
239 consumedAt: now,
240 now,
241 });
242
243 if (Option.isSome(consumed)) {
244 yield* emitRemoved(consumed.value.id);
245 return {
246 method: consumed.value.method,
247 role: consumed.value.role,
248 subject: consumed.value.subject,
249 ...(consumed.value.label ? { label: consumed.value.label } : {}),
250 expiresAt: consumed.value.expiresAt,
251 } satisfies BootstrapGrant;
252 }
253
254 const matching = yield* pairingLinks.getByCredential({ credential });
255 if (Option.isNone(matching)) {
256 return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
257 }
258
259 if (matching.value.revokedAt !== null) {
260 return yield* invalidBootstrapCredentialError(
261 "Bootstrap credential is no longer available.",
262 );
263 }
264
265 if (matching.value.consumedAt !== null) {
266 return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
267 }
268
269 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
270 return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
271 }
272
273 return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
274 }).pipe(
275 Effect.mapError((cause) =>
276 cause instanceof BootstrapCredentialError
277 ? cause
278 : internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
279 ),
280 );
281
282 return {
283 issueOneTimeToken,
284 listActive,
285 get streamChanges() {
286 return Stream.fromPubSub(changesPubSub);
287 },
288 revoke,
289 consume,
290 } satisfies BootstrapCredentialServiceShape;
291});
292
293export const BootstrapCredentialServiceLive = Layer.effect(
294 BootstrapCredentialService,
295 makeBootstrapCredentialService,
296).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));
apps/server/src/auth/Layers/ServerAuth.test.ts+182−0
@@ -0,0 +1,182 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { Effect, Layer } from "effect";
4
5import type { ServerConfigShape } from "../../config.ts";
6import { ServerConfig } from "../../config.ts";
7import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
8import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
9import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";
10import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";
11import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
12
13const makeServerConfigLayer = (overrides?: Partial<ServerConfigShape>) =>
14 Layer.effect(
15 ServerConfig,
16 Effect.gen(function* () {
17 const config = yield* ServerConfig;
18 return {
19 ...config,
20 ...overrides,
21 } satisfies ServerConfigShape;
22 }),
23 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
24
25const makeServerAuthLayer = (overrides?: Partial<ServerConfigShape>) =>
26 ServerAuthLive.pipe(
27 Layer.provide(SqlitePersistenceMemory),
28 Layer.provide(ServerSecretStoreLive),
29 Layer.provide(makeServerConfigLayer(overrides)),
30 );
31
32const makeCookieRequest = (
33 sessionToken: string,
34): Parameters<ServerAuthShape["authenticateHttpRequest"]>[0] =>
35 ({
36 cookies: {
37 t3_session: sessionToken,
38 },
39 headers: {},
40 }) as unknown as Parameters<ServerAuthShape["authenticateHttpRequest"]>[0];
41
42const requestMetadata = {
43 deviceType: "desktop" as const,
44 os: "macOS",
45 browser: "Chrome",
46 ipAddress: "192.168.1.23",
47};
48
49it.layer(NodeServices.layer)("ServerAuthLive", (it) => {
50 it.effect("maps invalid bootstrap credential failures to 401", () =>
51 Effect.sync(() => {
52 const error = toBootstrapExchangeAuthError(
53 new BootstrapCredentialError({
54 message: "Unknown bootstrap credential.",
55 status: 401,
56 }),
57 );
58
59 expect(error.status).toBe(401);
60 expect(error.message).toBe("Invalid bootstrap credential.");
61 }),
62 );
63
64 it.effect("maps unexpected bootstrap failures to 500", () =>
65 Effect.sync(() => {
66 const error = toBootstrapExchangeAuthError(
67 new BootstrapCredentialError({
68 message: "Failed to consume bootstrap credential.",
69 status: 500,
70 cause: new Error("sqlite is unavailable"),
71 }),
72 );
73
74 expect(error.status).toBe(500);
75 expect(error.message).toBe("Failed to validate bootstrap credential.");
76 }),
77 );
78
79 it.effect("issues client pairing credentials by default", () =>
80 Effect.gen(function* () {
81 const serverAuth = yield* ServerAuth;
82
83 const pairingCredential = yield* serverAuth.issuePairingCredential();
84 const exchanged = yield* serverAuth.exchangeBootstrapCredential(
85 pairingCredential.credential,
86 requestMetadata,
87 );
88 const verified = yield* serverAuth.authenticateHttpRequest(
89 makeCookieRequest(exchanged.sessionToken),
90 );
91
92 expect(verified.sessionId.length).toBeGreaterThan(0);
93 expect(verified.role).toBe("client");
94 expect(verified.subject).toBe("one-time-token");
95 }).pipe(Effect.provide(makeServerAuthLayer())),
96 );
97
98 it.effect("issues startup pairing URLs that bootstrap owner sessions", () =>
99 Effect.gen(function* () {
100 const serverAuth = yield* ServerAuth;
101
102 const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773");
103 const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token");
104 const listedPairingLinks = yield* serverAuth.listPairingLinks();
105 expect(token).toBeTruthy();
106 expect(
107 listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"),
108 ).toBe(false);
109
110 const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata);
111 const verified = yield* serverAuth.authenticateHttpRequest(
112 makeCookieRequest(exchanged.sessionToken),
113 );
114
115 expect(verified.role).toBe("owner");
116 expect(verified.subject).toBe("owner-bootstrap");
117 }).pipe(Effect.provide(makeServerAuthLayer())),
118 );
119
120 it.effect("lists pairing links and revokes other client sessions while keeping the owner", () =>
121 Effect.gen(function* () {
122 const serverAuth = yield* ServerAuth;
123
124 const ownerExchange = yield* serverAuth.exchangeBootstrapCredential(
125 "desktop-bootstrap-token",
126 requestMetadata,
127 );
128 const ownerSession = yield* serverAuth.authenticateHttpRequest(
129 makeCookieRequest(ownerExchange.sessionToken),
130 );
131 const pairingCredential = yield* serverAuth.issuePairingCredential({
132 label: "Julius iPhone",
133 });
134 const listedPairingLinks = yield* serverAuth.listPairingLinks();
135 const clientExchange = yield* serverAuth.exchangeBootstrapCredential(
136 pairingCredential.credential,
137 {
138 ...requestMetadata,
139 deviceType: "mobile",
140 os: "iOS",
141 browser: "Safari",
142 ipAddress: "192.168.1.88",
143 },
144 );
145 const clientSession = yield* serverAuth.authenticateHttpRequest(
146 makeCookieRequest(clientExchange.sessionToken),
147 );
148 const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
149 const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId);
150 const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
151
152 expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id);
153 expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe(
154 "Julius iPhone",
155 );
156 expect(clientsBeforeRevoke).toHaveLength(2);
157 expect(
158 clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current,
159 ).toBe(true);
160 expect(
161 clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current,
162 ).toBe(false);
163 expect(
164 clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
165 .label,
166 ).toBe("Julius iPhone");
167 expect(
168 clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
169 .deviceType,
170 ).toBe("mobile");
171 expect(revokedCount).toBe(1);
172 expect(clientsAfterRevoke).toHaveLength(1);
173 expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId);
174 }).pipe(
175 Effect.provide(
176 makeServerAuthLayer({
177 desktopBootstrapToken: "desktop-bootstrap-token",
178 }),
179 ),
180 ),
181 );
182});
apps/server/src/auth/Layers/ServerAuth.ts+395−0
@@ -0,0 +1,395 @@
1import {
2 type AuthBearerBootstrapResult,
3 type AuthClientSession,
4 type AuthBootstrapResult,
5 type AuthPairingCredentialResult,
6 type AuthSessionState,
7 type AuthWebSocketTokenResult,
8} from "@t3tools/contracts";
9import { DateTime, Effect, Layer, Option } from "effect";
10import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
11
12import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
13import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
14import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
15import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
16import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
17import {
18 ServerAuth,
19 type AuthenticatedSession,
20 AuthError,
21 type ServerAuthShape,
22} from "../Services/ServerAuth.ts";
23import {
24 SessionCredentialError,
25 SessionCredentialService,
26} from "../Services/SessionCredentialService.ts";
27import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
28
29type BootstrapExchangeResult = {
30 readonly response: AuthBootstrapResult;
31 readonly sessionToken: string;
32};
33
34const AUTHORIZATION_PREFIX = "Bearer ";
35const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
36
37export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {
38 if (cause.status === 500) {
39 return new AuthError({
40 message: "Failed to validate bootstrap credential.",
41 status: 500,
42 cause,
43 });
44 }
45
46 return new AuthError({
47 message: "Invalid bootstrap credential.",
48 status: 401,
49 cause,
50 });
51}
52
53function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
54 const header = request.headers["authorization"];
55 if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
56 return null;
57 }
58 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
59 return token.length > 0 ? token : null;
60}
61
62export const makeServerAuth = Effect.gen(function* () {
63 const policy = yield* ServerAuthPolicy;
64 const bootstrapCredentials = yield* BootstrapCredentialService;
65 const authControlPlane = yield* AuthControlPlane;
66 const sessions = yield* SessionCredentialService;
67 const descriptor = yield* policy.getDescriptor();
68
69 const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
70 sessions.verify(token).pipe(
71 Effect.tapError((cause: SessionCredentialError) =>
72 Effect.logWarning("Rejected authenticated session credential.").pipe(
73 Effect.annotateLogs({
74 reason: cause.message,
75 }),
76 ),
77 ),
78 Effect.map((session) => ({
79 sessionId: session.sessionId,
80 subject: session.subject,
81 method: session.method,
82 role: session.role,
83 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
84 })),
85 Effect.mapError(
86 (cause) =>
87 new AuthError({
88 message: "Unauthorized request.",
89 status: 401,
90 cause,
91 }),
92 ),
93 );
94
95 const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
96 const cookieToken = request.cookies[sessions.cookieName];
97 const bearerToken = parseBearerToken(request);
98 const credential = cookieToken ?? bearerToken;
99 if (!credential) {
100 return Effect.fail(
101 new AuthError({
102 message: "Authentication required.",
103 status: 401,
104 }),
105 );
106 }
107 return authenticateToken(credential);
108 };
109
110 const getSessionState: ServerAuthShape["getSessionState"] = (request) =>
111 authenticateRequest(request).pipe(
112 Effect.map(
113 (session) =>
114 ({
115 authenticated: true,
116 auth: descriptor,
117 role: session.role,
118 sessionMethod: session.method,
119 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
120 }) satisfies AuthSessionState,
121 ),
122 Effect.catchTag("AuthError", () =>
123 Effect.succeed({
124 authenticated: false,
125 auth: descriptor,
126 } satisfies AuthSessionState),
127 ),
128 );
129
130 const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (
131 credential,
132 requestMetadata,
133 ) =>
134 bootstrapCredentials.consume(credential).pipe(
135 Effect.mapError(toBootstrapExchangeAuthError),
136 Effect.flatMap((grant) =>
137 sessions
138 .issue({
139 method: "browser-session-cookie",
140 subject: grant.subject,
141 role: grant.role,
142 client: {
143 ...requestMetadata,
144 ...(grant.label ? { label: grant.label } : {}),
145 },
146 })
147 .pipe(
148 Effect.mapError(
149 (cause) =>
150 new AuthError({
151 message: "Failed to issue authenticated session.",
152 cause,
153 }),
154 ),
155 ),
156 ),
157 Effect.map(
158 (session) =>
159 ({
160 response: {
161 authenticated: true,
162 role: session.role,
163 sessionMethod: session.method,
164 expiresAt: DateTime.toUtc(session.expiresAt),
165 } satisfies AuthBootstrapResult,
166 sessionToken: session.token,
167 }) satisfies BootstrapExchangeResult,
168 ),
169 );
170
171 const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =
172 (credential, requestMetadata) =>
173 bootstrapCredentials.consume(credential).pipe(
174 Effect.mapError(toBootstrapExchangeAuthError),
175 Effect.flatMap((grant) =>
176 sessions
177 .issue({
178 method: "bearer-session-token",
179 subject: grant.subject,
180 role: grant.role,
181 client: {
182 ...requestMetadata,
183 ...(grant.label ? { label: grant.label } : {}),
184 },
185 })
186 .pipe(
187 Effect.mapError(
188 (cause) =>
189 new AuthError({
190 message: "Failed to issue authenticated session.",
191 cause,
192 }),
193 ),
194 ),
195 ),
196 Effect.map(
197 (session) =>
198 ({
199 authenticated: true,
200 role: session.role,
201 sessionMethod: "bearer-session-token",
202 expiresAt: DateTime.toUtc(session.expiresAt),
203 sessionToken: session.token,
204 }) satisfies AuthBearerBootstrapResult,
205 ),
206 );
207
208 const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>
209 authControlPlane
210 .createPairingLink({
211 role: input?.role ?? "client",
212 subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",
213 ...(input?.label ? { label: input.label } : {}),
214 })
215 .pipe(
216 Effect.mapError(
217 (cause) =>
218 new AuthError({
219 message: "Failed to issue pairing credential.",
220 cause,
221 }),
222 ),
223 Effect.map(
224 (issued) =>
225 ({
226 id: issued.id,
227 credential: issued.credential,
228 ...(issued.label ? { label: issued.label } : {}),
229 expiresAt: issued.expiresAt,
230 }) satisfies AuthPairingCredentialResult,
231 ),
232 );
233
234 const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>
235 authControlPlane
236 .listPairingLinks({
237 role: "client",
238 excludeSubjects: ["owner-bootstrap"],
239 })
240 .pipe(
241 Effect.mapError(
242 (cause) =>
243 new AuthError({
244 message: "Failed to load pairing links.",
245 cause,
246 }),
247 ),
248 );
249
250 const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>
251 authControlPlane.revokePairingLink(id).pipe(
252 Effect.mapError(
253 (cause) =>
254 new AuthError({
255 message: "Failed to revoke pairing link.",
256 cause,
257 }),
258 ),
259 );
260
261 const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>
262 authControlPlane.listSessions().pipe(
263 Effect.mapError(
264 (cause) =>
265 new AuthError({
266 message: "Failed to load paired clients.",
267 cause,
268 }),
269 ),
270 Effect.map((clientSessions) =>
271 clientSessions.map(
272 (clientSession): AuthClientSession => ({
273 ...clientSession,
274 current: clientSession.sessionId === currentSessionId,
275 }),
276 ),
277 ),
278 );
279
280 const revokeClientSession: ServerAuthShape["revokeClientSession"] = (
281 currentSessionId,
282 targetSessionId,
283 ) =>
284 Effect.gen(function* () {
285 if (currentSessionId === targetSessionId) {
286 return yield* new AuthError({
287 message: "Use revoke other clients to keep the current owner session active.",
288 status: 403,
289 });
290 }
291 return yield* authControlPlane.revokeSession(targetSessionId).pipe(
292 Effect.mapError(
293 (cause) =>
294 new AuthError({
295 message: "Failed to revoke client session.",
296 cause,
297 }),
298 ),
299 );
300 });
301
302 const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (
303 currentSessionId,
304 ) =>
305 authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(
306 Effect.mapError(
307 (cause) =>
308 new AuthError({
309 message: "Failed to revoke other client sessions.",
310 cause,
311 }),
312 ),
313 );
314
315 const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
316 issuePairingCredential({ role: "owner" }).pipe(
317 Effect.map((issued) => {
318 const url = new URL(baseUrl);
319 url.pathname = "/pair";
320 url.searchParams.delete("token");
321 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
322 return url.toString();
323 }),
324 );
325
326 const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>
327 sessions.issueWebSocketToken(session.sessionId).pipe(
328 Effect.mapError(
329 (cause) =>
330 new AuthError({
331 message: "Failed to issue websocket token.",
332 cause,
333 }),
334 ),
335 Effect.map(
336 (issued) =>
337 ({
338 token: issued.token,
339 expiresAt: DateTime.toUtc(issued.expiresAt),
340 }) satisfies AuthWebSocketTokenResult,
341 ),
342 );
343
344 const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>
345 Effect.gen(function* () {
346 const requestUrl = HttpServerRequest.toURL(request);
347 if (Option.isSome(requestUrl)) {
348 const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);
349 if (websocketToken && websocketToken.trim().length > 0) {
350 return yield* sessions.verifyWebSocketToken(websocketToken).pipe(
351 Effect.map((session) => ({
352 sessionId: session.sessionId,
353 subject: session.subject,
354 method: session.method,
355 role: session.role,
356 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
357 })),
358 Effect.mapError(
359 (cause) =>
360 new AuthError({
361 message: "Unauthorized request.",
362 status: 401,
363 cause,
364 }),
365 ),
366 );
367 }
368 }
369
370 return yield* authenticateRequest(request);
371 });
372
373 return {
374 getDescriptor: () => Effect.succeed(descriptor),
375 getSessionState,
376 exchangeBootstrapCredential,
377 exchangeBootstrapCredentialForBearerSession,
378 issuePairingCredential,
379 listPairingLinks,
380 revokePairingLink,
381 listClientSessions,
382 revokeClientSession,
383 revokeOtherClientSessions,
384 authenticateHttpRequest: authenticateRequest,
385 authenticateWebSocketUpgrade,
386 issueWebSocketToken,
387 issueStartupPairingUrl,
388 } satisfies ServerAuthShape;
389});
390
391export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(
392 Layer.provideMerge(AuthControlPlaneLive),
393 Layer.provideMerge(AuthCoreLive),
394 Layer.provideMerge(ServerAuthPolicyLive),
395);
apps/server/src/auth/Layers/ServerAuthPolicy.test.ts+114−0
@@ -0,0 +1,114 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { Effect, Layer } from "effect";
4
5import type { ServerConfigShape } from "../../config.ts";
6import { ServerConfig } from "../../config.ts";
7import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
8import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
9
10const makeServerAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>
11 ServerAuthPolicyLive.pipe(
12 Layer.provide(
13 Layer.effect(
14 ServerConfig,
15 Effect.gen(function* () {
16 const config = yield* ServerConfig;
17 return {
18 ...config,
19 ...overrides,
20 } satisfies ServerConfigShape;
21 }),
22 ).pipe(
23 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-policy-test-" })),
24 ),
25 ),
26 );
27
28it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
29 it.effect("uses desktop-managed-local policy for desktop mode", () =>
30 Effect.gen(function* () {
31 const policy = yield* ServerAuthPolicy;
32 const descriptor = yield* policy.getDescriptor();
33
34 expect(descriptor.policy).toBe("desktop-managed-local");
35 expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
36 expect(descriptor.sessionCookieName).toBe("t3_session_3773");
37 }).pipe(
38 Effect.provide(
39 makeServerAuthPolicyLayer({
40 mode: "desktop",
41 port: 3773,
42 }),
43 ),
44 ),
45 );
46
47 it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
48 Effect.gen(function* () {
49 const policy = yield* ServerAuthPolicy;
50 const descriptor = yield* policy.getDescriptor();
51
52 expect(descriptor.policy).toBe("remote-reachable");
53 expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]);
54 }).pipe(
55 Effect.provide(
56 makeServerAuthPolicyLayer({
57 mode: "desktop",
58 host: "0.0.0.0",
59 }),
60 ),
61 ),
62 );
63
64 it.effect("uses loopback-browser policy for loopback web hosts", () =>
65 Effect.gen(function* () {
66 const policy = yield* ServerAuthPolicy;
67 const descriptor = yield* policy.getDescriptor();
68
69 expect(descriptor.policy).toBe("loopback-browser");
70 expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
71 expect(descriptor.sessionCookieName).toBe("t3_session");
72 }).pipe(
73 Effect.provide(
74 makeServerAuthPolicyLayer({
75 mode: "web",
76 host: "127.0.0.1",
77 }),
78 ),
79 ),
80 );
81
82 it.effect("uses remote-reachable policy for wildcard web hosts", () =>
83 Effect.gen(function* () {
84 const policy = yield* ServerAuthPolicy;
85 const descriptor = yield* policy.getDescriptor();
86
87 expect(descriptor.policy).toBe("remote-reachable");
88 expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
89 }).pipe(
90 Effect.provide(
91 makeServerAuthPolicyLayer({
92 mode: "web",
93 host: "0.0.0.0",
94 }),
95 ),
96 ),
97 );
98
99 it.effect("uses remote-reachable policy for non-loopback web hosts", () =>
100 Effect.gen(function* () {
101 const policy = yield* ServerAuthPolicy;
102 const descriptor = yield* policy.getDescriptor();
103
104 expect(descriptor.policy).toBe("remote-reachable");
105 }).pipe(
106 Effect.provide(
107 makeServerAuthPolicyLayer({
108 mode: "web",
109 host: "192.168.1.50",
110 }),
111 ),
112 ),
113 );
114});
apps/server/src/auth/Layers/ServerAuthPolicy.ts+44−0
@@ -0,0 +1,44 @@
1import type { ServerAuthDescriptor } from "@t3tools/contracts";
2import { Effect, Layer } from "effect";
3
4import { ServerConfig } from "../../config.ts";
5import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
6import { resolveSessionCookieName } from "../utils.ts";
7import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
8
9export const makeServerAuthPolicy = Effect.gen(function* () {
10 const config = yield* ServerConfig;
11 const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
12
13 const policy =
14 config.mode === "desktop"
15 ? isRemoteReachable
16 ? "remote-reachable"
17 : "desktop-managed-local"
18 : isRemoteReachable
19 ? "remote-reachable"
20 : "loopback-browser";
21
22 const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
23 policy === "desktop-managed-local"
24 ? ["desktop-bootstrap"]
25 : config.mode === "desktop" && policy === "remote-reachable"
26 ? ["desktop-bootstrap", "one-time-token"]
27 : ["one-time-token"];
28
29 const descriptor: ServerAuthDescriptor = {
30 policy,
31 bootstrapMethods,
32 sessionMethods: ["browser-session-cookie", "bearer-session-token"],
33 sessionCookieName: resolveSessionCookieName({
34 mode: config.mode,
35 port: config.port,
36 }),
37 };
38
39 return {
40 getDescriptor: () => Effect.succeed(descriptor),
41 } satisfies ServerAuthPolicyShape;
42});
43
44export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
apps/server/src/auth/Layers/ServerSecretStore.test.ts+263−0
@@ -0,0 +1,263 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
4import * as PlatformError from "effect/PlatformError";
5
6import { ServerConfig } from "../../config.ts";
7import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";
8import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
9
10const makeServerConfigLayer = () =>
11 ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });
12
13const makeServerSecretStoreLayer = () =>
14 Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
15
16const PermissionDeniedFileSystemLayer = Layer.effect(
17 FileSystem.FileSystem,
18 Effect.gen(function* () {
19 const fileSystem = yield* FileSystem.FileSystem;
20
21 return {
22 ...fileSystem,
23 readFile: (path) =>
24 Effect.fail(
25 PlatformError.systemError({
26 _tag: "PermissionDenied",
27 module: "FileSystem",
28 method: "readFile",
29 pathOrDescriptor: path,
30 description: "Permission denied while reading secret file.",
31 }),
32 ),
33 } satisfies FileSystem.FileSystem;
34 }),
35).pipe(Layer.provide(NodeServices.layer));
36
37const makePermissionDeniedSecretStoreLayer = () =>
38 ServerSecretStoreLive.pipe(
39 Layer.provide(makeServerConfigLayer()),
40 Layer.provideMerge(PermissionDeniedFileSystemLayer),
41 );
42
43const RenameFailureFileSystemLayer = Layer.effect(
44 FileSystem.FileSystem,
45 Effect.gen(function* () {
46 const fileSystem = yield* FileSystem.FileSystem;
47
48 return {
49 ...fileSystem,
50 rename: (from, to) =>
51 Effect.fail(
52 PlatformError.systemError({
53 _tag: "PermissionDenied",
54 module: "FileSystem",
55 method: "rename",
56 pathOrDescriptor: `${String(from)} -> ${String(to)}`,
57 description: "Permission denied while persisting secret file.",
58 }),
59 ),
60 } satisfies FileSystem.FileSystem;
61 }),
62).pipe(Layer.provide(NodeServices.layer));
63
64const makeRenameFailureSecretStoreLayer = () =>
65 ServerSecretStoreLive.pipe(
66 Layer.provide(makeServerConfigLayer()),
67 Layer.provideMerge(RenameFailureFileSystemLayer),
68 );
69
70const RemoveFailureFileSystemLayer = Layer.effect(
71 FileSystem.FileSystem,
72 Effect.gen(function* () {
73 const fileSystem = yield* FileSystem.FileSystem;
74
75 return {
76 ...fileSystem,
77 remove: (path, options) =>
78 Effect.fail(
79 PlatformError.systemError({
80 _tag: "PermissionDenied",
81 module: "FileSystem",
82 method: "remove",
83 pathOrDescriptor: String(path),
84 description: `Permission denied while removing secret file.${options ? " options-set" : ""}`,
85 }),
86 ),
87 } satisfies FileSystem.FileSystem;
88 }),
89).pipe(Layer.provide(NodeServices.layer));
90
91const makeRemoveFailureSecretStoreLayer = () =>
92 ServerSecretStoreLive.pipe(
93 Layer.provide(makeServerConfigLayer()),
94 Layer.provideMerge(RemoveFailureFileSystemLayer),
95 );
96
97const ConcurrentReadMissFileSystemLayer = Layer.effect(
98 FileSystem.FileSystem,
99 Effect.gen(function* () {
100 const fileSystem = yield* FileSystem.FileSystem;
101 const readCountRef = yield* Ref.make(0);
102 const readBarrier = yield* Deferred.make<void>();
103
104 return {
105 ...fileSystem,
106 readFile: (path) =>
107 String(path).endsWith("/session-signing-key.bin")
108 ? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe(
109 Effect.flatMap((count) => {
110 if (count > 2) {
111 return fileSystem.readFile(path);
112 }
113 return Effect.gen(function* () {
114 if (count === 2) {
115 yield* Deferred.succeed(readBarrier, void 0);
116 }
117 yield* Deferred.await(readBarrier);
118 return yield* Effect.failCause(
119 Cause.fail(
120 PlatformError.systemError({
121 _tag: "NotFound",
122 module: "FileSystem",
123 method: "readFile",
124 pathOrDescriptor: String(path),
125 description: "Secret file does not exist yet.",
126 }),
127 ),
128 );
129 });
130 }),
131 )
132 : fileSystem.readFile(path),
133 } satisfies FileSystem.FileSystem;
134 }),
135).pipe(Layer.provide(NodeServices.layer));
136
137const makeConcurrentCreateSecretStoreLayer = () =>
138 ServerSecretStoreLive.pipe(
139 Layer.provide(makeServerConfigLayer()),
140 Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
141 );
142
143it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
144 it.effect("returns null when a secret file does not exist", () =>
145 Effect.gen(function* () {
146 const secretStore = yield* ServerSecretStore;
147
148 const secret = yield* secretStore.get("missing-secret");
149
150 expect(secret).toBeNull();
151 }).pipe(Effect.provide(makeServerSecretStoreLayer())),
152 );
153
154 it.effect("reuses an existing secret instead of regenerating it", () =>
155 Effect.gen(function* () {
156 const secretStore = yield* ServerSecretStore;
157
158 const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
159 const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
160
161 expect(Array.from(second)).toEqual(Array.from(first));
162 }).pipe(Effect.provide(makeServerSecretStoreLayer())),
163 );
164
165 it.effect("returns the persisted secret when concurrent creators race", () =>
166 Effect.gen(function* () {
167 const secretStore = yield* ServerSecretStore;
168
169 const [first, second] = yield* Effect.all(
170 [
171 secretStore.getOrCreateRandom("session-signing-key", 32),
172 secretStore.getOrCreateRandom("session-signing-key", 32),
173 ],
174 { concurrency: "unbounded" },
175 );
176 const persisted = yield* secretStore.get("session-signing-key");
177
178 expect(persisted).not.toBeNull();
179 expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
180 expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
181 }).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
182 );
183
184 it.effect("uses restrictive permissions for the secret directory and files", () =>
185 Effect.gen(function* () {
186 const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
187 const recordingFileSystemLayer = Layer.effect(
188 FileSystem.FileSystem,
189 Effect.gen(function* () {
190 const fileSystem = yield* FileSystem.FileSystem;
191
192 return {
193 ...fileSystem,
194 makeDirectory: () => Effect.void,
195 writeFile: () => Effect.void,
196 rename: () => Effect.void,
197 chmod: (path, mode) =>
198 Effect.sync(() => {
199 chmodCalls.push({ path: String(path), mode });
200 }),
201 } satisfies FileSystem.FileSystem;
202 }),
203 ).pipe(Layer.provide(NodeServices.layer));
204
205 const secretStore = yield* Effect.service(ServerSecretStore).pipe(
206 Effect.provide(
207 ServerSecretStoreLive.pipe(
208 Layer.provide(makeServerConfigLayer()),
209 Layer.provideMerge(recordingFileSystemLayer),
210 ),
211 ),
212 );
213
214 yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
215
216 expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe(
217 true,
218 );
219 expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2);
220 }).pipe(Effect.provide(NodeServices.layer)),
221 );
222
223 it.effect("propagates read failures other than missing-file errors", () =>
224 Effect.gen(function* () {
225 const secretStore = yield* ServerSecretStore;
226
227 const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
228
229 expect(error).toBeInstanceOf(SecretStoreError);
230 expect(error.message).toContain("Failed to read secret session-signing-key.");
231 expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
232 expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
233 }).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
234 );
235
236 it.effect("propagates write failures instead of treating them as success", () =>
237 Effect.gen(function* () {
238 const secretStore = yield* ServerSecretStore;
239
240 const error = yield* Effect.flip(
241 secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
242 );
243
244 expect(error).toBeInstanceOf(SecretStoreError);
245 expect(error.message).toContain("Failed to persist secret session-signing-key.");
246 expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
247 expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
248 }).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
249 );
250
251 it.effect("propagates remove failures other than missing-file errors", () =>
252 Effect.gen(function* () {
253 const secretStore = yield* ServerSecretStore;
254
255 const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
256
257 expect(error).toBeInstanceOf(SecretStoreError);
258 expect(error.message).toContain("Failed to remove secret session-signing-key.");
259 expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
260 expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
261 }).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
262 );
263});
apps/server/src/auth/Layers/ServerSecretStore.ts+148−0
@@ -0,0 +1,148 @@
1import * as Crypto from "node:crypto";
2
3import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
4import * as PlatformError from "effect/PlatformError";
5
6import { ServerConfig } from "../../config.ts";
7import {
8 SecretStoreError,
9 ServerSecretStore,
10 type ServerSecretStoreShape,
11} from "../Services/ServerSecretStore.ts";
12
13export const makeServerSecretStore = Effect.gen(function* () {
14 const fileSystem = yield* FileSystem.FileSystem;
15 const path = yield* Path.Path;
16 const serverConfig = yield* ServerConfig;
17
18 yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
19 yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
20 Effect.mapError(
21 (cause) =>
22 new SecretStoreError({
23 message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
24 cause,
25 }),
26 ),
27 );
28
29 const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
30
31 const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
32 Predicate.isTagged(u, "PlatformError");
33
34 const get: ServerSecretStoreShape["get"] = (name) =>
35 fileSystem.readFile(resolveSecretPath(name)).pipe(
36 Effect.map((bytes) => Uint8Array.from(bytes)),
37 Effect.catch((cause) =>
38 cause.reason._tag === "NotFound"
39 ? Effect.succeed(null)
40 : Effect.fail(
41 new SecretStoreError({
42 message: `Failed to read secret ${name}.`,
43 cause,
44 }),
45 ),
46 ),
47 );
48
49 const set: ServerSecretStoreShape["set"] = (name, value) => {
50 const secretPath = resolveSecretPath(name);
51 const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
52 return Effect.gen(function* () {
53 yield* fileSystem.writeFile(tempPath, value);
54 yield* fileSystem.chmod(tempPath, 0o600);
55 yield* fileSystem.rename(tempPath, secretPath);
56 yield* fileSystem.chmod(secretPath, 0o600);
57 }).pipe(
58 Effect.catch((cause) =>
59 fileSystem.remove(tempPath).pipe(
60 Effect.ignore,
61 Effect.flatMap(() =>
62 Effect.fail(
63 new SecretStoreError({
64 message: `Failed to persist secret ${name}.`,
65 cause,
66 }),
67 ),
68 ),
69 ),
70 ),
71 );
72 };
73
74 const create: ServerSecretStoreShape["set"] = (name, value) => {
75 const secretPath = resolveSecretPath(name);
76 return Effect.scoped(
77 Effect.gen(function* () {
78 const file = yield* fileSystem.open(secretPath, {
79 flag: "wx",
80 mode: 0o600,
81 });
82 yield* file.writeAll(value);
83 yield* file.sync;
84 yield* fileSystem.chmod(secretPath, 0o600);
85 }),
86 ).pipe(
87 Effect.mapError(
88 (cause) =>
89 new SecretStoreError({
90 message: `Failed to persist secret ${name}.`,
91 cause,
92 }),
93 ),
94 );
95 };
96
97 const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
98 get(name).pipe(
99 Effect.flatMap((existing) => {
100 if (existing) {
101 return Effect.succeed(existing);
102 }
103
104 const generated = Crypto.randomBytes(bytes);
105 return create(name, generated).pipe(
106 Effect.as(Uint8Array.from(generated)),
107 Effect.catchTag("SecretStoreError", (error) =>
108 isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
109 ? get(name).pipe(
110 Effect.flatMap((created) =>
111 created !== null
112 ? Effect.succeed(created)
113 : Effect.fail(
114 new SecretStoreError({
115 message: `Failed to read secret ${name} after concurrent creation.`,
116 }),
117 ),
118 ),
119 )
120 : Effect.fail(error),
121 ),
122 );
123 }),
124 );
125
126 const remove: ServerSecretStoreShape["remove"] = (name) =>
127 fileSystem.remove(resolveSecretPath(name)).pipe(
128 Effect.catch((cause) =>
129 cause.reason._tag === "NotFound"
130 ? Effect.void
131 : Effect.fail(
132 new SecretStoreError({
133 message: `Failed to remove secret ${name}.`,
134 cause,
135 }),
136 ),
137 ),
138 );
139
140 return {
141 get,
142 set,
143 getOrCreateRandom,
144 remove,
145 } satisfies ServerSecretStoreShape;
146});
147
148export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);
apps/server/src/auth/Layers/SessionCredentialService.test.ts+191−0
@@ -0,0 +1,191 @@
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { Duration, Effect, Layer } from "effect";
4import { TestClock } from "effect/testing";
5
6import type { ServerConfigShape } from "../../config.ts";
7import { ServerConfig } from "../../config.ts";
8import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
9import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
10import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
11import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
12
13const makeServerConfigLayer = (
14 overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
15) =>
16 Layer.effect(
17 ServerConfig,
18 Effect.gen(function* () {
19 const config = yield* ServerConfig;
20 return {
21 ...config,
22 ...overrides,
23 } satisfies ServerConfigShape;
24 }),
25 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" })));
26
27const makeSessionCredentialLayer = (
28 overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
29) =>
30 SessionCredentialServiceLive.pipe(
31 Layer.provide(SqlitePersistenceMemory),
32 Layer.provide(ServerSecretStoreLive),
33 Layer.provide(makeServerConfigLayer(overrides)),
34 );
35
36it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {
37 it.effect("issues and verifies signed browser session tokens", () =>
38 Effect.gen(function* () {
39 const sessions = yield* SessionCredentialService;
40 const issued = yield* sessions.issue({
41 subject: "desktop-bootstrap",
42 role: "owner",
43 client: {
44 label: "Desktop app",
45 deviceType: "desktop",
46 os: "macOS",
47 browser: "Electron",
48 ipAddress: "127.0.0.1",
49 },
50 });
51 const verified = yield* sessions.verify(issued.token);
52
53 expect(verified.method).toBe("browser-session-cookie");
54 expect(verified.subject).toBe("desktop-bootstrap");
55 expect(verified.role).toBe("owner");
56 expect(verified.client.label).toBe("Desktop app");
57 expect(verified.client.browser).toBe("Electron");
58 expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
59 }).pipe(Effect.provide(makeSessionCredentialLayer())),
60 );
61 it.effect("rejects malformed session tokens", () =>
62 Effect.gen(function* () {
63 const sessions = yield* SessionCredentialService;
64 const error = yield* Effect.flip(sessions.verify("not-a-session-token"));
65
66 expect(error._tag).toBe("SessionCredentialError");
67 expect(error.message).toContain("Malformed session token");
68 }).pipe(Effect.provide(makeSessionCredentialLayer())),
69 );
70 it.effect("verifies session tokens against the Effect clock", () =>
71 Effect.gen(function* () {
72 const sessions = yield* SessionCredentialService;
73 const issued = yield* sessions.issue({
74 method: "bearer-session-token",
75 subject: "test-clock",
76 });
77 const verified = yield* sessions.verify(issued.token);
78
79 expect(verified.method).toBe("bearer-session-token");
80 expect(verified.subject).toBe("test-clock");
81 expect(verified.role).toBe("client");
82 }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
83 );
84
85 it.effect("rejects websocket tokens once the parent session has expired", () =>
86 Effect.gen(function* () {
87 const sessions = yield* SessionCredentialService;
88 const issued = yield* sessions.issue({
89 method: "bearer-session-token",
90 subject: "short-lived",
91 ttl: Duration.seconds(1),
92 });
93 const websocket = yield* sessions.issueWebSocketToken(issued.sessionId);
94
95 yield* TestClock.adjust(Duration.seconds(2));
96
97 const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
98 expect(error.message).toContain("expired");
99 }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
100 );
101
102 it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>
103 Effect.gen(function* () {
104 const sessions = yield* SessionCredentialService;
105 const owner = yield* sessions.issue({
106 subject: "desktop-bootstrap",
107 role: "owner",
108 client: {
109 label: "Desktop app",
110 deviceType: "desktop",
111 os: "macOS",
112 browser: "Electron",
113 },
114 });
115 const client = yield* sessions.issue({
116 subject: "one-time-token",
117 role: "client",
118 client: {
119 label: "Julius iPhone",
120 deviceType: "mobile",
121 os: "iOS",
122 browser: "Safari",
123 ipAddress: "192.168.1.88",
124 },
125 });
126
127 yield* sessions.markConnected(client.sessionId);
128 const beforeRevoke = yield* sessions.listActive();
129 const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId);
130 const afterRevoke = yield* sessions.listActive();
131 const revokedClient = yield* Effect.flip(sessions.verify(client.token));
132
133 expect(beforeRevoke).toHaveLength(2);
134 expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
135 true,
136 );
137 expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.client.label).toBe(
138 "Julius iPhone",
139 );
140 expect(
141 beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType,
142 ).toBe("desktop");
143 expect(revokedCount).toBe(1);
144 expect(afterRevoke).toHaveLength(1);
145 expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId);
146 expect(revokedClient.message).toContain("revoked");
147 }).pipe(Effect.provide(makeSessionCredentialLayer())),
148 );
149
150 it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () =>
151 Effect.gen(function* () {
152 const sessions = yield* SessionCredentialService;
153 const issued = yield* sessions.issue({
154 subject: "reconnect-test",
155 method: "bearer-session-token",
156 });
157
158 const beforeConnect = yield* sessions.listActive();
159 expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
160
161 yield* TestClock.adjust(Duration.seconds(1));
162 yield* sessions.markConnected(issued.sessionId);
163 const firstConnect = yield* sessions.listActive();
164 const firstConnectedAt = firstConnect[0]?.lastConnectedAt;
165
166 expect(firstConnect[0]?.connected).toBe(true);
167 expect(firstConnectedAt).not.toBeNull();
168
169 yield* TestClock.adjust(Duration.seconds(1));
170 yield* sessions.markConnected(issued.sessionId);
171 const stillConnected = yield* sessions.listActive();
172
173 expect(stillConnected[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
174
175 yield* sessions.markDisconnected(issued.sessionId);
176 yield* sessions.markDisconnected(issued.sessionId);
177 const afterDisconnect = yield* sessions.listActive();
178
179 expect(afterDisconnect[0]?.connected).toBe(false);
180 expect(afterDisconnect[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
181
182 yield* TestClock.adjust(Duration.seconds(1));
183 yield* sessions.markConnected(issued.sessionId);
184 const afterReconnect = yield* sessions.listActive();
185
186 expect(afterReconnect[0]?.connected).toBe(true);
187 expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull();
188 expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());
189 }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
190 );
191});
apps/server/src/auth/Layers/SessionCredentialService.ts+500−0
@@ -0,0 +1,500 @@
1import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
2import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
3import { Option } from "effect";
4
5import { ServerConfig } from "../../config.ts";
6import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
7import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
8import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
9import {
10 SessionCredentialError,
11 SessionCredentialService,
12 type IssuedSession,
13 type SessionCredentialChange,
14 type SessionCredentialServiceShape,
15 type VerifiedSession,
16} from "../Services/SessionCredentialService.ts";
17import {
18 base64UrlDecodeUtf8,
19 base64UrlEncode,
20 resolveSessionCookieName,
21 signPayload,
22 timingSafeEqualBase64Url,
23} from "../utils.ts";
24
25const SIGNING_SECRET_NAME = "server-signing-key";
26const DEFAULT_SESSION_TTL = Duration.days(30);
27const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
28
29const SessionClaims = Schema.Struct({
30 v: Schema.Literal(1),
31 kind: Schema.Literal("session"),
32 sid: AuthSessionId,
33 sub: Schema.String,
34 role: Schema.Literals(["owner", "client"]),
35 method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
36 iat: Schema.Number,
37 exp: Schema.Number,
38});
39type SessionClaims = typeof SessionClaims.Type;
40
41const WebSocketClaims = Schema.Struct({
42 v: Schema.Literal(1),
43 kind: Schema.Literal("websocket"),
44 sid: AuthSessionId,
45 iat: Schema.Number,
46 exp: Schema.Number,
47});
48type WebSocketClaims = typeof WebSocketClaims.Type;
49
50const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
51const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
52
53function createDefaultClientMetadata(): AuthClientMetadata {
54 return {
55 deviceType: "unknown",
56 };
57}
58
59function toClientMetadata(record: {
60 readonly label: string | null;
61 readonly ipAddress: string | null;
62 readonly userAgent: string | null;
63 readonly deviceType: AuthClientMetadata["deviceType"];
64 readonly os: string | null;
65 readonly browser: string | null;
66}): AuthClientMetadata {
67 return {
68 ...(record.label ? { label: record.label } : {}),
69 ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
70 ...(record.userAgent ? { userAgent: record.userAgent } : {}),
71 deviceType: record.deviceType,
72 ...(record.os ? { os: record.os } : {}),
73 ...(record.browser ? { browser: record.browser } : {}),
74 };
75}
76
77function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
78 return {
79 ...input,
80 current: false,
81 };
82}
83
84export const makeSessionCredentialService = Effect.gen(function* () {
85 const serverConfig = yield* ServerConfig;
86 const secretStore = yield* ServerSecretStore;
87 const authSessions = yield* AuthSessionRepository;
88 const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
89 const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
90 const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
91 const cookieName = resolveSessionCookieName({
92 mode: serverConfig.mode,
93 port: serverConfig.port,
94 });
95
96 const toSessionCredentialError = (message: string) => (cause: unknown) =>
97 new SessionCredentialError({
98 message,
99 cause,
100 });
101
102 const emitUpsert = (clientSession: AuthClientSession) =>
103 PubSub.publish(changesPubSub, {
104 type: "clientUpserted",
105 clientSession,
106 }).pipe(Effect.asVoid);
107
108 const emitRemoved = (sessionId: AuthSessionId) =>
109 PubSub.publish(changesPubSub, {
110 type: "clientRemoved",
111 sessionId,
112 }).pipe(Effect.asVoid);
113
114 const loadActiveSession = (sessionId: AuthSessionId) =>
115 Effect.gen(function* () {
116 const row = yield* authSessions.getById({ sessionId });
117 if (Option.isNone(row) || row.value.revokedAt !== null) {
118 return Option.none<AuthClientSession>();
119 }
120
121 const connectedSessions = yield* Ref.get(connectedSessionsRef);
122 return Option.some(
123 toAuthClientSession({
124 sessionId: row.value.sessionId,
125 subject: row.value.subject,
126 role: row.value.role,
127 method: row.value.method,
128 client: toClientMetadata(row.value.client),
129 issuedAt: row.value.issuedAt,
130 expiresAt: row.value.expiresAt,
131 lastConnectedAt: row.value.lastConnectedAt,
132 connected: connectedSessions.has(row.value.sessionId),
133 }),
134 );
135 });
136
137 const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>
138 Ref.modify(connectedSessionsRef, (current) => {
139 const next = new Map(current);
140 const wasDisconnected = !next.has(sessionId);
141 next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
142 return [wasDisconnected, next] as const;
143 }).pipe(
144 Effect.flatMap((wasDisconnected) =>
145 wasDisconnected
146 ? DateTime.now.pipe(
147 Effect.flatMap((lastConnectedAt) =>
148 authSessions.setLastConnectedAt({
149 sessionId,
150 lastConnectedAt,
151 }),
152 ),
153 )
154 : Effect.void,
155 ),
156 Effect.flatMap(() => loadActiveSession(sessionId)),
157 Effect.flatMap((session) =>
158 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
159 ),
160 Effect.catchCause((cause) =>
161 Effect.logError("Failed to publish connected-session auth update.").pipe(
162 Effect.annotateLogs({
163 sessionId,
164 cause,
165 }),
166 ),
167 ),
168 );
169
170 const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>
171 Ref.update(connectedSessionsRef, (current) => {
172 const next = new Map(current);
173 const remaining = (next.get(sessionId) ?? 0) - 1;
174 if (remaining > 0) {
175 next.set(sessionId, remaining);
176 } else {
177 next.delete(sessionId);
178 }
179 return next;
180 }).pipe(
181 Effect.flatMap(() => loadActiveSession(sessionId)),
182 Effect.flatMap((session) =>
183 Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
184 ),
185 Effect.catchCause((cause) =>
186 Effect.logError("Failed to publish disconnected-session auth update.").pipe(
187 Effect.annotateLogs({
188 sessionId,
189 cause,
190 }),
191 ),
192 ),
193 );
194
195 const issue: SessionCredentialServiceShape["issue"] = (input) =>
196 Effect.gen(function* () {
197 const sessionId = AuthSessionId.make(crypto.randomUUID());
198 const issuedAt = yield* DateTime.now;
199 const expiresAt = DateTime.add(issuedAt, {
200 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
201 });
202 const claims: SessionClaims = {
203 v: 1,
204 kind: "session",
205 sid: sessionId,
206 sub: input?.subject ?? "browser",
207 role: input?.role ?? "client",
208 method: input?.method ?? "browser-session-cookie",
209 iat: issuedAt.epochMilliseconds,
210 exp: expiresAt.epochMilliseconds,
211 };
212 const encodedPayload = base64UrlEncode(JSON.stringify(claims));
213 const signature = signPayload(encodedPayload, signingSecret);
214 const client = input?.client ?? createDefaultClientMetadata();
215 yield* authSessions.create({
216 sessionId,
217 subject: claims.sub,
218 role: claims.role,
219 method: claims.method,
220 client: {
221 label: client.label ?? null,
222 ipAddress: client.ipAddress ?? null,
223 userAgent: client.userAgent ?? null,
224 deviceType: client.deviceType,
225 os: client.os ?? null,
226 browser: client.browser ?? null,
227 },
228 issuedAt,
229 expiresAt,
230 });
231 yield* emitUpsert(
232 toAuthClientSession({
233 sessionId,
234 subject: claims.sub,
235 role: claims.role,
236 method: claims.method,
237 client,
238 issuedAt,
239 expiresAt,
240 lastConnectedAt: null,
241 connected: false,
242 }),
243 );
244
245 return {
246 sessionId,
247 token: `${encodedPayload}.${signature}`,
248 method: claims.method,
249 client,
250 expiresAt: expiresAt,
251 role: claims.role,
252 } satisfies IssuedSession;
253 }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
254
255 const verify: SessionCredentialServiceShape["verify"] = (token) =>
256 Effect.gen(function* () {
257 const [encodedPayload, signature] = token.split(".");
258 if (!encodedPayload || !signature) {
259 return yield* new SessionCredentialError({
260 message: "Malformed session token.",
261 });
262 }
263
264 const expectedSignature = signPayload(encodedPayload, signingSecret);
265 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
266 return yield* new SessionCredentialError({
267 message: "Invalid session token signature.",
268 });
269 }
270
271 const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
272 Effect.mapError(
273 (cause) =>
274 new SessionCredentialError({
275 message: "Invalid session token payload.",
276 cause,
277 }),
278 ),
279 );
280
281 const now = yield* Clock.currentTimeMillis;
282 if (claims.exp <= now) {
283 return yield* new SessionCredentialError({
284 message: "Session token expired.",
285 });
286 }
287
288 const row = yield* authSessions.getById({ sessionId: claims.sid });
289 if (Option.isNone(row)) {
290 return yield* new SessionCredentialError({
291 message: "Unknown session token.",
292 });
293 }
294 if (row.value.revokedAt !== null) {
295 return yield* new SessionCredentialError({
296 message: "Session token revoked.",
297 });
298 }
299
300 return {
301 sessionId: claims.sid,
302 token,
303 method: claims.method,
304 client: toClientMetadata(row.value.client),
305 expiresAt: DateTime.makeUnsafe(claims.exp),
306 subject: claims.sub,
307 role: claims.role,
308 } satisfies VerifiedSession;
309 }).pipe(
310 Effect.mapError((cause) =>
311 cause instanceof SessionCredentialError
312 ? cause
313 : new SessionCredentialError({
314 message: "Failed to verify session credential.",
315 cause,
316 }),
317 ),
318 );
319
320 const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
321 sessionId,
322 input,
323 ) =>
324 Effect.gen(function* () {
325 const issuedAt = yield* DateTime.now;
326 const expiresAt = DateTime.add(issuedAt, {
327 milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
328 });
329 const claims: WebSocketClaims = {
330 v: 1,
331 kind: "websocket",
332 sid: sessionId,
333 iat: issuedAt.epochMilliseconds,
334 exp: expiresAt.epochMilliseconds,
335 };
336 const encodedPayload = base64UrlEncode(JSON.stringify(claims));
337 const signature = signPayload(encodedPayload, signingSecret);
338 return {
339 token: `${encodedPayload}.${signature}`,
340 expiresAt,
341 };
342 }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
343
344 const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
345 Effect.gen(function* () {
346 const [encodedPayload, signature] = token.split(".");
347 if (!encodedPayload || !signature) {
348 return yield* new SessionCredentialError({
349 message: "Malformed websocket token.",
350 });
351 }
352
353 const expectedSignature = signPayload(encodedPayload, signingSecret);
354 if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
355 return yield* new SessionCredentialError({
356 message: "Invalid websocket token signature.",
357 });
358 }
359
360 const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
361 Effect.mapError(
362 (cause) =>
363 new SessionCredentialError({
364 message: "Invalid websocket token payload.",
365 cause,
366 }),
367 ),
368 );
369
370 const now = yield* Clock.currentTimeMillis;
371 if (claims.exp <= now) {
372 return yield* new SessionCredentialError({
373 message: "Websocket token expired.",
374 });
375 }
376
377 const row = yield* authSessions.getById({ sessionId: claims.sid });
378 if (Option.isNone(row)) {
379 return yield* new SessionCredentialError({
380 message: "Unknown websocket session.",
381 });
382 }
383 if (row.value.expiresAt.epochMilliseconds <= now) {
384 return yield* new SessionCredentialError({
385 message: "Websocket session expired.",
386 });
387 }
388 if (row.value.revokedAt !== null) {
389 return yield* new SessionCredentialError({
390 message: "Websocket session revoked.",
391 });
392 }
393
394 return {
395 sessionId: row.value.sessionId,
396 token,
397 method: row.value.method,
398 client: toClientMetadata(row.value.client),
399 expiresAt: row.value.expiresAt,
400 subject: row.value.subject,
401 role: row.value.role,
402 } satisfies VerifiedSession;
403 }).pipe(
404 Effect.mapError((cause) =>
405 cause instanceof SessionCredentialError
406 ? cause
407 : new SessionCredentialError({
408 message: "Failed to verify websocket token.",
409 cause,
410 }),
411 ),
412 );
413
414 const listActive: SessionCredentialServiceShape["listActive"] = () =>
415 Effect.gen(function* () {
416 const now = yield* DateTime.now;
417 const connectedSessions = yield* Ref.get(connectedSessionsRef);
418 const rows = yield* authSessions.listActive({ now });
419
420 return rows.map((row) =>
421 toAuthClientSession({
422 sessionId: row.sessionId,
423 subject: row.subject,
424 role: row.role,
425 method: row.method,
426 client: toClientMetadata(row.client),
427 issuedAt: row.issuedAt,
428 expiresAt: row.expiresAt,
429 lastConnectedAt: row.lastConnectedAt,
430 connected: connectedSessions.has(row.sessionId),
431 }),
432 );
433 }).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
434
435 const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
436 Effect.gen(function* () {
437 const revokedAt = yield* DateTime.now;
438 const revoked = yield* authSessions.revoke({
439 sessionId,
440 revokedAt,
441 });
442 if (revoked) {
443 yield* Ref.update(connectedSessionsRef, (current) => {
444 const next = new Map(current);
445 next.delete(sessionId);
446 return next;
447 });
448 yield* emitRemoved(sessionId);
449 }
450 return revoked;
451 }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
452
453 const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
454 Effect.gen(function* () {
455 const revokedAt = yield* DateTime.now;
456 const revokedSessionIds = yield* authSessions.revokeAllExcept({
457 currentSessionId: sessionId,
458 revokedAt,
459 });
460 if (revokedSessionIds.length > 0) {
461 yield* Ref.update(connectedSessionsRef, (current) => {
462 const next = new Map(current);
463 for (const revokedSessionId of revokedSessionIds) {
464 next.delete(revokedSessionId);
465 }
466 return next;
467 });
468 yield* Effect.forEach(
469 revokedSessionIds,
470 (revokedSessionId) => emitRemoved(revokedSessionId),
471 {
472 concurrency: "unbounded",
473 discard: true,
474 },
475 );
476 }
477 return revokedSessionIds.length;
478 }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
479
480 return {
481 cookieName,
482 issue,
483 verify,
484 issueWebSocketToken,
485 verifyWebSocketToken,
486 listActive,
487 get streamChanges() {
488 return Stream.fromPubSub(changesPubSub);
489 },
490 revoke,
491 revokeAllExcept,
492 markConnected,
493 markDisconnected,
494 } satisfies SessionCredentialServiceShape;
495});
496
497export const SessionCredentialServiceLive = Layer.effect(
498 SessionCredentialService,
499 makeSessionCredentialService,
500).pipe(Layer.provideMerge(AuthSessionRepositoryLive));
apps/server/src/auth/Services/AuthControlPlane.ts+69−0
@@ -0,0 +1,69 @@
1import type {
2 AuthClientMetadata,
3 AuthClientSession,
4 AuthPairingLink,
5 AuthSessionId,
6} from "@t3tools/contracts";
7import { Data, DateTime, Duration, Effect, Context } from "effect";
8import { SessionRole } from "./SessionCredentialService";
9
10export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
11
12export interface IssuedPairingLink {
13 readonly id: string;
14 readonly credential: string;
15 readonly role: SessionRole;
16 readonly subject: string;
17 readonly label?: string;
18 readonly createdAt: DateTime.Utc;
19 readonly expiresAt: DateTime.Utc;
20}
21
22export interface IssuedBearerSession {
23 readonly sessionId: AuthSessionId;
24 readonly token: string;
25 readonly method: "bearer-session-token";
26 readonly role: SessionRole;
27 readonly subject: string;
28 readonly client: AuthClientMetadata;
29 readonly expiresAt: DateTime.Utc;
30}
31
32export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{
33 readonly message: string;
34 readonly cause?: unknown;
35}> {}
36
37export interface AuthControlPlaneShape {
38 readonly createPairingLink: (input?: {
39 readonly ttl?: Duration.Duration;
40 readonly label?: string;
41 readonly role?: SessionRole;
42 readonly subject?: string;
43 }) => Effect.Effect<IssuedPairingLink, AuthControlPlaneError>;
44 readonly listPairingLinks: (input?: {
45 readonly role?: SessionRole;
46 readonly excludeSubjects?: ReadonlyArray<string>;
47 }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthControlPlaneError>;
48 readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthControlPlaneError>;
49 readonly issueSession: (input?: {
50 readonly ttl?: Duration.Duration;
51 readonly subject?: string;
52 readonly role?: SessionRole;
53 readonly label?: string;
54 }) => Effect.Effect<IssuedBearerSession, AuthControlPlaneError>;
55 readonly listSessions: () => Effect.Effect<
56 ReadonlyArray<AuthClientSession>,
57 AuthControlPlaneError
58 >;
59 readonly revokeSession: (
60 sessionId: AuthSessionId,
61 ) => Effect.Effect<boolean, AuthControlPlaneError>;
62 readonly revokeOtherSessionsExcept: (
63 sessionId: AuthSessionId,
64 ) => Effect.Effect<number, AuthControlPlaneError>;
65}
66
67export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
68 "t3/AuthControlPlane",
69) {}
apps/server/src/auth/Services/BootstrapCredentialService.ts+57−0
@@ -0,0 +1,57 @@
1import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
2import { Data, DateTime, Duration, Context } from "effect";
3import type { Effect, Stream } from "effect";
4
5export type BootstrapCredentialRole = "owner" | "client";
6
7export interface BootstrapGrant {
8 readonly method: ServerAuthBootstrapMethod;
9 readonly role: BootstrapCredentialRole;
10 readonly subject: string;
11 readonly label?: string;
12 readonly expiresAt: DateTime.DateTime;
13}
14
15export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{
16 readonly message: string;
17 readonly status?: 401 | 500;
18 readonly cause?: unknown;
19}> {}
20
21export interface IssuedBootstrapCredential {
22 readonly id: string;
23 readonly credential: string;
24 readonly label?: string;
25 readonly expiresAt: DateTime.Utc;
26}
27
28export type BootstrapCredentialChange =
29 | {
30 readonly type: "pairingLinkUpserted";
31 readonly pairingLink: AuthPairingLink;
32 }
33 | {
34 readonly type: "pairingLinkRemoved";
35 readonly id: string;
36 };
37
38export interface BootstrapCredentialServiceShape {
39 readonly issueOneTimeToken: (input?: {
40 readonly ttl?: Duration.Duration;
41 readonly role?: BootstrapCredentialRole;
42 readonly subject?: string;
43 readonly label?: string;
44 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialError>;
45 readonly listActive: () => Effect.Effect<
46 ReadonlyArray<AuthPairingLink>,
47 BootstrapCredentialError
48 >;
49 readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
50 readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialError>;
51 readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
52}
53
54export class BootstrapCredentialService extends Context.Service<
55 BootstrapCredentialService,
56 BootstrapCredentialServiceShape
57>()("t3/auth/Services/BootstrapCredentialService") {}
apps/server/src/auth/Services/ServerAuth.ts+84−0
@@ -0,0 +1,84 @@
1import type {
2 AuthBearerBootstrapResult,
3 AuthBootstrapResult,
4 AuthClientMetadata,
5 AuthClientSession,
6 AuthCreatePairingCredentialInput,
7 AuthPairingLink,
8 AuthPairingCredentialResult,
9 AuthSessionId,
10 AuthSessionState,
11 ServerAuthDescriptor,
12 ServerAuthSessionMethod,
13 AuthWebSocketTokenResult,
14} from "@t3tools/contracts";
15import { Data, DateTime, Context } from "effect";
16import type { Effect } from "effect";
17import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
18import type { SessionRole } from "./SessionCredentialService.ts";
19
20export interface AuthenticatedSession {
21 readonly sessionId: AuthSessionId;
22 readonly subject: string;
23 readonly method: ServerAuthSessionMethod;
24 readonly role: SessionRole;
25 readonly expiresAt?: DateTime.DateTime;
26}
27
28export class AuthError extends Data.TaggedError("AuthError")<{
29 readonly message: string;
30 readonly status?: 400 | 401 | 403 | 500;
31 readonly cause?: unknown;
32}> {}
33
34export interface ServerAuthShape {
35 readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
36 readonly getSessionState: (
37 request: HttpServerRequest.HttpServerRequest,
38 ) => Effect.Effect<AuthSessionState, never>;
39 readonly exchangeBootstrapCredential: (
40 credential: string,
41 requestMetadata: AuthClientMetadata,
42 ) => Effect.Effect<
43 {
44 readonly response: AuthBootstrapResult;
45 readonly sessionToken: string;
46 },
47 AuthError
48 >;
49 readonly exchangeBootstrapCredentialForBearerSession: (
50 credential: string,
51 requestMetadata: AuthClientMetadata,
52 ) => Effect.Effect<AuthBearerBootstrapResult, AuthError>;
53 readonly issuePairingCredential: (
54 input?: AuthCreatePairingCredentialInput & {
55 readonly role?: SessionRole;
56 },
57 ) => Effect.Effect<AuthPairingCredentialResult, AuthError>;
58 readonly listPairingLinks: () => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthError>;
59 readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthError>;
60 readonly listClientSessions: (
61 currentSessionId: AuthSessionId,
62 ) => Effect.Effect<ReadonlyArray<AuthClientSession>, AuthError>;
63 readonly revokeClientSession: (
64 currentSessionId: AuthSessionId,
65 targetSessionId: AuthSessionId,
66 ) => Effect.Effect<boolean, AuthError>;
67 readonly revokeOtherClientSessions: (
68 currentSessionId: AuthSessionId,
69 ) => Effect.Effect<number, AuthError>;
70 readonly authenticateHttpRequest: (
71 request: HttpServerRequest.HttpServerRequest,
72 ) => Effect.Effect<AuthenticatedSession, AuthError>;
73 readonly authenticateWebSocketUpgrade: (
74 request: HttpServerRequest.HttpServerRequest,
75 ) => Effect.Effect<AuthenticatedSession, AuthError>;
76 readonly issueWebSocketToken: (
77 session: AuthenticatedSession,
78 ) => Effect.Effect<AuthWebSocketTokenResult, AuthError>;
79 readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
80}
81
82export class ServerAuth extends Context.Service<ServerAuth, ServerAuthShape>()(
83 "t3/auth/Services/ServerAuth",
84) {}
apps/server/src/auth/Services/ServerAuthPolicy.ts+11−0
@@ -0,0 +1,11 @@
1import type { ServerAuthDescriptor } from "@t3tools/contracts";
2import { Context } from "effect";
3import type { Effect } from "effect";
4
5export interface ServerAuthPolicyShape {
6 readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
7}
8
9export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
10 "t3/auth/Services/ServerAuthPolicy",
11) {}
apps/server/src/auth/Services/ServerSecretStore.ts+21−0
@@ -0,0 +1,21 @@
1import { Data, Context } from "effect";
2import type { Effect } from "effect";
3
4export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
5 readonly message: string;
6 readonly cause?: unknown;
7}> {}
8
9export interface ServerSecretStoreShape {
10 readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
11 readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
12 readonly getOrCreateRandom: (
13 name: string,
14 bytes: number,
15 ) => Effect.Effect<Uint8Array, SecretStoreError>;
16 readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
17}
18
19export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
20 "t3/auth/Services/ServerSecretStore",
21) {}
apps/server/src/auth/Services/SessionCredentialService.ts+87−0
@@ -0,0 +1,87 @@
1import type {
2 AuthClientMetadata,
3 AuthClientSession,
4 AuthSessionId,
5 ServerAuthSessionMethod,
6} from "@t3tools/contracts";
7import { Data, DateTime, Duration, Context } from "effect";
8import type { Effect, Stream } from "effect";
9
10export type SessionRole = "owner" | "client";
11
12export interface IssuedSession {
13 readonly sessionId: AuthSessionId;
14 readonly token: string;
15 readonly method: ServerAuthSessionMethod;
16 readonly client: AuthClientMetadata;
17 readonly expiresAt: DateTime.DateTime;
18 readonly role: SessionRole;
19}
20
21export interface VerifiedSession {
22 readonly sessionId: AuthSessionId;
23 readonly token: string;
24 readonly method: ServerAuthSessionMethod;
25 readonly client: AuthClientMetadata;
26 readonly expiresAt?: DateTime.DateTime;
27 readonly subject: string;
28 readonly role: SessionRole;
29}
30
31export type SessionCredentialChange =
32 | {
33 readonly type: "clientUpserted";
34 readonly clientSession: AuthClientSession;
35 }
36 | {
37 readonly type: "clientRemoved";
38 readonly sessionId: AuthSessionId;
39 };
40
41export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{
42 readonly message: string;
43 readonly cause?: unknown;
44}> {}
45
46export interface SessionCredentialServiceShape {
47 readonly cookieName: string;
48 readonly issue: (input?: {
49 readonly ttl?: Duration.Duration;
50 readonly subject?: string;
51 readonly method?: ServerAuthSessionMethod;
52 readonly role?: SessionRole;
53 readonly client?: AuthClientMetadata;
54 }) => Effect.Effect<IssuedSession, SessionCredentialError>;
55 readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
56 readonly issueWebSocketToken: (
57 sessionId: AuthSessionId,
58 input?: {
59 readonly ttl?: Duration.Duration;
60 },
61 ) => Effect.Effect<
62 {
63 readonly token: string;
64 readonly expiresAt: DateTime.DateTime;
65 },
66 SessionCredentialError
67 >;
68 readonly verifyWebSocketToken: (
69 token: string,
70 ) => Effect.Effect<VerifiedSession, SessionCredentialError>;
71 readonly listActive: () => Effect.Effect<
72 ReadonlyArray<AuthClientSession>,
73 SessionCredentialError
74 >;
75 readonly streamChanges: Stream.Stream<SessionCredentialChange>;
76 readonly revoke: (sessionId: AuthSessionId) => Effect.Effect<boolean, SessionCredentialError>;
77 readonly revokeAllExcept: (
78 sessionId: AuthSessionId,
79 ) => Effect.Effect<number, SessionCredentialError>;
80 readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
81 readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
82}
83
84export class SessionCredentialService extends Context.Service<
85 SessionCredentialService,
86 SessionCredentialServiceShape
87>()("t3/auth/Services/SessionCredentialService") {}
apps/server/src/auth/http.ts+254−0
@@ -0,0 +1,254 @@
1import {
2 type AuthBearerBootstrapResult,
3 AuthBootstrapInput,
4 AuthCreatePairingCredentialInput,
5 AuthRevokeClientSessionInput,
6 AuthRevokePairingLinkInput,
7 type AuthWebSocketTokenResult,
8} from "@t3tools/contracts";
9import { DateTime, Effect, Schema } from "effect";
10import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
11
12import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
13import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
14import { deriveAuthClientMetadata } from "./utils.ts";
15
16export const respondToAuthError = (error: AuthError) =>
17 Effect.gen(function* () {
18 if ((error.status ?? 500) >= 500) {
19 yield* Effect.logError("auth route failed", {
20 message: error.message,
21 cause: error.cause,
22 });
23 }
24 return HttpServerResponse.jsonUnsafe(
25 {
26 error: error.message,
27 },
28 { status: error.status ?? 500 },
29 );
30 });
31
32export const authSessionRouteLayer = HttpRouter.add(
33 "GET",
34 "/api/auth/session",
35 Effect.gen(function* () {
36 const request = yield* HttpServerRequest.HttpServerRequest;
37 const serverAuth = yield* ServerAuth;
38 const session = yield* serverAuth.getSessionState(request);
39 return HttpServerResponse.jsonUnsafe(session, { status: 200 });
40 }),
41);
42
43const PairingCredentialRequestHeaders = Schema.Struct({
44 "content-length": Schema.optionalKey(Schema.String),
45 "content-type": Schema.optionalKey(Schema.String),
46 "transfer-encoding": Schema.optionalKey(Schema.String),
47});
48
49function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) {
50 const contentLengthHeader = headers["content-length"];
51 if (typeof contentLengthHeader === "string") {
52 const contentLength = Number.parseInt(contentLengthHeader, 10);
53 if (Number.isFinite(contentLength)) {
54 return contentLength > 0;
55 }
56 }
57 return typeof headers["transfer-encoding"] === "string";
58}
59
60export const authBootstrapRouteLayer = HttpRouter.add(
61 "POST",
62 "/api/auth/bootstrap",
63 Effect.gen(function* () {
64 const request = yield* HttpServerRequest.HttpServerRequest;
65 const serverAuth = yield* ServerAuth;
66 const sessions = yield* SessionCredentialService;
67 const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
68 Effect.mapError(
69 (cause) =>
70 new AuthError({
71 message: "Invalid bootstrap payload.",
72 status: 400,
73 cause,
74 }),
75 ),
76 );
77 const result = yield* serverAuth.exchangeBootstrapCredential(
78 payload.credential,
79 deriveAuthClientMetadata({ request }),
80 );
81
82 return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
83 HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
84 expires: DateTime.toDate(result.response.expiresAt),
85 httpOnly: true,
86 path: "/",
87 sameSite: "lax",
88 }),
89 );
90 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
91);
92
93export const authBearerBootstrapRouteLayer = HttpRouter.add(
94 "POST",
95 "/api/auth/bootstrap/bearer",
96 Effect.gen(function* () {
97 const request = yield* HttpServerRequest.HttpServerRequest;
98 const serverAuth = yield* ServerAuth;
99 const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
100 Effect.mapError(
101 (cause) =>
102 new AuthError({
103 message: "Invalid bootstrap payload.",
104 status: 400,
105 cause,
106 }),
107 ),
108 );
109 const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession(
110 payload.credential,
111 deriveAuthClientMetadata({ request }),
112 );
113 return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
114 status: 200,
115 });
116 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
117);
118
119export const authWebSocketTokenRouteLayer = HttpRouter.add(
120 "POST",
121 "/api/auth/ws-token",
122 Effect.gen(function* () {
123 const request = yield* HttpServerRequest.HttpServerRequest;
124 const serverAuth = yield* ServerAuth;
125 const session = yield* serverAuth.authenticateHttpRequest(request);
126 const result = yield* serverAuth.issueWebSocketToken(session);
127 return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
128 status: 200,
129 });
130 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
131);
132
133export const authPairingCredentialRouteLayer = HttpRouter.add(
134 "POST",
135 "/api/auth/pairing-token",
136 Effect.gen(function* () {
137 const serverAuth = yield* ServerAuth;
138 const request = yield* HttpServerRequest.HttpServerRequest;
139 const session = yield* serverAuth.authenticateHttpRequest(request);
140 if (session.role !== "owner") {
141 return yield* new AuthError({
142 message: "Only owner sessions can create pairing credentials.",
143 status: 403,
144 });
145 }
146 const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe(
147 Effect.mapError(
148 (cause) =>
149 new AuthError({
150 message: "Invalid pairing credential request headers.",
151 status: 400,
152 cause,
153 }),
154 ),
155 );
156 const payload = hasRequestBody(headers)
157 ? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe(
158 Effect.mapError(
159 (cause) =>
160 new AuthError({
161 message: "Invalid pairing credential payload.",
162 status: 400,
163 cause,
164 }),
165 ),
166 )
167 : {};
168 const result = yield* serverAuth.issuePairingCredential(payload);
169 return HttpServerResponse.jsonUnsafe(result, { status: 200 });
170 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
171);
172
173const authenticateOwnerSession = Effect.gen(function* () {
174 const request = yield* HttpServerRequest.HttpServerRequest;
175 const serverAuth = yield* ServerAuth;
176 const session = yield* serverAuth.authenticateHttpRequest(request);
177 if (session.role !== "owner") {
178 return yield* new AuthError({
179 message: "Only owner sessions can manage network access.",
180 status: 403,
181 });
182 }
183 return { serverAuth, session } as const;
184});
185
186export const authPairingLinksRouteLayer = HttpRouter.add(
187 "GET",
188 "/api/auth/pairing-links",
189 Effect.gen(function* () {
190 const { serverAuth } = yield* authenticateOwnerSession;
191 const pairingLinks = yield* serverAuth.listPairingLinks();
192 return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 });
193 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
194);
195
196export const authPairingLinksRevokeRouteLayer = HttpRouter.add(
197 "POST",
198 "/api/auth/pairing-links/revoke",
199 Effect.gen(function* () {
200 const { serverAuth } = yield* authenticateOwnerSession;
201 const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe(
202 Effect.mapError(
203 (cause) =>
204 new AuthError({
205 message: "Invalid revoke pairing link payload.",
206 status: 400,
207 cause,
208 }),
209 ),
210 );
211 const revoked = yield* serverAuth.revokePairingLink(payload.id);
212 return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
213 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
214);
215
216export const authClientsRouteLayer = HttpRouter.add(
217 "GET",
218 "/api/auth/clients",
219 Effect.gen(function* () {
220 const { serverAuth, session } = yield* authenticateOwnerSession;
221 const clients = yield* serverAuth.listClientSessions(session.sessionId);
222 return HttpServerResponse.jsonUnsafe(clients, { status: 200 });
223 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
224);
225
226export const authClientsRevokeRouteLayer = HttpRouter.add(
227 "POST",
228 "/api/auth/clients/revoke",
229 Effect.gen(function* () {
230 const { serverAuth, session } = yield* authenticateOwnerSession;
231 const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe(
232 Effect.mapError(
233 (cause) =>
234 new AuthError({
235 message: "Invalid revoke client payload.",
236 status: 400,
237 cause,
238 }),
239 ),
240 );
241 const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId);
242 return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
243 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
244);
245
246export const authClientsRevokeOthersRouteLayer = HttpRouter.add(
247 "POST",
248 "/api/auth/clients/revoke-others",
249 Effect.gen(function* () {
250 const { serverAuth, session } = yield* authenticateOwnerSession;
251 const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
252 return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 });
253 }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
254);
apps/server/src/auth/utils.test.ts+26−0
@@ -0,0 +1,26 @@
1import { describe, expect, it } from "vitest";
2
3import { deriveAuthClientMetadata } from "./utils";
4
5describe("deriveAuthClientMetadata", () => {
6 it("labels Electron user agents as Electron instead of Chrome", () => {
7 const metadata = deriveAuthClientMetadata({
8 request: {
9 headers: {
10 "user-agent":
11 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) t3code/0.0.15 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36",
12 },
13 source: {
14 remoteAddress: "::ffff:127.0.0.1",
15 },
16 } as never,
17 });
18
19 expect(metadata).toMatchObject({
20 browser: "Electron",
21 deviceType: "desktop",
22 ipAddress: "127.0.0.1",
23 os: "macOS",
24 });
25 });
26});
apps/server/src/auth/utils.ts+132−0
@@ -0,0 +1,132 @@
1import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";
2import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
3import * as Crypto from "node:crypto";
4
5const SESSION_COOKIE_NAME = "t3_session";
6
7export function resolveSessionCookieName(input: {
8 readonly mode: "web" | "desktop";
9 readonly port: number;
10}): string {
11 if (input.mode !== "desktop") {
12 return SESSION_COOKIE_NAME;
13 }
14
15 return `${SESSION_COOKIE_NAME}_${input.port}`;
16}
17
18export function base64UrlEncode(input: string | Uint8Array): string {
19 const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
20 return buffer.toString("base64url");
21}
22
23export function base64UrlDecodeUtf8(input: string): string {
24 return Buffer.from(input, "base64url").toString("utf8");
25}
26
27export function signPayload(payload: string, secret: Uint8Array): string {
28 return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
29}
30
31export function timingSafeEqualBase64Url(left: string, right: string): boolean {
32 const leftBuffer = Buffer.from(left, "base64url");
33 const rightBuffer = Buffer.from(right, "base64url");
34 if (leftBuffer.length !== rightBuffer.length) {
35 return false;
36 }
37 return Crypto.timingSafeEqual(leftBuffer, rightBuffer);
38}
39
40function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
41 if (typeof value !== "string") {
42 return undefined;
43 }
44 const trimmed = value.trim();
45 return trimmed.length > 0 ? trimmed : undefined;
46}
47
48function normalizeIpAddress(value: string | null | undefined): string | undefined {
49 const normalized = normalizeNonEmptyString(value);
50 if (!normalized) {
51 return undefined;
52 }
53 return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
54}
55
56function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
57 if (!userAgent) {
58 return "unknown";
59 }
60
61 const normalized = userAgent.toLowerCase();
62 if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
63 return "bot";
64 }
65 if (/ipad|tablet/.test(normalized)) {
66 return "tablet";
67 }
68 if (/iphone|android.+mobile|mobile/.test(normalized)) {
69 return "mobile";
70 }
71 return "desktop";
72}
73
74function inferBrowser(userAgent: string | undefined): string | undefined {
75 if (!userAgent) {
76 return undefined;
77 }
78 const normalized = userAgent.toLowerCase();
79 if (/edg\//.test(normalized)) return "Edge";
80 if (/opr\//.test(normalized)) return "Opera";
81 if (/firefox\//.test(normalized)) return "Firefox";
82 if (/electron\//.test(normalized)) return "Electron";
83 if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
84 if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
85 return undefined;
86}
87
88function inferOs(userAgent: string | undefined): string | undefined {
89 if (!userAgent) {
90 return undefined;
91 }
92 const normalized = userAgent.toLowerCase();
93 if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
94 if (/android/.test(normalized)) return "Android";
95 if (/mac os x|macintosh/.test(normalized)) return "macOS";
96 if (/windows nt/.test(normalized)) return "Windows";
97 if (/linux/.test(normalized)) return "Linux";
98 return undefined;
99}
100
101function readRemoteAddressFromSource(source: unknown): string | undefined {
102 if (!source || typeof source !== "object") {
103 return undefined;
104 }
105
106 const candidate = source as {
107 readonly remoteAddress?: string | null;
108 readonly socket?: {
109 readonly remoteAddress?: string | null;
110 };
111 };
112
113 return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
114}
115
116export function deriveAuthClientMetadata(input: {
117 readonly request: HttpServerRequest.HttpServerRequest;
118 readonly label?: string;
119}): AuthClientMetadata {
120 const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
121 const ipAddress = readRemoteAddressFromSource(input.request.source);
122 const os = inferOs(userAgent);
123 const browser = inferBrowser(userAgent);
124 return {
125 ...(input.label ? { label: input.label } : {}),
126 ...(ipAddress ? { ipAddress } : {}),
127 ...(userAgent ? { userAgent } : {}),
128 deviceType: inferDeviceType(userAgent),
129 ...(os ? { os } : {}),
130 ...(browser ? { browser } : {}),
131 };
132}
apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts+4−4
@@ -26,7 +26,7 @@ function makeThreadCheckpointContext(input: { · 25 unmodified lines
26 worktreePath: input.worktreePath,26 worktreePath: input.worktreePath,
27 checkpoints: [27 checkpoints: [
28 {28 {
29 turnId: TurnId.makeUnsafe("turn-1"),29 turnId: TurnId.make("turn-1"),
30 checkpointTurnCount: input.checkpointTurnCount,30 checkpointTurnCount: input.checkpointTurnCount,
31 checkpointRef: input.checkpointRef,31 checkpointRef: input.checkpointRef,
32 status: "ready",32 status: "ready",
@@ -40,8 +40,8 @@ function makeThreadCheckpointContext(input: { · 7 unmodified lines
40 40
41describe("CheckpointDiffQueryLive", () => {41describe("CheckpointDiffQueryLive", () => {
42 it("computes diffs using canonical turn-0 checkpoint refs", async () => {42 it("computes diffs using canonical turn-0 checkpoint refs", async () => {
43 const projectId = ProjectId.makeUnsafe("project-1");43 const projectId = ProjectId.make("project-1");
44 const threadId = ThreadId.makeUnsafe("thread-1");44 const threadId = ThreadId.make("thread-1");
45 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);45 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
46 const hasCheckpointRefCalls: Array<CheckpointRef> = [];46 const hasCheckpointRefCalls: Array<CheckpointRef> = [];
47 const diffCheckpointsCalls: Array<{47 const diffCheckpointsCalls: Array<{
@@ -119,7 +119,7 @@ describe("CheckpointDiffQueryLive", () => { · 71 unmodified lines
119 });119 });
120 120
121 it("fails when the thread is missing from the snapshot", async () => {121 it("fails when the thread is missing from the snapshot", async () => {
122 const threadId = ThreadId.makeUnsafe("thread-missing");122 const threadId = ThreadId.make("thread-missing");
123 123
124 const checkpointStore: CheckpointStoreShape = {124 const checkpointStore: CheckpointStoreShape = {
125 isGitRepository: () => Effect.succeed(true),125 isGitRepository: () => Effect.succeed(true),
apps/server/src/checkpointing/Layers/CheckpointStore.test.ts+3−3
@@ -80,7 +80,7 @@ function initRepoWithCommit( · 79 unmodified lines
80 });80 });
81}81}
82 82
83function buildLargeText(lineCount = 20_000): string {83function buildLargeText(lineCount = 5_000): string {
84 return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)84 return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
85 .join("\n")85 .join("\n")
86 .concat("\n");86 .concat("\n");
@@ -93,7 +93,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => { · 6 unmodified lines
93 const tmp = yield* makeTmpDir();93 const tmp = yield* makeTmpDir();
94 yield* initRepoWithCommit(tmp);94 yield* initRepoWithCommit(tmp);
95 const checkpointStore = yield* CheckpointStore;95 const checkpointStore = yield* CheckpointStore;
96 const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");96 const threadId = ThreadId.make("thread-checkpoint-store");
97 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);97 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
98 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);98 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
99 99
@@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => { · 15 unmodified lines
115 115
116 expect(diff).toContain("diff --git");116 expect(diff).toContain("diff --git");
117 expect(diff).not.toContain("[truncated]");117 expect(diff).not.toContain("[truncated]");
118 expect(diff).toContain("+line 19999");118 expect(diff).toContain("+line 04999");
119 }),119 }),
120 );120 );
121 });121 });
apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts+2−2
@@ -12,7 +12,7 @@ import type { · 11 unmodified lines
12 OrchestrationGetTurnDiffInput,12 OrchestrationGetTurnDiffInput,
13 OrchestrationGetTurnDiffResult,13 OrchestrationGetTurnDiffResult,
14} from "@t3tools/contracts";14} from "@t3tools/contracts";
15import { ServiceMap } from "effect";15import { Context } from "effect";
16import type { Effect } from "effect";16import type { Effect } from "effect";
17 17
18import type { CheckpointServiceError } from "../Errors.ts";18import type { CheckpointServiceError } from "../Errors.ts";
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape { · 24 unmodified lines
43/**43/**
44 * CheckpointDiffQuery - Service tag for checkpoint diff queries.44 * CheckpointDiffQuery - Service tag for checkpoint diff queries.
45 */45 */
46export class CheckpointDiffQuery extends ServiceMap.Service<46export class CheckpointDiffQuery extends Context.Service<
47 CheckpointDiffQuery,47 CheckpointDiffQuery,
48 CheckpointDiffQueryShape48 CheckpointDiffQueryShape
49>()("t3/checkpointing/Services/CheckpointDiffQuery") {}49>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
apps/server/src/checkpointing/Services/CheckpointStore.ts+3−3
@@ -5,12 +5,12 @@ · 4 unmodified lines
5 * workspace thread timeline. It does not store user-facing checkpoint metadata5 * workspace thread timeline. It does not store user-facing checkpoint metadata
6 * and does not coordinate provider conversation rollback.6 * and does not coordinate provider conversation rollback.
7 *7 *
8 * Uses Effect `ServiceMap.Service` for dependency injection and exposes typed8 * Uses Effect `Context.Service` for dependency injection and exposes typed
9 * domain errors for checkpoint storage operations.9 * domain errors for checkpoint storage operations.
10 *10 *
11 * @module CheckpointStore11 * @module CheckpointStore
12 */12 */
13import { ServiceMap } from "effect";13import { Context } from "effect";
14import type { Effect } from "effect";14import type { Effect } from "effect";
15 15
16import type { CheckpointStoreError } from "../Errors.ts";16import type { CheckpointStoreError } from "../Errors.ts";
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape { · 78 unmodified lines
95/**95/**
96 * CheckpointStore - Service tag for checkpoint persistence and restore operations.96 * CheckpointStore - Service tag for checkpoint persistence and restore operations.
97 */97 */
98export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(98export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
99 "t3/checkpointing/Services/CheckpointStore",99 "t3/checkpointing/Services/CheckpointStore",
100) {}100) {}
apps/server/src/checkpointing/Utils.ts+1−1
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts"; · 3 unmodified lines
4export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";4export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
5 5
6export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {6export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
7 return CheckpointRef.makeUnsafe(7 return CheckpointRef.make(
8 `${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,8 `${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
9 );9 );
10}10}
apps/server/src/cli-config.test.ts+223−13
@@ -9,6 +9,18 @@ import { deriveServerPaths } from "./config"; · 8 unmodified lines
9import { resolveServerConfig } from "./cli";9import { resolveServerConfig } from "./cli";
10 10
11it.layer(NodeServices.layer)("cli config resolution", (it) => {11it.layer(NodeServices.layer)("cli config resolution", (it) => {
12 const defaultObservabilityConfig = {
13 traceMinLevel: "Info",
14 traceTimingEnabled: true,
15 traceBatchWindowMs: 200,
16 traceMaxBytes: 10 * 1024 * 1024,
17 traceMaxFiles: 10,
18 otlpTracesUrl: undefined,
19 otlpMetricsUrl: undefined,
20 otlpExportIntervalMs: 10_000,
21 otlpServiceName: "t3-server",
22 } as const;
23
12 const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {24 const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
13 const fs = yield* FileSystem.FileSystem;25 const fs = yield* FileSystem.FileSystem;
14 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });26 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
@@ -28,9 +40,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 13 unmodified lines
28 port: Option.none(),40 port: Option.none(),
29 host: Option.none(),41 host: Option.none(),
30 baseDir: Option.none(),42 baseDir: Option.none(),
43 cwd: Option.none(),
31 devUrl: Option.none(),44 devUrl: Option.none(),
32 noBrowser: Option.none(),45 noBrowser: Option.none(),
33 authToken: Option.none(),
34 bootstrapFd: Option.none(),46 bootstrapFd: Option.none(),
35 autoBootstrapProjectFromCwd: Option.none(),47 autoBootstrapProjectFromCwd: Option.none(),
36 logWebSocketEvents: Option.none(),48 logWebSocketEvents: Option.none(),
@@ -49,7 +61,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 12 unmodified lines
49 T3CODE_HOME: baseDir,61 T3CODE_HOME: baseDir,
50 VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",62 VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
51 T3CODE_NO_BROWSER: "true",63 T3CODE_NO_BROWSER: "true",
52 T3CODE_AUTH_TOKEN: "env-token",
53 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",64 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
54 T3CODE_LOG_WS_EVENTS: "true",65 T3CODE_LOG_WS_EVENTS: "true",
55 },66 },
@@ -62,6 +73,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 6 unmodified lines
62 73
63 expect(resolved).toEqual({74 expect(resolved).toEqual({
64 logLevel: "Warn",75 logLevel: "Warn",
76 ...defaultObservabilityConfig,
65 mode: "desktop",77 mode: "desktop",
66 port: 4001,78 port: 4001,
67 cwd: process.cwd(),79 cwd: process.cwd(),
@@ -71,7 +83,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
71 staticDir: undefined,83 staticDir: undefined,
72 devUrl: new URL("http://127.0.0.1:5173"),84 devUrl: new URL("http://127.0.0.1:5173"),
73 noBrowser: true,85 noBrowser: true,
74 authToken: "env-token",86 startupPresentation: "browser",
87 desktopBootstrapToken: undefined,
75 autoBootstrapProjectFromCwd: false,88 autoBootstrapProjectFromCwd: false,
76 logWebSocketEvents: true,89 logWebSocketEvents: true,
77 });90 });
@@ -89,9 +102,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 11 unmodified lines
89 port: Option.some(8788),102 port: Option.some(8788),
90 host: Option.some("127.0.0.1"),103 host: Option.some("127.0.0.1"),
91 baseDir: Option.some(baseDir),104 baseDir: Option.some(baseDir),
105 cwd: Option.none(),
92 devUrl: Option.some(new URL("http://127.0.0.1:4173")),106 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
93 noBrowser: Option.some(true),107 noBrowser: Option.some(true),
94 authToken: Option.some("flag-token"),
95 bootstrapFd: Option.none(),108 bootstrapFd: Option.none(),
96 autoBootstrapProjectFromCwd: Option.some(true),109 autoBootstrapProjectFromCwd: Option.some(true),
97 logWebSocketEvents: Option.some(true),110 logWebSocketEvents: Option.some(true),
@@ -110,7 +123,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 12 unmodified lines
110 T3CODE_HOME: join(os.tmpdir(), "ignored-base"),123 T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
111 VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",124 VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
112 T3CODE_NO_BROWSER: "false",125 T3CODE_NO_BROWSER: "false",
113 T3CODE_AUTH_TOKEN: "ignored-token",
114 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",126 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
115 T3CODE_LOG_WS_EVENTS: "false",127 T3CODE_LOG_WS_EVENTS: "false",
116 },128 },
@@ -123,6 +135,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 6 unmodified lines
123 135
124 expect(resolved).toEqual({136 expect(resolved).toEqual({
125 logLevel: "Debug",137 logLevel: "Debug",
138 ...defaultObservabilityConfig,
126 mode: "web",139 mode: "web",
127 port: 8788,140 port: 8788,
128 cwd: process.cwd(),141 cwd: process.cwd(),
@@ -132,10 +145,74 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
132 staticDir: undefined,145 staticDir: undefined,
133 devUrl: new URL("http://127.0.0.1:4173"),146 devUrl: new URL("http://127.0.0.1:4173"),
134 noBrowser: true,147 noBrowser: true,
135 authToken: "flag-token",148 startupPresentation: "browser",
149 desktopBootstrapToken: undefined,
150 autoBootstrapProjectFromCwd: true,
151 logWebSocketEvents: true,
152 });
153 }),
154 );
155
156 it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
157 Effect.gen(function* () {
158 const { join } = yield* Path.Path;
159 const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
160 const fd = yield* openBootstrapFd({
161 noBrowser: true,
136 autoBootstrapProjectFromCwd: true,162 autoBootstrapProjectFromCwd: true,
137 logWebSocketEvents: true,163 logWebSocketEvents: true,
138 });164 });
165 const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
166
167 const resolved = yield* resolveServerConfig(
168 {
169 mode: Option.some("web"),
170 port: Option.some(8788),
171 host: Option.some("127.0.0.1"),
172 baseDir: Option.some(baseDir),
173 cwd: Option.none(),
174 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
175 noBrowser: Option.some(false),
176 bootstrapFd: Option.none(),
177 autoBootstrapProjectFromCwd: Option.some(false),
178 logWebSocketEvents: Option.some(false),
179 },
180 Option.none(),
181 ).pipe(
182 Effect.provide(
183 Layer.mergeAll(
184 ConfigProvider.layer(
185 ConfigProvider.fromEnv({
186 env: {
187 T3CODE_BOOTSTRAP_FD: String(fd),
188 T3CODE_NO_BROWSER: "true",
189 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
190 T3CODE_LOG_WS_EVENTS: "true",
191 },
192 }),
193 ),
194 NetService.layer,
195 ),
196 ),
197 );
198
199 expect(resolved).toEqual({
200 logLevel: "Info",
201 ...defaultObservabilityConfig,
202 mode: "web",
203 port: 8788,
204 cwd: process.cwd(),
205 baseDir,
206 ...derivedPaths,
207 host: "127.0.0.1",
208 staticDir: undefined,
209 devUrl: new URL("http://127.0.0.1:4173"),
210 noBrowser: false,
211 startupPresentation: "browser",
212 desktopBootstrapToken: undefined,
213 autoBootstrapProjectFromCwd: false,
214 logWebSocketEvents: false,
215 });
139 }),216 }),
140 );217 );
141 218
@@ -150,9 +227,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 8 unmodified lines
150 t3Home: baseDir,227 t3Home: baseDir,
151 devUrl: "http://127.0.0.1:5173",228 devUrl: "http://127.0.0.1:5173",
152 noBrowser: true,229 noBrowser: true,
153 authToken: "bootstrap-token",
154 autoBootstrapProjectFromCwd: false,230 autoBootstrapProjectFromCwd: false,
155 logWebSocketEvents: true,231 logWebSocketEvents: true,
232 otlpTracesUrl: "http://localhost:4318/v1/traces",
233 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
156 });234 });
157 const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));235 const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
158 236
@@ -162,9 +240,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
162 port: Option.none(),240 port: Option.none(),
163 host: Option.none(),241 host: Option.none(),
164 baseDir: Option.none(),242 baseDir: Option.none(),
243 cwd: Option.none(),
165 devUrl: Option.none(),244 devUrl: Option.none(),
166 noBrowser: Option.none(),245 noBrowser: Option.none(),
167 authToken: Option.none(),
168 bootstrapFd: Option.none(),246 bootstrapFd: Option.none(),
169 autoBootstrapProjectFromCwd: Option.none(),247 autoBootstrapProjectFromCwd: Option.none(),
170 logWebSocketEvents: Option.none(),248 logWebSocketEvents: Option.none(),
@@ -187,6 +265,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 16 unmodified lines
187 265
188 expect(resolved).toEqual({266 expect(resolved).toEqual({
189 logLevel: "Info",267 logLevel: "Info",
268 ...defaultObservabilityConfig,
269 otlpTracesUrl: "http://localhost:4318/v1/traces",
270 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
190 mode: "desktop",271 mode: "desktop",
191 port: 4888,272 port: 4888,
192 cwd: process.cwd(),273 cwd: process.cwd(),
@@ -196,7 +277,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
196 staticDir: undefined,277 staticDir: undefined,
197 devUrl: new URL("http://127.0.0.1:5173"),278 devUrl: new URL("http://127.0.0.1:5173"),
198 noBrowser: true,279 noBrowser: true,
199 authToken: "bootstrap-token",280 startupPresentation: "browser",
281 desktopBootstrapToken: undefined,
200 autoBootstrapProjectFromCwd: false,282 autoBootstrapProjectFromCwd: false,
201 logWebSocketEvents: true,283 logWebSocketEvents: true,
202 });284 });
@@ -209,6 +291,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 6 unmodified lines
209 const fs = yield* FileSystem.FileSystem;291 const fs = yield* FileSystem.FileSystem;
210 const path = yield* Path.Path;292 const path = yield* Path.Path;
211 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });293 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
294 const customCwd = path.join(baseDir, "nested", "project");
212 295
213 const resolved = yield* resolveServerConfig(296 const resolved = yield* resolveServerConfig(
214 {297 {
@@ -216,9 +299,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 1 unmodified line
216 port: Option.some(4888),299 port: Option.some(4888),
217 host: Option.none(),300 host: Option.none(),
218 baseDir: Option.some(baseDir),301 baseDir: Option.some(baseDir),
302 cwd: Option.some(customCwd),
219 devUrl: Option.some(new URL("http://127.0.0.1:5173")),303 devUrl: Option.some(new URL("http://127.0.0.1:5173")),
220 noBrowser: Option.none(),304 noBrowser: Option.none(),
221 authToken: Option.none(),
222 bootstrapFd: Option.none(),305 bootstrapFd: Option.none(),
223 autoBootstrapProjectFromCwd: Option.none(),306 autoBootstrapProjectFromCwd: Option.none(),
224 logWebSocketEvents: Option.none(),307 logWebSocketEvents: Option.none(),
@@ -234,6 +317,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 9 unmodified lines
234 );317 );
235 318
236 for (const directory of [319 for (const directory of [
320 customCwd,
237 resolved.stateDir,321 resolved.stateDir,
238 resolved.logsDir,322 resolved.logsDir,
239 resolved.providerLogsDir,323 resolved.providerLogsDir,
@@ -241,9 +325,11 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 1 unmodified line
241 resolved.attachmentsDir,325 resolved.attachmentsDir,
242 resolved.worktreesDir,326 resolved.worktreesDir,
243 path.dirname(resolved.serverLogPath),327 path.dirname(resolved.serverLogPath),
328 path.dirname(resolved.serverTracePath),
244 ]) {329 ]) {
245 expect(yield* fs.exists(directory)).toBe(true);330 expect(yield* fs.exists(directory)).toBe(true);
246 }331 }
332 expect(resolved.cwd).toBe(path.resolve(customCwd));
247 }),333 }),
248 );334 );
249 335
@@ -258,7 +344,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 8 unmodified lines
258 t3Home: "/tmp/t3-bootstrap-home",344 t3Home: "/tmp/t3-bootstrap-home",
259 devUrl: "http://127.0.0.1:5173",345 devUrl: "http://127.0.0.1:5173",
260 noBrowser: false,346 noBrowser: false,
261 authToken: "bootstrap-token",
262 autoBootstrapProjectFromCwd: false,347 autoBootstrapProjectFromCwd: false,
263 logWebSocketEvents: false,348 logWebSocketEvents: false,
264 });349 });
@@ -270,9 +355,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 5 unmodified lines
270 port: Option.some(8788),355 port: Option.some(8788),
271 host: Option.some("127.0.0.1"),356 host: Option.some("127.0.0.1"),
272 baseDir: Option.none(),357 baseDir: Option.none(),
358 cwd: Option.none(),
273 devUrl: Option.some(new URL("http://127.0.0.1:4173")),359 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
274 noBrowser: Option.none(),360 noBrowser: Option.none(),
275 authToken: Option.some("flag-token"),
276 bootstrapFd: Option.none(),361 bootstrapFd: Option.none(),
277 autoBootstrapProjectFromCwd: Option.none(),362 autoBootstrapProjectFromCwd: Option.none(),
278 logWebSocketEvents: Option.none(),363 logWebSocketEvents: Option.none(),
@@ -300,6 +385,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 21 unmodified lines
300 385
301 expect(resolved).toEqual({386 expect(resolved).toEqual({
302 logLevel: "Debug",387 logLevel: "Debug",
388 ...defaultObservabilityConfig,
303 mode: "web",389 mode: "web",
304 port: 8788,390 port: 8788,
305 cwd: process.cwd(),391 cwd: process.cwd(),
@@ -309,10 +395,134 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
309 staticDir: undefined,395 staticDir: undefined,
310 devUrl: new URL("http://127.0.0.1:4173"),396 devUrl: new URL("http://127.0.0.1:4173"),
311 noBrowser: true,397 noBrowser: true,
312 authToken: "flag-token",398 startupPresentation: "browser",
399 desktopBootstrapToken: undefined,
313 autoBootstrapProjectFromCwd: true,400 autoBootstrapProjectFromCwd: true,
314 logWebSocketEvents: true,401 logWebSocketEvents: true,
315 });402 });
316 }),403 }),
317 );404 );
405
406 it.effect("falls back to persisted observability settings when env vars are absent", () =>
407 Effect.gen(function* () {
408 const fs = yield* FileSystem.FileSystem;
409 const path = yield* Path.Path;
410 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
411 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
412 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
413 yield* fs.writeFileString(
414 derivedPaths.settingsPath,
415 `${JSON.stringify({
416 observability: {
417 otlpTracesUrl: "http://localhost:4318/v1/traces",
418 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
419 },
420 })}\n`,
421 );
422
423 const resolved = yield* resolveServerConfig(
424 {
425 mode: Option.some("desktop"),
426 port: Option.some(4888),
427 host: Option.none(),
428 baseDir: Option.some(baseDir),
429 cwd: Option.none(),
430 devUrl: Option.none(),
431 noBrowser: Option.none(),
432 bootstrapFd: Option.none(),
433 autoBootstrapProjectFromCwd: Option.none(),
434 logWebSocketEvents: Option.none(),
435 },
436 Option.none(),
437 ).pipe(
438 Effect.provide(
439 Layer.mergeAll(
440 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
441 NetService.layer,
442 ),
443 ),
444 );
445
446 expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
447 expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics");
448 expect(resolved).toEqual({
449 logLevel: "Info",
450 ...defaultObservabilityConfig,
451 otlpTracesUrl: "http://localhost:4318/v1/traces",
452 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
453 mode: "desktop",
454 port: 4888,
455 cwd: process.cwd(),
456 baseDir,
457 ...derivedPaths,
458 host: "127.0.0.1",
459 staticDir: resolved.staticDir,
460 devUrl: undefined,
461 noBrowser: true,
462 startupPresentation: "browser",
463 desktopBootstrapToken: undefined,
464 autoBootstrapProjectFromCwd: false,
465 logWebSocketEvents: false,
466 });
467 }),
468 );
469
470 it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
471 Effect.gen(function* () {
472 const { join } = yield* Path.Path;
473 const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base");
474 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
475
476 const resolved = yield* resolveServerConfig(
477 {
478 mode: Option.some("web"),
479 port: Option.some(3773),
480 host: Option.none(),
481 baseDir: Option.some(baseDir),
482 cwd: Option.none(),
483 devUrl: Option.none(),
484 noBrowser: Option.none(),
485 bootstrapFd: Option.none(),
486 autoBootstrapProjectFromCwd: Option.none(),
487 logWebSocketEvents: Option.none(),
488 },
489 Option.none(),
490 {
491 startupPresentation: "headless",
492 },
493 ).pipe(
494 Effect.provide(
495 Layer.mergeAll(
496 ConfigProvider.layer(
497 ConfigProvider.fromEnv({
498 env: {
499 T3CODE_NO_BROWSER: "false",
500 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
501 },
502 }),
503 ),
504 NetService.layer,
505 ),
506 ),
507 );
508
509 expect(resolved).toEqual({
510 logLevel: "Info",
511 ...defaultObservabilityConfig,
512 mode: "web",
513 port: 3773,
514 cwd: process.cwd(),
515 baseDir,
516 ...derivedPaths,
517 host: undefined,
518 staticDir: resolved.staticDir,
519 devUrl: undefined,
520 noBrowser: true,
521 startupPresentation: "headless",
522 desktopBootstrapToken: undefined,
523 autoBootstrapProjectFromCwd: false,
524 logWebSocketEvents: false,
525 });
526 }),
527 );
318});528});
apps/server/src/cli.test.ts+326−7
@@ -1,28 +1,164 @@
1import * as NodeHttp from "node:http";
2import { mkdtempSync } from "node:fs";
3import { tmpdir } from "node:os";
4import { join } from "node:path";
5
6import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
1import * as NodeServices from "@effect/platform-node/NodeServices";7import * as NodeServices from "@effect/platform-node/NodeServices";
2import { NetService } from "@t3tools/shared/Net";8import { NetService } from "@t3tools/shared/Net";
3import { assert, it } from "@effect/vitest";9import { assert, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";10import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";11import * as Layer from "effect/Layer";
12import * as HttpRouter from "effect/unstable/http/HttpRouter";
13import * as HttpServer from "effect/unstable/http/HttpServer";
6import * as CliError from "effect/unstable/cli/CliError";14import * as CliError from "effect/unstable/cli/CliError";
15import * as TestConsole from "effect/testing/TestConsole";
7import { Command } from "effect/unstable/cli";16import { Command } from "effect/unstable/cli";
8 17
9import { cli } from "./cli.ts";18import { cli } from "./cli.ts";
19import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
20import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
21import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
22import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
23import {
24 orchestrationDispatchRouteLayer,
25 orchestrationSnapshotRouteLayer,
26} from "./orchestration/http.ts";
27import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
28import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
29import {
30 makePersistedServerRuntimeState,
31 persistServerRuntimeState,
32} from "./serverRuntimeState.ts";
33import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
34import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
35import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
10 36
11const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);37const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
12 38
39const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
40const runCliWithRuntime = (args: ReadonlyArray<string>) =>
41 runCli(args).pipe(Effect.provide(CliRuntimeLayer));
42
43const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
44 Effect.gen(function* () {
45 const result = yield* effect;
46 const output =
47 (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
48 "";
49 return { result, output };
50 }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
51
52const makeCliTestServerConfig = (baseDir: string) =>
53 Effect.gen(function* () {
54 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
55 return {
56 logLevel: "Info",
57 traceMinLevel: "Info",
58 traceTimingEnabled: true,
59 traceBatchWindowMs: 200,
60 traceMaxBytes: 10 * 1024 * 1024,
61 traceMaxFiles: 10,
62 otlpTracesUrl: undefined,
63 otlpMetricsUrl: undefined,
64 otlpExportIntervalMs: 10_000,
65 otlpServiceName: "t3-server",
66 mode: "web",
67 port: 0,
68 host: "127.0.0.1",
69 cwd: process.cwd(),
70 baseDir,
71 ...derivedPaths,
72 staticDir: undefined,
73 devUrl: undefined,
74 noBrowser: true,
75 startupPresentation: "browser",
76 desktopBootstrapToken: undefined,
77 autoBootstrapProjectFromCwd: false,
78 logWebSocketEvents: false,
79 } satisfies ServerConfigShape;
80 });
81
82const makeProjectPersistenceLayer = (config: ServerConfigShape) =>
83 Layer.mergeAll(
84 OrchestrationLayerLive.pipe(
85 Layer.provideMerge(RepositoryIdentityResolverLive),
86 Layer.provideMerge(SqlitePersistenceLayerLive),
87 ),
88 WorkspacePathsLive,
89 ).pipe(
90 Layer.provideMerge(NodeServices.layer),
91 Layer.provide(Layer.succeed(ServerConfig, config)),
92 );
93
94const readPersistedSnapshot = (baseDir: string) =>
95 Effect.gen(function* () {
96 const config = yield* makeCliTestServerConfig(baseDir);
97 return yield* Effect.gen(function* () {
98 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
99 return yield* projectionSnapshotQuery.getSnapshot();
100 }).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
101 });
102
103const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
104 Effect.gen(function* () {
105 const config = yield* makeCliTestServerConfig(baseDir);
106 const routesLayer = Layer.mergeAll(
107 orchestrationSnapshotRouteLayer,
108 orchestrationDispatchRouteLayer,
109 );
110 const appLayer = HttpRouter.serve(routesLayer, {
111 disableListenLog: true,
112 disableLogger: true,
113 }).pipe(
114 Layer.provideMerge(
115 ServerAuthLive.pipe(
116 Layer.provideMerge(SqlitePersistenceLayerLive),
117 Layer.provide(ServerSecretStoreLive),
118 ),
119 ),
120 Layer.provideMerge(makeProjectPersistenceLayer(config)),
121 Layer.provideMerge(
122 NodeHttpServer.layer(NodeHttp.createServer, {
123 host: "127.0.0.1",
124 port: 0,
125 }),
126 ),
127 Layer.provideMerge(NodeServices.layer),
128 Layer.provide(Layer.succeed(ServerConfig, config)),
129 );
130
131 return yield* Effect.scoped(
132 Effect.gen(function* () {
133 const server = yield* HttpServer.HttpServer;
134 const address = server.address;
135 if (typeof address === "string" || !("port" in address)) {
136 assert.fail(`Expected TCP address, got ${address}`);
137 }
138 yield* persistServerRuntimeState({
139 path: config.serverRuntimeStatePath,
140 state: makePersistedServerRuntimeState({
141 config,
142 port: address.port,
143 }),
144 });
145 return yield* run();
146 }).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
147 );
148 });
149
13it.layer(NodeServices.layer)("cli log-level parsing", (it) => {150it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
14 it.effect("accepts the built-in lowercase log-level flag values", () =>151 it.effect("accepts the built-in lowercase log-level flag values", () =>
15 Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(152 runCliWithRuntime(["--log-level", "debug", "--version"]),
16 Effect.provide(CliRuntimeLayer),153 );
17 ),154
155 it.effect("accepts canonical --no-<flag> boolean negation", () =>
156 runCliWithRuntime(["--no-log-websocket-events", "--version"]),
18 );157 );
19 158
20 it.effect("rejects invalid log-level casing before launching the server", () =>159 it.effect("rejects invalid log-level casing before launching the server", () =>
21 Effect.gen(function* () {160 Effect.gen(function* () {
22 const error = yield* Command.runWith(cli, { version: "0.0.0" })([161 const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
23 "--log-level",
24 "Debug",
25 ]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
26 162
27 if (!CliError.isCliError(error)) {163 if (!CliError.isCliError(error)) {
28 assert.fail(`Expected CliError, got ${String(error)}`);164 assert.fail(`Expected CliError, got ${String(error)}`);
@@ -34,4 +170,187 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => { · 5 unmodified lines
34 assert.equal(error.value, "Debug");170 assert.equal(error.value, "Debug");
35 }),171 }),
36 );172 );
173
174 it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
175 Effect.gen(function* () {
176 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
177
178 const createdOutput = yield* captureStdout(
179 runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
180 );
181 const created = JSON.parse(createdOutput.output) as {
182 readonly id: string;
183 readonly credential: string;
184 };
185 const listedOutput = yield* captureStdout(
186 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
187 );
188 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
189 readonly id: string;
190 readonly credential?: string;
191 }>;
192
193 assert.equal(typeof created.id, "string");
194 assert.equal(typeof created.credential, "string");
195 assert.equal(created.credential.length > 0, true);
196 assert.equal(listed.length, 1);
197 assert.equal(listed[0]?.id, created.id);
198 assert.equal("credential" in (listed[0] ?? {}), false);
199 }),
200 );
201
202 it.effect("executes auth session subcommands and redacts secrets from list output", () =>
203 Effect.gen(function* () {
204 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
205
206 const issuedOutput = yield* captureStdout(
207 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
208 );
209 const issued = JSON.parse(issuedOutput.output) as {
210 readonly sessionId: string;
211 readonly token: string;
212 readonly role: string;
213 };
214 const listedOutput = yield* captureStdout(
215 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
216 );
217 const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
218 readonly sessionId: string;
219 readonly token?: string;
220 readonly role: string;
221 }>;
222
223 assert.equal(typeof issued.sessionId, "string");
224 assert.equal(typeof issued.token, "string");
225 assert.equal(issued.role, "owner");
226 assert.equal(listed.length, 1);
227 assert.equal(listed[0]?.sessionId, issued.sessionId);
228 assert.equal(listed[0]?.role, "owner");
229 assert.equal("token" in (listed[0] ?? {}), false);
230 }),
231 );
232
233 it.effect("rejects invalid ttl values before running auth commands", () =>
234 Effect.gen(function* () {
235 const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
236 Effect.flip,
237 );
238
239 if (!CliError.isCliError(error)) {
240 assert.fail(`Expected CliError, got ${String(error)}`);
241 }
242 if (error._tag !== "ShowHelp") {
243 assert.fail(`Expected ShowHelp, got ${error._tag}`);
244 }
245 assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
246 const ttlError = error.errors[0] as CliError.CliError | undefined;
247 if (!ttlError || ttlError._tag !== "InvalidValue") {
248 assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
249 }
250 assert.equal(ttlError.option, "ttl");
251 assert.equal(ttlError.value, "soon");
252 assert.isTrue(ttlError.message.includes("Invalid duration"));
253 assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
254 }),
255 );
256
257 it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
258 Effect.gen(function* () {
259 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
260 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
261
262 yield* runCliWithRuntime([
263 "project",
264 "add",
265 workspaceRoot,
266 "--title",
267 "Alpha",
268 "--base-dir",
269 baseDir,
270 ]);
271 const afterAdd = yield* readPersistedSnapshot(baseDir);
272 const addedProject = afterAdd.projects.find(
273 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
274 );
275 assert.isTrue(addedProject !== undefined);
276 assert.equal(addedProject?.title, "Alpha");
277
278 yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
279 const afterRename = yield* readPersistedSnapshot(baseDir);
280 const renamedProject = afterRename.projects.find(
281 (project) => project.id === addedProject?.id,
282 );
283 assert.equal(renamedProject?.title, "Beta");
284 assert.equal(renamedProject?.deletedAt, null);
285
286 yield* runCliWithRuntime([
287 "project",
288 "remove",
289 addedProject?.id ?? "",
290 "--base-dir",
291 baseDir,
292 ]);
293 const afterRemove = yield* readPersistedSnapshot(baseDir);
294 const removedProject = afterRemove.projects.find(
295 (project) => project.id === addedProject?.id,
296 );
297 assert.isTrue((removedProject?.deletedAt ?? null) !== null);
298 }),
299 );
300
301 it.effect("routes project commands through a running server when runtime state is present", () =>
302 Effect.gen(function* () {
303 const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-"));
304 const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-"));
305
306 yield* withLiveProjectCliServer(baseDir, () =>
307 Effect.gen(function* () {
308 yield* runCliWithRuntime([
309 "project",
310 "add",
311 workspaceRoot,
312 "--title",
313 "Live Project",
314 "--base-dir",
315 baseDir,
316 ]);
317 const orchestrationEngine = yield* OrchestrationEngineService;
318 const readModel = yield* orchestrationEngine.getReadModel();
319 const addedProject = readModel.projects.find(
320 (project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
321 );
322 assert.isTrue(addedProject !== undefined);
323 assert.equal(addedProject?.title, "Live Project");
324 }),
325 );
326 }),
327 );
328
329 it.effect("rejects dev-url on project commands", () =>
330 Effect.gen(function* () {
331 const workspaceRoot = mkdtempSync(
332 join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
333 );
334 const error = yield* runCliWithRuntime([
335 "project",
336 "add",
337 workspaceRoot,
338 "--dev-url",
339 "http://127.0.0.1:5173",
340 ]).pipe(Effect.flip);
341
342 if (!CliError.isCliError(error)) {
343 assert.fail(`Expected CliError, got ${String(error)}`);
344 }
345 if (error._tag !== "ShowHelp") {
346 assert.fail(`Expected ShowHelp, got ${error._tag}`);
347 }
348 assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
349 const optionError = error.errors[0] as CliError.CliError | undefined;
350 if (!optionError || optionError._tag !== "UnrecognizedOption") {
351 assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
352 }
353 assert.equal(optionError.option, "--dev-url");
354 }),
355 );
37});356});
apps/server/src/cli.ts+916−76
@@ -1,6 +1,35 @@
1import { NetService } from "@t3tools/shared/Net";1import { NetService } from "@t3tools/shared/Net";
2import { Config, Effect, LogLevel, Option, Schema } from "effect";2import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
3import { Command, Flag, GlobalFlag } from "effect/unstable/cli";3import {
4 AuthSessionId,
5 CommandId,
6 OrchestrationReadModel,
7 ProjectId,
8 type ClientOrchestrationCommand,
9} from "@t3tools/contracts";
10import {
11 Config,
12 Console,
13 Duration,
14 Effect,
15 Exit,
16 FileSystem,
17 Layer,
18 LogLevel,
19 Option,
20 Path,
21 References,
22 Schema,
23 SchemaIssue,
24 SchemaTransformation,
25} from "effect";
26import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
27import {
28 FetchHttpClient,
29 HttpClient,
30 HttpClientRequest,
31 HttpClientResponse,
32} from "effect/unstable/http";
4 33
5import {34import {
6 DEFAULT_PORT,35 DEFAULT_PORT,
@@ -10,10 +39,31 @@ import { · 3 unmodified lines
10 ServerConfig,39 ServerConfig,
11 RuntimeMode,40 RuntimeMode,
12 type ServerConfigShape,41 type ServerConfigShape,
42 type StartupPresentation,
13} from "./config";43} from "./config";
14import { readBootstrapEnvelope } from "./bootstrap";44import { readBootstrapEnvelope } from "./bootstrap";
15import { resolveBaseDir } from "./os-jank";45import { expandHomePath, resolveBaseDir } from "./os-jank";
16import { runServer } from "./server";46import { runServer } from "./server";
47import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
48import {
49 formatIssuedPairingCredential,
50 formatIssuedSession,
51 formatPairingCredentialList,
52 formatSessionList,
53} from "./cliAuthFormat";
54import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
55import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
56import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
57import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
58import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
59import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
60import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
61import {
62 clearPersistedServerRuntimeState,
63 readPersistedServerRuntimeState,
64} from "./serverRuntimeState";
65import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
66import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
17 67
18const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));68const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
19 69
@@ -24,9 +74,11 @@ const BootstrapEnvelopeSchema = Schema.Struct({ · 4 unmodified lines
24 t3Home: Schema.optional(Schema.String),74 t3Home: Schema.optional(Schema.String),
25 devUrl: Schema.optional(Schema.URLFromString),75 devUrl: Schema.optional(Schema.URLFromString),
26 noBrowser: Schema.optional(Schema.Boolean),76 noBrowser: Schema.optional(Schema.Boolean),
27 authToken: Schema.optional(Schema.String),77 desktopBootstrapToken: Schema.optional(Schema.String),
28 autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),78 autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
29 logWebSocketEvents: Schema.optional(Schema.Boolean),79 logWebSocketEvents: Schema.optional(Schema.Boolean),
80 otlpTracesUrl: Schema.optional(Schema.String),
81 otlpMetricsUrl: Schema.optional(Schema.String),
30});82});
31 83
32const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(84const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
@@ -55,11 +107,6 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe( · 22 unmodified lines
55 Flag.withDescription("Disable automatic browser opening."),107 Flag.withDescription("Disable automatic browser opening."),
56 Flag.optional,108 Flag.optional,
57);109);
58const authTokenFlag = Flag.string("auth-token").pipe(
59 Flag.withDescription("Auth token required for WebSocket connections."),
60 Flag.withAlias("token"),
61 Flag.optional,
62);
63const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(110const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
64 Flag.withSchema(Schema.Int),111 Flag.withSchema(Schema.Int),
65 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),112 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
@@ -81,6 +128,27 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe( · 15 unmodified lines
81 128
82const EnvServerConfig = Config.all({129const EnvServerConfig = Config.all({
83 logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),130 logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
131 traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
132 traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
133 traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
134 Config.option,
135 Config.map(Option.getOrUndefined),
136 ),
137 traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
138 traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
139 traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
140 otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
141 Config.option,
142 Config.map(Option.getOrUndefined),
143 ),
144 otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
145 Config.option,
146 Config.map(Option.getOrUndefined),
147 ),
148 otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
149 Config.withDefault(10_000),
150 ),
151 otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
84 mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(152 mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
85 Config.option,153 Config.option,
86 Config.map(Option.getOrUndefined),154 Config.map(Option.getOrUndefined),
@@ -93,10 +161,6 @@ const EnvServerConfig = Config.all({ · 6 unmodified lines
93 Config.option,161 Config.option,
94 Config.map(Option.getOrUndefined),162 Config.map(Option.getOrUndefined),
95 ),163 ),
96 authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
97 Config.option,
98 Config.map(Option.getOrUndefined),
99 ),
100 bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(164 bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
101 Config.option,165 Config.option,
102 Config.map(Option.getOrUndefined),166 Config.map(Option.getOrUndefined),
@@ -116,48 +180,80 @@ interface CliServerFlags { · 13 unmodified lines
116 readonly port: Option.Option<number>;180 readonly port: Option.Option<number>;
117 readonly host: Option.Option<string>;181 readonly host: Option.Option<string>;
118 readonly baseDir: Option.Option<string>;182 readonly baseDir: Option.Option<string>;
183 readonly cwd: Option.Option<string>;
119 readonly devUrl: Option.Option<URL>;184 readonly devUrl: Option.Option<URL>;
120 readonly noBrowser: Option.Option<boolean>;185 readonly noBrowser: Option.Option<boolean>;
121 readonly authToken: Option.Option<string>;
122 readonly bootstrapFd: Option.Option<number>;186 readonly bootstrapFd: Option.Option<number>;
123 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;187 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
124 readonly logWebSocketEvents: Option.Option<boolean>;188 readonly logWebSocketEvents: Option.Option<boolean>;
125}189}
126 190
127const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>191interface CliAuthLocationFlags {
128 Option.getOrElse(Option.filter(flag, Boolean), () => envValue);192 readonly baseDir: Option.Option<string>;
193 readonly devUrl?: Option.Option<URL>;
194}
129 195
130const resolveOptionPrecedence = <Value>(196const resolveOptionPrecedence = <Value>(
131 ...values: ReadonlyArray<Option.Option<Value>>197 ...values: ReadonlyArray<Option.Option<Value>>
132): Option.Option<Value> => Option.firstSomeOf(values);198): Option.Option<Value> => Option.firstSomeOf(values);
133 199
200const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
201 const fs = yield* FileSystem.FileSystem;
202 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
203 if (!exists) {
204 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
205 }
206
207 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
208 return parsePersistedServerObservabilitySettings(raw);
209});
210
134export const resolveServerConfig = (211export const resolveServerConfig = (
135 flags: CliServerFlags,212 flags: CliServerFlags,
136 cliLogLevel: Option.Option<LogLevel.LogLevel>,213 cliLogLevel: Option.Option<LogLevel.LogLevel>,
214 options?: {
215 readonly startupPresentation?: StartupPresentation;
216 readonly forceAutoBootstrapProjectFromCwd?: boolean;
217 },
137) =>218) =>
138 Effect.gen(function* () {219 Effect.gen(function* () {
139 const { findAvailablePort } = yield* NetService;220 const { findAvailablePort } = yield* NetService;
221 const path = yield* Path.Path;
222 const fs = yield* FileSystem.FileSystem;
140 const env = yield* EnvServerConfig;223 const env = yield* EnvServerConfig;
141 const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;224 const normalizedFlags = {
225 mode: flags.mode ?? Option.none(),
226 port: flags.port ?? Option.none(),
227 host: flags.host ?? Option.none(),
228 baseDir: flags.baseDir ?? Option.none(),
229 cwd: flags.cwd ?? Option.none(),
230 devUrl: flags.devUrl ?? Option.none(),
231 noBrowser: flags.noBrowser ?? Option.none(),
232 bootstrapFd: flags.bootstrapFd ?? Option.none(),
233 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
234 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
235 } satisfies CliServerFlags;
236 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
142 const bootstrapEnvelope =237 const bootstrapEnvelope =
143 bootstrapFd !== undefined238 bootstrapFd !== undefined
144 ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)239 ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
145 : Option.none();240 : Option.none();
241 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
146 242
147 const mode: RuntimeMode = Option.getOrElse(243 const mode: RuntimeMode = Option.getOrElse(
148 resolveOptionPrecedence(244 resolveOptionPrecedence(
149 flags.mode,245 normalizedFlags.mode,
150 Option.fromUndefinedOr(env.mode),246 Option.fromUndefinedOr(env.mode),
151 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),247 Option.fromUndefinedOr(bootstrap?.mode),
152 ),248 ),
153 () => "web",249 () => "web",
154 );250 );
155 251
156 const port = yield* Option.match(252 const port = yield* Option.match(
157 resolveOptionPrecedence(253 resolveOptionPrecedence(
158 flags.port,254 normalizedFlags.port,
159 Option.fromUndefinedOr(env.port),255 Option.fromUndefinedOr(env.port),
160 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),256 Option.fromUndefinedOr(bootstrap?.port),
161 ),257 ),
162 {258 {
163 onSome: (value) => Effect.succeed(value),259 onSome: (value) => Effect.succeed(value),
@@ -171,76 +267,67 @@ export const resolveServerConfig = ( · 7 unmodified lines
171 );267 );
172 const devUrl = Option.getOrElse(268 const devUrl = Option.getOrElse(
173 resolveOptionPrecedence(269 resolveOptionPrecedence(
174 flags.devUrl,270 normalizedFlags.devUrl,
175 Option.fromUndefinedOr(env.devUrl),271 Option.fromUndefinedOr(env.devUrl),
176 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),272 Option.fromUndefinedOr(bootstrap?.devUrl),
177 ),273 ),
178 () => undefined,274 () => undefined,
179 );275 );
180 const baseDir = yield* resolveBaseDir(276 const baseDir = yield* resolveBaseDir(
181 Option.getOrUndefined(277 Option.getOrUndefined(
182 resolveOptionPrecedence(278 resolveOptionPrecedence(
183 flags.baseDir,279 normalizedFlags.baseDir,
184 Option.fromUndefinedOr(env.t3Home),280 Option.fromUndefinedOr(env.t3Home),
185 Option.flatMap(bootstrapEnvelope, (bootstrap) =>281 Option.fromUndefinedOr(bootstrap?.t3Home),
186 Option.fromUndefinedOr(bootstrap.t3Home),
187 ),
188 ),282 ),
189 ),283 ),
190 );284 );
285 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
286 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
287 yield* fs.makeDirectory(cwd, { recursive: true });
191 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);288 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
192 yield* ensureServerDirectories(derivedPaths);289 yield* ensureServerDirectories(derivedPaths);
193 const noBrowser = resolveBooleanFlag(290 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
194 flags.noBrowser,291 derivedPaths.settingsPath,
195 Option.getOrElse(
196 resolveOptionPrecedence(
197 Option.fromUndefinedOr(env.noBrowser),
198 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
199 Option.fromUndefinedOr(bootstrap.noBrowser),
200 ),
201 ),
202 () => mode === "desktop",
203 ),
204 );292 );
205 const authToken = Option.getOrUndefined(293 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
294 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
295 const startupPresentation = options?.startupPresentation ?? "browser";
296 const isHeadlessStartup = startupPresentation === "headless";
297 const noBrowser = Option.getOrElse(
206 resolveOptionPrecedence(298 resolveOptionPrecedence(
207 flags.authToken,299 isHeadlessStartup ? Option.some(true) : Option.none(),
208 Option.fromUndefinedOr(env.authToken),300 normalizedFlags.noBrowser,
209 Option.flatMap(bootstrapEnvelope, (bootstrap) =>301 Option.fromUndefinedOr(env.noBrowser),
210 Option.fromUndefinedOr(bootstrap.authToken),302 Option.fromUndefinedOr(bootstrap?.noBrowser),
211 ),
212 ),303 ),
304 () => mode === "desktop",
213 );305 );
214 const autoBootstrapProjectFromCwd = resolveBooleanFlag(306 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
215 flags.autoBootstrapProjectFromCwd,307 const autoBootstrapProjectFromCwd = Option.getOrElse(
216 Option.getOrElse(308 resolveOptionPrecedence(
217 resolveOptionPrecedence(309 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
218 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),310 isHeadlessStartup ? Option.some(false) : Option.none(),
219 Option.flatMap(bootstrapEnvelope, (bootstrap) =>311 normalizedFlags.autoBootstrapProjectFromCwd,
220 Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),312 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
221 ),313 Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
222 ),
223 () => mode === "web",
224 ),314 ),
315 () => mode === "web",
225 );316 );
226 const logWebSocketEvents = resolveBooleanFlag(317 const logWebSocketEvents = Option.getOrElse(
227 flags.logWebSocketEvents,318 resolveOptionPrecedence(
228 Option.getOrElse(319 normalizedFlags.logWebSocketEvents,
229 resolveOptionPrecedence(320 Option.fromUndefinedOr(env.logWebSocketEvents),
230 Option.fromUndefinedOr(env.logWebSocketEvents),321 Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
231 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
232 Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
233 ),
234 ),
235 () => Boolean(devUrl),
236 ),322 ),
323 () => Boolean(devUrl),
237 );324 );
238 const staticDir = devUrl ? undefined : yield* resolveStaticDir();325 const staticDir = devUrl ? undefined : yield* resolveStaticDir();
239 const host = Option.getOrElse(326 const host = Option.getOrElse(
240 resolveOptionPrecedence(327 resolveOptionPrecedence(
241 flags.host,328 normalizedFlags.host,
242 Option.fromUndefinedOr(env.host),329 Option.fromUndefinedOr(env.host),
243 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),330 Option.fromUndefinedOr(bootstrap?.host),
244 ),331 ),
245 () => (mode === "desktop" ? "127.0.0.1" : undefined),332 () => (mode === "desktop" ? "127.0.0.1" : undefined),
246 );333 );
@@ -248,16 +335,33 @@ export const resolveServerConfig = ( · 1 unmodified line
248 335
249 const config: ServerConfigShape = {336 const config: ServerConfigShape = {
250 logLevel,337 logLevel,
338 traceMinLevel: env.traceMinLevel,
339 traceTimingEnabled: env.traceTimingEnabled,
340 traceBatchWindowMs: env.traceBatchWindowMs,
341 traceMaxBytes: env.traceMaxBytes,
342 traceMaxFiles: env.traceMaxFiles,
343 otlpTracesUrl:
344 env.otlpTracesUrl ??
345 bootstrap?.otlpTracesUrl ??
346 persistedObservabilitySettings.otlpTracesUrl,
347 otlpMetricsUrl:
348 env.otlpMetricsUrl ??
349 bootstrap?.otlpMetricsUrl ??
350 persistedObservabilitySettings.otlpMetricsUrl,
351 otlpExportIntervalMs: env.otlpExportIntervalMs,
352 otlpServiceName: env.otlpServiceName,
251 mode,353 mode,
252 port,354 port,
253 cwd: process.cwd(),355 cwd,
254 baseDir,356 baseDir,
255 ...derivedPaths,357 ...derivedPaths,
358 serverTracePath,
256 host,359 host,
257 staticDir,360 staticDir,
258 devUrl,361 devUrl,
259 noBrowser,362 noBrowser,
260 authToken,363 startupPresentation,
364 desktopBootstrapToken,
261 autoBootstrapProjectFromCwd,365 autoBootstrapProjectFromCwd,
262 logWebSocketEvents,366 logWebSocketEvents,
263 };367 };
@@ -265,28 +369,764 @@ export const resolveServerConfig = ( · 1 unmodified line
265 return config;369 return config;
266 });370 });
267 371
268const commandFlags = {372const resolveCliAuthConfig = (
373 flags: CliAuthLocationFlags,
374 cliLogLevel: Option.Option<LogLevel.LogLevel>,
375) =>
376 resolveServerConfig(
377 {
378 mode: Option.none(),
379 port: Option.none(),
380 host: Option.none(),
381 baseDir: flags.baseDir,
382 cwd: Option.none(),
383 devUrl: flags.devUrl ?? Option.none(),
384 noBrowser: Option.none(),
385 bootstrapFd: Option.none(),
386 autoBootstrapProjectFromCwd: Option.none(),
387 logWebSocketEvents: Option.none(),
388 },
389 cliLogLevel,
390 );
391
392const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
393
394const parseDurationInput = (value: string): Duration.Duration | null => {
395 const trimmed = value.trim();
396 if (trimmed.length === 0) return null;
397
398 const shorthand = DurationShorthandPattern.exec(trimmed);
399 const normalizedInput = shorthand?.groups
400 ? (() => {
401 const amountText = shorthand.groups.value;
402 const unitText = shorthand.groups.unit;
403 if (typeof amountText !== "string" || typeof unitText !== "string") {
404 return null;
405 }
406
407 const amount = Number.parseInt(amountText, 10);
408 if (!Number.isFinite(amount)) return null;
409
410 switch (unitText.toLowerCase()) {
411 case "ms":
412 return `${amount} millis`;
413 case "s":
414 return `${amount} seconds`;
415 case "m":
416 return `${amount} minutes`;
417 case "h":
418 return `${amount} hours`;
419 case "d":
420 return `${amount} days`;
421 case "w":
422 return `${amount} weeks`;
423 default:
424 return null;
425 }
426 })()
427 : (trimmed as Duration.Input);
428
429 if (normalizedInput === null) return null;
430
431 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
432 return Option.isSome(decoded) ? decoded.value : null;
433};
434
435const DurationFromString = Schema.String.pipe(
436 Schema.decodeTo(
437 Schema.Duration,
438 SchemaTransformation.transformOrFail({
439 decode: (value) => {
440 const duration = parseDurationInput(value);
441 if (duration !== null) {
442 return Effect.succeed(duration);
443 }
444 return Effect.fail(
445 new SchemaIssue.InvalidValue(Option.some(value), {
446 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
447 }),
448 );
449 },
450 encode: (duration) => Effect.succeed(Duration.format(duration)),
451 }),
452 ),
453);
454
455const runWithAuthControlPlane = <A, E>(
456 flags: CliAuthLocationFlags,
457 run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,
458 options?: {
459 readonly quietLogs?: boolean;
460 },
461) =>
462 Effect.gen(function* () {
463 const logLevel = yield* GlobalFlag.LogLevel;
464 const config = yield* resolveCliAuthConfig(flags, logLevel);
465 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
466 return yield* Effect.gen(function* () {
467 const authControlPlane = yield* AuthControlPlane;
468 return yield* run(authControlPlane);
469 }).pipe(
470 Effect.provide(
471 Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe(
472 Layer.provide(Layer.succeed(ServerConfig, config)),
473 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
474 ),
475 ),
476 );
477 });
478
479type ProjectMutationTarget = {
480 readonly id: ProjectId;
481 readonly title: string;
482 readonly workspaceRoot: string;
483};
484
485type ProjectCommandExecutionMode = "live" | "offline";
486type ProjectCliDispatchCommand = Extract<
487 ClientOrchestrationCommand,
488 { type: "project.create" | "project.meta.update" | "project.delete" }
489>;
490
491const ProjectCliRuntimeLive = Layer.mergeAll(
492 WorkspacePathsLive,
493 OrchestrationLayerLive.pipe(
494 Layer.provideMerge(RepositoryIdentityResolverLive),
495 Layer.provideMerge(SqlitePersistenceLayerLive),
496 ),
497);
498
499const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
500const OrchestrationHttpErrorResponse = Schema.Struct({
501 error: Schema.String,
502});
503
504const withProjectCliSessionToken = <A, E, R>(
505 authControlPlane: AuthControlPlaneShape,
506 run: (token: string) => Effect.Effect<A, E, R>,
507) =>
508 Effect.acquireUseRelease(
509 authControlPlane.issueSession({
510 role: "owner",
511 label: "t3 project cli",
512 }),
513 (issued) => run(issued.token),
514 (issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
515 );
516
517const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
518 effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
519
520const runLiveServerRequest = <A, E extends Error, R>(
521 request: HttpClientRequest.HttpClientRequest,
522 handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,
523) =>
524 Effect.gen(function* () {
525 const httpClient = yield* HttpClient.HttpClient;
526 const response = yield* httpClient.execute(request);
527 return yield* handle(response);
528 }).pipe(withProjectCliLiveServerTimeout);
529
530const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
531 HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
532
533const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>
534 HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(
535 Effect.map((body) => body.error),
536 Effect.catch(() => Effect.succeed(null)),
537 Effect.map((body) => {
538 if (typeof body === "string" && body.trim().length > 0) {
539 return body;
540 }
541 return `Server request failed with status ${response.status}.`;
542 }),
543 );
544
545const normalizeWorkspaceRootForProjectCommand = Effect.fn(
546 "normalizeWorkspaceRootForProjectCommand",
547)(function* (workspaceRoot: string) {
548 const workspacePaths = yield* WorkspacePaths;
549 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
550});
551
552const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
553 workspaceRoot: string,
554 explicitTitle?: string,
555) {
556 if (explicitTitle !== undefined) {
557 const trimmed = explicitTitle.trim();
558 if (trimmed.length > 0) {
559 return trimmed;
560 }
561 return yield* Effect.fail(new Error("Project title cannot be empty."));
562 }
563
564 const path = yield* Path.Path;
565 const basename = path.basename(workspaceRoot).trim();
566 return basename.length > 0 ? basename : "project";
567});
568
569const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
570 readonly snapshot: OrchestrationReadModel;
571 readonly identifier: string;
572}) {
573 const trimmedIdentifier = input.identifier.trim();
574 if (trimmedIdentifier.length === 0) {
575 return yield* Effect.fail(new Error("Project identifier cannot be empty."));
576 }
577
578 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
579 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
580 if (exactIdMatch) {
581 return {
582 id: exactIdMatch.id,
583 title: exactIdMatch.title,
584 workspaceRoot: exactIdMatch.workspaceRoot,
585 } satisfies ProjectMutationTarget;
586 }
587
588 const normalizedWorkspaceRootResult = yield* Effect.exit(
589 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
590 );
591 const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
592 ? normalizedWorkspaceRootResult.value
593 : null;
594
595 const exactWorkspaceMatch =
596 normalizedWorkspaceRoot === null
597 ? undefined
598 : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
599
600 const resolved = exactWorkspaceMatch;
601 if (!resolved) {
602 return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
603 }
604
605 return {
606 id: resolved.id,
607 title: resolved.title,
608 workspaceRoot: resolved.workspaceRoot,
609 } satisfies ProjectMutationTarget;
610});
611
612const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
613 runLiveServerRequest(
614 HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(
615 HttpClientRequest.acceptJson,
616 HttpClientRequest.bearerToken(bearerToken),
617 ),
618 HttpClientResponse.matchStatus({
619 "2xx": decodeOrchestrationReadModelResponse,
620 orElse: (response) =>
621 readErrorMessageFromResponse(response).pipe(
622 Effect.flatMap((message) => Effect.fail(new Error(message))),
623 ),
624 }),
625 );
626
627const dispatchLiveOrchestrationCommand = (
628 origin: string,
629 bearerToken: string,
630 command: ProjectCliDispatchCommand,
631) =>
632 HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(
633 HttpClientRequest.acceptJson,
634 HttpClientRequest.bearerToken(bearerToken),
635 HttpClientRequest.bodyJson(command),
636 Effect.flatMap((request) =>
637 runLiveServerRequest(
638 request,
639 HttpClientResponse.matchStatus({
640 "2xx": () => Effect.void,
641 orElse: (response) =>
642 readErrorMessageFromResponse(response).pipe(
643 Effect.flatMap((message) => Effect.fail(new Error(message))),
644 ),
645 }),
646 ),
647 ),
648 );
649
650const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
651 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
652 return yield* projectionSnapshotQuery.getSnapshot();
653});
654
655const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
656 function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {
657 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
658 if (Option.isNone(runtimeState)) {
659 return Option.none<{ readonly origin: string }>();
660 }
661
662 const attempt = withProjectCliSessionToken(authControlPlane, (token) =>
663 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
664 Effect.as({
665 origin: runtimeState.value.origin,
666 }),
667 ),
668 );
669
670 const attempted = yield* Effect.exit(attempt);
671 if (Exit.isSuccess(attempted)) {
672 return Option.some(attempted.value);
673 }
674
675 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
676 return Option.none<{ readonly origin: string }>();
677 },
678);
679
680const runProjectMutation = Effect.fn("runProjectMutation")(function* (
681 flags: CliAuthLocationFlags,
682 run: (input: {
683 readonly snapshot: OrchestrationReadModel;
684 readonly dispatch: (
685 command: ProjectCliDispatchCommand,
686 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
687 readonly mode: ProjectCommandExecutionMode;
688 }) => Effect.Effect<
689 string,
690 Error,
691 FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
692 >,
693) {
694 const logLevel = yield* GlobalFlag.LogLevel;
695 const config = yield* resolveCliAuthConfig(flags, logLevel);
696 const minimumLogLevel = config.logLevel;
697
698 return yield* Effect.gen(function* () {
699 const authControlPlane = yield* AuthControlPlane;
700 const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);
701
702 if (Option.isSome(liveMode)) {
703 return yield* withProjectCliSessionToken(authControlPlane, (token) =>
704 Effect.gen(function* () {
705 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
706 const output = yield* run({
707 snapshot,
708 dispatch: (command) =>
709 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
710 mode: "live",
711 });
712 yield* Console.log(output);
713 }),
714 );
715 }
716
717 const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
718 Layer.provide(Layer.succeed(ServerConfig, config)),
719 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
720 );
721
722 return yield* Effect.gen(function* () {
723 const snapshot = yield* getOfflineSnapshot();
724 const orchestrationEngine = yield* OrchestrationEngineService;
725 const output = yield* run({
726 snapshot,
727 dispatch: (command) => orchestrationEngine.dispatch(command),
728 mode: "offline",
729 });
730 yield* Console.log(output);
731 }).pipe(Effect.provide(offlineRuntimeLayer));
732 }).pipe(
733 Effect.provide(
734 Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(
735 Layer.provideMerge(FetchHttpClient.layer),
736 Layer.provide(Layer.succeed(ServerConfig, config)),
737 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
738 ),
739 ),
740 );
741});
742
743const sharedServerLocationFlags = {
744 baseDir: baseDirFlag,
745 devUrl: devUrlFlag,
746} as const;
747
748const projectLocationFlags = {
749 baseDir: baseDirFlag,
750} as const;
751
752const sharedServerCommandFlags = {
269 mode: modeFlag,753 mode: modeFlag,
270 port: portFlag,754 port: portFlag,
271 host: hostFlag,755 host: hostFlag,
272 baseDir: baseDirFlag,756 baseDir: baseDirFlag,
757 cwd: Argument.string("cwd").pipe(
758 Argument.withDescription(
759 "Working directory for provider sessions (defaults to the current directory).",
760 ),
761 Argument.optional,
762 ),
273 devUrl: devUrlFlag,763 devUrl: devUrlFlag,
274 noBrowser: noBrowserFlag,764 noBrowser: noBrowserFlag,
275 authToken: authTokenFlag,
276 bootstrapFd: bootstrapFdFlag,765 bootstrapFd: bootstrapFdFlag,
277 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,766 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
278 logWebSocketEvents: logWebSocketEventsFlag,767 logWebSocketEvents: logWebSocketEventsFlag,
279} as const;768} as const;
280 769
281const rootCommand = Command.make("t3", commandFlags).pipe(770const authLocationFlags = sharedServerLocationFlags;
771
772const ttlFlag = Flag.string("ttl").pipe(
773 Flag.withSchema(DurationFromString),
774 Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
775 Flag.optional,
776);
777
778const jsonFlag = Flag.boolean("json").pipe(
779 Flag.withDescription("Emit JSON instead of human-readable output."),
780 Flag.withDefault(false),
781);
782
783const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
784 Flag.withDescription("Role for the issued bearer session."),
785 Flag.withDefault("owner"),
786);
787
788const labelFlag = Flag.string("label").pipe(
789 Flag.withDescription("Optional human-readable label."),
790 Flag.optional,
791);
792
793const subjectFlag = Flag.string("subject").pipe(
794 Flag.withDescription("Optional session subject."),
795 Flag.optional,
796);
797
798const baseUrlFlag = Flag.string("base-url").pipe(
799 Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
800 Flag.optional,
801);
802
803const tokenOnlyFlag = Flag.boolean("token-only").pipe(
804 Flag.withDescription("Print only the issued bearer token."),
805 Flag.withDefault(false),
806);
807
808const pairingCreateCommand = Command.make("create", {
809 ...authLocationFlags,
810 ttl: ttlFlag,
811 label: labelFlag,
812 baseUrl: baseUrlFlag,
813 json: jsonFlag,
814}).pipe(
815 Command.withDescription("Issue a new client pairing token."),
816 Command.withHandler((flags) =>
817 runWithAuthControlPlane(
818 flags,
819 (authControlPlane) =>
820 Effect.gen(function* () {
821 const issued = yield* authControlPlane.createPairingLink({
822 role: "client",
823 subject: "one-time-token",
824 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
825 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
826 });
827 const output = formatIssuedPairingCredential(issued, {
828 json: flags.json,
829 ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
830 });
831 yield* Console.log(output);
832 }),
833 {
834 quietLogs: flags.json,
835 },
836 ),
837 ),
838);
839
840const pairingListCommand = Command.make("list", {
841 ...authLocationFlags,
842 json: jsonFlag,
843}).pipe(
844 Command.withDescription("List active client pairing tokens without revealing their secrets."),
845 Command.withHandler((flags) =>
846 runWithAuthControlPlane(
847 flags,
848 (authControlPlane) =>
849 Effect.gen(function* () {
850 const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });
851 yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
852 }),
853 {
854 quietLogs: flags.json,
855 },
856 ),
857 ),
858);
859
860const pairingRevokeCommand = Command.make("revoke", {
861 ...authLocationFlags,
862 id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
863}).pipe(
864 Command.withDescription("Revoke an active client pairing token."),
865 Command.withHandler((flags) =>
866 runWithAuthControlPlane(flags, (authControlPlane) =>
867 Effect.gen(function* () {
868 const revoked = yield* authControlPlane.revokePairingLink(flags.id);
869 yield* Console.log(
870 revoked
871 ? `Revoked pairing credential ${flags.id}.\n`
872 : `No active pairing credential found for ${flags.id}.\n`,
873 );
874 }),
875 ),
876 ),
877);
878
879const pairingCommand = Command.make("pairing").pipe(
880 Command.withDescription("Manage one-time client pairing tokens."),
881 Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
882);
883
884const sessionIssueCommand = Command.make("issue", {
885 ...authLocationFlags,
886 ttl: ttlFlag,
887 role: sessionRoleFlag,
888 label: labelFlag,
889 subject: subjectFlag,
890 tokenOnly: tokenOnlyFlag,
891 json: jsonFlag,
892}).pipe(
893 Command.withDescription("Issue a bearer session token for headless or remote clients."),
894 Command.withHandler((flags) =>
895 runWithAuthControlPlane(
896 flags,
897 (authControlPlane) =>
898 Effect.gen(function* () {
899 const issued = yield* authControlPlane.issueSession({
900 role: flags.role,
901 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
902 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
903 ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
904 });
905 yield* Console.log(
906 formatIssuedSession(issued, {
907 json: flags.json,
908 tokenOnly: flags.tokenOnly,
909 }),
910 );
911 }),
912 {
913 quietLogs: flags.json || flags.tokenOnly,
914 },
915 ),
916 ),
917);
918
919const sessionListCommand = Command.make("list", {
920 ...authLocationFlags,
921 json: jsonFlag,
922}).pipe(
923 Command.withDescription("List active sessions without revealing bearer tokens."),
924 Command.withHandler((flags) =>
925 runWithAuthControlPlane(
926 flags,
927 (authControlPlane) =>
928 Effect.gen(function* () {
929 const sessions = yield* authControlPlane.listSessions();
930 yield* Console.log(formatSessionList(sessions, { json: flags.json }));
931 }),
932 {
933 quietLogs: flags.json,
934 },
935 ),
936 ),
937);
938
939const sessionRevokeCommand = Command.make("revoke", {
940 ...authLocationFlags,
941 sessionId: Argument.string("session-id").pipe(
942 Argument.withDescription("Session id to revoke."),
943 Argument.withSchema(AuthSessionId),
944 ),
945}).pipe(
946 Command.withDescription("Revoke an active session."),
947 Command.withHandler((flags) =>
948 runWithAuthControlPlane(flags, (authControlPlane) =>
949 Effect.gen(function* () {
950 const revoked = yield* authControlPlane.revokeSession(flags.sessionId);
951 yield* Console.log(
952 revoked
953 ? `Revoked session ${flags.sessionId}.\n`
954 : `No active session found for ${flags.sessionId}.\n`,
955 );
956 }),
957 ),
958 ),
959);
960
961const sessionCommand = Command.make("session").pipe(
962 Command.withDescription("Manage bearer sessions."),
963 Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
964);
965
966const authCommand = Command.make("auth").pipe(
967 Command.withDescription("Manage the local auth control plane for headless deployments."),
968 Command.withSubcommands([pairingCommand, sessionCommand]),
969);
970
971const projectAddCommand = Command.make("add", {
972 ...projectLocationFlags,
973 workspaceRoot: Argument.string("path").pipe(
974 Argument.withDescription("Workspace root to add as a project."),
975 ),
976 title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
977}).pipe(
978 Command.withDescription("Add a project."),
979 Command.withHandler((flags) =>
980 runProjectMutation(
981 flags,
982 Effect.fn("projectAddMutation")(function* ({
983 snapshot,
984 dispatch,
985 }: {
986 readonly snapshot: OrchestrationReadModel;
987 readonly dispatch: (
988 command: ProjectCliDispatchCommand,
989 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
990 }) {
991 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
992 const existingProject = snapshot.projects.find(
993 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
994 );
995 if (existingProject) {
996 return yield* Effect.fail(
997 new Error(`An active project already exists for '${workspaceRoot}'.`),
998 );
999 }
1000
1001 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
1002 const projectId = ProjectId.make(crypto.randomUUID());
1003 yield* dispatch({
1004 type: "project.create",
1005 commandId: CommandId.make(crypto.randomUUID()),
1006 projectId,
1007 title,
1008 workspaceRoot,
1009 defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
1010 createdAt: new Date().toISOString(),
1011 });
1012 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
1013 }),
1014 ),
1015 ),
1016);
1017
1018const projectRemoveCommand = Command.make("remove", {
1019 ...projectLocationFlags,
1020 project: Argument.string("project").pipe(
1021 Argument.withDescription("Project id or workspace root to remove."),
1022 ),
1023}).pipe(
1024 Command.withDescription("Remove a project."),
1025 Command.withHandler((flags) =>
1026 runProjectMutation(
1027 flags,
1028 Effect.fn("projectRemoveMutation")(function* ({
1029 snapshot,
1030 dispatch,
1031 }: {
1032 readonly snapshot: OrchestrationReadModel;
1033 readonly dispatch: (
1034 command: ProjectCliDispatchCommand,
1035 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
1036 }) {
1037 const project = yield* findActiveProjectTarget({
1038 snapshot,
1039 identifier: flags.project,
1040 });
1041 yield* dispatch({
1042 type: "project.delete",
1043 commandId: CommandId.make(crypto.randomUUID()),
1044 projectId: project.id,
1045 });
1046 return `Removed project ${project.id} (${project.title}).`;
1047 }),
1048 ),
1049 ),
1050);
1051
1052const projectRenameCommand = Command.make("rename", {
1053 ...projectLocationFlags,
1054 project: Argument.string("project").pipe(
1055 Argument.withDescription("Project id or workspace root to rename."),
1056 ),
1057 title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
1058}).pipe(
1059 Command.withDescription("Rename a project."),
1060 Command.withHandler((flags) =>
1061 runProjectMutation(
1062 flags,
1063 Effect.fn("projectRenameMutation")(function* ({
1064 snapshot,
1065 dispatch,
1066 }: {
1067 readonly snapshot: OrchestrationReadModel;
1068 readonly dispatch: (
1069 command: ProjectCliDispatchCommand,
1070 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
1071 }) {
1072 const project = yield* findActiveProjectTarget({
1073 snapshot,
1074 identifier: flags.project,
1075 });
1076 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
1077 if (nextTitle === project.title) {
1078 return `Project ${project.id} is already named ${nextTitle}.`;
1079 }
1080
1081 yield* dispatch({
1082 type: "project.meta.update",
1083 commandId: CommandId.make(crypto.randomUUID()),
1084 projectId: project.id,
1085 title: nextTitle,
1086 });
1087 return `Renamed project ${project.id} to ${nextTitle}.`;
1088 }),
1089 ),
1090 ),
1091);
1092
1093const projectCommand = Command.make("project").pipe(
1094 Command.withDescription("Manage projects."),
1095 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
1096);
1097
1098const runServerCommand = (
1099 flags: CliServerFlags,
1100 options?: {
1101 readonly startupPresentation?: StartupPresentation;
1102 readonly forceAutoBootstrapProjectFromCwd?: boolean;
1103 },
1104) =>
1105 Effect.gen(function* () {
1106 const logLevel = yield* GlobalFlag.LogLevel;
1107 const config = yield* resolveServerConfig(flags, logLevel, options);
1108 return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
1109 });
1110
1111const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
282 Command.withDescription("Run the T3 Code server."),1112 Command.withDescription("Run the T3 Code server."),
1113 Command.withHandler((flags) => runServerCommand(flags)),
1114);
1115
1116const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
1117 Command.withDescription(
1118 "Run the T3 Code server without opening a browser and print headless pairing details.",
1119 ),
283 Command.withHandler((flags) =>1120 Command.withHandler((flags) =>
284 Effect.gen(function* () {1121 runServerCommand(flags, {
285 const logLevel = yield* GlobalFlag.LogLevel;1122 startupPresentation: "headless",
286 const config = yield* resolveServerConfig(flags, logLevel);1123 forceAutoBootstrapProjectFromCwd: false,
287 return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
288 }),1124 }),
289 ),1125 ),
290);1126);
291 1127
292export const cli = rootCommand;1128export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
1129 Command.withDescription("Run the T3 Code server."),
1130 Command.withHandler((flags) => runServerCommand(flags)),
1131 Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),
1132);
apps/server/src/cliAuthFormat.test.ts+88−0
@@ -0,0 +1,88 @@
1import { expect, it } from "@effect/vitest";
2import { DateTime } from "effect";
3
4import {
5 formatIssuedPairingCredential,
6 formatIssuedSession,
7 formatPairingCredentialList,
8 formatSessionList,
9} from "./cliAuthFormat.ts";
10
11it("formats issued pairing credentials with the secret and optional pair URL", () => {
12 const output = formatIssuedPairingCredential(
13 {
14 id: "pairing-1",
15 credential: "secret-pairing-token",
16 role: "client",
17 subject: "one-time-token",
18 createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
19 expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
20 },
21 { baseUrl: "https://example.com", json: false },
22 );
23
24 expect(output).toContain("secret-pairing-token");
25 expect(output).toContain("https://example.com/pair#token=secret-pairing-token");
26});
27
28it("formats pairing listings without exposing the secret token", () => {
29 const output = formatPairingCredentialList(
30 [
31 {
32 id: "pairing-1",
33 credential: "secret-pairing-token",
34 subject: "one-time-token",
35 label: "Phone",
36 role: "client",
37 createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
38 expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
39 },
40 ],
41 { json: false },
42 );
43
44 expect(output).toContain("pairing-1");
45 expect(output).not.toContain("secret-pairing-token");
46});
47
48it("formats issued sessions with the bearer token but omits tokens from listings", () => {
49 const issuedOutput = formatIssuedSession(
50 {
51 sessionId: "session-1" as never,
52 token: "secret-session-token",
53 method: "bearer-session-token",
54 role: "owner",
55 subject: "cli-issued-session",
56 client: {
57 label: "deploy-bot",
58 deviceType: "bot",
59 },
60 expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
61 },
62 { json: false },
63 );
64
65 const listedOutput = formatSessionList(
66 [
67 {
68 sessionId: "session-1" as never,
69 method: "bearer-session-token",
70 role: "owner",
71 subject: "cli-issued-session",
72 client: {
73 label: "deploy-bot",
74 deviceType: "bot",
75 },
76 connected: false,
77 current: false,
78 issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
79 expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
80 lastConnectedAt: null,
81 },
82 ],
83 { json: false },
84 );
85
86 expect(issuedOutput).toContain("secret-session-token");
87 expect(listedOutput).not.toContain("secret-session-token");
88});
apps/server/src/cliAuthFormat.ts+190−0
@@ -0,0 +1,190 @@
1import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
2import { DateTime } from "effect";
3
4import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
5
6const newline = "\n";
7
8function serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {
9 return values.filter((value): value is string => typeof value === "string" && value.length > 0);
10}
11
12function formatClientMetadata(metadata: AuthClientMetadata): string {
13 const details = serializeOptionalFields([
14 metadata.label,
15 metadata.deviceType !== "unknown" ? metadata.deviceType : undefined,
16 metadata.os,
17 metadata.browser,
18 metadata.ipAddress,
19 ]);
20 return details.length > 0 ? details.join(" | ") : "unlabeled client";
21}
22
23function toIsoString(value: DateTime.DateTime | DateTime.Utc): string {
24 return DateTime.formatIso(DateTime.toUtc(value));
25}
26
27export function formatIssuedPairingCredential(
28 credential: IssuedPairingLink,
29 options?: {
30 readonly json?: boolean;
31 readonly baseUrl?: string;
32 },
33): string {
34 const pairUrl =
35 options?.baseUrl != null && options.baseUrl.length > 0
36 ? (() => {
37 const url = new URL("/pair", options.baseUrl);
38 url.searchParams.delete("token");
39 url.hash = new URLSearchParams([["token", credential.credential]]).toString();
40 return url.toString();
41 })()
42 : undefined;
43
44 if (options?.json) {
45 return `${JSON.stringify(
46 {
47 id: credential.id,
48 credential: credential.credential,
49 ...(credential.label ? { label: credential.label } : {}),
50 role: credential.role,
51 expiresAt: toIsoString(credential.expiresAt),
52 ...(pairUrl ? { pairUrl } : {}),
53 },
54 null,
55 2,
56 )}${newline}`;
57 }
58
59 return (
60 [
61 `Issued client pairing token ${credential.id}.`,
62 `Token: ${credential.credential}`,
63 ...(pairUrl ? [`Pair URL: ${pairUrl}`] : []),
64 `Expires at: ${credential.expiresAt}`,
65 ].join(newline) + newline
66 );
67}
68
69export function formatPairingCredentialList(
70 credentials: ReadonlyArray<AuthPairingLink>,
71 options?: {
72 readonly json?: boolean;
73 },
74): string {
75 if (options?.json) {
76 return `${JSON.stringify(
77 credentials.map((credential) => ({
78 id: credential.id,
79 ...(credential.label ? { label: credential.label } : {}),
80 role: credential.role,
81 createdAt: toIsoString(credential.createdAt),
82 expiresAt: toIsoString(credential.expiresAt),
83 })),
84 null,
85 2,
86 )}${newline}`;
87 }
88
89 if (credentials.length === 0) {
90 return `No active pairing credentials.${newline}`;
91 }
92
93 return (
94 credentials
95 .map((credential) =>
96 [
97 `${credential.id}${credential.label ? ` (${credential.label})` : ""}`,
98 ` role: ${credential.role}`,
99 ` created: ${toIsoString(credential.createdAt)}`,
100 ` expires: ${toIsoString(credential.expiresAt)}`,
101 ].join(newline),
102 )
103 .join(`${newline}${newline}`) + newline
104 );
105}
106
107export function formatIssuedSession(
108 session: IssuedBearerSession,
109 options?: {
110 readonly json?: boolean;
111 readonly tokenOnly?: boolean;
112 },
113): string {
114 if (options?.tokenOnly) {
115 return `${session.token}${newline}`;
116 }
117
118 if (options?.json) {
119 return `${JSON.stringify(
120 {
121 sessionId: session.sessionId,
122 token: session.token,
123 method: session.method,
124 role: session.role,
125 subject: session.subject,
126 client: session.client,
127 expiresAt: toIsoString(session.expiresAt),
128 },
129 null,
130 2,
131 )}${newline}`;
132 }
133
134 return (
135 [
136 `Issued ${session.role} bearer session ${session.sessionId}.`,
137 `Token: ${session.token}`,
138 `Subject: ${session.subject}`,
139 `Client: ${formatClientMetadata(session.client)}`,
140 `Expires at: ${toIsoString(session.expiresAt)}`,
141 ].join(newline) + newline
142 );
143}
144
145export function formatSessionList(
146 sessions: ReadonlyArray<AuthClientSession>,
147 options?: {
148 readonly json?: boolean;
149 },
150): string {
151 if (options?.json) {
152 return `${JSON.stringify(
153 sessions.map((session) => ({
154 sessionId: session.sessionId,
155 method: session.method,
156 role: session.role,
157 subject: session.subject,
158 client: session.client,
159 connected: session.connected,
160 issuedAt: toIsoString(session.issuedAt),
161 expiresAt: toIsoString(session.expiresAt),
162 lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null,
163 })),
164 null,
165 2,
166 )}${newline}`;
167 }
168
169 if (sessions.length === 0) {
170 return `No active sessions.${newline}`;
171 }
172
173 return (
174 sessions
175 .map((session) =>
176 [
177 `${session.sessionId} [${session.role}]${session.connected ? " connected" : ""}`,
178 ` method: ${session.method}`,
179 ` subject: ${session.subject}`,
180 ` client: ${formatClientMetadata(session.client)}`,
181 ` issued: ${toIsoString(session.issuedAt)}`,
182 ` last connected: ${
183 session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : "never"
184 }`,
185 ` expires: ${toIsoString(session.expiresAt)}`,
186 ].join(newline),
187 )
188 .join(`${newline}${newline}`) + newline
189 );
190}
apps/server/src/codexAppServerManager.test.ts+5−5
@@ -17,7 +17,7 @@ import { · 16 unmodified lines
17 resolveCodexModelForAccount,17 resolveCodexModelForAccount,
18} from "./codexAppServerManager";18} from "./codexAppServerManager";
19 19
20const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);20const asThreadId = (value: string): ThreadId => ThreadId.make(value);
21 21
22function createSendTurnHarness() {22function createSendTurnHarness() {
23 const manager = new CodexAppServerManager();23 const manager = new CodexAppServerManager();
@@ -111,9 +111,9 @@ function createPendingUserInputHarness() { · 87 unmodified lines
111 },111 },
112 pendingUserInputs: new Map([112 pendingUserInputs: new Map([
113 [113 [
114 ApprovalRequestId.makeUnsafe("req-user-input-1"),114 ApprovalRequestId.make("req-user-input-1"),
115 {115 {
116 requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),116 requestId: ApprovalRequestId.make("req-user-input-1"),
117 jsonRpcId: 42,117 jsonRpcId: 42,
118 threadId: asThreadId("thread_1"),118 threadId: asThreadId("thread_1"),
119 },119 },
@@ -743,7 +743,7 @@ describe("respondToUserInput", () => { · 623 unmodified lines
743 743
744 await manager.respondToUserInput(744 await manager.respondToUserInput(
745 asThreadId("thread_1"),745 asThreadId("thread_1"),
746 ApprovalRequestId.makeUnsafe("req-user-input-1"),746 ApprovalRequestId.make("req-user-input-1"),
747 {747 {
748 scope: "All request methods",748 scope: "All request methods",
749 compat: "Keep current envelope",749 compat: "Keep current envelope",
@@ -780,7 +780,7 @@ describe("respondToUserInput", () => { · 30 unmodified lines
780 780
781 await manager.respondToUserInput(781 await manager.respondToUserInput(
782 asThreadId("thread_1"),782 asThreadId("thread_1"),
783 ApprovalRequestId.makeUnsafe("req-user-input-1"),783 ApprovalRequestId.make("req-user-input-1"),
784 {784 {
785 scope: [],785 scope: [],
786 },786 },
apps/server/src/codexAppServerManager.ts+34−28
@@ -19,7 +19,7 @@ import { · 18 unmodified lines
19 ProviderInteractionMode,19 ProviderInteractionMode,
20} from "@t3tools/contracts";20} from "@t3tools/contracts";
21import { normalizeModelSlug } from "@t3tools/shared/model";21import { normalizeModelSlug } from "@t3tools/shared/model";
22import { Effect, ServiceMap } from "effect";22import { Effect, Context } from "effect";
23 23
24import {24import {
25 formatCodexCliUpgradeMessage,25 formatCodexCliUpgradeMessage,
@@ -290,20 +290,26 @@ In Default mode, strongly prefer making reasonable assumptions and executing the · 264 unmodified lines
290</collaboration_mode>`;290</collaboration_mode>`;
291 291
292function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {292function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
293 readonly approvalPolicy: "on-request" | "never";293 readonly approvalPolicy: "untrusted" | "on-request" | "never";
294 readonly sandbox: "workspace-write" | "danger-full-access";294 readonly sandbox: "read-only" | "workspace-write" | "danger-full-access";
295} {295} {
296 if (runtimeMode === "approval-required") {296 switch (runtimeMode) {
297 return {297 case "approval-required":
298 approvalPolicy: "on-request",298 return {
299 sandbox: "workspace-write",299 approvalPolicy: "untrusted",
300 };300 sandbox: "read-only",
301 };
302 case "auto-accept-edits":
303 return {
304 approvalPolicy: "on-request",
305 sandbox: "workspace-write",
306 };
307 case "full-access":
308 return {
309 approvalPolicy: "never",
310 sandbox: "danger-full-access",
311 };
301 }312 }
302
303 return {
304 approvalPolicy: "never",
305 sandbox: "danger-full-access",
306 };
307}313}
308 314
309/**315/**
@@ -433,7 +439,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 123 unmodified lines
433 private readonly sessions = new Map<ThreadId, CodexSessionContext>();439 private readonly sessions = new Map<ThreadId, CodexSessionContext>();
434 440
435 private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;441 private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
436 constructor(services?: ServiceMap.ServiceMap<never>) {442 constructor(services?: Context.Context<never>) {
437 super();443 super();
438 this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;444 this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
439 }445 }
@@ -634,7 +640,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 194 unmodified lines
634 this.stopSession(threadId);640 this.stopSession(threadId);
635 } else {641 } else {
636 this.emitEvent({642 this.emitEvent({
637 id: EventId.makeUnsafe(randomUUID()),643 id: EventId.make(randomUUID()),
638 kind: "error",644 kind: "error",
639 provider: "codex",645 provider: "codex",
640 threadId,646 threadId,
@@ -733,7 +739,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 92 unmodified lines
733 if (!turnIdRaw) {739 if (!turnIdRaw) {
734 throw new Error("turn/start response did not include a turn id.");740 throw new Error("turn/start response did not include a turn id.");
735 }741 }
736 const turnId = TurnId.makeUnsafe(turnIdRaw);742 const turnId = TurnId.make(turnIdRaw);
737 743
738 this.updateSession(context, {744 this.updateSession(context, {
739 status: "running",745 status: "running",
@@ -834,7 +840,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 94 unmodified lines
834 });840 });
835 841
836 this.emitEvent({842 this.emitEvent({
837 id: EventId.makeUnsafe(randomUUID()),843 id: EventId.make(randomUUID()),
838 kind: "notification",844 kind: "notification",
839 provider: "codex",845 provider: "codex",
840 threadId: context.session.threadId,846 threadId: context.session.threadId,
@@ -873,7 +879,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 32 unmodified lines
873 });879 });
874 880
875 this.emitEvent({881 this.emitEvent({
876 id: EventId.makeUnsafe(randomUUID()),882 id: EventId.make(randomUUID()),
877 kind: "notification",883 kind: "notification",
878 provider: "codex",884 provider: "codex",
879 threadId: context.session.threadId,885 threadId: context.session.threadId,
@@ -1055,7 +1061,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 175 unmodified lines
1055 : undefined;1061 : undefined;
1056 1062
1057 this.emitEvent({1063 this.emitEvent({
1058 id: EventId.makeUnsafe(randomUUID()),1064 id: EventId.make(randomUUID()),
1059 kind: "notification",1065 kind: "notification",
1060 provider: "codex",1066 provider: "codex",
1061 threadId: context.session.threadId,1067 threadId: context.session.threadId,
@@ -1128,7 +1134,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 66 unmodified lines
1128 const requestKind = this.requestKindForMethod(request.method);1134 const requestKind = this.requestKindForMethod(request.method);
1129 let requestId: ApprovalRequestId | undefined;1135 let requestId: ApprovalRequestId | undefined;
1130 if (requestKind) {1136 if (requestKind) {
1131 requestId = ApprovalRequestId.makeUnsafe(randomUUID());1137 requestId = ApprovalRequestId.make(randomUUID());
1132 const pendingRequest: PendingApprovalRequest = {1138 const pendingRequest: PendingApprovalRequest = {
1133 requestId,1139 requestId,
1134 jsonRpcId: request.id,1140 jsonRpcId: request.id,
@@ -1147,7 +1153,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 12 unmodified lines
1147 }1153 }
1148 1154
1149 if (request.method === "item/tool/requestUserInput") {1155 if (request.method === "item/tool/requestUserInput") {
1150 requestId = ApprovalRequestId.makeUnsafe(randomUUID());1156 requestId = ApprovalRequestId.make(randomUUID());
1151 context.pendingUserInputs.set(requestId, {1157 context.pendingUserInputs.set(requestId, {
1152 requestId,1158 requestId,
1153 jsonRpcId: request.id,1159 jsonRpcId: request.id,
@@ -1158,7 +1164,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 4 unmodified lines
1158 }1164 }
1159 1165
1160 this.emitEvent({1166 this.emitEvent({
1161 id: EventId.makeUnsafe(randomUUID()),1167 id: EventId.make(randomUUID()),
1162 kind: "request",1168 kind: "request",
1163 provider: "codex",1169 provider: "codex",
1164 threadId: context.session.threadId,1170 threadId: context.session.threadId,
@@ -1248,7 +1254,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 83 unmodified lines
1248 1254
1249 private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {1255 private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
1250 this.emitEvent({1256 this.emitEvent({
1251 id: EventId.makeUnsafe(randomUUID()),1257 id: EventId.make(randomUUID()),
1252 kind: "session",1258 kind: "session",
1253 provider: "codex",1259 provider: "codex",
1254 threadId: context.session.threadId,1260 threadId: context.session.threadId,
@@ -1260,7 +1266,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 5 unmodified lines
1260 1266
1261 private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {1267 private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
1262 this.emitEvent({1268 this.emitEvent({
1263 id: EventId.makeUnsafe(randomUUID()),1269 id: EventId.make(randomUUID()),
1264 kind: "error",1270 kind: "error",
1265 provider: "codex",1271 provider: "codex",
1266 threadId: context.session.threadId,1272 threadId: context.session.threadId,
@@ -1276,7 +1282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 9 unmodified lines
1276 message: string,1282 message: string,
1277 ): void {1283 ): void {
1278 this.emitEvent({1284 this.emitEvent({
1279 id: EventId.makeUnsafe(randomUUID()),1285 id: EventId.make(randomUUID()),
1280 kind: "notification",1286 kind: "notification",
1281 provider: "codex",1287 provider: "codex",
1282 threadId: context.session.threadId,1288 threadId: context.session.threadId,
@@ -1335,7 +1341,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 52 unmodified lines
1335 const turns = turnsRaw.map((turnValue, index) => {1341 const turns = turnsRaw.map((turnValue, index) => {
1336 const turn = this.readObject(turnValue);1342 const turn = this.readObject(turnValue);
1337 const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;1343 const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
1338 const turnId = TurnId.makeUnsafe(turnIdRaw);1344 const turnId = TurnId.make(turnIdRaw);
1339 const items = this.readArray(turn, "items") ?? [];1345 const items = this.readArray(turn, "items") ?? [];
1340 return {1346 return {
1341 id: turnId,1347 id: turnId,
@@ -1584,9 +1590,9 @@ function readResumeThreadId(input: { · 242 unmodified lines
1584}1590}
1585 1591
1586function toTurnId(value: string | undefined): TurnId | undefined {1592function toTurnId(value: string | undefined): TurnId | undefined {
1587 return brandIfNonEmpty(value, TurnId.makeUnsafe);1593 return brandIfNonEmpty(value, TurnId.make);
1588}1594}
1589 1595
1590function toProviderItemId(value: string | undefined): ProviderItemId | undefined {1596function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
1591 return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);1597 return brandIfNonEmpty(value, ProviderItemId.make);
1592}1598}
apps/server/src/config.ts+36−4
@@ -6,13 +6,16 @@ · 5 unmodified lines
6 *6 *
7 * @module ServerConfig7 * @module ServerConfig
8 */8 */
9import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";9import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
10 10
11export const DEFAULT_PORT = 3773;11export const DEFAULT_PORT = 3773;
12 12
13export const RuntimeMode = Schema.Literals(["web", "desktop"]);13export const RuntimeMode = Schema.Literals(["web", "desktop"]);
14export type RuntimeMode = typeof RuntimeMode.Type;14export type RuntimeMode = typeof RuntimeMode.Type;
15 15
16export const StartupPresentation = Schema.Literals(["browser", "headless"]);
17export type StartupPresentation = typeof StartupPresentation.Type;
18
16/**19/**
17 * ServerDerivedPaths - Derived paths from the base directory.20 * ServerDerivedPaths - Derived paths from the base directory.
18 */21 */
@@ -25,10 +28,14 @@ export interface ServerDerivedPaths { · 6 unmodified lines
25 readonly attachmentsDir: string;28 readonly attachmentsDir: string;
26 readonly logsDir: string;29 readonly logsDir: string;
27 readonly serverLogPath: string;30 readonly serverLogPath: string;
31 readonly serverTracePath: string;
28 readonly providerLogsDir: string;32 readonly providerLogsDir: string;
29 readonly providerEventLogPath: string;33 readonly providerEventLogPath: string;
30 readonly terminalLogsDir: string;34 readonly terminalLogsDir: string;
31 readonly anonymousIdPath: string;35 readonly anonymousIdPath: string;
36 readonly environmentIdPath: string;
37 readonly serverRuntimeStatePath: string;
38 readonly secretsDir: string;
32}39}
33 40
34/**41/**
@@ -36,6 +43,15 @@ export interface ServerDerivedPaths { · 1 unmodified line
36 */43 */
37export interface ServerConfigShape extends ServerDerivedPaths {44export interface ServerConfigShape extends ServerDerivedPaths {
38 readonly logLevel: LogLevel.LogLevel;45 readonly logLevel: LogLevel.LogLevel;
46 readonly traceMinLevel: LogLevel.LogLevel;
47 readonly traceTimingEnabled: boolean;
48 readonly traceBatchWindowMs: number;
49 readonly traceMaxBytes: number;
50 readonly traceMaxFiles: number;
51 readonly otlpTracesUrl: string | undefined;
52 readonly otlpMetricsUrl: string | undefined;
53 readonly otlpExportIntervalMs: number;
54 readonly otlpServiceName: string;
39 readonly mode: RuntimeMode;55 readonly mode: RuntimeMode;
40 readonly port: number;56 readonly port: number;
41 readonly host: string | undefined;57 readonly host: string | undefined;
@@ -44,7 +60,8 @@ export interface ServerConfigShape extends ServerDerivedPaths { · 2 unmodified lines
44 readonly staticDir: string | undefined;60 readonly staticDir: string | undefined;
45 readonly devUrl: URL | undefined;61 readonly devUrl: URL | undefined;
46 readonly noBrowser: boolean;62 readonly noBrowser: boolean;
47 readonly authToken: string | undefined;63 readonly startupPresentation: StartupPresentation;
64 readonly desktopBootstrapToken: string | undefined;
48 readonly autoBootstrapProjectFromCwd: boolean;65 readonly autoBootstrapProjectFromCwd: boolean;
49 readonly logWebSocketEvents: boolean;66 readonly logWebSocketEvents: boolean;
50}67}
@@ -68,10 +85,14 @@ export const deriveServerPaths = Effect.fn(function* ( · 17 unmodified lines
68 attachmentsDir,85 attachmentsDir,
69 logsDir,86 logsDir,
70 serverLogPath: join(logsDir, "server.log"),87 serverLogPath: join(logsDir, "server.log"),
88 serverTracePath: join(logsDir, "server.trace.ndjson"),
71 providerLogsDir,89 providerLogsDir,
72 providerEventLogPath: join(providerLogsDir, "events.log"),90 providerEventLogPath: join(providerLogsDir, "events.log"),
73 terminalLogsDir: join(logsDir, "terminals"),91 terminalLogsDir: join(logsDir, "terminals"),
74 anonymousIdPath: join(stateDir, "anonymous-id"),92 anonymousIdPath: join(stateDir, "anonymous-id"),
93 environmentIdPath: join(stateDir, "environment-id"),
94 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
95 secretsDir: join(stateDir, "secrets"),
75 };96 };
76});97});
77 98
@@ -90,6 +111,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server · 12 unmodified lines
90 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),111 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
91 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),112 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
92 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),113 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
114 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
93 ],115 ],
94 { concurrency: "unbounded" },116 { concurrency: "unbounded" },
95 );117 );
@@ -98,7 +120,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server · 2 unmodified lines
98/**120/**
99 * ServerConfig - Service tag for server runtime configuration.121 * ServerConfig - Service tag for server runtime configuration.
100 */122 */
101export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(123export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
102 "t3/config/ServerConfig",124 "t3/config/ServerConfig",
103) {125) {
104 static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>126 static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
@@ -117,6 +139,15 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS · 12 unmodified lines
117 139
118 return {140 return {
119 logLevel: "Error",141 logLevel: "Error",
142 traceMinLevel: "Info",
143 traceTimingEnabled: true,
144 traceBatchWindowMs: 200,
145 traceMaxBytes: 10 * 1024 * 1024,
146 traceMaxFiles: 10,
147 otlpTracesUrl: undefined,
148 otlpMetricsUrl: undefined,
149 otlpExportIntervalMs: 10_000,
150 otlpServiceName: "t3-server",
120 cwd,151 cwd,
121 baseDir,152 baseDir,
122 ...derivedPaths,153 ...derivedPaths,
@@ -125,10 +156,11 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS · 2 unmodified lines
125 logWebSocketEvents: false,156 logWebSocketEvents: false,
126 port: 0,157 port: 0,
127 host: undefined,158 host: undefined,
128 authToken: undefined,159 desktopBootstrapToken: undefined,
129 staticDir: undefined,160 staticDir: undefined,
130 devUrl,161 devUrl,
131 noBrowser: false,162 noBrowser: false,
163 startupPresentation: "browser",
132 } satisfies ServerConfigShape;164 } satisfies ServerConfigShape;
133 }),165 }),
134 );166 );
apps/server/src/environment/Layers/ServerEnvironment.test.ts+125−0
@@ -0,0 +1,125 @@
1import * as nodePath from "node:path";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { expect, it } from "@effect/vitest";
4import { Effect, Exit, FileSystem, Layer, PlatformError } from "effect";
5
6import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "../../config.ts";
7import { ServerEnvironment } from "../Services/ServerEnvironment.ts";
8import { ServerEnvironmentLive } from "./ServerEnvironment.ts";
9
10const makeServerEnvironmentLayer = (baseDir: string) =>
11 ServerEnvironmentLive.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
12
13const makeServerConfig = Effect.fn(function* (baseDir: string) {
14 const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
15
16 return {
17 ...derivedPaths,
18 logLevel: "Error",
19 traceMinLevel: "Info",
20 traceTimingEnabled: true,
21 traceBatchWindowMs: 200,
22 traceMaxBytes: 10 * 1024 * 1024,
23 traceMaxFiles: 10,
24 otlpTracesUrl: undefined,
25 otlpMetricsUrl: undefined,
26 otlpExportIntervalMs: 10_000,
27 otlpServiceName: "t3-server",
28 cwd: process.cwd(),
29 baseDir,
30 mode: "web",
31 autoBootstrapProjectFromCwd: false,
32 logWebSocketEvents: false,
33 port: 0,
34 host: undefined,
35 desktopBootstrapToken: undefined,
36 staticDir: undefined,
37 devUrl: undefined,
38 noBrowser: false,
39 startupPresentation: "browser",
40 } satisfies ServerConfigShape;
41});
42
43it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
44 it.effect("persists the environment id across service restarts", () =>
45 Effect.gen(function* () {
46 const fileSystem = yield* FileSystem.FileSystem;
47 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
48 prefix: "t3-server-environment-test-",
49 });
50
51 const first = yield* Effect.gen(function* () {
52 const serverEnvironment = yield* ServerEnvironment;
53 return yield* serverEnvironment.getDescriptor;
54 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
55 const second = yield* Effect.gen(function* () {
56 const serverEnvironment = yield* ServerEnvironment;
57 return yield* serverEnvironment.getDescriptor;
58 }).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
59
60 expect(first.environmentId).toBe(second.environmentId);
61 expect(second.capabilities.repositoryIdentity).toBe(true);
62 }),
63 );
64
65 it.effect("fails instead of overwriting a persisted id when reading the file errors", () =>
66 Effect.gen(function* () {
67 const fileSystem = yield* FileSystem.FileSystem;
68 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
69 prefix: "t3-server-environment-read-error-test-",
70 });
71 const serverConfig = yield* makeServerConfig(baseDir);
72 const environmentIdPath = serverConfig.environmentIdPath;
73 yield* fileSystem.makeDirectory(nodePath.dirname(environmentIdPath), { recursive: true });
74 yield* fileSystem.writeFileString(environmentIdPath, "persisted-environment-id\n");
75 const writeAttempts: string[] = [];
76 const failingFileSystemLayer = FileSystem.layerNoop({
77 exists: (path) => Effect.succeed(path === environmentIdPath),
78 readFileString: (path) =>
79 path === environmentIdPath
80 ? Effect.fail(
81 PlatformError.systemError({
82 _tag: "PermissionDenied",
83 module: "FileSystem",
84 method: "readFileString",
85 description: "permission denied",
86 pathOrDescriptor: path,
87 }),
88 )
89 : Effect.fail(
90 PlatformError.systemError({
91 _tag: "NotFound",
92 module: "FileSystem",
93 method: "readFileString",
94 description: "not found",
95 pathOrDescriptor: path,
96 }),
97 ),
98 writeFileString: (path) => {
99 writeAttempts.push(path);
100 return Effect.void;
101 },
102 });
103
104 const exit = yield* Effect.gen(function* () {
105 const serverEnvironment = yield* ServerEnvironment;
106 return yield* serverEnvironment.getDescriptor;
107 }).pipe(
108 Effect.provide(
109 ServerEnvironmentLive.pipe(
110 Layer.provide(
111 Layer.merge(Layer.succeed(ServerConfig, serverConfig), failingFileSystemLayer),
112 ),
113 ),
114 ),
115 Effect.exit,
116 );
117
118 expect(Exit.isFailure(exit)).toBe(true);
119 expect(writeAttempts).toEqual([]);
120 expect(yield* fileSystem.readFileString(environmentIdPath)).toBe(
121 "persisted-environment-id\n",
122 );
123 }),
124 );
125});
apps/server/src/environment/Layers/ServerEnvironment.ts+92−0
@@ -0,0 +1,92 @@
1import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
2import { Effect, FileSystem, Layer, Path, Random } from "effect";
3
4import { ServerConfig } from "../../config.ts";
5import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
6import { version } from "../../../package.json" with { type: "json" };
7import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
8
9function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
10 switch (process.platform) {
11 case "darwin":
12 return "darwin";
13 case "linux":
14 return "linux";
15 case "win32":
16 return "windows";
17 default:
18 return "unknown";
19 }
20}
21
22function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] {
23 switch (process.arch) {
24 case "arm64":
25 return "arm64";
26 case "x64":
27 return "x64";
28 default:
29 return "other";
30 }
31}
32
33export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function* () {
34 const fileSystem = yield* FileSystem.FileSystem;
35 const path = yield* Path.Path;
36 const serverConfig = yield* ServerConfig;
37
38 const readPersistedEnvironmentId = Effect.gen(function* () {
39 const exists = yield* fileSystem
40 .exists(serverConfig.environmentIdPath)
41 .pipe(Effect.orElseSucceed(() => false));
42 if (!exists) {
43 return null;
44 }
45
46 const raw = yield* fileSystem
47 .readFileString(serverConfig.environmentIdPath)
48 .pipe(Effect.map((value) => value.trim()));
49
50 return raw.length > 0 ? raw : null;
51 });
52
53 const persistEnvironmentId = (value: string) =>
54 fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`);
55
56 const environmentIdRaw = yield* Effect.gen(function* () {
57 const persisted = yield* readPersistedEnvironmentId;
58 if (persisted) {
59 return persisted;
60 }
61
62 const generated = yield* Random.nextUUIDv4;
63 yield* persistEnvironmentId(generated);
64 return generated;
65 });
66
67 const environmentId = EnvironmentId.make(environmentIdRaw);
68 const cwdBaseName = path.basename(serverConfig.cwd).trim();
69 const label = yield* resolveServerEnvironmentLabel({
70 cwdBaseName,
71 });
72
73 const descriptor: ExecutionEnvironmentDescriptor = {
74 environmentId,
75 label,
76 platform: {
77 os: platformOs(),
78 arch: platformArch(),
79 },
80 serverVersion: version,
81 capabilities: {
82 repositoryIdentity: true,
83 },
84 };
85
86 return {
87 getEnvironmentId: Effect.succeed(environmentId),
88 getDescriptor: Effect.succeed(descriptor),
89 } satisfies ServerEnvironmentShape;
90});
91
92export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts+150−0
@@ -0,0 +1,150 @@
1import { afterEach, describe, expect, it } from "@effect/vitest";
2import { Effect, FileSystem } from "effect";
3import { vi } from "vitest";
4
5vi.mock("../../processRunner.ts", () => ({
6 runProcess: vi.fn(),
7}));
8
9import { runProcess } from "../../processRunner.ts";
10import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
11
12const mockedRunProcess = vi.mocked(runProcess);
13const NoopFileSystemLayer = FileSystem.layerNoop({});
14
15afterEach(() => {
16 mockedRunProcess.mockReset();
17});
18
19describe("resolveServerEnvironmentLabel", () => {
20 it.effect("uses hostname fallback regardless of launch mode", () =>
21 Effect.gen(function* () {
22 const result = yield* resolveServerEnvironmentLabel({
23 cwdBaseName: "t3code",
24 platform: "win32",
25 hostname: "macbook-pro",
26 }).pipe(Effect.provide(NoopFileSystemLayer));
27
28 expect(result).toBe("macbook-pro");
29 }),
30 );
31
32 it.effect("prefers the macOS ComputerName", () =>
33 Effect.gen(function* () {
34 mockedRunProcess.mockResolvedValueOnce({
35 stdout: " Julius's MacBook Pro \n",
36 stderr: "",
37 code: 0,
38 signal: null,
39 timedOut: false,
40 });
41
42 const result = yield* resolveServerEnvironmentLabel({
43 cwdBaseName: "t3code",
44 platform: "darwin",
45 hostname: "macbook-pro",
46 }).pipe(Effect.provide(NoopFileSystemLayer));
47
48 expect(result).toBe("Julius's MacBook Pro");
49 expect(mockedRunProcess).toHaveBeenCalledWith(
50 "scutil",
51 ["--get", "ComputerName"],
52 expect.objectContaining({ allowNonZeroExit: true }),
53 );
54 }),
55 );
56
57 it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () =>
58 Effect.gen(function* () {
59 const result = yield* resolveServerEnvironmentLabel({
60 cwdBaseName: "t3code",
61 platform: "linux",
62 hostname: "buildbox",
63 }).pipe(
64 Effect.provide(
65 FileSystem.layerNoop({
66 exists: (path) => Effect.succeed(path === "/etc/machine-info"),
67 readFileString: (path) =>
68 path === "/etc/machine-info"
69 ? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
70 : Effect.succeed(""),
71 }),
72 ),
73 );
74
75 expect(result).toBe("Build Agent 01");
76 expect(mockedRunProcess).not.toHaveBeenCalled();
77 }),
78 );
79
80 it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
81 Effect.gen(function* () {
82 mockedRunProcess.mockResolvedValueOnce({
83 stdout: "CI Runner\n",
84 stderr: "",
85 code: 0,
86 signal: null,
87 timedOut: false,
88 });
89
90 const result = yield* resolveServerEnvironmentLabel({
91 cwdBaseName: "t3code",
92 platform: "linux",
93 hostname: "runner-01",
94 }).pipe(Effect.provide(NoopFileSystemLayer));
95
96 expect(result).toBe("CI Runner");
97 expect(mockedRunProcess).toHaveBeenCalledWith(
98 "hostnamectl",
99 ["--pretty"],
100 expect.objectContaining({ allowNonZeroExit: true }),
101 );
102 }),
103 );
104
105 it.effect("falls back to the hostname when friendly labels are unavailable", () =>
106 Effect.gen(function* () {
107 const result = yield* resolveServerEnvironmentLabel({
108 cwdBaseName: "t3code",
109 platform: "win32",
110 hostname: "JULIUS-LAPTOP",
111 }).pipe(Effect.provide(NoopFileSystemLayer));
112
113 expect(result).toBe("JULIUS-LAPTOP");
114 }),
115 );
116
117 it.effect("falls back to the hostname when the friendly-label command is missing", () =>
118 Effect.gen(function* () {
119 mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
120
121 const result = yield* resolveServerEnvironmentLabel({
122 cwdBaseName: "t3code",
123 platform: "darwin",
124 hostname: "macbook-pro",
125 }).pipe(Effect.provide(NoopFileSystemLayer));
126
127 expect(result).toBe("macbook-pro");
128 }),
129 );
130
131 it.effect("falls back to the cwd basename when the hostname is blank", () =>
132 Effect.gen(function* () {
133 mockedRunProcess.mockResolvedValueOnce({
134 stdout: " ",
135 stderr: "",
136 code: 0,
137 signal: null,
138 timedOut: false,
139 });
140
141 const result = yield* resolveServerEnvironmentLabel({
142 cwdBaseName: "t3code",
143 platform: "linux",
144 hostname: " ",
145 }).pipe(Effect.provide(NoopFileSystemLayer));
146
147 expect(result).toBe("t3code");
148 }),
149 );
150});
apps/server/src/environment/Layers/ServerEnvironmentLabel.ts+106−0
@@ -0,0 +1,106 @@
1import * as OS from "node:os";
2
3import { Effect, FileSystem } from "effect";
4
5import { runProcess } from "../../processRunner.ts";
6
7interface ResolveServerEnvironmentLabelInput {
8 readonly cwdBaseName: string;
9 readonly platform?: NodeJS.Platform;
10 readonly hostname?: string | null;
11}
12
13function normalizeLabel(value: string | null | undefined): string | null {
14 const trimmed = value?.trim();
15 return trimmed && trimmed.length > 0 ? trimmed : null;
16}
17
18function parseMachineInfoValue(raw: string, key: string): string | null {
19 for (const line of raw.split(/\r?\n/g)) {
20 const trimmed = line.trim();
21 if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) {
22 continue;
23 }
24 const value = trimmed.slice(key.length + 1).trim();
25 if (
26 (value.startsWith('"') && value.endsWith('"')) ||
27 (value.startsWith("'") && value.endsWith("'"))
28 ) {
29 return normalizeLabel(value.slice(1, -1));
30 }
31 return normalizeLabel(value);
32 }
33 return null;
34}
35
36const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
37 const fileSystem = yield* FileSystem.FileSystem;
38 const exists = yield* fileSystem
39 .exists("/etc/machine-info")
40 .pipe(Effect.orElseSucceed(() => false));
41 if (!exists) {
42 return null;
43 }
44
45 return yield* fileSystem
46 .readFileString("/etc/machine-info")
47 .pipe(Effect.orElseSucceed(() => null));
48});
49
50const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
51 command: string,
52 args: readonly string[],
53) {
54 const result = yield* Effect.tryPromise({
55 try: () =>
56 runProcess(command, args, {
57 allowNonZeroExit: true,
58 }),
59 catch: () => null,
60 }).pipe(Effect.orElseSucceed(() => null));
61
62 if (!result || result.code !== 0) {
63 return null;
64 }
65
66 return normalizeLabel(result.stdout);
67});
68
69const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
70 platform: NodeJS.Platform,
71) {
72 if (platform === "darwin") {
73 return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
74 }
75
76 if (platform === "linux") {
77 const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());
78 if (machineInfo) {
79 const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME");
80 if (prettyHostname) {
81 return prettyHostname;
82 }
83 }
84
85 return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
86 }
87
88 return null;
89});
90
91export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
92 input: ResolveServerEnvironmentLabelInput,
93) {
94 const platform = input.platform ?? process.platform;
95 const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
96 if (friendlyHostLabel) {
97 return friendlyHostLabel;
98 }
99
100 const hostname = normalizeLabel(input.hostname ?? OS.hostname());
101 if (hostname) {
102 return hostname;
103 }
104
105 return normalizeLabel(input.cwdBaseName) ?? "T3 environment";
106});
apps/server/src/environment/Services/ServerEnvironment.ts+12−0
@@ -0,0 +1,12 @@
1import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
2import { Context } from "effect";
3import type { Effect } from "effect";
4
5export interface ServerEnvironmentShape {
6 readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
7 readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
8}
9
10export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
11 "t3/environment/Services/ServerEnvironment",
12) {}
apps/server/src/git/Layers/GitCore.test.ts+183−63
@@ -40,6 +40,24 @@ function writeTextFile( · 39 unmodified lines
40 });40 });
41}41}
42 42
43function removePath(
44 targetPath: string,
45): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
46 return Effect.gen(function* () {
47 const fileSystem = yield* FileSystem.FileSystem;
48 yield* fileSystem.remove(targetPath, { recursive: true, force: true });
49 });
50}
51
52function makeDirectory(
53 dirPath: string,
54): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
55 return Effect.gen(function* () {
56 const fileSystem = yield* FileSystem.FileSystem;
57 yield* fileSystem.makeDirectory(dirPath, { recursive: true });
58 });
59}
60
43/** Run a raw git command for test setup (not under test). */61/** Run a raw git command for test setup (not under test). */
44function git(62function git(
45 cwd: string,63 cwd: string,
@@ -219,7 +237,10 @@ it.layer(TestLayer)("git integration", (it) => { · 173 unmodified lines
219 237
220 const seenChunks: string[][] = [];238 const seenChunks: string[][] = [];
221 const core = yield* makeIsolatedGitCore((input) => {239 const core = yield* makeIsolatedGitCore((input) => {
222 if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") {240 if (
241 input.args.join(" ") !==
242 "-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin"
243 ) {
223 return Effect.fail(244 return Effect.fail(
224 new GitCommandError({245 new GitCommandError({
225 operation: input.operation,246 operation: input.operation,
@@ -252,6 +273,35 @@ it.layer(TestLayer)("git integration", (it) => { · 26 unmodified lines
252 expect(result).toEqual(expectedPaths);273 expect(result).toEqual(expectedPaths);
253 }),274 }),
254 );275 );
276
277 it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () =>
278 Effect.gen(function* () {
279 const core = yield* makeIsolatedGitCore((input) => {
280 expect(input.args).toEqual([
281 "-c",
282 "core.fsmonitor=false",
283 "-c",
284 "core.untrackedCache=false",
285 "ls-files",
286 "--cached",
287 "--others",
288 "--exclude-standard",
289 "-z",
290 ]);
291 return Effect.succeed({
292 code: 0,
293 stdout: "src/index.ts\0README.md\0",
294 stderr: "",
295 stdoutTruncated: false,
296 stderrTruncated: false,
297 });
298 });
299
300 const result = yield* core.listWorkspaceFiles("/virtual/repo");
301 expect(result.paths).toEqual(["src/index.ts", "README.md"]);
302 expect(result.truncated).toBe(false);
303 }),
304 );
255 });305 });
256 306
257 // ── listGitBranches ──307 // ── listGitBranches ──
@@ -267,6 +317,21 @@ it.layer(TestLayer)("git integration", (it) => { · 9 unmodified lines
267 }),317 }),
268 );318 );
269 319
320 it.effect("returns isRepo: false for deleted directories", () =>
321 Effect.gen(function* () {
322 const tmp = yield* makeTmpDir();
323 const deletedDir = path.join(tmp, "deleted-repo");
324 yield* makeDirectory(deletedDir);
325 yield* removePath(deletedDir);
326
327 const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir });
328
329 expect(result.isRepo).toBe(false);
330 expect(result.hasOriginRemote).toBe(false);
331 expect(result.branches).toEqual([]);
332 }),
333 );
334
270 it.effect("returns the current branch with current: true", () =>335 it.effect("returns the current branch with current: true", () =>
271 Effect.gen(function* () {336 Effect.gen(function* () {
272 const tmp = yield* makeTmpDir();337 const tmp = yield* makeTmpDir();
@@ -617,8 +682,8 @@ it.layer(TestLayer)("git integration", (it) => { · 344 unmodified lines
617 682
618 it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>683 it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
619 Effect.gen(function* () {684 Effect.gen(function* () {
620 const services = yield* Effect.services();685 const context = yield* Effect.context<never>();
621 const runPromise = Effect.runPromiseWith(services);686 const runPromise = Effect.runPromiseWith(context);
622 687
623 const remote = yield* makeTmpDir();688 const remote = yield* makeTmpDir();
624 const source = yield* makeTmpDir();689 const source = yield* makeTmpDir();
@@ -761,7 +826,7 @@ it.layer(TestLayer)("git integration", (it) => { · 136 unmodified lines
761 }),826 }),
762 );827 );
763 828
764 it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>829 it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
765 Effect.gen(function* () {830 Effect.gen(function* () {
766 const ok = (stdout = "") =>831 const ok = (stdout = "") =>
767 Effect.succeed({832 Effect.succeed({
@@ -780,7 +845,9 @@ it.layer(TestLayer)("git integration", (it) => { · 12 unmodified lines
780 input.args[2] === "--symbolic-full-name" &&845 input.args[2] === "--symbolic-full-name" &&
781 input.args[3] === "@{upstream}"846 input.args[3] === "@{upstream}"
782 ) {847 ) {
783 return ok("origin/main\n");848 return ok(
849 input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
850 );
784 }851 }
785 if (input.args[0] === "remote") {852 if (input.args[0] === "remote") {
786 return ok("origin\n");853 return ok("origin\n");
@@ -791,10 +858,22 @@ it.layer(TestLayer)("git integration", (it) => { · 4 unmodified lines
791 if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {858 if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
792 fetchCount += 1;859 fetchCount += 1;
793 expect(input.cwd).toBe("/repo");860 expect(input.cwd).toBe("/repo");
861 expect(input.args).toEqual([
862 "--git-dir",
863 "/repo/.git",
864 "fetch",
865 "--quiet",
866 "--no-tags",
867 "origin",
868 ]);
794 return ok();869 return ok();
795 }870 }
796 if (input.operation === "GitCore.statusDetails.status") {871 if (input.operation === "GitCore.statusDetails.status") {
797 return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");872 return ok(
873 input.cwd === "/repo/worktrees/pr-123"
874 ? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
875 : "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
876 );
798 }877 }
799 if (878 if (
800 input.operation === "GitCore.statusDetails.unstagedNumstat" ||879 input.operation === "GitCore.statusDetails.unstagedNumstat" ||
@@ -821,70 +900,80 @@ it.layer(TestLayer)("git integration", (it) => { · 20 unmodified lines
821 }),900 }),
822 );901 );
823 902
824 it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>903 it.effect(
825 Effect.gen(function* () {904 "briefly backs off failed upstream refreshes across sibling worktrees on one remote",
826 const ok = (stdout = "") =>905 () =>
827 Effect.succeed({906 Effect.gen(function* () {
828 code: 0,907 const ok = (stdout = "") =>
829 stdout,908 Effect.succeed({
830 stderr: "",909 code: 0,
831 stdoutTruncated: false,910 stdout,
832 stderrTruncated: false,911 stderr: "",
833 });912 stdoutTruncated: false,
913 stderrTruncated: false,
914 });
834 915
835 let fetchCount = 0;916 let fetchCount = 0;
836 const core = yield* makeIsolatedGitCore((input) => {917 const core = yield* makeIsolatedGitCore((input) => {
837 if (918 if (
838 input.args[0] === "rev-parse" &&919 input.args[0] === "rev-parse" &&
839 input.args[1] === "--abbrev-ref" &&920 input.args[1] === "--abbrev-ref" &&
840 input.args[2] === "--symbolic-full-name" &&921 input.args[2] === "--symbolic-full-name" &&
841 input.args[3] === "@{upstream}"922 input.args[3] === "@{upstream}"
842 ) {923 ) {
843 return ok("origin/main\n");924 return ok(
844 }925 input.cwd === "/repo/worktrees/pr-123"
845 if (input.args[0] === "remote") {926 ? "origin/feature/pr-123\n"
846 return ok("origin\n");927 : "origin/main\n",
847 }928 );
848 if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {929 }
849 return ok("/repo/.git\n");930 if (input.args[0] === "remote") {
850 }931 return ok("origin\n");
851 if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {932 }
852 fetchCount += 1;933 if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
934 return ok("/repo/.git\n");
935 }
936 if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
937 fetchCount += 1;
938 return Effect.fail(
939 new GitCommandError({
940 operation: input.operation,
941 command: `git ${input.args.join(" ")}`,
942 cwd: input.cwd,
943 detail: "simulated fetch timeout",
944 }),
945 );
946 }
947 if (input.operation === "GitCore.statusDetails.status") {
948 return ok(
949 input.cwd === "/repo/worktrees/pr-123"
950 ? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
951 : "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
952 );
953 }
954 if (
955 input.operation === "GitCore.statusDetails.unstagedNumstat" ||
956 input.operation === "GitCore.statusDetails.stagedNumstat"
957 ) {
958 return ok();
959 }
960 if (input.operation === "GitCore.statusDetails.defaultRef") {
961 return ok("refs/remotes/origin/main\n");
962 }
853 return Effect.fail(963 return Effect.fail(
854 new GitCommandError({964 new GitCommandError({
855 operation: input.operation,965 operation: input.operation,
856 command: `git ${input.args.join(" ")}`,966 command: `git ${input.args.join(" ")}`,
857 cwd: input.cwd,967 cwd: input.cwd,
858 detail: "simulated fetch timeout",968 detail: "Unexpected git command in refresh failure cooldown test.",
859 }),969 }),
860 );970 );
861 }971 });
862 if (input.operation === "GitCore.statusDetails.status") {
863 return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
864 }
865 if (
866 input.operation === "GitCore.statusDetails.unstagedNumstat" ||
867 input.operation === "GitCore.statusDetails.stagedNumstat"
868 ) {
869 return ok();
870 }
871 if (input.operation === "GitCore.statusDetails.defaultRef") {
872 return ok("refs/remotes/origin/main\n");
873 }
874 return Effect.fail(
875 new GitCommandError({
876 operation: input.operation,
877 command: `git ${input.args.join(" ")}`,
878 cwd: input.cwd,
879 detail: "Unexpected git command in refresh failure cooldown test.",
880 }),
881 );
882 });
883 972
884 yield* core.statusDetails("/repo/worktrees/main");973 yield* core.statusDetails("/repo/worktrees/main");
885 yield* core.statusDetails("/repo/worktrees/pr-123");974 yield* core.statusDetails("/repo/worktrees/pr-123");
886 expect(fetchCount).toBe(1);975 expect(fetchCount).toBe(1);
887 }),976 }),
888 );977 );
889 978
890 it.effect("throws when branch does not exist", () =>979 it.effect("throws when branch does not exist", () =>
@@ -949,11 +1038,12 @@ it.layer(TestLayer)("git integration", (it) => { · 58 unmodified lines
949 yield* git(source, ["checkout", defaultBranch]);1038 yield* git(source, ["checkout", defaultBranch]);
950 yield* git(source, ["branch", "-D", featureBranch]);1039 yield* git(source, ["branch", "-D", featureBranch]);
951 1040
952 yield* (yield* GitCore).checkoutBranch({1041 const checkoutResult = yield* (yield* GitCore).checkoutBranch({
953 cwd: source,1042 cwd: source,
954 branch: `${remoteName}/${featureBranch}`,1043 branch: `${remoteName}/${featureBranch}`,
955 });1044 });
956 1045
1046 expect(checkoutResult.branch).toBe("upstream/feature");
957 expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");1047 expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
958 const realGitCore = yield* GitCore;1048 const realGitCore = yield* GitCore;
959 let fetchArgs: readonly string[] | null = null;1049 let fetchArgs: readonly string[] | null = null;
@@ -981,7 +1071,6 @@ it.layer(TestLayer)("git integration", (it) => { · 21 unmodified lines
981 "--quiet",1071 "--quiet",
982 "--no-tags",1072 "--no-tags",
983 remoteName,1073 remoteName,
984 `+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
985 ]);1074 ]);
986 }),1075 }),
987 );1076 );
@@ -1593,6 +1682,37 @@ it.layer(TestLayer)("git integration", (it) => { · 605 unmodified lines
1593 }),1682 }),
1594 );1683 );
1595 1684
1685 it.effect("returns a non-repo status for deleted directories", () =>
1686 Effect.gen(function* () {
1687 const tmp = yield* makeTmpDir();
1688 const deletedDir = path.join(tmp, "deleted-repo");
1689 yield* makeDirectory(deletedDir);
1690 yield* removePath(deletedDir);
1691 const core = yield* GitCore;
1692
1693 const status = yield* core.statusDetails(deletedDir);
1694 const localStatus = yield* core.statusDetailsLocal(deletedDir);
1695
1696 expect(status).toEqual({
1697 isRepo: false,
1698 hasOriginRemote: false,
1699 isDefaultBranch: false,
1700 branch: null,
1701 upstreamRef: null,
1702 hasWorkingTreeChanges: false,
1703 workingTree: {
1704 files: [],
1705 insertions: 0,
1706 deletions: 0,
1707 },
1708 hasUpstream: false,
1709 aheadCount: 0,
1710 behindCount: 0,
1711 });
1712 expect(localStatus).toEqual(status);
1713 }),
1714 );
1715
1596 it.effect("computes ahead count against base branch when no upstream is configured", () =>1716 it.effect("computes ahead count against base branch when no upstream is configured", () =>
1597 Effect.gen(function* () {1717 Effect.gen(function* () {
1598 const tmp = yield* makeTmpDir();1718 const tmp = yield* makeTmpDir();
apps/server/src/git/Layers/GitCore.ts+158−42
@@ -20,11 +20,14 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; · 19 unmodified lines
20 20
21import { GitCommandError, type GitBranch } from "@t3tools/contracts";21import { GitCommandError, type GitBranch } from "@t3tools/contracts";
22import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";22import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
23import { compactTraceAttributes } from "../../observability/Attributes.ts";
24import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts";
23import {25import {
24 GitCore,26 GitCore,
25 type ExecuteGitProgress,27 type ExecuteGitProgress,
26 type GitCommitOptions,28 type GitCommitOptions,
27 type GitCoreShape,29 type GitCoreShape,
30 type GitStatusDetails,
28 type ExecuteGitInput,31 type ExecuteGitInput,
29 type ExecuteGitResult,32 type ExecuteGitResult,
30} from "../Services/GitCore.ts";33} from "../Services/GitCore.ts";
@@ -45,23 +48,39 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; · 14 unmodified lines
45const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;48const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
46const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;49const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
47const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;50const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
51const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
52 "-c",
53 "core.fsmonitor=false",
54 "-c",
55 "core.untrackedCache=false",
56] as const;
48const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);57const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
49const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);58const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
50const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);59const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
51const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;60const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
52const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;61const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
53const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;62const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
63const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
64 isRepo: false,
65 hasOriginRemote: false,
66 isDefaultBranch: false,
67 branch: null,
68 upstreamRef: null,
69 hasWorkingTreeChanges: false,
70 workingTree: { files: [], insertions: 0, deletions: 0 },
71 hasUpstream: false,
72 aheadCount: 0,
73 behindCount: 0,
74});
54 75
55type TraceTailState = {76type TraceTailState = {
56 processedChars: number;77 processedChars: number;
57 remainder: string;78 remainder: string;
58};79};
59 80
60class StatusUpstreamRefreshCacheKey extends Data.Class<{81class StatusRemoteRefreshCacheKey extends Data.Class<{
61 gitCommonDir: string;82 gitCommonDir: string;
62 upstreamRef: string;
63 remoteName: string;83 remoteName: string;
64 upstreamBranch: string;
65}> {}84}> {}
66 85
67interface ExecuteGitOptions {86interface ExecuteGitOptions {
@@ -351,6 +370,16 @@ function quoteGitCommand(args: ReadonlyArray<string>): string { · 283 unmodified lines
351 return `git ${args.join(" ")}`;370 return `git ${args.join(" ")}`;
352}371}
353 372
373function isMissingGitCwdError(error: GitCommandError): boolean {
374 const normalized = `${error.detail}\n${error.message}`.toLowerCase();
375 return (
376 normalized.includes("no such file or directory") ||
377 normalized.includes("notfound: filesystem.access") ||
378 normalized.includes("enoent") ||
379 normalized.includes("not a directory")
380 );
381}
382
354function toGitCommandError(383function toGitCommandError(
355 input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,384 input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
356 detail: string,385 detail: string,
@@ -372,6 +401,18 @@ interface Trace2Monitor { · 15 unmodified lines
372 readonly flush: Effect.Effect<void, never>;401 readonly flush: Effect.Effect<void, never>;
373}402}
374 403
404const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n;
405
406const addCurrentSpanEvent = (name: string, attributes: Record<string, unknown>) =>
407 Effect.currentSpan.pipe(
408 Effect.tap((span) =>
409 Effect.sync(() => {
410 span.event(name, nowUnixNano(), compactTraceAttributes(attributes));
411 }),
412 ),
413 Effect.catch(() => Effect.void),
414 );
415
375function trace2ChildKey(record: Record<string, unknown>): string | null {416function trace2ChildKey(record: Record<string, unknown>): string | null {
376 const childId = record.child_id;417 const childId = record.child_id;
377 if (typeof childId === "number" || typeof childId === "string") {418 if (typeof childId === "number" || typeof childId === "string") {
@@ -444,6 +485,9 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( · 66 unmodified lines
444 485
445 if (event === "child_start") {486 if (event === "child_start") {
446 hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });487 hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
488 yield* addCurrentSpanEvent("git.hook.started", {
489 hookName,
490 });
447 if (progress.onHookStarted) {491 if (progress.onHookStarted) {
448 yield* progress.onHookStarted(hookName);492 yield* progress.onHookStarted(hookName);
449 }493 }
@@ -452,12 +496,19 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( · 2 unmodified lines
452 496
453 if (event === "child_exit") {497 if (event === "child_exit") {
454 hookStartByChildKey.delete(childKey);498 hookStartByChildKey.delete(childKey);
499 const code = traceRecord.success.code;
500 const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null;
501 const durationMs = started ? Math.max(0, Date.now() - started.startedAtMs) : null;
502 yield* addCurrentSpanEvent("git.hook.finished", {
503 hookName: started?.hookName ?? hookName,
504 exitCode,
505 durationMs,
506 });
455 if (progress.onHookFinished) {507 if (progress.onHookFinished) {
456 const code = traceRecord.success.code;
457 yield* progress.onHookFinished({508 yield* progress.onHookFinished({
458 hookName: started?.hookName ?? hookName,509 hookName: started?.hookName ?? hookName,
459 exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,510 exitCode,
460 durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,511 durationMs,
461 });512 });
462 }513 }
463 }514 }
@@ -609,13 +660,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 145 unmodified lines
609 const path = yield* Path.Path;660 const path = yield* Path.Path;
610 const { worktreesDir } = yield* ServerConfig;661 const { worktreesDir } = yield* ServerConfig;
611 662
612 let execute: GitCoreShape["execute"];663 let executeRaw: GitCoreShape["execute"];
613 664
614 if (options?.executeOverride) {665 if (options?.executeOverride) {
615 execute = options.executeOverride;666 executeRaw = options.executeOverride;
616 } else {667 } else {
617 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;668 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
618 execute = Effect.fnUntraced(function* (input) {669 executeRaw = Effect.fnUntraced(function* (input) {
619 const commandInput = {670 const commandInput = {
620 ...input,671 ...input,
621 args: [...input.args],672 args: [...input.args],
@@ -716,6 +767,25 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 94 unmodified lines
716 });767 });
717 }768 }
718 769
770 const execute: GitCoreShape["execute"] = (input) =>
771 executeRaw(input).pipe(
772 withMetrics({
773 counter: gitCommandsTotal,
774 timer: gitCommandDuration,
775 attributes: {
776 operation: input.operation,
777 },
778 }),
779 Effect.withSpan(input.operation, {
780 kind: "client",
781 attributes: {
782 "git.operation": input.operation,
783 "git.cwd": input.cwd,
784 "git.args_count": input.args.length,
785 },
786 }),
787 );
788
719 const executeGit = (789 const executeGit = (
720 operation: string,790 operation: string,
721 cwd: string,791 cwd: string,
@@ -847,17 +917,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 125 unmodified lines
847 );917 );
848 });918 });
849 919
850 const fetchUpstreamRefForStatus = (920 const fetchRemoteForStatus = (
851 gitCommonDir: string,921 gitCommonDir: string,
852 upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },922 remoteName: string,
853 ): Effect.Effect<void, GitCommandError> => {923 ): Effect.Effect<void, GitCommandError> => {
854 const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
855 const fetchCwd =924 const fetchCwd =
856 path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;925 path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
857 return executeGit(926 return executeGit(
858 "GitCore.fetchUpstreamRefForStatus",927 "GitCore.fetchRemoteForStatus",
859 fetchCwd,928 fetchCwd,
860 ["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],929 ["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
861 {930 {
862 allowNonZeroExit: true,931 allowNonZeroExit: true,
863 timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),932 timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
@@ -873,20 +942,15 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 9 unmodified lines
873 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);942 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
874 });943 });
875 944
876 const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (945 const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
877 cacheKey: StatusUpstreamRefreshCacheKey,946 cacheKey: StatusRemoteRefreshCacheKey,
878 ) {947 ) {
879 yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {948 yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
880 upstreamRef: cacheKey.upstreamRef,
881 remoteName: cacheKey.remoteName,
882 upstreamBranch: cacheKey.upstreamBranch,
883 });
884 return true as const;949 return true as const;
885 });950 });
886 951
887 const statusUpstreamRefreshCache = yield* Cache.makeWith({952 const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
888 capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,953 capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
889 lookup: refreshStatusUpstreamCacheEntry,
890 // Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.954 // Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
891 timeToLive: (exit) =>955 timeToLive: (exit) =>
892 Exit.isSuccess(exit)956 Exit.isSuccess(exit)
@@ -901,12 +965,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 8 unmodified lines
901 if (!upstream) return;965 if (!upstream) return;
902 const gitCommonDir = yield* resolveGitCommonDir(cwd);966 const gitCommonDir = yield* resolveGitCommonDir(cwd);
903 yield* Cache.get(967 yield* Cache.get(
904 statusUpstreamRefreshCache,968 statusRemoteRefreshCache,
905 new StatusUpstreamRefreshCacheKey({969 new StatusRemoteRefreshCacheKey({
906 gitCommonDir,970 gitCommonDir,
907 upstreamRef: upstream.upstreamRef,
908 remoteName: upstream.remoteName,971 remoteName: upstream.remoteName,
909 upstreamBranch: upstream.upstreamBranch,
910 }),972 }),
911 );973 );
912 });974 });
@@ -1134,9 +1196,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 221 unmodified lines
1134 return branchLastCommit;1196 return branchLastCommit;
1135 });1197 });
1136 1198
1137 const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {1199 const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
1138 yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
1139
1140 const statusResult = yield* executeGit(1200 const statusResult = yield* executeGit(
1141 "GitCore.statusDetails.status",1201 "GitCore.statusDetails.status",
1142 cwd,1202 cwd,
@@ -1144,7 +1204,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 1 unmodified line
1144 {1204 {
1145 allowNonZeroExit: true,1205 allowNonZeroExit: true,
1146 },1206 },
1147 );1207 ).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
1208
1209 if (statusResult === null) {
1210 return NON_REPOSITORY_STATUS_DETAILS;
1211 }
1148 1212
1149 if (statusResult.code !== 0) {1213 if (statusResult.code !== 0) {
1150 const stderr = statusResult.stderr.trim();1214 const stderr = statusResult.stderr.trim();
@@ -1269,6 +1333,20 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 118 unmodified lines
1269 };1333 };
1270 });1334 });
1271 1335
1336 const statusDetailsLocal: GitCoreShape["statusDetailsLocal"] = Effect.fn("statusDetailsLocal")(
1337 function* (cwd) {
1338 return yield* readStatusDetailsLocal(cwd);
1339 },
1340 );
1341
1342 const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
1343 yield* refreshStatusUpstreamIfStale(cwd).pipe(
1344 Effect.catchIf(isMissingGitCwdError, () => Effect.void),
1345 Effect.ignoreCause({ log: true }),
1346 );
1347 return yield* readStatusDetailsLocal(cwd);
1348 });
1349
1272 const status: GitCoreShape["status"] = (input) =>1350 const status: GitCoreShape["status"] = (input) =>
1273 statusDetails(input.cwd).pipe(1351 statusDetails(input.cwd).pipe(
1274 Effect.map((details) => ({1352 Effect.map((details) => ({
@@ -1567,7 +1645,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 292 unmodified lines
1567 executeGit(1645 executeGit(
1568 "GitCore.listWorkspaceFiles",1646 "GitCore.listWorkspaceFiles",
1569 cwd,1647 cwd,
1570 ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],1648 [
1649 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
1650 "ls-files",
1651 "--cached",
1652 "--others",
1653 "--exclude-standard",
1654 "-z",
1655 ],
1571 {1656 {
1572 allowNonZeroExit: true,1657 allowNonZeroExit: true,
1573 timeoutMs: 20_000,1658 timeoutMs: 20_000,
@@ -1585,7 +1670,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 11 unmodified lines
1585 createGitCommandError(1670 createGitCommandError(
1586 "GitCore.listWorkspaceFiles",1671 "GitCore.listWorkspaceFiles",
1587 cwd,1672 cwd,
1588 ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],1673 [
1674 ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
1675 "ls-files",
1676 "--cached",
1677 "--others",
1678 "--exclude-standard",
1679 "-z",
1680 ],
1589 result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",1681 result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
1590 ),1682 ),
1591 ),1683 ),
@@ -1605,7 +1697,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 13 unmodified lines
1605 const result = yield* executeGit(1697 const result = yield* executeGit(
1606 "GitCore.filterIgnoredPaths",1698 "GitCore.filterIgnoredPaths",
1607 cwd,1699 cwd,
1608 ["check-ignore", "--no-index", "-z", "--stdin"],1700 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
1609 {1701 {
1610 stdin: `${chunk.join("\0")}\0`,1702 stdin: `${chunk.join("\0")}\0`,
1611 allowNonZeroExit: true,1703 allowNonZeroExit: true,
@@ -1619,7 +1711,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 7 unmodified lines
1619 return yield* createGitCommandError(1711 return yield* createGitCommandError(
1620 "GitCore.filterIgnoredPaths",1712 "GitCore.filterIgnoredPaths",
1621 cwd,1713 cwd,
1622 ["check-ignore", "--no-index", "-z", "--stdin"],1714 [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
1623 result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",1715 result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
1624 );1716 );
1625 }1717 }
@@ -1648,6 +1740,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 22 unmodified lines
1648 timeoutMs: 10_000,1740 timeoutMs: 10_000,
1649 allowNonZeroExit: true,1741 allowNonZeroExit: true,
1650 },1742 },
1743 ).pipe(
1744 Effect.catchIf(isMissingGitCwdError, () =>
1745 Effect.succeed({
1746 code: 128,
1747 stdout: "",
1748 stderr: "fatal: not a git repository",
1749 stdoutTruncated: false,
1750 stderrTruncated: false,
1751 }),
1752 ),
1651 );1753 );
1652 1754
1653 if (localBranchResult.code !== 0) {1755 if (localBranchResult.code !== 0) {
@@ -1930,7 +2032,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 276 unmodified lines
1930 "GitCore.removeWorktree",2032 "GitCore.removeWorktree",
1931 input.cwd,2033 input.cwd,
1932 args,2034 args,
1933 `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,2035 `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error.message}`,
1934 error,2036 error,
1935 ),2037 ),
1936 ),2038 ),
@@ -1957,12 +2059,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 20 unmodified lines
1957 return { branch: targetBranch };2059 return { branch: targetBranch };
1958 });2060 });
1959 2061
1960 const createBranch: GitCoreShape["createBranch"] = (input) =>
1961 executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
1962 timeoutMs: 10_000,
1963 fallbackErrorMessage: "git branch create failed",
1964 }).pipe(Effect.asVoid);
1965
1966 const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")(2062 const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")(
1967 function* (input) {2063 function* (input) {
1968 const [localInputExists, remoteExists] = yield* Effect.all(2064 const [localInputExists, remoteExists] = yield* Effect.all(
@@ -2035,9 +2131,28 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 66 unmodified lines
2035 timeoutMs: 10_000,2131 timeoutMs: 10_000,
2036 fallbackErrorMessage: "git checkout failed",2132 fallbackErrorMessage: "git checkout failed",
2037 });2133 });
2134
2135 const branch = yield* runGitStdout("GitCore.checkoutBranch.currentBranch", input.cwd, [
2136 "branch",
2137 "--show-current",
2138 ]).pipe(Effect.map((stdout) => stdout.trim() || null));
2139
2140 return { branch };
2038 },2141 },
2039 );2142 );
2040 2143
2144 const createBranch: GitCoreShape["createBranch"] = Effect.fn("createBranch")(function* (input) {
2145 yield* executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
2146 timeoutMs: 10_000,
2147 fallbackErrorMessage: "git branch create failed",
2148 });
2149 if (input.checkout) {
2150 yield* checkoutBranch({ cwd: input.cwd, branch: input.branch });
2151 }
2152
2153 return { branch: input.branch };
2154 });
2155
2041 const initRepo: GitCoreShape["initRepo"] = (input) =>2156 const initRepo: GitCoreShape["initRepo"] = (input) =>
2042 executeGit("GitCore.initRepo", input.cwd, ["init"], {2157 executeGit("GitCore.initRepo", input.cwd, ["init"], {
2043 timeoutMs: 10_000,2158 timeoutMs: 10_000,
@@ -2063,6 +2178,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 19 unmodified lines
2063 execute,2178 execute,
2064 status,2179 status,
2065 statusDetails,2180 statusDetails,
2181 statusDetailsLocal,
2066 prepareCommitContext,2182 prepareCommitContext,
2067 commit,2183 commit,
2068 pushCurrentBranch,2184 pushCurrentBranch,
apps/server/src/git/Layers/GitHubCli.test.ts+99−0
@@ -76,6 +76,105 @@ layer("GitHubCliLive", (it) => { · 75 unmodified lines
76 }),76 }),
77 );77 );
78 78
79 it.effect("trims pull request fields decoded from gh json", () =>
80 Effect.gen(function* () {
81 mockedRunProcess.mockResolvedValueOnce({
82 stdout: JSON.stringify({
83 number: 42,
84 title: " Add PR thread creation \n",
85 url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
86 baseRefName: " main ",
87 headRefName: "\tfeature/pr-threads\t",
88 state: "OPEN",
89 mergedAt: null,
90 isCrossRepository: true,
91 headRepository: {
92 nameWithOwner: " octocat/codething-mvp ",
93 },
94 headRepositoryOwner: {
95 login: " octocat ",
96 },
97 }),
98 stderr: "",
99 code: 0,
100 signal: null,
101 timedOut: false,
102 });
103
104 const result = yield* Effect.gen(function* () {
105 const gh = yield* GitHubCli;
106 return yield* gh.getPullRequest({
107 cwd: "/repo",
108 reference: "#42",
109 });
110 });
111
112 assert.deepStrictEqual(result, {
113 number: 42,
114 title: "Add PR thread creation",
115 url: "https://github.com/pingdotgg/codething-mvp/pull/42",
116 baseRefName: "main",
117 headRefName: "feature/pr-threads",
118 state: "open",
119 isCrossRepository: true,
120 headRepositoryNameWithOwner: "octocat/codething-mvp",
121 headRepositoryOwnerLogin: "octocat",
122 });
123 }),
124 );
125
126 it.effect("skips invalid entries when parsing pr lists", () =>
127 Effect.gen(function* () {
128 mockedRunProcess.mockResolvedValueOnce({
129 stdout: JSON.stringify([
130 {
131 number: 0,
132 title: "invalid",
133 url: "https://github.com/pingdotgg/codething-mvp/pull/0",
134 baseRefName: "main",
135 headRefName: "feature/invalid",
136 },
137 {
138 number: 43,
139 title: " Valid PR ",
140 url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
141 baseRefName: " main ",
142 headRefName: " feature/pr-list ",
143 headRepository: {
144 nameWithOwner: " ",
145 },
146 headRepositoryOwner: {
147 login: " ",
148 },
149 },
150 ]),
151 stderr: "",
152 code: 0,
153 signal: null,
154 timedOut: false,
155 });
156
157 const result = yield* Effect.gen(function* () {
158 const gh = yield* GitHubCli;
159 return yield* gh.listOpenPullRequests({
160 cwd: "/repo",
161 headSelector: "feature/pr-list",
162 });
163 });
164
165 assert.deepStrictEqual(result, [
166 {
167 number: 43,
168 title: "Valid PR",
169 url: "https://github.com/pingdotgg/codething-mvp/pull/43",
170 baseRefName: "main",
171 headRefName: "feature/pr-list",
172 state: "open",
173 },
174 ]);
175 }),
176 );
177
79 it.effect("reads repository clone URLs", () =>178 it.effect("reads repository clone URLs", () =>
80 Effect.gen(function* () {179 Effect.gen(function* () {
81 mockedRunProcess.mockResolvedValueOnce({180 mockedRunProcess.mockResolvedValueOnce({
apps/server/src/git/Layers/GitHubCli.ts+40−80
@@ -1,5 +1,5 @@
1import { Effect, Layer, Schema } from "effect";1import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
2import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";2import { TrimmedNonEmptyString } from "@t3tools/contracts";
3 3
4import { runProcess } from "../../processRunner";4import { runProcess } from "../../processRunner";
5import { GitHubCliError } from "@t3tools/contracts";5import { GitHubCliError } from "@t3tools/contracts";
@@ -7,8 +7,12 @@ import { · 1 unmodified line
7 GitHubCli,7 GitHubCli,
8 type GitHubRepositoryCloneUrls,8 type GitHubRepositoryCloneUrls,
9 type GitHubCliShape,9 type GitHubCliShape,
10 type GitHubPullRequestSummary,
11} from "../Services/GitHubCli.ts";10} from "../Services/GitHubCli.ts";
11import {
12 decodeGitHubPullRequestJson,
13 decodeGitHubPullRequestListJson,
14 formatGitHubJsonDecodeError,
15} from "../githubPullRequests.ts";
12 16
13const DEFAULT_TIMEOUT_MS = 30_000;17const DEFAULT_TIMEOUT_MS = 30_000;
14 18
@@ -63,76 +67,12 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown · 48 unmodified lines
63 });67 });
64}68}
65 69
66function normalizePullRequestState(input: {
67 state?: string | null | undefined;
68 mergedAt?: string | null | undefined;
69}): "open" | "closed" | "merged" {
70 const mergedAt = input.mergedAt;
71 const state = input.state;
72 if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
73 return "merged";
74 }
75 if (state === "CLOSED") {
76 return "closed";
77 }
78 return "open";
79}
80
81const RawGitHubPullRequestSchema = Schema.Struct({
82 number: PositiveInt,
83 title: TrimmedNonEmptyString,
84 url: TrimmedNonEmptyString,
85 baseRefName: TrimmedNonEmptyString,
86 headRefName: TrimmedNonEmptyString,
87 state: Schema.optional(Schema.NullOr(Schema.String)),
88 mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
89 isCrossRepository: Schema.optional(Schema.Boolean),
90 headRepository: Schema.optional(
91 Schema.NullOr(
92 Schema.Struct({
93 nameWithOwner: Schema.String,
94 }),
95 ),
96 ),
97 headRepositoryOwner: Schema.optional(
98 Schema.NullOr(
99 Schema.Struct({
100 login: Schema.String,
101 }),
102 ),
103 ),
104});
105
106const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({70const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
107 nameWithOwner: TrimmedNonEmptyString,71 nameWithOwner: TrimmedNonEmptyString,
108 url: TrimmedNonEmptyString,72 url: TrimmedNonEmptyString,
109 sshUrl: TrimmedNonEmptyString,73 sshUrl: TrimmedNonEmptyString,
110});74});
111 75
112function normalizePullRequestSummary(
113 raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
114): GitHubPullRequestSummary {
115 const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
116 const headRepositoryOwnerLogin =
117 raw.headRepositoryOwner?.login ??
118 (typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
119 ? (headRepositoryNameWithOwner.split("/")[0] ?? null)
120 : null);
121 return {
122 number: raw.number,
123 title: raw.title,
124 url: raw.url,
125 baseRefName: raw.baseRefName,
126 headRefName: raw.headRefName,
127 state: normalizePullRequestState(raw),
128 ...(typeof raw.isCrossRepository === "boolean"
129 ? { isCrossRepository: raw.isCrossRepository }
130 : {}),
131 ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
132 ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
133 };
134}
135
136function normalizeRepositoryCloneUrls(76function normalizeRepositoryCloneUrls(
137 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,77 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
138): GitHubRepositoryCloneUrls {78): GitHubRepositoryCloneUrls {
@@ -154,7 +94,7 @@ function decodeGitHubJson<S extends Schema.Top>( · 15 unmodified lines
154 (error) =>94 (error) =>
155 new GitHubCliError({95 new GitHubCliError({
156 operation,96 operation,
157 detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,97 detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
158 cause: error,98 cause: error,
159 }),99 }),
160 ),100 ),
@@ -194,14 +134,24 @@ const makeGitHubCli = Effect.sync(() => { · 33 unmodified lines
194 Effect.flatMap((raw) =>134 Effect.flatMap((raw) =>
195 raw.length === 0135 raw.length === 0
196 ? Effect.succeed([])136 ? Effect.succeed([])
197 : decodeGitHubJson(137 : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
198 raw,138 Effect.flatMap((decoded) => {
199 Schema.Array(RawGitHubPullRequestSchema),139 if (!Result.isSuccess(decoded)) {
200 "listOpenPullRequests",140 return Effect.fail(
201 "GitHub CLI returned invalid PR list JSON.",141 new GitHubCliError({
142 operation: "listOpenPullRequests",
143 detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
144 cause: decoded.failure,
145 }),
146 );
147 }
148
149 return Effect.succeed(
150 decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
151 );
152 }),
202 ),153 ),
203 ),154 ),
204 Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
205 ),155 ),
206 getPullRequest: (input) =>156 getPullRequest: (input) =>
207 execute({157 execute({
@@ -216,14 +166,24 @@ const makeGitHubCli = Effect.sync(() => { · 8 unmodified lines
216 }).pipe(166 }).pipe(
217 Effect.map((result) => result.stdout.trim()),167 Effect.map((result) => result.stdout.trim()),
218 Effect.flatMap((raw) =>168 Effect.flatMap((raw) =>
219 decodeGitHubJson(169 Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
220 raw,170 Effect.flatMap((decoded) => {
221 RawGitHubPullRequestSchema,171 if (!Result.isSuccess(decoded)) {
222 "getPullRequest",172 return Effect.fail(
223 "GitHub CLI returned invalid pull request JSON.",173 new GitHubCliError({
174 operation: "getPullRequest",
175 detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
176 cause: decoded.failure,
177 }),
178 );
179 }
180
181 return Effect.succeed(
182 (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
183 );
184 }),
224 ),185 ),
225 ),186 ),
226 Effect.map(normalizePullRequestSummary),
227 ),187 ),
228 getRepositoryCloneUrls: (input) =>188 getRepositoryCloneUrls: (input) =>
229 execute({189 execute({
apps/server/src/git/Layers/GitManager.test.ts+316−5
@@ -6,7 +6,12 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; · 5 unmodified lines
6import { it } from "@effect/vitest";6import { it } from "@effect/vitest";
7import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";7import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
8import { expect } from "vitest";8import { expect } from "vitest";
9import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";9import type {
10 GitActionProgressEvent,
11 GitPreparePullRequestThreadInput,
12 ModelSelection,
13 ThreadId,
14} from "@t3tools/contracts";
10 15
11import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";16import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
12import { type GitManagerShape } from "../Services/GitManager.ts";17import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -21,6 +26,11 @@ import { GitCore } from "../Services/GitCore.ts"; · 8 unmodified lines
21import { makeGitManager } from "./GitManager.ts";26import { makeGitManager } from "./GitManager.ts";
22import { ServerConfig } from "../../config.ts";27import { ServerConfig } from "../../config.ts";
23import { ServerSettingsService } from "../../serverSettings.ts";28import { ServerSettingsService } from "../../serverSettings.ts";
29import {
30 ProjectSetupScriptRunner,
31 type ProjectSetupScriptRunnerInput,
32 type ProjectSetupScriptRunnerShape,
33} from "../../project/Services/ProjectSetupScriptRunner.ts";
24 34
25interface FakeGhScenario {35interface FakeGhScenario {
26 prListSequence?: string[];36 prListSequence?: string[];
@@ -176,6 +186,24 @@ function makeTempDir( · 149 unmodified lines
176 });186 });
177}187}
178 188
189function removePath(
190 targetPath: string,
191): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
192 return Effect.gen(function* () {
193 const fileSystem = yield* FileSystem.FileSystem;
194 yield* fileSystem.remove(targetPath, { recursive: true, force: true });
195 });
196}
197
198function makeDirectory(
199 dirPath: string,
200): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
201 return Effect.gen(function* () {
202 const fileSystem = yield* FileSystem.FileSystem;
203 yield* fileSystem.makeDirectory(dirPath, { recursive: true });
204 });
205}
206
179function runGit(207function runGit(
180 cwd: string,208 cwd: string,
181 args: readonly string[],209 args: readonly string[],
@@ -593,7 +621,7 @@ function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; refe · 411 unmodified lines
593 621
594function preparePullRequestThread(622function preparePullRequestThread(
595 manager: GitManagerShape,623 manager: GitManagerShape,
596 input: { cwd: string; reference: string; mode: "local" | "worktree" },624 input: GitPreparePullRequestThreadInput,
597) {625) {
598 return manager.preparePullRequestThread(input);626 return manager.preparePullRequestThread(input);
599}627}
@@ -601,6 +629,7 @@ function preparePullRequestThread( · 1 unmodified line
601function makeManager(input?: {629function makeManager(input?: {
602 ghScenario?: FakeGhScenario;630 ghScenario?: FakeGhScenario;
603 textGeneration?: Partial<FakeGitTextGeneration>;631 textGeneration?: Partial<FakeGitTextGeneration>;
632 setupScriptRunner?: ProjectSetupScriptRunnerShape;
604}) {633}) {
605 const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);634 const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
606 const textGeneration = createTextGeneration(input?.textGeneration);635 const textGeneration = createTextGeneration(input?.textGeneration);
@@ -618,6 +647,12 @@ function makeManager(input?: { · 11 unmodified lines
618 const managerLayer = Layer.mergeAll(647 const managerLayer = Layer.mergeAll(
619 Layer.succeed(GitHubCli, gitHubCli),648 Layer.succeed(GitHubCli, gitHubCli),
620 Layer.succeed(TextGeneration, textGeneration),649 Layer.succeed(TextGeneration, textGeneration),
650 Layer.succeed(
651 ProjectSetupScriptRunner,
652 input?.setupScriptRunner ?? {
653 runForThread: () => Effect.succeed({ status: "no-script" as const }),
654 },
655 ),
621 gitCoreLayer,656 gitCoreLayer,
622 serverSettingsLayer,657 serverSettingsLayer,
623 ).pipe(Layer.provideMerge(NodeServices.layer));658 ).pipe(Layer.provideMerge(NodeServices.layer));
@@ -628,6 +663,8 @@ function makeManager(input?: { · 4 unmodified lines
628 );663 );
629}664}
630 665
666const asThreadId = (threadId: string) => threadId as ThreadId;
667
631const GitManagerTestLayer = GitCoreLive.pipe(668const GitManagerTestLayer = GitCoreLive.pipe(
632 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),669 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
633 Layer.provideMerge(NodeServices.layer),670 Layer.provideMerge(NodeServices.layer),
@@ -675,6 +712,144 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 41 unmodified lines
675 }),712 }),
676 );713 );
677 714
715 it.effect("status trims PR metadata returned by gh before publishing it", () =>
716 Effect.gen(function* () {
717 const repoDir = yield* makeTempDir("t3code-git-manager-");
718 yield* initRepo(repoDir);
719 yield* runGit(repoDir, ["checkout", "-b", "feature/status-trimmed-pr"]);
720 const remoteDir = yield* createBareRemote();
721 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
722 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-trimmed-pr"]);
723
724 const { manager } = yield* makeManager({
725 ghScenario: {
726 prListSequence: [
727 JSON.stringify([
728 {
729 number: 14,
730 title: " Existing PR title \n",
731 url: " https://github.com/pingdotgg/codething-mvp/pull/14 ",
732 baseRefName: " main ",
733 headRefName: "\tfeature/status-trimmed-pr\t",
734 },
735 ]),
736 ],
737 },
738 });
739
740 const status = yield* manager.status({ cwd: repoDir });
741
742 expect(status.pr).toEqual({
743 number: 14,
744 title: "Existing PR title",
745 url: "https://github.com/pingdotgg/codething-mvp/pull/14",
746 baseBranch: "main",
747 headBranch: "feature/status-trimmed-pr",
748 state: "open",
749 });
750 }),
751 );
752
753 it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
754 Effect.gen(function* () {
755 const repoDir = yield* makeTempDir("t3code-git-manager-");
756 yield* initRepo(repoDir);
757 yield* runGit(repoDir, ["checkout", "-b", "feature/status-valid-pr-entry"]);
758 const remoteDir = yield* createBareRemote();
759 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
760 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-valid-pr-entry"]);
761
762 const { manager } = yield* makeManager({
763 ghScenario: {
764 prListSequence: [
765 JSON.stringify([
766 {
767 number: 0,
768 title: "invalid",
769 url: "https://github.com/pingdotgg/codething-mvp/pull/0",
770 baseRefName: "main",
771 headRefName: "feature/invalid",
772 },
773 {
774 number: 15,
775 title: " Valid PR title ",
776 url: " https://github.com/pingdotgg/codething-mvp/pull/15 ",
777 baseRefName: " main ",
778 headRefName: "\tfeature/status-valid-pr-entry\t",
779 headRepository: {
780 nameWithOwner: " ",
781 },
782 headRepositoryOwner: {
783 login: " ",
784 },
785 },
786 ]),
787 ],
788 },
789 });
790
791 const status = yield* manager.status({ cwd: repoDir });
792
793 expect(status.pr).toEqual({
794 number: 15,
795 title: "Valid PR title",
796 url: "https://github.com/pingdotgg/codething-mvp/pull/15",
797 baseBranch: "main",
798 headBranch: "feature/status-valid-pr-entry",
799 state: "open",
800 });
801 }),
802 );
803
804 it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
805 Effect.gen(function* () {
806 const repoDir = yield* makeTempDir("t3code-git-manager-");
807 yield* initRepo(repoDir);
808 yield* runGit(repoDir, ["checkout", "-b", "feature/status-lowercase-state"]);
809 const remoteDir = yield* createBareRemote();
810 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
811 yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-lowercase-state"]);
812
813 const { manager } = yield* makeManager({
814 ghScenario: {
815 prListSequence: [
816 JSON.stringify([
817 {
818 number: 16,
819 title: "Closed PR",
820 url: "https://github.com/pingdotgg/codething-mvp/pull/16",
821 baseRefName: "main",
822 headRefName: "feature/status-lowercase-state",
823 state: "closed",
824 updatedAt: "2026-01-01T00:00:00.000Z",
825 },
826 {
827 number: 17,
828 title: "Merged PR",
829 url: "https://github.com/pingdotgg/codething-mvp/pull/17",
830 baseRefName: "main",
831 headRefName: "feature/status-lowercase-state",
832 state: "merged",
833 updatedAt: "2026-01-02T00:00:00.000Z",
834 },
835 ]),
836 ],
837 },
838 });
839
840 const status = yield* manager.status({ cwd: repoDir });
841
842 expect(status.pr).toEqual({
843 number: 17,
844 title: "Merged PR",
845 url: "https://github.com/pingdotgg/codething-mvp/pull/17",
846 baseBranch: "main",
847 headBranch: "feature/status-lowercase-state",
848 state: "merged",
849 });
850 }),
851 );
852
678 it.effect("status returns an explicit non-repo result for non-git directories", () =>853 it.effect("status returns an explicit non-repo result for non-git directories", () =>
679 Effect.gen(function* () {854 Effect.gen(function* () {
680 const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");855 const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
@@ -701,6 +876,35 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 20 unmodified lines
701 }),876 }),
702 );877 );
703 878
879 it.effect("status returns an explicit non-repo result for deleted directories", () =>
880 Effect.gen(function* () {
881 const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
882 const cwd = path.join(rootDir, "deleted-repo");
883 yield* makeDirectory(cwd);
884 yield* removePath(cwd);
885 const { manager } = yield* makeManager();
886
887 const status = yield* manager.status({ cwd });
888
889 expect(status).toEqual({
890 isRepo: false,
891 hasOriginRemote: false,
892 isDefaultBranch: false,
893 branch: null,
894 hasWorkingTreeChanges: false,
895 workingTree: {
896 files: [],
897 insertions: 0,
898 deletions: 0,
899 },
900 hasUpstream: false,
901 aheadCount: 0,
902 behindCount: 0,
903 pr: null,
904 });
905 }),
906 );
907
704 it.effect("status briefly caches repeated lookups for the same cwd", () =>908 it.effect("status briefly caches repeated lookups for the same cwd", () =>
705 Effect.gen(function* () {909 Effect.gen(function* () {
706 const repoDir = yield* makeTempDir("t3code-git-manager-");910 const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -835,7 +1039,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 128 unmodified lines
835 "pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",1039 "pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
836 );1040 );
837 }),1041 }),
838 12_000,1042 20_000,
839 );1043 );
840 1044
841 it.effect(1045 it.effect(
@@ -943,7 +1147,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 101 unmodified lines
943 ),1147 ),
944 ).toBe(false);1148 ).toBe(false);
945 }),1149 }),
946 12_000,1150 20_000,
947 );1151 );
948 1152
949 it.effect("status returns merged PR state when latest PR was merged", () =>1153 it.effect("status returns merged PR state when latest PR was merged", () =>
@@ -1666,7 +1870,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 716 unmodified lines
1666 false,1870 false,
1667 );1871 );
1668 }),1872 }),
1669 12_000,1873 20_000,
1670 );1874 );
1671 1875
1672 it.effect(1876 it.effect(
@@ -2176,6 +2380,59 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 503 unmodified lines
2176 }),2380 }),
2177 );2381 );
2178 2382
2383 it.effect("launches setup only when creating a new PR worktree", () =>
2384 Effect.gen(function* () {
2385 const repoDir = yield* makeTempDir("t3code-git-manager-");
2386 yield* initRepo(repoDir);
2387 const remoteDir = yield* createBareRemote();
2388 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
2389 yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
2390 yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree-setup"]);
2391 fs.writeFileSync(path.join(repoDir, "setup.txt"), "setup\n");
2392 yield* runGit(repoDir, ["add", "setup.txt"]);
2393 yield* runGit(repoDir, ["commit", "-m", "PR worktree setup branch"]);
2394 yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree-setup"]);
2395 yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/177/head"]);
2396 yield* runGit(repoDir, ["checkout", "main"]);
2397
2398 const setupCalls: ProjectSetupScriptRunnerInput[] = [];
2399 const { manager } = yield* makeManager({
2400 ghScenario: {
2401 pullRequest: {
2402 number: 177,
2403 title: "Worktree setup PR",
2404 url: "https://github.com/pingdotgg/codething-mvp/pull/177",
2405 baseRefName: "main",
2406 headRefName: "feature/pr-worktree-setup",
2407 state: "open",
2408 },
2409 },
2410 setupScriptRunner: {
2411 runForThread: (setupInput) =>
2412 Effect.sync(() => {
2413 setupCalls.push(setupInput);
2414 return { status: "no-script" as const };
2415 }),
2416 },
2417 });
2418
2419 const result = yield* preparePullRequestThread(manager, {
2420 cwd: repoDir,
2421 reference: "177",
2422 mode: "worktree",
2423 threadId: asThreadId("thread-pr-setup"),
2424 });
2425
2426 expect(result.worktreePath).not.toBeNull();
2427 expect(setupCalls).toHaveLength(1);
2428 expect(setupCalls[0]).toEqual({
2429 threadId: "thread-pr-setup",
2430 projectCwd: repoDir,
2431 worktreePath: result.worktreePath as string,
2432 });
2433 }),
2434 );
2435
2179 it.effect("preserves fork upstream tracking when preparing a worktree PR thread", () =>2436 it.effect("preserves fork upstream tracking when preparing a worktree PR thread", () =>
2180 Effect.gen(function* () {2437 Effect.gen(function* () {
2181 const repoDir = yield* makeTempDir("t3code-git-manager-");2438 const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2360,6 +2617,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 178 unmodified lines
2360 const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`);2617 const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`);
2361 yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);2618 yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);
2362 2619
2620 const setupCalls: ProjectSetupScriptRunnerInput[] = [];
2363 const { manager } = yield* makeManager({2621 const { manager } = yield* makeManager({
2364 ghScenario: {2622 ghScenario: {
2365 pullRequest: {2623 pullRequest: {
@@ -2371,18 +2629,27 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 5 unmodified lines
2371 state: "open",2629 state: "open",
2372 },2630 },
2373 },2631 },
2632 setupScriptRunner: {
2633 runForThread: (setupInput) =>
2634 Effect.sync(() => {
2635 setupCalls.push(setupInput);
2636 return { status: "no-script" as const };
2637 }),
2638 },
2374 });2639 });
2375 2640
2376 const result = yield* preparePullRequestThread(manager, {2641 const result = yield* preparePullRequestThread(manager, {
2377 cwd: repoDir,2642 cwd: repoDir,
2378 reference: "78",2643 reference: "78",
2379 mode: "worktree",2644 mode: "worktree",
2645 threadId: asThreadId("thread-pr-existing-worktree"),
2380 });2646 });
2381 2647
2382 expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe(2648 expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe(
2383 fs.realpathSync.native(worktreePath),2649 fs.realpathSync.native(worktreePath),
2384 );2650 );
2385 expect(result.branch).toBe("feature/pr-existing-worktree");2651 expect(result.branch).toBe("feature/pr-existing-worktree");
2652 expect(setupCalls).toHaveLength(0);
2386 }),2653 }),
2387 );2654 );
2388 2655
@@ -2562,6 +2829,50 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 173 unmodified lines
2562 }),2829 }),
2563 );2830 );
2564 2831
2832 it.effect("does not fail PR worktree prep when setup terminal startup fails", () =>
2833 Effect.gen(function* () {
2834 const repoDir = yield* makeTempDir("t3code-git-manager-");
2835 yield* initRepo(repoDir);
2836 const remoteDir = yield* createBareRemote();
2837 yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
2838 yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
2839 yield* runGit(repoDir, ["checkout", "-b", "feature/pr-setup-failure"]);
2840 fs.writeFileSync(path.join(repoDir, "setup-failure.txt"), "setup failure\n");
2841 yield* runGit(repoDir, ["add", "setup-failure.txt"]);
2842 yield* runGit(repoDir, ["commit", "-m", "PR setup failure branch"]);
2843 yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-setup-failure"]);
2844 yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/184/head"]);
2845 yield* runGit(repoDir, ["checkout", "main"]);
2846
2847 const { manager } = yield* makeManager({
2848 ghScenario: {
2849 pullRequest: {
2850 number: 184,
2851 title: "Setup failure PR",
2852 url: "https://github.com/pingdotgg/codething-mvp/pull/184",
2853 baseRefName: "main",
2854 headRefName: "feature/pr-setup-failure",
2855 state: "open",
2856 },
2857 },
2858 setupScriptRunner: {
2859 runForThread: () => Effect.fail(new Error("terminal start failed")),
2860 },
2861 });
2862
2863 const result = yield* preparePullRequestThread(manager, {
2864 cwd: repoDir,
2865 reference: "184",
2866 mode: "worktree",
2867 threadId: asThreadId("thread-pr-setup-failure"),
2868 });
2869
2870 expect(result.branch).toBe("feature/pr-setup-failure");
2871 expect(result.worktreePath).not.toBeNull();
2872 expect(fs.existsSync(result.worktreePath as string)).toBe(true);
2873 }),
2874 );
2875
2565 it.effect("rejects worktree prep when the PR head branch is checked out in the main repo", () =>2876 it.effect("rejects worktree prep when the PR head branch is checked out in the main repo", () =>
2566 Effect.gen(function* () {2877 Effect.gen(function* () {
2567 const repoDir = yield* makeTempDir("t3code-git-manager-");2878 const repoDir = yield* makeTempDir("t3code-git-manager-");
apps/server/src/git/Layers/GitManager.ts+155−118
@@ -1,16 +1,31 @@
1import { randomUUID } from "node:crypto";1import { randomUUID } from "node:crypto";
2import { realpathSync } from "node:fs";2import { realpathSync } from "node:fs";
3 3
4import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } from "effect";4import {
5 Cache,
6 Duration,
7 Effect,
8 Exit,
9 FileSystem,
10 Layer,
11 Option,
12 Path,
13 Ref,
14 Result,
15} from "effect";
5import {16import {
6 GitActionProgressEvent,17 GitActionProgressEvent,
7 GitActionProgressPhase,18 GitActionProgressPhase,
8 GitCommandError,19 GitCommandError,
9 GitRunStackedActionResult,20 GitRunStackedActionResult,
10 GitStackedAction,21 GitStackedAction,
22 type GitStatusLocalResult,
23 type GitStatusRemoteResult,
11 ModelSelection,24 ModelSelection,
12} from "@t3tools/contracts";25} from "@t3tools/contracts";
13import {26import {
27 detectGitHostingProviderFromRemoteUrl,
28 mergeGitStatusParts,
14 resolveAutoFeatureBranchName,29 resolveAutoFeatureBranchName,
15 sanitizeBranchFragment,30 sanitizeBranchFragment,
16 sanitizeFeatureBranchName,31 sanitizeFeatureBranchName,
@@ -26,9 +41,14 @@ import { · 9 unmodified lines
26import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";41import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";
27import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";42import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
28import { TextGeneration } from "../Services/TextGeneration.ts";43import { TextGeneration } from "../Services/TextGeneration.ts";
44import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
29import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";45import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
30import { ServerSettingsService } from "../../serverSettings.ts";46import { ServerSettingsService } from "../../serverSettings.ts";
31import type { GitManagerServiceError } from "@t3tools/contracts";47import type { GitManagerServiceError } from "@t3tools/contracts";
48import {
49 decodeGitHubPullRequestListJson,
50 formatGitHubJsonDecodeError,
51} from "../githubPullRequests.ts";
32 52
33const COMMIT_TIMEOUT_MS = 10 * 60_000;53const COMMIT_TIMEOUT_MS = 10 * 60_000;
34const MAX_PROGRESS_TEXT_LENGTH = 500;54const MAX_PROGRESS_TEXT_LENGTH = 500;
@@ -235,85 +255,6 @@ function matchesBranchHeadContext( · 200 unmodified lines
235 return true;255 return true;
236}256}
237 257
238function parsePullRequestList(raw: unknown): PullRequestInfo[] {
239 if (!Array.isArray(raw)) return [];
240
241 const parsed: PullRequestInfo[] = [];
242 for (const entry of raw) {
243 if (!entry || typeof entry !== "object") continue;
244 const record = entry as Record<string, unknown>;
245 const number = record.number;
246 const title = record.title;
247 const url = record.url;
248 const baseRefName = record.baseRefName;
249 const headRefName = record.headRefName;
250 const state = record.state;
251 const mergedAt = record.mergedAt;
252 const updatedAt = record.updatedAt;
253 const isCrossRepository = record.isCrossRepository;
254 const headRepositoryRecord =
255 typeof record.headRepository === "object" && record.headRepository !== null
256 ? (record.headRepository as Record<string, unknown>)
257 : null;
258 const headRepositoryOwnerRecord =
259 typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null
260 ? (record.headRepositoryOwner as Record<string, unknown>)
261 : null;
262 const headRepositoryNameWithOwner =
263 typeof record.headRepositoryNameWithOwner === "string"
264 ? record.headRepositoryNameWithOwner
265 : typeof headRepositoryRecord?.nameWithOwner === "string"
266 ? headRepositoryRecord.nameWithOwner
267 : null;
268 const headRepositoryOwnerLogin =
269 typeof record.headRepositoryOwnerLogin === "string"
270 ? record.headRepositoryOwnerLogin
271 : typeof headRepositoryOwnerRecord?.login === "string"
272 ? headRepositoryOwnerRecord.login
273 : null;
274 if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
275 continue;
276 }
277 if (
278 typeof title !== "string" ||
279 typeof url !== "string" ||
280 typeof baseRefName !== "string" ||
281 typeof headRefName !== "string"
282 ) {
283 continue;
284 }
285
286 let normalizedState: "open" | "closed" | "merged";
287 if (
288 (typeof mergedAt === "string" && mergedAt.trim().length > 0) ||
289 state === "MERGED" ||
290 state === "merged"
291 ) {
292 normalizedState = "merged";
293 } else if (state === "OPEN" || state === "open" || state === undefined || state === null) {
294 normalizedState = "open";
295 } else if (state === "CLOSED" || state === "closed") {
296 normalizedState = "closed";
297 } else {
298 continue;
299 }
300
301 parsed.push({
302 number,
303 title,
304 url,
305 baseRefName,
306 headRefName,
307 state: normalizedState,
308 updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
309 ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
310 ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
311 ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
312 });
313 }
314 return parsed;
315}
316
317function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {258function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
318 return {259 return {
319 number: summary.number,260 number: summary.number,
@@ -552,6 +493,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 232 unmodified lines
552 const gitCore = yield* GitCore;493 const gitCore = yield* GitCore;
553 const gitHubCli = yield* GitHubCli;494 const gitHubCli = yield* GitHubCli;
554 const textGeneration = yield* TextGeneration;495 const textGeneration = yield* TextGeneration;
496 const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
555 const serverSettingsService = yield* ServerSettingsService;497 const serverSettingsService = yield* ServerSettingsService;
556 498
557 const createProgressEmitter = (499 const createProgressEmitter = (
@@ -693,26 +635,54 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 135 unmodified lines
693 635
694 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";636 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
695 const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);637 const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
696 const readStatus = Effect.fn("readStatus")(function* (cwd: string) {638 const nonRepositoryStatusDetails = {
697 const details = yield* gitCore.statusDetails(cwd).pipe(639 isRepo: false,
698 Effect.catchIf(isNotGitRepositoryError, () =>640 hasOriginRemote: false,
699 Effect.succeed({641 isDefaultBranch: false,
700 isRepo: false,642 branch: null,
701 hasOriginRemote: false,643 upstreamRef: null,
702 isDefaultBranch: false,644 hasWorkingTreeChanges: false,
703 branch: null,645 workingTree: { files: [], insertions: 0, deletions: 0 },
704 upstreamRef: null,646 hasUpstream: false,
705 hasWorkingTreeChanges: false,647 aheadCount: 0,
706 workingTree: { files: [], insertions: 0, deletions: 0 },648 behindCount: 0,
707 hasUpstream: false,649 } satisfies GitStatusDetails;
708 aheadCount: 0,650 const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
709 behindCount: 0,651 const details = yield* gitCore
710 } satisfies GitStatusDetails),652 .statusDetailsLocal(cwd)
711 ),653 .pipe(
712 );654 Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)),
655 );
656 const hostingProvider = details.isRepo
657 ? yield* resolveHostingProvider(cwd, details.branch)
658 : null;
659
660 return {
661 isRepo: details.isRepo,
662 ...(hostingProvider ? { hostingProvider } : {}),
663 hasOriginRemote: details.hasOriginRemote,
664 isDefaultBranch: details.isDefaultBranch,
665 branch: details.branch,
666 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
667 workingTree: details.workingTree,
668 } satisfies GitStatusLocalResult;
669 });
670 const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
671 capacity: STATUS_RESULT_CACHE_CAPACITY,
672 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
673 });
674 const invalidateLocalStatusResultCache = (cwd: string) =>
675 Cache.invalidate(localStatusResultCache, normalizeStatusCacheKey(cwd));
676 const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
677 const details = yield* gitCore
678 .statusDetails(cwd)
679 .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
680 if (details === null || !details.isRepo) {
681 return null;
682 }
713 683
714 const pr =684 const pr =
715 details.isRepo && details.branch !== null685 details.branch !== null
716 ? yield* findLatestPr(cwd, {686 ? yield* findLatestPr(cwd, {
717 branch: details.branch,687 branch: details.branch,
718 upstreamRef: details.upstreamRef,688 upstreamRef: details.upstreamRef,
@@ -723,29 +693,37 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 4 unmodified lines
723 : null;693 : null;
724 694
725 return {695 return {
726 isRepo: details.isRepo,
727 hasOriginRemote: details.hasOriginRemote,
728 isDefaultBranch: details.isDefaultBranch,
729 branch: details.branch,
730 hasWorkingTreeChanges: details.hasWorkingTreeChanges,
731 workingTree: details.workingTree,
732 hasUpstream: details.hasUpstream,696 hasUpstream: details.hasUpstream,
733 aheadCount: details.aheadCount,697 aheadCount: details.aheadCount,
734 behindCount: details.behindCount,698 behindCount: details.behindCount,
735 pr,699 pr,
736 };700 } satisfies GitStatusRemoteResult;
737 });701 });
738 const statusResultCache = yield* Cache.makeWith({702 const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
739 capacity: STATUS_RESULT_CACHE_CAPACITY,703 capacity: STATUS_RESULT_CACHE_CAPACITY,
740 lookup: readStatus,
741 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),704 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
742 });705 });
743 const invalidateStatusResultCache = (cwd: string) =>706 const invalidateRemoteStatusResultCache = (cwd: string) =>
744 Cache.invalidate(statusResultCache, normalizeStatusCacheKey(cwd));707 Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
745 708
746 const readConfigValueNullable = (cwd: string, key: string) =>709 const readConfigValueNullable = (cwd: string, key: string) =>
747 gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));710 gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
748 711
712 const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
713 cwd: string,
714 branch: string | null,
715 ) {
716 const preferredRemoteName =
717 branch === null
718 ? "origin"
719 : ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin");
720 const remoteUrl =
721 (yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
722 (yield* readConfigValueNullable(cwd, "remote.origin.url"));
723
724 return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
725 });
726
749 const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (727 const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
750 cwd: string,728 cwd: string,
751 remoteName: string | null,729 remoteName: string | null,
@@ -905,13 +883,23 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 153 unmodified lines
905 continue;883 continue;
906 }884 }
907 885
908 const parsedJson = yield* Effect.try({886 const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
909 try: () => JSON.parse(raw) as unknown,887 Effect.flatMap((decoded) => {
910 catch: (cause) =>888 if (!Result.isSuccess(decoded)) {
911 gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),889 return Effect.fail(
912 });890 gitManagerError(
891 "findLatestPr",
892 `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
893 decoded.failure,
894 ),
895 );
896 }
897
898 return Effect.succeed(decoded.success);
899 }),
900 );
913 901
914 for (const pr of parsePullRequestList(parsedJson)) {902 for (const pr of pullRequests) {
915 if (!matchesBranchHeadContext(pr, headContext)) {903 if (!matchesBranchHeadContext(pr, headContext)) {
916 continue;904 continue;
917 }905 }
@@ -1309,9 +1297,34 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 391 unmodified lines
1309 };1297 };
1310 });1298 });
1311 1299
1300 const localStatus: GitManagerShape["localStatus"] = Effect.fn("localStatus")(function* (input) {
1301 return yield* Cache.get(localStatusResultCache, normalizeStatusCacheKey(input.cwd));
1302 });
1303 const remoteStatus: GitManagerShape["remoteStatus"] = Effect.fn("remoteStatus")(
1304 function* (input) {
1305 return yield* Cache.get(remoteStatusResultCache, normalizeStatusCacheKey(input.cwd));
1306 },
1307 );
1312 const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {1308 const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) {
1313 return yield* Cache.get(statusResultCache, normalizeStatusCacheKey(input.cwd));1309 const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
1310 return mergeGitStatusParts(local, remote);
1311 });
1312 const invalidateLocalStatus: GitManagerShape["invalidateLocalStatus"] = Effect.fn(
1313 "invalidateLocalStatus",
1314 )(function* (cwd) {
1315 yield* invalidateLocalStatusResultCache(cwd);
1316 });
1317 const invalidateRemoteStatus: GitManagerShape["invalidateRemoteStatus"] = Effect.fn(
1318 "invalidateRemoteStatus",
1319 )(function* (cwd) {
1320 yield* invalidateRemoteStatusResultCache(cwd);
1314 });1321 });
1322 const invalidateStatus: GitManagerShape["invalidateStatus"] = Effect.fn("invalidateStatus")(
1323 function* (cwd) {
1324 yield* invalidateLocalStatusResultCache(cwd);
1325 yield* invalidateRemoteStatusResultCache(cwd);
1326 },
1327 );
1315 1328
1316 const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(1329 const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
1317 function* (input) {1330 function* (input) {
@@ -1329,6 +1342,24 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 11 unmodified lines
1329 const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn(1342 const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn(
1330 "preparePullRequestThread",1343 "preparePullRequestThread",
1331 )(function* (input) {1344 )(function* (input) {
1345 const maybeRunSetupScript = (worktreePath: string) => {
1346 if (!input.threadId) {
1347 return Effect.void;
1348 }
1349 return projectSetupScriptRunner
1350 .runForThread({
1351 threadId: input.threadId,
1352 projectCwd: input.cwd,
1353 worktreePath,
1354 })
1355 .pipe(
1356 Effect.catch((error) =>
1357 Effect.logWarning(
1358 `GitManager.preparePullRequestThread: failed to launch worktree setup script for thread ${input.threadId} in ${worktreePath}: ${error.message}`,
1359 ).pipe(Effect.asVoid),
1360 ),
1361 );
1362 };
1332 return yield* Effect.gen(function* () {1363 return yield* Effect.gen(function* () {
1333 const normalizedReference = normalizePullRequestReference(input.reference);1364 const normalizedReference = normalizePullRequestReference(input.reference);
1334 const rootWorktreePath = canonicalizeExistingPath(input.cwd);1365 const rootWorktreePath = canonicalizeExistingPath(input.cwd);
@@ -1461,13 +1492,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 126 unmodified lines
1461 path: null,1492 path: null,
1462 });1493 });
1463 yield* ensureExistingWorktreeUpstream(worktree.worktree.path);1494 yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
1495 yield* maybeRunSetupScript(worktree.worktree.path);
1464 1496
1465 return {1497 return {
1466 pullRequest,1498 pullRequest,
1467 branch: worktree.worktree.branch,1499 branch: worktree.worktree.branch,
1468 worktreePath: worktree.worktree.path,1500 worktreePath: worktree.worktree.path,
1469 };1501 };
1470 }).pipe(Effect.ensuring(invalidateStatusResultCache(input.cwd)));1502 }).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
1471 });1503 });
1472 1504
1473 const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (1505 const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
@@ -1671,7 +1703,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 197 unmodified lines
1671 });1703 });
1672 1704
1673 return yield* runAction().pipe(1705 return yield* runAction().pipe(
1674 Effect.ensuring(invalidateStatusResultCache(input.cwd)),1706 Effect.ensuring(invalidateStatus(input.cwd)),
1675 Effect.tapError((error) =>1707 Effect.tapError((error) =>
1676 Effect.flatMap(Ref.get(currentPhase), (phase) =>1708 Effect.flatMap(Ref.get(currentPhase), (phase) =>
1677 progress.emit({1709 progress.emit({
@@ -1686,7 +1718,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 8 unmodified lines
1686 );1718 );
1687 1719
1688 return {1720 return {
1721 localStatus,
1722 remoteStatus,
1689 status,1723 status,
1724 invalidateLocalStatus,
1725 invalidateRemoteStatus,
1726 invalidateStatus,
1690 resolvePullRequest,1727 resolvePullRequest,
1691 preparePullRequestThread,1728 preparePullRequestThread,
1692 runStackedAction,1729 runStackedAction,
apps/server/src/git/Layers/GitStatusBroadcaster.test.ts+312−0
@@ -0,0 +1,312 @@
1import { assert, it } from "@effect/vitest";
2import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
3import type {
4 GitStatusLocalResult,
5 GitStatusRemoteResult,
6 GitStatusResult,
7 GitStatusStreamEvent,
8} from "@t3tools/contracts";
9import { describe } from "vitest";
10
11import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
12import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
13import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
14
15const baseLocalStatus: GitStatusLocalResult = {
16 isRepo: true,
17 hostingProvider: {
18 kind: "github",
19 name: "GitHub",
20 baseUrl: "https://github.com",
21 },
22 hasOriginRemote: true,
23 isDefaultBranch: false,
24 branch: "feature/status-broadcast",
25 hasWorkingTreeChanges: false,
26 workingTree: { files: [], insertions: 0, deletions: 0 },
27};
28
29const baseRemoteStatus: GitStatusRemoteResult = {
30 hasUpstream: true,
31 aheadCount: 0,
32 behindCount: 0,
33 pr: null,
34};
35
36const baseStatus: GitStatusResult = {
37 ...baseLocalStatus,
38 ...baseRemoteStatus,
39};
40
41function makeTestLayer(state: {
42 currentLocalStatus: GitStatusLocalResult;
43 currentRemoteStatus: GitStatusRemoteResult | null;
44 localStatusCalls: number;
45 remoteStatusCalls: number;
46 localInvalidationCalls: number;
47 remoteInvalidationCalls: number;
48}) {
49 const gitManager: GitManagerShape = {
50 localStatus: () =>
51 Effect.sync(() => {
52 state.localStatusCalls += 1;
53 return state.currentLocalStatus;
54 }),
55 remoteStatus: () =>
56 Effect.sync(() => {
57 state.remoteStatusCalls += 1;
58 return state.currentRemoteStatus;
59 }),
60 status: () => Effect.die("status should not be called in this test"),
61 invalidateLocalStatus: () =>
62 Effect.sync(() => {
63 state.localInvalidationCalls += 1;
64 }),
65 invalidateRemoteStatus: () =>
66 Effect.sync(() => {
67 state.remoteInvalidationCalls += 1;
68 }),
69 invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
70 resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
71 preparePullRequestThread: () =>
72 Effect.die("preparePullRequestThread should not be called in this test"),
73 runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
74 };
75
76 return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
77}
78
79describe("GitStatusBroadcasterLive", () => {
80 it.effect("reuses the cached git status across repeated reads", () => {
81 const state = {
82 currentLocalStatus: baseLocalStatus,
83 currentRemoteStatus: baseRemoteStatus,
84 localStatusCalls: 0,
85 remoteStatusCalls: 0,
86 localInvalidationCalls: 0,
87 remoteInvalidationCalls: 0,
88 };
89
90 return Effect.gen(function* () {
91 const broadcaster = yield* GitStatusBroadcaster;
92
93 const first = yield* broadcaster.getStatus({ cwd: "/repo" });
94 const second = yield* broadcaster.getStatus({ cwd: "/repo" });
95
96 assert.deepStrictEqual(first, baseStatus);
97 assert.deepStrictEqual(second, baseStatus);
98 assert.equal(state.localStatusCalls, 1);
99 assert.equal(state.remoteStatusCalls, 1);
100 assert.equal(state.localInvalidationCalls, 0);
101 assert.equal(state.remoteInvalidationCalls, 0);
102 }).pipe(Effect.provide(makeTestLayer(state)));
103 });
104
105 it.effect("refreshes the cached snapshot after explicit invalidation", () => {
106 const state = {
107 currentLocalStatus: baseLocalStatus,
108 currentRemoteStatus: baseRemoteStatus,
109 localStatusCalls: 0,
110 remoteStatusCalls: 0,
111 localInvalidationCalls: 0,
112 remoteInvalidationCalls: 0,
113 };
114
115 return Effect.gen(function* () {
116 const broadcaster = yield* GitStatusBroadcaster;
117 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
118
119 state.currentLocalStatus = {
120 ...baseLocalStatus,
121 branch: "feature/updated-status",
122 };
123 state.currentRemoteStatus = {
124 ...baseRemoteStatus,
125 aheadCount: 2,
126 };
127 const refreshed = yield* broadcaster.refreshStatus("/repo");
128 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
129
130 assert.deepStrictEqual(initial, baseStatus);
131 assert.deepStrictEqual(refreshed, {
132 ...state.currentLocalStatus,
133 ...state.currentRemoteStatus,
134 });
135 assert.deepStrictEqual(cached, {
136 ...state.currentLocalStatus,
137 ...state.currentRemoteStatus,
138 });
139 assert.equal(state.localStatusCalls, 2);
140 assert.equal(state.remoteStatusCalls, 2);
141 assert.equal(state.localInvalidationCalls, 1);
142 assert.equal(state.remoteInvalidationCalls, 1);
143 }).pipe(Effect.provide(makeTestLayer(state)));
144 });
145
146 it.effect("refreshes only the cached local snapshot when requested", () => {
147 const state = {
148 currentLocalStatus: baseLocalStatus,
149 currentRemoteStatus: baseRemoteStatus,
150 localStatusCalls: 0,
151 remoteStatusCalls: 0,
152 localInvalidationCalls: 0,
153 remoteInvalidationCalls: 0,
154 };
155
156 return Effect.gen(function* () {
157 const broadcaster = yield* GitStatusBroadcaster;
158 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
159
160 state.currentLocalStatus = {
161 ...baseLocalStatus,
162 branch: "feature/local-only-refresh",
163 hasWorkingTreeChanges: true,
164 };
165
166 const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
167 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
168
169 assert.deepStrictEqual(initial, baseStatus);
170 assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
171 assert.deepStrictEqual(cached, {
172 ...state.currentLocalStatus,
173 ...baseRemoteStatus,
174 });
175 assert.equal(state.localStatusCalls, 2);
176 assert.equal(state.remoteStatusCalls, 1);
177 assert.equal(state.localInvalidationCalls, 1);
178 assert.equal(state.remoteInvalidationCalls, 0);
179 }).pipe(Effect.provide(makeTestLayer(state)));
180 });
181
182 it.effect("streams a local snapshot first and remote updates later", () => {
183 const state = {
184 currentLocalStatus: baseLocalStatus,
185 currentRemoteStatus: baseRemoteStatus,
186 localStatusCalls: 0,
187 remoteStatusCalls: 0,
188 localInvalidationCalls: 0,
189 remoteInvalidationCalls: 0,
190 };
191
192 return Effect.gen(function* () {
193 const broadcaster = yield* GitStatusBroadcaster;
194 const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
195 const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
196 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
197 if (event._tag === "snapshot") {
198 return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
199 }
200 if (event._tag === "remoteUpdated") {
201 return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore);
202 }
203 return Effect.void;
204 }).pipe(Effect.forkScoped);
205
206 const snapshot = yield* Deferred.await(snapshotDeferred);
207 yield* broadcaster.refreshStatus("/repo");
208 const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
209
210 assert.deepStrictEqual(snapshot, {
211 _tag: "snapshot",
212 local: baseLocalStatus,
213 remote: null,
214 } satisfies GitStatusStreamEvent);
215 assert.deepStrictEqual(remoteUpdated, {
216 _tag: "remoteUpdated",
217 remote: baseRemoteStatus,
218 } satisfies GitStatusStreamEvent);
219 }).pipe(Effect.provide(makeTestLayer(state)));
220 });
221
222 it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
223 const state = {
224 currentLocalStatus: baseLocalStatus,
225 currentRemoteStatus: baseRemoteStatus,
226 localStatusCalls: 0,
227 remoteStatusCalls: 0,
228 localInvalidationCalls: 0,
229 remoteInvalidationCalls: 0,
230 };
231 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
232 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
233 const testLayer = GitStatusBroadcasterLive.pipe(
234 Layer.provide(
235 Layer.succeed(GitManager, {
236 localStatus: () =>
237 Effect.sync(() => {
238 state.localStatusCalls += 1;
239 return state.currentLocalStatus;
240 }),
241 remoteStatus: () =>
242 Effect.sync(() => {
243 state.remoteStatusCalls += 1;
244 }).pipe(
245 Effect.andThen(
246 remoteStartedDeferred
247 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
248 : Effect.void,
249 ),
250 Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
251 Effect.onInterrupt(() =>
252 remoteInterruptedDeferred
253 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
254 : Effect.void,
255 ),
256 ),
257 status: () => Effect.die("status should not be called in this test"),
258 invalidateLocalStatus: () =>
259 Effect.sync(() => {
260 state.localInvalidationCalls += 1;
261 }),
262 invalidateRemoteStatus: () =>
263 Effect.sync(() => {
264 state.remoteInvalidationCalls += 1;
265 }),
266 invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
267 resolvePullRequest: () =>
268 Effect.die("resolvePullRequest should not be called in this test"),
269 preparePullRequestThread: () =>
270 Effect.die("preparePullRequestThread should not be called in this test"),
271 runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
272 } satisfies GitManagerShape),
273 ),
274 );
275
276 return Effect.gen(function* () {
277 const remoteInterrupted = yield* Deferred.make<void>();
278 const remoteStarted = yield* Deferred.make<void>();
279 remoteInterruptedDeferred = remoteInterrupted;
280 remoteStartedDeferred = remoteStarted;
281
282 const broadcaster = yield* GitStatusBroadcaster;
283 const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
284 const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
285 const firstScope = yield* Scope.make();
286 const secondScope = yield* Scope.make();
287 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
288 event._tag === "snapshot"
289 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
290 : Effect.void,
291 ).pipe(Effect.forkIn(firstScope));
292 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
293 event._tag === "snapshot"
294 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
295 : Effect.void,
296 ).pipe(Effect.forkIn(secondScope));
297
298 yield* Deferred.await(firstSnapshot);
299 yield* Deferred.await(secondSnapshot);
300 yield* Deferred.await(remoteStarted);
301
302 assert.equal(state.remoteStatusCalls, 1);
303
304 yield* Scope.close(firstScope, Exit.void);
305 assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true);
306
307 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
308 yield* Deferred.await(remoteInterrupted);
309 assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true);
310 }).pipe(Effect.provide(testLayer));
311 });
312});
apps/server/src/git/Layers/GitStatusBroadcaster.ts+311−0
@@ -0,0 +1,311 @@
1import { realpathSync } from "node:fs";
2
3import {
4 Duration,
5 Effect,
6 Exit,
7 Fiber,
8 Layer,
9 PubSub,
10 Ref,
11 Scope,
12 Stream,
13 SynchronizedRef,
14} from "effect";
15import type {
16 GitStatusInput,
17 GitStatusLocalResult,
18 GitStatusRemoteResult,
19 GitStatusStreamEvent,
20} from "@t3tools/contracts";
21import { mergeGitStatusParts } from "@t3tools/shared/git";
22
23import {
24 GitStatusBroadcaster,
25 type GitStatusBroadcasterShape,
26} from "../Services/GitStatusBroadcaster.ts";
27import { GitManager } from "../Services/GitManager.ts";
28
29const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
30
31interface GitStatusChange {
32 readonly cwd: string;
33 readonly event: GitStatusStreamEvent;
34}
35
36interface CachedValue<T> {
37 readonly fingerprint: string;
38 readonly value: T;
39}
40
41interface CachedGitStatus {
42 readonly local: CachedValue<GitStatusLocalResult> | null;
43 readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
44}
45
46interface ActiveRemotePoller {
47 readonly fiber: Fiber.Fiber<void, never>;
48 readonly subscriberCount: number;
49}
50
51function normalizeCwd(cwd: string): string {
52 try {
53 return realpathSync.native(cwd);
54 } catch {
55 return cwd;
56 }
57}
58
59function fingerprintStatusPart(status: unknown): string {
60 return JSON.stringify(status);
61}
62
63export const GitStatusBroadcasterLive = Layer.effect(
64 GitStatusBroadcaster,
65 Effect.gen(function* () {
66 const gitManager = yield* GitManager;
67 const changesPubSub = yield* Effect.acquireRelease(
68 PubSub.unbounded<GitStatusChange>(),
69 (pubsub) => PubSub.shutdown(pubsub),
70 );
71 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
72 Scope.close(scope, Exit.void),
73 );
74 const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
75 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
76
77 const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
78 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
79 });
80
81 const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
82 cwd: string,
83 local: GitStatusLocalResult,
84 options?: { publish?: boolean },
85 ) {
86 const nextLocal = {
87 fingerprint: fingerprintStatusPart(local),
88 value: local,
89 } satisfies CachedValue<GitStatusLocalResult>;
90 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
91 const previous = cache.get(cwd) ?? { local: null, remote: null };
92 const nextCache = new Map(cache);
93 nextCache.set(cwd, {
94 ...previous,
95 local: nextLocal,
96 });
97 return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
98 });
99
100 if (options?.publish && shouldPublish) {
101 yield* PubSub.publish(changesPubSub, {
102 cwd,
103 event: {
104 _tag: "localUpdated",
105 local,
106 },
107 });
108 }
109
110 return local;
111 });
112
113 const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
114 cwd: string,
115 remote: GitStatusRemoteResult | null,
116 options?: { publish?: boolean },
117 ) {
118 const nextRemote = {
119 fingerprint: fingerprintStatusPart(remote),
120 value: remote,
121 } satisfies CachedValue<GitStatusRemoteResult | null>;
122 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
123 const previous = cache.get(cwd) ?? { local: null, remote: null };
124 const nextCache = new Map(cache);
125 nextCache.set(cwd, {
126 ...previous,
127 remote: nextRemote,
128 });
129 return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
130 });
131
132 if (options?.publish && shouldPublish) {
133 yield* PubSub.publish(changesPubSub, {
134 cwd,
135 event: {
136 _tag: "remoteUpdated",
137 remote,
138 },
139 });
140 }
141
142 return remote;
143 });
144
145 const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
146 const local = yield* gitManager.localStatus({ cwd });
147 return yield* updateCachedLocalStatus(cwd, local);
148 });
149
150 const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
151 const remote = yield* gitManager.remoteStatus({ cwd });
152 return yield* updateCachedRemoteStatus(cwd, remote);
153 });
154
155 const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
156 const cached = yield* getCachedStatus(cwd);
157 if (cached?.local) {
158 return cached.local.value;
159 }
160 return yield* loadLocalStatus(cwd);
161 });
162
163 const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
164 const cached = yield* getCachedStatus(cwd);
165 if (cached?.remote) {
166 return cached.remote.value;
167 }
168 return yield* loadRemoteStatus(cwd);
169 });
170
171 const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
172 input: GitStatusInput,
173 ) {
174 const normalizedCwd = normalizeCwd(input.cwd);
175 const [local, remote] = yield* Effect.all([
176 getOrLoadLocalStatus(normalizedCwd),
177 getOrLoadRemoteStatus(normalizedCwd),
178 ]);
179 return mergeGitStatusParts(local, remote);
180 });
181
182 const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
183 "refreshLocalStatus",
184 )(function* (cwd) {
185 const normalizedCwd = normalizeCwd(cwd);
186 yield* gitManager.invalidateLocalStatus(normalizedCwd);
187 const local = yield* gitManager.localStatus({ cwd: normalizedCwd });
188 return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true });
189 });
190
191 const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
192 yield* gitManager.invalidateRemoteStatus(cwd);
193 const remote = yield* gitManager.remoteStatus({ cwd });
194 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
195 });
196
197 const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
198 function* (cwd) {
199 const normalizedCwd = normalizeCwd(cwd);
200 const [local, remote] = yield* Effect.all([
201 refreshLocalStatus(normalizedCwd),
202 refreshRemoteStatus(normalizedCwd),
203 ]);
204 return mergeGitStatusParts(local, remote);
205 },
206 );
207
208 const makeRemoteRefreshLoop = (cwd: string) => {
209 const logRefreshFailure = (error: Error) =>
210 Effect.logWarning("git remote status refresh failed", {
211 cwd,
212 detail: error.message,
213 });
214
215 return refreshRemoteStatus(cwd).pipe(
216 Effect.catch(logRefreshFailure),
217 Effect.andThen(
218 Effect.forever(
219 Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
220 Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
221 ),
222 ),
223 ),
224 );
225 };
226
227 const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
228 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
229 const existing = activePollers.get(cwd);
230 if (existing) {
231 const nextPollers = new Map(activePollers);
232 nextPollers.set(cwd, {
233 ...existing,
234 subscriberCount: existing.subscriberCount + 1,
235 });
236 return Effect.succeed([undefined, nextPollers] as const);
237 }
238
239 return makeRemoteRefreshLoop(cwd).pipe(
240 Effect.forkIn(broadcasterScope),
241 Effect.map((fiber) => {
242 const nextPollers = new Map(activePollers);
243 nextPollers.set(cwd, {
244 fiber,
245 subscriberCount: 1,
246 });
247 return [undefined, nextPollers] as const;
248 }),
249 );
250 });
251 });
252
253 const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
254 const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
255 const existing = activePollers.get(cwd);
256 if (!existing) {
257 return [null, activePollers] as const;
258 }
259
260 if (existing.subscriberCount > 1) {
261 const nextPollers = new Map(activePollers);
262 nextPollers.set(cwd, {
263 ...existing,
264 subscriberCount: existing.subscriberCount - 1,
265 });
266 return [null, nextPollers] as const;
267 }
268
269 const nextPollers = new Map(activePollers);
270 nextPollers.delete(cwd);
271 return [existing.fiber, nextPollers] as const;
272 });
273
274 if (pollerToInterrupt) {
275 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
276 }
277 });
278
279 const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
280 Stream.unwrap(
281 Effect.gen(function* () {
282 const normalizedCwd = normalizeCwd(input.cwd);
283 const subscription = yield* PubSub.subscribe(changesPubSub);
284 const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
285 const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
286 yield* retainRemotePoller(normalizedCwd);
287
288 const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
289
290 return Stream.concat(
291 Stream.make({
292 _tag: "snapshot" as const,
293 local: initialLocal,
294 remote: initialRemote,
295 }),
296 Stream.fromSubscription(subscription).pipe(
297 Stream.filter((event) => event.cwd === normalizedCwd),
298 Stream.map((event) => event.event),
299 ),
300 ).pipe(Stream.ensuring(release));
301 }),
302 );
303
304 return {
305 getStatus,
306 refreshLocalStatus,
307 refreshStatus,
308 streamStatus,
309 } satisfies GitStatusBroadcasterShape;
310 }),
311);
apps/server/src/git/Layers/RoutingTextGeneration.ts+3−3
@@ -9,7 +9,7 @@ · 8 unmodified lines
9 *9 *
10 * @module RoutingTextGeneration10 * @module RoutingTextGeneration
11 */11 */
12import { Effect, Layer, ServiceMap } from "effect";12import { Effect, Layer, Context } from "effect";
13 13
14import {14import {
15 TextGeneration,15 TextGeneration,
@@ -23,11 +23,11 @@ import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; · 7 unmodified lines
23// Internal service tags so both concrete layers can coexist.23// Internal service tags so both concrete layers can coexist.
24// ---------------------------------------------------------------------------24// ---------------------------------------------------------------------------
25 25
26class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(26class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
27 "t3/git/Layers/RoutingTextGeneration/CodexTextGen",27 "t3/git/Layers/RoutingTextGeneration/CodexTextGen",
28) {}28) {}
29 29
30class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(30class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
31 "t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",31 "t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
32) {}32) {}
33 33
apps/server/src/git/Services/GitCore.ts+14−7
@@ -6,11 +6,13 @@ · 5 unmodified lines
6 *6 *
7 * @module GitCore7 * @module GitCore
8 */8 */
9import { ServiceMap } from "effect";9import { Context } from "effect";
10import type { Effect, Scope } from "effect";10import type { Effect } from "effect";
11import type {11import type {
12 GitCheckoutInput,12 GitCheckoutInput,
13 GitCheckoutResult,
13 GitCreateBranchInput,14 GitCreateBranchInput,
15 GitCreateBranchResult,
14 GitCreateWorktreeInput,16 GitCreateWorktreeInput,
15 GitCreateWorktreeResult,17 GitCreateWorktreeResult,
16 GitInitInput,18 GitInitInput,
@@ -156,6 +158,11 @@ export interface GitCoreShape { · 139 unmodified lines
156 */158 */
157 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;159 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
158 160
161 /**
162 * Read detailed working tree / branch status without refreshing remote tracking refs.
163 */
164 readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
165
159 /**166 /**
160 * Build staged change context for commit generation.167 * Build staged change context for commit generation.
161 */168 */
@@ -278,14 +285,16 @@ export interface GitCoreShape { · 116 unmodified lines
278 /**285 /**
279 * Create a local branch.286 * Create a local branch.
280 */287 */
281 readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;288 readonly createBranch: (
289 input: GitCreateBranchInput,
290 ) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
282 291
283 /**292 /**
284 * Checkout an existing branch and refresh its upstream metadata in background.293 * Checkout an existing branch and refresh its upstream metadata in background.
285 */294 */
286 readonly checkoutBranch: (295 readonly checkoutBranch: (
287 input: GitCheckoutInput,296 input: GitCheckoutInput,
288 ) => Effect.Effect<void, GitCommandError, Scope.Scope>;297 ) => Effect.Effect<GitCheckoutResult, GitCommandError>;
289 298
290 /**299 /**
291 * Initialize a repository in the provided directory.300 * Initialize a repository in the provided directory.
@@ -301,6 +310,4 @@ export interface GitCoreShape { · 9 unmodified lines
301/**310/**
302 * GitCore - Service tag for low-level Git repository operations.311 * GitCore - Service tag for low-level Git repository operations.
303 */312 */
304export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(313export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
305 "t3/git/Services/GitCore",
306) {}
apps/server/src/git/Services/GitHubCli.ts+2−2
@@ -5,7 +5,7 @@ · 4 unmodified lines
5 *5 *
6 * @module GitHubCli6 * @module GitHubCli
7 */7 */
8import { ServiceMap } from "effect";8import { Context } from "effect";
9import type { Effect } from "effect";9import type { Effect } from "effect";
10 10
11import type { ProcessRunResult } from "../../processRunner";11import type { ProcessRunResult } from "../../processRunner";
@@ -98,6 +98,6 @@ export interface GitHubCliShape { · 86 unmodified lines
98/**98/**
99 * GitHubCli - Service tag for GitHub CLI process execution.99 * GitHubCli - Service tag for GitHub CLI process execution.
100 */100 */
101export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()(101export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
102 "t3/git/Services/GitHubCli",102 "t3/git/Services/GitHubCli",
103) {}103) {}
apps/server/src/git/Services/GitManager.ts+33−2
@@ -14,10 +14,12 @@ import { · 13 unmodified lines
14 GitResolvePullRequestResult,14 GitResolvePullRequestResult,
15 GitRunStackedActionInput,15 GitRunStackedActionInput,
16 GitRunStackedActionResult,16 GitRunStackedActionResult,
17 GitStatusLocalResult,
18 GitStatusRemoteResult,
17 GitStatusInput,19 GitStatusInput,
18 GitStatusResult,20 GitStatusResult,
19} from "@t3tools/contracts";21} from "@t3tools/contracts";
20import { ServiceMap } from "effect";22import { Context } from "effect";
21import type { Effect } from "effect";23import type { Effect } from "effect";
22import type { GitManagerServiceError } from "@t3tools/contracts";24import type { GitManagerServiceError } from "@t3tools/contracts";
23 25
@@ -41,6 +43,35 @@ export interface GitManagerShape { · 17 unmodified lines
41 input: GitStatusInput,43 input: GitStatusInput,
42 ) => Effect.Effect<GitStatusResult, GitManagerServiceError>;44 ) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
43 45
46 /**
47 * Read local repository status without remote hosting enrichment.
48 */
49 readonly localStatus: (
50 input: GitStatusInput,
51 ) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
52
53 /**
54 * Read remote tracking / PR status for a repository.
55 */
56 readonly remoteStatus: (
57 input: GitStatusInput,
58 ) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
59
60 /**
61 * Clear any cached local status snapshot for a repository.
62 */
63 readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
64
65 /**
66 * Clear any cached remote status snapshot for a repository.
67 */
68 readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
69
70 /**
71 * Clear any cached status snapshot for a repository so the next read is fresh.
72 */
73 readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
74
44 /**75 /**
45 * Resolve a pull request by URL/number against the current repository.76 * Resolve a pull request by URL/number against the current repository.
46 */77 */
@@ -68,6 +99,6 @@ export interface GitManagerShape { · 21 unmodified lines
68/**99/**
69 * GitManager - Service tag for stacked Git workflow orchestration.100 * GitManager - Service tag for stacked Git workflow orchestration.
70 */101 */
71export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(102export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
72 "t3/git/Services/GitManager",103 "t3/git/Services/GitManager",
73) {}104) {}
apps/server/src/git/Services/GitStatusBroadcaster.ts+27−0
@@ -0,0 +1,27 @@
1import { Context } from "effect";
2import type { Effect, Stream } from "effect";
3import type {
4 GitManagerServiceError,
5 GitStatusInput,
6 GitStatusLocalResult,
7 GitStatusResult,
8 GitStatusStreamEvent,
9} from "@t3tools/contracts";
10
11export interface GitStatusBroadcasterShape {
12 readonly getStatus: (
13 input: GitStatusInput,
14 ) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
15 readonly refreshLocalStatus: (
16 cwd: string,
17 ) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
18 readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
19 readonly streamStatus: (
20 input: GitStatusInput,
21 ) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
22}
23
24export class GitStatusBroadcaster extends Context.Service<
25 GitStatusBroadcaster,
26 GitStatusBroadcasterShape
27>()("t3/git/Services/GitStatusBroadcaster") {}
apps/server/src/git/Services/TextGeneration.ts+2−2
@@ -6,7 +6,7 @@ · 5 unmodified lines
6 *6 *
7 * @module TextGeneration7 * @module TextGeneration
8 */8 */
9import { ServiceMap } from "effect";9import { Context } from "effect";
10import type { Effect } from "effect";10import type { Effect } from "effect";
11import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";11import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
12 12
@@ -118,6 +118,6 @@ export interface TextGenerationShape { · 105 unmodified lines
118/**118/**
119 * TextGeneration - Service tag for commit and PR text generation.119 * TextGeneration - Service tag for commit and PR text generation.
120 */120 */
121export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(121export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
122 "t3/git/Services/TextGeneration",122 "t3/git/Services/TextGeneration",
123) {}123) {}
apps/server/src/git/githubPullRequests.ts+128−0
@@ -0,0 +1,128 @@
1import { Cause, Exit, Result, Schema } from "effect";
2import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
3import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
4
5export interface NormalizedGitHubPullRequestRecord {
6 readonly number: number;
7 readonly title: string;
8 readonly url: string;
9 readonly baseRefName: string;
10 readonly headRefName: string;
11 readonly state: "open" | "closed" | "merged";
12 readonly updatedAt: string | null;
13 readonly isCrossRepository?: boolean;
14 readonly headRepositoryNameWithOwner?: string | null;
15 readonly headRepositoryOwnerLogin?: string | null;
16}
17
18const GitHubPullRequestSchema = Schema.Struct({
19 number: PositiveInt,
20 title: TrimmedNonEmptyString,
21 url: TrimmedNonEmptyString,
22 baseRefName: TrimmedNonEmptyString,
23 headRefName: TrimmedNonEmptyString,
24 state: Schema.optional(Schema.NullOr(Schema.String)),
25 mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
26 updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
27 isCrossRepository: Schema.optional(Schema.Boolean),
28 headRepository: Schema.optional(
29 Schema.NullOr(
30 Schema.Struct({
31 nameWithOwner: Schema.String,
32 }),
33 ),
34 ),
35 headRepositoryOwner: Schema.optional(
36 Schema.NullOr(
37 Schema.Struct({
38 login: Schema.String,
39 }),
40 ),
41 ),
42});
43
44function trimOptionalString(value: string | null | undefined): string | null {
45 const trimmed = value?.trim() ?? "";
46 return trimmed.length > 0 ? trimmed : null;
47}
48
49function normalizeGitHubPullRequestState(input: {
50 state?: string | null | undefined;
51 mergedAt?: string | null | undefined;
52}): "open" | "closed" | "merged" {
53 const normalizedState = input.state?.trim().toUpperCase();
54 if (
55 (typeof input.mergedAt === "string" && input.mergedAt.trim().length > 0) ||
56 normalizedState === "MERGED"
57 ) {
58 return "merged";
59 }
60 if (normalizedState === "CLOSED") {
61 return "closed";
62 }
63 return "open";
64}
65
66function normalizeGitHubPullRequestRecord(
67 raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
68): NormalizedGitHubPullRequestRecord {
69 const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
70 const headRepositoryOwnerLogin =
71 trimOptionalString(raw.headRepositoryOwner?.login) ??
72 (typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
73 ? (headRepositoryNameWithOwner.split("/")[0] ?? null)
74 : null);
75
76 return {
77 number: raw.number,
78 title: raw.title,
79 url: raw.url,
80 baseRefName: raw.baseRefName,
81 headRefName: raw.headRefName,
82 state: normalizeGitHubPullRequestState(raw),
83 updatedAt:
84 typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
85 ...(typeof raw.isCrossRepository === "boolean"
86 ? { isCrossRepository: raw.isCrossRepository }
87 : {}),
88 ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
89 ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
90 };
91}
92
93const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
94const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
95const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
96
97export const formatGitHubJsonDecodeError = formatSchemaError;
98
99export function decodeGitHubPullRequestListJson(
100 raw: string,
101): Result.Result<
102 ReadonlyArray<NormalizedGitHubPullRequestRecord>,
103 Cause.Cause<Schema.SchemaError>
104> {
105 const result = decodeGitHubPullRequestList(raw);
106 if (Result.isSuccess(result)) {
107 const pullRequests: NormalizedGitHubPullRequestRecord[] = [];
108 for (const entry of result.success) {
109 const decodedEntry = decodeGitHubPullRequestEntry(entry);
110 if (Exit.isFailure(decodedEntry)) {
111 continue;
112 }
113 pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));
114 }
115 return Result.succeed(pullRequests);
116 }
117 return Result.fail(result.failure);
118}
119
120export function decodeGitHubPullRequestJson(
121 raw: string,
122): Result.Result<NormalizedGitHubPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
123 const result = decodeGitHubPullRequest(raw);
124 if (Result.isSuccess(result)) {
125 return Result.succeed(normalizeGitHubPullRequestRecord(result.success));
126 }
127 return Result.fail(result.failure);
128}
apps/server/src/http.test.ts+27−0
@@ -0,0 +1,27 @@
1import { describe, expect, it } from "vitest";
2
3import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
4
5describe("http dev routing", () => {
6 it("treats localhost and loopback addresses as local", () => {
7 expect(isLoopbackHostname("127.0.0.1")).toBe(true);
8 expect(isLoopbackHostname("localhost")).toBe(true);
9 expect(isLoopbackHostname("::1")).toBe(true);
10 expect(isLoopbackHostname("[::1]")).toBe(true);
11 });
12
13 it("does not treat LAN addresses as local", () => {
14 expect(isLoopbackHostname("192.168.86.35")).toBe(false);
15 expect(isLoopbackHostname("10.0.0.24")).toBe(false);
16 expect(isLoopbackHostname("example.local")).toBe(false);
17 });
18
19 it("preserves path and query when redirecting to the dev server", () => {
20 const devUrl = new URL("http://127.0.0.1:5173/");
21 const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token");
22
23 expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe(
24 "http://127.0.0.1:5173/pair?token=test-token",
25 );
26 });
27});
apps/server/src/http.ts+123−9
@@ -1,6 +1,15 @@
1import Mime from "@effect/platform-node/Mime";1import Mime from "@effect/platform-node/Mime";
2import { Effect, FileSystem, Option, Path } from "effect";2import { Data, Effect, FileSystem, Option, Path } from "effect";
3import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";3import { cast } from "effect/Function";
4import {
5 HttpBody,
6 HttpClient,
7 HttpClientResponse,
8 HttpRouter,
9 HttpServerResponse,
10 HttpServerRequest,
11} from "effect/unstable/http";
12import { OtlpTracer } from "effect/unstable/observability";
4 13
5import {14import {
6 ATTACHMENTS_ROUTE_PREFIX,15 ATTACHMENTS_ROUTE_PREFIX,
@@ -8,16 +17,117 @@ import { · 1 unmodified line
8 resolveAttachmentRelativePath,17 resolveAttachmentRelativePath,
9} from "./attachmentPaths";18} from "./attachmentPaths";
10import { resolveAttachmentPathById } from "./attachmentStore";19import { resolveAttachmentPathById } from "./attachmentStore";
11import { ServerConfig } from "./config";20import { resolveStaticDir, ServerConfig } from "./config";
21import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
22import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
12import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";23import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
24import { ServerAuth } from "./auth/Services/ServerAuth.ts";
25import { respondToAuthError } from "./auth/http.ts";
26import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
13 27
14const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";28const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
15const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;29const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
30const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
31const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
32
33export const browserApiCorsLayer = HttpRouter.cors({
34 allowedMethods: ["GET", "POST", "OPTIONS"],
35 allowedHeaders: ["authorization", "b3", "traceparent", "content-type"],
36 maxAge: 600,
37});
38
39export function isLoopbackHostname(hostname: string): boolean {
40 const normalizedHostname = hostname
41 .trim()
42 .toLowerCase()
43 .replace(/^\[(.*)\]$/, "$1");
44 return LOOPBACK_HOSTNAMES.has(normalizedHostname);
45}
46
47export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
48 const redirectUrl = new URL(devUrl.toString());
49 redirectUrl.pathname = requestUrl.pathname;
50 redirectUrl.search = requestUrl.search;
51 redirectUrl.hash = requestUrl.hash;
52 return redirectUrl.toString();
53}
54
55const requireAuthenticatedRequest = Effect.gen(function* () {
56 const request = yield* HttpServerRequest.HttpServerRequest;
57 const serverAuth = yield* ServerAuth;
58 yield* serverAuth.authenticateHttpRequest(request);
59});
60
61export const serverEnvironmentRouteLayer = HttpRouter.add(
62 "GET",
63 "/.well-known/t3/environment",
64 Effect.gen(function* () {
65 const descriptor = yield* Effect.service(ServerEnvironment).pipe(
66 Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor),
67 );
68 return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 });
69 }),
70);
71
72class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
73 readonly cause: unknown;
74 readonly bodyJson: OtlpTracer.TraceData;
75}> {}
76
77export const otlpTracesProxyRouteLayer = HttpRouter.add(
78 "POST",
79 OTLP_TRACES_PROXY_PATH,
80 Effect.gen(function* () {
81 yield* requireAuthenticatedRequest;
82 const request = yield* HttpServerRequest.HttpServerRequest;
83 const config = yield* ServerConfig;
84 const otlpTracesUrl = config.otlpTracesUrl;
85 const browserTraceCollector = yield* BrowserTraceCollector;
86 const httpClient = yield* HttpClient.HttpClient;
87 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
88
89 yield* Effect.try({
90 try: () => decodeOtlpTraceRecords(bodyJson),
91 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
92 }).pipe(
93 Effect.flatMap((records) => browserTraceCollector.record(records)),
94 Effect.catch((cause) =>
95 Effect.logWarning("Failed to decode browser OTLP traces", {
96 cause,
97 bodyJson,
98 }),
99 ),
100 );
101
102 if (otlpTracesUrl === undefined) {
103 return HttpServerResponse.empty({ status: 204 });
104 }
105
106 return yield* httpClient
107 .post(otlpTracesUrl, {
108 body: HttpBody.jsonUnsafe(bodyJson),
109 })
110 .pipe(
111 Effect.flatMap(HttpClientResponse.filterStatusOk),
112 Effect.as(HttpServerResponse.empty({ status: 204 })),
113 Effect.tapError((cause) =>
114 Effect.logWarning("Failed to export browser OTLP traces", {
115 cause,
116 otlpTracesUrl,
117 }),
118 ),
119 Effect.catch(() =>
120 Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
121 ),
122 );
123 }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
124);
16 125
17export const attachmentsRouteLayer = HttpRouter.add(126export const attachmentsRouteLayer = HttpRouter.add(
18 "GET",127 "GET",
19 `${ATTACHMENTS_ROUTE_PREFIX}/*`,128 `${ATTACHMENTS_ROUTE_PREFIX}/*`,
20 Effect.gen(function* () {129 Effect.gen(function* () {
130 yield* requireAuthenticatedRequest;
21 const request = yield* HttpServerRequest.HttpServerRequest;131 const request = yield* HttpServerRequest.HttpServerRequest;
22 const url = HttpServerRequest.toURL(request);132 const url = HttpServerRequest.toURL(request);
23 if (Option.isNone(url)) {133 if (Option.isNone(url)) {
@@ -66,13 +176,14 @@ export const attachmentsRouteLayer = HttpRouter.add( · 42 unmodified lines
66 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),176 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
67 ),177 ),
68 );178 );
69 }),179 }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
70);180);
71 181
72export const projectFaviconRouteLayer = HttpRouter.add(182export const projectFaviconRouteLayer = HttpRouter.add(
73 "GET",183 "GET",
74 "/api/project-favicon",184 "/api/project-favicon",
75 Effect.gen(function* () {185 Effect.gen(function* () {
186 yield* requireAuthenticatedRequest;
76 const request = yield* HttpServerRequest.HttpServerRequest;187 const request = yield* HttpServerRequest.HttpServerRequest;
77 const url = HttpServerRequest.toURL(request);188 const url = HttpServerRequest.toURL(request);
78 if (Option.isNone(url)) {189 if (Option.isNone(url)) {
@@ -106,7 +217,7 @@ export const projectFaviconRouteLayer = HttpRouter.add( · 27 unmodified lines
106 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),217 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
107 ),218 ),
108 );219 );
109 }),220 }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
110);221);
111 222
112export const staticAndDevRouteLayer = HttpRouter.add(223export const staticAndDevRouteLayer = HttpRouter.add(
@@ -120,11 +231,14 @@ export const staticAndDevRouteLayer = HttpRouter.add( · 7 unmodified lines
120 }231 }
121 232
122 const config = yield* ServerConfig;233 const config = yield* ServerConfig;
123 if (config.devUrl) {234 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
124 return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });235 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
236 status: 302,
237 });
125 }238 }
126 239
127 if (!config.staticDir) {240 const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined);
241 if (!staticDir) {
128 return HttpServerResponse.text("No static directory configured and no dev URL set.", {242 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
129 status: 503,243 status: 503,
130 });244 });
@@ -132,7 +246,7 @@ export const staticAndDevRouteLayer = HttpRouter.add( · 1 unmodified line
132 246
133 const fileSystem = yield* FileSystem.FileSystem;247 const fileSystem = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;248 const path = yield* Path.Path;
135 const staticRoot = path.resolve(config.staticDir);249 const staticRoot = path.resolve(staticDir);
136 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;250 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
137 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");251 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
138 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");252 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
apps/server/src/keybindings.test.ts+18−1
@@ -2,7 +2,7 @@ import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/c · 1 unmodified line
2import * as NodeServices from "@effect/platform-node/NodeServices";2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";3import { assert, it } from "@effect/vitest";
4import { assertFailure } from "@effect/vitest/utils";4import { assertFailure } from "@effect/vitest/utils";
5import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";5import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
6import { ServerConfig } from "./config";6import { ServerConfig } from "./config";
7 7
8import {8import {
@@ -149,6 +149,23 @@ it.layer(NodeServices.layer)("keybindings", (it) => { · 140 unmodified lines
149 }),149 }),
150 );150 );
151 151
152 it.effect("formats invalid resolved keybinding rules with the custom message", () =>
153 Effect.sync(() => {
154 const result = Schema.decodeUnknownExit(ResolvedKeybindingFromConfig)({
155 key: "mod+shift+d+o",
156 command: "terminal.new",
157 });
158
159 if (result._tag !== "Failure") {
160 assert.fail("Expected invalid keybinding decode to fail");
161 }
162
163 const detail = Cause.pretty(result.cause);
164 assert.isTrue(detail.includes("Invalid keybinding rule"));
165 assert.isFalse(detail.includes("Invalid data"));
166 }),
167 );
168
152 it.effect("bootstraps default keybindings when config file is missing", () =>169 it.effect("bootstraps default keybindings when config file is missing", () =>
153 Effect.gen(function* () {170 Effect.gen(function* () {
154 const fs = yield* FileSystem.FileSystem;171 const fs = yield* FileSystem.FileSystem;
apps/server/src/keybindings.ts+5−4
@@ -39,7 +39,7 @@ import { · 38 unmodified lines
39 SchemaIssue,39 SchemaIssue,
40 SchemaTransformation,40 SchemaTransformation,
41 Ref,41 Ref,
42 ServiceMap,42 Context,
43 Scope,43 Scope,
44 Stream,44 Stream,
45} from "effect";45} from "effect";
@@ -61,6 +61,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [ · 15 unmodified lines
61 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },61 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
62 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },62 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
63 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },63 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
64 { key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
64 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },65 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
65 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },66 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
66 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },67 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
@@ -322,7 +323,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( · 255 unmodified lines
322 Predicate.isNotNull,323 Predicate.isNotNull,
323 () =>324 () =>
324 new SchemaIssue.InvalidValue(Option.some(rule), {325 new SchemaIssue.InvalidValue(Option.some(rule), {
325 title: "Invalid keybinding rule",326 message: "Invalid keybinding rule",
326 }),327 }),
327 ),328 ),
328 Effect.map((resolved) => resolved),329 Effect.map((resolved) => resolved),
@@ -334,7 +335,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( · 5 unmodified lines
334 if (!key) {335 if (!key) {
335 return yield* Effect.fail(336 return yield* Effect.fail(
336 new SchemaIssue.InvalidValue(Option.some(resolved), {337 new SchemaIssue.InvalidValue(Option.some(resolved), {
337 title: "Resolved shortcut cannot be encoded to key string",338 message: "Resolved shortcut cannot be encoded to key string",
338 }),339 }),
339 );340 );
340 }341 }
@@ -521,7 +522,7 @@ export interface KeybindingsShape { · 180 unmodified lines
521/**522/**
522 * Keybindings - Service tag for keybinding configuration operations.523 * Keybindings - Service tag for keybinding configuration operations.
523 */524 */
524export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(525export class Keybindings extends Context.Service<Keybindings, KeybindingsShape>()(
525 "t3/keybindings",526 "t3/keybindings",
526) {}527) {}
527 528
apps/server/src/observability/Attributes.test.ts+46−0
@@ -0,0 +1,46 @@
1import { assert, describe, it } from "@effect/vitest";
2
3import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts";
4
5describe("Attributes", () => {
6 it("normalizes circular arrays, maps, and sets without recursing forever", () => {
7 const array: Array<unknown> = ["alpha"];
8 array.push(array);
9
10 const map = new Map<string, unknown>();
11 map.set("self", map);
12
13 const set = new Set<unknown>();
14 set.add(set);
15
16 assert.deepStrictEqual(
17 compactTraceAttributes({
18 array,
19 map,
20 set,
21 }),
22 {
23 array: ["alpha", "[Circular]"],
24 map: { self: "[Circular]" },
25 set: ["[Circular]"],
26 },
27 );
28 });
29
30 it("normalizes invalid dates without throwing", () => {
31 assert.deepStrictEqual(
32 compactTraceAttributes({
33 invalidDate: new Date("not-a-real-date"),
34 }),
35 {
36 invalidDate: "Invalid Date",
37 },
38 );
39 });
40
41 it("groups GPT-family models under a shared metric label", () => {
42 assert.strictEqual(normalizeModelMetricLabel("gpt-4o"), "gpt");
43 assert.strictEqual(normalizeModelMetricLabel("gpt-5.4"), "gpt");
44 assert.strictEqual(normalizeModelMetricLabel("claude-sonnet-4"), "claude");
45 });
46});
apps/server/src/observability/Attributes.ts+128−0
@@ -0,0 +1,128 @@
1import { Cause, Exit } from "effect";
2
3export type MetricAttributeValue = string;
4export type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;
5export type TraceAttributes = Readonly<Record<string, unknown>>;
6export type ObservabilityOutcome = "success" | "failure" | "interrupt";
7
8function isPlainObject(value: unknown): value is Record<string, unknown> {
9 return typeof value === "object" && value !== null && !Array.isArray(value);
10}
11
12function markSeen(value: object, seen: WeakSet<object>): boolean {
13 if (seen.has(value)) {
14 return true;
15 }
16 seen.add(value);
17 return false;
18}
19
20function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
21 if (
22 value === null ||
23 value === undefined ||
24 typeof value === "string" ||
25 typeof value === "number" ||
26 typeof value === "boolean"
27 ) {
28 return value ?? null;
29 }
30 if (typeof value === "bigint") {
31 return value.toString();
32 }
33 if (value instanceof Date) {
34 return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
35 }
36 if (value instanceof Error) {
37 return {
38 name: value.name,
39 message: value.message,
40 ...(value.stack ? { stack: value.stack } : {}),
41 };
42 }
43 if (Array.isArray(value)) {
44 if (markSeen(value, seen)) {
45 return "[Circular]";
46 }
47 return value.map((entry) => normalizeJsonValue(entry, seen));
48 }
49 if (value instanceof Map) {
50 if (markSeen(value, seen)) {
51 return "[Circular]";
52 }
53 return Object.fromEntries(
54 Array.from(value.entries(), ([key, entryValue]) => [
55 String(key),
56 normalizeJsonValue(entryValue, seen),
57 ]),
58 );
59 }
60 if (value instanceof Set) {
61 if (markSeen(value, seen)) {
62 return "[Circular]";
63 }
64 return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
65 }
66 if (!isPlainObject(value)) {
67 return String(value);
68 }
69 if (markSeen(value, seen)) {
70 return "[Circular]";
71 }
72 return Object.fromEntries(
73 Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
74 );
75}
76
77export function compactTraceAttributes(
78 attributes: Readonly<Record<string, unknown>>,
79): TraceAttributes {
80 return Object.fromEntries(
81 Object.entries(attributes)
82 .filter(([, value]) => value !== undefined)
83 .map(([key, value]) => [key, normalizeJsonValue(value)]),
84 );
85}
86
87export function compactMetricAttributes(
88 attributes: Readonly<Record<string, unknown>>,
89): MetricAttributes {
90 return Object.fromEntries(
91 Object.entries(attributes).flatMap(([key, value]) => {
92 if (value === undefined || value === null) {
93 return [];
94 }
95 if (typeof value === "string") {
96 return [[key, value]];
97 }
98 if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
99 return [[key, String(value)]];
100 }
101 return [];
102 }),
103 );
104}
105
106export function outcomeFromExit(exit: Exit.Exit<unknown, unknown>): ObservabilityOutcome {
107 if (Exit.isSuccess(exit)) {
108 return "success";
109 }
110 return Cause.hasInterruptsOnly(exit.cause) ? "interrupt" : "failure";
111}
112
113export function normalizeModelMetricLabel(model: string | null | undefined): string | undefined {
114 const normalized = model?.trim().toLowerCase();
115 if (!normalized) {
116 return undefined;
117 }
118 if (normalized.includes("gpt")) {
119 return "gpt";
120 }
121 if (normalized.includes("claude")) {
122 return "claude";
123 }
124 if (normalized.includes("gemini")) {
125 return "gemini";
126 }
127 return "other";
128}
apps/server/src/observability/Layers/Observability.ts+84−0
@@ -0,0 +1,84 @@
1import { Effect, Layer, References, Tracer } from "effect";
2import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
3
4import { ServerConfig } from "../../config.ts";
5import { ServerLoggerLive } from "../../serverLogger.ts";
6import { makeLocalFileTracer } from "../LocalFileTracer.ts";
7import { BrowserTraceCollector } from "../Services/BrowserTraceCollector.ts";
8import { makeTraceSink } from "../TraceSink.ts";
9
10const otlpSerializationLayer = OtlpSerialization.layerJson;
11
12export const ObservabilityLive = Layer.unwrap(
13 Effect.gen(function* () {
14 const config = yield* ServerConfig;
15
16 const traceReferencesLayer = Layer.mergeAll(
17 Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
18 Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
19 );
20
21 const tracerLayer = Layer.unwrap(
22 Effect.gen(function* () {
23 const sink = yield* makeTraceSink({
24 filePath: config.serverTracePath,
25 maxBytes: config.traceMaxBytes,
26 maxFiles: config.traceMaxFiles,
27 batchWindowMs: config.traceBatchWindowMs,
28 });
29 const delegate =
30 config.otlpTracesUrl === undefined
31 ? undefined
32 : yield* OtlpTracer.make({
33 url: config.otlpTracesUrl,
34 exportInterval: `${config.otlpExportIntervalMs} millis`,
35 resource: {
36 serviceName: config.otlpServiceName,
37 attributes: {
38 "service.runtime": "t3-server",
39 "service.mode": config.mode,
40 },
41 },
42 });
43
44 const tracer = yield* makeLocalFileTracer({
45 filePath: config.serverTracePath,
46 maxBytes: config.traceMaxBytes,
47 maxFiles: config.traceMaxFiles,
48 batchWindowMs: config.traceBatchWindowMs,
49 sink,
50 ...(delegate ? { delegate } : {}),
51 });
52
53 return Layer.mergeAll(
54 Layer.succeed(Tracer.Tracer, tracer),
55 Layer.succeed(BrowserTraceCollector, {
56 record: (records) =>
57 Effect.sync(() => {
58 for (const record of records) {
59 sink.push(record);
60 }
61 }),
62 }),
63 );
64 }),
65 ).pipe(Layer.provideMerge(otlpSerializationLayer));
66
67 const metricsLayer =
68 config.otlpMetricsUrl === undefined
69 ? Layer.empty
70 : OtlpMetrics.layer({
71 url: config.otlpMetricsUrl,
72 exportInterval: `${config.otlpExportIntervalMs} millis`,
73 resource: {
74 serviceName: config.otlpServiceName,
75 attributes: {
76 "service.runtime": "t3-server",
77 "service.mode": config.mode,
78 },
79 },
80 }).pipe(Layer.provideMerge(otlpSerializationLayer));
81
82 return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer);
83 }),
84);
apps/server/src/observability/LocalFileTracer.test.ts+117−0
@@ -0,0 +1,117 @@
1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4
5import { assert, describe, it } from "@effect/vitest";
6import { Effect, Layer, Logger, References, Tracer } from "effect";
7
8import type { EffectTraceRecord } from "./TraceRecord.ts";
9import { makeLocalFileTracer } from "./LocalFileTracer.ts";
10
11const makeTestLayer = (tracePath: string) =>
12 Layer.mergeAll(
13 Layer.effect(
14 Tracer.Tracer,
15 makeLocalFileTracer({
16 filePath: tracePath,
17 maxBytes: 1024 * 1024,
18 maxFiles: 2,
19 batchWindowMs: 10_000,
20 }),
21 ),
22 Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }),
23 Layer.succeed(References.MinimumLogLevel, "Info"),
24 );
25
26const readTraceRecords = (tracePath: string): Array<EffectTraceRecord> =>
27 fs
28 .readFileSync(tracePath, "utf8")
29 .trim()
30 .split("\n")
31 .filter((line) => line.length > 0)
32 .map((line) => JSON.parse(line) as EffectTraceRecord);
33
34describe("LocalFileTracer", () => {
35 it.effect("writes nested spans to disk and captures log messages as span events", () =>
36 Effect.gen(function* () {
37 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
38 const tracePath = path.join(tempDir, "server.trace.ndjson");
39
40 try {
41 yield* Effect.scoped(
42 Effect.gen(function* () {
43 const program = Effect.gen(function* () {
44 yield* Effect.annotateCurrentSpan({
45 "demo.parent": true,
46 });
47 yield* Effect.logInfo("parent event");
48 yield* Effect.gen(function* () {
49 yield* Effect.annotateCurrentSpan({
50 "demo.child": true,
51 });
52 yield* Effect.logInfo("child event");
53 }).pipe(Effect.withSpan("child-span"));
54 }).pipe(Effect.withSpan("parent-span"));
55
56 yield* program.pipe(Effect.provide(makeTestLayer(tracePath)));
57 }),
58 );
59
60 const records = readTraceRecords(tracePath);
61 assert.equal(records.length, 2);
62
63 const parent = records.find((record) => record.name === "parent-span");
64 const child = records.find((record) => record.name === "child-span");
65
66 assert.notEqual(parent, undefined);
67 assert.notEqual(child, undefined);
68 if (!parent || !child) {
69 return;
70 }
71
72 assert.equal(child.parentSpanId, parent.spanId);
73 assert.equal(parent.attributes["demo.parent"], true);
74 assert.equal(child.attributes["demo.child"], true);
75 assert.equal(
76 parent.events.some((event) => event.name === "parent event"),
77 true,
78 );
79 assert.equal(
80 child.events.some((event) => event.name === "child event"),
81 true,
82 );
83 assert.equal(
84 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
85 true,
86 );
87 } finally {
88 fs.rmSync(tempDir, { recursive: true, force: true });
89 }
90 }),
91 );
92
93 it.effect("serializes interrupted spans with an interrupted exit status", () =>
94 Effect.gen(function* () {
95 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
96 const tracePath = path.join(tempDir, "server.trace.ndjson");
97
98 try {
99 yield* Effect.scoped(
100 Effect.exit(
101 Effect.interrupt.pipe(
102 Effect.withSpan("interrupt-span"),
103 Effect.provide(makeTestLayer(tracePath)),
104 ),
105 ),
106 );
107
108 const records = readTraceRecords(tracePath);
109 assert.equal(records.length, 1);
110 assert.equal(records[0]?.name, "interrupt-span");
111 assert.equal(records[0]?.exit._tag, "Interrupted");
112 } finally {
113 fs.rmSync(tempDir, { recursive: true, force: true });
114 }
115 }),
116 );
117});
apps/server/src/observability/LocalFileTracer.ts+107−0
@@ -0,0 +1,107 @@
1import type * as Exit from "effect/Exit";
2import { Effect, Option, Tracer } from "effect";
3
4import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";
5import { makeTraceSink, type TraceSink } from "./TraceSink.ts";
6
7export interface LocalFileTracerOptions {
8 readonly filePath: string;
9 readonly maxBytes: number;
10 readonly maxFiles: number;
11 readonly batchWindowMs: number;
12 readonly delegate?: Tracer.Tracer;
13 readonly sink?: TraceSink;
14}
15
16class LocalFileSpan implements Tracer.Span {
17 readonly _tag = "Span";
18 readonly name: string;
19 readonly spanId: string;
20 readonly traceId: string;
21 readonly parent: Option.Option<Tracer.AnySpan>;
22 readonly annotations: Tracer.Span["annotations"];
23 readonly links: Array<Tracer.SpanLink>;
24 readonly sampled: boolean;
25 readonly kind: Tracer.SpanKind;
26
27 status: Tracer.SpanStatus;
28 attributes: Map<string, unknown>;
29 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
30
31 constructor(
32 options: Parameters<Tracer.Tracer["span"]>[0],
33 private readonly delegate: Tracer.Span,
34 private readonly push: (record: EffectTraceRecord) => void,
35 ) {
36 this.name = delegate.name;
37 this.spanId = delegate.spanId;
38 this.traceId = delegate.traceId;
39 this.parent = options.parent;
40 this.annotations = options.annotations;
41 this.links = [...options.links];
42 this.sampled = delegate.sampled;
43 this.kind = delegate.kind;
44 this.status = {
45 _tag: "Started",
46 startTime: options.startTime,
47 };
48 this.attributes = new Map();
49 this.events = [];
50 }
51
52 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
53 this.status = {
54 _tag: "Ended",
55 startTime: this.status.startTime,
56 endTime,
57 exit,
58 };
59 this.delegate.end(endTime, exit);
60
61 if (this.sampled) {
62 this.push(spanToTraceRecord(this));
63 }
64 }
65
66 attribute(key: string, value: unknown): void {
67 this.attributes.set(key, value);
68 this.delegate.attribute(key, value);
69 }
70
71 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
72 const nextAttributes = attributes ?? {};
73 this.events.push([name, startTime, nextAttributes]);
74 this.delegate.event(name, startTime, nextAttributes);
75 }
76
77 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
78 this.links.push(...links);
79 this.delegate.addLinks(links);
80 }
81}
82
83export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
84 options: LocalFileTracerOptions,
85) {
86 const sink =
87 options.sink ??
88 (yield* makeTraceSink({
89 filePath: options.filePath,
90 maxBytes: options.maxBytes,
91 maxFiles: options.maxFiles,
92 batchWindowMs: options.batchWindowMs,
93 }));
94
95 const delegate =
96 options.delegate ??
97 Tracer.make({
98 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
99 });
100
101 return Tracer.make({
102 span(spanOptions) {
103 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
104 },
105 ...(delegate.context ? { context: delegate.context } : {}),
106 });
107});
apps/server/src/observability/Metrics.test.ts+111−0
@@ -0,0 +1,111 @@
1import { assert, describe, it } from "@effect/vitest";
2import { Effect, Metric } from "effect";
3
4import { withMetrics } from "./Metrics.ts";
5
6const hasMetricSnapshot = (
7 snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
8 id: string,
9 attributes: Readonly<Record<string, string>>,
10) =>
11 snapshots.some(
12 (snapshot) =>
13 snapshot.id === id &&
14 Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
15 );
16
17describe("withMetrics", () => {
18 it.effect("supports pipe-style usage", () =>
19 Effect.gen(function* () {
20 const counter = Metric.counter("with_metrics_pipe_total");
21 const timer = Metric.timer("with_metrics_pipe_duration");
22
23 const result = yield* Effect.succeed("ok").pipe(
24 withMetrics({
25 counter,
26 timer,
27 attributes: {
28 operation: "pipe",
29 },
30 }),
31 );
32
33 assert.equal(result, "ok");
34
35 const snapshots = yield* Metric.snapshot;
36 assert.equal(
37 hasMetricSnapshot(snapshots, "with_metrics_pipe_total", {
38 operation: "pipe",
39 outcome: "success",
40 }),
41 true,
42 );
43 assert.equal(
44 hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", {
45 operation: "pipe",
46 }),
47 true,
48 );
49 }),
50 );
51
52 it.effect("supports direct invocation", () =>
53 Effect.gen(function* () {
54 const counter = Metric.counter("with_metrics_direct_total");
55
56 yield* withMetrics(Effect.fail("boom"), {
57 counter,
58 attributes: {
59 operation: "direct",
60 },
61 }).pipe(Effect.exit);
62
63 const snapshots = yield* Metric.snapshot;
64 assert.equal(
65 hasMetricSnapshot(snapshots, "with_metrics_direct_total", {
66 operation: "direct",
67 outcome: "failure",
68 }),
69 true,
70 );
71 }),
72 );
73
74 it.effect("evaluates attributes lazily after the wrapped effect runs", () =>
75 Effect.gen(function* () {
76 const counter = Metric.counter("with_metrics_lazy_total");
77 const timer = Metric.timer("with_metrics_lazy_duration");
78 let provider = "unknown";
79
80 yield* Effect.sync(() => {
81 provider = "codex";
82 }).pipe(
83 withMetrics({
84 counter,
85 timer,
86 attributes: () => ({
87 provider,
88 operation: "lazy",
89 }),
90 }),
91 );
92
93 const snapshots = yield* Metric.snapshot;
94 assert.equal(
95 hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
96 provider: "codex",
97 operation: "lazy",
98 outcome: "success",
99 }),
100 true,
101 );
102 assert.equal(
103 hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
104 provider: "codex",
105 operation: "lazy",
106 }),
107 true,
108 );
109 }),
110 );
111});
apps/server/src/observability/Metrics.ts+160−0
@@ -0,0 +1,160 @@
1import { Duration, Effect, Exit, Metric } from "effect";
2import { dual } from "effect/Function";
3
4import {
5 compactMetricAttributes,
6 normalizeModelMetricLabel,
7 outcomeFromExit,
8} from "./Attributes.ts";
9
10export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", {
11 description: "Total RPC requests handled by the websocket RPC server.",
12});
13
14export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", {
15 description: "RPC request handling duration.",
16});
17
18export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", {
19 description: "Total orchestration commands dispatched.",
20});
21
22export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", {
23 description: "Orchestration command dispatch duration.",
24});
25
26export const orchestrationCommandAckDuration = Metric.timer(
27 "t3_orchestration_command_ack_duration",
28 {
29 description:
30 "Time from orchestration command dispatch to the first committed domain event emitted for that command.",
31 },
32);
33
34export const orchestrationEventsProcessedTotal = Metric.counter(
35 "t3_orchestration_events_processed_total",
36 {
37 description: "Total orchestration intent events processed by runtime reactors.",
38 },
39);
40
41export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
42 description: "Total provider session lifecycle operations.",
43});
44
45export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", {
46 description: "Total provider turn lifecycle operations.",
47});
48
49export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
50 description: "Provider turn request duration.",
51});
52
53export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", {
54 description: "Total canonical provider runtime events processed.",
55});
56
57export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {
58 description: "Total git commands executed by the server runtime.",
59});
60
61export const gitCommandDuration = Metric.timer("t3_git_command_duration", {
62 description: "Git command execution duration.",
63});
64
65export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", {
66 description: "Total terminal sessions started.",
67});
68
69export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", {
70 description: "Total terminal restart requests handled.",
71});
72
73export const metricAttributes = (
74 attributes: Readonly<Record<string, unknown>>,
75): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
76
77export const increment = (
78 metric: Metric.Metric<number, unknown>,
79 attributes: Readonly<Record<string, unknown>>,
80 amount = 1,
81) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);
82
83export interface WithMetricsOptions {
84 readonly counter?: Metric.Metric<number, unknown>;
85 readonly timer?: Metric.Metric<Duration.Duration, unknown>;
86 readonly attributes?:
87 | Readonly<Record<string, unknown>>
88 | (() => Readonly<Record<string, unknown>>);
89 readonly outcomeAttributes?: (
90 outcome: ReturnType<typeof outcomeFromExit>,
91 ) => Readonly<Record<string, unknown>>;
92}
93
94const withMetricsImpl = <A, E, R>(
95 effect: Effect.Effect<A, E, R>,
96 options: WithMetricsOptions,
97): Effect.Effect<A, E, R> =>
98 Effect.gen(function* () {
99 const startedAt = Date.now();
100 const exit = yield* Effect.exit(effect);
101 const duration = Duration.millis(Math.max(0, Date.now() - startedAt));
102 const baseAttributes =
103 typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
104
105 if (options.timer) {
106 yield* Metric.update(
107 Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),
108 duration,
109 );
110 }
111
112 if (options.counter) {
113 const outcome = outcomeFromExit(exit);
114 yield* Metric.update(
115 Metric.withAttributes(
116 options.counter,
117 metricAttributes({
118 ...baseAttributes,
119 outcome,
120 ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),
121 }),
122 ),
123 1,
124 );
125 }
126
127 if (Exit.isSuccess(exit)) {
128 return exit.value;
129 }
130 return yield* Effect.failCause(exit.cause);
131 });
132
133export const withMetrics: {
134 <A, E, R>(
135 options: WithMetricsOptions,
136 ): (effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
137 <A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
138} = dual(2, withMetricsImpl);
139
140export const providerMetricAttributes = (
141 provider: string,
142 extra?: Readonly<Record<string, unknown>>,
143) =>
144 compactMetricAttributes({
145 provider,
146 ...extra,
147 });
148
149export const providerTurnMetricAttributes = (input: {
150 readonly provider: string;
151 readonly model: string | null | undefined;
152 readonly extra?: Readonly<Record<string, unknown>>;
153}) => {
154 const modelFamily = normalizeModelMetricLabel(input.model);
155 return compactMetricAttributes({
156 provider: input.provider,
157 ...(modelFamily ? { modelFamily } : {}),
158 ...input.extra,
159 });
160};
apps/server/src/observability/RpcInstrumentation.test.ts+161−0
@@ -0,0 +1,161 @@
1import { assert, describe, it } from "@effect/vitest";
2import { Effect, Exit, Metric, Stream } from "effect";
3
4import {
5 observeRpcEffect,
6 observeRpcStream,
7 observeRpcStreamEffect,
8} from "./RpcInstrumentation.ts";
9
10const hasMetricSnapshot = (
11 snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
12 id: string,
13 attributes: Readonly<Record<string, string>>,
14) =>
15 snapshots.some(
16 (snapshot) =>
17 snapshot.id === id &&
18 Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
19 );
20
21describe("RpcInstrumentation", () => {
22 it.effect("records success metrics for unary RPC handlers", () =>
23 Effect.gen(function* () {
24 yield* observeRpcEffect("rpc.instrumentation.success", Effect.succeed("ok"), {
25 "rpc.aggregate": "test",
26 }).pipe(Effect.withSpan("rpc.instrumentation.success.span"));
27
28 const snapshots = yield* Metric.snapshot;
29
30 assert.equal(
31 hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
32 method: "rpc.instrumentation.success",
33 outcome: "success",
34 }),
35 true,
36 );
37 assert.equal(
38 hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
39 method: "rpc.instrumentation.success",
40 }),
41 true,
42 );
43 }),
44 );
45
46 it.effect("records failure outcomes for unary RPC handlers", () =>
47 Effect.gen(function* () {
48 yield* Effect.exit(
49 observeRpcEffect("rpc.instrumentation.failure", Effect.fail("boom"), {
50 "rpc.aggregate": "test",
51 }).pipe(Effect.withSpan("rpc.instrumentation.failure.span")),
52 );
53
54 const snapshots = yield* Metric.snapshot;
55
56 assert.equal(
57 hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
58 method: "rpc.instrumentation.failure",
59 outcome: "failure",
60 }),
61 true,
62 );
63 assert.equal(
64 hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
65 method: "rpc.instrumentation.failure",
66 }),
67 true,
68 );
69 }),
70 );
71
72 it.effect("records subscription activation metrics for stream RPC handlers", () =>
73 Effect.gen(function* () {
74 const events = yield* Stream.runCollect(
75 observeRpcStreamEffect(
76 "rpc.instrumentation.stream",
77 Effect.succeed(Stream.make("a", "b")),
78 { "rpc.aggregate": "test" },
79 ).pipe(Stream.withSpan("rpc.instrumentation.stream.span")),
80 );
81
82 assert.deepStrictEqual(Array.from(events), ["a", "b"]);
83
84 const snapshots = yield* Metric.snapshot;
85
86 assert.equal(
87 hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
88 method: "rpc.instrumentation.stream",
89 outcome: "success",
90 }),
91 true,
92 );
93 assert.equal(
94 hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
95 method: "rpc.instrumentation.stream",
96 }),
97 true,
98 );
99 }),
100 );
101
102 it.effect("records failure outcomes for direct stream RPC handlers during consumption", () =>
103 Effect.gen(function* () {
104 const exit = yield* Stream.runCollect(
105 observeRpcStream(
106 "rpc.instrumentation.stream.failure",
107 Stream.make("a").pipe(Stream.concat(Stream.fail("boom"))),
108 { "rpc.aggregate": "test" },
109 ).pipe(Stream.withSpan("rpc.instrumentation.stream.failure.span")),
110 ).pipe(Effect.exit);
111
112 assert.equal(Exit.isFailure(exit), true);
113
114 const snapshots = yield* Metric.snapshot;
115
116 assert.equal(
117 hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
118 method: "rpc.instrumentation.stream.failure",
119 outcome: "failure",
120 }),
121 true,
122 );
123 assert.equal(
124 hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
125 method: "rpc.instrumentation.stream.failure",
126 }),
127 true,
128 );
129 }),
130 );
131
132 it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () =>
133 Effect.gen(function* () {
134 const exit = yield* Stream.runCollect(
135 observeRpcStreamEffect(
136 "rpc.instrumentation.stream.effect.failure",
137 Effect.succeed(Stream.fail("boom")),
138 { "rpc.aggregate": "test" },
139 ).pipe(Stream.withSpan("rpc.instrumentation.stream.effect.failure.span")),
140 ).pipe(Effect.exit);
141
142 assert.equal(Exit.isFailure(exit), true);
143
144 const snapshots = yield* Metric.snapshot;
145
146 assert.equal(
147 hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
148 method: "rpc.instrumentation.stream.effect.failure",
149 outcome: "failure",
150 }),
151 true,
152 );
153 assert.equal(
154 hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
155 method: "rpc.instrumentation.stream.effect.failure",
156 }),
157 true,
158 );
159 }),
160 );
161});
apps/server/src/observability/RpcInstrumentation.ts+89−0
@@ -0,0 +1,89 @@
1import { Duration, Effect, Exit, Metric, Stream } from "effect";
2
3import { outcomeFromExit } from "./Attributes.ts";
4import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
5
6const annotateRpcSpan = (
7 method: string,
8 traceAttributes?: Readonly<Record<string, unknown>>,
9): Effect.Effect<void, never, never> =>
10 Effect.annotateCurrentSpan({
11 "rpc.method": method,
12 ...traceAttributes,
13 });
14
15const recordRpcStreamMetrics = <E>(
16 method: string,
17 startedAt: number,
18 exit: Exit.Exit<unknown, E>,
19): Effect.Effect<void, never, never> =>
20 Effect.gen(function* () {
21 yield* Metric.update(
22 Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
23 Duration.millis(Math.max(0, Date.now() - startedAt)),
24 );
25 yield* Metric.update(
26 Metric.withAttributes(
27 rpcRequestsTotal,
28 metricAttributes({
29 method,
30 outcome: outcomeFromExit(exit),
31 }),
32 ),
33 1,
34 );
35 });
36
37export const observeRpcEffect = <A, E, R>(
38 method: string,
39 effect: Effect.Effect<A, E, R>,
40 traceAttributes?: Readonly<Record<string, unknown>>,
41): Effect.Effect<A, E, R> =>
42 Effect.gen(function* () {
43 yield* annotateRpcSpan(method, traceAttributes);
44
45 return yield* effect.pipe(
46 withMetrics({
47 counter: rpcRequestsTotal,
48 timer: rpcRequestDuration,
49 attributes: {
50 method,
51 },
52 }),
53 );
54 });
55
56export const observeRpcStream = <A, E, R>(
57 method: string,
58 stream: Stream.Stream<A, E, R>,
59 traceAttributes?: Readonly<Record<string, unknown>>,
60): Stream.Stream<A, E, R> =>
61 Stream.unwrap(
62 Effect.gen(function* () {
63 yield* annotateRpcSpan(method, traceAttributes);
64 const startedAt = Date.now();
65 return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
66 }),
67 );
68
69export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
70 method: string,
71 effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
72 traceAttributes?: Readonly<Record<string, unknown>>,
73): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
74 Stream.unwrap(
75 Effect.gen(function* () {
76 yield* annotateRpcSpan(method, traceAttributes);
77 const startedAt = Date.now();
78 const exit = yield* Effect.exit(effect);
79
80 if (Exit.isFailure(exit)) {
81 yield* recordRpcStreamMetrics(method, startedAt, exit);
82 return yield* Effect.failCause(exit.cause);
83 }
84
85 return exit.value.pipe(
86 Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),
87 );
88 }),
89 );
apps/server/src/observability/Services/BrowserTraceCollector.ts+13−0
@@ -0,0 +1,13 @@
1import { Context } from "effect";
2import type { Effect } from "effect";
3
4import type { TraceRecord } from "../TraceRecord.ts";
5
6export interface BrowserTraceCollectorShape {
7 readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
8}
9
10export class BrowserTraceCollector extends Context.Service<
11 BrowserTraceCollector,
12 BrowserTraceCollectorShape
13>()("t3/observability/Services/BrowserTraceCollector") {}
apps/server/src/observability/TraceRecord.ts+287−0
@@ -0,0 +1,287 @@
1import { Cause, Exit, Option, Tracer } from "effect";
2
3import { compactTraceAttributes } from "./Attributes.ts";
4import { OtlpResource, OtlpTracer } from "effect/unstable/observability";
5
6interface TraceRecordEvent {
7 readonly name: string;
8 readonly timeUnixNano: string;
9 readonly attributes: Readonly<Record<string, unknown>>;
10}
11
12interface TraceRecordLink {
13 readonly traceId: string;
14 readonly spanId: string;
15 readonly attributes: Readonly<Record<string, unknown>>;
16}
17
18interface BaseTraceRecord {
19 readonly name: string;
20 readonly kind: string;
21 readonly traceId: string;
22 readonly spanId: string;
23 readonly parentSpanId?: string;
24 readonly sampled: boolean;
25 readonly startTimeUnixNano: string;
26 readonly endTimeUnixNano: string;
27 readonly durationMs: number;
28 readonly attributes: Readonly<Record<string, unknown>>;
29 readonly events: ReadonlyArray<TraceRecordEvent>;
30 readonly links: ReadonlyArray<TraceRecordLink>;
31}
32
33export interface EffectTraceRecord extends BaseTraceRecord {
34 readonly type: "effect-span";
35 readonly exit:
36 | {
37 readonly _tag: "Success";
38 }
39 | {
40 readonly _tag: "Interrupted";
41 readonly cause: string;
42 }
43 | {
44 readonly _tag: "Failure";
45 readonly cause: string;
46 };
47}
48
49interface OtlpTraceRecord extends BaseTraceRecord {
50 readonly type: "otlp-span";
51 readonly resourceAttributes: Readonly<Record<string, unknown>>;
52 readonly scope: Readonly<{
53 readonly name?: string;
54 readonly version?: string;
55 readonly attributes: Readonly<Record<string, unknown>>;
56 }>;
57 readonly status?:
58 | {
59 readonly code?: string;
60 readonly message?: string;
61 }
62 | undefined;
63}
64
65export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
66
67type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
68type OtlpSpanEvent = OtlpSpan["events"][number];
69type OtlpSpanLink = OtlpSpan["links"][number];
70type OtlpSpanStatus = OtlpSpan["status"];
71
72interface SerializableSpan {
73 readonly name: string;
74 readonly traceId: string;
75 readonly spanId: string;
76 readonly parent: Option.Option<Tracer.AnySpan>;
77 readonly status: Tracer.SpanStatus;
78 readonly sampled: boolean;
79 readonly kind: Tracer.SpanKind;
80 readonly attributes: ReadonlyMap<string, unknown>;
81 readonly links: ReadonlyArray<Tracer.SpanLink>;
82 readonly events: ReadonlyArray<
83 readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
84 >;
85}
86
87function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
88 if (Exit.isSuccess(exit)) {
89 return { _tag: "Success" };
90 }
91 if (Cause.hasInterruptsOnly(exit.cause)) {
92 return {
93 _tag: "Interrupted",
94 cause: Cause.pretty(exit.cause),
95 };
96 }
97 return {
98 _tag: "Failure",
99 cause: Cause.pretty(exit.cause),
100 };
101}
102
103export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
104 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
105 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
106
107 return {
108 type: "effect-span",
109 name: span.name,
110 traceId: span.traceId,
111 spanId: span.spanId,
112 ...(parentSpanId ? { parentSpanId } : {}),
113 sampled: span.sampled,
114 kind: span.kind,
115 startTimeUnixNano: String(status.startTime),
116 endTimeUnixNano: String(status.endTime),
117 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
118 attributes: compactTraceAttributes(Object.fromEntries(span.attributes)),
119 events: span.events.map(([name, startTime, attributes]) => ({
120 name,
121 timeUnixNano: String(startTime),
122 attributes: compactTraceAttributes(attributes),
123 })),
124 links: span.links.map((link) => ({
125 traceId: link.span.traceId,
126 spanId: link.span.spanId,
127 attributes: compactTraceAttributes(link.attributes),
128 })),
129 exit: formatTraceExit(status.exit),
130 };
131}
132
133const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
134 1: "internal",
135 2: "server",
136 3: "client",
137 4: "producer",
138 5: "consumer",
139};
140
141export function decodeOtlpTraceRecords(
142 payload: OtlpTracer.TraceData,
143): ReadonlyArray<OtlpTraceRecord> {
144 const records: Array<OtlpTraceRecord> = [];
145
146 for (const resourceSpan of payload.resourceSpans) {
147 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
148
149 for (const scopeSpan of resourceSpan.scopeSpans) {
150 for (const span of scopeSpan.spans) {
151 records.push(
152 otlpSpanToTraceRecord({
153 resourceAttributes,
154 scopeAttributes: decodeAttributes(
155 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
156 ? scopeSpan.scope.attributes
157 : [],
158 ),
159 scopeName: scopeSpan.scope.name,
160 scopeVersion:
161 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
162 ? scopeSpan.scope.version
163 : undefined,
164 span,
165 }),
166 );
167 }
168 }
169 }
170
171 return records;
172}
173
174function otlpSpanToTraceRecord(input: {
175 readonly resourceAttributes: Readonly<Record<string, unknown>>;
176 readonly scopeAttributes: Readonly<Record<string, unknown>>;
177 readonly scopeName: string | undefined;
178 readonly scopeVersion: string | undefined;
179 readonly span: OtlpSpan;
180}): OtlpTraceRecord {
181 return {
182 type: "otlp-span",
183 name: input.span.name,
184 traceId: input.span.traceId,
185 spanId: input.span.spanId,
186 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
187 sampled: true,
188 kind: normalizeSpanKind(input.span.kind),
189 startTimeUnixNano: input.span.startTimeUnixNano,
190 endTimeUnixNano: input.span.endTimeUnixNano,
191 durationMs:
192 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
193 1_000_000,
194 attributes: decodeAttributes(input.span.attributes),
195 resourceAttributes: input.resourceAttributes,
196 scope: {
197 ...(input.scopeName ? { name: input.scopeName } : {}),
198 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
199 attributes: input.scopeAttributes,
200 },
201 events: decodeEvents(input.span.events),
202 links: decodeLinks(input.span.links),
203 status: decodeStatus(input.span.status),
204 };
205}
206
207function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
208 const code = String(input.code);
209 const message = input.message;
210
211 return {
212 code,
213 ...(message ? { message } : {}),
214 };
215}
216
217function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
218 return input.map((current) => ({
219 name: current.name,
220 timeUnixNano: current.timeUnixNano,
221 attributes: decodeAttributes(current.attributes),
222 }));
223}
224
225function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
226 return input.flatMap((current) => {
227 const traceId = current.traceId;
228 const spanId = current.spanId;
229 return {
230 traceId,
231 spanId,
232 attributes: decodeAttributes(current.attributes),
233 };
234 });
235}
236
237function decodeAttributes(
238 input: ReadonlyArray<OtlpResource.KeyValue>,
239): Readonly<Record<string, unknown>> {
240 const entries: Record<string, unknown> = {};
241
242 for (const attribute of input) {
243 entries[attribute.key] = decodeValue(attribute.value);
244 }
245
246 return compactTraceAttributes(entries);
247}
248
249function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
250 if (input == null) {
251 return null;
252 }
253 if ("stringValue" in input) {
254 return input.stringValue;
255 }
256 if ("boolValue" in input) {
257 return input.boolValue;
258 }
259 if ("intValue" in input) {
260 return input.intValue;
261 }
262 if ("doubleValue" in input) {
263 return input.doubleValue;
264 }
265 if ("bytesValue" in input) {
266 return input.bytesValue;
267 }
268 if (input.arrayValue) {
269 return input.arrayValue.values.map((entry) => decodeValue(entry));
270 }
271 if (input.kvlistValue) {
272 return decodeAttributes(input.kvlistValue.values);
273 }
274 return null;
275}
276
277function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
278 return SPAN_KIND_MAP[input] || "internal";
279}
280
281function parseBigInt(input: string): bigint {
282 try {
283 return BigInt(input);
284 } catch {
285 return 0n;
286 }
287}
apps/server/src/observability/TraceSink.test.ts+152−0
@@ -0,0 +1,152 @@
1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4
5import { assert, describe, it } from "@effect/vitest";
6import { Effect } from "effect";
7
8import type { TraceRecord } from "./TraceRecord.ts";
9import { makeTraceSink } from "./TraceSink.ts";
10
11const makeRecord = (name: string, suffix = ""): TraceRecord => ({
12 type: "effect-span",
13 name,
14 traceId: `trace-${name}-${suffix}`,
15 spanId: `span-${name}-${suffix}`,
16 sampled: true,
17 kind: "internal",
18 startTimeUnixNano: "1",
19 endTimeUnixNano: "2",
20 durationMs: 1,
21 attributes: {
22 payload: suffix,
23 },
24 events: [],
25 links: [],
26 exit: {
27 _tag: "Success",
28 },
29});
30
31describe("TraceSink", () => {
32 it.effect("flushes buffered records on close", () =>
33 Effect.scoped(
34 Effect.gen(function* () {
35 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
36 const tracePath = path.join(tempDir, "server.trace.ndjson");
37
38 try {
39 const sink = yield* makeTraceSink({
40 filePath: tracePath,
41 maxBytes: 1024,
42 maxFiles: 2,
43 batchWindowMs: 10_000,
44 });
45
46 sink.push(makeRecord("alpha"));
47 sink.push(makeRecord("beta"));
48 yield* sink.close();
49
50 const lines = fs
51 .readFileSync(tracePath, "utf8")
52 .trim()
53 .split("\n")
54 .map((line) => JSON.parse(line) as TraceRecord);
55
56 assert.equal(lines.length, 2);
57 assert.equal(lines[0]?.name, "alpha");
58 assert.equal(lines[1]?.name, "beta");
59 } finally {
60 fs.rmSync(tempDir, { recursive: true, force: true });
61 }
62 }),
63 ),
64 );
65
66 it.effect("rotates the trace file when the configured max size is exceeded", () =>
67 Effect.scoped(
68 Effect.gen(function* () {
69 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
70 const tracePath = path.join(tempDir, "server.trace.ndjson");
71
72 try {
73 const sink = yield* makeTraceSink({
74 filePath: tracePath,
75 maxBytes: 180,
76 maxFiles: 2,
77 batchWindowMs: 10_000,
78 });
79
80 for (let index = 0; index < 8; index += 1) {
81 sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
82 yield* sink.flush;
83 }
84 yield* sink.close();
85
86 const matchingFiles = fs
87 .readdirSync(tempDir)
88 .filter(
89 (entry) =>
90 entry === "server.trace.ndjson" || entry.startsWith("server.trace.ndjson."),
91 )
92 .toSorted();
93
94 assert.equal(
95 matchingFiles.some((entry) => entry === "server.trace.ndjson.1"),
96 true,
97 );
98 assert.equal(
99 matchingFiles.some((entry) => entry === "server.trace.ndjson.3"),
100 false,
101 );
102 } finally {
103 fs.rmSync(tempDir, { recursive: true, force: true });
104 }
105 }),
106 ),
107 );
108
109 it.effect("drops only the invalid record when serialization fails", () =>
110 Effect.scoped(
111 Effect.gen(function* () {
112 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
113 const tracePath = path.join(tempDir, "server.trace.ndjson");
114
115 try {
116 const sink = yield* makeTraceSink({
117 filePath: tracePath,
118 maxBytes: 1024,
119 maxFiles: 2,
120 batchWindowMs: 10_000,
121 });
122
123 const circular: Array<unknown> = [];
124 circular.push(circular);
125
126 sink.push(makeRecord("alpha"));
127 sink.push({
128 ...makeRecord("invalid"),
129 attributes: {
130 circular,
131 },
132 } as TraceRecord);
133 sink.push(makeRecord("beta"));
134 yield* sink.close();
135
136 const lines = fs
137 .readFileSync(tracePath, "utf8")
138 .trim()
139 .split("\n")
140 .map((line) => JSON.parse(line) as TraceRecord);
141
142 assert.deepStrictEqual(
143 lines.map((line) => line.name),
144 ["alpha", "beta"],
145 );
146 } finally {
147 fs.rmSync(tempDir, { recursive: true, force: true });
148 }
149 }),
150 ),
151 );
152});
apps/server/src/observability/TraceSink.ts+68−0
@@ -0,0 +1,68 @@
1import { RotatingFileSink } from "@t3tools/shared/logging";
2import { Effect } from "effect";
3
4import type { TraceRecord } from "./TraceRecord.ts";
5
6const FLUSH_BUFFER_THRESHOLD = 32;
7
8export interface TraceSinkOptions {
9 readonly filePath: string;
10 readonly maxBytes: number;
11 readonly maxFiles: number;
12 readonly batchWindowMs: number;
13}
14
15export interface TraceSink {
16 readonly filePath: string;
17 push: (record: TraceRecord) => void;
18 flush: Effect.Effect<void>;
19 close: () => Effect.Effect<void>;
20}
21
22export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
23 const sink = new RotatingFileSink({
24 filePath: options.filePath,
25 maxBytes: options.maxBytes,
26 maxFiles: options.maxFiles,
27 });
28
29 let buffer: Array<string> = [];
30
31 const flushUnsafe = () => {
32 if (buffer.length === 0) {
33 return;
34 }
35
36 const chunk = buffer.join("");
37 buffer = [];
38
39 try {
40 sink.write(chunk);
41 } catch {
42 buffer.unshift(chunk);
43 }
44 };
45
46 const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false));
47
48 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
49 yield* Effect.forkScoped(
50 Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),
51 );
52
53 return {
54 filePath: options.filePath,
55 push(record) {
56 try {
57 buffer.push(`${JSON.stringify(record)}\n`);
58 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
59 flushUnsafe();
60 }
61 } catch {
62 return;
63 }
64 },
65 flush,
66 close: () => flush,
67 } satisfies TraceSink;
68});
apps/server/src/open.test.ts+105−1
@@ -16,6 +16,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 15 unmodified lines
16 const antigravityLaunch = yield* resolveEditorLaunch(16 const antigravityLaunch = yield* resolveEditorLaunch(
17 { cwd: "/tmp/workspace", editor: "antigravity" },17 { cwd: "/tmp/workspace", editor: "antigravity" },
18 "darwin",18 "darwin",
19 { PATH: "" },
19 );20 );
20 assert.deepEqual(antigravityLaunch, {21 assert.deepEqual(antigravityLaunch, {
21 command: "agy",22 command: "agy",
@@ -25,6 +26,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 3 unmodified lines
25 const cursorLaunch = yield* resolveEditorLaunch(26 const cursorLaunch = yield* resolveEditorLaunch(
26 { cwd: "/tmp/workspace", editor: "cursor" },27 { cwd: "/tmp/workspace", editor: "cursor" },
27 "darwin",28 "darwin",
29 { PATH: "" },
28 );30 );
29 assert.deepEqual(cursorLaunch, {31 assert.deepEqual(cursorLaunch, {
30 command: "cursor",32 command: "cursor",
@@ -43,6 +45,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 12 unmodified lines
43 const vscodeLaunch = yield* resolveEditorLaunch(45 const vscodeLaunch = yield* resolveEditorLaunch(
44 { cwd: "/tmp/workspace", editor: "vscode" },46 { cwd: "/tmp/workspace", editor: "vscode" },
45 "darwin",47 "darwin",
48 { PATH: "" },
46 );49 );
47 assert.deepEqual(vscodeLaunch, {50 assert.deepEqual(vscodeLaunch, {
48 command: "code",51 command: "code",
@@ -70,19 +73,30 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 21 unmodified lines
70 const zedLaunch = yield* resolveEditorLaunch(73 const zedLaunch = yield* resolveEditorLaunch(
71 { cwd: "/tmp/workspace", editor: "zed" },74 { cwd: "/tmp/workspace", editor: "zed" },
72 "darwin",75 "darwin",
76 { PATH: "" },
73 );77 );
74 assert.deepEqual(zedLaunch, {78 assert.deepEqual(zedLaunch, {
75 command: "zed",79 command: "zed",
76 args: ["/tmp/workspace"],80 args: ["/tmp/workspace"],
77 });81 });
82
83 const ideaLaunch = yield* resolveEditorLaunch(
84 { cwd: "/tmp/workspace", editor: "idea" },
85 "darwin",
86 );
87 assert.deepEqual(ideaLaunch, {
88 command: "idea",
89 args: ["/tmp/workspace"],
90 });
78 }),91 }),
79 );92 );
80 93
81 it.effect("uses --goto when editor supports line/column suffixes", () =>94 it.effect("applies launch-style-specific navigation arguments", () =>
82 Effect.gen(function* () {95 Effect.gen(function* () {
83 const lineOnly = yield* resolveEditorLaunch(96 const lineOnly = yield* resolveEditorLaunch(
84 { cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },97 { cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
85 "darwin",98 "darwin",
99 { PATH: "" },
86 );100 );
87 assert.deepEqual(lineOnly, {101 assert.deepEqual(lineOnly, {
88 command: "cursor",102 command: "cursor",
@@ -92,6 +106,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 3 unmodified lines
92 const lineAndColumn = yield* resolveEditorLaunch(106 const lineAndColumn = yield* resolveEditorLaunch(
93 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },107 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
94 "darwin",108 "darwin",
109 { PATH: "" },
95 );110 );
96 assert.deepEqual(lineAndColumn, {111 assert.deepEqual(lineAndColumn, {
97 command: "cursor",112 command: "cursor",
@@ -110,6 +125,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 12 unmodified lines
110 const vscodeLineAndColumn = yield* resolveEditorLaunch(125 const vscodeLineAndColumn = yield* resolveEditorLaunch(
111 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },126 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
112 "darwin",127 "darwin",
128 { PATH: "" },
113 );129 );
114 assert.deepEqual(vscodeLineAndColumn, {130 assert.deepEqual(vscodeLineAndColumn, {
115 command: "code",131 command: "code",
@@ -137,11 +153,71 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 21 unmodified lines
137 const zedLineAndColumn = yield* resolveEditorLaunch(153 const zedLineAndColumn = yield* resolveEditorLaunch(
138 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },154 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
139 "darwin",155 "darwin",
156 { PATH: "" },
140 );157 );
141 assert.deepEqual(zedLineAndColumn, {158 assert.deepEqual(zedLineAndColumn, {
142 command: "zed",159 command: "zed",
143 args: ["/tmp/workspace/src/open.ts:71:5"],160 args: ["/tmp/workspace/src/open.ts:71:5"],
144 });161 });
162
163 const zedLineOnly = yield* resolveEditorLaunch(
164 { cwd: "/tmp/workspace/AGENTS.md:48", editor: "zed" },
165 "darwin",
166 { PATH: "" },
167 );
168 assert.deepEqual(zedLineOnly, {
169 command: "zed",
170 args: ["/tmp/workspace/AGENTS.md:48"],
171 });
172
173 const ideaLineOnly = yield* resolveEditorLaunch(
174 { cwd: "/tmp/workspace/AGENTS.md:48", editor: "idea" },
175 "darwin",
176 );
177 assert.deepEqual(ideaLineOnly, {
178 command: "idea",
179 args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
180 });
181
182 const ideaLineAndColumn = yield* resolveEditorLaunch(
183 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" },
184 "darwin",
185 );
186 assert.deepEqual(ideaLineAndColumn, {
187 command: "idea",
188 args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
189 });
190 }),
191 );
192
193 it.effect("falls back to zeditor when zed is not installed", () =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
196 const path = yield* Path.Path;
197 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
198 yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n");
199 yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
200
201 const result = yield* resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "zed" }, "linux", {
202 PATH: dir,
203 });
204
205 assert.deepEqual(result, {
206 command: "zeditor",
207 args: ["/tmp/workspace"],
208 });
209 }),
210 );
211
212 it.effect("falls back to the primary command when no alias is installed", () =>
213 Effect.gen(function* () {
214 const result = yield* resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "zed" }, "linux", {
215 PATH: "",
216 });
217 assert.deepEqual(result, {
218 command: "zed",
219 args: ["/tmp/workspace"],
220 });
145 }),221 }),
146 );222 );
147 223
@@ -150,6 +226,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 2 unmodified lines
150 const launch1 = yield* resolveEditorLaunch(226 const launch1 = yield* resolveEditorLaunch(
151 { cwd: "/tmp/workspace", editor: "file-manager" },227 { cwd: "/tmp/workspace", editor: "file-manager" },
152 "darwin",228 "darwin",
229 { PATH: "" },
153 );230 );
154 assert.deepEqual(launch1, {231 assert.deepEqual(launch1, {
155 command: "open",232 command: "open",
@@ -159,6 +236,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 3 unmodified lines
159 const launch2 = yield* resolveEditorLaunch(236 const launch2 = yield* resolveEditorLaunch(
160 { cwd: "C:\\workspace", editor: "file-manager" },237 { cwd: "C:\\workspace", editor: "file-manager" },
161 "win32",238 "win32",
239 { PATH: "" },
162 );240 );
163 assert.deepEqual(launch2, {241 assert.deepEqual(launch2, {
164 command: "explorer",242 command: "explorer",
@@ -168,6 +246,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 3 unmodified lines
168 const launch3 = yield* resolveEditorLaunch(246 const launch3 = yield* resolveEditorLaunch(
169 { cwd: "/tmp/workspace", editor: "file-manager" },247 { cwd: "/tmp/workspace", editor: "file-manager" },
170 "linux",248 "linux",
249 { PATH: "" },
171 );250 );
172 assert.deepEqual(launch3, {251 assert.deepEqual(launch3, {
173 command: "xdg-open",252 command: "xdg-open",
@@ -285,4 +364,29 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => { · 111 unmodified lines
285 assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);364 assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
286 }),365 }),
287 );366 );
367
368 it.effect("includes zed when only the zeditor command is installed", () =>
369 Effect.gen(function* () {
370 const fs = yield* FileSystem.FileSystem;
371 const path = yield* Path.Path;
372 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
373
374 yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n");
375 yield* fs.writeFileString(path.join(dir, "xdg-open"), "#!/bin/sh\nexit 0\n");
376 yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
377 yield* fs.chmod(path.join(dir, "xdg-open"), 0o755);
378
379 const editors = resolveAvailableEditors("linux", {
380 PATH: dir,
381 });
382 assert.deepEqual(editors, ["zed", "file-manager"]);
383 }),
384 );
385
386 it("omits file-manager when the platform opener is unavailable", () => {
387 const editors = resolveAvailableEditors("linux", {
388 PATH: "",
389 });
390 assert.deepEqual(editors, []);
391 });
288});392});
apps/server/src/open.ts+86−17
@@ -11,7 +11,7 @@ import { accessSync, constants, statSync } from "node:fs"; · 10 unmodified lines
11import { extname, join } from "node:path";11import { extname, join } from "node:path";
12 12
13import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";13import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
14import { ServiceMap, Effect, Layer } from "effect";14import { Context, Effect, Layer } from "effect";
15 15
16// ==============================16// ==============================
17// Definitions17// Definitions
@@ -34,10 +34,57 @@ interface CommandAvailabilityOptions { · 16 unmodified lines
34 readonly env?: NodeJS.ProcessEnv;34 readonly env?: NodeJS.ProcessEnv;
35}35}
36 36
37const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;37const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
38 38
39function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {39function parseTargetPathAndPosition(target: string): {
40 return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);40 path: string;
41 line: string | undefined;
42 column: string | undefined;
43} | null {
44 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
45 if (!match?.[1] || !match[2]) {
46 return null;
47 }
48
49 return {
50 path: match[1],
51 line: match[2],
52 column: match[3],
53 };
54}
55
56function resolveCommandEditorArgs(
57 editor: (typeof EDITORS)[number],
58 target: string,
59): ReadonlyArray<string> {
60 const parsedTarget = parseTargetPathAndPosition(target);
61
62 switch (editor.launchStyle) {
63 case "direct-path":
64 return [target];
65 case "goto":
66 return parsedTarget ? ["--goto", target] : [target];
67 case "line-column": {
68 if (!parsedTarget) {
69 return [target];
70 }
71
72 const { path, line, column } = parsedTarget;
73 return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
74 }
75 }
76}
77
78function resolveAvailableCommand(
79 commands: ReadonlyArray<string>,
80 options: CommandAvailabilityOptions = {},
81): string | null {
82 for (const command of commands) {
83 if (isCommandAvailable(command, options)) {
84 return command;
85 }
86 }
87 return null;
41}88}
42 89
43function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {90function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
@@ -163,8 +210,16 @@ export function resolveAvailableEditors( · 119 unmodified lines
163 const available: EditorId[] = [];210 const available: EditorId[] = [];
164 211
165 for (const editor of EDITORS) {212 for (const editor of EDITORS) {
166 const command = editor.command ?? fileManagerCommandForPlatform(platform);213 if (editor.commands === null) {
167 if (isCommandAvailable(command, { platform, env })) {214 const command = fileManagerCommandForPlatform(platform);
215 if (isCommandAvailable(command, { platform, env })) {
216 available.push(editor.id);
217 }
218 continue;
219 }
220
221 const command = resolveAvailableCommand(editor.commands, { platform, env });
222 if (command !== null) {
168 available.push(editor.id);223 available.push(editor.id);
169 }224 }
170 }225 }
@@ -192,25 +247,34 @@ export interface OpenShape { · 21 unmodified lines
192/**247/**
193 * Open - Service tag for browser/editor launch operations.248 * Open - Service tag for browser/editor launch operations.
194 */249 */
195export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}250export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
196 251
197// ==============================252// ==============================
198// Implementations253// Implementations
199// ==============================254// ==============================
200 255
201export const resolveEditorLaunch = Effect.fnUntraced(function* (256export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
202 input: OpenInEditorInput,257 input: OpenInEditorInput,
203 platform: NodeJS.Platform = process.platform,258 platform: NodeJS.Platform = process.platform,
259 env: NodeJS.ProcessEnv = process.env,
204): Effect.fn.Return<EditorLaunch, OpenError> {260): Effect.fn.Return<EditorLaunch, OpenError> {
261 yield* Effect.annotateCurrentSpan({
262 "open.editor": input.editor,
263 "open.cwd": input.cwd,
264 "open.platform": platform,
265 });
205 const editorDef = EDITORS.find((editor) => editor.id === input.editor);266 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
206 if (!editorDef) {267 if (!editorDef) {
207 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });268 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
208 }269 }
209 270
210 if (editorDef.command) {271 if (editorDef.commands) {
211 return shouldUseGotoFlag(editorDef, input.cwd)272 const command =
212 ? { command: editorDef.command, args: ["--goto", input.cwd] }273 resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
213 : { command: editorDef.command, args: [input.cwd] };274 return {
275 command,
276 args: resolveCommandEditorArgs(editorDef, input.cwd),
277 };
214 }278 }
215 279
216 if (editorDef.id !== "file-manager") {280 if (editorDef.id !== "file-manager") {
@@ -229,11 +293,16 @@ export const launchDetached = (launch: EditorLaunch) => · 12 unmodified lines
229 yield* Effect.callback<void, OpenError>((resume) => {293 yield* Effect.callback<void, OpenError>((resume) => {
230 let child;294 let child;
231 try {295 try {
232 child = spawn(launch.command, [...launch.args], {296 const isWin32 = process.platform === "win32";
233 detached: true,297 child = spawn(
234 stdio: "ignore",298 launch.command,
235 shell: process.platform === "win32",299 isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
236 });300 {
301 detached: true,
302 stdio: "ignore",
303 shell: isWin32,
304 },
305 );
237 } catch (error) {306 } catch (error) {
238 return resume(307 return resume(
239 Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),308 Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
apps/server/src/orchestration/Layers/CheckpointReactor.test.ts+164−119
@@ -20,6 +20,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; · 19 unmodified lines
20import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";20import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
21import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";21import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
22import { GitCoreLive } from "../../git/Layers/GitCore.ts";22import { GitCoreLive } from "../../git/Layers/GitCore.ts";
23import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
24import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
23import { CheckpointReactorLive } from "./CheckpointReactor.ts";25import { CheckpointReactorLive } from "./CheckpointReactor.ts";
24import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";26import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
25import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";27import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -42,8 +44,8 @@ import { ServerConfig } from "../../config.ts"; · 16 unmodified lines
42import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";44import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
43import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";45import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
44 46
45const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);47const asProjectId = (value: string): ProjectId => ProjectId.make(value);
46const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);48const asTurnId = (value: string): TurnId => TurnId.make(value);
47 49
48type LegacyProviderRuntimeEvent = {50type LegacyProviderRuntimeEvent = {
49 readonly type: string;51 readonly type: string;
@@ -79,7 +81,7 @@ function createProviderServiceHarness( · 29 unmodified lines
79 provider: providerName,81 provider: providerName,
80 status: "ready",82 status: "ready",
81 runtimeMode: "full-access",83 runtimeMode: "full-access",
82 threadId: ThreadId.makeUnsafe("thread-1"),84 threadId: ThreadId.make("thread-1"),
83 cwd: sessionCwd,85 cwd: sessionCwd,
84 createdAt: now,86 createdAt: now,
85 updatedAt: now,87 updatedAt: now,
@@ -96,7 +98,9 @@ function createProviderServiceHarness( · 10 unmodified lines
96 listSessions,98 listSessions,
97 getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),99 getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
98 rollbackConversation,100 rollbackConversation,
99 streamEvents: Stream.fromPubSub(runtimeEventPubSub),101 get streamEvents() {
102 return Stream.fromPubSub(runtimeEventPubSub);
103 },
100 };104 };
101 105
102 const emit = (event: LegacyProviderRuntimeEvent): void => {106 const emit = (event: LegacyProviderRuntimeEvent): void => {
@@ -126,7 +130,7 @@ async function waitForThread( · 23 unmodified lines
126 activities: ReadonlyArray<{ kind: string }>;130 activities: ReadonlyArray<{ kind: string }>;
127 }> => {131 }> => {
128 const readModel = await Effect.runPromise(engine.getReadModel());132 const readModel = await Effect.runPromise(engine.getReadModel());
129 const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));133 const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
130 if (thread && predicate(thread)) {134 if (thread && predicate(thread)) {
131 return thread;135 return thread;
132 }136 }
@@ -240,6 +244,7 @@ describe("CheckpointReactor", () => { · 107 unmodified lines
240 readonly threadWorktreePath?: string | null;244 readonly threadWorktreePath?: string | null;
241 readonly providerSessionCwd?: string;245 readonly providerSessionCwd?: string;
242 readonly providerName?: ProviderKind;246 readonly providerName?: ProviderKind;
247 readonly gitStatusRefreshCalls?: Array<string>;
243 }) {248 }) {
244 const cwd = createGitRepository();249 const cwd = createGitRepository();
245 tempDirs.push(cwd);250 tempDirs.push(cwd);
@@ -254,17 +259,37 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
254 Layer.provide(OrchestrationProjectionPipelineLive),259 Layer.provide(OrchestrationProjectionPipelineLive),
255 Layer.provide(OrchestrationEventStoreLive),260 Layer.provide(OrchestrationEventStoreLive),
256 Layer.provide(OrchestrationCommandReceiptRepositoryLive),261 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
262 Layer.provide(RepositoryIdentityResolverLive),
257 Layer.provide(SqlitePersistenceMemory),263 Layer.provide(SqlitePersistenceMemory),
258 );264 );
259 265
260 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {266 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
261 prefix: "t3-checkpoint-reactor-test-",267 prefix: "t3-checkpoint-reactor-test-",
262 });268 });
269 const gitStatusBroadcasterLayer = Layer.succeed(GitStatusBroadcaster, {
270 getStatus: () => Effect.die("getStatus should not be called in this test"),
271 refreshLocalStatus: (cwd: string) =>
272 Effect.sync(() => {
273 options?.gitStatusRefreshCalls?.push(cwd);
274 }).pipe(
275 Effect.as({
276 isRepo: true,
277 hasOriginRemote: false,
278 isDefaultBranch: true,
279 branch: "main",
280 hasWorkingTreeChanges: false,
281 workingTree: { files: [], insertions: 0, deletions: 0 },
282 }),
283 ),
284 refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
285 streamStatus: () => Stream.empty,
286 });
263 287
264 const layer = CheckpointReactorLive.pipe(288 const layer = CheckpointReactorLive.pipe(
265 Layer.provideMerge(orchestrationLayer),289 Layer.provideMerge(orchestrationLayer),
266 Layer.provideMerge(RuntimeReceiptBusLive),290 Layer.provideMerge(RuntimeReceiptBusLive),
267 Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),291 Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
292 Layer.provideMerge(gitStatusBroadcasterLayer),
268 Layer.provideMerge(CheckpointStoreLive),293 Layer.provideMerge(CheckpointStoreLive),
269 Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),294 Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
270 Layer.provideMerge(WorkspacePathsLive),295 Layer.provideMerge(WorkspacePathsLive),
@@ -285,7 +310,7 @@ describe("CheckpointReactor", () => { · 14 unmodified lines
285 await Effect.runPromise(310 await Effect.runPromise(
286 engine.dispatch({311 engine.dispatch({
287 type: "project.create",312 type: "project.create",
288 commandId: CommandId.makeUnsafe("cmd-project-create"),313 commandId: CommandId.make("cmd-project-create"),
289 projectId: asProjectId("project-1"),314 projectId: asProjectId("project-1"),
290 title: "Test Project",315 title: "Test Project",
291 workspaceRoot: options?.projectWorkspaceRoot ?? cwd,316 workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
@@ -299,8 +324,8 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
299 await Effect.runPromise(324 await Effect.runPromise(
300 engine.dispatch({325 engine.dispatch({
301 type: "thread.create",326 type: "thread.create",
302 commandId: CommandId.makeUnsafe("cmd-thread-create"),327 commandId: CommandId.make("cmd-thread-create"),
303 threadId: ThreadId.makeUnsafe("thread-1"),328 threadId: ThreadId.make("thread-1"),
304 projectId: asProjectId("project-1"),329 projectId: asProjectId("project-1"),
305 title: "Thread",330 title: "Thread",
306 modelSelection: {331 modelSelection: {
@@ -319,21 +344,21 @@ describe("CheckpointReactor", () => { · 12 unmodified lines
319 await runtime.runPromise(344 await runtime.runPromise(
320 checkpointStore.captureCheckpoint({345 checkpointStore.captureCheckpoint({
321 cwd,346 cwd,
322 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),347 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
323 }),348 }),
324 );349 );
325 fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");350 fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
326 await runtime.runPromise(351 await runtime.runPromise(
327 checkpointStore.captureCheckpoint({352 checkpointStore.captureCheckpoint({
328 cwd,353 cwd,
329 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),354 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
330 }),355 }),
331 );356 );
332 fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");357 fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
333 await runtime.runPromise(358 await runtime.runPromise(
334 checkpointStore.captureCheckpoint({359 checkpointStore.captureCheckpoint({
335 cwd,360 cwd,
336 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),361 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
337 }),362 }),
338 );363 );
339 }364 }
@@ -353,10 +378,10 @@ describe("CheckpointReactor", () => { · 13 unmodified lines
353 await Effect.runPromise(378 await Effect.runPromise(
354 harness.engine.dispatch({379 harness.engine.dispatch({
355 type: "thread.session.set",380 type: "thread.session.set",
356 commandId: CommandId.makeUnsafe("cmd-session-set-capture"),381 commandId: CommandId.make("cmd-session-set-capture"),
357 threadId: ThreadId.makeUnsafe("thread-1"),382 threadId: ThreadId.make("thread-1"),
358 session: {383 session: {
359 threadId: ThreadId.makeUnsafe("thread-1"),384 threadId: ThreadId.make("thread-1"),
360 status: "ready",385 status: "ready",
361 providerName: "codex",386 providerName: "codex",
362 runtimeMode: "approval-required",387 runtimeMode: "approval-required",
@@ -370,26 +395,26 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
370 395
371 harness.provider.emit({396 harness.provider.emit({
372 type: "turn.started",397 type: "turn.started",
373 eventId: EventId.makeUnsafe("evt-turn-started-1"),398 eventId: EventId.make("evt-turn-started-1"),
374 provider: "codex",399 provider: "codex",
375 400
376 createdAt: new Date().toISOString(),401 createdAt: new Date().toISOString(),
377 threadId: ThreadId.makeUnsafe("thread-1"),402 threadId: ThreadId.make("thread-1"),
378 turnId: asTurnId("turn-1"),403 turnId: asTurnId("turn-1"),
379 });404 });
380 await waitForGitRefExists(405 await waitForGitRefExists(
381 harness.cwd,406 harness.cwd,
382 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),407 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
383 );408 );
384 409
385 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");410 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
386 harness.provider.emit({411 harness.provider.emit({
387 type: "turn.completed",412 type: "turn.completed",
388 eventId: EventId.makeUnsafe("evt-turn-completed-1"),413 eventId: EventId.make("evt-turn-completed-1"),
389 provider: "codex",414 provider: "codex",
390 415
391 createdAt: new Date().toISOString(),416 createdAt: new Date().toISOString(),
392 threadId: ThreadId.makeUnsafe("thread-1"),417 threadId: ThreadId.make("thread-1"),
393 turnId: asTurnId("turn-1"),418 turnId: asTurnId("turn-1"),
394 payload: { state: "completed" },419 payload: { state: "completed" },
395 });420 });
@@ -401,27 +426,49 @@ describe("CheckpointReactor", () => { · 5 unmodified lines
401 );426 );
402 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);427 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
403 expect(428 expect(
404 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),429 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
405 ).toBe(true);430 ).toBe(true);
406 expect(431 expect(
407 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),432 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
408 ).toBe(true);433 ).toBe(true);
409 expect(434 expect(
410 gitShowFileAtRef(435 gitShowFileAtRef(
411 harness.cwd,436 harness.cwd,
412 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),437 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
413 "README.md",438 "README.md",
414 ),439 ),
415 ).toBe("v1\n");440 ).toBe("v1\n");
416 expect(441 expect(
417 gitShowFileAtRef(442 gitShowFileAtRef(
418 harness.cwd,443 harness.cwd,
419 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),444 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
420 "README.md",445 "README.md",
421 ),446 ),
422 ).toBe("v2\n");447 ).toBe("v2\n");
423 });448 });
424 449
450 it("refreshes local git status state on turn completion using the session cwd", async () => {
451 const gitStatusRefreshCalls: string[] = [];
452 const harness = await createHarness({
453 seedFilesystemCheckpoints: false,
454 gitStatusRefreshCalls,
455 });
456
457 harness.provider.emit({
458 type: "turn.completed",
459 eventId: EventId.make("evt-turn-completed-refresh-local-status"),
460 provider: "codex",
461 createdAt: new Date().toISOString(),
462 threadId: ThreadId.make("thread-1"),
463 turnId: asTurnId("turn-refresh-local-status"),
464 payload: { state: "completed" },
465 });
466
467 await harness.drain();
468
469 expect(gitStatusRefreshCalls).toEqual([harness.cwd]);
470 });
471
425 it("ignores auxiliary thread turn completion while primary turn is active", async () => {472 it("ignores auxiliary thread turn completion while primary turn is active", async () => {
426 const harness = await createHarness({ seedFilesystemCheckpoints: false });473 const harness = await createHarness({ seedFilesystemCheckpoints: false });
427 const createdAt = new Date().toISOString();474 const createdAt = new Date().toISOString();
@@ -429,10 +476,10 @@ describe("CheckpointReactor", () => { · 1 unmodified line
429 await Effect.runPromise(476 await Effect.runPromise(
430 harness.engine.dispatch({477 harness.engine.dispatch({
431 type: "thread.session.set",478 type: "thread.session.set",
432 commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),479 commandId: CommandId.make("cmd-session-set-primary-running"),
433 threadId: ThreadId.makeUnsafe("thread-1"),480 threadId: ThreadId.make("thread-1"),
434 session: {481 session: {
435 threadId: ThreadId.makeUnsafe("thread-1"),482 threadId: ThreadId.make("thread-1"),
436 status: "running",483 status: "running",
437 providerName: "codex",484 providerName: "codex",
438 runtimeMode: "approval-required",485 runtimeMode: "approval-required",
@@ -446,45 +493,43 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
446 493
447 harness.provider.emit({494 harness.provider.emit({
448 type: "turn.started",495 type: "turn.started",
449 eventId: EventId.makeUnsafe("evt-turn-started-main"),496 eventId: EventId.make("evt-turn-started-main"),
450 provider: "codex",497 provider: "codex",
451 498
452 createdAt: new Date().toISOString(),499 createdAt: new Date().toISOString(),
453 threadId: ThreadId.makeUnsafe("thread-1"),500 threadId: ThreadId.make("thread-1"),
454 turnId: asTurnId("turn-main"),501 turnId: asTurnId("turn-main"),
455 });502 });
456 await waitForGitRefExists(503 await waitForGitRefExists(
457 harness.cwd,504 harness.cwd,
458 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),505 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
459 );506 );
460 507
461 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");508 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
462 509
463 harness.provider.emit({510 harness.provider.emit({
464 type: "turn.completed",511 type: "turn.completed",
465 eventId: EventId.makeUnsafe("evt-turn-completed-aux"),512 eventId: EventId.make("evt-turn-completed-aux"),
466 provider: "codex",513 provider: "codex",
467 514
468 createdAt: new Date().toISOString(),515 createdAt: new Date().toISOString(),
469 threadId: ThreadId.makeUnsafe("thread-1"),516 threadId: ThreadId.make("thread-1"),
470 turnId: asTurnId("turn-aux"),517 turnId: asTurnId("turn-aux"),
471 payload: { state: "completed" },518 payload: { state: "completed" },
472 });519 });
473 520
474 await harness.drain();521 await harness.drain();
475 const midReadModel = await Effect.runPromise(harness.engine.getReadModel());522 const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
476 const midThread = midReadModel.threads.find(523 const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
477 (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
478 );
479 expect(midThread?.checkpoints).toHaveLength(0);524 expect(midThread?.checkpoints).toHaveLength(0);
480 525
481 harness.provider.emit({526 harness.provider.emit({
482 type: "turn.completed",527 type: "turn.completed",
483 eventId: EventId.makeUnsafe("evt-turn-completed-main"),528 eventId: EventId.make("evt-turn-completed-main"),
484 provider: "codex",529 provider: "codex",
485 530
486 createdAt: new Date().toISOString(),531 createdAt: new Date().toISOString(),
487 threadId: ThreadId.makeUnsafe("thread-1"),532 threadId: ThreadId.make("thread-1"),
488 turnId: asTurnId("turn-main"),533 turnId: asTurnId("turn-main"),
489 payload: { state: "completed" },534 payload: { state: "completed" },
490 });535 });
@@ -506,10 +551,10 @@ describe("CheckpointReactor", () => { · 15 unmodified lines
506 await Effect.runPromise(551 await Effect.runPromise(
507 harness.engine.dispatch({552 harness.engine.dispatch({
508 type: "thread.session.set",553 type: "thread.session.set",
509 commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),554 commandId: CommandId.make("cmd-session-set-capture-claude"),
510 threadId: ThreadId.makeUnsafe("thread-1"),555 threadId: ThreadId.make("thread-1"),
511 session: {556 session: {
512 threadId: ThreadId.makeUnsafe("thread-1"),557 threadId: ThreadId.make("thread-1"),
513 status: "ready",558 status: "ready",
514 providerName: "claudeAgent",559 providerName: "claudeAgent",
515 runtimeMode: "approval-required",560 runtimeMode: "approval-required",
@@ -523,24 +568,24 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
523 568
524 harness.provider.emit({569 harness.provider.emit({
525 type: "turn.started",570 type: "turn.started",
526 eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),571 eventId: EventId.make("evt-turn-started-claude-1"),
527 provider: "claudeAgent",572 provider: "claudeAgent",
528 createdAt: new Date().toISOString(),573 createdAt: new Date().toISOString(),
529 threadId: ThreadId.makeUnsafe("thread-1"),574 threadId: ThreadId.make("thread-1"),
530 turnId: asTurnId("turn-claude-1"),575 turnId: asTurnId("turn-claude-1"),
531 });576 });
532 await waitForGitRefExists(577 await waitForGitRefExists(
533 harness.cwd,578 harness.cwd,
534 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),579 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
535 );580 );
536 581
537 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");582 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
538 harness.provider.emit({583 harness.provider.emit({
539 type: "turn.completed",584 type: "turn.completed",
540 eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),585 eventId: EventId.make("evt-turn-completed-claude-1"),
541 provider: "claudeAgent",586 provider: "claudeAgent",
542 createdAt: new Date().toISOString(),587 createdAt: new Date().toISOString(),
543 threadId: ThreadId.makeUnsafe("thread-1"),588 threadId: ThreadId.make("thread-1"),
544 turnId: asTurnId("turn-claude-1"),589 turnId: asTurnId("turn-claude-1"),
545 payload: { state: "completed" },590 payload: { state: "completed" },
546 });591 });
@@ -553,7 +598,7 @@ describe("CheckpointReactor", () => { · 6 unmodified lines
553 598
554 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);599 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
555 expect(600 expect(
556 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),601 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
557 ).toBe(true);602 ).toBe(true);
558 });603 });
559 604
@@ -564,10 +609,10 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
564 await Effect.runPromise(609 await Effect.runPromise(
565 harness.engine.dispatch({610 harness.engine.dispatch({
566 type: "thread.session.set",611 type: "thread.session.set",
567 commandId: CommandId.makeUnsafe("cmd-session-set-missing-baseline-diff"),612 commandId: CommandId.make("cmd-session-set-missing-baseline-diff"),
568 threadId: ThreadId.makeUnsafe("thread-1"),613 threadId: ThreadId.make("thread-1"),
569 session: {614 session: {
570 threadId: ThreadId.makeUnsafe("thread-1"),615 threadId: ThreadId.make("thread-1"),
571 status: "ready",616 status: "ready",
572 providerName: "codex",617 providerName: "codex",
573 runtimeMode: "approval-required",618 runtimeMode: "approval-required",
@@ -581,11 +626,11 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
581 626
582 harness.provider.emit({627 harness.provider.emit({
583 type: "turn.completed",628 type: "turn.completed",
584 eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),629 eventId: EventId.make("evt-turn-completed-missing-baseline"),
585 provider: "codex",630 provider: "codex",
586 631
587 createdAt: new Date().toISOString(),632 createdAt: new Date().toISOString(),
588 threadId: ThreadId.makeUnsafe("thread-1"),633 threadId: ThreadId.make("thread-1"),
589 turnId: asTurnId("turn-missing-baseline"),634 turnId: asTurnId("turn-missing-baseline"),
590 payload: { state: "completed" },635 payload: { state: "completed" },
591 });636 });
@@ -614,10 +659,10 @@ describe("CheckpointReactor", () => { · 22 unmodified lines
614 await Effect.runPromise(659 await Effect.runPromise(
615 harness.engine.dispatch({660 harness.engine.dispatch({
616 type: "thread.turn.start",661 type: "thread.turn.start",
617 commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"),662 commandId: CommandId.make("cmd-turn-start-for-baseline"),
618 threadId: ThreadId.makeUnsafe("thread-1"),663 threadId: ThreadId.make("thread-1"),
619 message: {664 message: {
620 messageId: MessageId.makeUnsafe("message-user-1"),665 messageId: MessageId.make("message-user-1"),
621 role: "user",666 role: "user",
622 text: "start turn",667 text: "start turn",
623 attachments: [],668 attachments: [],
@@ -630,12 +675,12 @@ describe("CheckpointReactor", () => { · 6 unmodified lines
630 675
631 await waitForGitRefExists(676 await waitForGitRefExists(
632 harness.cwd,677 harness.cwd,
633 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),678 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
634 );679 );
635 expect(680 expect(
636 gitShowFileAtRef(681 gitShowFileAtRef(
637 harness.cwd,682 harness.cwd,
638 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),683 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
639 "README.md",684 "README.md",
640 ),685 ),
641 ).toBe("v1\n");686 ).toBe("v1\n");
@@ -652,10 +697,10 @@ describe("CheckpointReactor", () => { · 10 unmodified lines
652 await Effect.runPromise(697 await Effect.runPromise(
653 harness.engine.dispatch({698 harness.engine.dispatch({
654 type: "thread.session.set",699 type: "thread.session.set",
655 commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"),700 commandId: CommandId.make("cmd-session-set-missing-provider-cwd"),
656 threadId: ThreadId.makeUnsafe("thread-1"),701 threadId: ThreadId.make("thread-1"),
657 session: {702 session: {
658 threadId: ThreadId.makeUnsafe("thread-1"),703 threadId: ThreadId.make("thread-1"),
659 status: "running",704 status: "running",
660 providerName: "codex",705 providerName: "codex",
661 runtimeMode: "approval-required",706 runtimeMode: "approval-required",
@@ -670,23 +715,23 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
670 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");715 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
671 harness.provider.emit({716 harness.provider.emit({
672 type: "turn.completed",717 type: "turn.completed",
673 eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),718 eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
674 provider: "codex",719 provider: "codex",
675 720
676 createdAt: new Date().toISOString(),721 createdAt: new Date().toISOString(),
677 threadId: ThreadId.makeUnsafe("thread-1"),722 threadId: ThreadId.make("thread-1"),
678 turnId: asTurnId("turn-missing-cwd"),723 turnId: asTurnId("turn-missing-cwd"),
679 payload: { state: "completed" },724 payload: { state: "completed" },
680 });725 });
681 726
682 await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");727 await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
683 expect(728 expect(
684 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),729 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
685 ).toBe(true);730 ).toBe(true);
686 expect(731 expect(
687 gitShowFileAtRef(732 gitShowFileAtRef(
688 harness.cwd,733 harness.cwd,
689 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),734 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
690 "README.md",735 "README.md",
691 ),736 ),
692 ).toBe("v2\n");737 ).toBe("v2\n");
@@ -699,10 +744,10 @@ describe("CheckpointReactor", () => { · 6 unmodified lines
699 await Effect.runPromise(744 await Effect.runPromise(
700 harness.engine.dispatch({745 harness.engine.dispatch({
701 type: "thread.session.set",746 type: "thread.session.set",
702 commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"),747 commandId: CommandId.make("cmd-session-set-checkpoint-captured"),
703 threadId: ThreadId.makeUnsafe("thread-1"),748 threadId: ThreadId.make("thread-1"),
704 session: {749 session: {
705 threadId: ThreadId.makeUnsafe("thread-1"),750 threadId: ThreadId.make("thread-1"),
706 status: "ready",751 status: "ready",
707 providerName: "codex",752 providerName: "codex",
708 runtimeMode: "approval-required",753 runtimeMode: "approval-required",
@@ -716,11 +761,11 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
716 761
717 harness.provider.emit({762 harness.provider.emit({
718 type: "checkpoint.captured",763 type: "checkpoint.captured",
719 eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),764 eventId: EventId.make("evt-checkpoint-captured-3"),
720 provider: "codex",765 provider: "codex",
721 766
722 createdAt: new Date().toISOString(),767 createdAt: new Date().toISOString(),
723 threadId: ThreadId.makeUnsafe("thread-1"),768 threadId: ThreadId.make("thread-1"),
724 turnId: asTurnId("turn-3"),769 turnId: asTurnId("turn-3"),
725 turnCount: 3,770 turnCount: 3,
726 status: "completed",771 status: "completed",
@@ -728,7 +773,7 @@ describe("CheckpointReactor", () => { · 1 unmodified line
728 773
729 await harness.drain();774 await harness.drain();
730 const readModel = await Effect.runPromise(harness.engine.getReadModel());775 const readModel = await Effect.runPromise(harness.engine.getReadModel());
731 const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));776 const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
732 expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(777 expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
733 false,778 false,
734 );779 );
@@ -749,10 +794,10 @@ describe("CheckpointReactor", () => { · 14 unmodified lines
749 await Effect.runPromise(794 await Effect.runPromise(
750 harness.engine.dispatch({795 harness.engine.dispatch({
751 type: "thread.session.set",796 type: "thread.session.set",
752 commandId: CommandId.makeUnsafe("cmd-session-set-non-repo-runtime"),797 commandId: CommandId.make("cmd-session-set-non-repo-runtime"),
753 threadId: ThreadId.makeUnsafe("thread-1"),798 threadId: ThreadId.make("thread-1"),
754 session: {799 session: {
755 threadId: ThreadId.makeUnsafe("thread-1"),800 threadId: ThreadId.make("thread-1"),
756 status: "ready",801 status: "ready",
757 providerName: "codex",802 providerName: "codex",
758 runtimeMode: "approval-required",803 runtimeMode: "approval-required",
@@ -766,31 +811,31 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
766 811
767 harness.provider.emit({812 harness.provider.emit({
768 type: "turn.completed",813 type: "turn.completed",
769 eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),814 eventId: EventId.make("evt-runtime-capture-failure"),
770 provider: "codex",815 provider: "codex",
771 816
772 createdAt: new Date().toISOString(),817 createdAt: new Date().toISOString(),
773 threadId: ThreadId.makeUnsafe("thread-1"),818 threadId: ThreadId.make("thread-1"),
774 turnId: asTurnId("turn-runtime-failure"),819 turnId: asTurnId("turn-runtime-failure"),
775 payload: { state: "completed" },820 payload: { state: "completed" },
776 });821 });
777 822
778 harness.provider.emit({823 harness.provider.emit({
779 type: "turn.started",824 type: "turn.started",
780 eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),825 eventId: EventId.make("evt-turn-started-after-runtime-failure"),
781 provider: "codex",826 provider: "codex",
782 827
783 createdAt: new Date().toISOString(),828 createdAt: new Date().toISOString(),
784 threadId: ThreadId.makeUnsafe("thread-1"),829 threadId: ThreadId.make("thread-1"),
785 turnId: asTurnId("turn-after-runtime-failure"),830 turnId: asTurnId("turn-after-runtime-failure"),
786 });831 });
787 832
788 await waitForGitRefExists(833 await waitForGitRefExists(
789 harness.cwd,834 harness.cwd,
790 checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),835 checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
791 );836 );
792 expect(837 expect(
793 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),838 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
794 ).toBe(true);839 ).toBe(true);
795 });840 });
796 841
@@ -801,10 +846,10 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
801 await Effect.runPromise(846 await Effect.runPromise(
802 harness.engine.dispatch({847 harness.engine.dispatch({
803 type: "thread.session.set",848 type: "thread.session.set",
804 commandId: CommandId.makeUnsafe("cmd-session-set"),849 commandId: CommandId.make("cmd-session-set"),
805 threadId: ThreadId.makeUnsafe("thread-1"),850 threadId: ThreadId.make("thread-1"),
806 session: {851 session: {
807 threadId: ThreadId.makeUnsafe("thread-1"),852 threadId: ThreadId.make("thread-1"),
808 status: "ready",853 status: "ready",
809 providerName: "codex",854 providerName: "codex",
810 runtimeMode: "approval-required",855 runtimeMode: "approval-required",
@@ -819,11 +864,11 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
819 await Effect.runPromise(864 await Effect.runPromise(
820 harness.engine.dispatch({865 harness.engine.dispatch({
821 type: "thread.turn.diff.complete",866 type: "thread.turn.diff.complete",
822 commandId: CommandId.makeUnsafe("cmd-diff-1"),867 commandId: CommandId.make("cmd-diff-1"),
823 threadId: ThreadId.makeUnsafe("thread-1"),868 threadId: ThreadId.make("thread-1"),
824 turnId: asTurnId("turn-1"),869 turnId: asTurnId("turn-1"),
825 completedAt: createdAt,870 completedAt: createdAt,
826 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),871 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
827 status: "ready",872 status: "ready",
828 files: [],873 files: [],
829 checkpointTurnCount: 1,874 checkpointTurnCount: 1,
@@ -833,11 +878,11 @@ describe("CheckpointReactor", () => { · 3 unmodified lines
833 await Effect.runPromise(878 await Effect.runPromise(
834 harness.engine.dispatch({879 harness.engine.dispatch({
835 type: "thread.turn.diff.complete",880 type: "thread.turn.diff.complete",
836 commandId: CommandId.makeUnsafe("cmd-diff-2"),881 commandId: CommandId.make("cmd-diff-2"),
837 threadId: ThreadId.makeUnsafe("thread-1"),882 threadId: ThreadId.make("thread-1"),
838 turnId: asTurnId("turn-2"),883 turnId: asTurnId("turn-2"),
839 completedAt: createdAt,884 completedAt: createdAt,
840 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),885 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
841 status: "ready",886 status: "ready",
842 files: [],887 files: [],
843 checkpointTurnCount: 2,888 checkpointTurnCount: 2,
@@ -848,8 +893,8 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
848 await Effect.runPromise(893 await Effect.runPromise(
849 harness.engine.dispatch({894 harness.engine.dispatch({
850 type: "thread.checkpoint.revert",895 type: "thread.checkpoint.revert",
851 commandId: CommandId.makeUnsafe("cmd-revert-request"),896 commandId: CommandId.make("cmd-revert-request"),
852 threadId: ThreadId.makeUnsafe("thread-1"),897 threadId: ThreadId.make("thread-1"),
853 turnCount: 1,898 turnCount: 1,
854 createdAt,899 createdAt,
855 }),900 }),
@@ -863,12 +908,12 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
863 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);908 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
864 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);909 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
865 expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({910 expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
866 threadId: ThreadId.makeUnsafe("thread-1"),911 threadId: ThreadId.make("thread-1"),
867 numTurns: 1,912 numTurns: 1,
868 });913 });
869 expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");914 expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
870 expect(915 expect(
871 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2)),916 gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2)),
872 ).toBe(false);917 ).toBe(false);
873 });918 });
874 919
@@ -879,10 +924,10 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
879 await Effect.runPromise(924 await Effect.runPromise(
880 harness.engine.dispatch({925 harness.engine.dispatch({
881 type: "thread.session.set",926 type: "thread.session.set",
882 commandId: CommandId.makeUnsafe("cmd-session-set-claude"),927 commandId: CommandId.make("cmd-session-set-claude"),
883 threadId: ThreadId.makeUnsafe("thread-1"),928 threadId: ThreadId.make("thread-1"),
884 session: {929 session: {
885 threadId: ThreadId.makeUnsafe("thread-1"),930 threadId: ThreadId.make("thread-1"),
886 status: "ready",931 status: "ready",
887 providerName: "claudeAgent",932 providerName: "claudeAgent",
888 runtimeMode: "approval-required",933 runtimeMode: "approval-required",
@@ -897,11 +942,11 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
897 await Effect.runPromise(942 await Effect.runPromise(
898 harness.engine.dispatch({943 harness.engine.dispatch({
899 type: "thread.turn.diff.complete",944 type: "thread.turn.diff.complete",
900 commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),945 commandId: CommandId.make("cmd-diff-claude-1"),
901 threadId: ThreadId.makeUnsafe("thread-1"),946 threadId: ThreadId.make("thread-1"),
902 turnId: asTurnId("turn-claude-1"),947 turnId: asTurnId("turn-claude-1"),
903 completedAt: createdAt,948 completedAt: createdAt,
904 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),949 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
905 status: "ready",950 status: "ready",
906 files: [],951 files: [],
907 checkpointTurnCount: 1,952 checkpointTurnCount: 1,
@@ -911,11 +956,11 @@ describe("CheckpointReactor", () => { · 3 unmodified lines
911 await Effect.runPromise(956 await Effect.runPromise(
912 harness.engine.dispatch({957 harness.engine.dispatch({
913 type: "thread.turn.diff.complete",958 type: "thread.turn.diff.complete",
914 commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),959 commandId: CommandId.make("cmd-diff-claude-2"),
915 threadId: ThreadId.makeUnsafe("thread-1"),960 threadId: ThreadId.make("thread-1"),
916 turnId: asTurnId("turn-claude-2"),961 turnId: asTurnId("turn-claude-2"),
917 completedAt: createdAt,962 completedAt: createdAt,
918 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),963 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
919 status: "ready",964 status: "ready",
920 files: [],965 files: [],
921 checkpointTurnCount: 2,966 checkpointTurnCount: 2,
@@ -926,8 +971,8 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
926 await Effect.runPromise(971 await Effect.runPromise(
927 harness.engine.dispatch({972 harness.engine.dispatch({
928 type: "thread.checkpoint.revert",973 type: "thread.checkpoint.revert",
929 commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),974 commandId: CommandId.make("cmd-revert-request-claude"),
930 threadId: ThreadId.makeUnsafe("thread-1"),975 threadId: ThreadId.make("thread-1"),
931 turnCount: 1,976 turnCount: 1,
932 createdAt,977 createdAt,
933 }),978 }),
@@ -936,7 +981,7 @@ describe("CheckpointReactor", () => { · 2 unmodified lines
936 await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");981 await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
937 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);982 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
938 expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({983 expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
939 threadId: ThreadId.makeUnsafe("thread-1"),984 threadId: ThreadId.make("thread-1"),
940 numTurns: 1,985 numTurns: 1,
941 });986 });
942 });987 });
@@ -948,10 +993,10 @@ describe("CheckpointReactor", () => { · 5 unmodified lines
948 await Effect.runPromise(993 await Effect.runPromise(
949 harness.engine.dispatch({994 harness.engine.dispatch({
950 type: "thread.session.set",995 type: "thread.session.set",
951 commandId: CommandId.makeUnsafe("cmd-session-set-inline-revert"),996 commandId: CommandId.make("cmd-session-set-inline-revert"),
952 threadId: ThreadId.makeUnsafe("thread-1"),997 threadId: ThreadId.make("thread-1"),
953 session: {998 session: {
954 threadId: ThreadId.makeUnsafe("thread-1"),999 threadId: ThreadId.make("thread-1"),
955 status: "ready",1000 status: "ready",
956 providerName: "codex",1001 providerName: "codex",
957 runtimeMode: "approval-required",1002 runtimeMode: "approval-required",
@@ -966,11 +1011,11 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
966 await Effect.runPromise(1011 await Effect.runPromise(
967 harness.engine.dispatch({1012 harness.engine.dispatch({
968 type: "thread.turn.diff.complete",1013 type: "thread.turn.diff.complete",
969 commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-1"),1014 commandId: CommandId.make("cmd-inline-revert-diff-1"),
970 threadId: ThreadId.makeUnsafe("thread-1"),1015 threadId: ThreadId.make("thread-1"),
971 turnId: asTurnId("turn-1"),1016 turnId: asTurnId("turn-1"),
972 completedAt: createdAt,1017 completedAt: createdAt,
973 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),1018 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
974 status: "ready",1019 status: "ready",
975 files: [],1020 files: [],
976 checkpointTurnCount: 1,1021 checkpointTurnCount: 1,
@@ -980,11 +1025,11 @@ describe("CheckpointReactor", () => { · 3 unmodified lines
980 await Effect.runPromise(1025 await Effect.runPromise(
981 harness.engine.dispatch({1026 harness.engine.dispatch({
982 type: "thread.turn.diff.complete",1027 type: "thread.turn.diff.complete",
983 commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-2"),1028 commandId: CommandId.make("cmd-inline-revert-diff-2"),
984 threadId: ThreadId.makeUnsafe("thread-1"),1029 threadId: ThreadId.make("thread-1"),
985 turnId: asTurnId("turn-2"),1030 turnId: asTurnId("turn-2"),
986 completedAt: createdAt,1031 completedAt: createdAt,
987 checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),1032 checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
988 status: "ready",1033 status: "ready",
989 files: [],1034 files: [],
990 checkpointTurnCount: 2,1035 checkpointTurnCount: 2,
@@ -995,8 +1040,8 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
995 await Effect.runPromise(1040 await Effect.runPromise(
996 harness.engine.dispatch({1041 harness.engine.dispatch({
997 type: "thread.checkpoint.revert",1042 type: "thread.checkpoint.revert",
998 commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-1"),1043 commandId: CommandId.make("cmd-sequenced-revert-request-1"),
999 threadId: ThreadId.makeUnsafe("thread-1"),1044 threadId: ThreadId.make("thread-1"),
1000 turnCount: 1,1045 turnCount: 1,
1001 createdAt,1046 createdAt,
1002 }),1047 }),
@@ -1004,8 +1049,8 @@ describe("CheckpointReactor", () => { · 1 unmodified line
1004 await Effect.runPromise(1049 await Effect.runPromise(
1005 harness.engine.dispatch({1050 harness.engine.dispatch({
1006 type: "thread.checkpoint.revert",1051 type: "thread.checkpoint.revert",
1007 commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-0"),1052 commandId: CommandId.make("cmd-sequenced-revert-request-0"),
1008 threadId: ThreadId.makeUnsafe("thread-1"),1053 threadId: ThreadId.make("thread-1"),
1009 turnCount: 0,1054 turnCount: 0,
1010 createdAt,1055 createdAt,
1011 }),1056 }),
@@ -1015,11 +1060,11 @@ describe("CheckpointReactor", () => { · 3 unmodified lines
1015 1060
1016 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);1061 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
1017 expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({1062 expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
1018 threadId: ThreadId.makeUnsafe("thread-1"),1063 threadId: ThreadId.make("thread-1"),
1019 numTurns: 1,1064 numTurns: 1,
1020 });1065 });
1021 expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({1066 expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
1022 threadId: ThreadId.makeUnsafe("thread-1"),1067 threadId: ThreadId.make("thread-1"),
1023 numTurns: 1,1068 numTurns: 1,
1024 });1069 });
1025 });1070 });
@@ -1031,8 +1076,8 @@ describe("CheckpointReactor", () => { · 5 unmodified lines
1031 await Effect.runPromise(1076 await Effect.runPromise(
1032 harness.engine.dispatch({1077 harness.engine.dispatch({
1033 type: "thread.checkpoint.revert",1078 type: "thread.checkpoint.revert",
1034 commandId: CommandId.makeUnsafe("cmd-revert-no-session"),1079 commandId: CommandId.make("cmd-revert-no-session"),
1035 threadId: ThreadId.makeUnsafe("thread-1"),1080 threadId: ThreadId.make("thread-1"),
1036 turnCount: 1,1081 turnCount: 1,
1037 createdAt,1082 createdAt,
1038 }),1083 }),
apps/server/src/orchestration/Layers/CheckpointReactor.ts+142−115
@@ -24,6 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts"; · 23 unmodified lines
24import { CheckpointStoreError } from "../../checkpointing/Errors.ts";24import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
25import { OrchestrationDispatchError } from "../Errors.ts";25import { OrchestrationDispatchError } from "../Errors.ts";
26import { isGitRepository } from "../../git/Utils.ts";26import { isGitRepository } from "../../git/Utils.ts";
27import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
27import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";28import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
28 29
29type ReactorInput =30type ReactorInput =
@@ -37,7 +38,7 @@ type ReactorInput = · 7 unmodified lines
37 };38 };
38 39
39function toTurnId(value: string | undefined): TurnId | null {40function toTurnId(value: string | undefined): TurnId | null {
40 return value === undefined ? null : TurnId.makeUnsafe(String(value));41 return value === undefined ? null : TurnId.make(String(value));
41}42}
42 43
43function sameId(left: string | null | undefined, right: string | null | undefined): boolean {44function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
@@ -61,7 +62,7 @@ function checkpointStatusFromRuntime(status: string | undefined): "ready" | "mis · 17 unmodified lines
61}62}
62 63
63const serverCommandId = (tag: string): CommandId =>64const serverCommandId = (tag: string): CommandId =>
64 CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);65 CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
65 66
66const make = Effect.gen(function* () {67const make = Effect.gen(function* () {
67 const orchestrationEngine = yield* OrchestrationEngineService;68 const orchestrationEngine = yield* OrchestrationEngineService;
@@ -69,6 +70,7 @@ const make = Effect.gen(function* () { · 1 unmodified line
69 const checkpointStore = yield* CheckpointStore;70 const checkpointStore = yield* CheckpointStore;
70 const receiptBus = yield* RuntimeReceiptBus;71 const receiptBus = yield* RuntimeReceiptBus;
71 const workspaceEntries = yield* WorkspaceEntries;72 const workspaceEntries = yield* WorkspaceEntries;
73 const gitStatusBroadcaster = yield* GitStatusBroadcaster;
72 74
73 const appendRevertFailureActivity = (input: {75 const appendRevertFailureActivity = (input: {
74 readonly threadId: ThreadId;76 readonly threadId: ThreadId;
@@ -81,7 +83,7 @@ const make = Effect.gen(function* () { · 6 unmodified lines
81 commandId: serverCommandId("checkpoint-revert-failure"),83 commandId: serverCommandId("checkpoint-revert-failure"),
82 threadId: input.threadId,84 threadId: input.threadId,
83 activity: {85 activity: {
84 id: EventId.makeUnsafe(crypto.randomUUID()),86 id: EventId.make(crypto.randomUUID()),
85 tone: "error",87 tone: "error",
86 kind: "checkpoint.revert.failed",88 kind: "checkpoint.revert.failed",
87 summary: "Checkpoint revert failed",89 summary: "Checkpoint revert failed",
@@ -106,7 +108,7 @@ const make = Effect.gen(function* () { · 18 unmodified lines
106 commandId: serverCommandId("checkpoint-capture-failure"),108 commandId: serverCommandId("checkpoint-capture-failure"),
107 threadId: input.threadId,109 threadId: input.threadId,
108 activity: {110 activity: {
109 id: EventId.makeUnsafe(crypto.randomUUID()),111 id: EventId.make(crypto.randomUUID()),
110 tone: "error",112 tone: "error",
111 kind: "checkpoint.capture.failed",113 kind: "checkpoint.capture.failed",
112 summary: "Checkpoint capture failed",114 summary: "Checkpoint capture failed",
@@ -119,7 +121,7 @@ const make = Effect.gen(function* () { · 6 unmodified lines
119 createdAt: input.createdAt,121 createdAt: input.createdAt,
120 });122 });
121 123
122 const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (124 const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
123 threadId: ThreadId,125 threadId: ThreadId,
124 ): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {126 ): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
125 const readModel = yield* orchestrationEngine.getReadModel();127 const readModel = yield* orchestrationEngine.getReadModel();
@@ -153,7 +155,7 @@ const make = Effect.gen(function* () { · 27 unmodified lines
153 // active provider session CWD and falling back to the thread/project config.155 // active provider session CWD and falling back to the thread/project config.
154 // Returns undefined when no CWD can be determined or the workspace is not156 // Returns undefined when no CWD can be determined or the workspace is not
155 // a git repository.157 // a git repository.
156 const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {158 const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: {
157 readonly threadId: ThreadId;159 readonly threadId: ThreadId;
158 readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };160 readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
159 readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;161 readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
@@ -188,7 +190,7 @@ const make = Effect.gen(function* () { · 28 unmodified lines
188 // Shared tail for both capture paths: creates the git checkpoint ref, diffs190 // Shared tail for both capture paths: creates the git checkpoint ref, diffs
189 // it against the previous turn, then dispatches the domain events to update191 // it against the previous turn, then dispatches the domain events to update
190 // the orchestration read model.192 // the orchestration read model.
191 const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {193 const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: {
192 readonly threadId: ThreadId;194 readonly threadId: ThreadId;
193 readonly turnId: TurnId;195 readonly turnId: TurnId;
194 readonly thread: {196 readonly thread: {
@@ -268,7 +270,7 @@ const make = Effect.gen(function* () { · 73 unmodified lines
268 input.thread.messages270 input.thread.messages
269 .toReversed()271 .toReversed()
270 .find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??272 .find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
271 MessageId.makeUnsafe(`assistant:${input.turnId}`);273 MessageId.make(`assistant:${input.turnId}`);
272 274
273 yield* orchestrationEngine.dispatch({275 yield* orchestrationEngine.dispatch({
274 type: "thread.turn.diff.complete",276 type: "thread.turn.diff.complete",
@@ -305,7 +307,7 @@ const make = Effect.gen(function* () { · 30 unmodified lines
305 commandId: serverCommandId("checkpoint-captured-activity"),307 commandId: serverCommandId("checkpoint-captured-activity"),
306 threadId: input.threadId,308 threadId: input.threadId,
307 activity: {309 activity: {
308 id: EventId.makeUnsafe(crypto.randomUUID()),310 id: EventId.make(crypto.randomUUID()),
309 tone: "info",311 tone: "info",
310 kind: "checkpoint.captured",312 kind: "checkpoint.captured",
311 summary: "Checkpoint captured",313 summary: "Checkpoint captured",
@@ -321,70 +323,70 @@ const make = Effect.gen(function* () { · 9 unmodified lines
321 });323 });
322 324
323 // Captures a real git checkpoint when a turn completes via a runtime event.325 // Captures a real git checkpoint when a turn completes via a runtime event.
324 const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (326 const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
325 event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,327 function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
326 ) {328 const turnId = toTurnId(event.turnId);
327 const turnId = toTurnId(event.turnId);329 if (!turnId) {
328 if (!turnId) {330 return;
329 return;331 }
330 }
331
332 const readModel = yield* orchestrationEngine.getReadModel();
333 const thread = readModel.threads.find((entry) => entry.id === event.threadId);
334 if (!thread) {
335 return;
336 }
337 332
338 // When a primary turn is active, only that turn may produce completion checkpoints.333 const readModel = yield* orchestrationEngine.getReadModel();
339 if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {334 const thread = readModel.threads.find((entry) => entry.id === event.threadId);
340 return;335 if (!thread) {
341 }336 return;
337 }
342 338
343 // Only skip if a real (non-placeholder) checkpoint already exists for this turn.339 // When a primary turn is active, only that turn may produce completion checkpoints.
344 // ProviderRuntimeIngestion may insert placeholder entries with status "missing"340 if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
345 // before this reactor runs; those must not prevent real git capture.341 return;
346 if (342 }
347 thread.checkpoints.some(
348 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
349 )
350 ) {
351 return;
352 }
353 343
354 const checkpointCwd = yield* resolveCheckpointCwd({344 // Only skip if a real (non-placeholder) checkpoint already exists for this turn.
355 threadId: thread.id,345 // ProviderRuntimeIngestion may insert placeholder entries with status "missing"
356 thread,346 // before this reactor runs; those must not prevent real git capture.
357 projects: readModel.projects,347 if (
358 preferSessionRuntime: true,348 thread.checkpoints.some(
359 });349 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
360 if (!checkpointCwd) {350 )
361 return;351 ) {
362 }352 return;
353 }
363 354
364 // If a placeholder checkpoint exists for this turn, reuse its turn count355 const checkpointCwd = yield* resolveCheckpointCwd({
365 // instead of incrementing past it.356 threadId: thread.id,
366 const existingPlaceholder = thread.checkpoints.find(357 thread,
367 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",358 projects: readModel.projects,
368 );359 preferSessionRuntime: true,
369 const currentTurnCount = thread.checkpoints.reduce(360 });
370 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),361 if (!checkpointCwd) {
371 0,362 return;
372 );363 }
373 const nextTurnCount = existingPlaceholder
374 ? existingPlaceholder.checkpointTurnCount
375 : currentTurnCount + 1;
376 364
377 yield* captureAndDispatchCheckpoint({365 // If a placeholder checkpoint exists for this turn, reuse its turn count
378 threadId: thread.id,366 // instead of incrementing past it.
379 turnId,367 const existingPlaceholder = thread.checkpoints.find(
380 thread,368 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
381 cwd: checkpointCwd,369 );
382 turnCount: nextTurnCount,370 const currentTurnCount = thread.checkpoints.reduce(
383 status: checkpointStatusFromRuntime(event.payload.state),371 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
384 assistantMessageId: undefined,372 0,
385 createdAt: event.createdAt,373 );
386 });374 const nextTurnCount = existingPlaceholder
387 });375 ? existingPlaceholder.checkpointTurnCount
376 : currentTurnCount + 1;
377
378 yield* captureAndDispatchCheckpoint({
379 threadId: thread.id,
380 turnId,
381 thread,
382 cwd: checkpointCwd,
383 turnCount: nextTurnCount,
384 status: checkpointStatusFromRuntime(event.payload.state),
385 assistantMessageId: undefined,
386 createdAt: event.createdAt,
387 });
388 },
389 );
388 390
389 // Captures a real git checkpoint when a placeholder checkpoint (status "missing")391 // Captures a real git checkpoint when a placeholder checkpoint (status "missing")
390 // is detected via a domain event. This replaces the placeholder with a real392 // is detected via a domain event. This replaces the placeholder with a real
@@ -394,7 +396,7 @@ const make = Effect.gen(function* () { · 3 unmodified lines
394 // events from the Codex runtime. This handler fires when the corresponding396 // events from the Codex runtime. This handler fires when the corresponding
395 // domain event arrives, allowing the reactor to capture the actual filesystem397 // domain event arrives, allowing the reactor to capture the actual filesystem
396 // state into a git ref and dispatch a replacement checkpoint.398 // state into a git ref and dispatch a replacement checkpoint.
397 const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (399 const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* (
398 event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,400 event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
399 ) {401 ) {
400 const { threadId, turnId, checkpointTurnCount, status } = event.payload;402 const { threadId, turnId, checkpointTurnCount, status } = event.payload;
@@ -448,57 +450,79 @@ const make = Effect.gen(function* () { · 47 unmodified lines
448 });450 });
449 });451 });
450 452
451 const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (453 const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
452 event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,454 function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
453 ) {455 const turnId = toTurnId(event.turnId);
454 const turnId = toTurnId(event.turnId);456 if (!turnId) {
455 if (!turnId) {457 return;
456 return;458 }
457 }
458 459
459 const readModel = yield* orchestrationEngine.getReadModel();460 const readModel = yield* orchestrationEngine.getReadModel();
460 const thread = readModel.threads.find((entry) => entry.id === event.threadId);461 const thread = readModel.threads.find((entry) => entry.id === event.threadId);
461 if (!thread) {462 if (!thread) {
462 return;463 return;
463 }464 }
464 465
465 const checkpointCwd = yield* resolveCheckpointCwd({466 const checkpointCwd = yield* resolveCheckpointCwd({
466 threadId: thread.id,467 threadId: thread.id,
467 thread,468 thread,
468 projects: readModel.projects,469 projects: readModel.projects,
469 preferSessionRuntime: false,470 preferSessionRuntime: false,
470 });471 });
471 if (!checkpointCwd) {472 if (!checkpointCwd) {
472 return;473 return;
473 }474 }
474 475
475 const currentTurnCount = thread.checkpoints.reduce(476 const currentTurnCount = thread.checkpoints.reduce(
476 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),477 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
477 0,478 0,
478 );479 );
479 const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);480 const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
480 const baselineExists = yield* checkpointStore.hasCheckpointRef({481 const baselineExists = yield* checkpointStore.hasCheckpointRef({
481 cwd: checkpointCwd,482 cwd: checkpointCwd,
482 checkpointRef: baselineCheckpointRef,483 checkpointRef: baselineCheckpointRef,
483 });484 });
484 if (baselineExists) {485 if (baselineExists) {
486 return;
487 }
488
489 yield* checkpointStore.captureCheckpoint({
490 cwd: checkpointCwd,
491 checkpointRef: baselineCheckpointRef,
492 });
493 yield* receiptBus.publish({
494 type: "checkpoint.baseline.captured",
495 threadId: thread.id,
496 checkpointTurnCount: currentTurnCount,
497 checkpointRef: baselineCheckpointRef,
498 createdAt: event.createdAt,
499 });
500 },
501 );
502
503 const refreshLocalGitStatusFromTurnCompletion = Effect.fn(
504 "refreshLocalGitStatusFromTurnCompletion",
505 )(function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
506 const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);
507 if (Option.isNone(sessionRuntime)) {
485 return;508 return;
486 }509 }
487 510
488 yield* checkpointStore.captureCheckpoint({511 yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
489 cwd: checkpointCwd,512 Effect.catch((error) =>
490 checkpointRef: baselineCheckpointRef,513 Effect.logWarning("failed to refresh local git status after turn completion", {
491 });514 threadId: event.threadId,
492 yield* receiptBus.publish({515 turnId: event.turnId ?? null,
493 type: "checkpoint.baseline.captured",516 cwd: sessionRuntime.value.cwd,
494 threadId: thread.id,517 detail: error.message,
495 checkpointTurnCount: currentTurnCount,518 }),
496 checkpointRef: baselineCheckpointRef,519 ),
497 createdAt: event.createdAt,520 );
498 });
499 });521 });
500 522
501 const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (523 const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
524 "ensurePreTurnBaselineFromDomainTurnStart",
525 )(function* (
502 event: Extract<526 event: Extract<
503 OrchestrationEvent,527 OrchestrationEvent,
504 { type: "thread.turn-start-requested" | "thread.message-sent" }528 { type: "thread.turn-start-requested" | "thread.message-sent" }
@@ -557,7 +581,7 @@ const make = Effect.gen(function* () { · 52 unmodified lines
557 });581 });
558 });582 });
559 583
560 const handleRevertRequested = Effect.fnUntraced(function* (584 const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
561 event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,585 event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
562 ) {586 ) {
563 const now = new Date().toISOString();587 const now = new Date().toISOString();
@@ -685,7 +709,7 @@ const make = Effect.gen(function* () { · 121 unmodified lines
685 );709 );
686 });710 });
687 711
688 const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {712 const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
689 if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {713 if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
690 yield* ensurePreTurnBaselineFromDomainTurnStart(event);714 yield* ensurePreTurnBaselineFromDomainTurnStart(event);
691 return;715 return;
@@ -724,7 +748,9 @@ const make = Effect.gen(function* () { · 32 unmodified lines
724 }748 }
725 });749 });
726 750
727 const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {751 const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
752 event: ProviderRuntimeEvent,
753 ) {
728 if (event.type === "turn.started") {754 if (event.type === "turn.started") {
729 yield* ensurePreTurnBaselineFromTurnStart(event);755 yield* ensurePreTurnBaselineFromTurnStart(event);
730 return;756 return;
@@ -732,6 +758,7 @@ const make = Effect.gen(function* () { · 1 unmodified line
732 758
733 if (event.type === "turn.completed") {759 if (event.type === "turn.completed") {
734 const turnId = toTurnId(event.turnId);760 const turnId = toTurnId(event.turnId);
761 yield* refreshLocalGitStatusFromTurnCompletion(event);
735 yield* captureCheckpointFromTurnCompletion(event).pipe(762 yield* captureCheckpointFromTurnCompletion(event).pipe(
736 Effect.catch((error) =>763 Effect.catch((error) =>
737 appendCaptureFailureActivity({764 appendCaptureFailureActivity({
apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+163−58
@@ -8,7 +8,7 @@ import { · 7 unmodified lines
8 TurnId,8 TurnId,
9 type OrchestrationEvent,9 type OrchestrationEvent,
10} from "@t3tools/contracts";10} from "@t3tools/contracts";
11import { Effect, Layer, ManagedRuntime, Option, Queue, Stream } from "effect";11import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
12import { describe, expect, it } from "vitest";12import { describe, expect, it } from "vitest";
13 13
14import { PersistenceSqlError } from "../../persistence/Errors.ts";14import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -19,6 +19,7 @@ import { · 4 unmodified lines
19 OrchestrationEventStore,19 OrchestrationEventStore,
20 type OrchestrationEventStoreShape,20 type OrchestrationEventStoreShape,
21} from "../../persistence/Services/OrchestrationEventStore.ts";21} from "../../persistence/Services/OrchestrationEventStore.ts";
22import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
22import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";23import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
23import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";24import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
24import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";25import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
@@ -31,10 +32,10 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts" · 6 unmodified lines
31import { ServerConfig } from "../../config.ts";32import { ServerConfig } from "../../config.ts";
32import * as NodeServices from "@effect/platform-node/NodeServices";33import * as NodeServices from "@effect/platform-node/NodeServices";
33 34
34const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);35const asProjectId = (value: string): ProjectId => ProjectId.make(value);
35const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);36const asMessageId = (value: string): MessageId => MessageId.make(value);
36const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);37const asTurnId = (value: string): TurnId => TurnId.make(value);
37const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);38const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
38 39
39async function createOrchestrationSystem() {40async function createOrchestrationSystem() {
40 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {41 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
@@ -45,6 +46,7 @@ async function createOrchestrationSystem() { · 4 unmodified lines
45 Layer.provide(OrchestrationProjectionPipelineLive),46 Layer.provide(OrchestrationProjectionPipelineLive),
46 Layer.provide(OrchestrationEventStoreLive),47 Layer.provide(OrchestrationEventStoreLive),
47 Layer.provide(OrchestrationCommandReceiptRepositoryLive),48 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
49 Layer.provide(RepositoryIdentityResolverLive),
48 Layer.provide(SqlitePersistenceMemory),50 Layer.provide(SqlitePersistenceMemory),
49 Layer.provideMerge(ServerConfigLayer),51 Layer.provideMerge(ServerConfigLayer),
50 Layer.provideMerge(NodeServices.layer),52 Layer.provideMerge(NodeServices.layer),
@@ -62,6 +64,17 @@ function now() { · 11 unmodified lines
62 return new Date().toISOString();64 return new Date().toISOString();
63}65}
64 66
67const hasMetricSnapshot = (
68 snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
69 id: string,
70 attributes: Readonly<Record<string, string>>,
71) =>
72 snapshots.some(
73 (snapshot) =>
74 snapshot.id === id &&
75 Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
76 );
77
65describe("OrchestrationEngine", () => {78describe("OrchestrationEngine", () => {
66 it("bootstraps the in-memory read model from persisted projections", async () => {79 it("bootstraps the in-memory read model from persisted projections", async () => {
67 const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {80 const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
@@ -102,7 +115,7 @@ describe("OrchestrationEngine", () => { · 34 unmodified lines
102 ],115 ],
103 threads: [116 threads: [
104 {117 {
105 id: ThreadId.makeUnsafe("thread-bootstrap"),118 id: ThreadId.make("thread-bootstrap"),
106 projectId: asProjectId("project-bootstrap"),119 projectId: asProjectId("project-bootstrap"),
107 title: "Bootstrap Thread",120 title: "Bootstrap Thread",
108 modelSelection: {121 modelSelection: {
@@ -170,7 +183,7 @@ describe("OrchestrationEngine", () => { · 61 unmodified lines
170 await system.run(183 await system.run(
171 engine.dispatch({184 engine.dispatch({
172 type: "project.create",185 type: "project.create",
173 commandId: CommandId.makeUnsafe("cmd-project-1-create"),186 commandId: CommandId.make("cmd-project-1-create"),
174 projectId: asProjectId("project-1"),187 projectId: asProjectId("project-1"),
175 title: "Project 1",188 title: "Project 1",
176 workspaceRoot: "/tmp/project-1",189 workspaceRoot: "/tmp/project-1",
@@ -184,8 +197,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
184 await system.run(197 await system.run(
185 engine.dispatch({198 engine.dispatch({
186 type: "thread.create",199 type: "thread.create",
187 commandId: CommandId.makeUnsafe("cmd-thread-1-create"),200 commandId: CommandId.make("cmd-thread-1-create"),
188 threadId: ThreadId.makeUnsafe("thread-1"),201 threadId: ThreadId.make("thread-1"),
189 projectId: asProjectId("project-1"),202 projectId: asProjectId("project-1"),
190 title: "Thread",203 title: "Thread",
191 modelSelection: {204 modelSelection: {
@@ -202,8 +215,8 @@ describe("OrchestrationEngine", () => { · 10 unmodified lines
202 await system.run(215 await system.run(
203 engine.dispatch({216 engine.dispatch({
204 type: "thread.turn.start",217 type: "thread.turn.start",
205 commandId: CommandId.makeUnsafe("cmd-turn-start-1"),218 commandId: CommandId.make("cmd-turn-start-1"),
206 threadId: ThreadId.makeUnsafe("thread-1"),219 threadId: ThreadId.make("thread-1"),
207 message: {220 message: {
208 messageId: asMessageId("msg-1"),221 messageId: asMessageId("msg-1"),
209 role: "user",222 role: "user",
@@ -230,7 +243,7 @@ describe("OrchestrationEngine", () => { · 20 unmodified lines
230 await system.run(243 await system.run(
231 engine.dispatch({244 engine.dispatch({
232 type: "project.create",245 type: "project.create",
233 commandId: CommandId.makeUnsafe("cmd-project-archive-create"),246 commandId: CommandId.make("cmd-project-archive-create"),
234 projectId: asProjectId("project-archive"),247 projectId: asProjectId("project-archive"),
235 title: "Project Archive",248 title: "Project Archive",
236 workspaceRoot: "/tmp/project-archive",249 workspaceRoot: "/tmp/project-archive",
@@ -244,8 +257,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
244 await system.run(257 await system.run(
245 engine.dispatch({258 engine.dispatch({
246 type: "thread.create",259 type: "thread.create",
247 commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),260 commandId: CommandId.make("cmd-thread-archive-create"),
248 threadId: ThreadId.makeUnsafe("thread-archive"),261 threadId: ThreadId.make("thread-archive"),
249 projectId: asProjectId("project-archive"),262 projectId: asProjectId("project-archive"),
250 title: "Archive me",263 title: "Archive me",
251 modelSelection: {264 modelSelection: {
@@ -263,8 +276,8 @@ describe("OrchestrationEngine", () => { · 11 unmodified lines
263 await system.run(276 await system.run(
264 engine.dispatch({277 engine.dispatch({
265 type: "thread.archive",278 type: "thread.archive",
266 commandId: CommandId.makeUnsafe("cmd-thread-archive"),279 commandId: CommandId.make("cmd-thread-archive"),
267 threadId: ThreadId.makeUnsafe("thread-archive"),280 threadId: ThreadId.make("thread-archive"),
268 }),281 }),
269 );282 );
270 expect(283 expect(
@@ -276,8 +289,8 @@ describe("OrchestrationEngine", () => { · 5 unmodified lines
276 await system.run(289 await system.run(
277 engine.dispatch({290 engine.dispatch({
278 type: "thread.unarchive",291 type: "thread.unarchive",
279 commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),292 commandId: CommandId.make("cmd-thread-unarchive"),
280 threadId: ThreadId.makeUnsafe("thread-archive"),293 threadId: ThreadId.make("thread-archive"),
281 }),294 }),
282 );295 );
283 expect(296 expect(
@@ -297,7 +310,7 @@ describe("OrchestrationEngine", () => { · 13 unmodified lines
297 await system.run(310 await system.run(
298 engine.dispatch({311 engine.dispatch({
299 type: "project.create",312 type: "project.create",
300 commandId: CommandId.makeUnsafe("cmd-project-replay-create"),313 commandId: CommandId.make("cmd-project-replay-create"),
301 projectId: asProjectId("project-replay"),314 projectId: asProjectId("project-replay"),
302 title: "Replay Project",315 title: "Replay Project",
303 workspaceRoot: "/tmp/project-replay",316 workspaceRoot: "/tmp/project-replay",
@@ -311,8 +324,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
311 await system.run(324 await system.run(
312 engine.dispatch({325 engine.dispatch({
313 type: "thread.create",326 type: "thread.create",
314 commandId: CommandId.makeUnsafe("cmd-thread-replay-create"),327 commandId: CommandId.make("cmd-thread-replay-create"),
315 threadId: ThreadId.makeUnsafe("thread-replay"),328 threadId: ThreadId.make("thread-replay"),
316 projectId: asProjectId("project-replay"),329 projectId: asProjectId("project-replay"),
317 title: "replay",330 title: "replay",
318 modelSelection: {331 modelSelection: {
@@ -329,8 +342,8 @@ describe("OrchestrationEngine", () => { · 10 unmodified lines
329 await system.run(342 await system.run(
330 engine.dispatch({343 engine.dispatch({
331 type: "thread.delete",344 type: "thread.delete",
332 commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"),345 commandId: CommandId.make("cmd-thread-replay-delete"),
333 threadId: ThreadId.makeUnsafe("thread-replay"),346 threadId: ThreadId.make("thread-replay"),
334 }),347 }),
335 );348 );
336 349
@@ -355,7 +368,7 @@ describe("OrchestrationEngine", () => { · 18 unmodified lines
355 await system.run(368 await system.run(
356 engine.dispatch({369 engine.dispatch({
357 type: "project.create",370 type: "project.create",
358 commandId: CommandId.makeUnsafe("cmd-project-stream-create"),371 commandId: CommandId.make("cmd-project-stream-create"),
359 projectId: asProjectId("project-stream"),372 projectId: asProjectId("project-stream"),
360 title: "Stream Project",373 title: "Stream Project",
361 workspaceRoot: "/tmp/project-stream",374 workspaceRoot: "/tmp/project-stream",
@@ -379,8 +392,8 @@ describe("OrchestrationEngine", () => { · 17 unmodified lines
379 yield* Effect.sleep("10 millis");392 yield* Effect.sleep("10 millis");
380 yield* engine.dispatch({393 yield* engine.dispatch({
381 type: "thread.create",394 type: "thread.create",
382 commandId: CommandId.makeUnsafe("cmd-stream-thread-create"),395 commandId: CommandId.make("cmd-stream-thread-create"),
383 threadId: ThreadId.makeUnsafe("thread-stream"),396 threadId: ThreadId.make("thread-stream"),
384 projectId: asProjectId("project-stream"),397 projectId: asProjectId("project-stream"),
385 title: "domain-stream",398 title: "domain-stream",
386 modelSelection: {399 modelSelection: {
@@ -395,8 +408,8 @@ describe("OrchestrationEngine", () => { · 8 unmodified lines
395 });408 });
396 yield* engine.dispatch({409 yield* engine.dispatch({
397 type: "thread.meta.update",410 type: "thread.meta.update",
398 commandId: CommandId.makeUnsafe("cmd-stream-thread-update"),411 commandId: CommandId.make("cmd-stream-thread-update"),
399 threadId: ThreadId.makeUnsafe("thread-stream"),412 threadId: ThreadId.make("thread-stream"),
400 title: "domain-stream-updated",413 title: "domain-stream-updated",
401 });414 });
402 eventTypes.push((yield* Queue.take(eventQueue)).type);415 eventTypes.push((yield* Queue.take(eventQueue)).type);
@@ -408,6 +421,95 @@ describe("OrchestrationEngine", () => { · 5 unmodified lines
408 await system.dispose();421 await system.dispose();
409 });422 });
410 423
424 it("records command ack duration using the first committed event type", async () => {
425 const system = await createOrchestrationSystem();
426 const { engine } = system;
427 const createdAt = now();
428
429 await system.run(
430 engine.dispatch({
431 type: "project.create",
432 commandId: CommandId.make("cmd-project-ack-create"),
433 projectId: asProjectId("project-ack"),
434 title: "Ack Project",
435 workspaceRoot: "/tmp/project-ack",
436 defaultModelSelection: {
437 provider: "codex",
438 model: "gpt-5-codex",
439 },
440 createdAt,
441 }),
442 );
443
444 await system.run(
445 engine.dispatch({
446 type: "thread.create",
447 commandId: CommandId.make("cmd-thread-ack-create"),
448 threadId: ThreadId.make("thread-ack"),
449 projectId: asProjectId("project-ack"),
450 title: "Ack Thread",
451 modelSelection: {
452 provider: "codex",
453 model: "gpt-5-codex",
454 },
455 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
456 runtimeMode: "full-access",
457 branch: null,
458 worktreePath: null,
459 createdAt,
460 }),
461 );
462
463 const snapshots = await system.run(Metric.snapshot);
464 expect(
465 hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", {
466 commandType: "thread.create",
467 aggregateKind: "thread",
468 ackEventType: "thread.created",
469 }),
470 ).toBe(true);
471
472 await system.dispose();
473 });
474
475 it("records failed command dispatches as metric failures", async () => {
476 const system = await createOrchestrationSystem();
477 const { engine } = system;
478 const createdAt = now();
479
480 await expect(
481 system.run(
482 engine.dispatch({
483 type: "thread.create",
484 commandId: CommandId.make("cmd-thread-missing-project"),
485 threadId: ThreadId.make("thread-missing-project"),
486 projectId: asProjectId("project-missing"),
487 title: "Missing Project Thread",
488 modelSelection: {
489 provider: "codex",
490 model: "gpt-5-codex",
491 },
492 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
493 runtimeMode: "full-access",
494 branch: null,
495 worktreePath: null,
496 createdAt,
497 }),
498 ),
499 ).rejects.toThrow("does not exist");
500
501 const snapshots = await system.run(Metric.snapshot);
502 expect(
503 hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", {
504 commandType: "thread.create",
505 aggregateKind: "thread",
506 outcome: "failure",
507 }),
508 ).toBe(true);
509
510 await system.dispose();
511 });
512
411 it("stores completed checkpoint summaries even when no files changed", async () => {513 it("stores completed checkpoint summaries even when no files changed", async () => {
412 const system = await createOrchestrationSystem();514 const system = await createOrchestrationSystem();
413 const { engine } = system;515 const { engine } = system;
@@ -416,7 +518,7 @@ describe("OrchestrationEngine", () => { · 2 unmodified lines
416 await system.run(518 await system.run(
417 engine.dispatch({519 engine.dispatch({
418 type: "project.create",520 type: "project.create",
419 commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"),521 commandId: CommandId.make("cmd-project-turn-diff-create"),
420 projectId: asProjectId("project-turn-diff"),522 projectId: asProjectId("project-turn-diff"),
421 title: "Turn Diff Project",523 title: "Turn Diff Project",
422 workspaceRoot: "/tmp/project-turn-diff",524 workspaceRoot: "/tmp/project-turn-diff",
@@ -430,8 +532,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
430 await system.run(532 await system.run(
431 engine.dispatch({533 engine.dispatch({
432 type: "thread.create",534 type: "thread.create",
433 commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"),535 commandId: CommandId.make("cmd-thread-turn-diff-create"),
434 threadId: ThreadId.makeUnsafe("thread-turn-diff"),536 threadId: ThreadId.make("thread-turn-diff"),
435 projectId: asProjectId("project-turn-diff"),537 projectId: asProjectId("project-turn-diff"),
436 title: "Turn diff thread",538 title: "Turn diff thread",
437 modelSelection: {539 modelSelection: {
@@ -448,8 +550,8 @@ describe("OrchestrationEngine", () => { · 10 unmodified lines
448 await system.run(550 await system.run(
449 engine.dispatch({551 engine.dispatch({
450 type: "thread.turn.diff.complete",552 type: "thread.turn.diff.complete",
451 commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"),553 commandId: CommandId.make("cmd-turn-diff-complete"),
452 threadId: ThreadId.makeUnsafe("thread-turn-diff"),554 threadId: ThreadId.make("thread-turn-diff"),
453 turnId: asTurnId("turn-1"),555 turnId: asTurnId("turn-1"),
454 completedAt: createdAt,556 completedAt: createdAt,
455 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),557 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
@@ -488,7 +590,7 @@ describe("OrchestrationEngine", () => { · 32 unmodified lines
488 590
489 const flakyStore: OrchestrationEventStoreShape = {591 const flakyStore: OrchestrationEventStoreShape = {
490 append(event) {592 append(event) {
491 if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) {593 if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) {
492 shouldFailFirstAppend = false;594 shouldFailFirstAppend = false;
493 return Effect.fail(595 return Effect.fail(
494 new PersistenceSqlError({596 new PersistenceSqlError({
@@ -523,6 +625,7 @@ describe("OrchestrationEngine", () => { · 28 unmodified lines
523 Layer.provide(OrchestrationProjectionPipelineLive),625 Layer.provide(OrchestrationProjectionPipelineLive),
524 Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),626 Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
525 Layer.provide(OrchestrationCommandReceiptRepositoryLive),627 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
628 Layer.provide(RepositoryIdentityResolverLive),
526 Layer.provide(SqlitePersistenceMemory),629 Layer.provide(SqlitePersistenceMemory),
527 Layer.provideMerge(ServerConfigLayer),630 Layer.provideMerge(ServerConfigLayer),
528 Layer.provideMerge(NodeServices.layer),631 Layer.provideMerge(NodeServices.layer),
@@ -534,7 +637,7 @@ describe("OrchestrationEngine", () => { · 5 unmodified lines
534 await runtime.runPromise(637 await runtime.runPromise(
535 engine.dispatch({638 engine.dispatch({
536 type: "project.create",639 type: "project.create",
537 commandId: CommandId.makeUnsafe("cmd-project-flaky-create"),640 commandId: CommandId.make("cmd-project-flaky-create"),
538 projectId: asProjectId("project-flaky"),641 projectId: asProjectId("project-flaky"),
539 title: "Flaky Project",642 title: "Flaky Project",
540 workspaceRoot: "/tmp/project-flaky",643 workspaceRoot: "/tmp/project-flaky",
@@ -550,8 +653,8 @@ describe("OrchestrationEngine", () => { · 9 unmodified lines
550 runtime.runPromise(653 runtime.runPromise(
551 engine.dispatch({654 engine.dispatch({
552 type: "thread.create",655 type: "thread.create",
553 commandId: CommandId.makeUnsafe("cmd-flaky-1"),656 commandId: CommandId.make("cmd-flaky-1"),
554 threadId: ThreadId.makeUnsafe("thread-flaky-fail"),657 threadId: ThreadId.make("thread-flaky-fail"),
555 projectId: asProjectId("project-flaky"),658 projectId: asProjectId("project-flaky"),
556 title: "flaky-fail",659 title: "flaky-fail",
557 modelSelection: {660 modelSelection: {
@@ -570,8 +673,8 @@ describe("OrchestrationEngine", () => { · 12 unmodified lines
570 const result = await runtime.runPromise(673 const result = await runtime.runPromise(
571 engine.dispatch({674 engine.dispatch({
572 type: "thread.create",675 type: "thread.create",
573 commandId: CommandId.makeUnsafe("cmd-flaky-2"),676 commandId: CommandId.make("cmd-flaky-2"),
574 threadId: ThreadId.makeUnsafe("thread-flaky-ok"),677 threadId: ThreadId.make("thread-flaky-ok"),
575 projectId: asProjectId("project-flaky"),678 projectId: asProjectId("project-flaky"),
576 title: "flaky-ok",679 title: "flaky-ok",
577 modelSelection: {680 modelSelection: {
@@ -598,7 +701,7 @@ describe("OrchestrationEngine", () => { · 20 unmodified lines
598 projectEvent: (event) => {701 projectEvent: (event) => {
599 if (702 if (
600 shouldFailRequestedProjection &&703 shouldFailRequestedProjection &&
601 event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") &&704 event.commandId === CommandId.make("cmd-turn-start-atomic") &&
602 event.type === "thread.turn-start-requested"705 event.type === "thread.turn-start-requested"
603 ) {706 ) {
604 shouldFailRequestedProjection = false;707 shouldFailRequestedProjection = false;
@@ -619,6 +722,7 @@ describe("OrchestrationEngine", () => { · 14 unmodified lines
619 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),722 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
620 Layer.provide(OrchestrationEventStoreLive),723 Layer.provide(OrchestrationEventStoreLive),
621 Layer.provide(OrchestrationCommandReceiptRepositoryLive),724 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
725 Layer.provide(RepositoryIdentityResolverLive),
622 Layer.provide(SqlitePersistenceMemory),726 Layer.provide(SqlitePersistenceMemory),
623 ),727 ),
624 );728 );
@@ -628,7 +732,7 @@ describe("OrchestrationEngine", () => { · 3 unmodified lines
628 await runtime.runPromise(732 await runtime.runPromise(
629 engine.dispatch({733 engine.dispatch({
630 type: "project.create",734 type: "project.create",
631 commandId: CommandId.makeUnsafe("cmd-project-atomic-create"),735 commandId: CommandId.make("cmd-project-atomic-create"),
632 projectId: asProjectId("project-atomic"),736 projectId: asProjectId("project-atomic"),
633 title: "Atomic Project",737 title: "Atomic Project",
634 workspaceRoot: "/tmp/project-atomic",738 workspaceRoot: "/tmp/project-atomic",
@@ -642,8 +746,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
642 await runtime.runPromise(746 await runtime.runPromise(
643 engine.dispatch({747 engine.dispatch({
644 type: "thread.create",748 type: "thread.create",
645 commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"),749 commandId: CommandId.make("cmd-thread-atomic-create"),
646 threadId: ThreadId.makeUnsafe("thread-atomic"),750 threadId: ThreadId.make("thread-atomic"),
647 projectId: asProjectId("project-atomic"),751 projectId: asProjectId("project-atomic"),
648 title: "atomic",752 title: "atomic",
649 modelSelection: {753 modelSelection: {
@@ -660,8 +764,8 @@ describe("OrchestrationEngine", () => { · 10 unmodified lines
660 764
661 const turnStartCommand = {765 const turnStartCommand = {
662 type: "thread.turn.start" as const,766 type: "thread.turn.start" as const,
663 commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"),767 commandId: CommandId.make("cmd-turn-start-atomic"),
664 threadId: ThreadId.makeUnsafe("thread-atomic"),768 threadId: ThreadId.make("thread-atomic"),
665 message: {769 message: {
666 messageId: asMessageId("msg-atomic-1"),770 messageId: asMessageId("msg-atomic-1"),
667 role: "user" as const,771 role: "user" as const,
@@ -741,7 +845,7 @@ describe("OrchestrationEngine", () => { · 73 unmodified lines
741 projectEvent: (event) => {845 projectEvent: (event) => {
742 if (846 if (
743 shouldFailProjection &&847 shouldFailProjection &&
744 event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail")848 event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
745 ) {849 ) {
746 shouldFailProjection = false;850 shouldFailProjection = false;
747 return Effect.fail(851 return Effect.fail(
@@ -761,6 +865,7 @@ describe("OrchestrationEngine", () => { · 13 unmodified lines
761 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),865 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
762 Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),866 Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
763 Layer.provide(OrchestrationCommandReceiptRepositoryLive),867 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
868 Layer.provide(RepositoryIdentityResolverLive),
764 Layer.provide(SqlitePersistenceMemory),869 Layer.provide(SqlitePersistenceMemory),
765 ),870 ),
766 );871 );
@@ -770,7 +875,7 @@ describe("OrchestrationEngine", () => { · 3 unmodified lines
770 await runtime.runPromise(875 await runtime.runPromise(
771 engine.dispatch({876 engine.dispatch({
772 type: "project.create",877 type: "project.create",
773 commandId: CommandId.makeUnsafe("cmd-project-sync-create"),878 commandId: CommandId.make("cmd-project-sync-create"),
774 projectId: asProjectId("project-sync"),879 projectId: asProjectId("project-sync"),
775 title: "Sync Project",880 title: "Sync Project",
776 workspaceRoot: "/tmp/project-sync",881 workspaceRoot: "/tmp/project-sync",
@@ -784,8 +889,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
784 await runtime.runPromise(889 await runtime.runPromise(
785 engine.dispatch({890 engine.dispatch({
786 type: "thread.create",891 type: "thread.create",
787 commandId: CommandId.makeUnsafe("cmd-thread-sync-create"),892 commandId: CommandId.make("cmd-thread-sync-create"),
788 threadId: ThreadId.makeUnsafe("thread-sync"),893 threadId: ThreadId.make("thread-sync"),
789 projectId: asProjectId("project-sync"),894 projectId: asProjectId("project-sync"),
790 title: "sync-before",895 title: "sync-before",
791 modelSelection: {896 modelSelection: {
@@ -804,8 +909,8 @@ describe("OrchestrationEngine", () => { · 12 unmodified lines
804 runtime.runPromise(909 runtime.runPromise(
805 engine.dispatch({910 engine.dispatch({
806 type: "thread.meta.update",911 type: "thread.meta.update",
807 commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"),912 commandId: CommandId.make("cmd-thread-meta-sync-fail"),
808 threadId: ThreadId.makeUnsafe("thread-sync"),913 threadId: ThreadId.make("thread-sync"),
809 title: "sync-after-failed-projection",914 title: "sync-after-failed-projection",
810 }),915 }),
811 ),916 ),
@@ -829,8 +934,8 @@ describe("OrchestrationEngine", () => { · 17 unmodified lines
829 system.run(934 system.run(
830 engine.dispatch({935 engine.dispatch({
831 type: "thread.turn.start",936 type: "thread.turn.start",
832 commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"),937 commandId: CommandId.make("cmd-invariant-missing-thread"),
833 threadId: ThreadId.makeUnsafe("thread-missing"),938 threadId: ThreadId.make("thread-missing"),
834 message: {939 message: {
835 messageId: asMessageId("msg-missing"),940 messageId: asMessageId("msg-missing"),
836 role: "user",941 role: "user",
@@ -855,7 +960,7 @@ describe("OrchestrationEngine", () => { · 18 unmodified lines
855 await system.run(960 await system.run(
856 engine.dispatch({961 engine.dispatch({
857 type: "project.create",962 type: "project.create",
858 commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"),963 commandId: CommandId.make("cmd-project-duplicate-create"),
859 projectId: asProjectId("project-duplicate"),964 projectId: asProjectId("project-duplicate"),
860 title: "Duplicate Project",965 title: "Duplicate Project",
861 workspaceRoot: "/tmp/project-duplicate",966 workspaceRoot: "/tmp/project-duplicate",
@@ -870,8 +975,8 @@ describe("OrchestrationEngine", () => { · 8 unmodified lines
870 await system.run(975 await system.run(
871 engine.dispatch({976 engine.dispatch({
872 type: "thread.create",977 type: "thread.create",
873 commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"),978 commandId: CommandId.make("cmd-thread-duplicate-1"),
874 threadId: ThreadId.makeUnsafe("thread-duplicate"),979 threadId: ThreadId.make("thread-duplicate"),
875 projectId: asProjectId("project-duplicate"),980 projectId: asProjectId("project-duplicate"),
876 title: "duplicate",981 title: "duplicate",
877 modelSelection: {982 modelSelection: {
@@ -890,8 +995,8 @@ describe("OrchestrationEngine", () => { · 12 unmodified lines
890 system.run(995 system.run(
891 engine.dispatch({996 engine.dispatch({
892 type: "thread.create",997 type: "thread.create",
893 commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"),998 commandId: CommandId.make("cmd-thread-duplicate-2"),
894 threadId: ThreadId.makeUnsafe("thread-duplicate"),999 threadId: ThreadId.make("thread-duplicate"),
895 projectId: asProjectId("project-duplicate"),1000 projectId: asProjectId("project-duplicate"),
896 title: "duplicate",1001 title: "duplicate",
897 modelSelection: {1002 modelSelection: {
apps/server/src/orchestration/Layers/OrchestrationEngine.ts+168−95
@@ -5,9 +5,28 @@ import type { · 4 unmodified lines
5 ThreadId,5 ThreadId,
6} from "@t3tools/contracts";6} from "@t3tools/contracts";
7import { OrchestrationCommand } from "@t3tools/contracts";7import { OrchestrationCommand } from "@t3tools/contracts";
8import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect";8import {
9 Cause,
10 Deferred,
11 Duration,
12 Effect,
13 Exit,
14 Layer,
15 Metric,
16 Option,
17 PubSub,
18 Queue,
19 Schema,
20 Stream,
21} from "effect";
9import * as SqlClient from "effect/unstable/sql/SqlClient";22import * as SqlClient from "effect/unstable/sql/SqlClient";
10 23
24import {
25 metricAttributes,
26 orchestrationCommandAckDuration,
27 orchestrationCommandsTotal,
28 orchestrationCommandDuration,
29} from "../../observability/Metrics.ts";
11import { toPersistenceSqlError } from "../../persistence/Errors.ts";30import { toPersistenceSqlError } from "../../persistence/Errors.ts";
12import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";31import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
13import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";32import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
@@ -28,6 +47,7 @@ import { · 14 unmodified lines
28interface CommandEnvelope {47interface CommandEnvelope {
29 command: OrchestrationCommand;48 command: OrchestrationCommand;
30 result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;49 result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
50 startedAtMs: number;
31}51}
32 52
33function commandToAggregateRef(command: OrchestrationCommand): {53function commandToAggregateRef(command: OrchestrationCommand): {
@@ -64,6 +84,12 @@ const makeOrchestrationEngine = Effect.gen(function* () { · 30 unmodified lines
64 84
65 const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {85 const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
66 const dispatchStartSequence = readModel.snapshotSequence;86 const dispatchStartSequence = readModel.snapshotSequence;
87 const processingStartedAtMs = Date.now();
88 const aggregateRef = commandToAggregateRef(envelope.command);
89 const baseMetricAttributes = {
90 commandType: envelope.command.type,
91 aggregateKind: aggregateRef.aggregateKind,
92 } as const;
67 const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {93 const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
68 const persistedEvents = yield* Stream.runCollect(94 const persistedEvents = yield* Stream.runCollect(
69 eventStore.readFromSequence(dispatchStartSequence),95 eventStore.readFromSequence(dispatchStartSequence),
@@ -83,113 +109,160 @@ const makeOrchestrationEngine = Effect.gen(function* () { · 13 unmodified lines
83 }109 }
84 });110 });
85 111
86 return Effect.gen(function* () {112 return Effect.exit(
87 const existingReceipt = yield* commandReceiptRepository.getByCommandId({113 Effect.gen(function* () {
88 commandId: envelope.command.commandId,114 yield* Effect.annotateCurrentSpan({
89 });115 "orchestration.command_id": envelope.command.commandId,
90 if (Option.isSome(existingReceipt)) {116 "orchestration.command_type": envelope.command.type,
91 if (existingReceipt.value.status === "accepted") {117 "orchestration.aggregate_kind": aggregateRef.aggregateKind,
92 yield* Deferred.succeed(envelope.result, {118 "orchestration.aggregate_id": aggregateRef.aggregateId,
93 sequence: existingReceipt.value.resultSequence,119 });
94 });120
95 return;121 const existingReceipt = yield* commandReceiptRepository.getByCommandId({
96 }122 commandId: envelope.command.commandId,
97 yield* Deferred.fail(123 });
98 envelope.result,124 if (Option.isSome(existingReceipt)) {
99 new OrchestrationCommandPreviouslyRejectedError({125 if (existingReceipt.value.status === "accepted") {
126 return {
127 sequence: existingReceipt.value.resultSequence,
128 };
129 }
130 return yield* new OrchestrationCommandPreviouslyRejectedError({
100 commandId: envelope.command.commandId,131 commandId: envelope.command.commandId,
101 detail: existingReceipt.value.error ?? "Previously rejected.",132 detail: existingReceipt.value.error ?? "Previously rejected.",
102 }),133 });
103 );134 }
104 return;
105 }
106 135
107 const eventBase = yield* decideOrchestrationCommand({136 const eventBase = yield* decideOrchestrationCommand({
108 command: envelope.command,137 command: envelope.command,
109 readModel,138 readModel,
110 });139 });
111 const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];140 const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
112 const committedCommand = yield* sql141 const committedCommand = yield* sql
113 .withTransaction(142 .withTransaction(
114 Effect.gen(function* () {143 Effect.gen(function* () {
115 const committedEvents: OrchestrationEvent[] = [];144 const committedEvents: OrchestrationEvent[] = [];
116 let nextReadModel = readModel;145 let nextReadModel = readModel;
117
118 for (const nextEvent of eventBases) {
119 const savedEvent = yield* eventStore.append(nextEvent);
120 nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
121 yield* projectionPipeline.projectEvent(savedEvent);
122 committedEvents.push(savedEvent);
123 }
124 146
125 const lastSavedEvent = committedEvents.at(-1) ?? null;147 for (const nextEvent of eventBases) {
126 if (lastSavedEvent === null) {148 const savedEvent = yield* eventStore.append(nextEvent);
127 return yield* new OrchestrationCommandInvariantError({149 nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
128 commandType: envelope.command.type,150 yield* projectionPipeline.projectEvent(savedEvent);
129 detail: "Command produced no events.",151 committedEvents.push(savedEvent);
130 });152 }
131 }
132 153
133 yield* commandReceiptRepository.upsert({154 const lastSavedEvent = committedEvents.at(-1) ?? null;
134 commandId: envelope.command.commandId,155 if (lastSavedEvent === null) {
135 aggregateKind: lastSavedEvent.aggregateKind,156 return yield* new OrchestrationCommandInvariantError({
136 aggregateId: lastSavedEvent.aggregateId,157 commandType: envelope.command.type,
137 acceptedAt: lastSavedEvent.occurredAt,158 detail: "Command produced no events.",
138 resultSequence: lastSavedEvent.sequence,159 });
139 status: "accepted",160 }
140 error: null,
141 });
142 161
143 return {162 yield* commandReceiptRepository.upsert({
144 committedEvents,163 commandId: envelope.command.commandId,
145 lastSequence: lastSavedEvent.sequence,164 aggregateKind: lastSavedEvent.aggregateKind,
146 nextReadModel,165 aggregateId: lastSavedEvent.aggregateId,
147 } as const;166 acceptedAt: lastSavedEvent.occurredAt,
148 }),167 resultSequence: lastSavedEvent.sequence,
149 )168 status: "accepted",
150 .pipe(169 error: null,
151 Effect.catchTag("SqlError", (sqlError) =>170 });
152 Effect.fail(171
153 toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),172 return {
173 committedEvents,
174 lastSequence: lastSavedEvent.sequence,
175 nextReadModel,
176 } as const;
177 }),
178 )
179 .pipe(
180 Effect.catchTag("SqlError", (sqlError) =>
181 Effect.fail(
182 toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
183 ),
154 ),184 ),
155 ),185 );
156 );
157 186
158 readModel = committedCommand.nextReadModel;187 readModel = committedCommand.nextReadModel;
159 for (const event of committedCommand.committedEvents) {188 for (const [index, event] of committedCommand.committedEvents.entries()) {
160 yield* PubSub.publish(eventPubSub, event);189 yield* PubSub.publish(eventPubSub, event);
161 }190 if (index === 0) {
162 yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence });191 yield* Metric.update(
163 }).pipe(192 Metric.withAttributes(
164 Effect.catch((error) =>193 orchestrationCommandAckDuration,
165 Effect.gen(function* () {194 metricAttributes({
166 yield* reconcileReadModelAfterDispatchFailure.pipe(195 ...baseMetricAttributes,
167 Effect.catch(() =>196 ackEventType: event.type,
168 Effect.logWarning(
169 "failed to reconcile orchestration read model after dispatch failure",
170 ).pipe(
171 Effect.annotateLogs({
172 commandId: envelope.command.commandId,
173 snapshotSequence: readModel.snapshotSequence,
174 }),197 }),
175 ),198 ),
199 Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)),
200 );
201 }
202 }
203 return { sequence: committedCommand.lastSequence };
204 }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),
205 ).pipe(
206 Effect.flatMap((exit) =>
207 Effect.gen(function* () {
208 const outcome = Exit.isSuccess(exit)
209 ? "success"
210 : Cause.hasInterruptsOnly(exit.cause)
211 ? "interrupt"
212 : "failure";
213 yield* Metric.update(
214 Metric.withAttributes(
215 orchestrationCommandDuration,
216 metricAttributes(baseMetricAttributes),
217 ),
218 Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)),
219 );
220 yield* Metric.update(
221 Metric.withAttributes(
222 orchestrationCommandsTotal,
223 metricAttributes({
224 ...baseMetricAttributes,
225 outcome,
226 }),
176 ),227 ),
228 1,
177 );229 );
178 230
179 if (Schema.is(OrchestrationCommandInvariantError)(error)) {231 if (Exit.isSuccess(exit)) {
180 const aggregateRef = commandToAggregateRef(envelope.command);232 yield* Deferred.succeed(envelope.result, exit.value);
181 yield* commandReceiptRepository233 return;
182 .upsert({
183 commandId: envelope.command.commandId,
184 aggregateKind: aggregateRef.aggregateKind,
185 aggregateId: aggregateRef.aggregateId,
186 acceptedAt: new Date().toISOString(),
187 resultSequence: readModel.snapshotSequence,
188 status: "rejected",
189 error: error.message,
190 })
191 .pipe(Effect.catch(() => Effect.void));
192 }234 }
235
236 const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
237 if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) {
238 yield* reconcileReadModelAfterDispatchFailure.pipe(
239 Effect.catch(() =>
240 Effect.logWarning(
241 "failed to reconcile orchestration read model after dispatch failure",
242 ).pipe(
243 Effect.annotateLogs({
244 commandId: envelope.command.commandId,
245 snapshotSequence: readModel.snapshotSequence,
246 }),
247 ),
248 ),
249 );
250
251 if (Schema.is(OrchestrationCommandInvariantError)(error)) {
252 yield* commandReceiptRepository
253 .upsert({
254 commandId: envelope.command.commandId,
255 aggregateKind: aggregateRef.aggregateKind,
256 aggregateId: aggregateRef.aggregateId,
257 acceptedAt: new Date().toISOString(),
258 resultSequence: readModel.snapshotSequence,
259 status: "rejected",
260 error: error.message,
261 })
262 .pipe(Effect.catch(() => Effect.void));
263 }
264 }
265
193 yield* Deferred.fail(envelope.result, error);266 yield* Deferred.fail(envelope.result, error);
194 }),267 }),
195 ),268 ),
@@ -214,7 +287,7 @@ const makeOrchestrationEngine = Effect.gen(function* () { · 18 unmodified lines
214 const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>287 const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
215 Effect.gen(function* () {288 Effect.gen(function* () {
216 const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();289 const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
217 yield* Queue.offer(commandQueue, { command, result });290 yield* Queue.offer(commandQueue, { command, result, startedAtMs: Date.now() });
218 return yield* Deferred.await(result);291 return yield* Deferred.await(result);
219 });292 });
220 293
apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+304−302
@@ -20,6 +20,7 @@ import { · 19 unmodified lines
20 SqlitePersistenceMemory,20 SqlitePersistenceMemory,
21} from "../../persistence/Layers/Sqlite.ts";21} from "../../persistence/Layers/Sqlite.ts";
22import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";22import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
23import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
23import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";24import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
24import {25import {
25 ORCHESTRATION_PROJECTOR_NAMES,26 ORCHESTRATION_PROJECTOR_NAMES,
@@ -57,16 +58,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 31 unmodified lines
57 58
58 yield* eventStore.append({59 yield* eventStore.append({
59 type: "project.created",60 type: "project.created",
60 eventId: EventId.makeUnsafe("evt-1"),61 eventId: EventId.make("evt-1"),
61 aggregateKind: "project",62 aggregateKind: "project",
62 aggregateId: ProjectId.makeUnsafe("project-1"),63 aggregateId: ProjectId.make("project-1"),
63 occurredAt: now,64 occurredAt: now,
64 commandId: CommandId.makeUnsafe("cmd-1"),65 commandId: CommandId.make("cmd-1"),
65 causationEventId: null,66 causationEventId: null,
66 correlationId: CommandId.makeUnsafe("cmd-1"),67 correlationId: CommandId.make("cmd-1"),
67 metadata: {},68 metadata: {},
68 payload: {69 payload: {
69 projectId: ProjectId.makeUnsafe("project-1"),70 projectId: ProjectId.make("project-1"),
70 title: "Project 1",71 title: "Project 1",
71 workspaceRoot: "/tmp/project-1",72 workspaceRoot: "/tmp/project-1",
72 defaultModelSelection: null,73 defaultModelSelection: null,
@@ -78,17 +79,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
78 79
79 yield* eventStore.append({80 yield* eventStore.append({
80 type: "thread.created",81 type: "thread.created",
81 eventId: EventId.makeUnsafe("evt-2"),82 eventId: EventId.make("evt-2"),
82 aggregateKind: "thread",83 aggregateKind: "thread",
83 aggregateId: ThreadId.makeUnsafe("thread-1"),84 aggregateId: ThreadId.make("thread-1"),
84 occurredAt: now,85 occurredAt: now,
85 commandId: CommandId.makeUnsafe("cmd-2"),86 commandId: CommandId.make("cmd-2"),
86 causationEventId: null,87 causationEventId: null,
87 correlationId: CommandId.makeUnsafe("cmd-2"),88 correlationId: CommandId.make("cmd-2"),
88 metadata: {},89 metadata: {},
89 payload: {90 payload: {
90 threadId: ThreadId.makeUnsafe("thread-1"),91 threadId: ThreadId.make("thread-1"),
91 projectId: ProjectId.makeUnsafe("project-1"),92 projectId: ProjectId.make("project-1"),
92 title: "Thread 1",93 title: "Thread 1",
93 modelSelection: {94 modelSelection: {
94 provider: "codex",95 provider: "codex",
@@ -104,17 +105,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
104 105
105 yield* eventStore.append({106 yield* eventStore.append({
106 type: "thread.message-sent",107 type: "thread.message-sent",
107 eventId: EventId.makeUnsafe("evt-3"),108 eventId: EventId.make("evt-3"),
108 aggregateKind: "thread",109 aggregateKind: "thread",
109 aggregateId: ThreadId.makeUnsafe("thread-1"),110 aggregateId: ThreadId.make("thread-1"),
110 occurredAt: now,111 occurredAt: now,
111 commandId: CommandId.makeUnsafe("cmd-3"),112 commandId: CommandId.make("cmd-3"),
112 causationEventId: null,113 causationEventId: null,
113 correlationId: CommandId.makeUnsafe("cmd-3"),114 correlationId: CommandId.make("cmd-3"),
114 metadata: {},115 metadata: {},
115 payload: {116 payload: {
116 threadId: ThreadId.makeUnsafe("thread-1"),117 threadId: ThreadId.make("thread-1"),
117 messageId: MessageId.makeUnsafe("message-1"),118 messageId: MessageId.make("message-1"),
118 role: "assistant",119 role: "assistant",
119 text: "hello",120 text: "hello",
120 turnId: null,121 turnId: null,
@@ -182,17 +183,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))( · 61 unmodified lines
182 183
183 yield* eventStore.append({184 yield* eventStore.append({
184 type: "thread.message-sent",185 type: "thread.message-sent",
185 eventId: EventId.makeUnsafe("evt-attachments"),186 eventId: EventId.make("evt-attachments"),
186 aggregateKind: "thread",187 aggregateKind: "thread",
187 aggregateId: ThreadId.makeUnsafe("thread-attachments"),188 aggregateId: ThreadId.make("thread-attachments"),
188 occurredAt: now,189 occurredAt: now,
189 commandId: CommandId.makeUnsafe("cmd-attachments"),190 commandId: CommandId.make("cmd-attachments"),
190 causationEventId: null,191 causationEventId: null,
191 correlationId: CommandId.makeUnsafe("cmd-attachments"),192 correlationId: CommandId.make("cmd-attachments"),
192 metadata: {},193 metadata: {},
193 payload: {194 payload: {
194 threadId: ThreadId.makeUnsafe("thread-attachments"),195 threadId: ThreadId.make("thread-attachments"),
195 messageId: MessageId.makeUnsafe("message-attachments"),196 messageId: MessageId.make("message-attachments"),
196 role: "user",197 role: "user",
197 text: "Inspect this",198 text: "Inspect this",
198 attachments: [199 attachments: [
@@ -248,17 +249,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 49 unmodified lines
248 249
249 yield* eventStore.append({250 yield* eventStore.append({
250 type: "thread.message-sent",251 type: "thread.message-sent",
251 eventId: EventId.makeUnsafe("evt-attachments-safe"),252 eventId: EventId.make("evt-attachments-safe"),
252 aggregateKind: "thread",253 aggregateKind: "thread",
253 aggregateId: ThreadId.makeUnsafe("thread-attachments-safe"),254 aggregateId: ThreadId.make("thread-attachments-safe"),
254 occurredAt: now,255 occurredAt: now,
255 commandId: CommandId.makeUnsafe("cmd-attachments-safe"),256 commandId: CommandId.make("cmd-attachments-safe"),
256 causationEventId: null,257 causationEventId: null,
257 correlationId: CommandId.makeUnsafe("cmd-attachments-safe"),258 correlationId: CommandId.make("cmd-attachments-safe"),
258 metadata: {},259 metadata: {},
259 payload: {260 payload: {
260 threadId: ThreadId.makeUnsafe("thread-attachments-safe"),261 threadId: ThreadId.make("thread-attachments-safe"),
261 messageId: MessageId.makeUnsafe("message-attachments-safe"),262 messageId: MessageId.make("message-attachments-safe"),
262 role: "user",263 role: "user",
263 text: "Inspect this",264 text: "Inspect this",
264 attachments: [265 attachments: [
@@ -329,16 +330,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 64 unmodified lines
329 330
330 yield* eventStore.append({331 yield* eventStore.append({
331 type: "project.created",332 type: "project.created",
332 eventId: EventId.makeUnsafe("evt-clear-attachments-1"),333 eventId: EventId.make("evt-clear-attachments-1"),
333 aggregateKind: "project",334 aggregateKind: "project",
334 aggregateId: ProjectId.makeUnsafe("project-clear-attachments"),335 aggregateId: ProjectId.make("project-clear-attachments"),
335 occurredAt: now,336 occurredAt: now,
336 commandId: CommandId.makeUnsafe("cmd-clear-attachments-1"),337 commandId: CommandId.make("cmd-clear-attachments-1"),
337 causationEventId: null,338 causationEventId: null,
338 correlationId: CommandId.makeUnsafe("cmd-clear-attachments-1"),339 correlationId: CommandId.make("cmd-clear-attachments-1"),
339 metadata: {},340 metadata: {},
340 payload: {341 payload: {
341 projectId: ProjectId.makeUnsafe("project-clear-attachments"),342 projectId: ProjectId.make("project-clear-attachments"),
342 title: "Project Clear Attachments",343 title: "Project Clear Attachments",
343 workspaceRoot: "/tmp/project-clear-attachments",344 workspaceRoot: "/tmp/project-clear-attachments",
344 defaultModelSelection: null,345 defaultModelSelection: null,
@@ -350,17 +351,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
350 351
351 yield* eventStore.append({352 yield* eventStore.append({
352 type: "thread.created",353 type: "thread.created",
353 eventId: EventId.makeUnsafe("evt-clear-attachments-2"),354 eventId: EventId.make("evt-clear-attachments-2"),
354 aggregateKind: "thread",355 aggregateKind: "thread",
355 aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"),356 aggregateId: ThreadId.make("thread-clear-attachments"),
356 occurredAt: now,357 occurredAt: now,
357 commandId: CommandId.makeUnsafe("cmd-clear-attachments-2"),358 commandId: CommandId.make("cmd-clear-attachments-2"),
358 causationEventId: null,359 causationEventId: null,
359 correlationId: CommandId.makeUnsafe("cmd-clear-attachments-2"),360 correlationId: CommandId.make("cmd-clear-attachments-2"),
360 metadata: {},361 metadata: {},
361 payload: {362 payload: {
362 threadId: ThreadId.makeUnsafe("thread-clear-attachments"),363 threadId: ThreadId.make("thread-clear-attachments"),
363 projectId: ProjectId.makeUnsafe("project-clear-attachments"),364 projectId: ProjectId.make("project-clear-attachments"),
364 title: "Thread Clear Attachments",365 title: "Thread Clear Attachments",
365 modelSelection: {366 modelSelection: {
366 provider: "codex",367 provider: "codex",
@@ -376,17 +377,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
376 377
377 yield* eventStore.append({378 yield* eventStore.append({
378 type: "thread.message-sent",379 type: "thread.message-sent",
379 eventId: EventId.makeUnsafe("evt-clear-attachments-3"),380 eventId: EventId.make("evt-clear-attachments-3"),
380 aggregateKind: "thread",381 aggregateKind: "thread",
381 aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"),382 aggregateId: ThreadId.make("thread-clear-attachments"),
382 occurredAt: now,383 occurredAt: now,
383 commandId: CommandId.makeUnsafe("cmd-clear-attachments-3"),384 commandId: CommandId.make("cmd-clear-attachments-3"),
384 causationEventId: null,385 causationEventId: null,
385 correlationId: CommandId.makeUnsafe("cmd-clear-attachments-3"),386 correlationId: CommandId.make("cmd-clear-attachments-3"),
386 metadata: {},387 metadata: {},
387 payload: {388 payload: {
388 threadId: ThreadId.makeUnsafe("thread-clear-attachments"),389 threadId: ThreadId.make("thread-clear-attachments"),
389 messageId: MessageId.makeUnsafe("message-clear-attachments"),390 messageId: MessageId.make("message-clear-attachments"),
390 role: "user",391 role: "user",
391 text: "Has attachments",392 text: "Has attachments",
392 attachments: [393 attachments: [
@@ -407,17 +408,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 14 unmodified lines
407 408
408 yield* eventStore.append({409 yield* eventStore.append({
409 type: "thread.message-sent",410 type: "thread.message-sent",
410 eventId: EventId.makeUnsafe("evt-clear-attachments-4"),411 eventId: EventId.make("evt-clear-attachments-4"),
411 aggregateKind: "thread",412 aggregateKind: "thread",
412 aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"),413 aggregateId: ThreadId.make("thread-clear-attachments"),
413 occurredAt: later,414 occurredAt: later,
414 commandId: CommandId.makeUnsafe("cmd-clear-attachments-4"),415 commandId: CommandId.make("cmd-clear-attachments-4"),
415 causationEventId: null,416 causationEventId: null,
416 correlationId: CommandId.makeUnsafe("cmd-clear-attachments-4"),417 correlationId: CommandId.make("cmd-clear-attachments-4"),
417 metadata: {},418 metadata: {},
418 payload: {419 payload: {
419 threadId: ThreadId.makeUnsafe("thread-clear-attachments"),420 threadId: ThreadId.make("thread-clear-attachments"),
420 messageId: MessageId.makeUnsafe("message-clear-attachments"),421 messageId: MessageId.make("message-clear-attachments"),
421 role: "user",422 role: "user",
422 text: "",423 text: "",
423 attachments: [],424 attachments: [],
@@ -457,16 +458,16 @@ it.layer( · 33 unmodified lines
457 458
458 yield* eventStore.append({459 yield* eventStore.append({
459 type: "project.created",460 type: "project.created",
460 eventId: EventId.makeUnsafe("evt-overwrite-1"),461 eventId: EventId.make("evt-overwrite-1"),
461 aggregateKind: "project",462 aggregateKind: "project",
462 aggregateId: ProjectId.makeUnsafe("project-overwrite"),463 aggregateId: ProjectId.make("project-overwrite"),
463 occurredAt: now,464 occurredAt: now,
464 commandId: CommandId.makeUnsafe("cmd-overwrite-1"),465 commandId: CommandId.make("cmd-overwrite-1"),
465 causationEventId: null,466 causationEventId: null,
466 correlationId: CommandId.makeUnsafe("cmd-overwrite-1"),467 correlationId: CommandId.make("cmd-overwrite-1"),
467 metadata: {},468 metadata: {},
468 payload: {469 payload: {
469 projectId: ProjectId.makeUnsafe("project-overwrite"),470 projectId: ProjectId.make("project-overwrite"),
470 title: "Project Overwrite",471 title: "Project Overwrite",
471 workspaceRoot: "/tmp/project-overwrite",472 workspaceRoot: "/tmp/project-overwrite",
472 defaultModelSelection: null,473 defaultModelSelection: null,
@@ -478,17 +479,17 @@ it.layer( · 5 unmodified lines
478 479
479 yield* eventStore.append({480 yield* eventStore.append({
480 type: "thread.created",481 type: "thread.created",
481 eventId: EventId.makeUnsafe("evt-overwrite-2"),482 eventId: EventId.make("evt-overwrite-2"),
482 aggregateKind: "thread",483 aggregateKind: "thread",
483 aggregateId: ThreadId.makeUnsafe("thread-overwrite"),484 aggregateId: ThreadId.make("thread-overwrite"),
484 occurredAt: now,485 occurredAt: now,
485 commandId: CommandId.makeUnsafe("cmd-overwrite-2"),486 commandId: CommandId.make("cmd-overwrite-2"),
486 causationEventId: null,487 causationEventId: null,
487 correlationId: CommandId.makeUnsafe("cmd-overwrite-2"),488 correlationId: CommandId.make("cmd-overwrite-2"),
488 metadata: {},489 metadata: {},
489 payload: {490 payload: {
490 threadId: ThreadId.makeUnsafe("thread-overwrite"),491 threadId: ThreadId.make("thread-overwrite"),
491 projectId: ProjectId.makeUnsafe("project-overwrite"),492 projectId: ProjectId.make("project-overwrite"),
492 title: "Thread Overwrite",493 title: "Thread Overwrite",
493 modelSelection: {494 modelSelection: {
494 provider: "codex",495 provider: "codex",
@@ -504,17 +505,17 @@ it.layer( · 9 unmodified lines
504 505
505 yield* eventStore.append({506 yield* eventStore.append({
506 type: "thread.message-sent",507 type: "thread.message-sent",
507 eventId: EventId.makeUnsafe("evt-overwrite-3"),508 eventId: EventId.make("evt-overwrite-3"),
508 aggregateKind: "thread",509 aggregateKind: "thread",
509 aggregateId: ThreadId.makeUnsafe("thread-overwrite"),510 aggregateId: ThreadId.make("thread-overwrite"),
510 occurredAt: now,511 occurredAt: now,
511 commandId: CommandId.makeUnsafe("cmd-overwrite-3"),512 commandId: CommandId.make("cmd-overwrite-3"),
512 causationEventId: null,513 causationEventId: null,
513 correlationId: CommandId.makeUnsafe("cmd-overwrite-3"),514 correlationId: CommandId.make("cmd-overwrite-3"),
514 metadata: {},515 metadata: {},
515 payload: {516 payload: {
516 threadId: ThreadId.makeUnsafe("thread-overwrite"),517 threadId: ThreadId.make("thread-overwrite"),
517 messageId: MessageId.makeUnsafe("message-overwrite"),518 messageId: MessageId.make("message-overwrite"),
518 role: "user",519 role: "user",
519 text: "first image",520 text: "first image",
520 attachments: [521 attachments: [
@@ -535,17 +536,17 @@ it.layer( · 14 unmodified lines
535 536
536 yield* eventStore.append({537 yield* eventStore.append({
537 type: "thread.message-sent",538 type: "thread.message-sent",
538 eventId: EventId.makeUnsafe("evt-overwrite-4"),539 eventId: EventId.make("evt-overwrite-4"),
539 aggregateKind: "thread",540 aggregateKind: "thread",
540 aggregateId: ThreadId.makeUnsafe("thread-overwrite"),541 aggregateId: ThreadId.make("thread-overwrite"),
541 occurredAt: later,542 occurredAt: later,
542 commandId: CommandId.makeUnsafe("cmd-overwrite-4"),543 commandId: CommandId.make("cmd-overwrite-4"),
543 causationEventId: null,544 causationEventId: null,
544 correlationId: CommandId.makeUnsafe("cmd-overwrite-4"),545 correlationId: CommandId.make("cmd-overwrite-4"),
545 metadata: {},546 metadata: {},
546 payload: {547 payload: {
547 threadId: ThreadId.makeUnsafe("thread-overwrite"),548 threadId: ThreadId.make("thread-overwrite"),
548 messageId: MessageId.makeUnsafe("message-overwrite"),549 messageId: MessageId.make("message-overwrite"),
549 role: "user",550 role: "user",
550 text: "",551 text: "",
551 attachments: [552 attachments: [
@@ -605,16 +606,16 @@ it.layer( · 53 unmodified lines
605 606
606 yield* appendAndProject({607 yield* appendAndProject({
607 type: "project.created",608 type: "project.created",
608 eventId: EventId.makeUnsafe("evt-rollback-1"),609 eventId: EventId.make("evt-rollback-1"),
609 aggregateKind: "project",610 aggregateKind: "project",
610 aggregateId: ProjectId.makeUnsafe("project-rollback"),611 aggregateId: ProjectId.make("project-rollback"),
611 occurredAt: now,612 occurredAt: now,
612 commandId: CommandId.makeUnsafe("cmd-rollback-1"),613 commandId: CommandId.make("cmd-rollback-1"),
613 causationEventId: null,614 causationEventId: null,
614 correlationId: CorrelationId.makeUnsafe("cmd-rollback-1"),615 correlationId: CorrelationId.make("cmd-rollback-1"),
615 metadata: {},616 metadata: {},
616 payload: {617 payload: {
617 projectId: ProjectId.makeUnsafe("project-rollback"),618 projectId: ProjectId.make("project-rollback"),
618 title: "Project Rollback",619 title: "Project Rollback",
619 workspaceRoot: "/tmp/project-rollback",620 workspaceRoot: "/tmp/project-rollback",
620 defaultModelSelection: null,621 defaultModelSelection: null,
@@ -626,17 +627,17 @@ it.layer( · 5 unmodified lines
626 627
627 yield* appendAndProject({628 yield* appendAndProject({
628 type: "thread.created",629 type: "thread.created",
629 eventId: EventId.makeUnsafe("evt-rollback-2"),630 eventId: EventId.make("evt-rollback-2"),
630 aggregateKind: "thread",631 aggregateKind: "thread",
631 aggregateId: ThreadId.makeUnsafe("thread-rollback"),632 aggregateId: ThreadId.make("thread-rollback"),
632 occurredAt: now,633 occurredAt: now,
633 commandId: CommandId.makeUnsafe("cmd-rollback-2"),634 commandId: CommandId.make("cmd-rollback-2"),
634 causationEventId: null,635 causationEventId: null,
635 correlationId: CorrelationId.makeUnsafe("cmd-rollback-2"),636 correlationId: CorrelationId.make("cmd-rollback-2"),
636 metadata: {},637 metadata: {},
637 payload: {638 payload: {
638 threadId: ThreadId.makeUnsafe("thread-rollback"),639 threadId: ThreadId.make("thread-rollback"),
639 projectId: ProjectId.makeUnsafe("project-rollback"),640 projectId: ProjectId.make("project-rollback"),
640 title: "Thread Rollback",641 title: "Thread Rollback",
641 modelSelection: {642 modelSelection: {
642 provider: "codex",643 provider: "codex",
@@ -662,17 +663,17 @@ it.layer( · 19 unmodified lines
662 const result = yield* Effect.result(663 const result = yield* Effect.result(
663 appendAndProject({664 appendAndProject({
664 type: "thread.message-sent",665 type: "thread.message-sent",
665 eventId: EventId.makeUnsafe("evt-rollback-3"),666 eventId: EventId.make("evt-rollback-3"),
666 aggregateKind: "thread",667 aggregateKind: "thread",
667 aggregateId: ThreadId.makeUnsafe("thread-rollback"),668 aggregateId: ThreadId.make("thread-rollback"),
668 occurredAt: now,669 occurredAt: now,
669 commandId: CommandId.makeUnsafe("cmd-rollback-3"),670 commandId: CommandId.make("cmd-rollback-3"),
670 causationEventId: null,671 causationEventId: null,
671 correlationId: CorrelationId.makeUnsafe("cmd-rollback-3"),672 correlationId: CorrelationId.make("cmd-rollback-3"),
672 metadata: {},673 metadata: {},
673 payload: {674 payload: {
674 threadId: ThreadId.makeUnsafe("thread-rollback"),675 threadId: ThreadId.make("thread-rollback"),
675 messageId: MessageId.makeUnsafe("message-rollback"),676 messageId: MessageId.make("message-rollback"),
676 role: "user",677 role: "user",
677 text: "Rollback me",678 text: "Rollback me",
678 attachments: [679 attachments: [
@@ -721,7 +722,7 @@ it.layer( · 42 unmodified lines
721 const eventStore = yield* OrchestrationEventStore;722 const eventStore = yield* OrchestrationEventStore;
722 const { attachmentsDir } = yield* ServerConfig;723 const { attachmentsDir } = yield* ServerConfig;
723 const now = new Date().toISOString();724 const now = new Date().toISOString();
724 const threadId = ThreadId.makeUnsafe("Thread Revert.Files");725 const threadId = ThreadId.make("Thread Revert.Files");
725 const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001";726 const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001";
726 const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002";727 const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002";
727 const otherThreadAttachmentId =728 const otherThreadAttachmentId =
@@ -734,16 +735,16 @@ it.layer( · 6 unmodified lines
734 735
735 yield* appendAndProject({736 yield* appendAndProject({
736 type: "project.created",737 type: "project.created",
737 eventId: EventId.makeUnsafe("evt-revert-files-1"),738 eventId: EventId.make("evt-revert-files-1"),
738 aggregateKind: "project",739 aggregateKind: "project",
739 aggregateId: ProjectId.makeUnsafe("project-revert-files"),740 aggregateId: ProjectId.make("project-revert-files"),
740 occurredAt: now,741 occurredAt: now,
741 commandId: CommandId.makeUnsafe("cmd-revert-files-1"),742 commandId: CommandId.make("cmd-revert-files-1"),
742 causationEventId: null,743 causationEventId: null,
743 correlationId: CorrelationId.makeUnsafe("cmd-revert-files-1"),744 correlationId: CorrelationId.make("cmd-revert-files-1"),
744 metadata: {},745 metadata: {},
745 payload: {746 payload: {
746 projectId: ProjectId.makeUnsafe("project-revert-files"),747 projectId: ProjectId.make("project-revert-files"),
747 title: "Project Revert Files",748 title: "Project Revert Files",
748 workspaceRoot: "/tmp/project-revert-files",749 workspaceRoot: "/tmp/project-revert-files",
749 defaultModelSelection: null,750 defaultModelSelection: null,
@@ -755,17 +756,17 @@ it.layer( · 5 unmodified lines
755 756
756 yield* appendAndProject({757 yield* appendAndProject({
757 type: "thread.created",758 type: "thread.created",
758 eventId: EventId.makeUnsafe("evt-revert-files-2"),759 eventId: EventId.make("evt-revert-files-2"),
759 aggregateKind: "thread",760 aggregateKind: "thread",
760 aggregateId: threadId,761 aggregateId: threadId,
761 occurredAt: now,762 occurredAt: now,
762 commandId: CommandId.makeUnsafe("cmd-revert-files-2"),763 commandId: CommandId.make("cmd-revert-files-2"),
763 causationEventId: null,764 causationEventId: null,
764 correlationId: CorrelationId.makeUnsafe("cmd-revert-files-2"),765 correlationId: CorrelationId.make("cmd-revert-files-2"),
765 metadata: {},766 metadata: {},
766 payload: {767 payload: {
767 threadId,768 threadId,
768 projectId: ProjectId.makeUnsafe("project-revert-files"),769 projectId: ProjectId.make("project-revert-files"),
769 title: "Thread Revert Files",770 title: "Thread Revert Files",
770 modelSelection: {771 modelSelection: {
771 provider: "codex",772 provider: "codex",
@@ -781,39 +782,39 @@ it.layer( · 9 unmodified lines
781 782
782 yield* appendAndProject({783 yield* appendAndProject({
783 type: "thread.turn-diff-completed",784 type: "thread.turn-diff-completed",
784 eventId: EventId.makeUnsafe("evt-revert-files-3"),785 eventId: EventId.make("evt-revert-files-3"),
785 aggregateKind: "thread",786 aggregateKind: "thread",
786 aggregateId: threadId,787 aggregateId: threadId,
787 occurredAt: now,788 occurredAt: now,
788 commandId: CommandId.makeUnsafe("cmd-revert-files-3"),789 commandId: CommandId.make("cmd-revert-files-3"),
789 causationEventId: null,790 causationEventId: null,
790 correlationId: CorrelationId.makeUnsafe("cmd-revert-files-3"),791 correlationId: CorrelationId.make("cmd-revert-files-3"),
791 metadata: {},792 metadata: {},
792 payload: {793 payload: {
793 threadId,794 threadId,
794 turnId: TurnId.makeUnsafe("turn-keep"),795 turnId: TurnId.make("turn-keep"),
795 checkpointTurnCount: 1,796 checkpointTurnCount: 1,
796 checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/1"),797 checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-files/turn/1"),
797 status: "ready",798 status: "ready",
798 files: [],799 files: [],
799 assistantMessageId: MessageId.makeUnsafe("message-keep"),800 assistantMessageId: MessageId.make("message-keep"),
800 completedAt: now,801 completedAt: now,
801 },802 },
802 });803 });
803 804
804 yield* appendAndProject({805 yield* appendAndProject({
805 type: "thread.message-sent",806 type: "thread.message-sent",
806 eventId: EventId.makeUnsafe("evt-revert-files-4"),807 eventId: EventId.make("evt-revert-files-4"),
807 aggregateKind: "thread",808 aggregateKind: "thread",
808 aggregateId: threadId,809 aggregateId: threadId,
809 occurredAt: now,810 occurredAt: now,
810 commandId: CommandId.makeUnsafe("cmd-revert-files-4"),811 commandId: CommandId.make("cmd-revert-files-4"),
811 causationEventId: null,812 causationEventId: null,
812 correlationId: CorrelationId.makeUnsafe("cmd-revert-files-4"),813 correlationId: CorrelationId.make("cmd-revert-files-4"),
813 metadata: {},814 metadata: {},
814 payload: {815 payload: {
815 threadId,816 threadId,
816 messageId: MessageId.makeUnsafe("message-keep"),817 messageId: MessageId.make("message-keep"),
817 role: "assistant",818 role: "assistant",
818 text: "Keep",819 text: "Keep",
819 attachments: [820 attachments: [
@@ -825,7 +826,7 @@ it.layer( · 5 unmodified lines
825 sizeBytes: 5,826 sizeBytes: 5,
826 },827 },
827 ],828 ],
828 turnId: TurnId.makeUnsafe("turn-keep"),829 turnId: TurnId.make("turn-keep"),
829 streaming: false,830 streaming: false,
830 createdAt: now,831 createdAt: now,
831 updatedAt: now,832 updatedAt: now,
@@ -834,39 +835,39 @@ it.layer( · 2 unmodified lines
834 835
835 yield* appendAndProject({836 yield* appendAndProject({
836 type: "thread.turn-diff-completed",837 type: "thread.turn-diff-completed",
837 eventId: EventId.makeUnsafe("evt-revert-files-5"),838 eventId: EventId.make("evt-revert-files-5"),
838 aggregateKind: "thread",839 aggregateKind: "thread",
839 aggregateId: threadId,840 aggregateId: threadId,
840 occurredAt: now,841 occurredAt: now,
841 commandId: CommandId.makeUnsafe("cmd-revert-files-5"),842 commandId: CommandId.make("cmd-revert-files-5"),
842 causationEventId: null,843 causationEventId: null,
843 correlationId: CorrelationId.makeUnsafe("cmd-revert-files-5"),844 correlationId: CorrelationId.make("cmd-revert-files-5"),
844 metadata: {},845 metadata: {},
845 payload: {846 payload: {
846 threadId,847 threadId,
847 turnId: TurnId.makeUnsafe("turn-remove"),848 turnId: TurnId.make("turn-remove"),
848 checkpointTurnCount: 2,849 checkpointTurnCount: 2,
849 checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/2"),850 checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-files/turn/2"),
850 status: "ready",851 status: "ready",
851 files: [],852 files: [],
852 assistantMessageId: MessageId.makeUnsafe("message-remove"),853 assistantMessageId: MessageId.make("message-remove"),
853 completedAt: now,854 completedAt: now,
854 },855 },
855 });856 });
856 857
857 yield* appendAndProject({858 yield* appendAndProject({
858 type: "thread.message-sent",859 type: "thread.message-sent",
859 eventId: EventId.makeUnsafe("evt-revert-files-6"),860 eventId: EventId.make("evt-revert-files-6"),
860 aggregateKind: "thread",861 aggregateKind: "thread",
861 aggregateId: threadId,862 aggregateId: threadId,
862 occurredAt: now,863 occurredAt: now,
863 commandId: CommandId.makeUnsafe("cmd-revert-files-6"),864 commandId: CommandId.make("cmd-revert-files-6"),
864 causationEventId: null,865 causationEventId: null,
865 correlationId: CorrelationId.makeUnsafe("cmd-revert-files-6"),866 correlationId: CorrelationId.make("cmd-revert-files-6"),
866 metadata: {},867 metadata: {},
867 payload: {868 payload: {
868 threadId,869 threadId,
869 messageId: MessageId.makeUnsafe("message-remove"),870 messageId: MessageId.make("message-remove"),
870 role: "assistant",871 role: "assistant",
871 text: "Remove",872 text: "Remove",
872 attachments: [873 attachments: [
@@ -878,7 +879,7 @@ it.layer( · 5 unmodified lines
878 sizeBytes: 5,879 sizeBytes: 5,
879 },880 },
880 ],881 ],
881 turnId: TurnId.makeUnsafe("turn-remove"),882 turnId: TurnId.make("turn-remove"),
882 streaming: false,883 streaming: false,
883 createdAt: now,884 createdAt: now,
884 updatedAt: now,885 updatedAt: now,
@@ -898,13 +899,13 @@ it.layer( · 13 unmodified lines
898 899
899 yield* appendAndProject({900 yield* appendAndProject({
900 type: "thread.reverted",901 type: "thread.reverted",
901 eventId: EventId.makeUnsafe("evt-revert-files-7"),902 eventId: EventId.make("evt-revert-files-7"),
902 aggregateKind: "thread",903 aggregateKind: "thread",
903 aggregateId: threadId,904 aggregateId: threadId,
904 occurredAt: now,905 occurredAt: now,
905 commandId: CommandId.makeUnsafe("cmd-revert-files-7"),906 commandId: CommandId.make("cmd-revert-files-7"),
906 causationEventId: null,907 causationEventId: null,
907 correlationId: CorrelationId.makeUnsafe("cmd-revert-files-7"),908 correlationId: CorrelationId.make("cmd-revert-files-7"),
908 metadata: {},909 metadata: {},
909 payload: {910 payload: {
910 threadId,911 threadId,
@@ -930,7 +931,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 19 unmodified lines
930 const eventStore = yield* OrchestrationEventStore;931 const eventStore = yield* OrchestrationEventStore;
931 const { attachmentsDir } = yield* ServerConfig;932 const { attachmentsDir } = yield* ServerConfig;
932 const now = new Date().toISOString();933 const now = new Date().toISOString();
933 const threadId = ThreadId.makeUnsafe("Thread Delete.Files");934 const threadId = ThreadId.make("Thread Delete.Files");
934 const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001";935 const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001";
935 const otherThreadAttachmentId =936 const otherThreadAttachmentId =
936 "thread-delete-files-extra-00000000-0000-4000-8000-000000000002";937 "thread-delete-files-extra-00000000-0000-4000-8000-000000000002";
@@ -942,16 +943,16 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 5 unmodified lines
942 943
943 yield* appendAndProject({944 yield* appendAndProject({
944 type: "project.created",945 type: "project.created",
945 eventId: EventId.makeUnsafe("evt-delete-files-1"),946 eventId: EventId.make("evt-delete-files-1"),
946 aggregateKind: "project",947 aggregateKind: "project",
947 aggregateId: ProjectId.makeUnsafe("project-delete-files"),948 aggregateId: ProjectId.make("project-delete-files"),
948 occurredAt: now,949 occurredAt: now,
949 commandId: CommandId.makeUnsafe("cmd-delete-files-1"),950 commandId: CommandId.make("cmd-delete-files-1"),
950 causationEventId: null,951 causationEventId: null,
951 correlationId: CorrelationId.makeUnsafe("cmd-delete-files-1"),952 correlationId: CorrelationId.make("cmd-delete-files-1"),
952 metadata: {},953 metadata: {},
953 payload: {954 payload: {
954 projectId: ProjectId.makeUnsafe("project-delete-files"),955 projectId: ProjectId.make("project-delete-files"),
955 title: "Project Delete Files",956 title: "Project Delete Files",
956 workspaceRoot: "/tmp/project-delete-files",957 workspaceRoot: "/tmp/project-delete-files",
957 defaultModelSelection: null,958 defaultModelSelection: null,
@@ -963,17 +964,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 5 unmodified lines
963 964
964 yield* appendAndProject({965 yield* appendAndProject({
965 type: "thread.created",966 type: "thread.created",
966 eventId: EventId.makeUnsafe("evt-delete-files-2"),967 eventId: EventId.make("evt-delete-files-2"),
967 aggregateKind: "thread",968 aggregateKind: "thread",
968 aggregateId: threadId,969 aggregateId: threadId,
969 occurredAt: now,970 occurredAt: now,
970 commandId: CommandId.makeUnsafe("cmd-delete-files-2"),971 commandId: CommandId.make("cmd-delete-files-2"),
971 causationEventId: null,972 causationEventId: null,
972 correlationId: CorrelationId.makeUnsafe("cmd-delete-files-2"),973 correlationId: CorrelationId.make("cmd-delete-files-2"),
973 metadata: {},974 metadata: {},
974 payload: {975 payload: {
975 threadId,976 threadId,
976 projectId: ProjectId.makeUnsafe("project-delete-files"),977 projectId: ProjectId.make("project-delete-files"),
977 title: "Thread Delete Files",978 title: "Thread Delete Files",
978 modelSelection: {979 modelSelection: {
979 provider: "codex",980 provider: "codex",
@@ -989,17 +990,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 9 unmodified lines
989 990
990 yield* appendAndProject({991 yield* appendAndProject({
991 type: "thread.message-sent",992 type: "thread.message-sent",
992 eventId: EventId.makeUnsafe("evt-delete-files-3"),993 eventId: EventId.make("evt-delete-files-3"),
993 aggregateKind: "thread",994 aggregateKind: "thread",
994 aggregateId: threadId,995 aggregateId: threadId,
995 occurredAt: now,996 occurredAt: now,
996 commandId: CommandId.makeUnsafe("cmd-delete-files-3"),997 commandId: CommandId.make("cmd-delete-files-3"),
997 causationEventId: null,998 causationEventId: null,
998 correlationId: CorrelationId.makeUnsafe("cmd-delete-files-3"),999 correlationId: CorrelationId.make("cmd-delete-files-3"),
999 metadata: {},1000 metadata: {},
1000 payload: {1001 payload: {
1001 threadId,1002 threadId,
1002 messageId: MessageId.makeUnsafe("message-delete-files"),1003 messageId: MessageId.make("message-delete-files"),
1003 role: "user",1004 role: "user",
1004 text: "Delete",1005 text: "Delete",
1005 attachments: [1006 attachments: [
@@ -1031,13 +1032,13 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 25 unmodified lines
1031 1032
1032 yield* appendAndProject({1033 yield* appendAndProject({
1033 type: "thread.deleted",1034 type: "thread.deleted",
1034 eventId: EventId.makeUnsafe("evt-delete-files-4"),1035 eventId: EventId.make("evt-delete-files-4"),
1035 aggregateKind: "thread",1036 aggregateKind: "thread",
1036 aggregateId: threadId,1037 aggregateId: threadId,
1037 occurredAt: now,1038 occurredAt: now,
1038 commandId: CommandId.makeUnsafe("cmd-delete-files-4"),1039 commandId: CommandId.make("cmd-delete-files-4"),
1039 causationEventId: null,1040 causationEventId: null,
1040 correlationId: CorrelationId.makeUnsafe("cmd-delete-files-4"),1041 correlationId: CorrelationId.make("cmd-delete-files-4"),
1041 metadata: {},1042 metadata: {},
1042 payload: {1043 payload: {
1043 threadId,1044 threadId,
@@ -1071,16 +1072,16 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 27 unmodified lines
1071 1072
1072 yield* eventStore.append({1073 yield* eventStore.append({
1073 type: "thread.deleted",1074 type: "thread.deleted",
1074 eventId: EventId.makeUnsafe("evt-unsafe-thread-delete"),1075 eventId: EventId.make("evt-unsafe-thread-delete"),
1075 aggregateKind: "thread",1076 aggregateKind: "thread",
1076 aggregateId: ThreadId.makeUnsafe(".."),1077 aggregateId: ThreadId.make(".."),
1077 occurredAt: now,1078 occurredAt: now,
1078 commandId: CommandId.makeUnsafe("cmd-unsafe-thread-delete"),1079 commandId: CommandId.make("cmd-unsafe-thread-delete"),
1079 causationEventId: null,1080 causationEventId: null,
1080 correlationId: CorrelationId.makeUnsafe("cmd-unsafe-thread-delete"),1081 correlationId: CorrelationId.make("cmd-unsafe-thread-delete"),
1081 metadata: {},1082 metadata: {},
1082 payload: {1083 payload: {
1083 threadId: ThreadId.makeUnsafe(".."),1084 threadId: ThreadId.make(".."),
1084 deletedAt: now,1085 deletedAt: now,
1085 },1086 },
1086 });1087 });
@@ -1105,16 +1106,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 18 unmodified lines
1105 1106
1106 yield* eventStore.append({1107 yield* eventStore.append({
1107 type: "project.created",1108 type: "project.created",
1108 eventId: EventId.makeUnsafe("evt-a1"),1109 eventId: EventId.make("evt-a1"),
1109 aggregateKind: "project",1110 aggregateKind: "project",
1110 aggregateId: ProjectId.makeUnsafe("project-a"),1111 aggregateId: ProjectId.make("project-a"),
1111 occurredAt: now,1112 occurredAt: now,
1112 commandId: CommandId.makeUnsafe("cmd-a1"),1113 commandId: CommandId.make("cmd-a1"),
1113 causationEventId: null,1114 causationEventId: null,
1114 correlationId: CorrelationId.makeUnsafe("cmd-a1"),1115 correlationId: CorrelationId.make("cmd-a1"),
1115 metadata: {},1116 metadata: {},
1116 payload: {1117 payload: {
1117 projectId: ProjectId.makeUnsafe("project-a"),1118 projectId: ProjectId.make("project-a"),
1118 title: "Project A",1119 title: "Project A",
1119 workspaceRoot: "/tmp/project-a",1120 workspaceRoot: "/tmp/project-a",
1120 defaultModelSelection: null,1121 defaultModelSelection: null,
@@ -1126,17 +1127,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
1126 1127
1127 yield* eventStore.append({1128 yield* eventStore.append({
1128 type: "thread.created",1129 type: "thread.created",
1129 eventId: EventId.makeUnsafe("evt-a2"),1130 eventId: EventId.make("evt-a2"),
1130 aggregateKind: "thread",1131 aggregateKind: "thread",
1131 aggregateId: ThreadId.makeUnsafe("thread-a"),1132 aggregateId: ThreadId.make("thread-a"),
1132 occurredAt: now,1133 occurredAt: now,
1133 commandId: CommandId.makeUnsafe("cmd-a2"),1134 commandId: CommandId.make("cmd-a2"),
1134 causationEventId: null,1135 causationEventId: null,
1135 correlationId: CorrelationId.makeUnsafe("cmd-a2"),1136 correlationId: CorrelationId.make("cmd-a2"),
1136 metadata: {},1137 metadata: {},
1137 payload: {1138 payload: {
1138 threadId: ThreadId.makeUnsafe("thread-a"),1139 threadId: ThreadId.make("thread-a"),
1139 projectId: ProjectId.makeUnsafe("project-a"),1140 projectId: ProjectId.make("project-a"),
1140 title: "Thread A",1141 title: "Thread A",
1141 modelSelection: {1142 modelSelection: {
1142 provider: "codex",1143 provider: "codex",
@@ -1152,17 +1153,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
1152 1153
1153 yield* eventStore.append({1154 yield* eventStore.append({
1154 type: "thread.message-sent",1155 type: "thread.message-sent",
1155 eventId: EventId.makeUnsafe("evt-a3"),1156 eventId: EventId.make("evt-a3"),
1156 aggregateKind: "thread",1157 aggregateKind: "thread",
1157 aggregateId: ThreadId.makeUnsafe("thread-a"),1158 aggregateId: ThreadId.make("thread-a"),
1158 occurredAt: now,1159 occurredAt: now,
1159 commandId: CommandId.makeUnsafe("cmd-a3"),1160 commandId: CommandId.make("cmd-a3"),
1160 causationEventId: null,1161 causationEventId: null,
1161 correlationId: CorrelationId.makeUnsafe("cmd-a3"),1162 correlationId: CorrelationId.make("cmd-a3"),
1162 metadata: {},1163 metadata: {},
1163 payload: {1164 payload: {
1164 threadId: ThreadId.makeUnsafe("thread-a"),1165 threadId: ThreadId.make("thread-a"),
1165 messageId: MessageId.makeUnsafe("message-a"),1166 messageId: MessageId.make("message-a"),
1166 role: "assistant",1167 role: "assistant",
1167 text: "hello",1168 text: "hello",
1168 turnId: null,1169 turnId: null,
@@ -1176,17 +1177,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 7 unmodified lines
1176 1177
1177 yield* eventStore.append({1178 yield* eventStore.append({
1178 type: "thread.message-sent",1179 type: "thread.message-sent",
1179 eventId: EventId.makeUnsafe("evt-a4"),1180 eventId: EventId.make("evt-a4"),
1180 aggregateKind: "thread",1181 aggregateKind: "thread",
1181 aggregateId: ThreadId.makeUnsafe("thread-a"),1182 aggregateId: ThreadId.make("thread-a"),
1182 occurredAt: now,1183 occurredAt: now,
1183 commandId: CommandId.makeUnsafe("cmd-a4"),1184 commandId: CommandId.make("cmd-a4"),
1184 causationEventId: null,1185 causationEventId: null,
1185 correlationId: CorrelationId.makeUnsafe("cmd-a4"),1186 correlationId: CorrelationId.make("cmd-a4"),
1186 metadata: {},1187 metadata: {},
1187 payload: {1188 payload: {
1188 threadId: ThreadId.makeUnsafe("thread-a"),1189 threadId: ThreadId.make("thread-a"),
1189 messageId: MessageId.makeUnsafe("message-a"),1190 messageId: MessageId.make("message-a"),
1190 role: "assistant",1191 role: "assistant",
1191 text: " world",1192 text: " world",
1192 turnId: null,1193 turnId: null,
@@ -1232,16 +1233,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 39 unmodified lines
1232 1233
1233 yield* eventStore.append({1234 yield* eventStore.append({
1234 type: "project.created",1235 type: "project.created",
1235 eventId: EventId.makeUnsafe("evt-empty-1"),1236 eventId: EventId.make("evt-empty-1"),
1236 aggregateKind: "project",1237 aggregateKind: "project",
1237 aggregateId: ProjectId.makeUnsafe("project-empty"),1238 aggregateId: ProjectId.make("project-empty"),
1238 occurredAt: now,1239 occurredAt: now,
1239 commandId: CommandId.makeUnsafe("cmd-empty-1"),1240 commandId: CommandId.make("cmd-empty-1"),
1240 causationEventId: null,1241 causationEventId: null,
1241 correlationId: CorrelationId.makeUnsafe("cmd-empty-1"),1242 correlationId: CorrelationId.make("cmd-empty-1"),
1242 metadata: {},1243 metadata: {},
1243 payload: {1244 payload: {
1244 projectId: ProjectId.makeUnsafe("project-empty"),1245 projectId: ProjectId.make("project-empty"),
1245 title: "Project Empty",1246 title: "Project Empty",
1246 workspaceRoot: "/tmp/project-empty",1247 workspaceRoot: "/tmp/project-empty",
1247 defaultModelSelection: null,1248 defaultModelSelection: null,
@@ -1253,17 +1254,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
1253 1254
1254 yield* eventStore.append({1255 yield* eventStore.append({
1255 type: "thread.created",1256 type: "thread.created",
1256 eventId: EventId.makeUnsafe("evt-empty-2"),1257 eventId: EventId.make("evt-empty-2"),
1257 aggregateKind: "thread",1258 aggregateKind: "thread",
1258 aggregateId: ThreadId.makeUnsafe("thread-empty"),1259 aggregateId: ThreadId.make("thread-empty"),
1259 occurredAt: now,1260 occurredAt: now,
1260 commandId: CommandId.makeUnsafe("cmd-empty-2"),1261 commandId: CommandId.make("cmd-empty-2"),
1261 causationEventId: null,1262 causationEventId: null,
1262 correlationId: CorrelationId.makeUnsafe("cmd-empty-2"),1263 correlationId: CorrelationId.make("cmd-empty-2"),
1263 metadata: {},1264 metadata: {},
1264 payload: {1265 payload: {
1265 threadId: ThreadId.makeUnsafe("thread-empty"),1266 threadId: ThreadId.make("thread-empty"),
1266 projectId: ProjectId.makeUnsafe("project-empty"),1267 projectId: ProjectId.make("project-empty"),
1267 title: "Thread Empty",1268 title: "Thread Empty",
1268 modelSelection: {1269 modelSelection: {
1269 provider: "codex",1270 provider: "codex",
@@ -1279,17 +1280,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
1279 1280
1280 yield* eventStore.append({1281 yield* eventStore.append({
1281 type: "thread.message-sent",1282 type: "thread.message-sent",
1282 eventId: EventId.makeUnsafe("evt-empty-3"),1283 eventId: EventId.make("evt-empty-3"),
1283 aggregateKind: "thread",1284 aggregateKind: "thread",
1284 aggregateId: ThreadId.makeUnsafe("thread-empty"),1285 aggregateId: ThreadId.make("thread-empty"),
1285 occurredAt: now,1286 occurredAt: now,
1286 commandId: CommandId.makeUnsafe("cmd-empty-3"),1287 commandId: CommandId.make("cmd-empty-3"),
1287 causationEventId: null,1288 causationEventId: null,
1288 correlationId: CorrelationId.makeUnsafe("cmd-empty-3"),1289 correlationId: CorrelationId.make("cmd-empty-3"),
1289 metadata: {},1290 metadata: {},
1290 payload: {1291 payload: {
1291 threadId: ThreadId.makeUnsafe("thread-empty"),1292 threadId: ThreadId.make("thread-empty"),
1292 messageId: MessageId.makeUnsafe("assistant-empty"),1293 messageId: MessageId.make("assistant-empty"),
1293 role: "assistant",1294 role: "assistant",
1294 text: "Hello",1295 text: "Hello",
1295 turnId: null,1296 turnId: null,
@@ -1301,17 +1302,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
1301 1302
1302 yield* eventStore.append({1303 yield* eventStore.append({
1303 type: "thread.message-sent",1304 type: "thread.message-sent",
1304 eventId: EventId.makeUnsafe("evt-empty-4"),1305 eventId: EventId.make("evt-empty-4"),
1305 aggregateKind: "thread",1306 aggregateKind: "thread",
1306 aggregateId: ThreadId.makeUnsafe("thread-empty"),1307 aggregateId: ThreadId.make("thread-empty"),
1307 occurredAt: now,1308 occurredAt: now,
1308 commandId: CommandId.makeUnsafe("cmd-empty-4"),1309 commandId: CommandId.make("cmd-empty-4"),
1309 causationEventId: null,1310 causationEventId: null,
1310 correlationId: CorrelationId.makeUnsafe("cmd-empty-4"),1311 correlationId: CorrelationId.make("cmd-empty-4"),
1311 metadata: {},1312 metadata: {},
1312 payload: {1313 payload: {
1313 threadId: ThreadId.makeUnsafe("thread-empty"),1314 threadId: ThreadId.make("thread-empty"),
1314 messageId: MessageId.makeUnsafe("assistant-empty"),1315 messageId: MessageId.make("assistant-empty"),
1315 role: "assistant",1316 role: "assistant",
1316 text: " world",1317 text: " world",
1317 turnId: null,1318 turnId: null,
@@ -1323,17 +1324,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
1323 1324
1324 yield* eventStore.append({1325 yield* eventStore.append({
1325 type: "thread.message-sent",1326 type: "thread.message-sent",
1326 eventId: EventId.makeUnsafe("evt-empty-5"),1327 eventId: EventId.make("evt-empty-5"),
1327 aggregateKind: "thread",1328 aggregateKind: "thread",
1328 aggregateId: ThreadId.makeUnsafe("thread-empty"),1329 aggregateId: ThreadId.make("thread-empty"),
1329 occurredAt: now,1330 occurredAt: now,
1330 commandId: CommandId.makeUnsafe("cmd-empty-5"),1331 commandId: CommandId.make("cmd-empty-5"),
1331 causationEventId: null,1332 causationEventId: null,
1332 correlationId: CorrelationId.makeUnsafe("cmd-empty-5"),1333 correlationId: CorrelationId.make("cmd-empty-5"),
1333 metadata: {},1334 metadata: {},
1334 payload: {1335 payload: {
1335 threadId: ThreadId.makeUnsafe("thread-empty"),1336 threadId: ThreadId.make("thread-empty"),
1336 messageId: MessageId.makeUnsafe("assistant-empty"),1337 messageId: MessageId.make("assistant-empty"),
1337 role: "assistant",1338 role: "assistant",
1338 text: "",1339 text: "",
1339 turnId: null,1340 turnId: null,
@@ -1372,16 +1373,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 32 unmodified lines
1372 1373
1373 yield* appendAndProject({1374 yield* appendAndProject({
1374 type: "project.created",1375 type: "project.created",
1375 eventId: EventId.makeUnsafe("evt-conflict-1"),1376 eventId: EventId.make("evt-conflict-1"),
1376 aggregateKind: "project",1377 aggregateKind: "project",
1377 aggregateId: ProjectId.makeUnsafe("project-conflict"),1378 aggregateId: ProjectId.make("project-conflict"),
1378 occurredAt: "2026-02-26T13:00:00.000Z",1379 occurredAt: "2026-02-26T13:00:00.000Z",
1379 commandId: CommandId.makeUnsafe("cmd-conflict-1"),1380 commandId: CommandId.make("cmd-conflict-1"),
1380 causationEventId: null,1381 causationEventId: null,
1381 correlationId: CorrelationId.makeUnsafe("cmd-conflict-1"),1382 correlationId: CorrelationId.make("cmd-conflict-1"),
1382 metadata: {},1383 metadata: {},
1383 payload: {1384 payload: {
1384 projectId: ProjectId.makeUnsafe("project-conflict"),1385 projectId: ProjectId.make("project-conflict"),
1385 title: "Project Conflict",1386 title: "Project Conflict",
1386 workspaceRoot: "/tmp/project-conflict",1387 workspaceRoot: "/tmp/project-conflict",
1387 defaultModelSelection: null,1388 defaultModelSelection: null,
@@ -1393,17 +1394,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
1393 1394
1394 yield* appendAndProject({1395 yield* appendAndProject({
1395 type: "thread.created",1396 type: "thread.created",
1396 eventId: EventId.makeUnsafe("evt-conflict-2"),1397 eventId: EventId.make("evt-conflict-2"),
1397 aggregateKind: "thread",1398 aggregateKind: "thread",
1398 aggregateId: ThreadId.makeUnsafe("thread-conflict"),1399 aggregateId: ThreadId.make("thread-conflict"),
1399 occurredAt: "2026-02-26T13:00:01.000Z",1400 occurredAt: "2026-02-26T13:00:01.000Z",
1400 commandId: CommandId.makeUnsafe("cmd-conflict-2"),1401 commandId: CommandId.make("cmd-conflict-2"),
1401 causationEventId: null,1402 causationEventId: null,
1402 correlationId: CorrelationId.makeUnsafe("cmd-conflict-2"),1403 correlationId: CorrelationId.make("cmd-conflict-2"),
1403 metadata: {},1404 metadata: {},
1404 payload: {1405 payload: {
1405 threadId: ThreadId.makeUnsafe("thread-conflict"),1406 threadId: ThreadId.make("thread-conflict"),
1406 projectId: ProjectId.makeUnsafe("project-conflict"),1407 projectId: ProjectId.make("project-conflict"),
1407 title: "Thread Conflict",1408 title: "Thread Conflict",
1408 modelSelection: {1409 modelSelection: {
1409 provider: "codex",1410 provider: "codex",
@@ -1419,37 +1420,37 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
1419 1420
1420 yield* appendAndProject({1421 yield* appendAndProject({
1421 type: "thread.turn-interrupt-requested",1422 type: "thread.turn-interrupt-requested",
1422 eventId: EventId.makeUnsafe("evt-conflict-3"),1423 eventId: EventId.make("evt-conflict-3"),
1423 aggregateKind: "thread",1424 aggregateKind: "thread",
1424 aggregateId: ThreadId.makeUnsafe("thread-conflict"),1425 aggregateId: ThreadId.make("thread-conflict"),
1425 occurredAt: "2026-02-26T13:00:02.000Z",1426 occurredAt: "2026-02-26T13:00:02.000Z",
1426 commandId: CommandId.makeUnsafe("cmd-conflict-3"),1427 commandId: CommandId.make("cmd-conflict-3"),
1427 causationEventId: null,1428 causationEventId: null,
1428 correlationId: CorrelationId.makeUnsafe("cmd-conflict-3"),1429 correlationId: CorrelationId.make("cmd-conflict-3"),
1429 metadata: {},1430 metadata: {},
1430 payload: {1431 payload: {
1431 threadId: ThreadId.makeUnsafe("thread-conflict"),1432 threadId: ThreadId.make("thread-conflict"),
1432 turnId: TurnId.makeUnsafe("turn-interrupted"),1433 turnId: TurnId.make("turn-interrupted"),
1433 createdAt: "2026-02-26T13:00:02.000Z",1434 createdAt: "2026-02-26T13:00:02.000Z",
1434 },1435 },
1435 });1436 });
1436 1437
1437 yield* appendAndProject({1438 yield* appendAndProject({
1438 type: "thread.message-sent",1439 type: "thread.message-sent",
1439 eventId: EventId.makeUnsafe("evt-conflict-4"),1440 eventId: EventId.make("evt-conflict-4"),
1440 aggregateKind: "thread",1441 aggregateKind: "thread",
1441 aggregateId: ThreadId.makeUnsafe("thread-conflict"),1442 aggregateId: ThreadId.make("thread-conflict"),
1442 occurredAt: "2026-02-26T13:00:03.000Z",1443 occurredAt: "2026-02-26T13:00:03.000Z",
1443 commandId: CommandId.makeUnsafe("cmd-conflict-4"),1444 commandId: CommandId.make("cmd-conflict-4"),
1444 causationEventId: null,1445 causationEventId: null,
1445 correlationId: CorrelationId.makeUnsafe("cmd-conflict-4"),1446 correlationId: CorrelationId.make("cmd-conflict-4"),
1446 metadata: {},1447 metadata: {},
1447 payload: {1448 payload: {
1448 threadId: ThreadId.makeUnsafe("thread-conflict"),1449 threadId: ThreadId.make("thread-conflict"),
1449 messageId: MessageId.makeUnsafe("assistant-conflict"),1450 messageId: MessageId.make("assistant-conflict"),
1450 role: "assistant",1451 role: "assistant",
1451 text: "done",1452 text: "done",
1452 turnId: TurnId.makeUnsafe("turn-completed"),1453 turnId: TurnId.make("turn-completed"),
1453 streaming: false,1454 streaming: false,
1454 createdAt: "2026-02-26T13:00:03.000Z",1455 createdAt: "2026-02-26T13:00:03.000Z",
1455 updatedAt: "2026-02-26T13:00:03.000Z",1456 updatedAt: "2026-02-26T13:00:03.000Z",
@@ -1458,22 +1459,22 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 2 unmodified lines
1458 1459
1459 yield* appendAndProject({1460 yield* appendAndProject({
1460 type: "thread.turn-diff-completed",1461 type: "thread.turn-diff-completed",
1461 eventId: EventId.makeUnsafe("evt-conflict-5"),1462 eventId: EventId.make("evt-conflict-5"),
1462 aggregateKind: "thread",1463 aggregateKind: "thread",
1463 aggregateId: ThreadId.makeUnsafe("thread-conflict"),1464 aggregateId: ThreadId.make("thread-conflict"),
1464 occurredAt: "2026-02-26T13:00:04.000Z",1465 occurredAt: "2026-02-26T13:00:04.000Z",
1465 commandId: CommandId.makeUnsafe("cmd-conflict-5"),1466 commandId: CommandId.make("cmd-conflict-5"),
1466 causationEventId: null,1467 causationEventId: null,
1467 correlationId: CorrelationId.makeUnsafe("cmd-conflict-5"),1468 correlationId: CorrelationId.make("cmd-conflict-5"),
1468 metadata: {},1469 metadata: {},
1469 payload: {1470 payload: {
1470 threadId: ThreadId.makeUnsafe("thread-conflict"),1471 threadId: ThreadId.make("thread-conflict"),
1471 turnId: TurnId.makeUnsafe("turn-completed"),1472 turnId: TurnId.make("turn-completed"),
1472 checkpointTurnCount: 1,1473 checkpointTurnCount: 1,
1473 checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-conflict/turn/1"),1474 checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-conflict/turn/1"),
1474 status: "ready",1475 status: "ready",
1475 files: [],1476 files: [],
1476 assistantMessageId: MessageId.makeUnsafe("assistant-conflict"),1477 assistantMessageId: MessageId.make("assistant-conflict"),
1477 completedAt: "2026-02-26T13:00:04.000Z",1478 completedAt: "2026-02-26T13:00:04.000Z",
1478 },1479 },
1479 });1480 });
@@ -1516,16 +1517,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 36 unmodified lines
1516 1517
1517 yield* appendAndProject({1518 yield* appendAndProject({
1518 type: "project.created",1519 type: "project.created",
1519 eventId: EventId.makeUnsafe("evt-revert-1"),1520 eventId: EventId.make("evt-revert-1"),
1520 aggregateKind: "project",1521 aggregateKind: "project",
1521 aggregateId: ProjectId.makeUnsafe("project-revert"),1522 aggregateId: ProjectId.make("project-revert"),
1522 occurredAt: "2026-02-26T12:00:00.000Z",1523 occurredAt: "2026-02-26T12:00:00.000Z",
1523 commandId: CommandId.makeUnsafe("cmd-revert-1"),1524 commandId: CommandId.make("cmd-revert-1"),
1524 causationEventId: null,1525 causationEventId: null,
1525 correlationId: CorrelationId.makeUnsafe("cmd-revert-1"),1526 correlationId: CorrelationId.make("cmd-revert-1"),
1526 metadata: {},1527 metadata: {},
1527 payload: {1528 payload: {
1528 projectId: ProjectId.makeUnsafe("project-revert"),1529 projectId: ProjectId.make("project-revert"),
1529 title: "Project Revert",1530 title: "Project Revert",
1530 workspaceRoot: "/tmp/project-revert",1531 workspaceRoot: "/tmp/project-revert",
1531 defaultModelSelection: null,1532 defaultModelSelection: null,
@@ -1537,17 +1538,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
1537 1538
1538 yield* appendAndProject({1539 yield* appendAndProject({
1539 type: "thread.created",1540 type: "thread.created",
1540 eventId: EventId.makeUnsafe("evt-revert-2"),1541 eventId: EventId.make("evt-revert-2"),
1541 aggregateKind: "thread",1542 aggregateKind: "thread",
1542 aggregateId: ThreadId.makeUnsafe("thread-revert"),1543 aggregateId: ThreadId.make("thread-revert"),
1543 occurredAt: "2026-02-26T12:00:01.000Z",1544 occurredAt: "2026-02-26T12:00:01.000Z",
1544 commandId: CommandId.makeUnsafe("cmd-revert-2"),1545 commandId: CommandId.make("cmd-revert-2"),
1545 causationEventId: null,1546 causationEventId: null,
1546 correlationId: CorrelationId.makeUnsafe("cmd-revert-2"),1547 correlationId: CorrelationId.make("cmd-revert-2"),
1547 metadata: {},1548 metadata: {},
1548 payload: {1549 payload: {
1549 threadId: ThreadId.makeUnsafe("thread-revert"),1550 threadId: ThreadId.make("thread-revert"),
1550 projectId: ProjectId.makeUnsafe("project-revert"),1551 projectId: ProjectId.make("project-revert"),
1551 title: "Thread Revert",1552 title: "Thread Revert",
1552 modelSelection: {1553 modelSelection: {
1553 provider: "codex",1554 provider: "codex",
@@ -1563,42 +1564,42 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
1563 1564
1564 yield* appendAndProject({1565 yield* appendAndProject({
1565 type: "thread.turn-diff-completed",1566 type: "thread.turn-diff-completed",
1566 eventId: EventId.makeUnsafe("evt-revert-3"),1567 eventId: EventId.make("evt-revert-3"),
1567 aggregateKind: "thread",1568 aggregateKind: "thread",
1568 aggregateId: ThreadId.makeUnsafe("thread-revert"),1569 aggregateId: ThreadId.make("thread-revert"),
1569 occurredAt: "2026-02-26T12:00:02.000Z",1570 occurredAt: "2026-02-26T12:00:02.000Z",
1570 commandId: CommandId.makeUnsafe("cmd-revert-3"),1571 commandId: CommandId.make("cmd-revert-3"),
1571 causationEventId: null,1572 causationEventId: null,
1572 correlationId: CorrelationId.makeUnsafe("cmd-revert-3"),1573 correlationId: CorrelationId.make("cmd-revert-3"),
1573 metadata: {},1574 metadata: {},
1574 payload: {1575 payload: {
1575 threadId: ThreadId.makeUnsafe("thread-revert"),1576 threadId: ThreadId.make("thread-revert"),
1576 turnId: TurnId.makeUnsafe("turn-1"),1577 turnId: TurnId.make("turn-1"),
1577 checkpointTurnCount: 1,1578 checkpointTurnCount: 1,
1578 checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/1"),1579 checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/1"),
1579 status: "ready",1580 status: "ready",
1580 files: [],1581 files: [],
1581 assistantMessageId: MessageId.makeUnsafe("assistant-keep"),1582 assistantMessageId: MessageId.make("assistant-keep"),
1582 completedAt: "2026-02-26T12:00:02.000Z",1583 completedAt: "2026-02-26T12:00:02.000Z",
1583 },1584 },
1584 });1585 });
1585 1586
1586 yield* appendAndProject({1587 yield* appendAndProject({
1587 type: "thread.message-sent",1588 type: "thread.message-sent",
1588 eventId: EventId.makeUnsafe("evt-revert-4"),1589 eventId: EventId.make("evt-revert-4"),
1589 aggregateKind: "thread",1590 aggregateKind: "thread",
1590 aggregateId: ThreadId.makeUnsafe("thread-revert"),1591 aggregateId: ThreadId.make("thread-revert"),
1591 occurredAt: "2026-02-26T12:00:02.100Z",1592 occurredAt: "2026-02-26T12:00:02.100Z",
1592 commandId: CommandId.makeUnsafe("cmd-revert-4"),1593 commandId: CommandId.make("cmd-revert-4"),
1593 causationEventId: null,1594 causationEventId: null,
1594 correlationId: CorrelationId.makeUnsafe("cmd-revert-4"),1595 correlationId: CorrelationId.make("cmd-revert-4"),
1595 metadata: {},1596 metadata: {},
1596 payload: {1597 payload: {
1597 threadId: ThreadId.makeUnsafe("thread-revert"),1598 threadId: ThreadId.make("thread-revert"),
1598 messageId: MessageId.makeUnsafe("assistant-keep"),1599 messageId: MessageId.make("assistant-keep"),
1599 role: "assistant",1600 role: "assistant",
1600 text: "kept",1601 text: "kept",
1601 turnId: TurnId.makeUnsafe("turn-1"),1602 turnId: TurnId.make("turn-1"),
1602 streaming: false,1603 streaming: false,
1603 createdAt: "2026-02-26T12:00:02.100Z",1604 createdAt: "2026-02-26T12:00:02.100Z",
1604 updatedAt: "2026-02-26T12:00:02.100Z",1605 updatedAt: "2026-02-26T12:00:02.100Z",
@@ -1607,42 +1608,42 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 2 unmodified lines
1607 1608
1608 yield* appendAndProject({1609 yield* appendAndProject({
1609 type: "thread.turn-diff-completed",1610 type: "thread.turn-diff-completed",
1610 eventId: EventId.makeUnsafe("evt-revert-5"),1611 eventId: EventId.make("evt-revert-5"),
1611 aggregateKind: "thread",1612 aggregateKind: "thread",
1612 aggregateId: ThreadId.makeUnsafe("thread-revert"),1613 aggregateId: ThreadId.make("thread-revert"),
1613 occurredAt: "2026-02-26T12:00:03.000Z",1614 occurredAt: "2026-02-26T12:00:03.000Z",
1614 commandId: CommandId.makeUnsafe("cmd-revert-5"),1615 commandId: CommandId.make("cmd-revert-5"),
1615 causationEventId: null,1616 causationEventId: null,
1616 correlationId: CorrelationId.makeUnsafe("cmd-revert-5"),1617 correlationId: CorrelationId.make("cmd-revert-5"),
1617 metadata: {},1618 metadata: {},
1618 payload: {1619 payload: {
1619 threadId: ThreadId.makeUnsafe("thread-revert"),1620 threadId: ThreadId.make("thread-revert"),
1620 turnId: TurnId.makeUnsafe("turn-2"),1621 turnId: TurnId.make("turn-2"),
1621 checkpointTurnCount: 2,1622 checkpointTurnCount: 2,
1622 checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/2"),1623 checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/2"),
1623 status: "ready",1624 status: "ready",
1624 files: [],1625 files: [],
1625 assistantMessageId: MessageId.makeUnsafe("assistant-remove"),1626 assistantMessageId: MessageId.make("assistant-remove"),
1626 completedAt: "2026-02-26T12:00:03.000Z",1627 completedAt: "2026-02-26T12:00:03.000Z",
1627 },1628 },
1628 });1629 });
1629 1630
1630 yield* appendAndProject({1631 yield* appendAndProject({
1631 type: "thread.message-sent",1632 type: "thread.message-sent",
1632 eventId: EventId.makeUnsafe("evt-revert-6"),1633 eventId: EventId.make("evt-revert-6"),
1633 aggregateKind: "thread",1634 aggregateKind: "thread",
1634 aggregateId: ThreadId.makeUnsafe("thread-revert"),1635 aggregateId: ThreadId.make("thread-revert"),
1635 occurredAt: "2026-02-26T12:00:03.050Z",1636 occurredAt: "2026-02-26T12:00:03.050Z",
1636 commandId: CommandId.makeUnsafe("cmd-revert-6"),1637 commandId: CommandId.make("cmd-revert-6"),
1637 causationEventId: null,1638 causationEventId: null,
1638 correlationId: CorrelationId.makeUnsafe("cmd-revert-6"),1639 correlationId: CorrelationId.make("cmd-revert-6"),
1639 metadata: {},1640 metadata: {},
1640 payload: {1641 payload: {
1641 threadId: ThreadId.makeUnsafe("thread-revert"),1642 threadId: ThreadId.make("thread-revert"),
1642 messageId: MessageId.makeUnsafe("user-remove"),1643 messageId: MessageId.make("user-remove"),
1643 role: "user",1644 role: "user",
1644 text: "removed",1645 text: "removed",
1645 turnId: TurnId.makeUnsafe("turn-2"),1646 turnId: TurnId.make("turn-2"),
1646 streaming: false,1647 streaming: false,
1647 createdAt: "2026-02-26T12:00:03.050Z",1648 createdAt: "2026-02-26T12:00:03.050Z",
1648 updatedAt: "2026-02-26T12:00:03.050Z",1649 updatedAt: "2026-02-26T12:00:03.050Z",
@@ -1651,20 +1652,20 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 2 unmodified lines
1651 1652
1652 yield* appendAndProject({1653 yield* appendAndProject({
1653 type: "thread.message-sent",1654 type: "thread.message-sent",
1654 eventId: EventId.makeUnsafe("evt-revert-7"),1655 eventId: EventId.make("evt-revert-7"),
1655 aggregateKind: "thread",1656 aggregateKind: "thread",
1656 aggregateId: ThreadId.makeUnsafe("thread-revert"),1657 aggregateId: ThreadId.make("thread-revert"),
1657 occurredAt: "2026-02-26T12:00:03.100Z",1658 occurredAt: "2026-02-26T12:00:03.100Z",
1658 commandId: CommandId.makeUnsafe("cmd-revert-7"),1659 commandId: CommandId.make("cmd-revert-7"),
1659 causationEventId: null,1660 causationEventId: null,
1660 correlationId: CorrelationId.makeUnsafe("cmd-revert-7"),1661 correlationId: CorrelationId.make("cmd-revert-7"),
1661 metadata: {},1662 metadata: {},
1662 payload: {1663 payload: {
1663 threadId: ThreadId.makeUnsafe("thread-revert"),1664 threadId: ThreadId.make("thread-revert"),
1664 messageId: MessageId.makeUnsafe("assistant-remove"),1665 messageId: MessageId.make("assistant-remove"),
1665 role: "assistant",1666 role: "assistant",
1666 text: "removed",1667 text: "removed",
1667 turnId: TurnId.makeUnsafe("turn-2"),1668 turnId: TurnId.make("turn-2"),
1668 streaming: false,1669 streaming: false,
1669 createdAt: "2026-02-26T12:00:03.100Z",1670 createdAt: "2026-02-26T12:00:03.100Z",
1670 updatedAt: "2026-02-26T12:00:03.100Z",1671 updatedAt: "2026-02-26T12:00:03.100Z",
@@ -1673,16 +1674,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 2 unmodified lines
1673 1674
1674 yield* appendAndProject({1675 yield* appendAndProject({
1675 type: "thread.reverted",1676 type: "thread.reverted",
1676 eventId: EventId.makeUnsafe("evt-revert-8"),1677 eventId: EventId.make("evt-revert-8"),
1677 aggregateKind: "thread",1678 aggregateKind: "thread",
1678 aggregateId: ThreadId.makeUnsafe("thread-revert"),1679 aggregateId: ThreadId.make("thread-revert"),
1679 occurredAt: "2026-02-26T12:00:04.000Z",1680 occurredAt: "2026-02-26T12:00:04.000Z",
1680 commandId: CommandId.makeUnsafe("cmd-revert-8"),1681 commandId: CommandId.make("cmd-revert-8"),
1681 causationEventId: null,1682 causationEventId: null,
1682 correlationId: CorrelationId.makeUnsafe("cmd-revert-8"),1683 correlationId: CorrelationId.make("cmd-revert-8"),
1683 metadata: {},1684 metadata: {},
1684 payload: {1685 payload: {
1685 threadId: ThreadId.makeUnsafe("thread-revert"),1686 threadId: ThreadId.make("thread-revert"),
1686 turnCount: 1,1687 turnCount: 1,
1687 },1688 },
1688 });1689 });
@@ -1724,10 +1725,10 @@ it.effect("restores pending turn-start metadata across projection pipeline resta · 35 unmodified lines
1724 Layer.provideMerge(persistenceLayer),1725 Layer.provideMerge(persistenceLayer),
1725 );1726 );
1726 1727
1727 const threadId = ThreadId.makeUnsafe("thread-restart");1728 const threadId = ThreadId.make("thread-restart");
1728 const turnId = TurnId.makeUnsafe("turn-restart");1729 const turnId = TurnId.make("turn-restart");
1729 const messageId = MessageId.makeUnsafe("message-restart");1730 const messageId = MessageId.make("message-restart");
1730 const sourcePlanThreadId = ThreadId.makeUnsafe("thread-plan-source");1731 const sourcePlanThreadId = ThreadId.make("thread-plan-source");
1731 const sourcePlanId = "plan-source";1732 const sourcePlanId = "plan-source";
1732 const turnStartedAt = "2026-02-26T14:00:00.000Z";1733 const turnStartedAt = "2026-02-26T14:00:00.000Z";
1733 const sessionSetAt = "2026-02-26T14:00:05.000Z";1734 const sessionSetAt = "2026-02-26T14:00:05.000Z";
@@ -1738,13 +1739,13 @@ it.effect("restores pending turn-start metadata across projection pipeline resta · 4 unmodified lines
1738 1739
1739 yield* eventStore.append({1740 yield* eventStore.append({
1740 type: "thread.turn-start-requested",1741 type: "thread.turn-start-requested",
1741 eventId: EventId.makeUnsafe("evt-restart-1"),1742 eventId: EventId.make("evt-restart-1"),
1742 aggregateKind: "thread",1743 aggregateKind: "thread",
1743 aggregateId: threadId,1744 aggregateId: threadId,
1744 occurredAt: turnStartedAt,1745 occurredAt: turnStartedAt,
1745 commandId: CommandId.makeUnsafe("cmd-restart-1"),1746 commandId: CommandId.make("cmd-restart-1"),
1746 causationEventId: null,1747 causationEventId: null,
1747 correlationId: CorrelationId.makeUnsafe("cmd-restart-1"),1748 correlationId: CorrelationId.make("cmd-restart-1"),
1748 metadata: {},1749 metadata: {},
1749 payload: {1750 payload: {
1750 threadId,1751 threadId,
@@ -1768,13 +1769,13 @@ it.effect("restores pending turn-start metadata across projection pipeline resta · 17 unmodified lines
1768 1769
1769 yield* eventStore.append({1770 yield* eventStore.append({
1770 type: "thread.session-set",1771 type: "thread.session-set",
1771 eventId: EventId.makeUnsafe("evt-restart-2"),1772 eventId: EventId.make("evt-restart-2"),
1772 aggregateKind: "thread",1773 aggregateKind: "thread",
1773 aggregateId: threadId,1774 aggregateId: threadId,
1774 occurredAt: sessionSetAt,1775 occurredAt: sessionSetAt,
1775 commandId: CommandId.makeUnsafe("cmd-restart-2"),1776 commandId: CommandId.make("cmd-restart-2"),
1776 causationEventId: null,1777 causationEventId: null,
1777 correlationId: CorrelationId.makeUnsafe("cmd-restart-2"),1778 correlationId: CorrelationId.make("cmd-restart-2"),
1778 metadata: {},1779 metadata: {},
1779 payload: {1780 payload: {
1780 threadId,1781 threadId,
@@ -1846,6 +1847,7 @@ const engineLayer = it.layer( · 65 unmodified lines
1846 Layer.provide(OrchestrationProjectionPipelineLive),1847 Layer.provide(OrchestrationProjectionPipelineLive),
1847 Layer.provide(OrchestrationEventStoreLive),1848 Layer.provide(OrchestrationEventStoreLive),
1848 Layer.provide(OrchestrationCommandReceiptRepositoryLive),1849 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
1850 Layer.provide(RepositoryIdentityResolverLive),
1849 Layer.provideMerge(SqlitePersistenceMemory),1851 Layer.provideMerge(SqlitePersistenceMemory),
1850 Layer.provideMerge(1852 Layer.provideMerge(
1851 ServerConfig.layerTest(process.cwd(), {1853 ServerConfig.layerTest(process.cwd(), {
@@ -1865,8 +1867,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { · 13 unmodified lines
1865 1867
1866 yield* engine.dispatch({1868 yield* engine.dispatch({
1867 type: "project.create",1869 type: "project.create",
1868 commandId: CommandId.makeUnsafe("cmd-live-project"),1870 commandId: CommandId.make("cmd-live-project"),
1869 projectId: ProjectId.makeUnsafe("project-live"),1871 projectId: ProjectId.make("project-live"),
1870 title: "Live Project",1872 title: "Live Project",
1871 workspaceRoot: "/tmp/project-live",1873 workspaceRoot: "/tmp/project-live",
1872 defaultModelSelection: {1874 defaultModelSelection: {
@@ -1903,8 +1905,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { · 30 unmodified lines
1903 1905
1904 yield* engine.dispatch({1906 yield* engine.dispatch({
1905 type: "project.create",1907 type: "project.create",
1906 commandId: CommandId.makeUnsafe("cmd-scripts-project-create"),1908 commandId: CommandId.make("cmd-scripts-project-create"),
1907 projectId: ProjectId.makeUnsafe("project-scripts"),1909 projectId: ProjectId.make("project-scripts"),
1908 title: "Scripts Project",1910 title: "Scripts Project",
1909 workspaceRoot: "/tmp/project-scripts",1911 workspaceRoot: "/tmp/project-scripts",
1910 defaultModelSelection: {1912 defaultModelSelection: {
@@ -1916,8 +1918,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { · 5 unmodified lines
1916 1918
1917 yield* engine.dispatch({1919 yield* engine.dispatch({
1918 type: "project.meta.update",1920 type: "project.meta.update",
1919 commandId: CommandId.makeUnsafe("cmd-scripts-project-update"),1921 commandId: CommandId.make("cmd-scripts-project-update"),
1920 projectId: ProjectId.makeUnsafe("project-scripts"),1922 projectId: ProjectId.make("project-scripts"),
1921 scripts: [1923 scripts: [
1922 {1924 {
1923 id: "script-1",1925 id: "script-1",
apps/server/src/orchestration/Layers/ProjectionPipeline.ts+1−1
@@ -86,7 +86,7 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null { · 85 unmodified lines
86 return null;86 return null;
87 }87 }
88 const requestId = (payload as Record<string, unknown>).requestId;88 const requestId = (payload as Record<string, unknown>).requestId;
89 return typeof requestId === "string" ? ApprovalRequestId.makeUnsafe(requestId) : null;89 return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null;
90}90}
91 91
92function retainProjectionMessagesAfterRevert(92function retainProjectionMessagesAfterRevert(
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+18−13
@@ -4,18 +4,22 @@ import { Effect, Layer } from "effect"; · 3 unmodified lines
4import * as SqlClient from "effect/unstable/sql/SqlClient";4import * as SqlClient from "effect/unstable/sql/SqlClient";
5 5
6import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";6import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
7import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
7import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";8import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
8import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";9import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
9import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";10import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
10 11
11const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);12const asProjectId = (value: string): ProjectId => ProjectId.make(value);
12const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);13const asTurnId = (value: string): TurnId => TurnId.make(value);
13const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);14const asMessageId = (value: string): MessageId => MessageId.make(value);
14const asEventId = (value: string): EventId => EventId.makeUnsafe(value);15const asEventId = (value: string): EventId => EventId.make(value);
15const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);16const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
16 17
17const projectionSnapshotLayer = it.layer(18const projectionSnapshotLayer = it.layer(
18 OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),19 OrchestrationProjectionSnapshotQueryLive.pipe(
20 Layer.provideMerge(RepositoryIdentityResolverLive),
21 Layer.provideMerge(SqlitePersistenceMemory),
22 ),
19);23);
20 24
21projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {25projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
@@ -234,6 +238,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 212 unmodified lines
234 id: asProjectId("project-1"),238 id: asProjectId("project-1"),
235 title: "Project 1",239 title: "Project 1",
236 workspaceRoot: "/tmp/project-1",240 workspaceRoot: "/tmp/project-1",
241 repositoryIdentity: null,
237 defaultModelSelection: {242 defaultModelSelection: {
238 provider: "codex",243 provider: "codex",
239 model: "gpt-5-codex",244 model: "gpt-5-codex",
@@ -254,7 +259,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 14 unmodified lines
254 ]);259 ]);
255 assert.deepEqual(snapshot.threads, [260 assert.deepEqual(snapshot.threads, [
256 {261 {
257 id: ThreadId.makeUnsafe("thread-1"),262 id: ThreadId.make("thread-1"),
258 projectId: asProjectId("project-1"),263 projectId: asProjectId("project-1"),
259 title: "Thread 1",264 title: "Thread 1",
260 modelSelection: {265 modelSelection: {
@@ -273,7 +278,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 12 unmodified lines
273 completedAt: "2026-02-24T00:00:08.000Z",278 completedAt: "2026-02-24T00:00:08.000Z",
274 assistantMessageId: asMessageId("message-1"),279 assistantMessageId: asMessageId("message-1"),
275 sourceProposedPlan: {280 sourceProposedPlan: {
276 threadId: ThreadId.makeUnsafe("thread-1"),281 threadId: ThreadId.make("thread-1"),
277 planId: "plan-1",282 planId: "plan-1",
278 },283 },
279 },284 },
@@ -298,7 +303,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 18 unmodified lines
298 turnId: asTurnId("turn-1"),303 turnId: asTurnId("turn-1"),
299 planMarkdown: "# Ship it",304 planMarkdown: "# Ship it",
300 implementedAt: "2026-02-24T00:00:05.500Z",305 implementedAt: "2026-02-24T00:00:05.500Z",
301 implementationThreadId: ThreadId.makeUnsafe("thread-2"),306 implementationThreadId: ThreadId.make("thread-2"),
302 createdAt: "2026-02-24T00:00:05.000Z",307 createdAt: "2026-02-24T00:00:05.000Z",
303 updatedAt: "2026-02-24T00:00:05.500Z",308 updatedAt: "2026-02-24T00:00:05.500Z",
304 },309 },
@@ -326,7 +331,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 21 unmodified lines
326 },331 },
327 ],332 ],
328 session: {333 session: {
329 threadId: ThreadId.makeUnsafe("thread-1"),334 threadId: ThreadId.make("thread-1"),
330 status: "running",335 status: "running",
331 providerName: "codex",336 providerName: "codex",
332 runtimeMode: "approval-required",337 runtimeMode: "approval-required",
@@ -468,7 +473,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 135 unmodified lines
468 );473 );
469 assert.equal(firstThreadId._tag, "Some");474 assert.equal(firstThreadId._tag, "Some");
470 if (firstThreadId._tag === "Some") {475 if (firstThreadId._tag === "Some") {
471 assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first"));476 assert.equal(firstThreadId.value, ThreadId.make("thread-first"));
472 }477 }
473 }),478 }),
474 );479 );
@@ -591,12 +596,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 116 unmodified lines
591 `;596 `;
592 597
593 const context = yield* snapshotQuery.getThreadCheckpointContext(598 const context = yield* snapshotQuery.getThreadCheckpointContext(
594 ThreadId.makeUnsafe("thread-context"),599 ThreadId.make("thread-context"),
595 );600 );
596 assert.equal(context._tag, "Some");601 assert.equal(context._tag, "Some");
597 if (context._tag === "Some") {602 if (context._tag === "Some") {
598 assert.deepEqual(context.value, {603 assert.deepEqual(context.value, {
599 threadId: ThreadId.makeUnsafe("thread-context"),604 threadId: ThreadId.make("thread-context"),
600 projectId: asProjectId("project-context"),605 projectId: asProjectId("project-context"),
601 workspaceRoot: "/tmp/context-workspace",606 workspaceRoot: "/tmp/context-workspace",
602 worktreePath: "/tmp/context-worktree",607 worktreePath: "/tmp/context-worktree",
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+279−259
@@ -6,7 +6,6 @@ import { · 5 unmodified lines
6 OrchestrationCheckpointFile,6 OrchestrationCheckpointFile,
7 OrchestrationProposedPlanId,7 OrchestrationProposedPlanId,
8 OrchestrationReadModel,8 OrchestrationReadModel,
9 OrchestrationThreadActivity,
10 ProjectScript,9 ProjectScript,
11 TurnId,10 TurnId,
12 type OrchestrationCheckpointSummary,11 type OrchestrationCheckpointSummary,
@@ -16,6 +15,7 @@ import { · 3 unmodified lines
16 type OrchestrationProject,15 type OrchestrationProject,
17 type OrchestrationSession,16 type OrchestrationSession,
18 type OrchestrationThread,17 type OrchestrationThread,
18 type OrchestrationThreadActivity,
19 ModelSelection,19 ModelSelection,
20 ProjectId,20 ProjectId,
21 ThreadId,21 ThreadId,
@@ -38,6 +38,7 @@ import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionTh · 16 unmodified lines
38import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";38import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
39import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";39import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
40import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";40import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
41import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts";
41import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";42import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
42import {43import {
43 ProjectionSnapshotQuery,44 ProjectionSnapshotQuery,
@@ -163,6 +164,8 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st · 119 unmodified lines
163 164
164const makeProjectionSnapshotQuery = Effect.gen(function* () {165const makeProjectionSnapshotQuery = Effect.gen(function* () {
165 const sql = yield* SqlClient.SqlClient;166 const sql = yield* SqlClient.SqlClient;
167 const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
168 const repositoryIdentityResolutionConcurrency = 4;
166 169
167 const listProjectRows = SqlSchema.findAll({170 const listProjectRows = SqlSchema.findAll({
168 Request: Schema.Void,171 Request: Schema.Void,
@@ -436,271 +439,283 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { · 267 unmodified lines
436 const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>439 const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
437 sql440 sql
438 .withTransaction(441 .withTransaction(
439 Effect.gen(function* () {442 Effect.all([
440 const [443 listProjectRows(undefined).pipe(
441 projectRows,444 Effect.mapError(
442 threadRows,445 toPersistenceSqlOrDecodeError(
443 messageRows,446 "ProjectionSnapshotQuery.getSnapshot:listProjects:query",
444 proposedPlanRows,447 "ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows",
445 activityRows,
446 sessionRows,
447 checkpointRows,
448 latestTurnRows,
449 stateRows,
450 ] = yield* Effect.all([
451 listProjectRows(undefined).pipe(
452 Effect.mapError(
453 toPersistenceSqlOrDecodeError(
454 "ProjectionSnapshotQuery.getSnapshot:listProjects:query",
455 "ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows",
456 ),
457 ),
458 ),
459 listThreadRows(undefined).pipe(
460 Effect.mapError(
461 toPersistenceSqlOrDecodeError(
462 "ProjectionSnapshotQuery.getSnapshot:listThreads:query",
463 "ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows",
464 ),
465 ),448 ),
466 ),449 ),
467 listThreadMessageRows(undefined).pipe(450 ),
468 Effect.mapError(451 listThreadRows(undefined).pipe(
469 toPersistenceSqlOrDecodeError(452 Effect.mapError(
470 "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query",453 toPersistenceSqlOrDecodeError(
471 "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows",454 "ProjectionSnapshotQuery.getSnapshot:listThreads:query",
472 ),455 "ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows",
473 ),456 ),
474 ),457 ),
475 listThreadProposedPlanRows(undefined).pipe(458 ),
476 Effect.mapError(459 listThreadMessageRows(undefined).pipe(
477 toPersistenceSqlOrDecodeError(460 Effect.mapError(
478 "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query",461 toPersistenceSqlOrDecodeError(
479 "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows",462 "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query",
480 ),463 "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows",
481 ),464 ),
482 ),465 ),
483 listThreadActivityRows(undefined).pipe(466 ),
484 Effect.mapError(467 listThreadProposedPlanRows(undefined).pipe(
485 toPersistenceSqlOrDecodeError(468 Effect.mapError(
486 "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query",469 toPersistenceSqlOrDecodeError(
487 "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows",470 "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query",
488 ),471 "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows",
489 ),472 ),
490 ),473 ),
491 listThreadSessionRows(undefined).pipe(474 ),
492 Effect.mapError(475 listThreadActivityRows(undefined).pipe(
493 toPersistenceSqlOrDecodeError(476 Effect.mapError(
494 "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query",477 toPersistenceSqlOrDecodeError(
495 "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows",478 "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query",
496 ),479 "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows",
497 ),480 ),
498 ),481 ),
499 listCheckpointRows(undefined).pipe(482 ),
500 Effect.mapError(483 listThreadSessionRows(undefined).pipe(
501 toPersistenceSqlOrDecodeError(484 Effect.mapError(
502 "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query",485 toPersistenceSqlOrDecodeError(
503 "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows",486 "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query",
504 ),487 "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows",
505 ),488 ),
506 ),489 ),
507 listLatestTurnRows(undefined).pipe(490 ),
508 Effect.mapError(491 listCheckpointRows(undefined).pipe(
509 toPersistenceSqlOrDecodeError(492 Effect.mapError(
510 "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",493 toPersistenceSqlOrDecodeError(
511 "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",494 "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query",
512 ),495 "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows",
513 ),496 ),
514 ),497 ),
515 listProjectionStateRows(undefined).pipe(498 ),
516 Effect.mapError(499 listLatestTurnRows(undefined).pipe(
517 toPersistenceSqlOrDecodeError(500 Effect.mapError(
518 "ProjectionSnapshotQuery.getSnapshot:listProjectionState:query",501 toPersistenceSqlOrDecodeError(
519 "ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows",502 "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
520 ),503 "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
521 ),504 ),
522 ),505 ),
523 ]);506 ),
524 507 listProjectionStateRows(undefined).pipe(
525 const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
526 const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
527 const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
528 const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
529 const sessionsByThread = new Map<string, OrchestrationSession>();
530 const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
531
532 let updatedAt: string | null = null;
533
534 for (const row of projectRows) {
535 updatedAt = maxIso(updatedAt, row.updatedAt);
536 }
537 for (const row of threadRows) {
538 updatedAt = maxIso(updatedAt, row.updatedAt);
539 }
540 for (const row of stateRows) {
541 updatedAt = maxIso(updatedAt, row.updatedAt);
542 }
543
544 for (const row of messageRows) {
545 updatedAt = maxIso(updatedAt, row.updatedAt);
546 const threadMessages = messagesByThread.get(row.threadId) ?? [];
547 threadMessages.push({
548 id: row.messageId,
549 role: row.role,
550 text: row.text,
551 ...(row.attachments !== null ? { attachments: row.attachments } : {}),
552 turnId: row.turnId,
553 streaming: row.isStreaming === 1,
554 createdAt: row.createdAt,
555 updatedAt: row.updatedAt,
556 });
557 messagesByThread.set(row.threadId, threadMessages);
558 }
559
560 for (const row of proposedPlanRows) {
561 updatedAt = maxIso(updatedAt, row.updatedAt);
562 const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
563 threadProposedPlans.push({
564 id: row.planId,
565 turnId: row.turnId,
566 planMarkdown: row.planMarkdown,
567 implementedAt: row.implementedAt,
568 implementationThreadId: row.implementationThreadId,
569 createdAt: row.createdAt,
570 updatedAt: row.updatedAt,
571 });
572 proposedPlansByThread.set(row.threadId, threadProposedPlans);
573 }
574
575 for (const row of activityRows) {
576 updatedAt = maxIso(updatedAt, row.createdAt);
577 const threadActivities = activitiesByThread.get(row.threadId) ?? [];
578 threadActivities.push(
579 Schema.decodeUnknownSync(OrchestrationThreadActivity)({
580 id: row.activityId,
581 tone: row.tone,
582 kind: row.kind,
583 summary: row.summary,
584 payload: row.payload,
585 turnId: row.turnId,
586 ...(row.sequence !== null ? { sequence: row.sequence } : {}),
587 createdAt: row.createdAt,
588 }),
589 );
590 activitiesByThread.set(row.threadId, threadActivities);
591 }
592
593 for (const row of checkpointRows) {
594 updatedAt = maxIso(updatedAt, row.completedAt);
595 const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
596 threadCheckpoints.push({
597 turnId: row.turnId,
598 checkpointTurnCount: row.checkpointTurnCount,
599 checkpointRef: row.checkpointRef,
600 status: row.status,
601 files: row.files,
602 assistantMessageId: row.assistantMessageId,
603 completedAt: row.completedAt,
604 });
605 checkpointsByThread.set(row.threadId, threadCheckpoints);
606 }
607
608 for (const row of latestTurnRows) {
609 updatedAt = maxIso(updatedAt, row.requestedAt);
610 if (row.startedAt !== null) {
611 updatedAt = maxIso(updatedAt, row.startedAt);
612 }
613 if (row.completedAt !== null) {
614 updatedAt = maxIso(updatedAt, row.completedAt);
615 }
616 if (latestTurnByThread.has(row.threadId)) {
617 continue;
618 }
619 latestTurnByThread.set(row.threadId, {
620 turnId: row.turnId,
621 state:
622 row.state === "error"
623 ? "error"
624 : row.state === "interrupted"
625 ? "interrupted"
626 : row.state === "completed"
627 ? "completed"
628 : "running",
629 requestedAt: row.requestedAt,
630 startedAt: row.startedAt,
631 completedAt: row.completedAt,
632 assistantMessageId: row.assistantMessageId,
633 ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
634 ? {
635 sourceProposedPlan: {
636 threadId: row.sourceProposedPlanThreadId,
637 planId: row.sourceProposedPlanId,
638 },
639 }
640 : {}),
641 });
642 }
643
644 for (const row of sessionRows) {
645 updatedAt = maxIso(updatedAt, row.updatedAt);
646 sessionsByThread.set(row.threadId, {
647 threadId: row.threadId,
648 status: row.status,
649 providerName: row.providerName,
650 runtimeMode: row.runtimeMode,
651 activeTurnId: row.activeTurnId,
652 lastError: row.lastError,
653 updatedAt: row.updatedAt,
654 });
655 }
656
657 const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
658 id: row.projectId,
659 title: row.title,
660 workspaceRoot: row.workspaceRoot,
661 defaultModelSelection: row.defaultModelSelection,
662 scripts: row.scripts,
663 createdAt: row.createdAt,
664 updatedAt: row.updatedAt,
665 deletedAt: row.deletedAt,
666 }));
667
668 const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
669 id: row.threadId,
670 projectId: row.projectId,
671 title: row.title,
672 modelSelection: row.modelSelection,
673 runtimeMode: row.runtimeMode,
674 interactionMode: row.interactionMode,
675 branch: row.branch,
676 worktreePath: row.worktreePath,
677 latestTurn: latestTurnByThread.get(row.threadId) ?? null,
678 createdAt: row.createdAt,
679 updatedAt: row.updatedAt,
680 archivedAt: row.archivedAt,
681 deletedAt: row.deletedAt,
682 messages: messagesByThread.get(row.threadId) ?? [],
683 proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
684 activities: activitiesByThread.get(row.threadId) ?? [],
685 checkpoints: checkpointsByThread.get(row.threadId) ?? [],
686 session: sessionsByThread.get(row.threadId) ?? null,
687 }));
688
689 const snapshot = {
690 snapshotSequence: computeSnapshotSequence(stateRows),
691 projects,
692 threads,
693 updatedAt: updatedAt ?? new Date(0).toISOString(),
694 };
695
696 return yield* decodeReadModel(snapshot).pipe(
697 Effect.mapError(508 Effect.mapError(
698 toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),509 toPersistenceSqlOrDecodeError(
510 "ProjectionSnapshotQuery.getSnapshot:listProjectionState:query",
511 "ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows",
512 ),
699 ),513 ),
700 );514 ),
701 }),515 ]),
702 )516 )
703 .pipe(517 .pipe(
518 Effect.flatMap(
519 ([
520 projectRows,
521 threadRows,
522 messageRows,
523 proposedPlanRows,
524 activityRows,
525 sessionRows,
526 checkpointRows,
527 latestTurnRows,
528 stateRows,
529 ]) =>
530 Effect.gen(function* () {
531 const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
532 const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
533 const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
534 const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
535 const sessionsByThread = new Map<string, OrchestrationSession>();
536 const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
537
538 let updatedAt: string | null = null;
539
540 for (const row of projectRows) {
541 updatedAt = maxIso(updatedAt, row.updatedAt);
542 }
543 for (const row of threadRows) {
544 updatedAt = maxIso(updatedAt, row.updatedAt);
545 }
546 for (const row of stateRows) {
547 updatedAt = maxIso(updatedAt, row.updatedAt);
548 }
549
550 for (const row of messageRows) {
551 updatedAt = maxIso(updatedAt, row.updatedAt);
552 const threadMessages = messagesByThread.get(row.threadId) ?? [];
553 threadMessages.push({
554 id: row.messageId,
555 role: row.role,
556 text: row.text,
557 ...(row.attachments !== null ? { attachments: row.attachments } : {}),
558 turnId: row.turnId,
559 streaming: row.isStreaming === 1,
560 createdAt: row.createdAt,
561 updatedAt: row.updatedAt,
562 });
563 messagesByThread.set(row.threadId, threadMessages);
564 }
565
566 for (const row of proposedPlanRows) {
567 updatedAt = maxIso(updatedAt, row.updatedAt);
568 const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
569 threadProposedPlans.push({
570 id: row.planId,
571 turnId: row.turnId,
572 planMarkdown: row.planMarkdown,
573 implementedAt: row.implementedAt,
574 implementationThreadId: row.implementationThreadId,
575 createdAt: row.createdAt,
576 updatedAt: row.updatedAt,
577 });
578 proposedPlansByThread.set(row.threadId, threadProposedPlans);
579 }
580
581 for (const row of activityRows) {
582 updatedAt = maxIso(updatedAt, row.createdAt);
583 const threadActivities = activitiesByThread.get(row.threadId) ?? [];
584 threadActivities.push({
585 id: row.activityId,
586 tone: row.tone,
587 kind: row.kind,
588 summary: row.summary,
589 payload: row.payload,
590 turnId: row.turnId,
591 ...(row.sequence !== null ? { sequence: row.sequence } : {}),
592 createdAt: row.createdAt,
593 } as OrchestrationThreadActivity);
594 activitiesByThread.set(row.threadId, threadActivities);
595 }
596
597 for (const row of checkpointRows) {
598 updatedAt = maxIso(updatedAt, row.completedAt);
599 const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
600 threadCheckpoints.push({
601 turnId: row.turnId,
602 checkpointTurnCount: row.checkpointTurnCount,
603 checkpointRef: row.checkpointRef,
604 status: row.status,
605 files: row.files,
606 assistantMessageId: row.assistantMessageId,
607 completedAt: row.completedAt,
608 });
609 checkpointsByThread.set(row.threadId, threadCheckpoints);
610 }
611
612 for (const row of latestTurnRows) {
613 updatedAt = maxIso(updatedAt, row.requestedAt);
614 if (row.startedAt !== null) {
615 updatedAt = maxIso(updatedAt, row.startedAt);
616 }
617 if (row.completedAt !== null) {
618 updatedAt = maxIso(updatedAt, row.completedAt);
619 }
620 if (latestTurnByThread.has(row.threadId)) {
621 continue;
622 }
623 latestTurnByThread.set(row.threadId, {
624 turnId: row.turnId,
625 state:
626 row.state === "error"
627 ? "error"
628 : row.state === "interrupted"
629 ? "interrupted"
630 : row.state === "completed"
631 ? "completed"
632 : "running",
633 requestedAt: row.requestedAt,
634 startedAt: row.startedAt,
635 completedAt: row.completedAt,
636 assistantMessageId: row.assistantMessageId,
637 ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null
638 ? {
639 sourceProposedPlan: {
640 threadId: row.sourceProposedPlanThreadId,
641 planId: row.sourceProposedPlanId,
642 },
643 }
644 : {}),
645 });
646 }
647
648 for (const row of sessionRows) {
649 updatedAt = maxIso(updatedAt, row.updatedAt);
650 sessionsByThread.set(row.threadId, {
651 threadId: row.threadId,
652 status: row.status,
653 providerName: row.providerName,
654 runtimeMode: row.runtimeMode,
655 activeTurnId: row.activeTurnId,
656 lastError: row.lastError,
657 updatedAt: row.updatedAt,
658 });
659 }
660
661 const repositoryIdentities = new Map(
662 yield* Effect.forEach(
663 projectRows,
664 (row) =>
665 repositoryIdentityResolver
666 .resolve(row.workspaceRoot)
667 .pipe(Effect.map((identity) => [row.projectId, identity] as const)),
668 { concurrency: repositoryIdentityResolutionConcurrency },
669 ),
670 );
671
672 const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
673 id: row.projectId,
674 title: row.title,
675 workspaceRoot: row.workspaceRoot,
676 repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,
677 defaultModelSelection: row.defaultModelSelection,
678 scripts: row.scripts,
679 createdAt: row.createdAt,
680 updatedAt: row.updatedAt,
681 deletedAt: row.deletedAt,
682 }));
683
684 const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
685 id: row.threadId,
686 projectId: row.projectId,
687 title: row.title,
688 modelSelection: row.modelSelection,
689 runtimeMode: row.runtimeMode,
690 interactionMode: row.interactionMode,
691 branch: row.branch,
692 worktreePath: row.worktreePath,
693 latestTurn: latestTurnByThread.get(row.threadId) ?? null,
694 createdAt: row.createdAt,
695 updatedAt: row.updatedAt,
696 archivedAt: row.archivedAt,
697 deletedAt: row.deletedAt,
698 messages: messagesByThread.get(row.threadId) ?? [],
699 proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
700 activities: activitiesByThread.get(row.threadId) ?? [],
701 checkpoints: checkpointsByThread.get(row.threadId) ?? [],
702 session: sessionsByThread.get(row.threadId) ?? null,
703 }));
704
705 const snapshot = {
706 snapshotSequence: computeSnapshotSequence(stateRows),
707 projects,
708 threads,
709 updatedAt: updatedAt ?? new Date(0).toISOString(),
710 };
711
712 return yield* decodeReadModel(snapshot).pipe(
713 Effect.mapError(
714 toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),
715 ),
716 );
717 }),
718 ),
704 Effect.mapError((error) => {719 Effect.mapError((error) => {
705 if (isPersistenceError(error)) {720 if (isPersistenceError(error)) {
706 return error;721 return error;
@@ -734,19 +749,24 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { · 27 unmodified lines
734 "ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow",749 "ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow",
735 ),750 ),
736 ),751 ),
737 Effect.map(752 Effect.flatMap((option) =>
738 Option.map(753 Option.isNone(option)
739 (row): OrchestrationProject => ({754 ? Effect.succeed(Option.none<OrchestrationProject>())
740 id: row.projectId,755 : repositoryIdentityResolver.resolve(option.value.workspaceRoot).pipe(
741 title: row.title,756 Effect.map((repositoryIdentity) =>
742 workspaceRoot: row.workspaceRoot,757 Option.some({
743 defaultModelSelection: row.defaultModelSelection,758 id: option.value.projectId,
744 scripts: row.scripts,759 title: option.value.title,
745 createdAt: row.createdAt,760 workspaceRoot: option.value.workspaceRoot,
746 updatedAt: row.updatedAt,761 repositoryIdentity,
747 deletedAt: row.deletedAt,762 defaultModelSelection: option.value.defaultModelSelection,
748 }),763 scripts: option.value.scripts,
749 ),764 createdAt: option.value.createdAt,
765 updatedAt: option.value.updatedAt,
766 deletedAt: option.value.deletedAt,
767 } satisfies OrchestrationProject),
768 ),
769 ),
750 ),770 ),
751 );771 );
752 772
apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts+143−152
@@ -28,6 +28,7 @@ import { · 27 unmodified lines
28} from "../../provider/Services/ProviderService.ts";28} from "../../provider/Services/ProviderService.ts";
29import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";29import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
30import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";30import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
31import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
31import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";32import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
32import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";33import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
33import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";34import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
@@ -37,11 +38,10 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; · 3 unmodified lines
37import * as NodeServices from "@effect/platform-node/NodeServices";38import * as NodeServices from "@effect/platform-node/NodeServices";
38import { ServerSettingsService } from "../../serverSettings.ts";39import { ServerSettingsService } from "../../serverSettings.ts";
39 40
40const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);41const asProjectId = (value: string): ProjectId => ProjectId.make(value);
41const asApprovalRequestId = (value: string): ApprovalRequestId =>42const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
42 ApprovalRequestId.makeUnsafe(value);43const asMessageId = (value: string): MessageId => MessageId.make(value);
43const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);44const asTurnId = (value: string): TurnId => TurnId.make(value);
44const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
45 45
46const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>46const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
47 Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));47 Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
@@ -121,8 +121,8 @@ describe("ProviderCommandReactor", () => { · 73 unmodified lines
121 input !== null &&121 input !== null &&
122 "threadId" in input &&122 "threadId" in input &&
123 typeof input.threadId === "string"123 typeof input.threadId === "string"
124 ? ThreadId.makeUnsafe(input.threadId)124 ? ThreadId.make(input.threadId)
125 : ThreadId.makeUnsafe(`thread-${sessionIndex}`);125 : ThreadId.make(`thread-${sessionIndex}`);
126 const session: ProviderSession = {126 const session: ProviderSession = {
127 provider: modelSelection.provider,127 provider: modelSelection.provider,
128 status: "ready" as const,128 status: "ready" as const,
@@ -144,7 +144,7 @@ describe("ProviderCommandReactor", () => { · 15 unmodified lines
144 });144 });
145 const sendTurn = vi.fn((_: unknown) =>145 const sendTurn = vi.fn((_: unknown) =>
146 Effect.succeed({146 Effect.succeed({
147 threadId: ThreadId.makeUnsafe("thread-1"),147 threadId: ThreadId.make("thread-1"),
148 turnId: asTurnId("turn-1"),148 turnId: asTurnId("turn-1"),
149 }),149 }),
150 );150 );
@@ -208,7 +208,9 @@ describe("ProviderCommandReactor", () => { · 57 unmodified lines
208 sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",208 sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
209 }),209 }),
210 rollbackConversation: () => unsupported(),210 rollbackConversation: () => unsupported(),
211 streamEvents: Stream.fromPubSub(runtimeEventPubSub),211 get streamEvents() {
212 return Stream.fromPubSub(runtimeEventPubSub);
213 },
212 };214 };
213 215
214 const orchestrationLayer = OrchestrationEngineLive.pipe(216 const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -216,6 +218,7 @@ describe("ProviderCommandReactor", () => { · 1 unmodified line
216 Layer.provide(OrchestrationProjectionPipelineLive),218 Layer.provide(OrchestrationProjectionPipelineLive),
217 Layer.provide(OrchestrationEventStoreLive),219 Layer.provide(OrchestrationEventStoreLive),
218 Layer.provide(OrchestrationCommandReceiptRepositoryLive),220 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
221 Layer.provide(RepositoryIdentityResolverLive),
219 Layer.provide(SqlitePersistenceMemory),222 Layer.provide(SqlitePersistenceMemory),
220 );223 );
221 const layer = ProviderCommandReactorLive.pipe(224 const layer = ProviderCommandReactorLive.pipe(
@@ -243,7 +246,7 @@ describe("ProviderCommandReactor", () => { · 21 unmodified lines
243 await Effect.runPromise(246 await Effect.runPromise(
244 engine.dispatch({247 engine.dispatch({
245 type: "project.create",248 type: "project.create",
246 commandId: CommandId.makeUnsafe("cmd-project-create"),249 commandId: CommandId.make("cmd-project-create"),
247 projectId: asProjectId("project-1"),250 projectId: asProjectId("project-1"),
248 title: "Provider Project",251 title: "Provider Project",
249 workspaceRoot: "/tmp/provider-project",252 workspaceRoot: "/tmp/provider-project",
@@ -254,8 +257,8 @@ describe("ProviderCommandReactor", () => { · 4 unmodified lines
254 await Effect.runPromise(257 await Effect.runPromise(
255 engine.dispatch({258 engine.dispatch({
256 type: "thread.create",259 type: "thread.create",
257 commandId: CommandId.makeUnsafe("cmd-thread-create"),260 commandId: CommandId.make("cmd-thread-create"),
258 threadId: ThreadId.makeUnsafe("thread-1"),261 threadId: ThreadId.make("thread-1"),
259 projectId: asProjectId("project-1"),262 projectId: asProjectId("project-1"),
260 title: "Thread",263 title: "Thread",
261 modelSelection: modelSelection,264 modelSelection: modelSelection,
@@ -290,8 +293,8 @@ describe("ProviderCommandReactor", () => { · 28 unmodified lines
290 await Effect.runPromise(293 await Effect.runPromise(
291 harness.engine.dispatch({294 harness.engine.dispatch({
292 type: "thread.turn.start",295 type: "thread.turn.start",
293 commandId: CommandId.makeUnsafe("cmd-turn-start-1"),296 commandId: CommandId.make("cmd-turn-start-1"),
294 threadId: ThreadId.makeUnsafe("thread-1"),297 threadId: ThreadId.make("thread-1"),
295 message: {298 message: {
296 messageId: asMessageId("user-message-1"),299 messageId: asMessageId("user-message-1"),
297 role: "user",300 role: "user",
@@ -306,7 +309,7 @@ describe("ProviderCommandReactor", () => { · 8 unmodified lines
306 309
307 await waitFor(() => harness.startSession.mock.calls.length === 1);310 await waitFor(() => harness.startSession.mock.calls.length === 1);
308 await waitFor(() => harness.sendTurn.mock.calls.length === 1);311 await waitFor(() => harness.sendTurn.mock.calls.length === 1);
309 expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));312 expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.make("thread-1"));
310 expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({313 expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
311 cwd: "/tmp/provider-project",314 cwd: "/tmp/provider-project",
312 modelSelection: {315 modelSelection: {
@@ -317,7 +320,7 @@ describe("ProviderCommandReactor", () => { · 4 unmodified lines
317 });320 });
318 321
319 const readModel = await Effect.runPromise(harness.engine.getReadModel());322 const readModel = await Effect.runPromise(harness.engine.getReadModel());
320 const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));323 const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
321 expect(thread?.session?.threadId).toBe("thread-1");324 expect(thread?.session?.threadId).toBe("thread-1");
322 expect(thread?.session?.runtimeMode).toBe("approval-required");325 expect(thread?.session?.runtimeMode).toBe("approval-required");
323 });326 });
@@ -331,8 +334,8 @@ describe("ProviderCommandReactor", () => { · 7 unmodified lines
331 await Effect.runPromise(334 await Effect.runPromise(
332 harness.engine.dispatch({335 harness.engine.dispatch({
333 type: "thread.meta.update",336 type: "thread.meta.update",
334 commandId: CommandId.makeUnsafe("cmd-thread-title-seed"),337 commandId: CommandId.make("cmd-thread-title-seed"),
335 threadId: ThreadId.makeUnsafe("thread-1"),338 threadId: ThreadId.make("thread-1"),
336 title: seededTitle,339 title: seededTitle,
337 }),340 }),
338 );341 );
@@ -340,8 +343,8 @@ describe("ProviderCommandReactor", () => { · 1 unmodified line
340 await Effect.runPromise(343 await Effect.runPromise(
341 harness.engine.dispatch({344 harness.engine.dispatch({
342 type: "thread.turn.start",345 type: "thread.turn.start",
343 commandId: CommandId.makeUnsafe("cmd-turn-start-title"),346 commandId: CommandId.make("cmd-turn-start-title"),
344 threadId: ThreadId.makeUnsafe("thread-1"),347 threadId: ThreadId.make("thread-1"),
345 message: {348 message: {
346 messageId: asMessageId("user-message-title"),349 messageId: asMessageId("user-message-title"),
347 role: "user",350 role: "user",
@@ -363,12 +366,12 @@ describe("ProviderCommandReactor", () => { · 15 unmodified lines
363 await waitFor(async () => {366 await waitFor(async () => {
364 const readModel = await Effect.runPromise(harness.engine.getReadModel());367 const readModel = await Effect.runPromise(harness.engine.getReadModel());
365 return (368 return (
366 readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===369 readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
367 "Generated title"370 "Generated title"
368 );371 );
369 });372 });
370 const readModel = await Effect.runPromise(harness.engine.getReadModel());373 const readModel = await Effect.runPromise(harness.engine.getReadModel());
371 const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));374 const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
372 expect(thread?.title).toBe("Generated title");375 expect(thread?.title).toBe("Generated title");
373 });376 });
374 377
@@ -380,8 +383,8 @@ describe("ProviderCommandReactor", () => { · 5 unmodified lines
380 await Effect.runPromise(383 await Effect.runPromise(
381 harness.engine.dispatch({384 harness.engine.dispatch({
382 type: "thread.meta.update",385 type: "thread.meta.update",
383 commandId: CommandId.makeUnsafe("cmd-thread-title-custom"),386 commandId: CommandId.make("cmd-thread-title-custom"),
384 threadId: ThreadId.makeUnsafe("thread-1"),387 threadId: ThreadId.make("thread-1"),
385 title: "Keep this custom title",388 title: "Keep this custom title",
386 }),389 }),
387 );390 );
@@ -389,8 +392,8 @@ describe("ProviderCommandReactor", () => { · 1 unmodified line
389 await Effect.runPromise(392 await Effect.runPromise(
390 harness.engine.dispatch({393 harness.engine.dispatch({
391 type: "thread.turn.start",394 type: "thread.turn.start",
392 commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"),395 commandId: CommandId.make("cmd-turn-start-title-preserve"),
393 threadId: ThreadId.makeUnsafe("thread-1"),396 threadId: ThreadId.make("thread-1"),
394 message: {397 message: {
395 messageId: asMessageId("user-message-title-preserve"),398 messageId: asMessageId("user-message-title-preserve"),
396 role: "user",399 role: "user",
@@ -408,7 +411,7 @@ describe("ProviderCommandReactor", () => { · 11 unmodified lines
408 expect(harness.generateThreadTitle).not.toHaveBeenCalled();411 expect(harness.generateThreadTitle).not.toHaveBeenCalled();
409 412
410 const readModel = await Effect.runPromise(harness.engine.getReadModel());413 const readModel = await Effect.runPromise(harness.engine.getReadModel());
411 const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));414 const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
412 expect(thread?.title).toBe("Keep this custom title");415 expect(thread?.title).toBe("Keep this custom title");
413 });416 });
414 417
@@ -425,8 +428,8 @@ describe("ProviderCommandReactor", () => { · 10 unmodified lines
425 await Effect.runPromise(428 await Effect.runPromise(
426 harness.engine.dispatch({429 harness.engine.dispatch({
427 type: "thread.meta.update",430 type: "thread.meta.update",
428 commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"),431 commandId: CommandId.make("cmd-thread-title-formatted-seed"),
429 threadId: ThreadId.makeUnsafe("thread-1"),432 threadId: ThreadId.make("thread-1"),
430 title: seededTitle,433 title: seededTitle,
431 }),434 }),
432 );435 );
@@ -434,8 +437,8 @@ describe("ProviderCommandReactor", () => { · 1 unmodified line
434 await Effect.runPromise(437 await Effect.runPromise(
435 harness.engine.dispatch({438 harness.engine.dispatch({
436 type: "thread.turn.start",439 type: "thread.turn.start",
437 commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"),440 commandId: CommandId.make("cmd-turn-start-title-formatted"),
438 threadId: ThreadId.makeUnsafe("thread-1"),441 threadId: ThreadId.make("thread-1"),
439 message: {442 message: {
440 messageId: asMessageId("user-message-title-formatted"),443 messageId: asMessageId("user-message-title-formatted"),
441 role: "user",444 role: "user",
@@ -453,13 +456,13 @@ describe("ProviderCommandReactor", () => { · 11 unmodified lines
453 await waitFor(async () => {456 await waitFor(async () => {
454 const readModel = await Effect.runPromise(harness.engine.getReadModel());457 const readModel = await Effect.runPromise(harness.engine.getReadModel());
455 return (458 return (
456 readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===459 readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
457 "Reconnect spinner resume bug"460 "Reconnect spinner resume bug"
458 );461 );
459 });462 });
460 463
461 const readModel = await Effect.runPromise(harness.engine.getReadModel());464 const readModel = await Effect.runPromise(harness.engine.getReadModel());
462 const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));465 const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
463 expect(thread?.title).toBe("Reconnect spinner resume bug");466 expect(thread?.title).toBe("Reconnect spinner resume bug");
464 });467 });
465 468
@@ -470,8 +473,8 @@ describe("ProviderCommandReactor", () => { · 4 unmodified lines
470 await Effect.runPromise(473 await Effect.runPromise(
471 harness.engine.dispatch({474 harness.engine.dispatch({
472 type: "thread.meta.update",475 type: "thread.meta.update",
473 commandId: CommandId.makeUnsafe("cmd-thread-branch"),476 commandId: CommandId.make("cmd-thread-branch"),
474 threadId: ThreadId.makeUnsafe("thread-1"),477 threadId: ThreadId.make("thread-1"),
475 branch: "t3code/1234abcd",478 branch: "t3code/1234abcd",
476 worktreePath: "/tmp/provider-project-worktree",479 worktreePath: "/tmp/provider-project-worktree",
477 }),480 }),
@@ -495,8 +498,8 @@ describe("ProviderCommandReactor", () => { · 17 unmodified lines
495 await Effect.runPromise(498 await Effect.runPromise(
496 harness.engine.dispatch({499 harness.engine.dispatch({
497 type: "thread.turn.start",500 type: "thread.turn.start",
498 commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"),501 commandId: CommandId.make("cmd-turn-start-branch-model"),
499 threadId: ThreadId.makeUnsafe("thread-1"),502 threadId: ThreadId.make("thread-1"),
500 message: {503 message: {
501 messageId: asMessageId("user-message-branch-model"),504 messageId: asMessageId("user-message-branch-model"),
502 role: "user",505 role: "user",
@@ -522,8 +525,8 @@ describe("ProviderCommandReactor", () => { · 19 unmodified lines
522 await Effect.runPromise(525 await Effect.runPromise(
523 harness.engine.dispatch({526 harness.engine.dispatch({
524 type: "thread.turn.start",527 type: "thread.turn.start",
525 commandId: CommandId.makeUnsafe("cmd-turn-start-fast"),528 commandId: CommandId.make("cmd-turn-start-fast"),
526 threadId: ThreadId.makeUnsafe("thread-1"),529 threadId: ThreadId.make("thread-1"),
527 message: {530 message: {
528 messageId: asMessageId("user-message-fast"),531 messageId: asMessageId("user-message-fast"),
529 role: "user",532 role: "user",
@@ -557,7 +560,7 @@ describe("ProviderCommandReactor", () => { · 27 unmodified lines
557 },560 },
558 });561 });
559 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({562 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
560 threadId: ThreadId.makeUnsafe("thread-1"),563 threadId: ThreadId.make("thread-1"),
561 modelSelection: {564 modelSelection: {
562 provider: "codex",565 provider: "codex",
563 model: "gpt-5.3-codex",566 model: "gpt-5.3-codex",
@@ -578,8 +581,8 @@ describe("ProviderCommandReactor", () => { · 14 unmodified lines
578 await Effect.runPromise(581 await Effect.runPromise(
579 harness.engine.dispatch({582 harness.engine.dispatch({
580 type: "thread.turn.start",583 type: "thread.turn.start",
581 commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),584 commandId: CommandId.make("cmd-turn-start-claude-effort"),
582 threadId: ThreadId.makeUnsafe("thread-1"),585 threadId: ThreadId.make("thread-1"),
583 message: {586 message: {
584 messageId: asMessageId("user-message-claude-effort"),587 messageId: asMessageId("user-message-claude-effort"),
585 role: "user",588 role: "user",
@@ -611,7 +614,7 @@ describe("ProviderCommandReactor", () => { · 25 unmodified lines
611 },614 },
612 });615 });
613 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({616 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
614 threadId: ThreadId.makeUnsafe("thread-1"),617 threadId: ThreadId.make("thread-1"),
615 modelSelection: {618 modelSelection: {
616 provider: "claudeAgent",619 provider: "claudeAgent",
617 model: "claude-sonnet-4-6",620 model: "claude-sonnet-4-6",
@@ -631,8 +634,8 @@ describe("ProviderCommandReactor", () => { · 13 unmodified lines
631 await Effect.runPromise(634 await Effect.runPromise(
632 harness.engine.dispatch({635 harness.engine.dispatch({
633 type: "thread.turn.start",636 type: "thread.turn.start",
634 commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),637 commandId: CommandId.make("cmd-turn-start-claude-fast-mode"),
635 threadId: ThreadId.makeUnsafe("thread-1"),638 threadId: ThreadId.make("thread-1"),
636 message: {639 message: {
637 messageId: asMessageId("user-message-claude-fast-mode"),640 messageId: asMessageId("user-message-claude-fast-mode"),
638 role: "user",641 role: "user",
@@ -664,7 +667,7 @@ describe("ProviderCommandReactor", () => { · 25 unmodified lines
664 },667 },
665 });668 });
666 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({669 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
667 threadId: ThreadId.makeUnsafe("thread-1"),670 threadId: ThreadId.make("thread-1"),
668 modelSelection: {671 modelSelection: {
669 provider: "claudeAgent",672 provider: "claudeAgent",
670 model: "claude-opus-4-6",673 model: "claude-opus-4-6",
@@ -682,8 +685,8 @@ describe("ProviderCommandReactor", () => { · 11 unmodified lines
682 await Effect.runPromise(685 await Effect.runPromise(
683 harness.engine.dispatch({686 harness.engine.dispatch({
684 type: "thread.interaction-mode.set",687 type: "thread.interaction-mode.set",
685 commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"),688 commandId: CommandId.make("cmd-interaction-mode-set-plan"),
686 threadId: ThreadId.makeUnsafe("thread-1"),689 threadId: ThreadId.make("thread-1"),
687 interactionMode: "plan",690 interactionMode: "plan",
688 createdAt: now,691 createdAt: now,
689 }),692 }),
@@ -692,8 +695,8 @@ describe("ProviderCommandReactor", () => { · 2 unmodified lines
692 await Effect.runPromise(695 await Effect.runPromise(
693 harness.engine.dispatch({696 harness.engine.dispatch({
694 type: "thread.turn.start",697 type: "thread.turn.start",
695 commandId: CommandId.makeUnsafe("cmd-turn-start-plan"),698 commandId: CommandId.make("cmd-turn-start-plan"),
696 threadId: ThreadId.makeUnsafe("thread-1"),699 threadId: ThreadId.make("thread-1"),
697 message: {700 message: {
698 messageId: asMessageId("user-message-plan"),701 messageId: asMessageId("user-message-plan"),
699 role: "user",702 role: "user",
@@ -708,7 +711,7 @@ describe("ProviderCommandReactor", () => { · 8 unmodified lines
708 711
709 await waitFor(() => harness.sendTurn.mock.calls.length === 1);712 await waitFor(() => harness.sendTurn.mock.calls.length === 1);
710 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({713 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
711 threadId: ThreadId.makeUnsafe("thread-1"),714 threadId: ThreadId.make("thread-1"),
712 interactionMode: "plan",715 interactionMode: "plan",
713 });716 });
714 });717 });
@@ -722,8 +725,8 @@ describe("ProviderCommandReactor", () => { · 7 unmodified lines
722 await Effect.runPromise(725 await Effect.runPromise(
723 harness.engine.dispatch({726 harness.engine.dispatch({
724 type: "thread.turn.start",727 type: "thread.turn.start",
725 commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),728 commandId: CommandId.make("cmd-turn-start-provider-first"),
726 threadId: ThreadId.makeUnsafe("thread-1"),729 threadId: ThreadId.make("thread-1"),
727 message: {730 message: {
728 messageId: asMessageId("user-message-provider-first"),731 messageId: asMessageId("user-message-provider-first"),
729 role: "user",732 role: "user",
@@ -742,9 +745,7 @@ describe("ProviderCommandReactor", () => { · 12 unmodified lines
742 745
743 await waitFor(async () => {746 await waitFor(async () => {
744 const readModel = await Effect.runPromise(harness.engine.getReadModel());747 const readModel = await Effect.runPromise(harness.engine.getReadModel());
745 const thread = readModel.threads.find(748 const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
746 (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
747 );
748 return (749 return (
749 thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??750 thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
750 false751 false
@@ -755,7 +756,7 @@ describe("ProviderCommandReactor", () => { · 4 unmodified lines
755 expect(harness.sendTurn).not.toHaveBeenCalled();756 expect(harness.sendTurn).not.toHaveBeenCalled();
756 757
757 const readModel = await Effect.runPromise(harness.engine.getReadModel());758 const readModel = await Effect.runPromise(harness.engine.getReadModel());
758 const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));759 const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
759 expect(thread?.session).toBeNull();760 expect(thread?.session).toBeNull();
760 expect(761 expect(
761 thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),762 thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
@@ -774,8 +775,8 @@ describe("ProviderCommandReactor", () => { · 12 unmodified lines
774 await Effect.runPromise(775 await Effect.runPromise(
775 harness.engine.dispatch({776 harness.engine.dispatch({
776 type: "thread.turn.start",777 type: "thread.turn.start",
777 commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),778 commandId: CommandId.make("cmd-turn-start-unsupported-1"),
778 threadId: ThreadId.makeUnsafe("thread-1"),779 threadId: ThreadId.make("thread-1"),
779 message: {780 message: {
780 messageId: asMessageId("user-message-unsupported-1"),781 messageId: asMessageId("user-message-unsupported-1"),
781 role: "user",782 role: "user",
@@ -793,8 +794,8 @@ describe("ProviderCommandReactor", () => { · 11 unmodified lines
793 await Effect.runPromise(794 await Effect.runPromise(
794 harness.engine.dispatch({795 harness.engine.dispatch({
795 type: "thread.turn.start",796 type: "thread.turn.start",
796 commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),797 commandId: CommandId.make("cmd-turn-start-unsupported-2"),
797 threadId: ThreadId.makeUnsafe("thread-1"),798 threadId: ThreadId.make("thread-1"),
798 message: {799 message: {
799 messageId: asMessageId("user-message-unsupported-2"),800 messageId: asMessageId("user-message-unsupported-2"),
800 role: "user",801 role: "user",
@@ -810,7 +811,7 @@ describe("ProviderCommandReactor", () => { · 9 unmodified lines
810 await waitFor(() => harness.sendTurn.mock.calls.length === 2);811 await waitFor(() => harness.sendTurn.mock.calls.length === 2);
811 812
812 expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({813 expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
813 threadId: ThreadId.makeUnsafe("thread-1"),814 threadId: ThreadId.make("thread-1"),
814 modelSelection: {815 modelSelection: {
815 provider: "codex",816 provider: "codex",
816 model: "gpt-5-codex",817 model: "gpt-5-codex",
@@ -825,8 +826,8 @@ describe("ProviderCommandReactor", () => { · 8 unmodified lines
825 await Effect.runPromise(826 await Effect.runPromise(
826 harness.engine.dispatch({827 harness.engine.dispatch({
827 type: "thread.turn.start",828 type: "thread.turn.start",
828 commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),829 commandId: CommandId.make("cmd-turn-start-unchanged-1"),
829 threadId: ThreadId.makeUnsafe("thread-1"),830 threadId: ThreadId.make("thread-1"),
830 message: {831 message: {
831 messageId: asMessageId("user-message-unchanged-1"),832 messageId: asMessageId("user-message-unchanged-1"),
832 role: "user",833 role: "user",
@@ -845,8 +846,8 @@ describe("ProviderCommandReactor", () => { · 12 unmodified lines
845 await Effect.runPromise(846 await Effect.runPromise(
846 harness.engine.dispatch({847 harness.engine.dispatch({
847 type: "thread.turn.start",848 type: "thread.turn.start",
848 commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),849 commandId: CommandId.make("cmd-turn-start-unchanged-2"),
849 threadId: ThreadId.makeUnsafe("thread-1"),850 threadId: ThreadId.make("thread-1"),
850 message: {851 message: {
851 messageId: asMessageId("user-message-unchanged-2"),852 messageId: asMessageId("user-message-unchanged-2"),
852 role: "user",853 role: "user",
@@ -873,8 +874,8 @@ describe("ProviderCommandReactor", () => { · 20 unmodified lines
873 await Effect.runPromise(874 await Effect.runPromise(
874 harness.engine.dispatch({875 harness.engine.dispatch({
875 type: "thread.turn.start",876 type: "thread.turn.start",
876 commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),877 commandId: CommandId.make("cmd-turn-start-claude-effort-1"),
877 threadId: ThreadId.makeUnsafe("thread-1"),878 threadId: ThreadId.make("thread-1"),
878 message: {879 message: {
879 messageId: asMessageId("user-message-claude-effort-1"),880 messageId: asMessageId("user-message-claude-effort-1"),
880 role: "user",881 role: "user",
@@ -900,8 +901,8 @@ describe("ProviderCommandReactor", () => { · 19 unmodified lines
900 await Effect.runPromise(901 await Effect.runPromise(
901 harness.engine.dispatch({902 harness.engine.dispatch({
902 type: "thread.turn.start",903 type: "thread.turn.start",
903 commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),904 commandId: CommandId.make("cmd-turn-start-claude-effort-2"),
904 threadId: ThreadId.makeUnsafe("thread-1"),905 threadId: ThreadId.make("thread-1"),
905 message: {906 message: {
906 messageId: asMessageId("user-message-claude-effort-2"),907 messageId: asMessageId("user-message-claude-effort-2"),
907 role: "user",908 role: "user",
@@ -942,8 +943,8 @@ describe("ProviderCommandReactor", () => { · 34 unmodified lines
942 await Effect.runPromise(943 await Effect.runPromise(
943 harness.engine.dispatch({944 harness.engine.dispatch({
944 type: "thread.runtime-mode.set",945 type: "thread.runtime-mode.set",
945 commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access"),946 commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access"),
946 threadId: ThreadId.makeUnsafe("thread-1"),947 threadId: ThreadId.make("thread-1"),
947 runtimeMode: "full-access",948 runtimeMode: "full-access",
948 createdAt: now,949 createdAt: now,
949 }),950 }),
@@ -952,8 +953,8 @@ describe("ProviderCommandReactor", () => { · 2 unmodified lines
952 await Effect.runPromise(953 await Effect.runPromise(
953 harness.engine.dispatch({954 harness.engine.dispatch({
954 type: "thread.turn.start",955 type: "thread.turn.start",
955 commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),956 commandId: CommandId.make("cmd-turn-start-runtime-mode-1"),
956 threadId: ThreadId.makeUnsafe("thread-1"),957 threadId: ThreadId.make("thread-1"),
957 message: {958 message: {
958 messageId: asMessageId("user-message-runtime-mode-1"),959 messageId: asMessageId("user-message-runtime-mode-1"),
959 role: "user",960 role: "user",
@@ -972,8 +973,8 @@ describe("ProviderCommandReactor", () => { · 12 unmodified lines
972 await Effect.runPromise(973 await Effect.runPromise(
973 harness.engine.dispatch({974 harness.engine.dispatch({
974 type: "thread.runtime-mode.set",975 type: "thread.runtime-mode.set",
975 commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-1"),976 commandId: CommandId.make("cmd-runtime-mode-set-1"),
976 threadId: ThreadId.makeUnsafe("thread-1"),977 threadId: ThreadId.make("thread-1"),
977 runtimeMode: "approval-required",978 runtimeMode: "approval-required",
978 createdAt: now,979 createdAt: now,
979 }),980 }),

387 more lines aren’t shown here.

apps/server/src/orchestration/Layers/ProviderCommandReactor.ts+105−90

This diff is large: its 282 lines aren’t shown here.

apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts+45−49

This diff is large: its 320 lines aren’t shown here.

apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts+51−50

This diff is large: its 175 lines aren’t shown here.

apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts+20−2

This diff is large: its 38 lines aren’t shown here.

apps/server/src/orchestration/Services/CheckpointReactor.ts+4−5

This diff is large: its 20 lines aren’t shown here.

apps/server/src/orchestration/Services/OrchestrationEngine.ts+3−3

This diff is large: its 27 lines aren’t shown here.

apps/server/src/orchestration/Services/OrchestrationReactor.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/orchestration/Services/ProjectionPipeline.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/orchestration/Services/ProviderCommandReactor.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/orchestration/Services/RuntimeReceiptBus.ts+21−6

This diff is large: its 38 lines aren’t shown here.

apps/server/src/orchestration/commandInvariants.test.ts+24−26

This diff is large: its 137 lines aren’t shown here.

apps/server/src/orchestration/decider.projectScripts.test.ts+34−34

This diff is large: its 199 lines aren’t shown here.

apps/server/src/orchestration/http.ts+93−0

This diff is large: its 94 lines aren’t shown here.

apps/server/src/orchestration/projector.test.ts+4−4

This diff is large: its 20 lines aren’t shown here.

apps/server/src/orchestration/runtimeLayer.ts+27−0

This diff is large: its 28 lines aren’t shown here.

apps/server/src/persistence/Errors.ts+2−0

This diff is large: its 8 lines aren’t shown here.

apps/server/src/persistence/Layers/AuthPairingLinks.ts+209−0

This diff is large: its 210 lines aren’t shown here.

apps/server/src/persistence/Layers/AuthSessions.ts+279−0

This diff is large: its 280 lines aren’t shown here.

apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts+8−8

This diff is large: its 41 lines aren’t shown here.

apps/server/src/persistence/Layers/ProjectionRepositories.test.ts+5−5

This diff is large: its 38 lines aren’t shown here.

apps/server/src/persistence/Layers/ProjectionThreadMessages.test.ts+4−4

This diff is large: its 22 lines aren’t shown here.

apps/server/src/persistence/Layers/Sqlite.ts+11−1

This diff is large: its 26 lines aren’t shown here.

apps/server/src/persistence/Migrations.ts+6−0

This diff is large: its 20 lines aren’t shown here.

apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts+42−0

This diff is large: its 43 lines aren’t shown here.

apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts+62−0

This diff is large: its 63 lines aren’t shown here.

apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts+17−0

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/NodeSqliteClient.ts+10−10

This diff is large: its 70 lines aren’t shown here.

apps/server/src/persistence/Services/AuthPairingLinks.ts+76−0

This diff is large: its 77 lines aren’t shown here.

apps/server/src/persistence/Services/AuthSessions.ts+93−0

This diff is large: its 94 lines aren’t shown here.

apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/OrchestrationEventStore.ts+3−3

This diff is large: its 25 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionCheckpoints.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionPendingApprovals.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionProjects.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionState.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionThreadActivities.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionThreadMessages.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionThreadProposedPlans.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionThreadSessions.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionThreads.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProjectionTurns.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/persistence/Services/ProviderSessionRuntime.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts+166−0

This diff is large: its 167 lines aren’t shown here.

apps/server/src/project/Layers/ProjectSetupScriptRunner.ts+75−0

This diff is large: its 76 lines aren’t shown here.

apps/server/src/project/Layers/RepositoryIdentityResolver.test.ts+193−0

This diff is large: its 194 lines aren’t shown here.

apps/server/src/project/Layers/RepositoryIdentityResolver.ts+149−0

This diff is large: its 150 lines aren’t shown here.

apps/server/src/project/Services/ProjectFaviconResolver.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/project/Services/ProjectSetupScriptRunner.ts+37−0

This diff is large: its 38 lines aren’t shown here.

apps/server/src/project/Services/RepositoryIdentityResolver.ts+12−0

This diff is large: its 13 lines aren’t shown here.

apps/server/src/provider/Layers/ClaudeAdapter.test.ts+72−69

This diff is large: its 256 lines aren’t shown here.

apps/server/src/provider/Layers/ClaudeAdapter.ts+25−20

This diff is large: its 161 lines aren’t shown here.

apps/server/src/provider/Layers/ClaudeProvider.ts+119−65

This diff is large: its 299 lines aren’t shown here.

apps/server/src/provider/Layers/CodexAdapter.test.ts+10−15

This diff is large: its 82 lines aren’t shown here.

apps/server/src/provider/Layers/CodexAdapter.ts+18−21

This diff is large: its 140 lines aren’t shown here.

apps/server/src/provider/Layers/CodexProvider.ts+61−18

This diff is large: its 186 lines aren’t shown here.

apps/server/src/provider/Layers/EventNdjsonLogger.test.ts+46−3

This diff is large: its 73 lines aren’t shown here.

apps/server/src/provider/Layers/EventNdjsonLogger.ts+65−27

This diff is large: its 126 lines aren’t shown here.

apps/server/src/provider/Layers/ProviderRegistry.test.ts+130−1

This diff is large: its 173 lines aren’t shown here.

apps/server/src/provider/Layers/ProviderService.test.ts+135−8

This diff is large: its 192 lines aren’t shown here.

apps/server/src/provider/Layers/ProviderService.ts+325−171

This diff is large: its 586 lines aren’t shown here.

apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts+5−5

This diff is large: its 45 lines aren’t shown here.

apps/server/src/provider/Services/ClaudeAdapter.ts+3−3

This diff is large: its 23 lines aren’t shown here.

apps/server/src/provider/Services/ClaudeProvider.ts+2−2

This diff is large: its 12 lines aren’t shown here.

apps/server/src/provider/Services/CodexAdapter.ts+3−3

This diff is large: its 23 lines aren’t shown here.

apps/server/src/provider/Services/CodexProvider.ts+2−2

This diff is large: its 12 lines aren’t shown here.

apps/server/src/provider/Services/ProviderAdapterRegistry.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/provider/Services/ProviderRegistry.ts+2−2

This diff is large: its 17 lines aren’t shown here.

apps/server/src/provider/Services/ProviderService.ts+3−3

This diff is large: its 26 lines aren’t shown here.

apps/server/src/provider/Services/ProviderSessionDirectory.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/provider/codexAppServer.ts+95−8

This diff is large: its 174 lines aren’t shown here.

apps/server/src/provider/providerSnapshot.ts+10−3

This diff is large: its 55 lines aren’t shown here.

apps/server/src/server.test.ts+2827−574

This diff is large: its 3858 lines aren’t shown here.

apps/server/src/server.ts+97−42

This diff is large: its 242 lines aren’t shown here.

apps/server/src/serverLifecycleEvents.test.ts+10−0

This diff is large: its 34 lines aren’t shown here.

apps/server/src/serverLifecycleEvents.ts+2−2

This diff is large: its 16 lines aren’t shown here.

apps/server/src/serverLogger.ts+1−4

This diff is large: its 13 lines aren’t shown here.

apps/server/src/serverRuntimeStartup.test.ts+9−0

This diff is large: its 24 lines aren’t shown here.

apps/server/src/serverRuntimeStartup.ts+134−64

This diff is large: its 319 lines aren’t shown here.

apps/server/src/serverRuntimeState.ts+77−0

This diff is large: its 78 lines aren’t shown here.

apps/server/src/serverSettings.test.ts+26−0

This diff is large: its 47 lines aren’t shown here.

apps/server/src/serverSettings.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/startupAccess.test.ts+79−0

This diff is large: its 80 lines aren’t shown here.

apps/server/src/startupAccess.ts+148−0

This diff is large: its 149 lines aren’t shown here.

apps/server/src/telemetry/Layers/AnalyticsService.ts+13−11

This diff is large: its 31 lines aren’t shown here.

apps/server/src/telemetry/Services/AnalyticsService.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/terminal/Layers/Manager.test.ts+79−0

This diff is large: its 86 lines aren’t shown here.

apps/server/src/terminal/Layers/Manager.ts+100−67

This diff is large: its 357 lines aren’t shown here.

apps/server/src/terminal/Services/Manager.ts+3−2

This diff is large: its 25 lines aren’t shown here.

apps/server/src/terminal/Services/PTY.ts+2−2

This diff is large: its 17 lines aren’t shown here.

apps/server/src/workspace/Layers/WorkspaceEntries.test.ts+12−0

This diff is large: its 19 lines aren’t shown here.

apps/server/src/workspace/Layers/WorkspaceEntries.ts+49−129

This diff is large: its 246 lines aren’t shown here.

apps/server/src/workspace/Services/WorkspaceEntries.ts+2−2

This diff is large: its 17 lines aren’t shown here.

apps/server/src/workspace/Services/WorkspaceFileSystem.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/server/src/workspace/Services/WorkspacePaths.ts+2−2

This diff is large: its 17 lines aren’t shown here.

apps/server/src/ws.ts+900−273

This diff is large: its 1239 lines aren’t shown here.

apps/web/index.html+83−2

This diff is large: its 101 lines aren’t shown here.

apps/web/package.json+2−1

This diff is large: its 16 lines aren’t shown here.

apps/web/src/authBootstrap.test.ts+501−0

This diff is large: its 502 lines aren’t shown here.

apps/web/src/clientPersistenceStorage.test.ts+80−0

This diff is large: its 81 lines aren’t shown here.

apps/web/src/clientPersistenceStorage.ts+194−0

This diff is large: its 195 lines aren’t shown here.

apps/web/src/commandPaletteStore.ts+13−0

This diff is large: its 14 lines aren’t shown here.

apps/web/src/components/BranchToolbar.logic.test.ts+82−1

This diff is large: its 104 lines aren’t shown here.

apps/web/src/components/BranchToolbar.logic.ts+50−4

This diff is large: its 73 lines aren’t shown here.

apps/web/src/components/BranchToolbar.tsx+68−133

This diff is large: its 240 lines aren’t shown here.

apps/web/src/components/BranchToolbarBranchSelector.tsx+164−79

This diff is large: its 396 lines aren’t shown here.

apps/web/src/components/BranchToolbarEnvModeSelector.tsx+97−0

This diff is large: its 98 lines aren’t shown here.

apps/web/src/components/BranchToolbarEnvironmentSelector.tsx+88−0

This diff is large: its 89 lines aren’t shown here.

apps/web/src/components/ChatMarkdown.browser.tsx+79−0

This diff is large: its 80 lines aren’t shown here.

apps/web/src/components/ChatMarkdown.tsx+13−5

This diff is large: its 59 lines aren’t shown here.

apps/web/src/components/ChatView.browser.tsx+1913−197

This diff is large: its 2699 lines aren’t shown here.

apps/web/src/components/ChatView.logic.test.ts+236−121

This diff is large: its 520 lines aren’t shown here.

apps/web/src/components/ChatView.logic.ts+48−9

This diff is large: its 99 lines aren’t shown here.

apps/web/src/components/ChatView.tsx+1083−2073

This diff is large: its 4297 lines aren’t shown here.

apps/web/src/components/CommandPalette.logic.test.ts+166−0

This diff is large: its 167 lines aren’t shown here.

apps/web/src/components/CommandPalette.logic.ts+262−0

This diff is large: its 263 lines aren’t shown here.

apps/web/src/components/CommandPalette.tsx+458−0

This diff is large: its 459 lines aren’t shown here.

apps/web/src/components/CommandPaletteResults.tsx+103−0

This diff is large: its 104 lines aren’t shown here.

apps/web/src/components/ComposerPromptEditor.tsx+566−13

This diff is large: its 782 lines aren’t shown here.

apps/web/src/components/DiffPanel.tsx+28−16

This diff is large: its 110 lines aren’t shown here.

apps/web/src/components/GitActionsControl.browser.tsx+294−70

This diff is large: its 469 lines aren’t shown here.

apps/web/src/components/GitActionsControl.tsx+138−38

This diff is large: its 305 lines aren’t shown here.

apps/web/src/components/Icons.tsx+222−0

This diff is large: its 236 lines aren’t shown here.

apps/web/src/components/KeybindingsToast.browser.tsx+141−24

This diff is large: its 259 lines aren’t shown here.

apps/web/src/components/NoActiveThreadState.tsx+41−0

This diff is large: its 42 lines aren’t shown here.

apps/web/src/components/PlanSidebar.tsx+6−3

This diff is large: its 49 lines aren’t shown here.

apps/web/src/components/ProjectFavicon.tsx+14−7

This diff is large: its 42 lines aren’t shown here.

apps/web/src/components/PullRequestThreadDialog.tsx+11−3

This diff is large: its 65 lines aren’t shown here.

apps/web/src/components/Sidebar.logic.test.ts+97−230

This diff is large: its 596 lines aren’t shown here.

apps/web/src/components/Sidebar.logic.ts+10−62

This diff is large: its 116 lines aren’t shown here.

apps/web/src/components/Sidebar.tsx+2438−1411

This diff is large: its 4324 lines aren’t shown here.

apps/web/src/components/SplashScreen.tsx+9−0

This diff is large: its 10 lines aren’t shown here.

apps/web/src/components/ThreadTerminalDrawer.browser.tsx+318−0

This diff is large: its 319 lines aren’t shown here.

apps/web/src/components/ThreadTerminalDrawer.tsx+83−31

This diff is large: its 326 lines aren’t shown here.

apps/web/src/components/WebSocketConnectionSurface.logic.test.ts+113−0

This diff is large: its 114 lines aren’t shown here.

apps/web/src/components/WebSocketConnectionSurface.tsx+390−0

This diff is large: its 391 lines aren’t shown here.

apps/web/src/components/auth/PairingRouteSurface.tsx+195−0

This diff is large: its 196 lines aren’t shown here.

apps/web/src/components/chat/ChangedFilesTree.test.tsx+2−2

This diff is large: its 18 lines aren’t shown here.

apps/web/src/components/chat/ChatComposer.tsx+1990−0

This diff is large: its 1991 lines aren’t shown here.

apps/web/src/components/chat/ChatHeader.tsx+14−1

This diff is large: its 50 lines aren’t shown here.

apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx+37−29

This diff is large: its 104 lines aren’t shown here.

apps/web/src/components/chat/CompactComposerControlsMenu.tsx+3−2

This diff is large: its 22 lines aren’t shown here.

apps/web/src/components/chat/ComposerCommandMenu.tsx+161−27

This diff is large: its 251 lines aren’t shown here.

apps/web/src/components/chat/ComposerPendingTerminalContexts.test.tsx+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx+39−32

This diff is large: its 155 lines aren’t shown here.

apps/web/src/components/chat/ComposerPrimaryActions.test.ts+93−0

This diff is large: its 94 lines aren’t shown here.

apps/web/src/components/chat/ComposerPrimaryActions.tsx+8−3

This diff is large: its 42 lines aren’t shown here.

apps/web/src/components/chat/ExpandedImageDialog.tsx+120−0

This diff is large: its 121 lines aren’t shown here.

apps/web/src/components/chat/MessageCopyButton.tsx+74−12

This diff is large: its 95 lines aren’t shown here.

apps/web/src/components/chat/MessagesTimeline.logic.test.ts+123−1

This diff is large: its 133 lines aren’t shown here.

apps/web/src/components/chat/MessagesTimeline.logic.ts+47−0

This diff is large: its 75 lines aren’t shown here.

apps/web/src/components/chat/MessagesTimeline.test.tsx+10−2

This diff is large: its 57 lines aren’t shown here.

apps/web/src/components/chat/MessagesTimeline.tsx+109−41

This diff is large: its 311 lines aren’t shown here.

apps/web/src/components/chat/MessagesTimeline.virtualization.browser.tsx+41−7

This diff is large: its 133 lines aren’t shown here.

apps/web/src/components/chat/OpenInPicker.tsx+21−6

This diff is large: its 67 lines aren’t shown here.

apps/web/src/components/chat/ProposedPlanCard.tsx+5−2

This diff is large: its 34 lines aren’t shown here.

apps/web/src/components/chat/ProviderModelPicker.browser.tsx+6−0

This diff is large: its 27 lines aren’t shown here.

apps/web/src/components/chat/TraitsPicker.browser.tsx+35−25

This diff is large: its 164 lines aren’t shown here.

apps/web/src/components/chat/TraitsPicker.tsx+12−5

This diff is large: its 48 lines aren’t shown here.

apps/web/src/components/chat/composerMenuHighlight.test.ts+51−0

This diff is large: its 52 lines aren’t shown here.

apps/web/src/components/chat/composerMenuHighlight.ts+20−0

This diff is large: its 21 lines aren’t shown here.

apps/web/src/components/chat/composerProviderRegistry.test.tsx+33−1

This diff is large: its 44 lines aren’t shown here.

apps/web/src/components/chat/composerProviderRegistry.tsx+93−53

This diff is large: its 227 lines aren’t shown here.

apps/web/src/components/chat/composerSlashCommandSearch.test.ts+68−0

This diff is large: its 69 lines aren’t shown here.

apps/web/src/components/chat/composerSlashCommandSearch.ts+83−0

This diff is large: its 84 lines aren’t shown here.

apps/web/src/components/composerFooterLayout.test.ts+0−99

This diff is large: its 110 lines aren’t shown here.

apps/web/src/components/composerFooterLayout.ts+0−45

This diff is large: its 56 lines aren’t shown here.

apps/web/src/components/composerInlineChip.ts+3−0

This diff is large: its 9 lines aren’t shown here.

apps/web/src/components/settings/ConnectionsSettings.tsx+1432−0

This diff is large: its 1433 lines aren’t shown here.

apps/web/src/components/settings/SettingsPanels.browser.tsx+694−0

This diff is large: its 695 lines aren’t shown here.

apps/web/src/components/settings/SettingsPanels.tsx+133−157

This diff is large: its 440 lines aren’t shown here.

apps/web/src/components/settings/SettingsSidebarNav.tsx+9−5

This diff is large: its 47 lines aren’t shown here.

apps/web/src/components/settings/settingsLayout.tsx+122−0

This diff is large: its 123 lines aren’t shown here.

apps/web/src/components/timelineHeight.test.ts+17−4

This diff is large: its 54 lines aren’t shown here.

apps/web/src/components/timelineHeight.ts+28−4

This diff is large: its 65 lines aren’t shown here.

apps/web/src/components/ui/command.tsx+6−3

This diff is large: its 26 lines aren’t shown here.

apps/web/src/components/ui/qr-code.test.tsx+27−0

This diff is large: its 28 lines aren’t shown here.

apps/web/src/components/ui/qr-code.tsx+81−0

This diff is large: its 82 lines aren’t shown here.

apps/web/src/components/ui/toast.logic.test.ts+52−1

This diff is large: its 62 lines aren’t shown here.

apps/web/src/components/ui/toast.logic.ts+27−0

This diff is large: its 35 lines aren’t shown here.

apps/web/src/components/ui/toast.tsx+48−32

This diff is large: its 167 lines aren’t shown here.

apps/web/src/composer-editor-mentions.test.ts+88−1

This diff is large: its 107 lines aren’t shown here.

apps/web/src/composer-editor-mentions.ts+185−27

This diff is large: its 267 lines aren’t shown here.

apps/web/src/composer-logic.test.ts+53−0

This diff is large: its 81 lines aren’t shown here.

apps/web/src/composer-logic.ts+50−14

This diff is large: its 121 lines aren’t shown here.

apps/web/src/composerDraftStore.test.ts+360−202

This diff is large: its 1103 lines aren’t shown here.

apps/web/src/composerDraftStore.ts+1635−960

This diff is large: its 3038 lines aren’t shown here.

apps/web/src/composerHandleContext.ts+10−0

This diff is large: its 11 lines aren’t shown here.

apps/web/src/diffRouteSearch.ts+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/editorPreferences.ts+2−2

This diff is large: its 15 lines aren’t shown here.

apps/web/src/environmentApi.ts+68−0

This diff is large: its 69 lines aren’t shown here.

apps/web/src/environmentGrouping.test.ts+453−0

This diff is large: its 454 lines aren’t shown here.

apps/web/src/environments/primary/auth.ts+359−0

This diff is large: its 360 lines aren’t shown here.

apps/web/src/environments/primary/bootstrap.test.ts+170−0

This diff is large: its 171 lines aren’t shown here.

apps/web/src/environments/primary/context.ts+120−0

This diff is large: its 121 lines aren’t shown here.

apps/web/src/environments/primary/index.ts+35−0

This diff is large: its 36 lines aren’t shown here.

apps/web/src/environments/primary/target.ts+158−0

This diff is large: its 159 lines aren’t shown here.

apps/web/src/environments/remote/api.test.ts+235−0

This diff is large: its 236 lines aren’t shown here.

apps/web/src/environments/remote/api.ts+143−0

This diff is large: its 144 lines aren’t shown here.

apps/web/src/environments/remote/target.ts+86−0

This diff is large: its 87 lines aren’t shown here.

apps/web/src/environments/runtime/catalog.test.ts+141−0

This diff is large: its 142 lines aren’t shown here.

apps/web/src/environments/runtime/catalog.ts+341−0

This diff is large: its 342 lines aren’t shown here.

apps/web/src/environments/runtime/connection.test.ts+347−0

This diff is large: its 348 lines aren’t shown here.

apps/web/src/environments/runtime/connection.ts+334−0

This diff is large: its 335 lines aren’t shown here.

apps/web/src/environments/runtime/index.ts+29−0

This diff is large: its 30 lines aren’t shown here.

apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts+105−0

This diff is large: its 106 lines aren’t shown here.

apps/web/src/environments/runtime/service.test.ts+41−0

This diff is large: its 42 lines aren’t shown here.

apps/web/src/environments/runtime/service.ts+720−0

This diff is large: its 721 lines aren’t shown here.

apps/web/src/historyBootstrap.test.ts+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/hooks/useHandleNewThread.ts+106−52

This diff is large: its 233 lines aren’t shown here.

apps/web/src/hooks/useSettings.test.ts+0−16

This diff is large: its 17 lines aren’t shown here.

apps/web/src/hooks/useSettings.ts+100−176

This diff is large: its 317 lines aren’t shown here.

apps/web/src/hooks/useTheme.ts+78−5

This diff is large: its 148 lines aren’t shown here.

apps/web/src/hooks/useThreadActions.ts+131−66

This diff is large: its 316 lines aren’t shown here.

apps/web/src/index.css+9−6

This diff is large: its 51 lines aren’t shown here.

apps/web/src/keybindings.test.ts+26−0

This diff is large: its 47 lines aren’t shown here.

apps/web/src/lib/chatThreadActions.test.ts+107−0

This diff is large: its 108 lines aren’t shown here.

apps/web/src/lib/chatThreadActions.ts+98−0

This diff is large: its 99 lines aren’t shown here.

apps/web/src/lib/contextWindow.test.ts+2−2

This diff is large: its 15 lines aren’t shown here.

apps/web/src/lib/gitReactQuery.test.ts+30−42

This diff is large: its 168 lines aren’t shown here.

apps/web/src/lib/gitReactQuery.ts+128−103

This diff is large: its 372 lines aren’t shown here.

apps/web/src/lib/gitStatusState.test.ts+326−0

This diff is large: its 327 lines aren’t shown here.

apps/web/src/lib/gitStatusState.ts+287−0

This diff is large: its 288 lines aren’t shown here.

apps/web/src/lib/projectReactQuery.ts+17−8

This diff is large: its 56 lines aren’t shown here.

apps/web/src/lib/providerReactQuery.test.ts+12−5

This diff is large: its 76 lines aren’t shown here.

apps/web/src/lib/providerReactQuery.ts+11−4

This diff is large: its 51 lines aren’t shown here.

apps/web/src/lib/terminalContext.test.ts+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/lib/terminalStateCleanup.test.ts+43−10

This diff is large: its 76 lines aren’t shown here.

apps/web/src/lib/terminalStateCleanup.ts+17−9

This diff is large: its 43 lines aren’t shown here.

apps/web/src/lib/threadSort.test.ts+187−0

This diff is large: its 188 lines aren’t shown here.

apps/web/src/lib/threadSort.ts+73−0

This diff is large: its 74 lines aren’t shown here.

apps/web/src/lib/utils.test.ts+1−2

This diff is large: its 7 lines aren’t shown here.

apps/web/src/lib/utils.ts+6−42

This diff is large: its 65 lines aren’t shown here.

apps/web/src/localApi.test.ts+618−0

This diff is large: its 619 lines aren’t shown here.

apps/web/src/localApi.ts+154−0

This diff is large: its 155 lines aren’t shown here.

apps/web/src/logicalProject.ts+19−0

This diff is large: its 20 lines aren’t shown here.

apps/web/src/markdown-links.test.ts+15−1

This diff is large: its 22 lines aren’t shown here.

apps/web/src/markdown-links.ts+18−7

This diff is large: its 44 lines aren’t shown here.

apps/web/src/nativeApi.ts+0−31

This diff is large: its 32 lines aren’t shown here.

apps/web/src/observability/clientTracing.ts+144−0

This diff is large: its 145 lines aren’t shown here.

apps/web/src/orchestrationEventEffects.test.ts+39−13

This diff is large: its 113 lines aren’t shown here.

apps/web/src/orchestrationEventEffects.ts+22−4

This diff is large: its 57 lines aren’t shown here.

apps/web/src/orchestrationRecovery.test.ts+177−4

This diff is large: its 214 lines aren’t shown here.

apps/web/src/orchestrationRecovery.ts+77−7

This diff is large: its 108 lines aren’t shown here.

apps/web/src/pairingUrl.ts+33−0

This diff is large: its 34 lines aren’t shown here.

apps/web/src/pendingUserInput.test.ts+113−55

This diff is large: its 277 lines aren’t shown here.

apps/web/src/pendingUserInput.ts+64−16

This diff is large: its 153 lines aren’t shown here.

apps/web/src/projectScripts.test.ts+5−3

This diff is large: its 19 lines aren’t shown here.

apps/web/src/projectScripts.ts+1−37

This diff is large: its 53 lines aren’t shown here.

apps/web/src/providerSkillPresentation.test.ts+57−0

This diff is large: its 58 lines aren’t shown here.

apps/web/src/providerSkillPresentation.ts+52−0

This diff is large: its 53 lines aren’t shown here.

apps/web/src/providerSkillSearch.test.ts+59−0

This diff is large: its 60 lines aren’t shown here.

apps/web/src/providerSkillSearch.ts+105−0

This diff is large: its 106 lines aren’t shown here.

apps/web/src/pullRequestReference.test.ts+2−2

This diff is large: its 18 lines aren’t shown here.

apps/web/src/pullRequestReference.ts+1−1

This diff is large: its 9 lines aren’t shown here.

apps/web/src/routeTree.gen.ts+81−17

This diff is large: its 224 lines aren’t shown here.

apps/web/src/routes/__root.tsx+101−310

This diff is large: its 518 lines aren’t shown here.

apps/web/src/routes/_chat.$environmentId.$threadId.tsxrenamed from apps/web/src/routes/_chat.$threadId.tsx+84−31

This diff is large: its 191 lines aren’t shown here.

apps/web/src/routes/_chat.draft.$draftId.tsx+86−0

This diff is large: its 87 lines aren’t shown here.

apps/web/src/routes/_chat.index.tsx+2−26

This diff is large: its 36 lines aren’t shown here.

apps/web/src/routes/_chat.tsx+49−25

This diff is large: its 131 lines aren’t shown here.

apps/web/src/routes/pair.tsx+47−0

This diff is large: its 48 lines aren’t shown here.

apps/web/src/routes/settings.connections.tsx+7−0

This diff is large: its 8 lines aren’t shown here.

apps/web/src/routes/settings.tsx+13−1

This diff is large: its 28 lines aren’t shown here.

apps/web/src/rpc/client.test.ts+0−231

This diff is large: its 232 lines aren’t shown here.

apps/web/src/rpc/client.ts+0−33

This diff is large: its 34 lines aren’t shown here.

apps/web/src/rpc/protocol.ts+163−13

This diff is large: its 191 lines aren’t shown here.

apps/web/src/rpc/requestLatencyState.test.ts+65−0

This diff is large: its 66 lines aren’t shown here.

apps/web/src/rpc/requestLatencyState.ts+133−0

This diff is large: its 134 lines aren’t shown here.

apps/web/src/rpc/serverState.test.ts+38−6

This diff is large: its 89 lines aren’t shown here.

apps/web/src/rpc/serverState.ts+6−1

This diff is large: its 28 lines aren’t shown here.

apps/web/src/rpc/transportError.test.ts+24−0

This diff is large: its 25 lines aren’t shown here.

apps/web/src/rpc/transportError.ts+23−0

This diff is large: its 24 lines aren’t shown here.

apps/web/src/rpc/wsConnectionState.test.ts+75−0

This diff is large: its 76 lines aren’t shown here.

apps/web/src/rpc/wsConnectionState.ts+199−0

This diff is large: its 200 lines aren’t shown here.

apps/web/src/rpc/wsRpcClient.test.ts+104−0

This diff is large: its 105 lines aren’t shown here.

apps/web/src/rpc/wsRpcClient.tsrenamed from apps/web/src/wsRpcClient.ts+66−31

This diff is large: its 187 lines aren’t shown here.

apps/web/src/rpc/wsTransport.test.ts+946−0

This diff is large: its 947 lines aren’t shown here.

apps/web/src/rpc/wsTransport.ts+281−0

This diff is large: its 282 lines aren’t shown here.

apps/web/src/session-logic.test.ts+141−128

This diff is large: its 567 lines aren’t shown here.

apps/web/src/session-logic.ts+188−47

This diff is large: its 332 lines aren’t shown here.

apps/web/src/store.test.ts+623−204

This diff is large: its 1294 lines aren’t shown here.

apps/web/src/store.ts+919−364

This diff is large: its 1623 lines aren’t shown here.

apps/web/src/storeSelectors.ts+69−18

This diff is large: its 96 lines aren’t shown here.

apps/web/src/terminal-links.test.ts+104−0

This diff is large: its 123 lines aren’t shown here.

apps/web/src/terminal-links.ts+111−0

This diff is large: its 125 lines aren’t shown here.

apps/web/src/terminalActivity.test.ts+1−0

This diff is large: its 8 lines aren’t shown here.

apps/web/src/terminalStateStore.test.ts+211−59

This diff is large: its 395 lines aren’t shown here.

apps/web/src/terminalStateStore.ts+281−99

This diff is large: its 548 lines aren’t shown here.

apps/web/src/threadDerivation.ts+152−0

This diff is large: its 153 lines aren’t shown here.

apps/web/src/threadRoutes.test.ts+67−0

This diff is large: its 68 lines aren’t shown here.

apps/web/src/threadRoutes.ts+59−0

This diff is large: its 60 lines aren’t shown here.

apps/web/src/threadSelectionStore.test.ts+59−59

This diff is large: its 280 lines aren’t shown here.

apps/web/src/threadSelectionStore.ts+51−53

This diff is large: its 173 lines aren’t shown here.

apps/web/src/timestampFormat.test.ts+86−2

This diff is large: its 97 lines aren’t shown here.

apps/web/src/timestampFormat.ts+87−0

This diff is large: its 91 lines aren’t shown here.

apps/web/src/types.ts+28−0

This diff is large: its 61 lines aren’t shown here.

apps/web/src/uiStateStore.test.ts+185−29

This diff is large: its 345 lines aren’t shown here.

apps/web/src/uiStateStore.ts+197−49

This diff is large: its 450 lines aren’t shown here.

apps/web/src/vite-env.d.ts+2−2

This diff is large: its 17 lines aren’t shown here.

apps/web/src/worktreeCleanup.test.ts+15−12

This diff is large: its 80 lines aren’t shown here.

apps/web/src/wsNativeApi.test.ts+0−352

This diff is large: its 353 lines aren’t shown here.

apps/web/src/wsNativeApi.ts+0−107

This diff is large: its 108 lines aren’t shown here.

apps/web/src/wsTransport.test.ts+0−443

This diff is large: its 444 lines aren’t shown here.

apps/web/src/wsTransport.ts+0−131

This diff is large: its 132 lines aren’t shown here.

apps/web/test/authHttpHandlers.ts+41−0

This diff is large: its 42 lines aren’t shown here.

apps/web/test/wsRpcHarness.ts+10−2

This diff is large: its 35 lines aren’t shown here.

apps/web/vite.config.ts+48−2

This diff is large: its 85 lines aren’t shown here.

apps/web/vitest.browser.config.ts+8−0

This diff is large: its 22 lines aren’t shown here.

bun.lock+40−17

This diff is large: its 135 lines aren’t shown here.

docs/observability.md+519−0

This diff is large: its 520 lines aren’t shown here.

package.json+14−6

This diff is large: its 34 lines aren’t shown here.

packages/client-runtime/package.json+25−0

This diff is large: its 26 lines aren’t shown here.

packages/client-runtime/src/index.ts+2−0

This diff is large: its 3 lines aren’t shown here.

packages/client-runtime/src/knownEnvironment.test.ts+92−0

This diff is large: its 93 lines aren’t shown here.

packages/client-runtime/src/knownEnvironment.ts+53−0

This diff is large: its 54 lines aren’t shown here.

packages/client-runtime/src/scoped.ts+64−0

This diff is large: its 65 lines aren’t shown here.

packages/client-runtime/tsconfig.json+4−0

This diff is large: its 5 lines aren’t shown here.

packages/contracts/package.json+1−1

This diff is large: its 8 lines aren’t shown here.

packages/contracts/src/auth.ts+266−0

This diff is large: its 267 lines aren’t shown here.

packages/contracts/src/baseSchemas.ts+7−2

This diff is large: its 28 lines aren’t shown here.

packages/contracts/src/editor.ts+21−10

This diff is large: its 43 lines aren’t shown here.

packages/contracts/src/environment.ts+77−0

This diff is large: its 78 lines aren’t shown here.

packages/contracts/src/git.ts+51−2

This diff is large: its 111 lines aren’t shown here.

packages/contracts/src/index.ts+2−0

This diff is large: its 7 lines aren’t shown here.

packages/contracts/src/ipc.ts+107−26

This diff is large: its 196 lines aren’t shown here.

packages/contracts/src/keybindings.test.ts+6−0

This diff is large: its 13 lines aren’t shown here.

packages/contracts/src/keybindings.ts+1−0

This diff is large: its 8 lines aren’t shown here.

packages/contracts/src/model.ts+1−0

This diff is large: its 8 lines aren’t shown here.

packages/contracts/src/orchestration.test.ts+41−0

This diff is large: its 48 lines aren’t shown here.

packages/contracts/src/orchestration.ts+81−16

This diff is large: its 233 lines aren’t shown here.

packages/contracts/src/rpc.ts+27−4

This diff is large: its 118 lines aren’t shown here.

packages/contracts/src/server.test.ts+26−0

This diff is large: its 27 lines aren’t shown here.

packages/contracts/src/server.ts+45−1

This diff is large: its 88 lines aren’t shown here.

packages/contracts/src/settings.ts+38−21

This diff is large: its 104 lines aren’t shown here.

packages/contracts/src/terminal.test.ts+26−0

This diff is large: its 52 lines aren’t shown here.

packages/contracts/src/terminal.ts+5−2

This diff is large: its 39 lines aren’t shown here.

packages/contracts/src/userInput.ts+2−2

This diff is large: its 15 lines aren’t shown here.

packages/shared/package.json+16−0

This diff is large: its 26 lines aren’t shown here.

packages/shared/src/Net.ts+2−2

This diff is large: its 17 lines aren’t shown here.

packages/shared/src/git.test.ts+114−0

This diff is large: its 115 lines aren’t shown here.

packages/shared/src/git.ts+188−1

This diff is large: its 204 lines aren’t shown here.

packages/shared/src/model.test.ts+1−0

This diff is large: its 8 lines aren’t shown here.

packages/shared/src/projectScripts.ts+37−0

This diff is large: its 38 lines aren’t shown here.

packages/shared/src/qrCode.ts+984−0

This diff is large: its 985 lines aren’t shown here.

packages/shared/src/searchRanking.test.ts+95−0

This diff is large: its 96 lines aren’t shown here.

packages/shared/src/searchRanking.ts+192−0

This diff is large: its 193 lines aren’t shown here.

packages/shared/src/serverSettings.test.ts+53−0

This diff is large: its 54 lines aren’t shown here.

packages/shared/src/serverSettings.ts+40−0

This diff is large: its 41 lines aren’t shown here.

scripts/build-desktop-artifact.test.ts+45−0

This diff is large: its 46 lines aren’t shown here.

scripts/build-desktop-artifact.ts+30−10

This diff is large: its 82 lines aren’t shown here.

scripts/dev-runner.test.ts+73−24

This diff is large: its 210 lines aren’t shown here.

scripts/dev-runner.ts+33−66

This diff is large: its 196 lines aren’t shown here.

scripts/lib/resolve-catalog.ts+3−3

This diff is large: its 14 lines aren’t shown here.

scripts/release-smoke.ts+1−0

This diff is large: its 8 lines aren’t shown here.

turbo.json+12−2

This diff is large: its 30 lines aren’t shown here.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t