Elffuss BraidHub

kikocis/continue public

main · 7.8 KiBRawPermalink
1/* Terminal emulator - commented because node-pty is causing problems. */
2
3import * as os from "node:os";
4
5import { longestCommonSubsequence } from "core/util/lcs";
6import stripAnsi from "strip-ansi";
7import * as vscode from "vscode";
8
9function loadNativeModule<T>(id: string): T | null {
10 try {
11 return require(`${vscode.env.appRoot}/node_modules.asar/${id}`);
12 } catch (err) {
13 // ignore
14 }
15
16 try {
17 return require(`${vscode.env.appRoot}/node_modules/${id}`);
18 } catch (err) {
19 // ignore
20 }
21
22 return null;
23}
24
25const pty = loadNativeModule<any>("node-pty");
26
27function getDefaultShell(): string {
28 if (process.platform !== "win32") {
29 return os.userInfo().shell || "cmd";
30 }
31 switch (process.platform) {
32 case "win32":
33 return process.env.COMSPEC || "cmd.exe";
34 // case "darwin":
35 // return process.env.SHELL || "/bin/zsh";
36 // default:
37 // return process.env.SHELL || "/bin/sh";
38 }
39}
40
41function getRootDir(): string | undefined {
42 const isWindows = os.platform() === "win32";
43 let cwd = isWindows ? process.env.USERPROFILE : process.env.HOME;
44 if (
45 vscode.workspace.workspaceFolders &&
46 vscode.workspace.workspaceFolders.length > 0
47 ) {
48 cwd = vscode.workspace.workspaceFolders[0].uri.fsPath;
49 }
50 return cwd;
51}
52
53export class CapturedTerminal {
54 private readonly terminal: vscode.Terminal;
55 private readonly shellCmd: string;
56 private readonly ptyProcess: any;
57
58 private shellPrompt: string | undefined = undefined;
59 private dataBuffer = "";
60
61 private onDataListeners: ((data: string) => void)[] = [];
62
63 show() {
64 this.terminal.show();
65 }
66
67 isClosed(): boolean {
68 return this.terminal.exitStatus !== undefined;
69 }
70
71 private commandQueue: [string, (output: string) => void][] = [];
72 private hasRunCommand = false;
73
74 private dataEndsInPrompt(strippedData: string): boolean {
75 const lines = strippedData.split("\n");
76 const lastLine = lines[lines.length - 1];
77
78 return (
79 lines.length > 0 &&
80 (((lastLine.includes("bash-") || lastLine.includes(") $ ")) &&
81 lastLine.includes("$")) ||
82 (lastLine.includes("]> ") && lastLine.includes(") [")) ||
83 (lastLine.includes(" (") && lastLine.includes(")>")) ||
84 (typeof this.commandPromptString !== "undefined" &&
85 (lastLine.includes(this.commandPromptString) ||
86 this.commandPromptString.length -
87 longestCommonSubsequence(lastLine, this.commandPromptString)
88 .length <
89 3)))
90 );
91 }
92
93 private async waitForCommandToFinish() {
94 return new Promise<string>((resolve, reject) => {
95 this.onDataListeners.push((data: any) => {
96 const strippedData = stripAnsi(data);
97 this.dataBuffer += strippedData;
98 if (this.dataEndsInPrompt(strippedData)) {
99 resolve(this.dataBuffer);
100 this.dataBuffer = "";
101 this.onDataListeners = [];
102 }
103 });
104 });
105 }
106
107 async runCommand(command: string): Promise<string> {
108 if (this.commandQueue.length === 0) {
109 return new Promise(async (resolve, reject) => {
110 this.commandQueue.push([command, resolve]);
111
112 while (this.commandQueue.length > 0) {
113 const [command, resolve] = this.commandQueue.shift()!;
114
115 // Refresh the command prompt string every time in case it changes
116 await this.refreshCommandPromptString();
117
118 this.terminal.sendText(command);
119 const output = await this.waitForCommandToFinish();
120 resolve(output);
121 }
122 });
123 } else {
124 return new Promise((resolve, reject) => {
125 this.commandQueue.push([command, resolve]);
126 });
127 }
128 }
129
130 private readonly writeEmitter: vscode.EventEmitter<string>;
131
132 private splitByCommandsBuffer = "";
133
134 splitByCommandsListener(data: string) {
135 // Split the output by commands so it can be sent to Continue Server
136
137 const strippedData = stripAnsi(data);
138 this.splitByCommandsBuffer += data;
139 if (this.dataEndsInPrompt(strippedData)) {
140 if (this.onCommandOutput) {
141 this.onCommandOutput(stripAnsi(this.splitByCommandsBuffer));
142 }
143 this.splitByCommandsBuffer = "";
144 }
145 }
146
147 private runningClearToGetPrompt = false;
148 private seenClear = false;
149 private commandPromptString: string | undefined = undefined;
150 private resolveMeWhenCommandPromptStringFound:
151 | ((_: unknown) => void)
152 | undefined = undefined;
153
154 private async refreshCommandPromptString(): Promise<string | undefined> {
155 // Sends a message that will be received by the terminal to get the command prompt string, see the onData method below in constructor.
156 this.runningClearToGetPrompt = true;
157 this.terminal.sendText("echo");
158 const promise = new Promise((resolve, reject) => {
159 this.resolveMeWhenCommandPromptStringFound = resolve;
160 });
161 await promise;
162 return this.commandPromptString;
163 }
164
165 constructor(
166 options: { name: string } & Partial<vscode.ExtensionTerminalOptions>,
167 private readonly onCommandOutput?: (output: string) => void,
168 ) {
169 // this.shellCmd = "bash"; // getDefaultShell();
170 this.shellCmd = getDefaultShell();
171
172 const env = { ...(process.env as any) };
173 if (os.platform() !== "win32") {
174 env.PATH += `:${["/opt/homebrew/bin", "/opt/homebrew/sbin"].join(":")}`;
175 }
176
177 // Create the pseudo terminal
178 this.ptyProcess = pty.spawn(this.shellCmd, [], {
179 name: "xterm-256color",
180 cols: 250, // No way to get the size of VS Code terminal, or listen to resize, so make it just bigger than most conceivable VS Code widths
181 rows: 26,
182 cwd: getRootDir(),
183 env,
184 useConpty: true,
185 });
186
187 this.writeEmitter = new vscode.EventEmitter<string>();
188
189 this.ptyProcess.onData((data: any) => {
190 if (this.runningClearToGetPrompt) {
191 if (
192 stripAnsi(data)
193 .split("\n")
194 .flatMap((line) => line.split("\r"))
195 .find((line) => line.trim() === "echo") !== undefined
196 ) {
197 this.seenClear = true;
198 return;
199 } else if (this.seenClear) {
200 const strippedLines = stripAnsi(data)
201 .split("\r")
202 .filter(
203 (line) =>
204 line.trim().length > 0 &&
205 line.trim() !== "%" &&
206 line.trim() !== "⏎",
207 );
208 const lastLine = strippedLines[strippedLines.length - 1] || "";
209 const lines = lastLine
210 .split("\n")
211 .filter(
212 (line) =>
213 line.trim().length > 0 &&
214 line.trim() !== "%" &&
215 line.trim() !== "⏎",
216 );
217 const commandPromptString = (lines[lines.length - 1] || "").trim();
218 if (
219 commandPromptString.length > 0 &&
220 !commandPromptString.includes("echo")
221 ) {
222 this.runningClearToGetPrompt = false;
223 this.seenClear = false;
224 this.commandPromptString = commandPromptString;
225 console.log(
226 `Found command prompt string: ${this.commandPromptString}`,
227 );
228 if (this.resolveMeWhenCommandPromptStringFound) {
229 this.resolveMeWhenCommandPromptStringFound(undefined);
230 }
231 }
232 return;
233 }
234 }
235
236 // Pass data through to terminal
237 data = data.replace(/⏎[\s\S]+⏎/g, "").replace(/⏎/g, "");
238 this.writeEmitter.fire(data);
239
240 this.splitByCommandsListener(data);
241 for (const listener of this.onDataListeners) {
242 listener(data);
243 }
244 });
245
246 process.on("exit", () => this.ptyProcess.kill());
247
248 const newPty: vscode.Pseudoterminal = {
249 onDidWrite: this.writeEmitter.event,
250 open: () => {},
251 close: () => {},
252 handleInput: (data) => {
253 this.ptyProcess.write(data);
254 },
255 };
256
257 // Create and clear the terminal
258 this.terminal = vscode.window.createTerminal({
259 ...options,
260 pty: newPty,
261 });
262 this.terminal.show();
263 }
264}