@hydranium/glsp-server 1.0.0-next.12 → 1.0.0-next.123

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 (71) hide show
  1. package/README.md +13 -2
  2. package/lib/command/hydranium-glsp-recording-command.d.ts +22 -22
  3. package/lib/command/hydranium-glsp-recording-command.d.ts.map +1 -1
  4. package/lib/command/hydranium-glsp-recording-command.js +25 -26
  5. package/lib/command/hydranium-glsp-recording-command.js.map +1 -1
  6. package/lib/launcher/hydranium-glsp-server.d.ts +4 -3
  7. package/lib/launcher/hydranium-glsp-server.d.ts.map +1 -1
  8. package/lib/launcher/hydranium-glsp-server.js +4 -3
  9. package/lib/launcher/hydranium-glsp-server.js.map +1 -1
  10. package/lib/messages/index.d.ts +24 -0
  11. package/lib/messages/index.d.ts.map +1 -0
  12. package/lib/messages/index.js +24 -0
  13. package/lib/messages/index.js.map +1 -0
  14. package/lib/node/start-glsp-server.js +1 -1
  15. package/lib/node/start-glsp-server.js.map +1 -1
  16. package/lib/state/abstract-hydranium-glsp-state.d.ts +110 -43
  17. package/lib/state/abstract-hydranium-glsp-state.d.ts.map +1 -1
  18. package/lib/state/abstract-hydranium-glsp-state.js +130 -41
  19. package/lib/state/abstract-hydranium-glsp-state.js.map +1 -1
  20. package/lib/state/full-text-hydranium-glsp-state.d.ts +6 -6
  21. package/lib/state/full-text-hydranium-glsp-state.d.ts.map +1 -1
  22. package/lib/state/full-text-hydranium-glsp-state.js +6 -10
  23. package/lib/state/full-text-hydranium-glsp-state.js.map +1 -1
  24. package/lib/state/reconcile-source-model-write.d.ts +9 -8
  25. package/lib/state/reconcile-source-model-write.d.ts.map +1 -1
  26. package/lib/state/reconcile-source-model-write.js +8 -8
  27. package/lib/state/reconcile-source-model-write.js.map +1 -1
  28. package/lib/state/reconciling-multi-document-glsp-state.d.ts +59 -59
  29. package/lib/state/reconciling-multi-document-glsp-state.d.ts.map +1 -1
  30. package/lib/state/reconciling-multi-document-glsp-state.js +84 -82
  31. package/lib/state/reconciling-multi-document-glsp-state.js.map +1 -1
  32. package/lib/state/reconciling-transfer-hydranium-glsp-state.d.ts +19 -18
  33. package/lib/state/reconciling-transfer-hydranium-glsp-state.d.ts.map +1 -1
  34. package/lib/state/reconciling-transfer-hydranium-glsp-state.js +26 -30
  35. package/lib/state/reconciling-transfer-hydranium-glsp-state.js.map +1 -1
  36. package/lib/storage/hydranium-glsp-storage.d.ts +271 -76
  37. package/lib/storage/hydranium-glsp-storage.d.ts.map +1 -1
  38. package/lib/storage/hydranium-glsp-storage.js +383 -87
  39. package/lib/storage/hydranium-glsp-storage.js.map +1 -1
  40. package/lib/storage/index.d.ts +1 -1
  41. package/lib/storage/index.js +1 -1
  42. package/lib/storage/save-delivery-policy.d.ts +46 -0
  43. package/lib/storage/save-delivery-policy.d.ts.map +1 -0
  44. package/lib/storage/{save-conflict-policy.js → save-delivery-policy.js} +7 -8
  45. package/lib/storage/save-delivery-policy.js.map +1 -0
  46. package/lib/validation/diagnostic-markers.d.ts +2 -2
  47. package/lib/validation/diagnostic-markers.d.ts.map +1 -1
  48. package/lib/validation/diagnostic-markers.js +7 -0
  49. package/lib/validation/diagnostic-markers.js.map +1 -1
  50. package/lib/validation/hydranium-glsp-model-validator.d.ts.map +1 -1
  51. package/lib/validation/hydranium-glsp-model-validator.js +1 -1
  52. package/lib/validation/hydranium-glsp-model-validator.js.map +1 -1
  53. package/package.json +17 -8
  54. package/src/command/hydranium-glsp-recording-command.ts +26 -26
  55. package/src/launcher/hydranium-glsp-server.ts +4 -3
  56. package/src/messages/index.ts +30 -0
  57. package/src/node/start-glsp-server.ts +1 -1
  58. package/src/state/abstract-hydranium-glsp-state.ts +162 -51
  59. package/src/state/full-text-hydranium-glsp-state.ts +7 -11
  60. package/src/state/reconcile-source-model-write.ts +18 -15
  61. package/src/state/reconciling-multi-document-glsp-state.ts +86 -83
  62. package/src/state/reconciling-transfer-hydranium-glsp-state.ts +27 -31
  63. package/src/storage/hydranium-glsp-storage.ts +445 -97
  64. package/src/storage/index.ts +1 -1
  65. package/src/storage/save-delivery-policy.ts +44 -0
  66. package/src/validation/diagnostic-markers.ts +10 -3
  67. package/src/validation/hydranium-glsp-model-validator.ts +3 -3
  68. package/lib/storage/save-conflict-policy.d.ts +0 -56
  69. package/lib/storage/save-conflict-policy.d.ts.map +0 -1
  70. package/lib/storage/save-conflict-policy.js.map +0 -1
  71. package/src/storage/save-conflict-policy.ts +0 -52
@@ -7,7 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { MarkersReason, SetMarkersAction } from '@eclipse-glsp/protocol';
10
+ import { MarkersReason, MessageAction, SetMarkersAction, StatusAction } from '@eclipse-glsp/protocol';
11
11
  import {
12
12
  type Action,
13
13
  ActionDispatcher,
@@ -31,16 +31,95 @@ import {
31
31
  type SourceModelStorage,
32
32
  TEMPORARY_CLIENT_ID
33
33
  } from '@eclipse-glsp/server';
34
- import { Debouncer, DisposableCollection } from '@hydranium/protocol';
34
+ import {
35
+ Debouncer,
36
+ defineMessage,
37
+ DisposableCollection,
38
+ isDuplicateClientIdError,
39
+ isSessionClosedError,
40
+ SessionClosedError
41
+ } from '@hydranium/protocol';
35
42
  import { inject, injectable, optional, postConstruct } from 'inversify';
36
43
  import { type AstNode } from '@hydranium/langium';
37
44
  import { URI } from '@hydranium/langium';
38
- import { AstDocument, type AstDocumentSavedEvent, type AstDocumentUpdatedEvent, type ServerSharedServices } from '@hydranium/core';
45
+ import {
46
+ AstDocument,
47
+ type AstDocumentSavedEvent,
48
+ type AstDocumentUpdatedEvent,
49
+ type ClientSession as ModelClientSession,
50
+ type ServerSharedServices
51
+ } from '@hydranium/core';
39
52
  import { DiagnosticSeverity } from 'vscode-languageserver-types';
40
53
  import { type AbstractHydraniumGlspState } from '../state/abstract-hydranium-glsp-state.js';
41
54
  import { type HydraniumGlspSubmissionHandler } from '../submission/hydranium-glsp-submission-handler.js';
42
55
  import { HydraniumTypes } from '../state/hydranium-shared-core-services.js';
43
- import { DEFAULT_SAVE_CONFLICT_POLICY, SaveConflictPolicy } from './save-conflict-policy.js';
56
+ import { DEFAULT_SAVE_DELIVERY_POLICY, SaveDeliveryPolicy } from './save-delivery-policy.js';
57
+
58
+ /**
59
+ * A save action arrived with nowhere to write to. A save action carries no
60
+ * request id, so it falls through to the error handler and `message` becomes
61
+ * the toast text.
62
+ *
63
+ * Rendered at the raise site rather than by a carrier method, because GLSP's
64
+ * action protocol has no slot for an identity anywhere — every member of its
65
+ * message, status and reject actions is prose or an enum, and
66
+ * `MessageAction.details` is not a substitute since it is prose populated from
67
+ * `cause?.toString?.()`, and a Theia host shows it to a user on demand. So the
68
+ * throw is the last place that still knows which message this is.
69
+ */
70
+ export const SAVE_TARGET_UNKNOWN = defineMessage(
71
+ 'hydranium/glsp-server/save-target-unknown',
72
+ 'Could not determine where to save this model'
73
+ );
74
+
75
+ /**
76
+ * A model request arrived without the source URI it is required to carry.
77
+ * Rendered at the raise site, like its save-path sibling and for the same
78
+ * reason.
79
+ */
80
+ export const SOURCE_URI_MISSING = defineMessage(
81
+ 'hydranium/glsp-server/source-uri-missing',
82
+ 'Could not open this model: the request did not say which document to load'
83
+ );
84
+
85
+ /**
86
+ * Why the canvas has stopped accepting edits.
87
+ *
88
+ * **A READONLY canvas is otherwise indistinguishable from a broken one.** The
89
+ * client's answer to {@link SetEditModeAction} is to withdraw the tool palette,
90
+ * so the surface a reader was working in silently loses the only control it had,
91
+ * with the cause — a syntax error in a document that may not even be open —
92
+ * nowhere on screen. The mode flip is the mechanism; this is the only part of it
93
+ * a user can see.
94
+ *
95
+ * Rendered at the raise site, like its two siblings above and for the same
96
+ * reason: every member of GLSP's status action is prose or an enum.
97
+ *
98
+ * It names the recovery rather than the fault, because the fault already has a
99
+ * surface — the squiggle and the problems list, both of which say WHICH
100
+ * character — and repeating it here would put a second, less precise account of
101
+ * the same error on screen. What no other surface says is that the diagram is
102
+ * waiting on it.
103
+ */
104
+ export const DIAGRAM_READONLY_PARSE_ERROR = defineMessage(
105
+ 'hydranium/glsp-server/diagram-readonly-parse-error',
106
+ 'Read-only: this document has a syntax error. Fix it to edit the diagram again.'
107
+ );
108
+
109
+ /**
110
+ * The diagram's GLSP client id is still live as another participant's client
111
+ * id once the load has waited for it to free, so the diagram does not load.
112
+ *
113
+ * Rendered at the raise site, as {@link SAVE_TARGET_UNKNOWN} is and for the
114
+ * same reason, and dispatched to the client as a message of its own: a model
115
+ * request fails as a rejection whose detail is the English cause, which no user
116
+ * sees. It names the recovery: a host that numbers its diagram clients gives a
117
+ * reopened diagram a fresh id.
118
+ */
119
+ export const DIAGRAM_SESSION_REFUSED = defineMessage(
120
+ 'hydranium/glsp-server/diagram-session-refused',
121
+ 'Could not open this diagram: its identifier is still in use by another editor. Close the diagram and open it again.'
122
+ );
44
123
 
45
124
  /** Window (ms) over which back-to-back external rebuilds collapse into one resubmit. */
46
125
  const EXTERNAL_SUBMIT_DEBOUNCE_MS = 250;
@@ -90,17 +169,24 @@ function isStructuralDiagnostic(diagnostic: unknown): boolean {
90
169
  *
91
170
  * Adopters with richer needs override the seams ({@link isStructurallyBroken},
92
171
  * {@link onParseErrorChanged}, {@link onSourceModelSettled}) rather than the
93
- * whole flow, and select a {@link SaveConflictPolicy} via the bound option to
94
- * tune how {@link saveSourceModel} reacts to a concurrent edit.
172
+ * whole flow, and select a {@link SaveDeliveryPolicy} via the bound option to
173
+ * tune how {@link saveSourceModel} delivers its result.
174
+ *
175
+ * **One client session per GLSP client session.** `init` registers the GLSP
176
+ * client id as a client session ({@link registerModelSession}) and hands it to
177
+ * the state as `modelSession`. The primary is opened through it on load, and
178
+ * every document that joins the write set as it joins
179
+ * ({@link openSecondary}); a document that leaves the write set stays open
180
+ * until the next save, so leaving never reverts the diagram's unsaved edits to
181
+ * it. Disposing the storage ends the session, which closes everything it has
182
+ * open.
95
183
  *
96
- * **Default `saveSourceModel` flow.** Delegates to `ModelService.save`, which
97
- * serialises through the language-specific `Serializer` bound at
98
- * `services.serializer.Serializer` (resolved per-URI via `ServiceRegistry`),
99
- * updates the multi-client text-document store, drives a rebuild, and writes the
100
- * result via the `WritableFileSystemProvider`. The bound
101
- * {@link SaveConflictPolicy} (default {@link DEFAULT_SAVE_CONFLICT_POLICY},
102
- * `overwrite`) decides the based-on-version guard, await-vs-fire-and-forget, and
103
- * failure handling.
184
+ * **Default `saveSourceModel` flow.** Flushes the stored text of every
185
+ * document the diagram's session has open via `AstDocumentManager.save`, with
186
+ * no serializer in the path — the update path already put the settled text in
187
+ * the store. The bound {@link SaveDeliveryPolicy} (default
188
+ * {@link DEFAULT_SAVE_DELIVERY_POLICY}, `await`) decides
189
+ * await-vs-fire-and-forget and failure handling.
104
190
  *
105
191
  * **tempId filter.** GLSP's `DefaultGlobalActionProvider` spins up a
106
192
  * throwaway per-diagram-type container with upstream's {@link TEMPORARY_CLIENT_ID}
@@ -111,9 +197,9 @@ function isStructuralDiagnostic(diagnostic: unknown): boolean {
111
197
  * **Lifecycle ordering.** `init` runs after DI resolution and parks the
112
198
  * secondary-write-set watch, which outlives any single load.
113
199
  * {@link sessionDisposed} calls {@link dispose}, which drains
114
- * {@link toDispose} idempotently. Every transient subscription created in
115
- * {@link doLoadSourceModel} is parked on {@link toDispose} so the drain catches
116
- * them on client-detach.
200
+ * {@link toDispose} idempotently and then ends the client session. Every
201
+ * transient subscription created in {@link doLoadSourceModel} is parked on
202
+ * {@link toDispose} so the drain catches them on client-detach.
117
203
  */
118
204
  @injectable()
119
205
  export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
@@ -137,14 +223,13 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
137
223
  @inject(ModelValidator) @optional() protected readonly modelValidator?: ModelValidator;
138
224
 
139
225
  /**
140
- * Selected {@link SaveConflictPolicy} for {@link saveSourceModel}. Bind the
141
- * {@link SaveConflictPolicy} token in a `DiagramModule` to choose a policy;
142
- * left unbound it resolves to {@link DEFAULT_SAVE_CONFLICT_POLICY}
143
- * (`overwrite`, last-write-wins). Read via {@link saveConflictPolicy} so the
144
- * fallback is applied even when inversify injects `undefined` for an unbound
145
- * `@optional()` member.
226
+ * Selected {@link SaveDeliveryPolicy} for {@link saveSourceModel}. Bind the
227
+ * {@link SaveDeliveryPolicy} token in a `DiagramModule` to choose a policy;
228
+ * left unbound it resolves to {@link DEFAULT_SAVE_DELIVERY_POLICY}. Read via
229
+ * {@link saveDeliveryPolicy} so the fallback is applied even when inversify
230
+ * injects `undefined` for an unbound `@optional()` member.
146
231
  */
147
- @inject(SaveConflictPolicy) @optional() protected readonly boundSaveConflictPolicy?: SaveConflictPolicy;
232
+ @inject(SaveDeliveryPolicy) @optional() protected readonly boundSaveDeliveryPolicy?: SaveDeliveryPolicy;
148
233
 
149
234
  /** Disposables created during {@link doLoadSourceModel}; drained on session disposal. */
150
235
  protected toDispose = new DisposableCollection();
@@ -159,6 +244,25 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
159
244
  */
160
245
  protected readonly secondarySubscriptions = new Map<string, Disposable>();
161
246
 
247
+ /**
248
+ * Documents that left the write set since the last save. They stay open in
249
+ * the diagram's session until that save has persisted them, and are closed
250
+ * after it: closing a document as it leaves would revert the diagram's
251
+ * unsaved edits to it where the diagram was its last client.
252
+ */
253
+ protected readonly departedSecondaries = new Set<string>();
254
+
255
+ /**
256
+ * How long a load waits for a client id another participant holds to free
257
+ * before refusing. A reloaded client can reconnect under its old id before
258
+ * the server has noticed the old connection close, which ends that
259
+ * connection's sessions a moment later.
260
+ */
261
+ protected readonly sessionWaitMs: number = 2_000;
262
+
263
+ /** Set by {@link dispose}; a disposed storage registers no session again. */
264
+ protected disposed = false;
265
+
162
266
  /**
163
267
  * Whether an external resubmit has ever been dispatched. Gates the
164
268
  * keep-the-last-valid-GModel branch, which needs to know a canvas is already
@@ -178,7 +282,7 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
178
282
  protected resubmitDebouncer!: Debouncer;
179
283
 
180
284
  /** Latest event document awaiting the debounced resubmit; read by {@link flushResubmit} (last write wins). */
181
- protected pendingResubmitDocument?: AstDocument<AstNode, unknown>;
285
+ protected pendingResubmitDocument?: AstDocument<AstNode>;
182
286
 
183
287
  @postConstruct()
184
288
  protected init(): void {
@@ -188,6 +292,7 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
188
292
  if (this.state.clientId === TEMPORARY_CLIENT_ID) {
189
293
  return;
190
294
  }
295
+ this.state.modelSession = this.registerModelSession();
191
296
  this.sessionManager.addListener(this, this.state.clientId);
192
297
  // Watched for this storage's whole lifetime rather than per load. The load
193
298
  // flow is a documented override point, so a subscription parked there would
@@ -196,6 +301,102 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
196
301
  this.toDispose.push(this.state.onSecondaryUrisChanged(() => this.reconcileSecondarySubscriptions()));
197
302
  }
198
303
 
304
+ /**
305
+ * Register the diagram's client session under the GLSP client id, or
306
+ * `undefined` when another participant holds that id, which is logged.
307
+ *
308
+ * The diagram then refuses to load ({@link requireModelSession}). Taking
309
+ * the id over would end the other participant's session under it, and
310
+ * working without a session would share that participant's opens and
311
+ * echoes, so its close would take the diagram's documents with it.
312
+ */
313
+ protected registerModelSession(): ModelClientSession<AstNode> | undefined {
314
+ try {
315
+ return this.sharedServices.model.ModelService.createSession('diagram', this.state.clientId);
316
+ } catch (error: unknown) {
317
+ if (!isDuplicateClientIdError(error)) {
318
+ throw error;
319
+ }
320
+ this.logger.warn(`Client id ${this.state.clientId} is held by another participant: this diagram has no session yet`);
321
+ return undefined;
322
+ }
323
+ }
324
+
325
+ /**
326
+ * The diagram's client session, registering it again when the id was held
327
+ * earlier. Throws `SessionClosedError` once the storage is disposed, and the
328
+ * refusal when the id is still held.
329
+ */
330
+ protected requireModelSession(): ModelClientSession<AstNode> {
331
+ if (this.disposed) {
332
+ throw new SessionClosedError(
333
+ this.state.clientId,
334
+ `The diagram of ${this.state.clientId} has closed; its client session has ended`
335
+ );
336
+ }
337
+ if (!this.state.modelSession) {
338
+ this.state.modelSession = this.registerModelSession();
339
+ }
340
+ const session = this.state.modelSession;
341
+ if (!session) {
342
+ throw new GLSPServerError(
343
+ this.sharedServices.MessageRenderer.renderMessage(DIAGRAM_SESSION_REFUSED),
344
+ `clientId=${this.state.clientId} is still held by another participant, so this diagram has no client session`
345
+ );
346
+ }
347
+ return session;
348
+ }
349
+
350
+ /**
351
+ * {@link requireModelSession} for the load: while the id is held, wait up to
352
+ * {@link sessionWaitMs} for its holder to end before refusing, and tell the
353
+ * user when it does not.
354
+ */
355
+ protected async awaitModelSession(): Promise<ModelClientSession<AstNode>> {
356
+ if (!this.state.modelSession && !this.disposed) {
357
+ this.state.modelSession = this.registerModelSession();
358
+ }
359
+ if (!this.state.modelSession && !this.disposed) {
360
+ await this.waitForSessionEnd(this.state.clientId, this.sessionWaitMs);
361
+ }
362
+ try {
363
+ return this.requireModelSession();
364
+ } catch (error: unknown) {
365
+ // A diagram closed while it waited has no client left to tell.
366
+ if (isSessionClosedError(error)) {
367
+ throw error;
368
+ }
369
+ this.logger.error(`Client id ${this.state.clientId} is still held by another participant: this diagram does not load`);
370
+ this.actionDispatcher
371
+ .dispatch(
372
+ MessageAction.create(this.sharedServices.MessageRenderer.renderMessage(DIAGRAM_SESSION_REFUSED), { severity: 'ERROR' })
373
+ )
374
+ .catch((dispatchError: unknown) =>
375
+ this.logger.warn(`Could not tell the client the diagram was refused: ${String(dispatchError)}`)
376
+ );
377
+ throw error;
378
+ }
379
+ }
380
+
381
+ /** Resolve once the client session under `clientId` ends, or after `timeoutMs`. */
382
+ protected waitForSessionEnd(clientId: string, timeoutMs: number): Promise<void> {
383
+ return new Promise<void>(resolve => {
384
+ const subscriptions = new DisposableCollection();
385
+ const done = (): void => {
386
+ subscriptions.dispose();
387
+ resolve();
388
+ };
389
+ subscriptions.push(this.sharedServices.Clock.setTimer(done, timeoutMs));
390
+ subscriptions.push(
391
+ this.sharedServices.workspace.TextDocuments.onDidCloseSession(event => {
392
+ if (event.clientId === clientId) {
393
+ done();
394
+ }
395
+ })
396
+ );
397
+ });
398
+ }
399
+
199
400
  /**
200
401
  * Default load flow — {@link doLoadSourceModel}. Adopters whose load flow
201
402
  * needs more than the seams allow override this method.
@@ -211,8 +412,8 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
211
412
 
212
413
  // Open FIRST: a workspace-scanned-but-never-didOpened document rebuilds here,
213
414
  // so the capture below settles on a built root rather than a transient
214
- // mid-rebuild one.
215
- this.toDispose.push(await modelService.open({ uri: rootUri, clientId: this.state.clientId }));
415
+ // mid-rebuild one. Closed when the session ends.
416
+ await (await this.awaitModelSession()).open(rootUri);
216
417
 
217
418
  // GLSP's sessionDisposed is unreliable on Theia tab-close; dispose on client
218
419
  // detach so reopens don't accumulate stale onModelUpdated listeners.
@@ -235,12 +436,29 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
235
436
  }
236
437
 
237
438
  /**
238
- * Capture the initial settled root and apply the initial edit mode. `settled()`
239
- * strips diagnostics by phase contract, so the first edit mode is `EDITABLE`;
240
- * the first {@link handleModelUpdated} (at `Validated`, with diagnostics) flips
241
- * it READONLY if the document has structural parse errors. Edit-mode +
242
- * settle-hook actions are dispatched on a macrotask so the initial
439
+ * Capture the initial settled root and apply the initial edit mode. Edit-mode
440
+ * + settle-hook actions are dispatched on a macrotask so the initial
243
441
  * `requestModel → setModel` handshake isn't perturbed.
442
+ *
443
+ * **Whether the settled document carries diagnostics depends on how far it
444
+ * had already got, so the initial edit mode has two correct outcomes rather
445
+ * than one.** `settled()` strips nothing: it resolves AT OR ABOVE the
446
+ * integrity landmark and hands back the live document's own array. Its
447
+ * `AstDocument<TAst, never>` return type asserts emptiness for a document the
448
+ * wait had to DRIVE to that landmark, which is pre-validation — and for that
449
+ * one the mode here is `EDITABLE` and the flip to READONLY arrives with the
450
+ * first {@link handleModelUpdated}. A document already past `Validated` when
451
+ * the session opened resolves immediately with its diagnostics intact, and is
452
+ * decided correctly here with no later update owed. Any host that validates
453
+ * its workspace before a diagram is opened produces the second case, so
454
+ * neither is exceptional.
455
+ *
456
+ * **A correct decision is not a delivered one.** This dispatch happens inside
457
+ * the initial `requestModel`, before the client has the model — so the UI
458
+ * extensions that answer {@link onParseErrorChanged}'s actions are not yet
459
+ * constructed, and a canvas that opens READONLY over a broken document shows
460
+ * none of that feedback. The same timer carries {@link onSourceModelSettled},
461
+ * so an adopter's own initial actions have it too.
244
462
  */
245
463
  protected async captureSettledRoot(rootUri: string, document: AstDocument<AstNode, never>): Promise<void> {
246
464
  this.state.setSourceRoot(rootUri, document.root as TRoot);
@@ -275,18 +493,44 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
275
493
  if (!current.has(uri)) {
276
494
  subscription.dispose();
277
495
  this.secondarySubscriptions.delete(uri);
496
+ this.departedSecondaries.add(uri);
278
497
  }
279
498
  }
280
499
  for (const uri of current) {
281
500
  if (!this.secondarySubscriptions.has(uri)) {
501
+ this.departedSecondaries.delete(uri);
282
502
  this.secondarySubscriptions.set(
283
503
  uri,
284
504
  this.sharedServices.model.ModelService.onModelUpdated(uri, event => this.handleSecondaryUpdated(uri, event))
285
505
  );
506
+ this.openSecondary(uri);
286
507
  }
287
508
  }
288
509
  }
289
510
 
511
+ /**
512
+ * Open a document that joined the write set through the diagram's session,
513
+ * where it stays open until the diagram's next save after it leaves the set,
514
+ * or the diagram's end. A document that does not exist yet is left to the
515
+ * write that creates it, and a failed open is logged: the write that needs
516
+ * the document opens it again and fails there.
517
+ */
518
+ protected openSecondary(uri: string): void {
519
+ const session = this.state.modelSession;
520
+ if (!session || !this.sharedServices.model.ModelService.getDocument(uri)) {
521
+ return;
522
+ }
523
+ session.open(uri).catch((error: unknown) => {
524
+ const detail = `Could not open ${uri} for ${this.state.clientId}: ${error instanceof Error ? error.message : String(error)}`;
525
+ // A session ending while the open reads is the diagram closing.
526
+ if (isSessionClosedError(error)) {
527
+ this.logger.debug(detail);
528
+ } else {
529
+ this.logger.warn(detail);
530
+ }
531
+ });
532
+ }
533
+
290
534
  /**
291
535
  * React to a rebuild of a SECONDARY document by resubmitting the diagram, so
292
536
  * an external edit to (say) a layout file reaches the canvas.
@@ -312,7 +556,7 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
312
556
  * drag this client authors — the guard above gates the resubmit, not the
313
557
  * markers.
314
558
  */
315
- protected handleSecondaryUpdated(uri: string, event: AstDocumentUpdatedEvent<AstNode, unknown>): void {
559
+ protected handleSecondaryUpdated(uri: string, event: AstDocumentUpdatedEvent<AstNode>): void {
316
560
  if (this.disposeIfStale(uri)) {
317
561
  return;
318
562
  }
@@ -333,11 +577,12 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
333
577
  *
334
578
  * Synchronous by construction — the phase-agnostic lookup door plus the shared
335
579
  * projection — so reacting to a secondary neither waits nor can force a build.
336
- * `settled()` is not an alternative: it strips diagnostics by phase contract,
337
- * and diagnostics are the reason {@link doUpdateAndSubmit} takes a separate
338
- * event document at all.
580
+ * `settled()` is not an alternative: besides being asynchronous, it cannot be
581
+ * relied on to carry diagnostics — a document it has to drive to the landmark
582
+ * arrives pre-validation with an empty array — and diagnostics are the reason
583
+ * {@link doUpdateAndSubmit} takes a separate event document at all.
339
584
  */
340
- protected currentPrimaryDocument(): AstDocument<AstNode, unknown> | undefined {
585
+ protected currentPrimaryDocument(): AstDocument<AstNode> | undefined {
341
586
  const document = this.sharedServices.model.ModelService.getDocument(this.state.sourceUri);
342
587
  return document ? AstDocument.from(document) : undefined;
343
588
  }
@@ -350,7 +595,7 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
350
595
  * diagnostic markers for every update — including own edits, which skip
351
596
  * the resubmit but can still change diagnostics.
352
597
  */
353
- protected async handleModelUpdated(rootUri: string, event: AstDocumentUpdatedEvent<AstNode, unknown>): Promise<void> {
598
+ protected async handleModelUpdated(rootUri: string, event: AstDocumentUpdatedEvent<AstNode>): Promise<void> {
354
599
  if (this.disposeIfStale(rootUri)) {
355
600
  return;
356
601
  }
@@ -382,7 +627,7 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
382
627
  * {@link resubmitDebouncer}, so a burst of rebuilds runs
383
628
  * {@link doUpdateAndSubmit} once with the most recent document.
384
629
  */
385
- protected scheduleUpdateAndSubmit(document: AstDocument<AstNode, unknown>): void {
630
+ protected scheduleUpdateAndSubmit(document: AstDocument<AstNode>): void {
386
631
  this.pendingResubmitDocument = document;
387
632
  this.resubmitDebouncer.schedule();
388
633
  }
@@ -409,7 +654,7 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
409
654
  * mark our stack clean so the editor doesn't prompt to re-save identical
410
655
  * content. Our own saves already settle the stack through the save flow.
411
656
  */
412
- protected handleModelSaved(event: AstDocumentSavedEvent<AstNode, unknown>): void {
657
+ protected handleModelSaved(event: AstDocumentSavedEvent<AstNode>): void {
413
658
  if (this.state.clientId !== event.sourceClientId) {
414
659
  this.commandStack.saveIsDone();
415
660
  }
@@ -418,10 +663,12 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
418
663
  /**
419
664
  * Re-settle to a guaranteed fully-linked + reprojected root, capture it, and
420
665
  * (unless suppressed) resubmit a deduped external GModel. Diagnostics for the
421
- * edit-mode decision come from the event document (`settled()` strips them by
422
- * phase contract).
666
+ * edit-mode decision come from the event document, because the re-settled one
667
+ * cannot be relied on to have any: a document driven to the landmark arrives
668
+ * pre-validation, and this path re-settles precisely to escape a transient
669
+ * mid-rebuild snapshot.
423
670
  */
424
- protected async doUpdateAndSubmit(rootUri: string, eventDocument: AstDocument<AstNode, unknown>): Promise<Action[]> {
671
+ protected async doUpdateAndSubmit(rootUri: string, eventDocument: AstDocument<AstNode>): Promise<Action[]> {
425
672
  // Settle-gate the capture: never setSourceRoot off the event's possibly-transient
426
673
  // snapshot — the event can arrive while a re-entered document is mid-rebuild.
427
674
  const document = await this.sharedServices.model.ModelService.settled(rootUri);
@@ -459,7 +706,7 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
459
706
  * flip {@link AbstractHydraniumGlspState.editMode}, and — only on a transition —
460
707
  * return the {@link onParseErrorChanged} actions. No transition → no actions.
461
708
  */
462
- protected refreshEditMode(document: AstDocument<AstNode, unknown>): Action[] {
709
+ protected refreshEditMode(document: AstDocument<AstNode>): Action[] {
463
710
  const broken = this.isStructurallyBroken(document);
464
711
  const previousEditMode = this.state.editMode;
465
712
  this.state.editMode = broken ? EditMode.READONLY : EditMode.EDITABLE;
@@ -476,20 +723,53 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
476
723
  * carrying a Langium `lexing-error` / `parsing-error` code. Adopters override
477
724
  * to compose additional break reasons.
478
725
  */
479
- protected isStructurallyBroken(document: AstDocument<AstNode, unknown>): boolean {
726
+ protected isStructurallyBroken(document: AstDocument<AstNode>): boolean {
480
727
  return document.diagnostics.some(diagnostic => isStructuralDiagnostic(diagnostic));
481
728
  }
482
729
 
483
730
  /**
484
- * Seam: actions to emit when the structural-broken state transitions. Default:
485
- * a single {@link SetEditModeAction} toggling READONLY ↔ EDITABLE — editing is
486
- * disabled while the syntax is broken but re-enabled once it parses, a sound
487
- * generic for any Langium-backed diagram. Adopters override to add or replace
488
- * the transition feedback. The {@link AbstractHydraniumGlspState.editMode}
489
- * flip itself is owned by {@link refreshEditMode}.
731
+ * Seam: actions to emit when the structural-broken state transitions.
732
+ * Default: a {@link SetEditModeAction} toggling READONLY ↔ EDITABLE — editing
733
+ * is disabled while the syntax is broken but re-enabled once it parses, a
734
+ * sound generic for any Langium-backed diagram — plus the
735
+ * {@link DIAGRAM_READONLY_PARSE_ERROR} band that says why, cleared on the way
736
+ * back. Adopters override to add or replace the transition feedback. The
737
+ * {@link AbstractHydraniumGlspState.editMode} flip itself is owned by
738
+ * {@link refreshEditMode}.
739
+ *
740
+ * **Both actions or neither, which is why they are one seam rather than
741
+ * two.** The mode flip removes the tool palette and the band is the only
742
+ * account of that, so an override that keeps one and drops the other produces
743
+ * either an unexplained loss of the palette or a warning about a restriction
744
+ * that is not in force.
745
+ *
746
+ * **The status is dispatched with no `timeout`, so it persists** — a
747
+ * time-limited band would describe a condition that outlasts it.
748
+ *
749
+ * **The slot is SHARED, and the other writer wins on one path.**
750
+ * `ModelSubmissionHandler`'s live validation writes the same slot, clearing
751
+ * it with `severity: 'NONE'` when it finishes, and an adopter dispatching its
752
+ * own `StatusAction` replaces this one too. Nothing re-asserts it. That is
753
+ * harmless while a document is being edited, because a resubmit is skipped
754
+ * once the AST is broken (see {@link doUpdateAndSubmit}) — but NOT at load:
755
+ * the initial `requestModel` submit is not that skipped path, so a diagram
756
+ * opened on an already-broken document shows this band and then loses it to
757
+ * the validation clear a moment later. Measured on a browser host, polling the
758
+ * overlay: no element, empty, the sentence, empty again.
490
759
  */
491
- protected onParseErrorChanged(_document: AstDocument<AstNode, unknown>, broken: boolean): Action[] {
492
- return [SetEditModeAction.create(broken ? EditMode.READONLY : EditMode.EDITABLE)];
760
+ protected onParseErrorChanged(_document: AstDocument<AstNode>, broken: boolean): Action[] {
761
+ return [
762
+ SetEditModeAction.create(broken ? EditMode.READONLY : EditMode.EDITABLE),
763
+ broken
764
+ ? StatusAction.create(this.sharedServices.MessageRenderer.renderMessage(DIAGRAM_READONLY_PARSE_ERROR), {
765
+ severity: 'WARNING'
766
+ })
767
+ : // `NONE` is the client's own spelling for "clear", not a severity it
768
+ // renders: `StatusOverlay.handle` branches on it before touching the
769
+ // DOM. An empty message at any other severity leaves an empty band
770
+ // with a warning icon standing on the canvas.
771
+ StatusAction.create('', { severity: 'NONE' })
772
+ ];
493
773
  }
494
774
 
495
775
  /**
@@ -500,32 +780,48 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
500
780
  return [];
501
781
  }
502
782
 
503
- /** The effective {@link SaveConflictPolicy}: the bound option, or {@link DEFAULT_SAVE_CONFLICT_POLICY} when unbound. */
504
- protected get saveConflictPolicy(): SaveConflictPolicy {
505
- return this.boundSaveConflictPolicy ?? DEFAULT_SAVE_CONFLICT_POLICY;
783
+ /** The effective {@link SaveDeliveryPolicy}: the bound option, or {@link DEFAULT_SAVE_DELIVERY_POLICY} when unbound. */
784
+ protected get saveDeliveryPolicy(): SaveDeliveryPolicy {
785
+ return this.boundSaveDeliveryPolicy ?? DEFAULT_SAVE_DELIVERY_POLICY;
506
786
  }
507
787
 
508
788
  /**
509
- * Default save flow: route through `ModelService.save`. The framework
510
- * serialise-and-persist machinery handles serialisation (via the
511
- * language-specific `Serializer` bound at `services.serializer.Serializer`),
512
- * the multi-client text-document update, the rebuild, and the eventual
513
- * `WritableFileSystemProvider.writeFile`.
789
+ * Default save flow: persist the store's current text for every document the
790
+ * diagram's session has open.
791
+ *
792
+ * **A save persists, it does not author.** Every diagram gesture already
793
+ * reached the store through the diagram's session, so the store holds the
794
+ * settled text and disk is the only thing behind. Re-serializing from the AST
795
+ * here cannot improve on that text and can only damage it: a serializer
796
+ * normalises formatting, and the comments the write path carries over keep
797
+ * none of the hand-formatting around them, so a save would reflow a document
798
+ * nothing changed — which is what a pure bounds drag does to the semantic
799
+ * file when only its layout moved.
514
800
  *
515
- * The configured {@link SaveConflictPolicy} (see {@link saveConflictPolicy})
516
- * decides how a concurrent edit that advanced the document is handled:
517
- * - `overwrite` (default): no based-on guard, await, propagate failures —
518
- * last-write-wins, correct for a single-editor head.
519
- * - `reject`: guard on the captured `state.version`, await, surface a
520
- * `ConflictError` (and any other failure) to the GLSP save action.
521
- * - `drop-and-log`: guard, fire-and-forget, log + swallow failures — a stale
522
- * diagram save is dropped because a concurrent form/code edit already wrote
523
- * the truth, and GLSP exposes no save-failure back-channel.
801
+ * **What is saved is the primary, every tracked secondary
802
+ * (`AbstractHydraniumGlspState.trackSecondaryDocument`) and every document
803
+ * that left the write set since the last save**, so a document the diagram
804
+ * wrote is persisted whether or not it is the one the client named. One the
805
+ * diagram's session does not have open is skipped, even when another client
806
+ * has it open: that client's unsaved edits are not the diagram's to persist.
807
+ *
808
+ * **A save therefore names documents the gesture did not aim at**, which is
809
+ * why an unchanged one is not rewritten even though the user asked for a
810
+ * save: the mtime would move on a file they never touched.
811
+ * `AstDocumentManager.save` decides that per document and announces the save
812
+ * either way.
813
+ *
814
+ * The configured {@link SaveDeliveryPolicy} (see {@link saveDeliveryPolicy})
815
+ * decides await-vs-fire-and-forget and failure handling. It carries no
816
+ * based-on guard: the guard exists to stop a stale writer overwriting a newer
817
+ * document, and a flush persists the store — which already holds every other
818
+ * client's change, including the one that advanced the version.
524
819
  *
525
820
  * Returns `MaybePromise<void>` to match upstream `SourceModelStorage`:
526
- * resolves with the persist under `overwrite`/`reject`, returns synchronously
527
- * under `drop-and-log`. Adopters that bypass `ModelService` (writing through
528
- * `WritableFileSystemProvider` directly) still override the whole method.
821
+ * resolves with the flush under `await`, returns synchronously under
822
+ * `fire-and-forget`. Adopters that bypass `AstDocumentManager` (writing
823
+ * through `WritableFileSystemProvider` directly) still override the whole
824
+ * method.
529
825
  */
530
826
  saveSourceModel(action: SaveModelAction): MaybePromise<void> {
531
827
  // Normalised for the same reason the load path is: `SaveModelAction.fileUri`
@@ -535,26 +831,51 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
535
831
  // the call site rather than inside `getFileUri` so that method's contract —
536
832
  // return what the action said — is unchanged for adopters overriding it.
537
833
  const uri = this.toSourceModelUri(this.getFileUri(action));
538
- const policy = this.saveConflictPolicy;
539
- const persisted = this.sharedServices.model.ModelService.save({
540
- uri,
541
- model: this.state.sourceRoot,
542
- clientId: this.state.clientId,
543
- baseVersion: policy.kind === 'overwrite' ? undefined : this.state.version
544
- }).then(() => undefined);
545
-
546
- if (policy.kind === 'drop-and-log') {
547
- // Fire-and-forget: the diagram save lost the race to a concurrent edit
548
- // that already persisted the truth, so it must neither block the action
549
- // nor surface. Log rather than leave an unhandled rejection.
834
+ const policy = this.saveDeliveryPolicy;
835
+ const persisted = this.flushWriteSet(uri);
836
+
837
+ if (policy.kind === 'fire-and-forget') {
838
+ // Log rather than leave an unhandled rejection: the promise is not
839
+ // returned, so nothing else will observe a failure.
550
840
  persisted.catch(error => this.logger.error(`Save failed for ${uri}: ${error instanceof Error ? error.message : String(error)}`));
551
841
  return undefined;
552
842
  }
553
- // overwrite / reject: await; a ConflictError (reject) or any other failure
554
- // propagates to GLSP's save-action handler.
843
+ // Awaited: any failure propagates to GLSP's save-action handler.
555
844
  return persisted;
556
845
  }
557
846
 
847
+ /**
848
+ * Save the stored text of `primaryUri`, every tracked secondary and every
849
+ * document that left the write set since the last save, each only where
850
+ * the diagram's session has it open; then close those that left.
851
+ *
852
+ * Deduplicated, because a state that tracks its own primary as a secondary
853
+ * would otherwise save it twice and fire two save notifications for one
854
+ * save. Every save is called in one synchronous step, so each takes its text
855
+ * before anything can close a document of the set: saved one after another,
856
+ * a GLSP session ending during the first write closes the rest unsaved.
857
+ */
858
+ protected async flushWriteSet(primaryUri: string): Promise<void> {
859
+ // Refused like the load: without a session the client id's opens are
860
+ // another participant's, and this would save them.
861
+ this.requireModelSession();
862
+ const documents = this.sharedServices.workspace.AstDocumentManager;
863
+ const textDocuments = this.sharedServices.workspace.TextDocuments;
864
+ const clientId = this.state.clientId;
865
+ // Taken with the targets: a document leaving the set during the writes
866
+ // was not saved by them, and stays open for the next save.
867
+ const departed = [...this.departedSecondaries];
868
+ const targets = [...new Set([primaryUri, ...this.state.secondaryUris, ...departed])].filter(uri =>
869
+ textDocuments.isOpenInClient(uri, clientId)
870
+ );
871
+ await Promise.all(targets.map(target => documents.save(target, clientId)));
872
+ for (const uri of departed) {
873
+ if (this.departedSecondaries.delete(uri) && uri !== this.state.sourceUri) {
874
+ await this.state.modelSession?.close(uri);
875
+ }
876
+ }
877
+ }
878
+
558
879
  /**
559
880
  * Normalise GLSP's `sourceUri` — which may be a filesystem PATH or a URI
560
881
  * string — to the URI string the workspace keys documents by.
@@ -584,11 +905,25 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
584
905
  *
585
906
  * Returns it VERBATIM, in whatever form the client sent;
586
907
  * {@link toSourceModelUri} is what normalises it.
908
+ *
909
+ * A model request DOES carry a request id, so a throw here takes the
910
+ * client-request path rather than the toast path — and on that path `detail`
911
+ * comes from `cause?.toString?.()`. A single-argument throw therefore reaches
912
+ * neither the server log nor the client console: both print `undefined`. So
913
+ * the two readers are addressed separately, as on the save path: `message`
914
+ * names what failed in the user's terms and is rendered, `cause` names the
915
+ * action and the option key that was missing and stays English. On THIS path
916
+ * the cause reaches only logs — `RejectAction.detail` is read by nothing but
917
+ * the client action-dispatcher's `logger.warn` — which is not what makes it
918
+ * English; its content is.
587
919
  */
588
920
  protected getSourceUri(action: RequestModelAction): string {
589
921
  const sourceUri = action.options?.[SOURCE_URI_ARG];
590
922
  if (typeof sourceUri !== 'string') {
591
- throw new GLSPServerError(`Invalid RequestModelAction! Missing argument with key '${SOURCE_URI_ARG}'`);
923
+ throw new GLSPServerError(
924
+ this.sharedServices.MessageRenderer.renderMessage(SOURCE_URI_MISSING),
925
+ `no '${SOURCE_URI_ARG}' option on the ${action.kind} action (received ${typeof sourceUri})`
926
+ );
592
927
  }
593
928
  return sourceUri;
594
929
  }
@@ -600,18 +935,24 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
600
935
  * {@link AbstractHydraniumGlspState.setSourceRoot}.
601
936
  *
602
937
  * A save action carries no request id, so a throw here reaches the user as a
603
- * toast built from `message`, with `cause` behind its details control. The
604
- * two therefore address different readers and must not be collapsed: the
605
- * message names what failed in the user's terms, and the cause names which
606
- * lookups came back empty for whom. Neither can name the URI — not having
607
- * one IS the failure, and both sources are written together, so the typed
608
- * `sourceUri` is equally empty whenever this fires.
938
+ * toast built from `message`, while `cause` travels in
939
+ * `MessageAction.details` — **which a Theia host DOES put in front of a
940
+ * user**, as a "Show details" button on the toast opening a dialog. So the
941
+ * two are not split by reachability; they are split by AUDIENCE, which is
942
+ * the older rule and the one that holds here. The message names what failed
943
+ * in the user's terms and is rendered; the cause names which lookups came
944
+ * back empty for whom, and stays English because a wire action kind, an
945
+ * option key and a client id address whoever composes the system — a
946
+ * translated developer string is a worse outcome than an untranslated one.
947
+ * Neither can name the URI — not having one IS the failure, and both sources
948
+ * are written together, so the typed `sourceUri` is equally empty whenever
949
+ * this fires.
609
950
  */
610
951
  protected getFileUri(action: SaveModelAction): string {
611
952
  const uri = action.fileUri ?? this.state.get<string>(SOURCE_URI_ARG);
612
953
  if (!uri) {
613
954
  throw new GLSPServerError(
614
- 'Could not determine where to save this model',
955
+ this.sharedServices.MessageRenderer.renderMessage(SAVE_TARGET_UNKNOWN),
615
956
  `no fileUri on the save action and no ${SOURCE_URI_ARG} in the model state (clientId=${this.state.clientId})`
616
957
  );
617
958
  }
@@ -644,10 +985,14 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
644
985
  }
645
986
 
646
987
  /**
647
- * Cancel any pending resubmit and drain every subscription — those registered
988
+ * Cancel any pending resubmit, drain every subscription — those registered
648
989
  * during {@link doLoadSourceModel} and the per-secondary ones, which live
649
- * outside {@link toDispose} because they come and go with the write set.
990
+ * outside {@link toDispose} because they come and go with the write set —
991
+ * and end the diagram's client session, closing everything it has open.
650
992
  * Idempotent.
993
+ *
994
+ * The session ends last, once the detach listener is gone: its closes would
995
+ * otherwise report this storage's own teardown as a client detaching.
651
996
  */
652
997
  dispose(): void {
653
998
  this.resubmitDebouncer?.dispose();
@@ -656,5 +1001,8 @@ export class HydraniumGlspStorage<TRoot extends AstNode, TSourceModel = string>
656
1001
  }
657
1002
  this.secondarySubscriptions.clear();
658
1003
  this.toDispose.dispose();
1004
+ this.disposed = true;
1005
+ this.state.modelSession?.dispose();
1006
+ this.state.modelSession = undefined;
659
1007
  }
660
1008
  }