(eventName: string, backgroundFn?: (shellId: string) => void)
| 784 | |
| 785 | // Helper to start backgrounding with logging |
| 786 | function startBackgrounding(eventName: string, backgroundFn?: (shellId: string) => void): void { |
| 787 | // If a foreground task is already registered (via registerForeground in the |
| 788 | // progress loop), background it in-place instead of re-spawning. Re-spawning |
| 789 | // would overwrite tasks[taskId], emit a duplicate task_started SDK event, |
| 790 | // and leak the first cleanup callback. |
| 791 | if (foregroundTaskId) { |
| 792 | if (!backgroundExistingForegroundTask(foregroundTaskId, shellCommand, description || command, setAppState, toolUseId)) { |
| 793 | return; |
| 794 | } |
| 795 | backgroundShellId = foregroundTaskId; |
| 796 | logEvent(eventName, { |
| 797 | command_type: getCommandTypeForLogging(command) |
| 798 | }); |
| 799 | backgroundFn?.(foregroundTaskId); |
| 800 | return; |
| 801 | } |
| 802 | |
| 803 | // No foreground task registered — spawn a new background task |
| 804 | // Note: spawn is essentially synchronous despite being async |
| 805 | void spawnBackgroundTask().then(shellId => { |
| 806 | backgroundShellId = shellId; |
| 807 | |
| 808 | // Wake the generator's Promise.race so it sees backgroundShellId. |
| 809 | // Without this, the generator waits for the current setTimeout to fire |
| 810 | // (up to ~1s) before noticing the backgrounding. Matches BashTool. |
| 811 | const resolve = resolveProgress; |
| 812 | if (resolve) { |
| 813 | resolveProgress = null; |
| 814 | resolve(); |
| 815 | } |
| 816 | logEvent(eventName, { |
| 817 | command_type: getCommandTypeForLogging(command) |
| 818 | }); |
| 819 | if (backgroundFn) { |
| 820 | backgroundFn(shellId); |
| 821 | } |
| 822 | }); |
| 823 | } |
| 824 | |
| 825 | // Set up auto-backgrounding on timeout if enabled |
| 826 | if (shellCommand.onTimeout && shouldAutoBackground) { |
no test coverage detected