@firstpick/pi-package-webui 0.11.0 → 0.11.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 (318) hide show
  1. package/DEVELOPMENT.md +181 -12
  2. package/README.md +41 -9
  3. package/TECHNICAL.md +91 -8
  4. package/bin/pi-webui.mjs +5432 -11428
  5. package/index.ts +10 -3
  6. package/lib/codex-cli-usage.mjs +232 -0
  7. package/lib/codex-usage-auth.mjs +39 -3
  8. package/lib/codex-usage-source.mjs +36 -0
  9. package/lib/component-update-state.mjs +2 -2
  10. package/lib/git-workflow-preference-values.mjs +122 -0
  11. package/lib/git-workflow-preferences.mjs +35 -563
  12. package/lib/package-updates.mjs +260 -0
  13. package/lib/rpc-supervisor-client.mjs +8 -4
  14. package/lib/server/app-runners.mjs +1667 -0
  15. package/lib/server/codex-fast-mode.mjs +161 -0
  16. package/lib/server/conversation-mode.mjs +218 -0
  17. package/lib/server/conversation-voice.mjs +318 -0
  18. package/lib/server/extension-ui-requests.mjs +114 -0
  19. package/lib/server/git-generation.mjs +459 -0
  20. package/lib/server/git-mutations.mjs +1827 -0
  21. package/lib/server/git-reads.mjs +608 -0
  22. package/lib/server/git-worktree-sessions.mjs +408 -0
  23. package/lib/server/helper-requests.mjs +82 -0
  24. package/lib/server/no-project-workspaces.mjs +103 -0
  25. package/lib/server/rpc-transports.mjs +394 -0
  26. package/lib/server/settings-store.mjs +544 -0
  27. package/lib/server/sse-delivery.mjs +138 -0
  28. package/lib/server/workspace-files.mjs +563 -0
  29. package/lib/update/supervisor.mjs +4 -0
  30. package/lib/webui-workspaces.mjs +2 -0
  31. package/package.json +5 -5
  32. package/public/activity-agents-controller.mjs +269 -0
  33. package/public/activity-events-controller.mjs +236 -0
  34. package/public/activity-intercom-controller.mjs +627 -0
  35. package/public/activity-queue-controller.mjs +534 -0
  36. package/public/activity-todo-view.mjs +89 -0
  37. package/public/activity-usage-controller.mjs +589 -0
  38. package/public/app.js +3761 -3878
  39. package/public/conversation-overview.css +84 -0
  40. package/public/conversation-overview.mjs +193 -0
  41. package/public/draft-conversations.mjs +135 -0
  42. package/public/focused-composer-controls.css +111 -0
  43. package/public/focused-composer-controls.mjs +143 -0
  44. package/public/focused-composer-disclosure.mjs +223 -0
  45. package/public/focused-shell-adapter.css +264 -0
  46. package/public/focused-shell-adapter.mjs +257 -0
  47. package/public/index.html +137 -80
  48. package/public/model-catalog-order.mjs +63 -0
  49. package/public/platform-event-stream.mjs +64 -0
  50. package/public/project-artifact-controller.mjs +218 -0
  51. package/public/project-file-viewer-controller.mjs +383 -0
  52. package/public/project-git-tools-controller.mjs +181 -0
  53. package/public/project-runners-controller.mjs +220 -0
  54. package/public/service-worker.js +52 -1
  55. package/public/session-attention-scheduler.mjs +182 -0
  56. package/public/session-composer-store.mjs +56 -0
  57. package/public/session-context.mjs +51 -0
  58. package/public/session-extension-requests.mjs +63 -0
  59. package/public/session-shelf-state.mjs +151 -0
  60. package/public/session-shelves.css +171 -0
  61. package/public/session-shelves.mjs +95 -0
  62. package/public/settings-navigation-controller.mjs +249 -0
  63. package/public/settings-navigation.css +61 -0
  64. package/public/settings-resource-controller.mjs +232 -0
  65. package/public/settings-workspace.css +19 -0
  66. package/public/settings-workspace.mjs +175 -0
  67. package/public/shell-actions.mjs +87 -0
  68. package/public/shell-attention-inbox.css +72 -0
  69. package/public/shell-attention-inbox.mjs +198 -0
  70. package/public/shell-context-actions.css +61 -0
  71. package/public/shell-context-actions.mjs +168 -0
  72. package/public/shell-inspector-resize.mjs +124 -0
  73. package/public/shell-navigation-resize.mjs +107 -0
  74. package/public/shell-navigation.mjs +127 -0
  75. package/public/shell-preferences.mjs +108 -0
  76. package/public/shell-surfaces.mjs +99 -0
  77. package/public/shell-tools-launcher.css +97 -0
  78. package/public/shell-tools-launcher.mjs +222 -0
  79. package/public/shell-view-host.mjs +115 -0
  80. package/public/shell-workspace.css +266 -0
  81. package/public/shell-workspace.mjs +402 -0
  82. package/public/sidebar-update-menu.css +190 -0
  83. package/public/sidebar-update-menu.mjs +512 -0
  84. package/public/styles.css +320 -169
  85. package/public/subagent-launch-slot-state.mjs +2 -2
  86. package/public/theme-contract.mjs +1 -1
  87. package/public/themed-selects.css +156 -0
  88. package/public/workspace-choices.mjs +104 -0
  89. package/tests/activity-agents-controller.test.mjs +652 -0
  90. package/tests/activity-events-controller.test.mjs +511 -0
  91. package/tests/app-runner-terminal-static.test.mjs +3 -3
  92. package/tests/append-system-http.test.mjs +7 -6
  93. package/tests/append-system-selector-static.test.mjs +6 -6
  94. package/tests/aur-review-widget-static.test.mjs +11 -3
  95. package/tests/boot-failure-diagnostics.test.mjs +8 -3
  96. package/tests/browser/activity-intercom-controller.spec.mjs +457 -0
  97. package/tests/browser/activity-navigation-integration.spec.mjs +45 -0
  98. package/tests/browser/activity-owner-integration.spec.mjs +201 -0
  99. package/tests/browser/activity-queue-controller.spec.mjs +405 -0
  100. package/tests/browser/activity-section-picker.spec.mjs +294 -0
  101. package/tests/browser/activity-todo-view.spec.mjs +60 -0
  102. package/tests/browser/activity-usage-controller.spec.mjs +416 -0
  103. package/tests/browser/compact-layout-integration.spec.mjs +58 -0
  104. package/tests/browser/composer-action-grid-reorder.spec.mjs +16 -0
  105. package/tests/browser/composer-disclosure.spec.mjs +389 -0
  106. package/tests/browser/composer-toolbar-polish.spec.mjs +343 -0
  107. package/tests/browser/control-deck-component-updates.spec.mjs +5 -14
  108. package/tests/browser/control-deck-side-panels.spec.mjs +27 -12
  109. package/tests/browser/control-visibility.spec.mjs +5 -0
  110. package/tests/browser/controls-layout.spec.mjs +21 -2
  111. package/tests/browser/conversation-overview.spec.mjs +251 -0
  112. package/tests/browser/draft-conversations.spec.mjs +276 -0
  113. package/tests/browser/empty-startup-fixture.mjs +135 -0
  114. package/tests/browser/empty-startup.spec.mjs +282 -0
  115. package/tests/browser/events-tree-context-menu.spec.mjs +1 -0
  116. package/tests/browser/focused-composer-more.spec.mjs +127 -0
  117. package/tests/browser/focused-model-shortcuts.spec.mjs +120 -0
  118. package/tests/browser/focused-navigation-fixture.mjs +32 -0
  119. package/tests/browser/focused-project-activity.spec.mjs +111 -0
  120. package/tests/browser/focused-shell-integration.spec.mjs +208 -0
  121. package/tests/browser/folder-picker-layout-fixture.mjs +13 -0
  122. package/tests/browser/folder-picker-layout.spec.mjs +302 -0
  123. package/tests/browser/footer-model-advanced-layout.spec.mjs +27 -14
  124. package/tests/browser/git-setup-cancel.spec.mjs +251 -0
  125. package/tests/browser/guided-git-fallback.spec.mjs +40 -21
  126. package/tests/browser/inspector-header.spec.mjs +221 -0
  127. package/tests/browser/inspector-overview-integration.spec.mjs +104 -0
  128. package/tests/browser/inspector-resize.spec.mjs +227 -0
  129. package/tests/browser/inspector-topic-overflow.spec.mjs +56 -0
  130. package/tests/browser/interaction-action-discovery.spec.mjs +332 -0
  131. package/tests/browser/interaction-attention-inbox.spec.mjs +364 -0
  132. package/tests/browser/interaction-attention-integration.spec.mjs +53 -0
  133. package/tests/browser/interaction-composer-controls.spec.mjs +267 -0
  134. package/tests/browser/interaction-composer-integration.spec.mjs +175 -0
  135. package/tests/browser/interaction-continuity.spec.mjs +50 -26
  136. package/tests/browser/interaction-model-picker.spec.mjs +86 -0
  137. package/tests/browser/last-terminal-close.spec.mjs +280 -0
  138. package/tests/browser/mobile-foundation.spec.mjs +172 -20
  139. package/tests/browser/model-catalog-groups.spec.mjs +104 -0
  140. package/tests/browser/more-row-menus.spec.mjs +258 -0
  141. package/tests/browser/new-tab-hit-target.spec.mjs +228 -0
  142. package/tests/browser/no-project-conversation.spec.mjs +113 -0
  143. package/tests/browser/optimistic-prompt.spec.mjs +3 -0
  144. package/tests/browser/overhaul-w7-accessibility.spec.mjs +227 -0
  145. package/tests/browser/overhaul-w7-capabilities.spec.mjs +298 -0
  146. package/tests/browser/overhaul-w7-companions.spec.mjs +290 -0
  147. package/tests/browser/overhaul-w7-focus-repairs.spec.mjs +210 -0
  148. package/tests/browser/overhaul-w7-layout-repairs.spec.mjs +183 -0
  149. package/tests/browser/overhaul-w7-parent-repairs.spec.mjs +97 -0
  150. package/tests/browser/overhaul-w7-pwa.spec.mjs +247 -0
  151. package/tests/browser/overhaul-w7-responsive.spec.mjs +450 -0
  152. package/tests/browser/overhaul-w7-update.spec.mjs +215 -0
  153. package/tests/browser/overhaul-w7-zoom.spec.mjs +243 -0
  154. package/tests/browser/overview-agent-ownership.spec.mjs +45 -0
  155. package/tests/browser/persistent-ui-layout.spec.mjs +3 -0
  156. package/tests/browser/project-artifact-controller.spec.mjs +324 -0
  157. package/tests/browser/project-artifact-integration.spec.mjs +103 -0
  158. package/tests/browser/project-file-buffer-integration.spec.mjs +230 -0
  159. package/tests/browser/project-git-tools-integration.spec.mjs +369 -0
  160. package/tests/browser/session-fixture.mjs +118 -0
  161. package/tests/browser/session-ownership.spec.mjs +175 -0
  162. package/tests/browser/session-shelves-integration.spec.mjs +219 -0
  163. package/tests/browser/session-shelves.spec.mjs +340 -0
  164. package/tests/browser/session-sidebar-resize.spec.mjs +138 -0
  165. package/tests/browser/session-summary.spec.mjs +17 -12
  166. package/tests/browser/settings-complete-home.spec.mjs +463 -0
  167. package/tests/browser/settings-entrypoint.spec.mjs +104 -0
  168. package/tests/browser/settings-navigation-controller.spec.mjs +383 -0
  169. package/tests/browser/settings-navigation-integration.spec.mjs +348 -0
  170. package/tests/browser/settings-resource-lifetime.spec.mjs +349 -0
  171. package/tests/browser/settings-workspace-integration.spec.mjs +132 -0
  172. package/tests/browser/shell-ownership.spec.mjs +398 -0
  173. package/tests/browser/shell-rollout-fixture.mjs +259 -0
  174. package/tests/browser/shell-rollout.spec.mjs +357 -0
  175. package/tests/browser/shell-tools-launcher.spec.mjs +260 -0
  176. package/tests/browser/shell-workspace.spec.mjs +433 -0
  177. package/tests/browser/side-panel-section-reorder.spec.mjs +3 -1
  178. package/tests/browser/sidebar-floating-tooltips.spec.mjs +37 -0
  179. package/tests/browser/sidebar-update-integration.spec.mjs +277 -0
  180. package/tests/browser/sidebar-update-menu.spec.mjs +402 -0
  181. package/tests/browser/sidebar-update-progress.spec.mjs +472 -0
  182. package/tests/browser/stream-output-isolation.spec.mjs +6 -3
  183. package/tests/browser/themed-selects.spec.mjs +297 -0
  184. package/tests/browser/thread-start-flow.spec.mjs +481 -0
  185. package/tests/browser/ui-polish-activity-controls.spec.mjs +177 -0
  186. package/tests/browser/ui-polish-features.spec.mjs +85 -0
  187. package/tests/browser/ui-polish-file-header.spec.mjs +43 -0
  188. package/tests/browser/ui-polish-local-git.spec.mjs +183 -0
  189. package/tests/browser/ui-polish-mobile-recovery.spec.mjs +36 -0
  190. package/tests/browser/ui-polish-navigation.spec.mjs +127 -0
  191. package/tests/browser/ui-polish-session-actions.spec.mjs +282 -0
  192. package/tests/browser/user-noticeable-fixes.spec.mjs +10 -3
  193. package/tests/browser/windows-drive-parent.spec.mjs +4 -2
  194. package/tests/browser/workspace-draft-selection.spec.mjs +266 -0
  195. package/tests/codex-cli-usage.test.mjs +189 -0
  196. package/tests/codex-fast-mode-static.test.mjs +16 -11
  197. package/tests/codex-speed-mode-browser-state.test.mjs +6 -3
  198. package/tests/codex-usage-auth.test.mjs +168 -9
  199. package/tests/codex-usage-http.test.mjs +124 -0
  200. package/tests/codex-usage-source.test.mjs +146 -0
  201. package/tests/component-update-api-static.test.mjs +2 -2
  202. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  203. package/tests/control-deck-component-updates-static.test.mjs +9 -4
  204. package/tests/control-visibility-static.test.mjs +3 -3
  205. package/tests/controls-layout-static.test.mjs +5 -5
  206. package/tests/conversation-overview-adapter.test.mjs +100 -0
  207. package/tests/document-artifact-static.test.mjs +2 -1
  208. package/tests/draft-conversations.test.mjs +205 -0
  209. package/tests/empty-startup-launcher.test.mjs +197 -0
  210. package/tests/events-tree-context-menu-static.test.mjs +22 -18
  211. package/tests/fake-pi-session-ownership.test.mjs +302 -0
  212. package/tests/fast-mode-client-static.test.mjs +1 -1
  213. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  214. package/tests/feature-system-prompt-optional-feature-static.test.mjs +1 -1
  215. package/tests/file-viewer-image-static.test.mjs +15 -11
  216. package/tests/file-viewer-search-static.test.mjs +5 -5
  217. package/tests/fixtures/fake-codex-app-server.mjs +61 -0
  218. package/tests/fixtures/fake-pi.mjs +41 -9
  219. package/tests/footer-provider-usage-visual-static.test.mjs +7 -6
  220. package/tests/foreground-transcript-catch-up-static.test.mjs +7 -4
  221. package/tests/git-footer-context-menu-static.test.mjs +1 -1
  222. package/tests/git-panel-file-preview-static.test.mjs +41 -48
  223. package/tests/git-panel-live-updates-static.test.mjs +2 -1
  224. package/tests/git-workflow-dispatch.test.mjs +66 -0
  225. package/tests/git-workflow-preferences.test.mjs +9 -1
  226. package/tests/guided-git-activation-static.test.mjs +14 -11
  227. package/tests/guided-git-fallback-ui-static.test.mjs +8 -5
  228. package/tests/guided-git-message-reliability-static.test.mjs +10 -6
  229. package/tests/guided-git-publication-backend-static.test.mjs +16 -11
  230. package/tests/http-endpoints-harness.test.mjs +29 -9
  231. package/tests/interaction-state-stability-static.test.mjs +4 -3
  232. package/tests/intercom-conversation-viewer-static.test.mjs +29 -17
  233. package/tests/intercom-tag-layout-static.test.mjs +13 -12
  234. package/tests/intercom-tag-overflow-layout.test.mjs +11 -10
  235. package/tests/main-output-loading-static.test.mjs +4 -4
  236. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  237. package/tests/mobile-compact-layout.test.mjs +2 -2
  238. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  239. package/tests/mobile-foundation-static.test.mjs +10 -7
  240. package/tests/mobile-phone-experience-static.test.mjs +3 -2
  241. package/tests/mobile-static.test.mjs +173 -135
  242. package/tests/model-catalog-order.test.mjs +103 -0
  243. package/tests/native-parity.test.mjs +6 -4
  244. package/tests/native-session-choice-owner.test.mjs +102 -0
  245. package/tests/native-update-lifecycle.test.mjs +10 -5
  246. package/tests/no-project-http-harness.test.mjs +328 -0
  247. package/tests/no-project-navigation.test.mjs +54 -0
  248. package/tests/no-project-workspaces.test.mjs +77 -0
  249. package/tests/open-issue-wizard-static.test.mjs +1 -1
  250. package/tests/optional-feature-migration-frontend.test.mjs +4 -4
  251. package/tests/optional-feature-prompt-impact-static.test.mjs +3 -3
  252. package/tests/package-updates.test.mjs +630 -0
  253. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  254. package/tests/platform-event-stream.test.mjs +253 -0
  255. package/tests/project-file-viewer-controller.test.mjs +652 -0
  256. package/tests/project-git-tools-adapter.test.mjs +103 -0
  257. package/tests/project-git-tools-controller.test.mjs +577 -0
  258. package/tests/project-runners-controller.test.mjs +453 -0
  259. package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
  260. package/tests/prompt-routing-input-clear-static.test.mjs +2 -2
  261. package/tests/questionnaire-dialog.test.mjs +6 -6
  262. package/tests/queue-edit-reorder-static.test.mjs +48 -51
  263. package/tests/rpc-supervisor-host.test.mjs +4 -1
  264. package/tests/safety-guard-auto-review-static.test.mjs +1 -1
  265. package/tests/sampling-native-controls-user-flow.test.mjs +7 -1
  266. package/tests/server-app-runners.test.mjs +536 -0
  267. package/tests/server-codex-fast-mode.test.mjs +346 -0
  268. package/tests/server-conversation-mode.test.mjs +386 -0
  269. package/tests/server-conversation-voice.test.mjs +426 -0
  270. package/tests/server-extension-ui-requests.test.mjs +357 -0
  271. package/tests/server-git-generation.test.mjs +558 -0
  272. package/tests/server-git-mutations.test.mjs +729 -0
  273. package/tests/server-git-reads.test.mjs +381 -0
  274. package/tests/server-git-worktree-sessions.test.mjs +502 -0
  275. package/tests/server-helper-requests.test.mjs +364 -0
  276. package/tests/server-rpc-transports.test.mjs +553 -0
  277. package/tests/server-settings-store.test.mjs +132 -0
  278. package/tests/server-shell-rollout.test.mjs +478 -0
  279. package/tests/server-sse-delivery.test.mjs +410 -0
  280. package/tests/server-workspace-files.test.mjs +546 -0
  281. package/tests/session-attention-scheduler.test.mjs +514 -0
  282. package/tests/session-composer-store.test.mjs +153 -0
  283. package/tests/session-context.test.mjs +134 -0
  284. package/tests/session-extension-requests.test.mjs +193 -0
  285. package/tests/session-ownership-adapter.test.mjs +130 -0
  286. package/tests/session-sampling-ui-static.test.mjs +10 -4
  287. package/tests/session-send-lifetime.test.mjs +140 -0
  288. package/tests/session-shelf-state.test.mjs +348 -0
  289. package/tests/session-shelves-adapter.test.mjs +79 -0
  290. package/tests/session-summary-lifetime.test.mjs +54 -0
  291. package/tests/settings-resource-controller.test.mjs +548 -0
  292. package/tests/shell-action-adapter.test.mjs +169 -0
  293. package/tests/shell-actions.test.mjs +182 -0
  294. package/tests/shell-navigation.test.mjs +348 -0
  295. package/tests/shell-preferences.test.mjs +367 -0
  296. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  297. package/tests/stream-output-isolation-static.test.mjs +1 -1
  298. package/tests/subagent-gate-visibility.test.mjs +1 -1
  299. package/tests/subagent-launch-slot-state.test.mjs +2 -2
  300. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  301. package/tests/subagent-observability-static.test.mjs +2 -2
  302. package/tests/subagent-reliability-integration.test.mjs +13 -30
  303. package/tests/syntax-highlighting-static.test.mjs +3 -3
  304. package/tests/tab-close-continuity-static.test.mjs +1 -1
  305. package/tests/tab-metadata-ordering.test.mjs +99 -0
  306. package/tests/terminal-cwd-grouping-static.test.mjs +2 -2
  307. package/tests/terminal-tab-prompt-tooltip-static.test.mjs +2 -0
  308. package/tests/terminal-tab-workspace-static.test.mjs +5 -4
  309. package/tests/terminal-tabs-resize-static.test.mjs +1 -1
  310. package/tests/theme-contract.test.mjs +10 -3
  311. package/tests/theme-customizer-static.test.mjs +1 -1
  312. package/tests/thread-display-title.test.mjs +44 -0
  313. package/tests/update-api-harness.test.mjs +15 -14
  314. package/tests/update-tab-restore-harness.test.mjs +3 -0
  315. package/tests/webui-settings-locking.test.mjs +2 -2
  316. package/tests/windows-drive-cwd-picker-static.test.mjs +7 -9
  317. package/tests/workspace-choices.test.mjs +114 -0
  318. package/tests/workspace-save-load-static.test.mjs +7 -4
@@ -0,0 +1,630 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { createServer } from "node:net";
4
+ import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { createPackageUpdates, runPackageCommand } from "../lib/package-updates.mjs";
10
+ import { validateUpdatePlanRequest } from "../lib/component-update-state.mjs";
11
+
12
+ const WEBUI = "@firstpick/pi-package-webui";
13
+ const SOURCE = `npm:${WEBUI}`;
14
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
15
+ const root = await mkdtemp(path.join(tmpdir(), "pi-package-updates-"));
16
+ const environment = { ...process.env, HOME: path.join(root, "home"), XDG_CONFIG_HOME: path.join(root, "config"),
17
+ XDG_CACHE_HOME: path.join(root, "cache"), XDG_STATE_HOME: path.join(root, "state"),
18
+ XDG_DATA_HOME: path.join(root, "data"), npm_config_cache: path.join(root, "cache", "npm"),
19
+ GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null",
20
+ NODE_ENV: "test", PI_OFFLINE: "1", PI_WEBUI_RPC_SUPERVISOR: "0" };
21
+
22
+ async function installed(modules) {
23
+ const directory = path.join(modules, ...WEBUI.split("/"));
24
+ await mkdir(directory, { recursive: true });
25
+ // Version, settings, ownership and command capabilities are deliberately irrelevant.
26
+ await writeFile(path.join(directory, "package.json"), "{}");
27
+ return directory;
28
+ }
29
+
30
+ async function finished(service, id) {
31
+ for (let attempt = 0; attempt < 200; attempt++) {
32
+ const job = service.getJob(id);
33
+ if (job.phase !== "running") return job;
34
+ await delay(10);
35
+ }
36
+ throw new Error(`Fixture update did not finish: ${id}`);
37
+ }
38
+
39
+ for (const requested of ["all", "webui", "pi"]) {
40
+ assert.deepEqual(validateUpdatePlanRequest({ targets: [requested] }), { ok: true, targets: [requested] });
41
+ }
42
+ for (const invalid of [null, [], {}, { targets: [] }, { targets: ["pi", "webui"] }, { targets: ["all", "pi"] },
43
+ { targets: ["pi", "pi"] }, { targets: ["npm"] }, { targets: [null] }, { targets: ["pi; echo bad"] },
44
+ { targets: ["pi"], command: "npm install" }, { targets: "all" }]) {
45
+ assert.equal(validateUpdatePlanRequest(invalid).ok, false, JSON.stringify(invalid));
46
+ }
47
+
48
+ try {
49
+ await mkdir(environment.HOME, { recursive: true });
50
+ for (const locations of [[], ["user"], ["global"], ["user", "global"]]) {
51
+ const fixture = path.join(root, locations.join("-") || "neither");
52
+ const agentDir = path.join(fixture, "agent");
53
+ const globalModules = path.join(fixture, "global", "node_modules");
54
+ await mkdir(agentDir, { recursive: true });
55
+ if (locations.includes("user")) await installed(path.join(agentDir, "npm", "node_modules"));
56
+ if (locations.includes("global")) await installed(globalModules);
57
+ for (const requested of ["all", "webui", "pi"]) {
58
+ const calls = [];
59
+ const service = createPackageUpdates({ agentDir, cwd: fixture, env: environment,
60
+ runCommand: async (command, args, options) => {
61
+ calls.push({ command, args, options });
62
+ return { exitCode: 0, stdout: args.join(" ") === "root -g" ? `${globalModules}\n` : "done" };
63
+ } });
64
+ assert.deepEqual(service.getJobs(), { all: null, webui: null, pi: null });
65
+ if (requested === "webui" && !locations.length) {
66
+ await assert.rejects(service.plan(requested), (error) => error.statusCode === 409 && /not installed/.test(error.message));
67
+ assert.deepEqual(calls.map(({ args }) => args), [["root", "-g"]]);
68
+ continue;
69
+ }
70
+ const plan = await service.plan(requested);
71
+ assert.equal(plan.requested, requested);
72
+ assert.match(plan.digest, /^[a-f0-9]{64}$/);
73
+ assert.equal(plan.context.agentDir, agentDir);
74
+ assert.equal(plan.context.cwd, fixture);
75
+ assert.match(plan.warning, /Restart Web UI manually/);
76
+ assert.equal(calls.filter(({ args }) => args.includes("update")).length, 0, "previewing and abandoning a plan never runs an update");
77
+ if (requested === "pi") assert.equal(calls.length, 0, "Pi-only needs no npm, version or capability probes");
78
+ assert.throws(() => service.apply(plan.transactionId, "0".repeat(64)), (error) => error.statusCode === 409);
79
+ assert.throws(() => service.apply("missing-preview", plan.digest), (error) => error.statusCode === 404);
80
+ // Caller mutation must not replace a server-owned command or its confirmation token.
81
+ const original = structuredClone(plan);
82
+ plan.targets[0].command.args.push("--arbitrary");
83
+ service.apply(original.transactionId, original.digest);
84
+ const job = await finished(service, original.transactionId);
85
+ const expected = requested === "pi" ? [["pi", ["update"]]] : requested === "all"
86
+ ? [["pi", ["update", "--all"]], ...(locations.includes("global") ? [["npm", ["update", "-g", WEBUI]]] : [])]
87
+ : [...(locations.includes("user") ? [["pi", ["update", "--extension", SOURCE]]] : []),
88
+ ...(locations.includes("global") ? [["npm", ["update", "-g", WEBUI]]] : [])];
89
+ assert.deepEqual(calls.filter(({ args }) => args.includes("update")).map(({ command, args }) => [command, args]), expected);
90
+ assert.ok(calls.every(({ options }) => options.env === environment && options.cwd === fixture && options.timeoutMs > 0));
91
+ assert.equal(job.phase, "success");
92
+ assert.equal(job.restartRequired, true);
93
+ assert.deepEqual(job.verifiedTargets, [], "command exit is never labeled as installed health verification");
94
+ assert.ok(job.receipts.every((receipt) => receipt.exitCode === 0 && receipt.status === "success"));
95
+ assert.equal(service.getJobs()[requested].transactionId, original.transactionId);
96
+ assert.throws(() => service.apply(original.transactionId, original.digest), (error) => error.statusCode === 409, "apply never replays an already launched preview");
97
+ job.receipts[0].stdout = "caller mutation";
98
+ assert.equal(service.getJob(original.transactionId).receipts[0].stdout, "done");
99
+ assert.equal(service.running, false);
100
+ }
101
+ }
102
+
103
+ // npm-global can be the same physical root as Pi user storage.
104
+ const dedupAgent = path.join(root, "dedup-agent");
105
+ const sharedModules = path.join(dedupAgent, "npm", "node_modules");
106
+ await installed(sharedModules);
107
+ const globalAlias = path.join(root, "global-modules-alias");
108
+ await symlink(sharedModules, globalAlias, "junction");
109
+ for (const requested of ["all", "webui"]) {
110
+ const calls = [];
111
+ const service = createPackageUpdates({ agentDir: dedupAgent, env: environment,
112
+ runCommand: async (command, args) => { calls.push([command, args]); return { exitCode: 0, stdout: globalAlias }; } });
113
+ const plan = await service.plan(requested);
114
+ assert.equal(plan.targets.length, 1);
115
+ assert.match(plan.refusals.join(" "), /one installation/);
116
+ if (requested === "all") assert.equal(plan.targets[0].coveredInstallations[0].installedRoot, path.join(sharedModules, ...WEBUI.split("/")));
117
+ service.apply(plan.transactionId, plan.digest);
118
+ await finished(service, plan.transactionId);
119
+ assert.equal(calls.filter(([, args]) => args.includes("update")).length, 1);
120
+ }
121
+
122
+ const globalOnly = path.join(root, "global-only-modules");
123
+ await installed(globalOnly);
124
+ let releaseFirst;
125
+ const gate = new Promise((resolve) => { releaseFirst = resolve; });
126
+ const orderedCalls = [];
127
+ const serial = createPackageUpdates({ agentDir: path.join(root, "serial-agent"), env: environment,
128
+ runCommand: async (command, args) => {
129
+ if (args[0] === "root") return { exitCode: 0, stdout: globalOnly };
130
+ orderedCalls.push(command);
131
+ if (command === "pi") { await gate; return { exitCode: 4, stderr: "self update failed" }; }
132
+ return { exitCode: 0, stdout: "global update finished" };
133
+ } });
134
+ const first = await serial.plan("all");
135
+ const second = await serial.plan("pi");
136
+ serial.apply(first.transactionId, first.digest);
137
+ assert.equal(serial.running, true);
138
+ assert.equal(serial.getJobs().all.phase, "running");
139
+ assert.throws(() => serial.apply(second.transactionId, second.digest), (error) => error.statusCode === 409);
140
+ await assert.rejects(serial.plan("webui"), (error) => error.statusCode === 409);
141
+ assert.deepEqual(orderedCalls, ["pi"], "global Web UI waits for the Pi command to close");
142
+ releaseFirst();
143
+ const partial = await finished(serial, first.transactionId);
144
+ assert.equal(partial.phase, "partial");
145
+ assert.deepEqual(partial.receipts.map(({ exitCode }) => exitCode), [4, 0]);
146
+ assert.deepEqual(orderedCalls, ["pi", "npm"], "a failed command has no retry or alternate command");
147
+ assert.match(partial.error, /command exited 4/);
148
+ serial.apply(second.transactionId, second.digest);
149
+ const failed = await finished(serial, second.transactionId);
150
+ assert.equal(failed.phase, "failed");
151
+ assert.equal(failed.restartRequired, false);
152
+ assert.equal(serial.getJobs().all.transactionId, first.transactionId, "pi jobs preserve the all result");
153
+ assert.equal(serial.getJobs().pi.transactionId, second.transactionId);
154
+ const webui = await serial.plan("webui");
155
+ serial.apply(webui.transactionId, webui.digest);
156
+ await finished(serial, webui.transactionId);
157
+ assert.deepEqual(Object.fromEntries(Object.entries(serial.getJobs()).map(([key, job]) => [key, job.transactionId])),
158
+ { all: first.transactionId, webui: webui.transactionId, pi: second.transactionId }, "each mode retains its own last launched result");
159
+
160
+ const detectionFailure = createPackageUpdates({ agentDir: dedupAgent, env: environment,
161
+ runCommand: async () => ({ exitCode: 1, stdout: "/unusable", stderr: "no npm" }) });
162
+ const userDespiteNpmFailure = await detectionFailure.plan("webui");
163
+ assert.deepEqual(userDespiteNpmFailure.targets.map(({ id }) => id), ["webui:pi-user"]);
164
+ assert.match(userDespiteNpmFailure.refusals.join(" "), /could not be detected/);
165
+ const emptyPackage = path.join(root, "empty-package-agent");
166
+ await mkdir(path.join(emptyPackage, "npm", "node_modules", ...WEBUI.split("/")), { recursive: true });
167
+ const absent = createPackageUpdates({ agentDir: emptyPackage, env: environment,
168
+ runCommand: async () => ({ exitCode: 0, stdout: path.join(root, "absent-global") }) });
169
+ await assert.rejects(absent.plan("webui"), (error) => error.statusCode === 409);
170
+ await assert.rejects(absent.plan("arbitrary"), (error) => error.statusCode === 400);
171
+
172
+ // Exercise real process handling with disposable Node scripts, never package managers.
173
+ const processScript = path.join(root, "fake-process.mjs");
174
+ await writeFile(processScript, `console.log('x'.repeat(20000)); console.error('password=super-secret'); console.log(process.env.FIXTURE_API_TOKEN); process.exitCode = 7;`);
175
+ const realEnv = { ...environment, FIXTURE_API_TOKEN: "fixture-private-value" };
176
+ const output = await runPackageCommand(process.execPath, [processScript], { cwd: root, env: realEnv, timeoutMs: 2_000 });
177
+ assert.equal(output.exitCode, 7);
178
+ assert.ok(output.stdout.length <= 16_000 && output.stderr.length <= 16_000);
179
+ assert.doesNotMatch(output.stdout, /fixture-private-value/);
180
+ assert.doesNotMatch(output.stderr, /super-secret/);
181
+ assert.match(output.stderr, /redacted/);
182
+ const missing = await runPackageCommand(path.join(root, "missing-command"), [], { cwd: root, env: environment, timeoutMs: 2_000 });
183
+ assert.match(missing.error, /ENOENT/);
184
+ await writeFile(processScript, `setInterval(() => {}, 1000);`);
185
+ const started = Date.now();
186
+ const timedOut = await runPackageCommand(process.execPath, [processScript], { cwd: root, env: environment, timeoutMs: 100 });
187
+ assert.equal(timedOut.timedOut, true);
188
+ assert.match(timedOut.error, /timed out/);
189
+ assert.ok(Date.now() - started < 4_000, "timeout closes the disposable child promptly");
190
+ if (process.platform !== "win32") {
191
+ const marker = path.join(root, "unwanted-descendant-output");
192
+ const descendant = path.join(root, "fake-descendant.mjs");
193
+ await writeFile(descendant, `import { writeFileSync } from 'node:fs';
194
+ process.on('SIGTERM', () => {});
195
+ setTimeout(() => writeFileSync(${JSON.stringify(marker)}, 'still running'), 800);`);
196
+ await writeFile(processScript, `import { spawn } from 'node:child_process';
197
+ spawn(process.execPath, [${JSON.stringify(descendant)}], { stdio: 'ignore' });
198
+ setInterval(() => {}, 1000);`);
199
+ const tree = await runPackageCommand(process.execPath, [processScript], { cwd: root, env: environment, timeoutMs: 200 });
200
+ assert.equal(tree.timedOut, true);
201
+ await delay(1_000);
202
+ await assert.rejects(readFile(marker), { code: "ENOENT" }, "timeout also terminates package-command descendants");
203
+ }
204
+ const timeoutService = createPackageUpdates({ agentDir: dedupAgent, env: environment,
205
+ runCommand: async () => timedOut });
206
+ const timeoutPlan = await timeoutService.plan("pi");
207
+ timeoutService.apply(timeoutPlan.transactionId, timeoutPlan.digest);
208
+ const timeoutJob = await finished(timeoutService, timeoutPlan.transactionId);
209
+ assert.equal(timeoutJob.phase, "failed");
210
+ assert.equal(timeoutJob.receipts[0].timedOut, true);
211
+
212
+ await progressFlow(globalOnly);
213
+ await classificationFlow(globalOnly, dedupAgent);
214
+ await streamedOutputFlow(processScript);
215
+ await httpFlow();
216
+ await httpFlow(true);
217
+ } finally {
218
+ await rm(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
219
+ }
220
+ console.log("package-updates.test.mjs passed");
221
+
222
+ async function progressFlow(globalModules) {
223
+ const steps = [];
224
+ const service = createPackageUpdates({ agentDir: path.join(root, "progress-agent"), env: environment,
225
+ runCommand: (command, args, { onOutput }) => {
226
+ if (args[0] === "root") return { exitCode: 0, stdout: globalModules };
227
+ return new Promise((resolve) => steps.push({ command, onOutput, resolve }));
228
+ } });
229
+ const plan = await service.plan("all");
230
+ assert.equal(service.getJob(plan.transactionId).progress, undefined, "abandoning a preview starts no progress or command");
231
+ service.apply(plan.transactionId, plan.digest);
232
+ const read = () => service.getJob(plan.transactionId);
233
+ const initial = read().progress;
234
+ assert.deepEqual({ ...initial, startedAt: "ISO", stepStartedAt: "ISO" }, {
235
+ totalSteps: 2, completedSteps: 0, currentTargetId: "pi", startedAt: "ISO", stepStartedAt: "ISO", stdout: "", stderr: "",
236
+ });
237
+ assert.equal(new Date(initial.startedAt).toISOString(), initial.startedAt);
238
+ assert.equal(new Date(initial.stepStartedAt).toISOString(), initial.stepStartedAt);
239
+ steps[0].onOutput({ stdout: "x".repeat(20_000) + "\npassword=fixture-password", stderr: "token=fixture-token" });
240
+ const live = read().progress;
241
+ assert.equal(read().phase, "running");
242
+ assert.ok(live.stdout.length <= 16_000 && live.stderr.length <= 16_000);
243
+ assert.doesNotMatch(JSON.stringify(live), /fixture-password|fixture-token/);
244
+ assert.match(live.stdout, /redacted/);
245
+ live.stdout = "caller mutation";
246
+ assert.notEqual(read().progress.stdout, live.stdout);
247
+ steps[0].resolve({ exitCode: 0, stdout: "Pi command completed" });
248
+ await delay(0);
249
+ const next = read();
250
+ assert.equal(steps.length, 2);
251
+ assert.deepEqual([next.progress.completedSteps, next.progress.currentTargetId, next.progress.stdout, next.progress.stderr], [1, "webui:npm-global", "", ""]);
252
+ assert.equal(next.progress.startedAt, initial.startedAt);
253
+ assert.ok(next.progress.stepStartedAt >= initial.stepStartedAt);
254
+ assert.equal(next.receipts[0].startedAt, initial.stepStartedAt);
255
+ assert.ok(next.receipts[0].at >= next.receipts[0].startedAt);
256
+ steps[0].onOutput({ stdout: "late output", stderr: "" });
257
+ assert.equal(read().progress.stdout, "", "settled command callbacks cannot overwrite the next step");
258
+ steps[1].onOutput({ stdout: "npm working\n", stderr: "" });
259
+ assert.equal(service.getJobs().all.progress.stdout, "npm working\n");
260
+ steps[1].resolve({ exitCode: 1, stderr: "npm failed" });
261
+ const completed = await finished(service, plan.transactionId);
262
+ assert.equal(completed.phase, "partial");
263
+ assert.equal(completed.progress.completedSteps, 2, "failed steps also settle");
264
+ assert.equal(completed.progress.currentTargetId, null);
265
+ assert.equal(completed.progress.stderr, "npm failed");
266
+ assert.equal(completed.receipts[1].startedAt, next.progress.stepStartedAt);
267
+ assert.ok(completed.finishedAt >= completed.receipts[1].at);
268
+ steps[1].onOutput({ stdout: "late terminal output", stderr: "" });
269
+ assert.deepEqual(read(), completed);
270
+
271
+ const throwing = createPackageUpdates({ agentDir: path.join(root, "throwing-agent"), env: environment,
272
+ runCommand: async (_command, _args, { onOutput }) => {
273
+ onOutput({ stdout: "last visible output", stderr: "password=fixture-password" });
274
+ throw new Error("fixture command failed");
275
+ } });
276
+ const throwingPlan = await throwing.plan("pi");
277
+ throwing.apply(throwingPlan.transactionId, throwingPlan.digest);
278
+ const thrown = await finished(throwing, throwingPlan.transactionId);
279
+ assert.equal(thrown.phase, "failed");
280
+ assert.equal(thrown.progress.completedSteps, 1);
281
+ assert.equal(thrown.progress.currentTargetId, null);
282
+ assert.equal(thrown.progress.stdout, "last visible output");
283
+ assert.equal(thrown.receipts[0].stdout, thrown.progress.stdout);
284
+ assert.match(thrown.progress.stderr, /redacted/);
285
+ assert.doesNotMatch(thrown.progress.stderr, /fixture-password/);
286
+ assert.match(thrown.error, /fixture command failed/);
287
+ }
288
+
289
+ async function classificationFlow(globalModules, userAgent) {
290
+ const self = "pi is already up to date (v9.8.7)";
291
+ const packages = "Packages are already up to date";
292
+ const extension = `${SOURCE} is already up to date`;
293
+ const npm = "up to date, audited 12 packages in 428ms";
294
+ const cases = [
295
+ ["pi", self, "unchanged"],
296
+ ["pi", `Extensions are skipped. Run pi update --extensions to update extensions.\n${self}`, "unchanged"],
297
+ ["pi", "Extensions are skipped. Run pi update --extensions to update extensions.", "success"],
298
+ ["all", `Extensions are skipped. Run pi update --extensions to update extensions.\n${self}\n${packages}`, "success"],
299
+ ["pi", `\u001b[32m${self}\u001b[39m\r\n`, "unchanged"],
300
+ ["webui", extension, "unchanged"],
301
+ ["all", `${self}\n${packages}`, "unchanged"],
302
+ ["all", `${packages}\n${self}`, "unchanged"],
303
+ ["all", self, "success"],
304
+ ["all", packages, "success"],
305
+ ["pi", "", "success"],
306
+ ["pi", "command finished", "success"],
307
+ ["pi", `${self}\nwarning: stale metadata`, "success"],
308
+ ["pi", `${self}\nSkipped package updates (offline mode)`, "success"],
309
+ ["pi", `${self}\nUpdated pi from 9.8.6 to 9.8.7`, "success"],
310
+ ["pi", `${self}\nunrecognized output`, "success"],
311
+ ["pi", `prefix ${self}`, "success"],
312
+ ["pi", `${self} trailing text`, "success"],
313
+ ["webui", "npm:@firstpick/another-package is already up to date", "success"],
314
+ ["webui", self, "success"],
315
+ ["pi", self, "success", { stderr: "npm warn stale metadata" }],
316
+ ["pi", self, "failed", { exitCode: 2 }],
317
+ ["pi", self, "failed", { timedOut: true }],
318
+ ["pi", self, "failed", { signal: "SIGTERM" }],
319
+ ["pi", self, "failed", { error: "command failed" }],
320
+ ["pi", "x".repeat(17_000) + "\n" + self, "success"],
321
+ ];
322
+ for (const [requested, stdout, expected, overrides] of cases) {
323
+ const service = createPackageUpdates({ agentDir: userAgent, env: environment,
324
+ runCommand: async (_command, args) => args[0] === "root" ? { exitCode: 0, stdout: path.join(root, "not-installed") } :
325
+ { exitCode: 0, stdout, ...overrides } });
326
+ const plan = await service.plan(requested);
327
+ service.apply(plan.transactionId, plan.digest);
328
+ const job = await finished(service, plan.transactionId);
329
+ assert.equal(job.receipts[0].status, expected, JSON.stringify([requested, stdout.slice(-200), overrides]));
330
+ assert.equal(job.phase, expected);
331
+ assert.equal(job.restartRequired, expected === "success");
332
+ if (expected === "unchanged") {
333
+ assert.match(job.message, /Already up to date/);
334
+ assert.doesNotMatch(job.message, /restart/i);
335
+ assert.equal(job.error, "");
336
+ } else assert.match(job.message, /Commands completed/);
337
+ }
338
+
339
+ for (const [stdout, expected] of [
340
+ [npm, "unchanged"],
341
+ ["up to date in 2s\n\n3 packages are looking for funding\n run `npm fund` for details", "unchanged"],
342
+ ["up to date, audited 1 package in 2s\nfound 0 vulnerabilities", "unchanged"],
343
+ ["3 packages are looking for funding\nrun `npm fund` for details", "success"],
344
+ ["up to date in 2s\n1 high severity vulnerability", "success"], ["up to date in 2s", "unchanged"], ["up to date, audited 1 package in 1m", "unchanged"],
345
+ ["\nup to date in 1.5s\n", "unchanged"], ["everything is up to date in 2s", "success"],
346
+ ["up to date", "success"], ["up to date in someday", "success"],
347
+ ["up to date, changed 1 package in 2s", "success"], ["up to date in 2s\nadded 1 package in 2s", "success"],
348
+ ["removed 1 package in 2s\nup to date in 2s", "success"], ["changed 1 package in 2s\nup to date in 2s", "success"],
349
+ ["npm warn skipped scripts\nup to date in 2s", "success"], ["up to date in 2s\nunknown output", "success"],
350
+ [JSON.stringify({ added: 0, changed: 0 }), "success"],
351
+ ]) {
352
+ const service = createPackageUpdates({ agentDir: path.join(root, "npm-classification-agent"), env: environment,
353
+ runCommand: async (_command, args) => ({ exitCode: 0, stdout: args[0] === "root" ? globalModules : stdout }) });
354
+ const plan = await service.plan("webui");
355
+ service.apply(plan.transactionId, plan.digest);
356
+ const job = await finished(service, plan.transactionId);
357
+ assert.equal(job.phase, expected, stdout);
358
+ assert.equal(job.restartRequired, expected !== "unchanged");
359
+ }
360
+
361
+ // Preserve warnings observed before a command adapter's final snapshot replaces its output.
362
+ const warned = createPackageUpdates({ agentDir: userAgent, env: environment,
363
+ runCommand: async (_command, _args, { onOutput }) => {
364
+ onOutput({ stdout: "warning: offline", stderr: "" });
365
+ return { exitCode: 0, stdout: self };
366
+ } });
367
+ const warnedPlan = await warned.plan("pi");
368
+ warned.apply(warnedPlan.transactionId, warnedPlan.digest);
369
+ assert.equal((await finished(warned, warnedPlan.transactionId)).phase, "success");
370
+
371
+ for (const piStatus of ["unchanged", "success", "failed"]) {
372
+ for (const npmStatus of ["unchanged", "success", "failed"]) {
373
+ const service = createPackageUpdates({ agentDir: path.join(root, "matrix-agent"), env: environment,
374
+ runCommand: async (command, args) => {
375
+ if (args[0] === "root") return { exitCode: 0, stdout: globalModules };
376
+ const status = command === "pi" ? piStatus : npmStatus;
377
+ return { exitCode: status === "failed" ? 7 : 0,
378
+ stdout: status === "unchanged" ? command === "pi" ? `${self}\n${packages}` : npm : "command completed" };
379
+ } });
380
+ const plan = await service.plan("all");
381
+ service.apply(plan.transactionId, plan.digest);
382
+ const job = await finished(service, plan.transactionId);
383
+ const statuses = [piStatus, npmStatus];
384
+ const failed = statuses.filter((status) => status === "failed").length;
385
+ const expected = failed === 2 ? "failed" : failed ? "partial" : statuses.every((status) => status === "unchanged") ? "unchanged" : "success";
386
+ assert.deepEqual(job.receipts.map(({ status }) => status), statuses);
387
+ assert.equal(job.phase, expected, statuses.join("/"));
388
+ assert.equal(job.outcome, expected);
389
+ assert.equal(job.restartRequired, statuses.includes("success"));
390
+ assert.equal(job.progress.completedSteps, 2);
391
+ assert.equal(job.error.split("\n").filter(Boolean).length, failed);
392
+ if (!job.restartRequired) assert.doesNotMatch(job.message, /restart/i);
393
+ }
394
+ }
395
+ }
396
+
397
+ async function streamedOutputFlow(script) {
398
+ await multilineSecretFlow(script);
399
+ const snapshots = [];
400
+ let releaseObserved;
401
+ const observed = new Promise((resolve) => { releaseObserved = resolve; });
402
+ await writeFile(script, `process.stdout.write('working\\n');
403
+ process.stdout.write('password=split-');
404
+ setTimeout(() => { process.stdout.write('credential\\n'); process.stderr.write('https://user:private@example.test\\n'); }, 50);
405
+ setTimeout(() => { process.stdout.write(process.env.FIXTURE_API_TOKEN.slice(0, 8)); }, 100);
406
+ setTimeout(() => { process.stdout.write(process.env.FIXTURE_API_TOKEN.slice(8) + '\\n'); }, 150);
407
+ setTimeout(() => { process.stdout.write('final without newline'); }, 400);`);
408
+ let settled = false;
409
+ const command = runPackageCommand(process.execPath, [script], {
410
+ cwd: root, env: { ...environment, FIXTURE_API_TOKEN: "fixture-private-value" }, timeoutMs: 2_000,
411
+ onOutput: (snapshot) => { snapshots.push(snapshot); if (snapshot.stdout.includes("working")) releaseObserved(); },
412
+ }).then((result) => { settled = true; return result; });
413
+ await Promise.race([observed, delay(1_500).then(() => { throw new Error("No live command snapshot"); })]);
414
+ assert.equal(settled, false, "output is available before the child exits");
415
+ const result = await command;
416
+ assert.equal(result.exitCode, 0);
417
+ assert.deepEqual(snapshots.at(-1), { stdout: result.stdout, stderr: result.stderr });
418
+ assert.match(result.stdout, /final without newline$/);
419
+ assert.match(result.stdout, /password=\[redacted\]/);
420
+ assert.match(result.stderr, /https:\/\/\[redacted\]@example.test/);
421
+ for (const snapshot of snapshots) {
422
+ assert.ok(snapshot.stdout.length <= 16_000 && snapshot.stderr.length <= 16_000);
423
+ assert.doesNotMatch(JSON.stringify(snapshot), /split-|credential|fixture-|private-value|user:private/);
424
+ }
425
+
426
+ await writeFile(script, `process.stdout.write('token=' + 'z'.repeat(17_000));
427
+ setTimeout(() => { console.log('z'.repeat(5_000)); console.log('up to date in 2s'); }, 50);`);
428
+ const boundedSnapshots = [];
429
+ const bounded = await runPackageCommand(process.execPath, [script], { cwd: root, env: environment, timeoutMs: 2_000,
430
+ onOutput: (snapshot) => boundedSnapshots.push(snapshot) });
431
+ assert.ok(bounded.stdout.length <= 16_000);
432
+ assert.match(bounded.stdout, /output truncated/);
433
+ assert.match(bounded.stdout, /up to date in 2s/);
434
+ for (const snapshot of boundedSnapshots) {
435
+ assert.ok(snapshot.stdout.length <= 16_000);
436
+ assert.doesNotMatch(snapshot.stdout, /z{6}/);
437
+ }
438
+
439
+ await writeFile(script, `process.stdout.write('\\u001b[');
440
+ setTimeout(() => { process.stdout.write('32mworking\\u001b[39m\\n'); process.stdout.write(Buffer.from([0xe2])); }, 50);
441
+ setTimeout(() => { process.stdout.write(Buffer.from([0x82, 0xac, 0x0a])); }, 100);
442
+ setTimeout(() => { for (let i = 0; i < 2000; i++) console.log('bounded output ' + i); }, 150);`);
443
+ const unicodeSnapshots = [];
444
+ const unicode = await runPackageCommand(process.execPath, [script], { cwd: root, env: environment, timeoutMs: 2_000,
445
+ onOutput: (snapshot) => unicodeSnapshots.push(snapshot) });
446
+ assert.ok(unicodeSnapshots.some(({ stdout }) => stdout.includes("working\n€\n")));
447
+ assert.match(unicode.stdout, /output truncated/);
448
+ assert.match(unicode.stdout, /bounded output 1999/);
449
+ for (const snapshot of unicodeSnapshots) {
450
+ assert.ok(snapshot.stdout.length <= 16_000);
451
+ assert.doesNotMatch(snapshot.stdout, /\u001b|\ufffd/);
452
+ }
453
+
454
+ await writeFile(script, `console.log('before timeout'); setInterval(() => {}, 1000);`);
455
+ const timeoutSnapshots = [];
456
+ const timeout = await runPackageCommand(process.execPath, [script], { cwd: root, env: environment, timeoutMs: 200,
457
+ onOutput: (snapshot) => timeoutSnapshots.push(snapshot) });
458
+ assert.equal(timeout.timedOut, true);
459
+ assert.match(timeout.stdout, /before timeout/);
460
+ const count = timeoutSnapshots.length;
461
+ await delay(50);
462
+ assert.equal(timeoutSnapshots.length, count);
463
+ assert.deepEqual(timeoutSnapshots.at(-1), { stdout: timeout.stdout, stderr: timeout.stderr });
464
+ if (process.platform !== "win32") {
465
+ await writeFile(script, `console.log('before cancellation'); process.kill(process.pid, 'SIGTERM');`);
466
+ const cancelled = await runPackageCommand(process.execPath, [script], { cwd: root, env: environment, timeoutMs: 2_000,
467
+ onOutput: () => { throw new Error("observer failure"); } });
468
+ assert.equal(cancelled.signal, "SIGTERM");
469
+ assert.equal(cancelled.exitCode, null);
470
+ assert.equal(cancelled.timedOut, false);
471
+ assert.match(cancelled.stdout, /before cancellation/);
472
+ }
473
+ }
474
+
475
+ async function multilineSecretFlow(script) {
476
+ for (const newline of ["\n", "\r\n"]) {
477
+ const fragments = ["fixture-private-first", "", "xy", "fixture-private-last"];
478
+ const env = { ...environment, FIXTURE_API_TOKEN: fragments.join(newline) };
479
+ await writeFile(script, `const lines = process.env.FIXTURE_API_TOKEN.split(/\\r?\\n/);
480
+ lines.forEach((line, index) => setTimeout(() => {
481
+ process.stdout.write(line + '\\n'); process.stderr.write(line + '\\n');
482
+ }, index * 75));
483
+ setTimeout(() => {}, 400);`);
484
+ const rawSnapshots = [], jobSnapshots = [];
485
+ let result, firstOutput;
486
+ const observed = new Promise(resolve => { firstOutput = resolve; });
487
+ const service = createPackageUpdates({ agentDir: path.join(root, "multiline-agent"), env,
488
+ runCommand: async (_command, _args, options) => {
489
+ result = await runPackageCommand(process.execPath, [script], { ...options, cwd: root, timeoutMs: 2_000,
490
+ onOutput: snapshot => {
491
+ rawSnapshots.push(snapshot);
492
+ options.onOutput(snapshot);
493
+ jobSnapshots.push(service.getJob(plan.transactionId));
494
+ if (snapshot.stdout.trim()) firstOutput();
495
+ } });
496
+ return result;
497
+ } });
498
+ const plan = await service.plan("pi");
499
+ service.apply(plan.transactionId, plan.digest);
500
+ await Promise.race([observed, delay(1_500).then(() => { throw new Error("No live multiline output"); })]);
501
+ assert.equal(service.getJob(plan.transactionId).phase, "running");
502
+ const terminal = await finished(service, plan.transactionId);
503
+ assert.equal(result.exitCode, 0);
504
+ assert.match(result.stdout, /redacted/);
505
+ assert.match(result.stderr, /redacted/);
506
+ for (const snapshot of [...rawSnapshots, ...jobSnapshots, result, terminal]) {
507
+ for (const fragment of fragments.filter(Boolean)) {
508
+ assert.ok(!JSON.stringify(snapshot).includes(fragment), "secret fragments must never reach raw or job output");
509
+ }
510
+ }
511
+ assert.deepEqual(rawSnapshots.at(-1), { stdout: result.stdout, stderr: result.stderr });
512
+ }
513
+ }
514
+
515
+ async function httpFlow(unchanged = false) {
516
+ const fixture = path.join(root, unchanged ? "http-unchanged" : "http");
517
+ const agentDir = path.join(fixture, "agent");
518
+ const prefix = path.join(fixture, "prefix");
519
+ const modules = path.join(prefix, ...(process.platform === "win32" ? [] : ["lib"]), "node_modules");
520
+ const piRoot = path.join(modules, "@earendil-works", "pi-coding-agent");
521
+ const bin = process.platform === "win32" ? prefix : path.join(prefix, "bin");
522
+ const cli = path.join(piRoot, "dist", "cli.js");
523
+ const npmCli = path.join(fixture, "fake-npm.mjs");
524
+ const log = path.join(fixture, "commands.jsonl");
525
+ await mkdir(path.dirname(cli), { recursive: true });
526
+ await mkdir(bin, { recursive: true });
527
+ await installed(modules);
528
+ await installed(path.join(agentDir, "npm", "node_modules"));
529
+ await writeFile(path.join(piRoot, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "9.8.7", bin: { pi: "dist/cli.js" } }));
530
+ await writeFile(cli, `#!${process.execPath}\nimport { appendFileSync } from 'node:fs';
531
+ const args = process.argv.slice(2);
532
+ if (args.includes('--version')) { console.log('9.8.7'); process.exit(0); }
533
+ if (args[0] === 'update') { appendFileSync(${JSON.stringify(log)}, JSON.stringify(['pi', args]) + '\\n'); console.log(${JSON.stringify(unchanged ? "pi is already up to date (v9.8.7)\nPackages are already up to date" : "updating pi\npassword=fixture-password")}); await new Promise(r => setTimeout(r, 500)); process.exit(0); }
534
+ await import(${JSON.stringify(pathToFileURL(path.join(packageRoot, "tests", "fixtures", "fake-pi.mjs")).href)});
535
+ ` , { mode: 0o755 });
536
+ if (process.platform === "win32") await writeFile(path.join(bin, "pi.cmd"), `@echo off\r\nnode "%dp0%\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\cli.js" %*\r\n`);
537
+ else await symlink(cli, path.join(bin, "pi"));
538
+ await writeFile(npmCli, `import { appendFileSync } from 'node:fs';
539
+ const args = process.argv.slice(2);
540
+ if (args.join(' ') === 'root -g') { console.log(${JSON.stringify(modules)}); process.exit(0); }
541
+ appendFileSync(${JSON.stringify(log)}, JSON.stringify(['npm', args]) + '\\n'); console.log(${JSON.stringify(unchanged ? "up to date in 2s" : "npm command failed")}); process.exitCode = ${unchanged ? 0 : 5};
542
+ `);
543
+ const listener = createServer();
544
+ await new Promise((resolve) => listener.listen(0, "127.0.0.1", resolve));
545
+ const port = listener.address().port;
546
+ await new Promise((resolve) => listener.close(resolve));
547
+ const base = `http://127.0.0.1:${port}`;
548
+ const child = spawn(process.execPath, [path.join(packageRoot, "bin", "pi-webui.mjs"), "--cwd", fixture,
549
+ "--host", "127.0.0.1", "--port", String(port), "--pi", cli], {
550
+ env: { ...environment, PATH: `${bin}${path.delimiter}${environment.PATH || ""}`, PI_CODING_AGENT_DIR: agentDir,
551
+ PI_WEBUI_SETTINGS_FILE: path.join(fixture, "settings.json"), PI_WEBUI_NPM_BIN: npmCli,
552
+ PI_WEBUI_UPDATE_TEST_HOME: fixture, PI_WEBUI_SESSION_SUMMARY_DIR: path.join(fixture, "summary") }, stdio: ["ignore", "pipe", "pipe"],
553
+ });
554
+ let serverOutput = "";
555
+ child.stdout.on("data", (chunk) => { serverOutput += chunk; });
556
+ child.stderr.on("data", (chunk) => { serverOutput += chunk; });
557
+ const api = async (route, body) => {
558
+ const response = await fetch(base + route, { ...(body === undefined ? {} : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }), signal: AbortSignal.timeout(5_000) });
559
+ return { status: response.status, body: await response.json() };
560
+ };
561
+ try {
562
+ let bootIdentity;
563
+ for (let attempt = 0; attempt < 120; attempt++) {
564
+ if (child.exitCode !== null) throw new Error(serverOutput);
565
+ try {
566
+ const health = await api("/api/health");
567
+ if (health.status === 200) { bootIdentity = health.body.bootIdentity; break; }
568
+ } catch {}
569
+ await delay(100);
570
+ }
571
+ assert.ok(bootIdentity, serverOutput);
572
+ const initial = await api("/api/update-status");
573
+ assert.deepEqual(initial.body.data.nativeJobs, { all: null, webui: null, pi: null });
574
+ assert.equal(initial.body.data.canRunUpdate, true);
575
+ assert.equal((await api("/api/update/plan", { targets: ["pi", "webui"] })).status, 400);
576
+ assert.equal((await api("/api/update/plan", { targets: ["all"], command: "arbitrary" })).status, 400);
577
+ const result = await api("/api/update/plan", { targets: ["all"] });
578
+ assert.equal(result.status, 201, JSON.stringify(result) + serverOutput);
579
+ const plan = result.body.data.plan;
580
+ assert.deepEqual(plan.targets.map(({ id }) => id), ["pi", "webui:npm-global"]);
581
+ await assert.rejects(readFile(log), { code: "ENOENT" }, "opening a preview makes no package changes");
582
+ assert.equal((await api("/api/update/apply", { transactionId: plan.transactionId, planDigest: "0".repeat(64) })).status, 409);
583
+ const apply = await api("/api/update/apply", { transactionId: plan.transactionId, planDigest: plan.digest });
584
+ assert.equal(apply.status, 202, JSON.stringify(apply));
585
+ assert.equal(apply.body.data.transactionId, plan.transactionId);
586
+ assert.equal((await api("/api/update-status")).body.data.canRunUpdate, false);
587
+ let live;
588
+ for (let attempt = 0; attempt < 50; attempt++) {
589
+ live = (await api(`/api/update/transactions/${plan.transactionId}`)).body.data;
590
+ if (live.progress.stdout) break;
591
+ await delay(10);
592
+ }
593
+ assert.equal(live.phase, "running", JSON.stringify(live));
594
+ assert.deepEqual([live.progress.totalSteps, live.progress.completedSteps, live.progress.currentTargetId], [2, 0, "pi"]);
595
+ assert.ok(live.progress.stdout);
596
+ assert.doesNotMatch(live.progress.stdout, /fixture-password/);
597
+ assert.equal((await api("/api/update-status")).body.data.nativeJobs.all.progress.stdout, live.progress.stdout);
598
+ let completed;
599
+ for (let attempt = 0; attempt < 100; attempt++) {
600
+ completed = (await api(`/api/update/transactions/${plan.transactionId}`)).body.data;
601
+ if (completed.phase !== "running") break;
602
+ await delay(20);
603
+ }
604
+ assert.equal(completed.phase, unchanged ? "unchanged" : "partial", JSON.stringify(completed));
605
+ assert.deepEqual(completed.receipts.map(({ exitCode }) => exitCode), [0, unchanged ? 0 : 5]);
606
+ assert.deepEqual(completed.verifiedTargets, []);
607
+ assert.equal(completed.restartRequired, !unchanged);
608
+ assert.match(completed.message, unchanged ? /Already up to date/ : /Restart Web UI manually/);
609
+ assert.equal(completed.progress.completedSteps, 2);
610
+ assert.equal(completed.progress.currentTargetId, null);
611
+ assert.equal((await api("/api/health")).body.bootIdentity, bootIdentity, "successful commands never restart the server");
612
+ const status = (await api("/api/update-status")).body.data;
613
+ assert.equal(status.nativeJobs.all.transactionId, plan.transactionId);
614
+ assert.equal(status.nativeJobs.all.phase, unchanged ? "unchanged" : "partial");
615
+ assert.equal(status.nativeJobs.pi, null);
616
+ assert.equal(status.nativeJobs.webui, null);
617
+ assert.equal(status.canRunUpdate, true);
618
+ assert.equal(status.restartRequired, !unchanged);
619
+ assert.deepEqual((await readFile(log, "utf8")).trim().split("\n").map(JSON.parse), [
620
+ ["pi", ["update", "--all"]], ["npm", ["update", "-g", WEBUI]],
621
+ ]);
622
+ assert.equal((await api("/api/update/apply", { transactionId: plan.transactionId, planDigest: plan.digest })).status, 409);
623
+ } finally {
624
+ if (child.exitCode === null) {
625
+ child.kill("SIGTERM");
626
+ await Promise.race([new Promise((resolve) => child.once("exit", resolve)), delay(6_000)]);
627
+ if (child.exitCode === null) { child.kill("SIGKILL"); await new Promise((resolve) => child.once("exit", resolve)); }
628
+ }
629
+ }
630
+ }
@@ -271,8 +271,8 @@ assert.match(
271
271
 
272
272
  // --- Coherent browser asset revisions --------------------------------------
273
273
 
274
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v156"/, "changed browser assets should advance the PWA cache identity");
275
- assert.match(html, /styles\.css\?v=154/, "the page should request the updated layout stylesheet revision");
276
- assert.match(html, /data-app-src="\/app\.js\?v=185"/, "the boot loader should request the updated app module revision");
274
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v200"/, "changed browser assets should advance the PWA cache identity");
275
+ assert.match(html, /styles\.css\?v=167/, "the page should request the updated layout stylesheet revision");
276
+ assert.match(html, /data-app-src="\/app\.js\?v=220"/, "the boot loader should request the updated app module revision");
277
277
 
278
278
  console.log("persistent-ui-layout-static.test.mjs passed");