@myrialabs/clopen 0.4.47 → 0.4.48

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 (325) hide show
  1. package/README.md +11 -11
  2. package/backend/artifacts/project/sources.ts +1 -1
  3. package/backend/auth/auth-service.ts +52 -358
  4. package/backend/auth/onboarding.test.ts +2 -3
  5. package/backend/auth/permissions.test.ts +10 -20
  6. package/backend/auth/permissions.ts +4 -290
  7. package/backend/auth/rate-limiter.test.ts +8 -9
  8. package/backend/auth/rate-limiter.ts +0 -2
  9. package/backend/auth/tokens.ts +1 -8
  10. package/backend/bootstrap.ts +7 -0
  11. package/backend/chat/attachments.test.ts +88 -0
  12. package/backend/chat/attachments.ts +159 -0
  13. package/backend/chat/engine-handoff.test.ts +0 -2
  14. package/backend/chat/stream-manager.ts +62 -62
  15. package/backend/chat/turn-answer.test.ts +64 -0
  16. package/backend/chat/turn-answer.ts +125 -0
  17. package/backend/chat-apps/awaiting.test.ts +39 -0
  18. package/backend/chat-apps/awaiting.ts +49 -0
  19. package/backend/chat-apps/conversation.ts +746 -0
  20. package/backend/chat-apps/inbound.ts +324 -0
  21. package/backend/chat-apps/index.ts +309 -0
  22. package/backend/chat-apps/link-events.ts +20 -0
  23. package/backend/chat-apps/media.test.ts +62 -0
  24. package/backend/chat-apps/media.ts +208 -0
  25. package/backend/chat-apps/messages.test.ts +229 -0
  26. package/backend/chat-apps/messages.ts +365 -0
  27. package/backend/chat-apps/outbound.ts +243 -0
  28. package/backend/chat-apps/pairing.test.ts +45 -0
  29. package/backend/chat-apps/pairing.ts +74 -0
  30. package/backend/chat-apps/platforms/index.ts +20 -0
  31. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  32. package/backend/chat-apps/platforms/telegram.ts +191 -0
  33. package/backend/chat-apps/platforms/types.ts +114 -0
  34. package/backend/chat-apps/questions.ts +133 -0
  35. package/backend/chat-apps/runtime.ts +572 -0
  36. package/backend/chat-apps/storage.test.ts +201 -0
  37. package/backend/chat-apps/turns.test.ts +45 -0
  38. package/backend/chat-apps/turns.ts +208 -0
  39. package/backend/containers/pty.ts +3 -11
  40. package/backend/control/actions/accounts.ts +89 -0
  41. package/backend/control/actions/files.ts +116 -0
  42. package/backend/control/actions/models.ts +188 -0
  43. package/backend/control/actions/projects.ts +272 -0
  44. package/backend/control/actions/sessions.ts +280 -0
  45. package/backend/control/actions/skills.ts +111 -0
  46. package/backend/control/control.test.ts +169 -0
  47. package/backend/control/define.ts +20 -0
  48. package/backend/control/folders.test.ts +67 -0
  49. package/backend/control/index.ts +213 -0
  50. package/backend/control/invoke.ts +44 -0
  51. package/backend/control/links.ts +35 -0
  52. package/backend/control/paging.ts +26 -0
  53. package/backend/control/types.ts +117 -0
  54. package/backend/control/workspace.ts +127 -0
  55. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  56. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  57. package/backend/database/migrations/086_single_owner.test.ts +170 -0
  58. package/backend/database/migrations/086_single_owner.ts +418 -0
  59. package/backend/database/migrations/index.ts +21 -0
  60. package/backend/database/queries/auth-queries.ts +7 -85
  61. package/backend/database/queries/channel-queries.ts +270 -0
  62. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  63. package/backend/database/queries/file-share-queries.ts +5 -23
  64. package/backend/database/queries/git-identity-queries.ts +31 -42
  65. package/backend/database/queries/graph-queries.ts +1 -1
  66. package/backend/database/queries/index.ts +13 -1
  67. package/backend/database/queries/message-queries.test.ts +146 -0
  68. package/backend/database/queries/message-queries.ts +42 -1
  69. package/backend/database/queries/permission-set-queries.ts +1 -1
  70. package/backend/database/queries/profile-queries.ts +1 -1
  71. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  72. package/backend/database/queries/project-queries.ts +50 -63
  73. package/backend/database/queries/session-queries.ts +28 -56
  74. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  75. package/backend/db-client/integrations/projector.ts +0 -5
  76. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  77. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  78. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  79. package/backend/engine/adapters/cline/stream.ts +11 -15
  80. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  81. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  82. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  83. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  84. package/backend/engine/adapters/opencode/stream.ts +11 -0
  85. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  86. package/backend/engine/adapters/parent-scope.ts +44 -0
  87. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  88. package/backend/engine/adapters/pi/stream.ts +4 -5
  89. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  90. package/backend/engine/bootstrap-default-engine.ts +2 -2
  91. package/backend/engine/docs/adapter-contract.md +8 -1
  92. package/backend/engine/install-runner.ts +8 -17
  93. package/backend/files/file-shares.ts +20 -44
  94. package/backend/files/file-size-limit.ts +3 -3
  95. package/backend/files/image-processing.ts +1 -1
  96. package/backend/files/os-clipboard.ts +2 -2
  97. package/backend/git/git-executor.ts +25 -5
  98. package/backend/git/git-service.ts +420 -19
  99. package/backend/git/identity/credential-helper.test.ts +2 -7
  100. package/backend/git/identity/import-local.test.ts +11 -16
  101. package/backend/git/identity/import-local.ts +12 -12
  102. package/backend/git/identity/index.ts +10 -24
  103. package/backend/git/identity/resolve.ts +13 -14
  104. package/backend/git/identity/scope-config.ts +33 -28
  105. package/backend/git/identity/service.ts +44 -47
  106. package/backend/git/op-lock.test.ts +111 -0
  107. package/backend/git/op-lock.ts +180 -0
  108. package/backend/git/remote-sync.test.ts +249 -0
  109. package/backend/host/metrics.ts +1 -1
  110. package/backend/http/bearer-auth.ts +1 -2
  111. package/backend/http/files-download.test.ts +8 -9
  112. package/backend/http/files-download.ts +2 -2
  113. package/backend/http/files-shared.test.ts +62 -89
  114. package/backend/http/files-shared.ts +2 -2
  115. package/backend/http/files-upload.test.ts +3 -7
  116. package/backend/http/files-upload.ts +3 -3
  117. package/backend/http/notes-images.test.ts +15 -38
  118. package/backend/http/notes-images.ts +6 -8
  119. package/backend/http/ssh-sftp.ts +5 -10
  120. package/backend/index.ts +21 -7
  121. package/backend/integrations/accounts.ts +61 -3
  122. package/backend/integrations/index.ts +2 -2
  123. package/backend/integrations/registry/define.ts +15 -0
  124. package/backend/integrations/registry/index.ts +2 -0
  125. package/backend/integrations/registry/providers/telegram.ts +54 -0
  126. package/backend/integrations/registry/types.ts +21 -1
  127. package/backend/integrations/webhooks/gateway.ts +7 -6
  128. package/backend/integrations/webhooks/verify.test.ts +30 -0
  129. package/backend/integrations/webhooks/verify.ts +4 -0
  130. package/backend/mcp/external/project.ts +1 -1
  131. package/backend/mcp/internal/remote-server.test.ts +1 -3
  132. package/backend/mcp/internal/remote-server.ts +4 -4
  133. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  134. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  135. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  136. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  137. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  138. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  139. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  140. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  141. package/backend/memory/redact.ts +1 -1
  142. package/backend/notes/access.test.ts +28 -29
  143. package/backend/notes/access.ts +6 -11
  144. package/backend/permissions/service.ts +1 -1
  145. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  146. package/backend/preview/browser/browser-clipboard.ts +67 -0
  147. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  148. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  149. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  150. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  151. package/backend/preview/browser/browser-pool.ts +67 -6
  152. package/backend/preview/browser/browser-preview-service.ts +361 -25
  153. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  154. package/backend/preview/browser/browser-video-capture.ts +92 -5
  155. package/backend/preview/browser/element-locator.ts +190 -17
  156. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  157. package/backend/preview/browser/keyboard-chords.ts +132 -0
  158. package/backend/preview/browser/paste.ts +81 -0
  159. package/backend/preview/browser/process-usage.ts +142 -0
  160. package/backend/preview/browser/profile-lock.ts +209 -0
  161. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  162. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  163. package/backend/preview/browser/types.ts +40 -2
  164. package/backend/preview/browser/viewport.test.ts +45 -0
  165. package/backend/preview/browser/viewport.ts +96 -0
  166. package/backend/profiles/service.ts +2 -2
  167. package/backend/project/status-manager.ts +43 -172
  168. package/backend/projects/home.ts +61 -0
  169. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  170. package/backend/projects/project-cleanup.ts +0 -8
  171. package/backend/skills/service.ts +2 -3
  172. package/backend/snapshot/helpers.ts +0 -1
  173. package/backend/snapshot/restore.ts +252 -0
  174. package/backend/ssh/ptykit.ts +1 -2
  175. package/backend/terminal/ptykit.ts +5 -8
  176. package/backend/tunnel/public-origin.ts +31 -20
  177. package/backend/utils/user-helpers.ts +0 -55
  178. package/backend/utils/ws.ts +61 -154
  179. package/backend/worktrees/branching/engine.ts +3 -16
  180. package/backend/worktrees/branching/index.ts +1 -1
  181. package/backend/worktrees/branching/projector.ts +1 -1
  182. package/backend/worktrees/branching/service.ts +13 -25
  183. package/backend/ws/access.ts +12 -21
  184. package/backend/ws/artifacts/generate.ts +2 -2
  185. package/backend/ws/auth/device.ts +16 -71
  186. package/backend/ws/auth/index.ts +4 -22
  187. package/backend/ws/auth/login.test.ts +14 -60
  188. package/backend/ws/auth/login.ts +24 -124
  189. package/backend/ws/auth/status.ts +0 -1
  190. package/backend/ws/chat/composer.ts +118 -118
  191. package/backend/ws/chat/stream.ts +64 -47
  192. package/backend/ws/chat-apps/index.ts +117 -0
  193. package/backend/ws/containers/actions.ts +11 -25
  194. package/backend/ws/containers/index.ts +3 -4
  195. package/backend/ws/containers/list.ts +10 -36
  196. package/backend/ws/containers/logs.ts +2 -2
  197. package/backend/ws/containers/tunnel.ts +1 -2
  198. package/backend/ws/db-client/access.ts +2 -16
  199. package/backend/ws/db-client/accounts.ts +5 -15
  200. package/backend/ws/db-client/connections.ts +17 -25
  201. package/backend/ws/db-client/context.ts +1 -1
  202. package/backend/ws/db-client/env.ts +7 -10
  203. package/backend/ws/db-client/index.ts +2 -2
  204. package/backend/ws/db-client/io.ts +5 -5
  205. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  206. package/backend/ws/db-client/query.ts +18 -17
  207. package/backend/ws/db-client/schema.ts +13 -13
  208. package/backend/ws/db-client/structure.ts +35 -35
  209. package/backend/ws/db-client/supabase.ts +4 -21
  210. package/backend/ws/deployments/context.ts +1 -1
  211. package/backend/ws/deployments/crud.ts +0 -5
  212. package/backend/ws/engine/access.ts +7 -20
  213. package/backend/ws/engine/claude/accounts.ts +4 -4
  214. package/backend/ws/engine/cline/accounts.ts +5 -5
  215. package/backend/ws/engine/codex/accounts.ts +3 -3
  216. package/backend/ws/engine/pi/accounts.ts +5 -5
  217. package/backend/ws/files/clipboard.ts +8 -27
  218. package/backend/ws/files/image-edit.ts +6 -6
  219. package/backend/ws/files/index.ts +1 -1
  220. package/backend/ws/files/path-access.test.ts +32 -131
  221. package/backend/ws/files/path-access.ts +8 -87
  222. package/backend/ws/files/read.ts +15 -19
  223. package/backend/ws/files/reveal.ts +3 -3
  224. package/backend/ws/files/search.ts +7 -7
  225. package/backend/ws/files/share.ts +9 -13
  226. package/backend/ws/files/state.ts +9 -12
  227. package/backend/ws/files/watch.ts +3 -3
  228. package/backend/ws/files/write.ts +30 -31
  229. package/backend/ws/git/branch.ts +80 -59
  230. package/backend/ws/git/commit.ts +63 -44
  231. package/backend/ws/git/conflict.ts +16 -18
  232. package/backend/ws/git/identity-context.ts +8 -17
  233. package/backend/ws/git/identity.ts +17 -27
  234. package/backend/ws/git/index.ts +3 -1
  235. package/backend/ws/git/op-state.ts +139 -0
  236. package/backend/ws/git/remote.ts +241 -141
  237. package/backend/ws/git/repo-context.ts +67 -0
  238. package/backend/ws/git/staging.ts +18 -28
  239. package/backend/ws/git/status.ts +5 -2
  240. package/backend/ws/index.ts +5 -1
  241. package/backend/ws/instructions/crud.ts +1 -1
  242. package/backend/ws/integrations/crud.ts +1 -3
  243. package/backend/ws/mcp/crud.ts +3 -5
  244. package/backend/ws/mcp/tools.ts +1 -1
  245. package/backend/ws/memory/crud.ts +14 -46
  246. package/backend/ws/memory/index.ts +2 -2
  247. package/backend/ws/messages/crud.ts +29 -8
  248. package/backend/ws/notes/index.ts +33 -39
  249. package/backend/ws/permissions/crud.ts +3 -4
  250. package/backend/ws/ports/index.ts +1 -2
  251. package/backend/ws/ports/kill.ts +5 -10
  252. package/backend/ws/ports/list.ts +4 -10
  253. package/backend/ws/preview/access.ts +1 -1
  254. package/backend/ws/preview/browser/interact.ts +52 -79
  255. package/backend/ws/preview/browser/native-ui.ts +24 -0
  256. package/backend/ws/preview/browser/stats.ts +98 -1
  257. package/backend/ws/preview/browser/tab-info.ts +15 -0
  258. package/backend/ws/preview/browser/tab.ts +19 -4
  259. package/backend/ws/preview/index.ts +27 -0
  260. package/backend/ws/profiles/crud.ts +6 -8
  261. package/backend/ws/project-artifacts/index.ts +30 -31
  262. package/backend/ws/projects/crud.ts +33 -35
  263. package/backend/ws/projects/index.ts +3 -8
  264. package/backend/ws/projects/info.ts +3 -3
  265. package/backend/ws/projects/overview.ts +19 -30
  266. package/backend/ws/projects/status.ts +17 -57
  267. package/backend/ws/sessions/crud.ts +34 -45
  268. package/backend/ws/sessions/index.ts +1 -1
  269. package/backend/ws/settings/crud.ts +1 -1
  270. package/backend/ws/skills/crud.ts +3 -4
  271. package/backend/ws/skills/index.ts +1 -1
  272. package/backend/ws/snapshot/changes.ts +7 -7
  273. package/backend/ws/snapshot/restore.ts +11 -295
  274. package/backend/ws/snapshot/timeline.ts +2 -4
  275. package/backend/ws/ssh/access.ts +6 -21
  276. package/backend/ws/ssh/connections.ts +21 -31
  277. package/backend/ws/ssh/forwards.ts +12 -12
  278. package/backend/ws/ssh/sftp.ts +34 -34
  279. package/backend/ws/ssh/tunnel.ts +1 -2
  280. package/backend/ws/stack/install.ts +7 -17
  281. package/backend/ws/subagents/crud.ts +1 -1
  282. package/backend/ws/tunnel/share.ts +0 -2
  283. package/backend/ws/user/crud.ts +1 -59
  284. package/backend/ws/user/index.ts +1 -1
  285. package/backend/ws/work/context.ts +1 -1
  286. package/backend/ws/work/crud.ts +0 -5
  287. package/backend/ws/workspace/state.ts +10 -13
  288. package/backend/ws/worktrees/branching.ts +7 -36
  289. package/backend/ws/worktrees/crud.ts +2 -2
  290. package/bin/clopen.ts +10 -11
  291. package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
  292. package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
  293. package/dist/assets/main-BUiUL3eZ.css +1 -0
  294. package/dist/assets/main-nBOb9YOA.js +1240 -0
  295. package/dist/index.html +2 -2
  296. package/package.json +2 -1
  297. package/shared/constants/attachments.ts +14 -0
  298. package/shared/constants/engine-tools.ts +1 -1
  299. package/shared/constants/preview.test.ts +259 -0
  300. package/shared/constants/preview.ts +1018 -57
  301. package/shared/constants/tool-icons.ts +5 -0
  302. package/shared/types/containers/container.ts +1 -1
  303. package/shared/types/database/schema.ts +9 -6
  304. package/shared/types/git-identity.ts +1 -1
  305. package/shared/types/git.ts +116 -0
  306. package/shared/types/integrations.ts +7 -0
  307. package/shared/types/stores/settings.ts +1 -1
  308. package/shared/types/unified/index.ts +1 -1
  309. package/shared/types/unified/message.ts +0 -7
  310. package/shared/types/unified/stream.ts +2 -4
  311. package/shared/types/unified/tool.ts +15 -1
  312. package/shared/utils/ask-user-question.test.ts +319 -0
  313. package/shared/utils/ask-user-question.ts +154 -0
  314. package/shared/utils/home-project.ts +25 -0
  315. package/shared/utils/logger.ts +2 -0
  316. package/shared/utils/ws-server.ts +32 -7
  317. package/backend/auth/session-invalidation.test.ts +0 -112
  318. package/backend/auth/session-invalidation.ts +0 -77
  319. package/backend/project/status-manager.test.ts +0 -32
  320. package/backend/ws/auth/invites.ts +0 -94
  321. package/backend/ws/auth/users.ts +0 -112
  322. package/backend/ws/projects/presence.ts +0 -46
  323. package/backend/ws/stack/access.ts +0 -31
  324. package/dist/assets/main-BiDNMWb3.css +0 -1
  325. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Sessions: where am I, what is running, list, search, open, start, stop,
3
+ * the queue, and delete.
4
+ */
5
+
6
+ import { t } from 'elysia';
7
+ import { profileQueries, projectQueries, sessionQueries } from '$backend/database/queries';
8
+ import type { UnifiedMessage } from '$shared/types/unified';
9
+ import { isWaitingForInteractiveInput } from '$shared/utils/interactive-input';
10
+ import { streamManager } from '$backend/chat/stream-manager';
11
+ import { excerptMarkdown, lastTurnAnswer } from '$backend/chat/turn-answer';
12
+ import { defineAction } from '../define';
13
+ import { paged } from '../paging';
14
+ import { accessibleSession, isSessionBusy, modelOf, projectLabel, resolveTarget } from '../workspace';
15
+ import { sessionLink } from '../links';
16
+ import { escapeMd } from './projects';
17
+ import { engineName } from './models';
18
+
19
+ /** How much of a session's last answer opening it shows. */
20
+ const OPEN_EXCERPT = 900;
21
+
22
+ export function sessionTitle(session: { title?: string | null; head_title?: string | null }): string {
23
+ return session.title || session.head_title || 'Untitled session';
24
+ }
25
+
26
+ interface QueueItem {
27
+ id: string;
28
+ userId: string;
29
+ userName: string;
30
+ text: string;
31
+ attachmentCount: number;
32
+ }
33
+
34
+ export const sessionStatus = defineAction({
35
+ id: 'sessions.status',
36
+ group: 'sessions',
37
+ title: 'Status',
38
+ description: 'Where you are and what it is doing',
39
+ args: t.Object({}),
40
+ command: { name: 'status' },
41
+ async run(ctx) {
42
+ const { project, session } = resolveTarget(ctx.target);
43
+ const model = modelOf(session);
44
+ const lines = [`📁 **${escapeMd(projectLabel(project))}**`];
45
+ lines.push(session ? `💬 ${escapeMd(sessionTitle(session))}` : '_No session yet. Your next message starts one here._');
46
+ if (model) {
47
+ const extras = [
48
+ session?.reasoning_effort ? `reasoning ${session.reasoning_effort}` : null,
49
+ session?.account_name ? `as ${escapeMd(session.account_name)}` : null
50
+ ].filter(Boolean);
51
+ lines.push(`🤖 \`${model.modelName}\` · ${engineName(model.engine)}${extras.length ? ` · ${extras.join(' · ')}` : ''}`);
52
+ }
53
+ const profile = session?.profile_id ? profileQueries.getById(session.profile_id) : null;
54
+ if (profile) lines.push(`🧰 Profile **${escapeMd(profile.name)}**`);
55
+ lines.push(session && isSessionBusy(session) ? '⏳ Running now. /stop stops it.' : '💤 Idle.');
56
+
57
+ if (session) {
58
+ const { queue } = await ctx.call<{ queue: QueueItem[] }>('chat:composer-state', { chatSessionId: session.id }, { projectId: project.id });
59
+ if (queue.length) lines.push(`🕒 ${queue.length} message${queue.length === 1 ? '' : 's'} queued. See /queue.`);
60
+ const limit = model && session.account_id ? streamManager.getRateLimitForAccount(model.engine, session.account_id) : null;
61
+ if (limit) {
62
+ const resets = limit.resetsAt ? `, resets ${new Date(limit.resetsAt * 1000).toLocaleString()}` : '';
63
+ lines.push(limit.status === 'rejected' ? `⛔ Rate limited${resets}.` : `⚠️ ${Math.round(limit.utilization * 100)}% of the rate limit used${resets}.`);
64
+ }
65
+ }
66
+ const link = session ? sessionLink(project.id, session.id) : null;
67
+ return { text: lines.join('\n'), ...(link ? { link: { label: 'Open in Clopen', url: link } } : {}) };
68
+ }
69
+ });
70
+
71
+ export const newSession = defineAction({
72
+ id: 'sessions.new',
73
+ group: 'sessions',
74
+ title: 'New session',
75
+ description: 'Start a new session',
76
+ args: t.Object({}),
77
+ command: { name: 'new' },
78
+ async run(ctx) {
79
+ const { project } = resolveTarget(ctx.target);
80
+ return { text: `✨ New session in **${escapeMd(projectLabel(project))}**. Type your message.`, target: { projectId: project.id, sessionId: null } };
81
+ }
82
+ });
83
+
84
+ export const listSessions = defineAction({
85
+ id: 'sessions.list',
86
+ group: 'sessions',
87
+ title: 'Sessions',
88
+ description: 'Switch session in this project',
89
+ args: t.Object({ page: t.Optional(t.Number({ minimum: 0 })) }),
90
+ command: { name: 'sessions' },
91
+ async run(ctx, args) {
92
+ const { project, session: current } = resolveTarget(ctx.target);
93
+ const sessions = sessionQueries
94
+ .getByProjectId(project.id)
95
+ .sort((a, b) => (b.last_message_at ?? b.started_at).localeCompare(a.last_message_at ?? a.started_at));
96
+ if (sessions.length === 0) return { text: `No sessions in **${escapeMd(projectLabel(project))}** yet. Just type to start one.` };
97
+ const { choices, range } = paged(
98
+ sessions,
99
+ args.page,
100
+ (session) => ({
101
+ label: `${isSessionBusy(session) ? '⏳ ' : ''}${sessionTitle(session)}`,
102
+ detail: session.last_message_at ? new Date(session.last_message_at).toLocaleString() : undefined,
103
+ current: session.id === current?.id,
104
+ action: 'sessions.open',
105
+ args: { sessionId: session.id }
106
+ }),
107
+ { action: 'sessions.list' }
108
+ );
109
+ return { text: `**💬 Sessions in ${escapeMd(projectLabel(project))}**${range}`, choices };
110
+ }
111
+ });
112
+
113
+ export const runningSessions = defineAction({
114
+ id: 'sessions.running',
115
+ group: 'sessions',
116
+ title: 'Running',
117
+ description: 'Sessions running or waiting for you, in all projects',
118
+ args: t.Object({}),
119
+ command: { name: 'running' },
120
+ async run(ctx) {
121
+ const rows = streamManager
122
+ .getActiveStreams()
123
+ .filter((stream) => stream.projectId && projectQueries.isListed(stream.projectId))
124
+ .map((stream) => {
125
+ const messages = stream.messages.map((event) => (event as { message?: UnifiedMessage }).message).filter((message): message is UnifiedMessage => Boolean(message));
126
+ return { stream, session: sessionQueries.getById(stream.chatSessionId), waiting: isWaitingForInteractiveInput(messages) };
127
+ })
128
+ .filter((row) => row.session)
129
+ // What needs you first, then the longest-running.
130
+ .sort((a, b) => Number(b.waiting) - Number(a.waiting) || a.stream.startedAt.getTime() - b.stream.startedAt.getTime());
131
+ if (rows.length === 0) return { text: '💤 Nothing is running in any of your projects.' };
132
+ return {
133
+ text: `**⏳ Running now** (${rows.length})`,
134
+ choices: rows.map(({ stream, session, waiting }) => {
135
+ const project = projectQueries.getById(session!.project_id);
136
+ return {
137
+ label: `${waiting ? '❓' : '⏳'} ${sessionTitle(session!)}`,
138
+ detail: `${project ? projectLabel(project) : 'Unknown project'} · ${waiting ? 'waiting for your answer' : `running ${elapsed(stream.startedAt)}`}`,
139
+ current: session!.id === ctx.target.sessionId,
140
+ action: 'sessions.open',
141
+ args: { sessionId: session!.id }
142
+ };
143
+ })
144
+ };
145
+ }
146
+ });
147
+
148
+ /** "3m", "1h 20m": how long something has been going. */
149
+ function elapsed(since: Date): string {
150
+ const minutes = Math.max(0, Math.round((Date.now() - since.getTime()) / 60_000));
151
+ if (minutes < 1) return 'under a minute';
152
+ if (minutes < 60) return `${minutes}m`;
153
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
154
+ }
155
+
156
+ export const searchSessions = defineAction({
157
+ id: 'sessions.search',
158
+ group: 'sessions',
159
+ title: 'Search sessions',
160
+ description: 'Find a session by what was said',
161
+ args: t.Object({ query: t.String({ minLength: 1 }), page: t.Optional(t.Number({ minimum: 0 })) }),
162
+ command: { name: 'search', argument: { keys: ['query'], hint: '<words>' } },
163
+ async run(ctx, args) {
164
+ const { sessions } = await ctx.call<{ sessions: Array<{ id: string; title?: string | null; project_id: string; matchSnippet?: string | null }> }>(
165
+ 'sessions:search-global',
166
+ { query: args.query.trim() }
167
+ );
168
+ if (sessions.length === 0) return { text: `Nothing matches “${escapeMd(args.query.trim())}”.` };
169
+ const { choices, range } = paged(
170
+ sessions,
171
+ args.page,
172
+ (session) => ({
173
+ label: sessionTitle(session),
174
+ detail: session.matchSnippet?.replace(/\s+/g, ' ').trim() || undefined,
175
+ current: session.id === ctx.target.sessionId,
176
+ action: 'sessions.open',
177
+ args: { sessionId: session.id }
178
+ }),
179
+ { action: 'sessions.search', args: { query: args.query } }
180
+ );
181
+ return { text: `**🔎 Sessions matching “${escapeMd(args.query.trim())}”**${range}`, choices };
182
+ }
183
+ });
184
+
185
+ export const openSession = defineAction({
186
+ id: 'sessions.open',
187
+ group: 'sessions',
188
+ title: 'Open session',
189
+ description: 'Switch to a session; plain messages continue it.',
190
+ args: t.Object({ sessionId: t.String({ minLength: 1 }) }),
191
+ async run(_ctx, args) {
192
+ const found = accessibleSession(args.sessionId);
193
+ if (!found) throw new Error('That session no longer exists.');
194
+ const last = lastTurnAnswer(found.session.id).text;
195
+ const busy = isSessionBusy(found.session) ? '\n\n⏳ It is running right now.' : '';
196
+ const recap = last ? `\n\n**Last reply:**\n\n${excerptMarkdown(last, OPEN_EXCERPT)}` : '';
197
+ return {
198
+ text: `💬 Now in **${escapeMd(sessionTitle(found.session))}** (${escapeMd(projectLabel(found.project))}). Type to continue it.${busy}${recap}`,
199
+ target: { projectId: found.project.id, sessionId: found.session.id }
200
+ };
201
+ }
202
+ });
203
+
204
+ export const stopSession = defineAction({
205
+ id: 'sessions.stop',
206
+ group: 'sessions',
207
+ title: 'Stop',
208
+ description: 'Stop the running turn',
209
+ args: t.Object({}),
210
+ command: { name: 'stop' },
211
+ async run(ctx) {
212
+ const found = accessibleSession(ctx.target.sessionId);
213
+ const stream = found ? streamManager.getSessionStream(found.session.id, found.project.id) : undefined;
214
+ if (!stream || stream.status !== 'active') return { text: 'Nothing is running.' };
215
+ await streamManager.cancelStream(stream.streamId, 'user');
216
+ return { text: '⏹ Stopped.' };
217
+ }
218
+ });
219
+
220
+ export const showQueue = defineAction({
221
+ id: 'sessions.queue',
222
+ group: 'sessions',
223
+ title: 'Queue',
224
+ description: 'Messages waiting to run',
225
+ args: t.Object({}),
226
+ command: { name: 'queue' },
227
+ async run(ctx) {
228
+ const found = accessibleSession(ctx.target.sessionId);
229
+ if (!found) return { text: 'Nothing is queued. There is no session yet.' };
230
+ const { queue } = await ctx.call<{ queue: QueueItem[] }>('chat:composer-state', { chatSessionId: found.session.id }, { projectId: found.project.id });
231
+ if (queue.length === 0) return { text: 'Nothing is queued.' };
232
+ const clip = (text: string) => (text.length > 60 ? `${text.slice(0, 59)}…` : text) || '(attachment only)';
233
+ return {
234
+ text: `**🕒 Queued in ${escapeMd(sessionTitle(found.session))}**\n_They run in this order. Tap one of yours to drop it._`,
235
+ choices: queue.map((item, index) => ({
236
+ label: `${index + 1}. ${item.userId === ctx.user.id ? '✕ ' : ''}${clip(item.text.replace(/\s+/g, ' ').trim())}`,
237
+ detail: `${item.userName}${item.attachmentCount ? ` · ${item.attachmentCount} file${item.attachmentCount === 1 ? '' : 's'}` : ''}`,
238
+ action: 'sessions.unqueue',
239
+ args: { sessionId: found.session.id, id: item.id }
240
+ }))
241
+ };
242
+ }
243
+ });
244
+
245
+ export const dropQueued = defineAction({
246
+ id: 'sessions.unqueue',
247
+ group: 'sessions',
248
+ title: 'Drop queued message',
249
+ description: 'Remove one of your queued messages before it runs.',
250
+ args: t.Object({ sessionId: t.String({ minLength: 1 }), id: t.String({ minLength: 1 }) }),
251
+ async run(ctx, args) {
252
+ const found = accessibleSession(args.sessionId);
253
+ if (!found) throw new Error('That session no longer exists.');
254
+ const { queue } = await ctx.call<{ queue: QueueItem[] }>('chat:composer-state', { chatSessionId: found.session.id }, { projectId: found.project.id });
255
+ const item = queue.find((entry) => entry.id === args.id);
256
+ if (!item) return { text: 'That message already ran or was dropped.' };
257
+ if (item.userId !== ctx.user.id) throw new Error(`Only ${item.userName} can drop that message.`);
258
+ await ctx.call('chat:queue-remove', { chatSessionId: found.session.id, id: args.id }, { projectId: found.project.id });
259
+ return { text: '🗑️ Dropped from the queue.' };
260
+ }
261
+ });
262
+
263
+ export const deleteSession = defineAction({
264
+ id: 'sessions.delete',
265
+ group: 'sessions',
266
+ title: 'Delete session',
267
+ description: 'Delete this session (files stay)',
268
+ args: t.Object({}),
269
+ command: { name: 'delete' },
270
+ confirm(_args, ctx) {
271
+ const found = accessibleSession(ctx.target.sessionId);
272
+ return found ? `Delete “${sessionTitle(found.session)}” and all of its messages? This cannot be undone.` : null;
273
+ },
274
+ async run(ctx) {
275
+ const found = accessibleSession(ctx.target.sessionId);
276
+ if (!found) throw new Error('No session to delete.');
277
+ await ctx.call('sessions:delete', { id: found.session.id }, { projectId: found.project.id });
278
+ return { text: '🗑️ Session deleted.', target: { projectId: found.project.id, sessionId: null } };
279
+ }
280
+ });
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Skills: running one of the user's slash skills (Settings → Skills).
3
+ *
4
+ * A skill runs exactly as typing `/<slug> args` in the web composer does:
5
+ * the action hands the surface that text as a prompt, and the stream expands
6
+ * it (`backend/skills/invoke.ts`) the same way for every engine. Which skills
7
+ * are offered follows the session's profile, like the web "/" picker.
8
+ */
9
+
10
+ import { t } from 'elysia';
11
+ import { defineAction } from '../define';
12
+ import { paged } from '../paging';
13
+ import { resolveTarget } from '../workspace';
14
+ import type { ControlContext } from '../types';
15
+
16
+ interface AvailableSkill {
17
+ slug: string;
18
+ name: string;
19
+ description: string;
20
+ argumentHint: string | null;
21
+ }
22
+
23
+ async function availableSkills(ctx: ControlContext): Promise<AvailableSkill[]> {
24
+ const { project, session } = resolveTarget(ctx.target);
25
+ const { skills } = await ctx.call<{ skills: AvailableSkill[] }>(
26
+ 'skills:available',
27
+ { profileId: session?.profile_id ?? null, projectId: project.id },
28
+ { projectId: project.id }
29
+ );
30
+ return skills;
31
+ }
32
+
33
+ /** What a person types for a skill: `/Review_PR`, `review-pr`, `review pr` all name `review-pr`. */
34
+ export function normaliseSkillName(input: string): string {
35
+ return input.trim().replace(/^\/+/, '').toLowerCase().replace(/[\s_]+/g, '-');
36
+ }
37
+
38
+ /**
39
+ * The skill a name refers to: an exact match, else the only skill that
40
+ * starts with it. Otherwise the skills it might have meant, for buttons.
41
+ */
42
+ export function matchSkill(skills: AvailableSkill[], input: string): { skill: AvailableSkill | null; similar: AvailableSkill[] } {
43
+ const wanted = normaliseSkillName(input);
44
+ const exact = skills.find((skill) => skill.slug === wanted);
45
+ if (exact) return { skill: exact, similar: [] };
46
+ const starts = skills.filter((skill) => skill.slug.startsWith(wanted));
47
+ if (starts.length === 1) return { skill: starts[0], similar: [] };
48
+ const similar = starts.length ? starts : skills.filter((skill) => skill.slug.includes(wanted) || wanted.includes(skill.slug));
49
+ return { skill: null, similar: similar.slice(0, 8) };
50
+ }
51
+
52
+ export const listSkills = defineAction({
53
+ id: 'skills.list',
54
+ group: 'skills',
55
+ title: 'Skills',
56
+ description: 'Your skills',
57
+ args: t.Object({ page: t.Optional(t.Number({ minimum: 0 })) }),
58
+ command: { name: 'skills' },
59
+ async run(ctx, args) {
60
+ const skills = await availableSkills(ctx);
61
+ if (skills.length === 0) return { text: 'No skills yet. Add them in Clopen → Settings → Skills.' };
62
+ const { choices, range } = paged(
63
+ skills,
64
+ args.page,
65
+ (skill) => ({
66
+ label: skill.slug,
67
+ detail: skill.argumentHint ? `${skill.description} (needs: ${skill.argumentHint})` : skill.description,
68
+ action: 'skills.run',
69
+ args: { slug: skill.slug }
70
+ }),
71
+ { action: 'skills.list' }
72
+ );
73
+ return { text: `**🧩 Skills**${range}\n_Tap one to run it here. To give it input: /run name input._`, choices };
74
+ }
75
+ });
76
+
77
+ /**
78
+ * Skills run through `/run`, never as `/<name>`: a bot command name shares
79
+ * one namespace with Clopen's own commands (a skill called `new` or `status`
80
+ * would never run), cannot hold the dashes skill names use, and a new skill
81
+ * must not be able to shadow a command. (A message that starts with a skill's
82
+ * own `/slug`, dashes and all, is not a bot command to Telegram: it is sent
83
+ * to the session as text and expanded by Clopen, exactly as in the web.)
84
+ */
85
+ export const runSkill = defineAction({
86
+ id: 'skills.run',
87
+ group: 'skills',
88
+ title: 'Run a skill',
89
+ description: 'Run a skill',
90
+ args: t.Object({ slug: t.Optional(t.String()), input: t.Optional(t.String()) }),
91
+ command: { name: 'run', argument: { keys: ['slug', 'input'], hint: '<skill> [input]' } },
92
+ async run(ctx, args) {
93
+ const skills = await availableSkills(ctx);
94
+ if (!args.slug?.trim()) {
95
+ return { text: 'Which skill? Pick one, or type /run name input.', choices: skills.slice(0, 20).map((skill) => ({ label: skill.slug, action: 'skills.run', args: { slug: skill.slug } })) };
96
+ }
97
+ const { skill, similar } = matchSkill(skills, args.slug);
98
+ if (!skill) {
99
+ if (similar.length === 0) return { text: `There is no skill called “${args.slug.trim()}”. /skills lists yours.` };
100
+ return {
101
+ text: `There is no skill called “${args.slug.trim()}”. Did you mean one of these?`,
102
+ choices: similar.map((entry) => ({ label: entry.slug, detail: entry.description, action: 'skills.run', args: { slug: entry.slug, ...(args.input ? { input: args.input } : {}) } }))
103
+ };
104
+ }
105
+ const input = args.input?.trim();
106
+ if (!input && skill.argumentHint) {
107
+ return { text: `${skill.slug} needs ${skill.argumentHint}. Send it like this:\n\n\`/run ${skill.slug} ${skill.argumentHint}\`` };
108
+ }
109
+ return { text: `▶️ Running ${skill.slug}…`, prompt: input ? `/${skill.slug} ${input}` : `/${skill.slug}` };
110
+ }
111
+ });
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The control catalog's own rules — the things every surface generated from
3
+ * it relies on: unique ids and commands, argument parsing and validation,
4
+ * help and the command menu agreeing, and in-process route calls that go
5
+ * through the same auth gate a browser does.
6
+ */
7
+
8
+ import { describe, it, expect } from 'bun:test';
9
+ import { t } from 'elysia';
10
+ import { createRouter } from '$shared/utils/ws-server';
11
+ import { ws } from '$backend/utils/ws';
12
+ import {
13
+ CONTROL_ACTIONS,
14
+ checkArgs,
15
+ commandReference,
16
+ controlActionForCommand,
17
+ controlHelp,
18
+ describeControlActions,
19
+ getControlAction,
20
+ matchSkill,
21
+ parseCommandArgument
22
+ } from './index';
23
+ import { defineAction } from './define';
24
+ import { botCommands } from '$backend/chat-apps';
25
+ import { CHAT_COMMANDS } from '$backend/chat-apps/messages';
26
+
27
+ describe('the catalog', () => {
28
+ it('has unique ids and commands, all well-formed', () => {
29
+ const ids = CONTROL_ACTIONS.map((action) => action.id);
30
+ expect(new Set(ids).size).toBe(ids.length);
31
+ for (const action of CONTROL_ACTIONS) {
32
+ expect(action.id).toMatch(/^[a-z]+\.[a-z][a-z-]*$/);
33
+ if (action.command) expect(controlActionForCommand(action.command.name)).toBe(action);
34
+ }
35
+ });
36
+
37
+ it('every choice an action can offer names an action that exists', () => {
38
+ const referenced = [
39
+ 'projects.open', 'projects.list', 'sessions.open', 'sessions.list', 'sessions.search', 'sessions.unqueue', 'files.get',
40
+ 'models.list', 'models.set', 'models.set-reasoning', 'accounts.list', 'accounts.switch', 'skills.run', 'projects.browse', 'projects.create'
41
+ ];
42
+ expect(referenced.every((id) => getControlAction(id))).toBe(true);
43
+ for (const id of referenced) expect(getControlAction(id)).not.toBeNull();
44
+ });
45
+
46
+ it('lists every command-bearing action in help and the description', () => {
47
+ const help = controlHelp();
48
+ for (const action of CONTROL_ACTIONS.filter((entry) => entry.command)) {
49
+ expect(help).toContain(`/${action.command!.name}`);
50
+ }
51
+ expect(describeControlActions().length).toBe(CONTROL_ACTIONS.length);
52
+ });
53
+
54
+ it('offers nothing a person would not do in the web UI: no raw routes, no secrets typed into a chat', () => {
55
+ const names = CONTROL_ACTIONS.flatMap((action) => (action.command ? [action.command.name] : []));
56
+ for (const gone of ['api', 'routes', 'addaccount', 'models', 'deletesession', 'update', 'system', 'mcp', 'rename', 'profile', 'notify', 'whoami']) {
57
+ expect(names).not.toContain(gone);
58
+ }
59
+ expect(names).toContain('delete');
60
+ });
61
+
62
+ it('keeps one command namespace: no catalog command shadows the chat’s own, Telegram’s, or a button prefix', () => {
63
+ const own = [...CHAT_COMMANDS.map((entry) => entry.command), 'start'];
64
+ const catalog = CONTROL_ACTIONS.flatMap((action) => (action.command ? [action.command.name] : []));
65
+ for (const name of catalog) expect(own).not.toContain(name);
66
+ expect(new Set([...own, ...catalog]).size).toBe(own.length + catalog.length);
67
+ expect(catalog).not.toContain('settings');
68
+ expect(() => defineAction({ id: 'chat.thing', group: 'sessions', title: 't', description: 'd', args: t.Object({}), async run() { return { text: '' }; } })).toThrow(/chat\./);
69
+ });
70
+
71
+ it('runs skills through /run, never as /<skill-name>', () => {
72
+ expect(controlActionForCommand('run')?.id).toBe('skills.run');
73
+ expect(controlActionForCommand('skills')?.id).toBe('skills.list');
74
+ const skills = [
75
+ { slug: 'new', name: 'New', description: 'd', argumentHint: null },
76
+ { slug: 'review-pr', name: 'Review', description: 'd', argumentHint: '<number>' },
77
+ { slug: 'review-docs', name: 'Docs', description: 'd', argumentHint: null }
78
+ ];
79
+ // A skill named like a command is reached by /run, not shadowed by /new.
80
+ expect(matchSkill(skills, 'new').skill?.slug).toBe('new');
81
+ // However it is typed: dashes, underscores, spaces, a leading slash, any case.
82
+ for (const typed of ['review-pr', 'Review_PR', '/review-pr', 'review pr']) expect(matchSkill(skills, typed).skill?.slug).toBe('review-pr');
83
+ // An unambiguous start is enough; an ambiguous one offers the candidates.
84
+ expect(matchSkill(skills, 'review-p').skill?.slug).toBe('review-pr');
85
+ const ambiguous = matchSkill(skills, 'review');
86
+ expect(ambiguous.skill).toBeNull();
87
+ expect(ambiguous.similar.map((skill) => skill.slug)).toEqual(['review-pr', 'review-docs']);
88
+ expect(matchSkill(skills, 'zzz')).toEqual({ skill: null, similar: [] });
89
+ });
90
+
91
+ it('publishes a command menu every chat app accepts', () => {
92
+ const commands = botCommands();
93
+ expect(commands.length).toBeLessThanOrEqual(100);
94
+ for (const command of commands) {
95
+ expect(command.command).toMatch(/^[a-z0-9_]{1,32}$/);
96
+ expect(command.description.length).toBeGreaterThan(0);
97
+ expect(command.description.length).toBeLessThanOrEqual(256);
98
+ }
99
+ expect(new Set(commands.map((command) => command.command)).size).toBe(commands.length);
100
+ });
101
+
102
+ it('the menu, /help and the Settings reference list the same commands in the same order', () => {
103
+ const reference = commandReference(CHAT_COMMANDS).map((entry) => entry.command);
104
+ expect(botCommands().map((command) => command.command)).toEqual(reference);
105
+ const help = controlHelp(CHAT_COMMANDS);
106
+ const inHelp = [...help.matchAll(/^\/([a-z0-9_]+)/gm)].map((match) => match[1]);
107
+ expect(inHelp).toEqual(reference);
108
+ });
109
+ });
110
+
111
+ describe('arguments', () => {
112
+ it('one key takes the whole text', () => {
113
+ expect(parseCommandArgument(getControlAction('sessions.search')!, ' login bug ')).toEqual({ query: 'login bug' });
114
+ });
115
+
116
+ it('several keys take a word each, the last taking the rest', () => {
117
+ expect(parseCommandArgument(getControlAction('models.engines')!, 'claude')).toEqual({ engine: 'claude' });
118
+ expect(parseCommandArgument(getControlAction('models.engines')!, 'opencode free gpt')).toEqual({ engine: 'opencode', query: 'free gpt' });
119
+ });
120
+
121
+ it('are validated, with the usage in the error', () => {
122
+ expect(() => checkArgs(getControlAction('sessions.search')!, {})).toThrow(/Usage: \/search/);
123
+ expect(checkArgs(getControlAction('accounts.switch')!, { engine: 'codex', accountId: '3' })).toEqual({ engine: 'codex', accountId: 3 });
124
+ });
125
+
126
+ it('destructive actions ask first', () => {
127
+ for (const id of ['sessions.delete']) expect(getControlAction(id)?.confirm).toBeDefined();
128
+ });
129
+ });
130
+
131
+ describe('in-process route calls', () => {
132
+ const router = createRouter()
133
+ .http('test:echo', { data: t.Object({ value: t.Number() }), response: t.Object({ value: t.Number(), userId: t.String() }) }, async ({ data, conn }) => ({
134
+ value: data.value,
135
+ userId: ws.getUserId(conn)
136
+ }))
137
+ .http('test:gated', { data: t.Object({}), response: t.Object({ ok: t.Boolean() }) }, async () => ({ ok: true }));
138
+ router.setAuthMiddleware(async (_conn, action) =>
139
+ action === 'test:gated' ? { allowed: false, error: 'Authentication required' } : { allowed: true }
140
+ );
141
+
142
+ async function call(action: string, data: unknown) {
143
+ const conn = ws.openVirtualConnection({ userId: 'u-1', projectId: 'p-1' });
144
+ try {
145
+ return await router.invoke(conn, action, data);
146
+ } finally {
147
+ ws.closeVirtualConnection(conn);
148
+ }
149
+ }
150
+
151
+ it('runs the handler as the virtual user and returns its result', async () => {
152
+ expect(await call('test:echo', { value: 7 })).toEqual({ value: 7, userId: 'u-1' });
153
+ });
154
+
155
+ it('goes through the auth gate and the request schema', async () => {
156
+ await expect(call('test:gated', {})).rejects.toThrow('Authentication required');
157
+ await expect(call('test:echo', { value: 'x' })).rejects.toThrow(/validation failed/);
158
+ await expect(call('test:missing', {})).rejects.toThrow(/Unknown action/);
159
+ });
160
+
161
+ it('a virtual connection is never online', () => {
162
+ const before = ws.getConnections().length;
163
+ const conn = ws.openVirtualConnection({ userId: 'u-1' });
164
+ expect(ws.isVirtual(conn)).toBe(true);
165
+ expect(ws.getConnections().length).toBe(before);
166
+ ws.closeVirtualConnection(conn);
167
+ expect(ws.isVirtual(conn)).toBe(false);
168
+ });
169
+ });
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `defineAction()` in its own module, so an action file can import it without
3
+ * importing the registry that imports the action file.
4
+ */
5
+
6
+ import type { TSchema } from 'elysia';
7
+ import type { ControlAction } from './types';
8
+
9
+ const ID = /^[a-z]+\.[a-z][a-z-]*$/;
10
+ const COMMAND = /^[a-z0-9_]{1,32}$/;
11
+
12
+ /** Validate a declaration at import — a malformed one is a bug, not a runtime condition. */
13
+ export function defineAction<A extends TSchema>(action: ControlAction<A>): ControlAction<A> {
14
+ if (!ID.test(action.id)) throw new Error(`Control action id "${action.id}" must look like group.verb`);
15
+ // `chat.*` buttons belong to the chat app itself (approvals); a catalog action by that name would never run.
16
+ if (action.id.startsWith('chat.')) throw new Error(`Control action id "${action.id}" may not start with chat.`);
17
+ const name = action.command?.name;
18
+ if (name !== undefined && !COMMAND.test(name)) throw new Error(`Control command "${name}" must match ${COMMAND}`);
19
+ return action;
20
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Managing folders from a chat while adding a project: making, renaming and
3
+ * deleting work on ordinary folders, never on a project's or above home.
4
+ */
5
+
6
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
7
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
8
+ import { homedir, tmpdir } from 'os';
9
+ import { join } from 'path';
10
+ import { initializeDatabase, closeDatabase } from '$backend/database';
11
+ import { projectQueries } from '$backend/database/queries';
12
+ import { createControlContext, getControlAction, runControlAction } from './index';
13
+
14
+ const admin = { id: 'folders-admin', name: 'Admin', role: 'admin' } as never;
15
+ const ctx = () => createControlContext(admin, { projectId: 'none', sessionId: null });
16
+
17
+ let root: string;
18
+ let projectId: string;
19
+
20
+ beforeAll(async () => {
21
+ await initializeDatabase();
22
+ root = mkdtempSync(join(tmpdir(), 'clopen-folders-'));
23
+ mkdirSync(join(root, 'project'));
24
+ projectId = projectQueries.create({ name: 'folders-test', path: join(root, 'project'), created_at: new Date().toISOString(), last_opened_at: new Date().toISOString() } as never).id;
25
+ });
26
+
27
+ afterAll(() => {
28
+ projectQueries.deleteProject(projectId);
29
+ rmSync(root, { recursive: true, force: true });
30
+ closeDatabase();
31
+ });
32
+
33
+ describe('folders while adding a project', () => {
34
+ it('asks for a name, then makes the folder and opens it', async () => {
35
+ const asked = await runControlAction(ctx(), 'projects.mkdir', { path: root });
36
+ expect(asked.ask).toMatchObject({ action: 'projects.mkdir', key: 'name', args: { path: root } });
37
+ const made = await runControlAction(ctx(), 'projects.mkdir', { path: root, name: 'fresh' });
38
+ expect(existsSync(join(root, 'fresh'))).toBe(true);
39
+ expect(made.text).toContain('Created');
40
+ expect(made.choices?.some((choice) => choice.action === 'projects.create')).toBe(true);
41
+ });
42
+
43
+ it('refuses names that are paths', async () => {
44
+ for (const name of ['../escape', 'a/b', '..', ' ']) {
45
+ await expect(runControlAction(ctx(), 'projects.mkdir', { path: root, name })).rejects.toThrow(/not a folder name/);
46
+ }
47
+ });
48
+
49
+ it('renames and deletes an ordinary folder, the delete asked first', async () => {
50
+ mkdirSync(join(root, 'old'));
51
+ writeFileSync(join(root, 'old', 'a.txt'), 'a');
52
+ await runControlAction(ctx(), 'projects.rename-folder', { path: join(root, 'old'), name: 'new' });
53
+ expect(existsSync(join(root, 'new', 'a.txt'))).toBe(true);
54
+ expect(await getControlAction('projects.delete-folder')!.confirm!({ path: join(root, 'new') } as never, ctx())).toContain('1 item');
55
+ await runControlAction(ctx(), 'projects.delete-folder', { path: join(root, 'new') });
56
+ expect(existsSync(join(root, 'new'))).toBe(false);
57
+ });
58
+
59
+ it('never renames or deletes a project, a folder holding one, or home', async () => {
60
+ await expect(runControlAction(ctx(), 'projects.delete-folder', { path: join(root, 'project') })).rejects.toThrow(/is the project/);
61
+ await expect(runControlAction(ctx(), 'projects.rename-folder', { path: root, name: 'x' })).rejects.toThrow(/holds the project/);
62
+ await expect(runControlAction(ctx(), 'projects.delete-folder', { path: homedir() })).rejects.toThrow(/home folder/);
63
+ expect(existsSync(join(root, 'project'))).toBe(true);
64
+ const menu = await runControlAction(ctx(), 'projects.browse', { path: join(root, 'project') });
65
+ expect(menu.choices?.some((choice) => choice.action === 'projects.delete-folder')).toBe(false);
66
+ });
67
+ });