@myrialabs/clopen 0.4.46 → 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 (328) 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/presets.ts +27 -2
  85. package/backend/engine/adapters/opencode/server.ts +6 -4
  86. package/backend/engine/adapters/opencode/stream.ts +11 -0
  87. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  88. package/backend/engine/adapters/parent-scope.ts +44 -0
  89. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  90. package/backend/engine/adapters/pi/stream.ts +4 -5
  91. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  92. package/backend/engine/bootstrap-default-engine.ts +2 -2
  93. package/backend/engine/docs/adapter-contract.md +8 -1
  94. package/backend/engine/install-runner.ts +8 -17
  95. package/backend/files/file-shares.ts +20 -44
  96. package/backend/files/file-size-limit.ts +3 -3
  97. package/backend/files/image-processing.ts +1 -1
  98. package/backend/files/os-clipboard.ts +2 -2
  99. package/backend/git/git-executor.ts +25 -5
  100. package/backend/git/git-service.ts +420 -19
  101. package/backend/git/identity/credential-helper.test.ts +2 -7
  102. package/backend/git/identity/import-local.test.ts +11 -16
  103. package/backend/git/identity/import-local.ts +12 -12
  104. package/backend/git/identity/index.ts +10 -24
  105. package/backend/git/identity/resolve.ts +13 -14
  106. package/backend/git/identity/scope-config.ts +33 -28
  107. package/backend/git/identity/service.ts +44 -47
  108. package/backend/git/op-lock.test.ts +111 -0
  109. package/backend/git/op-lock.ts +180 -0
  110. package/backend/git/remote-sync.test.ts +249 -0
  111. package/backend/host/metrics.ts +1 -1
  112. package/backend/http/bearer-auth.ts +1 -2
  113. package/backend/http/files-download.test.ts +8 -9
  114. package/backend/http/files-download.ts +2 -2
  115. package/backend/http/files-shared.test.ts +62 -89
  116. package/backend/http/files-shared.ts +2 -2
  117. package/backend/http/files-upload.test.ts +3 -7
  118. package/backend/http/files-upload.ts +3 -3
  119. package/backend/http/notes-images.test.ts +15 -38
  120. package/backend/http/notes-images.ts +6 -8
  121. package/backend/http/ssh-sftp.ts +5 -10
  122. package/backend/index.ts +21 -7
  123. package/backend/integrations/accounts.ts +61 -3
  124. package/backend/integrations/index.ts +2 -2
  125. package/backend/integrations/registry/define.ts +15 -0
  126. package/backend/integrations/registry/index.ts +2 -0
  127. package/backend/integrations/registry/providers/telegram.ts +54 -0
  128. package/backend/integrations/registry/types.ts +21 -1
  129. package/backend/integrations/webhooks/gateway.ts +7 -6
  130. package/backend/integrations/webhooks/verify.test.ts +30 -0
  131. package/backend/integrations/webhooks/verify.ts +4 -0
  132. package/backend/mcp/external/project.ts +1 -1
  133. package/backend/mcp/internal/remote-server.test.ts +1 -3
  134. package/backend/mcp/internal/remote-server.ts +4 -4
  135. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  136. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  137. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  138. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  139. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  140. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  141. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  142. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  143. package/backend/memory/redact.ts +1 -1
  144. package/backend/notes/access.test.ts +28 -29
  145. package/backend/notes/access.ts +6 -11
  146. package/backend/permissions/service.ts +1 -1
  147. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  148. package/backend/preview/browser/browser-clipboard.ts +67 -0
  149. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  150. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  151. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  152. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  153. package/backend/preview/browser/browser-pool.ts +67 -6
  154. package/backend/preview/browser/browser-preview-service.ts +361 -25
  155. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  156. package/backend/preview/browser/browser-video-capture.ts +92 -5
  157. package/backend/preview/browser/element-locator.ts +190 -17
  158. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  159. package/backend/preview/browser/keyboard-chords.ts +132 -0
  160. package/backend/preview/browser/paste.ts +81 -0
  161. package/backend/preview/browser/process-usage.ts +142 -0
  162. package/backend/preview/browser/profile-lock.ts +209 -0
  163. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  164. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  165. package/backend/preview/browser/types.ts +40 -2
  166. package/backend/preview/browser/viewport.test.ts +45 -0
  167. package/backend/preview/browser/viewport.ts +96 -0
  168. package/backend/profiles/service.ts +2 -2
  169. package/backend/project/status-manager.ts +43 -172
  170. package/backend/projects/home.ts +61 -0
  171. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  172. package/backend/projects/project-cleanup.ts +0 -8
  173. package/backend/skills/service.ts +2 -3
  174. package/backend/snapshot/helpers.ts +0 -1
  175. package/backend/snapshot/restore.ts +252 -0
  176. package/backend/ssh/ptykit.ts +1 -2
  177. package/backend/terminal/ptykit.ts +5 -8
  178. package/backend/tunnel/public-origin.ts +31 -20
  179. package/backend/utils/user-helpers.ts +0 -55
  180. package/backend/utils/ws.ts +61 -154
  181. package/backend/worktrees/branching/engine.ts +3 -16
  182. package/backend/worktrees/branching/index.ts +1 -1
  183. package/backend/worktrees/branching/projector.ts +1 -1
  184. package/backend/worktrees/branching/service.ts +13 -25
  185. package/backend/ws/access.ts +12 -21
  186. package/backend/ws/artifacts/generate.ts +2 -2
  187. package/backend/ws/auth/device.ts +16 -71
  188. package/backend/ws/auth/index.ts +4 -22
  189. package/backend/ws/auth/login.test.ts +14 -60
  190. package/backend/ws/auth/login.ts +24 -124
  191. package/backend/ws/auth/status.ts +0 -1
  192. package/backend/ws/chat/composer.ts +118 -118
  193. package/backend/ws/chat/stream.ts +64 -47
  194. package/backend/ws/chat-apps/index.ts +117 -0
  195. package/backend/ws/containers/actions.ts +11 -25
  196. package/backend/ws/containers/index.ts +3 -4
  197. package/backend/ws/containers/list.ts +10 -36
  198. package/backend/ws/containers/logs.ts +2 -2
  199. package/backend/ws/containers/tunnel.ts +1 -2
  200. package/backend/ws/db-client/access.ts +2 -16
  201. package/backend/ws/db-client/accounts.ts +5 -15
  202. package/backend/ws/db-client/connections.ts +17 -25
  203. package/backend/ws/db-client/context.ts +1 -1
  204. package/backend/ws/db-client/env.ts +7 -10
  205. package/backend/ws/db-client/index.ts +2 -2
  206. package/backend/ws/db-client/io.ts +5 -5
  207. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  208. package/backend/ws/db-client/query.ts +18 -17
  209. package/backend/ws/db-client/schema.ts +13 -13
  210. package/backend/ws/db-client/structure.ts +35 -35
  211. package/backend/ws/db-client/supabase.ts +4 -21
  212. package/backend/ws/deployments/context.ts +1 -1
  213. package/backend/ws/deployments/crud.ts +0 -5
  214. package/backend/ws/engine/access.ts +7 -20
  215. package/backend/ws/engine/claude/accounts.ts +4 -4
  216. package/backend/ws/engine/cline/accounts.ts +5 -5
  217. package/backend/ws/engine/codex/accounts.ts +3 -3
  218. package/backend/ws/engine/opencode/providers.ts +2 -1
  219. package/backend/ws/engine/pi/accounts.ts +5 -5
  220. package/backend/ws/files/clipboard.ts +8 -27
  221. package/backend/ws/files/image-edit.ts +6 -6
  222. package/backend/ws/files/index.ts +1 -1
  223. package/backend/ws/files/path-access.test.ts +32 -131
  224. package/backend/ws/files/path-access.ts +8 -87
  225. package/backend/ws/files/read.ts +15 -19
  226. package/backend/ws/files/reveal.ts +3 -3
  227. package/backend/ws/files/search.ts +7 -7
  228. package/backend/ws/files/share.ts +9 -13
  229. package/backend/ws/files/state.ts +9 -12
  230. package/backend/ws/files/watch.ts +3 -3
  231. package/backend/ws/files/write.ts +30 -31
  232. package/backend/ws/git/branch.ts +80 -59
  233. package/backend/ws/git/commit.ts +63 -44
  234. package/backend/ws/git/conflict.ts +16 -18
  235. package/backend/ws/git/identity-context.ts +8 -17
  236. package/backend/ws/git/identity.ts +17 -27
  237. package/backend/ws/git/index.ts +3 -1
  238. package/backend/ws/git/op-state.ts +139 -0
  239. package/backend/ws/git/remote.ts +241 -141
  240. package/backend/ws/git/repo-context.ts +67 -0
  241. package/backend/ws/git/staging.ts +18 -28
  242. package/backend/ws/git/status.ts +5 -2
  243. package/backend/ws/index.ts +5 -1
  244. package/backend/ws/instructions/crud.ts +1 -1
  245. package/backend/ws/integrations/crud.ts +1 -3
  246. package/backend/ws/mcp/crud.ts +3 -5
  247. package/backend/ws/mcp/tools.ts +1 -1
  248. package/backend/ws/memory/crud.ts +14 -46
  249. package/backend/ws/memory/index.ts +2 -2
  250. package/backend/ws/messages/crud.ts +29 -8
  251. package/backend/ws/notes/index.ts +33 -39
  252. package/backend/ws/permissions/crud.ts +3 -4
  253. package/backend/ws/ports/index.ts +1 -2
  254. package/backend/ws/ports/kill.ts +5 -10
  255. package/backend/ws/ports/list.ts +4 -10
  256. package/backend/ws/preview/access.ts +1 -1
  257. package/backend/ws/preview/browser/interact.ts +52 -79
  258. package/backend/ws/preview/browser/native-ui.ts +24 -0
  259. package/backend/ws/preview/browser/stats.ts +98 -1
  260. package/backend/ws/preview/browser/tab-info.ts +15 -0
  261. package/backend/ws/preview/browser/tab.ts +19 -4
  262. package/backend/ws/preview/index.ts +27 -0
  263. package/backend/ws/profiles/crud.ts +6 -8
  264. package/backend/ws/project-artifacts/index.ts +30 -31
  265. package/backend/ws/projects/crud.ts +33 -35
  266. package/backend/ws/projects/index.ts +3 -8
  267. package/backend/ws/projects/info.ts +3 -3
  268. package/backend/ws/projects/overview.ts +19 -30
  269. package/backend/ws/projects/status.ts +17 -57
  270. package/backend/ws/sessions/crud.ts +34 -45
  271. package/backend/ws/sessions/index.ts +1 -1
  272. package/backend/ws/settings/crud.ts +1 -1
  273. package/backend/ws/skills/crud.ts +3 -4
  274. package/backend/ws/skills/index.ts +1 -1
  275. package/backend/ws/snapshot/changes.ts +7 -7
  276. package/backend/ws/snapshot/restore.ts +11 -295
  277. package/backend/ws/snapshot/timeline.ts +2 -4
  278. package/backend/ws/ssh/access.ts +6 -21
  279. package/backend/ws/ssh/connections.ts +21 -31
  280. package/backend/ws/ssh/forwards.ts +12 -12
  281. package/backend/ws/ssh/sftp.ts +34 -34
  282. package/backend/ws/ssh/tunnel.ts +1 -2
  283. package/backend/ws/stack/install.ts +7 -17
  284. package/backend/ws/subagents/crud.ts +1 -1
  285. package/backend/ws/tunnel/share.ts +0 -2
  286. package/backend/ws/user/crud.ts +1 -59
  287. package/backend/ws/user/index.ts +1 -1
  288. package/backend/ws/work/context.ts +1 -1
  289. package/backend/ws/work/crud.ts +0 -5
  290. package/backend/ws/workspace/state.ts +10 -13
  291. package/backend/ws/worktrees/branching.ts +7 -36
  292. package/backend/ws/worktrees/crud.ts +2 -2
  293. package/bin/clopen.ts +10 -11
  294. package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
  295. package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
  296. package/dist/assets/main-BUiUL3eZ.css +1 -0
  297. package/dist/assets/main-nBOb9YOA.js +1240 -0
  298. package/dist/index.html +2 -2
  299. package/package.json +2 -1
  300. package/shared/constants/attachments.ts +14 -0
  301. package/shared/constants/engine-tools.ts +1 -1
  302. package/shared/constants/preview.test.ts +259 -0
  303. package/shared/constants/preview.ts +1018 -57
  304. package/shared/constants/tool-icons.ts +5 -0
  305. package/shared/types/containers/container.ts +1 -1
  306. package/shared/types/database/schema.ts +9 -6
  307. package/shared/types/git-identity.ts +1 -1
  308. package/shared/types/git.ts +116 -0
  309. package/shared/types/integrations.ts +7 -0
  310. package/shared/types/stores/settings.ts +1 -1
  311. package/shared/types/unified/index.ts +1 -1
  312. package/shared/types/unified/message.ts +0 -7
  313. package/shared/types/unified/stream.ts +2 -4
  314. package/shared/types/unified/tool.ts +15 -1
  315. package/shared/utils/ask-user-question.test.ts +319 -0
  316. package/shared/utils/ask-user-question.ts +154 -0
  317. package/shared/utils/home-project.ts +25 -0
  318. package/shared/utils/logger.ts +2 -0
  319. package/shared/utils/ws-server.ts +32 -7
  320. package/backend/auth/session-invalidation.test.ts +0 -112
  321. package/backend/auth/session-invalidation.ts +0 -77
  322. package/backend/project/status-manager.test.ts +0 -32
  323. package/backend/ws/auth/invites.ts +0 -94
  324. package/backend/ws/auth/users.ts +0 -112
  325. package/backend/ws/projects/presence.ts +0 -46
  326. package/backend/ws/stack/access.ts +0 -31
  327. package/dist/assets/main-BiDNMWb3.css +0 -1
  328. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Inbound — every message a paired chat sends, and the checks in front of it.
3
+ *
4
+ * Nothing in a message is trusted on its own. A button names a row, and that
5
+ * row must belong to the link of the chat that pressed it; the link's account
6
+ * must still exist and the row's project must still be in Clopen; the person
7
+ * pressing must be the platform user who paired the chat; and anything that
8
+ * drives Clopen needs the bot's `control` capability. Only then does anything
9
+ * happen.
10
+ *
11
+ * /start <code>, /unlink pairing (here)
12
+ * any other /command the chat's own commands or the control catalog (`conversation.ts`)
13
+ * a button a question, a menu, or a confirmation
14
+ * an edit Edit Message on what the user sent
15
+ * a reply answer that question / continue from that point
16
+ * text, photos, files, an album a question of the active session that waits, else the active session
17
+ *
18
+ * ONE AT A TIME PER CHAT. Messages of one chat are handled in the order they
19
+ * arrived, each after the previous finished: two sent a second apart into a
20
+ * chat with no session must make one session, not two. Different chats never
21
+ * wait for each other.
22
+ *
23
+ * An ALBUM arrives as one message per photo. They are collected for a moment
24
+ * and handled as one message, so five photos are one turn, not five.
25
+ */
26
+
27
+ import type { UniversalMessage } from '@myrialabs/chatkit';
28
+ import {
29
+ channelMessageQueries,
30
+ channelLinkQueries,
31
+ projectQueries,
32
+ type ChannelMessageRow,
33
+ type ChannelLinkRow
34
+ } from '$backend/database/queries';
35
+ import { getUserById } from '$backend/auth/auth-service';
36
+ import { debug } from '$shared/utils/logger';
37
+ import { channelRuntime, type ActiveChannel } from './runtime';
38
+ import { redeemPairingCode } from './pairing';
39
+ import { notifyLinksChanged } from './link-events';
40
+ import { REPLIES, decodeButtonData } from './messages';
41
+ import { answerQuestionWithText, handleQuestionButton, replyText } from './questions';
42
+ import { collectAttachments, isMedia, textOf, type PromptAttachment } from './media';
43
+ import { clearAwaiting, hasAwaiting, takeAwaiting } from './awaiting';
44
+ import {
45
+ activeTarget,
46
+ answerAsk,
47
+ isAsking,
48
+ isKnownCommand,
49
+ continueActive,
50
+ continueFrom,
51
+ editSent,
52
+ handleControlButton,
53
+ handleControlCommand,
54
+ type Conversation
55
+ } from './conversation';
56
+
57
+ export { registerComposer } from './conversation';
58
+ export { onLinksChanged } from './link-events';
59
+ export type { Composer } from './conversation';
60
+
61
+ /** How long the rest of an album may take to arrive after its first photo. */
62
+ const ALBUM_WINDOW_MS = 1200;
63
+
64
+ // ── Ordering ────────────────────────────────────────────────────────────────
65
+
66
+ const chains = new Map<string, Promise<void>>();
67
+
68
+ function chatKey(message: UniversalMessage): string {
69
+ return `${message.address.account}\u0000${message.address.conversation_id}`;
70
+ }
71
+
72
+ /** Run `task` after everything this chat sent before it. */
73
+ function inOrder(key: string, task: () => Promise<void>): Promise<void> {
74
+ const next = (chains.get(key) ?? Promise.resolve()).then(task).catch((error) => {
75
+ debug.error('chat-apps', 'Handling a channel message failed:', error);
76
+ });
77
+ chains.set(key, next);
78
+ void next.finally(() => {
79
+ if (chains.get(key) === next) chains.delete(key);
80
+ });
81
+ return next;
82
+ }
83
+
84
+ interface PendingAlbum {
85
+ messages: UniversalMessage[];
86
+ channel: ActiveChannel;
87
+ timer: ReturnType<typeof setTimeout> | null;
88
+ }
89
+
90
+ const albums = new Map<string, PendingAlbum>();
91
+
92
+ export function handleInboundMessage(message: UniversalMessage, channel: ActiveChannel): Promise<void> {
93
+ if (message.from?.is_self) return Promise.resolve();
94
+ const key = chatKey(message);
95
+ const album = isMedia(message.content) && !message.edited ? channel.platform.albumOf(message) : null;
96
+ if (!album) return inOrder(key, () => handleMessages([message], channel));
97
+
98
+ // The photos of an album trickle in; hold them until the album is complete.
99
+ const albumKey = `${key}\u0000${album}`;
100
+ const pending = albums.get(albumKey);
101
+ if (pending) pending.messages.push(message);
102
+ const entry: PendingAlbum = pending ?? { messages: [message], channel, timer: null };
103
+ if (entry.timer) clearTimeout(entry.timer);
104
+ entry.timer = setTimeout(() => {
105
+ albums.delete(albumKey);
106
+ void inOrder(key, () => handleMessages(entry.messages, entry.channel));
107
+ }, ALBUM_WINDOW_MS);
108
+ entry.timer.unref?.();
109
+ albums.set(albumKey, entry);
110
+ return Promise.resolve();
111
+ }
112
+
113
+ // ── One message (or one album) ──────────────────────────────────────────────
114
+
115
+ /** Content a chat can drive Clopen with. Reactions and platform extras are not. */
116
+ function isActionable(message: UniversalMessage): boolean {
117
+ const type = message.content.type;
118
+ return type === 'text' || type === 'postback' || type === 'media' || type === 'location' || type === 'contact';
119
+ }
120
+
121
+ /** Files ChatKit downloaded that will not be used must still leave its store. */
122
+ async function discardMedia(messages: UniversalMessage[]): Promise<void> {
123
+ for (const message of messages) {
124
+ if (isMedia(message.content)) await channelRuntime.takeMedia(message.content.url).catch(() => null);
125
+ }
126
+ }
127
+
128
+ async function handleMessages(messages: UniversalMessage[], channel: ActiveChannel): Promise<void> {
129
+ const message = messages[0];
130
+ if (!isActionable(message)) return;
131
+ const content = message.content;
132
+ let command = content.type === 'text' && !message.edited ? channel.platform.parseCommand(content.text) : null;
133
+
134
+ if (!channel.platform.isDirect(message)) {
135
+ await discardMedia(messages);
136
+ if (command?.command === 'start') await replyText(channel, message, REPLIES.groupRefused);
137
+ return;
138
+ }
139
+
140
+ const link = channelLinkQueries.getByConversation(channel.accountId, message.address.conversation_id);
141
+
142
+ if (command?.command === 'start') {
143
+ await pair(channel, message, link, command.argument);
144
+ return;
145
+ }
146
+ if (!link) {
147
+ await discardMedia(messages);
148
+ await replyText(channel, message, REPLIES.notLinked);
149
+ return;
150
+ }
151
+ // In a private chat the sender is the chat, but the check is cheap and the
152
+ // day a platform's notion of "direct" turns out looser is not the day to find out.
153
+ if (message.from?.user_id !== link.platform_user_id) {
154
+ await discardMedia(messages);
155
+ return;
156
+ }
157
+ const user = getUserById(link.user_id);
158
+ if (!user) {
159
+ await discardMedia(messages);
160
+ return;
161
+ }
162
+ // While the bot waits for typed words, "/etc is fine" is those words, not a
163
+ // typo'd command. Only a command Clopen knows ends the wait.
164
+ if (command && command.command !== 'start' && !isKnownCommand(command.command) && hasAwaiting(link.id)) command = null;
165
+
166
+ // Switched off: nothing but leaving (or asking why) works.
167
+ if (!channelLinkQueries.isActive(link) && command?.command !== 'unlink') {
168
+ await discardMedia(messages);
169
+ if (content.type !== 'postback') await replyText(channel, message, REPLIES.chatOff);
170
+ return;
171
+ }
172
+ channelLinkQueries.touch(link.id);
173
+ const conversation: Conversation = { channel, message, link, user };
174
+
175
+ try {
176
+ if (command) {
177
+ // A command is not the answer to whatever was being typed.
178
+ clearAwaiting(link.id);
179
+ await handleCommand(conversation, command.command, command.argument, content.type === 'text' ? content.text : '');
180
+ } else if (content.type === 'postback') {
181
+ await handleButton(conversation, content.data);
182
+ } else {
183
+ const { attachments, problems } = await collectAttachments(channel, messages);
184
+ if (problems.length) await replyText(channel, message, REPLIES.attachmentsDropped(problems));
185
+ // An album's caption sits on whichever photo the user wrote it under.
186
+ const text = messages.map((entry) => textOf(entry.content)).filter((entry) => entry.trim()).join('\n\n');
187
+ if (!text.trim() && attachments.length === 0) return;
188
+ if (message.edited) await editSent(conversation, text, attachments);
189
+ else await handleText(conversation, text, attachments);
190
+ }
191
+ } catch (error) {
192
+ debug.error('chat-apps', 'Handling a channel message failed:', error);
193
+ await replyText(channel, message, error instanceof Error ? `⚠️ ${error.message}` : REPLIES.answerFailed);
194
+ }
195
+ }
196
+
197
+ async function pair(channel: ActiveChannel, message: UniversalMessage, link: ChannelLinkRow | null, code: string): Promise<void> {
198
+ if (!code) {
199
+ const reply = !link
200
+ ? REPLIES.notLinked
201
+ : link.is_enabled !== 1
202
+ ? REPLIES.chatOff
203
+ : REPLIES.helpIntro;
204
+ await replyText(channel, message, reply);
205
+ return;
206
+ }
207
+ const redeemed = redeemPairingCode(code, channel.accountId);
208
+ const user = redeemed ? getUserById(redeemed.userId) : null;
209
+ if (!redeemed || !user || !message.from) {
210
+ await replyText(channel, message, REPLIES.pairingExpired);
211
+ return;
212
+ }
213
+ const paired = channelLinkQueries.upsert({
214
+ accountId: channel.accountId,
215
+ userId: user.id,
216
+ conversationId: message.address.conversation_id,
217
+ platformUserId: message.from.user_id,
218
+ displayName: message.from.display_name ?? null
219
+ });
220
+ debug.log('chat-apps', `Paired a ${channel.platform.provider} chat (${paired.id})`);
221
+ notifyLinksChanged();
222
+ await replyText(channel, message, REPLIES.paired);
223
+ }
224
+
225
+ async function handleCommand(conversation: Conversation, command: string, argument: string, rawText: string): Promise<void> {
226
+ const { channel, message, link } = conversation;
227
+ if (command === 'unlink') {
228
+ channelLinkQueries.remove(link.id);
229
+ await replyText(channel, message, REPLIES.unlinked);
230
+ notifyLinksChanged();
231
+ return;
232
+ }
233
+ await handleControlCommand(conversation, command, argument, rawText);
234
+ }
235
+
236
+ /** The row, if it is this chat's and its project is still in Clopen. */
237
+ async function ownedRow(conversation: Conversation, row: ChannelMessageRow | null): Promise<ChannelMessageRow | null> {
238
+ const { channel, message, link } = conversation;
239
+ if (!row || row.link_id !== link.id) {
240
+ await replyText(channel, message, REPLIES.staleAction);
241
+ return null;
242
+ }
243
+ if (row.project_id && !projectQueries.isListed(row.project_id)) {
244
+ await replyText(channel, message, REPLIES.noAccess);
245
+ return null;
246
+ }
247
+ return row;
248
+ }
249
+
250
+ async function handleButton(conversation: Conversation, data: string): Promise<void> {
251
+ const decoded = decodeButtonData(data);
252
+ if (!decoded) return;
253
+ const row = await ownedRow(conversation, channelMessageQueries.getById(decoded.rowId));
254
+ if (!row) return;
255
+ if (row.kind === 'question') await handleQuestionButton(conversation.channel, conversation.message, conversation.link, row, decoded.action);
256
+ else await handleControlButton(conversation, row, decoded.action);
257
+ }
258
+
259
+ async function answerWithText(conversation: Conversation, row: ChannelMessageRow, text: string, attachments: PromptAttachment[]): Promise<void> {
260
+ const { channel, message, link } = conversation;
261
+ if (attachments.length) await replyText(channel, message, REPLIES.answerTakesText);
262
+ if (!text.trim()) return;
263
+ await answerQuestionWithText(channel, message, link, row, text);
264
+ }
265
+
266
+ async function handleText(conversation: Conversation, text: string, attachments: PromptAttachment[]): Promise<void> {
267
+ const { channel, message, link } = conversation;
268
+
269
+ if (message.reply_to) {
270
+ const target = channelMessageQueries.getByMessage(link.id, message.reply_to);
271
+ if (target) {
272
+ const row = await ownedRow(conversation, target);
273
+ if (!row) return;
274
+ if (row.kind === 'question') {
275
+ await answerWithText(conversation, row, text, attachments);
276
+ return;
277
+ }
278
+ if (row.chat_session_id && (row.kind === 'answer' || row.kind === 'user')) {
279
+ await continueFrom(conversation, row, text, attachments);
280
+ return;
281
+ }
282
+ if (row.kind === 'menu' && isAsking(row)) {
283
+ clearAwaiting(link.id);
284
+ await answerAsk(conversation, row, text);
285
+ return;
286
+ }
287
+ }
288
+ // A reply to something with no place in a conversation (a hint, a menu)
289
+ // is just a message.
290
+ }
291
+
292
+ // The bot just asked for words ("Other…", a folder name): this is them.
293
+ const awaited = takeAwaiting(link.id);
294
+ const awaitedRow = awaited ? channelMessageQueries.getById(awaited.rowId) : null;
295
+ if (awaitedRow && awaitedRow.link_id === link.id && awaitedRow.state === 'open') {
296
+ if (awaited!.kind === 'question') {
297
+ const row = await ownedRow(conversation, awaitedRow);
298
+ if (row) await answerWithText(conversation, row, text, attachments);
299
+ return;
300
+ }
301
+ if (isAsking(awaitedRow)) {
302
+ await answerAsk(conversation, awaitedRow, text);
303
+ return;
304
+ }
305
+ }
306
+
307
+ // A question the session you are in is waiting on is what a plain message
308
+ // most likely answers. One waiting in ANOTHER session is not: switching to
309
+ // a session and typing must reach that session, so those are answered by
310
+ // replying to them.
311
+ const { session } = activeTarget(link);
312
+ const open = session ? channelMessageQueries.openQuestionsForLink(link.id).filter((row) => row.chat_session_id === session.id) : [];
313
+ if (open.length === 1) {
314
+ const row = await ownedRow(conversation, open[0]);
315
+ if (row) await answerWithText(conversation, row, text, attachments);
316
+ return;
317
+ }
318
+ if (open.length > 1) {
319
+ await replyText(channel, message, REPLIES.pickReply);
320
+ return;
321
+ }
322
+
323
+ await continueActive(conversation, text, attachments);
324
+ }
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Chat apps — control Clopen from a chat app. Chat with any session (or with
3
+ * none, from Home), reply to an earlier message to continue from that point,
4
+ * edit a sent message like Edit Message, and drive the rest of Clopen through
5
+ * the control catalog: sessions, files, skills, projects, models and engine
6
+ * accounts. Questions and answers of the turns a chat starts come back to it
7
+ * as part of the same conversation.
8
+ *
9
+ * platforms/ per-platform shape (Telegram first; Task 14 adds the rest)
10
+ * runtime.ts the one ChatKit, its adapters, webhook-or-polling delivery, menus
11
+ * media.ts files and albums in, images of an answer out
12
+ * outbound.ts what is sent, and keeping sent messages true
13
+ * turns.ts turns a chat started: mapping, typing, progress
14
+ * inbound.ts every inbound message, and the checks before each
15
+ * conversation.ts the active target, sending, going back, menus, commands
16
+ * questions.ts answering AskUserQuestion from a chat
17
+ * messages.ts the wording, as pure functions
18
+ * pairing.ts one-time codes binding a chat to Clopen
19
+ *
20
+ * A chat app is a CAPABILITY of a connected account (`control`), not a panel:
21
+ * the bot token lives on its `integration_accounts` row like every other
22
+ * credential. Pairing and what the chat is told about unprompted sit in
23
+ * Settings → Chat Apps. WHAT the chat can do
24
+ * is not here at all: it is the control catalog (`backend/control/`), shared
25
+ * with every other remote surface.
26
+ *
27
+ * Importing this module wires the stream hooks and the webhook subscriber;
28
+ * `startChatApps()` opens the bots.
29
+ */
30
+
31
+ import type { AskUserQuestion } from '$shared/types/unified';
32
+ import {
33
+ integrationAccountQueries,
34
+ channelLinkQueries,
35
+ type ChannelLinkRow
36
+ } from '$backend/database/queries';
37
+ import { onAccountsChanged, onWebhook, registerAccountProbe } from '$backend/integrations';
38
+ import { streamManager, type StreamEvent } from '$backend/chat/stream-manager';
39
+ import { debug } from '$shared/utils/logger';
40
+ import { channelRuntime } from './runtime';
41
+ import { listChannelPlatforms, getChannelPlatform } from './platforms';
42
+ import { announceQuestion, announceRunEnded, forgetSession, settleToolUses } from './outbound';
43
+ import { handleInboundMessage } from './inbound';
44
+ import { issuePairingCode, revokePairingCode, PAIRING_TTL_MS } from './pairing';
45
+ import { onToolActivity, onUserMessage } from './turns';
46
+ import { CHAT_COMMANDS, REPLIES, describeToolUse, textCard } from './messages';
47
+ import { commandReference, setPublicOriginResolver, type CommandEntry } from '$backend/control';
48
+ import type { ChannelCommand } from './platforms';
49
+ import { notifyLinksChanged } from './link-events';
50
+
51
+ export { registerComposer, onLinksChanged } from './inbound';
52
+
53
+ /** Told when a bot's running state may have changed, so Settings can refresh. */
54
+ export function onBotsChanged(listener: () => void): void {
55
+ channelRuntime.onStatusChanged(listener);
56
+ }
57
+ export type { Composer } from './inbound';
58
+
59
+ // ── Wiring ──────────────────────────────────────────────────────────────────
60
+
61
+ /** Telegram's ceiling, and a sane one for any menu. */
62
+ const MAX_MENU_COMMANDS = 100;
63
+ const MAX_MENU_DESCRIPTION = 256;
64
+
65
+ /**
66
+ * The `/` menu: EXACTLY what `/help` lists, in the same order — the chat's own
67
+ * commands, then the catalog's. Generated, so a new catalog action shows up in
68
+ * every chat app without touching this module.
69
+ */
70
+ export function botCommands(): ChannelCommand[] {
71
+ return commandReference(CHAT_COMMANDS)
72
+ .slice(0, MAX_MENU_COMMANDS)
73
+ .map((entry) => {
74
+ const described = entry.hint ? `${entry.description} (${entry.hint})` : entry.description;
75
+ return { command: entry.command, description: described.length > MAX_MENU_DESCRIPTION ? `${described.slice(0, MAX_MENU_DESCRIPTION - 1)}…` : described };
76
+ });
77
+ }
78
+
79
+ channelRuntime.setInboundHandler(handleInboundMessage);
80
+ channelRuntime.setCommandMenu({
81
+ commands: botCommands,
82
+ chatsOf: (accountId) => channelLinkQueries.listByAccount(accountId).map((link) => link.conversation_id)
83
+ });
84
+ // Links in catalog results use the runtime's origin, which remembers the last
85
+ // real domain a browser used — better than a bare lookup.
86
+ setPublicOriginResolver(() => channelRuntime.publicOrigin());
87
+
88
+ for (const platform of listChannelPlatforms()) {
89
+ onWebhook(platform.provider, (event) => channelRuntime.receiveWebhook(event));
90
+
91
+ registerAccountProbe(platform.provider, async (accountId) => {
92
+ const row = integrationAccountQueries.getById(accountId);
93
+ if (!row) return null;
94
+ if (!integrationAccountQueries.capabilitiesOf(row).includes('control')) {
95
+ return { status: 'unknown', detail: '"Control Clopen" is switched off for this bot' };
96
+ }
97
+ const status = channelRuntime.status(accountId);
98
+ const adapter = channelRuntime.adapterFor(accountId);
99
+ if (!adapter || !status.mode) {
100
+ return { status: 'error', detail: status.error ?? 'The bot is not running' };
101
+ }
102
+ const health = await platform.probe(adapter, status.mode);
103
+ const via = status.mode === 'webhook' && status.originSource ? ` via ${status.originSource}` : '';
104
+ return { status: health.status, detail: health.detail ? `${health.detail}${via}` : null };
105
+ });
106
+ }
107
+
108
+ // Any account change may add, drop or rebuild a bot. Cheap when nothing moved:
109
+ // the runtime compares fingerprints before touching an adapter.
110
+ onAccountsChanged(() => {
111
+ if (channelRuntime.isStarted) void channelRuntime.reconcile();
112
+ });
113
+
114
+ // Server-side stream events: these fire whether or not a browser is attached,
115
+ // which is exactly when a chat that started a turn still needs its answer.
116
+ streamManager.on('stream:message', (payload: {
117
+ event: StreamEvent;
118
+ projectId?: string;
119
+ chatSessionId: string;
120
+ requestedByUserId?: string;
121
+ }) => {
122
+ if (!channelRuntime.isStarted || !payload.projectId) return;
123
+ const message = payload.event.data?.message;
124
+ const blocks: any[] = Array.isArray(message?.content) ? message.content : [];
125
+
126
+ // A user message a chat sent: map it, and start that chat's live feedback.
127
+ // Matched by the prompt's own id, so a photo with no caption counts too.
128
+ if (message?.type === 'user' && typeof payload.event.data?.message_id === 'string' && typeof message.messageId === 'string' && !message.parent?.toolUseId) {
129
+ onUserMessage(payload.chatSessionId, payload.event.data.message_id, message.messageId);
130
+ }
131
+
132
+ // What the turn is doing, for the progress line of a turn a chat started.
133
+ for (const block of blocks) {
134
+ if (block?.type === 'tool_use' && typeof block.name === 'string' && block.name !== 'AskUserQuestion') {
135
+ onToolActivity(payload.chatSessionId, describeToolUse(block.name, block.input));
136
+ }
137
+ }
138
+
139
+ const settled = blocks.filter((block) => block?.type === 'tool_result' && typeof block.toolUseId === 'string').map((block) => block.toolUseId as string);
140
+ if (settled.length > 0) void settleToolUses(settled).catch((error) => debug.warn('chat-apps', 'Settling channel questions failed:', error));
141
+
142
+ const ask = blocks.find((block) => block?.type === 'tool_use' && block.name === 'AskUserQuestion');
143
+ if (ask && Array.isArray(ask.input?.questions)) {
144
+ void announceQuestion({
145
+ projectId: payload.projectId,
146
+ chatSessionId: payload.chatSessionId,
147
+ toolUseId: ask.id,
148
+ questions: ask.input.questions as AskUserQuestion[]
149
+ }).catch((error) => debug.warn('chat-apps', 'Announcing a channel question failed:', error));
150
+ }
151
+ });
152
+
153
+ streamManager.on('stream:lifecycle', (event: {
154
+ status: 'completed' | 'error' | 'cancelled';
155
+ projectId?: string;
156
+ chatSessionId?: string;
157
+ reason?: string;
158
+ }) => {
159
+ if (!channelRuntime.isStarted || !event.projectId || !event.chatSessionId) return;
160
+ void announceRunEnded({
161
+ status: event.status,
162
+ projectId: event.projectId,
163
+ chatSessionId: event.chatSessionId,
164
+ reason: event.reason
165
+ }).catch((error) => debug.warn('chat-apps', 'Announcing a finished run failed:', error));
166
+ });
167
+
168
+ streamManager.on('session:cleanup', (chatSessionId: string) => {
169
+ try {
170
+ forgetSession(chatSessionId);
171
+ } catch (error) {
172
+ debug.warn('chat-apps', 'Dropping channel prompts for a deleted session failed:', error);
173
+ }
174
+ });
175
+
176
+ // ── Lifecycle ───────────────────────────────────────────────────────────────
177
+
178
+ export async function startChatApps(): Promise<void> {
179
+ try {
180
+ await channelRuntime.start();
181
+ } catch (error) {
182
+ // A chat app failing to open must never keep Clopen from starting.
183
+ debug.error('chat-apps', 'Chat apps failed to start:', error);
184
+ }
185
+ }
186
+
187
+ export async function stopChatApps(): Promise<void> {
188
+ await channelRuntime.stop();
189
+ }
190
+
191
+ // ── What Settings → Chat Apps shows and does ────────────────────────────────
192
+
193
+ export interface ChannelLinkInfo {
194
+ id: string;
195
+ /** The chat's name on the platform. */
196
+ displayName: string | null;
197
+ /** Off: the chat can do nothing at all until it is switched back on. */
198
+ isEnabled: boolean;
199
+ createdAt: string;
200
+ lastUsedAt: string | null;
201
+ }
202
+
203
+ export interface ChannelBotInfo {
204
+ accountId: string;
205
+ provider: string;
206
+ label: string;
207
+ botName: string | null;
208
+ projectId: string | null;
209
+ running: boolean;
210
+ mode: 'webhook' | 'polling' | null;
211
+ originSource: 'configured' | 'domain' | 'tunnel' | null;
212
+ /** Whether the bot is actually reaching the platform right now. */
213
+ connection: 'connecting' | 'open' | 'closed' | null;
214
+ error: string | null;
215
+ /** "Control Clopen" is on for this bot; without it a chat cannot drive anything. */
216
+ control: boolean;
217
+ /** The chats paired through this bot. */
218
+ links: ChannelLinkInfo[];
219
+ }
220
+
221
+ function toLinkInfo(row: ChannelLinkRow): ChannelLinkInfo {
222
+ return {
223
+ id: row.id,
224
+ displayName: row.display_name,
225
+ isEnabled: row.is_enabled === 1,
226
+ createdAt: row.created_at,
227
+ lastUsedAt: row.last_used_at
228
+ };
229
+ }
230
+
231
+ /** Every bot a chat can pair with, and the chats paired through it. */
232
+ export async function listChannelBots(requestOrigin?: string): Promise<ChannelBotInfo[]> {
233
+ channelRuntime.rememberBrowserOrigin(requestOrigin);
234
+ const bots: ChannelBotInfo[] = [];
235
+ for (const row of integrationAccountQueries.getAll()) {
236
+ const platform = getChannelPlatform(row.provider);
237
+ if (!platform || row.is_enabled !== 1) continue;
238
+ const capabilities = integrationAccountQueries.capabilitiesOf(row);
239
+ const status = channelRuntime.status(row.id);
240
+ const adapter = channelRuntime.adapterFor(row.id);
241
+ const links = channelLinkQueries.listByAccount(row.id);
242
+ bots.push({
243
+ accountId: row.id,
244
+ provider: row.provider,
245
+ label: row.label,
246
+ botName: adapter ? await platform.botName(adapter) : null,
247
+ projectId: row.project_id,
248
+ running: status.running,
249
+ mode: status.mode,
250
+ originSource: status.originSource,
251
+ connection: status.connection,
252
+ error: status.error,
253
+ control: capabilities.includes('control'),
254
+ links: links.map(toLinkInfo)
255
+ });
256
+ }
257
+ return bots;
258
+ }
259
+
260
+ export async function createPairingLink(userId: string, accountId: string): Promise<{ url: string; expiresAt: string; ttlSeconds: number }> {
261
+ const row = integrationAccountQueries.getById(accountId);
262
+ const platform = row ? getChannelPlatform(row.provider) : null;
263
+ const adapter = channelRuntime.adapterFor(accountId);
264
+ if (!row || !platform || !adapter) throw new Error('That bot is not running. Check it in Settings → Integrations.');
265
+ const { code, expiresAt } = issuePairingCode(userId, accountId);
266
+ return { url: await platform.pairingLink(adapter, code), expiresAt, ttlSeconds: Math.round(PAIRING_TTL_MS / 1000) };
267
+ }
268
+
269
+ /** Close the pairing link the user was shown: scanning it afterwards does nothing. */
270
+ export function cancelPairingLink(userId: string, accountId: string): void {
271
+ revokePairingCode(userId, accountId);
272
+ }
273
+
274
+ function requireLink(linkId: string): ChannelLinkRow {
275
+ const link = channelLinkQueries.getById(linkId);
276
+ if (!link) throw new Error('Linked chat not found');
277
+ return link;
278
+ }
279
+
280
+ export async function setChannelLinkEnabled(linkId: string, enabled: boolean): Promise<void> {
281
+ const link = requireLink(linkId);
282
+ channelLinkQueries.setEnabled(linkId, enabled);
283
+ // Switched off or back on from Clopen: the chat should know why it went quiet.
284
+ if (enabled !== (link.is_enabled === 1)) {
285
+ await channelRuntime.send(link.account_id, link.conversation_id, textCard(enabled ? REPLIES.chatOn : REPLIES.chatOff)).catch(() => {});
286
+ }
287
+ notifyLinksChanged();
288
+ }
289
+
290
+ export async function removeChannelLink(linkId: string): Promise<void> {
291
+ const link = requireLink(linkId);
292
+ channelLinkQueries.remove(linkId);
293
+ // Tell the chat, so it does not keep waiting for messages that will never come.
294
+ await channelRuntime.send(link.account_id, link.conversation_id, textCard(REPLIES.unlinked)).catch(() => {});
295
+ notifyLinksChanged();
296
+ }
297
+
298
+ export async function sendChannelTest(linkId: string): Promise<void> {
299
+ const link = requireLink(linkId);
300
+ await channelRuntime.send(link.account_id, link.conversation_id, textCard(REPLIES.testMessage));
301
+ channelLinkQueries.touch(linkId);
302
+ }
303
+
304
+ export type ChatAppCommandInfo = CommandEntry;
305
+
306
+ /** The command reference Settings shows — the same list `/help` and the `/` menu are. */
307
+ export function listChatAppCommands(): ChatAppCommandInfo[] {
308
+ return commandReference(CHAT_COMMANDS);
309
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * "The paired chats changed": told when a chat pairs or unpairs from the
3
+ * phone, so an open Settings panel refreshes without a request from the tab.
4
+ */
5
+
6
+ import { debug } from '$shared/utils/logger';
7
+
8
+ let listener: (() => void) | null = null;
9
+
10
+ export function onLinksChanged(next: () => void): void {
11
+ listener = next;
12
+ }
13
+
14
+ export function notifyLinksChanged(): void {
15
+ try {
16
+ listener?.();
17
+ } catch (error) {
18
+ debug.warn('chat-apps', 'Links-changed listener failed:', error);
19
+ }
20
+ }