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+
3+This document describes the target architecture for first-class remote environments in T3 Code.
4+
5+It 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+
24+T3 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+
26+Remote 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+
59+The 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+
65+An `ExecutionEnvironment` is one running T3 server instance.
66+
67+It 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+
77+It is identified by a stable `environmentId`.
78+
79+This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
80+
81+### KnownEnvironment
82+
83+A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
84+
85+It is not server-authored. It is local to a device or client profile.
86+
87+Examples:
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+
94+A known environment may or may not know the target `environmentId` before first successful connect.
95+
96+### AccessEndpoint
97+
98+An `AccessEndpoint` is one concrete way to reach a known environment.
99+
100+This is the key abstraction that keeps SSH from taking over the model.
101+
102+A 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+
109+The 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+
115+It 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+
119+The current `Project` model remains environment-local.
120+
121+That 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+
129+Access methods answer one question:
130+
131+How does the client speak WebSocket to a T3 server?
132+
133+They 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+
141+Examples:
142+
143+- `ws://10.0.0.15:3773`
144+- `wss://t3.example.com`
145+
146+This is the base model and should be the first-class default.
147+
148+Benefits:
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+
156+Examples:
157+
158+- public relay URLs
159+- private network relay URLs
160+- local tunnel products such as pipenet
161+
162+This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
163+
164+For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
165+
166+This 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+
175+SSH is an access and launch helper, not a separate environment type.
176+
177+The 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+
184+After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
185+
186+This keeps the renderer transport model consistent with every other access method.
187+
188+## Launch methods
189+
190+Launch methods answer a different question:
191+
192+How does a T3 server come to exist on the target machine?
193+
194+Launch and access should stay separate in the design.
195+
196+### 1. Pre-existing server
197+
198+The simplest launch method is no launch at all.
199+
200+The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
201+
202+This 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+
206+This is the main place where Zed is a useful reference.
207+
208+Useful 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+
216+What 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+
222+The recommended T3 flow is:
223+
224+1. Desktop connects over SSH.
225+2. Desktop probes the remote machine and verifies T3 availability.
226+3. Desktop launches or reuses a remote T3 server.
227+4. Desktop establishes local port forwarding.
228+5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
229+
230+### 3. Client-managed local publish
231+
232+This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
233+
234+This is useful for:
235+
236+- exposing a desktop-hosted environment to mobile
237+- temporary remote access without changing router or firewall settings
238+
239+This is still a launch concern, not a new environment kind.
240+
241+## Why access and launch must stay separate
242+
243+These concerns are easy to conflate, but separating them prevents architectural drift.
244+
245+Examples:
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+
252+In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
253+
254+Only the launch and access paths differ.
255+
256+## Security model
257+
258+Remote support must assume that some environments will be reachable over untrusted networks.
259+
260+That 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+
266+T3 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+
268+For publicly reachable environments, authenticated access should be treated as required.
269+
270+## Relationship to Zed
271+
272+Zed is a useful reference implementation for managed remote launch and reconnect behavior.
273+
274+The 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+
281+The important mismatch is transport shape.
282+
283+Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
284+
285+T3 should not copy that part.
286+
287+T3 already has the right runtime boundary:
288+
289+- one T3 server per environment
290+- ordinary HTTP/WebSocket between client and environment
291+
292+So T3 should borrow Zed's launch discipline, not its transport protocol.
293+
294+## Recommended rollout
295+
296+1. First-class known environments and access endpoints.
297+2. Direct `ws` / `wss` remote environments.
298+3. Authenticated tunnel-backed environments.
299+4. Desktop-managed SSH launch and forwarding.
300+5. Multi-environment UI improvements after the base runtime path is proven.
301+
302+This 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
1010 quality:
1111 name: Format, Lint, Typecheck, Test, Browser Test, Build
1212 runs-on: blacksmith-4vcpu-ubuntu-2404
13+ timeout-minutes: 10
1314 steps:
1415 - name: Checkout
1516 uses: actions/checkout@v6
@@ -71,11 +72,12 @@ jobs: · 55 unmodified lines
7172 - name: Verify preload bundle output
7273 run: |
7374 test -f apps/desktop/dist-electron/preload.js
74− grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
75+ grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
7576
7677 release_smoke:
7778 name: Release Smoke
7879 runs-on: ubuntu-24.04
80+ timeout-minutes: 10
7981 steps:
8082 - name: Checkout
8183 uses: actions/checkout@v6
.github/workflows/release.yml+5−0
@@ -19,6 +19,7 @@ jobs: · 18 unmodified lines
1919 preflight:
2020 name: Preflight
2121 runs-on: ubuntu-24.04
22+ timeout-minutes: 10
2223 outputs:
2324 version: ${{ steps.release_meta.outputs.version }}
2425 tag: ${{ steps.release_meta.outputs.tag }}
@@ -81,6 +82,7 @@ jobs: · 56 unmodified lines
8182 name: Build ${{ matrix.label }}
8283 needs: preflight
8384 runs-on: ${{ matrix.runner }}
85+ timeout-minutes: 30
8486 strategy:
8587 fail-fast: false
8688 matrix:
@@ -227,6 +229,7 @@ jobs: · 140 unmodified lines
227229 name: Publish CLI to npm
228230 needs: [preflight, build]
229231 runs-on: ubuntu-24.04
232+ timeout-minutes: 10
230233 steps:
231234 - name: Checkout
232235 uses: actions/checkout@v6
@@ -260,6 +263,7 @@ jobs: · 27 unmodified lines
260263 name: Publish GitHub Release
261264 needs: [preflight, build, publish_cli]
262265 runs-on: ubuntu-24.04
266+ timeout-minutes: 10
263267 steps:
264268 - name: Checkout
265269 uses: actions/checkout@v6
@@ -307,6 +311,7 @@ jobs: · 41 unmodified lines
307311 name: Finalize release
308312 needs: [preflight, release]
309313 runs-on: ubuntu-24.04
314+ timeout-minutes: 10
310315 steps:
311316 - id: app_token
312317 name: Mint release app token
.gitignore+1−0
@@ -21,3 +21,4 @@ apps/web/src/components/__screenshots__ · 20 unmodified lines
2121 .vitest-*
2222 __screenshots__/
2323 .tanstack
24+squashfs-root/
.oxfmtrc.json+2−1
@@ -9,7 +9,8 @@ · 8 unmodified lines
99 "bun.lock",
1010 "*.tsbuildinfo",
1111 "**/routeTree.gen.ts",
12− "apps/web/public/mockServiceWorker.js"
12+ "apps/web/public/mockServiceWorker.js",
13+ "apps/web/src/lib/vendor/qrcodegen.ts"
1314 ],
1415 "sortPackageJson": {}
1516 }
.plans/18-server-auth-model.md+823−0
@@ -0,0 +1,823 @@
1+# Server Auth Model Plan
2+
3+## Purpose
4+
5+Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
6+
7+This 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+
9+This 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+
32+Every 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+
38+The 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+
42+The system should distinguish:
43+
44+- bootstrap credentials
45+- session credentials
46+
47+Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
48+
49+Session credentials are the durable credentials used after pairing.
50+
51+Bootstrap should never become the long-lived request credential.
52+
53+### 3. Auth and transport are separate
54+
55+Auth must not be defined by how the client reached the server.
56+
57+Examples:
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+
65+All of these should feed into the same auth model.
66+
67+### 4. Exposure level changes defaults
68+
69+The more exposed an environment is, the narrower the safe default should be.
70+
71+Safe 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+
80+The auth model should support more than one session credential type even if only one ships first.
81+
82+Examples:
83+
84+- browser session cookie
85+- native bearer/device token
86+
87+This 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+
93+Every route or transport entrypoint should be classified as one of:
94+
95+1. `public`
96+2. `bootstrap`
97+3. `authenticated`
98+
99+#### `public`
100+
101+Unauthenticated by definition.
102+
103+Should 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+
111+Used only to exchange a bootstrap credential for a session.
112+
113+Examples:
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+
121+Everything that reveals machine state or mutates it.
122+
123+Examples:
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+
134+The default stance should be: if it touches the machine, it is authenticated.
135+
136+## Credential model
137+
138+### Bootstrap credentials
139+
140+Initial credential types to model:
141+
142+- `desktop-bootstrap`
143+- `one-time-token`
144+
145+Possible future credential types:
146+
147+- `device-code`
148+- `passkey-assertion`
149+- `external-identity`
150+
151+#### `desktop-bootstrap`
152+
153+Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
154+
155+Properties:
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+
164+Used for explicit browser/mobile pairing flows.
165+
166+Properties:
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+
175+Initial credential types to model:
176+
177+- `browser-session-cookie`
178+- `bearer-session-token`
179+
180+#### `browser-session-cookie`
181+
182+Primary browser credential.
183+
184+Properties:
185+
186+- signed
187+- `HttpOnly`
188+- bounded lifetime
189+- revocable by server key rotation or session invalidation
190+
191+#### `bearer-session-token`
192+
193+Reserved for native/mobile or non-browser clients.
194+
195+Properties:
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+
203+Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
204+
205+### Policy examples
206+
207+#### `DesktopManagedLocalPolicy`
208+
209+Default for desktop-managed local server.
210+
211+Allowed bootstrap methods:
212+
213+- `desktop-bootstrap`
214+
215+Allowed session methods:
216+
217+- `browser-session-cookie`
218+
219+Disabled by default:
220+
221+- `one-time-token`
222+- `bearer-session-token`
223+- password login
224+- public pairing
225+
226+#### `LoopbackBrowserPolicy`
227+
228+Used for browser access on localhost without desktop-managed bootstrap.
229+
230+Allowed bootstrap methods:
231+
232+- `one-time-token`
233+
234+Allowed session methods:
235+
236+- `browser-session-cookie`
237+
238+#### `RemoteReachablePolicy`
239+
240+Used when binding non-loopback or using an explicit remote/tunnel workflow.
241+
242+Allowed bootstrap methods:
243+
244+- `one-time-token`
245+- possibly `desktop-bootstrap` when a desktop shell is brokering access
246+
247+Allowed session methods:
248+
249+- `browser-session-cookie`
250+- `bearer-session-token`
251+
252+#### `UnsafeNoAuthPolicy`
253+
254+Should exist only as an explicit escape hatch.
255+
256+Requirements:
257+
258+- explicit opt-in flag
259+- loud startup warnings
260+- never defaulted automatically
261+
262+## Effect-native service model
263+
264+### `ServerAuth`
265+
266+The main auth facade used by HTTP routes and WebSocket upgrade handling.
267+
268+Responsibilities:
269+
270+- classify requests
271+- authenticate requests
272+- authorize bootstrap attempts
273+- create sessions from bootstrap credentials
274+- enforce policy by environment mode
275+
276+Sketch:
277+
278+```ts
279+export 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+
293+export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
294+ "t3/ServerAuth",
295+) {}
296+```
297+
298+### `BootstrapCredentialService`
299+
300+Owns issuance, storage, validation, and consumption of bootstrap credentials.
301+
302+Responsibilities:
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+
309+Sketch:
310+
311+```ts
312+export 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+
327+Owns creation and validation of authenticated sessions.
328+
329+Responsibilities:
330+
331+- mint cookie sessions
332+- mint bearer sessions
333+- validate active session credentials
334+- revoke sessions if needed later
335+
336+Sketch:
337+
338+```ts
339+export 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+
357+Pure policy/config service that decides which credential types are allowed.
358+
359+Responsibilities:
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+
365+This should stay mostly pure and cheap to test.
366+
367+### `ServerSecretStore`
368+
369+Owns long-lived server signing keys and secrets.
370+
371+Responsibilities:
372+
373+- get or create signing key
374+- rotate signing key
375+- abstract secure OS-backed storage vs filesystem fallback
376+
377+Important:
378+
379+- prefer platform secure storage when available
380+- support hardened filesystem fallback for headless/server-only environments
381+
382+### `BrowserSessionCookieCodec`
383+
384+Focused utility service for cookie encode/decode/signing behavior.
385+
386+This should not own policy. It should only own the cookie format.
387+
388+### `AuthRouteGuards`
389+
390+Thin helper layer used by routes to enforce auth consistently.
391+
392+Responsibilities:
393+
394+- require auth for HTTP route handlers
395+- classify route auth mode
396+- convert auth failures into `401` / `403`
397+
398+This prevents every route from re-implementing the same pattern.
399+
400+Integrates with `HttpRouter.middleware` to enforce auth consistently.
401+
402+## Suggested layer graph
403+
404+```text
405+ServerSecretStore
406+ ├─> BootstrapCredentialService
407+ ├─> BrowserSessionCookieCodec
408+ └─> SessionCredentialService
409+
410+ServerAuthPolicy
411+ ├─> BootstrapCredentialService
412+ ├─> SessionCredentialService
413+ └─> ServerAuth
414+
415+ServerAuth
416+ └─> AuthRouteGuards
417+```
418+
419+Layer 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+
432+Current state:
433+
434+- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
435+
436+Target shape:
437+
438+```ts
439+const 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+
449+Then the `/ws` route becomes:
450+
451+```ts
452+export const websocketRpcRouteLayer = HttpRouter.add(
453+ "GET",
454+ "/ws",
455+ rpcWebSocketHttpEffect.pipe(
456+ websocketUpgradeAuth,
457+ Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
458+ ),
459+);
460+```
461+
462+This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
463+
464+### Example: authenticated HTTP route
465+
466+For routes like attachments or project favicon:
467+
468+```ts
469+const 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+
480+Then:
481+
482+```ts
483+export 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+
495+The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
496+
497+That grant is then exchanged for a browser cookie session when the renderer loads.
498+
499+Sketch:
500+
501+```ts
502+const 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+
512+The 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+
516+For browser-driven pairing:
517+
518+```ts
519+const 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+
528+The 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+
532+These flows are meant to anchor the auth model in concrete user journeys.
533+
534+The 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+
542+This is the default desktop-managed local flow.
543+
544+The 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
547+Participants:
548+ DesktopMain = Electron main
549+ SecretStore = secure local secret backend
550+ T3Server = local backend child process
551+ Frontend = desktop renderer
552+
553+DesktopMain -> SecretStore : getOrCreate("server-signing-key")
554+SecretStore --> DesktopMain : signing key available
555+
556+DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
557+DesktopMain -> T3Server : send desktop bootstrap envelope
558+note over T3Server : policy = DesktopManagedLocalPolicy
559+note over T3Server : allowed pairing = desktop-bootstrap only
560+
561+Frontend -> DesktopMain : request local bootstrap grant
562+DesktopMain --> Frontend : short-lived desktop bootstrap grant
563+
564+Frontend -> T3Server : POST /api/auth/bootstrap
565+T3Server -> T3Server : validate desktop bootstrap grant
566+T3Server -> T3Server : create browser session
567+T3Server --> Frontend : Set-Cookie: session=...
568+
569+Frontend -> T3Server : GET /ws + authenticated cookie
570+T3Server -> T3Server : validate cookie session
571+T3Server --> Frontend : websocket accepted
572+```
573+
574+### `npx t3` user
575+
576+This is the standalone local server flow.
577+
578+There is no trusted desktop shell here, so pairing should be explicit.
579+
580+```text
581+Participants:
582+ UserShell = npx t3 launcher
583+ T3Server = standalone local server
584+ Browser = browser tab
585+
586+UserShell -> T3Server : start server
587+T3Server -> T3Server : getOrCreate("server-signing-key")
588+note over T3Server : policy = LoopbackBrowserPolicy
589+
590+UserShell -> T3Server : issue one-time pairing token
591+T3Server --> UserShell : pairing URL or pairing token
592+
593+UserShell --> Browser : open /pair?token=...
594+
595+Browser -> T3Server : GET /pair?token=...
596+T3Server -> T3Server : validate one-time token
597+T3Server -> T3Server : create browser session
598+T3Server --> Browser : Set-Cookie: session=...
599+T3Server --> Browser : redirect to app
600+
601+Browser -> T3Server : GET /ws + authenticated cookie
602+T3Server --> Browser : websocket accepted
603+```
604+
605+### Phone user with tunneled host
606+
607+This is the explicit remote access flow for a browser on another device.
608+
609+The tunnel only provides reachability. It must not imply trust.
610+
611+Recommended 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
618+Participants:
619+ DesktopUser = user at the host machine
620+ DesktopMain = desktop app
621+ Tunnel = tunnel provider
622+ T3Server = T3 server
623+ PhoneBrowser = mobile browser
624+
625+DesktopUser -> DesktopMain : enable remote access via tunnel
626+DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
627+DesktopMain -> Tunnel : publish local T3 endpoint
628+Tunnel --> DesktopMain : public https/wss URL
629+
630+DesktopMain -> T3Server : issue one-time pairing token
631+T3Server --> DesktopMain : pairing token
632+DesktopMain -> DesktopUser : show QR code / shareable URL
633+
634+DesktopUser -> PhoneBrowser : scan QR / open URL
635+PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
636+Tunnel -> T3Server : forward request
637+T3Server -> T3Server : validate one-time token
638+T3Server -> T3Server : create mobile browser session
639+T3Server --> PhoneBrowser : Set-Cookie: session=...
640+T3Server --> PhoneBrowser : redirect to app
641+
642+PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
643+Tunnel -> T3Server : forward websocket upgrade
644+T3Server --> PhoneBrowser : websocket accepted
645+```
646+
647+### Phone user with private network
648+
649+This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
650+
651+The auth flow should stay the same.
652+
653+```text
654+Participants:
655+ DesktopUser = user at the host machine
656+ T3Server = T3 server
657+ PrivateNet = tailscale / private LAN
658+ PhoneBrowser = mobile browser
659+
660+DesktopUser -> T3Server : enable private-network access
661+T3Server -> T3Server : switch policy to RemoteReachablePolicy
662+DesktopUser -> T3Server : issue one-time pairing token
663+T3Server --> DesktopUser : pairing URL / QR
664+
665+DesktopUser -> PhoneBrowser : open private-network URL
666+PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
667+PrivateNet -> T3Server : route request
668+T3Server -> T3Server : validate one-time token
669+T3Server -> T3Server : create mobile browser session
670+T3Server --> PhoneBrowser : Set-Cookie: session=...
671+T3Server --> PhoneBrowser : redirect to app
672+
673+PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
674+PrivateNet -> T3Server : websocket upgrade
675+T3Server --> PhoneBrowser : websocket accepted
676+```
677+
678+### Desktop user adding new SSH hosts
679+
680+SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
681+
682+The 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
685+Participants:
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+
693+DesktopUser -> DesktopMain : add SSH host
694+DesktopMain -> SSH : connect to remote host
695+SSH -> RemoteHost : probe environment / verify t3 availability
696+DesktopMain -> SSH : run remote launch command
697+SSH -> RemoteHost : t3 remote launch --json
698+RemoteHost -> RemoteT3 : start or reuse server
699+RemoteT3 --> RemoteHost : port + environment metadata
700+RemoteHost --> SSH : launch result JSON
701+SSH --> DesktopMain : remote server details
702+
703+DesktopMain -> SSH : establish local port forward
704+SSH --> DesktopMain : localhost:FORWARDED_PORT ready
705+
706+note over RemoteT3 : policy = RemoteReachablePolicy
707+note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
708+
709+Frontend -> DesktopMain : request bootstrap for selected environment
710+DesktopMain --> Frontend : short-lived bootstrap grant
711+
712+Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
713+RemoteT3 -> RemoteT3 : validate bootstrap grant
714+RemoteT3 -> RemoteT3 : create browser session
715+RemoteT3 --> Frontend : Set-Cookie: session=...
716+
717+Frontend -> RemoteT3 : GET /ws + authenticated cookie
718+RemoteT3 --> Frontend : websocket accepted
719+```
720+
721+## Storage decisions
722+
723+### Server secrets
724+
725+Use a `ServerSecretStore` abstraction.
726+
727+Preferred order (use a layer for each, resolve on startup):
728+
729+1. OS secure storage if available
730+2. hardened filesystem fallback if not
731+
732+The 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+
736+Client-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+
742+This concern should stay in the client shell/runtime layer, not the server auth layer.
743+
744+## What to build now
745+
746+These are the parts worth building before remote environments ship:
747+
748+1. `ServerAuth` service boundary.
749+2. route classification and route guards.
750+3. `ServerSecretStore` abstraction.
751+4. bootstrap vs session credential split.
752+5. browser session cookie codec as one session method.
753+6. explicit auth capabilities/config surfaced in contracts.
754+
755+Even 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+
759+1. Browser pairing flow using one-time bootstrap token and cookie session.
760+2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
761+3. Auth-required defaults for any non-loopback or explicitly published server.
762+4. 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+
774+These can all sit on top of the same bootstrap/session/service split.
775+
776+## Relationship to future remote environments
777+
778+Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
779+
780+Keep the design focused on:
781+
782+- one T3 server
783+- one auth policy
784+- multiple credential types
785+- multiple future access methods
786+
787+That 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 @@
1−AGENTS.md
1+AGENTS.md
KEYBINDINGS.md+2−0
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`]( · 22 unmodified lines
2323 { "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
2424 { "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
2525 { "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
26+ { "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
2627 { "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
2728 { "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
2829 { "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
5051 - `terminal.split`: split terminal (in focused terminal context by default)
5152 - `terminal.new`: create new terminal (in focused terminal context by default)
5253 - `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
54+- `commandPalette.toggle`: open or close the global command palette
5355 - `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
5456 - `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
5557 - `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
4545
4646 We are not accepting contributions yet.
4747
48+Observability guide: [docs/observability.md](./docs/observability.md)
49+
4850 ## If you REALLY want to contribute still.... read this first
4951
5052 Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
REMOTE.md+63−44
@@ -1,68 +1,87 @@
1−# Remote Access Setup
1+# Remote Access
22
3−Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
3+Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
44
5−## CLI ↔ Env option map
5+## Recommended Setup
66
7−The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
7+Use a trusted private network that meshes your devices together, such as a tailnet.
88
9−| CLI flag | Env var | Notes |
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. |
9+That gives you:
1910
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
2114
22−## Security First
15+## Enabling Network Access
2316
24−- Always set `--auth-token` before exposing the server outside localhost.
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.
17+There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
2918
30−## 1) Build + run server for remote access
19+### Option 1: Desktop App
3120
32−Remote access should use the built web app (not local Vite redirect mode).
21+If you are already running the desktop app and want to make it reachable from other devices:
22+
23+1. Open **Settings** → **Connections**.
24+2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
25+3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
26+4. Use **Create Link** to generate a pairing link you can share with another device.
27+
28+### Option 2: Headless Server (CLI)
29+
30+Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
31+
32+Run the server with `t3 serve`.
3333
3434 ```bash
35−bun run build
36−TOKEN="$(openssl rand -hex 24)"
37−bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
35+npx t3 serve --host "$(tailscale ip -4)"
3836 ```
3937
40−Then open on your phone:
38+`t3 serve` starts the server without opening a browser and prints:
4139
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
4344
44−Example:
45+From there, connect from another device in either of these ways:
4546
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
4750
48−Notes:
51+Use `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.
4952
50−- `--host 0.0.0.0` listens on all IPv4 interfaces.
51−- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
52−- Ensure your OS firewall allows inbound TCP on the selected port.
53+> Note
54+> The GUIs do not currently support adding projects on remote environments.
55+> For now, use `t3 project ...` on the server machine instead.
56+> Full GUI support for remote project management is coming soon.
5357
54−## 2) Tailnet / Tailscale access
58+## How Pairing Works
5559
56−If you use Tailscale, you can bind directly to your Tailnet address.
60+The remote device does not need a long-lived secret up front.
5761
58−```bash
59−TAILNET_IP="$(tailscale ip -4)"
60−TOKEN="$(openssl rand -hex 24)"
61−bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
62−```
62+Instead:
63+
64+1. `t3 serve` issues a one-time owner pairing token.
65+2. The remote device exchanges that token with the server.
66+3. The server creates an authenticated session for that device.
67+
68+After 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+
72+Use `t3 auth` to manage access after the initial pairing flow.
73+
74+Typical uses:
75+
76+- issue additional pairing credentials
77+- inspect active sessions
78+- revoke old pairing links or sessions
6379
64−Open from any device in your tailnet:
80+Use `t3 auth --help` and the nested subcommand help pages for the full reference.
6581
66−`http://<tailnet-ip>:3773`
82+## Security Notes
6783
68−You 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 @@
11 {
22 "name": "@t3tools/desktop",
3− "version": "0.0.15",
3+ "version": "0.0.17",
44 "private": true,
55 "main": "dist-electron/main.js",
66 "scripts": {
apps/desktop/scripts/dev-electron.mjs+13−6
@@ -5,8 +5,17 @@ import { join } from "node:path"; · 4 unmodified lines
55 import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
66 import { waitForResources } from "./wait-for-resources.mjs";
77
8−const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
9−const devServerUrl = `http://localhost:${port}`;
8+const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
9+if (!devServerUrl) {
10+ throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
11+}
12+
13+const devServer = new URL(devServerUrl);
14+const port = Number.parseInt(devServer.port, 10);
15+if (!Number.isInteger(port) || port <= 0) {
16+ throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
17+}
18+
1019 const requiredFiles = [
1120 "dist-electron/main.js",
1221 "dist-electron/preload.js",
@@ -23,6 +32,7 @@ const childTreeGracePeriodMs = 1_200; · 10 unmodified lines
2332 await waitForResources({
2433 baseDir: desktopDir,
2534 files: requiredFiles,
35+ tcpHost: devServer.hostname,
2636 tcpPort: port,
2737 });
2838
@@ -62,10 +72,7 @@ function startApp() { · 33 unmodified lines
6272 [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
6373 {
6474 cwd: desktopDir,
65− env: {
66− ...childEnv,
67− VITE_DEV_SERVER_URL: devServerUrl,
68− },
75+ env: childEnv,
6976 stdio: "inherit",
7077 },
7178 );
apps/desktop/scripts/electron-launcher.mjs+1−1
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url"; · 17 unmodified lines
1818
1919 const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
2020 const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
21−const APP_BUNDLE_ID = "com.t3tools.t3code";
21+const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
2222 const LAUNCHER_VERSION = 1;
2323
2424 const __dirname = dirname(fileURLToPath(import.meta.url));
apps/desktop/src/backendPort.test.ts+109−0
@@ -0,0 +1,109 @@
1+import { describe, expect, it, vi } from "vitest";
2+
3+import { resolveDesktopBackendPort } from "./backendPort";
4+
5+describe("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 @@
1+import * as Effect from "effect/Effect";
2+import { NetService } from "@t3tools/shared/Net";
3+
4+export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
5+const MAX_TCP_PORT = 65_535;
6+
7+export 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+
15+const 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+
22+const isValidPort = (port: number): boolean =>
23+ Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
24+
25+const 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+
37+async 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+
51+export 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 @@
1+import { describe, expect, it, vi } from "vitest";
2+
3+import {
4+ BackendReadinessAbortedError,
5+ isBackendReadinessAborted,
6+ waitForHttpReady,
7+} from "./backendReadiness";
8+
9+describe("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 @@
1+export 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+
9+const DEFAULT_TIMEOUT_MS = 10_000;
10+const DEFAULT_INTERVAL_MS = 100;
11+const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
12+
13+export class BackendReadinessAbortedError extends Error {
14+ constructor() {
15+ super("Backend readiness wait was aborted.");
16+ this.name = "BackendReadinessAbortedError";
17+ }
18+}
19+
20+function 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+
47+export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError {
48+ return error instanceof BackendReadinessAbortedError;
49+}
50+
51+export 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 @@
1+import * as fs from "node:fs";
2+import * as os from "node:os";
3+import * as path from "node:path";
4+
5+import {
6+ EnvironmentId,
7+ type ClientSettings,
8+ type PersistedSavedEnvironmentRecord,
9+} from "@t3tools/contracts";
10+import { afterEach, describe, expect, it } from "vitest";
11+
12+import {
13+ readClientSettings,
14+ readSavedEnvironmentRegistry,
15+ readSavedEnvironmentSecret,
16+ removeSavedEnvironmentSecret,
17+ writeClientSettings,
18+ writeSavedEnvironmentRegistry,
19+ writeSavedEnvironmentSecret,
20+ type DesktopSecretStorage,
21+} from "./clientPersistence";
22+
23+const tempDirectories: string[] = [];
24+
25+afterEach(() => {
26+ for (const directory of tempDirectories.splice(0)) {
27+ fs.rmSync(directory, { recursive: true, force: true });
28+ }
29+});
30+
31+function 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+
37+function 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+
51+const clientSettings: ClientSettings = {
52+ confirmThreadArchive: true,
53+ confirmThreadDelete: false,
54+ diffWordWrap: true,
55+ sidebarProjectSortOrder: "manual",
56+ sidebarThreadSortOrder: "created_at",
57+ timestampFormat: "24-hour",
58+};
59+
60+const 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+
69+describe("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 @@
1+import * as FS from "node:fs";
2+import * as Path from "node:path";
3+
4+import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
5+import { Predicate } from "effect";
6+
7+interface ClientSettingsDocument {
8+ readonly settings: ClientSettings;
9+}
10+
11+interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
12+ readonly encryptedBearerToken?: string;
13+}
14+
15+interface SavedEnvironmentRegistryDocument {
16+ readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
17+}
18+
19+export interface DesktopSecretStorage {
20+ readonly isEncryptionAvailable: () => boolean;
21+ readonly encryptString: (value: string) => Buffer;
22+ readonly decryptString: (value: Buffer) => string;
23+}
24+
25+function 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+
36+function 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+
44+function 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+
59+function 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+
72+function 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+
85+export function readClientSettings(settingsPath: string): ClientSettings | null {
86+ return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
87+}
88+
89+export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
90+ writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
91+}
92+
93+export function readSavedEnvironmentRegistry(
94+ registryPath: string,
95+): readonly PersistedSavedEnvironmentRecord[] {
96+ return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
97+ toPersistedSavedEnvironmentRecord(record),
98+ );
99+}
100+
101+export 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+
131+export 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+
155+export 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+
193+export 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 @@
1+import * as fs from "node:fs";
2+import * as os from "node:os";
3+import * as path from "node:path";
4+
5+import { afterEach, describe, expect, it } from "vitest";
6+
7+import {
8+ DEFAULT_DESKTOP_SETTINGS,
9+ readDesktopSettings,
10+ setDesktopServerExposurePreference,
11+ writeDesktopSettings,
12+} from "./desktopSettings";
13+
14+const tempDirectories: string[] = [];
15+
16+afterEach(() => {
17+ for (const directory of tempDirectories.splice(0)) {
18+ fs.rmSync(directory, { recursive: true, force: true });
19+ }
20+});
21+
22+function 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+
28+describe("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 @@
1+import * as FS from "node:fs";
2+import * as Path from "node:path";
3+import type { DesktopServerExposureMode } from "@t3tools/contracts";
4+
5+export interface DesktopSettings {
6+ readonly serverExposureMode: DesktopServerExposureMode;
7+}
8+
9+export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
10+ serverExposureMode: "local-only",
11+};
12+
13+export 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+
25+export 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+
45+export 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
77 import {
88 app,
99 BrowserWindow,
10+ clipboard,
1011 dialog,
1112 ipcMain,
1213 Menu,
1314 nativeImage,
1415 nativeTheme,
1516 protocol,
17+ safeStorage,
1618 shell,
1719 } from "electron";
1820 import type { MenuItemConstructorOptions } from "electron";
19−import * as Effect from "effect/Effect";
2021 import type {
22+ ClientSettings,
2123 DesktopTheme,
24+ DesktopServerExposureMode,
25+ DesktopServerExposureState,
26+ PersistedSavedEnvironmentRecord,
2227 DesktopUpdateActionResult,
2328 DesktopUpdateCheckResult,
2429 DesktopUpdateState,
@@ -26,9 +31,27 @@ import type { · 1 unmodified line
2631 import { autoUpdater } from "electron-updater";
2732
2833 import type { ContextMenuItem } from "@t3tools/contracts";
29−import { NetService } from "@t3tools/shared/Net";
3034 import { RotatingFileSink } from "@t3tools/shared/logging";
35+import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
36+import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
37+import {
38+ DEFAULT_DESKTOP_SETTINGS,
39+ readDesktopSettings,
40+ setDesktopServerExposurePreference,
41+ writeDesktopSettings,
42+} from "./desktopSettings";
43+import {
44+ readClientSettings,
45+ readSavedEnvironmentRegistry,
46+ readSavedEnvironmentSecret,
47+ removeSavedEnvironmentSecret,
48+ writeClientSettings,
49+ writeSavedEnvironmentRegistry,
50+ writeSavedEnvironmentSecret,
51+} from "./clientPersistence";
52+import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
3153 import { showDesktopConfirmDialog } from "./confirmDialog";
54+import { resolveDesktopServerExposure } from "./serverExposure";
3255 import { syncShellEnvironment } from "./syncShellEnvironment";
3356 import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
3457 import {
@@ -58,14 +81,26 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; · 23 unmodified lines
5881 const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
5982 const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
6083 const UPDATE_CHECK_CHANNEL = "desktop:update-check";
61−const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
84+const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
85+const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
86+const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
87+const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
88+const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
89+const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
90+const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
91+const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
92+const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
93+const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
6294 const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
6395 const STATE_DIR = Path.join(BASE_DIR, "userdata");
96+const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
97+const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
98+const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
6499 const DESKTOP_SCHEME = "t3";
65100 const ROOT_DIR = Path.resolve(__dirname, "../../..");
66101 const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
67102 const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
68−const APP_USER_MODEL_ID = "com.t3tools.t3code";
103+const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
69104 const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
70105 const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
71106 const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
@@ -76,10 +111,13 @@ const LOG_DIR = Path.join(STATE_DIR, "logs"); · 4 unmodified lines
76111 const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
77112 const LOG_FILE_MAX_FILES = 10;
78113 const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
114+const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
79115 const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
80116 const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
81117 const DESKTOP_UPDATE_CHANNEL = "latest";
82118 const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
119+const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
120+const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
83121
84122 type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
85123 type LinuxDesktopNamedApp = Electron.App & {
@@ -89,8 +127,13 @@ type LinuxDesktopNamedApp = Electron.App & { · 3 unmodified lines
89127 let mainWindow: BrowserWindow | null = null;
90128 let backendProcess: ChildProcess.ChildProcess | null = null;
91129 let backendPort = 0;
92−let backendAuthToken = "";
130+let backendBindHost = DESKTOP_LOOPBACK_HOST;
131+let backendBootstrapToken = "";
132+let backendHttpUrl = "";
93133 let backendWsUrl = "";
134+let backendEndpointUrl: string | null = null;
135+let backendAdvertisedHost: string | null = null;
136+let backendReadinessAbortController: AbortController | null = null;
94137 let restartAttempt = 0;
95138 let restartTimer: ReturnType<typeof setTimeout> | null = null;
96139 let isQuitting = false;
@@ -99,8 +142,12 @@ let aboutCommitHashCache: string | null | undefined; · 2 unmodified lines
99142 let desktopLogSink: RotatingFileSink | null = null;
100143 let backendLogSink: RotatingFileSink | null = null;
101144 let restoreStdIoCapture: (() => void) | null = null;
145+let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
146+let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
147+let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
102148
103149 let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
150+const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
104151 const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
105152 platform: process.platform,
106153 processArch: process.arch,
@@ -121,17 +168,143 @@ function sanitizeLogValue(value: string): string { · 14 unmodified lines
121168 return value.replace(/\s+/g, " ").trim();
122169 }
123170
171+function 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+
186+function 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+
199+function 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+
124208 function backendChildEnv(): NodeJS.ProcessEnv {
125209 const env = { ...process.env };
126210 delete env.T3CODE_PORT;
127− delete env.T3CODE_AUTH_TOKEN;
128211 delete env.T3CODE_MODE;
129212 delete env.T3CODE_NO_BROWSER;
130213 delete env.T3CODE_HOST;
131214 delete env.T3CODE_DESKTOP_WS_URL;
215+ delete env.T3CODE_DESKTOP_LAN_ACCESS;
216+ delete env.T3CODE_DESKTOP_LAN_HOST;
132217 return env;
133218 }
134219
220+function getDesktopServerExposureState(): DesktopServerExposureState {
221+ return {
222+ mode: desktopServerExposureMode,
223+ endpointUrl: backendEndpointUrl,
224+ advertisedHost: backendAdvertisedHost,
225+ };
226+}
227+
228+function 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+
236+function resolveAdvertisedHostOverride(): string | undefined {
237+ const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim();
238+ return override && override.length > 0 ? override : undefined;
239+}
240+
241+async 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+
281+function 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+
135308 function writeDesktopLogHeader(message: string): void {
136309 if (!desktopLogSink) return;
137310 desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
@@ -179,6 +352,27 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null { · 41 unmodified lines
179352 return null;
180353 }
181354
355+async 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+
371+function cancelBackendReadinessWait(): void {
372+ backendReadinessAbortController?.abort();
373+ backendReadinessAbortController = null;
374+}
375+
182376 function writeDesktopStreamChunk(
183377 streamName: "stdout" | "stderr",
184378 chunk: unknown,
@@ -523,10 +717,7 @@ function dispatchMenuAction(action: string): void { · 338 unmodified lines
523717 const send = () => {
524718 if (targetWindow.isDestroyed()) return;
525719 targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
526− if (!targetWindow.isVisible()) {
527− targetWindow.show();
528− }
529− targetWindow.focus();
720+ revealWindow(targetWindow);
530721 };
531722
532723 if (targetWindow.webContents.isLoadingMainFrame()) {
@@ -538,12 +729,15 @@ function dispatchMenuAction(action: string): void { · 5 unmodified lines
538729 }
539730
540731 function handleCheckForUpdatesMenuClick(): void {
732+ const hasUpdateFeedConfig =
733+ readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
541734 const disabledReason = getAutoUpdateDisabledReason({
542735 isDevelopment,
543736 isPackaged: app.isPackaged,
544737 platform: process.platform,
545738 appImage: process.env.APPIMAGE,
546739 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
740+ hasUpdateFeedConfig,
547741 });
548742 if (disabledReason) {
549743 console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
@@ -747,6 +941,26 @@ function clearUpdatePollTimer(): void { · 197 unmodified lines
747941 }
748942 }
749943
944+function 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+
750964 function emitUpdateState(): void {
751965 for (const window of BrowserWindow.getAllWindows()) {
752966 if (window.isDestroyed()) continue;
@@ -760,6 +974,8 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void { · 7 unmodified lines
760974 }
761975
762976 function shouldEnableAutoUpdates(): boolean {
977+ const hasUpdateFeedConfig =
978+ readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
763979 return (
764980 getAutoUpdateDisabledReason({
765981 isDevelopment,
@@ -767,6 +983,7 @@ function shouldEnableAutoUpdates(): boolean { · 1 unmodified line
767983 platform: process.platform,
768984 appImage: process.env.APPIMAGE,
769985 disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
986+ hasUpdateFeedConfig,
770987 }) === null
771988 );
772989 }
@@ -850,17 +1067,6 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed · 77 unmodified lines
8501067 }
8511068
8521069 function 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−
8641070 const githubToken =
8651071 process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
8661072 if (githubToken) {
@@ -885,6 +1091,17 @@ function configureAutoUpdater(): void { · 18 unmodified lines
8851091 });
8861092 }
8871093
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+
8881105 autoUpdater.autoDownload = false;
8891106 autoUpdater.autoInstallOnAppQuit = false;
8901107 // Keep alpha branding, but force all installs onto the stable update track.
@@ -988,6 +1205,7 @@ function scheduleBackendRestart(reason: string): void { · 97 unmodified lines
9881205 function startBackend(): void {
9891206 if (isQuitting || backendProcess) return;
9901207
1208+ backendObservabilitySettings = readPersistedBackendObservabilitySettings();
9911209 const backendEntry = resolveBackendEntry();
9921210 if (!FS.existsSync(backendEntry)) {
9931211 scheduleBackendRestart(`missing server entry at ${backendEntry}`);
@@ -1015,7 +1233,14 @@ function startBackend(): void { · 21 unmodified lines
10151233 noBrowser: true,
10161234 port: backendPort,
10171235 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+ : {}),
10191244 })}\n`,
10201245 );
10211246 bootstrapStream.end();
@@ -1042,27 +1267,33 @@ function startBackend(): void { · 20 unmodified lines
10421267 });
10431268
10441269 child.on("error", (error) => {
1270+ const wasExpected = expectedBackendExitChildren.has(child);
10451271 if (backendProcess === child) {
10461272 backendProcess = null;
10471273 }
10481274 closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
1275+ if (wasExpected) {
1276+ return;
1277+ }
10491278 scheduleBackendRestart(error.message);
10501279 });
10511280
10521281 child.on("exit", (code, signal) => {
1282+ const wasExpected = expectedBackendExitChildren.has(child);
10531283 if (backendProcess === child) {
10541284 backendProcess = null;
10551285 }
10561286 closeBackendSession(
10571287 `pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
10581288 );
1059− if (isQuitting) return;
1289+ if (isQuitting || wasExpected) return;
10601290 const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
10611291 scheduleBackendRestart(reason);
10621292 });
10631293 }
10641294
10651295 function stopBackend(): void {
1296+ cancelBackendReadinessWait();
10661297 if (restartTimer) {
10671298 clearTimeout(restartTimer);
10681299 restartTimer = null;
@@ -1073,6 +1304,7 @@ function stopBackend(): void { · 4 unmodified lines
10731304 if (!child) return;
10741305
10751306 if (child.exitCode === null && child.signalCode === null) {
1307+ expectedBackendExitChildren.add(child);
10761308 child.kill("SIGTERM");
10771309 setTimeout(() => {
10781310 if (child.exitCode === null && child.signalCode === null) {
@@ -1083,6 +1315,7 @@ function stopBackend(): void { · 4 unmodified lines
10831315 }
10841316
10851317 async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
1318+ cancelBackendReadinessWait();
10861319 if (restartTimer) {
10871320 clearTimeout(restartTimer);
10881321 restartTimer = null;
@@ -1093,6 +1326,7 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> { · 4 unmodified lines
10931326 if (!child) return;
10941327 const backendChild = child;
10951328 if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
1329+ expectedBackendExitChildren.add(backendChild);
10961330
10971331 await new Promise<void>((resolve) => {
10981332 let settled = false;
@@ -1134,9 +1368,116 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> { · 35 unmodified lines
11341368 }
11351369
11361370 function registerIpcHandlers(): void {
1137− ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
1138− ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
1139− event.returnValue = backendWsUrl;
1371+ ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
1372+ ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
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;
11401481 });
11411482
11421483 ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
@@ -1304,14 +1645,19 @@ function getIconOption(): { icon: string } | Record<string, never> { · 161 unmodified lines
13041645 return iconPath ? { icon: iconPath } : {};
13051646 }
13061647
1648+function getInitialWindowBackgroundColor(): string {
1649+ return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
1650+}
1651+
13071652 function createWindow(): BrowserWindow {
13081653 const window = new BrowserWindow({
13091654 width: 1100,
13101655 height: 780,
13111656 minWidth: 840,
13121657 minHeight: 620,
1313− show: false,
1658+ show: isDevelopment,
13141659 autoHideMenuBar: true,
1660+ backgroundColor: getInitialWindowBackgroundColor(),
13151661 ...getIconOption(),
13161662 title: APP_DISPLAY_NAME,
13171663 titleBarStyle: "hiddenInset",
@@ -1342,6 +1688,22 @@ function createWindow(): BrowserWindow { · 24 unmodified lines
13421688 menuTemplate.push({ type: "separator" });
13431689 }
13441690
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+
13451707 menuTemplate.push(
13461708 { role: "cut", enabled: params.editFlags.canCut },
13471709 { role: "copy", enabled: params.editFlags.canCopy },
@@ -1368,15 +1730,20 @@ function createWindow(): BrowserWindow { · 20 unmodified lines
13681730 window.setTitle(APP_DISPLAY_NAME);
13691731 emitUpdateState();
13701732 });
1371− window.once("ready-to-show", () => {
1372− window.show();
1373− });
1733+ if (!isDevelopment) {
1734+ window.once("ready-to-show", () => {
1735+ revealWindow(window);
1736+ });
1737+ }
13741738
13751739 if (isDevelopment) {
1376− void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
1740+ void window.loadURL(resolveDesktopDevServerUrl());
13771741 window.webContents.openDevTools({ mode: "detach" });
1742+ setImmediate(() => {
1743+ revealWindow(window);
1744+ });
13781745 } else {
1379− void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
1746+ void window.loadURL(resolveDesktopWindowUrl());
13801747 }
13811748
13821749 window.on("closed", () => {
@@ -1388,6 +1755,14 @@ function createWindow(): BrowserWindow { · 5 unmodified lines
13881755 return window;
13891756 }
13901757
1758+function resolveDesktopWindowUrl(): string {
1759+ if (backendHttpUrl) {
1760+ return backendHttpUrl;
1761+ }
1762+
1763+ return `${DESKTOP_SCHEME}://app`;
1764+}
1765+
13911766 // Override Electron's userData path before the `ready` event so that
13921767 // Chromium session data uses a filesystem-friendly directory name.
13931768 // Must be called synchronously at the top level — before `app.whenReady()`.
@@ -1397,21 +1772,72 @@ configureAppIdentity(); · 3 unmodified lines
13971772
13981773 async function bootstrap(): Promise<void> {
13991774 writeDesktopLogHeader("bootstrap start");
1400− backendPort = await Effect.service(NetService).pipe(
1401− Effect.flatMap((net) => net.reserveLoopbackPort()),
1402− Effect.provide(NetService.layer),
1403− Effect.runPromise,
1775+ const configuredBackendPort = resolveConfiguredDesktopBackendPort(process.env.T3CODE_PORT);
1776+ if (isDevelopment && configuredBackendPort === undefined) {
1777+ throw new Error("T3CODE_PORT is required in desktop development.");
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}`,
14041791 );
1405− writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
1406− backendAuthToken = Crypto.randomBytes(24).toString("hex");
1407− const baseUrl = `ws://127.0.0.1:${backendPort}`;
1408− backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
1409− writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
1792+ backendBootstrapToken = Crypto.randomBytes(24).toString("hex");
1793+ if (desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode) {
1794+ writeDesktopLogHeader(
1795+ `bootstrap restoring persisted server exposure mode mode=${desktopSettings.serverExposureMode}`,
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+ }
14101814
14111815 registerIpcHandlers();
14121816 writeDesktopLogHeader("bootstrap ipc handlers registered");
14131817 startBackend();
14141818 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");
14151841 mainWindow = createWindow();
14161842 writeDesktopLogHeader("bootstrap main window created");
14171843 }
@@ -1421,6 +1847,7 @@ app.on("before-quit", () => { · 3 unmodified lines
14211847 updateInstallInFlight = false;
14221848 writeDesktopLogHeader("before-quit received");
14231849 clearUpdatePollTimer();
1850+ cancelBackendReadinessWait();
14241851 stopBackend();
14251852 restoreStdIoCapture?.();
14261853 });
@@ -1434,13 +1861,19 @@ app · 7 unmodified lines
14341861 registerDesktopProtocol();
14351862 configureAutoUpdater();
14361863 void bootstrap().catch((error) => {
1864+ if (isBackendReadinessAborted(error) && isQuitting) {
1865+ return;
1866+ }
14371867 handleFatalStartupError("bootstrap", error);
14381868 });
14391869
14401870 app.on("activate", () => {
1441− if (BrowserWindow.getAllWindows().length === 0) {
1442− mainWindow = createWindow();
1871+ const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0];
1872+ if (existingWindow) {
1873+ revealWindow(existingWindow);
1874+ return;
14431875 }
1876+ mainWindow = createWindow();
14441877 });
14451878 })
14461879 .catch((error) => {
@@ -1459,6 +1892,7 @@ if (process.platform !== "win32") { · 12 unmodified lines
14591892 isQuitting = true;
14601893 writeDesktopLogHeader("SIGINT received");
14611894 clearUpdatePollTimer();
1895+ cancelBackendReadinessWait();
14621896 stopBackend();
14631897 restoreStdIoCapture?.();
14641898 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
1212 const UPDATE_CHECK_CHANNEL = "desktop:update-check";
1313 const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
1414 const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
15−const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
15+const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
16+const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
17+const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
18+const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
19+const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
20+const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
21+const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
22+const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
23+const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
24+const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
1625
1726 contextBridge.exposeInMainWorld("desktopBridge", {
18− getWsUrl: () => {
19− const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
20− return typeof result === "string" ? result : null;
27+ getLocalEnvironmentBootstrap: () => {
28+ const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
29+ if (typeof result !== "object" || result === null) {
30+ return null;
31+ }
32+ return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
2133 },
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),
2247 pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
2348 confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
2449 setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
apps/desktop/src/serverExposure.test.ts+139−0
@@ -0,0 +1,139 @@
1+import { describe, expect, it } from "vitest";
2+
3+import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
4+
5+describe("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+
77+describe("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 @@
1+import type { NetworkInterfaceInfo } from "node:os";
2+import type { DesktopServerExposureMode } from "@t3tools/contracts";
3+
4+const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
5+const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
6+
7+export 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+
16+const normalizeOptionalHost = (value: string | undefined): string | undefined => {
17+ const normalized = value?.trim();
18+ return normalized && normalized.length > 0 ? normalized : undefined;
19+};
20+
21+const isUsableLanIpv4Address = (address: string): boolean =>
22+ !address.startsWith("127.") && !address.startsWith("169.254.");
23+
24+export 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+
47+export 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
7171 platform: "darwin",
7272 appImage: undefined,
7373 disabledByEnv: false,
74+ hasUpdateFeedConfig: true,
7475 }),
7576 ).toContain("packaged production builds");
7677 });
7778
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+
78105 it("reports env-disabled auto updates", () => {
79106 expect(
80107 getAutoUpdateDisabledReason({
@@ -83,6 +110,7 @@ describe("getAutoUpdateDisabledReason", () => { · 2 unmodified lines
83110 platform: "darwin",
84111 appImage: undefined,
85112 disabledByEnv: true,
113+ hasUpdateFeedConfig: true,
86114 }),
87115 ).toContain("T3CODE_DISABLE_AUTO_UPDATE");
88116 });
@@ -95,6 +123,7 @@ describe("getAutoUpdateDisabledReason", () => { · 6 unmodified lines
95123 platform: "linux",
96124 appImage: undefined,
97125 disabledByEnv: false,
126+ hasUpdateFeedConfig: true,
98127 }),
99128 ).toContain("AppImage");
100129 });
apps/desktop/src/updateState.ts+4−0
@@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: { · 33 unmodified lines
3434 platform: NodeJS.Platform;
3535 appImage?: string | undefined;
3636 disabledByEnv: boolean;
37+ hasUpdateFeedConfig: boolean;
3738 }): string | null {
39+ if (!args.hasUpdateFeedConfig) {
40+ return "Automatic updates are not available because no update feed is configured.";
41+ }
3842 if (args.isDevelopment || !args.isPackaged) {
3943 return "Automatic updates are only available in packaged production builds.";
4044 }
apps/marketing/src/pages/download.astro+5−4
@@ -1,5 +1,6 @@
11 ---
22 import Layout from "../layouts/Layout.astro";
3+import { RELEASES_URL } from "../lib/releases";
34 ---
45
56 <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
1718 <h2 class="platform-name">macOS</h2>
1819 </div>
1920 <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}>
2122 <span class="card-arch">Apple Silicon (arm64)</span>
2223 <span class="card-format">.dmg</span>
2324 </a>
24− <a class="download-card" data-asset="x64.dmg" href="#">
25+ <a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
2526 <span class="card-arch">Intel (x64)</span>
2627 <span class="card-format">.dmg</span>
2728 </a>
@@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro"; · 7 unmodified lines
3536 <h2 class="platform-name">Windows</h2>
3637 </div>
3738 <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}>
3940 <span class="card-arch">Windows 10, 11</span>
4041 <span class="card-format">.exe</span>
4142 </a>
@@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro"; · 7 unmodified lines
4950 <h2 class="platform-name">Linux</h2>
5051 </div>
5152 <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}>
5354 <span class="card-arch">x86_64</span>
5455 <span class="card-format">AppImage</span>
5556 </a>
apps/server/integration/OrchestrationEngineHarness.integration.ts+23−4
@@ -26,6 +26,7 @@ import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore · 25 unmodified lines
2626 import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
2727 import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
2828 import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
29+import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
2930 import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
3031 import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
3132 import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
@@ -46,10 +47,11 @@ import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts"; · 14 unmodified lines
4647 import { ProviderService } from "../src/provider/Services/ProviderService.ts";
4748 import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
4849 import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
50+import { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.ts";
4951 import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
5052 import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
5153 import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
52−import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
54+import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
5355 import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
5456 import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
5557 import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
@@ -299,7 +301,7 @@ export const makeOrchestrationIntegrationHarness = ( · 243 unmodified lines
299301 ProjectionTurnRepositoryLive,
300302 checkpointStoreLayer,
301303 providerLayer,
302− RuntimeReceiptBusLive,
304+ RuntimeReceiptBusTest,
303305 );
304306 const serverSettingsLayer = ServerSettingsService.layerTest();
305307 const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
@@ -322,6 +324,22 @@ export const makeOrchestrationIntegrationHarness = ( · 16 unmodified lines
322324 );
323325 const checkpointReactorLayer = CheckpointReactorLive.pipe(
324326 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+ ),
325343 Layer.provideMerge(
326344 WorkspaceEntriesLive.pipe(
327345 Layer.provide(WorkspacePathsLive),
@@ -340,6 +358,7 @@ export const makeOrchestrationIntegrationHarness = ( · 12 unmodified lines
340358 Layer.provideMerge(runtimeServicesLayer),
341359 Layer.provideMerge(orchestrationReactorLayer),
342360 Layer.provide(persistenceLayer),
361+ Layer.provideMerge(RepositoryIdentityResolverLive),
343362 Layer.provideMerge(ServerSettingsService.layerTest()),
344363 Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
345364 Layer.provideMerge(NodeServices.layer),
@@ -378,7 +397,7 @@ export const makeOrchestrationIntegrationHarness = ( · 32 unmodified lines
378397 runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
379398 ).pipe(Effect.orDie);
380399 const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
381− yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
400+ yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
382401 Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
383402 ).pipe(Effect.forkIn(scope));
384403 yield* Effect.sleep(10);
@@ -421,7 +440,7 @@ export const makeOrchestrationIntegrationHarness = ( · 36 unmodified lines
421440 ) =>
422441 waitFor(
423442 pendingApprovalRepository
424− .getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
443+ .getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
425444 .pipe(
426445 Effect.map((row) =>
427446 Option.match(row, {
apps/server/integration/TestProviderAdapter.integration.ts+3−3
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter · 288 unmodified lines
289289
290290 state.turnCount += 1;
291291 const turnCount = state.turnCount;
292− const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
292+ const turnId = TurnId.make(`turn-${turnCount}`);
293293
294294 const response = state.queuedResponses.shift();
295295 if (!response) {
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter · 11 unmodified lines
307307 ...(fixtureEvent as Record<string, unknown>),
308308 eventId: randomUUID(),
309309 provider,
310− sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
310+ sessionId: RuntimeSessionId.make(String(input.threadId)),
311311 createdAt: nowIso(),
312312 };
313313 rawEvent.threadId = state.snapshot.threadId;
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter · 49 unmodified lines
363363 if (deferredTurnCompletedEvents.length === 0) {
364364 yield* emit({
365365 type: "turn.completed",
366− eventId: EventId.makeUnsafe(randomUUID()),
366+ eventId: EventId.make(randomUUID()),
367367 provider,
368368 createdAt: nowIso(),
369369 threadId: state.snapshot.threadId,
apps/server/integration/fixtures/providerRuntime.ts+2−2
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const; · 4 unmodified lines
55 const SESSION_ID = "fixture-session";
66 const THREAD_ID = "fixture-thread";
77 const TURN_ID = "fixture-turn";
8−const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
8+const REQUEST_ID = RuntimeRequestId.make("req-1");
99
1010 function baseEvent(
1111 eventId: string,
1212 createdAt: string,
1313 ): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
1414 return {
15− eventId: EventId.makeUnsafe(eventId),
15+ eventId: EventId.make(eventId),
1616 provider: PROVIDER,
1717 sessionId: SESSION_ID,
1818 createdAt,
apps/server/integration/orchestrationEngine.integration.test.ts+18−19
@@ -30,14 +30,13 @@ import type { · 29 unmodified lines
3030 } from "../src/orchestration/Services/RuntimeReceiptBus.ts";
3131 import * as NodeServices from "@effect/platform-node/NodeServices";
3232
33−const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
34−const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
35−const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
36−const asApprovalRequestId = (value: string): ApprovalRequestId =>
37− ApprovalRequestId.makeUnsafe(value);
33+const asMessageId = (value: string): MessageId => MessageId.make(value);
34+const asProjectId = (value: string): ProjectId => ProjectId.make(value);
35+const asEventId = (value: string): EventId => EventId.make(value);
36+const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
3837
3938 const PROJECT_ID = asProjectId("project-1");
40−const THREAD_ID = ThreadId.makeUnsafe("thread-1");
39+const THREAD_ID = ThreadId.make("thread-1");
4140 const FIXTURE_TURN_ID = "fixture-turn";
4241 const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
4342 type IntegrationProvider = ProviderKind;
@@ -112,7 +111,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => · 68 unmodified lines
112111
113112 yield* harness.engine.dispatch({
114113 type: "project.create",
115− commandId: CommandId.makeUnsafe("cmd-project-create"),
114+ commandId: CommandId.make("cmd-project-create"),
116115 projectId: PROJECT_ID,
117116 title: "Integration Project",
118117 workspaceRoot: harness.workspaceDir,
@@ -125,7 +124,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) => · 6 unmodified lines
125124
126125 yield* harness.engine.dispatch({
127126 type: "thread.create",
128− commandId: CommandId.makeUnsafe("cmd-thread-create"),
127+ commandId: CommandId.make("cmd-thread-create"),
129128 threadId: THREAD_ID,
130129 projectId: PROJECT_ID,
131130 title: "Integration Thread",
@@ -150,7 +149,7 @@ const startTurn = (input: { · 18 unmodified lines
150149 }) =>
151150 input.harness.engine.dispatch({
152151 type: "thread.turn.start",
153− commandId: CommandId.makeUnsafe(input.commandId),
152+ commandId: CommandId.make(input.commandId),
154153 threadId: THREAD_ID,
155154 message: {
156155 messageId: asMessageId(input.messageId),
@@ -261,7 +260,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( · 104 unmodified lines
261260
262261 yield* harness.engine.dispatch({
263262 type: "project.create",
264− commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
263+ commandId: CommandId.make("cmd-project-create-real-codex"),
265264 projectId: PROJECT_ID,
266265 title: "Integration Project",
267266 workspaceRoot: harness.workspaceDir,
@@ -274,7 +273,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( · 6 unmodified lines
274273
275274 yield* harness.engine.dispatch({
276275 type: "thread.create",
277− commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
276+ commandId: CommandId.make("cmd-thread-create-real-codex"),
278277 threadId: THREAD_ID,
279278 projectId: PROJECT_ID,
280279 title: "Integration Thread",
@@ -291,7 +290,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( · 10 unmodified lines
291290
292291 yield* harness.engine.dispatch({
293292 type: "thread.turn.start",
294− commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
293+ commandId: CommandId.make("cmd-turn-start-real-codex-1"),
295294 threadId: THREAD_ID,
296295 message: {
297296 messageId: asMessageId("msg-real-codex-1"),
@@ -318,7 +317,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)( · 20 unmodified lines
318317
319318 yield* harness.engine.dispatch({
320319 type: "thread.turn.start",
321− commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
320+ commandId: CommandId.make("cmd-turn-start-real-codex-2"),
322321 threadId: THREAD_ID,
323322 message: {
324323 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
583582
584583 yield* harness.engine.dispatch({
585584 type: "thread.approval.respond",
586− commandId: CommandId.makeUnsafe("cmd-approval-respond"),
585+ commandId: CommandId.make("cmd-approval-respond"),
587586 threadId: THREAD_ID,
588587 requestId: APPROVAL_REQUEST_ID,
589588 decision: "accept",
@@ -815,7 +814,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git · 225 unmodified lines
815814
816815 yield* harness.engine.dispatch({
817816 type: "thread.checkpoint.revert",
818− commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
817+ commandId: CommandId.make("cmd-checkpoint-revert"),
819818 threadId: THREAD_ID,
820819 turnCount: 1,
821820 createdAt: nowIso(),
@@ -875,7 +874,7 @@ it.live( · 53 unmodified lines
875874
876875 yield* harness.engine.dispatch({
877876 type: "thread.checkpoint.revert",
878− commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
877+ commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
879878 threadId: THREAD_ID,
880879 turnCount: 0,
881880 createdAt: nowIso(),
@@ -1119,7 +1118,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () => · 237 unmodified lines
11191118
11201119 yield* harness.engine.dispatch({
11211120 type: "thread.approval.respond",
1122− commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
1121+ commandId: CommandId.make("cmd-claude-approval-respond"),
11231122 threadId: THREAD_ID,
11241123 requestId: APPROVAL_REQUEST_ID,
11251124 decision: "accept",
@@ -1192,7 +1191,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () => · 66 unmodified lines
11921191
11931192 yield* harness.engine.dispatch({
11941193 type: "thread.turn.interrupt",
1195− commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
1194+ commandId: CommandId.make("cmd-turn-interrupt-claude"),
11961195 threadId: THREAD_ID,
11971196 createdAt: nowIso(),
11981197 });
@@ -1309,7 +1308,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state", · 110 unmodified lines
13091308
13101309 yield* harness.engine.dispatch({
13111310 type: "thread.checkpoint.revert",
1312− commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
1311+ commandId: CommandId.make("cmd-checkpoint-revert-claude"),
13131312 threadId: THREAD_ID,
13141313 turnCount: 1,
13151314 createdAt: nowIso(),
apps/server/integration/providerService.integration.test.ts+29−41
@@ -86,6 +86,7 @@ const collectEventsDuring = <A, E, R>( · 85 unmodified lines
8686 Effect.forkScoped,
8787 );
8888
89+ yield* Effect.sleep("50 millis");
8990 yield* action;
9091
9192 return yield* Effect.forEach(
@@ -104,7 +105,6 @@ const runTurn = (input: { · 12 unmodified lines
104105 }) =>
105106 Effect.gen(function* () {
106107 yield* input.harness.queueTurnResponse(input.threadId, input.response);
107−
108108 return yield* collectEventsDuring(
109109 input.provider.streamEvents,
110110 input.response.events.length,
@@ -116,21 +116,18 @@ const runTurn = (input: { · 5 unmodified lines
116116 );
117117 });
118118
119−it.effect("replays typed runtime fixture events", () =>
119+it.live("replays typed runtime fixture events", () =>
120120 Effect.gen(function* () {
121121 const fixture = yield* makeIntegrationFixture;
122122
123123 yield* Effect.gen(function* () {
124124 const provider = yield* ProviderService;
125− const session = yield* provider.startSession(
126− ThreadId.makeUnsafe("thread-integration-typed"),
127− {
128− threadId: ThreadId.makeUnsafe("thread-integration-typed"),
129− provider: "codex",
130− cwd: fixture.cwd,
131− runtimeMode: "full-access",
132− },
133− );
125+ const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
126+ threadId: ThreadId.make("thread-integration-typed"),
127+ provider: "codex",
128+ cwd: fixture.cwd,
129+ runtimeMode: "full-access",
130+ });
134131 assert.equal((session.threadId ?? "").length > 0, true);
135132
136133 const observedEvents = yield* runTurn({
@@ -149,7 +146,7 @@ it.effect("replays typed runtime fixture events", () => · 12 unmodified lines
149146 }).pipe(Effect.provide(NodeServices.layer)),
150147 );
151148
152−it.effect("replays file-changing fixture turn events", () =>
149+it.live("replays file-changing fixture turn events", () =>
153150 Effect.gen(function* () {
154151 const fixture = yield* makeIntegrationFixture;
155152 const { join } = yield* Path.Path;
@@ -157,15 +154,12 @@ it.effect("replays file-changing fixture turn events", () => · 1 unmodified line
157154
158155 yield* Effect.gen(function* () {
159156 const provider = yield* ProviderService;
160− const session = yield* provider.startSession(
161− ThreadId.makeUnsafe("thread-integration-tools"),
162− {
163− threadId: ThreadId.makeUnsafe("thread-integration-tools"),
164− provider: "codex",
165− cwd: fixture.cwd,
166− runtimeMode: "full-access",
167− },
168− );
157+ const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
158+ threadId: ThreadId.make("thread-integration-tools"),
159+ provider: "codex",
160+ cwd: fixture.cwd,
161+ runtimeMode: "full-access",
162+ });
169163 assert.equal((session.threadId ?? "").length > 0, true);
170164
171165 const observedEvents = yield* runTurn({
@@ -188,7 +182,7 @@ it.effect("replays file-changing fixture turn events", () => · 16 unmodified lines
188182 }).pipe(Effect.provide(NodeServices.layer)),
189183 );
190184
191−it.effect("runs multi-turn tool/approval flow", () =>
185+it.live("runs multi-turn tool/approval flow", () =>
192186 Effect.gen(function* () {
193187 const fixture = yield* makeIntegrationFixture;
194188 const { join } = yield* Path.Path;
@@ -196,15 +190,12 @@ it.effect("runs multi-turn tool/approval flow", () => · 1 unmodified line
196190
197191 yield* Effect.gen(function* () {
198192 const provider = yield* ProviderService;
199− const session = yield* provider.startSession(
200− ThreadId.makeUnsafe("thread-integration-multi"),
201− {
202− threadId: ThreadId.makeUnsafe("thread-integration-multi"),
203− provider: "codex",
204− cwd: fixture.cwd,
205− runtimeMode: "full-access",
206− },
207− );
193+ const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
194+ threadId: ThreadId.make("thread-integration-multi"),
195+ provider: "codex",
196+ cwd: fixture.cwd,
197+ runtimeMode: "full-access",
198+ });
208199 assert.equal((session.threadId ?? "").length > 0, true);
209200
210201 const firstTurnEvents = yield* runTurn({
@@ -242,7 +233,7 @@ it.effect("runs multi-turn tool/approval flow", () => · 31 unmodified lines
242233 }).pipe(Effect.provide(NodeServices.layer)),
243234 );
244235
245−it.effect("rolls back provider conversation state only", () =>
236+it.live("rolls back provider conversation state only", () =>
246237 Effect.gen(function* () {
247238 const fixture = yield* makeIntegrationFixture;
248239 const { join } = yield* Path.Path;
@@ -250,15 +241,12 @@ it.effect("rolls back provider conversation state only", () => · 1 unmodified line
250241
251242 yield* Effect.gen(function* () {
252243 const provider = yield* ProviderService;
253− const session = yield* provider.startSession(
254− ThreadId.makeUnsafe("thread-integration-rollback"),
255− {
256− threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
257− provider: "codex",
258− cwd: fixture.cwd,
259− runtimeMode: "full-access",
260− },
261− );
244+ const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
245+ threadId: ThreadId.make("thread-integration-rollback"),
246+ provider: "codex",
247+ cwd: fixture.cwd,
248+ runtimeMode: "full-access",
249+ });
262250 assert.equal((session.threadId ?? "").length > 0, true);
263251
264252 yield* runTurn({
apps/server/package.json+1−1
@@ -1,6 +1,6 @@
11 {
22 "name": "t3",
3− "version": "0.0.15",
3+ "version": "0.0.17",
44 "license": "MIT",
55 "repository": {
66 "type": "git",
apps/server/scripts/cli.ts+25−3
@@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog · 13 unmodified lines
1414 import rootPackageJson from "../../../package.json" with { type: "json" };
1515 import serverPackageJson from "../package.json" with { type: "json" };
1616
17+interface 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+
1733 class CliError extends Data.TaggedError("CliError")<{
1834 readonly message: string;
1935 readonly cause?: unknown;
@@ -177,7 +193,7 @@ const publishCmd = Command.make( · 157 unmodified lines
177193 const backupPath = `${packageJsonPath}.bak`;
178194
179195 // 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"]) {
181197 const abs = path.join(serverDir, relPath);
182198 if (!(yield* fs.exists(abs))) {
183199 return yield* new CliError({
@@ -192,7 +208,7 @@ const publishCmd = Command.make( · 8 unmodified lines
192208 // Resolve catalog dependencies before any file mutations. If this throws,
193209 // acquire fails and no release hook runs, so filesystem must still be untouched.
194210 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
195− const pkg = {
211+ const pkg: PackageJson = {
196212 name: serverPackageJson.name,
197213 repository: serverPackageJson.repository,
198214 bin: serverPackageJson.bin,
@@ -200,7 +216,8 @@ const publishCmd = Command.make( · 1 unmodified line
200216 version,
201217 engines: serverPackageJson.engines,
202218 files: serverPackageJson.files,
203− dependencies: serverPackageJson.dependencies as Record<string, unknown>,
219+ dependencies: serverPackageJson.dependencies,
220+ overrides: rootPackageJson.overrides,
204221 };
205222
206223 pkg.dependencies = resolveCatalogDependencies(
@@ -208,6 +225,11 @@ const publishCmd = Command.make( · 1 unmodified line
208225 rootPackageJson.workspaces.catalog,
209226 "apps/server dependencies",
210227 );
228+ pkg.overrides = resolveCatalogDependencies(
229+ pkg.overrides,
230+ rootPackageJson.workspaces.catalog,
231+ "root overrides",
232+ );
211233
212234 const original = yield* fs.readFileString(packageJsonPath);
213235 yield* fs.writeFileString(backupPath, original);
apps/server/src/auth/Layers/AuthControlPlane.test.ts+111−0
@@ -0,0 +1,111 @@
1+import * as NodeServices from "@effect/platform-node/NodeServices";
2+import { expect, it } from "@effect/vitest";
3+import { Effect, Layer } from "effect";
4+
5+import { ServerConfigShape } from "../../config.ts";
6+import { ServerConfig } from "../../config.ts";
7+import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
8+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
9+import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
10+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
11+import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
12+import { makeAuthControlPlane } from "./AuthControlPlane.ts";
13+import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
14+
15+const 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+
31+const 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+
42+it.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 @@
1+import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
2+import { DateTime, Effect, Layer } from "effect";
3+
4+import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
5+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
6+import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
7+import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
8+import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
9+import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
10+import {
11+ AuthControlPlane,
12+ AuthControlPlaneError,
13+ AuthControlPlaneShape,
14+ DEFAULT_SESSION_SUBJECT,
15+ IssuedBearerSession,
16+ IssuedPairingLink,
17+} from "../Services/AuthControlPlane.ts";
18+
19+const 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+
29+const toAuthControlPlaneError =
30+ (message: string) =>
31+ (cause: unknown): AuthControlPlaneError =>
32+ new AuthControlPlaneError({
33+ message,
34+ cause,
35+ });
36+
37+export 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+
163+export const AuthCoreLive = Layer.mergeAll(
164+ BootstrapCredentialServiceLive,
165+ SessionCredentialServiceLive,
166+);
167+
168+export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
169+
170+export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
171+
172+export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
173+
174+export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
175+ Layer.provideMerge(AuthRuntimeLive),
176+);
apps/server/src/auth/Layers/BootstrapCredentialService.test.ts+151−0
@@ -0,0 +1,151 @@
1+import * as NodeServices from "@effect/platform-node/NodeServices";
2+import { expect, it } from "@effect/vitest";
3+import { Duration, Effect, Layer } from "effect";
4+import { TestClock } from "effect/testing";
5+
6+import type { ServerConfigShape } from "../../config.ts";
7+import { ServerConfig } from "../../config.ts";
8+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
9+import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
10+import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
11+
12+const 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+
28+const makeBootstrapCredentialLayer = (
29+ overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
30+) =>
31+ BootstrapCredentialServiceLive.pipe(
32+ Layer.provide(SqlitePersistenceMemory),
33+ Layer.provide(makeServerConfigLayer(overrides)),
34+ );
35+
36+it.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 @@
1+import type { AuthPairingLink } from "@t3tools/contracts";
2+import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
3+import { Option } from "effect";
4+
5+import { ServerConfig } from "../../config.ts";
6+import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
7+import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
8+import {
9+ BootstrapCredentialError,
10+ BootstrapCredentialService,
11+ type BootstrapCredentialChange,
12+ type BootstrapCredentialServiceShape,
13+ type BootstrapGrant,
14+ type IssuedBootstrapCredential,
15+} from "../Services/BootstrapCredentialService.ts";
16+
17+interface StoredBootstrapGrant extends BootstrapGrant {
18+ readonly remainingUses: number | "unbounded";
19+}
20+
21+type 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+
32+const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
33+const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
34+const PAIRING_TOKEN_LENGTH = 12;
35+
36+const 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+
42+export 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+
293+export 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 @@
1+import * as NodeServices from "@effect/platform-node/NodeServices";
2+import { expect, it } from "@effect/vitest";
3+import { Effect, Layer } from "effect";
4+
5+import type { ServerConfigShape } from "../../config.ts";
6+import { ServerConfig } from "../../config.ts";
7+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
8+import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
9+import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";
10+import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";
11+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
12+
13+const 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+
25+const makeServerAuthLayer = (overrides?: Partial<ServerConfigShape>) =>
26+ ServerAuthLive.pipe(
27+ Layer.provide(SqlitePersistenceMemory),
28+ Layer.provide(ServerSecretStoreLive),
29+ Layer.provide(makeServerConfigLayer(overrides)),
30+ );
31+
32+const 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+
42+const requestMetadata = {
43+ deviceType: "desktop" as const,
44+ os: "macOS",
45+ browser: "Chrome",
46+ ipAddress: "192.168.1.23",
47+};
48+
49+it.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 @@
1+import {
2+ type AuthBearerBootstrapResult,
3+ type AuthClientSession,
4+ type AuthBootstrapResult,
5+ type AuthPairingCredentialResult,
6+ type AuthSessionState,
7+ type AuthWebSocketTokenResult,
8+} from "@t3tools/contracts";
9+import { DateTime, Effect, Layer, Option } from "effect";
10+import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
11+
12+import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
13+import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
14+import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
15+import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
16+import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
17+import {
18+ ServerAuth,
19+ type AuthenticatedSession,
20+ AuthError,
21+ type ServerAuthShape,
22+} from "../Services/ServerAuth.ts";
23+import {
24+ SessionCredentialError,
25+ SessionCredentialService,
26+} from "../Services/SessionCredentialService.ts";
27+import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
28+
29+type BootstrapExchangeResult = {
30+ readonly response: AuthBootstrapResult;
31+ readonly sessionToken: string;
32+};
33+
34+const AUTHORIZATION_PREFIX = "Bearer ";
35+const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
36+
37+export 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+
53+function 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+
62+export 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+
391+export 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 @@
1+import * as NodeServices from "@effect/platform-node/NodeServices";
2+import { expect, it } from "@effect/vitest";
3+import { Effect, Layer } from "effect";
4+
5+import type { ServerConfigShape } from "../../config.ts";
6+import { ServerConfig } from "../../config.ts";
7+import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
8+import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
9+
10+const 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+
28+it.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 @@
1+import type { ServerAuthDescriptor } from "@t3tools/contracts";
2+import { Effect, Layer } from "effect";
3+
4+import { ServerConfig } from "../../config.ts";
5+import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
6+import { resolveSessionCookieName } from "../utils.ts";
7+import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
8+
9+export 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+
44+export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
apps/server/src/auth/Layers/ServerSecretStore.test.ts+263−0
@@ -0,0 +1,263 @@
1+import * as NodeServices from "@effect/platform-node/NodeServices";
2+import { expect, it } from "@effect/vitest";
3+import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
4+import * as PlatformError from "effect/PlatformError";
5+
6+import { ServerConfig } from "../../config.ts";
7+import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";
8+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
9+
10+const makeServerConfigLayer = () =>
11+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });
12+
13+const makeServerSecretStoreLayer = () =>
14+ Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
15+
16+const 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+
37+const makePermissionDeniedSecretStoreLayer = () =>
38+ ServerSecretStoreLive.pipe(
39+ Layer.provide(makeServerConfigLayer()),
40+ Layer.provideMerge(PermissionDeniedFileSystemLayer),
41+ );
42+
43+const 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+
64+const makeRenameFailureSecretStoreLayer = () =>
65+ ServerSecretStoreLive.pipe(
66+ Layer.provide(makeServerConfigLayer()),
67+ Layer.provideMerge(RenameFailureFileSystemLayer),
68+ );
69+
70+const 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+
91+const makeRemoveFailureSecretStoreLayer = () =>
92+ ServerSecretStoreLive.pipe(
93+ Layer.provide(makeServerConfigLayer()),
94+ Layer.provideMerge(RemoveFailureFileSystemLayer),
95+ );
96+
97+const 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+
137+const makeConcurrentCreateSecretStoreLayer = () =>
138+ ServerSecretStoreLive.pipe(
139+ Layer.provide(makeServerConfigLayer()),
140+ Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
141+ );
142+
143+it.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 @@
1+import * as Crypto from "node:crypto";
2+
3+import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
4+import * as PlatformError from "effect/PlatformError";
5+
6+import { ServerConfig } from "../../config.ts";
7+import {
8+ SecretStoreError,
9+ ServerSecretStore,
10+ type ServerSecretStoreShape,
11+} from "../Services/ServerSecretStore.ts";
12+
13+export 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+
148+export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);
apps/server/src/auth/Layers/SessionCredentialService.test.ts+191−0
@@ -0,0 +1,191 @@
1+import * as NodeServices from "@effect/platform-node/NodeServices";
2+import { expect, it } from "@effect/vitest";
3+import { Duration, Effect, Layer } from "effect";
4+import { TestClock } from "effect/testing";
5+
6+import type { ServerConfigShape } from "../../config.ts";
7+import { ServerConfig } from "../../config.ts";
8+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
9+import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
10+import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
11+import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
12+
13+const 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+
27+const 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+
36+it.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 @@
1+import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
2+import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
3+import { Option } from "effect";
4+
5+import { ServerConfig } from "../../config.ts";
6+import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
7+import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
8+import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
9+import {
10+ SessionCredentialError,
11+ SessionCredentialService,
12+ type IssuedSession,
13+ type SessionCredentialChange,
14+ type SessionCredentialServiceShape,
15+ type VerifiedSession,
16+} from "../Services/SessionCredentialService.ts";
17+import {
18+ base64UrlDecodeUtf8,
19+ base64UrlEncode,
20+ resolveSessionCookieName,
21+ signPayload,
22+ timingSafeEqualBase64Url,
23+} from "../utils.ts";
24+
25+const SIGNING_SECRET_NAME = "server-signing-key";
26+const DEFAULT_SESSION_TTL = Duration.days(30);
27+const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
28+
29+const 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+});
39+type SessionClaims = typeof SessionClaims.Type;
40+
41+const 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+});
48+type WebSocketClaims = typeof WebSocketClaims.Type;
49+
50+const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
51+const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
52+
53+function createDefaultClientMetadata(): AuthClientMetadata {
54+ return {
55+ deviceType: "unknown",
56+ };
57+}
58+
59+function 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+
77+function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
78+ return {
79+ ...input,
80+ current: false,
81+ };
82+}
83+
84+export 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+
497+export 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 @@
1+import type {
2+ AuthClientMetadata,
3+ AuthClientSession,
4+ AuthPairingLink,
5+ AuthSessionId,
6+} from "@t3tools/contracts";
7+import { Data, DateTime, Duration, Effect, Context } from "effect";
8+import { SessionRole } from "./SessionCredentialService";
9+
10+export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
11+
12+export 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+
22+export 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+
32+export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{
33+ readonly message: string;
34+ readonly cause?: unknown;
35+}> {}
36+
37+export 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+
67+export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
68+ "t3/AuthControlPlane",
69+) {}
apps/server/src/auth/Services/BootstrapCredentialService.ts+57−0
@@ -0,0 +1,57 @@
1+import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
2+import { Data, DateTime, Duration, Context } from "effect";
3+import type { Effect, Stream } from "effect";
4+
5+export type BootstrapCredentialRole = "owner" | "client";
6+
7+export 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+
15+export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{
16+ readonly message: string;
17+ readonly status?: 401 | 500;
18+ readonly cause?: unknown;
19+}> {}
20+
21+export interface IssuedBootstrapCredential {
22+ readonly id: string;
23+ readonly credential: string;
24+ readonly label?: string;
25+ readonly expiresAt: DateTime.Utc;
26+}
27+
28+export type BootstrapCredentialChange =
29+ | {
30+ readonly type: "pairingLinkUpserted";
31+ readonly pairingLink: AuthPairingLink;
32+ }
33+ | {
34+ readonly type: "pairingLinkRemoved";
35+ readonly id: string;
36+ };
37+
38+export 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+
54+export 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 @@
1+import 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";
15+import { Data, DateTime, Context } from "effect";
16+import type { Effect } from "effect";
17+import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
18+import type { SessionRole } from "./SessionCredentialService.ts";
19+
20+export 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+
28+export class AuthError extends Data.TaggedError("AuthError")<{
29+ readonly message: string;
30+ readonly status?: 400 | 401 | 403 | 500;
31+ readonly cause?: unknown;
32+}> {}
33+
34+export 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+
82+export 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 @@
1+import type { ServerAuthDescriptor } from "@t3tools/contracts";
2+import { Context } from "effect";
3+import type { Effect } from "effect";
4+
5+export interface ServerAuthPolicyShape {
6+ readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
7+}
8+
9+export 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 @@
1+import { Data, Context } from "effect";
2+import type { Effect } from "effect";
3+
4+export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
5+ readonly message: string;
6+ readonly cause?: unknown;
7+}> {}
8+
9+export 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+
19+export 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 @@
1+import type {
2+ AuthClientMetadata,
3+ AuthClientSession,
4+ AuthSessionId,
5+ ServerAuthSessionMethod,
6+} from "@t3tools/contracts";
7+import { Data, DateTime, Duration, Context } from "effect";
8+import type { Effect, Stream } from "effect";
9+
10+export type SessionRole = "owner" | "client";
11+
12+export 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+
21+export 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+
31+export type SessionCredentialChange =
32+ | {
33+ readonly type: "clientUpserted";
34+ readonly clientSession: AuthClientSession;
35+ }
36+ | {
37+ readonly type: "clientRemoved";
38+ readonly sessionId: AuthSessionId;
39+ };
40+
41+export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{
42+ readonly message: string;
43+ readonly cause?: unknown;
44+}> {}
45+
46+export 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+
84+export 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 @@
1+import {
2+ type AuthBearerBootstrapResult,
3+ AuthBootstrapInput,
4+ AuthCreatePairingCredentialInput,
5+ AuthRevokeClientSessionInput,
6+ AuthRevokePairingLinkInput,
7+ type AuthWebSocketTokenResult,
8+} from "@t3tools/contracts";
9+import { DateTime, Effect, Schema } from "effect";
10+import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
11+
12+import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
13+import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
14+import { deriveAuthClientMetadata } from "./utils.ts";
15+
16+export 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+
32+export 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+
43+const 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+
49+function 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+
60+export 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+
93+export 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+
119+export 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+
133+export 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+
173+const 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+
186+export 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+
196+export 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+
216+export 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+
226+export 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+
246+export 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 @@
1+import { describe, expect, it } from "vitest";
2+
3+import { deriveAuthClientMetadata } from "./utils";
4+
5+describe("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 @@
1+import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";
2+import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
3+import * as Crypto from "node:crypto";
4+
5+const SESSION_COOKIE_NAME = "t3_session";
6+
7+export 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+
18+export 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+
23+export function base64UrlDecodeUtf8(input: string): string {
24+ return Buffer.from(input, "base64url").toString("utf8");
25+}
26+
27+export function signPayload(payload: string, secret: Uint8Array): string {
28+ return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
29+}
30+
31+export 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+
40+function 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+
48+function 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+
56+function 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+
74+function 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+
88+function 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+
101+function 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+
116+export 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
2626 worktreePath: input.worktreePath,
2727 checkpoints: [
2828 {
29− turnId: TurnId.makeUnsafe("turn-1"),
29+ turnId: TurnId.make("turn-1"),
3030 checkpointTurnCount: input.checkpointTurnCount,
3131 checkpointRef: input.checkpointRef,
3232 status: "ready",
@@ -40,8 +40,8 @@ function makeThreadCheckpointContext(input: { · 7 unmodified lines
4040
4141 describe("CheckpointDiffQueryLive", () => {
4242 it("computes diffs using canonical turn-0 checkpoint refs", async () => {
43− const projectId = ProjectId.makeUnsafe("project-1");
44− const threadId = ThreadId.makeUnsafe("thread-1");
43+ const projectId = ProjectId.make("project-1");
44+ const threadId = ThreadId.make("thread-1");
4545 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
4646 const hasCheckpointRefCalls: Array<CheckpointRef> = [];
4747 const diffCheckpointsCalls: Array<{
@@ -119,7 +119,7 @@ describe("CheckpointDiffQueryLive", () => { · 71 unmodified lines
119119 });
120120
121121 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");
123123
124124 const checkpointStore: CheckpointStoreShape = {
125125 isGitRepository: () => Effect.succeed(true),
apps/server/src/checkpointing/Layers/CheckpointStore.test.ts+3−3
@@ -80,7 +80,7 @@ function initRepoWithCommit( · 79 unmodified lines
8080 });
8181 }
8282
83−function buildLargeText(lineCount = 20_000): string {
83+function buildLargeText(lineCount = 5_000): string {
8484 return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
8585 .join("\n")
8686 .concat("\n");
@@ -93,7 +93,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => { · 6 unmodified lines
9393 const tmp = yield* makeTmpDir();
9494 yield* initRepoWithCommit(tmp);
9595 const checkpointStore = yield* CheckpointStore;
96− const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
96+ const threadId = ThreadId.make("thread-checkpoint-store");
9797 const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
9898 const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
9999
@@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => { · 15 unmodified lines
115115
116116 expect(diff).toContain("diff --git");
117117 expect(diff).not.toContain("[truncated]");
118− expect(diff).toContain("+line 19999");
118+ expect(diff).toContain("+line 04999");
119119 }),
120120 );
121121 });
apps/server/src/checkpointing/Services/CheckpointDiffQuery.ts+2−2
@@ -12,7 +12,7 @@ import type { · 11 unmodified lines
1212 OrchestrationGetTurnDiffInput,
1313 OrchestrationGetTurnDiffResult,
1414 } from "@t3tools/contracts";
15−import { ServiceMap } from "effect";
15+import { Context } from "effect";
1616 import type { Effect } from "effect";
1717
1818 import type { CheckpointServiceError } from "../Errors.ts";
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape { · 24 unmodified lines
4343 /**
4444 * CheckpointDiffQuery - Service tag for checkpoint diff queries.
4545 */
46−export class CheckpointDiffQuery extends ServiceMap.Service<
46+export class CheckpointDiffQuery extends Context.Service<
4747 CheckpointDiffQuery,
4848 CheckpointDiffQueryShape
4949 >()("t3/checkpointing/Services/CheckpointDiffQuery") {}
apps/server/src/checkpointing/Services/CheckpointStore.ts+3−3
@@ -5,12 +5,12 @@ · 4 unmodified lines
55 * workspace thread timeline. It does not store user-facing checkpoint metadata
66 * and does not coordinate provider conversation rollback.
77 *
8− * Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
8+ * Uses Effect `Context.Service` for dependency injection and exposes typed
99 * domain errors for checkpoint storage operations.
1010 *
1111 * @module CheckpointStore
1212 */
13−import { ServiceMap } from "effect";
13+import { Context } from "effect";
1414 import type { Effect } from "effect";
1515
1616 import type { CheckpointStoreError } from "../Errors.ts";
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape { · 78 unmodified lines
9595 /**
9696 * CheckpointStore - Service tag for checkpoint persistence and restore operations.
9797 */
98−export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
98+export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
9999 "t3/checkpointing/Services/CheckpointStore",
100100 ) {}
apps/server/src/checkpointing/Utils.ts+1−1
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts"; · 3 unmodified lines
44 export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
55
66 export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
7− return CheckpointRef.makeUnsafe(
7+ return CheckpointRef.make(
88 `${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
99 );
1010 }
apps/server/src/cli-config.test.ts+223−13
@@ -9,6 +9,18 @@ import { deriveServerPaths } from "./config"; · 8 unmodified lines
99 import { resolveServerConfig } from "./cli";
1010
1111 it.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+
1224 const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
1325 const fs = yield* FileSystem.FileSystem;
1426 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
2840 port: Option.none(),
2941 host: Option.none(),
3042 baseDir: Option.none(),
43+ cwd: Option.none(),
3144 devUrl: Option.none(),
3245 noBrowser: Option.none(),
33− authToken: Option.none(),
3446 bootstrapFd: Option.none(),
3547 autoBootstrapProjectFromCwd: Option.none(),
3648 logWebSocketEvents: Option.none(),
@@ -49,7 +61,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 12 unmodified lines
4961 T3CODE_HOME: baseDir,
5062 VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
5163 T3CODE_NO_BROWSER: "true",
52− T3CODE_AUTH_TOKEN: "env-token",
5364 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
5465 T3CODE_LOG_WS_EVENTS: "true",
5566 },
@@ -62,6 +73,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 6 unmodified lines
6273
6374 expect(resolved).toEqual({
6475 logLevel: "Warn",
76+ ...defaultObservabilityConfig,
6577 mode: "desktop",
6678 port: 4001,
6779 cwd: process.cwd(),
@@ -71,7 +83,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
7183 staticDir: undefined,
7284 devUrl: new URL("http://127.0.0.1:5173"),
7385 noBrowser: true,
74− authToken: "env-token",
86+ startupPresentation: "browser",
87+ desktopBootstrapToken: undefined,
7588 autoBootstrapProjectFromCwd: false,
7689 logWebSocketEvents: true,
7790 });
@@ -89,9 +102,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 11 unmodified lines
89102 port: Option.some(8788),
90103 host: Option.some("127.0.0.1"),
91104 baseDir: Option.some(baseDir),
105+ cwd: Option.none(),
92106 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
93107 noBrowser: Option.some(true),
94− authToken: Option.some("flag-token"),
95108 bootstrapFd: Option.none(),
96109 autoBootstrapProjectFromCwd: Option.some(true),
97110 logWebSocketEvents: Option.some(true),
@@ -110,7 +123,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 12 unmodified lines
110123 T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
111124 VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
112125 T3CODE_NO_BROWSER: "false",
113− T3CODE_AUTH_TOKEN: "ignored-token",
114126 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
115127 T3CODE_LOG_WS_EVENTS: "false",
116128 },
@@ -123,6 +135,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 6 unmodified lines
123135
124136 expect(resolved).toEqual({
125137 logLevel: "Debug",
138+ ...defaultObservabilityConfig,
126139 mode: "web",
127140 port: 8788,
128141 cwd: process.cwd(),
@@ -132,10 +145,74 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
132145 staticDir: undefined,
133146 devUrl: new URL("http://127.0.0.1:4173"),
134147 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,
136162 autoBootstrapProjectFromCwd: true,
137163 logWebSocketEvents: true,
138164 });
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+ });
139216 }),
140217 );
141218
@@ -150,9 +227,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 8 unmodified lines
150227 t3Home: baseDir,
151228 devUrl: "http://127.0.0.1:5173",
152229 noBrowser: true,
153− authToken: "bootstrap-token",
154230 autoBootstrapProjectFromCwd: false,
155231 logWebSocketEvents: true,
232+ otlpTracesUrl: "http://localhost:4318/v1/traces",
233+ otlpMetricsUrl: "http://localhost:4318/v1/metrics",
156234 });
157235 const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
158236
@@ -162,9 +240,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
162240 port: Option.none(),
163241 host: Option.none(),
164242 baseDir: Option.none(),
243+ cwd: Option.none(),
165244 devUrl: Option.none(),
166245 noBrowser: Option.none(),
167− authToken: Option.none(),
168246 bootstrapFd: Option.none(),
169247 autoBootstrapProjectFromCwd: Option.none(),
170248 logWebSocketEvents: Option.none(),
@@ -187,6 +265,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 16 unmodified lines
187265
188266 expect(resolved).toEqual({
189267 logLevel: "Info",
268+ ...defaultObservabilityConfig,
269+ otlpTracesUrl: "http://localhost:4318/v1/traces",
270+ otlpMetricsUrl: "http://localhost:4318/v1/metrics",
190271 mode: "desktop",
191272 port: 4888,
192273 cwd: process.cwd(),
@@ -196,7 +277,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
196277 staticDir: undefined,
197278 devUrl: new URL("http://127.0.0.1:5173"),
198279 noBrowser: true,
199− authToken: "bootstrap-token",
280+ startupPresentation: "browser",
281+ desktopBootstrapToken: undefined,
200282 autoBootstrapProjectFromCwd: false,
201283 logWebSocketEvents: true,
202284 });
@@ -209,6 +291,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 6 unmodified lines
209291 const fs = yield* FileSystem.FileSystem;
210292 const path = yield* Path.Path;
211293 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
294+ const customCwd = path.join(baseDir, "nested", "project");
212295
213296 const resolved = yield* resolveServerConfig(
214297 {
@@ -216,9 +299,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 1 unmodified line
216299 port: Option.some(4888),
217300 host: Option.none(),
218301 baseDir: Option.some(baseDir),
302+ cwd: Option.some(customCwd),
219303 devUrl: Option.some(new URL("http://127.0.0.1:5173")),
220304 noBrowser: Option.none(),
221− authToken: Option.none(),
222305 bootstrapFd: Option.none(),
223306 autoBootstrapProjectFromCwd: Option.none(),
224307 logWebSocketEvents: Option.none(),
@@ -234,6 +317,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 9 unmodified lines
234317 );
235318
236319 for (const directory of [
320+ customCwd,
237321 resolved.stateDir,
238322 resolved.logsDir,
239323 resolved.providerLogsDir,
@@ -241,9 +325,11 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 1 unmodified line
241325 resolved.attachmentsDir,
242326 resolved.worktreesDir,
243327 path.dirname(resolved.serverLogPath),
328+ path.dirname(resolved.serverTracePath),
244329 ]) {
245330 expect(yield* fs.exists(directory)).toBe(true);
246331 }
332+ expect(resolved.cwd).toBe(path.resolve(customCwd));
247333 }),
248334 );
249335
@@ -258,7 +344,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 8 unmodified lines
258344 t3Home: "/tmp/t3-bootstrap-home",
259345 devUrl: "http://127.0.0.1:5173",
260346 noBrowser: false,
261− authToken: "bootstrap-token",
262347 autoBootstrapProjectFromCwd: false,
263348 logWebSocketEvents: false,
264349 });
@@ -270,9 +355,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 5 unmodified lines
270355 port: Option.some(8788),
271356 host: Option.some("127.0.0.1"),
272357 baseDir: Option.none(),
358+ cwd: Option.none(),
273359 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
274360 noBrowser: Option.none(),
275− authToken: Option.some("flag-token"),
276361 bootstrapFd: Option.none(),
277362 autoBootstrapProjectFromCwd: Option.none(),
278363 logWebSocketEvents: Option.none(),
@@ -300,6 +385,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 21 unmodified lines
300385
301386 expect(resolved).toEqual({
302387 logLevel: "Debug",
388+ ...defaultObservabilityConfig,
303389 mode: "web",
304390 port: 8788,
305391 cwd: process.cwd(),
@@ -309,10 +395,134 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { · 3 unmodified lines
309395 staticDir: undefined,
310396 devUrl: new URL("http://127.0.0.1:4173"),
311397 noBrowser: true,
312− authToken: "flag-token",
398+ startupPresentation: "browser",
399+ desktopBootstrapToken: undefined,
313400 autoBootstrapProjectFromCwd: true,
314401 logWebSocketEvents: true,
315402 });
316403 }),
317404 );
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+ );
318528 });
apps/server/src/cli.test.ts+326−7
@@ -1,28 +1,164 @@
1+import * as NodeHttp from "node:http";
2+import { mkdtempSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+
6+import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
17 import * as NodeServices from "@effect/platform-node/NodeServices";
28 import { NetService } from "@t3tools/shared/Net";
39 import { assert, it } from "@effect/vitest";
410 import * as Effect from "effect/Effect";
511 import * as Layer from "effect/Layer";
12+import * as HttpRouter from "effect/unstable/http/HttpRouter";
13+import * as HttpServer from "effect/unstable/http/HttpServer";
614 import * as CliError from "effect/unstable/cli/CliError";
15+import * as TestConsole from "effect/testing/TestConsole";
716 import { Command } from "effect/unstable/cli";
817
918 import { cli } from "./cli.ts";
19+import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
20+import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
21+import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
22+import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
23+import {
24+ orchestrationDispatchRouteLayer,
25+ orchestrationSnapshotRouteLayer,
26+} from "./orchestration/http.ts";
27+import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
28+import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
29+import {
30+ makePersistedServerRuntimeState,
31+ persistServerRuntimeState,
32+} from "./serverRuntimeState.ts";
33+import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
34+import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
35+import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
1036
1137 const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
1238
39+const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
40+const runCliWithRuntime = (args: ReadonlyArray<string>) =>
41+ runCli(args).pipe(Effect.provide(CliRuntimeLayer));
42+
43+const 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+
52+const 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+
82+const 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+
94+const 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+
103+const 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+
13150 it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
14151 it.effect("accepts the built-in lowercase log-level flag values", () =>
15− Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
16− Effect.provide(CliRuntimeLayer),
17− ),
152+ runCliWithRuntime(["--log-level", "debug", "--version"]),
153+ );
154+
155+ it.effect("accepts canonical --no-<flag> boolean negation", () =>
156+ runCliWithRuntime(["--no-log-websocket-events", "--version"]),
18157 );
19158
20159 it.effect("rejects invalid log-level casing before launching the server", () =>
21160 Effect.gen(function* () {
22− const error = yield* Command.runWith(cli, { version: "0.0.0" })([
23− "--log-level",
24− "Debug",
25− ]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
161+ const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
26162
27163 if (!CliError.isCliError(error)) {
28164 assert.fail(`Expected CliError, got ${String(error)}`);
@@ -34,4 +170,187 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => { · 5 unmodified lines
34170 assert.equal(error.value, "Debug");
35171 }),
36172 );
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+ );
37356 });
apps/server/src/cli.ts+916−76
@@ -1,6 +1,35 @@
11 import { NetService } from "@t3tools/shared/Net";
2−import { Config, Effect, LogLevel, Option, Schema } from "effect";
3−import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
2+import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
3+import {
4+ AuthSessionId,
5+ CommandId,
6+ OrchestrationReadModel,
7+ ProjectId,
8+ type ClientOrchestrationCommand,
9+} from "@t3tools/contracts";
10+import {
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";
26+import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
27+import {
28+ FetchHttpClient,
29+ HttpClient,
30+ HttpClientRequest,
31+ HttpClientResponse,
32+} from "effect/unstable/http";
433
534 import {
635 DEFAULT_PORT,
@@ -10,10 +39,31 @@ import { · 3 unmodified lines
1039 ServerConfig,
1140 RuntimeMode,
1241 type ServerConfigShape,
42+ type StartupPresentation,
1343 } from "./config";
1444 import { readBootstrapEnvelope } from "./bootstrap";
15−import { resolveBaseDir } from "./os-jank";
45+import { expandHomePath, resolveBaseDir } from "./os-jank";
1646 import { runServer } from "./server";
47+import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
48+import {
49+ formatIssuedPairingCredential,
50+ formatIssuedSession,
51+ formatPairingCredentialList,
52+ formatSessionList,
53+} from "./cliAuthFormat";
54+import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
55+import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
56+import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
57+import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
58+import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
59+import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
60+import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
61+import {
62+ clearPersistedServerRuntimeState,
63+ readPersistedServerRuntimeState,
64+} from "./serverRuntimeState";
65+import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
66+import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
1767
1868 const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
1969
@@ -24,9 +74,11 @@ const BootstrapEnvelopeSchema = Schema.Struct({ · 4 unmodified lines
2474 t3Home: Schema.optional(Schema.String),
2575 devUrl: Schema.optional(Schema.URLFromString),
2676 noBrowser: Schema.optional(Schema.Boolean),
27− authToken: Schema.optional(Schema.String),
77+ desktopBootstrapToken: Schema.optional(Schema.String),
2878 autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
2979 logWebSocketEvents: Schema.optional(Schema.Boolean),
80+ otlpTracesUrl: Schema.optional(Schema.String),
81+ otlpMetricsUrl: Schema.optional(Schema.String),
3082 });
3183
3284 const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
@@ -55,11 +107,6 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe( · 22 unmodified lines
55107 Flag.withDescription("Disable automatic browser opening."),
56108 Flag.optional,
57109 );
58−const authTokenFlag = Flag.string("auth-token").pipe(
59− Flag.withDescription("Auth token required for WebSocket connections."),
60− Flag.withAlias("token"),
61− Flag.optional,
62−);
63110 const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
64111 Flag.withSchema(Schema.Int),
65112 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
81128
82129 const EnvServerConfig = Config.all({
83130 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")),
84152 mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
85153 Config.option,
86154 Config.map(Option.getOrUndefined),
@@ -93,10 +161,6 @@ const EnvServerConfig = Config.all({ · 6 unmodified lines
93161 Config.option,
94162 Config.map(Option.getOrUndefined),
95163 ),
96− authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
97− Config.option,
98− Config.map(Option.getOrUndefined),
99− ),
100164 bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
101165 Config.option,
102166 Config.map(Option.getOrUndefined),
@@ -116,48 +180,80 @@ interface CliServerFlags { · 13 unmodified lines
116180 readonly port: Option.Option<number>;
117181 readonly host: Option.Option<string>;
118182 readonly baseDir: Option.Option<string>;
183+ readonly cwd: Option.Option<string>;
119184 readonly devUrl: Option.Option<URL>;
120185 readonly noBrowser: Option.Option<boolean>;
121− readonly authToken: Option.Option<string>;
122186 readonly bootstrapFd: Option.Option<number>;
123187 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
124188 readonly logWebSocketEvents: Option.Option<boolean>;
125189 }
126190
127−const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
128− Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
191+interface CliAuthLocationFlags {
192+ readonly baseDir: Option.Option<string>;
193+ readonly devUrl?: Option.Option<URL>;
194+}
129195
130196 const resolveOptionPrecedence = <Value>(
131197 ...values: ReadonlyArray<Option.Option<Value>>
132198 ): Option.Option<Value> => Option.firstSomeOf(values);
133199
200+const 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+
134211 export const resolveServerConfig = (
135212 flags: CliServerFlags,
136213 cliLogLevel: Option.Option<LogLevel.LogLevel>,
214+ options?: {
215+ readonly startupPresentation?: StartupPresentation;
216+ readonly forceAutoBootstrapProjectFromCwd?: boolean;
217+ },
137218 ) =>
138219 Effect.gen(function* () {
139220 const { findAvailablePort } = yield* NetService;
221+ const path = yield* Path.Path;
222+ const fs = yield* FileSystem.FileSystem;
140223 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;
142237 const bootstrapEnvelope =
143238 bootstrapFd !== undefined
144239 ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
145240 : Option.none();
241+ const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
146242
147243 const mode: RuntimeMode = Option.getOrElse(
148244 resolveOptionPrecedence(
149− flags.mode,
245+ normalizedFlags.mode,
150246 Option.fromUndefinedOr(env.mode),
151− Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
247+ Option.fromUndefinedOr(bootstrap?.mode),
152248 ),
153249 () => "web",
154250 );
155251
156252 const port = yield* Option.match(
157253 resolveOptionPrecedence(
158− flags.port,
254+ normalizedFlags.port,
159255 Option.fromUndefinedOr(env.port),
160− Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
256+ Option.fromUndefinedOr(bootstrap?.port),
161257 ),
162258 {
163259 onSome: (value) => Effect.succeed(value),
@@ -171,76 +267,67 @@ export const resolveServerConfig = ( · 7 unmodified lines
171267 );
172268 const devUrl = Option.getOrElse(
173269 resolveOptionPrecedence(
174− flags.devUrl,
270+ normalizedFlags.devUrl,
175271 Option.fromUndefinedOr(env.devUrl),
176− Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
272+ Option.fromUndefinedOr(bootstrap?.devUrl),
177273 ),
178274 () => undefined,
179275 );
180276 const baseDir = yield* resolveBaseDir(
181277 Option.getOrUndefined(
182278 resolveOptionPrecedence(
183− flags.baseDir,
279+ normalizedFlags.baseDir,
184280 Option.fromUndefinedOr(env.t3Home),
185− Option.flatMap(bootstrapEnvelope, (bootstrap) =>
186− Option.fromUndefinedOr(bootstrap.t3Home),
187− ),
281+ Option.fromUndefinedOr(bootstrap?.t3Home),
188282 ),
189283 ),
190284 );
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 });
191288 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
192289 yield* ensureServerDirectories(derivedPaths);
193− const noBrowser = resolveBooleanFlag(
194− flags.noBrowser,
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− ),
290+ const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
291+ derivedPaths.settingsPath,
204292 );
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(
206298 resolveOptionPrecedence(
207− flags.authToken,
208− Option.fromUndefinedOr(env.authToken),
209− Option.flatMap(bootstrapEnvelope, (bootstrap) =>
210− Option.fromUndefinedOr(bootstrap.authToken),
211− ),
299+ isHeadlessStartup ? Option.some(true) : Option.none(),
300+ normalizedFlags.noBrowser,
301+ Option.fromUndefinedOr(env.noBrowser),
302+ Option.fromUndefinedOr(bootstrap?.noBrowser),
212303 ),
304+ () => mode === "desktop",
213305 );
214− const autoBootstrapProjectFromCwd = resolveBooleanFlag(
215− flags.autoBootstrapProjectFromCwd,
216− Option.getOrElse(
217− resolveOptionPrecedence(
218− Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
219− Option.flatMap(bootstrapEnvelope, (bootstrap) =>
220− Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
221− ),
222− ),
223− () => mode === "web",
306+ const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
307+ const autoBootstrapProjectFromCwd = Option.getOrElse(
308+ resolveOptionPrecedence(
309+ Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
310+ isHeadlessStartup ? Option.some(false) : Option.none(),
311+ normalizedFlags.autoBootstrapProjectFromCwd,
312+ Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
313+ Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
224314 ),
315+ () => mode === "web",
225316 );
226− const logWebSocketEvents = resolveBooleanFlag(
227− flags.logWebSocketEvents,
228− Option.getOrElse(
229− resolveOptionPrecedence(
230− Option.fromUndefinedOr(env.logWebSocketEvents),
231− Option.flatMap(bootstrapEnvelope, (bootstrap) =>
232− Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
233− ),
234− ),
235− () => Boolean(devUrl),
317+ const logWebSocketEvents = Option.getOrElse(
318+ resolveOptionPrecedence(
319+ normalizedFlags.logWebSocketEvents,
320+ Option.fromUndefinedOr(env.logWebSocketEvents),
321+ Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
236322 ),
323+ () => Boolean(devUrl),
237324 );
238325 const staticDir = devUrl ? undefined : yield* resolveStaticDir();
239326 const host = Option.getOrElse(
240327 resolveOptionPrecedence(
241− flags.host,
328+ normalizedFlags.host,
242329 Option.fromUndefinedOr(env.host),
243− Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
330+ Option.fromUndefinedOr(bootstrap?.host),
244331 ),
245332 () => (mode === "desktop" ? "127.0.0.1" : undefined),
246333 );
@@ -248,16 +335,33 @@ export const resolveServerConfig = ( · 1 unmodified line
248335
249336 const config: ServerConfigShape = {
250337 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,
251353 mode,
252354 port,
253− cwd: process.cwd(),
355+ cwd,
254356 baseDir,
255357 ...derivedPaths,
358+ serverTracePath,
256359 host,
257360 staticDir,
258361 devUrl,
259362 noBrowser,
260− authToken,
363+ startupPresentation,
364+ desktopBootstrapToken,
261365 autoBootstrapProjectFromCwd,
262366 logWebSocketEvents,
263367 };
@@ -265,28 +369,764 @@ export const resolveServerConfig = ( · 1 unmodified line
265369 return config;
266370 });
267371
268−const commandFlags = {
372+const 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+
392+const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
393+
394+const 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+
435+const 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+
455+const 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+
479+type ProjectMutationTarget = {
480+ readonly id: ProjectId;
481+ readonly title: string;
482+ readonly workspaceRoot: string;
483+};
484+
485+type ProjectCommandExecutionMode = "live" | "offline";
486+type ProjectCliDispatchCommand = Extract<
487+ ClientOrchestrationCommand,
488+ { type: "project.create" | "project.meta.update" | "project.delete" }
489+>;
490+
491+const ProjectCliRuntimeLive = Layer.mergeAll(
492+ WorkspacePathsLive,
493+ OrchestrationLayerLive.pipe(
494+ Layer.provideMerge(RepositoryIdentityResolverLive),
495+ Layer.provideMerge(SqlitePersistenceLayerLive),
496+ ),
497+);
498+
499+const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
500+const OrchestrationHttpErrorResponse = Schema.Struct({
501+ error: Schema.String,
502+});
503+
504+const 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+
517+const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
518+ effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
519+
520+const 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+
530+const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
531+ HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
532+
533+const 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+
545+const normalizeWorkspaceRootForProjectCommand = Effect.fn(
546+ "normalizeWorkspaceRootForProjectCommand",
547+)(function* (workspaceRoot: string) {
548+ const workspacePaths = yield* WorkspacePaths;
549+ return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
550+});
551+
552+const 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+
569+const 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+
612+const 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+
627+const 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+
650+const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
651+ const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
652+ return yield* projectionSnapshotQuery.getSnapshot();
653+});
654+
655+const 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+
680+const 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+
743+const sharedServerLocationFlags = {
744+ baseDir: baseDirFlag,
745+ devUrl: devUrlFlag,
746+} as const;
747+
748+const projectLocationFlags = {
749+ baseDir: baseDirFlag,
750+} as const;
751+
752+const sharedServerCommandFlags = {
269753 mode: modeFlag,
270754 port: portFlag,
271755 host: hostFlag,
272756 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+ ),
273763 devUrl: devUrlFlag,
274764 noBrowser: noBrowserFlag,
275− authToken: authTokenFlag,
276765 bootstrapFd: bootstrapFdFlag,
277766 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
278767 logWebSocketEvents: logWebSocketEventsFlag,
279768 } as const;
280769
281−const rootCommand = Command.make("t3", commandFlags).pipe(
770+const authLocationFlags = sharedServerLocationFlags;
771+
772+const 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+
778+const jsonFlag = Flag.boolean("json").pipe(
779+ Flag.withDescription("Emit JSON instead of human-readable output."),
780+ Flag.withDefault(false),
781+);
782+
783+const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
784+ Flag.withDescription("Role for the issued bearer session."),
785+ Flag.withDefault("owner"),
786+);
787+
788+const labelFlag = Flag.string("label").pipe(
789+ Flag.withDescription("Optional human-readable label."),
790+ Flag.optional,
791+);
792+
793+const subjectFlag = Flag.string("subject").pipe(
794+ Flag.withDescription("Optional session subject."),
795+ Flag.optional,
796+);
797+
798+const 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+
803+const tokenOnlyFlag = Flag.boolean("token-only").pipe(
804+ Flag.withDescription("Print only the issued bearer token."),
805+ Flag.withDefault(false),
806+);
807+
808+const 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+
840+const 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+
860+const 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+
879+const pairingCommand = Command.make("pairing").pipe(
880+ Command.withDescription("Manage one-time client pairing tokens."),
881+ Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
882+);
883+
884+const 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+
919+const 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+
939+const 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+
961+const sessionCommand = Command.make("session").pipe(
962+ Command.withDescription("Manage bearer sessions."),
963+ Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
964+);
965+
966+const authCommand = Command.make("auth").pipe(
967+ Command.withDescription("Manage the local auth control plane for headless deployments."),
968+ Command.withSubcommands([pairingCommand, sessionCommand]),
969+);
970+
971+const 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+
1018+const 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+
1052+const 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+
1093+const projectCommand = Command.make("project").pipe(
1094+ Command.withDescription("Manage projects."),
1095+ Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
1096+);
1097+
1098+const 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+
1111+const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
2821112 Command.withDescription("Run the T3 Code server."),
1113+ Command.withHandler((flags) => runServerCommand(flags)),
1114+);
1115+
1116+const 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+ ),
2831120 Command.withHandler((flags) =>
284− Effect.gen(function* () {
285− const logLevel = yield* GlobalFlag.LogLevel;
286− const config = yield* resolveServerConfig(flags, logLevel);
287− return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
1121+ runServerCommand(flags, {
1122+ startupPresentation: "headless",
1123+ forceAutoBootstrapProjectFromCwd: false,
2881124 }),
2891125 ),
2901126 );
2911127
292−export const cli = rootCommand;
1128+export 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 @@
1+import { expect, it } from "@effect/vitest";
2+import { DateTime } from "effect";
3+
4+import {
5+ formatIssuedPairingCredential,
6+ formatIssuedSession,
7+ formatPairingCredentialList,
8+ formatSessionList,
9+} from "./cliAuthFormat.ts";
10+
11+it("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+
28+it("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+
48+it("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 @@
1+import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
2+import { DateTime } from "effect";
3+
4+import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
5+
6+const newline = "\n";
7+
8+function serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {
9+ return values.filter((value): value is string => typeof value === "string" && value.length > 0);
10+}
11+
12+function 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+
23+function toIsoString(value: DateTime.DateTime | DateTime.Utc): string {
24+ return DateTime.formatIso(DateTime.toUtc(value));
25+}
26+
27+export 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+
69+export 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+
107+export 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+
145+export 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
1717 resolveCodexModelForAccount,
1818 } from "./codexAppServerManager";
1919
20−const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
20+const asThreadId = (value: string): ThreadId => ThreadId.make(value);
2121
2222 function createSendTurnHarness() {
2323 const manager = new CodexAppServerManager();
@@ -111,9 +111,9 @@ function createPendingUserInputHarness() { · 87 unmodified lines
111111 },
112112 pendingUserInputs: new Map([
113113 [
114− ApprovalRequestId.makeUnsafe("req-user-input-1"),
114+ ApprovalRequestId.make("req-user-input-1"),
115115 {
116− requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
116+ requestId: ApprovalRequestId.make("req-user-input-1"),
117117 jsonRpcId: 42,
118118 threadId: asThreadId("thread_1"),
119119 },
@@ -743,7 +743,7 @@ describe("respondToUserInput", () => { · 623 unmodified lines
743743
744744 await manager.respondToUserInput(
745745 asThreadId("thread_1"),
746− ApprovalRequestId.makeUnsafe("req-user-input-1"),
746+ ApprovalRequestId.make("req-user-input-1"),
747747 {
748748 scope: "All request methods",
749749 compat: "Keep current envelope",
@@ -780,7 +780,7 @@ describe("respondToUserInput", () => { · 30 unmodified lines
780780
781781 await manager.respondToUserInput(
782782 asThreadId("thread_1"),
783− ApprovalRequestId.makeUnsafe("req-user-input-1"),
783+ ApprovalRequestId.make("req-user-input-1"),
784784 {
785785 scope: [],
786786 },
apps/server/src/codexAppServerManager.ts+34−28
@@ -19,7 +19,7 @@ import { · 18 unmodified lines
1919 ProviderInteractionMode,
2020 } from "@t3tools/contracts";
2121 import { normalizeModelSlug } from "@t3tools/shared/model";
22−import { Effect, ServiceMap } from "effect";
22+import { Effect, Context } from "effect";
2323
2424 import {
2525 formatCodexCliUpgradeMessage,
@@ -290,20 +290,26 @@ In Default mode, strongly prefer making reasonable assumptions and executing the · 264 unmodified lines
290290 </collaboration_mode>`;
291291
292292 function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
293− readonly approvalPolicy: "on-request" | "never";
294− readonly sandbox: "workspace-write" | "danger-full-access";
293+ readonly approvalPolicy: "untrusted" | "on-request" | "never";
294+ readonly sandbox: "read-only" | "workspace-write" | "danger-full-access";
295295 } {
296− if (runtimeMode === "approval-required") {
297− return {
298− approvalPolicy: "on-request",
299− sandbox: "workspace-write",
300− };
296+ switch (runtimeMode) {
297+ case "approval-required":
298+ return {
299+ approvalPolicy: "untrusted",
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+ };
301312 }
302−
303− return {
304− approvalPolicy: "never",
305− sandbox: "danger-full-access",
306− };
307313 }
308314
309315 /**
@@ -433,7 +439,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 123 unmodified lines
433439 private readonly sessions = new Map<ThreadId, CodexSessionContext>();
434440
435441 private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
436− constructor(services?: ServiceMap.ServiceMap<never>) {
442+ constructor(services?: Context.Context<never>) {
437443 super();
438444 this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
439445 }
@@ -634,7 +640,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 194 unmodified lines
634640 this.stopSession(threadId);
635641 } else {
636642 this.emitEvent({
637− id: EventId.makeUnsafe(randomUUID()),
643+ id: EventId.make(randomUUID()),
638644 kind: "error",
639645 provider: "codex",
640646 threadId,
@@ -733,7 +739,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 92 unmodified lines
733739 if (!turnIdRaw) {
734740 throw new Error("turn/start response did not include a turn id.");
735741 }
736− const turnId = TurnId.makeUnsafe(turnIdRaw);
742+ const turnId = TurnId.make(turnIdRaw);
737743
738744 this.updateSession(context, {
739745 status: "running",
@@ -834,7 +840,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 94 unmodified lines
834840 });
835841
836842 this.emitEvent({
837− id: EventId.makeUnsafe(randomUUID()),
843+ id: EventId.make(randomUUID()),
838844 kind: "notification",
839845 provider: "codex",
840846 threadId: context.session.threadId,
@@ -873,7 +879,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 32 unmodified lines
873879 });
874880
875881 this.emitEvent({
876− id: EventId.makeUnsafe(randomUUID()),
882+ id: EventId.make(randomUUID()),
877883 kind: "notification",
878884 provider: "codex",
879885 threadId: context.session.threadId,
@@ -1055,7 +1061,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 175 unmodified lines
10551061 : undefined;
10561062
10571063 this.emitEvent({
1058− id: EventId.makeUnsafe(randomUUID()),
1064+ id: EventId.make(randomUUID()),
10591065 kind: "notification",
10601066 provider: "codex",
10611067 threadId: context.session.threadId,
@@ -1128,7 +1134,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 66 unmodified lines
11281134 const requestKind = this.requestKindForMethod(request.method);
11291135 let requestId: ApprovalRequestId | undefined;
11301136 if (requestKind) {
1131− requestId = ApprovalRequestId.makeUnsafe(randomUUID());
1137+ requestId = ApprovalRequestId.make(randomUUID());
11321138 const pendingRequest: PendingApprovalRequest = {
11331139 requestId,
11341140 jsonRpcId: request.id,
@@ -1147,7 +1153,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 12 unmodified lines
11471153 }
11481154
11491155 if (request.method === "item/tool/requestUserInput") {
1150− requestId = ApprovalRequestId.makeUnsafe(randomUUID());
1156+ requestId = ApprovalRequestId.make(randomUUID());
11511157 context.pendingUserInputs.set(requestId, {
11521158 requestId,
11531159 jsonRpcId: request.id,
@@ -1158,7 +1164,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 4 unmodified lines
11581164 }
11591165
11601166 this.emitEvent({
1161− id: EventId.makeUnsafe(randomUUID()),
1167+ id: EventId.make(randomUUID()),
11621168 kind: "request",
11631169 provider: "codex",
11641170 threadId: context.session.threadId,
@@ -1248,7 +1254,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 83 unmodified lines
12481254
12491255 private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
12501256 this.emitEvent({
1251− id: EventId.makeUnsafe(randomUUID()),
1257+ id: EventId.make(randomUUID()),
12521258 kind: "session",
12531259 provider: "codex",
12541260 threadId: context.session.threadId,
@@ -1260,7 +1266,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 5 unmodified lines
12601266
12611267 private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
12621268 this.emitEvent({
1263− id: EventId.makeUnsafe(randomUUID()),
1269+ id: EventId.make(randomUUID()),
12641270 kind: "error",
12651271 provider: "codex",
12661272 threadId: context.session.threadId,
@@ -1276,7 +1282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 9 unmodified lines
12761282 message: string,
12771283 ): void {
12781284 this.emitEvent({
1279− id: EventId.makeUnsafe(randomUUID()),
1285+ id: EventId.make(randomUUID()),
12801286 kind: "notification",
12811287 provider: "codex",
12821288 threadId: context.session.threadId,
@@ -1335,7 +1341,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve · 52 unmodified lines
13351341 const turns = turnsRaw.map((turnValue, index) => {
13361342 const turn = this.readObject(turnValue);
13371343 const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
1338− const turnId = TurnId.makeUnsafe(turnIdRaw);
1344+ const turnId = TurnId.make(turnIdRaw);
13391345 const items = this.readArray(turn, "items") ?? [];
13401346 return {
13411347 id: turnId,
@@ -1584,9 +1590,9 @@ function readResumeThreadId(input: { · 242 unmodified lines
15841590 }
15851591
15861592 function toTurnId(value: string | undefined): TurnId | undefined {
1587− return brandIfNonEmpty(value, TurnId.makeUnsafe);
1593+ return brandIfNonEmpty(value, TurnId.make);
15881594 }
15891595
15901596 function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
1591− return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
1597+ return brandIfNonEmpty(value, ProviderItemId.make);
15921598 }
apps/server/src/config.ts+36−4
@@ -6,13 +6,16 @@ · 5 unmodified lines
66 *
77 * @module ServerConfig
88 */
9−import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
9+import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
1010
1111 export const DEFAULT_PORT = 3773;
1212
1313 export const RuntimeMode = Schema.Literals(["web", "desktop"]);
1414 export type RuntimeMode = typeof RuntimeMode.Type;
1515
16+export const StartupPresentation = Schema.Literals(["browser", "headless"]);
17+export type StartupPresentation = typeof StartupPresentation.Type;
18+
1619 /**
1720 * ServerDerivedPaths - Derived paths from the base directory.
1821 */
@@ -25,10 +28,14 @@ export interface ServerDerivedPaths { · 6 unmodified lines
2528 readonly attachmentsDir: string;
2629 readonly logsDir: string;
2730 readonly serverLogPath: string;
31+ readonly serverTracePath: string;
2832 readonly providerLogsDir: string;
2933 readonly providerEventLogPath: string;
3034 readonly terminalLogsDir: string;
3135 readonly anonymousIdPath: string;
36+ readonly environmentIdPath: string;
37+ readonly serverRuntimeStatePath: string;
38+ readonly secretsDir: string;
3239 }
3340
3441 /**
@@ -36,6 +43,15 @@ export interface ServerDerivedPaths { · 1 unmodified line
3643 */
3744 export interface ServerConfigShape extends ServerDerivedPaths {
3845 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;
3955 readonly mode: RuntimeMode;
4056 readonly port: number;
4157 readonly host: string | undefined;
@@ -44,7 +60,8 @@ export interface ServerConfigShape extends ServerDerivedPaths { · 2 unmodified lines
4460 readonly staticDir: string | undefined;
4561 readonly devUrl: URL | undefined;
4662 readonly noBrowser: boolean;
47− readonly authToken: string | undefined;
63+ readonly startupPresentation: StartupPresentation;
64+ readonly desktopBootstrapToken: string | undefined;
4865 readonly autoBootstrapProjectFromCwd: boolean;
4966 readonly logWebSocketEvents: boolean;
5067 }
@@ -68,10 +85,14 @@ export const deriveServerPaths = Effect.fn(function* ( · 17 unmodified lines
6885 attachmentsDir,
6986 logsDir,
7087 serverLogPath: join(logsDir, "server.log"),
88+ serverTracePath: join(logsDir, "server.trace.ndjson"),
7189 providerLogsDir,
7290 providerEventLogPath: join(providerLogsDir, "events.log"),
7391 terminalLogsDir: join(logsDir, "terminals"),
7492 anonymousIdPath: join(stateDir, "anonymous-id"),
93+ environmentIdPath: join(stateDir, "environment-id"),
94+ serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
95+ secretsDir: join(stateDir, "secrets"),
7596 };
7697 });
7798
@@ -90,6 +111,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server · 12 unmodified lines
90111 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
91112 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
92113 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
114+ fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
93115 ],
94116 { concurrency: "unbounded" },
95117 );
@@ -98,7 +120,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server · 2 unmodified lines
98120 /**
99121 * ServerConfig - Service tag for server runtime configuration.
100122 */
101−export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
123+export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
102124 "t3/config/ServerConfig",
103125 ) {
104126 static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
@@ -117,6 +139,15 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS · 12 unmodified lines
117139
118140 return {
119141 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",
120151 cwd,
121152 baseDir,
122153 ...derivedPaths,
@@ -125,10 +156,11 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS · 2 unmodified lines
125156 logWebSocketEvents: false,
126157 port: 0,
127158 host: undefined,
128− authToken: undefined,
159+ desktopBootstrapToken: undefined,
129160 staticDir: undefined,
130161 devUrl,
131162 noBrowser: false,
163+ startupPresentation: "browser",
132164 } satisfies ServerConfigShape;
133165 }),
134166 );
apps/server/src/environment/Layers/ServerEnvironment.test.ts+125−0
@@ -0,0 +1,125 @@
1+import * as nodePath from "node:path";
2+import * as NodeServices from "@effect/platform-node/NodeServices";
3+import { expect, it } from "@effect/vitest";
4+import { Effect, Exit, FileSystem, Layer, PlatformError } from "effect";
5+
6+import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "../../config.ts";
7+import { ServerEnvironment } from "../Services/ServerEnvironment.ts";
8+import { ServerEnvironmentLive } from "./ServerEnvironment.ts";
9+
10+const makeServerEnvironmentLayer = (baseDir: string) =>
11+ ServerEnvironmentLive.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
12+
13+const 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+
43+it.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 @@
1+import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
2+import { Effect, FileSystem, Layer, Path, Random } from "effect";
3+
4+import { ServerConfig } from "../../config.ts";
5+import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
6+import { version } from "../../../package.json" with { type: "json" };
7+import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
8+
9+function 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+
22+function 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+
33+export 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+
92+export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts+150−0
@@ -0,0 +1,150 @@
1+import { afterEach, describe, expect, it } from "@effect/vitest";
2+import { Effect, FileSystem } from "effect";
3+import { vi } from "vitest";
4+
5+vi.mock("../../processRunner.ts", () => ({
6+ runProcess: vi.fn(),
7+}));
8+
9+import { runProcess } from "../../processRunner.ts";
10+import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
11+
12+const mockedRunProcess = vi.mocked(runProcess);
13+const NoopFileSystemLayer = FileSystem.layerNoop({});
14+
15+afterEach(() => {
16+ mockedRunProcess.mockReset();
17+});
18+
19+describe("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 @@
1+import * as OS from "node:os";
2+
3+import { Effect, FileSystem } from "effect";
4+
5+import { runProcess } from "../../processRunner.ts";
6+
7+interface ResolveServerEnvironmentLabelInput {
8+ readonly cwdBaseName: string;
9+ readonly platform?: NodeJS.Platform;
10+ readonly hostname?: string | null;
11+}
12+
13+function normalizeLabel(value: string | null | undefined): string | null {
14+ const trimmed = value?.trim();
15+ return trimmed && trimmed.length > 0 ? trimmed : null;
16+}
17+
18+function 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+
36+const 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+
50+const 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+
69+const 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+
91+export 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 @@
1+import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
2+import { Context } from "effect";
3+import type { Effect } from "effect";
4+
5+export interface ServerEnvironmentShape {
6+ readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
7+ readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
8+}
9+
10+export 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
4040 });
4141 }
4242
43+function 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+
52+function 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+
4361 /** Run a raw git command for test setup (not under test). */
4462 function git(
4563 cwd: string,
@@ -219,7 +237,10 @@ it.layer(TestLayer)("git integration", (it) => { · 173 unmodified lines
219237
220238 const seenChunks: string[][] = [];
221239 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+ ) {
223244 return Effect.fail(
224245 new GitCommandError({
225246 operation: input.operation,
@@ -252,6 +273,35 @@ it.layer(TestLayer)("git integration", (it) => { · 26 unmodified lines
252273 expect(result).toEqual(expectedPaths);
253274 }),
254275 );
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+ );
255305 });
256306
257307 // ── listGitBranches ──
@@ -267,6 +317,21 @@ it.layer(TestLayer)("git integration", (it) => { · 9 unmodified lines
267317 }),
268318 );
269319
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+
270335 it.effect("returns the current branch with current: true", () =>
271336 Effect.gen(function* () {
272337 const tmp = yield* makeTmpDir();
@@ -617,8 +682,8 @@ it.layer(TestLayer)("git integration", (it) => { · 344 unmodified lines
617682
618683 it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
619684 Effect.gen(function* () {
620− const services = yield* Effect.services();
621− const runPromise = Effect.runPromiseWith(services);
685+ const context = yield* Effect.context<never>();
686+ const runPromise = Effect.runPromiseWith(context);
622687
623688 const remote = yield* makeTmpDir();
624689 const source = yield* makeTmpDir();
@@ -761,7 +826,7 @@ it.layer(TestLayer)("git integration", (it) => { · 136 unmodified lines
761826 }),
762827 );
763828
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", () =>
765830 Effect.gen(function* () {
766831 const ok = (stdout = "") =>
767832 Effect.succeed({
@@ -780,7 +845,9 @@ it.layer(TestLayer)("git integration", (it) => { · 12 unmodified lines
780845 input.args[2] === "--symbolic-full-name" &&
781846 input.args[3] === "@{upstream}"
782847 ) {
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+ );
784851 }
785852 if (input.args[0] === "remote") {
786853 return ok("origin\n");
@@ -791,10 +858,22 @@ it.layer(TestLayer)("git integration", (it) => { · 4 unmodified lines
791858 if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
792859 fetchCount += 1;
793860 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+ ]);
794869 return ok();
795870 }
796871 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+ );
798877 }
799878 if (
800879 input.operation === "GitCore.statusDetails.unstagedNumstat" ||
@@ -821,70 +900,80 @@ it.layer(TestLayer)("git integration", (it) => { · 20 unmodified lines
821900 }),
822901 );
823902
824− it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
825− Effect.gen(function* () {
826− const ok = (stdout = "") =>
827− Effect.succeed({
828− code: 0,
829− stdout,
830− stderr: "",
831− stdoutTruncated: false,
832− stderrTruncated: false,
833− });
903+ it.effect(
904+ "briefly backs off failed upstream refreshes across sibling worktrees on one remote",
905+ () =>
906+ Effect.gen(function* () {
907+ const ok = (stdout = "") =>
908+ Effect.succeed({
909+ code: 0,
910+ stdout,
911+ stderr: "",
912+ stdoutTruncated: false,
913+ stderrTruncated: false,
914+ });
834915
835− let fetchCount = 0;
836− const core = yield* makeIsolatedGitCore((input) => {
837− if (
838− input.args[0] === "rev-parse" &&
839− input.args[1] === "--abbrev-ref" &&
840− input.args[2] === "--symbolic-full-name" &&
841− input.args[3] === "@{upstream}"
842− ) {
843− return ok("origin/main\n");
844− }
845− if (input.args[0] === "remote") {
846− return ok("origin\n");
847− }
848− if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
849− return ok("/repo/.git\n");
850− }
851− if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
852− fetchCount += 1;
916+ let fetchCount = 0;
917+ const core = yield* makeIsolatedGitCore((input) => {
918+ if (
919+ input.args[0] === "rev-parse" &&
920+ input.args[1] === "--abbrev-ref" &&
921+ input.args[2] === "--symbolic-full-name" &&
922+ input.args[3] === "@{upstream}"
923+ ) {
924+ return ok(
925+ input.cwd === "/repo/worktrees/pr-123"
926+ ? "origin/feature/pr-123\n"
927+ : "origin/main\n",
928+ );
929+ }
930+ if (input.args[0] === "remote") {
931+ return ok("origin\n");
932+ }
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+ }
853963 return Effect.fail(
854964 new GitCommandError({
855965 operation: input.operation,
856966 command: `git ${input.args.join(" ")}`,
857967 cwd: input.cwd,
858− detail: "simulated fetch timeout",
968+ detail: "Unexpected git command in refresh failure cooldown test.",
859969 }),
860970 );
861− }
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− });
971+ });
883972
884− yield* core.statusDetails("/repo/worktrees/main");
885− yield* core.statusDetails("/repo/worktrees/pr-123");
886− expect(fetchCount).toBe(1);
887− }),
973+ yield* core.statusDetails("/repo/worktrees/main");
974+ yield* core.statusDetails("/repo/worktrees/pr-123");
975+ expect(fetchCount).toBe(1);
976+ }),
888977 );
889978
890979 it.effect("throws when branch does not exist", () =>
@@ -949,11 +1038,12 @@ it.layer(TestLayer)("git integration", (it) => { · 58 unmodified lines
9491038 yield* git(source, ["checkout", defaultBranch]);
9501039 yield* git(source, ["branch", "-D", featureBranch]);
9511040
952− yield* (yield* GitCore).checkoutBranch({
1041+ const checkoutResult = yield* (yield* GitCore).checkoutBranch({
9531042 cwd: source,
9541043 branch: `${remoteName}/${featureBranch}`,
9551044 });
9561045
1046+ expect(checkoutResult.branch).toBe("upstream/feature");
9571047 expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
9581048 const realGitCore = yield* GitCore;
9591049 let fetchArgs: readonly string[] | null = null;
@@ -981,7 +1071,6 @@ it.layer(TestLayer)("git integration", (it) => { · 21 unmodified lines
9811071 "--quiet",
9821072 "--no-tags",
9831073 remoteName,
984− `+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
9851074 ]);
9861075 }),
9871076 );
@@ -1593,6 +1682,37 @@ it.layer(TestLayer)("git integration", (it) => { · 605 unmodified lines
15931682 }),
15941683 );
15951684
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+
15961716 it.effect("computes ahead count against base branch when no upstream is configured", () =>
15971717 Effect.gen(function* () {
15981718 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
2020
2121 import { GitCommandError, type GitBranch } from "@t3tools/contracts";
2222 import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
23+import { compactTraceAttributes } from "../../observability/Attributes.ts";
24+import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts";
2325 import {
2426 GitCore,
2527 type ExecuteGitProgress,
2628 type GitCommitOptions,
2729 type GitCoreShape,
30+ type GitStatusDetails,
2831 type ExecuteGitInput,
2932 type ExecuteGitResult,
3033 } from "../Services/GitCore.ts";
@@ -45,23 +48,39 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; · 14 unmodified lines
4548 const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
4649 const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
4750 const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
51+const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
52+ "-c",
53+ "core.fsmonitor=false",
54+ "-c",
55+ "core.untrackedCache=false",
56+] as const;
4857 const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
4958 const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
5059 const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
5160 const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
5261 const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
5362 const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
63+const 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+});
5475
5576 type TraceTailState = {
5677 processedChars: number;
5778 remainder: string;
5879 };
5980
60−class StatusUpstreamRefreshCacheKey extends Data.Class<{
81+class StatusRemoteRefreshCacheKey extends Data.Class<{
6182 gitCommonDir: string;
62− upstreamRef: string;
6383 remoteName: string;
64− upstreamBranch: string;
6584 }> {}
6685
6786 interface ExecuteGitOptions {
@@ -351,6 +370,16 @@ function quoteGitCommand(args: ReadonlyArray<string>): string { · 283 unmodified lines
351370 return `git ${args.join(" ")}`;
352371 }
353372
373+function 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+
354383 function toGitCommandError(
355384 input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
356385 detail: string,
@@ -372,6 +401,18 @@ interface Trace2Monitor { · 15 unmodified lines
372401 readonly flush: Effect.Effect<void, never>;
373402 }
374403
404+const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n;
405+
406+const 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+
375416 function trace2ChildKey(record: Record<string, unknown>): string | null {
376417 const childId = record.child_id;
377418 if (typeof childId === "number" || typeof childId === "string") {
@@ -444,6 +485,9 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( · 66 unmodified lines
444485
445486 if (event === "child_start") {
446487 hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
488+ yield* addCurrentSpanEvent("git.hook.started", {
489+ hookName,
490+ });
447491 if (progress.onHookStarted) {
448492 yield* progress.onHookStarted(hookName);
449493 }
@@ -452,12 +496,19 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( · 2 unmodified lines
452496
453497 if (event === "child_exit") {
454498 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+ });
455507 if (progress.onHookFinished) {
456− const code = traceRecord.success.code;
457508 yield* progress.onHookFinished({
458509 hookName: started?.hookName ?? hookName,
459− exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
460− durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
510+ exitCode,
511+ durationMs,
461512 });
462513 }
463514 }
@@ -609,13 +660,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 145 unmodified lines
609660 const path = yield* Path.Path;
610661 const { worktreesDir } = yield* ServerConfig;
611662
612− let execute: GitCoreShape["execute"];
663+ let executeRaw: GitCoreShape["execute"];
613664
614665 if (options?.executeOverride) {
615− execute = options.executeOverride;
666+ executeRaw = options.executeOverride;
616667 } else {
617668 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
618− execute = Effect.fnUntraced(function* (input) {
669+ executeRaw = Effect.fnUntraced(function* (input) {
619670 const commandInput = {
620671 ...input,
621672 args: [...input.args],
@@ -716,6 +767,25 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 94 unmodified lines
716767 });
717768 }
718769
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+
719789 const executeGit = (
720790 operation: string,
721791 cwd: string,
@@ -847,17 +917,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 125 unmodified lines
847917 );
848918 });
849919
850− const fetchUpstreamRefForStatus = (
920+ const fetchRemoteForStatus = (
851921 gitCommonDir: string,
852− upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
922+ remoteName: string,
853923 ): Effect.Effect<void, GitCommandError> => {
854− const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
855924 const fetchCwd =
856925 path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
857926 return executeGit(
858− "GitCore.fetchUpstreamRefForStatus",
927+ "GitCore.fetchRemoteForStatus",
859928 fetchCwd,
860− ["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
929+ ["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
861930 {
862931 allowNonZeroExit: true,
863932 timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
@@ -873,20 +942,15 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 9 unmodified lines
873942 return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
874943 });
875944
876− const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
877− cacheKey: StatusUpstreamRefreshCacheKey,
945+ const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
946+ cacheKey: StatusRemoteRefreshCacheKey,
878947 ) {
879− yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
880− upstreamRef: cacheKey.upstreamRef,
881− remoteName: cacheKey.remoteName,
882− upstreamBranch: cacheKey.upstreamBranch,
883− });
948+ yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
884949 return true as const;
885950 });
886951
887− const statusUpstreamRefreshCache = yield* Cache.makeWith({
952+ const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
888953 capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
889− lookup: refreshStatusUpstreamCacheEntry,
890954 // Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
891955 timeToLive: (exit) =>
892956 Exit.isSuccess(exit)
@@ -901,12 +965,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 8 unmodified lines
901965 if (!upstream) return;
902966 const gitCommonDir = yield* resolveGitCommonDir(cwd);
903967 yield* Cache.get(
904− statusUpstreamRefreshCache,
905− new StatusUpstreamRefreshCacheKey({
968+ statusRemoteRefreshCache,
969+ new StatusRemoteRefreshCacheKey({
906970 gitCommonDir,
907− upstreamRef: upstream.upstreamRef,
908971 remoteName: upstream.remoteName,
909− upstreamBranch: upstream.upstreamBranch,
910972 }),
911973 );
912974 });
@@ -1134,9 +1196,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 221 unmodified lines
11341196 return branchLastCommit;
11351197 });
11361198
1137− const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
1138− yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
1139−
1199+ const readStatusDetailsLocal = Effect.fn("readStatusDetailsLocal")(function* (cwd: string) {
11401200 const statusResult = yield* executeGit(
11411201 "GitCore.statusDetails.status",
11421202 cwd,
@@ -1144,7 +1204,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 1 unmodified line
11441204 {
11451205 allowNonZeroExit: true,
11461206 },
1147− );
1207+ ).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
1208+
1209+ if (statusResult === null) {
1210+ return NON_REPOSITORY_STATUS_DETAILS;
1211+ }
11481212
11491213 if (statusResult.code !== 0) {
11501214 const stderr = statusResult.stderr.trim();
@@ -1269,6 +1333,20 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 118 unmodified lines
12691333 };
12701334 });
12711335
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+
12721350 const status: GitCoreShape["status"] = (input) =>
12731351 statusDetails(input.cwd).pipe(
12741352 Effect.map((details) => ({
@@ -1567,7 +1645,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 292 unmodified lines
15671645 executeGit(
15681646 "GitCore.listWorkspaceFiles",
15691647 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+ ],
15711656 {
15721657 allowNonZeroExit: true,
15731658 timeoutMs: 20_000,
@@ -1585,7 +1670,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 11 unmodified lines
15851670 createGitCommandError(
15861671 "GitCore.listWorkspaceFiles",
15871672 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+ ],
15891681 result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
15901682 ),
15911683 ),
@@ -1605,7 +1697,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 13 unmodified lines
16051697 const result = yield* executeGit(
16061698 "GitCore.filterIgnoredPaths",
16071699 cwd,
1608− ["check-ignore", "--no-index", "-z", "--stdin"],
1700+ [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
16091701 {
16101702 stdin: `${chunk.join("\0")}\0`,
16111703 allowNonZeroExit: true,
@@ -1619,7 +1711,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 7 unmodified lines
16191711 return yield* createGitCommandError(
16201712 "GitCore.filterIgnoredPaths",
16211713 cwd,
1622− ["check-ignore", "--no-index", "-z", "--stdin"],
1714+ [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
16231715 result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
16241716 );
16251717 }
@@ -1648,6 +1740,16 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 22 unmodified lines
16481740 timeoutMs: 10_000,
16491741 allowNonZeroExit: true,
16501742 },
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+ ),
16511753 );
16521754
16531755 if (localBranchResult.code !== 0) {
@@ -1930,7 +2032,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 276 unmodified lines
19302032 "GitCore.removeWorktree",
19312033 input.cwd,
19322034 args,
1933− `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
2035+ `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error.message}`,
19342036 error,
19352037 ),
19362038 ),
@@ -1957,12 +2059,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 20 unmodified lines
19572059 return { branch: targetBranch };
19582060 });
19592061
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−
19662062 const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")(
19672063 function* (input) {
19682064 const [localInputExists, remoteExists] = yield* Effect.all(
@@ -2035,9 +2131,28 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 66 unmodified lines
20352131 timeoutMs: 10_000,
20362132 fallbackErrorMessage: "git checkout failed",
20372133 });
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 };
20382141 },
20392142 );
20402143
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+
20412156 const initRepo: GitCoreShape["initRepo"] = (input) =>
20422157 executeGit("GitCore.initRepo", input.cwd, ["init"], {
20432158 timeoutMs: 10_000,
@@ -2063,6 +2178,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { · 19 unmodified lines
20632178 execute,
20642179 status,
20652180 statusDetails,
2181+ statusDetailsLocal,
20662182 prepareCommitContext,
20672183 commit,
20682184 pushCurrentBranch,
apps/server/src/git/Layers/GitHubCli.test.ts+99−0
@@ -76,6 +76,105 @@ layer("GitHubCliLive", (it) => { · 75 unmodified lines
7676 }),
7777 );
7878
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+
79178 it.effect("reads repository clone URLs", () =>
80179 Effect.gen(function* () {
81180 mockedRunProcess.mockResolvedValueOnce({
apps/server/src/git/Layers/GitHubCli.ts+40−80
@@ -1,5 +1,5 @@
1−import { Effect, Layer, Schema } from "effect";
2−import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
1+import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
2+import { TrimmedNonEmptyString } from "@t3tools/contracts";
33
44 import { runProcess } from "../../processRunner";
55 import { GitHubCliError } from "@t3tools/contracts";
@@ -7,8 +7,12 @@ import { · 1 unmodified line
77 GitHubCli,
88 type GitHubRepositoryCloneUrls,
99 type GitHubCliShape,
10− type GitHubPullRequestSummary,
1110 } from "../Services/GitHubCli.ts";
11+import {
12+ decodeGitHubPullRequestJson,
13+ decodeGitHubPullRequestListJson,
14+ formatGitHubJsonDecodeError,
15+} from "../githubPullRequests.ts";
1216
1317 const DEFAULT_TIMEOUT_MS = 30_000;
1418
@@ -63,76 +67,12 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown · 48 unmodified lines
6367 });
6468 }
6569
66−function 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−
81−const 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−
10670 const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
10771 nameWithOwner: TrimmedNonEmptyString,
10872 url: TrimmedNonEmptyString,
10973 sshUrl: TrimmedNonEmptyString,
11074 });
11175
112−function 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−
13676 function normalizeRepositoryCloneUrls(
13777 raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
13878 ): GitHubRepositoryCloneUrls {
@@ -154,7 +94,7 @@ function decodeGitHubJson<S extends Schema.Top>( · 15 unmodified lines
15494 (error) =>
15595 new GitHubCliError({
15696 operation,
157− detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
97+ detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
15898 cause: error,
15999 }),
160100 ),
@@ -194,14 +134,24 @@ const makeGitHubCli = Effect.sync(() => { · 33 unmodified lines
194134 Effect.flatMap((raw) =>
195135 raw.length === 0
196136 ? Effect.succeed([])
197− : decodeGitHubJson(
198− raw,
199− Schema.Array(RawGitHubPullRequestSchema),
200− "listOpenPullRequests",
201− "GitHub CLI returned invalid PR list JSON.",
137+ : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
138+ Effect.flatMap((decoded) => {
139+ if (!Result.isSuccess(decoded)) {
140+ return Effect.fail(
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+ }),
202153 ),
203154 ),
204− Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
205155 ),
206156 getPullRequest: (input) =>
207157 execute({
@@ -216,14 +166,24 @@ const makeGitHubCli = Effect.sync(() => { · 8 unmodified lines
216166 }).pipe(
217167 Effect.map((result) => result.stdout.trim()),
218168 Effect.flatMap((raw) =>
219− decodeGitHubJson(
220− raw,
221− RawGitHubPullRequestSchema,
222− "getPullRequest",
223− "GitHub CLI returned invalid pull request JSON.",
169+ Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
170+ Effect.flatMap((decoded) => {
171+ if (!Result.isSuccess(decoded)) {
172+ return Effect.fail(
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+ }),
224185 ),
225186 ),
226− Effect.map(normalizePullRequestSummary),
227187 ),
228188 getRepositoryCloneUrls: (input) =>
229189 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
66 import { it } from "@effect/vitest";
77 import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
88 import { expect } from "vitest";
9−import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
9+import type {
10+ GitActionProgressEvent,
11+ GitPreparePullRequestThreadInput,
12+ ModelSelection,
13+ ThreadId,
14+} from "@t3tools/contracts";
1015
1116 import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
1217 import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -21,6 +26,11 @@ import { GitCore } from "../Services/GitCore.ts"; · 8 unmodified lines
2126 import { makeGitManager } from "./GitManager.ts";
2227 import { ServerConfig } from "../../config.ts";
2328 import { ServerSettingsService } from "../../serverSettings.ts";
29+import {
30+ ProjectSetupScriptRunner,
31+ type ProjectSetupScriptRunnerInput,
32+ type ProjectSetupScriptRunnerShape,
33+} from "../../project/Services/ProjectSetupScriptRunner.ts";
2434
2535 interface FakeGhScenario {
2636 prListSequence?: string[];
@@ -176,6 +186,24 @@ function makeTempDir( · 149 unmodified lines
176186 });
177187 }
178188
189+function 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+
198+function 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+
179207 function runGit(
180208 cwd: string,
181209 args: readonly string[],
@@ -593,7 +621,7 @@ function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; refe · 411 unmodified lines
593621
594622 function preparePullRequestThread(
595623 manager: GitManagerShape,
596− input: { cwd: string; reference: string; mode: "local" | "worktree" },
624+ input: GitPreparePullRequestThreadInput,
597625 ) {
598626 return manager.preparePullRequestThread(input);
599627 }
@@ -601,6 +629,7 @@ function preparePullRequestThread( · 1 unmodified line
601629 function makeManager(input?: {
602630 ghScenario?: FakeGhScenario;
603631 textGeneration?: Partial<FakeGitTextGeneration>;
632+ setupScriptRunner?: ProjectSetupScriptRunnerShape;
604633 }) {
605634 const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
606635 const textGeneration = createTextGeneration(input?.textGeneration);
@@ -618,6 +647,12 @@ function makeManager(input?: { · 11 unmodified lines
618647 const managerLayer = Layer.mergeAll(
619648 Layer.succeed(GitHubCli, gitHubCli),
620649 Layer.succeed(TextGeneration, textGeneration),
650+ Layer.succeed(
651+ ProjectSetupScriptRunner,
652+ input?.setupScriptRunner ?? {
653+ runForThread: () => Effect.succeed({ status: "no-script" as const }),
654+ },
655+ ),
621656 gitCoreLayer,
622657 serverSettingsLayer,
623658 ).pipe(Layer.provideMerge(NodeServices.layer));
@@ -628,6 +663,8 @@ function makeManager(input?: { · 4 unmodified lines
628663 );
629664 }
630665
666+const asThreadId = (threadId: string) => threadId as ThreadId;
667+
631668 const GitManagerTestLayer = GitCoreLive.pipe(
632669 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
633670 Layer.provideMerge(NodeServices.layer),
@@ -675,6 +712,144 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 41 unmodified lines
675712 }),
676713 );
677714
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+
678853 it.effect("status returns an explicit non-repo result for non-git directories", () =>
679854 Effect.gen(function* () {
680855 const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
@@ -701,6 +876,35 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 20 unmodified lines
701876 }),
702877 );
703878
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+
704908 it.effect("status briefly caches repeated lookups for the same cwd", () =>
705909 Effect.gen(function* () {
706910 const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -835,7 +1039,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 128 unmodified lines
8351039 "pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
8361040 );
8371041 }),
838− 12_000,
1042+ 20_000,
8391043 );
8401044
8411045 it.effect(
@@ -943,7 +1147,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 101 unmodified lines
9431147 ),
9441148 ).toBe(false);
9451149 }),
946− 12_000,
1150+ 20_000,
9471151 );
9481152
9491153 it.effect("status returns merged PR state when latest PR was merged", () =>
@@ -1666,7 +1870,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 716 unmodified lines
16661870 false,
16671871 );
16681872 }),
1669− 12_000,
1873+ 20_000,
16701874 );
16711875
16721876 it.effect(
@@ -2176,6 +2380,59 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 503 unmodified lines
21762380 }),
21772381 );
21782382
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+
21792436 it.effect("preserves fork upstream tracking when preparing a worktree PR thread", () =>
21802437 Effect.gen(function* () {
21812438 const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2360,6 +2617,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 178 unmodified lines
23602617 const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`);
23612618 yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);
23622619
2620+ const setupCalls: ProjectSetupScriptRunnerInput[] = [];
23632621 const { manager } = yield* makeManager({
23642622 ghScenario: {
23652623 pullRequest: {
@@ -2371,18 +2629,27 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 5 unmodified lines
23712629 state: "open",
23722630 },
23732631 },
2632+ setupScriptRunner: {
2633+ runForThread: (setupInput) =>
2634+ Effect.sync(() => {
2635+ setupCalls.push(setupInput);
2636+ return { status: "no-script" as const };
2637+ }),
2638+ },
23742639 });
23752640
23762641 const result = yield* preparePullRequestThread(manager, {
23772642 cwd: repoDir,
23782643 reference: "78",
23792644 mode: "worktree",
2645+ threadId: asThreadId("thread-pr-existing-worktree"),
23802646 });
23812647
23822648 expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe(
23832649 fs.realpathSync.native(worktreePath),
23842650 );
23852651 expect(result.branch).toBe("feature/pr-existing-worktree");
2652+ expect(setupCalls).toHaveLength(0);
23862653 }),
23872654 );
23882655
@@ -2562,6 +2829,50 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 173 unmodified lines
25622829 }),
25632830 );
25642831
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+
25652876 it.effect("rejects worktree prep when the PR head branch is checked out in the main repo", () =>
25662877 Effect.gen(function* () {
25672878 const repoDir = yield* makeTempDir("t3code-git-manager-");
apps/server/src/git/Layers/GitManager.ts+155−118
@@ -1,16 +1,31 @@
11 import { randomUUID } from "node:crypto";
22 import { realpathSync } from "node:fs";
33
4−import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } from "effect";
4+import {
5+ Cache,
6+ Duration,
7+ Effect,
8+ Exit,
9+ FileSystem,
10+ Layer,
11+ Option,
12+ Path,
13+ Ref,
14+ Result,
15+} from "effect";
516 import {
617 GitActionProgressEvent,
718 GitActionProgressPhase,
819 GitCommandError,
920 GitRunStackedActionResult,
1021 GitStackedAction,
22+ type GitStatusLocalResult,
23+ type GitStatusRemoteResult,
1124 ModelSelection,
1225 } from "@t3tools/contracts";
1326 import {
27+ detectGitHostingProviderFromRemoteUrl,
28+ mergeGitStatusParts,
1429 resolveAutoFeatureBranchName,
1530 sanitizeBranchFragment,
1631 sanitizeFeatureBranchName,
@@ -26,9 +41,14 @@ import { · 9 unmodified lines
2641 import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";
2742 import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
2843 import { TextGeneration } from "../Services/TextGeneration.ts";
44+import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
2945 import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
3046 import { ServerSettingsService } from "../../serverSettings.ts";
3147 import type { GitManagerServiceError } from "@t3tools/contracts";
48+import {
49+ decodeGitHubPullRequestListJson,
50+ formatGitHubJsonDecodeError,
51+} from "../githubPullRequests.ts";
3252
3353 const COMMIT_TIMEOUT_MS = 10 * 60_000;
3454 const MAX_PROGRESS_TEXT_LENGTH = 500;
@@ -235,85 +255,6 @@ function matchesBranchHeadContext( · 200 unmodified lines
235255 return true;
236256 }
237257
238−function 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−
317258 function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
318259 return {
319260 number: summary.number,
@@ -552,6 +493,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 232 unmodified lines
552493 const gitCore = yield* GitCore;
553494 const gitHubCli = yield* GitHubCli;
554495 const textGeneration = yield* TextGeneration;
496+ const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
555497 const serverSettingsService = yield* ServerSettingsService;
556498
557499 const createProgressEmitter = (
@@ -693,26 +635,54 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 135 unmodified lines
693635
694636 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
695637 const normalizeStatusCacheKey = (cwd: string) => canonicalizeExistingPath(cwd);
696− const readStatus = Effect.fn("readStatus")(function* (cwd: string) {
697− const details = yield* gitCore.statusDetails(cwd).pipe(
698− Effect.catchIf(isNotGitRepositoryError, () =>
699− Effect.succeed({
700− isRepo: false,
701− hasOriginRemote: false,
702− isDefaultBranch: false,
703− branch: null,
704− upstreamRef: null,
705− hasWorkingTreeChanges: false,
706− workingTree: { files: [], insertions: 0, deletions: 0 },
707− hasUpstream: false,
708− aheadCount: 0,
709− behindCount: 0,
710− } satisfies GitStatusDetails),
711− ),
712− );
638+ const nonRepositoryStatusDetails = {
639+ isRepo: false,
640+ hasOriginRemote: false,
641+ isDefaultBranch: false,
642+ branch: null,
643+ upstreamRef: null,
644+ hasWorkingTreeChanges: false,
645+ workingTree: { files: [], insertions: 0, deletions: 0 },
646+ hasUpstream: false,
647+ aheadCount: 0,
648+ behindCount: 0,
649+ } satisfies GitStatusDetails;
650+ const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
651+ const details = yield* gitCore
652+ .statusDetailsLocal(cwd)
653+ .pipe(
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+ }
713683
714684 const pr =
715− details.isRepo && details.branch !== null
685+ details.branch !== null
716686 ? yield* findLatestPr(cwd, {
717687 branch: details.branch,
718688 upstreamRef: details.upstreamRef,
@@ -723,29 +693,37 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 4 unmodified lines
723693 : null;
724694
725695 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,
732696 hasUpstream: details.hasUpstream,
733697 aheadCount: details.aheadCount,
734698 behindCount: details.behindCount,
735699 pr,
736− };
700+ } satisfies GitStatusRemoteResult;
737701 });
738− const statusResultCache = yield* Cache.makeWith({
702+ const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
739703 capacity: STATUS_RESULT_CACHE_CAPACITY,
740− lookup: readStatus,
741704 timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
742705 });
743− const invalidateStatusResultCache = (cwd: string) =>
744− Cache.invalidate(statusResultCache, normalizeStatusCacheKey(cwd));
706+ const invalidateRemoteStatusResultCache = (cwd: string) =>
707+ Cache.invalidate(remoteStatusResultCache, normalizeStatusCacheKey(cwd));
745708
746709 const readConfigValueNullable = (cwd: string, key: string) =>
747710 gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
748711
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+
749727 const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
750728 cwd: string,
751729 remoteName: string | null,
@@ -905,13 +883,23 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 153 unmodified lines
905883 continue;
906884 }
907885
908− const parsedJson = yield* Effect.try({
909− try: () => JSON.parse(raw) as unknown,
910− catch: (cause) =>
911− gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
912− });
886+ const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
887+ Effect.flatMap((decoded) => {
888+ if (!Result.isSuccess(decoded)) {
889+ return Effect.fail(
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+ );
913901
914− for (const pr of parsePullRequestList(parsedJson)) {
902+ for (const pr of pullRequests) {
915903 if (!matchesBranchHeadContext(pr, headContext)) {
916904 continue;
917905 }
@@ -1309,9 +1297,34 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 391 unmodified lines
13091297 };
13101298 });
13111299
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+ );
13121308 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);
13141321 });
1322+ const invalidateStatus: GitManagerShape["invalidateStatus"] = Effect.fn("invalidateStatus")(
1323+ function* (cwd) {
1324+ yield* invalidateLocalStatusResultCache(cwd);
1325+ yield* invalidateRemoteStatusResultCache(cwd);
1326+ },
1327+ );
13151328
13161329 const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
13171330 function* (input) {
@@ -1329,6 +1342,24 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 11 unmodified lines
13291342 const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn(
13301343 "preparePullRequestThread",
13311344 )(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+ };
13321363 return yield* Effect.gen(function* () {
13331364 const normalizedReference = normalizePullRequestReference(input.reference);
13341365 const rootWorktreePath = canonicalizeExistingPath(input.cwd);
@@ -1461,13 +1492,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 126 unmodified lines
14611492 path: null,
14621493 });
14631494 yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
1495+ yield* maybeRunSetupScript(worktree.worktree.path);
14641496
14651497 return {
14661498 pullRequest,
14671499 branch: worktree.worktree.branch,
14681500 worktreePath: worktree.worktree.path,
14691501 };
1470− }).pipe(Effect.ensuring(invalidateStatusResultCache(input.cwd)));
1502+ }).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
14711503 });
14721504
14731505 const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
@@ -1671,7 +1703,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 197 unmodified lines
16711703 });
16721704
16731705 return yield* runAction().pipe(
1674− Effect.ensuring(invalidateStatusResultCache(input.cwd)),
1706+ Effect.ensuring(invalidateStatus(input.cwd)),
16751707 Effect.tapError((error) =>
16761708 Effect.flatMap(Ref.get(currentPhase), (phase) =>
16771709 progress.emit({
@@ -1686,7 +1718,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { · 8 unmodified lines
16861718 );
16871719
16881720 return {
1721+ localStatus,
1722+ remoteStatus,
16891723 status,
1724+ invalidateLocalStatus,
1725+ invalidateRemoteStatus,
1726+ invalidateStatus,
16901727 resolvePullRequest,
16911728 preparePullRequestThread,
16921729 runStackedAction,
apps/server/src/git/Layers/GitStatusBroadcaster.test.ts+312−0
@@ -0,0 +1,312 @@
1+import { assert, it } from "@effect/vitest";
2+import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
3+import type {
4+ GitStatusLocalResult,
5+ GitStatusRemoteResult,
6+ GitStatusResult,
7+ GitStatusStreamEvent,
8+} from "@t3tools/contracts";
9+import { describe } from "vitest";
10+
11+import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
12+import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
13+import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
14+
15+const 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+
29+const baseRemoteStatus: GitStatusRemoteResult = {
30+ hasUpstream: true,
31+ aheadCount: 0,
32+ behindCount: 0,
33+ pr: null,
34+};
35+
36+const baseStatus: GitStatusResult = {
37+ ...baseLocalStatus,
38+ ...baseRemoteStatus,
39+};
40+
41+function 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+
79+describe("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 @@
1+import { realpathSync } from "node:fs";
2+
3+import {
4+ Duration,
5+ Effect,
6+ Exit,
7+ Fiber,
8+ Layer,
9+ PubSub,
10+ Ref,
11+ Scope,
12+ Stream,
13+ SynchronizedRef,
14+} from "effect";
15+import type {
16+ GitStatusInput,
17+ GitStatusLocalResult,
18+ GitStatusRemoteResult,
19+ GitStatusStreamEvent,
20+} from "@t3tools/contracts";
21+import { mergeGitStatusParts } from "@t3tools/shared/git";
22+
23+import {
24+ GitStatusBroadcaster,
25+ type GitStatusBroadcasterShape,
26+} from "../Services/GitStatusBroadcaster.ts";
27+import { GitManager } from "../Services/GitManager.ts";
28+
29+const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
30+
31+interface GitStatusChange {
32+ readonly cwd: string;
33+ readonly event: GitStatusStreamEvent;
34+}
35+
36+interface CachedValue<T> {
37+ readonly fingerprint: string;
38+ readonly value: T;
39+}
40+
41+interface CachedGitStatus {
42+ readonly local: CachedValue<GitStatusLocalResult> | null;
43+ readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
44+}
45+
46+interface ActiveRemotePoller {
47+ readonly fiber: Fiber.Fiber<void, never>;
48+ readonly subscriberCount: number;
49+}
50+
51+function normalizeCwd(cwd: string): string {
52+ try {
53+ return realpathSync.native(cwd);
54+ } catch {
55+ return cwd;
56+ }
57+}
58+
59+function fingerprintStatusPart(status: unknown): string {
60+ return JSON.stringify(status);
61+}
62+
63+export 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
99 *
1010 * @module RoutingTextGeneration
1111 */
12−import { Effect, Layer, ServiceMap } from "effect";
12+import { Effect, Layer, Context } from "effect";
1313
1414 import {
1515 TextGeneration,
@@ -23,11 +23,11 @@ import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; · 7 unmodified lines
2323 // Internal service tags so both concrete layers can coexist.
2424 // ---------------------------------------------------------------------------
2525
26−class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
26+class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
2727 "t3/git/Layers/RoutingTextGeneration/CodexTextGen",
2828 ) {}
2929
30−class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
30+class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
3131 "t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
3232 ) {}
3333
apps/server/src/git/Services/GitCore.ts+14−7
@@ -6,11 +6,13 @@ · 5 unmodified lines
66 *
77 * @module GitCore
88 */
9−import { ServiceMap } from "effect";
10−import type { Effect, Scope } from "effect";
9+import { Context } from "effect";
10+import type { Effect } from "effect";
1111 import type {
1212 GitCheckoutInput,
13+ GitCheckoutResult,
1314 GitCreateBranchInput,
15+ GitCreateBranchResult,
1416 GitCreateWorktreeInput,
1517 GitCreateWorktreeResult,
1618 GitInitInput,
@@ -156,6 +158,11 @@ export interface GitCoreShape { · 139 unmodified lines
156158 */
157159 readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
158160
161+ /**
162+ * Read detailed working tree / branch status without refreshing remote tracking refs.
163+ */
164+ readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
165+
159166 /**
160167 * Build staged change context for commit generation.
161168 */
@@ -278,14 +285,16 @@ export interface GitCoreShape { · 116 unmodified lines
278285 /**
279286 * Create a local branch.
280287 */
281− readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;
288+ readonly createBranch: (
289+ input: GitCreateBranchInput,
290+ ) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
282291
283292 /**
284293 * Checkout an existing branch and refresh its upstream metadata in background.
285294 */
286295 readonly checkoutBranch: (
287296 input: GitCheckoutInput,
288− ) => Effect.Effect<void, GitCommandError, Scope.Scope>;
297+ ) => Effect.Effect<GitCheckoutResult, GitCommandError>;
289298
290299 /**
291300 * Initialize a repository in the provided directory.
@@ -301,6 +310,4 @@ export interface GitCoreShape { · 9 unmodified lines
301310 /**
302311 * GitCore - Service tag for low-level Git repository operations.
303312 */
304−export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(
305− "t3/git/Services/GitCore",
306−) {}
313+export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
apps/server/src/git/Services/GitHubCli.ts+2−2
@@ -5,7 +5,7 @@ · 4 unmodified lines
55 *
66 * @module GitHubCli
77 */
8−import { ServiceMap } from "effect";
8+import { Context } from "effect";
99 import type { Effect } from "effect";
1010
1111 import type { ProcessRunResult } from "../../processRunner";
@@ -98,6 +98,6 @@ export interface GitHubCliShape { · 86 unmodified lines
9898 /**
9999 * GitHubCli - Service tag for GitHub CLI process execution.
100100 */
101−export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()(
101+export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
102102 "t3/git/Services/GitHubCli",
103103 ) {}
apps/server/src/git/Services/GitManager.ts+33−2
@@ -14,10 +14,12 @@ import { · 13 unmodified lines
1414 GitResolvePullRequestResult,
1515 GitRunStackedActionInput,
1616 GitRunStackedActionResult,
17+ GitStatusLocalResult,
18+ GitStatusRemoteResult,
1719 GitStatusInput,
1820 GitStatusResult,
1921 } from "@t3tools/contracts";
20−import { ServiceMap } from "effect";
22+import { Context } from "effect";
2123 import type { Effect } from "effect";
2224 import type { GitManagerServiceError } from "@t3tools/contracts";
2325
@@ -41,6 +43,35 @@ export interface GitManagerShape { · 17 unmodified lines
4143 input: GitStatusInput,
4244 ) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
4345
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+
4475 /**
4576 * Resolve a pull request by URL/number against the current repository.
4677 */
@@ -68,6 +99,6 @@ export interface GitManagerShape { · 21 unmodified lines
6899 /**
69100 * GitManager - Service tag for stacked Git workflow orchestration.
70101 */
71−export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
102+export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
72103 "t3/git/Services/GitManager",
73104 ) {}
apps/server/src/git/Services/GitStatusBroadcaster.ts+27−0
@@ -0,0 +1,27 @@
1+import { Context } from "effect";
2+import type { Effect, Stream } from "effect";
3+import type {
4+ GitManagerServiceError,
5+ GitStatusInput,
6+ GitStatusLocalResult,
7+ GitStatusResult,
8+ GitStatusStreamEvent,
9+} from "@t3tools/contracts";
10+
11+export 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+
24+export 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
66 *
77 * @module TextGeneration
88 */
9−import { ServiceMap } from "effect";
9+import { Context } from "effect";
1010 import type { Effect } from "effect";
1111 import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
1212
@@ -118,6 +118,6 @@ export interface TextGenerationShape { · 105 unmodified lines
118118 /**
119119 * TextGeneration - Service tag for commit and PR text generation.
120120 */
121−export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(
121+export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
122122 "t3/git/Services/TextGeneration",
123123 ) {}
apps/server/src/git/githubPullRequests.ts+128−0
@@ -0,0 +1,128 @@
1+import { Cause, Exit, Result, Schema } from "effect";
2+import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
3+import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
4+
5+export 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+
18+const 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+
44+function trimOptionalString(value: string | null | undefined): string | null {
45+ const trimmed = value?.trim() ?? "";
46+ return trimmed.length > 0 ? trimmed : null;
47+}
48+
49+function 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+
66+function 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+
93+const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
94+const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
95+const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
96+
97+export const formatGitHubJsonDecodeError = formatSchemaError;
98+
99+export 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+
120+export 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 @@
1+import { describe, expect, it } from "vitest";
2+
3+import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
4+
5+describe("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 @@
11 import Mime from "@effect/platform-node/Mime";
2−import { Effect, FileSystem, Option, Path } from "effect";
3−import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
2+import { Data, Effect, FileSystem, Option, Path } from "effect";
3+import { cast } from "effect/Function";
4+import {
5+ HttpBody,
6+ HttpClient,
7+ HttpClientResponse,
8+ HttpRouter,
9+ HttpServerResponse,
10+ HttpServerRequest,
11+} from "effect/unstable/http";
12+import { OtlpTracer } from "effect/unstable/observability";
413
514 import {
615 ATTACHMENTS_ROUTE_PREFIX,
@@ -8,16 +17,117 @@ import { · 1 unmodified line
817 resolveAttachmentRelativePath,
918 } from "./attachmentPaths";
1019 import { resolveAttachmentPathById } from "./attachmentStore";
11−import { ServerConfig } from "./config";
20+import { resolveStaticDir, ServerConfig } from "./config";
21+import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
22+import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
1223 import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
24+import { ServerAuth } from "./auth/Services/ServerAuth.ts";
25+import { respondToAuthError } from "./auth/http.ts";
26+import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
1327
1428 const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
1529 const 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>`;
30+const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
31+const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
32+
33+export const browserApiCorsLayer = HttpRouter.cors({
34+ allowedMethods: ["GET", "POST", "OPTIONS"],
35+ allowedHeaders: ["authorization", "b3", "traceparent", "content-type"],
36+ maxAge: 600,
37+});
38+
39+export function isLoopbackHostname(hostname: string): boolean {
40+ const normalizedHostname = hostname
41+ .trim()
42+ .toLowerCase()
43+ .replace(/^\[(.*)\]$/, "$1");
44+ return LOOPBACK_HOSTNAMES.has(normalizedHostname);
45+}
46+
47+export 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+
55+const requireAuthenticatedRequest = Effect.gen(function* () {
56+ const request = yield* HttpServerRequest.HttpServerRequest;
57+ const serverAuth = yield* ServerAuth;
58+ yield* serverAuth.authenticateHttpRequest(request);
59+});
60+
61+export 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+
72+class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
73+ readonly cause: unknown;
74+ readonly bodyJson: OtlpTracer.TraceData;
75+}> {}
76+
77+export 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+);
16125
17126 export const attachmentsRouteLayer = HttpRouter.add(
18127 "GET",
19128 `${ATTACHMENTS_ROUTE_PREFIX}/*`,
20129 Effect.gen(function* () {
130+ yield* requireAuthenticatedRequest;
21131 const request = yield* HttpServerRequest.HttpServerRequest;
22132 const url = HttpServerRequest.toURL(request);
23133 if (Option.isNone(url)) {
@@ -66,13 +176,14 @@ export const attachmentsRouteLayer = HttpRouter.add( · 42 unmodified lines
66176 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
67177 ),
68178 );
69− }),
179+ }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
70180 );
71181
72182 export const projectFaviconRouteLayer = HttpRouter.add(
73183 "GET",
74184 "/api/project-favicon",
75185 Effect.gen(function* () {
186+ yield* requireAuthenticatedRequest;
76187 const request = yield* HttpServerRequest.HttpServerRequest;
77188 const url = HttpServerRequest.toURL(request);
78189 if (Option.isNone(url)) {
@@ -106,7 +217,7 @@ export const projectFaviconRouteLayer = HttpRouter.add( · 27 unmodified lines
106217 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
107218 ),
108219 );
109− }),
220+ }).pipe(Effect.catchTag("AuthError", respondToAuthError)),
110221 );
111222
112223 export const staticAndDevRouteLayer = HttpRouter.add(
@@ -120,11 +231,14 @@ export const staticAndDevRouteLayer = HttpRouter.add( · 7 unmodified lines
120231 }
121232
122233 const config = yield* ServerConfig;
123− if (config.devUrl) {
124− return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
234+ if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
235+ return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
236+ status: 302,
237+ });
125238 }
126239
127− if (!config.staticDir) {
240+ const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined);
241+ if (!staticDir) {
128242 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
129243 status: 503,
130244 });
@@ -132,7 +246,7 @@ export const staticAndDevRouteLayer = HttpRouter.add( · 1 unmodified line
132246
133247 const fileSystem = yield* FileSystem.FileSystem;
134248 const path = yield* Path.Path;
135− const staticRoot = path.resolve(config.staticDir);
249+ const staticRoot = path.resolve(staticDir);
136250 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
137251 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
138252 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
22 import * as NodeServices from "@effect/platform-node/NodeServices";
33 import { assert, it } from "@effect/vitest";
44 import { assertFailure } from "@effect/vitest/utils";
5−import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
5+import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
66 import { ServerConfig } from "./config";
77
88 import {
@@ -149,6 +149,23 @@ it.layer(NodeServices.layer)("keybindings", (it) => { · 140 unmodified lines
149149 }),
150150 );
151151
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+
152169 it.effect("bootstraps default keybindings when config file is missing", () =>
153170 Effect.gen(function* () {
154171 const fs = yield* FileSystem.FileSystem;
apps/server/src/keybindings.ts+5−4
@@ -39,7 +39,7 @@ import { · 38 unmodified lines
3939 SchemaIssue,
4040 SchemaTransformation,
4141 Ref,
42− ServiceMap,
42+ Context,
4343 Scope,
4444 Stream,
4545 } from "effect";
@@ -61,6 +61,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [ · 15 unmodified lines
6161 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
6262 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
6363 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
64+ { key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
6465 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
6566 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
6667 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
@@ -322,7 +323,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( · 255 unmodified lines
322323 Predicate.isNotNull,
323324 () =>
324325 new SchemaIssue.InvalidValue(Option.some(rule), {
325− title: "Invalid keybinding rule",
326+ message: "Invalid keybinding rule",
326327 }),
327328 ),
328329 Effect.map((resolved) => resolved),
@@ -334,7 +335,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( · 5 unmodified lines
334335 if (!key) {
335336 return yield* Effect.fail(
336337 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",
338339 }),
339340 );
340341 }
@@ -521,7 +522,7 @@ export interface KeybindingsShape { · 180 unmodified lines
521522 /**
522523 * Keybindings - Service tag for keybinding configuration operations.
523524 */
524−export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
525+export class Keybindings extends Context.Service<Keybindings, KeybindingsShape>()(
525526 "t3/keybindings",
526527 ) {}
527528
apps/server/src/observability/Attributes.test.ts+46−0
@@ -0,0 +1,46 @@
1+import { assert, describe, it } from "@effect/vitest";
2+
3+import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts";
4+
5+describe("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 @@
1+import { Cause, Exit } from "effect";
2+
3+export type MetricAttributeValue = string;
4+export type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;
5+export type TraceAttributes = Readonly<Record<string, unknown>>;
6+export type ObservabilityOutcome = "success" | "failure" | "interrupt";
7+
8+function isPlainObject(value: unknown): value is Record<string, unknown> {
9+ return typeof value === "object" && value !== null && !Array.isArray(value);
10+}
11+
12+function 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+
20+function 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+
77+export 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+
87+export 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+
106+export 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+
113+export 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 @@
1+import { Effect, Layer, References, Tracer } from "effect";
2+import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
3+
4+import { ServerConfig } from "../../config.ts";
5+import { ServerLoggerLive } from "../../serverLogger.ts";
6+import { makeLocalFileTracer } from "../LocalFileTracer.ts";
7+import { BrowserTraceCollector } from "../Services/BrowserTraceCollector.ts";
8+import { makeTraceSink } from "../TraceSink.ts";
9+
10+const otlpSerializationLayer = OtlpSerialization.layerJson;
11+
12+export 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 @@
1+import fs from "node:fs";
2+import os from "node:os";
3+import path from "node:path";
4+
5+import { assert, describe, it } from "@effect/vitest";
6+import { Effect, Layer, Logger, References, Tracer } from "effect";
7+
8+import type { EffectTraceRecord } from "./TraceRecord.ts";
9+import { makeLocalFileTracer } from "./LocalFileTracer.ts";
10+
11+const 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+
26+const 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+
34+describe("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 @@
1+import type * as Exit from "effect/Exit";
2+import { Effect, Option, Tracer } from "effect";
3+
4+import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";
5+import { makeTraceSink, type TraceSink } from "./TraceSink.ts";
6+
7+export 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+
16+class 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+
83+export 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 @@
1+import { assert, describe, it } from "@effect/vitest";
2+import { Effect, Metric } from "effect";
3+
4+import { withMetrics } from "./Metrics.ts";
5+
6+const 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+
17+describe("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 @@
1+import { Duration, Effect, Exit, Metric } from "effect";
2+import { dual } from "effect/Function";
3+
4+import {
5+ compactMetricAttributes,
6+ normalizeModelMetricLabel,
7+ outcomeFromExit,
8+} from "./Attributes.ts";
9+
10+export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", {
11+ description: "Total RPC requests handled by the websocket RPC server.",
12+});
13+
14+export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", {
15+ description: "RPC request handling duration.",
16+});
17+
18+export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", {
19+ description: "Total orchestration commands dispatched.",
20+});
21+
22+export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", {
23+ description: "Orchestration command dispatch duration.",
24+});
25+
26+export 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+
34+export const orchestrationEventsProcessedTotal = Metric.counter(
35+ "t3_orchestration_events_processed_total",
36+ {
37+ description: "Total orchestration intent events processed by runtime reactors.",
38+ },
39+);
40+
41+export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
42+ description: "Total provider session lifecycle operations.",
43+});
44+
45+export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", {
46+ description: "Total provider turn lifecycle operations.",
47+});
48+
49+export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
50+ description: "Provider turn request duration.",
51+});
52+
53+export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", {
54+ description: "Total canonical provider runtime events processed.",
55+});
56+
57+export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {
58+ description: "Total git commands executed by the server runtime.",
59+});
60+
61+export const gitCommandDuration = Metric.timer("t3_git_command_duration", {
62+ description: "Git command execution duration.",
63+});
64+
65+export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", {
66+ description: "Total terminal sessions started.",
67+});
68+
69+export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", {
70+ description: "Total terminal restart requests handled.",
71+});
72+
73+export const metricAttributes = (
74+ attributes: Readonly<Record<string, unknown>>,
75+): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
76+
77+export 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+
83+export 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+
94+const 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+
133+export 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+
140+export const providerMetricAttributes = (
141+ provider: string,
142+ extra?: Readonly<Record<string, unknown>>,
143+) =>
144+ compactMetricAttributes({
145+ provider,
146+ ...extra,
147+ });
148+
149+export 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 @@
1+import { assert, describe, it } from "@effect/vitest";
2+import { Effect, Exit, Metric, Stream } from "effect";
3+
4+import {
5+ observeRpcEffect,
6+ observeRpcStream,
7+ observeRpcStreamEffect,
8+} from "./RpcInstrumentation.ts";
9+
10+const 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+
21+describe("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 @@
1+import { Duration, Effect, Exit, Metric, Stream } from "effect";
2+
3+import { outcomeFromExit } from "./Attributes.ts";
4+import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
5+
6+const 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+
15+const 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+
37+export 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+
56+export 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+
69+export 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 @@
1+import { Context } from "effect";
2+import type { Effect } from "effect";
3+
4+import type { TraceRecord } from "../TraceRecord.ts";
5+
6+export interface BrowserTraceCollectorShape {
7+ readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
8+}
9+
10+export 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 @@
1+import { Cause, Exit, Option, Tracer } from "effect";
2+
3+import { compactTraceAttributes } from "./Attributes.ts";
4+import { OtlpResource, OtlpTracer } from "effect/unstable/observability";
5+
6+interface TraceRecordEvent {
7+ readonly name: string;
8+ readonly timeUnixNano: string;
9+ readonly attributes: Readonly<Record<string, unknown>>;
10+}
11+
12+interface TraceRecordLink {
13+ readonly traceId: string;
14+ readonly spanId: string;
15+ readonly attributes: Readonly<Record<string, unknown>>;
16+}
17+
18+interface 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+
33+export 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+
49+interface 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+
65+export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
66+
67+type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
68+type OtlpSpanEvent = OtlpSpan["events"][number];
69+type OtlpSpanLink = OtlpSpan["links"][number];
70+type OtlpSpanStatus = OtlpSpan["status"];
71+
72+interface 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+
87+function 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+
103+export 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+
133+const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
134+ 1: "internal",
135+ 2: "server",
136+ 3: "client",
137+ 4: "producer",
138+ 5: "consumer",
139+};
140+
141+export 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+
174+function 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+
207+function 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+
217+function 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+
225+function 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+
237+function 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+
249+function 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+
277+function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
278+ return SPAN_KIND_MAP[input] || "internal";
279+}
280+
281+function 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 @@
1+import fs from "node:fs";
2+import os from "node:os";
3+import path from "node:path";
4+
5+import { assert, describe, it } from "@effect/vitest";
6+import { Effect } from "effect";
7+
8+import type { TraceRecord } from "./TraceRecord.ts";
9+import { makeTraceSink } from "./TraceSink.ts";
10+
11+const 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+
31+describe("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 @@
1+import { RotatingFileSink } from "@t3tools/shared/logging";
2+import { Effect } from "effect";
3+
4+import type { TraceRecord } from "./TraceRecord.ts";
5+
6+const FLUSH_BUFFER_THRESHOLD = 32;
7+
8+export interface TraceSinkOptions {
9+ readonly filePath: string;
10+ readonly maxBytes: number;
11+ readonly maxFiles: number;
12+ readonly batchWindowMs: number;
13+}
14+
15+export interface TraceSink {
16+ readonly filePath: string;
17+ push: (record: TraceRecord) => void;
18+ flush: Effect.Effect<void>;
19+ close: () => Effect.Effect<void>;
20+}
21+
22+export 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
1616 const antigravityLaunch = yield* resolveEditorLaunch(
1717 { cwd: "/tmp/workspace", editor: "antigravity" },
1818 "darwin",
19+ { PATH: "" },
1920 );
2021 assert.deepEqual(antigravityLaunch, {
2122 command: "agy",
@@ -25,6 +26,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 3 unmodified lines
2526 const cursorLaunch = yield* resolveEditorLaunch(
2627 { cwd: "/tmp/workspace", editor: "cursor" },
2728 "darwin",
29+ { PATH: "" },
2830 );
2931 assert.deepEqual(cursorLaunch, {
3032 command: "cursor",
@@ -43,6 +45,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 12 unmodified lines
4345 const vscodeLaunch = yield* resolveEditorLaunch(
4446 { cwd: "/tmp/workspace", editor: "vscode" },
4547 "darwin",
48+ { PATH: "" },
4649 );
4750 assert.deepEqual(vscodeLaunch, {
4851 command: "code",
@@ -70,19 +73,30 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 21 unmodified lines
7073 const zedLaunch = yield* resolveEditorLaunch(
7174 { cwd: "/tmp/workspace", editor: "zed" },
7275 "darwin",
76+ { PATH: "" },
7377 );
7478 assert.deepEqual(zedLaunch, {
7579 command: "zed",
7680 args: ["/tmp/workspace"],
7781 });
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+ });
7891 }),
7992 );
8093
81− it.effect("uses --goto when editor supports line/column suffixes", () =>
94+ it.effect("applies launch-style-specific navigation arguments", () =>
8295 Effect.gen(function* () {
8396 const lineOnly = yield* resolveEditorLaunch(
8497 { cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
8598 "darwin",
99+ { PATH: "" },
86100 );
87101 assert.deepEqual(lineOnly, {
88102 command: "cursor",
@@ -92,6 +106,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 3 unmodified lines
92106 const lineAndColumn = yield* resolveEditorLaunch(
93107 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
94108 "darwin",
109+ { PATH: "" },
95110 );
96111 assert.deepEqual(lineAndColumn, {
97112 command: "cursor",
@@ -110,6 +125,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 12 unmodified lines
110125 const vscodeLineAndColumn = yield* resolveEditorLaunch(
111126 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
112127 "darwin",
128+ { PATH: "" },
113129 );
114130 assert.deepEqual(vscodeLineAndColumn, {
115131 command: "code",
@@ -137,11 +153,71 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 21 unmodified lines
137153 const zedLineAndColumn = yield* resolveEditorLaunch(
138154 { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
139155 "darwin",
156+ { PATH: "" },
140157 );
141158 assert.deepEqual(zedLineAndColumn, {
142159 command: "zed",
143160 args: ["/tmp/workspace/src/open.ts:71:5"],
144161 });
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+ });
145221 }),
146222 );
147223
@@ -150,6 +226,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 2 unmodified lines
150226 const launch1 = yield* resolveEditorLaunch(
151227 { cwd: "/tmp/workspace", editor: "file-manager" },
152228 "darwin",
229+ { PATH: "" },
153230 );
154231 assert.deepEqual(launch1, {
155232 command: "open",
@@ -159,6 +236,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 3 unmodified lines
159236 const launch2 = yield* resolveEditorLaunch(
160237 { cwd: "C:\\workspace", editor: "file-manager" },
161238 "win32",
239+ { PATH: "" },
162240 );
163241 assert.deepEqual(launch2, {
164242 command: "explorer",
@@ -168,6 +246,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { · 3 unmodified lines
168246 const launch3 = yield* resolveEditorLaunch(
169247 { cwd: "/tmp/workspace", editor: "file-manager" },
170248 "linux",
249+ { PATH: "" },
171250 );
172251 assert.deepEqual(launch3, {
173252 command: "xdg-open",
@@ -285,4 +364,29 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => { · 111 unmodified lines
285364 assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
286365 }),
287366 );
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+ });
288392 });
apps/server/src/open.ts+86−17
@@ -11,7 +11,7 @@ import { accessSync, constants, statSync } from "node:fs"; · 10 unmodified lines
1111 import { extname, join } from "node:path";
1212
1313 import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
14−import { ServiceMap, Effect, Layer } from "effect";
14+import { Context, Effect, Layer } from "effect";
1515
1616 // ==============================
1717 // Definitions
@@ -34,10 +34,57 @@ interface CommandAvailabilityOptions { · 16 unmodified lines
3434 readonly env?: NodeJS.ProcessEnv;
3535 }
3636
37−const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
37+const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
3838
39−function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
40− return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
39+function parseTargetPathAndPosition(target: string): {
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+
56+function 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+
78+function 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;
4188 }
4289
4390 function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
@@ -163,8 +210,16 @@ export function resolveAvailableEditors( · 119 unmodified lines
163210 const available: EditorId[] = [];
164211
165212 for (const editor of EDITORS) {
166− const command = editor.command ?? fileManagerCommandForPlatform(platform);
167− if (isCommandAvailable(command, { platform, env })) {
213+ if (editor.commands === null) {
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) {
168223 available.push(editor.id);
169224 }
170225 }
@@ -192,25 +247,34 @@ export interface OpenShape { · 21 unmodified lines
192247 /**
193248 * Open - Service tag for browser/editor launch operations.
194249 */
195−export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
250+export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
196251
197252 // ==============================
198253 // Implementations
199254 // ==============================
200255
201−export const resolveEditorLaunch = Effect.fnUntraced(function* (
256+export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
202257 input: OpenInEditorInput,
203258 platform: NodeJS.Platform = process.platform,
259+ env: NodeJS.ProcessEnv = process.env,
204260 ): Effect.fn.Return<EditorLaunch, OpenError> {
261+ yield* Effect.annotateCurrentSpan({
262+ "open.editor": input.editor,
263+ "open.cwd": input.cwd,
264+ "open.platform": platform,
265+ });
205266 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
206267 if (!editorDef) {
207268 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
208269 }
209270
210− if (editorDef.command) {
211− return shouldUseGotoFlag(editorDef, input.cwd)
212− ? { command: editorDef.command, args: ["--goto", input.cwd] }
213− : { command: editorDef.command, args: [input.cwd] };
271+ if (editorDef.commands) {
272+ const command =
273+ resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
274+ return {
275+ command,
276+ args: resolveCommandEditorArgs(editorDef, input.cwd),
277+ };
214278 }
215279
216280 if (editorDef.id !== "file-manager") {
@@ -229,11 +293,16 @@ export const launchDetached = (launch: EditorLaunch) => · 12 unmodified lines
229293 yield* Effect.callback<void, OpenError>((resume) => {
230294 let child;
231295 try {
232− child = spawn(launch.command, [...launch.args], {
233− detached: true,
234− stdio: "ignore",
235− shell: process.platform === "win32",
236− });
296+ const isWin32 = process.platform === "win32";
297+ child = spawn(
298+ launch.command,
299+ isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
300+ {
301+ detached: true,
302+ stdio: "ignore",
303+ shell: isWin32,
304+ },
305+ );
237306 } catch (error) {
238307 return resume(
239308 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
2020 import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
2121 import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
2222 import { GitCoreLive } from "../../git/Layers/GitCore.ts";
23+import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
24+import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
2325 import { CheckpointReactorLive } from "./CheckpointReactor.ts";
2426 import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
2527 import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -42,8 +44,8 @@ import { ServerConfig } from "../../config.ts"; · 16 unmodified lines
4244 import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
4345 import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
4446
45−const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
46−const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
47+const asProjectId = (value: string): ProjectId => ProjectId.make(value);
48+const asTurnId = (value: string): TurnId => TurnId.make(value);
4749
4850 type LegacyProviderRuntimeEvent = {
4951 readonly type: string;
@@ -79,7 +81,7 @@ function createProviderServiceHarness( · 29 unmodified lines
7981 provider: providerName,
8082 status: "ready",
8183 runtimeMode: "full-access",
82− threadId: ThreadId.makeUnsafe("thread-1"),
84+ threadId: ThreadId.make("thread-1"),
8385 cwd: sessionCwd,
8486 createdAt: now,
8587 updatedAt: now,
@@ -96,7 +98,9 @@ function createProviderServiceHarness( · 10 unmodified lines
9698 listSessions,
9799 getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
98100 rollbackConversation,
99− streamEvents: Stream.fromPubSub(runtimeEventPubSub),
101+ get streamEvents() {
102+ return Stream.fromPubSub(runtimeEventPubSub);
103+ },
100104 };
101105
102106 const emit = (event: LegacyProviderRuntimeEvent): void => {
@@ -126,7 +130,7 @@ async function waitForThread( · 23 unmodified lines
126130 activities: ReadonlyArray<{ kind: string }>;
127131 }> => {
128132 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"));
130134 if (thread && predicate(thread)) {
131135 return thread;
132136 }
@@ -240,6 +244,7 @@ describe("CheckpointReactor", () => { · 107 unmodified lines
240244 readonly threadWorktreePath?: string | null;
241245 readonly providerSessionCwd?: string;
242246 readonly providerName?: ProviderKind;
247+ readonly gitStatusRefreshCalls?: Array<string>;
243248 }) {
244249 const cwd = createGitRepository();
245250 tempDirs.push(cwd);
@@ -254,17 +259,37 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
254259 Layer.provide(OrchestrationProjectionPipelineLive),
255260 Layer.provide(OrchestrationEventStoreLive),
256261 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
262+ Layer.provide(RepositoryIdentityResolverLive),
257263 Layer.provide(SqlitePersistenceMemory),
258264 );
259265
260266 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
261267 prefix: "t3-checkpoint-reactor-test-",
262268 });
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+ });
263287
264288 const layer = CheckpointReactorLive.pipe(
265289 Layer.provideMerge(orchestrationLayer),
266290 Layer.provideMerge(RuntimeReceiptBusLive),
267291 Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
292+ Layer.provideMerge(gitStatusBroadcasterLayer),
268293 Layer.provideMerge(CheckpointStoreLive),
269294 Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
270295 Layer.provideMerge(WorkspacePathsLive),
@@ -285,7 +310,7 @@ describe("CheckpointReactor", () => { · 14 unmodified lines
285310 await Effect.runPromise(
286311 engine.dispatch({
287312 type: "project.create",
288− commandId: CommandId.makeUnsafe("cmd-project-create"),
313+ commandId: CommandId.make("cmd-project-create"),
289314 projectId: asProjectId("project-1"),
290315 title: "Test Project",
291316 workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
@@ -299,8 +324,8 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
299324 await Effect.runPromise(
300325 engine.dispatch({
301326 type: "thread.create",
302− commandId: CommandId.makeUnsafe("cmd-thread-create"),
303− threadId: ThreadId.makeUnsafe("thread-1"),
327+ commandId: CommandId.make("cmd-thread-create"),
328+ threadId: ThreadId.make("thread-1"),
304329 projectId: asProjectId("project-1"),
305330 title: "Thread",
306331 modelSelection: {
@@ -319,21 +344,21 @@ describe("CheckpointReactor", () => { · 12 unmodified lines
319344 await runtime.runPromise(
320345 checkpointStore.captureCheckpoint({
321346 cwd,
322− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
347+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
323348 }),
324349 );
325350 fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
326351 await runtime.runPromise(
327352 checkpointStore.captureCheckpoint({
328353 cwd,
329− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
354+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
330355 }),
331356 );
332357 fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
333358 await runtime.runPromise(
334359 checkpointStore.captureCheckpoint({
335360 cwd,
336− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
361+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
337362 }),
338363 );
339364 }
@@ -353,10 +378,10 @@ describe("CheckpointReactor", () => { · 13 unmodified lines
353378 await Effect.runPromise(
354379 harness.engine.dispatch({
355380 type: "thread.session.set",
356− commandId: CommandId.makeUnsafe("cmd-session-set-capture"),
357− threadId: ThreadId.makeUnsafe("thread-1"),
381+ commandId: CommandId.make("cmd-session-set-capture"),
382+ threadId: ThreadId.make("thread-1"),
358383 session: {
359− threadId: ThreadId.makeUnsafe("thread-1"),
384+ threadId: ThreadId.make("thread-1"),
360385 status: "ready",
361386 providerName: "codex",
362387 runtimeMode: "approval-required",
@@ -370,26 +395,26 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
370395
371396 harness.provider.emit({
372397 type: "turn.started",
373− eventId: EventId.makeUnsafe("evt-turn-started-1"),
398+ eventId: EventId.make("evt-turn-started-1"),
374399 provider: "codex",
375400
376401 createdAt: new Date().toISOString(),
377− threadId: ThreadId.makeUnsafe("thread-1"),
402+ threadId: ThreadId.make("thread-1"),
378403 turnId: asTurnId("turn-1"),
379404 });
380405 await waitForGitRefExists(
381406 harness.cwd,
382− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
407+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
383408 );
384409
385410 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
386411 harness.provider.emit({
387412 type: "turn.completed",
388− eventId: EventId.makeUnsafe("evt-turn-completed-1"),
413+ eventId: EventId.make("evt-turn-completed-1"),
389414 provider: "codex",
390415
391416 createdAt: new Date().toISOString(),
392− threadId: ThreadId.makeUnsafe("thread-1"),
417+ threadId: ThreadId.make("thread-1"),
393418 turnId: asTurnId("turn-1"),
394419 payload: { state: "completed" },
395420 });
@@ -401,27 +426,49 @@ describe("CheckpointReactor", () => { · 5 unmodified lines
401426 );
402427 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
403428 expect(
404− gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
429+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
405430 ).toBe(true);
406431 expect(
407− gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
432+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
408433 ).toBe(true);
409434 expect(
410435 gitShowFileAtRef(
411436 harness.cwd,
412− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
437+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
413438 "README.md",
414439 ),
415440 ).toBe("v1\n");
416441 expect(
417442 gitShowFileAtRef(
418443 harness.cwd,
419− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
444+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
420445 "README.md",
421446 ),
422447 ).toBe("v2\n");
423448 });
424449
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+
425472 it("ignores auxiliary thread turn completion while primary turn is active", async () => {
426473 const harness = await createHarness({ seedFilesystemCheckpoints: false });
427474 const createdAt = new Date().toISOString();
@@ -429,10 +476,10 @@ describe("CheckpointReactor", () => { · 1 unmodified line
429476 await Effect.runPromise(
430477 harness.engine.dispatch({
431478 type: "thread.session.set",
432− commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
433− threadId: ThreadId.makeUnsafe("thread-1"),
479+ commandId: CommandId.make("cmd-session-set-primary-running"),
480+ threadId: ThreadId.make("thread-1"),
434481 session: {
435− threadId: ThreadId.makeUnsafe("thread-1"),
482+ threadId: ThreadId.make("thread-1"),
436483 status: "running",
437484 providerName: "codex",
438485 runtimeMode: "approval-required",
@@ -446,45 +493,43 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
446493
447494 harness.provider.emit({
448495 type: "turn.started",
449− eventId: EventId.makeUnsafe("evt-turn-started-main"),
496+ eventId: EventId.make("evt-turn-started-main"),
450497 provider: "codex",
451498
452499 createdAt: new Date().toISOString(),
453− threadId: ThreadId.makeUnsafe("thread-1"),
500+ threadId: ThreadId.make("thread-1"),
454501 turnId: asTurnId("turn-main"),
455502 });
456503 await waitForGitRefExists(
457504 harness.cwd,
458− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
505+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
459506 );
460507
461508 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
462509
463510 harness.provider.emit({
464511 type: "turn.completed",
465− eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
512+ eventId: EventId.make("evt-turn-completed-aux"),
466513 provider: "codex",
467514
468515 createdAt: new Date().toISOString(),
469− threadId: ThreadId.makeUnsafe("thread-1"),
516+ threadId: ThreadId.make("thread-1"),
470517 turnId: asTurnId("turn-aux"),
471518 payload: { state: "completed" },
472519 });
473520
474521 await harness.drain();
475522 const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
476− const midThread = midReadModel.threads.find(
477− (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
478− );
523+ const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
479524 expect(midThread?.checkpoints).toHaveLength(0);
480525
481526 harness.provider.emit({
482527 type: "turn.completed",
483− eventId: EventId.makeUnsafe("evt-turn-completed-main"),
528+ eventId: EventId.make("evt-turn-completed-main"),
484529 provider: "codex",
485530
486531 createdAt: new Date().toISOString(),
487− threadId: ThreadId.makeUnsafe("thread-1"),
532+ threadId: ThreadId.make("thread-1"),
488533 turnId: asTurnId("turn-main"),
489534 payload: { state: "completed" },
490535 });
@@ -506,10 +551,10 @@ describe("CheckpointReactor", () => { · 15 unmodified lines
506551 await Effect.runPromise(
507552 harness.engine.dispatch({
508553 type: "thread.session.set",
509− commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
510− threadId: ThreadId.makeUnsafe("thread-1"),
554+ commandId: CommandId.make("cmd-session-set-capture-claude"),
555+ threadId: ThreadId.make("thread-1"),
511556 session: {
512− threadId: ThreadId.makeUnsafe("thread-1"),
557+ threadId: ThreadId.make("thread-1"),
513558 status: "ready",
514559 providerName: "claudeAgent",
515560 runtimeMode: "approval-required",
@@ -523,24 +568,24 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
523568
524569 harness.provider.emit({
525570 type: "turn.started",
526− eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
571+ eventId: EventId.make("evt-turn-started-claude-1"),
527572 provider: "claudeAgent",
528573 createdAt: new Date().toISOString(),
529− threadId: ThreadId.makeUnsafe("thread-1"),
574+ threadId: ThreadId.make("thread-1"),
530575 turnId: asTurnId("turn-claude-1"),
531576 });
532577 await waitForGitRefExists(
533578 harness.cwd,
534− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
579+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
535580 );
536581
537582 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
538583 harness.provider.emit({
539584 type: "turn.completed",
540− eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
585+ eventId: EventId.make("evt-turn-completed-claude-1"),
541586 provider: "claudeAgent",
542587 createdAt: new Date().toISOString(),
543− threadId: ThreadId.makeUnsafe("thread-1"),
588+ threadId: ThreadId.make("thread-1"),
544589 turnId: asTurnId("turn-claude-1"),
545590 payload: { state: "completed" },
546591 });
@@ -553,7 +598,7 @@ describe("CheckpointReactor", () => { · 6 unmodified lines
553598
554599 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
555600 expect(
556− gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
601+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
557602 ).toBe(true);
558603 });
559604
@@ -564,10 +609,10 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
564609 await Effect.runPromise(
565610 harness.engine.dispatch({
566611 type: "thread.session.set",
567− commandId: CommandId.makeUnsafe("cmd-session-set-missing-baseline-diff"),
568− threadId: ThreadId.makeUnsafe("thread-1"),
612+ commandId: CommandId.make("cmd-session-set-missing-baseline-diff"),
613+ threadId: ThreadId.make("thread-1"),
569614 session: {
570− threadId: ThreadId.makeUnsafe("thread-1"),
615+ threadId: ThreadId.make("thread-1"),
571616 status: "ready",
572617 providerName: "codex",
573618 runtimeMode: "approval-required",
@@ -581,11 +626,11 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
581626
582627 harness.provider.emit({
583628 type: "turn.completed",
584− eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
629+ eventId: EventId.make("evt-turn-completed-missing-baseline"),
585630 provider: "codex",
586631
587632 createdAt: new Date().toISOString(),
588− threadId: ThreadId.makeUnsafe("thread-1"),
633+ threadId: ThreadId.make("thread-1"),
589634 turnId: asTurnId("turn-missing-baseline"),
590635 payload: { state: "completed" },
591636 });
@@ -614,10 +659,10 @@ describe("CheckpointReactor", () => { · 22 unmodified lines
614659 await Effect.runPromise(
615660 harness.engine.dispatch({
616661 type: "thread.turn.start",
617− commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"),
618− threadId: ThreadId.makeUnsafe("thread-1"),
662+ commandId: CommandId.make("cmd-turn-start-for-baseline"),
663+ threadId: ThreadId.make("thread-1"),
619664 message: {
620− messageId: MessageId.makeUnsafe("message-user-1"),
665+ messageId: MessageId.make("message-user-1"),
621666 role: "user",
622667 text: "start turn",
623668 attachments: [],
@@ -630,12 +675,12 @@ describe("CheckpointReactor", () => { · 6 unmodified lines
630675
631676 await waitForGitRefExists(
632677 harness.cwd,
633− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
678+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
634679 );
635680 expect(
636681 gitShowFileAtRef(
637682 harness.cwd,
638− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
683+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
639684 "README.md",
640685 ),
641686 ).toBe("v1\n");
@@ -652,10 +697,10 @@ describe("CheckpointReactor", () => { · 10 unmodified lines
652697 await Effect.runPromise(
653698 harness.engine.dispatch({
654699 type: "thread.session.set",
655− commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"),
656− threadId: ThreadId.makeUnsafe("thread-1"),
700+ commandId: CommandId.make("cmd-session-set-missing-provider-cwd"),
701+ threadId: ThreadId.make("thread-1"),
657702 session: {
658− threadId: ThreadId.makeUnsafe("thread-1"),
703+ threadId: ThreadId.make("thread-1"),
659704 status: "running",
660705 providerName: "codex",
661706 runtimeMode: "approval-required",
@@ -670,23 +715,23 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
670715 fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
671716 harness.provider.emit({
672717 type: "turn.completed",
673− eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
718+ eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
674719 provider: "codex",
675720
676721 createdAt: new Date().toISOString(),
677− threadId: ThreadId.makeUnsafe("thread-1"),
722+ threadId: ThreadId.make("thread-1"),
678723 turnId: asTurnId("turn-missing-cwd"),
679724 payload: { state: "completed" },
680725 });
681726
682727 await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
683728 expect(
684− gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
729+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
685730 ).toBe(true);
686731 expect(
687732 gitShowFileAtRef(
688733 harness.cwd,
689− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
734+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
690735 "README.md",
691736 ),
692737 ).toBe("v2\n");
@@ -699,10 +744,10 @@ describe("CheckpointReactor", () => { · 6 unmodified lines
699744 await Effect.runPromise(
700745 harness.engine.dispatch({
701746 type: "thread.session.set",
702− commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"),
703− threadId: ThreadId.makeUnsafe("thread-1"),
747+ commandId: CommandId.make("cmd-session-set-checkpoint-captured"),
748+ threadId: ThreadId.make("thread-1"),
704749 session: {
705− threadId: ThreadId.makeUnsafe("thread-1"),
750+ threadId: ThreadId.make("thread-1"),
706751 status: "ready",
707752 providerName: "codex",
708753 runtimeMode: "approval-required",
@@ -716,11 +761,11 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
716761
717762 harness.provider.emit({
718763 type: "checkpoint.captured",
719− eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
764+ eventId: EventId.make("evt-checkpoint-captured-3"),
720765 provider: "codex",
721766
722767 createdAt: new Date().toISOString(),
723− threadId: ThreadId.makeUnsafe("thread-1"),
768+ threadId: ThreadId.make("thread-1"),
724769 turnId: asTurnId("turn-3"),
725770 turnCount: 3,
726771 status: "completed",
@@ -728,7 +773,7 @@ describe("CheckpointReactor", () => { · 1 unmodified line
728773
729774 await harness.drain();
730775 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"));
732777 expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
733778 false,
734779 );
@@ -749,10 +794,10 @@ describe("CheckpointReactor", () => { · 14 unmodified lines
749794 await Effect.runPromise(
750795 harness.engine.dispatch({
751796 type: "thread.session.set",
752− commandId: CommandId.makeUnsafe("cmd-session-set-non-repo-runtime"),
753− threadId: ThreadId.makeUnsafe("thread-1"),
797+ commandId: CommandId.make("cmd-session-set-non-repo-runtime"),
798+ threadId: ThreadId.make("thread-1"),
754799 session: {
755− threadId: ThreadId.makeUnsafe("thread-1"),
800+ threadId: ThreadId.make("thread-1"),
756801 status: "ready",
757802 providerName: "codex",
758803 runtimeMode: "approval-required",
@@ -766,31 +811,31 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
766811
767812 harness.provider.emit({
768813 type: "turn.completed",
769− eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
814+ eventId: EventId.make("evt-runtime-capture-failure"),
770815 provider: "codex",
771816
772817 createdAt: new Date().toISOString(),
773− threadId: ThreadId.makeUnsafe("thread-1"),
818+ threadId: ThreadId.make("thread-1"),
774819 turnId: asTurnId("turn-runtime-failure"),
775820 payload: { state: "completed" },
776821 });
777822
778823 harness.provider.emit({
779824 type: "turn.started",
780− eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
825+ eventId: EventId.make("evt-turn-started-after-runtime-failure"),
781826 provider: "codex",
782827
783828 createdAt: new Date().toISOString(),
784− threadId: ThreadId.makeUnsafe("thread-1"),
829+ threadId: ThreadId.make("thread-1"),
785830 turnId: asTurnId("turn-after-runtime-failure"),
786831 });
787832
788833 await waitForGitRefExists(
789834 harness.cwd,
790− checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
835+ checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
791836 );
792837 expect(
793− gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
838+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
794839 ).toBe(true);
795840 });
796841
@@ -801,10 +846,10 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
801846 await Effect.runPromise(
802847 harness.engine.dispatch({
803848 type: "thread.session.set",
804− commandId: CommandId.makeUnsafe("cmd-session-set"),
805− threadId: ThreadId.makeUnsafe("thread-1"),
849+ commandId: CommandId.make("cmd-session-set"),
850+ threadId: ThreadId.make("thread-1"),
806851 session: {
807− threadId: ThreadId.makeUnsafe("thread-1"),
852+ threadId: ThreadId.make("thread-1"),
808853 status: "ready",
809854 providerName: "codex",
810855 runtimeMode: "approval-required",
@@ -819,11 +864,11 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
819864 await Effect.runPromise(
820865 harness.engine.dispatch({
821866 type: "thread.turn.diff.complete",
822− commandId: CommandId.makeUnsafe("cmd-diff-1"),
823− threadId: ThreadId.makeUnsafe("thread-1"),
867+ commandId: CommandId.make("cmd-diff-1"),
868+ threadId: ThreadId.make("thread-1"),
824869 turnId: asTurnId("turn-1"),
825870 completedAt: createdAt,
826− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
871+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
827872 status: "ready",
828873 files: [],
829874 checkpointTurnCount: 1,
@@ -833,11 +878,11 @@ describe("CheckpointReactor", () => { · 3 unmodified lines
833878 await Effect.runPromise(
834879 harness.engine.dispatch({
835880 type: "thread.turn.diff.complete",
836− commandId: CommandId.makeUnsafe("cmd-diff-2"),
837− threadId: ThreadId.makeUnsafe("thread-1"),
881+ commandId: CommandId.make("cmd-diff-2"),
882+ threadId: ThreadId.make("thread-1"),
838883 turnId: asTurnId("turn-2"),
839884 completedAt: createdAt,
840− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
885+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
841886 status: "ready",
842887 files: [],
843888 checkpointTurnCount: 2,
@@ -848,8 +893,8 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
848893 await Effect.runPromise(
849894 harness.engine.dispatch({
850895 type: "thread.checkpoint.revert",
851− commandId: CommandId.makeUnsafe("cmd-revert-request"),
852− threadId: ThreadId.makeUnsafe("thread-1"),
896+ commandId: CommandId.make("cmd-revert-request"),
897+ threadId: ThreadId.make("thread-1"),
853898 turnCount: 1,
854899 createdAt,
855900 }),
@@ -863,12 +908,12 @@ describe("CheckpointReactor", () => { · 7 unmodified lines
863908 expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
864909 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
865910 expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
866− threadId: ThreadId.makeUnsafe("thread-1"),
911+ threadId: ThreadId.make("thread-1"),
867912 numTurns: 1,
868913 });
869914 expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
870915 expect(
871− gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2)),
916+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2)),
872917 ).toBe(false);
873918 });
874919
@@ -879,10 +924,10 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
879924 await Effect.runPromise(
880925 harness.engine.dispatch({
881926 type: "thread.session.set",
882− commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
883− threadId: ThreadId.makeUnsafe("thread-1"),
927+ commandId: CommandId.make("cmd-session-set-claude"),
928+ threadId: ThreadId.make("thread-1"),
884929 session: {
885− threadId: ThreadId.makeUnsafe("thread-1"),
930+ threadId: ThreadId.make("thread-1"),
886931 status: "ready",
887932 providerName: "claudeAgent",
888933 runtimeMode: "approval-required",
@@ -897,11 +942,11 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
897942 await Effect.runPromise(
898943 harness.engine.dispatch({
899944 type: "thread.turn.diff.complete",
900− commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
901− threadId: ThreadId.makeUnsafe("thread-1"),
945+ commandId: CommandId.make("cmd-diff-claude-1"),
946+ threadId: ThreadId.make("thread-1"),
902947 turnId: asTurnId("turn-claude-1"),
903948 completedAt: createdAt,
904− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
949+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
905950 status: "ready",
906951 files: [],
907952 checkpointTurnCount: 1,
@@ -911,11 +956,11 @@ describe("CheckpointReactor", () => { · 3 unmodified lines
911956 await Effect.runPromise(
912957 harness.engine.dispatch({
913958 type: "thread.turn.diff.complete",
914− commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
915− threadId: ThreadId.makeUnsafe("thread-1"),
959+ commandId: CommandId.make("cmd-diff-claude-2"),
960+ threadId: ThreadId.make("thread-1"),
916961 turnId: asTurnId("turn-claude-2"),
917962 completedAt: createdAt,
918− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
963+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
919964 status: "ready",
920965 files: [],
921966 checkpointTurnCount: 2,
@@ -926,8 +971,8 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
926971 await Effect.runPromise(
927972 harness.engine.dispatch({
928973 type: "thread.checkpoint.revert",
929− commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
930− threadId: ThreadId.makeUnsafe("thread-1"),
974+ commandId: CommandId.make("cmd-revert-request-claude"),
975+ threadId: ThreadId.make("thread-1"),
931976 turnCount: 1,
932977 createdAt,
933978 }),
@@ -936,7 +981,7 @@ describe("CheckpointReactor", () => { · 2 unmodified lines
936981 await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
937982 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
938983 expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
939− threadId: ThreadId.makeUnsafe("thread-1"),
984+ threadId: ThreadId.make("thread-1"),
940985 numTurns: 1,
941986 });
942987 });
@@ -948,10 +993,10 @@ describe("CheckpointReactor", () => { · 5 unmodified lines
948993 await Effect.runPromise(
949994 harness.engine.dispatch({
950995 type: "thread.session.set",
951− commandId: CommandId.makeUnsafe("cmd-session-set-inline-revert"),
952− threadId: ThreadId.makeUnsafe("thread-1"),
996+ commandId: CommandId.make("cmd-session-set-inline-revert"),
997+ threadId: ThreadId.make("thread-1"),
953998 session: {
954− threadId: ThreadId.makeUnsafe("thread-1"),
999+ threadId: ThreadId.make("thread-1"),
9551000 status: "ready",
9561001 providerName: "codex",
9571002 runtimeMode: "approval-required",
@@ -966,11 +1011,11 @@ describe("CheckpointReactor", () => { · 8 unmodified lines
9661011 await Effect.runPromise(
9671012 harness.engine.dispatch({
9681013 type: "thread.turn.diff.complete",
969− commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-1"),
970− threadId: ThreadId.makeUnsafe("thread-1"),
1014+ commandId: CommandId.make("cmd-inline-revert-diff-1"),
1015+ threadId: ThreadId.make("thread-1"),
9711016 turnId: asTurnId("turn-1"),
9721017 completedAt: createdAt,
973− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
1018+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
9741019 status: "ready",
9751020 files: [],
9761021 checkpointTurnCount: 1,
@@ -980,11 +1025,11 @@ describe("CheckpointReactor", () => { · 3 unmodified lines
9801025 await Effect.runPromise(
9811026 harness.engine.dispatch({
9821027 type: "thread.turn.diff.complete",
983− commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-2"),
984− threadId: ThreadId.makeUnsafe("thread-1"),
1028+ commandId: CommandId.make("cmd-inline-revert-diff-2"),
1029+ threadId: ThreadId.make("thread-1"),
9851030 turnId: asTurnId("turn-2"),
9861031 completedAt: createdAt,
987− checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
1032+ checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
9881033 status: "ready",
9891034 files: [],
9901035 checkpointTurnCount: 2,
@@ -995,8 +1040,8 @@ describe("CheckpointReactor", () => { · 4 unmodified lines
9951040 await Effect.runPromise(
9961041 harness.engine.dispatch({
9971042 type: "thread.checkpoint.revert",
998− commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-1"),
999− threadId: ThreadId.makeUnsafe("thread-1"),
1043+ commandId: CommandId.make("cmd-sequenced-revert-request-1"),
1044+ threadId: ThreadId.make("thread-1"),
10001045 turnCount: 1,
10011046 createdAt,
10021047 }),
@@ -1004,8 +1049,8 @@ describe("CheckpointReactor", () => { · 1 unmodified line
10041049 await Effect.runPromise(
10051050 harness.engine.dispatch({
10061051 type: "thread.checkpoint.revert",
1007− commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-0"),
1008− threadId: ThreadId.makeUnsafe("thread-1"),
1052+ commandId: CommandId.make("cmd-sequenced-revert-request-0"),
1053+ threadId: ThreadId.make("thread-1"),
10091054 turnCount: 0,
10101055 createdAt,
10111056 }),
@@ -1015,11 +1060,11 @@ describe("CheckpointReactor", () => { · 3 unmodified lines
10151060
10161061 expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
10171062 expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
1018− threadId: ThreadId.makeUnsafe("thread-1"),
1063+ threadId: ThreadId.make("thread-1"),
10191064 numTurns: 1,
10201065 });
10211066 expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
1022− threadId: ThreadId.makeUnsafe("thread-1"),
1067+ threadId: ThreadId.make("thread-1"),
10231068 numTurns: 1,
10241069 });
10251070 });
@@ -1031,8 +1076,8 @@ describe("CheckpointReactor", () => { · 5 unmodified lines
10311076 await Effect.runPromise(
10321077 harness.engine.dispatch({
10331078 type: "thread.checkpoint.revert",
1034− commandId: CommandId.makeUnsafe("cmd-revert-no-session"),
1035− threadId: ThreadId.makeUnsafe("thread-1"),
1079+ commandId: CommandId.make("cmd-revert-no-session"),
1080+ threadId: ThreadId.make("thread-1"),
10361081 turnCount: 1,
10371082 createdAt,
10381083 }),
apps/server/src/orchestration/Layers/CheckpointReactor.ts+142−115
@@ -24,6 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts"; · 23 unmodified lines
2424 import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
2525 import { OrchestrationDispatchError } from "../Errors.ts";
2626 import { isGitRepository } from "../../git/Utils.ts";
27+import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
2728 import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
2829
2930 type ReactorInput =
@@ -37,7 +38,7 @@ type ReactorInput = · 7 unmodified lines
3738 };
3839
3940 function toTurnId(value: string | undefined): TurnId | null {
40− return value === undefined ? null : TurnId.makeUnsafe(String(value));
41+ return value === undefined ? null : TurnId.make(String(value));
4142 }
4243
4344 function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
@@ -61,7 +62,7 @@ function checkpointStatusFromRuntime(status: string | undefined): "ready" | "mis · 17 unmodified lines
6162 }
6263
6364 const serverCommandId = (tag: string): CommandId =>
64− CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
65+ CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
6566
6667 const make = Effect.gen(function* () {
6768 const orchestrationEngine = yield* OrchestrationEngineService;
@@ -69,6 +70,7 @@ const make = Effect.gen(function* () { · 1 unmodified line
6970 const checkpointStore = yield* CheckpointStore;
7071 const receiptBus = yield* RuntimeReceiptBus;
7172 const workspaceEntries = yield* WorkspaceEntries;
73+ const gitStatusBroadcaster = yield* GitStatusBroadcaster;
7274
7375 const appendRevertFailureActivity = (input: {
7476 readonly threadId: ThreadId;
@@ -81,7 +83,7 @@ const make = Effect.gen(function* () { · 6 unmodified lines
8183 commandId: serverCommandId("checkpoint-revert-failure"),
8284 threadId: input.threadId,
8385 activity: {
84− id: EventId.makeUnsafe(crypto.randomUUID()),
86+ id: EventId.make(crypto.randomUUID()),
8587 tone: "error",
8688 kind: "checkpoint.revert.failed",
8789 summary: "Checkpoint revert failed",
@@ -106,7 +108,7 @@ const make = Effect.gen(function* () { · 18 unmodified lines
106108 commandId: serverCommandId("checkpoint-capture-failure"),
107109 threadId: input.threadId,
108110 activity: {
109− id: EventId.makeUnsafe(crypto.randomUUID()),
111+ id: EventId.make(crypto.randomUUID()),
110112 tone: "error",
111113 kind: "checkpoint.capture.failed",
112114 summary: "Checkpoint capture failed",
@@ -119,7 +121,7 @@ const make = Effect.gen(function* () { · 6 unmodified lines
119121 createdAt: input.createdAt,
120122 });
121123
122− const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
124+ const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
123125 threadId: ThreadId,
124126 ): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
125127 const readModel = yield* orchestrationEngine.getReadModel();
@@ -153,7 +155,7 @@ const make = Effect.gen(function* () { · 27 unmodified lines
153155 // active provider session CWD and falling back to the thread/project config.
154156 // Returns undefined when no CWD can be determined or the workspace is not
155157 // a git repository.
156− const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
158+ const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: {
157159 readonly threadId: ThreadId;
158160 readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
159161 readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
@@ -188,7 +190,7 @@ const make = Effect.gen(function* () { · 28 unmodified lines
188190 // Shared tail for both capture paths: creates the git checkpoint ref, diffs
189191 // it against the previous turn, then dispatches the domain events to update
190192 // the orchestration read model.
191− const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {
193+ const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: {
192194 readonly threadId: ThreadId;
193195 readonly turnId: TurnId;
194196 readonly thread: {
@@ -268,7 +270,7 @@ const make = Effect.gen(function* () { · 73 unmodified lines
268270 input.thread.messages
269271 .toReversed()
270272 .find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
271− MessageId.makeUnsafe(`assistant:${input.turnId}`);
273+ MessageId.make(`assistant:${input.turnId}`);
272274
273275 yield* orchestrationEngine.dispatch({
274276 type: "thread.turn.diff.complete",
@@ -305,7 +307,7 @@ const make = Effect.gen(function* () { · 30 unmodified lines
305307 commandId: serverCommandId("checkpoint-captured-activity"),
306308 threadId: input.threadId,
307309 activity: {
308− id: EventId.makeUnsafe(crypto.randomUUID()),
310+ id: EventId.make(crypto.randomUUID()),
309311 tone: "info",
310312 kind: "checkpoint.captured",
311313 summary: "Checkpoint captured",
@@ -321,70 +323,70 @@ const make = Effect.gen(function* () { · 9 unmodified lines
321323 });
322324
323325 // Captures a real git checkpoint when a turn completes via a runtime event.
324− const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
325− event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
326− ) {
327− const turnId = toTurnId(event.turnId);
328− if (!turnId) {
329− return;
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− }
326+ const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
327+ function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
328+ const turnId = toTurnId(event.turnId);
329+ if (!turnId) {
330+ return;
331+ }
337332
338− // When a primary turn is active, only that turn may produce completion checkpoints.
339− if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
340− return;
341− }
333+ const readModel = yield* orchestrationEngine.getReadModel();
334+ const thread = readModel.threads.find((entry) => entry.id === event.threadId);
335+ if (!thread) {
336+ return;
337+ }
342338
343− // Only skip if a real (non-placeholder) checkpoint already exists for this turn.
344− // ProviderRuntimeIngestion may insert placeholder entries with status "missing"
345− // before this reactor runs; those must not prevent real git capture.
346− if (
347− thread.checkpoints.some(
348− (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
349− )
350− ) {
351− return;
352− }
339+ // When a primary turn is active, only that turn may produce completion checkpoints.
340+ if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
341+ return;
342+ }
353343
354− const checkpointCwd = yield* resolveCheckpointCwd({
355− threadId: thread.id,
356− thread,
357− projects: readModel.projects,
358− preferSessionRuntime: true,
359− });
360− if (!checkpointCwd) {
361− return;
362− }
344+ // Only skip if a real (non-placeholder) checkpoint already exists for this turn.
345+ // ProviderRuntimeIngestion may insert placeholder entries with status "missing"
346+ // before this reactor runs; those must not prevent real git capture.
347+ if (
348+ thread.checkpoints.some(
349+ (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
350+ )
351+ ) {
352+ return;
353+ }
363354
364− // If a placeholder checkpoint exists for this turn, reuse its turn count
365− // instead of incrementing past it.
366− const existingPlaceholder = thread.checkpoints.find(
367− (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
368− );
369− const currentTurnCount = thread.checkpoints.reduce(
370− (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
371− 0,
372− );
373− const nextTurnCount = existingPlaceholder
374− ? existingPlaceholder.checkpointTurnCount
375− : currentTurnCount + 1;
355+ const checkpointCwd = yield* resolveCheckpointCwd({
356+ threadId: thread.id,
357+ thread,
358+ projects: readModel.projects,
359+ preferSessionRuntime: true,
360+ });
361+ if (!checkpointCwd) {
362+ return;
363+ }
376364
377− yield* captureAndDispatchCheckpoint({
378− threadId: thread.id,
379− turnId,
380− thread,
381− cwd: checkpointCwd,
382− turnCount: nextTurnCount,
383− status: checkpointStatusFromRuntime(event.payload.state),
384− assistantMessageId: undefined,
385− createdAt: event.createdAt,
386− });
387− });
365+ // If a placeholder checkpoint exists for this turn, reuse its turn count
366+ // instead of incrementing past it.
367+ const existingPlaceholder = thread.checkpoints.find(
368+ (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
369+ );
370+ const currentTurnCount = thread.checkpoints.reduce(
371+ (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
372+ 0,
373+ );
374+ const nextTurnCount = existingPlaceholder
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+ );
388390
389391 // Captures a real git checkpoint when a placeholder checkpoint (status "missing")
390392 // 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
394396 // events from the Codex runtime. This handler fires when the corresponding
395397 // domain event arrives, allowing the reactor to capture the actual filesystem
396398 // state into a git ref and dispatch a replacement checkpoint.
397− const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (
399+ const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* (
398400 event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
399401 ) {
400402 const { threadId, turnId, checkpointTurnCount, status } = event.payload;
@@ -448,57 +450,79 @@ const make = Effect.gen(function* () { · 47 unmodified lines
448450 });
449451 });
450452
451− const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (
452− event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,
453− ) {
454− const turnId = toTurnId(event.turnId);
455− if (!turnId) {
456− return;
457− }
453+ const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
454+ function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
455+ const turnId = toTurnId(event.turnId);
456+ if (!turnId) {
457+ return;
458+ }
458459
459− const readModel = yield* orchestrationEngine.getReadModel();
460− const thread = readModel.threads.find((entry) => entry.id === event.threadId);
461− if (!thread) {
462− return;
463− }
460+ const readModel = yield* orchestrationEngine.getReadModel();
461+ const thread = readModel.threads.find((entry) => entry.id === event.threadId);
462+ if (!thread) {
463+ return;
464+ }
464465
465− const checkpointCwd = yield* resolveCheckpointCwd({
466− threadId: thread.id,
467− thread,
468− projects: readModel.projects,
469− preferSessionRuntime: false,
470− });
471− if (!checkpointCwd) {
472− return;
473− }
466+ const checkpointCwd = yield* resolveCheckpointCwd({
467+ threadId: thread.id,
468+ thread,
469+ projects: readModel.projects,
470+ preferSessionRuntime: false,
471+ });
472+ if (!checkpointCwd) {
473+ return;
474+ }
474475
475− const currentTurnCount = thread.checkpoints.reduce(
476− (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
477− 0,
478− );
479− const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
480− const baselineExists = yield* checkpointStore.hasCheckpointRef({
481− cwd: checkpointCwd,
482− checkpointRef: baselineCheckpointRef,
483− });
484− if (baselineExists) {
476+ const currentTurnCount = thread.checkpoints.reduce(
477+ (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
478+ 0,
479+ );
480+ const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
481+ const baselineExists = yield* checkpointStore.hasCheckpointRef({
482+ cwd: checkpointCwd,
483+ checkpointRef: baselineCheckpointRef,
484+ });
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)) {
485508 return;
486509 }
487510
488− yield* checkpointStore.captureCheckpoint({
489− cwd: checkpointCwd,
490− checkpointRef: baselineCheckpointRef,
491− });
492− yield* receiptBus.publish({
493− type: "checkpoint.baseline.captured",
494− threadId: thread.id,
495− checkpointTurnCount: currentTurnCount,
496− checkpointRef: baselineCheckpointRef,
497− createdAt: event.createdAt,
498− });
511+ yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
512+ Effect.catch((error) =>
513+ Effect.logWarning("failed to refresh local git status after turn completion", {
514+ threadId: event.threadId,
515+ turnId: event.turnId ?? null,
516+ cwd: sessionRuntime.value.cwd,
517+ detail: error.message,
518+ }),
519+ ),
520+ );
499521 });
500522
501− const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
523+ const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
524+ "ensurePreTurnBaselineFromDomainTurnStart",
525+ )(function* (
502526 event: Extract<
503527 OrchestrationEvent,
504528 { type: "thread.turn-start-requested" | "thread.message-sent" }
@@ -557,7 +581,7 @@ const make = Effect.gen(function* () { · 52 unmodified lines
557581 });
558582 });
559583
560− const handleRevertRequested = Effect.fnUntraced(function* (
584+ const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
561585 event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
562586 ) {
563587 const now = new Date().toISOString();
@@ -685,7 +709,7 @@ const make = Effect.gen(function* () { · 121 unmodified lines
685709 );
686710 });
687711
688− const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
712+ const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
689713 if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
690714 yield* ensurePreTurnBaselineFromDomainTurnStart(event);
691715 return;
@@ -724,7 +748,9 @@ const make = Effect.gen(function* () { · 32 unmodified lines
724748 }
725749 });
726750
727− const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {
751+ const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
752+ event: ProviderRuntimeEvent,
753+ ) {
728754 if (event.type === "turn.started") {
729755 yield* ensurePreTurnBaselineFromTurnStart(event);
730756 return;
@@ -732,6 +758,7 @@ const make = Effect.gen(function* () { · 1 unmodified line
732758
733759 if (event.type === "turn.completed") {
734760 const turnId = toTurnId(event.turnId);
761+ yield* refreshLocalGitStatusFromTurnCompletion(event);
735762 yield* captureCheckpointFromTurnCompletion(event).pipe(
736763 Effect.catch((error) =>
737764 appendCaptureFailureActivity({
apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+163−58
@@ -8,7 +8,7 @@ import { · 7 unmodified lines
88 TurnId,
99 type OrchestrationEvent,
1010 } from "@t3tools/contracts";
11−import { Effect, Layer, ManagedRuntime, Option, Queue, Stream } from "effect";
11+import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
1212 import { describe, expect, it } from "vitest";
1313
1414 import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -19,6 +19,7 @@ import { · 4 unmodified lines
1919 OrchestrationEventStore,
2020 type OrchestrationEventStoreShape,
2121 } from "../../persistence/Services/OrchestrationEventStore.ts";
22+import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
2223 import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
2324 import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
2425 import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
@@ -31,10 +32,10 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts" · 6 unmodified lines
3132 import { ServerConfig } from "../../config.ts";
3233 import * as NodeServices from "@effect/platform-node/NodeServices";
3334
34−const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
35−const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
36−const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
37−const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
35+const asProjectId = (value: string): ProjectId => ProjectId.make(value);
36+const asMessageId = (value: string): MessageId => MessageId.make(value);
37+const asTurnId = (value: string): TurnId => TurnId.make(value);
38+const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
3839
3940 async function createOrchestrationSystem() {
4041 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
@@ -45,6 +46,7 @@ async function createOrchestrationSystem() { · 4 unmodified lines
4546 Layer.provide(OrchestrationProjectionPipelineLive),
4647 Layer.provide(OrchestrationEventStoreLive),
4748 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
49+ Layer.provide(RepositoryIdentityResolverLive),
4850 Layer.provide(SqlitePersistenceMemory),
4951 Layer.provideMerge(ServerConfigLayer),
5052 Layer.provideMerge(NodeServices.layer),
@@ -62,6 +64,17 @@ function now() { · 11 unmodified lines
6264 return new Date().toISOString();
6365 }
6466
67+const 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+
6578 describe("OrchestrationEngine", () => {
6679 it("bootstraps the in-memory read model from persisted projections", async () => {
6780 const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
@@ -102,7 +115,7 @@ describe("OrchestrationEngine", () => { · 34 unmodified lines
102115 ],
103116 threads: [
104117 {
105− id: ThreadId.makeUnsafe("thread-bootstrap"),
118+ id: ThreadId.make("thread-bootstrap"),
106119 projectId: asProjectId("project-bootstrap"),
107120 title: "Bootstrap Thread",
108121 modelSelection: {
@@ -170,7 +183,7 @@ describe("OrchestrationEngine", () => { · 61 unmodified lines
170183 await system.run(
171184 engine.dispatch({
172185 type: "project.create",
173− commandId: CommandId.makeUnsafe("cmd-project-1-create"),
186+ commandId: CommandId.make("cmd-project-1-create"),
174187 projectId: asProjectId("project-1"),
175188 title: "Project 1",
176189 workspaceRoot: "/tmp/project-1",
@@ -184,8 +197,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
184197 await system.run(
185198 engine.dispatch({
186199 type: "thread.create",
187− commandId: CommandId.makeUnsafe("cmd-thread-1-create"),
188− threadId: ThreadId.makeUnsafe("thread-1"),
200+ commandId: CommandId.make("cmd-thread-1-create"),
201+ threadId: ThreadId.make("thread-1"),
189202 projectId: asProjectId("project-1"),
190203 title: "Thread",
191204 modelSelection: {
@@ -202,8 +215,8 @@ describe("OrchestrationEngine", () => { · 10 unmodified lines
202215 await system.run(
203216 engine.dispatch({
204217 type: "thread.turn.start",
205− commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
206− threadId: ThreadId.makeUnsafe("thread-1"),
218+ commandId: CommandId.make("cmd-turn-start-1"),
219+ threadId: ThreadId.make("thread-1"),
207220 message: {
208221 messageId: asMessageId("msg-1"),
209222 role: "user",
@@ -230,7 +243,7 @@ describe("OrchestrationEngine", () => { · 20 unmodified lines
230243 await system.run(
231244 engine.dispatch({
232245 type: "project.create",
233− commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
246+ commandId: CommandId.make("cmd-project-archive-create"),
234247 projectId: asProjectId("project-archive"),
235248 title: "Project Archive",
236249 workspaceRoot: "/tmp/project-archive",
@@ -244,8 +257,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
244257 await system.run(
245258 engine.dispatch({
246259 type: "thread.create",
247− commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
248− threadId: ThreadId.makeUnsafe("thread-archive"),
260+ commandId: CommandId.make("cmd-thread-archive-create"),
261+ threadId: ThreadId.make("thread-archive"),
249262 projectId: asProjectId("project-archive"),
250263 title: "Archive me",
251264 modelSelection: {
@@ -263,8 +276,8 @@ describe("OrchestrationEngine", () => { · 11 unmodified lines
263276 await system.run(
264277 engine.dispatch({
265278 type: "thread.archive",
266− commandId: CommandId.makeUnsafe("cmd-thread-archive"),
267− threadId: ThreadId.makeUnsafe("thread-archive"),
279+ commandId: CommandId.make("cmd-thread-archive"),
280+ threadId: ThreadId.make("thread-archive"),
268281 }),
269282 );
270283 expect(
@@ -276,8 +289,8 @@ describe("OrchestrationEngine", () => { · 5 unmodified lines
276289 await system.run(
277290 engine.dispatch({
278291 type: "thread.unarchive",
279− commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
280− threadId: ThreadId.makeUnsafe("thread-archive"),
292+ commandId: CommandId.make("cmd-thread-unarchive"),
293+ threadId: ThreadId.make("thread-archive"),
281294 }),
282295 );
283296 expect(
@@ -297,7 +310,7 @@ describe("OrchestrationEngine", () => { · 13 unmodified lines
297310 await system.run(
298311 engine.dispatch({
299312 type: "project.create",
300− commandId: CommandId.makeUnsafe("cmd-project-replay-create"),
313+ commandId: CommandId.make("cmd-project-replay-create"),
301314 projectId: asProjectId("project-replay"),
302315 title: "Replay Project",
303316 workspaceRoot: "/tmp/project-replay",
@@ -311,8 +324,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
311324 await system.run(
312325 engine.dispatch({
313326 type: "thread.create",
314− commandId: CommandId.makeUnsafe("cmd-thread-replay-create"),
315− threadId: ThreadId.makeUnsafe("thread-replay"),
327+ commandId: CommandId.make("cmd-thread-replay-create"),
328+ threadId: ThreadId.make("thread-replay"),
316329 projectId: asProjectId("project-replay"),
317330 title: "replay",
318331 modelSelection: {
@@ -329,8 +342,8 @@ describe("OrchestrationEngine", () => { · 10 unmodified lines
329342 await system.run(
330343 engine.dispatch({
331344 type: "thread.delete",
332− commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"),
333− threadId: ThreadId.makeUnsafe("thread-replay"),
345+ commandId: CommandId.make("cmd-thread-replay-delete"),
346+ threadId: ThreadId.make("thread-replay"),
334347 }),
335348 );
336349
@@ -355,7 +368,7 @@ describe("OrchestrationEngine", () => { · 18 unmodified lines
355368 await system.run(
356369 engine.dispatch({
357370 type: "project.create",
358− commandId: CommandId.makeUnsafe("cmd-project-stream-create"),
371+ commandId: CommandId.make("cmd-project-stream-create"),
359372 projectId: asProjectId("project-stream"),
360373 title: "Stream Project",
361374 workspaceRoot: "/tmp/project-stream",
@@ -379,8 +392,8 @@ describe("OrchestrationEngine", () => { · 17 unmodified lines
379392 yield* Effect.sleep("10 millis");
380393 yield* engine.dispatch({
381394 type: "thread.create",
382− commandId: CommandId.makeUnsafe("cmd-stream-thread-create"),
383− threadId: ThreadId.makeUnsafe("thread-stream"),
395+ commandId: CommandId.make("cmd-stream-thread-create"),
396+ threadId: ThreadId.make("thread-stream"),
384397 projectId: asProjectId("project-stream"),
385398 title: "domain-stream",
386399 modelSelection: {
@@ -395,8 +408,8 @@ describe("OrchestrationEngine", () => { · 8 unmodified lines
395408 });
396409 yield* engine.dispatch({
397410 type: "thread.meta.update",
398− commandId: CommandId.makeUnsafe("cmd-stream-thread-update"),
399− threadId: ThreadId.makeUnsafe("thread-stream"),
411+ commandId: CommandId.make("cmd-stream-thread-update"),
412+ threadId: ThreadId.make("thread-stream"),
400413 title: "domain-stream-updated",
401414 });
402415 eventTypes.push((yield* Queue.take(eventQueue)).type);
@@ -408,6 +421,95 @@ describe("OrchestrationEngine", () => { · 5 unmodified lines
408421 await system.dispose();
409422 });
410423
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+
411513 it("stores completed checkpoint summaries even when no files changed", async () => {
412514 const system = await createOrchestrationSystem();
413515 const { engine } = system;
@@ -416,7 +518,7 @@ describe("OrchestrationEngine", () => { · 2 unmodified lines
416518 await system.run(
417519 engine.dispatch({
418520 type: "project.create",
419− commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"),
521+ commandId: CommandId.make("cmd-project-turn-diff-create"),
420522 projectId: asProjectId("project-turn-diff"),
421523 title: "Turn Diff Project",
422524 workspaceRoot: "/tmp/project-turn-diff",
@@ -430,8 +532,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
430532 await system.run(
431533 engine.dispatch({
432534 type: "thread.create",
433− commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"),
434− threadId: ThreadId.makeUnsafe("thread-turn-diff"),
535+ commandId: CommandId.make("cmd-thread-turn-diff-create"),
536+ threadId: ThreadId.make("thread-turn-diff"),
435537 projectId: asProjectId("project-turn-diff"),
436538 title: "Turn diff thread",
437539 modelSelection: {
@@ -448,8 +550,8 @@ describe("OrchestrationEngine", () => { · 10 unmodified lines
448550 await system.run(
449551 engine.dispatch({
450552 type: "thread.turn.diff.complete",
451− commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"),
452− threadId: ThreadId.makeUnsafe("thread-turn-diff"),
553+ commandId: CommandId.make("cmd-turn-diff-complete"),
554+ threadId: ThreadId.make("thread-turn-diff"),
453555 turnId: asTurnId("turn-1"),
454556 completedAt: createdAt,
455557 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
@@ -488,7 +590,7 @@ describe("OrchestrationEngine", () => { · 32 unmodified lines
488590
489591 const flakyStore: OrchestrationEventStoreShape = {
490592 append(event) {
491− if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) {
593+ if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) {
492594 shouldFailFirstAppend = false;
493595 return Effect.fail(
494596 new PersistenceSqlError({
@@ -523,6 +625,7 @@ describe("OrchestrationEngine", () => { · 28 unmodified lines
523625 Layer.provide(OrchestrationProjectionPipelineLive),
524626 Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
525627 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
628+ Layer.provide(RepositoryIdentityResolverLive),
526629 Layer.provide(SqlitePersistenceMemory),
527630 Layer.provideMerge(ServerConfigLayer),
528631 Layer.provideMerge(NodeServices.layer),
@@ -534,7 +637,7 @@ describe("OrchestrationEngine", () => { · 5 unmodified lines
534637 await runtime.runPromise(
535638 engine.dispatch({
536639 type: "project.create",
537− commandId: CommandId.makeUnsafe("cmd-project-flaky-create"),
640+ commandId: CommandId.make("cmd-project-flaky-create"),
538641 projectId: asProjectId("project-flaky"),
539642 title: "Flaky Project",
540643 workspaceRoot: "/tmp/project-flaky",
@@ -550,8 +653,8 @@ describe("OrchestrationEngine", () => { · 9 unmodified lines
550653 runtime.runPromise(
551654 engine.dispatch({
552655 type: "thread.create",
553− commandId: CommandId.makeUnsafe("cmd-flaky-1"),
554− threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
656+ commandId: CommandId.make("cmd-flaky-1"),
657+ threadId: ThreadId.make("thread-flaky-fail"),
555658 projectId: asProjectId("project-flaky"),
556659 title: "flaky-fail",
557660 modelSelection: {
@@ -570,8 +673,8 @@ describe("OrchestrationEngine", () => { · 12 unmodified lines
570673 const result = await runtime.runPromise(
571674 engine.dispatch({
572675 type: "thread.create",
573− commandId: CommandId.makeUnsafe("cmd-flaky-2"),
574− threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
676+ commandId: CommandId.make("cmd-flaky-2"),
677+ threadId: ThreadId.make("thread-flaky-ok"),
575678 projectId: asProjectId("project-flaky"),
576679 title: "flaky-ok",
577680 modelSelection: {
@@ -598,7 +701,7 @@ describe("OrchestrationEngine", () => { · 20 unmodified lines
598701 projectEvent: (event) => {
599702 if (
600703 shouldFailRequestedProjection &&
601− event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") &&
704+ event.commandId === CommandId.make("cmd-turn-start-atomic") &&
602705 event.type === "thread.turn-start-requested"
603706 ) {
604707 shouldFailRequestedProjection = false;
@@ -619,6 +722,7 @@ describe("OrchestrationEngine", () => { · 14 unmodified lines
619722 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
620723 Layer.provide(OrchestrationEventStoreLive),
621724 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
725+ Layer.provide(RepositoryIdentityResolverLive),
622726 Layer.provide(SqlitePersistenceMemory),
623727 ),
624728 );
@@ -628,7 +732,7 @@ describe("OrchestrationEngine", () => { · 3 unmodified lines
628732 await runtime.runPromise(
629733 engine.dispatch({
630734 type: "project.create",
631− commandId: CommandId.makeUnsafe("cmd-project-atomic-create"),
735+ commandId: CommandId.make("cmd-project-atomic-create"),
632736 projectId: asProjectId("project-atomic"),
633737 title: "Atomic Project",
634738 workspaceRoot: "/tmp/project-atomic",
@@ -642,8 +746,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
642746 await runtime.runPromise(
643747 engine.dispatch({
644748 type: "thread.create",
645− commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"),
646− threadId: ThreadId.makeUnsafe("thread-atomic"),
749+ commandId: CommandId.make("cmd-thread-atomic-create"),
750+ threadId: ThreadId.make("thread-atomic"),
647751 projectId: asProjectId("project-atomic"),
648752 title: "atomic",
649753 modelSelection: {
@@ -660,8 +764,8 @@ describe("OrchestrationEngine", () => { · 10 unmodified lines
660764
661765 const turnStartCommand = {
662766 type: "thread.turn.start" as const,
663− commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"),
664− threadId: ThreadId.makeUnsafe("thread-atomic"),
767+ commandId: CommandId.make("cmd-turn-start-atomic"),
768+ threadId: ThreadId.make("thread-atomic"),
665769 message: {
666770 messageId: asMessageId("msg-atomic-1"),
667771 role: "user" as const,
@@ -741,7 +845,7 @@ describe("OrchestrationEngine", () => { · 73 unmodified lines
741845 projectEvent: (event) => {
742846 if (
743847 shouldFailProjection &&
744− event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail")
848+ event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
745849 ) {
746850 shouldFailProjection = false;
747851 return Effect.fail(
@@ -761,6 +865,7 @@ describe("OrchestrationEngine", () => { · 13 unmodified lines
761865 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
762866 Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
763867 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
868+ Layer.provide(RepositoryIdentityResolverLive),
764869 Layer.provide(SqlitePersistenceMemory),
765870 ),
766871 );
@@ -770,7 +875,7 @@ describe("OrchestrationEngine", () => { · 3 unmodified lines
770875 await runtime.runPromise(
771876 engine.dispatch({
772877 type: "project.create",
773− commandId: CommandId.makeUnsafe("cmd-project-sync-create"),
878+ commandId: CommandId.make("cmd-project-sync-create"),
774879 projectId: asProjectId("project-sync"),
775880 title: "Sync Project",
776881 workspaceRoot: "/tmp/project-sync",
@@ -784,8 +889,8 @@ describe("OrchestrationEngine", () => { · 7 unmodified lines
784889 await runtime.runPromise(
785890 engine.dispatch({
786891 type: "thread.create",
787− commandId: CommandId.makeUnsafe("cmd-thread-sync-create"),
788− threadId: ThreadId.makeUnsafe("thread-sync"),
892+ commandId: CommandId.make("cmd-thread-sync-create"),
893+ threadId: ThreadId.make("thread-sync"),
789894 projectId: asProjectId("project-sync"),
790895 title: "sync-before",
791896 modelSelection: {
@@ -804,8 +909,8 @@ describe("OrchestrationEngine", () => { · 12 unmodified lines
804909 runtime.runPromise(
805910 engine.dispatch({
806911 type: "thread.meta.update",
807− commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"),
808− threadId: ThreadId.makeUnsafe("thread-sync"),
912+ commandId: CommandId.make("cmd-thread-meta-sync-fail"),
913+ threadId: ThreadId.make("thread-sync"),
809914 title: "sync-after-failed-projection",
810915 }),
811916 ),
@@ -829,8 +934,8 @@ describe("OrchestrationEngine", () => { · 17 unmodified lines
829934 system.run(
830935 engine.dispatch({
831936 type: "thread.turn.start",
832− commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"),
833− threadId: ThreadId.makeUnsafe("thread-missing"),
937+ commandId: CommandId.make("cmd-invariant-missing-thread"),
938+ threadId: ThreadId.make("thread-missing"),
834939 message: {
835940 messageId: asMessageId("msg-missing"),
836941 role: "user",
@@ -855,7 +960,7 @@ describe("OrchestrationEngine", () => { · 18 unmodified lines
855960 await system.run(
856961 engine.dispatch({
857962 type: "project.create",
858− commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"),
963+ commandId: CommandId.make("cmd-project-duplicate-create"),
859964 projectId: asProjectId("project-duplicate"),
860965 title: "Duplicate Project",
861966 workspaceRoot: "/tmp/project-duplicate",
@@ -870,8 +975,8 @@ describe("OrchestrationEngine", () => { · 8 unmodified lines
870975 await system.run(
871976 engine.dispatch({
872977 type: "thread.create",
873− commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"),
874− threadId: ThreadId.makeUnsafe("thread-duplicate"),
978+ commandId: CommandId.make("cmd-thread-duplicate-1"),
979+ threadId: ThreadId.make("thread-duplicate"),
875980 projectId: asProjectId("project-duplicate"),
876981 title: "duplicate",
877982 modelSelection: {
@@ -890,8 +995,8 @@ describe("OrchestrationEngine", () => { · 12 unmodified lines
890995 system.run(
891996 engine.dispatch({
892997 type: "thread.create",
893− commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"),
894− threadId: ThreadId.makeUnsafe("thread-duplicate"),
998+ commandId: CommandId.make("cmd-thread-duplicate-2"),
999+ threadId: ThreadId.make("thread-duplicate"),
8951000 projectId: asProjectId("project-duplicate"),
8961001 title: "duplicate",
8971002 modelSelection: {
apps/server/src/orchestration/Layers/OrchestrationEngine.ts+168−95
@@ -5,9 +5,28 @@ import type { · 4 unmodified lines
55 ThreadId,
66 } from "@t3tools/contracts";
77 import { OrchestrationCommand } from "@t3tools/contracts";
8−import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect";
8+import {
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";
922 import * as SqlClient from "effect/unstable/sql/SqlClient";
1023
24+import {
25+ metricAttributes,
26+ orchestrationCommandAckDuration,
27+ orchestrationCommandsTotal,
28+ orchestrationCommandDuration,
29+} from "../../observability/Metrics.ts";
1130 import { toPersistenceSqlError } from "../../persistence/Errors.ts";
1231 import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
1332 import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
@@ -28,6 +47,7 @@ import { · 14 unmodified lines
2847 interface CommandEnvelope {
2948 command: OrchestrationCommand;
3049 result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
50+ startedAtMs: number;
3151 }
3252
3353 function commandToAggregateRef(command: OrchestrationCommand): {
@@ -64,6 +84,12 @@ const makeOrchestrationEngine = Effect.gen(function* () { · 30 unmodified lines
6484
6585 const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
6686 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;
6793 const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
6894 const persistedEvents = yield* Stream.runCollect(
6995 eventStore.readFromSequence(dispatchStartSequence),
@@ -83,113 +109,160 @@ const makeOrchestrationEngine = Effect.gen(function* () { · 13 unmodified lines
83109 }
84110 });
85111
86− return Effect.gen(function* () {
87− const existingReceipt = yield* commandReceiptRepository.getByCommandId({
88− commandId: envelope.command.commandId,
89− });
90− if (Option.isSome(existingReceipt)) {
91− if (existingReceipt.value.status === "accepted") {
92− yield* Deferred.succeed(envelope.result, {
93− sequence: existingReceipt.value.resultSequence,
94− });
95− return;
96− }
97− yield* Deferred.fail(
98− envelope.result,
99− new OrchestrationCommandPreviouslyRejectedError({
112+ return Effect.exit(
113+ Effect.gen(function* () {
114+ yield* Effect.annotateCurrentSpan({
115+ "orchestration.command_id": envelope.command.commandId,
116+ "orchestration.command_type": envelope.command.type,
117+ "orchestration.aggregate_kind": aggregateRef.aggregateKind,
118+ "orchestration.aggregate_id": aggregateRef.aggregateId,
119+ });
120+
121+ const existingReceipt = yield* commandReceiptRepository.getByCommandId({
122+ commandId: envelope.command.commandId,
123+ });
124+ if (Option.isSome(existingReceipt)) {
125+ if (existingReceipt.value.status === "accepted") {
126+ return {
127+ sequence: existingReceipt.value.resultSequence,
128+ };
129+ }
130+ return yield* new OrchestrationCommandPreviouslyRejectedError({
100131 commandId: envelope.command.commandId,
101132 detail: existingReceipt.value.error ?? "Previously rejected.",
102− }),
103− );
104− return;
105− }
133+ });
134+ }
106135
107− const eventBase = yield* decideOrchestrationCommand({
108− command: envelope.command,
109− readModel,
110− });
111− const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
112− const committedCommand = yield* sql
113− .withTransaction(
114− Effect.gen(function* () {
115− const committedEvents: OrchestrationEvent[] = [];
116− 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− }
136+ const eventBase = yield* decideOrchestrationCommand({
137+ command: envelope.command,
138+ readModel,
139+ });
140+ const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
141+ const committedCommand = yield* sql
142+ .withTransaction(
143+ Effect.gen(function* () {
144+ const committedEvents: OrchestrationEvent[] = [];
145+ let nextReadModel = readModel;
124146
125− const lastSavedEvent = committedEvents.at(-1) ?? null;
126− if (lastSavedEvent === null) {
127− return yield* new OrchestrationCommandInvariantError({
128− commandType: envelope.command.type,
129− detail: "Command produced no events.",
130− });
131− }
147+ for (const nextEvent of eventBases) {
148+ const savedEvent = yield* eventStore.append(nextEvent);
149+ nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
150+ yield* projectionPipeline.projectEvent(savedEvent);
151+ committedEvents.push(savedEvent);
152+ }
132153
133− yield* commandReceiptRepository.upsert({
134− commandId: envelope.command.commandId,
135− aggregateKind: lastSavedEvent.aggregateKind,
136− aggregateId: lastSavedEvent.aggregateId,
137− acceptedAt: lastSavedEvent.occurredAt,
138− resultSequence: lastSavedEvent.sequence,
139− status: "accepted",
140− error: null,
141− });
154+ const lastSavedEvent = committedEvents.at(-1) ?? null;
155+ if (lastSavedEvent === null) {
156+ return yield* new OrchestrationCommandInvariantError({
157+ commandType: envelope.command.type,
158+ detail: "Command produced no events.",
159+ });
160+ }
142161
143− return {
144− committedEvents,
145− lastSequence: lastSavedEvent.sequence,
146− nextReadModel,
147− } as const;
148− }),
149− )
150− .pipe(
151− Effect.catchTag("SqlError", (sqlError) =>
152− Effect.fail(
153− toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
162+ yield* commandReceiptRepository.upsert({
163+ commandId: envelope.command.commandId,
164+ aggregateKind: lastSavedEvent.aggregateKind,
165+ aggregateId: lastSavedEvent.aggregateId,
166+ acceptedAt: lastSavedEvent.occurredAt,
167+ resultSequence: lastSavedEvent.sequence,
168+ status: "accepted",
169+ error: null,
170+ });
171+
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+ ),
154184 ),
155− ),
156− );
185+ );
157186
158− readModel = committedCommand.nextReadModel;
159− for (const event of committedCommand.committedEvents) {
160− yield* PubSub.publish(eventPubSub, event);
161− }
162− yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence });
163− }).pipe(
164− Effect.catch((error) =>
165− Effect.gen(function* () {
166− yield* reconcileReadModelAfterDispatchFailure.pipe(
167− Effect.catch(() =>
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,
187+ readModel = committedCommand.nextReadModel;
188+ for (const [index, event] of committedCommand.committedEvents.entries()) {
189+ yield* PubSub.publish(eventPubSub, event);
190+ if (index === 0) {
191+ yield* Metric.update(
192+ Metric.withAttributes(
193+ orchestrationCommandAckDuration,
194+ metricAttributes({
195+ ...baseMetricAttributes,
196+ ackEventType: event.type,
174197 }),
175198 ),
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+ }),
176227 ),
228+ 1,
177229 );
178230
179− if (Schema.is(OrchestrationCommandInvariantError)(error)) {
180− const aggregateRef = commandToAggregateRef(envelope.command);
181− yield* commandReceiptRepository
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));
231+ if (Exit.isSuccess(exit)) {
232+ yield* Deferred.succeed(envelope.result, exit.value);
233+ return;
192234 }
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+
193266 yield* Deferred.fail(envelope.result, error);
194267 }),
195268 ),
@@ -214,7 +287,7 @@ const makeOrchestrationEngine = Effect.gen(function* () { · 18 unmodified lines
214287 const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
215288 Effect.gen(function* () {
216289 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() });
218291 return yield* Deferred.await(result);
219292 });
220293
apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+304−302
@@ -20,6 +20,7 @@ import { · 19 unmodified lines
2020 SqlitePersistenceMemory,
2121 } from "../../persistence/Layers/Sqlite.ts";
2222 import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
23+import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
2324 import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
2425 import {
2526 ORCHESTRATION_PROJECTOR_NAMES,
@@ -57,16 +58,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 31 unmodified lines
5758
5859 yield* eventStore.append({
5960 type: "project.created",
60− eventId: EventId.makeUnsafe("evt-1"),
61+ eventId: EventId.make("evt-1"),
6162 aggregateKind: "project",
62− aggregateId: ProjectId.makeUnsafe("project-1"),
63+ aggregateId: ProjectId.make("project-1"),
6364 occurredAt: now,
64− commandId: CommandId.makeUnsafe("cmd-1"),
65+ commandId: CommandId.make("cmd-1"),
6566 causationEventId: null,
66− correlationId: CommandId.makeUnsafe("cmd-1"),
67+ correlationId: CommandId.make("cmd-1"),
6768 metadata: {},
6869 payload: {
69− projectId: ProjectId.makeUnsafe("project-1"),
70+ projectId: ProjectId.make("project-1"),
7071 title: "Project 1",
7172 workspaceRoot: "/tmp/project-1",
7273 defaultModelSelection: null,
@@ -78,17 +79,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
7879
7980 yield* eventStore.append({
8081 type: "thread.created",
81− eventId: EventId.makeUnsafe("evt-2"),
82+ eventId: EventId.make("evt-2"),
8283 aggregateKind: "thread",
83− aggregateId: ThreadId.makeUnsafe("thread-1"),
84+ aggregateId: ThreadId.make("thread-1"),
8485 occurredAt: now,
85− commandId: CommandId.makeUnsafe("cmd-2"),
86+ commandId: CommandId.make("cmd-2"),
8687 causationEventId: null,
87− correlationId: CommandId.makeUnsafe("cmd-2"),
88+ correlationId: CommandId.make("cmd-2"),
8889 metadata: {},
8990 payload: {
90− threadId: ThreadId.makeUnsafe("thread-1"),
91− projectId: ProjectId.makeUnsafe("project-1"),
91+ threadId: ThreadId.make("thread-1"),
92+ projectId: ProjectId.make("project-1"),
9293 title: "Thread 1",
9394 modelSelection: {
9495 provider: "codex",
@@ -104,17 +105,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
104105
105106 yield* eventStore.append({
106107 type: "thread.message-sent",
107− eventId: EventId.makeUnsafe("evt-3"),
108+ eventId: EventId.make("evt-3"),
108109 aggregateKind: "thread",
109− aggregateId: ThreadId.makeUnsafe("thread-1"),
110+ aggregateId: ThreadId.make("thread-1"),
110111 occurredAt: now,
111− commandId: CommandId.makeUnsafe("cmd-3"),
112+ commandId: CommandId.make("cmd-3"),
112113 causationEventId: null,
113− correlationId: CommandId.makeUnsafe("cmd-3"),
114+ correlationId: CommandId.make("cmd-3"),
114115 metadata: {},
115116 payload: {
116− threadId: ThreadId.makeUnsafe("thread-1"),
117− messageId: MessageId.makeUnsafe("message-1"),
117+ threadId: ThreadId.make("thread-1"),
118+ messageId: MessageId.make("message-1"),
118119 role: "assistant",
119120 text: "hello",
120121 turnId: null,
@@ -182,17 +183,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))( · 61 unmodified lines
182183
183184 yield* eventStore.append({
184185 type: "thread.message-sent",
185− eventId: EventId.makeUnsafe("evt-attachments"),
186+ eventId: EventId.make("evt-attachments"),
186187 aggregateKind: "thread",
187− aggregateId: ThreadId.makeUnsafe("thread-attachments"),
188+ aggregateId: ThreadId.make("thread-attachments"),
188189 occurredAt: now,
189− commandId: CommandId.makeUnsafe("cmd-attachments"),
190+ commandId: CommandId.make("cmd-attachments"),
190191 causationEventId: null,
191− correlationId: CommandId.makeUnsafe("cmd-attachments"),
192+ correlationId: CommandId.make("cmd-attachments"),
192193 metadata: {},
193194 payload: {
194− threadId: ThreadId.makeUnsafe("thread-attachments"),
195− messageId: MessageId.makeUnsafe("message-attachments"),
195+ threadId: ThreadId.make("thread-attachments"),
196+ messageId: MessageId.make("message-attachments"),
196197 role: "user",
197198 text: "Inspect this",
198199 attachments: [
@@ -248,17 +249,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 49 unmodified lines
248249
249250 yield* eventStore.append({
250251 type: "thread.message-sent",
251− eventId: EventId.makeUnsafe("evt-attachments-safe"),
252+ eventId: EventId.make("evt-attachments-safe"),
252253 aggregateKind: "thread",
253− aggregateId: ThreadId.makeUnsafe("thread-attachments-safe"),
254+ aggregateId: ThreadId.make("thread-attachments-safe"),
254255 occurredAt: now,
255− commandId: CommandId.makeUnsafe("cmd-attachments-safe"),
256+ commandId: CommandId.make("cmd-attachments-safe"),
256257 causationEventId: null,
257− correlationId: CommandId.makeUnsafe("cmd-attachments-safe"),
258+ correlationId: CommandId.make("cmd-attachments-safe"),
258259 metadata: {},
259260 payload: {
260− threadId: ThreadId.makeUnsafe("thread-attachments-safe"),
261− messageId: MessageId.makeUnsafe("message-attachments-safe"),
261+ threadId: ThreadId.make("thread-attachments-safe"),
262+ messageId: MessageId.make("message-attachments-safe"),
262263 role: "user",
263264 text: "Inspect this",
264265 attachments: [
@@ -329,16 +330,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 64 unmodified lines
329330
330331 yield* eventStore.append({
331332 type: "project.created",
332− eventId: EventId.makeUnsafe("evt-clear-attachments-1"),
333+ eventId: EventId.make("evt-clear-attachments-1"),
333334 aggregateKind: "project",
334− aggregateId: ProjectId.makeUnsafe("project-clear-attachments"),
335+ aggregateId: ProjectId.make("project-clear-attachments"),
335336 occurredAt: now,
336− commandId: CommandId.makeUnsafe("cmd-clear-attachments-1"),
337+ commandId: CommandId.make("cmd-clear-attachments-1"),
337338 causationEventId: null,
338− correlationId: CommandId.makeUnsafe("cmd-clear-attachments-1"),
339+ correlationId: CommandId.make("cmd-clear-attachments-1"),
339340 metadata: {},
340341 payload: {
341− projectId: ProjectId.makeUnsafe("project-clear-attachments"),
342+ projectId: ProjectId.make("project-clear-attachments"),
342343 title: "Project Clear Attachments",
343344 workspaceRoot: "/tmp/project-clear-attachments",
344345 defaultModelSelection: null,
@@ -350,17 +351,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
350351
351352 yield* eventStore.append({
352353 type: "thread.created",
353− eventId: EventId.makeUnsafe("evt-clear-attachments-2"),
354+ eventId: EventId.make("evt-clear-attachments-2"),
354355 aggregateKind: "thread",
355− aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"),
356+ aggregateId: ThreadId.make("thread-clear-attachments"),
356357 occurredAt: now,
357− commandId: CommandId.makeUnsafe("cmd-clear-attachments-2"),
358+ commandId: CommandId.make("cmd-clear-attachments-2"),
358359 causationEventId: null,
359− correlationId: CommandId.makeUnsafe("cmd-clear-attachments-2"),
360+ correlationId: CommandId.make("cmd-clear-attachments-2"),
360361 metadata: {},
361362 payload: {
362− threadId: ThreadId.makeUnsafe("thread-clear-attachments"),
363− projectId: ProjectId.makeUnsafe("project-clear-attachments"),
363+ threadId: ThreadId.make("thread-clear-attachments"),
364+ projectId: ProjectId.make("project-clear-attachments"),
364365 title: "Thread Clear Attachments",
365366 modelSelection: {
366367 provider: "codex",
@@ -376,17 +377,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
376377
377378 yield* eventStore.append({
378379 type: "thread.message-sent",
379− eventId: EventId.makeUnsafe("evt-clear-attachments-3"),
380+ eventId: EventId.make("evt-clear-attachments-3"),
380381 aggregateKind: "thread",
381− aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"),
382+ aggregateId: ThreadId.make("thread-clear-attachments"),
382383 occurredAt: now,
383− commandId: CommandId.makeUnsafe("cmd-clear-attachments-3"),
384+ commandId: CommandId.make("cmd-clear-attachments-3"),
384385 causationEventId: null,
385− correlationId: CommandId.makeUnsafe("cmd-clear-attachments-3"),
386+ correlationId: CommandId.make("cmd-clear-attachments-3"),
386387 metadata: {},
387388 payload: {
388− threadId: ThreadId.makeUnsafe("thread-clear-attachments"),
389− messageId: MessageId.makeUnsafe("message-clear-attachments"),
389+ threadId: ThreadId.make("thread-clear-attachments"),
390+ messageId: MessageId.make("message-clear-attachments"),
390391 role: "user",
391392 text: "Has attachments",
392393 attachments: [
@@ -407,17 +408,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 14 unmodified lines
407408
408409 yield* eventStore.append({
409410 type: "thread.message-sent",
410− eventId: EventId.makeUnsafe("evt-clear-attachments-4"),
411+ eventId: EventId.make("evt-clear-attachments-4"),
411412 aggregateKind: "thread",
412− aggregateId: ThreadId.makeUnsafe("thread-clear-attachments"),
413+ aggregateId: ThreadId.make("thread-clear-attachments"),
413414 occurredAt: later,
414− commandId: CommandId.makeUnsafe("cmd-clear-attachments-4"),
415+ commandId: CommandId.make("cmd-clear-attachments-4"),
415416 causationEventId: null,
416− correlationId: CommandId.makeUnsafe("cmd-clear-attachments-4"),
417+ correlationId: CommandId.make("cmd-clear-attachments-4"),
417418 metadata: {},
418419 payload: {
419− threadId: ThreadId.makeUnsafe("thread-clear-attachments"),
420− messageId: MessageId.makeUnsafe("message-clear-attachments"),
420+ threadId: ThreadId.make("thread-clear-attachments"),
421+ messageId: MessageId.make("message-clear-attachments"),
421422 role: "user",
422423 text: "",
423424 attachments: [],
@@ -457,16 +458,16 @@ it.layer( · 33 unmodified lines
457458
458459 yield* eventStore.append({
459460 type: "project.created",
460− eventId: EventId.makeUnsafe("evt-overwrite-1"),
461+ eventId: EventId.make("evt-overwrite-1"),
461462 aggregateKind: "project",
462− aggregateId: ProjectId.makeUnsafe("project-overwrite"),
463+ aggregateId: ProjectId.make("project-overwrite"),
463464 occurredAt: now,
464− commandId: CommandId.makeUnsafe("cmd-overwrite-1"),
465+ commandId: CommandId.make("cmd-overwrite-1"),
465466 causationEventId: null,
466− correlationId: CommandId.makeUnsafe("cmd-overwrite-1"),
467+ correlationId: CommandId.make("cmd-overwrite-1"),
467468 metadata: {},
468469 payload: {
469− projectId: ProjectId.makeUnsafe("project-overwrite"),
470+ projectId: ProjectId.make("project-overwrite"),
470471 title: "Project Overwrite",
471472 workspaceRoot: "/tmp/project-overwrite",
472473 defaultModelSelection: null,
@@ -478,17 +479,17 @@ it.layer( · 5 unmodified lines
478479
479480 yield* eventStore.append({
480481 type: "thread.created",
481− eventId: EventId.makeUnsafe("evt-overwrite-2"),
482+ eventId: EventId.make("evt-overwrite-2"),
482483 aggregateKind: "thread",
483− aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
484+ aggregateId: ThreadId.make("thread-overwrite"),
484485 occurredAt: now,
485− commandId: CommandId.makeUnsafe("cmd-overwrite-2"),
486+ commandId: CommandId.make("cmd-overwrite-2"),
486487 causationEventId: null,
487− correlationId: CommandId.makeUnsafe("cmd-overwrite-2"),
488+ correlationId: CommandId.make("cmd-overwrite-2"),
488489 metadata: {},
489490 payload: {
490− threadId: ThreadId.makeUnsafe("thread-overwrite"),
491− projectId: ProjectId.makeUnsafe("project-overwrite"),
491+ threadId: ThreadId.make("thread-overwrite"),
492+ projectId: ProjectId.make("project-overwrite"),
492493 title: "Thread Overwrite",
493494 modelSelection: {
494495 provider: "codex",
@@ -504,17 +505,17 @@ it.layer( · 9 unmodified lines
504505
505506 yield* eventStore.append({
506507 type: "thread.message-sent",
507− eventId: EventId.makeUnsafe("evt-overwrite-3"),
508+ eventId: EventId.make("evt-overwrite-3"),
508509 aggregateKind: "thread",
509− aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
510+ aggregateId: ThreadId.make("thread-overwrite"),
510511 occurredAt: now,
511− commandId: CommandId.makeUnsafe("cmd-overwrite-3"),
512+ commandId: CommandId.make("cmd-overwrite-3"),
512513 causationEventId: null,
513− correlationId: CommandId.makeUnsafe("cmd-overwrite-3"),
514+ correlationId: CommandId.make("cmd-overwrite-3"),
514515 metadata: {},
515516 payload: {
516− threadId: ThreadId.makeUnsafe("thread-overwrite"),
517− messageId: MessageId.makeUnsafe("message-overwrite"),
517+ threadId: ThreadId.make("thread-overwrite"),
518+ messageId: MessageId.make("message-overwrite"),
518519 role: "user",
519520 text: "first image",
520521 attachments: [
@@ -535,17 +536,17 @@ it.layer( · 14 unmodified lines
535536
536537 yield* eventStore.append({
537538 type: "thread.message-sent",
538− eventId: EventId.makeUnsafe("evt-overwrite-4"),
539+ eventId: EventId.make("evt-overwrite-4"),
539540 aggregateKind: "thread",
540− aggregateId: ThreadId.makeUnsafe("thread-overwrite"),
541+ aggregateId: ThreadId.make("thread-overwrite"),
541542 occurredAt: later,
542− commandId: CommandId.makeUnsafe("cmd-overwrite-4"),
543+ commandId: CommandId.make("cmd-overwrite-4"),
543544 causationEventId: null,
544− correlationId: CommandId.makeUnsafe("cmd-overwrite-4"),
545+ correlationId: CommandId.make("cmd-overwrite-4"),
545546 metadata: {},
546547 payload: {
547− threadId: ThreadId.makeUnsafe("thread-overwrite"),
548− messageId: MessageId.makeUnsafe("message-overwrite"),
548+ threadId: ThreadId.make("thread-overwrite"),
549+ messageId: MessageId.make("message-overwrite"),
549550 role: "user",
550551 text: "",
551552 attachments: [
@@ -605,16 +606,16 @@ it.layer( · 53 unmodified lines
605606
606607 yield* appendAndProject({
607608 type: "project.created",
608− eventId: EventId.makeUnsafe("evt-rollback-1"),
609+ eventId: EventId.make("evt-rollback-1"),
609610 aggregateKind: "project",
610− aggregateId: ProjectId.makeUnsafe("project-rollback"),
611+ aggregateId: ProjectId.make("project-rollback"),
611612 occurredAt: now,
612− commandId: CommandId.makeUnsafe("cmd-rollback-1"),
613+ commandId: CommandId.make("cmd-rollback-1"),
613614 causationEventId: null,
614− correlationId: CorrelationId.makeUnsafe("cmd-rollback-1"),
615+ correlationId: CorrelationId.make("cmd-rollback-1"),
615616 metadata: {},
616617 payload: {
617− projectId: ProjectId.makeUnsafe("project-rollback"),
618+ projectId: ProjectId.make("project-rollback"),
618619 title: "Project Rollback",
619620 workspaceRoot: "/tmp/project-rollback",
620621 defaultModelSelection: null,
@@ -626,17 +627,17 @@ it.layer( · 5 unmodified lines
626627
627628 yield* appendAndProject({
628629 type: "thread.created",
629− eventId: EventId.makeUnsafe("evt-rollback-2"),
630+ eventId: EventId.make("evt-rollback-2"),
630631 aggregateKind: "thread",
631− aggregateId: ThreadId.makeUnsafe("thread-rollback"),
632+ aggregateId: ThreadId.make("thread-rollback"),
632633 occurredAt: now,
633− commandId: CommandId.makeUnsafe("cmd-rollback-2"),
634+ commandId: CommandId.make("cmd-rollback-2"),
634635 causationEventId: null,
635− correlationId: CorrelationId.makeUnsafe("cmd-rollback-2"),
636+ correlationId: CorrelationId.make("cmd-rollback-2"),
636637 metadata: {},
637638 payload: {
638− threadId: ThreadId.makeUnsafe("thread-rollback"),
639− projectId: ProjectId.makeUnsafe("project-rollback"),
639+ threadId: ThreadId.make("thread-rollback"),
640+ projectId: ProjectId.make("project-rollback"),
640641 title: "Thread Rollback",
641642 modelSelection: {
642643 provider: "codex",
@@ -662,17 +663,17 @@ it.layer( · 19 unmodified lines
662663 const result = yield* Effect.result(
663664 appendAndProject({
664665 type: "thread.message-sent",
665− eventId: EventId.makeUnsafe("evt-rollback-3"),
666+ eventId: EventId.make("evt-rollback-3"),
666667 aggregateKind: "thread",
667− aggregateId: ThreadId.makeUnsafe("thread-rollback"),
668+ aggregateId: ThreadId.make("thread-rollback"),
668669 occurredAt: now,
669− commandId: CommandId.makeUnsafe("cmd-rollback-3"),
670+ commandId: CommandId.make("cmd-rollback-3"),
670671 causationEventId: null,
671− correlationId: CorrelationId.makeUnsafe("cmd-rollback-3"),
672+ correlationId: CorrelationId.make("cmd-rollback-3"),
672673 metadata: {},
673674 payload: {
674− threadId: ThreadId.makeUnsafe("thread-rollback"),
675− messageId: MessageId.makeUnsafe("message-rollback"),
675+ threadId: ThreadId.make("thread-rollback"),
676+ messageId: MessageId.make("message-rollback"),
676677 role: "user",
677678 text: "Rollback me",
678679 attachments: [
@@ -721,7 +722,7 @@ it.layer( · 42 unmodified lines
721722 const eventStore = yield* OrchestrationEventStore;
722723 const { attachmentsDir } = yield* ServerConfig;
723724 const now = new Date().toISOString();
724− const threadId = ThreadId.makeUnsafe("Thread Revert.Files");
725+ const threadId = ThreadId.make("Thread Revert.Files");
725726 const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001";
726727 const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002";
727728 const otherThreadAttachmentId =
@@ -734,16 +735,16 @@ it.layer( · 6 unmodified lines
734735
735736 yield* appendAndProject({
736737 type: "project.created",
737− eventId: EventId.makeUnsafe("evt-revert-files-1"),
738+ eventId: EventId.make("evt-revert-files-1"),
738739 aggregateKind: "project",
739− aggregateId: ProjectId.makeUnsafe("project-revert-files"),
740+ aggregateId: ProjectId.make("project-revert-files"),
740741 occurredAt: now,
741− commandId: CommandId.makeUnsafe("cmd-revert-files-1"),
742+ commandId: CommandId.make("cmd-revert-files-1"),
742743 causationEventId: null,
743− correlationId: CorrelationId.makeUnsafe("cmd-revert-files-1"),
744+ correlationId: CorrelationId.make("cmd-revert-files-1"),
744745 metadata: {},
745746 payload: {
746− projectId: ProjectId.makeUnsafe("project-revert-files"),
747+ projectId: ProjectId.make("project-revert-files"),
747748 title: "Project Revert Files",
748749 workspaceRoot: "/tmp/project-revert-files",
749750 defaultModelSelection: null,
@@ -755,17 +756,17 @@ it.layer( · 5 unmodified lines
755756
756757 yield* appendAndProject({
757758 type: "thread.created",
758− eventId: EventId.makeUnsafe("evt-revert-files-2"),
759+ eventId: EventId.make("evt-revert-files-2"),
759760 aggregateKind: "thread",
760761 aggregateId: threadId,
761762 occurredAt: now,
762− commandId: CommandId.makeUnsafe("cmd-revert-files-2"),
763+ commandId: CommandId.make("cmd-revert-files-2"),
763764 causationEventId: null,
764− correlationId: CorrelationId.makeUnsafe("cmd-revert-files-2"),
765+ correlationId: CorrelationId.make("cmd-revert-files-2"),
765766 metadata: {},
766767 payload: {
767768 threadId,
768− projectId: ProjectId.makeUnsafe("project-revert-files"),
769+ projectId: ProjectId.make("project-revert-files"),
769770 title: "Thread Revert Files",
770771 modelSelection: {
771772 provider: "codex",
@@ -781,39 +782,39 @@ it.layer( · 9 unmodified lines
781782
782783 yield* appendAndProject({
783784 type: "thread.turn-diff-completed",
784− eventId: EventId.makeUnsafe("evt-revert-files-3"),
785+ eventId: EventId.make("evt-revert-files-3"),
785786 aggregateKind: "thread",
786787 aggregateId: threadId,
787788 occurredAt: now,
788− commandId: CommandId.makeUnsafe("cmd-revert-files-3"),
789+ commandId: CommandId.make("cmd-revert-files-3"),
789790 causationEventId: null,
790− correlationId: CorrelationId.makeUnsafe("cmd-revert-files-3"),
791+ correlationId: CorrelationId.make("cmd-revert-files-3"),
791792 metadata: {},
792793 payload: {
793794 threadId,
794− turnId: TurnId.makeUnsafe("turn-keep"),
795+ turnId: TurnId.make("turn-keep"),
795796 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"),
797798 status: "ready",
798799 files: [],
799− assistantMessageId: MessageId.makeUnsafe("message-keep"),
800+ assistantMessageId: MessageId.make("message-keep"),
800801 completedAt: now,
801802 },
802803 });
803804
804805 yield* appendAndProject({
805806 type: "thread.message-sent",
806− eventId: EventId.makeUnsafe("evt-revert-files-4"),
807+ eventId: EventId.make("evt-revert-files-4"),
807808 aggregateKind: "thread",
808809 aggregateId: threadId,
809810 occurredAt: now,
810− commandId: CommandId.makeUnsafe("cmd-revert-files-4"),
811+ commandId: CommandId.make("cmd-revert-files-4"),
811812 causationEventId: null,
812− correlationId: CorrelationId.makeUnsafe("cmd-revert-files-4"),
813+ correlationId: CorrelationId.make("cmd-revert-files-4"),
813814 metadata: {},
814815 payload: {
815816 threadId,
816− messageId: MessageId.makeUnsafe("message-keep"),
817+ messageId: MessageId.make("message-keep"),
817818 role: "assistant",
818819 text: "Keep",
819820 attachments: [
@@ -825,7 +826,7 @@ it.layer( · 5 unmodified lines
825826 sizeBytes: 5,
826827 },
827828 ],
828− turnId: TurnId.makeUnsafe("turn-keep"),
829+ turnId: TurnId.make("turn-keep"),
829830 streaming: false,
830831 createdAt: now,
831832 updatedAt: now,
@@ -834,39 +835,39 @@ it.layer( · 2 unmodified lines
834835
835836 yield* appendAndProject({
836837 type: "thread.turn-diff-completed",
837− eventId: EventId.makeUnsafe("evt-revert-files-5"),
838+ eventId: EventId.make("evt-revert-files-5"),
838839 aggregateKind: "thread",
839840 aggregateId: threadId,
840841 occurredAt: now,
841− commandId: CommandId.makeUnsafe("cmd-revert-files-5"),
842+ commandId: CommandId.make("cmd-revert-files-5"),
842843 causationEventId: null,
843− correlationId: CorrelationId.makeUnsafe("cmd-revert-files-5"),
844+ correlationId: CorrelationId.make("cmd-revert-files-5"),
844845 metadata: {},
845846 payload: {
846847 threadId,
847− turnId: TurnId.makeUnsafe("turn-remove"),
848+ turnId: TurnId.make("turn-remove"),
848849 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"),
850851 status: "ready",
851852 files: [],
852− assistantMessageId: MessageId.makeUnsafe("message-remove"),
853+ assistantMessageId: MessageId.make("message-remove"),
853854 completedAt: now,
854855 },
855856 });
856857
857858 yield* appendAndProject({
858859 type: "thread.message-sent",
859− eventId: EventId.makeUnsafe("evt-revert-files-6"),
860+ eventId: EventId.make("evt-revert-files-6"),
860861 aggregateKind: "thread",
861862 aggregateId: threadId,
862863 occurredAt: now,
863− commandId: CommandId.makeUnsafe("cmd-revert-files-6"),
864+ commandId: CommandId.make("cmd-revert-files-6"),
864865 causationEventId: null,
865− correlationId: CorrelationId.makeUnsafe("cmd-revert-files-6"),
866+ correlationId: CorrelationId.make("cmd-revert-files-6"),
866867 metadata: {},
867868 payload: {
868869 threadId,
869− messageId: MessageId.makeUnsafe("message-remove"),
870+ messageId: MessageId.make("message-remove"),
870871 role: "assistant",
871872 text: "Remove",
872873 attachments: [
@@ -878,7 +879,7 @@ it.layer( · 5 unmodified lines
878879 sizeBytes: 5,
879880 },
880881 ],
881− turnId: TurnId.makeUnsafe("turn-remove"),
882+ turnId: TurnId.make("turn-remove"),
882883 streaming: false,
883884 createdAt: now,
884885 updatedAt: now,
@@ -898,13 +899,13 @@ it.layer( · 13 unmodified lines
898899
899900 yield* appendAndProject({
900901 type: "thread.reverted",
901− eventId: EventId.makeUnsafe("evt-revert-files-7"),
902+ eventId: EventId.make("evt-revert-files-7"),
902903 aggregateKind: "thread",
903904 aggregateId: threadId,
904905 occurredAt: now,
905− commandId: CommandId.makeUnsafe("cmd-revert-files-7"),
906+ commandId: CommandId.make("cmd-revert-files-7"),
906907 causationEventId: null,
907− correlationId: CorrelationId.makeUnsafe("cmd-revert-files-7"),
908+ correlationId: CorrelationId.make("cmd-revert-files-7"),
908909 metadata: {},
909910 payload: {
910911 threadId,
@@ -930,7 +931,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 19 unmodified lines
930931 const eventStore = yield* OrchestrationEventStore;
931932 const { attachmentsDir } = yield* ServerConfig;
932933 const now = new Date().toISOString();
933− const threadId = ThreadId.makeUnsafe("Thread Delete.Files");
934+ const threadId = ThreadId.make("Thread Delete.Files");
934935 const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001";
935936 const otherThreadAttachmentId =
936937 "thread-delete-files-extra-00000000-0000-4000-8000-000000000002";
@@ -942,16 +943,16 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 5 unmodified lines
942943
943944 yield* appendAndProject({
944945 type: "project.created",
945− eventId: EventId.makeUnsafe("evt-delete-files-1"),
946+ eventId: EventId.make("evt-delete-files-1"),
946947 aggregateKind: "project",
947− aggregateId: ProjectId.makeUnsafe("project-delete-files"),
948+ aggregateId: ProjectId.make("project-delete-files"),
948949 occurredAt: now,
949− commandId: CommandId.makeUnsafe("cmd-delete-files-1"),
950+ commandId: CommandId.make("cmd-delete-files-1"),
950951 causationEventId: null,
951− correlationId: CorrelationId.makeUnsafe("cmd-delete-files-1"),
952+ correlationId: CorrelationId.make("cmd-delete-files-1"),
952953 metadata: {},
953954 payload: {
954− projectId: ProjectId.makeUnsafe("project-delete-files"),
955+ projectId: ProjectId.make("project-delete-files"),
955956 title: "Project Delete Files",
956957 workspaceRoot: "/tmp/project-delete-files",
957958 defaultModelSelection: null,
@@ -963,17 +964,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 5 unmodified lines
963964
964965 yield* appendAndProject({
965966 type: "thread.created",
966− eventId: EventId.makeUnsafe("evt-delete-files-2"),
967+ eventId: EventId.make("evt-delete-files-2"),
967968 aggregateKind: "thread",
968969 aggregateId: threadId,
969970 occurredAt: now,
970− commandId: CommandId.makeUnsafe("cmd-delete-files-2"),
971+ commandId: CommandId.make("cmd-delete-files-2"),
971972 causationEventId: null,
972− correlationId: CorrelationId.makeUnsafe("cmd-delete-files-2"),
973+ correlationId: CorrelationId.make("cmd-delete-files-2"),
973974 metadata: {},
974975 payload: {
975976 threadId,
976− projectId: ProjectId.makeUnsafe("project-delete-files"),
977+ projectId: ProjectId.make("project-delete-files"),
977978 title: "Thread Delete Files",
978979 modelSelection: {
979980 provider: "codex",
@@ -989,17 +990,17 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 9 unmodified lines
989990
990991 yield* appendAndProject({
991992 type: "thread.message-sent",
992− eventId: EventId.makeUnsafe("evt-delete-files-3"),
993+ eventId: EventId.make("evt-delete-files-3"),
993994 aggregateKind: "thread",
994995 aggregateId: threadId,
995996 occurredAt: now,
996− commandId: CommandId.makeUnsafe("cmd-delete-files-3"),
997+ commandId: CommandId.make("cmd-delete-files-3"),
997998 causationEventId: null,
998− correlationId: CorrelationId.makeUnsafe("cmd-delete-files-3"),
999+ correlationId: CorrelationId.make("cmd-delete-files-3"),
9991000 metadata: {},
10001001 payload: {
10011002 threadId,
1002− messageId: MessageId.makeUnsafe("message-delete-files"),
1003+ messageId: MessageId.make("message-delete-files"),
10031004 role: "user",
10041005 text: "Delete",
10051006 attachments: [
@@ -1031,13 +1032,13 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 25 unmodified lines
10311032
10321033 yield* appendAndProject({
10331034 type: "thread.deleted",
1034− eventId: EventId.makeUnsafe("evt-delete-files-4"),
1035+ eventId: EventId.make("evt-delete-files-4"),
10351036 aggregateKind: "thread",
10361037 aggregateId: threadId,
10371038 occurredAt: now,
1038− commandId: CommandId.makeUnsafe("cmd-delete-files-4"),
1039+ commandId: CommandId.make("cmd-delete-files-4"),
10391040 causationEventId: null,
1040− correlationId: CorrelationId.makeUnsafe("cmd-delete-files-4"),
1041+ correlationId: CorrelationId.make("cmd-delete-files-4"),
10411042 metadata: {},
10421043 payload: {
10431044 threadId,
@@ -1071,16 +1072,16 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta · 27 unmodified lines
10711072
10721073 yield* eventStore.append({
10731074 type: "thread.deleted",
1074− eventId: EventId.makeUnsafe("evt-unsafe-thread-delete"),
1075+ eventId: EventId.make("evt-unsafe-thread-delete"),
10751076 aggregateKind: "thread",
1076− aggregateId: ThreadId.makeUnsafe(".."),
1077+ aggregateId: ThreadId.make(".."),
10771078 occurredAt: now,
1078− commandId: CommandId.makeUnsafe("cmd-unsafe-thread-delete"),
1079+ commandId: CommandId.make("cmd-unsafe-thread-delete"),
10791080 causationEventId: null,
1080− correlationId: CorrelationId.makeUnsafe("cmd-unsafe-thread-delete"),
1081+ correlationId: CorrelationId.make("cmd-unsafe-thread-delete"),
10811082 metadata: {},
10821083 payload: {
1083− threadId: ThreadId.makeUnsafe(".."),
1084+ threadId: ThreadId.make(".."),
10841085 deletedAt: now,
10851086 },
10861087 });
@@ -1105,16 +1106,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 18 unmodified lines
11051106
11061107 yield* eventStore.append({
11071108 type: "project.created",
1108− eventId: EventId.makeUnsafe("evt-a1"),
1109+ eventId: EventId.make("evt-a1"),
11091110 aggregateKind: "project",
1110− aggregateId: ProjectId.makeUnsafe("project-a"),
1111+ aggregateId: ProjectId.make("project-a"),
11111112 occurredAt: now,
1112− commandId: CommandId.makeUnsafe("cmd-a1"),
1113+ commandId: CommandId.make("cmd-a1"),
11131114 causationEventId: null,
1114− correlationId: CorrelationId.makeUnsafe("cmd-a1"),
1115+ correlationId: CorrelationId.make("cmd-a1"),
11151116 metadata: {},
11161117 payload: {
1117− projectId: ProjectId.makeUnsafe("project-a"),
1118+ projectId: ProjectId.make("project-a"),
11181119 title: "Project A",
11191120 workspaceRoot: "/tmp/project-a",
11201121 defaultModelSelection: null,
@@ -1126,17 +1127,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
11261127
11271128 yield* eventStore.append({
11281129 type: "thread.created",
1129− eventId: EventId.makeUnsafe("evt-a2"),
1130+ eventId: EventId.make("evt-a2"),
11301131 aggregateKind: "thread",
1131− aggregateId: ThreadId.makeUnsafe("thread-a"),
1132+ aggregateId: ThreadId.make("thread-a"),
11321133 occurredAt: now,
1133− commandId: CommandId.makeUnsafe("cmd-a2"),
1134+ commandId: CommandId.make("cmd-a2"),
11341135 causationEventId: null,
1135− correlationId: CorrelationId.makeUnsafe("cmd-a2"),
1136+ correlationId: CorrelationId.make("cmd-a2"),
11361137 metadata: {},
11371138 payload: {
1138− threadId: ThreadId.makeUnsafe("thread-a"),
1139− projectId: ProjectId.makeUnsafe("project-a"),
1139+ threadId: ThreadId.make("thread-a"),
1140+ projectId: ProjectId.make("project-a"),
11401141 title: "Thread A",
11411142 modelSelection: {
11421143 provider: "codex",
@@ -1152,17 +1153,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
11521153
11531154 yield* eventStore.append({
11541155 type: "thread.message-sent",
1155− eventId: EventId.makeUnsafe("evt-a3"),
1156+ eventId: EventId.make("evt-a3"),
11561157 aggregateKind: "thread",
1157− aggregateId: ThreadId.makeUnsafe("thread-a"),
1158+ aggregateId: ThreadId.make("thread-a"),
11581159 occurredAt: now,
1159− commandId: CommandId.makeUnsafe("cmd-a3"),
1160+ commandId: CommandId.make("cmd-a3"),
11601161 causationEventId: null,
1161− correlationId: CorrelationId.makeUnsafe("cmd-a3"),
1162+ correlationId: CorrelationId.make("cmd-a3"),
11621163 metadata: {},
11631164 payload: {
1164− threadId: ThreadId.makeUnsafe("thread-a"),
1165− messageId: MessageId.makeUnsafe("message-a"),
1165+ threadId: ThreadId.make("thread-a"),
1166+ messageId: MessageId.make("message-a"),
11661167 role: "assistant",
11671168 text: "hello",
11681169 turnId: null,
@@ -1176,17 +1177,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 7 unmodified lines
11761177
11771178 yield* eventStore.append({
11781179 type: "thread.message-sent",
1179− eventId: EventId.makeUnsafe("evt-a4"),
1180+ eventId: EventId.make("evt-a4"),
11801181 aggregateKind: "thread",
1181− aggregateId: ThreadId.makeUnsafe("thread-a"),
1182+ aggregateId: ThreadId.make("thread-a"),
11821183 occurredAt: now,
1183− commandId: CommandId.makeUnsafe("cmd-a4"),
1184+ commandId: CommandId.make("cmd-a4"),
11841185 causationEventId: null,
1185− correlationId: CorrelationId.makeUnsafe("cmd-a4"),
1186+ correlationId: CorrelationId.make("cmd-a4"),
11861187 metadata: {},
11871188 payload: {
1188− threadId: ThreadId.makeUnsafe("thread-a"),
1189− messageId: MessageId.makeUnsafe("message-a"),
1189+ threadId: ThreadId.make("thread-a"),
1190+ messageId: MessageId.make("message-a"),
11901191 role: "assistant",
11911192 text: " world",
11921193 turnId: null,
@@ -1232,16 +1233,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 39 unmodified lines
12321233
12331234 yield* eventStore.append({
12341235 type: "project.created",
1235− eventId: EventId.makeUnsafe("evt-empty-1"),
1236+ eventId: EventId.make("evt-empty-1"),
12361237 aggregateKind: "project",
1237− aggregateId: ProjectId.makeUnsafe("project-empty"),
1238+ aggregateId: ProjectId.make("project-empty"),
12381239 occurredAt: now,
1239− commandId: CommandId.makeUnsafe("cmd-empty-1"),
1240+ commandId: CommandId.make("cmd-empty-1"),
12401241 causationEventId: null,
1241− correlationId: CorrelationId.makeUnsafe("cmd-empty-1"),
1242+ correlationId: CorrelationId.make("cmd-empty-1"),
12421243 metadata: {},
12431244 payload: {
1244− projectId: ProjectId.makeUnsafe("project-empty"),
1245+ projectId: ProjectId.make("project-empty"),
12451246 title: "Project Empty",
12461247 workspaceRoot: "/tmp/project-empty",
12471248 defaultModelSelection: null,
@@ -1253,17 +1254,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
12531254
12541255 yield* eventStore.append({
12551256 type: "thread.created",
1256− eventId: EventId.makeUnsafe("evt-empty-2"),
1257+ eventId: EventId.make("evt-empty-2"),
12571258 aggregateKind: "thread",
1258− aggregateId: ThreadId.makeUnsafe("thread-empty"),
1259+ aggregateId: ThreadId.make("thread-empty"),
12591260 occurredAt: now,
1260− commandId: CommandId.makeUnsafe("cmd-empty-2"),
1261+ commandId: CommandId.make("cmd-empty-2"),
12611262 causationEventId: null,
1262− correlationId: CorrelationId.makeUnsafe("cmd-empty-2"),
1263+ correlationId: CorrelationId.make("cmd-empty-2"),
12631264 metadata: {},
12641265 payload: {
1265− threadId: ThreadId.makeUnsafe("thread-empty"),
1266− projectId: ProjectId.makeUnsafe("project-empty"),
1266+ threadId: ThreadId.make("thread-empty"),
1267+ projectId: ProjectId.make("project-empty"),
12671268 title: "Thread Empty",
12681269 modelSelection: {
12691270 provider: "codex",
@@ -1279,17 +1280,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
12791280
12801281 yield* eventStore.append({
12811282 type: "thread.message-sent",
1282− eventId: EventId.makeUnsafe("evt-empty-3"),
1283+ eventId: EventId.make("evt-empty-3"),
12831284 aggregateKind: "thread",
1284− aggregateId: ThreadId.makeUnsafe("thread-empty"),
1285+ aggregateId: ThreadId.make("thread-empty"),
12851286 occurredAt: now,
1286− commandId: CommandId.makeUnsafe("cmd-empty-3"),
1287+ commandId: CommandId.make("cmd-empty-3"),
12871288 causationEventId: null,
1288− correlationId: CorrelationId.makeUnsafe("cmd-empty-3"),
1289+ correlationId: CorrelationId.make("cmd-empty-3"),
12891290 metadata: {},
12901291 payload: {
1291− threadId: ThreadId.makeUnsafe("thread-empty"),
1292− messageId: MessageId.makeUnsafe("assistant-empty"),
1292+ threadId: ThreadId.make("thread-empty"),
1293+ messageId: MessageId.make("assistant-empty"),
12931294 role: "assistant",
12941295 text: "Hello",
12951296 turnId: null,
@@ -1301,17 +1302,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
13011302
13021303 yield* eventStore.append({
13031304 type: "thread.message-sent",
1304− eventId: EventId.makeUnsafe("evt-empty-4"),
1305+ eventId: EventId.make("evt-empty-4"),
13051306 aggregateKind: "thread",
1306− aggregateId: ThreadId.makeUnsafe("thread-empty"),
1307+ aggregateId: ThreadId.make("thread-empty"),
13071308 occurredAt: now,
1308− commandId: CommandId.makeUnsafe("cmd-empty-4"),
1309+ commandId: CommandId.make("cmd-empty-4"),
13091310 causationEventId: null,
1310− correlationId: CorrelationId.makeUnsafe("cmd-empty-4"),
1311+ correlationId: CorrelationId.make("cmd-empty-4"),
13111312 metadata: {},
13121313 payload: {
1313− threadId: ThreadId.makeUnsafe("thread-empty"),
1314− messageId: MessageId.makeUnsafe("assistant-empty"),
1314+ threadId: ThreadId.make("thread-empty"),
1315+ messageId: MessageId.make("assistant-empty"),
13151316 role: "assistant",
13161317 text: " world",
13171318 turnId: null,
@@ -1323,17 +1324,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
13231324
13241325 yield* eventStore.append({
13251326 type: "thread.message-sent",
1326− eventId: EventId.makeUnsafe("evt-empty-5"),
1327+ eventId: EventId.make("evt-empty-5"),
13271328 aggregateKind: "thread",
1328− aggregateId: ThreadId.makeUnsafe("thread-empty"),
1329+ aggregateId: ThreadId.make("thread-empty"),
13291330 occurredAt: now,
1330− commandId: CommandId.makeUnsafe("cmd-empty-5"),
1331+ commandId: CommandId.make("cmd-empty-5"),
13311332 causationEventId: null,
1332− correlationId: CorrelationId.makeUnsafe("cmd-empty-5"),
1333+ correlationId: CorrelationId.make("cmd-empty-5"),
13331334 metadata: {},
13341335 payload: {
1335− threadId: ThreadId.makeUnsafe("thread-empty"),
1336− messageId: MessageId.makeUnsafe("assistant-empty"),
1336+ threadId: ThreadId.make("thread-empty"),
1337+ messageId: MessageId.make("assistant-empty"),
13371338 role: "assistant",
13381339 text: "",
13391340 turnId: null,
@@ -1372,16 +1373,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 32 unmodified lines
13721373
13731374 yield* appendAndProject({
13741375 type: "project.created",
1375− eventId: EventId.makeUnsafe("evt-conflict-1"),
1376+ eventId: EventId.make("evt-conflict-1"),
13761377 aggregateKind: "project",
1377− aggregateId: ProjectId.makeUnsafe("project-conflict"),
1378+ aggregateId: ProjectId.make("project-conflict"),
13781379 occurredAt: "2026-02-26T13:00:00.000Z",
1379− commandId: CommandId.makeUnsafe("cmd-conflict-1"),
1380+ commandId: CommandId.make("cmd-conflict-1"),
13801381 causationEventId: null,
1381− correlationId: CorrelationId.makeUnsafe("cmd-conflict-1"),
1382+ correlationId: CorrelationId.make("cmd-conflict-1"),
13821383 metadata: {},
13831384 payload: {
1384− projectId: ProjectId.makeUnsafe("project-conflict"),
1385+ projectId: ProjectId.make("project-conflict"),
13851386 title: "Project Conflict",
13861387 workspaceRoot: "/tmp/project-conflict",
13871388 defaultModelSelection: null,
@@ -1393,17 +1394,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
13931394
13941395 yield* appendAndProject({
13951396 type: "thread.created",
1396− eventId: EventId.makeUnsafe("evt-conflict-2"),
1397+ eventId: EventId.make("evt-conflict-2"),
13971398 aggregateKind: "thread",
1398− aggregateId: ThreadId.makeUnsafe("thread-conflict"),
1399+ aggregateId: ThreadId.make("thread-conflict"),
13991400 occurredAt: "2026-02-26T13:00:01.000Z",
1400− commandId: CommandId.makeUnsafe("cmd-conflict-2"),
1401+ commandId: CommandId.make("cmd-conflict-2"),
14011402 causationEventId: null,
1402− correlationId: CorrelationId.makeUnsafe("cmd-conflict-2"),
1403+ correlationId: CorrelationId.make("cmd-conflict-2"),
14031404 metadata: {},
14041405 payload: {
1405− threadId: ThreadId.makeUnsafe("thread-conflict"),
1406− projectId: ProjectId.makeUnsafe("project-conflict"),
1406+ threadId: ThreadId.make("thread-conflict"),
1407+ projectId: ProjectId.make("project-conflict"),
14071408 title: "Thread Conflict",
14081409 modelSelection: {
14091410 provider: "codex",
@@ -1419,37 +1420,37 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
14191420
14201421 yield* appendAndProject({
14211422 type: "thread.turn-interrupt-requested",
1422− eventId: EventId.makeUnsafe("evt-conflict-3"),
1423+ eventId: EventId.make("evt-conflict-3"),
14231424 aggregateKind: "thread",
1424− aggregateId: ThreadId.makeUnsafe("thread-conflict"),
1425+ aggregateId: ThreadId.make("thread-conflict"),
14251426 occurredAt: "2026-02-26T13:00:02.000Z",
1426− commandId: CommandId.makeUnsafe("cmd-conflict-3"),
1427+ commandId: CommandId.make("cmd-conflict-3"),
14271428 causationEventId: null,
1428− correlationId: CorrelationId.makeUnsafe("cmd-conflict-3"),
1429+ correlationId: CorrelationId.make("cmd-conflict-3"),
14291430 metadata: {},
14301431 payload: {
1431− threadId: ThreadId.makeUnsafe("thread-conflict"),
1432− turnId: TurnId.makeUnsafe("turn-interrupted"),
1432+ threadId: ThreadId.make("thread-conflict"),
1433+ turnId: TurnId.make("turn-interrupted"),
14331434 createdAt: "2026-02-26T13:00:02.000Z",
14341435 },
14351436 });
14361437
14371438 yield* appendAndProject({
14381439 type: "thread.message-sent",
1439− eventId: EventId.makeUnsafe("evt-conflict-4"),
1440+ eventId: EventId.make("evt-conflict-4"),
14401441 aggregateKind: "thread",
1441− aggregateId: ThreadId.makeUnsafe("thread-conflict"),
1442+ aggregateId: ThreadId.make("thread-conflict"),
14421443 occurredAt: "2026-02-26T13:00:03.000Z",
1443− commandId: CommandId.makeUnsafe("cmd-conflict-4"),
1444+ commandId: CommandId.make("cmd-conflict-4"),
14441445 causationEventId: null,
1445− correlationId: CorrelationId.makeUnsafe("cmd-conflict-4"),
1446+ correlationId: CorrelationId.make("cmd-conflict-4"),
14461447 metadata: {},
14471448 payload: {
1448− threadId: ThreadId.makeUnsafe("thread-conflict"),
1449− messageId: MessageId.makeUnsafe("assistant-conflict"),
1449+ threadId: ThreadId.make("thread-conflict"),
1450+ messageId: MessageId.make("assistant-conflict"),
14501451 role: "assistant",
14511452 text: "done",
1452− turnId: TurnId.makeUnsafe("turn-completed"),
1453+ turnId: TurnId.make("turn-completed"),
14531454 streaming: false,
14541455 createdAt: "2026-02-26T13:00:03.000Z",
14551456 updatedAt: "2026-02-26T13:00:03.000Z",
@@ -1458,22 +1459,22 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 2 unmodified lines
14581459
14591460 yield* appendAndProject({
14601461 type: "thread.turn-diff-completed",
1461− eventId: EventId.makeUnsafe("evt-conflict-5"),
1462+ eventId: EventId.make("evt-conflict-5"),
14621463 aggregateKind: "thread",
1463− aggregateId: ThreadId.makeUnsafe("thread-conflict"),
1464+ aggregateId: ThreadId.make("thread-conflict"),
14641465 occurredAt: "2026-02-26T13:00:04.000Z",
1465− commandId: CommandId.makeUnsafe("cmd-conflict-5"),
1466+ commandId: CommandId.make("cmd-conflict-5"),
14661467 causationEventId: null,
1467− correlationId: CorrelationId.makeUnsafe("cmd-conflict-5"),
1468+ correlationId: CorrelationId.make("cmd-conflict-5"),
14681469 metadata: {},
14691470 payload: {
1470− threadId: ThreadId.makeUnsafe("thread-conflict"),
1471− turnId: TurnId.makeUnsafe("turn-completed"),
1471+ threadId: ThreadId.make("thread-conflict"),
1472+ turnId: TurnId.make("turn-completed"),
14721473 checkpointTurnCount: 1,
1473− checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-conflict/turn/1"),
1474+ checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-conflict/turn/1"),
14741475 status: "ready",
14751476 files: [],
1476− assistantMessageId: MessageId.makeUnsafe("assistant-conflict"),
1477+ assistantMessageId: MessageId.make("assistant-conflict"),
14771478 completedAt: "2026-02-26T13:00:04.000Z",
14781479 },
14791480 });
@@ -1516,16 +1517,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 36 unmodified lines
15161517
15171518 yield* appendAndProject({
15181519 type: "project.created",
1519− eventId: EventId.makeUnsafe("evt-revert-1"),
1520+ eventId: EventId.make("evt-revert-1"),
15201521 aggregateKind: "project",
1521− aggregateId: ProjectId.makeUnsafe("project-revert"),
1522+ aggregateId: ProjectId.make("project-revert"),
15221523 occurredAt: "2026-02-26T12:00:00.000Z",
1523− commandId: CommandId.makeUnsafe("cmd-revert-1"),
1524+ commandId: CommandId.make("cmd-revert-1"),
15241525 causationEventId: null,
1525− correlationId: CorrelationId.makeUnsafe("cmd-revert-1"),
1526+ correlationId: CorrelationId.make("cmd-revert-1"),
15261527 metadata: {},
15271528 payload: {
1528− projectId: ProjectId.makeUnsafe("project-revert"),
1529+ projectId: ProjectId.make("project-revert"),
15291530 title: "Project Revert",
15301531 workspaceRoot: "/tmp/project-revert",
15311532 defaultModelSelection: null,
@@ -1537,17 +1538,17 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 5 unmodified lines
15371538
15381539 yield* appendAndProject({
15391540 type: "thread.created",
1540− eventId: EventId.makeUnsafe("evt-revert-2"),
1541+ eventId: EventId.make("evt-revert-2"),
15411542 aggregateKind: "thread",
1542− aggregateId: ThreadId.makeUnsafe("thread-revert"),
1543+ aggregateId: ThreadId.make("thread-revert"),
15431544 occurredAt: "2026-02-26T12:00:01.000Z",
1544− commandId: CommandId.makeUnsafe("cmd-revert-2"),
1545+ commandId: CommandId.make("cmd-revert-2"),
15451546 causationEventId: null,
1546− correlationId: CorrelationId.makeUnsafe("cmd-revert-2"),
1547+ correlationId: CorrelationId.make("cmd-revert-2"),
15471548 metadata: {},
15481549 payload: {
1549− threadId: ThreadId.makeUnsafe("thread-revert"),
1550− projectId: ProjectId.makeUnsafe("project-revert"),
1550+ threadId: ThreadId.make("thread-revert"),
1551+ projectId: ProjectId.make("project-revert"),
15511552 title: "Thread Revert",
15521553 modelSelection: {
15531554 provider: "codex",
@@ -1563,42 +1564,42 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 9 unmodified lines
15631564
15641565 yield* appendAndProject({
15651566 type: "thread.turn-diff-completed",
1566− eventId: EventId.makeUnsafe("evt-revert-3"),
1567+ eventId: EventId.make("evt-revert-3"),
15671568 aggregateKind: "thread",
1568− aggregateId: ThreadId.makeUnsafe("thread-revert"),
1569+ aggregateId: ThreadId.make("thread-revert"),
15691570 occurredAt: "2026-02-26T12:00:02.000Z",
1570− commandId: CommandId.makeUnsafe("cmd-revert-3"),
1571+ commandId: CommandId.make("cmd-revert-3"),
15711572 causationEventId: null,
1572− correlationId: CorrelationId.makeUnsafe("cmd-revert-3"),
1573+ correlationId: CorrelationId.make("cmd-revert-3"),
15731574 metadata: {},
15741575 payload: {
1575− threadId: ThreadId.makeUnsafe("thread-revert"),
1576− turnId: TurnId.makeUnsafe("turn-1"),
1576+ threadId: ThreadId.make("thread-revert"),
1577+ turnId: TurnId.make("turn-1"),
15771578 checkpointTurnCount: 1,
1578− checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/1"),
1579+ checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/1"),
15791580 status: "ready",
15801581 files: [],
1581− assistantMessageId: MessageId.makeUnsafe("assistant-keep"),
1582+ assistantMessageId: MessageId.make("assistant-keep"),
15821583 completedAt: "2026-02-26T12:00:02.000Z",
15831584 },
15841585 });
15851586
15861587 yield* appendAndProject({
15871588 type: "thread.message-sent",
1588− eventId: EventId.makeUnsafe("evt-revert-4"),
1589+ eventId: EventId.make("evt-revert-4"),
15891590 aggregateKind: "thread",
1590− aggregateId: ThreadId.makeUnsafe("thread-revert"),
1591+ aggregateId: ThreadId.make("thread-revert"),
15911592 occurredAt: "2026-02-26T12:00:02.100Z",
1592− commandId: CommandId.makeUnsafe("cmd-revert-4"),
1593+ commandId: CommandId.make("cmd-revert-4"),
15931594 causationEventId: null,
1594− correlationId: CorrelationId.makeUnsafe("cmd-revert-4"),
1595+ correlationId: CorrelationId.make("cmd-revert-4"),
15951596 metadata: {},
15961597 payload: {
1597− threadId: ThreadId.makeUnsafe("thread-revert"),
1598− messageId: MessageId.makeUnsafe("assistant-keep"),
1598+ threadId: ThreadId.make("thread-revert"),
1599+ messageId: MessageId.make("assistant-keep"),
15991600 role: "assistant",
16001601 text: "kept",
1601− turnId: TurnId.makeUnsafe("turn-1"),
1602+ turnId: TurnId.make("turn-1"),
16021603 streaming: false,
16031604 createdAt: "2026-02-26T12:00:02.100Z",
16041605 updatedAt: "2026-02-26T12:00:02.100Z",
@@ -1607,42 +1608,42 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 2 unmodified lines
16071608
16081609 yield* appendAndProject({
16091610 type: "thread.turn-diff-completed",
1610− eventId: EventId.makeUnsafe("evt-revert-5"),
1611+ eventId: EventId.make("evt-revert-5"),
16111612 aggregateKind: "thread",
1612− aggregateId: ThreadId.makeUnsafe("thread-revert"),
1613+ aggregateId: ThreadId.make("thread-revert"),
16131614 occurredAt: "2026-02-26T12:00:03.000Z",
1614− commandId: CommandId.makeUnsafe("cmd-revert-5"),
1615+ commandId: CommandId.make("cmd-revert-5"),
16151616 causationEventId: null,
1616− correlationId: CorrelationId.makeUnsafe("cmd-revert-5"),
1617+ correlationId: CorrelationId.make("cmd-revert-5"),
16171618 metadata: {},
16181619 payload: {
1619− threadId: ThreadId.makeUnsafe("thread-revert"),
1620− turnId: TurnId.makeUnsafe("turn-2"),
1620+ threadId: ThreadId.make("thread-revert"),
1621+ turnId: TurnId.make("turn-2"),
16211622 checkpointTurnCount: 2,
1622− checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/2"),
1623+ checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/2"),
16231624 status: "ready",
16241625 files: [],
1625− assistantMessageId: MessageId.makeUnsafe("assistant-remove"),
1626+ assistantMessageId: MessageId.make("assistant-remove"),
16261627 completedAt: "2026-02-26T12:00:03.000Z",
16271628 },
16281629 });
16291630
16301631 yield* appendAndProject({
16311632 type: "thread.message-sent",
1632− eventId: EventId.makeUnsafe("evt-revert-6"),
1633+ eventId: EventId.make("evt-revert-6"),
16331634 aggregateKind: "thread",
1634− aggregateId: ThreadId.makeUnsafe("thread-revert"),
1635+ aggregateId: ThreadId.make("thread-revert"),
16351636 occurredAt: "2026-02-26T12:00:03.050Z",
1636− commandId: CommandId.makeUnsafe("cmd-revert-6"),
1637+ commandId: CommandId.make("cmd-revert-6"),
16371638 causationEventId: null,
1638− correlationId: CorrelationId.makeUnsafe("cmd-revert-6"),
1639+ correlationId: CorrelationId.make("cmd-revert-6"),
16391640 metadata: {},
16401641 payload: {
1641− threadId: ThreadId.makeUnsafe("thread-revert"),
1642− messageId: MessageId.makeUnsafe("user-remove"),
1642+ threadId: ThreadId.make("thread-revert"),
1643+ messageId: MessageId.make("user-remove"),
16431644 role: "user",
16441645 text: "removed",
1645− turnId: TurnId.makeUnsafe("turn-2"),
1646+ turnId: TurnId.make("turn-2"),
16461647 streaming: false,
16471648 createdAt: "2026-02-26T12:00:03.050Z",
16481649 updatedAt: "2026-02-26T12:00:03.050Z",
@@ -1651,20 +1652,20 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 2 unmodified lines
16511652
16521653 yield* appendAndProject({
16531654 type: "thread.message-sent",
1654− eventId: EventId.makeUnsafe("evt-revert-7"),
1655+ eventId: EventId.make("evt-revert-7"),
16551656 aggregateKind: "thread",
1656− aggregateId: ThreadId.makeUnsafe("thread-revert"),
1657+ aggregateId: ThreadId.make("thread-revert"),
16571658 occurredAt: "2026-02-26T12:00:03.100Z",
1658− commandId: CommandId.makeUnsafe("cmd-revert-7"),
1659+ commandId: CommandId.make("cmd-revert-7"),
16591660 causationEventId: null,
1660− correlationId: CorrelationId.makeUnsafe("cmd-revert-7"),
1661+ correlationId: CorrelationId.make("cmd-revert-7"),
16611662 metadata: {},
16621663 payload: {
1663− threadId: ThreadId.makeUnsafe("thread-revert"),
1664− messageId: MessageId.makeUnsafe("assistant-remove"),
1664+ threadId: ThreadId.make("thread-revert"),
1665+ messageId: MessageId.make("assistant-remove"),
16651666 role: "assistant",
16661667 text: "removed",
1667− turnId: TurnId.makeUnsafe("turn-2"),
1668+ turnId: TurnId.make("turn-2"),
16681669 streaming: false,
16691670 createdAt: "2026-02-26T12:00:03.100Z",
16701671 updatedAt: "2026-02-26T12:00:03.100Z",
@@ -1673,16 +1674,16 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { · 2 unmodified lines
16731674
16741675 yield* appendAndProject({
16751676 type: "thread.reverted",
1676− eventId: EventId.makeUnsafe("evt-revert-8"),
1677+ eventId: EventId.make("evt-revert-8"),
16771678 aggregateKind: "thread",
1678− aggregateId: ThreadId.makeUnsafe("thread-revert"),
1679+ aggregateId: ThreadId.make("thread-revert"),
16791680 occurredAt: "2026-02-26T12:00:04.000Z",
1680− commandId: CommandId.makeUnsafe("cmd-revert-8"),
1681+ commandId: CommandId.make("cmd-revert-8"),
16811682 causationEventId: null,
1682− correlationId: CorrelationId.makeUnsafe("cmd-revert-8"),
1683+ correlationId: CorrelationId.make("cmd-revert-8"),
16831684 metadata: {},
16841685 payload: {
1685− threadId: ThreadId.makeUnsafe("thread-revert"),
1686+ threadId: ThreadId.make("thread-revert"),
16861687 turnCount: 1,
16871688 },
16881689 });
@@ -1724,10 +1725,10 @@ it.effect("restores pending turn-start metadata across projection pipeline resta · 35 unmodified lines
17241725 Layer.provideMerge(persistenceLayer),
17251726 );
17261727
1727− const threadId = ThreadId.makeUnsafe("thread-restart");
1728− const turnId = TurnId.makeUnsafe("turn-restart");
1729− const messageId = MessageId.makeUnsafe("message-restart");
1730− const sourcePlanThreadId = ThreadId.makeUnsafe("thread-plan-source");
1728+ const threadId = ThreadId.make("thread-restart");
1729+ const turnId = TurnId.make("turn-restart");
1730+ const messageId = MessageId.make("message-restart");
1731+ const sourcePlanThreadId = ThreadId.make("thread-plan-source");
17311732 const sourcePlanId = "plan-source";
17321733 const turnStartedAt = "2026-02-26T14:00:00.000Z";
17331734 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
17381739
17391740 yield* eventStore.append({
17401741 type: "thread.turn-start-requested",
1741− eventId: EventId.makeUnsafe("evt-restart-1"),
1742+ eventId: EventId.make("evt-restart-1"),
17421743 aggregateKind: "thread",
17431744 aggregateId: threadId,
17441745 occurredAt: turnStartedAt,
1745− commandId: CommandId.makeUnsafe("cmd-restart-1"),
1746+ commandId: CommandId.make("cmd-restart-1"),
17461747 causationEventId: null,
1747− correlationId: CorrelationId.makeUnsafe("cmd-restart-1"),
1748+ correlationId: CorrelationId.make("cmd-restart-1"),
17481749 metadata: {},
17491750 payload: {
17501751 threadId,
@@ -1768,13 +1769,13 @@ it.effect("restores pending turn-start metadata across projection pipeline resta · 17 unmodified lines
17681769
17691770 yield* eventStore.append({
17701771 type: "thread.session-set",
1771− eventId: EventId.makeUnsafe("evt-restart-2"),
1772+ eventId: EventId.make("evt-restart-2"),
17721773 aggregateKind: "thread",
17731774 aggregateId: threadId,
17741775 occurredAt: sessionSetAt,
1775− commandId: CommandId.makeUnsafe("cmd-restart-2"),
1776+ commandId: CommandId.make("cmd-restart-2"),
17761777 causationEventId: null,
1777− correlationId: CorrelationId.makeUnsafe("cmd-restart-2"),
1778+ correlationId: CorrelationId.make("cmd-restart-2"),
17781779 metadata: {},
17791780 payload: {
17801781 threadId,
@@ -1846,6 +1847,7 @@ const engineLayer = it.layer( · 65 unmodified lines
18461847 Layer.provide(OrchestrationProjectionPipelineLive),
18471848 Layer.provide(OrchestrationEventStoreLive),
18481849 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
1850+ Layer.provide(RepositoryIdentityResolverLive),
18491851 Layer.provideMerge(SqlitePersistenceMemory),
18501852 Layer.provideMerge(
18511853 ServerConfig.layerTest(process.cwd(), {
@@ -1865,8 +1867,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { · 13 unmodified lines
18651867
18661868 yield* engine.dispatch({
18671869 type: "project.create",
1868− commandId: CommandId.makeUnsafe("cmd-live-project"),
1869− projectId: ProjectId.makeUnsafe("project-live"),
1870+ commandId: CommandId.make("cmd-live-project"),
1871+ projectId: ProjectId.make("project-live"),
18701872 title: "Live Project",
18711873 workspaceRoot: "/tmp/project-live",
18721874 defaultModelSelection: {
@@ -1903,8 +1905,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { · 30 unmodified lines
19031905
19041906 yield* engine.dispatch({
19051907 type: "project.create",
1906− commandId: CommandId.makeUnsafe("cmd-scripts-project-create"),
1907− projectId: ProjectId.makeUnsafe("project-scripts"),
1908+ commandId: CommandId.make("cmd-scripts-project-create"),
1909+ projectId: ProjectId.make("project-scripts"),
19081910 title: "Scripts Project",
19091911 workspaceRoot: "/tmp/project-scripts",
19101912 defaultModelSelection: {
@@ -1916,8 +1918,8 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { · 5 unmodified lines
19161918
19171919 yield* engine.dispatch({
19181920 type: "project.meta.update",
1919− commandId: CommandId.makeUnsafe("cmd-scripts-project-update"),
1920− projectId: ProjectId.makeUnsafe("project-scripts"),
1921+ commandId: CommandId.make("cmd-scripts-project-update"),
1922+ projectId: ProjectId.make("project-scripts"),
19211923 scripts: [
19221924 {
19231925 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
8686 return null;
8787 }
8888 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;
9090 }
9191
9292 function retainProjectionMessagesAfterRevert(
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+18−13
@@ -4,18 +4,22 @@ import { Effect, Layer } from "effect"; · 3 unmodified lines
44 import * as SqlClient from "effect/unstable/sql/SqlClient";
55
66 import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
7+import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
78 import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
89 import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
910 import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
1011
11−const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
12−const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
13−const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
14−const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
15−const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
12+const asProjectId = (value: string): ProjectId => ProjectId.make(value);
13+const asTurnId = (value: string): TurnId => TurnId.make(value);
14+const asMessageId = (value: string): MessageId => MessageId.make(value);
15+const asEventId = (value: string): EventId => EventId.make(value);
16+const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
1617
1718 const projectionSnapshotLayer = it.layer(
18− OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
19+ OrchestrationProjectionSnapshotQueryLive.pipe(
20+ Layer.provideMerge(RepositoryIdentityResolverLive),
21+ Layer.provideMerge(SqlitePersistenceMemory),
22+ ),
1923 );
2024
2125 projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
@@ -234,6 +238,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 212 unmodified lines
234238 id: asProjectId("project-1"),
235239 title: "Project 1",
236240 workspaceRoot: "/tmp/project-1",
241+ repositoryIdentity: null,
237242 defaultModelSelection: {
238243 provider: "codex",
239244 model: "gpt-5-codex",
@@ -254,7 +259,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 14 unmodified lines
254259 ]);
255260 assert.deepEqual(snapshot.threads, [
256261 {
257− id: ThreadId.makeUnsafe("thread-1"),
262+ id: ThreadId.make("thread-1"),
258263 projectId: asProjectId("project-1"),
259264 title: "Thread 1",
260265 modelSelection: {
@@ -273,7 +278,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 12 unmodified lines
273278 completedAt: "2026-02-24T00:00:08.000Z",
274279 assistantMessageId: asMessageId("message-1"),
275280 sourceProposedPlan: {
276− threadId: ThreadId.makeUnsafe("thread-1"),
281+ threadId: ThreadId.make("thread-1"),
277282 planId: "plan-1",
278283 },
279284 },
@@ -298,7 +303,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 18 unmodified lines
298303 turnId: asTurnId("turn-1"),
299304 planMarkdown: "# Ship it",
300305 implementedAt: "2026-02-24T00:00:05.500Z",
301− implementationThreadId: ThreadId.makeUnsafe("thread-2"),
306+ implementationThreadId: ThreadId.make("thread-2"),
302307 createdAt: "2026-02-24T00:00:05.000Z",
303308 updatedAt: "2026-02-24T00:00:05.500Z",
304309 },
@@ -326,7 +331,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 21 unmodified lines
326331 },
327332 ],
328333 session: {
329− threadId: ThreadId.makeUnsafe("thread-1"),
334+ threadId: ThreadId.make("thread-1"),
330335 status: "running",
331336 providerName: "codex",
332337 runtimeMode: "approval-required",
@@ -468,7 +473,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 135 unmodified lines
468473 );
469474 assert.equal(firstThreadId._tag, "Some");
470475 if (firstThreadId._tag === "Some") {
471− assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first"));
476+ assert.equal(firstThreadId.value, ThreadId.make("thread-first"));
472477 }
473478 }),
474479 );
@@ -591,12 +596,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { · 116 unmodified lines
591596 `;
592597
593598 const context = yield* snapshotQuery.getThreadCheckpointContext(
594− ThreadId.makeUnsafe("thread-context"),
599+ ThreadId.make("thread-context"),
595600 );
596601 assert.equal(context._tag, "Some");
597602 if (context._tag === "Some") {
598603 assert.deepEqual(context.value, {
599− threadId: ThreadId.makeUnsafe("thread-context"),
604+ threadId: ThreadId.make("thread-context"),
600605 projectId: asProjectId("project-context"),
601606 workspaceRoot: "/tmp/context-workspace",
602607 worktreePath: "/tmp/context-worktree",
apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+279−259
@@ -6,7 +6,6 @@ import { · 5 unmodified lines
66 OrchestrationCheckpointFile,
77 OrchestrationProposedPlanId,
88 OrchestrationReadModel,
9− OrchestrationThreadActivity,
109 ProjectScript,
1110 TurnId,
1211 type OrchestrationCheckpointSummary,
@@ -16,6 +15,7 @@ import { · 3 unmodified lines
1615 type OrchestrationProject,
1716 type OrchestrationSession,
1817 type OrchestrationThread,
18+ type OrchestrationThreadActivity,
1919 ModelSelection,
2020 ProjectId,
2121 ThreadId,
@@ -38,6 +38,7 @@ import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionTh · 16 unmodified lines
3838 import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
3939 import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
4040 import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
41+import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIdentityResolver.ts";
4142 import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
4243 import {
4344 ProjectionSnapshotQuery,
@@ -163,6 +164,8 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st · 119 unmodified lines
163164
164165 const makeProjectionSnapshotQuery = Effect.gen(function* () {
165166 const sql = yield* SqlClient.SqlClient;
167+ const repositoryIdentityResolver = yield* RepositoryIdentityResolver;
168+ const repositoryIdentityResolutionConcurrency = 4;
166169
167170 const listProjectRows = SqlSchema.findAll({
168171 Request: Schema.Void,
@@ -436,271 +439,283 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { · 267 unmodified lines
436439 const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
437440 sql
438441 .withTransaction(
439− Effect.gen(function* () {
440− const [
441− projectRows,
442− threadRows,
443− messageRows,
444− proposedPlanRows,
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− ),
442+ Effect.all([
443+ listProjectRows(undefined).pipe(
444+ Effect.mapError(
445+ toPersistenceSqlOrDecodeError(
446+ "ProjectionSnapshotQuery.getSnapshot:listProjects:query",
447+ "ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows",
465448 ),
466449 ),
467− listThreadMessageRows(undefined).pipe(
468− Effect.mapError(
469− toPersistenceSqlOrDecodeError(
470− "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query",
471− "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows",
472− ),
450+ ),
451+ listThreadRows(undefined).pipe(
452+ Effect.mapError(
453+ toPersistenceSqlOrDecodeError(
454+ "ProjectionSnapshotQuery.getSnapshot:listThreads:query",
455+ "ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows",
473456 ),
474457 ),
475− listThreadProposedPlanRows(undefined).pipe(
476− Effect.mapError(
477− toPersistenceSqlOrDecodeError(
478− "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query",
479− "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows",
480− ),
458+ ),
459+ listThreadMessageRows(undefined).pipe(
460+ Effect.mapError(
461+ toPersistenceSqlOrDecodeError(
462+ "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query",
463+ "ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows",
481464 ),
482465 ),
483− listThreadActivityRows(undefined).pipe(
484− Effect.mapError(
485− toPersistenceSqlOrDecodeError(
486− "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query",
487− "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows",
488− ),
466+ ),
467+ listThreadProposedPlanRows(undefined).pipe(
468+ Effect.mapError(
469+ toPersistenceSqlOrDecodeError(
470+ "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query",
471+ "ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows",
489472 ),
490473 ),
491− listThreadSessionRows(undefined).pipe(
492− Effect.mapError(
493− toPersistenceSqlOrDecodeError(
494− "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query",
495− "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows",
496− ),
474+ ),
475+ listThreadActivityRows(undefined).pipe(
476+ Effect.mapError(
477+ toPersistenceSqlOrDecodeError(
478+ "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query",
479+ "ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows",
497480 ),
498481 ),
499− listCheckpointRows(undefined).pipe(
500− Effect.mapError(
501− toPersistenceSqlOrDecodeError(
502− "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query",
503− "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows",
504− ),
482+ ),
483+ listThreadSessionRows(undefined).pipe(
484+ Effect.mapError(
485+ toPersistenceSqlOrDecodeError(
486+ "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query",
487+ "ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows",
505488 ),
506489 ),
507− listLatestTurnRows(undefined).pipe(
508− Effect.mapError(
509− toPersistenceSqlOrDecodeError(
510− "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
511− "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
512− ),
490+ ),
491+ listCheckpointRows(undefined).pipe(
492+ Effect.mapError(
493+ toPersistenceSqlOrDecodeError(
494+ "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query",
495+ "ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows",
513496 ),
514497 ),
515− listProjectionStateRows(undefined).pipe(
516− Effect.mapError(
517− toPersistenceSqlOrDecodeError(
518− "ProjectionSnapshotQuery.getSnapshot:listProjectionState:query",
519− "ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows",
520− ),
498+ ),
499+ listLatestTurnRows(undefined).pipe(
500+ Effect.mapError(
501+ toPersistenceSqlOrDecodeError(
502+ "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query",
503+ "ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows",
521504 ),
522505 ),
523− ]);
524−
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(
506+ ),
507+ listProjectionStateRows(undefined).pipe(
697508 Effect.mapError(
698− toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),
509+ toPersistenceSqlOrDecodeError(
510+ "ProjectionSnapshotQuery.getSnapshot:listProjectionState:query",
511+ "ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows",
512+ ),
699513 ),
700− );
701− }),
514+ ),
515+ ]),
702516 )
703517 .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+ ),
704719 Effect.mapError((error) => {
705720 if (isPersistenceError(error)) {
706721 return error;
@@ -734,19 +749,24 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { · 27 unmodified lines
734749 "ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow",
735750 ),
736751 ),
737− Effect.map(
738− Option.map(
739− (row): OrchestrationProject => ({
740− id: row.projectId,
741− title: row.title,
742− workspaceRoot: row.workspaceRoot,
743− defaultModelSelection: row.defaultModelSelection,
744− scripts: row.scripts,
745− createdAt: row.createdAt,
746− updatedAt: row.updatedAt,
747− deletedAt: row.deletedAt,
748− }),
749− ),
752+ Effect.flatMap((option) =>
753+ Option.isNone(option)
754+ ? Effect.succeed(Option.none<OrchestrationProject>())
755+ : repositoryIdentityResolver.resolve(option.value.workspaceRoot).pipe(
756+ Effect.map((repositoryIdentity) =>
757+ Option.some({
758+ id: option.value.projectId,
759+ title: option.value.title,
760+ workspaceRoot: option.value.workspaceRoot,
761+ repositoryIdentity,
762+ defaultModelSelection: option.value.defaultModelSelection,
763+ scripts: option.value.scripts,
764+ createdAt: option.value.createdAt,
765+ updatedAt: option.value.updatedAt,
766+ deletedAt: option.value.deletedAt,
767+ } satisfies OrchestrationProject),
768+ ),
769+ ),
750770 ),
751771 );
752772
apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts+143−152
@@ -28,6 +28,7 @@ import { · 27 unmodified lines
2828 } from "../../provider/Services/ProviderService.ts";
2929 import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
3030 import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
31+import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
3132 import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
3233 import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
3334 import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
@@ -37,11 +38,10 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; · 3 unmodified lines
3738 import * as NodeServices from "@effect/platform-node/NodeServices";
3839 import { ServerSettingsService } from "../../serverSettings.ts";
3940
40−const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
41−const asApprovalRequestId = (value: string): ApprovalRequestId =>
42− ApprovalRequestId.makeUnsafe(value);
43−const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
44−const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
41+const asProjectId = (value: string): ProjectId => ProjectId.make(value);
42+const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
43+const asMessageId = (value: string): MessageId => MessageId.make(value);
44+const asTurnId = (value: string): TurnId => TurnId.make(value);
4545
4646 const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
4747 Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
@@ -121,8 +121,8 @@ describe("ProviderCommandReactor", () => { · 73 unmodified lines
121121 input !== null &&
122122 "threadId" in input &&
123123 typeof input.threadId === "string"
124− ? ThreadId.makeUnsafe(input.threadId)
125− : ThreadId.makeUnsafe(`thread-${sessionIndex}`);
124+ ? ThreadId.make(input.threadId)
125+ : ThreadId.make(`thread-${sessionIndex}`);
126126 const session: ProviderSession = {
127127 provider: modelSelection.provider,
128128 status: "ready" as const,
@@ -144,7 +144,7 @@ describe("ProviderCommandReactor", () => { · 15 unmodified lines
144144 });
145145 const sendTurn = vi.fn((_: unknown) =>
146146 Effect.succeed({
147− threadId: ThreadId.makeUnsafe("thread-1"),
147+ threadId: ThreadId.make("thread-1"),
148148 turnId: asTurnId("turn-1"),
149149 }),
150150 );
@@ -208,7 +208,9 @@ describe("ProviderCommandReactor", () => { · 57 unmodified lines
208208 sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
209209 }),
210210 rollbackConversation: () => unsupported(),
211− streamEvents: Stream.fromPubSub(runtimeEventPubSub),
211+ get streamEvents() {
212+ return Stream.fromPubSub(runtimeEventPubSub);
213+ },
212214 };
213215
214216 const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -216,6 +218,7 @@ describe("ProviderCommandReactor", () => { · 1 unmodified line
216218 Layer.provide(OrchestrationProjectionPipelineLive),
217219 Layer.provide(OrchestrationEventStoreLive),
218220 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
221+ Layer.provide(RepositoryIdentityResolverLive),
219222 Layer.provide(SqlitePersistenceMemory),
220223 );
221224 const layer = ProviderCommandReactorLive.pipe(
@@ -243,7 +246,7 @@ describe("ProviderCommandReactor", () => { · 21 unmodified lines
243246 await Effect.runPromise(
244247 engine.dispatch({
245248 type: "project.create",
246− commandId: CommandId.makeUnsafe("cmd-project-create"),
249+ commandId: CommandId.make("cmd-project-create"),
247250 projectId: asProjectId("project-1"),
248251 title: "Provider Project",
249252 workspaceRoot: "/tmp/provider-project",
@@ -254,8 +257,8 @@ describe("ProviderCommandReactor", () => { · 4 unmodified lines
254257 await Effect.runPromise(
255258 engine.dispatch({
256259 type: "thread.create",
257− commandId: CommandId.makeUnsafe("cmd-thread-create"),
258− threadId: ThreadId.makeUnsafe("thread-1"),
260+ commandId: CommandId.make("cmd-thread-create"),
261+ threadId: ThreadId.make("thread-1"),
259262 projectId: asProjectId("project-1"),
260263 title: "Thread",
261264 modelSelection: modelSelection,
@@ -290,8 +293,8 @@ describe("ProviderCommandReactor", () => { · 28 unmodified lines
290293 await Effect.runPromise(
291294 harness.engine.dispatch({
292295 type: "thread.turn.start",
293− commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
294− threadId: ThreadId.makeUnsafe("thread-1"),
296+ commandId: CommandId.make("cmd-turn-start-1"),
297+ threadId: ThreadId.make("thread-1"),
295298 message: {
296299 messageId: asMessageId("user-message-1"),
297300 role: "user",
@@ -306,7 +309,7 @@ describe("ProviderCommandReactor", () => { · 8 unmodified lines
306309
307310 await waitFor(() => harness.startSession.mock.calls.length === 1);
308311 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"));
310313 expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
311314 cwd: "/tmp/provider-project",
312315 modelSelection: {
@@ -317,7 +320,7 @@ describe("ProviderCommandReactor", () => { · 4 unmodified lines
317320 });
318321
319322 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"));
321324 expect(thread?.session?.threadId).toBe("thread-1");
322325 expect(thread?.session?.runtimeMode).toBe("approval-required");
323326 });
@@ -331,8 +334,8 @@ describe("ProviderCommandReactor", () => { · 7 unmodified lines
331334 await Effect.runPromise(
332335 harness.engine.dispatch({
333336 type: "thread.meta.update",
334− commandId: CommandId.makeUnsafe("cmd-thread-title-seed"),
335− threadId: ThreadId.makeUnsafe("thread-1"),
337+ commandId: CommandId.make("cmd-thread-title-seed"),
338+ threadId: ThreadId.make("thread-1"),
336339 title: seededTitle,
337340 }),
338341 );
@@ -340,8 +343,8 @@ describe("ProviderCommandReactor", () => { · 1 unmodified line
340343 await Effect.runPromise(
341344 harness.engine.dispatch({
342345 type: "thread.turn.start",
343− commandId: CommandId.makeUnsafe("cmd-turn-start-title"),
344− threadId: ThreadId.makeUnsafe("thread-1"),
346+ commandId: CommandId.make("cmd-turn-start-title"),
347+ threadId: ThreadId.make("thread-1"),
345348 message: {
346349 messageId: asMessageId("user-message-title"),
347350 role: "user",
@@ -363,12 +366,12 @@ describe("ProviderCommandReactor", () => { · 15 unmodified lines
363366 await waitFor(async () => {
364367 const readModel = await Effect.runPromise(harness.engine.getReadModel());
365368 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 ===
367370 "Generated title"
368371 );
369372 });
370373 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"));
372375 expect(thread?.title).toBe("Generated title");
373376 });
374377
@@ -380,8 +383,8 @@ describe("ProviderCommandReactor", () => { · 5 unmodified lines
380383 await Effect.runPromise(
381384 harness.engine.dispatch({
382385 type: "thread.meta.update",
383− commandId: CommandId.makeUnsafe("cmd-thread-title-custom"),
384− threadId: ThreadId.makeUnsafe("thread-1"),
386+ commandId: CommandId.make("cmd-thread-title-custom"),
387+ threadId: ThreadId.make("thread-1"),
385388 title: "Keep this custom title",
386389 }),
387390 );
@@ -389,8 +392,8 @@ describe("ProviderCommandReactor", () => { · 1 unmodified line
389392 await Effect.runPromise(
390393 harness.engine.dispatch({
391394 type: "thread.turn.start",
392− commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"),
393− threadId: ThreadId.makeUnsafe("thread-1"),
395+ commandId: CommandId.make("cmd-turn-start-title-preserve"),
396+ threadId: ThreadId.make("thread-1"),
394397 message: {
395398 messageId: asMessageId("user-message-title-preserve"),
396399 role: "user",
@@ -408,7 +411,7 @@ describe("ProviderCommandReactor", () => { · 11 unmodified lines
408411 expect(harness.generateThreadTitle).not.toHaveBeenCalled();
409412
410413 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"));
412415 expect(thread?.title).toBe("Keep this custom title");
413416 });
414417
@@ -425,8 +428,8 @@ describe("ProviderCommandReactor", () => { · 10 unmodified lines
425428 await Effect.runPromise(
426429 harness.engine.dispatch({
427430 type: "thread.meta.update",
428− commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"),
429− threadId: ThreadId.makeUnsafe("thread-1"),
431+ commandId: CommandId.make("cmd-thread-title-formatted-seed"),
432+ threadId: ThreadId.make("thread-1"),
430433 title: seededTitle,
431434 }),
432435 );
@@ -434,8 +437,8 @@ describe("ProviderCommandReactor", () => { · 1 unmodified line
434437 await Effect.runPromise(
435438 harness.engine.dispatch({
436439 type: "thread.turn.start",
437− commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"),
438− threadId: ThreadId.makeUnsafe("thread-1"),
440+ commandId: CommandId.make("cmd-turn-start-title-formatted"),
441+ threadId: ThreadId.make("thread-1"),
439442 message: {
440443 messageId: asMessageId("user-message-title-formatted"),
441444 role: "user",
@@ -453,13 +456,13 @@ describe("ProviderCommandReactor", () => { · 11 unmodified lines
453456 await waitFor(async () => {
454457 const readModel = await Effect.runPromise(harness.engine.getReadModel());
455458 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 ===
457460 "Reconnect spinner resume bug"
458461 );
459462 });
460463
461464 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"));
463466 expect(thread?.title).toBe("Reconnect spinner resume bug");
464467 });
465468
@@ -470,8 +473,8 @@ describe("ProviderCommandReactor", () => { · 4 unmodified lines
470473 await Effect.runPromise(
471474 harness.engine.dispatch({
472475 type: "thread.meta.update",
473− commandId: CommandId.makeUnsafe("cmd-thread-branch"),
474− threadId: ThreadId.makeUnsafe("thread-1"),
476+ commandId: CommandId.make("cmd-thread-branch"),
477+ threadId: ThreadId.make("thread-1"),
475478 branch: "t3code/1234abcd",
476479 worktreePath: "/tmp/provider-project-worktree",
477480 }),
@@ -495,8 +498,8 @@ describe("ProviderCommandReactor", () => { · 17 unmodified lines
495498 await Effect.runPromise(
496499 harness.engine.dispatch({
497500 type: "thread.turn.start",
498− commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"),
499− threadId: ThreadId.makeUnsafe("thread-1"),
501+ commandId: CommandId.make("cmd-turn-start-branch-model"),
502+ threadId: ThreadId.make("thread-1"),
500503 message: {
501504 messageId: asMessageId("user-message-branch-model"),
502505 role: "user",
@@ -522,8 +525,8 @@ describe("ProviderCommandReactor", () => { · 19 unmodified lines
522525 await Effect.runPromise(
523526 harness.engine.dispatch({
524527 type: "thread.turn.start",
525− commandId: CommandId.makeUnsafe("cmd-turn-start-fast"),
526− threadId: ThreadId.makeUnsafe("thread-1"),
528+ commandId: CommandId.make("cmd-turn-start-fast"),
529+ threadId: ThreadId.make("thread-1"),
527530 message: {
528531 messageId: asMessageId("user-message-fast"),
529532 role: "user",
@@ -557,7 +560,7 @@ describe("ProviderCommandReactor", () => { · 27 unmodified lines
557560 },
558561 });
559562 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
560− threadId: ThreadId.makeUnsafe("thread-1"),
563+ threadId: ThreadId.make("thread-1"),
561564 modelSelection: {
562565 provider: "codex",
563566 model: "gpt-5.3-codex",
@@ -578,8 +581,8 @@ describe("ProviderCommandReactor", () => { · 14 unmodified lines
578581 await Effect.runPromise(
579582 harness.engine.dispatch({
580583 type: "thread.turn.start",
581− commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
582− threadId: ThreadId.makeUnsafe("thread-1"),
584+ commandId: CommandId.make("cmd-turn-start-claude-effort"),
585+ threadId: ThreadId.make("thread-1"),
583586 message: {
584587 messageId: asMessageId("user-message-claude-effort"),
585588 role: "user",
@@ -611,7 +614,7 @@ describe("ProviderCommandReactor", () => { · 25 unmodified lines
611614 },
612615 });
613616 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
614− threadId: ThreadId.makeUnsafe("thread-1"),
617+ threadId: ThreadId.make("thread-1"),
615618 modelSelection: {
616619 provider: "claudeAgent",
617620 model: "claude-sonnet-4-6",
@@ -631,8 +634,8 @@ describe("ProviderCommandReactor", () => { · 13 unmodified lines
631634 await Effect.runPromise(
632635 harness.engine.dispatch({
633636 type: "thread.turn.start",
634− commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
635− threadId: ThreadId.makeUnsafe("thread-1"),
637+ commandId: CommandId.make("cmd-turn-start-claude-fast-mode"),
638+ threadId: ThreadId.make("thread-1"),
636639 message: {
637640 messageId: asMessageId("user-message-claude-fast-mode"),
638641 role: "user",
@@ -664,7 +667,7 @@ describe("ProviderCommandReactor", () => { · 25 unmodified lines
664667 },
665668 });
666669 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
667− threadId: ThreadId.makeUnsafe("thread-1"),
670+ threadId: ThreadId.make("thread-1"),
668671 modelSelection: {
669672 provider: "claudeAgent",
670673 model: "claude-opus-4-6",
@@ -682,8 +685,8 @@ describe("ProviderCommandReactor", () => { · 11 unmodified lines
682685 await Effect.runPromise(
683686 harness.engine.dispatch({
684687 type: "thread.interaction-mode.set",
685− commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"),
686− threadId: ThreadId.makeUnsafe("thread-1"),
688+ commandId: CommandId.make("cmd-interaction-mode-set-plan"),
689+ threadId: ThreadId.make("thread-1"),
687690 interactionMode: "plan",
688691 createdAt: now,
689692 }),
@@ -692,8 +695,8 @@ describe("ProviderCommandReactor", () => { · 2 unmodified lines
692695 await Effect.runPromise(
693696 harness.engine.dispatch({
694697 type: "thread.turn.start",
695− commandId: CommandId.makeUnsafe("cmd-turn-start-plan"),
696− threadId: ThreadId.makeUnsafe("thread-1"),
698+ commandId: CommandId.make("cmd-turn-start-plan"),
699+ threadId: ThreadId.make("thread-1"),
697700 message: {
698701 messageId: asMessageId("user-message-plan"),
699702 role: "user",
@@ -708,7 +711,7 @@ describe("ProviderCommandReactor", () => { · 8 unmodified lines
708711
709712 await waitFor(() => harness.sendTurn.mock.calls.length === 1);
710713 expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
711− threadId: ThreadId.makeUnsafe("thread-1"),
714+ threadId: ThreadId.make("thread-1"),
712715 interactionMode: "plan",
713716 });
714717 });
@@ -722,8 +725,8 @@ describe("ProviderCommandReactor", () => { · 7 unmodified lines
722725 await Effect.runPromise(
723726 harness.engine.dispatch({
724727 type: "thread.turn.start",
725− commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
726− threadId: ThreadId.makeUnsafe("thread-1"),
728+ commandId: CommandId.make("cmd-turn-start-provider-first"),
729+ threadId: ThreadId.make("thread-1"),
727730 message: {
728731 messageId: asMessageId("user-message-provider-first"),
729732 role: "user",
@@ -742,9 +745,7 @@ describe("ProviderCommandReactor", () => { · 12 unmodified lines
742745
743746 await waitFor(async () => {
744747 const readModel = await Effect.runPromise(harness.engine.getReadModel());
745− const thread = readModel.threads.find(
746− (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
747− );
748+ const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
748749 return (
749750 thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
750751 false
@@ -755,7 +756,7 @@ describe("ProviderCommandReactor", () => { · 4 unmodified lines
755756 expect(harness.sendTurn).not.toHaveBeenCalled();
756757
757758 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"));
759760 expect(thread?.session).toBeNull();
760761 expect(
761762 thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
@@ -774,8 +775,8 @@ describe("ProviderCommandReactor", () => { · 12 unmodified lines
774775 await Effect.runPromise(
775776 harness.engine.dispatch({
776777 type: "thread.turn.start",
777− commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
778− threadId: ThreadId.makeUnsafe("thread-1"),
778+ commandId: CommandId.make("cmd-turn-start-unsupported-1"),
779+ threadId: ThreadId.make("thread-1"),
779780 message: {
780781 messageId: asMessageId("user-message-unsupported-1"),
781782 role: "user",
@@ -793,8 +794,8 @@ describe("ProviderCommandReactor", () => { · 11 unmodified lines
793794 await Effect.runPromise(
794795 harness.engine.dispatch({
795796 type: "thread.turn.start",
796− commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),
797− threadId: ThreadId.makeUnsafe("thread-1"),
797+ commandId: CommandId.make("cmd-turn-start-unsupported-2"),
798+ threadId: ThreadId.make("thread-1"),
798799 message: {
799800 messageId: asMessageId("user-message-unsupported-2"),
800801 role: "user",
@@ -810,7 +811,7 @@ describe("ProviderCommandReactor", () => { · 9 unmodified lines
810811 await waitFor(() => harness.sendTurn.mock.calls.length === 2);
811812
812813 expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
813− threadId: ThreadId.makeUnsafe("thread-1"),
814+ threadId: ThreadId.make("thread-1"),
814815 modelSelection: {
815816 provider: "codex",
816817 model: "gpt-5-codex",
@@ -825,8 +826,8 @@ describe("ProviderCommandReactor", () => { · 8 unmodified lines
825826 await Effect.runPromise(
826827 harness.engine.dispatch({
827828 type: "thread.turn.start",
828− commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),
829− threadId: ThreadId.makeUnsafe("thread-1"),
829+ commandId: CommandId.make("cmd-turn-start-unchanged-1"),
830+ threadId: ThreadId.make("thread-1"),
830831 message: {
831832 messageId: asMessageId("user-message-unchanged-1"),
832833 role: "user",
@@ -845,8 +846,8 @@ describe("ProviderCommandReactor", () => { · 12 unmodified lines
845846 await Effect.runPromise(
846847 harness.engine.dispatch({
847848 type: "thread.turn.start",
848− commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),
849− threadId: ThreadId.makeUnsafe("thread-1"),
849+ commandId: CommandId.make("cmd-turn-start-unchanged-2"),
850+ threadId: ThreadId.make("thread-1"),
850851 message: {
851852 messageId: asMessageId("user-message-unchanged-2"),
852853 role: "user",
@@ -873,8 +874,8 @@ describe("ProviderCommandReactor", () => { · 20 unmodified lines
873874 await Effect.runPromise(
874875 harness.engine.dispatch({
875876 type: "thread.turn.start",
876− commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
877− threadId: ThreadId.makeUnsafe("thread-1"),
877+ commandId: CommandId.make("cmd-turn-start-claude-effort-1"),
878+ threadId: ThreadId.make("thread-1"),
878879 message: {
879880 messageId: asMessageId("user-message-claude-effort-1"),
880881 role: "user",
@@ -900,8 +901,8 @@ describe("ProviderCommandReactor", () => { · 19 unmodified lines
900901 await Effect.runPromise(
901902 harness.engine.dispatch({
902903 type: "thread.turn.start",
903− commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),
904− threadId: ThreadId.makeUnsafe("thread-1"),
904+ commandId: CommandId.make("cmd-turn-start-claude-effort-2"),
905+ threadId: ThreadId.make("thread-1"),
905906 message: {
906907 messageId: asMessageId("user-message-claude-effort-2"),
907908 role: "user",
@@ -942,8 +943,8 @@ describe("ProviderCommandReactor", () => { · 34 unmodified lines
942943 await Effect.runPromise(
943944 harness.engine.dispatch({
944945 type: "thread.runtime-mode.set",
945− commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access"),
946− threadId: ThreadId.makeUnsafe("thread-1"),
946+ commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access"),
947+ threadId: ThreadId.make("thread-1"),
947948 runtimeMode: "full-access",
948949 createdAt: now,
949950 }),
@@ -952,8 +953,8 @@ describe("ProviderCommandReactor", () => { · 2 unmodified lines
952953 await Effect.runPromise(
953954 harness.engine.dispatch({
954955 type: "thread.turn.start",
955− commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),
956− threadId: ThreadId.makeUnsafe("thread-1"),
956+ commandId: CommandId.make("cmd-turn-start-runtime-mode-1"),
957+ threadId: ThreadId.make("thread-1"),
957958 message: {
958959 messageId: asMessageId("user-message-runtime-mode-1"),
959960 role: "user",
@@ -972,8 +973,8 @@ describe("ProviderCommandReactor", () => { · 12 unmodified lines
972973 await Effect.runPromise(
973974 harness.engine.dispatch({
974975 type: "thread.runtime-mode.set",
975− commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-1"),
976− threadId: ThreadId.makeUnsafe("thread-1"),
976+ commandId: CommandId.make("cmd-runtime-mode-set-1"),
977+ threadId: ThreadId.make("thread-1"),
977978 runtimeMode: "approval-required",
978979 createdAt: now,
979980 }),

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