@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
@@ -15,15 +15,65 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
15
15
  var __metadata = (this && this.__metadata) || function (k, v) {
16
16
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
17
17
  };
18
- import { MarkersReason, SetMarkersAction } from '@eclipse-glsp/protocol';
18
+ import { MarkersReason, MessageAction, SetMarkersAction, StatusAction } from '@eclipse-glsp/protocol';
19
19
  import { ActionDispatcher, ClientSessionManager, CommandStack, EditMode, GLSPServerError, Logger as GlspLogger, ModelState, ModelSubmissionHandler, ModelValidator, SOURCE_URI_ARG, SetEditModeAction, TEMPORARY_CLIENT_ID } from '@eclipse-glsp/server';
20
- import { Debouncer, DisposableCollection } from '@hydranium/protocol';
20
+ import { Debouncer, defineMessage, DisposableCollection, isDuplicateClientIdError, isSessionClosedError, SessionClosedError } from '@hydranium/protocol';
21
21
  import { inject, injectable, optional, postConstruct } from 'inversify';
22
22
  import { URI } from '@hydranium/langium';
23
23
  import { AstDocument } from '@hydranium/core';
24
24
  import { DiagnosticSeverity } from 'vscode-languageserver-types';
25
25
  import { HydraniumTypes } from '../state/hydranium-shared-core-services.js';
26
- import { DEFAULT_SAVE_CONFLICT_POLICY, SaveConflictPolicy } from './save-conflict-policy.js';
26
+ import { DEFAULT_SAVE_DELIVERY_POLICY, SaveDeliveryPolicy } from './save-delivery-policy.js';
27
+ /**
28
+ * A save action arrived with nowhere to write to. A save action carries no
29
+ * request id, so it falls through to the error handler and `message` becomes
30
+ * the toast text.
31
+ *
32
+ * Rendered at the raise site rather than by a carrier method, because GLSP's
33
+ * action protocol has no slot for an identity anywhere — every member of its
34
+ * message, status and reject actions is prose or an enum, and
35
+ * `MessageAction.details` is not a substitute since it is prose populated from
36
+ * `cause?.toString?.()`, and a Theia host shows it to a user on demand. So the
37
+ * throw is the last place that still knows which message this is.
38
+ */
39
+ export const SAVE_TARGET_UNKNOWN = defineMessage('hydranium/glsp-server/save-target-unknown', 'Could not determine where to save this model');
40
+ /**
41
+ * A model request arrived without the source URI it is required to carry.
42
+ * Rendered at the raise site, like its save-path sibling and for the same
43
+ * reason.
44
+ */
45
+ export const SOURCE_URI_MISSING = defineMessage('hydranium/glsp-server/source-uri-missing', 'Could not open this model: the request did not say which document to load');
46
+ /**
47
+ * Why the canvas has stopped accepting edits.
48
+ *
49
+ * **A READONLY canvas is otherwise indistinguishable from a broken one.** The
50
+ * client's answer to {@link SetEditModeAction} is to withdraw the tool palette,
51
+ * so the surface a reader was working in silently loses the only control it had,
52
+ * with the cause — a syntax error in a document that may not even be open —
53
+ * nowhere on screen. The mode flip is the mechanism; this is the only part of it
54
+ * a user can see.
55
+ *
56
+ * Rendered at the raise site, like its two siblings above and for the same
57
+ * reason: every member of GLSP's status action is prose or an enum.
58
+ *
59
+ * It names the recovery rather than the fault, because the fault already has a
60
+ * surface — the squiggle and the problems list, both of which say WHICH
61
+ * character — and repeating it here would put a second, less precise account of
62
+ * the same error on screen. What no other surface says is that the diagram is
63
+ * waiting on it.
64
+ */
65
+ export const DIAGRAM_READONLY_PARSE_ERROR = defineMessage('hydranium/glsp-server/diagram-readonly-parse-error', 'Read-only: this document has a syntax error. Fix it to edit the diagram again.');
66
+ /**
67
+ * The diagram's GLSP client id is still live as another participant's client
68
+ * id once the load has waited for it to free, so the diagram does not load.
69
+ *
70
+ * Rendered at the raise site, as {@link SAVE_TARGET_UNKNOWN} is and for the
71
+ * same reason, and dispatched to the client as a message of its own: a model
72
+ * request fails as a rejection whose detail is the English cause, which no user
73
+ * sees. It names the recovery: a host that numbers its diagram clients gives a
74
+ * reopened diagram a fresh id.
75
+ */
76
+ export const DIAGRAM_SESSION_REFUSED = defineMessage('hydranium/glsp-server/diagram-session-refused', 'Could not open this diagram: its identifier is still in use by another editor. Close the diagram and open it again.');
27
77
  /** Window (ms) over which back-to-back external rebuilds collapse into one resubmit. */
28
78
  const EXTERNAL_SUBMIT_DEBOUNCE_MS = 250;
29
79
  /**
@@ -69,17 +119,24 @@ function isStructuralDiagnostic(diagnostic) {
69
119
  *
70
120
  * Adopters with richer needs override the seams ({@link isStructurallyBroken},
71
121
  * {@link onParseErrorChanged}, {@link onSourceModelSettled}) rather than the
72
- * whole flow, and select a {@link SaveConflictPolicy} via the bound option to
73
- * tune how {@link saveSourceModel} reacts to a concurrent edit.
122
+ * whole flow, and select a {@link SaveDeliveryPolicy} via the bound option to
123
+ * tune how {@link saveSourceModel} delivers its result.
74
124
  *
75
- * **Default `saveSourceModel` flow.** Delegates to `ModelService.save`, which
76
- * serialises through the language-specific `Serializer` bound at
77
- * `services.serializer.Serializer` (resolved per-URI via `ServiceRegistry`),
78
- * updates the multi-client text-document store, drives a rebuild, and writes the
79
- * result via the `WritableFileSystemProvider`. The bound
80
- * {@link SaveConflictPolicy} (default {@link DEFAULT_SAVE_CONFLICT_POLICY},
81
- * `overwrite`) decides the based-on-version guard, await-vs-fire-and-forget, and
82
- * failure handling.
125
+ * **One client session per GLSP client session.** `init` registers the GLSP
126
+ * client id as a client session ({@link registerModelSession}) and hands it to
127
+ * the state as `modelSession`. The primary is opened through it on load, and
128
+ * every document that joins the write set as it joins
129
+ * ({@link openSecondary}); a document that leaves the write set stays open
130
+ * until the next save, so leaving never reverts the diagram's unsaved edits to
131
+ * it. Disposing the storage ends the session, which closes everything it has
132
+ * open.
133
+ *
134
+ * **Default `saveSourceModel` flow.** Flushes the stored text of every
135
+ * document the diagram's session has open via `AstDocumentManager.save`, with
136
+ * no serializer in the path — the update path already put the settled text in
137
+ * the store. The bound {@link SaveDeliveryPolicy} (default
138
+ * {@link DEFAULT_SAVE_DELIVERY_POLICY}, `await`) decides
139
+ * await-vs-fire-and-forget and failure handling.
83
140
  *
84
141
  * **tempId filter.** GLSP's `DefaultGlobalActionProvider` spins up a
85
142
  * throwaway per-diagram-type container with upstream's {@link TEMPORARY_CLIENT_ID}
@@ -90,9 +147,9 @@ function isStructuralDiagnostic(diagnostic) {
90
147
  * **Lifecycle ordering.** `init` runs after DI resolution and parks the
91
148
  * secondary-write-set watch, which outlives any single load.
92
149
  * {@link sessionDisposed} calls {@link dispose}, which drains
93
- * {@link toDispose} idempotently. Every transient subscription created in
94
- * {@link doLoadSourceModel} is parked on {@link toDispose} so the drain catches
95
- * them on client-detach.
150
+ * {@link toDispose} idempotently and then ends the client session. Every
151
+ * transient subscription created in {@link doLoadSourceModel} is parked on
152
+ * {@link toDispose} so the drain catches them on client-detach.
96
153
  */
97
154
  let HydraniumGlspStorage = class HydraniumGlspStorage {
98
155
  logger;
@@ -111,14 +168,13 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
111
168
  */
112
169
  modelValidator;
113
170
  /**
114
- * Selected {@link SaveConflictPolicy} for {@link saveSourceModel}. Bind the
115
- * {@link SaveConflictPolicy} token in a `DiagramModule` to choose a policy;
116
- * left unbound it resolves to {@link DEFAULT_SAVE_CONFLICT_POLICY}
117
- * (`overwrite`, last-write-wins). Read via {@link saveConflictPolicy} so the
118
- * fallback is applied even when inversify injects `undefined` for an unbound
119
- * `@optional()` member.
171
+ * Selected {@link SaveDeliveryPolicy} for {@link saveSourceModel}. Bind the
172
+ * {@link SaveDeliveryPolicy} token in a `DiagramModule` to choose a policy;
173
+ * left unbound it resolves to {@link DEFAULT_SAVE_DELIVERY_POLICY}. Read via
174
+ * {@link saveDeliveryPolicy} so the fallback is applied even when inversify
175
+ * injects `undefined` for an unbound `@optional()` member.
120
176
  */
121
- boundSaveConflictPolicy;
177
+ boundSaveDeliveryPolicy;
122
178
  /** Disposables created during {@link doLoadSourceModel}; drained on session disposal. */
123
179
  toDispose = new DisposableCollection();
124
180
  /**
@@ -130,6 +186,22 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
130
186
  * with it rather than linger until the client detaches.
131
187
  */
132
188
  secondarySubscriptions = new Map();
189
+ /**
190
+ * Documents that left the write set since the last save. They stay open in
191
+ * the diagram's session until that save has persisted them, and are closed
192
+ * after it: closing a document as it leaves would revert the diagram's
193
+ * unsaved edits to it where the diagram was its last client.
194
+ */
195
+ departedSecondaries = new Set();
196
+ /**
197
+ * How long a load waits for a client id another participant holds to free
198
+ * before refusing. A reloaded client can reconnect under its old id before
199
+ * the server has noticed the old connection close, which ends that
200
+ * connection's sessions a moment later.
201
+ */
202
+ sessionWaitMs = 2_000;
203
+ /** Set by {@link dispose}; a disposed storage registers no session again. */
204
+ disposed = false;
133
205
  /**
134
206
  * Whether an external resubmit has ever been dispatched. Gates the
135
207
  * keep-the-last-valid-GModel branch, which needs to know a canvas is already
@@ -155,6 +227,7 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
155
227
  if (this.state.clientId === TEMPORARY_CLIENT_ID) {
156
228
  return;
157
229
  }
230
+ this.state.modelSession = this.registerModelSession();
158
231
  this.sessionManager.addListener(this, this.state.clientId);
159
232
  // Watched for this storage's whole lifetime rather than per load. The load
160
233
  // flow is a documented override point, so a subscription parked there would
@@ -162,6 +235,88 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
162
235
  // run long after any load.
163
236
  this.toDispose.push(this.state.onSecondaryUrisChanged(() => this.reconcileSecondarySubscriptions()));
164
237
  }
238
+ /**
239
+ * Register the diagram's client session under the GLSP client id, or
240
+ * `undefined` when another participant holds that id, which is logged.
241
+ *
242
+ * The diagram then refuses to load ({@link requireModelSession}). Taking
243
+ * the id over would end the other participant's session under it, and
244
+ * working without a session would share that participant's opens and
245
+ * echoes, so its close would take the diagram's documents with it.
246
+ */
247
+ registerModelSession() {
248
+ try {
249
+ return this.sharedServices.model.ModelService.createSession('diagram', this.state.clientId);
250
+ }
251
+ catch (error) {
252
+ if (!isDuplicateClientIdError(error)) {
253
+ throw error;
254
+ }
255
+ this.logger.warn(`Client id ${this.state.clientId} is held by another participant: this diagram has no session yet`);
256
+ return undefined;
257
+ }
258
+ }
259
+ /**
260
+ * The diagram's client session, registering it again when the id was held
261
+ * earlier. Throws `SessionClosedError` once the storage is disposed, and the
262
+ * refusal when the id is still held.
263
+ */
264
+ requireModelSession() {
265
+ if (this.disposed) {
266
+ throw new SessionClosedError(this.state.clientId, `The diagram of ${this.state.clientId} has closed; its client session has ended`);
267
+ }
268
+ if (!this.state.modelSession) {
269
+ this.state.modelSession = this.registerModelSession();
270
+ }
271
+ const session = this.state.modelSession;
272
+ if (!session) {
273
+ throw new GLSPServerError(this.sharedServices.MessageRenderer.renderMessage(DIAGRAM_SESSION_REFUSED), `clientId=${this.state.clientId} is still held by another participant, so this diagram has no client session`);
274
+ }
275
+ return session;
276
+ }
277
+ /**
278
+ * {@link requireModelSession} for the load: while the id is held, wait up to
279
+ * {@link sessionWaitMs} for its holder to end before refusing, and tell the
280
+ * user when it does not.
281
+ */
282
+ async awaitModelSession() {
283
+ if (!this.state.modelSession && !this.disposed) {
284
+ this.state.modelSession = this.registerModelSession();
285
+ }
286
+ if (!this.state.modelSession && !this.disposed) {
287
+ await this.waitForSessionEnd(this.state.clientId, this.sessionWaitMs);
288
+ }
289
+ try {
290
+ return this.requireModelSession();
291
+ }
292
+ catch (error) {
293
+ // A diagram closed while it waited has no client left to tell.
294
+ if (isSessionClosedError(error)) {
295
+ throw error;
296
+ }
297
+ this.logger.error(`Client id ${this.state.clientId} is still held by another participant: this diagram does not load`);
298
+ this.actionDispatcher
299
+ .dispatch(MessageAction.create(this.sharedServices.MessageRenderer.renderMessage(DIAGRAM_SESSION_REFUSED), { severity: 'ERROR' }))
300
+ .catch((dispatchError) => this.logger.warn(`Could not tell the client the diagram was refused: ${String(dispatchError)}`));
301
+ throw error;
302
+ }
303
+ }
304
+ /** Resolve once the client session under `clientId` ends, or after `timeoutMs`. */
305
+ waitForSessionEnd(clientId, timeoutMs) {
306
+ return new Promise(resolve => {
307
+ const subscriptions = new DisposableCollection();
308
+ const done = () => {
309
+ subscriptions.dispose();
310
+ resolve();
311
+ };
312
+ subscriptions.push(this.sharedServices.Clock.setTimer(done, timeoutMs));
313
+ subscriptions.push(this.sharedServices.workspace.TextDocuments.onDidCloseSession(event => {
314
+ if (event.clientId === clientId) {
315
+ done();
316
+ }
317
+ }));
318
+ });
319
+ }
165
320
  /**
166
321
  * Default load flow — {@link doLoadSourceModel}. Adopters whose load flow
167
322
  * needs more than the seams allow override this method.
@@ -175,8 +330,8 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
175
330
  const modelService = this.sharedServices.model.ModelService;
176
331
  // Open FIRST: a workspace-scanned-but-never-didOpened document rebuilds here,
177
332
  // so the capture below settles on a built root rather than a transient
178
- // mid-rebuild one.
179
- this.toDispose.push(await modelService.open({ uri: rootUri, clientId: this.state.clientId }));
333
+ // mid-rebuild one. Closed when the session ends.
334
+ await (await this.awaitModelSession()).open(rootUri);
180
335
  // GLSP's sessionDisposed is unreliable on Theia tab-close; dispose on client
181
336
  // detach so reopens don't accumulate stale onModelUpdated listeners.
182
337
  this.toDispose.push(modelService.onClientClosed(rootUri, this.state.clientId, () => {
@@ -192,12 +347,29 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
192
347
  await this.captureSettledRoot(rootUri, document);
193
348
  }
194
349
  /**
195
- * Capture the initial settled root and apply the initial edit mode. `settled()`
196
- * strips diagnostics by phase contract, so the first edit mode is `EDITABLE`;
197
- * the first {@link handleModelUpdated} (at `Validated`, with diagnostics) flips
198
- * it READONLY if the document has structural parse errors. Edit-mode +
199
- * settle-hook actions are dispatched on a macrotask so the initial
350
+ * Capture the initial settled root and apply the initial edit mode. Edit-mode
351
+ * + settle-hook actions are dispatched on a macrotask so the initial
200
352
  * `requestModel → setModel` handshake isn't perturbed.
353
+ *
354
+ * **Whether the settled document carries diagnostics depends on how far it
355
+ * had already got, so the initial edit mode has two correct outcomes rather
356
+ * than one.** `settled()` strips nothing: it resolves AT OR ABOVE the
357
+ * integrity landmark and hands back the live document's own array. Its
358
+ * `AstDocument<TAst, never>` return type asserts emptiness for a document the
359
+ * wait had to DRIVE to that landmark, which is pre-validation — and for that
360
+ * one the mode here is `EDITABLE` and the flip to READONLY arrives with the
361
+ * first {@link handleModelUpdated}. A document already past `Validated` when
362
+ * the session opened resolves immediately with its diagnostics intact, and is
363
+ * decided correctly here with no later update owed. Any host that validates
364
+ * its workspace before a diagram is opened produces the second case, so
365
+ * neither is exceptional.
366
+ *
367
+ * **A correct decision is not a delivered one.** This dispatch happens inside
368
+ * the initial `requestModel`, before the client has the model — so the UI
369
+ * extensions that answer {@link onParseErrorChanged}'s actions are not yet
370
+ * constructed, and a canvas that opens READONLY over a broken document shows
371
+ * none of that feedback. The same timer carries {@link onSourceModelSettled},
372
+ * so an adopter's own initial actions have it too.
201
373
  */
202
374
  async captureSettledRoot(rootUri, document) {
203
375
  this.state.setSourceRoot(rootUri, document.root);
@@ -231,14 +403,40 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
231
403
  if (!current.has(uri)) {
232
404
  subscription.dispose();
233
405
  this.secondarySubscriptions.delete(uri);
406
+ this.departedSecondaries.add(uri);
234
407
  }
235
408
  }
236
409
  for (const uri of current) {
237
410
  if (!this.secondarySubscriptions.has(uri)) {
411
+ this.departedSecondaries.delete(uri);
238
412
  this.secondarySubscriptions.set(uri, this.sharedServices.model.ModelService.onModelUpdated(uri, event => this.handleSecondaryUpdated(uri, event)));
413
+ this.openSecondary(uri);
239
414
  }
240
415
  }
241
416
  }
417
+ /**
418
+ * Open a document that joined the write set through the diagram's session,
419
+ * where it stays open until the diagram's next save after it leaves the set,
420
+ * or the diagram's end. A document that does not exist yet is left to the
421
+ * write that creates it, and a failed open is logged: the write that needs
422
+ * the document opens it again and fails there.
423
+ */
424
+ openSecondary(uri) {
425
+ const session = this.state.modelSession;
426
+ if (!session || !this.sharedServices.model.ModelService.getDocument(uri)) {
427
+ return;
428
+ }
429
+ session.open(uri).catch((error) => {
430
+ const detail = `Could not open ${uri} for ${this.state.clientId}: ${error instanceof Error ? error.message : String(error)}`;
431
+ // A session ending while the open reads is the diagram closing.
432
+ if (isSessionClosedError(error)) {
433
+ this.logger.debug(detail);
434
+ }
435
+ else {
436
+ this.logger.warn(detail);
437
+ }
438
+ });
439
+ }
242
440
  /**
243
441
  * React to a rebuild of a SECONDARY document by resubmitting the diagram, so
244
442
  * an external edit to (say) a layout file reaches the canvas.
@@ -284,9 +482,10 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
284
482
  *
285
483
  * Synchronous by construction — the phase-agnostic lookup door plus the shared
286
484
  * projection — so reacting to a secondary neither waits nor can force a build.
287
- * `settled()` is not an alternative: it strips diagnostics by phase contract,
288
- * and diagnostics are the reason {@link doUpdateAndSubmit} takes a separate
289
- * event document at all.
485
+ * `settled()` is not an alternative: besides being asynchronous, it cannot be
486
+ * relied on to carry diagnostics — a document it has to drive to the landmark
487
+ * arrives pre-validation with an empty array — and diagnostics are the reason
488
+ * {@link doUpdateAndSubmit} takes a separate event document at all.
290
489
  */
291
490
  currentPrimaryDocument() {
292
491
  const document = this.sharedServices.model.ModelService.getDocument(this.state.sourceUri);
@@ -360,8 +559,10 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
360
559
  /**
361
560
  * Re-settle to a guaranteed fully-linked + reprojected root, capture it, and
362
561
  * (unless suppressed) resubmit a deduped external GModel. Diagnostics for the
363
- * edit-mode decision come from the event document (`settled()` strips them by
364
- * phase contract).
562
+ * edit-mode decision come from the event document, because the re-settled one
563
+ * cannot be relied on to have any: a document driven to the landmark arrives
564
+ * pre-validation, and this path re-settles precisely to escape a transient
565
+ * mid-rebuild snapshot.
365
566
  */
366
567
  async doUpdateAndSubmit(rootUri, eventDocument) {
367
568
  // Settle-gate the capture: never setSourceRoot off the event's possibly-transient
@@ -419,15 +620,48 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
419
620
  return document.diagnostics.some(diagnostic => isStructuralDiagnostic(diagnostic));
420
621
  }
421
622
  /**
422
- * Seam: actions to emit when the structural-broken state transitions. Default:
423
- * a single {@link SetEditModeAction} toggling READONLY ↔ EDITABLE — editing is
424
- * disabled while the syntax is broken but re-enabled once it parses, a sound
425
- * generic for any Langium-backed diagram. Adopters override to add or replace
426
- * the transition feedback. The {@link AbstractHydraniumGlspState.editMode}
427
- * flip itself is owned by {@link refreshEditMode}.
623
+ * Seam: actions to emit when the structural-broken state transitions.
624
+ * Default: a {@link SetEditModeAction} toggling READONLY ↔ EDITABLE — editing
625
+ * is disabled while the syntax is broken but re-enabled once it parses, a
626
+ * sound generic for any Langium-backed diagram — plus the
627
+ * {@link DIAGRAM_READONLY_PARSE_ERROR} band that says why, cleared on the way
628
+ * back. Adopters override to add or replace the transition feedback. The
629
+ * {@link AbstractHydraniumGlspState.editMode} flip itself is owned by
630
+ * {@link refreshEditMode}.
631
+ *
632
+ * **Both actions or neither, which is why they are one seam rather than
633
+ * two.** The mode flip removes the tool palette and the band is the only
634
+ * account of that, so an override that keeps one and drops the other produces
635
+ * either an unexplained loss of the palette or a warning about a restriction
636
+ * that is not in force.
637
+ *
638
+ * **The status is dispatched with no `timeout`, so it persists** — a
639
+ * time-limited band would describe a condition that outlasts it.
640
+ *
641
+ * **The slot is SHARED, and the other writer wins on one path.**
642
+ * `ModelSubmissionHandler`'s live validation writes the same slot, clearing
643
+ * it with `severity: 'NONE'` when it finishes, and an adopter dispatching its
644
+ * own `StatusAction` replaces this one too. Nothing re-asserts it. That is
645
+ * harmless while a document is being edited, because a resubmit is skipped
646
+ * once the AST is broken (see {@link doUpdateAndSubmit}) — but NOT at load:
647
+ * the initial `requestModel` submit is not that skipped path, so a diagram
648
+ * opened on an already-broken document shows this band and then loses it to
649
+ * the validation clear a moment later. Measured on a browser host, polling the
650
+ * overlay: no element, empty, the sentence, empty again.
428
651
  */
429
652
  onParseErrorChanged(_document, broken) {
430
- return [SetEditModeAction.create(broken ? EditMode.READONLY : EditMode.EDITABLE)];
653
+ return [
654
+ SetEditModeAction.create(broken ? EditMode.READONLY : EditMode.EDITABLE),
655
+ broken
656
+ ? StatusAction.create(this.sharedServices.MessageRenderer.renderMessage(DIAGRAM_READONLY_PARSE_ERROR), {
657
+ severity: 'WARNING'
658
+ })
659
+ : // `NONE` is the client's own spelling for "clear", not a severity it
660
+ // renders: `StatusOverlay.handle` branches on it before touching the
661
+ // DOM. An empty message at any other severity leaves an empty band
662
+ // with a warning icon standing on the canvas.
663
+ StatusAction.create('', { severity: 'NONE' })
664
+ ];
431
665
  }
432
666
  /**
433
667
  * Seam: extra actions to dispatch right after the initial settled root is
@@ -436,31 +670,47 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
436
670
  onSourceModelSettled(_document) {
437
671
  return [];
438
672
  }
439
- /** The effective {@link SaveConflictPolicy}: the bound option, or {@link DEFAULT_SAVE_CONFLICT_POLICY} when unbound. */
440
- get saveConflictPolicy() {
441
- return this.boundSaveConflictPolicy ?? DEFAULT_SAVE_CONFLICT_POLICY;
673
+ /** The effective {@link SaveDeliveryPolicy}: the bound option, or {@link DEFAULT_SAVE_DELIVERY_POLICY} when unbound. */
674
+ get saveDeliveryPolicy() {
675
+ return this.boundSaveDeliveryPolicy ?? DEFAULT_SAVE_DELIVERY_POLICY;
442
676
  }
443
677
  /**
444
- * Default save flow: route through `ModelService.save`. The framework
445
- * serialise-and-persist machinery handles serialisation (via the
446
- * language-specific `Serializer` bound at `services.serializer.Serializer`),
447
- * the multi-client text-document update, the rebuild, and the eventual
448
- * `WritableFileSystemProvider.writeFile`.
678
+ * Default save flow: persist the store's current text for every document the
679
+ * diagram's session has open.
680
+ *
681
+ * **A save persists, it does not author.** Every diagram gesture already
682
+ * reached the store through the diagram's session, so the store holds the
683
+ * settled text and disk is the only thing behind. Re-serializing from the AST
684
+ * here cannot improve on that text and can only damage it: a serializer
685
+ * normalises formatting, and the comments the write path carries over keep
686
+ * none of the hand-formatting around them, so a save would reflow a document
687
+ * nothing changed — which is what a pure bounds drag does to the semantic
688
+ * file when only its layout moved.
689
+ *
690
+ * **What is saved is the primary, every tracked secondary
691
+ * (`AbstractHydraniumGlspState.trackSecondaryDocument`) and every document
692
+ * that left the write set since the last save**, so a document the diagram
693
+ * wrote is persisted whether or not it is the one the client named. One the
694
+ * diagram's session does not have open is skipped, even when another client
695
+ * has it open: that client's unsaved edits are not the diagram's to persist.
696
+ *
697
+ * **A save therefore names documents the gesture did not aim at**, which is
698
+ * why an unchanged one is not rewritten even though the user asked for a
699
+ * save: the mtime would move on a file they never touched.
700
+ * `AstDocumentManager.save` decides that per document and announces the save
701
+ * either way.
449
702
  *
450
- * The configured {@link SaveConflictPolicy} (see {@link saveConflictPolicy})
451
- * decides how a concurrent edit that advanced the document is handled:
452
- * - `overwrite` (default): no based-on guard, await, propagate failures —
453
- * last-write-wins, correct for a single-editor head.
454
- * - `reject`: guard on the captured `state.version`, await, surface a
455
- * `ConflictError` (and any other failure) to the GLSP save action.
456
- * - `drop-and-log`: guard, fire-and-forget, log + swallow failures — a stale
457
- * diagram save is dropped because a concurrent form/code edit already wrote
458
- * the truth, and GLSP exposes no save-failure back-channel.
703
+ * The configured {@link SaveDeliveryPolicy} (see {@link saveDeliveryPolicy})
704
+ * decides await-vs-fire-and-forget and failure handling. It carries no
705
+ * based-on guard: the guard exists to stop a stale writer overwriting a newer
706
+ * document, and a flush persists the store — which already holds every other
707
+ * client's change, including the one that advanced the version.
459
708
  *
460
709
  * Returns `MaybePromise<void>` to match upstream `SourceModelStorage`:
461
- * resolves with the persist under `overwrite`/`reject`, returns synchronously
462
- * under `drop-and-log`. Adopters that bypass `ModelService` (writing through
463
- * `WritableFileSystemProvider` directly) still override the whole method.
710
+ * resolves with the flush under `await`, returns synchronously under
711
+ * `fire-and-forget`. Adopters that bypass `AstDocumentManager` (writing
712
+ * through `WritableFileSystemProvider` directly) still override the whole
713
+ * method.
464
714
  */
465
715
  saveSourceModel(action) {
466
716
  // Normalised for the same reason the load path is: `SaveModelAction.fileUri`
@@ -470,24 +720,46 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
470
720
  // the call site rather than inside `getFileUri` so that method's contract —
471
721
  // return what the action said — is unchanged for adopters overriding it.
472
722
  const uri = this.toSourceModelUri(this.getFileUri(action));
473
- const policy = this.saveConflictPolicy;
474
- const persisted = this.sharedServices.model.ModelService.save({
475
- uri,
476
- model: this.state.sourceRoot,
477
- clientId: this.state.clientId,
478
- baseVersion: policy.kind === 'overwrite' ? undefined : this.state.version
479
- }).then(() => undefined);
480
- if (policy.kind === 'drop-and-log') {
481
- // Fire-and-forget: the diagram save lost the race to a concurrent edit
482
- // that already persisted the truth, so it must neither block the action
483
- // nor surface. Log rather than leave an unhandled rejection.
723
+ const policy = this.saveDeliveryPolicy;
724
+ const persisted = this.flushWriteSet(uri);
725
+ if (policy.kind === 'fire-and-forget') {
726
+ // Log rather than leave an unhandled rejection: the promise is not
727
+ // returned, so nothing else will observe a failure.
484
728
  persisted.catch(error => this.logger.error(`Save failed for ${uri}: ${error instanceof Error ? error.message : String(error)}`));
485
729
  return undefined;
486
730
  }
487
- // overwrite / reject: await; a ConflictError (reject) or any other failure
488
- // propagates to GLSP's save-action handler.
731
+ // Awaited: any failure propagates to GLSP's save-action handler.
489
732
  return persisted;
490
733
  }
734
+ /**
735
+ * Save the stored text of `primaryUri`, every tracked secondary and every
736
+ * document that left the write set since the last save, each only where
737
+ * the diagram's session has it open; then close those that left.
738
+ *
739
+ * Deduplicated, because a state that tracks its own primary as a secondary
740
+ * would otherwise save it twice and fire two save notifications for one
741
+ * save. Every save is called in one synchronous step, so each takes its text
742
+ * before anything can close a document of the set: saved one after another,
743
+ * a GLSP session ending during the first write closes the rest unsaved.
744
+ */
745
+ async flushWriteSet(primaryUri) {
746
+ // Refused like the load: without a session the client id's opens are
747
+ // another participant's, and this would save them.
748
+ this.requireModelSession();
749
+ const documents = this.sharedServices.workspace.AstDocumentManager;
750
+ const textDocuments = this.sharedServices.workspace.TextDocuments;
751
+ const clientId = this.state.clientId;
752
+ // Taken with the targets: a document leaving the set during the writes
753
+ // was not saved by them, and stays open for the next save.
754
+ const departed = [...this.departedSecondaries];
755
+ const targets = [...new Set([primaryUri, ...this.state.secondaryUris, ...departed])].filter(uri => textDocuments.isOpenInClient(uri, clientId));
756
+ await Promise.all(targets.map(target => documents.save(target, clientId)));
757
+ for (const uri of departed) {
758
+ if (this.departedSecondaries.delete(uri) && uri !== this.state.sourceUri) {
759
+ await this.state.modelSession?.close(uri);
760
+ }
761
+ }
762
+ }
491
763
  /**
492
764
  * Normalise GLSP's `sourceUri` — which may be a filesystem PATH or a URI
493
765
  * string — to the URI string the workspace keys documents by.
@@ -516,11 +788,22 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
516
788
  *
517
789
  * Returns it VERBATIM, in whatever form the client sent;
518
790
  * {@link toSourceModelUri} is what normalises it.
791
+ *
792
+ * A model request DOES carry a request id, so a throw here takes the
793
+ * client-request path rather than the toast path — and on that path `detail`
794
+ * comes from `cause?.toString?.()`. A single-argument throw therefore reaches
795
+ * neither the server log nor the client console: both print `undefined`. So
796
+ * the two readers are addressed separately, as on the save path: `message`
797
+ * names what failed in the user's terms and is rendered, `cause` names the
798
+ * action and the option key that was missing and stays English. On THIS path
799
+ * the cause reaches only logs — `RejectAction.detail` is read by nothing but
800
+ * the client action-dispatcher's `logger.warn` — which is not what makes it
801
+ * English; its content is.
519
802
  */
520
803
  getSourceUri(action) {
521
804
  const sourceUri = action.options?.[SOURCE_URI_ARG];
522
805
  if (typeof sourceUri !== 'string') {
523
- throw new GLSPServerError(`Invalid RequestModelAction! Missing argument with key '${SOURCE_URI_ARG}'`);
806
+ throw new GLSPServerError(this.sharedServices.MessageRenderer.renderMessage(SOURCE_URI_MISSING), `no '${SOURCE_URI_ARG}' option on the ${action.kind} action (received ${typeof sourceUri})`);
524
807
  }
525
808
  return sourceUri;
526
809
  }
@@ -531,17 +814,23 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
531
814
  * {@link AbstractHydraniumGlspState.setSourceRoot}.
532
815
  *
533
816
  * A save action carries no request id, so a throw here reaches the user as a
534
- * toast built from `message`, with `cause` behind its details control. The
535
- * two therefore address different readers and must not be collapsed: the
536
- * message names what failed in the user's terms, and the cause names which
537
- * lookups came back empty for whom. Neither can name the URI — not having
538
- * one IS the failure, and both sources are written together, so the typed
539
- * `sourceUri` is equally empty whenever this fires.
817
+ * toast built from `message`, while `cause` travels in
818
+ * `MessageAction.details` — **which a Theia host DOES put in front of a
819
+ * user**, as a "Show details" button on the toast opening a dialog. So the
820
+ * two are not split by reachability; they are split by AUDIENCE, which is
821
+ * the older rule and the one that holds here. The message names what failed
822
+ * in the user's terms and is rendered; the cause names which lookups came
823
+ * back empty for whom, and stays English because a wire action kind, an
824
+ * option key and a client id address whoever composes the system — a
825
+ * translated developer string is a worse outcome than an untranslated one.
826
+ * Neither can name the URI — not having one IS the failure, and both sources
827
+ * are written together, so the typed `sourceUri` is equally empty whenever
828
+ * this fires.
540
829
  */
541
830
  getFileUri(action) {
542
831
  const uri = action.fileUri ?? this.state.get(SOURCE_URI_ARG);
543
832
  if (!uri) {
544
- throw new GLSPServerError('Could not determine where to save this model', `no fileUri on the save action and no ${SOURCE_URI_ARG} in the model state (clientId=${this.state.clientId})`);
833
+ throw new GLSPServerError(this.sharedServices.MessageRenderer.renderMessage(SAVE_TARGET_UNKNOWN), `no fileUri on the save action and no ${SOURCE_URI_ARG} in the model state (clientId=${this.state.clientId})`);
545
834
  }
546
835
  return uri;
547
836
  }
@@ -569,10 +858,14 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
569
858
  this.dispose();
570
859
  }
571
860
  /**
572
- * Cancel any pending resubmit and drain every subscription — those registered
861
+ * Cancel any pending resubmit, drain every subscription — those registered
573
862
  * during {@link doLoadSourceModel} and the per-secondary ones, which live
574
- * outside {@link toDispose} because they come and go with the write set.
863
+ * outside {@link toDispose} because they come and go with the write set —
864
+ * and end the diagram's client session, closing everything it has open.
575
865
  * Idempotent.
866
+ *
867
+ * The session ends last, once the detach listener is gone: its closes would
868
+ * otherwise report this storage's own teardown as a client detaching.
576
869
  */
577
870
  dispose() {
578
871
  this.resubmitDebouncer?.dispose();
@@ -581,6 +874,9 @@ let HydraniumGlspStorage = class HydraniumGlspStorage {
581
874
  }
582
875
  this.secondarySubscriptions.clear();
583
876
  this.toDispose.dispose();
877
+ this.disposed = true;
878
+ this.state.modelSession?.dispose();
879
+ this.state.modelSession = undefined;
584
880
  }
585
881
  };
586
882
  __decorate([
@@ -617,10 +913,10 @@ __decorate([
617
913
  __metadata("design:type", Object)
618
914
  ], HydraniumGlspStorage.prototype, "modelValidator", void 0);
619
915
  __decorate([
620
- inject(SaveConflictPolicy),
916
+ inject(SaveDeliveryPolicy),
621
917
  optional(),
622
918
  __metadata("design:type", Object)
623
- ], HydraniumGlspStorage.prototype, "boundSaveConflictPolicy", void 0);
919
+ ], HydraniumGlspStorage.prototype, "boundSaveDeliveryPolicy", void 0);
624
920
  __decorate([
625
921
  postConstruct(),
626
922
  __metadata("design:type", Function),