@pi-chamber/web 1.0.7 → 1.0.8-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (265) hide show
  1. package/dist/assets/AgentsSurface-CcWBqAWV.js +1 -0
  2. package/dist/assets/ChoicesArtifact-Kk-qvrSB.js +1 -0
  3. package/dist/assets/DiagramView-DZUBo1uP.js +1 -0
  4. package/dist/assets/{DiffView-BxW6BuOC.js → DiffView-CiZy4jFA.js} +6 -6
  5. package/dist/assets/FileSaveConflictDialog-DZ9NDwOO.js +3 -0
  6. package/dist/assets/FilesView-DqiZ9kw9.js +6 -0
  7. package/dist/assets/GitHubDetailScaffold-DM2DH7o8.js +11 -0
  8. package/dist/assets/GitHubLinkPicker-ChB8NZ1h.js +1 -0
  9. package/dist/assets/GitHubListPrimitives-CibDiJGq.js +1 -0
  10. package/dist/assets/{GitView-DD33ngnM.js → GitView--EaZQrBr.js} +5 -5
  11. package/dist/assets/{IssuesSurface-BAY_eyX5.js → IssuesSurface-CySTpaD1.js} +3 -3
  12. package/dist/assets/{JsonTreeView-DpXbUrAl.js → JsonTreeView-_yMHKKQZ.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cn63lAmn.js → MarkdownRendererImpl-D_-2fQw0.js} +3 -3
  14. package/dist/assets/PatchDiff-bHObDlhD.js +1 -0
  15. package/dist/assets/PierreDiffViewer-UY7Cse-s.js +147 -0
  16. package/dist/assets/PullRequestsSurface-iXy6chwc.js +2 -0
  17. package/dist/assets/{SessionSwitcherContent-CscYekC1.js → SessionSwitcherContent-DJGCa_wN.js} +1 -1
  18. package/dist/assets/SessionSwitcherDropdown-CDOX-5Y2.js +2 -0
  19. package/dist/assets/SessionUnreadDot-Dwc3MdvA.js +1 -0
  20. package/dist/assets/SettingsView-DA-U9lsj.js +11 -0
  21. package/dist/assets/{SettingsWindow-gxjULdm1.js → SettingsWindow-CUg49Mfh.js} +1 -1
  22. package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
  23. package/dist/assets/SubagentsArtifact-DUZX9tDe.js +1 -0
  24. package/dist/assets/ToolOutputDialog-BuZZaRw4.js +8 -0
  25. package/dist/assets/ToolPartDiffPreview-CKncG6i2.js +1 -0
  26. package/dist/assets/{VirtualizedFileDiff-BrbPymTL.js → VirtualizedFileDiff-BGZiLPe_.js} +4 -4
  27. package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
  28. package/dist/assets/VisualFrame-DBZkHFnG.js +22 -0
  29. package/dist/assets/VisualsArtifact-Bq0vMO-i.js +1 -0
  30. package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-Bro9KrfM.js} +1 -1
  31. package/dist/assets/{computeVirtualFileMetrics-G4csGiKs.js → computeVirtualFileMetrics-DJQqK49u.js} +2 -2
  32. package/dist/assets/contextFileOpenGuard-ByWK3Sru.js +1 -0
  33. package/dist/assets/{fileTreeStatus-Bskhj4qT.js → fileTreeStatus-CyJ3TOYD.js} +2 -2
  34. package/dist/assets/gitStatusPredicates-BsXrwngT.js +1 -0
  35. package/dist/assets/githubLink-g2bmC0qi.js +10 -0
  36. package/dist/assets/index-B_L9GVYw.css +1 -0
  37. package/dist/assets/{index-ComwtfT4.js → index-C9rUUQ_Y.js} +1 -1
  38. package/dist/assets/index-CKKWVoND.js +11 -0
  39. package/dist/assets/{main-DoiadX0a.js → main-DT-4_fhe.js} +2 -2
  40. package/dist/assets/main-DsLMU9CT.js +137 -0
  41. package/dist/assets/{markdownCore-DczkEluO.js → markdownCore-QmM_aOnZ.js} +2 -2
  42. package/dist/assets/{miniChat-Ck6MEZ9Q.js → miniChat-BqGslD2z.js} +2 -2
  43. package/dist/assets/{mobile-BucKVm1P.js → mobile-C5JOcDIC.js} +2 -2
  44. package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-DSMsJqXM.js} +1 -1
  45. package/dist/assets/pi-session-focus-preference-Cc_S4zi1.js +9 -0
  46. package/dist/assets/{renderDiffWithHighlighter-PL82AR81.js → renderDiffWithHighlighter-BXhnIAHg.js} +1 -1
  47. package/dist/assets/renderElectronMiniChatApp-CiSkecEE.js +2 -0
  48. package/dist/assets/{renderFileWithHighlighter-CYgfbA4F.js → renderFileWithHighlighter-CK29YZtC.js} +1 -1
  49. package/dist/assets/renderMobileApp-C4JuoxsZ.js +11 -0
  50. package/dist/assets/runtimeEndpointReset-Dwj-jCDS.js +66 -0
  51. package/dist/assets/runtimeSurface-0K7vuUpd.js +1 -0
  52. package/dist/assets/selection-CnYkEsu_.js +1 -0
  53. package/dist/assets/useAppFontEffects-CV5UyTRw.js +226 -0
  54. package/dist/assets/useGitHubRemoteSearch-CgP-zEBj.js +1 -0
  55. package/dist/assets/useSwitcherItems-C8G5F0hs.js +1 -0
  56. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
  57. package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
  58. package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
  59. package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
  60. package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
  61. package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
  85. package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
  86. package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
  87. package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
  88. package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
  89. package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
  90. package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
  91. package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
  92. package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
  93. package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
  94. package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
  95. package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
  96. package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
  97. package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
  98. package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
  99. package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
  100. package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
  101. package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
  102. package/dist/assets/{web-components-CGDpzixf.js → web-components-BpncHjnV.js} +4 -4
  103. package/dist/index.html +4 -4
  104. package/dist/mini-chat.html +3 -3
  105. package/dist/mobile.html +3 -3
  106. package/package.json +2 -1
  107. package/plugins/featured.json +12 -0
  108. package/plugins/registry.json +7 -0
  109. package/plugins/subagents/LICENSE +25 -0
  110. package/plugins/subagents/agents/planner.md +36 -0
  111. package/plugins/subagents/agents/reviewer.md +34 -0
  112. package/plugins/subagents/agents/scout.md +49 -0
  113. package/plugins/subagents/agents/worker.md +23 -0
  114. package/plugins/subagents/extension.js +631 -0
  115. package/plugins/subagents/extension.test.js +295 -0
  116. package/plugins/subagents/package.json +41 -0
  117. package/plugins/visuals/choices.js +168 -0
  118. package/plugins/visuals/extension.js +90 -0
  119. package/plugins/visuals/files.js +74 -0
  120. package/plugins/visuals/package.json +32 -0
  121. package/server/index.js +103 -24
  122. package/server/lib/git/DOCUMENTATION.md +4 -0
  123. package/server/lib/git/service.js +70 -5
  124. package/server/lib/git/service.test.js +179 -0
  125. package/server/lib/github/DOCUMENTATION.md +6 -2
  126. package/server/lib/github/gh-cli.js +35 -9
  127. package/server/lib/github/gh-cli.test.js +122 -0
  128. package/server/lib/marketplace/DOCUMENTATION.md +95 -0
  129. package/server/lib/marketplace/featured.js +176 -0
  130. package/server/lib/marketplace/featured.test.js +207 -0
  131. package/server/lib/marketplace/npm-registry.js +255 -0
  132. package/server/lib/marketplace/npm-registry.test.js +227 -0
  133. package/server/lib/marketplace/routes.js +64 -0
  134. package/server/lib/marketplace/routes.test.js +119 -0
  135. package/server/lib/marketplace/service.js +225 -0
  136. package/server/lib/marketplace/service.test.js +174 -0
  137. package/server/lib/notifications/DOCUMENTATION.md +10 -4
  138. package/server/lib/notifications/pi-notification-watcher.js +95 -33
  139. package/server/lib/notifications/pi-notification-watcher.test.js +89 -0
  140. package/server/lib/open-url/DOCUMENTATION.md +2 -1
  141. package/server/lib/pi/extension-protocol.js +54 -0
  142. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
  143. package/server/lib/pi/merged-event-stream.js +316 -0
  144. package/server/lib/pi/merged-event-stream.test.js +95 -0
  145. package/server/lib/pi/routes-daemon-pool.test.js +348 -0
  146. package/server/lib/pi/routes-extension-events.test.js +115 -0
  147. package/server/lib/pi/routes-merged-events.test.js +327 -0
  148. package/server/lib/pi/routes-sandbox.test.js +1684 -0
  149. package/server/lib/pi/routes.js +790 -87
  150. package/server/lib/pi/routes.test.js +381 -1
  151. package/server/lib/pi/sandbox/DOCUMENTATION.md +68 -0
  152. package/server/lib/pi/sandbox/launcher.js +122 -0
  153. package/server/lib/pi/sandbox/launcher.test.js +91 -0
  154. package/server/lib/pi/sandbox/nono-launcher.js +455 -0
  155. package/server/lib/pi/sandbox/nono-launcher.test.js +371 -0
  156. package/server/lib/pi/sandbox/nono-profile-macos.json +20 -0
  157. package/server/lib/pi/sandbox/nono-profile-wsl2.json +21 -0
  158. package/server/lib/pi/sandbox/nono-profile.json +22 -0
  159. package/server/lib/pi/sandbox/project-sandbox-manager.js +1461 -0
  160. package/server/lib/pi/sandbox/project-sandbox-setting.js +166 -0
  161. package/server/lib/pi/sandbox/project-sandbox.js +207 -0
  162. package/server/lib/pi/sandbox/sandbox-routes.js +110 -0
  163. package/server/lib/pi/sandbox/sandboxed-folders.js +100 -0
  164. package/server/lib/pi/sandbox/sandboxed-folders.test.js +65 -0
  165. package/server/lib/pi/sandbox/trust-ask.js +135 -0
  166. package/server/lib/pi/sandbox/trust-ask.test.js +54 -0
  167. package/server/lib/pi/sandbox/worktree-ids.js +96 -0
  168. package/server/lib/pi/sandbox/worktree-ids.test.js +73 -0
  169. package/server/lib/pi/session-daemon/DOCUMENTATION.md +47 -10
  170. package/server/lib/pi/session-daemon/daemon-pool.js +157 -0
  171. package/server/lib/pi/session-daemon/daemon-process.js +10 -1
  172. package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
  173. package/server/lib/pi/session-daemon/extension-config.js +902 -0
  174. package/server/lib/pi/session-daemon/extension-config.test.js +798 -0
  175. package/server/lib/pi/session-daemon/extension-controls.js +177 -0
  176. package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
  177. package/server/lib/pi/session-daemon/extension-name.js +6 -0
  178. package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
  179. package/server/lib/pi/session-daemon/extension-palette.js +146 -0
  180. package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
  181. package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
  182. package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
  183. package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
  184. package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
  185. package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
  186. package/server/lib/pi/session-daemon/plugin-host.js +245 -0
  187. package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
  188. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
  189. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
  190. package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
  191. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
  192. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
  193. package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
  194. package/server/lib/pi/session-daemon/session-daemon-read-persisted.test.js +167 -0
  195. package/server/lib/pi/session-daemon/session-daemon.js +927 -108
  196. package/server/lib/pi/session-daemon/session-daemon.test.js +391 -4
  197. package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
  198. package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
  199. package/server/lib/pi/session-daemon/session-idle-residency.test.js +98 -1
  200. package/server/lib/pi/session-daemon/session-jsonl.js +49 -10
  201. package/server/lib/pi/session-daemon/session-jsonl.test.js +11 -0
  202. package/server/lib/pi/session-daemon/session-lease.js +93 -15
  203. package/server/lib/pi/session-daemon/session-lease.test.js +107 -1
  204. package/server/lib/pi/session-daemon/supervisor-launcher-stop.test.js +295 -0
  205. package/server/lib/pi/session-daemon/supervisor-sandbox-nono.e2e.test.js +301 -0
  206. package/server/lib/pi/session-daemon/supervisor-sandbox.test.js +444 -0
  207. package/server/lib/pi/session-daemon/supervisor.js +408 -38
  208. package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
  209. package/server/lib/pi/settings-store.js +14 -0
  210. package/server/lib/pi/settings-store.test.js +11 -0
  211. package/server/lib/pi/ui-settings-store.js +88 -2
  212. package/server/lib/pi/ui-settings-store.test.js +118 -0
  213. package/server/lib/plugins/DOCUMENTATION.md +198 -0
  214. package/server/lib/plugins/daemon-sync.js +88 -0
  215. package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
  216. package/server/lib/plugins/daemon-sync.test.js +108 -0
  217. package/server/lib/plugins/impact.js +139 -0
  218. package/server/lib/plugins/impact.test.js +83 -0
  219. package/server/lib/plugins/manifest.js +220 -0
  220. package/server/lib/plugins/manifest.test.js +127 -0
  221. package/server/lib/plugins/registry.js +59 -0
  222. package/server/lib/plugins/routes.js +92 -0
  223. package/server/lib/plugins/routes.test.js +247 -0
  224. package/server/lib/plugins/service.js +183 -0
  225. package/server/lib/plugins/store.js +261 -0
  226. package/server/lib/plugins/store.test.js +188 -0
  227. package/server/lib/plugins/visuals-extension.test.js +237 -0
  228. package/server/lib/server/cross-process-lock.js +28 -3
  229. package/server/lib/server-browser/DOCUMENTATION.md +32 -7
  230. package/server/lib/server-browser/browser-tab.js +4 -1
  231. package/server/lib/server-browser/downloads.js +261 -34
  232. package/server/lib/server-browser/downloads.test.js +171 -0
  233. package/server/lib/server-browser/runtime.integration.test.js +47 -0
  234. package/server/lib/server-browser/runtime.js +16 -0
  235. package/server/lib/server-browser/server-browser.js +25 -6
  236. package/server/lib/tunnels/executable-search.js +5 -1
  237. package/server/lib/tunnels/executable-search.test.js +26 -0
  238. package/dist/assets/DiagramView-BB-aZobi.js +0 -1
  239. package/dist/assets/FileSaveConflictDialog-Bzz8FNMq.js +0 -3
  240. package/dist/assets/FilesView-DECxN8Z0.js +0 -6
  241. package/dist/assets/GitHubDetailScaffold-CWsWycRd.js +0 -11
  242. package/dist/assets/GitHubLinkPicker-BVYdg_e8.js +0 -1
  243. package/dist/assets/GitHubListPrimitives-Dlv3tC4d.js +0 -1
  244. package/dist/assets/PatchDiff-BklyOEHs.js +0 -1
  245. package/dist/assets/PierreDiffViewer-wc6cB6qw.js +0 -147
  246. package/dist/assets/PullRequestsSurface-BZvJkT1I.js +0 -2
  247. package/dist/assets/SessionSwitcherDropdown-DShvvGwC.js +0 -2
  248. package/dist/assets/SessionUnreadDot-CbqRq6h_.js +0 -1
  249. package/dist/assets/SettingsView-DcF-At5E.js +0 -6
  250. package/dist/assets/ToolOutputDialog-DdMIfrnK.js +0 -8
  251. package/dist/assets/ToolPartDiffPreview-C6Sm4eVf.js +0 -1
  252. package/dist/assets/contextFileOpenGuard-UU86YHgI.js +0 -1
  253. package/dist/assets/gitStatusPredicates-DQEO4Psc.js +0 -1
  254. package/dist/assets/githubLink-ByPAyFjh.js +0 -10
  255. package/dist/assets/index-BaLCg7tL.css +0 -1
  256. package/dist/assets/index-I2QYqABE.js +0 -11
  257. package/dist/assets/main-DyFfbllq.js +0 -137
  258. package/dist/assets/pi-session-focus-preference-Dx0UXPoO.js +0 -9
  259. package/dist/assets/renderElectronMiniChatApp-Cb7s7dWl.js +0 -2
  260. package/dist/assets/renderMobileApp-Bp74b_Lo.js +0 -11
  261. package/dist/assets/runtimeEndpointReset-7nWYnKd4.js +0 -62
  262. package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
  263. package/dist/assets/useAppFontEffects-ZTyNwFk6.js +0 -213
  264. package/dist/assets/useGitHubRemoteSearch-BF3ohpsh.js +0 -1
  265. package/dist/assets/useSwitcherItems-BJzwyDGX.js +0 -1
@@ -0,0 +1,1684 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import express from 'express';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { readFileSync } from 'node:fs';
5
+ import { mkdir, mkdtemp, readFile, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises';
6
+ import { tmpdir } from 'node:os';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
9
+
10
+ import { registerPiRuntimeRoutes } from './routes.js';
11
+ import { createPiDaemonPool, publicDaemonStreamId } from './session-daemon/daemon-pool.js';
12
+ import { createPiUiSettingsStore } from './ui-settings-store.js';
13
+ import { createProjectSandboxManager } from './sandbox/project-sandbox-manager.js';
14
+ import { createTrustAskStore } from './sandbox/trust-ask.js';
15
+ import { sandboxedFoldersFile } from './sandbox/sandboxed-folders.js';
16
+ import { ownWorktreeId, worktreeIdsFile } from './sandbox/worktree-ids.js';
17
+ import { getPiSessionDirectory } from './session-daemon/session-jsonl.js';
18
+
19
+ const listen = (app) => new Promise((resolve, reject) => {
20
+ const server = app.listen(0, '127.0.0.1', () => resolve(server));
21
+ server.once('error', reject);
22
+ });
23
+
24
+ const close = (server) => new Promise((resolve) => {
25
+ if (!server) return resolve();
26
+ server.closeAllConnections?.();
27
+ server.close(() => resolve());
28
+ });
29
+
30
+ // A fake daemon records every command it receives and answers from a table
31
+ // keyed by command name (a function receives the payload).
32
+ const fakeDaemon = (name, answers = {}) => {
33
+ const calls = [];
34
+ const subscriptions = [];
35
+ return {
36
+ name,
37
+ calls,
38
+ subscriptions,
39
+ commands: () => calls.map((call) => call.command),
40
+ // Event stream: each subscription is recorded; `emit` writes a frame to
41
+ // every open one.
42
+ subscribe: async (options) => {
43
+ const record = { options, closed: false };
44
+ subscriptions.push(record);
45
+ return () => { record.closed = true; };
46
+ },
47
+ emit: (event, sequence, payload) => {
48
+ for (const record of subscriptions.filter((item) => !item.closed)) {
49
+ record.options.onEvent({ protocolVersion: 1, kind: 'event', event, sequence, streamEpoch: `epoch-${name}`, payload });
50
+ }
51
+ },
52
+ request: async (command, payload) => {
53
+ calls.push({ command, payload });
54
+ const answer = answers[command];
55
+ if (answer instanceof Error) throw answer;
56
+ if (typeof answer === 'function') return answer(payload);
57
+ if (answer !== undefined) return answer;
58
+ return {};
59
+ },
60
+ };
61
+ };
62
+
63
+ const daemonError = (code) => Object.assign(new Error(code), { code });
64
+
65
+ const session = (id, directory) => ({ id, directory, createdAt: 1, updatedAt: 2 });
66
+ const detail = (id, directory) => ({ session: session(id, directory), messages: [], lastSequence: 0 });
67
+ const row = (id, directory) => ({ session: session(id, directory), updatedAt: 2 });
68
+
69
+ const daemonAnswers = (extra = {}) => ({
70
+ 'sessions.open': (p) => detail(p.sessionId, p.directory),
71
+ 'sessions.readPersisted': (p) => ({ ...detail(p.sessionId, p.directory), lastSequence: -1, isStreaming: false, lifecycle: 'idle', readOnly: true }),
72
+ 'sessions.create': (p) => detail('s-new', p.cwd),
73
+ 'sessions.list': (p) => ({ sessions: [row('s-1', p.directory)] }),
74
+ 'sessions.prompt': {},
75
+ 'providers.hosts': { hosts: ['api.anthropic.com'] },
76
+ 'runtime.health': { state: 'ready', residentSessions: 1 },
77
+ 'sessions.release': { released: [], pending: [] },
78
+ ...extra,
79
+ });
80
+
81
+ // The launcher seam: a probe result and a record of what was launched.
82
+ const fakeLauncher = (probe = { available: true, version: '0.82.0', capabilities: ['landlock-abi-6'] }) => {
83
+ const launcher = {
84
+ id: 'nono',
85
+ probes: 0,
86
+ probeResult: probe,
87
+ probe: async () => {
88
+ launcher.probes += 1;
89
+ return launcher.probeResult;
90
+ },
91
+ // The profile seam of the nono launcher: a built-in text, and a custom
92
+ // one that replaces it. Text holding `nope` is what nono refuses.
93
+ customProfile: null,
94
+ profile: async () => (launcher.customProfile === null
95
+ ? { hostKind: 'linux', builtInPath: '/app/nono-profile.json', customPath: '/data/custom.json', custom: false, path: '/app/nono-profile.json', content: '{"built":"in"}', hash: 'built-in' }
96
+ : { hostKind: 'linux', builtInPath: '/app/nono-profile.json', customPath: '/data/custom.json', custom: true, path: '/data/custom.json', content: launcher.customProfile, hash: `custom:${launcher.customProfile}` }),
97
+ saveProfile: async (content) => {
98
+ if (typeof content !== 'string' || content.includes('nope')) {
99
+ throw Object.assign(new Error('invalid'), { code: 'INVALID_SANDBOX_PROFILE', messages: ['Group nope not found'] });
100
+ }
101
+ launcher.customProfile = content;
102
+ },
103
+ resetProfile: async () => {
104
+ launcher.customProfile = null;
105
+ },
106
+ };
107
+ return launcher;
108
+ };
109
+
110
+ // Transcript reads (session detail and older pages) are answered read-only
111
+ // from JSONL while the sandbox cannot run; see the fail-closed tests.
112
+ const PI_RUNNING = [
113
+ ['GET', '/api/pi/sessions/s-1/tree?directory=DIR'],
114
+ ['POST', '/api/pi/sessions', { cwd: 'DIR' }],
115
+ ['POST', '/api/pi/sessions/s-1/prompt', { directory: 'DIR', text: 'hi', streamEpoch: 'epoch-1' }],
116
+ ['POST', '/api/pi/sessions/s-1/steer', { directory: 'DIR', text: 'hi', streamEpoch: 'epoch-1' }],
117
+ ['POST', '/api/pi/sessions/s-1/follow-up', { directory: 'DIR', text: 'hi', streamEpoch: 'epoch-1' }],
118
+ ['POST', '/api/pi/sessions/s-1/bash', { directory: 'DIR', command: 'ls' }],
119
+ ['POST', '/api/pi/sessions/s-1/navigate', { directory: 'DIR', messageId: 'm-1' }],
120
+ ['POST', '/api/pi/sessions/s-1/fork', { directory: 'DIR', messageId: 'm-1' }],
121
+ ['POST', '/api/pi/sessions/s-1/compact', { directory: 'DIR' }],
122
+ ['POST', '/api/pi/sessions/s-1/model', { directory: 'DIR', providerId: 'p', modelId: 'm' }],
123
+ ['POST', '/api/pi/sessions/s-1/thinking', { directory: 'DIR', level: 'low' }],
124
+ ['POST', '/api/pi/extensions/respond', { requestId: 'r-1', directory: 'DIR', cancelled: true }],
125
+ ['GET', '/api/pi/resources?directory=DIR'],
126
+ ['POST', '/api/pi/extensions/control', { sessionId: 's-1', id: 'mode', directory: 'DIR' }],
127
+ ['POST', '/api/pi/sessions/s-1/discard-draft?directory=DIR'],
128
+ ['GET', '/api/pi/extensions/config?directory=DIR'],
129
+ ];
130
+
131
+ const buildSandboxRoutes = async ({ probe, mainAnswers = {}, sandboxAnswers = {}, startError, onStart, idleStopMs = 60_000, agentFiles = {}, beforeReconcile, supervisorOptions } = {}) => {
132
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-routes-sandbox-'));
133
+ const dataDir = join(root, 'data');
134
+ const agentDir = join(root, 'agent');
135
+ const projectA = join(root, 'code', 'a');
136
+ const projectB = join(root, 'code', 'b');
137
+ const gitId = 'f'.repeat(40);
138
+ const worktree = join(dataDir, 'worktree', gitId, 'feature');
139
+ await Promise.all([
140
+ mkdir(join(projectA, '.git'), { recursive: true }),
141
+ mkdir(projectB, { recursive: true }),
142
+ mkdir(worktree, { recursive: true }),
143
+ mkdir(agentDir, { recursive: true }),
144
+ ]);
145
+ await writeFile(join(projectA, '.git', 'pichamber'), gitId);
146
+ const uiSettingsStore = createPiUiSettingsStore({ file: join(dataDir, 'settings.json') });
147
+ await uiSettingsStore.write({ projects: [{ id: 'proj-a', path: projectA }, { id: 'proj-b', path: projectB }] });
148
+
149
+ const main = fakeDaemon('main', daemonAnswers(mainAnswers));
150
+ const pool = createPiDaemonPool({ getMainRuntime: () => main });
151
+ const launcher = fakeLauncher(probe);
152
+ const launched = [];
153
+ const intakes = [];
154
+ const trustAsk = createTrustAskStore({ dataDir });
155
+ let clock = 0;
156
+ const timers = [];
157
+ const manager = createProjectSandboxManager({
158
+ daemonPool: pool,
159
+ uiSettingsStore,
160
+ launcher,
161
+ dataDir,
162
+ agentDir,
163
+ getServerPort: () => 3000,
164
+ readRoots: ['/opt/node'],
165
+ now: () => clock,
166
+ setInterval: (fn) => { timers.push(fn); return timers.length; },
167
+ clearInterval: () => {},
168
+ idleStopMs,
169
+ trustAsk,
170
+ ...(supervisorOptions ? { supervisorOptions } : {}),
171
+ createIntake: ({ socketPath, publish }) => {
172
+ const intake = { socketPath, publish, started: false, stopped: false };
173
+ intakes.push(intake);
174
+ return {
175
+ start: async () => { intake.started = true; return true; },
176
+ stop: async () => { intake.stopped = true; },
177
+ };
178
+ },
179
+ createSupervisor: async ({ sandbox, launcher: used, ...options }) => {
180
+ const probed = await used.probe();
181
+ if (!probed.available) throw Object.assign(daemonError('SANDBOX_UNAVAILABLE'), { reason: probed.code });
182
+ const daemon = fakeDaemon(`sandbox-${launched.length}`, daemonAnswers(sandboxAnswers));
183
+ daemon.sandbox = sandbox;
184
+ daemon.options = options;
185
+ daemon.stopped = false;
186
+ daemon.paths = { openUrlSocket: join(root, 'run', `${launched.length}`, 'open-url.sock') };
187
+ daemon.start = async () => {
188
+ if (startError) throw daemonError(startError);
189
+ await onStart?.(daemon);
190
+ };
191
+ daemon.stop = async () => { daemon.stopped = true; };
192
+ launched.push(daemon);
193
+ return daemon;
194
+ },
195
+ });
196
+ await beforeReconcile?.({ trustAsk, projectA, projectB });
197
+ await manager.reconcile();
198
+
199
+ const app = express();
200
+ app.use(express.json());
201
+ registerPiRuntimeRoutes(app, {
202
+ daemonPool: pool,
203
+ sandboxManager: manager,
204
+ uiSettingsStore,
205
+ trustAsk,
206
+ archiveStore: { read: async () => ({}), set: async () => undefined },
207
+ });
208
+ const server = await listen(app);
209
+ const base = `http://127.0.0.1:${server.address().port}`;
210
+ const call = (path, init) => fetch(`${base}${path}`, init?.body
211
+ ? { ...init, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(init.body) }
212
+ : init);
213
+ const sandboxOn = (projectId = 'proj-a', setting = {}) => call(`/api/pi/sandbox/projects/${projectId}`, {
214
+ method: 'PUT',
215
+ body: { mode: 'nono', allowHosts: [], allowLocalPorts: [], extraFolders: [], ...setting },
216
+ });
217
+ const tick = async (ms) => {
218
+ clock += ms;
219
+ for (const timer of timers) await timer();
220
+ };
221
+ const moves = [];
222
+ pool.onMove((sessionId, directory) => moves.push([sessionId, directory]));
223
+ return { server, manager, root, dataDir, agentDir, projectA, projectB, worktree, gitId, main, pool, launcher, launched, intakes, call, sandboxOn, tick, uiSettingsStore, moves, trustAsk };
224
+ };
225
+
226
+
227
+ describe('Pi routes for sandboxed projects', () => {
228
+ let server;
229
+ let manager;
230
+ afterEach(async () => {
231
+ await manager?.stop();
232
+ manager = undefined;
233
+ await close(server);
234
+ server = undefined;
235
+ });
236
+
237
+ const setup = async (options = {}) => {
238
+ const built = await buildSandboxRoutes(options);
239
+ server = built.server;
240
+ manager = built.manager;
241
+ return built;
242
+ };
243
+
244
+ it('changes nothing while no project is sandboxed', async () => {
245
+ const ctx = await setup();
246
+ const response = await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
247
+ expect((await response.json()).session).toEqual(session('s-1', ctx.projectA));
248
+ expect(ctx.main.commands()).toEqual(['sessions.open']);
249
+ expect(ctx.launched).toEqual([]);
250
+ expect(ctx.launcher.probes).toBe(0);
251
+ });
252
+
253
+ it('starts a sandboxed project\'s own daemon on first use and routes the project and its worktrees there', async () => {
254
+ const ctx = await setup();
255
+ const saved = await ctx.sandboxOn('proj-a', {
256
+ allowHosts: ['registry.npmjs.org'],
257
+ allowLocalPorts: [8080],
258
+ extraFolders: [{ path: join(ctx.root, 'docs'), access: 'read' }],
259
+ });
260
+ expect(saved.status).toBe(200);
261
+ expect(await saved.json()).toEqual({
262
+ project: {
263
+ projectId: 'proj-a',
264
+ mode: 'nono',
265
+ launcher: 'nono',
266
+ availability: { state: 'available' },
267
+ choice: 'nono',
268
+ allowHosts: ['registry.npmjs.org'],
269
+ allowLocalPorts: [8080],
270
+ extraFolders: [{ path: join(ctx.root, 'docs'), access: 'read' }],
271
+ },
272
+ });
273
+ // Saving starts nothing; the first Pi command does.
274
+ expect(ctx.launched).toEqual([]);
275
+
276
+ const opened = await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
277
+ expect((await opened.json()).session).toEqual({ ...session('s-1', ctx.projectA), sandboxed: true });
278
+ await ctx.call(`/api/pi/sessions/s-2?directory=${ctx.worktree}`);
279
+ await ctx.call(`/api/pi/sessions/s-3?directory=${ctx.projectB}`);
280
+
281
+ expect(ctx.launched).toHaveLength(1);
282
+ const [daemon] = ctx.launched;
283
+ expect(daemon.calls.map((c) => c.payload?.sessionId)).toEqual(['s-1', 's-2']);
284
+ expect(ctx.main.calls.filter((c) => c.command === 'sessions.open').map((c) => c.payload.sessionId)).toEqual(['s-3']);
285
+
286
+ // Grants come from the project, its existing worktrees and its extras;
287
+ // the network allows the signed-in providers' hosts plus the project's.
288
+ const { grants, network, leaseAgentDir } = daemon.sandbox;
289
+ expect(grants).toEqual(expect.arrayContaining([
290
+ { kind: 'readWrite', path: ctx.projectA },
291
+ { kind: 'readWrite', path: join(ctx.dataDir, 'worktree', ctx.gitId) },
292
+ { kind: 'readWrite', path: getPiSessionDirectory({ cwd: ctx.worktree, agentDir: ctx.agentDir }) },
293
+ { kind: 'read', path: join(ctx.root, 'docs') },
294
+ ]));
295
+ expect(network).toEqual({ mode: 'proxy', allowHosts: ['api.anthropic.com', 'registry.npmjs.org'], allowLocalPorts: [8080] });
296
+ expect(leaseAgentDir).toBe(ctx.agentDir);
297
+
298
+ // Its own Open request intake, publishing through that daemon.
299
+ expect(ctx.intakes).toHaveLength(1);
300
+ expect(ctx.intakes[0]).toMatchObject({ socketPath: daemon.paths.openUrlSocket, started: true });
301
+ await ctx.intakes[0].publish({ url: 'https://example.test' });
302
+ expect(daemon.calls.at(-1)).toEqual({ command: 'openUrl.publish', payload: { url: 'https://example.test' } });
303
+ });
304
+
305
+ it('routes composer controls, draft discards and project extension config to the sandbox, and gives it only its own folders\' plugin config', async () => {
306
+ const configResult = { project: { available: true, trusted: true }, packages: [], extensions: [], installFailures: [] };
307
+ const ctx = await setup({
308
+ supervisorOptions: ({ roots } = {}) => ({ port: 3000, roots }),
309
+ mainAnswers: { 'extensions.config.set': configResult, 'extensions.packages.remove': configResult },
310
+ sandboxAnswers: { 'extensions.control': { ran: true }, 'sessions.discardDraft': { discarded: true }, 'extensions.config.list': configResult, 'extensions.config.set': configResult },
311
+ });
312
+ await ctx.sandboxOn();
313
+
314
+ // A draft has no transcript yet, so the folder the client names decides.
315
+ const control = await ctx.call('/api/pi/extensions/control', { method: 'POST', body: { sessionId: 's-draft', id: 'mode', value: 'fast', directory: ctx.projectA } });
316
+ expect(await control.json()).toEqual({ ran: true });
317
+ const discarded = await ctx.call(`/api/pi/sessions/s-draft/discard-draft?directory=${ctx.projectA}`, { method: 'POST' });
318
+ expect(await discarded.json()).toEqual({ discarded: true });
319
+ expect((await ctx.call(`/api/pi/extensions/config?directory=${ctx.projectA}`)).status).toBe(200);
320
+ const id = 'a'.repeat(43);
321
+ const projectSet = await ctx.call(`/api/pi/extensions/config/${id}`, { method: 'PUT', body: { scope: 'project', state: 'unload', directory: ctx.projectA } });
322
+ expect(projectSet.status).toBe(200);
323
+ // Pi's agent folder is read-only in a sandbox: global choices and package
324
+ // removal stay with the main daemon.
325
+ const globalSet = await ctx.call(`/api/pi/extensions/config/${id}`, { method: 'PUT', body: { scope: 'global', enabled: false, directory: ctx.projectA } });
326
+ expect(globalSet.status).toBe(200);
327
+ expect((await ctx.call(`/api/pi/extensions/packages/${id}?directory=${ctx.projectA}`, { method: 'DELETE' })).status).toBe(200);
328
+
329
+ expect(ctx.launched).toHaveLength(1);
330
+ const [daemon] = ctx.launched;
331
+ expect(daemon.commands()).toEqual(['extensions.control', 'sessions.discardDraft', 'extensions.config.list', 'extensions.config.set']);
332
+ expect(daemon.calls[0].payload).toEqual({ sessionId: 's-draft', id: 'mode', value: 'fast' });
333
+ expect(ctx.main.commands().filter((command) => command.startsWith('extensions.') || command === 'sessions.discardDraft'))
334
+ .toEqual(['extensions.config.set', 'extensions.packages.remove']);
335
+ // Per-daemon options (the plugin config) are built for the folders the
336
+ // daemon owns.
337
+ expect(daemon.options.port).toBe(3000);
338
+ expect(daemon.options.roots).toEqual(expect.arrayContaining([ctx.projectA, join(ctx.dataDir, 'worktree', ctx.gitId)]));
339
+ expect(daemon.options.roots.some((root) => root.startsWith(ctx.projectB))).toBe(false);
340
+ });
341
+
342
+ it('marks sandboxed sessions in lists, details and creation, and leaves other projects\' rows unchanged', async () => {
343
+ const ctx = await setup();
344
+ await ctx.sandboxOn();
345
+ const listA = await (await ctx.call(`/api/pi/sessions?directory=${ctx.projectA}`)).json();
346
+ const listB = await (await ctx.call(`/api/pi/sessions?directory=${ctx.projectB}`)).json();
347
+ const created = await (await ctx.call('/api/pi/sessions', { method: 'POST', body: { cwd: ctx.projectA } })).json();
348
+ expect(listA.sessions[0].session.sandboxed).toBe(true);
349
+ expect(listB.sessions[0].session).toEqual(session('s-1', ctx.projectB));
350
+ expect(created.session.sandboxed).toBe(true);
351
+ });
352
+
353
+ it('keeps routing a session by its transcript after the file was first found, and follows it when it is gone', async () => {
354
+ const ctx = await setup({ probe: { available: false, code: 'NOT_INSTALLED' } });
355
+ await ctx.sandboxOn();
356
+ const sessions = getPiSessionDirectory({ cwd: ctx.projectA, agentDir: ctx.agentDir });
357
+ await mkdir(sessions, { recursive: true });
358
+ const file = join(sessions, '2026-01-01_s-9.jsonl');
359
+ await writeFile(file, `${JSON.stringify({ type: 'session', id: 's-9', cwd: ctx.projectA, timestamp: '2026-01-01T00:00:00.000Z' })}\n`);
360
+ for (let attempt = 0; attempt < 2; attempt += 1) {
361
+ expect((await ctx.call('/api/pi/sessions/s-9/tree')).status).toBe(503);
362
+ }
363
+ // The file now holds another session: s-9 has no transcript, so the
364
+ // request's own folder decides.
365
+ await writeFile(file, `${JSON.stringify({ type: 'session', id: 's-other', cwd: ctx.projectA, timestamp: '2026-01-01T00:00:00.000Z' })}\n`);
366
+ expect(ctx.main.commands()).not.toContain('sessions.tree');
367
+ await ctx.call(`/api/pi/sessions/s-9/tree?directory=${ctx.projectB}`);
368
+ expect(ctx.main.commands().filter((command) => command === 'sessions.tree')).toHaveLength(1);
369
+ await rm(file);
370
+ await ctx.call(`/api/pi/sessions/s-9/tree?directory=${ctx.projectB}`);
371
+ expect(ctx.main.commands().filter((command) => command === 'sessions.tree')).toHaveLength(2);
372
+ });
373
+
374
+ it('fails closed: an unavailable launcher answers SANDBOX_UNAVAILABLE for every Pi-running command and never uses the main daemon', async () => {
375
+ const ctx = await setup({
376
+ probe: { available: false, code: 'NO_LANDLOCK' },
377
+ mainAnswers: {
378
+ 'sessions.list': (p) => ({
379
+ sessions: [{ ...row('s-1', p.directory), live: { lifecycle: 'idle', sequence: 3 }, inputState: { pending: null, sequence: 3 } }],
380
+ streamEpoch: 'epoch-main',
381
+ }),
382
+ },
383
+ });
384
+ const saved = await ctx.sandboxOn();
385
+ expect(await saved.json()).toMatchObject({ project: { mode: 'nono', availability: { state: 'unavailable', reason: 'NO_LANDLOCK' } } });
386
+
387
+ for (const [method, path, body] of PI_RUNNING) {
388
+ const response = await ctx.call(path.replace('DIR', ctx.projectA), {
389
+ method,
390
+ ...(body ? { body: JSON.parse(JSON.stringify(body).replace('DIR', ctx.projectA)) } : {}),
391
+ });
392
+ expect([path, response.status]).toEqual([path, 503]);
393
+ expect(await response.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'NO_LANDLOCK' } });
394
+ }
395
+ expect(ctx.launched).toEqual([]);
396
+ // Asking main to release the project's folders runs no Pi code.
397
+ expect(ctx.main.calls.filter((c) => !['sessions.list', 'sessions.release'].includes(c.command))).toEqual([]);
398
+
399
+ // Transcripts stay readable: main reads the JSONL and starts no runtime.
400
+ for (const path of ['/api/pi/sessions/s-1', '/api/pi/sessions/s-1/messages']) {
401
+ const read = await ctx.call(`${path}?directory=${ctx.projectA}`);
402
+ expect([path, read.status]).toEqual([path, 200]);
403
+ const body = await read.json();
404
+ // Metadata only: no epoch or input state, the project's stream named,
405
+ // and the row still sandboxed (a send fails with SANDBOX_UNAVAILABLE).
406
+ expect(body).toMatchObject({ readOnly: true, readOnlyReason: 'NO_LANDLOCK', lastSequence: -1, lifecycle: 'idle', session: { id: 's-1' } });
407
+ if (path === '/api/pi/sessions/s-1') expect(body.session.sandboxed).toBe(true);
408
+ expect(body.stream).toBe(publicDaemonStreamId('sandbox:proj-a'));
409
+ expect(body).not.toHaveProperty('streamEpoch');
410
+ expect(body).not.toHaveProperty('inputState');
411
+ }
412
+ expect(ctx.main.commands()).not.toContain('sessions.open');
413
+ expect(ctx.main.commands()).not.toContain('sessions.messages');
414
+ expect(ctx.main.calls.filter((c) => c.command === 'sessions.readPersisted').map((c) => c.payload))
415
+ .toEqual([{ sessionId: 's-1', directory: ctx.projectA }, { sessionId: 's-1', directory: ctx.projectA }]);
416
+
417
+ // Listing still works: it reads transcripts on disk and runs no Pi code.
418
+ const list = await ctx.call(`/api/pi/sessions?directory=${ctx.projectA}`);
419
+ expect(list.status).toBe(200);
420
+ // The list names the project's stream but carries no epoch and no live
421
+ // state (both are the main daemon's), so clients commit its rows as
422
+ // metadata only. A row says sandboxed: opening it runs in the sandbox
423
+ // or fails with SANDBOX_UNAVAILABLE, never on the main daemon.
424
+ const listed = await list.json();
425
+ expect(typeof listed.stream).toBe('string');
426
+ expect(listed.stream).not.toBe('main');
427
+ expect(listed.streamEpoch).toBeUndefined();
428
+ expect(listed.sessions).toEqual([{ session: { ...session('s-1', ctx.projectA), sandboxed: true }, updatedAt: 2 }]);
429
+ });
430
+
431
+ it('fails closed with the launch failure code when the sandbox daemon cannot start', async () => {
432
+ const ctx = await setup({ startError: 'DAEMON_START_TIMEOUT' });
433
+ await ctx.sandboxOn();
434
+ const response = await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: ctx.projectA, text: 'hi', streamEpoch: 'epoch-1' } });
435
+ expect(response.status).toBe(503);
436
+ expect(await response.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'DAEMON_START_TIMEOUT' } });
437
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
438
+ expect(ctx.intakes[0].stopped).toBe(true);
439
+ const projects = await (await ctx.call('/api/pi/sandbox/projects')).json();
440
+ expect(projects.projects.find((p) => p.projectId === 'proj-a').availability)
441
+ .toEqual({ state: 'unavailable', reason: 'DAEMON_START_TIMEOUT' });
442
+ });
443
+
444
+ it('routes a session command without a directory by the transcript\'s folder, so it cannot reach the main daemon', async () => {
445
+ // Main finds a directory-less read's transcript itself and answers with
446
+ // the session's own folder.
447
+ let sessionFolder;
448
+ const ctx = await setup({
449
+ probe: { available: false, code: 'NOT_INSTALLED' },
450
+ mainAnswers: { 'sessions.readPersisted': (p) => ({ ...detail(p.sessionId, p.directory ?? sessionFolder), lastSequence: -1, readOnly: true }) },
451
+ });
452
+ sessionFolder = ctx.projectA;
453
+ await ctx.sandboxOn();
454
+ const sessions = getPiSessionDirectory({ cwd: ctx.projectA, agentDir: ctx.agentDir });
455
+ await mkdir(sessions, { recursive: true });
456
+ await writeFile(join(sessions, '2026-01-01_s-9.jsonl'), `${JSON.stringify({ type: 'session', id: 's-9', cwd: ctx.projectA, timestamp: '2026-01-01T00:00:00.000Z' })}\n`);
457
+
458
+ const response = await ctx.call('/api/pi/sessions/s-9/tree');
459
+ expect(response.status).toBe(503);
460
+ expect(await response.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'NOT_INSTALLED' } });
461
+ expect(ctx.main.commands()).toEqual(['sessions.release']);
462
+
463
+ // A read of it is answered from its transcript, stamped with the
464
+ // project's stream.
465
+ const read = await ctx.call('/api/pi/sessions/s-9');
466
+ expect(read.status).toBe(200);
467
+ expect(await read.json()).toMatchObject({ readOnly: true, stream: publicDaemonStreamId('sandbox:proj-a') });
468
+ expect(ctx.main.commands()).toEqual(['sessions.release', 'sessions.readPersisted']);
469
+ });
470
+
471
+ it('routes by the transcript\'s folder even when the request names another folder, so a wrong hint cannot unsandbox a session', async () => {
472
+ // The UI sends its current folder; a deep link opened while another
473
+ // folder is selected names the wrong one. The main daemon would find the
474
+ // session by id anyway and run its agent outside the sandbox.
475
+ const ctx = await setup({
476
+ probe: { available: false, code: 'NOT_INSTALLED' },
477
+ mainAnswers: { 'sessions.readPersisted': (p) => ({ ...detail(p.sessionId, ctx.projectA), lastSequence: -1, readOnly: true }) },
478
+ });
479
+ await ctx.sandboxOn();
480
+ const sessions = getPiSessionDirectory({ cwd: ctx.projectA, agentDir: ctx.agentDir });
481
+ await mkdir(sessions, { recursive: true });
482
+ await writeFile(join(sessions, '2026-01-01_s-9.jsonl'), `${JSON.stringify({ type: 'session', id: 's-9', cwd: ctx.projectA, timestamp: '2026-01-01T00:00:00.000Z' })}\n`);
483
+
484
+ const prompt = await ctx.call(`/api/pi/sessions/s-9/prompt`, { method: 'POST', body: { directory: ctx.projectB, text: 'hi', streamEpoch: 'epoch-1' } });
485
+ expect(prompt.status).toBe(503);
486
+ expect(await prompt.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'NOT_INSTALLED' } });
487
+ const opened = await ctx.call(`/api/pi/sessions/s-9?directory=${ctx.projectB}`);
488
+ expect(await opened.json()).toMatchObject({ readOnly: true, stream: publicDaemonStreamId('sandbox:proj-a') });
489
+ for (const command of ['sessions.prompt', 'sessions.open']) expect(ctx.main.commands()).not.toContain(command);
490
+ });
491
+
492
+ it('stamps a session read routed by its transcript with the sandbox daemon\'s stream', async () => {
493
+ // A daemon answers a directory-less read with the session's own folder.
494
+ let sessionFolder;
495
+ const ctx = await setup({ sandboxAnswers: { 'sessions.open': (p) => detail(p.sessionId, p.directory ?? sessionFolder) } });
496
+ sessionFolder = ctx.projectA;
497
+ await ctx.sandboxOn();
498
+ const sessions = getPiSessionDirectory({ cwd: ctx.projectA, agentDir: ctx.agentDir });
499
+ await mkdir(sessions, { recursive: true });
500
+ await writeFile(join(sessions, '2026-01-01_s-9.jsonl'), `${JSON.stringify({ type: 'session', id: 's-9', cwd: ctx.projectA, timestamp: '2026-01-01T00:00:00.000Z' })}\n`);
501
+
502
+ const response = await ctx.call('/api/pi/sessions/s-9');
503
+ expect(response.status).toBe(200);
504
+ // Its sequences belong to the sandbox daemon's stream, not the main one.
505
+ expect((await response.json()).stream).toBe(publicDaemonStreamId('sandbox:proj-a'));
506
+ expect(ctx.main.commands()).not.toContain('sessions.open');
507
+ });
508
+
509
+ it('forgets a failed start on Check again, so the project is not left unavailable for a one-off timeout', async () => {
510
+ const ctx = await setup({ startError: 'DAEMON_START_TIMEOUT' });
511
+ await ctx.sandboxOn();
512
+ await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: ctx.projectA, text: 'hi', streamEpoch: 'epoch-1' } });
513
+ const before = await (await ctx.call('/api/pi/sandbox/projects')).json();
514
+ expect(before.projects[0].availability).toEqual({ state: 'unavailable', reason: 'DAEMON_START_TIMEOUT' });
515
+ await ctx.call('/api/pi/sandbox/recheck', { method: 'POST' });
516
+ const after = await (await ctx.call('/api/pi/sandbox/projects')).json();
517
+ expect(after.projects[0].availability).toEqual({ state: 'available' });
518
+ });
519
+
520
+ it('shows the profile in use, saves a custom one and resets it, replacing the running sandbox each time', async () => {
521
+ const ctx = await setup();
522
+ const builtIn = { launcher: 'nono', custom: false, path: '/app/nono-profile.json', builtInPath: '/app/nono-profile.json', customPath: '/data/custom.json', content: '{"built":"in"}' };
523
+ expect(await (await ctx.call('/api/pi/sandbox/profile')).json()).toEqual({ profile: builtIn });
524
+ await ctx.sandboxOn();
525
+ const prompt = () => ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
526
+ expect((await prompt()).status).toBe(200);
527
+ expect(ctx.launched).toHaveLength(1);
528
+
529
+ const refused = await ctx.call('/api/pi/sandbox/profile', { method: 'PUT', body: { content: '{"nope":1}' } });
530
+ expect(refused.status).toBe(400);
531
+ expect(await refused.json()).toEqual({ error: { code: 'INVALID_SANDBOX_PROFILE', messages: ['Group nope not found'] } });
532
+ expect((await ctx.call('/api/pi/sandbox/profile', { method: 'PUT', body: {} })).status).toBe(400);
533
+ // A refused profile changes nothing: the same daemon answers.
534
+ expect((await prompt()).status).toBe(200);
535
+ expect(ctx.launched).toHaveLength(1);
536
+
537
+ const saved = await ctx.call('/api/pi/sandbox/profile', { method: 'PUT', body: { content: '{"mine":1}' } });
538
+ expect(await saved.json()).toEqual({ profile: { ...builtIn, custom: true, path: '/data/custom.json', content: '{"mine":1}' } });
539
+ expect((await prompt()).status).toBe(200);
540
+ expect(ctx.launched).toHaveLength(2);
541
+
542
+ const reset = await ctx.call('/api/pi/sandbox/profile', { method: 'DELETE' });
543
+ expect(await reset.json()).toEqual({ profile: builtIn });
544
+ expect((await prompt()).status).toBe(200);
545
+ expect(ctx.launched).toHaveLength(3);
546
+ });
547
+
548
+ it('replaces a running sandbox whose custom profile was edited on disk', async () => {
549
+ const ctx = await setup();
550
+ await ctx.sandboxOn();
551
+ const prompt = () => ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
552
+ await prompt();
553
+ await ctx.manager.checkIdle();
554
+ await prompt();
555
+ expect(ctx.launched).toHaveLength(1);
556
+ ctx.launcher.customProfile = '{"edited":"by hand"}';
557
+ await ctx.manager.checkIdle();
558
+ await prompt();
559
+ expect(ctx.launched).toHaveLength(2);
560
+ });
561
+
562
+ it('reports the launcher status and re-checks it on request, without paths or raw nono output', async () => {
563
+ const ctx = await setup({ probe: { available: false, code: 'NOT_INSTALLED' } });
564
+ const first = await ctx.call('/api/pi/sandbox');
565
+ expect(await first.json()).toEqual({ launchers: [{ id: 'nono', available: false, reason: 'NOT_INSTALLED' }] });
566
+ ctx.launcher.probeResult = { available: true, version: '0.82.0', capabilities: ['landlock-abi-6'] };
567
+ expect(await (await ctx.call('/api/pi/sandbox')).json()).toEqual({ launchers: [{ id: 'nono', available: false, reason: 'NOT_INSTALLED' }] });
568
+ const rechecked = await ctx.call('/api/pi/sandbox/recheck', { method: 'POST' });
569
+ expect(await rechecked.json()).toEqual({ launchers: [{ id: 'nono', available: true, version: '0.82.0' }] });
570
+ });
571
+
572
+ it('runs no sandbox on a host with limits until its owner accepts them, and retires sandboxes when acceptance is withdrawn', async () => {
573
+ const ctx = await setup({ probe: { available: true, version: '0.82.0', capabilities: ['landlock-abi-7'], limits: ['UNIX_SOCKETS', 'PROXY_PORT'] } });
574
+ const prompt = () => ctx.call('/api/pi/sessions/s-1/prompt', { method: 'POST', body: { directory: ctx.projectA, text: 'hi', streamEpoch: 'epoch-1' } });
575
+ const saved = await (await ctx.sandboxOn()).json();
576
+ expect(saved.project.availability).toEqual({ state: 'unavailable', reason: 'SANDBOX_LIMITS_NOT_ACCEPTED' });
577
+ expect(await (await ctx.call('/api/pi/sandbox')).json()).toEqual({
578
+ launchers: [{ id: 'nono', available: true, version: '0.82.0', limits: ['UNIX_SOCKETS', 'PROXY_PORT'], limitsAccepted: false }],
579
+ });
580
+ const refused = await prompt();
581
+ expect(refused.status).toBe(503);
582
+ expect(await refused.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'SANDBOX_LIMITS_NOT_ACCEPTED' } });
583
+ expect(ctx.launched).toEqual([]);
584
+
585
+ const put = (body) => ctx.call('/api/pi/sandbox/defaults', { method: 'PUT', body });
586
+ // Every limit must be accepted.
587
+ const partly = await (await put({ acceptedLimits: ['UNIX_SOCKETS'] })).json();
588
+ expect(partly.projects[0].availability).toEqual({ state: 'unavailable', reason: 'SANDBOX_LIMITS_NOT_ACCEPTED' });
589
+ expect((await prompt()).status).toBe(503);
590
+ expect(ctx.launched).toEqual([]);
591
+ const accepted = await (await put({ acceptedLimits: ['PROXY_PORT', 'UNIX_SOCKETS'] })).json();
592
+ expect(accepted.defaults).toEqual({ mode: 'off', allowHosts: [], acceptedLimits: ['UNIX_SOCKETS', 'PROXY_PORT'] });
593
+ expect(accepted.projects[0].availability).toEqual({ state: 'available' });
594
+ expect((await (await ctx.call('/api/pi/sandbox')).json()).launchers[0].limitsAccepted).toBe(true);
595
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
596
+ expect(ctx.launched).toHaveLength(1);
597
+
598
+ // Withdrawn: the running daemon is retired and the next command fails closed.
599
+ await put({ acceptedLimits: [] });
600
+ expect(ctx.launched[0].stopped).toBe(true);
601
+ expect((await prompt()).status).toBe(503);
602
+ expect(ctx.launched).toHaveLength(1);
603
+
604
+ expect((await put({ acceptedLimits: ['EVERYTHING'] })).status).toBe(400);
605
+ });
606
+
607
+ it('lists every project\'s sandbox state and refuses invalid settings or unknown projects', async () => {
608
+ const ctx = await setup();
609
+ await ctx.sandboxOn('proj-a');
610
+ const listed = await (await ctx.call('/api/pi/sandbox/projects')).json();
611
+ expect(listed).toEqual({
612
+ projects: [
613
+ { projectId: 'proj-a', mode: 'nono', launcher: 'nono', availability: { state: 'available' }, choice: 'nono', allowHosts: [], allowLocalPorts: [], extraFolders: [] },
614
+ { projectId: 'proj-b', mode: 'off', launcher: null, availability: { state: 'off' }, choice: 'default', allowHosts: [], allowLocalPorts: [], extraFolders: [] },
615
+ ],
616
+ });
617
+ const body = JSON.stringify(listed);
618
+ expect(body).not.toContain(ctx.root);
619
+
620
+ const refusedPort = await ctx.sandboxOn('proj-a', { allowLocalPorts: [443] });
621
+ expect(refusedPort.status).toBe(400);
622
+ expect(await refusedPort.json()).toEqual({ error: { code: 'INVALID_SANDBOX_SETTING', reason: 'REFUSED_PORT' } });
623
+ const unknownMode = await ctx.sandboxOn('proj-a', { mode: 'docker' });
624
+ expect(unknownMode.status).toBe(400);
625
+ expect(await unknownMode.json()).toEqual({ error: { code: 'INVALID_SANDBOX_SETTING' } });
626
+ expect((await ctx.sandboxOn('missing')).status).toBe(404);
627
+ });
628
+
629
+ it('sandboxes every project that follows the host default, keeps an explicit off off, and adds the shared hosts', async () => {
630
+ const ctx = await setup();
631
+ expect(await (await ctx.call('/api/pi/sandbox/defaults')).json()).toEqual({ defaults: { mode: 'off', allowHosts: [], acceptedLimits: [] } });
632
+ await ctx.call('/api/pi/sandbox/projects/proj-b', { method: 'PUT', body: { mode: 'off' } });
633
+ const saved = await ctx.call('/api/pi/sandbox/defaults', { method: 'PUT', body: { mode: 'nono', allowHosts: ['GitHub.com', 'github.com'] } });
634
+ expect(saved.status).toBe(200);
635
+ const body = await saved.json();
636
+ expect(body.defaults).toEqual({ mode: 'nono', allowHosts: ['github.com'], acceptedLimits: [] });
637
+ expect(body.projects.map((p) => [p.projectId, p.mode, p.choice])).toEqual([['proj-a', 'nono', 'default'], ['proj-b', 'off', 'off']]);
638
+ // proj-a has no setting of its own, yet runs sandboxed with the shared host.
639
+ await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: ctx.projectA, text: 'hi', streamEpoch: 'epoch-1' } });
640
+ expect(ctx.launched).toHaveLength(1);
641
+ expect(ctx.launched[0].sandbox.network.allowHosts).toContain('github.com');
642
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
643
+ // The project's own hosts add to the shared ones.
644
+ await ctx.call('/api/pi/sandbox/projects/proj-a', { method: 'PUT', body: { mode: 'default', allowHosts: ['registry.npmjs.org'] } });
645
+ expect((await (await ctx.call('/api/pi/sandbox/projects')).json()).projects[0]).toMatchObject({ mode: 'nono', choice: 'default', allowHosts: ['registry.npmjs.org'] });
646
+
647
+ // Turning the default off unsandboxes only the projects that follow it.
648
+ await ctx.call('/api/pi/sandbox/defaults', { method: 'PUT', body: { mode: 'off', allowHosts: [] } });
649
+ expect((await (await ctx.call('/api/pi/sandbox/projects')).json()).projects.map((p) => p.mode)).toEqual(['off', 'off']);
650
+ expect((await ctx.call('/api/pi/sandbox/defaults', { method: 'PUT', body: { mode: 'default' } })).status).toBe(400);
651
+ });
652
+
653
+ it('keeps the default out of ordinary settings writes, so a client cannot change it that way', async () => {
654
+ const ctx = await setup();
655
+ await ctx.uiSettingsStore.write({ sandboxDefaults: { mode: 'nono', allowHosts: [] } });
656
+ expect(await (await ctx.call('/api/pi/sandbox/defaults')).json()).toEqual({ defaults: { mode: 'off', allowHosts: [], acceptedLimits: [] } });
657
+ await ctx.call('/api/pi/sandbox/defaults', { method: 'PUT', body: { mode: 'nono', allowHosts: [] } });
658
+ await ctx.uiSettingsStore.write({ sandboxDefaults: { mode: 'off', allowHosts: [] }, projects: [{ id: 'proj-a', path: ctx.projectA }, { id: 'proj-b', path: ctx.projectB }] });
659
+ expect((await (await ctx.call('/api/pi/sandbox/defaults')).json()).defaults.mode).toBe('nono');
660
+ });
661
+
662
+ it('turning a project off routes it back to the main daemon and stops its sandbox daemon', async () => {
663
+ const ctx = await setup();
664
+ await ctx.sandboxOn();
665
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
666
+ expect(await (await ctx.sandboxOn('proj-a', { mode: 'off' })).json()).toMatchObject({ project: { mode: 'off', availability: { state: 'off' } } });
667
+ expect(ctx.launched[0].stopped).toBe(true);
668
+ expect(ctx.intakes[0].stopped).toBe(true);
669
+ const response = await ctx.call(`/api/pi/sessions/s-2?directory=${ctx.projectA}`);
670
+ expect((await response.json()).session).toEqual(session('s-2', ctx.projectA));
671
+ expect(ctx.main.calls.filter((c) => c.command === 'sessions.open').map((c) => c.payload.sessionId)).toEqual(['s-2']);
672
+ });
673
+
674
+ it('a project rewrite by a client cannot turn its sandbox off', async () => {
675
+ const ctx = await setup({ probe: { available: false, code: 'NO_LANDLOCK' } });
676
+ await ctx.sandboxOn();
677
+ await ctx.call('/api/pi/ui-settings', { method: 'PUT', body: { projects: [{ id: 'proj-b', path: ctx.projectB }, { id: 'proj-a', path: ctx.projectA }] } });
678
+ const response = await ctx.call('/api/pi/sessions', { method: 'POST', body: { cwd: ctx.projectA } });
679
+ expect(response.status).toBe(503);
680
+ });
681
+
682
+ it('includes a running sandbox daemon in pending input, and stops it after an idle period with no resident sessions', async () => {
683
+ let resident = 1;
684
+ const ctx = await setup({
685
+ idleStopMs: 10_000,
686
+ sandboxAnswers: {
687
+ 'runtime.health': () => ({ state: 'ready', residentSessions: resident }),
688
+ 'sessions.pendingInput': { sessions: [], sequence: 1, streamEpoch: 'epoch-box' },
689
+ },
690
+ mainAnswers: { 'sessions.pendingInput': { sessions: [], sequence: 4, streamEpoch: 'epoch-main' } },
691
+ });
692
+ await ctx.sandboxOn();
693
+ expect(ctx.pool.live().map((d) => d.key)).toEqual(['main']);
694
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
695
+ expect(ctx.pool.live()).toHaveLength(2);
696
+ await ctx.call('/api/pi/sessions/pending-input');
697
+ expect(ctx.launched[0].commands()).toContain('sessions.pendingInput');
698
+
699
+ await ctx.tick(20_000);
700
+ expect(ctx.launched[0].stopped).toBe(false);
701
+ resident = 0;
702
+ await ctx.tick(5_000);
703
+ expect(ctx.launched[0].stopped).toBe(false);
704
+ await ctx.tick(10_000);
705
+ expect(ctx.launched[0].stopped).toBe(true);
706
+ expect(ctx.intakes[0].stopped).toBe(true);
707
+ expect(ctx.pool.live().map((d) => d.key)).toEqual(['main']);
708
+
709
+ // The next open starts it again.
710
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
711
+ expect(ctx.launched).toHaveLength(2);
712
+ });
713
+
714
+ it('joins a started sandbox daemon to the merged event stream and leaves it when the daemon stops idle', async () => {
715
+ let resident = 1;
716
+ const ctx = await setup({
717
+ idleStopMs: 10_000,
718
+ sandboxAnswers: { 'runtime.health': () => ({ state: 'ready', residentSessions: resident }) },
719
+ });
720
+ await ctx.sandboxOn();
721
+ const events = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?capabilities=events.streamEpoch`);
722
+ const reader = events.body.getReader();
723
+ const decoder = new TextDecoder();
724
+ let text = '';
725
+ // One read stays pending across timeouts, so no chunk is taken by an
726
+ // abandoned read and lost.
727
+ let pendingRead = null;
728
+ const readUntil = async (predicate) => {
729
+ for (let i = 0; i < 50 && !predicate(text); i += 1) {
730
+ pendingRead ??= reader.read();
731
+ const next = await Promise.race([pendingRead, new Promise((r) => setTimeout(() => r({ timeout: true }), 100))]);
732
+ if (next.timeout) continue;
733
+ pendingRead = null;
734
+ if (next.done) break;
735
+ text += decoder.decode(next.value);
736
+ }
737
+ return text;
738
+ };
739
+ const waitFor = async (predicate) => {
740
+ for (let i = 0; i < 50 && !predicate(); i += 1) await new Promise((r) => setTimeout(r, 10));
741
+ };
742
+ await waitFor(() => ctx.main.subscriptions.length > 0);
743
+ // Not started yet, so nothing subscribes to it.
744
+ expect(ctx.launched).toEqual([]);
745
+
746
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
747
+ const [daemon] = ctx.launched;
748
+ await waitFor(() => daemon.subscriptions.some((item) => !item.closed));
749
+ daemon.emit('session.updated', 1, { sessionId: 's-1', directory: ctx.projectA, title: 'Boxed' });
750
+ const stream = publicDaemonStreamId('sandbox:proj-a');
751
+ await readUntil((body) => body.includes('Boxed'));
752
+ const frame = text.split('\n').filter((line) => line.startsWith('data: ')).map((line) => JSON.parse(line.slice(6)))
753
+ .find((item) => item.payload?.title === 'Boxed');
754
+ expect(frame).toMatchObject({ stream, sessionId: 's-1', payload: { title: 'Boxed' } });
755
+
756
+ resident = 0;
757
+ await ctx.tick(1_000);
758
+ await ctx.tick(11_000);
759
+ expect(daemon.stopped).toBe(true);
760
+ await waitFor(() => daemon.subscriptions.every((item) => item.closed));
761
+ expect(daemon.subscriptions.every((item) => item.closed)).toBe(true);
762
+ // The main daemon's subscription is untouched.
763
+ expect(ctx.main.subscriptions.filter((item) => !item.closed)).toHaveLength(1);
764
+ await reader.cancel();
765
+ });
766
+
767
+ it('leaves a provider on the server machine or local network out of the allowed hosts instead of failing the start', async () => {
768
+ const ctx = await setup({ mainAnswers: { 'providers.hosts': { hosts: ['api.anthropic.com', 'ollama', 'nas.local'] } } });
769
+ await ctx.sandboxOn();
770
+ expect((await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`)).status).toBe(200);
771
+ expect(ctx.launched[0].sandbox.network.allowHosts).toEqual(['api.anthropic.com']);
772
+ });
773
+
774
+ it('fails a sandbox start closed when the main daemon cannot name the provider hosts', async () => {
775
+ const ctx = await setup({ mainAnswers: { 'providers.hosts': daemonError('DAEMON_UNAVAILABLE') } });
776
+ await ctx.sandboxOn();
777
+ const response = await ctx.call('/api/pi/sessions', { method: 'POST', body: { cwd: ctx.projectA } });
778
+ expect(await response.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'PROVIDER_HOSTS_UNAVAILABLE' } });
779
+ expect(ctx.launched).toEqual([]);
780
+ });
781
+ });
782
+
783
+ describe('switching a project between daemons', () => {
784
+ let server;
785
+ let manager;
786
+ afterEach(async () => {
787
+ await manager?.stop();
788
+ manager = undefined;
789
+ await close(server);
790
+ server = undefined;
791
+ });
792
+
793
+ // Same wiring as above, kept separate so switch tests can script the
794
+ // old daemon's `sessions.release` answers.
795
+ const setup = async (options = {}) => {
796
+ const built = await buildSandboxRoutes(options);
797
+ server = built.server;
798
+ manager = built.manager;
799
+ return built;
800
+ };
801
+
802
+ it('moves idle sessions at once and holds a busy one in the old daemon until its turn ends', async () => {
803
+ // The main daemon runs s-idle (idle) and s-busy (mid-turn) in project A.
804
+ let busy = true;
805
+ const ctx = await setup({
806
+ mainAnswers: {
807
+ 'sessions.release': (p) => (busy
808
+ ? { released: [{ sessionId: 's-idle', directory: p.directories[0] }], pending: [{ sessionId: 's-busy', directory: p.directories[0] }], streamEpoch: 'epoch-main' }
809
+ : { released: [{ sessionId: 's-busy', directory: p.directories[0] }], pending: [], streamEpoch: 'epoch-main' }),
810
+ 'sessions.list': (p) => ({
811
+ sessions: [{ ...row('s-busy', p.directory), live: { lifecycle: 'busy', sequence: 7 } }, row('s-idle', p.directory)],
812
+ streamEpoch: 'epoch-main',
813
+ }),
814
+ },
815
+ sandboxAnswers: { 'sessions.list': (p) => ({ sessions: [row('s-busy', p.directory), row('s-idle', p.directory)], streamEpoch: 'epoch-box' }) },
816
+ });
817
+ const saved = await ctx.sandboxOn();
818
+ expect(saved.status).toBe(200);
819
+
820
+ // The old daemon was asked to let go of the project's folders.
821
+ const release = ctx.main.calls.find((c) => c.command === 'sessions.release');
822
+ expect(release.payload.directories).toEqual([ctx.projectA, join(ctx.dataDir, 'worktree', ctx.gitId)]);
823
+ // Clients refetch both: the idle one from its new daemon, the busy one
824
+ // to learn it switches after this turn.
825
+ expect(ctx.moves.map(([id]) => id).sort()).toEqual(['s-busy', 's-idle']);
826
+
827
+ // The list comes from the sandbox daemon; the busy row keeps its live
828
+ // state from the main daemon and says it switches after this turn.
829
+ const list = await (await ctx.call(`/api/pi/sessions?directory=${ctx.projectA}`)).json();
830
+ const busyRow = list.sessions.find((item) => item.session.id === 's-busy');
831
+ expect(busyRow).toMatchObject({ live: { lifecycle: 'busy', sequence: 7 }, stream: 'main', streamEpoch: 'epoch-main' });
832
+ expect(busyRow.session.pendingSwitch).toEqual({ to: 'nono' });
833
+ expect(busyRow.session.sandboxed).toBeUndefined();
834
+ const idleRow = list.sessions.find((item) => item.session.id === 's-idle');
835
+ expect(idleRow.session).toMatchObject({ sandboxed: true });
836
+ expect(idleRow.session.pendingSwitch).toBeUndefined();
837
+
838
+ // Reading and stopping the busy session reach the daemon running it.
839
+ const detail = await ctx.call(`/api/pi/sessions/s-busy?directory=${ctx.projectA}`);
840
+ const detailBody = await detail.json();
841
+ expect(detailBody.session).toMatchObject({ id: 's-busy', pendingSwitch: { to: 'nono' } });
842
+ expect(detailBody.stream).toBeUndefined();
843
+ expect((await ctx.call(`/api/pi/sessions/s-busy/abort`, { method: 'POST', body: { directory: ctx.projectA } })).status).toBe(204);
844
+ expect(ctx.main.calls.filter((c) => ['sessions.open', 'sessions.abort'].includes(c.command)).map((c) => c.payload.sessionId)).toEqual(['s-busy', 's-busy']);
845
+
846
+ // New work for it is refused until it has moved.
847
+ const prompt = await ctx.call('/api/pi/sessions/s-busy/prompt', { method: 'POST', body: { directory: ctx.projectA, text: 'more', streamEpoch: 'epoch-main' } });
848
+ expect(prompt.status).toBe(409);
849
+ expect(await prompt.json()).toEqual({ error: { code: 'SESSION_IN_USE', reason: 'SESSION_SWITCHING' } });
850
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
851
+
852
+ // Its turn ends; the next drain check moves it.
853
+ busy = false;
854
+ ctx.moves.length = 0;
855
+ await ctx.tick(1_000);
856
+ expect(ctx.moves.map(([id]) => id)).toEqual(['s-busy']);
857
+ const after = await (await ctx.call(`/api/pi/sessions?directory=${ctx.projectA}`)).json();
858
+ expect(after.sessions.every((item) => item.session.pendingSwitch === undefined && item.session.sandboxed === true)).toBe(true);
859
+ expect(ctx.pool.drainingFor(ctx.projectA)).toEqual([]);
860
+ const reopened = await ctx.call(`/api/pi/sessions/s-busy?directory=${ctx.projectA}`);
861
+ expect((await reopened.json()).stream).toBe(publicDaemonStreamId('sandbox:proj-a'));
862
+ });
863
+
864
+ it('turning a project off drains its sandbox daemon into the main daemon and resets the project\'s trust to ask', async () => {
865
+ let busy = true;
866
+ const ctx = await setup({
867
+ sandboxAnswers: {
868
+ 'sessions.release': (p) => (busy
869
+ ? { released: [], pending: [{ sessionId: 's-1', directory: p.directories[0] }], streamEpoch: 'epoch-box' }
870
+ : { released: [{ sessionId: 's-1', directory: p.directories[0] }], pending: [], streamEpoch: 'epoch-box' }),
871
+ 'extensions.respond': (p) => ({ resolved: p.requestId === 'dialog-in-box' }),
872
+ },
873
+ mainAnswers: { 'extensions.respond': { resolved: false } },
874
+ });
875
+ await ctx.sandboxOn();
876
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
877
+ const [box] = ctx.launched;
878
+ ctx.moves.length = 0;
879
+
880
+ const off = await ctx.sandboxOn('proj-a', { mode: 'off' });
881
+ expect(await off.json()).toMatchObject({ project: { mode: 'off' } });
882
+ // Trust goes back to "ask" for the project and its worktrees, through
883
+ // the main daemon, and stays recorded so auto-trust skips them.
884
+ const trustCalls = ctx.main.calls.filter((c) => c.command === 'settings.set').map((c) => c.payload);
885
+ expect(trustCalls).toEqual([
886
+ { scope: 'project', directory: ctx.projectA, trust: null },
887
+ { scope: 'project', directory: ctx.worktree, trust: null },
888
+ ]);
889
+ expect(await ctx.trustAsk.list()).toEqual([ctx.projectA, ctx.worktree]);
890
+
891
+ // The sandbox daemon keeps running the busy session.
892
+ expect(box.stopped).toBe(false);
893
+ expect(ctx.moves).toEqual([['s-1', ctx.projectA]]);
894
+ const detail = await (await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`)).json();
895
+ expect(detail.session).toMatchObject({ sandboxed: true, pendingSwitch: { to: 'off' } });
896
+ expect(detail.stream).toBe(publicDaemonStreamId('sandbox:proj-a'));
897
+ // A dialog it shows is answered there.
898
+ const respond = await ctx.call('/api/pi/extensions/respond', { method: 'POST', body: { requestId: 'dialog-in-box', directory: ctx.projectA, cancelled: true } });
899
+ expect(respond.status).toBe(204);
900
+ // New sessions in the project already run in the main daemon.
901
+ await ctx.call(`/api/pi/sessions/s-2?directory=${ctx.projectA}`);
902
+ expect(ctx.main.calls.filter((c) => c.command === 'sessions.open').map((c) => c.payload.sessionId)).toEqual(['s-2']);
903
+
904
+ busy = false;
905
+ await ctx.tick(1_000);
906
+ // The server checks the released session against its transcripts first.
907
+ await waitFor(() => ctx.pool.live().length === 1);
908
+ expect(box.stopped).toBe(true);
909
+ expect(ctx.intakes[0].stopped).toBe(true);
910
+ expect(ctx.pool.live().map((d) => d.key)).toEqual(['main']);
911
+ const moved = await (await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`)).json();
912
+ expect(moved.session.sandboxed).toBeUndefined();
913
+ expect(moved.session.pendingSwitch).toBeUndefined();
914
+ });
915
+
916
+ it('answers a dialog of a session still finishing in the main daemon without starting the sandbox', async () => {
917
+ // Turned on while s-busy shows a dialog in the main daemon, on a host
918
+ // where nono cannot run: the answer must reach the main daemon, or the
919
+ // session could never end its turn.
920
+ const ctx = await setup({
921
+ probe: { available: false, code: 'NOT_INSTALLED' },
922
+ mainAnswers: {
923
+ 'sessions.release': (p) => ({ released: [], pending: [{ sessionId: 's-busy', directory: p.directories[0] }], streamEpoch: 'epoch-main' }),
924
+ 'extensions.respond': (p) => ({ resolved: p.requestId === 'dialog-in-main' }),
925
+ },
926
+ });
927
+ await ctx.sandboxOn();
928
+ const respond = await ctx.call('/api/pi/extensions/respond', { method: 'POST', body: { requestId: 'dialog-in-main', directory: ctx.projectA, cancelled: true } });
929
+ expect(respond.status).toBe(204);
930
+ expect(ctx.launched).toEqual([]);
931
+ // A dialog nobody holds is still asked of the folder's owner, which
932
+ // fails closed.
933
+ const other = await ctx.call('/api/pi/extensions/respond', { method: 'POST', body: { requestId: 'unknown', directory: ctx.projectA, cancelled: true } });
934
+ expect(other.status).toBe(503);
935
+ });
936
+
937
+ it('turning a project off again while its session still runs in the main daemon leaves the session there', async () => {
938
+ const ctx = await setup({
939
+ mainAnswers: {
940
+ 'sessions.release': (p) => ({ released: [], pending: [{ sessionId: 's-busy', directory: p.directories[0] }], streamEpoch: 'epoch-main' }),
941
+ },
942
+ });
943
+ await ctx.sandboxOn();
944
+ expect((await (await ctx.call(`/api/pi/sessions/s-busy?directory=${ctx.projectA}`)).json()).session.pendingSwitch).toEqual({ to: 'nono' });
945
+ ctx.moves.length = 0;
946
+
947
+ await ctx.sandboxOn('proj-a', { mode: 'off' });
948
+ // Clients refetch it: it no longer waits to switch, and takes new work.
949
+ expect(ctx.moves).toEqual([['s-busy', ctx.projectA]]);
950
+ expect(ctx.pool.drainingFor(ctx.projectA)).toEqual([]);
951
+ const detail = await (await ctx.call(`/api/pi/sessions/s-busy?directory=${ctx.projectA}`)).json();
952
+ expect(detail.session.pendingSwitch).toBeUndefined();
953
+ expect(detail.session.sandboxed).toBeUndefined();
954
+ const followUp = await ctx.call('/api/pi/sessions/s-busy/follow-up', { method: 'POST', body: { directory: ctx.projectA, text: 'more', streamEpoch: 'epoch-main' } });
955
+ expect(followUp.status).not.toBe(409);
956
+ expect(ctx.main.commands()).toContain('sessions.followUp');
957
+ // The main daemon is not asked to release the folder any more.
958
+ const releases = ctx.main.calls.filter((c) => c.command === 'sessions.release').length;
959
+ await ctx.tick(1_000);
960
+ expect(ctx.main.calls.filter((c) => c.command === 'sessions.release')).toHaveLength(releases);
961
+ });
962
+
963
+ it('turning a project on again while its session still runs in the old sandbox shows no switch', async () => {
964
+ const ctx = await setup({
965
+ sandboxAnswers: {
966
+ 'sessions.release': (p) => ({ released: [], pending: [{ sessionId: 's-1', directory: p.directories[0] }], streamEpoch: 'epoch-box' }),
967
+ },
968
+ });
969
+ await ctx.sandboxOn();
970
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
971
+ await ctx.sandboxOn('proj-a', { mode: 'off' });
972
+ expect((await (await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`)).json()).session).toMatchObject({ sandboxed: true, pendingSwitch: { to: 'off' } });
973
+
974
+ await ctx.sandboxOn();
975
+ const detail = await (await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`)).json();
976
+ expect(detail.session.sandboxed).toBe(true);
977
+ expect(detail.session.pendingSwitch).toBeUndefined();
978
+ // It is still served by the daemon running it.
979
+ expect(detail.stream).toBe(publicDaemonStreamId('sandbox:proj-a'));
980
+ });
981
+
982
+ it('records the trust reset on a later check when the first write fails, without unsetting trust again', async () => {
983
+ const ctx = await setup();
984
+ await ctx.sandboxOn();
985
+ const add = ctx.trustAsk.add;
986
+ ctx.trustAsk.add = async () => {
987
+ ctx.trustAsk.add = add;
988
+ throw new Error('disk full');
989
+ };
990
+ await ctx.sandboxOn('proj-a', { mode: 'off' });
991
+ expect(await ctx.trustAsk.list()).toEqual([]);
992
+ const resets = () => ctx.main.calls.filter((c) => c.command === 'settings.set').length;
993
+ expect(resets()).toBe(2);
994
+ await ctx.tick(1_000);
995
+ expect(await ctx.trustAsk.list()).toEqual([ctx.projectA, ctx.worktree]);
996
+ expect(resets()).toBe(2);
997
+ });
998
+
999
+ it('keeps a draining daemon that holds a busy session through a few failed checks', async () => {
1000
+ let answer = 'busy';
1001
+ const ctx = await setup({
1002
+ sandboxAnswers: {
1003
+ 'sessions.release': (p) => {
1004
+ if (answer === 'fail') throw daemonError('DAEMON_TIMEOUT');
1005
+ return answer === 'busy'
1006
+ ? { released: [], pending: [{ sessionId: 's-1', directory: p.directories[0] }], streamEpoch: 'epoch-box' }
1007
+ : { released: [{ sessionId: 's-1', directory: p.directories[0] }], pending: [], streamEpoch: 'epoch-box' };
1008
+ },
1009
+ },
1010
+ });
1011
+ await ctx.sandboxOn();
1012
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1013
+ const [box] = ctx.launched;
1014
+ await ctx.sandboxOn('proj-a', { mode: 'off' });
1015
+ answer = 'fail';
1016
+ for (let i = 0; i < 5; i += 1) await ctx.tick(1_000);
1017
+ expect(box.stopped).toBe(false);
1018
+ answer = 'done';
1019
+ await ctx.tick(1_000);
1020
+ expect(box.stopped).toBe(true);
1021
+ });
1022
+
1023
+ it('refuses a daemon whose setting changed while it was starting, so removed access is not kept', async () => {
1024
+ let release;
1025
+ const gate = new Promise((resolve) => { release = resolve; });
1026
+ let starts = 0;
1027
+ const ctx = await setup({ onStart: () => { starts += 1; return starts === 1 ? gate : undefined; } });
1028
+ await ctx.sandboxOn('proj-a', { allowHosts: ['registry.npmjs.org'] });
1029
+ const first = ctx.call(`/api/pi/sessions/s-1/tree?directory=${ctx.projectA}`);
1030
+ for (let i = 0; i < 100 && starts === 0; i += 1) await new Promise((r) => setTimeout(r, 5));
1031
+ expect(starts).toBe(1);
1032
+ // The host is removed while the daemon that was granted it still starts.
1033
+ await ctx.sandboxOn('proj-a', { allowHosts: [] });
1034
+ release();
1035
+ const refused = await first;
1036
+ expect(refused.status).toBe(503);
1037
+ expect(await refused.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'SANDBOX_SETTING_CHANGED' } });
1038
+ expect(ctx.launched[0].stopped).toBe(true);
1039
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1040
+ expect(ctx.launched).toHaveLength(2);
1041
+ expect(ctx.launched[1].sandbox.network.allowHosts).toEqual(['api.anthropic.com']);
1042
+ expect(ctx.launched[1].stopped).toBe(false);
1043
+ });
1044
+
1045
+ it('an explicit trust decision clears the recorded reset', async () => {
1046
+ const ctx = await setup({ mainAnswers: { 'settings.set': { global: {}, project: { trusted: true } } } });
1047
+ await ctx.sandboxOn();
1048
+ await ctx.sandboxOn('proj-a', { mode: 'off' });
1049
+ expect(await ctx.trustAsk.list()).toContain(ctx.projectA);
1050
+ await ctx.call('/api/pi/settings/pi', { method: 'PUT', body: { scope: 'project', directory: ctx.projectA, trust: true } });
1051
+ expect(await ctx.trustAsk.list()).not.toContain(ctx.projectA);
1052
+ });
1053
+
1054
+ const waitFor = async (predicate) => {
1055
+ for (let i = 0; i < 100 && !predicate(); i += 1) await new Promise((r) => setTimeout(r, 5));
1056
+ };
1057
+
1058
+ it('a models.json save replaces a running sandbox daemon at its next idle edge', async () => {
1059
+ let busy = true;
1060
+ const ctx = await setup({
1061
+ mainAnswers: { 'providers.models.set': { config: null } },
1062
+ sandboxAnswers: {
1063
+ 'sessions.release': (p) => (busy
1064
+ ? { released: [], pending: [{ sessionId: 's-1', directory: p.directories[0] }], streamEpoch: 'epoch-box' }
1065
+ : { released: [{ sessionId: 's-1', directory: p.directories[0] }], pending: [], streamEpoch: 'epoch-box' }),
1066
+ },
1067
+ });
1068
+ await ctx.sandboxOn();
1069
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1070
+ const [first] = ctx.launched;
1071
+ ctx.moves.length = 0;
1072
+
1073
+ const saved = await ctx.call('/api/pi/providers/local/models', { method: 'PUT', body: { models: [] } });
1074
+ expect(saved.status).toBe(200);
1075
+ await waitFor(() => first.commands().includes('sessions.release'));
1076
+ await waitFor(() => ctx.manager.drainingSession('s-1'));
1077
+ // The busy session finishes in the old daemon; it is not a mode switch.
1078
+ expect(first.stopped).toBe(false);
1079
+ const detail = await (await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`)).json();
1080
+ expect(detail.session).toMatchObject({ sandboxed: true });
1081
+ expect(detail.session.pendingSwitch).toBeUndefined();
1082
+ expect(detail.stream).toBe(publicDaemonStreamId('sandbox:proj-a'));
1083
+
1084
+ // Another session starts a fresh daemon that reads the new file.
1085
+ await ctx.call(`/api/pi/sessions/s-2?directory=${ctx.projectA}`);
1086
+ expect(ctx.launched).toHaveLength(2);
1087
+ expect(ctx.launched[1].commands()).toEqual(['sessions.open']);
1088
+
1089
+ busy = false;
1090
+ await ctx.tick(1_000);
1091
+ expect(first.stopped).toBe(true);
1092
+ expect(ctx.moves).toEqual([['s-1', ctx.projectA]]);
1093
+ expect(ctx.pool.live().map((d) => d.key)).toEqual(['main', 'sandbox:proj-a:1']);
1094
+ });
1095
+
1096
+ it('a replaced daemon never takes the pool key of one that is still draining', async () => {
1097
+ let busy = true;
1098
+ const ctx = await setup({
1099
+ mainAnswers: { 'providers.models.set': { config: null } },
1100
+ sandboxAnswers: {
1101
+ 'sessions.release': (p) => (busy
1102
+ ? { released: [], pending: [{ sessionId: 's-1', directory: p.directories[0] }], streamEpoch: 'epoch-box' }
1103
+ : { released: [{ sessionId: 's-1', directory: p.directories[0] }], pending: [], streamEpoch: 'epoch-box' }),
1104
+ },
1105
+ });
1106
+ const replace = async () => {
1107
+ expect((await ctx.call('/api/pi/providers/local/models', { method: 'PUT', body: { models: [] } })).status).toBe(200);
1108
+ };
1109
+ await ctx.sandboxOn();
1110
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1111
+ // Replaced once: the first daemon drains and finishes, the project moves
1112
+ // to the second key.
1113
+ await replace();
1114
+ await waitFor(() => ctx.manager.drainingSession('s-1'));
1115
+ busy = false;
1116
+ await ctx.tick(1_000);
1117
+ expect(ctx.launched[0].stopped).toBe(true);
1118
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1119
+ expect(ctx.pool.live().map((d) => d.key)).toEqual(['main', 'sandbox:proj-a:1']);
1120
+
1121
+ // Turned off mid-turn: that daemon drains under the second key. Turned
1122
+ // on again, the project gets the first key back, which is free.
1123
+ busy = true;
1124
+ await ctx.sandboxOn('proj-a', { mode: 'off' });
1125
+ await ctx.sandboxOn();
1126
+ await ctx.call(`/api/pi/sessions/s-2?directory=${ctx.projectA}`);
1127
+ expect(ctx.pool.live().map((d) => d.key).sort()).toEqual(['main', 'sandbox:proj-a', 'sandbox:proj-a:1']);
1128
+
1129
+ // Replaced again: the next key is the draining daemon's, so it is skipped.
1130
+ await replace();
1131
+ await waitFor(() => ctx.launched[2].commands().includes('sessions.release'));
1132
+ await ctx.call(`/api/pi/sessions/s-3?directory=${ctx.projectA}`);
1133
+ expect(ctx.launched).toHaveLength(4);
1134
+ expect(ctx.launched[1].stopped).toBe(false);
1135
+ expect(ctx.pool.live().map((d) => d.key).sort()).toEqual(['main', 'sandbox:proj-a', 'sandbox:proj-a:1', 'sandbox:proj-a:2']);
1136
+ });
1137
+
1138
+ it('a Pi config file changed outside PiChamber replaces an idle sandbox daemon on the next check', async () => {
1139
+ const ctx = await setup();
1140
+ await writeFile(join(ctx.agentDir, 'models.json'), '{}');
1141
+ await ctx.sandboxOn();
1142
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1143
+ await ctx.tick(60_000);
1144
+ expect(ctx.launched[0].stopped).toBe(false);
1145
+
1146
+ await writeFile(join(ctx.agentDir, 'models.json.tmp'), '{"providers":{}}');
1147
+ await rename(join(ctx.agentDir, 'models.json.tmp'), join(ctx.agentDir, 'models.json'));
1148
+ await ctx.tick(60_000);
1149
+ expect(ctx.launched[0].commands()).toContain('sessions.release');
1150
+ expect(ctx.launched[0].stopped).toBe(true);
1151
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1152
+ expect(ctx.launched).toHaveLength(2);
1153
+ });
1154
+
1155
+ it('a worktree added after the daemon started starts a daemon that has it', async () => {
1156
+ const ctx = await setup();
1157
+ await ctx.sandboxOn();
1158
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1159
+ const added = join(ctx.dataDir, 'worktree', ctx.gitId, 'second');
1160
+ await mkdir(added, { recursive: true });
1161
+ await ctx.call(`/api/pi/sessions/s-2?directory=${added}`);
1162
+ expect(ctx.launched).toHaveLength(2);
1163
+ expect(ctx.launched[0].stopped).toBe(true);
1164
+ expect(ctx.launched[1].calls.map((c) => c.payload?.sessionId)).toEqual(['s-2']);
1165
+ expect(ctx.launched[1].sandbox.grants).toEqual(expect.arrayContaining([
1166
+ { kind: 'readWrite', path: getPiSessionDirectory({ cwd: added, agentDir: ctx.agentDir }) },
1167
+ ]));
1168
+ });
1169
+
1170
+ it('a changed setting drains the running daemon instead of cutting it off', async () => {
1171
+ const ctx = await setup({
1172
+ sandboxAnswers: { 'sessions.release': (p) => ({ released: [], pending: [{ sessionId: 's-1', directory: p.directories[0] }] }) },
1173
+ });
1174
+ await ctx.sandboxOn();
1175
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1176
+ await ctx.sandboxOn('proj-a', { allowHosts: ['registry.npmjs.org'] });
1177
+ expect(ctx.launched[0].stopped).toBe(false);
1178
+ expect(ctx.launched[0].commands()).toContain('sessions.release');
1179
+ await ctx.call(`/api/pi/sessions/s-2?directory=${ctx.projectA}`);
1180
+ expect(ctx.launched[1].sandbox.network.allowHosts).toContain('registry.npmjs.org');
1181
+ });
1182
+
1183
+ it('asks the main daemon to refresh OAuth tokens before a sandbox daemon starts, without making it stale', async () => {
1184
+ let agentDir;
1185
+ const ctx = await setup({
1186
+ mainAnswers: {
1187
+ // The refresh rewrites auth.json, as Pi does.
1188
+ 'providers.oauth.refresh': async () => {
1189
+ await writeFile(join(agentDir, 'auth.json.tmp'), '{"anthropic":{"type":"oauth"}}');
1190
+ await rename(join(agentDir, 'auth.json.tmp'), join(agentDir, 'auth.json'));
1191
+ return {};
1192
+ },
1193
+ },
1194
+ });
1195
+ agentDir = ctx.agentDir;
1196
+ await ctx.sandboxOn();
1197
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1198
+ expect(ctx.main.commands().filter((c) => ['providers.oauth.refresh', 'providers.hosts'].includes(c)))
1199
+ .toEqual(['providers.oauth.refresh', 'providers.hosts']);
1200
+ // Both name the sandboxed folders, so the main daemon starts no runtime there to answer.
1201
+ const exclude = [ctx.projectA, join(ctx.dataDir, 'worktree', ctx.gitId)];
1202
+ // The main daemon also reads them from the server's record before it starts any runtime.
1203
+ expect(JSON.parse(await readFile(sandboxedFoldersFile(ctx.dataDir), 'utf8')).directories).toEqual([...exclude].sort());
1204
+ expect(ctx.main.calls.find((c) => c.command === 'providers.oauth.refresh').payload).toEqual({ minValidityMs: 30 * 60_000, exclude });
1205
+ expect(ctx.main.calls.find((c) => c.command === 'providers.hosts').payload).toEqual({ exclude });
1206
+ await ctx.tick(60_000);
1207
+ expect(ctx.launched[0].stopped).toBe(false);
1208
+ // Turned off, the project is the main daemon's again.
1209
+ await ctx.sandboxOn('proj-a', { mode: 'off' });
1210
+ expect(JSON.parse(await readFile(sandboxedFoldersFile(ctx.dataDir), 'utf8')).directories).toEqual([]);
1211
+ });
1212
+
1213
+ it('starts the sandbox anyway when the main daemon cannot refresh OAuth tokens', async () => {
1214
+ const ctx = await setup({ mainAnswers: { 'providers.oauth.refresh': daemonError('UNKNOWN_COMMAND') } });
1215
+ await ctx.sandboxOn();
1216
+ const response = await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1217
+ expect(response.status).toBe(200);
1218
+ });
1219
+
1220
+ it('a sandboxed turn that fails to refresh its OAuth token gets the main daemon to refresh and replaces the daemon', async () => {
1221
+ let agentDir;
1222
+ let refreshes = 0;
1223
+ const ctx = await setup({
1224
+ mainAnswers: {
1225
+ 'providers.oauth.refresh': async () => {
1226
+ refreshes += 1;
1227
+ if (refreshes > 1) {
1228
+ await writeFile(join(agentDir, 'auth.json'), `{"refresh":${refreshes}}`);
1229
+ }
1230
+ return {};
1231
+ },
1232
+ },
1233
+ });
1234
+ agentDir = ctx.agentDir;
1235
+ await ctx.sandboxOn();
1236
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1237
+ const [box] = ctx.launched;
1238
+ await waitFor(() => box.subscriptions.some((item) => !item.closed));
1239
+ // An unrelated error does nothing.
1240
+ box.emit('session.error', 3, { code: 'ASSISTANT_ERROR', message: 'Rate limited' });
1241
+ box.emit('session.error', 4, { code: 'ASSISTANT_ERROR', message: 'Credential store modify failed for anthropic' });
1242
+ await waitFor(() => box.stopped);
1243
+ expect(refreshes).toBe(2);
1244
+ expect(box.stopped).toBe(true);
1245
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1246
+ expect(ctx.launched).toHaveLength(2);
1247
+ });
1248
+
1249
+ // The manager recognises Pi's own error text. Produce it with the pi-ai
1250
+ // the Pi SDK actually loads (its `refreshStoredOAuthCredential`, not part
1251
+ // of pi-ai's public exports), so a rewording upstream fails this test.
1252
+ it('recognises the OAuth refresh failures pi-ai reports', async () => {
1253
+ let sdkDir = await realpath(fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent')));
1254
+ while (!sdkDir.endsWith('/pi-coding-agent')) sdkDir = dirname(sdkDir);
1255
+ const { refreshStoredOAuthCredential } = await import(pathToFileURL(join(dirname(sdkDir), 'pi-ai', 'dist', 'auth', 'resolve.js')).href);
1256
+ const piError = async (credentials) => {
1257
+ try {
1258
+ await refreshStoredOAuthCredential(
1259
+ credentials,
1260
+ 'anthropic',
1261
+ { refresh: async () => { throw new Error('invalid_grant'); } },
1262
+ () => true,
1263
+ new AbortController().signal,
1264
+ );
1265
+ } catch (error) {
1266
+ return error.message;
1267
+ }
1268
+ throw new Error('pi-ai did not fail the refresh');
1269
+ };
1270
+ const messages = [
1271
+ // The provider refused the refresh.
1272
+ await piError({ modify: async (_id, update) => update({ type: 'oauth', expires: 0 }) }),
1273
+ // auth.json is read-only in the sandbox: the store cannot be modified.
1274
+ await piError({ modify: async () => { throw Object.assign(new Error('EACCES'), { code: 'EACCES' }); } }),
1275
+ ];
1276
+ // pi-ai appends the cause (`...: invalid_grant`).
1277
+ expect(messages[0]).toMatch(/^OAuth refresh failed for anthropic\b/);
1278
+ expect(messages[1]).toMatch(/^Credential store modify failed for anthropic\b/);
1279
+
1280
+ let refreshes = 0;
1281
+ const ctx = await setup({ mainAnswers: { 'providers.oauth.refresh': async () => { refreshes += 1; return {}; } } });
1282
+ await ctx.sandboxOn();
1283
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1284
+ const [box] = ctx.launched;
1285
+ const waitFor = async (predicate) => {
1286
+ for (let tries = 0; tries < 200 && !predicate(); tries += 1) await new Promise((resolve) => setTimeout(resolve, 5));
1287
+ };
1288
+ await waitFor(() => box.subscriptions.some((item) => !item.closed));
1289
+ expect(refreshes).toBe(1);
1290
+ for (const [index, message] of messages.entries()) {
1291
+ box.emit('session.error', 10 + index, { code: 'ASSISTANT_ERROR', message });
1292
+ await waitFor(() => refreshes === index + 2);
1293
+ expect(refreshes).toBe(index + 2);
1294
+ // Let the shared (single-flight) refresh settle before the next error.
1295
+ await new Promise((resolve) => setTimeout(resolve, 20));
1296
+ }
1297
+ });
1298
+
1299
+ it('accepts a send made with the old daemon\'s epoch right after its session moved', async () => {
1300
+ const ctx = await setup({
1301
+ mainAnswers: { 'sessions.release': (p) => ({ released: [{ sessionId: 's-1', directory: p.directories[0] }], pending: [], streamEpoch: 'epoch-main' }) },
1302
+ sandboxAnswers: {
1303
+ 'runtime.health': { state: 'ready', residentSessions: 1, streamEpoch: 'epoch-box' },
1304
+ 'sessions.prompt': (p) => {
1305
+ if (p.streamEpoch !== 'epoch-box') throw daemonError('STALE_STREAM_EPOCH');
1306
+ return { accepted: true, messageId: 'm-1' };
1307
+ },
1308
+ },
1309
+ });
1310
+ await ctx.sandboxOn();
1311
+ const send = (sessionId, streamEpoch) => ctx.call(`/api/pi/sessions/${sessionId}/prompt`, {
1312
+ method: 'POST',
1313
+ body: { directory: ctx.projectA, text: 'hi', streamEpoch },
1314
+ });
1315
+ expect((await send('s-1', 'epoch-main')).status).toBe(202);
1316
+ // Only the moved session, and only its old daemon's epoch.
1317
+ expect((await send('s-1', 'epoch-older')).status).toBe(409);
1318
+ expect((await send('s-2', 'epoch-main')).status).toBe(409);
1319
+ });
1320
+
1321
+ it('looks up a send receipt in the daemon still running a session that waits to switch', async () => {
1322
+ const ctx = await setup({
1323
+ mainAnswers: {
1324
+ 'sessions.release': (p) => ({ released: [], pending: [{ sessionId: 's-1', directory: p.directories[0] }], streamEpoch: 'epoch-main' }),
1325
+ 'sessions.sendReceipt': { status: 'accepted', receipt: { messageId: 'm-1' } },
1326
+ },
1327
+ });
1328
+ await ctx.sandboxOn();
1329
+ const response = await ctx.call(`/api/pi/sessions/s-1/send-receipt?directory=${ctx.projectA}`, {
1330
+ method: 'POST',
1331
+ body: { kind: 'prompt', operationId: 'op-1', streamEpoch: 'epoch-main' },
1332
+ });
1333
+ expect(await response.json()).toEqual({ status: 'accepted', receipt: { messageId: 'm-1' } });
1334
+ expect(ctx.launched).toEqual([]);
1335
+ });
1336
+ });
1337
+
1338
+ describe('keeping a sandboxed project owned', () => {
1339
+ let server;
1340
+ let manager;
1341
+ afterEach(async () => {
1342
+ await manager?.stop();
1343
+ manager = undefined;
1344
+ await close(server);
1345
+ server = undefined;
1346
+ });
1347
+
1348
+ const setup = async (options = {}) => {
1349
+ const built = await buildSandboxRoutes(options);
1350
+ server = built.server;
1351
+ manager = built.manager;
1352
+ return built;
1353
+ };
1354
+
1355
+ const transcript = async (ctx, storedFor, id, headerCwd) => {
1356
+ const sessions = getPiSessionDirectory({ cwd: storedFor, agentDir: ctx.agentDir });
1357
+ await mkdir(sessions, { recursive: true });
1358
+ await writeFile(join(sessions, `2026-01-01_${id}.jsonl`), `${JSON.stringify({ type: 'session', id, cwd: headerCwd, timestamp: '2026-01-01T00:00:00.000Z' })}\n`);
1359
+ };
1360
+
1361
+ const until = async (predicate) => {
1362
+ for (let attempt = 0; attempt < 400 && !await predicate(); attempt += 1) await new Promise((resolve) => setTimeout(resolve, 5));
1363
+ };
1364
+
1365
+ // A sandbox daemon is not trusted to say which sessions are its own.
1366
+ it('ignores another project\'s session in a draining sandbox daemon\'s answer', async () => {
1367
+ let busy = true;
1368
+ const ctx = await setup({
1369
+ sandboxAnswers: {
1370
+ 'sessions.release': (p) => ({
1371
+ released: [],
1372
+ // s-1 is its own; s-b belongs to the unsandboxed project B, and
1373
+ // the daemon claims it runs in its own folder.
1374
+ pending: busy
1375
+ ? [{ sessionId: 's-1', directory: p.directories[0] }, { sessionId: 's-b', directory: p.directories[0] }]
1376
+ : [{ sessionId: 's-b', directory: p.directories[0] }],
1377
+ streamEpoch: 'epoch-box',
1378
+ }),
1379
+ },
1380
+ });
1381
+ await transcript(ctx, ctx.projectB, 's-b', ctx.projectB);
1382
+ await ctx.sandboxOn();
1383
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1384
+ await ctx.sandboxOn('proj-a', { mode: 'off' });
1385
+ await until(() => ctx.manager.drainingSession('s-1'));
1386
+
1387
+ expect(ctx.manager.drainingSession('s-b')).toBeNull();
1388
+ expect(await ctx.manager.sessionOnDaemon('sandbox:proj-a', 's-b', ctx.projectA)).toBe(false);
1389
+ expect(await ctx.manager.sessionOnDaemon('sandbox:proj-a', 's-1', ctx.projectA)).toBe(true);
1390
+ // Project B's session still runs in the main daemon.
1391
+ await ctx.call('/api/pi/sessions/s-b/prompt', { method: 'POST', body: { directory: ctx.projectB, text: 'hi', streamEpoch: 'epoch-1' } });
1392
+ expect(ctx.main.commands()).toContain('sessions.prompt');
1393
+ expect(ctx.launched[0].commands()).not.toContain('sessions.prompt');
1394
+
1395
+ // The claim does not keep the drain open either.
1396
+ busy = false;
1397
+ await ctx.tick(1_000);
1398
+ await until(() => ctx.pool.live().length === 1);
1399
+ expect(ctx.launched[0].stopped).toBe(true);
1400
+ });
1401
+
1402
+ it('routes a session by its real transcript when a sandboxed project holds a planted copy', async () => {
1403
+ const ctx = await setup({ probe: { available: false, code: 'NOT_INSTALLED' } });
1404
+ await ctx.sandboxOn();
1405
+ // Project A's sandbox wrote a transcript with the id of B's session.
1406
+ await transcript(ctx, ctx.projectA, 's-b', ctx.projectA);
1407
+ await transcript(ctx, ctx.projectB, 's-b', ctx.projectB);
1408
+ expect(await ctx.manager.directoryForSession('s-b')).toBe(ctx.projectB);
1409
+ const response = await ctx.call('/api/pi/sessions/s-b/prompt', { method: 'POST', body: { text: 'hi', streamEpoch: 'epoch-1' } });
1410
+ // The fake daemon's answer is not a real one; that it was asked is the point.
1411
+ expect((await response.json()).error?.code).not.toBe('SANDBOX_UNAVAILABLE');
1412
+ expect(ctx.main.commands()).toContain('sessions.prompt');
1413
+ });
1414
+
1415
+ it('tells the main daemon to stay out of a project before it asks it to let go', async () => {
1416
+ let recorded;
1417
+ const ctx = await setup({
1418
+ mainAnswers: {
1419
+ 'sessions.release': () => {
1420
+ recorded ??= JSON.parse(readFileSync(sandboxedFoldersFile(recordDataDir), 'utf8'));
1421
+ return { released: [], pending: [] };
1422
+ },
1423
+ },
1424
+ });
1425
+ const recordDataDir = ctx.dataDir;
1426
+ await ctx.sandboxOn();
1427
+ expect(JSON.stringify(recorded)).toContain(ctx.projectA);
1428
+ });
1429
+
1430
+ it.skipIf(process.platform === 'win32')('does not wait on a project id file the sandbox turned into a FIFO', async () => {
1431
+ const ctx = await setup();
1432
+ await rm(join(ctx.projectB, '.git', 'pichamber'), { force: true });
1433
+ await mkdir(join(ctx.projectB, '.git'), { recursive: true });
1434
+ execFileSync('mkfifo', [join(ctx.projectB, '.git', 'pichamber')]);
1435
+ const saved = await Promise.race([
1436
+ ctx.sandboxOn('proj-b'),
1437
+ new Promise((resolve) => setTimeout(() => resolve('stuck'), 3_000)),
1438
+ ]);
1439
+ expect(saved).not.toBe('stuck');
1440
+ expect(saved.status).toBe(200);
1441
+ expect(ctx.manager.sandboxFor(ctx.projectB)).toEqual({ launcher: 'nono' });
1442
+ });
1443
+
1444
+ it('two saves applied at once leave the project owned by its sandbox', async () => {
1445
+ const ctx = await setup();
1446
+ await ctx.sandboxOn();
1447
+ // Off then on, overlapping: the last stored setting is on.
1448
+ const [off, on] = await Promise.all([ctx.sandboxOn('proj-a', { mode: 'off' }), ctx.sandboxOn()]);
1449
+ expect([off.status, on.status]).toEqual([200, 200]);
1450
+ expect(ctx.manager.sandboxFor(ctx.projectA)).toEqual({ launcher: 'nono' });
1451
+ await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: ctx.projectA, text: 'hi', streamEpoch: 'epoch-1' } });
1452
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
1453
+ expect(ctx.launched.at(-1).commands()).toContain('sessions.prompt');
1454
+ });
1455
+
1456
+ it('routes a transcript stored in a sandboxed project\'s folder to its sandbox even when its header names another folder', async () => {
1457
+ const ctx = await setup({ probe: { available: false, code: 'NOT_INSTALLED' } });
1458
+ await ctx.sandboxOn();
1459
+ // The sandboxed agent can rewrite the header of its own transcript.
1460
+ await transcript(ctx, ctx.projectA, 's-9', ctx.projectB);
1461
+ for (const body of [{ text: 'hi', streamEpoch: 'epoch-1' }, { directory: ctx.projectB, text: 'hi', streamEpoch: 'epoch-1' }]) {
1462
+ const response = await ctx.call('/api/pi/sessions/s-9/prompt', { method: 'POST', body });
1463
+ expect(response.status).toBe(503);
1464
+ expect(await response.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'NOT_INSTALLED' } });
1465
+ }
1466
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
1467
+ });
1468
+
1469
+ it('routes a folder spelled with spaces or through a symlink to the project\'s sandbox', async () => {
1470
+ const ctx = await setup();
1471
+ await ctx.sandboxOn();
1472
+ const link = join(ctx.root, 'link-to-a');
1473
+ await symlink(ctx.projectA, link);
1474
+ await ctx.call('/api/pi/sessions', { method: 'POST', body: { cwd: ` ${ctx.projectA} ` } });
1475
+ await ctx.call('/api/pi/sessions', { method: 'POST', body: { cwd: link } });
1476
+ await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: ` ${ctx.projectA}`, text: 'hi', streamEpoch: 'epoch-1' } });
1477
+ const listed = await (await ctx.call(`/api/pi/sessions?directory=${encodeURIComponent(link)}`)).json();
1478
+ // The answer names the sandbox daemon's stream, not the main one.
1479
+ expect(listed.stream).toBe(publicDaemonStreamId('sandbox:proj-a'));
1480
+ await ctx.call(`/api/pi/resources?directory=${encodeURIComponent(`${ctx.projectA} `)}`);
1481
+ for (const command of ['sessions.create', 'sessions.prompt', 'sessions.list', 'resources.list']) {
1482
+ expect(ctx.main.commands()).not.toContain(command);
1483
+ }
1484
+ expect(ctx.launched).toHaveLength(1);
1485
+ expect(ctx.launched[0].commands().filter((command) => command === 'sessions.create')).toHaveLength(2);
1486
+ });
1487
+
1488
+ it('refuses a folder that is not an absolute path while a project is sandboxed', async () => {
1489
+ const ctx = await setup();
1490
+ await ctx.sandboxOn();
1491
+ const created = await ctx.call('/api/pi/sessions', { method: 'POST', body: { cwd: 'code/a' } });
1492
+ expect(created.status).toBe(400);
1493
+ const prompted = await ctx.call('/api/pi/sessions/s-1/prompt', { method: 'POST', body: { directory: './a', text: 'hi', streamEpoch: 'epoch-1' } });
1494
+ expect(prompted.status).toBe(400);
1495
+ expect(ctx.main.commands()).toEqual(['sessions.release']);
1496
+ expect(ctx.launched).toEqual([]);
1497
+ });
1498
+
1499
+ it('gives a project that had no worktrees when it was sandboxed a worktree folder of its own', async () => {
1500
+ const ctx = await setup();
1501
+ await ctx.sandboxOn('proj-b');
1502
+ // Remembered at once, from the project's path: the Git panel files the
1503
+ // project's first worktree there, whatever the agent writes meanwhile.
1504
+ const id = ownWorktreeId(ctx.projectB);
1505
+ expect(JSON.parse(await readFile(worktreeIdsFile(ctx.dataDir), 'utf8')).projects).toEqual({ [ctx.projectB]: id });
1506
+ await mkdir(join(ctx.projectB, '.git'), { recursive: true });
1507
+ await writeFile(join(ctx.projectB, '.git', 'pichamber'), 'e'.repeat(40));
1508
+ const added = join(ctx.dataDir, 'worktree', id, 'feature');
1509
+ await mkdir(added, { recursive: true });
1510
+ await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: added, text: 'hi', streamEpoch: 'epoch-1' } });
1511
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
1512
+ expect(ctx.launched).toHaveLength(1);
1513
+ expect(ctx.launched[0].sandbox.grants).toEqual(expect.arrayContaining([{ kind: 'readWrite', path: join(ctx.dataDir, 'worktree', id) }]));
1514
+ });
1515
+
1516
+ it('keeps a project\'s worktrees when its id file is rewritten or deleted', async () => {
1517
+ const ctx = await setup();
1518
+ await ctx.sandboxOn();
1519
+ const other = 'a'.repeat(40);
1520
+ const foreign = join(ctx.dataDir, 'worktree', other, 'x');
1521
+ await mkdir(foreign, { recursive: true });
1522
+ for (const change of [() => writeFile(join(ctx.projectA, '.git', 'pichamber'), other), () => rm(join(ctx.projectA, '.git', 'pichamber'))]) {
1523
+ await change();
1524
+ await ctx.manager.reconcile();
1525
+ expect(ctx.manager.sandboxFor(ctx.worktree)).toEqual({ launcher: 'nono' });
1526
+ // The rewritten id names another project's worktrees; they are not taken.
1527
+ expect(ctx.manager.sandboxFor(foreign)).toBeNull();
1528
+ }
1529
+ // A restart reads the remembered id, not the file.
1530
+ expect(JSON.parse(await readFile(worktreeIdsFile(ctx.dataDir), 'utf8')).projects).toEqual({ [ctx.projectA]: ctx.gitId });
1531
+ });
1532
+
1533
+ it('needs a reconcile before the first one has run, so a request at server start cannot reach the main daemon', async () => {
1534
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-routes-sandbox-'));
1535
+ const fresh = createProjectSandboxManager({
1536
+ daemonPool: createPiDaemonPool({ getMainRuntime: () => null }),
1537
+ uiSettingsStore: createPiUiSettingsStore({ file: join(root, 'data', 'settings.json') }),
1538
+ launcher: fakeLauncher(),
1539
+ dataDir: join(root, 'data'),
1540
+ agentDir: join(root, 'agent'),
1541
+ getServerPort: () => 3000,
1542
+ setInterval: () => 0,
1543
+ clearInterval: () => {},
1544
+ });
1545
+ expect(fresh.needsReconcile()).toBe(true);
1546
+ await fresh.reconcile();
1547
+ expect(fresh.needsReconcile()).toBe(false);
1548
+ await fresh.stop?.();
1549
+ });
1550
+
1551
+ it('resets trust again after a restart for folders still marked to ask', async () => {
1552
+ // An earlier server process recorded the mark, then stopped before the
1553
+ // main daemon had taken the reset.
1554
+ const ctx = await setup({ beforeReconcile: ({ trustAsk, projectB }) => trustAsk.add([projectB]) });
1555
+ const resets = () => ctx.main.calls.filter((c) => c.command === 'settings.set').map((c) => c.payload);
1556
+ expect(resets()).toEqual([{ scope: 'project', directory: ctx.projectB, trust: null }]);
1557
+ // Done once; later passes do not repeat it.
1558
+ await ctx.manager.reconcile();
1559
+ await ctx.tick(1000);
1560
+ expect(resets()).toHaveLength(1);
1561
+ expect(await ctx.trustAsk.list()).toEqual([ctx.projectB]);
1562
+ });
1563
+
1564
+ it('keeps two clones of one repository apart: the sandboxed one gets a worktree folder of its own', async () => {
1565
+ const ctx = await setup();
1566
+ // Project B is a second clone of A's repository: both files name the
1567
+ // repository's root commit, and B (not sandboxed) has a worktree there.
1568
+ await mkdir(join(ctx.projectB, '.git'), { recursive: true });
1569
+ await writeFile(join(ctx.projectB, '.git', 'pichamber'), ctx.gitId);
1570
+ await ctx.sandboxOn();
1571
+ const own = join(ctx.dataDir, 'worktree', ownWorktreeId(ctx.projectA));
1572
+ await mkdir(join(own, 'new'), { recursive: true });
1573
+
1574
+ const listed = await (await ctx.call('/api/pi/sandbox/projects')).json();
1575
+ expect(listed.projects.find((project) => project.projectId === 'proj-a').availability).toEqual({ state: 'available' });
1576
+ // The shared folder stays the other clone's; A's sandbox is not granted it.
1577
+ expect(ctx.manager.sandboxFor(ctx.worktree)).toBeNull();
1578
+ expect(ctx.manager.sandboxFor(join(own, 'new'))).toEqual({ launcher: 'nono' });
1579
+ await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectA}`);
1580
+ const paths = ctx.launched[0].sandbox.grants.map((grant) => grant.path);
1581
+ expect(paths).toContain(own);
1582
+ expect(paths.some((path) => path.startsWith(join(ctx.dataDir, 'worktree', ctx.gitId)))).toBe(false);
1583
+ await ctx.call(`/api/pi/sessions/s-2/prompt`, { method: 'POST', body: { directory: ctx.worktree, text: 'hi', streamEpoch: 'epoch-1' } });
1584
+ expect(ctx.main.commands()).toContain('sessions.prompt');
1585
+ });
1586
+
1587
+ it('runs nothing in a worktree the sandboxed project made before it had its own folder', async () => {
1588
+ const ctx = await setup();
1589
+ await mkdir(join(ctx.projectB, '.git'), { recursive: true });
1590
+ await writeFile(join(ctx.projectB, '.git', 'pichamber'), ctx.gitId);
1591
+ // One worktree in the shared folder is project A's, one is B's.
1592
+ const mine = join(ctx.dataDir, 'worktree', ctx.gitId, 'mine');
1593
+ await mkdir(mine, { recursive: true });
1594
+ await writeFile(join(mine, '.git'), `gitdir: ${join(ctx.projectA, '.git', 'worktrees', 'mine')}\n`);
1595
+ await writeFile(join(ctx.worktree, '.git'), `gitdir: ${join(ctx.projectB, '.git', 'worktrees', 'feature')}\n`);
1596
+ await ctx.sandboxOn();
1597
+
1598
+ expect(ctx.manager.sandboxFor(mine)).toEqual({ launcher: 'nono' });
1599
+ expect(ctx.manager.sandboxFor(ctx.worktree)).toBeNull();
1600
+ const refused = await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: mine, text: 'hi', streamEpoch: 'epoch-1' } });
1601
+ expect(await refused.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'SANDBOX_WORKTREE_OUTSIDE_FOLDER' } });
1602
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
1603
+ expect(ctx.launched).toHaveLength(0);
1604
+ // Its sessions are still listed, by the main daemon.
1605
+ expect((await ctx.call(`/api/pi/sessions?directory=${mine}`)).status).toBe(200);
1606
+ expect(ctx.launched).toHaveLength(0);
1607
+ });
1608
+
1609
+ it('starts no sandbox on an id it cannot check against the remembered ones, and keeps those worktrees off the main daemon', async () => {
1610
+ const ctx = await setup();
1611
+ // The sandboxed agent can write this file; the record that would
1612
+ // confirm it is unreadable.
1613
+ const id = 'e'.repeat(40);
1614
+ await mkdir(join(ctx.projectB, '.git'), { recursive: true });
1615
+ await writeFile(join(ctx.projectB, '.git', 'pichamber'), id);
1616
+ const claimed = join(ctx.dataDir, 'worktree', id, 'feature');
1617
+ await mkdir(claimed, { recursive: true });
1618
+ await mkdir(dirname(worktreeIdsFile(ctx.dataDir)), { recursive: true });
1619
+ await writeFile(worktreeIdsFile(ctx.dataDir), '{');
1620
+ await ctx.sandboxOn('proj-b');
1621
+ const listed = await (await ctx.call('/api/pi/sandbox/projects')).json();
1622
+ expect(listed.projects.find((project) => project.projectId === 'proj-b').availability)
1623
+ .toEqual({ state: 'unavailable', reason: 'SANDBOX_WORKTREE_IDS_UNREADABLE' });
1624
+ for (const directory of [ctx.projectB, claimed]) {
1625
+ const refused = await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory, text: 'hi', streamEpoch: 'epoch-1' } });
1626
+ expect(await refused.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'SANDBOX_WORKTREE_IDS_UNREADABLE' } });
1627
+ }
1628
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
1629
+ expect(ctx.launched).toHaveLength(0);
1630
+ // Once the record can be read again the project runs.
1631
+ await rm(worktreeIdsFile(ctx.dataDir));
1632
+ await ctx.manager.reconcile();
1633
+ await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: ctx.projectB, text: 'hi', streamEpoch: 'epoch-1' } });
1634
+ expect(ctx.launched).toHaveLength(1);
1635
+ });
1636
+
1637
+ it('refuses Pi-running commands while the stored settings could not be applied, and recovers on the next request', async () => {
1638
+ const ctx = await setup();
1639
+ await ctx.sandboxOn();
1640
+ const read = ctx.uiSettingsStore.read;
1641
+ ctx.uiSettingsStore.read = async () => { throw new Error('unreadable'); };
1642
+ await expect(ctx.manager.reconcile()).rejects.toThrow();
1643
+ const refused = await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: ctx.projectB, text: 'hi', streamEpoch: 'epoch-1' } });
1644
+ expect(refused.status).toBe(503);
1645
+ expect(await refused.json()).toEqual({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'SANDBOX_SETTINGS_UNREADABLE' } });
1646
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
1647
+ // The sandbox pages stay reachable so the cause can be seen and fixed.
1648
+ expect((await ctx.call('/api/pi/sandbox')).status).toBe(200);
1649
+
1650
+ ctx.uiSettingsStore.read = read;
1651
+ const served = await ctx.call(`/api/pi/sessions/s-1?directory=${ctx.projectB}`);
1652
+ expect(served.status).toBe(200);
1653
+ expect(ctx.manager.needsReconcile()).toBe(false);
1654
+ });
1655
+
1656
+ it('answers a stored save as saved when applying it fails, and applies it before the next Pi command', async () => {
1657
+ const ctx = await setup();
1658
+ const register = ctx.pool.register;
1659
+ ctx.pool.register = () => {
1660
+ ctx.pool.register = register;
1661
+ throw new Error('register failed');
1662
+ };
1663
+ const saved = await ctx.sandboxOn();
1664
+ expect(saved.status).toBe(200);
1665
+ expect(ctx.manager.needsReconcile()).toBe(true);
1666
+ await ctx.call(`/api/pi/sessions/s-1/prompt`, { method: 'POST', body: { directory: ctx.projectA, text: 'hi', streamEpoch: 'epoch-1' } });
1667
+ expect(ctx.main.commands()).not.toContain('sessions.prompt');
1668
+ expect(ctx.launched).toHaveLength(1);
1669
+ });
1670
+
1671
+ it('changes only the fields a default save names', async () => {
1672
+ const ctx = await setup();
1673
+ const put = (body) => ctx.call('/api/pi/sandbox/defaults', { method: 'PUT', body });
1674
+ await put({ mode: 'nono', allowHosts: ['github.com'] });
1675
+ // A page loaded before the default was turned on adds a host.
1676
+ expect((await (await put({ allowHosts: ['github.com', 'registry.npmjs.org'] })).json()).defaults)
1677
+ .toEqual({ mode: 'nono', allowHosts: ['github.com', 'registry.npmjs.org'], acceptedLimits: [] });
1678
+ expect((await (await put({ mode: 'off' })).json()).defaults)
1679
+ .toEqual({ mode: 'off', allowHosts: ['github.com', 'registry.npmjs.org'], acceptedLimits: [] });
1680
+ expect((await ctx.call('/api/pi/sandbox/defaults', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: undefined })).status).toBe(400);
1681
+ expect((await put({ note: 'x' })).status).toBe(400);
1682
+ expect((await put({ mode: 'nono', allowHosts: 'github.com' })).status).toBe(400);
1683
+ });
1684
+ });