@terreno/syncdb 58.0.0-beta.3 → 58.0.0-beta.4

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 (73) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/dist/api/client.d.ts +6 -0
  3. package/dist/api/client.d.ts.map +1 -1
  4. package/dist/api/client.js +8 -0
  5. package/dist/api/client.js.map +1 -1
  6. package/dist/api/client.test.js +52 -0
  7. package/dist/api/client.test.js.map +1 -1
  8. package/dist/app/app.d.ts +6 -5
  9. package/dist/app/app.d.ts.map +1 -1
  10. package/dist/app/app.js +6 -5
  11. package/dist/app/app.js.map +1 -1
  12. package/dist/auth/session.d.ts +6 -0
  13. package/dist/auth/session.d.ts.map +1 -1
  14. package/dist/auth/session.js +21 -1
  15. package/dist/auth/session.js.map +1 -1
  16. package/dist/auth/session.test.js +148 -0
  17. package/dist/auth/session.test.js.map +1 -1
  18. package/dist/client.d.ts.map +1 -1
  19. package/dist/client.js +2 -0
  20. package/dist/client.js.map +1 -1
  21. package/dist/client.test.js +1 -0
  22. package/dist/client.test.js.map +1 -1
  23. package/dist/isolated/appEntryWithoutMcp.isolated.d.ts +2 -0
  24. package/dist/isolated/appEntryWithoutMcp.isolated.d.ts.map +1 -0
  25. package/dist/isolated/appEntryWithoutMcp.isolated.js +21 -0
  26. package/dist/isolated/appEntryWithoutMcp.isolated.js.map +1 -0
  27. package/dist/storage/schema.d.ts.map +1 -1
  28. package/dist/storage/schema.js +6 -0
  29. package/dist/storage/schema.js.map +1 -1
  30. package/dist/storage/store.d.ts +6 -0
  31. package/dist/storage/store.d.ts.map +1 -1
  32. package/dist/storage/store.js +25 -10
  33. package/dist/storage/store.js.map +1 -1
  34. package/dist/storage/store.test.js +18 -0
  35. package/dist/storage/store.test.js.map +1 -1
  36. package/dist/storage/types.d.ts +11 -0
  37. package/dist/storage/types.d.ts.map +1 -1
  38. package/dist/sync/deltaApplier.d.ts +3 -2
  39. package/dist/sync/deltaApplier.d.ts.map +1 -1
  40. package/dist/sync/deltaApplier.js +13 -3
  41. package/dist/sync/deltaApplier.js.map +1 -1
  42. package/dist/sync/deltaApplier.test.js +52 -0
  43. package/dist/sync/deltaApplier.test.js.map +1 -1
  44. package/dist/sync/replayCoordinator.d.ts.map +1 -1
  45. package/dist/sync/replayCoordinator.js +4 -0
  46. package/dist/sync/replayCoordinator.js.map +1 -1
  47. package/dist/sync/replayCoordinator.test.js +1 -0
  48. package/dist/sync/replayCoordinator.test.js.map +1 -1
  49. package/dist/sync/windowHydrate.d.ts +9 -7
  50. package/dist/sync/windowHydrate.d.ts.map +1 -1
  51. package/dist/sync/windowHydrate.js +20 -10
  52. package/dist/sync/windowHydrate.js.map +1 -1
  53. package/dist/sync/windowHydrate.test.js +189 -2
  54. package/dist/sync/windowHydrate.test.js.map +1 -1
  55. package/package.json +8 -4
  56. package/src/api/client.test.ts +73 -0
  57. package/src/api/client.ts +15 -0
  58. package/src/app/app.ts +6 -10
  59. package/src/auth/session.test.ts +177 -0
  60. package/src/auth/session.ts +26 -1
  61. package/src/client.test.ts +1 -0
  62. package/src/client.ts +2 -0
  63. package/src/isolated/appEntryWithoutMcp.isolated.ts +23 -0
  64. package/src/storage/schema.ts +6 -0
  65. package/src/storage/store.test.ts +19 -0
  66. package/src/storage/store.ts +33 -10
  67. package/src/storage/types.ts +11 -0
  68. package/src/sync/deltaApplier.test.ts +55 -0
  69. package/src/sync/deltaApplier.ts +15 -3
  70. package/src/sync/replayCoordinator.test.ts +1 -0
  71. package/src/sync/replayCoordinator.ts +4 -0
  72. package/src/sync/windowHydrate.test.ts +225 -3
  73. package/src/sync/windowHydrate.ts +23 -13
@@ -974,3 +974,180 @@ describe("betterAuthSessionSource", () => {
974
974
  expect(() => unsubscribe?.()).not.toThrow();
975
975
  });
976
976
  });
977
+
978
+ describe("createSessionStore initialSession (server-rendered first state)", () => {
979
+ const ADMIN: User = {id: "ba1", name: "Admin"};
980
+
981
+ /** Records `isLoading` after every state change, so a test can prove it never flips to true. */
982
+ const trackLoading = (
983
+ store: ReturnType<typeof createSessionStore<User>>
984
+ ): {changes: () => number; loadingSeen: () => boolean} => {
985
+ let changes = 0;
986
+ let loadingSeen = false;
987
+ store.subscribe(() => {
988
+ changes += 1;
989
+ if (store.getState().isLoading) {
990
+ loadingSeen = true;
991
+ }
992
+ });
993
+ return {changes: (): number => changes, loadingSeen: (): boolean => loadingSeen};
994
+ };
995
+
996
+ it("starts authenticated and not loading, before start(), for a signed-in snapshot", () => {
997
+ const {source} = makeSource(snapshot("ba1"));
998
+ const store = createSessionStore<User>({
999
+ initialSession: {user: ADMIN, userId: "ba1"},
1000
+ pollIntervalMs: 0,
1001
+ source,
1002
+ });
1003
+
1004
+ expect(store.getState()).toMatchObject({
1005
+ isAuthenticated: true,
1006
+ isLoading: false,
1007
+ user: ADMIN,
1008
+ userId: "ba1",
1009
+ });
1010
+ });
1011
+
1012
+ it("start() with a matching snapshot makes its first read silently, with no state change", async () => {
1013
+ const {reads, source} = makeSource({user: ADMIN, userId: "ba1"});
1014
+ const store = createSessionStore<User>({
1015
+ initialSession: {user: ADMIN, userId: "ba1"},
1016
+ pollIntervalMs: 0,
1017
+ source,
1018
+ });
1019
+ const tracker = trackLoading(store);
1020
+ const before = store.getState();
1021
+
1022
+ store.start();
1023
+ await flush();
1024
+
1025
+ expect(reads()).toBe(1);
1026
+ expect(tracker.changes()).toBe(0);
1027
+ expect(tracker.loadingSeen()).toBe(false);
1028
+ expect(store.getState()).toBe(before);
1029
+ store.stop();
1030
+ });
1031
+
1032
+ it("start() with a source that reports signed out flips to unauthenticated without loading", async () => {
1033
+ const {source} = makeSource(null);
1034
+ const store = createSessionStore<User>({
1035
+ initialSession: {user: ADMIN, userId: "ba1"},
1036
+ pollIntervalMs: 0,
1037
+ source,
1038
+ });
1039
+ expect(store.getState().isLoading).toBe(false);
1040
+ const tracker = trackLoading(store);
1041
+
1042
+ store.start();
1043
+ await flush();
1044
+
1045
+ expect(store.getState()).toMatchObject({isAuthenticated: false, isLoading: false, user: null});
1046
+ expect(tracker.loadingSeen()).toBe(false);
1047
+ store.stop();
1048
+ });
1049
+
1050
+ it("start() with a different user applies the new user without loading", async () => {
1051
+ const {source} = makeSource(snapshot("ba2", "Other"));
1052
+ const store = createSessionStore<User>({
1053
+ initialSession: {user: ADMIN, userId: "ba1"},
1054
+ pollIntervalMs: 0,
1055
+ source,
1056
+ });
1057
+ expect(store.getState().isLoading).toBe(false);
1058
+ const tracker = trackLoading(store);
1059
+
1060
+ store.start();
1061
+ await flush();
1062
+
1063
+ expect(store.getState().userId).toBe("ba2");
1064
+ expect(tracker.loadingSeen()).toBe(false);
1065
+ store.stop();
1066
+ });
1067
+
1068
+ it("initialSession null starts signed out and not loading", () => {
1069
+ const {source} = makeSource(null);
1070
+ const store = createSessionStore<User>({initialSession: null, pollIntervalMs: 0, source});
1071
+
1072
+ expect(store.getState()).toMatchObject({
1073
+ isAuthenticated: false,
1074
+ isLoading: false,
1075
+ user: null,
1076
+ userId: null,
1077
+ });
1078
+ });
1079
+
1080
+ it("initialSession null, then start() finds a session: authenticated without loading", async () => {
1081
+ const {source} = makeSource(snapshot("ba1"));
1082
+ const store = createSessionStore<User>({initialSession: null, pollIntervalMs: 0, source});
1083
+ expect(store.getState().isLoading).toBe(false);
1084
+ const tracker = trackLoading(store);
1085
+
1086
+ store.start();
1087
+ await flush();
1088
+
1089
+ expect(store.getState().isAuthenticated).toBe(true);
1090
+ expect(tracker.loadingSeen()).toBe(false);
1091
+ store.stop();
1092
+ });
1093
+
1094
+ it("without initialSession the first state is still loading (unchanged)", () => {
1095
+ const {source} = makeSource(snapshot("ba1"));
1096
+ const store = createSessionStore<User>({pollIntervalMs: 0, source});
1097
+
1098
+ expect(store.getState()).toMatchObject({isAuthenticated: false, isLoading: true});
1099
+ });
1100
+
1101
+ it("keeps the seeded session when the silent first read fails", async () => {
1102
+ const restore = silenceConsole();
1103
+ try {
1104
+ const {source} = makeSource(new Error("offline") as never);
1105
+ const store = createSessionStore<User>({
1106
+ initialSession: {user: ADMIN, userId: "ba1"},
1107
+ pollIntervalMs: 0,
1108
+ source,
1109
+ });
1110
+
1111
+ store.start();
1112
+ await flush();
1113
+
1114
+ expect(store.getState()).toMatchObject({error: null, isAuthenticated: true, userId: "ba1"});
1115
+ store.stop();
1116
+ } finally {
1117
+ restore();
1118
+ }
1119
+ });
1120
+
1121
+ it("refresh() after a seeded start is still a loud read (marks loading)", async () => {
1122
+ const {source} = makeSource(snapshot("ba1"));
1123
+ const store = createSessionStore<User>({
1124
+ initialSession: {user: ADMIN, userId: "ba1"},
1125
+ pollIntervalMs: 0,
1126
+ source,
1127
+ });
1128
+ store.start();
1129
+ await flush();
1130
+ const tracker = trackLoading(store);
1131
+
1132
+ await store.refresh();
1133
+
1134
+ expect(tracker.loadingSeen()).toBe(true);
1135
+ store.stop();
1136
+ });
1137
+
1138
+ it("two stores built for two server requests share no state", () => {
1139
+ const first = createSessionStore<User>({
1140
+ initialSession: {user: ADMIN, userId: "ba1"},
1141
+ pollIntervalMs: 0,
1142
+ source: makeSource(null).source,
1143
+ });
1144
+ const second = createSessionStore<User>({
1145
+ initialSession: null,
1146
+ pollIntervalMs: 0,
1147
+ source: makeSource(null).source,
1148
+ });
1149
+
1150
+ expect(first.getState().userId).toBe("ba1");
1151
+ expect(second.getState().userId).toBeNull();
1152
+ });
1153
+ });
@@ -99,6 +99,12 @@ export interface SessionStoreConfig<TUser = BetterAuthUser> {
99
99
  * @default 10000
100
100
  */
101
101
  signOutTimeoutMs?: number;
102
+ /**
103
+ * The session a server render already read, as the source would report it (`null` for signed
104
+ * out). The store starts settled on it, `isLoading: false`, and `start()` re-checks silently,
105
+ * so a matching session causes no state change and the state never flips back to loading.
106
+ */
107
+ initialSession?: SessionSnapshot<TUser> | null;
102
108
  /** Extra app cleanup run on logout after the auth and syncdb sign-outs. */
103
109
  onLogout?: () => void | Promise<void>;
104
110
  /**
@@ -297,8 +303,25 @@ export const createSessionStore = <TUser = BetterAuthUser>(
297
303
  config.clearIntervalFn ??
298
304
  ((handle: unknown): void => clearInterval(handle as ReturnType<typeof setInterval>));
299
305
 
306
+ const initialSession = config.initialSession;
300
307
  let state: SessionState<TUser> = {...INITIAL_STATE};
301
308
  let currentKey: string | undefined;
309
+ // A seeded store's first read only confirms what the server already read.
310
+ let isFirstReadSilent = initialSession !== undefined;
311
+ if (initialSession === null) {
312
+ state = {...SIGNED_OUT_STATE};
313
+ currentKey = snapshotKey(null);
314
+ } else if (initialSession) {
315
+ state = {
316
+ error: null,
317
+ isAuthenticated: true,
318
+ isLoading: false,
319
+ isSigningOut: false,
320
+ user: initialSession.user,
321
+ userId: initialSession.userId,
322
+ };
323
+ currentKey = snapshotKey(initialSession);
324
+ }
302
325
  const listeners = new Set<() => void>();
303
326
  let isStarted = false;
304
327
  let unsubscribeSource: (() => void) | undefined;
@@ -404,7 +427,9 @@ export const createSessionStore = <TUser = BetterAuthUser>(
404
427
  void readSession({silent: true});
405
428
  }, pollIntervalMs);
406
429
  }
407
- void readSession({silent: false});
430
+ const silent = isFirstReadSilent;
431
+ isFirstReadSilent = false;
432
+ void readSession({silent});
408
433
  };
409
434
 
410
435
  const stop = (): void => {
@@ -447,6 +447,7 @@ describe("createSyncDb", () => {
447
447
  const entity = client.store.getEntity({collection: "todos", id});
448
448
  expect(entity?.pendingMutationId).toBeUndefined();
449
449
  expect(entity?.seq).toBe(11);
450
+ expect(entity?.awaitingServerDelta).toBe(true);
450
451
  expect(client.getSyncStatus().queuedCount).toBe(0);
451
452
  await client.stop();
452
453
  });
package/src/client.ts CHANGED
@@ -2190,6 +2190,7 @@ export const createSyncDb = (config: SyncDbConfig): SyncDb => {
2190
2190
  // transition exactly like softDeleteEntity, and also records the pending
2191
2191
  // mutation id that protects the row from inbound deltas.
2192
2192
  store.upsertEntity({
2193
+ awaitingServerDelta: false,
2193
2194
  collection,
2194
2195
  data: existing.data ?? null,
2195
2196
  deleted: true,
@@ -2202,6 +2203,7 @@ export const createSyncDb = (config: SyncDbConfig): SyncDb => {
2202
2203
  ? {...existing.data, ...data}
2203
2204
  : (data ?? {});
2204
2205
  store.upsertEntity({
2206
+ awaitingServerDelta: false,
2205
2207
  collection,
2206
2208
  data: mergedData,
2207
2209
  id: entityId,
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Isolated because it `mock.module`s `@modelcontextprotocol/client` to behave as if the
3
+ * optional peer were not installed. A shared `bun test` process would keep that for every
4
+ * other syncdb file.
5
+ */
6
+ import {describe, expect, it, mock} from "bun:test";
7
+
8
+ mock.module("@modelcontextprotocol/client", () => {
9
+ throw new Error("Cannot find module '@modelcontextprotocol/client'");
10
+ });
11
+
12
+ describe("@terreno/syncdb/app without @modelcontextprotocol/client", () => {
13
+ it("loads, since MCP tool discovery lives in @terreno/syncdb/mcp", async () => {
14
+ const app = await import("../app/app");
15
+ expect(typeof app.installDevConsoleLogger).toBe("function");
16
+ expect(typeof app.useUpgradeCheck).toBe("function");
17
+ expect("useMCPTools" in app).toBe(false);
18
+ });
19
+
20
+ it("leaves @terreno/syncdb/mcp as the only entry point that needs the peer", async () => {
21
+ await expect(import("../app/mcpTools")).rejects.toThrow("@modelcontextprotocol/client");
22
+ });
23
+ });
@@ -21,6 +21,12 @@ import {
21
21
  export const SYNC_SCHEMA_VERSION = 3;
22
22
 
23
23
  const ENTITY_TABLE_SCHEMA: Record<string, CellSchema> = {
24
+ /**
25
+ * Set by the mutation ACK until the equal-seq server delta is applied.
26
+ * Absent on older rows means false. Not a schema-version bump: a bump wipes
27
+ * the store, and a missing cell is already the false state.
28
+ */
29
+ awaitingServerDelta: {type: "boolean"},
24
30
  data: {type: "string"},
25
31
  deleted: {type: "boolean"},
26
32
  /** E5: stamped when a tombstone is first applied; "" otherwise. */
@@ -91,6 +91,25 @@ describe("upsertEntity / getEntity", () => {
91
91
  expect(updated.pendingMutationId).toBe("m1");
92
92
  });
93
93
 
94
+ it("clears awaitingServerDelta when a later write changes the payload", () => {
95
+ const store = makeStore();
96
+ store.upsertEntity({
97
+ awaitingServerDelta: true,
98
+ collection: "todos",
99
+ data: {title: "acked"},
100
+ id: "t1",
101
+ seq: 4,
102
+ });
103
+ expect(store.getEntity({collection: "todos", id: "t1"})?.awaitingServerDelta).toBe(true);
104
+ const edited = store.upsertEntity({
105
+ collection: "todos",
106
+ data: {title: "edited"},
107
+ id: "t1",
108
+ });
109
+ expect(edited.awaitingServerDelta).toBeUndefined();
110
+ expect(edited.seq).toBe(4);
111
+ });
112
+
94
113
  it("clears pendingMutationId when explicitly set to empty", () => {
95
114
  const store = makeStore();
96
115
  store.upsertEntity({
@@ -29,15 +29,21 @@ const decodeData = <TData>(raw: string | undefined): TData => {
29
29
  }
30
30
  };
31
31
 
32
- const rowToEntity = <TData>(id: string, row: Partial<EntityRow>): SyncEntity<TData> => ({
33
- data: decodeData<TData>(row.data),
34
- deleted: Boolean(row.deleted),
35
- deletedAt: row.deletedAt ? row.deletedAt : undefined,
36
- id,
37
- pendingMutationId: row.pendingMutationId ? row.pendingMutationId : undefined,
38
- seq: row.seq ?? 0,
39
- stream: row.stream ? row.stream : undefined,
40
- });
32
+ const rowToEntity = <TData>(id: string, row: Partial<EntityRow>): SyncEntity<TData> => {
33
+ const entity: SyncEntity<TData> = {
34
+ data: decodeData<TData>(row.data),
35
+ deleted: Boolean(row.deleted),
36
+ deletedAt: row.deletedAt ? row.deletedAt : undefined,
37
+ id,
38
+ pendingMutationId: row.pendingMutationId ? row.pendingMutationId : undefined,
39
+ seq: row.seq ?? 0,
40
+ stream: row.stream ? row.stream : undefined,
41
+ };
42
+ if (row.awaitingServerDelta) {
43
+ entity.awaitingServerDelta = true;
44
+ }
45
+ return entity;
46
+ };
41
47
 
42
48
  interface UpsertEntityArgs {
43
49
  collection: string;
@@ -51,6 +57,12 @@ interface UpsertEntityArgs {
51
57
  pendingMutationId?: string;
52
58
  /** C2: the stream this entity was written under; omitted = preserve existing. */
53
59
  stream?: string;
60
+ /**
61
+ * True when this write is the mutation ACK stamping `seq` ahead of the
62
+ * server delta. False clears it. Omitted keeps it, unless `data` or
63
+ * `deleted` changed, which means a newer local edit and clears it.
64
+ */
65
+ awaitingServerDelta?: boolean;
54
66
  }
55
67
 
56
68
  interface CompactTombstonesResult {
@@ -179,8 +191,19 @@ export const createSyncStore = ({
179
191
  ? (raw.getRow(args.collection, args.id) as Partial<EntityRow>)
180
192
  : undefined;
181
193
  const deleted = args.deleted ?? existing?.deleted ?? false;
194
+ const encodedData = encodeData(args.data);
195
+ const contentChanged =
196
+ existing !== undefined &&
197
+ (encodedData !== (existing.data ?? "null") || deleted !== Boolean(existing.deleted));
198
+ const awaitingServerDelta =
199
+ args.awaitingServerDelta !== undefined
200
+ ? args.awaitingServerDelta
201
+ : contentChanged
202
+ ? false
203
+ : Boolean(existing?.awaitingServerDelta);
182
204
  const row: EntityRow = {
183
- data: encodeData(args.data),
205
+ awaitingServerDelta,
206
+ data: encodedData,
184
207
  deleted,
185
208
  // E5: stamp deletedAt the moment a row FIRST becomes a tombstone (not
186
209
  // on every subsequent upsert while it stays deleted, and never on a
@@ -46,6 +46,12 @@ export const RESERVED_TABLE_PREFIX = "_";
46
46
 
47
47
  /** Primitive row shape for a `{collection}` entity table; rowId = entity id. */
48
48
  export interface EntityRow {
49
+ /**
50
+ * True only after this row's own mutation ACK stamped `seq` and the matching
51
+ * server delta has not been applied yet. Absent on rows written before the
52
+ * cell existed; readers treat that the same as false.
53
+ */
54
+ awaitingServerDelta: boolean;
49
55
  /** JSON-encoded entity payload. */
50
56
  data: string;
51
57
  /** Soft-delete tombstone flag. */
@@ -143,6 +149,11 @@ export interface ConflictRow {
143
149
 
144
150
  /** Decoded, application-facing entity record returned by store accessors. */
145
151
  export interface SyncEntity<TData = unknown> {
152
+ /**
153
+ * True when this row's seq was stamped by its own ACK and the server delta
154
+ * at that seq has not been applied yet. Omitted when false.
155
+ */
156
+ awaitingServerDelta?: boolean;
146
157
  /** Decoded entity payload. */
147
158
  data: TData;
148
159
  /** Soft-delete tombstone flag. */
@@ -59,6 +59,61 @@ describe("applyDelta", () => {
59
59
  expect(getCursor({store, stream: STREAM})).toBe(3);
60
60
  });
61
61
 
62
+ it("applies the server's doc for an own create whose ACK already stamped the same seq", () => {
63
+ const store = makeStore();
64
+ // releaseEntity stamps seq and awaitingServerDelta before the server's delta arrives.
65
+ store.upsertEntity({
66
+ awaitingServerDelta: true,
67
+ collection: "todos",
68
+ data: {title: "Optimistic"},
69
+ id: "t1",
70
+ seq: 4,
71
+ });
72
+ const result = applyDelta({
73
+ delta: makeDelta({data: {_id: "t1", ownerId: "u1", title: "Optimistic"}, seq: 4}),
74
+ store,
75
+ });
76
+ expect(result.applied).toBe(true);
77
+ const entity = store.getEntity({collection: "todos", id: "t1"});
78
+ expect(entity?.data).toEqual({_id: "t1", ownerId: "u1", title: "Optimistic"});
79
+ expect(entity?.stream).toBe(STREAM);
80
+ expect(entity?.awaitingServerDelta).toBeUndefined();
81
+ });
82
+
83
+ it("skips an equal-seq delta once a later local edit has cleared the ACK marker", () => {
84
+ const store = makeStore();
85
+ store.upsertEntity({
86
+ awaitingServerDelta: true,
87
+ collection: "todos",
88
+ data: {title: "Optimistic"},
89
+ id: "t1",
90
+ seq: 4,
91
+ });
92
+ store.upsertEntity({collection: "todos", data: {title: "Edited after ACK"}, id: "t1"});
93
+ const result = applyDelta({
94
+ delta: makeDelta({data: {_id: "t1", title: "Optimistic"}, seq: 4}),
95
+ store,
96
+ });
97
+ expect(result.applied).toBe(false);
98
+ expect(store.getEntity({collection: "todos", id: "t1"})?.data).toEqual({
99
+ title: "Edited after ACK",
100
+ });
101
+ });
102
+
103
+ it("still skips an older delta for an ACK-stamped row with no stream", () => {
104
+ const store = makeStore();
105
+ store.upsertEntity({
106
+ awaitingServerDelta: true,
107
+ collection: "todos",
108
+ data: {title: "Optimistic"},
109
+ id: "t1",
110
+ seq: 4,
111
+ });
112
+ const result = applyDelta({delta: makeDelta({data: {title: "Stale"}, seq: 3}), store});
113
+ expect(result.applied).toBe(false);
114
+ expect(store.getEntity({collection: "todos", id: "t1"})?.data).toEqual({title: "Optimistic"});
115
+ });
116
+
62
117
  it("skips an out-of-order older delta without rewinding entity or cursor", () => {
63
118
  const store = makeStore();
64
119
  applyDelta({delta: makeDelta({data: {title: "v5"}, seq: 5}), store});
@@ -16,8 +16,9 @@ export interface ApplyDeltaResult {
16
16
  /**
17
17
  * Apply a server delta to the local store, idempotently:
18
18
  *
19
- * - a delta at or below the entity's applied seq is skipped (duplicate /
20
- * out-of-order delivery);
19
+ * - a delta below the entity's applied seq is skipped (out-of-order delivery),
20
+ * and so is one at that seq unless the row is still waiting for the server
21
+ * doc from its own ACK (`awaitingServerDelta`);
21
22
  * - an entity with a pending outbox mutation is never overwritten — its
22
23
  * optimistic state is protected until conflict resolution decides;
23
24
  * - create/update writes data + seq; tombstones set `deleted: true` (keeping
@@ -53,7 +54,17 @@ export const applyDelta = ({
53
54
  };
54
55
 
55
56
  const existing = store.getEntity({collection: delta.collection, id: delta.id});
56
- if (existing && delta.seq <= existing.seq) {
57
+ // An equal-seq delta is the server's canonical doc only while the row is
58
+ // marked by its own ACK (`releaseEntity` sets `awaitingServerDelta`). A
59
+ // missing `stream` is not that signal: a later local edit also has no
60
+ // stream until a delta lands, and taking the old delta would overwrite it.
61
+ // Skipping the awaited delta would leave the row without server-added
62
+ // fields such as `_id`, and the cursor advance below means it is never
63
+ // fetched again.
64
+ if (
65
+ existing &&
66
+ (delta.seq < existing.seq || (delta.seq === existing.seq && !existing.awaitingServerDelta))
67
+ ) {
57
68
  advanceCursor();
58
69
  return {applied: false, seqJump};
59
70
  }
@@ -78,6 +89,7 @@ export const applyDelta = ({
78
89
 
79
90
  const deleted = delta.deleted === true || delta.method === "delete";
80
91
  store.upsertEntity({
92
+ awaitingServerDelta: false,
81
93
  collection: delta.collection,
82
94
  // Tombstone deltas omit data; keep the last known payload for conflict UIs.
83
95
  data: delta.data !== undefined ? delta.data : (existing?.data ?? null),
@@ -168,6 +168,7 @@ describe("createReplayCoordinator", () => {
168
168
  expect(entity?.pendingMutationId).toBeUndefined();
169
169
  expect(entity?.seq).toBe(42);
170
170
  expect(entity?.data).toEqual({title: "t1"});
171
+ expect(entity?.awaitingServerDelta).toBe(true);
171
172
  });
172
173
 
173
174
  it("ignores an ack that resolves after its replay lifecycle is reset", async () => {
@@ -409,6 +409,10 @@ export const createReplayCoordinator = ({
409
409
  return;
410
410
  }
411
411
  store.upsertEntity({
412
+ // The seq stamp is the only write that arms the equal-seq delta. A
413
+ // release without a seq (terminal failure) clears it so that delta
414
+ // cannot overwrite a newer local edit.
415
+ awaitingServerDelta: seq !== undefined,
412
416
  collection: mutation.collection,
413
417
  data: entity.data,
414
418
  id: mutation.entityId,