@hydranium/client-theia 1.0.0-next.9 → 1.0.0-next.90

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 (55) hide show
  1. package/README.md +2 -2
  2. package/lib/browser/connection-diagnostics-contribution.d.ts +69 -0
  3. package/lib/browser/connection-diagnostics-contribution.d.ts.map +1 -0
  4. package/lib/browser/connection-diagnostics-contribution.js +153 -0
  5. package/lib/browser/connection-diagnostics-contribution.js.map +1 -0
  6. package/lib/browser/index.d.ts +2 -0
  7. package/lib/browser/index.d.ts.map +1 -1
  8. package/lib/browser/index.js +2 -0
  9. package/lib/browser/index.js.map +1 -1
  10. package/lib/browser/log-level-preference.d.ts.map +1 -1
  11. package/lib/browser/log-level-preference.js +11 -0
  12. package/lib/browser/log-level-preference.js.map +1 -1
  13. package/lib/browser/memory-diagnostics-contribution.d.ts +40 -4
  14. package/lib/browser/memory-diagnostics-contribution.d.ts.map +1 -1
  15. package/lib/browser/memory-diagnostics-contribution.js +161 -31
  16. package/lib/browser/memory-diagnostics-contribution.js.map +1 -1
  17. package/lib/browser/session-aware-connection-source.d.ts +98 -0
  18. package/lib/browser/session-aware-connection-source.d.ts.map +1 -0
  19. package/lib/browser/session-aware-connection-source.js +167 -0
  20. package/lib/browser/session-aware-connection-source.js.map +1 -0
  21. package/lib/common/connection-resilience-options.d.ts +24 -0
  22. package/lib/common/connection-resilience-options.d.ts.map +1 -0
  23. package/lib/common/connection-resilience-options.js +11 -0
  24. package/lib/common/connection-resilience-options.js.map +1 -0
  25. package/lib/common/framed-socket-write-buffer.d.ts +121 -0
  26. package/lib/common/framed-socket-write-buffer.d.ts.map +1 -0
  27. package/lib/common/framed-socket-write-buffer.js +190 -0
  28. package/lib/common/framed-socket-write-buffer.js.map +1 -0
  29. package/lib/common/index.d.ts +11 -0
  30. package/lib/common/index.d.ts.map +1 -0
  31. package/lib/common/index.js +30 -0
  32. package/lib/common/index.js.map +1 -0
  33. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
  34. package/lib/node/abstract-socket-forwarding-connection-handler.js +6 -1
  35. package/lib/node/abstract-socket-forwarding-connection-handler.js.map +1 -1
  36. package/lib/node/index.d.ts +1 -0
  37. package/lib/node/index.d.ts.map +1 -1
  38. package/lib/node/index.js +1 -0
  39. package/lib/node/index.js.map +1 -1
  40. package/lib/node/session-bound-frontend-connection-service.d.ts +77 -0
  41. package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
  42. package/lib/node/session-bound-frontend-connection-service.js +128 -0
  43. package/lib/node/session-bound-frontend-connection-service.js.map +1 -0
  44. package/package.json +16 -7
  45. package/src/browser/connection-diagnostics-contribution.ts +142 -0
  46. package/src/browser/index.ts +2 -0
  47. package/src/browser/log-level-preference.ts +11 -0
  48. package/src/browser/memory-diagnostics-contribution.ts +268 -45
  49. package/src/browser/session-aware-connection-source.ts +179 -0
  50. package/src/common/connection-resilience-options.ts +24 -0
  51. package/src/common/framed-socket-write-buffer.ts +227 -0
  52. package/src/common/index.ts +14 -0
  53. package/src/node/abstract-socket-forwarding-connection-handler.ts +6 -1
  54. package/src/node/index.ts +1 -0
  55. package/src/node/session-bound-frontend-connection-service.ts +155 -0
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ /********************************************************************************
3
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
4
+ *
5
+ * This program and the accompanying materials are made available under the
6
+ * terms of the MIT License which is available in the project root.
7
+ *
8
+ * SPDX-License-Identifier: MIT
9
+ ********************************************************************************/
10
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
11
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
12
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
13
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.SessionBoundFrontendConnectionService = void 0;
18
+ exports.bindConnectionResilience = bindConnectionResilience;
19
+ const backend_application_config_provider_1 = require("@theia/core/lib/node/backend-application-config-provider");
20
+ const socket_write_buffer_1 = require("@theia/core/lib/common/messaging/socket-write-buffer");
21
+ const websocket_frontend_connection_service_1 = require("@theia/core/lib/node/messaging/websocket-frontend-connection-service");
22
+ const inversify_1 = require("@theia/core/shared/inversify");
23
+ const framed_socket_write_buffer_1 = require("../common/framed-socket-write-buffer");
24
+ /**
25
+ * Ignores a disconnect from a socket that no longer belongs to the frontend.
26
+ *
27
+ * A frontend that loses its network reconnects on a new socket within seconds;
28
+ * the server only notices the old one is gone when its next heartbeat write
29
+ * fails, which is a whole ping interval later. For that stretch both sockets are
30
+ * registered against the same session, and Theia's disconnect handler tears the
31
+ * session off its socket without checking which one just died. The late
32
+ * notification from the abandoned socket therefore cuts the healthy one loose.
33
+ * The frontend sees a connected socket and never retries, so the session is dead
34
+ * until the page is reloaded.
35
+ *
36
+ * Changed here: only the socket the session is currently using may act on a
37
+ * disconnect. The handler is rewritten rather than wrapped because the problem
38
+ * sits inside the listener Theia installs; the rest of the body is Theia's.
39
+ *
40
+ * Re-diff against Theia when the supported range moves: `override` catches a changed signature,
41
+ * not a changed body, so this copy can go stale in silence.
42
+ */
43
+ let SessionBoundFrontendConnectionService = class SessionBoundFrontendConnectionService extends websocket_frontend_connection_service_1.WebsocketFrontendConnectionService {
44
+ /** Socket each frontend's channel is currently bound to, with the time it was bound. */
45
+ bindings = new Map();
46
+ /** When a frontend's live socket went away, so the reconnect gap can be reported. */
47
+ offlineSince = new Map();
48
+ handleSocketDisconnect(socket, channel, frontEndId) {
49
+ const previous = this.bindings.get(frontEndId);
50
+ this.bindings.set(frontEndId, { socketId: socket.id, boundAt: Date.now() });
51
+ const wentOfflineAt = this.offlineSince.get(frontEndId);
52
+ this.offlineSince.delete(frontEndId);
53
+ const replacing = previous ? `, replacing socket ${previous.socketId}` : '';
54
+ const gap = wentOfflineAt === undefined ? '' : `, after ${Date.now() - wentOfflineAt} ms offline`;
55
+ console.info(`${framed_socket_write_buffer_1.CONNECTION_LOG_PREFIX} frontend ${frontEndId} channel bound to socket ${socket.id}${replacing}${gap}`);
56
+ socket.on('disconnect', reason => {
57
+ const bound = this.bindings.get(frontEndId);
58
+ if (bound?.socketId !== socket.id) {
59
+ // Either a superseded socket being reaped late, or one outliving `closeConnection`, which
60
+ // deletes the binding. Neither owns the channel, so neither may disconnect it, arm a close
61
+ // timeout, or close a connection that is no longer in `connectionsByFrontend`.
62
+ const owner = bound
63
+ ? `socket ${bound.socketId} owns it (bound ${Date.now() - bound.boundAt} ms ago)`
64
+ : 'the connection is already closed';
65
+ console.info(`${framed_socket_write_buffer_1.CONNECTION_LOG_PREFIX} ignoring disconnect of stale socket ${socket.id} (frontend ${frontEndId}, ${reason}); ${owner}`);
66
+ return;
67
+ }
68
+ // From here on: Theia's own handler body, unchanged apart from naming the socket.
69
+ this.offlineSince.set(frontEndId, Date.now());
70
+ console.info(`${framed_socket_write_buffer_1.CONNECTION_LOG_PREFIX} socket ${socket.id} (frontend ${frontEndId}) disconnected: ${reason}`);
71
+ channel.disconnect();
72
+ const timeout = this.connectionTimeout();
73
+ const isMarkedForClose = this.channelsMarkedForClose.delete(frontEndId);
74
+ if (timeout === 0 || isMarkedForClose) {
75
+ this.closeConnection(frontEndId, reason);
76
+ }
77
+ else if (timeout > 0) {
78
+ console.info(`${framed_socket_write_buffer_1.CONNECTION_LOG_PREFIX} close timeout for frontend ${frontEndId} set to ${timeout} ms`);
79
+ this.closeTimeouts.set(frontEndId, setTimeout(() => this.closeConnection(frontEndId, reason), timeout));
80
+ }
81
+ // timeout < 0: never close the back end.
82
+ });
83
+ }
84
+ closeConnection(frontEndId, reason) {
85
+ console.info(`${framed_socket_write_buffer_1.CONNECTION_LOG_PREFIX} closing frontend ${frontEndId}: ${reason}`);
86
+ this.bindings.delete(frontEndId);
87
+ this.offlineSince.delete(frontEndId);
88
+ super.closeConnection(frontEndId, reason);
89
+ }
90
+ /** Mirrors Theia's private `frontendConnectionTimeout`, including `Number('')` resolving to 0.
91
+ * Private there, so the copy is forced; re-diff it with the handler above. */
92
+ connectionTimeout() {
93
+ const envValue = Number(process.env['FRONTEND_CONNECTION_TIMEOUT']);
94
+ if (!isNaN(envValue)) {
95
+ return envValue;
96
+ }
97
+ return backend_application_config_provider_1.BackendApplicationConfigProvider.get().frontendConnectionTimeout;
98
+ }
99
+ };
100
+ exports.SessionBoundFrontendConnectionService = SessionBoundFrontendConnectionService;
101
+ exports.SessionBoundFrontendConnectionService = SessionBoundFrontendConnectionService = __decorate([
102
+ (0, inversify_1.injectable)()
103
+ ], SessionBoundFrontendConnectionService);
104
+ /**
105
+ * Replaces the server pieces that decide how a session survives a reconnect.
106
+ *
107
+ * `FrontendConnectionService` is bound `toService(WebsocketFrontendConnectionService)`,
108
+ * so rebinding the concrete class is enough. The buffer stays transient (one per
109
+ * connection), matching Theia's `bind(SocketWriteBuffer).toSelf()`; the frontend
110
+ * counterpart is bound by `bindConnectionResilience` in a `frontendPreload`
111
+ * module, which is the only point early enough on that side.
112
+ *
113
+ * Does nothing but warn on a Theia too old to expose the buffer binding, so the
114
+ * package keeps one supported range rather than splitting its floor for this
115
+ * feature. Returns whether the hardening was installed, for an adopter that
116
+ * wants to branch on it.
117
+ */
118
+ function bindConnectionResilience(bind, isBound, rebind, options = {}) {
119
+ if (!(0, framed_socket_write_buffer_1.supportsConnectionResilience)(isBound)) {
120
+ (0, framed_socket_write_buffer_1.warnConnectionResilienceUnavailable)('backend');
121
+ return false;
122
+ }
123
+ bind(SessionBoundFrontendConnectionService).toSelf().inSingletonScope();
124
+ rebind(websocket_frontend_connection_service_1.WebsocketFrontendConnectionService).toService(SessionBoundFrontendConnectionService);
125
+ rebind(socket_write_buffer_1.SocketWriteBuffer).toDynamicValue(() => (0, framed_socket_write_buffer_1.createFramedSocketWriteBuffer)(options.bufferBytes));
126
+ return true;
127
+ }
128
+ //# sourceMappingURL=session-bound-frontend-connection-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-bound-frontend-connection-service.js","sourceRoot":"","sources":["../../src/node/session-bound-frontend-connection-service.ts"],"names":[],"mappings":";AAAA;;;;;;;kFAOkF;;;;;;;;;AAqIlF,4DAcC;AAjJD,kHAA4G;AAC5G,8FAAyF;AACzF,gIAA0H;AAC1H,4DAA2E;AAE3E,qFAK8C;AAqB9C;;;;;;;;;;;;;;;;;;GAkBG;AAEI,IAAM,qCAAqC,GAA3C,MAAM,qCAAsC,SAAQ,0EAAkC;IAC1F,wFAAwF;IACrE,QAAQ,GAAG,IAAI,GAAG,EAAiD,CAAC;IACvF,qFAAqF;IAClE,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;IAEnD,sBAAsB,CAAC,MAAsB,EAAE,OAAwB,EAAE,UAAkB;QACjG,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,EAAE,EAAE,QAAQ,EAAE,MAAM,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAE5E,MAAM,aAAa,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACxD,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACrC,MAAM,SAAS,GAAG,QAAQ,CAAC,CAAC,CAAC,sBAAsB,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5E,MAAM,GAAG,GAAG,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,IAAI,CAAC,GAAG,EAAE,GAAG,a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1C,IAAA,gEAAmC,EAAC,SAAS,CAAC,CAAC;QAC/C,OAAO,KAAK,CAAC;IAChB,CAAC;IACD,IAAI,CAAC,qCAAqC,CAAC,CAAC,MAAM,EAAE,CAAC,gBAAgB,EAAE,CAAC;IACxE,MAAM,CAAC,0EAAkC,CAAC,CAAC,SAAS,CAAC,qCAAqC,CAAC,CAAC;IAC5F,MAAM,CAAC,uCAAiB,CAAC,CAAC,cAAc,CAAC,GAAG,EAAE,CAAC,IAAA,0DAA6B,EAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC;IACnG,OAAO,IAAI,CAAC;AACf,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hydranium/client-theia",
3
- "version": "1.0.0-next.9",
3
+ "version": "1.0.0-next.90",
4
4
  "description": "Cross-head Theia client primitives shared by the hydranium protocol heads. Provides the socket-forwarding connection-handler base that the data-server and GLSP Theia integrations subclass, plus the preference-driven Output-channel logger; carries no head-specific dependency.",
5
5
  "keywords": [
6
6
  "hydranium",
@@ -36,6 +36,14 @@
36
36
  "types": "./lib/browser/index.d.ts",
37
37
  "default": "./lib/browser/index.js"
38
38
  },
39
+ "./common": {
40
+ "types": "./lib/common/index.d.ts",
41
+ "default": "./lib/common/index.js"
42
+ },
43
+ "./lib/common": {
44
+ "types": "./lib/common/index.d.ts",
45
+ "default": "./lib/common/index.js"
46
+ },
39
47
  "./node": {
40
48
  "types": "./lib/node/index.d.ts",
41
49
  "default": "./lib/node/index.js"
@@ -70,9 +78,9 @@
70
78
  "watch": "tsc -b -w --preserveWatchOutput"
71
79
  },
72
80
  "devDependencies": {
73
- "@hydranium/protocol": "1.0.0-next.9",
74
- "@theia/core": "^1.71.0",
75
- "@theia/output": "^1.71.0",
81
+ "@hydranium/protocol": "1.0.0-next.90",
82
+ "@theia/core": "^1.70.0",
83
+ "@theia/output": "^1.70.0",
76
84
  "@types/node": "^22.0.0",
77
85
  "inversify": "6.2.2",
78
86
  "reflect-metadata": "0.2.2",
@@ -80,9 +88,9 @@
80
88
  "typescript": "^5.8.0"
81
89
  },
82
90
  "peerDependencies": {
83
- "@hydranium/protocol": "1.0.0-next.9",
84
- "@theia/core": "^1.71.0",
85
- "@theia/output": "^1.71.0",
91
+ "@hydranium/protocol": "1.0.0-next.90",
92
+ "@theia/core": "^1.70.0",
93
+ "@theia/output": "^1.70.0",
86
94
  "inversify": "^6.0.0"
87
95
  },
88
96
  "engines": {
@@ -91,5 +99,6 @@
91
99
  "publishConfig": {
92
100
  "access": "public"
93
101
  },
102
+ "//peerDependencies": "@theia/core stays at 1.70 here, matching the sibling Theia packages, even though the connection-resilience bindings need 1.71: Theia only began binding `SocketWriteBuffer` then, and before that each connection built one privately, so there is no binding to rebind. Rather than split the package's floor for one feature, `bindConnectionResilience` probes for that binding and warns instead of installing when it is absent — a capability check rather than a version parse, so it answers about the container in front of it. Everything else the feature touches exists at 1.70, and the emitted declarations deliberately name no type that 1.70 lacks, so the package still compiles there. Verified by unpacking 1.70, 1.71 and 1.72, not inferred from a changelog.",
94
103
  "//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."
95
104
  }
@@ -0,0 +1,142 @@
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 { MessageService, nls } from '@theia/core';
11
+ import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application-contribution';
12
+ import { ConnectionStatus, ConnectionStatusService } from '@theia/core/lib/browser/connection-status-service';
13
+ import { WebSocketConnectionSource } from '@theia/core/lib/browser/messaging/ws-connection-source';
14
+ import { inject, injectable, type interfaces } from '@theia/core/shared/inversify';
15
+ import { type ConnectionBufferOverflow } from '../common/framed-socket-write-buffer';
16
+ import { ChannelLogger } from './channel-logger';
17
+ import { SessionAwareConnectionSource } from './session-aware-connection-source';
18
+
19
+ /**
20
+ * Records the browser side of the websocket lifecycle into the adopter's Output
21
+ * channel, and tells the user the one thing they cannot recover from on their
22
+ * own.
23
+ *
24
+ * Theia reports an outage only as an "Offline" status-bar item, which cannot
25
+ * distinguish a plain network drop from the server having stopped answering on a
26
+ * socket that is still up. The latter is what a connection defect looks like
27
+ * from here, so the two are logged differently — that distinction is what says
28
+ * whether reopening an editor helps or only a reload does.
29
+ *
30
+ * Purely observational apart from the overflow message: nothing here changes how
31
+ * the connection behaves.
32
+ */
33
+ @injectable()
34
+ export class ConnectionDiagnosticsContribution implements FrontendApplicationContribution {
35
+ @inject(WebSocketConnectionSource) protected readonly connectionSource: WebSocketConnectionSource;
36
+ @inject(ConnectionStatusService) protected readonly connectionStatus: ConnectionStatusService;
37
+ @inject(ChannelLogger) protected readonly logger: ChannelLogger;
38
+ @inject(MessageService) protected readonly messageService: MessageService;
39
+
40
+ /** Main channels created so far; more than one means the server did not recognise this frontend. */
41
+ protected channelCount = 0;
42
+ protected socketClosedAt?: number;
43
+ protected offlineAt?: number;
44
+
45
+ initialize(): void {
46
+ this.connectionSource.onSocketDidOpen(() => this.handleSocketOpen());
47
+ this.connectionSource.onSocketDidClose(() => this.handleSocketClose());
48
+ this.connectionSource.onConnectionDidOpen(() => this.handleChannelOpen());
49
+ this.connectionStatus.onStatusChange(status => this.handleStatusChange(status));
50
+ if (this.connectionSource instanceof SessionAwareConnectionSource) {
51
+ this.connectionSource.onBufferOverflow(overflow => this.handleBufferOverflow(overflow));
52
+ }
53
+ // The socket is opened by the preloader, before this contribution exists, so the first
54
+ // `onSocketDidOpen` has already fired; state the current situation instead.
55
+ this.logger.info(`diagnostics active; socket ${this.socketId()}, backend ${this.statusName(this.connectionStatus.currentStatus)}`);
56
+ }
57
+
58
+ protected handleSocketOpen(): void {
59
+ const downFor = this.socketClosedAt === undefined ? '' : ` after ${Date.now() - this.socketClosedAt} ms down`;
60
+ this.socketClosedAt = undefined;
61
+ this.logger.info(`websocket connected: socket ${this.socketId()}${downFor}`);
62
+ }
63
+
64
+ protected handleSocketClose(): void {
65
+ this.socketClosedAt = Date.now();
66
+ this.logger.info(`websocket disconnected: socket ${this.socketId()}; outgoing messages are buffered until it returns`);
67
+ }
68
+
69
+ /**
70
+ * A second channel means the reconnect was refused and the session discarded.
71
+ * Only reachable with `reloadOnReconnect` off — with it on, Theia reloads the
72
+ * page instead of opening another channel.
73
+ */
74
+ protected handleChannelOpen(): void {
75
+ this.channelCount++;
76
+ if (this.channelCount === 1) {
77
+ this.logger.info(`initial channel opened on socket ${this.socketId()}`);
78
+ return;
79
+ }
80
+ this.logger.warn(
81
+ `new channel #${this.channelCount} on socket ${this.socketId()}: the backend did not recognise this frontend, ` +
82
+ 'so its session was discarded and every pending request rejected'
83
+ );
84
+ }
85
+
86
+ protected handleStatusChange(status: ConnectionStatus): void {
87
+ if (status === ConnectionStatus.ONLINE) {
88
+ const offlineFor = this.offlineAt === undefined ? '' : ` after ${Date.now() - this.offlineAt} ms`;
89
+ this.offlineAt = undefined;
90
+ this.logger.info(`backend reachable again${offlineFor}`);
91
+ return;
92
+ }
93
+ this.offlineAt = Date.now();
94
+ const socket = this.connectionSource.socket;
95
+ if (socket?.connected) {
96
+ this.logger.warn(
97
+ `backend stopped answering while socket ${socket.id} is still connected: nothing this session sends will ` +
98
+ 'arrive, and socket.io will not reconnect on its own. Reload the page to recover.'
99
+ );
100
+ return;
101
+ }
102
+ this.logger.info(`backend unreachable; websocket is disconnected (socket ${this.socketId()})`);
103
+ }
104
+
105
+ /**
106
+ * The outage outlasted what the buffer can hold, so changes made from here on
107
+ * are being thrown away rather than queued. Reconnecting resumes sending but
108
+ * cannot bring those back, which leaves the editor disagreeing with the
109
+ * server — and without a message the user would see nothing but an editor
110
+ * that has quietly stopped saving, so say it plainly.
111
+ */
112
+ protected handleBufferOverflow(overflow: ConnectionBufferOverflow): void {
113
+ this.logger.error(`buffer full at ${overflow.maxBytes} bytes holding ${overflow.messages} message(s)`);
114
+ this.messageService.error(
115
+ nls.localize(
116
+ 'hydranium/connection/offlineLimitReached',
117
+ 'Disconnected for too long: recent changes were not sent. Reload the page before continuing.'
118
+ )
119
+ );
120
+ }
121
+
122
+ protected socketId(): string {
123
+ return this.connectionSource.socket?.id ?? WebSocketConnectionSource.NO_CONNECTION;
124
+ }
125
+
126
+ protected statusName(status: ConnectionStatus): string {
127
+ return status === ConnectionStatus.ONLINE ? 'online' : 'offline';
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Bind {@link ConnectionDiagnosticsContribution} as a `FrontendApplicationContribution`.
133
+ *
134
+ * Needs a {@link ChannelLogger} binding, so call it from a module that has also
135
+ * called `bindChannelLogger`. Unlike `bindConnectionResilience` this belongs in a
136
+ * normal frontend module: it only observes, so it has no reason to run during
137
+ * preload, and `MessageService` is not available that early.
138
+ */
139
+ export function bindConnectionDiagnostics(bind: interfaces.Bind): void {
140
+ bind(ConnectionDiagnosticsContribution).toSelf().inSingletonScope();
141
+ bind(FrontendApplicationContribution).toService(ConnectionDiagnosticsContribution);
142
+ }
@@ -12,3 +12,5 @@ export * from './channel-logger';
12
12
  export * from './log-level-preference';
13
13
  export * from './browser-capture';
14
14
  export * from './memory-diagnostics-contribution';
15
+ export * from './session-aware-connection-source';
16
+ export * from './connection-diagnostics-contribution';
@@ -108,7 +108,18 @@ export class LogLevelPreferenceContribution implements FrontendApplicationContri
108
108
  protected applyLevel(): void {
109
109
  const level = parseLogLevel(this.preferences.get<string>(this.preferenceName));
110
110
  if (level) {
111
+ const previous = Logger.getLevel();
111
112
  Logger.setLevel(level);
113
+ if (previous !== level) {
114
+ // Through Theia's `ILogger`, which has a threshold of its own and so
115
+ // is not silenced by the value just applied — the framework logger
116
+ // this preference governs would drop the line on a switch to `error`.
117
+ //
118
+ // Frontend and server announce separately: this preference reaches
119
+ // the server only if a client delivers it as configuration, so one
120
+ // line without the other says it did not.
121
+ this.logger.info(`Log level ${previous} → ${level} (preference '${this.preferenceName}')`);
122
+ }
112
123
  }
113
124
  }
114
125
  }