( description: string, setAppState: SetAppState, mainThreadAgentDefinition?: AgentDefinition, existingAbortController?: AbortController, )
| 92 | * @returns Object with task ID and abort signal for stopping the background query |
| 93 | */ |
| 94 | export function registerMainSessionTask( |
| 95 | description: string, |
| 96 | setAppState: SetAppState, |
| 97 | mainThreadAgentDefinition?: AgentDefinition, |
| 98 | existingAbortController?: AbortController, |
| 99 | ): { taskId: string; abortSignal: AbortSignal } { |
| 100 | const taskId = generateMainSessionTaskId() |
| 101 | |
| 102 | // Link output to an isolated per-task transcript file (same layout as |
| 103 | // sub-agents). Do NOT use getTranscriptPath() — that's the main session's |
| 104 | // file, and writing there from a background query after /clear would corrupt |
| 105 | // the post-clear conversation. The isolated path lets this task survive |
| 106 | // /clear: the symlink re-link in clearConversation handles session ID changes. |
| 107 | void initTaskOutputAsSymlink( |
| 108 | taskId, |
| 109 | getAgentTranscriptPath(asAgentId(taskId)), |
| 110 | ) |
| 111 | |
| 112 | // Use the existing abort controller if provided (important for backgrounding an active query) |
| 113 | // This ensures that aborting the task will abort the actual query |
| 114 | const abortController = existingAbortController ?? createAbortController() |
| 115 | |
| 116 | const unregisterCleanup = registerCleanup(async () => { |
| 117 | // Clean up on process exit |
| 118 | setAppState(prev => { |
| 119 | const { [taskId]: removed, ...rest } = prev.tasks |
| 120 | return { ...prev, tasks: rest } |
| 121 | }) |
| 122 | }) |
| 123 | |
| 124 | // Use provided agent definition or default |
| 125 | const selectedAgent = mainThreadAgentDefinition ?? DEFAULT_MAIN_SESSION_AGENT |
| 126 | |
| 127 | // Create task state - already backgrounded since this is called when user backgrounds |
| 128 | const taskState: LocalMainSessionTaskState = { |
| 129 | ...createTaskStateBase(taskId, 'local_agent', description), |
| 130 | type: 'local_agent', |
| 131 | status: 'running', |
| 132 | agentId: taskId, |
| 133 | prompt: description, |
| 134 | selectedAgent, |
| 135 | agentType: 'main-session', |
| 136 | abortController, |
| 137 | unregisterCleanup, |
| 138 | retrieved: false, |
| 139 | lastReportedToolCount: 0, |
| 140 | lastReportedTokenCount: 0, |
| 141 | isBackgrounded: true, // Already backgrounded |
| 142 | pendingMessages: [], |
| 143 | retain: false, |
| 144 | diskLoaded: false, |
| 145 | } |
| 146 | |
| 147 | logForDebugging( |
| 148 | `[LocalMainSessionTask] Registering task ${taskId} with description: ${description}`, |
| 149 | ) |
| 150 | registerTask(taskState, setAppState) |
| 151 |
no test coverage detected