@noldova/terminal 0.0.4 → 0.0.6

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.6",
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.6",
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.6",
40
+ "@noldova/terminal.window": "0.0.6",
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",
49
- "@noldova/context.json": ">=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.12 <0.1.0",
49
+ "@noldova/context.json": ">=0.0.12 <0.1.0"
50
50
  },
51
- "gitHead": "d196e4e1493d3350d9dab89f1873e78de561448f"
51
+ "gitHead": "f57fcc215b0be7cabefe6bb1a45a5299aa5c87b6"
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,8 +6,13 @@
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;
13
+ countsFolderReports = true;
14
+ isFolderReportHeld = false;
15
+ heldFolderReport = null;
11
16
  session;
12
17
  shell;
13
18
  folder;
@@ -35,6 +40,7 @@ export class HostedTerminal {
35
40
  pendingCommand = null;
36
41
  launchCommandOffset = null;
37
42
  runs = new Map();
43
+ paneClients = new Map();
38
44
  name = null;
39
45
  isRunStarting = false;
40
46
  waitingRun = null;
@@ -49,6 +55,22 @@ export class HostedTerminal {
49
55
  this.owner = owner;
50
56
  this.connection = connection;
51
57
  this.environment = environment;
58
+ this.opening = new TerminalOpening(owner, connection);
59
+ }
60
+ keepFolderReports(isOwnShell, isOwnFolder) {
61
+ this.countsFolderReports = isOwnShell;
62
+ this.isFolderReportHeld = !isOwnFolder;
63
+ }
64
+ countsFolderReport(cwd) {
65
+ if (!this.countsFolderReports)
66
+ return false;
67
+ if (this.isFolderReportHeld) {
68
+ this.heldFolderReport ??= cwd;
69
+ if (cwd === this.heldFolderReport)
70
+ return false;
71
+ this.isFolderReportHeld = false;
72
+ }
73
+ return true;
52
74
  }
53
75
  get hasRecentInput() {
54
76
  return Date.now() - this.inputTime < Resources.echoSettleMilliseconds;
@@ -63,6 +85,10 @@ export class HostedTerminal {
63
85
  return this.ownerSessionId === null && !this.session.hasExited && !this.isRestarting && this.pendingCommand === null
64
86
  && this.session.commands.hasMarks && !this.hasUnreadInput && this.session.readPromptLine() === "";
65
87
  }
88
+ get isDrawingPrompt() {
89
+ return this.ownerSessionId === null && !this.session.hasExited && !this.isRestarting && this.pendingCommand === null
90
+ && this.session.commands.isDrawingPrompt;
91
+ }
66
92
  recordInput(isReply = false, data = "") {
67
93
  this.inputReceivedLength = this.session.receivedLength;
68
94
  if (isReply)
@@ -98,7 +124,7 @@ export class HostedTerminal {
98
124
  this.pendingInterrupt = null;
99
125
  }
100
126
  isReachedBy(connection, isApp) {
101
- return this.connection === null ? this.owner !== null && isApp : this.connection === connection;
127
+ return this.opening.isReachedBy(connection, isApp);
102
128
  }
103
129
  record(prompt) {
104
130
  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";
@@ -516,6 +521,11 @@ export class Resources {
516
521
  static loginArguments = ["-l", "--login", "-login"];
517
522
  static powerShellArguments = ["-NoExit", "-EncodedCommand"];
518
523
  static powerShellIntegrationArguments = ["-NoProfile", ...Resources.powerShellArguments];
524
+ static powerShellLoginParameter = "-login";
525
+ static powerShellLoginShell = "/bin/zsh";
526
+ static powerShellLoginShellArguments = ["--emulate", "sh", "-l", "-c", "exec \"$0\" \"$@\""];
527
+ static powerShellLoginCheckedVariable = "__PWSH_LOGIN_CHECKED";
528
+ static powerShellLoginCheckedValue = "1";
519
529
  static environmentReadArguments = ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand"];
520
530
  static formatPowerShellLookupFailed(count, message) {
521
531
  return `PowerShell's lookup of ${count} ${count === 1 ? "name" : "names"} a command line runs gave up, so they count as found, as later ones do until one succeeds: ${message}`;
@@ -564,6 +574,7 @@ exit 0
564
574
  static systemRootMissing = "SystemRoot is not set, so reg.exe can't be found.";
565
575
  static environmentExportInvalid = "reg.exe did not export the machine's and the person's variables in a form that could be read.";
566
576
  static hostEnded = "The terminals have ended, so no shell starts.";
577
+ static connectionClosing = "The connection that sent the run is closing, so the run types nothing and opens no terminal.";
567
578
  static storedLinesFailed = "The terminal's stored lines could not be written.";
568
579
  static storedLinesDamaged = "The terminal's stored lines are damaged.";
569
580
  static carriageReturn = "\r";
@@ -733,6 +744,9 @@ exit 0
733
744
  static formatStartedCommandUnread(sessionId, message) {
734
745
  return `The command started in terminal ${sessionId} could not be kept: ${message}`;
735
746
  }
747
+ static formatResizeUnasked(sessionId) {
748
+ return `ConPTY sent terminal ${sessionId} no cursor request within ${String(Resources.cursorAnswerMilliseconds)} ms of a resize, so the keys typed meanwhile went on without one.`;
749
+ }
736
750
  static formatLateShellLeftRunning(pid) {
737
751
  return `A shell that started as the terminals ended${pid === null ? "" : `, process ${pid}`}, or a process it started, did not end in time.`;
738
752
  }
@@ -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
+ }
@@ -14,6 +14,8 @@ export class PseudoTerminal {
14
14
  hasExited = false;
15
15
  isEnding = false;
16
16
  openRequests = 0;
17
+ isResizeAsking = false;
18
+ hasOutput = false;
17
19
  outputEnd = "";
18
20
  answerLimit = undefined;
19
21
  constructor(process, listener, isConPty = false) {
@@ -21,6 +23,7 @@ export class PseudoTerminal {
21
23
  this.listener = listener;
22
24
  this.isConPty = isConPty;
23
25
  this.process.onData(t => {
26
+ this.hasOutput = true;
24
27
  if (this.isConPty)
25
28
  this.watchCursorRequests(t);
26
29
  this.listener.onData(t);
@@ -55,11 +58,17 @@ export class PseudoTerminal {
55
58
  this.releaseKeys();
56
59
  }
57
60
  resize(size) {
58
- if (!this.hasExited)
59
- this.process.resize(size.columns, size.rows);
61
+ if (this.hasExited)
62
+ return;
63
+ this.process.resize(size.columns, size.rows);
64
+ if (!this.isConPty || !this.hasOutput || this.isResizeAsking)
65
+ return;
66
+ this.isResizeAsking = true;
67
+ this.openRequests++;
68
+ this.limitAnswers();
60
69
  }
61
- async readForegroundProcessGroupAsync() {
62
- return this.hasExited ? null : await this.process.readForegroundProcessGroupAsync();
70
+ async readForegroundProcessAsync() {
71
+ return this.hasExited ? null : await this.process.readForegroundProcessAsync();
63
72
  }
64
73
  pause() {
65
74
  if (!this.hasExited && !this.isEnding)
@@ -80,14 +89,24 @@ export class PseudoTerminal {
80
89
  this.outputEnd = text.slice(1 - Resources.cursorRequest.length);
81
90
  if (requests === 0)
82
91
  return;
92
+ this.limitAnswers();
93
+ this.openRequests += this.isResizeAsking ? requests - 1 : requests;
94
+ this.isResizeAsking = false;
95
+ }
96
+ limitAnswers() {
83
97
  clearTimeout(this.answerLimit);
84
- this.answerLimit = setTimeout(() => this.releaseKeys(), Resources.cursorAnswerMilliseconds);
85
- this.openRequests += requests;
98
+ this.answerLimit = setTimeout(() => this.releaseUnanswered(), Resources.cursorAnswerMilliseconds);
99
+ }
100
+ releaseUnanswered() {
101
+ if (this.isResizeAsking)
102
+ this.listener.onResizeUnasked?.();
103
+ this.releaseKeys();
86
104
  }
87
105
  releaseKeys() {
88
106
  clearTimeout(this.answerLimit);
89
107
  this.answerLimit = undefined;
90
108
  this.openRequests = 0;
109
+ this.isResizeAsking = false;
91
110
  for (const key of this.heldKeys.splice(0))
92
111
  this.write(key);
93
112
  }
@@ -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
  }