-
Notifications
You must be signed in to change notification settings - Fork 39.3k
Expand file tree
/
Copy pathagentHostTerminalManager.ts
More file actions
717 lines (640 loc) · 22.7 KB
/
agentHostTerminalManager.ts
File metadata and controls
717 lines (640 loc) · 22.7 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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import { DeferredPromise, raceCancellablePromises, timeout } from '../../../base/common/async.js';
import { Emitter } from '../../../base/common/event.js';
import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../base/common/lifecycle.js';
import { dirname } from '../../../base/common/path.js';
import * as platform from '../../../base/common/platform.js';
import { URI } from '../../../base/common/uri.js';
import { generateUuid } from '../../../base/common/uuid.js';
import { createDecorator } from '../../instantiation/common/instantiation.js';
import { ILogService } from '../../log/common/log.js';
import { IProductService } from '../../product/common/productService.js';
import { getShellIntegrationInjection } from '../../terminal/node/terminalEnvironment.js';
import { ActionType } from '../common/state/protocol/actions.js';
import type { ICreateTerminalParams } from '../common/state/protocol/commands.js';
import { ITerminalClaim, ITerminalContentPart, ITerminalInfo, ITerminalState, TerminalClaimKind } from '../common/state/protocol/state.js';
import { isTerminalAction } from '../common/state/sessionActions.js';
import type { AgentHostStateManager } from './agentHostStateManager.js';
import { Osc633Event, Osc633EventType, Osc633Parser } from './osc633Parser.js';
const WAIT_FOR_PROMPT_TIMEOUT = 10_000;
export const IAgentHostTerminalManager = createDecorator<IAgentHostTerminalManager>('agentHostTerminalManager');
export interface ICommandFinishedEvent {
commandId: string;
exitCode: number | undefined;
command: string;
output: string;
}
/**
* Service interface for terminal management in the agent host.
*/
export interface IAgentHostTerminalManager {
readonly _serviceBrand: undefined;
createTerminal(params: ICreateTerminalParams, options?: { shell?: string; preventShellHistory?: boolean; nonInteractive?: boolean }): Promise<void>;
writeInput(uri: string, data: string): void;
onData(uri: string, cb: (data: string) => void): IDisposable;
onExit(uri: string, cb: (exitCode: number) => void): IDisposable;
onClaimChanged(uri: string, cb: (claim: ITerminalClaim) => void): IDisposable;
onCommandFinished(uri: string, cb: (event: ICommandFinishedEvent) => void): IDisposable;
getContent(uri: string): string | undefined;
getClaim(uri: string): ITerminalClaim | undefined;
hasTerminal(uri: string): boolean;
getExitCode(uri: string): number | undefined;
supportsCommandDetection(uri: string): boolean;
disposeTerminal(uri: string): void;
getTerminalInfos(): ITerminalInfo[];
getTerminalState(uri: string): ITerminalState | undefined;
}
// node-pty is loaded dynamically to avoid bundling issues in non-node environments
let nodePtyModule: typeof import('node-pty') | undefined;
async function getNodePty(): Promise<typeof import('node-pty')> {
if (!nodePtyModule) {
nodePtyModule = await import('node-pty');
}
return nodePtyModule;
}
/** Per-terminal command detection tracking state. */
interface ICommandTracker {
readonly parser: Osc633Parser;
readonly nonce: string;
commandCounter: number;
detectionAvailableEmitted: boolean;
pendingCommandLine?: string;
activeCommandId?: string;
activeCommandTimestamp?: number;
}
/** Represents a single managed terminal with its PTY process. */
interface IManagedTerminal {
readonly uri: string;
readonly store: DisposableStore;
readonly pty: import('node-pty').IPty;
readonly onDataEmitter: Emitter<string>;
readonly onExitEmitter: Emitter<number>;
readonly onClaimChangedEmitter: Emitter<ITerminalClaim>;
readonly onCommandFinishedEmitter: Emitter<ICommandFinishedEvent>;
title: string;
cwd: string;
cols: number;
rows: number;
content: ITerminalContentPart[];
contentSize: number;
claim: ITerminalClaim;
exitCode?: number;
commandTracker?: ICommandTracker;
}
/**
* Manages terminal processes for the agent host. Each terminal is backed by
* a node-pty instance and identified by a protocol URI.
*
* Listens to the {@link AgentHostStateManager} for client-dispatched terminal
* actions (input, resize, claim changes) and dispatches server-originated
* PTY output back through the state manager.
*/
export class AgentHostTerminalManager extends Disposable implements IAgentHostTerminalManager {
declare readonly _serviceBrand: undefined;
private readonly _terminals = new Map<string, IManagedTerminal>();
constructor(
private readonly _stateManager: AgentHostStateManager,
@ILogService private readonly _logService: ILogService,
@IProductService private readonly _productService: IProductService,
) {
super();
// React to client-dispatched terminal actions flowing through the state manager
this._register(this._stateManager.onDidEmitEnvelope(envelope => {
const action = envelope.action;
if (!isTerminalAction(action)) {
return;
}
switch (action.type) {
case ActionType.TerminalInput:
this._writeInput(action.terminal, action.data);
break;
case ActionType.TerminalResized:
this._resize(action.terminal, action.cols, action.rows);
break;
case ActionType.TerminalClaimed:
this._setClaim(action.terminal, action.claim);
break;
case ActionType.TerminalTitleChanged:
this._setTitle(action.terminal, action.title);
break;
case ActionType.TerminalCleared:
this._clearContent(action.terminal);
break;
}
}));
}
/** Get metadata for all active terminals (for root state). */
getTerminalInfos(): ITerminalInfo[] {
return [...this._terminals.values()].map(t => ({
resource: t.uri,
title: t.title,
claim: t.claim,
exitCode: t.exitCode,
}));
}
/** Get the full state for a terminal (for subscribe snapshots). */
getTerminalState(uri: string): ITerminalState | undefined {
const terminal = this._terminals.get(uri);
if (!terminal) {
return undefined;
}
return {
title: terminal.title,
cwd: terminal.cwd,
cols: terminal.cols,
rows: terminal.rows,
content: terminal.content,
exitCode: terminal.exitCode,
claim: terminal.claim,
supportsCommandDetection: terminal.commandTracker?.detectionAvailableEmitted,
};
}
/**
* Create a new terminal backed by node-pty.
* Spawns the user's default shell.
*/
async createTerminal(params: ICreateTerminalParams, options?: { shell?: string; preventShellHistory?: boolean; nonInteractive?: boolean }): Promise<void> {
const uri = params.terminal;
if (this._terminals.has(uri)) {
throw new Error(`Terminal already exists: ${uri}`);
}
const nodePty = await getNodePty();
const cwd = await this._resolveCwd(params.cwd, uri);
const cols = params.cols ?? 80;
const rows = params.rows ?? 24;
const shell = options?.shell ?? this._getDefaultShell();
const name = platform.isWindows ? 'cmd' : 'xterm-256color';
this._logService.info(`[TerminalManager] Creating terminal ${uri}: shell=${shell}, cwd=${cwd}, cols=${cols}, rows=${rows}`);
// Shell integration — inject scripts so the shell emits OSC 633 sequences
const nonce = generateUuid();
const env: Record<string, string> = { ...process.env as Record<string, string> };
if (options?.preventShellHistory) {
// Picked up by the shell integration scripts to set HISTCONTROL=ignorespace
// (bash) / HIST_IGNORE_SPACE (zsh), or suppress PSReadLine history (pwsh).
// Combined with the leading-space prefix applied at command-write time, this
// prevents agent-executed commands from polluting the user's shell history.
env['VSCODE_PREVENT_SHELL_HISTORY'] = '1';
}
if (options?.nonInteractive) {
// Suppress paging and interactive prompts so that tool-spawned
// terminals produce clean, machine-friendly output. An empty
// string disables paging in git, less, and most CLI tools and
// is safe on all platforms (unlike 'cat' which isn't on Windows PATH).
env['LC_ALL'] = 'C.UTF-8';
env['PAGER'] = '';
env['GIT_PAGER'] = '';
env['GH_PAGER'] = '';
env['GIT_TERMINAL_PROMPT'] = '0';
env['DEBIAN_FRONTEND'] = 'noninteractive';
}
let shellArgs: string[] = [];
const injection = await getShellIntegrationInjection(
{ executable: shell, args: [], forceShellIntegration: true },
{
shellIntegration: { enabled: true, suggestEnabled: false, nonce },
windowsUseConptyDll: false,
environmentVariableCollections: undefined,
workspaceFolder: undefined,
isScreenReaderOptimized: false,
},
undefined,
this._logService,
this._productService,
);
let commandTracker: ICommandTracker | undefined;
if (injection.type === 'injection') {
this._logService.info(`[TerminalManager] Shell integration injected for ${uri}`);
if (injection.envMixin) {
for (const [key, value] of Object.entries(injection.envMixin)) {
if (value !== undefined) {
env[key] = value;
}
}
}
if (injection.newArgs) {
shellArgs = injection.newArgs;
}
if (injection.filesToCopy) {
for (const f of injection.filesToCopy) {
try {
await fs.promises.mkdir(dirname(f.dest), { recursive: true });
await fs.promises.copyFile(f.source, f.dest);
} catch {
// Swallow — another process may be using the same temp dir
}
}
}
commandTracker = {
parser: new Osc633Parser(),
nonce,
commandCounter: 0,
detectionAvailableEmitted: false,
};
} else {
this._logService.info(`[TerminalManager] Shell integration not available for ${uri}: ${injection.reason}`);
}
const ptyProcess = nodePty.spawn(shell, shellArgs, {
name,
cwd,
env,
cols,
rows,
});
const store = new DisposableStore();
const claim: ITerminalClaim = params.claim ?? { kind: TerminalClaimKind.Client, clientId: '' };
const onDataEmitter = store.add(new Emitter<string>());
const onExitEmitter = store.add(new Emitter<number>());
const onClaimChangedEmitter = store.add(new Emitter<ITerminalClaim>());
const onCommandFinishedEmitter = store.add(new Emitter<ICommandFinishedEvent>());
const managed: IManagedTerminal = {
uri,
store,
pty: ptyProcess,
onDataEmitter,
onExitEmitter,
onClaimChangedEmitter,
onCommandFinishedEmitter,
title: params.name ?? shell,
cwd,
cols,
rows,
content: [],
contentSize: 0,
claim,
commandTracker,
};
this._terminals.set(uri, managed);
// Wire PTY events → protocol events
store.add(toDisposable(() => {
try { ptyProcess.kill(); } catch { /* already dead */ }
}));
const onFirstData = new DeferredPromise<void>();
const dataListener = ptyProcess.onData(rawData => {
this._handlePtyData(managed, rawData);
onFirstData.complete();
});
store.add(toDisposable(() => dataListener.dispose()));
const exitListener = ptyProcess.onExit(e => {
managed.exitCode = e.exitCode;
managed.onExitEmitter.fire(e.exitCode);
onFirstData.complete();
this._stateManager.dispatchServerAction({
type: ActionType.TerminalExited,
terminal: uri,
exitCode: e.exitCode,
});
this._broadcastTerminalList();
});
store.add(toDisposable(() => exitListener.dispose()));
// Poll for title changes (non-Windows)
if (!platform.isWindows) {
const titleInterval = setInterval(() => {
const newTitle = ptyProcess.process;
if (newTitle && newTitle !== managed.title) {
managed.title = newTitle;
this._stateManager.dispatchServerAction({
type: ActionType.TerminalTitleChanged,
terminal: uri,
title: newTitle,
});
this._broadcastTerminalList();
}
}, 200);
store.add(toDisposable(() => clearInterval(titleInterval)));
}
await raceCancellablePromises([onFirstData.p, timeout(WAIT_FOR_PROMPT_TIMEOUT)]);
this._broadcastTerminalList();
}
/** Send input data to a terminal's PTY process (from client-dispatched actions). */
private _writeInput(uri: string, data: string): void {
this.writeInput(uri, data);
}
/** Send input data to a terminal's PTY process. */
writeInput(uri: string, data: string): void {
const terminal = this._terminals.get(uri);
if (terminal && terminal.exitCode === undefined) {
terminal.pty.write(data);
}
}
/** Register a callback for PTY data events on a terminal. */
onData(uri: string, cb: (data: string) => void): IDisposable {
const terminal = this._terminals.get(uri);
if (!terminal) {
return toDisposable(() => { });
}
return terminal.onDataEmitter.event(cb);
}
/** Register a callback for PTY exit events on a terminal. */
onExit(uri: string, cb: (exitCode: number) => void): IDisposable {
const terminal = this._terminals.get(uri);
if (!terminal) {
return toDisposable(() => { });
}
return terminal.onExitEmitter.event(cb);
}
/** Register a callback for terminal claim changes. */
onClaimChanged(uri: string, cb: (claim: ITerminalClaim) => void): IDisposable {
const terminal = this._terminals.get(uri);
if (!terminal) {
return toDisposable(() => { });
}
return terminal.onClaimChangedEmitter.event(cb);
}
/** Register a callback for command completion events (requires shell integration). */
onCommandFinished(uri: string, cb: (event: ICommandFinishedEvent) => void): IDisposable {
const terminal = this._terminals.get(uri);
if (!terminal) {
return toDisposable(() => { });
}
return terminal.onCommandFinishedEmitter.event(cb);
}
/** Get accumulated scrollback content for a terminal as raw text. */
getContent(uri: string): string | undefined {
const terminal = this._terminals.get(uri);
if (!terminal) {
return undefined;
}
return terminal.content.map(p => p.type === 'command' ? p.output : p.value).join('');
}
/** Get the current claim for a terminal. */
getClaim(uri: string): ITerminalClaim | undefined {
return this._terminals.get(uri)?.claim;
}
/** Check whether a terminal exists. */
hasTerminal(uri: string): boolean {
return this._terminals.has(uri);
}
/** Whether the terminal has shell integration active for command detection. */
supportsCommandDetection(uri: string): boolean {
const terminal = this._terminals.get(uri);
return terminal?.commandTracker?.detectionAvailableEmitted ?? false;
}
/** Get the exit code for a terminal, or undefined if still running. */
getExitCode(uri: string): number | undefined {
return this._terminals.get(uri)?.exitCode;
}
/** Resize a terminal. */
private _resize(uri: string, cols: number, rows: number): void {
const terminal = this._terminals.get(uri);
if (terminal && terminal.exitCode === undefined) {
terminal.cols = cols;
terminal.rows = rows;
terminal.pty.resize(cols, rows);
}
}
/** Update a terminal's claim. */
private _setClaim(uri: string, claim: ITerminalClaim): void {
const terminal = this._terminals.get(uri);
if (terminal) {
terminal.claim = claim;
terminal.onClaimChangedEmitter.fire(claim);
this._broadcastTerminalList();
}
}
/** Update a terminal's title. */
private _setTitle(uri: string, title: string): void {
const terminal = this._terminals.get(uri);
if (terminal) {
terminal.title = title;
this._broadcastTerminalList();
}
}
/** Clear a terminal's scrollback buffer. */
private _clearContent(uri: string): void {
const terminal = this._terminals.get(uri);
if (terminal) {
terminal.content = [];
terminal.contentSize = 0;
}
}
/** Process raw PTY output: parse OSC 633 sequences, dispatch actions, track content. */
private _handlePtyData(managed: IManagedTerminal, rawData: string): void {
const tracker = managed.commandTracker;
let cleanedData: string;
if (tracker) {
const parseResult = tracker.parser.parse(rawData);
cleanedData = parseResult.cleanedData;
for (const event of parseResult.events) {
this._handleOsc633Event(managed, tracker, event);
}
} else {
cleanedData = rawData;
}
// Append to structured content
if (cleanedData.length > 0) {
this._appendToContent(managed, cleanedData);
}
// Trim content if too large
this._trimContent(managed);
// Fire data event and dispatch to protocol (cleaned, without OSC 633)
if (cleanedData.length > 0) {
managed.onDataEmitter.fire(cleanedData);
this._stateManager.dispatchServerAction({
type: ActionType.TerminalData,
terminal: managed.uri,
data: cleanedData,
});
}
}
/** Handle a parsed OSC 633 event by dispatching the appropriate protocol actions. */
private _handleOsc633Event(managed: IManagedTerminal, tracker: ICommandTracker, event: Osc633Event): void {
// Emit TerminalCommandDetectionAvailable on first sequence
if (!tracker.detectionAvailableEmitted) {
tracker.detectionAvailableEmitted = true;
this._stateManager.dispatchServerAction({
type: ActionType.TerminalCommandDetectionAvailable,
terminal: managed.uri,
});
}
switch (event.type) {
case Osc633EventType.CommandLine: {
// Only trust command lines with a valid nonce
if (event.nonce === tracker.nonce) {
tracker.pendingCommandLine = event.commandLine;
}
break;
}
case Osc633EventType.CommandExecuted: {
const commandId = `cmd-${++tracker.commandCounter}`;
const commandLine = tracker.pendingCommandLine ?? '';
const timestamp = Date.now();
tracker.pendingCommandLine = undefined;
tracker.activeCommandId = commandId;
tracker.activeCommandTimestamp = timestamp;
// Push a new command content part
managed.content.push({
type: 'command',
commandId,
commandLine,
output: '',
timestamp,
isComplete: false,
});
this._stateManager.dispatchServerAction({
type: ActionType.TerminalCommandExecuted,
terminal: managed.uri,
commandId,
commandLine,
timestamp,
});
break;
}
case Osc633EventType.CommandFinished: {
const finishedCommandId = tracker.activeCommandId;
if (!finishedCommandId) {
break;
}
const durationMs = tracker.activeCommandTimestamp !== undefined
? Date.now() - tracker.activeCommandTimestamp
: undefined;
// Mark the command content part as complete and collect output
let commandLine = '';
let commandOutput = '';
for (const part of managed.content) {
if (part.type === 'command' && part.commandId === finishedCommandId) {
part.isComplete = true;
part.exitCode = event.exitCode;
part.durationMs = durationMs;
commandLine = part.commandLine;
commandOutput = part.output;
break;
}
}
tracker.activeCommandId = undefined;
tracker.activeCommandTimestamp = undefined;
managed.onCommandFinishedEmitter.fire({
commandId: finishedCommandId,
exitCode: event.exitCode,
command: commandLine,
output: commandOutput,
});
this._stateManager.dispatchServerAction({
type: ActionType.TerminalCommandFinished,
terminal: managed.uri,
commandId: finishedCommandId,
exitCode: event.exitCode,
durationMs,
});
break;
}
case Osc633EventType.Property: {
if (event.key === 'Cwd') {
managed.cwd = event.value;
this._stateManager.dispatchServerAction({
type: ActionType.TerminalCwdChanged,
terminal: managed.uri,
cwd: event.value,
});
}
break;
}
}
}
/** Append cleaned data to the terminal's structured content array. */
private _appendToContent(managed: IManagedTerminal, data: string): void {
const tail = managed.content.length > 0 ? managed.content[managed.content.length - 1] : undefined;
if (tail && tail.type === 'command' && !tail.isComplete) {
// Active command — append to its output
tail.output += data;
managed.contentSize += data.length;
} else if (tail && tail.type === 'unclassified') {
// Extend the existing unclassified part
tail.value += data;
managed.contentSize += data.length;
} else {
// Start a new unclassified part
managed.content.push({ type: 'unclassified', value: data });
managed.contentSize += data.length;
}
}
private _getContentPartSize(part: ITerminalContentPart): number {
return part.type === 'command' ? part.output.length : part.value.length;
}
/** Trim content parts to stay within the rolling buffer limit. */
private _trimContent(managed: IManagedTerminal): void {
const maxSize = 100_000;
const targetSize = 80_000;
if (managed.contentSize <= maxSize) {
return;
}
// Drop whole parts from the front while possible
while (managed.contentSize > targetSize && managed.content.length > 1) {
const removed = managed.content.shift()!;
managed.contentSize -= this._getContentPartSize(removed);
}
// If the single remaining (or first) part is still over budget, trim its text
if (managed.contentSize > targetSize && managed.content.length > 0) {
const head = managed.content[0];
const excess = managed.contentSize - targetSize;
if (head.type === 'command') {
head.output = head.output.slice(excess);
} else {
head.value = head.value.slice(excess);
}
managed.contentSize -= excess;
}
}
/** Dispose a terminal: kill the process and remove it. */
disposeTerminal(uri: string): void {
const terminal = this._terminals.get(uri);
if (terminal) {
this._terminals.delete(uri);
terminal.store.dispose();
this._broadcastTerminalList();
}
}
private _getDefaultShell(): string {
if (platform.isWindows) {
return process.env['COMSPEC'] || 'cmd.exe';
}
return process.env['SHELL'] || '/bin/sh';
}
/**
* Resolves the cwd string from {@link ICreateTerminalParams} to an
* accessible filesystem path, falling back to $HOME if the requested
* directory is missing (otherwise node-pty exits silently with code 1).
* Accepts either a `file://` URI string or a raw absolute filesystem path.
*/
private async _resolveCwd(cwd: string | undefined, terminalURI: string): Promise<string> {
let resolved = cwd;
if (cwd) {
const parsed = URI.parse(cwd);
if (parsed.scheme === 'file' && parsed.fsPath && parsed.fsPath !== '/') {
resolved = parsed.fsPath;
} else {
this._logService.warn(`[TerminalManager] Ignoring non-file cwd for ${terminalURI}: ${cwd}`);
}
}
try {
if (resolved) {
const stat = await fs.promises.stat(resolved);
if (stat.isDirectory()) {
return resolved;
}
}
} catch {
// fall through to fallback
}
const fallback = process.env['HOME'] || process.env['USERPROFILE'] || process.cwd();
this._logService.warn(`[TerminalManager] cwd '${resolved}' is not accessible, falling back to ${fallback}`);
return fallback;
}
/** Dispatch root/terminalsChanged with the current terminal list. */
private _broadcastTerminalList(): void {
this._stateManager.dispatchServerAction({
type: ActionType.RootTerminalsChanged,
terminals: this.getTerminalInfos(),
});
}
override dispose(): void {
for (const terminal of this._terminals.values()) {
terminal.store.dispose();
}
this._terminals.clear();
super.dispose();
}
}