@widgetic/editor 4.1.22 → 4.1.23

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.
@@ -38,11 +38,17 @@
38
38
  * (`setEditsBlocked`): the props editor and the preview's resize then change nothing, however the call got there.
39
39
  * Blocking is not locking: it never touches what was edited before it (that is saved as usual), and it never makes a
40
40
  * save fail, so a teammate's presence can never cost a person their work.
41
+ * - A tab that comes back is looked at (`startStaleGuard`): the composition is asked for with the content version this
42
+ * editor shows (a conditional GET: 304 and no body when nothing was saved since), and when a newer one was saved
43
+ * elsewhere (an MCP client, the assistant, another tab, a teammate) it replaces what is on the screen, behind a dark
44
+ * layer (`state.refreshing`) while edits are refused, so a copy that is out of date is never edited. Edits that are not
45
+ * saved yet are never replaced: they raise the same `state.conflict` a refused save does, and the person chooses.
41
46
  * - After `dispose()` nothing more happens: no request goes out, and answers still on their way are ignored.
42
47
  */
43
48
  import type { Translate } from '@widgetic/design-system/i18n';
44
49
  import type { EditorMessageKey } from '../i18n/messages.js';
45
50
  import type { CompositionApi } from './compositionApi.js';
51
+ import { type StaleGuardOptions } from './staleGuard.js';
46
52
  import { type JsonRecord } from './compositionHelpers.js';
47
53
  import { type CompositionEditorShellStore } from './compositionEditorSchemaCache.js';
48
54
  import { type DraftJournal, type DraftJournalOptions } from '../drafts/draftJournal.js';
@@ -135,10 +141,17 @@ export interface CompositionEditorState {
135
141
  /** The last save failed (cleared when the next one starts). A save refused because the content changed is a `conflict`, not this. */
136
142
  saveError: EditorFailure | null;
137
143
  /**
138
- * The last save was refused because a teammate saved the content since it was loaded. Every edit is kept and
139
- * nothing is saved until the person chooses (`keepMyChanges` or `loadLatestVersion`). `null` when there is none.
144
+ * Somebody else saved the content since it was loaded, and this editor has edits that are not saved: found when a save
145
+ * was refused, or when the tab came back (`startStaleGuard`). Every edit is kept and nothing is saved until the person
146
+ * chooses (`keepMyChanges` or `loadLatestVersion`). `null` when there is none.
140
147
  */
141
148
  conflict: EditorConflict | null;
149
+ /**
150
+ * The tab came back and a newer copy saved elsewhere is being put on the screen (`startStaleGuard`). The screen shows a
151
+ * dark layer meanwhile, and `changeProperty` and `changeContentItems` change nothing, so a copy that is out of date is
152
+ * never edited.
153
+ */
154
+ refreshing: boolean;
142
155
  /**
143
156
  * The editor takes no new edit: a teammate is editing this composition, or the person chose to only look (see
144
157
  * `setEditsBlocked`). What was edited before is still saved. The preview keeps working.
@@ -163,7 +176,10 @@ export type CompositionEditorEvent = {
163
176
  failure: EditorFailure;
164
177
  fatal: boolean;
165
178
  }
166
- /** A save was refused because a teammate saved the content first (not an `error`: nothing is lost, the person chooses). */
179
+ /**
180
+ * A teammate saved the content first and this editor has edits that are not saved: a save was refused, or the tab came back
181
+ * and found a newer copy (not an `error`: nothing is lost, the person chooses).
182
+ */
167
183
  | {
168
184
  type: 'conflict';
169
185
  conflict: EditorConflict;
@@ -234,6 +250,11 @@ export interface CompositionEditorOptions {
234
250
  draftJournal?: DraftJournal<CompositionDraftPayload> | null;
235
251
  /** Options for the default journal when `draftJournal` is not passed. */
236
252
  draftJournalOptions?: DraftJournalOptions;
253
+ /**
254
+ * The clock and the wake-ups of the guard that looks at a tab that comes back (see `startStaleGuard`), and its waits, so a
255
+ * test can move them by hand. Default: the page's window, document and timers, and the waits named in `staleGuard.ts`.
256
+ */
257
+ staleGuardOptions?: Partial<Pick<StaleGuardOptions<number, JsonRecord>, 'environment' | 'minimumGapMilliseconds' | 'minimumOverlayMilliseconds' | 'busyRetryMilliseconds' | 'maximumBusyRetries'>>;
237
258
  }
238
259
  /** What went wrong, from whatever was thrown. */
239
260
  export declare function describeFailure(error: unknown): EditorFailure;
@@ -285,6 +306,8 @@ export declare class CompositionEditorController {
285
306
  private lastJournaledPayload;
286
307
  private leaveFlushDisposer;
287
308
  private leaveSaveIdempotencyKey;
309
+ /** Looks at the tab when it comes back (see `startStaleGuard`); `null` until it is started. */
310
+ private staleGuard;
288
311
  constructor(options: CompositionEditorOptions);
289
312
  /** The state now. It is never changed in place: a change makes a new object. */
290
313
  getState(): CompositionEditorState;
@@ -402,6 +425,43 @@ export declare class CompositionEditorController {
402
425
  * dropped. The preview is told the new values (its page may not reload, when the widget is the same).
403
426
  */
404
427
  loadLatestVersion(): Promise<void>;
428
+ /**
429
+ * Starts looking at the tab whenever the person comes back to it (the window gets focus, the tab becomes visible, the
430
+ * network is back, the page is shown again). Each time, at most every few seconds, the composition is asked for with the
431
+ * content version this editor shows: the API answers 304 with no body when nothing was saved since, so a tab nobody
432
+ * touched costs a header. When a newer version was saved elsewhere (an MCP client, the assistant, another tab, a
433
+ * teammate), it is put on the screen on the spot, behind a dark layer (`state.refreshing`) during which edits are refused,
434
+ * so a copy that is out of date is never edited. The values and the items are replaced and the preview is told; the schemas
435
+ * and the preview page stay (a composition that moved to another widget is loaded again in full).
436
+ *
437
+ * Edits that are not saved are never replaced: they raise `state.conflict`, the same choice a refused save does ("Keep my
438
+ * changes" / "Use the latest version"), and the guard waits for it. A save that is on its way is waited for first, and an
439
+ * own save is never taken for news. Nothing is shown when the question fails: the next time the person comes back it is
440
+ * asked again. Call it once the editor is on the screen (the component does, in `onMount`); asking again does nothing.
441
+ */
442
+ startStaleGuard(): void;
443
+ /**
444
+ * Whether the copy on the screen may be replaced now. `skip`: there is nothing to bring up to date (still loading, failed)
445
+ * or a choice is already waiting for the person. `busy`: a save (or a reload of the schemas) is on its way, and its answer
446
+ * moves the version, so look again in a moment. `dirty`: edits that are not saved, which are never replaced.
447
+ */
448
+ private readStaleGuardBlocker;
449
+ /** Puts the newer copy on the screen: in place when it is the same widget, in full (a load) when the widget is another. */
450
+ private adoptNewerComposition;
451
+ /**
452
+ * The composition as it was saved elsewhere replaces the values and the items on the screen (the schemas stay: it is the
453
+ * same widget), the version later saves are checked against moves to its version, and the preview is told. Nothing is
454
+ * unsaved at this point (the guard never gets here with edits), so the draft kept for a refresh is dropped too.
455
+ */
456
+ private adoptComposition;
457
+ /**
458
+ * The tab came back and found a newer version while it has edits that are not saved: they are kept, nothing is saved, and
459
+ * the person gets the choice a refused save gives ("Keep my changes" / "Use the latest version"). Who saved the newer
460
+ * version and when are not known from a conditional read, so the card says it plainly.
461
+ */
462
+ private raiseContentConflict;
463
+ /** The guard's own notes: what could not be done is a warning, what went well a line for a developer's console. */
464
+ private logStaleGuard;
405
465
  /** Starts the wait for an autosave of what is unsaved (for callers that have something unsaved). */
406
466
  private scheduleAutosave;
407
467
  /** After an autosave failed for a reason that may pass: try again later, but only so many times. */
@@ -38,9 +38,15 @@
38
38
  * (`setEditsBlocked`): the props editor and the preview's resize then change nothing, however the call got there.
39
39
  * Blocking is not locking: it never touches what was edited before it (that is saved as usual), and it never makes a
40
40
  * save fail, so a teammate's presence can never cost a person their work.
41
+ * - A tab that comes back is looked at (`startStaleGuard`): the composition is asked for with the content version this
42
+ * editor shows (a conditional GET: 304 and no body when nothing was saved since), and when a newer one was saved
43
+ * elsewhere (an MCP client, the assistant, another tab, a teammate) it replaces what is on the screen, behind a dark
44
+ * layer (`state.refreshing`) while edits are refused, so a copy that is out of date is never edited. Edits that are not
45
+ * saved yet are never replaced: they raise the same `state.conflict` a refused save does, and the person chooses.
41
46
  * - After `dispose()` nothing more happens: no request goes out, and answers still on their way are ignored.
42
47
  */
43
48
  import { translateEnglish } from '../i18n/translate.js';
49
+ import { createStaleGuard } from './staleGuard.js';
44
50
  import { buildPropsEditorContentSchema, compositionContentVersion, compositionWidgetId, contentItemsToEditorValueMap, ensureSubtitleFontInDesignSchema, extractContentItemsFromCompositionRaw, extractContentValuesFromCompositionRaw, flattenContentItemsForPreview, flattenDesignValuesForPreview, getCompositionEmbedSettings, mergeContentItemsWithSchema, mergeMissingContentValues, normalizeContentSchemaFromApiResponse, normalizeDesignSchemaFromApiResponse, parseEmbedDimension, readContentVersion, seedMissingFontFaces } from './compositionHelpers.js';
45
51
  import { createCompositionEditorShellStore } from './compositionEditorSchemaCache.js';
46
52
  import { createDraftJournal } from '../drafts/draftJournal.js';
@@ -177,6 +183,26 @@ function schemaContentItems(contentSchema) {
177
183
  const items = contentSchema?.contentItems ?? contentSchema?.data?.contentItems;
178
184
  return Array.isArray(items) ? items : [];
179
185
  }
186
+ /**
187
+ * The values to edit, from a composition record and the content schema of its widget. The one reading of a record that a
188
+ * load and a refresh of a tab that came back share, so the editor shows the same thing either way.
189
+ */
190
+ function readEditedValues(composition, contentSchema) {
191
+ const rawContent = (isRecord(composition.content) ? composition.content : {});
192
+ const designValues = seedMissingFontFaces((rawContent.design ?? composition.design ?? {}));
193
+ const contentValues = mergeMissingContentValues(extractContentValuesFromCompositionRaw(rawContent), contentSchema);
194
+ // (With no items in the schema, the items are the saved ones as they are.)
195
+ const contentItems = mergeContentItemsWithSchema(extractContentItemsFromCompositionRaw(rawContent), schemaContentItems(contentSchema));
196
+ const embedSettings = getCompositionEmbedSettings(composition);
197
+ return {
198
+ designValues,
199
+ contentValues,
200
+ contentItems,
201
+ embedSettings,
202
+ embedWidth: parseEmbedDimension(embedSettings.width, DEFAULT_PREVIEW_WIDTH),
203
+ embedHeight: parseEmbedDimension(embedSettings.height, DEFAULT_PREVIEW_HEIGHT)
204
+ };
205
+ }
180
206
  export class CompositionEditorController {
181
207
  options;
182
208
  timers;
@@ -223,6 +249,8 @@ export class CompositionEditorController {
223
249
  lastJournaledPayload = null;
224
250
  leaveFlushDisposer = null;
225
251
  leaveSaveIdempotencyKey = null;
252
+ /** Looks at the tab when it comes back (see `startStaleGuard`); `null` until it is started. */
253
+ staleGuard = null;
226
254
  constructor(options) {
227
255
  if (typeof options?.compositionId !== 'string' || options.compositionId.trim() === '') {
228
256
  throw new TypeError('CompositionEditorController needs a composition id');
@@ -275,6 +303,7 @@ export class CompositionEditorController {
275
303
  saving: false,
276
304
  saveError: null,
277
305
  conflict: null,
306
+ refreshing: false,
278
307
  editsBlocked: false,
279
308
  loadError: null,
280
309
  lastSavedAt: null
@@ -475,14 +504,8 @@ export class CompositionEditorController {
475
504
  : null;
476
505
  const schemas = this.readSchemas(designResult, contentResult);
477
506
  // The values being edited: what the composition saved, with the schema's defaults for what it never saved.
478
- const rawContent = (isRecord(composition.content) ? composition.content : {});
479
- const designValues = seedMissingFontFaces((rawContent.design ?? composition.design ?? {}));
480
- const contentValues = mergeMissingContentValues(extractContentValuesFromCompositionRaw(rawContent), schemas.contentSchema);
481
- // (With no items in the schema, the items are the saved ones as they are.)
482
- const contentItems = mergeContentItemsWithSchema(extractContentItemsFromCompositionRaw(rawContent), schemaContentItems(schemas.contentSchema));
483
- this.storedEmbedSettings = getCompositionEmbedSettings(composition);
484
- const embedWidth = parseEmbedDimension(this.storedEmbedSettings.width, DEFAULT_PREVIEW_WIDTH);
485
- const embedHeight = parseEmbedDimension(this.storedEmbedSettings.height, DEFAULT_PREVIEW_HEIGHT);
507
+ const { designValues, contentValues, contentItems, embedSettings, embedWidth, embedHeight } = readEditedValues(composition, schemas.contentSchema);
508
+ this.storedEmbedSettings = embedSettings;
486
509
  // What a later save is checked against: the version of the content just read (`null` for an API without versions).
487
510
  this.contentVersion = compositionContentVersion(composition);
488
511
  this.revision = 0;
@@ -694,7 +717,10 @@ export class CompositionEditorController {
694
717
  }
695
718
  /** One property was changed in the props editor. */
696
719
  changeProperty(change) {
697
- if (this.disposed || this.state.phase !== 'ready' || this.state.editsBlocked)
720
+ if (this.disposed ||
721
+ this.state.phase !== 'ready' ||
722
+ this.state.editsBlocked ||
723
+ this.state.refreshing)
698
724
  return;
699
725
  const { schema, propertyId, value, itemId } = change;
700
726
  if (schema === 'design') {
@@ -719,7 +745,10 @@ export class CompositionEditorController {
719
745
  }
720
746
  /** The content items (slides, rows, cards...) were changed in the props editor. */
721
747
  changeContentItems(items) {
722
- if (this.disposed || this.state.phase !== 'ready' || this.state.editsBlocked)
748
+ if (this.disposed ||
749
+ this.state.phase !== 'ready' ||
750
+ this.state.editsBlocked ||
751
+ this.state.refreshing)
723
752
  return;
724
753
  const incoming = Array.isArray(items) ? items : [];
725
754
  const contentItems = mergeContentItemsWithSchema(incoming, schemaContentItems(this.state.contentSchema));
@@ -1032,6 +1061,167 @@ export class CompositionEditorController {
1032
1061
  this.emit({ type: 'conflictResolved', resolution: 'loadLatest' });
1033
1062
  }
1034
1063
  // ---------------------------------------------------------------------------------------------
1064
+ // A tab that comes back
1065
+ // ---------------------------------------------------------------------------------------------
1066
+ /**
1067
+ * Starts looking at the tab whenever the person comes back to it (the window gets focus, the tab becomes visible, the
1068
+ * network is back, the page is shown again). Each time, at most every few seconds, the composition is asked for with the
1069
+ * content version this editor shows: the API answers 304 with no body when nothing was saved since, so a tab nobody
1070
+ * touched costs a header. When a newer version was saved elsewhere (an MCP client, the assistant, another tab, a
1071
+ * teammate), it is put on the screen on the spot, behind a dark layer (`state.refreshing`) during which edits are refused,
1072
+ * so a copy that is out of date is never edited. The values and the items are replaced and the preview is told; the schemas
1073
+ * and the preview page stay (a composition that moved to another widget is loaded again in full).
1074
+ *
1075
+ * Edits that are not saved are never replaced: they raise `state.conflict`, the same choice a refused save does ("Keep my
1076
+ * changes" / "Use the latest version"), and the guard waits for it. A save that is on its way is waited for first, and an
1077
+ * own save is never taken for news. Nothing is shown when the question fails: the next time the person comes back it is
1078
+ * asked again. Call it once the editor is on the screen (the component does, in `onMount`); asking again does nothing.
1079
+ */
1080
+ startStaleGuard() {
1081
+ if (this.disposed || this.staleGuard !== null)
1082
+ return;
1083
+ const guard = createStaleGuard({
1084
+ probe: async ({ signal, currentToken }) => {
1085
+ const { api, compositionId } = this.options;
1086
+ let composition;
1087
+ if (typeof api.getCompositionIfChanged === 'function') {
1088
+ const answer = await api.getCompositionIfChanged(compositionId, {
1089
+ signal,
1090
+ ...(currentToken !== null ? { ifNoneMatchVersion: currentToken } : {})
1091
+ });
1092
+ if (answer.status === 'notModified')
1093
+ return { outcome: 'unchanged' };
1094
+ composition = answer.composition;
1095
+ }
1096
+ else {
1097
+ // A client made by hand with no conditional read: the whole composition is read and the versions are compared here.
1098
+ composition = await api.getComposition(compositionId, { signal });
1099
+ }
1100
+ const version = compositionContentVersion(composition);
1101
+ // An API that keeps no content versions gives nothing to compare: the tab cannot tell, so it leaves things as they are.
1102
+ if (version === null)
1103
+ return { outcome: 'unchanged' };
1104
+ return { outcome: 'changed', token: version, snapshot: composition };
1105
+ },
1106
+ readCurrentToken: () => (this.state.phase === 'ready' ? this.contentVersion : null),
1107
+ readBlocker: () => this.readStaleGuardBlocker(),
1108
+ apply: (composition) => this.adoptNewerComposition(composition),
1109
+ onConflict: ({ token }) => this.raiseContentConflict(token),
1110
+ onPhaseChange: (phase) => {
1111
+ const refreshing = phase === 'updating';
1112
+ if (this.state.refreshing !== refreshing)
1113
+ this.patch({ refreshing });
1114
+ },
1115
+ log: (event, detail) => this.logStaleGuard(event, detail),
1116
+ ...this.options.staleGuardOptions
1117
+ });
1118
+ this.staleGuard = guard;
1119
+ guard.start();
1120
+ }
1121
+ /**
1122
+ * Whether the copy on the screen may be replaced now. `skip`: there is nothing to bring up to date (still loading, failed)
1123
+ * or a choice is already waiting for the person. `busy`: a save (or a reload of the schemas) is on its way, and its answer
1124
+ * moves the version, so look again in a moment. `dirty`: edits that are not saved, which are never replaced.
1125
+ */
1126
+ readStaleGuardBlocker() {
1127
+ if (this.state.phase !== 'ready' || this.state.conflict !== null)
1128
+ return 'skip';
1129
+ if (this.savePromise !== null || this.state.saving || this.state.schemasLoading)
1130
+ return 'busy';
1131
+ if (this.hasUnsavedChanges())
1132
+ return 'dirty';
1133
+ return null;
1134
+ }
1135
+ /** Puts the newer copy on the screen: in place when it is the same widget, in full (a load) when the widget is another. */
1136
+ async adoptNewerComposition(composition) {
1137
+ if (this.disposed || this.state.phase !== 'ready')
1138
+ return;
1139
+ if (compositionWidgetId(composition) !== this.state.widgetId) {
1140
+ // Another widget: the schemas and the preview on the screen belong to the old one, so everything is read again.
1141
+ await this.load();
1142
+ if (!this.disposed && this.state.phase === 'ready')
1143
+ this.syncPreview();
1144
+ return;
1145
+ }
1146
+ this.adoptComposition(composition);
1147
+ }
1148
+ /**
1149
+ * The composition as it was saved elsewhere replaces the values and the items on the screen (the schemas stay: it is the
1150
+ * same widget), the version later saves are checked against moves to its version, and the preview is told. Nothing is
1151
+ * unsaved at this point (the guard never gets here with edits), so the draft kept for a refresh is dropped too.
1152
+ */
1153
+ adoptComposition(composition) {
1154
+ const { designValues, contentValues, contentItems, embedSettings, embedWidth, embedHeight } = readEditedValues(composition, this.state.contentSchema);
1155
+ this.storedEmbedSettings = embedSettings;
1156
+ this.contentVersion = compositionContentVersion(composition);
1157
+ this.revision = 0;
1158
+ this.savedRevision = 0;
1159
+ this.contentRevision = 0;
1160
+ this.savedContentRevision = 0;
1161
+ this.embedRevision = 0;
1162
+ this.savedEmbedRevision = 0;
1163
+ this.failedAutosaves = 0;
1164
+ this.clearAutosaveTimer();
1165
+ const showsDesktop = this.state.deviceView === 'desktop';
1166
+ this.patch({
1167
+ name: String(composition.name || 'Untitled Composition'),
1168
+ designValues,
1169
+ contentValues,
1170
+ contentItems,
1171
+ embedWidth,
1172
+ embedHeight,
1173
+ // (The mobile view keeps drawing at a phone's size; only the desktop view follows the size that is saved.)
1174
+ ...(showsDesktop ? { previewWidth: embedWidth, previewHeight: embedHeight } : {}),
1175
+ dirty: false,
1176
+ saveError: null,
1177
+ conflict: null
1178
+ });
1179
+ const serverPayload = draftPayloadFromEditorState({
1180
+ designValues,
1181
+ contentValues,
1182
+ contentItems,
1183
+ embedWidth,
1184
+ embedHeight
1185
+ });
1186
+ this.draftBaseRevision = serverBaseRevision(this.contentVersion, serverPayload);
1187
+ this.draftJournal?.clear(this.options.compositionId);
1188
+ this.lastJournaledPayload = null;
1189
+ this.syncPreview();
1190
+ // What the next open shows first is what is saved now.
1191
+ void this.persistSchemaCacheFromState();
1192
+ }
1193
+ /**
1194
+ * The tab came back and found a newer version while it has edits that are not saved: they are kept, nothing is saved, and
1195
+ * the person gets the choice a refused save gives ("Keep my changes" / "Use the latest version"). Who saved the newer
1196
+ * version and when are not known from a conditional read, so the card says it plainly.
1197
+ */
1198
+ raiseContentConflict(currentVersion) {
1199
+ if (this.disposed || this.state.phase !== 'ready' || this.state.conflict !== null)
1200
+ return;
1201
+ const conflict = {
1202
+ currentVersion,
1203
+ lastEditedBy: null,
1204
+ lastEditedAt: null,
1205
+ resolving: false,
1206
+ resolveError: null
1207
+ };
1208
+ this.logger.warn('[CompositionEditor] The composition was saved elsewhere after it was loaded, and this tab has edits that are not saved. They are kept until the person chooses:', currentVersion);
1209
+ // Nothing is saved until the person chooses, so the wait for an autosave has no point.
1210
+ this.clearAutosaveTimer();
1211
+ this.patch({ conflict });
1212
+ this.emit({ type: 'conflict', conflict });
1213
+ }
1214
+ /** The guard's own notes: what could not be done is a warning, what went well a line for a developer's console. */
1215
+ logStaleGuard(event, detail) {
1216
+ if (/could not|failed|threw/.test(event)) {
1217
+ this.logger.warn(`[CompositionEditor] ${event}`, detail ?? '');
1218
+ return;
1219
+ }
1220
+ if (typeof console !== 'undefined' && typeof console.debug === 'function') {
1221
+ console.debug(`[CompositionEditor] ${event}`, detail ?? '');
1222
+ }
1223
+ }
1224
+ // ---------------------------------------------------------------------------------------------
1035
1225
  // Autosave timing
1036
1226
  // ---------------------------------------------------------------------------------------------
1037
1227
  /** Starts the wait for an autosave of what is unsaved (for callers that have something unsaved). */
@@ -1067,6 +1257,8 @@ export class CompositionEditorController {
1067
1257
  dispose() {
1068
1258
  this.disposed = true;
1069
1259
  this.clearAutosaveTimer();
1260
+ this.staleGuard?.dispose();
1261
+ this.staleGuard = null;
1070
1262
  this.leaveFlushDisposer?.();
1071
1263
  this.leaveFlushDisposer = null;
1072
1264
  this.abortController.abort();
@@ -1199,6 +1391,7 @@ export class CompositionEditorController {
1199
1391
  /** Makes the next state out of the changes, tells the watchers, and says when the unsaved flag turned over. */
1200
1392
  patch(changes) {
1201
1393
  const wasDirty = this.state.dirty;
1394
+ const hadConflict = this.state.conflict !== null;
1202
1395
  this.state = { ...this.state, ...changes };
1203
1396
  for (const listener of [...this.stateListeners]) {
1204
1397
  try {
@@ -1210,6 +1403,10 @@ export class CompositionEditorController {
1210
1403
  }
1211
1404
  if (this.state.dirty !== wasDirty)
1212
1405
  this.emit({ type: 'dirty', dirty: this.state.dirty });
1406
+ // However the choice ended (the person kept their edits, took the latest version, or a load replaced everything), the
1407
+ // guard that looks at a tab that comes back may look again.
1408
+ if (hadConflict && this.state.conflict === null)
1409
+ this.staleGuard?.settleConflict();
1213
1410
  }
1214
1411
  emit(event) {
1215
1412
  for (const listener of [...this.eventListeners]) {
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The stale-tab guard: when a person comes back to a tab, it asks the server whether what the tab shows is still what the
3
+ * server holds. When the server holds something newer (an MCP client, another tab, a teammate, an automation changed it
4
+ * while the tab sat in the background), the tab is brought up to date on the spot, behind a dark overlay that fades in
5
+ * while it happens and fades out when it is done, so nothing can be edited on a copy that is out of date.
6
+ *
7
+ * It decides nothing about a product. Everything that differs is handed in:
8
+ * - `probe`: how to read what the server holds (a revision, a content version, an `updatedAt`), and with it what is needed
9
+ * to show it (a conditional GET that answers "unchanged" costs no body);
10
+ * - `readCurrentToken`: the version this tab shows now (an own save moves it, so an own save is never "news");
11
+ * - `readBlocker`: whether the tab may be replaced right now (`busy`: a save is on its way, try again in a moment;
12
+ * `dirty`: unsaved work that must never be overwritten; `skip`: nothing to guard at the moment);
13
+ * - `apply`: how to put the newer copy on the screen (the product's own "load the latest").
14
+ *
15
+ * What it does and does not do:
16
+ * - it wakes on `focus`, `visibilitychange` (to visible), `online` and `pageshow`, one check at a time, at most one in
17
+ * `minimumGapMilliseconds` (a click into an iframe and back must not ask again and again);
18
+ * - a check that finds the same version, or an older one than the tab has (the tab saved while the question was out),
19
+ * does nothing and shows nothing;
20
+ * - it never replaces unsaved work: with `dirty` it says `conflict` and leaves the choice to the product's own conflict
21
+ * screen, until `settleConflict()`;
22
+ * - a failed check is silent (the next wake asks again); a failed `apply` leaves the overlay and tells the log;
23
+ * - the overlay (`phase === 'updating'`) stays for at least `minimumOverlayMilliseconds`, so it never reads as a flicker.
24
+ *
25
+ * This file is the same in the site, in the workflows package and in the composition editor, and has no imports on purpose:
26
+ * a change belongs in all three copies (`src/lib/utils/staleGuard.ts`, `src/lib/editor/staleGuard.ts`,
27
+ * `src/lib/composition/staleGuard.ts`), and their tests say the same.
28
+ */
29
+ /** What the guard is doing. `updating` is the one that puts the overlay up; `conflict` waits for the person. */
30
+ export type StaleGuardPhase = 'idle' | 'checking' | 'updating' | 'conflict';
31
+ /** Why the tab may not be replaced right now. */
32
+ export type StaleGuardBlocker = 'busy' | 'dirty' | 'skip';
33
+ /** What woke the guard: a tab that came back, or a call from the product (`request`). */
34
+ export type StaleGuardReason = 'wake' | 'request' | 'retry';
35
+ /** The server holds what the tab shows (a 304). */
36
+ type ProbeUnchanged = {
37
+ outcome: 'unchanged';
38
+ };
39
+ /** The server holds another version: its token, and what is needed to show it. */
40
+ type ProbeChanged<Token, Snapshot> = {
41
+ outcome: 'changed';
42
+ token: Token;
43
+ snapshot: Snapshot;
44
+ };
45
+ /** What a probe found: `unchanged`, or `changed` with the server's version and what is needed to show it. */
46
+ export type StaleProbeResult<Token, Snapshot> = ProbeUnchanged | ProbeChanged<Token, Snapshot>;
47
+ /** What the guard needs from the browser; a test hands in a fake one. */
48
+ export interface StaleGuardEnvironment {
49
+ now(): number;
50
+ /** `false` while the tab is hidden: a hidden tab asks nothing, it asks when it is shown. */
51
+ isVisible(): boolean;
52
+ /** Calls `listener` whenever the tab may have come back; returns the function that stops listening. */
53
+ onWake(listener: () => void): () => void;
54
+ setTimeout(callback: () => void, milliseconds: number): unknown;
55
+ clearTimeout(handle: unknown): void;
56
+ }
57
+ export interface StaleGuardOptions<Token, Snapshot> {
58
+ /** Reads what the server holds. `currentToken` is what the tab shows, for a conditional request. Abort on `signal`. */
59
+ probe: (request: {
60
+ signal: AbortSignal;
61
+ currentToken: Token | null;
62
+ }) => Promise<StaleProbeResult<Token, Snapshot>>;
63
+ /** The version the tab shows now, or `null` while it shows nothing. */
64
+ readCurrentToken: () => Token | null;
65
+ /** Whether the tab may be replaced now; `null` when it may. Read before the question and again before the answer is used. */
66
+ readBlocker: () => StaleGuardBlocker | null;
67
+ /** Puts the newer copy on the screen. The overlay is up while this runs. */
68
+ apply: (snapshot: Snapshot, token: Token) => Promise<void> | void;
69
+ /** The server holds something newer but the tab has unsaved work: the product shows its own conflict choice. */
70
+ onConflict?: (detail: {
71
+ token: Token;
72
+ }) => void;
73
+ /** Called with every change of phase (not with a repeat of it): the overlay is `phase === 'updating'`. */
74
+ onPhaseChange?: (phase: StaleGuardPhase) => void;
75
+ /** Whether `serverToken` is newer than what the tab shows. Default: bigger numbers, later dates, else "not equal". */
76
+ isNewer?: (serverToken: Token, currentToken: Token | null) => boolean;
77
+ /** One line for the log; the guard never writes to the console itself. */
78
+ log?: (event: string, detail?: unknown) => void;
79
+ environment?: StaleGuardEnvironment;
80
+ /** The least time between two checks (default 5000). */
81
+ minimumGapMilliseconds?: number;
82
+ /** The least time the overlay stays once it is up (default 400). */
83
+ minimumOverlayMilliseconds?: number;
84
+ /** How long to wait before asking again after a `busy` tab (default 1500), at most `maximumBusyRetries` times (default 6). */
85
+ busyRetryMilliseconds?: number;
86
+ maximumBusyRetries?: number;
87
+ }
88
+ export interface StaleGuard {
89
+ /** Starts listening for the tab coming back. Does not check: a tab that has just loaded is up to date. */
90
+ start(): void;
91
+ /**
92
+ * Checks now, unless a check or an update is on, the tab is hidden, or the last check was too recent (`force` skips
93
+ * the last one). Resolves when this check is over. Never rejects.
94
+ */
95
+ check(reason?: StaleGuardReason, settings?: {
96
+ force?: boolean;
97
+ }): Promise<void>;
98
+ /** The conflict is over (the person chose, or it went away): the guard asks again at the next wake. */
99
+ settleConflict(): void;
100
+ /** Stops listening and aborts a question that is out. Nothing is called afterwards. */
101
+ dispose(): void;
102
+ readonly phase: StaleGuardPhase;
103
+ }
104
+ export declare const DEFAULT_MINIMUM_GAP_MILLISECONDS = 5000;
105
+ export declare const DEFAULT_MINIMUM_OVERLAY_MILLISECONDS = 400;
106
+ export declare const DEFAULT_BUSY_RETRY_MILLISECONDS = 1500;
107
+ export declare const DEFAULT_MAXIMUM_BUSY_RETRIES = 6;
108
+ /** The real browser: the four ways a tab comes back (`focus`, `visibilitychange`, `online`, `pageshow`). */
109
+ export declare function createBrowserStaleGuardEnvironment(): StaleGuardEnvironment;
110
+ export declare function createStaleGuard<Token, Snapshot>(options: StaleGuardOptions<Token, Snapshot>): StaleGuard;
111
+ export {};