@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
@@ -15,9 +15,20 @@
15
15
  // *****************************************************************************
16
16
 
17
17
  import * as cp from 'child_process';
18
+ import * as path from 'path';
18
19
  import { injectable, inject, named } from 'inversify';
19
20
  import { ILogger } from '../common/logger';
20
21
 
22
+ /**
23
+ * How long to wait for PowerShell to list child processes before giving up, in milliseconds.
24
+ */
25
+ const WIN_LIST_CHILDREN_TIMEOUT_MS = 5000;
26
+
27
+ /**
28
+ * Options for running PowerShell to list child processes.
29
+ */
30
+ const WIN_LIST_CHILDREN_OPTIONS = { windowsHide: true, timeout: WIN_LIST_CHILDREN_TIMEOUT_MS };
31
+
21
32
  /**
22
33
  * `@theia/core` service with some process-related utilities.
23
34
  */
@@ -27,6 +38,13 @@ export class ProcessUtils {
27
38
  @inject(ILogger) @named('core:ProcessUtils')
28
39
  protected readonly logger: ILogger;
29
40
 
41
+ /**
42
+ * Kills the given process together with all of its descendants.
43
+ *
44
+ * This blocks the event loop, so that it can run in an `exit` handler, where the loop is no longer
45
+ * available. Prefer {@link terminateChildProcessTrees} while the event loop is running, as listing
46
+ * the descendants of a process can be slow, in particular on Windows.
47
+ */
30
48
  terminateProcessTree(ppid: number): void {
31
49
  if (process.platform === 'win32') {
32
50
  this.winTerminateProcessTree(ppid);
@@ -35,18 +53,128 @@ export class ProcessUtils {
35
53
  }
36
54
  }
37
55
 
56
+ /**
57
+ * Kills all of the descendants of the given process, but not the process itself, without blocking
58
+ * the event loop.
59
+ *
60
+ * @throws if the descendants of the process cannot be listed
61
+ */
62
+ async terminateChildProcessTrees(ppid: number): Promise<void> {
63
+ if (process.platform === 'win32') {
64
+ await this.winTerminateChildProcessTrees(ppid);
65
+ } else {
66
+ await this.unixTerminateChildProcessTrees(ppid);
67
+ }
68
+ }
69
+
38
70
  protected winTerminateProcessTree(ppid: number): void {
39
- const result = cp.spawnSync('taskkill.exe', ['/f', '/t', '/pid', ppid.toString(10)], { encoding: 'utf8' });
71
+ if (ppid !== process.pid) {
72
+ this.winTaskkillTrees([ppid]);
73
+ return;
74
+ }
75
+ // `taskkill /t` always kills the root of the tree as well. Killing the current process
76
+ // with `/f` terminates it with exit code 1, overriding the exit code that it may be
77
+ // exiting with, so only kill the trees of its children, as on Unix.
78
+ let childPids: number[];
79
+ try {
80
+ childPids = this.winGetChildPids(ppid);
81
+ } catch (error) {
82
+ // Without the list of children, killing the whole tree is the only way to avoid leaking
83
+ // child processes, at the cost of the current process exiting with code 1.
84
+ this.logger.warn(`Failed to list the child processes of PID ${ppid}, killing its whole tree`, error);
85
+ this.winTaskkillTrees([ppid]);
86
+ return;
87
+ }
88
+ if (childPids.length > 0) {
89
+ this.winTaskkillTrees(childPids);
90
+ }
91
+ }
92
+
93
+ protected async winTerminateChildProcessTrees(ppid: number): Promise<void> {
94
+ const childPids = await this.winGetChildPidsAsync(ppid);
95
+ if (childPids.length > 0) {
96
+ // `taskkill` is quick, unlike PowerShell, so running it synchronously is fine here too.
97
+ this.winTaskkillTrees(childPids);
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Forcefully kills the given processes together with all of their descendants.
103
+ */
104
+ protected winTaskkillTrees(pids: number[]): void {
105
+ const pidArgs = pids.flatMap(pid => ['/pid', pid.toString(10)]);
106
+ // Not `this.spawnSync`, which throws on a non-zero exit code that is expected here.
107
+ const result = cp.spawnSync('taskkill.exe', ['/f', '/t', ...pidArgs], { encoding: 'utf8' });
40
108
  if (result.error) {
41
109
  throw result.error;
42
110
  }
43
111
  // taskkill may exit with a non-zero code when some child processes have already exited.
44
112
  // This is expected during shutdown — log but don't throw.
45
113
  if (result.status !== 0) {
46
- this.logger.warn(`taskkill.exe exited with ${result.status} for PID ${ppid}. Output:\n${JSON.stringify(result.output)}`);
114
+ this.logger.warn(`taskkill.exe exited with ${result.status} for PIDs ${pids.join(', ')}. Output:\n${JSON.stringify(result.output)}`);
47
115
  }
48
116
  }
49
117
 
118
+ /**
119
+ * @returns the PIDs of the direct children of the given process, see {@link winGetChildPidsArgs}
120
+ */
121
+ protected winGetChildPids(ppid: number): number[] {
122
+ const { stdout } = this.spawnSync(this.winGetPowerShellPath(), this.winGetChildPidsArgs(ppid), WIN_LIST_CHILDREN_OPTIONS);
123
+ return this.winParsePids(stdout);
124
+ }
125
+
126
+ /**
127
+ * @returns the PIDs of the direct children of the given process, see {@link winGetChildPidsArgs}
128
+ */
129
+ protected async winGetChildPidsAsync(ppid: number): Promise<number[]> {
130
+ const { stdout } = await this.execFile(this.winGetPowerShellPath(), this.winGetChildPidsArgs(ppid), WIN_LIST_CHILDREN_OPTIONS);
131
+ return this.winParsePids(stdout);
132
+ }
133
+
134
+ /**
135
+ * @returns the arguments of a PowerShell command that prints the PIDs of the direct children of the
136
+ * given process, one per line, except for:
137
+ * - the PowerShell process that lists them, which is a child of the current process and exits right after
138
+ * - the console host (`conhost.exe`) that Windows attaches to a process launched without a console,
139
+ * which `taskkill` may fail to kill
140
+ * - processes created before the given process: Windows does not update the parent of a process
141
+ * when the parent exits and reuses PIDs, so these are the orphans of a previous process with the same PID
142
+ */
143
+ protected winGetChildPidsArgs(ppid: number): string[] {
144
+ const pid = ppid.toString(10);
145
+ return [
146
+ '-NoLogo', '-NoProfile', '-NonInteractive', '-Command',
147
+ `$parent = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}';`
148
+ + ` Get-CimInstance -ClassName Win32_Process -Filter 'ParentProcessId=${pid}'`
149
+ + " | Where-Object { $_.ProcessId -ne $PID -and $_.Name -ne 'conhost.exe' -and $_.CreationDate -ge $parent.CreationDate }"
150
+ + ' | ForEach-Object { $_.ProcessId }'
151
+ ];
152
+ }
153
+
154
+ /**
155
+ * @param output the output of the command of {@link winGetChildPidsArgs}
156
+ */
157
+ protected winParsePids(output: string): number[] {
158
+ return output
159
+ .split(/\s+/)
160
+ .filter(token => /^\d+$/.test(token))
161
+ .map(token => Number.parseInt(token, 10));
162
+ }
163
+
164
+ /**
165
+ * @returns the absolute path of Windows PowerShell, so that it does not depend on the `PATH`,
166
+ * or just its name if the Windows directory is unknown.
167
+ */
168
+ protected winGetPowerShellPath(): string {
169
+ const systemRoot = process.env.SystemRoot;
170
+ if (!systemRoot) {
171
+ return 'powershell.exe';
172
+ }
173
+ // `v1.0` is not the version: all versions of Windows PowerShell, up to the final 5.1, are installed
174
+ // in this directory. PowerShell 7 and later are a separate, optional installation (`pwsh.exe`).
175
+ return path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
176
+ }
177
+
50
178
  protected unixTerminateProcessTree(ppid: number): void {
51
179
  for (const pid of this.unixGetChildrenRecursive(ppid)) {
52
180
  // Prevent killing the current process:
@@ -63,6 +191,16 @@ export class ProcessUtils {
63
191
  this.unixKill(ppid);
64
192
  }
65
193
 
194
+ protected async unixTerminateChildProcessTrees(ppid: number): Promise<void> {
195
+ const { stdout } = await this.execFile('ps', ['ax', '-o', 'ppid=,pid=']);
196
+ for (const pid of this.unixParseChildrenRecursive(stdout, ppid)) {
197
+ // Prevent killing the current process:
198
+ if (pid !== process.pid) {
199
+ this.unixKill(pid);
200
+ }
201
+ }
202
+ }
203
+
66
204
  protected unixKill(pid: number): void {
67
205
  try {
68
206
  process.kill(pid);
@@ -82,9 +220,17 @@ export class ProcessUtils {
82
220
 
83
221
  protected unixGetChildrenRecursive(ppid: number): Set<number> {
84
222
  const { stdout } = this.spawnSync('ps', ['ax', '-o', 'ppid=,pid=']);
223
+ return this.unixParseChildrenRecursive(stdout, ppid);
224
+ }
225
+
226
+ /**
227
+ * @param psOutput the output of `ps ax -o ppid=,pid=`
228
+ * @returns the PIDs of all of the descendants of the given process
229
+ */
230
+ protected unixParseChildrenRecursive(psOutput: string, ppid: number): Set<number> {
85
231
  const pids = new Set<number>([ppid]);
86
232
  const matcher = /(\d+)\s+(\d+)/;
87
- const psList = stdout
233
+ const psList = psOutput
88
234
  .trim()
89
235
  .split('\n')
90
236
  .map(line => {
@@ -108,6 +254,23 @@ export class ProcessUtils {
108
254
  return pids;
109
255
  }
110
256
 
257
+ /**
258
+ * Runs the given executable without blocking the event loop.
259
+ *
260
+ * @throws if the executable cannot be run or exits with a non-zero code, or on timeout
261
+ */
262
+ protected execFile(file: string, argv: string[], options?: cp.ExecFileOptions): Promise<{ stdout: string, stderr: string }> {
263
+ return new Promise((resolve, reject) => {
264
+ cp.execFile(file, argv, { ...options, encoding: 'utf8' }, (error, stdout, stderr) => {
265
+ if (error) {
266
+ reject(error);
267
+ } else {
268
+ resolve({ stdout, stderr });
269
+ }
270
+ });
271
+ });
272
+ }
273
+
111
274
  protected spawnSync(file: string, argv: string[], options?: cp.SpawnSyncOptions): cp.SpawnSyncReturns<string> {
112
275
  const result = cp.spawnSync(file, argv, { ...options, encoding: 'utf8' });
113
276
  if (result.error) {
@@ -0,0 +1,75 @@
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
+ /**
18
+ * Script for tests: creates a `BackendApplication`, which installs its process handlers, starts a
19
+ * child process, prints the PID of the child and exits with code {@link EXITING_BACKEND_EXIT_CODE}.
20
+ * The `exit` handler of the `BackendApplication` then terminates the process tree.
21
+ * Set {@link EXITING_BACKEND_NO_POWERSHELL} to make the listing of the children of the process fail.
22
+ * Set {@link EXITING_BACKEND_GRACEFUL} to shut down as on `SIGTERM` instead, which exits with code 1.
23
+ */
24
+
25
+ import 'reflect-metadata';
26
+ import * as cp from 'child_process';
27
+ import { Container } from 'inversify';
28
+ import { bindContributionProvider, ILogger, Stopwatch } from '../../common';
29
+ import { MockLogger } from '../../common/test/mock-logger';
30
+ import {
31
+ BackendApplication, BackendApplicationCliContribution, BackendApplicationContribution, EarlyExpressMiddleware, RootContainer
32
+ } from '../backend-application';
33
+ import { NodeStopwatch } from '../performance/node-stopwatch';
34
+ import { ProcessUtils } from '../process-utils';
35
+
36
+ export const EXITING_BACKEND_EXIT_CODE = 3;
37
+
38
+ /**
39
+ * Environment variable that makes PowerShell unrunnable for the {@link ProcessUtils} of the script.
40
+ */
41
+ export const EXITING_BACKEND_NO_POWERSHELL = 'THEIA_TEST_EXITING_BACKEND_NO_POWERSHELL';
42
+
43
+ /**
44
+ * Environment variable that makes the script shut down gracefully, as on `SIGTERM`, rather than exit abruptly.
45
+ */
46
+ export const EXITING_BACKEND_GRACEFUL = 'THEIA_TEST_EXITING_BACKEND_GRACEFUL';
47
+
48
+ class NoPowerShellProcessUtils extends ProcessUtils {
49
+ protected override winGetPowerShellPath(): string {
50
+ return 'C:\\does-not-exist\\powershell.exe';
51
+ }
52
+ }
53
+
54
+ if (require.main === module) {
55
+ const container = new Container();
56
+ container.bind(RootContainer).toConstantValue(container);
57
+ container.bind(ILogger).to(MockLogger).inSingletonScope();
58
+ container.bind(Stopwatch).to(NodeStopwatch).inSingletonScope();
59
+ container.bind(ProcessUtils).to(process.env[EXITING_BACKEND_NO_POWERSHELL] ? NoPowerShellProcessUtils : ProcessUtils).inSingletonScope();
60
+ container.bind(BackendApplicationCliContribution).toSelf().inSingletonScope();
61
+ container.bind(EarlyExpressMiddleware).toSelf().inSingletonScope();
62
+ bindContributionProvider(container, BackendApplicationContribution);
63
+ container.bind(BackendApplication).toSelf().inSingletonScope();
64
+ container.get(BackendApplication);
65
+
66
+ const child = cp.spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' });
67
+ child.on('spawn', () => process.stdout.write(`${child.pid}\n`, () => {
68
+ if (process.env[EXITING_BACKEND_GRACEFUL]) {
69
+ // Signals cannot be sent to a process on Windows, so invoke the handler of the `BackendApplication` directly.
70
+ process.emit('SIGTERM', 'SIGTERM');
71
+ } else {
72
+ process.exit(EXITING_BACKEND_EXIT_CODE);
73
+ }
74
+ }));
75
+ }