@collective-intelligence/external-apps-client-sdk-react 0.11.0 → 0.13.0

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.
@@ -0,0 +1,277 @@
1
+ # Record Collections
2
+
3
+ `./records` holds the record layer: Record Collections, `RecordWrites`, the
4
+ server seed and the bridge to Business Logic Machines. A Record Collection is
5
+ a TanStack DB collection of CI records, one Realtime Topic or one query, for
6
+ the signed-in CI identity. Every optimistic write of a CI record is a TanStack
7
+ DB transaction on a Record Collection; the SDK has no second optimistic
8
+ engine.
9
+
10
+ Install the TanStack peers with the exact versions in the package's
11
+ `peerDependencies`: `@tanstack/db` and `@tanstack/react-db` `1.0.0-rc.1.5`,
12
+ `@tanstack/query-db-collection` `1.5.2`, `@tanstack/offline-transactions`
13
+ `1.2.1`, and `@tanstack/query-core`. Load the TanStack DB skills that
14
+ [tanstack-skills.md](tanstack-skills.md) names before you write a live query
15
+ or a collection.
16
+
17
+ ## Which kind to use
18
+
19
+ | Data | Use |
20
+ | -------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
21
+ | Records of a Realtime Topic that other users or CI change while the view is open | Realtime Record Collection |
22
+ | Records of one query with no Realtime Topic, or that change only through this tab | Query Record Collection |
23
+ | A one-off read that is not a set of records you write or follow: a count, a search, a report | Plain TanStack Query (`useQuery`, `QueryCache.fetch`) |
24
+ | Create, update or delete of a record | The entity hooks of `./resources` |
25
+ | A record write that a Business Logic Machine or a flow runs itself | `RecordWrites` with `entityWriteTarget(contract)` |
26
+
27
+ - **Realtime Record Collection**: `RecordCollections.realtime(topic, schema)`.
28
+ Make the topic with `entityTopic(contract, { schema, filter? })`: the
29
+ collection reads each hinted record through the entity client of
30
+ `contract`. Mount `RealtimeProvider` of `./realtime` inside
31
+ `CollectiveIntelligenceProvider`; the provider feeds the Change Hints of its
32
+ one connection to the collections. A collection with no server seed first
33
+ loads every record of the topic, and its stream starts at that read. If
34
+ that first load fails, the collection is ready with no rows, reports
35
+ `RecordSyncFailed`, and loads the topic again as a reload. The collection
36
+ applies Change Hints, removes a record on a `leave` or `delete` hint, and
37
+ reloads on every Resync. A reload whose load fails, or a read by id of a
38
+ `change` hint that fails, is tried again with backoff for up to 60 seconds.
39
+ If a reload still fails, the collection keeps its rows, reports
40
+ `RecordSyncFailed`, applies the Change Hints it holds, and reloads with its
41
+ next batch of Change Hints. If a read still fails, the collection keeps
42
+ that row, reports `RecordSyncFailed`, and reads the record again with its
43
+ next batch of Change Hints.
44
+ - **Query Record Collection**: `RecordCollections.query(options)`, with
45
+ `options` `{ queryKey, schema, load, target? }`. `load` is an Effect that returns every record of the query as
46
+ `{ id, revision, value }`; the rows stay on the app's shared QueryClient,
47
+ under a key that starts with the CI identity. Pass
48
+ `target: entityWriteTarget(contract)` when the query holds records of an
49
+ entity contract: record writes of that contract then show in the rows it
50
+ holds.
51
+ - `schema` is an Effect `Schema` of the record value. A record that does not
52
+ decode fails the collection's sync with `RecordSyncFailed`.
53
+
54
+ ## Open a collection
55
+
56
+ `useRecordRuntime()` gives the runtime of the signed-in identity's record
57
+ layer, with `RecordCollections` and `RecordWrites`. It is `undefined` while no
58
+ user is signed in. A sign-out or a user switch closes that runtime: its
59
+ collections are cleaned up and its pending writes roll back, so no row of one
60
+ user reaches the view of another.
61
+
62
+ ```tsx
63
+ import {
64
+ entityTopic,
65
+ RecordCollections,
66
+ useRecordRuntime
67
+ } from "@collective-intelligence/external-apps-client-sdk-react/records"
68
+ import { useLiveQuery } from "@tanstack/react-db"
69
+ import * as Schema from "effect/Schema"
70
+
71
+ const Lead = Schema.Struct({ name: Schema.String, stage: Schema.String })
72
+ const leadTopic = entityTopic(leadContract, { schema: "crm.lead" })
73
+
74
+ const LeadList = () => {
75
+ const runtime = useRecordRuntime()
76
+ const leads = useMemo(
77
+ () =>
78
+ runtime?.runSync(
79
+ RecordCollections.use((collections) =>
80
+ collections.realtime(leadTopic, Lead)
81
+ )
82
+ ),
83
+ [runtime]
84
+ )
85
+ // `leads` is undefined while signed out: the live query is then disabled.
86
+ const { data } = useLiveQuery(
87
+ (q) => (leads === undefined ? undefined : q.from({ lead: leads })),
88
+ [leads]
89
+ )
90
+ // ...
91
+ }
92
+ ```
93
+
94
+ - Each row is `{ id, revision, value }`; `revision` is `null` while a create
95
+ waits for CI. Read rows through live queries; keep no copy of them in
96
+ React state or machine context.
97
+ - A collection of one topic or query key is opened once per identity; a
98
+ second call returns the same collection.
99
+ - Provide the services that `load` needs where you call `query`: the runtime
100
+ provides only `RecordCollections` and `RecordWrites`.
101
+
102
+ ## Mutations
103
+
104
+ Write CI records with `useEntityCreate`, `useEntityUpdate` and
105
+ `useEntityDelete` of `./resources`. Each write is one `RecordWrites`
106
+ transaction over every open Record Collection of the identity that shows the
107
+ contract's records:
108
+
109
+ - A Realtime Record Collection of an `entityTopic` of the contract shows each
110
+ write at once: an update and a delete of a row it holds, and a create whose
111
+ value matches the topic's filter. A Query Record Collection opened with the
112
+ contract's `target` shows the updates and deletes of the rows it holds. The
113
+ record's own Record Collection shows every write.
114
+ - The write puts CI's confirmed row in each of those collections before it
115
+ settles, so a list keeps the new value whether the Change Hint arrives
116
+ before CI's answer or after it. A Realtime Record Collection whose topic
117
+ filter no longer matches CI's row removes the row instead. It reads the
118
+ filter as CI does: a field with a dot is a path into the record's data, and
119
+ a relation field matches when any of its ids equals the filter value. When
120
+ the row does not hold the filter's field, the collection keeps the row and
121
+ CI's `leave` decides.
122
+ - An update or a delete sends the revision of the app's collection that holds
123
+ the row, a Realtime Record Collection first, so it follows other writers'
124
+ changes and reads nothing first. A Query Record Collection follows no
125
+ Change Hint: when the edited revision is not the one it holds, the write
126
+ reads CI again before it counts the edit as a conflict. A create gives its
127
+ record a client id
128
+ (UUIDv7), so the row keeps its key when CI confirms it. A store that
129
+ assigns its own ids (a Remote-first CI schema, or an app store resource
130
+ without the client id opt-in, such as a server SDK Drizzle resource
131
+ without `entities.clientIdField`) refuses the id (`details.reason:
132
+ "client_id_not_supported"`): the create is sent once more without it, and
133
+ the row takes the store's id when it answers; updates and deletes queued
134
+ behind the create go to the store's id. The entity reads
135
+ keep CI's record and read CI again when the write settles.
136
+ - Writes to one record run one at a time, in call order; a queued write sends
137
+ the revision that the write before it confirmed.
138
+ - A write whose answer was lost is sent again with the same idempotency key
139
+ for up to 60 seconds; the Write Receipt makes CI apply it once. After that
140
+ its status is `uncertain`, and `resubmit` sends the same action on a user
141
+ request.
142
+ - CI's confirmed row replaces the optimistic row before the write settles, so
143
+ nothing flickers back. A refused or conflicting write rolls back only its
144
+ own change and reaches `onWriteFailed`.
145
+
146
+ To write without the hooks (a Business Logic Machine, a flow that writes
147
+ several records), call `RecordWrites` with `entityWriteTarget(contract)` on
148
+ your own Record Collection. The write runs the same transaction, order,
149
+ resend and confirmation as a hook's, and shows in every collection of the
150
+ contract:
151
+
152
+ ```ts
153
+ import {
154
+ entityWriteTarget,
155
+ IdempotencyKey,
156
+ RecordId,
157
+ RecordWrites
158
+ } from "@collective-intelligence/external-apps-client-sdk-react/records"
159
+
160
+ const markWon = (
161
+ leads: RealtimeRecordCollection<RecordRow<Lead>>,
162
+ id: string
163
+ ) =>
164
+ RecordWrites.use((writes) =>
165
+ writes.update({
166
+ change: { stage: "won" },
167
+ collection: leads,
168
+ id: RecordId.make(id),
169
+ idempotencyKey: IdempotencyKey.make(crypto.randomUUID()),
170
+ target: entityWriteTarget(leadContract)
171
+ })
172
+ )
173
+ ```
174
+
175
+ `collection` is the collection whose row the write reads; it must hold the
176
+ record for an update or a delete. When a flow needs a write that neither the
177
+ hooks nor `RecordWrites` can express, file an SDK gap (see
178
+ [File an SDK gap](#file-an-sdk-gap)).
179
+
180
+ ## Server seed
181
+
182
+ A server component seeds Record Collections in the first HTML with one fetch
183
+ per collection. Run the
184
+ [client-sdk-react-tanstack-db-ssr](../skills/client-sdk-react-tanstack-db-ssr/SKILL.md)
185
+ skill for the steps. The parts:
186
+
187
+ - `getRequestClients()` (server only) gives the QueryClient and DbClient of
188
+ the current request.
189
+ - `seedRecords({ identity, query?, realtime? })` (server only) fetches each
190
+ collection once, renders it and returns the seed. `identity` is
191
+ `{ applicationId, organizationId, userId }` of the request's session, the
192
+ values the browser's entity source reports: the seed keys its Query rows as
193
+ that identity's collections do. A realtime seed's `load` returns
194
+ `{ records, position }`; the browser stream of the topic starts at that
195
+ `position`, so it misses no change after the read and repeats none.
196
+ - `<RecordSeedBoundary seed>` hydrates the seed in the browser, inside the SDK
197
+ provider, which gives the identity's DbClient to its tree. While no user is
198
+ signed in, the seed waits and hydrates at the sign-in. A seed made for
199
+ another identity, or with no `identity`, never hydrates.
200
+ - A seeded collection reads nothing on its first render. A seeded Query
201
+ Record Collection takes its seed as fresh for one minute after it hydrated,
202
+ until its first browser update; an invalidation still reads it again.
203
+
204
+ The `react-server` build of `./records` holds the server values. TypeScript
205
+ sees `getRequestClients` and `seedRecords` in every build; a client component
206
+ that imports them fails when it bundles.
207
+
208
+ ## Outbox
209
+
210
+ The SDK provider keeps the pending writes of the signed-in user and
211
+ Organization in an outbox, in IndexedDB (or localStorage) under
212
+ `ci-records:<organization>:<user>`. The app configures nothing:
213
+
214
+ - Each write is stored before its first send. After a reload, the outbox
215
+ sends the stored writes once each, oldest first, with their idempotency
216
+ keys; CI's Write Receipt answers a write that it already applied.
217
+ - A refused or conflicting stored write leaves the outbox; a lost answer is
218
+ sent again with backoff.
219
+ - A user switch or an expired session keeps the stored writes for that user;
220
+ only a sign-out drops them. One user's writes are never sent in another
221
+ user's session.
222
+ - In the page that made it, a write that ends `uncertain` waits for
223
+ `resubmit` or a reload.
224
+
225
+ ## Business Logic Machines
226
+
227
+ A Business Logic Machine runs Record Collection actions and reads records
228
+ through a live query; it keeps ids in its context, never rows. Pass
229
+ `useRecordRuntime()` as `runtime` in the machine input.
230
+
231
+ - `fromTransaction((writes, input) => writes.update({ ... }))` runs one
232
+ `RecordWrites` action as a promise actor. Its output is the confirmed row; a
233
+ typed write error fails the actor; a stop interrupts the write and rolls
234
+ back its change. Give the action `target: entityWriteTarget(contract)` (see
235
+ [Mutations](#mutations)).
236
+ - `fromLiveQuery((input) => effect)` follows a Record Collection or a live
237
+ query collection over Record Collections. It sends the parent
238
+ `{ type: "records.rows", rows }` when the rows are ready and after each
239
+ change, and `{ type: "records.failed", error }` when the query or its first
240
+ load fails. A stop ends the subscription.
241
+
242
+ ```tsx
243
+ const watchLeads = fromLiveQuery(
244
+ (_input: Readonly<{ runtime: RecordRuntime }>) =>
245
+ RecordCollections.use((collections) =>
246
+ collections.realtime(leadTopic, Lead)
247
+ )
248
+ )
249
+
250
+ const LeadCounter = () => {
251
+ const runtime = useRecordRuntime()
252
+ // Render the signed-out state when `runtime` is undefined; otherwise start
253
+ // a machine that invokes `watchLeads` with `{ runtime }` and counts
254
+ // `event.rows` on each `records.rows` event.
255
+ }
256
+ ```
257
+
258
+ ## Errors
259
+
260
+ | Error | Meaning |
261
+ | --------------------------- | ---------------------------------------------------------------------------- |
262
+ | `RecordWriteRefused` | CI refused the write; only that write rolls back |
263
+ | `RecordWriteConflict` | The record changed since the revision the write sent |
264
+ | `RecordWriteOutcomeUnknown` | No answer arrived within the 60-second resend window |
265
+ | `RecordSyncFailed` | A collection could not load or apply records; `retrying` tells if it retries |
266
+
267
+ ## File an SDK gap
268
+
269
+ When the record layer cannot express what a flow needs, stop and report it;
270
+ write no local optimistic code, record cache or write queue in the app.
271
+
272
+ 1. Write down the flow, the record type, and the `./records` or entity hook
273
+ call that is missing.
274
+ 2. Open an issue for `@collective-intelligence/external-apps-client-sdk-react`
275
+ with that note, or tell the user that the SDK lacks it.
276
+ 3. Until the SDK has it, keep the flow on the entity hooks, or leave it
277
+ unbuilt.
@@ -0,0 +1,73 @@
1
+ # TanStack skills
2
+
3
+ `@tanstack/db` and `@tanstack/react-db` ship their own agent skills, which
4
+ TanStack Intent loads by name. This SDK names the ones to load and adds the
5
+ rules of its record layer; it copies none of them.
6
+
7
+ ## Allowlist the packages
8
+
9
+ Permit both packages in the app's `package.json`, then run `intent install`
10
+ (`@tanstack/intent` as a devDependency) and commit what it writes:
11
+
12
+ ```json
13
+ {
14
+ "intent": {
15
+ "skills": ["@tanstack/db", "@tanstack/react-db"],
16
+ "exclude": ["@tanstack/db#meta-framework"]
17
+ }
18
+ }
19
+ ```
20
+
21
+ `intent list` shows the permitted skills; `intent load <package>#<skill>`
22
+ prints one.
23
+
24
+ ## Skills to load
25
+
26
+ | Task | Load |
27
+ | ------------------------------------------------------------------------------- | ------------------------------------------- |
28
+ | Any work on Record Collections: concepts, and the entry to the other skills | `@tanstack/db#db-core` |
29
+ | A live query: `from`, `where`, `join`, `select`, `orderBy`, `$hasPendingWrites` | `@tanstack/db#db-core/live-queries` |
30
+ | `useLiveQuery` and the other React hooks | `@tanstack/react-db#react-db` |
31
+ | What a pending write shows, and the transaction states | `@tanstack/db#db-core/mutations-optimistic` |
32
+ | The states of a collection (`loading`, `ready`, `error`) | `@tanstack/db#db-core/collection-setup` |
33
+
34
+ These skills teach TanStack DB itself. Where one of them makes a collection
35
+ (`createCollection`, `queryCollectionOptions`) or writes
36
+ (`collection.insert`, `collection.update`, `collection.delete`,
37
+ `createOptimisticAction`, `createTransaction`), use the SDK instead: open
38
+ collections with `RecordCollections` and write with the entity hooks
39
+ ([record-collections.md](record-collections.md)).
40
+
41
+ The SDK owns two topics, so skip their skills:
42
+ `@tanstack/db#db-core/custom-adapter` (the Realtime Record Collection is the
43
+ SDK's adapter) and `@tanstack/db#db-core/persistence` (the SDK's outbox keeps
44
+ pending writes).
45
+
46
+ ## The shipped server-rendering skill is out of date
47
+
48
+ `@tanstack/db#meta-framework` was written for TanStack DB 0.6 and says that
49
+ TanStack DB has no server rendering and that routes must turn it off. TanStack
50
+ DB `1.0.0-rc.1.5` dehydrates and hydrates a DbClient, and `./records` seeds
51
+ Record Collections in the first HTML. Run the
52
+ [client-sdk-react-tanstack-db-ssr](../skills/client-sdk-react-tanstack-db-ssr/SKILL.md)
53
+ skill in its place; the allowlist above excludes it.
54
+
55
+ ## TanStack Query rules
56
+
57
+ Apply these rules on top of the repository `tanstack-query` skill; where they
58
+ differ, these win.
59
+
60
+ - Write CI records through Record Collections: the entity hooks of
61
+ `./resources`. Record Collection transactions replace the "Optimistic
62
+ Updates" patterns of the `tanstack-query` skill (`useMutation` with
63
+ `onMutate`, `setQueryData` and a rollback). The `ci-solution/effect-writes`
64
+ lint rule reports `useMutation`.
65
+ - Run a write that is not a CI record write, such as an upload or an agent
66
+ run, in a `fromEffect` actor of `./effect`, and refresh the reads after it
67
+ with `QueryCache` (`invalidate`, `setData`, `update`, `remove`).
68
+ - Read one-off data with `useQuery`, or with `QueryCache.fetch` in a machine.
69
+ Records that the app writes or follows go in a Record Collection.
70
+ - Seed Record Collections with `seedRecords`, not with the "SSR & Hydration"
71
+ steps of the `tanstack-query` skill; plain queries keep those steps.
72
+ - Keep user data in TanStack Query or a Record Collection; only reads with the
73
+ app's own credential go into the Next.js server cache.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-client-sdk-react",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "React bindings for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -37,11 +37,22 @@
37
37
  "types": "./dist/realtime.d.ts",
38
38
  "import": "./dist/realtime.js",
39
39
  "default": "./dist/realtime.js"
40
+ },
41
+ "./records": {
42
+ "react-server": {
43
+ "ci-source": "./src/records.server.ts",
44
+ "types": "./dist/records.server.d.ts",
45
+ "import": "./dist/records.server.js",
46
+ "default": "./dist/records.server.js"
47
+ },
48
+ "ci-source": "./src/records.ts",
49
+ "types": "./dist/records.d.ts",
50
+ "import": "./dist/records.js",
51
+ "default": "./dist/records.js"
40
52
  }
41
53
  },
42
54
  "scripts": {
43
55
  "build": "bun tools/build.ts",
44
- "check:models": "tsprover",
45
56
  "test": "bun tools/test-pack.ts",
46
57
  "test:pack": "bun tools/test-pack.ts",
47
58
  "test:unit": "vitest run src",
@@ -54,12 +65,17 @@
54
65
  "type-check": "bun check --no-script -p tsconfig.json"
55
66
  },
56
67
  "dependencies": {
57
- "@collective-intelligence/effect-xstate": "0.11.0",
58
- "@collective-intelligence/external-apps-client-sdk": "0.11.0",
68
+ "@collective-intelligence/effect-xstate": "0.13.0",
69
+ "@collective-intelligence/external-apps-client-sdk": "0.13.0",
59
70
  "nuqs": "2.10.1"
60
71
  },
61
72
  "peerDependencies": {
62
- "@collective-intelligence/ui-react": "0.11.0",
73
+ "@collective-intelligence/ui-react": "0.13.0",
74
+ "@tanstack/db": "1.0.0-rc.1.5",
75
+ "@tanstack/offline-transactions": "1.2.1",
76
+ "@tanstack/query-core": "^5.101.4",
77
+ "@tanstack/query-db-collection": "1.5.2",
78
+ "@tanstack/react-db": "1.0.0-rc.1.5",
63
79
  "@tanstack/react-query": "^5.101.4",
64
80
  "effect": "^4.1.0",
65
81
  "react": ">=18.2 <20",
@@ -70,10 +86,15 @@
70
86
  "access": "public"
71
87
  },
72
88
  "devDependencies": {
73
- "@collective-intelligence/ui-react": "0.11.0",
89
+ "@collective-intelligence/ui-react": "0.13.0",
74
90
  "@effect/eslint-plugin": "0.3.2",
75
91
  "@oxlint/plugins": "1.94.0",
76
92
  "@punks/lints": "0.2.0",
93
+ "@tanstack/db": "1.0.0-rc.1.5",
94
+ "@tanstack/offline-transactions": "1.2.1",
95
+ "@tanstack/query-core": "5.101.4",
96
+ "@tanstack/query-db-collection": "1.5.2",
97
+ "@tanstack/react-db": "1.0.0-rc.1.5",
77
98
  "@tanstack/react-query": "5.101.4",
78
99
  "@tanstack/react-router": "1.170.44",
79
100
  "@tanstack/react-start": "1.169.2",
@@ -92,12 +113,11 @@
92
113
  "oxlint": "1.94.0",
93
114
  "react": "^19.2.8",
94
115
  "react-dom": "^19.2.8",
95
- "tsprover": "0.0.2",
96
116
  "typescript": "5.9.3",
97
117
  "ultracite": "7.10.7",
98
118
  "vite": "8.2.1",
99
119
  "vitest": "4.1.10",
100
120
  "xstate": "5.33.3"
101
121
  },
102
- "gitHead": "8d52a59042026b9044f6e4c49084efbd34868c0c"
122
+ "gitHead": "d3e93c4287307c474b0bf32c386a1471fe67ce2c"
103
123
  }
@@ -0,0 +1,62 @@
1
+ ---
2
+ name: client-sdk-react-move-to-record-collections
3
+ description: Move the optimistic writes of a React app on `@collective-intelligence/external-apps-client-sdk-react` from `QueryCache.optimisticUpdate` and `optimistic-write` modules to Record Collection transactions. Use when an SDK upgrade fails the type-check on `optimisticUpdate`, `pending`, `QueryCacheWriteValues` or `QueryCacheOptimisticOptions`, or code imports an `entities/optimistic-write` module.
4
+ ---
5
+
6
+ # Move optimistic writes to Record Collections
7
+
8
+ Reference: [record-collections.md](../../docs/record-collections.md),
9
+ [effect.md](../../docs/effect.md), [errors.md](../../docs/errors.md).
10
+
11
+ The SDK release with `./records` removed `QueryCache.optimisticUpdate`,
12
+ `QueryCache.pending`, the types `QueryCacheWriteValues` and
13
+ `QueryCacheOptimisticOptions`, and its `entities/optimistic-write.ts` engine,
14
+ with no wrapper. An app stays on the old SDK until this skill has moved every
15
+ call site.
16
+
17
+ ## Steps
18
+
19
+ 1. **Inventory.** Upgrade the SDK and run the type-check. Also search for
20
+ `optimisticUpdate(`, `.pending(`, `QueryCacheWriteValues`,
21
+ `QueryCacheOptimisticOptions`, `optimistic-write`, `optimistic: false`, and
22
+ `useMutation` with `onMutate`. Done when you have a list of call sites,
23
+ each with the record type it writes.
24
+ 2. **Sort each call site** into one of three cases. Done when each call site
25
+ has its case.
26
+ - **A**: it writes a CI entity record (create, update or delete of an
27
+ entity contract).
28
+ - **B**: it writes CI records that no entity contract covers.
29
+ - **C**: it edits a cache value that is not a CI record, such as a
30
+ preference or a computed list.
31
+ 3. **Move case A to the entity hooks.** Call `useEntityCreate`,
32
+ `useEntityUpdate` or `useEntityDelete` of `./resources` in the view or
33
+ form that owns the action. When a Business Logic Machine starts the
34
+ write, the machine emits the action, the view calls the hook's `submit`,
35
+ and sends the result back to the machine as an event, or the machine
36
+ runs `fromTransaction` with `entityWriteTarget(contract)`. Delete the
37
+ `edit`, `confirm` and `write` functions of the old call; the write shows
38
+ in every Record Collection of the contract and puts CI's row in place.
39
+ Done when no
40
+ case A call site calls `optimisticUpdate` or an `optimistic-write` module.
41
+ 4. **File an SDK gap for case B.** Follow "File an SDK gap" in
42
+ `record-collections.md`. Until the SDK has the write, run it in a
43
+ `fromEffect` actor without an optimistic value and `invalidate` its keys
44
+ when the actor ends. Done when each case B call site has a filed gap and
45
+ no optimistic code.
46
+ 5. **Move case C to the `QueryCache` steps.** In the `fromEffect` actor:
47
+ `cancel` the keys, `update` them, run the write, and `invalidate` them
48
+ when the actor ends. Done when no case C call site calls
49
+ `optimisticUpdate`.
50
+ 6. **Replace the pending reads.** `pending(queryKey)` becomes the hook's
51
+ `pending` or `status`, or `$hasPendingWrites` in a live query over the
52
+ Record Collection. Remove `optimistic: false` from hook targets: every
53
+ write shows at once. Remove read code that waited for a pending write.
54
+ Done when the search of step 1 finds nothing.
55
+ 7. **Fix the tests.** Remove `optimisticUpdate` and `pending` from
56
+ `makeTestQueryCache` overrides and from `calls` assertions. Test case A
57
+ through the hooks, and assert on the rows of the Record Collection and on
58
+ `status`. Done when the tests pass.
59
+ 8. **Verify.** Run the type-check, the tests and oxlint with the
60
+ `recommended` config of `@collective-intelligence/lint`. Done when all
61
+ pass with no `ci-solution/effect-writes` finding, and a refused write in
62
+ the browser rolls back only its own change.
@@ -0,0 +1,49 @@
1
+ ---
2
+ name: client-sdk-react-record-collections
3
+ description: Build views and Business Logic Machines of a React app on the Record Collections of `@collective-intelligence/external-apps-client-sdk-react/records`. Use when a view or machine reads CI records that it writes or follows, a list must follow realtime changes, code imports `@tanstack/db` or `@tanstack/react-db`, or lint reports `ci-solution/effect-writes`.
4
+ ---
5
+
6
+ # Build on Record Collections
7
+
8
+ Reference: [record-collections.md](../../docs/record-collections.md),
9
+ [tanstack-skills.md](../../docs/tanstack-skills.md).
10
+
11
+ ## Steps
12
+
13
+ 1. **Load the TanStack DB skills.** Check that the app's `package.json`
14
+ permits `@tanstack/db` and `@tanstack/react-db` in `intent.skills`, then
15
+ load each skill that `tanstack-skills.md` names for the task. Done when
16
+ `intent list` shows them and you have read `@tanstack/db#db-core`.
17
+ 2. **Choose the kind** for each data set with the table "Which kind to use"
18
+ in `record-collections.md`: a Realtime Record Collection for records that
19
+ others change while the view is open, a Query Record Collection for the
20
+ rest, plain TanStack Query for one-off reads. Done when each data set has
21
+ one kind and a reason.
22
+ 3. **Mount the providers.** `CollectiveIntelligenceProvider` with an
23
+ `entitySource`, and, for a Realtime Record Collection, `RealtimeProvider`
24
+ of `./realtime` inside it with an `onResync`. Done when
25
+ `useRecordRuntime()` gives a runtime for a signed-in user.
26
+ 4. **Open each collection once** through `RecordCollections` on that runtime:
27
+ `realtime(entityTopic(contract, topic), schema)` or
28
+ `query({ queryKey, schema, load })`. Put the topics, query keys and
29
+ schemas in one module, so the views, the machines and a server seed open
30
+ the same collection. Done when no module calls `createCollection` or
31
+ `queryCollectionOptions` itself.
32
+ 5. **Render through live queries.** Views read rows with `useLiveQuery` of
33
+ `@tanstack/react-db`; a Business Logic Machine reads them with
34
+ `fromLiveQuery` and keeps ids or counts in its context. Done when no
35
+ React state or machine context holds a copy of a row.
36
+ 6. **Write through the entity hooks.** Use `useEntityCreate`,
37
+ `useEntityUpdate` and `useEntityDelete` of `./resources`, and show
38
+ failures with `onWriteFailed`; each write shows at once in the app's
39
+ Record Collections of the contract. A Business Logic Machine writes with
40
+ `fromTransaction` and `entityWriteTarget(contract)`. When a write cannot
41
+ go through either, follow "File an SDK gap" in `record-collections.md`.
42
+ Done when the app has no
43
+ `useMutation`, no hand-written optimistic value and no write queue for CI
44
+ records.
45
+ 7. **Verify.** Run the type-check, the tests and oxlint with the
46
+ `recommended` config of `@collective-intelligence/lint`. In the browser,
47
+ sign in as two users in turn and check that the second sees none of the
48
+ first user's rows. Done when all pass with no `ci-solution/effect-writes`
49
+ finding.
@@ -0,0 +1,52 @@
1
+ ---
2
+ name: client-sdk-react-tanstack-db-ssr
3
+ description: Server-render the Record Collections of a Next.js app on `@collective-intelligence/external-apps-client-sdk-react/records`, so the first HTML holds the rows and the browser does not fetch them again. Use when a page shows Record Collection rows on first load, a route turns off server rendering for TanStack DB, or the `@tanstack/db#meta-framework` skill would apply.
4
+ ---
5
+
6
+ # Server-render Record Collections
7
+
8
+ Reference: [record-collections.md](../../docs/record-collections.md),
9
+ [tanstack-skills.md](../../docs/tanstack-skills.md).
10
+
11
+ The shipped `@tanstack/db#meta-framework` skill is out of date: it says to turn
12
+ server rendering off. Follow these steps in its place.
13
+
14
+ ## Steps
15
+
16
+ 1. **Share one definition.** Put each seeded collection's options in a module
17
+ that both the server page and the client component import, with no
18
+ `"use client"`: for a Query Record Collection its `queryKey`, `schema` and
19
+ `load`; for a Realtime Record Collection its topic object
20
+ (`{ schema, filter? }`) and `schema`. The browser wraps the topic with
21
+ `entityTopic(contract, topic)`. Done when the server and the browser build
22
+ each collection from the same object.
23
+ 2. **Seed in the server component.** Import `seedRecords` from `./records`
24
+ (the `react-server` build) and run it once per request with the
25
+ session's identity:
26
+ `seedRecords({ identity, query: [leadsQuery], realtime: [{ topic, schema, load }] })`.
27
+ `identity` is `{ applicationId, organizationId, userId }` of the request's
28
+ session, the values the browser's entity source reports; without it the
29
+ browser never hydrates the seed.
30
+ A realtime `load` reads the topic with the signed-in user's credential and
31
+ returns `{ records, position }`, with the `position` of the Entity API
32
+ list read. Provide the services of the loads, then run the Effect. Done
33
+ when the page awaits one `RecordSeed`.
34
+ 3. **Keep the seed per request.** `seedRecords` uses `getRequestClients()`,
35
+ the QueryClient and DbClient of the current request. Seeds hold user data:
36
+ keep them out of `"use cache"`, `unstable_cache` and other shared caches.
37
+ Done when no cached function returns a seed.
38
+ 4. **Hydrate in the browser.** Render `<RecordSeedBoundary seed={seed}>`
39
+ inside the SDK provider, around the client components that read the
40
+ collections. They open the collections through `useRecordRuntime()` and
41
+ `RecordCollections`, and read rows with `useLiveQuery`. While no user is
42
+ signed in, the seed waits and hydrates at the sign-in; give the entity
43
+ source the session at its first render to show the rows in the first
44
+ HTML. Done when the client component renders rows with no loading state
45
+ on first load.
46
+ 5. **Keep the server values on the server.** Import `getRequestClients` and
47
+ `seedRecords` only in server components; a client component that imports
48
+ them fails when it bundles. Done when the build passes.
49
+ 6. **Verify.** Fetch the page HTML and find the seeded rows in it. In the
50
+ browser, check that the seeded collections make no list read after load,
51
+ and that the realtime stream opens with a `from` for each seeded topic.
52
+ Done when all three hold.