-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathTaskChannel.ts
More file actions
228 lines (194 loc) · 6.46 KB
/
TaskChannel.ts
File metadata and controls
228 lines (194 loc) · 6.46 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
import type { Socket } from "socket.io-client"
import {
type ClineMessage,
type TaskEvents,
type TaskLike,
type TaskBridgeCommand,
type TaskBridgeEvent,
type JoinResponse,
type LeaveResponse,
RooCodeEventName,
TaskBridgeEventName,
TaskBridgeCommandName,
TaskSocketEvents,
} from "@roo-code/types"
import { BaseChannel } from "./BaseChannel.js"
type TaskEventListener = {
[K in keyof TaskEvents]: (...args: TaskEvents[K]) => void | Promise<void>
}[keyof TaskEvents]
type TaskEventMapping = {
from: keyof TaskEvents
to: TaskBridgeEventName
createPayload: (task: TaskLike, ...args: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any
}
/**
* Manages task-level communication channels.
* Handles task subscriptions, messaging, and task-specific commands.
*/
export class TaskChannel extends BaseChannel<
TaskBridgeCommand,
TaskSocketEvents,
TaskBridgeEvent | { taskId: string }
> {
private subscribedTasks: Map<string, TaskLike> = new Map()
private pendingTasks: Map<string, TaskLike> = new Map()
private taskListeners: Map<string, Map<TaskBridgeEventName, TaskEventListener>> = new Map()
private readonly eventMapping: readonly TaskEventMapping[] = [
{
from: RooCodeEventName.Message,
to: TaskBridgeEventName.Message,
createPayload: (task: TaskLike, data: { action: string; message: ClineMessage }) => ({
type: TaskBridgeEventName.Message,
taskId: task.taskId,
action: data.action,
message: data.message,
}),
},
{
from: RooCodeEventName.TaskModeSwitched,
to: TaskBridgeEventName.TaskModeSwitched,
createPayload: (task: TaskLike, mode: string) => ({
type: TaskBridgeEventName.TaskModeSwitched,
taskId: task.taskId,
mode,
}),
},
{
from: RooCodeEventName.TaskInteractive,
to: TaskBridgeEventName.TaskInteractive,
createPayload: (task: TaskLike, _taskId: string) => ({
type: TaskBridgeEventName.TaskInteractive,
taskId: task.taskId,
}),
},
] as const
constructor(instanceId: string) {
super(instanceId)
}
public handleCommand(command: TaskBridgeCommand): void {
const task = this.subscribedTasks.get(command.taskId)
if (!task) {
console.error(`[TaskChannel] Unable to find task ${command.taskId}`)
return
}
switch (command.type) {
case TaskBridgeCommandName.Message:
console.log(
`[TaskChannel] ${TaskBridgeCommandName.Message} ${command.taskId} -> submitUserMessage()`,
command,
)
task.submitUserMessage(command.payload.text, command.payload.images)
break
case TaskBridgeCommandName.ApproveAsk:
console.log(
`[TaskChannel] ${TaskBridgeCommandName.ApproveAsk} ${command.taskId} -> approveAsk()`,
command,
)
task.approveAsk(command.payload)
break
case TaskBridgeCommandName.DenyAsk:
console.log(`[TaskChannel] ${TaskBridgeCommandName.DenyAsk} ${command.taskId} -> denyAsk()`, command)
task.denyAsk(command.payload)
break
}
}
protected async handleConnect(socket: Socket): Promise<void> {
// Rejoin all subscribed tasks.
for (const taskId of this.subscribedTasks.keys()) {
await this.publish(TaskSocketEvents.JOIN, { taskId })
}
// Subscribe to any pending tasks.
for (const task of this.pendingTasks.values()) {
await this.subscribeToTask(task, socket)
}
this.pendingTasks.clear()
}
protected async handleReconnect(_socket: Socket): Promise<void> {
// Rejoin all subscribed tasks.
for (const taskId of this.subscribedTasks.keys()) {
await this.publish(TaskSocketEvents.JOIN, { taskId })
}
}
protected async handleCleanup(socket: Socket): Promise<void> {
const unsubscribePromises = []
for (const taskId of this.subscribedTasks.keys()) {
unsubscribePromises.push(this.unsubscribeFromTask(taskId, socket))
}
await Promise.allSettled(unsubscribePromises)
this.subscribedTasks.clear()
this.taskListeners.clear()
this.pendingTasks.clear()
}
/**
* Add a task to the pending queue (will be subscribed when connected).
*/
public addPendingTask(task: TaskLike): void {
this.pendingTasks.set(task.taskId, task)
}
public async subscribeToTask(task: TaskLike, _socket: Socket): Promise<void> {
const taskId = task.taskId
await this.publish(TaskSocketEvents.JOIN, { taskId }, (response: JoinResponse) => {
if (response.success) {
console.log(`[TaskChannel#subscribeToTask] subscribed to ${taskId}`)
this.subscribedTasks.set(taskId, task)
this.setupTaskListeners(task)
} else {
console.error(`[TaskChannel#subscribeToTask] failed to subscribe to ${taskId}: ${response.error}`)
}
})
}
public async unsubscribeFromTask(taskId: string, _socket: Socket): Promise<void> {
const task = this.subscribedTasks.get(taskId)
await this.publish(TaskSocketEvents.LEAVE, { taskId }, (response: LeaveResponse) => {
if (response.success) {
console.log(`[TaskChannel#unsubscribeFromTask] unsubscribed from ${taskId}`, response)
} else {
console.error(`[TaskChannel#unsubscribeFromTask] failed to unsubscribe from ${taskId}`)
}
// If we failed to unsubscribe then something is probably wrong and
// we should still discard this task from `subscribedTasks`.
if (task) {
this.removeTaskListeners(task)
this.subscribedTasks.delete(taskId)
}
})
}
private setupTaskListeners(task: TaskLike): void {
if (this.taskListeners.has(task.taskId)) {
console.warn("[TaskChannel] Listeners already exist for task, removing old listeners:", task.taskId)
this.removeTaskListeners(task)
}
const listeners = new Map<TaskBridgeEventName, TaskEventListener>()
this.eventMapping.forEach(({ from, to, createPayload }) => {
const listener = (...args: unknown[]) => {
const payload = createPayload(task, ...args)
this.publish(TaskSocketEvents.EVENT, payload)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
task.on(from, listener as any)
listeners.set(to, listener)
})
this.taskListeners.set(task.taskId, listeners)
}
private removeTaskListeners(task: TaskLike): void {
const listeners = this.taskListeners.get(task.taskId)
if (!listeners) {
return
}
this.eventMapping.forEach(({ from, to }) => {
const listener = listeners.get(to)
if (listener) {
try {
task.off(from, listener as any) // eslint-disable-line @typescript-eslint/no-explicit-any
} catch (error) {
console.error(
`[TaskChannel] task.off(${from}) failed for task ${task.taskId}: ${
error instanceof Error ? error.message : String(error)
}`,
)
}
}
})
this.taskListeners.delete(task.taskId)
}
}