@myrialabs/clopen 0.2.16 → 0.2.17

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 (286) hide show
  1. package/.env.example +4 -4
  2. package/backend/utils/env.ts +5 -5
  3. package/bin/clopen.ts +21 -298
  4. package/dist/assets/addon-clipboard-wHJhZAA4.js +1 -0
  5. package/dist/assets/addon-fit-DX4qG4td.js +1 -0
  6. package/dist/assets/addon-ligatures-DpDY8N_X.js +2 -0
  7. package/dist/assets/addon-unicode11-Bt8F3D7-.js +7 -0
  8. package/dist/assets/addon-web-links-DIbG5aQx.js +1 -0
  9. package/dist/assets/index-C-eR9PGW.js +2 -0
  10. package/dist/assets/main-D1IISCsM.js +247 -0
  11. package/dist/assets/main-DzSwlujO.css +1 -0
  12. package/dist/assets/xterm-B-qIQCd3.js +16 -0
  13. package/{index.html → dist/index.html} +2 -1
  14. package/package.json +11 -2
  15. package/scripts/start.ts +3 -3
  16. package/shared/utils/logger.ts +1 -1
  17. package/.dockerignore +0 -5
  18. package/.github/workflows/ci.yml +0 -86
  19. package/CONTRIBUTING.md +0 -188
  20. package/bun.lock +0 -1127
  21. package/docker-compose.yml +0 -31
  22. package/frontend/App.svelte +0 -77
  23. package/frontend/app-environment.ts +0 -10
  24. package/frontend/app.css +0 -313
  25. package/frontend/components/auth/InvitePage.svelte +0 -215
  26. package/frontend/components/auth/LoginPage.svelte +0 -129
  27. package/frontend/components/auth/SetupPage.svelte +0 -1054
  28. package/frontend/components/chat/ChatInterface.svelte +0 -426
  29. package/frontend/components/chat/formatters/ErrorMessage.svelte +0 -57
  30. package/frontend/components/chat/formatters/MessageFormatter.svelte +0 -244
  31. package/frontend/components/chat/formatters/TextMessage.svelte +0 -383
  32. package/frontend/components/chat/formatters/Tools.svelte +0 -79
  33. package/frontend/components/chat/formatters/index.ts +0 -3
  34. package/frontend/components/chat/input/ChatInput.svelte +0 -492
  35. package/frontend/components/chat/input/components/ChatInputActions.svelte +0 -88
  36. package/frontend/components/chat/input/components/DragDropOverlay.svelte +0 -30
  37. package/frontend/components/chat/input/components/EditModeIndicator.svelte +0 -33
  38. package/frontend/components/chat/input/components/EngineModelPicker.svelte +0 -642
  39. package/frontend/components/chat/input/components/FileAttachmentPreview.svelte +0 -48
  40. package/frontend/components/chat/input/components/LoadingIndicator.svelte +0 -43
  41. package/frontend/components/chat/input/composables/use-animations.svelte.ts +0 -217
  42. package/frontend/components/chat/input/composables/use-chat-actions.svelte.ts +0 -152
  43. package/frontend/components/chat/input/composables/use-file-handling.svelte.ts +0 -216
  44. package/frontend/components/chat/input/composables/use-input-state.svelte.ts +0 -357
  45. package/frontend/components/chat/input/composables/use-textarea-resize.svelte.ts +0 -69
  46. package/frontend/components/chat/message/ChatMessage.svelte +0 -509
  47. package/frontend/components/chat/message/ChatMessages.svelte +0 -553
  48. package/frontend/components/chat/message/DateSeparator.svelte +0 -86
  49. package/frontend/components/chat/message/MessageBubble.svelte +0 -114
  50. package/frontend/components/chat/message/MessageHeader.svelte +0 -143
  51. package/frontend/components/chat/modal/DebugModal.svelte +0 -59
  52. package/frontend/components/chat/shared/index.ts +0 -2
  53. package/frontend/components/chat/shared/utils.ts +0 -116
  54. package/frontend/components/chat/tools/AgentTool.svelte +0 -96
  55. package/frontend/components/chat/tools/AskUserQuestionTool.svelte +0 -391
  56. package/frontend/components/chat/tools/BashOutputTool.svelte +0 -35
  57. package/frontend/components/chat/tools/BashTool.svelte +0 -51
  58. package/frontend/components/chat/tools/CustomMcpTool.svelte +0 -141
  59. package/frontend/components/chat/tools/EditTool.svelte +0 -48
  60. package/frontend/components/chat/tools/EnterPlanModeTool.svelte +0 -24
  61. package/frontend/components/chat/tools/ExitPlanModeTool.svelte +0 -29
  62. package/frontend/components/chat/tools/GlobTool.svelte +0 -51
  63. package/frontend/components/chat/tools/GrepTool.svelte +0 -90
  64. package/frontend/components/chat/tools/ListMcpResourcesTool.svelte +0 -31
  65. package/frontend/components/chat/tools/NotebookEditTool.svelte +0 -38
  66. package/frontend/components/chat/tools/ReadMcpResourceTool.svelte +0 -34
  67. package/frontend/components/chat/tools/ReadTool.svelte +0 -41
  68. package/frontend/components/chat/tools/SkillTool.svelte +0 -21
  69. package/frontend/components/chat/tools/TaskStopTool.svelte +0 -26
  70. package/frontend/components/chat/tools/TaskTool.svelte +0 -64
  71. package/frontend/components/chat/tools/TodoWriteTool.svelte +0 -75
  72. package/frontend/components/chat/tools/WebFetchTool.svelte +0 -35
  73. package/frontend/components/chat/tools/WebSearchTool.svelte +0 -84
  74. package/frontend/components/chat/tools/WriteTool.svelte +0 -33
  75. package/frontend/components/chat/tools/components/CodeBlock.svelte +0 -79
  76. package/frontend/components/chat/tools/components/DiffBlock.svelte +0 -408
  77. package/frontend/components/chat/tools/components/FileHeader.svelte +0 -59
  78. package/frontend/components/chat/tools/components/InfoLine.svelte +0 -19
  79. package/frontend/components/chat/tools/components/StatsBadges.svelte +0 -27
  80. package/frontend/components/chat/tools/components/TerminalCommand.svelte +0 -61
  81. package/frontend/components/chat/tools/components/index.ts +0 -7
  82. package/frontend/components/chat/tools/index.ts +0 -30
  83. package/frontend/components/chat/widgets/ContextIndicator.svelte +0 -186
  84. package/frontend/components/chat/widgets/FloatingTodoList.svelte +0 -367
  85. package/frontend/components/checkpoint/ConflictResolutionModal.svelte +0 -189
  86. package/frontend/components/checkpoint/TimelineModal.svelte +0 -447
  87. package/frontend/components/checkpoint/timeline/TimelineEdge.svelte +0 -26
  88. package/frontend/components/checkpoint/timeline/TimelineGraph.svelte +0 -87
  89. package/frontend/components/checkpoint/timeline/TimelineNode.svelte +0 -119
  90. package/frontend/components/checkpoint/timeline/TimelineVersionGroup.svelte +0 -59
  91. package/frontend/components/checkpoint/timeline/animation.ts +0 -168
  92. package/frontend/components/checkpoint/timeline/config.ts +0 -44
  93. package/frontend/components/checkpoint/timeline/graph-builder.ts +0 -304
  94. package/frontend/components/checkpoint/timeline/types.ts +0 -69
  95. package/frontend/components/checkpoint/timeline/utils.ts +0 -53
  96. package/frontend/components/common/display/AvatarBubble.svelte +0 -56
  97. package/frontend/components/common/display/Button.svelte +0 -71
  98. package/frontend/components/common/display/Card.svelte +0 -102
  99. package/frontend/components/common/display/Icon.svelte +0 -58
  100. package/frontend/components/common/display/PageTemplate.svelte +0 -76
  101. package/frontend/components/common/display/ProjectUserAvatars.svelte +0 -79
  102. package/frontend/components/common/display/ThemeToggle.svelte +0 -44
  103. package/frontend/components/common/editor/MonacoEditor.svelte +0 -583
  104. package/frontend/components/common/feedback/Alert.svelte +0 -139
  105. package/frontend/components/common/feedback/ConnectionBanner.svelte +0 -55
  106. package/frontend/components/common/feedback/LoadingScreen.svelte +0 -52
  107. package/frontend/components/common/feedback/LoadingSpinner.svelte +0 -48
  108. package/frontend/components/common/feedback/NotificationToast.svelte +0 -128
  109. package/frontend/components/common/feedback/RestartRequiredModal.svelte +0 -53
  110. package/frontend/components/common/feedback/UpdateBanner.svelte +0 -99
  111. package/frontend/components/common/form/Checkbox.svelte +0 -48
  112. package/frontend/components/common/form/FolderBrowser.svelte +0 -856
  113. package/frontend/components/common/form/Input.svelte +0 -72
  114. package/frontend/components/common/form/ModelSelector.svelte +0 -110
  115. package/frontend/components/common/form/Select.svelte +0 -98
  116. package/frontend/components/common/form/Textarea.svelte +0 -80
  117. package/frontend/components/common/lucide-icons.ts +0 -1642
  118. package/frontend/components/common/material-icons.ts +0 -1082
  119. package/frontend/components/common/media/MediaPreview.svelte +0 -187
  120. package/frontend/components/common/overlay/Dialog.svelte +0 -251
  121. package/frontend/components/common/overlay/Lightbox.svelte +0 -233
  122. package/frontend/components/common/overlay/Modal.svelte +0 -177
  123. package/frontend/components/common/overlay/ModalProvider.svelte +0 -28
  124. package/frontend/components/common/xterm/XTerm.svelte +0 -743
  125. package/frontend/components/common/xterm/index.ts +0 -16
  126. package/frontend/components/common/xterm/terminal-config.ts +0 -68
  127. package/frontend/components/common/xterm/types.ts +0 -32
  128. package/frontend/components/common/xterm/xterm-service.ts +0 -437
  129. package/frontend/components/files/FileNode.svelte +0 -327
  130. package/frontend/components/files/FileTree.svelte +0 -690
  131. package/frontend/components/files/FileViewer.svelte +0 -551
  132. package/frontend/components/files/SearchResults.svelte +0 -303
  133. package/frontend/components/git/BranchManager.svelte +0 -446
  134. package/frontend/components/git/ChangesSection.svelte +0 -196
  135. package/frontend/components/git/CommitForm.svelte +0 -128
  136. package/frontend/components/git/ConflictResolver.svelte +0 -158
  137. package/frontend/components/git/DiffViewer.svelte +0 -298
  138. package/frontend/components/git/FileChangeItem.svelte +0 -119
  139. package/frontend/components/git/GitButton.svelte +0 -33
  140. package/frontend/components/git/GitLog.svelte +0 -401
  141. package/frontend/components/git/GitModal.svelte +0 -80
  142. package/frontend/components/history/HistoryModal.svelte +0 -602
  143. package/frontend/components/history/HistoryView.svelte +0 -561
  144. package/frontend/components/index.ts +0 -34
  145. package/frontend/components/preview/browser/BrowserPreview.svelte +0 -558
  146. package/frontend/components/preview/browser/components/Canvas.svelte +0 -1523
  147. package/frontend/components/preview/browser/components/ConsolePanel.svelte +0 -757
  148. package/frontend/components/preview/browser/components/Container.svelte +0 -507
  149. package/frontend/components/preview/browser/components/ContextMenu.svelte +0 -236
  150. package/frontend/components/preview/browser/components/SelectDropdown.svelte +0 -224
  151. package/frontend/components/preview/browser/components/Toolbar.svelte +0 -358
  152. package/frontend/components/preview/browser/components/VirtualCursor.svelte +0 -36
  153. package/frontend/components/preview/browser/core/cleanup.svelte.ts +0 -155
  154. package/frontend/components/preview/browser/core/coordinator.svelte.ts +0 -885
  155. package/frontend/components/preview/browser/core/interactions.svelte.ts +0 -113
  156. package/frontend/components/preview/browser/core/mcp-handlers.svelte.ts +0 -331
  157. package/frontend/components/preview/browser/core/native-ui-handlers.svelte.ts +0 -391
  158. package/frontend/components/preview/browser/core/stream-handler.svelte.ts +0 -288
  159. package/frontend/components/preview/browser/core/tab-manager.svelte.ts +0 -210
  160. package/frontend/components/preview/browser/core/tab-operations.svelte.ts +0 -241
  161. package/frontend/components/preview/index.ts +0 -2
  162. package/frontend/components/settings/SettingsModal.svelte +0 -268
  163. package/frontend/components/settings/SettingsView.svelte +0 -54
  164. package/frontend/components/settings/account/AccountSettings.svelte +0 -5
  165. package/frontend/components/settings/admin/InviteManagement.svelte +0 -239
  166. package/frontend/components/settings/admin/UserManagement.svelte +0 -127
  167. package/frontend/components/settings/appearance/AppearanceSettings.svelte +0 -104
  168. package/frontend/components/settings/appearance/LayoutPresetSettings.svelte +0 -160
  169. package/frontend/components/settings/appearance/LayoutPreview.svelte +0 -76
  170. package/frontend/components/settings/engines/AIEnginesSettings.svelte +0 -917
  171. package/frontend/components/settings/general/AdvancedSettings.svelte +0 -193
  172. package/frontend/components/settings/general/AuthModeSettings.svelte +0 -229
  173. package/frontend/components/settings/general/DataManagementSettings.svelte +0 -89
  174. package/frontend/components/settings/general/GeneralSettings.svelte +0 -20
  175. package/frontend/components/settings/general/UpdateSettings.svelte +0 -130
  176. package/frontend/components/settings/git/GitSettings.svelte +0 -392
  177. package/frontend/components/settings/model/EngineModelPicker.svelte +0 -284
  178. package/frontend/components/settings/model/ModelSettings.svelte +0 -240
  179. package/frontend/components/settings/notifications/NotificationSettings.svelte +0 -205
  180. package/frontend/components/settings/security/SecuritySettings.svelte +0 -10
  181. package/frontend/components/settings/system/SystemSettings.svelte +0 -10
  182. package/frontend/components/settings/tunnel/TunnelSettings.svelte +0 -1060
  183. package/frontend/components/settings/user/UserSettings.svelte +0 -270
  184. package/frontend/components/terminal/Terminal.svelte +0 -338
  185. package/frontend/components/terminal/TerminalTabs.svelte +0 -88
  186. package/frontend/components/terminal/TerminalView.svelte +0 -55
  187. package/frontend/components/tunnel/TunnelActive.svelte +0 -218
  188. package/frontend/components/tunnel/TunnelButton.svelte +0 -60
  189. package/frontend/components/tunnel/TunnelInactive.svelte +0 -260
  190. package/frontend/components/tunnel/TunnelModal.svelte +0 -101
  191. package/frontend/components/tunnel/TunnelQRCode.svelte +0 -49
  192. package/frontend/components/workspace/DesktopNavigator.svelte +0 -445
  193. package/frontend/components/workspace/MobileNavigator.svelte +0 -427
  194. package/frontend/components/workspace/PanelContainer.svelte +0 -100
  195. package/frontend/components/workspace/PanelHeader.svelte +0 -664
  196. package/frontend/components/workspace/ViewMenu.svelte +0 -146
  197. package/frontend/components/workspace/WorkspaceLayout.svelte +0 -199
  198. package/frontend/components/workspace/layout/DesktopLayout.svelte +0 -15
  199. package/frontend/components/workspace/layout/MobileLayout.svelte +0 -17
  200. package/frontend/components/workspace/layout/split-pane/Container.svelte +0 -42
  201. package/frontend/components/workspace/layout/split-pane/Handle.svelte +0 -85
  202. package/frontend/components/workspace/layout/split-pane/Layout.svelte +0 -62
  203. package/frontend/components/workspace/panels/ChatPanel.svelte +0 -282
  204. package/frontend/components/workspace/panels/FilesPanel.svelte +0 -1376
  205. package/frontend/components/workspace/panels/GitPanel.svelte +0 -1601
  206. package/frontend/components/workspace/panels/PreviewPanel.svelte +0 -153
  207. package/frontend/components/workspace/panels/TerminalPanel.svelte +0 -73
  208. package/frontend/main.ts +0 -17
  209. package/frontend/services/chat/chat.service.ts +0 -975
  210. package/frontend/services/chat/index.ts +0 -7
  211. package/frontend/services/favicon.service.ts +0 -103
  212. package/frontend/services/notification/global-stream-monitor.ts +0 -120
  213. package/frontend/services/notification/index.ts +0 -8
  214. package/frontend/services/notification/push.service.ts +0 -144
  215. package/frontend/services/notification/sound.service.ts +0 -127
  216. package/frontend/services/preview/browser/browser-console.service.ts +0 -61
  217. package/frontend/services/preview/browser/browser-webcodecs.service.ts +0 -1643
  218. package/frontend/services/preview/browser/mcp-integration.svelte.ts +0 -67
  219. package/frontend/services/preview/index.ts +0 -23
  220. package/frontend/services/project/index.ts +0 -8
  221. package/frontend/services/project/status.service.ts +0 -170
  222. package/frontend/services/snapshot/snapshot.service.ts +0 -86
  223. package/frontend/services/terminal/background/index.ts +0 -130
  224. package/frontend/services/terminal/background/session-restore.ts +0 -274
  225. package/frontend/services/terminal/background/stream-manager.ts +0 -286
  226. package/frontend/services/terminal/index.ts +0 -14
  227. package/frontend/services/terminal/persistence.service.ts +0 -260
  228. package/frontend/services/terminal/project.service.ts +0 -1004
  229. package/frontend/services/terminal/session.service.ts +0 -364
  230. package/frontend/services/terminal/terminal.service.ts +0 -379
  231. package/frontend/stores/core/app.svelte.ts +0 -296
  232. package/frontend/stores/core/files.svelte.ts +0 -87
  233. package/frontend/stores/core/presence.svelte.ts +0 -128
  234. package/frontend/stores/core/projects.svelte.ts +0 -325
  235. package/frontend/stores/core/sessions.svelte.ts +0 -452
  236. package/frontend/stores/features/auth.svelte.ts +0 -336
  237. package/frontend/stores/features/claude-accounts.svelte.ts +0 -58
  238. package/frontend/stores/features/models.svelte.ts +0 -89
  239. package/frontend/stores/features/settings.svelte.ts +0 -151
  240. package/frontend/stores/features/terminal.svelte.ts +0 -747
  241. package/frontend/stores/features/tunnel-config.svelte.ts +0 -205
  242. package/frontend/stores/features/tunnel.svelte.ts +0 -277
  243. package/frontend/stores/features/user.svelte.ts +0 -54
  244. package/frontend/stores/ui/chat-input.svelte.ts +0 -57
  245. package/frontend/stores/ui/chat-model.svelte.ts +0 -61
  246. package/frontend/stores/ui/connection.svelte.ts +0 -40
  247. package/frontend/stores/ui/dialog.svelte.ts +0 -59
  248. package/frontend/stores/ui/edit-mode.svelte.ts +0 -214
  249. package/frontend/stores/ui/notification.svelte.ts +0 -169
  250. package/frontend/stores/ui/settings-modal.svelte.ts +0 -116
  251. package/frontend/stores/ui/theme.svelte.ts +0 -179
  252. package/frontend/stores/ui/todo-panel.svelte.ts +0 -39
  253. package/frontend/stores/ui/update.svelte.ts +0 -159
  254. package/frontend/stores/ui/workspace.svelte.ts +0 -798
  255. package/frontend/utils/chat/date-separator.ts +0 -39
  256. package/frontend/utils/chat/message-grouper.ts +0 -329
  257. package/frontend/utils/chat/message-processor.ts +0 -169
  258. package/frontend/utils/chat/tool-handler.ts +0 -287
  259. package/frontend/utils/chat/virtual-scroll.svelte.ts +0 -142
  260. package/frontend/utils/click-outside.ts +0 -20
  261. package/frontend/utils/context-manager.ts +0 -55
  262. package/frontend/utils/file-icon-mappings.ts +0 -769
  263. package/frontend/utils/file-type.ts +0 -68
  264. package/frontend/utils/folder-icon-mappings.ts +0 -1030
  265. package/frontend/utils/git-status.ts +0 -68
  266. package/frontend/utils/native-ui.ts +0 -73
  267. package/frontend/utils/platform.ts +0 -113
  268. package/frontend/utils/port-check.ts +0 -65
  269. package/frontend/utils/preview-constants.ts +0 -45
  270. package/frontend/utils/terminal-formatter.ts +0 -207
  271. package/frontend/utils/theme.ts +0 -6
  272. package/frontend/utils/tree-visualizer.ts +0 -320
  273. package/frontend/utils/ws.ts +0 -90
  274. package/scripts/dev.ts +0 -46
  275. package/scripts/generate-icons.ts +0 -87
  276. package/svelte.config.js +0 -20
  277. package/tsconfig.json +0 -41
  278. package/vite.config.ts +0 -51
  279. /package/{static → dist}/audio/notification.ogg +0 -0
  280. /package/{static → dist}/favicon.svg +0 -0
  281. /package/{static → dist}/fonts/dm-sans/dm-sans-italic-latin-ext.woff2 +0 -0
  282. /package/{static → dist}/fonts/dm-sans/dm-sans-italic-latin.woff2 +0 -0
  283. /package/{static → dist}/fonts/dm-sans/dm-sans-normal-latin-ext.woff2 +0 -0
  284. /package/{static → dist}/fonts/dm-sans/dm-sans-normal-latin.woff2 +0 -0
  285. /package/{static → dist}/fonts/dm-sans.css +0 -0
  286. /package/{static → dist}/manifest.json +0 -0
@@ -1,975 +0,0 @@
1
- /**
2
- * WebSocket-based Chat Service
3
- *
4
- * Modern WebSocket implementation for real-time chat communication
5
- * Replaces the old SSE-based chat service
6
- *
7
- * Key features:
8
- * - Sequence-based deduplication to prevent duplicate messages
9
- * - Stream reconnection after browser refresh / project switch
10
- * - Robust cancel that works even after refresh
11
- * - Proper presence synchronization
12
- */
13
-
14
- import { appState, updateSessionProcessState } from '$frontend/stores/core/app.svelte';
15
- import type { SessionProcessState } from '$frontend/stores/core/app.svelte';
16
- import { chatModelState } from '$frontend/stores/ui/chat-model.svelte';
17
- import { projectState } from '$frontend/stores/core/projects.svelte';
18
- import { sessionState, setCurrentSession, createSession, updateSession } from '$frontend/stores/core/sessions.svelte';
19
- import { addNotification } from '$frontend/stores/ui/notification.svelte';
20
- import { userStore } from '$frontend/stores/features/user.svelte';
21
- import { SDK_CONFIG, parseModelId } from '$shared/constants/engines';
22
- import type { ChatServiceOptions } from '$shared/types/messaging';
23
- import { buildMetadataFromTransport } from '$shared/utils/message-formatter';
24
- import { debug } from '$shared/utils/logger';
25
- import ws from '$frontend/utils/ws';
26
-
27
- /**
28
- * Tools that block the SDK waiting for user interaction.
29
- * When these tools appear in an assistant message without a result,
30
- * and the stream is active, the chat status switches to "waiting for input".
31
- * Extend this list for future interactive tools.
32
- */
33
- const INTERACTIVE_TOOLS = new Set(['AskUserQuestion']);
34
-
35
- class ChatService {
36
- private activeProcessId: string | null = null;
37
- private streamCompleted: boolean = false;
38
- private currentSessionId: string | null = null;
39
- private lastEventSeq = new Map<string, number>(); // Sequence-based deduplication
40
- private cancelledProcessIds = new Set<string>(); // Track ALL cancelled streams to ignore late events
41
- private reconnected: boolean = false; // Whether we've reconnected to an active stream
42
- private cancelSafetyTimer: ReturnType<typeof setTimeout> | null = null;
43
-
44
- static loadingTexts: string[] = [
45
- 'thinking', 'processing', 'analyzing', 'calculating', 'computing',
46
- 'strategizing', 'learningpatterns', 'adaptingmodels', 'evaluatingoptions',
47
- 'executingplans', 'simulatingscenarios', 'predictingoutcomes', 'planningactions',
48
- 'processinginputs', 'optimizing', 'generatingresponses', 'refininglogic',
49
- 'validatingoutputs', 'modulatingresponse', 'updatingmemory', 'recognizingpatterns',
50
- 'switchingcontext', 'allocatingresources', 'prioritizingtasks',
51
- 'developingawareness', 'buildingstrategies', 'assessingscenarios',
52
- 'bootingreasoning', 'triggeringaction', 'deployinglogic', 'synthesizinginformation',
53
- 'maintainingstate', 'updating', 'reflecting', 'syncinglogic',
54
- 'connectingdots', 'compilingideas', 'brainstorming', 'schedulingtasks'
55
- ].map(text => text + '...');
56
-
57
- static placeholderTexts: string[] = [
58
- // Creating new projects
59
- 'Create a full-stack e-commerce platform with Next.js, Stripe, and PostgreSQL',
60
- 'Build a real-time chat application using Socket.io with room support and typing indicators',
61
- 'Create a SaaS dashboard with user management, billing, and analytics',
62
- 'Build a REST API with authentication, rate limiting, and Swagger documentation',
63
- 'Create a CLI tool in TypeScript that scaffolds new projects with custom templates',
64
- // Debugging & fixing
65
- 'Debug a memory leak in a Node.js service causing it to crash every 24 hours',
66
- 'Fix race conditions in a concurrent queue processor causing duplicate jobs',
67
- 'Fix a CORS issue blocking requests between a frontend and backend on different origins',
68
- 'Fix broken JWT refresh logic that logs users out unexpectedly',
69
- 'Fix flaky tests that pass locally but fail randomly in CI',
70
- // Code review & refactoring
71
- 'Refactor a 1000-line monolithic function into clean, testable modules',
72
- 'Convert a class-based React codebase to functional components with hooks',
73
- 'Migrate a JavaScript project to TypeScript with strict mode enabled',
74
- 'Refactor database queries to use an ORM with proper migrations',
75
- 'Clean up and standardize error handling across an entire Express application',
76
- // Writing tests
77
- 'Write unit tests for a payment processing module with 100% coverage',
78
- 'Add end-to-end tests using Playwright for a multi-step checkout flow',
79
- 'Set up integration tests for a REST API using a real test database',
80
- 'Write property-based tests to find edge cases in a data validation library',
81
- 'Set up test coverage reporting and enforce a minimum threshold in CI',
82
- // Performance & optimization
83
- 'Optimize a slow PostgreSQL query that runs 10 seconds on a 5M-row table',
84
- 'Implement Redis caching to reduce database load by 80%',
85
- 'Reduce bundle size of a React app from 4MB to under 500KB',
86
- 'Profile and optimize a Python data pipeline processing 1M records per hour',
87
- 'Add lazy loading and virtualization to a list rendering 10,000 items',
88
- // Architecture & design
89
- 'Design a scalable event-driven architecture using Kafka for a high-traffic app',
90
- 'Plan a migration from a monolith to microservices without downtime',
91
- 'Design a multi-tenant SaaS architecture with data isolation per customer',
92
- 'Create an authentication system supporting SSO, OAuth, and MFA',
93
- 'Architect a real-time notification system using WebSockets and a message queue',
94
- // DevOps & infrastructure
95
- 'Write a Dockerfile and docker-compose setup for a full-stack app with hot reload',
96
- 'Set up a GitHub Actions CI/CD pipeline with testing, linting, and auto-deploy',
97
- 'Configure Nginx as a reverse proxy with SSL termination and load balancing',
98
- 'Create Terraform scripts to provision a production-ready AWS infrastructure',
99
- 'Set up monitoring and alerting using Prometheus and Grafana',
100
- // AI & data
101
- 'Build a RAG pipeline using LangChain, embeddings, and a vector database',
102
- 'Create a sentiment analysis API using a fine-tuned transformer model',
103
- 'Build a data scraper that extracts and structures product data at scale',
104
- 'Implement a recommendation engine using collaborative filtering',
105
- 'Create a real-time data dashboard ingesting from multiple streaming sources',
106
- ];
107
-
108
- constructor() {
109
- this.setupWebSocketHandlers();
110
- }
111
-
112
- /**
113
- * Update process state for a session.
114
- * Writes to both the per-session map (for multi-session support)
115
- * and global convenience flags (for backward-compatible single-session components).
116
- *
117
- * @param update - Partial state to merge
118
- * @param sessionId - Override session ID (defaults to this.currentSessionId or current session)
119
- */
120
- private setProcessState(
121
- update: Partial<SessionProcessState>,
122
- sessionId?: string | null
123
- ): void {
124
- const resolvedId = sessionId ?? this.currentSessionId ?? sessionState.currentSession?.id;
125
- if (resolvedId) {
126
- updateSessionProcessState(resolvedId, update);
127
- }
128
- // Always sync to global convenience flags
129
- if ('isLoading' in update) appState.isLoading = update.isLoading!;
130
- if ('isWaitingInput' in update) appState.isWaitingInput = update.isWaitingInput!;
131
- if ('isCancelling' in update) appState.isCancelling = update.isCancelling!;
132
- if ('isRestoring' in update) appState.isRestoring = update.isRestoring!;
133
- if ('error' in update && update.error !== undefined) appState.error = update.error;
134
- }
135
-
136
- /**
137
- * Check if event should be skipped (sequence-based deduplication)
138
- */
139
- private shouldSkipEvent(processId: string, seq: number | undefined): boolean {
140
- if (seq === undefined || seq === null) return false;
141
-
142
- const lastSeq = this.lastEventSeq.get(processId) || 0;
143
- if (seq <= lastSeq) {
144
- // Skip duplicate
145
- return true;
146
- }
147
-
148
- this.lastEventSeq.set(processId, seq);
149
- return false;
150
- }
151
-
152
- /**
153
- * Setup WebSocket event handlers
154
- */
155
- private setupWebSocketHandlers(): void {
156
- // Session available event - reset stream state if we were streaming from the old session.
157
- // With session-scoped routing, this is mostly a safety measure.
158
- ws.on('sessions:session-available', () => {
159
- // No-op: with chat session rooms, events are already scoped.
160
- // Users stay in their current session until they explicitly switch.
161
- });
162
-
163
- // Connection event - received by ALL users in the project
164
- ws.on('chat:connection', (data) => {
165
- if (this.shouldSkipEvent(data.processId, data.seq)) return;
166
- // Ignore events from a locally cancelled stream
167
- if (data.processId && this.cancelledProcessIds.has(data.processId)) return;
168
-
169
- this.activeProcessId = data.processId;
170
- this.streamCompleted = false;
171
- });
172
-
173
- // Message event
174
- ws.on('chat:message', (data) => {
175
- if (this.shouldSkipEvent(data.processId, data.seq)) return;
176
- // Ignore events from a locally cancelled stream
177
- if (data.processId && this.cancelledProcessIds.has(data.processId)) return;
178
-
179
- this.handleMessageEvent(data);
180
- });
181
-
182
- // Partial message event (streaming)
183
- ws.on('chat:partial', (data) => {
184
- if (this.shouldSkipEvent(data.processId, data.seq)) return;
185
- // Ignore events from a locally cancelled stream
186
- if (data.processId && this.cancelledProcessIds.has(data.processId)) return;
187
-
188
- this.handlePartialEvent(data);
189
- });
190
-
191
- // Notification event
192
- ws.on('chat:notification', (data) => {
193
- // Notifications don't have processId, use a global key
194
- if (this.shouldSkipEvent('notification', data.seq)) return;
195
-
196
- if (data.notification) {
197
- const notif = data.notification;
198
- addNotification({
199
- type: notif.type as any,
200
- title: notif.title,
201
- message: notif.message,
202
- duration: notif.type === 'warning' ? 7000 : 5000
203
- });
204
- }
205
- });
206
-
207
- // Complete event
208
- ws.on('chat:complete', async (data) => {
209
- if (this.shouldSkipEvent(data.processId, data.seq)) return;
210
- // Ignore late events from a locally cancelled stream
211
- if (data.processId && this.cancelledProcessIds.has(data.processId)) return;
212
-
213
- this.streamCompleted = true;
214
- this.reconnected = false;
215
- this.clearCancelSafetyTimer();
216
- this.setProcessState({ isLoading: false, isWaitingInput: false, isCancelling: false });
217
-
218
- // Mark any tool_use blocks that never got a tool_result
219
- this.markInterruptedTools();
220
-
221
- // Stream completed successfully — all old cancelled streams' events
222
- // have definitely been delivered by now, so clear the blacklist.
223
- this.cancelledProcessIds.clear();
224
-
225
- // Don't reload messages - they're already added via chat:message events
226
- // Reloading would cause duplicates
227
-
228
- // Notifications handled by GlobalStreamMonitor via chat:stream-finished
229
- });
230
-
231
- // Cancelled event - broadcast to ALL collaborators when any user cancels
232
- ws.on('chat:cancelled', async (data) => {
233
- // Track the cancelled processId so late-arriving events are blocked.
234
- // This handles the case where a collaborator initiated the cancel
235
- // (so our local cancelRequest was not called).
236
- if (data.processId) {
237
- this.cancelledProcessIds.add(data.processId);
238
- }
239
- this.streamCompleted = true;
240
- this.reconnected = false;
241
- this.activeProcessId = null;
242
- this.clearCancelSafetyTimer();
243
- // Don't clear isCancelling here — it causes a race with presence.
244
- // The chat:cancelled WS event arrives before broadcastPresence() updates,
245
- // so clearing isCancelling lets the presence $effect re-enable isLoading
246
- // (because hasActiveForSession is still true). The presence $effect will
247
- // clear isCancelling once the stream is actually gone from presence.
248
- this.setProcessState({ isLoading: false, isWaitingInput: false });
249
-
250
- // Mark any tool_use blocks that never got a tool_result
251
- this.markInterruptedTools();
252
-
253
- // Notifications handled by GlobalStreamMonitor via chat:stream-finished
254
- });
255
-
256
- // Error event
257
- ws.on('chat:error', async (data) => {
258
- if (this.shouldSkipEvent(data.processId, data.seq)) return;
259
- if (this.streamCompleted) return;
260
- // Ignore late error events from a locally cancelled stream
261
- if (data.processId && this.cancelledProcessIds.has(data.processId)) return;
262
-
263
- // Mark completed immediately to block any duplicate error events that may arrive
264
- // (e.g. from multiple subscriptions or late-arriving events with different processId/seq)
265
- this.streamCompleted = true;
266
- this.reconnected = false;
267
- this.setProcessState({ isLoading: false, isWaitingInput: false, isCancelling: false });
268
-
269
- // Mark any tool_use blocks that never got a tool_result
270
- this.markInterruptedTools();
271
-
272
- // Don't show notification for cancel-triggered errors
273
- if (data.error === 'Stream cancelled') return;
274
-
275
- // Remove any remaining stream_event messages (streaming placeholders that won't be finalized).
276
- // The actual error bubble is now emitted as a chat:message from the backend and saved to DB,
277
- // so it persists across browser refresh. No need to inject a synthetic bubble here.
278
- for (let i = sessionState.messages.length - 1; i >= 0; i--) {
279
- const msg = sessionState.messages[i] as any;
280
- if (msg.type === 'stream_event') {
281
- sessionState.messages.splice(i, 1);
282
- }
283
- }
284
-
285
- addNotification({
286
- type: 'error',
287
- title: 'AI Engine Error',
288
- message: data.error,
289
- duration: 5000
290
- });
291
- });
292
- }
293
-
294
- /**
295
- * Reconnect to an active stream after browser refresh or project switch.
296
- * This re-subscribes the connection to receive live stream events.
297
- * Called from catchupActiveStream in ChatInput.
298
- */
299
- reconnectToStream(chatSessionId: string, processId: string): void {
300
- debug.log('chat', 'Reconnecting to active stream:', { chatSessionId, processId });
301
-
302
- // Set up local state so events are processed and cancel works
303
- this.activeProcessId = processId;
304
- this.currentSessionId = chatSessionId;
305
- this.streamCompleted = false;
306
- this.cancelledProcessIds.clear();
307
- this.reconnected = true;
308
-
309
- // Tell backend to re-subscribe this connection to the stream
310
- ws.emit('chat:reconnect', {
311
- chatSessionId
312
- });
313
- }
314
-
315
- /**
316
- * Send a message using WebSocket
317
- */
318
- async sendMessage(
319
- message: string,
320
- options: ChatServiceOptions = {}
321
- ): Promise<void> {
322
- if ((!message.trim() && !options.attachedFiles?.length) || appState.isLoading) return;
323
-
324
- // Check if project is selected
325
- if (!projectState.currentProject) {
326
- addNotification({
327
- type: 'warning',
328
- title: 'No Project Selected',
329
- message: 'Please select a project from the sidebar before sending messages',
330
- duration: 3000
331
- });
332
- return;
333
- }
334
-
335
- const userMessage = message.trim();
336
-
337
- // Create a new session if none exists
338
- if (!sessionState.currentSession) {
339
- const newSession = await createSession(
340
- projectState.currentProject.id,
341
- 'New Chat Session'
342
- );
343
- if (newSession) {
344
- await setCurrentSession(newSession);
345
- } else {
346
- addNotification({
347
- type: 'error',
348
- title: 'Session Creation Failed',
349
- message: 'Failed to create chat session. Please try again.',
350
- duration: 5000
351
- });
352
- return;
353
- }
354
- }
355
-
356
- // Ensure we have a valid session before proceeding
357
- if (!sessionState.currentSession?.id) {
358
- addNotification({
359
- type: 'error',
360
- title: 'No Valid Session',
361
- message: 'No valid chat session available. Please refresh and try again.',
362
- duration: 5000
363
- });
364
- return;
365
- }
366
-
367
- // Set loading state
368
- this.streamCompleted = false;
369
- this.reconnected = false;
370
- this.currentSessionId = sessionState.currentSession.id;
371
- this.setProcessState({ isLoading: true, isWaitingInput: false, isCancelling: false });
372
- // DON'T clear cancelledProcessIds — late events from previously cancelled
373
- // streams must still be blocked. The set is cleared on stream complete.
374
- // Clear sequence tracking for new stream
375
- this.lastEventSeq.clear();
376
-
377
- // Clean up stale stream_events from any previous cancelled streams.
378
- // These linger because cancel doesn't remove them, and they cause
379
- // wrong insertion positions for new reasoning/text streams.
380
- this.cleanupStreamEvents();
381
-
382
- try {
383
- // Build message content (text + optional file attachments)
384
- let messageContent: any = userMessage;
385
- if (options.attachedFiles && options.attachedFiles.length > 0) {
386
- const contentBlocks: any[] = [];
387
- // Add file attachments first
388
- for (const file of options.attachedFiles) {
389
- if (file.type === 'image') {
390
- contentBlocks.push({
391
- type: 'image',
392
- source: { type: 'base64', media_type: file.mediaType, data: file.data }
393
- });
394
- } else {
395
- contentBlocks.push({
396
- type: 'document',
397
- source: { type: 'base64', media_type: file.mediaType, data: file.data },
398
- title: file.fileName
399
- });
400
- }
401
- }
402
- // Add text block
403
- if (userMessage) {
404
- contentBlocks.push({ type: 'text', text: userMessage });
405
- }
406
- messageContent = contentBlocks;
407
- }
408
-
409
- // Create SDKUserMessage format for prompt
410
- const sdkUserMessage = {
411
- type: 'user' as const,
412
- uuid: crypto.randomUUID(),
413
- session_id: sessionState.currentSession.id,
414
- parent_tool_use_id: null,
415
- message: {
416
- role: 'user' as const,
417
- content: messageContent
418
- }
419
- };
420
-
421
- // Optimistic UI: show user message immediately (before server confirms)
422
- const optimisticMessage = {
423
- ...sdkUserMessage,
424
- _optimistic: true,
425
- metadata: buildMetadataFromTransport({
426
- timestamp: new Date().toISOString(),
427
- sender_id: userStore.currentUser?.id || null,
428
- sender_name: userStore.currentUser?.name || null,
429
- })
430
- };
431
- (sessionState.messages as any[]).push(optimisticMessage);
432
-
433
- // Parse engine and model from the local chat model state (isolated from Settings)
434
- const { engine, modelId } = parseModelId(chatModelState.model);
435
-
436
- // Capture selected engine/model/account before sending
437
- const selectedEngine = chatModelState.engine || engine;
438
- const selectedModel = chatModelState.model;
439
- const selectedAccountId = chatModelState.claudeAccountId;
440
-
441
- // Send WebSocket message to start streaming
442
- ws.emit('chat:stream', {
443
- sessionId: crypto.randomUUID(), // ephemeral session ID for this stream
444
- chatSessionId: sessionState.currentSession.id,
445
- projectPath: projectState.currentProject?.path || '',
446
- prompt: sdkUserMessage,
447
- messages: sessionState.messages.filter((msg: any) => !msg._optimistic).map(msg => {
448
- // Convert SDKMessage to API format
449
- if (msg.type === 'user' && 'message' in msg) {
450
- return {
451
- role: msg.message.role,
452
- content: typeof msg.message.content === 'string' ? msg.message.content : JSON.stringify(msg.message.content)
453
- };
454
- } else if (msg.type === 'assistant' && 'message' in msg) {
455
- return {
456
- role: msg.message.role,
457
- content: Array.isArray(msg.message.content)
458
- ? msg.message.content.map(c => c.type === 'text' ? c.text : JSON.stringify(c)).join(' ')
459
- : JSON.stringify(msg.message.content)
460
- };
461
- }
462
- return {
463
- role: 'assistant',
464
- content: ''
465
- };
466
- }).filter(msg => msg.content),
467
- engine: selectedEngine,
468
- model: modelId,
469
- temperature: SDK_CONFIG.DEFAULT_TEMPERATURE,
470
- senderId: userStore.currentUser?.id,
471
- senderName: userStore.currentUser?.name,
472
- ...(selectedEngine === 'claude-code' && selectedAccountId !== null && { claudeAccountId: selectedAccountId }),
473
- });
474
-
475
- // Persist engine/model to frontend session state immediately.
476
- // Backend also saves to DB (for refresh/project-switch restore),
477
- // but we update the frontend state here so the $effect in
478
- // EngineModelPicker can see it without a server round-trip.
479
- // IMPORTANT: Use updateSession() to update BOTH sessionState.currentSession
480
- // AND sessionState.sessions[] array. A direct spread on currentSession
481
- // creates a new object, leaving sessions[] stale — causing the model
482
- // picker to lose the selection when switching projects and back.
483
- if (sessionState.currentSession) {
484
- updateSession({
485
- ...sessionState.currentSession,
486
- engine: selectedEngine,
487
- model: selectedModel,
488
- ...(selectedEngine === 'claude-code' && selectedAccountId !== null && { claude_account_id: selectedAccountId }),
489
- });
490
- }
491
-
492
- } catch (error) {
493
- this.handleError(error as Error, options);
494
- }
495
- }
496
-
497
- /**
498
- * Cancel the current request - works for ANY collaborator, not just the sender
499
- * Also works after browser refresh since it uses sessionState as fallback
500
- */
501
- cancelRequest(): void {
502
- // Use currentSessionId (set by sender) OR sessionState (available to all collaborators)
503
- const chatSessionId = this.currentSessionId || sessionState.currentSession?.id;
504
-
505
- if (chatSessionId) {
506
- ws.emit('chat:cancel', {
507
- sessionId: crypto.randomUUID(),
508
- chatSessionId
509
- });
510
- }
511
-
512
- // Track cancelled processId so late-arriving events are ignored.
513
- // Use a Set to track ALL cancelled streams (not just the last one),
514
- // preventing late events from any previously cancelled stream from leaking through.
515
- if (this.activeProcessId) {
516
- this.cancelledProcessIds.add(this.activeProcessId);
517
- }
518
- this.activeProcessId = null;
519
- this.currentSessionId = null;
520
- this.streamCompleted = true;
521
- this.reconnected = false;
522
- // Update per-session map with captured ID (before it was nulled above)
523
- // and global flags — cancel sets isCancelling=true to prevent presence re-enabling
524
- this.setProcessState({ isLoading: false, isWaitingInput: false, isCancelling: true }, chatSessionId);
525
-
526
- // Convert stream_events to finalized assistant messages on cancel.
527
- // This preserves partial reasoning/text that was visible to the user.
528
- // Empty stream_events are removed. The backend saves partial text to DB
529
- // independently, so on refresh the DB version takes over.
530
- this.finalizeStreamEvents();
531
-
532
- // Safety timeout: if backend events (chat:cancelled + presence update) don't
533
- // arrive within 10 seconds, force-clear isCancelling to prevent infinite loader.
534
- // This catches edge cases: WS disconnect during cancel, engine.cancel() timeout,
535
- // or race conditions between presence update and chat:cancelled event ordering.
536
- this.clearCancelSafetyTimer();
537
- this.cancelSafetyTimer = setTimeout(() => {
538
- this.cancelSafetyTimer = null;
539
- if (appState.isCancelling) {
540
- debug.warn('chat', 'Cancel safety timeout: force-clearing isCancelling after 10s');
541
- this.setProcessState({ isCancelling: false, isLoading: false }, chatSessionId);
542
- }
543
- }, 10000);
544
- }
545
-
546
- /**
547
- * Clear the cancel safety timer (called when cancel completes normally)
548
- */
549
- private clearCancelSafetyTimer(): void {
550
- if (this.cancelSafetyTimer) {
551
- clearTimeout(this.cancelSafetyTimer);
552
- this.cancelSafetyTimer = null;
553
- }
554
- }
555
-
556
- /**
557
- * Reset stream state when switching sessions (e.g. collaborator receiving new-chat).
558
- * Blocks all stale events from the old stream.
559
- */
560
- resetForSessionSwitch(): void {
561
- if (this.activeProcessId) {
562
- this.cancelledProcessIds.add(this.activeProcessId);
563
- }
564
- this.activeProcessId = null;
565
- this.currentSessionId = null;
566
- this.streamCompleted = true;
567
- this.reconnected = false;
568
- this.lastEventSeq.clear();
569
- appState.isLoading = false;
570
- appState.isWaitingInput = false;
571
- appState.isCancelling = false;
572
- }
573
-
574
- /**
575
- * Handle message events from stream
576
- */
577
- private handleMessageEvent(data: any): void {
578
- const sdkMessage = data.message;
579
-
580
- // Early return if no message
581
- if (!sdkMessage) return;
582
-
583
- // Ignore messages from a completed/cancelled stream
584
- if (this.streamCompleted) return;
585
-
586
- // Early return if no valid session
587
- if (!sessionState.currentSession?.id) {
588
- return;
589
- }
590
-
591
- // If this is a user message from server, replace the optimistic message
592
- if (sdkMessage.type === 'user' && sdkMessage.message?.role === 'user') {
593
- const optimisticIndex = sessionState.messages.findIndex(
594
- (m: any) => m._optimistic && m.type === 'user' && m.uuid === sdkMessage.uuid
595
- );
596
- if (optimisticIndex !== -1) {
597
- // Replace optimistic with server-confirmed message
598
- const confirmedMessage = {
599
- ...sdkMessage,
600
- metadata: buildMetadataFromTransport(data)
601
- };
602
- sessionState.messages[optimisticIndex] = confirmedMessage;
603
- return;
604
- }
605
- }
606
-
607
- // If this is an assistant message, replace the matching streaming message
608
- if (sdkMessage.message?.role === 'assistant') {
609
- const isReasoning = sdkMessage.metadata?.reasoning === true;
610
- if (isReasoning) {
611
- // Replace reasoning stream_event IN PLACE to preserve message order
612
- for (let i = sessionState.messages.length - 1; i >= 0; i--) {
613
- const msg = sessionState.messages[i] as any;
614
- if (msg.type === 'stream_event' && msg.metadata?.reasoning) {
615
- const messageFormatter = {
616
- ...sdkMessage,
617
- metadata: buildMetadataFromTransport({ ...data, reasoning: true })
618
- };
619
- sessionState.messages[i] = messageFormatter;
620
- return; // Already replaced in-place, skip push below
621
- }
622
- }
623
- // If no reasoning stream_event found, fall through to push at end
624
- } else {
625
- // Replace text stream_event IN PLACE to preserve message position
626
- // (same approach as reasoning — prevents visual displacement)
627
- for (let i = sessionState.messages.length - 1; i >= 0; i--) {
628
- const msg = sessionState.messages[i] as any;
629
- if (msg.type === 'stream_event' && !msg.metadata?.reasoning) {
630
- const messageFormatter = {
631
- ...sdkMessage,
632
- metadata: buildMetadataFromTransport(data)
633
- };
634
- sessionState.messages[i] = messageFormatter;
635
-
636
- // Detect interactive tool_use blocks in the replaced message
637
- if (sdkMessage.type === 'assistant' && sdkMessage.message?.content) {
638
- const content = Array.isArray(sdkMessage.message.content) ? sdkMessage.message.content : [];
639
- const hasInteractiveTool = content.some(
640
- (item: any) => item.type === 'tool_use' && INTERACTIVE_TOOLS.has(item.name)
641
- );
642
- if (hasInteractiveTool) {
643
- this.setProcessState({ isWaitingInput: true });
644
- }
645
- }
646
-
647
- return; // Replaced in-place, skip push below
648
- }
649
- }
650
- // No stream_event found, fall through to push at end
651
- }
652
- }
653
-
654
- // Deduplicate: skip if a message with the same uuid already exists
655
- if (sdkMessage.uuid) {
656
- const alreadyExists = sessionState.messages.some(
657
- (m: any) => m.uuid === sdkMessage.uuid && m.type === sdkMessage.type && !m._optimistic
658
- );
659
- if (alreadyExists) return;
660
- }
661
-
662
- // Update UI state (message already saved to DB by server)
663
- const isReasoning = sdkMessage.metadata?.reasoning === true;
664
- const messageFormatter = {
665
- ...sdkMessage,
666
- metadata: buildMetadataFromTransport({
667
- ...data,
668
- ...(isReasoning && { reasoning: true }),
669
- })
670
- };
671
-
672
- // Detect interactive tool_use blocks (e.g., AskUserQuestion) and set waiting status.
673
- // When the SDK is blocked on canUseTool, partial events stop and the user must interact.
674
- if (sdkMessage.type === 'assistant' && sdkMessage.message?.content) {
675
- const content = Array.isArray(sdkMessage.message.content) ? sdkMessage.message.content : [];
676
- const hasInteractiveTool = content.some(
677
- (item: any) => item.type === 'tool_use' && INTERACTIVE_TOOLS.has(item.name)
678
- );
679
- if (hasInteractiveTool) {
680
- this.setProcessState({ isWaitingInput: true });
681
- }
682
- }
683
-
684
- // When a user message with tool_result arrives, the SDK is unblocked — clear waiting status
685
- if (sdkMessage.type === 'user' && sdkMessage.message?.content) {
686
- const content = Array.isArray(sdkMessage.message.content) ? sdkMessage.message.content : [];
687
- const hasToolResult = content.some((item: any) => item.type === 'tool_result');
688
- if (hasToolResult && appState.isWaitingInput) {
689
- this.setProcessState({ isWaitingInput: false });
690
- }
691
- }
692
-
693
- // For reasoning messages that couldn't find a matching stream_event,
694
- // insert BEFORE trailing non-reasoning assistant messages (tools/text)
695
- // to preserve reasoning-before-tool ordering within the same turn.
696
- if (isReasoning) {
697
- let insertIdx = sessionState.messages.length;
698
- for (let i = sessionState.messages.length - 1; i >= 0; i--) {
699
- const msg = sessionState.messages[i] as any;
700
- // Stop at user messages or other reasoning messages — they mark turn boundaries
701
- if (msg.type === 'user' || (msg.type === 'assistant' && msg.metadata?.reasoning)) break;
702
- // Insert before non-reasoning assistant messages and non-reasoning stream_events
703
- if (msg.type === 'assistant' || (msg.type === 'stream_event' && !msg.metadata?.reasoning)) {
704
- insertIdx = i;
705
- }
706
- }
707
- (sessionState.messages as any[]).splice(insertIdx, 0, messageFormatter);
708
- } else {
709
- (sessionState.messages as any[]).push(messageFormatter);
710
- }
711
- }
712
-
713
- /**
714
- * Handle partial message events (streaming)
715
- */
716
- private handlePartialEvent(data: any): void {
717
- // Ignore partials from a completed/cancelled stream
718
- if (this.streamCompleted) return;
719
-
720
- // Early return if no valid session
721
- if (!sessionState.currentSession?.id) {
722
- return;
723
- }
724
-
725
- const { eventType, partialText } = data;
726
- const isReasoning = data.reasoning === true;
727
-
728
- if (eventType === 'start') {
729
- if (isReasoning) {
730
- // Check if there's already a reasoning stream_event (from catchup)
731
- const existingReasoning = sessionState.messages.find(
732
- (m: any) => m.type === 'stream_event' && m.metadata?.reasoning && m.processId === data.processId
733
- );
734
- if (existingReasoning) {
735
- // Already have one, just update it
736
- (existingReasoning as any).partialText = partialText || '';
737
- return;
738
- }
739
- } else {
740
- // Check if there's already a regular stream_event for this process (from catchup)
741
- const existingStream = sessionState.messages.find(
742
- (m: any) => m.type === 'stream_event' && !m.metadata?.reasoning && m.processId === data.processId
743
- );
744
- if (existingStream) {
745
- // Already have one, just update it
746
- (existingStream as any).partialText = partialText || '';
747
- return;
748
- }
749
- }
750
-
751
- // Create new streaming message (reasoning or text)
752
- const streamingMessage = {
753
- type: 'stream_event' as const,
754
- processId: data.processId,
755
- partialText: partialText || '',
756
- metadata: buildMetadataFromTransport({
757
- timestamp: data.timestamp,
758
- ...(isReasoning && { reasoning: true }),
759
- })
760
- };
761
-
762
- if (isReasoning) {
763
- // Insert reasoning stream BEFORE any existing non-reasoning stream_event
764
- // to preserve logical order (reasoning comes before text in the model's output)
765
- const textStreamIdx = (sessionState.messages as any[]).findIndex(
766
- (m: any) => m.type === 'stream_event' && !m.metadata?.reasoning
767
- );
768
- if (textStreamIdx >= 0) {
769
- (sessionState.messages as any[]).splice(textStreamIdx, 0, streamingMessage);
770
- } else {
771
- (sessionState.messages as any[]).push(streamingMessage);
772
- }
773
- } else {
774
- // Text stream always goes to the end (after any reasoning)
775
- (sessionState.messages as any[]).push(streamingMessage);
776
- }
777
- } else if (eventType === 'update') {
778
- if (isReasoning) {
779
- // Update reasoning streaming message — find last reasoning stream_event
780
- for (let i = sessionState.messages.length - 1; i >= 0; i--) {
781
- const msg = sessionState.messages[i] as any;
782
- if (msg.type === 'stream_event' && msg.metadata?.reasoning) {
783
- msg.partialText = partialText || '';
784
- return;
785
- }
786
- }
787
- } else {
788
- // Update regular text streaming message — find matching stream_event
789
- // Search backwards to find the most recent non-reasoning stream_event
790
- for (let i = sessionState.messages.length - 1; i >= 0; i--) {
791
- const msg = sessionState.messages[i] as any;
792
- if (msg.type === 'stream_event' && !msg.metadata?.reasoning) {
793
- msg.partialText = partialText || '';
794
- return;
795
- }
796
- }
797
- }
798
-
799
- // Fallback: no matching stream_event found (start event was missed).
800
- // Create one now so text doesn't get lost.
801
- const fallbackMessage = {
802
- type: 'stream_event' as const,
803
- processId: data.processId,
804
- partialText: partialText || '',
805
- metadata: buildMetadataFromTransport({
806
- timestamp: data.timestamp,
807
- ...(isReasoning && { reasoning: true }),
808
- })
809
- };
810
-
811
- if (isReasoning) {
812
- const textStreamIdx = (sessionState.messages as any[]).findIndex(
813
- (m: any) => m.type === 'stream_event' && !m.metadata?.reasoning
814
- );
815
- if (textStreamIdx >= 0) {
816
- (sessionState.messages as any[]).splice(textStreamIdx, 0, fallbackMessage);
817
- } else {
818
- (sessionState.messages as any[]).push(fallbackMessage);
819
- }
820
- } else {
821
- (sessionState.messages as any[]).push(fallbackMessage);
822
- }
823
- }
824
- // Note: 'end' event is not needed - streaming message will be replaced by final message in handleMessageEvent
825
- }
826
-
827
- /**
828
- * Remove all stream_event messages from the messages array.
829
- * Called on new message send to prevent stale streaming
830
- * placeholders from causing wrong insertion positions.
831
- */
832
- private cleanupStreamEvents(): void {
833
- for (let i = sessionState.messages.length - 1; i >= 0; i--) {
834
- if ((sessionState.messages[i] as any).type === 'stream_event') {
835
- sessionState.messages.splice(i, 1);
836
- }
837
- }
838
- }
839
-
840
- /**
841
- * Convert stream_event messages with text to finalized assistant messages.
842
- * Called on cancel to preserve partial reasoning/text that was visible.
843
- * Empty stream_events (no text) are removed.
844
- * The backend saves these to DB independently, so on refresh the DB version takes over.
845
- */
846
- private finalizeStreamEvents(): void {
847
- for (let i = sessionState.messages.length - 1; i >= 0; i--) {
848
- const msg = sessionState.messages[i] as any;
849
- if (msg.type !== 'stream_event') continue;
850
-
851
- if (msg.partialText) {
852
- const isReasoning = msg.metadata?.reasoning === true;
853
- sessionState.messages[i] = {
854
- type: 'assistant',
855
- message: {
856
- role: 'assistant',
857
- content: [{ type: 'text', text: msg.partialText }]
858
- },
859
- metadata: {
860
- ...msg.metadata,
861
- ...(isReasoning && { reasoning: true }),
862
- }
863
- } as any;
864
- } else {
865
- sessionState.messages.splice(i, 1);
866
- }
867
- }
868
- }
869
-
870
- /**
871
- * Detect whether any interactive tool (e.g. AskUserQuestion) is pending in the current messages.
872
- * Used after browser refresh / catchup to restore the isWaitingInput state.
873
- */
874
- detectPendingInteractiveTools(): void {
875
- if (!appState.isLoading) return;
876
-
877
- // Collect all tool_use IDs that have a matching tool_result
878
- const answeredToolIds = new Set<string>();
879
- for (const msg of sessionState.messages) {
880
- const msgAny = msg as any;
881
- if (msgAny.type !== 'user' || !msgAny.message?.content) continue;
882
- const content = Array.isArray(msgAny.message.content) ? msgAny.message.content : [];
883
- for (const item of content) {
884
- if (item.type === 'tool_result' && item.tool_use_id) {
885
- answeredToolIds.add(item.tool_use_id);
886
- }
887
- }
888
- }
889
-
890
- // Check if any interactive tool is unanswered (skip interrupted/cancelled messages)
891
- for (const msg of sessionState.messages) {
892
- const msgAny = msg as any;
893
- if (msgAny.type !== 'assistant' || !msgAny.message?.content) continue;
894
- if (msgAny.metadata?.interrupted) continue;
895
- const content = Array.isArray(msgAny.message.content) ? msgAny.message.content : [];
896
- const hasPendingInteractive = content.some(
897
- (item: any) => item.type === 'tool_use' && INTERACTIVE_TOOLS.has(item.name) && item.id && !answeredToolIds.has(item.id)
898
- );
899
- if (hasPendingInteractive) {
900
- this.setProcessState({ isWaitingInput: true });
901
- return;
902
- }
903
- }
904
- }
905
-
906
- /**
907
- * Mark assistant messages with unanswered tool_use blocks as interrupted.
908
- * Sets metadata.interrupted at the MESSAGE level (not tool_use content level).
909
- * Called when stream ends (complete/error/cancel) for immediate in-memory update.
910
- * The backend persists this to DB via stream:lifecycle for durability.
911
- */
912
- private markInterruptedTools(): void {
913
- // Collect all tool_use IDs that have a matching tool_result
914
- const answeredToolIds = new Set<string>();
915
-
916
- for (const msg of sessionState.messages) {
917
- const msgAny = msg as any;
918
- if (msgAny.type !== 'user' || !msgAny.message?.content) continue;
919
- const content = Array.isArray(msgAny.message.content) ? msgAny.message.content : [];
920
-
921
- for (const item of content) {
922
- if (item.type === 'tool_result' && item.tool_use_id) {
923
- answeredToolIds.add(item.tool_use_id);
924
- }
925
- }
926
- }
927
-
928
- // Mark messages with unanswered tool_use blocks as interrupted (message-level metadata)
929
- for (const msg of sessionState.messages) {
930
- const msgAny = msg as any;
931
- if (msgAny.type !== 'assistant' || !msgAny.message?.content) continue;
932
- const content = Array.isArray(msgAny.message.content) ? msgAny.message.content : [];
933
-
934
- const hasUnansweredTool = content.some(
935
- (item: any) => item.type === 'tool_use' && item.id && !answeredToolIds.has(item.id)
936
- );
937
-
938
- if (hasUnansweredTool && !msgAny.metadata?.interrupted) {
939
- if (!msgAny.metadata) msgAny.metadata = {};
940
- msgAny.metadata.interrupted = true;
941
- }
942
- }
943
- }
944
-
945
- /**
946
- * Handle general errors
947
- */
948
- private handleError(
949
- error: Error,
950
- options: ChatServiceOptions
951
- ): void {
952
- let errorMessage = 'Failed to connect to AI engine';
953
- if (error.message.includes('Project path')) {
954
- errorMessage = error.message;
955
- } else {
956
- errorMessage = error.message;
957
- }
958
-
959
- addNotification({
960
- type: 'error',
961
- title: 'Chat Error',
962
- message: errorMessage,
963
- duration: 5000
964
- });
965
-
966
- options.onError?.(error);
967
- appState.isLoading = false;
968
- }
969
- }
970
-
971
- // Export singleton instance
972
- export const chatService = new ChatService();
973
-
974
- // Export class for static methods
975
- export { ChatService };