@hydranium/data-client-theia 1.0.0-next.28 → 1.0.0-next.281

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 (70) hide show
  1. package/README.md +57 -101
  2. package/lib/browser/channel-connection.d.ts +11 -8
  3. package/lib/browser/channel-connection.d.ts.map +1 -1
  4. package/lib/browser/channel-connection.js +7 -5
  5. package/lib/browser/channel-connection.js.map +1 -1
  6. package/lib/browser/channel-data-port.d.ts +92 -0
  7. package/lib/browser/channel-data-port.d.ts.map +1 -0
  8. package/lib/browser/channel-data-port.js +199 -0
  9. package/lib/browser/channel-data-port.js.map +1 -0
  10. package/lib/browser/data-session-stop-contribution.d.ts +76 -0
  11. package/lib/browser/data-session-stop-contribution.d.ts.map +1 -0
  12. package/lib/browser/data-session-stop-contribution.js +146 -0
  13. package/lib/browser/data-session-stop-contribution.js.map +1 -0
  14. package/lib/browser/host-diagnostics-frontend.js +1 -1
  15. package/lib/browser/host-diagnostics-frontend.js.map +1 -1
  16. package/lib/browser/index.d.ts +2 -3
  17. package/lib/browser/index.d.ts.map +1 -1
  18. package/lib/browser/index.js +2 -3
  19. package/lib/browser/index.js.map +1 -1
  20. package/lib/browser/workspace-gate.js.map +1 -1
  21. package/lib/common/emitter-data-client.d.ts +13 -1
  22. package/lib/common/emitter-data-client.d.ts.map +1 -1
  23. package/lib/common/emitter-data-client.js +18 -0
  24. package/lib/common/emitter-data-client.js.map +1 -1
  25. package/lib/node/connection-container-module.d.ts +5 -4
  26. package/lib/node/connection-container-module.d.ts.map +1 -1
  27. package/lib/node/connection-container-module.js +5 -4
  28. package/lib/node/connection-container-module.js.map +1 -1
  29. package/lib/node/data-server-connection-handler.d.ts +9 -19
  30. package/lib/node/data-server-connection-handler.d.ts.map +1 -1
  31. package/lib/node/data-server-connection-handler.js +9 -13
  32. package/lib/node/data-server-connection-handler.js.map +1 -1
  33. package/lib/node/host-diagnostics-server.d.ts.map +1 -1
  34. package/lib/node/host-diagnostics-server.js +1 -1
  35. package/lib/node/host-diagnostics-server.js.map +1 -1
  36. package/lib/node/index.d.ts +0 -1
  37. package/lib/node/index.d.ts.map +1 -1
  38. package/lib/node/index.js +0 -1
  39. package/lib/node/index.js.map +1 -1
  40. package/package.json +25 -39
  41. package/src/browser/channel-connection.ts +16 -12
  42. package/src/browser/channel-data-port.ts +189 -0
  43. package/src/browser/data-session-stop-contribution.ts +151 -0
  44. package/src/browser/host-diagnostics-frontend.ts +1 -1
  45. package/src/browser/index.ts +2 -3
  46. package/src/common/emitter-data-client.ts +27 -0
  47. package/src/node/connection-container-module.ts +5 -4
  48. package/src/node/data-server-connection-handler.ts +10 -23
  49. package/src/node/host-diagnostics-server.ts +1 -1
  50. package/src/node/index.ts +0 -1
  51. package/lib/browser/data-service-frontend.d.ts +0 -154
  52. package/lib/browser/data-service-frontend.d.ts.map +0 -1
  53. package/lib/browser/data-service-frontend.js +0 -169
  54. package/lib/browser/data-service-frontend.js.map +0 -1
  55. package/lib/browser/diagnostics-data-service-frontend.d.ts +0 -35
  56. package/lib/browser/diagnostics-data-service-frontend.d.ts.map +0 -1
  57. package/lib/browser/diagnostics-data-service-frontend.js +0 -54
  58. package/lib/browser/diagnostics-data-service-frontend.js.map +0 -1
  59. package/lib/browser/references-data-service-frontend.d.ts +0 -45
  60. package/lib/browser/references-data-service-frontend.d.ts.map +0 -1
  61. package/lib/browser/references-data-service-frontend.js +0 -55
  62. package/lib/browser/references-data-service-frontend.js.map +0 -1
  63. package/lib/node/socket-channel-forwarder.d.ts +0 -34
  64. package/lib/node/socket-channel-forwarder.d.ts.map +0 -1
  65. package/lib/node/socket-channel-forwarder.js +0 -68
  66. package/lib/node/socket-channel-forwarder.js.map +0 -1
  67. package/src/browser/data-service-frontend.ts +0 -208
  68. package/src/browser/diagnostics-data-service-frontend.ts +0 -70
  69. package/src/browser/references-data-service-frontend.ts +0 -70
  70. package/src/node/socket-channel-forwarder.ts +0 -69
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hydranium/data-client-theia",
3
- "version": "1.0.0-next.28",
3
+ "version": "1.0.0-next.281",
4
4
  "description": "Theia-coupled client primitives for the hydranium data-server protocol head; companion of @hydranium/data-server. Bridges framework typed errors (e.g. ConflictError) across Theia's RPC boundary so their code + data survive the wire.",
5
5
  "keywords": [
6
6
  "hydranium",
@@ -13,16 +13,23 @@
13
13
  "bugs": {
14
14
  "url": "https://github.com/eclipse-emfcloud/hydranium/issues"
15
15
  },
16
+ "license": "MIT",
17
+ "author": {
18
+ "name": "Hydranium Team"
19
+ },
16
20
  "repository": {
17
21
  "type": "git",
18
22
  "url": "https://github.com/eclipse-emfcloud/hydranium.git",
19
23
  "directory": "packages/data-client-theia"
20
24
  },
21
- "license": "MIT",
22
- "author": {
23
- "name": "Hydranium Team"
24
- },
25
+ "files": [
26
+ "lib",
27
+ "src",
28
+ "!lib/**/*.tsbuildinfo"
29
+ ],
25
30
  "sideEffects": false,
31
+ "main": "lib/index.js",
32
+ "types": "lib/index.d.ts",
26
33
  "exports": {
27
34
  ".": {
28
35
  "types": "./lib/index.d.ts",
@@ -39,64 +46,43 @@
39
46
  "./node": {
40
47
  "types": "./lib/node/index.d.ts",
41
48
  "default": "./lib/node/index.js"
42
- },
43
- "./lib/common": {
44
- "types": "./lib/common/index.d.ts",
45
- "default": "./lib/common/index.js"
46
- },
47
- "./lib/browser": {
48
- "types": "./lib/browser/index.d.ts",
49
- "default": "./lib/browser/index.js"
50
- },
51
- "./lib/node": {
52
- "types": "./lib/node/index.d.ts",
53
- "default": "./lib/node/index.js"
54
49
  }
55
50
  },
56
- "main": "lib/index.js",
57
- "types": "lib/index.d.ts",
58
- "files": [
59
- "lib",
60
- "src",
61
- "!lib/**/*.tsbuildinfo"
62
- ],
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
63
54
  "scripts": {
64
55
  "build": "tsc -b",
65
56
  "clean": "rimraf lib tsconfig.tsbuildinfo",
66
- "lint": "eslint src test --max-warnings 0",
57
+ "lint": "oxlint --format stylish --config ../../oxlint.config.cjs src test --max-warnings 0",
67
58
  "prepack": "node -e \"const m=require('./package.json'),fs=require('node:fs');const missing=[m.main,...Object.values(m.bin||{})].filter(entry=>entry&&!fs.existsSync(entry));if(missing.length){console.error('prepack '+m.name+': not built ('+missing.join(', ')+' missing). Run the build before packing: a files entry that matches nothing is skipped silently, so the tarball would ship src only.');process.exit(1);}\"",
68
59
  "test": "npm run typecheck:test && vitest run",
69
60
  "typecheck:test": "tsc --noEmit -p tsconfig.test.json",
70
61
  "watch": "tsc -b -w --preserveWatchOutput"
71
62
  },
72
63
  "devDependencies": {
73
- "@hydranium/client-theia": "1.0.0-next.28",
74
- "@hydranium/core": "1.0.0-next.28",
75
- "@hydranium/protocol": "1.0.0-next.28",
64
+ "@hydranium/client-theia": "1.0.0-next.281",
65
+ "@hydranium/protocol": "1.0.0-next.281",
76
66
  "@theia/core": "^1.70.0",
77
67
  "@theia/workspace": "^1.70.0",
78
68
  "@types/node": "^22.0.0",
79
69
  "inversify": "6.2.2",
80
70
  "reflect-metadata": "0.2.2",
81
71
  "rimraf": "^5.0.0",
82
- "typescript": "^5.8.0",
83
- "vscode-jsonrpc": "9.0.1"
72
+ "typescript": "^7.0.2",
73
+ "vscode-jsonrpc": "9.0.0"
84
74
  },
85
75
  "peerDependencies": {
86
- "@hydranium/client-theia": "1.0.0-next.28",
87
- "@hydranium/core": "1.0.0-next.28",
88
- "@hydranium/protocol": "1.0.0-next.28",
76
+ "@hydranium/client-theia": "1.0.0-next.281",
77
+ "@hydranium/protocol": "1.0.0-next.281",
89
78
  "@theia/core": "^1.70.0",
90
79
  "@theia/workspace": "^1.70.0",
91
80
  "inversify": "^6.0.0",
92
- "vscode-jsonrpc": "9.0.1"
81
+ "vscode-jsonrpc": "^9.0.0"
93
82
  },
94
83
  "engines": {
95
84
  "node": ">=22.13"
96
85
  },
97
- "publishConfig": {
98
- "access": "public"
99
- },
100
- "//peerDependencies": "`vscode-jsonrpc` is EXACT rather than a range, because it is one link of an atomic chain with no independently movable link: `vscode-languageserver-protocol` depends on it at exactly 9.0.1, so any other value an adopter supplies is a SECOND physical copy rather than an upgrade. This wire stack breaks on copy identity rather than on structure — `ParameterStructures.auto` is a singleton compared by `===` in connection.js, so a request type built by one copy and sent over a connection owned by the other throws `Unknown parameter structure auto`. A caret or union range was rejected because npm then resolves a `vscode-jsonrpc@8.2.0` tree SILENTLY, with no diagnostic at all, and the failure surfaces only later at server init. Exact does not fail the install either — npm downgrades an unsatisfiable peer to a warning — but it is a NAMED ERESOLVE warning printing the required version beside the found one, and a hard error for anyone installing with `--strict-peer-deps`. It does NOT prevent a NESTED copy — `@eclipse-glsp/*` carries its own exact `vscode-jsonrpc@8.2.0` dependency and root `overrides` do not ship — so a consumer of the GLSP head must pin the chain in its own manifest.",
101
- "//prepack": "The publish guard, and it deliberately is NOT a `prepare`: npm runs a workspace `prepare` BEFORE the root `postinstall` that applies patches/vscode-jsonrpc+9.0.1.patch, so building there fails on a cold clone and npm rolls the entire install back. `prepack` runs only when a tarball is made (`npm pack`, `npm publish`) and never on install, so it cannot break the install it has no business touching. It FAILS rather than rebuilds, because the rebuild is exactly the part that ordering defeats. What it defends against: `files` lists `lib`, `lib` is gitignored, and a `files` entry matching nothing is skipped SILENTLY — so `npm publish` from an unbuilt tree emits a tarball of `src` and nothing else, with no error."
86
+ "//peerDependencies": "`vscode-jsonrpc` takes a caret, so the framework shares the transport the LSP connection resolves, which an `init` scaffold pins: each `vscode-languageserver-protocol` release pins its transport exactly, so an exact peer would name a copy a fresh install rarely holds. The caret excludes 8.x, so a tree whose top holds GLSP's copy fails the peer with a named ERESOLVE warning, an error under `--strict-peer-deps`, rather than resolving silently. No peer reaches a NESTED copy, such as GLSP's or one the LSP packages nest. The wire compares message types and `ResponseError`s by copy identity, so the framework sends typed messages by method name and recognises errors with `isResponseError` rather than `instanceof`.",
87
+ "//prepack": "The publish guard, a `prepack` rather than a `prepare`: `prepack` runs only when a tarball is made (`npm pack`, `npm publish`) and never on install, so it cannot break the install it has no business touching. What it defends against: `files` lists `lib`, `lib` is gitignored, and a `files` entry matching nothing is skipped SILENTLY — so `npm publish` from an unbuilt tree emits a tarball of `src` and nothing else, with no error."
102
88
  }
@@ -7,6 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
+ import { type Clock, type Stopwatch, SystemClock } from '@hydranium/protocol';
10
11
  import { type Channel, DisposableCollection, Emitter, type Event, type MessageProvider } from '@theia/core';
11
12
  import { type ServiceConnectionProvider } from '@theia/core/lib/browser';
12
13
  import { Deferred } from '@theia/core/lib/common/promise-util';
@@ -104,7 +105,7 @@ class ChannelMessageWriter extends AbstractMessageWriter implements MessageWrite
104
105
  * Mirrors `@eclipse-glsp/theia-integration`'s `createChannelConnection`, but
105
106
  * lives here so the data-server head carries no GLSP dependency.
106
107
  */
107
- export function createChannelConnection(channel: Channel, logger?: Logger): MessageConnection {
108
+ export function createChannelConnection(channel: Channel, logger: Logger): MessageConnection {
108
109
  const reader = new ChannelMessageReader(channel);
109
110
  const writer = new ChannelMessageWriter(channel);
110
111
  return createMessageConnection(reader, writer, logger);
@@ -120,8 +121,10 @@ export interface OpenChannelConnectionOptions {
120
121
  * publishes the port) exists.
121
122
  */
122
123
  whenReady?: Promise<void>;
123
- /** Optional `vscode-jsonrpc` logger threaded into the connection. */
124
- logger?: Logger;
124
+ /** Where the connection logs its protocol faults; without one they leave no trace. */
125
+ logger: Logger;
126
+ /** Times the escalation reset. Default a `SystemClock`. */
127
+ clock?: Clock;
125
128
  /**
126
129
  * Re-establish the connection whenever the live one is lost, by RE-OPENING
127
130
  * the channel on `path` — not merely by rebuilding over a channel Theia hands
@@ -199,8 +202,8 @@ export interface ChannelConnectionHandle {
199
202
  /**
200
203
  * The current connection. Read it per use rather than caching it: after a
201
204
  * reconnect this returns a NEW promise, and a cached one resolves to the
202
- * dead connection forever. The same reasoning makes
203
- * `AbstractDataServiceFrontend` rebuild its proxy rather than hold one.
205
+ * dead connection forever. The same reasoning makes `RpcConnection` rebuild
206
+ * its proxy per generation rather than hold one.
204
207
  */
205
208
  readonly current: Promise<MessageConnection>;
206
209
 
@@ -213,10 +216,10 @@ export interface ChannelConnectionHandle {
213
216
  *
214
217
  * **This is the event a consumer wants, not {@link onDidReconnect}.** Anything
215
218
  * derived from a connection — an `createRpcProxy`, a readiness gate, a
216
- * `DataSession` generation — is dead from this moment, and a consumer that
219
+ * `DataConnection` generation — is dead from this moment, and a consumer that
217
220
  * waits for the replacement to be live instead keeps sending into the dead one
218
221
  * for the whole gap. A `DataPort` implementation translates this into the
219
- * port's own `onDispose`, which is what makes `DataSession` drop its
222
+ * port's own `onDispose`, which is what makes `DataConnection` drop its
220
223
  * generation.
221
224
  *
222
225
  * Never fires when {@link OpenChannelConnectionOptions.reconnect} is off.
@@ -269,7 +272,7 @@ export interface ChannelConnectionHandle {
269
272
  export function openChannelConnection(
270
273
  connectionProvider: ServiceConnectionProvider,
271
274
  path: string,
272
- options: OpenChannelConnectionOptions = {}
275
+ options: OpenChannelConnectionOptions
273
276
  ): ChannelConnectionHandle {
274
277
  const reconnect = options.reconnect ?? true;
275
278
  const reconnectDelays = options.reconnectDelays ?? DEFAULT_RECONNECT_DELAYS;
@@ -283,8 +286,9 @@ export function openChannelConnection(
283
286
  let awaitingReplacement = false;
284
287
  /** Consecutive losses, indexing `reconnectDelays`. */
285
288
  let losses = 0;
286
- /** When the live connection was built, for the escalation reset. `0` before the first. */
287
- let liveSince = 0;
289
+ const clock = options.clock ?? new SystemClock();
290
+ /** Running since the live connection was built, for the escalation reset. */
291
+ let sinceLive: Stopwatch | undefined;
288
292
  let reopenTimer: ReturnType<typeof setTimeout> | undefined;
289
293
  // Own synchronous flag, deliberately NOT `deferred.state`. Theia's
290
294
  // `Deferred` sets `state` inside a `.then()` on its own promise, so it is
@@ -298,7 +302,7 @@ export function openChannelConnection(
298
302
  let built = false;
299
303
 
300
304
  const scheduleReopen = (): void => {
301
- if (liveSince > 0 && Date.now() - liveSince >= RECONNECT_ESCALATION_RESET_MS) {
305
+ if (sinceLive !== undefined && sinceLive.elapsedMs >= RECONNECT_ESCALATION_RESET_MS) {
302
306
  losses = 0;
303
307
  }
304
308
  const delay = reconnectDelays[Math.min(losses, reconnectDelays.length - 1)];
@@ -355,7 +359,7 @@ export function openChannelConnection(
355
359
  built = true;
356
360
  awaitingReplacement = false;
357
361
  generation++;
358
- liveSince = Date.now();
362
+ sinceLive = clock.stopwatch();
359
363
  if (reconnect) {
360
364
  // Registered AFTER `createChannelConnection`, so the connection's own
361
365
  // reader and writer see the close first and `connection.onClose` still
@@ -0,0 +1,189 @@
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 MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { ChannelLogger, ConnectionReporter, type ConnectionAttempt, type ConnectionTarget } from '@hydranium/client-theia/browser';
11
+ import { Clock } from '@hydranium/client-theia/common';
12
+ import {
13
+ DATA_SERVER_CONNECT_FAILED,
14
+ DATA_SERVER_NOT_READY,
15
+ renderFrameworkMessage,
16
+ SystemClock,
17
+ type DataPort,
18
+ type ResolvedMessage,
19
+ type RpcConnectionLifecycle
20
+ } from '@hydranium/protocol';
21
+ import { Emitter, MessageService, nls, type Event } from '@theia/core';
22
+ import { type ServiceConnectionProvider } from '@theia/core/lib/browser';
23
+ import { RemoteConnectionProvider } from '@theia/core/lib/browser/messaging/service-connection-provider';
24
+ import { inject, injectable, optional } from '@theia/core/shared/inversify';
25
+ import { WorkspaceService } from '@theia/workspace/lib/browser';
26
+ import type { MessageConnection } from 'vscode-jsonrpc';
27
+ import { type ChannelConnectionHandle, openChannelConnection } from './channel-connection';
28
+ import { whenWorkspaceOpen } from './workspace-gate';
29
+
30
+ /**
31
+ * A {@link DataPort} over a Theia frontend channel.
32
+ *
33
+ * Subclasses supply {@link servicePath}; everything above the port —
34
+ * `DataConnection`, its sessions, and whatever model a widget drives — is
35
+ * host-neutral and shared with the VS Code and browser shells.
36
+ *
37
+ * Bind one per service path and in singleton scope. Theia keys a frontend
38
+ * channel by its path and refuses a second on a path already open, and the
39
+ * throw escapes the `openChannelConnection` the loser is awaiting, leaving that
40
+ * promise unsettled rather than rejected.
41
+ */
42
+ @injectable()
43
+ export abstract class ChannelDataPort implements DataPort {
44
+ @inject(RemoteConnectionProvider) protected readonly connectionProvider!: ServiceConnectionProvider;
45
+ @inject(WorkspaceService) protected readonly workspaceService!: WorkspaceService;
46
+ @inject(MessageService) protected readonly messageService!: MessageService;
47
+ @inject(ConnectionReporter) protected readonly connectionReporter!: ConnectionReporter;
48
+ @inject(ChannelLogger) readonly logger!: ChannelLogger;
49
+ /** Times the channel's reconnect escalation: the container's {@link Clock}, or a `SystemClock`. */
50
+ @inject(Clock) @optional() protected readonly clock: Clock = new SystemClock();
51
+
52
+ /** Frontend service path the backend forwarder for this head is registered under. */
53
+ protected abstract readonly servicePath: string;
54
+
55
+ /**
56
+ * Re-open the channel when the current connection is lost. Default `true` —
57
+ * re-opening is the only thing that recovers a restarted language server,
58
+ * which binds new ephemeral ports. Turn it off for a frontend that tears
59
+ * itself down on transport loss instead.
60
+ */
61
+ protected readonly reconnectOnConnectionLoss: boolean = true;
62
+
63
+ protected readonly disposeEmitter = new Emitter<void>();
64
+ readonly onDispose: Event<void> = this.disposeEmitter.event;
65
+
66
+ protected handle?: ChannelConnectionHandle;
67
+ /** Set by {@link dispose}, after which {@link connect} rejects. */
68
+ protected disposed = false;
69
+
70
+ /** How long a connection may take before it is reported as failed; it keeps trying after. */
71
+ protected readonly connectFailureNoticeMs: number = 30_000;
72
+ protected attempt?: ConnectionAttempt;
73
+ protected attemptTimer?: ReturnType<typeof setTimeout>;
74
+ /** Set once {@link connectionLifecycle} reports, which then owns the connection failures. */
75
+ protected reportsConnections = false;
76
+
77
+ /** Reports each connection generation through the {@link ConnectionReporter}. */
78
+ readonly connectionLifecycle: RpcConnectionLifecycle = {
79
+ onConnecting: () => {
80
+ this.reportsConnections = true;
81
+ this.settleAttempt();
82
+ const attempt = this.connectionReporter.connecting(this.connectionTarget);
83
+ this.attempt = attempt;
84
+ this.attemptTimer = setTimeout(() => {
85
+ attempt.failed(this.connectTimeoutMessage());
86
+ // The generation keeps waiting; a follow-up attempt reports it connecting.
87
+ this.attempt = this.connectionReporter.connecting(this.connectionTarget);
88
+ }, this.connectFailureNoticeMs);
89
+ },
90
+ onReady: () => this.settleAttempt(attempt => attempt.connected()),
91
+ onFailed: () => this.settleAttempt(attempt => attempt.failed(this.unreachableMessage()))
92
+ };
93
+
94
+ /**
95
+ * Open the workspace-gated channel and hand back its listening connection.
96
+ *
97
+ * Gated because the backend forwarder discovers the head's port by executing
98
+ * a command the language server answers, and the language server only
99
+ * launches once there is a workspace to launch it for. Asking earlier polls
100
+ * a command nobody has registered.
101
+ *
102
+ * Rejects once the port is disposed: the consumer reconnects when the
103
+ * dispose fires {@link onDispose}, and a channel opened then is closed by
104
+ * nothing.
105
+ */
106
+ connect(): Promise<MessageConnection> {
107
+ if (this.disposed) {
108
+ return Promise.reject(new Error(`${this.constructor.name}: the port is disposed`));
109
+ }
110
+ // Read per call rather than cached: `current` is repointed at a fresh
111
+ // promise every time the channel is re-opened, so reading through the
112
+ // handle is what makes a later generation reach the live server.
113
+ if (!this.handle) {
114
+ this.handle = openChannelConnection(this.connectionProvider, this.servicePath, {
115
+ whenReady: whenWorkspaceOpen(this.workspaceService),
116
+ logger: this.logger,
117
+ clock: this.clock,
118
+ reconnect: this.reconnectOnConnectionLoss
119
+ });
120
+ // A relaunched server binds new ephemeral ports; the handle re-opens
121
+ // and the forwarder rediscovers, but `DataConnection` caches its
122
+ // generation and would go on addressing the dead one. Its signal to
123
+ // drop that generation is this event.
124
+ this.handle.onDidLoseConnection(() => this.disposeEmitter.fire(undefined));
125
+ }
126
+ return this.handle.current;
127
+ }
128
+
129
+ /**
130
+ * Surface a transport or write failure as a Theia notification.
131
+ *
132
+ * Swallowing it is the failure this exists to prevent: a dead connection and
133
+ * an empty document are indistinguishable in a widget.
134
+ *
135
+ * `reported` is already a complete sentence with the detail interpolated, so
136
+ * wrapping it in a sentence of the host's own would nest one owner's clause
137
+ * inside another's and leave no translator in control of the whole.
138
+ */
139
+ reportError(_error: unknown, reported: ResolvedMessage): void {
140
+ const connectionFailure = reported.code === DATA_SERVER_CONNECT_FAILED.code || reported.code === DATA_SERVER_NOT_READY.code;
141
+ const message = renderFrameworkMessage(reported, nls.localization?.translations);
142
+ if (connectionFailure && this.reportsConnections) {
143
+ // The reporter shows the failure without its detail, so it is kept here.
144
+ this.logger.warn(message);
145
+ return;
146
+ }
147
+ this.messageService.error(message);
148
+ }
149
+
150
+ /** End the current attempt through `settle`, or cancel it. */
151
+ protected settleAttempt(settle: (attempt: ConnectionAttempt) => void = attempt => attempt.cancelled()): void {
152
+ clearTimeout(this.attemptTimer);
153
+ const attempt = this.attempt;
154
+ this.attempt = undefined;
155
+ if (attempt) {
156
+ settle(attempt);
157
+ }
158
+ }
159
+
160
+ protected get connectionTarget(): ConnectionTarget {
161
+ return (this.cachedConnectionTarget ??= {
162
+ connectingMessage: nls.localize('hydranium/data-client-theia/data-server-connecting', 'Connecting to the data server…'),
163
+ connectedMessage: nls.localize('hydranium/data-client-theia/data-server-connected', 'Connected to the data server.')
164
+ });
165
+ }
166
+ /** One object per port: the reporter keys what it has shown on it. */
167
+ protected cachedConnectionTarget?: ConnectionTarget;
168
+
169
+ protected unreachableMessage(): string {
170
+ return nls.localize('hydranium/data-client-theia/data-server-unreachable', 'Could not connect to the data server.');
171
+ }
172
+
173
+ protected connectTimeoutMessage(): string {
174
+ return nls.localize(
175
+ 'hydranium/data-client-theia/data-server-timeout',
176
+ 'The data server did not answer within {0} seconds.',
177
+ String(Math.round(this.connectFailureNoticeMs / 1000))
178
+ );
179
+ }
180
+
181
+ dispose(): void {
182
+ this.disposed = true;
183
+ this.settleAttempt();
184
+ this.handle?.dispose();
185
+ this.handle = undefined;
186
+ this.disposeEmitter.fire(undefined);
187
+ this.disposeEmitter.dispose();
188
+ }
189
+ }
@@ -0,0 +1,151 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { bindConnectionReporter } from '@hydranium/client-theia/browser';
11
+ import type { DataConnection, DataServerProtocol, DataSession, DiagnosticOf, TransferElement } from '@hydranium/protocol';
12
+ // Not the `@theia/core/lib/browser` barrel: it touches DOM globals at module
13
+ // load, which the node-environment unit tests cannot provide.
14
+ import { FrontendApplicationContribution, type OnWillStopAction } from '@theia/core/lib/browser/frontend-application-contribution';
15
+ import { injectable, type interfaces } from '@theia/core/shared/inversify';
16
+
17
+ /**
18
+ * Ends a Theia frontend's data sessions with its page, and holds the page
19
+ * while one of them is still saving. {@link bindDataConnection} binds it and
20
+ * has it {@link track} each data connection bound through it.
21
+ *
22
+ * **Stop.** {@link onStop} disposes every tracked session, which sends its
23
+ * `closeSession`, so the server ends it as closed: each document it was the
24
+ * last to hold is released at once. Otherwise the server learns of the page only
25
+ * when its connection goes, which Theia may hold open for its reconnect
26
+ * timeout, and then ends the sessions as lost, so their documents wait out the
27
+ * release grace. The close is best effort: under load the page's last frames
28
+ * can be lost on the way, and the server then ends the sessions as lost. A
29
+ * session with calls still in flight at the stop closes after them, which is
30
+ * too late for a page going away, and is left to the server's connection-close
31
+ * cleanup. A call a session makes in the same tick as the stop is refused and
32
+ * never sent.
33
+ *
34
+ * **Veto.** While a tracked session has a save in flight, {@link onWillStop}
35
+ * vetoes, including a session disposed meanwhile. In Electron, Theia awaits
36
+ * the veto's action, which waits for the saves to answer, a save started during
37
+ * the wait included, up to {@link maxSettlePasses} times. The browser runs no
38
+ * action before unload, so there the veto shows the leave-page prompt and
39
+ * nothing more. Theia ignores every veto under
40
+ * `application.confirmExit: 'never'`, so there a save in flight at the stop
41
+ * may be cut off.
42
+ */
43
+ @injectable()
44
+ export class DataSessionStopContribution implements FrontendApplicationContribution {
45
+ /** The sessions to end at the stop, and to wait for while they save. */
46
+ protected readonly sessions = new Set<DataSession<TransferElement>>();
47
+ /**
48
+ * How many times the veto's action waits for the saves in flight before it
49
+ * lets the stop go. Each wait ends by the session's own bound, so a save
50
+ * that never answers holds the stop for a few bounds, not for good.
51
+ */
52
+ protected readonly maxSettlePasses: number = 3;
53
+
54
+ /**
55
+ * Take every session of `connection` into the stop: the ones it has
56
+ * started already, and each one it starts from now on. Generic, so a
57
+ * connection of any transfer root, server and client fits.
58
+ */
59
+ track<TTransfer extends TransferElement, TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>, TClient extends object>(
60
+ connection: DataConnection<TTransfer, TServer, TClient>
61
+ ): void {
62
+ connection.liveSessions.forEach(session => this.trackSession(session));
63
+ connection.onDidCreateSession(session => this.trackSession(session));
64
+ }
65
+
66
+ /**
67
+ * Take `session` into the stop. It leaves once it has ended and its saves
68
+ * have answered, so a session disposed with a save in flight still holds
69
+ * the page.
70
+ */
71
+ protected trackSession(session: DataSession<TransferElement>): void {
72
+ this.sessions.add(session);
73
+ // A save can outlast the wait's bound, so the session stays until none
74
+ // is left in flight.
75
+ const release = (): void =>
76
+ void session.whenSavesSettled().then(() => (session.hasSavesInFlight ? release() : this.sessions.delete(session)));
77
+ // An ended session has fired its event already, and never fires it again.
78
+ if (session.isDisposed) {
79
+ release();
80
+ } else {
81
+ session.onDidDispose(release);
82
+ }
83
+ }
84
+
85
+ onWillStop(): OnWillStopAction | undefined {
86
+ if (this.savingSessions().length === 0) {
87
+ return undefined;
88
+ }
89
+ return {
90
+ // Theia logs the reason and shows it nowhere, so it is not translated.
91
+ reason: 'Data sessions are saving',
92
+ action: async () => {
93
+ // The page stays usable while Theia awaits this, so a save can
94
+ // start during a wait; each pass waits for the saves then in flight.
95
+ for (let pass = 0; pass < this.maxSettlePasses; pass++) {
96
+ const saving = this.savingSessions();
97
+ if (saving.length === 0) {
98
+ break;
99
+ }
100
+ await Promise.all(saving.map(session => session.whenSavesSettled()));
101
+ }
102
+ return true;
103
+ }
104
+ };
105
+ }
106
+
107
+ /** The tracked sessions with a save in flight. */
108
+ protected savingSessions(): DataSession<TransferElement>[] {
109
+ return [...this.sessions].filter(session => session.hasSavesInFlight);
110
+ }
111
+
112
+ onStop(): void {
113
+ for (const session of this.sessions) {
114
+ session.dispose();
115
+ }
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Bind `connectionClass` in singleton scope, its sessions tracked by the
121
+ * {@link DataSessionStopContribution}, and bind that contribution and the
122
+ * `ConnectionReporter` the connection's port injects unless they are bound
123
+ * already. The binding's `onActivation` is taken; a frontend's own hook on the
124
+ * connection goes on the container's `onActivation`, which runs after it. A
125
+ * subclass of the contribution is rebound after this call: one bound before it
126
+ * is never registered as a frontend contribution, so its stop never runs.
127
+ * Call it once per connection class: a second call makes the class's lookup
128
+ * ambiguous.
129
+ */
130
+ export function bindDataConnection<
131
+ TTransfer extends TransferElement,
132
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>>,
133
+ TClient extends object
134
+ >(
135
+ bind: interfaces.Bind,
136
+ isBound: interfaces.IsBound,
137
+ connectionClass: interfaces.Newable<DataConnection<TTransfer, TServer, TClient>>
138
+ ): void {
139
+ bind(connectionClass)
140
+ .toSelf()
141
+ .inSingletonScope()
142
+ .onActivation((context, connection) => {
143
+ context.container.get(DataSessionStopContribution).track(connection);
144
+ return connection;
145
+ });
146
+ if (!isBound(DataSessionStopContribution)) {
147
+ bind(DataSessionStopContribution).toSelf().inSingletonScope();
148
+ bind(FrontendApplicationContribution).toService(DataSessionStopContribution);
149
+ }
150
+ bindConnectionReporter(bind, isBound);
151
+ }
@@ -7,7 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { HostMemoryDiagnosticsService } from '@hydranium/client-theia/lib/browser';
10
+ import { HostMemoryDiagnosticsService } from '@hydranium/client-theia/browser';
11
11
  import { HOST_DIAGNOSTICS_PATH, type HostDiagnosticsProtocol } from '@hydranium/protocol';
12
12
  import { RemoteConnectionProvider, type ServiceConnectionProvider } from '@theia/core/lib/browser/messaging/service-connection-provider';
13
13
  import { type interfaces } from '@theia/core/shared/inversify';
@@ -8,8 +8,7 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  export * from './channel-connection';
11
- export * from './data-service-frontend';
12
- export * from './diagnostics-data-service-frontend';
11
+ export * from './channel-data-port';
12
+ export * from './data-session-stop-contribution';
13
13
  export * from './host-diagnostics-frontend';
14
- export * from './references-data-service-frontend';
15
14
  export * from './workspace-gate';
@@ -12,7 +12,10 @@ import type {
12
12
  Project,
13
13
  ProjectsChangedEvent,
14
14
  TransferDiagnostic,
15
+ TransferDocumentDeletedEvent,
16
+ TransferDocumentDirtyChangedEvent,
15
17
  TransferDocumentSavedEvent,
18
+ TransferDocumentsBuiltEvent,
16
19
  TransferDocumentUpdatedEvent,
17
20
  TransferElement
18
21
  } from '@hydranium/protocol';
@@ -46,6 +49,18 @@ export class EmitterDataClient<
46
49
  /** Fires for each inbound {@link onDocumentSaved} notification. */
47
50
  readonly onDidSaveDocument: Event<TransferDocumentSavedEvent<TTransfer, TDiagnostic>> = this.onDocumentSavedEmitter.event;
48
51
 
52
+ protected readonly onDocumentDirtyChangedEmitter = new Emitter<TransferDocumentDirtyChangedEvent>();
53
+ /** Fires for each inbound {@link onDocumentDirtyChanged} notification. */
54
+ readonly onDidChangeDocumentDirty: Event<TransferDocumentDirtyChangedEvent> = this.onDocumentDirtyChangedEmitter.event;
55
+
56
+ protected readonly onDocumentDeletedEmitter = new Emitter<TransferDocumentDeletedEvent>();
57
+ /** Fires for each inbound {@link onDocumentDeleted} notification. */
58
+ readonly onDidDeleteDocument: Event<TransferDocumentDeletedEvent> = this.onDocumentDeletedEmitter.event;
59
+
60
+ protected readonly onDocumentsBuiltEmitter = new Emitter<TransferDocumentsBuiltEvent>();
61
+ /** Fires for each inbound {@link onDocumentsBuilt} notification. */
62
+ readonly onDidBuildDocuments: Event<TransferDocumentsBuiltEvent> = this.onDocumentsBuiltEmitter.event;
63
+
49
64
  protected readonly onProjectsChangedEmitter = new Emitter<ProjectsChangedEvent<TProject>>();
50
65
  /** Fires for each inbound {@link onProjectsChanged} notification. */
51
66
  readonly onDidChangeProjects: Event<ProjectsChangedEvent<TProject>> = this.onProjectsChangedEmitter.event;
@@ -58,6 +73,18 @@ export class EmitterDataClient<
58
73
  this.onDocumentSavedEmitter.fire(event);
59
74
  }
60
75
 
76
+ onDocumentDirtyChanged(event: TransferDocumentDirtyChangedEvent): void {
77
+ this.onDocumentDirtyChangedEmitter.fire(event);
78
+ }
79
+
80
+ onDocumentDeleted(event: TransferDocumentDeletedEvent): void {
81
+ this.onDocumentDeletedEmitter.fire(event);
82
+ }
83
+
84
+ onDocumentsBuilt(event: TransferDocumentsBuiltEvent): void {
85
+ this.onDocumentsBuiltEmitter.fire(event);
86
+ }
87
+
61
88
  onProjectsChanged(event: ProjectsChangedEvent<TProject>): void {
62
89
  this.onProjectsChangedEmitter.fire(event);
63
90
  }
@@ -27,11 +27,12 @@ import { ContainerModule, type interfaces } from '@theia/core/shared/inversify';
27
27
  *
28
28
  * **More than one handler is the normal case, not an exotic one.** Theia keys a
29
29
  * frontend channel by its service path and refuses a second channel on a path
30
- * already open, so every frontend abstraction reaching the data head needs its
31
- * own path and therefore its own handler — a host-neutral `DataPort` beside a
32
- * Theia `AbstractDataServiceFrontend` is exactly that shape. They still forward
30
+ * already open, so every frontend abstraction reaching the data head on its own
31
+ * channel needs its own path and therefore its own handler. They still forward
33
32
  * to the SAME data server: the path distinguishes the channel, the shared
34
- * `portCommand` names the one process behind it.
33
+ * `portCommand` names the one process behind it. Several participants over ONE
34
+ * channel need no second handler — that is what `DataConnection`'s sessions are
35
+ * for, and it is the cheaper arrangement.
35
36
  */
36
37
  export function createDataServerConnectionContainerModule(...handlerClasses: interfaces.Newable<ConnectionHandler>[]): ContainerModule {
37
38
  const frontendScopedConnectionModule = ConnectionContainerModule.create(({ bind }) => {