Refactor Terminal Module (#7966)

* refactor: move terminal integration from core to vscode host

- Relocate terminal-related code from core/integrations to hosts/vscode/terminal
- Move TerminalManager, TerminalProcess, TerminalRegistry, and related utilities
- Update import paths across the codebase to reference new locations
- Remove unused shellIntegrationWarningTracker and shouldShowBackgroundTerminalSuggestion from Controller
- This change better separates VSCode-specific terminal handling from core logic

* Mistral change

* refactor: consolidate terminal types into types.ts

- Move ActiveBackgroundCommand, AskResponse, CommandExecutorCallbacks, CommandExecutorConfig from ICommandExecutor.ts to types.ts
- Move OrchestrationOptions, OrchestrationResult from CommandOrchestrator.ts to types.ts
- Delete ICommandExecutor.ts (all types now in types.ts)
- Update imports in CommandExecutor.ts, CommandOrchestrator.ts, index.ts, and src/core/task/index.ts
- types.ts is now the single source of truth for all terminal-related types

* refactor: consolidate ITerminalProcess into types.ts

- Move ITerminalProcess, TerminalProcessEvents from ITerminalProcess.ts to types.ts
- Delete ITerminalProcess.ts (all types now in types.ts)
- Update imports in VscodeTerminalProcess.ts, StandaloneTerminalProcess.ts
- Update exports in index.ts
- types.ts is now the single source of truth for ALL terminal-related types
This commit is contained in:
Ara authored and GitHub committed 2025-12-11 12:11:32 -08:00
1 parent bce403476e
commit 8ce476ccaa
14 files changed
+959 -506

No files matched your search

-38
View File
@@ -81,12 +81,6 @@ export class Controller {
// Flag to prevent duplicate cancellations from spam clicking
private cancelInProgress = false
// Shell integration warning tracker
private shellIntegrationWarningTracker: {
timestamps: number[]
lastSuggestionShown?: number
} = { timestamps: [] }
// Timer for periodic remote config fetching
private remoteConfigTimer?: NodeJS.Timeout
@@ -515,38 +509,6 @@ export class Controller {
}
}
/**
* Check if we should show the background terminal suggestion based on shell integration warning frequency
* @returns true if we should show the suggestion, false otherwise
*/
shouldShowBackgroundTerminalSuggestion(): boolean {
const oneHourAgo = Date.now() - 60 * 60 * 1000
// Clean old timestamps (older than 1 hour)
this.shellIntegrationWarningTracker.timestamps = this.shellIntegrationWarningTracker.timestamps.filter(
(ts) => ts > oneHourAgo,
)
// Add current warning
this.shellIntegrationWarningTracker.timestamps.push(Date.now())
// Check if we've shown suggestion recently (within last hour)
if (
this.shellIntegrationWarningTracker.lastSuggestionShown &&
Date.now() - this.shellIntegrationWarningTracker.lastSuggestionShown < 60 * 60 * 1000
) {
return false
}
// Show suggestion if 3+ warnings in last hour
if (this.shellIntegrationWarningTracker.timestamps.length >= 3) {
this.shellIntegrationWarningTracker.lastSuggestionShown = Date.now()
return true
}
return false
}
async handleAuthCallback(customToken: string, provider: string | null = null) {
try {
await this.authService.handleAuthCallback(customToken, provider ? provider : "google")
+1 -1
View File
@@ -1,6 +1,5 @@
import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker"
import * as extractTextModule from "@integrations/misc/extract-text"
import * as terminalModule from "@integrations/terminal/get-latest-output"
import { UrlContentFetcher } from "@services/browser/UrlContentFetcher"
import * as gitModule from "@utils/git"
import { expect } from "chai"
@@ -9,6 +8,7 @@ import * as isBinaryFileModule from "isbinaryfile"
import * as path from "path"
import * as sinon from "sinon"
import { HostProvider } from "@/hosts/host-provider"
import * as terminalModule from "@/hosts/vscode/terminal/get-latest-output"
import { setVscodeHostProviderMock } from "@/test/host-provider-test-utils"
import { parseMentions } from "."
+1 -1
View File
@@ -1,7 +1,6 @@
import { diagnosticsToProblemsString } from "@integrations/diagnostics"
import { extractTextFromFile } from "@integrations/misc/extract-text"
import { openFile } from "@integrations/misc/open-file"
import { getLatestTerminalOutput } from "@integrations/terminal/get-latest-output"
import { UrlContentFetcher } from "@services/browser/UrlContentFetcher"
import { telemetryService } from "@services/telemetry"
import { mentionRegexGlobal } from "@shared/context-mentions"
@@ -12,6 +11,7 @@ import fs from "fs/promises"
import { isBinaryFile } from "isbinaryfile"
import * as path from "path"
import { HostProvider } from "@/hosts/host-provider"
import { getLatestTerminalOutput } from "@/hosts/vscode/terminal/get-latest-output"
import { ShowMessageType } from "@/shared/proto/host/window"
import { DiagnosticSeverity } from "@/shared/proto/index.cline"
import { isDirectory } from "@/utils/fs"
+51 -426
View File
@@ -46,6 +46,7 @@ import { showSystemNotification } from "@integrations/notifications"
import { ITerminalManager } from "@integrations/terminal/types"
import { BrowserSession } from "@services/browser/BrowserSession"
import { UrlContentFetcher } from "@services/browser/UrlContentFetcher"
import { featureFlagsService } from "@services/feature-flags"
import { listFiles } from "@services/glob/list-files"
import { Logger } from "@services/logging/Logger"
import { McpHub } from "@services/mcp/McpHub"
@@ -53,14 +54,7 @@ import { ApiConfiguration } from "@shared/api"
import { findLast, findLastIndex } from "@shared/array"
import { combineApiRequests } from "@shared/combineApiRequests"
import { combineCommandSequences } from "@shared/combineCommandSequences"
import {
ClineApiReqCancelReason,
ClineApiReqInfo,
ClineAsk,
ClineMessage,
ClineSay,
COMMAND_CANCEL_TOKEN,
} from "@shared/ExtensionMessage"
import { ClineApiReqCancelReason, ClineApiReqInfo, ClineAsk, ClineMessage, ClineSay } from "@shared/ExtensionMessage"
import { HistoryItem } from "@shared/HistoryItem"
import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@shared/Languages"
import { USER_CONTENT_TAGS } from "@shared/messages/constants"
@@ -79,12 +73,10 @@ import * as vscode from "vscode"
import type { SystemPromptContext } from "@/core/prompts/system-prompt"
import { getSystemPrompt } from "@/core/prompts/system-prompt"
import { HostProvider } from "@/hosts/host-provider"
import { TerminalProcessResultPromise } from "@/hosts/vscode/terminal/VscodeTerminalProcess"
import { isSubagentCommand, transformClineCommand } from "@/integrations/cli-subagents/subagent_command"
import { StandaloneTerminalManager } from "@/integrations/terminal"
import { CommandExecutorCallbacks, StandaloneTerminalManager } from "@/integrations/terminal"
import { CommandExecutor, FullCommandExecutorConfig } from "@/integrations/terminal/CommandExecutor"
import { ClineError, ClineErrorType, ErrorService } from "@/services/error"
import { featureFlagsService } from "@/services/feature-flags"
import { TerminalHangStage, TerminalUserInterventionAction, telemetryService } from "@/services/telemetry"
import { telemetryService } from "@/services/telemetry"
import {
ClineAssistantContent,
ClineContent,
@@ -97,7 +89,6 @@ import {
} from "@/shared/messages"
import { ShowMessageType } from "@/shared/proto/index.host"
import { isClineCliInstalled, isCliSubagentContext } from "@/utils/cli-detector"
import { isInTestMode } from "../../services/test/TestMode"
import { ensureLocalClineDirExists } from "../context/instructions/user-instructions/rule-helpers"
import { refreshWorkflowToggles } from "../context/instructions/user-instructions/workflows"
import { Controller } from "../controller"
@@ -216,13 +207,6 @@ export class Task {
private streamHandler: StreamResponseHandler
private terminalExecutionMode: "vscodeTerminal" | "backgroundExec"
private activeBackgroundCommand?: {
process: TerminalProcessResultPromise & {
terminate?: () => void
}
command: string
outputLines: string[]
}
// Metadata tracking
private fileContextTracker: FileContextTracker
@@ -250,6 +234,9 @@ export class Task {
// Task Locking (Sqlite)
private taskLockAcquired: boolean
// Command executor for running shell commands (extracted from executeCommandTool)
private commandExecutor!: CommandExecutor
constructor(params: TaskParams) {
const {
controller,
@@ -497,6 +484,40 @@ export class Task {
telemetryService.captureTaskCreated(this.ulid, currentProvider, openAiCompatibleDomain)
}
// Initialize command executor with config and callbacks
const commandExecutorConfig: FullCommandExecutorConfig = {
cwd: this.cwd,
terminalExecutionMode: this.terminalExecutionMode,
terminalManager: this.terminalManager,
taskId: this.taskId,
ulid: this.ulid,
}
const commandExecutorCallbacks: CommandExecutorCallbacks = {
say: this.say.bind(this) as CommandExecutorCallbacks["say"],
ask: async (type: string, text?: string, partial?: boolean) => {
const result = await this.ask(type as ClineAsk, text, partial)
return {
response: result.response,
text: result.text,
images: result.images,
files: result.files,
}
},
updateBackgroundCommandState: (isRunning: boolean) =>
this.controller.updateBackgroundCommandState(isRunning, this.taskId),
updateClineMessage: async (index: number, updates: { commandCompleted?: boolean }) => {
await this.messageStateHandler.updateClineMessage(index, updates)
},
getClineMessages: () => this.messageStateHandler.getClineMessages() as Array<{ ask?: string; say?: string }>,
addToUserMessageContent: (content: { type: string; text: string }) => {
// Cast to ClineTextContentBlock which is compatible with ClineContent
this.taskState.userMessageContent.push({ type: "text", text: content.text } as ClineTextContentBlock)
},
}
this.commandExecutor = new CommandExecutor(commandExecutorConfig, commandExecutorCallbacks)
this.toolExecutor = new ToolExecutor(
this.controller.context,
this.taskState,
@@ -1352,7 +1373,7 @@ export class Task {
}
// Run if there's active background command (work happening now)
if (this.activeBackgroundCommand) {
if (this.commandExecutor.hasActiveBackgroundCommand()) {
return true
}
@@ -1406,9 +1427,9 @@ export class Task {
}
}
if (this.activeBackgroundCommand) {
if (this.commandExecutor.hasActiveBackgroundCommand()) {
try {
await this.cancelBackgroundCommand()
await this.commandExecutor.cancelBackgroundCommand()
} catch (error) {
Logger.error("Failed to cancel background command during task abort", error)
}
@@ -1525,410 +1546,15 @@ export class Task {
// Tools
async executeCommandTool(command: string, timeoutSeconds: number | undefined): Promise<[boolean, ClineToolResponseContent]> {
// For Cline CLI subagents, we want to parse and process the command to ensure flags are correct
const isSubagent = isSubagentCommand(command)
if (transformClineCommand(command) !== command && isSubagent) {
command = transformClineCommand(command)
}
// Strip leading `cd` to workspace from command
// TODO - feed this back to the model to discourage redundant `cd` usage in subsequent commands. For now we re just stripping it for better UX
const workspaceCdPrefix = `cd ${this.cwd} && `
if (command.startsWith(workspaceCdPrefix)) {
command = command.substring(workspaceCdPrefix.length)
}
const subAgentStartTime = isSubagent ? performance.now() : 0
Logger.info("IS_TEST: " + isInTestMode())
// Force subagents to use background terminal (hidden execution)
Logger.info("Executing command in terminal: " + command)
let terminalManager: ITerminalManager
if (isSubagent || this.terminalExecutionMode === "backgroundExec") {
// Use StandaloneTerminalManager for hidden background execution (subagents and backgroundExec mode)
terminalManager = new StandaloneTerminalManager()
Logger.info(
`[Task ${this.taskId}] Using StandaloneTerminalManager for ${isSubagent ? "subagent" : "backgroundExec"} command: ${command}`,
)
} else {
// Use the configured terminal manager for regular commands (VSCode terminal)
terminalManager = this.terminalManager
}
const terminalInfo = await terminalManager.getOrCreateTerminal(this.cwd)
terminalInfo.terminal.show() // weird visual bug when creating new terminals (even manually) where there's an empty space at the top.
// Use `as any` to handle type incompatibility between VSCode's Thenable and Promise
// Both TerminalInfo types have the same runtime structure, the difference is purely TypeScript
const process = terminalManager.runCommand(terminalInfo as any, command)
// Track command execution for both terminal modes
this.controller.updateBackgroundCommandState(true, this.taskId)
if (this.terminalExecutionMode === "backgroundExec") {
this.activeBackgroundCommand = { process: process as any, command, outputLines: [] }
}
const clearCommandState = async () => {
if (this.terminalExecutionMode === "backgroundExec") {
if (this.activeBackgroundCommand?.process !== process) {
return
}
this.activeBackgroundCommand = undefined
}
this.controller.updateBackgroundCommandState(false, this.taskId)
// Mark the command message as completed
const clineMessages = this.messageStateHandler.getClineMessages()
const lastCommandIndex = findLastIndex(clineMessages, (m) => m.ask === "command" || m.say === "command")
if (lastCommandIndex !== -1) {
await this.messageStateHandler.updateClineMessage(lastCommandIndex, {
commandCompleted: true,
})
}
}
process.once("completed", clearCommandState)
process.once("error", clearCommandState)
process
// process.continue() will complete the process promise, letting exeuction continue. therefore the command should not be considered 'completed', since it could still be running in the background
// .finally(() => {
// clearCommandState()
// })
.catch(() => {
clearCommandState()
})
let userFeedback: { text?: string; images?: string[]; files?: string[] } | undefined
let didContinue = false
let didCancelViaUi = false
// Chunked terminal output buffering
const CHUNK_LINE_COUNT = 20
const CHUNK_BYTE_SIZE = 2048 // 2KB
const CHUNK_DEBOUNCE_MS = 100
let outputBuffer: string[] = []
let outputBufferSize: number = 0
let chunkTimer: NodeJS.Timeout | null = null
// Track if buffer gets stuck (correlated with PROCESS_WHILE_RUNNING to indicate genuine technical issues)
let bufferStuckTimer: NodeJS.Timeout | null = null
const BUFFER_STUCK_TIMEOUT_MS = 6000 // 6 seconds
const flushBuffer = async (force = false) => {
if (outputBuffer.length === 0) {
if (force) {
// If force is true, flush anyway
} else {
return
}
}
const chunk = outputBuffer.join("\n")
outputBuffer = []
outputBufferSize = 0
// Start timer to detect if buffer gets stuck
bufferStuckTimer = setTimeout(() => {
telemetryService.captureTerminalHang(TerminalHangStage.BUFFER_STUCK)
bufferStuckTimer = null
}, BUFFER_STUCK_TIMEOUT_MS)
try {
const { response, text, images, files } = await this.ask("command_output", chunk)
if (response === "yesButtonClicked") {
// Track when user clicks "Process while Running"
telemetryService.captureTerminalUserIntervention(TerminalUserInterventionAction.PROCESS_WHILE_RUNNING)
// proceed while running - but still capture user feedback if provided
if (text || (images && images.length > 0) || (files && files.length > 0)) {
userFeedback = { text, images, files }
}
} else if (response === "noButtonClicked" && text === COMMAND_CANCEL_TOKEN) {
telemetryService.captureTerminalUserIntervention(TerminalUserInterventionAction.CANCELLED)
didCancelViaUi = true
userFeedback = undefined
} else {
userFeedback = { text, images, files }
}
didContinue = true
process.continue()
if (didCancelViaUi) {
outputBuffer = []
outputBufferSize = 0
await this.say("command_output", "Command cancelled")
}
// If more output accumulated, flush again
if (!didCancelViaUi && outputBuffer.length > 0) {
await flushBuffer()
}
} catch {
Logger.error("Error while asking for command output")
} finally {
// If the command finishes execution before the 'command_output' ask promise resolves (in other words before the user responded to the ask, which is expected when the command finishes execution first), this block is reached. This is expected and safe to ignore, as no further handling is required.
// Clear the stuck timer
if (bufferStuckTimer) {
clearTimeout(bufferStuckTimer)
bufferStuckTimer = null
}
}
}
const scheduleFlush = () => {
if (chunkTimer) {
clearTimeout(chunkTimer)
}
chunkTimer = setTimeout(async () => await flushBuffer(), CHUNK_DEBOUNCE_MS)
}
const outputLines: string[] = []
process.on("line", async (line) => {
if (didCancelViaUi) {
return
}
outputLines.push(line)
// Track output in activeBackgroundCommand for cancellation
if (this.terminalExecutionMode === "backgroundExec" && this.activeBackgroundCommand) {
this.activeBackgroundCommand.outputLines.push(line)
}
// Apply buffered streaming for both vscodeTerminal and backgroundExec modes
if (!didContinue) {
outputBuffer.push(line)
outputBufferSize += Buffer.byteLength(line, "utf8")
// Flush if buffer is large enough
if (outputBuffer.length >= CHUNK_LINE_COUNT || outputBufferSize >= CHUNK_BYTE_SIZE) {
await flushBuffer()
} else {
scheduleFlush()
}
} else {
// For backgroundExec mode, stream output directly to UI after user continues
// For vscodeTerminal mode, this maintains existing behavior
this.say("command_output", line)
}
})
let completed = false
let completionTimer: NodeJS.Timeout | null = null
const COMPLETION_TIMEOUT_MS = 6000 // 6 seconds
// Start timer to detect if waiting for completion takes too long
completionTimer = setTimeout(() => {
if (!completed) {
telemetryService.captureTerminalHang(TerminalHangStage.WAITING_FOR_COMPLETION)
completionTimer = null
}
}, COMPLETION_TIMEOUT_MS)
process.once("completed", async () => {
completed = true
//await this.say("shell_integration_warning_with_suggestion")
// Clear the completion timer
if (completionTimer) {
clearTimeout(completionTimer)
completionTimer = null
}
// Flush any remaining buffered output
if (!didContinue && outputBuffer.length > 0) {
if (chunkTimer) {
clearTimeout(chunkTimer)
chunkTimer = null
}
await flushBuffer(true)
}
})
process.once("no_shell_integration", async () => {
const shouldShowSuggestion = this.controller.shouldShowBackgroundTerminalSuggestion()
if (shouldShowSuggestion) {
await this.say("shell_integration_warning_with_suggestion")
} else {
await this.say("shell_integration_warning")
}
})
//await process
if (!didCancelViaUi) {
if (timeoutSeconds) {
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => {
reject(new Error("COMMAND_TIMEOUT"))
}, timeoutSeconds * 1000)
})
try {
await Promise.race([process, timeoutPromise])
} catch (error) {
// This will continue running the command in the background
didContinue = true
process.continue()
// Clear all our timers
if (chunkTimer) {
clearTimeout(chunkTimer)
chunkTimer = null
}
if (completionTimer) {
clearTimeout(completionTimer)
completionTimer = null
}
// Process any output we captured before timeout
await setTimeoutPromise(50)
const result = terminalManager.processOutput(outputLines, undefined, isSubagent)
if (error.message === "COMMAND_TIMEOUT") {
return [
false,
`Command execution timed out after ${timeoutSeconds} seconds. ${result.length > 0 ? `\nOutput so far:\n${result}` : ""}`,
]
}
// Re-throw other errors
throw error
}
} else {
await process
}
}
// Clear timer if process completes normally
if (completionTimer) {
clearTimeout(completionTimer)
completionTimer = null
}
// Wait for a short delay to ensure all messages are sent to the webview
// This delay allows time for non-awaited promises to be created and
// for their associated messages to be sent to the webview, maintaining
// the correct order of messages (although the webview is smart about
// grouping command_output messages despite any gaps anyways)
if (!didCancelViaUi) {
await setTimeoutPromise(50)
}
const result = terminalManager.processOutput(outputLines, undefined, isSubagent)
if (didCancelViaUi) {
return [
true,
formatResponse.toolResult(
`Command cancelled. ${result.length > 0 ? `\nOutput captured before cancellation:\n${result}` : ""}`,
),
]
}
// Capture subagent telemetry if this was a subagent command
if (isSubagent && subAgentStartTime > 0) {
const durationMs = Math.round(performance.now() - subAgentStartTime)
telemetryService.captureSubagentExecution(this.ulid, durationMs, outputLines.length, completed)
}
if (userFeedback) {
await this.say("user_feedback", userFeedback.text, userFeedback.images, userFeedback.files)
let fileContentString = ""
if (userFeedback.files && userFeedback.files.length > 0) {
fileContentString = await processFilesIntoText(userFeedback.files)
}
return [
true,
formatResponse.toolResult(
`Command is still running in the user's terminal.${
result.length > 0 ? `\nHere's the output so far:\n${result}` : ""
}\n\nThe user provided the following feedback:\n<feedback>\n${userFeedback.text}\n</feedback>`,
userFeedback.images,
fileContentString,
),
]
}
if (completed) {
return [false, `Command executed.${result.length > 0 ? `\nOutput:\n${result}` : ""}`]
} else {
return [
false,
`Command is still running in the user's terminal.${
result.length > 0 ? `\nHere's the output so far:\n${result}` : ""
}\n\nYou will be updated on the terminal status and new output in the future.`,
]
}
return this.commandExecutor.execute(command, timeoutSeconds)
}
/**
* Cancel a background command that is running in the background
* @returns true if a command was cancelled, false if no command was running
*/
public async cancelBackgroundCommand(): Promise<boolean> {
if (this.terminalExecutionMode !== "backgroundExec" || !this.activeBackgroundCommand) {
return false
}
const { process, command, outputLines } = this.activeBackgroundCommand
this.activeBackgroundCommand = undefined
this.controller.updateBackgroundCommandState(false, this.taskId)
try {
// Try to terminate the process if the method exists
if (typeof process.terminate === "function") {
try {
await process.terminate()
Logger.info(`Terminated background command: ${command}`)
} catch (error) {
Logger.error(`Error terminating background command: ${command}`, error)
}
}
// Ensure any pending operations complete
if (typeof process.continue === "function") {
try {
process.continue()
} catch (error) {
Logger.error(`Error continuing background command: ${command}`, error)
}
}
// Mark the command message as completed in the UI
const clineMessages = this.messageStateHandler.getClineMessages()
const lastCommandIndex = findLastIndex(clineMessages, (m) => m.ask === "command" || m.say === "command")
if (lastCommandIndex !== -1) {
await this.messageStateHandler.updateClineMessage(lastCommandIndex, {
commandCompleted: true,
})
}
// Process the captured output to include in the cancellation message
const processedOutput = this.terminalManager.processOutput(outputLines, undefined, isSubagentCommand(command))
// Add cancellation information to the API conversation history
// This ensures the agent knows the command was cancelled in the next request
let cancellationMessage = `Command "${command}" was cancelled by the user.`
if (processedOutput.length > 0) {
cancellationMessage += `\n\nOutput captured before cancellation:\n${processedOutput}`
}
this.taskState.userMessageContent.push({
type: "text",
text: cancellationMessage,
})
return true
} catch (error) {
Logger.error("Error in cancelBackgroundCommand", error)
return false
} finally {
try {
await this.say("command_output", "Command execution has been cancelled.")
} catch (error) {
Logger.error("Failed to send cancellation notification", error)
}
}
return this.commandExecutor.cancelBackgroundCommand()
}
/**
@@ -3563,7 +3189,6 @@ export class Task {
// || this.didEditFile
await setTimeoutPromise(300) // delay after saving file to let terminals catch up
}
// let terminalWasBusy = false
if (busyTerminals.length > 0) {
// wait for terminals to cool down
@@ -1,22 +1,30 @@
import { TerminalOutputFailureReason, telemetryService } from "@services/telemetry"
import { EventEmitter } from "events"
import * as vscode from "vscode"
import { getLatestTerminalOutput } from "../../../integrations/terminal/get-latest-output"
import { stripAnsi } from "./ansiUtils"
export interface TerminalProcessEvents {
line: [line: string]
continue: []
completed: []
error: [error: Error]
no_shell_integration: []
}
import { stripAnsi } from "@/hosts/vscode/terminal/ansiUtils"
import { getLatestTerminalOutput } from "@/hosts/vscode/terminal/get-latest-output"
import type { ITerminalProcess, TerminalProcessEvents } from "@/integrations/terminal/types"
// how long to wait after a process outputs anything before we consider it "cool" again
const PROCESS_HOT_TIMEOUT_NORMAL = 2_000
const PROCESS_HOT_TIMEOUT_COMPILING = 15_000
export class VscodeTerminalProcess extends EventEmitter<TerminalProcessEvents> {
/**
* VscodeTerminalProcess - Manages command execution in VSCode's integrated terminal.
*
* This class handles command execution using VSCode's shell integration API.
* It processes VSCode-specific escape sequences and streams output through events.
*
* Implements ITerminalProcess interface for polymorphic usage with CommandExecutor.
*
* Events:
* - 'line': Emitted for each line of output
* - 'completed': Emitted when the process completes
* - 'continue': Emitted when continue() is called
* - 'error': Emitted on process errors
* - 'no_shell_integration': Emitted when shell integration is not available
*/
export class VscodeTerminalProcess extends EventEmitter<TerminalProcessEvents> implements ITerminalProcess {
waitForShellIntegration: boolean = true
private isListening: boolean = true
private buffer: string = ""
@@ -0,0 +1,319 @@
/**
* CommandExecutor - Unified command execution for all terminal modes.
*
* This class handles command execution for both VSCode terminal mode and
* standalone/CLI mode. It uses the shared CommandOrchestrator for the
* common orchestration logic (buffering, user interaction, result formatting).
*
* The differentiation between modes happens at the TerminalManager level:
* - VscodeTerminalManager → VscodeTerminalProcess (shell integration)
* - StandaloneTerminalManager → StandaloneTerminalProcess (child_process)
*
* IMPORTANT: Subagent commands (cline CLI) are ALWAYS routed to use
* StandaloneTerminalManager regardless of the configured mode. This ensures
* subagents run in hidden/background terminals rather than cluttering the
* user's visible VSCode terminal.
*/
import { isSubagentCommand, transformClineCommand } from "@integrations/cli-subagents/subagent_command"
import { Logger } from "@services/logging/Logger"
import { telemetryService } from "@services/telemetry"
import { ClineToolResponseContent } from "@shared/messages"
import { orchestrateCommandExecution } from "./CommandOrchestrator"
import { StandaloneTerminalManager } from "./standalone/StandaloneTerminalManager"
import {
ActiveBackgroundCommand,
CommandExecutorCallbacks,
CommandExecutorConfig,
ITerminalManager,
TerminalProcessResultPromise,
} from "./types"
// Re-export types for convenience
export type { CommandExecutorCallbacks, CommandExecutorConfig, FullCommandExecutorConfig } from "./types"
/**
* Tracker for shell integration warnings to determine when to show background terminal suggestion
*/
interface ShellIntegrationWarningTracker {
timestamps: number[]
lastSuggestionShown?: number
}
/**
* CommandExecutor - Unified command executor for all terminal modes.
*
* Uses the shared CommandOrchestrator for common logic and delegates
* process management to the appropriate TerminalManager.
*/
export class CommandExecutor {
private cwd: string
private taskId: string
private ulid: string
private terminalExecutionMode: "vscodeTerminal" | "backgroundExec"
private terminalManager: ITerminalManager
private standaloneManager: StandaloneTerminalManager
private callbacks: CommandExecutorCallbacks
// Track shell integration warnings to determine when to show background terminal suggestion
private shellIntegrationWarningTracker: ShellIntegrationWarningTracker = {
timestamps: [],
lastSuggestionShown: undefined,
}
// Track active background command for cancellation (standalone mode only)
private activeBackgroundCommand?: {
process: TerminalProcessResultPromise & { terminate?: () => void }
command: string
outputLines: string[]
}
constructor(config: CommandExecutorConfig, callbacks: CommandExecutorCallbacks) {
this.cwd = config.cwd
this.taskId = config.taskId
this.ulid = config.ulid
this.terminalExecutionMode = config.terminalExecutionMode
this.terminalManager = config.terminalManager
this.callbacks = callbacks
// Always create StandaloneTerminalManager for subagents (even in VSCode mode)
this.standaloneManager = new StandaloneTerminalManager()
// Copy settings from the provided terminalManager to ensure consistency
if ("shellIntegrationTimeout" in config.terminalManager) {
const tm = config.terminalManager as any
this.standaloneManager.setShellIntegrationTimeout(tm.shellIntegrationTimeout || 4000)
this.standaloneManager.setTerminalReuseEnabled(tm.terminalReuseEnabled ?? true)
this.standaloneManager.setTerminalOutputLineLimit(tm.terminalOutputLineLimit || 500)
this.standaloneManager.setSubagentTerminalOutputLineLimit(tm.subagentTerminalOutputLineLimit || 2000)
}
}
/**
* Execute a command in the terminal.
*
* Routing logic:
* 1. Subagent commands (cline CLI) → Always use StandaloneTerminalManager
* This ensures subagents run in hidden terminals, not cluttering the user's VSCode terminal
* 2. Regular commands → Use the configured terminal manager based on terminalExecutionMode
*
* @param command The command to execute
* @param timeoutSeconds Optional timeout in seconds
* @returns [userRejected, result] tuple
*/
async execute(command: string, timeoutSeconds: number | undefined): Promise<[boolean, ClineToolResponseContent]> {
// Transform subagent commands to ensure flags are correct
const isSubagent = isSubagentCommand(command)
if (isSubagent) {
command = transformClineCommand(command)
}
// Strip leading `cd` to workspace from command
const workspaceCdPrefix = `cd ${this.cwd} && `
if (command.startsWith(workspaceCdPrefix)) {
command = command.substring(workspaceCdPrefix.length)
}
const subAgentStartTime = isSubagent ? performance.now() : 0
// Select the appropriate terminal manager
// Subagents always use standalone manager (hidden terminal)
const useStandalone = isSubagent || this.terminalExecutionMode === "backgroundExec"
const manager = useStandalone ? this.standaloneManager : this.terminalManager
Logger.info(`Executing command in ${useStandalone ? "standalone" : "VSCode"} terminal: ${command}`)
// Get terminal and run command
const terminalInfo = await manager.getOrCreateTerminal(this.cwd)
terminalInfo.terminal.show()
const process = manager.runCommand(terminalInfo, command)
// Track background command for standalone mode (enables cancellation)
if (useStandalone) {
this.activeBackgroundCommand = {
process: process as any,
command,
outputLines: [],
}
}
// Use shared orchestration logic
const result = await orchestrateCommandExecution(process, manager, this.callbacks, {
command,
timeoutSeconds,
onOutputLine: useStandalone
? (line) => {
if (this.activeBackgroundCommand) {
this.activeBackgroundCommand.outputLines.push(line)
}
}
: undefined,
showShellIntegrationSuggestion: this.shouldShowBackgroundTerminalSuggestion(),
})
// Clear background command tracking if completed
if (result.completed && useStandalone) {
this.activeBackgroundCommand = undefined
}
// Capture subagent telemetry
if (isSubagent && subAgentStartTime > 0) {
const durationMs = Math.round(performance.now() - subAgentStartTime)
telemetryService.captureSubagentExecution(this.ulid, durationMs, result.outputLines.length, result.completed)
}
return [result.userRejected, result.result]
}
/**
* Cancel the currently running background command.
* Only works in standalone/backgroundExec mode.
*
* @returns true if a command was cancelled, false otherwise
*/
async cancelBackgroundCommand(): Promise<boolean> {
if (!this.activeBackgroundCommand) {
return false
}
const { process, command, outputLines } = this.activeBackgroundCommand
this.activeBackgroundCommand = undefined
this.callbacks.updateBackgroundCommandState(false)
try {
// Try to terminate the process if the method exists
if (typeof process.terminate === "function") {
try {
await process.terminate()
Logger.info(`Terminated background command: ${command}`)
} catch (error) {
Logger.error(`Error terminating background command: ${command}`, error)
}
}
// Ensure any pending operations complete
if (typeof process.continue === "function") {
try {
process.continue()
} catch (error) {
Logger.error(`Error continuing background command: ${command}`, error)
}
}
// Mark the command message as completed in the UI
const clineMessages = this.callbacks.getClineMessages()
const lastCommandIndex = this.findLastIndex(clineMessages, (m) => m.ask === "command" || m.say === "command")
if (lastCommandIndex !== -1) {
await this.callbacks.updateClineMessage(lastCommandIndex, {
commandCompleted: true,
})
}
// Process the captured output to include in the cancellation message
const processedOutput = this.standaloneManager.processOutput(outputLines, undefined, false)
// Add cancellation information to the API conversation history
let cancellationMessage = `Command "${command}" was cancelled by the user.`
if (processedOutput.length > 0) {
cancellationMessage += `\n\nOutput captured before cancellation:\n${processedOutput}`
}
this.callbacks.addToUserMessageContent({
type: "text",
text: cancellationMessage,
})
return true
} catch (error) {
Logger.error("Error in cancelBackgroundCommand", error)
return false
} finally {
try {
await this.callbacks.say("command_output", "Command execution has been cancelled.")
} catch (error) {
Logger.error("Failed to send cancellation notification", error)
}
}
}
/**
* Check if there's an active background command
*/
hasActiveBackgroundCommand(): boolean {
return !!this.activeBackgroundCommand
}
/**
* Get the active background command info (for external access)
*/
getActiveBackgroundCommand(): ActiveBackgroundCommand | undefined {
return this.activeBackgroundCommand
}
/**
* Get a summary of background commands for environment details
*/
getBackgroundCommandSummary(): string | undefined {
if (!this.activeBackgroundCommand) {
return undefined
}
const { command, outputLines } = this.activeBackgroundCommand
const recentOutput = outputLines.slice(-10).join("\n")
let summary = "# Background Commands\n"
summary += `## Running: \`${command}\`\n`
if (recentOutput) {
summary += `### Recent Output\n${recentOutput}`
}
return summary
}
/**
* Determines whether to show the background terminal suggestion.
* Shows suggestion if there have been 3+ shell integration warnings in the last hour,
* and we haven't shown the suggestion in the last hour.
*
* @returns true if the suggestion should be shown, false otherwise
*/
private shouldShowBackgroundTerminalSuggestion(): boolean {
const oneHourAgo = Date.now() - 60 * 60 * 1000
// Clean old timestamps (older than 1 hour)
this.shellIntegrationWarningTracker.timestamps = this.shellIntegrationWarningTracker.timestamps.filter(
(ts) => ts > oneHourAgo,
)
// Add current warning
this.shellIntegrationWarningTracker.timestamps.push(Date.now())
// Check if we've shown suggestion recently (within last hour)
if (
this.shellIntegrationWarningTracker.lastSuggestionShown &&
Date.now() - this.shellIntegrationWarningTracker.lastSuggestionShown < 60 * 60 * 1000
) {
return false
}
// Show suggestion if 3+ warnings in last hour
if (this.shellIntegrationWarningTracker.timestamps.length >= 3) {
this.shellIntegrationWarningTracker.lastSuggestionShown = Date.now()
return true
}
return false
}
/**
* Helper to find last index matching a predicate
*/
private findLastIndex<T>(array: T[], predicate: (item: T) => boolean): number {
for (let i = array.length - 1; i >= 0; i--) {
if (predicate(array[i])) {
return i
}
}
return -1
}
}
@@ -0,0 +1,350 @@
/**
* CommandOrchestrator - Shared command execution orchestration logic.
*
* This module contains the common orchestration logic for command execution
* that is shared between VSCode and Standalone terminal modes. It handles:
* - Output buffering and chunking
* - User interaction (ask/say callbacks)
* - "Proceed While Running" behavior
* - Timeout handling
* - Result formatting
*
* The actual process spawning/management is handled by the TerminalProcess
* implementations (VscodeTerminalProcess, StandaloneTerminalProcess).
*/
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import { formatResponse } from "@core/prompts/responses"
import { processFilesIntoText } from "@integrations/misc/extract-text"
import { Logger } from "@services/logging/Logger"
import { TerminalHangStage, TerminalUserInterventionAction, telemetryService } from "@services/telemetry"
import { COMMAND_CANCEL_TOKEN } from "@shared/ExtensionMessage"
import type {
CommandExecutorCallbacks,
ITerminalManager,
OrchestrationOptions,
OrchestrationResult,
TerminalProcessResultPromise,
} from "./types"
// Chunked terminal output buffering constants
export const CHUNK_LINE_COUNT = 20
export const CHUNK_BYTE_SIZE = 2048 // 2KB
export const CHUNK_DEBOUNCE_MS = 100
export const BUFFER_STUCK_TIMEOUT_MS = 6000 // 6 seconds
export const COMPLETION_TIMEOUT_MS = 6000 // 6 seconds
// Re-export types for convenience
export type { OrchestrationOptions, OrchestrationResult } from "./types"
/**
* Orchestrate command execution with shared logic for buffering, user interaction, and result formatting.
*
* @param process The terminal process (implements ITerminalProcess)
* @param terminalManager The terminal manager (for processOutput)
* @param callbacks The executor callbacks for UI interaction
* @param options Orchestration options
* @returns The orchestration result
*/
export async function orchestrateCommandExecution(
process: TerminalProcessResultPromise,
terminalManager: ITerminalManager,
callbacks: CommandExecutorCallbacks,
options: OrchestrationOptions,
): Promise<OrchestrationResult> {
const { command, timeoutSeconds, onOutputLine, showShellIntegrationSuggestion } = options
// Track command execution state
callbacks.updateBackgroundCommandState(true)
const clearCommandState = async () => {
callbacks.updateBackgroundCommandState(false)
// Mark the command message as completed
const clineMessages = callbacks.getClineMessages()
const lastCommandIndex = findLastIndex(clineMessages, (m) => m.ask === "command" || m.say === "command")
if (lastCommandIndex !== -1) {
await callbacks.updateClineMessage(lastCommandIndex, {
commandCompleted: true,
})
}
}
process.once("completed", clearCommandState)
process.once("error", clearCommandState)
process.catch(() => {
clearCommandState()
})
let userFeedback: { text?: string; images?: string[]; files?: string[] } | undefined
let didContinue = false
let didCancelViaUi = false
// Chunked terminal output buffering
let outputBuffer: string[] = []
let outputBufferSize: number = 0
let chunkTimer: NodeJS.Timeout | null = null
// Track if buffer gets stuck
let bufferStuckTimer: NodeJS.Timeout | null = null
/**
* Flush buffered output to the UI using ask() which waits for user response.
* This is the key mechanism for "Proceed While Running" - when user clicks the button,
* the ask() returns with response "yesButtonClicked".
*/
const flushBuffer = async (force = false) => {
if (outputBuffer.length === 0 && !force) {
return
}
const chunk = outputBuffer.join("\n")
outputBuffer = []
outputBufferSize = 0
if (!didContinue) {
// Start timer to detect if buffer gets stuck
bufferStuckTimer = setTimeout(() => {
telemetryService.captureTerminalHang(TerminalHangStage.BUFFER_STUCK)
bufferStuckTimer = null
}, BUFFER_STUCK_TIMEOUT_MS)
try {
// Use ask() to present output and wait for user response
// This enables "Proceed While Running" button functionality
const { response, text, images, files } = await callbacks.ask("command_output", chunk)
if (response === "yesButtonClicked") {
// Track when user clicks "Proceed While Running"
telemetryService.captureTerminalUserIntervention(TerminalUserInterventionAction.PROCESS_WHILE_RUNNING)
// Proceed while running - but still capture user feedback if provided
if (text || (images && images.length > 0) || (files && files.length > 0)) {
userFeedback = { text, images, files }
}
didContinue = true
process.continue()
} else if (response === "noButtonClicked" && text === COMMAND_CANCEL_TOKEN) {
telemetryService.captureTerminalUserIntervention(TerminalUserInterventionAction.CANCELLED)
didCancelViaUi = true
userFeedback = undefined
didContinue = true
process.continue()
outputBuffer = []
outputBufferSize = 0
await callbacks.say("command_output", "Command cancelled")
} else {
userFeedback = { text, images, files }
didContinue = true
process.continue()
// If more output accumulated, flush again
if (outputBuffer.length > 0) {
await flushBuffer()
}
}
} catch {
Logger.error("Error while asking for command output")
} finally {
// Clear the stuck timer
if (bufferStuckTimer) {
clearTimeout(bufferStuckTimer)
bufferStuckTimer = null
}
}
} else {
// After "Proceed While Running": stream output directly to UI
await callbacks.say("command_output", chunk)
}
}
const scheduleFlush = () => {
if (chunkTimer) {
clearTimeout(chunkTimer)
}
chunkTimer = setTimeout(async () => await flushBuffer(), CHUNK_DEBOUNCE_MS)
}
const outputLines: string[] = []
process.on("line", async (line: string) => {
if (didCancelViaUi) {
return
}
outputLines.push(line)
// Notify caller about output line (for background command tracking)
if (onOutputLine) {
onOutputLine(line)
}
// Apply buffered streaming
if (!didContinue) {
outputBuffer.push(line)
outputBufferSize += Buffer.byteLength(line, "utf8")
// Flush if buffer is large enough
if (outputBuffer.length >= CHUNK_LINE_COUNT || outputBufferSize >= CHUNK_BYTE_SIZE) {
await flushBuffer()
} else {
scheduleFlush()
}
} else {
// After "Proceed While Running": stream output directly to UI
await callbacks.say("command_output", line)
}
})
let completed = false
let completionTimer: NodeJS.Timeout | null = null
// Start timer to detect if waiting for completion takes too long
completionTimer = setTimeout(() => {
if (!completed) {
telemetryService.captureTerminalHang(TerminalHangStage.WAITING_FOR_COMPLETION)
completionTimer = null
}
}, COMPLETION_TIMEOUT_MS)
process.once("completed", async () => {
completed = true
// Clear the completion timer
if (completionTimer) {
clearTimeout(completionTimer)
completionTimer = null
}
// Flush any remaining buffered output
if (!didContinue && outputBuffer.length > 0) {
if (chunkTimer) {
clearTimeout(chunkTimer)
chunkTimer = null
}
await flushBuffer(true)
}
})
process.once("no_shell_integration", async () => {
if (showShellIntegrationSuggestion) {
await callbacks.say("shell_integration_warning_with_suggestion")
} else {
await callbacks.say("shell_integration_warning")
}
})
// Handle timeout if specified, or wait for process to complete
if (!didCancelViaUi) {
if (timeoutSeconds) {
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => {
reject(new Error("COMMAND_TIMEOUT"))
}, timeoutSeconds * 1000)
})
try {
await Promise.race([process, timeoutPromise])
} catch (error: any) {
if (error.message === "COMMAND_TIMEOUT") {
// Timeout triggers "Proceed While Running" behavior
didContinue = true
process.continue()
// Clear all our timers
if (chunkTimer) {
clearTimeout(chunkTimer)
chunkTimer = null
}
if (completionTimer) {
clearTimeout(completionTimer)
completionTimer = null
}
// Process any output we captured before timeout
await setTimeoutPromise(50)
const result = terminalManager.processOutput(outputLines)
return {
userRejected: false,
result: `Command execution timed out after ${timeoutSeconds} seconds. ${result.length > 0 ? `\nOutput so far:\n${result}` : ""}`,
completed: false,
outputLines,
}
}
// Re-throw other errors
throw error
}
} else {
// No timeout - wait for process to complete
await process
}
}
// Clear timer if process completes normally
if (completionTimer) {
clearTimeout(completionTimer)
completionTimer = null
}
// Wait for a short delay to ensure all messages are sent to the webview
await setTimeoutPromise(50)
const result = terminalManager.processOutput(outputLines)
if (didCancelViaUi) {
return {
userRejected: true,
result: formatResponse.toolResult(
`Command cancelled. ${result.length > 0 ? `\nOutput captured before cancellation:\n${result}` : ""}`,
),
completed: false,
outputLines,
}
}
if (userFeedback) {
await callbacks.say("user_feedback", userFeedback.text, userFeedback.images, userFeedback.files)
let fileContentString = ""
if (userFeedback.files && userFeedback.files.length > 0) {
fileContentString = await processFilesIntoText(userFeedback.files)
}
return {
userRejected: true,
result: formatResponse.toolResult(
`Command is still running in the user's terminal.${
result.length > 0 ? `\nHere's the output so far:\n${result}` : ""
}\n\nThe user provided the following feedback:\n<feedback>\n${userFeedback.text}\n</feedback>`,
userFeedback.images,
fileContentString,
),
completed: false,
outputLines,
}
}
if (completed) {
return {
userRejected: false,
result: `Command executed.${result.length > 0 ? `\nOutput:\n${result}` : ""}`,
completed: true,
outputLines,
}
} else {
return {
userRejected: false,
result: `Command is still running in the user's terminal.${
result.length > 0 ? `\nHere's the output so far:\n${result}` : ""
}\n\nYou will be updated on the terminal status and new output in the future.`,
completed: false,
outputLines,
}
}
}
/**
* Helper to find last index matching a predicate
*/
export function findLastIndex<T>(array: T[], predicate: (item: T) => boolean): number {
for (let i = array.length - 1; i >= 0; i--) {
if (predicate(array[i])) {
return i
}
}
return -1
}
+36 -7
View File
@@ -8,7 +8,7 @@
*
* @example
* ```typescript
* import { StandaloneTerminalManager, ITerminalManager } from "@shared/terminal"
* import { StandaloneTerminalManager, ITerminalManager } from "@integrations/terminal"
*
* const manager: ITerminalManager = new StandaloneTerminalManager()
* const terminalInfo = await manager.getOrCreateTerminal("/path/to/cwd")
@@ -19,17 +19,46 @@
* ```
*/
export { StandaloneTerminal } from "./StandaloneTerminal"
export { StandaloneTerminalManager } from "./StandaloneTerminalManager"
// Export standalone implementations
export { StandaloneTerminalProcess } from "./StandaloneTerminalProcess"
export { StandaloneTerminalRegistry } from "./StandaloneTerminalRegistry"
// Export all types
// Export unified command executor
export { CommandExecutor } from "./CommandExecutor"
// Export command orchestrator (shared logic)
export {
BUFFER_STUCK_TIMEOUT_MS,
CHUNK_BYTE_SIZE,
CHUNK_DEBOUNCE_MS,
CHUNK_LINE_COUNT,
COMPLETION_TIMEOUT_MS,
findLastIndex,
orchestrateCommandExecution,
} from "./CommandOrchestrator"
// Export terminal process interface
// Export standalone terminal implementations
export { StandaloneTerminal } from "./standalone/StandaloneTerminal"
export { StandaloneTerminalManager } from "./standalone/StandaloneTerminalManager"
export { StandaloneTerminalProcess } from "./standalone/StandaloneTerminalProcess"
export { StandaloneTerminalRegistry } from "./standalone/StandaloneTerminalRegistry"
// Export all types from types.ts
export type {
// Command Executor types
ActiveBackgroundCommand,
AskResponse,
CommandExecutorCallbacks,
CommandExecutorConfig,
FullCommandExecutorConfig,
// Terminal types
ITerminal,
ITerminalManager,
ITerminalProcess,
ITerminalProcessResult,
// Command Orchestrator types
OrchestrationOptions,
OrchestrationResult,
StandaloneTerminalOptions,
TerminalInfo,
TerminalProcessEvents,
TerminalProcessResultPromise,
} from "./types"
@@ -7,7 +7,7 @@
import type { ChildProcess } from "child_process"
import type { ITerminal, StandaloneTerminalOptions } from "./types"
import type { ITerminal, StandaloneTerminalOptions } from "../types"
/**
* A standalone terminal implementation that doesn't depend on VSCode.
@@ -6,9 +6,9 @@
* VSCode's terminal API.
*/
import type { ITerminalManager, TerminalInfo, TerminalProcessResultPromise } from "../types"
import { StandaloneTerminalProcess } from "./StandaloneTerminalProcess"
import { StandaloneTerminalRegistry } from "./StandaloneTerminalRegistry"
import type { ITerminalManager, TerminalInfo, TerminalProcessResultPromise } from "./types"
/**
* Helper function to merge a process with a promise for the TerminalProcessResultPromise type.
@@ -4,24 +4,29 @@
* This class handles subprocess management for terminal commands when running
* outside of VSCode (CLI, JetBrains). It spawns child processes and streams
* their output through events.
*
* Implements ITerminalProcess interface for polymorphic usage with CommandExecutor.
*/
import { ChildProcess, spawn } from "child_process"
import { EventEmitter } from "events"
import type { ITerminal, ITerminalProcessResult } from "./types"
import type { ITerminal, ITerminalProcess, TerminalProcessEvents } from "../types"
/**
* Manages the execution of a command in a standalone terminal environment.
* Extends EventEmitter to provide real-time output streaming.
*
* Implements ITerminalProcess for polymorphic usage with CommandExecutor.
*
* Events:
* - 'line': Emitted for each line of output
* - 'completed': Emitted when the process completes
* - 'continue': Emitted when continue() is called
* - 'error': Emitted on process errors
* - 'no_shell_integration': Emitted for compatibility (never actually emitted in standalone)
*/
export class StandaloneTerminalProcess extends EventEmitter implements ITerminalProcessResult {
export class StandaloneTerminalProcess extends EventEmitter<TerminalProcessEvents> implements ITerminalProcess {
/** We don't need to wait since we control the process directly */
waitForShellIntegration: boolean = false
@@ -5,8 +5,8 @@
* functionality to create, retrieve, update, and remove terminals.
*/
import type { ITerminal, StandaloneTerminalOptions, TerminalInfo } from "../types"
import { StandaloneTerminal } from "./StandaloneTerminal"
import type { ITerminal, StandaloneTerminalOptions, TerminalInfo } from "./types"
/**
* Registry for tracking standalone terminal instances.
+172 -17
View File
@@ -4,7 +4,71 @@
* the StandaloneTerminalManager used in CLI/JetBrains environments.
*/
import { EventEmitter } from "events"
import type { ClineToolResponseContent } from "@shared/messages"
import type { EventEmitter } from "events"
// =============================================================================
// Terminal Process Types
// =============================================================================
/**
* Event types for terminal process
*/
export interface TerminalProcessEvents {
line: [line: string]
continue: []
completed: []
error: [error: Error]
no_shell_integration: []
}
/**
* Interface for terminal process implementations.
* Both VscodeTerminalProcess and StandaloneTerminalProcess implement this interface.
*
* Events emitted:
* - 'line': Emitted for each line of output
* - 'completed': Emitted when the process completes
* - 'continue': Emitted when continue() is called
* - 'error': Emitted on process errors
* - 'no_shell_integration': Emitted when shell integration is not available (VSCode only)
*/
export interface ITerminalProcess extends EventEmitter<TerminalProcessEvents> {
/**
* Whether the process is actively outputting (used to stall API requests)
*/
isHot: boolean
/**
* Whether to wait for shell integration before running commands.
* VSCode processes may need to wait, standalone processes don't.
*/
waitForShellIntegration: boolean
/**
* Continue execution without waiting for completion.
* Stops event emission and resolves the promise.
* This is called when user clicks "Proceed While Running".
*/
continue(): void
/**
* Get output that hasn't been retrieved yet.
* @returns The unretrieved output
*/
getUnretrievedOutput(): string
/**
* Terminate the process if it's still running.
* Only available for standalone processes (child_process).
* VSCode terminal processes cannot be terminated via this interface.
*/
terminate?(): void
}
// =============================================================================
// Terminal Types
// =============================================================================
/**
* Represents a terminal instance with its metadata and state.
@@ -54,28 +118,19 @@ export interface ITerminal {
}
/**
* Terminal process result that combines Promise functionality with event emission.
* Allows for both awaiting completion and listening to real-time output.
* Terminal process result interface.
* @deprecated Use ITerminalProcess instead.
* This is kept for backwards compatibility.
*/
export interface ITerminalProcessResult extends EventEmitter {
/** Whether the process is actively outputting (hot) */
isHot: boolean
/** Whether we're waiting for shell integration to activate */
waitForShellIntegration: boolean
/** Continue execution without waiting for completion */
continue(): void
/** Terminate the process (if supported) */
terminate?(): void
/** Get output that hasn't been retrieved yet */
getUnretrievedOutput(): string
}
export type ITerminalProcessResult = ITerminalProcess
/**
* Promise-like interface for terminal process results.
* Combines Promise<void> with ITerminalProcessResult for flexible usage.
* Combines Promise<void> with ITerminalProcess for flexible usage.
* This allows the process to be awaited while also providing access to events.
*/
export type TerminalProcessResultPromise = Promise<void> &
ITerminalProcessResult & {
ITerminalProcess & {
/** Listen for line output events */
on(event: "line", listener: (line: string) => void): TerminalProcessResultPromise
/** Listen for completion event */
@@ -187,3 +242,103 @@ export interface StandaloneTerminalOptions {
/** Shell path to use */
shellPath?: string
}
// =============================================================================
// Command Executor Types
// =============================================================================
/**
* Represents an active background command that can be cancelled
*/
export interface ActiveBackgroundCommand {
process: {
terminate?: () => void
continue?: () => void
}
command: string
outputLines: string[]
}
/**
* Response from an ask() call
*/
export interface AskResponse {
response: string // "yesButtonClicked" | "noButtonClicked" | "messageResponse"
text?: string
images?: string[]
files?: string[]
}
/**
* Callbacks for CommandExecutor to interact with Task state
* These are bound methods from the Task class that allow CommandExecutor
* to update UI and state without owning that state directly.
*/
export interface CommandExecutorCallbacks {
/** Display a message in the chat UI (non-blocking) */
say: (type: string, text?: string, images?: string[], files?: string[], partial?: boolean) => Promise<number | undefined>
/**
* Ask the user a question and wait for response (blocking)
* This is used for "Proceed While Running" flow where we need to wait for user input
*/
ask: (type: string, text?: string, partial?: boolean) => Promise<AskResponse>
/** Update the background command running state in the controller */
updateBackgroundCommandState: (running: boolean) => void
/** Update a cline message by index */
updateClineMessage: (index: number, updates: { commandCompleted?: boolean }) => Promise<void>
/** Get cline messages array */
getClineMessages: () => Array<{ ask?: string; say?: string }>
/** Add content to user message for next API request */
addToUserMessageContent: (content: { type: string; text: string }) => void
}
/**
* Configuration for CommandExecutor
*/
export interface CommandExecutorConfig {
/** Working directory for command execution */
cwd: string
/** Task ID for tracking */
taskId: string
/** Unique task identifier */
ulid: string
/** Terminal execution mode */
terminalExecutionMode: "vscodeTerminal" | "backgroundExec"
/** The primary terminal manager (VSCode or Standalone) */
terminalManager: ITerminalManager
}
/** Alias for backwards compatibility */
export type FullCommandExecutorConfig = CommandExecutorConfig
// =============================================================================
// Command Orchestrator Types
// =============================================================================
/**
* Options for command orchestration
*/
export interface OrchestrationOptions {
/** The command being executed */
command: string
/** Optional timeout in seconds */
timeoutSeconds?: number
/** Callback to track output lines for background command tracking */
onOutputLine?: (line: string) => void
/** Whether to show shell integration warning with suggestion */
showShellIntegrationSuggestion?: boolean
}
/**
* Result of command orchestration
*/
export interface OrchestrationResult {
/** Whether the user rejected/cancelled the command */
userRejected: boolean
/** The result content to return */
result: ClineToolResponseContent
/** Whether the command completed */
completed: boolean
/** All output lines captured */
outputLines: string[]
}