-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathExtensionChannel.ts
More file actions
236 lines (203 loc) · 7.14 KB
/
ExtensionChannel.ts
File metadata and controls
236 lines (203 loc) · 7.14 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
import type { Socket } from "socket.io-client"
import {
type TaskProviderLike,
type TaskProviderEvents,
type ExtensionInstance,
type ExtensionBridgeCommand,
type ExtensionBridgeEvent,
RooCodeEventName,
TaskStatus,
ExtensionBridgeCommandName,
ExtensionBridgeEventName,
ExtensionSocketEvents,
HEARTBEAT_INTERVAL_MS,
} from "@roo-code/types"
import { BaseChannel } from "./BaseChannel.js"
/**
* Manages the extension-level communication channel.
* Handles extension registration, heartbeat, and extension-specific commands.
*/
export class ExtensionChannel extends BaseChannel<
ExtensionBridgeCommand,
ExtensionSocketEvents,
ExtensionBridgeEvent | ExtensionInstance
> {
private userId: string
private provider: TaskProviderLike
private extensionInstance: ExtensionInstance
private heartbeatInterval: NodeJS.Timeout | null = null
private eventListeners: Map<RooCodeEventName, (...args: unknown[]) => void> = new Map()
constructor(instanceId: string, userId: string, provider: TaskProviderLike) {
super(instanceId)
this.userId = userId
this.provider = provider
this.extensionInstance = {
instanceId: this.instanceId,
userId: this.userId,
workspacePath: this.provider.cwd,
appProperties: this.provider.appProperties,
gitProperties: this.provider.gitProperties,
lastHeartbeat: Date.now(),
task: {
taskId: "",
taskStatus: TaskStatus.None,
},
taskHistory: [],
}
this.setupListeners()
}
public async handleCommand(command: ExtensionBridgeCommand): Promise<void> {
if (command.instanceId !== this.instanceId) {
console.log(`[ExtensionChannel] command -> instance id mismatch | ${this.instanceId}`, {
messageInstanceId: command.instanceId,
})
return
}
switch (command.type) {
case ExtensionBridgeCommandName.StartTask: {
console.log(`[ExtensionChannel] command -> createTask() | ${command.instanceId}`, {
text: command.payload.text?.substring(0, 100) + "...",
hasImages: !!command.payload.images,
mode: command.payload.mode,
providerProfile: command.payload.providerProfile,
})
this.provider.createTask(
command.payload.text,
command.payload.images,
undefined, // parentTask
undefined, // options
{ mode: command.payload.mode, currentApiConfigName: command.payload.providerProfile },
)
break
}
case ExtensionBridgeCommandName.StopTask: {
const instance = await this.updateInstance()
if (instance.task.taskStatus === TaskStatus.Running) {
console.log(`[ExtensionChannel] command -> cancelTask() | ${command.instanceId}`)
this.provider.cancelTask()
this.provider.postStateToWebview()
} else if (instance.task.taskId) {
console.log(`[ExtensionChannel] command -> clearTask() | ${command.instanceId}`)
this.provider.clearTask()
this.provider.postStateToWebview()
}
break
}
case ExtensionBridgeCommandName.ResumeTask: {
console.log(`[ExtensionChannel] command -> resumeTask() | ${command.instanceId}`, {
taskId: command.payload.taskId,
})
this.provider.resumeTask(command.payload.taskId)
this.provider.postStateToWebview()
break
}
}
}
protected async handleConnect(socket: Socket): Promise<void> {
await this.registerInstance(socket)
this.startHeartbeat(socket)
}
protected async handleReconnect(socket: Socket): Promise<void> {
await this.registerInstance(socket)
this.startHeartbeat(socket)
}
protected override handleDisconnect(): void {
this.stopHeartbeat()
}
protected async handleCleanup(socket: Socket): Promise<void> {
this.stopHeartbeat()
this.cleanupListeners()
await this.unregisterInstance(socket)
}
private async registerInstance(_socket: Socket): Promise<void> {
const instance = await this.updateInstance()
await this.publish(ExtensionSocketEvents.REGISTER, instance)
}
private async unregisterInstance(_socket: Socket): Promise<void> {
const instance = await this.updateInstance()
await this.publish(ExtensionSocketEvents.UNREGISTER, instance)
}
private startHeartbeat(socket: Socket): void {
this.stopHeartbeat()
this.heartbeatInterval = setInterval(async () => {
const instance = await this.updateInstance()
try {
socket.emit(ExtensionSocketEvents.HEARTBEAT, instance)
// Heartbeat is too frequent to log
} catch (error) {
console.error(
`[ExtensionChannel] emit() failed -> ${ExtensionSocketEvents.HEARTBEAT}: ${
error instanceof Error ? error.message : String(error)
}`,
)
}
}, HEARTBEAT_INTERVAL_MS)
}
private stopHeartbeat(): void {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval)
this.heartbeatInterval = null
}
}
private setupListeners(): void {
const eventMapping = [
{ from: RooCodeEventName.TaskCreated, to: ExtensionBridgeEventName.TaskCreated },
{ from: RooCodeEventName.TaskStarted, to: ExtensionBridgeEventName.TaskStarted },
{ from: RooCodeEventName.TaskCompleted, to: ExtensionBridgeEventName.TaskCompleted },
{ from: RooCodeEventName.TaskAborted, to: ExtensionBridgeEventName.TaskAborted },
{ from: RooCodeEventName.TaskFocused, to: ExtensionBridgeEventName.TaskFocused },
{ from: RooCodeEventName.TaskUnfocused, to: ExtensionBridgeEventName.TaskUnfocused },
{ from: RooCodeEventName.TaskActive, to: ExtensionBridgeEventName.TaskActive },
{ from: RooCodeEventName.TaskInteractive, to: ExtensionBridgeEventName.TaskInteractive },
{ from: RooCodeEventName.TaskResumable, to: ExtensionBridgeEventName.TaskResumable },
{ from: RooCodeEventName.TaskIdle, to: ExtensionBridgeEventName.TaskIdle },
] as const
eventMapping.forEach(({ from, to }) => {
// Create and store the listener function for cleanup.
const listener = async (..._args: unknown[]) => {
this.publish(ExtensionSocketEvents.EVENT, {
type: to,
instance: await this.updateInstance(),
timestamp: Date.now(),
})
}
this.eventListeners.set(from, listener)
this.provider.on(from, listener)
})
}
private cleanupListeners(): void {
this.eventListeners.forEach((listener, eventName) => {
// Cast is safe because we only store valid event names from eventMapping.
this.provider.off(eventName as keyof TaskProviderEvents, listener)
})
this.eventListeners.clear()
}
private async updateInstance(): Promise<ExtensionInstance> {
const task = this.provider?.getCurrentTask()
const taskHistory = this.provider?.getRecentTasks() ?? []
const mode = await this.provider?.getMode()
const modes = (await this.provider?.getModes()) ?? []
const providerProfile = await this.provider?.getProviderProfile()
const providerProfiles = (await this.provider?.getProviderProfiles()) ?? []
this.extensionInstance = {
...this.extensionInstance,
appProperties: this.extensionInstance.appProperties ?? this.provider.appProperties,
gitProperties: this.extensionInstance.gitProperties ?? this.provider.gitProperties,
lastHeartbeat: Date.now(),
task: task
? {
taskId: task.taskId,
taskStatus: task.taskStatus,
...task.metadata,
}
: { taskId: "", taskStatus: TaskStatus.None },
taskAsk: task?.taskAsk,
taskHistory,
mode,
providerProfile,
modes,
providerProfiles,
}
return this.extensionInstance
}
}