-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathBridgeOrchestrator.ts
More file actions
313 lines (261 loc) · 9.12 KB
/
BridgeOrchestrator.ts
File metadata and controls
313 lines (261 loc) · 9.12 KB
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
import crypto from "crypto"
import {
type TaskProviderLike,
type TaskLike,
type CloudUserInfo,
type ExtensionBridgeCommand,
type TaskBridgeCommand,
ConnectionState,
ExtensionSocketEvents,
TaskSocketEvents,
} from "@roo-code/types"
import { SocketTransport } from "./SocketTransport.js"
import { ExtensionChannel } from "./ExtensionChannel.js"
import { TaskChannel } from "./TaskChannel.js"
export interface BridgeOrchestratorOptions {
userId: string
socketBridgeUrl: string
token: string
provider: TaskProviderLike
sessionId?: string
}
/**
* Central orchestrator for the extension bridge system.
* Coordinates communication between the VSCode extension and web application
* through WebSocket connections and manages extension/task channels.
*/
export class BridgeOrchestrator {
private static instance: BridgeOrchestrator | null = null
private static pendingTask: TaskLike | null = null
// Core
private readonly userId: string
private readonly socketBridgeUrl: string
private readonly token: string
private readonly provider: TaskProviderLike
private readonly instanceId: string
// Components
private socketTransport: SocketTransport
private extensionChannel: ExtensionChannel
private taskChannel: TaskChannel
// Reconnection
private readonly MAX_RECONNECT_ATTEMPTS = Infinity
private readonly RECONNECT_DELAY = 1_000
private readonly RECONNECT_DELAY_MAX = 30_000
public static getInstance(): BridgeOrchestrator | null {
return BridgeOrchestrator.instance
}
public static isEnabled(user?: CloudUserInfo | null, remoteControlEnabled?: boolean): boolean {
return !!(user?.id && user.extensionBridgeEnabled && remoteControlEnabled)
}
public static async connectOrDisconnect(
userInfo: CloudUserInfo | null,
remoteControlEnabled: boolean | undefined,
options?: BridgeOrchestratorOptions,
): Promise<void> {
const isEnabled = BridgeOrchestrator.isEnabled(userInfo, remoteControlEnabled)
const instance = BridgeOrchestrator.instance
if (isEnabled) {
if (!instance) {
if (!options) {
console.error(
`[BridgeOrchestrator#connectOrDisconnect] Cannot connect: options are required for connection`,
)
return
}
try {
console.log(`[BridgeOrchestrator#connectOrDisconnect] Connecting...`)
BridgeOrchestrator.instance = new BridgeOrchestrator(options)
await BridgeOrchestrator.instance.connect()
} catch (error) {
console.error(
`[BridgeOrchestrator#connectOrDisconnect] connect() failed: ${error instanceof Error ? error.message : String(error)}`,
)
}
} else {
if (
instance.connectionState === ConnectionState.FAILED ||
instance.connectionState === ConnectionState.DISCONNECTED
) {
console.log(
`[BridgeOrchestrator#connectOrDisconnect] Re-connecting... (state: ${instance.connectionState})`,
)
instance.reconnect().catch((error) => {
console.error(
`[BridgeOrchestrator#connectOrDisconnect] reconnect() failed: ${error instanceof Error ? error.message : String(error)}`,
)
})
} else {
console.log(
`[BridgeOrchestrator#connectOrDisconnect] Already connected or connecting (state: ${instance.connectionState})`,
)
}
}
} else {
if (instance) {
try {
console.log(
`[BridgeOrchestrator#connectOrDisconnect] Disconnecting... (state: ${instance.connectionState})`,
)
await instance.disconnect()
} catch (error) {
console.error(
`[BridgeOrchestrator#connectOrDisconnect] disconnect() failed: ${error instanceof Error ? error.message : String(error)}`,
)
} finally {
BridgeOrchestrator.instance = null
}
} else {
console.log(`[BridgeOrchestrator#connectOrDisconnect] Already disconnected`)
}
}
}
/**
* @TODO: What if subtasks also get spawned? We'd probably want deferred
* subscriptions for those too.
*/
public static async subscribeToTask(task: TaskLike): Promise<void> {
const instance = BridgeOrchestrator.instance
if (instance && instance.socketTransport.isConnected()) {
console.log(`[BridgeOrchestrator#subscribeToTask] Subscribing to task ${task.taskId}`)
await instance.subscribeToTask(task)
} else {
console.log(`[BridgeOrchestrator#subscribeToTask] Deferring subscription for task ${task.taskId}`)
BridgeOrchestrator.pendingTask = task
}
}
private constructor(options: BridgeOrchestratorOptions) {
this.userId = options.userId
this.socketBridgeUrl = options.socketBridgeUrl
this.token = options.token
this.provider = options.provider
this.instanceId = options.sessionId || crypto.randomUUID()
this.socketTransport = new SocketTransport({
url: this.socketBridgeUrl,
socketOptions: {
query: {
token: this.token,
clientType: "extension",
instanceId: this.instanceId,
},
transports: ["websocket", "polling"],
reconnection: true,
reconnectionAttempts: this.MAX_RECONNECT_ATTEMPTS,
reconnectionDelay: this.RECONNECT_DELAY,
reconnectionDelayMax: this.RECONNECT_DELAY_MAX,
},
onConnect: () => this.handleConnect(),
onDisconnect: () => this.handleDisconnect(),
onReconnect: () => this.handleReconnect(),
})
this.extensionChannel = new ExtensionChannel(this.instanceId, this.userId, this.provider)
this.taskChannel = new TaskChannel(this.instanceId)
}
private setupSocketListeners() {
const socket = this.socketTransport.getSocket()
if (!socket) {
console.error("[BridgeOrchestrator] Socket not available")
return
}
// Remove any existing listeners first to prevent duplicates.
socket.off(ExtensionSocketEvents.RELAYED_COMMAND)
socket.off(TaskSocketEvents.RELAYED_COMMAND)
socket.off("connected")
socket.on(ExtensionSocketEvents.RELAYED_COMMAND, (message: ExtensionBridgeCommand) => {
console.log(
`[BridgeOrchestrator] on(${ExtensionSocketEvents.RELAYED_COMMAND}) -> ${message.type} for ${message.instanceId}`,
)
this.extensionChannel?.handleCommand(message)
})
socket.on(TaskSocketEvents.RELAYED_COMMAND, (message: TaskBridgeCommand) => {
console.log(
`[BridgeOrchestrator] on(${TaskSocketEvents.RELAYED_COMMAND}) -> ${message.type} for ${message.taskId}`,
)
this.taskChannel.handleCommand(message)
})
}
private async handleConnect() {
const socket = this.socketTransport.getSocket()
if (!socket) {
console.error("[BridgeOrchestrator#handleConnect] Socket not available")
return
}
await this.extensionChannel.onConnect(socket)
await this.taskChannel.onConnect(socket)
if (BridgeOrchestrator.pendingTask) {
console.log(
`[BridgeOrchestrator#handleConnect] Subscribing to task ${BridgeOrchestrator.pendingTask.taskId}`,
)
try {
await this.subscribeToTask(BridgeOrchestrator.pendingTask)
BridgeOrchestrator.pendingTask = null
} catch (error) {
console.error(
`[BridgeOrchestrator#handleConnect] subscribeToTask() failed: ${error instanceof Error ? error.message : String(error)}`,
)
}
}
}
private handleDisconnect() {
this.extensionChannel.onDisconnect()
this.taskChannel.onDisconnect()
}
private async handleReconnect() {
const socket = this.socketTransport.getSocket()
if (!socket) {
console.error("[BridgeOrchestrator] Socket not available after reconnect")
return
}
// Re-setup socket listeners to ensure they're properly configured
// after automatic reconnection (Socket.IO's built-in reconnection)
// The socket.off() calls in setupSocketListeners prevent duplicates
this.setupSocketListeners()
await this.extensionChannel.onReconnect(socket)
await this.taskChannel.onReconnect(socket)
}
// Task API
public async subscribeToTask(task: TaskLike): Promise<void> {
const socket = this.socketTransport.getSocket()
if (!socket || !this.socketTransport.isConnected()) {
console.warn("[BridgeOrchestrator] Cannot subscribe to task: not connected. Will retry when connected.")
this.taskChannel.addPendingTask(task)
if (
this.connectionState === ConnectionState.DISCONNECTED ||
this.connectionState === ConnectionState.FAILED
) {
await this.connect()
}
return
}
await this.taskChannel.subscribeToTask(task, socket)
}
public async unsubscribeFromTask(taskId: string): Promise<void> {
const socket = this.socketTransport.getSocket()
if (!socket) {
return
}
await this.taskChannel.unsubscribeFromTask(taskId, socket)
}
// Shared API
public get connectionState(): ConnectionState {
return this.socketTransport.getConnectionState()
}
private async connect(): Promise<void> {
// Populate the app and git properties before registering the instance.
await this.provider.getTelemetryProperties()
await this.socketTransport.connect()
this.setupSocketListeners()
}
public async disconnect(): Promise<void> {
await this.extensionChannel.cleanup(this.socketTransport.getSocket())
await this.taskChannel.cleanup(this.socketTransport.getSocket())
await this.socketTransport.disconnect()
BridgeOrchestrator.instance = null
BridgeOrchestrator.pendingTask = null
}
public async reconnect(): Promise<void> {
await this.socketTransport.reconnect()
// After a manual reconnect, we have a new socket instance
// so we need to set up listeners again.
this.setupSocketListeners()
}
}