Repository navigation
Expand file tree
/
Copy pathTerminalRegistry.ts
More file actions
427 lines (362 loc) · 13.4 KB
/
Copy pathTerminalRegistry.ts
File metadata and controls
427 lines (362 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import * as vscode from "vscode"
import { arePathsEqual } from "../../utils/path"
import { RooTerminal, RooTerminalProvider } from "./types"
import { TerminalProcess } from "./TerminalProcess"
import { Terminal } from "./Terminal"
import { ExecaTerminal } from "./ExecaTerminal"
import { ShellIntegrationManager } from "./ShellIntegrationManager"
// Although vscode.window.terminals provides a list of all open terminals,
// there's no way to know whether they're busy or not (exitStatus does not
// provide useful information for most commands). In order to prevent creating
// too many terminals, we need to keep track of terminals through the life of
// the extension, as well as session specific terminals for the life of a task
// (to get latest unretrieved output).
// Since we have promises keeping track of terminal processes, we get the added
// benefit of keep track of busy terminals even after a task is closed.
export class TerminalRegistry {
private static terminals: RooTerminal[] = []
private static nextTerminalId = 1
private static disposables: vscode.Disposable[] = []
private static isInitialized = false
public static initialize() {
if (this.isInitialized) {
throw new Error("TerminalRegistry.initialize() should only be called once")
}
this.isInitialized = true
// TODO: This initialization code is VSCode specific, and therefore
// should probably live elsewhere.
// Register handler for terminal close events to clean up temporary
// directories.
const closeDisposable = vscode.window.onDidCloseTerminal((vsceTerminal) => {
const terminal = this.getTerminalByVSCETerminal(vsceTerminal)
if (terminal) {
ShellIntegrationManager.zshCleanupTmpDir(terminal.id)
}
})
this.disposables.push(closeDisposable)
try {
const startDisposable = vscode.window.onDidStartTerminalShellExecution?.(
async (e: vscode.TerminalShellExecutionStartEvent) => {
const terminal = this.getTerminalByVSCETerminal(e.terminal)
console.info("[onDidStartTerminalShellExecution]", {
command: e.execution?.commandLine?.value,
terminalId: terminal?.id,
})
if (terminal instanceof Terminal) {
// Always call read() from this event — it fires when VSCode's shell
// integration confirms the command has actually started, which is the
// earliest point at which read() will reliably capture output. Calling
// read() earlier (e.g. immediately after executeCommand()) creates a
// stream window that misses data on cold terminals where the shell
// hasn't started yet: VSCode doesn't buffer retroactively.
//
// Guard: only set the stream for the execution we own. Stale start
// events for a previous execution on the same reused terminal must
// not overwrite the current command's stream.
const process = terminal.process
const isOwnExecution =
!(process instanceof TerminalProcess) ||
// Allow undefined only when the process hasn't started yet (cold
// terminal: process is assigned but run() hasn't called executeCommand).
// Once isHot is true, ownExecution is always set — a stale start
// event on a reused terminal must match exactly.
(!process.isHot && process.ownExecution === undefined) ||
process.ownExecution === e.execution
if (!isOwnExecution) {
console.info(
"[TerminalRegistry] Ignoring onDidStartTerminalShellExecution for a different execution",
{ terminalId: terminal.id },
)
return
}
const stream = e.execution.read()
terminal.setActiveStream(stream)
// Only mark busy when there is a live process to clear it later.
// If the end event already fired (early-completion race), process is
// undefined and setActiveStream returned early — setting busy here would
// leave the terminal stuck busy with nothing to clear it.
if (terminal.process) {
terminal.busy = true
}
} else {
console.error(
"[onDidStartTerminalShellExecution] Shell execution started, but not from a Roo-registered terminal:",
e,
)
}
},
)
if (startDisposable) {
this.disposables.push(startDisposable)
}
const endDisposable = vscode.window.onDidEndTerminalShellExecution?.(
async (e: vscode.TerminalShellExecutionEndEvent) => {
const terminal = this.getTerminalByVSCETerminal(e.terminal)
const process = terminal?.process
const exitDetails = TerminalProcess.interpretExitCode(e.exitCode)
console.info("[onDidEndTerminalShellExecution]", {
command: e.execution?.commandLine?.value,
terminalId: terminal?.id,
...exitDetails,
})
if (!terminal) {
console.error(
"[onDidEndTerminalShellExecution] Shell execution ended, but not from a Roo-registered terminal:",
e,
)
return
}
if (terminal instanceof Terminal && terminal.activeShellExecution === e.execution) {
terminal.activeShellExecution = undefined
}
// Guard against a late end event for an execution that has already been
// superseded on this terminal. This can happen when a process self-finalizes
// after TerminalProcess's own D-marker grace period elapses without ever
// seeing this event (see TerminalProcess.ts's finalize()): the terminal gets
// reused for a new command before VSCode's stale event for the OLD command
// finally arrives. Without this check, that stale event would call
// shellExecutionComplete() on whatever process/exit-code tracking is
// currently attached -- the NEW command's -- corrupting its state instead of
// being a harmless no-op for the command it actually belongs to.
const isStaleExecution =
process instanceof TerminalProcess &&
process.ownExecution !== undefined &&
process.ownExecution !== e.execution
if (isStaleExecution) {
console.info(
"[TerminalRegistry] Ignoring stale onDidEndTerminalShellExecution for a superseded execution",
{ terminalId: terminal.id, exitCode: e.exitCode },
)
return
}
if (!terminal.running) {
// The end event can arrive before setActiveStream() has set
// running=true (race between the global VS Code event and the
// synchronous call in TerminalProcess.run). If a process is
// waiting for completion, deliver the signal so it doesn't
// hang forever. See #489 / #622.
if (process) {
console.info(
"[TerminalRegistry] End event arrived before running=true (race); delivering completion signal",
{ terminalId: terminal.id, exitCode: e.exitCode },
)
terminal.shellExecutionComplete(exitDetails)
} else {
terminal.busy = false
}
return
}
if (!process) {
console.error(
"[TerminalRegistry] Shell execution end event received on running terminal, but process is undefined:",
{ terminalId: terminal.id, exitCode: e.exitCode },
)
return
}
// Signal completion to any waiting processes.
terminal.shellExecutionComplete(exitDetails)
},
)
if (endDisposable) {
this.disposables.push(endDisposable)
}
} catch (error) {
console.error("[TerminalRegistry] Error setting up shell execution handlers:", error)
}
}
public static createTerminal(cwd: string, provider: RooTerminalProvider): RooTerminal {
let newTerminal
if (provider === "vscode") {
newTerminal = new Terminal(this.nextTerminalId++, undefined, cwd)
} else {
newTerminal = new ExecaTerminal(this.nextTerminalId++, cwd)
}
this.terminals.push(newTerminal)
return newTerminal
}
/**
* Gets an existing terminal or creates a new one for the given working
* directory.
*
* @param cwd The working directory path
* @param taskId Optional task ID to associate with the terminal
* @returns A Terminal instance
*/
public static async getOrCreateTerminal(
cwd: string,
taskId?: string,
provider: RooTerminalProvider = "vscode",
): Promise<RooTerminal> {
const terminals = this.getAllTerminals()
const reuseKey = provider === "vscode" ? Terminal.getReuseKey() : provider
let terminal: RooTerminal | undefined
// First priority: Find a terminal already assigned to this task with
// matching directory.
if (taskId) {
terminal = terminals.find((t) => {
if (t.busy || t.taskId !== taskId || t.provider !== provider || t.reuseKey !== reuseKey) {
return false
}
const terminalCwd = t.getCurrentWorkingDirectory()
if (!terminalCwd) {
return false
}
return arePathsEqual(vscode.Uri.file(cwd).fsPath, terminalCwd)
})
}
// Second priority: Find any available terminal with matching directory.
if (!terminal) {
terminal = terminals.find((t) => {
if (t.busy || t.provider !== provider || t.reuseKey !== reuseKey) {
return false
}
const terminalCwd = t.getCurrentWorkingDirectory()
if (!terminalCwd) {
return false
}
return arePathsEqual(vscode.Uri.file(cwd).fsPath, terminalCwd)
})
}
// If no suitable terminal found, create a new one.
if (!terminal) {
terminal = this.createTerminal(cwd, provider)
}
terminal.taskId = taskId
return terminal
}
/**
* Gets unretrieved output from a terminal process.
*
* @param id The terminal ID
* @returns The unretrieved output as a string, or empty string if terminal not found
*/
public static getUnretrievedOutput(id: number): string {
return this.getTerminalById(id)?.getUnretrievedOutput() ?? ""
}
/**
* Checks if a terminal process is "hot" (recently active).
*
* @param id The terminal ID
* @returns True if the process is hot, false otherwise
*/
public static isProcessHot(id: number): boolean {
return this.getTerminalById(id)?.process?.isHot ?? false
}
/**
* Gets terminals filtered by busy state and optionally by task id.
*
* @param busy Whether to get busy or non-busy terminals
* @param taskId Optional task ID to filter terminals by
* @returns Array of Terminal objects
*/
public static getTerminals(busy: boolean, taskId?: string): RooTerminal[] {
return this.getAllTerminals().filter((t) => {
// Filter by busy state.
if (t.busy !== busy) {
return false
}
// If taskId is provided, also filter by taskId.
if (taskId !== undefined && t.taskId !== taskId) {
return false
}
return true
})
}
/**
* Gets background terminals (taskId undefined) that have unretrieved output
* or are still running.
*
* @param busy Whether to get busy or non-busy terminals
* @returns Array of Terminal objects
*/
public static getBackgroundTerminals(busy?: boolean): RooTerminal[] {
return this.getAllTerminals().filter((t) => {
// Only get background terminals (taskId undefined).
if (t.taskId !== undefined) {
return false
}
// If busy is undefined, return all background terminals.
if (busy === undefined) {
return t.getProcessesWithOutput().length > 0 || t.process?.hasUnretrievedOutput()
}
// Filter by busy state.
return t.busy === busy
})
}
public static cleanup() {
// Clean up all temporary directories.
ShellIntegrationManager.clear()
this.disposables.forEach((disposable) => disposable.dispose())
this.disposables = []
}
/**
* Disposes all idle (non-busy) VS Code terminals so they are not reused
* after a shell profile change. Busy terminals are left untouched.
*/
public static closeIdleTerminals(): void {
this.terminals = this.terminals.filter((t) => {
if (t.busy || !(t instanceof Terminal)) {
return true
}
t.terminal.dispose()
ShellIntegrationManager.zshCleanupTmpDir(t.id)
return false
})
}
/**
* Releases all terminals associated with a task.
*
* @param taskId The task ID
*/
public static releaseTerminalsForTask(taskId: string): void {
this.terminals.forEach((terminal) => {
if (terminal.taskId === taskId) {
// #245: If the terminal is still executing a command when its task is torn
// down (user pressed cancel ✕, or the task was switched/removed), abort the
// process. Otherwise the command keeps running orphaned and the terminal stays
// stuck "busy" — the cancel-doesn't-terminate bug. abort() is safe when idle
// (Ctrl+C is gated on an active stream; Execa abort is idempotent).
if (terminal.busy) {
try {
terminal.process?.abort()
} catch (error) {
console.error(
`[TerminalRegistry] Error aborting process for terminal ${terminal.id} on release:`,
error,
)
}
}
terminal.taskId = undefined
}
})
}
private static getAllTerminals(): RooTerminal[] {
this.terminals = this.terminals.filter((t) => !t.isClosed())
return this.terminals
}
private static getTerminalById(id: number): RooTerminal | undefined {
const terminal = this.terminals.find((t) => t.id === id)
if (terminal?.isClosed()) {
this.removeTerminal(id)
return undefined
}
return terminal
}
/**
* Gets a terminal by its VSCode terminal instance
* @param terminal The VSCode terminal instance
* @returns The Terminal object, or undefined if not found
*/
private static getTerminalByVSCETerminal(vsceTerminal: vscode.Terminal): RooTerminal | undefined {
const found = this.terminals.find((t) => t instanceof Terminal && t.terminal === vsceTerminal)
if (found?.isClosed()) {
this.removeTerminal(found.id)
return undefined
}
return found
}
private static removeTerminal(id: number) {
ShellIntegrationManager.zshCleanupTmpDir(id)
this.terminals = this.terminals.filter((t) => t.id !== id)
}
}