diff --git a/.vscodeignore b/.vscodeignore index 02df63c5..2d15bd4d 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -40,9 +40,6 @@ buf.yaml .changeset/ .clinerules/ -# Include specific file needed for Background Exec mode -!standalone/runtime-files/vscode/enhanced-terminal.js - # Ignore all webview-ui files except the build directory (https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/frameworks/hello-world-react-cra/.vscodeignore) webview-ui/src/** webview-ui/public/** diff --git a/esbuild.mjs b/esbuild.mjs index 7719ed73..49103296 100644 --- a/esbuild.mjs +++ b/esbuild.mjs @@ -125,7 +125,7 @@ const copyWasmFiles = { const buildEnvVars = { "import.meta.url": "_importMetaUrl", - "process.env.IS_STANDALONE": JSON.stringify(standalone), + "process.env.IS_STANDALONE": JSON.stringify(standalone ? "true" : "false"), } if (production) { diff --git a/src/core/controller/state/updateSettings.ts b/src/core/controller/state/updateSettings.ts index f880388c..b017a2c6 100644 --- a/src/core/controller/state/updateSettings.ts +++ b/src/core/controller/state/updateSettings.ts @@ -12,7 +12,6 @@ import { OpenaiReasoningEffort } from "@shared/storage/types" import { TelemetrySetting } from "@shared/TelemetrySetting" import { ClineEnv } from "@/config" import { HostProvider } from "@/hosts/host-provider" -import { TerminalInfo } from "@/integrations/terminal/TerminalRegistry" import { McpDisplayMode } from "@/shared/McpDisplayMode" import { ShowMessageType } from "@/shared/proto/host/window" import { telemetryService } from "../../../services/telemetry" @@ -281,14 +280,15 @@ export async function updateSettings(controller: Controller, request: UpdateSett controller.stateManager.setGlobalState("defaultTerminalProfile", profileId) let closedCount = 0 - let busyTerminals: TerminalInfo[] = [] + let busyTerminalsCount = 0 // Update the terminal manager of the current task if it exists if (controller.task) { // Call the updated setDefaultTerminalProfile method that returns closed terminal info - const result = controller.task.terminalManager.setDefaultTerminalProfile(profileId) + // Use `as any` to handle type incompatibility between VSCode's TerminalInfo and standalone TerminalInfo + const result = controller.task.terminalManager.setDefaultTerminalProfile(profileId) as any closedCount = result.closedCount - busyTerminals = result.busyTerminals + busyTerminalsCount = result.busyTerminals?.length ?? 0 // Show information message if terminals were closed if (closedCount > 0) { @@ -300,10 +300,10 @@ export async function updateSettings(controller: Controller, request: UpdateSett } // Show warning if there are busy terminals that couldn't be closed - if (busyTerminals.length > 0) { + if (busyTerminalsCount > 0) { const message = - `${busyTerminals.length} busy ${busyTerminals.length === 1 ? "terminal has" : "terminals have"} a different profile. ` + - `Close ${busyTerminals.length === 1 ? "it" : "them"} to use the new profile for all commands.` + `${busyTerminalsCount} busy ${busyTerminalsCount === 1 ? "terminal has" : "terminals have"} a different profile. ` + + `Close ${busyTerminalsCount === 1 ? "it" : "them"} to use the new profile for all commands.` HostProvider.window.showMessage({ type: ShowMessageType.WARNING, message, diff --git a/src/core/controller/state/updateSettingsCli.ts b/src/core/controller/state/updateSettingsCli.ts index 83fccf4a..73783db6 100644 --- a/src/core/controller/state/updateSettingsCli.ts +++ b/src/core/controller/state/updateSettingsCli.ts @@ -11,7 +11,6 @@ import { Settings } from "@shared/storage/state-keys" import { TelemetrySetting } from "@shared/TelemetrySetting" import { ClineEnv } from "@/config" import { HostProvider } from "@/hosts/host-provider" -import { TerminalInfo } from "@/integrations/terminal/TerminalRegistry" import { ShowMessageType } from "@/shared/proto/host/window" import { Mode, OpenaiReasoningEffort } from "@/shared/storage/types" import { telemetryService } from "../../../services/telemetry" @@ -215,7 +214,7 @@ export async function updateSettingsCli(controller: Controller, request: UpdateS controller.stateManager.setGlobalState("defaultTerminalProfile", profileId) let closedCount = 0 - let busyTerminals: TerminalInfo[] = [] + let busyTerminalsCount = 0 // Update the terminal manager of the current task if it exists if (controller.task) { @@ -225,9 +224,10 @@ export async function updateSettingsCli(controller: Controller, request: UpdateS } // Call the updated setDefaultTerminalProfile method that returns closed terminal info - const result = controller.task.terminalManager.setDefaultTerminalProfile(profileId) + // Use `as any` to handle type incompatibility between VSCode's TerminalInfo and standalone TerminalInfo + const result = controller.task.terminalManager.setDefaultTerminalProfile(profileId) as any closedCount = result.closedCount - busyTerminals = result.busyTerminals + busyTerminalsCount = result.busyTerminals?.length ?? 0 // Show information message if terminals were closed if (closedCount > 0) { @@ -239,10 +239,10 @@ export async function updateSettingsCli(controller: Controller, request: UpdateS } // Show warning if there are busy terminals that couldn't be closed - if (busyTerminals.length > 0) { + if (busyTerminalsCount > 0) { const message = - `${busyTerminals.length} busy ${busyTerminals.length === 1 ? "terminal has" : "terminals have"} a different profile. ` + - `Close ${busyTerminals.length === 1 ? "it" : "them"} to use the new profile for all commands.` + `${busyTerminalsCount} busy ${busyTerminalsCount === 1 ? "terminal has" : "terminals have"} a different profile. ` + + `Close ${busyTerminalsCount === 1 ? "it" : "them"} to use the new profile for all commands.` HostProvider.window.showMessage({ type: ShowMessageType.WARNING, message, diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 1aca65d0..df3e8d5a 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -42,7 +42,6 @@ import { DiffViewProvider } from "@integrations/editor/DiffViewProvider" import { formatContentBlockToMarkdown } from "@integrations/misc/export-markdown" import { processFilesIntoText } from "@integrations/misc/extract-text" import { showSystemNotification } from "@integrations/notifications" -import { TerminalManager } from "@integrations/terminal/TerminalManager" import { TerminalProcessResultPromise } from "@integrations/terminal/TerminalProcess" import { BrowserSession } from "@services/browser/BrowserSession" import { UrlContentFetcher } from "@services/browser/UrlContentFetcher" @@ -66,6 +65,7 @@ import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@sha import { CLINE_MCP_TOOL_IDENTIFIER } from "@shared/mcp" import { USER_CONTENT_TAGS } from "@shared/messages/constants" import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message" +import { ITerminalManager } from "@shared/terminal/types" import { ClineDefaultTool } from "@shared/tools" import { ClineAskResponse } from "@shared/WebviewMessage" import { isClaude4PlusModelFamily, isGPT5ModelFamily, isLocalModel, isNextGenModelFamily } from "@utils/model-utils" @@ -135,12 +135,6 @@ type TaskParams = { } export class Task { - // Constants - private static readonly STANDALONE_TERMINAL_MODULE_PATH = path.join( - __dirname, - "../standalone/runtime-files/vscode/enhanced-terminal.js", - ) - // Core task variables readonly taskId: string readonly ulid: string @@ -200,7 +194,7 @@ export class Task { // Service handlers api: ApiHandler - terminalManager: TerminalManager + terminalManager: ITerminalManager private urlContentFetcher: UrlContentFetcher browserSession: BrowserSession contextManager: ContextManager @@ -288,38 +282,20 @@ export class Task { this.clineIgnoreController = new ClineIgnoreController(cwd) this.taskLockAcquired = taskLockAcquired - // TODO(ae) this is a hack to replace the terminal manager for standalone, - // until we have proper host bridge support for terminal execution. The - // standaloneTerminalManager is defined in the vscode-impls and injected - // during compilation of the standalone manager only, so this variable only - // exists in that case + // Determine terminal execution mode and create appropriate terminal manager + this.terminalExecutionMode = vscodeTerminalExecutionMode || "vscodeTerminal" - // First check if we're in standalone mode (original automatic detection) - if ((global as any).standaloneTerminalManager) { - this.terminalManager = (global as any).standaloneTerminalManager - this.terminalExecutionMode = "backgroundExec" + // When backgroundExec mode is selected, use StandaloneTerminalManager for hidden execution + // Otherwise, use the HostProvider's terminal manager (VSCode terminal in VSCode, standalone in CLI) + if (this.terminalExecutionMode === "backgroundExec") { + // Import StandaloneTerminalManager for background execution + const { StandaloneTerminalManager } = require("@shared/terminal/StandaloneTerminalManager") + this.terminalManager = new StandaloneTerminalManager() + Logger.info(`[Task ${taskId}] Using StandaloneTerminalManager for backgroundExec mode`) } else { - // Not in standalone mode, use the configured mode (default to vscodeTerminal) - const terminalExecutionMode = vscodeTerminalExecutionMode || "vscodeTerminal" - this.terminalExecutionMode = terminalExecutionMode - - if (terminalExecutionMode === "backgroundExec") { - try { - const { StandaloneTerminalManager } = require(Task.STANDALONE_TERMINAL_MODULE_PATH) as { - StandaloneTerminalManager?: new () => TerminalManager - } - if (StandaloneTerminalManager) { - this.terminalManager = new StandaloneTerminalManager() - } else { - this.terminalManager = new TerminalManager() - } - } catch (error) { - console.error("[DEBUG] Failed to load standalone terminal manager", error) - this.terminalManager = new TerminalManager() - } - } else { - this.terminalManager = new TerminalManager() - } + // Use the host-provided terminal manager (VSCode terminal in VSCode environment) + this.terminalManager = HostProvider.get().createTerminalManager() + Logger.info(`[Task ${taskId}] Using HostProvider terminal manager for vscodeTerminal mode`) } this.terminalManager.setShellIntegrationTimeout(shellIntegrationTimeout) this.terminalManager.setTerminalReuseEnabled(terminalReuseEnabled ?? true) @@ -1528,34 +1504,24 @@ export class Task { Logger.info("Executing command in terminal: " + command) - let terminalManager: TerminalManager - if (isSubagent) { - // Create a background TerminalManager for CLI subagents - try { - const { StandaloneTerminalManager } = require(Task.STANDALONE_TERMINAL_MODULE_PATH) as { - StandaloneTerminalManager?: new () => TerminalManager - } - if (StandaloneTerminalManager) { - terminalManager = new StandaloneTerminalManager() - } else { - terminalManager = new TerminalManager() - } - } catch (error) { - console.error("[DEBUG] Failed to load standalone terminal manager for subagent", error) - terminalManager = new TerminalManager() - } - terminalManager.setShellIntegrationTimeout(this.terminalManager["shellIntegrationTimeout"] || 4000) - terminalManager.setTerminalReuseEnabled(this.terminalManager["terminalReuseEnabled"] ?? true) - terminalManager.setTerminalOutputLineLimit(this.terminalManager["terminalOutputLineLimit"] || 500) - terminalManager.setSubagentTerminalOutputLineLimit(this.terminalManager["subagentTerminalOutputLineLimit"] || 2000) + let terminalManager: ITerminalManager + if (isSubagent || this.terminalExecutionMode === "backgroundExec") { + // Use StandaloneTerminalManager for hidden background execution (subagents and backgroundExec mode) + const { StandaloneTerminalManager } = require("@shared/terminal/StandaloneTerminalManager") + 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 + // 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. - const process = terminalManager.runCommand(terminalInfo, command) + // 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) @@ -1776,7 +1742,7 @@ export class Task { // Process any output we captured before timeout await setTimeoutPromise(50) - const result = this.terminalManager.processOutput(outputLines, undefined, false) + const result = terminalManager.processOutput(outputLines, undefined, isSubagent) if (error.message === "COMMAND_TIMEOUT") { return [ @@ -1808,11 +1774,7 @@ export class Task { await setTimeoutPromise(50) } - const result = terminalManager.processOutput( - outputLines, - isSubagent ? terminalManager["subagentTerminalOutputLineLimit"] : undefined, - isSubagent, - ) + const result = terminalManager.processOutput(outputLines, undefined, isSubagent) if (didCancelViaUi) { return [ @@ -1900,7 +1862,7 @@ export class Task { } // Process the captured output to include in the cancellation message - const processedOutput = this.terminalManager.processOutput(outputLines, undefined, false) + 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 diff --git a/src/extension.ts b/src/extension.ts index ad05a7a8..95f6384a 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -39,6 +39,7 @@ import { } from "./hosts/vscode/review/VscodeCommentReviewController" import { VscodeDiffViewProvider } from "./hosts/vscode/VscodeDiffViewProvider" import { VscodeWebviewProvider } from "./hosts/vscode/VscodeWebviewProvider" +import { TerminalManager } from "./integrations/terminal/TerminalManager" import { ExtensionRegistryInfo } from "./registry" import { AuthService } from "./services/auth/AuthService" import { LogoutReason } from "./services/auth/types" @@ -433,6 +434,7 @@ function setupHostProvider(context: ExtensionContext) { const createWebview = () => new VscodeWebviewProvider(context) const createDiffView = () => new VscodeDiffViewProvider() const createCommentReview = () => getVscodeCommentReviewController() + const createTerminalManager = () => new TerminalManager() const outputChannel = vscode.window.createOutputChannel("Cline") context.subscriptions.push(outputChannel) @@ -441,6 +443,7 @@ function setupHostProvider(context: ExtensionContext) { createWebview, createDiffView, createCommentReview, + createTerminalManager, vscodeHostBridgeClient, outputChannel.appendLine, getCallbackUrl, diff --git a/src/hosts/host-provider.ts b/src/hosts/host-provider.ts index f9971d4d..f05dfe39 100644 --- a/src/hosts/host-provider.ts +++ b/src/hosts/host-provider.ts @@ -1,6 +1,7 @@ import { WebviewProvider } from "@/core/webview" import { CommentReviewController } from "@/integrations/editor/CommentReviewController" import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider" +import { ITerminalManager } from "@/shared/terminal/types" import { HostBridgeClientProvider } from "./host-provider-types" /** * Singleton class that manages host-specific providers for dependency injection. @@ -21,6 +22,7 @@ export class HostProvider { createWebviewProvider: WebviewProviderCreator createDiffViewProvider: DiffViewProviderCreator createCommentReviewController: CommentReviewControllerCreator + createTerminalManager: TerminalManagerCreator hostBridge: HostBridgeClientProvider // Logs to a user-visible output channel. @@ -47,6 +49,7 @@ export class HostProvider { createWebviewProvider: WebviewProviderCreator, createDiffViewProvider: DiffViewProviderCreator, createCommentReviewController: CommentReviewControllerCreator, + createTerminalManager: TerminalManagerCreator, hostBridge: HostBridgeClientProvider, logToChannel: LogToChannel, getCallbackUrl: () => Promise, @@ -57,6 +60,7 @@ export class HostProvider { this.createWebviewProvider = createWebviewProvider this.createDiffViewProvider = createDiffViewProvider this.createCommentReviewController = createCommentReviewController + this.createTerminalManager = createTerminalManager this.hostBridge = hostBridge this.logToChannel = logToChannel this.getCallbackUrl = getCallbackUrl @@ -69,6 +73,7 @@ export class HostProvider { webviewProviderCreator: WebviewProviderCreator, diffViewProviderCreator: DiffViewProviderCreator, commentReviewControllerCreator: CommentReviewControllerCreator, + terminalManagerCreator: TerminalManagerCreator, hostBridgeProvider: HostBridgeClientProvider, logToChannel: LogToChannel, getCallbackUrl: () => Promise, @@ -83,6 +88,7 @@ export class HostProvider { webviewProviderCreator, diffViewProviderCreator, commentReviewControllerCreator, + terminalManagerCreator, hostBridgeProvider, logToChannel, getCallbackUrl, @@ -148,3 +154,9 @@ export type DiffViewProviderCreator = () => DiffViewProvider export type CommentReviewControllerCreator = () => CommentReviewController export type LogToChannel = (message: string) => void + +/** + * A function that creates TerminalManager instances + * Returns the platform-appropriate terminal manager (VSCode TerminalManager or StandaloneTerminalManager) + */ +export type TerminalManagerCreator = () => ITerminalManager diff --git a/src/integrations/terminal/TerminalManager.ts b/src/integrations/terminal/TerminalManager.ts index e209def6..8b5b796b 100644 --- a/src/integrations/terminal/TerminalManager.ts +++ b/src/integrations/terminal/TerminalManager.ts @@ -2,7 +2,12 @@ import { arePathsEqual } from "@utils/path" import { getShellForProfile } from "@utils/shell" import pWaitFor from "p-wait-for" import * as vscode from "vscode" -import { mergePromise, TerminalProcess, TerminalProcessResultPromise } from "./TerminalProcess" +import { + TerminalInfo as ITerminalInfo, + ITerminalManager, + TerminalProcessResultPromise as ITerminalProcessResultPromise, +} from "@/shared/terminal/types" +import { mergePromise, TerminalProcess } from "./TerminalProcess" import { TerminalInfo, TerminalRegistry } from "./TerminalRegistry" /* @@ -90,7 +95,7 @@ declare module "vscode" { } } -export class TerminalManager { +export class TerminalManager implements ITerminalManager { private terminalIds: Set = new Set() private processes: Map = new Map() private disposables: vscode.Disposable[] = [] @@ -156,27 +161,30 @@ export class TerminalManager { return arePathsEqual(currentCwd, targetCwd) } - runCommand(terminalInfo: TerminalInfo, command: string): TerminalProcessResultPromise { - console.log(`[TerminalManager] Running command on terminal ${terminalInfo.id}: "${command}"`) - console.log(`[TerminalManager] Terminal ${terminalInfo.id} busy state before: ${terminalInfo.busy}`) + runCommand(terminalInfo: ITerminalInfo, command: string): ITerminalProcessResultPromise { + // Cast to VSCode-specific TerminalInfo for internal use + // Using unknown as intermediate cast due to structural differences between ITerminal and vscode.Terminal + const vscodeTerminalInfo = terminalInfo as unknown as TerminalInfo + console.log(`[TerminalManager] Running command on terminal ${vscodeTerminalInfo.id}: "${command}"`) + console.log(`[TerminalManager] Terminal ${vscodeTerminalInfo.id} busy state before: ${vscodeTerminalInfo.busy}`) - terminalInfo.busy = true - terminalInfo.lastCommand = command + vscodeTerminalInfo.busy = true + vscodeTerminalInfo.lastCommand = command const process = new TerminalProcess() - this.processes.set(terminalInfo.id, process) + this.processes.set(vscodeTerminalInfo.id, process) process.once("completed", () => { - console.log(`[TerminalManager] Terminal ${terminalInfo.id} completed, setting busy to false`) - terminalInfo.busy = false + console.log(`[TerminalManager] Terminal ${vscodeTerminalInfo.id} completed, setting busy to false`) + vscodeTerminalInfo.busy = false }) // if shell integration is not available, remove terminal so it does not get reused as it may be running a long-running process process.once("no_shell_integration", () => { - console.log(`no_shell_integration received for terminal ${terminalInfo.id}`) + console.log(`no_shell_integration received for terminal ${vscodeTerminalInfo.id}`) // Remove the terminal so we can't reuse it (in case it's running a long-running process) - TerminalRegistry.removeTerminal(terminalInfo.id) - this.terminalIds.delete(terminalInfo.id) - this.processes.delete(terminalInfo.id) + TerminalRegistry.removeTerminal(vscodeTerminalInfo.id) + this.terminalIds.delete(vscodeTerminalInfo.id) + this.processes.delete(vscodeTerminalInfo.id) }) const promise = new Promise((resolve, reject) => { @@ -184,39 +192,39 @@ export class TerminalManager { resolve() }) process.once("error", (error) => { - console.error(`Error in terminal ${terminalInfo.id}:`, error) + console.error(`Error in terminal ${vscodeTerminalInfo.id}:`, error) reject(error) }) }) // if shell integration is already active, run the command immediately - if (terminalInfo.terminal.shellIntegration) { + if (vscodeTerminalInfo.terminal.shellIntegration) { process.waitForShellIntegration = false - process.run(terminalInfo.terminal, command) + process.run(vscodeTerminalInfo.terminal, command) } else { // docs recommend waiting 3s for shell integration to activate console.log( - `[TerminalManager Test] Waiting for shell integration for terminal ${terminalInfo.id} with timeout ${this.shellIntegrationTimeout}ms`, + `[TerminalManager Test] Waiting for shell integration for terminal ${vscodeTerminalInfo.id} with timeout ${this.shellIntegrationTimeout}ms`, ) - pWaitFor(() => terminalInfo.terminal.shellIntegration !== undefined, { + pWaitFor(() => vscodeTerminalInfo.terminal.shellIntegration !== undefined, { timeout: this.shellIntegrationTimeout, }) .then(() => { console.log( - `[TerminalManager Test] Shell integration activated for terminal ${terminalInfo.id} within timeout.`, + `[TerminalManager Test] Shell integration activated for terminal ${vscodeTerminalInfo.id} within timeout.`, ) }) .catch((err) => { console.warn( - `[TerminalManager Test] Shell integration timed out or failed for terminal ${terminalInfo.id}: ${err.message}`, + `[TerminalManager Test] Shell integration timed out or failed for terminal ${vscodeTerminalInfo.id}: ${err.message}`, ) }) .finally(() => { - console.log(`[TerminalManager Test] Proceeding with command execution for terminal ${terminalInfo.id}.`) - const existingProcess = this.processes.get(terminalInfo.id) + console.log(`[TerminalManager Test] Proceeding with command execution for terminal ${vscodeTerminalInfo.id}.`) + const existingProcess = this.processes.get(vscodeTerminalInfo.id) if (existingProcess && existingProcess.waitForShellIntegration) { existingProcess.waitForShellIntegration = false - existingProcess.run(terminalInfo.terminal, command) + existingProcess.run(vscodeTerminalInfo.terminal, command) } }) } @@ -224,7 +232,7 @@ export class TerminalManager { return mergePromise(process, promise) } - async getOrCreateTerminal(cwd: string): Promise { + async getOrCreateTerminal(cwd: string): Promise { const terminals = TerminalRegistry.getAllTerminals() const expectedShellPath = this.defaultTerminalProfile !== "default" ? getShellForProfile(this.defaultTerminalProfile) : undefined @@ -254,7 +262,8 @@ export class TerminalManager { if (matchingTerminal) { console.log(`[TerminalManager] Found matching terminal ${matchingTerminal.id} in correct cwd`) this.terminalIds.add(matchingTerminal.id) - return matchingTerminal + // Cast to ITerminalInfo for interface compatibility + return matchingTerminal as unknown as ITerminalInfo } // If no non-busy terminal in the current working dir exists and terminal reuse is enabled, try to find any non-busy terminal regardless of CWD @@ -268,7 +277,8 @@ export class TerminalManager { }) // Navigate back to the desired directory - const cdProcess = this.runCommand(availableTerminal, `cd "${cwd}"`) + // Cast to ITerminalInfo for interface compatibility + const cdProcess = this.runCommand(availableTerminal as unknown as ITerminalInfo, `cd "${cwd}"`) // Wait for the cd command to complete before proceeding await cdProcess @@ -299,14 +309,16 @@ export class TerminalManager { } } this.terminalIds.add(availableTerminal.id) - return availableTerminal + // Cast to ITerminalInfo for interface compatibility + return availableTerminal as unknown as ITerminalInfo } } // If all terminals are busy or don't match shell profile, create a new one with the configured shell const newTerminalInfo = TerminalRegistry.createTerminal(cwd, expectedShellPath) this.terminalIds.add(newTerminalInfo.id) - return newTerminalInfo + // Cast to ITerminalInfo for interface compatibility + return newTerminalInfo as unknown as ITerminalInfo } getTerminals(busy: boolean): { id: number; lastCommand: string }[] { diff --git a/src/shared/terminal/StandaloneTerminal.ts b/src/shared/terminal/StandaloneTerminal.ts new file mode 100644 index 00000000..255cbd65 --- /dev/null +++ b/src/shared/terminal/StandaloneTerminal.ts @@ -0,0 +1,123 @@ +/** + * StandaloneTerminal - A terminal wrapper for standalone environments. + * + * This class provides a terminal abstraction that works outside of VSCode, + * implementing the ITerminal interface for compatibility with the terminal manager. + */ + +import type { ChildProcess } from "child_process" + +import type { ITerminal, StandaloneTerminalOptions } from "./types" + +/** + * A standalone terminal implementation that doesn't depend on VSCode. + * Used in CLI and JetBrains environments. + */ +export class StandaloneTerminal implements ITerminal { + /** Terminal name */ + name: string + + /** Promise that resolves to the process ID */ + processId: Promise + + /** Terminal creation options */ + creationOptions: StandaloneTerminalOptions + + /** Exit status (if terminal has exited) */ + exitStatus: { code: number } | undefined + + /** Terminal state */ + state: { isInteractedWith: boolean } + + /** Current working directory */ + _cwd: string + + /** Shell path */ + _shellPath: string | undefined + + /** Active child process */ + _process: ChildProcess | null = null + + /** Process ID of the active process */ + _processId: number | null = null + + /** Mock shell integration for compatibility */ + shellIntegration: { + cwd: { fsPath: string } + executeCommand: (command: string) => { + read: () => AsyncGenerator + } + } + + constructor(options: StandaloneTerminalOptions = {}) { + this.name = options.name || `Terminal ${Math.floor(Math.random() * 10000)}` + this.processId = Promise.resolve(Math.floor(Math.random() * 100000)) + this.creationOptions = options + this.exitStatus = undefined + this.state = { isInteractedWith: false } + this._cwd = options.cwd || process.cwd() + this._shellPath = options.shellPath + + // Mock shell integration for compatibility + this.shellIntegration = { + cwd: { fsPath: this._cwd }, + executeCommand: (_command: string) => { + // Return a mock execution object that the TerminalProcess expects + return { + read: async function* (): AsyncGenerator { + // This will be handled by our StandaloneTerminalProcess + yield "" + }, + } + }, + } + + console.log(`[StandaloneTerminal] Created terminal: ${this.name} in ${this._cwd}`) + } + + /** + * Send text to the terminal. + * @param text The text to send + * @param addNewLine Whether to add a newline (default: true) + */ + sendText(text: string, addNewLine: boolean = true): void { + console.log(`[StandaloneTerminal] sendText: ${text}`) + + // If we have an active process, send input to it + if (this._process && !this._process.killed) { + try { + this._process.stdin?.write(text + (addNewLine ? "\n" : "")) + } catch (error) { + console.error(`[StandaloneTerminal] Error sending text to process:`, error) + } + } else { + // For compatibility with old behavior, we could spawn a new process + console.log(`[StandaloneTerminal] No active process to send text to`) + } + } + + /** + * Show the terminal (no-op in standalone mode). + */ + show(): void { + console.log(`[StandaloneTerminal] show: ${this.name}`) + this.state.isInteractedWith = true + } + + /** + * Hide the terminal (no-op in standalone mode). + */ + hide(): void { + console.log(`[StandaloneTerminal] hide: ${this.name}`) + } + + /** + * Dispose of the terminal and kill any running process. + */ + dispose(): void { + console.log(`[StandaloneTerminal] dispose: ${this.name}`) + if (this._process && !this._process.killed) { + this._process.kill("SIGTERM") + } + } +} diff --git a/src/shared/terminal/StandaloneTerminalManager.ts b/src/shared/terminal/StandaloneTerminalManager.ts new file mode 100644 index 00000000..c71906ce --- /dev/null +++ b/src/shared/terminal/StandaloneTerminalManager.ts @@ -0,0 +1,372 @@ +/** + * StandaloneTerminalManager - Main terminal manager for standalone environments. + * + * This class provides the same interface as VSCode's TerminalManager but works + * in CLI and JetBrains environments by using subprocess management instead of + * VSCode's terminal API. + */ + +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. + * This allows the returned object to be both awaitable and have event methods. + */ +function mergePromise(process: StandaloneTerminalProcess, promise: Promise): TerminalProcessResultPromise { + const nativePromisePrototype = (async () => {})().constructor.prototype + const descriptors = ["then", "catch", "finally"].map((property) => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property), + ]) as [string, PropertyDescriptor][] + + for (const [property, descriptor] of descriptors) { + if (descriptor) { + const value = (descriptor.value as Function).bind(promise) + Reflect.defineProperty(process, property, { ...descriptor, value }) + } + } + + // Ensure terminate() is accessible on the merged promise + // This allows Task.cancelBackgroundCommand() to kill the process + if (process.terminate && typeof process.terminate === "function") { + Object.defineProperty(process, "terminate", { + value: process.terminate.bind(process), + writable: false, + enumerable: false, + configurable: false, + }) + } + + return process as unknown as TerminalProcessResultPromise +} + +/** + * Terminal manager for standalone (non-VSCode) environments. + * Implements ITerminalManager for compatibility with the Task class. + */ +export class StandaloneTerminalManager implements ITerminalManager { + /** Registry for tracking terminals */ + private registry: StandaloneTerminalRegistry = new StandaloneTerminalRegistry() + + /** Map of terminal ID to process */ + private processes: Map = new Map() + + /** Set of terminal IDs managed by this instance */ + private terminalIds: Set = new Set() + + /** Timeout for shell integration (not used in standalone, but kept for interface compatibility) */ + private shellIntegrationTimeout: number = 4000 + + /** Whether terminal reuse is enabled */ + private terminalReuseEnabled: boolean = true + + /** Maximum output lines to keep */ + private terminalOutputLineLimit: number = 500 + + /** Maximum output lines for subagent commands */ + private subagentTerminalOutputLineLimit: number = 2000 + + /** Default terminal profile */ + private defaultTerminalProfile: string = "default" + + /** + * Run a command in the specified terminal. + * @param terminalInfo The terminal to run the command in + * @param command The command to execute + * @returns A promise-like object that emits events and resolves on completion + */ + runCommand(terminalInfo: TerminalInfo, command: string): TerminalProcessResultPromise { + terminalInfo.busy = true + terminalInfo.lastCommand = command + + const process = new StandaloneTerminalProcess() + this.processes.set(terminalInfo.id, process) + + process.once("completed", () => { + terminalInfo.busy = false + }) + + process.once("error", (error: Error) => { + terminalInfo.busy = false + console.error(`[StandaloneTerminalManager] Command error on terminal ${terminalInfo.id}:`, error) + }) + + // Create promise for the process + const promise = new Promise((resolve, reject) => { + process.once("continue", () => resolve()) + process.once("error", (error: Error) => reject(error)) + }) + + // Run the command immediately (no shell integration wait needed) + process.run(terminalInfo.terminal, command) + + // Return merged promise/process object + return mergePromise(process, promise) + } + + /** + * Get or create a terminal for the specified working directory. + * @param cwd The working directory for the terminal + * @returns The terminal info for an available terminal + */ + async getOrCreateTerminal(cwd: string): Promise { + const terminals = this.registry.getAllTerminals() + + // Find available terminal with matching CWD + const matchingTerminal = terminals.find((t) => { + if (t.busy) { + return false + } + return (t.terminal as any)._cwd === cwd + }) + + if (matchingTerminal) { + this.terminalIds.add(matchingTerminal.id) + return matchingTerminal + } + + // Find any available terminal if reuse is enabled + if (this.terminalReuseEnabled) { + const availableTerminal = terminals.find((t) => !t.busy) + if (availableTerminal) { + // Change directory + await this.runCommand(availableTerminal, `cd "${cwd}"`) + ;(availableTerminal.terminal as any)._cwd = cwd + if (availableTerminal.terminal.shellIntegration?.cwd) { + availableTerminal.terminal.shellIntegration.cwd.fsPath = cwd + } + this.terminalIds.add(availableTerminal.id) + console.log(`[StandaloneTerminalManager] Reused terminal ${availableTerminal.id} with cd`) + return availableTerminal + } + } + + // Create new terminal + const newTerminalInfo = this.registry.createTerminal({ + cwd: cwd, + name: `Cline Terminal ${this.registry.size + 1}`, + }) + this.terminalIds.add(newTerminalInfo.id) + return newTerminalInfo + } + + /** + * Get terminals filtered by busy state. + * @param busy Whether to get busy or idle terminals + * @returns Array of terminal info with id and last command + */ + getTerminals(busy: boolean): { id: number; lastCommand: string }[] { + return Array.from(this.terminalIds) + .map((id) => this.registry.getTerminal(id)) + .filter((t): t is TerminalInfo => t !== undefined && t.busy === busy) + .map((t) => ({ id: t.id, lastCommand: t.lastCommand })) + } + + /** + * Get output that hasn't been retrieved yet from a terminal. + * @param terminalId The terminal ID + * @returns The unretrieved output string + */ + getUnretrievedOutput(terminalId: number): string { + if (!this.terminalIds.has(terminalId)) { + return "" + } + const process = this.processes.get(terminalId) + return process ? process.getUnretrievedOutput() : "" + } + + /** + * Check if a terminal's process is actively outputting. + * @param terminalId The terminal ID + * @returns Whether the process is hot + */ + isProcessHot(terminalId: number): boolean { + const process = this.processes.get(terminalId) + return process ? process.isHot : false + } + + /** + * Process output lines, potentially truncating if over limit. + * @param outputLines Array of output lines + * @param overrideLimit Optional limit override + * @param isSubagentCommand Whether this is a subagent command + * @returns Processed output string + */ + processOutput(outputLines: string[], overrideLimit?: number, isSubagentCommand?: boolean): string { + const limit = isSubagentCommand + ? overrideLimit !== undefined + ? overrideLimit + : this.subagentTerminalOutputLineLimit + : this.terminalOutputLineLimit + if (outputLines.length > limit) { + const halfLimit = Math.floor(limit / 2) + const start = outputLines.slice(0, halfLimit) + const end = outputLines.slice(outputLines.length - halfLimit) + return `${start.join("\n")}\n... (output truncated) ...\n${end.join("\n")}`.trim() + } + return outputLines.join("\n").trim() + } + + /** + * Dispose of all terminals and clean up resources. + */ + disposeAll(): void { + // Terminate all processes + for (const [_terminalId, process] of this.processes) { + if (process && process.terminate) { + process.terminate() + } + } + + // Clear all tracking + this.terminalIds.clear() + this.processes.clear() + + // Dispose all terminals + for (const terminalInfo of this.registry.getAllTerminals()) { + terminalInfo.terminal.dispose() + } + + this.registry.clear() + } + + /** + * Set the timeout for waiting for shell integration. + * @param timeout Timeout in milliseconds + */ + setShellIntegrationTimeout(timeout: number): void { + this.shellIntegrationTimeout = timeout + } + + /** + * Enable or disable terminal reuse. + * @param enabled Whether to enable terminal reuse + */ + setTerminalReuseEnabled(enabled: boolean): void { + this.terminalReuseEnabled = enabled + } + + /** + * Set the maximum number of output lines to keep. + * @param limit Maximum number of lines + */ + setTerminalOutputLineLimit(limit: number): void { + this.terminalOutputLineLimit = limit + } + + /** + * Set the maximum number of output lines for subagent commands. + * @param limit Maximum number of lines + */ + setSubagentTerminalOutputLineLimit(limit: number): void { + this.subagentTerminalOutputLineLimit = limit + } + + /** + * Set the default terminal profile. + * @param profile The profile identifier + * @returns Object with information about closed terminals and remaining busy terminals + */ + setDefaultTerminalProfile(profile: string): { closedCount: number; busyTerminals: TerminalInfo[] } { + const previousProfile = this.defaultTerminalProfile + this.defaultTerminalProfile = profile + + // If profile changed, handle terminal cleanup like TerminalManager does + if (previousProfile !== profile) { + return this.handleTerminalProfileChange(profile) + } + + return { closedCount: 0, busyTerminals: [] } + } + + // Additional methods required for TerminalManager compatibility + + /** Disposables array (for VSCode compatibility) */ + disposables: any[] = [] + + /** + * Find a TerminalInfo by its terminal instance. + * @param terminal The terminal instance to find + * @returns The terminal info or undefined + */ + findTerminalInfoByTerminal(terminal: any): TerminalInfo | undefined { + const terminals = this.registry.getAllTerminals() + return terminals.find((t) => t.terminal === terminal) + } + + /** + * Check if a terminal's CWD matches its expected pending change. + * @param terminalInfo The terminal info to check + * @returns Whether the CWD matches + */ + isCwdMatchingExpected(terminalInfo: TerminalInfo): boolean { + if (!(terminalInfo as any).pendingCwdChange) { + return false + } + const currentCwd = (terminalInfo.terminal as any)._cwd + const targetCwd = (terminalInfo as any).pendingCwdChange + return currentCwd === targetCwd + } + + /** + * Filter terminals based on a provided criteria function. + * @param filterFn Function that accepts TerminalInfo and returns boolean + * @returns Array of terminals that match the criteria + */ + filterTerminals(filterFn: (terminal: TerminalInfo) => boolean): TerminalInfo[] { + const terminals = this.registry.getAllTerminals() + return terminals.filter(filterFn) + } + + /** + * Close terminals that match the provided criteria. + * @param filterFn Function that accepts TerminalInfo and returns boolean for terminals to close + * @param force If true, closes even busy terminals + * @returns Number of terminals closed + */ + closeTerminals(filterFn: (terminal: TerminalInfo) => boolean, force: boolean = false): number { + const terminalsToClose = this.filterTerminals(filterFn) + let closedCount = 0 + + for (const terminalInfo of terminalsToClose) { + if (terminalInfo.busy && !force) { + continue + } + + this.terminalIds.delete(terminalInfo.id) + this.processes.delete(terminalInfo.id) + terminalInfo.terminal.dispose() + this.registry.removeTerminal(terminalInfo.id) + closedCount++ + } + + return closedCount + } + + /** + * Handle terminal management when the terminal profile changes. + * @param newShellPath New shell path to use + * @returns Object with information about closed terminals and remaining busy terminals + */ + handleTerminalProfileChange(newShellPath: string | undefined): { + closedCount: number + busyTerminals: TerminalInfo[] + } { + const closedCount = this.closeTerminals( + (terminal) => !terminal.busy && (terminal as any).shellPath !== newShellPath, + false, + ) + const busyTerminals = this.filterTerminals((terminal) => terminal.busy && (terminal as any).shellPath !== newShellPath) + return { closedCount, busyTerminals } + } + + /** + * Force closure of all terminals (including busy ones). + * @returns Number of terminals closed + */ + closeAllTerminals(): number { + return this.closeTerminals(() => true, true) + } +} diff --git a/src/shared/terminal/StandaloneTerminalProcess.ts b/src/shared/terminal/StandaloneTerminalProcess.ts new file mode 100644 index 00000000..09f82798 --- /dev/null +++ b/src/shared/terminal/StandaloneTerminalProcess.ts @@ -0,0 +1,340 @@ +/** + * StandaloneTerminalProcess - Manages command execution in standalone environments. + * + * 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. + */ + +import { ChildProcess, spawn } from "child_process" +import { EventEmitter } from "events" + +import type { ITerminal, ITerminalProcessResult } from "./types" + +/** + * Manages the execution of a command in a standalone terminal environment. + * Extends EventEmitter to provide real-time output streaming. + * + * 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 + */ +export class StandaloneTerminalProcess extends EventEmitter implements ITerminalProcessResult { + /** We don't need to wait since we control the process directly */ + waitForShellIntegration: boolean = false + + /** Whether we're actively listening for output */ + isListening: boolean = true + + /** Buffer for incomplete lines */ + private buffer: string = "" + + /** Full output captured from the process */ + private fullOutput: string = "" + + /** Index of last retrieved output position */ + private lastRetrievedIndex: number = 0 + + /** Whether the process is actively outputting */ + isHot: boolean = false + + /** Timer for tracking hot state */ + private hotTimer: NodeJS.Timeout | null = null + + /** The spawned child process */ + private childProcess: ChildProcess | null = null + + /** Exit code from the process */ + private exitCode: number | null = null + + /** Whether the process has completed */ + private isCompleted: boolean = false + + constructor() { + super() + } + + /** + * Run a command in the terminal. + * @param terminal The terminal instance to run in + * @param command The command to execute + */ + async run(terminal: ITerminal, command: string): Promise { + console.log(`[StandaloneTerminal] Running command: ${command}`) + + // Get shell and working directory from terminal + const shell = (terminal as any)._shellPath || this.getDefaultShell() + const cwd = (terminal as any)._cwd || process.cwd() + + // Prepare command for execution + const shellArgs = this.getShellArgs(shell, command) + + try { + // Create shell options + const shellOptions: { + cwd: string + stdio: ["ignore", "pipe", "pipe"] + env: NodeJS.ProcessEnv + shell?: boolean + } = { + cwd: cwd, + stdio: ["ignore", "pipe", "pipe"], // Disable STDIN to prevent interactivity + env: { + ...process.env, + TERM: "xterm-256color", + PAGER: "cat", // Prevent less from being used, reducing interactivity + EDITOR: process.env.EDITOR || "cat", // Set EDITOR if not already set + GIT_PAGER: "cat", // Prevent git from using less + SYSTEMD_PAGER: "", // Disable systemd pager + MANPAGER: "cat", // Disable man pager + }, + } + + // Enable the shell option for "cmd.exe" to prevent double quotes from being over escaped + if (shell.toLowerCase().includes("cmd")) { + shellOptions.shell = true + + // Spawn the process with special handling for "cmd.exe" + this.childProcess = spawn("cmd.exe", shellArgs, shellOptions) + } else { + // Spawn the process + this.childProcess = spawn(shell, shellArgs, shellOptions) + } + + // Track process state + let didEmitEmptyLine = false + + // Handle stdout + this.childProcess.stdout?.on("data", (data: Buffer) => { + const output = data.toString() + this.handleOutput(output, didEmitEmptyLine) + if (!didEmitEmptyLine && output) { + this.emit("line", "") // Signal start of output + didEmitEmptyLine = true + } + }) + + // Handle stderr + this.childProcess.stderr?.on("data", (data: Buffer) => { + const output = data.toString() + this.handleOutput(output, didEmitEmptyLine) + if (!didEmitEmptyLine && output) { + this.emit("line", "") + didEmitEmptyLine = true + } + }) + + // Handle process completion + this.childProcess.on("close", (code: number | null, signal: NodeJS.Signals | null) => { + console.log(`[StandaloneTerminal] Process closed with code ${code}, signal ${signal}`) + this.exitCode = code + this.isCompleted = true + this.emitRemainingBuffer() + + // Clear hot timer + if (this.hotTimer) { + clearTimeout(this.hotTimer) + this.isHot = false + } + + this.emit("completed") + this.emit("continue") + }) + + // Handle process errors + this.childProcess.on("error", (error: Error) => { + console.error(`[StandaloneTerminal] Process error:`, error) + this.emit("error", error) + }) + + // Update terminal's process reference + ;(terminal as any)._process = this.childProcess + ;(terminal as any)._processId = this.childProcess.pid + } catch (error) { + console.error(`[StandaloneTerminal] Failed to spawn process:`, error) + this.emit("error", error) + } + } + + /** + * Handle output from the process. + * @param data The output data + * @param _didEmitEmptyLine Whether we've already emitted an empty line + */ + private handleOutput(data: string, _didEmitEmptyLine: boolean): void { + // Set process as hot (actively outputting) + this.isHot = true + if (this.hotTimer) { + clearTimeout(this.hotTimer) + } + + // Check for compilation markers to adjust hot timeout + const compilingMarkers = ["compiling", "building", "bundling", "transpiling", "generating", "starting"] + const markerNullifiers = [ + "compiled", + "success", + "finish", + "complete", + "succeed", + "done", + "end", + "stop", + "exit", + "terminate", + "error", + "fail", + ] + + const isCompiling = + compilingMarkers.some((marker) => data.toLowerCase().includes(marker.toLowerCase())) && + !markerNullifiers.some((nullifier) => data.toLowerCase().includes(nullifier.toLowerCase())) + + const hotTimeout = isCompiling ? 15000 : 2000 + this.hotTimer = setTimeout(() => { + this.isHot = false + }, hotTimeout) + + // Store full output + this.fullOutput += data + + if (this.isListening) { + this.emitLines(data) + this.lastRetrievedIndex = this.fullOutput.length - this.buffer.length + } + } + + /** + * Emit lines from the buffer. + * @param chunk The chunk of data to process + */ + private emitLines(chunk: string): void { + this.buffer += chunk + let lineEndIndex: number + while ((lineEndIndex = this.buffer.indexOf("\n")) !== -1) { + const line = this.buffer.slice(0, lineEndIndex).trimEnd() + this.emit("line", line) + this.buffer = this.buffer.slice(lineEndIndex + 1) + } + } + + /** + * Emit any remaining content in the buffer. + */ + private emitRemainingBuffer(): void { + if (this.buffer && this.isListening) { + const remainingBuffer = this.removeLastLineArtifacts(this.buffer) + if (remainingBuffer) { + this.emit("line", remainingBuffer) + } + this.buffer = "" + this.lastRetrievedIndex = this.fullOutput.length + } + } + + /** + * Continue execution without waiting for completion. + * Stops event emission and resolves the promise. + */ + continue(): void { + this.emitRemainingBuffer() + this.isListening = false + this.removeAllListeners("line") + this.emit("continue") + } + + /** + * Get output that hasn't been retrieved yet. + * @returns The unretrieved output + */ + getUnretrievedOutput(): string { + const unretrieved = this.fullOutput.slice(this.lastRetrievedIndex) + this.lastRetrievedIndex = this.fullOutput.length + return this.removeLastLineArtifacts(unretrieved) + } + + /** + * Remove shell prompt artifacts from the end of output. + * @param output The output to clean + * @returns Cleaned output + */ + private removeLastLineArtifacts(output: string): string { + const lines = output.trimEnd().split("\n") + if (lines.length > 0) { + const lastLine = lines[lines.length - 1] + lines[lines.length - 1] = lastLine.replace(/[%$#>]\s*$/, "") + } + return lines.join("\n").trimEnd() + } + + /** + * Get the default shell for the current platform. + * @returns The default shell path + */ + private getDefaultShell(): string { + if (process.platform === "win32") { + return process.env.COMSPEC || "cmd.exe" + } else { + return process.env.SHELL || "/bin/bash" + } + } + + /** + * Get shell arguments for executing a command. + * @param shell The shell path + * @param command The command to execute + * @returns Array of shell arguments + */ + private getShellArgs(shell: string, command: string): string[] { + if (process.platform === "win32") { + if (shell.toLowerCase().includes("powershell") || shell.toLowerCase().includes("pwsh")) { + return ["-Command", command] + } else { + return ["/c", command] + } + } else { + // Use -l for login shell, -c for command + return ["-l", "-c", command] + } + } + + /** + * Terminate the process if it's still running. + */ + terminate(): void { + if (!this.childProcess || this.isCompleted) { + console.log(`[StandaloneTerminal] Process already completed or doesn't exist, skipping termination`) + return + } + + const pid = this.childProcess.pid + console.log(`[StandaloneTerminal] Terminating process ${pid} with SIGTERM`) + + try { + this.childProcess.kill("SIGTERM") + + // Force kill after timeout if process doesn't exit gracefully + setTimeout(() => { + if (!this.isCompleted && this.childProcess) { + console.log(`[StandaloneTerminal] Process ${pid} did not exit gracefully, force killing with SIGKILL`) + try { + this.childProcess.kill("SIGKILL") + } catch (killError) { + console.error(`[StandaloneTerminal] Failed to force kill process ${pid}:`, killError) + } + } else { + console.log(`[StandaloneTerminal] Process ${pid} exited gracefully`) + } + }, 5000) + } catch (error) { + console.error(`[StandaloneTerminal] Failed to send SIGTERM to process ${pid}:`, error) + // Try SIGKILL immediately if SIGTERM fails + try { + this.childProcess.kill("SIGKILL") + } catch (killError) { + console.error(`[StandaloneTerminal] Failed to send SIGKILL to process ${pid}:`, killError) + } + } + } +} diff --git a/src/shared/terminal/StandaloneTerminalRegistry.ts b/src/shared/terminal/StandaloneTerminalRegistry.ts new file mode 100644 index 00000000..95841327 --- /dev/null +++ b/src/shared/terminal/StandaloneTerminalRegistry.ts @@ -0,0 +1,108 @@ +/** + * StandaloneTerminalRegistry - Manages terminal instances in standalone environments. + * + * This class tracks and manages multiple terminal instances, providing + * functionality to create, retrieve, update, and remove terminals. + */ + +import { StandaloneTerminal } from "./StandaloneTerminal" +import type { ITerminal, StandaloneTerminalOptions, TerminalInfo } from "./types" + +/** + * Registry for tracking standalone terminal instances. + * Provides CRUD operations for terminal management. + */ +export class StandaloneTerminalRegistry { + /** Map of terminal ID to terminal info */ + private terminals: Map = new Map() + + /** Next available terminal ID */ + private nextId: number = 1 + + /** + * Create a new terminal and register it. + * @param options Terminal creation options + * @returns The created terminal info + */ + createTerminal(options: StandaloneTerminalOptions = {}): TerminalInfo { + const terminal = new StandaloneTerminal(options) + const id = this.nextId++ + + const terminalInfo: TerminalInfo = { + id: id, + terminal: terminal as ITerminal, + busy: false, + lastCommand: "", + shellPath: options.shellPath, + lastActive: Date.now(), + pendingCwdChange: undefined, + cwdResolved: undefined, + } + + this.terminals.set(id, terminalInfo) + console.log(`[StandaloneTerminalRegistry] Created terminal ${id}`) + return terminalInfo + } + + /** + * Get a terminal by ID. + * @param id The terminal ID + * @returns The terminal info or undefined if not found + */ + getTerminal(id: number): TerminalInfo | undefined { + return this.terminals.get(id) + } + + /** + * Get all registered terminals. + * @returns Array of all terminal info objects + */ + getAllTerminals(): TerminalInfo[] { + return Array.from(this.terminals.values()) + } + + /** + * Remove a terminal from the registry and dispose it. + * @param id The terminal ID to remove + */ + removeTerminal(id: number): void { + const terminalInfo = this.terminals.get(id) + if (terminalInfo) { + terminalInfo.terminal.dispose() + this.terminals.delete(id) + console.log(`[StandaloneTerminalRegistry] Removed terminal ${id}`) + } + } + + /** + * Update a terminal's properties. + * @param id The terminal ID + * @param updates Partial terminal info to update + */ + updateTerminal(id: number, updates: Partial): void { + const terminalInfo = this.terminals.get(id) + if (terminalInfo) { + Object.assign(terminalInfo, updates) + } + } + + /** + * Clear all terminals from the registry. + */ + clear(): void { + for (const terminalInfo of this.terminals.values()) { + terminalInfo.terminal.dispose() + } + this.terminals.clear() + this.nextId = 1 + console.log(`[StandaloneTerminalRegistry] Cleared all terminals`) + } + + /** + * Get the count of registered terminals. + * @returns Number of terminals + */ + get size(): number { + return this.terminals.size + } +} diff --git a/src/shared/terminal/index.ts b/src/shared/terminal/index.ts new file mode 100644 index 00000000..10150f78 --- /dev/null +++ b/src/shared/terminal/index.ts @@ -0,0 +1,35 @@ +/** + * Shared terminal module for both VSCode and Standalone environments. + * + * This module provides terminal management functionality that works across: + * - VSCode Extension (using VSCode's terminal API or background execution) + * - CLI (using StandaloneTerminalManager) + * - JetBrains (using StandaloneTerminalManager via cline-core) + * + * @example + * ```typescript + * import { StandaloneTerminalManager, ITerminalManager } from "@shared/terminal" + * + * const manager: ITerminalManager = new StandaloneTerminalManager() + * const terminalInfo = await manager.getOrCreateTerminal("/path/to/cwd") + * const process = manager.runCommand(terminalInfo, "npm install") + * + * process.on("line", (line) => console.log(line)) + * await process + * ``` + */ + +export { StandaloneTerminal } from "./StandaloneTerminal" +export { StandaloneTerminalManager } from "./StandaloneTerminalManager" +// Export standalone implementations +export { StandaloneTerminalProcess } from "./StandaloneTerminalProcess" +export { StandaloneTerminalRegistry } from "./StandaloneTerminalRegistry" +// Export all types +export type { + ITerminal, + ITerminalManager, + ITerminalProcessResult, + StandaloneTerminalOptions, + TerminalInfo, + TerminalProcessResultPromise, +} from "./types" diff --git a/src/shared/terminal/types.ts b/src/shared/terminal/types.ts new file mode 100644 index 00000000..f2e87d10 --- /dev/null +++ b/src/shared/terminal/types.ts @@ -0,0 +1,189 @@ +/** + * Shared terminal types and interfaces for both VSCode and Standalone terminal managers. + * These types ensure compatibility between the VSCode-based TerminalManager and + * the StandaloneTerminalManager used in CLI/JetBrains environments. + */ + +import { EventEmitter } from "events" + +/** + * Represents a terminal instance with its metadata and state. + */ +export interface TerminalInfo { + /** Unique identifier for the terminal */ + id: number + /** The underlying terminal instance */ + terminal: ITerminal + /** Whether the terminal is currently executing a command */ + busy: boolean + /** The last command executed in this terminal */ + lastCommand: string + /** The shell path used by this terminal (e.g., /bin/bash, /bin/zsh) */ + shellPath?: string + /** Timestamp of last activity */ + lastActive: number + /** Pending CWD change path (used for tracking directory changes) */ + pendingCwdChange?: string + /** Promise resolver for CWD change completion */ + cwdResolved?: { resolve: () => void; reject: (err: Error) => void } +} + +/** + * Minimal terminal interface that both VSCode terminals and standalone terminals implement. + */ +export interface ITerminal { + /** Terminal name */ + name: string + /** Promise that resolves to the process ID */ + processId: Promise + /** Shell integration information (if available) */ + shellIntegration?: { + cwd?: { fsPath: string } + executeCommand?: (command: string) => { + read: () => AsyncIterable + } + } + /** Send text to the terminal */ + sendText(text: string, addNewLine?: boolean): void + /** Show the terminal */ + show(): void + /** Hide the terminal */ + hide(): void + /** Dispose of the terminal */ + dispose(): void +} + +/** + * Terminal process result that combines Promise functionality with event emission. + * Allows for both awaiting completion and listening to real-time output. + */ +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 +} + +/** + * Promise-like interface for terminal process results. + * Combines Promise with ITerminalProcessResult for flexible usage. + */ +export type TerminalProcessResultPromise = Promise & + ITerminalProcessResult & { + /** Listen for line output events */ + on(event: "line", listener: (line: string) => void): TerminalProcessResultPromise + /** Listen for completion event */ + on(event: "completed", listener: () => void): TerminalProcessResultPromise + /** Listen for continue event */ + on(event: "continue", listener: () => void): TerminalProcessResultPromise + /** Listen for error events */ + on(event: "error", listener: (error: Error) => void): TerminalProcessResultPromise + /** Listen for no shell integration event */ + on(event: "no_shell_integration", listener: () => void): TerminalProcessResultPromise + /** Listen once for any event */ + once(event: string, listener: (...args: any[]) => void): TerminalProcessResultPromise + } + +/** + * Interface for terminal managers (both VSCode and Standalone implementations). + * Defines the contract that both implementations must follow. + */ +export interface ITerminalManager { + /** + * Run a command in the specified terminal. + * @param terminalInfo The terminal to run the command in + * @param command The command to execute + * @returns A promise-like object that emits events and resolves on completion + */ + runCommand(terminalInfo: TerminalInfo, command: string): TerminalProcessResultPromise + + /** + * Get or create a terminal for the specified working directory. + * @param cwd The working directory for the terminal + * @returns The terminal info for an available terminal + */ + getOrCreateTerminal(cwd: string): Promise + + /** + * Get terminals filtered by busy state. + * @param busy Whether to get busy or idle terminals + * @returns Array of terminal info with id and last command + */ + getTerminals(busy: boolean): { id: number; lastCommand: string }[] + + /** + * Get output that hasn't been retrieved yet from a terminal. + * @param terminalId The terminal ID + * @returns The unretrieved output string + */ + getUnretrievedOutput(terminalId: number): string + + /** + * Check if a terminal's process is actively outputting. + * @param terminalId The terminal ID + * @returns Whether the process is hot + */ + isProcessHot(terminalId: number): boolean + + /** + * Dispose of all terminals and clean up resources. + */ + disposeAll(): void + + /** + * Set the timeout for waiting for shell integration. + * @param timeout Timeout in milliseconds + */ + setShellIntegrationTimeout(timeout: number): void + + /** + * Enable or disable terminal reuse. + * @param enabled Whether to enable terminal reuse + */ + setTerminalReuseEnabled(enabled: boolean): void + + /** + * Set the maximum number of output lines to keep. + * @param limit Maximum number of lines + */ + setTerminalOutputLineLimit(limit: number): void + + /** + * Set the maximum number of output lines for subagent commands. + * @param limit Maximum number of lines + */ + setSubagentTerminalOutputLineLimit(limit: number): void + + /** + * Set the default terminal profile. + * @param profile The profile identifier + */ + setDefaultTerminalProfile(profile: string): void + + /** + * Process output lines, potentially truncating if over limit. + * @param outputLines Array of output lines + * @param overrideLimit Optional limit override + * @param isSubagentCommand Whether this is a subagent command + * @returns Processed output string + */ + processOutput(outputLines: string[], overrideLimit?: number, isSubagentCommand?: boolean): string +} + +/** + * Options for creating a standalone terminal. + */ +export interface StandaloneTerminalOptions { + /** Terminal name */ + name?: string + /** Working directory */ + cwd?: string + /** Shell path to use */ + shellPath?: string +} diff --git a/src/standalone/cline-core.ts b/src/standalone/cline-core.ts index 2f5c92b2..4d8b4e24 100644 --- a/src/standalone/cline-core.ts +++ b/src/standalone/cline-core.ts @@ -10,6 +10,7 @@ import { WebviewProvider } from "@/core/webview" import { AuthHandler } from "@/hosts/external/AuthHandler" import { HostProvider } from "@/hosts/host-provider" import { DiffViewProvider } from "@/integrations/editor/DiffViewProvider" +import { StandaloneTerminalManager } from "@/shared/terminal" import { HOSTBRIDGE_PORT, waitForHostBridgeReady } from "./hostbridge-client" import { setLockManager } from "./lock-manager" import { PROTOBUS_PORT, startProtobusService } from "./protobus-service" @@ -104,6 +105,7 @@ function setupHostProvider(extensionContext: any, extensionDir: string, dataDir: return new ExternalDiffViewProvider() } const createCommentReview = () => new ExternalCommentReviewController() + const createTerminalManager = () => new StandaloneTerminalManager() const getCallbackUrl = (): Promise => { return AuthHandler.getInstance().getCallbackUrl() } @@ -114,6 +116,7 @@ function setupHostProvider(extensionContext: any, extensionDir: string, dataDir: createWebview, createDiffView, createCommentReview, + createTerminalManager, new ExternalHostBridgeClientManager(), log, getCallbackUrl, diff --git a/src/test/host-provider-test-utils.ts b/src/test/host-provider-test-utils.ts index b6be7a4a..ab005c5c 100644 --- a/src/test/host-provider-test-utils.ts +++ b/src/test/host-provider-test-utils.ts @@ -2,10 +2,12 @@ import { CommentReviewControllerCreator, DiffViewProviderCreator, HostProvider, + TerminalManagerCreator, WebviewProviderCreator, } from "@/hosts/host-provider" import { HostBridgeClientProvider } from "@/hosts/host-provider-types" import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-grpc-client" +import { ITerminalManager } from "@/shared/terminal/types" /** * Initializes the HostProvider with test defaults. @@ -17,6 +19,7 @@ export function setVscodeHostProviderMock(options?: { webviewProviderCreator?: WebviewProviderCreator diffViewProviderCreator?: DiffViewProviderCreator commentReviewControllerCreator?: CommentReviewControllerCreator + terminalManagerCreator?: TerminalManagerCreator hostBridgeClient?: HostBridgeClientProvider logToChannel?: (message: string) => void getCallbackUri?: () => Promise @@ -29,10 +32,11 @@ export function setVscodeHostProviderMock(options?: { options?.webviewProviderCreator ?? ((() => {}) as WebviewProviderCreator), options?.diffViewProviderCreator ?? ((() => {}) as DiffViewProviderCreator), options?.commentReviewControllerCreator ?? ((() => {}) as CommentReviewControllerCreator), + options?.terminalManagerCreator ?? ((() => ({}) as ITerminalManager) as TerminalManagerCreator), options?.hostBridgeClient ?? vscodeHostBridgeClient, - options?.logToChannel ?? ((_) => {}), + options?.logToChannel ?? ((_: string) => {}), options?.getCallbackUri ?? (async () => "http://example.com:1234/"), - options?.getBinaryLocation ?? (async (n) => `/mock/path/to/binary/${n}`), + options?.getBinaryLocation ?? (async (n: string) => `/mock/path/to/binary/${n}`), options?.extensionFsPath ?? "/mock/path/to/extension", options?.globalStorageFsPath ?? "/mock/path/to/globalstorage", ) diff --git a/standalone/runtime-files/vscode/enhanced-terminal.js b/standalone/runtime-files/vscode/enhanced-terminal.js deleted file mode 100644 index d4561a93..00000000 --- a/standalone/runtime-files/vscode/enhanced-terminal.js +++ /dev/null @@ -1,576 +0,0 @@ -const { spawn } = require("child_process") -const { EventEmitter } = require("events") -const _path = require("path") -const _os = require("os") - -// Enhanced terminal management for standalone Cline -// This replaces VSCode's terminal integration with real subprocess management - -class StandaloneTerminalProcess extends EventEmitter { - constructor() { - super() - this.waitForShellIntegration = false // We don't need to wait since we control the process - this.isListening = true - this.buffer = "" - this.fullOutput = "" - this.lastRetrievedIndex = 0 - this.isHot = false - this.hotTimer = null - this.childProcess = null - this.exitCode = null - this.isCompleted = false - } - - async run(terminal, command) { - console.log(`[StandaloneTerminal] Running command: ${command}`) - - // Get shell and working directory from terminal - const shell = terminal._shellPath || this.getDefaultShell() - const cwd = terminal._cwd || process.cwd() - - // Prepare command for execution - const shellArgs = this.getShellArgs(shell, command) - - try { - // Create shell options - const shellOptions = { - cwd: cwd, - stdio: ["ignore", "pipe", "pipe"], // Disable STDIN to prevent interactivity - env: { - ...process.env, - TERM: "xterm-256color", - PAGER: "cat", // Prevent less from being used, reducing interactivity - EDITOR: process.env.EDITOR || "cat", // Set EDITOR if not already set - GIT_PAGER: "cat", // Prevent git from using less - SYSTEMD_PAGER: "", // Disable systemd pager - MANPAGER: "cat", // Disable man pager - }, - } - - // Enable the shell option for "cmd.exe" to prevent double quotes from being over escaped - if (shell.toLowerCase().includes("cmd")) { - shellOptions.shell = true - - // Spawn the process with special handling for "cmd.exe" - this.childProcess = spawn("cmd.exe", shellArgs, shellOptions) - } else { - // Spawn the process - this.childProcess = spawn(shell, shellArgs, shellOptions) - } - - // Track process state - let didEmitEmptyLine = false - - // Handle stdout - this.childProcess.stdout.on("data", (data) => { - const output = data.toString() - this.handleOutput(output, didEmitEmptyLine) - if (!didEmitEmptyLine && output) { - this.emit("line", "") // Signal start of output - didEmitEmptyLine = true - } - }) - - // Handle stderr - this.childProcess.stderr.on("data", (data) => { - const output = data.toString() - this.handleOutput(output, didEmitEmptyLine) - if (!didEmitEmptyLine && output) { - this.emit("line", "") - didEmitEmptyLine = true - } - }) - - // Handle process completion - this.childProcess.on("close", (code, signal) => { - console.log(`[StandaloneTerminal] Process closed with code ${code}, signal ${signal}`) - this.exitCode = code - this.isCompleted = true - this.emitRemainingBuffer() - - // Clear hot timer - if (this.hotTimer) { - clearTimeout(this.hotTimer) - this.isHot = false - } - - this.emit("completed") - this.emit("continue") - }) - - // Handle process errors - this.childProcess.on("error", (error) => { - console.error(`[StandaloneTerminal] Process error:`, error) - this.emit("error", error) - }) - - // Update terminal's process reference - terminal._process = this.childProcess - terminal._processId = this.childProcess.pid - } catch (error) { - console.error(`[StandaloneTerminal] Failed to spawn process:`, error) - this.emit("error", error) - } - } - - handleOutput(data, _didEmitEmptyLine) { - // Set process as hot (actively outputting) - this.isHot = true - if (this.hotTimer) { - clearTimeout(this.hotTimer) - } - - // Check for compilation markers to adjust hot timeout - const compilingMarkers = ["compiling", "building", "bundling", "transpiling", "generating", "starting"] - const markerNullifiers = [ - "compiled", - "success", - "finish", - "complete", - "succeed", - "done", - "end", - "stop", - "exit", - "terminate", - "error", - "fail", - ] - - const isCompiling = - compilingMarkers.some((marker) => data.toLowerCase().includes(marker.toLowerCase())) && - !markerNullifiers.some((nullifier) => data.toLowerCase().includes(nullifier.toLowerCase())) - - const hotTimeout = isCompiling ? 15000 : 2000 - this.hotTimer = setTimeout(() => { - this.isHot = false - }, hotTimeout) - - // Store full output - this.fullOutput += data - - if (this.isListening) { - this.emitLines(data) - this.lastRetrievedIndex = this.fullOutput.length - this.buffer.length - } - } - - emitLines(chunk) { - this.buffer += chunk - let lineEndIndex - while ((lineEndIndex = this.buffer.indexOf("\n")) !== -1) { - const line = this.buffer.slice(0, lineEndIndex).trimEnd() - this.emit("line", line) - this.buffer = this.buffer.slice(lineEndIndex + 1) - } - } - - emitRemainingBuffer() { - if (this.buffer && this.isListening) { - const remainingBuffer = this.removeLastLineArtifacts(this.buffer) - if (remainingBuffer) { - this.emit("line", remainingBuffer) - } - this.buffer = "" - this.lastRetrievedIndex = this.fullOutput.length - } - } - - continue() { - this.emitRemainingBuffer() - this.isListening = false - this.removeAllListeners("line") - this.emit("continue") - } - - getUnretrievedOutput() { - const unretrieved = this.fullOutput.slice(this.lastRetrievedIndex) - this.lastRetrievedIndex = this.fullOutput.length - return this.removeLastLineArtifacts(unretrieved) - } - - removeLastLineArtifacts(output) { - const lines = output.trimEnd().split("\n") - if (lines.length > 0) { - const lastLine = lines[lines.length - 1] - lines[lines.length - 1] = lastLine.replace(/[%$#>]\s*$/, "") - } - return lines.join("\n").trimEnd() - } - - getDefaultShell() { - if (process.platform === "win32") { - return process.env.COMSPEC || "cmd.exe" - } else { - return process.env.SHELL || "/bin/bash" - } - } - - getShellArgs(shell, command) { - if (process.platform === "win32") { - if (shell.toLowerCase().includes("powershell") || shell.toLowerCase().includes("pwsh")) { - return ["-Command", command] - } else { - return ["/c", command] - } - } else { - // Use -l for login shell, -c for command - return ["-l", "-c", command] - } - } - - // Terminate the process if it's still running - terminate() { - if (!this.childProcess || this.isCompleted) { - console.log(`[StandaloneTerminal] Process already completed or doesn't exist, skipping termination`) - return - } - - const pid = this.childProcess.pid - console.log(`[StandaloneTerminal] Terminating process ${pid} with SIGTERM`) - - try { - this.childProcess.kill("SIGTERM") - - // Force kill after timeout if process doesn't exit gracefully - setTimeout(() => { - if (!this.isCompleted && this.childProcess) { - console.log(`[StandaloneTerminal] Process ${pid} did not exit gracefully, force killing with SIGKILL`) - try { - this.childProcess.kill("SIGKILL") - } catch (killError) { - console.error(`[StandaloneTerminal] Failed to force kill process ${pid}:`, killError) - } - } else { - console.log(`[StandaloneTerminal] Process ${pid} exited gracefully`) - } - }, 5000) - } catch (error) { - console.error(`[StandaloneTerminal] Failed to send SIGTERM to process ${pid}:`, error) - // Try SIGKILL immediately if SIGTERM fails - try { - this.childProcess.kill("SIGKILL") - } catch (killError) { - console.error(`[StandaloneTerminal] Failed to send SIGKILL to process ${pid}:`, killError) - } - } - } -} - -class StandaloneTerminal { - constructor(options = {}) { - this.name = options.name || `Terminal ${Math.floor(Math.random() * 10000)}` - this.processId = Promise.resolve(Math.floor(Math.random() * 100000)) - this.creationOptions = options - this.exitStatus = undefined - this.state = { isInteractedWith: false } - this._cwd = options.cwd || process.cwd() - this._shellPath = options.shellPath - this._process = null - this._processId = null - - // Mock shell integration for compatibility - this.shellIntegration = { - cwd: { fsPath: this._cwd }, - executeCommand: (_command) => { - // Return a mock execution object that the TerminalProcess expects - return { - read: async function* () { - // This will be handled by our StandaloneTerminalProcess - yield "" - }, - } - }, - } - - console.log(`[StandaloneTerminal] Created terminal: ${this.name} in ${this._cwd}`) - } - - sendText(text, addNewLine = true) { - console.log(`[StandaloneTerminal] sendText: ${text}`) - - // If we have an active process, send input to it - if (this._process && !this._process.killed) { - try { - this._process.stdin.write(text + (addNewLine ? "\n" : "")) - } catch (error) { - console.error(`[StandaloneTerminal] Error sending text to process:`, error) - } - } else { - // For compatibility with old behavior, we could spawn a new process - console.log(`[StandaloneTerminal] No active process to send text to`) - } - } - - show() { - console.log(`[StandaloneTerminal] show: ${this.name}`) - this.state.isInteractedWith = true - } - - hide() { - console.log(`[StandaloneTerminal] hide: ${this.name}`) - } - - dispose() { - console.log(`[StandaloneTerminal] dispose: ${this.name}`) - if (this._process && !this._process.killed) { - this._process.kill("SIGTERM") - } - } -} - -// Terminal registry for tracking terminals -class StandaloneTerminalRegistry { - constructor() { - this.terminals = new Map() - this.nextId = 1 - } - - createTerminal(options = {}) { - const terminal = new StandaloneTerminal(options) - const id = this.nextId++ - - const terminalInfo = { - id: id, - terminal: terminal, - busy: false, - lastCommand: "", - shellPath: options.shellPath, - lastActive: Date.now(), - pendingCwdChange: undefined, - cwdResolved: undefined, - } - - this.terminals.set(id, terminalInfo) - console.log(`[StandaloneTerminalRegistry] Created terminal ${id}`) - return terminalInfo - } - - getTerminal(id) { - return this.terminals.get(id) - } - - getAllTerminals() { - return Array.from(this.terminals.values()) - } - - removeTerminal(id) { - const terminalInfo = this.terminals.get(id) - if (terminalInfo) { - terminalInfo.terminal.dispose() - this.terminals.delete(id) - console.log(`[StandaloneTerminalRegistry] Removed terminal ${id}`) - } - } - - updateTerminal(id, updates) { - const terminalInfo = this.terminals.get(id) - if (terminalInfo) { - Object.assign(terminalInfo, updates) - } - } -} - -// Enhanced terminal manager -class StandaloneTerminalManager { - constructor() { - this.registry = new StandaloneTerminalRegistry() - this.processes = new Map() - this.terminalIds = new Set() - this.shellIntegrationTimeout = 4000 - this.terminalReuseEnabled = true - this.terminalOutputLineLimit = 500 - this.subagentTerminalOutputLineLimit = 2000 - this.defaultTerminalProfile = "default" - } - - runCommand(terminalInfo, command) { - console.log(`[StandaloneTerminalManager] Running command on terminal ${terminalInfo.id}: ${command}`) - - terminalInfo.busy = true - terminalInfo.lastCommand = command - - const process = new StandaloneTerminalProcess() - this.processes.set(terminalInfo.id, process) - - process.once("completed", () => { - terminalInfo.busy = false - console.log(`[StandaloneTerminalManager] Command completed on terminal ${terminalInfo.id}`) - }) - - process.once("error", (error) => { - terminalInfo.busy = false - console.error(`[StandaloneTerminalManager] Command error on terminal ${terminalInfo.id}:`, error) - }) - - // Create promise for the process - const promise = new Promise((resolve, reject) => { - process.once("continue", () => resolve()) - process.once("error", (error) => reject(error)) - }) - - // Run the command immediately (no shell integration wait needed) - process.run(terminalInfo.terminal, command) - - // Return merged promise/process object - return this.mergePromise(process, promise) - } - - async getOrCreateTerminal(cwd) { - const terminals = this.registry.getAllTerminals() - - // Find available terminal with matching CWD - const matchingTerminal = terminals.find((t) => { - if (t.busy) { - return false - } - return t.terminal._cwd === cwd - }) - - if (matchingTerminal) { - this.terminalIds.add(matchingTerminal.id) - console.log(`[StandaloneTerminalManager] Reusing terminal ${matchingTerminal.id}`) - return matchingTerminal - } - - // Find any available terminal if reuse is enabled - if (this.terminalReuseEnabled) { - const availableTerminal = terminals.find((t) => !t.busy) - if (availableTerminal) { - // Change directory - await this.runCommand(availableTerminal, `cd "${cwd}"`) - availableTerminal.terminal._cwd = cwd - availableTerminal.terminal.shellIntegration.cwd.fsPath = cwd - this.terminalIds.add(availableTerminal.id) - console.log(`[StandaloneTerminalManager] Reused terminal ${availableTerminal.id} with cd`) - return availableTerminal - } - } - - // Create new terminal - const newTerminalInfo = this.registry.createTerminal({ - cwd: cwd, - name: `Cline Terminal ${this.registry.nextId}`, - }) - this.terminalIds.add(newTerminalInfo.id) - console.log(`[StandaloneTerminalManager] Created new terminal ${newTerminalInfo.id}`) - return newTerminalInfo - } - - getTerminals(busy) { - return Array.from(this.terminalIds) - .map((id) => this.registry.getTerminal(id)) - .filter((t) => t && t.busy === busy) - .map((t) => ({ id: t.id, lastCommand: t.lastCommand })) - } - - getUnretrievedOutput(terminalId) { - if (!this.terminalIds.has(terminalId)) { - return "" - } - const process = this.processes.get(terminalId) - return process ? process.getUnretrievedOutput() : "" - } - - isProcessHot(terminalId) { - const process = this.processes.get(terminalId) - return process ? process.isHot : false - } - - processOutput(outputLines, overrideLimit, isSubagentCommand) { - const limit = isSubagentCommand && overrideLimit ? overrideLimit : this.terminalOutputLineLimit - if (outputLines.length > limit) { - const halfLimit = Math.floor(limit / 2) - const start = outputLines.slice(0, halfLimit) - const end = outputLines.slice(outputLines.length - halfLimit) - return `${start.join("\n")}\n... (output truncated) ...\n${end.join("\n")}`.trim() - } - return outputLines.join("\n").trim() - } - - disposeAll() { - // Terminate all processes - for (const [_terminalId, process] of this.processes) { - if (process && process.terminate) { - process.terminate() - } - } - - // Clear all tracking - this.terminalIds.clear() - this.processes.clear() - - // Dispose all terminals - for (const terminalInfo of this.registry.getAllTerminals()) { - terminalInfo.terminal.dispose() - } - - console.log(`[StandaloneTerminalManager] Disposed all terminals`) - } - - // Set shell integration timeout (compatibility method) - setShellIntegrationTimeout(timeout) { - this.shellIntegrationTimeout = timeout - console.log(`[StandaloneTerminalManager] Set shell integration timeout to ${timeout}ms`) - } - - // Set terminal reuse enabled (compatibility method) - setTerminalReuseEnabled(enabled) { - this.terminalReuseEnabled = enabled - console.log(`[StandaloneTerminalManager] Set terminal reuse enabled to ${enabled}`) - } - - // Set terminal output line limit (compatibility method) - setTerminalOutputLineLimit(limit) { - this.terminalOutputLineLimit = limit - console.log(`[StandaloneTerminalManager] Set terminal output line limit to ${limit}`) - } - - // Set subagent terminal output line limit (compatibility method) - setSubagentTerminalOutputLineLimit(limit) { - this.subagentTerminalOutputLineLimit = limit - console.log(`[StandaloneTerminalManager] Set subagent terminal output line limit to ${limit}`) - } - - // Set default terminal profile (compatibility method) - setDefaultTerminalProfile(profile) { - this.defaultTerminalProfile = profile - console.log(`[StandaloneTerminalManager] Set default terminal profile to ${profile}`) - } - - // Helper to merge process and promise (similar to execa) - mergePromise(process, promise) { - const nativePromisePrototype = (async () => {})().constructor.prototype - const descriptors = ["then", "catch", "finally"].map((property) => [ - property, - Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property), - ]) - - for (const [property, descriptor] of descriptors) { - if (descriptor) { - const value = descriptor.value.bind(promise) - Reflect.defineProperty(process, property, { ...descriptor, value }) - } - } - - // Ensure terminate() is accessible on the merged promise - // This allows Task.cancelBackgroundCommand() to kill the process - if (process.terminate && typeof process.terminate === "function") { - Object.defineProperty(process, "terminate", { - value: process.terminate.bind(process), - writable: false, - enumerable: false, - configurable: false, - }) - } - - return process - } -} - -module.exports = { - StandaloneTerminal, - StandaloneTerminalProcess, - StandaloneTerminalRegistry, - StandaloneTerminalManager, -} diff --git a/standalone/runtime-files/vscode/vscode-impls.js b/standalone/runtime-files/vscode/vscode-impls.js index e9b61fbd..a8741b1e 100644 --- a/standalone/runtime-files/vscode/vscode-impls.js +++ b/standalone/runtime-files/vscode/vscode-impls.js @@ -1,14 +1,10 @@ console.log("Loading stub impls...") const { createStub } = require("./stub-utils") -const { StandaloneTerminalManager } = require("./enhanced-terminal") // Import the base vscode object from stubs const vscode = require("./vscode-stubs.js") -// Create global terminal manager instance -const globalTerminalManager = new StandaloneTerminalManager() - // Extend the existing window object from stubs rather than overwriting it vscode.window = { ...vscode.window, // Keep existing properties from stubs @@ -41,39 +37,25 @@ vscode.window = { return {} }, createTerminal: (...args) => { - console.log("Enhanced createTerminal:", ...args) + // In standalone mode, terminals are managed directly by Task.terminalManager (StandaloneTerminalManager) + // This stub is provided for compatibility but should not be called directly + console.log("Stubbed createTerminal:", ...args) - // Extract options from arguments - let options = {} - if (args.length > 0) { - if (typeof args[0] === "string") { - // Called with (name, shellPath, shellArgs) - options = { - name: args[0], - shellPath: args[1], - shellArgs: args[2], - } - } else if (typeof args[0] === "object") { - // Called with options object - options = args[0] - } + // Return a minimal stub terminal object + const stubTerminal = { + name: args[0]?.name || args[0] || "Terminal", + processId: Promise.resolve(undefined), + creationOptions: {}, + exitStatus: undefined, + state: { isInteractedWith: false }, + sendText: (text) => console.log("Stubbed terminal.sendText:", text), + show: () => console.log("Stubbed terminal.show"), + hide: () => console.log("Stubbed terminal.hide"), + dispose: () => console.log("Stubbed terminal.dispose"), } - // Use our enhanced terminal manager to create a terminal - const terminalInfo = globalTerminalManager.registry.createTerminal({ - name: options.name || `Terminal ${Date.now()}`, - cwd: options.cwd || process.cwd(), - shellPath: options.shellPath, - }) - - // Store reference for tracking - vscode.window.terminals.push(terminalInfo.terminal) - if (!vscode.window.activeTerminal) { - vscode.window.activeTerminal = terminalInfo.terminal - } - - console.log(`Enhanced terminal created: ${terminalInfo.id}`) - return terminalInfo.terminal + vscode.window.terminals.push(stubTerminal) + return stubTerminal }, activeTextEditor: undefined, visibleTextEditors: [], @@ -173,7 +155,4 @@ vscode.Uri = { }, } -// Export the terminal manager globally for Cline core to use -global.standaloneTerminalManager = globalTerminalManager - console.log("Finished loading stub impls...")