@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.
@@ -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);
@@ -166,8 +176,8 @@ export class TerminalHost {
166
176
  findTerminal(sessionId) {
167
177
  return this.sessions.get(sessionId);
168
178
  }
169
- 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));
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, kept = null) {
180
+ return this.trackAsync(this.startTerminalAsync(shellId, folder, size, ownerSessionId, storedLimit, note, isPanelTerminal, owner, client, sessionId, environment, startsAtFit, opensTab, kept), 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);
@@ -238,7 +257,7 @@ export class TerminalHost {
238
257
  }
239
258
  await this.disposeAsync(terminal.session);
240
259
  }
241
- async startTerminalAsync(shellId, folder, size, ownerSessionId, storedLimit, note, isPanelTerminal, owner, client, sessionId, environment, startsAtFit, opensTab) {
260
+ async startTerminalAsync(shellId, folder, size, ownerSessionId, storedLimit, note, isPanelTerminal, owner, client, sessionId, environment, startsAtFit, opensTab, kept) {
242
261
  const shell = await this.locator.findAsync(shellId);
243
262
  this.ensureRunning();
244
263
  if (shell === undefined)
@@ -267,7 +286,7 @@ export class TerminalHost {
267
286
  },
268
287
  onTitleChanged: t => publish(this.events.titleChanged, t.toJson()),
269
288
  onCwdChanged: t => {
270
- if (isKept)
289
+ if (isKept && terminal.countsFolderReport(t.cwd))
271
290
  this.saved.moveTo(t.sessionId, t.cwd);
272
291
  publish(this.events.cwdChanged, t.toJson());
273
292
  },
@@ -283,8 +302,11 @@ export class TerminalHost {
283
302
  },
284
303
  onCommandStarted: t => this.addCommand(shell.id, t),
285
304
  onDetached: t => publish(this.events.detached, t.toJson()),
286
- onFailed: (id, message) => this.log.write(Resources.formatStartedCommandUnread(id, message))
305
+ onFailed: (id, message) => this.log.write(Resources.formatStartedCommandUnread(id, message)),
306
+ onResizeUnasked: t => this.log.write(Resources.formatResizeUnasked(t))
287
307
  }, Resources.maximumAgentTextLength, shell.kind, ownerSessionId === null), shell, folder, ownerSessionId, isPanelTerminal, owner, client?.connection ?? null, environment);
308
+ if (kept !== null)
309
+ terminal.keepFolderReports(kept.shellId === shell.id, kept.folder === folder);
288
310
  terminal.deferredShell = started.deferred;
289
311
  terminal.startTemporaryFolder = started.temporaryFolder;
290
312
  for (const line of started.printsNote ? [] : note?.split(Resources.lineBreaks) ?? [])
@@ -292,7 +314,7 @@ export class TerminalHost {
292
314
  terminal.opensTab = opensTab;
293
315
  this.sessions.set(sessionId, terminal);
294
316
  if (isKept)
295
- this.saved.save(new SavedTerminal(sessionId, shell.id, folder, isPanelTerminal, owner, opensTab));
317
+ this.saved.save(kept ?? new SavedTerminal(sessionId, shell.id, folder, isPanelTerminal, owner, opensTab));
296
318
  else if (ownerSessionId !== null && owner !== null)
297
319
  this.audience.publish(this.events.opened, terminal, terminal.session.toSummary(folder, true, isPanelTerminal, owner, true, null, shell.name).toJson());
298
320
  return terminal;
@@ -312,27 +334,50 @@ export class TerminalHost {
312
334
  async endConnectionAsync(connection, wasApp) {
313
335
  const isEnding = (terminal) => terminal.connection === null ? wasApp && terminal.owner !== null
314
336
  : 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();
337
+ const closed = Promise.withResolvers();
338
+ this.closings.set(isEnding, closed);
339
+ this.closingConnections.add(connection);
340
+ try {
341
+ for (const terminal of this.terminals.filter(isEnding))
342
+ terminal.cancelCommand();
343
+ await Promise.allSettled([this.restoring]);
344
+ await this.settleOpensAsync(isEnding);
345
+ if (this.hasEnded)
346
+ return;
347
+ const ending = this.terminals.filter(isEnding);
348
+ for (const terminal of ending) {
349
+ this.sessions.delete(terminal.session.sessionId);
350
+ terminal.cancelCommand();
351
+ }
352
+ if (wasApp)
353
+ this.restoring = null;
354
+ await Promise.all(ending.map(t => this.endAsync(t.session)));
325
355
  }
326
- if (wasApp)
327
- this.restoring = null;
328
- await Promise.all(ending.map(t => this.endAsync(t.session)));
356
+ finally {
357
+ this.closings.delete(isEnding);
358
+ this.closingConnections.delete(connection);
359
+ closed.resolve();
360
+ }
361
+ }
362
+ isClosing(terminal) {
363
+ return [...this.closings.keys()].some(isTheirs => isTheirs(terminal));
364
+ }
365
+ endForClose(params, client) {
366
+ const closing = this.findClosing(params, client);
367
+ return closing === undefined ? null : new TerminalRunResult(closing.session.sessionId, TerminalRunOutcome.Ended);
368
+ }
369
+ findClosing(params, client) {
370
+ return this.terminals.findLast(t => t.owner === params.owner && t.isReachedBy(client.connection, client.isApp) && this.isClosing(t));
329
371
  }
330
- trackAsync(opening) {
331
- this.opens.add(opening);
372
+ trackAsync(opening, place) {
373
+ this.opens.set(opening, place);
332
374
  const settled = () => void this.opens.delete(opening);
333
375
  void opening.then(settled, settled);
334
376
  return opening;
335
377
  }
378
+ async settleOpensAsync(isTheirs) {
379
+ await Promise.allSettled([...this.opens].filter(([, t]) => isTheirs(t)).map(([t]) => t));
380
+ }
336
381
  async launchAsync(params, client) {
337
382
  if (params.folder !== null && !this.isAbsolute(params.folder))
338
383
  throw new ArgumentException(ProtocolResources.formatNotAbsolutePath(ProtocolResources.valueSubject), Resources.folderParameter);
@@ -349,7 +394,7 @@ export class TerminalHost {
349
394
  throw new ShellKindNotFoundException(params.shellKinds);
350
395
  shellId = shell.id;
351
396
  }
352
- const terminal = await this.startTerminalAsync(shellId, folder, params.size, null, params.storedLimit, params.notice, false, null, client, randomUUID(), params.environment, false, params.opensTab);
397
+ const terminal = await this.startTerminalAsync(shellId, folder, params.size, null, params.storedLimit, params.notice, false, null, client, randomUUID(), params.environment, false, params.opensTab, null);
353
398
  if (!params.opensTab)
354
399
  terminal.launcher = client;
355
400
  if (params.command !== null)
@@ -387,7 +432,7 @@ export class TerminalHost {
387
432
  }
388
433
  if (session.hasIntegration && session.commands.isLoaded)
389
434
  await session.changes.waitUntilAsync(() => session.hasExited || isReady(), Resources.shellStartMilliseconds, signal);
390
- const isEnded = () => signal.aborted || session.hasExited || this.sessions.get(session.sessionId) !== terminal;
435
+ const isEnded = () => signal.aborted || session.hasExited || this.sessions.get(session.sessionId) !== terminal || this.isClosing(terminal);
391
436
  const isBracketed = isPaste && !isEnded() && await session.isBracketedPasteAsync();
392
437
  const outcome = isEnded() ? TerminalRunOutcome.Ended
393
438
  : isPaste && ((waitsForFit ? terminal.keyCount !== keyCount : terminal.inputCount !== inputCount) || session.commands.promptEndOffset !== null && session.readPromptLine() !== "") ? TerminalRunOutcome.Input
@@ -425,22 +470,54 @@ export class TerminalHost {
425
470
  const text = command.replace(Resources.trailingLineBreaks, "").replace(Resources.pasteLineBreaks, Resources.enterKey);
426
471
  return isBracketed ? `${Resources.pasteStart}${text}${Resources.pasteEnd}${Resources.enterKey}` : `${text}${Resources.enterKey}`;
427
472
  }
473
+ async runAfterClosesAsync(params, client) {
474
+ const place = new TerminalOpening(params.owner, client.connection);
475
+ for (;;) {
476
+ if (params.sessionId === null && this.isClosing(place)) {
477
+ const closing = this.findClosing(params, client);
478
+ if (closing !== undefined)
479
+ return new TerminalRunResult(closing.session.sessionId, TerminalRunOutcome.Ended);
480
+ if (this.closingConnections.has(client.connection))
481
+ throw new ConnectionClosingException();
482
+ await Promise.allSettled([...this.closings].filter(([isTheirs]) => isTheirs(place)).map(([, closed]) => closed.promise));
483
+ }
484
+ const result = await this.trackAsync(this.runAsync(params, client), place);
485
+ if (result !== null)
486
+ return result;
487
+ }
488
+ }
428
489
  async runAsync(params, client) {
429
490
  await Promise.allSettled([this.restoring]);
430
491
  this.ensureRunning();
431
492
  if (params.sessionId !== null) {
432
493
  const target = this.findRunTarget(params.sessionId, params, client);
433
- return target === null ? new TerminalRunResult(params.sessionId, TerminalRunOutcome.Ended) : this.runIntoAsync(params, target, client);
494
+ return target === null || this.isClosing(target) ? new TerminalRunResult(params.sessionId, TerminalRunOutcome.Ended)
495
+ : this.runIntoAsync(params, target, client);
496
+ }
497
+ const place = new TerminalOpening(params.owner, client.connection);
498
+ if (this.isClosing(place))
499
+ return this.endForClose(params, client);
500
+ const isOwned = (t) => t.owner === params.owner && t.isReachedBy(client.connection, client.isApp)
501
+ && (params.shellKinds.length === 0 || params.shellKinds.includes(t.shell.kind)) && !t.isRunStarting;
502
+ const wanted = params.folder === null ? null : await this.toRunFolderKeyAsync(params.folder);
503
+ let inFolder = await this.findInFolderAsync(wanted, isOwned);
504
+ const newest = this.terminals.findLast(t => isOwned(t) && inFolder?.has(t) !== false && (t.isFree || t.isDrawingPrompt));
505
+ if (newest !== undefined && !newest.isFree) {
506
+ await this.waitForPromptAsync(newest);
507
+ inFolder = await this.findInFolderAsync(wanted, isOwned);
434
508
  }
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);
509
+ let terminal = this.terminals.findLast(t => isOwned(t) && inFolder?.has(t) !== false && t.isFree);
437
510
  const isNew = terminal === undefined;
438
511
  if (terminal === undefined) {
439
512
  const shell = params.shellKinds.length === 0 ? await this.findFallbackShellAsync(params.shellId)
440
513
  : await this.findShellOfKindsAsync(params.shellKinds, params.shellId);
441
514
  if (shell === undefined && params.shellKinds.length > 0)
442
515
  return new TerminalRunResult(null, TerminalRunOutcome.NoShell);
516
+ if (this.isClosing(place))
517
+ return this.endForClose(params, client);
443
518
  terminal = await this.startForPersonAsync(new TerminalOpenParams(shell?.id ?? null, params.folder, params.size, params.storedLimit, false, params.owner), client, true, params.opensTab);
519
+ if (this.isClosing(terminal))
520
+ return new TerminalRunResult(terminal.session.sessionId, TerminalRunOutcome.Ended);
444
521
  if (!params.opensTab)
445
522
  terminal.fitWindow = client;
446
523
  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 +527,17 @@ export class TerminalHost {
450
527
  this.events.runOpened.publishTo(client.connection, client.window, new TerminalReference(terminal.session.sessionId).toJson());
451
528
  return this.typeRunAsync(terminal, params.command, client, isNew);
452
529
  }
530
+ async waitForPromptAsync(terminal) {
531
+ const wasStarting = terminal.isRunStarting;
532
+ terminal.isRunStarting = true;
533
+ try {
534
+ await terminal.session.changes.waitUntilAsync(() => !terminal.isDrawingPrompt, Resources.promptDrawWaitMilliseconds, terminal.beginInterrupt());
535
+ }
536
+ finally {
537
+ terminal.endInterrupt();
538
+ terminal.isRunStarting = wasStarting;
539
+ }
540
+ }
453
541
  findRunTarget(sessionId, params, client) {
454
542
  const terminal = this.sessions.get(sessionId);
455
543
  return terminal === undefined || !terminal.isReachedBy(client.connection, client.isApp) || terminal.ownerSessionId !== null
@@ -461,7 +549,13 @@ export class TerminalHost {
461
549
  return new TerminalRunResult(session.sessionId, TerminalRunOutcome.Busy);
462
550
  terminal.isRunStarting = true;
463
551
  try {
464
- const isBusy = () => !terminal.isFree && !session.hasExited && this.sessions.get(session.sessionId) === terminal;
552
+ const isBusy = () => !terminal.isFree && !session.hasExited && this.sessions.get(session.sessionId) === terminal
553
+ && !this.isClosing(terminal);
554
+ if (isBusy() && terminal.isDrawingPrompt) {
555
+ await this.waitForPromptAsync(terminal);
556
+ if (this.sessions.get(session.sessionId) !== terminal)
557
+ return new TerminalRunResult(session.sessionId, TerminalRunOutcome.Ended);
558
+ }
465
559
  if (isBusy() && params.whenBusy === TerminalRunBusy.Interrupt && terminal.pendingCommand === null) {
466
560
  const isStarted = () => isBusy() && session.commands.runningCommand !== null;
467
561
  const signal = terminal.beginInterrupt();
@@ -489,13 +583,14 @@ export class TerminalHost {
489
583
  }
490
584
  static async waitForCommandAsync(session, isStarted, deadline, signal) {
491
585
  for (;;) {
492
- const group = await session.readForegroundProcessGroupAsync();
586
+ const foreground = await session.readForegroundProcessAsync();
493
587
  if (!isStarted() || signal.aborted)
494
588
  return false;
495
- if (group !== session.pid)
589
+ const isCommand = foreground === null || foreground.group !== session.pid;
590
+ if (isCommand && (foreground === null || !foreground.isTerminalProgram))
496
591
  return true;
497
592
  if (Date.now() >= deadline)
498
- return false;
593
+ return isCommand;
499
594
  await session.changes.waitUntilAsync(() => !isStarted(), Math.min(Resources.foregroundPollMilliseconds, deadline - Date.now()), signal);
500
595
  }
501
596
  }
@@ -565,7 +660,7 @@ export class TerminalHost {
565
660
  return fallback !== undefined && kinds.includes(fallback.kind) ? fallback : await this.locator.findKindAsync(kinds);
566
661
  }
567
662
  openAsync(params, client) {
568
- return this.trackAsync(this.openRequestedAsync(params, client));
663
+ return this.trackAsync(this.openRequestedAsync(params, client), new TerminalOpening(params.owner, client.connection));
569
664
  }
570
665
  async openRequestedAsync(params, client) {
571
666
  if (!params.isPanelTerminal)
@@ -655,7 +750,7 @@ export class TerminalHost {
655
750
  const note = hasShell
656
751
  ? hasFolder ? null : Resources.formatStartFolderNote(saved.folder)
657
752
  : hasFolder ? Resources.formatRestoredShellNote(saved.shellId) : Resources.formatRestoredShellAndFolderNote(saved.shellId, saved.folder);
658
- const terminal = await this.openTerminalAsync(hasShell ? saved.shellId : fallback, hasFolder ? saved.folder : this.homeFolder, params.size, null, params.storedLimit, note, saved.isPanelTerminal, saved.owner, client, saved.sessionId, null, false, saved.opensTab);
753
+ const terminal = await this.openTerminalAsync(hasShell ? saved.shellId : fallback, hasFolder ? saved.folder : this.homeFolder, params.size, null, params.storedLimit, note, saved.isPanelTerminal, saved.owner, client, saved.sessionId, null, false, saved.opensTab, saved);
659
754
  const name = saved.name;
660
755
  terminal.name = name !== null && name.trim() !== "" && name.length <= ProtocolResources.maximumTitleLength ? name : null;
661
756
  if (!hasShell)
@@ -669,6 +764,72 @@ export class TerminalHost {
669
764
  isAbsolute(folder) {
670
765
  return this.windowsPty === null ? folder.startsWith(Resources.posixRoot) : Resources.windowsAbsolutePath.test(folder);
671
766
  }
767
+ async findInFolderAsync(wanted, isOwned) {
768
+ if (wanted === null)
769
+ return null;
770
+ const matched = [];
771
+ await Promise.all(this.terminals.filter(isOwned).map(async (t) => {
772
+ const known = await this.toTerminalFolderKeyAsync(t);
773
+ if (known !== null && known[1] === wanted)
774
+ matched.push([t, known[0]]);
775
+ }));
776
+ return new Set(matched.filter(([t, folder]) => folder === this.currentFolderOf(t)).map(([t]) => t));
777
+ }
778
+ async toRunFolderKeyAsync(folder) {
779
+ const real = await this.readRealFolderAsync(folder);
780
+ if (real !== null || await this.readBoundedAsync(() => this.fileSystem.isFolderAsync(folder)) !== false)
781
+ return this.toFolderKey(real ?? folder);
782
+ return this.toFolderKey(await this.readRealFolderAsync(this.homeFolder) ?? this.homeFolder);
783
+ }
784
+ async toTerminalFolderKeyAsync(terminal) {
785
+ const folder = this.currentFolderOf(terminal);
786
+ if (folder === null)
787
+ return null;
788
+ const known = this.folderKeys.get(terminal);
789
+ if (known !== undefined && known[0] === folder)
790
+ return known;
791
+ const reading = this.joinRealFolderRead(folder);
792
+ void reading.then(real => {
793
+ if (this.currentFolderOf(terminal) === folder)
794
+ this.folderKeys.set(terminal, [folder, this.toFolderKey(real ?? folder)]);
795
+ }, () => undefined);
796
+ const real = await this.readBoundedAsync(() => reading);
797
+ return [folder, this.toFolderKey(real ?? folder)];
798
+ }
799
+ currentFolderOf(terminal) {
800
+ const cwd = terminal.session.cwd;
801
+ if (cwd === null)
802
+ return terminal.folder;
803
+ const local = this.completions.toLocalFolder(cwd, terminal.shell.kind, this.readCompletionEnvironment(terminal));
804
+ if (local === null)
805
+ return null;
806
+ return this.isAbsolute(local) ? local : terminal.folder;
807
+ }
808
+ readRealFolderAsync(folder) {
809
+ return this.readBoundedAsync(() => this.joinRealFolderRead(folder));
810
+ }
811
+ joinRealFolderRead(folder) {
812
+ const running = this.realFolderReads.get(folder);
813
+ if (running !== undefined)
814
+ return running;
815
+ const reading = this.fileSystem.readRealPathOrNullAsync(folder).finally(() => this.realFolderReads.delete(folder));
816
+ this.realFolderReads.set(folder, reading);
817
+ return reading;
818
+ }
819
+ async readBoundedAsync(read) {
820
+ const late = Promise.withResolvers();
821
+ const timer = setTimeout(() => late.resolve(undefined), Resources.runFolderReadMilliseconds);
822
+ try {
823
+ return await Promise.race([read().catch(() => undefined), late.promise]);
824
+ }
825
+ finally {
826
+ clearTimeout(timer);
827
+ }
828
+ }
829
+ toFolderKey(folder) {
830
+ const trimmed = folder.replace(Resources.trailingFolderSeparators, "");
831
+ return this.windowsPty === null ? trimmed : trimmed.replaceAll(Resources.posixRoot, Resources.windowsSeparator).toLowerCase();
832
+ }
672
833
  async closeAsync(sessionId, client) {
673
834
  this.find(sessionId, client);
674
835
  await this.closeTerminalAsync(sessionId);
@@ -684,7 +845,7 @@ export class TerminalHost {
684
845
  const keys = params.asksShell && this.completions.followsCommand(terminal.shell.kind, params.line, params.cursor)
685
846
  ? Resources.optionsKeys.get(terminal.shell.kind) : undefined;
686
847
  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)),
848
+ 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
849
  keys === undefined ? Promise.resolve(ShellOptionsReply.none) : terminal.session.askOptionsAsync(keys)
689
850
  ]);
690
851
  if (reply.isTimedOut)
@@ -696,12 +857,12 @@ export class TerminalHost {
696
857
  const terminal = this.findHosted(params.sessionId, client);
697
858
  const shellNames = terminal.session.isShellPathReset || terminal.session.isShellModulePathReset ? null
698
859
  : terminal.session.shellNames;
699
- const environment = await this.readCompletionEnvironmentAsync(terminal);
860
+ const environment = this.readCompletionEnvironment(terminal);
700
861
  return terminal.shell.kind === TerminalShellKind.PowerShell
701
862
  ? this.completions.findMissingPowerShellAsync(terminal.session.commands, terminal.shell.file, params.names, shellNames, environment)
702
863
  : this.completions.findMissingAsync(params.sessionId, terminal.session.commands, terminal.session.prompts, terminal.shell.kind, terminal.session.cwd ?? terminal.folder, params.names, shellNames, environment);
703
864
  }
704
- async readCompletionEnvironmentAsync(terminal) {
865
+ readCompletionEnvironment(terminal) {
705
866
  const replaced = {};
706
867
  if (terminal.session.shellPath !== null)
707
868
  replaced[Resources.pathVariable] = terminal.session.shellPath;
@@ -711,7 +872,7 @@ export class TerminalHost {
711
872
  if (temporaryFolder !== null)
712
873
  replaced[Resources.temporaryFolderVariable] = temporaryFolder;
713
874
  const keys = new Set(Object.keys(replaced).map(t => this.toVariableKey(t)));
714
- return this.readShellEnvironmentAsync({
875
+ return this.withVariables(TerminalHost.toTerminalEnvironment(this.environment.read()), {
715
876
  ...Object.fromEntries(Object.entries(terminal.environment ?? {}).filter(([t]) => !keys.has(this.toVariableKey(t)))),
716
877
  ...replaced
717
878
  });
@@ -785,9 +946,14 @@ export class TerminalHost {
785
946
  if (terminal.shell.id === shellId && terminal.ownerSessionId === null)
786
947
  this.audience.publish(this.events.commandAdded, terminal, new TerminalCommandAdded(terminal.session.sessionId, command).toJson());
787
948
  }
788
- attachAsync(reference, client) {
949
+ async attachAsync(reference, client) {
789
950
  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) : []);
951
+ terminal.paneClients.set(reference.paneId, client);
952
+ const attachment = await terminal.session.attachAsync(reference.paneId, terminal.ownerSessionId === null && this.isSuggesting()
953
+ ? this.commandHistory.list(terminal.shell.id) : []);
954
+ if (!terminal.paneClients.has(reference.paneId))
955
+ terminal.session.detach(reference.paneId);
956
+ return attachment;
791
957
  }
792
958
  isSuggesting() {
793
959
  return this.integration.isSuggesting();
@@ -815,10 +981,22 @@ export class TerminalHost {
815
981
  }
816
982
  detach(reference, client) {
817
983
  const terminal = this.reachable(reference.sessionId, client);
984
+ terminal?.paneClients.delete(reference.paneId);
818
985
  terminal?.session.detach(reference.paneId);
819
986
  if (terminal !== null && !terminal.isSized)
820
987
  this.startShell(terminal);
821
988
  }
989
+ detachLeftPanes(isLeft) {
990
+ for (const terminal of this.terminals) {
991
+ const left = [...terminal.paneClients].filter(([, t]) => isLeft(t)).map(([t]) => t);
992
+ for (const paneId of left) {
993
+ terminal.paneClients.delete(paneId);
994
+ terminal.session.detach(paneId);
995
+ }
996
+ if (left.length > 0 && !terminal.isSized)
997
+ this.startShell(terminal);
998
+ }
999
+ }
822
1000
  startUnshownShells() {
823
1001
  for (const terminal of this.terminals)
824
1002
  this.startIfUnshown(terminal);
@@ -877,7 +1055,7 @@ export class TerminalHost {
877
1055
  return process;
878
1056
  }
879
1057
  async startShellAsync(shell, folder, size, note, variables, deferredSessionId = null) {
880
- const environment = await this.readShellEnvironmentAsync(variables);
1058
+ const environment = this.withVariables(await this.readEnvironmentAsync(), variables);
881
1059
  const printedNote = note === null || this.windowsPty === null ? null
882
1060
  : note.split(Resources.lineBreaks).map(t => TerminalSession.toNote(t)).join("");
883
1061
  const launch = await this.integration.prepareAsync(shell, randomUUID().replaceAll(Resources.terminalHostUuidSeparator, ""), environment, printedNote);
@@ -909,15 +1087,15 @@ export class TerminalHost {
909
1087
  const temporaryKey = this.toVariableKey(Resources.temporaryFolderVariable);
910
1088
  return new StartedShell(process, launch.nonce, launch.printsNote, deferred, Object.entries(environment).find(([t]) => this.toVariableKey(t) === temporaryKey)?.[1] ?? null);
911
1089
  }
912
- async readShellEnvironmentAsync(variables) {
1090
+ withVariables(environment, variables) {
913
1091
  const names = new Set(Object.keys(variables).map(t => this.toVariableKey(t)));
914
1092
  return Object.fromEntries([
915
- ...Object.entries(await this.readEnvironmentAsync()).filter(([t]) => !names.has(this.toVariableKey(t))),
1093
+ ...Object.entries(environment).filter(([t]) => !names.has(this.toVariableKey(t))),
916
1094
  ...Object.entries(variables)
917
1095
  ]);
918
1096
  }
919
1097
  async readEnvironmentAsync() {
920
- const environment = await this.environmentSource.readAsync();
1098
+ const environment = await this.environment.readAsync();
921
1099
  this.ensureRunning();
922
1100
  return TerminalHost.toTerminalEnvironment(environment);
923
1101
  }
@@ -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)
@@ -346,7 +354,8 @@ export class TerminalSession {
346
354
  onExit: t => {
347
355
  if (this.terminal === terminal)
348
356
  this.end(t);
349
- }
357
+ },
358
+ onResizeUnasked: () => this.listener.onResizeUnasked(this.sessionId)
350
359
  }, this.windowsPty !== null);
351
360
  return terminal;
352
361
  }
@@ -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() {