* Background a specific foreground task. * @returns true if backgrounded successfully, false otherwise
(taskId: string, getAppState: () => AppState, setAppState: SetAppState)
| 291 | * @returns true if backgrounded successfully, false otherwise |
| 292 | */ |
| 293 | function backgroundTask(taskId: string, getAppState: () => AppState, setAppState: SetAppState): boolean { |
| 294 | // Step 1: Get the task and shell command from current state |
| 295 | const state = getAppState(); |
| 296 | const task = state.tasks[taskId]; |
| 297 | if (!isLocalShellTask(task) || task.isBackgrounded || !task.shellCommand) { |
| 298 | return false; |
| 299 | } |
| 300 | const shellCommand = task.shellCommand; |
| 301 | const description = task.description; |
| 302 | const { |
| 303 | toolUseId, |
| 304 | kind, |
| 305 | agentId |
| 306 | } = task; |
| 307 | |
| 308 | // Transition to backgrounded — TaskOutput continues receiving data automatically |
| 309 | if (!shellCommand.background(taskId)) { |
| 310 | return false; |
| 311 | } |
| 312 | setAppState(prev => { |
| 313 | const prevTask = prev.tasks[taskId]; |
| 314 | if (!isLocalShellTask(prevTask) || prevTask.isBackgrounded) { |
| 315 | return prev; |
| 316 | } |
| 317 | return { |
| 318 | ...prev, |
| 319 | tasks: { |
| 320 | ...prev.tasks, |
| 321 | [taskId]: { |
| 322 | ...prevTask, |
| 323 | isBackgrounded: true |
| 324 | } |
| 325 | } |
| 326 | }; |
| 327 | }); |
| 328 | const cancelStallWatchdog = startStallWatchdog(taskId, description, kind, toolUseId, agentId); |
| 329 | |
| 330 | // Set up result handler |
| 331 | void shellCommand.result.then(async result => { |
| 332 | cancelStallWatchdog(); |
| 333 | await flushAndCleanup(shellCommand); |
| 334 | let wasKilled = false; |
| 335 | let cleanupFn: (() => void) | undefined; |
| 336 | updateTaskState<LocalShellTaskState>(taskId, setAppState, t => { |
| 337 | if (t.status === 'killed') { |
| 338 | wasKilled = true; |
| 339 | return t; |
| 340 | } |
| 341 | |
| 342 | // Capture cleanup function to call outside of updater |
| 343 | cleanupFn = t.unregisterCleanup; |
| 344 | return { |
| 345 | ...t, |
| 346 | status: result.code === 0 ? 'completed' : 'failed', |
| 347 | result: { |
| 348 | code: result.code, |
| 349 | interrupted: result.interrupted |
| 350 | }, |
no test coverage detected