@theia/core 1.77.0 → 1.78.0-next.19

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 (180) hide show
  1. package/lib/browser/catalog.json +208 -32
  2. package/lib/browser/encoding-registry.js +1 -1
  3. package/lib/browser/encoding-registry.js.map +1 -1
  4. package/lib/browser/encoding-registry.spec.d.ts +2 -0
  5. package/lib/browser/encoding-registry.spec.d.ts.map +1 -0
  6. package/lib/browser/encoding-registry.spec.js +43 -0
  7. package/lib/browser/encoding-registry.spec.js.map +1 -0
  8. package/lib/browser/messaging/service-connection-provider.d.ts.map +1 -1
  9. package/lib/browser/messaging/service-connection-provider.js +9 -1
  10. package/lib/browser/messaging/service-connection-provider.js.map +1 -1
  11. package/lib/browser/messaging/service-connection-provider.spec.d.ts +2 -0
  12. package/lib/browser/messaging/service-connection-provider.spec.d.ts.map +1 -0
  13. package/lib/browser/messaging/service-connection-provider.spec.js +76 -0
  14. package/lib/browser/messaging/service-connection-provider.spec.js.map +1 -0
  15. package/lib/browser/shell/tab-bars.d.ts +7 -0
  16. package/lib/browser/shell/tab-bars.d.ts.map +1 -1
  17. package/lib/browser/shell/tab-bars.js +25 -11
  18. package/lib/browser/shell/tab-bars.js.map +1 -1
  19. package/lib/browser/shell/tab-bars.spec.js +20 -0
  20. package/lib/browser/shell/tab-bars.spec.js.map +1 -1
  21. package/lib/common/core-preferences.d.ts +1 -0
  22. package/lib/common/core-preferences.d.ts.map +1 -1
  23. package/lib/common/core-preferences.js +11 -1
  24. package/lib/common/core-preferences.js.map +1 -1
  25. package/lib/common/messaging/handler.d.ts +11 -0
  26. package/lib/common/messaging/handler.d.ts.map +1 -1
  27. package/lib/common/messaging/proxy-factory.d.ts +8 -1
  28. package/lib/common/messaging/proxy-factory.d.ts.map +1 -1
  29. package/lib/common/messaging/proxy-factory.js +4 -2
  30. package/lib/common/messaging/proxy-factory.js.map +1 -1
  31. package/lib/common/messaging/proxy-factory.spec.js +16 -1
  32. package/lib/common/messaging/proxy-factory.spec.js.map +1 -1
  33. package/lib/common/shell-environment.d.ts +61 -0
  34. package/lib/common/shell-environment.d.ts.map +1 -0
  35. package/lib/common/shell-environment.js +29 -0
  36. package/lib/common/shell-environment.js.map +1 -0
  37. package/lib/electron-browser/shell-environment/electron-shell-environment-contribution.d.ts +20 -0
  38. package/lib/electron-browser/shell-environment/electron-shell-environment-contribution.d.ts.map +1 -0
  39. package/lib/electron-browser/shell-environment/electron-shell-environment-contribution.js +72 -0
  40. package/lib/electron-browser/shell-environment/electron-shell-environment-contribution.js.map +1 -0
  41. package/lib/electron-browser/shell-environment/electron-shell-environment-contribution.spec.d.ts +2 -0
  42. package/lib/electron-browser/shell-environment/electron-shell-environment-contribution.spec.d.ts.map +1 -0
  43. package/lib/electron-browser/shell-environment/electron-shell-environment-contribution.spec.js +86 -0
  44. package/lib/electron-browser/shell-environment/electron-shell-environment-contribution.spec.js.map +1 -0
  45. package/lib/electron-browser/shell-environment/electron-shell-environment-module.d.ts +4 -0
  46. package/lib/electron-browser/shell-environment/electron-shell-environment-module.d.ts.map +1 -0
  47. package/lib/electron-browser/shell-environment/electron-shell-environment-module.js +26 -0
  48. package/lib/electron-browser/shell-environment/electron-shell-environment-module.js.map +1 -0
  49. package/lib/electron-main/electron-main-application.d.ts.map +1 -1
  50. package/lib/electron-main/electron-main-application.js +12 -4
  51. package/lib/electron-main/electron-main-application.js.map +1 -1
  52. package/lib/electron-node/keyboard/electron-backend-keyboard-module.d.ts.map +1 -1
  53. package/lib/electron-node/keyboard/electron-backend-keyboard-module.js +1 -1
  54. package/lib/electron-node/keyboard/electron-backend-keyboard-module.js.map +1 -1
  55. package/lib/electron-node/request/electron-backend-request-service.d.ts +4 -1
  56. package/lib/electron-node/request/electron-backend-request-service.d.ts.map +1 -1
  57. package/lib/electron-node/request/electron-backend-request-service.js +56 -13
  58. package/lib/electron-node/request/electron-backend-request-service.js.map +1 -1
  59. package/lib/node/backend-application-module.d.ts.map +1 -1
  60. package/lib/node/backend-application-module.js +13 -5
  61. package/lib/node/backend-application-module.js.map +1 -1
  62. package/lib/node/env-variables/env-variables-server.d.ts +13 -3
  63. package/lib/node/env-variables/env-variables-server.d.ts.map +1 -1
  64. package/lib/node/env-variables/env-variables-server.js +21 -14
  65. package/lib/node/env-variables/env-variables-server.js.map +1 -1
  66. package/lib/node/env-variables/env-variables-server.spec.d.ts +2 -0
  67. package/lib/node/env-variables/env-variables-server.spec.d.ts.map +1 -0
  68. package/lib/node/env-variables/env-variables-server.spec.js +83 -0
  69. package/lib/node/env-variables/env-variables-server.spec.js.map +1 -0
  70. package/lib/node/i18n/i18n-backend-module.js +2 -2
  71. package/lib/node/i18n/i18n-backend-module.js.map +1 -1
  72. package/lib/node/index.d.ts +1 -0
  73. package/lib/node/index.d.ts.map +1 -1
  74. package/lib/node/index.js +1 -0
  75. package/lib/node/index.js.map +1 -1
  76. package/lib/node/logger-backend-module.js +1 -1
  77. package/lib/node/logger-backend-module.js.map +1 -1
  78. package/lib/node/messaging/connection-container-module.d.ts +11 -2
  79. package/lib/node/messaging/connection-container-module.d.ts.map +1 -1
  80. package/lib/node/messaging/connection-container-module.js +13 -2
  81. package/lib/node/messaging/connection-container-module.js.map +1 -1
  82. package/lib/node/messaging/connection-container-module.spec.d.ts +2 -0
  83. package/lib/node/messaging/connection-container-module.spec.d.ts.map +1 -0
  84. package/lib/node/messaging/connection-container-module.spec.js +37 -0
  85. package/lib/node/messaging/connection-container-module.spec.js.map +1 -0
  86. package/lib/node/messaging/default-messaging-service.d.ts +33 -4
  87. package/lib/node/messaging/default-messaging-service.d.ts.map +1 -1
  88. package/lib/node/messaging/default-messaging-service.js +52 -10
  89. package/lib/node/messaging/default-messaging-service.js.map +1 -1
  90. package/lib/node/messaging/gated-channel-multiplexer.d.ts +20 -0
  91. package/lib/node/messaging/gated-channel-multiplexer.d.ts.map +1 -0
  92. package/lib/node/messaging/gated-channel-multiplexer.js +50 -0
  93. package/lib/node/messaging/gated-channel-multiplexer.js.map +1 -0
  94. package/lib/node/messaging/gated-channel-multiplexer.spec.d.ts +2 -0
  95. package/lib/node/messaging/gated-channel-multiplexer.spec.d.ts.map +1 -0
  96. package/lib/node/messaging/gated-channel-multiplexer.spec.js +74 -0
  97. package/lib/node/messaging/gated-channel-multiplexer.spec.js.map +1 -0
  98. package/lib/node/messaging/index.d.ts +1 -0
  99. package/lib/node/messaging/index.d.ts.map +1 -1
  100. package/lib/node/messaging/index.js +1 -0
  101. package/lib/node/messaging/index.js.map +1 -1
  102. package/lib/node/messaging/messaging-backend-module.js +1 -1
  103. package/lib/node/messaging/messaging-backend-module.js.map +1 -1
  104. package/lib/node/messaging/messaging-service.d.ts +5 -1
  105. package/lib/node/messaging/messaging-service.d.ts.map +1 -1
  106. package/lib/node/messaging/messaging-service.js.map +1 -1
  107. package/lib/node/messaging/test/default-messaging-service.spec.js +82 -2
  108. package/lib/node/messaging/test/default-messaging-service.spec.js.map +1 -1
  109. package/lib/node/messaging/websocket-frontend-connection-service.d.ts +1 -0
  110. package/lib/node/messaging/websocket-frontend-connection-service.d.ts.map +1 -1
  111. package/lib/node/messaging/websocket-frontend-connection-service.js +8 -0
  112. package/lib/node/messaging/websocket-frontend-connection-service.js.map +1 -1
  113. package/lib/node/messaging/websocket-frontend-connection-service.spec.d.ts +2 -0
  114. package/lib/node/messaging/websocket-frontend-connection-service.spec.d.ts.map +1 -0
  115. package/lib/node/messaging/websocket-frontend-connection-service.spec.js +141 -0
  116. package/lib/node/messaging/websocket-frontend-connection-service.spec.js.map +1 -0
  117. package/lib/node/performance/measurement-backend-bindings.js +1 -1
  118. package/lib/node/performance/measurement-backend-bindings.js.map +1 -1
  119. package/lib/node/process-utils.d.ts +125 -2
  120. package/lib/node/process-utils.d.ts.map +1 -1
  121. package/lib/node/process-utils.js +297 -25
  122. package/lib/node/process-utils.js.map +1 -1
  123. package/lib/node/process-utils.slow-spec.js +78 -3
  124. package/lib/node/process-utils.slow-spec.js.map +1 -1
  125. package/lib/node/process-utils.spec.js +237 -2
  126. package/lib/node/process-utils.spec.js.map +1 -1
  127. package/lib/node/shell-environment.d.ts +107 -0
  128. package/lib/node/shell-environment.d.ts.map +1 -0
  129. package/lib/node/shell-environment.js +396 -0
  130. package/lib/node/shell-environment.js.map +1 -0
  131. package/lib/node/shell-environment.spec.d.ts +2 -0
  132. package/lib/node/shell-environment.spec.d.ts.map +1 -0
  133. package/lib/node/shell-environment.spec.js +348 -0
  134. package/lib/node/shell-environment.spec.js.map +1 -0
  135. package/lib/node/test/exiting-backend.d.ts +5 -0
  136. package/lib/node/test/exiting-backend.d.ts.map +1 -1
  137. package/lib/node/test/exiting-backend.js +16 -3
  138. package/lib/node/test/exiting-backend.js.map +1 -1
  139. package/package.json +7 -4
  140. package/src/browser/encoding-registry.spec.ts +48 -0
  141. package/src/browser/encoding-registry.ts +1 -1
  142. package/src/browser/messaging/service-connection-provider.spec.ts +88 -0
  143. package/src/browser/messaging/service-connection-provider.ts +9 -2
  144. package/src/browser/shell/tab-bars.spec.ts +22 -0
  145. package/src/browser/shell/tab-bars.ts +25 -12
  146. package/src/common/core-preferences.ts +12 -1
  147. package/src/common/messaging/handler.ts +11 -0
  148. package/src/common/messaging/proxy-factory.spec.ts +17 -1
  149. package/src/common/messaging/proxy-factory.ts +16 -2
  150. package/src/common/shell-environment.ts +81 -0
  151. package/src/electron-browser/shell-environment/electron-shell-environment-contribution.spec.ts +95 -0
  152. package/src/electron-browser/shell-environment/electron-shell-environment-contribution.ts +72 -0
  153. package/src/electron-browser/shell-environment/electron-shell-environment-module.ts +29 -0
  154. package/src/electron-main/electron-main-application.ts +15 -4
  155. package/src/electron-node/keyboard/electron-backend-keyboard-module.ts +2 -1
  156. package/src/electron-node/request/electron-backend-request-service.ts +59 -11
  157. package/src/node/backend-application-module.ts +19 -5
  158. package/src/node/env-variables/env-variables-server.spec.ts +93 -0
  159. package/src/node/env-variables/env-variables-server.ts +22 -14
  160. package/src/node/i18n/i18n-backend-module.ts +2 -2
  161. package/src/node/index.ts +1 -0
  162. package/src/node/logger-backend-module.ts +1 -1
  163. package/src/node/messaging/connection-container-module.spec.ts +39 -0
  164. package/src/node/messaging/connection-container-module.ts +16 -4
  165. package/src/node/messaging/default-messaging-service.ts +64 -10
  166. package/src/node/messaging/gated-channel-multiplexer.spec.ts +80 -0
  167. package/src/node/messaging/gated-channel-multiplexer.ts +52 -0
  168. package/src/node/messaging/index.ts +1 -0
  169. package/src/node/messaging/messaging-backend-module.ts +1 -1
  170. package/src/node/messaging/messaging-service.ts +5 -1
  171. package/src/node/messaging/test/default-messaging-service.spec.ts +89 -2
  172. package/src/node/messaging/websocket-frontend-connection-service.spec.ts +158 -0
  173. package/src/node/messaging/websocket-frontend-connection-service.ts +9 -0
  174. package/src/node/performance/measurement-backend-bindings.ts +1 -1
  175. package/src/node/process-utils.slow-spec.ts +90 -3
  176. package/src/node/process-utils.spec.ts +268 -3
  177. package/src/node/process-utils.ts +342 -24
  178. package/src/node/shell-environment.spec.ts +388 -0
  179. package/src/node/shell-environment.ts +406 -0
  180. package/src/node/test/exiting-backend.ts +17 -3
@@ -0,0 +1,80 @@
1
+ // *****************************************************************************
2
+ // Copyright (C) 2026 STMicroelectronics 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 { ChannelMultiplexer } from '../../common/message-rpc/channel.js';
19
+ import { ChannelPipe } from '../../common/message-rpc/channel.spec.js';
20
+ import { Deferred, wait } from '../../common/promise-util.js';
21
+ import { GatedChannelMultiplexer } from './gated-channel-multiplexer.js';
22
+
23
+ describe('GatedChannelMultiplexer', () => {
24
+
25
+ const setup = (): { pipe: ChannelPipe, gate: Deferred<void>, frontend: ChannelMultiplexer, backend: GatedChannelMultiplexer, opened: string[] } => {
26
+ const pipe = new ChannelPipe();
27
+ const gate = new Deferred<void>();
28
+ const frontend = new ChannelMultiplexer(pipe.left);
29
+ const backend = new GatedChannelMultiplexer(pipe.right, id => id.startsWith('/held') ? gate.promise : undefined);
30
+ const opened: string[] = [];
31
+ backend.onDidOpenChannel(({ id }) => opened.push(id));
32
+ return { pipe, gate, frontend, backend, opened };
33
+ };
34
+
35
+ it('acknowledges a held channel only once the gate has opened', async () => {
36
+ const { gate, frontend, opened } = setup();
37
+ let acknowledged = false;
38
+ const open = frontend.open('/held/task').then(channel => {
39
+ acknowledged = true;
40
+ return channel;
41
+ });
42
+ await wait(0);
43
+ expect(acknowledged).to.be.false;
44
+ expect(opened).to.be.empty;
45
+ gate.resolve();
46
+ await open;
47
+ expect(opened).to.deep.equal(['/held/task']);
48
+ });
49
+
50
+ it('acknowledges a channel that the gate lets through at once', async () => {
51
+ const { frontend, opened } = setup();
52
+ await frontend.open('/services/filesystem');
53
+ expect(opened).to.deep.equal(['/services/filesystem']);
54
+ });
55
+
56
+ it('delivers a message sent right after the acknowledgement to the handler attached when the channel opened', async () => {
57
+ const { gate, frontend, backend } = setup();
58
+ const received: string[] = [];
59
+ backend.onDidOpenChannel(event => event.channel.onMessage(buffer => received.push(buffer().readString())));
60
+ const open = frontend.open('/held/task');
61
+ gate.resolve();
62
+ const channel = await open;
63
+ channel.getWriteBuffer().writeString('hello').commit();
64
+ expect(received).to.deep.equal(['hello']);
65
+ });
66
+
67
+ it('does not open a held channel once the connection has closed', async () => {
68
+ const { pipe, gate, frontend, opened } = setup();
69
+ let rejected: unknown;
70
+ const open = frontend.open('/held/task').catch(error => { rejected = error; });
71
+ // the socket closes: each side learns of it through its own channel
72
+ pipe.right.onCloseEmitter.fire({ reason: 'The frontend went away' });
73
+ pipe.left.onCloseEmitter.fire({ reason: 'The backend went away' });
74
+ gate.resolve();
75
+ await wait(0);
76
+ expect(opened).to.be.empty;
77
+ await open;
78
+ expect(rejected).to.be.instanceOf(Error);
79
+ });
80
+ });
@@ -0,0 +1,52 @@
1
+ // *****************************************************************************
2
+ // Copyright (C) 2026 STMicroelectronics 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 { Channel, ChannelMultiplexer } from '../../common/message-rpc/channel.js';
18
+
19
+ /**
20
+ * A channel multiplexer that can defer the acknowledgement of a channel that the other side opens until a gate opens.
21
+ * The other side sends nothing on a channel before the acknowledgement, so nothing is lost while the channel is held.
22
+ *
23
+ * The backend holds the service channels of a frontend until the `PATH` of the user's login shell has been
24
+ * applied to `process.env`, so that the services find the user's tools,
25
+ * see `ShellEnvironmentServer` and `ConnectionHandler.independentOfShellEnvironment`.
26
+ */
27
+ export class GatedChannelMultiplexer extends ChannelMultiplexer {
28
+
29
+ /**
30
+ * @param underlyingChannel the channel on which the channels are multiplexed
31
+ * @param gate tells how long to hold the channel of a given id before acknowledging it,
32
+ * or `undefined` to acknowledge it at once. The channel is acknowledged whether the promise resolves or rejects.
33
+ */
34
+ constructor(underlyingChannel: Channel, protected readonly gate: (id: string) => Promise<void> | undefined) {
35
+ super(underlyingChannel);
36
+ }
37
+
38
+ protected override handleOpen(id: string): void {
39
+ const hold = this.gate(id);
40
+ if (!hold) {
41
+ super.handleOpen(id);
42
+ return;
43
+ }
44
+ const open = (): void => {
45
+ // the connection may have been closed while the channel was held
46
+ if (!this.toDispose.disposed) {
47
+ super.handleOpen(id);
48
+ }
49
+ };
50
+ hold.then(open, open);
51
+ }
52
+ }
@@ -18,3 +18,4 @@ export * from './messaging-service.js';
18
18
  export * from './ipc-connection-provider.js';
19
19
  export * from './ipc-channel.js';
20
20
  export * from './websocket-frontend-connection-service.js';
21
+ export * from './gated-channel-multiplexer.js';
@@ -51,6 +51,6 @@ export const messagingBackendModule = new ContainerModule(bind => {
51
51
  markForClose: (channelId: string) => {
52
52
  connectionService.markForClose(channelId);
53
53
  }
54
- }));
54
+ }), { independentOfShellEnvironment: true });
55
55
  }).inSingletonScope();
56
56
  });
@@ -21,7 +21,7 @@ export interface MessagingService {
21
21
  * Accept a web socket channel on the given path.
22
22
  * A path supports the route syntax: https://github.com/rcs/route-parser#what-can-i-use-in-my-routes.
23
23
  */
24
- registerChannelHandler(path: string, handler: (params: MessagingService.PathParams, channel: Channel) => void): void;
24
+ registerChannelHandler(path: string, handler: (params: MessagingService.PathParams, channel: Channel) => void, options?: MessagingService.ChannelHandlerOptions): void;
25
25
  /**
26
26
  * Accept a web socket connection on the given path.
27
27
  * A path supports the route syntax: https://github.com/rcs/route-parser#what-can-i-use-in-my-routes.
@@ -39,6 +39,10 @@ export namespace MessagingService {
39
39
  export interface PathParams {
40
40
  [name: string]: string
41
41
  }
42
+ export interface ChannelHandlerOptions {
43
+ /** See `ConnectionHandler.independentOfShellEnvironment`. The default is `false`. */
44
+ independentOfShellEnvironment?: boolean;
45
+ }
42
46
  export const Contribution = Symbol('MessagingService.Contribution');
43
47
  export interface Contribution {
44
48
  configure(service: MessagingService): void;
@@ -17,13 +17,16 @@
17
17
  import { expect } from 'chai';
18
18
  import { Container, injectable, preDestroy } from 'inversify';
19
19
  import { ConnectionHandler, bindContributionProvider, servicesPath, ILogger } from '../../../common/index.js';
20
- import { BasicChannel, Channel } from '../../../common/message-rpc/channel.js';
20
+ import { BasicChannel, Channel, ChannelMultiplexer } from '../../../common/message-rpc/channel.js';
21
21
  import { Uint8ArrayWriteBuffer } from '../../../common/message-rpc/uint8-array-message-buffer.js';
22
22
  import { ConnectionContainerModule } from '../connection-container-module.js';
23
- import { DefaultMessagingService, MessagingContainer } from '../default-messaging-service.js';
23
+ import { ConnectionHandlers, DefaultMessagingService, MessagingContainer } from '../default-messaging-service.js';
24
24
  import { FrontendConnectionService } from '../frontend-connection-service.js';
25
25
  import { MessagingService } from '../messaging-service.js';
26
26
  import { MockLogger } from '../../../common/test/mock-logger.js';
27
+ import { ChannelPipe } from '../../../common/message-rpc/channel.spec.js';
28
+ import { Deferred } from '../../../common/promise-util.js';
29
+ import { ShellEnvironmentResolution, ShellEnvironmentServer } from '../../../common/shell-environment.js';
27
30
 
28
31
  describe('DefaultMessagingService', () => {
29
32
 
@@ -65,6 +68,10 @@ describe('DefaultMessagingService', () => {
65
68
  };
66
69
  container.bind(FrontendConnectionService).toConstantValue(frontendConnectionService);
67
70
  container.bind(ILogger).to(MockLogger).inSingletonScope();
71
+ container.bind(ShellEnvironmentServer).toConstantValue(<ShellEnvironmentServer>{
72
+ whenResolved: async () => ({ status: 'skipped', reason: 'test' }),
73
+ setResolutionTimeout: async () => { }
74
+ });
68
75
 
69
76
  const messagingService = container.get(DefaultMessagingService);
70
77
  messagingService.initialize();
@@ -84,4 +91,84 @@ describe('DefaultMessagingService', () => {
84
91
 
85
92
  });
86
93
 
94
+ describe('when a frontend opens service channels', () => {
95
+
96
+ let resolution: Deferred<ShellEnvironmentResolution>;
97
+ let connections: ((params: MessagingService.PathParams, mainChannel: Channel) => void)[];
98
+ let connected: string[];
99
+
100
+ const setup = (): DefaultMessagingService => {
101
+ resolution = new Deferred();
102
+ connections = [];
103
+ connected = [];
104
+ const container = new Container({ defaultScope: 'Singleton' });
105
+ container.bind(ILogger).to(MockLogger);
106
+ container.bind(MessagingContainer).toConstantValue(container);
107
+ container.bind(FrontendConnectionService).toConstantValue(<FrontendConnectionService>{
108
+ registerConnectionHandler: (path, callback) => { connections.push(callback); }
109
+ });
110
+ bindContributionProvider(container, ConnectionContainerModule);
111
+ bindContributionProvider(container, MessagingService.Contribution);
112
+ container.bind(ShellEnvironmentServer).toConstantValue(<ShellEnvironmentServer>{
113
+ whenResolved: () => resolution.promise,
114
+ setResolutionTimeout: async () => { }
115
+ });
116
+ const handler = (path: string, independentOfShellEnvironment?: boolean): ConnectionHandler => ({
117
+ path, independentOfShellEnvironment, onConnection: () => { connected.push(path); }
118
+ });
119
+ container.bind(ConnectionHandler).toConstantValue(handler('/services/task'));
120
+ container.bind(ConnectionHandler).toConstantValue(handler('/services/filesystem', true));
121
+ container.bind(DefaultMessagingService).toSelf();
122
+ const service = container.get(DefaultMessagingService);
123
+ service.initialize();
124
+ return service;
125
+ };
126
+
127
+ it('holds the services that depend on the shell environment and lets the others through', async () => {
128
+ const service = setup();
129
+ service.registerChannelHandler('/services/terminals/:id', ({ id }) => { connected.push(`/services/terminals/${id}`); });
130
+ service.registerChannelHandler('/services/keyboard', () => { connected.push('/services/keyboard'); }, { independentOfShellEnvironment: true });
131
+ expect(connections).to.have.lengthOf(1);
132
+ const pipe = new ChannelPipe();
133
+ connections[0]({}, pipe.right);
134
+ const frontend = new ChannelMultiplexer(pipe.left);
135
+ const held = Promise.all([frontend.open('/services/task'), frontend.open('/services/terminals/1')]);
136
+ await Promise.all([frontend.open('/services/filesystem'), frontend.open('/services/keyboard')]);
137
+ expect(connected).to.have.members(['/services/filesystem', '/services/keyboard']);
138
+ resolution.resolve({ status: 'applied' });
139
+ await held;
140
+ expect(connected).to.have.members(['/services/filesystem', '/services/keyboard', '/services/task', '/services/terminals/1']);
141
+ });
142
+ });
143
+ });
144
+
145
+ describe('ConnectionHandlers', () => {
146
+
147
+ it('holds every path until the shell environment is resolved unless its handler is declared independent of it', () => {
148
+ const handlers = new ConnectionHandlers<string>();
149
+ handlers.push('/services/terminals/:id', () => { });
150
+ handlers.push('/services/filesystem', () => { }, { independentOfShellEnvironment: true });
151
+ expect(handlers.isIndependentOfShellEnvironment('/services/terminals/42')).to.be.false;
152
+ expect(handlers.isIndependentOfShellEnvironment('/services/filesystem')).to.be.true;
153
+ expect(handlers.isIndependentOfShellEnvironment('/services/unknown')).to.be.false;
154
+ });
155
+
156
+ it('consults the parent handlers', () => {
157
+ const parent = new ConnectionHandlers<string>();
158
+ parent.push('/services/os', () => { }, { independentOfShellEnvironment: true });
159
+ const child = new ConnectionHandlers<string>(parent);
160
+ child.push('/services/task', () => { });
161
+ expect(child.isIndependentOfShellEnvironment('/services/os')).to.be.true;
162
+ expect(child.isIndependentOfShellEnvironment('/services/task')).to.be.false;
163
+ });
164
+
165
+ it('does not invoke the handlers when asked about their independence', () => {
166
+ let invoked = 0;
167
+ const handlers = new ConnectionHandlers<string>();
168
+ handlers.push('/services/:name', () => { invoked++; }, { independentOfShellEnvironment: true });
169
+ expect(handlers.isIndependentOfShellEnvironment('/services/anything')).to.be.true;
170
+ expect(invoked).to.equal(0);
171
+ expect(handlers.route('/services/anything', 'connection')).to.equal('/services/anything');
172
+ expect(invoked).to.equal(1);
173
+ });
87
174
  });
@@ -0,0 +1,158 @@
1
+ // *****************************************************************************
2
+ // Copyright (C) 2026 CodeSignal 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 http from 'http';
19
+ import { AddressInfo } from 'net';
20
+ import { Container } from 'inversify';
21
+ import { Server, Socket as ServerSocket } from 'socket.io';
22
+ import { io, Socket as ClientSocket } from 'socket.io-client';
23
+ import { ILogger } from '../../common/index.js';
24
+ import { Channel } from '../../common/message-rpc/channel.js';
25
+ import { Uint8ArrayReadBuffer, Uint8ArrayWriteBuffer } from '../../common/message-rpc/uint8-array-message-buffer.js';
26
+ import { ConnectionManagementMessages } from '../../common/messaging/connection-management.js';
27
+ import { SocketWriteBuffer } from '../../common/messaging/socket-write-buffer.js';
28
+ import { timeout } from '../../common/promise-util.js';
29
+ import { MockLogger } from '../../common/test/mock-logger.js';
30
+ import { MessagingContainer } from './default-messaging-service.js';
31
+ import { WebsocketEndpoint } from './websocket-endpoint.js';
32
+ import { ReconnectableSocketChannel, WebsocketFrontendConnectionService } from './websocket-frontend-connection-service.js';
33
+
34
+ const FRONTEND_ID = 'frontend-1';
35
+ const CLOSE_TIMEOUT_MS = 300;
36
+
37
+ class TestConnectionService extends WebsocketFrontendConnectionService {
38
+ readonly channels: Channel[] = [];
39
+
40
+ accept(socket: ServerSocket): void {
41
+ this.handleConnection(socket, channel => this.channels.push(channel));
42
+ }
43
+ }
44
+
45
+ function encode(text: string): Uint8Array {
46
+ const buffer = new Uint8ArrayWriteBuffer();
47
+ buffer.writeString(text);
48
+ return buffer.getCurrentContents();
49
+ }
50
+
51
+ describe('WebsocketFrontendConnectionService', () => {
52
+ let httpServer: http.Server;
53
+ let ioServer: Server;
54
+ let url: string;
55
+ let service: TestConnectionService;
56
+ let serverSockets: ServerSocket[];
57
+ let clients: ClientSocket[];
58
+ let savedTimeout: string | undefined;
59
+
60
+ beforeEach(async () => {
61
+ savedTimeout = process.env.FRONTEND_CONNECTION_TIMEOUT;
62
+ process.env.FRONTEND_CONNECTION_TIMEOUT = String(CLOSE_TIMEOUT_MS);
63
+ const container = new Container();
64
+ container.bind(MessagingContainer).toConstantValue(container);
65
+ container.bind(ILogger).to(MockLogger);
66
+ container.bind(WebsocketEndpoint).toConstantValue(new WebsocketEndpoint());
67
+ container.bind(SocketWriteBuffer).toSelf();
68
+ container.bind(ReconnectableSocketChannel).toSelf();
69
+ container.bind(TestConnectionService).toSelf().inSingletonScope();
70
+ service = container.get(TestConnectionService);
71
+
72
+ serverSockets = [];
73
+ clients = [];
74
+ httpServer = http.createServer();
75
+ ioServer = new Server(httpServer);
76
+ ioServer.on('connection', socket => {
77
+ serverSockets.push(socket);
78
+ service.accept(socket);
79
+ });
80
+ await new Promise<void>(resolve => httpServer.listen(0, '127.0.0.1', resolve));
81
+ url = `http://127.0.0.1:${(httpServer.address() as AddressInfo).port}`;
82
+ });
83
+
84
+ afterEach(async () => {
85
+ clients.forEach(client => client.disconnect());
86
+ await timeout(CLOSE_TIMEOUT_MS * 2);
87
+ await new Promise<void>(resolve => ioServer.close(() => resolve()));
88
+ if (savedTimeout === undefined) {
89
+ delete process.env.FRONTEND_CONNECTION_TIMEOUT;
90
+ } else {
91
+ process.env.FRONTEND_CONNECTION_TIMEOUT = savedTimeout;
92
+ }
93
+ });
94
+
95
+ async function connect(message: string): Promise<{ client: ClientSocket, received: string[] }> {
96
+ const client = io(url, { transports: ['websocket'], reconnection: false });
97
+ clients.push(client);
98
+ await new Promise<void>(resolve => client.once('connect', () => resolve()));
99
+ const received: string[] = [];
100
+ client.on('message', (data: Uint8Array) => received.push(new Uint8ArrayReadBuffer(new Uint8Array(data)).readString()));
101
+ const answered = new Promise(resolve => client.once(message, resolve));
102
+ client.emit(message, FRONTEND_ID);
103
+ await answered;
104
+ return { client, received };
105
+ }
106
+
107
+ async function closeServerSide(index: number): Promise<void> {
108
+ const socket = serverSockets[index];
109
+ const closed = new Promise(resolve => socket.once('disconnect', resolve));
110
+ socket.disconnect(true);
111
+ await closed;
112
+ }
113
+
114
+ it("keeps the channel on the new socket when the old socket's disconnect arrives after a reconnect", async () => {
115
+ await connect(ConnectionManagementMessages.INITIAL_CONNECT);
116
+ const channel = service.channels[0];
117
+ let closed = false;
118
+ channel.onClose(() => closed = true);
119
+ const backendReceived: string[] = [];
120
+ channel.onMessage(read => backendReceived.push(read().readString()));
121
+
122
+ const fresh = await connect(ConnectionManagementMessages.RECONNECT);
123
+ await closeServerSide(0);
124
+ channel.getWriteBuffer().writeString('to frontend').commit();
125
+ fresh.client.send(encode('to backend'));
126
+ await timeout(CLOSE_TIMEOUT_MS * 2);
127
+
128
+ expect(fresh.received).to.deep.equal(['to frontend']);
129
+ expect(backendReceived).to.deep.equal(['to backend']);
130
+ expect(closed).to.be.false;
131
+ });
132
+
133
+ it('keeps the connection a front end opened again when its first socket closes later', async () => {
134
+ await connect(ConnectionManagementMessages.INITIAL_CONNECT);
135
+ const again = await connect(ConnectionManagementMessages.INITIAL_CONNECT);
136
+ const channel = service.channels[1];
137
+ let closed = false;
138
+ channel.onClose(() => closed = true);
139
+
140
+ await closeServerSide(0);
141
+ channel.getWriteBuffer().writeString('to frontend').commit();
142
+ await timeout(CLOSE_TIMEOUT_MS * 2);
143
+
144
+ expect(again.received).to.deep.equal(['to frontend']);
145
+ expect(closed).to.be.false;
146
+ });
147
+
148
+ it('closes the channel when its current socket disconnects and the front end does not come back', async () => {
149
+ await connect(ConnectionManagementMessages.INITIAL_CONNECT);
150
+ const channel = service.channels[0];
151
+ const closed = new Promise(resolve => channel.onClose(resolve));
152
+ await connect(ConnectionManagementMessages.RECONNECT);
153
+
154
+ await closeServerSide(1);
155
+
156
+ await closed;
157
+ });
158
+ });
@@ -110,6 +110,11 @@ export class WebsocketFrontendConnectionService implements FrontendConnectionSer
110
110
 
111
111
  handleSocketDisconnect(socket: Socket, channel: ReconnectableSocketChannel, frontEndId: string): void {
112
112
  socket.on('disconnect', evt => {
113
+ if (this.connectionsByFrontend.get(frontEndId) !== channel || !channel.isConnectedTo(socket)) {
114
+ // The front end has moved to another socket since: leave its connection alone.
115
+ this.logger.info(`superseded socket closed for ${frontEndId}`);
116
+ return;
117
+ }
113
118
  this.logger.info('socket closed');
114
119
  channel.disconnect();
115
120
 
@@ -183,6 +188,10 @@ export class ReconnectableSocketChannel extends AbstractChannel {
183
188
  this.socket = undefined;
184
189
  }
185
190
 
191
+ isConnectedTo(socket: Socket): boolean {
192
+ return this.socket === socket;
193
+ }
194
+
186
195
  drainBuffer(): void {
187
196
  this.socketBuffer.drain();
188
197
  }
@@ -27,7 +27,7 @@ export function bindNodeStopwatch(bind: interfaces.Bind): interfaces.BindingWhen
27
27
 
28
28
  export function bindBackendStopwatchServer(bind: interfaces.Bind): interfaces.BindingWhenOnSyntax<unknown> {
29
29
  bind(ConnectionHandler).toDynamicValue(({ container }) =>
30
- new RpcConnectionHandler<never>(stopwatchPath, () => container.get<BackendStopwatch>(BackendStopwatch))
30
+ new RpcConnectionHandler<never>(stopwatchPath, () => container.get<BackendStopwatch>(BackendStopwatch), { independentOfShellEnvironment: true })
31
31
  ).inSingletonScope();
32
32
 
33
33
  bind(DefaultBackendStopwatch).toSelf().inSingletonScope();
@@ -21,7 +21,9 @@ import { Container } from 'inversify';
21
21
  import { ILogger } from '../common/logger.js';
22
22
  import { MockLogger } from '../common/test/mock-logger.js';
23
23
  import { ProcessUtils } from './process-utils.js';
24
- import { EXITING_BACKEND_EXIT_CODE, EXITING_BACKEND_GRACEFUL, EXITING_BACKEND_NO_POWERSHELL } from './test/exiting-backend.js';
24
+ import {
25
+ EXITING_BACKEND_CHILD_IGNORES_SIGTERM, EXITING_BACKEND_EXIT_CODE, EXITING_BACKEND_GRACEFUL, EXITING_BACKEND_NO_POWERSHELL
26
+ } from './test/exiting-backend.js';
25
27
 
26
28
  interface ExitingProcessResult {
27
29
  exitCode: number | null;
@@ -71,8 +73,8 @@ describe('ProcessUtils (real processes)', function (): void {
71
73
  afterEach(() => {
72
74
  // Do not leak processes if a test fails.
73
75
  for (const pid of childPids.splice(0)) {
74
- if (isAlive(pid)) {
75
- process.kill(pid);
76
+ if (Number.isInteger(pid) && isAlive(pid)) {
77
+ process.kill(pid, 'SIGKILL');
76
78
  }
77
79
  }
78
80
  });
@@ -98,6 +100,91 @@ describe('ProcessUtils (real processes)', function (): void {
98
100
  await expectTerminatedTree({ env: { [EXITING_BACKEND_GRACEFUL]: 'true' } }, 1);
99
101
  });
100
102
 
103
+ (process.platform === 'win32' ? it.skip : it)('kills a child of the backend that ignores SIGTERM on graceful shutdown', async () => {
104
+ await expectTerminatedTree({ env: { [EXITING_BACKEND_GRACEFUL]: 'true', [EXITING_BACKEND_CHILD_IGNORES_SIGTERM]: 'true' } }, 1);
105
+ });
106
+
107
+ describe('processes that ignore SIGTERM', () => {
108
+
109
+ // `console.log` would color the PID when `FORCE_COLOR` is set, even though stdout is a pipe.
110
+ const ignoringScript = 'process.on("SIGTERM", () => {}); process.stdout.write(process.pid + "\\n"); setInterval(() => {}, 1000);';
111
+
112
+ function createProcessUtils(): ProcessUtils {
113
+ const container = new Container();
114
+ container.bind(ProcessUtils).toSelf().inSingletonScope();
115
+ container.bind(ILogger).to(MockLogger).inSingletonScope();
116
+ const processUtils = container.get(ProcessUtils);
117
+ (processUtils as unknown as { unixForceKillDelay: number }).unixForceKillDelay = 1000;
118
+ return processUtils;
119
+ }
120
+
121
+ /**
122
+ * Starts a process that runs the given script, which prints the PID of a process that ignores SIGTERM on a line
123
+ * once it is ready.
124
+ */
125
+ async function startProcess(script: string, options: cp.SpawnOptions = {}): Promise<{ pid: number, ignoringPid: number }> {
126
+ const started = cp.spawn(process.execPath, ['-e', script], { ...options, stdio: ['ignore', 'pipe', 'ignore'] });
127
+ childPids.push(started.pid!);
128
+ const ignoringPid = await new Promise<number>((resolve, reject) => {
129
+ let output = '';
130
+ const onData = (data: Buffer): void => {
131
+ output += data;
132
+ const newline = output.indexOf('\n');
133
+ if (newline < 0) {
134
+ return;
135
+ }
136
+ started.stdout!.off('data', onData);
137
+ started.off('exit', onExit);
138
+ const line = output.substring(0, newline).trim();
139
+ if (/^\d+$/.test(line)) {
140
+ resolve(Number.parseInt(line, 10));
141
+ } else {
142
+ reject(new Error(`Expected the PID of the process that ignores SIGTERM, got ${JSON.stringify(output)}`));
143
+ }
144
+ };
145
+ const onExit = (): void => reject(new Error(`Exited before printing the PID of the process that ignores SIGTERM, got ${JSON.stringify(output)}`));
146
+ started.stdout!.on('data', onData);
147
+ started.once('exit', onExit);
148
+ });
149
+ childPids.push(ignoringPid);
150
+ return { pid: started.pid!, ignoringPid };
151
+ }
152
+
153
+ (process.platform === 'win32' ? it.skip : it)('kills a descendant that ignores SIGTERM with SIGKILL', async () => {
154
+ const processUtils = createProcessUtils();
155
+ const { pid, ignoringPid } = await startProcess(`const child = require('child_process').spawn(process.execPath, ['-e', ${JSON.stringify(ignoringScript)}],
156
+ { stdio: ['ignore', 'pipe', 'ignore'] });
157
+ child.stdout.once('data', data => process.stdout.write(data));
158
+ setInterval(() => {}, 1000);`);
159
+
160
+ processUtils.terminateProcessTree(pid);
161
+
162
+ expect(isAlive(ignoringPid), 'the child should survive SIGTERM').to.be.true;
163
+ expect(await isAliveAfterKill(pid), 'the parent should exit on SIGTERM').to.be.false;
164
+ expect(await isAliveAfterKill(ignoringPid), 'the child should be killed with SIGKILL').to.be.false;
165
+ });
166
+
167
+ (process.platform === 'win32' ? it.skip : it)('kills a member of the group of the tree that ignores SIGTERM and was reparented with SIGKILL', async () => {
168
+ const processUtils = createProcessUtils();
169
+ // The group leader's grandchild outlives its parent, so it is no longer a descendant of the leader.
170
+ const { pid, ignoringPid } = await startProcess(`const middle = require('child_process').spawn(process.execPath, ['-e',
171
+ ${JSON.stringify(`const child = require('child_process').spawn(process.execPath, ['-e', ${JSON.stringify(ignoringScript)}],
172
+ { stdio: ['ignore', 'pipe', 'ignore'] });
173
+ child.stdout.once('data', data => { process.stdout.write(data); process.exit(); });`)}],
174
+ { stdio: ['ignore', 'pipe', 'ignore'] });
175
+ let ignoringPid;
176
+ middle.stdout.once('data', data => ignoringPid = data);
177
+ middle.on('exit', () => process.stdout.write(ignoringPid));
178
+ setInterval(() => {}, 1000);`, { detached: true });
179
+
180
+ processUtils.terminateProcessTree(pid);
181
+
182
+ expect(isAlive(ignoringPid), 'the group member should survive SIGTERM').to.be.true;
183
+ expect(await isAliveAfterKill(pid), 'the group leader should exit on SIGTERM').to.be.false;
184
+ expect(await isAliveAfterKill(ignoringPid), 'the group member should be killed with SIGKILL').to.be.false;
185
+ });
186
+ });
187
+
101
188
  (process.platform === 'win32' ? it : it.skip)('kills the whole tree of the backend when PowerShell cannot be run', async () => {
102
189
  // Only PowerShell is made unrunnable: breaking the environment, e.g. `SystemRoot`, would
103
190
  // break `taskkill.exe` as well. The fallback kills the backend too, with exit code 1.