(
ws: WebSocket,
channelId: string,
agent: IPackAgent,
)
| 475 | // ------------------------------------------------------------------------- |
| 476 | |
| 477 | private handleWsConnection( |
| 478 | ws: WebSocket, |
| 479 | channelId: string, |
| 480 | agent: IPackAgent, |
| 481 | ): void { |
| 482 | this.addSocket(channelId, ws); |
| 483 | |
| 484 | ws.on("message", async (data) => { |
| 485 | try { |
| 486 | const payload = JSON.parse(data.toString()); |
| 487 | if (!payload.text) return; |
| 488 | |
| 489 | const text: string = payload.text; |
| 490 | |
| 491 | // Check for bot commands |
| 492 | const command = parseCommand(text); |
| 493 | if (command) { |
| 494 | const result = await agent.handleCommand(command, channelId); |
| 495 | |
| 496 | // sendWsEvent(ws, { type: "agent_start" }); |
| 497 | // sendWsEvent(ws, { type: "message_start", role: "assistant" }); |
| 498 | |
| 499 | if (result.message) { |
| 500 | sendWsEvent(ws, { type: "text_delta", delta: result.message }); |
| 501 | } |
| 502 | |
| 503 | // sendWsEvent(ws, { type: "message_end", role: "assistant" }); |
| 504 | // sendWsEvent(ws, { type: "agent_end" }); |
| 505 | ws.send(JSON.stringify({ done: true })); |
| 506 | return; |
| 507 | } |
| 508 | |
| 509 | // Regular message → stream events via WebSocket |
| 510 | const onEvent = (event: AgentEvent) => { |
| 511 | sendWsEvent(ws, event); |
| 512 | this.ipcBroadcaster?.broadcastAgentEvent(channelId, event); |
| 513 | }; |
| 514 | |
| 515 | const result = await agent.handleMessage("web", channelId, text, onEvent); |
| 516 | |
| 517 | if (result.errorMessage) { |
| 518 | ws.send(JSON.stringify({ error: result.errorMessage })); |
| 519 | return; |
| 520 | } |
| 521 | |
| 522 | ws.send(JSON.stringify({ done: true })); |
| 523 | } catch (err) { |
| 524 | ws.send(JSON.stringify({ error: String(err) })); |
| 525 | } |
| 526 | }); |
| 527 | |
| 528 | ws.on("close", () => { |
| 529 | this.removeSocket(channelId, ws); |
| 530 | if (channelId !== DEFAULT_WEB_CHANNEL_ID) { |
| 531 | agent.dispose(channelId); |
| 532 | } |
| 533 | }); |
| 534 | } |
no test coverage detected