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