@noldova/terminal 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,6 +10,7 @@ import { ArgumentException } from "@noldova/context.exceptions";
10
10
  import { EndedBy, Resources as ProtocolResources, TerminalAckParams, TerminalCommandAdded, TerminalCommandEnded, TerminalCompleteParams, TerminalCompletion, TerminalExit, TerminalExited, TerminalFindCommandsParams, TerminalInputParams, TerminalLaunched, TerminalLaunchParams, TerminalLinesParams, TerminalName, TerminalNames, TerminalOpenParams, TerminalOwnerReference, TerminalPaneReference, TerminalReference, TerminalResizeParams, TerminalRestartParams, TerminalRestoreParams, TerminalRunBusy, TerminalRunEnded, TerminalRunEndedBy, TerminalRunOutcome, TerminalRunOutputParams, TerminalRunParams, TerminalRunResult, TerminalSessions, TerminalShellKind, TerminalShells, TerminalShowOwnerParams, TerminalSize, TerminalVisibilityParams, WindowsPty } from "@noldova/terminal.protocol";
11
11
  import { AgentTerminalRestartException } from "../exceptions/agent-terminal-restart.exception.js";
12
12
  import { SystemRequirement } from "../enums/system-requirement.js";
13
+ import { ConnectionClosingException } from "../exceptions/connection-closing.exception.js";
13
14
  import { DefaultShellNotFoundException } from "../exceptions/default-shell-not-found.exception.js";
14
15
  import { FolderNotFoundException } from "../exceptions/folder-not-found.exception.js";
15
16
  import { HostEndedException } from "../exceptions/host-ended.exception.js";
@@ -22,6 +23,7 @@ import { HostedTerminal } from "../models/hosted-terminal.js";
22
23
  import { SavedTerminal } from "../models/saved-terminal.js";
23
24
  import { ShellOptionsReply } from "../models/shell-options-reply.js";
24
25
  import { StartedShell } from "../models/started-shell.js";
26
+ import { TerminalOpening } from "../models/terminal-opening.js";
25
27
  import { WaitingRun } from "../models/waiting-run.js";
26
28
  import { Resources } from "../resources.js";
27
29
  import { CommandHistory } from "./command-history.js";
@@ -37,16 +39,18 @@ export class TerminalHost {
37
39
  historyFolder;
38
40
  locator;
39
41
  windowsPty;
40
- environmentSource;
42
+ environment;
41
43
  homeFolder;
42
44
  log;
43
45
  events;
44
46
  saved;
45
47
  completions;
48
+ folderKeys = new WeakMap();
49
+ realFolderReads = new Map();
46
50
  sessions = new Map();
47
51
  commandHistory = new CommandHistory();
48
52
  disposals = new Set();
49
- opens = new Set();
53
+ opens = new Map();
50
54
  launches = new Map();
51
55
  agentSessionOwners = new Map();
52
56
  audience = new TerminalAudience();
@@ -54,7 +58,9 @@ export class TerminalHost {
54
58
  hasEnded = false;
55
59
  restoring = null;
56
60
  appCloses = new Set();
57
- constructor(spawner, fileSystem, integration, historyFolder, locator, platform, osRelease, environmentSource, homeFolder, log, events, saved, completions) {
61
+ closings = new Map();
62
+ closingConnections = new Set();
63
+ constructor(spawner, fileSystem, integration, historyFolder, locator, platform, osRelease, environment, homeFolder, log, events, saved, completions) {
58
64
  this.spawner = spawner;
59
65
  this.fileSystem = fileSystem;
60
66
  this.integration = integration;
@@ -67,7 +73,7 @@ export class TerminalHost {
67
73
  this.windowsPty = platform === Resources.windowsPlatform
68
74
  ? new WindowsPty(TerminalHost.readWindowsBuild(osRelease))
69
75
  : null;
70
- this.environmentSource = environmentSource;
76
+ this.environment = environment;
71
77
  this.homeFolder = homeFolder;
72
78
  this.log = log;
73
79
  this.events = events;
@@ -116,9 +122,11 @@ export class TerminalHost {
116
122
  await this.closeOwnerAsync(TerminalOwnerReference.fromJson(payload).owner, client);
117
123
  return null;
118
124
  case TerminalNames.launchMethod:
119
- return (await this.trackLaunchAsync(this.trackAsync(this.launchAsync(TerminalLaunchParams.fromJson(payload), client)), client)).toJson();
120
- case TerminalNames.runMethod:
121
- return (await this.trackAsync(this.runAsync(TerminalRunParams.fromJson(payload), client))).toJson();
125
+ return (await this.trackLaunchAsync(this.trackAsync(this.launchAsync(TerminalLaunchParams.fromJson(payload), client), new TerminalOpening(null, client.connection)), client)).toJson();
126
+ case TerminalNames.runMethod: {
127
+ const params = TerminalRunParams.fromJson(payload);
128
+ return (await this.runAfterClosesAsync(params, client)).toJson();
129
+ }
122
130
  case TerminalNames.runOutputMethod:
123
131
  return (await this.readRunOutputAsync(TerminalRunOutputParams.fromJson(payload), client))?.toJson() ?? null;
124
132
  case TerminalNames.renameMethod:
@@ -129,8 +137,10 @@ export class TerminalHost {
129
137
  case TerminalNames.findCommandsMethod:
130
138
  return (await this.findCommandsAsync(TerminalFindCommandsParams.fromJson(payload), client)).toJson();
131
139
  case TerminalNames.windowStartedMethod:
132
- if (client.window !== null)
140
+ if (client.window !== null) {
141
+ this.detachLeftPanes(t => t.connection === client.connection && t.window === client.window && t.page !== client.page);
133
142
  await this.endLaunchesWithoutTabAsync(client.connection, client.window, client.page);
143
+ }
134
144
  return null;
135
145
  case TerminalNames.showOwnerMethod: {
136
146
  const shown = TerminalShowOwnerParams.fromJson(payload);
@@ -167,7 +177,7 @@ export class TerminalHost {
167
177
  return this.sessions.get(sessionId);
168
178
  }
169
179
  openTerminalAsync(shellId, folder, size, ownerSessionId, storedLimit = ProtocolResources.defaultStoredLimit, note = null, isPanelTerminal = false, owner = null, client = null, sessionId = randomUUID(), environment = null, startsAtFit = false, opensTab = true) {
170
- return this.trackAsync(this.startTerminalAsync(shellId, folder, size, ownerSessionId, storedLimit, note, isPanelTerminal, owner, client, sessionId, environment, startsAtFit, opensTab));
180
+ return this.trackAsync(this.startTerminalAsync(shellId, folder, size, ownerSessionId, storedLimit, note, isPanelTerminal, owner, client, sessionId, environment, startsAtFit, opensTab), new TerminalOpening(owner, client?.connection ?? null));
171
181
  }
172
182
  bindAgentSession(agentSessionId, owner) {
173
183
  this.agentSessionOwners.set(agentSessionId, owner);
@@ -189,24 +199,33 @@ export class TerminalHost {
189
199
  this.agentSessionOwners.delete(agentSessionId);
190
200
  const isOwned = (terminal) => terminal.owner === owner
191
201
  && (client === null || terminal.isReachedBy(client.connection, client.isApp));
192
- for (const terminal of this.terminals.filter(isOwned))
193
- terminal.cancelCommand();
194
- await Promise.allSettled([this.restoring]);
195
- await Promise.allSettled(this.opens);
196
- this.ensureRunning();
197
- const owned = this.terminals.filter(isOwned);
198
- if (isApp)
199
- this.saved.forgetOwner(owner);
200
- for (const terminal of owned) {
201
- this.sessions.delete(terminal.session.sessionId);
202
- terminal.cancelCommand();
203
- this.endRun(terminal, TerminalRunEndedBy.TerminalEnded, null);
204
- this.audience.publish(this.events.closed, terminal, new TerminalReference(terminal.session.sessionId).toJson());
202
+ const closed = Promise.withResolvers();
203
+ this.closings.set(isOwned, closed);
204
+ try {
205
+ for (const terminal of this.terminals.filter(isOwned))
206
+ terminal.cancelCommand();
207
+ await Promise.allSettled([this.restoring]);
208
+ await this.settleOpensAsync(isOwned);
209
+ this.ensureRunning();
210
+ const owned = this.terminals.filter(isOwned);
211
+ if (isApp)
212
+ this.saved.forgetOwner(owner);
213
+ for (const terminal of owned) {
214
+ this.sessions.delete(terminal.session.sessionId);
215
+ terminal.cancelCommand();
216
+ this.endRun(terminal, TerminalRunEndedBy.TerminalEnded, null);
217
+ this.audience.publish(this.events.closed, terminal, new TerminalReference(terminal.session.sessionId).toJson());
218
+ }
219
+ await Promise.all(owned.map(t => this.endAsync(t.session)));
220
+ }
221
+ finally {
222
+ this.closings.delete(isOwned);
223
+ closed.resolve();
205
224
  }
206
- await Promise.all(owned.map(t => this.endAsync(t.session)));
207
225
  }
208
226
  async closeConnectionAsync(connection, window) {
209
227
  const wasApp = this.audience.forget(connection, window);
228
+ this.detachLeftPanes(t => t.connection === connection && (window === null || t.window === window));
210
229
  this.startUnshownShells();
211
230
  if (window !== null) {
212
231
  await this.endLaunchesWithoutTabAsync(connection, window, null);
@@ -312,27 +331,50 @@ export class TerminalHost {
312
331
  async endConnectionAsync(connection, wasApp) {
313
332
  const isEnding = (terminal) => terminal.connection === null ? wasApp && terminal.owner !== null
314
333
  : terminal.connection === connection;
315
- for (const terminal of this.terminals.filter(isEnding))
316
- terminal.cancelCommand();
317
- await Promise.allSettled([this.restoring]);
318
- await Promise.allSettled(this.opens);
319
- if (this.hasEnded)
320
- return;
321
- const ending = this.terminals.filter(isEnding);
322
- for (const terminal of ending) {
323
- this.sessions.delete(terminal.session.sessionId);
324
- terminal.cancelCommand();
334
+ const closed = Promise.withResolvers();
335
+ this.closings.set(isEnding, closed);
336
+ this.closingConnections.add(connection);
337
+ try {
338
+ for (const terminal of this.terminals.filter(isEnding))
339
+ terminal.cancelCommand();
340
+ await Promise.allSettled([this.restoring]);
341
+ await this.settleOpensAsync(isEnding);
342
+ if (this.hasEnded)
343
+ return;
344
+ const ending = this.terminals.filter(isEnding);
345
+ for (const terminal of ending) {
346
+ this.sessions.delete(terminal.session.sessionId);
347
+ terminal.cancelCommand();
348
+ }
349
+ if (wasApp)
350
+ this.restoring = null;
351
+ await Promise.all(ending.map(t => this.endAsync(t.session)));
325
352
  }
326
- if (wasApp)
327
- this.restoring = null;
328
- await Promise.all(ending.map(t => this.endAsync(t.session)));
353
+ finally {
354
+ this.closings.delete(isEnding);
355
+ this.closingConnections.delete(connection);
356
+ closed.resolve();
357
+ }
358
+ }
359
+ isClosing(terminal) {
360
+ return [...this.closings.keys()].some(isTheirs => isTheirs(terminal));
361
+ }
362
+ endForClose(params, client) {
363
+ const closing = this.findClosing(params, client);
364
+ return closing === undefined ? null : new TerminalRunResult(closing.session.sessionId, TerminalRunOutcome.Ended);
365
+ }
366
+ findClosing(params, client) {
367
+ return this.terminals.findLast(t => t.owner === params.owner && t.isReachedBy(client.connection, client.isApp) && this.isClosing(t));
329
368
  }
330
- trackAsync(opening) {
331
- this.opens.add(opening);
369
+ trackAsync(opening, place) {
370
+ this.opens.set(opening, place);
332
371
  const settled = () => void this.opens.delete(opening);
333
372
  void opening.then(settled, settled);
334
373
  return opening;
335
374
  }
375
+ async settleOpensAsync(isTheirs) {
376
+ await Promise.allSettled([...this.opens].filter(([, t]) => isTheirs(t)).map(([t]) => t));
377
+ }
336
378
  async launchAsync(params, client) {
337
379
  if (params.folder !== null && !this.isAbsolute(params.folder))
338
380
  throw new ArgumentException(ProtocolResources.formatNotAbsolutePath(ProtocolResources.valueSubject), Resources.folderParameter);
@@ -387,7 +429,7 @@ export class TerminalHost {
387
429
  }
388
430
  if (session.hasIntegration && session.commands.isLoaded)
389
431
  await session.changes.waitUntilAsync(() => session.hasExited || isReady(), Resources.shellStartMilliseconds, signal);
390
- const isEnded = () => signal.aborted || session.hasExited || this.sessions.get(session.sessionId) !== terminal;
432
+ const isEnded = () => signal.aborted || session.hasExited || this.sessions.get(session.sessionId) !== terminal || this.isClosing(terminal);
391
433
  const isBracketed = isPaste && !isEnded() && await session.isBracketedPasteAsync();
392
434
  const outcome = isEnded() ? TerminalRunOutcome.Ended
393
435
  : isPaste && ((waitsForFit ? terminal.keyCount !== keyCount : terminal.inputCount !== inputCount) || session.commands.promptEndOffset !== null && session.readPromptLine() !== "") ? TerminalRunOutcome.Input
@@ -425,22 +467,54 @@ export class TerminalHost {
425
467
  const text = command.replace(Resources.trailingLineBreaks, "").replace(Resources.pasteLineBreaks, Resources.enterKey);
426
468
  return isBracketed ? `${Resources.pasteStart}${text}${Resources.pasteEnd}${Resources.enterKey}` : `${text}${Resources.enterKey}`;
427
469
  }
470
+ async runAfterClosesAsync(params, client) {
471
+ const place = new TerminalOpening(params.owner, client.connection);
472
+ for (;;) {
473
+ if (params.sessionId === null && this.isClosing(place)) {
474
+ const closing = this.findClosing(params, client);
475
+ if (closing !== undefined)
476
+ return new TerminalRunResult(closing.session.sessionId, TerminalRunOutcome.Ended);
477
+ if (this.closingConnections.has(client.connection))
478
+ throw new ConnectionClosingException();
479
+ await Promise.allSettled([...this.closings].filter(([isTheirs]) => isTheirs(place)).map(([, closed]) => closed.promise));
480
+ }
481
+ const result = await this.trackAsync(this.runAsync(params, client), place);
482
+ if (result !== null)
483
+ return result;
484
+ }
485
+ }
428
486
  async runAsync(params, client) {
429
487
  await Promise.allSettled([this.restoring]);
430
488
  this.ensureRunning();
431
489
  if (params.sessionId !== null) {
432
490
  const target = this.findRunTarget(params.sessionId, params, client);
433
- return target === null ? new TerminalRunResult(params.sessionId, TerminalRunOutcome.Ended) : this.runIntoAsync(params, target, client);
491
+ return target === null || this.isClosing(target) ? new TerminalRunResult(params.sessionId, TerminalRunOutcome.Ended)
492
+ : this.runIntoAsync(params, target, client);
493
+ }
494
+ const place = new TerminalOpening(params.owner, client.connection);
495
+ if (this.isClosing(place))
496
+ return this.endForClose(params, client);
497
+ const isOwned = (t) => t.owner === params.owner && t.isReachedBy(client.connection, client.isApp)
498
+ && (params.shellKinds.length === 0 || params.shellKinds.includes(t.shell.kind)) && !t.isRunStarting;
499
+ const wanted = params.folder === null ? null : await this.toRunFolderKeyAsync(params.folder);
500
+ let inFolder = await this.findInFolderAsync(wanted, isOwned);
501
+ const newest = this.terminals.findLast(t => isOwned(t) && inFolder?.has(t) !== false && (t.isFree || t.isDrawingPrompt));
502
+ if (newest !== undefined && !newest.isFree) {
503
+ await this.waitForPromptAsync(newest);
504
+ inFolder = await this.findInFolderAsync(wanted, isOwned);
434
505
  }
435
- let terminal = this.terminals.findLast(t => t.owner === params.owner && t.isReachedBy(client.connection, client.isApp)
436
- && (params.shellKinds.length === 0 || params.shellKinds.includes(t.shell.kind)) && t.isFree && !t.isRunStarting);
506
+ let terminal = this.terminals.findLast(t => isOwned(t) && inFolder?.has(t) !== false && t.isFree);
437
507
  const isNew = terminal === undefined;
438
508
  if (terminal === undefined) {
439
509
  const shell = params.shellKinds.length === 0 ? await this.findFallbackShellAsync(params.shellId)
440
510
  : await this.findShellOfKindsAsync(params.shellKinds, params.shellId);
441
511
  if (shell === undefined && params.shellKinds.length > 0)
442
512
  return new TerminalRunResult(null, TerminalRunOutcome.NoShell);
513
+ if (this.isClosing(place))
514
+ return this.endForClose(params, client);
443
515
  terminal = await this.startForPersonAsync(new TerminalOpenParams(shell?.id ?? null, params.folder, params.size, params.storedLimit, false, params.owner), client, true, params.opensTab);
516
+ if (this.isClosing(terminal))
517
+ return new TerminalRunResult(terminal.session.sessionId, TerminalRunOutcome.Ended);
444
518
  if (!params.opensTab)
445
519
  terminal.fitWindow = client;
446
520
  this.audience.publish(this.events.opened, terminal, terminal.session.toSummary(terminal.folder, false, false, params.owner, terminal.opensTab, terminal.name, terminal.shell.name).toJson());
@@ -450,6 +524,17 @@ export class TerminalHost {
450
524
  this.events.runOpened.publishTo(client.connection, client.window, new TerminalReference(terminal.session.sessionId).toJson());
451
525
  return this.typeRunAsync(terminal, params.command, client, isNew);
452
526
  }
527
+ async waitForPromptAsync(terminal) {
528
+ const wasStarting = terminal.isRunStarting;
529
+ terminal.isRunStarting = true;
530
+ try {
531
+ await terminal.session.changes.waitUntilAsync(() => !terminal.isDrawingPrompt, Resources.promptDrawWaitMilliseconds, terminal.beginInterrupt());
532
+ }
533
+ finally {
534
+ terminal.endInterrupt();
535
+ terminal.isRunStarting = wasStarting;
536
+ }
537
+ }
453
538
  findRunTarget(sessionId, params, client) {
454
539
  const terminal = this.sessions.get(sessionId);
455
540
  return terminal === undefined || !terminal.isReachedBy(client.connection, client.isApp) || terminal.ownerSessionId !== null
@@ -461,7 +546,13 @@ export class TerminalHost {
461
546
  return new TerminalRunResult(session.sessionId, TerminalRunOutcome.Busy);
462
547
  terminal.isRunStarting = true;
463
548
  try {
464
- const isBusy = () => !terminal.isFree && !session.hasExited && this.sessions.get(session.sessionId) === terminal;
549
+ const isBusy = () => !terminal.isFree && !session.hasExited && this.sessions.get(session.sessionId) === terminal
550
+ && !this.isClosing(terminal);
551
+ if (isBusy() && terminal.isDrawingPrompt) {
552
+ await this.waitForPromptAsync(terminal);
553
+ if (this.sessions.get(session.sessionId) !== terminal)
554
+ return new TerminalRunResult(session.sessionId, TerminalRunOutcome.Ended);
555
+ }
465
556
  if (isBusy() && params.whenBusy === TerminalRunBusy.Interrupt && terminal.pendingCommand === null) {
466
557
  const isStarted = () => isBusy() && session.commands.runningCommand !== null;
467
558
  const signal = terminal.beginInterrupt();
@@ -489,13 +580,14 @@ export class TerminalHost {
489
580
  }
490
581
  static async waitForCommandAsync(session, isStarted, deadline, signal) {
491
582
  for (;;) {
492
- const group = await session.readForegroundProcessGroupAsync();
583
+ const foreground = await session.readForegroundProcessAsync();
493
584
  if (!isStarted() || signal.aborted)
494
585
  return false;
495
- if (group !== session.pid)
586
+ const isCommand = foreground === null || foreground.group !== session.pid;
587
+ if (isCommand && (foreground === null || !foreground.isTerminalProgram))
496
588
  return true;
497
589
  if (Date.now() >= deadline)
498
- return false;
590
+ return isCommand;
499
591
  await session.changes.waitUntilAsync(() => !isStarted(), Math.min(Resources.foregroundPollMilliseconds, deadline - Date.now()), signal);
500
592
  }
501
593
  }
@@ -565,7 +657,7 @@ export class TerminalHost {
565
657
  return fallback !== undefined && kinds.includes(fallback.kind) ? fallback : await this.locator.findKindAsync(kinds);
566
658
  }
567
659
  openAsync(params, client) {
568
- return this.trackAsync(this.openRequestedAsync(params, client));
660
+ return this.trackAsync(this.openRequestedAsync(params, client), new TerminalOpening(params.owner, client.connection));
569
661
  }
570
662
  async openRequestedAsync(params, client) {
571
663
  if (!params.isPanelTerminal)
@@ -669,6 +761,72 @@ export class TerminalHost {
669
761
  isAbsolute(folder) {
670
762
  return this.windowsPty === null ? folder.startsWith(Resources.posixRoot) : Resources.windowsAbsolutePath.test(folder);
671
763
  }
764
+ async findInFolderAsync(wanted, isOwned) {
765
+ if (wanted === null)
766
+ return null;
767
+ const matched = [];
768
+ await Promise.all(this.terminals.filter(isOwned).map(async (t) => {
769
+ const known = await this.toTerminalFolderKeyAsync(t);
770
+ if (known !== null && known[1] === wanted)
771
+ matched.push([t, known[0]]);
772
+ }));
773
+ return new Set(matched.filter(([t, folder]) => folder === this.currentFolderOf(t)).map(([t]) => t));
774
+ }
775
+ async toRunFolderKeyAsync(folder) {
776
+ const real = await this.readRealFolderAsync(folder);
777
+ if (real !== null || await this.readBoundedAsync(() => this.fileSystem.isFolderAsync(folder)) !== false)
778
+ return this.toFolderKey(real ?? folder);
779
+ return this.toFolderKey(await this.readRealFolderAsync(this.homeFolder) ?? this.homeFolder);
780
+ }
781
+ async toTerminalFolderKeyAsync(terminal) {
782
+ const folder = this.currentFolderOf(terminal);
783
+ if (folder === null)
784
+ return null;
785
+ const known = this.folderKeys.get(terminal);
786
+ if (known !== undefined && known[0] === folder)
787
+ return known;
788
+ const reading = this.joinRealFolderRead(folder);
789
+ void reading.then(real => {
790
+ if (this.currentFolderOf(terminal) === folder)
791
+ this.folderKeys.set(terminal, [folder, this.toFolderKey(real ?? folder)]);
792
+ }, () => undefined);
793
+ const real = await this.readBoundedAsync(() => reading);
794
+ return [folder, this.toFolderKey(real ?? folder)];
795
+ }
796
+ currentFolderOf(terminal) {
797
+ const cwd = terminal.session.cwd;
798
+ if (cwd === null)
799
+ return terminal.folder;
800
+ const local = this.completions.toLocalFolder(cwd, terminal.shell.kind, this.readCompletionEnvironment(terminal));
801
+ if (local === null)
802
+ return null;
803
+ return this.isAbsolute(local) ? local : terminal.folder;
804
+ }
805
+ readRealFolderAsync(folder) {
806
+ return this.readBoundedAsync(() => this.joinRealFolderRead(folder));
807
+ }
808
+ joinRealFolderRead(folder) {
809
+ const running = this.realFolderReads.get(folder);
810
+ if (running !== undefined)
811
+ return running;
812
+ const reading = this.fileSystem.readRealPathOrNullAsync(folder).finally(() => this.realFolderReads.delete(folder));
813
+ this.realFolderReads.set(folder, reading);
814
+ return reading;
815
+ }
816
+ async readBoundedAsync(read) {
817
+ const late = Promise.withResolvers();
818
+ const timer = setTimeout(() => late.resolve(undefined), Resources.runFolderReadMilliseconds);
819
+ try {
820
+ return await Promise.race([read().catch(() => undefined), late.promise]);
821
+ }
822
+ finally {
823
+ clearTimeout(timer);
824
+ }
825
+ }
826
+ toFolderKey(folder) {
827
+ const trimmed = folder.replace(Resources.trailingFolderSeparators, "");
828
+ return this.windowsPty === null ? trimmed : trimmed.replaceAll(Resources.posixRoot, Resources.windowsSeparator).toLowerCase();
829
+ }
672
830
  async closeAsync(sessionId, client) {
673
831
  this.find(sessionId, client);
674
832
  await this.closeTerminalAsync(sessionId);
@@ -684,7 +842,7 @@ export class TerminalHost {
684
842
  const keys = params.asksShell && this.completions.followsCommand(terminal.shell.kind, params.line, params.cursor)
685
843
  ? Resources.optionsKeys.get(terminal.shell.kind) : undefined;
686
844
  const [completion, reply] = await Promise.all([
687
- this.readCompletionEnvironmentAsync(terminal).then(t => this.completions.completeAsync(params.sessionId, terminal.shell.kind, params.line, params.cursor, terminal.session.cwd ?? terminal.folder, t, terminal.session.shellNames, terminal.session.shellBuiltins)),
845
+ this.completions.completeAsync(params.sessionId, terminal.shell.kind, params.line, params.cursor, terminal.session.cwd ?? terminal.folder, this.readCompletionEnvironment(terminal), terminal.session.shellNames, terminal.session.shellBuiltins),
688
846
  keys === undefined ? Promise.resolve(ShellOptionsReply.none) : terminal.session.askOptionsAsync(keys)
689
847
  ]);
690
848
  if (reply.isTimedOut)
@@ -696,12 +854,12 @@ export class TerminalHost {
696
854
  const terminal = this.findHosted(params.sessionId, client);
697
855
  const shellNames = terminal.session.isShellPathReset || terminal.session.isShellModulePathReset ? null
698
856
  : terminal.session.shellNames;
699
- const environment = await this.readCompletionEnvironmentAsync(terminal);
857
+ const environment = this.readCompletionEnvironment(terminal);
700
858
  return terminal.shell.kind === TerminalShellKind.PowerShell
701
859
  ? this.completions.findMissingPowerShellAsync(terminal.session.commands, terminal.shell.file, params.names, shellNames, environment)
702
860
  : this.completions.findMissingAsync(params.sessionId, terminal.session.commands, terminal.session.prompts, terminal.shell.kind, terminal.session.cwd ?? terminal.folder, params.names, shellNames, environment);
703
861
  }
704
- async readCompletionEnvironmentAsync(terminal) {
862
+ readCompletionEnvironment(terminal) {
705
863
  const replaced = {};
706
864
  if (terminal.session.shellPath !== null)
707
865
  replaced[Resources.pathVariable] = terminal.session.shellPath;
@@ -711,7 +869,7 @@ export class TerminalHost {
711
869
  if (temporaryFolder !== null)
712
870
  replaced[Resources.temporaryFolderVariable] = temporaryFolder;
713
871
  const keys = new Set(Object.keys(replaced).map(t => this.toVariableKey(t)));
714
- return this.readShellEnvironmentAsync({
872
+ return this.withVariables(TerminalHost.toTerminalEnvironment(this.environment.read()), {
715
873
  ...Object.fromEntries(Object.entries(terminal.environment ?? {}).filter(([t]) => !keys.has(this.toVariableKey(t)))),
716
874
  ...replaced
717
875
  });
@@ -785,9 +943,14 @@ export class TerminalHost {
785
943
  if (terminal.shell.id === shellId && terminal.ownerSessionId === null)
786
944
  this.audience.publish(this.events.commandAdded, terminal, new TerminalCommandAdded(terminal.session.sessionId, command).toJson());
787
945
  }
788
- attachAsync(reference, client) {
946
+ async attachAsync(reference, client) {
789
947
  const terminal = this.findHosted(reference.sessionId, client);
790
- return terminal.session.attachAsync(reference.paneId, terminal.ownerSessionId === null && this.isSuggesting() ? this.commandHistory.list(terminal.shell.id) : []);
948
+ terminal.paneClients.set(reference.paneId, client);
949
+ const attachment = await terminal.session.attachAsync(reference.paneId, terminal.ownerSessionId === null && this.isSuggesting()
950
+ ? this.commandHistory.list(terminal.shell.id) : []);
951
+ if (!terminal.paneClients.has(reference.paneId))
952
+ terminal.session.detach(reference.paneId);
953
+ return attachment;
791
954
  }
792
955
  isSuggesting() {
793
956
  return this.integration.isSuggesting();
@@ -815,10 +978,22 @@ export class TerminalHost {
815
978
  }
816
979
  detach(reference, client) {
817
980
  const terminal = this.reachable(reference.sessionId, client);
981
+ terminal?.paneClients.delete(reference.paneId);
818
982
  terminal?.session.detach(reference.paneId);
819
983
  if (terminal !== null && !terminal.isSized)
820
984
  this.startShell(terminal);
821
985
  }
986
+ detachLeftPanes(isLeft) {
987
+ for (const terminal of this.terminals) {
988
+ const left = [...terminal.paneClients].filter(([, t]) => isLeft(t)).map(([t]) => t);
989
+ for (const paneId of left) {
990
+ terminal.paneClients.delete(paneId);
991
+ terminal.session.detach(paneId);
992
+ }
993
+ if (left.length > 0 && !terminal.isSized)
994
+ this.startShell(terminal);
995
+ }
996
+ }
822
997
  startUnshownShells() {
823
998
  for (const terminal of this.terminals)
824
999
  this.startIfUnshown(terminal);
@@ -877,7 +1052,7 @@ export class TerminalHost {
877
1052
  return process;
878
1053
  }
879
1054
  async startShellAsync(shell, folder, size, note, variables, deferredSessionId = null) {
880
- const environment = await this.readShellEnvironmentAsync(variables);
1055
+ const environment = this.withVariables(await this.readEnvironmentAsync(), variables);
881
1056
  const printedNote = note === null || this.windowsPty === null ? null
882
1057
  : note.split(Resources.lineBreaks).map(t => TerminalSession.toNote(t)).join("");
883
1058
  const launch = await this.integration.prepareAsync(shell, randomUUID().replaceAll(Resources.terminalHostUuidSeparator, ""), environment, printedNote);
@@ -909,15 +1084,15 @@ export class TerminalHost {
909
1084
  const temporaryKey = this.toVariableKey(Resources.temporaryFolderVariable);
910
1085
  return new StartedShell(process, launch.nonce, launch.printsNote, deferred, Object.entries(environment).find(([t]) => this.toVariableKey(t) === temporaryKey)?.[1] ?? null);
911
1086
  }
912
- async readShellEnvironmentAsync(variables) {
1087
+ withVariables(environment, variables) {
913
1088
  const names = new Set(Object.keys(variables).map(t => this.toVariableKey(t)));
914
1089
  return Object.fromEntries([
915
- ...Object.entries(await this.readEnvironmentAsync()).filter(([t]) => !names.has(this.toVariableKey(t))),
1090
+ ...Object.entries(environment).filter(([t]) => !names.has(this.toVariableKey(t))),
916
1091
  ...Object.entries(variables)
917
1092
  ]);
918
1093
  }
919
1094
  async readEnvironmentAsync() {
920
- const environment = await this.environmentSource.readAsync();
1095
+ const environment = await this.environment.readAsync();
921
1096
  this.ensureRunning();
922
1097
  return TerminalHost.toTerminalEnvironment(environment);
923
1098
  }
@@ -41,6 +41,7 @@ export class TerminalSession {
41
41
  receivedOffset = 0;
42
42
  reportedCwd = null;
43
43
  typedLines = new Set();
44
+ restartOffsets = [];
44
45
  options = new ShellOptionsQueue();
45
46
  isPromptNew = false;
46
47
  hasAnsweredOptions = false;
@@ -87,8 +88,8 @@ export class TerminalSession {
87
88
  get pid() {
88
89
  return this.terminal.pid;
89
90
  }
90
- readForegroundProcessGroupAsync() {
91
- return this.terminal.readForegroundProcessGroupAsync();
91
+ readForegroundProcessAsync() {
92
+ return this.terminal.readForegroundProcessAsync();
92
93
  }
93
94
  get title() {
94
95
  return this.mirror.title;
@@ -120,6 +121,12 @@ export class TerminalSession {
120
121
  get prompts() {
121
122
  return this.commands.prompts;
122
123
  }
124
+ get run() {
125
+ return this.restartOffsets.length;
126
+ }
127
+ endOfRun(run) {
128
+ return this.restartOffsets[run] ?? null;
129
+ }
123
130
  get hasExited() {
124
131
  return this.exit !== null;
125
132
  }
@@ -212,6 +219,7 @@ export class TerminalSession {
212
219
  return this.terminal.endAsync();
213
220
  }
214
221
  restart(process, nonce, size) {
222
+ this.restartOffsets.push(this.text.endOffset);
215
223
  this.wakeup?.stop();
216
224
  this.terminal = this.startTerminal(process);
217
225
  if (this.flow.isPaused)
@@ -76,7 +76,7 @@ export class WindowsEnvironment {
76
76
  }
77
77
  catch (error) {
78
78
  this.log.write(Resources.formatEnvironmentUnread(FailureText.read(error)));
79
- return this.environment;
79
+ return null;
80
80
  }
81
81
  }
82
82
  async prepareFolderAsync() {
@@ -14,13 +14,15 @@ export class TerminalOutputReport {
14
14
  type: Resources.jsonObjectType,
15
15
  additionalProperties: false,
16
16
  required: [
17
- Resources.terminalIdField, Resources.titleField, Resources.terminalOutputReportMethodField, Resources.terminalOutputReportStatusField,
17
+ Resources.terminalIdField, Resources.titleField, Resources.nameField, Resources.shellNameField, Resources.terminalOutputReportMethodField, Resources.terminalOutputReportStatusField,
18
18
  Resources.terminalOutputReportExitCodeField, Resources.cwdField, Resources.terminalOutputReportOutputField,
19
19
  Resources.terminalOutputReportOmittedCharactersField, Resources.terminalOutputReportLogFileField, Resources.terminalOutputReportIsAwaitingSecretField
20
20
  ],
21
21
  properties: {
22
22
  [Resources.terminalIdField]: { type: Resources.jsonStringType },
23
23
  [Resources.titleField]: { type: Resources.jsonStringType },
24
+ [Resources.nameField]: { type: [Resources.jsonStringType, Resources.jsonNullType], description: Resources.nameFieldDescription },
25
+ [Resources.shellNameField]: { type: Resources.jsonStringType, description: Resources.shellNameFieldDescription },
24
26
  [Resources.terminalOutputReportMethodField]: { type: [Resources.jsonStringType, Resources.jsonNullType], enum: [...Object.values(RunMethod), null], description: Resources.methodFieldDescription },
25
27
  [Resources.terminalOutputReportStatusField]: { type: [Resources.jsonStringType, Resources.jsonNullType], enum: [...Object.values(CommandStatus), null], description: Resources.statusFieldDescription },
26
28
  [Resources.terminalOutputReportExitCodeField]: { type: [Resources.jsonIntegerType, Resources.jsonNullType] },
@@ -48,6 +50,8 @@ export class TerminalOutputReport {
48
50
  return ToolResults.create(this.excerpt.text + Resources.formatCommandSummary(status, exitCode, this.cwd, isAwaitingSecret) + note, {
49
51
  [Resources.terminalIdField]: this.access.terminal.id,
50
52
  [Resources.titleField]: this.access.terminal.title,
53
+ [Resources.nameField]: this.access.terminal.name,
54
+ [Resources.shellNameField]: this.access.terminal.shellName,
51
55
  [Resources.terminalOutputReportMethodField]: this.command === null ? null : this.command.method,
52
56
  [Resources.terminalOutputReportStatusField]: status,
53
57
  [Resources.terminalOutputReportExitCodeField]: exitCode,
@@ -26,11 +26,13 @@ export class TerminalListTool extends TerminalTool {
26
26
  items: {
27
27
  type: Resources.jsonObjectType,
28
28
  additionalProperties: false,
29
- required: [Resources.terminalIdField, Resources.titleField, Resources.shellField, Resources.cwdField, Resources.terminalListToolIsSharedField,
30
- Resources.terminalListToolIsRunningField],
29
+ required: [Resources.terminalIdField, Resources.titleField, Resources.nameField, Resources.shellNameField, Resources.shellField, Resources.cwdField,
30
+ Resources.terminalListToolIsSharedField, Resources.terminalListToolIsRunningField],
31
31
  properties: {
32
32
  [Resources.terminalIdField]: { type: Resources.jsonStringType },
33
33
  [Resources.titleField]: { type: Resources.jsonStringType },
34
+ [Resources.nameField]: { type: [Resources.jsonStringType, Resources.jsonNullType], description: Resources.nameFieldDescription },
35
+ [Resources.shellNameField]: { type: Resources.jsonStringType, description: Resources.shellNameFieldDescription },
34
36
  [Resources.shellField]: { type: Resources.jsonStringType },
35
37
  [Resources.cwdField]: { type: [Resources.jsonStringType, Resources.jsonNullType], description: Resources.cwdFieldDescription },
36
38
  [Resources.terminalListToolIsSharedField]: { type: Resources.jsonBooleanType, description: Resources.sharedFieldDescription },
@@ -59,6 +61,8 @@ export class TerminalListTool extends TerminalTool {
59
61
  const terminals = accesses.map(t => ({
60
62
  [Resources.terminalIdField]: t.terminal.id,
61
63
  [Resources.titleField]: t.terminal.title,
64
+ [Resources.nameField]: t.terminal.name,
65
+ [Resources.shellNameField]: t.terminal.shellName,
62
66
  [Resources.shellField]: t.terminal.shellId,
63
67
  [Resources.cwdField]: t.terminal.readPrompt().cwd,
64
68
  [Resources.terminalListToolIsSharedField]: t.isShared,
@@ -25,10 +25,12 @@ export class TerminalOpenTool extends TerminalTool {
25
25
  outputSchema: {
26
26
  type: Resources.jsonObjectType,
27
27
  additionalProperties: false,
28
- required: [Resources.terminalIdField, Resources.titleField, Resources.shellField, Resources.cwdField, Resources.terminalOpenToolHasShellIntegrationField],
28
+ required: [Resources.terminalIdField, Resources.titleField, Resources.nameField, Resources.shellNameField, Resources.shellField, Resources.cwdField, Resources.terminalOpenToolHasShellIntegrationField],
29
29
  properties: {
30
30
  [Resources.terminalIdField]: { type: Resources.jsonStringType },
31
31
  [Resources.titleField]: { type: Resources.jsonStringType },
32
+ [Resources.nameField]: { type: [Resources.jsonStringType, Resources.jsonNullType], description: Resources.nameFieldDescription },
33
+ [Resources.shellNameField]: { type: Resources.jsonStringType, description: Resources.shellNameFieldDescription },
32
34
  [Resources.shellField]: { type: Resources.jsonStringType },
33
35
  [Resources.cwdField]: { type: Resources.jsonStringType },
34
36
  [Resources.terminalOpenToolHasShellIntegrationField]: { type: Resources.jsonBooleanType, description: Resources.integrationFieldDescription }
@@ -56,6 +58,8 @@ export class TerminalOpenTool extends TerminalTool {
56
58
  return ToolResults.create(Resources.formatTerminalOpened(terminal.id, terminal.shellId, context.workingFolder), {
57
59
  [Resources.terminalIdField]: terminal.id,
58
60
  [Resources.titleField]: terminal.title,
61
+ [Resources.nameField]: terminal.name,
62
+ [Resources.shellNameField]: terminal.shellName,
59
63
  [Resources.shellField]: terminal.shellId,
60
64
  [Resources.cwdField]: context.workingFolder,
61
65
  [Resources.terminalOpenToolHasShellIntegrationField]: terminal.hasShellIntegration