@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,47 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The default model a NEW chat inherits from the workspace it starts in.
8
+ *
9
+ * "Defaults for new chats" on a project is only a setting if the spawn reads
10
+ * it. The spawn used to fall back to Kabmo's global persisted pick and nothing
11
+ * else, so the project's model column rendered in the settings pane and in the
12
+ * sidebar payload while every chat actually started on the global pick — a
13
+ * control that promised something it never decided.
14
+ *
15
+ * Resolution is by the spawn's cwd, compared the way the sidebar compares
16
+ * folders: the row holds the spelling the user registered, while the composer
17
+ * may hand over a worktree or a symlinked path of the same project.
18
+ */
19
+
20
+ import type { DbClient } from '@/server/lib/db/client';
21
+ import { projectPathKey } from '@/server/lib/omp/core/paths';
22
+ import { parseProjectModel } from '@/shared/lib/workspace/project-model';
23
+ import type { SelectedModel } from '@/shared/types';
24
+
25
+ export async function projectModelForCwd(db: DbClient, cwd: string | null | undefined): Promise<SelectedModel | null> {
26
+ if (!cwd || !cwd.trim()) return null;
27
+
28
+ const rows = await db.all<{ model: string | null; project_path: string | null }>(
29
+ 'SELECT model, project_path FROM workspace_folders WHERE project_path IS NOT NULL ORDER BY length(project_path) DESC',
30
+ );
31
+ if (rows.length === 0) return null;
32
+
33
+ const target = projectPathKey(cwd);
34
+ const exact = rows.find((row) => row.project_path && projectPathKey(row.project_path) === target);
35
+ if (exact) return parseProjectModel(exact.model);
36
+
37
+ // A linked checkout runs outside its project root, and its own path is not
38
+ // registered — so the nearest bound root that CONTAINS it is the folder the
39
+ // chat belongs to. Longest first, so a project nested inside another
40
+ // workspace resolves to the more specific one.
41
+ const nested = rows.find((row) => {
42
+ if (!row.project_path) return false;
43
+ const root = projectPathKey(row.project_path);
44
+ return target.startsWith(`${root}/`);
45
+ });
46
+ return nested ? parseProjectModel(nested.model) : null;
47
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Turn a settings PATCH body for one workspace into a row patch the store can
8
+ * apply, or a refusal that names what is wrong.
9
+ *
10
+ * The pane edits facts that decide where chats run and which sessions appear in
11
+ * the sidebar, so a value that cannot be honoured must be refused HERE rather
12
+ * than written and quietly ignored:
13
+ *
14
+ * - **A project needs a name.** The store skips an empty name on purpose (so a
15
+ * partial update cannot blank a row), which meant the field could be cleared
16
+ * on screen while the old name stayed on the server — a rename that silently
17
+ * did nothing.
18
+ * - **Names are unique case-insensitively**, the same rule the creation path
19
+ * enforces (`registerWorkspaceFolder`), because the sidebar identifies a
20
+ * workspace by its name.
21
+ * - **A project path must be a real directory**, expanded from `~` exactly like
22
+ * the creation path. Binding a typo produced a folder that listed no sessions
23
+ * forever with nothing on screen saying why.
24
+ * - **An accent must be a hex colour.** The sidebar paints it into a CSS
25
+ * `color`, so a free-form string is a style injection, not a preference.
26
+ * - **One directory, one workspace.** Two rows bound to the same root list the
27
+ * same sessions twice and fight over the discovery tombstones.
28
+ */
29
+
30
+ import { getDb } from '@/server/db.server';
31
+ import type { DbClient } from '@/server/lib/db/client';
32
+ import { projectPathKey } from '@/server/lib/omp/core/paths';
33
+ import { expandHome } from '@/server/routes/folders/create';
34
+ import { normalizeHexAccent } from '@/shared/lib/workspace/project-accent';
35
+ import { parseFolderSettingsPatch, type FolderSettingsPatch } from '@/shared/lib/workspace/project-settings';
36
+
37
+ export type PreparedProjectPatch =
38
+ | { ok: true; patch: FolderSettingsPatch }
39
+ | { ok: false; status: number; error: string; code?: string };
40
+
41
+ /** An icon may be an uploaded raster (data URL) or a fetched absolute URL. */
42
+ const MAX_ICON_CHARS = 700_000; // ~512 KiB of bytes, base64-inflated
43
+
44
+ /**
45
+ * True when the value is something an `<img src>` can render and the store may
46
+ * keep. The field is written from the client, and without this a whole
47
+ * megabyte image, a `javascript:` URI or a relative path could be persisted as
48
+ * a project icon and then rendered in every sidebar row.
49
+ */
50
+ function isIconUrl(value: string): boolean {
51
+ if (value.length > MAX_ICON_CHARS) return false;
52
+ if (/^data:image\/(png|jpeg|jpg|svg\+xml|webp|gif);base64,[A-Za-z0-9+/=]+$/.test(value)) return true;
53
+ try {
54
+ const url = new URL(value);
55
+ return url.protocol === 'https:' || url.protocol === 'http:';
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ /** True when the path is an existing directory (symlinks followed). */
62
+ async function isDirectory(target: string): Promise<boolean> {
63
+ try {
64
+ return (await Bun.file(target).stat()).isDirectory();
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ export async function prepareProjectPatch(
71
+ db: DbClient,
72
+ folderId: string,
73
+ raw: unknown,
74
+ ): Promise<PreparedProjectPatch> {
75
+ const patch = parseFolderSettingsPatch(raw);
76
+
77
+ if (patch.name !== undefined && patch.name === '') {
78
+ return { ok: false, status: 400, error: 'A project needs a name', code: 'name_required' };
79
+ }
80
+
81
+ if (patch.name !== undefined) {
82
+ const clash = await db.get<{ id: number }>(
83
+ 'SELECT id FROM workspace_folders WHERE lower(name) = lower(?) AND id != ?',
84
+ [patch.name, folderId],
85
+ );
86
+ if (clash) {
87
+ return {
88
+ ok: false,
89
+ status: 409,
90
+ error: `A workspace named "${patch.name}" already exists`,
91
+ code: 'duplicate_name',
92
+ };
93
+ }
94
+ }
95
+
96
+ if (patch.accentColor !== undefined && patch.accentColor !== '') {
97
+ const normalized = normalizeHexAccent(patch.accentColor);
98
+ if (normalized === null) {
99
+ return {
100
+ ok: false,
101
+ status: 400,
102
+ error: 'An accent must be a hex colour like #7c3aed',
103
+ code: 'invalid_accent',
104
+ };
105
+ }
106
+ // Stored in ONE form — the sidebar paints this straight into a style, and two
107
+ // spellings of the same colour would defeat the "is this a preset?" check.
108
+ patch.accentColor = normalized;
109
+ }
110
+
111
+ if (patch.customIconUrl !== undefined && patch.customIconUrl !== null && !isIconUrl(patch.customIconUrl)) {
112
+ return {
113
+ ok: false,
114
+ status: 400,
115
+ error: 'An icon must be an uploaded image or an http(s) URL under 512 KiB',
116
+ code: 'invalid_icon',
117
+ };
118
+ }
119
+
120
+ if (patch.projectPath) {
121
+ const resolved = expandHome(patch.projectPath);
122
+ if (!(await isDirectory(resolved))) {
123
+ return {
124
+ ok: false,
125
+ status: 400,
126
+ error: `Directory does not exist: ${patch.projectPath}`,
127
+ code: 'directory_not_found',
128
+ };
129
+ }
130
+ const target = projectPathKey(resolved);
131
+ const bound = await db.all<{ id: number; project_path: string | null }>(
132
+ 'SELECT id, project_path FROM workspace_folders WHERE project_path IS NOT NULL AND id != ?',
133
+ [folderId],
134
+ );
135
+ const duplicate = bound.find((row) => row.project_path && projectPathKey(row.project_path) === target);
136
+ if (duplicate) {
137
+ // A worktree of a bound project canonicalizes elsewhere, so this only
138
+ // refuses the same project root twice.
139
+ const other = await db.get<{ name: string }>('SELECT name FROM workspace_folders WHERE id = ?', [duplicate.id]);
140
+ return {
141
+ ok: false,
142
+ status: 409,
143
+ error: `${other?.name ?? 'Another workspace'} is already bound to ${resolved}`,
144
+ code: 'duplicate_path',
145
+ };
146
+ }
147
+ patch.projectPath = resolved;
148
+ }
149
+
150
+ return { ok: true, patch };
151
+ }
152
+
153
+ /** Convenience for route handlers: prepare against the process database. */
154
+ export async function prepareProjectPatchForStore(folderId: string, raw: unknown): Promise<PreparedProjectPatch> {
155
+ return prepareProjectPatch(await getDb(), folderId, raw);
156
+ }
@@ -7,6 +7,7 @@ import { loadPersistedAccessMode } from '@/shared/lib/omp/config/access-mode.ser
7
7
  import { rpcErrorResponse } from '@/server/lib/omp/rpc/errors';
8
8
  import { kabmoModeEnv } from '@/server/lib/omp/extensions/locator';
9
9
  import { parseModeSelection } from '@/server/lib/omp/mode/request';
10
+ import { projectModelForCwd } from '@/server/lib/workspace/project-model.server';
10
11
 
11
12
  /** The model-dropdown persists its selection here (actionType 'selectModel');
12
13
  * a spawn that arrives without an explicit provider/modelId falls back to it. */
@@ -79,7 +80,13 @@ export async function action({ request }: ActionFunctionArgs) {
79
80
  thinkingLevel?: string;
80
81
  };
81
82
 
82
- const effectiveModel = provider && modelId ? { provider, modelId } : await loadPersistedModel();
83
+ // The workspace's own default is the FIRST fallback: "Defaults for new
84
+ // chats" exists to decide the model a chat starts on, so a project pick
85
+ // outranks Kabmo's global one for a chat born in that project.
86
+ const projectModel = await projectModelForCwd(await getDb(), cwd);
87
+ const effectiveModel = provider && modelId
88
+ ? { provider, modelId }
89
+ : projectModel ?? await loadPersistedModel();
83
90
  if (effectiveModel) {
84
91
  await session.send({ type: 'set_model', ...effectiveModel }).catch(() => {});
85
92
  }
@@ -6,7 +6,9 @@ import { DEFAULT_AGENTS_LIST } from '@/client/data/agent-data';
6
6
  import { isMockMode } from '@/server/mock.server';
7
7
  import type { AgentItem } from '@/shared/types';
8
8
  import { createSettingsListStore } from '@/server/lib/db/settings-store';
9
+ import { join } from 'path';
9
10
  import { deleteAgentDefinition, discoverNativeAgents, writeAgentDefinition, type DiscoveredAgent } from '@/server/lib/omp/config/agents';
11
+ import { resolveRoot } from '@/server/lib/fs/root';
10
12
 
11
13
  const agentsStore = createSettingsListStore<AgentItem>({
12
14
  key: 'omp_agents',
@@ -40,8 +42,8 @@ function nativeToAgentItem(agent: DiscoveredAgent): AgentItem & { sourceRoot: st
40
42
  }
41
43
 
42
44
  /** Merge native omp agents (disk discovery) with app-local custom agents. */
43
- async function mergeAgents(custom: AgentItem[]): Promise<Array<AgentItem & { sourceRoot?: string }>> {
44
- const native = (await discoverNativeAgents()).map(nativeToAgentItem);
45
+ async function mergeAgents(custom: AgentItem[], projectDir?: string): Promise<Array<AgentItem & { sourceRoot?: string }>> {
46
+ const native = (await discoverNativeAgents(projectDir)).map(nativeToAgentItem);
45
47
  const nativeNames = new Set(native.map((a) => a.name.toLowerCase()));
46
48
  return [...native, ...custom.filter((a) => !nativeNames.has(a.name.toLowerCase()))];
47
49
  }
@@ -54,13 +56,23 @@ export async function loader({ request }: LoaderFunctionArgs) {
54
56
  const mock = isMockMode();
55
57
  const agents = await agentsStore.read(db);
56
58
 
59
+ // The panel's project picker is a SCOPE, not decoration: `<workspace>/.omp/agents`
60
+ // holds agents that only exist for that workspace, and an unscoped read
61
+ // could never list them. Gated through `resolveRoot` like every other
62
+ // client-supplied path, so an arbitrary directory is not readable here.
63
+ const rawRoot = url.searchParams.get('root');
64
+ const projectDir = rawRoot
65
+ ? join(await resolveRoot(rawRoot, ''), '.omp', 'agents')
66
+ : undefined;
67
+
57
68
  if (includeNative && !mock) {
58
- return json({ agents: await mergeAgents(agents), isMock: mock });
69
+ return json({ agents: await mergeAgents(agents, projectDir), isMock: mock });
59
70
  }
60
71
 
61
72
  return json({ agents, isMock: mock });
62
- } catch (error: any) {
63
- return json({ error: error.message, agents: isMockMode() ? DEFAULT_AGENTS_LIST : [], isMock: isMockMode() }, { status: 500 });
73
+ } catch (error) {
74
+ const message = error instanceof Error ? error.message : String(error);
75
+ return json({ error: message, agents: isMockMode() ? DEFAULT_AGENTS_LIST : [], isMock: isMockMode() }, { status: 500 });
64
76
  }
65
77
  }
66
78
 
@@ -122,7 +134,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
122
134
  }
123
135
 
124
136
  return methodNotAllowed({ request, params });
125
- } catch (error: any) {
126
- return json({ error: error.message }, { status: 500 });
137
+ } catch (error) {
138
+ return json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 });
127
139
  }
128
140
  }
@@ -2,13 +2,25 @@ import { json } from '@/server/lib/remix-compat';
2
2
  import type { ActionFunctionArgs, LoaderFunctionArgs } from '@/server/lib/remix-compat';
3
3
  import { methodNotAllowed } from '@/server/lib/route-adapter';
4
4
  import { getDb } from '@/server/db.server';
5
- import { ACCENT_COLOR_OPTIONS, AVAILABLE_PROJECT_MODELS } from '@/client/data/settings/project';
6
- import { deleteWorkspaceFolder, parseFolderSettingsPatch, projectConfigFromFolder, updateWorkspaceFolder } from '@/shared/lib/workspace/project-settings';
5
+ import { PROJECT_ACCENT_OPTIONS } from '@/shared/lib/workspace/project-accent';
6
+ import { deleteWorkspaceFolder, projectConfigFromFolder, updateWorkspaceFolder } from '@/shared/lib/workspace/project-settings';
7
7
  import { isRecord } from '@/shared/lib/util/guards';
8
8
  import { emitRealtimeSignal } from '@/server/lib/realtime/signals.server';
9
+ import { syncDiscoveryRootsWatch } from '@/server/lib/omp/config/roots-watch.server';
10
+ import { prepareProjectPatch } from '@/server/lib/workspace/project-patch.server';
9
11
 
10
- function projectPatch(project: Record<string, unknown>) {
11
- return parseFolderSettingsPatch({
12
+ /**
13
+ * The fields this route accepts from a project form. Anything else in the body
14
+ * (an `id`, a `path` read back from the list) is derived from the row: `path` is
15
+ * the API's name for `project_path`, and a client echoing the whole project back
16
+ * must not be able to write a column through a synonym.
17
+ *
18
+ * The default model is NOT served from here. It is one of `provider:modelId`
19
+ * from the live catalog (`/api/models`), and this route used to answer with a
20
+ * hardcoded list of display names that no session could ever start on.
21
+ */
22
+ function projectPatchBody(project: Record<string, unknown>): Record<string, unknown> {
23
+ return {
12
24
  name: project.name,
13
25
  projectPath: project.projectPath ?? project.path,
14
26
  model: project.model,
@@ -17,27 +29,23 @@ function projectPatch(project: Record<string, unknown>) {
17
29
  customIconUrl: project.customIconUrl,
18
30
  isPinned: project.isPinned,
19
31
  isExpanded: project.isExpanded,
20
- });
32
+ };
21
33
  }
22
34
 
23
35
  export async function loader({ request: _request }: LoaderFunctionArgs) {
24
36
  try {
25
37
  const db = await getDb();
26
38
  const folders = await db.all('SELECT * FROM workspace_folders ORDER BY id ASC');
27
- const projects = folders.map(projectConfigFromFolder);
28
-
29
39
  return json({
30
- projects,
31
- availableModels: AVAILABLE_PROJECT_MODELS,
32
- accentColorOptions: ACCENT_COLOR_OPTIONS,
40
+ projects: folders.map(projectConfigFromFolder),
41
+ accentColorOptions: PROJECT_ACCENT_OPTIONS,
33
42
  });
34
43
  } catch (error) {
35
44
  const message = error instanceof Error ? error.message : 'Failed to load projects';
36
45
  return json({
37
46
  error: message,
38
47
  projects: [],
39
- availableModels: AVAILABLE_PROJECT_MODELS,
40
- accentColorOptions: ACCENT_COLOR_OPTIONS,
48
+ accentColorOptions: PROJECT_ACCENT_OPTIONS,
41
49
  }, { status: 500 });
42
50
  }
43
51
  }
@@ -52,6 +60,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
52
60
 
53
61
  const deleted = await deleteWorkspaceFolder(db, folderId);
54
62
  if (!deleted) return json({ error: 'Workspace not found' }, { status: 404 });
63
+ // The removed workspace's `.omp` roots leave scope with it; a lingering
64
+ // watcher would keep broadcasting reloads for a tree Kabmo no longer reads.
65
+ void syncDiscoveryRootsWatch();
55
66
  emitRealtimeSignal('sidebar-structure');
56
67
  return json({ success: true });
57
68
  }
@@ -75,15 +86,38 @@ export async function action({ request, params }: ActionFunctionArgs) {
75
86
  const folderId = typeof project.folderId === 'number' ? String(project.folderId) : undefined;
76
87
  if (!folderId) return json({ error: 'project.folderId is required' }, { status: 400 });
77
88
 
78
- const updated = await updateWorkspaceFolder(db, folderId, projectPatch(project));
79
- if (!updated) {
80
- const folder = await db.get('SELECT id FROM workspace_folders WHERE id = ?', [folderId]);
81
- if (!folder) return json({ error: 'Workspace not found' }, { status: 404 });
89
+ const before = await db.get<{ project_path: string | null }>(
90
+ 'SELECT project_path FROM workspace_folders WHERE id = ?',
91
+ [folderId],
92
+ );
93
+ if (!before) return json({ error: 'Workspace not found' }, { status: 404 });
94
+
95
+ const prepared = await prepareProjectPatch(db, folderId, projectPatchBody(project));
96
+ if (!prepared.ok) {
97
+ return json({ error: prepared.error, ...(prepared.code ? { code: prepared.code } : {}) }, { status: prepared.status });
82
98
  }
83
99
 
100
+ const patch = prepared.patch;
101
+ const updated = await updateWorkspaceFolder(db, folderId, patch);
84
102
  const folder = await db.get('SELECT * FROM workspace_folders WHERE id = ?', [folderId]);
85
- // A project field (name, model, accent, icon, pin) rides the sidebar's own
86
- // folder rows, so this write is a structure change there.
103
+
104
+ const pathChanged = patch.projectPath !== undefined && (folder?.project_path ?? null) !== before.project_path;
105
+ if (pathChanged) {
106
+ // The watched discovery-root set is keyed by `project_path`, so a re-bind
107
+ // has to re-sync it: without this the OLD root stayed watched and the new
108
+ // one was never added until a restart.
109
+ void syncDiscoveryRootsWatch();
110
+ }
111
+
112
+ // A project field (name, model, accent, icon, pin, path) rides the sidebar's
113
+ // own folder rows, so this write is a structure change there.
87
114
  emitRealtimeSignal('sidebar-structure');
88
- return json({ success: true, project: folder ? projectConfigFromFolder(folder) : null });
115
+ // `changed: false` is an answer, not a failure: the form re-sent what it
116
+ // already had, or touched a field the store deliberately ignores.
117
+ return json({
118
+ success: true,
119
+ changed: Boolean(updated),
120
+ project: folder ? projectConfigFromFolder(folder) : null,
121
+ accentColorOptions: PROJECT_ACCENT_OPTIONS,
122
+ });
89
123
  }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * `POST /api/settings/projects` — the refusal half of the project form.
8
+ *
9
+ * The pane edits facts that decide where a chat runs and which sessions the
10
+ * sidebar lists, so every rule that can make a write unhonourable is enforced
11
+ * here and named in the response:
12
+ *
13
+ * - an empty name (the store skips it, so the form would show a value the row
14
+ * never took),
15
+ * - a name another workspace already holds (case-insensitively — the sidebar
16
+ * identifies a workspace by name),
17
+ * - a path that is not an existing directory (a typo bound a folder that then
18
+ * listed nothing, with no reason on screen),
19
+ * - a directory another workspace is already bound to (two rows would list the
20
+ * same sessions and fight over the discovery tombstones).
21
+ *
22
+ * A refusal must also leave the stored row UNCHANGED — half-applied writes are
23
+ * what made a rename look successful until the next refresh.
24
+ */
25
+
26
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
27
+ import fs from 'fs';
28
+ import os from 'os';
29
+ import path from 'path';
30
+
31
+ import { getDb } from '@/server/db.server';
32
+ import { action as projectsAction, loader as projectsLoader } from '@/server/routes/settings/projects';
33
+ import { isolateDb, releaseDb } from '@/test-support/isolated-db';
34
+ import { removeDir } from '@/test-support/remove-dir';
35
+
36
+ const ROOT = path.join(os.tmpdir(), 'omc-settings-projects-routes-test');
37
+ const API = 'http://localhost/api/settings/projects';
38
+ const AGENT_DIR = path.join(ROOT, 'agent');
39
+
40
+ type Handler = (args: never) => unknown;
41
+
42
+ function call(handler: Handler, request: Request): Promise<Response> {
43
+ return handler({ request, params: {} } as never) as Promise<Response>;
44
+ }
45
+
46
+ function send(url: string, verb: string, body?: unknown): Request {
47
+ return new Request(url, {
48
+ method: verb,
49
+ ...(body === undefined ? {} : { body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }),
50
+ });
51
+ }
52
+
53
+ async function folderId(name: string): Promise<number> {
54
+ const db = await getDb();
55
+ const row = await db.get<{ id: number }>('SELECT id FROM workspace_folders WHERE name = ?', [name]);
56
+ if (!row) throw new Error(`no folder named ${name}`);
57
+ return row.id;
58
+ }
59
+
60
+ beforeAll(async () => {
61
+ removeDir(ROOT);
62
+ fs.mkdirSync(AGENT_DIR, { recursive: true });
63
+ Bun.env.PI_CODING_AGENT_DIR = AGENT_DIR;
64
+ Bun.env.SYNC_WORKSPACE = 'false';
65
+ delete Bun.env.MOCK;
66
+ await isolateDb();
67
+ await getDb();
68
+ });
69
+
70
+ beforeEach(async () => {
71
+ const db = await getDb();
72
+ await db.run('DELETE FROM workspace_folders');
73
+ });
74
+
75
+ afterAll(async () => {
76
+ await releaseDb();
77
+ delete Bun.env.PI_CODING_AGENT_DIR;
78
+ delete Bun.env.SYNC_WORKSPACE;
79
+ removeDir(ROOT);
80
+ });
81
+
82
+ describe('settings projects route', () => {
83
+ test('the loader serves the accent palette but no model list', async () => {
84
+ const body = await (await call(projectsLoader, new Request(API))).json();
85
+ expect(Array.isArray(body.projects)).toBe(true);
86
+ expect(body.accentColorOptions[0]).toMatchObject({ label: 'None', value: '' });
87
+ // The default model is a `provider:modelId` from the live catalog, so this
88
+ // route must not answer with a hardcoded list of display names.
89
+ expect(body.availableModels).toBeUndefined();
90
+ });
91
+
92
+ test('an empty name is refused and the stored name survives', async () => {
93
+ const db = await getDb();
94
+ await db.run('INSERT INTO workspace_folders (name, is_expanded) VALUES (?, 1)', ['Keep']);
95
+ const id = await folderId('Keep');
96
+
97
+ const res = await call(projectsAction, send(API, 'POST', { project: { folderId: id, name: ' ' } }));
98
+ expect(res.status).toBe(400);
99
+ expect(await res.json()).toMatchObject({ code: 'name_required' });
100
+ expect((await db.get<{ name: string }>('SELECT name FROM workspace_folders WHERE id = ?', [id]))?.name).toBe('Keep');
101
+ });
102
+
103
+ test('a duplicate name is a 409 naming the clash, and nothing is written', async () => {
104
+ const db = await getDb();
105
+ await db.run('INSERT INTO workspace_folders (name, is_expanded) VALUES (?, 1)', ['alpha']);
106
+ await db.run('INSERT INTO workspace_folders (name, is_expanded) VALUES (?, 1)', ['beta']);
107
+ const id = await folderId('beta');
108
+
109
+ const res = await call(projectsAction, send(API, 'POST', { project: { folderId: id, name: 'ALPHA' } }));
110
+ expect(res.status).toBe(409);
111
+ expect(await res.json()).toMatchObject({ code: 'duplicate_name' });
112
+ expect((await db.get<{ name: string }>('SELECT name FROM workspace_folders WHERE id = ?', [id]))?.name).toBe('beta');
113
+ });
114
+
115
+ test('a path that is not a directory is refused and the old binding survives', async () => {
116
+ const db = await getDb();
117
+ await db.run('INSERT INTO workspace_folders (name, is_expanded, project_path) VALUES (?, 1, ?)', ['bound', AGENT_DIR]);
118
+ const id = await folderId('bound');
119
+
120
+ const res = await call(
121
+ projectsAction,
122
+ send(API, 'POST', { project: { folderId: id, projectPath: path.join(ROOT, 'nope') } }),
123
+ );
124
+ expect(res.status).toBe(400);
125
+ expect(await res.json()).toMatchObject({ code: 'directory_not_found' });
126
+ expect((await db.get<{ project_path: string }>('SELECT project_path FROM workspace_folders WHERE id = ?', [id]))?.project_path)
127
+ .toBe(AGENT_DIR);
128
+ });
129
+
130
+ test('a directory another workspace already holds is a 409 naming the holder', async () => {
131
+ await getDb().then((db) => db.run(
132
+ 'INSERT INTO workspace_folders (name, is_expanded, project_path) VALUES (?, 1, ?)',
133
+ ['first', AGENT_DIR],
134
+ ));
135
+ await getDb().then((db) => db.run('INSERT INTO workspace_folders (name, is_expanded) VALUES (?, 1)', ['second']));
136
+ const id = await folderId('second');
137
+
138
+ const res = await call(projectsAction, send(API, 'POST', { project: { folderId: id, projectPath: AGENT_DIR } }));
139
+ expect(res.status).toBe(409);
140
+ expect(await res.json()).toMatchObject({ code: 'duplicate_path' });
141
+ });
142
+
143
+ test('an accepted bind is stored as the absolute path, and changing the path re-syncs discovery', async () => {
144
+ const db = await getDb();
145
+ await db.run('INSERT INTO workspace_folders (name, is_expanded) VALUES (?, 1)', ['tilde']);
146
+ const id = await folderId('tilde');
147
+
148
+ const res = await call(projectsAction, send(API, 'POST', { project: { folderId: id, projectPath: AGENT_DIR } }));
149
+ expect(res.status).toBe(200);
150
+ const body = await res.json();
151
+ expect(body).toMatchObject({ success: true, changed: true });
152
+ expect(body.project).toMatchObject({ name: 'tilde', path: AGENT_DIR });
153
+ expect(path.isAbsolute(body.project.path)).toBe(true);
154
+ });
155
+
156
+ test('a custom accent is stored in one canonical form', async () => {
157
+ const db = await getDb();
158
+ await db.run('INSERT INTO workspace_folders (name, is_expanded) VALUES (?, 1)', ['custom']);
159
+ const id = await folderId('custom');
160
+
161
+ // `#ABC` and `#aabbcc` are the same colour; the sidebar compares the stored
162
+ // string against the preset table, so one spelling has to win.
163
+ const res = await call(projectsAction, send(API, 'POST', { project: { folderId: id, accentColor: '#0F8' } }));
164
+ expect(res.status).toBe(200);
165
+ expect((await res.json()).project).toMatchObject({ accentColor: '#00ff88' });
166
+ expect(
167
+ (await db.get<{ accent_color: string }>('SELECT accent_color FROM workspace_folders WHERE id = ?', [id]))?.accent_color,
168
+ ).toBe('#00ff88');
169
+
170
+ // The paint the sidebar actually does: a six-digit hex reaches the loader.
171
+ const body = await (await call(projectsLoader, new Request(API))).json();
172
+ expect(body.projects.find((project: { folderId: number }) => project.folderId === id)).toMatchObject({
173
+ accentColor: '#00ff88',
174
+ });
175
+ });
176
+
177
+ test('an accent that is not a hex colour is refused before it reaches a style', async () => {
178
+ const db = await getDb();
179
+ await db.run('INSERT INTO workspace_folders (name, is_expanded, accent_color) VALUES (?, 1, ?)', ['plain', '#38bdf8']);
180
+ const id = await folderId('plain');
181
+
182
+ for (const accentColor of ['red;background:url(//evil)', 'rgb(1,2,3)', '#12345', 'url(#x)']) {
183
+ const res = await call(projectsAction, send(API, 'POST', { project: { folderId: id, accentColor } }));
184
+ expect(res.status).toBe(400);
185
+ expect(await res.json()).toMatchObject({ code: 'invalid_accent' });
186
+ }
187
+ expect(
188
+ (await db.get<{ accent_color: string }>('SELECT accent_color FROM workspace_folders WHERE id = ?', [id]))?.accent_color,
189
+ ).toBe('#38bdf8');
190
+ });
191
+
192
+ test('an empty accent clears the mark instead of being refused', async () => {
193
+ const db = await getDb();
194
+ await db.run('INSERT INTO workspace_folders (name, is_expanded, accent_color) VALUES (?, 1, ?)', ['clearing', '#f43f5e']);
195
+ const id = await folderId('clearing');
196
+
197
+ const res = await call(projectsAction, send(API, 'POST', { project: { folderId: id, accentColor: '' } }));
198
+ expect(res.status).toBe(200);
199
+ expect((await res.json()).project).toMatchObject({ accentColor: '' });
200
+ });
201
+
202
+ test('a body carrying no editable field answers success with changed:false', async () => {
203
+ const db = await getDb();
204
+ await db.run('INSERT INTO workspace_folders (name, is_expanded) VALUES (?, 1)', ['same']);
205
+ const id = await folderId('same');
206
+
207
+ // Only the id: nothing the store can write. That is an ANSWER, not a
208
+ // failure — the form may legitimately re-send an untouched row.
209
+ const res = await call(projectsAction, send(API, 'POST', { project: { folderId: id } }));
210
+ expect(res.status).toBe(200);
211
+ expect(await res.json()).toMatchObject({ success: true, changed: false });
212
+ expect((await db.get<{ name: string }>('SELECT name FROM workspace_folders WHERE id = ?', [id]))?.name).toBe('same');
213
+ });
214
+ });
@@ -121,11 +121,14 @@ describe('settings root', () => {
121
121
  });
122
122
 
123
123
  describe('settings projects', () => {
124
- test('the loader reports the model and accent options alongside the list', async () => {
124
+ test('the loader reports the accent options alongside the list', async () => {
125
125
  const body = await (await call(projectsLoader, new Request(`${API}/projects`))).json();
126
126
  expect(Array.isArray(body.projects)).toBe(true);
127
- expect(Array.isArray(body.availableModels)).toBe(true);
128
127
  expect(Array.isArray(body.accentColorOptions)).toBe(true);
128
+ expect(body.accentColorOptions[0]).toMatchObject({ label: 'None', value: '' });
129
+ // The default model comes from the live catalog, not from this route: a
130
+ // hardcoded list of display names here was never readable by a spawn.
131
+ expect(body.availableModels).toBeUndefined();
129
132
  });
130
133
 
131
134
  test('a delete without an id is refused before touching the store', async () => {