@hydranium/client-theia 1.0.0-next.39 → 1.0.0-next.390

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 (95) hide show
  1. package/README.md +53 -81
  2. package/lib/browser/browser-capture.js.map +1 -1
  3. package/lib/browser/channel-logger.d.ts +4 -3
  4. package/lib/browser/channel-logger.d.ts.map +1 -1
  5. package/lib/browser/channel-logger.js +11 -19
  6. package/lib/browser/channel-logger.js.map +1 -1
  7. package/lib/browser/connection-diagnostics-contribution.d.ts +73 -0
  8. package/lib/browser/connection-diagnostics-contribution.d.ts.map +1 -0
  9. package/lib/browser/connection-diagnostics-contribution.js +162 -0
  10. package/lib/browser/connection-diagnostics-contribution.js.map +1 -0
  11. package/lib/browser/connection-reporter.d.ts +57 -0
  12. package/lib/browser/connection-reporter.d.ts.map +1 -0
  13. package/lib/browser/connection-reporter.js +104 -0
  14. package/lib/browser/connection-reporter.js.map +1 -0
  15. package/lib/browser/editor-disk-sync.d.ts +142 -0
  16. package/lib/browser/editor-disk-sync.d.ts.map +1 -0
  17. package/lib/browser/editor-disk-sync.js +250 -0
  18. package/lib/browser/editor-disk-sync.js.map +1 -0
  19. package/lib/browser/hydranium-file-service.d.ts +44 -0
  20. package/lib/browser/hydranium-file-service.d.ts.map +1 -0
  21. package/lib/browser/hydranium-file-service.js +61 -0
  22. package/lib/browser/hydranium-file-service.js.map +1 -0
  23. package/lib/browser/index.d.ts +5 -0
  24. package/lib/browser/index.d.ts.map +1 -1
  25. package/lib/browser/index.js +5 -0
  26. package/lib/browser/index.js.map +1 -1
  27. package/lib/browser/log-level-preference.d.ts.map +1 -1
  28. package/lib/browser/log-level-preference.js +11 -0
  29. package/lib/browser/log-level-preference.js.map +1 -1
  30. package/lib/browser/memory-diagnostics-contribution.d.ts +1 -1
  31. package/lib/browser/memory-diagnostics-contribution.d.ts.map +1 -1
  32. package/lib/browser/memory-diagnostics-contribution.js +1 -1
  33. package/lib/browser/memory-diagnostics-contribution.js.map +1 -1
  34. package/lib/browser/session-aware-connection-source.d.ts +104 -0
  35. package/lib/browser/session-aware-connection-source.d.ts.map +1 -0
  36. package/lib/browser/session-aware-connection-source.js +193 -0
  37. package/lib/browser/session-aware-connection-source.js.map +1 -0
  38. package/lib/common/clock.d.ts +19 -0
  39. package/lib/common/clock.d.ts.map +1 -0
  40. package/lib/common/clock.js +13 -0
  41. package/lib/common/clock.js.map +1 -0
  42. package/lib/common/connection-resilience-options.d.ts +30 -0
  43. package/lib/common/connection-resilience-options.d.ts.map +1 -0
  44. package/lib/common/connection-resilience-options.js +11 -0
  45. package/lib/common/connection-resilience-options.js.map +1 -0
  46. package/lib/common/framed-socket-write-buffer.d.ts +173 -0
  47. package/lib/common/framed-socket-write-buffer.d.ts.map +1 -0
  48. package/lib/common/framed-socket-write-buffer.js +293 -0
  49. package/lib/common/framed-socket-write-buffer.js.map +1 -0
  50. package/lib/common/inbound-message-sequence.d.ts +56 -0
  51. package/lib/common/inbound-message-sequence.d.ts.map +1 -0
  52. package/lib/common/inbound-message-sequence.js +98 -0
  53. package/lib/common/inbound-message-sequence.js.map +1 -0
  54. package/lib/common/index.d.ts +13 -0
  55. package/lib/common/index.d.ts.map +1 -0
  56. package/lib/common/index.js +32 -0
  57. package/lib/common/index.js.map +1 -0
  58. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts +16 -12
  59. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
  60. package/lib/node/abstract-socket-forwarding-connection-handler.js +94 -31
  61. package/lib/node/abstract-socket-forwarding-connection-handler.js.map +1 -1
  62. package/lib/node/index.d.ts +2 -0
  63. package/lib/node/index.d.ts.map +1 -1
  64. package/lib/node/index.js +2 -0
  65. package/lib/node/index.js.map +1 -1
  66. package/lib/node/session-bound-frontend-connection-service.d.ts +122 -0
  67. package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
  68. package/lib/node/session-bound-frontend-connection-service.js +236 -0
  69. package/lib/node/session-bound-frontend-connection-service.js.map +1 -0
  70. package/lib/node/socket-channel-forwarder.d.ts +54 -0
  71. package/lib/node/socket-channel-forwarder.d.ts.map +1 -0
  72. package/lib/node/socket-channel-forwarder.js +95 -0
  73. package/lib/node/socket-channel-forwarder.js.map +1 -0
  74. package/lib/testing/stub-inversify-context.js.map +1 -1
  75. package/lib/testing/stub-output-channel.js.map +1 -1
  76. package/package.json +33 -34
  77. package/src/browser/browser-capture.ts +1 -1
  78. package/src/browser/channel-logger.ts +11 -19
  79. package/src/browser/connection-diagnostics-contribution.ts +146 -0
  80. package/src/browser/connection-reporter.ts +121 -0
  81. package/src/browser/editor-disk-sync.ts +253 -0
  82. package/src/browser/hydranium-file-service.ts +56 -0
  83. package/src/browser/index.ts +5 -0
  84. package/src/browser/log-level-preference.ts +11 -0
  85. package/src/browser/memory-diagnostics-contribution.ts +4 -3
  86. package/src/browser/session-aware-connection-source.ts +205 -0
  87. package/src/common/clock.ts +20 -0
  88. package/src/common/connection-resilience-options.ts +30 -0
  89. package/src/common/framed-socket-write-buffer.ts +345 -0
  90. package/src/common/inbound-message-sequence.ts +102 -0
  91. package/src/common/index.ts +16 -0
  92. package/src/node/abstract-socket-forwarding-connection-handler.ts +85 -36
  93. package/src/node/index.ts +2 -0
  94. package/src/node/session-bound-frontend-connection-service.ts +264 -0
  95. package/src/node/socket-channel-forwarder.ts +101 -0
@@ -0,0 +1,146 @@
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 { type Stopwatch, SystemClock } from '@hydranium/protocol';
11
+ import { MessageService, nls } from '@theia/core';
12
+ import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application-contribution';
13
+ import { ConnectionStatus, ConnectionStatusService } from '@theia/core/lib/browser/connection-status-service';
14
+ import { WebSocketConnectionSource } from '@theia/core/lib/browser/messaging/ws-connection-source';
15
+ import { inject, injectable, optional, type interfaces } from '@theia/core/shared/inversify';
16
+ import { Clock } from '../common/clock';
17
+ import { type ConnectionBufferOverflow } from '../common/framed-socket-write-buffer';
18
+ import { ChannelLogger } from './channel-logger';
19
+ import { SessionAwareConnectionSource } from './session-aware-connection-source';
20
+
21
+ /**
22
+ * Records the browser side of the websocket lifecycle into the adopter's Output
23
+ * channel, and tells the user the one thing they cannot recover from on their
24
+ * own.
25
+ *
26
+ * Theia reports an outage only as an "Offline" status-bar item, which cannot
27
+ * distinguish a plain network drop from the server having stopped answering on a
28
+ * socket that is still up. The latter is what a connection defect looks like
29
+ * from here, so the two are logged differently — that distinction is what says
30
+ * whether reopening an editor helps or only a reload does.
31
+ *
32
+ * Purely observational apart from the overflow message: nothing here changes how
33
+ * the connection behaves.
34
+ */
35
+ @injectable()
36
+ export class ConnectionDiagnosticsContribution implements FrontendApplicationContribution {
37
+ @inject(WebSocketConnectionSource) protected readonly connectionSource: WebSocketConnectionSource;
38
+ @inject(ConnectionStatusService) protected readonly connectionStatus: ConnectionStatusService;
39
+ @inject(ChannelLogger) protected readonly logger: ChannelLogger;
40
+ @inject(MessageService) protected readonly messageService: MessageService;
41
+ /** Times the outages the log reports: the container's {@link Clock}, or a `SystemClock`. */
42
+ @inject(Clock) @optional() protected readonly clock: Clock = new SystemClock();
43
+
44
+ /** Main channels created so far; more than one means the server did not recognise this frontend. */
45
+ protected channelCount = 0;
46
+ protected sinceSocketClosed?: Stopwatch;
47
+ protected sinceOffline?: Stopwatch;
48
+
49
+ initialize(): void {
50
+ this.connectionSource.onSocketDidOpen(() => this.handleSocketOpen());
51
+ this.connectionSource.onSocketDidClose(() => this.handleSocketClose());
52
+ this.connectionSource.onConnectionDidOpen(() => this.handleChannelOpen());
53
+ this.connectionStatus.onStatusChange(status => this.handleStatusChange(status));
54
+ if (this.connectionSource instanceof SessionAwareConnectionSource) {
55
+ this.connectionSource.onBufferOverflow(overflow => this.handleBufferOverflow(overflow));
56
+ }
57
+ // The socket is opened by the preloader, before this contribution exists, so the first
58
+ // `onSocketDidOpen` has already fired; state the current situation instead.
59
+ this.logger.debug(`diagnostics active; socket ${this.socketId()}, backend ${this.statusName(this.connectionStatus.currentStatus)}`);
60
+ }
61
+
62
+ protected handleSocketOpen(): void {
63
+ const downFor = this.sinceSocketClosed === undefined ? '' : ` after ${Math.round(this.sinceSocketClosed.elapsedMs)} ms down`;
64
+ this.sinceSocketClosed = undefined;
65
+ this.logger.info(`websocket connected: socket ${this.socketId()}${downFor}`);
66
+ }
67
+
68
+ protected handleSocketClose(): void {
69
+ this.sinceSocketClosed = this.clock.stopwatch();
70
+ this.logger.info(`websocket disconnected: socket ${this.socketId()}; outgoing messages are buffered until it returns`);
71
+ }
72
+
73
+ /**
74
+ * A second channel means the reconnect was refused and the session discarded.
75
+ * Only reachable with `reloadOnReconnect` off — with it on, Theia reloads the
76
+ * page instead of opening another channel.
77
+ */
78
+ protected handleChannelOpen(): void {
79
+ this.channelCount++;
80
+ if (this.channelCount === 1) {
81
+ this.logger.debug(`initial channel opened on socket ${this.socketId()}`);
82
+ return;
83
+ }
84
+ this.logger.warn(
85
+ `new channel #${this.channelCount} on socket ${this.socketId()}: the backend did not recognise this frontend, ` +
86
+ 'so its session was discarded and every pending request rejected'
87
+ );
88
+ }
89
+
90
+ protected handleStatusChange(status: ConnectionStatus): void {
91
+ if (status === ConnectionStatus.ONLINE) {
92
+ const offlineFor = this.sinceOffline === undefined ? '' : ` after ${Math.round(this.sinceOffline.elapsedMs)} ms`;
93
+ this.sinceOffline = undefined;
94
+ this.logger.info(`backend reachable again${offlineFor}`);
95
+ return;
96
+ }
97
+ this.sinceOffline = this.clock.stopwatch();
98
+ const socket = this.connectionSource.socket;
99
+ if (socket?.connected) {
100
+ this.logger.warn(
101
+ `backend stopped answering while socket ${socket.id} is still connected: nothing this session sends will ` +
102
+ 'arrive, and socket.io will not reconnect on its own. Reload the page to recover.'
103
+ );
104
+ return;
105
+ }
106
+ this.logger.info(`backend unreachable; websocket is disconnected (socket ${this.socketId()})`);
107
+ }
108
+
109
+ /**
110
+ * The outage outlasted what the buffer can hold, so changes made from here on
111
+ * are being thrown away rather than queued. Reconnecting resumes sending but
112
+ * cannot bring those back, which leaves the editor disagreeing with the
113
+ * server — and without a message the user would see nothing but an editor
114
+ * that has quietly stopped saving, so say it plainly.
115
+ */
116
+ protected handleBufferOverflow(overflow: ConnectionBufferOverflow): void {
117
+ this.logger.error(`buffer full at ${overflow.maxBytes} bytes holding ${overflow.messages} message(s)`);
118
+ this.messageService.error(
119
+ nls.localize(
120
+ 'hydranium/connection/offlineLimitReached',
121
+ 'Disconnected for too long: recent changes were not sent. Reload the page before continuing.'
122
+ )
123
+ );
124
+ }
125
+
126
+ protected socketId(): string {
127
+ return this.connectionSource.socket?.id ?? WebSocketConnectionSource.NO_CONNECTION;
128
+ }
129
+
130
+ protected statusName(status: ConnectionStatus): string {
131
+ return status === ConnectionStatus.ONLINE ? 'online' : 'offline';
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Bind {@link ConnectionDiagnosticsContribution} as a `FrontendApplicationContribution`.
137
+ *
138
+ * Needs a {@link ChannelLogger} binding, so call it from a module that has also
139
+ * called `bindChannelLogger`. Unlike `bindConnectionResilience` this belongs in a
140
+ * normal frontend module: it only observes, so it has no reason to run during
141
+ * preload, and `MessageService` is not available that early.
142
+ */
143
+ export function bindConnectionDiagnostics(bind: interfaces.Bind): void {
144
+ bind(ConnectionDiagnosticsContribution).toSelf().inSingletonScope();
145
+ bind(FrontendApplicationContribution).toService(ConnectionDiagnosticsContribution);
146
+ }
@@ -0,0 +1,121 @@
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, type Progress } from '@theia/core';
11
+ import { inject, injectable, type interfaces } from '@theia/core/shared/inversify';
12
+
13
+ /** What a head connects to, as the whole sentences reported about it. */
14
+ export interface ConnectionTarget {
15
+ readonly connectingMessage: string;
16
+ readonly connectedMessage: string;
17
+ }
18
+
19
+ /** One connection attempt; it reports exactly one end. */
20
+ export interface ConnectionAttempt {
21
+ connected(): void;
22
+ /** Ends the attempt with nothing to report, as when its head is disposed
23
+ * or a newer attempt takes over. */
24
+ cancelled(): void;
25
+ /**
26
+ * `message` is the whole sentence to report. `retry`, when given, starts a
27
+ * fresh attempt at once; a head without one keeps retrying on its own.
28
+ */
29
+ failed(message: string, retry?: () => void): void;
30
+ }
31
+
32
+ /**
33
+ * How a head's connection attempts reach the user. A head calls
34
+ * {@link connecting} for every attempt, a reconnect included, and keeps the
35
+ * attempt's retries and bounds itself; this decides only what is shown. Rebind
36
+ * the slot to show nothing, or something other than notifications.
37
+ */
38
+ export interface ConnectionReporter {
39
+ connecting(target: ConnectionTarget): ConnectionAttempt;
40
+ }
41
+ export const ConnectionReporter = Symbol('ConnectionReporter');
42
+
43
+ /**
44
+ * Reports through Theia notifications: an attempt still running after
45
+ * {@link connectingNoticeDelayMs} shows its progress, and an attempt ends in at
46
+ * most one notification. A failure is shown once per target until it connects
47
+ * again, so a head that keeps retrying does not raise one per attempt.
48
+ */
49
+ @injectable()
50
+ export class DefaultConnectionReporter implements ConnectionReporter {
51
+ @inject(MessageService) protected readonly messageService!: MessageService;
52
+
53
+ protected readonly connectingNoticeDelayMs: number = 3_000;
54
+ /** Targets whose last reported attempt failed. */
55
+ protected readonly failing = new Set<ConnectionTarget>();
56
+
57
+ connecting(target: ConnectionTarget): ConnectionAttempt {
58
+ let progress: Promise<Progress> | undefined;
59
+ const notice = this.failing.has(target)
60
+ ? undefined
61
+ : setTimeout(() => (progress = this.showConnecting(target)), this.connectingNoticeDelayMs);
62
+ let settled = false;
63
+ const settle = (): boolean => {
64
+ if (settled) {
65
+ return false;
66
+ }
67
+ settled = true;
68
+ clearTimeout(notice);
69
+ void progress?.then(shown => shown.cancel());
70
+ return true;
71
+ };
72
+ return {
73
+ connected: () => {
74
+ if (settle() && (this.failing.delete(target) || progress)) {
75
+ this.showConnected(target);
76
+ }
77
+ },
78
+ cancelled: () => {
79
+ settle();
80
+ },
81
+ failed: (message, retry) => {
82
+ if (settle() && !this.failing.has(target)) {
83
+ this.failing.add(target);
84
+ void this.showFailed(target, message, retry);
85
+ }
86
+ }
87
+ };
88
+ }
89
+
90
+ protected showConnecting(target: ConnectionTarget): Promise<Progress> {
91
+ return this.messageService.showProgress({ text: target.connectingMessage });
92
+ }
93
+
94
+ protected showConnected(target: ConnectionTarget): void {
95
+ this.messageService.info(target.connectedMessage);
96
+ }
97
+
98
+ protected async showFailed(target: ConnectionTarget, message: string, retry?: () => void): Promise<void> {
99
+ if (!retry) {
100
+ this.messageService.error(message);
101
+ return;
102
+ }
103
+ const label = this.retryLabel();
104
+ if ((await this.messageService.error(message, label)) === label) {
105
+ // The retried attempt reports afresh, progress included.
106
+ this.failing.delete(target);
107
+ retry();
108
+ }
109
+ }
110
+
111
+ protected retryLabel(): string {
112
+ return nls.localize('hydranium/client-theia/connection-retry', 'Retry');
113
+ }
114
+ }
115
+
116
+ /** Bind {@link DefaultConnectionReporter} unless the slot is bound already; every head calls this. */
117
+ export function bindConnectionReporter(bind: interfaces.Bind, isBound: interfaces.IsBound): void {
118
+ if (!isBound(ConnectionReporter)) {
119
+ bind(ConnectionReporter).to(DefaultConnectionReporter).inSingletonScope();
120
+ }
121
+ }
@@ -0,0 +1,253 @@
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 { SystemClock, TIMED_OUT } from '@hydranium/protocol';
11
+ import { FrontendApplicationContribution } from '@theia/core/lib/browser/frontend-application-contribution';
12
+ import { ILogger } from '@theia/core/lib/common/logger';
13
+ import URI from '@theia/core/lib/common/uri';
14
+ import { inject, injectable, optional, type interfaces } from '@theia/core/shared/inversify';
15
+ import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
16
+ import type { EditorWidget } from '@theia/editor/lib/browser/editor-widget';
17
+ import type { FileResourceVersion } from '@theia/filesystem/lib/browser/file-resource';
18
+ import { FileService, type TextFileContent } from '@theia/filesystem/lib/browser/file-service';
19
+ import { Clock } from '../common/clock';
20
+ import { HydraniumFileService } from './hydranium-file-service';
21
+
22
+ /**
23
+ * The members of Theia's Monaco editor model {@link EditorDiskSync} reads and
24
+ * resets. `contentChanges`, `resourceVersion` and `run` are `protected` there,
25
+ * so {@link isResyncableEditorDocument} checks for them at runtime: a Theia
26
+ * that renames them yields a document it refuses, and the sync then leaves it
27
+ * alone.
28
+ */
29
+ export interface ResyncableEditorDocument {
30
+ readonly uri: string;
31
+ readonly dirty: boolean;
32
+ getText(): string;
33
+ revert(options: { soft: boolean }): Promise<void>;
34
+ /** The edits the next save applies to the file, in place of the whole text. */
35
+ readonly contentChanges: unknown[];
36
+ /** The file version the next save expects to find on disk. */
37
+ resourceVersion: FileResourceVersion | undefined;
38
+ /** Queue `operation` behind the model's saves and syncs in progress. */
39
+ run(operation: () => Promise<void>): Promise<void>;
40
+ /** Awaited by each save before it takes the pending edits. */
41
+ onModelWillSaveModel(listener: () => Promise<void>): { dispose(): void };
42
+ }
43
+
44
+ /** Whether `document` carries the members of {@link ResyncableEditorDocument}. */
45
+ export function isResyncableEditorDocument(document: object): document is ResyncableEditorDocument {
46
+ return (
47
+ 'uri' in document &&
48
+ typeof document.uri === 'string' &&
49
+ 'dirty' in document &&
50
+ 'getText' in document &&
51
+ typeof document.getText === 'function' &&
52
+ 'revert' in document &&
53
+ typeof document.revert === 'function' &&
54
+ 'contentChanges' in document &&
55
+ Array.isArray(document.contentChanges) &&
56
+ 'resourceVersion' in document &&
57
+ 'run' in document &&
58
+ typeof document.run === 'function' &&
59
+ 'onModelWillSaveModel' in document &&
60
+ typeof document.onModelWillSaveModel === 'function'
61
+ );
62
+ }
63
+
64
+ /**
65
+ * Keeps a dirty editor's save from applying edits its file already holds, as
66
+ * the file does once the server saves a document the editor shows unsaved.
67
+ *
68
+ * Theia keeps such an editor dirty, and its next save corrupts the file: the
69
+ * save applies the editor's pending edits to the file rather than writing the
70
+ * whole text, and the file already holds them, so each is applied twice.
71
+ * Theia's check that the file has not changed since the editor read it passes
72
+ * whenever the new file has the old one's size, so no conflict is reported. A
73
+ * revert alone keeps the pending edits.
74
+ *
75
+ * Before each save of the editor it reads the file. When the file holds the
76
+ * text the buffer held as the save began, it drops the edits pending then and
77
+ * has the save expect the file's version, so the save writes only the edits
78
+ * made after that point, a save participant's included, onto the file as it
79
+ * is. The save is not cancelled: it completes and is reported as saved. Save
80
+ * All relies on this check, since it saves a diagram and then an editor on the
81
+ * same file at once, before the file watcher has reported the diagram's write.
82
+ * The buffer is taken when the save calls its will-save listeners. Theia runs
83
+ * its save participants one after another, each behind an await, and its
84
+ * first one awaits before it edits, so none has changed the buffer by then. A
85
+ * participant ordered ahead of it that edits before its first await makes the
86
+ * file and the taken text differ, and the save applies every edit again.
87
+ *
88
+ * On each change the file watcher reports, it marks the editor clean when the
89
+ * file holds exactly its buffer. The file is compared with the buffer after
90
+ * it has been read, and the editor is marked in the same step, so a keystroke
91
+ * made while the file was read leaves the editor dirty. This sync waits behind
92
+ * a save in flight: that save drops the edits it sent from the pending ones
93
+ * when it finishes, and a sync before then would have it drop the edits typed
94
+ * meanwhile.
95
+ *
96
+ * An editor whose file holds neither text is left to Theia's own save,
97
+ * same-size gap included, and so is one whose file cannot be read within
98
+ * {@link readTimeoutMs}, or whose check throws.
99
+ *
100
+ * Bound by {@link bindEditorDiskSync}.
101
+ */
102
+ @injectable()
103
+ export class EditorDiskSync implements FrontendApplicationContribution {
104
+ @inject(FileService) protected readonly fileService!: FileService;
105
+ @inject(EditorManager) protected readonly editorManager!: EditorManager;
106
+ @inject(ILogger) protected readonly logger!: ILogger;
107
+ /** Times {@link readTimeoutMs}: the container's {@link Clock}, or a `SystemClock`. */
108
+ @inject(Clock) @optional() protected readonly clock: Clock = new SystemClock();
109
+ /** Whether an editor's document has failed {@link isResyncableEditorDocument}; warned of once. */
110
+ protected warnedUnsyncable = false;
111
+ /**
112
+ * How long a check waits for the file. The editor's save, and every later
113
+ * save and sync of that editor, waits for the check.
114
+ */
115
+ protected readTimeoutMs = 1_000;
116
+
117
+ onStart(): void {
118
+ this.fileService.onDidFilesChange(event => {
119
+ for (const change of event.changes) {
120
+ this.checkFile(change.resource);
121
+ }
122
+ });
123
+ this.editorManager.onCreated(widget => this.guardSaves(widget));
124
+ for (const widget of this.editorManager.all) {
125
+ this.guardSaves(widget);
126
+ }
127
+ }
128
+
129
+ /** Check `widget`'s document before each of its saves, for as long as the widget lives. */
130
+ protected guardSaves(widget: EditorWidget): void {
131
+ const document = this.resyncable(widget.editor.document);
132
+ if (document) {
133
+ const registration = document.onModelWillSaveModel(() => this.isolate(() => this.dropChangesOnDisk(document)));
134
+ widget.onDidDispose(() => registration.dispose());
135
+ }
136
+ }
137
+
138
+ /** Check each dirty document an editor shows on `uri`, behind that document's save in flight. */
139
+ protected checkFile(uri: URI): void {
140
+ for (const document of this.dirtyDocuments(uri)) {
141
+ void document.run(() => this.isolate(() => this.syncIfOnDisk(document)));
142
+ }
143
+ }
144
+
145
+ /** Read the file of `document` if it is dirty, and sync it if the file holds its buffer. */
146
+ protected async syncIfOnDisk(document: ResyncableEditorDocument): Promise<void> {
147
+ if (!document.dirty) {
148
+ return;
149
+ }
150
+ const content = await this.readFile(document);
151
+ if (content && document.getText() === content.value) {
152
+ this.syncFromDisk(document, { etag: content.etag, mtime: content.mtime, encoding: content.encoding });
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Before a save of `document`, drop the edits pending now if its file holds
158
+ * the buffer as it is now, and take the file's version. The buffer and the
159
+ * count are taken before the first await, while the save is still calling
160
+ * its will-save listeners; an edit made after that stays pending, and the
161
+ * save writes it onto the file.
162
+ */
163
+ protected async dropChangesOnDisk(document: ResyncableEditorDocument): Promise<void> {
164
+ if (!document.dirty) {
165
+ return;
166
+ }
167
+ const text = document.getText();
168
+ const pending = document.contentChanges.length;
169
+ const content = await this.readFile(document);
170
+ if (content?.value === text) {
171
+ document.contentChanges.splice(0, pending);
172
+ document.resourceVersion = { etag: content.etag, mtime: content.mtime, encoding: content.encoding };
173
+ }
174
+ }
175
+
176
+ /**
177
+ * The file of `document`, or `undefined` when it is gone, cannot be read, or
178
+ * is not read within {@link readTimeoutMs}.
179
+ */
180
+ protected async readFile(document: ResyncableEditorDocument): Promise<TextFileContent | undefined> {
181
+ const read = this.fileService.read(new URI(document.uri)).catch(() => undefined);
182
+ const content = await this.clock.raceTimer(read, this.readTimeoutMs);
183
+ return content === TIMED_OUT ? undefined : content;
184
+ }
185
+
186
+ /**
187
+ * Run `check`, and log its failure rather than pass it on. A will-save
188
+ * listener that rejects makes Theia drop the save without writing, and a
189
+ * sync that rejects goes unhandled.
190
+ */
191
+ protected async isolate(check: () => Promise<void>): Promise<void> {
192
+ try {
193
+ await check();
194
+ } catch (err: unknown) {
195
+ void this.logger.error('EditorDiskSync: checking an editor against its file failed; the editor is left as it is.', err);
196
+ }
197
+ }
198
+
199
+ /** The dirty documents open in an editor on `uri`, each once however many editors show it. */
200
+ protected dirtyDocuments(uri: URI): ResyncableEditorDocument[] {
201
+ const target = uri.toString();
202
+ const documents = new Set<ResyncableEditorDocument>();
203
+ for (const widget of this.editorManager.all) {
204
+ const document = this.resyncable(widget.editor.document);
205
+ if (document && document.uri === target && document.dirty) {
206
+ documents.add(document);
207
+ }
208
+ }
209
+ return [...documents];
210
+ }
211
+
212
+ /** `document` if it carries the members the sync resets; otherwise `undefined`, warned of once. */
213
+ protected resyncable(document: object): ResyncableEditorDocument | undefined {
214
+ if (isResyncableEditorDocument(document)) {
215
+ return document;
216
+ }
217
+ if (!this.warnedUnsyncable) {
218
+ this.warnedUnsyncable = true;
219
+ void this.logger.warn(
220
+ 'EditorDiskSync: an editor document lacks the Monaco model members the sync resets, so such editors are not synced with their files.'
221
+ );
222
+ }
223
+ return undefined;
224
+ }
225
+
226
+ /**
227
+ * Take `version` as the file `document` was last saved to, with nothing
228
+ * pending, and mark it clean. Synchronous throughout: a soft revert only
229
+ * marks the document clean, and reads nothing. The revert also cancels a
230
+ * save queued behind the sync, which would have written the same text.
231
+ */
232
+ protected syncFromDisk(document: ResyncableEditorDocument, version: FileResourceVersion): void {
233
+ document.contentChanges.splice(0, document.contentChanges.length);
234
+ document.resourceVersion = version;
235
+ void document.revert({ soft: true });
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Bind {@link EditorDiskSync} as a frontend contribution and rebind Theia's
241
+ * `FileService` to {@link HydraniumFileService}, unless `EditorDiskSync` is
242
+ * bound already. No framework module calls this, because the rebind would
243
+ * replace a frontend's own `FileService` binding. A subclass of the sync is
244
+ * rebound after this call: one bound before it skips the whole call.
245
+ */
246
+ export function bindEditorDiskSync(bind: interfaces.Bind, isBound: interfaces.IsBound, rebind: interfaces.Rebind): void {
247
+ if (isBound(EditorDiskSync)) {
248
+ return;
249
+ }
250
+ bind(EditorDiskSync).toSelf().inSingletonScope();
251
+ bind(FrontendApplicationContribution).toService(EditorDiskSync);
252
+ rebind(FileService).to(HydraniumFileService).inSingletonScope();
253
+ }
@@ -0,0 +1,56 @@
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 type URI from '@theia/core/lib/common/uri';
11
+ import { injectable } from '@theia/core/shared/inversify';
12
+ import { FileService, type UpdateTextFileOptions } from '@theia/filesystem/lib/browser/file-service';
13
+ import { ETAG_DISABLED } from '@theia/filesystem/lib/common/files';
14
+
15
+ /**
16
+ * Theia's `FileService`, refusing an incremental save once the file has
17
+ * changed since the editor read it.
18
+ *
19
+ * Theia's own check, which `write` and `update` share, passes a file whose
20
+ * mtime moved on when its size still matches the etag the editor read. That
21
+ * is safe for `write`, which replaces the file with the whole text, but
22
+ * `update` applies the editor's pending edits to the file as it is, so after a
23
+ * same-size change, the server saving those very edits included, it applies
24
+ * them a second time. Here `update` hands that check the etag with a `!`
25
+ * appended, which no file's etag can match: Theia writes an etag as the mtime
26
+ * in base 29 followed by the size in base 31, digits and lower-case letters
27
+ * only. An advanced mtime is then enough for Theia to refuse with its
28
+ * `FILE_MODIFIED_SINCE`. The editor's save then falls back to `write` with the
29
+ * whole text, which Theia checks as before: it writes when the size is
30
+ * unchanged, and asks the user otherwise. A same-size change by another
31
+ * process is therefore overwritten by that write rather than merged with the
32
+ * editor's edits. `write` is left as it is.
33
+ *
34
+ * It is the safety net behind `EditorDiskSync`, which acts only when the
35
+ * file holds the editor's buffer: a file holding some of the edits, as when a
36
+ * save participant ordered ahead of Theia's first one edits before its first
37
+ * await, is left to this check.
38
+ *
39
+ * A write within the file system's mtime resolution of the read goes unseen,
40
+ * as it does for Theia's own check. A file whose mtime moves while its text
41
+ * stays the same costs a whole-text write rather than the edits.
42
+ *
43
+ * Bound by `bindEditorDiskSync`.
44
+ */
45
+ @injectable()
46
+ export class HydraniumFileService extends FileService {
47
+ override update(
48
+ resource: URI,
49
+ changes: Parameters<FileService['update']>[1],
50
+ options: UpdateTextFileOptions
51
+ ): ReturnType<FileService['update']> {
52
+ const strict =
53
+ typeof options.etag === 'string' && options.etag !== ETAG_DISABLED ? { ...options, etag: `${options.etag}!` } : options;
54
+ return super.update(resource, changes, strict);
55
+ }
56
+ }
@@ -12,3 +12,8 @@ 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';
17
+ export * from './connection-reporter';
18
+ export * from './editor-disk-sync';
19
+ export * from './hydranium-file-service';
@@ -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
  }
@@ -11,7 +11,8 @@ import {
11
11
  formatLatencyReport,
12
12
  type DataServerDiagnosticsProtocol,
13
13
  type HostDiagnosticsProtocol,
14
- type StartProfilingArgs
14
+ type StartProfilingArgs,
15
+ describeError
15
16
  } from '@hydranium/protocol';
16
17
  import { captureBrowserRuntime, formatBrowserRuntime } from './browser-capture';
17
18
  import { CommandContribution, MessageService, nls, type Command, type CommandRegistry } from '@theia/core';
@@ -92,7 +93,7 @@ export class MemoryDiagnosticsContribution implements CommandContribution {
92
93
  /** Dimensions the profiling commands capture — the server samples only what is named. */
93
94
  protected readonly profileDimensions: StartProfilingArgs = { cpu: true, allocation: true, gc: true, eventLoopDelay: true };
94
95
  /** Window length for the "Record Performance Profile" command. */
95
- protected readonly recordDurationMs = 10_000;
96
+ protected readonly recordDurationMs: number = 10_000;
96
97
  /**
97
98
  * Label of the stop-profiling command, and of the action its start toast
98
99
  * offers. One field for both: two literals naming one command can be
@@ -454,7 +455,7 @@ export class MemoryDiagnosticsContribution implements CommandContribution {
454
455
  }
455
456
 
456
457
  protected errorMessage(error: unknown): string {
457
- return error instanceof Error ? error.message : String(error);
458
+ return describeError(error);
458
459
  }
459
460
  }
460
461