summaryrefslogtreecommitdiffhomepage
path: root/packages/transport-ws/src/extension.ts
blob: 56bd8e28404085ca716dc717056acd5a464d66f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/**
 * Shell — thin imperative layer that owns the Bun.serve WebSocket server.
 *
 * All decision logic lives in router.ts (pure, unit-tested).
 * This file handles I/O only: WS accept, JSON parse/stringify,
 * provider.subscribe wiring, orchestrator turn-streaming, server lifecycle.
 */

import type { Extension, HostAPI } from "@dispatch/kernel";
import type { SessionOrchestrator } from "@dispatch/session-orchestrator";
import {
	conversationCompacted,
	conversationOpened,
	conversationStatusChanged,
	sessionOrchestratorHandle,
} from "@dispatch/session-orchestrator";
import type { SurfaceContext, SurfaceProvider, SurfaceRegistry } from "@dispatch/surface-registry";
import { surfaceRegistryHandle } from "@dispatch/surface-registry";
import type { WsClientMessage, WsServerMessage } from "@dispatch/transport-contract";
import { manifest } from "./manifest.js";
import { catalogMessage, routeClientMessage, subKey } from "./router.js";

/** Active provider subscriptions + chat subscription disposers for a single WS connection. */
interface ConnectionState {
	readonly subs: Set<string>;
	readonly providerDisposers: Map<string, () => void>;
	/** Per-conversation chat subscription disposers (orchestrator.subscribe). */
	readonly chatSubscriptions: Map<string, () => void>;
}

type Ws = Bun.ServerWebSocket<ConnectionState>;

export function createTransportWsExtension(): Extension {
	let server: ReturnType<typeof Bun.serve<ConnectionState>> | undefined;
	/** Every currently-connected WS client — used for global fan-out broadcasts. */
	const connections = new Set<Ws>();
	/** Disposers for host hook subscriptions (drained on deactivate). */
	const disposers: Array<() => void> = [];

	return {
		manifest,
		async activate(host: HostAPI) {
			const registry: SurfaceRegistry = host.getService(surfaceRegistryHandle);
			const orchestrator: SessionOrchestrator = host.getService(sessionOrchestratorHandle);
			const logger = host.logger;
			const port = host.config.get<number>("surfaceWsPort") ?? 24205;

			function send(ws: Ws, msg: WsServerMessage): void {
				try {
					ws.send(JSON.stringify(msg));
				} catch {
					// Connection may have been dropped; swallow.
				}
			}

			/** Broadcast a message to EVERY connected WS client (global fan-out). */
			function broadcast(msg: WsServerMessage): void {
				for (const ws of connections) {
					send(ws, msg);
				}
			}

			/**
			 * Ensure this connection is subscribed to a conversation's chat events.
			 * Idempotent — no-op if already subscribed. The orchestrator replays
			 * buffered events to new subscribers (late-join), then streams live.
			 */
			function ensureChatSubscribed(ws: Ws, state: ConnectionState, conversationId: string): void {
				if (state.chatSubscriptions.has(conversationId)) {
					return;
				}
				const unsubscribe = orchestrator.subscribe(conversationId, (event) => {
					send(ws, { type: "chat.delta", event });
				});
				state.chatSubscriptions.set(conversationId, unsubscribe);
			}

			function subscribeToProvider(
				ws: Ws,
				provider: SurfaceProvider,
				surfaceId: string,
				conversationId: string | undefined,
				state: ConnectionState,
			): void {
				const key = subKey(surfaceId, conversationId);
				if (!provider.subscribe || state.providerDisposers.has(key)) {
					return;
				}
				const context: SurfaceContext | undefined =
					conversationId !== undefined ? { conversationId } : undefined;
				const dispose = provider.subscribe(() => {
					try {
						const spec = provider.getSpec(context);
						if (spec instanceof Promise) {
							spec
								.then((s) =>
									send(ws, {
										type: "update",
										update: {
											surfaceId,
											spec: s,
											...(conversationId !== undefined ? { conversationId } : {}),
										},
									}),
								)
								.catch(() => {});
						} else {
							send(ws, {
								type: "update",
								update: {
									surfaceId,
									spec,
									...(conversationId !== undefined ? { conversationId } : {}),
								},
							});
						}
					} catch {
						// Provider threw — log but don't kill the connection.
					}
				});
				state.providerDisposers.set(key, dispose);
			}

			function unsubscribeFromProvider(state: ConnectionState, key: string): void {
				const dispose = state.providerDisposers.get(key);
				if (dispose) {
					dispose();
					state.providerDisposers.delete(key);
				}
			}

			// Broadcast a `conversation.open` WS message to ALL connected clients
			// whenever the orchestrator signals a conversation was opened (e.g. the
			// CLI `--open` flag). The frontend decides whether to open/focus a tab —
			// the backend just signals. This is a GLOBAL fan-out (like the catalog),
			// NOT a per-conversation chat broadcast. The payload's `workspaceId`
			// is the conversation's actual persisted workspace (resolved by the
			// orchestrator from the store), so a frontend opens/focuses the tab in
			// the correct workspace.
			disposers.push(
				host.on(conversationOpened, ({ conversationId, workspaceId }) => {
					broadcast({ type: "conversation.open", conversationId, workspaceId });
				}),
			);

			// Broadcast `conversation.statusChanged` to all connected clients so
			// tabs sync across devices in real time. `workspaceId` is the
			// conversation's actual persisted workspace (resolved by the
			// orchestrator from the store), forwarded so a frontend syncs the tab
			// in the correct workspace.
			disposers.push(
				host.on(conversationStatusChanged, ({ conversationId, status, workspaceId }) => {
					broadcast({
						type: "conversation.statusChanged",
						conversationId,
						status,
						workspaceId,
					});
				}),
			);

			// Broadcast `conversation.compacted` to all connected clients so
			// the FE reloads the conversation history after compaction.
			disposers.push(
				host.on(
					conversationCompacted,
					({ conversationId, newConversationId, messagesSummarized, messagesKept }) => {
						broadcast({
							type: "conversation.compacted",
							conversationId,
							newConversationId,
							messagesSummarized,
							messagesKept,
						});
					},
				),
			);

			server = Bun.serve<ConnectionState>({
				port,
				fetch(req, srv) {
					const initial: ConnectionState = {
						subs: new Set(),
						providerDisposers: new Map(),
						chatSubscriptions: new Map(),
					};
					if (srv.upgrade(req, { data: initial })) return;
					return new Response("expected websocket", { status: 426 });
				},
				websocket: {
					open(ws) {
						connections.add(ws);
						logger.debug("transport-ws: connection open");
						send(ws, catalogMessage(registry));
					},

					message(ws, message) {
						const state = ws.data;
						if (!state) return;

						let parsed: WsClientMessage;
						try {
							parsed = JSON.parse(String(message)) as WsClientMessage;
						} catch {
							send(ws, { type: "error", message: "Invalid JSON" });
							return;
						}

						const result = routeClientMessage(registry, state.subs, parsed);

						switch (result.kind) {
							case "surface": {
								// Log surface-op errors (unknown surface or invoke failure).
								for (const reply of result.replies) {
									if (reply.type === "error") {
										logger.warn?.("transport-ws: surface-op error", {
											...(reply.surfaceId !== undefined ? { surfaceId: reply.surfaceId } : {}),
											reason: reply.message,
										});
									}
								}

								// Apply sub change.
								if (result.subChange) {
									const key = subKey(result.subChange.surfaceId, result.subChange.conversationId);
									if (result.subChange.op === "add") {
										state.subs.add(key);
										const provider = registry.getSurface(result.subChange.surfaceId);
										if (provider) {
											subscribeToProvider(
												ws,
												provider,
												result.subChange.surfaceId,
												result.subChange.conversationId,
												state,
											);
										}
									} else {
										state.subs.delete(key);
										unsubscribeFromProvider(state, key);
									}
								}

								// Send replies.
								for (const reply of result.replies) {
									send(ws, reply);
								}

								// Perform invoke if signalled.
								if (result.invoke) {
									const provider = registry.getSurface(result.invoke.surfaceId);
									if (provider) {
										const context: SurfaceContext | undefined =
											result.invoke.conversationId !== undefined
												? { conversationId: result.invoke.conversationId }
												: undefined;
										try {
											const r = provider.invoke(
												result.invoke.actionId,
												result.invoke.payload,
												context,
											);
											if (r instanceof Promise) {
												r.catch(() => {});
											}
										} catch (err: unknown) {
											const reason = err instanceof Error ? err.message : "invoke failed";
											logger.warn?.("transport-ws: surface-op error", {
												surfaceId: result.invoke.surfaceId,
												actionId: result.invoke.actionId,
												reason,
											});
										}
									}
								}
								break;
							}

							case "chat": {
								const resolvedId = result.conversationId ?? crypto.randomUUID();
								// Auto-subscribe the sender so it sees the turn's events.
								ensureChatSubscribed(ws, state, resolvedId);
								// Start the turn detached from this connection.
								const startResult = orchestrator.startTurn({
									conversationId: resolvedId,
									text: result.message,
									...(result.model !== undefined ? { modelName: result.model } : {}),
									...(result.cwd !== undefined ? { cwd: result.cwd } : {}),
									...(result.reasoningEffort !== undefined
										? { reasoningEffort: result.reasoningEffort }
										: {}),
									...(result.workspaceId !== undefined ? { workspaceId: result.workspaceId } : {}),
									...(result.computerId !== undefined ? { computerId: result.computerId } : {}),
								});
								if (!startResult.started) {
									send(ws, {
										type: "chat.error",
										conversationId: resolvedId,
										message: "a turn is already generating for this conversation",
									});
								} else {
									logger.info?.("transport-ws: chat.send accepted", {
										conversationId: resolvedId,
										model: result.model ?? null,
									});
								}
								break;
							}

							case "chat-subscribe": {
								ensureChatSubscribed(ws, state, result.conversationId);
								break;
							}

							case "chat-unsubscribe": {
								const dispose = state.chatSubscriptions.get(result.conversationId);
								if (dispose) {
									dispose();
									state.chatSubscriptions.delete(result.conversationId);
								}
								break;
							}

							case "chat-queue": {
								// Fire-and-forget: success is confirmed by the message-queue
								// SURFACE updating (startedTurn:false) or by streaming
								// chat.deltas (startedTurn:true), NOT by a reply here. On
								// startedTurn:true the sender is auto-subscribed so the new
								// turn's events stream to it (same as chat.send); on
								// startedTurn:false (queued for steering) we emit NOTHING
								// back and do not auto-subscribe.
								const enqueueResult = orchestrator.enqueue({
									conversationId: result.conversationId,
									text: result.text,
									...(result.workspaceId !== undefined ? { workspaceId: result.workspaceId } : {}),
								});
								if (enqueueResult.startedTurn) {
									ensureChatSubscribed(ws, state, result.conversationId);
								}
								logger.info?.("transport-ws: chat.queue accepted", {
									conversationId: result.conversationId,
									startedTurn: enqueueResult.startedTurn,
								});
								break;
							}

							case "chat-error": {
								logger.warn?.("transport-ws: malformed chat.send", {
									reason: result.errorMessage,
									...(result.conversationId !== undefined
										? { conversationId: result.conversationId }
										: {}),
								});
								send(ws, {
									type: "chat.error",
									...(result.conversationId !== undefined
										? { conversationId: result.conversationId }
										: {}),
									message: result.errorMessage,
								});
								break;
							}
						}
					},

					close(ws) {
						connections.delete(ws);
						const state = ws.data;
						if (state) {
							// Dispose all chat subscriptions (does NOT abort turns).
							for (const dispose of state.chatSubscriptions.values()) {
								dispose();
							}
							state.chatSubscriptions.clear();
							// Dispose surface provider subscriptions.
							for (const dispose of state.providerDisposers.values()) {
								dispose();
							}
						}
						logger.debug("transport-ws: connection close");
					},
				},
			});

			logger.info?.("transport-ws: surface WebSocket listening", { port });
		},

		deactivate() {
			for (const dispose of disposers) {
				dispose();
			}
			disposers.length = 0;
			connections.clear();
			if (server) {
				server.stop();
				server = undefined;
			}
		},
	};
}