* Background a specific foreground task. * @returns true if backgrounded successfully, false otherwise
(taskId: string, getAppState: () => AppState, setAppState: SetAppState)
| 332 | * @returns true if backgrounded successfully, false otherwise |
| 333 | */ |
| 334 | function backgroundTask(taskId: string, getAppState: () => AppState, setAppState: SetAppState): boolean { |
| 335 | // Step 1: Get the task and shell command from current state |
| 336 | const state = getAppState(); |
| 337 | const task = state.tasks[taskId]; |
| 338 | if (!isLocalShellTask(task) || task.isBackgrounded || !task.shellCommand) { |
| 339 | return false; |
| 340 | } |
| 341 | |
| 342 | const shellCommand = task.shellCommand; |
| 343 | const description = task.description; |
| 344 | const { toolUseId, kind, agentId } = task; |
| 345 | |
| 346 | // Transition to backgrounded — TaskOutput continues receiving data automatically |
| 347 | if (!shellCommand.background(taskId)) { |
| 348 | return false; |
| 349 | } |
| 350 | |
| 351 | setAppState(prev => { |
| 352 | const prevTask = prev.tasks[taskId]; |
| 353 | if (!isLocalShellTask(prevTask) || prevTask.isBackgrounded) { |
| 354 | return prev; |
| 355 | } |
| 356 | return { |
| 357 | ...prev, |
| 358 | tasks: { |
| 359 | ...prev.tasks, |
| 360 | [taskId]: { ...prevTask, isBackgrounded: true }, |
| 361 | }, |
| 362 | }; |
| 363 | }); |
| 364 | |
| 365 | const cancelStallWatchdog = startStallWatchdog(taskId, description, kind, toolUseId, agentId); |
| 366 | |
| 367 | // Set up result handler |
| 368 | void shellCommand.result.then(async result => { |
| 369 | cancelStallWatchdog(); |
| 370 | await flushAndCleanup(shellCommand); |
| 371 | let wasKilled = false; |
| 372 | let cleanupFn: (() => void) | undefined; |
| 373 | |
| 374 | updateTaskState<LocalShellTaskState>(taskId, setAppState, t => { |
| 375 | if (t.status === 'killed') { |
| 376 | wasKilled = true; |
| 377 | return t; |
| 378 | } |
| 379 | |
| 380 | // Capture cleanup function to call outside of updater |
| 381 | cleanupFn = t.unregisterCleanup; |
| 382 | |
| 383 | return { |
| 384 | ...t, |
| 385 | status: result.code === 0 ? 'completed' : 'failed', |
| 386 | result: { code: result.code, interrupted: result.interrupted }, |
| 387 | shellCommand: null, |
| 388 | unregisterCleanup: undefined, |
| 389 | endTime: Date.now(), |
| 390 | }; |
| 391 | }); |
no test coverage detected