@theia/core 1.77.0-next.57 → 1.77.0-next.63

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.
Files changed (65) hide show
  1. package/lib/browser/keybinding.spec.js +15 -0
  2. package/lib/browser/keybinding.spec.js.map +1 -1
  3. package/lib/browser/keyboard/keyboard-layout-service.d.ts.map +1 -1
  4. package/lib/browser/keyboard/keyboard-layout-service.js +4 -0
  5. package/lib/browser/keyboard/keyboard-layout-service.js.map +1 -1
  6. package/lib/browser/keyboard/keyboard-layout-service.spec.js +29 -0
  7. package/lib/browser/keyboard/keyboard-layout-service.spec.js.map +1 -1
  8. package/lib/browser/tree/tree-compression/compressed-tree-model.d.ts +2 -0
  9. package/lib/browser/tree/tree-compression/compressed-tree-model.d.ts.map +1 -1
  10. package/lib/browser/tree/tree-compression/compressed-tree-model.js +6 -2
  11. package/lib/browser/tree/tree-compression/compressed-tree-model.js.map +1 -1
  12. package/lib/browser/tree/tree-compression/compressed-tree-model.spec.d.ts +2 -0
  13. package/lib/browser/tree/tree-compression/compressed-tree-model.spec.d.ts.map +1 -0
  14. package/lib/browser/tree/tree-compression/compressed-tree-model.spec.js +52 -0
  15. package/lib/browser/tree/tree-compression/compressed-tree-model.spec.js.map +1 -0
  16. package/lib/browser/tree/tree-widget.d.ts.map +1 -1
  17. package/lib/browser/tree/tree-widget.js +2 -3
  18. package/lib/browser/tree/tree-widget.js.map +1 -1
  19. package/lib/browser/tree/tree-widget.spec.js +18 -0
  20. package/lib/browser/tree/tree-widget.spec.js.map +1 -1
  21. package/lib/browser/view-container.d.ts.map +1 -1
  22. package/lib/browser/view-container.js +2 -1
  23. package/lib/browser/view-container.js.map +1 -1
  24. package/lib/common/promise-util.d.ts.map +1 -1
  25. package/lib/common/promise-util.js +5 -2
  26. package/lib/common/promise-util.js.map +1 -1
  27. package/lib/common/promise-util.spec.js +15 -0
  28. package/lib/common/promise-util.spec.js.map +1 -1
  29. package/lib/node/backend-application.d.ts +10 -4
  30. package/lib/node/backend-application.d.ts.map +1 -1
  31. package/lib/node/backend-application.js +27 -5
  32. package/lib/node/backend-application.js.map +1 -1
  33. package/lib/node/backend-application.spec.js +51 -2
  34. package/lib/node/backend-application.spec.js.map +1 -1
  35. package/lib/node/process-utils.d.ts +61 -0
  36. package/lib/node/process-utils.d.ts.map +1 -1
  37. package/lib/node/process-utils.js +156 -3
  38. package/lib/node/process-utils.js.map +1 -1
  39. package/lib/node/process-utils.slow-spec.d.ts +2 -0
  40. package/lib/node/process-utils.slow-spec.d.ts.map +1 -0
  41. package/lib/node/process-utils.slow-spec.js +106 -0
  42. package/lib/node/process-utils.slow-spec.js.map +1 -0
  43. package/lib/node/process-utils.spec.js +137 -0
  44. package/lib/node/process-utils.spec.js.map +1 -1
  45. package/lib/node/test/exiting-backend.d.ts +18 -0
  46. package/lib/node/test/exiting-backend.d.ts.map +1 -0
  47. package/lib/node/test/exiting-backend.js +71 -0
  48. package/lib/node/test/exiting-backend.js.map +1 -0
  49. package/package.json +4 -4
  50. package/src/browser/keybinding.spec.ts +17 -0
  51. package/src/browser/keyboard/keyboard-layout-service.spec.ts +33 -0
  52. package/src/browser/keyboard/keyboard-layout-service.ts +4 -0
  53. package/src/browser/tree/tree-compression/compressed-tree-model.spec.ts +57 -0
  54. package/src/browser/tree/tree-compression/compressed-tree-model.ts +11 -2
  55. package/src/browser/tree/tree-widget.spec.tsx +20 -0
  56. package/src/browser/tree/tree-widget.tsx +2 -3
  57. package/src/browser/view-container.ts +2 -1
  58. package/src/common/promise-util.spec.ts +18 -2
  59. package/src/common/promise-util.ts +5 -2
  60. package/src/node/backend-application.spec.ts +68 -2
  61. package/src/node/backend-application.ts +27 -5
  62. package/src/node/process-utils.slow-spec.ts +122 -0
  63. package/src/node/process-utils.spec.ts +162 -0
  64. package/src/node/process-utils.ts +166 -3
  65. package/src/node/test/exiting-backend.ts +75 -0
@@ -52,6 +52,7 @@ type AnyListener = (...args: any[]) => void;
52
52
  describe('BackendApplication', () => {
53
53
  let sandbox: sinon.SinonSandbox;
54
54
  let exitStub: sinon.SinonStub;
55
+ let terminateChildrenStub: sinon.SinonStub;
55
56
  let savedListeners: Partial<Record<ProcessEventName, AnyListener[]>>;
56
57
 
57
58
  beforeEach(() => {
@@ -66,6 +67,8 @@ describe('BackendApplication', () => {
66
67
  }
67
68
 
68
69
  exitStub = sandbox.stub(process, 'exit');
70
+ // Never kill the children of the test process.
71
+ terminateChildrenStub = sandbox.stub(ProcessUtils.prototype, 'terminateChildProcessTrees').resolves();
69
72
  });
70
73
 
71
74
  afterEach(() => {
@@ -173,6 +176,53 @@ describe('BackendApplication', () => {
173
176
  expect(warnStub.firstCall.args[0]).to.match(/timed out/);
174
177
  });
175
178
 
179
+ it('kills the child processes after unbinding the container and before exiting', async () => {
180
+ const container = createTestContainer();
181
+ const unbindSpy = sandbox.spy(container, 'unbindAllAsync');
182
+
183
+ const app = container.get(TestBackendApplication);
184
+
185
+ await app.invokeGracefulShutdown();
186
+
187
+ expect(terminateChildrenStub.calledOnceWithExactly(process.pid), 'the child processes of the backend should be killed').to.be.true;
188
+ expect(unbindSpy.calledBefore(terminateChildrenStub), 'the container should be unbound first').to.be.true;
189
+ expect(terminateChildrenStub.calledBefore(exitStub), 'the child processes should be killed before exiting').to.be.true;
190
+ });
191
+
192
+ it('still exits if killing the child processes rejects', async () => {
193
+ const container = createTestContainer();
194
+ terminateChildrenStub.rejects(new Error('powershell boom'));
195
+ const mockLogger = container.get(ILogger) as ILogger;
196
+ const warnStub = sandbox.stub(mockLogger, 'warn');
197
+
198
+ const app = container.get(TestBackendApplication);
199
+
200
+ await app.invokeGracefulShutdown();
201
+
202
+ expect(exitStub.calledOnceWith(1), 'process.exit(1) was not called').to.be.true;
203
+ expect(warnStub.calledOnce, 'a warning should be logged when killing the child processes rejects').to.be.true;
204
+ expect(warnStub.firstCall.args[0]).to.match(/powershell boom/);
205
+ });
206
+
207
+ it('exits even when killing the child processes hangs past the timeout', async () => {
208
+ const clock = sandbox.useFakeTimers();
209
+ const container = createTestContainer();
210
+ terminateChildrenStub.returns(new Promise<void>(() => { /* never */ }));
211
+ const mockLogger = container.get(ILogger) as ILogger;
212
+ const warnStub = sandbox.stub(mockLogger, 'warn');
213
+
214
+ const app = container.get(TestBackendApplication);
215
+
216
+ const shutdownPromise = app.invokeGracefulShutdown();
217
+
218
+ await clock.tickAsync(5001);
219
+ await shutdownPromise;
220
+
221
+ expect(exitStub.calledOnceWith(1), 'process.exit(1) was not called after timeout').to.be.true;
222
+ expect(warnStub.calledOnce, 'a warning should be logged on timeout').to.be.true;
223
+ expect(warnStub.firstCall.args[0]).to.match(/timed out/);
224
+ });
225
+
176
226
  it('awaits async onStop contributions before unbinding the container', async () => {
177
227
  const container = createTestContainer();
178
228
  const onStopDeferred = new Deferred<void>();
@@ -277,7 +327,7 @@ describe('BackendApplication', () => {
277
327
 
278
328
  describe('process exit handler', () => {
279
329
 
280
- it('does not re-invoke contributions after graceful shutdown ran them', async () => {
330
+ it('does not re-invoke contributions nor kill the child processes again after graceful shutdown did', async () => {
281
331
  const container = createTestContainer();
282
332
  const onStopSpy = sandbox.spy();
283
333
  container.bind(BackendApplicationContribution).toConstantValue({ onStop: onStopSpy });
@@ -288,11 +338,27 @@ describe('BackendApplication', () => {
288
338
 
289
339
  await app.invokeGracefulShutdown();
290
340
  expect(onStopSpy.callCount, 'contribution onStop should fire from gracefulShutdown').to.equal(1);
341
+ expect(terminateChildrenStub.callCount, 'the child processes should be killed by gracefulShutdown').to.equal(1);
291
342
 
292
343
  exitListener();
293
344
 
294
345
  expect(onStopSpy.callCount, 'contribution onStop should not be invoked a second time').to.equal(1);
295
- expect(terminateStub.called, 'terminateProcessTree should be invoked by the exit handler').to.be.true;
346
+ expect(terminateStub.called, 'terminateProcessTree should not be invoked by the exit handler').to.be.false;
347
+ expect(terminateChildrenStub.callCount, 'the child processes should not be killed a second time').to.equal(1);
348
+ });
349
+
350
+ it('does not retry killing the child processes in the exit handler when graceful shutdown failed to', async () => {
351
+ const container = createTestContainer();
352
+ terminateChildrenStub.rejects(new Error('powershell boom'));
353
+ const terminateStub = sandbox.stub(ProcessUtils.prototype, 'terminateProcessTree');
354
+
355
+ const app = container.get(TestBackendApplication);
356
+ const exitListener = process.listeners('exit')[0] as () => void;
357
+
358
+ await app.invokeGracefulShutdown();
359
+ exitListener();
360
+
361
+ expect(terminateStub.called, 'terminateProcessTree should not be retried by the exit handler').to.be.false;
296
362
  });
297
363
 
298
364
  it('invokes contributions synchronously when graceful shutdown was bypassed', () => {
@@ -204,6 +204,7 @@ export class BackendApplication {
204
204
 
205
205
  private stoppedContributions = false;
206
206
  private shuttingDown = false;
207
+ private terminatedChildProcesses = false;
207
208
 
208
209
  private settlementContext?: MeasurementContext<BackendApplicationContribution>;
209
210
 
@@ -389,10 +390,15 @@ export class BackendApplication {
389
390
  * settle in the background and could log noisily or interact with a partly
390
391
  * unbound container; this is accepted because the process is exiting.
391
392
  *
392
- * Idempotent: a second invocation is a no-op. Exits the process with code 1 so
393
- * that the `process.on('exit')` handler runs for fallback cleanup such as
394
- * {@link ProcessUtils.terminateProcessTree}; the exit handler does not re-invoke
395
- * contribution `onStop()` hooks that this method already dispatched.
393
+ * Child processes that are still running after both phases are then killed, see
394
+ * {@link ProcessUtils.terminateChildProcessTrees}, while the event loop is still
395
+ * available, so that the `process.on('exit')` handler does not have to do it
396
+ * synchronously.
397
+ *
398
+ * Idempotent: a second invocation is a no-op. Exits the process with code 1, so
399
+ * the `process.on('exit')` handler runs; it does not re-invoke contribution
400
+ * `onStop()` hooks that this method already dispatched, nor the termination of
401
+ * child processes.
396
402
  */
397
403
  protected async gracefulShutdown(): Promise<void> {
398
404
  if (this.shuttingDown) {
@@ -420,6 +426,18 @@ export class BackendApplication {
420
426
  this.logger.warn(`Backend root container cleanup failed: ${message}`);
421
427
  }
422
428
 
429
+ try {
430
+ await Promise.race([
431
+ this.processUtils.terminateChildProcessTrees(process.pid),
432
+ timeoutReject<void>(SHUTDOWN_TIMEOUT_MS, `Terminating child processes timed out after ${SHUTDOWN_TIMEOUT_MS}ms`)
433
+ ]);
434
+ } catch (err) {
435
+ const message = err instanceof Error ? err.message : String(err);
436
+ this.logger.warn(`Terminating child processes failed: ${message}`);
437
+ }
438
+ // Even if it failed: the synchronous fallback in `onStop` would fail the same way, only slower.
439
+ this.terminatedChildProcesses = true;
440
+
423
441
  process.exit(1);
424
442
  }
425
443
 
@@ -451,7 +469,11 @@ export class BackendApplication {
451
469
  // `terminateProcessTree`. Any returned promises are abandoned because
452
470
  // the `'exit'` event does not yield back to the event loop.
453
471
  this.stopContributions();
454
- this.processUtils.terminateProcessTree(process.pid);
472
+ // Fallback for an abrupt exit, e.g. `process.exit()`, that bypasses `gracefulShutdown`:
473
+ // listing the children blocks the event loop and can be slow, in particular on Windows.
474
+ if (!this.terminatedChildProcesses) {
475
+ this.processUtils.terminateProcessTree(process.pid);
476
+ }
455
477
  }
456
478
 
457
479
  protected async serveGzipped(contentType: string, req: express.Request, res: express.Response, next: express.NextFunction): Promise<void> {
@@ -0,0 +1,122 @@
1
+ // *****************************************************************************
2
+ // Copyright (C) 2026 EclipseSource and others.
3
+ //
4
+ // This program and the accompanying materials are made available under the
5
+ // terms of the Eclipse Public License v. 2.0 which is available at
6
+ // http://www.eclipse.org/legal/epl-2.0.
7
+ //
8
+ // This Source Code may also be made available under the following Secondary
9
+ // Licenses when the conditions for such availability set forth in the Eclipse
10
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
+ // with the GNU Classpath Exception which is available at
12
+ // https://www.gnu.org/software/classpath/license.html.
13
+ //
14
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
+ // *****************************************************************************
16
+
17
+ import { expect } from 'chai';
18
+ import * as cp from 'child_process';
19
+ import { Container } from 'inversify';
20
+ import { ILogger } from '../common/logger';
21
+ import { MockLogger } from '../common/test/mock-logger';
22
+ import { ProcessUtils } from './process-utils';
23
+ import { EXITING_BACKEND_EXIT_CODE, EXITING_BACKEND_GRACEFUL, EXITING_BACKEND_NO_POWERSHELL } from './test/exiting-backend';
24
+
25
+ interface ExitingProcessResult {
26
+ exitCode: number | null;
27
+ childPid: number;
28
+ }
29
+
30
+ function runExitingProcess(options: { env?: NodeJS.ProcessEnv, detached?: boolean } = {}): Promise<ExitingProcessResult> {
31
+ return new Promise((resolve, reject) => {
32
+ const exitingProcess = cp.spawn(process.execPath, [require.resolve('./test/exiting-backend')], {
33
+ env: { ...process.env, ...options.env },
34
+ detached: options.detached,
35
+ stdio: ['ignore', 'pipe', 'inherit'],
36
+ windowsHide: true
37
+ });
38
+ let stdout = '';
39
+ exitingProcess.stdout.on('data', data => stdout += data);
40
+ exitingProcess.on('error', reject);
41
+ exitingProcess.on('close', exitCode => resolve({ exitCode, childPid: Number.parseInt(stdout, 10) }));
42
+ });
43
+ }
44
+
45
+ function isAlive(pid: number): boolean {
46
+ try {
47
+ process.kill(pid, 0);
48
+ return true;
49
+ } catch (error) {
50
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Waits a little for the process to disappear, as killing it may not take effect immediately.
56
+ */
57
+ async function isAliveAfterKill(pid: number): Promise<boolean> {
58
+ for (let attempt = 0; attempt < 20 && isAlive(pid); attempt++) {
59
+ await new Promise(resolve => setTimeout(resolve, 100));
60
+ }
61
+ return isAlive(pid);
62
+ }
63
+
64
+ describe('ProcessUtils (real processes)', function (): void {
65
+
66
+ this.timeout(30_000);
67
+
68
+ const childPids: number[] = [];
69
+
70
+ afterEach(() => {
71
+ // Do not leak processes if a test fails.
72
+ for (const pid of childPids.splice(0)) {
73
+ if (isAlive(pid)) {
74
+ process.kill(pid);
75
+ }
76
+ }
77
+ });
78
+
79
+ async function expectTerminatedTree(options: Parameters<typeof runExitingProcess>[0], expectedExitCode: number): Promise<void> {
80
+ const { exitCode, childPid } = await runExitingProcess(options);
81
+ expect(childPid, 'the exiting process should report the PID of its child').to.be.greaterThan(0);
82
+ childPids.push(childPid);
83
+ expect(exitCode).to.equal(expectedExitCode);
84
+ expect(await isAliveAfterKill(childPid), 'the child of the exiting process should be killed').to.be.false;
85
+ }
86
+
87
+ it('keeps the exit code of the backend and kills its children', async () => {
88
+ await expectTerminatedTree({}, EXITING_BACKEND_EXIT_CODE);
89
+ });
90
+
91
+ (process.platform === 'win32' ? it.skip : it)('keeps the exit code of the backend when it leads its process group', async () => {
92
+ await expectTerminatedTree({ detached: true }, EXITING_BACKEND_EXIT_CODE);
93
+ });
94
+
95
+ it('kills the children of the backend on graceful shutdown', async () => {
96
+ // `BackendApplication.gracefulShutdown` exits with code 1 on purpose.
97
+ await expectTerminatedTree({ env: { [EXITING_BACKEND_GRACEFUL]: 'true' } }, 1);
98
+ });
99
+
100
+ (process.platform === 'win32' ? it : it.skip)('kills the whole tree of the backend when PowerShell cannot be run', async () => {
101
+ // Only PowerShell is made unrunnable: breaking the environment, e.g. `SystemRoot`, would
102
+ // break `taskkill.exe` as well. The fallback kills the backend too, with exit code 1.
103
+ await expectTerminatedTree({ env: { [EXITING_BACKEND_NO_POWERSHELL]: 'true' } }, 1);
104
+ });
105
+
106
+ (process.platform === 'win32' ? it : it.skip)('lists the children of a process with PowerShell', async () => {
107
+ const container = new Container();
108
+ container.bind(ProcessUtils).toSelf().inSingletonScope();
109
+ container.bind(ILogger).to(MockLogger).inSingletonScope();
110
+ const processUtils = container.get(ProcessUtils);
111
+
112
+ const children = [1, 2].map(() => cp.spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }));
113
+ await Promise.all(children.map(child => new Promise(resolve => child.on('spawn', resolve))));
114
+ childPids.push(...children.map(child => child.pid!));
115
+
116
+ for (const listedPids of [processUtils['winGetChildPids'](process.pid), await processUtils['winGetChildPidsAsync'](process.pid)]) {
117
+ expect(listedPids).to.include.members(childPids);
118
+ // The PowerShell process that lists the children has exited by now, so it must not be listed.
119
+ expect(listedPids.filter(pid => !isAlive(pid)), 'only live processes should be listed').to.be.empty;
120
+ }
121
+ });
122
+ });
@@ -51,6 +51,33 @@ describe('ProcessUtils', () => {
51
51
  expect(Array.from(pids)).members([40, 5, 6, 7]);
52
52
  });
53
53
 
54
+ describe('#unixTerminateChildProcessTrees', () => {
55
+ let killStub: sinon.SinonStub;
56
+
57
+ beforeEach(() => {
58
+ coreProcessManager['execFile'] = async () => ({ stdout: mockPsOutput, stderr: '' });
59
+ killStub = sinon.stub();
60
+ coreProcessManager['unixKill'] = killStub;
61
+ });
62
+
63
+ afterEach(() => {
64
+ sinon.restore();
65
+ });
66
+
67
+ it('kills all descendants but not the process itself', async () => {
68
+ await coreProcessManager['unixTerminateChildProcessTrees'](2);
69
+ expect(killStub.args.map(([pid]) => pid)).members([40, 5, 6, 7]);
70
+ });
71
+
72
+ it('rejects when the processes cannot be listed', async () => {
73
+ coreProcessManager['execFile'] = async () => { throw new Error('ps not found'); };
74
+ let error: unknown;
75
+ await coreProcessManager['unixTerminateChildProcessTrees'](2).catch(e => error = e);
76
+ expect(error).to.be.instanceOf(Error);
77
+ expect(killStub.called).to.be.false;
78
+ });
79
+ });
80
+
54
81
  describe('#unixTerminateProcessTree', () => {
55
82
  let originalKill: typeof process.kill;
56
83
  let errorStub: sinon.SinonStub;
@@ -96,4 +123,139 @@ describe('ProcessUtils', () => {
96
123
  expect(errorStub.called).to.be.true;
97
124
  });
98
125
  });
126
+
127
+ describe('#winTerminateProcessTree', () => {
128
+ let taskkillStub: sinon.SinonStub;
129
+ let warnStub: sinon.SinonStub;
130
+
131
+ beforeEach(() => {
132
+ const mockLogger = (coreProcessManager as unknown as { logger: ILogger }).logger;
133
+ warnStub = sinon.stub(mockLogger, 'warn');
134
+ taskkillStub = sinon.stub();
135
+ coreProcessManager['winTaskkillTrees'] = taskkillStub;
136
+ });
137
+
138
+ afterEach(() => {
139
+ sinon.restore();
140
+ });
141
+
142
+ it('kills the tree of another process including its root', () => {
143
+ coreProcessManager['winGetChildPids'] = () => expect.fail('children should not be listed');
144
+ coreProcessManager['winTerminateProcessTree'](424243);
145
+ expect(taskkillStub.calledOnceWithExactly([424243])).to.be.true;
146
+ });
147
+
148
+ it('kills only the trees of the children of the current process', () => {
149
+ coreProcessManager['winGetChildPids'] = () => [424244, 424245];
150
+ coreProcessManager['winTerminateProcessTree'](process.pid);
151
+ expect(taskkillStub.calledOnceWithExactly([424244, 424245])).to.be.true;
152
+ });
153
+
154
+ it('does not run taskkill when the current process has no children', () => {
155
+ coreProcessManager['winGetChildPids'] = () => [];
156
+ coreProcessManager['winTerminateProcessTree'](process.pid);
157
+ expect(taskkillStub.called).to.be.false;
158
+ });
159
+
160
+ it('falls back to killing the whole tree when the children of the current process cannot be listed', () => {
161
+ coreProcessManager['winGetChildPids'] = () => { throw new Error('powershell.exe not found'); };
162
+ expect(() => coreProcessManager['winTerminateProcessTree'](process.pid)).to.not.throw();
163
+ expect(taskkillStub.calledOnceWithExactly([process.pid])).to.be.true;
164
+ expect(warnStub.called).to.be.true;
165
+ });
166
+ });
167
+
168
+ describe('#winTerminateChildProcessTrees', () => {
169
+ let taskkillStub: sinon.SinonStub;
170
+
171
+ beforeEach(() => {
172
+ taskkillStub = sinon.stub();
173
+ coreProcessManager['winTaskkillTrees'] = taskkillStub;
174
+ });
175
+
176
+ afterEach(() => {
177
+ sinon.restore();
178
+ });
179
+
180
+ it('kills the trees of the children of the process', async () => {
181
+ coreProcessManager['winGetChildPidsAsync'] = async () => [424244, 424245];
182
+ await coreProcessManager['winTerminateChildProcessTrees'](process.pid);
183
+ expect(taskkillStub.calledOnceWithExactly([424244, 424245])).to.be.true;
184
+ });
185
+
186
+ it('does not run taskkill when the process has no children', async () => {
187
+ coreProcessManager['winGetChildPidsAsync'] = async () => [];
188
+ await coreProcessManager['winTerminateChildProcessTrees'](process.pid);
189
+ expect(taskkillStub.called).to.be.false;
190
+ });
191
+
192
+ it('rejects when the children cannot be listed', async () => {
193
+ coreProcessManager['winGetChildPidsAsync'] = async () => { throw new Error('powershell.exe not found'); };
194
+ let error: unknown;
195
+ await coreProcessManager['winTerminateChildProcessTrees'](process.pid).catch(e => error = e);
196
+ expect(error).to.be.instanceOf(Error);
197
+ expect(taskkillStub.called).to.be.false;
198
+ });
199
+ });
200
+
201
+ describe('#winGetChildPids', () => {
202
+ let originalSystemRoot: string | undefined;
203
+ let spawnSyncStub: sinon.SinonStub;
204
+ let execFileStub: sinon.SinonStub;
205
+
206
+ beforeEach(() => {
207
+ originalSystemRoot = process.env.SystemRoot;
208
+ spawnSyncStub = sinon.stub().returns({ stdout: '1234\r\n5678\r\n\r\n' });
209
+ coreProcessManager['spawnSync'] = spawnSyncStub;
210
+ execFileStub = sinon.stub().resolves({ stdout: '1234\r\n5678\r\n\r\n', stderr: '' });
211
+ coreProcessManager['execFile'] = execFileStub;
212
+ });
213
+
214
+ afterEach(() => {
215
+ if (originalSystemRoot === undefined) {
216
+ delete process.env.SystemRoot;
217
+ } else {
218
+ process.env.SystemRoot = originalSystemRoot;
219
+ }
220
+ });
221
+
222
+ it('parses the PowerShell output', () => {
223
+ expect(coreProcessManager['winGetChildPids'](42)).to.deep.equal([1234, 5678]);
224
+ });
225
+
226
+ it('parses the PowerShell output asynchronously', async () => {
227
+ expect(await coreProcessManager['winGetChildPidsAsync'](42)).to.deep.equal([1234, 5678]);
228
+ expect(spawnSyncStub.called).to.be.false;
229
+ });
230
+
231
+ it('runs PowerShell from the Windows directory with a timeout', async () => {
232
+ process.env.SystemRoot = 'C:\\Windows';
233
+ coreProcessManager['winGetChildPids'](42);
234
+ await coreProcessManager['winGetChildPidsAsync'](42);
235
+ for (const stub of [spawnSyncStub, execFileStub]) {
236
+ const [file, , options] = stub.firstCall.args;
237
+ expect(file).to.equal('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe');
238
+ expect(options.timeout).to.be.greaterThan(0);
239
+ }
240
+ });
241
+
242
+ it('excludes the PowerShell process itself, the console host and the children of a previous process with the same PID', async () => {
243
+ coreProcessManager['winGetChildPids'](42);
244
+ await coreProcessManager['winGetChildPidsAsync'](42);
245
+ for (const stub of [spawnSyncStub, execFileStub]) {
246
+ const command: string = stub.firstCall.args[1].at(-1);
247
+ expect(command).to.contain("Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=42'");
248
+ expect(command).to.contain('ParentProcessId=42');
249
+ expect(command).to.contain('$_.ProcessId -ne $PID');
250
+ expect(command).to.contain("$_.Name -ne 'conhost.exe'");
251
+ expect(command).to.contain('$_.CreationDate -ge $parent.CreationDate');
252
+ }
253
+ });
254
+
255
+ it('runs PowerShell from the PATH when the Windows directory is unknown', () => {
256
+ delete process.env.SystemRoot;
257
+ coreProcessManager['winGetChildPids'](42);
258
+ expect(spawnSyncStub.firstCall.args[0]).to.equal('powershell.exe');
259
+ });
260
+ });
99
261
  });