@kabmo-labs/kabmo 0.25.0 → 0.26.0

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 (188) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +440 -436
  3. package/dist/client/static/js/{index-ga8cbpt4.js → index-95b3n20k.js} +945 -945
  4. package/dist/client/static/js/index-p2yw9ywf.css +1 -0
  5. package/package.json +1 -1
  6. package/src/client/components/common/session-actions-menu/index.tsx +38 -12
  7. package/src/client/components/common/session-branch/BranchGuides.tsx +93 -0
  8. package/src/client/components/common/session-branch/SubagentRow.tsx +77 -0
  9. package/src/client/components/common/session-branch/index.tsx +169 -0
  10. package/src/client/components/common/session-branch/session-branch.test.tsx +240 -0
  11. package/src/client/components/common/session-branch/style.ts +29 -0
  12. package/src/client/components/common/session-row/StatusSlot.tsx +15 -3
  13. package/src/client/components/common/session-row/index.tsx +24 -25
  14. package/src/client/components/common/session-row/session-row.test.tsx +11 -0
  15. package/src/client/components/common/session-state-provider/index.tsx +1 -1
  16. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +64 -68
  17. package/src/client/components/layout/session-sidebar/SessionItem.batch.test.ts +3 -3
  18. package/src/client/components/layout/session-sidebar/SessionItem.test.ts +25 -2
  19. package/src/client/components/layout/session-sidebar/SessionItem.tsx +33 -30
  20. package/src/client/components/layout/session-sidebar/about-modal/HarnessRow.tsx +261 -0
  21. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +35 -225
  22. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +36 -16
  23. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +11 -3
  24. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +13 -4
  25. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +28 -13
  26. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +59 -57
  27. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +57 -61
  28. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.test.ts +5 -0
  29. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +33 -30
  30. package/src/client/components/settings/Sidebar.tsx +1 -1
  31. package/src/client/components/settings/categories/NotificationSettings.test.tsx +92 -0
  32. package/src/client/components/settings/categories/NotificationSettings.tsx +112 -2
  33. package/src/client/components/settings/categories/harness-settings/HarnessCard.tsx +1 -1
  34. package/src/client/components/workspace/chat-timeline/AiMessageFooter.fork.test.ts +94 -0
  35. package/src/client/components/workspace/chat-timeline/AiMessageFooter.tsx +31 -5
  36. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +28 -39
  37. package/src/client/components/workspace/chat-timeline/MessageList.tsx +7 -5
  38. package/src/client/components/workspace/chat-timeline/PendingChatView.tsx +10 -0
  39. package/src/client/components/workspace/chat-timeline/RunFooter.tsx +12 -3
  40. package/src/client/components/workspace/chat-timeline/chat-input/AttachmentToolbar.tsx +2 -0
  41. package/src/client/components/workspace/chat-timeline/chat-input/ModeToggles.tsx +15 -1
  42. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.test.tsx +85 -0
  43. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.tsx +84 -0
  44. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +2 -0
  45. package/src/client/components/workspace/chat-timeline/chat-input/modes-props.ts +5 -0
  46. package/src/client/components/workspace/chat-timeline/index.tsx +10 -21
  47. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +115 -0
  48. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.tsx +173 -0
  49. package/src/client/components/workspace/chat-timeline/target-picker/parent-session-options.test.ts +49 -0
  50. package/src/client/hooks/chat/composer/items.test.ts +19 -0
  51. package/src/client/hooks/chat/omp/folder-auto-expand.ts +1 -1
  52. package/src/client/hooks/chat/omp/pending-adoption.ts +51 -0
  53. package/src/client/hooks/chat/omp/pending-child.test.ts +73 -0
  54. package/src/client/hooks/chat/omp/pending-entry.ts +59 -0
  55. package/src/client/hooks/chat/omp/pending-rows.ts +6 -2
  56. package/src/client/hooks/chat/omp/pending-sessions.test.ts +1 -2
  57. package/src/client/hooks/chat/omp/pending-sessions.ts +45 -69
  58. package/src/client/hooks/chat/omp/pending-waiting.ts +1 -1
  59. package/src/client/hooks/chat/omp/run-switch.ts +1 -1
  60. package/src/client/hooks/chat/omp/session-list.tsx +4 -0
  61. package/src/client/hooks/chat/subagents/roster.ts +122 -0
  62. package/src/client/hooks/chat/timeline/child-spawn.test.ts +55 -0
  63. package/src/client/hooks/chat/timeline/child-spawn.ts +45 -0
  64. package/src/client/hooks/chat/timeline/fork-request.test.ts +54 -0
  65. package/src/client/hooks/chat/timeline/fork-request.ts +43 -0
  66. package/src/client/hooks/chat/timeline/mode-availability.test.ts +1 -1
  67. package/src/client/hooks/chat/timeline/mode-availability.ts +33 -0
  68. package/src/client/hooks/chat/timeline/mode-markers.ts +7 -1
  69. package/src/client/hooks/chat/timeline/mode-post.ts +15 -3
  70. package/src/client/hooks/chat/timeline/modes-contract.ts +9 -4
  71. package/src/client/hooks/chat/timeline/modes.test.ts +56 -18
  72. package/src/client/hooks/chat/timeline/modes.ts +42 -29
  73. package/src/client/hooks/chat/timeline/pending-branch.ts +205 -0
  74. package/src/client/hooks/chat/timeline/pending-dispatch.ts +253 -0
  75. package/src/client/hooks/chat/timeline/send.ts +17 -103
  76. package/src/client/hooks/chat/timeline/session-harness.ts +6 -0
  77. package/src/client/hooks/chat/timeline/stop-with-queue.ts +42 -0
  78. package/src/client/hooks/chat/timeline/use-fork-session.ts +40 -31
  79. package/src/client/hooks/models/use-harness-update.test.ts +137 -44
  80. package/src/client/hooks/models/use-harness-update.ts +133 -85
  81. package/src/client/hooks/ui/input-required-alert.ts +12 -5
  82. package/src/client/hooks/ui/notifications.ts +45 -0
  83. package/src/client/hooks/ui/run-outcome-alert.ts +48 -0
  84. package/src/client/hooks/workspace/expanded-sessions.ts +36 -7
  85. package/src/client/lib/native/open-session.ts +33 -0
  86. package/src/client/lib/notifications/os.test.ts +125 -0
  87. package/src/client/lib/notifications/os.ts +130 -0
  88. package/src/client/lib/plugins/sidebar-bridge.ts +2 -20
  89. package/src/client/lib/router/open-session.test.ts +75 -0
  90. package/src/client/lib/router/open-session.ts +34 -0
  91. package/src/client/lib/signals.ts +5 -1
  92. package/src/client/main.tsx +6 -0
  93. package/src/server/lib/db/schema.ts +1 -0
  94. package/src/server/lib/harness/acp/calls.ts +15 -1
  95. package/src/server/lib/harness/acp/client-capabilities.test.ts +55 -0
  96. package/src/server/lib/harness/acp/client-capabilities.ts +61 -0
  97. package/src/server/lib/harness/acp/client-fs.test.ts +135 -0
  98. package/src/server/lib/harness/acp/client-fs.ts +131 -0
  99. package/src/server/lib/harness/acp/client-initialize.test.ts +70 -0
  100. package/src/server/lib/harness/acp/client-initialize.ts +84 -0
  101. package/src/server/lib/harness/acp/client.ts +31 -21
  102. package/src/server/lib/harness/acp/commands.test.ts +5 -5
  103. package/src/server/lib/harness/acp/commands.ts +14 -2
  104. package/src/server/lib/harness/acp/frames-timing.test.ts +68 -0
  105. package/src/server/lib/harness/acp/frames-v2.test.ts +85 -0
  106. package/src/server/lib/harness/acp/frames.ts +71 -158
  107. package/src/server/lib/harness/acp/mapper.test.ts +40 -0
  108. package/src/server/lib/harness/acp/mapper.ts +12 -0
  109. package/src/server/lib/harness/acp/permissions.ts +6 -0
  110. package/src/server/lib/harness/acp/protocol.ts +41 -2
  111. package/src/server/lib/harness/acp/session-facts.ts +1 -1
  112. package/src/server/lib/harness/acp/session-handshake.test.ts +90 -1
  113. package/src/server/lib/harness/acp/session-handshake.ts +83 -6
  114. package/src/server/lib/harness/acp/session-idle.ts +7 -6
  115. package/src/server/lib/harness/acp/session-notifications.ts +41 -2
  116. package/src/server/lib/harness/acp/session-observers.test.ts +63 -0
  117. package/src/server/lib/harness/acp/session-permissions.test.ts +29 -0
  118. package/src/server/lib/harness/acp/session-permissions.ts +36 -0
  119. package/src/server/lib/harness/acp/session-requests.test.ts +92 -0
  120. package/src/server/lib/harness/acp/session-requests.ts +48 -6
  121. package/src/server/lib/harness/acp/session-turns.ts +8 -3
  122. package/src/server/lib/harness/acp/session-usage.ts +4 -0
  123. package/src/server/lib/harness/acp/session-web-state.ts +30 -2
  124. package/src/server/lib/harness/acp/session.test-util.ts +19 -1
  125. package/src/server/lib/harness/acp/session.ts +60 -60
  126. package/src/server/lib/harness/acp/tool-calls.ts +223 -0
  127. package/src/server/lib/harness/acp/turn.test.ts +102 -0
  128. package/src/server/lib/harness/acp/turn.ts +81 -6
  129. package/src/server/lib/harness/acp/v2.test.ts +144 -0
  130. package/src/server/lib/harness/acp/v2.ts +220 -0
  131. package/src/server/lib/harness/acp/verbs.ts +46 -6
  132. package/src/server/lib/harness/launch.test.ts +25 -0
  133. package/src/server/lib/harness/launch.ts +21 -9
  134. package/src/server/lib/harness/session.ts +3 -0
  135. package/src/server/lib/harness/update-job-store.test.ts +37 -12
  136. package/src/server/lib/harness/update-job-store.ts +22 -16
  137. package/src/server/lib/harness/update-job.server.ts +66 -175
  138. package/src/server/lib/harness/update-queue.server.ts +292 -0
  139. package/src/server/lib/harness/update-queue.test.ts +265 -0
  140. package/src/server/lib/harness/update-spawn.server.ts +96 -0
  141. package/src/server/lib/harness/update-worker.ts +8 -3
  142. package/src/server/lib/lifecycle/after-listen.ts +9 -0
  143. package/src/server/lib/lifecycle/paths.ts +14 -9
  144. package/src/server/lib/omp/rpc/run-settle.server.ts +10 -1
  145. package/src/server/lib/omp/rpc/subagent-liveness.ts +5 -5
  146. package/src/server/lib/omp/rpc/terminal-settle.ts +5 -1
  147. package/src/server/lib/omp/session/delete-flow.server.ts +1 -0
  148. package/src/server/lib/omp/session/sidebar-data.server.ts +10 -12
  149. package/src/server/lib/sessions/fork.server.test.ts +68 -0
  150. package/src/server/lib/sessions/fork.server.ts +31 -6
  151. package/src/server/lib/sessions/spawn.server.test.ts +41 -0
  152. package/src/server/lib/sessions/spawn.server.ts +27 -2
  153. package/src/server/routes/agent/harness-command.ts +6 -5
  154. package/src/server/routes/chat/stream.ts +7 -2
  155. package/src/server/routes/harness/update-status.ts +18 -12
  156. package/src/server/routes/harness/update.test.ts +53 -16
  157. package/src/server/routes/harness/update.ts +13 -8
  158. package/src/server/routes/sessions/body-readers.ts +43 -0
  159. package/src/server/routes/sessions/fork.ts +19 -4
  160. package/src/server/routes/sessions/routes.test.ts +1 -2
  161. package/src/server/routes/sessions/session.ts +19 -0
  162. package/src/server/routes/sessions/spawn.ts +16 -13
  163. package/src/shared/lib/chat/omp/agent-events.ts +11 -0
  164. package/src/shared/lib/chat/omp/session-modes-signal.test.ts +41 -0
  165. package/src/shared/lib/harness/mode-signal.ts +20 -0
  166. package/src/shared/lib/harness/session-modes.ts +24 -0
  167. package/src/shared/lib/harness/update-job.ts +53 -6
  168. package/src/shared/lib/icons/tint-hues.generated.ts +34 -34
  169. package/src/shared/lib/notifications/outcomes.test.ts +96 -0
  170. package/src/shared/lib/notifications/outcomes.ts +64 -0
  171. package/src/shared/lib/notifications/settings.test.ts +49 -0
  172. package/src/shared/lib/notifications/settings.ts +34 -0
  173. package/src/shared/lib/omp/session/default-title.ts +5 -4
  174. package/src/shared/lib/omp/session/prewarm-misc.test.ts +3 -2
  175. package/src/shared/lib/omp/session/schema-migrations.ts +4 -0
  176. package/src/shared/lib/omp/session/stream-state.server.test.ts +19 -0
  177. package/src/shared/lib/omp/session/stream-state.server.ts +24 -4
  178. package/src/shared/lib/settings/defaults.ts +3 -0
  179. package/src/shared/types/harness-update.ts +24 -0
  180. package/src/shared/types/realtime.ts +2 -0
  181. package/src/shared/types/settings/state.ts +10 -0
  182. package/src/shared/types/workspace.ts +4 -0
  183. package/src/test-support/harness-table.test-util.ts +25 -9
  184. package/dist/client/static/js/index-bc9aa4mx.css +0 -1
  185. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +0 -113
  186. package/src/client/components/common/subagent-list/index.tsx +0 -165
  187. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +0 -66
  188. package/src/client/hooks/workspace/child-expansion.ts +0 -33
@@ -4,200 +4,91 @@
4
4
  */
5
5
 
6
6
  /**
7
- * Starting a harness update in the background, and applying what a finished one
8
- * left behind.
7
+ * Accepting a harness update: start it now, or queue it behind the install that
8
+ * is already running.
9
9
  *
10
- * The POST that asks for an update answers as soon as the worker is spawned; the
10
+ * The POST that asks for an update answers as soon as the record exists; the
11
11
  * worker (`update-worker.ts`) owns the install and writes its progress to disk.
12
- * This module is the server half: it refuses a second run, starts the worker,
13
- * and — on the next status read — does the two things a detached process cannot
14
- * do for itself: drop the cached probe/CLI-version reads, and point an adapter's
15
- * launch line at the binary the install wrote.
12
+ * This module is the server half of that handshake:
16
13
  *
17
- * **The refusal is a fact on disk, not a flag in memory.** The old route had no
14
+ * - it refuses a SECOND press for the SAME harness, with the run that caused it;
15
+ * - it accepts a press for a DIFFERENT harness as a WAITING record, because two
16
+ * presses is now a queue rather than an error (`update-queue.server.ts` starts
17
+ * it when the one ahead of it settles);
18
+ * - and it never runs two workers at once, because both would install into the
19
+ * same global npm prefix.
20
+ *
21
+ * **The decision is a fact on disk, not a flag in memory.** The old route had no
18
22
  * single-flight at all: a page reload mid-install offered the button again, and a
19
23
  * second `npm install -g` over the same prefix is how an npm tree gets corrupted.
20
- * The check reads the same record the worker writes, so a second tab and a
24
+ * The check reads the same records the worker writes, so a second tab and a
21
25
  * second server instance see the same answer.
22
26
  */
23
27
 
24
- import { existsSync } from 'node:fs';
25
- import { join } from 'node:path';
26
- import { resolveBunBin } from '@/server/lib/lifecycle/bun';
27
- import { packageDir } from '@/server/lib/fs/package-root';
28
- import {
29
- getHarnessUpdateLockPath,
30
- getHarnessUpdateSpecPath,
31
- getHarnessUpdateStatusPath,
32
- } from '@/server/lib/lifecycle/paths';
33
- import { forgetProbe } from '@/server/lib/harness/probe-cache.server';
34
- import { forgetCliVersion } from '@/server/lib/harness/update-state.server';
35
- import { jobInFlight, readUpdateJob, settleDeadJob, writeUpdateJob } from '@/server/lib/harness/update-job-store';
36
- import { loadHarnessConfig, saveHarnessConfig } from '@/server/lib/harness/config.server';
37
- import { invalidateOmpCliCache } from '@/server/lib/omp/core/cli';
38
- import { harnessUpdateFacts, type HarnessUpdateFacts } from '@/shared/lib/harness/updates';
39
- import { repointAdapterLaunch, type HarnessUpdateStep } from '@/shared/lib/harness/update-plan';
40
- import { HARNESS_IDS, type HarnessId } from '@/shared/lib/harness/catalog';
41
- import type { HarnessUpdateJob, HarnessUpdateJobSpec } from '@/shared/types/harness-update';
28
+ import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
29
+ import { readUpdateJob, settleDeadJob, writeUpdateJob } from '@/server/lib/harness/update-job-store';
30
+ import { pumpUpdateQueue, readAllUpdateJobs, serializeUpdateWork } from '@/server/lib/harness/update-queue.server';
31
+ import { spawnUpdateWorker } from '@/server/lib/harness/update-spawn.server';
32
+ import { jobRunning, jobUnfinished } from '@/shared/lib/harness/update-job';
33
+ import type { HarnessUpdateStep } from '@/shared/lib/harness/update-plan';
34
+ import type { HarnessId } from '@/shared/lib/harness/catalog';
35
+ import type { HarnessUpdateJob } from '@/shared/types/harness-update';
42
36
 
43
37
  /**
44
- * Where the worker's source lives inside this package.
45
- *
46
- * Derived from the package root rather than `import.meta.dir`: in production the
47
- * server runs the AOT bundle in `dist/client`, so this module's own directory is
48
- * not the source tree. `src/` ships in the tarball (`package.json#files`), which
49
- * is what makes the path valid in an installed copy too.
38
+ * This harness's unfinished record — installing, or waiting its turn — or null.
39
+ * Used to refuse a second press with a reason.
50
40
  */
51
- function workerPath(): string {
52
- return join(packageDir(), 'src', 'server', 'lib', 'harness', 'update-worker.ts');
53
- }
54
-
55
- /** The current record, with a run that died without reporting turned into a failure. */
56
- export async function currentUpdateJob(): Promise<HarnessUpdateJob | null> {
57
- return settleDeadJob(await readUpdateJob());
58
- }
59
-
60
- /** The run in flight, or null. Used to refuse a second press with a reason. */
61
- export async function runningUpdateJob(): Promise<HarnessUpdateJob | null> {
62
- const job = await currentUpdateJob();
63
- return jobInFlight(job) ? job : null;
41
+ export async function unfinishedUpdateJob(harness: HarnessId): Promise<HarnessUpdateJob | null> {
42
+ const path = getHarnessUpdateStatusPath(harness);
43
+ const job = await settleDeadJob(await readUpdateJob(path), path);
44
+ return jobUnfinished(job) ? job : null;
64
45
  }
65
46
 
66
47
  /**
67
- * Spawn the worker for `steps` and return the record it will fill.
48
+ * Start `steps`, or write the record that waits for the install in front of it.
68
49
  *
69
- * The record is written BEFORE the spawn so a poll that arrives in between sees
70
- * "running" rather than "no update"; the pid is written immediately after, and
71
- * the start grace window covers the gap.
50
+ * Serialized with the queue's own passes: two presses arriving together are one
51
+ * decision, not two "nothing is running" reads that both spawn.
72
52
  */
73
- export async function startHarnessUpdateJob(
53
+ export function startHarnessUpdateJob(
74
54
  harness: HarnessId,
75
55
  label: string,
76
56
  steps: HarnessUpdateStep[],
77
57
  ): Promise<HarnessUpdateJob> {
78
- const worker = workerPath();
79
- if (!existsSync(worker)) {
80
- throw new Error(`The update worker is missing from ${worker} — reinstall Kabmo to restore it`);
81
- }
82
-
83
- const spec: HarnessUpdateJobSpec = {
84
- harness,
85
- label,
86
- steps,
87
- statusPath: getHarnessUpdateStatusPath(),
88
- lockPath: getHarnessUpdateLockPath(),
89
- };
90
- await Bun.write(getHarnessUpdateSpecPath(), JSON.stringify(spec, null, 2));
91
-
92
- const startedAt = Date.now();
93
- const job: HarnessUpdateJob = {
94
- harness,
95
- label,
96
- startedAt,
97
- finishedAt: null,
98
- pid: null,
99
- steps: steps.map((step) => ({ ...step, state: 'pending', code: null })),
100
- output: '',
101
- ok: null,
102
- message: null,
103
- applied: false,
104
- repointed: null,
105
- };
106
- await writeUpdateJob(job);
107
-
108
- const child = Bun.spawn({
109
- cmd: [resolveBunBin(), worker, getHarnessUpdateSpecPath()],
110
- cwd: packageDir(),
111
- stdin: 'ignore',
112
- // Nothing is read back from stdio: the worker reports through the record, so
113
- // the install cannot be wedged by a parent that stopped draining a pipe.
114
- stdout: 'ignore',
115
- stderr: 'ignore',
116
- detached: true,
58
+ return serializeUpdateWork(async () => {
59
+ const busy = (await readAllUpdateJobs()).some(jobRunning);
60
+ const job: HarnessUpdateJob = {
61
+ harness,
62
+ label,
63
+ startedAt: Date.now(),
64
+ finishedAt: null,
65
+ // Set only while this record waits; the spawn clears it.
66
+ queuedAt: busy ? Date.now() : null,
67
+ pid: null,
68
+ steps: steps.map((step) => ({ ...step, state: 'pending', code: null })),
69
+ output: '',
70
+ ok: null,
71
+ message: null,
72
+ applied: false,
73
+ repointed: null,
74
+ };
75
+
76
+ if (busy) {
77
+ await writeUpdateJob(job, getHarnessUpdateStatusPath(harness));
78
+ // The ticker starts the queued run when the install ahead of it settles —
79
+ // including with the About card closed. It must not be awaited here.
80
+ void pumpUpdateQueue().catch((cause) => {
81
+ console.error('[harness-update] queue pump failed:', cause);
82
+ });
83
+ return job;
84
+ }
85
+
86
+ const started = await spawnUpdateWorker(job);
87
+ // Ticker for the FINALIZE half as well: the side effects a detached worker
88
+ // cannot apply happen without a browser polling this time.
89
+ void pumpUpdateQueue().catch((cause) => {
90
+ console.error('[harness-update] queue pump failed:', cause);
91
+ });
92
+ return started;
117
93
  });
118
- // Never adopted by this process: the worker has to survive a server exit, and
119
- // `unref` is what keeps the event loop from waiting on it.
120
- child.unref();
121
-
122
- job.pid = child.pid ?? null;
123
- await writeUpdateJob(job);
124
- return job;
125
- }
126
-
127
- /**
128
- * Make an adapter install the one the next spawn runs.
129
- *
130
- * The launch table starts an npm adapter through a PINNED `npx -y pkg@x.y.z`,
131
- * while the update installs the package GLOBALLY. Those are two different
132
- * resolvers: `npm i -g` writes a binary onto PATH that `npx` never consults, so
133
- * the press reported success while every new session still started the old
134
- * pinned build. A user's own configured command is never replaced.
135
- */
136
- async function pointAtInstalledAdapter(
137
- harness: HarnessId,
138
- facts: HarnessUpdateFacts,
139
- steps: HarnessUpdateStep[],
140
- ): Promise<string | null> {
141
- const config = await loadHarnessConfig(harness);
142
- const bin = repointAdapterLaunch(
143
- facts,
144
- steps,
145
- config.command,
146
- facts.agentBin ? Boolean(Bun.which(facts.agentBin)) : false,
147
- );
148
- if (!bin) return null;
149
- await saveHarnessConfig(harness, { ...config, command: bin });
150
- return bin;
151
- }
152
-
153
- async function finalizeOnce(): Promise<HarnessUpdateJob | null> {
154
- const job = await currentUpdateJob();
155
- if (!job || job.finishedAt === null || job.applied) return job;
156
-
157
- // The record is a file, so its id is not proof of a catalog entry; an unknown
158
- // one has no facts and nothing to repoint — it is still marked applied, so it
159
- // is not re-finalized on every poll.
160
- const harness = HARNESS_IDS.includes(job.harness as HarnessId) ? job.harness as HarnessId : null;
161
- const facts = harness ? harnessUpdateFacts(harness) : null;
162
- let repointed: string | null = null;
163
-
164
- if (job.ok && harness) {
165
- // The cached probe describes the binary that WAS installed, and the CLI's
166
- // `--version` read is cached for ten minutes: keeping either would report the
167
- // pre-update number until its TTL ran out.
168
- await forgetProbe(harness);
169
- if (facts?.cli) forgetCliVersion(facts.cli.bin);
170
- // `omp update` can replace its own launcher, so a cached path may be gone.
171
- if (harness === 'omp-acp') invalidateOmpCliCache();
172
- if (facts) repointed = await pointAtInstalledAdapter(harness, facts, job.steps);
173
- }
174
-
175
- const settled: HarnessUpdateJob = {
176
- ...job,
177
- applied: true,
178
- repointed,
179
- message: job.ok && job.message
180
- ? `${job.message}${repointed ? ` — launches now run \`${repointed}\`` : ''} — check its status to read the new version`
181
- : job.message,
182
- };
183
- await writeUpdateJob(settled);
184
- return settled;
185
- }
186
-
187
- /**
188
- * One finalize at a time, and only once per finished run.
189
- *
190
- * Two polls (two tabs, a poll racing the next one) would otherwise both see
191
- * `applied: false` and both repoint the launch line; the work is idempotent, but
192
- * the message would be composed twice.
193
- */
194
- let finalizing: Promise<HarnessUpdateJob | null> | null = null;
195
-
196
- export async function finalizeUpdateJob(): Promise<HarnessUpdateJob | null> {
197
- finalizing ??= finalizeOnce();
198
- try {
199
- return await finalizing;
200
- } finally {
201
- finalizing = null;
202
- }
203
94
  }
@@ -0,0 +1,292 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The queue behind "update two harnesses": read every record, apply what a
8
+ * finished run left behind, and start the next WAITING one.
9
+ *
10
+ * **Why a queue and not two installs at once.** The press used to be refused
11
+ * while any run was in flight, which made "update these two" impossible: the
12
+ * second press got a `409` and the user had to come back later. Two installs
13
+ * really cannot overlap — they share the global npm prefix, and two
14
+ * `npm install -g` over it is the way an npm tree is corrupted — so the second
15
+ * press is now ACCEPTED and its record carries `queuedAt`. This module starts it
16
+ * when the install ahead of it settles, and the row says it is waiting.
17
+ *
18
+ * **The queue is driven by a clock, not by the dialog.** A queued run must not
19
+ * depend on a browser tab staying open: the About card can be closed, the page
20
+ * reloaded, and the worker still has to start. The ticker reads the same records
21
+ * the worker writes, so it also settles a run that died without reporting, and
22
+ * applies the post-install side effects (`forgetProbe`, the launch-line repoint)
23
+ * that a detached process cannot — it does not own the database.
24
+ *
25
+ * **Every write goes through one chain.** Two presses, a queue tick and a status
26
+ * poll can each read-decide-write the records; serialized, the second press sees
27
+ * the first's record and waits instead of racing it into a second worker.
28
+ */
29
+
30
+ import { probeWithConfig } from '@/server/lib/harness/auto-probe.server';
31
+ import { forgetProbe, rememberProbe } from '@/server/lib/harness/probe-cache.server';
32
+ import { forgetCliVersion } from '@/server/lib/harness/update-state.server';
33
+ import { loadHarnessConfig, saveHarnessConfig } from '@/server/lib/harness/config.server';
34
+ import { invalidateOmpCliCache } from '@/server/lib/omp/core/cli';
35
+ import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
36
+ import { readUpdateJob, settleDeadJob, writeUpdateJob } from '@/server/lib/harness/update-job-store';
37
+ import { spawnUpdateWorker } from '@/server/lib/harness/update-spawn.server';
38
+ import { HARNESS_IDS, type HarnessId } from '@/shared/lib/harness/catalog';
39
+ import { harnessUpdateFacts, type HarnessUpdateFacts } from '@/shared/lib/harness/updates';
40
+ import { repointAdapterLaunch, type HarnessUpdateStep } from '@/shared/lib/harness/update-plan';
41
+ import { jobMoving, jobQueued, jobRunning } from '@/shared/lib/harness/update-job';
42
+ import type { HarnessProbe } from '@/server/lib/harness/capabilities';
43
+ import type { HarnessUpdateJob } from '@/shared/types/harness-update';
44
+
45
+ declare global {
46
+ // eslint-disable-next-line no-var
47
+ var __kabmoHarnessUpdateQueueTimer: ReturnType<typeof setInterval> | undefined;
48
+ }
49
+
50
+ /** How often a waiting run is looked at while anything is unfinished. 2 s is
51
+ * below the dialog's own poll, and the tick is a handful of small file reads. */
52
+ export const HARNESS_UPDATE_QUEUE_TICK_MS = 2_000;
53
+
54
+ /**
55
+ * Run `work` after every earlier read-decide-write over the update records.
56
+ *
57
+ * The records are files, so no lock is held between the read and the write; this
58
+ * chain is what makes "is anything running?" and "start this one" one decision
59
+ * inside a single process. Across processes the worker's own `flock` is still
60
+ * the guard (see `update-worker.ts`).
61
+ */
62
+ let chain: Promise<unknown> = Promise.resolve();
63
+
64
+ export function serializeUpdateWork<T>(work: () => Promise<T>): Promise<T> {
65
+ const next = chain.then(work, work);
66
+ chain = next.then(() => undefined, () => undefined);
67
+ return next;
68
+ }
69
+
70
+ /** Every harness's record, with a run that died without reporting settled. */
71
+ export async function readAllUpdateJobs(): Promise<HarnessUpdateJob[]> {
72
+ const jobs = await Promise.all(HARNESS_IDS.map(async (id) => {
73
+ const path = getHarnessUpdateStatusPath(id);
74
+ return settleDeadJob(await readUpdateJob(path), path);
75
+ }));
76
+ return jobs.filter((job): job is HarnessUpdateJob => job !== null);
77
+ }
78
+
79
+ /**
80
+ * Make an adapter install the one the next spawn runs.
81
+ *
82
+ * The launch table starts an npm adapter through a PINNED `npx -y pkg@x.y.z`,
83
+ * while the update installs the package GLOBALLY. Those are two different
84
+ * resolvers: `npm i -g` writes a binary onto PATH that `npx` never consults, so
85
+ * the press reported success while every new session still started the old
86
+ * pinned build. A user's own configured command is never replaced.
87
+ */
88
+ async function pointAtInstalledAdapter(
89
+ harness: HarnessId,
90
+ facts: HarnessUpdateFacts,
91
+ steps: HarnessUpdateStep[],
92
+ ): Promise<string | null> {
93
+ const config = await loadHarnessConfig(harness);
94
+ const bin = repointAdapterLaunch(
95
+ facts,
96
+ steps,
97
+ config.command,
98
+ facts.agentBin ? Boolean(Bun.which(facts.agentBin)) : false,
99
+ );
100
+ if (!bin) return null;
101
+ await saveHarnessConfig(harness, { ...config, command: bin });
102
+ return bin;
103
+ }
104
+
105
+ /**
106
+ * What a queue pass may run on the side, for the suite that cannot spawn an
107
+ * agent: the real probe by default, a stub in the tests (the seam
108
+ * `runAutoProbe` already offers for the boot pass).
109
+ */
110
+ export interface HarnessQueueOptions {
111
+ probe?: (id: HarnessId, cwd: string) => Promise<HarnessProbe>;
112
+ }
113
+
114
+ /**
115
+ * The probes this process is running, keyed by run.
116
+ *
117
+ * A probe spawns an agent and is not awaited by the queue, so the ticker would
118
+ * otherwise start a second one on every pass (and a re-kicked record after a
119
+ * restart would stack on the first).
120
+ */
121
+ const probing = new Set<string>();
122
+
123
+ /**
124
+ * Probe the freshly installed agent and write the answer's arrival onto the
125
+ * record.
126
+ *
127
+ * **The update is not finished with the user until this answers.** `forgetProbe`
128
+ * only drops the stale number; without a new probe the row keeps quoting the
129
+ * version the install just replaced, and the reader has to open Settings and
130
+ * press Check status themselves. The probe is NOT awaited by the install's own
131
+ * report — it spawns an agent process that may take a minute — so the record
132
+ * carries `probe: 'pending'` and a polling dialog re-reads the rows when it
133
+ * turns `done`.
134
+ */
135
+ async function probeAfterUpdate(
136
+ harness: HarnessId,
137
+ startedAt: number,
138
+ probe: (id: HarnessId, cwd: string) => Promise<HarnessProbe>,
139
+ ): Promise<void> {
140
+ let version: string | null = null;
141
+ try {
142
+ const recorded = await probe(harness, process.cwd());
143
+ version = recorded.capabilities.agentVersion ?? null;
144
+ await rememberProbe(harness, recorded);
145
+ } catch (cause) {
146
+ // A probe that fails is a fact the row can live with (it reads "not probed"
147
+ // with the reason'); leaving the record `pending` forever is not.
148
+ console.error(`[harness-update] probe after updating ${harness} failed:`, cause);
149
+ }
150
+ const path = getHarnessUpdateStatusPath(harness);
151
+ const current = await readUpdateJob(path);
152
+ // A NEW run for the same harness may have replaced the record while this
153
+ // probe ran; writing here would revert that run to the previous one.
154
+ if (!current || current.startedAt !== startedAt) return;
155
+ // The version is stated only when the agent itself answered it: a claim about
156
+ // a number nobody read is the fabrication this whole record exists to avoid.
157
+ const message = version && current.message && !current.message.includes(version)
158
+ ? `${current.message} — it now reports ${version}`
159
+ : current.message;
160
+ await writeUpdateJob({ ...current, probe: 'done', message }, path);
161
+ }
162
+
163
+ /** Run the probe for a settled record, once per run, in the background. */
164
+ function startProbe(job: HarnessUpdateJob, options: HarnessQueueOptions): void {
165
+ if (!HARNESS_IDS.includes(job.harness as HarnessId)) return;
166
+ const key = `${job.harness}:${job.startedAt}`;
167
+ if (probing.has(key)) return;
168
+ probing.add(key);
169
+ void probeAfterUpdate(job.harness as HarnessId, job.startedAt, options.probe ?? probeWithConfig)
170
+ .finally(() => probing.delete(key));
171
+ }
172
+
173
+ /** Apply a finished run's post-install side effects exactly once. */
174
+ async function applyFinishedJob(
175
+ job: HarnessUpdateJob,
176
+ options: HarnessQueueOptions,
177
+ ): Promise<HarnessUpdateJob> {
178
+ // The record is a file, so its id is not proof of a catalog entry; an unknown
179
+ // one has no facts and nothing to repoint — it is still marked applied, so it
180
+ // is not re-applied on every tick.
181
+ const harness = HARNESS_IDS.includes(job.harness as HarnessId) ? job.harness as HarnessId : null;
182
+ const facts = harness ? harnessUpdateFacts(harness) : null;
183
+ let repointed: string | null = null;
184
+
185
+ if (job.ok && harness) {
186
+ // The cached probe describes the binary that WAS installed, and the CLI's
187
+ // `--version` read is cached for ten minutes: keeping either would report the
188
+ // pre-update number until its TTL ran out.
189
+ await forgetProbe(harness);
190
+ if (facts?.cli) forgetCliVersion(facts.cli.bin);
191
+ // `omp update` can replace its own launcher, so a cached path may be gone.
192
+ if (harness === 'omp-acp') invalidateOmpCliCache();
193
+ if (facts) repointed = await pointAtInstalledAdapter(harness, facts, job.steps);
194
+ }
195
+
196
+ // The probe starts only for a run that actually moved something: a failed
197
+ // install has no new binary to ask, and an `own` harness is never updated here.
198
+ const willProbe = Boolean(job.ok && harness);
199
+ const settled: HarnessUpdateJob = {
200
+ ...job,
201
+ applied: true,
202
+ probe: willProbe ? 'pending' : job.probe ?? null,
203
+ repointed,
204
+ message: job.ok && job.message
205
+ ? `${job.message}${repointed ? ` — launches now run \`${repointed}\`` : ''}`
206
+ : job.message,
207
+ };
208
+ await writeUpdateJob(settled, getHarnessUpdateStatusPath(job.harness));
209
+ if (willProbe) startProbe(settled, options);
210
+ return settled;
211
+ }
212
+
213
+ /**
214
+ * The oldest WAITING record, or null.
215
+ *
216
+ * One install at a time, so the records form a queue and the OLDEST press is the
217
+ * next one — not the newest, which would let a later press jump ahead of the one
218
+ * the user made first.
219
+ */
220
+ export function nextQueuedJob(jobs: HarnessUpdateJob[]): HarnessUpdateJob | null {
221
+ const waiting = jobs.filter(jobQueued);
222
+ if (waiting.length === 0) return null;
223
+ return waiting.sort((a, b) => (a.queuedAt ?? 0) - (b.queuedAt ?? 0))[0];
224
+ }
225
+
226
+ /** Keep the ticker alive while anything is moving, and stop it when nothing is. */
227
+ function syncTicker(jobs: HarnessUpdateJob[]): void {
228
+ if (jobs.some(jobMoving)) {
229
+ globalThis.__kabmoHarnessUpdateQueueTimer ??= setInterval(() => {
230
+ void pumpUpdateQueue().catch((cause) => {
231
+ console.error('[harness-update] queue tick failed:', cause);
232
+ });
233
+ }, HARNESS_UPDATE_QUEUE_TICK_MS);
234
+ // A background queue must not be the reason the process will not exit.
235
+ globalThis.__kabmoHarnessUpdateQueueTimer.unref?.();
236
+ return;
237
+ }
238
+ if (globalThis.__kabmoHarnessUpdateQueueTimer) {
239
+ clearInterval(globalThis.__kabmoHarnessUpdateQueueTimer);
240
+ globalThis.__kabmoHarnessUpdateQueueTimer = undefined;
241
+ }
242
+ }
243
+
244
+ /**
245
+ * One pass: settle dead runs, apply finished ones, start the next waiting run.
246
+ *
247
+ * Returns the records as this pass left them, so the status route answers from
248
+ * the same read it acted on. Called by the status route, by the ticker while
249
+ * anything is unfinished, and once after the listener is up (a queued run
250
+ * accepted before a restart must not wait for a browser).
251
+ */
252
+ export function pumpUpdateQueue(options: HarnessQueueOptions = {}): Promise<HarnessUpdateJob[]> {
253
+ return serializeUpdateWork(async () => {
254
+ let jobs = await readAllUpdateJobs();
255
+
256
+ const finished = await Promise.all(
257
+ jobs.map((job) => job.finishedAt !== null && !job.applied ? applyFinishedJob(job, options) : job),
258
+ );
259
+ jobs = finished;
260
+
261
+ // A probe whose server went away mid-flight leaves `pending` behind; the
262
+ // next pass (a poll, or the boot pump) runs it again rather than leaving the
263
+ // row on the old number forever.
264
+ for (const job of jobs) {
265
+ if (job.finishedAt !== null && job.probe === 'pending') startProbe(job, options);
266
+ }
267
+
268
+ const waiting = nextQueuedJob(jobs);
269
+ if (waiting && !jobs.some(jobRunning)) {
270
+ try {
271
+ const started = await spawnUpdateWorker(waiting);
272
+ jobs = jobs.map((job) => job.harness === started.harness ? started : job);
273
+ } catch (cause) {
274
+ // Starting it failed (the worker is missing, the spec is unwritable).
275
+ // The record says so instead of sitting in the queue forever.
276
+ const failed: HarnessUpdateJob = {
277
+ ...waiting,
278
+ finishedAt: Date.now(),
279
+ pid: null,
280
+ ok: false,
281
+ applied: true,
282
+ message: `${waiting.label} update could not start: ${cause instanceof Error ? cause.message : String(cause)}`,
283
+ };
284
+ await writeUpdateJob(failed, getHarnessUpdateStatusPath(waiting.harness));
285
+ jobs = jobs.map((job) => job.harness === failed.harness ? failed : job);
286
+ }
287
+ }
288
+
289
+ syncTicker(jobs);
290
+ return jobs;
291
+ });
292
+ }