| 163 | const localUnlisten: UnlistenFn[] = []; |
| 164 | |
| 165 | const setup = async () => { |
| 166 | const unlistenChatDone = await listen<string>('chat-done', (event) => { |
| 167 | clearStreaming(); |
| 168 | if (event.payload === 'cancelled') return; |
| 169 | const sessionId = useSessionStore.getState().activeSessionId; |
| 170 | if (sessionId) { |
| 171 | invoke<Message[]>('get_messages', { sessionId }) |
| 172 | .then((msgs) => { |
| 173 | useChatStore.getState().setMessages(msgs); |
| 174 | autoRenameSession(sessionId); |
| 175 | }) |
| 176 | .catch(console.error); |
| 177 | } |
| 178 | }); |
| 179 | |
| 180 | const unlistenChatError = await listen<string>('chat-error', (event) => { |
| 181 | console.error('Chat error:', event.payload); |
| 182 | clearStreaming(); |
| 183 | }); |
| 184 | |
| 185 | const unlistenChatUsage = await listen<ChatUsageEvent>('chat-usage', (event) => { |
| 186 | addTokenUsage(event.payload.sessionId, event.payload.usage); |
| 187 | }); |
| 188 | |
| 189 | const unlistenAgentStarted = await listen<{ |
| 190 | agentRunId: string; |
| 191 | agentType: string; |
| 192 | parentAgentRunId: string | null; |
| 193 | }>('agent-started', (event) => { |
| 194 | const { agentRunId, agentType, parentAgentRunId } = event.payload; |
| 195 | if (useAgentStore.getState().agentRuns.some((r) => r.id === agentRunId)) { |
| 196 | return; |
| 197 | } |
| 198 | |
| 199 | const now = new Date().toISOString(); |
| 200 | const newRun: AgentRunWithTools = { |
| 201 | id: agentRunId, |
| 202 | sessionId: useSessionStore.getState().activeSessionId ?? '', |
| 203 | agentType: agentType as AgentType, |
| 204 | status: 'running', |
| 205 | input: undefined, |
| 206 | output: undefined, |
| 207 | error: undefined, |
| 208 | startedAt: now, |
| 209 | completedAt: undefined, |
| 210 | createdAt: now, |
| 211 | toolCalls: [], |
| 212 | streamingText: '', |
| 213 | thinkingBlocks: [], |
| 214 | parentAgentRunId: parentAgentRunId, |
| 215 | projectPath: null, |
| 216 | }; |
| 217 | addAgentRun(newRun); |
| 218 | }); |
| 219 | |
| 220 | const unlistenAgentToken = await listen<{ agentRunId: string; token: string }>( |
| 221 | 'agent-token', |
| 222 | (event) => { |