@noldova/terminal 0.0.4 → 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.
package/module.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "id": "terminal",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "displayName": "Terminal",
5
5
  "description": "Runs shells in terminal panes, and lets AI agents run commands in them through permission requests.",
6
6
  "parts": ["runtime", "window"],
7
7
  "pseudoTerminals": true,
8
8
  "dependencies": {},
9
- "noldovaDesktop": ">=0.0.7 <0.1.0",
9
+ "noldovaDesktop": ">=0.0.11 <0.1.0",
10
10
  "contributes": {
11
11
  "methods": [
12
12
  "terminal.shells", "terminal.open", "terminal.close", "terminal.restart", "terminal.sessions", "terminal.attach", "terminal.input", "terminal.resize",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noldova/terminal",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "The terminal module for apps on Noldova Desktop: terminal panes over real shells, and agent tools that run commands through permission requests.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -36,17 +36,17 @@
36
36
  "registry": "https://registry.npmjs.org/"
37
37
  },
38
38
  "dependencies": {
39
- "@noldova/terminal.protocol": "0.0.4",
40
- "@noldova/terminal.window": "0.0.4",
39
+ "@noldova/terminal.protocol": "0.0.5",
40
+ "@noldova/terminal.window": "0.0.5",
41
41
  "@xterm/addon-serialize": "0.14.0",
42
42
  "@xterm/headless": "6.0.0",
43
43
  "node-pty": "1.2.0-beta.15"
44
44
  },
45
45
  "peerDependencies": {
46
- "@noldova/desktop.protocol": ">=0.0.7 <0.1.0",
47
- "@noldova/desktop.runtime": ">=0.0.7 <0.1.0",
48
- "@noldova/context.exceptions": ">=0.0.7 <0.1.0",
46
+ "@noldova/desktop.protocol": ">=0.0.11 <0.1.0",
47
+ "@noldova/desktop.runtime": ">=0.0.11 <0.1.0",
48
+ "@noldova/context.exceptions": ">=0.0.10 <0.1.0",
49
49
  "@noldova/context.json": ">=0.0.7 <0.1.0"
50
50
  },
51
- "gitHead": "d196e4e1493d3350d9dab89f1873e78de561448f"
51
+ "gitHead": "82ac135f2ac5abd327cf7fbf6b8556d4d129df47"
52
52
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { Resources } from "../resources.js";
9
+ import { TerminalException } from "./terminal.exception.js";
10
+ export class ConnectionClosingException extends TerminalException {
11
+ constructor() {
12
+ super(Resources.connectionClosing);
13
+ }
14
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { Resources } from "../resources.js";
9
+ import { TerminalException } from "./terminal.exception.js";
10
+ export class ReadDroppedException extends TerminalException {
11
+ constructor() {
12
+ super(Resources.readDropped);
13
+ }
14
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export {};
@@ -6,7 +6,9 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  import { Resources } from "../resources.js";
9
+ import { TerminalOpening } from "./terminal-opening.js";
9
10
  export class HostedTerminal {
11
+ opening;
10
12
  pendingInterrupt = null;
11
13
  session;
12
14
  shell;
@@ -35,6 +37,7 @@ export class HostedTerminal {
35
37
  pendingCommand = null;
36
38
  launchCommandOffset = null;
37
39
  runs = new Map();
40
+ paneClients = new Map();
38
41
  name = null;
39
42
  isRunStarting = false;
40
43
  waitingRun = null;
@@ -49,6 +52,7 @@ export class HostedTerminal {
49
52
  this.owner = owner;
50
53
  this.connection = connection;
51
54
  this.environment = environment;
55
+ this.opening = new TerminalOpening(owner, connection);
52
56
  }
53
57
  get hasRecentInput() {
54
58
  return Date.now() - this.inputTime < Resources.echoSettleMilliseconds;
@@ -63,6 +67,10 @@ export class HostedTerminal {
63
67
  return this.ownerSessionId === null && !this.session.hasExited && !this.isRestarting && this.pendingCommand === null
64
68
  && this.session.commands.hasMarks && !this.hasUnreadInput && this.session.readPromptLine() === "";
65
69
  }
70
+ get isDrawingPrompt() {
71
+ return this.ownerSessionId === null && !this.session.hasExited && !this.isRestarting && this.pendingCommand === null
72
+ && this.session.commands.isDrawingPrompt;
73
+ }
66
74
  recordInput(isReply = false, data = "") {
67
75
  this.inputReceivedLength = this.session.receivedLength;
68
76
  if (isReply)
@@ -98,7 +106,7 @@ export class HostedTerminal {
98
106
  this.pendingInterrupt = null;
99
107
  }
100
108
  isReachedBy(connection, isApp) {
101
- return this.connection === null ? this.owner !== null && isApp : this.connection === connection;
109
+ return this.opening.isReachedBy(connection, isApp);
102
110
  }
103
111
  record(prompt) {
104
112
  this.inputCount++;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { ReadDroppedException } from "../exceptions/read-dropped.exception.js";
9
+ import { Resources } from "../resources.js";
10
+ export class SharedRead {
11
+ promise;
12
+ answer = Promise.withResolvers();
13
+ read;
14
+ interest = 0;
15
+ hasStarted = false;
16
+ constructor(read) {
17
+ this.read = read;
18
+ this.promise = this.answer.promise;
19
+ }
20
+ watch(signal, onDropped) {
21
+ this.interest++;
22
+ signal.addEventListener(Resources.abortEvent, () => {
23
+ if (this.hasStarted || --this.interest > 0)
24
+ return;
25
+ this.answer.reject(new ReadDroppedException());
26
+ onDropped();
27
+ }, { once: true });
28
+ }
29
+ startAsync() {
30
+ this.hasStarted = true;
31
+ return this.read().then(this.answer.resolve, this.answer.reject);
32
+ }
33
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export class TerminalOpening {
9
+ owner;
10
+ connection;
11
+ constructor(owner, connection) {
12
+ this.owner = owner;
13
+ this.connection = connection;
14
+ }
15
+ isReachedBy(connection, isApp) {
16
+ return this.connection === null ? this.owner !== null && isApp : this.connection === connection;
17
+ }
18
+ }
package/src/resources.js CHANGED
@@ -20,6 +20,7 @@ export class Resources {
20
20
  static promptSettleMilliseconds = 500;
21
21
  static echoSettleMilliseconds = 1_000;
22
22
  static runInterruptWaitMilliseconds = 2_000;
23
+ static promptDrawWaitMilliseconds = 10_000;
23
24
  static foregroundPollMilliseconds = 50;
24
25
  static cursorAnswerMilliseconds = 500;
25
26
  static maximumKeptRuns = 100;
@@ -91,13 +92,14 @@ export class Resources {
91
92
  static cursorHome = "\u001b[H";
92
93
  static windowsAbsolutePath = /^(?:[A-Za-z]:[\\/]|\\\\)/u;
93
94
  static posixRoot = "/";
95
+ static trailingFolderSeparators = /[\\/]+$/u;
94
96
  static folderParameter = "folder";
95
97
  static noteStyle = "\u001b[2;3m";
96
98
  static styleReset = "\u001b[0m";
97
99
  static noteLineBreak = "\r\n";
98
100
  static lineBreaks = /\r\n|\r|\n/u;
99
101
  static escapesOnly = /^(?:\u001b\[[0-9;?]*[A-Za-z])*(?:\u001b(?:\[[0-9;?]*)?)?$/u;
100
- static resizeStall = /^(?:\u001b\[[0-9;?]*[A-Za-z])*\u001b\[6n\u001b\[\d+;\d+H$/u;
102
+ static resizeStall = /^(?:\u001b\[[0-9;?]*[A-Za-z])*\u001b\[6n(?:\u001b(?:\[[0-9;]*H?)?)?$/u;
101
103
  static cursorRequest = "\u001b[6n";
102
104
  static cursorAnswers = /\u001b\[\d+;\d+R/gu;
103
105
  static whiteSpace = /\s+/gu;
@@ -293,6 +295,8 @@ export class Resources {
293
295
  static packageFile = "package.json";
294
296
  static completionCommandMilliseconds = 2_000;
295
297
  static completionReadMilliseconds = 1_000;
298
+ static runFolderReadMilliseconds = 1_000;
299
+ static completionConcurrentReads = 2;
296
300
  static optionsKeys = new Map([
297
301
  [TerminalShellKind.PowerShell, "\u001b[24~o"],
298
302
  [TerminalShellKind.Zsh, "\u001b[24;7~"]
@@ -382,6 +386,7 @@ export class Resources {
382
386
  static vswhereInstallationPathField = "installationPath";
383
387
  static shellListMilliseconds = 60_000;
384
388
  static wslDistributionsUnreadable = "The shell list leaves out the WSL distributions, which could not be read.";
389
+ static readDropped = "The read was dropped before it started, since no one waits for it any more.";
385
390
  static visualStudioUnreadable = "The shell list leaves out Visual Studio's developer shells, since its installations could not be read.";
386
391
  static developerToolsPath = ["Common7", "Tools"];
387
392
  static developerCommandScript = "VsDevCmd.bat";
@@ -564,6 +569,7 @@ exit 0
564
569
  static systemRootMissing = "SystemRoot is not set, so reg.exe can't be found.";
565
570
  static environmentExportInvalid = "reg.exe did not export the machine's and the person's variables in a form that could be read.";
566
571
  static hostEnded = "The terminals have ended, so no shell starts.";
572
+ static connectionClosing = "The connection that sent the run is closing, so the run types nothing and opens no terminal.";
567
573
  static storedLinesFailed = "The terminal's stored lines could not be written.";
568
574
  static storedLinesDamaged = "The terminal's stored lines are damaged.";
569
575
  static carriageReturn = "\r";
@@ -19,6 +19,7 @@ import { ContextPtySpawner } from "./services/context-pty-spawner.js";
19
19
  import { FileSystemWriter } from "./services/file-system-writer.js";
20
20
  import { FileSystemReader } from "./services/file-system.reader.js";
21
21
  import { FolderAccess } from "./services/folder-access.js";
22
+ import { LatestEnvironment } from "./services/latest-environment.js";
22
23
  import { LineProcessStarter } from "./services/line-process-starter.js";
23
24
  import { MacEnvironment } from "./services/mac-environment.js";
24
25
  import { ProcessSignaller } from "./services/process-signaller.js";
@@ -51,7 +52,7 @@ export class RuntimePart {
51
52
  environment.start();
52
53
  try {
53
54
  const events = new TerminalEvents(context.declareEvent(TerminalNames.outputEvent), context.declareEvent(TerminalNames.exitedEvent), context.declareEvent(TerminalNames.restartedEvent), context.declareEvent(TerminalNames.titleChangedEvent), context.declareEvent(TerminalNames.cwdChangedEvent), context.declareEvent(TerminalNames.detachedEvent), context.declareEvent(TerminalNames.closedEvent), context.declareEvent(TerminalNames.openedEvent), context.declareEvent(TerminalNames.launchCommandEndedEvent), context.declareEvent(TerminalNames.runOpenedEvent), context.declareEvent(TerminalNames.runEndedEvent), context.declareEvent(TerminalNames.renamedEvent), context.declareEvent(TerminalNames.commandAddedEvent));
54
- const host = new TerminalHost(new ContextPtySpawner(context), reader, new ShellIntegration(writer, tmpdir(), context.log, access, context.settings, process.platform), new TerminalHistoryFolder(writer, reader, new ProcessSignaller(), tmpdir(), process.pid, context.log, access), new ShellLocator(process.platform, process.arch, process.env, ShellLocator.readUserShell(), reader, runner, context.log), process.platform, release(), environment, homedir(), context.log, events, new SavedTerminals(context.database, context.log), new CompletionSource(reader, runner, process.platform, homedir(), context.log));
55
+ const host = new TerminalHost(new ContextPtySpawner(context), reader, new ShellIntegration(writer, tmpdir(), context.log, access, context.settings, process.platform), new TerminalHistoryFolder(writer, reader, new ProcessSignaller(), tmpdir(), process.pid, context.log, access), new ShellLocator(process.platform, process.arch, process.env, ShellLocator.readUserShell(), reader, runner, context.log), process.platform, release(), new LatestEnvironment(environment, process.env), homedir(), context.log, events, new SavedTerminals(context.database, context.log), new CompletionSource(reader, runner, process.platform, homedir(), context.log));
55
56
  for (const name of TerminalNames.methods)
56
57
  context.registerMethod(name, { handleAsync: t => host.handleAsync(name, t.payload, RequestClient.fromContext(t)) });
57
58
  context.onClientClosed(t => host.closeConnectionAsync(t.connection, t.window));
@@ -5,10 +5,12 @@
5
5
  * This source code is licensed under the license found in the
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
+ import { ReadDroppedException } from "../exceptions/read-dropped.exception.js";
8
9
  export class BoundedReads {
9
10
  reader;
10
11
  expiry = Promise.withResolvers();
11
12
  timer;
13
+ stopping = new AbortController();
12
14
  pending = new Set();
13
15
  hasExpired = false;
14
16
  hasCutShort = false;
@@ -17,6 +19,7 @@ export class BoundedReads {
17
19
  this.timer = setTimeout(() => {
18
20
  this.hasExpired = true;
19
21
  this.expiry.resolve();
22
+ this.stopping.abort();
20
23
  }, milliseconds);
21
24
  }
22
25
  get wasCutShort() {
@@ -27,28 +30,33 @@ export class BoundedReads {
27
30
  }
28
31
  end() {
29
32
  clearTimeout(this.timer);
33
+ this.stopping.abort();
30
34
  }
31
35
  readEntriesAsync(path) {
32
- return this.boundAsync(() => this.reader.readEntriesAsync(path), []);
36
+ return this.boundAsync(t => this.reader.readEntriesAsync(path, t), []);
33
37
  }
34
38
  readTextOrNullAsync(path) {
35
- return this.boundAsync(() => this.reader.readTextOrNullAsync(path), null);
39
+ return this.boundAsync(t => this.reader.readTextOrNullAsync(path, t), null);
36
40
  }
37
41
  isProgramAsync(path) {
38
- return this.boundAsync(() => this.reader.isProgramAsync(path), false);
42
+ return this.boundAsync(t => this.reader.isProgramAsync(path, t), false);
39
43
  }
40
44
  readRealPathOrNullAsync(path) {
41
- return this.boundAsync(() => this.reader.readRealPathOrNullAsync(path), null);
45
+ return this.boundAsync(t => this.reader.readRealPathOrNullAsync(path, t), null);
42
46
  }
43
47
  async boundAsync(read, late) {
44
48
  if (this.hasExpired) {
45
49
  this.hasCutShort = true;
46
50
  return late;
47
51
  }
48
- const shared = read();
52
+ const shared = read(this.stopping.signal);
49
53
  this.pending.add(shared);
50
54
  const tracked = shared.finally(() => this.pending.delete(shared));
51
- const answer = await Promise.race([tracked.then(t => ({ value: t })), this.expiry.promise.then(() => null)]);
55
+ const answer = await Promise.race([tracked.then(t => ({ value: t }), (error) => {
56
+ if (error instanceof ReadDroppedException)
57
+ return null;
58
+ throw error;
59
+ }), this.expiry.promise.then(() => null)]);
52
60
  if (answer !== null)
53
61
  return answer.value;
54
62
  this.hasCutShort = true;
@@ -20,6 +20,7 @@ export class CommandTracker {
20
20
  hasTypedAhead = false;
21
21
  hasMarks = false;
22
22
  isAtPrompt = false;
23
+ isDrawingPrompt = false;
23
24
  hasEnteredLine = false;
24
25
  cwd = null;
25
26
  path = null;
@@ -67,21 +68,25 @@ export class CommandTracker {
67
68
  this.redrawFrom = this.canRedraw ? this.lineOffset : null;
68
69
  this.canRedraw = false;
69
70
  this.isAtPrompt = false;
71
+ this.isDrawingPrompt = true;
70
72
  this.promptStart = mark.offset;
71
73
  this.prompts++;
72
74
  break;
73
75
  case MarkKind.PromptEnd:
76
+ this.isDrawingPrompt = false;
74
77
  this.endPrompt(mark.offset);
75
78
  break;
76
79
  case MarkKind.OutputStart:
77
80
  this.stopRedraws();
78
81
  this.isAtPrompt = false;
82
+ this.isDrawingPrompt = false;
79
83
  this.current = new TrackedCommand(mark.offset, true);
80
84
  this.commandMarks++;
81
85
  break;
82
86
  case MarkKind.CommandEnd:
83
87
  this.stopRedraws();
84
88
  this.commandMarks++;
89
+ this.isDrawingPrompt = true;
85
90
  this.end(mark);
86
91
  break;
87
92
  case MarkKind.Property:
@@ -49,6 +49,9 @@ export class CompletionSource {
49
49
  .filter(t => !t.startsWith(Resources.helperNamePrefix) && t !== Resources.autocdName && !t.startsWith(Resources.suffixAliasNameStart));
50
50
  return this.readAsync(key, t => this.completeLineAsync(t, kind, builtins, line.slice(0, cursor), folder, environment));
51
51
  }
52
+ toLocalFolder(folder, kind, environment) {
53
+ return this.toLocalPath(folder, kind, this.readVariable(environment, Resources.temporaryFolderVariable) ?? null);
54
+ }
52
55
  followsCommand(kind, line, cursor) {
53
56
  return ShellWords.read(line.slice(0, cursor), kind === TerminalShellKind.PowerShell).words.length > 0;
54
57
  }
@@ -58,7 +61,8 @@ export class CompletionSource {
58
61
  const prefix = toKey(line.slice(completion.replaceFrom, cursor));
59
62
  const labels = new Set(completion.items.map(t => t.label));
60
63
  const added = [...new Set(options)]
61
- .filter(t => t.trim().length > 0 && t.length <= ProtocolResources.maximumPathLength && !labels.has(t) && toKey(t).startsWith(prefix))
64
+ .filter(t => t.trim().length > 0 && t.length <= ProtocolResources.maximumPathLength && !ProtocolResources.controlCharacters.test(t) && !labels.has(t)
65
+ && toKey(t).startsWith(prefix))
62
66
  .map(t => new TerminalCompletionItem(t, t, TerminalCompletionKind.Option));
63
67
  if (added.length === 0)
64
68
  return completion;
@@ -137,7 +141,7 @@ export class CompletionSource {
137
141
  return start > 0 && shellNames.has(`${Resources.suffixAliasNameStart}${name.slice(start + 1)}`);
138
142
  }
139
143
  async dropFoldersAsync(reads, kind, folder, environment, names) {
140
- const workFolder = this.toLocalPath(folder, kind, this.readVariable(environment, Resources.temporaryFolderVariable) ?? null);
144
+ const workFolder = this.toLocalFolder(folder, kind, environment);
141
145
  if (workFolder === null)
142
146
  return names;
143
147
  const folders = new Set((await reads.readEntriesAsync(workFolder)).filter(t => t.isFolder)
@@ -173,7 +177,7 @@ export class CompletionSource {
173
177
  const items = [...new Map(candidates.map(t => [t.value, t])).values()]
174
178
  .sort((a, b) => a.label.localeCompare(b.label, Resources.sortLocale))
175
179
  .map((t) => [ShellWords.write(t.value, shellLine.quote, isPowerShell, t.closesQuote, escapesWildcards && (t.kind === TerminalCompletionKind.File || t.kind === TerminalCompletionKind.Folder), keepsHome), t])
176
- .filter(([t]) => t.length <= ProtocolResources.maximumPathLength)
180
+ .filter(([t]) => t.length <= ProtocolResources.maximumPathLength && !ProtocolResources.controlCharacters.test(t))
177
181
  .map(([text, t]) => new TerminalCompletionItem(text, t.label, t.kind));
178
182
  return new TerminalCompletion(shellLine.start, items.slice(0, ProtocolResources.maximumCompletionItems));
179
183
  }
@@ -61,8 +61,8 @@ export class ContextPtyProcess {
61
61
  resize(columns, rows) {
62
62
  this.terminal.resize(columns, rows);
63
63
  }
64
- readForegroundProcessGroupAsync() {
65
- return this.terminal.readForegroundProcessGroupAsync();
64
+ readForegroundProcessAsync() {
65
+ return this.terminal.readForegroundProcessAsync();
66
66
  }
67
67
  pause() {
68
68
  this.terminal.pause();
@@ -56,8 +56,8 @@ export class DeferredPtyProcess {
56
56
  this.isPaused = false;
57
57
  this.process?.resume();
58
58
  }
59
- readForegroundProcessGroupAsync() {
60
- return this.process?.readForegroundProcessGroupAsync() ?? Promise.resolve(null);
59
+ readForegroundProcessAsync() {
60
+ return this.process?.readForegroundProcessAsync() ?? Promise.resolve(null);
61
61
  }
62
62
  async endAsync() {
63
63
  this.isEnded = true;
@@ -33,7 +33,10 @@ export class FileSystemReader {
33
33
  }
34
34
  async readEntriesAsync(path) {
35
35
  const entries = await FileSystemReader.readOrAsync(() => readdir(path, { withFileTypes: true }), [], Resources.unreadablePathCodes);
36
- return Promise.all(entries.map(async (t) => new FolderEntry(t.name, t.isDirectory() || (t.isSymbolicLink() && await this.isFolderAsync(join(path, t.name))))));
36
+ const listed = [];
37
+ for (const entry of entries)
38
+ listed.push(new FolderEntry(entry.name, entry.isDirectory() || entry.isSymbolicLink() && await this.isFolderAsync(join(path, entry.name))));
39
+ return listed;
37
40
  }
38
41
  readRealPathOrNullAsync(path) {
39
42
  return FileSystemReader.readOrAsync(() => realpath(path), null, Resources.unreadablePathCodes);
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export class LatestEnvironment {
9
+ source;
10
+ inherited;
11
+ latest;
12
+ reading = null;
13
+ constructor(source, inherited) {
14
+ this.source = source;
15
+ this.inherited = inherited;
16
+ this.latest = inherited;
17
+ }
18
+ async readAsync() {
19
+ const environment = await this.source.readAsync();
20
+ if (environment === null)
21
+ return this.inherited;
22
+ this.latest = environment;
23
+ return environment;
24
+ }
25
+ read() {
26
+ this.reading ??= this.readAsync().catch(() => undefined).then(() => {
27
+ this.reading = null;
28
+ });
29
+ return this.latest;
30
+ }
31
+ }
@@ -58,8 +58,8 @@ export class PseudoTerminal {
58
58
  if (!this.hasExited)
59
59
  this.process.resize(size.columns, size.rows);
60
60
  }
61
- async readForegroundProcessGroupAsync() {
62
- return this.hasExited ? null : await this.process.readForegroundProcessGroupAsync();
61
+ async readForegroundProcessAsync() {
62
+ return this.hasExited ? null : await this.process.readForegroundProcessAsync();
63
63
  }
64
64
  pause() {
65
65
  if (!this.hasExited && !this.isEnding)
@@ -5,37 +5,64 @@
5
5
  * This source code is licensed under the license found in the
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
+ import { ReadDroppedException } from "../exceptions/read-dropped.exception.js";
9
+ import { SharedRead } from "../models/shared-read.js";
10
+ import { Resources } from "../resources.js";
8
11
  export class SharedReads {
9
12
  reader;
10
13
  entries = new Map();
11
14
  texts = new Map();
12
15
  programs = new Map();
13
16
  realPaths = new Map();
17
+ waiting = new Set();
18
+ running = 0;
14
19
  constructor(reader) {
15
20
  this.reader = reader;
16
21
  }
17
- readEntriesAsync(path) {
18
- return this.share(this.entries, path, () => this.reader.readEntriesAsync(path));
22
+ readEntriesAsync(path, signal) {
23
+ return this.share(this.entries, path, signal, () => this.reader.readEntriesAsync(path));
19
24
  }
20
- readTextOrNullAsync(path) {
21
- return this.share(this.texts, path, () => this.reader.readTextOrNullAsync(path));
25
+ readTextOrNullAsync(path, signal) {
26
+ return this.share(this.texts, path, signal, () => this.reader.readTextOrNullAsync(path));
22
27
  }
23
- isProgramAsync(path) {
24
- return this.share(this.programs, path, () => this.reader.isProgramAsync(path));
28
+ isProgramAsync(path, signal) {
29
+ return this.share(this.programs, path, signal, () => this.reader.isProgramAsync(path));
25
30
  }
26
- readRealPathOrNullAsync(path) {
27
- return this.share(this.realPaths, path, () => this.reader.readRealPathOrNullAsync(path).catch((error) => {
31
+ readRealPathOrNullAsync(path, signal) {
32
+ return this.share(this.realPaths, path, signal, () => this.reader.readRealPathOrNullAsync(path).catch((error) => {
28
33
  if (error instanceof Error && "code" in error)
29
34
  return null;
30
35
  throw error;
31
36
  }));
32
37
  }
33
- share(running, path, read) {
34
- const shared = running.get(path);
35
- if (shared !== undefined)
36
- return shared;
37
- const started = read().finally(() => running.delete(path));
38
- running.set(path, started);
39
- return started;
38
+ share(running, path, signal, read) {
39
+ if (signal.aborted)
40
+ return Promise.reject(new ReadDroppedException());
41
+ let shared = running.get(path);
42
+ if (shared === undefined) {
43
+ const created = new SharedRead(read);
44
+ const settled = () => void running.delete(path);
45
+ void created.promise.then(settled, settled);
46
+ running.set(path, created);
47
+ this.waiting.add(created);
48
+ shared = created;
49
+ }
50
+ const watched = shared;
51
+ watched.watch(signal, () => void this.waiting.delete(watched));
52
+ this.startWaiting();
53
+ return watched.promise;
54
+ }
55
+ startWaiting() {
56
+ while (this.running < Resources.completionConcurrentReads) {
57
+ const next = this.waiting.values().next().value;
58
+ if (next === undefined)
59
+ return;
60
+ this.waiting.delete(next);
61
+ this.running++;
62
+ void next.startAsync().then(() => {
63
+ this.running--;
64
+ this.startWaiting();
65
+ });
66
+ }
40
67
  }
41
68
  }
@@ -12,6 +12,7 @@ import { OutputChunk } from "../tools/models/output-chunk.js";
12
12
  export class ShellCommand {
13
13
  session;
14
14
  line;
15
+ run;
15
16
  isKilled = false;
16
17
  givenUp = null;
17
18
  method = RunMethod.InShell;
@@ -19,6 +20,7 @@ export class ShellCommand {
19
20
  constructor(session, command, timeoutMilliseconds, logFile) {
20
21
  this.session = session;
21
22
  this.logFile = logFile;
23
+ this.run = session.run;
22
24
  this.line = session.typeLine(command);
23
25
  if (timeoutMilliseconds > 0) {
24
26
  const limit = new AbortController();
@@ -35,7 +37,7 @@ export class ShellCommand {
35
37
  return CommandStatus.Killed;
36
38
  if (this.tracked?.hasEnded === true || this.unmarkedEnd !== null)
37
39
  return this.isKilled ? CommandStatus.Killed : CommandStatus.Exited;
38
- if (this.session.hasExited)
40
+ if (this.restartEnd !== null || this.session.hasExited)
39
41
  return CommandStatus.Killed;
40
42
  return this.session.text.isAwaitingSecret ? CommandStatus.AwaitingInput : CommandStatus.Running;
41
43
  }
@@ -46,7 +48,7 @@ export class ShellCommand {
46
48
  return this.givenUp === null ? this.tracked?.cwd ?? null : null;
47
49
  }
48
50
  get hasEnded() {
49
- return this.givenUp !== null || this.tracked?.hasEnded === true || this.unmarkedEnd !== null || this.session.hasExited;
51
+ return this.givenUp !== null || this.tracked?.hasEnded === true || this.unmarkedEnd !== null || this.restartEnd !== null || this.session.hasExited;
50
52
  }
51
53
  get outputStart() {
52
54
  if (this.givenUp !== null)
@@ -55,7 +57,10 @@ export class ShellCommand {
55
57
  return tracked?.hasOutputStart === true ? tracked.outputStart : this.line.startOffset;
56
58
  }
57
59
  get outputEnd() {
58
- return this.givenUp?.[1] ?? this.tracked?.outputEnd ?? this.unmarkedEnd ?? this.session.text.endOffset;
60
+ return this.givenUp?.[1] ?? this.tracked?.outputEnd ?? this.unmarkedEnd ?? this.restartEnd ?? this.session.text.endOffset;
61
+ }
62
+ get restartEnd() {
63
+ return this.session.endOfRun(this.run);
59
64
  }
60
65
  get unmarkedEnd() {
61
66
  return this.line.endOffset;
@@ -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() {