@agent-relay/dashboard 2.0.80 → 2.0.82

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 (244) hide show
  1. package/out/404.html +1 -1
  2. package/out/_next/static/chunks/{118-4c8241b0218335de.js → 118-ae2b650136a5a5fc.js} +1 -1
  3. package/out/_next/static/chunks/407-0c82986cf79c8ecb.js +1 -0
  4. package/out/_next/static/chunks/app/app/[[...slug]]/{page-1e81c047cff17212.js → page-f7eca1b66fb4249b.js} +1 -1
  5. package/out/_next/static/chunks/app/{page-6892fe2dd07fb48b.js → page-0ee604f7070d14c0.js} +1 -1
  6. package/out/_next/static/css/8968d98ed4c4d33f.css +1 -0
  7. package/out/about.html +2 -2
  8. package/out/about.txt +1 -1
  9. package/out/app/onboarding.html +1 -1
  10. package/out/app/onboarding.txt +1 -1
  11. package/out/app.html +1 -1
  12. package/out/app.txt +2 -2
  13. package/out/blog/go-to-bed-wake-up-to-a-finished-product.html +2 -2
  14. package/out/blog/go-to-bed-wake-up-to-a-finished-product.txt +1 -1
  15. package/out/blog/let-them-cook-multi-agent-orchestration.html +2 -2
  16. package/out/blog/let-them-cook-multi-agent-orchestration.txt +2 -2
  17. package/out/blog.html +2 -2
  18. package/out/blog.txt +1 -1
  19. package/out/careers.html +2 -2
  20. package/out/careers.txt +1 -1
  21. package/out/changelog.html +2 -2
  22. package/out/changelog.txt +1 -1
  23. package/out/cloud/link.html +1 -1
  24. package/out/cloud/link.txt +2 -2
  25. package/out/complete-profile.html +2 -2
  26. package/out/complete-profile.txt +1 -1
  27. package/out/connect-repos.html +1 -1
  28. package/out/connect-repos.txt +1 -1
  29. package/out/contact.html +2 -2
  30. package/out/contact.txt +1 -1
  31. package/out/docs.html +2 -2
  32. package/out/docs.txt +1 -1
  33. package/out/history.html +1 -1
  34. package/out/history.txt +2 -2
  35. package/out/index.html +1 -1
  36. package/out/index.txt +2 -2
  37. package/out/login.html +2 -2
  38. package/out/login.txt +1 -1
  39. package/out/metrics.html +1 -1
  40. package/out/metrics.txt +2 -2
  41. package/out/pricing.html +2 -2
  42. package/out/pricing.txt +1 -1
  43. package/out/privacy.html +2 -2
  44. package/out/privacy.txt +1 -1
  45. package/out/providers/setup/claude.html +1 -1
  46. package/out/providers/setup/claude.txt +1 -1
  47. package/out/providers/setup/codex.html +1 -1
  48. package/out/providers/setup/codex.txt +1 -1
  49. package/out/providers/setup/cursor.html +1 -1
  50. package/out/providers/setup/cursor.txt +1 -1
  51. package/out/providers.html +1 -1
  52. package/out/providers.txt +1 -1
  53. package/out/security.html +2 -2
  54. package/out/security.txt +1 -1
  55. package/out/signup.html +2 -2
  56. package/out/signup.txt +1 -1
  57. package/out/terms.html +2 -2
  58. package/out/terms.txt +1 -1
  59. package/package.json +7 -1
  60. package/src/app/about/page.tsx +7 -0
  61. package/src/app/app/[[...slug]]/DashboardPageClient.tsx +853 -0
  62. package/src/app/app/[[...slug]]/page.tsx +23 -0
  63. package/src/app/app/onboarding/page.tsx +394 -0
  64. package/src/app/apple-icon.png +0 -0
  65. package/src/app/blog/go-to-bed-wake-up-to-a-finished-product/page.tsx +88 -0
  66. package/src/app/blog/let-them-cook-multi-agent-orchestration/page.tsx +93 -0
  67. package/src/app/blog/page.tsx +15 -0
  68. package/src/app/careers/page.tsx +7 -0
  69. package/src/app/changelog/page.tsx +7 -0
  70. package/src/app/cloud/link/page.tsx +464 -0
  71. package/src/app/complete-profile/page.tsx +204 -0
  72. package/src/app/connect-repos/page.tsx +410 -0
  73. package/src/app/contact/page.tsx +7 -0
  74. package/src/app/docs/page.tsx +7 -0
  75. package/src/app/favicon.png +0 -0
  76. package/src/app/globals.css +200 -0
  77. package/src/app/history/page.tsx +658 -0
  78. package/src/app/layout.tsx +25 -0
  79. package/src/app/login/page.tsx +424 -0
  80. package/src/app/metrics/page.tsx +781 -0
  81. package/src/app/page.tsx +59 -0
  82. package/src/app/pricing/page.tsx +7 -0
  83. package/src/app/privacy/page.tsx +7 -0
  84. package/src/app/providers/page.tsx +193 -0
  85. package/src/app/providers/setup/[provider]/ProviderSetupClient.tsx +197 -0
  86. package/src/app/providers/setup/[provider]/constants.ts +35 -0
  87. package/src/app/providers/setup/[provider]/page.tsx +42 -0
  88. package/src/app/security/page.tsx +7 -0
  89. package/src/app/signup/page.tsx +533 -0
  90. package/src/app/terms/page.tsx +7 -0
  91. package/src/components/ActivityFeed.tsx +216 -0
  92. package/src/components/AddWorkspaceModal.tsx +170 -0
  93. package/src/components/AgentCard.test.tsx +134 -0
  94. package/src/components/AgentCard.tsx +585 -0
  95. package/src/components/AgentList.test.tsx +147 -0
  96. package/src/components/AgentList.tsx +419 -0
  97. package/src/components/AgentLogPreview.tsx +173 -0
  98. package/src/components/AgentProfilePanel.tsx +569 -0
  99. package/src/components/App.tsx +3424 -0
  100. package/src/components/BillingPanel.tsx +922 -0
  101. package/src/components/BillingResult.tsx +447 -0
  102. package/src/components/BroadcastComposer.tsx +690 -0
  103. package/src/components/ChannelAdminPanel.tsx +773 -0
  104. package/src/components/ChannelBrowser.tsx +385 -0
  105. package/src/components/ChannelChat.tsx +261 -0
  106. package/src/components/ChannelSidebar.tsx +399 -0
  107. package/src/components/CloudSessionProvider.tsx +130 -0
  108. package/src/components/CommandPalette.tsx +815 -0
  109. package/src/components/ConfirmationDialog.tsx +133 -0
  110. package/src/components/ConversationHistory.tsx +518 -0
  111. package/src/components/CoordinatorPanel.tsx +956 -0
  112. package/src/components/DecisionQueue.tsx +717 -0
  113. package/src/components/DirectMessageView.tsx +164 -0
  114. package/src/components/FileAutocomplete.tsx +368 -0
  115. package/src/components/FleetOverview.tsx +278 -0
  116. package/src/components/LogViewer.tsx +310 -0
  117. package/src/components/LogViewerPanel.tsx +482 -0
  118. package/src/components/Logo.tsx +284 -0
  119. package/src/components/MentionAutocomplete.tsx +384 -0
  120. package/src/components/MessageComposer.tsx +473 -0
  121. package/src/components/MessageList.tsx +725 -0
  122. package/src/components/MessageSenderName.tsx +91 -0
  123. package/src/components/MessageStatusIndicator.tsx +142 -0
  124. package/src/components/NewConversationModal.tsx +400 -0
  125. package/src/components/NotificationToast.tsx +488 -0
  126. package/src/components/OnlineUsersIndicator.tsx +164 -0
  127. package/src/components/Pagination.tsx +124 -0
  128. package/src/components/PricingPlans.tsx +386 -0
  129. package/src/components/ProjectList.tsx +711 -0
  130. package/src/components/ProviderAuthFlow.tsx +343 -0
  131. package/src/components/ProviderConnectionList.tsx +375 -0
  132. package/src/components/ProvisioningProgress.tsx +730 -0
  133. package/src/components/ReactionChips.tsx +70 -0
  134. package/src/components/ReactionPicker.tsx +121 -0
  135. package/src/components/RepoAccessPanel.tsx +787 -0
  136. package/src/components/RepositoriesPanel.tsx +901 -0
  137. package/src/components/ServerCard.tsx +202 -0
  138. package/src/components/SessionExpiredModal.tsx +128 -0
  139. package/src/components/SpawnModal.test.tsx +190 -0
  140. package/src/components/SpawnModal.tsx +1001 -0
  141. package/src/components/TaskAssignmentUI.tsx +375 -0
  142. package/src/components/TerminalProviderSetup.tsx +517 -0
  143. package/src/components/ThemeProvider.tsx +159 -0
  144. package/src/components/ThinkingIndicator.tsx +231 -0
  145. package/src/components/ThreadList.tsx +198 -0
  146. package/src/components/ThreadPanel.tsx +405 -0
  147. package/src/components/TrajectoryViewer.tsx +698 -0
  148. package/src/components/TypingIndicator.tsx +69 -0
  149. package/src/components/UsageBanner.tsx +231 -0
  150. package/src/components/UserProfilePanel.tsx +233 -0
  151. package/src/components/WorkspaceContext.tsx +95 -0
  152. package/src/components/WorkspaceSelector.tsx +234 -0
  153. package/src/components/WorkspaceStatusIndicator.tsx +396 -0
  154. package/src/components/XTermInteractive.tsx +516 -0
  155. package/src/components/XTermLogViewer.tsx +719 -0
  156. package/src/components/channels/ChannelDialogs.tsx +1411 -0
  157. package/src/components/channels/ChannelHeader.tsx +317 -0
  158. package/src/components/channels/ChannelMessageList.tsx +463 -0
  159. package/src/components/channels/ChannelViewV1.tsx +146 -0
  160. package/src/components/channels/MessageInput.tsx +302 -0
  161. package/src/components/channels/SearchInput.tsx +172 -0
  162. package/src/components/channels/SearchResults.tsx +336 -0
  163. package/src/components/channels/api.test.ts +1527 -0
  164. package/src/components/channels/api.ts +703 -0
  165. package/src/components/channels/index.ts +76 -0
  166. package/src/components/channels/mockApi.ts +344 -0
  167. package/src/components/channels/types.ts +566 -0
  168. package/src/components/hooks/index.ts +58 -0
  169. package/src/components/hooks/useAgentLogs.ts +504 -0
  170. package/src/components/hooks/useAgents.ts +127 -0
  171. package/src/components/hooks/useBroadcastDedup.test.ts +371 -0
  172. package/src/components/hooks/useBroadcastDedup.ts +86 -0
  173. package/src/components/hooks/useChannelAdmin.ts +329 -0
  174. package/src/components/hooks/useChannelBrowser.ts +239 -0
  175. package/src/components/hooks/useChannelCommands.ts +138 -0
  176. package/src/components/hooks/useChannels.ts +367 -0
  177. package/src/components/hooks/useDebounce.ts +29 -0
  178. package/src/components/hooks/useDirectMessage.test.ts +952 -0
  179. package/src/components/hooks/useDirectMessage.ts +141 -0
  180. package/src/components/hooks/useMessages.ts +310 -0
  181. package/src/components/hooks/useOrchestrator.test.ts +165 -0
  182. package/src/components/hooks/useOrchestrator.ts +424 -0
  183. package/src/components/hooks/usePinnedAgents.test.ts +356 -0
  184. package/src/components/hooks/usePinnedAgents.ts +140 -0
  185. package/src/components/hooks/usePresence.test.ts +245 -0
  186. package/src/components/hooks/usePresence.ts +377 -0
  187. package/src/components/hooks/useRecentRepos.ts +130 -0
  188. package/src/components/hooks/useSession.ts +209 -0
  189. package/src/components/hooks/useThread.ts +138 -0
  190. package/src/components/hooks/useTrajectory.ts +265 -0
  191. package/src/components/hooks/useWebSocket.ts +290 -0
  192. package/src/components/hooks/useWorkspaceMembers.ts +132 -0
  193. package/src/components/hooks/useWorkspaceRepos.ts +73 -0
  194. package/src/components/hooks/useWorkspaceStatus.ts +237 -0
  195. package/src/components/index.ts +81 -0
  196. package/src/components/layout/Header.tsx +311 -0
  197. package/src/components/layout/RepoContextHeader.tsx +361 -0
  198. package/src/components/layout/Sidebar.archive.test.tsx +126 -0
  199. package/src/components/layout/Sidebar.test.tsx +691 -0
  200. package/src/components/layout/Sidebar.tsx +900 -0
  201. package/src/components/layout/index.ts +7 -0
  202. package/src/components/settings/BillingSettingsPanel.tsx +564 -0
  203. package/src/components/settings/SettingsPage.tsx +683 -0
  204. package/src/components/settings/TeamSettingsPanel.tsx +560 -0
  205. package/src/components/settings/WorkspaceSettingsPanel.tsx +1368 -0
  206. package/src/components/settings/index.ts +11 -0
  207. package/src/components/settings/types.ts +79 -0
  208. package/src/components/utils/messageFormatting.test.tsx +331 -0
  209. package/src/components/utils/messageFormatting.tsx +597 -0
  210. package/src/index.ts +63 -0
  211. package/src/landing/AboutPage.tsx +77 -0
  212. package/src/landing/BlogContent.tsx +187 -0
  213. package/src/landing/BlogPage.tsx +47 -0
  214. package/src/landing/CareersPage.tsx +53 -0
  215. package/src/landing/ChangelogPage.tsx +33 -0
  216. package/src/landing/ContactPage.tsx +41 -0
  217. package/src/landing/DocsPage.tsx +43 -0
  218. package/src/landing/LandingPage.tsx +702 -0
  219. package/src/landing/PricingPage.tsx +549 -0
  220. package/src/landing/PrivacyPage.tsx +117 -0
  221. package/src/landing/SecurityPage.tsx +42 -0
  222. package/src/landing/StaticPage.tsx +165 -0
  223. package/src/landing/TermsPage.tsx +125 -0
  224. package/src/landing/blogData.ts +312 -0
  225. package/src/landing/index.ts +18 -0
  226. package/src/landing/styles.css +3673 -0
  227. package/src/lib/agent-merge.test.ts +43 -0
  228. package/src/lib/agent-merge.ts +35 -0
  229. package/src/lib/api.ts +1294 -0
  230. package/src/lib/cloudApi.ts +893 -0
  231. package/src/lib/colors.test.ts +175 -0
  232. package/src/lib/colors.ts +218 -0
  233. package/src/lib/config.ts +109 -0
  234. package/src/lib/hierarchy.ts +242 -0
  235. package/src/lib/stuckDetection.ts +142 -0
  236. package/src/lib/useUrlRouting.ts +190 -0
  237. package/src/types/index.ts +317 -0
  238. package/src/types/threading.ts +7 -0
  239. package/out/_next/static/chunks/285-dc644487a8d6500d.js +0 -1
  240. package/out/_next/static/css/4c58d9cf493aa626.css +0 -1
  241. /package/out/_next/static/{AqelRhy1vr2nBUcU0Iqcp → IxfA6RZu4trcsEMYlkQra}/_buildManifest.js +0 -0
  242. /package/out/_next/static/{AqelRhy1vr2nBUcU0Iqcp → IxfA6RZu4trcsEMYlkQra}/_ssgManifest.js +0 -0
  243. /package/out/_next/static/chunks/{528-d375bc8b46912d2c.js → 528-f5f676996d613c25.js} +0 -0
  244. /package/out/_next/static/chunks/app/blog/let-them-cook-multi-agent-orchestration/{page-a58308f43557b908.js → page-b194f207fbd91862.js} +0 -0
package/src/lib/api.ts ADDED
@@ -0,0 +1,1294 @@
1
+ /**
2
+ * Dashboard API Client
3
+ *
4
+ * Provides a clean interface to the dashboard REST and WebSocket APIs.
5
+ * Can be used by both the current dashboard and the v2 React dashboard.
6
+ */
7
+
8
+ import type {
9
+ Agent,
10
+ Message,
11
+ Session,
12
+ AgentSummary,
13
+ FleetData,
14
+ Project,
15
+ SendMessageRequest,
16
+ SpawnAgentRequest,
17
+ SpawnAgentResponse,
18
+ ApiResponse,
19
+ Attachment,
20
+ Reaction,
21
+ } from '../types';
22
+
23
+ /**
24
+ * Bridge data returned by /api/bridge endpoint
25
+ * Contains workspace repos as projects with their agents
26
+ */
27
+ export interface BridgeData {
28
+ projects: Project[];
29
+ bridgeAgents?: Agent[];
30
+ messages: Message[];
31
+ connected: boolean;
32
+ workspace?: {
33
+ id: string;
34
+ name: string;
35
+ status: string;
36
+ };
37
+ }
38
+ import { getWebSocketUrl, getApiBaseUrl } from './config';
39
+
40
+ // API base URL - uses centralized config
41
+ const API_BASE = getApiBaseUrl();
42
+
43
+ // Storage key for workspace ID persistence
44
+ const WORKSPACE_ID_KEY = 'agentrelay_workspace_id';
45
+
46
+ // Workspace ID for cloud mode proxying
47
+ let activeWorkspaceId: string | null = null;
48
+
49
+ // CSRF token storage key
50
+ const CSRF_TOKEN_KEY = 'agentrelay_csrf_token';
51
+
52
+ // CSRF token for cloud mode requests - persisted in sessionStorage
53
+ let csrfToken: string | null = null;
54
+
55
+ // Initialize from sessionStorage if available
56
+ if (typeof window !== 'undefined' && window.sessionStorage) {
57
+ csrfToken = sessionStorage.getItem(CSRF_TOKEN_KEY);
58
+ }
59
+
60
+ /**
61
+ * Set the CSRF token for API requests
62
+ * Persists to sessionStorage for page reload resilience
63
+ */
64
+ export function setCsrfToken(token: string | null): void {
65
+ csrfToken = token;
66
+ if (typeof window !== 'undefined' && window.sessionStorage) {
67
+ if (token) {
68
+ sessionStorage.setItem(CSRF_TOKEN_KEY, token);
69
+ } else {
70
+ sessionStorage.removeItem(CSRF_TOKEN_KEY);
71
+ }
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Get the current CSRF token
77
+ */
78
+ export function getCsrfToken(): string | null {
79
+ return csrfToken;
80
+ }
81
+
82
+ /**
83
+ * Capture CSRF token from response headers
84
+ * Automatically persists to sessionStorage
85
+ */
86
+ function captureCsrfToken(response: Response): void {
87
+ const token = response.headers.get('X-CSRF-Token');
88
+ if (token) {
89
+ setCsrfToken(token);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Set the active workspace ID for API proxying in cloud mode.
95
+ * Also persists to localStorage so other pages can access it.
96
+ */
97
+ export function setActiveWorkspaceId(workspaceId: string | null): void {
98
+ activeWorkspaceId = workspaceId;
99
+ // Persist to localStorage for cross-page access
100
+ if (typeof window !== 'undefined') {
101
+ if (workspaceId) {
102
+ localStorage.setItem(WORKSPACE_ID_KEY, workspaceId);
103
+ } else {
104
+ localStorage.removeItem(WORKSPACE_ID_KEY);
105
+ }
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Get the active workspace ID
111
+ */
112
+ export function getActiveWorkspaceId(): string | null {
113
+ return activeWorkspaceId;
114
+ }
115
+
116
+ /**
117
+ * Initialize workspace ID from localStorage if not already set.
118
+ * Call this on pages that need workspace context but aren't in the main app flow.
119
+ */
120
+ export function initializeWorkspaceId(): string | null {
121
+ if (activeWorkspaceId) {
122
+ return activeWorkspaceId;
123
+ }
124
+ if (typeof window !== 'undefined') {
125
+ const stored = localStorage.getItem(WORKSPACE_ID_KEY);
126
+ if (stored) {
127
+ activeWorkspaceId = stored;
128
+ return stored;
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+
134
+ /**
135
+ * Cloud-native API paths that should NOT be proxied through workspace.
136
+ * These are routes handled by the cloud server itself, not workspace daemons.
137
+ */
138
+ const CLOUD_NATIVE_PATHS = [
139
+ '/api/daemons/', // Linked daemons API
140
+ '/api/workspaces/', // Workspace management
141
+ '/api/providers/', // OAuth providers
142
+ '/api/auth/', // Authentication
143
+ '/api/billing/', // Billing
144
+ '/api/usage/', // Usage metrics
145
+ '/api/admin/', // Admin endpoints
146
+ '/api/onboarding/', // Onboarding
147
+ '/api/repos/', // Repository management
148
+ '/api/project-groups/', // Coordinators
149
+ '/api/github-app/', // GitHub App
150
+ '/api/channels', // Channel proxy handled by dashboard server
151
+ '/api/bridge', // Bridge data (multi-repo view)
152
+ ];
153
+
154
+ /**
155
+ * Get the API URL, accounting for cloud mode proxying
156
+ * @param path - API path like '/api/spawn' or '/api/send'
157
+ */
158
+ export function getApiUrl(path: string): string {
159
+ if (activeWorkspaceId) {
160
+ // Check if this is a cloud-native path that shouldn't be proxied
161
+ const isCloudNative = CLOUD_NATIVE_PATHS.some(prefix => path.startsWith(prefix));
162
+ if (isCloudNative) {
163
+ return `${API_BASE}${path}`;
164
+ }
165
+ // In cloud mode, proxy through the cloud server
166
+ // Strip /api/ prefix since the proxy endpoint adds it back
167
+ const proxyPath = path.startsWith('/api/') ? path.substring(5) : path.replace(/^\//, '');
168
+ return `/api/workspaces/${activeWorkspaceId}/proxy/${proxyPath}`;
169
+ }
170
+ return `${API_BASE}${path}`;
171
+ }
172
+
173
+ /**
174
+ * Wrapper for fetch that handles CSRF tokens and credentials
175
+ * All requests include credentials and capture CSRF tokens from responses.
176
+ * Non-GET requests include the CSRF token in headers.
177
+ */
178
+ async function apiFetch(
179
+ url: string,
180
+ options: RequestInit = {}
181
+ ): Promise<Response> {
182
+ const method = options.method?.toUpperCase() || 'GET';
183
+ const headers: Record<string, string> = {
184
+ ...(options.headers as Record<string, string>),
185
+ };
186
+
187
+ // Add CSRF token for state-changing requests
188
+ if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') {
189
+ if (csrfToken) {
190
+ headers['X-CSRF-Token'] = csrfToken;
191
+ }
192
+ // Ensure Content-Type is set for requests with body
193
+ if (options.body && !headers['Content-Type']) {
194
+ headers['Content-Type'] = 'application/json';
195
+ }
196
+ }
197
+
198
+ const response = await fetch(url, {
199
+ ...options,
200
+ headers,
201
+ credentials: 'include',
202
+ });
203
+
204
+ // Always capture CSRF token from response
205
+ captureCsrfToken(response);
206
+
207
+ return response;
208
+ }
209
+
210
+ /**
211
+ * Dashboard data received from WebSocket
212
+ */
213
+ export interface DashboardData {
214
+ agents: Agent[];
215
+ messages: Message[];
216
+ sessions?: Session[];
217
+ summaries?: AgentSummary[];
218
+ fleet?: FleetData;
219
+ }
220
+
221
+ /**
222
+ * WebSocket connection manager
223
+ */
224
+ export class DashboardWebSocket {
225
+ private ws: WebSocket | null = null;
226
+ private reconnectAttempts = 0;
227
+ private maxReconnectAttempts = 10;
228
+ private reconnectDelay = 1000;
229
+ private listeners: Set<(data: DashboardData) => void> = new Set();
230
+ private statusListeners: Set<(connected: boolean) => void> = new Set();
231
+
232
+ constructor(private url?: string) {}
233
+
234
+ /**
235
+ * Connect to the WebSocket server
236
+ */
237
+ connect(): void {
238
+ if (this.ws?.readyState === WebSocket.OPEN) return;
239
+
240
+ const wsUrl = this.url || this.getDefaultUrl();
241
+ this.ws = new WebSocket(wsUrl);
242
+
243
+ this.ws.onopen = () => {
244
+ this.reconnectAttempts = 0;
245
+ this.reconnectDelay = 1000;
246
+ this.notifyStatus(true);
247
+ };
248
+
249
+ this.ws.onclose = () => {
250
+ this.notifyStatus(false);
251
+ this.scheduleReconnect();
252
+ };
253
+
254
+ this.ws.onerror = (error) => {
255
+ console.error('[ws] WebSocket error:', error);
256
+ };
257
+
258
+ this.ws.onmessage = (event) => {
259
+ try {
260
+ const data = JSON.parse(event.data) as DashboardData;
261
+ this.notifyListeners(data);
262
+ } catch (e) {
263
+ console.error('[ws] Failed to parse message:', e);
264
+ }
265
+ };
266
+ }
267
+
268
+ /**
269
+ * Disconnect from the WebSocket server
270
+ */
271
+ disconnect(): void {
272
+ if (this.ws) {
273
+ this.ws.close();
274
+ this.ws = null;
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Subscribe to data updates
280
+ */
281
+ onData(callback: (data: DashboardData) => void): () => void {
282
+ this.listeners.add(callback);
283
+ return () => this.listeners.delete(callback);
284
+ }
285
+
286
+ /**
287
+ * Subscribe to connection status changes
288
+ */
289
+ onStatusChange(callback: (connected: boolean) => void): () => void {
290
+ this.statusListeners.add(callback);
291
+ return () => this.statusListeners.delete(callback);
292
+ }
293
+
294
+ /**
295
+ * Check if connected
296
+ */
297
+ get isConnected(): boolean {
298
+ return this.ws?.readyState === WebSocket.OPEN;
299
+ }
300
+
301
+ private getDefaultUrl(): string {
302
+ // Use centralized config for consistent URL resolution
303
+ return getWebSocketUrl('/ws');
304
+ }
305
+
306
+ private notifyListeners(data: DashboardData): void {
307
+ for (const listener of this.listeners) {
308
+ try {
309
+ listener(data);
310
+ } catch (e) {
311
+ console.error('[ws] Listener error:', e);
312
+ }
313
+ }
314
+ }
315
+
316
+ private notifyStatus(connected: boolean): void {
317
+ for (const listener of this.statusListeners) {
318
+ try {
319
+ listener(connected);
320
+ } catch (e) {
321
+ console.error('[ws] Status listener error:', e);
322
+ }
323
+ }
324
+ }
325
+
326
+ private scheduleReconnect(): void {
327
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
328
+ console.error('[ws] Max reconnect attempts reached');
329
+ return;
330
+ }
331
+
332
+ this.reconnectAttempts++;
333
+ const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), 30000);
334
+
335
+ setTimeout(() => {
336
+ console.log(`[ws] Reconnecting (attempt ${this.reconnectAttempts})...`);
337
+ this.connect();
338
+ }, delay);
339
+ }
340
+ }
341
+
342
+ /**
343
+ * REST API methods
344
+ */
345
+ export const api = {
346
+ /**
347
+ * Generic GET request
348
+ */
349
+ async get<T = unknown>(path: string): Promise<T> {
350
+ const response = await apiFetch(getApiUrl(path), {
351
+ method: 'GET',
352
+ });
353
+
354
+ if (!response.ok) {
355
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
356
+ }
357
+
358
+ return await response.json() as T;
359
+ },
360
+
361
+ /**
362
+ * Generic POST request
363
+ */
364
+ async post<T = unknown>(path: string, body?: unknown): Promise<T> {
365
+ const response = await apiFetch(getApiUrl(path), {
366
+ method: 'POST',
367
+ body: body ? JSON.stringify(body) : undefined,
368
+ });
369
+
370
+ if (!response.ok) {
371
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
372
+ }
373
+
374
+ return await response.json() as T;
375
+ },
376
+
377
+ /**
378
+ * Generic PATCH request
379
+ */
380
+ async patch<T = unknown>(path: string, body?: unknown): Promise<T> {
381
+ const response = await apiFetch(getApiUrl(path), {
382
+ method: 'PATCH',
383
+ body: body ? JSON.stringify(body) : undefined,
384
+ });
385
+
386
+ if (!response.ok) {
387
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
388
+ }
389
+
390
+ return await response.json() as T;
391
+ },
392
+
393
+ /**
394
+ * Generic DELETE request
395
+ */
396
+ async delete<T = unknown>(path: string): Promise<T> {
397
+ const response = await apiFetch(getApiUrl(path), {
398
+ method: 'DELETE',
399
+ });
400
+
401
+ if (!response.ok) {
402
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
403
+ }
404
+
405
+ return await response.json() as T;
406
+ },
407
+
408
+ /**
409
+ * Send a message via the relay
410
+ */
411
+ async sendMessage(request: SendMessageRequest): Promise<ApiResponse<void>> {
412
+ try {
413
+ const response = await apiFetch(getApiUrl('/api/send'), {
414
+ method: 'POST',
415
+ body: JSON.stringify(request),
416
+ });
417
+
418
+ const result = await response.json() as { success?: boolean; error?: string };
419
+
420
+ if (response.ok && result.success) {
421
+ return { success: true };
422
+ }
423
+
424
+ return { success: false, error: result.error || 'Failed to send message' };
425
+ } catch (_error) {
426
+ return { success: false, error: 'Network error' };
427
+ }
428
+ },
429
+
430
+ /**
431
+ * Upload an attachment (image/screenshot)
432
+ * @param file - File object or { filename, mimeType, data } for base64 uploads
433
+ */
434
+ async uploadAttachment(
435
+ file: File | { filename: string; mimeType: string; data: string }
436
+ ): Promise<ApiResponse<{ attachment: Omit<Attachment, 'data'> }>> {
437
+ try {
438
+ let filename: string;
439
+ let mimeType: string;
440
+ let data: string;
441
+
442
+ if (file instanceof File) {
443
+ // Convert File to base64
444
+ filename = file.name;
445
+ mimeType = file.type;
446
+ data = await new Promise<string>((resolve, reject) => {
447
+ const reader = new FileReader();
448
+ reader.onload = () => resolve(reader.result as string);
449
+ reader.onerror = reject;
450
+ reader.readAsDataURL(file);
451
+ });
452
+ } else {
453
+ filename = file.filename;
454
+ mimeType = file.mimeType;
455
+ data = file.data;
456
+ }
457
+
458
+ const response = await apiFetch(getApiUrl('/api/upload'), {
459
+ method: 'POST',
460
+ body: JSON.stringify({ filename, mimeType, data }),
461
+ });
462
+
463
+ const result = await response.json() as {
464
+ success?: boolean;
465
+ attachment?: Omit<Attachment, 'data'>;
466
+ error?: string;
467
+ };
468
+
469
+ if (response.ok && result.success && result.attachment) {
470
+ return { success: true, data: { attachment: result.attachment } };
471
+ }
472
+
473
+ return { success: false, error: result.error || 'Failed to upload attachment' };
474
+ } catch (_error) {
475
+ return { success: false, error: 'Network error' };
476
+ }
477
+ },
478
+
479
+ /**
480
+ * Spawn a new agent
481
+ */
482
+ async spawnAgent(request: SpawnAgentRequest): Promise<SpawnAgentResponse> {
483
+ try {
484
+ const response = await apiFetch(getApiUrl('/api/spawn'), {
485
+ method: 'POST',
486
+ body: JSON.stringify(request),
487
+ });
488
+
489
+ return await response.json() as SpawnAgentResponse;
490
+ } catch (_error) {
491
+ return { success: false, name: request.name, error: 'Network error' };
492
+ }
493
+ },
494
+
495
+ /**
496
+ * Get list of spawned agents
497
+ */
498
+ async getSpawnedAgents(): Promise<ApiResponse<{ agents: Array<{ name: string; cli: string; startedAt: string }> }>> {
499
+ try {
500
+ const response = await apiFetch(getApiUrl('/api/spawned'));
501
+ const result = await response.json() as { success?: boolean; agents?: Array<{ name: string; cli: string; startedAt: string }>; error?: string };
502
+
503
+ if (response.ok && result.success) {
504
+ return { success: true, data: { agents: result.agents || [] } };
505
+ }
506
+
507
+ return { success: false, error: result.error };
508
+ } catch (_error) {
509
+ return { success: false, error: 'Network error' };
510
+ }
511
+ },
512
+
513
+ /**
514
+ * Release a spawned agent
515
+ */
516
+ async releaseAgent(name: string): Promise<ApiResponse<void>> {
517
+ try {
518
+ const response = await apiFetch(getApiUrl(`/api/spawned/${encodeURIComponent(name)}`), {
519
+ method: 'DELETE',
520
+ });
521
+
522
+ const result = await response.json() as { success?: boolean; error?: string };
523
+
524
+ if (response.ok && result.success) {
525
+ return { success: true };
526
+ }
527
+
528
+ return { success: false, error: result.error };
529
+ } catch (_error) {
530
+ return { success: false, error: 'Network error' };
531
+ }
532
+ },
533
+
534
+ /**
535
+ * Interrupt an agent by sending Ctrl+C (SIGINT equivalent).
536
+ * Use this to break an agent out of a stuck loop for refocusing.
537
+ * @param agentName - The agent's name
538
+ */
539
+ async interruptAgent(agentName: string): Promise<ApiResponse<void>> {
540
+ try {
541
+ const response = await apiFetch(getApiUrl(`/api/agents/by-name/${encodeURIComponent(agentName)}/interrupt`), {
542
+ method: 'POST',
543
+ });
544
+
545
+ const result = await response.json() as { success?: boolean; error?: string };
546
+
547
+ if (response.ok && result.success) {
548
+ return { success: true };
549
+ }
550
+
551
+ return { success: false, error: result.error || 'Failed to interrupt agent' };
552
+ } catch (_error) {
553
+ return { success: false, error: 'Network error' };
554
+ }
555
+ },
556
+
557
+ /**
558
+ * Get dashboard data (fallback for REST polling)
559
+ * @param workspaceId - Optional workspace ID to get data for
560
+ */
561
+ async getData(workspaceId?: string): Promise<ApiResponse<DashboardData>> {
562
+ try {
563
+ const wsId = workspaceId || activeWorkspaceId;
564
+ const url = wsId
565
+ ? getApiUrl(`/api/data?workspaceId=${encodeURIComponent(wsId)}`)
566
+ : getApiUrl('/api/data');
567
+ const response = await apiFetch(url);
568
+ const data = await response.json() as DashboardData;
569
+
570
+ if (response.ok) {
571
+ return { success: true, data };
572
+ }
573
+
574
+ return { success: false, error: 'Failed to fetch data' };
575
+ } catch (_error) {
576
+ return { success: false, error: 'Network error' };
577
+ }
578
+ },
579
+
580
+ /**
581
+ * Get bridge data for multi-project view
582
+ * @param workspaceId - Optional workspace ID to get repos/projects for
583
+ */
584
+ async getBridgeData(workspaceId?: string): Promise<ApiResponse<BridgeData>> {
585
+ try {
586
+ // Use provided workspaceId or fall back to active workspace
587
+ const wsId = workspaceId || activeWorkspaceId;
588
+ const url = wsId
589
+ ? `${API_BASE}/api/bridge?workspaceId=${encodeURIComponent(wsId)}`
590
+ : `${API_BASE}/api/bridge`;
591
+
592
+ const response = await apiFetch(url);
593
+ const data = await response.json() as BridgeData;
594
+
595
+ if (response.ok) {
596
+ return { success: true, data };
597
+ }
598
+
599
+ return { success: false, error: 'Failed to fetch bridge data' };
600
+ } catch (_error) {
601
+ return { success: false, error: 'Network error' };
602
+ }
603
+ },
604
+
605
+ /**
606
+ * Get system metrics
607
+ */
608
+ async getMetrics(): Promise<ApiResponse<unknown>> {
609
+ try {
610
+ const response = await apiFetch(getApiUrl('/api/metrics'));
611
+ const data = await response.json();
612
+
613
+ if (response.ok) {
614
+ return { success: true, data };
615
+ }
616
+
617
+ return { success: false, error: 'Failed to fetch metrics' };
618
+ } catch (_error) {
619
+ return { success: false, error: 'Network error' };
620
+ }
621
+ },
622
+
623
+ // ===== Conversation History API =====
624
+
625
+ /**
626
+ * Get historical sessions
627
+ */
628
+ async getHistorySessions(params?: {
629
+ agent?: string;
630
+ since?: number;
631
+ limit?: number;
632
+ }): Promise<ApiResponse<{ sessions: HistorySession[] }>> {
633
+ try {
634
+ const query = new URLSearchParams();
635
+ if (params?.agent) query.set('agent', params.agent);
636
+ if (params?.since) query.set('since', String(params.since));
637
+ if (params?.limit) query.set('limit', String(params.limit));
638
+
639
+ const response = await apiFetch(getApiUrl(`/api/history/sessions?${query}`));
640
+ const data = await response.json();
641
+
642
+ if (response.ok) {
643
+ return { success: true, data };
644
+ }
645
+
646
+ return { success: false, error: 'Failed to fetch sessions' };
647
+ } catch (_error) {
648
+ return { success: false, error: 'Network error' };
649
+ }
650
+ },
651
+
652
+ /**
653
+ * Get historical messages
654
+ */
655
+ async getHistoryMessages(params?: {
656
+ from?: string;
657
+ to?: string;
658
+ thread?: string;
659
+ since?: number;
660
+ limit?: number;
661
+ order?: 'asc' | 'desc';
662
+ search?: string;
663
+ }): Promise<ApiResponse<{ messages: HistoryMessage[] }>> {
664
+ try {
665
+ const query = new URLSearchParams();
666
+ if (params?.from) query.set('from', params.from);
667
+ if (params?.to) query.set('to', params.to);
668
+ if (params?.thread) query.set('thread', params.thread);
669
+ if (params?.since) query.set('since', String(params.since));
670
+ if (params?.limit) query.set('limit', String(params.limit));
671
+ if (params?.order) query.set('order', params.order);
672
+ if (params?.search) query.set('search', params.search);
673
+
674
+ const response = await apiFetch(getApiUrl(`/api/history/messages?${query}`));
675
+ const data = await response.json();
676
+
677
+ if (response.ok) {
678
+ return { success: true, data };
679
+ }
680
+
681
+ return { success: false, error: 'Failed to fetch messages' };
682
+ } catch (_error) {
683
+ return { success: false, error: 'Network error' };
684
+ }
685
+ },
686
+
687
+ /**
688
+ * Get unique conversations (agent pairs)
689
+ */
690
+ async getHistoryConversations(): Promise<ApiResponse<{ conversations: Conversation[] }>> {
691
+ try {
692
+ const response = await apiFetch(getApiUrl('/api/history/conversations'));
693
+ const data = await response.json();
694
+
695
+ if (response.ok) {
696
+ return { success: true, data };
697
+ }
698
+
699
+ return { success: false, error: 'Failed to fetch conversations' };
700
+ } catch (_error) {
701
+ return { success: false, error: 'Network error' };
702
+ }
703
+ },
704
+
705
+ /**
706
+ * Get a single message by ID
707
+ */
708
+ async getHistoryMessage(id: string): Promise<ApiResponse<HistoryMessage>> {
709
+ try {
710
+ const response = await apiFetch(getApiUrl(`/api/history/message/${encodeURIComponent(id)}`));
711
+ const data = await response.json();
712
+
713
+ if (response.ok) {
714
+ return { success: true, data };
715
+ }
716
+
717
+ return { success: false, error: data.error || 'Failed to fetch message' };
718
+ } catch (_error) {
719
+ return { success: false, error: 'Network error' };
720
+ }
721
+ },
722
+
723
+ /**
724
+ * Get storage statistics
725
+ */
726
+ async getHistoryStats(): Promise<ApiResponse<HistoryStats>> {
727
+ try {
728
+ const response = await apiFetch(getApiUrl('/api/history/stats'));
729
+ const data = await response.json();
730
+
731
+ if (response.ok) {
732
+ return { success: true, data };
733
+ }
734
+
735
+ return { success: false, error: 'Failed to fetch stats' };
736
+ } catch (_error) {
737
+ return { success: false, error: 'Network error' };
738
+ }
739
+ },
740
+
741
+ // ===== File Search API =====
742
+
743
+ /**
744
+ * Search for files in the repository
745
+ */
746
+ async searchFiles(params?: {
747
+ query?: string;
748
+ limit?: number;
749
+ }): Promise<ApiResponse<FileSearchResponse>> {
750
+ try {
751
+ const queryParams = new URLSearchParams();
752
+ if (params?.query) queryParams.set('q', params.query);
753
+ if (params?.limit) queryParams.set('limit', String(params.limit));
754
+
755
+ const response = await apiFetch(getApiUrl(`/api/files?${queryParams}`));
756
+ const data = await response.json();
757
+
758
+ if (response.ok) {
759
+ return { success: true, data };
760
+ }
761
+
762
+ return { success: false, error: 'Failed to search files' };
763
+ } catch (_error) {
764
+ return { success: false, error: 'Network error' };
765
+ }
766
+ },
767
+
768
+ // ===== Decision Queue API =====
769
+
770
+ /**
771
+ * Get all pending decisions
772
+ */
773
+ async getDecisions(): Promise<ApiResponse<{ decisions: ApiDecision[] }>> {
774
+ try {
775
+ const response = await apiFetch(getApiUrl('/api/decisions'));
776
+ const data = await response.json();
777
+
778
+ if (response.ok && data.success) {
779
+ return { success: true, data: { decisions: data.decisions || [] } };
780
+ }
781
+
782
+ return { success: false, error: data.error || 'Failed to fetch decisions' };
783
+ } catch (_error) {
784
+ return { success: false, error: 'Network error' };
785
+ }
786
+ },
787
+
788
+ /**
789
+ * Approve a decision
790
+ */
791
+ async approveDecision(id: string, optionId?: string, response?: string): Promise<ApiResponse<void>> {
792
+ try {
793
+ const res = await apiFetch(getApiUrl(`/api/decisions/${encodeURIComponent(id)}/approve`), {
794
+ method: 'POST',
795
+ body: JSON.stringify({ optionId, response }),
796
+ });
797
+
798
+ const data = await res.json();
799
+
800
+ if (res.ok && data.success) {
801
+ return { success: true };
802
+ }
803
+
804
+ return { success: false, error: data.error || 'Failed to approve decision' };
805
+ } catch (_error) {
806
+ return { success: false, error: 'Network error' };
807
+ }
808
+ },
809
+
810
+ /**
811
+ * Reject a decision
812
+ */
813
+ async rejectDecision(id: string, reason?: string): Promise<ApiResponse<void>> {
814
+ try {
815
+ const res = await apiFetch(getApiUrl(`/api/decisions/${encodeURIComponent(id)}/reject`), {
816
+ method: 'POST',
817
+ body: JSON.stringify({ reason }),
818
+ });
819
+
820
+ const data = await res.json();
821
+
822
+ if (res.ok && data.success) {
823
+ return { success: true };
824
+ }
825
+
826
+ return { success: false, error: data.error || 'Failed to reject decision' };
827
+ } catch (_error) {
828
+ return { success: false, error: 'Network error' };
829
+ }
830
+ },
831
+
832
+ /**
833
+ * Dismiss a decision
834
+ */
835
+ async dismissDecision(id: string): Promise<ApiResponse<void>> {
836
+ try {
837
+ const res = await apiFetch(getApiUrl(`/api/decisions/${encodeURIComponent(id)}`), {
838
+ method: 'DELETE',
839
+ });
840
+
841
+ const data = await res.json();
842
+
843
+ if (res.ok && data.success) {
844
+ return { success: true };
845
+ }
846
+
847
+ return { success: false, error: data.error || 'Failed to dismiss decision' };
848
+ } catch (_error) {
849
+ return { success: false, error: 'Network error' };
850
+ }
851
+ },
852
+
853
+ // ===== Fleet Overview API =====
854
+
855
+ /**
856
+ * Get fleet servers
857
+ */
858
+ async getFleetServers(): Promise<ApiResponse<{ servers: FleetServer[] }>> {
859
+ try {
860
+ const response = await apiFetch(getApiUrl('/api/fleet/servers'));
861
+ const data = await response.json();
862
+
863
+ if (response.ok && data.success) {
864
+ return { success: true, data: { servers: data.servers || [] } };
865
+ }
866
+
867
+ return { success: false, error: data.error || 'Failed to fetch fleet servers' };
868
+ } catch (_error) {
869
+ return { success: false, error: 'Network error' };
870
+ }
871
+ },
872
+
873
+ /**
874
+ * Get fleet statistics
875
+ */
876
+ async getFleetStats(): Promise<ApiResponse<{ stats: FleetStats }>> {
877
+ try {
878
+ const response = await apiFetch(getApiUrl('/api/fleet/stats'));
879
+ const data = await response.json();
880
+
881
+ if (response.ok && data.success) {
882
+ return { success: true, data: { stats: data.stats } };
883
+ }
884
+
885
+ return { success: false, error: data.error || 'Failed to fetch fleet stats' };
886
+ } catch (_error) {
887
+ return { success: false, error: 'Network error' };
888
+ }
889
+ },
890
+
891
+ // ===== Task Assignment API =====
892
+
893
+ /**
894
+ * Get all tasks
895
+ */
896
+ async getTasks(params?: {
897
+ status?: string;
898
+ agent?: string;
899
+ }): Promise<ApiResponse<{ tasks: TaskAssignment[] }>> {
900
+ try {
901
+ const queryParams = new URLSearchParams();
902
+ if (params?.status) queryParams.set('status', params.status);
903
+ if (params?.agent) queryParams.set('agent', params.agent);
904
+
905
+ const response = await apiFetch(getApiUrl(`/api/tasks?${queryParams}`));
906
+ const data = await response.json();
907
+
908
+ if (response.ok && data.success) {
909
+ return { success: true, data: { tasks: data.tasks || [] } };
910
+ }
911
+
912
+ return { success: false, error: data.error || 'Failed to fetch tasks' };
913
+ } catch (_error) {
914
+ return { success: false, error: 'Network error' };
915
+ }
916
+ },
917
+
918
+ /**
919
+ * Create and assign a task
920
+ */
921
+ async createTask(request: {
922
+ agentName: string;
923
+ title: string;
924
+ description?: string;
925
+ priority: 'low' | 'medium' | 'high' | 'critical';
926
+ }): Promise<ApiResponse<{ task: TaskAssignment }>> {
927
+ try {
928
+ const response = await apiFetch(getApiUrl('/api/tasks'), {
929
+ method: 'POST',
930
+ body: JSON.stringify(request),
931
+ });
932
+
933
+ const data = await response.json();
934
+
935
+ if (response.ok && data.success) {
936
+ return { success: true, data: { task: data.task } };
937
+ }
938
+
939
+ return { success: false, error: data.error || 'Failed to create task' };
940
+ } catch (_error) {
941
+ return { success: false, error: 'Network error' };
942
+ }
943
+ },
944
+
945
+ /**
946
+ * Update task status
947
+ */
948
+ async updateTask(id: string, updates: {
949
+ status?: TaskAssignment['status'];
950
+ result?: string;
951
+ }): Promise<ApiResponse<{ task: TaskAssignment }>> {
952
+ try {
953
+ const response = await apiFetch(getApiUrl(`/api/tasks/${encodeURIComponent(id)}`), {
954
+ method: 'PATCH',
955
+ body: JSON.stringify(updates),
956
+ });
957
+
958
+ const data = await response.json();
959
+
960
+ if (response.ok && data.success) {
961
+ return { success: true, data: { task: data.task } };
962
+ }
963
+
964
+ return { success: false, error: data.error || 'Failed to update task' };
965
+ } catch (_error) {
966
+ return { success: false, error: 'Network error' };
967
+ }
968
+ },
969
+
970
+ /**
971
+ * Cancel a task
972
+ */
973
+ async cancelTask(id: string): Promise<ApiResponse<void>> {
974
+ try {
975
+ const response = await apiFetch(getApiUrl(`/api/tasks/${encodeURIComponent(id)}`), {
976
+ method: 'DELETE',
977
+ });
978
+
979
+ const data = await response.json();
980
+
981
+ if (response.ok && data.success) {
982
+ return { success: true };
983
+ }
984
+
985
+ return { success: false, error: data.error || 'Failed to cancel task' };
986
+ } catch (_error) {
987
+ return { success: false, error: 'Network error' };
988
+ }
989
+ },
990
+
991
+ // ===== Beads Integration API =====
992
+
993
+ /**
994
+ * Create a bead (task/issue) via the beads CLI
995
+ */
996
+ async createBead(request: {
997
+ title: string;
998
+ assignee?: string;
999
+ priority?: number;
1000
+ type?: 'task' | 'bug' | 'feature';
1001
+ description?: string;
1002
+ }): Promise<ApiResponse<{ bead: { id: string; title: string } }>> {
1003
+ try {
1004
+ const response = await apiFetch(getApiUrl('/api/beads'), {
1005
+ method: 'POST',
1006
+ body: JSON.stringify(request),
1007
+ });
1008
+
1009
+ const data = await response.json();
1010
+
1011
+ if (response.ok && data.success) {
1012
+ return { success: true, data: { bead: data.bead } };
1013
+ }
1014
+
1015
+ return { success: false, error: data.error || 'Failed to create bead' };
1016
+ } catch (_error) {
1017
+ return { success: false, error: 'Network error' };
1018
+ }
1019
+ },
1020
+
1021
+ /**
1022
+ * Send a relay message to an agent (non-interrupting notification)
1023
+ */
1024
+ async sendRelayMessage(request: {
1025
+ to: string;
1026
+ content: string;
1027
+ thread?: string;
1028
+ }): Promise<ApiResponse<{ messageId: string }>> {
1029
+ try {
1030
+ const response = await apiFetch(getApiUrl('/api/relay/send'), {
1031
+ method: 'POST',
1032
+ body: JSON.stringify(request),
1033
+ });
1034
+
1035
+ const data = await response.json();
1036
+
1037
+ if (response.ok && data.success) {
1038
+ return { success: true, data: { messageId: data.messageId } };
1039
+ }
1040
+
1041
+ return { success: false, error: data.error || 'Failed to send message' };
1042
+ } catch (_error) {
1043
+ return { success: false, error: 'Network error' };
1044
+ }
1045
+ },
1046
+
1047
+ // --- Reactions API ---
1048
+
1049
+ async addReaction(
1050
+ messageId: string,
1051
+ emoji: string,
1052
+ ): Promise<ApiResponse<void>> {
1053
+ try {
1054
+ const response = await apiFetch(
1055
+ getApiUrl(`/api/messages/${encodeURIComponent(messageId)}/reactions`),
1056
+ { method: 'POST', body: JSON.stringify({ emoji }) },
1057
+ );
1058
+ if (response.ok) return { success: true, data: undefined };
1059
+ const data = await response.json();
1060
+ return { success: false, error: data.error || 'Failed to add reaction' };
1061
+ } catch (_error) {
1062
+ return { success: false, error: 'Network error' };
1063
+ }
1064
+ },
1065
+
1066
+ async removeReaction(
1067
+ messageId: string,
1068
+ emoji: string,
1069
+ ): Promise<ApiResponse<void>> {
1070
+ try {
1071
+ const response = await apiFetch(
1072
+ getApiUrl(
1073
+ `/api/messages/${encodeURIComponent(messageId)}/reactions/${encodeURIComponent(emoji)}`,
1074
+ ),
1075
+ { method: 'DELETE' },
1076
+ );
1077
+ if (response.ok) return { success: true, data: undefined };
1078
+ const data = await response.json();
1079
+ return { success: false, error: data.error || 'Failed to remove reaction' };
1080
+ } catch (_error) {
1081
+ return { success: false, error: 'Network error' };
1082
+ }
1083
+ },
1084
+
1085
+ async getReactions(
1086
+ messageId: string,
1087
+ ): Promise<ApiResponse<{ reactions: Reaction[] }>> {
1088
+ try {
1089
+ const response = await apiFetch(
1090
+ getApiUrl(`/api/messages/${encodeURIComponent(messageId)}/reactions`),
1091
+ );
1092
+ const data = await response.json();
1093
+ if (response.ok) return { success: true, data: { reactions: data.data ?? [] } };
1094
+ return { success: false, error: data.error || 'Failed to get reactions' };
1095
+ } catch (_error) {
1096
+ return { success: false, error: 'Network error' };
1097
+ }
1098
+ },
1099
+
1100
+ // --- Thread API ---
1101
+
1102
+ async getThread(
1103
+ messageId: string,
1104
+ opts?: { cursor?: string; limit?: number },
1105
+ ): Promise<
1106
+ ApiResponse<{
1107
+ parent: Message & { reply_count: number };
1108
+ replies: Message[];
1109
+ nextCursor?: string;
1110
+ }>
1111
+ > {
1112
+ try {
1113
+ const params = new URLSearchParams();
1114
+ if (opts?.cursor) params.set('before', opts.cursor);
1115
+ if (opts?.limit) params.set('limit', String(opts.limit));
1116
+ const qs = params.toString();
1117
+ const response = await apiFetch(
1118
+ getApiUrl(
1119
+ `/api/messages/${encodeURIComponent(messageId)}/replies${qs ? `?${qs}` : ''}`,
1120
+ ),
1121
+ );
1122
+ const data = await response.json();
1123
+ if (response.ok && data.ok !== false) {
1124
+ return { success: true, data: data.data ?? data };
1125
+ }
1126
+ return { success: false, error: data.error || 'Failed to get thread' };
1127
+ } catch (_error) {
1128
+ return { success: false, error: 'Network error' };
1129
+ }
1130
+ },
1131
+
1132
+ async postReply(
1133
+ messageId: string,
1134
+ text: string,
1135
+ ): Promise<ApiResponse<Message>> {
1136
+ try {
1137
+ const response = await apiFetch(
1138
+ getApiUrl(`/api/messages/${encodeURIComponent(messageId)}/replies`),
1139
+ { method: 'POST', body: JSON.stringify({ text }) },
1140
+ );
1141
+ const data = await response.json();
1142
+ if (response.ok) return { success: true, data: data.data ?? data };
1143
+ return { success: false, error: data.error || 'Failed to post reply' };
1144
+ } catch (_error) {
1145
+ return { success: false, error: 'Network error' };
1146
+ }
1147
+ },
1148
+ };
1149
+
1150
+ // History API types
1151
+ export interface HistorySession {
1152
+ id: string;
1153
+ agentName: string;
1154
+ cli?: string;
1155
+ startedAt: string;
1156
+ endedAt?: string;
1157
+ duration: string;
1158
+ messageCount: number;
1159
+ summary?: string;
1160
+ isActive: boolean;
1161
+ closedBy?: 'agent' | 'disconnect' | 'error';
1162
+ }
1163
+
1164
+ export interface HistoryMessage {
1165
+ id: string;
1166
+ from: string;
1167
+ to: string;
1168
+ content: string;
1169
+ timestamp: string;
1170
+ thread?: string;
1171
+ isBroadcast?: boolean;
1172
+ isUrgent?: boolean;
1173
+ status?: string;
1174
+ data?: Record<string, unknown>;
1175
+ }
1176
+
1177
+ export interface Conversation {
1178
+ participants: string[];
1179
+ lastMessage: string;
1180
+ lastTimestamp: string;
1181
+ messageCount: number;
1182
+ }
1183
+
1184
+ export interface HistoryStats {
1185
+ messageCount: number | string;
1186
+ sessionCount: number | string;
1187
+ activeSessions: number | string;
1188
+ uniqueAgents: number | string;
1189
+ oldestMessageDate?: string | null;
1190
+ }
1191
+
1192
+ // File search types
1193
+ export interface FileSearchResult {
1194
+ path: string;
1195
+ name: string;
1196
+ isDirectory: boolean;
1197
+ }
1198
+
1199
+ export interface FileSearchResponse {
1200
+ files: FileSearchResult[];
1201
+ query: string;
1202
+ searchRoot: string;
1203
+ }
1204
+
1205
+ // Decision Queue types (API response format)
1206
+ export interface ApiDecision {
1207
+ id: string;
1208
+ agentName: string;
1209
+ title: string;
1210
+ description: string;
1211
+ options?: { id: string; label: string; description?: string }[];
1212
+ urgency: 'low' | 'medium' | 'high' | 'critical';
1213
+ category: 'approval' | 'choice' | 'input' | 'confirmation';
1214
+ createdAt: string;
1215
+ expiresAt?: string;
1216
+ context?: Record<string, unknown>;
1217
+ }
1218
+
1219
+ // Decision type (component format)
1220
+ export interface Decision {
1221
+ id: string;
1222
+ agentName: string;
1223
+ timestamp: string | number;
1224
+ type: 'approval' | 'choice' | 'confirmation' | 'input';
1225
+ title: string;
1226
+ description: string;
1227
+ options?: { id: string; label: string; description?: string }[];
1228
+ priority: 'low' | 'medium' | 'high' | 'critical';
1229
+ context?: Record<string, unknown>;
1230
+ expiresAt?: string | number;
1231
+ }
1232
+
1233
+ // Convert API decision to component format
1234
+ export function convertApiDecision(apiDecision: ApiDecision): Decision {
1235
+ return {
1236
+ id: apiDecision.id,
1237
+ agentName: apiDecision.agentName,
1238
+ timestamp: apiDecision.createdAt,
1239
+ type: apiDecision.category,
1240
+ title: apiDecision.title,
1241
+ description: apiDecision.description,
1242
+ options: apiDecision.options,
1243
+ priority: apiDecision.urgency,
1244
+ context: apiDecision.context,
1245
+ expiresAt: apiDecision.expiresAt,
1246
+ };
1247
+ }
1248
+
1249
+ // Fleet types
1250
+ export interface FleetServer {
1251
+ id: string;
1252
+ name: string;
1253
+ status: 'healthy' | 'degraded' | 'offline';
1254
+ agents: { name: string; status: string }[];
1255
+ cpuUsage: number;
1256
+ memoryUsage: number;
1257
+ activeConnections: number;
1258
+ uptime: number;
1259
+ lastHeartbeat: string;
1260
+ }
1261
+
1262
+ export interface FleetStats {
1263
+ totalAgents: number;
1264
+ onlineAgents: number;
1265
+ busyAgents: number;
1266
+ pendingDecisions: number;
1267
+ activeTasks: number;
1268
+ }
1269
+
1270
+ // Task Assignment types
1271
+ export interface TaskAssignment {
1272
+ id: string;
1273
+ agentName: string;
1274
+ title: string;
1275
+ description: string;
1276
+ priority: 'low' | 'medium' | 'high' | 'critical';
1277
+ status: 'pending' | 'assigned' | 'in_progress' | 'completed' | 'failed';
1278
+ createdAt: string;
1279
+ assignedAt?: string;
1280
+ completedAt?: string;
1281
+ result?: string;
1282
+ }
1283
+
1284
+ /**
1285
+ * Create a singleton WebSocket connection
1286
+ */
1287
+ let wsInstance: DashboardWebSocket | null = null;
1288
+
1289
+ export function getWebSocket(): DashboardWebSocket {
1290
+ if (!wsInstance) {
1291
+ wsInstance = new DashboardWebSocket();
1292
+ }
1293
+ return wsInstance;
1294
+ }