| 1 | import { createAsyncThunk } from "@reduxjs/toolkit"; |
| 2 | import { ContextItem } from "core"; |
| 3 | import { |
| 4 | abortStream, |
| 5 | acceptToolCall, |
| 6 | updateToolCallOutput, |
| 7 | } from "../slices/sessionSlice"; |
| 8 | import { ThunkApiType } from "../store"; |
| 9 | import { findToolCallById } from "../util"; |
| 10 | import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; |
| 11 | |
| 12 | /** |
| 13 | * This thunk is used to move a terminal command to the background |
| 14 | * when the user clicks the "Move to background" link in the UI |
| 15 | * |
| 16 | * It preserves all existing terminal output, marks the command as |
| 17 | * visually complete, and stops listening to further output from |
| 18 | * the already running process |
| 19 | */ |
| 20 | export const moveTerminalProcessToBackground = createAsyncThunk< |
| 21 | void, |
| 22 | { toolCallId: string }, |
| 23 | ThunkApiType |
| 24 | >( |
| 25 | "chat/moveTerminalProcessToBackground", |
| 26 | async ({ toolCallId }, { dispatch, getState, extra }) => { |
| 27 | // Find the current tool call using utility function |
| 28 | const state = getState(); |
| 29 | const toolCall = findToolCallById(state.session.history, toolCallId); |
| 30 | |
| 31 | if (!toolCall) { |
| 32 | console.error("Could not find tool call with ID:", toolCallId); |
| 33 | return; |
| 34 | } |
| 35 | |
| 36 | // Find existing terminal output to preserve it |
| 37 | const existingOutput = toolCall.output?.find( |
| 38 | (item) => item.name === "Terminal", |
| 39 | ); |
| 40 | const existingContent = existingOutput?.content || ""; |
| 41 | |
| 42 | const status = |
| 43 | "Command moved to background. Further output will be ignored."; |
| 44 | |
| 45 | const contextItems: ContextItem[] = [ |
| 46 | { |
| 47 | name: "Terminal", |
| 48 | description: "Terminal command output", |
| 49 | content: existingContent, |
| 50 | status: status, |
| 51 | }, |
| 52 | ]; |
| 53 | |
| 54 | // Abort any existing stream for this tool call |
| 55 | dispatch(abortStream()); |
| 56 | |
| 57 | // Update the tool call output |
| 58 | dispatch( |
| 59 | updateToolCallOutput({ |
| 60 | toolCallId, |
| 61 | contextItems, |
| 62 | }), |
| 63 | ); |
| 64 | |
| 65 | // Mark the process as backgrounded so we ignore future events |
| 66 | await extra.ideMessenger.request("process/markAsBackgrounded", { |
| 67 | toolCallId, |
| 68 | }); |
| 69 | |
| 70 | // Mark the tool call as "done" in the UI |
| 71 | // This will set isRunning to false in RunTerminalCommand.tsx |
| 72 | dispatch(acceptToolCall({ toolCallId })); |
| 73 | |
| 74 | // Trigger an LLM response about the command being moved to background |
| 75 | dispatch(updateToolCallOutput({ toolCallId, contextItems })); |
| 76 | dispatch( |
| 77 | streamResponseAfterToolCall({ |
| 78 | toolCallId, |
| 79 | }), |
| 80 | ); |
| 81 | }, |
| 82 | ); |