@kabmo-labs/kabmo 0.15.0 → 0.17.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 (177) hide show
  1. package/README.md +3 -2
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +412 -394
  4. package/dist/client/static/js/index-3ve31rzx.css +1 -0
  5. package/dist/client/static/js/{index-mx658m43.js → index-rerjq5th.js} +846 -844
  6. package/marketplace/plugins/stats/README.md +27 -8
  7. package/marketplace/plugins/stats/package.json +2 -2
  8. package/marketplace/plugins/stats/src/HeaderReadout.test.tsx +2 -1
  9. package/marketplace/plugins/stats/src/HeaderReadout.tsx +6 -2
  10. package/marketplace/plugins/stats/src/KillConfirm.test.tsx +159 -0
  11. package/marketplace/plugins/stats/src/KillConfirm.tsx +145 -0
  12. package/marketplace/plugins/stats/src/ProcessTable.tsx +54 -8
  13. package/marketplace/plugins/stats/src/TotalsBar.test.tsx +5 -2
  14. package/marketplace/plugins/stats/src/TotalsBar.tsx +13 -3
  15. package/marketplace/plugins/stats/src/app.test.tsx +100 -4
  16. package/marketplace/plugins/stats/src/app.tsx +51 -4
  17. package/marketplace/plugins/stats/src/groups.test.ts +1 -1
  18. package/marketplace/plugins/stats/src/kill.test.ts +131 -0
  19. package/marketplace/plugins/stats/src/kill.ts +74 -0
  20. package/marketplace/plugins/stats/src/labels.test.ts +1 -0
  21. package/marketplace/plugins/stats/src/machine.test.ts +77 -0
  22. package/marketplace/plugins/stats/src/machine.ts +115 -0
  23. package/marketplace/plugins/stats/src/proc/darwin.ts +38 -0
  24. package/marketplace/plugins/stats/src/proc/linux.ts +4 -0
  25. package/marketplace/plugins/stats/src/proc/ps.ts +1 -0
  26. package/marketplace/plugins/stats/src/proc/types.ts +11 -0
  27. package/marketplace/plugins/stats/src/sampler.test.ts +42 -4
  28. package/marketplace/plugins/stats/src/sampler.ts +32 -18
  29. package/marketplace/plugins/stats/src/server.ts +29 -2
  30. package/marketplace/plugins/stats/src/snapshot.ts +31 -3
  31. package/package.json +3 -2
  32. package/src/client/components/common/Modal.tsx +7 -0
  33. package/src/client/components/common/code-surface/bracket-guide.test.ts +2 -2
  34. package/src/client/components/common/code-surface/bracket-guide.ts +2 -2
  35. package/src/client/components/common/code-surface/conflict-markers.ts +5 -5
  36. package/src/client/components/common/code-surface/extensions.ts +7 -4
  37. package/src/client/components/common/code-surface/theme.ts +34 -9
  38. package/src/client/components/common/code-surface/whitespace.test.ts +223 -0
  39. package/src/client/components/common/code-surface/whitespace.ts +140 -0
  40. package/src/client/components/common/{server-switcher/index.tsx → server-control/Panel.tsx} +73 -35
  41. package/src/client/components/common/{server-switcher → server-control}/index.test.tsx +98 -37
  42. package/src/client/components/common/server-control/index.tsx +118 -0
  43. package/src/client/components/layout/LeftDock.tsx +1 -0
  44. package/src/client/components/layout/desktop-layout/TopNavbar.tsx +8 -50
  45. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +1 -0
  46. package/src/client/components/mobile/RightSidebar.tsx +1 -0
  47. package/src/client/components/mobile/mobile-main-view/Header.tsx +6 -12
  48. package/src/client/components/mobile/mobile-session-sidebar/Header.tsx +41 -13
  49. package/src/client/components/mobile/mobile-session-sidebar/use-dock.ts +1 -0
  50. package/src/client/components/settings/Modal.tsx +9 -3
  51. package/src/client/components/settings/ProjectSelectorDropdown.tsx +19 -9
  52. package/src/client/components/settings/categories/AgentSettings.tsx +27 -6
  53. package/src/client/components/settings/categories/ProjectSettings.tsx +122 -156
  54. package/src/client/components/settings/categories/SkillCatalogSettings.tsx +220 -260
  55. package/src/client/components/settings/categories/SkillSettings.tsx +6 -3
  56. package/src/client/components/settings/categories/agent-settings/SidebarList.tsx +5 -0
  57. package/src/client/components/settings/categories/project-settings/AccentPalette.test.tsx +189 -0
  58. package/src/client/components/settings/categories/project-settings/AccentPalette.tsx +156 -24
  59. package/src/client/components/settings/categories/project-settings/AddProjectModal.tsx +175 -0
  60. package/src/client/components/settings/categories/project-settings/DeleteProjectModal.tsx +107 -0
  61. package/src/client/components/settings/categories/project-settings/DetailsForm.tsx +40 -24
  62. package/src/client/components/settings/categories/project-settings/DetailsHeader.tsx +17 -7
  63. package/src/client/components/settings/categories/project-settings/IconGrid.tsx +164 -69
  64. package/src/client/components/settings/categories/project-settings/ModelDropdown.test.tsx +122 -0
  65. package/src/client/components/settings/categories/project-settings/ModelDropdown.tsx +124 -53
  66. package/src/client/components/settings/categories/project-settings/NameInput.tsx +57 -11
  67. package/src/client/components/settings/categories/project-settings/PathField.tsx +122 -0
  68. package/src/client/components/settings/categories/project-settings/SidebarList.tsx +100 -59
  69. package/src/client/components/settings/categories/skill-catalog/GitImportPanel.tsx +253 -0
  70. package/src/client/components/settings/categories/skill-catalog/SkillCard.tsx +89 -0
  71. package/src/client/components/settings/categories/skill-catalog/SourceRail.tsx +122 -0
  72. package/src/client/components/settings/categories/skill-catalog/catalog-ui.test.tsx +179 -0
  73. package/src/client/components/settings/categories/skill-settings/DetailHeader.tsx +208 -0
  74. package/src/client/components/settings/categories/skill-settings/DetailPane.tsx +137 -232
  75. package/src/client/components/settings/categories/skill-settings/InstructionsEditor.tsx +84 -0
  76. package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +123 -87
  77. package/src/client/components/settings/categories/skill-settings/pane.test.tsx +179 -0
  78. package/src/client/components/settings/categories/skill-settings/row-meta.ts +58 -0
  79. package/src/client/components/workspace/chat-timeline/index.tsx +6 -1
  80. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.test.ts +46 -0
  81. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.tsx +15 -6
  82. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.test.ts +29 -0
  83. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.tsx +11 -3
  84. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.test.ts +24 -1
  85. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.ts +6 -2
  86. package/src/client/components/workspace/editor/viewers/SvgPreview.tsx +18 -2
  87. package/src/client/components/workspace/editor/viewers/viewers.test.ts +39 -0
  88. package/src/client/components/workspace/file-explorer/ContextMenu.tsx +18 -5
  89. package/src/client/components/workspace/file-explorer/Modals.tsx +15 -1
  90. package/src/client/components/workspace/file-explorer/RowLabel.tsx +68 -0
  91. package/src/client/components/workspace/file-explorer/TreeItem.tsx +47 -57
  92. package/src/client/components/workspace/file-explorer/collapsed-chain.test.ts +167 -0
  93. package/src/client/components/workspace/file-explorer/drag-props.ts +42 -0
  94. package/src/client/components/workspace/file-explorer/drag.test.ts +43 -0
  95. package/src/client/components/workspace/file-explorer/index.tsx +21 -20
  96. package/src/client/components/workspace/model-dropdown/Panel.tsx +7 -2
  97. package/src/client/components/workspace/model-dropdown/Section.test.tsx +13 -0
  98. package/src/client/components/workspace/model-dropdown/Section.tsx +5 -1
  99. package/src/client/components/workspace/panels/builtin.tsx +7 -0
  100. package/src/client/components/workspace/wiki-panel/NavModal.test.tsx +136 -0
  101. package/src/client/components/workspace/wiki-panel/NavModal.tsx +94 -0
  102. package/src/client/components/workspace/wiki-panel/PageView.tsx +16 -10
  103. package/src/client/components/workspace/wiki-panel/index.tsx +44 -9
  104. package/src/client/data/settings/omp-schema.json +91 -4
  105. package/src/client/data/settings/project.ts +9 -28
  106. package/src/client/data/settings/skill.ts +6 -32
  107. package/src/client/hooks/chat/timeline/pending-model.ts +28 -0
  108. package/src/client/hooks/settings/projects/index.ts +294 -0
  109. package/src/client/hooks/settings/projects.test.ts +237 -0
  110. package/src/client/hooks/settings/skill-catalog.ts +101 -9
  111. package/src/client/hooks/settings/skill-git-import.ts +153 -0
  112. package/src/client/hooks/shell/servers.test.ts +166 -0
  113. package/src/client/hooks/{desktop → shell}/servers.ts +17 -14
  114. package/src/client/hooks/ui/updates/shell-download.ts +1 -1
  115. package/src/client/hooks/ui/updates/shell-update.ts +2 -6
  116. package/src/client/hooks/workspace/file-row-drag.ts +41 -0
  117. package/src/client/hooks/workspace/file-tree-actions.ts +25 -1
  118. package/src/client/hooks/workspace/file-tree-edits.ts +23 -6
  119. package/src/client/hooks/workspace/root-drop-target.ts +77 -0
  120. package/src/client/hooks/workspace/unfolded-chains.ts +165 -0
  121. package/src/client/lib/desktop/dropped-paths.ts +1 -1
  122. package/src/client/lib/desktop/titlebar.test.ts +12 -3
  123. package/src/client/lib/desktop/titlebar.ts +1 -1
  124. package/src/client/lib/shell/desktop.ts +117 -0
  125. package/src/client/lib/shell/servers.ts +75 -0
  126. package/src/client/lib/shell/transport.ts +216 -0
  127. package/src/client/main.tsx +9 -0
  128. package/src/server/lib/db/schema.ts +11 -0
  129. package/src/server/lib/fs/git-merge-conflict.test.ts +14 -1
  130. package/src/server/lib/lifecycle/memory.test.ts +41 -1
  131. package/src/server/lib/lifecycle/memory.ts +131 -14
  132. package/src/server/lib/omp/config/skill-sources.ts +49 -0
  133. package/src/server/lib/omp/config/skills-git-install.ts +155 -0
  134. package/src/server/lib/omp/config/skills-git-repo.ts +288 -0
  135. package/src/server/lib/omp/config/skills-git.test.ts +220 -0
  136. package/src/server/lib/omp/session/subagent-presence-scan.test.ts +137 -0
  137. package/src/server/lib/omp/session/subagent-presence-scan.ts +120 -0
  138. package/src/server/lib/omp/session/subagent-presence-store.test.ts +120 -0
  139. package/src/server/lib/omp/session/subagent-presence-store.ts +65 -0
  140. package/src/server/lib/omp/session/subagent-presence.ts +52 -15
  141. package/src/server/lib/workspace/project-model.server.test.ts +102 -0
  142. package/src/server/lib/workspace/project-model.server.ts +47 -0
  143. package/src/server/lib/workspace/project-patch.server.ts +156 -0
  144. package/src/server/routes/agent/new.ts +8 -1
  145. package/src/server/routes/settings/agents.ts +19 -7
  146. package/src/server/routes/settings/projects.ts +53 -19
  147. package/src/server/routes/settings/settings-projects-routes.test.ts +214 -0
  148. package/src/server/routes/settings/settings-store-routes.test.ts +5 -2
  149. package/src/server/routes/settings/skills-catalog-actions.ts +195 -0
  150. package/src/server/routes/settings/skills.test.ts +225 -0
  151. package/src/server/routes/settings/skills.ts +18 -15
  152. package/src/shared/lib/fs/folder-chain.test.ts +81 -1
  153. package/src/shared/lib/fs/folder-chain.ts +84 -0
  154. package/src/shared/lib/omp/config/schema.test.ts +35 -0
  155. package/src/shared/lib/omp/session/job-progress.test.ts +37 -1
  156. package/src/shared/lib/omp/session/job-progress.ts +31 -0
  157. package/src/shared/lib/omp/session/proc.ts +5 -0
  158. package/src/shared/lib/omp/session/wait.ts +5 -0
  159. package/src/shared/lib/ui/mobile-overlay.ts +61 -0
  160. package/src/shared/lib/ui/svg-scope.test.ts +97 -0
  161. package/src/shared/lib/ui/svg-scope.ts +134 -0
  162. package/src/shared/lib/workspace/project-accent.test.ts +69 -0
  163. package/src/shared/lib/workspace/project-accent.ts +63 -0
  164. package/src/shared/lib/workspace/project-icon.ts +40 -0
  165. package/src/shared/lib/workspace/project-model.test.ts +79 -0
  166. package/src/shared/lib/workspace/project-model.ts +64 -0
  167. package/src/shared/types/settings/skill.ts +53 -3
  168. package/src/test-support/file-explorer-disk.test-util.ts +25 -1
  169. package/src/test-support/file-explorer-drag.test-util.ts +88 -0
  170. package/src/test-support/file-explorer.test-util.ts +47 -47
  171. package/dist/client/static/js/index-28pwtt69.css +0 -1
  172. package/src/client/components/common/code-surface/indent-guide.ts +0 -104
  173. package/src/client/components/settings/categories/skill-catalog/AddSourceModal.tsx +0 -133
  174. package/src/client/hooks/desktop/servers.test.ts +0 -73
  175. package/src/client/lib/desktop/bridge.ts +0 -203
  176. package/src/shared/lib/code/editor/indent-guide-rule.test.ts +0 -65
  177. package/src/shared/lib/code/editor/indent-guide-rule.ts +0 -47
@@ -0,0 +1,216 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The shell transport, and the reason every other module asks this one whether it
8
+ * is running inside a shell.
9
+ *
10
+ * FIVE shells speak to this page, and they do NOT all inject the same thing:
11
+ *
12
+ * - `packages/macos` / `packages/windows` / `packages/linux` install
13
+ * `window.__kabmoCall` themselves, at document start, together with
14
+ * `window.__kabmoDesktop` (their identity). Nothing in this file has to run for
15
+ * them: `installShellTransport` is a no-op when a call function already exists.
16
+ * - `packages/android` exposes only `window.kabmoHost` (a `@JavascriptInterface`),
17
+ * and `packages/ios` only `window.webkit.messageHandlers.kabmo`. Neither can
18
+ * inject script before the page, so THIS module adapts their transport into
19
+ * `__kabmoCall` — one shape for the whole console — from
20
+ * `installShellTransport()` in `main.tsx`.
21
+ *
22
+ * The split between `isDesktopShell()` and `isMobileShell()` is load-bearing, not
23
+ * bookkeeping: `titlebarInsetLeft` treats "a shell, with no identity" as a macOS
24
+ * window whose traffic lights float over the page's left edge. A phone that
25
+ * answered `isDesktopShell() === true` would reserve 5rem for controls it does
26
+ * not have and draw its wordmark 80px from the edge.
27
+ *
28
+ * Params cross the mobile transport FORM-ENCODED (`k=v&k=v`), not as JSON:
29
+ * Android's `org.json` is a stub in a JVM unit test, so a JSON wire would leave
30
+ * the parser that most needs a test as the only one that cannot have one. State
31
+ * comes back as JSON TEXT for the same reason — the native side builds one string,
32
+ * and the page parses it in the one place that has a real JSON parser.
33
+ */
34
+
35
+ /** Which shell host is answering, once one is present. */
36
+ export type ShellHostKind = 'desktop' | 'android' | 'ios';
37
+
38
+ /** What a phone's native side exposes. Android only; iOS uses WebKit messages. */
39
+ interface AndroidHost {
40
+ post: (method: string, id: string, params: string) => void;
41
+ }
42
+
43
+ declare global {
44
+ interface Window {
45
+ __kabmoCall?: (method: string, params?: Record<string, unknown>) => Promise<unknown>;
46
+ __kabmoReply?: (id: number, ok: boolean, payload: unknown) => void;
47
+ /** Set by `installShellTransport` — which host answered this page. */
48
+ __kabmoShellHost?: 'android' | 'ios';
49
+ kabmoHost?: AndroidHost;
50
+ webkit?: {
51
+ messageHandlers?: {
52
+ kabmo?: { postMessage: (message: unknown) => void };
53
+ };
54
+ };
55
+ }
56
+ }
57
+
58
+ /** The host object a phone's native side has already installed, if any. */
59
+ function detectedHost(): 'android' | 'ios' | null {
60
+ if (typeof window === 'undefined') return null;
61
+ if (window.kabmoHost) return 'android';
62
+ if (window.webkit?.messageHandlers?.kabmo) return 'ios';
63
+ return null;
64
+ }
65
+
66
+ /**
67
+ * Which shell this page is inside, or null in a browser.
68
+ *
69
+ * A desktop shell is identified by the transport it installed by itself; a phone
70
+ * by the host object its native side exposes (or by the marker
71
+ * `installShellTransport` wrote once it adapted that host).
72
+ */
73
+ export function shellHost(): ShellHostKind | null {
74
+ if (typeof window === 'undefined') return null;
75
+ const marked = window.__kabmoShellHost;
76
+ if (marked) return marked;
77
+ // The DESKTOP trio is asked FIRST, and not for tidiness: macOS and Linux post
78
+ // over `window.webkit.messageHandlers.kabmo` — the very handler name iOS uses
79
+ // — so a phone-first check read every macOS/Linux shell as `ios`,
80
+ // `isDesktopShell()` answered false, and `titlebarInsetLeft` stopped reserving
81
+ // the 5rem macOS keeps for its traffic lights. The wordmark and the drawer's
82
+ // title were drawn UNDER close / minimise / maximise.
83
+ if (window.__kabmoDesktop) return 'desktop';
84
+ if (typeof window.__kabmoCall === 'function') return 'desktop';
85
+ return detectedHost();
86
+ }
87
+
88
+ /** True once some shell answers `__kabmoCall` — desktop or a phone. */
89
+ export function hasShellBridge(): boolean {
90
+ if (typeof window === 'undefined') return false;
91
+ if (typeof window.__kabmoCall === 'function') return true;
92
+ return detectedHost() !== null;
93
+ }
94
+
95
+ /** True in the macOS / Windows / Linux shells. */
96
+ export function isDesktopShell(): boolean {
97
+ return shellHost() === 'desktop';
98
+ }
99
+
100
+ /** True in the Android / iOS shells. */
101
+ export function isMobileShell(): boolean {
102
+ const host = shellHost();
103
+ return host === 'android' || host === 'ios';
104
+ }
105
+
106
+ /** `{ label: 'NAS', port: 3000 }` → `label=NAS&port=3000`. */
107
+ function encodeParams(params: Record<string, unknown>): string {
108
+ const parts: string[] = [];
109
+ for (const [key, value] of Object.entries(params)) {
110
+ if (value === undefined) continue;
111
+ const text = value === null ? '' : String(value);
112
+ parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(text)}`);
113
+ }
114
+ return parts.join('&');
115
+ }
116
+
117
+ /**
118
+ * How long a phone's shell gets to answer one command.
119
+ *
120
+ * `servers_state` PROBES every stored URL (`GET /api/health`, 6 s each), so the
121
+ * budget has to cover a short list of unreachable servers rather than a single
122
+ * round trip. A timeout here reports the shell as unresponsive, which is the
123
+ * honest answer for a native thread that never replied.
124
+ */
125
+ const REPLY_TIMEOUT_MS = 60_000;
126
+
127
+ /**
128
+ * Adapt a phone's native transport into the `__kabmoCall` shape the console uses.
129
+ *
130
+ * Idempotent, and a no-op in a browser and in a desktop shell (both either have no
131
+ * host or already have the function). Installed before the first render, so the
132
+ * server control is drawn on the first paint.
133
+ */
134
+ export function installShellTransport(): void {
135
+ if (typeof window === 'undefined') return;
136
+ // A desktop shell installed its own transport before the page's scripts, and
137
+ // macOS/Linux expose the same WebKit handler name a phone does — so this test
138
+ // is the identity, not `detectedHost()`.
139
+ if (window.__kabmoDesktop) return;
140
+ if (typeof window.__kabmoCall === 'function') return;
141
+ const host = detectedHost();
142
+ if (!host) return;
143
+
144
+ window.__kabmoShellHost = host;
145
+
146
+ // The bare globals, not `window.setTimeout`: this file's tests install a
147
+ // minimal `window`, and the timer is the one thing they must not have to fake.
148
+ /** The handle this runtime hands back: a number in a browser, an object under Bun. */
149
+ type TimerHandle = ReturnType<typeof setTimeout>;
150
+
151
+ interface PendingReply {
152
+ resolve: (value: unknown) => void;
153
+ reject: (reason: Error) => void;
154
+ timer: TimerHandle;
155
+ }
156
+ const pending = new Map<number, PendingReply>();
157
+ let next = 1;
158
+
159
+ window.__kabmoReply = (id, ok, payload) => {
160
+ const entry = pending.get(id);
161
+ if (!entry) return;
162
+ pending.delete(id);
163
+ clearTimeout(entry.timer);
164
+ if (!ok) {
165
+ entry.reject(new Error(typeof payload === 'string' ? payload : 'The shell refused that command.'));
166
+ return;
167
+ }
168
+ // State crosses as JSON TEXT (see this module's header): an unparseable answer
169
+ // is still the shell's answer, so it resolves as-is rather than turning a
170
+ // working command into a failure.
171
+ if (typeof payload !== 'string') {
172
+ entry.resolve(payload);
173
+ return;
174
+ }
175
+ try {
176
+ entry.resolve(JSON.parse(payload));
177
+ } catch {
178
+ entry.resolve(payload);
179
+ }
180
+ };
181
+
182
+ window.__kabmoCall = (method, params) => {
183
+ const { promise, resolve, reject } = Promise.withResolvers<unknown>();
184
+ const id = next++;
185
+ const timer = setTimeout(() => {
186
+ pending.delete(id);
187
+ reject(new Error(`The shell did not answer ${method} within 60s.`));
188
+ }, REPLY_TIMEOUT_MS);
189
+ pending.set(id, { resolve, reject, timer });
190
+ const form = encodeParams(params ?? {});
191
+ if (host === 'android') {
192
+ window.kabmoHost?.post(method, String(id), form);
193
+ } else {
194
+ window.webkit?.messageHandlers?.kabmo?.postMessage({ id, method, params: form });
195
+ }
196
+ return promise;
197
+ };
198
+ }
199
+
200
+ /** One command over whichever transport this shell installed. */
201
+ export async function callShell<T>(method: string, params: Record<string, unknown> = {}): Promise<T> {
202
+ const invoke = typeof window === 'undefined' ? undefined : window.__kabmoCall;
203
+ if (!invoke) throw new Error('Not running inside a Kabmo shell.');
204
+ return (await invoke(method, params)) as T;
205
+ }
206
+
207
+ /**
208
+ * A refused command's message.
209
+ *
210
+ * The shell sends its own sentence (a refused URL, a server that exited), which is
211
+ * what the UI shows. Nothing is stripped: a message that genuinely starts with
212
+ * "Error" would lose its first word.
213
+ */
214
+ export function bridgeError(error: unknown): string {
215
+ return error instanceof Error ? error.message : String(error);
216
+ }
@@ -12,6 +12,7 @@ import { installUiKit } from '@/client/lib/plugins/kit';
12
12
  import { installScrollbarActivity } from '@/client/lib/scrollbar-activity';
13
13
  import { installBackDispatcher } from '@/client/lib/native/back';
14
14
  import { installPalettePublisher } from '@/client/lib/native/palette';
15
+ import { installShellTransport } from '@/client/lib/shell/transport';
15
16
  import { installResumeDispatcher } from '@/client/lib/native/resume';
16
17
  import { installFileLaunchHandler } from '@/client/lib/launch/file-handlers';
17
18
  import { installOpenPaths } from '@/client/lib/native/open-paths';
@@ -79,6 +80,14 @@ installBackDispatcher();
79
80
  // asks on the load it is hiding, not on a later interaction.
80
81
  installPalettePublisher();
81
82
 
83
+ // A phone's shell exposes its own transport (`window.kabmoHost` on Android,
84
+ // `window.webkit.messageHandlers.kabmo` on iOS) and cannot inject script before
85
+ // the page — so the console adapts it into `__kabmoCall` here, before the first
86
+ // render, which is what makes the header's server control appear on the first
87
+ // paint instead of after a round trip. A no-op in a browser and in the three
88
+ // desktop shells, which install `__kabmoCall` themselves.
89
+ installShellTransport();
90
+
82
91
  // The native shell calls `window.__kabmoResume()` when its app returns to the
83
92
  // foreground. A backgrounded Android WebView fires no `visibilitychange` and
84
93
  // gets no `close` for a socket the server reaped, so the shell's own lifecycle
@@ -74,6 +74,17 @@ export async function initSchema(db: DbClient): Promise<void> {
74
74
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
75
75
  );
76
76
 
77
+ -- The sidebar's subagent badge, saved per file version so a restart does
78
+ -- not re-derive it by streaming every transcript (see
79
+ -- lib/omp/session/subagent-presence-store). Derived data: deleting the
80
+ -- table only costs one cold pass.
81
+ CREATE TABLE IF NOT EXISTS session_subagent_presence (
82
+ session_path TEXT PRIMARY KEY,
83
+ version TEXT NOT NULL,
84
+ has_subagents INTEGER NOT NULL,
85
+ updated_at INTEGER NOT NULL DEFAULT 0
86
+ );
87
+
77
88
  CREATE TABLE IF NOT EXISTS queued_messages (
78
89
  id TEXT PRIMARY KEY,
79
90
  session_id TEXT NOT NULL,
@@ -20,7 +20,7 @@
20
20
  * a real failure (a bad ref, a dirty tree) leaves none.
21
21
  */
22
22
 
23
- import { afterEach, describe, expect, test } from 'bun:test';
23
+ import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
24
24
  import fs from 'node:fs';
25
25
  import os from 'node:os';
26
26
  import path from 'node:path';
@@ -28,6 +28,19 @@ import { mergeBranch, rebaseOnto } from '@/server/lib/fs/git-merge';
28
28
  import { applyStash, pushStash } from '@/server/lib/fs/git-stash';
29
29
  import { readGitState } from '@/server/lib/fs/git-state';
30
30
 
31
+ /**
32
+ * Every case here builds a real repository and drives several `git` processes
33
+ * through it (`init`, two `config`, `add`, two `commit`, `stash push`, `stash
34
+ * pop`), so Bun's 5s per-test default is a budget for the RUNNER rather than
35
+ * for the code. Measured on `windows-latest`: "applyStash resolves with the
36
+ * stash-pop state" timed out at 5011ms while the same suite is green locally in
37
+ * well under a second, and process spawn on that runner costs several times
38
+ * what it does on POSIX. A budget, not a skip: the behaviour is identical on
39
+ * both platforms. `git-actions-sync.test.ts` and the route's `git-merge.test.ts`
40
+ * set the same 30s for the same reason.
41
+ */
42
+ setDefaultTimeout(30_000);
43
+
31
44
  const repos: string[] = [];
32
45
 
33
46
  afterEach(() => {
@@ -13,7 +13,13 @@
13
13
  */
14
14
 
15
15
  import { afterEach, describe, expect, test } from 'bun:test';
16
- import { maintainMemory, snapshot, stopMemoryMaintenance } from '@/server/lib/lifecycle/memory';
16
+ import {
17
+ footprintMBFromOutput,
18
+ footprintMBFromSmapsRollup,
19
+ maintainMemory,
20
+ snapshot,
21
+ stopMemoryMaintenance,
22
+ } from '@/server/lib/lifecycle/memory';
17
23
 
18
24
  const originalCeiling = Bun.env.KABMO_MEMORY_CEILING_MB;
19
25
 
@@ -57,6 +63,40 @@ describe('snapshot', () => {
57
63
  );
58
64
  expect(Math.abs(snapshot().rssMB - Math.round(psKb / 1024))).toBeLessThanOrEqual(2);
59
65
  });
66
+
67
+ test('reports a physical footprint, because RSS is not the memory in use', () => {
68
+ // On macOS a Bun process that has read and dropped a transcript keeps
69
+ // freed pages resident: measured on a live server, RSS 752 MB against a
70
+ // 70.6 MB physical footprint and a 24 MB JS heap. The sweep reacts to the
71
+ // footprint, so it has to be there.
72
+ const snap = snapshot();
73
+ expect(snap.footprintMB).not.toBeNull();
74
+ expect(snap.footprintMB ?? 0).toBeGreaterThan(0);
75
+ // A footprint larger than the resident set would mean the parser read the
76
+ // wrong field; compressed pages can push it close, never past it by much.
77
+ expect(snap.footprintMB ?? 0).toBeLessThanOrEqual(snap.rssMB * 1.25 + 16);
78
+ });
79
+ });
80
+
81
+ describe('footprint parsing', () => {
82
+ test('reads the macOS `footprint -p` headline', () => {
83
+ expect(footprintMBFromOutput('bun [98166]: 64-bit Footprint: 122 MB (16384 bytes per page)')).toBe(122);
84
+ });
85
+
86
+ test('honours the unit the tool prints', () => {
87
+ expect(footprintMBFromOutput(' Footprint: 512 KB (4096 bytes per page)')).toBe(1);
88
+ expect(footprintMBFromOutput(' Footprint: 1.5 GB (16384 bytes per page)')).toBe(1536);
89
+ });
90
+
91
+ test('an unreadable report is null rather than a guess', () => {
92
+ expect(footprintMBFromOutput('')).toBeNull();
93
+ expect(footprintMBFromOutput('some other report')).toBeNull();
94
+ });
95
+
96
+ test('reads Pss from Linux smaps_rollup', () => {
97
+ expect(footprintMBFromSmapsRollup('Rss: 40960 kB\nPss: 12345 kB\nPss_Anon: 1 kB\n')).toBe(12);
98
+ expect(footprintMBFromSmapsRollup('Rss: 40960 kB\n')).toBeNull();
99
+ });
60
100
  });
61
101
 
62
102
  describe('maintainMemory', () => {
@@ -18,12 +18,6 @@
18
18
  * | 20 concurrent `GET /api/chat/:id` | 1.69 GB |
19
19
  * | 10 s idle afterwards | 1.13 GB |
20
20
  *
21
- * The same work with an explicit `Bun.gc(true)` in the middle measured
22
- * 319 MB → 69 MB in a standalone probe, so the memory is garbage the collector
23
- * had simply not been asked to reclaim — a young-generation collection returns
24
- * the JS objects but leaves the arena, and nothing in this process allocates
25
- * enough to force a full one.
26
- *
27
21
  * Two rules keep the sweep honest:
28
22
  *
29
23
  * 1. **It is a CEILING, not a schedule.** A full collection is stop-the-world,
@@ -32,11 +26,39 @@
32
26
  * 2. **It is observable.** `snapshot()` is what `/api/health` reports, so the
33
27
  * condition the sweep reacts to is visible from `kabmo status` rather than
34
28
  * only from Activity Monitor.
29
+ *
30
+ * ## Which number is "memory"
31
+ *
32
+ * RSS is NOT it. On macOS a Bun process that has read and dropped a large
33
+ * transcript keeps the freed pages resident: measured on a live server, RSS
34
+ * 752 MB while the operating system charged the process a 70.6 MB physical
35
+ * footprint (`vmmap -summary`), with a 24 MB JS heap — and `Bun.gc(true)`
36
+ * changed nothing (`swept 1049 MB → 1050 MB`, every minute, for hours). The
37
+ * same process's RSS fell to 134 MB on its own once the OS reclaimed the
38
+ * clean pages.
39
+ *
40
+ * So the ceiling is applied to the OS's PHYSICAL FOOTPRINT where the host can
41
+ * answer, and `rssMB` is reported beside it as a diagnostic because that is
42
+ * the number `ps`-style tools show. `footprint -p <pid>` prints it on macOS
43
+ * (78 ms, and its headline matched `vmmap`'s "Physical footprint" exactly —
44
+ * 122 MB against 121.6 MB); Linux answers from `/proc/self/smaps_rollup`
45
+ * (`Pss`, which discounts shared pages) with `VmRSS` as the fallback; Windows
46
+ * uses the runtime's own number, which is accurate there.
47
+ *
48
+ * A reading is cached for `FOOTPRINT_TTL_MS`: the probe costs a spawn, and
49
+ * `/api/health` is polled far more often than the number can move. The sweep
50
+ * always refreshes both sides, because it is reporting the effect of a
51
+ * collection it just ran.
35
52
  */
36
53
 
54
+ import { readFileSync } from 'node:fs';
55
+
37
56
  /** Bytes in a megabyte, for the MB-shaped numbers this module reports. */
38
57
  const BYTES_PER_MB = 1024 * 1024;
39
58
 
59
+ /** How long an operating-system footprint reading is reused. */
60
+ const FOOTPRINT_TTL_MS = 30_000;
61
+
40
62
  /**
41
63
  * The process's resident set, in MB, from the OPERATING SYSTEM.
42
64
  *
@@ -69,6 +91,79 @@ function residentMB(): number {
69
91
  return Math.round(process.memoryUsage().rss / BYTES_PER_MB);
70
92
  }
71
93
 
94
+ /**
95
+ * The footprint line from `footprint -p <pid>`:
96
+ * `bun [123]: 64-bit Footprint: 122 MB (16384 bytes per page)`.
97
+ *
98
+ * Exported as a pure parser so the shape is pinned without spawning anything.
99
+ */
100
+ export function footprintMBFromOutput(output: string): number | null {
101
+ const match = /Footprint:\s+([\d.]+)\s+(B|KB|MB|GB)\b/i.exec(output);
102
+ if (!match) return null;
103
+ const value = Number(match[1]);
104
+ if (!Number.isFinite(value)) return null;
105
+ const unit = match[2].toUpperCase();
106
+ const mb = unit === 'GB' ? value * 1024
107
+ : unit === 'KB' ? value / 1024
108
+ : unit === 'B' ? value / BYTES_PER_MB
109
+ : value;
110
+ return Math.round(mb);
111
+ }
112
+
113
+ /** `Pss:` from `/proc/self/smaps_rollup` — the Linux analogue of footprint. */
114
+ export function footprintMBFromSmapsRollup(text: string): number | null {
115
+ const match = /^Pss:\s+(\d+)\s+kB$/m.exec(text);
116
+ if (!match) return null;
117
+ return Math.round(Number(match[1]) / 1024);
118
+ }
119
+
120
+ /** The OS's own charge for this process, in MB, or null where it cannot answer. */
121
+ function readFootprintMB(): number | null {
122
+ if (process.platform === 'win32') {
123
+ return Math.round(process.memoryUsage().rss / BYTES_PER_MB);
124
+ }
125
+ if (process.platform === 'linux') {
126
+ try {
127
+ const pss = footprintMBFromSmapsRollup(readFileSync('/proc/self/smaps_rollup', 'utf8'));
128
+ if (pss !== null) return pss;
129
+ } catch {
130
+ // smaps_rollup is unreadable on a hardened kernel; VmRSS below.
131
+ }
132
+ try {
133
+ const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(readFileSync('/proc/self/status', 'utf8'));
134
+ if (match) return Math.round(Number(match[1]) / 1024);
135
+ } catch {
136
+ return null;
137
+ }
138
+ return null;
139
+ }
140
+ try {
141
+ const out = Bun.spawnSync(['footprint', '-p', String(process.pid)]);
142
+ return footprintMBFromOutput(out.stdout.toString());
143
+ } catch {
144
+ // No `footprint` on this host (an older macOS, another POSIX): the sweep
145
+ // falls back to RSS.
146
+ return null;
147
+ }
148
+ }
149
+
150
+ interface FootprintCache {
151
+ at: number;
152
+ mb: number | null;
153
+ }
154
+
155
+ let footprintCache: FootprintCache | null = null;
156
+
157
+ /** The cached OS charge, refreshed when `refresh` or when the reading is stale. */
158
+ function footprintMB(refresh: boolean): number | null {
159
+ if (!refresh && footprintCache && Date.now() - footprintCache.at < FOOTPRINT_TTL_MS) {
160
+ return footprintCache.mb;
161
+ }
162
+ const mb = readFootprintMB();
163
+ footprintCache = { at: Date.now(), mb };
164
+ return mb;
165
+ }
166
+
72
167
  /** Default ceiling: above this, a sweep is worth a pause. */
73
168
  const DEFAULT_CEILING_MB = 1024;
74
169
 
@@ -77,8 +172,13 @@ const DEFAULT_CEILING_MB = 1024;
77
172
  const DEFAULT_INTERVAL_MS = 60_000;
78
173
 
79
174
  export interface MemorySnapshot {
80
- /** Resident set size in MB — what a process monitor shows. */
175
+ /** Resident set size in MB — what a `ps`-style monitor shows. On macOS it
176
+ * counts freed pages Bun has not returned, so it can exceed the footprint
177
+ * many times over. Reported for diagnosis; never the sweep's input. */
81
178
  rssMB: number;
179
+ /** What the operating system actually charges this process, in MB. Null when
180
+ * the host cannot answer. This is the number the sweep reacts to. */
181
+ footprintMB: number | null;
82
182
  /** Live JS objects in MB. */
83
183
  heapUsedMB: number;
84
184
  /** Reserved JS heap in MB (what the collector has not returned). */
@@ -97,16 +197,26 @@ export interface MemoryMaintenance {
97
197
  stop: () => void;
98
198
  }
99
199
 
100
- /** The process's memory, in MB. Reads `process.memoryUsage()`, never throws. */
101
- export function snapshot(): MemorySnapshot {
200
+ function takeSnapshot(refreshFootprint: boolean): MemorySnapshot {
102
201
  const usage = process.memoryUsage();
103
202
  return {
104
203
  rssMB: residentMB(),
204
+ footprintMB: footprintMB(refreshFootprint),
105
205
  heapUsedMB: Math.round(usage.heapUsed / BYTES_PER_MB),
106
206
  heapTotalMB: Math.round(usage.heapTotal / BYTES_PER_MB),
107
207
  };
108
208
  }
109
209
 
210
+ /** The process's memory, in MB. Cached footprint, never throws. */
211
+ export function snapshot(): MemorySnapshot {
212
+ return takeSnapshot(false);
213
+ }
214
+
215
+ /** The pressure the ceiling is applied to: the OS's charge when it is known. */
216
+ function pressureMB(snap: MemorySnapshot): number {
217
+ return snap.footprintMB ?? snap.rssMB;
218
+ }
219
+
110
220
  /** The ceiling in bytes, from `KABMO_MEMORY_CEILING_MB` when set. */
111
221
  function ceilingBytes(): number {
112
222
  const raw = Number(Bun.env.KABMO_MEMORY_CEILING_MB);
@@ -121,14 +231,16 @@ function ceilingBytes(): number {
121
231
  * arena is holding it — the maintenance interval never passes it.
122
232
  */
123
233
  export function maintainMemory(force = false): SweepResult {
124
- const before = snapshot();
125
- if (!force && before.rssMB * BYTES_PER_MB < ceilingBytes()) {
234
+ // Both sides refresh the OS reading: this function exists to report what a
235
+ // collection did, and a cached number would report the state before it.
236
+ const before = takeSnapshot(true);
237
+ if (!force && pressureMB(before) * BYTES_PER_MB < ceilingBytes()) {
126
238
  return { swept: false, before, after: before };
127
239
  }
128
240
  // A full collection: the point is to release the arena, and the young
129
241
  // generation alone is what failed to do that.
130
242
  Bun.gc(true);
131
- return { swept: true, before, after: snapshot() };
243
+ return { swept: true, before, after: takeSnapshot(true) };
132
244
  }
133
245
 
134
246
  /** Where the interval lives, so a `bun --hot` reload does not install a second. */
@@ -159,7 +271,12 @@ export function installMemoryMaintenance(): MemoryMaintenance {
159
271
  try {
160
272
  const result = maintainMemory();
161
273
  if (result.swept) {
162
- console.log(`[kabmo] memory: swept ${result.before.rssMB} MB → ${result.after.rssMB} MB`);
274
+ // Footprint first: it is the number the decision used, and the one a
275
+ // reader should trust. RSS rides along because a monitor shows it.
276
+ console.log(
277
+ `[kabmo] memory: swept ${pressureMB(result.before)} MB → ${pressureMB(result.after)} MB`
278
+ + ` (rss ${result.after.rssMB} MB)`,
279
+ );
163
280
  }
164
281
  } catch (error) {
165
282
  // A sweep is maintenance, never a reason to take the server down.
@@ -170,4 +287,4 @@ export function installMemoryMaintenance(): MemoryMaintenance {
170
287
  timer.unref?.();
171
288
  host.__kabmoMemorySweep = timer;
172
289
  return { stop: stopMemoryMaintenance };
173
- }
290
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The stored catalog sources — the git repositories the Skills Catalog offers.
8
+ *
9
+ * Its own module because two surfaces read it (the loader's payload and every
10
+ * source mutation) and a second reader is how the two shapes would drift. The
11
+ * normalisation is the whole job: a source written by the previous UI carried
12
+ * `stars` and `updatedAt` literals that no request had produced, and a count
13
+ * that was never measured. Reading through `toCatalogSource` drops the first two
14
+ * and turns a missing count into `null` — "not scanned" — which is what the card
15
+ * prints. A guessed number is indistinguishable from a measured one once it is on
16
+ * screen, so it is never stored.
17
+ */
18
+
19
+ import type { SkillCatalogSource } from '@/shared/types';
20
+ import { DEFAULT_CATALOG_SOURCES } from '@/client/data/settings/skill';
21
+ import { readSettingsJson, writeSettingsJson } from '@/server/lib/db/settings-store';
22
+ import type { DbClient } from '@/server/lib/db/client';
23
+
24
+ export const SOURCES_KEY = 'omp_catalog_sources';
25
+
26
+ /** One stored record, narrowed to the fields this build understands. */
27
+ export function toCatalogSource(source: Partial<SkillCatalogSource>): SkillCatalogSource {
28
+ return {
29
+ id: String(source.id ?? ''),
30
+ name: String(source.name ?? source.repo ?? 'source'),
31
+ repo: String(source.repo ?? ''),
32
+ skillCount: typeof source.skillCount === 'number' ? source.skillCount : null,
33
+ scannedAt: typeof source.scannedAt === 'number' ? source.scannedAt : null,
34
+ isCustom: source.isCustom === true,
35
+ };
36
+ }
37
+
38
+ /** Every source, with the shipped defaults standing in when none is stored. */
39
+ export async function readCatalogSources(db: DbClient): Promise<SkillCatalogSource[]> {
40
+ const stored = await readSettingsJson<Partial<SkillCatalogSource>[]>(db, SOURCES_KEY, DEFAULT_CATALOG_SOURCES);
41
+ const list = Array.isArray(stored) && stored.length > 0 ? stored : DEFAULT_CATALOG_SOURCES;
42
+ // `toCatalogSource` with no id is a record this build cannot address; drop it
43
+ // rather than render a card every action would 404 on.
44
+ return list.map(toCatalogSource).filter((source) => source.id.length > 0 && source.repo.length > 0);
45
+ }
46
+
47
+ export async function writeCatalogSources(db: DbClient, sources: SkillCatalogSource[]): Promise<void> {
48
+ await writeSettingsJson(db, SOURCES_KEY, sources);
49
+ }